From d41ed82a4ea0cc8e1674b6d5d2c49fd6462610bb Mon Sep 17 00:00:00 2001 From: ng0 Date: Sun, 8 Sep 2019 12:33:09 +0000 Subject: [PATCH] uncrustify as demanded. --- src/abe/abe.c | 327 +- src/abe/test_cpabe.c | 65 +- src/arm/arm.h | 18 +- src/arm/arm_api.c | 710 +- src/arm/arm_monitor_api.c | 150 +- src/arm/gnunet-arm.c | 840 +- src/arm/gnunet-service-arm.c | 2268 ++--- src/arm/mockup-service.c | 75 +- src/arm/test_arm_api.c | 241 +- src/arm/test_exponential_backoff.c | 386 +- src/arm/test_gnunet_service_arm.c | 252 +- src/ats-tests/ats-testing-experiment.c | 1023 +-- src/ats-tests/ats-testing-log.c | 979 ++- src/ats-tests/ats-testing-preferences.c | 196 +- src/ats-tests/ats-testing-traffic.c | 359 +- src/ats-tests/ats-testing.c | 1081 +-- src/ats-tests/ats-testing.h | 128 +- src/ats-tests/gnunet-ats-sim.c | 427 +- src/ats-tests/gnunet-solver-eval.c | 1244 +-- src/ats-tests/perf_ats.c | 571 +- src/ats-tests/perf_ats.h | 40 +- src/ats-tests/perf_ats_logging.c | 678 +- src/ats-tool/gnunet-ats.c | 943 +- src/ats/ats.h | 58 +- src/ats/ats2.h | 30 +- src/ats/ats_api2_application.c | 203 +- src/ats/ats_api2_transport.c | 435 +- src/ats/ats_api_connectivity.c | 221 +- src/ats/ats_api_performance.c | 776 +- src/ats/ats_api_scanner.c | 32 +- src/ats/ats_api_scheduling.c | 613 +- src/ats/gnunet-ats-solver-eval.c | 3826 ++++---- src/ats/gnunet-ats-solver-eval.h | 78 +- src/ats/gnunet-service-ats-new.c | 658 +- src/ats/gnunet-service-ats.c | 466 +- src/ats/gnunet-service-ats.h | 6 +- src/ats/gnunet-service-ats_addresses.c | 627 +- src/ats/gnunet-service-ats_addresses.h | 73 +- src/ats/gnunet-service-ats_connectivity.c | 121 +- src/ats/gnunet-service-ats_connectivity.h | 22 +- src/ats/gnunet-service-ats_normalization.c | 217 +- src/ats/gnunet-service-ats_normalization.h | 10 +- src/ats/gnunet-service-ats_performance.c | 230 +- src/ats/gnunet-service-ats_performance.h | 30 +- src/ats/gnunet-service-ats_plugins.c | 574 +- src/ats/gnunet-service-ats_plugins.h | 58 +- src/ats/gnunet-service-ats_preferences.c | 496 +- src/ats/gnunet-service-ats_preferences.h | 38 +- src/ats/gnunet-service-ats_reservations.c | 158 +- src/ats/gnunet-service-ats_reservations.h | 18 +- src/ats/gnunet-service-ats_scheduling.c | 146 +- src/ats/gnunet-service-ats_scheduling.h | 22 +- src/ats/perf_ats_solver.c | 1373 +-- src/ats/plugin_ats2_common.c | 114 +- src/ats/plugin_ats2_simple.c | 718 +- src/ats/plugin_ats_mlp.c | 2260 ++--- src/ats/plugin_ats_proportional.c | 1070 ++- src/ats/plugin_ats_ril.c | 2134 ++--- src/ats/test_ats2_lib.c | 140 +- src/ats/test_ats2_lib.h | 12 +- src/ats/test_ats_api.c | 22 +- src/ats/test_ats_lib.c | 1123 +-- src/ats/test_ats_lib.h | 80 +- src/ats/test_ats_reservation_api.c | 18 +- src/auction/auction.h | 7 +- src/auction/gnunet-auction-create.c | 292 +- src/auction/gnunet-auction-info.c | 33 +- src/auction/gnunet-auction-join.c | 33 +- src/auction/gnunet-service-auction.c | 72 +- src/auction/test_auction_api.c | 10 +- src/block/bg_bf.c | 120 +- src/block/block.c | 254 +- src/block/plugin_block_template.c | 104 +- src/block/plugin_block_test.c | 122 +- src/cadet/cadet.h | 67 +- src/cadet/cadet_api.c | 762 +- src/cadet/cadet_api_get_channel.c | 139 +- src/cadet/cadet_api_get_path.c | 155 +- src/cadet/cadet_api_helper.c | 16 +- src/cadet/cadet_api_list_peers.c | 126 +- src/cadet/cadet_api_list_tunnels.c | 134 +- src/cadet/cadet_protocol.h | 58 +- src/cadet/cadet_test_lib.c | 252 +- src/cadet/cadet_test_lib.h | 34 +- src/cadet/desirability_table.c | 40 +- src/cadet/gnunet-cadet-profiler.c | 837 +- src/cadet/gnunet-cadet.c | 712 +- src/cadet/gnunet-service-cadet.c | 1174 ++- src/cadet/gnunet-service-cadet.h | 42 +- src/cadet/gnunet-service-cadet_channel.c | 1870 ++-- src/cadet/gnunet-service-cadet_channel.h | 90 +- src/cadet/gnunet-service-cadet_connection.c | 760 +- src/cadet/gnunet-service-cadet_connection.h | 83 +- src/cadet/gnunet-service-cadet_core.c | 1164 ++- src/cadet/gnunet-service-cadet_core.h | 8 +- src/cadet/gnunet-service-cadet_dht.c | 308 +- src/cadet/gnunet-service-cadet_dht.h | 14 +- src/cadet/gnunet-service-cadet_hello.c | 96 +- src/cadet/gnunet-service-cadet_hello.h | 10 +- src/cadet/gnunet-service-cadet_paths.c | 748 +- src/cadet/gnunet-service-cadet_paths.h | 50 +- src/cadet/gnunet-service-cadet_peer.c | 1244 ++- src/cadet/gnunet-service-cadet_peer.h | 116 +- src/cadet/gnunet-service-cadet_tunnels.c | 3467 ++++---- src/cadet/gnunet-service-cadet_tunnels.h | 88 +- src/cadet/test_cadet.c | 1198 ++- src/cadet/test_cadet_flow.c | 747 +- src/cadet/test_cadet_local_mq.c | 265 +- src/consensus/consensus.h | 11 +- src/consensus/consensus_api.c | 183 +- src/consensus/consensus_protocol.h | 16 +- src/consensus/gnunet-consensus-profiler.c | 536 +- src/consensus/gnunet-service-consensus.c | 2974 +++---- src/consensus/plugin_block_consensus.c | 60 +- src/consensus/test_consensus_api.c | 77 +- src/conversation/conversation.h | 77 +- src/conversation/conversation_api.c | 696 +- src/conversation/conversation_api_call.c | 713 +- src/conversation/gnunet-conversation-test.c | 191 +- src/conversation/gnunet-conversation.c | 1325 +-- .../gnunet-helper-audio-playback-gst.c | 385 +- .../gnunet-helper-audio-playback.c | 1023 +-- .../gnunet-helper-audio-record-gst.c | 375 +- src/conversation/gnunet-helper-audio-record.c | 688 +- .../gnunet-service-conversation.c | 1348 +-- src/conversation/gnunet_gst.c | 1217 +-- src/conversation/gnunet_gst.h | 58 +- src/conversation/gnunet_gst_def.h | 80 +- src/conversation/gnunet_gst_test.c | 127 +- src/conversation/microphone.c | 115 +- .../plugin_gnsrecord_conversation.c | 188 +- src/conversation/speaker.c | 120 +- src/conversation/test_conversation_api.c | 526 +- .../test_conversation_api_reject.c | 362 +- .../test_conversation_api_twocalls.c | 654 +- src/core/core.h | 31 +- src/core/core_api.c | 562 +- src/core/core_api_monitor_peers.c | 84 +- src/core/gnunet-core.c | 196 +- src/core/gnunet-service-core.c | 897 +- src/core/gnunet-service-core.h | 24 +- src/core/gnunet-service-core_kx.c | 2027 ++--- src/core/gnunet-service-core_kx.h | 20 +- src/core/gnunet-service-core_sessions.c | 819 +- src/core/gnunet-service-core_sessions.h | 42 +- src/core/gnunet-service-core_typemap.c | 231 +- src/core/gnunet-service-core_typemap.h | 42 +- src/core/test_core_api.c | 344 +- src/core/test_core_api_reliability.c | 584 +- src/core/test_core_api_send_to_self.c | 150 +- src/core/test_core_api_start_only.c | 228 +- src/core/test_core_quota_compliance.c | 901 +- src/credential/credential.h | 38 +- src/credential/credential_api.c | 354 +- src/credential/credential_misc.c | 159 +- src/credential/credential_misc.h | 6 +- src/credential/credential_serialization.c | 444 +- src/credential/credential_serialization.h | 166 +- src/credential/gnunet-credential.c | 655 +- src/credential/gnunet-service-credential.c | 1064 +-- src/credential/plugin_gnsrecord_credential.c | 346 +- src/credential/plugin_rest_credential.c | 1368 +-- src/curl/curl.c | 529 +- src/curl/curl_reschedule.c | 119 +- src/datacache/datacache.c | 338 +- src/datacache/perf_datacache.c | 138 +- src/datacache/plugin_datacache_heap.c | 360 +- src/datacache/plugin_datacache_postgres.c | 699 +- src/datacache/plugin_datacache_sqlite.c | 887 +- src/datacache/plugin_datacache_template.c | 81 +- src/datacache/test_datacache.c | 222 +- src/datacache/test_datacache_quota.c | 156 +- src/datastore/datastore.h | 31 +- src/datastore/datastore_api.c | 1315 ++- src/datastore/gnunet-datastore.c | 442 +- src/datastore/gnunet-service-datastore.c | 1518 ++-- src/datastore/perf_datastore_api.c | 497 +- src/datastore/perf_plugin_datastore.c | 563 +- src/datastore/plugin_datastore_heap.c | 622 +- src/datastore/plugin_datastore_mysql.c | 1114 ++- src/datastore/plugin_datastore_postgres.c | 942 +- src/datastore/plugin_datastore_sqlite.c | 1445 +-- src/datastore/plugin_datastore_template.c | 119 +- src/datastore/test_datastore_api.c | 696 +- src/datastore/test_datastore_api_management.c | 377 +- src/datastore/test_plugin_datastore.c | 451 +- src/dht/dht.h | 39 +- src/dht/dht_api.c | 964 +- src/dht/dht_test_lib.c | 135 +- src/dht/dht_test_lib.h | 24 +- src/dht/gnunet-dht-get.c | 226 +- src/dht/gnunet-dht-monitor.c | 276 +- src/dht/gnunet-dht-put.c | 173 +- src/dht/gnunet-service-dht.c | 120 +- src/dht/gnunet-service-dht.h | 74 +- src/dht/gnunet-service-dht_clients.c | 1395 ++- src/dht/gnunet-service-dht_datacache.c | 387 +- src/dht/gnunet-service-dht_datacache.h | 44 +- src/dht/gnunet-service-dht_hello.c | 86 +- src/dht/gnunet-service-dht_hello.h | 10 +- src/dht/gnunet-service-dht_neighbours.c | 2652 +++--- src/dht/gnunet-service-dht_neighbours.h | 72 +- src/dht/gnunet-service-dht_nse.c | 58 +- src/dht/gnunet-service-dht_nse.h | 10 +- src/dht/gnunet-service-dht_routing.c | 396 +- src/dht/gnunet-service-dht_routing.h | 40 +- src/dht/gnunet_dht_profiler.c | 760 +- src/dht/plugin_block_dht.c | 196 +- src/dht/test_dht_api.c | 184 +- src/dht/test_dht_monitor.c | 324 +- src/dht/test_dht_topo.c | 495 +- src/dns/dns.h | 17 +- src/dns/dns_api.c | 225 +- src/dns/gnunet-dns-monitor.c | 380 +- src/dns/gnunet-dns-redirector.c | 234 +- src/dns/gnunet-helper-dns.c | 1336 +-- src/dns/gnunet-service-dns.c | 1251 +-- src/dns/gnunet-zonewalk.c | 593 +- src/dns/plugin_block_dns.c | 191 +- src/exit/exit.h | 31 +- src/exit/gnunet-daemon-exit.c | 4704 +++++----- src/exit/gnunet-helper-exit-windows.c | 1160 +-- src/exit/gnunet-helper-exit.c | 964 +- src/fragmentation/defragmentation.c | 400 +- src/fragmentation/fragmentation.c | 402 +- src/fragmentation/fragmentation.h | 14 +- src/fragmentation/test_fragmentation.c | 246 +- .../test_fragmentation_parallel.c | 190 +- src/fs/fs.h | 43 +- src/fs/fs_api.c | 3372 +++---- src/fs/fs_api.h | 231 +- src/fs/fs_directory.c | 612 +- src/fs/fs_dirmetascan.c | 473 +- src/fs/fs_download.c | 2574 +++--- src/fs/fs_file_information.c | 324 +- src/fs/fs_getopt.c | 239 +- src/fs/fs_list_indexed.c | 134 +- src/fs/fs_misc.c | 198 +- src/fs/fs_namespace.c | 663 +- src/fs/fs_publish.c | 1659 ++-- src/fs/fs_publish_ksk.c | 151 +- src/fs/fs_publish_ublock.c | 247 +- src/fs/fs_publish_ublock.h | 38 +- src/fs/fs_search.c | 1622 ++-- src/fs/fs_sharetree.c | 259 +- src/fs/fs_test_lib.c | 424 +- src/fs/fs_test_lib.h | 38 +- src/fs/fs_tree.c | 264 +- src/fs/fs_tree.h | 38 +- src/fs/fs_unindex.c | 862 +- src/fs/fs_uri.c | 1774 ++-- src/fs/gnunet-auto-share.c | 602 +- src/fs/gnunet-daemon-fsprofiler.c | 565 +- src/fs/gnunet-directory.c | 171 +- src/fs/gnunet-download.c | 446 +- src/fs/gnunet-fs-profiler.c | 150 +- src/fs/gnunet-fs.c | 108 +- src/fs/gnunet-helper-fs-publish.c | 404 +- src/fs/gnunet-publish.c | 1076 +-- src/fs/gnunet-search.c | 376 +- src/fs/gnunet-service-fs.c | 1124 ++- src/fs/gnunet-service-fs.h | 24 +- src/fs/gnunet-service-fs_cadet.h | 36 +- src/fs/gnunet-service-fs_cadet_client.c | 427 +- src/fs/gnunet-service-fs_cadet_server.c | 457 +- src/fs/gnunet-service-fs_cp.c | 1451 ++- src/fs/gnunet-service-fs_cp.h | 85 +- src/fs/gnunet-service-fs_indexing.c | 480 +- src/fs/gnunet-service-fs_indexing.h | 40 +- src/fs/gnunet-service-fs_pe.c | 629 +- src/fs/gnunet-service-fs_pe.h | 22 +- src/fs/gnunet-service-fs_pr.c | 1845 ++-- src/fs/gnunet-service-fs_pr.h | 93 +- src/fs/gnunet-service-fs_push.c | 468 +- src/fs/gnunet-service-fs_push.h | 12 +- src/fs/gnunet-service-fs_put.c | 176 +- src/fs/gnunet-service-fs_put.h | 8 +- src/fs/gnunet-unindex.c | 161 +- src/fs/perf_gnunet_service_fs_p2p.c | 312 +- src/fs/perf_gnunet_service_fs_p2p_respect.c | 378 +- src/fs/plugin_block_fs.c | 287 +- src/fs/test_fs.c | 249 +- src/fs/test_fs_directory.c | 171 +- src/fs/test_fs_download.c | 419 +- src/fs/test_fs_download_persistence.c | 375 +- src/fs/test_fs_file_information.c | 124 +- src/fs/test_fs_getopt.c | 14 +- src/fs/test_fs_list_indexed.c | 276 +- src/fs/test_fs_namespace.c | 327 +- src/fs/test_fs_namespace_list_updateable.c | 115 +- src/fs/test_fs_publish.c | 262 +- src/fs/test_fs_publish_persistence.c | 324 +- src/fs/test_fs_search.c | 257 +- src/fs/test_fs_search_persistence.c | 317 +- src/fs/test_fs_search_probes.c | 264 +- src/fs/test_fs_search_with_and.c | 285 +- src/fs/test_fs_start_stop.c | 28 +- src/fs/test_fs_test_lib.c | 149 +- src/fs/test_fs_unindex.c | 248 +- src/fs/test_fs_unindex_persistence.c | 321 +- src/fs/test_fs_uri.c | 420 +- src/fs/test_gnunet_service_fs_migration.c | 213 +- src/fs/test_gnunet_service_fs_p2p.c | 142 +- src/fs/test_plugin_block_fs.c | 74 +- src/gns/gns.h | 11 +- src/gns/gns_api.c | 257 +- src/gns/gns_api.h | 9 +- src/gns/gns_tld_api.c | 236 +- src/gns/gnunet-bcd.c | 629 +- src/gns/gnunet-dns2gns.c | 791 +- src/gns/gnunet-gns-benchmark.c | 540 +- src/gns/gnunet-gns-helper-service-w32.c | 944 +- src/gns/gnunet-gns-import.c | 387 +- src/gns/gnunet-gns-proxy.c | 4108 ++++----- src/gns/gnunet-gns.c | 250 +- src/gns/gnunet-service-gns.c | 491 +- src/gns/gnunet-service-gns.h | 10 +- src/gns/gnunet-service-gns_interceptor.c | 429 +- src/gns/gnunet-service-gns_interceptor.h | 8 +- src/gns/gnunet-service-gns_resolver.c | 3290 +++---- src/gns/gnunet-service-gns_resolver.h | 28 +- src/gns/gnunet_w32nsp_lib.h | 2 +- src/gns/nss/nss_gns.c | 192 +- src/gns/nss/nss_gns_query.c | 140 +- src/gns/nss/nss_gns_query.h | 11 +- src/gns/plugin_block_gns.c | 148 +- src/gns/plugin_gnsrecord_gns.c | 443 +- src/gns/plugin_rest_gns.c | 284 +- src/gns/test_gns_proxy.c | 548 +- src/gns/w32nsp-install.c | 152 +- src/gns/w32nsp-resolve.c | 636 +- src/gns/w32nsp-uninstall.c | 28 +- src/gns/w32nsp.c | 728 +- src/gns/w32resolver.h | 7 +- src/gnsrecord/gnsrecord.c | 139 +- src/gnsrecord/gnsrecord_crypto.c | 484 +- src/gnsrecord/gnsrecord_misc.c | 210 +- src/gnsrecord/gnsrecord_serialization.c | 253 +- src/gnsrecord/perf_gnsrecord_crypto.c | 106 +- src/gnsrecord/plugin_gnsrecord_dns.c | 1167 +-- .../test_gnsrecord_block_expiration.c | 31 +- src/gnsrecord/test_gnsrecord_crypto.c | 123 +- src/gnsrecord/test_gnsrecord_serialization.c | 159 +- src/hello/address.c | 74 +- src/hello/gnunet-hello.c | 186 +- src/hello/hello-ng.c | 145 +- src/hello/hello.c | 882 +- src/hello/test_friend_hello.c | 200 +- src/hello/test_hello.c | 288 +- src/hostlist/gnunet-daemon-hostlist.c | 282 +- src/hostlist/gnunet-daemon-hostlist.h | 4 +- src/hostlist/gnunet-daemon-hostlist_client.c | 1771 ++-- src/hostlist/gnunet-daemon-hostlist_client.h | 18 +- src/hostlist/gnunet-daemon-hostlist_server.c | 887 +- src/hostlist/gnunet-daemon-hostlist_server.h | 16 +- src/hostlist/test_gnunet_daemon_hostlist.c | 236 +- .../test_gnunet_daemon_hostlist_learning.c | 659 +- .../test_gnunet_daemon_hostlist_reconnect.c | 260 +- src/identity/gnunet-identity.c | 360 +- src/identity/gnunet-service-identity.c | 1059 ++- src/identity/identity.h | 29 +- src/identity/identity_api.c | 605 +- src/identity/identity_api_lookup.c | 122 +- src/identity/identity_api_suffix_lookup.c | 122 +- src/identity/plugin_rest_identity.c | 1090 ++- src/identity/test_identity.c | 225 +- src/identity/test_identity_defaults.c | 178 +- src/include/block_dns.h | 8 +- src/include/block_fs.h | 13 +- src/include/block_regex.h | 10 +- src/include/compat.h | 14 +- src/include/gauger.h | 152 +- src/include/gettext.h | 14 +- src/include/gnunet_abe_lib.h | 50 +- src/include/gnunet_applications.h | 4 +- src/include/gnunet_arm_service.h | 54 +- src/include/gnunet_ats_application_service.h | 38 +- src/include/gnunet_ats_plugin.h | 40 +- src/include/gnunet_ats_plugin_new.h | 76 +- src/include/gnunet_ats_service.h | 143 +- src/include/gnunet_ats_transport_service.h | 57 +- src/include/gnunet_bandwidth_lib.h | 50 +- src/include/gnunet_bio_lib.h | 66 +- src/include/gnunet_block_group_lib.h | 26 +- src/include/gnunet_block_lib.h | 84 +- src/include/gnunet_block_plugin.h | 33 +- src/include/gnunet_cadet_service.h | 112 +- src/include/gnunet_client_lib.h | 14 +- src/include/gnunet_common.h | 454 +- src/include/gnunet_configuration_lib.h | 208 +- src/include/gnunet_consensus_service.h | 34 +- src/include/gnunet_constants.h | 24 +- src/include/gnunet_container_lib.h | 655 +- src/include/gnunet_conversation_service.h | 111 +- src/include/gnunet_core_service.h | 40 +- src/include/gnunet_credential_service.h | 84 +- src/include/gnunet_crypto_lib.h | 530 +- src/include/gnunet_curl_lib.h | 97 +- src/include/gnunet_datacache_lib.h | 54 +- src/include/gnunet_datacache_plugin.h | 22 +- src/include/gnunet_datastore_plugin.h | 34 +- src/include/gnunet_datastore_service.h | 118 +- src/include/gnunet_db_lib.h | 36 +- src/include/gnunet_dht_service.h | 75 +- src/include/gnunet_disk_lib.h | 199 +- src/include/gnunet_dns_service.h | 27 +- src/include/gnunet_dnsparser_lib.h | 193 +- src/include/gnunet_dnsstub_lib.h | 30 +- src/include/gnunet_fragmentation_lib.h | 52 +- src/include/gnunet_friends_lib.h | 18 +- src/include/gnunet_fs_service.h | 1053 +-- src/include/gnunet_getopt_lib.h | 148 +- src/include/gnunet_gns_service.h | 40 +- src/include/gnunet_gnsrecord_lib.h | 98 +- src/include/gnunet_gnsrecord_plugin.h | 27 +- src/include/gnunet_hello_lib.h | 112 +- src/include/gnunet_helper_lib.h | 38 +- src/include/gnunet_identity_service.h | 84 +- src/include/gnunet_json_lib.h | 136 +- src/include/gnunet_load_lib.h | 18 +- src/include/gnunet_microphone_lib.h | 51 +- src/include/gnunet_mq_lib.h | 258 +- src/include/gnunet_mst_lib.h | 32 +- src/include/gnunet_my_lib.h | 236 +- src/include/gnunet_mysql_lib.h | 22 +- src/include/gnunet_namecache_plugin.h | 18 +- src/include/gnunet_namecache_service.h | 26 +- src/include/gnunet_namestore_plugin.h | 52 +- src/include/gnunet_namestore_service.h | 108 +- src/include/gnunet_nat_auto_service.h | 32 +- src/include/gnunet_nat_service.h | 91 +- src/include/gnunet_nc_lib.h | 20 +- src/include/gnunet_network_lib.h | 188 +- src/include/gnunet_nse_service.h | 8 +- src/include/gnunet_nt_lib.h | 40 +- src/include/gnunet_op_lib.h | 44 +- src/include/gnunet_os_lib.h | 135 +- src/include/gnunet_peer_lib.h | 20 +- src/include/gnunet_peerinfo_service.h | 38 +- src/include/gnunet_peerstore_plugin.h | 9 +- src/include/gnunet_peerstore_service.h | 63 +- src/include/gnunet_plugin_lib.h | 22 +- src/include/gnunet_pq_lib.h | 158 +- src/include/gnunet_program_lib.h | 34 +- src/include/gnunet_protocols.h | 10 +- src/include/gnunet_reclaim_attribute_lib.h | 55 +- src/include/gnunet_reclaim_attribute_plugin.h | 6 +- src/include/gnunet_reclaim_service.h | 107 +- src/include/gnunet_regex_service.h | 24 +- src/include/gnunet_resolver_service.h | 42 +- src/include/gnunet_rest_lib.h | 28 +- src/include/gnunet_rest_plugin.h | 9 +- src/include/gnunet_revocation_service.h | 34 +- src/include/gnunet_rps_service.h | 76 +- src/include/gnunet_scalarproduct_service.h | 37 +- src/include/gnunet_scheduler_lib.h | 214 +- src/include/gnunet_secretsharing_service.h | 119 +- src/include/gnunet_service_lib.h | 87 +- src/include/gnunet_set_service.h | 106 +- src/include/gnunet_signal_lib.h | 12 +- src/include/gnunet_signatures.h | 2 +- src/include/gnunet_socks.h | 12 +- src/include/gnunet_speaker_lib.h | 47 +- src/include/gnunet_sq_lib.h | 139 +- src/include/gnunet_statistics_service.h | 60 +- src/include/gnunet_strings_lib.h | 174 +- src/include/gnunet_testbed_logger_service.h | 20 +- src/include/gnunet_testbed_service.h | 430 +- src/include/gnunet_testing_lib.h | 101 +- src/include/gnunet_time_lib.h | 140 +- .../gnunet_transport_application_service.h | 34 +- .../gnunet_transport_communication_service.h | 27 +- src/include/gnunet_transport_core_service.h | 24 +- src/include/gnunet_transport_hello_service.h | 23 +- .../gnunet_transport_manipulation_service.h | 18 +- .../gnunet_transport_monitor_service.h | 19 +- src/include/gnunet_transport_plugin.h | 26 +- src/include/gnunet_transport_service.h | 72 +- src/include/gnunet_tun_lib.h | 152 +- src/include/gnunet_util_lib.h | 2 +- src/include/gnunet_util_taler_wallet_lib.h | 2 +- src/include/gnunet_vpn_service.h | 42 +- src/include/platform.h | 12 +- src/include/tap-windows.h | 24 +- src/include/winproc.h | 331 +- src/json/json.c | 126 +- src/json/json_generator.c | 168 +- src/json/json_gnsrecord.c | 233 +- src/json/json_helper.c | 725 +- src/json/json_mhd.c | 356 +- src/json/test_json.c | 192 +- src/json/test_json_mhd.c | 240 +- src/my/my.c | 274 +- src/my/my_query_helper.c | 153 +- src/my/my_result_helper.c | 600 +- src/my/test_my.c | 366 +- src/mysql/mysql.c | 358 +- src/namecache/gnunet-namecache.c | 198 +- src/namecache/gnunet-service-namecache.c | 338 +- src/namecache/namecache.h | 20 +- src/namecache/namecache_api.c | 363 +- src/namecache/plugin_namecache_flat.c | 446 +- src/namecache/plugin_namecache_postgres.c | 329 +- src/namecache/plugin_namecache_sqlite.c | 656 +- .../test_namecache_api_cache_block.c | 231 +- src/namecache/test_plugin_namecache.c | 78 +- src/namestore/gnunet-namestore-fcfsd.c | 1097 +-- src/namestore/gnunet-namestore.c | 1779 ++-- src/namestore/gnunet-service-namestore.c | 1934 ++-- src/namestore/gnunet-zoneimport.c | 1801 ++-- src/namestore/namestore.h | 48 +- src/namestore/namestore_api.c | 841 +- src/namestore/namestore_api_monitor.c | 189 +- .../perf_namestore_api_zone_iteration.c | 386 +- src/namestore/plugin_namestore_flat.c | 828 +- src/namestore/plugin_namestore_postgres.c | 674 +- src/namestore/plugin_namestore_sqlite.c | 849 +- src/namestore/plugin_rest_namestore.c | 632 +- src/namestore/test_common.c | 68 +- .../test_namestore_api_lookup_nick.c | 367 +- .../test_namestore_api_lookup_private.c | 230 +- .../test_namestore_api_lookup_public.c | 214 +- .../test_namestore_api_lookup_shadow.c | 276 +- .../test_namestore_api_lookup_shadow_filter.c | 375 +- src/namestore/test_namestore_api_monitoring.c | 390 +- .../test_namestore_api_monitoring_existing.c | 444 +- src/namestore/test_namestore_api_remove.c | 204 +- ...namestore_api_remove_not_existing_record.c | 144 +- src/namestore/test_namestore_api_store.c | 132 +- .../test_namestore_api_store_update.c | 326 +- .../test_namestore_api_zone_iteration.c | 584 +- .../test_namestore_api_zone_iteration_nick.c | 463 +- ...mestore_api_zone_iteration_specific_zone.c | 546 +- .../test_namestore_api_zone_iteration_stop.c | 527 +- .../test_namestore_api_zone_to_name.c | 274 +- src/namestore/test_plugin_namestore.c | 176 +- src/nat-auto/gnunet-nat-auto.c | 288 +- src/nat-auto/gnunet-nat-auto_legacy.c | 476 +- src/nat-auto/gnunet-nat-server.c | 300 +- src/nat-auto/gnunet-service-nat-auto.c | 327 +- src/nat-auto/gnunet-service-nat-auto_legacy.c | 1008 ++- src/nat-auto/nat-auto.h | 17 +- src/nat-auto/nat_auto_api.c | 264 +- src/nat-auto/nat_auto_api_test.c | 490 +- src/nat/gnunet-helper-nat-client-windows.c | 325 +- src/nat/gnunet-helper-nat-client.c | 341 +- src/nat/gnunet-helper-nat-server-windows.c | 433 +- src/nat/gnunet-helper-nat-server.c | 583 +- src/nat/gnunet-nat.c | 432 +- src/nat/gnunet-service-nat.c | 2190 ++--- src/nat/gnunet-service-nat.h | 26 +- src/nat/gnunet-service-nat_externalip.c | 181 +- src/nat/gnunet-service-nat_externalip.h | 18 +- src/nat/gnunet-service-nat_helper.c | 368 +- src/nat/gnunet-service-nat_helper.h | 28 +- src/nat/gnunet-service-nat_mini.c | 594 +- src/nat/gnunet-service-nat_mini.h | 20 +- src/nat/gnunet-service-nat_stun.c | 178 +- src/nat/gnunet-service-nat_stun.h | 10 +- src/nat/nat.h | 34 +- src/nat/nat_api.c | 548 +- src/nat/nat_api_stun.c | 155 +- src/nat/nat_stun.h | 67 +- src/nat/test_nat.c | 124 +- src/nat/test_nat_mini.c | 84 +- src/nat/test_nat_test.c | 107 +- src/nat/test_stun.c | 278 +- src/nse/gnunet-nse-profiler.c | 713 +- src/nse/gnunet-nse.c | 77 +- src/nse/gnunet-service-nse.c | 1300 ++- src/nse/nse.h | 7 +- src/nse/nse_api.c | 95 +- src/nse/perf_kdf.c | 50 +- src/nse/test_nse_api.c | 54 +- src/nse/test_nse_multipeer.c | 115 +- src/nt/nt.c | 366 +- src/peerinfo-tool/gnunet-peerinfo.c | 677 +- src/peerinfo-tool/gnunet-peerinfo_plugins.c | 117 +- src/peerinfo-tool/gnunet-peerinfo_plugins.h | 10 +- src/peerinfo-tool/plugin_rest_peerinfo.c | 520 +- src/peerinfo/gnunet-service-peerinfo.c | 1301 ++- src/peerinfo/peerinfo.h | 22 +- src/peerinfo/peerinfo_api.c | 427 +- src/peerinfo/peerinfo_api_notify.c | 170 +- src/peerinfo/perf_peerinfo_api.c | 150 +- src/peerinfo/test_peerinfo_api.c | 127 +- src/peerinfo/test_peerinfo_api_friend_only.c | 155 +- .../test_peerinfo_api_notify_friend_only.c | 226 +- src/peerinfo/test_peerinfo_shipped_hellos.c | 134 +- src/peerstore/gnunet-peerstore.c | 39 +- src/peerstore/gnunet-service-peerstore.c | 446 +- src/peerstore/peerstore.h | 12 +- src/peerstore/peerstore_api.c | 541 +- src/peerstore/peerstore_common.c | 154 +- src/peerstore/peerstore_common.h | 30 +- src/peerstore/perf_peerstore_store.c | 68 +- src/peerstore/plugin_peerstore_flat.c | 520 +- src/peerstore/plugin_peerstore_sqlite.c | 699 +- src/peerstore/test_peerstore_api_iterate.c | 194 +- src/peerstore/test_peerstore_api_store.c | 208 +- src/peerstore/test_peerstore_api_sync.c | 96 +- src/peerstore/test_peerstore_api_watch.c | 84 +- src/peerstore/test_plugin_peerstore.c | 205 +- src/pq/pq.c | 156 +- src/pq/pq_connect.c | 108 +- src/pq/pq_eval.c | 294 +- src/pq/pq_exec.c | 88 +- src/pq/pq_prepare.c | 88 +- src/pq/pq_query_helper.c | 282 +- src/pq/pq_result_helper.c | 838 +- src/pq/test_pq.c | 382 +- src/pt/gnunet-daemon-pt.c | 1115 +-- src/pt/test_gns_vpn.c | 902 +- src/pt/test_gnunet_vpn.c | 521 +- .../plugin_reclaim_attribute_gnuid.c | 59 +- src/reclaim-attribute/reclaim_attribute.c | 340 +- src/reclaim-attribute/reclaim_attribute.h | 5 +- src/reclaim/gnunet-reclaim.c | 715 +- src/reclaim/gnunet-service-reclaim.c | 1273 +-- src/reclaim/gnunet-service-reclaim_tickets.c | 1154 +-- src/reclaim/gnunet-service-reclaim_tickets.h | 45 +- src/reclaim/json_reclaim.c | 244 +- src/reclaim/json_reclaim.h | 6 +- src/reclaim/oidc_helper.h | 46 +- src/reclaim/plugin_gnsrecord_reclaim.c | 101 +- src/reclaim/plugin_rest_openid_connect.c | 2084 ++--- src/reclaim/plugin_rest_reclaim.c | 941 +- src/reclaim/reclaim.h | 50 +- src/reclaim/reclaim_api.c | 576 +- src/regex/gnunet-daemon-regexprofiler.c | 330 +- src/regex/gnunet-regex-profiler.c | 1308 ++- src/regex/gnunet-regex-simulation-profiler.c | 634 +- src/regex/gnunet-service-regex.c | 303 +- src/regex/perf-regex.c | 102 +- src/regex/plugin_block_regex.c | 347 +- src/regex/regex_api_announce.c | 105 +- src/regex/regex_api_search.c | 167 +- src/regex/regex_block_lib.c | 380 +- src/regex/regex_block_lib.h | 51 +- src/regex/regex_internal.c | 3107 +++---- src/regex/regex_internal.h | 54 +- src/regex/regex_internal_dht.c | 662 +- src/regex/regex_internal_lib.h | 60 +- src/regex/regex_ipc.h | 16 +- src/regex/regex_test_graph.c | 289 +- src/regex/regex_test_lib.c | 484 +- src/regex/regex_test_lib.h | 21 +- src/regex/regex_test_random.c | 115 +- src/regex/test_regex_api.c | 72 +- src/regex/test_regex_eval_api.c | 436 +- src/regex/test_regex_graph_api.c | 161 +- src/regex/test_regex_integration.c | 186 +- src/regex/test_regex_iterate_api.c | 314 +- src/regex/test_regex_proofs.c | 92 +- src/rest/gnunet-rest-server.c | 1067 +-- src/rest/plugin_rest_config.c | 339 +- src/rest/plugin_rest_copying.c | 112 +- src/rest/rest.c | 79 +- src/revocation/gnunet-revocation.c | 500 +- src/revocation/gnunet-service-revocation.c | 985 +-- src/revocation/plugin_block_revocation.c | 179 +- src/revocation/revocation.h | 20 +- src/revocation/revocation_api.c | 298 +- src/revocation/test_revocation.c | 424 +- src/rps/gnunet-rps-profiler.c | 2967 +++---- src/rps/gnunet-rps.c | 229 +- src/rps/gnunet-service-rps.c | 4232 ++++----- src/rps/gnunet-service-rps_custommap.c | 253 +- src/rps/gnunet-service-rps_custommap.h | 32 +- src/rps/gnunet-service-rps_sampler.c | 64 +- src/rps/gnunet-service-rps_sampler.h | 44 +- src/rps/gnunet-service-rps_sampler_elem.c | 98 +- src/rps/gnunet-service-rps_sampler_elem.h | 30 +- src/rps/gnunet-service-rps_view.c | 201 +- src/rps/gnunet-service-rps_view.h | 34 +- src/rps/rps-sampler_client.c | 175 +- src/rps/rps-sampler_client.h | 44 +- src/rps/rps-sampler_common.c | 493 +- src/rps/rps-sampler_common.h | 76 +- src/rps/rps-test_util.c | 585 +- src/rps/rps-test_util.h | 84 +- src/rps/rps.h | 46 +- src/rps/rps_api.c | 913 +- src/rps/test_rps.c | 2658 +++--- src/rps/test_rps_api.c | 59 +- src/rps/test_service_rps_custommap.c | 153 +- src/rps/test_service_rps_sampler_elem.c | 230 +- src/rps/test_service_rps_view.c | 184 +- src/scalarproduct/gnunet-scalarproduct.c | 441 +- .../gnunet-service-scalarproduct-ecc.h | 13 +- .../gnunet-service-scalarproduct-ecc_alice.c | 973 ++- .../gnunet-service-scalarproduct-ecc_bob.c | 930 +- .../gnunet-service-scalarproduct.h | 15 +- .../gnunet-service-scalarproduct_alice.c | 1141 +-- .../gnunet-service-scalarproduct_bob.c | 1140 +-- src/scalarproduct/scalarproduct.h | 22 +- src/scalarproduct/scalarproduct_api.c | 406 +- src/scalarproduct/test_ecc_scalarproduct.c | 187 +- .../gnunet-secretsharing-profiler.c | 502 +- .../gnunet-service-secretsharing.c | 2096 +++-- src/secretsharing/secretsharing.h | 26 +- src/secretsharing/secretsharing_api.c | 337 +- src/secretsharing/secretsharing_common.c | 92 +- src/secretsharing/secretsharing_protocol.h | 16 +- src/secretsharing/test_secretsharing_api.c | 68 +- src/set/gnunet-service-set.c | 1843 ++-- src/set/gnunet-service-set.h | 54 +- src/set/gnunet-service-set_intersection.c | 1241 +-- src/set/gnunet-service-set_intersection.h | 20 +- src/set/gnunet-service-set_protocol.h | 26 +- src/set/gnunet-service-set_union.c | 2299 ++--- src/set/gnunet-service-set_union.h | 76 +- ...nunet-service-set_union_strata_estimator.c | 210 +- ...nunet-service-set_union_strata_estimator.h | 41 +- src/set/gnunet-set-ibf-profiler.c | 362 +- src/set/gnunet-set-profiler.c | 505 +- src/set/ibf.c | 282 +- src/set/ibf.h | 60 +- src/set/ibf_sim.c | 119 +- src/set/plugin_block_set_test.c | 48 +- src/set/set.h | 45 +- src/set/set_api.c | 923 +- src/set/test_set_api.c | 411 +- src/set/test_set_intersection_result_full.c | 388 +- src/set/test_set_union_copy.c | 285 +- src/set/test_set_union_result_symmetric.c | 394 +- src/sq/sq.c | 134 +- src/sq/sq_exec.c | 94 +- src/sq/sq_prepare.c | 72 +- src/sq/sq_query_helper.c | 305 +- src/sq/sq_result_helper.c | 550 +- src/sq/test_sq.c | 364 +- src/statistics/gnunet-service-statistics.c | 853 +- src/statistics/gnunet-statistics.c | 815 +- src/statistics/statistics.h | 18 +- src/statistics/statistics_api.c | 1146 ++- src/statistics/test_statistics_api.c | 297 +- src/statistics/test_statistics_api_loop.c | 101 +- src/statistics/test_statistics_api_watch.c | 139 +- .../test_statistics_api_watch_zero_value.c | 187 +- src/template/gnunet-service-template.c | 40 +- src/template/gnunet-template.c | 38 +- src/template/test_template_api.c | 8 +- .../gnunet-service-testbed-logger.c | 196 +- src/testbed-logger/test_testbed_logger_api.c | 228 +- src/testbed-logger/testbed_logger_api.c | 183 +- src/testbed/generate-underlay-topology.c | 375 +- src/testbed/gnunet-daemon-latency-logger.c | 264 +- src/testbed/gnunet-daemon-testbed-blacklist.c | 170 +- src/testbed/gnunet-daemon-testbed-underlay.c | 366 +- src/testbed/gnunet-helper-testbed.c | 556 +- src/testbed/gnunet-service-test-barriers.c | 80 +- src/testbed/gnunet-service-testbed.c | 919 +- src/testbed/gnunet-service-testbed.h | 223 +- src/testbed/gnunet-service-testbed_barriers.c | 740 +- src/testbed/gnunet-service-testbed_barriers.h | 60 +- src/testbed/gnunet-service-testbed_cache.c | 147 +- .../gnunet-service-testbed_connectionpool.c | 676 +- .../gnunet-service-testbed_connectionpool.h | 37 +- .../gnunet-service-testbed_cpustatus.c | 363 +- src/testbed/gnunet-service-testbed_links.c | 1147 ++- src/testbed/gnunet-service-testbed_links.h | 61 +- src/testbed/gnunet-service-testbed_meminfo.c | 185 +- src/testbed/gnunet-service-testbed_meminfo.h | 4 +- src/testbed/gnunet-service-testbed_oc.c | 1658 ++-- src/testbed/gnunet-service-testbed_peers.c | 1630 ++-- src/testbed/gnunet-testbed-profiler.c | 222 +- src/testbed/gnunet_mpi_test.c | 122 +- src/testbed/gnunet_testbed_mpi_spawn.c | 293 +- src/testbed/test_gnunet_helper_testbed.c | 112 +- src/testbed/test_testbed_api.c | 359 +- .../test_testbed_api_2peers_1controller.c | 396 +- .../test_testbed_api_3peers_3controllers.c | 968 +- src/testbed/test_testbed_api_barriers.c | 163 +- src/testbed/test_testbed_api_controllerlink.c | 770 +- src/testbed/test_testbed_api_hosts.c | 155 +- src/testbed/test_testbed_api_operations.c | 469 +- .../test_testbed_api_peer_reconfiguration.c | 108 +- .../test_testbed_api_peers_manage_services.c | 133 +- src/testbed/test_testbed_api_sd.c | 76 +- src/testbed/test_testbed_api_statistics.c | 108 +- src/testbed/test_testbed_api_test.c | 173 +- src/testbed/test_testbed_api_test_timeout.c | 82 +- src/testbed/test_testbed_api_testbed_run.c | 181 +- src/testbed/test_testbed_api_topology.c | 150 +- .../test_testbed_api_topology_clique.c | 142 +- src/testbed/test_testbed_underlay.c | 106 +- src/testbed/testbed.h | 134 +- src/testbed/testbed_api.c | 2063 ++--- src/testbed/testbed_api.h | 134 +- src/testbed/testbed_api_barriers.c | 236 +- src/testbed/testbed_api_hosts.c | 1081 ++- src/testbed/testbed_api_hosts.h | 55 +- src/testbed/testbed_api_operations.c | 794 +- src/testbed/testbed_api_operations.h | 41 +- src/testbed/testbed_api_peers.c | 727 +- src/testbed/testbed_api_peers.h | 65 +- src/testbed/testbed_api_sd.c | 82 +- src/testbed/testbed_api_sd.h | 12 +- src/testbed/testbed_api_services.c | 129 +- src/testbed/testbed_api_statistics.c | 207 +- src/testbed/testbed_api_test.c | 51 +- src/testbed/testbed_api_testbed.c | 1179 +-- src/testbed/testbed_api_topology.c | 1368 +-- src/testbed/testbed_api_topology.h | 20 +- src/testbed/testbed_api_underlay.c | 105 +- src/testbed/testbed_helper.h | 8 +- src/testing/gnunet-testing.c | 470 +- src/testing/list-keys.c | 112 +- src/testing/test_testing_peerstartup.c | 73 +- src/testing/test_testing_peerstartup2.c | 140 +- src/testing/test_testing_portreservation.c | 68 +- src/testing/test_testing_servicestartup.c | 30 +- src/testing/test_testing_sharedservices.c | 104 +- src/testing/testing.c | 1474 ++-- src/topology/friends.c | 263 +- src/topology/gnunet-daemon-topology.c | 854 +- src/topology/test_gnunet_daemon_topology.c | 224 +- src/transport/communicator.h | 8 +- src/transport/gnunet-communicator-tcp.c | 1840 ++-- src/transport/gnunet-communicator-udp.c | 2292 +++-- src/transport/gnunet-communicator-unix.c | 958 +- .../gnunet-helper-transport-bluetooth.c | 3205 ++++--- .../gnunet-helper-transport-wlan-dummy.c | 595 +- src/transport/gnunet-helper-transport-wlan.c | 1607 ++-- src/transport/gnunet-service-tng.c | 7783 ++++++++--------- src/transport/gnunet-service-transport.c | 2390 +++-- src/transport/gnunet-service-transport.h | 64 +- src/transport/gnunet-service-transport_ats.c | 772 +- src/transport/gnunet-service-transport_ats.h | 56 +- .../gnunet-service-transport_hello.c | 209 +- .../gnunet-service-transport_hello.h | 24 +- .../gnunet-service-transport_manipulation.c | 508 +- .../gnunet-service-transport_manipulation.h | 38 +- .../gnunet-service-transport_neighbours.c | 4336 ++++----- .../gnunet-service-transport_neighbours.h | 86 +- .../gnunet-service-transport_plugins.c | 486 +- .../gnunet-service-transport_plugins.h | 24 +- .../gnunet-service-transport_validation.c | 1702 ++-- .../gnunet-service-transport_validation.h | 32 +- src/transport/gnunet-transport-profiler.c | 560 +- .../gnunet-transport-wlan-receiver.c | 144 +- src/transport/gnunet-transport-wlan-sender.c | 280 +- src/transport/gnunet-transport.c | 1266 +-- src/transport/ieee80211_radiotap.h | 60 +- src/transport/plugin_transport_http.h | 88 +- src/transport/plugin_transport_http_client.c | 2426 ++--- src/transport/plugin_transport_http_common.c | 961 +- src/transport/plugin_transport_http_common.h | 91 +- src/transport/plugin_transport_http_server.c | 3571 ++++---- src/transport/plugin_transport_smtp.c | 642 +- src/transport/plugin_transport_tcp.c | 3635 ++++---- src/transport/plugin_transport_template.c | 188 +- src/transport/plugin_transport_udp.c | 3988 ++++----- src/transport/plugin_transport_udp.h | 46 +- .../plugin_transport_udp_broadcasting.c | 643 +- src/transport/plugin_transport_unix.c | 1603 ++-- src/transport/plugin_transport_wlan.c | 2091 +++-- src/transport/plugin_transport_wlan.h | 53 +- src/transport/tcp_connection_legacy.c | 1315 ++- src/transport/tcp_server_legacy.c | 1283 ++- src/transport/tcp_server_mst_legacy.c | 329 +- src/transport/tcp_service_legacy.c | 1761 ++-- src/transport/test_communicator_unix.c | 222 +- src/transport/test_http_common.c | 227 +- src/transport/test_plugin_transport.c | 836 +- src/transport/test_quota_compliance.c | 326 +- src/transport/test_transport_address_switch.c | 406 +- src/transport/test_transport_api.c | 78 +- .../test_transport_api_blacklisting.c | 178 +- src/transport/test_transport_api_disconnect.c | 96 +- .../test_transport_api_limited_sockets.c | 78 +- .../test_transport_api_manipulation_cfg.c | 175 +- ...test_transport_api_manipulation_recv_tcp.c | 180 +- ...test_transport_api_manipulation_send_tcp.c | 178 +- .../test_transport_api_monitor_peers.c | 206 +- .../test_transport_api_reliability.c | 218 +- .../test_transport_api_restart_reconnect.c | 182 +- src/transport/test_transport_api_timeout.c | 128 +- src/transport/test_transport_blacklisting.c | 705 +- .../test_transport_testing_restart.c | 133 +- .../test_transport_testing_startstop.c | 117 +- src/transport/transport-testing-filenames.c | 124 +- src/transport/transport-testing-loggers.c | 44 +- src/transport/transport-testing-main.c | 460 +- src/transport/transport-testing-send.c | 206 +- src/transport/transport-testing.c | 1019 +-- src/transport/transport-testing.h | 81 +- src/transport/transport-testing2.c | 456 +- src/transport/transport-testing2.h | 62 +- src/transport/transport.h | 155 +- src/transport/transport_api2_application.c | 189 +- src/transport/transport_api2_communication.c | 465 +- src/transport/transport_api2_core.c | 490 +- src/transport/transport_api2_monitor.c | 127 +- .../transport_api_address_to_string.c | 222 +- src/transport/transport_api_blacklist.c | 91 +- src/transport/transport_api_core.c | 603 +- src/transport/transport_api_hello_get.c | 142 +- src/transport/transport_api_manipulation.c | 130 +- src/transport/transport_api_monitor_peers.c | 377 +- src/transport/transport_api_monitor_plugins.c | 294 +- src/transport/transport_api_offer_hello.c | 81 +- src/util/bandwidth.c | 368 +- src/util/benchmark.c | 260 +- src/util/benchmark.h | 92 +- src/util/bio.c | 384 +- src/util/client.c | 891 +- src/util/common_allocation.c | 294 +- src/util/common_endian.c | 26 +- src/util/common_logging.c | 1083 +-- src/util/configuration.c | 1351 +-- src/util/configuration_loader.c | 66 +- src/util/container_bloomfilter.c | 552 +- src/util/container_heap.c | 329 +- src/util/container_meta_data.c | 975 +-- src/util/container_multihashmap.c | 885 +- src/util/container_multihashmap32.c | 333 +- src/util/container_multipeermap.c | 831 +- src/util/container_multishortmap.c | 785 +- src/util/container_multiuuidmap.c | 795 +- src/util/crypto_abe.c | 335 +- src/util/crypto_crc.c | 63 +- src/util/crypto_ecc.c | 1416 +-- src/util/crypto_ecc_dlog.c | 377 +- src/util/crypto_ecc_setup.c | 608 +- src/util/crypto_hash.c | 305 +- src/util/crypto_hash_file.c | 167 +- src/util/crypto_hkdf.c | 184 +- src/util/crypto_kdf.c | 136 +- src/util/crypto_mpi.c | 112 +- src/util/crypto_paillier.c | 423 +- src/util/crypto_random.c | 283 +- src/util/crypto_rsa.c | 1106 +-- src/util/crypto_symmetric.c | 186 +- src/util/disk.c | 2507 +++--- src/util/disk.h | 8 +- src/util/dnsparser.c | 1292 +-- src/util/dnsstub.c | 546 +- src/util/getopt.c | 1041 ++- src/util/getopt_helpers.c | 766 +- src/util/gnunet-config-diff.c | 20 +- src/util/gnunet-config.c | 342 +- src/util/gnunet-ecc.c | 560 +- src/util/gnunet-helper-w32-console.c | 249 +- src/util/gnunet-helper-w32-console.h | 10 +- src/util/gnunet-qr.c | 258 +- src/util/gnunet-resolver.c | 146 +- src/util/gnunet-scrypt.c | 356 +- src/util/gnunet-service-resolver.c | 1241 +-- src/util/gnunet-timeout-w32.c | 182 +- src/util/gnunet-timeout.c | 104 +- src/util/gnunet-uri.c | 149 +- src/util/helper.c | 562 +- src/util/load.c | 97 +- src/util/mq.c | 680 +- src/util/mst.c | 463 +- src/util/nc.c | 97 +- src/util/network.c | 1975 ++--- src/util/op.c | 157 +- src/util/os_installation.c | 1005 +-- src/util/os_network.c | 560 +- src/util/os_priority.c | 2218 ++--- src/util/peer.c | 141 +- src/util/perf_crypto_asymmetric.c | 95 +- src/util/perf_crypto_ecc_dlog.c | 168 +- src/util/perf_crypto_hash.c | 84 +- src/util/perf_crypto_paillier.c | 90 +- src/util/perf_crypto_rsa.c | 266 +- src/util/perf_crypto_symmetric.c | 52 +- src/util/perf_malloc.c | 30 +- src/util/plugin.c | 246 +- src/util/proc_compat.c | 14 +- src/util/program.c | 354 +- src/util/regex.c | 970 +- src/util/resolver.h | 11 +- src/util/resolver_api.c | 1294 +-- src/util/scheduler.c | 1923 ++-- src/util/service.c | 2247 ++--- src/util/signal.c | 64 +- src/util/socks.c | 549 +- src/util/speedup.c | 94 +- src/util/speedup.h | 10 +- src/util/strings.c | 2002 ++--- src/util/test_bio.c | 436 +- src/util/test_client.c | 154 +- src/util/test_common_allocation.c | 118 +- src/util/test_common_endian.c | 18 +- src/util/test_common_logging.c | 96 +- src/util/test_common_logging_dummy.c | 92 +- .../test_common_logging_runtime_loglevels.c | 493 +- src/util/test_configuration.c | 663 +- src/util/test_container_bloomfilter.c | 304 +- src/util/test_container_dll.c | 79 +- src/util/test_container_heap.c | 382 +- src/util/test_container_meta_data.c | 426 +- src/util/test_container_multihashmap.c | 126 +- src/util/test_container_multihashmap32.c | 92 +- src/util/test_container_multipeermap.c | 126 +- src/util/test_crypto_crc.c | 12 +- src/util/test_crypto_ecc_dlog.c | 174 +- src/util/test_crypto_ecdh_eddsa.c | 82 +- src/util/test_crypto_ecdhe.c | 58 +- src/util/test_crypto_ecdsa.c | 266 +- src/util/test_crypto_eddsa.c | 206 +- src/util/test_crypto_hash.c | 104 +- src/util/test_crypto_hash_context.c | 44 +- src/util/test_crypto_hkdf.c | 276 +- src/util/test_crypto_kdf.c | 47 +- src/util/test_crypto_paillier.c | 305 +- src/util/test_crypto_random.c | 37 +- src/util/test_crypto_rsa.c | 154 +- src/util/test_crypto_symmetric.c | 152 +- src/util/test_disk.c | 336 +- src/util/test_getopt.c | 167 +- src/util/test_hexcoder.c | 32 +- src/util/test_mq.c | 281 +- src/util/test_os_network.c | 68 +- src/util/test_os_start_process.c | 279 +- src/util/test_peer.c | 98 +- src/util/test_plugin.c | 40 +- src/util/test_plugin_plug.c | 14 +- src/util/test_program.c | 128 +- src/util/test_regex.c | 184 +- src/util/test_resolver_api.c | 421 +- src/util/test_scheduler.c | 182 +- src/util/test_scheduler_delay.c | 56 +- src/util/test_service.c | 196 +- src/util/test_socks.c | 255 +- src/util/test_speedup.c | 86 +- src/util/test_strings.c | 170 +- src/util/test_strings_to_data.c | 43 +- src/util/test_time.c | 260 +- src/util/test_tun.c | 66 +- src/util/time.c | 413 +- src/util/tun.c | 264 +- src/util/w32cat.c | 166 +- src/util/win.c | 1319 +-- src/util/winproc.c | 369 +- src/vpn/gnunet-helper-vpn-windows.c | 1106 +-- src/vpn/gnunet-helper-vpn.c | 897 +- src/vpn/gnunet-service-vpn.c | 3816 ++++---- src/vpn/gnunet-vpn.c | 375 +- src/vpn/vpn.h | 17 +- src/vpn/vpn_api.c | 339 +- .../gnunet-service-zonemaster-monitor.c | 423 +- src/zonemaster/gnunet-service-zonemaster.c | 801 +- 1047 files changed, 224194 insertions(+), 224539 deletions(-) diff --git a/src/abe/abe.c b/src/abe/abe.c index 091ba0ced..31c6e04e0 100644 --- a/src/abe/abe.c +++ b/src/abe/abe.c @@ -11,13 +11,13 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file abe/abe.c @@ -33,55 +33,53 @@ #include "gnunet_crypto_lib.h" #include "gnunet_abe_lib.h" -struct GNUNET_ABE_AbeMasterKey -{ +struct GNUNET_ABE_AbeMasterKey { gabe_pub_t* pub; gabe_msk_t* msk; }; -struct GNUNET_ABE_AbeKey -{ +struct GNUNET_ABE_AbeKey { gabe_pub_t* pub; gabe_prv_t* prv; }; static int -init_aes( element_t k, int enc, - gcry_cipher_hd_t* handle, - struct GNUNET_CRYPTO_SymmetricSessionKey *key, - unsigned char* iv) +init_aes(element_t k, int enc, + gcry_cipher_hd_t* handle, + struct GNUNET_CRYPTO_SymmetricSessionKey *key, + unsigned char* iv) { int rc; int key_len; unsigned char* key_buf; key_len = element_length_in_bytes(k) < 33 ? 3 : element_length_in_bytes(k); - key_buf = (unsigned char*) malloc(key_len); + key_buf = (unsigned char*)malloc(key_len); element_to_bytes(key_buf, k); - GNUNET_memcpy (key->aes_key, key_buf, GNUNET_CRYPTO_AES_KEY_LENGTH); - GNUNET_assert (0 == - gcry_cipher_open (handle, GCRY_CIPHER_AES256, - GCRY_CIPHER_MODE_CFB, 0)); - rc = gcry_cipher_setkey (*handle, - key->aes_key, - sizeof (key->aes_key)); - GNUNET_assert ((0 == rc) || ((char) rc == GPG_ERR_WEAK_KEY)); - memset (iv, 0, 16); //TODO make reasonable - rc = gcry_cipher_setiv (*handle, - iv, - 16); - GNUNET_assert ((0 == rc) || ((char) rc == GPG_ERR_WEAK_KEY)); + GNUNET_memcpy(key->aes_key, key_buf, GNUNET_CRYPTO_AES_KEY_LENGTH); + GNUNET_assert(0 == + gcry_cipher_open(handle, GCRY_CIPHER_AES256, + GCRY_CIPHER_MODE_CFB, 0)); + rc = gcry_cipher_setkey(*handle, + key->aes_key, + sizeof(key->aes_key)); + GNUNET_assert((0 == rc) || ((char)rc == GPG_ERR_WEAK_KEY)); + memset(iv, 0, 16); //TODO make reasonable + rc = gcry_cipher_setiv(*handle, + iv, + 16); + GNUNET_assert((0 == rc) || ((char)rc == GPG_ERR_WEAK_KEY)); free(key_buf); return rc; } static int -aes_128_cbc_encrypt( char* pt, - int size, - element_t k, - char **ct ) +aes_128_cbc_encrypt(char* pt, + int size, + element_t k, + char **ct) { gcry_cipher_hd_t handle; struct GNUNET_CRYPTO_SymmetricSessionKey skey; @@ -90,34 +88,35 @@ aes_128_cbc_encrypt( char* pt, int padding; int buf_size; uint8_t len[4]; + init_aes(k, 1, &handle, &skey, iv); /* TODO make less crufty */ /* stuff in real length (big endian) before padding */ - len[0] = (size & 0xff000000)>>24; - len[1] = (size & 0xff0000)>>16; - len[2] = (size & 0xff00)>>8; - len[3] = (size & 0xff)>>0; - padding = 16 - ((4+size) % 16); + len[0] = (size & 0xff000000) >> 24; + len[1] = (size & 0xff0000) >> 16; + len[2] = (size & 0xff00) >> 8; + len[3] = (size & 0xff) >> 0; + padding = 16 - ((4 + size) % 16); buf_size = 4 + size + padding; - buf = GNUNET_malloc (buf_size); - GNUNET_memcpy (buf, len, 4); - GNUNET_memcpy (buf+4, pt, size); - *ct = GNUNET_malloc (buf_size); + buf = GNUNET_malloc(buf_size); + GNUNET_memcpy(buf, len, 4); + GNUNET_memcpy(buf + 4, pt, size); + *ct = GNUNET_malloc(buf_size); - GNUNET_assert (0 == gcry_cipher_encrypt (handle, *ct, buf_size, buf, buf_size)); - gcry_cipher_close (handle); + GNUNET_assert(0 == gcry_cipher_encrypt(handle, *ct, buf_size, buf, buf_size)); + gcry_cipher_close(handle); //AES_cbc_encrypt(pt->data, ct->data, pt->len, &key, iv, AES_ENCRYPT); - GNUNET_free (buf); + GNUNET_free(buf); return buf_size; } static int -aes_128_cbc_decrypt( char* ct, - int size, - element_t k, - char **pt ) +aes_128_cbc_decrypt(char* ct, + int size, + element_t k, + char **pt) { struct GNUNET_CRYPTO_SymmetricSessionKey skey; gcry_cipher_hd_t handle; @@ -127,22 +126,22 @@ aes_128_cbc_decrypt( char* ct, init_aes(k, 1, &handle, &skey, iv); - tmp = GNUNET_malloc (size); + tmp = GNUNET_malloc(size); //AES_cbc_encrypt(ct->data, pt->data, ct->len, &key, iv, AES_DECRYPT); - GNUNET_assert (0 == gcry_cipher_decrypt (handle, tmp, size, ct, size)); - gcry_cipher_close (handle); + GNUNET_assert(0 == gcry_cipher_decrypt(handle, tmp, size, ct, size)); + gcry_cipher_close(handle); /* TODO make less crufty */ /* get real length */ len = 0; len = len - | ((tmp[0])<<24) | ((tmp[1])<<16) - | ((tmp[2])<<8) | ((tmp[3])<<0); + | ((tmp[0]) << 24) | ((tmp[1]) << 16) + | ((tmp[2]) << 8) | ((tmp[3]) << 0); /* truncate any garbage from the padding */ - *pt = GNUNET_malloc (len); - GNUNET_memcpy (*pt, tmp+4, len); - GNUNET_free (tmp); + *pt = GNUNET_malloc(len); + GNUNET_memcpy(*pt, tmp + 4, len); + GNUNET_free(tmp); return len; } @@ -153,13 +152,14 @@ aes_128_cbc_decrypt( char* ct, * @return fresh private key; free using #GNUNET_ABE_cpabe_delete_master_key */ struct GNUNET_ABE_AbeMasterKey* -GNUNET_ABE_cpabe_create_master_key (void) +GNUNET_ABE_cpabe_create_master_key(void) { struct GNUNET_ABE_AbeMasterKey* key; - key = GNUNET_new (struct GNUNET_ABE_AbeMasterKey); + + key = GNUNET_new(struct GNUNET_ABE_AbeMasterKey); gabe_setup(&key->pub, &key->msk); - GNUNET_assert (NULL != key->pub); - GNUNET_assert (NULL != key->msk); + GNUNET_assert(NULL != key->pub); + GNUNET_assert(NULL != key->msk); return key; } @@ -171,13 +171,13 @@ GNUNET_ABE_cpabe_create_master_key (void) * @return fresh private key; free using #GNUNET_free */ void -GNUNET_ABE_cpabe_delete_master_key (struct GNUNET_ABE_AbeMasterKey *key) +GNUNET_ABE_cpabe_delete_master_key(struct GNUNET_ABE_AbeMasterKey *key) { - gabe_msk_free (key->msk); - gabe_pub_free (key->pub); + gabe_msk_free(key->msk); + gabe_pub_free(key->pub); //GNUNET_free (key->msk); //gabe_msk_free (key->msk); //For some reason free of pub implicit? - GNUNET_free (key); + GNUNET_free(key); } /** @@ -189,19 +189,19 @@ GNUNET_ABE_cpabe_delete_master_key (struct GNUNET_ABE_AbeMasterKey *key) * @return fresh private key; free using #GNUNET_ABE_cpabe_delete_key */ struct GNUNET_ABE_AbeKey* -GNUNET_ABE_cpabe_create_key (struct GNUNET_ABE_AbeMasterKey *key, - char **attrs) +GNUNET_ABE_cpabe_create_key(struct GNUNET_ABE_AbeMasterKey *key, + char **attrs) { struct GNUNET_ABE_AbeKey *prv_key; int size; char *tmp; - prv_key = GNUNET_new (struct GNUNET_ABE_AbeKey); + prv_key = GNUNET_new(struct GNUNET_ABE_AbeKey); prv_key->prv = gabe_keygen(key->pub, key->msk, attrs); size = gabe_pub_serialize(key->pub, &tmp); prv_key->pub = gabe_pub_unserialize(tmp, size); - GNUNET_free (tmp); - GNUNET_assert (NULL != prv_key->prv); + GNUNET_free(tmp); + GNUNET_assert(NULL != prv_key->prv); return prv_key; } @@ -214,50 +214,50 @@ GNUNET_ABE_cpabe_create_key (struct GNUNET_ABE_AbeMasterKey *key, * @return fresh private key; free using #GNUNET_free */ void -GNUNET_ABE_cpabe_delete_key (struct GNUNET_ABE_AbeKey *key, - int delete_pub) +GNUNET_ABE_cpabe_delete_key(struct GNUNET_ABE_AbeKey *key, + int delete_pub) { //Memory management in gabe is buggy - gabe_prv_free (key->prv); + gabe_prv_free(key->prv); if (GNUNET_YES == delete_pub) - gabe_pub_free (key->pub); - GNUNET_free (key); + gabe_pub_free(key->pub); + GNUNET_free(key); } static ssize_t -write_cpabe (void **result, - uint32_t file_len, - char* cph_buf, - int cph_buf_len, - char* aes_buf, - int aes_buf_len) +write_cpabe(void **result, + uint32_t file_len, + char* cph_buf, + int cph_buf_len, + char* aes_buf, + int aes_buf_len) { char *ptr; uint32_t *len; - *result = GNUNET_malloc (12 + cph_buf_len + aes_buf_len); + *result = GNUNET_malloc(12 + cph_buf_len + aes_buf_len); ptr = *result; - len = (uint32_t*) ptr; - *len = htonl (file_len); + len = (uint32_t*)ptr; + *len = htonl(file_len); ptr += 4; - len = (uint32_t*) ptr; - *len = htonl (aes_buf_len); + len = (uint32_t*)ptr; + *len = htonl(aes_buf_len); ptr += 4; - GNUNET_memcpy (ptr, aes_buf, aes_buf_len); + GNUNET_memcpy(ptr, aes_buf, aes_buf_len); ptr += aes_buf_len; - len = (uint32_t*) ptr; - *len = htonl (cph_buf_len); + len = (uint32_t*)ptr; + *len = htonl(cph_buf_len); ptr += 4; - GNUNET_memcpy (ptr, cph_buf, cph_buf_len); + GNUNET_memcpy(ptr, cph_buf, cph_buf_len); return 12 + cph_buf_len + aes_buf_len; } static ssize_t -read_cpabe (const void *data, - char** cph_buf, - int *cph_buf_len, - char** aes_buf, - int *aes_buf_len) +read_cpabe(const void *data, + char** cph_buf, + int *cph_buf_len, + char** aes_buf, + int *aes_buf_len) { int buf_len; char *ptr; @@ -265,18 +265,18 @@ read_cpabe (const void *data, ptr = (char*)data; len = (uint32_t*)ptr; - buf_len = ntohl (*len); + buf_len = ntohl(*len); ptr += 4; len = (uint32_t*)ptr; - *aes_buf_len = ntohl (*len); + *aes_buf_len = ntohl(*len); ptr += 4; - *aes_buf = GNUNET_malloc (*aes_buf_len); + *aes_buf = GNUNET_malloc(*aes_buf_len); GNUNET_memcpy(*aes_buf, ptr, *aes_buf_len); ptr += *aes_buf_len; len = (uint32_t*)ptr; - *cph_buf_len = ntohl (*len); + *cph_buf_len = ntohl(*len); ptr += 4; - *cph_buf = GNUNET_malloc (*cph_buf_len); + *cph_buf = GNUNET_malloc(*cph_buf_len); GNUNET_memcpy(*cph_buf, ptr, *cph_buf_len); return buf_len; @@ -294,11 +294,11 @@ read_cpabe (const void *data, * @return the size of the encrypted block, -1 for errors */ ssize_t -GNUNET_ABE_cpabe_encrypt (const void *block, - size_t size, - const char *policy, - const struct GNUNET_ABE_AbeMasterKey *key, - void **result) +GNUNET_ABE_cpabe_encrypt(const void *block, + size_t size, + const char *policy, + const struct GNUNET_ABE_AbeMasterKey *key, + void **result) { gabe_cph_t* cph; char* plt; @@ -309,15 +309,15 @@ GNUNET_ABE_cpabe_encrypt (const void *block, int aes_buf_len; ssize_t result_len; - if( !(cph = gabe_enc(key->pub, m, (char*)policy)) ) + if (!(cph = gabe_enc(key->pub, m, (char*)policy))) return GNUNET_SYSERR; cph_buf_len = gabe_cph_serialize(cph, - &cph_buf); + &cph_buf); gabe_cph_free(cph); - GNUNET_free (cph); - plt = GNUNET_memdup (block, size); + GNUNET_free(cph); + plt = GNUNET_memdup(block, size); aes_buf_len = aes_128_cbc_encrypt(plt, size, m, &aes_buf); - GNUNET_free (plt); + GNUNET_free(plt); element_clear(m); result_len = write_cpabe(result, size, cph_buf, cph_buf_len, aes_buf, aes_buf_len); GNUNET_free(cph_buf); @@ -336,10 +336,10 @@ GNUNET_ABE_cpabe_encrypt (const void *block, * @return the size of the encrypted block, -1 for errors */ ssize_t -GNUNET_ABE_cpabe_decrypt (const void *block, - size_t size, - const struct GNUNET_ABE_AbeKey *key, - void **result) +GNUNET_ABE_cpabe_decrypt(const void *block, + size_t size, + const struct GNUNET_ABE_AbeKey *key, + void **result) { char* aes_buf; char* cph_buf; @@ -351,22 +351,23 @@ GNUNET_ABE_cpabe_decrypt (const void *block, read_cpabe(block, &cph_buf, &cph_buf_size, &aes_buf, &aes_buf_size); cph = gabe_cph_unserialize(key->pub, cph_buf, cph_buf_size); - if( !gabe_dec(key->pub, key->prv, cph, m) ) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "%s\n", gabe_error()); - GNUNET_free (aes_buf); - GNUNET_free (cph_buf); - gabe_cph_free(cph); - GNUNET_free (cph); - element_clear (m); - return GNUNET_SYSERR; - } + if (!gabe_dec(key->pub, key->prv, cph, m)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "%s\n", gabe_error()); + GNUNET_free(aes_buf); + GNUNET_free(cph_buf); + gabe_cph_free(cph); + GNUNET_free(cph); + element_clear(m); + return GNUNET_SYSERR; + } gabe_cph_free(cph); - GNUNET_free (cph); + GNUNET_free(cph); plt_len = aes_128_cbc_decrypt(aes_buf, aes_buf_size, m, (char**)result); - GNUNET_free (cph_buf); - GNUNET_free (aes_buf); - element_clear (m); + GNUNET_free(cph_buf); + GNUNET_free(aes_buf); + element_clear(m); //freeing is buggy in gabe //gabe_prv_free (prv); //gabe_pub_free (pub); @@ -382,8 +383,8 @@ GNUNET_ABE_cpabe_decrypt (const void *block, * @return the size of the encrypted block, -1 for errors */ ssize_t -GNUNET_ABE_cpabe_serialize_key (const struct GNUNET_ABE_AbeKey *key, - void **result) +GNUNET_ABE_cpabe_serialize_key(const struct GNUNET_ABE_AbeKey *key, + void **result) { ssize_t len; char *pub; @@ -391,14 +392,14 @@ GNUNET_ABE_cpabe_serialize_key (const struct GNUNET_ABE_AbeKey *key, int pub_len; int prv_len; - pub_len = gabe_pub_serialize (key->pub, &pub); - prv_len = gabe_prv_serialize (key->prv, &prv); + pub_len = gabe_pub_serialize(key->pub, &pub); + prv_len = gabe_prv_serialize(key->prv, &prv); len = pub_len + prv_len + 12; - write_cpabe (result, len, pub, pub_len, prv, prv_len); + write_cpabe(result, len, pub, pub_len, prv, prv_len); - GNUNET_free (pub); - GNUNET_free (prv); + GNUNET_free(pub); + GNUNET_free(prv); return len; } @@ -412,8 +413,8 @@ GNUNET_ABE_cpabe_serialize_key (const struct GNUNET_ABE_AbeKey *key, * @return the ABE key. NULL of unsuccessful */ struct GNUNET_ABE_AbeKey* -GNUNET_ABE_cpabe_deserialize_key (const void *data, - size_t len) +GNUNET_ABE_cpabe_deserialize_key(const void *data, + size_t len) { struct GNUNET_ABE_AbeKey *key; char *pub; @@ -421,17 +422,17 @@ GNUNET_ABE_cpabe_deserialize_key (const void *data, int prv_len; int pub_len; - key = GNUNET_new (struct GNUNET_ABE_AbeKey); - read_cpabe (data, - &pub, - &pub_len, - &prv, - &prv_len); - key->pub = gabe_pub_unserialize (pub, pub_len); - key->prv = gabe_prv_unserialize (key->pub, prv, prv_len); - - GNUNET_free (pub); - GNUNET_free (prv); + key = GNUNET_new(struct GNUNET_ABE_AbeKey); + read_cpabe(data, + &pub, + &pub_len, + &prv, + &prv_len); + key->pub = gabe_pub_unserialize(pub, pub_len); + key->prv = gabe_prv_unserialize(key->pub, prv, prv_len); + + GNUNET_free(pub); + GNUNET_free(prv); return key; } @@ -444,8 +445,8 @@ GNUNET_ABE_cpabe_deserialize_key (const void *data, * @return the size of the encrypted block, -1 for errors */ ssize_t -GNUNET_ABE_cpabe_serialize_master_key (const struct GNUNET_ABE_AbeMasterKey *key, - void **result) +GNUNET_ABE_cpabe_serialize_master_key(const struct GNUNET_ABE_AbeMasterKey *key, + void **result) { ssize_t len; char *pub; @@ -453,14 +454,14 @@ GNUNET_ABE_cpabe_serialize_master_key (const struct GNUNET_ABE_AbeMasterKey *key int pub_len; int msk_len; - pub_len = gabe_pub_serialize (key->pub, &pub); - msk_len = gabe_msk_serialize (key->msk, &msk); + pub_len = gabe_pub_serialize(key->pub, &pub); + msk_len = gabe_msk_serialize(key->msk, &msk); len = pub_len + msk_len + 12; - write_cpabe (result, len, pub, pub_len, msk, msk_len); + write_cpabe(result, len, pub, pub_len, msk, msk_len); - GNUNET_free (pub); - GNUNET_free (msk); + GNUNET_free(pub); + GNUNET_free(msk); return len; } @@ -474,8 +475,8 @@ GNUNET_ABE_cpabe_serialize_master_key (const struct GNUNET_ABE_AbeMasterKey *key * @return the ABE key. NULL of unsuccessful */ struct GNUNET_ABE_AbeMasterKey* -GNUNET_ABE_cpabe_deserialize_master_key (const void *data, - size_t len) +GNUNET_ABE_cpabe_deserialize_master_key(const void *data, + size_t len) { struct GNUNET_ABE_AbeMasterKey *key; char *msk; @@ -483,17 +484,17 @@ GNUNET_ABE_cpabe_deserialize_master_key (const void *data, int msk_len; int pub_len; - key = GNUNET_new (struct GNUNET_ABE_AbeMasterKey); - read_cpabe (data, - &pub, - &pub_len, - &msk, - &msk_len); - key->pub = gabe_pub_unserialize (pub, pub_len); - key->msk = gabe_msk_unserialize (key->pub, msk, msk_len); - - GNUNET_free (pub); - GNUNET_free (msk); + key = GNUNET_new(struct GNUNET_ABE_AbeMasterKey); + read_cpabe(data, + &pub, + &pub_len, + &msk, + &msk_len); + key->pub = gabe_pub_unserialize(pub, pub_len); + key->msk = gabe_msk_unserialize(key->pub, msk, msk_len); + + GNUNET_free(pub); + GNUNET_free(msk); return key; } diff --git a/src/abe/test_cpabe.c b/src/abe/test_cpabe.c index e2c86e986..84b45fc8a 100644 --- a/src/abe/test_cpabe.c +++ b/src/abe/test_cpabe.c @@ -11,13 +11,13 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Martin Schanzenbach * @file util/test_crypto_abe.c @@ -30,7 +30,7 @@ #define TESTSTRING "Hello World!" static int -testAbecipher () +testAbecipher() { struct GNUNET_ABE_AbeMasterKey *msk; struct GNUNET_ABE_AbeKey *key; @@ -38,49 +38,50 @@ testAbecipher () char **attrs; int size; char *res; - msk = GNUNET_ABE_cpabe_create_master_key (); - size = GNUNET_ABE_cpabe_encrypt (TESTSTRING, strlen (TESTSTRING) + 1, - "testattr", //Policy - msk, - (void*)&result); - GNUNET_assert (-1 != size); - attrs = GNUNET_malloc (2 * sizeof (char*)); + + msk = GNUNET_ABE_cpabe_create_master_key(); + size = GNUNET_ABE_cpabe_encrypt(TESTSTRING, strlen(TESTSTRING) + 1, + "testattr", //Policy + msk, + (void*)&result); + GNUNET_assert(-1 != size); + attrs = GNUNET_malloc(2 * sizeof(char*)); attrs[0] = "testattr"; attrs[1] = NULL; - key = GNUNET_ABE_cpabe_create_key (msk, - attrs); + key = GNUNET_ABE_cpabe_create_key(msk, + attrs); - size = GNUNET_ABE_cpabe_decrypt (result, size, - key, - (void*)&res); - if (strlen (TESTSTRING) + 1 != size) - { - printf ("abeciphertest failed: decryptBlock returned %d\n", size); - return 1; - } - if (0 != strcmp (res, TESTSTRING)) - { - printf ("abeciphertest failed: %s != %s\n", res, TESTSTRING); - return 1; - } + size = GNUNET_ABE_cpabe_decrypt(result, size, + key, + (void*)&res); + if (strlen(TESTSTRING) + 1 != size) + { + printf("abeciphertest failed: decryptBlock returned %d\n", size); + return 1; + } + if (0 != strcmp(res, TESTSTRING)) + { + printf("abeciphertest failed: %s != %s\n", res, TESTSTRING); + return 1; + } else return 0; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { int failureCount = 0; - GNUNET_log_setup ("test-crypto-abe", "WARNING", NULL); - failureCount += testAbecipher (); + GNUNET_log_setup("test-crypto-abe", "WARNING", NULL); + failureCount += testAbecipher(); if (failureCount != 0) - { - printf ("%d TESTS FAILED!\n", failureCount); - return -1; - } + { + printf("%d TESTS FAILED!\n", failureCount); + return -1; + } return 0; } diff --git a/src/arm/arm.h b/src/arm/arm.h index 937cca1e7..983586060 100644 --- a/src/arm/arm.h +++ b/src/arm/arm.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -38,9 +38,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Status update from ARM to client. */ -struct GNUNET_ARM_StatusMessage -{ - +struct GNUNET_ARM_StatusMessage { /** * Reply to client, of type is #GNUNET_MESSAGE_TYPE_ARM_STATUS. */ @@ -54,8 +52,7 @@ struct GNUNET_ARM_StatusMessage /* followed by a 0-terminated service name */ }; -struct GNUNET_ARM_Message -{ +struct GNUNET_ARM_Message { /** * Reply to client, type is #GNUNET_MESSAGE_TYPE_ARM_RESULT or * #GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT. @@ -84,9 +81,7 @@ struct GNUNET_ARM_Message /** * Reply from ARM to client. */ -struct GNUNET_ARM_ResultMessage -{ - +struct GNUNET_ARM_ResultMessage { /** * Reply to client, of type is #GNUNET_MESSAGE_TYPE_ARM_RESULT, with an ID. */ @@ -104,8 +99,7 @@ struct GNUNET_ARM_ResultMessage * '\0' terminated strings. header->size contains the * total size (including all strings). */ -struct GNUNET_ARM_ListResultMessage -{ +struct GNUNET_ARM_ListResultMessage { /** * Reply to client, of type is #GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT, * with an ID. diff --git a/src/arm/arm_api.c b/src/arm/arm_api.c index bf0acbcb9..b42c95dc0 100644 --- a/src/arm/arm_api.c +++ b/src/arm/arm_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file arm/arm_api.c @@ -30,15 +30,14 @@ #include "gnunet_protocols.h" #include "arm.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "arm-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "arm-api", __VA_ARGS__) /** * Entry in a doubly-linked list of operations awaiting for replies * (in-order) from the ARM service. */ -struct GNUNET_ARM_Operation -{ +struct GNUNET_ARM_Operation { /** * This is a doubly-linked list. */ @@ -94,8 +93,7 @@ struct GNUNET_ARM_Operation /** * Handle for interacting with ARM. */ -struct GNUNET_ARM_Handle -{ +struct GNUNET_ARM_Handle { /** * Our connection to the ARM service. */ @@ -166,7 +164,7 @@ struct GNUNET_ARM_Handle * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure */ static int -reconnect_arm (struct GNUNET_ARM_Handle *h); +reconnect_arm(struct GNUNET_ARM_Handle *h); /** @@ -175,12 +173,12 @@ reconnect_arm (struct GNUNET_ARM_Handle *h); * @param cls the `struct GNUNET_ARM_Handle` */ static void -reconnect_arm_task (void *cls) +reconnect_arm_task(void *cls) { struct GNUNET_ARM_Handle *h = cls; h->reconnect_task = NULL; - reconnect_arm (h); + reconnect_arm(h); } @@ -191,31 +189,31 @@ reconnect_arm_task (void *cls) * @param h our handle */ static void -reconnect_arm_later (struct GNUNET_ARM_Handle *h) +reconnect_arm_later(struct GNUNET_ARM_Handle *h) { struct GNUNET_ARM_Operation *op; if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } h->currently_up = GNUNET_NO; - GNUNET_assert (NULL == h->reconnect_task); + GNUNET_assert(NULL == h->reconnect_task); h->reconnect_task = - GNUNET_SCHEDULER_add_delayed (h->retry_backoff, &reconnect_arm_task, h); + GNUNET_SCHEDULER_add_delayed(h->retry_backoff, &reconnect_arm_task, h); while (NULL != (op = h->operation_pending_head)) - { - if (NULL != op->result_cont) - op->result_cont (op->cont_cls, GNUNET_ARM_REQUEST_DISCONNECTED, 0); - if (NULL != op->list_cont) - op->list_cont (op->cont_cls, GNUNET_ARM_REQUEST_DISCONNECTED, 0, NULL); - GNUNET_ARM_operation_cancel (op); - } - GNUNET_assert (NULL == h->operation_pending_head); - h->retry_backoff = GNUNET_TIME_STD_BACKOFF (h->retry_backoff); + { + if (NULL != op->result_cont) + op->result_cont(op->cont_cls, GNUNET_ARM_REQUEST_DISCONNECTED, 0); + if (NULL != op->list_cont) + op->list_cont(op->cont_cls, GNUNET_ARM_REQUEST_DISCONNECTED, 0, NULL); + GNUNET_ARM_operation_cancel(op); + } + GNUNET_assert(NULL == h->operation_pending_head); + h->retry_backoff = GNUNET_TIME_STD_BACKOFF(h->retry_backoff); if (NULL != h->conn_status) - h->conn_status (h->conn_status_cls, GNUNET_NO); + h->conn_status(h->conn_status_cls, GNUNET_NO); } @@ -227,7 +225,7 @@ reconnect_arm_later (struct GNUNET_ARM_Handle *h) * @return NULL if not found */ static struct GNUNET_ARM_Operation * -find_op_by_id (struct GNUNET_ARM_Handle *h, uint64_t id) +find_op_by_id(struct GNUNET_ARM_Handle *h, uint64_t id) { struct GNUNET_ARM_Operation *result; @@ -246,7 +244,7 @@ find_op_by_id (struct GNUNET_ARM_Handle *h, uint64_t id) * @param res the message received from the arm service */ static void -handle_arm_result (void *cls, const struct GNUNET_ARM_ResultMessage *res) +handle_arm_result(void *cls, const struct GNUNET_ARM_ResultMessage *res) { struct GNUNET_ARM_Handle *h = cls; struct GNUNET_ARM_Operation *op; @@ -255,43 +253,43 @@ handle_arm_result (void *cls, const struct GNUNET_ARM_ResultMessage *res) GNUNET_ARM_ResultCallback result_cont; void *result_cont_cls; - id = GNUNET_ntohll (res->arm_msg.request_id); - op = find_op_by_id (h, id); + id = GNUNET_ntohll(res->arm_msg.request_id); + op = find_op_by_id(h, id); if (NULL == op) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Message with unknown id %llu\n", - (unsigned long long) id); - return; - } - - result = (enum GNUNET_ARM_Result) ntohl (res->result); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Message with unknown id %llu\n", + (unsigned long long)id); + return; + } + + result = (enum GNUNET_ARM_Result)ntohl(res->result); if ((GNUNET_YES == op->is_arm_stop) && (GNUNET_ARM_RESULT_STOPPING == result)) - { - /* special case: if we are stopping 'gnunet-service-arm', we do not just - wait for the result message, but also wait for the service to close - the connection (and then we have to close our client handle as well); - this is done by installing a different receive handler, waiting for - the connection to go down */ - if (NULL != h->thm) { - GNUNET_break (0); - op->result_cont (h->thm->cont_cls, - GNUNET_ARM_REQUEST_SENT_OK, - GNUNET_ARM_RESULT_IS_NOT_KNOWN); - GNUNET_free (h->thm); + /* special case: if we are stopping 'gnunet-service-arm', we do not just + wait for the result message, but also wait for the service to close + the connection (and then we have to close our client handle as well); + this is done by installing a different receive handler, waiting for + the connection to go down */ + if (NULL != h->thm) + { + GNUNET_break(0); + op->result_cont(h->thm->cont_cls, + GNUNET_ARM_REQUEST_SENT_OK, + GNUNET_ARM_RESULT_IS_NOT_KNOWN); + GNUNET_free(h->thm); + } + GNUNET_CONTAINER_DLL_remove(h->operation_pending_head, + h->operation_pending_tail, + op); + h->thm = op; + return; } - GNUNET_CONTAINER_DLL_remove (h->operation_pending_head, - h->operation_pending_tail, - op); - h->thm = op; - return; - } result_cont = op->result_cont; result_cont_cls = op->cont_cls; - GNUNET_ARM_operation_cancel (op); + GNUNET_ARM_operation_cancel(op); if (NULL != result_cont) - result_cont (result_cont_cls, GNUNET_ARM_REQUEST_SENT_OK, result); + result_cont(result_cont_cls, GNUNET_ARM_REQUEST_SENT_OK, result); } @@ -303,27 +301,27 @@ handle_arm_result (void *cls, const struct GNUNET_ARM_ResultMessage *res) * @return #GNUNET_OK if message is well-formed */ static int -check_arm_list_result (void *cls, - const struct GNUNET_ARM_ListResultMessage *lres) +check_arm_list_result(void *cls, + const struct GNUNET_ARM_ListResultMessage *lres) { - const char *pos = (const char *) &lres[1]; - uint16_t rcount = ntohs (lres->count); - uint16_t msize = ntohs (lres->arm_msg.header.size) - sizeof (*lres); + const char *pos = (const char *)&lres[1]; + uint16_t rcount = ntohs(lres->count); + uint16_t msize = ntohs(lres->arm_msg.header.size) - sizeof(*lres); uint16_t size_check; - (void) cls; + (void)cls; size_check = 0; for (unsigned int i = 0; i < rcount; i++) - { - const char *end = memchr (pos, 0, msize - size_check); - if (NULL == end) { - GNUNET_break (0); - return GNUNET_SYSERR; + const char *end = memchr(pos, 0, msize - size_check); + if (NULL == end) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + size_check += (end - pos) + 1; + pos = end + 1; } - size_check += (end - pos) + 1; - pos = end + 1; - } return GNUNET_OK; } @@ -335,41 +333,41 @@ check_arm_list_result (void *cls, * @param lres the message received from the arm service */ static void -handle_arm_list_result (void *cls, - const struct GNUNET_ARM_ListResultMessage *lres) +handle_arm_list_result(void *cls, + const struct GNUNET_ARM_ListResultMessage *lres) { struct GNUNET_ARM_Handle *h = cls; - uint16_t rcount = ntohs (lres->count); + uint16_t rcount = ntohs(lres->count); const char *list[rcount]; - const char *pos = (const char *) &lres[1]; - uint16_t msize = ntohs (lres->arm_msg.header.size) - sizeof (*lres); + const char *pos = (const char *)&lres[1]; + uint16_t msize = ntohs(lres->arm_msg.header.size) - sizeof(*lres); struct GNUNET_ARM_Operation *op; uint16_t size_check; uint64_t id; - id = GNUNET_ntohll (lres->arm_msg.request_id); - op = find_op_by_id (h, id); + id = GNUNET_ntohll(lres->arm_msg.request_id); + op = find_op_by_id(h, id); if (NULL == op) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Message with unknown id %llu\n", - (unsigned long long) id); - return; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Message with unknown id %llu\n", + (unsigned long long)id); + return; + } size_check = 0; for (unsigned int i = 0; i < rcount; i++) - { - const char *end = memchr (pos, 0, msize - size_check); - - /* Assert, as this was already checked in #check_arm_list_result() */ - GNUNET_assert (NULL != end); - list[i] = pos; - size_check += (end - pos) + 1; - pos = end + 1; - } + { + const char *end = memchr(pos, 0, msize - size_check); + + /* Assert, as this was already checked in #check_arm_list_result() */ + GNUNET_assert(NULL != end); + list[i] = pos; + size_check += (end - pos) + 1; + pos = end + 1; + } if (NULL != op->list_cont) - op->list_cont (op->cont_cls, GNUNET_ARM_REQUEST_SENT_OK, rcount, list); - GNUNET_ARM_operation_cancel (op); + op->list_cont(op->cont_cls, GNUNET_ARM_REQUEST_SENT_OK, rcount, list); + GNUNET_ARM_operation_cancel(op); } @@ -380,18 +378,18 @@ handle_arm_list_result (void *cls, * @param msg message received */ static void -handle_confirm (void *cls, const struct GNUNET_MessageHeader *msg) +handle_confirm(void *cls, const struct GNUNET_MessageHeader *msg) { struct GNUNET_ARM_Handle *h = cls; - (void) msg; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Got confirmation from ARM that we are up!\n"); + (void)msg; + LOG(GNUNET_ERROR_TYPE_DEBUG, "Got confirmation from ARM that we are up!\n"); if (GNUNET_NO == h->currently_up) - { - h->currently_up = GNUNET_YES; - if (NULL != h->conn_status) - h->conn_status (h->conn_status_cls, GNUNET_YES); - } + { + h->currently_up = GNUNET_YES; + if (NULL != h->conn_status) + h->conn_status(h->conn_status_cls, GNUNET_YES); + } } @@ -404,22 +402,22 @@ handle_confirm (void *cls, const struct GNUNET_MessageHeader *msg) * @param error error code */ static void -mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_ARM_Handle *h = cls; struct GNUNET_ARM_Operation *op; - (void) error; + (void)error; h->currently_up = GNUNET_NO; if (NULL != (op = h->thm)) - { - h->thm = NULL; - op->result_cont (op->cont_cls, - GNUNET_ARM_REQUEST_SENT_OK, - GNUNET_ARM_RESULT_STOPPED); - GNUNET_free (op); - } - reconnect_arm_later (h); + { + h->thm = NULL; + op->result_cont(op->cont_cls, + GNUNET_ARM_REQUEST_SENT_OK, + GNUNET_ARM_RESULT_STOPPED); + GNUNET_free(op); + } + reconnect_arm_later(h); } @@ -430,39 +428,39 @@ mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure */ static int -reconnect_arm (struct GNUNET_ARM_Handle *h) +reconnect_arm(struct GNUNET_ARM_Handle *h) { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_fixed_size (arm_result, - GNUNET_MESSAGE_TYPE_ARM_RESULT, - struct GNUNET_ARM_ResultMessage, - h), - GNUNET_MQ_hd_var_size (arm_list_result, - GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT, - struct GNUNET_ARM_ListResultMessage, + { GNUNET_MQ_hd_fixed_size(arm_result, + GNUNET_MESSAGE_TYPE_ARM_RESULT, + struct GNUNET_ARM_ResultMessage, + h), + GNUNET_MQ_hd_var_size(arm_list_result, + GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT, + struct GNUNET_ARM_ListResultMessage, + h), + GNUNET_MQ_hd_fixed_size(confirm, + GNUNET_MESSAGE_TYPE_ARM_TEST, + struct GNUNET_MessageHeader, h), - GNUNET_MQ_hd_fixed_size (confirm, - GNUNET_MESSAGE_TYPE_ARM_TEST, - struct GNUNET_MessageHeader, - h), - GNUNET_MQ_handler_end ()}; + GNUNET_MQ_handler_end() }; struct GNUNET_MessageHeader *test; struct GNUNET_MQ_Envelope *env; if (NULL != h->mq) return GNUNET_OK; - GNUNET_assert (GNUNET_NO == h->currently_up); - h->mq = GNUNET_CLIENT_connect (h->cfg, "arm", handlers, &mq_error_handler, h); + GNUNET_assert(GNUNET_NO == h->currently_up); + h->mq = GNUNET_CLIENT_connect(h->cfg, "arm", handlers, &mq_error_handler, h); if (NULL == h->mq) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_CLIENT_connect returned NULL\n"); - if (NULL != h->conn_status) - h->conn_status (h->conn_status_cls, GNUNET_SYSERR); - return GNUNET_SYSERR; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending TEST message to ARM\n"); - env = GNUNET_MQ_msg (test, GNUNET_MESSAGE_TYPE_ARM_TEST); - GNUNET_MQ_send (h->mq, env); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "GNUNET_CLIENT_connect returned NULL\n"); + if (NULL != h->conn_status) + h->conn_status(h->conn_status_cls, GNUNET_SYSERR); + return GNUNET_SYSERR; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, "Sending TEST message to ARM\n"); + env = GNUNET_MQ_msg(test, GNUNET_MESSAGE_TYPE_ARM_TEST); + GNUNET_MQ_send(h->mq, env); return GNUNET_OK; } @@ -479,21 +477,21 @@ reconnect_arm (struct GNUNET_ARM_Handle *h) * @return context to use for further ARM operations, NULL on error. */ struct GNUNET_ARM_Handle * -GNUNET_ARM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_ARM_ConnectionStatusCallback conn_status, - void *conn_status_cls) +GNUNET_ARM_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_ARM_ConnectionStatusCallback conn_status, + void *conn_status_cls) { struct GNUNET_ARM_Handle *h; - h = GNUNET_new (struct GNUNET_ARM_Handle); + h = GNUNET_new(struct GNUNET_ARM_Handle); h->cfg = cfg; h->conn_status = conn_status; h->conn_status_cls = conn_status_cls; - if (GNUNET_OK != reconnect_arm (h)) - { - GNUNET_free (h); - return NULL; - } + if (GNUNET_OK != reconnect_arm(h)) + { + GNUNET_free(h); + return NULL; + } return h; } @@ -504,38 +502,38 @@ GNUNET_ARM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param h the handle that was being used */ void -GNUNET_ARM_disconnect (struct GNUNET_ARM_Handle *h) +GNUNET_ARM_disconnect(struct GNUNET_ARM_Handle *h) { struct GNUNET_ARM_Operation *op; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from ARM service\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from ARM service\n"); while (NULL != (op = h->operation_pending_head)) - { - GNUNET_CONTAINER_DLL_remove (h->operation_pending_head, - h->operation_pending_tail, - op); - if (NULL != op->result_cont) - op->result_cont (op->cont_cls, GNUNET_ARM_REQUEST_DISCONNECTED, 0); - if (NULL != op->list_cont) - op->list_cont (op->cont_cls, GNUNET_ARM_REQUEST_DISCONNECTED, 0, NULL); - if (NULL != op->async) { - GNUNET_SCHEDULER_cancel (op->async); - op->async = NULL; + GNUNET_CONTAINER_DLL_remove(h->operation_pending_head, + h->operation_pending_tail, + op); + if (NULL != op->result_cont) + op->result_cont(op->cont_cls, GNUNET_ARM_REQUEST_DISCONNECTED, 0); + if (NULL != op->list_cont) + op->list_cont(op->cont_cls, GNUNET_ARM_REQUEST_DISCONNECTED, 0, NULL); + if (NULL != op->async) + { + GNUNET_SCHEDULER_cancel(op->async); + op->async = NULL; + } + GNUNET_free(op); } - GNUNET_free (op); - } if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } if (NULL != h->reconnect_task) - { - GNUNET_SCHEDULER_cancel (h->reconnect_task); - h->reconnect_task = NULL; - } - GNUNET_free (h); + { + GNUNET_SCHEDULER_cancel(h->reconnect_task); + h->reconnect_task = NULL; + } + GNUNET_free(h); } @@ -548,8 +546,8 @@ GNUNET_ARM_disconnect (struct GNUNET_ARM_Handle *h) * @return operation status code */ static enum GNUNET_ARM_Result -start_arm_service (struct GNUNET_ARM_Handle *h, - enum GNUNET_OS_InheritStdioFlags std_inheritance) +start_arm_service(struct GNUNET_ARM_Handle *h, + enum GNUNET_OS_InheritStdioFlags std_inheritance) { struct GNUNET_OS_Process *proc; char *cbinary; @@ -559,98 +557,98 @@ start_arm_service (struct GNUNET_ARM_Handle *h, char *loprefix; char *lopostfix; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (h->cfg, - "arm", - "PREFIX", - &loprefix)) - loprefix = GNUNET_strdup (""); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(h->cfg, + "arm", + "PREFIX", + &loprefix)) + loprefix = GNUNET_strdup(""); else - loprefix = GNUNET_CONFIGURATION_expand_dollar (h->cfg, loprefix); - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (h->cfg, - "arm", - "OPTIONS", - &lopostfix)) - lopostfix = GNUNET_strdup (""); + loprefix = GNUNET_CONFIGURATION_expand_dollar(h->cfg, loprefix); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(h->cfg, + "arm", + "OPTIONS", + &lopostfix)) + lopostfix = GNUNET_strdup(""); else - lopostfix = GNUNET_CONFIGURATION_expand_dollar (h->cfg, lopostfix); + lopostfix = GNUNET_CONFIGURATION_expand_dollar(h->cfg, lopostfix); if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (h->cfg, "arm", "BINARY", &cbinary)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING, "arm", "BINARY"); - GNUNET_free (loprefix); - GNUNET_free (lopostfix); - return GNUNET_ARM_RESULT_IS_NOT_KNOWN; - } - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (h->cfg, - "arm", - "CONFIG", - &config)) + GNUNET_CONFIGURATION_get_value_string(h->cfg, "arm", "BINARY", &cbinary)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_WARNING, "arm", "BINARY"); + GNUNET_free(loprefix); + GNUNET_free(lopostfix); + return GNUNET_ARM_RESULT_IS_NOT_KNOWN; + } + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(h->cfg, + "arm", + "CONFIG", + &config)) config = NULL; - binary = GNUNET_OS_get_libexec_binary_path (cbinary); - GNUNET_asprintf ("edbinary, "\"%s\"", binary); - GNUNET_free (cbinary); + binary = GNUNET_OS_get_libexec_binary_path(cbinary); + GNUNET_asprintf("edbinary, "\"%s\"", binary); + GNUNET_free(cbinary); if ((GNUNET_YES == - GNUNET_CONFIGURATION_have_value (h->cfg, "TESTING", "WEAKRANDOM")) && - (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (h->cfg, - "TESTING", - "WEAKRANDOM")) && + GNUNET_CONFIGURATION_have_value(h->cfg, "TESTING", "WEAKRANDOM")) && + (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(h->cfg, + "TESTING", + "WEAKRANDOM")) && (GNUNET_NO == - GNUNET_CONFIGURATION_have_value (h->cfg, "TESTING", "HOSTFILE"))) - { - /* Means we are ONLY running locally */ - /* we're clearly running a test, don't daemonize */ - if (NULL == config) - proc = GNUNET_OS_start_process_s (GNUNET_NO, - std_inheritance, - NULL, - loprefix, - quotedbinary, - /* no daemonization! */ - lopostfix, - NULL); - else - proc = GNUNET_OS_start_process_s (GNUNET_NO, - std_inheritance, - NULL, - loprefix, - quotedbinary, - "-c", - config, - /* no daemonization! */ - lopostfix, - NULL); - } + GNUNET_CONFIGURATION_have_value(h->cfg, "TESTING", "HOSTFILE"))) + { + /* Means we are ONLY running locally */ + /* we're clearly running a test, don't daemonize */ + if (NULL == config) + proc = GNUNET_OS_start_process_s(GNUNET_NO, + std_inheritance, + NULL, + loprefix, + quotedbinary, + /* no daemonization! */ + lopostfix, + NULL); + else + proc = GNUNET_OS_start_process_s(GNUNET_NO, + std_inheritance, + NULL, + loprefix, + quotedbinary, + "-c", + config, + /* no daemonization! */ + lopostfix, + NULL); + } else - { - if (NULL == config) - proc = GNUNET_OS_start_process_s (GNUNET_NO, - std_inheritance, - NULL, - loprefix, - quotedbinary, - "-d", /* do daemonize */ - lopostfix, - NULL); - else - proc = GNUNET_OS_start_process_s (GNUNET_NO, - std_inheritance, - NULL, - loprefix, - quotedbinary, - "-c", - config, - "-d", /* do daemonize */ - lopostfix, - NULL); - } - GNUNET_free (binary); - GNUNET_free (quotedbinary); - GNUNET_free_non_null (config); - GNUNET_free (loprefix); - GNUNET_free (lopostfix); + { + if (NULL == config) + proc = GNUNET_OS_start_process_s(GNUNET_NO, + std_inheritance, + NULL, + loprefix, + quotedbinary, + "-d", /* do daemonize */ + lopostfix, + NULL); + else + proc = GNUNET_OS_start_process_s(GNUNET_NO, + std_inheritance, + NULL, + loprefix, + quotedbinary, + "-c", + config, + "-d", /* do daemonize */ + lopostfix, + NULL); + } + GNUNET_free(binary); + GNUNET_free(quotedbinary); + GNUNET_free_non_null(config); + GNUNET_free(loprefix); + GNUNET_free(lopostfix); if (NULL == proc) return GNUNET_ARM_RESULT_START_FAILED; - GNUNET_OS_process_destroy (proc); + GNUNET_OS_process_destroy(proc); return GNUNET_ARM_RESULT_STARTING; } @@ -662,19 +660,19 @@ start_arm_service (struct GNUNET_ARM_Handle *h, * @param op operation to cancel */ void -GNUNET_ARM_operation_cancel (struct GNUNET_ARM_Operation *op) +GNUNET_ARM_operation_cancel(struct GNUNET_ARM_Operation *op) { struct GNUNET_ARM_Handle *h = op->h; if (h->thm == op) - { - op->result_cont = NULL; - return; - } - GNUNET_CONTAINER_DLL_remove (h->operation_pending_head, - h->operation_pending_tail, - op); - GNUNET_free (op); + { + op->result_cont = NULL; + return; + } + GNUNET_CONTAINER_DLL_remove(h->operation_pending_head, + h->operation_pending_tail, + op); + GNUNET_free(op); } @@ -689,38 +687,38 @@ GNUNET_ARM_operation_cancel (struct GNUNET_ARM_Operation *op) * @return handle to queue, NULL on error */ static struct GNUNET_ARM_Operation * -change_service (struct GNUNET_ARM_Handle *h, - const char *service_name, - GNUNET_ARM_ResultCallback cb, - void *cb_cls, - uint16_t type) +change_service(struct GNUNET_ARM_Handle *h, + const char *service_name, + GNUNET_ARM_ResultCallback cb, + void *cb_cls, + uint16_t type) { struct GNUNET_ARM_Operation *op; size_t slen; struct GNUNET_MQ_Envelope *env; struct GNUNET_ARM_Message *msg; - slen = strlen (service_name) + 1; - if (slen + sizeof (struct GNUNET_ARM_Message) >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return NULL; - } + slen = strlen(service_name) + 1; + if (slen + sizeof(struct GNUNET_ARM_Message) >= GNUNET_MAX_MESSAGE_SIZE) + { + GNUNET_break(0); + return NULL; + } if (0 == h->request_id_counter) h->request_id_counter++; - op = GNUNET_new (struct GNUNET_ARM_Operation); + op = GNUNET_new(struct GNUNET_ARM_Operation); op->h = h; op->result_cont = cb; op->cont_cls = cb_cls; op->id = h->request_id_counter++; - GNUNET_CONTAINER_DLL_insert_tail (h->operation_pending_head, - h->operation_pending_tail, - op); - env = GNUNET_MQ_msg_extra (msg, slen, type); - msg->reserved = htonl (0); - msg->request_id = GNUNET_htonll (op->id); - GNUNET_memcpy (&msg[1], service_name, slen); - GNUNET_MQ_send (h->mq, env); + GNUNET_CONTAINER_DLL_insert_tail(h->operation_pending_head, + h->operation_pending_tail, + op); + env = GNUNET_MQ_msg_extra(msg, slen, type); + msg->reserved = htonl(0); + msg->request_id = GNUNET_htonll(op->id); + GNUNET_memcpy(&msg[1], service_name, slen); + GNUNET_MQ_send(h->mq, env); return op; } @@ -731,22 +729,22 @@ change_service (struct GNUNET_ARM_Handle *h, * @param cls the operation that asked ARM to be started */ static void -notify_running (void *cls) +notify_running(void *cls) { struct GNUNET_ARM_Operation *op = cls; struct GNUNET_ARM_Handle *h = op->h; op->async = NULL; - GNUNET_CONTAINER_DLL_remove (h->operation_pending_head, - h->operation_pending_tail, - op); + GNUNET_CONTAINER_DLL_remove(h->operation_pending_head, + h->operation_pending_tail, + op); if (NULL != op->result_cont) - op->result_cont (op->cont_cls, - GNUNET_ARM_REQUEST_SENT_OK, - GNUNET_ARM_RESULT_IS_STARTED_ALREADY); + op->result_cont(op->cont_cls, + GNUNET_ARM_REQUEST_SENT_OK, + GNUNET_ARM_RESULT_IS_STARTED_ALREADY); if ((GNUNET_YES == h->currently_up) && (NULL != h->conn_status)) - h->conn_status (h->conn_status_cls, GNUNET_YES); - GNUNET_free (op); + h->conn_status(h->conn_status_cls, GNUNET_YES); + GNUNET_free(op); } @@ -756,22 +754,22 @@ notify_running (void *cls) * @param cls the operation that asked ARM to be started */ static void -notify_starting (void *cls) +notify_starting(void *cls) { struct GNUNET_ARM_Operation *op = cls; struct GNUNET_ARM_Handle *h = op->h; op->async = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Notifying client that we started the ARM service\n"); - GNUNET_CONTAINER_DLL_remove (h->operation_pending_head, - h->operation_pending_tail, - op); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Notifying client that we started the ARM service\n"); + GNUNET_CONTAINER_DLL_remove(h->operation_pending_head, + h->operation_pending_tail, + op); if (NULL != op->result_cont) - op->result_cont (op->cont_cls, - GNUNET_ARM_REQUEST_SENT_OK, - op->starting_ret); - GNUNET_free (op); + op->result_cont(op->cont_cls, + GNUNET_ARM_REQUEST_SENT_OK, + op->starting_ret); + GNUNET_free(op); } @@ -786,7 +784,7 @@ notify_starting (void *cls) * @return handle for the operation, NULL on error */ struct GNUNET_ARM_Operation * -GNUNET_ARM_request_service_start ( +GNUNET_ARM_request_service_start( struct GNUNET_ARM_Handle *h, const char *service_name, enum GNUNET_OS_InheritStdioFlags std_inheritance, @@ -796,13 +794,13 @@ GNUNET_ARM_request_service_start ( struct GNUNET_ARM_Operation *op; enum GNUNET_ARM_Result ret; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting service `%s'\n", service_name); - if (0 != strcasecmp ("arm", service_name)) - return change_service (h, - service_name, - cont, - cont_cls, - GNUNET_MESSAGE_TYPE_ARM_START); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Starting service `%s'\n", service_name); + if (0 != strcasecmp("arm", service_name)) + return change_service(h, + service_name, + cont, + cont_cls, + GNUNET_MESSAGE_TYPE_ARM_START); /* Possible cases: * 1) We're connected to ARM already. Invoke the callback immediately. @@ -811,37 +809,37 @@ GNUNET_ARM_request_service_start ( * a service test. */ if (GNUNET_YES == h->currently_up) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, "ARM is already running\n"); - op = GNUNET_new (struct GNUNET_ARM_Operation); - op->h = h; - op->result_cont = cont; - op->cont_cls = cont_cls; - GNUNET_CONTAINER_DLL_insert_tail (h->operation_pending_head, - h->operation_pending_tail, - op); - op->async = GNUNET_SCHEDULER_add_now (¬ify_running, op); - return op; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "ARM is already running\n"); + op = GNUNET_new(struct GNUNET_ARM_Operation); + op->h = h; + op->result_cont = cont; + op->cont_cls = cont_cls; + GNUNET_CONTAINER_DLL_insert_tail(h->operation_pending_head, + h->operation_pending_tail, + op); + op->async = GNUNET_SCHEDULER_add_now(¬ify_running, op); + return op; + } /* This is an inherently uncertain choice, as it is of course theoretically possible that ARM is up and we just did not yet complete the MQ handshake. However, given that users are unlikely to hammer 'gnunet-arm -s' on a busy system, the above check should catch 99.99% of the cases where ARM is already running. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting ARM service\n"); - ret = start_arm_service (h, std_inheritance); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Starting ARM service\n"); + ret = start_arm_service(h, std_inheritance); if (GNUNET_ARM_RESULT_STARTING == ret) - reconnect_arm (h); - op = GNUNET_new (struct GNUNET_ARM_Operation); + reconnect_arm(h); + op = GNUNET_new(struct GNUNET_ARM_Operation); op->h = h; op->result_cont = cont; op->cont_cls = cont_cls; - GNUNET_CONTAINER_DLL_insert_tail (h->operation_pending_head, - h->operation_pending_tail, - op); + GNUNET_CONTAINER_DLL_insert_tail(h->operation_pending_head, + h->operation_pending_tail, + op); op->starting_ret = ret; - op->async = GNUNET_SCHEDULER_add_now (¬ify_starting, op); + op->async = GNUNET_SCHEDULER_add_now(¬ify_starting, op); return op; } @@ -861,24 +859,24 @@ GNUNET_ARM_request_service_start ( * @return handle for the operation, NULL on error */ struct GNUNET_ARM_Operation * -GNUNET_ARM_request_service_stop (struct GNUNET_ARM_Handle *h, - const char *service_name, - GNUNET_ARM_ResultCallback cont, - void *cont_cls) +GNUNET_ARM_request_service_stop(struct GNUNET_ARM_Handle *h, + const char *service_name, + GNUNET_ARM_ResultCallback cont, + void *cont_cls) { struct GNUNET_ARM_Operation *op; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Stopping service `%s'\n", service_name); - op = change_service (h, - service_name, - cont, - cont_cls, - GNUNET_MESSAGE_TYPE_ARM_STOP); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Stopping service `%s'\n", service_name); + op = change_service(h, + service_name, + cont, + cont_cls, + GNUNET_MESSAGE_TYPE_ARM_STOP); if (NULL == op) return NULL; /* If the service is ARM, set a flag as we will use MQ errors to detect that the process is really gone. */ - if (0 == strcasecmp (service_name, "arm")) + if (0 == strcasecmp(service_name, "arm")) op->is_arm_stop = GNUNET_YES; return op; } @@ -893,29 +891,29 @@ GNUNET_ARM_request_service_stop (struct GNUNET_ARM_Handle *h, * @return handle for the operation, NULL on error */ struct GNUNET_ARM_Operation * -GNUNET_ARM_request_service_list (struct GNUNET_ARM_Handle *h, - GNUNET_ARM_ServiceListCallback cont, - void *cont_cls) +GNUNET_ARM_request_service_list(struct GNUNET_ARM_Handle *h, + GNUNET_ARM_ServiceListCallback cont, + void *cont_cls) { struct GNUNET_ARM_Operation *op; struct GNUNET_MQ_Envelope *env; struct GNUNET_ARM_Message *msg; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting LIST from ARM service\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Requesting LIST from ARM service\n"); if (0 == h->request_id_counter) h->request_id_counter++; - op = GNUNET_new (struct GNUNET_ARM_Operation); + op = GNUNET_new(struct GNUNET_ARM_Operation); op->h = h; op->list_cont = cont; op->cont_cls = cont_cls; op->id = h->request_id_counter++; - GNUNET_CONTAINER_DLL_insert_tail (h->operation_pending_head, - h->operation_pending_tail, - op); - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_ARM_LIST); - msg->reserved = htonl (0); - msg->request_id = GNUNET_htonll (op->id); - GNUNET_MQ_send (h->mq, env); + GNUNET_CONTAINER_DLL_insert_tail(h->operation_pending_head, + h->operation_pending_tail, + op); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_ARM_LIST); + msg->reserved = htonl(0); + msg->request_id = GNUNET_htonll(op->id); + GNUNET_MQ_send(h->mq, env); return op; } diff --git a/src/arm/arm_monitor_api.c b/src/arm/arm_monitor_api.c index 55b12240f..c6e1e2683 100644 --- a/src/arm/arm_monitor_api.c +++ b/src/arm/arm_monitor_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file arm/arm_monitor_api.c @@ -30,16 +30,14 @@ #include "gnunet_protocols.h" #include "arm.h" -#define INIT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define INIT_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) -#define LOG(kind, ...) GNUNET_log_from (kind, "arm-monitor-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "arm-monitor-api", __VA_ARGS__) /** * Handle for interacting with ARM. */ -struct GNUNET_ARM_MonitorHandle -{ - +struct GNUNET_ARM_MonitorHandle { /** * Our control connection to the ARM service. */ @@ -79,7 +77,7 @@ struct GNUNET_ARM_MonitorHandle * @return #GNUNET_OK on success */ static int -reconnect_arm_monitor (struct GNUNET_ARM_MonitorHandle *h); +reconnect_arm_monitor(struct GNUNET_ARM_MonitorHandle *h); /** @@ -88,14 +86,14 @@ reconnect_arm_monitor (struct GNUNET_ARM_MonitorHandle *h); * @param cls the `struct GNUNET_ARM_MonitorHandle` */ static void -reconnect_arm_monitor_task (void *cls) +reconnect_arm_monitor_task(void *cls) { struct GNUNET_ARM_MonitorHandle *h = cls; h->reconnect_task = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Connecting to ARM service for monitoring after delay\n"); - GNUNET_break (GNUNET_OK == reconnect_arm_monitor (h)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Connecting to ARM service for monitoring after delay\n"); + GNUNET_break(GNUNET_OK == reconnect_arm_monitor(h)); } @@ -106,18 +104,18 @@ reconnect_arm_monitor_task (void *cls) * @param h our handle */ static void -reconnect_arm_monitor_later (struct GNUNET_ARM_MonitorHandle *h) +reconnect_arm_monitor_later(struct GNUNET_ARM_MonitorHandle *h) { if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } - GNUNET_assert (NULL == h->reconnect_task); - h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->retry_backoff, - &reconnect_arm_monitor_task, - h); - h->retry_backoff = GNUNET_TIME_STD_BACKOFF (h->retry_backoff); + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } + GNUNET_assert(NULL == h->reconnect_task); + h->reconnect_task = GNUNET_SCHEDULER_add_delayed(h->retry_backoff, + &reconnect_arm_monitor_task, + h); + h->retry_backoff = GNUNET_TIME_STD_BACKOFF(h->retry_backoff); } @@ -129,18 +127,18 @@ reconnect_arm_monitor_later (struct GNUNET_ARM_MonitorHandle *h) * @return #GNUNET_OK if the message is well-formed */ static int -check_monitor_notify (void *cls, const struct GNUNET_ARM_StatusMessage *msg) +check_monitor_notify(void *cls, const struct GNUNET_ARM_StatusMessage *msg) { size_t sl = - ntohs (msg->header.size) - sizeof (struct GNUNET_ARM_StatusMessage); - const char *name = (const char *) &msg[1]; + ntohs(msg->header.size) - sizeof(struct GNUNET_ARM_StatusMessage); + const char *name = (const char *)&msg[1]; - (void) cls; + (void)cls; if ((0 == sl) || ('\0' != name[sl - 1])) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -152,18 +150,18 @@ check_monitor_notify (void *cls, const struct GNUNET_ARM_StatusMessage *msg) * @param res the message received from the arm service */ static void -handle_monitor_notify (void *cls, const struct GNUNET_ARM_StatusMessage *res) +handle_monitor_notify(void *cls, const struct GNUNET_ARM_StatusMessage *res) { struct GNUNET_ARM_MonitorHandle *h = cls; enum GNUNET_ARM_ServiceStatus status; - status = (enum GNUNET_ARM_ServiceStatus) ntohl (res->status); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received notification from ARM for service `%s' with status %d\n", - (const char *) &res[1], - (int) status); + status = (enum GNUNET_ARM_ServiceStatus)ntohl(res->status); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received notification from ARM for service `%s' with status %d\n", + (const char *)&res[1], + (int)status); if (NULL != h->service_status) - h->service_status (h->service_status_cls, (const char *) &res[1], status); + h->service_status(h->service_status_cls, (const char *)&res[1], status); } @@ -176,12 +174,12 @@ handle_monitor_notify (void *cls, const struct GNUNET_ARM_StatusMessage *res) * @param error error code */ static void -mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_ARM_MonitorHandle *h = cls; - (void) error; - reconnect_arm_monitor_later (h); + (void)error; + reconnect_arm_monitor_later(h); } @@ -192,29 +190,29 @@ mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @return #GNUNET_OK on success */ static int -reconnect_arm_monitor (struct GNUNET_ARM_MonitorHandle *h) +reconnect_arm_monitor(struct GNUNET_ARM_MonitorHandle *h) { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_var_size (monitor_notify, - GNUNET_MESSAGE_TYPE_ARM_STATUS, - struct GNUNET_ARM_StatusMessage, - h), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_var_size(monitor_notify, + GNUNET_MESSAGE_TYPE_ARM_STATUS, + struct GNUNET_ARM_StatusMessage, + h), + GNUNET_MQ_handler_end() }; struct GNUNET_MessageHeader *msg; struct GNUNET_MQ_Envelope *env; - GNUNET_assert (NULL == h->mq); - h->mq = GNUNET_CLIENT_connect (h->cfg, "arm", handlers, &mq_error_handler, h); + GNUNET_assert(NULL == h->mq); + h->mq = GNUNET_CLIENT_connect(h->cfg, "arm", handlers, &mq_error_handler, h); if (NULL == h->mq) - { - if (NULL != h->service_status) - h->service_status (h->service_status_cls, - NULL, - GNUNET_ARM_SERVICE_STOPPED); - return GNUNET_SYSERR; - } - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_ARM_MONITOR); - GNUNET_MQ_send (h->mq, env); + { + if (NULL != h->service_status) + h->service_status(h->service_status_cls, + NULL, + GNUNET_ARM_SERVICE_STOPPED); + return GNUNET_SYSERR; + } + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_ARM_MONITOR); + GNUNET_MQ_send(h->mq, env); return GNUNET_OK; } @@ -231,21 +229,21 @@ reconnect_arm_monitor (struct GNUNET_ARM_MonitorHandle *h) * @return context to use for further ARM monitor operations, NULL on error. */ struct GNUNET_ARM_MonitorHandle * -GNUNET_ARM_monitor_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_ARM_ServiceStatusCallback cont, - void *cont_cls) +GNUNET_ARM_monitor_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_ARM_ServiceStatusCallback cont, + void *cont_cls) { struct GNUNET_ARM_MonitorHandle *h; - h = GNUNET_new (struct GNUNET_ARM_MonitorHandle); + h = GNUNET_new(struct GNUNET_ARM_MonitorHandle); h->cfg = cfg; h->service_status = cont; h->service_status_cls = cont_cls; - if (GNUNET_OK != reconnect_arm_monitor (h)) - { - GNUNET_free (h); - return NULL; - } + if (GNUNET_OK != reconnect_arm_monitor(h)) + { + GNUNET_free(h); + return NULL; + } return h; } @@ -256,19 +254,19 @@ GNUNET_ARM_monitor_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param h the handle that was being used */ void -GNUNET_ARM_monitor_stop (struct GNUNET_ARM_MonitorHandle *h) +GNUNET_ARM_monitor_stop(struct GNUNET_ARM_MonitorHandle *h) { if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } if (NULL != h->reconnect_task) - { - GNUNET_SCHEDULER_cancel (h->reconnect_task); - h->reconnect_task = NULL; - } - GNUNET_free (h); + { + GNUNET_SCHEDULER_cancel(h->reconnect_task); + h->reconnect_task = NULL; + } + GNUNET_free(h); } diff --git a/src/arm/gnunet-arm.c b/src/arm/gnunet-arm.c index f96076231..3396a4dbe 100644 --- a/src/arm/gnunet-arm.c +++ b/src/arm/gnunet-arm.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file arm/gnunet-arm.c @@ -144,25 +144,25 @@ static struct GNUNET_ARM_Operation *op; * were specified when gnunet-arm was run. */ static void -delete_files () +delete_files() { - GNUNET_log ( + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "Will attempt to remove configuration file %s and service directory %s\n", config_file, dir); - if (0 != unlink (config_file)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to remove configuration file %s\n"), - config_file); - } - if (GNUNET_OK != GNUNET_DISK_directory_remove (dir)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to remove servicehome directory %s\n"), - dir); - } + if (0 != unlink(config_file)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to remove configuration file %s\n"), + config_file); + } + if (GNUNET_OK != GNUNET_DISK_directory_remove(dir)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to remove servicehome directory %s\n"), + dir); + } } @@ -173,37 +173,37 @@ delete_files () * @param cls closure, unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - (void) cls; + (void)cls; if (NULL != al_task) - { - GNUNET_SCHEDULER_cancel (al_task); - al_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(al_task); + al_task = NULL; + } if (NULL != op) - { - GNUNET_ARM_operation_cancel (op); - op = NULL; - } + { + GNUNET_ARM_operation_cancel(op); + op = NULL; + } if (NULL != h) - { - GNUNET_ARM_disconnect (h); - h = NULL; - } + { + GNUNET_ARM_disconnect(h); + h = NULL; + } if (NULL != m) - { - GNUNET_ARM_monitor_stop (m); - m = NULL; - } + { + GNUNET_ARM_monitor_stop(m); + m = NULL; + } if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } if ((GNUNET_YES == end) && (GNUNET_YES == delete)) - delete_files (); - GNUNET_CONFIGURATION_destroy (cfg); + delete_files(); + GNUNET_CONFIGURATION_destroy(cfg); cfg = NULL; } @@ -215,16 +215,17 @@ shutdown_task (void *cls) * @return a string interpretation of the request status */ static const char * -req_string (enum GNUNET_ARM_RequestStatus rs) +req_string(enum GNUNET_ARM_RequestStatus rs) { switch (rs) - { - case GNUNET_ARM_REQUEST_SENT_OK: - return _ ("Message was sent successfully"); - case GNUNET_ARM_REQUEST_DISCONNECTED: - return _ ("We disconnected from ARM before we could send a request"); - } - return _ ("Unknown request status"); + { + case GNUNET_ARM_REQUEST_SENT_OK: + return _("Message was sent successfully"); + + case GNUNET_ARM_REQUEST_DISCONNECTED: + return _("We disconnected from ARM before we could send a request"); + } + return _("Unknown request status"); } @@ -235,32 +236,41 @@ req_string (enum GNUNET_ARM_RequestStatus rs) * @return a string interpretation */ static const char * -ret_string (enum GNUNET_ARM_Result result) +ret_string(enum GNUNET_ARM_Result result) { switch (result) - { - case GNUNET_ARM_RESULT_STOPPED: - return _ ("is stopped"); - case GNUNET_ARM_RESULT_STARTING: - return _ ("is starting"); - case GNUNET_ARM_RESULT_STOPPING: - return _ ("is stopping"); - case GNUNET_ARM_RESULT_IS_STARTING_ALREADY: - return _ ("is starting already"); - case GNUNET_ARM_RESULT_IS_STOPPING_ALREADY: - return _ ("is stopping already"); - case GNUNET_ARM_RESULT_IS_STARTED_ALREADY: - return _ ("is started already"); - case GNUNET_ARM_RESULT_IS_STOPPED_ALREADY: - return _ ("is stopped already"); - case GNUNET_ARM_RESULT_IS_NOT_KNOWN: - return _ ("service is not known to ARM"); - case GNUNET_ARM_RESULT_START_FAILED: - return _ ("service failed to start"); - case GNUNET_ARM_RESULT_IN_SHUTDOWN: - return _ ("service cannot be manipulated because ARM is shutting down"); - } - return _ ("Unknown result code."); + { + case GNUNET_ARM_RESULT_STOPPED: + return _("is stopped"); + + case GNUNET_ARM_RESULT_STARTING: + return _("is starting"); + + case GNUNET_ARM_RESULT_STOPPING: + return _("is stopping"); + + case GNUNET_ARM_RESULT_IS_STARTING_ALREADY: + return _("is starting already"); + + case GNUNET_ARM_RESULT_IS_STOPPING_ALREADY: + return _("is stopping already"); + + case GNUNET_ARM_RESULT_IS_STARTED_ALREADY: + return _("is started already"); + + case GNUNET_ARM_RESULT_IS_STOPPED_ALREADY: + return _("is stopped already"); + + case GNUNET_ARM_RESULT_IS_NOT_KNOWN: + return _("service is not known to ARM"); + + case GNUNET_ARM_RESULT_START_FAILED: + return _("service failed to start"); + + case GNUNET_ARM_RESULT_IN_SHUTDOWN: + return _("service cannot be manipulated because ARM is shutting down"); + } + return _("Unknown result code."); } @@ -270,7 +280,7 @@ ret_string (enum GNUNET_ARM_Result result) * @param cls closure */ static void -action_loop (void *cls); +action_loop(void *cls); /** @@ -283,18 +293,18 @@ action_loop (void *cls); * #GNUNET_SYSERR on error. */ static void -conn_status (void *cls, int connected) +conn_status(void *cls, int connected) { static int once; - (void) cls; + (void)cls; if ((GNUNET_SYSERR == connected) && (0 == once)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Fatal error initializing ARM API.\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Fatal error initializing ARM API.\n")); + GNUNET_SCHEDULER_shutdown(); + return; + } once = 1; } @@ -311,32 +321,32 @@ conn_status (void *cls, int connected) * according to ARM */ static void -start_callback (void *cls, - enum GNUNET_ARM_RequestStatus rs, - enum GNUNET_ARM_Result result) +start_callback(void *cls, + enum GNUNET_ARM_RequestStatus rs, + enum GNUNET_ARM_Result result) { - (void) cls; + (void)cls; op = NULL; if (GNUNET_ARM_REQUEST_SENT_OK != rs) - { - fprintf (stdout, - _ ("Failed to start the ARM service: %s\n"), - req_string (rs)); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + fprintf(stdout, + _("Failed to start the ARM service: %s\n"), + req_string(rs)); + GNUNET_SCHEDULER_shutdown(); + return; + } if ((GNUNET_ARM_RESULT_STARTING != result) && (GNUNET_ARM_RESULT_IS_STARTED_ALREADY != result)) - { - fprintf (stdout, - _ ("Failed to start the ARM service: %s\n"), - ret_string (result)); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ARM service [re]start successful\n"); + { + fprintf(stdout, + _("Failed to start the ARM service: %s\n"), + ret_string(result)); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "ARM service [re]start successful\n"); start = 0; - al_task = GNUNET_SCHEDULER_add_now (&action_loop, NULL); + al_task = GNUNET_SCHEDULER_add_now(&action_loop, NULL); } @@ -352,44 +362,44 @@ start_callback (void *cls, * according to ARM */ static void -stop_callback (void *cls, - enum GNUNET_ARM_RequestStatus rs, - enum GNUNET_ARM_Result result) +stop_callback(void *cls, + enum GNUNET_ARM_RequestStatus rs, + enum GNUNET_ARM_Result result) { char *msg; - (void) cls; + (void)cls; op = NULL; if (GNUNET_ARM_REQUEST_SENT_OK != rs) - { - GNUNET_asprintf (&msg, - "%s", - _ ( - "Failed to send a stop request to the ARM service: %s\n")); - fprintf (stdout, msg, req_string (rs)); - GNUNET_free (msg); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_asprintf(&msg, + "%s", + _( + "Failed to send a stop request to the ARM service: %s\n")); + fprintf(stdout, msg, req_string(rs)); + GNUNET_free(msg); + GNUNET_SCHEDULER_shutdown(); + return; + } if ((GNUNET_ARM_RESULT_STOPPING != result) && (GNUNET_ARM_RESULT_STOPPED != result) && (GNUNET_ARM_RESULT_IS_STOPPED_ALREADY != result)) - { - fprintf (stdout, - _ ("Failed to stop the ARM service: %s\n"), - ret_string (result)); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ARM service shutdown successful\n"); + { + fprintf(stdout, + _("Failed to stop the ARM service: %s\n"), + ret_string(result)); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "ARM service shutdown successful\n"); end = 0; if (restart) - { - restart = 0; - start = 1; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Initiating an ARM restart\n"); - } - al_task = GNUNET_SCHEDULER_add_now (&action_loop, NULL); + { + restart = 0; + start = 1; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initiating an ARM restart\n"); + } + al_task = GNUNET_SCHEDULER_add_now(&action_loop, NULL); } @@ -405,37 +415,37 @@ stop_callback (void *cls, * according to ARM */ static void -init_callback (void *cls, - enum GNUNET_ARM_RequestStatus rs, - enum GNUNET_ARM_Result result) +init_callback(void *cls, + enum GNUNET_ARM_RequestStatus rs, + enum GNUNET_ARM_Result result) { - (void) cls; + (void)cls; op = NULL; if (GNUNET_ARM_REQUEST_SENT_OK != rs) - { - fprintf (stdout, - _ ("Failed to send a request to start the `%s' service: %s\n"), - init, - req_string (rs)); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + fprintf(stdout, + _("Failed to send a request to start the `%s' service: %s\n"), + init, + req_string(rs)); + GNUNET_SCHEDULER_shutdown(); + return; + } if ((GNUNET_ARM_RESULT_STARTING != result) && (GNUNET_ARM_RESULT_IS_STARTED_ALREADY != result)) - { - fprintf (stdout, - _ ("Failed to start the `%s' service: %s\n"), - init, - ret_string (result)); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Service %s [re]started successfully\n", - init); - GNUNET_free (init); + { + fprintf(stdout, + _("Failed to start the `%s' service: %s\n"), + init, + ret_string(result)); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Service %s [re]started successfully\n", + init); + GNUNET_free(init); init = NULL; - al_task = GNUNET_SCHEDULER_add_now (&action_loop, NULL); + al_task = GNUNET_SCHEDULER_add_now(&action_loop, NULL); } @@ -451,42 +461,42 @@ init_callback (void *cls, * according to ARM */ static void -term_callback (void *cls, - enum GNUNET_ARM_RequestStatus rs, - enum GNUNET_ARM_Result result) +term_callback(void *cls, + enum GNUNET_ARM_RequestStatus rs, + enum GNUNET_ARM_Result result) { char *msg; - (void) cls; + (void)cls; op = NULL; if (GNUNET_ARM_REQUEST_SENT_OK != rs) - { - GNUNET_asprintf (&msg, - _ ( - "Failed to send a request to kill the `%s' service: %%s\n"), - term); - fprintf (stdout, msg, req_string (rs)); - GNUNET_free (msg); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_asprintf(&msg, + _( + "Failed to send a request to kill the `%s' service: %%s\n"), + term); + fprintf(stdout, msg, req_string(rs)); + GNUNET_free(msg); + GNUNET_SCHEDULER_shutdown(); + return; + } if ((GNUNET_ARM_RESULT_STOPPED != result) && (GNUNET_ARM_RESULT_IS_STOPPED_ALREADY != result)) - { - fprintf (stdout, - _ ("Failed to kill the `%s' service: %s\n"), - term, - ret_string (result)); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + fprintf(stdout, + _("Failed to kill the `%s' service: %s\n"), + term, + ret_string(result)); + GNUNET_SCHEDULER_shutdown(); + return; + } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Service %s stopped successfully\n", - term); - GNUNET_free (term); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Service %s stopped successfully\n", + term); + GNUNET_free(term); term = NULL; - al_task = GNUNET_SCHEDULER_add_now (&action_loop, NULL); + al_task = GNUNET_SCHEDULER_add_now(&action_loop, NULL); } @@ -501,39 +511,39 @@ term_callback (void *cls, * @param list list of services that are running */ static void -list_callback (void *cls, - enum GNUNET_ARM_RequestStatus rs, - unsigned int count, - const char *const *list) +list_callback(void *cls, + enum GNUNET_ARM_RequestStatus rs, + unsigned int count, + const char *const *list) { - (void) cls; + (void)cls; op = NULL; if (GNUNET_ARM_REQUEST_SENT_OK != rs) - { - char *msg; - - GNUNET_asprintf (&msg, - "%s", - _ ("Failed to request a list of services: %s\n")); - fprintf (stdout, msg, req_string (rs)); - GNUNET_free (msg); - ret = 3; - GNUNET_SCHEDULER_shutdown (); - } + { + char *msg; + + GNUNET_asprintf(&msg, + "%s", + _("Failed to request a list of services: %s\n")); + fprintf(stdout, msg, req_string(rs)); + GNUNET_free(msg); + ret = 3; + GNUNET_SCHEDULER_shutdown(); + } if (NULL == list) - { - fprintf (stderr, - "%s", - _ ("Error communicating with ARM. ARM not running?\n")); - GNUNET_SCHEDULER_shutdown (); - ret = 3; - return; - } - if (! quiet) - fprintf (stdout, "%s", _ ("Running services:\n")); + { + fprintf(stderr, + "%s", + _("Error communicating with ARM. ARM not running?\n")); + GNUNET_SCHEDULER_shutdown(); + ret = 3; + return; + } + if (!quiet) + fprintf(stdout, "%s", _("Running services:\n")); for (unsigned int i = 0; i < count; i++) - fprintf (stdout, "%s\n", list[i]); - al_task = GNUNET_SCHEDULER_add_now (&action_loop, NULL); + fprintf(stdout, "%s\n", list[i]); + al_task = GNUNET_SCHEDULER_add_now(&action_loop, NULL); } @@ -544,85 +554,91 @@ list_callback (void *cls, * @param cls closure, unused */ static void -action_loop (void *cls) +action_loop(void *cls) { - (void) cls; + (void)cls; al_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Running requested actions\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Running requested actions\n"); while (1) - { - switch (phase++) { - case 0: - if (NULL != term) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Termination action\n"); - op = GNUNET_ARM_request_service_stop (h, term, &term_callback, NULL); - return; - } - break; - case 1: - if (end || restart) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "End action\n"); - op = GNUNET_ARM_request_service_stop (h, "arm", &stop_callback, NULL); - return; - } - break; - case 2: - if (start) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Start action\n"); - op = - GNUNET_ARM_request_service_start (h, - "arm", - (no_stdout - ? 0 - : GNUNET_OS_INHERIT_STD_OUT) | - (no_stderr - ? 0 - : GNUNET_OS_INHERIT_STD_ERR), - &start_callback, - NULL); - return; - } - break; - case 3: - if (NULL != init) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Initialization action\n"); - op = GNUNET_ARM_request_service_start (h, - init, - GNUNET_OS_INHERIT_STD_NONE, - &init_callback, - NULL); - return; - } - break; - case 4: - if (list) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Going to list all running services controlled by ARM.\n"); - op = GNUNET_ARM_request_service_list (h, &list_callback, &list); - return; - } - break; - case 5: - if (monitor) - { - if (! quiet) - fprintf (stderr, _ ("Now only monitoring, press CTRL-C to stop.\n")); - quiet = - 0; /* does not make sense to stay quiet in monitor mode at this time */ - return; /* done with tasks, just monitor */ - } - break; - default: /* last phase */ - GNUNET_SCHEDULER_shutdown (); - return; + switch (phase++) + { + case 0: + if (NULL != term) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Termination action\n"); + op = GNUNET_ARM_request_service_stop(h, term, &term_callback, NULL); + return; + } + break; + + case 1: + if (end || restart) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "End action\n"); + op = GNUNET_ARM_request_service_stop(h, "arm", &stop_callback, NULL); + return; + } + break; + + case 2: + if (start) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Start action\n"); + op = + GNUNET_ARM_request_service_start(h, + "arm", + (no_stdout + ? 0 + : GNUNET_OS_INHERIT_STD_OUT) | + (no_stderr + ? 0 + : GNUNET_OS_INHERIT_STD_ERR), + &start_callback, + NULL); + return; + } + break; + + case 3: + if (NULL != init) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Initialization action\n"); + op = GNUNET_ARM_request_service_start(h, + init, + GNUNET_OS_INHERIT_STD_NONE, + &init_callback, + NULL); + return; + } + break; + + case 4: + if (list) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Going to list all running services controlled by ARM.\n"); + op = GNUNET_ARM_request_service_list(h, &list_callback, &list); + return; + } + break; + + case 5: + if (monitor) + { + if (!quiet) + fprintf(stderr, _("Now only monitoring, press CTRL-C to stop.\n")); + quiet = + 0; /* does not make sense to stay quiet in monitor mode at this time */ + return; /* done with tasks, just monitor */ + } + break; + + default: /* last phase */ + GNUNET_SCHEDULER_shutdown(); + return; + } } - } } @@ -634,44 +650,48 @@ action_loop (void *cls) * @param status status of the service */ static void -srv_status (void *cls, - const char *service, - enum GNUNET_ARM_ServiceStatus status) +srv_status(void *cls, + const char *service, + enum GNUNET_ARM_ServiceStatus status) { const char *msg; - (void) cls; + (void)cls; switch (status) - { - case GNUNET_ARM_SERVICE_MONITORING_STARTED: - return; /* this should be done silently */ - case GNUNET_ARM_SERVICE_STOPPED: - msg = _ ("Stopped %s.\n"); - break; - case GNUNET_ARM_SERVICE_STARTING: - msg = _ ("Starting %s...\n"); - break; - case GNUNET_ARM_SERVICE_STOPPING: - msg = _ ("Stopping %s...\n"); - break; - default: - msg = NULL; - break; - } - if (! quiet) - { - if (NULL != msg) - fprintf (stderr, msg, service); - else - fprintf (stderr, - _ ("Unknown status %u for service %s.\n"), - status, - service); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got service %s status %d\n", - service, - (int) status); + { + case GNUNET_ARM_SERVICE_MONITORING_STARTED: + return; /* this should be done silently */ + + case GNUNET_ARM_SERVICE_STOPPED: + msg = _("Stopped %s.\n"); + break; + + case GNUNET_ARM_SERVICE_STARTING: + msg = _("Starting %s...\n"); + break; + + case GNUNET_ARM_SERVICE_STOPPING: + msg = _("Stopping %s...\n"); + break; + + default: + msg = NULL; + break; + } + if (!quiet) + { + if (NULL != msg) + fprintf(stderr, msg, service); + else + fprintf(stderr, + _("Unknown status %u for service %s.\n"), + status, + service); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got service %s status %d\n", + service, + (int)status); } @@ -679,12 +699,12 @@ srv_status (void *cls, * Task run on timeout (if -T is given). */ static void -timeout_task_cb (void *cls) +timeout_task_cb(void *cls) { - (void) cls; + (void)cls; timeout_task = NULL; ret = 2; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -697,34 +717,34 @@ timeout_task_cb (void *cls) * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { - (void) cls; - (void) args; - (void) cfgfile; - cfg = GNUNET_CONFIGURATION_dup (c); + (void)cls; + (void)args; + (void)cfgfile; + cfg = GNUNET_CONFIGURATION_dup(c); if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS", "GNUNET_HOME", &dir)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "PATHS", "GNUNET_HOME"); - return; - } - (void) GNUNET_CONFIGURATION_get_value_filename (cfg, - "arm", - "CONFIG", - &config_file); - if (NULL == (h = GNUNET_ARM_connect (cfg, &conn_status, NULL))) + GNUNET_CONFIGURATION_get_value_string(cfg, "PATHS", "GNUNET_HOME", &dir)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "PATHS", "GNUNET_HOME"); + return; + } + (void)GNUNET_CONFIGURATION_get_value_filename(cfg, + "arm", + "CONFIG", + &config_file); + if (NULL == (h = GNUNET_ARM_connect(cfg, &conn_status, NULL))) return; if (monitor) - m = GNUNET_ARM_monitor_start (cfg, &srv_status, NULL); - al_task = GNUNET_SCHEDULER_add_now (&action_loop, NULL); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + m = GNUNET_ARM_monitor_start(cfg, &srv_status, NULL); + al_task = GNUNET_SCHEDULER_add_now(&action_loop, NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); if (0 != timeout.rel_value_us) timeout_task = - GNUNET_SCHEDULER_add_delayed (timeout, &timeout_task_cb, NULL); + GNUNET_SCHEDULER_add_delayed(timeout, &timeout_task_cb, NULL); } @@ -736,88 +756,88 @@ run (void *cls, * @return 0 ok, 1 on error, 2 on timeout */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_flag ('e', - "end", - gettext_noop ("stop all GNUnet services"), - &end), - GNUNET_GETOPT_option_string ('i', - "init", - "SERVICE", - gettext_noop ("start a particular service"), - &init), - GNUNET_GETOPT_option_string ('k', - "kill", - "SERVICE", - gettext_noop ("stop a particular service"), - &term), - GNUNET_GETOPT_option_flag ('s', - "start", - gettext_noop ( - "start all GNUnet default services"), - &start), - GNUNET_GETOPT_option_flag ('r', - "restart", - gettext_noop ( - "stop and start all GNUnet default services"), - &restart), - GNUNET_GETOPT_option_flag ('d', - "delete", - gettext_noop ( - "delete config file and directory on exit"), - &delete), - GNUNET_GETOPT_option_flag ('m', - "monitor", - gettext_noop ("monitor ARM activities"), - &monitor), - GNUNET_GETOPT_option_flag ('q', - "quiet", - gettext_noop ("don't print status messages"), - &quiet), - GNUNET_GETOPT_option_relative_time ( - 'T', - "timeout", - "DELAY", - gettext_noop ( - "exit with error status if operation does not finish after DELAY"), - &timeout), - GNUNET_GETOPT_option_flag ('I', - "info", - gettext_noop ( - "list currently running services"), - &list), - GNUNET_GETOPT_option_flag ( - 'O', - "no-stdout", - gettext_noop ("don't let gnunet-service-arm inherit standard output"), - &no_stdout), - GNUNET_GETOPT_option_flag ( - 'E', - "no-stderr", - gettext_noop ("don't let gnunet-service-arm inherit standard error"), - &no_stderr), - GNUNET_GETOPT_OPTION_END}; + { GNUNET_GETOPT_option_flag('e', + "end", + gettext_noop("stop all GNUnet services"), + &end), + GNUNET_GETOPT_option_string('i', + "init", + "SERVICE", + gettext_noop("start a particular service"), + &init), + GNUNET_GETOPT_option_string('k', + "kill", + "SERVICE", + gettext_noop("stop a particular service"), + &term), + GNUNET_GETOPT_option_flag('s', + "start", + gettext_noop( + "start all GNUnet default services"), + &start), + GNUNET_GETOPT_option_flag('r', + "restart", + gettext_noop( + "stop and start all GNUnet default services"), + &restart), + GNUNET_GETOPT_option_flag('d', + "delete", + gettext_noop( + "delete config file and directory on exit"), + &delete), + GNUNET_GETOPT_option_flag('m', + "monitor", + gettext_noop("monitor ARM activities"), + &monitor), + GNUNET_GETOPT_option_flag('q', + "quiet", + gettext_noop("don't print status messages"), + &quiet), + GNUNET_GETOPT_option_relative_time( + 'T', + "timeout", + "DELAY", + gettext_noop( + "exit with error status if operation does not finish after DELAY"), + &timeout), + GNUNET_GETOPT_option_flag('I', + "info", + gettext_noop( + "list currently running services"), + &list), + GNUNET_GETOPT_option_flag( + 'O', + "no-stdout", + gettext_noop("don't let gnunet-service-arm inherit standard output"), + &no_stdout), + GNUNET_GETOPT_option_flag( + 'E', + "no-stderr", + gettext_noop("don't let gnunet-service-arm inherit standard error"), + &no_stderr), + GNUNET_GETOPT_OPTION_END }; int lret; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; if (GNUNET_OK == - (lret = GNUNET_PROGRAM_run ( + (lret = GNUNET_PROGRAM_run( argc, argv, "gnunet-arm", - gettext_noop ( + gettext_noop( "Control services and the Automated Restart Manager (ARM)"), options, &run, NULL))) - { - GNUNET_free ((void *) argv); - return ret; - } - GNUNET_free ((void *) argv); + { + GNUNET_free((void *)argv); + return ret; + } + GNUNET_free((void *)argv); return lret; } diff --git a/src/arm/gnunet-service-arm.c b/src/arm/gnunet-service-arm.c index b0f7e07c4..e8c740235 100644 --- a/src/arm/gnunet-service-arm.c +++ b/src/arm/gnunet-service-arm.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file arm/gnunet-service-arm.c @@ -29,10 +29,10 @@ #include "gnunet_protocols.h" #include "arm.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "util", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "util", __VA_ARGS__) #define LOG_STRERROR(kind, syscall) \ - GNUNET_log_from_strerror (kind, "util", syscall) + GNUNET_log_from_strerror(kind, "util", syscall) #if HAVE_WAIT4 @@ -65,8 +65,7 @@ struct ServiceList; /** * Record with information about a listen socket we have open. */ -struct ServiceListeningInfo -{ +struct ServiceListeningInfo { /** * This is a linked list. */ @@ -107,8 +106,7 @@ struct ServiceListeningInfo /** * List of our services. */ -struct ServiceList -{ +struct ServiceList { /** * This is a doubly-linked list. */ @@ -280,30 +278,30 @@ static struct GNUNET_NotificationContext *notifier; * parameter is ignore on systems other than LINUX */ static void -add_unixpath (struct sockaddr **saddrs, - socklen_t *saddrlens, - const char *unixpath, - int abstract) +add_unixpath(struct sockaddr **saddrs, + socklen_t *saddrlens, + const char *unixpath, + int abstract) { #ifdef AF_UNIX struct sockaddr_un *un; - un = GNUNET_new (struct sockaddr_un); + un = GNUNET_new(struct sockaddr_un); un->sun_family = AF_UNIX; - GNUNET_strlcpy (un->sun_path, unixpath, sizeof (un->sun_path)); + GNUNET_strlcpy(un->sun_path, unixpath, sizeof(un->sun_path)); #ifdef LINUX if (GNUNET_YES == abstract) un->sun_path[0] = '\0'; #endif #if HAVE_SOCKADDR_UN_SUN_LEN - un->sun_len = (u_char) sizeof (struct sockaddr_un); + un->sun_len = (u_char)sizeof(struct sockaddr_un); #endif - *saddrs = (struct sockaddr *) un; - *saddrlens = sizeof (struct sockaddr_un); + *saddrs = (struct sockaddr *)un; + *saddrlens = sizeof(struct sockaddr_un); #else /* this function should never be called * unless AF_UNIX is defined! */ - GNUNET_assert (0); + GNUNET_assert(0); #endif } @@ -329,10 +327,10 @@ add_unixpath (struct sockaddr **saddrs, * set to NULL). */ static int -get_server_addresses (const char *service_name, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct sockaddr ***addrs, - socklen_t **addr_lens) +get_server_addresses(const char *service_name, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct sockaddr ***addrs, + socklen_t **addr_lens) { int disablev6; struct GNUNET_NETWORK_Handle *desc; @@ -353,72 +351,72 @@ get_server_addresses (const char *service_name, *addrs = NULL; *addr_lens = NULL; desc = NULL; - if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "DISABLEV6")) - { - if (GNUNET_SYSERR == - (disablev6 = GNUNET_CONFIGURATION_get_value_yesno (cfg, - service_name, - "DISABLEV6"))) - return GNUNET_SYSERR; - } - else - disablev6 = GNUNET_NO; - - if (! disablev6) - { - /* probe IPv6 support */ - desc = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0); - if (NULL == desc) + if (GNUNET_CONFIGURATION_have_value(cfg, service_name, "DISABLEV6")) { - if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) || - (EACCES == errno)) - { - LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket"); + if (GNUNET_SYSERR == + (disablev6 = GNUNET_CONFIGURATION_get_value_yesno(cfg, + service_name, + "DISABLEV6"))) return GNUNET_SYSERR; - } - LOG (GNUNET_ERROR_TYPE_INFO, - _ ( - "Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"), - service_name, - strerror (errno)); - disablev6 = GNUNET_YES; } - else + else + disablev6 = GNUNET_NO; + + if (!disablev6) { - GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc)); - desc = NULL; + /* probe IPv6 support */ + desc = GNUNET_NETWORK_socket_create(PF_INET6, SOCK_STREAM, 0); + if (NULL == desc) + { + if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) || + (EACCES == errno)) + { + LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "socket"); + return GNUNET_SYSERR; + } + LOG(GNUNET_ERROR_TYPE_INFO, + _( + "Disabling IPv6 support for service `%s', failed to create IPv6 socket: %s\n"), + service_name, + strerror(errno)); + disablev6 = GNUNET_YES; + } + else + { + GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(desc)); + desc = NULL; + } } - } port = 0; - if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT")) - { - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, - service_name, - "PORT", - &port)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _ ("Require valid port number for service `%s' in configuration!\n"), - service_name); - } - if (port > 65535) + if (GNUNET_CONFIGURATION_have_value(cfg, service_name, "PORT")) { - LOG (GNUNET_ERROR_TYPE_ERROR, - _ ("Require valid port number for service `%s' in configuration!\n"), - service_name); - return GNUNET_SYSERR; + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, + service_name, + "PORT", + &port)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Require valid port number for service `%s' in configuration!\n"), + service_name); + } + if (port > 65535) + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Require valid port number for service `%s' in configuration!\n"), + service_name); + return GNUNET_SYSERR; + } } - } - if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "BINDTO")) - { - GNUNET_break (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (cfg, + if (GNUNET_CONFIGURATION_have_value(cfg, service_name, "BINDTO")) + { + GNUNET_break(GNUNET_OK == + GNUNET_CONFIGURATION_get_value_string(cfg, service_name, "BINDTO", &hostname)); - } + } else hostname = NULL; @@ -426,235 +424,235 @@ get_server_addresses (const char *service_name, abstract = GNUNET_NO; #ifdef AF_UNIX if ((GNUNET_YES == - GNUNET_CONFIGURATION_have_value (cfg, service_name, "UNIXPATH")) && - (GNUNET_OK == GNUNET_CONFIGURATION_get_value_filename (cfg, - service_name, - "UNIXPATH", - &unixpath)) && - (0 < strlen (unixpath))) - { - /* probe UNIX support */ - struct sockaddr_un s_un; - - if (strlen (unixpath) >= sizeof (s_un.sun_path)) + GNUNET_CONFIGURATION_have_value(cfg, service_name, "UNIXPATH")) && + (GNUNET_OK == GNUNET_CONFIGURATION_get_value_filename(cfg, + service_name, + "UNIXPATH", + &unixpath)) && + (0 < strlen(unixpath))) { - LOG (GNUNET_ERROR_TYPE_WARNING, - _ ("UNIXPATH `%s' too long, maximum length is %llu\n"), - unixpath, - (unsigned long long) sizeof (s_un.sun_path)); - unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath); - LOG (GNUNET_ERROR_TYPE_INFO, _ ("Using `%s' instead\n"), unixpath); - } + /* probe UNIX support */ + struct sockaddr_un s_un; + + if (strlen(unixpath) >= sizeof(s_un.sun_path)) + { + LOG(GNUNET_ERROR_TYPE_WARNING, + _("UNIXPATH `%s' too long, maximum length is %llu\n"), + unixpath, + (unsigned long long)sizeof(s_un.sun_path)); + unixpath = GNUNET_NETWORK_shorten_unixpath(unixpath); + LOG(GNUNET_ERROR_TYPE_INFO, _("Using `%s' instead\n"), unixpath); + } #ifdef LINUX - abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg, - "TESTING", - "USE_ABSTRACT_SOCKETS"); - if (GNUNET_SYSERR == abstract) - abstract = GNUNET_NO; + abstract = GNUNET_CONFIGURATION_get_value_yesno(cfg, + "TESTING", + "USE_ABSTRACT_SOCKETS"); + if (GNUNET_SYSERR == abstract) + abstract = GNUNET_NO; #endif - if ((GNUNET_YES != abstract) && - (GNUNET_OK != GNUNET_DISK_directory_create_for_file (unixpath))) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mkdir", unixpath); - } - if (NULL != unixpath) - { - desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0); - if (NULL == desc) - { - if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) || - (EACCES == errno)) - { - LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket"); - GNUNET_free_non_null (hostname); - GNUNET_free (unixpath); - return GNUNET_SYSERR; - } - LOG (GNUNET_ERROR_TYPE_INFO, - _ ( - "Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"), - service_name, - strerror (errno)); - GNUNET_free (unixpath); - unixpath = NULL; + if ((GNUNET_YES != abstract) && + (GNUNET_OK != GNUNET_DISK_directory_create_for_file(unixpath))) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "mkdir", unixpath); } - else + if (NULL != unixpath) { - GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc)); - desc = NULL; + desc = GNUNET_NETWORK_socket_create(AF_UNIX, SOCK_STREAM, 0); + if (NULL == desc) + { + if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) || + (EACCES == errno)) + { + LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "socket"); + GNUNET_free_non_null(hostname); + GNUNET_free(unixpath); + return GNUNET_SYSERR; + } + LOG(GNUNET_ERROR_TYPE_INFO, + _( + "Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"), + service_name, + strerror(errno)); + GNUNET_free(unixpath); + unixpath = NULL; + } + else + { + GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(desc)); + desc = NULL; + } } - } #endif if ((0 == port) && (NULL == unixpath)) - { - if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, - service_name, - "START_ON_DEMAND")) - LOG (GNUNET_ERROR_TYPE_ERROR, - _ ( - "Have neither PORT nor UNIXPATH for service `%s', but one is required\n"), - service_name); - GNUNET_free_non_null (hostname); - return GNUNET_SYSERR; - } - if (0 == port) - { - saddrs = GNUNET_new_array (2, struct sockaddr *); - saddrlens = GNUNET_new_array (2, socklen_t); - add_unixpath (saddrs, saddrlens, unixpath, abstract); - GNUNET_free_non_null (unixpath); - GNUNET_free_non_null (hostname); - *addrs = saddrs; - *addr_lens = saddrlens; - return 1; - } - - if (NULL != hostname) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Resolving `%s' since that is where `%s' will bind to.\n", - hostname, - service_name); - memset (&hints, 0, sizeof (struct addrinfo)); - if (disablev6) - hints.ai_family = AF_INET; - hints.ai_protocol = IPPROTO_TCP; - if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) || - (NULL == res)) { - LOG (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to resolve `%s': %s\n"), - hostname, - gai_strerror (ret)); - GNUNET_free (hostname); - GNUNET_free_non_null (unixpath); - return GNUNET_SYSERR; - } - next = res; - i = 0; - while (NULL != (pos = next)) - { - next = pos->ai_next; - if ((disablev6) && (pos->ai_family == AF_INET6)) - continue; - i++; - } - if (0 == i) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to find %saddress for `%s'.\n"), - disablev6 ? "IPv4 " : "", - hostname); - freeaddrinfo (res); - GNUNET_free (hostname); - GNUNET_free_non_null (unixpath); + if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, + service_name, + "START_ON_DEMAND")) + LOG(GNUNET_ERROR_TYPE_ERROR, + _( + "Have neither PORT nor UNIXPATH for service `%s', but one is required\n"), + service_name); + GNUNET_free_non_null(hostname); return GNUNET_SYSERR; } - resi = i; - if (NULL != unixpath) - resi++; - saddrs = GNUNET_new_array (resi + 1, struct sockaddr *); - saddrlens = GNUNET_new_array (resi + 1, socklen_t); - i = 0; - if (NULL != unixpath) + if (0 == port) { - add_unixpath (saddrs, saddrlens, unixpath, abstract); - i++; + saddrs = GNUNET_new_array(2, struct sockaddr *); + saddrlens = GNUNET_new_array(2, socklen_t); + add_unixpath(saddrs, saddrlens, unixpath, abstract); + GNUNET_free_non_null(unixpath); + GNUNET_free_non_null(hostname); + *addrs = saddrs; + *addr_lens = saddrlens; + return 1; } - next = res; - while (NULL != (pos = next)) - { - next = pos->ai_next; - if ((disablev6) && (AF_INET6 == pos->ai_family)) - continue; - if ((IPPROTO_TCP != pos->ai_protocol) && (0 != pos->ai_protocol)) - continue; /* not TCP */ - if ((SOCK_STREAM != pos->ai_socktype) && (0 != pos->ai_socktype)) - continue; /* huh? */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Service `%s' will bind to `%s'\n", - service_name, - GNUNET_a2s (pos->ai_addr, pos->ai_addrlen)); - if (AF_INET == pos->ai_family) - { - GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen); - saddrlens[i] = pos->ai_addrlen; - saddrs[i] = GNUNET_malloc (saddrlens[i]); - GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]); - ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port); - } - else - { - GNUNET_assert (AF_INET6 == pos->ai_family); - GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen); - saddrlens[i] = pos->ai_addrlen; - saddrs[i] = GNUNET_malloc (saddrlens[i]); - GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]); - ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port); - } - i++; - } - GNUNET_free (hostname); - freeaddrinfo (res); - resi = i; - } - else - { - /* will bind against everything, just set port */ - if (disablev6) + + if (NULL != hostname) { - /* V4-only */ - resi = 1; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Resolving `%s' since that is where `%s' will bind to.\n", + hostname, + service_name); + memset(&hints, 0, sizeof(struct addrinfo)); + if (disablev6) + hints.ai_family = AF_INET; + hints.ai_protocol = IPPROTO_TCP; + if ((0 != (ret = getaddrinfo(hostname, NULL, &hints, &res))) || + (NULL == res)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Failed to resolve `%s': %s\n"), + hostname, + gai_strerror(ret)); + GNUNET_free(hostname); + GNUNET_free_non_null(unixpath); + return GNUNET_SYSERR; + } + next = res; + i = 0; + while (NULL != (pos = next)) + { + next = pos->ai_next; + if ((disablev6) && (pos->ai_family == AF_INET6)) + continue; + i++; + } + if (0 == i) + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Failed to find %saddress for `%s'.\n"), + disablev6 ? "IPv4 " : "", + hostname); + freeaddrinfo(res); + GNUNET_free(hostname); + GNUNET_free_non_null(unixpath); + return GNUNET_SYSERR; + } + resi = i; if (NULL != unixpath) resi++; + saddrs = GNUNET_new_array(resi + 1, struct sockaddr *); + saddrlens = GNUNET_new_array(resi + 1, socklen_t); i = 0; - saddrs = GNUNET_new_array (resi + 1, struct sockaddr *); - saddrlens = GNUNET_new_array (resi + 1, socklen_t); if (NULL != unixpath) - { - add_unixpath (saddrs, saddrlens, unixpath, abstract); - i++; - } - saddrlens[i] = sizeof (struct sockaddr_in); - saddrs[i] = GNUNET_malloc (saddrlens[i]); -#if HAVE_SOCKADDR_IN_SIN_LEN - ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i]; -#endif - ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET; - ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port); + { + add_unixpath(saddrs, saddrlens, unixpath, abstract); + i++; + } + next = res; + while (NULL != (pos = next)) + { + next = pos->ai_next; + if ((disablev6) && (AF_INET6 == pos->ai_family)) + continue; + if ((IPPROTO_TCP != pos->ai_protocol) && (0 != pos->ai_protocol)) + continue; /* not TCP */ + if ((SOCK_STREAM != pos->ai_socktype) && (0 != pos->ai_socktype)) + continue; /* huh? */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Service `%s' will bind to `%s'\n", + service_name, + GNUNET_a2s(pos->ai_addr, pos->ai_addrlen)); + if (AF_INET == pos->ai_family) + { + GNUNET_assert(sizeof(struct sockaddr_in) == pos->ai_addrlen); + saddrlens[i] = pos->ai_addrlen; + saddrs[i] = GNUNET_malloc(saddrlens[i]); + GNUNET_memcpy(saddrs[i], pos->ai_addr, saddrlens[i]); + ((struct sockaddr_in *)saddrs[i])->sin_port = htons(port); + } + else + { + GNUNET_assert(AF_INET6 == pos->ai_family); + GNUNET_assert(sizeof(struct sockaddr_in6) == pos->ai_addrlen); + saddrlens[i] = pos->ai_addrlen; + saddrs[i] = GNUNET_malloc(saddrlens[i]); + GNUNET_memcpy(saddrs[i], pos->ai_addr, saddrlens[i]); + ((struct sockaddr_in6 *)saddrs[i])->sin6_port = htons(port); + } + i++; + } + GNUNET_free(hostname); + freeaddrinfo(res); + resi = i; } - else + else { - /* dual stack */ - resi = 2; - if (NULL != unixpath) - resi++; - saddrs = GNUNET_new_array (resi + 1, struct sockaddr *); - saddrlens = GNUNET_new_array (resi + 1, socklen_t); - i = 0; - if (NULL != unixpath) - { - add_unixpath (saddrs, saddrlens, unixpath, abstract); - i++; - } - saddrlens[i] = sizeof (struct sockaddr_in6); - saddrs[i] = GNUNET_malloc (saddrlens[i]); + /* will bind against everything, just set port */ + if (disablev6) + { + /* V4-only */ + resi = 1; + if (NULL != unixpath) + resi++; + i = 0; + saddrs = GNUNET_new_array(resi + 1, struct sockaddr *); + saddrlens = GNUNET_new_array(resi + 1, socklen_t); + if (NULL != unixpath) + { + add_unixpath(saddrs, saddrlens, unixpath, abstract); + i++; + } + saddrlens[i] = sizeof(struct sockaddr_in); + saddrs[i] = GNUNET_malloc(saddrlens[i]); +#if HAVE_SOCKADDR_IN_SIN_LEN + ((struct sockaddr_in *)saddrs[i])->sin_len = saddrlens[i]; +#endif + ((struct sockaddr_in *)saddrs[i])->sin_family = AF_INET; + ((struct sockaddr_in *)saddrs[i])->sin_port = htons(port); + } + else + { + /* dual stack */ + resi = 2; + if (NULL != unixpath) + resi++; + saddrs = GNUNET_new_array(resi + 1, struct sockaddr *); + saddrlens = GNUNET_new_array(resi + 1, socklen_t); + i = 0; + if (NULL != unixpath) + { + add_unixpath(saddrs, saddrlens, unixpath, abstract); + i++; + } + saddrlens[i] = sizeof(struct sockaddr_in6); + saddrs[i] = GNUNET_malloc(saddrlens[i]); #if HAVE_SOCKADDR_IN_SIN_LEN - ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0]; + ((struct sockaddr_in6 *)saddrs[i])->sin6_len = saddrlens[0]; #endif - ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6; - ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port); - i++; - saddrlens[i] = sizeof (struct sockaddr_in); - saddrs[i] = GNUNET_malloc (saddrlens[i]); + ((struct sockaddr_in6 *)saddrs[i])->sin6_family = AF_INET6; + ((struct sockaddr_in6 *)saddrs[i])->sin6_port = htons(port); + i++; + saddrlens[i] = sizeof(struct sockaddr_in); + saddrs[i] = GNUNET_malloc(saddrlens[i]); #if HAVE_SOCKADDR_IN_SIN_LEN - ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1]; + ((struct sockaddr_in *)saddrs[i])->sin_len = saddrlens[1]; #endif - ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET; - ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port); + ((struct sockaddr_in *)saddrs[i])->sin_family = AF_INET; + ((struct sockaddr_in *)saddrs[i])->sin_port = htons(port); + } } - } - GNUNET_free_non_null (unixpath); + GNUNET_free_non_null(unixpath); *addrs = saddrs; *addr_lens = saddrlens; return resi; @@ -672,19 +670,19 @@ get_server_addresses (const char *service_name, * @return NULL if it was not found */ static void -signal_result (struct GNUNET_SERVICE_Client *client, - const char *name, - uint64_t request_id, - enum GNUNET_ARM_Result result) +signal_result(struct GNUNET_SERVICE_Client *client, + const char *name, + uint64_t request_id, + enum GNUNET_ARM_Result result) { struct GNUNET_MQ_Envelope *env; struct GNUNET_ARM_ResultMessage *msg; - (void) name; - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_ARM_RESULT); - msg->result = htonl (result); - msg->arm_msg.request_id = GNUNET_htonll (request_id); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); + (void)name; + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_ARM_RESULT); + msg->result = htonl(result); + msg->arm_msg.request_id = GNUNET_htonll(request_id); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); } @@ -697,34 +695,34 @@ signal_result (struct GNUNET_SERVICE_Client *client, * otherwise, send to all clients in the notifier */ static void -broadcast_status (const char *name, - enum GNUNET_ARM_ServiceStatus status, - struct GNUNET_SERVICE_Client *unicast) +broadcast_status(const char *name, + enum GNUNET_ARM_ServiceStatus status, + struct GNUNET_SERVICE_Client *unicast) { struct GNUNET_MQ_Envelope *env; struct GNUNET_ARM_StatusMessage *msg; size_t namelen; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending status %u of service `%s' to client\n", - (unsigned int) status, - name); - namelen = strlen (name) + 1; - env = GNUNET_MQ_msg_extra (msg, namelen, GNUNET_MESSAGE_TYPE_ARM_STATUS); - msg->status = htonl ((uint32_t) (status)); - GNUNET_memcpy ((char *) &msg[1], name, namelen); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending status %u of service `%s' to client\n", + (unsigned int)status, + name); + namelen = strlen(name) + 1; + env = GNUNET_MQ_msg_extra(msg, namelen, GNUNET_MESSAGE_TYPE_ARM_STATUS); + msg->status = htonl((uint32_t)(status)); + GNUNET_memcpy((char *)&msg[1], name, namelen); if (NULL == unicast) - { - if (NULL != notifier) - GNUNET_notification_context_broadcast (notifier, - &msg->header, - GNUNET_YES); - GNUNET_MQ_discard (env); - } + { + if (NULL != notifier) + GNUNET_notification_context_broadcast(notifier, + &msg->header, + GNUNET_YES); + GNUNET_MQ_discard(env); + } else - { - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (unicast), env); - } + { + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(unicast), env); + } } @@ -737,9 +735,9 @@ broadcast_status (const char *name, * being started. 0 if starting was not requested. */ static void -start_process (struct ServiceList *sl, - struct GNUNET_SERVICE_Client *client, - uint64_t request_id) +start_process(struct ServiceList *sl, + struct GNUNET_SERVICE_Client *client, + uint64_t request_id) { char *loprefix; char *options; @@ -755,194 +753,194 @@ start_process (struct ServiceList *sl, lsocks = NULL; ls = 0; for (sli = sl->listen_head; NULL != sli; sli = sli->next) - { - GNUNET_array_append (lsocks, - ls, - GNUNET_NETWORK_get_fd (sli->listen_socket)); - if (NULL != sli->accept_task) { - GNUNET_SCHEDULER_cancel (sli->accept_task); - sli->accept_task = NULL; + GNUNET_array_append(lsocks, + ls, + GNUNET_NETWORK_get_fd(sli->listen_socket)); + if (NULL != sli->accept_task) + { + GNUNET_SCHEDULER_cancel(sli->accept_task); + sli->accept_task = NULL; + } } - } #if WINDOWS - GNUNET_array_append (lsocks, ls, INVALID_SOCKET); + GNUNET_array_append(lsocks, ls, INVALID_SOCKET); #else - GNUNET_array_append (lsocks, ls, -1); + GNUNET_array_append(lsocks, ls, -1); #endif /* obtain configuration */ - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - sl->name, - "PREFIX", - &loprefix)) - loprefix = GNUNET_strdup (prefix_command); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + sl->name, + "PREFIX", + &loprefix)) + loprefix = GNUNET_strdup(prefix_command); else - loprefix = GNUNET_CONFIGURATION_expand_dollar (cfg, loprefix); - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - sl->name, - "OPTIONS", - &options)) + loprefix = GNUNET_CONFIGURATION_expand_dollar(cfg, loprefix); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + sl->name, + "OPTIONS", + &options)) options = NULL; else - options = GNUNET_CONFIGURATION_expand_dollar (cfg, options); + options = GNUNET_CONFIGURATION_expand_dollar(cfg, options); { char *new_options; char *optpos; char *fin_options; - fin_options = GNUNET_strdup (final_option); + fin_options = GNUNET_strdup(final_option); /* replace '{}' with service name */ - while (NULL != (optpos = strstr (fin_options, "{}"))) - { - /* terminate string at opening parenthesis */ - *optpos = 0; - GNUNET_asprintf (&new_options, - "%s%s%s", - fin_options, - sl->name, - optpos + 2); - GNUNET_free (fin_options); - fin_options = new_options; - } + while (NULL != (optpos = strstr(fin_options, "{}"))) + { + /* terminate string at opening parenthesis */ + *optpos = 0; + GNUNET_asprintf(&new_options, + "%s%s%s", + fin_options, + sl->name, + optpos + 2); + GNUNET_free(fin_options); + fin_options = new_options; + } if (NULL != options) - { - /* combine "fin_options" with "options" */ - optpos = options; - GNUNET_asprintf (&options, "%s %s", fin_options, optpos); - GNUNET_free (fin_options); - GNUNET_free (optpos); - } + { + /* combine "fin_options" with "options" */ + optpos = options; + GNUNET_asprintf(&options, "%s %s", fin_options, optpos); + GNUNET_free(fin_options); + GNUNET_free(optpos); + } else - { - /* only have "fin_options", use that */ - options = fin_options; - } + { + /* only have "fin_options", use that */ + options = fin_options; + } } - options = GNUNET_CONFIGURATION_expand_dollar (cfg, options); - use_debug = GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name, "DEBUG"); + options = GNUNET_CONFIGURATION_expand_dollar(cfg, options); + use_debug = GNUNET_CONFIGURATION_get_value_yesno(cfg, sl->name, "DEBUG"); { const char *service_type = NULL; - const char *choices[] = {"GNUNET", "SIMPLE", NULL}; + const char *choices[] = { "GNUNET", "SIMPLE", NULL }; is_simple_service = GNUNET_NO; - if ((GNUNET_OK == GNUNET_CONFIGURATION_get_value_choice (cfg, - sl->name, - "TYPE", - choices, - &service_type)) && - (0 == strcasecmp (service_type, "SIMPLE"))) + if ((GNUNET_OK == GNUNET_CONFIGURATION_get_value_choice(cfg, + sl->name, + "TYPE", + choices, + &service_type)) && + (0 == strcasecmp(service_type, "SIMPLE"))) is_simple_service = GNUNET_YES; } - GNUNET_assert (NULL == sl->proc); + GNUNET_assert(NULL == sl->proc); if (GNUNET_YES == is_simple_service) - { - /* A simple service will receive no GNUnet specific - command line options. */ - binary = GNUNET_strdup (sl->binary); - binary = GNUNET_CONFIGURATION_expand_dollar (cfg, binary); - GNUNET_asprintf ("edbinary, "\"%s\"", sl->binary); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting simple service `%s' using binary `%s'\n", - sl->name, - sl->binary); - /* FIXME: dollar expansion should only be done outside - * of ''-quoted strings, escaping should be considered. */ - if (NULL != options) - options = GNUNET_CONFIGURATION_expand_dollar (cfg, options); - sl->proc = GNUNET_OS_start_process_s (sl->pipe_control, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - lsocks, - loprefix, - quotedbinary, - options, - NULL); - } - else - { - /* actually start process */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting service `%s' using binary `%s' and configuration `%s'\n", - sl->name, - sl->binary, - sl->config); - binary = GNUNET_OS_get_libexec_binary_path (sl->binary); - GNUNET_asprintf ("edbinary, "\"%s\"", binary); - - if (GNUNET_YES == use_debug) { - if (NULL == sl->config) - sl->proc = GNUNET_OS_start_process_s (sl->pipe_control, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - lsocks, - loprefix, - quotedbinary, - "-L", - "DEBUG", - options, - NULL); - else - sl->proc = GNUNET_OS_start_process_s (sl->pipe_control, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - lsocks, - loprefix, - quotedbinary, - "-c", - sl->config, - "-L", - "DEBUG", - options, - NULL); + /* A simple service will receive no GNUnet specific + command line options. */ + binary = GNUNET_strdup(sl->binary); + binary = GNUNET_CONFIGURATION_expand_dollar(cfg, binary); + GNUNET_asprintf("edbinary, "\"%s\"", sl->binary); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting simple service `%s' using binary `%s'\n", + sl->name, + sl->binary); + /* FIXME: dollar expansion should only be done outside + * of ''-quoted strings, escaping should be considered. */ + if (NULL != options) + options = GNUNET_CONFIGURATION_expand_dollar(cfg, options); + sl->proc = GNUNET_OS_start_process_s(sl->pipe_control, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + lsocks, + loprefix, + quotedbinary, + options, + NULL); } - else + else { - if (NULL == sl->config) - sl->proc = GNUNET_OS_start_process_s (sl->pipe_control, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - lsocks, - loprefix, - quotedbinary, - options, - NULL); + /* actually start process */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting service `%s' using binary `%s' and configuration `%s'\n", + sl->name, + sl->binary, + sl->config); + binary = GNUNET_OS_get_libexec_binary_path(sl->binary); + GNUNET_asprintf("edbinary, "\"%s\"", binary); + + if (GNUNET_YES == use_debug) + { + if (NULL == sl->config) + sl->proc = GNUNET_OS_start_process_s(sl->pipe_control, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + lsocks, + loprefix, + quotedbinary, + "-L", + "DEBUG", + options, + NULL); + else + sl->proc = GNUNET_OS_start_process_s(sl->pipe_control, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + lsocks, + loprefix, + quotedbinary, + "-c", + sl->config, + "-L", + "DEBUG", + options, + NULL); + } else - sl->proc = GNUNET_OS_start_process_s (sl->pipe_control, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - lsocks, - loprefix, - quotedbinary, - "-c", - sl->config, - options, - NULL); + { + if (NULL == sl->config) + sl->proc = GNUNET_OS_start_process_s(sl->pipe_control, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + lsocks, + loprefix, + quotedbinary, + options, + NULL); + else + sl->proc = GNUNET_OS_start_process_s(sl->pipe_control, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + lsocks, + loprefix, + quotedbinary, + "-c", + sl->config, + options, + NULL); + } } - } - GNUNET_free (binary); - GNUNET_free (quotedbinary); + GNUNET_free(binary); + GNUNET_free(quotedbinary); if (NULL == sl->proc) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to start service `%s'\n"), - sl->name); - if (client) - signal_result (client, - sl->name, - request_id, - GNUNET_ARM_RESULT_START_FAILED); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to start service `%s'\n"), + sl->name); + if (client) + signal_result(client, + sl->name, + request_id, + GNUNET_ARM_RESULT_START_FAILED); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Starting service `%s'\n"), - sl->name); - broadcast_status (sl->name, GNUNET_ARM_SERVICE_STARTING, NULL); - if (client) - signal_result (client, sl->name, request_id, GNUNET_ARM_RESULT_STARTING); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Starting service `%s'\n"), + sl->name); + broadcast_status(sl->name, GNUNET_ARM_SERVICE_STARTING, NULL); + if (client) + signal_result(client, sl->name, request_id, GNUNET_ARM_RESULT_STARTING); + } /* clean up */ - GNUNET_free (loprefix); - GNUNET_free (options); - GNUNET_array_grow (lsocks, ls, 0); + GNUNET_free(loprefix); + GNUNET_free(options); + GNUNET_array_grow(lsocks, ls, 0); } @@ -954,17 +952,17 @@ start_process (struct ServiceList *sl, * @return NULL if it was not found */ static struct ServiceList * -find_service (const char *name) +find_service(const char *name) { struct ServiceList *sl; sl = running_head; while (sl != NULL) - { - if (0 == strcasecmp (sl->name, name)) - return sl; - sl = sl->next; - } + { + if (0 == strcasecmp(sl->name, name)) + return sl; + sl = sl->next; + } return NULL; } @@ -976,14 +974,14 @@ find_service (const char *name) * @param cls callback data, `struct ServiceListeningInfo` describing a listen socket */ static void -accept_connection (void *cls) +accept_connection(void *cls) { struct ServiceListeningInfo *sli = cls; struct ServiceList *sl = sli->sl; sli->accept_task = NULL; - GNUNET_assert (GNUNET_NO == in_shutdown); - start_process (sl, NULL, 0); + GNUNET_assert(GNUNET_NO == in_shutdown); + start_process(sl, NULL, 0); } @@ -996,121 +994,125 @@ accept_connection (void *cls) * @param sl service entry for the service in question */ static void -create_listen_socket (struct sockaddr *sa, - socklen_t addr_len, - struct ServiceList *sl) +create_listen_socket(struct sockaddr *sa, + socklen_t addr_len, + struct ServiceList *sl) { static int on = 1; struct GNUNET_NETWORK_Handle *sock; struct ServiceListeningInfo *sli; + #ifndef WINDOWS int match_uid; int match_gid; #endif switch (sa->sa_family) - { - case AF_INET: - sock = GNUNET_NETWORK_socket_create (PF_INET, SOCK_STREAM, 0); - break; - case AF_INET6: - sock = GNUNET_NETWORK_socket_create (PF_INET6, SOCK_STREAM, 0); - break; - case AF_UNIX: - if (0 == strcmp (GNUNET_a2s (sa, addr_len), - "@")) /* Do not bind to blank UNIX path! */ - return; - sock = GNUNET_NETWORK_socket_create (PF_UNIX, SOCK_STREAM, 0); - break; - default: - GNUNET_break (0); - sock = NULL; - errno = EAFNOSUPPORT; - break; - } + { + case AF_INET: + sock = GNUNET_NETWORK_socket_create(PF_INET, SOCK_STREAM, 0); + break; + + case AF_INET6: + sock = GNUNET_NETWORK_socket_create(PF_INET6, SOCK_STREAM, 0); + break; + + case AF_UNIX: + if (0 == strcmp(GNUNET_a2s(sa, addr_len), + "@")) /* Do not bind to blank UNIX path! */ + return; + sock = GNUNET_NETWORK_socket_create(PF_UNIX, SOCK_STREAM, 0); + break; + + default: + GNUNET_break(0); + sock = NULL; + errno = EAFNOSUPPORT; + break; + } if (NULL == sock) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to create socket for service `%s': %s\n"), - sl->name, - strerror (errno)); - GNUNET_free (sa); - return; - } - if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (sock, - SOL_SOCKET, - SO_REUSEADDR, - &on, - sizeof (on))) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "setsockopt"); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to create socket for service `%s': %s\n"), + sl->name, + strerror(errno)); + GNUNET_free(sa); + return; + } + if (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt(sock, + SOL_SOCKET, + SO_REUSEADDR, + &on, + sizeof(on))) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "setsockopt"); #ifdef IPV6_V6ONLY if ((sa->sa_family == AF_INET6) && - (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt (sock, - IPPROTO_IPV6, - IPV6_V6ONLY, - &on, - sizeof (on)))) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "setsockopt"); + (GNUNET_OK != GNUNET_NETWORK_socket_setsockopt(sock, + IPPROTO_IPV6, + IPV6_V6ONLY, + &on, + sizeof(on)))) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "setsockopt"); #endif #ifndef WINDOWS if (AF_UNIX == sa->sa_family) - GNUNET_NETWORK_unix_precheck ((struct sockaddr_un *) sa); + GNUNET_NETWORK_unix_precheck((struct sockaddr_un *)sa); #endif if (GNUNET_OK != - GNUNET_NETWORK_socket_bind (sock, (const struct sockaddr *) sa, addr_len)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_WARNING, - _ ( - "Unable to bind listening socket for service `%s' to address `%s': %s\n"), - sl->name, - GNUNET_a2s (sa, addr_len), - strerror (errno)); - GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock)); - GNUNET_free (sa); - return; - } + GNUNET_NETWORK_socket_bind(sock, (const struct sockaddr *)sa, addr_len)) + { + GNUNET_log( + GNUNET_ERROR_TYPE_WARNING, + _( + "Unable to bind listening socket for service `%s' to address `%s': %s\n"), + sl->name, + GNUNET_a2s(sa, addr_len), + strerror(errno)); + GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(sock)); + GNUNET_free(sa); + return; + } #ifndef WINDOWS if ((AF_UNIX == sa->sa_family) #ifdef LINUX /* Permission settings are not required when abstract sockets are used */ - && ('\0' != ((const struct sockaddr_un *) sa)->sun_path[0]) + && ('\0' != ((const struct sockaddr_un *)sa)->sun_path[0]) #endif - ) - { - match_uid = - GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name, "UNIX_MATCH_UID"); - match_gid = - GNUNET_CONFIGURATION_get_value_yesno (cfg, sl->name, "UNIX_MATCH_GID"); - GNUNET_DISK_fix_permissions (((const struct sockaddr_un *) sa)->sun_path, - match_uid, - match_gid); - } + ) + { + match_uid = + GNUNET_CONFIGURATION_get_value_yesno(cfg, sl->name, "UNIX_MATCH_UID"); + match_gid = + GNUNET_CONFIGURATION_get_value_yesno(cfg, sl->name, "UNIX_MATCH_GID"); + GNUNET_DISK_fix_permissions(((const struct sockaddr_un *)sa)->sun_path, + match_uid, + match_gid); + } #endif - if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5)) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen"); - GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock)); - GNUNET_free (sa); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("ARM now monitors connections to service `%s' at `%s'\n"), - sl->name, - GNUNET_a2s (sa, addr_len)); - sli = GNUNET_new (struct ServiceListeningInfo); + if (GNUNET_OK != GNUNET_NETWORK_socket_listen(sock, 5)) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "listen"); + GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(sock)); + GNUNET_free(sa); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("ARM now monitors connections to service `%s' at `%s'\n"), + sl->name, + GNUNET_a2s(sa, addr_len)); + sli = GNUNET_new(struct ServiceListeningInfo); sli->service_addr = sa; sli->service_addr_len = addr_len; sli->listen_socket = sock; sli->sl = sl; sli->accept_task = - GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - sock, - &accept_connection, - sli); - GNUNET_CONTAINER_DLL_insert (sl->listen_head, sl->listen_tail, sli); + GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + sock, + &accept_connection, + sli); + GNUNET_CONTAINER_DLL_insert(sl->listen_head, sl->listen_tail, sli); } @@ -1121,15 +1123,15 @@ create_listen_socket (struct sockaddr *sa, * @param sl entry to free */ static void -free_service (struct ServiceList *sl) +free_service(struct ServiceList *sl) { - GNUNET_assert (GNUNET_YES == in_shutdown); - GNUNET_CONTAINER_DLL_remove (running_head, running_tail, sl); - GNUNET_assert (NULL == sl->listen_head); - GNUNET_free_non_null (sl->config); - GNUNET_free_non_null (sl->binary); - GNUNET_free (sl->name); - GNUNET_free (sl); + GNUNET_assert(GNUNET_YES == in_shutdown); + GNUNET_CONTAINER_DLL_remove(running_head, running_tail, sl); + GNUNET_assert(NULL == sl->listen_head); + GNUNET_free_non_null(sl->config); + GNUNET_free_non_null(sl->binary); + GNUNET_free(sl->name); + GNUNET_free(sl); } @@ -1142,10 +1144,10 @@ free_service (struct ServiceList *sl) * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_start (void *cls, const struct GNUNET_ARM_Message *amsg) +check_start(void *cls, const struct GNUNET_ARM_Message *amsg) { - (void) cls; - GNUNET_MQ_check_zero_termination (amsg); + (void)cls; + GNUNET_MQ_check_zero_termination(amsg); return GNUNET_OK; } @@ -1157,43 +1159,43 @@ check_start (void *cls, const struct GNUNET_ARM_Message *amsg) * @param amsg the actual message */ static void -handle_start (void *cls, const struct GNUNET_ARM_Message *amsg) +handle_start(void *cls, const struct GNUNET_ARM_Message *amsg) { struct GNUNET_SERVICE_Client *client = cls; const char *servicename; struct ServiceList *sl; uint64_t request_id; - request_id = GNUNET_ntohll (amsg->request_id); - servicename = (const char *) &amsg[1]; - GNUNET_SERVICE_client_continue (client); + request_id = GNUNET_ntohll(amsg->request_id); + servicename = (const char *)&amsg[1]; + GNUNET_SERVICE_client_continue(client); if (GNUNET_YES == in_shutdown) - { - signal_result (client, - servicename, - request_id, - GNUNET_ARM_RESULT_IN_SHUTDOWN); - return; - } - sl = find_service (servicename); + { + signal_result(client, + servicename, + request_id, + GNUNET_ARM_RESULT_IN_SHUTDOWN); + return; + } + sl = find_service(servicename); if (NULL == sl) - { - signal_result (client, - servicename, - request_id, - GNUNET_ARM_RESULT_IS_NOT_KNOWN); - return; - } + { + signal_result(client, + servicename, + request_id, + GNUNET_ARM_RESULT_IS_NOT_KNOWN); + return; + } sl->force_start = GNUNET_YES; if (NULL != sl->proc) - { - signal_result (client, - servicename, - request_id, - GNUNET_ARM_RESULT_IS_STARTED_ALREADY); - return; - } - start_process (sl, client, request_id); + { + signal_result(client, + servicename, + request_id, + GNUNET_ARM_RESULT_IS_STARTED_ALREADY); + return; + } + start_process(sl, client, request_id); } @@ -1203,11 +1205,11 @@ handle_start (void *cls, const struct GNUNET_ARM_Message *amsg) * @param cls closure (refers to service) */ static void -trigger_shutdown (void *cls) +trigger_shutdown(void *cls) { - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Triggering shutdown\n"); - GNUNET_SCHEDULER_shutdown (); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Triggering shutdown\n"); + GNUNET_SCHEDULER_shutdown(); } @@ -1220,10 +1222,10 @@ trigger_shutdown (void *cls) * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_stop (void *cls, const struct GNUNET_ARM_Message *amsg) +check_stop(void *cls, const struct GNUNET_ARM_Message *amsg) { - (void) cls; - GNUNET_MQ_check_zero_termination (amsg); + (void)cls; + GNUNET_MQ_check_zero_termination(amsg); return GNUNET_OK; } @@ -1235,72 +1237,72 @@ check_stop (void *cls, const struct GNUNET_ARM_Message *amsg) * @param amsg the actual message */ static void -handle_stop (void *cls, const struct GNUNET_ARM_Message *amsg) +handle_stop(void *cls, const struct GNUNET_ARM_Message *amsg) { struct GNUNET_SERVICE_Client *client = cls; struct ServiceList *sl; const char *servicename; uint64_t request_id; - request_id = GNUNET_ntohll (amsg->request_id); - servicename = (const char *) &amsg[1]; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Preparing to stop `%s'\n"), - servicename); - GNUNET_SERVICE_client_continue (client); - if (0 == strcasecmp (servicename, "arm")) - { - broadcast_status (servicename, GNUNET_ARM_SERVICE_STOPPING, NULL); - signal_result (client, servicename, request_id, GNUNET_ARM_RESULT_STOPPING); - GNUNET_SERVICE_client_persist (client); - GNUNET_SCHEDULER_add_now (&trigger_shutdown, NULL); - return; - } - sl = find_service (servicename); + request_id = GNUNET_ntohll(amsg->request_id); + servicename = (const char *)&amsg[1]; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Preparing to stop `%s'\n"), + servicename); + GNUNET_SERVICE_client_continue(client); + if (0 == strcasecmp(servicename, "arm")) + { + broadcast_status(servicename, GNUNET_ARM_SERVICE_STOPPING, NULL); + signal_result(client, servicename, request_id, GNUNET_ARM_RESULT_STOPPING); + GNUNET_SERVICE_client_persist(client); + GNUNET_SCHEDULER_add_now(&trigger_shutdown, NULL); + return; + } + sl = find_service(servicename); if (NULL == sl) - { - signal_result (client, - servicename, - request_id, - GNUNET_ARM_RESULT_IS_NOT_KNOWN); - return; - } + { + signal_result(client, + servicename, + request_id, + GNUNET_ARM_RESULT_IS_NOT_KNOWN); + return; + } sl->force_start = GNUNET_NO; if (GNUNET_YES == in_shutdown) - { - /* shutdown in progress */ - signal_result (client, - servicename, - request_id, - GNUNET_ARM_RESULT_IN_SHUTDOWN); - return; - } + { + /* shutdown in progress */ + signal_result(client, + servicename, + request_id, + GNUNET_ARM_RESULT_IN_SHUTDOWN); + return; + } if (NULL != sl->killing_client) - { - /* killing already in progress */ - signal_result (client, - servicename, - request_id, - GNUNET_ARM_RESULT_IS_STOPPING_ALREADY); - return; - } + { + /* killing already in progress */ + signal_result(client, + servicename, + request_id, + GNUNET_ARM_RESULT_IS_STOPPING_ALREADY); + return; + } if (NULL == sl->proc) - { - /* process is down */ - signal_result (client, - servicename, - request_id, - GNUNET_ARM_RESULT_IS_STOPPED_ALREADY); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending kill signal to service `%s', waiting for process to die.\n", - servicename); - broadcast_status (servicename, GNUNET_ARM_SERVICE_STOPPING, NULL); + { + /* process is down */ + signal_result(client, + servicename, + request_id, + GNUNET_ARM_RESULT_IS_STOPPED_ALREADY); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending kill signal to service `%s', waiting for process to die.\n", + servicename); + broadcast_status(servicename, GNUNET_ARM_SERVICE_STOPPING, NULL); /* no signal_start - only when it's STOPPED */ - sl->killed_at = GNUNET_TIME_absolute_get (); - if (0 != GNUNET_OS_process_kill (sl->proc, GNUNET_TERM_SIG)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill"); + sl->killed_at = GNUNET_TIME_absolute_get(); + if (0 != GNUNET_OS_process_kill(sl->proc, GNUNET_TERM_SIG)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill"); sl->killing_client = client; sl->killing_client_request_id = request_id; } @@ -1313,7 +1315,7 @@ handle_stop (void *cls, const struct GNUNET_ARM_Message *amsg) * @param message the actual message */ static void -handle_list (void *cls, const struct GNUNET_ARM_Message *request) +handle_list(void *cls, const struct GNUNET_ARM_Message *request) { struct GNUNET_SERVICE_Client *client = cls; struct GNUNET_MQ_Envelope *env; @@ -1323,40 +1325,40 @@ handle_list (void *cls, const struct GNUNET_ARM_Message *request) uint16_t count; char *pos; - GNUNET_break (0 == ntohl (request->reserved)); + GNUNET_break(0 == ntohl(request->reserved)); count = 0; string_list_size = 0; /* first count the running processes get their name's size */ for (sl = running_head; NULL != sl; sl = sl->next) - { - if (NULL != sl->proc) { - string_list_size += strlen (sl->name); - string_list_size += strlen (sl->binary); - string_list_size += 4; - count++; + if (NULL != sl->proc) + { + string_list_size += strlen(sl->name); + string_list_size += strlen(sl->binary); + string_list_size += 4; + count++; + } } - } - env = GNUNET_MQ_msg_extra (msg, - string_list_size, - GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT); + env = GNUNET_MQ_msg_extra(msg, + string_list_size, + GNUNET_MESSAGE_TYPE_ARM_LIST_RESULT); msg->arm_msg.request_id = request->request_id; - msg->count = htons (count); + msg->count = htons(count); - pos = (char *) &msg[1]; + pos = (char *)&msg[1]; for (sl = running_head; NULL != sl; sl = sl->next) - { - if (NULL != sl->proc) { - size_t s = strlen (sl->name) + strlen (sl->binary) + 4; - GNUNET_snprintf (pos, s, "%s (%s)", sl->name, sl->binary); - pos += s; + if (NULL != sl->proc) + { + size_t s = strlen(sl->name) + strlen(sl->binary) + 4; + GNUNET_snprintf(pos, s, "%s (%s)", sl->name, sl->binary); + pos += s; + } } - } - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); - GNUNET_SERVICE_client_continue (client); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); + GNUNET_SERVICE_client_continue(client); } @@ -1367,16 +1369,16 @@ handle_list (void *cls, const struct GNUNET_ARM_Message *request) * @param message the actual message */ static void -handle_test (void *cls, const struct GNUNET_MessageHeader *message) +handle_test(void *cls, const struct GNUNET_MessageHeader *message) { struct GNUNET_SERVICE_Client *client = cls; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; - (void) message; - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_ARM_TEST); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); - GNUNET_SERVICE_client_continue (client); + (void)message; + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_ARM_TEST); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); + GNUNET_SERVICE_client_continue(client); } @@ -1385,24 +1387,24 @@ handle_test (void *cls, const struct GNUNET_MessageHeader *message) * tasks, signal handler and the server. */ static void -do_shutdown () +do_shutdown() { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Last shutdown phase\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Last shutdown phase\n"); if (NULL != notifier) - { - GNUNET_notification_context_destroy (notifier); - notifier = NULL; - } + { + GNUNET_notification_context_destroy(notifier); + notifier = NULL; + } if (NULL != service) - { - GNUNET_SERVICE_shutdown (service); - service = NULL; - } + { + GNUNET_SERVICE_shutdown(service); + service = NULL; + } if (NULL != child_death_task) - { - GNUNET_SCHEDULER_cancel (child_death_task); - child_death_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(child_death_task); + child_death_task = NULL; + } } @@ -1413,13 +1415,13 @@ do_shutdown () * @return number of active services found */ static unsigned int -list_count (struct ServiceList *running_head) +list_count(struct ServiceList *running_head) { struct ServiceList *i; unsigned int res; for (res = 0, i = running_head; NULL != i; i = i->next, res++) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s\n", i->name); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s\n", i->name); return res; } @@ -1430,61 +1432,61 @@ list_count (struct ServiceList *running_head) * @param cls closure, NULL if we need to self-restart */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { struct ServiceList *pos; struct ServiceList *nxt; struct ServiceListeningInfo *sli; - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "First shutdown phase\n"); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "First shutdown phase\n"); if (NULL != child_restart_task) - { - GNUNET_SCHEDULER_cancel (child_restart_task); - child_restart_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(child_restart_task); + child_restart_task = NULL; + } in_shutdown = GNUNET_YES; /* first, stop listening */ for (pos = running_head; NULL != pos; pos = pos->next) - { - while (NULL != (sli = pos->listen_head)) { - GNUNET_CONTAINER_DLL_remove (pos->listen_head, pos->listen_tail, sli); - if (NULL != sli->accept_task) - { - GNUNET_SCHEDULER_cancel (sli->accept_task); - sli->accept_task = NULL; - } - GNUNET_break (GNUNET_OK == - GNUNET_NETWORK_socket_close (sli->listen_socket)); - GNUNET_free (sli->service_addr); - GNUNET_free (sli); + while (NULL != (sli = pos->listen_head)) + { + GNUNET_CONTAINER_DLL_remove(pos->listen_head, pos->listen_tail, sli); + if (NULL != sli->accept_task) + { + GNUNET_SCHEDULER_cancel(sli->accept_task); + sli->accept_task = NULL; + } + GNUNET_break(GNUNET_OK == + GNUNET_NETWORK_socket_close(sli->listen_socket)); + GNUNET_free(sli->service_addr); + GNUNET_free(sli); + } } - } /* then, shutdown all existing service processes */ nxt = running_head; while (NULL != (pos = nxt)) - { - nxt = pos->next; - if (NULL != pos->proc) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Stopping service `%s'\n", pos->name); - pos->killed_at = GNUNET_TIME_absolute_get (); - if (0 != GNUNET_OS_process_kill (pos->proc, GNUNET_TERM_SIG)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill"); - } - else { - free_service (pos); + nxt = pos->next; + if (NULL != pos->proc) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Stopping service `%s'\n", pos->name); + pos->killed_at = GNUNET_TIME_absolute_get(); + if (0 != GNUNET_OS_process_kill(pos->proc, GNUNET_TERM_SIG)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill"); + } + else + { + free_service(pos); + } } - } /* finally, should all service processes be already gone, terminate for real */ if (NULL == running_head) - do_shutdown (); + do_shutdown(); else - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Delaying shutdown, have %u childs still running\n", - list_count (running_head)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Delaying shutdown, have %u childs still running\n", + list_count(running_head)); } @@ -1494,73 +1496,73 @@ shutdown_task (void *cls) * @param cls closure, always NULL */ static void -delayed_restart_task (void *cls) +delayed_restart_task(void *cls) { struct ServiceList *sl; struct GNUNET_TIME_Relative lowestRestartDelay; struct ServiceListeningInfo *sli; - (void) cls; + (void)cls; child_restart_task = NULL; - GNUNET_assert (GNUNET_NO == in_shutdown); + GNUNET_assert(GNUNET_NO == in_shutdown); lowestRestartDelay = GNUNET_TIME_UNIT_FOREVER_REL; /* check for services that need to be restarted due to * configuration changes or because the last restart failed */ for (sl = running_head; NULL != sl; sl = sl->next) - { - if (NULL != sl->proc) - continue; - /* service is currently not running */ - if (0 == GNUNET_TIME_absolute_get_remaining (sl->restart_at).rel_value_us) { - /* restart is now allowed */ - if (sl->force_start) - { - /* process should run by default, start immediately */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Restarting service `%s'.\n"), - sl->name); - start_process (sl, NULL, 0); - } + if (NULL != sl->proc) + continue; + /* service is currently not running */ + if (0 == GNUNET_TIME_absolute_get_remaining(sl->restart_at).rel_value_us) + { + /* restart is now allowed */ + if (sl->force_start) + { + /* process should run by default, start immediately */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Restarting service `%s'.\n"), + sl->name); + start_process(sl, NULL, 0); + } + else + { + /* process is run on-demand, ensure it is re-started if there is demand */ + for (sli = sl->listen_head; NULL != sli; sli = sli->next) + if (NULL == sli->accept_task) + { + /* accept was actually paused, so start it again */ + sli->accept_task = + GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + sli->listen_socket, + &accept_connection, + sli); + } + } + } else - { - /* process is run on-demand, ensure it is re-started if there is demand */ - for (sli = sl->listen_head; NULL != sli; sli = sli->next) - if (NULL == sli->accept_task) - { - /* accept was actually paused, so start it again */ - sli->accept_task = - GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - sli->listen_socket, - &accept_connection, - sli); - } - } - } - else - { - /* update calculation for earliest time to reactivate a service */ - lowestRestartDelay = - GNUNET_TIME_relative_min (lowestRestartDelay, - GNUNET_TIME_absolute_get_remaining ( - sl->restart_at)); + { + /* update calculation for earliest time to reactivate a service */ + lowestRestartDelay = + GNUNET_TIME_relative_min(lowestRestartDelay, + GNUNET_TIME_absolute_get_remaining( + sl->restart_at)); + } } - } if (lowestRestartDelay.rel_value_us != GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Will restart process in %s\n", - GNUNET_STRINGS_relative_time_to_string (lowestRestartDelay, + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Will restart process in %s\n", + GNUNET_STRINGS_relative_time_to_string(lowestRestartDelay, GNUNET_YES)); - child_restart_task = - GNUNET_SCHEDULER_add_delayed_with_priority (lowestRestartDelay, - GNUNET_SCHEDULER_PRIORITY_IDLE, - &delayed_restart_task, - NULL); - } + child_restart_task = + GNUNET_SCHEDULER_add_delayed_with_priority(lowestRestartDelay, + GNUNET_SCHEDULER_PRIORITY_IDLE, + &delayed_restart_task, + NULL); + } } @@ -1571,7 +1573,7 @@ delayed_restart_task (void *cls) * @param cls closure, NULL */ static void -maint_child_death (void *cls) +maint_child_death(void *cls) { struct ServiceList *pos; struct ServiceList *next; @@ -1584,199 +1586,199 @@ maint_child_death (void *cls) unsigned long statusCode; const struct GNUNET_DISK_FileHandle *pr; - (void) cls; - pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ); + (void)cls; + pr = GNUNET_DISK_pipe_handle(sigpipe, GNUNET_DISK_PIPE_END_READ); child_death_task = NULL; /* consume the signal */ - GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c))); + GNUNET_break(0 < GNUNET_DISK_file_read(pr, &c, sizeof(c))); /* check for services that died (WAITPID) */ next = running_head; while (NULL != (pos = next)) - { - next = pos->next; - - if (NULL == pos->proc) { - if (GNUNET_YES == in_shutdown) - free_service (pos); - continue; - } + next = pos->next; + + if (NULL == pos->proc) + { + if (GNUNET_YES == in_shutdown) + free_service(pos); + continue; + } #if HAVE_WAIT4 - if (NULL != wait_file) - { - /* need to use 'wait4()' to obtain and log performance data */ - struct rusage ru; - int status; - pid_t pid; - - pid = GNUNET_OS_process_get_pid (pos->proc); - ret = wait4 (pid, &status, WNOHANG, &ru); - if (ret <= 0) - continue; /* no process done */ - if (WIFEXITED (status)) - { - statusType = GNUNET_OS_PROCESS_EXITED; - statusCode = WEXITSTATUS (status); - } - else if (WIFSIGNALED (status)) - { - statusType = GNUNET_OS_PROCESS_SIGNALED; - statusCode = WTERMSIG (status); - } - else if (WIFSTOPPED (status)) - { - statusType = GNUNET_OS_PROCESS_SIGNALED; - statusCode = WSTOPSIG (status); - } + if (NULL != wait_file) + { + /* need to use 'wait4()' to obtain and log performance data */ + struct rusage ru; + int status; + pid_t pid; + + pid = GNUNET_OS_process_get_pid(pos->proc); + ret = wait4(pid, &status, WNOHANG, &ru); + if (ret <= 0) + continue; /* no process done */ + if (WIFEXITED(status)) + { + statusType = GNUNET_OS_PROCESS_EXITED; + statusCode = WEXITSTATUS(status); + } + else if (WIFSIGNALED(status)) + { + statusType = GNUNET_OS_PROCESS_SIGNALED; + statusCode = WTERMSIG(status); + } + else if (WIFSTOPPED(status)) + { + statusType = GNUNET_OS_PROCESS_SIGNALED; + statusCode = WSTOPSIG(status); + } #ifdef WIFCONTINUED - else if (WIFCONTINUED (status)) - { - statusType = GNUNET_OS_PROCESS_RUNNING; - statusCode = 0; - } + else if (WIFCONTINUED(status)) + { + statusType = GNUNET_OS_PROCESS_RUNNING; + statusCode = 0; + } #endif - else - { - statusType = GNUNET_OS_PROCESS_UNKNOWN; - statusCode = 0; - } - if ((GNUNET_OS_PROCESS_EXITED == statusType) || - (GNUNET_OS_PROCESS_SIGNALED == statusType)) - { - double utime = ru.ru_utime.tv_sec + (ru.ru_utime.tv_usec / 10e6); - double stime = ru.ru_stime.tv_sec + (ru.ru_stime.tv_usec / 10e6); - fprintf (wait_file, - "%s(%u) %.3f %.3f %llu %llu %llu %llu %llu\n", - pos->binary, - (unsigned int) pid, - utime, - stime, - (unsigned long long) ru.ru_maxrss, - (unsigned long long) ru.ru_inblock, - (unsigned long long) ru.ru_oublock, - (unsigned long long) ru.ru_nvcsw, - (unsigned long long) ru.ru_nivcsw); - } - } - else /* continue with JUST this "if" as "else" (intentionally no brackets!) */ + else + { + statusType = GNUNET_OS_PROCESS_UNKNOWN; + statusCode = 0; + } + if ((GNUNET_OS_PROCESS_EXITED == statusType) || + (GNUNET_OS_PROCESS_SIGNALED == statusType)) + { + double utime = ru.ru_utime.tv_sec + (ru.ru_utime.tv_usec / 10e6); + double stime = ru.ru_stime.tv_sec + (ru.ru_stime.tv_usec / 10e6); + fprintf(wait_file, + "%s(%u) %.3f %.3f %llu %llu %llu %llu %llu\n", + pos->binary, + (unsigned int)pid, + utime, + stime, + (unsigned long long)ru.ru_maxrss, + (unsigned long long)ru.ru_inblock, + (unsigned long long)ru.ru_oublock, + (unsigned long long)ru.ru_nvcsw, + (unsigned long long)ru.ru_nivcsw); + } + } + else /* continue with JUST this "if" as "else" (intentionally no brackets!) */ #endif - if ((GNUNET_SYSERR == (ret = GNUNET_OS_process_status (pos->proc, - &statusType, - &statusCode))) || + if ((GNUNET_SYSERR == (ret = GNUNET_OS_process_status(pos->proc, + &statusType, + &statusCode))) || (ret == GNUNET_NO) || (statusType == GNUNET_OS_PROCESS_STOPPED) || (statusType == GNUNET_OS_PROCESS_UNKNOWN) || (statusType == GNUNET_OS_PROCESS_RUNNING)) - continue; + continue; - if (statusType == GNUNET_OS_PROCESS_EXITED) - { - statstr = _ (/* process termination method */ "exit"); - statcode = statusCode; - } - else if (statusType == GNUNET_OS_PROCESS_SIGNALED) - { - statstr = _ (/* process termination method */ "signal"); - statcode = statusCode; - } - else - { - statstr = _ (/* process termination method */ "unknown"); - statcode = 0; - } - if (0 != pos->killed_at.abs_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Service `%s' took %s to terminate\n"), - pos->name, - GNUNET_STRINGS_relative_time_to_string ( - GNUNET_TIME_absolute_get_duration (pos->killed_at), - GNUNET_YES)); - } - GNUNET_OS_process_destroy (pos->proc); - pos->proc = NULL; - broadcast_status (pos->name, GNUNET_ARM_SERVICE_STOPPED, NULL); - if (NULL != pos->killing_client) - { - signal_result (pos->killing_client, - pos->name, - pos->killing_client_request_id, - GNUNET_ARM_RESULT_STOPPED); - pos->killing_client = NULL; - pos->killing_client_request_id = 0; - } - if (GNUNET_YES != in_shutdown) - { - if ((statusType == GNUNET_OS_PROCESS_EXITED) && (statcode == 0)) - { - /* process terminated normally, allow restart at any time */ - pos->restart_at.abs_value_us = 0; - GNUNET_log ( - GNUNET_ERROR_TYPE_INFO, - _ ("Service `%s' terminated normally, will restart at any time\n"), - pos->name); - /* process can still be re-started on-demand, ensure it is re-started if there is demand */ - for (sli = pos->listen_head; NULL != sli; sli = sli->next) + if (statusType == GNUNET_OS_PROCESS_EXITED) { - GNUNET_break (NULL == sli->accept_task); - sli->accept_task = - GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - sli->listen_socket, - &accept_connection, - sli); + statstr = _(/* process termination method */ "exit"); + statcode = statusCode; + } + else if (statusType == GNUNET_OS_PROCESS_SIGNALED) + { + statstr = _(/* process termination method */ "signal"); + statcode = statusCode; } - } else - { - GNUNET_log ( - GNUNET_ERROR_TYPE_INFO, - _ ("Service `%s' terminated with status %s/%d, will restart in %s\n"), - pos->name, - statstr, - statcode, - GNUNET_STRINGS_relative_time_to_string (pos->backoff, GNUNET_YES)); { - /* Reduce backoff based on runtime of the process, - so that there is a cool-down if a process actually - runs for a while. */ - struct GNUNET_TIME_Relative runtime; - unsigned int minutes; - - runtime = GNUNET_TIME_absolute_get_duration (pos->restart_at); - minutes = - runtime.rel_value_us / GNUNET_TIME_UNIT_MINUTES.rel_value_us; - if (minutes > 31) - pos->backoff = GNUNET_TIME_UNIT_ZERO; + statstr = _(/* process termination method */ "unknown"); + statcode = 0; + } + if (0 != pos->killed_at.abs_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Service `%s' took %s to terminate\n"), + pos->name, + GNUNET_STRINGS_relative_time_to_string( + GNUNET_TIME_absolute_get_duration(pos->killed_at), + GNUNET_YES)); + } + GNUNET_OS_process_destroy(pos->proc); + pos->proc = NULL; + broadcast_status(pos->name, GNUNET_ARM_SERVICE_STOPPED, NULL); + if (NULL != pos->killing_client) + { + signal_result(pos->killing_client, + pos->name, + pos->killing_client_request_id, + GNUNET_ARM_RESULT_STOPPED); + pos->killing_client = NULL; + pos->killing_client_request_id = 0; + } + if (GNUNET_YES != in_shutdown) + { + if ((statusType == GNUNET_OS_PROCESS_EXITED) && (statcode == 0)) + { + /* process terminated normally, allow restart at any time */ + pos->restart_at.abs_value_us = 0; + GNUNET_log( + GNUNET_ERROR_TYPE_INFO, + _("Service `%s' terminated normally, will restart at any time\n"), + pos->name); + /* process can still be re-started on-demand, ensure it is re-started if there is demand */ + for (sli = pos->listen_head; NULL != sli; sli = sli->next) + { + GNUNET_break(NULL == sli->accept_task); + sli->accept_task = + GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + sli->listen_socket, + &accept_connection, + sli); + } + } else - pos->backoff.rel_value_us <<= minutes; + { + GNUNET_log( + GNUNET_ERROR_TYPE_INFO, + _("Service `%s' terminated with status %s/%d, will restart in %s\n"), + pos->name, + statstr, + statcode, + GNUNET_STRINGS_relative_time_to_string(pos->backoff, GNUNET_YES)); + { + /* Reduce backoff based on runtime of the process, + so that there is a cool-down if a process actually + runs for a while. */ + struct GNUNET_TIME_Relative runtime; + unsigned int minutes; + + runtime = GNUNET_TIME_absolute_get_duration(pos->restart_at); + minutes = + runtime.rel_value_us / GNUNET_TIME_UNIT_MINUTES.rel_value_us; + if (minutes > 31) + pos->backoff = GNUNET_TIME_UNIT_ZERO; + else + pos->backoff.rel_value_us <<= minutes; + } + /* schedule restart */ + pos->restart_at = GNUNET_TIME_relative_to_absolute(pos->backoff); + pos->backoff = GNUNET_TIME_STD_BACKOFF(pos->backoff); + if (NULL != child_restart_task) + GNUNET_SCHEDULER_cancel(child_restart_task); + child_restart_task = + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_IDLE, + &delayed_restart_task, + NULL); + } + } + else + { + free_service(pos); } - /* schedule restart */ - pos->restart_at = GNUNET_TIME_relative_to_absolute (pos->backoff); - pos->backoff = GNUNET_TIME_STD_BACKOFF (pos->backoff); - if (NULL != child_restart_task) - GNUNET_SCHEDULER_cancel (child_restart_task); - child_restart_task = - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE, - &delayed_restart_task, - NULL); - } - } - else - { - free_service (pos); } - } child_death_task = - GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, - pr, - &maint_child_death, - NULL); + GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL, + pr, + &maint_child_death, + NULL); if ((NULL == running_head) && (GNUNET_YES == in_shutdown)) - do_shutdown (); + do_shutdown(); else if (GNUNET_YES == in_shutdown) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Delaying shutdown after child's death, still have %u children\n", - list_count (running_head)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Delaying shutdown after child's death, still have %u children\n", + list_count(running_head)); } @@ -1785,17 +1787,17 @@ maint_child_death (void *cls) * respective handler by writing to the trigger pipe. */ static void -sighandler_child_death () +sighandler_child_death() { static char c; int old_errno = errno; /* back-up errno */ - GNUNET_break ( + GNUNET_break( 1 == - GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle (sigpipe, - GNUNET_DISK_PIPE_END_WRITE), - &c, - sizeof (c))); + GNUNET_DISK_file_write(GNUNET_DISK_pipe_handle(sigpipe, + GNUNET_DISK_PIPE_END_WRITE), + &c, + sizeof(c))); errno = old_errno; /* restore errno */ } @@ -1809,7 +1811,7 @@ sighandler_child_death () * @return #GNUNET_OK (continue) */ static void -setup_service (void *cls, const char *section) +setup_service(void *cls, const char *section) { struct ServiceList *sl; char *binary; @@ -1819,65 +1821,65 @@ setup_service (void *cls, const char *section) socklen_t *addr_lens; int ret; - (void) cls; - if (0 == strcasecmp (section, "arm")) + (void)cls; + if (0 == strcasecmp(section, "arm")) return; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, section, "BINARY", &binary)) - { - /* not a service section */ - return; - } + GNUNET_CONFIGURATION_get_value_string(cfg, section, "BINARY", &binary)) + { + /* not a service section */ + return; + } if ((GNUNET_YES == - GNUNET_CONFIGURATION_have_value (cfg, section, "RUN_PER_USER")) && + GNUNET_CONFIGURATION_have_value(cfg, section, "RUN_PER_USER")) && (GNUNET_YES == - GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "RUN_PER_USER"))) - { - if (GNUNET_NO == start_user) + GNUNET_CONFIGURATION_get_value_yesno(cfg, section, "RUN_PER_USER"))) { - GNUNET_free (binary); - return; /* user service, and we don't deal with those */ + if (GNUNET_NO == start_user) + { + GNUNET_free(binary); + return; /* user service, and we don't deal with those */ + } } - } else - { - if (GNUNET_NO == start_system) { - GNUNET_free (binary); - return; /* system service, and we don't deal with those */ + if (GNUNET_NO == start_system) + { + GNUNET_free(binary); + return; /* system service, and we don't deal with those */ + } } - } - sl = find_service (section); + sl = find_service(section); if (NULL != sl) - { - /* got the same section twice!? */ - GNUNET_break (0); - GNUNET_free (binary); - return; - } + { + /* got the same section twice!? */ + GNUNET_break(0); + GNUNET_free(binary); + return; + } config = NULL; - if (((GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, - section, - "CONFIG", - &config)) && - (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, - "PATHS", - "DEFAULTCONFIG", - &config))) || - (0 != stat (config, &sbuf))) - { - if (NULL != config) + if (((GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(cfg, + section, + "CONFIG", + &config)) && + (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(cfg, + "PATHS", + "DEFAULTCONFIG", + &config))) || + (0 != stat(config, &sbuf))) { - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING, - section, - "CONFIG", - strerror (errno)); - GNUNET_free (config); - config = NULL; + if (NULL != config) + { + GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_WARNING, + section, + "CONFIG", + strerror(errno)); + GNUNET_free(config); + config = NULL; + } } - } - sl = GNUNET_new (struct ServiceList); - sl->name = GNUNET_strdup (section); + sl = GNUNET_new(struct ServiceList); + sl->name = GNUNET_strdup(section); sl->binary = binary; sl->config = config; sl->backoff = GNUNET_TIME_UNIT_MILLISECONDS; @@ -1885,32 +1887,32 @@ setup_service (void *cls, const char *section) #if WINDOWS sl->pipe_control = GNUNET_YES; #else - if (GNUNET_CONFIGURATION_have_value (cfg, section, "PIPECONTROL")) + if (GNUNET_CONFIGURATION_have_value(cfg, section, "PIPECONTROL")) sl->pipe_control = - GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "PIPECONTROL"); + GNUNET_CONFIGURATION_get_value_yesno(cfg, section, "PIPECONTROL"); #endif - GNUNET_CONTAINER_DLL_insert (running_head, running_tail, sl); + GNUNET_CONTAINER_DLL_insert(running_head, running_tail, sl); if (GNUNET_YES == - GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "IMMEDIATE_START")) - { - sl->force_start = GNUNET_YES; - if (GNUNET_YES == - GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "NOARMBIND")) - return; - } + GNUNET_CONFIGURATION_get_value_yesno(cfg, section, "IMMEDIATE_START")) + { + sl->force_start = GNUNET_YES; + if (GNUNET_YES == + GNUNET_CONFIGURATION_get_value_yesno(cfg, section, "NOARMBIND")) + return; + } else - { - if (GNUNET_YES != - GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "START_ON_DEMAND")) - return; - } - if (0 >= (ret = get_server_addresses (section, cfg, &addrs, &addr_lens))) + { + if (GNUNET_YES != + GNUNET_CONFIGURATION_get_value_yesno(cfg, section, "START_ON_DEMAND")) + return; + } + if (0 >= (ret = get_server_addresses(section, cfg, &addrs, &addr_lens))) return; /* this will free (or capture) addrs[i] */ - for (unsigned int i = 0; i < (unsigned int) ret; i++) - create_listen_socket (addrs[i], addr_lens[i], sl); - GNUNET_free (addrs); - GNUNET_free (addr_lens); + for (unsigned int i = 0; i < (unsigned int)ret; i++) + create_listen_socket(addrs[i], addr_lens[i], sl); + GNUNET_free(addrs); + GNUNET_free(addr_lens); } @@ -1923,16 +1925,16 @@ setup_service (void *cls, const char *section) * @return @a client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { /* All clients are considered to be of the "monitor" kind * (that is, they don't affect ARM shutdown). */ - (void) cls; - (void) mq; - GNUNET_SERVICE_client_mark_monitor (client); + (void)cls; + (void)mq; + GNUNET_SERVICE_client_mark_monitor(client); return client; } @@ -1945,12 +1947,12 @@ client_connect_cb (void *cls, * @param app_ctx must match @a client */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { - (void) cls; - GNUNET_assert (client == app_ctx); + (void)cls; + GNUNET_assert(client == app_ctx); for (struct ServiceList *sl = running_head; NULL != sl; sl = sl->next) if (sl->killing_client == client) sl->killing_client = NULL; @@ -1966,18 +1968,18 @@ client_disconnect_cb (void *cls, * #GNUNET_SYSERR to close it (signal serious error) */ static void -handle_monitor (void *cls, const struct GNUNET_MessageHeader *message) +handle_monitor(void *cls, const struct GNUNET_MessageHeader *message) { struct GNUNET_SERVICE_Client *client = cls; - (void) message; + (void)message; /* FIXME: might want to start by letting monitor know about services that are already running */ /* Removal is handled by the server implementation, internally. */ - GNUNET_notification_context_add (notifier, - GNUNET_SERVICE_client_get_mq (client)); - broadcast_status ("arm", GNUNET_ARM_SERVICE_MONITORING_STARTED, client); - GNUNET_SERVICE_client_continue (client); + GNUNET_notification_context_add(notifier, + GNUNET_SERVICE_client_get_mq(client)); + broadcast_status("arm", GNUNET_ARM_SERVICE_MONITORING_STARTED, client); + GNUNET_SERVICE_client_continue(client); } @@ -1989,71 +1991,71 @@ handle_monitor (void *cls, const struct GNUNET_MessageHeader *message) * @param c configuration to use */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *serv) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *serv) { struct ServiceList *sl; - (void) cls; + (void)cls; cfg = c; service = serv; - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); - child_death_task = GNUNET_SCHEDULER_add_read_file ( + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); + child_death_task = GNUNET_SCHEDULER_add_read_file( GNUNET_TIME_UNIT_FOREVER_REL, - GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ), + GNUNET_DISK_pipe_handle(sigpipe, GNUNET_DISK_PIPE_END_READ), &maint_child_death, NULL); #if HAVE_WAIT4 if (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_filename (cfg, - "ARM", - "RESOURCE_DIAGNOSTICS", - &wait_filename)) - { - wait_file = fopen (wait_filename, "w"); - if (NULL == wait_file) + GNUNET_CONFIGURATION_get_value_filename(cfg, + "ARM", + "RESOURCE_DIAGNOSTICS", + &wait_filename)) { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, - "fopen", - wait_filename); + wait_file = fopen(wait_filename, "w"); + if (NULL == wait_file) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, + "fopen", + wait_filename); + } } - } #endif - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "ARM", - "GLOBAL_PREFIX", - &prefix_command)) - prefix_command = GNUNET_strdup (""); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "ARM", + "GLOBAL_PREFIX", + &prefix_command)) + prefix_command = GNUNET_strdup(""); else - prefix_command = GNUNET_CONFIGURATION_expand_dollar (cfg, prefix_command); - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "ARM", - "GLOBAL_POSTFIX", - &final_option)) - final_option = GNUNET_strdup (""); + prefix_command = GNUNET_CONFIGURATION_expand_dollar(cfg, prefix_command); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "ARM", + "GLOBAL_POSTFIX", + &final_option)) + final_option = GNUNET_strdup(""); else - final_option = GNUNET_CONFIGURATION_expand_dollar (cfg, final_option); + final_option = GNUNET_CONFIGURATION_expand_dollar(cfg, final_option); start_user = - GNUNET_CONFIGURATION_get_value_yesno (cfg, "ARM", "START_USER_SERVICES"); + GNUNET_CONFIGURATION_get_value_yesno(cfg, "ARM", "START_USER_SERVICES"); start_system = - GNUNET_CONFIGURATION_get_value_yesno (cfg, "ARM", "START_SYSTEM_SERVICES"); + GNUNET_CONFIGURATION_get_value_yesno(cfg, "ARM", "START_SYSTEM_SERVICES"); if ((GNUNET_NO == start_user) && (GNUNET_NO == start_system)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_ERROR, - "Please configure either START_USER_SERVICES or START_SYSTEM_SERVICES or both.\n"); - GNUNET_SCHEDULER_shutdown (); - global_ret = 1; - return; - } - GNUNET_CONFIGURATION_iterate_sections (cfg, &setup_service, NULL); + { + GNUNET_log( + GNUNET_ERROR_TYPE_ERROR, + "Please configure either START_USER_SERVICES or START_SYSTEM_SERVICES or both.\n"); + GNUNET_SCHEDULER_shutdown(); + global_ret = 1; + return; + } + GNUNET_CONFIGURATION_iterate_sections(cfg, &setup_service, NULL); /* start default services... */ for (sl = running_head; NULL != sl; sl = sl->next) if (GNUNET_YES == sl->force_start) - start_process (sl, NULL, 0); - notifier = GNUNET_notification_context_create (MAX_NOTIFY_QUEUE); + start_process(sl, NULL, 0); + notifier = GNUNET_notification_context_create(MAX_NOTIFY_QUEUE); } @@ -2065,61 +2067,61 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_SIGNAL_Context *shc_chld; struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_var_size (start, - GNUNET_MESSAGE_TYPE_ARM_START, - struct GNUNET_ARM_Message, + { GNUNET_MQ_hd_var_size(start, + GNUNET_MESSAGE_TYPE_ARM_START, + struct GNUNET_ARM_Message, + NULL), + GNUNET_MQ_hd_var_size(stop, + GNUNET_MESSAGE_TYPE_ARM_STOP, + struct GNUNET_ARM_Message, + NULL), + GNUNET_MQ_hd_fixed_size(monitor, + GNUNET_MESSAGE_TYPE_ARM_MONITOR, + struct GNUNET_MessageHeader, NULL), - GNUNET_MQ_hd_var_size (stop, - GNUNET_MESSAGE_TYPE_ARM_STOP, + GNUNET_MQ_hd_fixed_size(list, + GNUNET_MESSAGE_TYPE_ARM_LIST, struct GNUNET_ARM_Message, NULL), - GNUNET_MQ_hd_fixed_size (monitor, - GNUNET_MESSAGE_TYPE_ARM_MONITOR, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_hd_fixed_size (list, - GNUNET_MESSAGE_TYPE_ARM_LIST, - struct GNUNET_ARM_Message, - NULL), - GNUNET_MQ_hd_fixed_size (test, - GNUNET_MESSAGE_TYPE_ARM_TEST, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end ()}; - - sigpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO); - GNUNET_assert (NULL != sigpipe); + GNUNET_MQ_hd_fixed_size(test, + GNUNET_MESSAGE_TYPE_ARM_TEST, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end() }; + + sigpipe = GNUNET_DISK_pipe(GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO); + GNUNET_assert(NULL != sigpipe); shc_chld = - GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death); - if (0 != GNUNET_SERVICE_run_ (argc, - argv, - "arm", - GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - handlers)) + GNUNET_SIGNAL_handler_install(GNUNET_SIGCHLD, &sighandler_child_death); + if (0 != GNUNET_SERVICE_run_(argc, + argv, + "arm", + GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + handlers)) global_ret = 2; #if HAVE_WAIT4 if (NULL != wait_file) - { - fclose (wait_file); - wait_file = NULL; - } + { + fclose(wait_file); + wait_file = NULL; + } if (NULL != wait_filename) - { - GNUNET_free (wait_filename); - wait_filename = NULL; - } + { + GNUNET_free(wait_filename); + wait_filename = NULL; + } #endif - GNUNET_SIGNAL_handler_uninstall (shc_chld); + GNUNET_SIGNAL_handler_uninstall(shc_chld); shc_chld = NULL; - GNUNET_DISK_pipe_close (sigpipe); + GNUNET_DISK_pipe_close(sigpipe); sigpipe = NULL; return global_ret; } @@ -2131,11 +2133,11 @@ main (int argc, char *const *argv) /** * MINIMIZE heap size (way below 128k) since this process doesn't need much. */ -void __attribute__ ((constructor)) GNUNET_ARM_memory_init () +void __attribute__ ((constructor)) GNUNET_ARM_memory_init() { - mallopt (M_TRIM_THRESHOLD, 4 * 1024); - mallopt (M_TOP_PAD, 1 * 1024); - malloc_trim (0); + mallopt(M_TRIM_THRESHOLD, 4 * 1024); + mallopt(M_TOP_PAD, 1 * 1024); + malloc_trim(0); } #endif diff --git a/src/arm/mockup-service.c b/src/arm/mockup-service.c index 667556314..6134f17b3 100644 --- a/src/arm/mockup-service.c +++ b/src/arm/mockup-service.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ #include #include "platform.h" @@ -33,15 +33,15 @@ static int special_ret = 0; * @param message the actual message */ static void -handle_stop (void *cls, const struct GNUNET_MessageHeader *message) +handle_stop(void *cls, const struct GNUNET_MessageHeader *message) { struct GNUNET_SERVICE_Client *client = cls; - (void) message; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Initiating shutdown as requested by client.\n")); - GNUNET_SERVICE_client_persist (client); - GNUNET_SCHEDULER_shutdown (); + (void)message; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Initiating shutdown as requested by client.\n")); + GNUNET_SERVICE_client_persist(client); + GNUNET_SCHEDULER_shutdown(); /* ARM won't exponentially increase restart delay if we * terminate normally. This changes the return code. */ @@ -58,12 +58,12 @@ handle_stop (void *cls, const struct GNUNET_MessageHeader *message) * @return @a c */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + struct GNUNET_MQ_Handle *mq) { - (void) cls; - (void) mq; + (void)cls; + (void)mq; return c; } @@ -76,23 +76,23 @@ client_connect_cb (void *cls, * @param internal_cls should be equal to @a c */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - void *internal_cls) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + void *internal_cls) { - (void) cls; - GNUNET_assert (c == internal_cls); + (void)cls; + GNUNET_assert(c == internal_cls); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_SERVICE_Handle *service) { - (void) cls; - (void) cfg; - (void) service; + (void)cls; + (void)cfg; + (void)service; /* nothing to do */ } @@ -100,20 +100,23 @@ run (void *cls, /** * Define "main" method using service macro. */ -GNUNET_SERVICE_MAIN ("do-nothing", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_fixed_size (stop, - GNUNET_MESSAGE_TYPE_ARM_STOP, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end ()); +GNUNET_SERVICE_MAIN("do-nothing", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_fixed_size(stop, + GNUNET_MESSAGE_TYPE_ARM_STOP, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end()); /** * MINIMIZE heap size (way below 128k) since this process doesn't need much. */ -void __attribute__ ((destructor)) GNUNET_mockup_done () { _exit (special_ret); } +void __attribute__ ((destructor)) GNUNET_mockup_done() +{ + _exit(special_ret); +} diff --git a/src/arm/test_arm_api.c b/src/arm/test_arm_api.c index f851595b0..84d6f1bfd 100644 --- a/src/arm/test_arm_api.c +++ b/src/arm/test_arm_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file arm/test_arm_api.c * @brief testcase for arm_api.c @@ -26,9 +26,9 @@ #include "gnunet_arm_service.h" #include "gnunet_resolver_service.h" -#define LOG(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__) +#define LOG(...) GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__) -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15) static const struct GNUNET_CONFIGURATION_Handle *cfg; @@ -42,139 +42,139 @@ static int phase = 0; static void -arm_stop_cb (void *cls, - enum GNUNET_ARM_RequestStatus status, - enum GNUNET_ARM_Result result) +arm_stop_cb(void *cls, + enum GNUNET_ARM_RequestStatus status, + enum GNUNET_ARM_Result result) { op = NULL; /* (6), a stop request should be sent to ARM successfully */ /* ARM should report that it is stopping */ - GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK); - GNUNET_break (result == GNUNET_ARM_RESULT_STOPPED); - GNUNET_break (phase == 6); + GNUNET_break(status == GNUNET_ARM_REQUEST_SENT_OK); + GNUNET_break(result == GNUNET_ARM_RESULT_STOPPED); + GNUNET_break(phase == 6); phase++; - LOG ("Sent 'STOP' request for arm to ARM %s\n", - (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully"); - GNUNET_SCHEDULER_shutdown (); + LOG("Sent 'STOP' request for arm to ARM %s\n", + (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully"); + GNUNET_SCHEDULER_shutdown(); } static void -resolver_stop_cb (void *cls, - enum GNUNET_ARM_RequestStatus status, - enum GNUNET_ARM_Result result) +resolver_stop_cb(void *cls, + enum GNUNET_ARM_RequestStatus status, + enum GNUNET_ARM_Result result) { op = NULL; /* (5), a stop request should be sent to ARM successfully. * ARM should report that resolver is stopped. */ - GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK); - GNUNET_break (result == GNUNET_ARM_RESULT_STOPPED); - GNUNET_break (phase == 5); - LOG ("Sent 'STOP' request for resolver to ARM %s\n", - (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully"); + GNUNET_break(status == GNUNET_ARM_REQUEST_SENT_OK); + GNUNET_break(result == GNUNET_ARM_RESULT_STOPPED); + GNUNET_break(phase == 5); + LOG("Sent 'STOP' request for resolver to ARM %s\n", + (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully"); phase++; - GNUNET_assert (NULL == op); - op = GNUNET_ARM_request_service_stop (arm, - "arm", - &arm_stop_cb, - NULL); + GNUNET_assert(NULL == op); + op = GNUNET_ARM_request_service_stop(arm, + "arm", + &arm_stop_cb, + NULL); } static void -dns_notify (void *cls, - const struct sockaddr *addr, - socklen_t addrlen) +dns_notify(void *cls, + const struct sockaddr *addr, + socklen_t addrlen) { if (addr == NULL) { /* (4), resolver should finish resolving localhost */ - GNUNET_break (phase == 4); + GNUNET_break(phase == 4); phase++; - LOG ("Finished resolving localhost\n"); + LOG("Finished resolving localhost\n"); if (ok != 0) ok = 2; - GNUNET_assert (NULL == op); - op = GNUNET_ARM_request_service_stop (arm, - "resolver", - &resolver_stop_cb, - NULL); + GNUNET_assert(NULL == op); + op = GNUNET_ARM_request_service_stop(arm, + "resolver", + &resolver_stop_cb, + NULL); return; } /* (3), resolver should resolve localhost */ - GNUNET_break (phase == 3); - LOG ("Resolved localhost\n"); + GNUNET_break(phase == 3); + LOG("Resolved localhost\n"); phase++; - GNUNET_break (addr != NULL); + GNUNET_break(addr != NULL); ok = 0; } static void -resolver_start_cb (void *cls, - enum GNUNET_ARM_RequestStatus status, - enum GNUNET_ARM_Result result) +resolver_start_cb(void *cls, + enum GNUNET_ARM_RequestStatus status, + enum GNUNET_ARM_Result result) { op = NULL; /* (2), the start request for resolver should be sent successfully * ARM should report that resolver service is starting. */ - GNUNET_assert (status == GNUNET_ARM_REQUEST_SENT_OK); - GNUNET_break (phase == 2); - GNUNET_break (result == GNUNET_ARM_RESULT_STARTING); - LOG ("Sent 'START' request for resolver to ARM %s\n", - (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully"); + GNUNET_assert(status == GNUNET_ARM_REQUEST_SENT_OK); + GNUNET_break(phase == 2); + GNUNET_break(result == GNUNET_ARM_RESULT_STARTING); + LOG("Sent 'START' request for resolver to ARM %s\n", + (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully"); phase++; - GNUNET_RESOLVER_ip_get ("localhost", - AF_INET, - TIMEOUT, - &dns_notify, NULL); + GNUNET_RESOLVER_ip_get("localhost", + AF_INET, + TIMEOUT, + &dns_notify, NULL); } static void -arm_conn (void *cls, - int connected) +arm_conn(void *cls, + int connected) { if (GNUNET_SYSERR == connected) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Fatal error initializing ARM API.\n")); - GNUNET_SCHEDULER_shutdown (); - GNUNET_assert (0); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Fatal error initializing ARM API.\n")); + GNUNET_SCHEDULER_shutdown(); + GNUNET_assert(0); + return; + } if (GNUNET_YES == connected) - { - /* (1), arm connection should be established */ - LOG ("Connected to ARM\n"); - GNUNET_break (phase == 1); - phase++; - GNUNET_assert (NULL == op); - op = GNUNET_ARM_request_service_start (arm, - "resolver", - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - &resolver_start_cb, - NULL); - } + { + /* (1), arm connection should be established */ + LOG("Connected to ARM\n"); + GNUNET_break(phase == 1); + phase++; + GNUNET_assert(NULL == op); + op = GNUNET_ARM_request_service_start(arm, + "resolver", + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + &resolver_start_cb, + NULL); + } else - { - /* (7), ARM should stop (we disconnect from it) */ - LOG ("Disconnected from ARM\n"); - GNUNET_break (phase == 7); - if (phase != 7) - ok = 3; - else if (ok == 1) - ok = 0; - } + { + /* (7), ARM should stop (we disconnect from it) */ + LOG("Disconnected from ARM\n"); + GNUNET_break(phase == 7); + if (phase != 7) + ok = 3; + else if (ok == 1) + ok = 0; + } } static void -arm_start_cb (void *cls, - enum GNUNET_ARM_RequestStatus status, - enum GNUNET_ARM_Result result) +arm_start_cb(void *cls, + enum GNUNET_ARM_RequestStatus status, + enum GNUNET_ARM_Result result) { op = NULL; /* (0) The request should be "sent" successfully @@ -182,55 +182,55 @@ arm_start_cb (void *cls, * by itself). * ARM API should report that ARM service is starting. */ - GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK); - GNUNET_break (phase == 0); - LOG ("Sent 'START' request for arm to ARM %s\n", - (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully"); - GNUNET_break (result == GNUNET_ARM_RESULT_STARTING); + GNUNET_break(status == GNUNET_ARM_REQUEST_SENT_OK); + GNUNET_break(phase == 0); + LOG("Sent 'START' request for arm to ARM %s\n", + (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully"); + GNUNET_break(result == GNUNET_ARM_RESULT_STARTING); phase++; } static void -do_shutdown (void *cls) +do_shutdown(void *cls) { if (NULL != op) - { - GNUNET_ARM_operation_cancel (op); - op = NULL; - } + { + GNUNET_ARM_operation_cancel(op); + op = NULL; + } if (NULL != arm) - { - GNUNET_ARM_disconnect (arm); - arm = NULL; - } + { + GNUNET_ARM_disconnect(arm); + arm = NULL; + } } static void -task (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +task(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { cfg = c; - arm = GNUNET_ARM_connect (cfg, - &arm_conn, - NULL); + arm = GNUNET_ARM_connect(cfg, + &arm_conn, + NULL); if (NULL == arm) return; - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - op = GNUNET_ARM_request_service_start (arm, - "arm", - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - &arm_start_cb, - NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); + op = GNUNET_ARM_request_service_start(arm, + "arm", + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + &arm_start_cb, + NULL); } int -main (int argc, char *argvx[]) +main(int argc, char *argvx[]) { char *const argv[] = { "test-arm-api", @@ -240,13 +240,14 @@ main (int argc, char *argvx[]) struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; - GNUNET_log_setup ("test-arm-api", - "WARNING", - NULL); - GNUNET_assert (GNUNET_OK == - GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, - argv, "test-arm-api", "nohelp", options, - &task, NULL)); + + GNUNET_log_setup("test-arm-api", + "WARNING", + NULL); + GNUNET_assert(GNUNET_OK == + GNUNET_PROGRAM_run((sizeof(argv) / sizeof(char *)) - 1, + argv, "test-arm-api", "nohelp", options, + &task, NULL)); return ok; } diff --git a/src/arm/test_exponential_backoff.c b/src/arm/test_exponential_backoff.c index 43984f9bf..8190d29c2 100644 --- a/src/arm/test_exponential_backoff.c +++ b/src/arm/test_exponential_backoff.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file arm/test_exponential_backoff.c * @brief testcase for gnunet-service-arm.c @@ -27,15 +27,15 @@ #include "gnunet_util_lib.h" #include "gnunet_protocols.h" -#define LOG(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__) +#define LOG(...) GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__) #define LOG_BACKOFF GNUNET_NO -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) #define SERVICE_TEST_TIMEOUT GNUNET_TIME_UNIT_FOREVER_REL -#define FIVE_MILLISECONDS GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 5) +#define FIVE_MILLISECONDS GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 5) #define SERVICE "do-nothing" @@ -74,8 +74,7 @@ static char *killLogFileName; /** * Context for handling the shutdown of a service. */ -struct ShutdownContext -{ +struct ShutdownContext { /** * Connection to the service that is being shutdown. */ @@ -85,12 +84,11 @@ struct ShutdownContext * Task set up to cancel the shutdown request on timeout. */ struct GNUNET_SCHEDULER_Task *cancel_task; - }; static void -kill_task (void *cbData); +kill_task(void *cbData); /** @@ -99,9 +97,9 @@ kill_task (void *cbData); * @param cls closure */ static void -service_shutdown_timeout (void *cls) +service_shutdown_timeout(void *cls) { - GNUNET_assert (0); + GNUNET_assert(0); } @@ -114,196 +112,196 @@ service_shutdown_timeout (void *cls) * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct ShutdownContext *shutdown_ctx = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Service shutdown complete (MQ error).\n"); - GNUNET_SCHEDULER_cancel (shutdown_ctx->cancel_task); - GNUNET_MQ_destroy (shutdown_ctx->mq); - GNUNET_free (shutdown_ctx); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Service shutdown complete (MQ error).\n"); + GNUNET_SCHEDULER_cancel(shutdown_ctx->cancel_task); + GNUNET_MQ_destroy(shutdown_ctx->mq); + GNUNET_free(shutdown_ctx); } static void -kill_task (void *cbData) +kill_task(void *cbData) { struct ShutdownContext *shutdown_ctx - = GNUNET_new (struct ShutdownContext); + = GNUNET_new(struct ShutdownContext); struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_handler_end () + GNUNET_MQ_handler_end() }; kt = NULL; if (trialCount == 13) - { - LOG ("Saw enough kills, asking ARM to stop mock service for good\n"); - GNUNET_ARM_request_service_stop (arm, - SERVICE, - NULL, - NULL); - ok = 0; - trialCount++; - GNUNET_free (shutdown_ctx); - return; - } - shutdown_ctx->mq = GNUNET_CLIENT_connect (cfg, - SERVICE, - handlers, - &mq_error_handler, - shutdown_ctx); - GNUNET_assert (NULL != shutdown_ctx->mq); + { + LOG("Saw enough kills, asking ARM to stop mock service for good\n"); + GNUNET_ARM_request_service_stop(arm, + SERVICE, + NULL, + NULL); + ok = 0; + trialCount++; + GNUNET_free(shutdown_ctx); + return; + } + shutdown_ctx->mq = GNUNET_CLIENT_connect(cfg, + SERVICE, + handlers, + &mq_error_handler, + shutdown_ctx); + GNUNET_assert(NULL != shutdown_ctx->mq); trialCount++; - LOG ("Sending a shutdown request to the mock service\n"); - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_ARM_STOP); /* FIXME: abuse of message type */ - GNUNET_MQ_send (shutdown_ctx->mq, - env); + LOG("Sending a shutdown request to the mock service\n"); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_ARM_STOP); /* FIXME: abuse of message type */ + GNUNET_MQ_send(shutdown_ctx->mq, + env); shutdown_ctx->cancel_task - = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &service_shutdown_timeout, - shutdown_ctx); + = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &service_shutdown_timeout, + shutdown_ctx); } static void -trigger_disconnect (void *cls) +trigger_disconnect(void *cls) { - GNUNET_ARM_disconnect (arm); - GNUNET_ARM_monitor_stop (mon); + GNUNET_ARM_disconnect(arm); + GNUNET_ARM_monitor_stop(mon); if (NULL != kt) - { - GNUNET_SCHEDULER_cancel (kt); - kt = NULL; - } + { + GNUNET_SCHEDULER_cancel(kt); + kt = NULL; + } } static void -arm_stop_cb (void *cls, - enum GNUNET_ARM_RequestStatus status, - enum GNUNET_ARM_Result result) +arm_stop_cb(void *cls, + enum GNUNET_ARM_RequestStatus status, + enum GNUNET_ARM_Result result) { - GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK); - GNUNET_break (result == GNUNET_ARM_RESULT_STOPPED); - LOG ("ARM service stopped\n"); - GNUNET_SCHEDULER_shutdown (); + GNUNET_break(status == GNUNET_ARM_REQUEST_SENT_OK); + GNUNET_break(result == GNUNET_ARM_RESULT_STOPPED); + LOG("ARM service stopped\n"); + GNUNET_SCHEDULER_shutdown(); } static void -srv_status (void *cls, - const char *service, - enum GNUNET_ARM_ServiceStatus status) +srv_status(void *cls, + const char *service, + enum GNUNET_ARM_ServiceStatus status) { if (status == GNUNET_ARM_SERVICE_MONITORING_STARTED) - { - LOG ("ARM monitor started, starting mock service\n"); - phase++; - GNUNET_ARM_request_service_start (arm, - SERVICE, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - NULL, - NULL); - return; - } - if (0 != strcasecmp (service, SERVICE)) + { + LOG("ARM monitor started, starting mock service\n"); + phase++; + GNUNET_ARM_request_service_start(arm, + SERVICE, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + NULL, + NULL); + return; + } + if (0 != strcasecmp(service, SERVICE)) return; /* not what we care about */ if (phase == 1) - { - GNUNET_break (status == GNUNET_ARM_SERVICE_STARTING); - GNUNET_break (phase == 1); - LOG ("do-nothing is starting\n"); - phase++; - ok = 1; - GNUNET_assert (NULL == kt); - startedWaitingAt = GNUNET_TIME_absolute_get (); - kt = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &kill_task, - NULL); - } - else if (phase == 2) - { - /* We passively monitor ARM for status updates. ARM should tell us - * when do-nothing dies (no need to run a service upness test ourselves). - */ - if (status == GNUNET_ARM_SERVICE_STARTING) { - waitedFor = GNUNET_TIME_absolute_get_duration (startedWaitingAt); - LOG ("Waited for: %s\n", - GNUNET_STRINGS_relative_time_to_string (waitedFor, - GNUNET_YES)); - - LOG ("do-nothing is starting, killing it...\n"); - GNUNET_assert (NULL == kt); - kt = GNUNET_SCHEDULER_add_now (&kill_task, &ok); + GNUNET_break(status == GNUNET_ARM_SERVICE_STARTING); + GNUNET_break(phase == 1); + LOG("do-nothing is starting\n"); + phase++; + ok = 1; + GNUNET_assert(NULL == kt); + startedWaitingAt = GNUNET_TIME_absolute_get(); + kt = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &kill_task, + NULL); } - else if ((status == GNUNET_ARM_SERVICE_STOPPED) && (trialCount == 14)) + else if (phase == 2) { - phase++; - LOG ("do-nothing stopped working %u times, we are done here\n", - (unsigned int) trialCount); - GNUNET_ARM_request_service_stop (arm, - "arm", - &arm_stop_cb, - NULL); + /* We passively monitor ARM for status updates. ARM should tell us + * when do-nothing dies (no need to run a service upness test ourselves). + */ + if (status == GNUNET_ARM_SERVICE_STARTING) + { + waitedFor = GNUNET_TIME_absolute_get_duration(startedWaitingAt); + LOG("Waited for: %s\n", + GNUNET_STRINGS_relative_time_to_string(waitedFor, + GNUNET_YES)); + + LOG("do-nothing is starting, killing it...\n"); + GNUNET_assert(NULL == kt); + kt = GNUNET_SCHEDULER_add_now(&kill_task, &ok); + } + else if ((status == GNUNET_ARM_SERVICE_STOPPED) && (trialCount == 14)) + { + phase++; + LOG("do-nothing stopped working %u times, we are done here\n", + (unsigned int)trialCount); + GNUNET_ARM_request_service_stop(arm, + "arm", + &arm_stop_cb, + NULL); + } } - } } static void -arm_start_cb (void *cls, - enum GNUNET_ARM_RequestStatus status, - enum GNUNET_ARM_Result result) +arm_start_cb(void *cls, + enum GNUNET_ARM_RequestStatus status, + enum GNUNET_ARM_Result result) { - GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK); - GNUNET_break (result == GNUNET_ARM_RESULT_STARTING); - GNUNET_break (phase == 0); - LOG ("Sent 'START' request for arm to ARM %s\n", - (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully"); + GNUNET_break(status == GNUNET_ARM_REQUEST_SENT_OK); + GNUNET_break(result == GNUNET_ARM_RESULT_STARTING); + GNUNET_break(phase == 0); + LOG("Sent 'START' request for arm to ARM %s\n", + (status == GNUNET_ARM_REQUEST_SENT_OK) ? "successfully" : "unsuccessfully"); } static void -task (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +task(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { cfg = c; - arm = GNUNET_ARM_connect (cfg, NULL, NULL); + arm = GNUNET_ARM_connect(cfg, NULL, NULL); if (NULL == arm) - { - GNUNET_break (0); - return; - } - mon = GNUNET_ARM_monitor_start (cfg, - &srv_status, - NULL); - if (NULL == mon) - { - GNUNET_break (0); - GNUNET_ARM_disconnect (arm); - arm = NULL; - return; - } - GNUNET_ARM_request_service_start (arm, - "arm", - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - &arm_start_cb, - NULL); - GNUNET_SCHEDULER_add_shutdown (&trigger_disconnect, + { + GNUNET_break(0); + return; + } + mon = GNUNET_ARM_monitor_start(cfg, + &srv_status, NULL); + if (NULL == mon) + { + GNUNET_break(0); + GNUNET_ARM_disconnect(arm); + arm = NULL; + return; + } + GNUNET_ARM_request_service_start(arm, + "arm", + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + &arm_start_cb, + NULL); + GNUNET_SCHEDULER_add_shutdown(&trigger_disconnect, + NULL); } static int -check () +check() { char *const argv[] = { "test-exponential-backoff", @@ -315,14 +313,14 @@ check () }; /* Running ARM and running the do_nothing task */ - GNUNET_assert (GNUNET_OK == - GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, - argv, - "test-exponential-backoff", - "nohelp", - options, - &task, - NULL)); + GNUNET_assert(GNUNET_OK == + GNUNET_PROGRAM_run((sizeof(argv) / sizeof(char *)) - 1, + argv, + "test-exponential-backoff", + "nohelp", + options, + &task, + NULL)); return ok; } @@ -336,47 +334,47 @@ check () static int -init () +init() { struct GNUNET_CONFIGURATION_Handle *cfg; char pwd[PATH_MAX]; char *binary; - cfg = GNUNET_CONFIGURATION_create (); - if (GNUNET_OK != GNUNET_CONFIGURATION_parse (cfg, - "test_arm_api_data.conf")) - { - GNUNET_CONFIGURATION_destroy (cfg); - return GNUNET_SYSERR; - } - if (NULL == getcwd (pwd, PATH_MAX)) - return GNUNET_SYSERR; - GNUNET_assert (0 < GNUNET_asprintf (&binary, - "%s/%s", - pwd, - BINARY)); - GNUNET_CONFIGURATION_set_value_string (cfg, - SERVICE, - "BINARY", - binary); - GNUNET_free (binary); - if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, - CFGFILENAME)) - { - GNUNET_CONFIGURATION_destroy (cfg); + cfg = GNUNET_CONFIGURATION_create(); + if (GNUNET_OK != GNUNET_CONFIGURATION_parse(cfg, + "test_arm_api_data.conf")) + { + GNUNET_CONFIGURATION_destroy(cfg); + return GNUNET_SYSERR; + } + if (NULL == getcwd(pwd, PATH_MAX)) return GNUNET_SYSERR; - } - GNUNET_CONFIGURATION_destroy (cfg); + GNUNET_assert(0 < GNUNET_asprintf(&binary, + "%s/%s", + pwd, + BINARY)); + GNUNET_CONFIGURATION_set_value_string(cfg, + SERVICE, + "BINARY", + binary); + GNUNET_free(binary); + if (GNUNET_OK != GNUNET_CONFIGURATION_write(cfg, + CFGFILENAME)) + { + GNUNET_CONFIGURATION_destroy(cfg); + return GNUNET_SYSERR; + } + GNUNET_CONFIGURATION_destroy(cfg); #if LOG_BACKOFF - killLogFileName = GNUNET_DISK_mktemp ("exponential-backoff-waiting.log"); - if (NULL == (killLogFilePtr = fopen (killLogFileName, - "w"))) + killLogFileName = GNUNET_DISK_mktemp("exponential-backoff-waiting.log"); + if (NULL == (killLogFilePtr = fopen(killLogFileName, + "w"))) { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, - "fopen", - killLogFileName); - GNUNET_free (killLogFileName); + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, + "fopen", + killLogFileName); + GNUNET_free(killLogFileName); return GNUNET_SYSERR; } #endif @@ -385,29 +383,29 @@ init () static void -houseKeep () +houseKeep() { #if LOG_BACKOFF - GNUNET_assert (0 == fclose (killLogFilePtr)); - GNUNET_free (killLogFileName); + GNUNET_assert(0 == fclose(killLogFilePtr)); + GNUNET_free(killLogFileName); #endif - (void) unlink (CFGFILENAME); + (void)unlink(CFGFILENAME); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { int ret; - GNUNET_log_setup ("test-exponential-backoff", - "WARNING", - NULL); + GNUNET_log_setup("test-exponential-backoff", + "WARNING", + NULL); - if (GNUNET_OK != init ()) + if (GNUNET_OK != init()) return 1; - ret = check (); - houseKeep (); + ret = check(); + houseKeep(); return ret; } diff --git a/src/arm/test_gnunet_service_arm.c b/src/arm/test_gnunet_service_arm.c index 9508581de..8c8c664f9 100644 --- a/src/arm/test_gnunet_service_arm.c +++ b/src/arm/test_gnunet_service_arm.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file arm/test_gnunet_service_arm.c * @brief testcase for gnunet-service-arm.c; tests ARM by making it start the resolver @@ -34,9 +34,9 @@ * (by checking if running before starting, so really this time is always waited on * startup (annoying)). */ -#define START_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 50) +#define START_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 50) -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) static int ret = 1; @@ -51,141 +51,141 @@ static const char hostname[] = "www.gnu.org"; /* any domain should do */ static void -trigger_disconnect (void *cls) +trigger_disconnect(void *cls) { - GNUNET_ARM_disconnect (arm); + GNUNET_ARM_disconnect(arm); arm = NULL; } static void -arm_stop_cb (void *cls, - enum GNUNET_ARM_RequestStatus status, - enum GNUNET_ARM_Result result) +arm_stop_cb(void *cls, + enum GNUNET_ARM_RequestStatus status, + enum GNUNET_ARM_Result result) { - GNUNET_break (status == GNUNET_ARM_REQUEST_SENT_OK); - GNUNET_break (result == GNUNET_ARM_RESULT_STOPPED); + GNUNET_break(status == GNUNET_ARM_REQUEST_SENT_OK); + GNUNET_break(result == GNUNET_ARM_RESULT_STOPPED); if (result != GNUNET_ARM_RESULT_STOPPED) - { - GNUNET_break (0); - ret = 4; - } - GNUNET_SCHEDULER_add_now (&trigger_disconnect, NULL); + { + GNUNET_break(0); + ret = 4; + } + GNUNET_SCHEDULER_add_now(&trigger_disconnect, NULL); } static void -service_list (void *cls, - enum GNUNET_ARM_RequestStatus rs, - unsigned int count, - const char *const*list) +service_list(void *cls, + enum GNUNET_ARM_RequestStatus rs, + unsigned int count, + const char *const*list) { unsigned int i; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "%u services are are currently running\n", - count); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "%u services are are currently running\n", + count); if (GNUNET_ARM_REQUEST_SENT_OK != rs) goto stop_arm; - for (i=0;i. + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -28,29 +28,35 @@ #include "ats-testing.h" const char * -print_op (enum OperationType op) +print_op(enum OperationType op) { - switch (op) { + switch (op) + { case START_SEND: return "START_SEND"; + case STOP_SEND: return "STOP_SEND"; + case START_PREFERENCE: return "START_PREFERENCE"; + case STOP_PREFERENCE: return "STOP_PREFERENCE"; + default: break; - } + } return ""; } static struct Experiment * -create_experiment () +create_experiment() { struct Experiment *e; - e = GNUNET_new (struct Experiment); + + e = GNUNET_new(struct Experiment); e->name = NULL; e->num_masters = 0; e->num_slaves = 0; @@ -60,7 +66,7 @@ create_experiment () } static void -free_experiment (struct Experiment *e) +free_experiment(struct Experiment *e) { struct Episode *cur; struct Episode *next; @@ -69,28 +75,28 @@ free_experiment (struct Experiment *e) next = e->start; for (cur = next; NULL != cur; cur = next) - { - next = cur->next; - - next_o = cur->head; - for (cur_o = next_o; NULL != cur_o; cur_o = next_o) { - next_o = cur_o->next; - GNUNET_free (cur_o); + next = cur->next; + + next_o = cur->head; + for (cur_o = next_o; NULL != cur_o; cur_o = next_o) + { + next_o = cur_o->next; + GNUNET_free(cur_o); + } + GNUNET_free(cur); } - GNUNET_free (cur); - } - GNUNET_free_non_null (e->name); - GNUNET_free_non_null (e->cfg_file); - GNUNET_free (e); + GNUNET_free_non_null(e->name); + GNUNET_free_non_null(e->cfg_file); + GNUNET_free(e); } static int -load_episode (struct Experiment *e, - struct Episode *cur, - struct GNUNET_CONFIGURATION_Handle *cfg) +load_episode(struct Experiment *e, + struct Episode *cur, + struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_ATS_TEST_Operation *o; char *sec_name; @@ -100,272 +106,272 @@ load_episode (struct Experiment *e, char *pref; int op_counter = 0; - fprintf (stderr, "Parsing episode %u\n",cur->id); - GNUNET_asprintf (&sec_name, "episode-%u", cur->id); + fprintf(stderr, "Parsing episode %u\n", cur->id); + GNUNET_asprintf(&sec_name, "episode-%u", cur->id); while (1) - { - /* Load operation */ - GNUNET_asprintf (&op_name, "op-%u-operation", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, - sec_name, op_name, &op)) { - GNUNET_free (op_name); - break; - } - o = GNUNET_new (struct GNUNET_ATS_TEST_Operation); - /* operations = set_rate, start_send, stop_send, set_preference */ - if (0 == strcmp (op, "start_send")) - { - o->type = START_SEND; - } - else if (0 == strcmp (op, "stop_send")) - { - o->type = STOP_SEND; - } - else if (0 == strcmp (op, "start_preference")) - { - o->type = START_PREFERENCE; - } - else if (0 == strcmp (op, "stop_preference")) - { - o->type = STOP_PREFERENCE; - } - else - { - fprintf (stderr, "Invalid operation %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (o); - GNUNET_free (sec_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); - - /* Get source */ - GNUNET_asprintf(&op_name, "op-%u-src", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->src_id)) - { - fprintf (stderr, "Missing src in operation %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (o); - GNUNET_free (sec_name); - return GNUNET_SYSERR; - } - if (o->src_id > (e->num_masters - 1)) - { - fprintf (stderr, "Invalid src %llu in operation %u `%s' in episode %u\n", - o->src_id, op_counter, op, cur->id); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (o); - GNUNET_free (sec_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); - - /* Get destination */ - GNUNET_asprintf(&op_name, "op-%u-dest", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->dest_id)) - { - fprintf (stderr, "Missing src in operation %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (o); - GNUNET_free (sec_name); - return GNUNET_SYSERR; - } - if (o->dest_id > (e->num_slaves - 1)) - { - fprintf (stderr, "Invalid destination %llu in operation %u `%s' in episode %u\n", - o->dest_id, op_counter, op, cur->id); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (o); - GNUNET_free (sec_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); - - GNUNET_asprintf(&op_name, "op-%u-type", op_counter); - if ( (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_string(cfg, - sec_name, op_name, &type)) && - (STOP_SEND != o->type) && - (STOP_PREFERENCE != o->type) ) - { - /* Load arguments for set_rate, start_send, set_preference */ - if (0 == strcmp (type, "constant")) - { - o->gen_type = GNUNET_ATS_TEST_TG_CONSTANT; - } - else if (0 == strcmp (type, "linear")) - { - o->gen_type = GNUNET_ATS_TEST_TG_LINEAR; - } - else if (0 == strcmp (type, "sinus")) - { - o->gen_type = GNUNET_ATS_TEST_TG_SINUS; - } - else if (0 == strcmp (type, "random")) - { - o->gen_type = GNUNET_ATS_TEST_TG_RANDOM; - } + /* Load operation */ + GNUNET_asprintf(&op_name, "op-%u-operation", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &op)) + { + GNUNET_free(op_name); + break; + } + o = GNUNET_new(struct GNUNET_ATS_TEST_Operation); + /* operations = set_rate, start_send, stop_send, set_preference */ + if (0 == strcmp(op, "start_send")) + { + o->type = START_SEND; + } + else if (0 == strcmp(op, "stop_send")) + { + o->type = STOP_SEND; + } + else if (0 == strcmp(op, "start_preference")) + { + o->type = START_PREFERENCE; + } + else if (0 == strcmp(op, "stop_preference")) + { + o->type = STOP_PREFERENCE; + } else - { - fprintf (stderr, "Invalid type %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (type); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (sec_name); - GNUNET_free (o); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); - - /* Get base rate */ - GNUNET_asprintf(&op_name, "op-%u-base-rate", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->base_rate)) - { - fprintf (stderr, "Missing base rate in operation %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (type); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (sec_name); - GNUNET_free (o); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); - - /* Get max rate */ - GNUNET_asprintf(&op_name, "op-%u-max-rate", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->max_rate)) - { - if ((GNUNET_ATS_TEST_TG_LINEAR == o->gen_type) || - (GNUNET_ATS_TEST_TG_RANDOM == o->gen_type) || - (GNUNET_ATS_TEST_TG_SINUS == o->gen_type)) { - fprintf (stderr, "Missing max rate in operation %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (type); - GNUNET_free (op_name); - GNUNET_free (op); - GNUNET_free (o); - GNUNET_free (sec_name); + fprintf(stderr, "Invalid operation %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(o); + GNUNET_free(sec_name); return GNUNET_SYSERR; } - } - GNUNET_free (op_name); - - /* Get period */ - GNUNET_asprintf(&op_name, "op-%u-period", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (cfg, - sec_name, op_name, &o->period)) - { - o->period = cur->duration; - } - GNUNET_free (op_name); - - if (START_PREFERENCE == o->type) - { - /* Get frequency */ - GNUNET_asprintf(&op_name, "op-%u-frequency", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (cfg, - sec_name, op_name, &o->frequency)) - { - fprintf (stderr, "Missing frequency in operation %u `%s' in episode %u\n", + GNUNET_free(op_name); + + /* Get source */ + GNUNET_asprintf(&op_name, "op-%u-src", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->src_id)) + { + fprintf(stderr, "Missing src in operation %u `%s' in episode %u\n", op_counter, op, cur->id); - GNUNET_free (type); - GNUNET_free (op_name); - GNUNET_free (op); - GNUNET_free (o); - GNUNET_free (sec_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); - - /* Get preference */ - GNUNET_asprintf(&op_name, "op-%u-pref", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, - sec_name, op_name, &pref)) - { - fprintf (stderr, "Missing preference in operation %u `%s' in episode %u\n", + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(o); + GNUNET_free(sec_name); + return GNUNET_SYSERR; + } + if (o->src_id > (e->num_masters - 1)) + { + fprintf(stderr, "Invalid src %llu in operation %u `%s' in episode %u\n", + o->src_id, op_counter, op, cur->id); + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(o); + GNUNET_free(sec_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); + + /* Get destination */ + GNUNET_asprintf(&op_name, "op-%u-dest", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->dest_id)) + { + fprintf(stderr, "Missing src in operation %u `%s' in episode %u\n", op_counter, op, cur->id); - GNUNET_free (type); - GNUNET_free (op_name); - GNUNET_free (op); - GNUNET_free_non_null (pref); - GNUNET_free (o); - GNUNET_free (sec_name); - return GNUNET_SYSERR; - } + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(o); + GNUNET_free(sec_name); + return GNUNET_SYSERR; + } + if (o->dest_id > (e->num_slaves - 1)) + { + fprintf(stderr, "Invalid destination %llu in operation %u `%s' in episode %u\n", + o->dest_id, op_counter, op, cur->id); + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(o); + GNUNET_free(sec_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); - if (0 == strcmp(pref, "bandwidth")) - o->pref_type = GNUNET_ATS_PREFERENCE_BANDWIDTH; - else if (0 == strcmp(pref, "latency")) - o->pref_type = GNUNET_ATS_PREFERENCE_LATENCY; + GNUNET_asprintf(&op_name, "op-%u-type", op_counter); + if ((GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &type)) && + (STOP_SEND != o->type) && + (STOP_PREFERENCE != o->type)) + { + /* Load arguments for set_rate, start_send, set_preference */ + if (0 == strcmp(type, "constant")) + { + o->gen_type = GNUNET_ATS_TEST_TG_CONSTANT; + } + else if (0 == strcmp(type, "linear")) + { + o->gen_type = GNUNET_ATS_TEST_TG_LINEAR; + } + else if (0 == strcmp(type, "sinus")) + { + o->gen_type = GNUNET_ATS_TEST_TG_SINUS; + } + else if (0 == strcmp(type, "random")) + { + o->gen_type = GNUNET_ATS_TEST_TG_RANDOM; + } else - { - fprintf (stderr, "Invalid preference in operation %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (type); - GNUNET_free (op_name); - GNUNET_free (op); - GNUNET_free_non_null (pref); - GNUNET_free (o); - GNUNET_free (sec_name); + { + fprintf(stderr, "Invalid type %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(type); + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(sec_name); + GNUNET_free(o); return GNUNET_SYSERR; - } - GNUNET_free (pref); - GNUNET_free (op_name); - } - } + } + GNUNET_free(op_name); + + /* Get base rate */ + GNUNET_asprintf(&op_name, "op-%u-base-rate", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->base_rate)) + { + fprintf(stderr, "Missing base rate in operation %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(type); + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(sec_name); + GNUNET_free(o); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); + + /* Get max rate */ + GNUNET_asprintf(&op_name, "op-%u-max-rate", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->max_rate)) + { + if ((GNUNET_ATS_TEST_TG_LINEAR == o->gen_type) || + (GNUNET_ATS_TEST_TG_RANDOM == o->gen_type) || + (GNUNET_ATS_TEST_TG_SINUS == o->gen_type)) + { + fprintf(stderr, "Missing max rate in operation %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(type); + GNUNET_free(op_name); + GNUNET_free(op); + GNUNET_free(o); + GNUNET_free(sec_name); + return GNUNET_SYSERR; + } + } + GNUNET_free(op_name); + + /* Get period */ + GNUNET_asprintf(&op_name, "op-%u-period", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, + sec_name, op_name, &o->period)) + { + o->period = cur->duration; + } + GNUNET_free(op_name); + + if (START_PREFERENCE == o->type) + { + /* Get frequency */ + GNUNET_asprintf(&op_name, "op-%u-frequency", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, + sec_name, op_name, &o->frequency)) + { + fprintf(stderr, "Missing frequency in operation %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(type); + GNUNET_free(op_name); + GNUNET_free(op); + GNUNET_free(o); + GNUNET_free(sec_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); + + /* Get preference */ + GNUNET_asprintf(&op_name, "op-%u-pref", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &pref)) + { + fprintf(stderr, "Missing preference in operation %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(type); + GNUNET_free(op_name); + GNUNET_free(op); + GNUNET_free_non_null(pref); + GNUNET_free(o); + GNUNET_free(sec_name); + return GNUNET_SYSERR; + } + + if (0 == strcmp(pref, "bandwidth")) + o->pref_type = GNUNET_ATS_PREFERENCE_BANDWIDTH; + else if (0 == strcmp(pref, "latency")) + o->pref_type = GNUNET_ATS_PREFERENCE_LATENCY; + else + { + fprintf(stderr, "Invalid preference in operation %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(type); + GNUNET_free(op_name); + GNUNET_free(op); + GNUNET_free_non_null(pref); + GNUNET_free(o); + GNUNET_free(sec_name); + return GNUNET_SYSERR; + } + GNUNET_free(pref); + GNUNET_free(op_name); + } + } - /* Safety checks */ - if ((GNUNET_ATS_TEST_TG_LINEAR == o->gen_type) || - (GNUNET_ATS_TEST_TG_SINUS == o->gen_type)) - { - if ((o->max_rate - o->base_rate) > o->base_rate) - { - /* This will cause an underflow */ - GNUNET_break (0); - } - fprintf (stderr, "Selected max rate and base rate cannot be used for desired traffic form!\n"); - } + /* Safety checks */ + if ((GNUNET_ATS_TEST_TG_LINEAR == o->gen_type) || + (GNUNET_ATS_TEST_TG_SINUS == o->gen_type)) + { + if ((o->max_rate - o->base_rate) > o->base_rate) + { + /* This will cause an underflow */ + GNUNET_break(0); + } + fprintf(stderr, "Selected max rate and base rate cannot be used for desired traffic form!\n"); + } - if ((START_SEND == o->type) || (START_PREFERENCE == o->type)) - fprintf (stderr, "Found operation %u in episode %u: %s [%llu]->[%llu] == %s, %llu -> %llu in %s\n", - op_counter, cur->id, print_op (o->type), o->src_id, - o->dest_id, (NULL != type) ? type : "", - o->base_rate, o->max_rate, - GNUNET_STRINGS_relative_time_to_string (o->period, GNUNET_YES)); - else - fprintf (stderr, "Found operation %u in episode %u: %s [%llu]->[%llu]\n", - op_counter, cur->id, print_op (o->type), o->src_id, o->dest_id); + if ((START_SEND == o->type) || (START_PREFERENCE == o->type)) + fprintf(stderr, "Found operation %u in episode %u: %s [%llu]->[%llu] == %s, %llu -> %llu in %s\n", + op_counter, cur->id, print_op(o->type), o->src_id, + o->dest_id, (NULL != type) ? type : "", + o->base_rate, o->max_rate, + GNUNET_STRINGS_relative_time_to_string(o->period, GNUNET_YES)); + else + fprintf(stderr, "Found operation %u in episode %u: %s [%llu]->[%llu]\n", + op_counter, cur->id, print_op(o->type), o->src_id, o->dest_id); - GNUNET_free_non_null (type); - GNUNET_free (op); + GNUNET_free_non_null(type); + GNUNET_free(op); - GNUNET_CONTAINER_DLL_insert (cur->head,cur->tail, o); - op_counter++; - } - GNUNET_free (sec_name); + GNUNET_CONTAINER_DLL_insert(cur->head, cur->tail, o); + op_counter++; + } + GNUNET_free(sec_name); return GNUNET_OK; } static int -load_episodes (struct Experiment *e, struct GNUNET_CONFIGURATION_Handle *cfg) +load_episodes(struct Experiment *e, struct GNUNET_CONFIGURATION_Handle *cfg) { int e_counter = 0; char *sec_name; @@ -376,373 +382,380 @@ load_episodes (struct Experiment *e, struct GNUNET_CONFIGURATION_Handle *cfg) e_counter = 0; last = NULL; while (1) - { - GNUNET_asprintf(&sec_name, "episode-%u", e_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, - sec_name, "duration", &e_duration)) { - GNUNET_free (sec_name); - break; - } + GNUNET_asprintf(&sec_name, "episode-%u", e_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, + sec_name, "duration", &e_duration)) + { + GNUNET_free(sec_name); + break; + } - cur = GNUNET_new (struct Episode); - cur->duration = e_duration; - cur->id = e_counter; + cur = GNUNET_new(struct Episode); + cur->duration = e_duration; + cur->id = e_counter; - if (GNUNET_OK != load_episode (e, cur, cfg)) - { - GNUNET_free (sec_name); - GNUNET_free (cur); - return GNUNET_SYSERR; - } + if (GNUNET_OK != load_episode(e, cur, cfg)) + { + GNUNET_free(sec_name); + GNUNET_free(cur); + return GNUNET_SYSERR; + } - fprintf (stderr, "Found episode %u with duration %s \n", - e_counter, - GNUNET_STRINGS_relative_time_to_string(cur->duration, GNUNET_YES)); - - /* Update experiment */ - e->num_episodes ++; - e->total_duration = GNUNET_TIME_relative_add(e->total_duration, cur->duration); - /* Put in linked list */ - if (NULL == last) - e->start = cur; - else - last->next = cur; - - GNUNET_free (sec_name); - e_counter ++; - last = cur; - } + fprintf(stderr, "Found episode %u with duration %s \n", + e_counter, + GNUNET_STRINGS_relative_time_to_string(cur->duration, GNUNET_YES)); + + /* Update experiment */ + e->num_episodes++; + e->total_duration = GNUNET_TIME_relative_add(e->total_duration, cur->duration); + /* Put in linked list */ + if (NULL == last) + e->start = cur; + else + last->next = cur; + + GNUNET_free(sec_name); + e_counter++; + last = cur; + } return e_counter; } static void -timeout_experiment (void *cls) +timeout_experiment(void *cls) { struct Experiment *e = cls; + e->experiment_timeout_task = NULL; - fprintf (stderr, "Experiment timeout!\n"); + fprintf(stderr, "Experiment timeout!\n"); if (NULL != e->episode_timeout_task) - { - GNUNET_SCHEDULER_cancel (e->episode_timeout_task); - e->episode_timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(e->episode_timeout_task); + e->episode_timeout_task = NULL; + } - e->e_done_cb (e, GNUNET_TIME_absolute_get_duration(e->start_time), - GNUNET_SYSERR); + e->e_done_cb(e, GNUNET_TIME_absolute_get_duration(e->start_time), + GNUNET_SYSERR); } static void -enforce_start_send (struct GNUNET_ATS_TEST_Operation *op) +enforce_start_send(struct GNUNET_ATS_TEST_Operation *op) { struct BenchmarkPeer *peer; struct BenchmarkPartner *partner; - peer = GNUNET_ATS_TEST_get_peer (op->src_id); + peer = GNUNET_ATS_TEST_get_peer(op->src_id); if (NULL == peer) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } - partner = GNUNET_ATS_TEST_get_partner (op->src_id, op->dest_id); + partner = GNUNET_ATS_TEST_get_partner(op->src_id, op->dest_id); if (NULL == partner) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } - fprintf (stderr, "Found master %llu slave %llu\n",op->src_id, op->dest_id); + fprintf(stderr, "Found master %llu slave %llu\n", op->src_id, op->dest_id); if (NULL != partner->tg) - { - fprintf (stderr, "Stopping traffic between master %llu slave %llu\n",op->src_id, op->dest_id); - GNUNET_ATS_TEST_generate_traffic_stop(partner->tg); - partner->tg = NULL; - } + { + fprintf(stderr, "Stopping traffic between master %llu slave %llu\n", op->src_id, op->dest_id); + GNUNET_ATS_TEST_generate_traffic_stop(partner->tg); + partner->tg = NULL; + } partner->tg = GNUNET_ATS_TEST_generate_traffic_start(peer, partner, - op->gen_type, op->base_rate, op->max_rate, op->period, - GNUNET_TIME_UNIT_FOREVER_REL); + op->gen_type, op->base_rate, op->max_rate, op->period, + GNUNET_TIME_UNIT_FOREVER_REL); } static void -enforce_stop_send (struct GNUNET_ATS_TEST_Operation *op) +enforce_stop_send(struct GNUNET_ATS_TEST_Operation *op) { struct BenchmarkPartner *p; - p = GNUNET_ATS_TEST_get_partner (op->src_id, op->dest_id); + + p = GNUNET_ATS_TEST_get_partner(op->src_id, op->dest_id); if (NULL == p) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } - fprintf (stderr, "Found master %llu slave %llu\n",op->src_id, op->dest_id); + fprintf(stderr, "Found master %llu slave %llu\n", op->src_id, op->dest_id); if (NULL != p->tg) - { - fprintf (stderr, "Stopping traffic between master %llu slave %llu\n", - op->src_id, op->dest_id); - GNUNET_ATS_TEST_generate_traffic_stop(p->tg); - p->tg = NULL; - } + { + fprintf(stderr, "Stopping traffic between master %llu slave %llu\n", + op->src_id, op->dest_id); + GNUNET_ATS_TEST_generate_traffic_stop(p->tg); + p->tg = NULL; + } } static void -enforce_start_preference (struct GNUNET_ATS_TEST_Operation *op) +enforce_start_preference(struct GNUNET_ATS_TEST_Operation *op) { struct BenchmarkPeer *peer; struct BenchmarkPartner *partner; - peer = GNUNET_ATS_TEST_get_peer (op->src_id); + peer = GNUNET_ATS_TEST_get_peer(op->src_id); if (NULL == peer) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } - partner = GNUNET_ATS_TEST_get_partner (op->src_id, op->dest_id); + partner = GNUNET_ATS_TEST_get_partner(op->src_id, op->dest_id); if (NULL == partner) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } - fprintf (stderr, "Found master %llu slave %llu\n",op->src_id, op->dest_id); + fprintf(stderr, "Found master %llu slave %llu\n", op->src_id, op->dest_id); if (NULL != partner->pg) - { - fprintf (stderr, "Stopping traffic between master %llu slave %llu\n", - op->src_id, op->dest_id); - GNUNET_ATS_TEST_generate_preferences_stop(partner->pg); - partner->pg = NULL; - } + { + fprintf(stderr, "Stopping traffic between master %llu slave %llu\n", + op->src_id, op->dest_id); + GNUNET_ATS_TEST_generate_preferences_stop(partner->pg); + partner->pg = NULL; + } partner->pg = GNUNET_ATS_TEST_generate_preferences_start(peer, partner, - op->gen_type, op->base_rate, op->max_rate, op->period, op->frequency, - op->pref_type); + op->gen_type, op->base_rate, op->max_rate, op->period, op->frequency, + op->pref_type); } static void -enforce_stop_preference (struct GNUNET_ATS_TEST_Operation *op) +enforce_stop_preference(struct GNUNET_ATS_TEST_Operation *op) { struct BenchmarkPartner *p; - p = GNUNET_ATS_TEST_get_partner (op->src_id, op->dest_id); + + p = GNUNET_ATS_TEST_get_partner(op->src_id, op->dest_id); if (NULL == p) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } - fprintf (stderr, "Found master %llu slave %llu\n",op->src_id, op->dest_id); + fprintf(stderr, "Found master %llu slave %llu\n", op->src_id, op->dest_id); if (NULL != p->pg) - { - fprintf (stderr, "Stopping preference between master %llu slave %llu\n", - op->src_id, op->dest_id); - GNUNET_ATS_TEST_generate_preferences_stop (p->pg); - p->pg = NULL; - } + { + fprintf(stderr, "Stopping preference between master %llu slave %llu\n", + op->src_id, op->dest_id); + GNUNET_ATS_TEST_generate_preferences_stop(p->pg); + p->pg = NULL; + } } -static void enforce_episode (struct Episode *ep) +static void enforce_episode(struct Episode *ep) { struct GNUNET_ATS_TEST_Operation *cur; + for (cur = ep->head; NULL != cur; cur = cur->next) - { - - fprintf (stderr, "Enforcing operation: %s [%llu]->[%llu] == %llu\n", - print_op (cur->type), cur->src_id, cur->dest_id, cur->base_rate); - switch (cur->type) { - case START_SEND: - enforce_start_send (cur); - break; - case STOP_SEND: - enforce_stop_send (cur); - break; - case START_PREFERENCE: - enforce_start_preference (cur); - break; - case STOP_PREFERENCE: - enforce_stop_preference (cur); - break; - default: - break; + { + fprintf(stderr, "Enforcing operation: %s [%llu]->[%llu] == %llu\n", + print_op(cur->type), cur->src_id, cur->dest_id, cur->base_rate); + switch (cur->type) + { + case START_SEND: + enforce_start_send(cur); + break; + + case STOP_SEND: + enforce_stop_send(cur); + break; + + case START_PREFERENCE: + enforce_start_preference(cur); + break; + + case STOP_PREFERENCE: + enforce_stop_preference(cur); + break; + + default: + break; + } } - } } static void -timeout_episode (void *cls) +timeout_episode(void *cls) { struct Experiment *e = cls; e->episode_timeout_task = NULL; if (NULL != e->ep_done_cb) - e->ep_done_cb (e->cur); + e->ep_done_cb(e->cur); /* Scheduling next */ e->cur = e->cur->next; if (NULL == e->cur) - { - /* done */ - fprintf (stderr, "Last episode done!\n"); - if (NULL != e->experiment_timeout_task) { - GNUNET_SCHEDULER_cancel (e->experiment_timeout_task); - e->experiment_timeout_task = NULL; + /* done */ + fprintf(stderr, "Last episode done!\n"); + if (NULL != e->experiment_timeout_task) + { + GNUNET_SCHEDULER_cancel(e->experiment_timeout_task); + e->experiment_timeout_task = NULL; + } + e->e_done_cb(e, GNUNET_TIME_absolute_get_duration(e->start_time), GNUNET_OK); + return; } - e->e_done_cb (e, GNUNET_TIME_absolute_get_duration(e->start_time), GNUNET_OK); - return; - } - fprintf (stderr, "Running episode %u with timeout %s\n", - e->cur->id, - GNUNET_STRINGS_relative_time_to_string(e->cur->duration, GNUNET_YES)); + fprintf(stderr, "Running episode %u with timeout %s\n", + e->cur->id, + GNUNET_STRINGS_relative_time_to_string(e->cur->duration, GNUNET_YES)); enforce_episode(e->cur); - e->episode_timeout_task = GNUNET_SCHEDULER_add_delayed (e->cur->duration, - &timeout_episode, e); + e->episode_timeout_task = GNUNET_SCHEDULER_add_delayed(e->cur->duration, + &timeout_episode, e); } void -GNUNET_ATS_TEST_experimentation_run (struct Experiment *e, - GNUNET_ATS_TESTING_EpisodeDoneCallback ep_done_cb, - GNUNET_ATS_TESTING_ExperimentDoneCallback e_done_cb) +GNUNET_ATS_TEST_experimentation_run(struct Experiment *e, + GNUNET_ATS_TESTING_EpisodeDoneCallback ep_done_cb, + GNUNET_ATS_TESTING_ExperimentDoneCallback e_done_cb) { - fprintf (stderr, "Running experiment `%s' with timeout %s\n", e->name, - GNUNET_STRINGS_relative_time_to_string(e->max_duration, GNUNET_YES)); + fprintf(stderr, "Running experiment `%s' with timeout %s\n", e->name, + GNUNET_STRINGS_relative_time_to_string(e->max_duration, GNUNET_YES)); e->e_done_cb = e_done_cb; e->ep_done_cb = ep_done_cb; e->start_time = GNUNET_TIME_absolute_get(); /* Start total time out */ - e->experiment_timeout_task = GNUNET_SCHEDULER_add_delayed (e->max_duration, - &timeout_experiment, e); + e->experiment_timeout_task = GNUNET_SCHEDULER_add_delayed(e->max_duration, + &timeout_experiment, e); /* Start */ e->cur = e->start; - fprintf (stderr, "Running episode %u with timeout %s\n", - e->cur->id, - GNUNET_STRINGS_relative_time_to_string(e->cur->duration, GNUNET_YES)); + fprintf(stderr, "Running episode %u with timeout %s\n", + e->cur->id, + GNUNET_STRINGS_relative_time_to_string(e->cur->duration, GNUNET_YES)); enforce_episode(e->cur); - e->episode_timeout_task = GNUNET_SCHEDULER_add_delayed (e->cur->duration, - &timeout_episode, e); - - + e->episode_timeout_task = GNUNET_SCHEDULER_add_delayed(e->cur->duration, + &timeout_episode, e); } struct Experiment * -GNUNET_ATS_TEST_experimentation_load (const char *filename) +GNUNET_ATS_TEST_experimentation_load(const char *filename) { struct Experiment *e; struct GNUNET_CONFIGURATION_Handle *cfg; + e = NULL; cfg = GNUNET_CONFIGURATION_create(); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, filename)) - { - fprintf (stderr, "Failed to load `%s'\n", filename); - GNUNET_CONFIGURATION_destroy (cfg); - return NULL; - } + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load(cfg, filename)) + { + fprintf(stderr, "Failed to load `%s'\n", filename); + GNUNET_CONFIGURATION_destroy(cfg); + return NULL; + } - e = create_experiment (); + e = create_experiment(); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, "experiment", - "name", &e->name)) - { - fprintf (stderr, "Invalid %s", "name"); - free_experiment (e); - return NULL; - } + "name", &e->name)) + { + fprintf(stderr, "Invalid %s", "name"); + free_experiment(e); + return NULL; + } else - fprintf (stderr, "Experiment name: `%s'\n", e->name); - - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_filename (cfg, "experiment", - "cfg_file", &e->cfg_file)) - { - fprintf (stderr, "Invalid %s", "cfg_file"); - free_experiment (e); - return NULL; - } + fprintf(stderr, "Experiment name: `%s'\n", e->name); + + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_filename(cfg, "experiment", + "cfg_file", &e->cfg_file)) + { + fprintf(stderr, "Invalid %s", "cfg_file"); + free_experiment(e); + return NULL; + } else - fprintf (stderr, "Experiment name: `%s'\n", e->cfg_file); + fprintf(stderr, "Experiment name: `%s'\n", e->cfg_file); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, "experiment", - "masters", &e->num_masters)) - { - fprintf (stderr, "Invalid %s", "masters"); - free_experiment (e); - return NULL; - } + "masters", &e->num_masters)) + { + fprintf(stderr, "Invalid %s", "masters"); + free_experiment(e); + return NULL; + } else - fprintf (stderr, "Experiment masters: `%llu'\n", - e->num_masters); + fprintf(stderr, "Experiment masters: `%llu'\n", + e->num_masters); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, "experiment", - "slaves", &e->num_slaves)) - { - fprintf (stderr, "Invalid %s", "slaves"); - free_experiment (e); - return NULL; - } + "slaves", &e->num_slaves)) + { + fprintf(stderr, "Invalid %s", "slaves"); + free_experiment(e); + return NULL; + } else - fprintf (stderr, "Experiment slaves: `%llu'\n", - e->num_slaves); + fprintf(stderr, "Experiment slaves: `%llu'\n", + e->num_slaves); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, "experiment", - "log_freq", &e->log_freq)) - { - fprintf (stderr, "Invalid %s", "log_freq"); - free_experiment (e); - return NULL; - } + "log_freq", &e->log_freq)) + { + fprintf(stderr, "Invalid %s", "log_freq"); + free_experiment(e); + return NULL; + } else - fprintf (stderr, "Experiment logging frequency: `%s'\n", - GNUNET_STRINGS_relative_time_to_string (e->log_freq, GNUNET_YES)); + fprintf(stderr, "Experiment logging frequency: `%s'\n", + GNUNET_STRINGS_relative_time_to_string(e->log_freq, GNUNET_YES)); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, "experiment", - "max_duration", &e->max_duration)) - { - fprintf (stderr, "Invalid %s", "max_duration"); - free_experiment (e); - return NULL; - } + "max_duration", &e->max_duration)) + { + fprintf(stderr, "Invalid %s", "max_duration"); + free_experiment(e); + return NULL; + } else - fprintf (stderr, "Experiment duration: `%s'\n", - GNUNET_STRINGS_relative_time_to_string (e->max_duration, GNUNET_YES)); + fprintf(stderr, "Experiment duration: `%s'\n", + GNUNET_STRINGS_relative_time_to_string(e->max_duration, GNUNET_YES)); - load_episodes (e, cfg); - fprintf (stderr, "Loaded %u episodes with total duration %s\n", - e->num_episodes, - GNUNET_STRINGS_relative_time_to_string (e->total_duration, GNUNET_YES)); + load_episodes(e, cfg); + fprintf(stderr, "Loaded %u episodes with total duration %s\n", + e->num_episodes, + GNUNET_STRINGS_relative_time_to_string(e->total_duration, GNUNET_YES)); - GNUNET_CONFIGURATION_destroy (cfg); + GNUNET_CONFIGURATION_destroy(cfg); return e; } void -GNUNET_ATS_TEST_experimentation_stop (struct Experiment *e) +GNUNET_ATS_TEST_experimentation_stop(struct Experiment *e) { if (NULL != e->experiment_timeout_task) - { - GNUNET_SCHEDULER_cancel (e->experiment_timeout_task); - e->experiment_timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(e->experiment_timeout_task); + e->experiment_timeout_task = NULL; + } if (NULL != e->episode_timeout_task) - { - GNUNET_SCHEDULER_cancel (e->episode_timeout_task); - e->episode_timeout_task = NULL; - } - free_experiment (e); + { + GNUNET_SCHEDULER_cancel(e->episode_timeout_task); + e->episode_timeout_task = NULL; + } + free_experiment(e); } /* end of file ats-testing-experiment.c*/ diff --git a/src/ats-tests/ats-testing-log.c b/src/ats-tests/ats-testing-log.c index 8624904a5..a362955d2 100644 --- a/src/ats-tests/ats-testing-log.c +++ b/src/ats-tests/ats-testing-log.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2013 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2013 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -28,25 +28,25 @@ #include "ats-testing.h" #define THROUGHPUT_TEMPLATE "#!/usr/bin/gnuplot \n" \ -"set datafile separator ';' \n" \ -"set title \"Throughput between Master and Slaves\" \n" \ -"set xlabel \"Time in ms\" \n" \ -"set ylabel \"Bytes/s\" \n" \ -"set grid \n" + "set datafile separator ';' \n" \ + "set title \"Throughput between Master and Slaves\" \n" \ + "set xlabel \"Time in ms\" \n" \ + "set ylabel \"Bytes/s\" \n" \ + "set grid \n" #define RTT_TEMPLATE "#!/usr/bin/gnuplot \n" \ -"set datafile separator ';' \n" \ -"set title \"Application level roundtrip time between Master and Slaves\" \n" \ -"set xlabel \"Time in ms\" \n" \ -"set ylabel \"ms\" \n" \ -"set grid \n" + "set datafile separator ';' \n" \ + "set title \"Application level roundtrip time between Master and Slaves\" \n" \ + "set xlabel \"Time in ms\" \n" \ + "set ylabel \"ms\" \n" \ + "set grid \n" #define BW_TEMPLATE "#!/usr/bin/gnuplot \n" \ -"set datafile separator ';' \n" \ -"set title \"Bandwidth inbound and outbound between Master and Slaves\" \n" \ -"set xlabel \"Time in ms\" \n" \ -"set ylabel \"Bytes / s \" \n" \ -"set grid \n" + "set datafile separator ';' \n" \ + "set title \"Bandwidth inbound and outbound between Master and Slaves\" \n" \ + "set xlabel \"Time in ms\" \n" \ + "set ylabel \"Bytes / s \" \n" \ + "set grid \n" #define LOG_ITEMS_TIME 2 #define LOG_ITEMS_PER_PEER 17 @@ -72,8 +72,7 @@ /** * A single logging time step for a partner */ -struct PartnerLoggingTimestep -{ +struct PartnerLoggingTimestep { /** * Peer */ @@ -143,8 +142,7 @@ struct PartnerLoggingTimestep /** * A single logging time step for a peer */ -struct PeerLoggingTimestep -{ +struct PeerLoggingTimestep { /** * Next in DLL */ @@ -199,8 +197,7 @@ struct PeerLoggingTimestep /** * Entry for a benchmark peer */ -struct LoggingPeer -{ +struct LoggingPeer { /** * Peer */ @@ -222,8 +219,7 @@ struct LoggingPeer struct PeerLoggingTimestep *tail; }; -struct LoggingHandle -{ +struct LoggingHandle { /** * Logging task */ @@ -248,179 +244,179 @@ struct LoggingHandle static void -write_throughput_gnuplot_script (char * fn, struct LoggingPeer *lp, char **fs, int slaves) +write_throughput_gnuplot_script(char * fn, struct LoggingPeer *lp, char **fs, int slaves) { struct GNUNET_DISK_FileHandle *f; char * gfn; char *data; int c_s; - GNUNET_asprintf (&gfn, "gnuplot_throughput_%s",fn); - fprintf (stderr, "Writing throughput plot for master %u and %u slaves to `%s'\n", - lp->peer->no, slaves, gfn); + GNUNET_asprintf(&gfn, "gnuplot_throughput_%s", fn); + fprintf(stderr, "Writing throughput plot for master %u and %u slaves to `%s'\n", + lp->peer->no, slaves, gfn); - f = GNUNET_DISK_file_open (gfn, - GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE); + f = GNUNET_DISK_file_open(gfn, + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE); if (NULL == f) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot open gnuplot file `%s'\n", gfn); - GNUNET_free (gfn); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot open gnuplot file `%s'\n", gfn); + GNUNET_free(gfn); + return; + } /* Write header */ if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, THROUGHPUT_TEMPLATE, - strlen(THROUGHPUT_TEMPLATE))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot write data to plot file `%s'\n", gfn); + strlen(THROUGHPUT_TEMPLATE))) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot write data to plot file `%s'\n", gfn); /* Write master data */ - GNUNET_asprintf (&data, - "plot '%s' using 2:%u with lines title 'Master %u send total', \\\n" \ - "'%s' using 2:%u with lines title 'Master %u receive total', \\\n", - fn, LOG_ITEMS_TIME + LOG_ITEM_THROUGHPUT_SENT, lp->peer->no, - fn, LOG_ITEMS_TIME + LOG_ITEM_THROUGHPUT_RECV, lp->peer->no); + GNUNET_asprintf(&data, + "plot '%s' using 2:%u with lines title 'Master %u send total', \\\n" \ + "'%s' using 2:%u with lines title 'Master %u receive total', \\\n", + fn, LOG_ITEMS_TIME + LOG_ITEM_THROUGHPUT_SENT, lp->peer->no, + fn, LOG_ITEMS_TIME + LOG_ITEM_THROUGHPUT_RECV, lp->peer->no); if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); - GNUNET_free (data); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); + GNUNET_free(data); for (c_s = 0; c_s < slaves; c_s++) - { - GNUNET_asprintf (&data, "'%s' using 2:%u with lines title 'Master %u - Slave %u send', \\\n" \ - "'%s' using 2:%u with lines title 'Master %u - Slave %u receive'%s\n", - fs[c_s], - LOG_ITEMS_TIME + LOG_ITEM_THROUGHPUT_SENT, - lp->peer->no, - lp->peer->partners[c_s].dest->no, - fs[c_s], - LOG_ITEMS_TIME + LOG_ITEM_THROUGHPUT_RECV, - lp->peer->no, - lp->peer->partners[c_s].dest->no, - (c_s < lp->peer->num_partners -1) ? ", \\" : "\n pause -1"); - if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); - GNUNET_free (data); - } + { + GNUNET_asprintf(&data, "'%s' using 2:%u with lines title 'Master %u - Slave %u send', \\\n" \ + "'%s' using 2:%u with lines title 'Master %u - Slave %u receive'%s\n", + fs[c_s], + LOG_ITEMS_TIME + LOG_ITEM_THROUGHPUT_SENT, + lp->peer->no, + lp->peer->partners[c_s].dest->no, + fs[c_s], + LOG_ITEMS_TIME + LOG_ITEM_THROUGHPUT_RECV, + lp->peer->no, + lp->peer->partners[c_s].dest->no, + (c_s < lp->peer->num_partners - 1) ? ", \\" : "\n pause -1"); + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); + GNUNET_free(data); + } if (GNUNET_SYSERR == GNUNET_DISK_file_close(f)) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot close gnuplot file `%s'\n", gfn); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot close gnuplot file `%s'\n", gfn); else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Data successfully written to plot file `%s'\n", gfn); - GNUNET_free (gfn); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Data successfully written to plot file `%s'\n", gfn); + GNUNET_free(gfn); } static void -write_rtt_gnuplot_script (char * fn, struct LoggingPeer *lp, char **fs, int slaves) +write_rtt_gnuplot_script(char * fn, struct LoggingPeer *lp, char **fs, int slaves) { struct GNUNET_DISK_FileHandle *f; char * gfn; char *data; int c_s; - GNUNET_asprintf (&gfn, "gnuplot_rtt_%s",fn); - fprintf (stderr, "Writing rtt plot for master %u to `%s'\n", - lp->peer->no, gfn); + GNUNET_asprintf(&gfn, "gnuplot_rtt_%s", fn); + fprintf(stderr, "Writing rtt plot for master %u to `%s'\n", + lp->peer->no, gfn); - f = GNUNET_DISK_file_open (gfn, - GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE); + f = GNUNET_DISK_file_open(gfn, + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE); if (NULL == f) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot open gnuplot file `%s'\n", gfn); - GNUNET_free (gfn); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot open gnuplot file `%s'\n", gfn); + GNUNET_free(gfn); + return; + } /* Write header */ if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, RTT_TEMPLATE, strlen(RTT_TEMPLATE))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); for (c_s = 0; c_s < slaves; c_s++) - { - GNUNET_asprintf (&data, "%s'%s' using 2:%u with lines title 'Master %u - Slave %u '%s\n", - (0 == c_s) ? "plot " :"", - fs[c_s], - LOG_ITEMS_TIME + LOG_ITEM_APP_RTT, - lp->peer->no, - lp->peer->partners[c_s].dest->no, - (c_s < lp->peer->num_partners -1) ? ", \\" : "\n pause -1"); - if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); - GNUNET_free (data); - } + { + GNUNET_asprintf(&data, "%s'%s' using 2:%u with lines title 'Master %u - Slave %u '%s\n", + (0 == c_s) ? "plot " : "", + fs[c_s], + LOG_ITEMS_TIME + LOG_ITEM_APP_RTT, + lp->peer->no, + lp->peer->partners[c_s].dest->no, + (c_s < lp->peer->num_partners - 1) ? ", \\" : "\n pause -1"); + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); + GNUNET_free(data); + } if (GNUNET_SYSERR == GNUNET_DISK_file_close(f)) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot close gnuplot file `%s'\n", gfn); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot close gnuplot file `%s'\n", gfn); else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Data successfully written to plot file `%s'\n", gfn); - GNUNET_free (gfn); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Data successfully written to plot file `%s'\n", gfn); + GNUNET_free(gfn); } static void -write_bw_gnuplot_script (char * fn, struct LoggingPeer *lp, char **fs, int slaves) +write_bw_gnuplot_script(char * fn, struct LoggingPeer *lp, char **fs, int slaves) { struct GNUNET_DISK_FileHandle *f; char * gfn; char *data; int c_s; - GNUNET_asprintf (&gfn, "gnuplot_bw_%s",fn); - fprintf (stderr, "Writing bandwidth plot for master %u to `%s'\n", - lp->peer->no, gfn); + GNUNET_asprintf(&gfn, "gnuplot_bw_%s", fn); + fprintf(stderr, "Writing bandwidth plot for master %u to `%s'\n", + lp->peer->no, gfn); - f = GNUNET_DISK_file_open (gfn, - GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE); + f = GNUNET_DISK_file_open(gfn, + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE); if (NULL == f) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot open gnuplot file `%s'\n", gfn); - GNUNET_free (gfn); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot open gnuplot file `%s'\n", gfn); + GNUNET_free(gfn); + return; + } /* Write header */ if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, BW_TEMPLATE, strlen(BW_TEMPLATE))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot write data to plot file `%s'\n", gfn); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot write data to plot file `%s'\n", gfn); for (c_s = 0; c_s < slaves; c_s++) - { - GNUNET_asprintf (&data, "%s"\ - "'%s' using 2:%u with lines title 'BW out master %u - Slave %u ', \\\n" \ - "'%s' using 2:%u with lines title 'BW in master %u - Slave %u '"\ - "%s\n", - (0 == c_s) ? "plot " :"", - fs[c_s], - LOG_ITEMS_TIME + LOG_ITEM_ATS_BW_OUT, - lp->peer->no, c_s, - fs[c_s], - LOG_ITEMS_TIME + LOG_ITEM_ATS_BW_IN, - lp->peer->no, c_s, - (c_s < lp->peer->num_partners -1) ? ", \\" : "\n pause -1"); - if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); - GNUNET_free (data); - } + { + GNUNET_asprintf(&data, "%s" \ + "'%s' using 2:%u with lines title 'BW out master %u - Slave %u ', \\\n" \ + "'%s' using 2:%u with lines title 'BW in master %u - Slave %u '" \ + "%s\n", + (0 == c_s) ? "plot " : "", + fs[c_s], + LOG_ITEMS_TIME + LOG_ITEM_ATS_BW_OUT, + lp->peer->no, c_s, + fs[c_s], + LOG_ITEMS_TIME + LOG_ITEM_ATS_BW_IN, + lp->peer->no, c_s, + (c_s < lp->peer->num_partners - 1) ? ", \\" : "\n pause -1"); + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); + GNUNET_free(data); + } if (GNUNET_SYSERR == GNUNET_DISK_file_close(f)) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot close gnuplot file `%s'\n", gfn); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot close gnuplot file `%s'\n", gfn); else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Data successfully written to plot file `%s'\n", gfn); - GNUNET_free (gfn); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Data successfully written to plot file `%s'\n", gfn); + GNUNET_free(gfn); } void -GNUNET_ATS_TEST_logging_write_to_file (struct LoggingHandle *l, - const char *experiment_name, - int plots) +GNUNET_ATS_TEST_logging_write_to_file(struct LoggingHandle *l, + const char *experiment_name, + int plots) { struct GNUNET_DISK_FileHandle *f[l->num_slaves]; struct GNUNET_DISK_FileHandle *f_m; @@ -439,179 +435,178 @@ GNUNET_ATS_TEST_logging_write_to_file (struct LoggingHandle *l, tmp_exp_name = experiment_name; for (c_m = 0; c_m < l->num_masters; c_m++) - { - GNUNET_asprintf (&filename_master, "%s_%llu_master%u_%s", - experiment_name, timestamp.abs_value_us, c_m, l->name); - fprintf (stderr, "Writing data for master %u to file `%s'\n", - c_m,filename_master); - - f_m = GNUNET_DISK_file_open (filename_master, - GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); - if (NULL == f_m) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot open log file `%s'\n", filename_master); - GNUNET_free (filename_master); - return; - } - - GNUNET_asprintf (&data, "# master %u; experiment : %s\n" - "timestamp; timestamp delta; #messages sent; #bytes sent; #throughput sent; #messages received; #bytes received; #throughput received; \n" , - c_m, experiment_name); - if (GNUNET_SYSERR == GNUNET_DISK_file_write(f_m, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot write data to log file `%s'\n",filename_master); - GNUNET_free (data); - - for (c_s = 0; c_s < l->lp[c_m].peer->num_partners; c_s++) - { - GNUNET_asprintf (&filename_slaves[c_s], "%s_%llu_master%u_slave_%u_%s", - tmp_exp_name, timestamp.abs_value_us, c_m, c_s, l->name); - - fprintf (stderr, "Writing data for master %u slave %u to file `%s'\n", - c_m, c_s, filename_slaves[c_s]); - - f[c_s] = GNUNET_DISK_file_open (filename_slaves[c_s], - GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); - if (NULL == f[c_s]) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot open log file `%s'\n", filename_slaves[c_s]); - GNUNET_free (filename_slaves[c_s]); - GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close(f_m)); - GNUNET_free (filename_master); - return; - } - - /* Header */ - GNUNET_asprintf (&data, "# master %u; slave %u ; experiment : %s\n" - "timestamp; timestamp delta; #messages sent; #bytes sent; #throughput sent; #messages received; #bytes received; #throughput received; " \ - "rtt; bw in; bw out; ats_cost_lan; ats_cost_wlan; ats_delay; ats_distance; ats_network_type; ats_utilization_up ;ats_utilization_down;" \ - "pref bandwidth; pref delay\n", - c_m, c_s, experiment_name); - if (GNUNET_SYSERR == GNUNET_DISK_file_write(f[c_s], data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot write data to log file `%s'\n",filename_slaves[c_s]); - GNUNET_free (data); - } - - for (cur_lt = l->lp[c_m].head; NULL != cur_lt; cur_lt = cur_lt->next) { - if (l->verbose) - fprintf (stderr, - "Master [%u]: timestamp %llu %llu ; %u %u %u ; %u %u %u\n", - l->lp[c_m].peer->no, - (long long unsigned int) cur_lt->timestamp.abs_value_us, - (long long unsigned int) GNUNET_TIME_absolute_get_difference(l->lp[c_m].start, - cur_lt->timestamp).rel_value_us / 1000, - cur_lt->total_messages_sent, - cur_lt->total_bytes_sent, - cur_lt->total_throughput_send, - cur_lt->total_messages_received, - cur_lt->total_bytes_received, - cur_lt->total_throughput_recv); - - /* Assembling master string */ - GNUNET_asprintf (&data, "%llu;%llu;%u;%u;%u;%u;%u;%u;\n", - (long long unsigned int) cur_lt->timestamp.abs_value_us, - (long long unsigned int) GNUNET_TIME_absolute_get_difference(l->lp[c_m].start, - cur_lt->timestamp).rel_value_us / 1000, - cur_lt->total_messages_sent, - cur_lt->total_bytes_sent, - cur_lt->total_throughput_send, - cur_lt->total_messages_received, - cur_lt->total_bytes_received, - cur_lt->total_throughput_recv); + GNUNET_asprintf(&filename_master, "%s_%llu_master%u_%s", + experiment_name, timestamp.abs_value_us, c_m, l->name); + fprintf(stderr, "Writing data for master %u to file `%s'\n", + c_m, filename_master); + + f_m = GNUNET_DISK_file_open(filename_master, + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); + if (NULL == f_m) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot open log file `%s'\n", filename_master); + GNUNET_free(filename_master); + return; + } + GNUNET_asprintf(&data, "# master %u; experiment : %s\n" + "timestamp; timestamp delta; #messages sent; #bytes sent; #throughput sent; #messages received; #bytes received; #throughput received; \n", + c_m, experiment_name); if (GNUNET_SYSERR == GNUNET_DISK_file_write(f_m, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot write data to master file %u\n", c_m); - GNUNET_free (data); - + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot write data to log file `%s'\n", filename_master); + GNUNET_free(data); for (c_s = 0; c_s < l->lp[c_m].peer->num_partners; c_s++) - { - plt = &cur_lt->slaves_log[c_s]; - /* Log partners */ - - /* Assembling slave string */ - GNUNET_asprintf(&data, - "%llu;%llu;%u;%u;%u;%u;%u;%u;%.3f;%u;%u;%u;%u;%u;%u;%u;%.3f;%.3f\n", - (long long unsigned int) cur_lt->timestamp.abs_value_us, - (long long unsigned int) GNUNET_TIME_absolute_get_difference(l->lp[c_m].start, - cur_lt->timestamp).rel_value_us / 1000, - plt->total_messages_sent, - plt->total_bytes_sent, - plt->throughput_sent, - plt->total_messages_received, - plt->total_bytes_received, - plt->throughput_recv, - (double) plt->app_rtt / 1000, - plt->bandwidth_in, - plt->bandwidth_out, - plt->ats_delay, - plt->ats_distance, - plt->ats_network_type, - plt->ats_utilization_out, - plt->ats_utilization_in, - plt->pref_bandwidth, - plt->pref_delay); - - if (l->verbose) - fprintf (stderr, - "\t Slave [%u]: %u %u %u ; %u %u %u rtt %u delay %llu bw_in %u bw_out %u \n", - plt->slave->no, - plt->total_messages_sent, - plt->total_bytes_sent, - plt->throughput_sent, - plt->total_messages_received, - plt->total_bytes_received, - plt->throughput_recv, - plt->app_rtt, - (long long unsigned int) plt->ats_delay.rel_value_us, - plt->bandwidth_in, - plt->bandwidth_out); - - if (GNUNET_SYSERR == GNUNET_DISK_file_write(f[c_s], data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot write data to log file `%s'\n", filename_slaves[c_s]); - GNUNET_free (data); - - } - } + { + GNUNET_asprintf(&filename_slaves[c_s], "%s_%llu_master%u_slave_%u_%s", + tmp_exp_name, timestamp.abs_value_us, c_m, c_s, l->name); + + fprintf(stderr, "Writing data for master %u slave %u to file `%s'\n", + c_m, c_s, filename_slaves[c_s]); + + f[c_s] = GNUNET_DISK_file_open(filename_slaves[c_s], + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); + if (NULL == f[c_s]) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot open log file `%s'\n", filename_slaves[c_s]); + GNUNET_free(filename_slaves[c_s]); + GNUNET_break(GNUNET_OK == GNUNET_DISK_file_close(f_m)); + GNUNET_free(filename_master); + return; + } + + /* Header */ + GNUNET_asprintf(&data, "# master %u; slave %u ; experiment : %s\n" + "timestamp; timestamp delta; #messages sent; #bytes sent; #throughput sent; #messages received; #bytes received; #throughput received; " \ + "rtt; bw in; bw out; ats_cost_lan; ats_cost_wlan; ats_delay; ats_distance; ats_network_type; ats_utilization_up ;ats_utilization_down;" \ + "pref bandwidth; pref delay\n", + c_m, c_s, experiment_name); + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f[c_s], data, strlen(data))) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot write data to log file `%s'\n", filename_slaves[c_s]); + GNUNET_free(data); + } - for (c_s = 0; c_s < l->lp[c_m].peer->num_partners; c_s++) - { - if (GNUNET_SYSERR == GNUNET_DISK_file_close(f[c_s])) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot close log file for master[%u] slave[%u]\n", c_m, c_s); - continue; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Data file successfully written to log file for `%s'\n", - filename_slaves[c_s]); - } + for (cur_lt = l->lp[c_m].head; NULL != cur_lt; cur_lt = cur_lt->next) + { + if (l->verbose) + fprintf(stderr, + "Master [%u]: timestamp %llu %llu ; %u %u %u ; %u %u %u\n", + l->lp[c_m].peer->no, + (long long unsigned int)cur_lt->timestamp.abs_value_us, + (long long unsigned int)GNUNET_TIME_absolute_get_difference(l->lp[c_m].start, + cur_lt->timestamp).rel_value_us / 1000, + cur_lt->total_messages_sent, + cur_lt->total_bytes_sent, + cur_lt->total_throughput_send, + cur_lt->total_messages_received, + cur_lt->total_bytes_received, + cur_lt->total_throughput_recv); + + /* Assembling master string */ + GNUNET_asprintf(&data, "%llu;%llu;%u;%u;%u;%u;%u;%u;\n", + (long long unsigned int)cur_lt->timestamp.abs_value_us, + (long long unsigned int)GNUNET_TIME_absolute_get_difference(l->lp[c_m].start, + cur_lt->timestamp).rel_value_us / 1000, + cur_lt->total_messages_sent, + cur_lt->total_bytes_sent, + cur_lt->total_throughput_send, + cur_lt->total_messages_received, + cur_lt->total_bytes_received, + cur_lt->total_throughput_recv); + + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f_m, data, strlen(data))) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot write data to master file %u\n", c_m); + GNUNET_free(data); + + + for (c_s = 0; c_s < l->lp[c_m].peer->num_partners; c_s++) + { + plt = &cur_lt->slaves_log[c_s]; + /* Log partners */ + + /* Assembling slave string */ + GNUNET_asprintf(&data, + "%llu;%llu;%u;%u;%u;%u;%u;%u;%.3f;%u;%u;%u;%u;%u;%u;%u;%.3f;%.3f\n", + (long long unsigned int)cur_lt->timestamp.abs_value_us, + (long long unsigned int)GNUNET_TIME_absolute_get_difference(l->lp[c_m].start, + cur_lt->timestamp).rel_value_us / 1000, + plt->total_messages_sent, + plt->total_bytes_sent, + plt->throughput_sent, + plt->total_messages_received, + plt->total_bytes_received, + plt->throughput_recv, + (double)plt->app_rtt / 1000, + plt->bandwidth_in, + plt->bandwidth_out, + plt->ats_delay, + plt->ats_distance, + plt->ats_network_type, + plt->ats_utilization_out, + plt->ats_utilization_in, + plt->pref_bandwidth, + plt->pref_delay); + + if (l->verbose) + fprintf(stderr, + "\t Slave [%u]: %u %u %u ; %u %u %u rtt %u delay %llu bw_in %u bw_out %u \n", + plt->slave->no, + plt->total_messages_sent, + plt->total_bytes_sent, + plt->throughput_sent, + plt->total_messages_received, + plt->total_bytes_received, + plt->throughput_recv, + plt->app_rtt, + (long long unsigned int)plt->ats_delay.rel_value_us, + plt->bandwidth_in, + plt->bandwidth_out); + + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f[c_s], data, strlen(data))) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot write data to log file `%s'\n", filename_slaves[c_s]); + GNUNET_free(data); + } + } - if (GNUNET_SYSERR == GNUNET_DISK_file_close(f_m)) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, - "close", - filename_master); - GNUNET_free (filename_master); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Data file successfully written to log file for master `%s'\n", filename_master); + for (c_s = 0; c_s < l->lp[c_m].peer->num_partners; c_s++) + { + if (GNUNET_SYSERR == GNUNET_DISK_file_close(f[c_s])) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot close log file for master[%u] slave[%u]\n", c_m, c_s); + continue; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Data file successfully written to log file for `%s'\n", + filename_slaves[c_s]); + } - if (GNUNET_YES == plots) - { - write_throughput_gnuplot_script (filename_master, &l->lp[c_m], filename_slaves, l->num_slaves); - write_rtt_gnuplot_script (filename_master, &l->lp[c_m], filename_slaves, l->num_slaves); - write_bw_gnuplot_script (filename_master, &l->lp[c_m], filename_slaves, l->num_slaves); + if (GNUNET_SYSERR == GNUNET_DISK_file_close(f_m)) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, + "close", + filename_master); + GNUNET_free(filename_master); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Data file successfully written to log file for master `%s'\n", filename_master); + + if (GNUNET_YES == plots) + { + write_throughput_gnuplot_script(filename_master, &l->lp[c_m], filename_slaves, l->num_slaves); + write_rtt_gnuplot_script(filename_master, &l->lp[c_m], filename_slaves, l->num_slaves); + write_bw_gnuplot_script(filename_master, &l->lp[c_m], filename_slaves, l->num_slaves); + } } - } - GNUNET_free (filename_master); + GNUNET_free(filename_master); } /** @@ -620,7 +615,7 @@ GNUNET_ATS_TEST_logging_write_to_file (struct LoggingHandle *l, * @param l logging handle to use */ void -GNUNET_ATS_TEST_logging_now (struct LoggingHandle *l) +GNUNET_ATS_TEST_logging_now(struct LoggingHandle *l) { struct LoggingPeer *bp; struct PeerLoggingTimestep *mlt; @@ -638,180 +633,180 @@ GNUNET_ATS_TEST_logging_now (struct LoggingHandle *l) return; for (c_m = 0; c_m < l->num_masters; c_m++) - { - bp = &l->lp[c_m]; - mlt = GNUNET_new (struct PeerLoggingTimestep); - GNUNET_CONTAINER_DLL_insert_tail(l->lp[c_m].head, l->lp[c_m].tail, mlt); - prev_log_mlt = mlt->prev; - - /* Collect data */ - /* Current master state */ - mlt->timestamp = GNUNET_TIME_absolute_get(); - mlt->total_bytes_sent = bp->peer->total_bytes_sent; - mlt->total_messages_sent = bp->peer->total_messages_sent; - mlt->total_bytes_received = bp->peer->total_bytes_received; - mlt->total_messages_received = bp->peer->total_messages_received; - - /* Throughput */ - if (NULL == prev_log_mlt) - { - /* Get difference to start */ - delta = GNUNET_TIME_absolute_get_difference (l->lp[c_m].start, mlt->timestamp); - } - else - { - /* Get difference to last timestep */ - delta = GNUNET_TIME_absolute_get_difference (mlt->prev->timestamp, mlt->timestamp); - } - - /* Multiplication factor for throughput calculation */ - mult = (double) GNUNET_TIME_UNIT_SECONDS.rel_value_us / (delta.rel_value_us); - - /* Total throughput */ - if (NULL != prev_log_mlt) - { - if (mlt->total_bytes_sent - mlt->prev->total_bytes_sent > 0) - { - mlt->total_throughput_send = mult * (mlt->total_bytes_sent - mlt->prev->total_bytes_sent); - } - else - { - mlt->total_throughput_send = 0; - // mlt->total_throughput_send = prev_log_mlt->total_throughput_send; /* no msgs send */ - } - - if (mlt->total_bytes_received - mlt->prev->total_bytes_received > 0) - { - mlt->total_throughput_recv = mult * (mlt->total_bytes_received - mlt->prev->total_bytes_received); - } - else - { - mlt->total_throughput_recv = 0; - //mlt->total_throughput_recv = prev_log_mlt->total_throughput_recv; /* no msgs received */ - } - } - else - { - mlt->total_throughput_send = mult * mlt->total_bytes_sent; - mlt->total_throughput_recv = mult * mlt->total_bytes_received; - } - - if (GNUNET_YES == l->verbose) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Master[%u] delta: %llu us, bytes (sent/received): %u / %u; throughput send/recv: %u / %u\n", - c_m, - (unsigned long long) delta.rel_value_us, - mlt->total_bytes_sent, - mlt->total_bytes_received, - mlt->total_throughput_send, - mlt->total_throughput_recv); - } - - mlt->slaves_log = GNUNET_malloc (bp->peer->num_partners * - sizeof (struct PartnerLoggingTimestep)); - - for (c_s = 0; c_s < bp->peer->num_partners; c_s++) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Collect logging data master[%u] slave [%u]\n", c_m, c_s); - - p = &bp->peer->partners[c_s]; - slt = &mlt->slaves_log[c_s]; - - slt->slave = p->dest; - /* Bytes sent from master to this slave */ - slt->total_bytes_sent = p->bytes_sent; - /* Messages sent from master to this slave */ - slt->total_messages_sent = p->messages_sent; - /* Bytes master received from this slave */ - slt->total_bytes_received = p->bytes_received; - /* Messages master received from this slave */ - slt->total_messages_received = p->messages_received; - slt->total_app_rtt = p->total_app_rtt; - /* ats performance information */ - slt->ats_delay = p->props.delay; - slt->ats_distance = p->props.distance; - slt->ats_network_type = p->props.scope; - slt->ats_utilization_in = p->props.utilization_out; - slt->ats_utilization_out = p->props.utilization_out; - slt->bandwidth_in = p->bandwidth_in; - slt->bandwidth_out = p->bandwidth_out; - slt->pref_bandwidth = p->pref_bandwidth; - slt->pref_delay = p->pref_delay; - - /* Total application level rtt */ + bp = &l->lp[c_m]; + mlt = GNUNET_new(struct PeerLoggingTimestep); + GNUNET_CONTAINER_DLL_insert_tail(l->lp[c_m].head, l->lp[c_m].tail, mlt); + prev_log_mlt = mlt->prev; + + /* Collect data */ + /* Current master state */ + mlt->timestamp = GNUNET_TIME_absolute_get(); + mlt->total_bytes_sent = bp->peer->total_bytes_sent; + mlt->total_messages_sent = bp->peer->total_messages_sent; + mlt->total_bytes_received = bp->peer->total_bytes_received; + mlt->total_messages_received = bp->peer->total_messages_received; + + /* Throughput */ if (NULL == prev_log_mlt) - { - if (0 != slt->total_messages_sent) - app_rtt = slt->total_app_rtt / slt->total_messages_sent; - else - app_rtt = 0; - } + { + /* Get difference to start */ + delta = GNUNET_TIME_absolute_get_difference(l->lp[c_m].start, mlt->timestamp); + } else - { - prev_log_slt = &prev_log_mlt->slaves_log[c_s]; - if ((slt->total_messages_sent - prev_log_slt->total_messages_sent) > 0) - app_rtt = (slt->total_app_rtt - prev_log_slt->total_app_rtt) / - (slt->total_messages_sent - prev_log_slt->total_messages_sent); - else { - app_rtt = prev_log_slt->app_rtt; /* No messages were */ + /* Get difference to last timestep */ + delta = GNUNET_TIME_absolute_get_difference(mlt->prev->timestamp, mlt->timestamp); } - } - slt->app_rtt = app_rtt; - /* Partner throughput */ + /* Multiplication factor for throughput calculation */ + mult = (double)GNUNET_TIME_UNIT_SECONDS.rel_value_us / (delta.rel_value_us); + + /* Total throughput */ if (NULL != prev_log_mlt) - { - prev_log_slt = &prev_log_mlt->slaves_log[c_s]; - if (slt->total_bytes_sent > prev_log_slt->total_bytes_sent) - slt->throughput_sent = mult * (slt->total_bytes_sent - prev_log_slt->total_bytes_sent); - else - slt->throughput_sent = 0; - - if (slt->total_bytes_received > prev_log_slt->total_bytes_received) - slt->throughput_recv = mult * - (slt->total_bytes_received - prev_log_slt->total_bytes_received); - else - slt->throughput_recv = 0; - } + { + if (mlt->total_bytes_sent - mlt->prev->total_bytes_sent > 0) + { + mlt->total_throughput_send = mult * (mlt->total_bytes_sent - mlt->prev->total_bytes_sent); + } + else + { + mlt->total_throughput_send = 0; + // mlt->total_throughput_send = prev_log_mlt->total_throughput_send; /* no msgs send */ + } + + if (mlt->total_bytes_received - mlt->prev->total_bytes_received > 0) + { + mlt->total_throughput_recv = mult * (mlt->total_bytes_received - mlt->prev->total_bytes_received); + } + else + { + mlt->total_throughput_recv = 0; + //mlt->total_throughput_recv = prev_log_mlt->total_throughput_recv; /* no msgs received */ + } + } else - { - slt->throughput_sent = mult * slt->total_bytes_sent; - slt->throughput_recv = mult * slt->total_bytes_received; - } + { + mlt->total_throughput_send = mult * mlt->total_bytes_sent; + mlt->total_throughput_recv = mult * mlt->total_bytes_received; + } if (GNUNET_YES == l->verbose) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Master [%u] -> Slave [%u]: delta: %llu us, bytes (sent/received): %u / %u; throughput send/recv: %u / %u\n", - c_m, c_s, - (unsigned long long) delta.rel_value_us, - mlt->total_bytes_sent, - mlt->total_bytes_received, - slt->throughput_sent, - slt->throughput_recv); - } - else - GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Master [%u]: slave [%u]\n", - bp->peer->no, p->dest->no); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Master[%u] delta: %llu us, bytes (sent/received): %u / %u; throughput send/recv: %u / %u\n", + c_m, + (unsigned long long)delta.rel_value_us, + mlt->total_bytes_sent, + mlt->total_bytes_received, + mlt->total_throughput_send, + mlt->total_throughput_recv); + } + + mlt->slaves_log = GNUNET_malloc(bp->peer->num_partners * + sizeof(struct PartnerLoggingTimestep)); + + for (c_s = 0; c_s < bp->peer->num_partners; c_s++) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Collect logging data master[%u] slave [%u]\n", c_m, c_s); + + p = &bp->peer->partners[c_s]; + slt = &mlt->slaves_log[c_s]; + + slt->slave = p->dest; + /* Bytes sent from master to this slave */ + slt->total_bytes_sent = p->bytes_sent; + /* Messages sent from master to this slave */ + slt->total_messages_sent = p->messages_sent; + /* Bytes master received from this slave */ + slt->total_bytes_received = p->bytes_received; + /* Messages master received from this slave */ + slt->total_messages_received = p->messages_received; + slt->total_app_rtt = p->total_app_rtt; + /* ats performance information */ + slt->ats_delay = p->props.delay; + slt->ats_distance = p->props.distance; + slt->ats_network_type = p->props.scope; + slt->ats_utilization_in = p->props.utilization_out; + slt->ats_utilization_out = p->props.utilization_out; + slt->bandwidth_in = p->bandwidth_in; + slt->bandwidth_out = p->bandwidth_out; + slt->pref_bandwidth = p->pref_bandwidth; + slt->pref_delay = p->pref_delay; + + /* Total application level rtt */ + if (NULL == prev_log_mlt) + { + if (0 != slt->total_messages_sent) + app_rtt = slt->total_app_rtt / slt->total_messages_sent; + else + app_rtt = 0; + } + else + { + prev_log_slt = &prev_log_mlt->slaves_log[c_s]; + if ((slt->total_messages_sent - prev_log_slt->total_messages_sent) > 0) + app_rtt = (slt->total_app_rtt - prev_log_slt->total_app_rtt) / + (slt->total_messages_sent - prev_log_slt->total_messages_sent); + else + { + app_rtt = prev_log_slt->app_rtt; /* No messages were */ + } + } + slt->app_rtt = app_rtt; + + /* Partner throughput */ + if (NULL != prev_log_mlt) + { + prev_log_slt = &prev_log_mlt->slaves_log[c_s]; + if (slt->total_bytes_sent > prev_log_slt->total_bytes_sent) + slt->throughput_sent = mult * (slt->total_bytes_sent - prev_log_slt->total_bytes_sent); + else + slt->throughput_sent = 0; + + if (slt->total_bytes_received > prev_log_slt->total_bytes_received) + slt->throughput_recv = mult * + (slt->total_bytes_received - prev_log_slt->total_bytes_received); + else + slt->throughput_recv = 0; + } + else + { + slt->throughput_sent = mult * slt->total_bytes_sent; + slt->throughput_recv = mult * slt->total_bytes_received; + } + + if (GNUNET_YES == l->verbose) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Master [%u] -> Slave [%u]: delta: %llu us, bytes (sent/received): %u / %u; throughput send/recv: %u / %u\n", + c_m, c_s, + (unsigned long long)delta.rel_value_us, + mlt->total_bytes_sent, + mlt->total_bytes_received, + slt->throughput_sent, + slt->throughput_recv); + } + else + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Master [%u]: slave [%u]\n", + bp->peer->no, p->dest->no); + } } - } } static void -collect_log_task (void *cls) +collect_log_task(void *cls) { struct LoggingHandle *l = cls; l->log_task = NULL; - GNUNET_ATS_TEST_logging_now (l); - l->log_task = GNUNET_SCHEDULER_add_delayed (l->frequency, - &collect_log_task, - l); + GNUNET_ATS_TEST_logging_now(l); + l->log_task = GNUNET_SCHEDULER_add_delayed(l->frequency, + &collect_log_task, + l); } @@ -821,20 +816,20 @@ collect_log_task (void *cls) * @param l the logging handle */ void -GNUNET_ATS_TEST_logging_stop (struct LoggingHandle *l) +GNUNET_ATS_TEST_logging_stop(struct LoggingHandle *l) { - if (GNUNET_YES!= l->running) + if (GNUNET_YES != l->running) return; if (NULL != l->log_task) - { - GNUNET_SCHEDULER_cancel (l->log_task); - l->log_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(l->log_task); + l->log_task = NULL; + } l->running = GNUNET_NO; GNUNET_log(GNUNET_ERROR_TYPE_INFO, - _("Stop logging\n")); + _("Stop logging\n")); } /** @@ -843,26 +838,26 @@ GNUNET_ATS_TEST_logging_stop (struct LoggingHandle *l) * @param l the logging handle */ void -GNUNET_ATS_TEST_logging_clean_up (struct LoggingHandle *l) +GNUNET_ATS_TEST_logging_clean_up(struct LoggingHandle *l) { int c_m; struct PeerLoggingTimestep *cur; if (GNUNET_YES == l->running) - GNUNET_ATS_TEST_logging_stop (l); + GNUNET_ATS_TEST_logging_stop(l); for (c_m = 0; c_m < l->num_masters; c_m++) - { - while (NULL != (cur = l->lp[c_m].head)) { - GNUNET_CONTAINER_DLL_remove (l->lp[c_m].head, l->lp[c_m].tail, cur); - GNUNET_free (cur->slaves_log); - GNUNET_free (cur); + while (NULL != (cur = l->lp[c_m].head)) + { + GNUNET_CONTAINER_DLL_remove(l->lp[c_m].head, l->lp[c_m].tail, cur); + GNUNET_free(cur->slaves_log); + GNUNET_free(cur); + } } - } - GNUNET_free (l->lp); - GNUNET_free (l); + GNUNET_free(l->lp); + GNUNET_free(l); } @@ -889,24 +884,24 @@ GNUNET_ATS_TEST_logging_start(struct GNUNET_TIME_Relative log_frequency, int c_m; GNUNET_log(GNUNET_ERROR_TYPE_INFO, - _("Start logging `%s'\n"), testname); + _("Start logging `%s'\n"), testname); - l = GNUNET_new (struct LoggingHandle); + l = GNUNET_new(struct LoggingHandle); l->num_masters = num_masters; l->num_slaves = num_slaves; l->name = testname; l->frequency = log_frequency; l->verbose = verbose; - l->lp = GNUNET_malloc (num_masters * sizeof (struct LoggingPeer)); + l->lp = GNUNET_malloc(num_masters * sizeof(struct LoggingPeer)); - for (c_m = 0; c_m < num_masters; c_m ++) - { - l->lp[c_m].peer = &masters[c_m]; - l->lp[c_m].start = GNUNET_TIME_absolute_get(); - } + for (c_m = 0; c_m < num_masters; c_m++) + { + l->lp[c_m].peer = &masters[c_m]; + l->lp[c_m].start = GNUNET_TIME_absolute_get(); + } /* Schedule logging task */ - l->log_task = GNUNET_SCHEDULER_add_now (&collect_log_task, l); + l->log_task = GNUNET_SCHEDULER_add_now(&collect_log_task, l); l->running = GNUNET_YES; return l; diff --git a/src/ats-tests/ats-testing-preferences.c b/src/ats-tests/ats-testing-preferences.c index ba2f133b9..a14e66736 100644 --- a/src/ats-tests/ats-testing-preferences.c +++ b/src/ats-tests/ats-testing-preferences.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2013 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2013 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -33,76 +33,82 @@ static struct PreferenceGenerator *pg_tail; extern struct GNUNET_ATS_TEST_Topology *top; static double -get_preference (struct PreferenceGenerator *pg) +get_preference(struct PreferenceGenerator *pg) { struct GNUNET_TIME_Relative time_delta; double delta_value; double pref_value; /* Calculate the current preference value */ - switch (pg->type) { + switch (pg->type) + { case GNUNET_ATS_TEST_TG_CONSTANT: pref_value = pg->base_value; break; + case GNUNET_ATS_TEST_TG_LINEAR: time_delta = GNUNET_TIME_absolute_get_duration(pg->time_start); /* Calculate point of time in the current period */ time_delta.rel_value_us = time_delta.rel_value_us % - pg->duration_period.rel_value_us; - delta_value = ((double) time_delta.rel_value_us / - pg->duration_period.rel_value_us) * (pg->max_value - pg->base_value); + pg->duration_period.rel_value_us; + delta_value = ((double)time_delta.rel_value_us / + pg->duration_period.rel_value_us) * (pg->max_value - pg->base_value); if ((pg->max_value < pg->base_value) && ((pg->max_value - pg->base_value) > pg->base_value)) - { - /* This will cause an underflow */ - GNUNET_break (0); - } + { + /* This will cause an underflow */ + GNUNET_break(0); + } pref_value = pg->base_value + delta_value; break; + case GNUNET_ATS_TEST_TG_RANDOM: - delta_value = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - 10000 * (pg->max_value - pg->base_value)) / 10000; + delta_value = (double)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + 10000 * (pg->max_value - pg->base_value)) / 10000; pref_value = pg->base_value + delta_value; break; + case GNUNET_ATS_TEST_TG_SINUS: time_delta = GNUNET_TIME_absolute_get_duration(pg->time_start); /* Calculate point of time in the current period */ time_delta.rel_value_us = time_delta.rel_value_us % - pg->duration_period.rel_value_us; + pg->duration_period.rel_value_us; if ((pg->max_value - pg->base_value) > pg->base_value) - { - /* This will cause an underflow for second half of sinus period, - * will be detected in general when experiments are loaded */ - GNUNET_break (0); - } + { + /* This will cause an underflow for second half of sinus period, + * will be detected in general when experiments are loaded */ + GNUNET_break(0); + } delta_value = (pg->max_value - pg->base_value) * - sin ( (2 * M_PI) / ((double) pg->duration_period.rel_value_us) * - time_delta.rel_value_us); + sin((2 * M_PI) / ((double)pg->duration_period.rel_value_us) * + time_delta.rel_value_us); pref_value = pg->base_value + delta_value; break; + default: pref_value = 0.0; break; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Current preference value is %f\n", - pref_value); + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Current preference value is %f\n", + pref_value); return pref_value; } static void -set_pref_task (void *cls) +set_pref_task(void *cls) { struct BenchmarkPartner *p = cls; double pref_value; + p->pg->set_task = NULL; - pref_value = get_preference (p->pg); + pref_value = get_preference(p->pg); GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Setting preference for master [%u] and slave [%u] for %s to %f\n", - p->me->no, p->dest->no, - GNUNET_ATS_print_preference_type (p->pg->kind), pref_value); + "Setting preference for master [%u] and slave [%u] for %s to %f\n", + p->me->no, p->dest->no, + GNUNET_ATS_print_preference_type(p->pg->kind), pref_value); GNUNET_ATS_performance_change_preference(p->me->ats_perf_handle, &p->dest->id, @@ -110,20 +116,22 @@ set_pref_task (void *cls) pref_value, GNUNET_ATS_PREFERENCE_END); - switch (p->pg->kind) { + switch (p->pg->kind) + { case GNUNET_ATS_PREFERENCE_BANDWIDTH: p->pref_bandwidth = pref_value; break; + case GNUNET_ATS_PREFERENCE_LATENCY: p->pref_delay = pref_value; break; + default: break; - } - - p->pg->set_task = GNUNET_SCHEDULER_add_delayed (p->pg->frequency, - set_pref_task, p); + } + p->pg->set_task = GNUNET_SCHEDULER_add_delayed(p->pg->frequency, + set_pref_task, p); } @@ -142,25 +150,25 @@ set_pref_task (void *cls) * @return the preference generator */ struct PreferenceGenerator * -GNUNET_ATS_TEST_generate_preferences_start (struct BenchmarkPeer *src, - struct BenchmarkPartner *dest, - enum GeneratorType type, - unsigned int base_value, - unsigned int value_rate, - struct GNUNET_TIME_Relative period, - struct GNUNET_TIME_Relative frequency, - enum GNUNET_ATS_PreferenceKind kind) +GNUNET_ATS_TEST_generate_preferences_start(struct BenchmarkPeer *src, + struct BenchmarkPartner *dest, + enum GeneratorType type, + unsigned int base_value, + unsigned int value_rate, + struct GNUNET_TIME_Relative period, + struct GNUNET_TIME_Relative frequency, + enum GNUNET_ATS_PreferenceKind kind) { struct PreferenceGenerator *pg; if (NULL != dest->pg) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } - pg = GNUNET_new (struct PreferenceGenerator); - GNUNET_CONTAINER_DLL_insert (pg_head, pg_tail, pg); + pg = GNUNET_new(struct PreferenceGenerator); + GNUNET_CONTAINER_DLL_insert(pg_head, pg_tail, pg); pg->type = type; pg->src = src; pg->dest = dest; @@ -171,58 +179,63 @@ GNUNET_ATS_TEST_generate_preferences_start (struct BenchmarkPeer *src, pg->frequency = frequency; pg->time_start = GNUNET_TIME_absolute_get(); - switch (type) { + switch (type) + { case GNUNET_ATS_TEST_TG_CONSTANT: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up constant preference generator master[%u] `%s' and slave [%u] `%s' max %u Bips\n", - dest->me->no, GNUNET_i2s (&dest->me->id), - dest->dest->no, GNUNET_i2s (&dest->dest->id), - base_value); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up constant preference generator master[%u] `%s' and slave [%u] `%s' max %u Bips\n", + dest->me->no, GNUNET_i2s(&dest->me->id), + dest->dest->no, GNUNET_i2s(&dest->dest->id), + base_value); break; + case GNUNET_ATS_TEST_TG_LINEAR: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up linear preference generator master[%u] `%s' and slave [%u] `%s' min %u Bips max %u Bips\n", - dest->me->no, GNUNET_i2s (&dest->me->id), - dest->dest->no, GNUNET_i2s (&dest->dest->id), - base_value, value_rate); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up linear preference generator master[%u] `%s' and slave [%u] `%s' min %u Bips max %u Bips\n", + dest->me->no, GNUNET_i2s(&dest->me->id), + dest->dest->no, GNUNET_i2s(&dest->dest->id), + base_value, value_rate); break; + case GNUNET_ATS_TEST_TG_SINUS: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up sinus preference generator master[%u] `%s' and slave [%u] `%s' baserate %u Bips, amplitude %u Bps\n", - dest->me->no, GNUNET_i2s (&dest->me->id), - dest->dest->no, GNUNET_i2s (&dest->dest->id), - base_value, value_rate); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up sinus preference generator master[%u] `%s' and slave [%u] `%s' baserate %u Bips, amplitude %u Bps\n", + dest->me->no, GNUNET_i2s(&dest->me->id), + dest->dest->no, GNUNET_i2s(&dest->dest->id), + base_value, value_rate); break; + case GNUNET_ATS_TEST_TG_RANDOM: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up random preference generator master[%u] `%s' and slave [%u] `%s' min %u Bips max %u Bps\n", - dest->me->no, GNUNET_i2s (&dest->me->id), - dest->dest->no, GNUNET_i2s (&dest->dest->id), - base_value, value_rate); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up random preference generator master[%u] `%s' and slave [%u] `%s' min %u Bips max %u Bps\n", + dest->me->no, GNUNET_i2s(&dest->me->id), + dest->dest->no, GNUNET_i2s(&dest->dest->id), + base_value, value_rate); break; + default: break; - } + } dest->pg = pg; - pg->set_task = GNUNET_SCHEDULER_add_now (&set_pref_task, dest); + pg->set_task = GNUNET_SCHEDULER_add_now(&set_pref_task, dest); return pg; } void -GNUNET_ATS_TEST_generate_preferences_stop (struct PreferenceGenerator *pg) +GNUNET_ATS_TEST_generate_preferences_stop(struct PreferenceGenerator *pg) { - GNUNET_CONTAINER_DLL_remove (pg_head, pg_tail, pg); + GNUNET_CONTAINER_DLL_remove(pg_head, pg_tail, pg); pg->dest->pg = NULL; if (NULL != pg->set_task) - { - GNUNET_SCHEDULER_cancel (pg->set_task); - pg->set_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(pg->set_task); + pg->set_task = NULL; + } - GNUNET_free (pg); + GNUNET_free(pg); } @@ -230,16 +243,17 @@ GNUNET_ATS_TEST_generate_preferences_stop (struct PreferenceGenerator *pg) * Stop all preferences generators */ void -GNUNET_ATS_TEST_generate_preferences_stop_all () +GNUNET_ATS_TEST_generate_preferences_stop_all() { struct PreferenceGenerator *cur; struct PreferenceGenerator *next; + next = pg_head; for (cur = next; NULL != cur; cur = next) - { + { next = cur->next; GNUNET_ATS_TEST_generate_preferences_stop(cur); - } + } } /* end of file ats-testing-preferences.c */ diff --git a/src/ats-tests/ats-testing-traffic.c b/src/ats-tests/ats-testing-traffic.c index 3756596c9..01462980c 100644 --- a/src/ats-tests/ats-testing-traffic.c +++ b/src/ats-tests/ats-testing-traffic.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2013, 2016 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2013, 2016 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -33,7 +33,7 @@ static struct TrafficGenerator *tg_tail; extern struct GNUNET_ATS_TEST_Topology *top; static struct GNUNET_TIME_Relative -get_delay (struct TrafficGenerator *tg) +get_delay(struct TrafficGenerator *tg) { struct GNUNET_TIME_Relative delay; struct GNUNET_TIME_Relative time_delta; @@ -43,65 +43,70 @@ get_delay (struct TrafficGenerator *tg) delay.rel_value_us = 0; /* Calculate the current transmission rate based on the type of traffic */ - switch (tg->type) { + switch (tg->type) + { case GNUNET_ATS_TEST_TG_CONSTANT: if (UINT32_MAX == tg->base_rate) return GNUNET_TIME_UNIT_ZERO; cur_rate = tg->base_rate; break; + case GNUNET_ATS_TEST_TG_LINEAR: time_delta = GNUNET_TIME_absolute_get_duration(tg->time_start); /* Calculate point of time in the current period */ time_delta.rel_value_us = time_delta.rel_value_us % tg->duration_period.rel_value_us; - delta_rate = ((double) time_delta.rel_value_us / tg->duration_period.rel_value_us) * - (tg->max_rate - tg->base_rate); + delta_rate = ((double)time_delta.rel_value_us / tg->duration_period.rel_value_us) * + (tg->max_rate - tg->base_rate); if ((tg->max_rate < tg->base_rate) && ((tg->max_rate - tg->base_rate) > tg->base_rate)) - { - /* This will cause an underflow */ - GNUNET_break (0); - } + { + /* This will cause an underflow */ + GNUNET_break(0); + } cur_rate = tg->base_rate + delta_rate; break; + case GNUNET_ATS_TEST_TG_RANDOM: - cur_rate = tg->base_rate + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - tg->max_rate - tg->base_rate); + cur_rate = tg->base_rate + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + tg->max_rate - tg->base_rate); break; + case GNUNET_ATS_TEST_TG_SINUS: time_delta = GNUNET_TIME_absolute_get_duration(tg->time_start); /* Calculate point of time in the current period */ time_delta.rel_value_us = time_delta.rel_value_us % tg->duration_period.rel_value_us; if ((tg->max_rate - tg->base_rate) > tg->base_rate) - { - /* This will cause an underflow for second half of sinus period, - * will be detected in general when experiments are loaded */ - GNUNET_break (0); - } + { + /* This will cause an underflow for second half of sinus period, + * will be detected in general when experiments are loaded */ + GNUNET_break(0); + } delta_rate = (tg->max_rate - tg->base_rate) * - sin ( (2 * M_PI) / ((double) tg->duration_period.rel_value_us) * time_delta.rel_value_us); + sin((2 * M_PI) / ((double)tg->duration_period.rel_value_us) * time_delta.rel_value_us); cur_rate = tg->base_rate + delta_rate; break; + default: return delay; break; - } + } if (cur_rate < 0) - { - cur_rate = 1; - } + { + cur_rate = 1; + } /* Calculate the delay for the next message based on the current delay */ - delay.rel_value_us = GNUNET_TIME_UNIT_SECONDS.rel_value_us * TEST_MESSAGE_SIZE / cur_rate; + delay.rel_value_us = GNUNET_TIME_UNIT_SECONDS.rel_value_us * TEST_MESSAGE_SIZE / cur_rate; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Current rate is %lld, calculated delay is %llu\n", - cur_rate, - (unsigned long long) delay.rel_value_us); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Current rate is %lld, calculated delay is %llu\n", + cur_rate, + (unsigned long long)delay.rel_value_us); return delay; } static void -update_ping_data (void *cls) +update_ping_data(void *cls) { struct BenchmarkPartner *p = cls; struct GNUNET_TIME_Relative delay; @@ -112,23 +117,23 @@ update_ping_data (void *cls) p->me->total_bytes_sent += TEST_MESSAGE_SIZE; if (NULL == p->tg) - { - GNUNET_break (0); - return; - } - delay = get_delay (p->tg); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Delay for next transmission %s\n", - GNUNET_STRINGS_relative_time_to_string (delay, - GNUNET_YES)); + { + GNUNET_break(0); + return; + } + delay = get_delay(p->tg); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Delay for next transmission %s\n", + GNUNET_STRINGS_relative_time_to_string(delay, + GNUNET_YES)); p->tg->next_ping_transmission - = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), - delay); + = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), + delay); } static void -comm_schedule_send (void *cls) +comm_schedule_send(void *cls) { struct BenchmarkPartner *p = cls; struct TestMessage *msg; @@ -136,25 +141,25 @@ comm_schedule_send (void *cls) p->tg->send_task = NULL; p->last_message_sent = GNUNET_TIME_absolute_get(); - env = GNUNET_MQ_msg (msg, - TEST_MESSAGE_TYPE_PING); - memset (msg->padding, - 'a', - sizeof (msg->padding)); - GNUNET_MQ_notify_sent (env, - &update_ping_data, - p); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Master [%u]: Sending PING to [%u]\n", - p->me->no, - p->dest->no); - GNUNET_MQ_send (p->mq, - env); + env = GNUNET_MQ_msg(msg, + TEST_MESSAGE_TYPE_PING); + memset(msg->padding, + 'a', + sizeof(msg->padding)); + GNUNET_MQ_notify_sent(env, + &update_ping_data, + p); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Master [%u]: Sending PING to [%u]\n", + p->me->no, + p->dest->no); + GNUNET_MQ_send(p->mq, + env); } static void -update_pong_data (void *cls) +update_pong_data(void *cls) { struct BenchmarkPartner *p = cls; @@ -166,49 +171,50 @@ update_pong_data (void *cls) void -GNUNET_ATS_TEST_traffic_handle_ping (struct BenchmarkPartner *p) +GNUNET_ATS_TEST_traffic_handle_ping(struct BenchmarkPartner *p) { struct TestMessage *msg; struct GNUNET_MQ_Envelope *env; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Slave [%u]: Received PING from [%u], sending PONG\n", - p->me->no, - p->dest->no); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Slave [%u]: Received PING from [%u], sending PONG\n", + p->me->no, + p->dest->no); p->messages_received++; p->bytes_received += TEST_MESSAGE_SIZE; p->me->total_messages_received++; p->me->total_bytes_received += TEST_MESSAGE_SIZE; - - env = GNUNET_MQ_msg (msg, - TEST_MESSAGE_TYPE_PING); - memset (msg->padding, - 'a', - sizeof (msg->padding)); - GNUNET_MQ_notify_sent (env, - &update_pong_data, - p); - GNUNET_MQ_send (p->mq, - env); + + env = GNUNET_MQ_msg(msg, + TEST_MESSAGE_TYPE_PING); + memset(msg->padding, + 'a', + sizeof(msg->padding)); + GNUNET_MQ_notify_sent(env, + &update_pong_data, + p); + GNUNET_MQ_send(p->mq, + env); } void -GNUNET_ATS_TEST_traffic_handle_pong (struct BenchmarkPartner *p) +GNUNET_ATS_TEST_traffic_handle_pong(struct BenchmarkPartner *p) { struct GNUNET_TIME_Relative left; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Master [%u]: Received PONG from [%u], next message\n", - p->me->no, - p->dest->no); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Master [%u]: Received PONG from [%u], next message\n", + p->me->no, + p->dest->no); p->messages_received++; p->bytes_received += TEST_MESSAGE_SIZE; p->me->total_messages_received++; p->me->total_bytes_received += TEST_MESSAGE_SIZE; p->total_app_rtt += GNUNET_TIME_absolute_get_difference(p->last_message_sent, - GNUNET_TIME_absolute_get()).rel_value_us; + GNUNET_TIME_absolute_get()).rel_value_us; /* Schedule next send event */ if (NULL == p->tg) @@ -216,23 +222,23 @@ GNUNET_ATS_TEST_traffic_handle_pong (struct BenchmarkPartner *p) left = GNUNET_TIME_absolute_get_remaining(p->tg->next_ping_transmission); if (UINT32_MAX == p->tg->base_rate) - { - p->tg->send_task = GNUNET_SCHEDULER_add_now (&comm_schedule_send, p); - } + { + p->tg->send_task = GNUNET_SCHEDULER_add_now(&comm_schedule_send, p); + } else if (0 == left.rel_value_us) - { - p->tg->send_task = GNUNET_SCHEDULER_add_now (&comm_schedule_send, p); - } + { + p->tg->send_task = GNUNET_SCHEDULER_add_now(&comm_schedule_send, p); + } else - { - /* Enforce minimum transmission rate 1 msg / sec */ - if (GNUNET_TIME_UNIT_SECONDS.rel_value_us == (left = GNUNET_TIME_relative_min (left, GNUNET_TIME_UNIT_SECONDS)).rel_value_us) - GNUNET_log(GNUNET_ERROR_TYPE_ERROR, - "Enforcing minimum send rate between master [%u] and slave [%u]\n", - p->me->no, p->dest->no); - p->tg->send_task = GNUNET_SCHEDULER_add_delayed (left, - &comm_schedule_send, p); - } + { + /* Enforce minimum transmission rate 1 msg / sec */ + if (GNUNET_TIME_UNIT_SECONDS.rel_value_us == (left = GNUNET_TIME_relative_min(left, GNUNET_TIME_UNIT_SECONDS)).rel_value_us) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Enforcing minimum send rate between master [%u] and slave [%u]\n", + p->me->no, p->dest->no); + p->tg->send_task = GNUNET_SCHEDULER_add_delayed(left, + &comm_schedule_send, p); + } } @@ -250,26 +256,26 @@ GNUNET_ATS_TEST_traffic_handle_pong (struct BenchmarkPartner *p) * @return the traffic generator */ struct TrafficGenerator * -GNUNET_ATS_TEST_generate_traffic_start (struct BenchmarkPeer *src, - struct BenchmarkPartner *dest, - enum GeneratorType type, - unsigned int base_rate, - unsigned int max_rate, - struct GNUNET_TIME_Relative period, - struct GNUNET_TIME_Relative duration) +GNUNET_ATS_TEST_generate_traffic_start(struct BenchmarkPeer *src, + struct BenchmarkPartner *dest, + enum GeneratorType type, + unsigned int base_rate, + unsigned int max_rate, + struct GNUNET_TIME_Relative period, + struct GNUNET_TIME_Relative duration) { struct TrafficGenerator *tg; if (NULL != dest->tg) - { - GNUNET_break (0); - return NULL; - } - - tg = GNUNET_new (struct TrafficGenerator); - GNUNET_CONTAINER_DLL_insert (tg_head, - tg_tail, - tg); + { + GNUNET_break(0); + return NULL; + } + + tg = GNUNET_new(struct TrafficGenerator); + GNUNET_CONTAINER_DLL_insert(tg_head, + tg_tail, + tg); tg->type = type; tg->src = src; tg->dest = dest; @@ -279,71 +285,76 @@ GNUNET_ATS_TEST_generate_traffic_start (struct BenchmarkPeer *src, tg->time_start = GNUNET_TIME_absolute_get(); tg->next_ping_transmission = GNUNET_TIME_UNIT_FOREVER_ABS; - switch (type) { - case GNUNET_ATS_TEST_TG_CONSTANT: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up constant traffic generator master[%u] `%s' and slave [%u] `%s' max %u Bips\n", - dest->me->no, - GNUNET_i2s (&dest->me->id), - dest->dest->no, - GNUNET_i2s (&dest->dest->id), - base_rate); - break; - case GNUNET_ATS_TEST_TG_LINEAR: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up linear traffic generator master[%u] `%s' and slave [%u] `%s' min %u Bips max %u Bips\n", - dest->me->no, - GNUNET_i2s (&dest->me->id), - dest->dest->no, - GNUNET_i2s (&dest->dest->id), - base_rate, - max_rate); - break; - case GNUNET_ATS_TEST_TG_SINUS: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up sinus traffic generator master[%u] `%s' and slave [%u] `%s' baserate %u Bips, amplitude %u Bps\n", - dest->me->no, - GNUNET_i2s (&dest->me->id), - dest->dest->no, - GNUNET_i2s (&dest->dest->id), - base_rate, - max_rate); - break; - case GNUNET_ATS_TEST_TG_RANDOM: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up random traffic generator master[%u] `%s' and slave [%u] `%s' min %u Bips max %u Bps\n", - dest->me->no, - GNUNET_i2s (&dest->me->id), - dest->dest->no, - GNUNET_i2s (&dest->dest->id), - base_rate, - max_rate); + switch (type) + { + case GNUNET_ATS_TEST_TG_CONSTANT: + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up constant traffic generator master[%u] `%s' and slave [%u] `%s' max %u Bips\n", + dest->me->no, + GNUNET_i2s(&dest->me->id), + dest->dest->no, + GNUNET_i2s(&dest->dest->id), + base_rate); + break; + + case GNUNET_ATS_TEST_TG_LINEAR: + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up linear traffic generator master[%u] `%s' and slave [%u] `%s' min %u Bips max %u Bips\n", + dest->me->no, + GNUNET_i2s(&dest->me->id), + dest->dest->no, + GNUNET_i2s(&dest->dest->id), + base_rate, + max_rate); + break; + + case GNUNET_ATS_TEST_TG_SINUS: + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up sinus traffic generator master[%u] `%s' and slave [%u] `%s' baserate %u Bips, amplitude %u Bps\n", + dest->me->no, + GNUNET_i2s(&dest->me->id), + dest->dest->no, + GNUNET_i2s(&dest->dest->id), + base_rate, + max_rate); break; + + case GNUNET_ATS_TEST_TG_RANDOM: + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up random traffic generator master[%u] `%s' and slave [%u] `%s' min %u Bips max %u Bps\n", + dest->me->no, + GNUNET_i2s(&dest->me->id), + dest->dest->no, + GNUNET_i2s(&dest->dest->id), + base_rate, + max_rate); + break; + default: break; - } + } dest->tg = tg; tg->send_task - = GNUNET_SCHEDULER_add_now (&comm_schedule_send, - dest); + = GNUNET_SCHEDULER_add_now(&comm_schedule_send, + dest); return tg; } void -GNUNET_ATS_TEST_generate_traffic_stop (struct TrafficGenerator *tg) +GNUNET_ATS_TEST_generate_traffic_stop(struct TrafficGenerator *tg) { - GNUNET_CONTAINER_DLL_remove (tg_head, - tg_tail, - tg); + GNUNET_CONTAINER_DLL_remove(tg_head, + tg_tail, + tg); tg->dest->tg = NULL; if (NULL != tg->send_task) - { - GNUNET_SCHEDULER_cancel (tg->send_task); - tg->send_task = NULL; - } - GNUNET_free (tg); + { + GNUNET_SCHEDULER_cancel(tg->send_task); + tg->send_task = NULL; + } + GNUNET_free(tg); } @@ -351,17 +362,17 @@ GNUNET_ATS_TEST_generate_traffic_stop (struct TrafficGenerator *tg) * Stop all traffic generators */ void -GNUNET_ATS_TEST_generate_traffic_stop_all () +GNUNET_ATS_TEST_generate_traffic_stop_all() { struct TrafficGenerator *cur; struct TrafficGenerator *next; next = tg_head; for (cur = next; NULL != cur; cur = next) - { - next = cur->next; - GNUNET_ATS_TEST_generate_traffic_stop(cur); - } + { + next = cur->next; + GNUNET_ATS_TEST_generate_traffic_stop(cur); + } } /* end of file ats-testing-traffic.c */ diff --git a/src/ats-tests/ats-testing.c b/src/ats-tests/ats-testing.c index d8b9e5ef5..696deb4bd 100644 --- a/src/ats-tests/ats-testing.c +++ b/src/ats-tests/ats-testing.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2013, 2016, 2017 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2013, 2016, 2017 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -30,8 +30,7 @@ /** * Connect peers with testbed */ -struct TestbedConnectOperation -{ +struct TestbedConnectOperation { /** * The benchmarking master initiating this connection */ @@ -59,7 +58,7 @@ struct GNUNET_ATS_TEST_Topology *top; * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { int c_m; int c_s; @@ -68,119 +67,119 @@ do_shutdown (void *cls) top->state.benchmarking = GNUNET_NO; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Benchmarking done\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Benchmarking done\n"); - GNUNET_ATS_TEST_generate_traffic_stop_all (); + GNUNET_ATS_TEST_generate_traffic_stop_all(); for (c_m = 0; c_m < top->num_masters; c_m++) - { - p = &top->mps[c_m]; - if (NULL != top->mps[c_m].peer_id_op) - { - GNUNET_TESTBED_operation_done (p->peer_id_op); - p->peer_id_op = NULL; - } - - if (NULL != p->ats_task) - GNUNET_SCHEDULER_cancel (p->ats_task); - p->ats_task = NULL; - - for (c_op = 0; c_op < p->num_partners; c_op++) - { - if ( (NULL != p->core_connect_ops) && - (NULL != p->core_connect_ops[c_op].connect_op) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Failed to connect peer 0 and %u\n", - c_op); - GNUNET_TESTBED_operation_done (p->core_connect_ops[c_op].connect_op); - p->core_connect_ops[c_op].connect_op = NULL; - } - } - - if (NULL != p->ats_perf_op) - { - GNUNET_TESTBED_operation_done (p->ats_perf_op); - p->ats_perf_op = NULL; - } - - if (NULL != p->comm_op) { - GNUNET_TESTBED_operation_done (p->comm_op); - p->comm_op = NULL; + p = &top->mps[c_m]; + if (NULL != top->mps[c_m].peer_id_op) + { + GNUNET_TESTBED_operation_done(p->peer_id_op); + p->peer_id_op = NULL; + } + + if (NULL != p->ats_task) + GNUNET_SCHEDULER_cancel(p->ats_task); + p->ats_task = NULL; + + for (c_op = 0; c_op < p->num_partners; c_op++) + { + if ((NULL != p->core_connect_ops) && + (NULL != p->core_connect_ops[c_op].connect_op)) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Failed to connect peer 0 and %u\n", + c_op); + GNUNET_TESTBED_operation_done(p->core_connect_ops[c_op].connect_op); + p->core_connect_ops[c_op].connect_op = NULL; + } + } + + if (NULL != p->ats_perf_op) + { + GNUNET_TESTBED_operation_done(p->ats_perf_op); + p->ats_perf_op = NULL; + } + + if (NULL != p->comm_op) + { + GNUNET_TESTBED_operation_done(p->comm_op); + p->comm_op = NULL; + } + GNUNET_free_non_null(p->core_connect_ops); + GNUNET_free(p->partners); + p->partners = NULL; } - GNUNET_free_non_null (p->core_connect_ops); - GNUNET_free(p->partners); - p->partners = NULL; - } for (c_s = 0; c_s < top->num_slaves; c_s++) - { - p = &top->sps[c_s]; - if (NULL != p->peer_id_op) - { - GNUNET_TESTBED_operation_done (p->peer_id_op); - p->peer_id_op = NULL; - } - if (NULL != p->ats_perf_op) - { - GNUNET_TESTBED_operation_done (p->ats_perf_op); - p->ats_perf_op = NULL; - } - if (NULL != p->comm_op) { - GNUNET_TESTBED_operation_done (p->comm_op); - p->comm_op = NULL; + p = &top->sps[c_s]; + if (NULL != p->peer_id_op) + { + GNUNET_TESTBED_operation_done(p->peer_id_op); + p->peer_id_op = NULL; + } + if (NULL != p->ats_perf_op) + { + GNUNET_TESTBED_operation_done(p->ats_perf_op); + p->ats_perf_op = NULL; + } + if (NULL != p->comm_op) + { + GNUNET_TESTBED_operation_done(p->comm_op); + p->comm_op = NULL; + } + GNUNET_free(p->partners); + p->partners = NULL; } - GNUNET_free(p->partners); - p->partners = NULL; - } - GNUNET_SCHEDULER_shutdown (); - GNUNET_free (top); + GNUNET_SCHEDULER_shutdown(); + GNUNET_free(top); top = NULL; } static struct BenchmarkPartner * -find_partner (struct BenchmarkPeer *me, - const struct GNUNET_PeerIdentity *peer) +find_partner(struct BenchmarkPeer *me, + const struct GNUNET_PeerIdentity *peer) { int c_m; for (c_m = 0; c_m < me->num_partners; c_m++) - { - /* Find a partner with other as destination */ - if (0 == GNUNET_memcmp (peer, - &me->partners[c_m].dest->id)) { - return &me->partners[c_m]; + /* Find a partner with other as destination */ + if (0 == GNUNET_memcmp(peer, + &me->partners[c_m].dest->id)) + { + return &me->partners[c_m]; + } } - } return NULL; } static struct BenchmarkPeer * -find_peer (const struct GNUNET_PeerIdentity * peer) +find_peer(const struct GNUNET_PeerIdentity * peer) { int c_p; for (c_p = 0; c_p < top->num_masters; c_p++) - { - if (0 == GNUNET_memcmp (&top->mps[c_p].id, - peer)) - return &top->mps[c_p]; - } + { + if (0 == GNUNET_memcmp(&top->mps[c_p].id, + peer)) + return &top->mps[c_p]; + } for (c_p = 0; c_p < top->num_slaves; c_p++) - { - if (0 == GNUNET_memcmp (&top->sps[c_p].id, - peer)) - return &top->sps[c_p]; - } - return NULL ; + { + if (0 == GNUNET_memcmp(&top->sps[c_p].id, + peer)) + return &top->sps[c_p]; + } + return NULL; } @@ -193,9 +192,9 @@ find_peer (const struct GNUNET_PeerIdentity * peer) * @return the `struct BenchmarkPartner` of @a peer */ static void * -comm_connect_cb (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +comm_connect_cb(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { struct BenchmarkPeer *me = cls; struct BenchmarkPeer *remote; @@ -204,60 +203,60 @@ comm_connect_cb (void *cls, int c; int completed; - remote = find_peer (peer); + remote = find_peer(peer); if (NULL == remote) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Unknown peer connected: `%s'\n", - GNUNET_i2s (peer)); - GNUNET_break (0); - return NULL; - } - - id = GNUNET_strdup (GNUNET_i2s (&me->id)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "%s [%u] `%s' connected to %s [%u] %s\n", - (me->master == GNUNET_YES) ? "Master": "Slave", - me->no, - id, - (remote->master == GNUNET_YES) ? "Master": "Slave", - remote->no, - GNUNET_i2s (peer)); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Unknown peer connected: `%s'\n", + GNUNET_i2s(peer)); + GNUNET_break(0); + return NULL; + } + + id = GNUNET_strdup(GNUNET_i2s(&me->id)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "%s [%u] `%s' connected to %s [%u] %s\n", + (me->master == GNUNET_YES) ? "Master" : "Slave", + me->no, + id, + (remote->master == GNUNET_YES) ? "Master" : "Slave", + remote->no, + GNUNET_i2s(peer)); me->core_connections++; if ((GNUNET_YES == me->master) && (GNUNET_NO == remote->master) && (GNUNET_NO == top->state.connected_CORE)) - { - me->core_slave_connections++; - - if (me->core_slave_connections == top->num_slaves) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Master [%u] connected all slaves\n", - me->no); - } - completed = GNUNET_YES; - for (c = 0; c < top->num_masters; c++) - { - if (top->mps[c].core_slave_connections != top->num_slaves) - completed = GNUNET_NO; - } - if (GNUNET_YES == completed) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "All master peers connected all slave peers\n"); - top->state.connected_CORE = GNUNET_YES; - /* Notify about setup done */ - if (NULL != top->done_cb) - top->done_cb (top->done_cb_cls, - top->mps, - top->sps); + me->core_slave_connections++; + + if (me->core_slave_connections == top->num_slaves) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Master [%u] connected all slaves\n", + me->no); + } + completed = GNUNET_YES; + for (c = 0; c < top->num_masters; c++) + { + if (top->mps[c].core_slave_connections != top->num_slaves) + completed = GNUNET_NO; + } + if (GNUNET_YES == completed) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "All master peers connected all slave peers\n"); + top->state.connected_CORE = GNUNET_YES; + /* Notify about setup done */ + if (NULL != top->done_cb) + top->done_cb(top->done_cb_cls, + top->mps, + top->sps); + } } - } - GNUNET_free (id); - p = find_partner (me, - peer); + GNUNET_free(id); + p = find_partner(me, + peer); if (NULL != p) p->mq = mq; return p; @@ -270,9 +269,9 @@ comm_connect_cb (void *cls, * @param internal_cls the `struct BenchmarkPartner` of @a peer */ static void -comm_disconnect_cb (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *internal_cls) +comm_disconnect_cb(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *internal_cls) { struct BenchmarkPeer *me = cls; struct BenchmarkPartner *p = internal_cls; @@ -281,169 +280,170 @@ comm_disconnect_cb (void *cls, if (NULL == p) return; - id = GNUNET_strdup (GNUNET_i2s (&me->id)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "%s disconnected from %s\n", - id, - GNUNET_i2s (peer)); - GNUNET_assert (me->core_connections > 0); + id = GNUNET_strdup(GNUNET_i2s(&me->id)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "%s disconnected from %s\n", + id, + GNUNET_i2s(peer)); + GNUNET_assert(me->core_connections > 0); me->core_connections--; - if ( (GNUNET_YES == top->state.benchmarking) && - ( (GNUNET_YES == me->master) || - (GNUNET_YES == p->dest->master) ) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "%s disconnected from %s while benchmarking\n", - id, - GNUNET_i2s (peer)); - } + if ((GNUNET_YES == top->state.benchmarking) && + ((GNUNET_YES == me->master) || + (GNUNET_YES == p->dest->master))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "%s disconnected from %s while benchmarking\n", + id, + GNUNET_i2s(peer)); + } GNUNET_free(id); } static void -handle_pong (void *cls, - const struct TestMessage *message) +handle_pong(void *cls, + const struct TestMessage *message) { struct BenchmarkPartner *p = cls; - GNUNET_ATS_TEST_traffic_handle_pong (p); + GNUNET_ATS_TEST_traffic_handle_pong(p); } static void -handle_ping (void *cls, - const struct TestMessage *message) +handle_ping(void *cls, + const struct TestMessage *message) { struct BenchmarkPartner *p = cls; - GNUNET_ATS_TEST_traffic_handle_ping (p); + GNUNET_ATS_TEST_traffic_handle_ping(p); } static void * -transport_connect_adapter (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +transport_connect_adapter(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct BenchmarkPeer *me = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (ping, - TEST_MESSAGE_TYPE_PING, - struct TestMessage, - me), - GNUNET_MQ_hd_fixed_size (pong, - TEST_MESSAGE_TYPE_PONG, - struct TestMessage, - me), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(ping, + TEST_MESSAGE_TYPE_PING, + struct TestMessage, + me), + GNUNET_MQ_hd_fixed_size(pong, + TEST_MESSAGE_TYPE_PONG, + struct TestMessage, + me), + GNUNET_MQ_handler_end() }; - me->th = GNUNET_TRANSPORT_core_connect (cfg, - &me->id, - handlers, - me, - &comm_connect_cb, - &comm_disconnect_cb, - NULL); + me->th = GNUNET_TRANSPORT_core_connect(cfg, + &me->id, + handlers, + me, + &comm_connect_cb, + &comm_disconnect_cb, + NULL); if (NULL == me->th) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create transport connection \n"); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create transport connection \n"); return me->th; } static void -transport_disconnect_adapter (void *cls, - void *op_result) +transport_disconnect_adapter(void *cls, + void *op_result) { struct BenchmarkPeer *me = cls; - GNUNET_TRANSPORT_core_disconnect (me->th); + GNUNET_TRANSPORT_core_disconnect(me->th); me->th = NULL; } static void * -core_connect_adapter (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +core_connect_adapter(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct BenchmarkPeer *me = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (ping, - TEST_MESSAGE_TYPE_PING, - struct TestMessage, - me), - GNUNET_MQ_hd_fixed_size (pong, - TEST_MESSAGE_TYPE_PONG, - struct TestMessage, - me), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(ping, + TEST_MESSAGE_TYPE_PING, + struct TestMessage, + me), + GNUNET_MQ_hd_fixed_size(pong, + TEST_MESSAGE_TYPE_PONG, + struct TestMessage, + me), + GNUNET_MQ_handler_end() }; - me->ch = GNUNET_CORE_connect (cfg, - me, - NULL, - &comm_connect_cb, - &comm_disconnect_cb, - handlers); + me->ch = GNUNET_CORE_connect(cfg, + me, + NULL, + &comm_connect_cb, + &comm_disconnect_cb, + handlers); if (NULL == me->ch) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create core connection \n"); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create core connection \n"); return me->ch; } static void -core_disconnect_adapter (void *cls, - void *op_result) +core_disconnect_adapter(void *cls, + void *op_result) { struct BenchmarkPeer *me = cls; - GNUNET_CORE_disconnect (me->ch); + GNUNET_CORE_disconnect(me->ch); me->ch = NULL; } static void -connect_completion_callback (void *cls, - struct GNUNET_TESTBED_Operation *op, - const char *emsg) +connect_completion_callback(void *cls, + struct GNUNET_TESTBED_Operation *op, + const char *emsg) { struct TestbedConnectOperation *cop = cls; static int ops = 0; int c; + if (NULL == emsg) - { - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - _("Connected master [%u] with slave [%u]\n"), - cop->master->no, - cop->slave->no); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Connected master [%u] with slave [%u]\n"), + cop->master->no, + cop->slave->no); + } else - { - GNUNET_log(GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect master peer [%u] with slave [%u]\n"), - cop->master->no, cop->slave->no); - GNUNET_break(0); - GNUNET_SCHEDULER_shutdown (); - } - GNUNET_TESTBED_operation_done (op); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect master peer [%u] with slave [%u]\n"), + cop->master->no, cop->slave->no); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + } + GNUNET_TESTBED_operation_done(op); ops++; for (c = 0; c < top->num_slaves; c++) - { - if (cop == &cop->master->core_connect_ops[c]) - cop->master->core_connect_ops[c].connect_op = NULL; - } + { + if (cop == &cop->master->core_connect_ops[c]) + cop->master->core_connect_ops[c].connect_op = NULL; + } if (ops == top->num_masters * top->num_slaves) - { - top->state.connected_PEERS = GNUNET_YES; - } + { + top->state.connected_PEERS = GNUNET_YES; + } } static void -do_connect_peers (void *cls) +do_connect_peers(void *cls) { int c_m; int c_s; @@ -453,142 +453,143 @@ do_connect_peers (void *cls) (top->state.connected_COMM_service == GNUNET_NO)) return; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Connecting peers on CORE level\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Connecting peers on CORE level\n"); for (c_m = 0; c_m < top->num_masters; c_m++) - { - p = &top->mps[c_m]; - p->core_connect_ops = GNUNET_malloc (top->num_slaves * - sizeof (struct TestbedConnectOperation)); - - for (c_s = 0; c_s < top->num_slaves; c_s++) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Connecting master [%u] with slave [%u]\n", - p->no, - top->sps[c_s].no); - p->core_connect_ops[c_s].master = p; - p->core_connect_ops[c_s].slave = &top->sps[c_s]; - p->core_connect_ops[c_s].connect_op - = GNUNET_TESTBED_overlay_connect (NULL, - &connect_completion_callback, - &p->core_connect_ops[c_s], - top->sps[c_s].peer, - p->peer); - if (NULL == p->core_connect_ops[c_s].connect_op) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not connect master [%u] and slave [%u]\n", - p->no, - top->sps[c_s].no); - GNUNET_break(0); - GNUNET_SCHEDULER_shutdown (); - return; - } + p = &top->mps[c_m]; + p->core_connect_ops = GNUNET_malloc(top->num_slaves * + sizeof(struct TestbedConnectOperation)); + + for (c_s = 0; c_s < top->num_slaves; c_s++) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Connecting master [%u] with slave [%u]\n", + p->no, + top->sps[c_s].no); + p->core_connect_ops[c_s].master = p; + p->core_connect_ops[c_s].slave = &top->sps[c_s]; + p->core_connect_ops[c_s].connect_op + = GNUNET_TESTBED_overlay_connect(NULL, + &connect_completion_callback, + &p->core_connect_ops[c_s], + top->sps[c_s].peer, + p->peer); + if (NULL == p->core_connect_ops[c_s].connect_op) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not connect master [%u] and slave [%u]\n", + p->no, + top->sps[c_s].no); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + } } - } } static void -comm_connect_completion_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg) +comm_connect_completion_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg) { static int comm_done = 0; if ((NULL != emsg) || (NULL == ca_result)) - { - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Initialization failed, shutdown\n"); - GNUNET_break(0); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Initialization failed, shutdown\n"); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } comm_done++; if (comm_done == top->num_slaves + top->num_masters) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Connected to all %s services\n", - (GNUNET_YES == top->test_core) ? "CORE" : "TRANSPORT"); - top->state.connected_COMM_service = GNUNET_YES; - GNUNET_SCHEDULER_add_now (&do_connect_peers, - NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Connected to all %s services\n", + (GNUNET_YES == top->test_core) ? "CORE" : "TRANSPORT"); + top->state.connected_COMM_service = GNUNET_YES; + GNUNET_SCHEDULER_add_now(&do_connect_peers, + NULL); + } } static void -do_comm_connect (void *cls) +do_comm_connect(void *cls) { int c_s; int c_m; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Connecting to all %s services\n", - (GNUNET_YES == top->test_core) ? "CORE" : "TRANSPORT"); + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Connecting to all %s services\n", + (GNUNET_YES == top->test_core) ? "CORE" : "TRANSPORT"); for (c_m = 0; c_m < top->num_masters; c_m++) - { - if (GNUNET_YES == top->test_core) - top->mps[c_m].comm_op - = GNUNET_TESTBED_service_connect (NULL, - top->mps[c_m].peer, - "core", - &comm_connect_completion_cb, - NULL, - &core_connect_adapter, - &core_disconnect_adapter, - &top->mps[c_m]); - else { - top->mps[c_m].comm_op - = GNUNET_TESTBED_service_connect (NULL, - top->mps[c_m].peer, - "transport", - &comm_connect_completion_cb, - NULL, - &transport_connect_adapter, - &transport_disconnect_adapter, - &top->mps[c_m]); + if (GNUNET_YES == top->test_core) + top->mps[c_m].comm_op + = GNUNET_TESTBED_service_connect(NULL, + top->mps[c_m].peer, + "core", + &comm_connect_completion_cb, + NULL, + &core_connect_adapter, + &core_disconnect_adapter, + &top->mps[c_m]); + else + { + top->mps[c_m].comm_op + = GNUNET_TESTBED_service_connect(NULL, + top->mps[c_m].peer, + "transport", + &comm_connect_completion_cb, + NULL, + &transport_connect_adapter, + &transport_disconnect_adapter, + &top->mps[c_m]); + } } - } for (c_s = 0; c_s < top->num_slaves; c_s++) - { - if (GNUNET_YES == top->test_core) - top->sps[c_s].comm_op - = GNUNET_TESTBED_service_connect (NULL, - top->sps[c_s].peer, - "core", - &comm_connect_completion_cb, - NULL, - &core_connect_adapter, - &core_disconnect_adapter, - &top->sps[c_s]); - else { - top->sps[c_s].comm_op - = GNUNET_TESTBED_service_connect (NULL, - top->sps[c_s].peer, - "transport", - &comm_connect_completion_cb, - NULL, - &transport_connect_adapter, - &transport_disconnect_adapter, - &top->sps[c_s]); + if (GNUNET_YES == top->test_core) + top->sps[c_s].comm_op + = GNUNET_TESTBED_service_connect(NULL, + top->sps[c_s].peer, + "core", + &comm_connect_completion_cb, + NULL, + &core_connect_adapter, + &core_disconnect_adapter, + &top->sps[c_s]); + else + { + top->sps[c_s].comm_op + = GNUNET_TESTBED_service_connect(NULL, + top->sps[c_s].peer, + "transport", + &comm_connect_completion_cb, + NULL, + &transport_connect_adapter, + &transport_disconnect_adapter, + &top->sps[c_s]); + } } - } } static void -ats_performance_info_cb (void *cls, - const struct GNUNET_HELLO_Address *address, - int address_active, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, - const struct GNUNET_ATS_Properties *ats_prop) +ats_performance_info_cb(void *cls, + const struct GNUNET_HELLO_Address *address, + int address_active, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, + const struct GNUNET_ATS_Properties *ats_prop) { struct BenchmarkPeer *me = cls; struct BenchmarkPartner *p; @@ -596,36 +597,36 @@ ats_performance_info_cb (void *cls, char *peer_id; if (NULL == address) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Peer %u: ATS Service disconnected!\n", - me->no); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Peer %u: ATS Service disconnected!\n", + me->no); + return; + } - p = find_partner (me, - &address->peer); + p = find_partner(me, + &address->peer); if (NULL == p) - { - /* This is not one of my partners - * Will happen since the peers will connect to each other due to gossiping - */ - return; - } - peer_id = GNUNET_strdup (GNUNET_i2s (&me->id)); + { + /* This is not one of my partners + * Will happen since the peers will connect to each other due to gossiping + */ + return; + } + peer_id = GNUNET_strdup(GNUNET_i2s(&me->id)); log = GNUNET_NO; - if ((p->bandwidth_in != ntohl (bandwidth_in.value__)) || - (p->bandwidth_out != ntohl (bandwidth_out.value__))) - log = GNUNET_YES; - p->bandwidth_in = ntohl (bandwidth_in.value__); - p->bandwidth_out = ntohl (bandwidth_out.value__); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "%s [%u] received ATS information: %s\n", - (GNUNET_YES == p->me->master) ? "Master" : "Slave", - p->me->no, - GNUNET_i2s (&p->dest->id)); + if ((p->bandwidth_in != ntohl(bandwidth_in.value__)) || + (p->bandwidth_out != ntohl(bandwidth_out.value__))) + log = GNUNET_YES; + p->bandwidth_in = ntohl(bandwidth_in.value__); + p->bandwidth_out = ntohl(bandwidth_out.value__); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "%s [%u] received ATS information: %s\n", + (GNUNET_YES == p->me->master) ? "Master" : "Slave", + p->me->no, + GNUNET_i2s(&p->dest->id)); p->props.utilization_out = ats_prop->utilization_out; p->props.utilization_in = ats_prop->utilization_in; @@ -634,113 +635,113 @@ ats_performance_info_cb (void *cls, p->props.distance = ats_prop->distance; if (GNUNET_YES == log) - top->ats_perf_cb (cls, address, - address_active, - bandwidth_out, - bandwidth_in, - ats_prop); + top->ats_perf_cb(cls, address, + address_active, + bandwidth_out, + bandwidth_in, + ats_prop); GNUNET_free(peer_id); } static void * -ats_perf_connect_adapter (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +ats_perf_connect_adapter(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct BenchmarkPeer *me = cls; me->ats_perf_handle - = GNUNET_ATS_performance_init (cfg, - &ats_performance_info_cb, - me); + = GNUNET_ATS_performance_init(cfg, + &ats_performance_info_cb, + me); if (NULL == me->ats_perf_handle) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create ATS performance handle \n"); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create ATS performance handle \n"); return me->ats_perf_handle; } static void -ats_perf_disconnect_adapter (void *cls, - void *op_result) +ats_perf_disconnect_adapter(void *cls, + void *op_result) { struct BenchmarkPeer *me = cls; - GNUNET_ATS_performance_done (me->ats_perf_handle); + GNUNET_ATS_performance_done(me->ats_perf_handle); me->ats_perf_handle = NULL; } static void -ats_connect_completion_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg) +ats_connect_completion_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg) { static int op_done = 0; if ((NULL != emsg) || (NULL == ca_result)) - { - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Initialization failed, shutdown\n"); - GNUNET_break(0); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Initialization failed, shutdown\n"); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } op_done++; if (op_done == (top->num_masters + top->num_slaves)) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Connected to all ATS services\n"); - top->state.connected_ATS_service = GNUNET_YES; - GNUNET_SCHEDULER_add_now (&do_comm_connect, - NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Connected to all ATS services\n"); + top->state.connected_ATS_service = GNUNET_YES; + GNUNET_SCHEDULER_add_now(&do_comm_connect, + NULL); + } } static void -do_connect_ats (void *cls) +do_connect_ats(void *cls) { int c_m; int c_s; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Connecting to all ATS services\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Connecting to all ATS services\n"); for (c_m = 0; c_m < top->num_masters; c_m++) - { - top->mps[c_m].ats_perf_op - = GNUNET_TESTBED_service_connect (NULL, - top->mps[c_m].peer, - "ats", - &ats_connect_completion_cb, - NULL, - &ats_perf_connect_adapter, - &ats_perf_disconnect_adapter, - &top->mps[c_m]); - } + { + top->mps[c_m].ats_perf_op + = GNUNET_TESTBED_service_connect(NULL, + top->mps[c_m].peer, + "ats", + &ats_connect_completion_cb, + NULL, + &ats_perf_connect_adapter, + &ats_perf_disconnect_adapter, + &top->mps[c_m]); + } for (c_s = 0; c_s < top->num_slaves; c_s++) - { - top->sps[c_s].ats_perf_op - = GNUNET_TESTBED_service_connect (NULL, - top->sps[c_s].peer, - "ats", - &ats_connect_completion_cb, - NULL, - &ats_perf_connect_adapter, - &ats_perf_disconnect_adapter, - &top->sps[c_s]); - } + { + top->sps[c_s].ats_perf_op + = GNUNET_TESTBED_service_connect(NULL, + top->sps[c_s].peer, + "ats", + &ats_connect_completion_cb, + NULL, + &ats_perf_connect_adapter, + &ats_perf_disconnect_adapter, + &top->sps[c_s]); + } } static void -peerinformation_cb (void *cb_cls, - struct GNUNET_TESTBED_Operation *op, - const struct GNUNET_TESTBED_PeerInformation *pinfo, - const char *emsg) +peerinformation_cb(void *cb_cls, + struct GNUNET_TESTBED_Operation *op, + const struct GNUNET_TESTBED_PeerInformation *pinfo, + const char *emsg) { struct BenchmarkPeer *p = cb_cls; static int done = 0; @@ -748,23 +749,23 @@ peerinformation_cb (void *cb_cls, GNUNET_assert(pinfo->pit == GNUNET_TESTBED_PIT_IDENTITY); p->id = *pinfo->result.id; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "%s [%u] has peer id `%s'\n", - (p->master == GNUNET_YES) ? "Master" : "Slave", - p->no, - GNUNET_i2s (&p->id)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "%s [%u] has peer id `%s'\n", + (p->master == GNUNET_YES) ? "Master" : "Slave", + p->no, + GNUNET_i2s(&p->id)); - GNUNET_TESTBED_operation_done (op); + GNUNET_TESTBED_operation_done(op); p->peer_id_op = NULL; done++; if (done == top->num_slaves + top->num_masters) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Retrieved all peer ID, connect to ATS\n"); - GNUNET_SCHEDULER_add_now (&do_connect_ats, - NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Retrieved all peer ID, connect to ATS\n"); + GNUNET_SCHEDULER_add_now(&do_connect_ats, + NULL); + } } @@ -781,85 +782,85 @@ peerinformation_cb (void *cb_cls, * failed */ static void -main_run (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers_, - unsigned int links_succeeded, - unsigned int links_failed) +main_run(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers_, + unsigned int links_succeeded, + unsigned int links_failed) { int c_m; int c_s; - GNUNET_assert (NULL == cls); - GNUNET_assert (top->num_masters + top->num_slaves == num_peers); - GNUNET_assert (NULL != peers_); + GNUNET_assert(NULL == cls); + GNUNET_assert(top->num_masters + top->num_slaves == num_peers); + GNUNET_assert(NULL != peers_); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - top); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + top); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up %u masters and %u slaves\n", - top->num_masters, - top->num_slaves); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up %u masters and %u slaves\n", + top->num_masters, + top->num_slaves); /* Setup master peers */ for (c_m = 0; c_m < top->num_masters; c_m++) - { - GNUNET_assert(NULL != peers_[c_m]); - top->mps[c_m].peer = peers_[c_m]; - top->mps[c_m].no = c_m; - top->mps[c_m].master = GNUNET_YES; - top->mps[c_m].pref_partner = &top->sps[c_m]; - top->mps[c_m].pref_value = TEST_ATS_PREFERENCE_DEFAULT; - top->mps[c_m].partners = - GNUNET_malloc (top->num_slaves * sizeof (struct BenchmarkPartner)); - top->mps[c_m].num_partners = top->num_slaves; - /* Initialize partners */ - for (c_s = 0; c_s < top->num_slaves; c_s++) { - top->mps[c_m].partners[c_s].me = &top->mps[c_m]; - top->mps[c_m].partners[c_s].dest = &top->sps[c_s]; + GNUNET_assert(NULL != peers_[c_m]); + top->mps[c_m].peer = peers_[c_m]; + top->mps[c_m].no = c_m; + top->mps[c_m].master = GNUNET_YES; + top->mps[c_m].pref_partner = &top->sps[c_m]; + top->mps[c_m].pref_value = TEST_ATS_PREFERENCE_DEFAULT; + top->mps[c_m].partners = + GNUNET_malloc(top->num_slaves * sizeof(struct BenchmarkPartner)); + top->mps[c_m].num_partners = top->num_slaves; + /* Initialize partners */ + for (c_s = 0; c_s < top->num_slaves; c_s++) + { + top->mps[c_m].partners[c_s].me = &top->mps[c_m]; + top->mps[c_m].partners[c_s].dest = &top->sps[c_s]; + } + /* Get configuration */ + top->mps[c_m].peer_id_op + = GNUNET_TESTBED_peer_get_information(top->mps[c_m].peer, + GNUNET_TESTBED_PIT_IDENTITY, + &peerinformation_cb, + &top->mps[c_m]); } - /* Get configuration */ - top->mps[c_m].peer_id_op - = GNUNET_TESTBED_peer_get_information (top->mps[c_m].peer, - GNUNET_TESTBED_PIT_IDENTITY, - &peerinformation_cb, - &top->mps[c_m]); - } /* Setup slave peers */ for (c_s = 0; c_s < top->num_slaves; c_s++) - { - GNUNET_assert(NULL != peers_[c_s + top->num_masters]); - top->sps[c_s].peer = peers_[c_s + top->num_masters]; - top->sps[c_s].no = c_s + top->num_masters; - top->sps[c_s].master = GNUNET_NO; - top->sps[c_s].partners = - GNUNET_new_array (top->num_masters, - struct BenchmarkPartner); - top->sps[c_s].num_partners = top->num_masters; - /* Initialize partners */ - for (c_m = 0; c_m < top->num_masters; c_m++) { - top->sps[c_s].partners[c_m].me = &top->sps[c_s]; - top->sps[c_s].partners[c_m].dest = &top->mps[c_m]; - - /* Initialize properties */ - top->sps[c_s].partners[c_m].props.delay = GNUNET_TIME_UNIT_ZERO; - top->sps[c_s].partners[c_m].props.distance = 0; - top->sps[c_s].partners[c_m].props.scope = GNUNET_NT_UNSPECIFIED; - top->sps[c_s].partners[c_m].props.utilization_in = 0; - top->sps[c_s].partners[c_m].props.utilization_out = 0; + GNUNET_assert(NULL != peers_[c_s + top->num_masters]); + top->sps[c_s].peer = peers_[c_s + top->num_masters]; + top->sps[c_s].no = c_s + top->num_masters; + top->sps[c_s].master = GNUNET_NO; + top->sps[c_s].partners = + GNUNET_new_array(top->num_masters, + struct BenchmarkPartner); + top->sps[c_s].num_partners = top->num_masters; + /* Initialize partners */ + for (c_m = 0; c_m < top->num_masters; c_m++) + { + top->sps[c_s].partners[c_m].me = &top->sps[c_s]; + top->sps[c_s].partners[c_m].dest = &top->mps[c_m]; + + /* Initialize properties */ + top->sps[c_s].partners[c_m].props.delay = GNUNET_TIME_UNIT_ZERO; + top->sps[c_s].partners[c_m].props.distance = 0; + top->sps[c_s].partners[c_m].props.scope = GNUNET_NT_UNSPECIFIED; + top->sps[c_s].partners[c_m].props.utilization_in = 0; + top->sps[c_s].partners[c_m].props.utilization_out = 0; + } + /* Get configuration */ + top->sps[c_s].peer_id_op + = GNUNET_TESTBED_peer_get_information(top->sps[c_s].peer, + GNUNET_TESTBED_PIT_IDENTITY, + &peerinformation_cb, + &top->sps[c_s]); } - /* Get configuration */ - top->sps[c_s].peer_id_op - = GNUNET_TESTBED_peer_get_information (top->sps[c_s].peer, - GNUNET_TESTBED_PIT_IDENTITY, - &peerinformation_cb, - &top->sps[c_s]); - } } @@ -870,24 +871,26 @@ main_run (void *cls, * @param event the controller event */ static void -controller_event_cb (void *cls, - const struct GNUNET_TESTBED_EventInformation *event) +controller_event_cb(void *cls, + const struct GNUNET_TESTBED_EventInformation *event) { switch (event->type) - { - case GNUNET_TESTBED_ET_CONNECT: - break; - case GNUNET_TESTBED_ET_OPERATION_FINISHED: - break; - default: - GNUNET_break(0); - GNUNET_SCHEDULER_shutdown (); - } + { + case GNUNET_TESTBED_ET_CONNECT: + break; + + case GNUNET_TESTBED_ET_OPERATION_FINISHED: + break; + + default: + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + } } struct BenchmarkPeer * -GNUNET_ATS_TEST_get_peer (int src) +GNUNET_ATS_TEST_get_peer(int src) { if (src > top->num_masters) return NULL; @@ -896,8 +899,8 @@ GNUNET_ATS_TEST_get_peer (int src) struct BenchmarkPartner * -GNUNET_ATS_TEST_get_partner (int src, - int dest) +GNUNET_ATS_TEST_get_partner(int src, + int dest) { if (src > top->num_masters) return NULL; @@ -920,37 +923,37 @@ GNUNET_ATS_TEST_get_partner (int src, * @param log_request_cb callback to call when logging is required */ void -GNUNET_ATS_TEST_create_topology (char *name, char *cfg_file, - unsigned int num_slaves, - unsigned int num_masters, - int test_core, - GNUNET_ATS_TEST_TopologySetupDoneCallback done_cb, - void *done_cb_cls, - GNUNET_ATS_AddressInformationCallback log_request_cb) +GNUNET_ATS_TEST_create_topology(char *name, char *cfg_file, + unsigned int num_slaves, + unsigned int num_masters, + int test_core, + GNUNET_ATS_TEST_TopologySetupDoneCallback done_cb, + void *done_cb_cls, + GNUNET_ATS_AddressInformationCallback log_request_cb) { - top = GNUNET_new (struct GNUNET_ATS_TEST_Topology); + top = GNUNET_new(struct GNUNET_ATS_TEST_Topology); top->num_masters = num_masters; top->num_slaves = num_slaves; top->done_cb = done_cb; top->done_cb_cls = done_cb_cls; top->test_core = test_core; top->ats_perf_cb = log_request_cb; - top->mps = GNUNET_new_array (num_masters, - struct BenchmarkPeer); - top->sps = GNUNET_new_array (num_slaves, - struct BenchmarkPeer); + top->mps = GNUNET_new_array(num_masters, + struct BenchmarkPeer); + top->sps = GNUNET_new_array(num_slaves, + struct BenchmarkPeer); /* Start topology */ uint64_t event_mask; event_mask = 0; event_mask |= (1LL << GNUNET_TESTBED_ET_CONNECT); event_mask |= (1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED); - (void) GNUNET_TESTBED_test_run (name, - cfg_file, - num_slaves + num_masters, - event_mask, - &controller_event_cb, NULL, - &main_run, NULL); + (void)GNUNET_TESTBED_test_run(name, + cfg_file, + num_slaves + num_masters, + event_mask, + &controller_event_cb, NULL, + &main_run, NULL); } @@ -958,7 +961,7 @@ GNUNET_ATS_TEST_create_topology (char *name, char *cfg_file, * Shutdown topology */ void -GNUNET_ATS_TEST_shutdown_topology (void) +GNUNET_ATS_TEST_shutdown_topology(void) { if (NULL == top) return; diff --git a/src/ats-tests/ats-testing.h b/src/ats-tests/ats-testing.h index f6df5a9bd..ff3a40837 100644 --- a/src/ats-tests/ats-testing.h +++ b/src/ats-tests/ats-testing.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2013 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2013 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -48,11 +48,10 @@ #define TEST_MESSAGE_SIZE 100 -struct TestMessage -{ +struct TestMessage { struct GNUNET_MessageHeader header; - uint8_t padding[TEST_MESSAGE_SIZE - sizeof (struct GNUNET_MessageHeader)]; + uint8_t padding[TEST_MESSAGE_SIZE - sizeof(struct GNUNET_MessageHeader)]; }; @@ -66,8 +65,7 @@ struct TrafficGenerator; struct LoggingHandle; -enum GeneratorType -{ +enum GeneratorType { GNUNET_ATS_TEST_TG_LINEAR, GNUNET_ATS_TEST_TG_CONSTANT, GNUNET_ATS_TEST_TG_RANDOM, @@ -108,8 +106,7 @@ typedef void (*GNUNET_ATS_TEST_LogRequest) ( /** * Information we track for a peer in the testbed. */ -struct BenchmarkPeer -{ +struct BenchmarkPeer { /** * Handle with testbed. */ @@ -227,8 +224,7 @@ struct BenchmarkPeer unsigned int total_bytes_received; }; -struct TrafficGenerator -{ +struct TrafficGenerator { struct TrafficGenerator *prev; struct TrafficGenerator *next; @@ -247,8 +243,7 @@ struct TrafficGenerator }; -struct PreferenceGenerator -{ +struct PreferenceGenerator { struct PreferenceGenerator *prev; struct PreferenceGenerator *next; @@ -272,8 +267,7 @@ struct PreferenceGenerator /** * Information about a benchmarking partner */ -struct BenchmarkPartner -{ +struct BenchmarkPartner { /** * The peer itself this partner belongs to */ @@ -359,8 +353,7 @@ struct BenchmarkPartner /** * Overall state of the performance benchmark */ -struct BenchmarkState -{ +struct BenchmarkState { /** * Are we connected to ATS service of all peers: GNUNET_YES/NO */ @@ -388,8 +381,7 @@ struct BenchmarkState }; -struct GNUNET_ATS_TEST_Topology -{ +struct GNUNET_ATS_TEST_Topology { /** * Progress task */ @@ -467,8 +459,7 @@ struct GNUNET_ATS_TEST_Topology void *done_cb_cls; }; -enum OperationType -{ +enum OperationType { START_SEND, STOP_SEND, START_PREFERENCE, @@ -489,8 +480,7 @@ typedef void (*GNUNET_ATS_TESTING_ExperimentDoneCallback) ( /** * An operation in an experiment */ -struct GNUNET_ATS_TEST_Operation -{ +struct GNUNET_ATS_TEST_Operation { struct GNUNET_ATS_TEST_Operation *next; struct GNUNET_ATS_TEST_Operation *prev; @@ -507,8 +497,7 @@ struct GNUNET_ATS_TEST_Operation enum GNUNET_ATS_PreferenceKind pref_type; }; -struct Episode -{ +struct Episode { int id; struct Episode *next; struct GNUNET_TIME_Relative duration; @@ -518,8 +507,7 @@ struct Episode }; -struct Experiment -{ +struct Experiment { char *name; char *cfg_file; unsigned long long int num_masters; @@ -550,7 +538,7 @@ extern struct GNUNET_CONFIGURATION_Handle *cfg; * @param e_done_cb the experiment is completed */ void -GNUNET_ATS_TEST_experimentation_run ( +GNUNET_ATS_TEST_experimentation_run( struct Experiment *e, GNUNET_ATS_TESTING_EpisodeDoneCallback ep_done_cb, GNUNET_ATS_TESTING_ExperimentDoneCallback e_done_cb); @@ -563,7 +551,7 @@ GNUNET_ATS_TEST_experimentation_run ( * @return the Experiment or NULL on failure */ struct Experiment * -GNUNET_ATS_TEST_experimentation_load (const char *filename); +GNUNET_ATS_TEST_experimentation_load(const char *filename); /** @@ -572,15 +560,15 @@ GNUNET_ATS_TEST_experimentation_load (const char *filename); * @param e the experiment */ void -GNUNET_ATS_TEST_experimentation_stop (struct Experiment *e); +GNUNET_ATS_TEST_experimentation_stop(struct Experiment *e); void -GNUNET_ATS_TEST_traffic_handle_ping (struct BenchmarkPartner *p); +GNUNET_ATS_TEST_traffic_handle_ping(struct BenchmarkPartner *p); void -GNUNET_ATS_TEST_traffic_handle_pong (struct BenchmarkPartner *p); +GNUNET_ATS_TEST_traffic_handle_pong(struct BenchmarkPartner *p); /** @@ -597,24 +585,24 @@ GNUNET_ATS_TEST_traffic_handle_pong (struct BenchmarkPartner *p); * @return the traffic generator */ struct TrafficGenerator * -GNUNET_ATS_TEST_generate_traffic_start (struct BenchmarkPeer *src, - struct BenchmarkPartner *dest, - enum GeneratorType type, - unsigned int base_rate, - unsigned int max_rate, - struct GNUNET_TIME_Relative period, - struct GNUNET_TIME_Relative duration); +GNUNET_ATS_TEST_generate_traffic_start(struct BenchmarkPeer *src, + struct BenchmarkPartner *dest, + enum GeneratorType type, + unsigned int base_rate, + unsigned int max_rate, + struct GNUNET_TIME_Relative period, + struct GNUNET_TIME_Relative duration); void -GNUNET_ATS_TEST_generate_traffic_stop (struct TrafficGenerator *tg); +GNUNET_ATS_TEST_generate_traffic_stop(struct TrafficGenerator *tg); /** * Stop all traffic generators */ void -GNUNET_ATS_TEST_generate_traffic_stop_all (void); +GNUNET_ATS_TEST_generate_traffic_stop_all(void); /** @@ -632,7 +620,7 @@ GNUNET_ATS_TEST_generate_traffic_stop_all (void); * @return the traffic generator */ struct PreferenceGenerator * -GNUNET_ATS_TEST_generate_preferences_start ( +GNUNET_ATS_TEST_generate_preferences_start( struct BenchmarkPeer *src, struct BenchmarkPartner *dest, enum GeneratorType type, @@ -644,11 +632,11 @@ GNUNET_ATS_TEST_generate_preferences_start ( void -GNUNET_ATS_TEST_generate_preferences_stop (struct PreferenceGenerator *pg); +GNUNET_ATS_TEST_generate_preferences_stop(struct PreferenceGenerator *pg); void -GNUNET_ATS_TEST_generate_preferences_stop_all (void); +GNUNET_ATS_TEST_generate_preferences_stop_all(void); /** @@ -663,12 +651,12 @@ GNUNET_ATS_TEST_generate_preferences_stop_all (void); * @return the logging handle or NULL on error */ struct LoggingHandle * -GNUNET_ATS_TEST_logging_start (struct GNUNET_TIME_Relative log_frequency, - const char *testname, - struct BenchmarkPeer *masters, - int num_masters, - int num_slaves, - int verbose); +GNUNET_ATS_TEST_logging_start(struct GNUNET_TIME_Relative log_frequency, + const char *testname, + struct BenchmarkPeer *masters, + int num_masters, + int num_slaves, + int verbose); /** @@ -677,7 +665,7 @@ GNUNET_ATS_TEST_logging_start (struct GNUNET_TIME_Relative log_frequency, * @param l the logging handle */ void -GNUNET_ATS_TEST_logging_clean_up (struct LoggingHandle *l); +GNUNET_ATS_TEST_logging_clean_up(struct LoggingHandle *l); /** @@ -686,7 +674,7 @@ GNUNET_ATS_TEST_logging_clean_up (struct LoggingHandle *l); * @param l the logging handle */ void -GNUNET_ATS_TEST_logging_stop (struct LoggingHandle *l); +GNUNET_ATS_TEST_logging_stop(struct LoggingHandle *l); /** @@ -695,7 +683,7 @@ GNUNET_ATS_TEST_logging_stop (struct LoggingHandle *l); * @param l logging handle to use */ void -GNUNET_ATS_TEST_logging_now (struct LoggingHandle *l); +GNUNET_ATS_TEST_logging_now(struct LoggingHandle *l); /** @@ -706,20 +694,20 @@ GNUNET_ATS_TEST_logging_now (struct LoggingHandle *l); * @param plots create gnuplots: #GNUNET_YES or #GNUNET_NO */ void -GNUNET_ATS_TEST_logging_write_to_file (struct LoggingHandle *l, - const char *test_name, - int plots); +GNUNET_ATS_TEST_logging_write_to_file(struct LoggingHandle *l, + const char *test_name, + int plots); /** * Topology related functions */ struct BenchmarkPeer * -GNUNET_ATS_TEST_get_peer (int src); +GNUNET_ATS_TEST_get_peer(int src); struct BenchmarkPartner * -GNUNET_ATS_TEST_get_partner (int src, int dest); +GNUNET_ATS_TEST_get_partner(int src, int dest); /** @@ -736,7 +724,7 @@ GNUNET_ATS_TEST_get_partner (int src, int dest); * @param log_request_cb callback to call when logging is required */ void -GNUNET_ATS_TEST_create_topology ( +GNUNET_ATS_TEST_create_topology( char *name, char *cfg_file, unsigned int num_slaves, @@ -751,7 +739,7 @@ GNUNET_ATS_TEST_create_topology ( * Shutdown topology */ void -GNUNET_ATS_TEST_shutdown_topology (void); +GNUNET_ATS_TEST_shutdown_topology(void); /* end of file ats-testing.h */ diff --git a/src/ats-tests/gnunet-ats-sim.c b/src/ats-tests/gnunet-ats-sim.c index af0eff534..d6168d388 100644 --- a/src/ats-tests/gnunet-ats-sim.c +++ b/src/ats-tests/gnunet-ats-sim.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2013 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2013 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -32,7 +32,7 @@ #include "gnunet_core_service.h" #include "ats-testing.h" -#define TEST_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) +#define TEST_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) static struct BenchmarkPeer *masters_p; static struct BenchmarkPeer *slaves_p; @@ -65,7 +65,7 @@ static struct LoggingHandle *l; static void -evaluate (struct GNUNET_TIME_Relative duration_total) +evaluate(struct GNUNET_TIME_Relative duration_total) { int c_m; int c_s; @@ -84,312 +84,313 @@ evaluate (struct GNUNET_TIME_Relative duration_total) if (0 == duration) duration = 1; for (c_m = 0; c_m < e->num_masters; c_m++) - { - mp = &masters_p[c_m]; - fprintf (stderr, - _("Master [%u]: sent: %u KiB in %u sec. = %u KiB/s, received: %u KiB in %u sec. = %u KiB/s\n"), - mp->no, mp->total_bytes_sent / 1024, - duration, - (mp->total_bytes_sent / 1024) / duration, - mp->total_bytes_received / 1024, - duration, - (mp->total_bytes_received / 1024) / duration); - - for (c_s = 0; c_s < e->num_slaves; c_s++) { - p = &mp->partners[c_s]; - - b_sent_sec = 0; - b_recv_sec = 0; - kb_sent_percent = 0.0; - kb_recv_percent = 0.0; - rtt = 0; - - if (duration > 0) - { - b_sent_sec = p->bytes_sent / duration; - b_recv_sec = p->bytes_received / duration; - } - - if (mp->total_bytes_sent > 0) - kb_sent_percent = ((double) p->bytes_sent * 100) / mp->total_bytes_sent; - if (mp->total_bytes_received > 0) - kb_recv_percent = ((double) p->bytes_received * 100) / mp->total_bytes_received; - if (1000 * p->messages_sent > 0) - rtt = p->total_app_rtt / (1000 * p->messages_sent); - fprintf (stderr, - "%c Master [%u] -> Slave [%u]: sent %u Bips (%.2f %%), received %u Bips (%.2f %%)\n", - (mp->pref_partner == p->dest) ? '*' : ' ', - mp->no, p->dest->no, - b_sent_sec, kb_sent_percent, + mp = &masters_p[c_m]; + fprintf(stderr, + _("Master [%u]: sent: %u KiB in %u sec. = %u KiB/s, received: %u KiB in %u sec. = %u KiB/s\n"), + mp->no, mp->total_bytes_sent / 1024, + duration, + (mp->total_bytes_sent / 1024) / duration, + mp->total_bytes_received / 1024, + duration, + (mp->total_bytes_received / 1024) / duration); + + for (c_s = 0; c_s < e->num_slaves; c_s++) + { + p = &mp->partners[c_s]; + + b_sent_sec = 0; + b_recv_sec = 0; + kb_sent_percent = 0.0; + kb_recv_percent = 0.0; + rtt = 0; + + if (duration > 0) + { + b_sent_sec = p->bytes_sent / duration; + b_recv_sec = p->bytes_received / duration; + } + + if (mp->total_bytes_sent > 0) + kb_sent_percent = ((double)p->bytes_sent * 100) / mp->total_bytes_sent; + if (mp->total_bytes_received > 0) + kb_recv_percent = ((double)p->bytes_received * 100) / mp->total_bytes_received; + if (1000 * p->messages_sent > 0) + rtt = p->total_app_rtt / (1000 * p->messages_sent); + fprintf(stderr, + "%c Master [%u] -> Slave [%u]: sent %u Bips (%.2f %%), received %u Bips (%.2f %%)\n", + (mp->pref_partner == p->dest) ? '*' : ' ', + mp->no, p->dest->no, + b_sent_sec, kb_sent_percent, b_recv_sec, kb_recv_percent); - fprintf (stderr, - "%c Master [%u] -> Slave [%u]: Average application layer RTT: %u ms\n", - (mp->pref_partner == p->dest) ? '*' : ' ', - mp->no, p->dest->no, rtt); + fprintf(stderr, + "%c Master [%u] -> Slave [%u]: Average application layer RTT: %u ms\n", + (mp->pref_partner == p->dest) ? '*' : ' ', + mp->no, p->dest->no, rtt); + } } - } } static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - fprintf (stderr, "Shutdown\n"); + fprintf(stderr, "Shutdown\n"); if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } if (NULL != l) - { - GNUNET_ATS_TEST_logging_stop (l); - GNUNET_ATS_TEST_logging_clean_up (l); - l = NULL; - } + { + GNUNET_ATS_TEST_logging_stop(l); + GNUNET_ATS_TEST_logging_clean_up(l); + l = NULL; + } /* Stop traffic generation */ GNUNET_ATS_TEST_generate_traffic_stop_all(); /* Stop all preference generations */ - GNUNET_ATS_TEST_generate_preferences_stop_all (); + GNUNET_ATS_TEST_generate_preferences_stop_all(); if (NULL != e) - { - GNUNET_ATS_TEST_experimentation_stop (e); - e = NULL; - } - GNUNET_ATS_TEST_shutdown_topology (); + { + GNUNET_ATS_TEST_experimentation_stop(e); + e = NULL; + } + GNUNET_ATS_TEST_shutdown_topology(); } static void -do_timeout (void *cls) +do_timeout(void *cls) { timeout_task = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } static void -log_request__cb (void *cls, - const struct GNUNET_HELLO_Address *address, - int address_active, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, - const struct GNUNET_ATS_Properties *ats) +log_request__cb(void *cls, + const struct GNUNET_HELLO_Address *address, + int address_active, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, + const struct GNUNET_ATS_Properties *ats) { if (NULL != l) - { - //GNUNET_break (0); - //GNUNET_ATS_TEST_logging_now (l); - } + { + //GNUNET_break (0); + //GNUNET_ATS_TEST_logging_now (l); + } } static void -experiment_done_cb (struct Experiment *e, - struct GNUNET_TIME_Relative duration, - int success) +experiment_done_cb(struct Experiment *e, + struct GNUNET_TIME_Relative duration, + int success) { if (GNUNET_OK == success) - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Experiment done successful in %s\n", - GNUNET_STRINGS_relative_time_to_string (duration, - GNUNET_YES)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Experiment done successful in %s\n", + GNUNET_STRINGS_relative_time_to_string(duration, + GNUNET_YES)); else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Experiment failed \n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Experiment failed \n"); /* Stop logging */ - GNUNET_ATS_TEST_logging_stop (l); + GNUNET_ATS_TEST_logging_stop(l); /* Stop traffic generation */ GNUNET_ATS_TEST_generate_traffic_stop_all(); /* Stop all preference generations */ - GNUNET_ATS_TEST_generate_preferences_stop_all (); + GNUNET_ATS_TEST_generate_preferences_stop_all(); - evaluate (duration); + evaluate(duration); if (opt_log) GNUNET_ATS_TEST_logging_write_to_file(l, opt_exp_file, opt_plot); - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } static void -episode_done_cb (struct Episode *ep) +episode_done_cb(struct Episode *ep) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Episode %u done\n", - ep->id); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Episode %u done\n", + ep->id); } static void -topology_setup_done (void *cls, - struct BenchmarkPeer *masters, - struct BenchmarkPeer *slaves) +topology_setup_done(void *cls, + struct BenchmarkPeer *masters, + struct BenchmarkPeer *slaves) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Topology setup complete!\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Topology setup complete!\n"); masters_p = masters; slaves_p = slaves; - l = GNUNET_ATS_TEST_logging_start (e->log_freq, - e->name, - masters_p, - e->num_masters, e->num_slaves, - opt_verbose); - GNUNET_ATS_TEST_experimentation_run (e, - &episode_done_cb, - &experiment_done_cb); + l = GNUNET_ATS_TEST_logging_start(e->log_freq, + e->name, + masters_p, + e->num_masters, e->num_slaves, + opt_verbose); + GNUNET_ATS_TEST_experimentation_run(e, + &episode_done_cb, + &experiment_done_cb); /* - GNUNET_ATS_TEST_generate_preferences_start(&masters[0],&masters[0].partners[0], + GNUNET_ATS_TEST_generate_preferences_start(&masters[0],&masters[0].partners[0], GNUNET_ATS_TEST_TG_CONSTANT, 1, 1, GNUNET_TIME_UNIT_SECONDS, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250), GNUNET_ATS_PREFERENCE_BANDWIDTH); -*/ + */ /* - GNUNET_ATS_TEST_generate_preferences_start(&masters[0],&masters[0].partners[0], + GNUNET_ATS_TEST_generate_preferences_start(&masters[0],&masters[0].partners[0], GNUNET_ATS_TEST_TG_LINEAR, 1, 50, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 2), GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250), GNUNET_ATS_PREFERENCE_BANDWIDTH); -*/ + */ /* - GNUNET_ATS_TEST_generate_preferences_start(&masters[0],&masters[0].partners[0], + GNUNET_ATS_TEST_generate_preferences_start(&masters[0],&masters[0].partners[0], GNUNET_ATS_TEST_TG_RANDOM, 1, 50, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 2), GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250), GNUNET_ATS_PREFERENCE_BANDWIDTH); -*/ - /* - GNUNET_ATS_TEST_generate_preferences_start(&masters[0],&masters[0].partners[0], - GNUNET_ATS_TEST_TG_SINUS, 10, 5, - GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), - GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250), - GNUNET_ATS_PREFERENCE_BANDWIDTH); -*/ + */ +/* + GNUNET_ATS_TEST_generate_preferences_start(&masters[0],&masters[0].partners[0], + GNUNET_ATS_TEST_TG_SINUS, 10, 5, + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250), + GNUNET_ATS_PREFERENCE_BANDWIDTH); + */ #if 0 int c_m; int c_s; for (c_m = 0; c_m < e->num_masters; c_m++) - { + { for (c_s = 0; c_s < e->num_slaves; c_s++) - { - /* Generate maximum traffic to all peers */ - /* Example: Generate traffic with constant 10,000 Bytes/s */ - GNUNET_ATS_TEST_generate_traffic_start (&masters[c_m], - &masters[c_m].partners[c_s], - GNUNET_ATS_TEST_TG_CONSTANT, - 10000, - GNUNET_TIME_UNIT_FOREVER_REL); - /* Example: Generate traffic with an increasing rate from 1000 to 2000 - * Bytes/s with in a minute */ - GNUNET_ATS_TEST_generate_traffic_start (&masters[c_m], - &masters[c_m].partners[c_s], - GNUNET_ATS_TEST_TG_LINEAR, - 1000, - 2000, - GNUNET_TIME_UNIT_MINUTES, - GNUNET_TIME_UNIT_FOREVER_REL); - /* Example: Generate traffic with a random rate between 1000 to 2000 - * Bytes/s */ - GNUNET_ATS_TEST_generate_traffic_start (&masters[c_m], - &masters[c_m].partners[c_s], - GNUNET_ATS_TEST_TG_RANDOM, - 1000, - 2000, - GNUNET_TIME_UNIT_FOREVER_REL, - GNUNET_TIME_UNIT_FOREVER_REL); - /* Example: Generate traffic with a sinus form, a base rate of - * 1000 Bytes/s, an amplitude of (max-base), and a period of 1 minute */ - GNUNET_ATS_TEST_generate_traffic_start (&masters[c_m], - &masters[c_m].partners[c_s], - GNUNET_ATS_TEST_TG_SINUS, - 1000, - 2000, - GNUNET_TIME_UNIT_MINUTES, - GNUNET_TIME_UNIT_FOREVER_REL); - } - } + { + /* Generate maximum traffic to all peers */ + /* Example: Generate traffic with constant 10,000 Bytes/s */ + GNUNET_ATS_TEST_generate_traffic_start(&masters[c_m], + &masters[c_m].partners[c_s], + GNUNET_ATS_TEST_TG_CONSTANT, + 10000, + GNUNET_TIME_UNIT_FOREVER_REL); + /* Example: Generate traffic with an increasing rate from 1000 to 2000 + * Bytes/s with in a minute */ + GNUNET_ATS_TEST_generate_traffic_start(&masters[c_m], + &masters[c_m].partners[c_s], + GNUNET_ATS_TEST_TG_LINEAR, + 1000, + 2000, + GNUNET_TIME_UNIT_MINUTES, + GNUNET_TIME_UNIT_FOREVER_REL); + /* Example: Generate traffic with a random rate between 1000 to 2000 + * Bytes/s */ + GNUNET_ATS_TEST_generate_traffic_start(&masters[c_m], + &masters[c_m].partners[c_s], + GNUNET_ATS_TEST_TG_RANDOM, + 1000, + 2000, + GNUNET_TIME_UNIT_FOREVER_REL, + GNUNET_TIME_UNIT_FOREVER_REL); + /* Example: Generate traffic with a sinus form, a base rate of + * 1000 Bytes/s, an amplitude of (max-base), and a period of 1 minute */ + GNUNET_ATS_TEST_generate_traffic_start(&masters[c_m], + &masters[c_m].partners[c_s], + GNUNET_ATS_TEST_TG_SINUS, + 1000, + 2000, + GNUNET_TIME_UNIT_MINUTES, + GNUNET_TIME_UNIT_FOREVER_REL); + } + } #endif timeout_task - = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_add (GNUNET_TIME_UNIT_MINUTES, - e->max_duration), - &do_timeout, - NULL); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL); + = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_add(GNUNET_TIME_UNIT_MINUTES, + e->max_duration), + &do_timeout, + NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); } static void -parse_args (int argc, char *argv[]) +parse_args(int argc, char *argv[]) { int c; + opt_exp_file = NULL; opt_log = GNUNET_NO; opt_plot = GNUNET_NO; for (c = 0; c < argc; c++) - { - if ((c < (argc - 1)) && (0 == strcmp (argv[c], "-e"))) - { - GNUNET_free_non_null (opt_exp_file); - opt_exp_file = GNUNET_strdup ( argv[c + 1]); - } - if (0 == strcmp (argv[c], "-l")) - { - opt_log = GNUNET_YES; - } - if (0 == strcmp (argv[c], "-p")) { - opt_plot = GNUNET_YES; + if ((c < (argc - 1)) && (0 == strcmp(argv[c], "-e"))) + { + GNUNET_free_non_null(opt_exp_file); + opt_exp_file = GNUNET_strdup(argv[c + 1]); + } + if (0 == strcmp(argv[c], "-l")) + { + opt_log = GNUNET_YES; + } + if (0 == strcmp(argv[c], "-p")) + { + opt_plot = GNUNET_YES; + } + if (0 == strcmp(argv[c], "-v")) + { + opt_verbose = GNUNET_YES; + } } - if (0 == strcmp (argv[c], "-v")) - { - opt_verbose = GNUNET_YES; - } - } } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { GNUNET_log_setup("gnunet-ats-sim", "INFO", NULL); - parse_args (argc, argv); - if (NULL == opt_exp_file ) - { - fprintf (stderr, "No experiment given...\n"); - return 1; - } + parse_args(argc, argv); + if (NULL == opt_exp_file) + { + fprintf(stderr, "No experiment given...\n"); + return 1; + } - fprintf (stderr, "Loading experiment `%s' \n", opt_exp_file ); - e = GNUNET_ATS_TEST_experimentation_load (opt_exp_file); + fprintf(stderr, "Loading experiment `%s' \n", opt_exp_file); + e = GNUNET_ATS_TEST_experimentation_load(opt_exp_file); if (NULL == e) - { - fprintf (stderr, "Invalid experiment\n"); - return 1; - } + { + fprintf(stderr, "Invalid experiment\n"); + return 1; + } if (0 == e->num_episodes) - { - fprintf (stderr, "No episodes included\n"); - return 1; - } + { + fprintf(stderr, "No episodes included\n"); + return 1; + } /* Setup a topology with */ - GNUNET_ATS_TEST_create_topology ("gnunet-ats-sim", e->cfg_file, - e->num_slaves, - e->num_masters, - GNUNET_NO, - &topology_setup_done, - NULL, - &log_request__cb); - GNUNET_free (opt_exp_file); + GNUNET_ATS_TEST_create_topology("gnunet-ats-sim", e->cfg_file, + e->num_slaves, + e->num_masters, + GNUNET_NO, + &topology_setup_done, + NULL, + &log_request__cb); + GNUNET_free(opt_exp_file); return 0; } /* end of file gnunet-ats-sim.c */ diff --git a/src/ats-tests/gnunet-solver-eval.c b/src/ats-tests/gnunet-solver-eval.c index cb1946448..b5e00bd6f 100644 --- a/src/ats-tests/gnunet-solver-eval.c +++ b/src/ats-tests/gnunet-solver-eval.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2013 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2013 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -34,29 +34,35 @@ * Experiments */ const char * -print_op (enum OperationType op) +print_op(enum OperationType op) { - switch (op) { + switch (op) + { case START_SEND: return "START_SEND"; + case STOP_SEND: return "STOP_SEND"; + case START_PREFERENCE: return "START_PREFERENCE"; + case STOP_PREFERENCE: return "STOP_PREFERENCE"; + default: break; - } + } return ""; } static struct Experiment * -create_experiment () +create_experiment() { struct Experiment *e; - e = GNUNET_new (struct Experiment); + + e = GNUNET_new(struct Experiment); e->name = NULL; e->num_masters = 0; e->num_slaves = 0; @@ -67,7 +73,7 @@ create_experiment () static void -free_experiment (struct Experiment *e) +free_experiment(struct Experiment *e) { struct Episode *cur; struct Episode *next; @@ -76,28 +82,28 @@ free_experiment (struct Experiment *e) next = e->start; for (cur = next; NULL != cur; cur = next) - { - next = cur->next; - - next_o = cur->head; - for (cur_o = next_o; NULL != cur_o; cur_o = next_o) { - next_o = cur_o->next; - GNUNET_free (cur_o); + next = cur->next; + + next_o = cur->head; + for (cur_o = next_o; NULL != cur_o; cur_o = next_o) + { + next_o = cur_o->next; + GNUNET_free(cur_o); + } + GNUNET_free(cur); } - GNUNET_free (cur); - } - GNUNET_free_non_null (e->name); - GNUNET_free_non_null (e->cfg_file); - GNUNET_free (e); + GNUNET_free_non_null(e->name); + GNUNET_free_non_null(e->cfg_file); + GNUNET_free(e); } static int -load_episode (struct Experiment *e, - struct Episode *cur, - struct GNUNET_CONFIGURATION_Handle *cfg) +load_episode(struct Experiment *e, + struct Episode *cur, + struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_ATS_TEST_Operation *o; char *sec_name; @@ -106,284 +112,285 @@ load_episode (struct Experiment *e, char *type; char *pref; int op_counter = 0; - fprintf (stderr, "Parsing episode %u\n",cur->id); + + fprintf(stderr, "Parsing episode %u\n", cur->id); GNUNET_asprintf(&sec_name, "episode-%u", cur->id); while (1) - { - /* Load operation */ - GNUNET_asprintf(&op_name, "op-%u-operation", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, - sec_name, op_name, &op)) - { - GNUNET_free (op_name); - break; - } - o = GNUNET_new (struct GNUNET_ATS_TEST_Operation); - /* operations = set_rate, start_send, stop_send, set_preference */ - if (0 == strcmp (op, "start_send")) - { - o->type = START_SEND; - } - else if (0 == strcmp (op, "stop_send")) - { - o->type = STOP_SEND; - } - else if (0 == strcmp (op, "start_preference")) - { - o->type = START_PREFERENCE; - } - else if (0 == strcmp (op, "stop_preference")) - { - o->type = STOP_PREFERENCE; - } - else - { - fprintf (stderr, "Invalid operation %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (sec_name); - GNUNET_free (o); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); - - /* Get source */ - GNUNET_asprintf(&op_name, "op-%u-src", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->src_id)) - { - fprintf (stderr, "Missing src in operation %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (sec_name); - GNUNET_free (o); - return GNUNET_SYSERR; - } - if (o->src_id > (e->num_masters - 1)) - { - fprintf (stderr, "Invalid src %llu in operation %u `%s' in episode %u\n", - o->src_id, op_counter, op, cur->id); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (sec_name); - GNUNET_free (o); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); - - /* Get destination */ - GNUNET_asprintf(&op_name, "op-%u-dest", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->dest_id)) { - fprintf (stderr, "Missing src in operation %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (sec_name); - GNUNET_free (o); - return GNUNET_SYSERR; - } - if (o->dest_id > (e->num_slaves - 1)) - { - fprintf (stderr, - "Invalid destination %llu in operation %u `%s' in episode %u\n", - o->dest_id, - op_counter, - op, - cur->id); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (sec_name); - GNUNET_free (o); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); - - GNUNET_asprintf(&op_name, "op-%u-type", op_counter); - if ( (GNUNET_SYSERR != - GNUNET_CONFIGURATION_get_value_string(cfg, - sec_name, - op_name, - &type)) && - (STOP_SEND != o->type) && - (STOP_PREFERENCE != o->type) ) - { - /* Load arguments for set_rate, start_send, set_preference */ - if (0 == strcmp (type, "constant")) - { - o->gen_type = GNUNET_ATS_TEST_TG_CONSTANT; - } - else if (0 == strcmp (type, "linear")) - { - o->gen_type = GNUNET_ATS_TEST_TG_LINEAR; - } - else if (0 == strcmp (type, "sinus")) - { - o->gen_type = GNUNET_ATS_TEST_TG_SINUS; - } - else if (0 == strcmp (type, "random")) - { - o->gen_type = GNUNET_ATS_TEST_TG_RANDOM; - } + /* Load operation */ + GNUNET_asprintf(&op_name, "op-%u-operation", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &op)) + { + GNUNET_free(op_name); + break; + } + o = GNUNET_new(struct GNUNET_ATS_TEST_Operation); + /* operations = set_rate, start_send, stop_send, set_preference */ + if (0 == strcmp(op, "start_send")) + { + o->type = START_SEND; + } + else if (0 == strcmp(op, "stop_send")) + { + o->type = STOP_SEND; + } + else if (0 == strcmp(op, "start_preference")) + { + o->type = START_PREFERENCE; + } + else if (0 == strcmp(op, "stop_preference")) + { + o->type = STOP_PREFERENCE; + } else - { - fprintf (stderr, "Invalid type %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (type); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (sec_name); - GNUNET_free (o); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); - - /* Get base rate */ - GNUNET_asprintf(&op_name, "op-%u-base-rate", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->base_rate)) - { - fprintf (stderr, "Missing base rate in operation %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (type); - GNUNET_free (op); - GNUNET_free (op_name); - GNUNET_free (sec_name); - GNUNET_free (o); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); - - /* Get max rate */ - GNUNET_asprintf(&op_name, "op-%u-max-rate", op_counter); - if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, - op_name, - &o->max_rate)) - { - if ((GNUNET_ATS_TEST_TG_LINEAR == o->gen_type) || - (GNUNET_ATS_TEST_TG_RANDOM == o->gen_type) || - (GNUNET_ATS_TEST_TG_SINUS == o->gen_type)) { - fprintf (stderr, "Missing max rate in operation %u `%s' in episode %u\n", - op_counter, op, cur->id); - GNUNET_free (type); - GNUNET_free (op_name); - GNUNET_free (op); - GNUNET_free (sec_name); - GNUNET_free (o); + fprintf(stderr, "Invalid operation %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(sec_name); + GNUNET_free(o); return GNUNET_SYSERR; } - } - GNUNET_free (op_name); - - /* Get period */ - GNUNET_asprintf(&op_name, "op-%u-period", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (cfg, - sec_name, op_name, &o->period)) - { - o->period = cur->duration; - } - GNUNET_free (op_name); - - if (START_PREFERENCE == o->type) - { - /* Get frequency */ - GNUNET_asprintf(&op_name, "op-%u-frequency", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (cfg, - sec_name, op_name, &o->frequency)) - { - fprintf (stderr, "Missing frequency in operation %u `%s' in episode %u\n", + GNUNET_free(op_name); + + /* Get source */ + GNUNET_asprintf(&op_name, "op-%u-src", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->src_id)) + { + fprintf(stderr, "Missing src in operation %u `%s' in episode %u\n", op_counter, op, cur->id); - GNUNET_free (type); - GNUNET_free (op_name); - GNUNET_free (op); - GNUNET_free (sec_name); - GNUNET_free (o); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); - - /* Get preference */ - GNUNET_asprintf(&op_name, "op-%u-pref", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, - sec_name, op_name, &pref)) - { - fprintf (stderr, "Missing preference in operation %u `%s' in episode %u\n", + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(sec_name); + GNUNET_free(o); + return GNUNET_SYSERR; + } + if (o->src_id > (e->num_masters - 1)) + { + fprintf(stderr, "Invalid src %llu in operation %u `%s' in episode %u\n", + o->src_id, op_counter, op, cur->id); + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(sec_name); + GNUNET_free(o); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); + + /* Get destination */ + GNUNET_asprintf(&op_name, "op-%u-dest", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->dest_id)) + { + fprintf(stderr, "Missing src in operation %u `%s' in episode %u\n", op_counter, op, cur->id); - GNUNET_free (type); - GNUNET_free (op_name); - GNUNET_free (op); - GNUNET_free (sec_name); - GNUNET_free_non_null (pref); - GNUNET_free (o); - return GNUNET_SYSERR; - } + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(sec_name); + GNUNET_free(o); + return GNUNET_SYSERR; + } + if (o->dest_id > (e->num_slaves - 1)) + { + fprintf(stderr, + "Invalid destination %llu in operation %u `%s' in episode %u\n", + o->dest_id, + op_counter, + op, + cur->id); + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(sec_name); + GNUNET_free(o); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); - if (0 == strcmp(pref, "bandwidth")) - o->pref_type = GNUNET_ATS_PREFERENCE_BANDWIDTH; - else if (0 == strcmp(pref, "latency")) - o->pref_type = GNUNET_ATS_PREFERENCE_LATENCY; + GNUNET_asprintf(&op_name, "op-%u-type", op_counter); + if ((GNUNET_SYSERR != + GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, + op_name, + &type)) && + (STOP_SEND != o->type) && + (STOP_PREFERENCE != o->type)) + { + /* Load arguments for set_rate, start_send, set_preference */ + if (0 == strcmp(type, "constant")) + { + o->gen_type = GNUNET_ATS_TEST_TG_CONSTANT; + } + else if (0 == strcmp(type, "linear")) + { + o->gen_type = GNUNET_ATS_TEST_TG_LINEAR; + } + else if (0 == strcmp(type, "sinus")) + { + o->gen_type = GNUNET_ATS_TEST_TG_SINUS; + } + else if (0 == strcmp(type, "random")) + { + o->gen_type = GNUNET_ATS_TEST_TG_RANDOM; + } else - { - fprintf (stderr, - "Invalid preference in operation %u `%s' in episode %u\n", - op_counter, - op, - cur->id); - GNUNET_free (type); - GNUNET_free (op_name); - GNUNET_free (op); - GNUNET_free (sec_name); - GNUNET_free_non_null (pref); - GNUNET_free (o); + { + fprintf(stderr, "Invalid type %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(type); + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(sec_name); + GNUNET_free(o); return GNUNET_SYSERR; - } - GNUNET_free (pref); - GNUNET_free (op_name); - } - } + } + GNUNET_free(op_name); + + /* Get base rate */ + GNUNET_asprintf(&op_name, "op-%u-base-rate", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->base_rate)) + { + fprintf(stderr, "Missing base rate in operation %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(type); + GNUNET_free(op); + GNUNET_free(op_name); + GNUNET_free(sec_name); + GNUNET_free(o); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); + + /* Get max rate */ + GNUNET_asprintf(&op_name, "op-%u-max-rate", op_counter); + if (GNUNET_SYSERR == + GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, + op_name, + &o->max_rate)) + { + if ((GNUNET_ATS_TEST_TG_LINEAR == o->gen_type) || + (GNUNET_ATS_TEST_TG_RANDOM == o->gen_type) || + (GNUNET_ATS_TEST_TG_SINUS == o->gen_type)) + { + fprintf(stderr, "Missing max rate in operation %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(type); + GNUNET_free(op_name); + GNUNET_free(op); + GNUNET_free(sec_name); + GNUNET_free(o); + return GNUNET_SYSERR; + } + } + GNUNET_free(op_name); + + /* Get period */ + GNUNET_asprintf(&op_name, "op-%u-period", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, + sec_name, op_name, &o->period)) + { + o->period = cur->duration; + } + GNUNET_free(op_name); + + if (START_PREFERENCE == o->type) + { + /* Get frequency */ + GNUNET_asprintf(&op_name, "op-%u-frequency", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, + sec_name, op_name, &o->frequency)) + { + fprintf(stderr, "Missing frequency in operation %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(type); + GNUNET_free(op_name); + GNUNET_free(op); + GNUNET_free(sec_name); + GNUNET_free(o); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); + + /* Get preference */ + GNUNET_asprintf(&op_name, "op-%u-pref", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &pref)) + { + fprintf(stderr, "Missing preference in operation %u `%s' in episode %u\n", + op_counter, op, cur->id); + GNUNET_free(type); + GNUNET_free(op_name); + GNUNET_free(op); + GNUNET_free(sec_name); + GNUNET_free_non_null(pref); + GNUNET_free(o); + return GNUNET_SYSERR; + } + + if (0 == strcmp(pref, "bandwidth")) + o->pref_type = GNUNET_ATS_PREFERENCE_BANDWIDTH; + else if (0 == strcmp(pref, "latency")) + o->pref_type = GNUNET_ATS_PREFERENCE_LATENCY; + else + { + fprintf(stderr, + "Invalid preference in operation %u `%s' in episode %u\n", + op_counter, + op, + cur->id); + GNUNET_free(type); + GNUNET_free(op_name); + GNUNET_free(op); + GNUNET_free(sec_name); + GNUNET_free_non_null(pref); + GNUNET_free(o); + return GNUNET_SYSERR; + } + GNUNET_free(pref); + GNUNET_free(op_name); + } + } - /* Safety checks */ - if ((GNUNET_ATS_TEST_TG_LINEAR == o->gen_type) || - (GNUNET_ATS_TEST_TG_SINUS == o->gen_type)) - { - if ((o->max_rate - o->base_rate) > o->base_rate) - { - /* This will cause an underflow */ - GNUNET_break (0); - } - fprintf (stderr, "Selected max rate and base rate cannot be used for desired traffic form!\n"); - } + /* Safety checks */ + if ((GNUNET_ATS_TEST_TG_LINEAR == o->gen_type) || + (GNUNET_ATS_TEST_TG_SINUS == o->gen_type)) + { + if ((o->max_rate - o->base_rate) > o->base_rate) + { + /* This will cause an underflow */ + GNUNET_break(0); + } + fprintf(stderr, "Selected max rate and base rate cannot be used for desired traffic form!\n"); + } - if ((START_SEND == o->type) || (START_PREFERENCE == o->type)) - fprintf (stderr, "Found operation %u in episode %u: %s [%llu]->[%llu] == %s, %llu -> %llu in %s\n", - op_counter, cur->id, print_op (o->type), o->src_id, - o->dest_id, (NULL != type) ? type : "", - o->base_rate, o->max_rate, - GNUNET_STRINGS_relative_time_to_string (o->period, GNUNET_YES)); - else - fprintf (stderr, "Found operation %u in episode %u: %s [%llu]->[%llu]\n", - op_counter, cur->id, print_op (o->type), o->src_id, o->dest_id); + if ((START_SEND == o->type) || (START_PREFERENCE == o->type)) + fprintf(stderr, "Found operation %u in episode %u: %s [%llu]->[%llu] == %s, %llu -> %llu in %s\n", + op_counter, cur->id, print_op(o->type), o->src_id, + o->dest_id, (NULL != type) ? type : "", + o->base_rate, o->max_rate, + GNUNET_STRINGS_relative_time_to_string(o->period, GNUNET_YES)); + else + fprintf(stderr, "Found operation %u in episode %u: %s [%llu]->[%llu]\n", + op_counter, cur->id, print_op(o->type), o->src_id, o->dest_id); - GNUNET_free_non_null (type); - GNUNET_free (op); + GNUNET_free_non_null(type); + GNUNET_free(op); - GNUNET_CONTAINER_DLL_insert (cur->head,cur->tail, o); - op_counter++; - } - GNUNET_free (sec_name); + GNUNET_CONTAINER_DLL_insert(cur->head, cur->tail, o); + op_counter++; + } + GNUNET_free(sec_name); return GNUNET_OK; } static int -load_episodes (struct Experiment *e, struct GNUNET_CONFIGURATION_Handle *cfg) +load_episodes(struct Experiment *e, struct GNUNET_CONFIGURATION_Handle *cfg) { int e_counter = 0; char *sec_name; @@ -394,438 +401,446 @@ load_episodes (struct Experiment *e, struct GNUNET_CONFIGURATION_Handle *cfg) e_counter = 0; last = NULL; while (1) - { - GNUNET_asprintf(&sec_name, "episode-%u", e_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, - sec_name, "duration", &e_duration)) { - GNUNET_free (sec_name); - break; - } + GNUNET_asprintf(&sec_name, "episode-%u", e_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, + sec_name, "duration", &e_duration)) + { + GNUNET_free(sec_name); + break; + } - cur = GNUNET_new (struct Episode); - cur->duration = e_duration; - cur->id = e_counter; + cur = GNUNET_new(struct Episode); + cur->duration = e_duration; + cur->id = e_counter; - if (GNUNET_OK != load_episode (e, cur, cfg)) - { - GNUNET_free (sec_name); - GNUNET_free (cur); - return GNUNET_SYSERR; - } + if (GNUNET_OK != load_episode(e, cur, cfg)) + { + GNUNET_free(sec_name); + GNUNET_free(cur); + return GNUNET_SYSERR; + } + + fprintf(stderr, "Found episode %u with duration %s \n", + e_counter, + GNUNET_STRINGS_relative_time_to_string(cur->duration, GNUNET_YES)); + + /* Update experiment */ + e->num_episodes++; + e->total_duration = GNUNET_TIME_relative_add(e->total_duration, cur->duration); + /* Put in linked list */ + if (NULL == last) + e->start = cur; + else + last->next = cur; - fprintf (stderr, "Found episode %u with duration %s \n", - e_counter, - GNUNET_STRINGS_relative_time_to_string(cur->duration, GNUNET_YES)); - - /* Update experiment */ - e->num_episodes ++; - e->total_duration = GNUNET_TIME_relative_add(e->total_duration, cur->duration); - /* Put in linked list */ - if (NULL == last) - e->start = cur; - else - last->next = cur; - - GNUNET_free (sec_name); - e_counter ++; - last = cur; - } + GNUNET_free(sec_name); + e_counter++; + last = cur; + } return e_counter; } static void -timeout_experiment (void *cls) +timeout_experiment(void *cls) { struct Experiment *e = cls; + e->experiment_timeout_task = NULL; - fprintf (stderr, "Experiment timeout!\n"); + fprintf(stderr, "Experiment timeout!\n"); if (NULL != e->episode_timeout_task) - { - GNUNET_SCHEDULER_cancel (e->episode_timeout_task); - e->episode_timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(e->episode_timeout_task); + e->episode_timeout_task = NULL; + } - e->e_done_cb (e, GNUNET_TIME_absolute_get_duration(e->start_time), - GNUNET_SYSERR); + e->e_done_cb(e, GNUNET_TIME_absolute_get_duration(e->start_time), + GNUNET_SYSERR); } static void -enforce_start_send (struct GNUNET_ATS_TEST_Operation *op) +enforce_start_send(struct GNUNET_ATS_TEST_Operation *op) { /* - struct BenchmarkPeer *peer; - struct BenchmarkPartner *partner; - - peer = GNUNET_ATS_TEST_get_peer (op->src_id); - if (NULL == peer) - { - GNUNET_break (0); - return; - } - - partner = GNUNET_ATS_TEST_get_partner (op->src_id, op->dest_id); - if (NULL == partner) - { - GNUNET_break (0); - return; - } - - fprintf (stderr, "Found master %llu slave %llu\n",op->src_id, op->dest_id); - - if (NULL != partner->tg) - { - fprintf (stderr, "Stopping traffic between master %llu slave %llu\n",op->src_id, op->dest_id); - GNUNET_ATS_TEST_generate_traffic_stop(partner->tg); - partner->tg = NULL; - } - - partner->tg = GNUNET_ATS_TEST_generate_traffic_start(peer, partner, + struct BenchmarkPeer *peer; + struct BenchmarkPartner *partner; + + peer = GNUNET_ATS_TEST_get_peer (op->src_id); + if (NULL == peer) + { + GNUNET_break (0); + return; + } + + partner = GNUNET_ATS_TEST_get_partner (op->src_id, op->dest_id); + if (NULL == partner) + { + GNUNET_break (0); + return; + } + + fprintf (stderr, "Found master %llu slave %llu\n",op->src_id, op->dest_id); + + if (NULL != partner->tg) + { + fprintf (stderr, "Stopping traffic between master %llu slave %llu\n",op->src_id, op->dest_id); + GNUNET_ATS_TEST_generate_traffic_stop(partner->tg); + partner->tg = NULL; + } + + partner->tg = GNUNET_ATS_TEST_generate_traffic_start(peer, partner, op->tg_type, op->base_rate, op->max_rate, op->period, GNUNET_TIME_UNIT_FOREVER_REL); */ } static void -enforce_stop_send (struct GNUNET_ATS_TEST_Operation *op) +enforce_stop_send(struct GNUNET_ATS_TEST_Operation *op) { /* - struct BenchmarkPartner *p; - p = GNUNET_ATS_TEST_get_partner (op->src_id, op->dest_id); - if (NULL == p) - { - GNUNET_break (0); - return; - } - - fprintf (stderr, "Found master %llu slave %llu\n",op->src_id, op->dest_id); - - if (NULL != p->tg) - { - fprintf (stderr, "Stopping traffic between master %llu slave %llu\n", + struct BenchmarkPartner *p; + p = GNUNET_ATS_TEST_get_partner (op->src_id, op->dest_id); + if (NULL == p) + { + GNUNET_break (0); + return; + } + + fprintf (stderr, "Found master %llu slave %llu\n",op->src_id, op->dest_id); + + if (NULL != p->tg) + { + fprintf (stderr, "Stopping traffic between master %llu slave %llu\n", op->src_id, op->dest_id); - GNUNET_ATS_TEST_generate_traffic_stop(p->tg); - p->tg = NULL; - } - */ + GNUNET_ATS_TEST_generate_traffic_stop(p->tg); + p->tg = NULL; + } + */ } static void -enforce_start_preference (struct GNUNET_ATS_TEST_Operation *op) +enforce_start_preference(struct GNUNET_ATS_TEST_Operation *op) { /* - struct BenchmarkPeer *peer; - struct BenchmarkPartner *partner; - - peer = GNUNET_ATS_TEST_get_peer (op->src_id); - if (NULL == peer) - { - GNUNET_break (0); - return; - } - - partner = GNUNET_ATS_TEST_get_partner (op->src_id, op->dest_id); - if (NULL == partner) - { - GNUNET_break (0); - return; - } - - fprintf (stderr, "Found master %llu slave %llu\n",op->src_id, op->dest_id); - - if (NULL != partner->pg) - { - fprintf (stderr, "Stopping traffic between master %llu slave %llu\n", + struct BenchmarkPeer *peer; + struct BenchmarkPartner *partner; + + peer = GNUNET_ATS_TEST_get_peer (op->src_id); + if (NULL == peer) + { + GNUNET_break (0); + return; + } + + partner = GNUNET_ATS_TEST_get_partner (op->src_id, op->dest_id); + if (NULL == partner) + { + GNUNET_break (0); + return; + } + + fprintf (stderr, "Found master %llu slave %llu\n",op->src_id, op->dest_id); + + if (NULL != partner->pg) + { + fprintf (stderr, "Stopping traffic between master %llu slave %llu\n", op->src_id, op->dest_id); - GNUNET_ATS_TEST_generate_preferences_stop(partner->pg); - partner->pg = NULL; - } + GNUNET_ATS_TEST_generate_preferences_stop(partner->pg); + partner->pg = NULL; + } - partner->pg = GNUNET_ATS_TEST_generate_preferences_start(peer, partner, + partner->pg = GNUNET_ATS_TEST_generate_preferences_start(peer, partner, op->tg_type, op->base_rate, op->max_rate, op->period, op->frequency, op->pref_type); - */ + */ } static void -enforce_stop_preference (struct GNUNET_ATS_TEST_Operation *op) +enforce_stop_preference(struct GNUNET_ATS_TEST_Operation *op) { /* - struct BenchmarkPartner *p; - p = GNUNET_ATS_TEST_get_partner (op->src_id, op->dest_id); - if (NULL == p) - { - GNUNET_break (0); - return; - } - - fprintf (stderr, "Found master %llu slave %llu\n",op->src_id, op->dest_id); - - if (NULL != p->pg) - { - fprintf (stderr, "Stopping preference between master %llu slave %llu\n", + struct BenchmarkPartner *p; + p = GNUNET_ATS_TEST_get_partner (op->src_id, op->dest_id); + if (NULL == p) + { + GNUNET_break (0); + return; + } + + fprintf (stderr, "Found master %llu slave %llu\n",op->src_id, op->dest_id); + + if (NULL != p->pg) + { + fprintf (stderr, "Stopping preference between master %llu slave %llu\n", op->src_id, op->dest_id); - GNUNET_ATS_TEST_generate_preferences_stop (p->pg); - p->pg = NULL; - } - */ + GNUNET_ATS_TEST_generate_preferences_stop (p->pg); + p->pg = NULL; + } + */ } -static void enforce_episode (struct Episode *ep) +static void enforce_episode(struct Episode *ep) { struct GNUNET_ATS_TEST_Operation *cur; + for (cur = ep->head; NULL != cur; cur = cur->next) - { + { + fprintf(stderr, "Enforcing operation: %s [%llu]->[%llu] == %llu\n", + print_op(cur->type), cur->src_id, cur->dest_id, cur->base_rate); + switch (cur->type) + { + case START_SEND: + enforce_start_send(cur); + break; + + case STOP_SEND: + enforce_stop_send(cur); + break; - fprintf (stderr, "Enforcing operation: %s [%llu]->[%llu] == %llu\n", - print_op (cur->type), cur->src_id, cur->dest_id, cur->base_rate); - switch (cur->type) { - case START_SEND: - enforce_start_send (cur); - break; - case STOP_SEND: - enforce_stop_send (cur); - break; - case START_PREFERENCE: - enforce_start_preference (cur); - break; - case STOP_PREFERENCE: - enforce_stop_preference (cur); - break; - default: - break; + case START_PREFERENCE: + enforce_start_preference(cur); + break; + + case STOP_PREFERENCE: + enforce_stop_preference(cur); + break; + + default: + break; + } } - } } static void -timeout_episode (void *cls) +timeout_episode(void *cls) { struct Experiment *e = cls; + e->episode_timeout_task = NULL; if (NULL != e->ep_done_cb) - e->ep_done_cb (e->cur); + e->ep_done_cb(e->cur); /* Scheduling next */ e->cur = e->cur->next; if (NULL == e->cur) - { - /* done */ - fprintf (stderr, "Last episode done!\n"); - if (NULL != e->experiment_timeout_task) { - GNUNET_SCHEDULER_cancel (e->experiment_timeout_task); - e->experiment_timeout_task = NULL; + /* done */ + fprintf(stderr, "Last episode done!\n"); + if (NULL != e->experiment_timeout_task) + { + GNUNET_SCHEDULER_cancel(e->experiment_timeout_task); + e->experiment_timeout_task = NULL; + } + e->e_done_cb(e, GNUNET_TIME_absolute_get_duration(e->start_time), GNUNET_OK); + return; } - e->e_done_cb (e, GNUNET_TIME_absolute_get_duration(e->start_time), GNUNET_OK); - return; - } - fprintf (stderr, "Running episode %u with timeout %s\n", - e->cur->id, - GNUNET_STRINGS_relative_time_to_string(e->cur->duration, GNUNET_YES)); + fprintf(stderr, "Running episode %u with timeout %s\n", + e->cur->id, + GNUNET_STRINGS_relative_time_to_string(e->cur->duration, GNUNET_YES)); enforce_episode(e->cur); - e->episode_timeout_task = GNUNET_SCHEDULER_add_delayed (e->cur->duration, - &timeout_episode, e); + e->episode_timeout_task = GNUNET_SCHEDULER_add_delayed(e->cur->duration, + &timeout_episode, e); } void -GNUNET_ATS_solvers_experimentation_run (struct Experiment *e, - GNUNET_ATS_TESTING_EpisodeDoneCallback ep_done_cb, - GNUNET_ATS_TESTING_ExperimentDoneCallback e_done_cb) +GNUNET_ATS_solvers_experimentation_run(struct Experiment *e, + GNUNET_ATS_TESTING_EpisodeDoneCallback ep_done_cb, + GNUNET_ATS_TESTING_ExperimentDoneCallback e_done_cb) { - fprintf (stderr, "Running experiment `%s' with timeout %s\n", e->name, - GNUNET_STRINGS_relative_time_to_string(e->max_duration, GNUNET_YES)); + fprintf(stderr, "Running experiment `%s' with timeout %s\n", e->name, + GNUNET_STRINGS_relative_time_to_string(e->max_duration, GNUNET_YES)); e->e_done_cb = e_done_cb; e->ep_done_cb = ep_done_cb; e->start_time = GNUNET_TIME_absolute_get(); /* Start total time out */ - e->experiment_timeout_task = GNUNET_SCHEDULER_add_delayed (e->max_duration, - &timeout_experiment, e); + e->experiment_timeout_task = GNUNET_SCHEDULER_add_delayed(e->max_duration, + &timeout_experiment, e); /* Start */ e->cur = e->start; - fprintf (stderr, "Running episode %u with timeout %s\n", - e->cur->id, - GNUNET_STRINGS_relative_time_to_string(e->cur->duration, GNUNET_YES)); + fprintf(stderr, "Running episode %u with timeout %s\n", + e->cur->id, + GNUNET_STRINGS_relative_time_to_string(e->cur->duration, GNUNET_YES)); enforce_episode(e->cur); - e->episode_timeout_task = GNUNET_SCHEDULER_add_delayed (e->cur->duration, - &timeout_episode, e); - - + e->episode_timeout_task = GNUNET_SCHEDULER_add_delayed(e->cur->duration, + &timeout_episode, e); } struct Experiment * -GNUNET_ATS_solvers_experimentation_load (char *filename) +GNUNET_ATS_solvers_experimentation_load(char *filename) { struct Experiment *e; struct GNUNET_CONFIGURATION_Handle *cfg; + e = NULL; cfg = GNUNET_CONFIGURATION_create(); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, filename)) - { - fprintf (stderr, "Failed to load `%s'\n", filename); - GNUNET_CONFIGURATION_destroy (cfg); - return NULL; - } + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load(cfg, filename)) + { + fprintf(stderr, "Failed to load `%s'\n", filename); + GNUNET_CONFIGURATION_destroy(cfg); + return NULL; + } - e = create_experiment (); + e = create_experiment(); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, "experiment", - "name", &e->name)) - { - fprintf (stderr, "Invalid %s", "name"); - free_experiment (e); - return NULL; - } + "name", &e->name)) + { + fprintf(stderr, "Invalid %s", "name"); + free_experiment(e); + return NULL; + } else - fprintf (stderr, "Experiment name: `%s'\n", e->name); + fprintf(stderr, "Experiment name: `%s'\n", e->name); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_filename (cfg, "experiment", - "cfg_file", &e->cfg_file)) - { - fprintf (stderr, "Invalid %s", "cfg_file"); - free_experiment (e); - return NULL; - } + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_filename(cfg, "experiment", + "cfg_file", &e->cfg_file)) + { + fprintf(stderr, "Invalid %s", "cfg_file"); + free_experiment(e); + return NULL; + } else - fprintf (stderr, "Experiment name: `%s'\n", e->cfg_file); + fprintf(stderr, "Experiment name: `%s'\n", e->cfg_file); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, "experiment", - "masters", &e->num_masters)) - { - fprintf (stderr, "Invalid %s", "masters"); - free_experiment (e); - return NULL; - } + "masters", &e->num_masters)) + { + fprintf(stderr, "Invalid %s", "masters"); + free_experiment(e); + return NULL; + } else - fprintf (stderr, "Experiment masters: `%llu'\n", - e->num_masters); + fprintf(stderr, "Experiment masters: `%llu'\n", + e->num_masters); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, "experiment", - "slaves", &e->num_slaves)) - { - fprintf (stderr, "Invalid %s", "slaves"); - free_experiment (e); - return NULL; - } + "slaves", &e->num_slaves)) + { + fprintf(stderr, "Invalid %s", "slaves"); + free_experiment(e); + return NULL; + } else - fprintf (stderr, "Experiment slaves: `%llu'\n", - e->num_slaves); + fprintf(stderr, "Experiment slaves: `%llu'\n", + e->num_slaves); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, "experiment", - "log_freq", &e->log_freq)) - { - fprintf (stderr, "Invalid %s", "log_freq"); - free_experiment (e); - return NULL; - } + "log_freq", &e->log_freq)) + { + fprintf(stderr, "Invalid %s", "log_freq"); + free_experiment(e); + return NULL; + } else - fprintf (stderr, "Experiment logging frequency: `%s'\n", - GNUNET_STRINGS_relative_time_to_string (e->log_freq, GNUNET_YES)); + fprintf(stderr, "Experiment logging frequency: `%s'\n", + GNUNET_STRINGS_relative_time_to_string(e->log_freq, GNUNET_YES)); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, "experiment", - "max_duration", &e->max_duration)) - { - fprintf (stderr, "Invalid %s", "max_duration"); - free_experiment (e); - return NULL; - } + "max_duration", &e->max_duration)) + { + fprintf(stderr, "Invalid %s", "max_duration"); + free_experiment(e); + return NULL; + } else - fprintf (stderr, "Experiment duration: `%s'\n", - GNUNET_STRINGS_relative_time_to_string (e->max_duration, GNUNET_YES)); + fprintf(stderr, "Experiment duration: `%s'\n", + GNUNET_STRINGS_relative_time_to_string(e->max_duration, GNUNET_YES)); - load_episodes (e, cfg); - fprintf (stderr, "Loaded %u episodes with total duration %s\n", - e->num_episodes, - GNUNET_STRINGS_relative_time_to_string (e->total_duration, GNUNET_YES)); + load_episodes(e, cfg); + fprintf(stderr, "Loaded %u episodes with total duration %s\n", + e->num_episodes, + GNUNET_STRINGS_relative_time_to_string(e->total_duration, GNUNET_YES)); - GNUNET_CONFIGURATION_destroy (cfg); + GNUNET_CONFIGURATION_destroy(cfg); return e; } void -GNUNET_ATS_solvers_experimentation_stop (struct Experiment *e) +GNUNET_ATS_solvers_experimentation_stop(struct Experiment *e) { if (NULL != e->experiment_timeout_task) - { - GNUNET_SCHEDULER_cancel (e->experiment_timeout_task); - e->experiment_timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(e->experiment_timeout_task); + e->experiment_timeout_task = NULL; + } if (NULL != e->episode_timeout_task) - { - GNUNET_SCHEDULER_cancel (e->episode_timeout_task); - e->episode_timeout_task = NULL; - } - free_experiment (e); + { + GNUNET_SCHEDULER_cancel(e->episode_timeout_task); + e->episode_timeout_task = NULL; + } + free_experiment(e); } /** * Solver */ -struct GNUNET_ATS_TESTING_SolverHandle -{ +struct GNUNET_ATS_TESTING_SolverHandle { char * plugin; struct GNUNET_ATS_PluginEnvironment env; void *solver; }; -enum GNUNET_ATS_Solvers -{ +enum GNUNET_ATS_Solvers { GNUNET_ATS_SOLVER_PROPORTIONAL, GNUNET_ATS_SOLVER_MLP, GNUNET_ATS_SOLVER_RIL, }; void -GNUNET_ATS_solvers_solver_stop (struct GNUNET_ATS_TESTING_SolverHandle *sh) +GNUNET_ATS_solvers_solver_stop(struct GNUNET_ATS_TESTING_SolverHandle *sh) { - GNUNET_PLUGIN_unload (sh->plugin, sh->solver); - GNUNET_free (sh->plugin); - GNUNET_free (sh); + GNUNET_PLUGIN_unload(sh->plugin, sh->solver); + GNUNET_free(sh->plugin); + GNUNET_free(sh); } struct GNUNET_ATS_TESTING_SolverHandle * -GNUNET_ATS_solvers_solver_start (enum GNUNET_ATS_Solvers type) +GNUNET_ATS_solvers_solver_start(enum GNUNET_ATS_Solvers type) { struct GNUNET_ATS_TESTING_SolverHandle *sh; char * solver_str; - switch (type) { + switch (type) + { case GNUNET_ATS_SOLVER_PROPORTIONAL: solver_str = "proportional"; break; + case GNUNET_ATS_SOLVER_MLP: solver_str = "mlp"; break; + case GNUNET_ATS_SOLVER_RIL: solver_str = "ril"; break; + default: - GNUNET_break (0); + GNUNET_break(0); return NULL; break; - } + } - sh = GNUNET_new (struct GNUNET_ATS_TESTING_SolverHandle); - GNUNET_asprintf (&sh->plugin, "libgnunet_plugin_ats_%s", solver_str); + sh = GNUNET_new(struct GNUNET_ATS_TESTING_SolverHandle); + GNUNET_asprintf(&sh->plugin, "libgnunet_plugin_ats_%s", solver_str); //sh->solver = GNUNET_PLUGIN_load (sh->plugin, &sh->env); if (NULL == sh->solver) - { - fprintf (stderr, "Failed to load solver `%s'\n", sh->plugin); - exit (1); - } + { + fprintf(stderr, "Failed to load solver `%s'\n", sh->plugin); + exit(1); + } return sh; } @@ -857,56 +872,56 @@ static int opt_plot; static int opt_verbose; static void -run (void *cls, char * const *args, const char *cfgfile, +run(void *cls, char * const *args, const char *cfgfile, const struct GNUNET_CONFIGURATION_Handle *cfg) { enum GNUNET_ATS_Solvers solver; if (NULL == opt_exp_file) - { - fprintf (stderr, "No experiment given ...\n"); - exit (1); - } + { + fprintf(stderr, "No experiment given ...\n"); + exit(1); + } if (NULL == opt_solver) - { - fprintf (stderr, "No solver given ...\n"); - exit (1); - } + { + fprintf(stderr, "No solver given ...\n"); + exit(1); + } if (0 == strcmp(opt_solver, "mlp")) - { - solver = GNUNET_ATS_SOLVER_MLP; - } + { + solver = GNUNET_ATS_SOLVER_MLP; + } else if (0 == strcmp(opt_solver, "proportional")) - { - solver = GNUNET_ATS_SOLVER_PROPORTIONAL; - } + { + solver = GNUNET_ATS_SOLVER_PROPORTIONAL; + } else if (0 == strcmp(opt_solver, "ril")) - { - solver = GNUNET_ATS_SOLVER_RIL; - } + { + solver = GNUNET_ATS_SOLVER_RIL; + } else - { - fprintf (stderr, "No solver given ..."); - return; - } + { + fprintf(stderr, "No solver given ..."); + return; + } /* load experiment */ - e = GNUNET_ATS_solvers_experimentation_load (opt_exp_file); + e = GNUNET_ATS_solvers_experimentation_load(opt_exp_file); if (NULL == e) - { - fprintf (stderr, "Failed to load experiment ...\n"); - return; - } + { + fprintf(stderr, "Failed to load experiment ...\n"); + return; + } /* load solver */ - sh = GNUNET_ATS_solvers_solver_start (solver); + sh = GNUNET_ATS_solvers_solver_start(solver); if (NULL == sh) - { - fprintf (stderr, "Failed to start solver ...\n"); - return; - } + { + fprintf(stderr, "Failed to start solver ...\n"); + return; + } /* start logging */ @@ -923,9 +938,8 @@ run (void *cls, char * const *args, const char *cfgfile, * @param argv argument values */ int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - opt_exp_file = NULL; opt_solver = NULL; opt_log = GNUNET_NO; @@ -933,31 +947,31 @@ main (int argc, char *argv[]) struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_option_string ('s', - "solver", - NULL, - gettext_noop ("solver to use"), - &opt_solver), - - GNUNET_GETOPT_option_string ('e', - "experiment", - NULL, - gettext_noop ("experiment to use"), - &opt_exp_file), - - GNUNET_GETOPT_option_flag ('e', - "experiment", - gettext_noop ("experiment to use"), - &opt_verbose), + GNUNET_GETOPT_option_string('s', + "solver", + NULL, + gettext_noop("solver to use"), + &opt_solver), + + GNUNET_GETOPT_option_string('e', + "experiment", + NULL, + gettext_noop("experiment to use"), + &opt_exp_file), + + GNUNET_GETOPT_option_flag('e', + "experiment", + gettext_noop("experiment to use"), + &opt_verbose), GNUNET_GETOPT_OPTION_END }; if (GNUNET_OK != - GNUNET_PROGRAM_run (argc, - argv, argv[0], - NULL, - options, - &run, argv[0])) + GNUNET_PROGRAM_run(argc, + argv, argv[0], + NULL, + options, + &run, argv[0])) return 1; return 0; diff --git a/src/ats-tests/perf_ats.c b/src/ats-tests/perf_ats.c index b8ab35f99..c31e8a1c4 100644 --- a/src/ats-tests/perf_ats.c +++ b/src/ats-tests/perf_ats.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2013, 2016 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2013, 2016 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -31,15 +31,15 @@ #include "ats-testing.h" -#define TEST_ATS_PREFRENCE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1) +#define TEST_ATS_PREFRENCE_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1) #define TEST_ATS_PREFRENCE_START 1.0 #define TEST_ATS_PREFRENCE_DELTA 1.0 -#define TEST_MESSAGE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1) +#define TEST_MESSAGE_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1) -#define TEST_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 120) -#define BENCHMARK_DURATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) -#define LOGGING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500) +#define TEST_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 120) +#define BENCHMARK_DURATION GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) +#define LOGGING_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 500) #define TESTNAME_PREFIX "perf_ats_" #define DEFAULT_SLAVES_NUM 2 #define DEFAULT_MASTERS_NUM 1 @@ -123,7 +123,7 @@ static struct LoggingHandle *l; static void -evaluate () +evaluate() { int c_m; int c_s; @@ -139,48 +139,48 @@ evaluate () duration = 1 + (perf_duration.rel_value_us / (1000 * 1000)); for (c_m = 0; c_m < num_masters; c_m++) - { - mp = &mps[c_m]; - fprintf (stderr, - "Master [%u]: sent: %u KiB in %u sec. = %u KiB/s, received: %u KiB in %u sec. = %u KiB/s\n", - mp->no, mp->total_bytes_sent / 1024, duration, - (mp->total_bytes_sent / 1024) / duration, - mp->total_bytes_received / 1024, duration, - (mp->total_bytes_received / 1024) / duration); - - for (c_s = 0; c_s < num_slaves; c_s++) { - p = &mp->partners[c_s]; - kb_sent_sec = 0; - kb_recv_sec = 0; - kb_sent_percent = 0.0; - kb_recv_percent = 0.0; - rtt = 0; - - if (duration > 0) - { - kb_sent_sec = (p->bytes_sent / 1024) / duration; - kb_recv_sec = (p->bytes_received / 1024) / duration; - } - - if (mp->total_bytes_sent > 0) - kb_sent_percent = ((double) p->bytes_sent * 100) / mp->total_bytes_sent; - if (mp->total_bytes_received > 0) - kb_recv_percent = ((double) p->bytes_received * 100) / mp->total_bytes_received; - if (1000 * p->messages_sent > 0) - rtt = p->total_app_rtt / (1000 * p->messages_sent); - fprintf (stderr, - "%c Master [%u] -> Slave [%u]: sent %u KiB/s (%.2f %%), received %u KiB/s (%.2f %%)\n", - (mp->pref_partner == p->dest) ? '*' : ' ', - mp->no, p->dest->no, - kb_sent_sec, kb_sent_percent, - kb_recv_sec, kb_recv_percent); - fprintf (stderr, - "%c Master [%u] -> Slave [%u]: Average application layer RTT: %u ms\n", - (mp->pref_partner == p->dest) ? '*' : ' ', - mp->no, p->dest->no, rtt); + mp = &mps[c_m]; + fprintf(stderr, + "Master [%u]: sent: %u KiB in %u sec. = %u KiB/s, received: %u KiB in %u sec. = %u KiB/s\n", + mp->no, mp->total_bytes_sent / 1024, duration, + (mp->total_bytes_sent / 1024) / duration, + mp->total_bytes_received / 1024, duration, + (mp->total_bytes_received / 1024) / duration); + + for (c_s = 0; c_s < num_slaves; c_s++) + { + p = &mp->partners[c_s]; + kb_sent_sec = 0; + kb_recv_sec = 0; + kb_sent_percent = 0.0; + kb_recv_percent = 0.0; + rtt = 0; + + if (duration > 0) + { + kb_sent_sec = (p->bytes_sent / 1024) / duration; + kb_recv_sec = (p->bytes_received / 1024) / duration; + } + + if (mp->total_bytes_sent > 0) + kb_sent_percent = ((double)p->bytes_sent * 100) / mp->total_bytes_sent; + if (mp->total_bytes_received > 0) + kb_recv_percent = ((double)p->bytes_received * 100) / mp->total_bytes_received; + if (1000 * p->messages_sent > 0) + rtt = p->total_app_rtt / (1000 * p->messages_sent); + fprintf(stderr, + "%c Master [%u] -> Slave [%u]: sent %u KiB/s (%.2f %%), received %u KiB/s (%.2f %%)\n", + (mp->pref_partner == p->dest) ? '*' : ' ', + mp->no, p->dest->no, + kb_sent_sec, kb_sent_percent, + kb_recv_sec, kb_recv_percent); + fprintf(stderr, + "%c Master [%u] -> Slave [%u]: Average application layer RTT: %u ms\n", + (mp->pref_partner == p->dest) ? '*' : ' ', + mp->no, p->dest->no, rtt); + } } - } } @@ -190,24 +190,24 @@ evaluate () * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { if (GNUNET_YES == logging) GNUNET_ATS_TEST_logging_clean_up(l); if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } if (NULL != progress_task) - { - fprintf (stderr, "0\n"); - GNUNET_SCHEDULER_cancel (progress_task); - progress_task = NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Benchmarking done\n"); - GNUNET_ATS_TEST_shutdown_topology (); + { + fprintf(stderr, "0\n"); + GNUNET_SCHEDULER_cancel(progress_task); + progress_task = NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Benchmarking done\n"); + GNUNET_ATS_TEST_shutdown_topology(); } @@ -217,162 +217,163 @@ do_shutdown (void *cls) * @param cls NULL */ static void -do_timeout (void *cls) +do_timeout(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Terminating with timeout\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Terminating with timeout\n"); timeout_task = NULL; - evaluate (); - GNUNET_SCHEDULER_shutdown (); + evaluate(); + GNUNET_SCHEDULER_shutdown(); } static void -print_progress (void *cls) +print_progress(void *cls) { static int calls; progress_task = NULL; - fprintf (stderr, - "%llu..", - (long long unsigned) perf_duration.rel_value_us / (1000 * 1000) - calls); + fprintf(stderr, + "%llu..", + (long long unsigned)perf_duration.rel_value_us / (1000 * 1000) - calls); calls++; - progress_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &print_progress, - NULL); + progress_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &print_progress, + NULL); } static void -ats_pref_task (void *cls) +ats_pref_task(void *cls) { struct BenchmarkPeer *me = cls; me->ats_task = NULL; GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, " Master [%u] set preference for slave [%u] to %f\n", - me->no, me->pref_partner->no, me->pref_value); - GNUNET_ATS_performance_change_preference (me->ats_perf_handle, - &me->pref_partner->id, - pref_val, me->pref_value, GNUNET_ATS_PREFERENCE_END); + me->no, me->pref_partner->no, me->pref_value); + GNUNET_ATS_performance_change_preference(me->ats_perf_handle, + &me->pref_partner->id, + pref_val, me->pref_value, GNUNET_ATS_PREFERENCE_END); me->pref_value += TEST_ATS_PREFRENCE_DELTA; - me->ats_task = GNUNET_SCHEDULER_add_delayed (TEST_ATS_PREFRENCE_FREQUENCY, - &ats_pref_task, cls); + me->ats_task = GNUNET_SCHEDULER_add_delayed(TEST_ATS_PREFRENCE_FREQUENCY, + &ats_pref_task, cls); } static void -start_benchmark (void *cls) +start_benchmark(void *cls) { int c_m; int c_s; - progress_task = GNUNET_SCHEDULER_add_now (&print_progress, - NULL); + progress_task = GNUNET_SCHEDULER_add_now(&print_progress, + NULL); GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Topology connected, start benchmarking...\n"); /* Start sending test messages */ for (c_m = 0; c_m < num_masters; c_m++) - { - for (c_s = 0; c_s < num_slaves; c_s++) { - GNUNET_ATS_TEST_generate_traffic_start (&mps[c_m], - &mps[c_m].partners[c_s], - GNUNET_ATS_TEST_TG_LINEAR, - UINT32_MAX, - UINT32_MAX, - GNUNET_TIME_UNIT_MINUTES, - GNUNET_TIME_UNIT_FOREVER_REL); + for (c_s = 0; c_s < num_slaves; c_s++) + { + GNUNET_ATS_TEST_generate_traffic_start(&mps[c_m], + &mps[c_m].partners[c_s], + GNUNET_ATS_TEST_TG_LINEAR, + UINT32_MAX, + UINT32_MAX, + GNUNET_TIME_UNIT_MINUTES, + GNUNET_TIME_UNIT_FOREVER_REL); + } + if (pref_val != GNUNET_ATS_PREFERENCE_END) + mps[c_m].ats_task = GNUNET_SCHEDULER_add_now(&ats_pref_task, + &mps[c_m]); } - if (pref_val != GNUNET_ATS_PREFERENCE_END) - mps[c_m].ats_task = GNUNET_SCHEDULER_add_now (&ats_pref_task, - &mps[c_m]); - } if (GNUNET_YES == logging) - l = GNUNET_ATS_TEST_logging_start (log_frequency, - testname, mps, - num_masters, num_slaves, - GNUNET_NO); + l = GNUNET_ATS_TEST_logging_start(log_frequency, + testname, mps, + num_masters, num_slaves, + GNUNET_NO); } static void -do_benchmark (void *cls, - struct BenchmarkPeer *masters, - struct BenchmarkPeer *slaves) +do_benchmark(void *cls, + struct BenchmarkPeer *masters, + struct BenchmarkPeer *slaves) { mps = masters; sps = slaves; - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - timeout_task = GNUNET_SCHEDULER_add_delayed (perf_duration, - &do_timeout, - NULL); - progress_task = GNUNET_SCHEDULER_add_now (&start_benchmark, - NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); + timeout_task = GNUNET_SCHEDULER_add_delayed(perf_duration, + &do_timeout, + NULL); + progress_task = GNUNET_SCHEDULER_add_now(&start_benchmark, + NULL); } static struct BenchmarkPartner * -find_partner (struct BenchmarkPeer *me, - const struct GNUNET_PeerIdentity *peer) +find_partner(struct BenchmarkPeer *me, + const struct GNUNET_PeerIdentity *peer) { int c_m; - GNUNET_assert (NULL != me); - GNUNET_assert (NULL != peer); + + GNUNET_assert(NULL != me); + GNUNET_assert(NULL != peer); for (c_m = 0; c_m < me->num_partners; c_m++) - { - /* Find a partner with other as destination */ - if (0 == GNUNET_memcmp (peer, &me->partners[c_m].dest->id)) { - return &me->partners[c_m]; + /* Find a partner with other as destination */ + if (0 == GNUNET_memcmp(peer, &me->partners[c_m].dest->id)) + { + return &me->partners[c_m]; + } } - } return NULL; } static void -log_request_cb (void *cls, - const struct GNUNET_HELLO_Address *address, - int address_active, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, - const struct GNUNET_ATS_Properties *ats) +log_request_cb(void *cls, + const struct GNUNET_HELLO_Address *address, + int address_active, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, + const struct GNUNET_ATS_Properties *ats) { struct BenchmarkPeer *me = cls; struct BenchmarkPartner *p; char *peer_id; - p = find_partner (me, &address->peer); + p = find_partner(me, &address->peer); if (NULL == p) - { - /* This is not one of my partners - * Will happen since the peers will connect to each other due to gossiping - */ - return; - } - peer_id = GNUNET_strdup (GNUNET_i2s (&me->id)); - - if ((p->bandwidth_in != ntohl (bandwidth_in.value__)) || - (p->bandwidth_out != ntohl (bandwidth_out.value__))) - p->bandwidth_in = ntohl (bandwidth_in.value__); - p->bandwidth_out = ntohl (bandwidth_out.value__); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "%s [%u] received ATS information for peers `%s'\n", - (GNUNET_YES == p->me->master) ? "Master" : "Slave", - p->me->no, - GNUNET_i2s (&p->dest->id)); - - GNUNET_free (peer_id); + { + /* This is not one of my partners + * Will happen since the peers will connect to each other due to gossiping + */ + return; + } + peer_id = GNUNET_strdup(GNUNET_i2s(&me->id)); + + if ((p->bandwidth_in != ntohl(bandwidth_in.value__)) || + (p->bandwidth_out != ntohl(bandwidth_out.value__))) + p->bandwidth_in = ntohl(bandwidth_in.value__); + p->bandwidth_out = ntohl(bandwidth_out.value__); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "%s [%u] received ATS information for peers `%s'\n", + (GNUNET_YES == p->me->master) ? "Master" : "Slave", + p->me->no, + GNUNET_i2s(&p->dest->id)); + + GNUNET_free(peer_id); if (NULL != l) - GNUNET_ATS_TEST_logging_now (l); + GNUNET_ATS_TEST_logging_now(l); } @@ -380,7 +381,7 @@ log_request_cb (void *cls, * Start the performance test case */ int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { char *tmp; char *tmp_sep; @@ -397,187 +398,187 @@ main (int argc, char *argv[]) * perf_ats___[.exe]*/ /* Find test prefix, store in temp */ - tmp = strstr (argv[0], TESTNAME_PREFIX); + tmp = strstr(argv[0], TESTNAME_PREFIX); if (NULL == tmp) - { - fprintf (stderr, "Unable to parse test name `%s'\n", argv[0]); - return GNUNET_SYSERR; - } + { + fprintf(stderr, "Unable to parse test name `%s'\n", argv[0]); + return GNUNET_SYSERR; + } /* Set tmp to end of test name prefix */ - tmp += strlen (TESTNAME_PREFIX); + tmp += strlen(TESTNAME_PREFIX); /* Determine solver name */ - solver = GNUNET_strdup (tmp); + solver = GNUNET_strdup(tmp); /* Remove .exe prefix */ - if (NULL != (dotexe = strstr (solver, ".exe")) && dotexe[4] == '\0') + if (NULL != (dotexe = strstr(solver, ".exe")) && dotexe[4] == '\0') dotexe[0] = '\0'; /* Determine first '_' after solver */ - tmp_sep = strchr (solver, '_'); + tmp_sep = strchr(solver, '_'); if (NULL == tmp_sep) - { - fprintf (stderr, "Unable to parse test name `%s'\n", argv[0]); - GNUNET_free(solver); - return GNUNET_SYSERR; - } + { + fprintf(stderr, "Unable to parse test name `%s'\n", argv[0]); + GNUNET_free(solver); + return GNUNET_SYSERR; + } tmp_sep[0] = '\0'; - comm_name = GNUNET_strdup (&tmp_sep[1]); - tmp_sep = strchr (comm_name, '_'); + comm_name = GNUNET_strdup(&tmp_sep[1]); + tmp_sep = strchr(comm_name, '_'); if (NULL == tmp_sep) - { - fprintf (stderr, "Unable to parse test name `%s'\n", argv[0]); - GNUNET_free(solver); - return GNUNET_SYSERR; - } + { + fprintf(stderr, "Unable to parse test name `%s'\n", argv[0]); + GNUNET_free(solver); + return GNUNET_SYSERR; + } tmp_sep[0] = '\0'; - for (c = 0; c <= strlen (comm_name); c++) - comm_name[c] = toupper (comm_name[c]); - if (0 == strcmp (comm_name, "CORE")) + for (c = 0; c <= strlen(comm_name); c++) + comm_name[c] = toupper(comm_name[c]); + if (0 == strcmp(comm_name, "CORE")) test_core = GNUNET_YES; - else if (0 == strcmp (comm_name, "TRANSPORT")) + else if (0 == strcmp(comm_name, "TRANSPORT")) test_core = GNUNET_NO; else - { - GNUNET_free (comm_name); - GNUNET_free (solver); - return GNUNET_SYSERR; - } + { + GNUNET_free(comm_name); + GNUNET_free(solver); + return GNUNET_SYSERR; + } pref_str = GNUNET_strdup(tmp_sep + 1); - GNUNET_asprintf (&conf_name, "%s%s_%s.conf", TESTNAME_PREFIX, solver, - pref_str); - GNUNET_asprintf (&test_name, "%s%s_%s", TESTNAME_PREFIX, solver, pref_str); + GNUNET_asprintf(&conf_name, "%s%s_%s.conf", TESTNAME_PREFIX, solver, + pref_str); + GNUNET_asprintf(&test_name, "%s%s_%s", TESTNAME_PREFIX, solver, pref_str); - for (c = 0; c <= strlen (pref_str); c++) - pref_str[c] = toupper (pref_str[c]); + for (c = 0; c <= strlen(pref_str); c++) + pref_str[c] = toupper(pref_str[c]); pref_val = -1; - if (0 != strcmp (pref_str, "NONE")) - { - for (c = 0; c < GNUNET_ATS_PREFERENCE_END; c++) + if (0 != strcmp(pref_str, "NONE")) { - if (0 == strcmp (pref_str, prefs[c])) - { - pref_val = c; - break; - } + for (c = 0; c < GNUNET_ATS_PREFERENCE_END; c++) + { + if (0 == strcmp(pref_str, prefs[c])) + { + pref_val = c; + break; + } + } } - } else - { - /* abuse terminator to indicate no pref */ - pref_val = GNUNET_ATS_PREFERENCE_END; - } + { + /* abuse terminator to indicate no pref */ + pref_val = GNUNET_ATS_PREFERENCE_END; + } if (-1 == pref_val) - { - fprintf (stderr, "Unknown preference: `%s'\n", pref_str); - GNUNET_free(solver); - GNUNET_free(pref_str); - GNUNET_free (comm_name); - return -1; - } + { + fprintf(stderr, "Unknown preference: `%s'\n", pref_str); + GNUNET_free(solver); + GNUNET_free(pref_str); + GNUNET_free(comm_name); + return -1; + } for (c = 0; c < (argc - 1); c++) - { - if (0 == strcmp (argv[c], "-d")) - break; - } + { + if (0 == strcmp(argv[c], "-d")) + break; + } if (c < argc - 1) - { - if (GNUNET_OK != GNUNET_STRINGS_fancy_time_to_relative (argv[c + 1], &perf_duration)) - fprintf (stderr, "Failed to parse duration `%s'\n", argv[c + 1]); - } + { + if (GNUNET_OK != GNUNET_STRINGS_fancy_time_to_relative(argv[c + 1], &perf_duration)) + fprintf(stderr, "Failed to parse duration `%s'\n", argv[c + 1]); + } else - { - perf_duration = BENCHMARK_DURATION; - } - fprintf (stderr, "Running benchmark for %llu secs\n", (unsigned long long) (perf_duration.rel_value_us) / (1000 * 1000)); + { + perf_duration = BENCHMARK_DURATION; + } + fprintf(stderr, "Running benchmark for %llu secs\n", (unsigned long long)(perf_duration.rel_value_us) / (1000 * 1000)); for (c = 0; c < (argc - 1); c++) - { - if (0 == strcmp (argv[c], "-s")) - break; - } + { + if (0 == strcmp(argv[c], "-s")) + break; + } if (c < argc - 1) - { - if ((0L != (num_slaves = strtol (argv[c + 1], NULL, 10))) - && (num_slaves >= 1)) - fprintf (stderr, "Starting %u slave peers\n", num_slaves); - else - num_slaves = DEFAULT_SLAVES_NUM; - } + { + if ((0L != (num_slaves = strtol(argv[c + 1], NULL, 10))) + && (num_slaves >= 1)) + fprintf(stderr, "Starting %u slave peers\n", num_slaves); + else + num_slaves = DEFAULT_SLAVES_NUM; + } else num_slaves = DEFAULT_SLAVES_NUM; for (c = 0; c < (argc - 1); c++) - { - if (0 == strcmp (argv[c], "-m")) - break; - } + { + if (0 == strcmp(argv[c], "-m")) + break; + } if (c < argc - 1) - { - if ((0L != (num_masters = strtol (argv[c + 1], NULL, 10))) - && (num_masters >= 2)) - fprintf (stderr, "Starting %u master peers\n", num_masters); - else - num_masters = DEFAULT_MASTERS_NUM; - } + { + if ((0L != (num_masters = strtol(argv[c + 1], NULL, 10))) + && (num_masters >= 2)) + fprintf(stderr, "Starting %u master peers\n", num_masters); + else + num_masters = DEFAULT_MASTERS_NUM; + } else num_masters = DEFAULT_MASTERS_NUM; logging = GNUNET_NO; for (c = 0; c < argc; c++) - { - if (0 == strcmp (argv[c], "-l")) - logging = GNUNET_YES; - } - - if (GNUNET_YES == logging) - { - for (c = 0; c < (argc - 1); c++) { - if (0 == strcmp (argv[c], "-f")) - break; + if (0 == strcmp(argv[c], "-l")) + logging = GNUNET_YES; } - if (c < argc - 1) - { - if (GNUNET_OK != GNUNET_STRINGS_fancy_time_to_relative (argv[c + 1], &log_frequency)) - fprintf (stderr, "Failed to parse duration `%s'\n", argv[c + 1]); - } - else + + if (GNUNET_YES == logging) { - log_frequency = LOGGING_FREQUENCY; + for (c = 0; c < (argc - 1); c++) + { + if (0 == strcmp(argv[c], "-f")) + break; + } + if (c < argc - 1) + { + if (GNUNET_OK != GNUNET_STRINGS_fancy_time_to_relative(argv[c + 1], &log_frequency)) + fprintf(stderr, "Failed to parse duration `%s'\n", argv[c + 1]); + } + else + { + log_frequency = LOGGING_FREQUENCY; + } + fprintf(stderr, "Using log frequency %llu ms\n", + (unsigned long long)(log_frequency.rel_value_us) / (1000)); } - fprintf (stderr, "Using log frequency %llu ms\n", - (unsigned long long) (log_frequency.rel_value_us) / (1000)); - } - GNUNET_asprintf (&testname, "%s_%s_%s",solver, comm_name, pref_str); + GNUNET_asprintf(&testname, "%s_%s_%s", solver, comm_name, pref_str); if (num_slaves < num_masters) - { - fprintf (stderr, - "Number of master peers is lower than slaves! exit...\n"); - GNUNET_free(test_name); - GNUNET_free(solver); - GNUNET_free(pref_str); - GNUNET_free (comm_name); - return GNUNET_SYSERR; - } + { + fprintf(stderr, + "Number of master peers is lower than slaves! exit...\n"); + GNUNET_free(test_name); + GNUNET_free(solver); + GNUNET_free(pref_str); + GNUNET_free(comm_name); + return GNUNET_SYSERR; + } /** * Setup the topology */ - GNUNET_ATS_TEST_create_topology ("perf-ats", - conf_name, - num_slaves, - num_masters, - test_core, - &do_benchmark, - NULL, - &log_request_cb); + GNUNET_ATS_TEST_create_topology("perf-ats", + conf_name, + num_slaves, + num_masters, + test_core, + &do_benchmark, + NULL, + &log_request_cb); return result; } diff --git a/src/ats-tests/perf_ats.h b/src/ats-tests/perf_ats.h index 4b52d4482..2d552a5d7 100644 --- a/src/ats-tests/perf_ats.h +++ b/src/ats-tests/perf_ats.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2013 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2013 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -30,27 +30,26 @@ #include "gnunet_core_service.h" #include "ats-testing.h" -#define TEST_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 120) -#define BENCHMARK_DURATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) -#define LOGGING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500) +#define TEST_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 120) +#define BENCHMARK_DURATION GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) +#define LOGGING_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 500) #define TESTNAME_PREFIX "perf_ats_" #define DEFAULT_SLAVES_NUM 2 #define DEFAULT_MASTERS_NUM 1 -#define TEST_ATS_PREFRENCE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1) +#define TEST_ATS_PREFRENCE_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1) #define TEST_ATS_PREFRENCE_START 1.0 #define TEST_ATS_PREFRENCE_DELTA 1.0 #define TEST_MESSAGE_TYPE_PING 12345 #define TEST_MESSAGE_TYPE_PONG 12346 #define TEST_MESSAGE_SIZE 1000 -#define TEST_MESSAGE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1) +#define TEST_MESSAGE_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1) /** * Information about a benchmarking partner */ -struct BenchmarkPartner -{ +struct BenchmarkPartner { /** * The peer itself this partner belongs to */ @@ -128,8 +127,7 @@ struct BenchmarkPartner /** * Information we track for a peer in the testbed. */ -struct BenchmarkPeer -{ +struct BenchmarkPeer { /** * Handle with testbed. */ diff --git a/src/ats-tests/perf_ats_logging.c b/src/ats-tests/perf_ats_logging.c index 4b59515d3..e0f192ae4 100644 --- a/src/ats-tests/perf_ats_logging.c +++ b/src/ats-tests/perf_ats_logging.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2013 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2013 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -28,25 +28,25 @@ #include "perf_ats.h" #define THROUGHPUT_TEMPLATE "#!/usr/bin/gnuplot \n" \ -"set datafile separator ';' \n" \ -"set title \"Throughput between Master and Slaves\" \n" \ -"set xlabel \"Time in ms\" \n" \ -"set ylabel \"Bytes/s\" \n" \ -"set grid \n" + "set datafile separator ';' \n" \ + "set title \"Throughput between Master and Slaves\" \n" \ + "set xlabel \"Time in ms\" \n" \ + "set ylabel \"Bytes/s\" \n" \ + "set grid \n" #define RTT_TEMPLATE "#!/usr/bin/gnuplot \n" \ -"set datafile separator ';' \n" \ -"set title \"Application level roundtrip time between Master and Slaves\" \n" \ -"set xlabel \"Time in ms\" \n" \ -"set ylabel \"ms\" \n" \ -"set grid \n" + "set datafile separator ';' \n" \ + "set title \"Application level roundtrip time between Master and Slaves\" \n" \ + "set xlabel \"Time in ms\" \n" \ + "set ylabel \"ms\" \n" \ + "set grid \n" #define BW_TEMPLATE "#!/usr/bin/gnuplot \n" \ -"set datafile separator ';' \n" \ -"set title \"Bandwidth inbound and outbound between Master and Slaves\" \n" \ -"set xlabel \"Time in ms\" \n" \ -"set ylabel \"Bytes / s \" \n" \ -"set grid \n" + "set datafile separator ';' \n" \ + "set title \"Bandwidth inbound and outbound between Master and Slaves\" \n" \ + "set xlabel \"Time in ms\" \n" \ + "set ylabel \"Bytes / s \" \n" \ + "set grid \n" #define LOG_ITEMS_TIME 2 #define LOG_ITEMS_PER_PEER 17 @@ -85,8 +85,7 @@ static struct GNUNET_TIME_Relative frequency; /** * A single logging time step for a partner */ -struct PartnerLoggingTimestep -{ +struct PartnerLoggingTimestep { /** * Peer */ @@ -159,8 +158,7 @@ struct PartnerLoggingTimestep /** * A single logging time step for a peer */ -struct PeerLoggingTimestep -{ +struct PeerLoggingTimestep { /** * Next in DLL */ @@ -215,8 +213,7 @@ struct PeerLoggingTimestep /** * Entry for a benchmark peer */ -struct LoggingPeer -{ +struct LoggingPeer { /** * Peer */ @@ -245,7 +242,7 @@ static struct LoggingPeer *lp; static void -write_throughput_gnuplot_script (char * fn, struct LoggingPeer *lp) +write_throughput_gnuplot_script(char * fn, struct LoggingPeer *lp) { struct GNUNET_DISK_FileHandle *f; char * gfn; @@ -253,57 +250,57 @@ write_throughput_gnuplot_script (char * fn, struct LoggingPeer *lp) int c_s; int peer_index; - GNUNET_asprintf (&gfn, "gnuplot_throughput_%s",fn); - f = GNUNET_DISK_file_open (gfn, - GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); + GNUNET_asprintf(&gfn, "gnuplot_throughput_%s", fn); + f = GNUNET_DISK_file_open(gfn, + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); if (NULL == f) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot open gnuplot file `%s'\n", gfn); - GNUNET_free (gfn); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot open gnuplot file `%s'\n", gfn); + GNUNET_free(gfn); + return; + } /* Write header */ if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, THROUGHPUT_TEMPLATE, strlen(THROUGHPUT_TEMPLATE))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); /* Write master data */ peer_index = LOG_ITEMS_TIME; - GNUNET_asprintf (&data, "plot '%s' using 2:%u with lines title 'Master %u send total', \\\n" \ - "'%s' using 2:%u with lines title 'Master %u receive total', \\\n", - fn, peer_index + LOG_ITEM_THROUGHPUT_SENT, lp->peer->no, - fn, peer_index + LOG_ITEM_THROUGHPUT_RECV, lp->peer->no); + GNUNET_asprintf(&data, "plot '%s' using 2:%u with lines title 'Master %u send total', \\\n" \ + "'%s' using 2:%u with lines title 'Master %u receive total', \\\n", + fn, peer_index + LOG_ITEM_THROUGHPUT_SENT, lp->peer->no, + fn, peer_index + LOG_ITEM_THROUGHPUT_RECV, lp->peer->no); if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); - GNUNET_free (data); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); + GNUNET_free(data); - peer_index = LOG_ITEMS_TIME + LOG_ITEMS_PER_PEER ; + peer_index = LOG_ITEMS_TIME + LOG_ITEMS_PER_PEER; for (c_s = 0; c_s < lp->peer->num_partners; c_s++) - { - GNUNET_asprintf (&data, "'%s' using 2:%u with lines title 'Master %u - Slave %u send', \\\n" \ - "'%s' using 2:%u with lines title 'Master %u - Slave %u receive'%s\n", - fn, peer_index + LOG_ITEM_THROUGHPUT_SENT, lp->peer->no, lp->peer->partners[c_s].dest->no, - fn, peer_index + LOG_ITEM_THROUGHPUT_RECV, lp->peer->no, lp->peer->partners[c_s].dest->no, - (c_s < lp->peer->num_partners -1) ? ", \\" : "\n pause -1"); - if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); - GNUNET_free (data); - peer_index += LOG_ITEMS_PER_PEER; - } + { + GNUNET_asprintf(&data, "'%s' using 2:%u with lines title 'Master %u - Slave %u send', \\\n" \ + "'%s' using 2:%u with lines title 'Master %u - Slave %u receive'%s\n", + fn, peer_index + LOG_ITEM_THROUGHPUT_SENT, lp->peer->no, lp->peer->partners[c_s].dest->no, + fn, peer_index + LOG_ITEM_THROUGHPUT_RECV, lp->peer->no, lp->peer->partners[c_s].dest->no, + (c_s < lp->peer->num_partners - 1) ? ", \\" : "\n pause -1"); + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); + GNUNET_free(data); + peer_index += LOG_ITEMS_PER_PEER; + } if (GNUNET_SYSERR == GNUNET_DISK_file_close(f)) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot close gnuplot file `%s'\n", gfn); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot close gnuplot file `%s'\n", gfn); else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Data successfully written to plot file `%s'\n", gfn); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Data successfully written to plot file `%s'\n", gfn); - GNUNET_free (gfn); + GNUNET_free(gfn); } static void -write_rtt_gnuplot_script (char * fn, struct LoggingPeer *lp) +write_rtt_gnuplot_script(char * fn, struct LoggingPeer *lp) { struct GNUNET_DISK_FileHandle *f; char * gfn; @@ -311,44 +308,44 @@ write_rtt_gnuplot_script (char * fn, struct LoggingPeer *lp) int c_s; int index; - GNUNET_asprintf (&gfn, "gnuplot_rtt_%s",fn); - f = GNUNET_DISK_file_open (gfn, - GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); + GNUNET_asprintf(&gfn, "gnuplot_rtt_%s", fn); + f = GNUNET_DISK_file_open(gfn, + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); if (NULL == f) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot open gnuplot file `%s'\n", gfn); - GNUNET_free (gfn); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot open gnuplot file `%s'\n", gfn); + GNUNET_free(gfn); + return; + } /* Write header */ if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, RTT_TEMPLATE, strlen(RTT_TEMPLATE))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); index = LOG_ITEMS_TIME + LOG_ITEMS_PER_PEER; for (c_s = 0; c_s < lp->peer->num_partners; c_s++) - { - GNUNET_asprintf (&data, "%s'%s' using 2:%u with lines title 'Master %u - Slave %u '%s\n", - (0 == c_s) ? "plot " :"", - fn, index + LOG_ITEM_APP_RTT, lp->peer->no, lp->peer->partners[c_s].dest->no, - (c_s < lp->peer->num_partners -1) ? ", \\" : "\n pause -1"); - if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); - GNUNET_free (data); - index += LOG_ITEMS_PER_PEER; - } + { + GNUNET_asprintf(&data, "%s'%s' using 2:%u with lines title 'Master %u - Slave %u '%s\n", + (0 == c_s) ? "plot " : "", + fn, index + LOG_ITEM_APP_RTT, lp->peer->no, lp->peer->partners[c_s].dest->no, + (c_s < lp->peer->num_partners - 1) ? ", \\" : "\n pause -1"); + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); + GNUNET_free(data); + index += LOG_ITEMS_PER_PEER; + } if (GNUNET_SYSERR == GNUNET_DISK_file_close(f)) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot close gnuplot file `%s'\n", gfn); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot close gnuplot file `%s'\n", gfn); else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Data successfully written to plot file `%s'\n", gfn); - GNUNET_free (gfn); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Data successfully written to plot file `%s'\n", gfn); + GNUNET_free(gfn); } static void -write_bw_gnuplot_script (char * fn, struct LoggingPeer *lp) +write_bw_gnuplot_script(char * fn, struct LoggingPeer *lp) { struct GNUNET_DISK_FileHandle *f; char * gfn; @@ -356,49 +353,49 @@ write_bw_gnuplot_script (char * fn, struct LoggingPeer *lp) int c_s; int index; - GNUNET_asprintf (&gfn, "gnuplot_bw_%s",fn); - f = GNUNET_DISK_file_open (gfn, - GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); + GNUNET_asprintf(&gfn, "gnuplot_bw_%s", fn); + f = GNUNET_DISK_file_open(gfn, + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); if (NULL == f) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot open gnuplot file `%s'\n", gfn); - GNUNET_free (gfn); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot open gnuplot file `%s'\n", gfn); + GNUNET_free(gfn); + return; + } /* Write header */ if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, BW_TEMPLATE, strlen(BW_TEMPLATE))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); index = LOG_ITEMS_TIME + LOG_ITEMS_PER_PEER; for (c_s = 0; c_s < lp->peer->num_partners; c_s++) - { - GNUNET_asprintf (&data, "%s"\ - "'%s' using 2:%u with lines title 'BW out master %u - Slave %u ', \\\n" \ - "'%s' using 2:%u with lines title 'BW in master %u - Slave %u '"\ - "%s\n", - (0 == c_s) ? "plot " :"", - fn, index + LOG_ITEM_ATS_BW_OUT, lp->peer->no, lp->peer->partners[c_s].dest->no, - fn, index + LOG_ITEM_ATS_BW_IN, lp->peer->no, lp->peer->partners[c_s].dest->no, - (c_s < lp->peer->num_partners -1) ? ", \\" : "\n pause -1"); - if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); - GNUNET_free (data); - index += LOG_ITEMS_PER_PEER; - } + { + GNUNET_asprintf(&data, "%s" \ + "'%s' using 2:%u with lines title 'BW out master %u - Slave %u ', \\\n" \ + "'%s' using 2:%u with lines title 'BW in master %u - Slave %u '" \ + "%s\n", + (0 == c_s) ? "plot " : "", + fn, index + LOG_ITEM_ATS_BW_OUT, lp->peer->no, lp->peer->partners[c_s].dest->no, + fn, index + LOG_ITEM_ATS_BW_IN, lp->peer->no, lp->peer->partners[c_s].dest->no, + (c_s < lp->peer->num_partners - 1) ? ", \\" : "\n pause -1"); + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to plot file `%s'\n", gfn); + GNUNET_free(data); + index += LOG_ITEMS_PER_PEER; + } if (GNUNET_SYSERR == GNUNET_DISK_file_close(f)) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot close gnuplot file `%s'\n", gfn); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot close gnuplot file `%s'\n", gfn); else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Data successfully written to plot file `%s'\n", gfn); - GNUNET_free (gfn); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Data successfully written to plot file `%s'\n", gfn); + GNUNET_free(gfn); } static void -write_to_file () +write_to_file() { struct GNUNET_DISK_FileHandle *f; @@ -412,88 +409,88 @@ write_to_file () int c_s; for (c_m = 0; c_m < num_peers; c_m++) - { - GNUNET_asprintf (&filename, "%llu_master_%u_%s_%s.data", GNUNET_TIME_absolute_get().abs_value_us, - lp[c_m].peer->no, GNUNET_i2s(&lp[c_m].peer->id), name); - - f = GNUNET_DISK_file_open (filename, - GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); - if (NULL == f) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot open log file `%s'\n", filename); - GNUNET_free (filename); - return; + GNUNET_asprintf(&filename, "%llu_master_%u_%s_%s.data", GNUNET_TIME_absolute_get().abs_value_us, + lp[c_m].peer->no, GNUNET_i2s(&lp[c_m].peer->id), name); + + f = GNUNET_DISK_file_open(filename, + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); + if (NULL == f) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot open log file `%s'\n", filename); + GNUNET_free(filename); + return; + } + + for (cur_lt = lp[c_m].head; NULL != cur_lt; cur_lt = cur_lt->next) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Master [%u]: timestamp %llu %llu ; %u %u %u ; %u %u %u\n", lp[c_m].peer->no, + cur_lt->timestamp, GNUNET_TIME_absolute_get_difference(lp[c_m].start, cur_lt->timestamp).rel_value_us / 1000, + cur_lt->total_messages_sent, cur_lt->total_bytes_sent, cur_lt->total_throughput_send, + cur_lt->total_messages_received, cur_lt->total_bytes_received, cur_lt->total_throughput_recv); + + slave_string = GNUNET_strdup(";"); + for (c_s = 0; c_s < lp[c_m].peer->num_partners; c_s++) + { + plt = &cur_lt->slaves_log[c_s]; + /* Log partners */ + + /* Assembling slave string */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "\t Slave [%u]: %u %u %u ; %u %u %u rtt %u delay %u bw_in %u bw_out %u \n", plt->slave->no, + plt->total_messages_sent, plt->total_bytes_sent, plt->throughput_sent, + plt->total_messages_received, plt->total_bytes_received, plt->throughput_recv, + plt->app_rtt, plt->ats_delay, + plt->bandwidth_in, plt->bandwidth_out); + + GNUNET_asprintf(&slave_string_tmp, "%s%u;%u;%u;%u;%u;%u;%.3f;%u;%u;%u;%u;%u;%u;%u;%u;%u;%u;", slave_string, + plt->total_messages_sent, plt->total_bytes_sent, plt->throughput_sent, + plt->total_messages_received, plt->total_bytes_received, plt->throughput_sent, + (double)plt->app_rtt / 1000, + plt->bandwidth_in, plt->bandwidth_out, + plt->ats_cost_lan, plt->ats_cost_wan, plt->ats_cost_wlan, + plt->ats_delay, plt->ats_distance, plt->ats_network_type, + plt->ats_utilization_up, plt->ats_utilization_down); + GNUNET_free(slave_string); + slave_string = slave_string_tmp; + } + /* Assembling master string */ + + + + GNUNET_asprintf(&data, "%llu;%llu;%u;%u;%u;%u;%u;%u;;;;;;;;;;;%s\n", + cur_lt->timestamp, + GNUNET_TIME_absolute_get_difference(lp[c_m].start, cur_lt->timestamp).rel_value_us / 1000, + cur_lt->total_messages_sent, cur_lt->total_bytes_sent, cur_lt->total_throughput_send, + cur_lt->total_messages_received, cur_lt->total_bytes_received, cur_lt->total_throughput_recv, + slave_string); + GNUNET_free(slave_string); + + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot write data to log file `%s'\n", filename); + GNUNET_free(data); + } + if (GNUNET_SYSERR == GNUNET_DISK_file_close(f)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot close log file `%s'\n", filename); + GNUNET_free(filename); + return; + } + + write_throughput_gnuplot_script(filename, lp); + write_rtt_gnuplot_script(filename, lp); + write_bw_gnuplot_script(filename, lp); + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Data file successfully written to log file `%s'\n", filename); + GNUNET_free(filename); } - - for (cur_lt = lp[c_m].head; NULL != cur_lt; cur_lt = cur_lt->next) - { - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Master [%u]: timestamp %llu %llu ; %u %u %u ; %u %u %u\n", lp[c_m].peer->no, - cur_lt->timestamp, GNUNET_TIME_absolute_get_difference(lp[c_m].start,cur_lt->timestamp).rel_value_us / 1000, - cur_lt->total_messages_sent, cur_lt->total_bytes_sent, cur_lt->total_throughput_send, - cur_lt->total_messages_received, cur_lt->total_bytes_received, cur_lt->total_throughput_recv); - - slave_string = GNUNET_strdup (";"); - for (c_s = 0; c_s < lp[c_m].peer->num_partners; c_s++) - { - plt = &cur_lt->slaves_log[c_s]; - /* Log partners */ - - /* Assembling slave string */ - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "\t Slave [%u]: %u %u %u ; %u %u %u rtt %u delay %u bw_in %u bw_out %u \n", plt->slave->no, - plt->total_messages_sent, plt->total_bytes_sent, plt->throughput_sent, - plt->total_messages_received, plt->total_bytes_received, plt->throughput_recv, - plt->app_rtt, plt->ats_delay, - plt->bandwidth_in, plt->bandwidth_out); - - GNUNET_asprintf(&slave_string_tmp, "%s%u;%u;%u;%u;%u;%u;%.3f;%u;%u;%u;%u;%u;%u;%u;%u;%u;%u;",slave_string, - plt->total_messages_sent, plt->total_bytes_sent, plt->throughput_sent, - plt->total_messages_received, plt->total_bytes_received, plt->throughput_sent, - (double) plt->app_rtt / 1000, - plt->bandwidth_in,plt->bandwidth_out, - plt->ats_cost_lan, plt->ats_cost_wan, plt->ats_cost_wlan, - plt->ats_delay, plt->ats_distance, plt->ats_network_type, - plt->ats_utilization_up, plt->ats_utilization_down); - GNUNET_free (slave_string); - slave_string = slave_string_tmp; - } - /* Assembling master string */ - - - - GNUNET_asprintf (&data, "%llu;%llu;%u;%u;%u;%u;%u;%u;;;;;;;;;;;%s\n", - cur_lt->timestamp, - GNUNET_TIME_absolute_get_difference(lp[c_m].start,cur_lt->timestamp).rel_value_us / 1000, - cur_lt->total_messages_sent, cur_lt->total_bytes_sent, cur_lt->total_throughput_send, - cur_lt->total_messages_received, cur_lt->total_bytes_received, cur_lt->total_throughput_recv, - slave_string); - GNUNET_free (slave_string); - - if (GNUNET_SYSERR == GNUNET_DISK_file_write(f, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot write data to log file `%s'\n", filename); - GNUNET_free (data); - } - if (GNUNET_SYSERR == GNUNET_DISK_file_close(f)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot close log file `%s'\n", filename); - GNUNET_free (filename); - return; - } - - write_throughput_gnuplot_script (filename, lp); - write_rtt_gnuplot_script (filename, lp); - write_bw_gnuplot_script (filename, lp); - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Data file successfully written to log file `%s'\n", filename); - GNUNET_free (filename); - } } void -collect_log_now (void) +collect_log_now(void) { struct LoggingPeer *bp; struct PeerLoggingTimestep *mlt; @@ -511,143 +508,143 @@ collect_log_now (void) return; for (c_m = 0; c_m < num_peers; c_m++) - { - bp = &lp[c_m]; - mlt = GNUNET_new (struct PeerLoggingTimestep); - GNUNET_CONTAINER_DLL_insert_tail(bp->head, bp->tail, mlt); - prev_log_mlt = mlt->prev; - - /* Collect data */ - - /* Current master state */ - mlt->timestamp = GNUNET_TIME_absolute_get(); - mlt->total_bytes_sent = bp->peer->total_bytes_sent; - mlt->total_messages_sent = bp->peer->total_messages_sent; - mlt->total_bytes_received = bp->peer->total_bytes_received; - mlt->total_messages_received = bp->peer->total_messages_received; - - /* Throughput */ - if (NULL == prev_log_mlt) - { - /* Get difference to start */ - delta = GNUNET_TIME_absolute_get_difference (lp[c_m].start, mlt->timestamp); - } - else - { - /* Get difference to last timestep */ - delta = GNUNET_TIME_absolute_get_difference (mlt->prev->timestamp, mlt->timestamp); - } - - /* Multiplication factor for throughput calculation */ - mult = (1.0 * 1000 * 1000) / (delta.rel_value_us); - - /* Total throughput */ - if (NULL != prev_log_mlt) - { - if (mlt->total_bytes_sent - mlt->prev->total_bytes_sent > 0) - mlt->total_throughput_send = mult * (mlt->total_bytes_sent - mlt->prev->total_bytes_sent); - else - mlt->total_throughput_send = prev_log_mlt->total_throughput_send; /* no msgs send */ - - if (mlt->total_bytes_received - mlt->prev->total_bytes_received > 0) - mlt->total_throughput_recv = mult * (mlt->total_bytes_received - mlt->prev->total_bytes_received); - else - mlt->total_throughput_recv = prev_log_mlt->total_throughput_recv; /* no msgs received */ - } - else - { - mlt->total_throughput_send = mult * mlt->total_bytes_sent; - mlt->total_throughput_send = mult * mlt->total_bytes_received; - } - - mlt->slaves_log = GNUNET_malloc (bp->peer->num_partners * - sizeof (struct PartnerLoggingTimestep)); - - for (c_s = 0; c_s < bp->peer->num_partners; c_s++) { - p = &bp->peer->partners[c_s]; - slt = &mlt->slaves_log[c_s]; - - slt->slave = p->dest; - /* Bytes sent from master to this slave */ - slt->total_bytes_sent = p->bytes_sent; - /* Messages sent from master to this slave */ - slt->total_messages_sent = p->messages_sent; - /* Bytes master received from this slave */ - slt->total_bytes_received = p->bytes_received; - /* Messages master received from this slave */ - slt->total_messages_received = p->messages_received; - slt->total_app_rtt = p->total_app_rtt; - /* ats performance information */ - slt->ats_cost_lan = p->ats_cost_lan; - slt->ats_cost_wan = p->ats_cost_wan; - slt->ats_cost_wlan = p->ats_cost_wlan; - slt->ats_delay = p->ats_delay; - slt->ats_distance = p->ats_distance; - slt->ats_network_type = p->ats_network_type; - slt->ats_utilization_down = p->ats_utilization_down; - slt->ats_utilization_up = p->ats_utilization_up; - slt->bandwidth_in = p->bandwidth_in; - slt->bandwidth_out = p->bandwidth_out; - - /* Total application level rtt */ + bp = &lp[c_m]; + mlt = GNUNET_new(struct PeerLoggingTimestep); + GNUNET_CONTAINER_DLL_insert_tail(bp->head, bp->tail, mlt); + prev_log_mlt = mlt->prev; + + /* Collect data */ + + /* Current master state */ + mlt->timestamp = GNUNET_TIME_absolute_get(); + mlt->total_bytes_sent = bp->peer->total_bytes_sent; + mlt->total_messages_sent = bp->peer->total_messages_sent; + mlt->total_bytes_received = bp->peer->total_bytes_received; + mlt->total_messages_received = bp->peer->total_messages_received; + + /* Throughput */ if (NULL == prev_log_mlt) - { - if (0 != slt->total_messages_sent) - app_rtt = slt->total_app_rtt / slt->total_messages_sent; - else - app_rtt = 0; - } + { + /* Get difference to start */ + delta = GNUNET_TIME_absolute_get_difference(lp[c_m].start, mlt->timestamp); + } else - { - prev_log_slt = &prev_log_mlt->slaves_log[c_s]; - if ((slt->total_messages_sent - prev_log_slt->total_messages_sent) > 0) - app_rtt = (slt->total_app_rtt - prev_log_slt->total_app_rtt) / - (slt->total_messages_sent - prev_log_slt->total_messages_sent); - else - app_rtt = prev_log_slt->app_rtt; /* No messages were */ - } - slt->app_rtt = app_rtt; - - /* Partner throughput */ + { + /* Get difference to last timestep */ + delta = GNUNET_TIME_absolute_get_difference(mlt->prev->timestamp, mlt->timestamp); + } + + /* Multiplication factor for throughput calculation */ + mult = (1.0 * 1000 * 1000) / (delta.rel_value_us); + + /* Total throughput */ if (NULL != prev_log_mlt) - { - prev_log_slt = &prev_log_mlt->slaves_log[c_s]; - if (slt->total_bytes_sent - prev_log_slt->total_bytes_sent > 0) - slt->throughput_sent = mult * (slt->total_bytes_sent - prev_log_slt->total_bytes_sent); - else - slt->throughput_sent = prev_log_slt->throughput_sent; /* no msgs send */ - - if (slt->total_bytes_received - prev_log_slt->total_bytes_received > 0) - slt->throughput_recv = mult * (slt->total_bytes_received - prev_log_slt->total_bytes_received); - else - slt->throughput_recv = prev_log_slt->throughput_recv; /* no msgs received */ - } + { + if (mlt->total_bytes_sent - mlt->prev->total_bytes_sent > 0) + mlt->total_throughput_send = mult * (mlt->total_bytes_sent - mlt->prev->total_bytes_sent); + else + mlt->total_throughput_send = prev_log_mlt->total_throughput_send; /* no msgs send */ + + if (mlt->total_bytes_received - mlt->prev->total_bytes_received > 0) + mlt->total_throughput_recv = mult * (mlt->total_bytes_received - mlt->prev->total_bytes_received); + else + mlt->total_throughput_recv = prev_log_mlt->total_throughput_recv; /* no msgs received */ + } else - { - slt->throughput_sent = mult * slt->total_bytes_sent; - slt->throughput_sent = mult * slt->total_bytes_received; - } - - GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Master [%u]: slave [%u]\n", - bp->peer->no, p->dest->no); + { + mlt->total_throughput_send = mult * mlt->total_bytes_sent; + mlt->total_throughput_send = mult * mlt->total_bytes_received; + } + + mlt->slaves_log = GNUNET_malloc(bp->peer->num_partners * + sizeof(struct PartnerLoggingTimestep)); + + for (c_s = 0; c_s < bp->peer->num_partners; c_s++) + { + p = &bp->peer->partners[c_s]; + slt = &mlt->slaves_log[c_s]; + + slt->slave = p->dest; + /* Bytes sent from master to this slave */ + slt->total_bytes_sent = p->bytes_sent; + /* Messages sent from master to this slave */ + slt->total_messages_sent = p->messages_sent; + /* Bytes master received from this slave */ + slt->total_bytes_received = p->bytes_received; + /* Messages master received from this slave */ + slt->total_messages_received = p->messages_received; + slt->total_app_rtt = p->total_app_rtt; + /* ats performance information */ + slt->ats_cost_lan = p->ats_cost_lan; + slt->ats_cost_wan = p->ats_cost_wan; + slt->ats_cost_wlan = p->ats_cost_wlan; + slt->ats_delay = p->ats_delay; + slt->ats_distance = p->ats_distance; + slt->ats_network_type = p->ats_network_type; + slt->ats_utilization_down = p->ats_utilization_down; + slt->ats_utilization_up = p->ats_utilization_up; + slt->bandwidth_in = p->bandwidth_in; + slt->bandwidth_out = p->bandwidth_out; + + /* Total application level rtt */ + if (NULL == prev_log_mlt) + { + if (0 != slt->total_messages_sent) + app_rtt = slt->total_app_rtt / slt->total_messages_sent; + else + app_rtt = 0; + } + else + { + prev_log_slt = &prev_log_mlt->slaves_log[c_s]; + if ((slt->total_messages_sent - prev_log_slt->total_messages_sent) > 0) + app_rtt = (slt->total_app_rtt - prev_log_slt->total_app_rtt) / + (slt->total_messages_sent - prev_log_slt->total_messages_sent); + else + app_rtt = prev_log_slt->app_rtt; /* No messages were */ + } + slt->app_rtt = app_rtt; + + /* Partner throughput */ + if (NULL != prev_log_mlt) + { + prev_log_slt = &prev_log_mlt->slaves_log[c_s]; + if (slt->total_bytes_sent - prev_log_slt->total_bytes_sent > 0) + slt->throughput_sent = mult * (slt->total_bytes_sent - prev_log_slt->total_bytes_sent); + else + slt->throughput_sent = prev_log_slt->throughput_sent; /* no msgs send */ + + if (slt->total_bytes_received - prev_log_slt->total_bytes_received > 0) + slt->throughput_recv = mult * (slt->total_bytes_received - prev_log_slt->total_bytes_received); + else + slt->throughput_recv = prev_log_slt->throughput_recv; /* no msgs received */ + } + else + { + slt->throughput_sent = mult * slt->total_bytes_sent; + slt->throughput_sent = mult * slt->total_bytes_received; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Master [%u]: slave [%u]\n", + bp->peer->no, p->dest->no); + } } - } } static void -collect_log_task (void *cls) +collect_log_task(void *cls) { log_task = NULL; - collect_log_now (); - log_task = GNUNET_SCHEDULER_add_delayed (frequency, - &collect_log_task, NULL); + collect_log_now(); + log_task = GNUNET_SCHEDULER_add_delayed(frequency, + &collect_log_task, NULL); } void -perf_logging_stop () +perf_logging_stop() { int c_m; struct PeerLoggingTimestep *cur; @@ -656,53 +653,54 @@ perf_logging_stop () return; if (NULL != log_task) - { - GNUNET_SCHEDULER_cancel (log_task); - log_task = NULL; - } - collect_log_task (NULL); + { + GNUNET_SCHEDULER_cancel(log_task); + log_task = NULL; + } + collect_log_task(NULL); GNUNET_log(GNUNET_ERROR_TYPE_INFO, - _("Stop logging\n")); + _("Stop logging\n")); - write_to_file (); + write_to_file(); for (c_m = 0; c_m < num_peers; c_m++) - { - while (NULL != (cur = lp[c_m].head)) { - GNUNET_CONTAINER_DLL_remove (lp[c_m].head, lp[c_m].tail, cur); - GNUNET_free (cur->slaves_log); - GNUNET_free (cur); + while (NULL != (cur = lp[c_m].head)) + { + GNUNET_CONTAINER_DLL_remove(lp[c_m].head, lp[c_m].tail, cur); + GNUNET_free(cur->slaves_log); + GNUNET_free(cur); + } } - } - GNUNET_free (lp); + GNUNET_free(lp); } void -perf_logging_start (struct GNUNET_TIME_Relative log_frequency, - char * testname, struct BenchmarkPeer *masters, int num_masters) +perf_logging_start(struct GNUNET_TIME_Relative log_frequency, + char * testname, struct BenchmarkPeer *masters, int num_masters) { int c_m; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, - _("Start logging `%s'\n"), testname); + _("Start logging `%s'\n"), testname); num_peers = num_masters; name = testname; frequency = log_frequency; - lp = GNUNET_malloc (num_masters * sizeof (struct LoggingPeer)); + lp = GNUNET_malloc(num_masters * sizeof(struct LoggingPeer)); - for (c_m = 0; c_m < num_masters; c_m ++) - { - lp[c_m].peer = &masters[c_m]; - lp[c_m].start = GNUNET_TIME_absolute_get(); - } + for (c_m = 0; c_m < num_masters; c_m++) + { + lp[c_m].peer = &masters[c_m]; + lp[c_m].start = GNUNET_TIME_absolute_get(); + } /* Schedule logging task */ - log_task = GNUNET_SCHEDULER_add_now (&collect_log_task, NULL); + log_task = GNUNET_SCHEDULER_add_now(&collect_log_task, NULL); running = GNUNET_YES; } /* end of file perf_ats_logging.c */ diff --git a/src/ats-tool/gnunet-ats.c b/src/ats-tool/gnunet-ats.c index 519f77af8..1628610cc 100644 --- a/src/ats-tool/gnunet-ats.c +++ b/src/ats-tool/gnunet-ats.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2009--2015 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2009--2015 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -81,7 +81,7 @@ static char *opt_pid_str; static char *opt_type_str; /** - * CLI Option: preference value to set + * CLI Option: preference value to set */ static unsigned int opt_pref_value; @@ -151,8 +151,7 @@ static struct GNUNET_CONTAINER_MultiPeerMap *addresses; * We keep address information in here while we talk to transport * to map the address to a string. */ -struct PendingResolutions -{ +struct PendingResolutions { /** * Kept in a DLL. */ @@ -200,8 +199,7 @@ struct PendingResolutions * Information we keep for an address. Used to avoid * printing the same data multiple times. */ -struct ATSAddress -{ +struct ATSAddress { /** * Address information. */ @@ -244,14 +242,14 @@ static struct PendingResolutions *tail; * @return #GNUNET_YES (always) */ static int -free_addr_it (void *cls, const struct GNUNET_PeerIdentity *key, void *value) +free_addr_it(void *cls, const struct GNUNET_PeerIdentity *key, void *value) { struct ATSAddress *a = value; - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_remove (addresses, key, value)); - GNUNET_HELLO_address_free (a->address); - GNUNET_free (a); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_remove(addresses, key, value)); + GNUNET_HELLO_address_free(a->address); + GNUNET_free(a); return GNUNET_OK; } @@ -262,56 +260,56 @@ free_addr_it (void *cls, const struct GNUNET_PeerIdentity *key, void *value) * @param cls NULL */ static void -end (void *cls) +end(void *cls) { struct PendingResolutions *pr; struct PendingResolutions *next; unsigned int pending; if (NULL != alh) - { - GNUNET_ATS_performance_list_addresses_cancel (alh); - alh = NULL; - } + { + GNUNET_ATS_performance_list_addresses_cancel(alh); + alh = NULL; + } if (NULL != ph) - { - GNUNET_ATS_performance_done (ph); - ph = NULL; - } + { + GNUNET_ATS_performance_done(ph); + ph = NULL; + } pending = 0; next = head; while (NULL != (pr = next)) - { - next = pr->next; - GNUNET_CONTAINER_DLL_remove (head, tail, pr); - GNUNET_TRANSPORT_address_to_string_cancel (pr->tats_ctx); - GNUNET_free (pr->address); - GNUNET_free (pr); - pending++; - } - GNUNET_CONTAINER_multipeermap_iterate (addresses, &free_addr_it, NULL); - GNUNET_CONTAINER_multipeermap_destroy (addresses); + { + next = pr->next; + GNUNET_CONTAINER_DLL_remove(head, tail, pr); + GNUNET_TRANSPORT_address_to_string_cancel(pr->tats_ctx); + GNUNET_free(pr->address); + GNUNET_free(pr); + pending++; + } + GNUNET_CONTAINER_multipeermap_iterate(addresses, &free_addr_it, NULL); + GNUNET_CONTAINER_multipeermap_destroy(addresses); addresses = NULL; if (0 < pending) - fprintf (stdout, _ ("%u address resolutions had a timeout\n"), pending); + fprintf(stdout, _("%u address resolutions had a timeout\n"), pending); if (opt_list_used || opt_list_all) - fprintf (stdout, - _ ("ATS returned stat_results for %u addresses\n"), - stat_results); + fprintf(stdout, + _("ATS returned stat_results for %u addresses\n"), + stat_results); if (NULL != ats_sh) - { - GNUNET_ATS_connectivity_suggest_cancel (ats_sh); - ats_sh = NULL; - } + { + GNUNET_ATS_connectivity_suggest_cancel(ats_sh); + ats_sh = NULL; + } if (NULL != ats_ch) - { - GNUNET_ATS_connectivity_done (ats_ch); - ats_ch = NULL; - } + { + GNUNET_ATS_connectivity_done(ats_ch); + ats_ch = NULL; + } ret = 0; } @@ -333,72 +331,74 @@ end (void *cls) * if #GNUNET_SYSERR: communication error (IPC error) */ static void -transport_addr_to_str_cb (void *cls, const char *address, int res) +transport_addr_to_str_cb(void *cls, const char *address, int res) { struct PendingResolutions *pr = cls; if (NULL == address) - { - /* We're done */ - GNUNET_CONTAINER_DLL_remove (head, tail, pr); - GNUNET_free (pr->address); - GNUNET_free (pr); - stat_pending--; - - if ((GNUNET_YES == stat_receive_done) && (0 == stat_pending)) { - /* All messages received and no resolutions pending*/ - if (shutdown_task != NULL) - GNUNET_SCHEDULER_cancel (shutdown_task); - shutdown_task = GNUNET_SCHEDULER_add_now (&end, NULL); + /* We're done */ + GNUNET_CONTAINER_DLL_remove(head, tail, pr); + GNUNET_free(pr->address); + GNUNET_free(pr); + stat_pending--; + + if ((GNUNET_YES == stat_receive_done) && (0 == stat_pending)) + { + /* All messages received and no resolutions pending*/ + if (shutdown_task != NULL) + GNUNET_SCHEDULER_cancel(shutdown_task); + shutdown_task = GNUNET_SCHEDULER_add_now(&end, NULL); + } + return; } - return; - } switch (res) - { - case GNUNET_SYSERR: - fprintf ( - stderr, - "Failed to convert address for peer `%s' plugin `%s' length %u to string (communication error)\n", - GNUNET_i2s (&pr->address->peer), - pr->address->transport_name, - (unsigned int) pr->address->address_length); - return; - case GNUNET_NO: - fprintf ( - stderr, - "Failed to convert address for peer `%s' plugin `%s' length %u to string (address invalid or not supported)\n", - GNUNET_i2s (&pr->address->peer), - pr->address->transport_name, - (unsigned int) pr->address->address_length); - return; - case GNUNET_OK: - /* continues below */ - break; - default: - GNUNET_break (0); - return; - } - - fprintf ( + { + case GNUNET_SYSERR: + fprintf( + stderr, + "Failed to convert address for peer `%s' plugin `%s' length %u to string (communication error)\n", + GNUNET_i2s(&pr->address->peer), + pr->address->transport_name, + (unsigned int)pr->address->address_length); + return; + + case GNUNET_NO: + fprintf( + stderr, + "Failed to convert address for peer `%s' plugin `%s' length %u to string (address invalid or not supported)\n", + GNUNET_i2s(&pr->address->peer), + pr->address->transport_name, + (unsigned int)pr->address->address_length); + return; + + case GNUNET_OK: + /* continues below */ + break; + + default: + GNUNET_break(0); + return; + } + + fprintf( stdout, - _ ( + _( "Peer `%s' plugin `%s', address `%s', `%s' bw out: %u Bytes/s, bw in %u Bytes/s, %s\n"), - GNUNET_i2s (&pr->address->peer), + GNUNET_i2s(&pr->address->peer), pr->address->transport_name, address, - GNUNET_NT_to_string (pr->properties.scope), - ntohl (pr->bandwidth_out.value__), - ntohl (pr->bandwidth_in.value__), - pr->active ? _ ("active ") : _ ("inactive ")); + GNUNET_NT_to_string(pr->properties.scope), + ntohl(pr->bandwidth_out.value__), + ntohl(pr->bandwidth_in.value__), + pr->active ? _("active ") : _("inactive ")); } /** * Closure for #find_address_it(). */ -struct AddressFindCtx -{ +struct AddressFindCtx { /** * Address we are looking for. */ @@ -420,16 +420,16 @@ struct AddressFindCtx * @return #GNUNET_NO if we found a match, #GNUNET_YES if not */ static int -find_address_it (void *cls, const struct GNUNET_PeerIdentity *key, void *value) +find_address_it(void *cls, const struct GNUNET_PeerIdentity *key, void *value) { struct AddressFindCtx *actx = cls; struct ATSAddress *exist = value; - if (0 == GNUNET_HELLO_address_cmp (actx->src, exist->address)) - { - actx->res = exist; - return GNUNET_NO; - } + if (0 == GNUNET_HELLO_address_cmp(actx->src, exist->address)) + { + actx->res = exist; + return GNUNET_NO; + } return GNUNET_YES; } @@ -448,115 +448,115 @@ find_address_it (void *cls, const struct GNUNET_PeerIdentity *key, void *value) * @param prop performance data for the address (as far as known) */ static void -ats_perf_mon_cb (void *cls, - const struct GNUNET_HELLO_Address *address, - int active, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, - const struct GNUNET_ATS_Properties *prop) +ats_perf_mon_cb(void *cls, + const struct GNUNET_HELLO_Address *address, + int active, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, + const struct GNUNET_ATS_Properties *prop) { struct PendingResolutions *pr; struct PendingResolutions *cur; struct PendingResolutions *next; if (NULL == address) - { - /* ATS service temporarily disconnected, remove current state */ - next = head; - for (cur = next; NULL != cur; cur = next) { - next = cur->next; - GNUNET_CONTAINER_DLL_remove (head, tail, cur); - GNUNET_TRANSPORT_address_to_string_cancel (cur->tats_ctx); - GNUNET_HELLO_address_free (cur->address); - GNUNET_free (cur); + /* ATS service temporarily disconnected, remove current state */ + next = head; + for (cur = next; NULL != cur; cur = next) + { + next = cur->next; + GNUNET_CONTAINER_DLL_remove(head, tail, cur); + GNUNET_TRANSPORT_address_to_string_cancel(cur->tats_ctx); + GNUNET_HELLO_address_free(cur->address); + GNUNET_free(cur); + } + GNUNET_CONTAINER_multipeermap_iterate(addresses, &free_addr_it, NULL); + return; } - GNUNET_CONTAINER_multipeermap_iterate (addresses, &free_addr_it, NULL); - return; - } if (GNUNET_SYSERR == active) - { - /* remove address */ - struct AddressFindCtx actx; - - actx.src = address; - actx.res = NULL; - GNUNET_CONTAINER_multipeermap_get_multiple (addresses, - &address->peer, - &find_address_it, - &actx); - if (NULL == actx.res) { - GNUNET_break (0); - return; - } - GNUNET_break (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_remove (addresses, + /* remove address */ + struct AddressFindCtx actx; + + actx.src = address; + actx.res = NULL; + GNUNET_CONTAINER_multipeermap_get_multiple(addresses, + &address->peer, + &find_address_it, + &actx); + if (NULL == actx.res) + { + GNUNET_break(0); + return; + } + GNUNET_break(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_remove(addresses, &address->peer, actx.res)); - fprintf (stdout, - _ ("Removed address of peer `%s' with plugin `%s'\n"), - GNUNET_i2s (&address->peer), - actx.res->address->transport_name); - GNUNET_HELLO_address_free (actx.res); - return; - } + fprintf(stdout, + _("Removed address of peer `%s' with plugin `%s'\n"), + GNUNET_i2s(&address->peer), + actx.res->address->transport_name); + GNUNET_HELLO_address_free(actx.res); + return; + } if (GNUNET_NO == opt_verbose) - { - struct AddressFindCtx actx; - struct ATSAddress *a; - - actx.src = address; - actx.res = NULL; - GNUNET_CONTAINER_multipeermap_get_multiple (addresses, - &address->peer, - &find_address_it, - &actx); - if ((NULL != actx.res)) { - if ((bandwidth_in.value__ == actx.res->bandwidth_in.value__) && - (bandwidth_out.value__ == actx.res->bandwidth_out.value__) && - (active == actx.res->active)) - { - return; /* Nothing to do here */ - } + struct AddressFindCtx actx; + struct ATSAddress *a; + + actx.src = address; + actx.res = NULL; + GNUNET_CONTAINER_multipeermap_get_multiple(addresses, + &address->peer, + &find_address_it, + &actx); + if ((NULL != actx.res)) + { + if ((bandwidth_in.value__ == actx.res->bandwidth_in.value__) && + (bandwidth_out.value__ == actx.res->bandwidth_out.value__) && + (active == actx.res->active)) + { + return; /* Nothing to do here */ + } + else + { + actx.res->bandwidth_in = bandwidth_in; + actx.res->bandwidth_out = bandwidth_out; + } + } else - { - actx.res->bandwidth_in = bandwidth_in; - actx.res->bandwidth_out = bandwidth_out; - } - } - else - { - a = GNUNET_new (struct ATSAddress); - - a->address = GNUNET_HELLO_address_copy (address); - a->bandwidth_in = bandwidth_in; - a->bandwidth_out = bandwidth_out; - a->active = active; - GNUNET_CONTAINER_multipeermap_put ( - addresses, - &address->peer, - a, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + { + a = GNUNET_new(struct ATSAddress); + + a->address = GNUNET_HELLO_address_copy(address); + a->bandwidth_in = bandwidth_in; + a->bandwidth_out = bandwidth_out; + a->active = active; + GNUNET_CONTAINER_multipeermap_put( + addresses, + &address->peer, + a, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + } } - } - pr = GNUNET_new (struct PendingResolutions); + pr = GNUNET_new(struct PendingResolutions); pr->properties = *prop; - pr->address = GNUNET_HELLO_address_copy (address); + pr->address = GNUNET_HELLO_address_copy(address); pr->bandwidth_in = bandwidth_in; pr->bandwidth_out = bandwidth_out; pr->active = active; - pr->tats_ctx = GNUNET_TRANSPORT_address_to_string ( + pr->tats_ctx = GNUNET_TRANSPORT_address_to_string( cfg, address, opt_resolve_addresses_numeric, - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10), + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10), &transport_addr_to_str_cb, pr); - GNUNET_CONTAINER_DLL_insert (head, tail, pr); + GNUNET_CONTAINER_DLL_insert(head, tail, pr); stat_results++; stat_pending++; } @@ -574,44 +574,44 @@ ats_perf_mon_cb (void *cls, * @param prop performance data for the address (as far as known) */ static void -ats_perf_cb (void *cls, - const struct GNUNET_HELLO_Address *address, - int active, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, - const struct GNUNET_ATS_Properties *prop) +ats_perf_cb(void *cls, + const struct GNUNET_HELLO_Address *address, + int active, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, + const struct GNUNET_ATS_Properties *prop) { struct PendingResolutions *pr; if (NULL == address) - { - /* All messages received */ - stat_receive_done = GNUNET_YES; - alh = NULL; - if (0 == stat_pending) { - /* All messages received and no resolutions pending*/ - if (shutdown_task != NULL) - GNUNET_SCHEDULER_cancel (shutdown_task); - shutdown_task = GNUNET_SCHEDULER_add_now (&end, NULL); + /* All messages received */ + stat_receive_done = GNUNET_YES; + alh = NULL; + if (0 == stat_pending) + { + /* All messages received and no resolutions pending*/ + if (shutdown_task != NULL) + GNUNET_SCHEDULER_cancel(shutdown_task); + shutdown_task = GNUNET_SCHEDULER_add_now(&end, NULL); + } + return; } - return; - } - pr = GNUNET_new (struct PendingResolutions); + pr = GNUNET_new(struct PendingResolutions); pr->properties = *prop; - pr->address = GNUNET_HELLO_address_copy (address); + pr->address = GNUNET_HELLO_address_copy(address); pr->bandwidth_in = bandwidth_in; pr->bandwidth_out = bandwidth_out; pr->active = active; - pr->tats_ctx = GNUNET_TRANSPORT_address_to_string ( + pr->tats_ctx = GNUNET_TRANSPORT_address_to_string( cfg, address, opt_resolve_addresses_numeric, - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10), + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10), &transport_addr_to_str_cb, pr); - GNUNET_CONTAINER_DLL_insert (head, tail, pr); + GNUNET_CONTAINER_DLL_insert(head, tail, pr); stat_results++; stat_pending++; } @@ -625,7 +625,7 @@ ats_perf_cb (void *cls, * @return total number of ATS network types known */ static unsigned int -print_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg) +print_quotas(const struct GNUNET_CONFIGURATION_Handle *cfg) { char *entry_in = NULL; char *entry_out = NULL; @@ -636,64 +636,63 @@ print_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg) int c; for (c = 0; (c < GNUNET_NT_COUNT); c++) - { - - GNUNET_asprintf (&entry_out, "%s_QUOTA_OUT", GNUNET_NT_to_string (c)); - GNUNET_asprintf (&entry_in, "%s_QUOTA_IN", GNUNET_NT_to_string (c)); - - /* quota out */ - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, - "ats", - entry_out, - "a_out_str)) - { - if (0 == strcmp (quota_out_str, UNLIMITED_STRING) || - (GNUNET_SYSERR == - GNUNET_STRINGS_fancy_size_to_bytes (quota_out_str, "a_out))) - quota_out = UINT32_MAX; - - GNUNET_free (quota_out_str); - GNUNET_asprintf ("a_out_str, "%llu", quota_out); - } - else - { - fprintf (stderr, - "Outbound quota for network `%11s' not configured!\n", - GNUNET_NT_to_string (c)); - GNUNET_asprintf ("a_out_str, "-"); - } - GNUNET_free (entry_out); - - /* quota in */ - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, - "ats", - entry_in, - "a_in_str)) - { - if (0 == strcmp (quota_in_str, UNLIMITED_STRING) || - (GNUNET_SYSERR == - GNUNET_STRINGS_fancy_size_to_bytes (quota_in_str, "a_in))) - quota_in = UINT32_MAX; - GNUNET_free (quota_in_str); - GNUNET_asprintf ("a_in_str, "%llu", quota_in); - } - else { - fprintf (stderr, - "Inbound quota for network `%11s' not configured!\n", - GNUNET_NT_to_string (c)); - GNUNET_asprintf ("a_in_str, "-"); + GNUNET_asprintf(&entry_out, "%s_QUOTA_OUT", GNUNET_NT_to_string(c)); + GNUNET_asprintf(&entry_in, "%s_QUOTA_IN", GNUNET_NT_to_string(c)); + + /* quota out */ + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, + "ats", + entry_out, + "a_out_str)) + { + if (0 == strcmp(quota_out_str, UNLIMITED_STRING) || + (GNUNET_SYSERR == + GNUNET_STRINGS_fancy_size_to_bytes(quota_out_str, "a_out))) + quota_out = UINT32_MAX; + + GNUNET_free(quota_out_str); + GNUNET_asprintf("a_out_str, "%llu", quota_out); + } + else + { + fprintf(stderr, + "Outbound quota for network `%11s' not configured!\n", + GNUNET_NT_to_string(c)); + GNUNET_asprintf("a_out_str, "-"); + } + GNUNET_free(entry_out); + + /* quota in */ + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, + "ats", + entry_in, + "a_in_str)) + { + if (0 == strcmp(quota_in_str, UNLIMITED_STRING) || + (GNUNET_SYSERR == + GNUNET_STRINGS_fancy_size_to_bytes(quota_in_str, "a_in))) + quota_in = UINT32_MAX; + GNUNET_free(quota_in_str); + GNUNET_asprintf("a_in_str, "%llu", quota_in); + } + else + { + fprintf(stderr, + "Inbound quota for network `%11s' not configured!\n", + GNUNET_NT_to_string(c)); + GNUNET_asprintf("a_in_str, "-"); + } + GNUNET_free(entry_in); + + fprintf(stdout, + _("Quota for network `%11s' (in/out): %10s / %10s\n"), + GNUNET_NT_to_string(c), + quota_in_str, + quota_out_str); + GNUNET_free(quota_out_str); + GNUNET_free(quota_in_str); } - GNUNET_free (entry_in); - - fprintf (stdout, - _ ("Quota for network `%11s' (in/out): %10s / %10s\n"), - GNUNET_NT_to_string (c), - quota_in_str, - quota_out_str); - GNUNET_free (quota_out_str); - GNUNET_free (quota_in_str); - } return GNUNET_NT_COUNT; } @@ -707,176 +706,176 @@ print_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg) * @param my_cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *my_cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *my_cfg) { struct GNUNET_PeerIdentity pid; struct GNUNET_PeerIdentity cpid; unsigned int c; unsigned int type; - cfg = (struct GNUNET_CONFIGURATION_Handle *) my_cfg; - addresses = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO); + cfg = (struct GNUNET_CONFIGURATION_Handle *)my_cfg; + addresses = GNUNET_CONTAINER_multipeermap_create(10, GNUNET_NO); stat_results = 0; c = 0; if (NULL != opt_pid_str) - { - if (GNUNET_OK != - GNUNET_CRYPTO_eddsa_public_key_from_string (opt_pid_str, - strlen (opt_pid_str), - &pid.public_key)) { - fprintf (stderr, _ ("Failed to parse peer identity `%s'\n"), opt_pid_str); - return; + if (GNUNET_OK != + GNUNET_CRYPTO_eddsa_public_key_from_string(opt_pid_str, + strlen(opt_pid_str), + &pid.public_key)) + { + fprintf(stderr, _("Failed to parse peer identity `%s'\n"), opt_pid_str); + return; + } } - } if (NULL != cpid_str) - { - if (GNUNET_OK != - GNUNET_CRYPTO_eddsa_public_key_from_string (cpid_str, - strlen (cpid_str), - &cpid.public_key)) { - fprintf (stderr, _ ("Failed to parse peer identity `%s'\n"), cpid_str); - return; + if (GNUNET_OK != + GNUNET_CRYPTO_eddsa_public_key_from_string(cpid_str, + strlen(cpid_str), + &cpid.public_key)) + { + fprintf(stderr, _("Failed to parse peer identity `%s'\n"), cpid_str); + return; + } + c++; } - c++; - } c += opt_list_all + opt_list_used + opt_monitor + opt_set_pref; if (1 < c) - { - fprintf (stderr, - _ ("Please select one operation: %s or %s or %s or %s or %s\n"), - "--used", - "--all", - "--monitor", - "--preference", - "--quotas"); - return; - } + { + fprintf(stderr, + _("Please select one operation: %s or %s or %s or %s or %s\n"), + "--used", + "--all", + "--monitor", + "--preference", + "--quotas"); + return; + } if (0 == c) opt_list_used = GNUNET_YES; /* set default */ if (opt_print_quotas) - { - ret = print_quotas (cfg); - return; - } - if (opt_list_all) - { - ph = GNUNET_ATS_performance_init (cfg, NULL, NULL); - if (NULL == ph) { - fprintf (stderr, "%s", _ ("Cannot connect to ATS service, exiting...\n")); + ret = print_quotas(cfg); return; } - alh = GNUNET_ATS_performance_list_addresses (ph, - (NULL == opt_pid_str) ? NULL - : &pid, - GNUNET_YES, - &ats_perf_cb, - NULL); - if (NULL == alh) + if (opt_list_all) { - fprintf (stderr, - "%s", - _ ("Cannot issue request to ATS service, exiting...\n")); - shutdown_task = GNUNET_SCHEDULER_add_now (&end, NULL); + ph = GNUNET_ATS_performance_init(cfg, NULL, NULL); + if (NULL == ph) + { + fprintf(stderr, "%s", _("Cannot connect to ATS service, exiting...\n")); + return; + } + alh = GNUNET_ATS_performance_list_addresses(ph, + (NULL == opt_pid_str) ? NULL + : &pid, + GNUNET_YES, + &ats_perf_cb, + NULL); + if (NULL == alh) + { + fprintf(stderr, + "%s", + _("Cannot issue request to ATS service, exiting...\n")); + shutdown_task = GNUNET_SCHEDULER_add_now(&end, NULL); + return; + } + shutdown_task = GNUNET_SCHEDULER_add_shutdown(&end, NULL); return; } - shutdown_task = GNUNET_SCHEDULER_add_shutdown (&end, NULL); - return; - } if (opt_list_used) - { - ph = GNUNET_ATS_performance_init (cfg, NULL, NULL); - if (NULL == ph) - fprintf (stderr, "%s", _ ("Cannot connect to ATS service, exiting...\n")); - - alh = GNUNET_ATS_performance_list_addresses (ph, - (NULL == opt_pid_str) ? NULL - : &pid, - GNUNET_NO, - &ats_perf_cb, - NULL); - if (NULL == alh) { - fprintf (stderr, - "%s", - _ ("Cannot issue request to ATS service, exiting...\n")); - shutdown_task = GNUNET_SCHEDULER_add_now (&end, NULL); + ph = GNUNET_ATS_performance_init(cfg, NULL, NULL); + if (NULL == ph) + fprintf(stderr, "%s", _("Cannot connect to ATS service, exiting...\n")); + + alh = GNUNET_ATS_performance_list_addresses(ph, + (NULL == opt_pid_str) ? NULL + : &pid, + GNUNET_NO, + &ats_perf_cb, + NULL); + if (NULL == alh) + { + fprintf(stderr, + "%s", + _("Cannot issue request to ATS service, exiting...\n")); + shutdown_task = GNUNET_SCHEDULER_add_now(&end, NULL); + return; + } + shutdown_task = GNUNET_SCHEDULER_add_shutdown(&end, NULL); return; } - shutdown_task = GNUNET_SCHEDULER_add_shutdown (&end, NULL); - return; - } if (opt_monitor) - { - ph = GNUNET_ATS_performance_init (cfg, &ats_perf_mon_cb, NULL); - shutdown_task = GNUNET_SCHEDULER_add_shutdown (&end, NULL); - if (NULL == ph) { - fprintf (stderr, "%s", _ ("Cannot connect to ATS service, exiting...\n")); - GNUNET_SCHEDULER_shutdown (); - } - return; - } - if (opt_set_pref) - { - if (NULL == opt_type_str) - { - fprintf (stderr, "%s", _ ("No preference type given!\n")); + ph = GNUNET_ATS_performance_init(cfg, &ats_perf_mon_cb, NULL); + shutdown_task = GNUNET_SCHEDULER_add_shutdown(&end, NULL); + if (NULL == ph) + { + fprintf(stderr, "%s", _("Cannot connect to ATS service, exiting...\n")); + GNUNET_SCHEDULER_shutdown(); + } return; } - if (NULL == opt_pid_str) + if (opt_set_pref) { - fprintf (stderr, "%s", _ ("No peer given!\n")); + if (NULL == opt_type_str) + { + fprintf(stderr, "%s", _("No preference type given!\n")); + return; + } + if (NULL == opt_pid_str) + { + fprintf(stderr, "%s", _("No peer given!\n")); + return; + } + + for (c = 0; c < strlen(opt_type_str); c++) + { + if (isupper((unsigned char)opt_type_str[c])) + opt_type_str[c] = tolower((unsigned char)opt_type_str[c]); + } + + if (0 == strcasecmp("latency", opt_type_str)) + type = GNUNET_ATS_PREFERENCE_LATENCY; + else if (0 == strcasecmp("bandwidth", opt_type_str)) + type = GNUNET_ATS_PREFERENCE_BANDWIDTH; + else + { + fprintf(stderr, "%s", _("Valid type required\n")); + return; + } + + /* set */ + ph = GNUNET_ATS_performance_init(cfg, NULL, NULL); + if (NULL == ph) + fprintf(stderr, "%s", _("Cannot connect to ATS service, exiting...\n")); + + GNUNET_ATS_performance_change_preference(ph, + &pid, + type, + (double)opt_pref_value, + GNUNET_ATS_PREFERENCE_END); + + shutdown_task = + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, &end, NULL); return; } - - for (c = 0; c < strlen (opt_type_str); c++) - { - if (isupper ((unsigned char) opt_type_str[c])) - opt_type_str[c] = tolower ((unsigned char) opt_type_str[c]); - } - - if (0 == strcasecmp ("latency", opt_type_str)) - type = GNUNET_ATS_PREFERENCE_LATENCY; - else if (0 == strcasecmp ("bandwidth", opt_type_str)) - type = GNUNET_ATS_PREFERENCE_BANDWIDTH; - else + if (NULL != cpid_str) { - fprintf (stderr, "%s", _ ("Valid type required\n")); + ats_ch = GNUNET_ATS_connectivity_init(cfg); + ats_sh = GNUNET_ATS_connectivity_suggest(ats_ch, &cpid, 1000); + shutdown_task = + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, &end, NULL); return; } - - /* set */ - ph = GNUNET_ATS_performance_init (cfg, NULL, NULL); - if (NULL == ph) - fprintf (stderr, "%s", _ ("Cannot connect to ATS service, exiting...\n")); - - GNUNET_ATS_performance_change_preference (ph, - &pid, - type, - (double) opt_pref_value, - GNUNET_ATS_PREFERENCE_END); - - shutdown_task = - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &end, NULL); - return; - } - if (NULL != cpid_str) - { - ats_ch = GNUNET_ATS_connectivity_init (cfg); - ats_sh = GNUNET_ATS_connectivity_suggest (ats_ch, &cpid, 1000); - shutdown_task = - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &end, NULL); - return; - } ret = 1; } @@ -889,7 +888,7 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { int res; @@ -903,82 +902,82 @@ main (int argc, char *const *argv) opt_type_str = NULL; struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_flag ('u', - "used", - gettext_noop ( - "get list of active addresses currently used"), - &opt_list_used), - GNUNET_GETOPT_option_flag ('a', - "all", - gettext_noop ( - "get list of all active addresses"), - &opt_list_all), - - GNUNET_GETOPT_option_string ('C', - "connect", - NULL, - gettext_noop ("connect to PEER"), - &cpid_str), - GNUNET_GETOPT_option_flag ('n', - "numeric", - gettext_noop ( - "do not resolve IP addresses to hostnames"), - &opt_resolve_addresses_numeric), - - GNUNET_GETOPT_option_flag ('m', - "monitor", - gettext_noop ("monitor mode"), - &opt_monitor), - - GNUNET_GETOPT_option_flag ('p', - "preference", - gettext_noop ( - "set preference for the given peer"), - &opt_set_pref), - - GNUNET_GETOPT_option_flag ('q', - "quotas", - gettext_noop ("print all configured quotas"), - &opt_print_quotas), - GNUNET_GETOPT_option_string ('i', - "id", - "TYPE", - gettext_noop ("peer id"), - &opt_pid_str), - - GNUNET_GETOPT_option_string ('t', - "type", - "TYPE", - gettext_noop ( - "preference type to set: latency | bandwidth"), - &opt_type_str), - - GNUNET_GETOPT_option_uint ('k', - "value", - "VALUE", - gettext_noop ("preference value"), - &opt_pref_value), - - GNUNET_GETOPT_option_flag ( - 'V', - "verbose", - gettext_noop ("verbose output (include ATS address properties)"), - &opt_verbose), - GNUNET_GETOPT_OPTION_END}; - - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + { GNUNET_GETOPT_option_flag('u', + "used", + gettext_noop( + "get list of active addresses currently used"), + &opt_list_used), + GNUNET_GETOPT_option_flag('a', + "all", + gettext_noop( + "get list of all active addresses"), + &opt_list_all), + + GNUNET_GETOPT_option_string('C', + "connect", + NULL, + gettext_noop("connect to PEER"), + &cpid_str), + GNUNET_GETOPT_option_flag('n', + "numeric", + gettext_noop( + "do not resolve IP addresses to hostnames"), + &opt_resolve_addresses_numeric), + + GNUNET_GETOPT_option_flag('m', + "monitor", + gettext_noop("monitor mode"), + &opt_monitor), + + GNUNET_GETOPT_option_flag('p', + "preference", + gettext_noop( + "set preference for the given peer"), + &opt_set_pref), + + GNUNET_GETOPT_option_flag('q', + "quotas", + gettext_noop("print all configured quotas"), + &opt_print_quotas), + GNUNET_GETOPT_option_string('i', + "id", + "TYPE", + gettext_noop("peer id"), + &opt_pid_str), + + GNUNET_GETOPT_option_string('t', + "type", + "TYPE", + gettext_noop( + "preference type to set: latency | bandwidth"), + &opt_type_str), + + GNUNET_GETOPT_option_uint('k', + "value", + "VALUE", + gettext_noop("preference value"), + &opt_pref_value), + + GNUNET_GETOPT_option_flag( + 'V', + "verbose", + gettext_noop("verbose output (include ATS address properties)"), + &opt_verbose), + GNUNET_GETOPT_OPTION_END }; + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; - res = GNUNET_PROGRAM_run (argc, - argv, - "gnunet-ats", - gettext_noop ("Print information about ATS state"), - options, - &run, - NULL); - GNUNET_free_non_null (opt_pid_str); - GNUNET_free_non_null (opt_type_str); - GNUNET_free ((void *) argv); + res = GNUNET_PROGRAM_run(argc, + argv, + "gnunet-ats", + gettext_noop("Print information about ATS state"), + options, + &run, + NULL); + GNUNET_free_non_null(opt_pid_str); + GNUNET_free_non_null(opt_type_str); + GNUNET_free((void *)argv); if (GNUNET_OK == res) return ret; diff --git a/src/ats/ats.h b/src/ats/ats.h index 7c9559495..3501860f3 100644 --- a/src/ats/ats.h +++ b/src/ats/ats.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/ats.h * @brief automatic transport selection messages @@ -34,9 +34,7 @@ * Flag used to indicate which type of client is connecting * to the ATS service. */ -enum StartFlag -{ - +enum StartFlag { /** * This is a scheduling client (aka transport service) */ @@ -67,8 +65,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * First message any client sends to ATS, used to self-identify * (what type of client this is). */ -struct ClientStartMessage -{ +struct ClientStartMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_START. */ @@ -85,8 +82,7 @@ struct ClientStartMessage * Connectivity client to ATS service: we would like to have * address suggestions for this peer. */ -struct RequestAddressMessage -{ +struct RequestAddressMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS or * #GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS_CANCEL to stop @@ -109,8 +105,7 @@ struct RequestAddressMessage /** * Scheduling client to ATS service: here is another address you can use. */ -struct AddressAddMessage -{ +struct AddressAddMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_ADDRESS_ADD. */ @@ -152,7 +147,6 @@ struct AddressAddMessage * - char address[address_length] * - char plugin_name[plugin_name_length] (including '\0'-termination). */ - }; @@ -160,8 +154,7 @@ struct AddressAddMessage * Message used to notify ATS that the performance * characteristics for an address have changed. */ -struct AddressUpdateMessage -{ +struct AddressUpdateMessage { /** * Message of type #GNUNET_MESSAGE_TYPE_ATS_ADDRESS_UPDATE. */ @@ -183,7 +176,6 @@ struct AddressUpdateMessage * Performance properties of the address. */ struct GNUNET_ATS_PropertiesNBO properties; - }; @@ -192,8 +184,7 @@ struct AddressUpdateMessage * was destroyed and must thus henceforth no longer be considered * for scheduling. */ -struct AddressDestroyedMessage -{ +struct AddressDestroyedMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_ADDRESS_DESTROYED. */ @@ -210,7 +201,6 @@ struct AddressDestroyedMessage * to find the session faster). */ struct GNUNET_PeerIdentity peer; - }; @@ -218,8 +208,7 @@ struct AddressDestroyedMessage * Message sent by ATS service to client to confirm that it is done * using the given session ID. */ -struct GNUNET_ATS_SessionReleaseMessage -{ +struct GNUNET_ATS_SessionReleaseMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_SESSION_RELEASE. */ @@ -245,8 +234,7 @@ struct GNUNET_ATS_SessionReleaseMessage * identified by the given @e session_id for the given @e peer with * the given @e bandwidth_in and @e bandwidth_out limits from now on. */ -struct AddressSuggestionMessage -{ +struct AddressSuggestionMessage { /** * A message of type #GNUNET_MESSAGE_TYPE_ATS_ADDRESS_SUGGESTION. */ @@ -274,15 +262,13 @@ struct AddressSuggestionMessage * How much bandwidth we are allowed for receiving. */ struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in; - }; /** * */ -struct PeerInformationMessage -{ +struct PeerInformationMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_PEER_INFORMATION */ @@ -338,15 +324,13 @@ struct PeerInformationMessage * - char address[address_length] * - char plugin_name[plugin_name_length] (including '\0'-termination). */ - }; /** * Client to service: please give us an overview of the addresses. */ -struct AddressListRequestMessage -{ +struct AddressListRequestMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_REQUEST */ @@ -367,15 +351,13 @@ struct AddressListRequestMessage * #GNUNET_NO to only return addresses that are in use. */ int32_t all GNUNET_PACKED; - }; /** * */ -struct ReservationRequestMessage -{ +struct ReservationRequestMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_RESERVATION_REQUEST */ @@ -396,8 +378,7 @@ struct ReservationRequestMessage /** * */ -struct ReservationResultMessage -{ +struct ReservationResultMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_RESERVATION_RESULT */ @@ -424,9 +405,7 @@ struct ReservationResultMessage * Variable-size entry in a `struct ChangePreferenceMessage` or * `struct FeedbackPreferenceMessage`. */ -struct PreferenceInformation -{ - +struct PreferenceInformation { /** * An `enum GNUNET_ATS_PreferenceKind` in NBO. */ @@ -437,15 +416,13 @@ struct PreferenceInformation * preference_kind being expressed. */ float preference_value GNUNET_PACKED; - }; /** * Client to ATS: I have a performance preference for a peer. */ -struct ChangePreferenceMessage -{ +struct ChangePreferenceMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_CHANGE. */ @@ -470,8 +447,7 @@ struct ChangePreferenceMessage /** * Message containing application feedback for a peer */ -struct FeedbackPreferenceMessage -{ +struct FeedbackPreferenceMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_FEEDBACK. */ diff --git a/src/ats/ats2.h b/src/ats/ats2.h index ad9b0a3da..723a8440d 100644 --- a/src/ats/ats2.h +++ b/src/ats/ats2.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/ats2.h * @brief automatic transport selection messages @@ -36,9 +36,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * ATS performance characteristics for an address. */ -struct PropertiesNBO -{ - +struct PropertiesNBO { /** * Delay. Time between when the time packet is sent and the packet * arrives. FOREVER if we did not (successfully) measure yet. @@ -101,7 +99,6 @@ struct PropertiesNBO * A `enum GNUNET_TRANSPORT_CommunicatorCharacteristics` in NBO. */ uint32_t cc; - }; @@ -109,8 +106,7 @@ struct PropertiesNBO * Application client to ATS service: we would like to have * address suggestions for this peer. */ -struct ExpressPreferenceMessage -{ +struct ExpressPreferenceMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_SUGGEST or * #GNUNET_MESSAGE_TYPE_ATS_SUGGEST_CANCEL to stop @@ -133,15 +129,13 @@ struct ExpressPreferenceMessage * How much bandwidth in bytes/second does the application expect? */ struct GNUNET_BANDWIDTH_Value32NBO bw; - }; /** * Transport client to ATS service: here is another session you can use. */ -struct SessionAddMessage -{ +struct SessionAddMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_SESSION_ADD or * #GNUNET_MESSAGE_TYPE_ATS_SESSION_ADD_INBOUND_ONLY @@ -167,7 +161,6 @@ struct SessionAddMessage /* followed by: * - char * address (including '\0'-termination). */ - }; @@ -175,8 +168,7 @@ struct SessionAddMessage * Message used to notify ATS that the performance * characteristics for an session have changed. */ -struct SessionUpdateMessage -{ +struct SessionUpdateMessage { /** * Message of type #GNUNET_MESSAGE_TYPE_ATS_SESSION_UPDATE. */ @@ -198,7 +190,6 @@ struct SessionUpdateMessage * Performance properties of the session. */ struct PropertiesNBO properties; - }; @@ -207,8 +198,7 @@ struct SessionUpdateMessage * was destroyed and must thus henceforth no longer be considered * for scheduling. */ -struct SessionDelMessage -{ +struct SessionDelMessage { /** * Type is #GNUNET_MESSAGE_TYPE_ATS_SESSION_DEL. */ @@ -225,7 +215,6 @@ struct SessionDelMessage * to find the session faster). */ struct GNUNET_PeerIdentity peer; - }; @@ -234,8 +223,7 @@ struct SessionDelMessage * identified by the given @e session_id for the given @e peer with * the given @e bandwidth_in and @e bandwidth_out limits from now on. */ -struct SessionAllocationMessage -{ +struct SessionAllocationMessage { /** * A message of type #GNUNET_MESSAGE_TYPE_ATS_SESSION_ALLOCATION. */ @@ -263,7 +251,6 @@ struct SessionAllocationMessage * How much bandwidth we are allowed for receiving. */ struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in; - }; @@ -271,8 +258,7 @@ struct SessionAllocationMessage * ATS Service suggests to the transport service to try the address * for the given @e peer. */ -struct AddressSuggestionMessage -{ +struct AddressSuggestionMessage { /** * A message of type #GNUNET_MESSAGE_TYPE_ATS_ADDRESS_SUGGESTION. */ diff --git a/src/ats/ats_api2_application.c b/src/ats/ats_api2_application.c index 444ac3ae3..2a21a116a 100644 --- a/src/ats/ats_api2_application.c +++ b/src/ats/ats_api2_application.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/ats_api2_application.c * @brief enable clients to ask ATS about establishing connections to peers @@ -28,14 +28,13 @@ #include "ats2.h" -#define LOG(kind,...) GNUNET_log_from(kind, "ats-application-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "ats-application-api", __VA_ARGS__) /** * Handle for ATS address suggestion requests. */ -struct GNUNET_ATS_ApplicationSuggestHandle -{ +struct GNUNET_ATS_ApplicationSuggestHandle { /** * ID of the peer for which address suggestion was requested. */ @@ -61,9 +60,7 @@ struct GNUNET_ATS_ApplicationSuggestHandle /** * Handle to the ATS subsystem for application management. */ -struct GNUNET_ATS_ApplicationHandle -{ - +struct GNUNET_ATS_ApplicationHandle { /** * Our configuration. */ @@ -99,7 +96,7 @@ struct GNUNET_ATS_ApplicationHandle * @param ch handle to use to re-connect. */ static void -reconnect (struct GNUNET_ATS_ApplicationHandle *ch); +reconnect(struct GNUNET_ATS_ApplicationHandle *ch); /** @@ -108,12 +105,12 @@ reconnect (struct GNUNET_ATS_ApplicationHandle *ch); * @param cls handle to use to re-connect. */ static void -reconnect_task (void *cls) +reconnect_task(void *cls) { struct GNUNET_ATS_ApplicationHandle *ch = cls; ch->task = NULL; - reconnect (ch); + reconnect(ch); } @@ -123,17 +120,17 @@ reconnect_task (void *cls) * @param ch our handle */ static void -force_reconnect (struct GNUNET_ATS_ApplicationHandle *ch) +force_reconnect(struct GNUNET_ATS_ApplicationHandle *ch) { if (NULL != ch->mq) - { - GNUNET_MQ_destroy (ch->mq); - ch->mq = NULL; - } - ch->backoff = GNUNET_TIME_STD_BACKOFF (ch->backoff); - ch->task = GNUNET_SCHEDULER_add_delayed (ch->backoff, - &reconnect_task, - ch); + { + GNUNET_MQ_destroy(ch->mq); + ch->mq = NULL; + } + ch->backoff = GNUNET_TIME_STD_BACKOFF(ch->backoff); + ch->task = GNUNET_SCHEDULER_add_delayed(ch->backoff, + &reconnect_task, + ch); } @@ -145,15 +142,15 @@ force_reconnect (struct GNUNET_ATS_ApplicationHandle *ch) * @param error details about the error */ static void -error_handler (void *cls, - enum GNUNET_MQ_Error error) +error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_ATS_ApplicationHandle *ch = cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "ATS connection died (code %d), reconnecting\n", - (int) error); - force_reconnect (ch); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "ATS connection died (code %d), reconnecting\n", + (int)error); + force_reconnect(ch); } @@ -167,9 +164,9 @@ error_handler (void *cls, * failure (message queue no longer exists) */ static int -transmit_suggestion (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *value) +transmit_suggestion(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *value) { struct GNUNET_ATS_ApplicationHandle *ch = cls; struct GNUNET_ATS_ApplicationSuggestHandle *sh = value; @@ -178,12 +175,12 @@ transmit_suggestion (void *cls, if (NULL == ch->mq) return GNUNET_SYSERR; - ev = GNUNET_MQ_msg (m, - GNUNET_MESSAGE_TYPE_ATS_SUGGEST); - m->pk = htonl ((uint32_t) sh->pk); + ev = GNUNET_MQ_msg(m, + GNUNET_MESSAGE_TYPE_ATS_SUGGEST); + m->pk = htonl((uint32_t)sh->pk); m->bw = sh->bw; m->peer = *peer; - GNUNET_MQ_send (ch->mq, ev); + GNUNET_MQ_send(ch->mq, ev); return GNUNET_OK; } @@ -194,26 +191,26 @@ transmit_suggestion (void *cls, * @param ch handle to use to re-connect. */ static void -reconnect (struct GNUNET_ATS_ApplicationHandle *ch) +reconnect(struct GNUNET_ATS_ApplicationHandle *ch) { static const struct GNUNET_MQ_MessageHandler handlers[] = { { NULL, 0, 0 } }; - GNUNET_assert (NULL == ch->mq); - ch->mq = GNUNET_CLIENT_connect (ch->cfg, - "ats", - handlers, - &error_handler, - ch); + GNUNET_assert(NULL == ch->mq); + ch->mq = GNUNET_CLIENT_connect(ch->cfg, + "ats", + handlers, + &error_handler, + ch); if (NULL == ch->mq) - { - force_reconnect (ch); - return; - } - GNUNET_CONTAINER_multipeermap_iterate (ch->sug_requests, - &transmit_suggestion, - ch); + { + force_reconnect(ch); + return; + } + GNUNET_CONTAINER_multipeermap_iterate(ch->sug_requests, + &transmit_suggestion, + ch); } @@ -224,15 +221,15 @@ reconnect (struct GNUNET_ATS_ApplicationHandle *ch) * @return ats application handle, NULL on error */ struct GNUNET_ATS_ApplicationHandle * -GNUNET_ATS_application_init (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_ATS_application_init(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_ATS_ApplicationHandle *ch; - ch = GNUNET_new (struct GNUNET_ATS_ApplicationHandle); + ch = GNUNET_new(struct GNUNET_ATS_ApplicationHandle); ch->cfg = cfg; - ch->sug_requests = GNUNET_CONTAINER_multipeermap_create (32, - GNUNET_YES); - reconnect (ch); + ch->sug_requests = GNUNET_CONTAINER_multipeermap_create(32, + GNUNET_YES); + reconnect(ch); return ch; } @@ -247,13 +244,13 @@ GNUNET_ATS_application_init (const struct GNUNET_CONFIGURATION_Handle *cfg) * @return #GNUNET_OK (continue to iterate) */ static int -free_sug_handle (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +free_sug_handle(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct GNUNET_ATS_ApplicationSuggestHandle *cur = value; - GNUNET_free (cur); + GNUNET_free(cur); return GNUNET_OK; } @@ -264,23 +261,23 @@ free_sug_handle (void *cls, * @param ch handle to release */ void -GNUNET_ATS_application_done (struct GNUNET_ATS_ApplicationHandle *ch) +GNUNET_ATS_application_done(struct GNUNET_ATS_ApplicationHandle *ch) { if (NULL != ch->mq) - { - GNUNET_MQ_destroy (ch->mq); - ch->mq = NULL; - } + { + GNUNET_MQ_destroy(ch->mq); + ch->mq = NULL; + } if (NULL != ch->task) - { - GNUNET_SCHEDULER_cancel (ch->task); - ch->task = NULL; - } - GNUNET_CONTAINER_multipeermap_iterate (ch->sug_requests, - &free_sug_handle, - NULL); - GNUNET_CONTAINER_multipeermap_destroy (ch->sug_requests); - GNUNET_free (ch); + { + GNUNET_SCHEDULER_cancel(ch->task); + ch->task = NULL; + } + GNUNET_CONTAINER_multipeermap_iterate(ch->sug_requests, + &free_sug_handle, + NULL); + GNUNET_CONTAINER_multipeermap_destroy(ch->sug_requests); + GNUNET_free(ch); } @@ -298,31 +295,31 @@ GNUNET_ATS_application_done (struct GNUNET_ATS_ApplicationHandle *ch) * @return suggest handle, NULL if a request is already pending */ struct GNUNET_ATS_ApplicationSuggestHandle * -GNUNET_ATS_application_suggest (struct GNUNET_ATS_ApplicationHandle *ch, - const struct GNUNET_PeerIdentity *peer, - enum GNUNET_MQ_PreferenceKind pk, - struct GNUNET_BANDWIDTH_Value32NBO bw) +GNUNET_ATS_application_suggest(struct GNUNET_ATS_ApplicationHandle *ch, + const struct GNUNET_PeerIdentity *peer, + enum GNUNET_MQ_PreferenceKind pk, + struct GNUNET_BANDWIDTH_Value32NBO bw) { struct GNUNET_ATS_ApplicationSuggestHandle *s; - s = GNUNET_new (struct GNUNET_ATS_ApplicationSuggestHandle); + s = GNUNET_new(struct GNUNET_ATS_ApplicationSuggestHandle); s->ch = ch; s->id = *peer; s->pk = pk; s->bw = bw; - (void) GNUNET_CONTAINER_multipeermap_put (ch->sug_requests, - &s->id, - s, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Requesting ATS to suggest address for `%s'\n", - GNUNET_i2s (peer)); + (void)GNUNET_CONTAINER_multipeermap_put(ch->sug_requests, + &s->id, + s, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Requesting ATS to suggest address for `%s'\n", + GNUNET_i2s(peer)); if (NULL == ch->mq) return s; - GNUNET_assert (GNUNET_OK == - transmit_suggestion (ch, - &s->id, - s)); + GNUNET_assert(GNUNET_OK == + transmit_suggestion(ch, + &s->id, + s)); return s; } @@ -333,32 +330,32 @@ GNUNET_ATS_application_suggest (struct GNUNET_ATS_ApplicationHandle *ch, * @param sh handle to stop */ void -GNUNET_ATS_application_suggest_cancel (struct GNUNET_ATS_ApplicationSuggestHandle *sh) +GNUNET_ATS_application_suggest_cancel(struct GNUNET_ATS_ApplicationSuggestHandle *sh) { struct GNUNET_ATS_ApplicationHandle *ch = sh->ch; struct GNUNET_MQ_Envelope *ev; struct ExpressPreferenceMessage *m; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Telling ATS we no longer care for an address for `%s'\n", - GNUNET_i2s (&sh->id)); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_remove (ch->sug_requests, - &sh->id, - sh)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Telling ATS we no longer care for an address for `%s'\n", + GNUNET_i2s(&sh->id)); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_remove(ch->sug_requests, + &sh->id, + sh)); if (NULL == ch->mq) - { - GNUNET_free (sh); - return; - } - ev = GNUNET_MQ_msg (m, - GNUNET_MESSAGE_TYPE_ATS_SUGGEST_CANCEL); - m->pk = htonl ((uint32_t) sh->pk); + { + GNUNET_free(sh); + return; + } + ev = GNUNET_MQ_msg(m, + GNUNET_MESSAGE_TYPE_ATS_SUGGEST_CANCEL); + m->pk = htonl((uint32_t)sh->pk); m->bw = sh->bw; m->peer = sh->id; - GNUNET_MQ_send (ch->mq, - ev); - GNUNET_free (sh); + GNUNET_MQ_send(ch->mq, + ev); + GNUNET_free(sh); } diff --git a/src/ats/ats_api2_transport.c b/src/ats/ats_api2_transport.c index e73b2daa8..441e7c8c2 100644 --- a/src/ats/ats_api2_transport.c +++ b/src/ats/ats_api2_transport.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/ats_api2_transport.c * @brief address suggestions and bandwidth allocation @@ -27,7 +27,7 @@ #include "gnunet_ats_transport_service.h" #include "ats2.h" -#define LOG(kind,...) GNUNET_log_from(kind, "ats-transport-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "ats-transport-api", __VA_ARGS__) /** @@ -35,9 +35,7 @@ * doesn't matter if we have a session, any session that ATS is * allowed to suggest right now should be tracked. */ -struct GNUNET_ATS_SessionRecord -{ - +struct GNUNET_ATS_SessionRecord { /** * Transport handle this session record belongs to. */ @@ -75,16 +73,13 @@ struct GNUNET_ATS_SessionRecord * messages. */ uint32_t slot; - }; /** * Handle to the ATS subsystem for bandwidth/transport transport information. */ -struct GNUNET_ATS_TransportHandle -{ - +struct GNUNET_ATS_TransportHandle { /** * Our configuration. */ @@ -129,7 +124,6 @@ struct GNUNET_ATS_TransportHandle * Reconnect backoff delay. */ struct GNUNET_TIME_Relative backoff; - }; @@ -141,18 +135,18 @@ struct GNUNET_ATS_TransportHandle * @param hbo value read */ static void -properties_hton (struct PropertiesNBO *nbo, - const struct GNUNET_ATS_Properties *hbo) +properties_hton(struct PropertiesNBO *nbo, + const struct GNUNET_ATS_Properties *hbo) { - nbo->delay = GNUNET_TIME_relative_hton (hbo->delay); - nbo->goodput_out = htonl (hbo->goodput_out); - nbo->goodput_in = htonl (hbo->goodput_in); - nbo->utilization_out = htonl (hbo->utilization_out); - nbo->utilization_in = htonl (hbo->utilization_in); - nbo->distance = htonl (hbo->distance); - nbo->mtu = htonl (hbo->mtu); - nbo->nt = htonl ((uint32_t) hbo->nt); - nbo->cc = htonl ((uint32_t) hbo->cc); + nbo->delay = GNUNET_TIME_relative_hton(hbo->delay); + nbo->goodput_out = htonl(hbo->goodput_out); + nbo->goodput_in = htonl(hbo->goodput_in); + nbo->utilization_out = htonl(hbo->utilization_out); + nbo->utilization_in = htonl(hbo->utilization_in); + nbo->distance = htonl(hbo->distance); + nbo->mtu = htonl(hbo->mtu); + nbo->nt = htonl((uint32_t)hbo->nt); + nbo->cc = htonl((uint32_t)hbo->cc); } @@ -162,7 +156,7 @@ properties_hton (struct PropertiesNBO *nbo, * @param sh handle to use to re-connect. */ static void -reconnect (struct GNUNET_ATS_TransportHandle *ath); +reconnect(struct GNUNET_ATS_TransportHandle *ath); /** @@ -171,12 +165,12 @@ reconnect (struct GNUNET_ATS_TransportHandle *ath); * @param cls handle to use to re-connect. */ static void -reconnect_task (void *cls) +reconnect_task(void *cls) { struct GNUNET_ATS_TransportHandle *ath = cls; ath->task = NULL; - reconnect (ath); + reconnect(ath); } @@ -186,20 +180,20 @@ reconnect_task (void *cls) * @param ath our handle */ static void -force_reconnect (struct GNUNET_ATS_TransportHandle *ath) +force_reconnect(struct GNUNET_ATS_TransportHandle *ath) { if (NULL != ath->mq) - { - GNUNET_MQ_destroy (ath->mq); - ath->mq = NULL; - } + { + GNUNET_MQ_destroy(ath->mq); + ath->mq = NULL; + } /* FIXME: do we tell transport service about disconnect events? CON: initially ATS will have a really screwed picture of the world and the rapid change would be bad. PRO: if we don't, ATS and transport may disagree about the allocation for a while... For now: lazy: do nothing. */ - ath->backoff = GNUNET_TIME_STD_BACKOFF (ath->backoff); - ath->task = GNUNET_SCHEDULER_add_delayed (ath->backoff, + ath->backoff = GNUNET_TIME_STD_BACKOFF(ath->backoff); + ath->task = GNUNET_SCHEDULER_add_delayed(ath->backoff, &reconnect_task, ath); } @@ -212,11 +206,11 @@ force_reconnect (struct GNUNET_ATS_TransportHandle *ath) * @param m message received */ static int -check_ats_address_suggestion (void *cls, - const struct AddressSuggestionMessage *m) +check_ats_address_suggestion(void *cls, + const struct AddressSuggestionMessage *m) { - (void) cls; - GNUNET_MQ_check_zero_termination (m); + (void)cls; + GNUNET_MQ_check_zero_termination(m); return GNUNET_SYSERR; } @@ -228,13 +222,13 @@ check_ats_address_suggestion (void *cls, * @param m message received */ static void -handle_ats_address_suggestion (void *cls, - const struct AddressSuggestionMessage *m) +handle_ats_address_suggestion(void *cls, + const struct AddressSuggestionMessage *m) { struct GNUNET_ATS_TransportHandle *ath = cls; - const char *address = (const char *) &m[1]; + const char *address = (const char *)&m[1]; - ath->suggest_cb (ath->suggest_cb_cls, + ath->suggest_cb(ath->suggest_cb_cls, &m->peer, address); } @@ -243,8 +237,7 @@ handle_ats_address_suggestion (void *cls, /** * Closure for #match_session_cb. */ -struct FindContext -{ +struct FindContext { /** * Key to look for. */ @@ -266,19 +259,19 @@ struct FindContext * @return #GNUNET_NO if match found, #GNUNET_YES to continue searching */ static int -match_session_cb (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *value) +match_session_cb(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *value) { struct FindContext *fc = cls; struct GNUNET_ATS_SessionRecord *sr = value; - (void) pid; + (void)pid; if (fc->session_id == sr->slot) - { - fc->sr = sr; - return GNUNET_NO; - } + { + fc->sr = sr; + return GNUNET_NO; + } return GNUNET_YES; } @@ -293,18 +286,19 @@ match_session_cb (void *cls, * @return NULL if no such record exists */ static struct GNUNET_ATS_SessionRecord * -find_session (struct GNUNET_ATS_TransportHandle *ath, - uint32_t session_id, - const struct GNUNET_PeerIdentity *pid) +find_session(struct GNUNET_ATS_TransportHandle *ath, + uint32_t session_id, + const struct GNUNET_PeerIdentity *pid) { struct FindContext fc = { .session_id = session_id, .sr = NULL }; - GNUNET_CONTAINER_multipeermap_get_multiple (ath->records, - pid, - &match_session_cb, - &fc); + + GNUNET_CONTAINER_multipeermap_get_multiple(ath->records, + pid, + &match_session_cb, + &fc); return fc.sr; } @@ -316,34 +310,34 @@ find_session (struct GNUNET_ATS_TransportHandle *ath, * @param m message received */ static void -handle_ats_session_allocation (void *cls, - const struct SessionAllocationMessage *m) +handle_ats_session_allocation(void *cls, + const struct SessionAllocationMessage *m) { struct GNUNET_ATS_TransportHandle *ath = cls; struct GNUNET_ATS_SessionRecord *ar; uint32_t session_id; - session_id = ntohl (m->session_id); - ar = find_session (ath, - session_id, - &m->peer); + session_id = ntohl(m->session_id); + ar = find_session(ath, + session_id, + &m->peer); if (NULL == ar) - { - /* this can (rarely) happen if ATS changes an sessiones allocation - just when the transport service deleted it */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Allocation ignored, session unknown\n"); - return; - } + { + /* this can (rarely) happen if ATS changes an sessiones allocation + just when the transport service deleted it */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Allocation ignored, session unknown\n"); + return; + } ath->backoff = GNUNET_TIME_UNIT_ZERO; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "ATS allocates bandwidth for peer `%s' using address %s\n", - GNUNET_i2s (&ar->pid), - ar->address); - ath->alloc_cb (ath->alloc_cb_cls, - ar->session, - m->bandwidth_out, - m->bandwidth_in); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "ATS allocates bandwidth for peer `%s' using address %s\n", + GNUNET_i2s(&ar->pid), + ar->address); + ath->alloc_cb(ath->alloc_cb_cls, + ar->session, + m->bandwidth_out, + m->bandwidth_in); } @@ -355,15 +349,15 @@ handle_ats_session_allocation (void *cls, * @param error details about the error */ static void -error_handler (void *cls, - enum GNUNET_MQ_Error error) +error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_ATS_TransportHandle *ath = cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "ATS connection died (code %d), reconnecting\n", - (int) error); - force_reconnect (ath); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "ATS connection died (code %d), reconnecting\n", + (int)error); + force_reconnect(ath); } @@ -374,7 +368,7 @@ error_handler (void *cls, * @param ar the session to inform the ATS service about */ static void -send_add_session_message (const struct GNUNET_ATS_SessionRecord *ar) +send_add_session_message(const struct GNUNET_ATS_SessionRecord *ar) { struct GNUNET_ATS_TransportHandle *ath = ar->ath; struct GNUNET_MQ_Envelope *ev; @@ -383,26 +377,26 @@ send_add_session_message (const struct GNUNET_ATS_SessionRecord *ar) if (NULL == ath->mq) return; /* disconnected, skip for now */ - alen = strlen (ar->address) + 1; - ev = GNUNET_MQ_msg_extra (m, - alen, - (NULL == ar->session) - ? GNUNET_MESSAGE_TYPE_ATS_SESSION_ADD_INBOUND_ONLY - : GNUNET_MESSAGE_TYPE_ATS_SESSION_ADD); + alen = strlen(ar->address) + 1; + ev = GNUNET_MQ_msg_extra(m, + alen, + (NULL == ar->session) + ? GNUNET_MESSAGE_TYPE_ATS_SESSION_ADD_INBOUND_ONLY + : GNUNET_MESSAGE_TYPE_ATS_SESSION_ADD); m->peer = ar->pid; - m->session_id = htonl (ar->slot); - properties_hton (&m->properties, - &ar->properties); - GNUNET_memcpy (&m[1], - ar->address, - alen); - - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Adding address `%s' for peer `%s'\n", - ar->address, - GNUNET_i2s (&ar->pid)); - GNUNET_MQ_send (ath->mq, - ev); + m->session_id = htonl(ar->slot); + properties_hton(&m->properties, + &ar->properties); + GNUNET_memcpy(&m[1], + ar->address, + alen); + + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Adding address `%s' for peer `%s'\n", + ar->address, + GNUNET_i2s(&ar->pid)); + GNUNET_MQ_send(ath->mq, + ev); } @@ -415,15 +409,15 @@ send_add_session_message (const struct GNUNET_ATS_SessionRecord *ar) * @return #GNUNET_OK */ static int -send_add_session_cb (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *value) +send_add_session_cb(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *value) { struct GNUNET_ATS_SessionRecord *ar = value; - (void) cls; - (void) pid; - send_add_session_message (ar); + (void)cls; + (void)pid; + send_add_session_message(ar); return GNUNET_OK; } @@ -434,43 +428,43 @@ send_add_session_cb (void *cls, * @param ath handle to use to re-connect. */ static void -reconnect (struct GNUNET_ATS_TransportHandle *ath) +reconnect(struct GNUNET_ATS_TransportHandle *ath) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (ats_address_suggestion, - GNUNET_MESSAGE_TYPE_ATS_ADDRESS_SUGGESTION, - struct AddressSuggestionMessage, - ath), - GNUNET_MQ_hd_fixed_size (ats_session_allocation, - GNUNET_MESSAGE_TYPE_ATS_SESSION_ALLOCATION, - struct SessionAllocationMessage, - ath), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(ats_address_suggestion, + GNUNET_MESSAGE_TYPE_ATS_ADDRESS_SUGGESTION, + struct AddressSuggestionMessage, + ath), + GNUNET_MQ_hd_fixed_size(ats_session_allocation, + GNUNET_MESSAGE_TYPE_ATS_SESSION_ALLOCATION, + struct SessionAllocationMessage, + ath), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *ev; struct GNUNET_MessageHeader *init; - GNUNET_assert (NULL == ath->mq); - ath->mq = GNUNET_CLIENT_connect (ath->cfg, + GNUNET_assert(NULL == ath->mq); + ath->mq = GNUNET_CLIENT_connect(ath->cfg, "ats", handlers, &error_handler, ath); if (NULL == ath->mq) - { - GNUNET_break (0); - force_reconnect (ath); - return; - } - ev = GNUNET_MQ_msg (init, - GNUNET_MESSAGE_TYPE_ATS_START); - GNUNET_MQ_send (ath->mq, - ev); + { + GNUNET_break(0); + force_reconnect(ath); + return; + } + ev = GNUNET_MQ_msg(init, + GNUNET_MESSAGE_TYPE_ATS_START); + GNUNET_MQ_send(ath->mq, + ev); if (NULL == ath->mq) return; - GNUNET_CONTAINER_multipeermap_iterate (ath->records, - &send_add_session_cb, - ath); + GNUNET_CONTAINER_multipeermap_iterate(ath->records, + &send_add_session_cb, + ath); } @@ -485,23 +479,23 @@ reconnect (struct GNUNET_ATS_TransportHandle *ath) * @return ats context */ struct GNUNET_ATS_TransportHandle * -GNUNET_ATS_transport_init (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_ATS_AllocationCallback alloc_cb, - void *alloc_cb_cls, - GNUNET_ATS_SuggestionCallback suggest_cb, - void *suggest_cb_cls) +GNUNET_ATS_transport_init(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_ATS_AllocationCallback alloc_cb, + void *alloc_cb_cls, + GNUNET_ATS_SuggestionCallback suggest_cb, + void *suggest_cb_cls) { struct GNUNET_ATS_TransportHandle *ath; - ath = GNUNET_new (struct GNUNET_ATS_TransportHandle); + ath = GNUNET_new(struct GNUNET_ATS_TransportHandle); ath->cfg = cfg; ath->suggest_cb = suggest_cb; ath->suggest_cb_cls = suggest_cb_cls; ath->alloc_cb = alloc_cb; ath->alloc_cb_cls = alloc_cb_cls; - ath->records = GNUNET_CONTAINER_multipeermap_create (128, + ath->records = GNUNET_CONTAINER_multipeermap_create(128, GNUNET_YES); - reconnect (ath); + reconnect(ath); return ath; } @@ -515,15 +509,15 @@ GNUNET_ATS_transport_init (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return #GNUNET_OK */ static int -free_record (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *value) +free_record(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *value) { struct GNUNET_ATS_SessionRecord *ar = value; - (void) cls; - (void) pid; - GNUNET_free (ar); + (void)cls; + (void)pid; + GNUNET_free(ar); return GNUNET_OK; } @@ -534,23 +528,23 @@ free_record (void *cls, * @param ath handle to release */ void -GNUNET_ATS_transport_done (struct GNUNET_ATS_TransportHandle *ath) +GNUNET_ATS_transport_done(struct GNUNET_ATS_TransportHandle *ath) { if (NULL != ath->mq) - { - GNUNET_MQ_destroy (ath->mq); - ath->mq = NULL; - } + { + GNUNET_MQ_destroy(ath->mq); + ath->mq = NULL; + } if (NULL != ath->task) - { - GNUNET_SCHEDULER_cancel (ath->task); - ath->task = NULL; - } - GNUNET_CONTAINER_multipeermap_iterate (ath->records, - &free_record, - NULL); - GNUNET_CONTAINER_multipeermap_destroy (ath->records); - GNUNET_free (ath); + { + GNUNET_SCHEDULER_cancel(ath->task); + ath->task = NULL; + } + GNUNET_CONTAINER_multipeermap_iterate(ath->records, + &free_record, + NULL); + GNUNET_CONTAINER_multipeermap_destroy(ath->records); + GNUNET_free(ath); } @@ -569,55 +563,56 @@ GNUNET_ATS_transport_done (struct GNUNET_ATS_TransportHandle *ath) * on error (i.e. ATS knows this exact session already) */ struct GNUNET_ATS_SessionRecord * -GNUNET_ATS_session_add (struct GNUNET_ATS_TransportHandle *ath, - const struct GNUNET_PeerIdentity *pid, - const char *address, - struct GNUNET_ATS_Session *session, - const struct GNUNET_ATS_Properties *prop) +GNUNET_ATS_session_add(struct GNUNET_ATS_TransportHandle *ath, + const struct GNUNET_PeerIdentity *pid, + const char *address, + struct GNUNET_ATS_Session *session, + const struct GNUNET_ATS_Properties *prop) { struct GNUNET_ATS_SessionRecord *ar; uint32_t s; size_t alen; if (NULL == address) - { - /* we need a valid address */ - GNUNET_break (0); - return NULL; - } - alen = strlen (address) + 1; - if ( (alen + sizeof (struct SessionAddMessage) >= GNUNET_MAX_MESSAGE_SIZE) || - (alen >= GNUNET_MAX_MESSAGE_SIZE) ) - { - /* address too large for us, this should not happen */ - GNUNET_break (0); - return NULL; - } + { + /* we need a valid address */ + GNUNET_break(0); + return NULL; + } + alen = strlen(address) + 1; + if ((alen + sizeof(struct SessionAddMessage) >= GNUNET_MAX_MESSAGE_SIZE) || + (alen >= GNUNET_MAX_MESSAGE_SIZE)) + { + /* address too large for us, this should not happen */ + GNUNET_break(0); + return NULL; + } /* Spin 's' until we find an unused session ID for this pid */ - for (s = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT32_MAX); - NULL != find_session (ath, - s, - pid); - s++) ; - - alen = strlen (address) + 1; - ar = GNUNET_malloc (sizeof (struct GNUNET_ATS_SessionRecord) + alen); + for (s = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + UINT32_MAX); + NULL != find_session(ath, + s, + pid); + s++) + ; + + alen = strlen(address) + 1; + ar = GNUNET_malloc(sizeof(struct GNUNET_ATS_SessionRecord) + alen); ar->ath = ath; ar->slot = s; ar->session = session; - ar->address = (const char *) &ar[1]; + ar->address = (const char *)&ar[1]; ar->pid = *pid; ar->properties = *prop; - memcpy (&ar[1], - address, - alen); - (void) GNUNET_CONTAINER_multipeermap_put (ath->records, - &ar->pid, - ar, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - send_add_session_message (ar); + memcpy(&ar[1], + address, + alen); + (void)GNUNET_CONTAINER_multipeermap_put(ath->records, + &ar->pid, + ar, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + send_add_session_message(ar); return ar; } @@ -634,28 +629,28 @@ GNUNET_ATS_session_add (struct GNUNET_ATS_TransportHandle *ath, * @param prop performance data for the session */ void -GNUNET_ATS_session_update (struct GNUNET_ATS_SessionRecord *ar, - const struct GNUNET_ATS_Properties *prop) +GNUNET_ATS_session_update(struct GNUNET_ATS_SessionRecord *ar, + const struct GNUNET_ATS_Properties *prop) { struct GNUNET_ATS_TransportHandle *ath = ar->ath; struct GNUNET_MQ_Envelope *ev; struct SessionUpdateMessage *m; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Updating address `%s' for peer `%s'\n", - ar->address, - GNUNET_i2s (&ar->pid)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Updating address `%s' for peer `%s'\n", + ar->address, + GNUNET_i2s(&ar->pid)); ar->properties = *prop; if (NULL == ath->mq) return; /* disconnected, skip for now */ - ev = GNUNET_MQ_msg (m, - GNUNET_MESSAGE_TYPE_ATS_SESSION_UPDATE); - m->session_id = htonl (ar->slot); + ev = GNUNET_MQ_msg(m, + GNUNET_MESSAGE_TYPE_ATS_SESSION_UPDATE); + m->session_id = htonl(ar->slot); m->peer = ar->pid; - properties_hton (&m->properties, - &ar->properties); - GNUNET_MQ_send (ath->mq, - ev); + properties_hton(&m->properties, + &ar->properties); + GNUNET_MQ_send(ath->mq, + ev); } @@ -667,24 +662,24 @@ GNUNET_ATS_session_update (struct GNUNET_ATS_SessionRecord *ar, * @param ar session record to drop */ void -GNUNET_ATS_session_del (struct GNUNET_ATS_SessionRecord *ar) +GNUNET_ATS_session_del(struct GNUNET_ATS_SessionRecord *ar) { struct GNUNET_ATS_TransportHandle *ath = ar->ath; struct GNUNET_MQ_Envelope *ev; struct SessionDelMessage *m; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Deleting address `%s' for peer `%s'\n", - ar->address, - GNUNET_i2s (&ar->pid)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Deleting address `%s' for peer `%s'\n", + ar->address, + GNUNET_i2s(&ar->pid)); if (NULL == ath->mq) return; - ev = GNUNET_MQ_msg (m, - GNUNET_MESSAGE_TYPE_ATS_SESSION_DEL); - m->session_id = htonl (ar->slot); + ev = GNUNET_MQ_msg(m, + GNUNET_MESSAGE_TYPE_ATS_SESSION_DEL); + m->session_id = htonl(ar->slot); m->peer = ar->pid; - GNUNET_MQ_send (ath->mq, - ev); + GNUNET_MQ_send(ath->mq, + ev); } diff --git a/src/ats/ats_api_connectivity.c b/src/ats/ats_api_connectivity.c index d1295d04d..2ff734c25 100644 --- a/src/ats/ats_api_connectivity.c +++ b/src/ats/ats_api_connectivity.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/ats_api_connectivity.c * @brief enable clients to ask ATS about establishing connections to peers @@ -28,14 +28,13 @@ #include "ats.h" -#define LOG(kind,...) GNUNET_log_from(kind, "ats-connectivity-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "ats-connectivity-api", __VA_ARGS__) /** * Handle for ATS address suggestion requests. */ -struct GNUNET_ATS_ConnectivitySuggestHandle -{ +struct GNUNET_ATS_ConnectivitySuggestHandle { /** * ID of the peer for which address suggestion was requested. */ @@ -56,9 +55,7 @@ struct GNUNET_ATS_ConnectivitySuggestHandle /** * Handle to the ATS subsystem for connectivity management. */ -struct GNUNET_ATS_ConnectivityHandle -{ - +struct GNUNET_ATS_ConnectivityHandle { /** * Our configuration. */ @@ -94,7 +91,7 @@ struct GNUNET_ATS_ConnectivityHandle * @param ch handle to use to re-connect. */ static void -reconnect (struct GNUNET_ATS_ConnectivityHandle *ch); +reconnect(struct GNUNET_ATS_ConnectivityHandle *ch); /** @@ -103,12 +100,12 @@ reconnect (struct GNUNET_ATS_ConnectivityHandle *ch); * @param cls handle to use to re-connect. */ static void -reconnect_task (void *cls) +reconnect_task(void *cls) { struct GNUNET_ATS_ConnectivityHandle *ch = cls; ch->task = NULL; - reconnect (ch); + reconnect(ch); } @@ -118,17 +115,17 @@ reconnect_task (void *cls) * @param ch our handle */ static void -force_reconnect (struct GNUNET_ATS_ConnectivityHandle *ch) +force_reconnect(struct GNUNET_ATS_ConnectivityHandle *ch) { if (NULL != ch->mq) - { - GNUNET_MQ_destroy (ch->mq); - ch->mq = NULL; - } - ch->backoff = GNUNET_TIME_STD_BACKOFF (ch->backoff); - ch->task = GNUNET_SCHEDULER_add_delayed (ch->backoff, - &reconnect_task, - ch); + { + GNUNET_MQ_destroy(ch->mq); + ch->mq = NULL; + } + ch->backoff = GNUNET_TIME_STD_BACKOFF(ch->backoff); + ch->task = GNUNET_SCHEDULER_add_delayed(ch->backoff, + &reconnect_task, + ch); } @@ -140,15 +137,15 @@ force_reconnect (struct GNUNET_ATS_ConnectivityHandle *ch) * @param error details about the error */ static void -error_handler (void *cls, - enum GNUNET_MQ_Error error) +error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_ATS_ConnectivityHandle *ch = cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "ATS connection died (code %d), reconnecting\n", - (int) error); - force_reconnect (ch); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "ATS connection died (code %d), reconnecting\n", + (int)error); + force_reconnect(ch); } @@ -162,9 +159,9 @@ error_handler (void *cls, * failure (message queue no longer exists) */ static int -transmit_suggestion (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *value) +transmit_suggestion(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *value) { struct GNUNET_ATS_ConnectivityHandle *ch = cls; struct GNUNET_ATS_ConnectivitySuggestHandle *sh = value; @@ -173,10 +170,10 @@ transmit_suggestion (void *cls, if (NULL == ch->mq) return GNUNET_SYSERR; - ev = GNUNET_MQ_msg (m, GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS); - m->strength = htonl (sh->strength); + ev = GNUNET_MQ_msg(m, GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS); + m->strength = htonl(sh->strength); m->peer = *peer; - GNUNET_MQ_send (ch->mq, ev); + GNUNET_MQ_send(ch->mq, ev); return GNUNET_OK; } @@ -187,33 +184,33 @@ transmit_suggestion (void *cls, * @param ch handle to use to re-connect. */ static void -reconnect (struct GNUNET_ATS_ConnectivityHandle *ch) +reconnect(struct GNUNET_ATS_ConnectivityHandle *ch) { static const struct GNUNET_MQ_MessageHandler handlers[] = - { { NULL, 0, 0 } }; + { { NULL, 0, 0 } }; struct GNUNET_MQ_Envelope *ev; struct ClientStartMessage *init; - GNUNET_assert (NULL == ch->mq); - ch->mq = GNUNET_CLIENT_connect (ch->cfg, - "ats", - handlers, - &error_handler, - ch); + GNUNET_assert(NULL == ch->mq); + ch->mq = GNUNET_CLIENT_connect(ch->cfg, + "ats", + handlers, + &error_handler, + ch); if (NULL == ch->mq) - { - force_reconnect (ch); - return; - } - ev = GNUNET_MQ_msg (init, - GNUNET_MESSAGE_TYPE_ATS_START); - init->start_flag = htonl (START_FLAG_CONNECTION_SUGGESTION); - GNUNET_MQ_send (ch->mq, ev); + { + force_reconnect(ch); + return; + } + ev = GNUNET_MQ_msg(init, + GNUNET_MESSAGE_TYPE_ATS_START); + init->start_flag = htonl(START_FLAG_CONNECTION_SUGGESTION); + GNUNET_MQ_send(ch->mq, ev); if (NULL == ch->mq) return; - GNUNET_CONTAINER_multipeermap_iterate (ch->sug_requests, - &transmit_suggestion, - ch); + GNUNET_CONTAINER_multipeermap_iterate(ch->sug_requests, + &transmit_suggestion, + ch); } @@ -224,15 +221,15 @@ reconnect (struct GNUNET_ATS_ConnectivityHandle *ch) * @return ats connectivity handle, NULL on error */ struct GNUNET_ATS_ConnectivityHandle * -GNUNET_ATS_connectivity_init (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_ATS_connectivity_init(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_ATS_ConnectivityHandle *ch; - ch = GNUNET_new (struct GNUNET_ATS_ConnectivityHandle); + ch = GNUNET_new(struct GNUNET_ATS_ConnectivityHandle); ch->cfg = cfg; - ch->sug_requests = GNUNET_CONTAINER_multipeermap_create (32, - GNUNET_YES); - reconnect (ch); + ch->sug_requests = GNUNET_CONTAINER_multipeermap_create(32, + GNUNET_YES); + reconnect(ch); return ch; } @@ -247,13 +244,13 @@ GNUNET_ATS_connectivity_init (const struct GNUNET_CONFIGURATION_Handle *cfg) * @return #GNUNET_OK (continue to iterate) */ static int -free_sug_handle (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +free_sug_handle(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct GNUNET_ATS_ConnectivitySuggestHandle *cur = value; - GNUNET_free (cur); + GNUNET_free(cur); return GNUNET_OK; } @@ -264,23 +261,23 @@ free_sug_handle (void *cls, * @param ch handle to release */ void -GNUNET_ATS_connectivity_done (struct GNUNET_ATS_ConnectivityHandle *ch) +GNUNET_ATS_connectivity_done(struct GNUNET_ATS_ConnectivityHandle *ch) { if (NULL != ch->mq) - { - GNUNET_MQ_destroy (ch->mq); - ch->mq = NULL; - } + { + GNUNET_MQ_destroy(ch->mq); + ch->mq = NULL; + } if (NULL != ch->task) - { - GNUNET_SCHEDULER_cancel (ch->task); - ch->task = NULL; - } - GNUNET_CONTAINER_multipeermap_iterate (ch->sug_requests, - &free_sug_handle, - NULL); - GNUNET_CONTAINER_multipeermap_destroy (ch->sug_requests); - GNUNET_free (ch); + { + GNUNET_SCHEDULER_cancel(ch->task); + ch->task = NULL; + } + GNUNET_CONTAINER_multipeermap_iterate(ch->sug_requests, + &free_sug_handle, + NULL); + GNUNET_CONTAINER_multipeermap_destroy(ch->sug_requests); + GNUNET_free(ch); } @@ -296,36 +293,36 @@ GNUNET_ATS_connectivity_done (struct GNUNET_ATS_ConnectivityHandle *ch) * @return suggest handle, NULL if a request is already pending */ struct GNUNET_ATS_ConnectivitySuggestHandle * -GNUNET_ATS_connectivity_suggest (struct GNUNET_ATS_ConnectivityHandle *ch, - const struct GNUNET_PeerIdentity *peer, - uint32_t strength) +GNUNET_ATS_connectivity_suggest(struct GNUNET_ATS_ConnectivityHandle *ch, + const struct GNUNET_PeerIdentity *peer, + uint32_t strength) { struct GNUNET_ATS_ConnectivitySuggestHandle *s; - s = GNUNET_new (struct GNUNET_ATS_ConnectivitySuggestHandle); + s = GNUNET_new(struct GNUNET_ATS_ConnectivitySuggestHandle); s->ch = ch; s->id = *peer; s->strength = strength; if (GNUNET_OK != - GNUNET_CONTAINER_multipeermap_put (ch->sug_requests, - &s->id, - s, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Not requesting ATS to suggest address for `%s', request already pending\n", - GNUNET_i2s (peer)); - GNUNET_free (s); - return NULL; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Requesting ATS to suggest address for `%s'\n", - GNUNET_i2s (peer)); + GNUNET_CONTAINER_multipeermap_put(ch->sug_requests, + &s->id, + s, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Not requesting ATS to suggest address for `%s', request already pending\n", + GNUNET_i2s(peer)); + GNUNET_free(s); + return NULL; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Requesting ATS to suggest address for `%s'\n", + GNUNET_i2s(peer)); if (NULL == ch->mq) return s; - (void) transmit_suggestion (ch, - &s->id, - s); + (void)transmit_suggestion(ch, + &s->id, + s); return s; } @@ -336,30 +333,30 @@ GNUNET_ATS_connectivity_suggest (struct GNUNET_ATS_ConnectivityHandle *ch, * @param sh handle to stop */ void -GNUNET_ATS_connectivity_suggest_cancel (struct GNUNET_ATS_ConnectivitySuggestHandle *sh) +GNUNET_ATS_connectivity_suggest_cancel(struct GNUNET_ATS_ConnectivitySuggestHandle *sh) { struct GNUNET_ATS_ConnectivityHandle *ch = sh->ch; struct GNUNET_MQ_Envelope *ev; struct RequestAddressMessage *m; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Telling ATS we no longer care for an address for `%s'\n", - GNUNET_i2s (&sh->id)); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_remove (ch->sug_requests, - &sh->id, - sh)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Telling ATS we no longer care for an address for `%s'\n", + GNUNET_i2s(&sh->id)); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_remove(ch->sug_requests, + &sh->id, + sh)); if (NULL == ch->mq) - { - GNUNET_free (sh); - return; - } - ev = GNUNET_MQ_msg (m, - GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS_CANCEL); - m->strength = htonl (0); + { + GNUNET_free(sh); + return; + } + ev = GNUNET_MQ_msg(m, + GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS_CANCEL); + m->strength = htonl(0); m->peer = sh->id; - GNUNET_MQ_send (ch->mq, ev); - GNUNET_free (sh); + GNUNET_MQ_send(ch->mq, ev); + GNUNET_free(sh); } diff --git a/src/ats/ats_api_performance.c b/src/ats/ats_api_performance.c index 0954c02d5..b30093f4c 100644 --- a/src/ats/ats_api_performance.c +++ b/src/ats/ats_api_performance.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010, 2011, 2016 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010, 2011, 2016 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -28,15 +28,13 @@ #include "ats.h" -#define LOG(kind,...) GNUNET_log_from(kind, "ats-performance-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "ats-performance-api", __VA_ARGS__) /** * Linked list of pending reservations. */ -struct GNUNET_ATS_ReservationContext -{ - +struct GNUNET_ATS_ReservationContext { /** * Kept in a DLL. */ @@ -82,9 +80,7 @@ struct GNUNET_ATS_ReservationContext /** * Linked list of pending reservations. */ -struct GNUNET_ATS_AddressListHandle -{ - +struct GNUNET_ATS_AddressListHandle { /** * Kept in a DLL. */ @@ -135,9 +131,7 @@ struct GNUNET_ATS_AddressListHandle /** * ATS Handle to obtain and/or modify performance information. */ -struct GNUNET_ATS_PerformanceHandle -{ - +struct GNUNET_ATS_PerformanceHandle { /** * Our configuration. */ @@ -215,7 +209,7 @@ struct GNUNET_ATS_PerformanceHandle * @param ph handle to use to re-connect. */ static void -reconnect (struct GNUNET_ATS_PerformanceHandle *ph); +reconnect(struct GNUNET_ATS_PerformanceHandle *ph); /** @@ -224,12 +218,12 @@ reconnect (struct GNUNET_ATS_PerformanceHandle *ph); * @param cls handle to use to re-connect. */ static void -reconnect_task (void *cls) +reconnect_task(void *cls) { struct GNUNET_ATS_PerformanceHandle *ph = cls; ph->task = NULL; - reconnect (ph); + reconnect(ph); } @@ -239,58 +233,58 @@ reconnect_task (void *cls) * @param ph handle to reconnect */ static void -do_reconnect (struct GNUNET_ATS_PerformanceHandle *ph) +do_reconnect(struct GNUNET_ATS_PerformanceHandle *ph) { struct GNUNET_ATS_ReservationContext *rc; struct GNUNET_ATS_AddressListHandle *alh; struct GNUNET_BANDWIDTH_Value32NBO bandwidth_zero; if (NULL != ph->mq) - { - GNUNET_MQ_destroy (ph->mq); - ph->mq = NULL; - } + { + GNUNET_MQ_destroy(ph->mq); + ph->mq = NULL; + } while (NULL != (rc = ph->reservation_head)) - { - GNUNET_CONTAINER_DLL_remove (ph->reservation_head, - ph->reservation_tail, - rc); - if (NULL != rc->rcb) - rc->rcb (rc->rcb_cls, - NULL, - 0, - GNUNET_TIME_UNIT_FOREVER_REL); - GNUNET_free (rc); - } - bandwidth_zero.value__ = htonl (0); + { + GNUNET_CONTAINER_DLL_remove(ph->reservation_head, + ph->reservation_tail, + rc); + if (NULL != rc->rcb) + rc->rcb(rc->rcb_cls, + NULL, + 0, + GNUNET_TIME_UNIT_FOREVER_REL); + GNUNET_free(rc); + } + bandwidth_zero.value__ = htonl(0); while (NULL != (alh = ph->addresslist_head)) - { - GNUNET_CONTAINER_DLL_remove (ph->addresslist_head, - ph->addresslist_tail, - alh); - if (NULL != alh->cb) - alh->cb (alh->cb_cls, - NULL, - GNUNET_NO, - bandwidth_zero, - bandwidth_zero, - NULL); - GNUNET_free (alh); - } + { + GNUNET_CONTAINER_DLL_remove(ph->addresslist_head, + ph->addresslist_tail, + alh); + if (NULL != alh->cb) + alh->cb(alh->cb_cls, + NULL, + GNUNET_NO, + bandwidth_zero, + bandwidth_zero, + NULL); + GNUNET_free(alh); + } if (NULL != ph->addr_info_cb) - { - /* Indicate reconnect */ - ph->addr_info_cb (ph->addr_info_cb_cls, - NULL, - GNUNET_NO, - bandwidth_zero, - bandwidth_zero, - NULL); - } - ph->backoff = GNUNET_TIME_STD_BACKOFF (ph->backoff); - ph->task = GNUNET_SCHEDULER_add_delayed (ph->backoff, - &reconnect_task, - ph); + { + /* Indicate reconnect */ + ph->addr_info_cb(ph->addr_info_cb_cls, + NULL, + GNUNET_NO, + bandwidth_zero, + bandwidth_zero, + NULL); + } + ph->backoff = GNUNET_TIME_STD_BACKOFF(ph->backoff); + ph->task = GNUNET_SCHEDULER_add_delayed(ph->backoff, + &reconnect_task, + ph); } @@ -302,25 +296,25 @@ do_reconnect (struct GNUNET_ATS_PerformanceHandle *ph) * @return #GNUNET_OK if the message was well-formed */ static int -check_peer_information (void *cls, - const struct PeerInformationMessage *pi) +check_peer_information(void *cls, + const struct PeerInformationMessage *pi) { const char *plugin_address; const char *plugin_name; uint16_t plugin_address_length; uint16_t plugin_name_length; - plugin_address_length = ntohs (pi->address_length); - plugin_name_length = ntohs (pi->plugin_name_length); - plugin_address = (const char *) &pi[1]; + plugin_address_length = ntohs(pi->address_length); + plugin_name_length = ntohs(pi->plugin_name_length); + plugin_address = (const char *)&pi[1]; plugin_name = &plugin_address[plugin_address_length]; - if ( (plugin_address_length + plugin_name_length - + sizeof(struct PeerInformationMessage) != ntohs (pi->header.size)) || - (plugin_name[plugin_name_length - 1] != '\0')) - { - GNUNET_break(0); - return GNUNET_SYSERR; - } + if ((plugin_address_length + plugin_name_length + + sizeof(struct PeerInformationMessage) != ntohs(pi->header.size)) || + (plugin_name[plugin_name_length - 1] != '\0')) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -333,8 +327,8 @@ check_peer_information (void *cls, * @return #GNUNET_OK if the message was well-formed */ static void -handle_peer_information (void *cls, - const struct PeerInformationMessage *pi) +handle_peer_information(void *cls, + const struct PeerInformationMessage *pi) { struct GNUNET_ATS_PerformanceHandle *ph = cls; const char *plugin_address; @@ -346,24 +340,24 @@ handle_peer_information (void *cls, if (NULL == ph->addr_info_cb) return; - plugin_address_length = ntohs (pi->address_length); - addr_active = (int) ntohl (pi->address_active); - plugin_address = (const char *) &pi[1]; + plugin_address_length = ntohs(pi->address_length); + addr_active = (int)ntohl(pi->address_active); + plugin_address = (const char *)&pi[1]; plugin_name = &plugin_address[plugin_address_length]; - GNUNET_ATS_properties_ntoh (&prop, - &pi->properties); + GNUNET_ATS_properties_ntoh(&prop, + &pi->properties); address.peer = pi->peer; - address.local_info = (enum GNUNET_HELLO_AddressInfo) ntohl (pi->address_local_info); + address.local_info = (enum GNUNET_HELLO_AddressInfo)ntohl(pi->address_local_info); address.address = plugin_address; address.address_length = plugin_address_length; address.transport_name = plugin_name; - ph->addr_info_cb (ph->addr_info_cb_cls, - &address, - addr_active, - pi->bandwidth_out, - pi->bandwidth_in, - &prop); + ph->addr_info_cb(ph->addr_info_cb_cls, + &address, + addr_active, + pi->bandwidth_out, + pi->bandwidth_in, + &prop); } @@ -374,48 +368,48 @@ handle_peer_information (void *cls, * @param rr the message */ static void -handle_reservation_result (void *cls, - const struct ReservationResultMessage *rr) +handle_reservation_result(void *cls, + const struct ReservationResultMessage *rr) { struct GNUNET_ATS_PerformanceHandle *ph = cls; struct GNUNET_ATS_ReservationContext *rc; int32_t amount; - amount = ntohl (rr->amount); + amount = ntohl(rr->amount); rc = ph->reservation_head; - if (0 != GNUNET_memcmp (&rr->peer, - &rc->peer)) - { - GNUNET_break(0); - reconnect (ph); - return; - } - GNUNET_CONTAINER_DLL_remove (ph->reservation_head, - ph->reservation_tail, - rc); - if ( (0 == amount) || - (NULL != rc->rcb) ) - { - /* tell client if not cancelled */ - if (NULL != rc->rcb) - rc->rcb (rc->rcb_cls, - &rr->peer, - amount, - GNUNET_TIME_relative_ntoh (rr->res_delay)); - GNUNET_free (rc); - return; - } + if (0 != GNUNET_memcmp(&rr->peer, + &rc->peer)) + { + GNUNET_break(0); + reconnect(ph); + return; + } + GNUNET_CONTAINER_DLL_remove(ph->reservation_head, + ph->reservation_tail, + rc); + if ((0 == amount) || + (NULL != rc->rcb)) + { + /* tell client if not cancelled */ + if (NULL != rc->rcb) + rc->rcb(rc->rcb_cls, + &rr->peer, + amount, + GNUNET_TIME_relative_ntoh(rr->res_delay)); + GNUNET_free(rc); + return; + } /* amount non-zero, but client cancelled, consider undo! */ if (GNUNET_YES != rc->undo) - { - GNUNET_free (rc); - return; /* do not try to undo failed undos or negative amounts */ - } - GNUNET_free (rc); - (void) GNUNET_ATS_reserve_bandwidth (ph, - &rr->peer, - -amount, - NULL, NULL); + { + GNUNET_free(rc); + return; /* do not try to undo failed undos or negative amounts */ + } + GNUNET_free(rc); + (void)GNUNET_ATS_reserve_bandwidth(ph, + &rr->peer, + -amount, + NULL, NULL); } @@ -427,25 +421,25 @@ handle_reservation_result (void *cls, * @return #GNUNET_OK if the message was well-formed */ static int -check_address_list (void *cls, - const struct PeerInformationMessage *pi) +check_address_list(void *cls, + const struct PeerInformationMessage *pi) { const char *plugin_address; const char *plugin_name; uint16_t plugin_address_length; uint16_t plugin_name_length; - plugin_address_length = ntohs (pi->address_length); - plugin_name_length = ntohs (pi->plugin_name_length); - plugin_address = (const char *) &pi[1]; + plugin_address_length = ntohs(pi->address_length); + plugin_name_length = ntohs(pi->plugin_name_length); + plugin_address = (const char *)&pi[1]; plugin_name = &plugin_address[plugin_address_length]; - if ( (plugin_address_length + plugin_name_length - + sizeof (struct PeerInformationMessage) != ntohs (pi->header.size)) || - (plugin_name[plugin_name_length - 1] != '\0') ) - { - GNUNET_break(0); - return GNUNET_SYSERR; - } + if ((plugin_address_length + plugin_name_length + + sizeof(struct PeerInformationMessage) != ntohs(pi->header.size)) || + (plugin_name[plugin_name_length - 1] != '\0')) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -458,8 +452,8 @@ check_address_list (void *cls, * @param pi the message */ static void -handle_address_list (void *cls, - const struct PeerInformationMessage *pi) +handle_address_list(void *cls, + const struct PeerInformationMessage *pi) { struct GNUNET_ATS_PerformanceHandle *ph = cls; struct GNUNET_ATS_AddressListHandle *alh; @@ -475,67 +469,67 @@ handle_address_list (void *cls, uint32_t active; uint32_t id; - id = ntohl (pi->id); - active = ntohl (pi->address_active); - plugin_address_length = ntohs (pi->address_length); - plugin_name_length = ntohs (pi->plugin_name_length); - plugin_address = (const char *) &pi[1]; + id = ntohl(pi->id); + active = ntohl(pi->address_active); + plugin_address_length = ntohs(pi->address_length); + plugin_name_length = ntohs(pi->plugin_name_length); + plugin_address = (const char *)&pi[1]; plugin_name = &plugin_address[plugin_address_length]; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received ATS_ADDRESSLIST_RESPONSE message for peer %s and plugin %s\n", - GNUNET_i2s (&pi->peer), - plugin_name); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received ATS_ADDRESSLIST_RESPONSE message for peer %s and plugin %s\n", + GNUNET_i2s(&pi->peer), + plugin_name); next = ph->addresslist_head; while (NULL != (alh = next)) - { - next = alh->next; - if (alh->id == id) - break; - } + { + next = alh->next; + if (alh->id == id) + break; + } if (NULL == alh) return; /* was canceled */ - memset (&allzeros, '\0', sizeof (allzeros)); - if ( (0 == GNUNET_is_zero (&pi->peer)) && - (0 == plugin_name_length) && - (0 == plugin_address_length) ) - { - /* Done */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received last message for ATS_ADDRESSLIST_RESPONSE\n"); - bandwidth_zero.value__ = htonl (0); - GNUNET_CONTAINER_DLL_remove (ph->addresslist_head, - ph->addresslist_tail, - alh); - if (NULL != alh->cb) - alh->cb (alh->cb_cls, - NULL, - GNUNET_NO, - bandwidth_zero, - bandwidth_zero, - NULL); - GNUNET_free (alh); - return; - } + memset(&allzeros, '\0', sizeof(allzeros)); + if ((0 == GNUNET_is_zero(&pi->peer)) && + (0 == plugin_name_length) && + (0 == plugin_address_length)) + { + /* Done */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received last message for ATS_ADDRESSLIST_RESPONSE\n"); + bandwidth_zero.value__ = htonl(0); + GNUNET_CONTAINER_DLL_remove(ph->addresslist_head, + ph->addresslist_tail, + alh); + if (NULL != alh->cb) + alh->cb(alh->cb_cls, + NULL, + GNUNET_NO, + bandwidth_zero, + bandwidth_zero, + NULL); + GNUNET_free(alh); + return; + } address.peer = pi->peer; address.address = plugin_address; address.address_length = plugin_address_length; address.transport_name = plugin_name; - if ( ( (GNUNET_YES == alh->all_addresses) || - (GNUNET_YES == active) ) && - (NULL != alh->cb) ) - { - GNUNET_ATS_properties_ntoh (&prop, - &pi->properties); - alh->cb (alh->cb_cls, - &address, - active, - pi->bandwidth_out, - pi->bandwidth_in, - &prop); - } + if (((GNUNET_YES == alh->all_addresses) || + (GNUNET_YES == active)) && + (NULL != alh->cb)) + { + GNUNET_ATS_properties_ntoh(&prop, + &pi->properties); + alh->cb(alh->cb_cls, + &address, + active, + pi->bandwidth_out, + pi->bandwidth_in, + &prop); + } } @@ -548,12 +542,12 @@ handle_address_list (void *cls, * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_ATS_PerformanceHandle *ph = cls; - do_reconnect (ph); + do_reconnect(ph); } @@ -563,41 +557,41 @@ mq_error_handler (void *cls, * @param ph handle to use to re-connect. */ static void -reconnect (struct GNUNET_ATS_PerformanceHandle *ph) +reconnect(struct GNUNET_ATS_PerformanceHandle *ph) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (peer_information, - GNUNET_MESSAGE_TYPE_ATS_PEER_INFORMATION, - struct PeerInformationMessage, - ph), - GNUNET_MQ_hd_fixed_size (reservation_result, - GNUNET_MESSAGE_TYPE_ATS_RESERVATION_RESULT, - struct ReservationResultMessage, - ph), - GNUNET_MQ_hd_var_size (address_list, - GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_RESPONSE, - struct PeerInformationMessage, - ph), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(peer_information, + GNUNET_MESSAGE_TYPE_ATS_PEER_INFORMATION, + struct PeerInformationMessage, + ph), + GNUNET_MQ_hd_fixed_size(reservation_result, + GNUNET_MESSAGE_TYPE_ATS_RESERVATION_RESULT, + struct ReservationResultMessage, + ph), + GNUNET_MQ_hd_var_size(address_list, + GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_RESPONSE, + struct PeerInformationMessage, + ph), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *env; struct ClientStartMessage *init; - GNUNET_assert (NULL == ph->mq); - ph->mq = GNUNET_CLIENT_connect (ph->cfg, - "ats", - handlers, - &mq_error_handler, - ph); + GNUNET_assert(NULL == ph->mq); + ph->mq = GNUNET_CLIENT_connect(ph->cfg, + "ats", + handlers, + &mq_error_handler, + ph); if (NULL == ph->mq) return; - env = GNUNET_MQ_msg (init, - GNUNET_MESSAGE_TYPE_ATS_START); - init->start_flag = htonl ( (NULL == ph->addr_info_cb) - ? START_FLAG_PERFORMANCE_NO_PIC - : START_FLAG_PERFORMANCE_WITH_PIC); - GNUNET_MQ_send (ph->mq, - env); + env = GNUNET_MQ_msg(init, + GNUNET_MESSAGE_TYPE_ATS_START); + init->start_flag = htonl((NULL == ph->addr_info_cb) + ? START_FLAG_PERFORMANCE_NO_PIC + : START_FLAG_PERFORMANCE_WITH_PIC); + GNUNET_MQ_send(ph->mq, + env); } @@ -606,27 +600,27 @@ reconnect (struct GNUNET_ATS_PerformanceHandle *ph) * * @param cfg configuration to use * @param addr_info_cb callback called when performance characteristics for - * an address change + * an address change * @param addr_info_cb_cls closure for @a addr_info_cb * @return ats performance context */ struct GNUNET_ATS_PerformanceHandle * -GNUNET_ATS_performance_init (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_ATS_AddressInformationCallback addr_info_cb, - void *addr_info_cb_cls) +GNUNET_ATS_performance_init(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_ATS_AddressInformationCallback addr_info_cb, + void *addr_info_cb_cls) { struct GNUNET_ATS_PerformanceHandle *ph; - ph = GNUNET_new (struct GNUNET_ATS_PerformanceHandle); + ph = GNUNET_new(struct GNUNET_ATS_PerformanceHandle); ph->cfg = cfg; ph->addr_info_cb = addr_info_cb; ph->addr_info_cb_cls = addr_info_cb_cls; - reconnect (ph); + reconnect(ph); if (NULL == ph->mq) - { - GNUNET_free (ph); - return NULL; - } + { + GNUNET_free(ph); + return NULL; + } return ph; } @@ -637,37 +631,37 @@ GNUNET_ATS_performance_init (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param ph handle */ void -GNUNET_ATS_performance_done (struct GNUNET_ATS_PerformanceHandle *ph) +GNUNET_ATS_performance_done(struct GNUNET_ATS_PerformanceHandle *ph) { struct GNUNET_ATS_ReservationContext *rc; struct GNUNET_ATS_AddressListHandle *alh; while (NULL != (alh = ph->addresslist_head)) - { - GNUNET_CONTAINER_DLL_remove (ph->addresslist_head, - ph->addresslist_tail, - alh); - GNUNET_free (alh); - } + { + GNUNET_CONTAINER_DLL_remove(ph->addresslist_head, + ph->addresslist_tail, + alh); + GNUNET_free(alh); + } while (NULL != (rc = ph->reservation_head)) - { - GNUNET_CONTAINER_DLL_remove (ph->reservation_head, - ph->reservation_tail, - rc); - GNUNET_break (NULL == rc->rcb); - GNUNET_free (rc); - } + { + GNUNET_CONTAINER_DLL_remove(ph->reservation_head, + ph->reservation_tail, + rc); + GNUNET_break(NULL == rc->rcb); + GNUNET_free(rc); + } if (NULL != ph->task) - { - GNUNET_SCHEDULER_cancel (ph->task); - ph->task = NULL; - } + { + GNUNET_SCHEDULER_cancel(ph->task); + ph->task = NULL; + } if (NULL != ph->mq) - { - GNUNET_MQ_destroy (ph->mq); - ph->mq = NULL; - } - GNUNET_free (ph); + { + GNUNET_MQ_destroy(ph->mq); + ph->mq = NULL; + } + GNUNET_free(ph); } @@ -686,11 +680,11 @@ GNUNET_ATS_performance_done (struct GNUNET_ATS_PerformanceHandle *ph) * @deprecated will be replaced soon */ struct GNUNET_ATS_ReservationContext * -GNUNET_ATS_reserve_bandwidth (struct GNUNET_ATS_PerformanceHandle *ph, - const struct GNUNET_PeerIdentity *peer, - int32_t amount, - GNUNET_ATS_ReservationCallback rcb, - void *rcb_cls) +GNUNET_ATS_reserve_bandwidth(struct GNUNET_ATS_PerformanceHandle *ph, + const struct GNUNET_PeerIdentity *peer, + int32_t amount, + GNUNET_ATS_ReservationCallback rcb, + void *rcb_cls) { struct GNUNET_ATS_ReservationContext *rc; struct GNUNET_MQ_Envelope *env; @@ -698,23 +692,23 @@ GNUNET_ATS_reserve_bandwidth (struct GNUNET_ATS_PerformanceHandle *ph, if (NULL == ph->mq) return NULL; - rc = GNUNET_new (struct GNUNET_ATS_ReservationContext); + rc = GNUNET_new(struct GNUNET_ATS_ReservationContext); rc->size = amount; rc->peer = *peer; rc->rcb = rcb; rc->rcb_cls = rcb_cls; - if ( (NULL != rcb) && - (amount > 0) ) + if ((NULL != rcb) && + (amount > 0)) rc->undo = GNUNET_YES; - GNUNET_CONTAINER_DLL_insert_tail (ph->reservation_head, - ph->reservation_tail, - rc); - env = GNUNET_MQ_msg (m, - GNUNET_MESSAGE_TYPE_ATS_RESERVATION_REQUEST); - m->amount = htonl (amount); + GNUNET_CONTAINER_DLL_insert_tail(ph->reservation_head, + ph->reservation_tail, + rc); + env = GNUNET_MQ_msg(m, + GNUNET_MESSAGE_TYPE_ATS_RESERVATION_REQUEST); + m->amount = htonl(amount); m->peer = *peer; - GNUNET_MQ_send (ph->mq, - env); + GNUNET_MQ_send(ph->mq, + env); return rc; } @@ -725,7 +719,7 @@ GNUNET_ATS_reserve_bandwidth (struct GNUNET_ATS_PerformanceHandle *ph, * @param rc context returned by the original #GNUNET_ATS_reserve_bandwidth() call */ void -GNUNET_ATS_reserve_bandwidth_cancel (struct GNUNET_ATS_ReservationContext *rc) +GNUNET_ATS_reserve_bandwidth_cancel(struct GNUNET_ATS_ReservationContext *rc) { rc->rcb = NULL; } @@ -744,11 +738,11 @@ GNUNET_ATS_reserve_bandwidth_cancel (struct GNUNET_ATS_ReservationContext *rc) * @return ats performance context */ struct GNUNET_ATS_AddressListHandle* -GNUNET_ATS_performance_list_addresses (struct GNUNET_ATS_PerformanceHandle *ph, - const struct GNUNET_PeerIdentity *peer, - int all, - GNUNET_ATS_AddressInformationCallback infocb, - void *infocb_cls) +GNUNET_ATS_performance_list_addresses(struct GNUNET_ATS_PerformanceHandle *ph, + const struct GNUNET_PeerIdentity *peer, + int all, + GNUNET_ATS_AddressInformationCallback infocb, + void *infocb_cls) { struct GNUNET_ATS_AddressListHandle *alh; struct GNUNET_MQ_Envelope *env; @@ -757,36 +751,36 @@ GNUNET_ATS_performance_list_addresses (struct GNUNET_ATS_PerformanceHandle *ph, if (NULL == ph->mq) return NULL; if (NULL == infocb) - { - GNUNET_break (0); - return NULL; - } - alh = GNUNET_new (struct GNUNET_ATS_AddressListHandle); + { + GNUNET_break(0); + return NULL; + } + alh = GNUNET_new(struct GNUNET_ATS_AddressListHandle); alh->id = ph->id++; alh->cb = infocb; alh->cb_cls = infocb_cls; alh->ph = ph; alh->all_addresses = all; if (NULL == peer) - { - alh->all_peers = GNUNET_YES; - } + { + alh->all_peers = GNUNET_YES; + } else - { - alh->all_peers = GNUNET_NO; - alh->peer = *peer; - } - GNUNET_CONTAINER_DLL_insert (ph->addresslist_head, - ph->addresslist_tail, - alh); - env = GNUNET_MQ_msg (m, - GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_REQUEST); - m->all = htonl (all); - m->id = htonl (alh->id); + { + alh->all_peers = GNUNET_NO; + alh->peer = *peer; + } + GNUNET_CONTAINER_DLL_insert(ph->addresslist_head, + ph->addresslist_tail, + alh); + env = GNUNET_MQ_msg(m, + GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_REQUEST); + m->all = htonl(all); + m->id = htonl(alh->id); if (NULL != peer) m->peer = *peer; - GNUNET_MQ_send (ph->mq, - env); + GNUNET_MQ_send(ph->mq, + env); return alh; } @@ -797,14 +791,14 @@ GNUNET_ATS_performance_list_addresses (struct GNUNET_ATS_PerformanceHandle *ph, * @param alh the handle of the request to cancel */ void -GNUNET_ATS_performance_list_addresses_cancel (struct GNUNET_ATS_AddressListHandle *alh) +GNUNET_ATS_performance_list_addresses_cancel(struct GNUNET_ATS_AddressListHandle *alh) { struct GNUNET_ATS_PerformanceHandle *ph = alh->ph; - GNUNET_CONTAINER_DLL_remove (ph->addresslist_head, - ph->addresslist_tail, - alh); - GNUNET_free (alh); + GNUNET_CONTAINER_DLL_remove(ph->addresslist_head, + ph->addresslist_tail, + alh); + GNUNET_free(alh); } @@ -815,7 +809,7 @@ GNUNET_ATS_performance_list_addresses_cancel (struct GNUNET_ATS_AddressListHandl * @return a string or NULL if invalid */ const char * -GNUNET_ATS_print_preference_type (enum GNUNET_ATS_PreferenceKind type) +GNUNET_ATS_print_preference_type(enum GNUNET_ATS_PreferenceKind type) { const char *prefs[] = GNUNET_ATS_PreferenceTypeString; @@ -834,9 +828,9 @@ GNUNET_ATS_print_preference_type (enum GNUNET_ATS_PreferenceKind type) * @param ... #GNUNET_ATS_PREFERENCE_END-terminated specification of the desired changes */ void -GNUNET_ATS_performance_change_preference (struct GNUNET_ATS_PerformanceHandle *ph, - const struct GNUNET_PeerIdentity *peer, - ...) +GNUNET_ATS_performance_change_preference(struct GNUNET_ATS_PerformanceHandle *ph, + const struct GNUNET_PeerIdentity *peer, + ...) { struct GNUNET_MQ_Envelope *env; struct ChangePreferenceMessage *m; @@ -850,54 +844,58 @@ GNUNET_ATS_performance_change_preference (struct GNUNET_ATS_PerformanceHandle *p count = 0; va_start(ap, peer); while (GNUNET_ATS_PREFERENCE_END != - (kind = GNUNET_VA_ARG_ENUM (ap, GNUNET_ATS_PreferenceKind) )) - { - switch (kind) + (kind = GNUNET_VA_ARG_ENUM(ap, GNUNET_ATS_PreferenceKind))) { - case GNUNET_ATS_PREFERENCE_BANDWIDTH: - count++; - (void) va_arg (ap, double); - break; - case GNUNET_ATS_PREFERENCE_LATENCY: - count++; - (void) va_arg (ap, double); - break; - default: - GNUNET_assert(0); + switch (kind) + { + case GNUNET_ATS_PREFERENCE_BANDWIDTH: + count++; + (void)va_arg(ap, double); + break; + + case GNUNET_ATS_PREFERENCE_LATENCY: + count++; + (void)va_arg(ap, double); + break; + + default: + GNUNET_assert(0); + } } - } va_end(ap); - env = GNUNET_MQ_msg_extra (m, - count * sizeof(struct PreferenceInformation), - GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_CHANGE); - m->num_preferences = htonl (count); + env = GNUNET_MQ_msg_extra(m, + count * sizeof(struct PreferenceInformation), + GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_CHANGE); + m->num_preferences = htonl(count); m->peer = *peer; - pi = (struct PreferenceInformation *) &m[1]; + pi = (struct PreferenceInformation *)&m[1]; count = 0; va_start(ap, peer); while (GNUNET_ATS_PREFERENCE_END != (kind = - GNUNET_VA_ARG_ENUM (ap, GNUNET_ATS_PreferenceKind) )) - { - pi[count].preference_kind = htonl (kind); - switch (kind) + GNUNET_VA_ARG_ENUM(ap, GNUNET_ATS_PreferenceKind))) { - case GNUNET_ATS_PREFERENCE_BANDWIDTH: - pi[count].preference_value = (float) va_arg (ap, double); - - count++; - break; - case GNUNET_ATS_PREFERENCE_LATENCY: - pi[count].preference_value = (float) va_arg (ap, double); - - count++; - break; - default: - GNUNET_assert(0); + pi[count].preference_kind = htonl(kind); + switch (kind) + { + case GNUNET_ATS_PREFERENCE_BANDWIDTH: + pi[count].preference_value = (float)va_arg(ap, double); + + count++; + break; + + case GNUNET_ATS_PREFERENCE_LATENCY: + pi[count].preference_value = (float)va_arg(ap, double); + + count++; + break; + + default: + GNUNET_assert(0); + } } - } va_end(ap); - GNUNET_MQ_send (ph->mq, - env); + GNUNET_MQ_send(ph->mq, + env); } @@ -911,10 +909,10 @@ GNUNET_ATS_performance_change_preference (struct GNUNET_ATS_PerformanceHandle *p * @param ... #GNUNET_ATS_PREFERENCE_END-terminated specification of the desired changes */ void -GNUNET_ATS_performance_give_feedback (struct GNUNET_ATS_PerformanceHandle *ph, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_TIME_Relative scope, - ...) +GNUNET_ATS_performance_give_feedback(struct GNUNET_ATS_PerformanceHandle *ph, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_TIME_Relative scope, + ...) { struct GNUNET_MQ_Envelope *env; struct FeedbackPreferenceMessage *m; @@ -928,55 +926,59 @@ GNUNET_ATS_performance_give_feedback (struct GNUNET_ATS_PerformanceHandle *ph, count = 0; va_start(ap, scope); while (GNUNET_ATS_PREFERENCE_END != - (kind = GNUNET_VA_ARG_ENUM (ap, GNUNET_ATS_PreferenceKind) )) - { - switch (kind) + (kind = GNUNET_VA_ARG_ENUM(ap, GNUNET_ATS_PreferenceKind))) { - case GNUNET_ATS_PREFERENCE_BANDWIDTH: - count++; - (void) va_arg (ap, double); - break; - case GNUNET_ATS_PREFERENCE_LATENCY: - count++; - (void) va_arg (ap, double); - break; - default: - GNUNET_assert(0); + switch (kind) + { + case GNUNET_ATS_PREFERENCE_BANDWIDTH: + count++; + (void)va_arg(ap, double); + break; + + case GNUNET_ATS_PREFERENCE_LATENCY: + count++; + (void)va_arg(ap, double); + break; + + default: + GNUNET_assert(0); + } } - } va_end(ap); - env = GNUNET_MQ_msg_extra (m, - count * sizeof(struct PreferenceInformation), - GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_FEEDBACK); - m->scope = GNUNET_TIME_relative_hton (scope); - m->num_feedback = htonl (count); + env = GNUNET_MQ_msg_extra(m, + count * sizeof(struct PreferenceInformation), + GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_FEEDBACK); + m->scope = GNUNET_TIME_relative_hton(scope); + m->num_feedback = htonl(count); m->peer = *peer; - pi = (struct PreferenceInformation *) &m[1]; + pi = (struct PreferenceInformation *)&m[1]; count = 0; va_start(ap, scope); while (GNUNET_ATS_PREFERENCE_END != (kind = - GNUNET_VA_ARG_ENUM (ap, GNUNET_ATS_PreferenceKind) )) - { - pi[count].preference_kind = htonl (kind); - switch (kind) + GNUNET_VA_ARG_ENUM(ap, GNUNET_ATS_PreferenceKind))) { - case GNUNET_ATS_PREFERENCE_BANDWIDTH: - pi[count].preference_value = (float) va_arg (ap, double); - - count++; - break; - case GNUNET_ATS_PREFERENCE_LATENCY: - pi[count].preference_value = (float) va_arg (ap, double); - - count++; - break; - default: - GNUNET_assert(0); + pi[count].preference_kind = htonl(kind); + switch (kind) + { + case GNUNET_ATS_PREFERENCE_BANDWIDTH: + pi[count].preference_value = (float)va_arg(ap, double); + + count++; + break; + + case GNUNET_ATS_PREFERENCE_LATENCY: + pi[count].preference_value = (float)va_arg(ap, double); + + count++; + break; + + default: + GNUNET_assert(0); + } } - } va_end(ap); - GNUNET_MQ_send (ph->mq, - env); + GNUNET_MQ_send(ph->mq, + env); } /* end of ats_api_performance.c */ diff --git a/src/ats/ats_api_scanner.c b/src/ats/ats_api_scanner.c index e23b4de8a..5c8ffe196 100644 --- a/src/ats/ats_api_scanner.c +++ b/src/ats/ats_api_scanner.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/ats_api_scanner.c * @brief LAN interface scanning to determine IPs in LAN @@ -33,14 +33,14 @@ * @param hbo value read */ void -GNUNET_ATS_properties_hton (struct GNUNET_ATS_PropertiesNBO *nbo, - const struct GNUNET_ATS_Properties *hbo) +GNUNET_ATS_properties_hton(struct GNUNET_ATS_PropertiesNBO *nbo, + const struct GNUNET_ATS_Properties *hbo) { - nbo->utilization_out = htonl (hbo->utilization_out); - nbo->utilization_in = htonl (hbo->utilization_in); - nbo->scope = htonl ((uint32_t) hbo->scope); - nbo->distance = htonl (hbo->distance); - nbo->delay = GNUNET_TIME_relative_hton (hbo->delay); + nbo->utilization_out = htonl(hbo->utilization_out); + nbo->utilization_in = htonl(hbo->utilization_in); + nbo->scope = htonl((uint32_t)hbo->scope); + nbo->distance = htonl(hbo->distance); + nbo->delay = GNUNET_TIME_relative_hton(hbo->delay); } @@ -51,14 +51,14 @@ GNUNET_ATS_properties_hton (struct GNUNET_ATS_PropertiesNBO *nbo, * @param nbo value read */ void -GNUNET_ATS_properties_ntoh (struct GNUNET_ATS_Properties *hbo, - const struct GNUNET_ATS_PropertiesNBO *nbo) +GNUNET_ATS_properties_ntoh(struct GNUNET_ATS_Properties *hbo, + const struct GNUNET_ATS_PropertiesNBO *nbo) { - hbo->utilization_out = ntohl (nbo->utilization_out); - hbo->utilization_in = ntohl (nbo->utilization_in); - hbo->scope = ntohl ((uint32_t) nbo->scope); - hbo->distance = ntohl (nbo->distance); - hbo->delay = GNUNET_TIME_relative_ntoh (nbo->delay); + hbo->utilization_out = ntohl(nbo->utilization_out); + hbo->utilization_in = ntohl(nbo->utilization_in); + hbo->scope = ntohl((uint32_t)nbo->scope); + hbo->distance = ntohl(nbo->distance); + hbo->delay = GNUNET_TIME_relative_ntoh(nbo->delay); } diff --git a/src/ats/ats_api_scheduling.c b/src/ats/ats_api_scheduling.c index 532426e91..f375be6a5 100644 --- a/src/ats/ats_api_scheduling.c +++ b/src/ats/ats_api_scheduling.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/ats_api_scheduling.c * @brief automatic transport selection and outbound bandwidth determination @@ -38,9 +38,9 @@ /** * How frequently do we scan the interfaces for changes to the addresses? */ -#define INTERFACE_PROCESSING_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2) +#define INTERFACE_PROCESSING_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2) -#define LOG(kind,...) GNUNET_log_from(kind, "ats-scheduling-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "ats-scheduling-api", __VA_ARGS__) /** * Session ID we use if there is no session / slot. @@ -53,9 +53,7 @@ * doesn't matter if we have a session, any address that ATS is * allowed to suggest right now should be tracked. */ -struct GNUNET_ATS_AddressRecord -{ - +struct GNUNET_ATS_AddressRecord { /** * Scheduling handle this address record belongs to. */ @@ -99,9 +97,7 @@ struct GNUNET_ATS_AddressRecord /** * Handle to the ATS subsystem for bandwidth/transport scheduling information. */ -struct GNUNET_ATS_SchedulingHandle -{ - +struct GNUNET_ATS_SchedulingHandle { /** * Our configuration. */ @@ -144,7 +140,6 @@ struct GNUNET_ATS_SchedulingHandle * Size of the @e session_array. */ unsigned int session_array_size; - }; @@ -154,7 +149,7 @@ struct GNUNET_ATS_SchedulingHandle * @param sh handle to use to re-connect. */ static void -reconnect (struct GNUNET_ATS_SchedulingHandle *sh); +reconnect(struct GNUNET_ATS_SchedulingHandle *sh); /** @@ -163,12 +158,12 @@ reconnect (struct GNUNET_ATS_SchedulingHandle *sh); * @param cls handle to use to re-connect. */ static void -reconnect_task (void *cls) +reconnect_task(void *cls) { struct GNUNET_ATS_SchedulingHandle *sh = cls; sh->task = NULL; - reconnect (sh); + reconnect(sh); } @@ -178,21 +173,21 @@ reconnect_task (void *cls) * @param sh our handle */ static void -force_reconnect (struct GNUNET_ATS_SchedulingHandle *sh) +force_reconnect(struct GNUNET_ATS_SchedulingHandle *sh) { if (NULL != sh->mq) - { - GNUNET_MQ_destroy (sh->mq); - sh->mq = NULL; - } - sh->suggest_cb (sh->suggest_cb_cls, - NULL, NULL, NULL, - GNUNET_BANDWIDTH_ZERO, - GNUNET_BANDWIDTH_ZERO); - sh->backoff = GNUNET_TIME_STD_BACKOFF (sh->backoff); - sh->task = GNUNET_SCHEDULER_add_delayed (sh->backoff, - &reconnect_task, - sh); + { + GNUNET_MQ_destroy(sh->mq); + sh->mq = NULL; + } + sh->suggest_cb(sh->suggest_cb_cls, + NULL, NULL, NULL, + GNUNET_BANDWIDTH_ZERO, + GNUNET_BANDWIDTH_ZERO); + sh->backoff = GNUNET_TIME_STD_BACKOFF(sh->backoff); + sh->task = GNUNET_SCHEDULER_add_delayed(sh->backoff, + &reconnect_task, + sh); } @@ -205,37 +200,37 @@ force_reconnect (struct GNUNET_ATS_SchedulingHandle *sh) * @return the session object (or NULL) */ static struct GNUNET_ATS_AddressRecord * -find_session (struct GNUNET_ATS_SchedulingHandle *sh, - uint32_t session_id, - const struct GNUNET_PeerIdentity *peer) +find_session(struct GNUNET_ATS_SchedulingHandle *sh, + uint32_t session_id, + const struct GNUNET_PeerIdentity *peer) { struct GNUNET_ATS_AddressRecord *ar; if (session_id >= sh->session_array_size) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } if (0 == session_id) return NULL; ar = sh->session_array[session_id]; if (NULL == ar) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } if (NULL == ar->address) - { - /* address was destroyed in the meantime, this can happen - as we communicate asynchronously with the ATS service. */ - return NULL; - } - if (0 != GNUNET_memcmp (peer, - &ar->address->peer)) - { - GNUNET_break (0); - return NULL; - } + { + /* address was destroyed in the meantime, this can happen + as we communicate asynchronously with the ATS service. */ + return NULL; + } + if (0 != GNUNET_memcmp(peer, + &ar->address->peer)) + { + GNUNET_break(0); + return NULL; + } return ar; } @@ -247,27 +242,27 @@ find_session (struct GNUNET_ATS_SchedulingHandle *sh, * @return an unused slot, but never NOT_FOUND (0) */ static uint32_t -find_empty_session_slot (struct GNUNET_ATS_SchedulingHandle *sh) +find_empty_session_slot(struct GNUNET_ATS_SchedulingHandle *sh) { static uint32_t off; uint32_t i; - GNUNET_assert (0 != sh->session_array_size); + GNUNET_assert(0 != sh->session_array_size); i = 0; - while ( ( (NOT_FOUND == off) || - (NULL != sh->session_array[off % sh->session_array_size]) ) && - (i < sh->session_array_size) ) - { - off++; - i++; - } - if ( (NOT_FOUND != off % sh->session_array_size) && - (NULL == sh->session_array[off % sh->session_array_size]) ) + while (((NOT_FOUND == off) || + (NULL != sh->session_array[off % sh->session_array_size])) && + (i < sh->session_array_size)) + { + off++; + i++; + } + if ((NOT_FOUND != off % sh->session_array_size) && + (NULL == sh->session_array[off % sh->session_array_size])) return off; i = sh->session_array_size; - GNUNET_array_grow (sh->session_array, - sh->session_array_size, - sh->session_array_size * 2); + GNUNET_array_grow(sh->session_array, + sh->session_array_size, + sh->session_array_size * 2); return i; } @@ -281,26 +276,26 @@ find_empty_session_slot (struct GNUNET_ATS_SchedulingHandle *sh) * @return the session id or NOT_FOUND for error */ static uint32_t -find_session_id (struct GNUNET_ATS_SchedulingHandle *sh, - struct GNUNET_ATS_Session *session, - const struct GNUNET_HELLO_Address *address) +find_session_id(struct GNUNET_ATS_SchedulingHandle *sh, + struct GNUNET_ATS_Session *session, + const struct GNUNET_HELLO_Address *address) { uint32_t i; if (NULL == address) - { - GNUNET_break (0); - return NOT_FOUND; - } + { + GNUNET_break(0); + return NOT_FOUND; + } for (i = 1; i < sh->session_array_size; i++) - if ( (NULL != sh->session_array[i]) && - (GNUNET_NO == sh->session_array[i]->in_destroy) && - ( (session == sh->session_array[i]->session) || - (NULL == sh->session_array[i]->session) ) && - (0 == GNUNET_memcmp (&address->peer, - &sh->session_array[i]->address->peer)) && - (0 == GNUNET_HELLO_address_cmp (address, - sh->session_array[i]->address)) ) + if ((NULL != sh->session_array[i]) && + (GNUNET_NO == sh->session_array[i]->in_destroy) && + ((session == sh->session_array[i]->session) || + (NULL == sh->session_array[i]->session)) && + (0 == GNUNET_memcmp(&address->peer, + &sh->session_array[i]->address->peer)) && + (0 == GNUNET_HELLO_address_cmp(address, + sh->session_array[i]->address))) return i; return NOT_FOUND; } @@ -314,29 +309,29 @@ find_session_id (struct GNUNET_ATS_SchedulingHandle *sh, * @param session_id identifies session that is no longer valid */ static void -release_session (struct GNUNET_ATS_SchedulingHandle *sh, - uint32_t session_id) +release_session(struct GNUNET_ATS_SchedulingHandle *sh, + uint32_t session_id) { struct GNUNET_ATS_AddressRecord *ar; if (NOT_FOUND == session_id) return; if (session_id >= sh->session_array_size) - { - GNUNET_break (0); - force_reconnect (sh); - return; - } + { + GNUNET_break(0); + force_reconnect(sh); + return; + } /* this slot should have been removed from remove_session before */ ar = sh->session_array[session_id]; if (NULL != ar->session) - { - GNUNET_break (0); - force_reconnect (sh); - return; - } - GNUNET_HELLO_address_free (ar->address); - GNUNET_free (ar); + { + GNUNET_break(0); + force_reconnect(sh); + return; + } + GNUNET_HELLO_address_free(ar->address); + GNUNET_free(ar); sh->session_array[session_id] = NULL; } @@ -349,15 +344,15 @@ release_session (struct GNUNET_ATS_SchedulingHandle *sh, * @param srm message received */ static void -handle_ats_session_release (void *cls, - const struct GNUNET_ATS_SessionReleaseMessage *srm) +handle_ats_session_release(void *cls, + const struct GNUNET_ATS_SessionReleaseMessage *srm) { struct GNUNET_ATS_SchedulingHandle *sh = cls; /* Note: peer field in srm not necessary right now, but might be good to have in the future */ - release_session (sh, - ntohl (srm->session_id)); + release_session(sh, + ntohl(srm->session_id)); } @@ -369,71 +364,71 @@ handle_ats_session_release (void *cls, * @param m message received */ static void -handle_ats_address_suggestion (void *cls, - const struct AddressSuggestionMessage *m) +handle_ats_address_suggestion(void *cls, + const struct AddressSuggestionMessage *m) { struct GNUNET_ATS_SchedulingHandle *sh = cls; struct GNUNET_ATS_AddressRecord *ar; uint32_t session_id; - session_id = ntohl (m->session_id); + session_id = ntohl(m->session_id); if (0 == session_id) - { - GNUNET_break (0); - force_reconnect (sh); - return; - } - ar = find_session (sh, - session_id, - &m->peer); + { + GNUNET_break(0); + force_reconnect(sh); + return; + } + ar = find_session(sh, + session_id, + &m->peer); if (NULL == ar) - { - GNUNET_break (0); - force_reconnect (sh); - return; - } + { + GNUNET_break(0); + force_reconnect(sh); + return; + } if (NULL == sh->suggest_cb) return; if (GNUNET_YES == ar->in_destroy) - { - /* ignore suggestion, as this address is dying, unless BW is 0, - in that case signal 'disconnect' via BW 0 */ - if ( (0 == ntohl (m->bandwidth_out.value__)) && - (0 == ntohl (m->bandwidth_in.value__)) ) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "ATS suggests disconnect from peer `%s' with BW %u/%u\n", - GNUNET_i2s (&ar->address->peer), - (unsigned int) ntohl (m->bandwidth_out.value__), - (unsigned int) ntohl (m->bandwidth_in.value__)); - sh->suggest_cb (sh->suggest_cb_cls, - &m->peer, - NULL, - NULL, - m->bandwidth_out, - m->bandwidth_in); + /* ignore suggestion, as this address is dying, unless BW is 0, + in that case signal 'disconnect' via BW 0 */ + if ((0 == ntohl(m->bandwidth_out.value__)) && + (0 == ntohl(m->bandwidth_in.value__))) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "ATS suggests disconnect from peer `%s' with BW %u/%u\n", + GNUNET_i2s(&ar->address->peer), + (unsigned int)ntohl(m->bandwidth_out.value__), + (unsigned int)ntohl(m->bandwidth_in.value__)); + sh->suggest_cb(sh->suggest_cb_cls, + &m->peer, + NULL, + NULL, + m->bandwidth_out, + m->bandwidth_in); + } + return; + } + if ((NULL == ar->session) && + (GNUNET_HELLO_address_check_option(ar->address, + GNUNET_HELLO_ADDRESS_INFO_INBOUND))) + { + GNUNET_break(0); + return; } - return; - } - if ( (NULL == ar->session) && - (GNUNET_HELLO_address_check_option (ar->address, - GNUNET_HELLO_ADDRESS_INFO_INBOUND)) ) - { - GNUNET_break (0); - return; - } sh->backoff = GNUNET_TIME_UNIT_ZERO; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "ATS suggests address slot %u for peer `%s' using plugin %s\n", - ar->slot, - GNUNET_i2s (&ar->address->peer), - ar->address->transport_name); - sh->suggest_cb (sh->suggest_cb_cls, - &m->peer, - ar->address, - ar->session, - m->bandwidth_out, - m->bandwidth_in); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "ATS suggests address slot %u for peer `%s' using plugin %s\n", + ar->slot, + GNUNET_i2s(&ar->address->peer), + ar->address->transport_name); + sh->suggest_cb(sh->suggest_cb_cls, + &m->peer, + ar->address, + ar->session, + m->bandwidth_out, + m->bandwidth_in); } @@ -445,15 +440,15 @@ handle_ats_address_suggestion (void *cls, * @param error details about the error */ static void -error_handler (void *cls, - enum GNUNET_MQ_Error error) +error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_ATS_SchedulingHandle *sh = cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "ATS connection died (code %d), reconnecting\n", - (int) error); - force_reconnect (sh); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "ATS connection died (code %d), reconnecting\n", + (int)error); + force_reconnect(sh); } @@ -465,8 +460,8 @@ error_handler (void *cls, * @param ar the address to inform the ATS service about */ static void -send_add_address_message (struct GNUNET_ATS_SchedulingHandle *sh, - const struct GNUNET_ATS_AddressRecord *ar) +send_add_address_message(struct GNUNET_ATS_SchedulingHandle *sh, + const struct GNUNET_ATS_AddressRecord *ar) { struct GNUNET_MQ_Envelope *ev; struct AddressAddMessage *m; @@ -476,32 +471,32 @@ send_add_address_message (struct GNUNET_ATS_SchedulingHandle *sh, if (NULL == sh->mq) return; /* disconnected, skip for now */ - GNUNET_break (GNUNET_NT_UNSPECIFIED != ar->properties.scope); - namelen = strlen (ar->address->transport_name) + 1; + GNUNET_break(GNUNET_NT_UNSPECIFIED != ar->properties.scope); + namelen = strlen(ar->address->transport_name) + 1; msize = ar->address->address_length + namelen; - ev = GNUNET_MQ_msg_extra (m, msize, GNUNET_MESSAGE_TYPE_ATS_ADDRESS_ADD); + ev = GNUNET_MQ_msg_extra(m, msize, GNUNET_MESSAGE_TYPE_ATS_ADDRESS_ADD); m->peer = ar->address->peer; - m->address_length = htons (ar->address->address_length); - m->address_local_info = htonl ((uint32_t) ar->address->local_info); - m->plugin_name_length = htons (namelen); - m->session_id = htonl (ar->slot); + m->address_length = htons(ar->address->address_length); + m->address_local_info = htonl((uint32_t)ar->address->local_info); + m->plugin_name_length = htons(namelen); + m->session_id = htonl(ar->slot); m->properties = ar->properties; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Adding address for peer `%s', plugin `%s', session %p slot %u\n", - GNUNET_i2s (&ar->address->peer), - ar->address->transport_name, - ar->session, - ar->slot); - pm = (char *) &m[1]; - GNUNET_memcpy (pm, - ar->address->address, - ar->address->address_length); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Adding address for peer `%s', plugin `%s', session %p slot %u\n", + GNUNET_i2s(&ar->address->peer), + ar->address->transport_name, + ar->session, + ar->slot); + pm = (char *)&m[1]; + GNUNET_memcpy(pm, + ar->address->address, + ar->address->address_length); if (NULL != ar->address->transport_name) - GNUNET_memcpy (&pm[ar->address->address_length], - ar->address->transport_name, - namelen); - GNUNET_MQ_send (sh->mq, ev); + GNUNET_memcpy(&pm[ar->address->address_length], + ar->address->transport_name, + namelen); + GNUNET_MQ_send(sh->mq, ev); } @@ -511,51 +506,51 @@ send_add_address_message (struct GNUNET_ATS_SchedulingHandle *sh, * @param sh handle to use to re-connect. */ static void -reconnect (struct GNUNET_ATS_SchedulingHandle *sh) +reconnect(struct GNUNET_ATS_SchedulingHandle *sh) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (ats_session_release, - GNUNET_MESSAGE_TYPE_ATS_SESSION_RELEASE, - struct GNUNET_ATS_SessionReleaseMessage, - sh), - GNUNET_MQ_hd_fixed_size (ats_address_suggestion, - GNUNET_MESSAGE_TYPE_ATS_ADDRESS_SUGGESTION, - struct AddressSuggestionMessage, - sh), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(ats_session_release, + GNUNET_MESSAGE_TYPE_ATS_SESSION_RELEASE, + struct GNUNET_ATS_SessionReleaseMessage, + sh), + GNUNET_MQ_hd_fixed_size(ats_address_suggestion, + GNUNET_MESSAGE_TYPE_ATS_ADDRESS_SUGGESTION, + struct AddressSuggestionMessage, + sh), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *ev; struct ClientStartMessage *init; unsigned int i; struct GNUNET_ATS_AddressRecord *ar; - GNUNET_assert (NULL == sh->mq); - sh->mq = GNUNET_CLIENT_connect (sh->cfg, - "ats", - handlers, - &error_handler, - sh); + GNUNET_assert(NULL == sh->mq); + sh->mq = GNUNET_CLIENT_connect(sh->cfg, + "ats", + handlers, + &error_handler, + sh); if (NULL == sh->mq) - { - GNUNET_break (0); - force_reconnect (sh); - return; - } - ev = GNUNET_MQ_msg (init, - GNUNET_MESSAGE_TYPE_ATS_START); - init->start_flag = htonl (START_FLAG_SCHEDULING); - GNUNET_MQ_send (sh->mq, ev); + { + GNUNET_break(0); + force_reconnect(sh); + return; + } + ev = GNUNET_MQ_msg(init, + GNUNET_MESSAGE_TYPE_ATS_START); + init->start_flag = htonl(START_FLAG_SCHEDULING); + GNUNET_MQ_send(sh->mq, ev); if (NULL == sh->mq) return; - for (i=0;isession_array_size;i++) - { - ar = sh->session_array[i]; - if (NULL == ar) - continue; - send_add_address_message (sh, ar); - if (NULL == sh->mq) - return; - } + for (i = 0; i < sh->session_array_size; i++) + { + ar = sh->session_array[i]; + if (NULL == ar) + continue; + send_add_address_message(sh, ar); + if (NULL == sh->mq) + return; + } } @@ -568,20 +563,20 @@ reconnect (struct GNUNET_ATS_SchedulingHandle *sh) * @return ats context */ struct GNUNET_ATS_SchedulingHandle * -GNUNET_ATS_scheduling_init (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_ATS_AddressSuggestionCallback suggest_cb, - void *suggest_cb_cls) +GNUNET_ATS_scheduling_init(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_ATS_AddressSuggestionCallback suggest_cb, + void *suggest_cb_cls) { struct GNUNET_ATS_SchedulingHandle *sh; - sh = GNUNET_new (struct GNUNET_ATS_SchedulingHandle); + sh = GNUNET_new(struct GNUNET_ATS_SchedulingHandle); sh->cfg = cfg; sh->suggest_cb = suggest_cb; sh->suggest_cb_cls = suggest_cb_cls; - GNUNET_array_grow (sh->session_array, - sh->session_array_size, - 4); - reconnect (sh); + GNUNET_array_grow(sh->session_array, + sh->session_array_size, + 4); + reconnect(sh); return sh; } @@ -592,34 +587,34 @@ GNUNET_ATS_scheduling_init (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param sh handle to release */ void -GNUNET_ATS_scheduling_done (struct GNUNET_ATS_SchedulingHandle *sh) +GNUNET_ATS_scheduling_done(struct GNUNET_ATS_SchedulingHandle *sh) { struct GNUNET_ATS_AddressRecord *ar; unsigned int i; if (NULL != sh->mq) - { - GNUNET_MQ_destroy (sh->mq); - sh->mq = NULL; - } + { + GNUNET_MQ_destroy(sh->mq); + sh->mq = NULL; + } if (NULL != sh->task) - { - GNUNET_SCHEDULER_cancel (sh->task); - sh->task = NULL; - } - for (i=0;isession_array_size;i++) - { - if (NULL != (ar = sh->session_array[i])) { - GNUNET_HELLO_address_free (ar->address); - GNUNET_free (ar); - sh->session_array[i] = NULL; + GNUNET_SCHEDULER_cancel(sh->task); + sh->task = NULL; } - } - GNUNET_array_grow (sh->session_array, - sh->session_array_size, - 0); - GNUNET_free (sh); + for (i = 0; i < sh->session_array_size; i++) + { + if (NULL != (ar = sh->session_array[i])) + { + GNUNET_HELLO_address_free(ar->address); + GNUNET_free(ar); + sh->session_array[i] = NULL; + } + } + GNUNET_array_grow(sh->session_array, + sh->session_array_size, + 0); + GNUNET_free(sh); } @@ -636,10 +631,10 @@ GNUNET_ATS_scheduling_done (struct GNUNET_ATS_SchedulingHandle *sh) * on error (i.e. ATS knows this exact address already) */ struct GNUNET_ATS_AddressRecord * -GNUNET_ATS_address_add (struct GNUNET_ATS_SchedulingHandle *sh, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_ATS_Session *session, - const struct GNUNET_ATS_Properties *prop) +GNUNET_ATS_address_add(struct GNUNET_ATS_SchedulingHandle *sh, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_ATS_Session *session, + const struct GNUNET_ATS_Properties *prop) { struct GNUNET_ATS_AddressRecord *ar; size_t namelen; @@ -647,42 +642,42 @@ GNUNET_ATS_address_add (struct GNUNET_ATS_SchedulingHandle *sh, uint32_t s; if (NULL == address) - { - /* we need a valid address */ - GNUNET_break (0); - return NULL; - } - GNUNET_break (GNUNET_NT_UNSPECIFIED != prop->scope); - namelen = strlen (address->transport_name) + 1; + { + /* we need a valid address */ + GNUNET_break(0); + return NULL; + } + GNUNET_break(GNUNET_NT_UNSPECIFIED != prop->scope); + namelen = strlen(address->transport_name) + 1; msize = address->address_length + namelen; - if ((msize + sizeof (struct AddressUpdateMessage) >= GNUNET_MAX_MESSAGE_SIZE) || + if ((msize + sizeof(struct AddressUpdateMessage) >= GNUNET_MAX_MESSAGE_SIZE) || (address->address_length >= GNUNET_MAX_MESSAGE_SIZE) || - (namelen >= GNUNET_MAX_MESSAGE_SIZE) ) - { - /* address too large for us, this should not happen */ - GNUNET_break (0); - return NULL; - } + (namelen >= GNUNET_MAX_MESSAGE_SIZE)) + { + /* address too large for us, this should not happen */ + GNUNET_break(0); + return NULL; + } if (NOT_FOUND != - find_session_id (sh, - session, - address)) - { - /* Already existing, nothing todo, but this should not happen */ - GNUNET_break (0); - return NULL; - } - s = find_empty_session_slot (sh); - ar = GNUNET_new (struct GNUNET_ATS_AddressRecord); + find_session_id(sh, + session, + address)) + { + /* Already existing, nothing todo, but this should not happen */ + GNUNET_break(0); + return NULL; + } + s = find_empty_session_slot(sh); + ar = GNUNET_new(struct GNUNET_ATS_AddressRecord); ar->sh = sh; ar->slot = s; ar->session = session; - ar->address = GNUNET_HELLO_address_copy (address); - GNUNET_ATS_properties_hton (&ar->properties, - prop); + ar->address = GNUNET_HELLO_address_copy(address); + GNUNET_ATS_properties_hton(&ar->properties, + prop); sh->session_array[s] = ar; - send_add_address_message (sh, ar); + send_add_address_message(sh, ar); return ar; } @@ -694,10 +689,10 @@ GNUNET_ATS_address_add (struct GNUNET_ATS_SchedulingHandle *sh, * @param session session handle */ void -GNUNET_ATS_address_add_session (struct GNUNET_ATS_AddressRecord *ar, - struct GNUNET_ATS_Session *session) +GNUNET_ATS_address_add_session(struct GNUNET_ATS_AddressRecord *ar, + struct GNUNET_ATS_Session *session) { - GNUNET_break (NULL == ar->session); + GNUNET_break(NULL == ar->session); ar->session = session; } @@ -715,17 +710,17 @@ GNUNET_ATS_address_add_session (struct GNUNET_ATS_AddressRecord *ar, * use it still to establish a new session */ int -GNUNET_ATS_address_del_session (struct GNUNET_ATS_AddressRecord *ar, - struct GNUNET_ATS_Session *session) +GNUNET_ATS_address_del_session(struct GNUNET_ATS_AddressRecord *ar, + struct GNUNET_ATS_Session *session) { - GNUNET_assert (session == ar->session); + GNUNET_assert(session == ar->session); ar->session = NULL; - if (GNUNET_HELLO_address_check_option (ar->address, - GNUNET_HELLO_ADDRESS_INFO_INBOUND)) - { - GNUNET_ATS_address_destroy (ar); - return GNUNET_YES; - } + if (GNUNET_HELLO_address_check_option(ar->address, + GNUNET_HELLO_ADDRESS_INFO_INBOUND)) + { + GNUNET_ATS_address_destroy(ar); + return GNUNET_YES; + } return GNUNET_NO; } @@ -742,30 +737,30 @@ GNUNET_ATS_address_del_session (struct GNUNET_ATS_AddressRecord *ar, * @param prop performance data for the address */ void -GNUNET_ATS_address_update (struct GNUNET_ATS_AddressRecord *ar, - const struct GNUNET_ATS_Properties *prop) +GNUNET_ATS_address_update(struct GNUNET_ATS_AddressRecord *ar, + const struct GNUNET_ATS_Properties *prop) { struct GNUNET_ATS_SchedulingHandle *sh = ar->sh; struct GNUNET_MQ_Envelope *ev; struct AddressUpdateMessage *m; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Updating address for peer `%s', plugin `%s', session %p slot %u\n", - GNUNET_i2s (&ar->address->peer), - ar->address->transport_name, - ar->session, - ar->slot); - GNUNET_break (GNUNET_NT_UNSPECIFIED != prop->scope); - GNUNET_ATS_properties_hton (&ar->properties, - prop); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Updating address for peer `%s', plugin `%s', session %p slot %u\n", + GNUNET_i2s(&ar->address->peer), + ar->address->transport_name, + ar->session, + ar->slot); + GNUNET_break(GNUNET_NT_UNSPECIFIED != prop->scope); + GNUNET_ATS_properties_hton(&ar->properties, + prop); if (NULL == sh->mq) return; /* disconnected, skip for now */ - ev = GNUNET_MQ_msg (m, GNUNET_MESSAGE_TYPE_ATS_ADDRESS_UPDATE); - m->session_id = htonl (ar->slot); + ev = GNUNET_MQ_msg(m, GNUNET_MESSAGE_TYPE_ATS_ADDRESS_UPDATE); + m->session_id = htonl(ar->slot); m->peer = ar->address->peer; m->properties = ar->properties; - GNUNET_MQ_send (sh->mq, - ev); + GNUNET_MQ_send(sh->mq, + ev); } @@ -775,27 +770,27 @@ GNUNET_ATS_address_update (struct GNUNET_ATS_AddressRecord *ar, * @param ar address to destroy */ void -GNUNET_ATS_address_destroy (struct GNUNET_ATS_AddressRecord *ar) +GNUNET_ATS_address_destroy(struct GNUNET_ATS_AddressRecord *ar) { struct GNUNET_ATS_SchedulingHandle *sh = ar->sh; struct GNUNET_MQ_Envelope *ev; struct AddressDestroyedMessage *m; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Deleting address for peer `%s', plugin `%s', slot %u session %p\n", - GNUNET_i2s (&ar->address->peer), - ar->address->transport_name, - ar->slot, - ar->session); - GNUNET_break (NULL == ar->session); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Deleting address for peer `%s', plugin `%s', slot %u session %p\n", + GNUNET_i2s(&ar->address->peer), + ar->address->transport_name, + ar->slot, + ar->session); + GNUNET_break(NULL == ar->session); ar->session = NULL; ar->in_destroy = GNUNET_YES; if (NULL == sh->mq) return; - ev = GNUNET_MQ_msg (m, GNUNET_MESSAGE_TYPE_ATS_ADDRESS_DESTROYED); - m->session_id = htonl (ar->slot); + ev = GNUNET_MQ_msg(m, GNUNET_MESSAGE_TYPE_ATS_ADDRESS_DESTROYED); + m->session_id = htonl(ar->slot); m->peer = ar->address->peer; - GNUNET_MQ_send (sh->mq, ev); + GNUNET_MQ_send(sh->mq, ev); } diff --git a/src/ats/gnunet-ats-solver-eval.c b/src/ats/gnunet-ats-solver-eval.c index 833cb9ded..4068cffce 100644 --- a/src/ats/gnunet-ats-solver-eval.c +++ b/src/ats/gnunet-ats-solver-eval.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2013 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2013 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -85,32 +85,38 @@ static int opt_disable_normalization; static int res; static void -end_now (); +end_now(); static char * -print_generator_type (enum GeneratorType g) +print_generator_type(enum GeneratorType g) { - switch (g) { + switch (g) + { case GNUNET_ATS_TEST_TG_CONSTANT: return "CONSTANT"; + case GNUNET_ATS_TEST_TG_LINEAR: return "LINEAR"; + case GNUNET_ATS_TEST_TG_RANDOM: return "RANDOM"; + case GNUNET_ATS_TEST_TG_SINUS: return "SINUS"; + default: return "INVALID"; break; - } + } } static struct TestPeer * -find_peer_by_id (int id) +find_peer_by_id(int id) { struct TestPeer *cur; + for (cur = peer_head; NULL != cur; cur = cur->next) if (cur->id == id) return cur; @@ -118,19 +124,21 @@ find_peer_by_id (int id) } static struct TestPeer * -find_peer_by_pid (const struct GNUNET_PeerIdentity *pid) +find_peer_by_pid(const struct GNUNET_PeerIdentity *pid) { struct TestPeer *cur; + for (cur = peer_head; NULL != cur; cur = cur->next) - if (0 == GNUNET_memcmp (&cur->peer_id, pid)) + if (0 == GNUNET_memcmp(&cur->peer_id, pid)) return cur; return NULL; } static struct TestAddress * -find_address_by_id (struct TestPeer *peer, int aid) +find_address_by_id(struct TestPeer *peer, int aid) { struct TestAddress *cur; + for (cur = peer->addr_head; NULL != cur; cur = cur->next) if (cur->aid == aid) return cur; @@ -142,7 +150,7 @@ find_address_by_id (struct TestPeer *peer, int aid) * Logging */ void -GNUNET_ATS_solver_logging_now (struct LoggingHandle *l) +GNUNET_ATS_solver_logging_now(struct LoggingHandle *l) { struct LoggingTimeStep *lts; struct TestPeer *cur; @@ -151,7 +159,7 @@ GNUNET_ATS_solver_logging_now (struct LoggingHandle *l) struct LoggingAddress *log_a; int c; - lts = GNUNET_new (struct LoggingTimeStep); + lts = GNUNET_new(struct LoggingTimeStep); GNUNET_CONTAINER_DLL_insert_tail(l->head, l->tail, lts); lts->timestamp = GNUNET_TIME_absolute_get(); if (NULL == lts->prev) @@ -159,102 +167,103 @@ GNUNET_ATS_solver_logging_now (struct LoggingHandle *l) else lts->delta = GNUNET_TIME_absolute_get_duration(lts->prev->timestamp); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Logging %llu, delta %llu\n", - lts->timestamp.abs_value_us, lts->delta.rel_value_us); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Logging %llu, delta %llu\n", + lts->timestamp.abs_value_us, lts->delta.rel_value_us); /* Store logging data here */ for (cur = peer_head; NULL != cur; cur = cur->next) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Logging peer id %llu\n", cur->id); - - log_p = GNUNET_new (struct LoggingPeer); - log_p->id = cur->id; - log_p->peer_id = cur->peer_id; - log_p->is_requested = cur->is_requested; - for (c = 0; c < GNUNET_ATS_PreferenceCount; c++) - { - log_p->pref_abs[c] = cur->pref_abs[c]; - log_p->pref_norm[c] = cur->pref_norm[c]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "\t %s = %.2f %.2f [abs/rel]\n", - GNUNET_ATS_print_preference_type(c), - log_p->pref_abs[c], log_p->pref_norm[c]); - } - GNUNET_CONTAINER_DLL_insert_tail(lts->head, lts->tail, log_p); - - for (cur_addr = cur->addr_head; NULL != cur_addr; cur_addr = cur_addr->next) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Logging peer id %llu address %llu\n", - cur->id, cur_addr->aid); - log_a = GNUNET_new (struct LoggingAddress); - log_a->aid = cur_addr->aid; - log_a->active = cur_addr->ats_addr->active; - log_a->network = cur_addr->network; - log_a->assigned_bw_in = cur_addr->ats_addr->assigned_bw_in; - log_a->assigned_bw_out = cur_addr->ats_addr->assigned_bw_out; - for (c = 0; c < GNUNET_ATS_PropertyCount; c++) - { - log_a->prop_abs[c] = cur_addr->prop_abs[c]; - log_a->prop_norm[c] = cur_addr->prop_norm[c]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "\t %s = %.2f %.2f [abs/rel]\n", - GNUNET_ATS_print_property_type(c), - log_a->prop_abs[c], - log_a->prop_norm[c]); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\t Active = %i\n", log_a->active); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\t BW in = %llu\n", log_a->assigned_bw_in); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "\t BW out = %llu\n", log_a->assigned_bw_out); + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Logging peer id %llu\n", cur->id); + + log_p = GNUNET_new(struct LoggingPeer); + log_p->id = cur->id; + log_p->peer_id = cur->peer_id; + log_p->is_requested = cur->is_requested; + for (c = 0; c < GNUNET_ATS_PreferenceCount; c++) + { + log_p->pref_abs[c] = cur->pref_abs[c]; + log_p->pref_norm[c] = cur->pref_norm[c]; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "\t %s = %.2f %.2f [abs/rel]\n", + GNUNET_ATS_print_preference_type(c), + log_p->pref_abs[c], log_p->pref_norm[c]); + } + GNUNET_CONTAINER_DLL_insert_tail(lts->head, lts->tail, log_p); - GNUNET_CONTAINER_DLL_insert_tail (log_p->addr_head, log_p->addr_tail, log_a); + for (cur_addr = cur->addr_head; NULL != cur_addr; cur_addr = cur_addr->next) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Logging peer id %llu address %llu\n", + cur->id, cur_addr->aid); + log_a = GNUNET_new(struct LoggingAddress); + log_a->aid = cur_addr->aid; + log_a->active = cur_addr->ats_addr->active; + log_a->network = cur_addr->network; + log_a->assigned_bw_in = cur_addr->ats_addr->assigned_bw_in; + log_a->assigned_bw_out = cur_addr->ats_addr->assigned_bw_out; + for (c = 0; c < GNUNET_ATS_PropertyCount; c++) + { + log_a->prop_abs[c] = cur_addr->prop_abs[c]; + log_a->prop_norm[c] = cur_addr->prop_norm[c]; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "\t %s = %.2f %.2f [abs/rel]\n", + GNUNET_ATS_print_property_type(c), + log_a->prop_abs[c], + log_a->prop_norm[c]); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "\t Active = %i\n", log_a->active); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "\t BW in = %llu\n", log_a->assigned_bw_in); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "\t BW out = %llu\n", log_a->assigned_bw_out); + + GNUNET_CONTAINER_DLL_insert_tail(log_p->addr_head, log_p->addr_tail, log_a); + } } - } } static void -logging_task (void *cls) +logging_task(void *cls) { struct LoggingHandle *l = cls; l->logging_task = NULL; - GNUNET_ATS_solver_logging_now (l); - l->logging_task = GNUNET_SCHEDULER_add_delayed (l->log_freq, - &logging_task, - l); + GNUNET_ATS_solver_logging_now(l); + l->logging_task = GNUNET_SCHEDULER_add_delayed(l->log_freq, + &logging_task, + l); } struct LoggingHandle * -GNUNET_ATS_solver_logging_start (struct GNUNET_TIME_Relative freq) +GNUNET_ATS_solver_logging_start(struct GNUNET_TIME_Relative freq) { struct LoggingHandle *l; - l = GNUNET_new (struct LoggingHandle); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Start logging every %s\n", - GNUNET_STRINGS_relative_time_to_string(freq, GNUNET_NO)); + l = GNUNET_new(struct LoggingHandle); + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Start logging every %s\n", + GNUNET_STRINGS_relative_time_to_string(freq, GNUNET_NO)); l->log_freq = freq; - l->logging_task = GNUNET_SCHEDULER_add_now (&logging_task, l); + l->logging_task = GNUNET_SCHEDULER_add_now(&logging_task, l); return l; } void -GNUNET_ATS_solver_logging_stop (struct LoggingHandle *l) +GNUNET_ATS_solver_logging_stop(struct LoggingHandle *l) { if (NULL != l->logging_task) - GNUNET_SCHEDULER_cancel (l->logging_task); + GNUNET_SCHEDULER_cancel(l->logging_task); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Stop logging\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Stop logging\n"); l->logging_task = NULL; } static struct LoggingFileHandle * -find_logging_file_handle (struct LoggingFileHandle *lf_head, - struct LoggingFileHandle *lf_tail, - int peer_id, int address_id) +find_logging_file_handle(struct LoggingFileHandle *lf_head, + struct LoggingFileHandle *lf_tail, + int peer_id, int address_id) { struct LoggingFileHandle *res; @@ -262,12 +271,11 @@ find_logging_file_handle (struct LoggingFileHandle *lf_head, if ((res->pid == peer_id) && (res->aid == address_id)) return res; return NULL; - } void -GNUNET_ATS_solver_logging_write_to_disk (struct LoggingHandle *l, int add_time_stamp, - char *output_dir) +GNUNET_ATS_solver_logging_write_to_disk(struct LoggingHandle *l, int add_time_stamp, + char *output_dir) { struct LoggingTimeStep *lts; struct LoggingPeer *log_p; @@ -287,157 +295,153 @@ GNUNET_ATS_solver_logging_write_to_disk (struct LoggingHandle *l, int add_time_s use_dir = GNUNET_NO; if (NULL != output_dir) - { - if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (output_dir)) { - fprintf (stderr, "Failed to create directory `%s'\n", output_dir); - return; - } - else - { - fprintf (stderr, "Created directory `%s'\n", output_dir); - use_dir = GNUNET_YES; + if (GNUNET_OK != GNUNET_DISK_directory_create_for_file(output_dir)) + { + fprintf(stderr, "Failed to create directory `%s'\n", output_dir); + return; + } + else + { + fprintf(stderr, "Created directory `%s'\n", output_dir); + use_dir = GNUNET_YES; + } } - } lf_head = NULL; lf_tail = NULL; for (lts = l->head; NULL != lts; lts = lts->next) - { - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Writing log step %llu\n", - (long long unsigned int) lts->timestamp.abs_value_us); - - for (log_p = lts->head; NULL != log_p; log_p = log_p->next) { - for (log_a = log_p->addr_head; NULL != log_a; log_a = log_a->next) - { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Writing log step %llu\n", + (long long unsigned int)lts->timestamp.abs_value_us); - cur = find_logging_file_handle (lf_head, lf_tail, log_p->id, - log_a->aid); - if (NULL == cur) + for (log_p = lts->head; NULL != log_p; log_p = log_p->next) { - cur = GNUNET_new (struct LoggingFileHandle); - cur->aid = log_a->aid; - cur->pid = log_p->id; - - if (GNUNET_YES == add_time_stamp) - GNUNET_asprintf (&filename, "%s%s%s_%s_p%u_a%u_%llu.log", - (GNUNET_YES == use_dir) ? output_dir : "", - (GNUNET_YES == use_dir) ? DIR_SEPARATOR_STR : "", - e->log_prefix, - opt_solver, - cur->pid, - cur->aid, - l->head->timestamp.abs_value_us); - else - GNUNET_asprintf (&filename, "%s%s%s_%s_p%u_a%u.log", - (GNUNET_YES == use_dir) ? output_dir : "", - (GNUNET_YES == use_dir) ? DIR_SEPARATOR_STR : "", - e->log_prefix, - opt_solver, - cur->pid, - cur->aid); - - fprintf (stderr, "Add writing log data for peer %llu address %llu to file `%s'\n", - cur->pid, cur->aid, filename); - - - cur->f_hd = GNUNET_DISK_file_open (filename, - GNUNET_DISK_OPEN_READWRITE | - GNUNET_DISK_OPEN_CREATE | - GNUNET_DISK_OPEN_TRUNCATE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_GROUP_READ | - GNUNET_DISK_PERM_OTHER_READ); - if (NULL == cur->f_hd) - { - fprintf (stderr, "Cannot open `%s' to write log data!\n", filename); - GNUNET_free (filename); - GNUNET_free (cur); - goto cleanup; - } - GNUNET_free (filename); - GNUNET_CONTAINER_DLL_insert (lf_head, lf_tail, cur); - - GNUNET_asprintf(&datastring,"#time delta;log duration;peer_requested;addr net; addr_active; bw in; bw out; " \ - "UTILIZATION_UP [abs/rel]; UTILIZATION_UP; UTILIZATION_DOWN; UTILIZATION_DOWN; " \ - "UTILIZATION_PAYLOAD_UP; UTILIZATION_PAYLOAD_UP; UTILIZATION_PAYLOAD_DOWN; UTILIZATION_PAYLOAD_DOWN;"\ - "DELAY; DELAY; " \ - "DISTANCE ;DISTANCE ; COST_WAN; COST_WAN; COST_LAN; COST_LAN; " \ - "COST_WLAN; COST_WLAN;COST_BT; COST_BT; PREF BW abs; PREF BW rel; PREF LATENCY abs; PREF LATENCY rel;\n"); - GNUNET_DISK_file_write (cur->f_hd, datastring, strlen(datastring)); - GNUNET_free (datastring); - - } - - prefstring = GNUNET_strdup(""); - for (c = 1; c < GNUNET_ATS_PreferenceCount; c++) - { - /* - fprintf(stderr,"\t %s = %.2f %.2f [abs/rel]\n", - GNUNET_ATS_print_preference_type(c), - log_p->pref_abs[c], log_p->pref_norm[c]); - */ - GNUNET_asprintf(&prefstring_tmp,"%s;%.3f;%.3f", - prefstring, log_p->pref_abs[c], log_p->pref_norm[c]); - - - GNUNET_free (prefstring); - prefstring = GNUNET_strdup(prefstring_tmp); - GNUNET_free (prefstring_tmp); - } - - - propstring = GNUNET_strdup(""); - for (c = 1; c < GNUNET_ATS_PropertyCount; c++) - { - if (GNUNET_ATS_NETWORK_TYPE == c) - continue; - /* - fprintf(stderr, "\t %s = %.2f %.2f [abs/rel]\n", - GNUNET_ATS_print_property_type(c), - log_a->prop_abs[c], log_a->prop_norm[c]);*/ - GNUNET_asprintf(&propstring_tmp,"%s%.3f;%.3f;", - propstring, - log_a->prop_abs[c], - log_a->prop_norm[c]); - GNUNET_free (propstring); - propstring = GNUNET_strdup(propstring_tmp); - GNUNET_free (propstring_tmp); + for (log_a = log_p->addr_head; NULL != log_a; log_a = log_a->next) + { + cur = find_logging_file_handle(lf_head, lf_tail, log_p->id, + log_a->aid); + if (NULL == cur) + { + cur = GNUNET_new(struct LoggingFileHandle); + cur->aid = log_a->aid; + cur->pid = log_p->id; + + if (GNUNET_YES == add_time_stamp) + GNUNET_asprintf(&filename, "%s%s%s_%s_p%u_a%u_%llu.log", + (GNUNET_YES == use_dir) ? output_dir : "", + (GNUNET_YES == use_dir) ? DIR_SEPARATOR_STR : "", + e->log_prefix, + opt_solver, + cur->pid, + cur->aid, + l->head->timestamp.abs_value_us); + else + GNUNET_asprintf(&filename, "%s%s%s_%s_p%u_a%u.log", + (GNUNET_YES == use_dir) ? output_dir : "", + (GNUNET_YES == use_dir) ? DIR_SEPARATOR_STR : "", + e->log_prefix, + opt_solver, + cur->pid, + cur->aid); + + fprintf(stderr, "Add writing log data for peer %llu address %llu to file `%s'\n", + cur->pid, cur->aid, filename); + + + cur->f_hd = GNUNET_DISK_file_open(filename, + GNUNET_DISK_OPEN_READWRITE | + GNUNET_DISK_OPEN_CREATE | + GNUNET_DISK_OPEN_TRUNCATE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_GROUP_READ | + GNUNET_DISK_PERM_OTHER_READ); + if (NULL == cur->f_hd) + { + fprintf(stderr, "Cannot open `%s' to write log data!\n", filename); + GNUNET_free(filename); + GNUNET_free(cur); + goto cleanup; + } + GNUNET_free(filename); + GNUNET_CONTAINER_DLL_insert(lf_head, lf_tail, cur); + + GNUNET_asprintf(&datastring, "#time delta;log duration;peer_requested;addr net; addr_active; bw in; bw out; " \ + "UTILIZATION_UP [abs/rel]; UTILIZATION_UP; UTILIZATION_DOWN; UTILIZATION_DOWN; " \ + "UTILIZATION_PAYLOAD_UP; UTILIZATION_PAYLOAD_UP; UTILIZATION_PAYLOAD_DOWN; UTILIZATION_PAYLOAD_DOWN;" \ + "DELAY; DELAY; " \ + "DISTANCE ;DISTANCE ; COST_WAN; COST_WAN; COST_LAN; COST_LAN; " \ + "COST_WLAN; COST_WLAN;COST_BT; COST_BT; PREF BW abs; PREF BW rel; PREF LATENCY abs; PREF LATENCY rel;\n"); + GNUNET_DISK_file_write(cur->f_hd, datastring, strlen(datastring)); + GNUNET_free(datastring); + } + + prefstring = GNUNET_strdup(""); + for (c = 1; c < GNUNET_ATS_PreferenceCount; c++) + { + /* + fprintf(stderr,"\t %s = %.2f %.2f [abs/rel]\n", + GNUNET_ATS_print_preference_type(c), + log_p->pref_abs[c], log_p->pref_norm[c]); + */ + GNUNET_asprintf(&prefstring_tmp, "%s;%.3f;%.3f", + prefstring, log_p->pref_abs[c], log_p->pref_norm[c]); + + + GNUNET_free(prefstring); + prefstring = GNUNET_strdup(prefstring_tmp); + GNUNET_free(prefstring_tmp); + } + + + propstring = GNUNET_strdup(""); + for (c = 1; c < GNUNET_ATS_PropertyCount; c++) + { + if (GNUNET_ATS_NETWORK_TYPE == c) + continue; + /* + fprintf(stderr, "\t %s = %.2f %.2f [abs/rel]\n", + GNUNET_ATS_print_property_type(c), + log_a->prop_abs[c], log_a->prop_norm[c]);*/ + GNUNET_asprintf(&propstring_tmp, "%s%.3f;%.3f;", + propstring, + log_a->prop_abs[c], + log_a->prop_norm[c]); + GNUNET_free(propstring); + propstring = GNUNET_strdup(propstring_tmp); + GNUNET_free(propstring_tmp); + } + GNUNET_asprintf(&datastring, "%llu;%llu;%u;%u;%i;%u;%u;%s;%s\n", + GNUNET_TIME_absolute_get_difference(l->head->timestamp, + lts->timestamp).rel_value_us / 1000, lts->delta, + log_p->is_requested, log_a->network, log_a->active, + log_a->assigned_bw_in, log_a->assigned_bw_out, propstring, + prefstring); + + GNUNET_DISK_file_write(cur->f_hd, datastring, strlen(datastring)); + GNUNET_free(datastring); + GNUNET_free(prefstring); + GNUNET_free(propstring); + } } - GNUNET_asprintf (&datastring, "%llu;%llu;%u;%u;%i;%u;%u;%s;%s\n", - GNUNET_TIME_absolute_get_difference (l->head->timestamp, - lts->timestamp).rel_value_us / 1000, lts->delta, - log_p->is_requested, log_a->network, log_a->active, - log_a->assigned_bw_in, log_a->assigned_bw_out, propstring, - prefstring); - - GNUNET_DISK_file_write (cur->f_hd, datastring, strlen(datastring)); - GNUNET_free (datastring); - GNUNET_free (prefstring); - GNUNET_free (propstring); - } } - } cleanup: next = lf_head; for (cur = next; NULL != cur; cur = next) - { - next = cur->next; - GNUNET_CONTAINER_DLL_remove (lf_head, lf_tail, cur); - if (NULL != cur->f_hd) - GNUNET_DISK_file_close (cur->f_hd); - GNUNET_free (cur); - } - + { + next = cur->next; + GNUNET_CONTAINER_DLL_remove(lf_head, lf_tail, cur); + if (NULL != cur->f_hd) + GNUNET_DISK_file_close(cur->f_hd); + GNUNET_free(cur); + } } void -GNUNET_ATS_solver_logging_eval (struct LoggingHandle *l) +GNUNET_ATS_solver_logging_eval(struct LoggingHandle *l) { struct LoggingTimeStep *lts; struct LoggingPeer *log_p; @@ -445,43 +449,43 @@ GNUNET_ATS_solver_logging_eval (struct LoggingHandle *l) int c; for (lts = l->head; NULL != lts; lts = lts->next) - { - fprintf (stderr, "Log step %llu %llu: \n", - (long long unsigned int) lts->timestamp.abs_value_us, - (long long unsigned int) lts->delta.rel_value_us); - - for (log_p = lts->head; NULL != log_p; log_p = log_p->next) { - fprintf (stderr,"\tLogging peer pid %llu\n", log_p->id); - for (c = 1; c < GNUNET_ATS_PreferenceCount; c++) - { - fprintf(stderr,"\t %s = %.2f %.2f [abs/rel]\n", - GNUNET_ATS_print_preference_type(c), - log_p->pref_abs[c], log_p->pref_norm[c]); - } - - for (log_a = log_p->addr_head; NULL != log_a; log_a = log_a->next) - { - fprintf (stderr, "\tPeer pid %llu address %llu: %u %u %u\n", - log_p->id, log_a->aid, log_a->active, - log_a->assigned_bw_in, - log_a->assigned_bw_out); + fprintf(stderr, "Log step %llu %llu: \n", + (long long unsigned int)lts->timestamp.abs_value_us, + (long long unsigned int)lts->delta.rel_value_us); - for (c = 1; c < GNUNET_ATS_PropertyCount; c++) + for (log_p = lts->head; NULL != log_p; log_p = log_p->next) { - if (GNUNET_ATS_NETWORK_TYPE == c) - continue; - fprintf(stderr, "\t %s = %.2f %.2f [abs/rel]\n", - GNUNET_ATS_print_property_type(c), - log_a->prop_abs[c], log_a->prop_norm[c]); + fprintf(stderr, "\tLogging peer pid %llu\n", log_p->id); + for (c = 1; c < GNUNET_ATS_PreferenceCount; c++) + { + fprintf(stderr, "\t %s = %.2f %.2f [abs/rel]\n", + GNUNET_ATS_print_preference_type(c), + log_p->pref_abs[c], log_p->pref_norm[c]); + } + + for (log_a = log_p->addr_head; NULL != log_a; log_a = log_a->next) + { + fprintf(stderr, "\tPeer pid %llu address %llu: %u %u %u\n", + log_p->id, log_a->aid, log_a->active, + log_a->assigned_bw_in, + log_a->assigned_bw_out); + + for (c = 1; c < GNUNET_ATS_PropertyCount; c++) + { + if (GNUNET_ATS_NETWORK_TYPE == c) + continue; + fprintf(stderr, "\t %s = %.2f %.2f [abs/rel]\n", + GNUNET_ATS_print_property_type(c), + log_a->prop_abs[c], log_a->prop_norm[c]); + } + } } - } } - } } void -GNUNET_ATS_solver_logging_free (struct LoggingHandle *l) +GNUNET_ATS_solver_logging_free(struct LoggingHandle *l) { struct LoggingTimeStep *lts_cur; struct LoggingTimeStep *lts_next; @@ -491,37 +495,37 @@ GNUNET_ATS_solver_logging_free (struct LoggingHandle *l) struct LoggingAddress *log_a_next; if (NULL != l->logging_task) - GNUNET_SCHEDULER_cancel (l->logging_task); + GNUNET_SCHEDULER_cancel(l->logging_task); l->logging_task = NULL; lts_next = l->head; while (NULL != (lts_cur = lts_next)) - { - lts_next = lts_cur->next; - - log_p_next = lts_cur->head; - while (NULL != (log_p_cur = log_p_next)) { - log_p_next = log_p_cur->next; + lts_next = lts_cur->next; - log_a_next = log_p_cur->addr_head; - while (NULL != (log_a_cur = log_a_next)) - { - log_a_next = log_a_cur->next; + log_p_next = lts_cur->head; + while (NULL != (log_p_cur = log_p_next)) + { + log_p_next = log_p_cur->next; - GNUNET_CONTAINER_DLL_remove (log_p_cur->addr_head, log_p_cur->addr_tail, log_a_cur); - GNUNET_free (log_a_cur); - } + log_a_next = log_p_cur->addr_head; + while (NULL != (log_a_cur = log_a_next)) + { + log_a_next = log_a_cur->next; - GNUNET_CONTAINER_DLL_remove (lts_cur->head, lts_cur->tail, log_p_cur); - GNUNET_free (log_p_cur); - } + GNUNET_CONTAINER_DLL_remove(log_p_cur->addr_head, log_p_cur->addr_tail, log_a_cur); + GNUNET_free(log_a_cur); + } - GNUNET_CONTAINER_DLL_remove (l->head, l->tail, lts_cur); - GNUNET_free (lts_cur); - } + GNUNET_CONTAINER_DLL_remove(lts_cur->head, lts_cur->tail, log_p_cur); + GNUNET_free(log_p_cur); + } + + GNUNET_CONTAINER_DLL_remove(l->head, l->tail, lts_cur); + GNUNET_free(lts_cur); + } - GNUNET_free (l); + GNUNET_free(l); } /** @@ -532,65 +536,70 @@ static struct PropertyGenerator *prop_gen_tail; static double -get_property (struct PropertyGenerator *pg) +get_property(struct PropertyGenerator *pg) { struct GNUNET_TIME_Relative time_delta; double delta_value; double pref_value; /* Calculate the current preference value */ - switch (pg->type) { + switch (pg->type) + { case GNUNET_ATS_TEST_TG_CONSTANT: pref_value = pg->base_value; break; + case GNUNET_ATS_TEST_TG_LINEAR: time_delta = GNUNET_TIME_absolute_get_duration(pg->time_start); /* Calculate point of time in the current period */ time_delta.rel_value_us = time_delta.rel_value_us % - pg->duration_period.rel_value_us; - delta_value = ((double) time_delta.rel_value_us / - pg->duration_period.rel_value_us) * (pg->max_value - pg->base_value); + pg->duration_period.rel_value_us; + delta_value = ((double)time_delta.rel_value_us / + pg->duration_period.rel_value_us) * (pg->max_value - pg->base_value); if ((pg->max_value < pg->base_value) && ((pg->max_value - pg->base_value) > pg->base_value)) - { - /* This will cause an underflow */ - GNUNET_break (0); - } + { + /* This will cause an underflow */ + GNUNET_break(0); + } pref_value = pg->base_value + delta_value; break; + case GNUNET_ATS_TEST_TG_RANDOM: - delta_value = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - 10000 * (pg->max_value - pg->base_value)) / 10000; + delta_value = (double)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + 10000 * (pg->max_value - pg->base_value)) / 10000; pref_value = pg->base_value + delta_value; break; + case GNUNET_ATS_TEST_TG_SINUS: time_delta = GNUNET_TIME_absolute_get_duration(pg->time_start); /* Calculate point of time in the current period */ time_delta.rel_value_us = time_delta.rel_value_us % - pg->duration_period.rel_value_us; + pg->duration_period.rel_value_us; if ((pg->max_value - pg->base_value) > pg->base_value) - { - /* This will cause an underflow for second half of sinus period, - * will be detected in general when experiments are loaded */ - GNUNET_break (0); - } + { + /* This will cause an underflow for second half of sinus period, + * will be detected in general when experiments are loaded */ + GNUNET_break(0); + } delta_value = (pg->max_value - pg->base_value) * - sin ( (2 * M_PI) / ((double) pg->duration_period.rel_value_us) * - time_delta.rel_value_us); + sin((2 * M_PI) / ((double)pg->duration_period.rel_value_us) * + time_delta.rel_value_us); pref_value = pg->base_value + delta_value; break; + default: pref_value = 0.0; break; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Current property value is %f\n", - pref_value); + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Current property value is %f\n", + pref_value); return pref_value; } static void -set_prop_task (void *cls) +set_prop_task(void *cls) { struct PropertyGenerator *pg = cls; struct TestPeer *p; @@ -600,58 +609,58 @@ set_prop_task (void *cls) pg->set_task = NULL; - if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains_value (sh->addresses, - &pg->test_peer->peer_id, pg->test_address->ats_addr)) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Setting property generation for unknown address [%u:%u]\n", - pg->peer, pg->address_id); - return; - } - if (NULL == (p = find_peer_by_id (pg->peer))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Setting property generation for unknown peer %u\n", - pg->peer); - return; - } - if (NULL == (a = find_address_by_id (p, pg->address_id))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Setting property generation for unknown peer %u\n", - pg->peer); - return; - } + if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains_value(sh->addresses, + &pg->test_peer->peer_id, pg->test_address->ats_addr)) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Setting property generation for unknown address [%u:%u]\n", + pg->peer, pg->address_id); + return; + } + if (NULL == (p = find_peer_by_id(pg->peer))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Setting property generation for unknown peer %u\n", + pg->peer); + return; + } + if (NULL == (a = find_address_by_id(p, pg->address_id))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Setting property generation for unknown peer %u\n", + pg->peer); + return; + } - prop_value = get_property (pg); + prop_value = get_property(pg); a->prop_abs[pg->ats_property] = prop_value; GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Setting property for peer [%u] address [%u] for %s to %f\n", - pg->peer, pg->address_id, - GNUNET_ATS_print_property_type (pg->ats_property), prop_value); + "Setting property for peer [%u] address [%u] for %s to %f\n", + pg->peer, pg->address_id, + GNUNET_ATS_print_property_type(pg->ats_property), prop_value); - atsi.type = htonl (pg->ats_property); - atsi.value = htonl ((uint32_t) prop_value); + atsi.type = htonl(pg->ats_property); + atsi.value = htonl((uint32_t)prop_value); /* set performance here! */ - sh->sf->s_bulk_start (sh->sf->cls); + sh->sf->s_bulk_start(sh->sf->cls); if (GNUNET_YES == opt_disable_normalization) - { - a->prop_abs[pg->ats_property] = prop_value; - a->prop_norm[pg->ats_property] = prop_value; - sh->sf->s_address_update_property (sh->sf->cls, a->ats_addr, - pg->ats_property, prop_value, prop_value); - } + { + a->prop_abs[pg->ats_property] = prop_value; + a->prop_norm[pg->ats_property] = prop_value; + sh->sf->s_address_update_property(sh->sf->cls, a->ats_addr, + pg->ats_property, prop_value, prop_value); + } else - GAS_normalization_update_property (pg->test_address->ats_addr, &atsi, 1); - sh->sf->s_bulk_stop (sh->sf->cls); + GAS_normalization_update_property(pg->test_address->ats_addr, &atsi, 1); + sh->sf->s_bulk_stop(sh->sf->cls); - pg->set_task = GNUNET_SCHEDULER_add_delayed (pg->frequency, - &set_prop_task, pg); + pg->set_task = GNUNET_SCHEDULER_add_delayed(pg->frequency, + &set_prop_task, pg); } @@ -659,35 +668,36 @@ set_prop_task (void *cls) * Set ats_property to 0 to find all pgs */ static struct PropertyGenerator * -find_prop_gen (unsigned int peer, unsigned int address, - uint32_t ats_property) +find_prop_gen(unsigned int peer, unsigned int address, + uint32_t ats_property) { struct PropertyGenerator *cur; + for (cur = prop_gen_head; NULL != cur; cur = cur->next) if ((cur->peer == peer) && (cur->address_id == address)) - { - if ((cur->ats_property == ats_property) || (0 == ats_property)) - return cur; - } + { + if ((cur->ats_property == ats_property) || (0 == ats_property)) + return cur; + } return NULL; } void -GNUNET_ATS_solver_generate_property_stop (struct PropertyGenerator *pg) +GNUNET_ATS_solver_generate_property_stop(struct PropertyGenerator *pg) { - GNUNET_CONTAINER_DLL_remove (prop_gen_head, prop_gen_tail, pg); + GNUNET_CONTAINER_DLL_remove(prop_gen_head, prop_gen_tail, pg); if (NULL != pg->set_task) - { - GNUNET_SCHEDULER_cancel (pg->set_task); - pg->set_task = NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Removing old up preference generator peer [%u] address [%u] `%s'\n", - pg->peer, pg->address_id, - GNUNET_ATS_print_property_type(pg->ats_property)); + { + GNUNET_SCHEDULER_cancel(pg->set_task); + pg->set_task = NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Removing old up preference generator peer [%u] address [%u] `%s'\n", + pg->peer, pg->address_id, + GNUNET_ATS_print_property_type(pg->ats_property)); - GNUNET_free (pg); + GNUNET_free(pg); } @@ -708,21 +718,21 @@ GNUNET_ATS_solver_generate_property_stop (struct PropertyGenerator *pg) * @return the property generator */ struct PropertyGenerator * -GNUNET_ATS_solver_generate_property_start (unsigned int peer, - unsigned int address_id, - struct TestPeer *test_peer, - struct TestAddress *test_address, - enum GeneratorType type, - long int base_value, - long int value_rate, - struct GNUNET_TIME_Relative period, - struct GNUNET_TIME_Relative frequency, - uint32_t ats_property) +GNUNET_ATS_solver_generate_property_start(unsigned int peer, + unsigned int address_id, + struct TestPeer *test_peer, + struct TestAddress *test_address, + enum GeneratorType type, + long int base_value, + long int value_rate, + struct GNUNET_TIME_Relative period, + struct GNUNET_TIME_Relative frequency, + uint32_t ats_property) { struct PropertyGenerator *pg; - pg = GNUNET_new (struct PropertyGenerator); - GNUNET_CONTAINER_DLL_insert (prop_gen_head, prop_gen_tail, pg); + pg = GNUNET_new(struct PropertyGenerator); + GNUNET_CONTAINER_DLL_insert(prop_gen_head, prop_gen_tail, pg); pg->type = type; pg->peer = peer; pg->test_address = test_address; @@ -735,44 +745,49 @@ GNUNET_ATS_solver_generate_property_start (unsigned int peer, pg->frequency = frequency; pg->time_start = GNUNET_TIME_absolute_get(); - switch (type) { + switch (type) + { case GNUNET_ATS_TEST_TG_CONSTANT: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up %s property generator peer [%u] address [%u] `%s'"\ - "max %u Bips\n", - print_generator_type(type), pg->peer, pg->address_id, - GNUNET_ATS_print_property_type (ats_property), - base_value); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up %s property generator peer [%u] address [%u] `%s'" \ + "max %u Bips\n", + print_generator_type(type), pg->peer, pg->address_id, + GNUNET_ATS_print_property_type(ats_property), + base_value); break; + case GNUNET_ATS_TEST_TG_LINEAR: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up %s property generator peer [%u] address [%u] `%s' " \ - "min %u Bips max %u Bips\n", - print_generator_type(type), pg->peer, pg->address_id, - GNUNET_ATS_print_property_type(ats_property), - base_value, value_rate); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up %s property generator peer [%u] address [%u] `%s' " \ + "min %u Bips max %u Bips\n", + print_generator_type(type), pg->peer, pg->address_id, + GNUNET_ATS_print_property_type(ats_property), + base_value, value_rate); break; + case GNUNET_ATS_TEST_TG_SINUS: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up %s property generator peer [%u] address [%u] `%s' "\ - "baserate %u Bips, amplitude %u Bps\n", - print_generator_type(type), pg->peer, pg->address_id, - GNUNET_ATS_print_property_type(ats_property), - base_value, value_rate); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up %s property generator peer [%u] address [%u] `%s' " \ + "baserate %u Bips, amplitude %u Bps\n", + print_generator_type(type), pg->peer, pg->address_id, + GNUNET_ATS_print_property_type(ats_property), + base_value, value_rate); break; + case GNUNET_ATS_TEST_TG_RANDOM: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Setting up %s property generator peer [%u] address [%u] `%s' "\ - "min %u Bips max %u Bps\n", - print_generator_type(type), pg->peer, pg->address_id, - GNUNET_ATS_print_property_type(ats_property), - base_value, value_rate); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Setting up %s property generator peer [%u] address [%u] `%s' " \ + "min %u Bips max %u Bps\n", + print_generator_type(type), pg->peer, pg->address_id, + GNUNET_ATS_print_property_type(ats_property), + base_value, value_rate); break; + default: break; - } + } - pg->set_task = GNUNET_SCHEDULER_add_now (&set_prop_task, pg); + pg->set_task = GNUNET_SCHEDULER_add_now(&set_prop_task, pg); return pg; } @@ -781,16 +796,17 @@ GNUNET_ATS_solver_generate_property_start (unsigned int peer, * Stop all preferences generators */ void -GNUNET_ATS_solver_generate_property_stop_all () +GNUNET_ATS_solver_generate_property_stop_all() { struct PropertyGenerator *cur; struct PropertyGenerator *next; + next = prop_gen_head; for (cur = next; NULL != cur; cur = next) - { + { next = cur->next; - GNUNET_ATS_solver_generate_property_stop (cur); - } + GNUNET_ATS_solver_generate_property_stop(cur); + } } @@ -802,65 +818,70 @@ static struct PreferenceGenerator *pref_gen_tail; static double -get_preference (struct PreferenceGenerator *pg) +get_preference(struct PreferenceGenerator *pg) { struct GNUNET_TIME_Relative time_delta; double delta_value; double pref_value; /* Calculate the current preference value */ - switch (pg->type) { + switch (pg->type) + { case GNUNET_ATS_TEST_TG_CONSTANT: pref_value = pg->base_value; break; + case GNUNET_ATS_TEST_TG_LINEAR: time_delta = GNUNET_TIME_absolute_get_duration(pg->time_start); /* Calculate point of time in the current period */ time_delta.rel_value_us = time_delta.rel_value_us % - pg->duration_period.rel_value_us; - delta_value = ((double) time_delta.rel_value_us / - pg->duration_period.rel_value_us) * (pg->max_value - pg->base_value); + pg->duration_period.rel_value_us; + delta_value = ((double)time_delta.rel_value_us / + pg->duration_period.rel_value_us) * (pg->max_value - pg->base_value); if ((pg->max_value < pg->base_value) && ((pg->max_value - pg->base_value) > pg->base_value)) - { - /* This will cause an underflow */ - GNUNET_break (0); - } + { + /* This will cause an underflow */ + GNUNET_break(0); + } pref_value = pg->base_value + delta_value; break; + case GNUNET_ATS_TEST_TG_RANDOM: - delta_value = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - 10000 * (pg->max_value - pg->base_value)) / 10000; + delta_value = (double)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + 10000 * (pg->max_value - pg->base_value)) / 10000; pref_value = pg->base_value + delta_value; break; + case GNUNET_ATS_TEST_TG_SINUS: time_delta = GNUNET_TIME_absolute_get_duration(pg->time_start); /* Calculate point of time in the current period */ time_delta.rel_value_us = time_delta.rel_value_us % - pg->duration_period.rel_value_us; + pg->duration_period.rel_value_us; if ((pg->max_value - pg->base_value) > pg->base_value) - { - /* This will cause an underflow for second half of sinus period, - * will be detected in general when experiments are loaded */ - GNUNET_break (0); - } + { + /* This will cause an underflow for second half of sinus period, + * will be detected in general when experiments are loaded */ + GNUNET_break(0); + } delta_value = (pg->max_value - pg->base_value) * - sin ( (2 * M_PI) / ((double) pg->duration_period.rel_value_us) * - time_delta.rel_value_us); + sin((2 * M_PI) / ((double)pg->duration_period.rel_value_us) * + time_delta.rel_value_us); pref_value = pg->base_value + delta_value; break; + default: pref_value = 0.0; break; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Current preference value is %f\n", - pref_value); + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Current preference value is %f\n", + pref_value); return pref_value; } static void -set_feedback_task (void *cls) +set_feedback_task(void *cls) { struct PreferenceGenerator *pg = cls; struct TestPeer *p; @@ -873,50 +894,52 @@ set_feedback_task (void *cls) pg->feedback_task = NULL; - if (NULL == (p = find_peer_by_id (pg->peer))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Setting feedback for unknown peer %u\n", pg->peer); - return; - } + if (NULL == (p = find_peer_by_id(pg->peer))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Setting feedback for unknown peer %u\n", pg->peer); + return; + } switch (pg->kind) - { + { case GNUNET_ATS_PREFERENCE_BANDWIDTH: dur = GNUNET_TIME_absolute_get_duration(pg->feedback_last_bw_update); - bw_acc_in = dur.rel_value_us *pg->last_assigned_bw_in + pg->feedback_bw_in_acc; + bw_acc_in = dur.rel_value_us * pg->last_assigned_bw_in + pg->feedback_bw_in_acc; pg->feedback_bw_in_acc = 0; - bw_acc_out = dur.rel_value_us *pg->last_assigned_bw_out + pg->feedback_bw_out_acc; - p_new = get_preference (pg); - feedback = (p_new / pg->pref_bw_old) * (bw_acc_in + bw_acc_out) / - (2 *GNUNET_TIME_absolute_get_duration(pg->feedback_last).rel_value_us); + bw_acc_out = dur.rel_value_us * pg->last_assigned_bw_out + pg->feedback_bw_out_acc; + p_new = get_preference(pg); + feedback = (p_new / pg->pref_bw_old) * (bw_acc_in + bw_acc_out) / + (2 * GNUNET_TIME_absolute_get_duration(pg->feedback_last).rel_value_us); break; + case GNUNET_ATS_PREFERENCE_LATENCY: dur = GNUNET_TIME_absolute_get_duration(pg->feedback_last_delay_update); - delay_acc_in =dur.rel_value_us *pg->last_delay_value + pg->feedback_delay_acc; + delay_acc_in = dur.rel_value_us * pg->last_delay_value + pg->feedback_delay_acc; pg->feedback_delay_acc = 0; - p_new = get_preference (pg); - feedback = (p_new / pg->pref_latency_old) * (delay_acc_in) / - (GNUNET_TIME_absolute_get_duration(pg->feedback_last).rel_value_us); + p_new = get_preference(pg); + feedback = (p_new / pg->pref_latency_old) * (delay_acc_in) / + (GNUNET_TIME_absolute_get_duration(pg->feedback_last).rel_value_us); break; + default: - GNUNET_break (0); + GNUNET_break(0); feedback = 0.0; break; - } + } GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Giving feedback for peer [%u] for client %p pref %s of %.3f\n", - pg->peer, NULL + (pg->client_id), - GNUNET_ATS_print_preference_type (pg->kind), - feedback); + "Giving feedback for peer [%u] for client %p pref %s of %.3f\n", + pg->peer, NULL + (pg->client_id), + GNUNET_ATS_print_preference_type(pg->kind), + feedback); - sh->sf->s_feedback (sh->sf->cls, NULL + (pg->client_id), &p->peer_id, - pg->feedback_frequency, pg->kind, feedback); + sh->sf->s_feedback(sh->sf->cls, NULL + (pg->client_id), &p->peer_id, + pg->feedback_frequency, pg->kind, feedback); pg->feedback_last = GNUNET_TIME_absolute_get(); @@ -928,105 +951,111 @@ set_feedback_task (void *cls) pg->feedback_last_delay_update = GNUNET_TIME_absolute_get(); - pg->feedback_task = GNUNET_SCHEDULER_add_delayed (pg->feedback_frequency, - &set_feedback_task, pg); + pg->feedback_task = GNUNET_SCHEDULER_add_delayed(pg->feedback_frequency, + &set_feedback_task, pg); } static void -set_pref_task (void *cls) +set_pref_task(void *cls) { struct PreferenceGenerator *pg = cls; struct TestPeer *p; double pref_value; + pg->set_task = NULL; - if (NULL == (p = find_peer_by_id (pg->peer))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Setting preference for unknown peer %u\n", pg->peer); - return; - } + if (NULL == (p = find_peer_by_id(pg->peer))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Setting preference for unknown peer %u\n", pg->peer); + return; + } - pref_value = get_preference (pg); - switch (pg->kind) { + pref_value = get_preference(pg); + switch (pg->kind) + { case GNUNET_ATS_PREFERENCE_BANDWIDTH: pg->pref_bw_old = pref_value; break; + case GNUNET_ATS_PREFERENCE_LATENCY: pg->pref_latency_old = pref_value; break; + default: break; - } + } p->pref_abs[pg->kind] = pref_value; GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Setting preference for peer [%u] for client %p pref %s to %f\n", - pg->peer, NULL + (pg->client_id), - GNUNET_ATS_print_preference_type (pg->kind), pref_value); + "Setting preference for peer [%u] for client %p pref %s to %f\n", + pg->peer, NULL + (pg->client_id), + GNUNET_ATS_print_preference_type(pg->kind), pref_value); if (GNUNET_YES == opt_disable_normalization) - { - p->pref_abs[pg->kind] = pref_value; - p->pref_norm[pg->kind] = pref_value; - sh->sf->s_pref (sh->sf->cls, &p->peer_id, pg->kind, pref_value); - } + { + p->pref_abs[pg->kind] = pref_value; + p->pref_norm[pg->kind] = pref_value; + sh->sf->s_pref(sh->sf->cls, &p->peer_id, pg->kind, pref_value); + } else - update_preference (NULL + (pg->client_id), - &p->peer_id, - pg->kind, - pref_value); + update_preference(NULL + (pg->client_id), + &p->peer_id, + pg->kind, + pref_value); - pg->set_task = GNUNET_SCHEDULER_add_delayed (pg->frequency, - &set_pref_task, - pg); + pg->set_task = GNUNET_SCHEDULER_add_delayed(pg->frequency, + &set_pref_task, + pg); } static struct PreferenceGenerator * -find_pref_gen (unsigned int peer, enum GNUNET_ATS_PreferenceKind kind) +find_pref_gen(unsigned int peer, enum GNUNET_ATS_PreferenceKind kind) { struct PreferenceGenerator *cur; + for (cur = pref_gen_head; NULL != cur; cur = cur->next) if (cur->peer == peer) - { - if ((cur->kind == kind) || (GNUNET_ATS_PREFERENCE_END == kind)) - return cur; - } + { + if ((cur->kind == kind) || (GNUNET_ATS_PREFERENCE_END == kind)) + return cur; + } return NULL; } void -GNUNET_ATS_solver_generate_preferences_stop (struct PreferenceGenerator *pg) +GNUNET_ATS_solver_generate_preferences_stop(struct PreferenceGenerator *pg) { - GNUNET_CONTAINER_DLL_remove (pref_gen_head, pref_gen_tail, pg); + GNUNET_CONTAINER_DLL_remove(pref_gen_head, pref_gen_tail, pg); if (NULL != pg->feedback_task) - { - GNUNET_SCHEDULER_cancel (pg->feedback_task); - pg->feedback_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(pg->feedback_task); + pg->feedback_task = NULL; + } if (NULL != pg->set_task) - { - GNUNET_SCHEDULER_cancel (pg->set_task); - pg->set_task = NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Removing old up preference generator peer [%u] `%s'\n", - pg->peer, GNUNET_ATS_print_preference_type(pg->kind)); + { + GNUNET_SCHEDULER_cancel(pg->set_task); + pg->set_task = NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Removing old up preference generator peer [%u] `%s'\n", + pg->peer, GNUNET_ATS_print_preference_type(pg->kind)); - GNUNET_free (pg); + GNUNET_free(pg); } static struct TestAddress* -find_active_address (struct TestPeer *p) +find_active_address(struct TestPeer *p) { struct TestAddress *cur; + for (cur = p->addr_head; NULL != cur; cur = cur->next) if (GNUNET_YES == cur->ats_addr->active) return cur; @@ -1051,30 +1080,30 @@ find_active_address (struct TestPeer *p) * @return the preference generator */ struct PreferenceGenerator * -GNUNET_ATS_solver_generate_preferences_start (unsigned int peer, - unsigned int address_id, - unsigned int client_id, - enum GeneratorType type, - long int base_value, - long int value_rate, - struct GNUNET_TIME_Relative period, - struct GNUNET_TIME_Relative frequency, - enum GNUNET_ATS_PreferenceKind kind, - struct GNUNET_TIME_Relative feedback_frequency) +GNUNET_ATS_solver_generate_preferences_start(unsigned int peer, + unsigned int address_id, + unsigned int client_id, + enum GeneratorType type, + long int base_value, + long int value_rate, + struct GNUNET_TIME_Relative period, + struct GNUNET_TIME_Relative frequency, + enum GNUNET_ATS_PreferenceKind kind, + struct GNUNET_TIME_Relative feedback_frequency) { struct PreferenceGenerator *pg; struct TestPeer *p; - if (NULL == (p = find_peer_by_id (peer))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Starting preference for unknown peer %u\n", peer); - return NULL; - } - - pg = GNUNET_new (struct PreferenceGenerator); - GNUNET_CONTAINER_DLL_insert (pref_gen_head, pref_gen_tail, pg); + if (NULL == (p = find_peer_by_id(peer))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Starting preference for unknown peer %u\n", peer); + return NULL; + } + + pg = GNUNET_new(struct PreferenceGenerator); + GNUNET_CONTAINER_DLL_insert(pref_gen_head, pref_gen_tail, pg); pg->type = type; pg->peer = peer; pg->client_id = client_id; @@ -1086,54 +1115,59 @@ GNUNET_ATS_solver_generate_preferences_start (unsigned int peer, pg->time_start = GNUNET_TIME_absolute_get(); pg->feedback_frequency = feedback_frequency; - switch (type) { + switch (type) + { case GNUNET_ATS_TEST_TG_CONSTANT: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Setting up %s preference generator peer [%u] `%s' max %u Bips\n", - print_generator_type (type), pg->peer, - GNUNET_ATS_print_preference_type(kind), - base_value); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Setting up %s preference generator peer [%u] `%s' max %u Bips\n", + print_generator_type(type), pg->peer, + GNUNET_ATS_print_preference_type(kind), + base_value); break; + case GNUNET_ATS_TEST_TG_LINEAR: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Setting up %s preference generator peer [%u] `%s' min %u Bips max %u Bips\n", - print_generator_type (type), pg->peer, GNUNET_ATS_print_preference_type(kind), - base_value, value_rate); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Setting up %s preference generator peer [%u] `%s' min %u Bips max %u Bips\n", + print_generator_type(type), pg->peer, GNUNET_ATS_print_preference_type(kind), + base_value, value_rate); break; + case GNUNET_ATS_TEST_TG_SINUS: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Setting up %s preference generator peer [%u] `%s' baserate %u Bips, amplitude %u Bps\n", - print_generator_type (type), pg->peer, GNUNET_ATS_print_preference_type(kind), - base_value, value_rate); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Setting up %s preference generator peer [%u] `%s' baserate %u Bips, amplitude %u Bps\n", + print_generator_type(type), pg->peer, GNUNET_ATS_print_preference_type(kind), + base_value, value_rate); break; + case GNUNET_ATS_TEST_TG_RANDOM: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Setting up %s preference generator peer [%u] `%s' min %u Bips max %u Bps\n", - print_generator_type (type), pg->peer, GNUNET_ATS_print_preference_type(kind), - base_value, value_rate); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Setting up %s preference generator peer [%u] `%s' min %u Bips max %u Bps\n", + print_generator_type(type), pg->peer, GNUNET_ATS_print_preference_type(kind), + base_value, value_rate); break; + default: break; - } + } - pg->set_task = GNUNET_SCHEDULER_add_now (&set_pref_task, pg); + pg->set_task = GNUNET_SCHEDULER_add_now(&set_pref_task, pg); if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us != feedback_frequency.rel_value_us) - { - struct TestAddress * addr = find_active_address(p); - - pg->last_assigned_bw_in = p->assigned_bw_in; - pg->last_assigned_bw_out = p->assigned_bw_out; - pg->feedback_bw_in_acc = 0; - pg->feedback_bw_out_acc = 0; - pg->last_delay_value = addr->prop_norm[GNUNET_ATS_QUALITY_NET_DELAY]; - pg->feedback_delay_acc = 0; - - pg->feedback_last_bw_update = GNUNET_TIME_absolute_get(); - pg->feedback_last_delay_update = GNUNET_TIME_absolute_get(); - pg->feedback_last = GNUNET_TIME_absolute_get(); - pg->feedback_task = GNUNET_SCHEDULER_add_delayed (feedback_frequency, - &set_feedback_task, pg); - } + { + struct TestAddress * addr = find_active_address(p); + + pg->last_assigned_bw_in = p->assigned_bw_in; + pg->last_assigned_bw_out = p->assigned_bw_out; + pg->feedback_bw_in_acc = 0; + pg->feedback_bw_out_acc = 0; + pg->last_delay_value = addr->prop_norm[GNUNET_ATS_QUALITY_NET_DELAY]; + pg->feedback_delay_acc = 0; + + pg->feedback_last_bw_update = GNUNET_TIME_absolute_get(); + pg->feedback_last_delay_update = GNUNET_TIME_absolute_get(); + pg->feedback_last = GNUNET_TIME_absolute_get(); + pg->feedback_task = GNUNET_SCHEDULER_add_delayed(feedback_frequency, + &set_feedback_task, pg); + } return pg; } @@ -1144,16 +1178,17 @@ GNUNET_ATS_solver_generate_preferences_start (unsigned int peer, * Stop all preferences generators */ void -GNUNET_ATS_solver_generate_preferences_stop_all () +GNUNET_ATS_solver_generate_preferences_stop_all() { struct PreferenceGenerator *cur; struct PreferenceGenerator *next; + next = pref_gen_head; for (cur = next; NULL != cur; cur = next) - { + { next = cur->next; GNUNET_ATS_solver_generate_preferences_stop(cur); - } + } } @@ -1162,37 +1197,47 @@ GNUNET_ATS_solver_generate_preferences_stop_all () * Experiments */ static const char * -print_op (enum OperationType op) +print_op(enum OperationType op) { - switch (op) { + switch (op) + { case SOLVER_OP_ADD_ADDRESS: return "ADD_ADDRESS"; + case SOLVER_OP_DEL_ADDRESS: return "DEL_ADDRESS"; + case SOLVER_OP_START_SET_PREFERENCE: return "START_SET_PREFERENCE"; + case SOLVER_OP_STOP_SET_PREFERENCE: return "STOP_STOP_PREFERENCE"; + case SOLVER_OP_START_SET_PROPERTY: return "START_SET_PROPERTY"; + case SOLVER_OP_STOP_SET_PROPERTY: return "STOP_SET_PROPERTY"; + case SOLVER_OP_START_REQUEST: return "START_REQUEST"; + case SOLVER_OP_STOP_REQUEST: return "STOP_REQUEST"; + default: break; - } + } return ""; } static struct Experiment * -create_experiment () +create_experiment() { struct Experiment *e; - e = GNUNET_new (struct Experiment); + + e = GNUNET_new(struct Experiment); e->name = NULL; e->start = NULL; e->total_duration = GNUNET_TIME_UNIT_ZERO; @@ -1201,7 +1246,7 @@ create_experiment () static void -free_experiment (struct Experiment *e) +free_experiment(struct Experiment *e) { struct Episode *cur; struct Episode *next; @@ -1210,237 +1255,238 @@ free_experiment (struct Experiment *e) next = e->start; for (cur = next; NULL != cur; cur = next) - { - next = cur->next; - - next_o = cur->head; - for (cur_o = next_o; NULL != cur_o; cur_o = next_o) { - next_o = cur_o->next; - GNUNET_free_non_null (cur_o->address); - GNUNET_free_non_null (cur_o->plugin); - GNUNET_free (cur_o); + next = cur->next; + + next_o = cur->head; + for (cur_o = next_o; NULL != cur_o; cur_o = next_o) + { + next_o = cur_o->next; + GNUNET_free_non_null(cur_o->address); + GNUNET_free_non_null(cur_o->plugin); + GNUNET_free(cur_o); + } + GNUNET_free(cur); } - GNUNET_free (cur); - } - GNUNET_free_non_null (e->name); - GNUNET_free_non_null (e->log_prefix); - GNUNET_free_non_null (e->log_output_dir); - GNUNET_free_non_null (e->cfg_file); - GNUNET_free (e); + GNUNET_free_non_null(e->name); + GNUNET_free_non_null(e->log_prefix); + GNUNET_free_non_null(e->log_output_dir); + GNUNET_free_non_null(e->cfg_file); + GNUNET_free(e); } static int -load_op_add_address (struct GNUNET_ATS_TEST_Operation *o, - struct Episode *e, - int op_counter, - char *sec_name, - const struct GNUNET_CONFIGURATION_Handle *cfg) +load_op_add_address(struct GNUNET_ATS_TEST_Operation *o, + struct Episode *e, + int op_counter, + char *sec_name, + const struct GNUNET_CONFIGURATION_Handle *cfg) { char *op_name; char *op_network; /* peer pid */ GNUNET_asprintf(&op_name, "op-%u-peer-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->peer_id)) - { - fprintf (stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", - op_counter, "ADD_ADDRESS", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->peer_id)) + { + fprintf(stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", + op_counter, "ADD_ADDRESS", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* address pid */ GNUNET_asprintf(&op_name, "op-%u-address-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->address_id)) - { - fprintf (stderr, "Missing address-id in operation %u `%s' in episode `%s'\n", - op_counter, "ADD_ADDRESS", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->address_id)) + { + fprintf(stderr, "Missing address-id in operation %u `%s' in episode `%s'\n", + op_counter, "ADD_ADDRESS", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* plugin */ GNUNET_asprintf(&op_name, "op-%u-plugin", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, - sec_name, op_name, &o->plugin)) - { - fprintf (stderr, "Missing plugin in operation %u `%s' in episode `%s'\n", - op_counter, "ADD_ADDRESS", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &o->plugin)) + { + fprintf(stderr, "Missing plugin in operation %u `%s' in episode `%s'\n", + op_counter, "ADD_ADDRESS", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* address */ GNUNET_asprintf(&op_name, "op-%u-address", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, - sec_name, op_name, &o->address)) - { - fprintf (stderr, "Missing address in operation %u `%s' in episode `%s'\n", - op_counter, "ADD_ADDRESS", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &o->address)) + { + fprintf(stderr, "Missing address in operation %u `%s' in episode `%s'\n", + op_counter, "ADD_ADDRESS", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* session */ GNUNET_asprintf(&op_name, "op-%u-address-session", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->address_session)) - { - fprintf (stderr, "Missing address-session in operation %u `%s' in episode `%s'\n", - op_counter, "ADD_ADDRESS", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->address_session)) + { + fprintf(stderr, "Missing address-session in operation %u `%s' in episode `%s'\n", + op_counter, "ADD_ADDRESS", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* network */ GNUNET_asprintf(&op_name, "op-%u-address-network", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, - sec_name, op_name, &op_network)) - { - fprintf (stderr, "Missing address-network in operation %u `%s' in episode `%s'\n", - op_counter, "ADD_ADDRESS", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - else - { - GNUNET_STRINGS_utf8_toupper (op_network,op_network); - if (0 == strcmp(op_network, "UNSPECIFIED")) - { - o->address_network = GNUNET_NT_UNSPECIFIED; - } - else if (0 == strcmp(op_network, "LOOPBACK")) + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &op_network)) { - o->address_network = GNUNET_NT_LOOPBACK; - } - else if (0 == strcmp(op_network, "LAN")) - { - o->address_network = GNUNET_NT_LAN; - } - else if (0 == strcmp(op_network, "WAN")) - { - o->address_network = GNUNET_NT_WAN; - } - else if (0 == strcmp(op_network, "WLAN")) - { - o->address_network = GNUNET_NT_WLAN; + fprintf(stderr, "Missing address-network in operation %u `%s' in episode `%s'\n", + op_counter, "ADD_ADDRESS", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; } - else if (0 == strcmp(op_network, "BT")) + else { - o->address_network = GNUNET_NT_BT; + GNUNET_STRINGS_utf8_toupper(op_network, op_network); + if (0 == strcmp(op_network, "UNSPECIFIED")) + { + o->address_network = GNUNET_NT_UNSPECIFIED; + } + else if (0 == strcmp(op_network, "LOOPBACK")) + { + o->address_network = GNUNET_NT_LOOPBACK; + } + else if (0 == strcmp(op_network, "LAN")) + { + o->address_network = GNUNET_NT_LAN; + } + else if (0 == strcmp(op_network, "WAN")) + { + o->address_network = GNUNET_NT_WAN; + } + else if (0 == strcmp(op_network, "WLAN")) + { + o->address_network = GNUNET_NT_WLAN; + } + else if (0 == strcmp(op_network, "BT")) + { + o->address_network = GNUNET_NT_BT; + } + else + { + fprintf(stderr, "Invalid address-network in operation %u `%s' in episode `%s': `%s'\n", + op_counter, "ADD_ADDRESS", op_name, op_network); + GNUNET_free(op_network); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } } - else - { - fprintf (stderr, "Invalid address-network in operation %u `%s' in episode `%s': `%s'\n", - op_counter, "ADD_ADDRESS", op_name, op_network); - GNUNET_free (op_network); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - } - GNUNET_free (op_network); - GNUNET_free (op_name); + GNUNET_free(op_network); + GNUNET_free(op_name); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Found operation %s: [%llu:%llu] address `%s' plugin `%s' \n", - "ADD_ADDRESS", o->peer_id, o->address_id, o->address, o->plugin); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Found operation %s: [%llu:%llu] address `%s' plugin `%s' \n", + "ADD_ADDRESS", o->peer_id, o->address_id, o->address, o->plugin); return GNUNET_OK; } static int -load_op_del_address (struct GNUNET_ATS_TEST_Operation *o, - struct Episode *e, - int op_counter, - char *sec_name, - const struct GNUNET_CONFIGURATION_Handle *cfg) +load_op_del_address(struct GNUNET_ATS_TEST_Operation *o, + struct Episode *e, + int op_counter, + char *sec_name, + const struct GNUNET_CONFIGURATION_Handle *cfg) { char *op_name; + //char *op_network; /* peer pid */ GNUNET_asprintf(&op_name, "op-%u-peer-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->peer_id)) - { - fprintf (stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", - op_counter, "DEL_ADDRESS", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->peer_id)) + { + fprintf(stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", + op_counter, "DEL_ADDRESS", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* address pid */ GNUNET_asprintf(&op_name, "op-%u-address-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->address_id)) - { - fprintf (stderr, "Missing address-id in operation %u `%s' in episode `%s'\n", - op_counter, "DEL_ADDRESS", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->address_id)) + { + fprintf(stderr, "Missing address-id in operation %u `%s' in episode `%s'\n", + op_counter, "DEL_ADDRESS", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); #if 0 /* plugin */ GNUNET_asprintf(&op_name, "op-%u-plugin", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, - sec_name, op_name, &o->plugin)) - { - fprintf (stderr, "Missing plugin in operation %u `%s' in episode `%s'\n", - op_counter, "DEL_ADDRESS", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &o->plugin)) + { + fprintf(stderr, "Missing plugin in operation %u `%s' in episode `%s'\n", + op_counter, "DEL_ADDRESS", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* address */ GNUNET_asprintf(&op_name, "op-%u-address", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, - sec_name, op_name, &o->address)) - { - fprintf (stderr, "Missing address in operation %u `%s' in episode `%s'\n", - op_counter, "DEL_ADDRESS", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &o->address)) + { + fprintf(stderr, "Missing address in operation %u `%s' in episode `%s'\n", + op_counter, "DEL_ADDRESS", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* session */ GNUNET_asprintf(&op_name, "op-%u-address-session", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->address_session)) - { - fprintf (stderr, "Missing address-session in operation %u `%s' in episode `%s'\n", - op_counter, "DEL_ADDRESS", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->address_session)) + { + fprintf(stderr, "Missing address-session in operation %u `%s' in episode `%s'\n", + op_counter, "DEL_ADDRESS", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); #endif - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Found operation %s: [%llu:%llu] address `%s' plugin `%s' \n", - "DEL_ADDRESS", o->peer_id, o->address_id, o->address, o->plugin); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Found operation %s: [%llu:%llu] address `%s' plugin `%s' \n", + "DEL_ADDRESS", o->peer_id, o->address_id, o->address, o->plugin); return GNUNET_OK; } static enum GNUNET_ATS_Property -parse_preference_string (const char * str) +parse_preference_string(const char * str) { int c = 0; char *props[GNUNET_ATS_PreferenceCount] = GNUNET_ATS_PreferenceTypeString; @@ -1453,11 +1499,11 @@ parse_preference_string (const char * str) static int -load_op_start_set_preference (struct GNUNET_ATS_TEST_Operation *o, - struct Episode *e, - int op_counter, - char *sec_name, - const struct GNUNET_CONFIGURATION_Handle *cfg) +load_op_start_set_preference(struct GNUNET_ATS_TEST_Operation *o, + struct Episode *e, + int op_counter, + char *sec_name, + const struct GNUNET_CONFIGURATION_Handle *cfg) { char *op_name; char *type; @@ -1465,235 +1511,235 @@ load_op_start_set_preference (struct GNUNET_ATS_TEST_Operation *o, /* peer pid */ GNUNET_asprintf(&op_name, "op-%u-peer-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->peer_id)) - { - fprintf (stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", - op_counter, "START_SET_PREFERENCE", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->peer_id)) + { + fprintf(stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", + op_counter, "START_SET_PREFERENCE", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* address pid */ GNUNET_asprintf(&op_name, "op-%u-client-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->client_id)) - { - fprintf (stderr, "Missing client-id in operation %u `%s' in episode `%s'\n", - op_counter, "START_SET_PREFERENCE", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->client_id)) + { + fprintf(stderr, "Missing client-id in operation %u `%s' in episode `%s'\n", + op_counter, "START_SET_PREFERENCE", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* generator */ GNUNET_asprintf(&op_name, "op-%u-gen-type", op_counter); - if ( (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, - sec_name, op_name, &type)) ) - { - fprintf (stderr, "Missing type in operation %u `%s' in episode `%s'\n", - op_counter, "START_SET_PREFERENCE", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } + if ((GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &type))) + { + fprintf(stderr, "Missing type in operation %u `%s' in episode `%s'\n", + op_counter, "START_SET_PREFERENCE", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } /* Load arguments for set_rate, start_send, set_preference */ - if (0 == strcmp (type, "constant")) - { - o->gen_type = GNUNET_ATS_TEST_TG_CONSTANT; - } - else if (0 == strcmp (type, "linear")) - { - o->gen_type = GNUNET_ATS_TEST_TG_LINEAR; - } - else if (0 == strcmp (type, "sinus")) - { - o->gen_type = GNUNET_ATS_TEST_TG_SINUS; - } - else if (0 == strcmp (type, "random")) - { - o->gen_type = GNUNET_ATS_TEST_TG_RANDOM; - } + if (0 == strcmp(type, "constant")) + { + o->gen_type = GNUNET_ATS_TEST_TG_CONSTANT; + } + else if (0 == strcmp(type, "linear")) + { + o->gen_type = GNUNET_ATS_TEST_TG_LINEAR; + } + else if (0 == strcmp(type, "sinus")) + { + o->gen_type = GNUNET_ATS_TEST_TG_SINUS; + } + else if (0 == strcmp(type, "random")) + { + o->gen_type = GNUNET_ATS_TEST_TG_RANDOM; + } else - { - fprintf (stderr, "Invalid generator type %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (type); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (type); - GNUNET_free (op_name); + { + fprintf(stderr, "Invalid generator type %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(type); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(type); + GNUNET_free(op_name); /* Get base rate */ GNUNET_asprintf(&op_name, "op-%u-base-rate", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->base_rate)) - { - fprintf (stderr, "Missing base rate in operation %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->base_rate)) + { + fprintf(stderr, "Missing base rate in operation %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* Get max rate */ GNUNET_asprintf(&op_name, "op-%u-max-rate", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->max_rate)) - { - if ((GNUNET_ATS_TEST_TG_LINEAR == o->gen_type) || - (GNUNET_ATS_TEST_TG_RANDOM == o->gen_type) || - (GNUNET_ATS_TEST_TG_SINUS == o->gen_type)) + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->max_rate)) { - fprintf (stderr, "Missing max rate in operation %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (op_name); - return GNUNET_SYSERR; + if ((GNUNET_ATS_TEST_TG_LINEAR == o->gen_type) || + (GNUNET_ATS_TEST_TG_RANDOM == o->gen_type) || + (GNUNET_ATS_TEST_TG_SINUS == o->gen_type)) + { + fprintf(stderr, "Missing max rate in operation %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } } - } - GNUNET_free (op_name); + GNUNET_free(op_name); /* Get period */ GNUNET_asprintf(&op_name, "op-%u-period", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (cfg, - sec_name, op_name, &o->period)) - { - o->period = e->duration; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, + sec_name, op_name, &o->period)) + { + o->period = e->duration; + } + GNUNET_free(op_name); /* Get frequency */ GNUNET_asprintf(&op_name, "op-%u-frequency", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (cfg, - sec_name, op_name, &o->frequency)) - { - fprintf (stderr, "Missing frequency in operation %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, + sec_name, op_name, &o->frequency)) + { + fprintf(stderr, "Missing frequency in operation %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(op_name); return GNUNET_SYSERR; - } - GNUNET_free (op_name); + } + GNUNET_free(op_name); /* Get preference */ GNUNET_asprintf(&op_name, "op-%u-pref", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, - sec_name, op_name, &pref)) - { - fprintf (stderr, "Missing preference in operation %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &pref)) + { + fprintf(stderr, "Missing preference in operation %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(op_name); return GNUNET_SYSERR; - } + } if (0 == (o->pref_type = parse_preference_string(pref))) - { - fprintf (stderr, "Invalid preference in operation %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (op_name); - GNUNET_free (pref); + { + fprintf(stderr, "Invalid preference in operation %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(op_name); + GNUNET_free(pref); return GNUNET_SYSERR; - } - GNUNET_free (pref); - GNUNET_free (op_name); + } + GNUNET_free(pref); + GNUNET_free(op_name); /* Get feedback delay */ GNUNET_asprintf(&op_name, "op-%u-feedback_delay", op_counter); - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_time (cfg, - sec_name, op_name, &o->feedback_delay)) - { - fprintf (stderr, "Using feedback delay %llu in operation %u `%s' in episode %u\n", - (long long unsigned int) o->feedback_delay.rel_value_us, - op_counter, op_name, e->id); - } + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_time(cfg, + sec_name, op_name, &o->feedback_delay)) + { + fprintf(stderr, "Using feedback delay %llu in operation %u `%s' in episode %u\n", + (long long unsigned int)o->feedback_delay.rel_value_us, + op_counter, op_name, e->id); + } else o->feedback_delay = GNUNET_TIME_UNIT_FOREVER_REL; - GNUNET_free (op_name); + GNUNET_free(op_name); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Found operation %s: [%llu:%llu]: %s = %llu\n", - "START_SET_PREFERENCE", o->peer_id, o->address_id, - GNUNET_ATS_print_preference_type(o->pref_type), o->base_rate); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Found operation %s: [%llu:%llu]: %s = %llu\n", + "START_SET_PREFERENCE", o->peer_id, o->address_id, + GNUNET_ATS_print_preference_type(o->pref_type), o->base_rate); return GNUNET_OK; } static int -load_op_stop_set_preference (struct GNUNET_ATS_TEST_Operation *o, - struct Episode *e, - int op_counter, - char *sec_name, - const struct GNUNET_CONFIGURATION_Handle *cfg) +load_op_stop_set_preference(struct GNUNET_ATS_TEST_Operation *o, + struct Episode *e, + int op_counter, + char *sec_name, + const struct GNUNET_CONFIGURATION_Handle *cfg) { char *op_name; char *pref; /* peer pid */ GNUNET_asprintf(&op_name, "op-%u-peer-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->peer_id)) - { - fprintf (stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", - op_counter, "STOP_SET_PREFERENCE", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->peer_id)) + { + fprintf(stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", + op_counter, "STOP_SET_PREFERENCE", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* address pid */ GNUNET_asprintf(&op_name, "op-%u-address-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->address_id)) - { - fprintf (stderr, "Missing address-id in operation %u `%s' in episode `%s'\n", - op_counter, "STOP_SET_PREFERENCE", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->address_id)) + { + fprintf(stderr, "Missing address-id in operation %u `%s' in episode `%s'\n", + op_counter, "STOP_SET_PREFERENCE", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* Get preference */ GNUNET_asprintf(&op_name, "op-%u-pref", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, - sec_name, op_name, &pref)) - { - fprintf (stderr, "Missing preference in operation %u `%s' in episode `%s'\n", - op_counter, "STOP_SET_PREFERENCE", op_name); - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &pref)) + { + fprintf(stderr, "Missing preference in operation %u `%s' in episode `%s'\n", + op_counter, "STOP_SET_PREFERENCE", op_name); + GNUNET_free(op_name); return GNUNET_SYSERR; - } + } if (0 == (o->pref_type = parse_preference_string(pref))) - { - fprintf (stderr, "Invalid preference in operation %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (op_name); - GNUNET_free (pref); + { + fprintf(stderr, "Invalid preference in operation %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(op_name); + GNUNET_free(pref); return GNUNET_SYSERR; - } - GNUNET_free (pref); - GNUNET_free (op_name); - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Found operation %s: [%llu:%llu]: %s\n", - "STOP_SET_PREFERENCE", o->peer_id, o->address_id, - GNUNET_ATS_print_preference_type(o->pref_type)); + } + GNUNET_free(pref); + GNUNET_free(op_name); + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Found operation %s: [%llu:%llu]: %s\n", + "STOP_SET_PREFERENCE", o->peer_id, o->address_id, + GNUNET_ATS_print_preference_type(o->pref_type)); return GNUNET_OK; } static enum GNUNET_ATS_Property -parse_property_string (const char *str) +parse_property_string(const char *str) { enum GNUNET_ATS_Property c; for (c = 0; c < GNUNET_ATS_PropertyCount; c++) if (0 == strcmp(str, - GNUNET_ATS_print_property_type (c))) + GNUNET_ATS_print_property_type(c))) return c; return 0; } @@ -1701,10 +1747,10 @@ parse_property_string (const char *str) static int load_op_start_set_property(struct GNUNET_ATS_TEST_Operation *o, - struct Episode *e, - int op_counter, - char *sec_name, - const struct GNUNET_CONFIGURATION_Handle *cfg) + struct Episode *e, + int op_counter, + char *sec_name, + const struct GNUNET_CONFIGURATION_Handle *cfg) { char *op_name; char *type; @@ -1712,268 +1758,268 @@ load_op_start_set_property(struct GNUNET_ATS_TEST_Operation *o, /* peer pid */ GNUNET_asprintf(&op_name, "op-%u-peer-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->peer_id)) - { - fprintf (stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", - op_counter, "START_SET_PROPERTY", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->peer_id)) + { + fprintf(stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", + op_counter, "START_SET_PROPERTY", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* address pid */ GNUNET_asprintf(&op_name, "op-%u-address-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->address_id)) - { - fprintf (stderr, "Missing address-id in operation %u `%s' in episode `%s'\n", - op_counter, "START_SET_PROPERTY", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->address_id)) + { + fprintf(stderr, "Missing address-id in operation %u `%s' in episode `%s'\n", + op_counter, "START_SET_PROPERTY", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* generator */ GNUNET_asprintf(&op_name, "op-%u-gen-type", op_counter); - if ( (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, - sec_name, op_name, &type)) ) - { - fprintf (stderr, "Missing type in operation %u `%s' in episode `%s'\n", - op_counter, "START_SET_PROPERTY", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } + if ((GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &type))) + { + fprintf(stderr, "Missing type in operation %u `%s' in episode `%s'\n", + op_counter, "START_SET_PROPERTY", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } /* Load arguments for set_rate, start_send, set_preference */ - if (0 == strcmp (type, "constant")) - { - o->gen_type = GNUNET_ATS_TEST_TG_CONSTANT; - } - else if (0 == strcmp (type, "linear")) - { - o->gen_type = GNUNET_ATS_TEST_TG_LINEAR; - } - else if (0 == strcmp (type, "sinus")) - { - o->gen_type = GNUNET_ATS_TEST_TG_SINUS; - } - else if (0 == strcmp (type, "random")) - { - o->gen_type = GNUNET_ATS_TEST_TG_RANDOM; - } + if (0 == strcmp(type, "constant")) + { + o->gen_type = GNUNET_ATS_TEST_TG_CONSTANT; + } + else if (0 == strcmp(type, "linear")) + { + o->gen_type = GNUNET_ATS_TEST_TG_LINEAR; + } + else if (0 == strcmp(type, "sinus")) + { + o->gen_type = GNUNET_ATS_TEST_TG_SINUS; + } + else if (0 == strcmp(type, "random")) + { + o->gen_type = GNUNET_ATS_TEST_TG_RANDOM; + } else - { - fprintf (stderr, "Invalid generator type %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (type); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (type); - GNUNET_free (op_name); + { + fprintf(stderr, "Invalid generator type %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(type); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(type); + GNUNET_free(op_name); /* Get base rate */ GNUNET_asprintf(&op_name, "op-%u-base-rate", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->base_rate)) - { - fprintf (stderr, "Missing base rate in operation %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->base_rate)) + { + fprintf(stderr, "Missing base rate in operation %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* Get max rate */ GNUNET_asprintf(&op_name, "op-%u-max-rate", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->max_rate)) - { - if ((GNUNET_ATS_TEST_TG_LINEAR == o->gen_type) || - (GNUNET_ATS_TEST_TG_RANDOM == o->gen_type) || - (GNUNET_ATS_TEST_TG_SINUS == o->gen_type)) + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->max_rate)) { - fprintf (stderr, "Missing max rate in operation %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (op_name); - return GNUNET_SYSERR; + if ((GNUNET_ATS_TEST_TG_LINEAR == o->gen_type) || + (GNUNET_ATS_TEST_TG_RANDOM == o->gen_type) || + (GNUNET_ATS_TEST_TG_SINUS == o->gen_type)) + { + fprintf(stderr, "Missing max rate in operation %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } } - } - GNUNET_free (op_name); + GNUNET_free(op_name); /* Get period */ GNUNET_asprintf(&op_name, "op-%u-period", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (cfg, - sec_name, op_name, &o->period)) - { - o->period = e->duration; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, + sec_name, op_name, &o->period)) + { + o->period = e->duration; + } + GNUNET_free(op_name); /* Get frequency */ GNUNET_asprintf(&op_name, "op-%u-frequency", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time (cfg, - sec_name, op_name, &o->frequency)) - { - fprintf (stderr, "Missing frequency in operation %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, + sec_name, op_name, &o->frequency)) + { + fprintf(stderr, "Missing frequency in operation %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(op_name); return GNUNET_SYSERR; - } - GNUNET_free (op_name); + } + GNUNET_free(op_name); /* Get preference */ GNUNET_asprintf(&op_name, "op-%u-property", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, - sec_name, op_name, &prop)) - { - fprintf (stderr, "Missing property in operation %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (op_name); - GNUNET_free_non_null (prop); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &prop)) + { + fprintf(stderr, "Missing property in operation %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(op_name); + GNUNET_free_non_null(prop); return GNUNET_SYSERR; - } + } if (0 == (o->prop_type = parse_property_string(prop))) - { - fprintf (stderr, "Invalid property in operation %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (op_name); - GNUNET_free (prop); + { + fprintf(stderr, "Invalid property in operation %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(op_name); + GNUNET_free(prop); return GNUNET_SYSERR; - } + } - GNUNET_free (prop); - GNUNET_free (op_name); + GNUNET_free(prop); + GNUNET_free(op_name); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Found operation %s: [%llu:%llu] %s = %llu\n", - "START_SET_PROPERTY", o->peer_id, o->address_id, - GNUNET_ATS_print_property_type (o->prop_type), o->base_rate); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Found operation %s: [%llu:%llu] %s = %llu\n", + "START_SET_PROPERTY", o->peer_id, o->address_id, + GNUNET_ATS_print_property_type(o->prop_type), o->base_rate); return GNUNET_OK; } static int -load_op_stop_set_property (struct GNUNET_ATS_TEST_Operation *o, - struct Episode *e, - int op_counter, - char *sec_name, - const struct GNUNET_CONFIGURATION_Handle *cfg) +load_op_stop_set_property(struct GNUNET_ATS_TEST_Operation *o, + struct Episode *e, + int op_counter, + char *sec_name, + const struct GNUNET_CONFIGURATION_Handle *cfg) { char *op_name; char *pref; /* peer pid */ GNUNET_asprintf(&op_name, "op-%u-peer-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->peer_id)) - { - fprintf (stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", - op_counter, "STOP_SET_PROPERTY", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->peer_id)) + { + fprintf(stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", + op_counter, "STOP_SET_PROPERTY", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* address pid */ GNUNET_asprintf(&op_name, "op-%u-address-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->address_id)) - { - fprintf (stderr, "Missing address-id in operation %u `%s' in episode `%s'\n", - op_counter, "STOP_SET_PROPERTY", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->address_id)) + { + fprintf(stderr, "Missing address-id in operation %u `%s' in episode `%s'\n", + op_counter, "STOP_SET_PROPERTY", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); /* Get property */ GNUNET_asprintf(&op_name, "op-%u-property", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, - sec_name, op_name, &pref)) - { - fprintf (stderr, "Missing property in operation %u `%s' in episode `%s'\n", - op_counter, "STOP_SET_PROPERTY", op_name); - GNUNET_free (op_name); - GNUNET_free_non_null (pref); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &pref)) + { + fprintf(stderr, "Missing property in operation %u `%s' in episode `%s'\n", + op_counter, "STOP_SET_PROPERTY", op_name); + GNUNET_free(op_name); + GNUNET_free_non_null(pref); return GNUNET_SYSERR; - } + } if (0 == (o->prop_type = parse_property_string(pref))) - { - fprintf (stderr, "Invalid property in operation %u `%s' in episode %u\n", - op_counter, op_name, e->id); - GNUNET_free (op_name); - GNUNET_free_non_null (pref); + { + fprintf(stderr, "Invalid property in operation %u `%s' in episode %u\n", + op_counter, op_name, e->id); + GNUNET_free(op_name); + GNUNET_free_non_null(pref); return GNUNET_SYSERR; - } + } - GNUNET_free (pref); - GNUNET_free (op_name); + GNUNET_free(pref); + GNUNET_free(op_name); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Found operation %s: [%llu:%llu] %s\n", - "STOP_SET_PROPERTY", o->peer_id, o->address_id, - GNUNET_ATS_print_property_type (o->prop_type)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Found operation %s: [%llu:%llu] %s\n", + "STOP_SET_PROPERTY", o->peer_id, o->address_id, + GNUNET_ATS_print_property_type(o->prop_type)); return GNUNET_OK; } static int -load_op_start_request (struct GNUNET_ATS_TEST_Operation *o, - struct Episode *e, - int op_counter, - char *sec_name, - const struct GNUNET_CONFIGURATION_Handle *cfg) +load_op_start_request(struct GNUNET_ATS_TEST_Operation *o, + struct Episode *e, + int op_counter, + char *sec_name, + const struct GNUNET_CONFIGURATION_Handle *cfg) { char *op_name; /* peer pid */ GNUNET_asprintf(&op_name, "op-%u-peer-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->peer_id)) - { - fprintf (stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", - op_counter, "START_REQUEST", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->peer_id)) + { + fprintf(stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", + op_counter, "START_REQUEST", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); return GNUNET_OK; } static int -load_op_stop_request (struct GNUNET_ATS_TEST_Operation *o, - struct Episode *e, - int op_counter, - char *sec_name, - const struct GNUNET_CONFIGURATION_Handle *cfg) +load_op_stop_request(struct GNUNET_ATS_TEST_Operation *o, + struct Episode *e, + int op_counter, + char *sec_name, + const struct GNUNET_CONFIGURATION_Handle *cfg) { char *op_name; /* peer pid */ GNUNET_asprintf(&op_name, "op-%u-peer-id", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number (cfg, - sec_name, op_name, &o->peer_id)) - { - fprintf (stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", - op_counter, "STOP_REQUEST", op_name); - GNUNET_free (op_name); - return GNUNET_SYSERR; - } - GNUNET_free (op_name); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_number(cfg, + sec_name, op_name, &o->peer_id)) + { + fprintf(stderr, "Missing peer-id in operation %u `%s' in episode `%s'\n", + op_counter, "STOP_REQUEST", op_name); + GNUNET_free(op_name); + return GNUNET_SYSERR; + } + GNUNET_free(op_name); return GNUNET_OK; } static int -load_episode (struct Experiment *e, struct Episode *cur, - struct GNUNET_CONFIGURATION_Handle *cfg) +load_episode(struct Experiment *e, struct Episode *cur, + struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_ATS_TEST_Operation *o; char *sec_name; @@ -1981,98 +2027,99 @@ load_episode (struct Experiment *e, struct Episode *cur, char *op; int op_counter = 0; int res; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "=== Parsing episode %u\n",cur->id); + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "=== Parsing episode %u\n", cur->id); GNUNET_asprintf(&sec_name, "episode-%u", cur->id); while (1) - { - /* Load operation */ - GNUNET_asprintf(&op_name, "op-%u-operation", op_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, - sec_name, op_name, &op)) { - GNUNET_free (op_name); - break; - } - o = GNUNET_new (struct GNUNET_ATS_TEST_Operation); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "==== Parsing operation %u: `%s'\n", - cur->id, op_name); + /* Load operation */ + GNUNET_asprintf(&op_name, "op-%u-operation", op_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, + sec_name, op_name, &op)) + { + GNUNET_free(op_name); + break; + } + o = GNUNET_new(struct GNUNET_ATS_TEST_Operation); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "==== Parsing operation %u: `%s'\n", + cur->id, op_name); - /* operations = set_rate, start_send, stop_send, set_preference */ - if (0 == strcmp (op, "address_add")) - { - o->type = SOLVER_OP_ADD_ADDRESS; - res = load_op_add_address (o, cur, - op_counter, sec_name, cfg); - } - else if (0 == strcmp (op, "address_del")) - { - o->type = SOLVER_OP_DEL_ADDRESS; - res = load_op_del_address (o, cur, - op_counter, sec_name, cfg); - } - else if (0 == strcmp (op, "start_set_property")) - { - o->type = SOLVER_OP_START_SET_PROPERTY; - res = load_op_start_set_property (o, cur, - op_counter, sec_name, cfg); - } - else if (0 == strcmp (op, "stop_set_property")) - { - o->type = SOLVER_OP_STOP_SET_PROPERTY; - res = load_op_stop_set_property (o, cur, - op_counter, sec_name, cfg); - } - else if (0 == strcmp (op, "start_set_preference")) - { - o->type = SOLVER_OP_START_SET_PREFERENCE; - res = load_op_start_set_preference (o, cur, - op_counter, sec_name, cfg); - } - else if (0 == strcmp (op, "stop_set_preference")) - { - o->type = SOLVER_OP_STOP_SET_PREFERENCE; - res = load_op_stop_set_preference (o, cur, - op_counter, sec_name, cfg); - } - else if (0 == strcmp (op, "start_request")) - { - o->type = SOLVER_OP_START_REQUEST; - res = load_op_start_request (o, cur, - op_counter, sec_name, cfg); - } - else if (0 == strcmp (op, "stop_request")) - { - o->type = SOLVER_OP_STOP_REQUEST; - res = load_op_stop_request(o, cur, - op_counter, sec_name, cfg); - } - else - { - fprintf (stderr, "Invalid operation %u `%s' in episode %u\n", - op_counter, op, cur->id); - res = GNUNET_SYSERR; - } + /* operations = set_rate, start_send, stop_send, set_preference */ + if (0 == strcmp(op, "address_add")) + { + o->type = SOLVER_OP_ADD_ADDRESS; + res = load_op_add_address(o, cur, + op_counter, sec_name, cfg); + } + else if (0 == strcmp(op, "address_del")) + { + o->type = SOLVER_OP_DEL_ADDRESS; + res = load_op_del_address(o, cur, + op_counter, sec_name, cfg); + } + else if (0 == strcmp(op, "start_set_property")) + { + o->type = SOLVER_OP_START_SET_PROPERTY; + res = load_op_start_set_property(o, cur, + op_counter, sec_name, cfg); + } + else if (0 == strcmp(op, "stop_set_property")) + { + o->type = SOLVER_OP_STOP_SET_PROPERTY; + res = load_op_stop_set_property(o, cur, + op_counter, sec_name, cfg); + } + else if (0 == strcmp(op, "start_set_preference")) + { + o->type = SOLVER_OP_START_SET_PREFERENCE; + res = load_op_start_set_preference(o, cur, + op_counter, sec_name, cfg); + } + else if (0 == strcmp(op, "stop_set_preference")) + { + o->type = SOLVER_OP_STOP_SET_PREFERENCE; + res = load_op_stop_set_preference(o, cur, + op_counter, sec_name, cfg); + } + else if (0 == strcmp(op, "start_request")) + { + o->type = SOLVER_OP_START_REQUEST; + res = load_op_start_request(o, cur, + op_counter, sec_name, cfg); + } + else if (0 == strcmp(op, "stop_request")) + { + o->type = SOLVER_OP_STOP_REQUEST; + res = load_op_stop_request(o, cur, + op_counter, sec_name, cfg); + } + else + { + fprintf(stderr, "Invalid operation %u `%s' in episode %u\n", + op_counter, op, cur->id); + res = GNUNET_SYSERR; + } - GNUNET_free (op); - GNUNET_free (op_name); + GNUNET_free(op); + GNUNET_free(op_name); - if (GNUNET_SYSERR == res) - { - GNUNET_free (o); - GNUNET_free (sec_name); - return GNUNET_SYSERR; - } + if (GNUNET_SYSERR == res) + { + GNUNET_free(o); + GNUNET_free(sec_name); + return GNUNET_SYSERR; + } - GNUNET_CONTAINER_DLL_insert_tail (cur->head,cur->tail, o); - op_counter++; - } - GNUNET_free (sec_name); + GNUNET_CONTAINER_DLL_insert_tail(cur->head, cur->tail, o); + op_counter++; + } + GNUNET_free(sec_name); return GNUNET_OK; } static int -load_episodes (struct Experiment *e, struct GNUNET_CONFIGURATION_Handle *cfg) +load_episodes(struct Experiment *e, struct GNUNET_CONFIGURATION_Handle *cfg) { int e_counter = 0; char *sec_name; @@ -2083,87 +2130,87 @@ load_episodes (struct Experiment *e, struct GNUNET_CONFIGURATION_Handle *cfg) e_counter = 0; last = NULL; while (1) - { - GNUNET_asprintf(&sec_name, "episode-%u", e_counter); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, - sec_name, "duration", &e_duration)) { - GNUNET_free (sec_name); - break; - } + GNUNET_asprintf(&sec_name, "episode-%u", e_counter); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, + sec_name, "duration", &e_duration)) + { + GNUNET_free(sec_name); + break; + } - cur = GNUNET_new (struct Episode); - cur->duration = e_duration; - cur->id = e_counter; + cur = GNUNET_new(struct Episode); + cur->duration = e_duration; + cur->id = e_counter; - if (GNUNET_OK != load_episode (e, cur, cfg)) - { - GNUNET_free (sec_name); - GNUNET_free (cur); - return GNUNET_SYSERR; - } + if (GNUNET_OK != load_episode(e, cur, cfg)) + { + GNUNET_free(sec_name); + GNUNET_free(cur); + return GNUNET_SYSERR; + } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Found episode %u with duration %s \n", - e_counter, - GNUNET_STRINGS_relative_time_to_string(cur->duration, GNUNET_YES)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Found episode %u with duration %s \n", + e_counter, + GNUNET_STRINGS_relative_time_to_string(cur->duration, GNUNET_YES)); - /* Update experiment */ - e->num_episodes ++; - e->total_duration = GNUNET_TIME_relative_add(e->total_duration, cur->duration); - /* Put in linked list */ - if (NULL == last) - e->start = cur; - else - last->next = cur; + /* Update experiment */ + e->num_episodes++; + e->total_duration = GNUNET_TIME_relative_add(e->total_duration, cur->duration); + /* Put in linked list */ + if (NULL == last) + e->start = cur; + else + last->next = cur; - GNUNET_free (sec_name); - e_counter ++; - last = cur; - } + GNUNET_free(sec_name); + e_counter++; + last = cur; + } return e_counter; } static void -timeout_experiment (void *cls) +timeout_experiment(void *cls) { struct Experiment *e = cls; e->experiment_timeout_task = NULL; - fprintf (stderr, "Experiment timeout!\n"); + fprintf(stderr, "Experiment timeout!\n"); if (NULL != e->episode_timeout_task) - { - GNUNET_SCHEDULER_cancel (e->episode_timeout_task); - e->episode_timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(e->episode_timeout_task); + e->episode_timeout_task = NULL; + } - e->e_done_cb (e, GNUNET_TIME_absolute_get_duration(e->start_time), - GNUNET_SYSERR); + e->e_done_cb(e, GNUNET_TIME_absolute_get_duration(e->start_time), + GNUNET_SYSERR); } struct ATS_Address * -create_ats_address (const struct GNUNET_PeerIdentity *peer, - const char *plugin_name, - const void *plugin_addr, - size_t plugin_addr_len, - uint32_t session_id, - uint32_t network) +create_ats_address(const struct GNUNET_PeerIdentity *peer, + const char *plugin_name, + const void *plugin_addr, + size_t plugin_addr_len, + uint32_t session_id, + uint32_t network) { struct ATS_Address *aa = NULL; - aa = GNUNET_malloc (sizeof (struct ATS_Address) + plugin_addr_len + strlen (plugin_name) + 1); - aa->atsi = GNUNET_new (struct GNUNET_ATS_Information); - aa->atsi[0].type = htonl (GNUNET_ATS_NETWORK_TYPE); - aa->atsi[0].value = htonl (network); + aa = GNUNET_malloc(sizeof(struct ATS_Address) + plugin_addr_len + strlen(plugin_name) + 1); + aa->atsi = GNUNET_new(struct GNUNET_ATS_Information); + aa->atsi[0].type = htonl(GNUNET_ATS_NETWORK_TYPE); + aa->atsi[0].value = htonl(network); aa->atsi_count = 1; aa->peer = *peer; aa->addr_len = plugin_addr_len; aa->addr = &aa[1]; - aa->plugin = (char *) &aa[1] + plugin_addr_len; - GNUNET_memcpy (&aa[1], plugin_addr, plugin_addr_len); - GNUNET_memcpy (aa->plugin, plugin_name, strlen (plugin_name) + 1); + aa->plugin = (char *)&aa[1] + plugin_addr_len; + GNUNET_memcpy(&aa[1], plugin_addr, plugin_addr_len); + GNUNET_memcpy(aa->plugin, plugin_name, strlen(plugin_name) + 1); aa->session_id = session_id; return aa; @@ -2172,522 +2219,529 @@ create_ats_address (const struct GNUNET_PeerIdentity *peer, static void -enforce_add_address (struct GNUNET_ATS_TEST_Operation *op) +enforce_add_address(struct GNUNET_ATS_TEST_Operation *op) { struct TestPeer *p; struct TestAddress *a; int c; - if (NULL == (p = find_peer_by_id (op->peer_id))) - { - p = GNUNET_new (struct TestPeer); - p->id = op->peer_id; - p->assigned_bw_in = 0; - p->assigned_bw_out = 0; - memset (&p->peer_id, op->peer_id, sizeof (p->peer_id)); - for (c = 0; c < GNUNET_ATS_PreferenceCount; c++) + if (NULL == (p = find_peer_by_id(op->peer_id))) { - p->pref_abs[c] = DEFAULT_ABS_PREFERENCE; - p->pref_norm[c] = DEFAULT_REL_PREFERENCE; - } + p = GNUNET_new(struct TestPeer); + p->id = op->peer_id; + p->assigned_bw_in = 0; + p->assigned_bw_out = 0; + memset(&p->peer_id, op->peer_id, sizeof(p->peer_id)); + for (c = 0; c < GNUNET_ATS_PreferenceCount; c++) + { + p->pref_abs[c] = DEFAULT_ABS_PREFERENCE; + p->pref_norm[c] = DEFAULT_REL_PREFERENCE; + } - GNUNET_CONTAINER_DLL_insert (peer_head, peer_tail, p); - } + GNUNET_CONTAINER_DLL_insert(peer_head, peer_tail, p); + } - if (NULL != (find_address_by_id (p, op->address_id))) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Duplicate address %u for peer %u\n", - op->address_id, op->peer_id); - return; - } + if (NULL != (find_address_by_id(p, op->address_id))) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Duplicate address %u for peer %u\n", + op->address_id, op->peer_id); + return; + } - a = GNUNET_new (struct TestAddress); + a = GNUNET_new(struct TestAddress); a->aid = op->address_id; a->network = op->address_network; - a->ats_addr = create_ats_address (&p->peer_id, op->plugin, op->address, - strlen (op->address) + 1, op->address_session, op->address_network); - memset (&p->peer_id, op->peer_id, sizeof (p->peer_id)); - GNUNET_CONTAINER_DLL_insert_tail (p->addr_head, p->addr_tail, a); + a->ats_addr = create_ats_address(&p->peer_id, op->plugin, op->address, + strlen(op->address) + 1, op->address_session, op->address_network); + memset(&p->peer_id, op->peer_id, sizeof(p->peer_id)); + GNUNET_CONTAINER_DLL_insert_tail(p->addr_head, p->addr_tail, a); for (c = 0; c < GNUNET_ATS_PropertyCount; c++) a->prop_norm[c] = DEFAULT_REL_QUALITY; - GNUNET_CONTAINER_multipeermap_put (sh->addresses, &p->peer_id, a->ats_addr, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + GNUNET_CONTAINER_multipeermap_put(sh->addresses, &p->peer_id, a->ats_addr, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Adding address %u for peer %u in network `%s'\n", - op->address_id, op->peer_id, GNUNET_NT_to_string(a->network)); - - sh->sf->s_add (sh->sf->cls, a->ats_addr, op->address_network); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Adding address %u for peer %u in network `%s'\n", + op->address_id, op->peer_id, GNUNET_NT_to_string(a->network)); + sh->sf->s_add(sh->sf->cls, a->ats_addr, op->address_network); } static void -enforce_del_address (struct GNUNET_ATS_TEST_Operation *op) +enforce_del_address(struct GNUNET_ATS_TEST_Operation *op) { struct TestPeer *p; struct TestAddress *a; struct PropertyGenerator *pg; - if (NULL == (p = find_peer_by_id (op->peer_id))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Deleting address for unknown peer %u\n", op->peer_id); - return; - } + if (NULL == (p = find_peer_by_id(op->peer_id))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Deleting address for unknown peer %u\n", op->peer_id); + return; + } - if (NULL == (a =find_address_by_id (p, op->address_id))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Deleting address for unknown peer %u\n", op->peer_id); - return; - } + if (NULL == (a = find_address_by_id(p, op->address_id))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Deleting address for unknown peer %u\n", op->peer_id); + return; + } - while (NULL != (pg = find_prop_gen (p->id, a->aid, 0))) - { - GNUNET_ATS_solver_generate_property_stop (pg); - } + while (NULL != (pg = find_prop_gen(p->id, a->aid, 0))) + { + GNUNET_ATS_solver_generate_property_stop(pg); + } - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (sh->addresses, - &p->peer_id, - a->ats_addr)); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Removing address %u for peer %u\n", - op->address_id, - op->peer_id); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(sh->addresses, + &p->peer_id, + a->ats_addr)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Removing address %u for peer %u\n", + op->address_id, + op->peer_id); - sh->sf->s_del (sh->sf->cls, a->ats_addr); + sh->sf->s_del(sh->sf->cls, a->ats_addr); if (NULL != l) - { - GNUNET_ATS_solver_logging_now (l); - } + { + GNUNET_ATS_solver_logging_now(l); + } GNUNET_CONTAINER_DLL_remove(p->addr_head, p->addr_tail, a); GNUNET_free_non_null(a->ats_addr->atsi); - GNUNET_free (a->ats_addr); - GNUNET_free (a); - + GNUNET_free(a->ats_addr); + GNUNET_free(a); } static void -enforce_start_property (struct GNUNET_ATS_TEST_Operation *op) +enforce_start_property(struct GNUNET_ATS_TEST_Operation *op) { struct PropertyGenerator *pg; struct TestPeer *p; struct TestAddress *a; - if (NULL != (pg = find_prop_gen (op->peer_id, op->address_id, op->prop_type))) - { - GNUNET_ATS_solver_generate_property_stop (pg); - GNUNET_free (pg); - } + if (NULL != (pg = find_prop_gen(op->peer_id, op->address_id, op->prop_type))) + { + GNUNET_ATS_solver_generate_property_stop(pg); + GNUNET_free(pg); + } - if (NULL == (p = find_peer_by_id (op->peer_id))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Starting property generation for unknown peer %u\n", op->peer_id); - return; - } + if (NULL == (p = find_peer_by_id(op->peer_id))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Starting property generation for unknown peer %u\n", op->peer_id); + return; + } - if (NULL == (a = find_address_by_id (p, op->address_id))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Setting property for unknown address %u\n", op->peer_id); - return; - } + if (NULL == (a = find_address_by_id(p, op->address_id))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Setting property for unknown address %u\n", op->peer_id); + return; + } - GNUNET_ATS_solver_generate_property_start (op->peer_id, - op->address_id, - p, a, - op->gen_type, - op->base_rate, - op->max_rate, - op->period, - op->frequency, - op->prop_type); + GNUNET_ATS_solver_generate_property_start(op->peer_id, + op->address_id, + p, a, + op->gen_type, + op->base_rate, + op->max_rate, + op->period, + op->frequency, + op->prop_type); } static void -enforce_stop_property (struct GNUNET_ATS_TEST_Operation *op) +enforce_stop_property(struct GNUNET_ATS_TEST_Operation *op) { struct PropertyGenerator *pg = find_prop_gen(op->peer_id, op->address_id, - op->prop_type); + op->prop_type); + if (NULL != pg) - { - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Stopping preference generation for peer %u address %u\n", op->peer_id, - op->address_id); - GNUNET_ATS_solver_generate_property_stop (pg); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Stopping preference generation for peer %u address %u\n", op->peer_id, + op->address_id); + GNUNET_ATS_solver_generate_property_stop(pg); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot find preference generator for peer %u address %u\n", - op->peer_id, op->address_id); - GNUNET_break (0); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot find preference generator for peer %u address %u\n", + op->peer_id, op->address_id); + GNUNET_break(0); + } } static void -enforce_start_preference (struct GNUNET_ATS_TEST_Operation *op) +enforce_start_preference(struct GNUNET_ATS_TEST_Operation *op) { struct PreferenceGenerator *pg; - if (NULL != (pg = find_pref_gen (op->peer_id, op->pref_type))) - { - GNUNET_ATS_solver_generate_preferences_stop (pg); - GNUNET_free (pg); - } - if (NULL == (find_peer_by_id (op->peer_id))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Starting preference generation for unknown peer %u\n", op->peer_id); - return; - } + if (NULL != (pg = find_pref_gen(op->peer_id, op->pref_type))) + { + GNUNET_ATS_solver_generate_preferences_stop(pg); + GNUNET_free(pg); + } - GNUNET_ATS_solver_generate_preferences_start (op->peer_id, - op->address_id, - op->client_id, - op->gen_type, - op->base_rate, - op->max_rate, - op->period, - op->frequency, - op->pref_type, - op->frequency); + if (NULL == (find_peer_by_id(op->peer_id))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Starting preference generation for unknown peer %u\n", op->peer_id); + return; + } + + GNUNET_ATS_solver_generate_preferences_start(op->peer_id, + op->address_id, + op->client_id, + op->gen_type, + op->base_rate, + op->max_rate, + op->period, + op->frequency, + op->pref_type, + op->frequency); } static void -enforce_stop_preference (struct GNUNET_ATS_TEST_Operation *op) +enforce_stop_preference(struct GNUNET_ATS_TEST_Operation *op) { struct PreferenceGenerator *pg = find_pref_gen(op->peer_id, - op->pref_type); + op->pref_type); + if (NULL != pg) - { - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Stopping property generation for peer %u address %u\n", op->peer_id, - op->address_id); - GNUNET_ATS_solver_generate_preferences_stop (pg); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Stopping property generation for peer %u address %u\n", op->peer_id, + op->address_id); + GNUNET_ATS_solver_generate_preferences_stop(pg); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot find preference generator for peer %u address %u\n", - op->peer_id, op->address_id); - GNUNET_break (0); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot find preference generator for peer %u address %u\n", + op->peer_id, op->address_id); + GNUNET_break(0); + } } static void -enforce_start_request (struct GNUNET_ATS_TEST_Operation *op) +enforce_start_request(struct GNUNET_ATS_TEST_Operation *op) { struct TestPeer *p; - if (NULL == (p = find_peer_by_id (op->peer_id))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Requesting address for unknown peer %u\n", op->peer_id); - return; - } + if (NULL == (p = find_peer_by_id(op->peer_id))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Requesting address for unknown peer %u\n", op->peer_id); + return; + } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Requesting address for peer %u\n", - op->peer_id); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Requesting address for peer %u\n", + op->peer_id); p->is_requested = GNUNET_YES; - sh->sf->s_get (sh->sf->cls, &p->peer_id); + sh->sf->s_get(sh->sf->cls, &p->peer_id); } static void -enforce_stop_request (struct GNUNET_ATS_TEST_Operation *op) +enforce_stop_request(struct GNUNET_ATS_TEST_Operation *op) { struct TestPeer *p; - if (NULL == (p = find_peer_by_id (op->peer_id))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Requesting address for unknown peer %u\n", op->peer_id); - return; - } + if (NULL == (p = find_peer_by_id(op->peer_id))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Requesting address for unknown peer %u\n", op->peer_id); + return; + } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Stop requesting address for peer %u\n", - op->peer_id); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Stop requesting address for peer %u\n", + op->peer_id); p->is_requested = GNUNET_NO; p->assigned_bw_in = 0; p->assigned_bw_out = 0; - sh->sf->s_get_stop (sh->sf->cls, &p->peer_id); + sh->sf->s_get_stop(sh->sf->cls, &p->peer_id); if (NULL != l) - { - GNUNET_ATS_solver_logging_now (l); - } - + { + GNUNET_ATS_solver_logging_now(l); + } } -static void enforce_episode (struct Episode *ep) +static void enforce_episode(struct Episode *ep) { struct GNUNET_ATS_TEST_Operation *cur; + for (cur = ep->head; NULL != cur; cur = cur->next) - { - switch (cur->type) { - case SOLVER_OP_ADD_ADDRESS: - fprintf (stderr, "Enforcing operation: %s [%llu:%llu]\n", - print_op (cur->type), cur->peer_id, cur->address_id); - enforce_add_address (cur); - break; - case SOLVER_OP_DEL_ADDRESS: - fprintf (stderr, "Enforcing operation: %s [%llu:%llu]\n", - print_op (cur->type), cur->peer_id, cur->address_id); - enforce_del_address (cur); - break; - case SOLVER_OP_START_SET_PROPERTY: - fprintf (stderr, "Enforcing operation: %s [%llu:%llu] == %llu\n", - print_op (cur->type), cur->peer_id, cur->address_id, cur->base_rate); - enforce_start_property (cur); - break; - case SOLVER_OP_STOP_SET_PROPERTY: - fprintf (stderr, "Enforcing operation: %s [%llu:%llu] == %llu\n", - print_op (cur->type), cur->peer_id, cur->address_id, cur->base_rate); - enforce_stop_property (cur); - break; - case SOLVER_OP_START_SET_PREFERENCE: - fprintf (stderr, "Enforcing operation: %s [%llu:%llu] == %llu\n", - print_op (cur->type), cur->peer_id, cur->address_id, cur->base_rate); - enforce_start_preference (cur); - break; - case SOLVER_OP_STOP_SET_PREFERENCE: - fprintf (stderr, "Enforcing operation: %s [%llu:%llu] == %llu\n", - print_op (cur->type), cur->peer_id, cur->address_id, cur->base_rate); - enforce_stop_preference (cur); - break; - case SOLVER_OP_START_REQUEST: - fprintf (stderr, "Enforcing operation: %s [%llu]\n", - print_op (cur->type), cur->peer_id); - enforce_start_request (cur); - break; - case SOLVER_OP_STOP_REQUEST: - fprintf (stderr, "Enforcing operation: %s [%llu]\n", - print_op (cur->type), cur->peer_id); - enforce_stop_request (cur); - break; - default: - break; - } - } + { + switch (cur->type) + { + case SOLVER_OP_ADD_ADDRESS: + fprintf(stderr, "Enforcing operation: %s [%llu:%llu]\n", + print_op(cur->type), cur->peer_id, cur->address_id); + enforce_add_address(cur); + break; + + case SOLVER_OP_DEL_ADDRESS: + fprintf(stderr, "Enforcing operation: %s [%llu:%llu]\n", + print_op(cur->type), cur->peer_id, cur->address_id); + enforce_del_address(cur); + break; + + case SOLVER_OP_START_SET_PROPERTY: + fprintf(stderr, "Enforcing operation: %s [%llu:%llu] == %llu\n", + print_op(cur->type), cur->peer_id, cur->address_id, cur->base_rate); + enforce_start_property(cur); + break; + + case SOLVER_OP_STOP_SET_PROPERTY: + fprintf(stderr, "Enforcing operation: %s [%llu:%llu] == %llu\n", + print_op(cur->type), cur->peer_id, cur->address_id, cur->base_rate); + enforce_stop_property(cur); + break; + + case SOLVER_OP_START_SET_PREFERENCE: + fprintf(stderr, "Enforcing operation: %s [%llu:%llu] == %llu\n", + print_op(cur->type), cur->peer_id, cur->address_id, cur->base_rate); + enforce_start_preference(cur); + break; + + case SOLVER_OP_STOP_SET_PREFERENCE: + fprintf(stderr, "Enforcing operation: %s [%llu:%llu] == %llu\n", + print_op(cur->type), cur->peer_id, cur->address_id, cur->base_rate); + enforce_stop_preference(cur); + break; + + case SOLVER_OP_START_REQUEST: + fprintf(stderr, "Enforcing operation: %s [%llu]\n", + print_op(cur->type), cur->peer_id); + enforce_start_request(cur); + break; + + case SOLVER_OP_STOP_REQUEST: + fprintf(stderr, "Enforcing operation: %s [%llu]\n", + print_op(cur->type), cur->peer_id); + enforce_stop_request(cur); + break; + + default: + break; + } + } } static void -timeout_episode (void *cls) +timeout_episode(void *cls) { struct Experiment *e = cls; e->episode_timeout_task = NULL; if (NULL != e->ep_done_cb) - e->ep_done_cb (e->cur); + e->ep_done_cb(e->cur); /* Scheduling next */ e->cur = e->cur->next; if (NULL == e->cur) - { - /* done */ - fprintf (stderr, "Last episode done!\n"); - if (NULL != e->experiment_timeout_task) { - GNUNET_SCHEDULER_cancel (e->experiment_timeout_task); - e->experiment_timeout_task = NULL; + /* done */ + fprintf(stderr, "Last episode done!\n"); + if (NULL != e->experiment_timeout_task) + { + GNUNET_SCHEDULER_cancel(e->experiment_timeout_task); + e->experiment_timeout_task = NULL; + } + e->e_done_cb(e, GNUNET_TIME_absolute_get_duration(e->start_time), GNUNET_OK); + return; } - e->e_done_cb (e, GNUNET_TIME_absolute_get_duration(e->start_time), GNUNET_OK); - return; - } - fprintf (stderr, "Running episode %u with timeout %s\n", - e->cur->id, - GNUNET_STRINGS_relative_time_to_string(e->cur->duration, GNUNET_YES)); - e->episode_timeout_task = GNUNET_SCHEDULER_add_delayed (e->cur->duration, - &timeout_episode, e); + fprintf(stderr, "Running episode %u with timeout %s\n", + e->cur->id, + GNUNET_STRINGS_relative_time_to_string(e->cur->duration, GNUNET_YES)); + e->episode_timeout_task = GNUNET_SCHEDULER_add_delayed(e->cur->duration, + &timeout_episode, e); enforce_episode(e->cur); - - } void -GNUNET_ATS_solvers_experimentation_run (struct Experiment *e, - GNUNET_ATS_TESTING_EpisodeDoneCallback ep_done_cb, - GNUNET_ATS_TESTING_ExperimentDoneCallback e_done_cb) +GNUNET_ATS_solvers_experimentation_run(struct Experiment *e, + GNUNET_ATS_TESTING_EpisodeDoneCallback ep_done_cb, + GNUNET_ATS_TESTING_ExperimentDoneCallback e_done_cb) { - fprintf (stderr, "Running experiment `%s' with timeout %s\n", e->name, - GNUNET_STRINGS_relative_time_to_string(e->max_duration, GNUNET_YES)); + fprintf(stderr, "Running experiment `%s' with timeout %s\n", e->name, + GNUNET_STRINGS_relative_time_to_string(e->max_duration, GNUNET_YES)); e->e_done_cb = e_done_cb; e->ep_done_cb = ep_done_cb; e->start_time = GNUNET_TIME_absolute_get(); /* Start total time out */ - e->experiment_timeout_task = GNUNET_SCHEDULER_add_delayed (e->max_duration, - &timeout_experiment, e); + e->experiment_timeout_task = GNUNET_SCHEDULER_add_delayed(e->max_duration, + &timeout_experiment, e); /* Start */ if (NULL == e->start) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } e->cur = e->start; - fprintf (stderr, "Running episode %u with timeout %s\n", - e->cur->id, - GNUNET_STRINGS_relative_time_to_string(e->cur->duration, GNUNET_YES)); - e->episode_timeout_task = GNUNET_SCHEDULER_add_delayed (e->cur->duration, - &timeout_episode, e); + fprintf(stderr, "Running episode %u with timeout %s\n", + e->cur->id, + GNUNET_STRINGS_relative_time_to_string(e->cur->duration, GNUNET_YES)); + e->episode_timeout_task = GNUNET_SCHEDULER_add_delayed(e->cur->duration, + &timeout_episode, e); enforce_episode(e->cur); - } void -GNUNET_ATS_solvers_experimentation_stop (struct Experiment *e) +GNUNET_ATS_solvers_experimentation_stop(struct Experiment *e) { if (NULL != e->experiment_timeout_task) - { - GNUNET_SCHEDULER_cancel (e->experiment_timeout_task); - e->experiment_timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(e->experiment_timeout_task); + e->experiment_timeout_task = NULL; + } if (NULL != e->episode_timeout_task) - { - GNUNET_SCHEDULER_cancel (e->episode_timeout_task); - e->episode_timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(e->episode_timeout_task); + e->episode_timeout_task = NULL; + } if (NULL != e->cfg) - { - GNUNET_CONFIGURATION_destroy(e->cfg); - e->cfg = NULL; - } - free_experiment (e); + { + GNUNET_CONFIGURATION_destroy(e->cfg); + e->cfg = NULL; + } + free_experiment(e); } struct Experiment * -GNUNET_ATS_solvers_experimentation_load (char *filename) +GNUNET_ATS_solvers_experimentation_load(char *filename) { struct Experiment *e; struct GNUNET_CONFIGURATION_Handle *cfg; + e = NULL; cfg = GNUNET_CONFIGURATION_create(); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, filename)) - { - fprintf (stderr, "Failed to load `%s'\n", filename); - GNUNET_CONFIGURATION_destroy (cfg); - return NULL; - } + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load(cfg, filename)) + { + fprintf(stderr, "Failed to load `%s'\n", filename); + GNUNET_CONFIGURATION_destroy(cfg); + return NULL; + } - e = create_experiment (); + e = create_experiment(); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, "experiment", - "name", &e->name)) - { - fprintf (stderr, "Invalid %s \n", "name"); - free_experiment (e); - return NULL; - } + "name", &e->name)) + { + fprintf(stderr, "Invalid %s \n", "name"); + free_experiment(e); + return NULL; + } else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Experiment name: `%s'\n", e->name); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Experiment name: `%s'\n", e->name); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, "experiment", - "log_prefix", &e->log_prefix)) - { - fprintf (stderr, "Invalid %s \n", "log_prefix"); - free_experiment (e); - return NULL; - } + "log_prefix", &e->log_prefix)) + { + fprintf(stderr, "Invalid %s \n", "log_prefix"); + free_experiment(e); + return NULL; + } else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Experiment logging prefix: `%s'\n", - e->log_prefix); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Experiment logging prefix: `%s'\n", + e->log_prefix); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_filename (cfg, "experiment", - "log_output_dir", &e->log_output_dir)) - { - e->log_output_dir = NULL; - } + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_filename(cfg, "experiment", + "log_output_dir", &e->log_output_dir)) + { + e->log_output_dir = NULL; + } else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Experiment logging output directory: `%s'\n", - e->log_output_dir); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Experiment logging output directory: `%s'\n", + e->log_output_dir); if (GNUNET_SYSERR == (e->log_append_time_stamp = GNUNET_CONFIGURATION_get_value_yesno(cfg, - "experiment", "log_append_time_stamp"))) + "experiment", "log_append_time_stamp"))) e->log_append_time_stamp = GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Experiment logging append timestamp: `%s'\n", - (GNUNET_YES == e->log_append_time_stamp) ? "yes" : "no"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Experiment logging append timestamp: `%s'\n", + (GNUNET_YES == e->log_append_time_stamp) ? "yes" : "no"); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_filename (cfg, "experiment", - "cfg_file", &e->cfg_file)) - { - fprintf (stderr, "Invalid %s \n", "cfg_file"); - free_experiment (e); - return NULL; - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Experiment configuration: `%s'\n", e->cfg_file); - e->cfg = GNUNET_CONFIGURATION_create(); - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (e->cfg, e->cfg_file)) + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_filename(cfg, "experiment", + "cfg_file", &e->cfg_file)) { - fprintf (stderr, "Invalid configuration %s \n", "cfg_file"); - free_experiment (e); + fprintf(stderr, "Invalid %s \n", "cfg_file"); + free_experiment(e); return NULL; } - - } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Experiment configuration: `%s'\n", e->cfg_file); + e->cfg = GNUNET_CONFIGURATION_create(); + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load(e->cfg, e->cfg_file)) + { + fprintf(stderr, "Invalid configuration %s \n", "cfg_file"); + free_experiment(e); + return NULL; + } + } if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, "experiment", - "log_freq", &e->log_freq)) - { - fprintf (stderr, "Invalid %s \n", "log_freq"); - free_experiment (e); - return NULL; - } + "log_freq", &e->log_freq)) + { + fprintf(stderr, "Invalid %s \n", "log_freq"); + free_experiment(e); + return NULL; + } else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Experiment logging frequency: `%s'\n", - GNUNET_STRINGS_relative_time_to_string (e->log_freq, GNUNET_YES)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Experiment logging frequency: `%s'\n", + GNUNET_STRINGS_relative_time_to_string(e->log_freq, GNUNET_YES)); if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_time(cfg, "experiment", - "max_duration", &e->max_duration)) - { - fprintf (stderr, "Invalid %s", "max_duration"); - free_experiment (e); - return NULL; - } + "max_duration", &e->max_duration)) + { + fprintf(stderr, "Invalid %s", "max_duration"); + free_experiment(e); + return NULL; + } else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Experiment duration: `%s'\n", - GNUNET_STRINGS_relative_time_to_string (e->max_duration, GNUNET_YES)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Experiment duration: `%s'\n", + GNUNET_STRINGS_relative_time_to_string(e->max_duration, GNUNET_YES)); - if (GNUNET_SYSERR == load_episodes (e, cfg)) - { - GNUNET_ATS_solvers_experimentation_stop (e); - GNUNET_CONFIGURATION_destroy (cfg); - e = NULL; - fprintf (stderr, "Failed to load experiment\n"); - return NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Loaded %u episodes with total duration %s\n", - e->num_episodes, - GNUNET_STRINGS_relative_time_to_string (e->total_duration, GNUNET_YES)); - - GNUNET_CONFIGURATION_destroy (cfg); + if (GNUNET_SYSERR == load_episodes(e, cfg)) + { + GNUNET_ATS_solvers_experimentation_stop(e); + GNUNET_CONFIGURATION_destroy(cfg); + e = NULL; + fprintf(stderr, "Failed to load experiment\n"); + return NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Loaded %u episodes with total duration %s\n", + e->num_episodes, + GNUNET_STRINGS_relative_time_to_string(e->total_duration, GNUNET_YES)); + + GNUNET_CONFIGURATION_destroy(cfg); return e; } @@ -2698,33 +2752,34 @@ GNUNET_ATS_solvers_experimentation_load (char *filename) */ static int -free_all_it (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +free_all_it(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct ATS_Address *address = value; - GNUNET_break (GNUNET_OK == GNUNET_CONTAINER_multipeermap_remove (sh->env.addresses, - key, value)); - GNUNET_free (address); + + GNUNET_break(GNUNET_OK == GNUNET_CONTAINER_multipeermap_remove(sh->env.addresses, + key, value)); + GNUNET_free(address); return GNUNET_OK; } void -GNUNET_ATS_solvers_solver_stop (struct SolverHandle *sh) +GNUNET_ATS_solvers_solver_stop(struct SolverHandle *sh) { - GNUNET_STATISTICS_destroy ((struct GNUNET_STATISTICS_Handle *) sh->env.stats, - GNUNET_NO); - GNUNET_PLUGIN_unload (sh->plugin, sh->sf); - sh->sf = NULL; - GAS_normalization_stop(); + GNUNET_STATISTICS_destroy((struct GNUNET_STATISTICS_Handle *)sh->env.stats, + GNUNET_NO); + GNUNET_PLUGIN_unload(sh->plugin, sh->sf); + sh->sf = NULL; + GAS_normalization_stop(); - GNUNET_CONTAINER_multipeermap_iterate (sh->addresses, + GNUNET_CONTAINER_multipeermap_iterate(sh->addresses, &free_all_it, NULL); - GNUNET_CONTAINER_multipeermap_destroy(sh->addresses); - GNUNET_free (sh->plugin); - GNUNET_free (sh); + GNUNET_CONTAINER_multipeermap_destroy(sh->addresses); + GNUNET_free(sh->plugin); + GNUNET_free(sh); } @@ -2738,10 +2793,10 @@ GNUNET_ATS_solvers_solver_stop (struct SolverHandle *sh) * @return number of networks loaded */ unsigned int -GNUNET_ATS_solvers_load_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg, - unsigned long long *out_dest, - unsigned long long *in_dest, - int dest_length) +GNUNET_ATS_solvers_load_quotas(const struct GNUNET_CONFIGURATION_Handle *cfg, + unsigned long long *out_dest, + unsigned long long *in_dest, + int dest_length) { char * entry_in = NULL; char * entry_out = NULL; @@ -2751,105 +2806,105 @@ GNUNET_ATS_solvers_load_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg, int res; for (c = 0; (c < GNUNET_NT_COUNT) && (c < dest_length); c++) - { - in_dest[c] = 0; - out_dest[c] = 0; - GNUNET_asprintf (&entry_out, - "%s_QUOTA_OUT", - GNUNET_NT_to_string (c)); - GNUNET_asprintf (&entry_in, - "%s_QUOTA_IN", - GNUNET_NT_to_string (c)); - - /* quota out */ - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_out, "a_out_str)) - { - res = GNUNET_NO; - if (0 == strcmp(quota_out_str, BIG_M_STRING)) - { - out_dest[c] = GNUNET_ATS_MaxBandwidth; - res = GNUNET_YES; - } - if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_STRINGS_fancy_size_to_bytes (quota_out_str, &out_dest[c]))) - res = GNUNET_YES; - if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number (cfg, "ats", entry_out, &out_dest[c]))) - res = GNUNET_YES; - - if (GNUNET_NO == res) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Could not load quota for network `%s': `%s', assigning default bandwidth %llu\n"), - GNUNET_NT_to_string (c), - quota_out_str, - GNUNET_ATS_DefaultBandwidth); - out_dest[c] = GNUNET_ATS_DefaultBandwidth; - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Outbound quota configure for network `%s' is %llu\n", - GNUNET_NT_to_string (c), - out_dest[c]); - } - GNUNET_free (quota_out_str); - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("No outbound quota configured for network `%s', assigning default bandwidth %llu\n"), - GNUNET_NT_to_string (c), - GNUNET_ATS_DefaultBandwidth); - out_dest[c] = GNUNET_ATS_DefaultBandwidth; - } - - /* quota in */ - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_in, "a_in_str)) { - res = GNUNET_NO; - if (0 == strcmp(quota_in_str, BIG_M_STRING)) - { - in_dest[c] = GNUNET_ATS_MaxBandwidth; - res = GNUNET_YES; - } - if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_STRINGS_fancy_size_to_bytes (quota_in_str, &in_dest[c]))) - res = GNUNET_YES; - if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number (cfg, "ats", entry_in, &in_dest[c]))) - res = GNUNET_YES; + in_dest[c] = 0; + out_dest[c] = 0; + GNUNET_asprintf(&entry_out, + "%s_QUOTA_OUT", + GNUNET_NT_to_string(c)); + GNUNET_asprintf(&entry_in, + "%s_QUOTA_IN", + GNUNET_NT_to_string(c)); + + /* quota out */ + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_out, "a_out_str)) + { + res = GNUNET_NO; + if (0 == strcmp(quota_out_str, BIG_M_STRING)) + { + out_dest[c] = GNUNET_ATS_MaxBandwidth; + res = GNUNET_YES; + } + if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_STRINGS_fancy_size_to_bytes(quota_out_str, &out_dest[c]))) + res = GNUNET_YES; + if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "ats", entry_out, &out_dest[c]))) + res = GNUNET_YES; + + if (GNUNET_NO == res) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Could not load quota for network `%s': `%s', assigning default bandwidth %llu\n"), + GNUNET_NT_to_string(c), + quota_out_str, + GNUNET_ATS_DefaultBandwidth); + out_dest[c] = GNUNET_ATS_DefaultBandwidth; + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Outbound quota configure for network `%s' is %llu\n", + GNUNET_NT_to_string(c), + out_dest[c]); + } + GNUNET_free(quota_out_str); + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("No outbound quota configured for network `%s', assigning default bandwidth %llu\n"), + GNUNET_NT_to_string(c), + GNUNET_ATS_DefaultBandwidth); + out_dest[c] = GNUNET_ATS_DefaultBandwidth; + } - if (GNUNET_NO == res) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Could not load quota for network `%s': `%s', assigning default bandwidth %llu\n"), - GNUNET_NT_to_string (c), - quota_in_str, - GNUNET_ATS_DefaultBandwidth); - in_dest[c] = GNUNET_ATS_DefaultBandwidth; - } + /* quota in */ + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_in, "a_in_str)) + { + res = GNUNET_NO; + if (0 == strcmp(quota_in_str, BIG_M_STRING)) + { + in_dest[c] = GNUNET_ATS_MaxBandwidth; + res = GNUNET_YES; + } + if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_STRINGS_fancy_size_to_bytes(quota_in_str, &in_dest[c]))) + res = GNUNET_YES; + if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "ats", entry_in, &in_dest[c]))) + res = GNUNET_YES; + + if (GNUNET_NO == res) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Could not load quota for network `%s': `%s', assigning default bandwidth %llu\n"), + GNUNET_NT_to_string(c), + quota_in_str, + GNUNET_ATS_DefaultBandwidth); + in_dest[c] = GNUNET_ATS_DefaultBandwidth; + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Inbound quota configured for network `%s' is %llu\n", + GNUNET_NT_to_string(c), + in_dest[c]); + } + GNUNET_free(quota_in_str); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Inbound quota configured for network `%s' is %llu\n", - GNUNET_NT_to_string (c), - in_dest[c]); - } - GNUNET_free (quota_in_str); - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("No outbound quota configure for network `%s', assigning default bandwidth %llu\n"), - GNUNET_NT_to_string (c), - GNUNET_ATS_DefaultBandwidth); - out_dest[c] = GNUNET_ATS_DefaultBandwidth; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Loaded quota for network `%s' (in/out): %llu %llu\n", - GNUNET_NT_to_string (c), - in_dest[c], - out_dest[c]); - GNUNET_free (entry_out); - GNUNET_free (entry_in); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("No outbound quota configure for network `%s', assigning default bandwidth %llu\n"), + GNUNET_NT_to_string(c), + GNUNET_ATS_DefaultBandwidth); + out_dest[c] = GNUNET_ATS_DefaultBandwidth; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Loaded quota for network `%s' (in/out): %llu %llu\n", + GNUNET_NT_to_string(c), + in_dest[c], + out_dest[c]); + GNUNET_free(entry_out); + GNUNET_free(entry_in); + } return GNUNET_NT_COUNT; } @@ -2863,107 +2918,121 @@ GNUNET_ATS_solvers_load_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param add additional solver information */ static void -solver_info_cb (void *cls, - enum GAS_Solver_Operation op, - enum GAS_Solver_Status stat, - enum GAS_Solver_Additional_Information add) +solver_info_cb(void *cls, + enum GAS_Solver_Operation op, + enum GAS_Solver_Status stat, + enum GAS_Solver_Additional_Information add) { char *add_info; - switch (add) { + + switch (add) + { case GAS_INFO_NONE: add_info = "GAS_INFO_NONE"; break; + case GAS_INFO_FULL: add_info = "GAS_INFO_MLP_FULL"; break; + case GAS_INFO_UPDATED: add_info = "GAS_INFO_MLP_UPDATED"; break; + case GAS_INFO_PROP_ALL: add_info = "GAS_INFO_PROP_ALL"; break; + case GAS_INFO_PROP_SINGLE: add_info = "GAS_INFO_PROP_SINGLE"; break; + default: add_info = "INVALID"; break; - } + } switch (op) - { + { case GAS_OP_SOLVE_START: GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s' `%s'\n", "GAS_OP_SOLVE_START", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL", add_info); + "Solver notifies `%s' with result `%s' `%s'\n", "GAS_OP_SOLVE_START", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL", add_info); return; + case GAS_OP_SOLVE_STOP: GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_STOP", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL", add_info); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_STOP", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL", add_info); return; case GAS_OP_SOLVE_SETUP_START: GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_SETUP_START", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_SETUP_START", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); return; case GAS_OP_SOLVE_SETUP_STOP: GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_SETUP_STOP", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_SETUP_STOP", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); return; case GAS_OP_SOLVE_MLP_LP_START: GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_LP_START", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_LP_START", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); return; + case GAS_OP_SOLVE_MLP_LP_STOP: GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_LP_STOP", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_LP_STOP", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); return; case GAS_OP_SOLVE_MLP_MLP_START: GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_MLP_START", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_MLP_START", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); return; + case GAS_OP_SOLVE_MLP_MLP_STOP: GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_MLP_STOP", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_MLP_STOP", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); return; + case GAS_OP_SOLVE_UPDATE_NOTIFICATION_START: GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_UPDATE_NOTIFICATION_START", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_UPDATE_NOTIFICATION_START", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); return; + case GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP: GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); return; + default: break; } } static void -solver_bandwidth_changed_cb (void *cls, struct ATS_Address *address) +solver_bandwidth_changed_cb(void *cls, struct ATS_Address *address) { struct GNUNET_TIME_Relative duration; struct TestPeer *p; static struct PreferenceGenerator *pg; uint32_t delta; - if ( (0 == address->assigned_bw_out) && (0 == address->assigned_bw_in) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Solver notified to disconnect peer `%s'\n", - GNUNET_i2s (&address->peer)); - } + + if ((0 == address->assigned_bw_out) && (0 == address->assigned_bw_in)) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Solver notified to disconnect peer `%s'\n", + GNUNET_i2s(&address->peer)); + } p = find_peer_by_pid(&address->peer); if (NULL == p) return; @@ -2971,82 +3040,87 @@ solver_bandwidth_changed_cb (void *cls, struct ATS_Address *address) p->assigned_bw_in = address->assigned_bw_in; for (pg = pref_gen_head; NULL != pg; pg = pg->next) - { - if (pg->peer == p->id) { - duration = GNUNET_TIME_absolute_get_duration(pg->feedback_last_bw_update); - delta = duration.rel_value_us * pg->last_assigned_bw_out; - pg->feedback_bw_out_acc += delta; + if (pg->peer == p->id) + { + duration = GNUNET_TIME_absolute_get_duration(pg->feedback_last_bw_update); + delta = duration.rel_value_us * pg->last_assigned_bw_out; + pg->feedback_bw_out_acc += delta; - delta = duration.rel_value_us * pg->last_assigned_bw_in; - pg->feedback_bw_in_acc += delta; + delta = duration.rel_value_us * pg->last_assigned_bw_in; + pg->feedback_bw_in_acc += delta; - pg->last_assigned_bw_in = address->assigned_bw_in; - pg->last_assigned_bw_out = address->assigned_bw_out; - pg->feedback_last_bw_update = GNUNET_TIME_absolute_get(); + pg->last_assigned_bw_in = address->assigned_bw_in; + pg->last_assigned_bw_out = address->assigned_bw_out; + pg->feedback_last_bw_update = GNUNET_TIME_absolute_get(); + } } - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Bandwidth changed addresses %s %p to %u Bps out / %u Bps in\n", - GNUNET_i2s (&address->peer), - address, - address->assigned_bw_out, - address->assigned_bw_in); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Bandwidth changed addresses %s %p to %u Bps out / %u Bps in\n", + GNUNET_i2s(&address->peer), + address, + address->assigned_bw_out, + address->assigned_bw_in); if (NULL != l) - GNUNET_ATS_solver_logging_now (l); + GNUNET_ATS_solver_logging_now(l); return; } const double * -get_preferences_cb (void *cls, const struct GNUNET_PeerIdentity *id) +get_preferences_cb(void *cls, const struct GNUNET_PeerIdentity *id) { struct TestPeer *p; + if (GNUNET_YES == opt_disable_normalization) - { - if (NULL == (p = find_peer_by_pid (id))) - return NULL; - return p->pref_abs; - } + { + if (NULL == (p = find_peer_by_pid(id))) + return NULL; + return p->pref_abs; + } else - return GAS_preference_get_by_peer (NULL, - id); + return GAS_preference_get_by_peer(NULL, + id); } struct SolverHandle * -GNUNET_ATS_solvers_solver_start (enum GNUNET_ATS_Solvers type) +GNUNET_ATS_solvers_solver_start(enum GNUNET_ATS_Solvers type) { struct SolverHandle *sh; char * solver_str; - switch (type) { + switch (type) + { case GNUNET_ATS_SOLVER_PROPORTIONAL: solver_str = "proportional"; break; + case GNUNET_ATS_SOLVER_MLP: solver_str = "mlp"; break; + case GNUNET_ATS_SOLVER_RIL: solver_str = "ril"; break; + default: - GNUNET_break (0); + GNUNET_break(0); return NULL; break; - } + } - sh = GNUNET_new (struct SolverHandle); - GNUNET_asprintf (&sh->plugin, - "libgnunet_plugin_ats_%s", - solver_str); - sh->addresses = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO); + sh = GNUNET_new(struct SolverHandle); + GNUNET_asprintf(&sh->plugin, + "libgnunet_plugin_ats_%s", + solver_str); + sh->addresses = GNUNET_CONTAINER_multipeermap_create(128, GNUNET_NO); /* setup environment */ sh->env.cfg = e->cfg; - sh->env.stats = GNUNET_STATISTICS_create ("ats", e->cfg); + sh->env.stats = GNUNET_STATISTICS_create("ats", e->cfg); sh->env.addresses = sh->addresses; sh->env.bandwidth_changed_cb = &solver_bandwidth_changed_cb; sh->env.get_preferences = &get_preferences_cb; @@ -3055,35 +3129,35 @@ GNUNET_ATS_solvers_solver_start (enum GNUNET_ATS_Solvers type) sh->env.network_count = GNUNET_NT_COUNT; /* start normalization */ - GAS_normalization_start (); + GAS_normalization_start(); /* load quotas */ - if (GNUNET_NT_COUNT != GNUNET_ATS_solvers_load_quotas (e->cfg, - sh->env.out_quota, sh->env.in_quota, GNUNET_NT_COUNT)) - { - GNUNET_break(0); - GNUNET_free (sh->plugin); - GNUNET_free (sh); - end_now (); - return NULL; - } - - sh->sf = GNUNET_PLUGIN_load (sh->plugin, &sh->env); + if (GNUNET_NT_COUNT != GNUNET_ATS_solvers_load_quotas(e->cfg, + sh->env.out_quota, sh->env.in_quota, GNUNET_NT_COUNT)) + { + GNUNET_break(0); + GNUNET_free(sh->plugin); + GNUNET_free(sh); + end_now(); + return NULL; + } + + sh->sf = GNUNET_PLUGIN_load(sh->plugin, &sh->env); if (NULL == sh->sf) - { - fprintf (stderr, "Failed to load solver `%s'\n", sh->plugin); - GNUNET_break(0); - GNUNET_free (sh->plugin); - GNUNET_free (sh); - end_now (); - return NULL; - } + { + fprintf(stderr, "Failed to load solver `%s'\n", sh->plugin); + GNUNET_break(0); + GNUNET_free(sh->plugin); + GNUNET_free(sh); + end_now(); + return NULL; + } return sh; } static void -done () +done() { struct TestPeer *cur; struct TestPeer *next; @@ -3092,79 +3166,79 @@ done () struct TestAddress *next_a; /* Stop logging */ - GNUNET_ATS_solver_logging_stop (l); + GNUNET_ATS_solver_logging_stop(l); /* Stop all preference generation */ - GNUNET_ATS_solver_generate_preferences_stop_all (); + GNUNET_ATS_solver_generate_preferences_stop_all(); /* Stop all property generation */ - GNUNET_ATS_solver_generate_property_stop_all (); + GNUNET_ATS_solver_generate_property_stop_all(); if (opt_print) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "== Printing log information \n"); - GNUNET_ATS_solver_logging_eval (l); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "== Printing log information \n"); + GNUNET_ATS_solver_logging_eval(l); + } if (opt_save) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "== Saving log information \n"); - GNUNET_ATS_solver_logging_write_to_disk (l, e->log_append_time_stamp, - e->log_output_dir); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "== Saving log information \n"); + GNUNET_ATS_solver_logging_write_to_disk(l, e->log_append_time_stamp, + e->log_output_dir); + } if (NULL != l) - { - GNUNET_ATS_solver_logging_free (l); - l = NULL; - } + { + GNUNET_ATS_solver_logging_free(l); + l = NULL; + } /* Clean up experiment */ if (NULL != e) - { - GNUNET_ATS_solvers_experimentation_stop (e); - e = NULL; - } + { + GNUNET_ATS_solvers_experimentation_stop(e); + e = NULL; + } next = peer_head; - while (NULL != (cur = next)) - { - next = cur->next; - GNUNET_CONTAINER_DLL_remove (peer_head, peer_tail, cur); - next_a = cur->addr_head; - while (NULL != (cur_a = next_a)) + while (NULL != (cur = next)) { - next_a = cur_a->next; - GNUNET_CONTAINER_DLL_remove (cur->addr_head, cur->addr_tail, cur_a); - GNUNET_free (cur_a); + next = cur->next; + GNUNET_CONTAINER_DLL_remove(peer_head, peer_tail, cur); + next_a = cur->addr_head; + while (NULL != (cur_a = next_a)) + { + next_a = cur_a->next; + GNUNET_CONTAINER_DLL_remove(cur->addr_head, cur->addr_tail, cur_a); + GNUNET_free(cur_a); + } + GNUNET_free(cur); } - GNUNET_free (cur); - } if (NULL != sh) - { - GNUNET_ATS_solvers_solver_stop (sh); - sh = NULL; - } + { + GNUNET_ATS_solvers_solver_stop(sh); + sh = NULL; + } /* Shutdown */ end_now(); } static void -experiment_done_cb (struct Experiment *e, struct GNUNET_TIME_Relative duration,int success) +experiment_done_cb(struct Experiment *e, struct GNUNET_TIME_Relative duration, int success) { if (GNUNET_OK == success) - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Experiment done successful in %s\n", - GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_YES)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Experiment done successful in %s\n", + GNUNET_STRINGS_relative_time_to_string(duration, GNUNET_YES)); else - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Experiment failed \n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Experiment failed \n"); - GNUNET_SCHEDULER_add_now (&done, NULL); + GNUNET_SCHEDULER_add_now(&done, NULL); } static void -episode_done_cb (struct Episode *ep) +episode_done_cb(struct Episode *ep) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Episode %u done\n", ep->id); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Episode %u done\n", ep->id); } @@ -3173,62 +3247,62 @@ episode_done_cb (struct Episode *ep) * Do shutdown */ static void -end_now () +end_now() { if (NULL != e) - { - GNUNET_ATS_solvers_experimentation_stop (e); - e = NULL; - } + { + GNUNET_ATS_solvers_experimentation_stop(e); + e = NULL; + } if (NULL != sh) - { - GNUNET_ATS_solvers_solver_stop (sh); - sh = NULL; - } + { + GNUNET_ATS_solvers_solver_stop(sh); + sh = NULL; + } } static void -run (void *cls, char * const *args, const char *cfgfile, +run(void *cls, char * const *args, const char *cfgfile, const struct GNUNET_CONFIGURATION_Handle *cfg) { enum GNUNET_ATS_Solvers solver; int c; if (NULL == opt_exp_file) - { - fprintf (stderr, "No experiment given ...\n"); - res = 1; - end_now (); - return; - } + { + fprintf(stderr, "No experiment given ...\n"); + res = 1; + end_now(); + return; + } if (NULL == opt_solver) - { - fprintf (stderr, "No solver given ...\n"); - res = 1; - end_now (); - return; - } + { + fprintf(stderr, "No solver given ...\n"); + res = 1; + end_now(); + return; + } if (0 == strcmp(opt_solver, "mlp")) - { - solver = GNUNET_ATS_SOLVER_MLP; - } + { + solver = GNUNET_ATS_SOLVER_MLP; + } else if (0 == strcmp(opt_solver, "proportional")) - { - solver = GNUNET_ATS_SOLVER_PROPORTIONAL; - } + { + solver = GNUNET_ATS_SOLVER_PROPORTIONAL; + } else if (0 == strcmp(opt_solver, "ril")) - { - solver = GNUNET_ATS_SOLVER_RIL; - } + { + solver = GNUNET_ATS_SOLVER_RIL; + } else - { - fprintf (stderr, "No solver given ..."); - res = 1; - end_now (); - return; - } + { + fprintf(stderr, "No solver given ..."); + res = 1; + end_now(); + return; + } for (c = 0; c < GNUNET_ATS_PropertyCount; c++) default_properties[c] = DEFAULT_REL_QUALITY; @@ -3237,35 +3311,35 @@ run (void *cls, char * const *args, const char *cfgfile, default_preferences[c] = DEFAULT_REL_PREFERENCE; /* load experiment */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "=== Loading experiment\n"); - e = GNUNET_ATS_solvers_experimentation_load (opt_exp_file); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "=== Loading experiment\n"); + e = GNUNET_ATS_solvers_experimentation_load(opt_exp_file); if (NULL == e) - { - fprintf (stderr, "Failed to load experiment ...\n"); - res = 1; - end_now (); - return; - } + { + fprintf(stderr, "Failed to load experiment ...\n"); + res = 1; + end_now(); + return; + } /* load solver */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "=== Loading solver\n"); - sh = GNUNET_ATS_solvers_solver_start (solver); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "=== Loading solver\n"); + sh = GNUNET_ATS_solvers_solver_start(solver); if (NULL == sh) - { - fprintf (stderr, "Failed to start solver ...\n"); - end_now (); - res = 1; - return; - } + { + fprintf(stderr, "Failed to start solver ...\n"); + end_now(); + res = 1; + return; + } /* start logging */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "=== Start logging \n"); - l = GNUNET_ATS_solver_logging_start (e->log_freq); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "=== Start logging \n"); + l = GNUNET_ATS_solver_logging_start(e->log_freq); /* run experiment */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "=== Running experiment \n"); - GNUNET_ATS_solvers_experimentation_run (e, episode_done_cb, - experiment_done_cb); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "=== Running experiment \n"); + GNUNET_ATS_solvers_experimentation_run(e, episode_done_cb, + experiment_done_cb); /* WAIT */ } @@ -3278,7 +3352,7 @@ run (void *cls, char * const *args, const char *cfgfile, * @param argv argument values */ int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { opt_exp_file = NULL; opt_solver = NULL; @@ -3289,38 +3363,38 @@ main (int argc, char *argv[]) static struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_option_string ('s', - "solver", - gettext_noop ("solver to use"), - &opt_solver), + GNUNET_GETOPT_option_string('s', + "solver", + gettext_noop("solver to use"), + &opt_solver), - GNUNET_GETOPT_option_string ('e', - "experiment" - gettext_noop ("experiment to use"), - &opt_exp_file), + GNUNET_GETOPT_option_string('e', + "experiment" + gettext_noop("experiment to use"), + &opt_exp_file), - GNUNET_GETOPT_option_verbose (&opt_verbose), + GNUNET_GETOPT_option_verbose(&opt_verbose), - GNUNET_GETOPT_option_flag ('p', - "print", - gettext_noop ("print logging"), - &opt_print), + GNUNET_GETOPT_option_flag('p', + "print", + gettext_noop("print logging"), + &opt_print), - GNUNET_GETOPT_option_flag ('f', - "file", - gettext_noop ("save logging to disk"), - &opt_save), + GNUNET_GETOPT_option_flag('f', + "file", + gettext_noop("save logging to disk"), + &opt_save), - GNUNET_GETOPT_option_flag ('d', - "dn", - gettext_noop ("disable normalization"), - &opt_disable_normalization), + GNUNET_GETOPT_option_flag('d', + "dn", + gettext_noop("disable normalization"), + &opt_disable_normalization), GNUNET_GETOPT_OPTION_END }; - GNUNET_PROGRAM_run (argc, argv, "gnunet-ats-solver-eval", - NULL, options, &run, argv[0]); + GNUNET_PROGRAM_run(argc, argv, "gnunet-ats-solver-eval", + NULL, options, &run, argv[0]); return res; } diff --git a/src/ats/gnunet-ats-solver-eval.h b/src/ats/gnunet-ats-solver-eval.h index d5a68c5b0..e3afa02b1 100644 --- a/src/ats/gnunet-ats-solver-eval.h +++ b/src/ats/gnunet-ats-solver-eval.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2013 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2013 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -34,8 +34,7 @@ #include "gnunet-service-ats_normalization.h" #include "test_ats_api_common.h" -enum GeneratorType -{ +enum GeneratorType { GNUNET_ATS_TEST_TG_LINEAR, GNUNET_ATS_TEST_TG_CONSTANT, GNUNET_ATS_TEST_TG_RANDOM, @@ -43,8 +42,7 @@ enum GeneratorType }; -enum OperationType -{ +enum OperationType { SOLVER_OP_ADD_ADDRESS, SOLVER_OP_DEL_ADDRESS, SOLVER_OP_START_SET_PROPERTY, @@ -55,8 +53,7 @@ enum OperationType SOLVER_OP_STOP_REQUEST, }; -struct SolverHandle -{ +struct SolverHandle { /** * Solver plugin name */ @@ -78,15 +75,13 @@ struct SolverHandle struct GNUNET_CONTAINER_MultiPeerMap *addresses; }; -enum GNUNET_ATS_Solvers -{ +enum GNUNET_ATS_Solvers { GNUNET_ATS_SOLVER_PROPORTIONAL, GNUNET_ATS_SOLVER_MLP, GNUNET_ATS_SOLVER_RIL, }; -struct LoggingFileHandle -{ +struct LoggingFileHandle { /* DLL list for logging time steps */ struct LoggingFileHandle *next; struct LoggingFileHandle *prev; @@ -98,11 +93,9 @@ struct LoggingFileHandle long long unsigned int aid; struct GNUNET_DISK_FileHandle *f_hd; - }; -struct LoggingTimeStep -{ +struct LoggingTimeStep { struct LoggingTimeStep *prev; struct LoggingTimeStep *next; @@ -113,8 +106,7 @@ struct LoggingTimeStep struct GNUNET_TIME_Relative delta; }; -struct LoggingPeer -{ +struct LoggingPeer { struct LoggingPeer *prev; struct LoggingPeer *next; @@ -128,8 +120,7 @@ struct LoggingPeer struct LoggingAddress *addr_tail; }; -struct LoggingAddress -{ +struct LoggingAddress { struct LoggingAddress *next; struct LoggingAddress *prev; @@ -144,8 +135,7 @@ struct LoggingAddress }; -struct TestPeer -{ +struct TestPeer { struct TestPeer *prev; struct TestPeer *next; @@ -165,8 +155,7 @@ struct TestPeer }; -struct TestAddress -{ +struct TestAddress { struct TestAddress *next; struct TestAddress *prev; @@ -183,16 +172,15 @@ struct Episode; struct Experiment; typedef void (*GNUNET_ATS_TESTING_EpisodeDoneCallback) ( - struct Episode *e); + struct Episode *e); typedef void (*GNUNET_ATS_TESTING_ExperimentDoneCallback) (struct Experiment *e, - struct GNUNET_TIME_Relative duration,int success); + struct GNUNET_TIME_Relative duration, int success); /** * An operation in an experiment */ -struct GNUNET_ATS_TEST_Operation -{ +struct GNUNET_ATS_TEST_Operation { struct GNUNET_ATS_TEST_Operation *next; struct GNUNET_ATS_TEST_Operation *prev; @@ -218,8 +206,7 @@ struct GNUNET_ATS_TEST_Operation // enum GNUNET_ATS_Property prop_type; }; -struct Episode -{ +struct Episode { int id; struct Episode *next; struct GNUNET_TIME_Relative duration; @@ -228,8 +215,7 @@ struct Episode struct GNUNET_ATS_TEST_Operation *tail; }; -struct LoggingHandle -{ +struct LoggingHandle { struct GNUNET_SCHEDULER_Task * logging_task; struct GNUNET_TIME_Relative log_freq; @@ -238,8 +224,7 @@ struct LoggingHandle struct LoggingTimeStep *tail; }; -struct Experiment -{ +struct Experiment { char *name; char *log_prefix; char *cfg_file; @@ -263,8 +248,7 @@ struct Experiment GNUNET_ATS_TESTING_ExperimentDoneCallback e_done_cb; }; -struct PreferenceGenerator -{ +struct PreferenceGenerator { struct PreferenceGenerator *prev; struct PreferenceGenerator *next; @@ -302,12 +286,10 @@ struct PreferenceGenerator uint32_t last_assigned_bw_in; uint32_t last_assigned_bw_out; double last_delay_value; - }; -struct PropertyGenerator -{ +struct PropertyGenerator { struct PropertyGenerator *prev; struct PropertyGenerator *next; diff --git a/src/ats/gnunet-service-ats-new.c b/src/ats/gnunet-service-ats-new.c index b451c8c67..1061c28c2 100644 --- a/src/ats/gnunet-service-ats-new.c +++ b/src/ats/gnunet-service-ats-new.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats-new.c * @brief ats service @@ -59,8 +59,7 @@ struct Client; /** * Preferences expressed by a client are kept in a DLL per client. */ -struct ClientPreference -{ +struct ClientPreference { /** * DLL pointer. */ @@ -91,9 +90,7 @@ struct ClientPreference /** * Information about ongoing sessions of the transport client. */ -struct GNUNET_ATS_Session -{ - +struct GNUNET_ATS_Session { /** * Session data exposed to the plugin. */ @@ -113,15 +110,13 @@ struct GNUNET_ATS_Session * Unique ID for the session when talking with the client. */ uint32_t session_id; - }; /** * Information we track per client. */ -struct Client -{ +struct Client { /** * Type of the client, initially #CT_NONE. */ @@ -141,9 +136,7 @@ struct Client * Details depending on @e type. */ union { - struct { - /** * Head of DLL of preferences expressed by this client. */ @@ -153,20 +146,15 @@ struct Client * Tail of DLL of preferences expressed by this client. */ struct ClientPreference *cp_tail; - } application; struct { - /** * Map from session IDs to `struct GNUNET_ATS_Session` objects. */ struct GNUNET_CONTAINER_MultiHashMap32 *sessions; - } transport; - } details; - }; @@ -200,32 +188,32 @@ static struct Client *transport_client; * @param address address the transport should try */ static void -suggest_cb (void *cls, - const struct GNUNET_PeerIdentity *pid, - const char *address) +suggest_cb(void *cls, + const struct GNUNET_PeerIdentity *pid, + const char *address) { struct GNUNET_MQ_Envelope *env; - size_t slen = strlen (address) + 1; + size_t slen = strlen(address) + 1; struct AddressSuggestionMessage *as; if (NULL == transport_client) - { - // FIXME: stats! - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Suggesting address `%s' of peer `%s'\n", - address, - GNUNET_i2s (pid)); - env = GNUNET_MQ_msg_extra (as, - slen, - GNUNET_MESSAGE_TYPE_ATS_ADDRESS_SUGGESTION); + { + // FIXME: stats! + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Suggesting address `%s' of peer `%s'\n", + address, + GNUNET_i2s(pid)); + env = GNUNET_MQ_msg_extra(as, + slen, + GNUNET_MESSAGE_TYPE_ATS_ADDRESS_SUGGESTION); as->peer = *pid; - memcpy (&as[1], - address, - slen); - GNUNET_MQ_send (transport_client->mq, - env); + memcpy(&as[1], + address, + slen); + GNUNET_MQ_send(transport_client->mq, + env); } @@ -240,37 +228,37 @@ suggest_cb (void *cls, * @param bw_out suggested bandwidth for transmission */ static void -allocate_cb (void *cls, - struct GNUNET_ATS_Session *session, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_BANDWIDTH_Value32NBO bw_in, - struct GNUNET_BANDWIDTH_Value32NBO bw_out) +allocate_cb(void *cls, + struct GNUNET_ATS_Session *session, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_BANDWIDTH_Value32NBO bw_in, + struct GNUNET_BANDWIDTH_Value32NBO bw_out) { struct GNUNET_MQ_Envelope *env; struct SessionAllocationMessage *sam; - (void) cls; - if ( (NULL == transport_client) || - (session->client != transport_client) ) - { - /* transport must have just died and solver is addressing the - losses of sessions (possibly of previous transport), ignore! */ - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Allocating %u/%u bytes for %p of peer `%s'\n", - ntohl (bw_in.value__), - ntohl (bw_out.value__), - session, - GNUNET_i2s (peer)); - env = GNUNET_MQ_msg (sam, - GNUNET_MESSAGE_TYPE_ATS_SESSION_ALLOCATION); + (void)cls; + if ((NULL == transport_client) || + (session->client != transport_client)) + { + /* transport must have just died and solver is addressing the + losses of sessions (possibly of previous transport), ignore! */ + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Allocating %u/%u bytes for %p of peer `%s'\n", + ntohl(bw_in.value__), + ntohl(bw_out.value__), + session, + GNUNET_i2s(peer)); + env = GNUNET_MQ_msg(sam, + GNUNET_MESSAGE_TYPE_ATS_SESSION_ALLOCATION); sam->session_id = session->session_id; sam->peer = *peer; sam->bandwidth_in = bw_in; sam->bandwidth_out = bw_out; - GNUNET_MQ_send (transport_client->mq, - env); + GNUNET_MQ_send(transport_client->mq, + env); } @@ -281,18 +269,18 @@ allocate_cb (void *cls, * @param prop[out] in HBO */ static void -prop_ntoh (const struct PropertiesNBO *properties, - struct GNUNET_ATS_Properties *prop) +prop_ntoh(const struct PropertiesNBO *properties, + struct GNUNET_ATS_Properties *prop) { - prop->delay = GNUNET_TIME_relative_ntoh (properties->delay); - prop->goodput_out = ntohl (properties->goodput_out); - prop->goodput_in = ntohl (properties->goodput_in); - prop->utilization_out = ntohl (properties->utilization_out); - prop->utilization_in = ntohl (properties->utilization_in); - prop->distance = ntohl (properties->distance); - prop->mtu = ntohl (properties->mtu); - prop->nt = (enum GNUNET_NetworkType) ntohl (properties->nt); - prop->cc = (enum GNUNET_TRANSPORT_CommunicatorCharacteristics) ntohl (properties->cc); + prop->delay = GNUNET_TIME_relative_ntoh(properties->delay); + prop->goodput_out = ntohl(properties->goodput_out); + prop->goodput_in = ntohl(properties->goodput_in); + prop->utilization_out = ntohl(properties->utilization_out); + prop->utilization_in = ntohl(properties->utilization_in); + prop->distance = ntohl(properties->distance); + prop->mtu = ntohl(properties->mtu); + prop->nt = (enum GNUNET_NetworkType)ntohl(properties->nt); + prop->cc = (enum GNUNET_TRANSPORT_CommunicatorCharacteristics)ntohl(properties->cc); } @@ -303,8 +291,8 @@ prop_ntoh (const struct PropertiesNBO *properties, * @param msg the start message */ static void -handle_suggest (void *cls, - const struct ExpressPreferenceMessage *msg) +handle_suggest(void *cls, + const struct ExpressPreferenceMessage *msg) { struct Client *c = cls; struct ClientPreference *cp; @@ -312,27 +300,27 @@ handle_suggest (void *cls, if (CT_NONE == c->type) c->type = CT_APPLICATION; if (CT_APPLICATION != c->type) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Client suggested we talk to %s with preference %d at rate %u\n", - GNUNET_i2s (&msg->peer), - (int) ntohl (msg->pk), - (int) ntohl (msg->bw.value__)); - cp = GNUNET_new (struct ClientPreference); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Client suggested we talk to %s with preference %d at rate %u\n", + GNUNET_i2s(&msg->peer), + (int)ntohl(msg->pk), + (int)ntohl(msg->bw.value__)); + cp = GNUNET_new(struct ClientPreference); cp->client = c; cp->pref.peer = msg->peer; cp->pref.bw = msg->bw; - cp->pref.pk = (enum GNUNET_MQ_PreferenceKind) ntohl (msg->pk); - cp->ph = plugin->preference_add (plugin->cls, - &cp->pref); - GNUNET_CONTAINER_DLL_insert (c->details.application.cp_head, - c->details.application.cp_tail, - cp); - GNUNET_SERVICE_client_continue (c->client); + cp->pref.pk = (enum GNUNET_MQ_PreferenceKind)ntohl(msg->pk); + cp->ph = plugin->preference_add(plugin->cls, + &cp->pref); + GNUNET_CONTAINER_DLL_insert(c->details.application.cp_head, + c->details.application.cp_tail, + cp); + GNUNET_SERVICE_client_continue(c->client); } @@ -343,8 +331,8 @@ handle_suggest (void *cls, * @param msg the start message */ static void -handle_suggest_cancel (void *cls, - const struct ExpressPreferenceMessage *msg) +handle_suggest_cancel(void *cls, + const struct ExpressPreferenceMessage *msg) { struct Client *c = cls; struct ClientPreference *cp; @@ -352,33 +340,33 @@ handle_suggest_cancel (void *cls, if (CT_NONE == c->type) c->type = CT_APPLICATION; if (CT_APPLICATION != c->type) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } for (cp = c->details.application.cp_head; NULL != cp; cp = cp->next) - if ( (cp->pref.pk == (enum GNUNET_MQ_PreferenceKind) ntohl (msg->pk)) && - (cp->pref.bw.value__ == msg->bw.value__) && - (0 == GNUNET_memcmp (&cp->pref.peer, - &msg->peer)) ) + if ((cp->pref.pk == (enum GNUNET_MQ_PreferenceKind)ntohl(msg->pk)) && + (cp->pref.bw.value__ == msg->bw.value__) && + (0 == GNUNET_memcmp(&cp->pref.peer, + &msg->peer))) break; if (NULL == cp) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - plugin->preference_del (plugin->cls, - cp->ph, - &cp->pref); - GNUNET_CONTAINER_DLL_remove (c->details.application.cp_head, - c->details.application.cp_tail, - cp); - GNUNET_free (cp); - GNUNET_SERVICE_client_continue (c->client); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + plugin->preference_del(plugin->cls, + cp->ph, + &cp->pref); + GNUNET_CONTAINER_DLL_remove(c->details.application.cp_head, + c->details.application.cp_tail, + cp); + GNUNET_free(cp); + GNUNET_SERVICE_client_continue(c->client); } @@ -389,27 +377,27 @@ handle_suggest_cancel (void *cls, * @param message the request message */ static void -handle_start (void *cls, - const struct GNUNET_MessageHeader *hdr) +handle_start(void *cls, + const struct GNUNET_MessageHeader *hdr) { struct Client *c = cls; if (CT_NONE != c->type) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } c->type = CT_TRANSPORT; c->details.transport.sessions - = GNUNET_CONTAINER_multihashmap32_create (128); + = GNUNET_CONTAINER_multihashmap32_create(128); if (NULL != transport_client) - { - GNUNET_SERVICE_client_drop (transport_client->client); - transport_client = NULL; - } + { + GNUNET_SERVICE_client_drop(transport_client->client); + transport_client = NULL; + } transport_client = c; - GNUNET_SERVICE_client_continue (c->client); + GNUNET_SERVICE_client_continue(c->client); } @@ -422,17 +410,17 @@ handle_start (void *cls, * @return #GNUNET_OK if @a message is well-formed */ static int -check_session_add (void *cls, - const struct SessionAddMessage *message) +check_session_add(void *cls, + const struct SessionAddMessage *message) { struct Client *c = cls; - GNUNET_MQ_check_zero_termination (message); + GNUNET_MQ_check_zero_termination(message); if (CT_TRANSPORT != c->type) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -444,45 +432,45 @@ check_session_add (void *cls, * @param message the request message */ static void -handle_session_add (void *cls, - const struct SessionAddMessage *message) +handle_session_add(void *cls, + const struct SessionAddMessage *message) { struct Client *c = cls; - const char *address = (const char *) &message[1]; + const char *address = (const char *)&message[1]; struct GNUNET_ATS_Session *session; int inbound_only = (GNUNET_MESSAGE_TYPE_ATS_SESSION_ADD_INBOUND_ONLY == - ntohs (message->header.type)); + ntohs(message->header.type)); - session = GNUNET_CONTAINER_multihashmap32_get (c->details.transport.sessions, - message->session_id); + session = GNUNET_CONTAINER_multihashmap32_get(c->details.transport.sessions, + message->session_id); if (NULL != session) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - session = GNUNET_new (struct GNUNET_ATS_Session); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + session = GNUNET_new(struct GNUNET_ATS_Session); session->data.session = session; session->client = c; session->session_id = message->session_id; session->data.peer = message->peer; - prop_ntoh (&message->properties, - &session->data.prop); + prop_ntoh(&message->properties, + &session->data.prop); session->data.inbound_only = inbound_only; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap32_put (c->details.transport.sessions, - message->session_id, - session, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - session->sh = plugin->session_add (plugin->cls, - &session->data, - address); - GNUNET_assert (NULL != session->sh); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Transport has new session %p to %s\n", - session, - GNUNET_i2s (&message->peer)); - GNUNET_SERVICE_client_continue (c->client); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap32_put(c->details.transport.sessions, + message->session_id, + session, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + session->sh = plugin->session_add(plugin->cls, + &session->data, + address); + GNUNET_assert(NULL != session->sh); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Transport has new session %p to %s\n", + session, + GNUNET_i2s(&message->peer)); + GNUNET_SERVICE_client_continue(c->client); } @@ -493,32 +481,32 @@ handle_session_add (void *cls, * @param msg the request message */ static void -handle_session_update (void *cls, - const struct SessionUpdateMessage *msg) +handle_session_update(void *cls, + const struct SessionUpdateMessage *msg) { struct Client *c = cls; struct GNUNET_ATS_Session *session; if (CT_TRANSPORT != c->type) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - session = GNUNET_CONTAINER_multihashmap32_get (c->details.transport.sessions, - msg->session_id); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + session = GNUNET_CONTAINER_multihashmap32_get(c->details.transport.sessions, + msg->session_id); if (NULL == session) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - prop_ntoh (&msg->properties, - &session->data.prop); - plugin->session_update (plugin->cls, - session->sh, - &session->data); - GNUNET_SERVICE_client_continue (c->client); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + prop_ntoh(&msg->properties, + &session->data.prop); + plugin->session_update(plugin->cls, + session->sh, + &session->data); + GNUNET_SERVICE_client_continue(c->client); } @@ -529,41 +517,41 @@ handle_session_update (void *cls, * @param message the request message */ static void -handle_session_del (void *cls, - const struct SessionDelMessage *message) +handle_session_del(void *cls, + const struct SessionDelMessage *message) { struct Client *c = cls; struct GNUNET_ATS_Session *session; if (CT_TRANSPORT != c->type) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - session = GNUNET_CONTAINER_multihashmap32_get (c->details.transport.sessions, - message->session_id); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + session = GNUNET_CONTAINER_multihashmap32_get(c->details.transport.sessions, + message->session_id); if (NULL == session) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - GNUNET_assert (NULL != session->sh); - plugin->session_del (plugin->cls, - session->sh, - &session->data); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + GNUNET_assert(NULL != session->sh); + plugin->session_del(plugin->cls, + session->sh, + &session->data); session->sh = NULL; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap32_remove (c->details.transport.sessions, - session->session_id, - session)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Transport lost session %p to %s\n", - session, - GNUNET_i2s (&session->data.peer)); - GNUNET_free (session); - GNUNET_SERVICE_client_continue (c->client); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap32_remove(c->details.transport.sessions, + session->session_id, + session)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Transport lost session %p to %s\n", + session, + GNUNET_i2s(&session->data.peer)); + GNUNET_free(session); + GNUNET_SERVICE_client_continue(c->client); } @@ -577,11 +565,11 @@ handle_session_del (void *cls, * @return @a client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { - struct Client *c = GNUNET_new (struct Client); + struct Client *c = GNUNET_new(struct Client); c->client = client; c->mq = mq; @@ -598,21 +586,21 @@ client_connect_cb (void *cls, * @param value a `struct GNUNET_ATS_Session` */ static int -free_session (void *cls, - uint32_t key, - void *value) +free_session(void *cls, + uint32_t key, + void *value) { struct Client *c = cls; struct GNUNET_ATS_Session *session = value; - (void) key; - GNUNET_assert (c == session->client); - GNUNET_assert (NULL != session->sh); - plugin->session_del (plugin->cls, - session->sh, - &session->data); + (void)key; + GNUNET_assert(c == session->client); + GNUNET_assert(NULL != session->sh); + plugin->session_del(plugin->cls, + session->sh, + &session->data); session->sh = NULL; - GNUNET_free (session); + GNUNET_free(session); return GNUNET_OK; } @@ -626,42 +614,44 @@ free_session (void *cls, * @param app_ctx our `struct Client` */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { struct Client *c = app_ctx; - (void) cls; - GNUNET_assert (c->client == client); + (void)cls; + GNUNET_assert(c->client == client); switch (c->type) - { - case CT_NONE: - break; - case CT_APPLICATION: - for (struct ClientPreference *cp = c->details.application.cp_head; - NULL != cp; - cp = c->details.application.cp_head) { - plugin->preference_del (plugin->cls, - cp->ph, - &cp->pref); - GNUNET_CONTAINER_DLL_remove (c->details.application.cp_head, - c->details.application.cp_tail, - cp); - GNUNET_free (cp); + case CT_NONE: + break; + + case CT_APPLICATION: + for (struct ClientPreference *cp = c->details.application.cp_head; + NULL != cp; + cp = c->details.application.cp_head) + { + plugin->preference_del(plugin->cls, + cp->ph, + &cp->pref); + GNUNET_CONTAINER_DLL_remove(c->details.application.cp_head, + c->details.application.cp_tail, + cp); + GNUNET_free(cp); + } + break; + + case CT_TRANSPORT: + if (transport_client == c) + transport_client = NULL; + GNUNET_CONTAINER_multihashmap32_iterate(c->details.transport.sessions, + &free_session, + c); + GNUNET_CONTAINER_multihashmap32_destroy(c->details.transport.sessions); + break; } - break; - case CT_TRANSPORT: - if (transport_client == c) - transport_client = NULL; - GNUNET_CONTAINER_multihashmap32_iterate (c->details.transport.sessions, - &free_session, - c); - GNUNET_CONTAINER_multihashmap32_destroy (c->details.transport.sessions); - break; - } - GNUNET_free (c); + GNUNET_free(c); } @@ -671,26 +661,26 @@ client_disconnect_cb (void *cls, * @param cls unused */ static void -final_cleanup (void *cls) +final_cleanup(void *cls) { - (void) cls; + (void)cls; if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, - GNUNET_NO); - stats = NULL; - } + { + GNUNET_STATISTICS_destroy(stats, + GNUNET_NO); + stats = NULL; + } if (NULL != plugin) - { - GNUNET_PLUGIN_unload (plugin_name, - plugin); - plugin = NULL; - } + { + GNUNET_PLUGIN_unload(plugin_name, + plugin); + plugin = NULL; + } if (NULL != plugin_name) - { - GNUNET_free (plugin_name); - plugin_name = NULL; - } + { + GNUNET_free(plugin_name); + plugin_name = NULL; + } } @@ -700,13 +690,13 @@ final_cleanup (void *cls) * @param cls unused */ static void -cleanup_task (void *cls) +cleanup_task(void *cls) { - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "ATS shutdown initiated\n"); - GNUNET_SCHEDULER_add_now (&final_cleanup, - NULL); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "ATS shutdown initiated\n"); + GNUNET_SCHEDULER_add_now(&final_cleanup, + NULL); } @@ -718,45 +708,45 @@ cleanup_task (void *cls) * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_SERVICE_Handle *service) { static struct GNUNET_ATS_PluginEnvironment env; char *solver; - stats = GNUNET_STATISTICS_create ("ats", - cfg); + stats = GNUNET_STATISTICS_create("ats", + cfg); if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, - "ats", - "SOLVER", - &solver)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "No ATS solver configured, using 'simple' approach\n"); - solver = GNUNET_strdup ("simple"); - } - GNUNET_SCHEDULER_add_shutdown (&cleanup_task, - NULL); + GNUNET_CONFIGURATION_get_value_string(cfg, + "ats", + "SOLVER", + &solver)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "No ATS solver configured, using 'simple' approach\n"); + solver = GNUNET_strdup("simple"); + } + GNUNET_SCHEDULER_add_shutdown(&cleanup_task, + NULL); env.cls = NULL; env.cfg = cfg; env.stats = stats; env.suggest_cb = &suggest_cb; env.allocate_cb = &allocate_cb; - GNUNET_asprintf (&plugin_name, - "libgnunet_plugin_ats2_%s", - solver); - GNUNET_free (solver); - if (NULL == (plugin = GNUNET_PLUGIN_load (plugin_name, - &env))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to initialize solver `%s'!\n"), - plugin_name); - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_asprintf(&plugin_name, + "libgnunet_plugin_ats2_%s", + solver); + GNUNET_free(solver); + if (NULL == (plugin = GNUNET_PLUGIN_load(plugin_name, + &env))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to initialize solver `%s'!\n"), + plugin_name); + GNUNET_SCHEDULER_shutdown(); + return; + } } @@ -764,41 +754,41 @@ run (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("ats", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_fixed_size (suggest, + ("ats", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_fixed_size(suggest, GNUNET_MESSAGE_TYPE_ATS_SUGGEST, struct ExpressPreferenceMessage, NULL), - GNUNET_MQ_hd_fixed_size (suggest_cancel, + GNUNET_MQ_hd_fixed_size(suggest_cancel, GNUNET_MESSAGE_TYPE_ATS_SUGGEST_CANCEL, struct ExpressPreferenceMessage, NULL), - GNUNET_MQ_hd_fixed_size (start, - GNUNET_MESSAGE_TYPE_ATS_START, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_hd_var_size (session_add, - GNUNET_MESSAGE_TYPE_ATS_SESSION_ADD, - struct SessionAddMessage, - NULL), - GNUNET_MQ_hd_var_size (session_add, - GNUNET_MESSAGE_TYPE_ATS_SESSION_ADD_INBOUND_ONLY, - struct SessionAddMessage, - NULL), - GNUNET_MQ_hd_fixed_size (session_update, - GNUNET_MESSAGE_TYPE_ATS_SESSION_UPDATE, - struct SessionUpdateMessage, - NULL), - GNUNET_MQ_hd_fixed_size (session_del, - GNUNET_MESSAGE_TYPE_ATS_SESSION_DEL, - struct SessionDelMessage, - NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_hd_fixed_size(start, + GNUNET_MESSAGE_TYPE_ATS_START, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_hd_var_size(session_add, + GNUNET_MESSAGE_TYPE_ATS_SESSION_ADD, + struct SessionAddMessage, + NULL), + GNUNET_MQ_hd_var_size(session_add, + GNUNET_MESSAGE_TYPE_ATS_SESSION_ADD_INBOUND_ONLY, + struct SessionAddMessage, + NULL), + GNUNET_MQ_hd_fixed_size(session_update, + GNUNET_MESSAGE_TYPE_ATS_SESSION_UPDATE, + struct SessionUpdateMessage, + NULL), + GNUNET_MQ_hd_fixed_size(session_del, + GNUNET_MESSAGE_TYPE_ATS_SESSION_DEL, + struct SessionDelMessage, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-ats.c */ diff --git a/src/ats/gnunet-service-ats.c b/src/ats/gnunet-service-ats.c index 2dc3edea6..d9bb71c2b 100644 --- a/src/ats/gnunet-service-ats.c +++ b/src/ats/gnunet-service-ats.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats.c * @brief ats service @@ -50,43 +50,47 @@ struct GNUNET_STATISTICS_Handle *GSA_stats; * @param msg the start message */ static void -handle_ats_start (void *cls, - const struct ClientStartMessage *msg) +handle_ats_start(void *cls, + const struct ClientStartMessage *msg) { struct GNUNET_SERVICE_Client *client = cls; enum StartFlag flag; - flag = ntohl (msg->start_flag); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ATS_START (%d) message\n", - (int) flag); + flag = ntohl(msg->start_flag); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ATS_START (%d) message\n", + (int)flag); switch (flag) - { - case START_FLAG_SCHEDULING: - if (GNUNET_OK != - GAS_scheduling_add_client (client)) { - GNUNET_SERVICE_client_drop (client); + case START_FLAG_SCHEDULING: + if (GNUNET_OK != + GAS_scheduling_add_client(client)) + { + GNUNET_SERVICE_client_drop(client); + return; + } + break; + + case START_FLAG_PERFORMANCE_WITH_PIC: + GAS_performance_add_client(client, + flag); + break; + + case START_FLAG_PERFORMANCE_NO_PIC: + GAS_performance_add_client(client, + flag); + break; + + case START_FLAG_CONNECTION_SUGGESTION: + /* This client won't receive messages from us, no need to 'add' */ + break; + + default: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(client); return; } - break; - case START_FLAG_PERFORMANCE_WITH_PIC: - GAS_performance_add_client (client, - flag); - break; - case START_FLAG_PERFORMANCE_NO_PIC: - GAS_performance_add_client (client, - flag); - break; - case START_FLAG_CONNECTION_SUGGESTION: - /* This client won't receive messages from us, no need to 'add' */ - break; - default: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (client); - return; - } - GNUNET_SERVICE_client_continue (client); + GNUNET_SERVICE_client_continue(client); } @@ -98,14 +102,14 @@ handle_ats_start (void *cls, * @param message the request message */ static void -handle_reservation_request (void *cls, - const struct ReservationRequestMessage *message) +handle_reservation_request(void *cls, + const struct ReservationRequestMessage *message) { struct GNUNET_SERVICE_Client *client = cls; - GAS_handle_reservation_request (client, - message); - GNUNET_SERVICE_client_continue (client); + GAS_handle_reservation_request(client, + message); + GNUNET_SERVICE_client_continue(client); } @@ -117,23 +121,23 @@ handle_reservation_request (void *cls, * @return #GNUNET_OK if @a message is well-formed */ static int -check_feedback (void *cls, - const struct FeedbackPreferenceMessage *message) +check_feedback(void *cls, + const struct FeedbackPreferenceMessage *message) { uint16_t msize; uint32_t nump; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received PREFERENCE_FEEDBACK message\n"); - msize = ntohs (message->header.size); - nump = ntohl (message->num_feedback); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received PREFERENCE_FEEDBACK message\n"); + msize = ntohs(message->header.size); + nump = ntohl(message->num_feedback); if (msize != - sizeof (struct FeedbackPreferenceMessage) + - nump * sizeof (struct PreferenceInformation)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + sizeof(struct FeedbackPreferenceMessage) + + nump * sizeof(struct PreferenceInformation)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -145,42 +149,42 @@ check_feedback (void *cls, * @param msg the request message */ static void -handle_feedback (void *cls, - const struct FeedbackPreferenceMessage *msg) +handle_feedback(void *cls, + const struct FeedbackPreferenceMessage *msg) { struct GNUNET_SERVICE_Client *client = cls; const struct PreferenceInformation *pi; uint32_t nump; - nump = ntohl (msg->num_feedback); + nump = ntohl(msg->num_feedback); if (GNUNET_NO == - GNUNET_CONTAINER_multipeermap_contains (GSA_addresses, - &msg->peer)) - { - GNUNET_log(GNUNET_ERROR_TYPE_WARNING, - "Received PREFERENCE FEEDBACK for unknown peer `%s'\n", - GNUNET_i2s (&msg->peer)); - GNUNET_SERVICE_client_continue (client); - return; - } + GNUNET_CONTAINER_multipeermap_contains(GSA_addresses, + &msg->peer)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Received PREFERENCE FEEDBACK for unknown peer `%s'\n", + GNUNET_i2s(&msg->peer)); + GNUNET_SERVICE_client_continue(client); + return; + } - GNUNET_STATISTICS_update (GSA_stats, - "# preference feedbacks requests processed", - 1, - GNUNET_NO); - pi = (const struct PreferenceInformation *) &msg[1]; + GNUNET_STATISTICS_update(GSA_stats, + "# preference feedbacks requests processed", + 1, + GNUNET_NO); + pi = (const struct PreferenceInformation *)&msg[1]; for (uint32_t i = 0; i < nump; i++) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received PREFERENCE FEEDBACK for peer `%s'\n", - GNUNET_i2s (&msg->peer)); - GAS_plugin_notify_feedback (client, - &msg->peer, - GNUNET_TIME_relative_ntoh (msg->scope), - (enum GNUNET_ATS_PreferenceKind) ntohl (pi[i].preference_kind), - pi[i].preference_value); - } - GNUNET_SERVICE_client_continue (client); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received PREFERENCE FEEDBACK for peer `%s'\n", + GNUNET_i2s(&msg->peer)); + GAS_plugin_notify_feedback(client, + &msg->peer, + GNUNET_TIME_relative_ntoh(msg->scope), + (enum GNUNET_ATS_PreferenceKind)ntohl(pi[i].preference_kind), + pi[i].preference_value); + } + GNUNET_SERVICE_client_continue(client); } @@ -191,14 +195,14 @@ handle_feedback (void *cls, * @param message the request message */ static void -handle_request_address_list (void *cls, - const struct AddressListRequestMessage *message) +handle_request_address_list(void *cls, + const struct AddressListRequestMessage *message) { struct GNUNET_SERVICE_Client *client = cls; - GAS_handle_request_address_list (client, - message); - GNUNET_SERVICE_client_continue (client); + GAS_handle_request_address_list(client, + message); + GNUNET_SERVICE_client_continue(client); } @@ -209,14 +213,14 @@ handle_request_address_list (void *cls, * @param message the request message */ static void -handle_request_address (void *cls, - const struct RequestAddressMessage * message) +handle_request_address(void *cls, + const struct RequestAddressMessage * message) { struct GNUNET_SERVICE_Client *client = cls; - GAS_handle_request_address (client, - message); - GNUNET_SERVICE_client_continue (client); + GAS_handle_request_address(client, + message); + GNUNET_SERVICE_client_continue(client); } @@ -227,14 +231,14 @@ handle_request_address (void *cls, * @param message the request message */ static void -handle_request_address_cancel (void *cls, - const struct RequestAddressMessage *message) +handle_request_address_cancel(void *cls, + const struct RequestAddressMessage *message) { struct GNUNET_SERVICE_Client *client = cls; - GAS_handle_request_address_cancel (client, - message); - GNUNET_SERVICE_client_continue (client); + GAS_handle_request_address_cancel(client, + message); + GNUNET_SERVICE_client_continue(client); } @@ -245,8 +249,8 @@ handle_request_address_cancel (void *cls, * @param m the request message */ static int -check_address_add (void *cls, - const struct AddressAddMessage *m) +check_address_add(void *cls, + const struct AddressAddMessage *m) { const char *address; const char *plugin_name; @@ -254,23 +258,23 @@ check_address_add (void *cls, uint16_t plugin_name_length; uint16_t size; - size = ntohs (m->header.size); - address_length = ntohs (m->address_length); - plugin_name_length = ntohs (m->plugin_name_length); - address = (const char *) &m[1]; + size = ntohs(m->header.size); + address_length = ntohs(m->address_length); + plugin_name_length = ntohs(m->plugin_name_length); + address = (const char *)&m[1]; if (plugin_name_length != 0) plugin_name = &address[address_length]; else plugin_name = ""; - if ( (address_length + plugin_name_length + - sizeof (struct AddressAddMessage) != size) || - ( (plugin_name_length > 0) && - (plugin_name[plugin_name_length - 1] != '\0') ) ) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + if ((address_length + plugin_name_length + + sizeof(struct AddressAddMessage) != size) || + ((plugin_name_length > 0) && + (plugin_name[plugin_name_length - 1] != '\0'))) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -282,13 +286,13 @@ check_address_add (void *cls, * @param message the request message */ static void -handle_address_add (void *cls, - const struct AddressAddMessage *message) +handle_address_add(void *cls, + const struct AddressAddMessage *message) { struct GNUNET_SERVICE_Client *client = cls; - GAS_handle_address_add (message); - GNUNET_SERVICE_client_continue (client); + GAS_handle_address_add(message); + GNUNET_SERVICE_client_continue(client); } @@ -299,13 +303,13 @@ handle_address_add (void *cls, * @param message the request message */ static void -handle_address_update (void *cls, - const struct AddressUpdateMessage *message) +handle_address_update(void *cls, + const struct AddressUpdateMessage *message) { struct GNUNET_SERVICE_Client *client = cls; - GAS_handle_address_update (message); - GNUNET_SERVICE_client_continue (client); + GAS_handle_address_update(message); + GNUNET_SERVICE_client_continue(client); } @@ -316,13 +320,13 @@ handle_address_update (void *cls, * @param message the request message */ static void -handle_address_destroyed (void *cls, - const struct AddressDestroyedMessage *message) +handle_address_destroyed(void *cls, + const struct AddressDestroyedMessage *message) { struct GNUNET_SERVICE_Client *client = cls; - GAS_handle_address_destroyed (message); - GNUNET_SERVICE_client_continue (client); + GAS_handle_address_destroyed(message); + GNUNET_SERVICE_client_continue(client); } @@ -334,22 +338,22 @@ handle_address_destroyed (void *cls, * @return #GNUNET_OK if @a message is well-formed */ static int -check_preference_change (void *cls, - const struct ChangePreferenceMessage *message) +check_preference_change(void *cls, + const struct ChangePreferenceMessage *message) { uint16_t msize; uint32_t nump; - msize = ntohs (message->header.size); - nump = ntohl (message->num_preferences); - if ( (msize != - sizeof (struct ChangePreferenceMessage) + - nump * sizeof (struct PreferenceInformation)) || - (UINT16_MAX / sizeof (struct PreferenceInformation) < nump) ) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + msize = ntohs(message->header.size); + nump = ntohl(message->num_preferences); + if ((msize != + sizeof(struct ChangePreferenceMessage) + + nump * sizeof(struct PreferenceInformation)) || + (UINT16_MAX / sizeof(struct PreferenceInformation) < nump)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -361,14 +365,14 @@ check_preference_change (void *cls, * @param message the request message */ static void -handle_preference_change (void *cls, - const struct ChangePreferenceMessage *message) +handle_preference_change(void *cls, + const struct ChangePreferenceMessage *message) { struct GNUNET_SERVICE_Client *client = cls; - GAS_handle_preference_change (client, - message); - GNUNET_SERVICE_client_continue (client); + GAS_handle_preference_change(client, + message); + GNUNET_SERVICE_client_continue(client); } @@ -382,9 +386,9 @@ handle_preference_change (void *cls, * @return @a client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { return client; } @@ -399,15 +403,15 @@ client_connect_cb (void *cls, * @param app_ctx */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { if (NULL == client) return; - GAS_scheduling_remove_client (client); - GAS_connectivity_remove_client (client); - GAS_preference_client_disconnect (client); + GAS_scheduling_remove_client(client); + GAS_connectivity_remove_client(client); + GAS_preference_client_disconnect(client); } @@ -417,22 +421,22 @@ client_disconnect_cb (void *cls, * @param cls unused */ static void -cleanup_task (void *cls) +cleanup_task(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "ATS shutdown initiated\n"); - GAS_connectivity_done (); - GAS_addresses_done (); - GAS_plugin_done (); - GAS_normalization_stop (); - GAS_performance_done (); - GAS_preference_done (); - GAS_reservations_done (); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "ATS shutdown initiated\n"); + GAS_connectivity_done(); + GAS_addresses_done(); + GAS_plugin_done(); + GAS_normalization_stop(); + GAS_performance_done(); + GAS_preference_done(); + GAS_reservations_done(); if (NULL != GSA_stats) - { - GNUNET_STATISTICS_destroy (GSA_stats, GNUNET_NO); - GSA_stats = NULL; - } + { + GNUNET_STATISTICS_destroy(GSA_stats, GNUNET_NO); + GSA_stats = NULL; + } } @@ -444,37 +448,37 @@ cleanup_task (void *cls) * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_SERVICE_Handle *service) { - GSA_stats = GNUNET_STATISTICS_create ("ats", - cfg); - GAS_reservations_init (); - GAS_connectivity_init (); - GAS_preference_init (); - GAS_normalization_start (); - GAS_addresses_init (); + GSA_stats = GNUNET_STATISTICS_create("ats", + cfg); + GAS_reservations_init(); + GAS_connectivity_init(); + GAS_preference_init(); + GAS_normalization_start(); + GAS_addresses_init(); if (GNUNET_OK != - GAS_plugin_init (cfg)) - { - GNUNET_break (0); - GAS_addresses_done (); - GAS_normalization_stop (); - GAS_reservations_done (); - GAS_connectivity_done (); - GAS_preference_done (); - if (NULL != GSA_stats) + GAS_plugin_init(cfg)) { - GNUNET_STATISTICS_destroy (GSA_stats, - GNUNET_NO); - GSA_stats = NULL; + GNUNET_break(0); + GAS_addresses_done(); + GAS_normalization_stop(); + GAS_reservations_done(); + GAS_connectivity_done(); + GAS_preference_done(); + if (NULL != GSA_stats) + { + GNUNET_STATISTICS_destroy(GSA_stats, + GNUNET_NO); + GSA_stats = NULL; + } + return; } - return; - } - GAS_performance_init (); - GNUNET_SCHEDULER_add_shutdown (&cleanup_task, - NULL); + GAS_performance_init(); + GNUNET_SCHEDULER_add_shutdown(&cleanup_task, + NULL); } @@ -482,53 +486,53 @@ run (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("ats", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_fixed_size (ats_start, - GNUNET_MESSAGE_TYPE_ATS_START, - struct ClientStartMessage, - NULL), - GNUNET_MQ_hd_fixed_size (request_address, - GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS, - struct RequestAddressMessage, - NULL), - GNUNET_MQ_hd_fixed_size (request_address_cancel, - GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS_CANCEL, - struct RequestAddressMessage, - NULL), - GNUNET_MQ_hd_fixed_size (request_address_list, - GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_REQUEST, - struct AddressListRequestMessage, - NULL), - GNUNET_MQ_hd_var_size (address_add, - GNUNET_MESSAGE_TYPE_ATS_ADDRESS_ADD, - struct AddressAddMessage, - NULL), - GNUNET_MQ_hd_fixed_size (address_update, - GNUNET_MESSAGE_TYPE_ATS_ADDRESS_UPDATE, - struct AddressUpdateMessage, - NULL), - GNUNET_MQ_hd_fixed_size (address_destroyed, - GNUNET_MESSAGE_TYPE_ATS_ADDRESS_DESTROYED, - struct AddressDestroyedMessage, - NULL), - GNUNET_MQ_hd_fixed_size (reservation_request, - GNUNET_MESSAGE_TYPE_ATS_RESERVATION_REQUEST, - struct ReservationRequestMessage, - NULL), - GNUNET_MQ_hd_var_size (preference_change, - GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_CHANGE, - struct ChangePreferenceMessage, - NULL), - GNUNET_MQ_hd_var_size (feedback, - GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_FEEDBACK, - struct FeedbackPreferenceMessage, - NULL), - GNUNET_MQ_handler_end ()); + ("ats", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_fixed_size(ats_start, + GNUNET_MESSAGE_TYPE_ATS_START, + struct ClientStartMessage, + NULL), + GNUNET_MQ_hd_fixed_size(request_address, + GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS, + struct RequestAddressMessage, + NULL), + GNUNET_MQ_hd_fixed_size(request_address_cancel, + GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS_CANCEL, + struct RequestAddressMessage, + NULL), + GNUNET_MQ_hd_fixed_size(request_address_list, + GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_REQUEST, + struct AddressListRequestMessage, + NULL), + GNUNET_MQ_hd_var_size(address_add, + GNUNET_MESSAGE_TYPE_ATS_ADDRESS_ADD, + struct AddressAddMessage, + NULL), + GNUNET_MQ_hd_fixed_size(address_update, + GNUNET_MESSAGE_TYPE_ATS_ADDRESS_UPDATE, + struct AddressUpdateMessage, + NULL), + GNUNET_MQ_hd_fixed_size(address_destroyed, + GNUNET_MESSAGE_TYPE_ATS_ADDRESS_DESTROYED, + struct AddressDestroyedMessage, + NULL), + GNUNET_MQ_hd_fixed_size(reservation_request, + GNUNET_MESSAGE_TYPE_ATS_RESERVATION_REQUEST, + struct ReservationRequestMessage, + NULL), + GNUNET_MQ_hd_var_size(preference_change, + GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_CHANGE, + struct ChangePreferenceMessage, + NULL), + GNUNET_MQ_hd_var_size(feedback, + GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_FEEDBACK, + struct FeedbackPreferenceMessage, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-ats.c */ diff --git a/src/ats/gnunet-service-ats.h b/src/ats/gnunet-service-ats.h index 521a460ff..6abe57fdb 100644 --- a/src/ats/gnunet-service-ats.h +++ b/src/ats/gnunet-service-ats.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats.h @@ -31,7 +31,7 @@ #define GAS_normalization_queue_length 3 -#define BANDWIDTH_ZERO GNUNET_BANDWIDTH_value_init (0) +#define BANDWIDTH_ZERO GNUNET_BANDWIDTH_value_init(0) /** * Handle for statistics. diff --git a/src/ats/gnunet-service-ats_addresses.c b/src/ats/gnunet-service-ats_addresses.c index efe968024..8ca245b1e 100644 --- a/src/ats/gnunet-service-ats_addresses.c +++ b/src/ats/gnunet-service-ats_addresses.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2011-2015 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2011-2015 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -41,12 +41,12 @@ struct GNUNET_CONTAINER_MultiPeerMap *GSA_addresses; * Update statistic on number of addresses. */ static void -update_addresses_stat () +update_addresses_stat() { - GNUNET_STATISTICS_set (GSA_stats, - "# addresses", - GNUNET_CONTAINER_multipeermap_size (GSA_addresses), - GNUNET_NO); + GNUNET_STATISTICS_set(GSA_stats, + "# addresses", + GNUNET_CONTAINER_multipeermap_size(GSA_addresses), + GNUNET_NO); } @@ -56,25 +56,25 @@ update_addresses_stat () * @param addr address to destroy */ static void -free_address (struct ATS_Address *addr) +free_address(struct ATS_Address *addr) { - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (GSA_addresses, - &addr->peer, - addr)); - update_addresses_stat (); - GAS_plugin_delete_address (addr); - GAS_performance_notify_all_clients (&addr->peer, - addr->plugin, - addr->addr, - addr->addr_len, - GNUNET_NO, - NULL, - addr->local_address_info, - GNUNET_BANDWIDTH_ZERO, - GNUNET_BANDWIDTH_ZERO); - GNUNET_free (addr->plugin); - GNUNET_free (addr); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(GSA_addresses, + &addr->peer, + addr)); + update_addresses_stat(); + GAS_plugin_delete_address(addr); + GAS_performance_notify_all_clients(&addr->peer, + addr->plugin, + addr->addr, + addr->addr_len, + GNUNET_NO, + NULL, + addr->local_address_info, + GNUNET_BANDWIDTH_ZERO, + GNUNET_BANDWIDTH_ZERO); + GNUNET_free(addr->plugin); + GNUNET_free(addr); } @@ -84,7 +84,7 @@ free_address (struct ATS_Address *addr) * @param norm normalization data to initialize */ static void -init_norm (struct GAS_NormalizationInfo *norm) +init_norm(struct GAS_NormalizationInfo *norm) { unsigned int c; @@ -105,29 +105,29 @@ init_norm (struct GAS_NormalizationInfo *norm) * @return the ATS_Address */ static struct ATS_Address * -create_address (const struct GNUNET_PeerIdentity *peer, - const char *plugin_name, - const void *plugin_addr, - size_t plugin_addr_len, - uint32_t local_address_info, - uint32_t session_id) +create_address(const struct GNUNET_PeerIdentity *peer, + const char *plugin_name, + const void *plugin_addr, + size_t plugin_addr_len, + uint32_t local_address_info, + uint32_t session_id) { struct ATS_Address *aa; - aa = GNUNET_malloc (sizeof (struct ATS_Address) + plugin_addr_len); + aa = GNUNET_malloc(sizeof(struct ATS_Address) + plugin_addr_len); aa->peer = *peer; aa->addr_len = plugin_addr_len; aa->addr = &aa[1]; - GNUNET_memcpy (&aa[1], - plugin_addr, - plugin_addr_len); - aa->plugin = GNUNET_strdup (plugin_name); + GNUNET_memcpy(&aa[1], + plugin_addr, + plugin_addr_len); + aa->plugin = GNUNET_strdup(plugin_name); aa->session_id = session_id; aa->local_address_info = local_address_info; - init_norm (&aa->norm_delay); - init_norm (&aa->norm_distance); - init_norm (&aa->norm_utilization_in); - init_norm (&aa->norm_utilization_out); + init_norm(&aa->norm_delay); + init_norm(&aa->norm_distance); + init_norm(&aa->norm_utilization_in); + init_norm(&aa->norm_utilization_out); return aa; } @@ -135,8 +135,7 @@ create_address (const struct GNUNET_PeerIdentity *peer, /** * Closure for #find_address_cb() */ -struct FindAddressContext -{ +struct FindAddressContext { /** * Session Id to look for. */ @@ -146,7 +145,6 @@ struct FindAddressContext * Where to store matching address result. */ struct ATS_Address *exact_address; - }; @@ -159,18 +157,18 @@ struct FindAddressContext * @return #GNUNET_YES to continue, #GNUNET_NO if address is found */ static int -find_address_cb (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +find_address_cb(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct FindAddressContext *fac = cls; struct ATS_Address *aa = value; if (aa->session_id == fac->session_id) - { - fac->exact_address = aa; - return GNUNET_NO; - } + { + fac->exact_address = aa; + return GNUNET_NO; + } return GNUNET_YES; } @@ -183,16 +181,16 @@ find_address_cb (void *cls, * @return an ATS_address or NULL */ static struct ATS_Address * -find_exact_address (const struct GNUNET_PeerIdentity *peer, - uint32_t session_id) +find_exact_address(const struct GNUNET_PeerIdentity *peer, + uint32_t session_id) { struct FindAddressContext fac; fac.exact_address = NULL; fac.session_id = session_id; - GNUNET_CONTAINER_multipeermap_get_multiple (GSA_addresses, - peer, - &find_address_cb, &fac); + GNUNET_CONTAINER_multipeermap_get_multiple(GSA_addresses, + peer, + &find_address_cb, &fac); return fac.exact_address; } @@ -209,58 +207,58 @@ find_exact_address (const struct GNUNET_PeerIdentity *peer, * @param prop performance information for this address */ void -GAS_addresses_add (const struct GNUNET_PeerIdentity *peer, - const char *plugin_name, - const void *plugin_addr, - size_t plugin_addr_len, - uint32_t local_address_info, - uint32_t session_id, - const struct GNUNET_ATS_Properties *prop) +GAS_addresses_add(const struct GNUNET_PeerIdentity *peer, + const char *plugin_name, + const void *plugin_addr, + size_t plugin_addr_len, + uint32_t local_address_info, + uint32_t session_id, + const struct GNUNET_ATS_Properties *prop) { struct ATS_Address *new_address; - if (NULL != find_exact_address (peer, - session_id)) - { - GNUNET_break (0); - return; - } - GNUNET_break (GNUNET_NT_UNSPECIFIED != prop->scope); - new_address = create_address (peer, - plugin_name, - plugin_addr, - plugin_addr_len, - local_address_info, - session_id); + if (NULL != find_exact_address(peer, + session_id)) + { + GNUNET_break(0); + return; + } + GNUNET_break(GNUNET_NT_UNSPECIFIED != prop->scope); + new_address = create_address(peer, + plugin_name, + plugin_addr, + plugin_addr_len, + local_address_info, + session_id); /* Add a new address */ new_address->properties = *prop; new_address->t_added = GNUNET_TIME_absolute_get(); new_address->t_last_activity = GNUNET_TIME_absolute_get(); GNUNET_assert(GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put (GSA_addresses, - peer, - new_address, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); - update_addresses_stat (); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Adding new address for peer `%s' slot %u\n", - GNUNET_i2s (peer), - session_id); + GNUNET_CONTAINER_multipeermap_put(GSA_addresses, + peer, + new_address, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); + update_addresses_stat(); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Adding new address for peer `%s' slot %u\n", + GNUNET_i2s(peer), + session_id); /* Tell solver about new address */ - GAS_plugin_solver_lock (); - GAS_plugin_new_address (new_address); - GAS_normalization_update_property (new_address); // FIXME: needed? - GAS_plugin_solver_unlock (); + GAS_plugin_solver_lock(); + GAS_plugin_new_address(new_address); + GAS_normalization_update_property(new_address); // FIXME: needed? + GAS_plugin_solver_unlock(); /* Notify performance clients about new address */ - GAS_performance_notify_all_clients (&new_address->peer, - new_address->plugin, - new_address->addr, - new_address->addr_len, - new_address->active, - &new_address->properties, - new_address->local_address_info, - GNUNET_BANDWIDTH_value_init (new_address->assigned_bw_out), - GNUNET_BANDWIDTH_value_init (new_address->assigned_bw_in)); + GAS_performance_notify_all_clients(&new_address->peer, + new_address->plugin, + new_address->addr, + new_address->addr_len, + new_address->active, + &new_address->properties, + new_address->local_address_info, + GNUNET_BANDWIDTH_value_init(new_address->assigned_bw_out), + GNUNET_BANDWIDTH_value_init(new_address->assigned_bw_in)); } @@ -272,45 +270,45 @@ GAS_addresses_add (const struct GNUNET_PeerIdentity *peer, * @param prop performance information for this address */ void -GAS_addresses_update (const struct GNUNET_PeerIdentity *peer, - uint32_t session_id, - const struct GNUNET_ATS_Properties *prop) +GAS_addresses_update(const struct GNUNET_PeerIdentity *peer, + uint32_t session_id, + const struct GNUNET_ATS_Properties *prop) { struct ATS_Address *aa; /* Get existing address */ - aa = find_exact_address (peer, - session_id); + aa = find_exact_address(peer, + session_id); if (NULL == aa) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } if (NULL == aa->solver_information) - { - GNUNET_break (0); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ADDRESS_UPDATE for peer `%s' slot %u\n", - GNUNET_i2s (peer), - (unsigned int) session_id); - GNUNET_break (GNUNET_NT_UNSPECIFIED != prop->scope); + { + GNUNET_break(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ADDRESS_UPDATE for peer `%s' slot %u\n", + GNUNET_i2s(peer), + (unsigned int)session_id); + GNUNET_break(GNUNET_NT_UNSPECIFIED != prop->scope); /* Update address */ aa->t_last_activity = GNUNET_TIME_absolute_get(); aa->properties = *prop; /* Notify performance clients about updated address */ - GAS_performance_notify_all_clients (&aa->peer, - aa->plugin, - aa->addr, - aa->addr_len, - aa->active, - prop, - aa->local_address_info, - GNUNET_BANDWIDTH_value_init (aa->assigned_bw_out), - GNUNET_BANDWIDTH_value_init (aa->assigned_bw_in)); - - GAS_normalization_update_property (aa); + GAS_performance_notify_all_clients(&aa->peer, + aa->plugin, + aa->addr, + aa->addr_len, + aa->active, + prop, + aa->local_address_info, + GNUNET_BANDWIDTH_value_init(aa->assigned_bw_out), + GNUNET_BANDWIDTH_value_init(aa->assigned_bw_in)); + + GAS_normalization_update_property(aa); } @@ -321,24 +319,24 @@ GAS_addresses_update (const struct GNUNET_PeerIdentity *peer, * @param session_id session id, can never be 0 */ void -GAS_addresses_destroy (const struct GNUNET_PeerIdentity *peer, - uint32_t session_id) +GAS_addresses_destroy(const struct GNUNET_PeerIdentity *peer, + uint32_t session_id) { struct ATS_Address *ea; /* Get existing address */ - ea = find_exact_address (peer, - session_id); + ea = find_exact_address(peer, + session_id); if (NULL == ea) - { - GNUNET_break (0); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ADDRESS_DESTROYED for peer `%s' session %u\n", - GNUNET_i2s (peer), - session_id); - free_address (ea); + { + GNUNET_break(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ADDRESS_DESTROYED for peer `%s' session %u\n", + GNUNET_i2s(peer), + session_id); + free_address(ea); } @@ -349,12 +347,12 @@ GAS_addresses_destroy (const struct GNUNET_PeerIdentity *peer, * and receives updates when the solver changes the resource allocation. */ void -GAS_addresses_init () +GAS_addresses_init() { GSA_addresses - = GNUNET_CONTAINER_multipeermap_create (128, - GNUNET_NO); - update_addresses_stat (); + = GNUNET_CONTAINER_multipeermap_create(128, + GNUNET_NO); + update_addresses_stat(); } @@ -367,13 +365,13 @@ GAS_addresses_init () * @return #GNUNET_OK (continue to iterate) */ static int -destroy_all_address_it (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +destroy_all_address_it(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct ATS_Address *aa = value; - free_address (aa); + free_address(aa); return GNUNET_OK; } @@ -382,18 +380,18 @@ destroy_all_address_it (void *cls, * Remove all addresses */ void -GAS_addresses_destroy_all () +GAS_addresses_destroy_all() { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Destroying all addresses\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Destroying all addresses\n"); if (0 == - GNUNET_CONTAINER_multipeermap_size (GSA_addresses)) + GNUNET_CONTAINER_multipeermap_size(GSA_addresses)) return; - GAS_plugin_solver_lock (); - GNUNET_CONTAINER_multipeermap_iterate (GSA_addresses, - &destroy_all_address_it, - NULL); - GAS_plugin_solver_unlock (); + GAS_plugin_solver_lock(); + GNUNET_CONTAINER_multipeermap_iterate(GSA_addresses, + &destroy_all_address_it, + NULL); + GAS_plugin_solver_unlock(); } @@ -401,14 +399,14 @@ GAS_addresses_destroy_all () * Shutdown address subsystem. */ void -GAS_addresses_done () +GAS_addresses_done() { GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Shutting down addresses\n"); - GAS_plugin_solver_lock (); - GAS_addresses_destroy_all (); - GAS_plugin_solver_unlock (); - GNUNET_CONTAINER_multipeermap_destroy (GSA_addresses); + GAS_plugin_solver_lock(); + GAS_addresses_destroy_all(); + GAS_plugin_solver_unlock(); + GNUNET_CONTAINER_multipeermap_destroy(GSA_addresses); GSA_addresses = NULL; } @@ -416,8 +414,7 @@ GAS_addresses_done () /** * Closure for #peerinfo_it(). */ -struct PeerInfoIteratorContext -{ +struct PeerInfoIteratorContext { /** * Function to call for each address. */ @@ -439,23 +436,23 @@ struct PeerInfoIteratorContext * @return #GNUNET_OK to continue */ static int -peerinfo_it (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +peerinfo_it(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct PeerInfoIteratorContext *pi_ctx = cls; struct ATS_Address *addr = value; - pi_ctx->it (pi_ctx->it_cls, - &addr->peer, - addr->plugin, - addr->addr, - addr->addr_len, - addr->active, - &addr->properties, - addr->local_address_info, - GNUNET_BANDWIDTH_value_init (addr->assigned_bw_out), - GNUNET_BANDWIDTH_value_init (addr->assigned_bw_in)); + pi_ctx->it(pi_ctx->it_cls, + &addr->peer, + addr->plugin, + addr->addr, + addr->addr_len, + addr->active, + &addr->properties, + addr->local_address_info, + GNUNET_BANDWIDTH_value_init(addr->assigned_bw_out), + GNUNET_BANDWIDTH_value_init(addr->assigned_bw_in)); return GNUNET_OK; } @@ -468,41 +465,41 @@ peerinfo_it (void *cls, * @param pi_it_cls the closure for @a pi_it */ void -GAS_addresses_get_peer_info (const struct GNUNET_PeerIdentity *peer, - GNUNET_ATS_PeerInfo_Iterator pi_it, - void *pi_it_cls) +GAS_addresses_get_peer_info(const struct GNUNET_PeerIdentity *peer, + GNUNET_ATS_PeerInfo_Iterator pi_it, + void *pi_it_cls) { struct PeerInfoIteratorContext pi_ctx; if (NULL == pi_it) - { - /* does not make sense without callback */ - GNUNET_break (0); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Returning information for %s from a total of %u known addresses\n", - (NULL == peer) - ? "all peers" - : GNUNET_i2s (peer), - (unsigned int) GNUNET_CONTAINER_multipeermap_size (GSA_addresses)); + { + /* does not make sense without callback */ + GNUNET_break(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Returning information for %s from a total of %u known addresses\n", + (NULL == peer) + ? "all peers" + : GNUNET_i2s(peer), + (unsigned int)GNUNET_CONTAINER_multipeermap_size(GSA_addresses)); pi_ctx.it = pi_it; pi_ctx.it_cls = pi_it_cls; if (NULL == peer) - GNUNET_CONTAINER_multipeermap_iterate (GSA_addresses, - &peerinfo_it, - &pi_ctx); + GNUNET_CONTAINER_multipeermap_iterate(GSA_addresses, + &peerinfo_it, + &pi_ctx); else - GNUNET_CONTAINER_multipeermap_get_multiple (GSA_addresses, - peer, - &peerinfo_it, &pi_ctx); - pi_it (pi_it_cls, - NULL, NULL, NULL, 0, - GNUNET_NO, - NULL, - GNUNET_HELLO_ADDRESS_INFO_NONE, - GNUNET_BANDWIDTH_ZERO, - GNUNET_BANDWIDTH_ZERO); + GNUNET_CONTAINER_multipeermap_get_multiple(GSA_addresses, + peer, + &peerinfo_it, &pi_ctx); + pi_it(pi_it_cls, + NULL, NULL, NULL, 0, + GNUNET_NO, + NULL, + GNUNET_HELLO_ADDRESS_INFO_NONE, + GNUNET_BANDWIDTH_ZERO, + GNUNET_BANDWIDTH_ZERO); } @@ -510,8 +507,7 @@ GAS_addresses_get_peer_info (const struct GNUNET_PeerIdentity *peer, * Information we need for the callbacks to return a list of addresses * back to the client. */ -struct AddressIteration -{ +struct AddressIteration { /** * Actual handle to the client. */ @@ -526,7 +522,6 @@ struct AddressIteration * Which ID should be included in the response? */ uint32_t id; - }; @@ -546,16 +541,16 @@ struct AddressIteration * @param bandwidth_in current inbound bandwidth assigned to address */ static void -transmit_req_addr (struct AddressIteration *ai, - const struct GNUNET_PeerIdentity *id, - const char *plugin_name, - const void *plugin_addr, - size_t plugin_addr_len, - int active, - const struct GNUNET_ATS_Properties *prop, - enum GNUNET_HELLO_AddressInfo local_address_info, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) +transmit_req_addr(struct AddressIteration *ai, + const struct GNUNET_PeerIdentity *id, + const char *plugin_name, + const void *plugin_addr, + size_t plugin_addr_len, + int active, + const struct GNUNET_ATS_Properties *prop, + enum GNUNET_HELLO_AddressInfo local_address_info, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) { struct GNUNET_MQ_Envelope *env; @@ -565,37 +560,37 @@ transmit_req_addr (struct AddressIteration *ai, size_t msize; if (NULL != plugin_name) - plugin_name_length = strlen (plugin_name) + 1; + plugin_name_length = strlen(plugin_name) + 1; else plugin_name_length = 0; msize = plugin_addr_len + plugin_name_length; - GNUNET_assert (sizeof (struct PeerInformationMessage) + msize - < GNUNET_MAX_MESSAGE_SIZE); - env = GNUNET_MQ_msg_extra (msg, - msize, - GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_RESPONSE); - msg->id = htonl (ai->id); + GNUNET_assert(sizeof(struct PeerInformationMessage) + msize + < GNUNET_MAX_MESSAGE_SIZE); + env = GNUNET_MQ_msg_extra(msg, + msize, + GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_RESPONSE); + msg->id = htonl(ai->id); if (NULL != id) msg->peer = *id; - msg->address_length = htons (plugin_addr_len); - msg->address_active = ntohl (active); - msg->plugin_name_length = htons (plugin_name_length); + msg->address_length = htons(plugin_addr_len); + msg->address_active = ntohl(active); + msg->plugin_name_length = htons(plugin_name_length); msg->bandwidth_out = bandwidth_out; msg->bandwidth_in = bandwidth_in; if (NULL != prop) - GNUNET_ATS_properties_hton (&msg->properties, - prop); - msg->address_local_info = htonl ((uint32_t) local_address_info); - addrp = (char *) &msg[1]; - GNUNET_memcpy (addrp, - plugin_addr, - plugin_addr_len); + GNUNET_ATS_properties_hton(&msg->properties, + prop); + msg->address_local_info = htonl((uint32_t)local_address_info); + addrp = (char *)&msg[1]; + GNUNET_memcpy(addrp, + plugin_addr, + plugin_addr_len); if (NULL != plugin_name) - strcpy (&addrp[plugin_addr_len], - plugin_name); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (ai->client), - env); + strcpy(&addrp[plugin_addr_len], + plugin_name); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(ai->client), + env); } @@ -615,48 +610,48 @@ transmit_req_addr (struct AddressIteration *ai, * @param bandwidth_in current inbound bandwidth assigned to address */ static void -req_addr_peerinfo_it (void *cls, - const struct GNUNET_PeerIdentity *id, - const char *plugin_name, - const void *plugin_addr, - size_t plugin_addr_len, - int active, - const struct GNUNET_ATS_Properties *prop, - enum GNUNET_HELLO_AddressInfo local_address_info, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) +req_addr_peerinfo_it(void *cls, + const struct GNUNET_PeerIdentity *id, + const char *plugin_name, + const void *plugin_addr, + size_t plugin_addr_len, + int active, + const struct GNUNET_ATS_Properties *prop, + enum GNUNET_HELLO_AddressInfo local_address_info, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) { struct AddressIteration *ai = cls; - if ( (NULL == id) && - (NULL == plugin_name) && - (NULL == plugin_addr) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Address iteration done for one peer\n"); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Callback for %s peer `%s' plugin `%s' BW out %u, BW in %u\n", - (active == GNUNET_YES) ? "ACTIVE" : "INACTIVE", - GNUNET_i2s (id), - plugin_name, - (unsigned int) ntohl (bandwidth_out.value__), - (unsigned int) ntohl (bandwidth_in.value__)); + if ((NULL == id) && + (NULL == plugin_name) && + (NULL == plugin_addr)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Address iteration done for one peer\n"); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Callback for %s peer `%s' plugin `%s' BW out %u, BW in %u\n", + (active == GNUNET_YES) ? "ACTIVE" : "INACTIVE", + GNUNET_i2s(id), + plugin_name, + (unsigned int)ntohl(bandwidth_out.value__), + (unsigned int)ntohl(bandwidth_in.value__)); /* Transmit result (either if address is active, or if client wanted all addresses) */ - if ( (GNUNET_YES != ai->all) && - (GNUNET_YES != active)) + if ((GNUNET_YES != ai->all) && + (GNUNET_YES != active)) return; - transmit_req_addr (ai, - id, - plugin_name, - plugin_addr, plugin_addr_len, - active, - prop, - local_address_info, - bandwidth_out, - bandwidth_in); + transmit_req_addr(ai, + id, + plugin_name, + plugin_addr, plugin_addr_len, + active, + prop, + local_address_info, + bandwidth_out, + bandwidth_in); } @@ -667,45 +662,45 @@ req_addr_peerinfo_it (void *cls, * @param alrm the request message */ void -GAS_handle_request_address_list (struct GNUNET_SERVICE_Client *client, - const struct AddressListRequestMessage *alrm) +GAS_handle_request_address_list(struct GNUNET_SERVICE_Client *client, + const struct AddressListRequestMessage *alrm) { struct AddressIteration ai; struct GNUNET_PeerIdentity allzeros; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ADDRESSLIST_REQUEST message\n"); - ai.all = ntohl (alrm->all); - ai.id = ntohl (alrm->id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ADDRESSLIST_REQUEST message\n"); + ai.all = ntohl(alrm->all); + ai.id = ntohl(alrm->id); ai.client = client; - memset (&allzeros, - '\0', - sizeof (struct GNUNET_PeerIdentity)); - if (0 == GNUNET_is_zero (&alrm->peer)) - { - /* Return addresses for all peers */ - GAS_addresses_get_peer_info (NULL, - &req_addr_peerinfo_it, - &ai); - } + memset(&allzeros, + '\0', + sizeof(struct GNUNET_PeerIdentity)); + if (0 == GNUNET_is_zero(&alrm->peer)) + { + /* Return addresses for all peers */ + GAS_addresses_get_peer_info(NULL, + &req_addr_peerinfo_it, + &ai); + } else - { - /* Return addresses for a specific peer */ - GAS_addresses_get_peer_info (&alrm->peer, - &req_addr_peerinfo_it, - &ai); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished handling `%s' message\n", - "ADDRESSLIST_REQUEST"); - transmit_req_addr (&ai, - NULL, NULL, NULL, - 0, GNUNET_NO, - NULL, - GNUNET_HELLO_ADDRESS_INFO_NONE, - GNUNET_BANDWIDTH_ZERO, - GNUNET_BANDWIDTH_ZERO); + { + /* Return addresses for a specific peer */ + GAS_addresses_get_peer_info(&alrm->peer, + &req_addr_peerinfo_it, + &ai); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished handling `%s' message\n", + "ADDRESSLIST_REQUEST"); + transmit_req_addr(&ai, + NULL, NULL, NULL, + 0, GNUNET_NO, + NULL, + GNUNET_HELLO_ADDRESS_INFO_NONE, + GNUNET_BANDWIDTH_ZERO, + GNUNET_BANDWIDTH_ZERO); } diff --git a/src/ats/gnunet-service-ats_addresses.h b/src/ats/gnunet-service-ats_addresses.h index c9ad9a45d..f7dd98b1e 100644 --- a/src/ats/gnunet-service-ats_addresses.h +++ b/src/ats/gnunet-service-ats_addresses.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2011-2014 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2011-2014 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -226,8 +226,7 @@ /** * Information provided by ATS normalization */ -struct GAS_NormalizationInfo -{ +struct GAS_NormalizationInfo { /** * Next index to use in averaging queue */ @@ -253,8 +252,7 @@ struct GAS_NormalizationInfo /** * Address with additional information */ -struct ATS_Address -{ +struct ATS_Address { /** * Peer ID this address is for. */ @@ -350,11 +348,10 @@ struct ATS_Address */ struct GAS_NormalizationInfo norm_utilization_in; - /** + /** * Normalized utilization outbound for this address. */ struct GAS_NormalizationInfo norm_utilization_out; - }; @@ -369,14 +366,14 @@ extern struct GNUNET_CONTAINER_MultiPeerMap *GSA_addresses; * known and current performance information. */ void -GAS_addresses_init (void); +GAS_addresses_init(void); /** * Shutdown address subsystem. */ void -GAS_addresses_done (void); +GAS_addresses_done(void); /** @@ -391,13 +388,13 @@ GAS_addresses_done (void); * @param prop performance information for this address */ void -GAS_addresses_add (const struct GNUNET_PeerIdentity *peer, - const char *plugin_name, - const void *plugin_addr, - size_t plugin_addr_len, - uint32_t local_address_info, - uint32_t session_id, - const struct GNUNET_ATS_Properties *prop); +GAS_addresses_add(const struct GNUNET_PeerIdentity *peer, + const char *plugin_name, + const void *plugin_addr, + size_t plugin_addr_len, + uint32_t local_address_info, + uint32_t session_id, + const struct GNUNET_ATS_Properties *prop); /** @@ -408,9 +405,9 @@ GAS_addresses_add (const struct GNUNET_PeerIdentity *peer, * @param prop performance information for this address */ void -GAS_addresses_update (const struct GNUNET_PeerIdentity *peer, - uint32_t session_id, - const struct GNUNET_ATS_Properties *prop); +GAS_addresses_update(const struct GNUNET_PeerIdentity *peer, + uint32_t session_id, + const struct GNUNET_ATS_Properties *prop); /** @@ -420,15 +417,15 @@ GAS_addresses_update (const struct GNUNET_PeerIdentity *peer, * @param session_id session id, can never be 0 */ void -GAS_addresses_destroy (const struct GNUNET_PeerIdentity *peer, - uint32_t session_id); +GAS_addresses_destroy(const struct GNUNET_PeerIdentity *peer, + uint32_t session_id); /** * Remove all addresses. */ void -GAS_addresses_destroy_all (void); +GAS_addresses_destroy_all(void); /** @@ -466,9 +463,9 @@ typedef void * @param pi_it_cls the closure for @a pi_it */ void -GAS_addresses_get_peer_info (const struct GNUNET_PeerIdentity *peer, - GNUNET_ATS_PeerInfo_Iterator pi_it, - void *pi_it_cls); +GAS_addresses_get_peer_info(const struct GNUNET_PeerIdentity *peer, + GNUNET_ATS_PeerInfo_Iterator pi_it, + void *pi_it_cls); /** @@ -478,8 +475,8 @@ GAS_addresses_get_peer_info (const struct GNUNET_PeerIdentity *peer, * @param alrm the request message */ void -GAS_handle_request_address_list (struct GNUNET_SERVICE_Client *client, - const struct AddressListRequestMessage *alrm); +GAS_handle_request_address_list(struct GNUNET_SERVICE_Client *client, + const struct AddressListRequestMessage *alrm); #endif diff --git a/src/ats/gnunet-service-ats_connectivity.c b/src/ats/gnunet-service-ats_connectivity.c index 3853aeb0e..f71d18e82 100644 --- a/src/ats/gnunet-service-ats_connectivity.c +++ b/src/ats/gnunet-service-ats_connectivity.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats_connectivity.c @@ -35,8 +35,7 @@ /** * Active connection requests. */ -struct ConnectionRequest -{ +struct ConnectionRequest { /** * Client that made the request. */ @@ -61,14 +60,14 @@ static struct GNUNET_CONTAINER_MultiPeerMap *connection_requests; * @return #GNUNET_YES if so, #GNUNET_NO if not */ unsigned int -GAS_connectivity_has_peer (void *cls, - const struct GNUNET_PeerIdentity *peer) +GAS_connectivity_has_peer(void *cls, + const struct GNUNET_PeerIdentity *peer) { if (NULL == connection_requests) return 0; /* TODO: return sum of 'strength's of connectivity requests */ - return GNUNET_CONTAINER_multipeermap_contains (connection_requests, - peer); + return GNUNET_CONTAINER_multipeermap_contains(connection_requests, + peer); } @@ -79,22 +78,22 @@ GAS_connectivity_has_peer (void *cls, * @param message the request message */ void -GAS_handle_request_address (struct GNUNET_SERVICE_Client *client, - const struct RequestAddressMessage *msg) +GAS_handle_request_address(struct GNUNET_SERVICE_Client *client, + const struct RequestAddressMessage *msg) { struct ConnectionRequest *cr; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received `%s' message\n", - "GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received `%s' message\n", + "GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS"); /* FIXME: should not ignore "msg->strength" */ - cr = GNUNET_new (struct ConnectionRequest); + cr = GNUNET_new(struct ConnectionRequest); cr->client = client; - (void) GNUNET_CONTAINER_multipeermap_put (connection_requests, - &msg->peer, - cr, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - GAS_plugin_request_connect_start (&msg->peer); + (void)GNUNET_CONTAINER_multipeermap_put(connection_requests, + &msg->peer, + cr, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + GAS_plugin_request_connect_start(&msg->peer); } @@ -108,25 +107,25 @@ GAS_handle_request_address (struct GNUNET_SERVICE_Client *client, * @return #GNUNET_OK (continue to iterate) */ static int -free_matching_requests (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *value) +free_matching_requests(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *value) { struct GNUNET_SERVICE_Client *client = cls; struct ConnectionRequest *cr = value; if (cr->client == client) - { - GAS_plugin_request_connect_stop (pid); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Removed request pending for peer `%s\n", - GNUNET_i2s (pid)); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (connection_requests, + { + GAS_plugin_request_connect_stop(pid); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Removed request pending for peer `%s\n", + GNUNET_i2s(pid)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(connection_requests, pid, cr)); - GNUNET_free (cr); - } + GNUNET_free(cr); + } return GNUNET_OK; } @@ -139,17 +138,17 @@ free_matching_requests (void *cls, * @param msg the request message */ void -GAS_handle_request_address_cancel (struct GNUNET_SERVICE_Client *client, - const struct RequestAddressMessage *msg) +GAS_handle_request_address_cancel(struct GNUNET_SERVICE_Client *client, + const struct RequestAddressMessage *msg) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS_CANCEL message for peer %s\n", - GNUNET_i2s (&msg->peer)); - GNUNET_break (0 == ntohl (msg->strength)); - GNUNET_CONTAINER_multipeermap_get_multiple (connection_requests, - &msg->peer, - &free_matching_requests, - client); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS_CANCEL message for peer %s\n", + GNUNET_i2s(&msg->peer)); + GNUNET_break(0 == ntohl(msg->strength)); + GNUNET_CONTAINER_multipeermap_get_multiple(connection_requests, + &msg->peer, + &free_matching_requests, + client); } @@ -160,11 +159,11 @@ GAS_handle_request_address_cancel (struct GNUNET_SERVICE_Client *client, * @param client handle of the (now dead) client */ void -GAS_connectivity_remove_client (struct GNUNET_SERVICE_Client *client) +GAS_connectivity_remove_client(struct GNUNET_SERVICE_Client *client) { - GNUNET_CONTAINER_multipeermap_iterate (connection_requests, - &free_matching_requests, - client); + GNUNET_CONTAINER_multipeermap_iterate(connection_requests, + &free_matching_requests, + client); } @@ -172,11 +171,11 @@ GAS_connectivity_remove_client (struct GNUNET_SERVICE_Client *client) * Shutdown connectivity subsystem. */ void -GAS_connectivity_init () +GAS_connectivity_init() { connection_requests - = GNUNET_CONTAINER_multipeermap_create (32, - GNUNET_NO); + = GNUNET_CONTAINER_multipeermap_create(32, + GNUNET_NO); } @@ -189,15 +188,15 @@ GAS_connectivity_init () * @return #GNUNET_OK (continue to iterate) */ static int -free_request (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *value) +free_request(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *value) { struct ConnectionRequest *cr = value; - free_matching_requests (cr->client, - pid, - cr); + free_matching_requests(cr->client, + pid, + cr); return GNUNET_OK; } @@ -206,14 +205,14 @@ free_request (void *cls, * Shutdown connectivity subsystem. */ void -GAS_connectivity_done () +GAS_connectivity_done() { - GAS_plugin_solver_lock (); - GNUNET_CONTAINER_multipeermap_iterate (connection_requests, - &free_request, - NULL); - GAS_plugin_solver_unlock (); - GNUNET_CONTAINER_multipeermap_destroy (connection_requests); + GAS_plugin_solver_lock(); + GNUNET_CONTAINER_multipeermap_iterate(connection_requests, + &free_request, + NULL); + GAS_plugin_solver_unlock(); + GNUNET_CONTAINER_multipeermap_destroy(connection_requests); connection_requests = NULL; } diff --git a/src/ats/gnunet-service-ats_connectivity.h b/src/ats/gnunet-service-ats_connectivity.h index 891a923db..98d84b44a 100644 --- a/src/ats/gnunet-service-ats_connectivity.h +++ b/src/ats/gnunet-service-ats_connectivity.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats_connectivity.h * @brief ats service, interaction with 'connecivity' API @@ -38,8 +38,8 @@ * @return #GNUNET_YES if so, #GNUNET_NO if not */ unsigned int -GAS_connectivity_has_peer (void *cls, - const struct GNUNET_PeerIdentity *peer); +GAS_connectivity_has_peer(void *cls, + const struct GNUNET_PeerIdentity *peer); /** @@ -49,8 +49,8 @@ GAS_connectivity_has_peer (void *cls, * @param msg the request message */ void -GAS_handle_request_address (struct GNUNET_SERVICE_Client *client, - const struct RequestAddressMessage *msg); +GAS_handle_request_address(struct GNUNET_SERVICE_Client *client, + const struct RequestAddressMessage *msg); /** @@ -60,8 +60,8 @@ GAS_handle_request_address (struct GNUNET_SERVICE_Client *client, * @param msg the request message */ void -GAS_handle_request_address_cancel (struct GNUNET_SERVICE_Client *client, - const struct RequestAddressMessage *msg); +GAS_handle_request_address_cancel(struct GNUNET_SERVICE_Client *client, + const struct RequestAddressMessage *msg); /** @@ -71,21 +71,21 @@ GAS_handle_request_address_cancel (struct GNUNET_SERVICE_Client *client, * @param client handle of the (now dead) client */ void -GAS_connectivity_remove_client (struct GNUNET_SERVICE_Client *client); +GAS_connectivity_remove_client(struct GNUNET_SERVICE_Client *client); /** * Initialize connectivity subsystem. */ void -GAS_connectivity_init (void); +GAS_connectivity_init(void); /** * Shutdown connectivity subsystem. */ void -GAS_connectivity_done (void); +GAS_connectivity_done(void); #endif diff --git a/src/ats/gnunet-service-ats_normalization.c b/src/ats/gnunet-service-ats_normalization.c index 4b58bf9b7..fa2b37425 100644 --- a/src/ats/gnunet-service-ats_normalization.c +++ b/src/ats/gnunet-service-ats_normalization.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2011-2015 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2011-2015 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -31,14 +31,13 @@ #include "gnunet-service-ats_normalization.h" #include "gnunet-service-ats_plugins.h" -#define LOG(kind,...) GNUNET_log_from (kind, "ats-normalization",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "ats-normalization", __VA_ARGS__) /** * Range information for normalization of quality properties. */ -struct PropertyRange -{ +struct PropertyRange { /** * Minimum value we see for this property across all addresses. */ @@ -65,8 +64,8 @@ static struct PropertyRange property_range; * @param ni normalization information to update */ static void -update_avg (uint64_t current_val, - struct GAS_NormalizationInfo *ni) +update_avg(uint64_t current_val, + struct GAS_NormalizationInfo *ni) { double sum; uint32_t count; @@ -78,13 +77,13 @@ update_avg (uint64_t current_val, count = 0; sum = 0.0; for (c1 = 0; c1 < GAS_normalization_queue_length; c1++) - { - if (UINT64_MAX != ni->atsi_abs[c1]) { - count++; - sum += (double) ni->atsi_abs[c1]; + if (UINT64_MAX != ni->atsi_abs[c1]) + { + count++; + sum += (double)ni->atsi_abs[c1]; + } } - } if (0 == count) ni->avg = current_val; /* must be UINT64_MAX */ else @@ -103,29 +102,29 @@ update_avg (uint64_t current_val, * @return #GNUNET_OK (continue to iterate) */ static int -find_min_max_it (void *cls, - const struct GNUNET_PeerIdentity *h, - void *k) +find_min_max_it(void *cls, + const struct GNUNET_PeerIdentity *h, + void *k) { struct PropertyRange *pr = cls; const struct ATS_Address *a = k; - pr->max.utilization_out = GNUNET_MAX (pr->max.utilization_out, - a->properties.utilization_out); - pr->max.utilization_in = GNUNET_MAX (pr->max.utilization_in, - a->properties.utilization_in); - pr->max.distance = GNUNET_MAX (pr->max.distance, - a->properties.distance); - pr->max.delay = GNUNET_TIME_relative_max (pr->max.delay, - a->properties.delay); - pr->min.utilization_out = GNUNET_MIN (pr->min.utilization_out, - a->properties.utilization_out); - pr->min.utilization_in = GNUNET_MIN (pr->min.utilization_in, - a->properties.utilization_in); - pr->min.distance = GNUNET_MIN (pr->min.distance, - a->properties.distance); - pr->min.delay = GNUNET_TIME_relative_min (pr->min.delay, - a->properties.delay); + pr->max.utilization_out = GNUNET_MAX(pr->max.utilization_out, + a->properties.utilization_out); + pr->max.utilization_in = GNUNET_MAX(pr->max.utilization_in, + a->properties.utilization_in); + pr->max.distance = GNUNET_MAX(pr->max.distance, + a->properties.distance); + pr->max.delay = GNUNET_TIME_relative_max(pr->max.delay, + a->properties.delay); + pr->min.utilization_out = GNUNET_MIN(pr->min.utilization_out, + a->properties.utilization_out); + pr->min.utilization_in = GNUNET_MIN(pr->min.utilization_in, + a->properties.utilization_in); + pr->min.distance = GNUNET_MIN(pr->min.distance, + a->properties.distance); + pr->min.delay = GNUNET_TIME_relative_min(pr->min.delay, + a->properties.delay); return GNUNET_OK; } @@ -139,13 +138,13 @@ find_min_max_it (void *cls, * @param ni normalization information to update */ static void -update_norm (uint64_t min, - uint64_t max, - struct GAS_NormalizationInfo *ni) +update_norm(uint64_t min, + uint64_t max, + struct GAS_NormalizationInfo *ni) { /* max - 2 * min + avg_value / (max - min) */ if (min < max) - ni->norm = DEFAULT_REL_QUALITY + (ni->avg - min) / (double) (max - min); + ni->norm = DEFAULT_REL_QUALITY + (ni->avg - min) / (double)(max - min); else ni->norm = DEFAULT_REL_QUALITY; } @@ -163,24 +162,24 @@ update_norm (uint64_t min, * @return #GNUNET_OK (continue to iterate) */ static int -normalize_address (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +normalize_address(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct ATS_Address *address = value; - update_norm (property_range.min.delay.rel_value_us, - property_range.max.delay.rel_value_us, - &address->norm_delay); - update_norm (property_range.min.distance, - property_range.max.distance, - &address->norm_distance); - update_norm (property_range.min.utilization_in, - property_range.max.utilization_in, - &address->norm_utilization_in); - update_norm (property_range.min.utilization_out, - property_range.max.utilization_out, - &address->norm_utilization_out); + update_norm(property_range.min.delay.rel_value_us, + property_range.max.delay.rel_value_us, + &address->norm_delay); + update_norm(property_range.min.distance, + property_range.max.distance, + &address->norm_distance); + update_norm(property_range.min.utilization_in, + property_range.max.utilization_in, + &address->norm_utilization_in); + update_norm(property_range.min.utilization_out, + property_range.max.utilization_out, + &address->norm_utilization_out); return GNUNET_OK; } @@ -194,13 +193,13 @@ normalize_address (void *cls, * @return #GNUNET_OK (continue to iterate) */ static int -notify_change (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +notify_change(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct ATS_Address *address = value; - GAS_plugin_notify_property_changed (address); + GAS_plugin_notify_property_changed(address); return GNUNET_OK; } @@ -212,9 +211,9 @@ notify_change (void *cls, * @param pr range to initialize */ static void -init_range (struct PropertyRange *pr) +init_range(struct PropertyRange *pr) { - memset (pr, 0, sizeof (struct PropertyRange)); + memset(pr, 0, sizeof(struct PropertyRange)); pr->min.utilization_out = UINT32_MAX; pr->min.utilization_in = UINT32_MAX; pr->min.distance = UINT32_MAX; @@ -228,51 +227,51 @@ init_range (struct PropertyRange *pr) * @param address the address to update */ void -GAS_normalization_update_property (struct ATS_Address *address) +GAS_normalization_update_property(struct ATS_Address *address) { const struct GNUNET_ATS_Properties *prop = &address->properties; struct PropertyRange range; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Updating properties for peer `%s'\n", - GNUNET_i2s (&address->peer)); - GAS_plugin_solver_lock (); - update_avg (prop->delay.rel_value_us, - &address->norm_delay); - update_avg (prop->distance, - &address->norm_distance); - update_avg (prop->utilization_in, - &address->norm_utilization_in); - update_avg (prop->utilization_in, - &address->norm_utilization_out); - - init_range (&range); - GNUNET_CONTAINER_multipeermap_iterate (GSA_addresses, - &find_min_max_it, - &range); - if (0 != GNUNET_memcmp (&range, - &property_range)) - { - /* limits changed, (re)normalize all addresses */ - property_range = range; - GNUNET_CONTAINER_multipeermap_iterate (GSA_addresses, - &normalize_address, - NULL); - GNUNET_CONTAINER_multipeermap_iterate (GSA_addresses, - ¬ify_change, - NULL); - } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Updating properties for peer `%s'\n", + GNUNET_i2s(&address->peer)); + GAS_plugin_solver_lock(); + update_avg(prop->delay.rel_value_us, + &address->norm_delay); + update_avg(prop->distance, + &address->norm_distance); + update_avg(prop->utilization_in, + &address->norm_utilization_in); + update_avg(prop->utilization_in, + &address->norm_utilization_out); + + init_range(&range); + GNUNET_CONTAINER_multipeermap_iterate(GSA_addresses, + &find_min_max_it, + &range); + if (0 != GNUNET_memcmp(&range, + &property_range)) + { + /* limits changed, (re)normalize all addresses */ + property_range = range; + GNUNET_CONTAINER_multipeermap_iterate(GSA_addresses, + &normalize_address, + NULL); + GNUNET_CONTAINER_multipeermap_iterate(GSA_addresses, + ¬ify_change, + NULL); + } else - { - /* renormalize just this one address */ - normalize_address (NULL, - &address->peer, - address); - notify_change (NULL, - &address->peer, - address); - } - GAS_plugin_solver_unlock (); + { + /* renormalize just this one address */ + normalize_address(NULL, + &address->peer, + address); + notify_change(NULL, + &address->peer, + address); + } + GAS_plugin_solver_unlock(); } @@ -280,9 +279,9 @@ GAS_normalization_update_property (struct ATS_Address *address) * Start the normalization component */ void -GAS_normalization_start () +GAS_normalization_start() { - init_range (&property_range); + init_range(&property_range); } @@ -290,7 +289,7 @@ GAS_normalization_start () * Stop the normalization component and free all items */ void -GAS_normalization_stop () +GAS_normalization_stop() { /* nothing to do */ } diff --git a/src/ats/gnunet-service-ats_normalization.h b/src/ats/gnunet-service-ats_normalization.h index 4435c4ae6..57bcf49f4 100644 --- a/src/ats/gnunet-service-ats_normalization.h +++ b/src/ats/gnunet-service-ats_normalization.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats_normalization.h @@ -40,21 +40,21 @@ * @param address the address to update */ void -GAS_normalization_update_property (struct ATS_Address *address); +GAS_normalization_update_property(struct ATS_Address *address); /** * Start the normalization component */ void -GAS_normalization_start (void); +GAS_normalization_start(void); /** * Stop the normalization component and free all items */ void -GAS_normalization_stop (void); +GAS_normalization_stop(void); #endif /* end of gnunet-service-ats_normalization.h */ diff --git a/src/ats/gnunet-service-ats_performance.c b/src/ats/gnunet-service-ats_performance.c index 94a22d378..16d0777de 100644 --- a/src/ats/gnunet-service-ats_performance.c +++ b/src/ats/gnunet-service-ats_performance.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats_performance.c * @brief ats service, interaction with 'performance' API @@ -63,64 +63,64 @@ static struct GNUNET_NotificationContext *nc_pic; * @param bandwidth_in assigned inbound bandwidth */ static void -notify_client (struct GNUNET_SERVICE_Client *client, - const struct GNUNET_PeerIdentity *peer, - const char *plugin_name, - const void *plugin_addr, - size_t plugin_addr_len, - int active, - const struct GNUNET_ATS_Properties *prop, - enum GNUNET_HELLO_AddressInfo local_address_info, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) +notify_client(struct GNUNET_SERVICE_Client *client, + const struct GNUNET_PeerIdentity *peer, + const char *plugin_name, + const void *plugin_addr, + size_t plugin_addr_len, + int active, + const struct GNUNET_ATS_Properties *prop, + enum GNUNET_HELLO_AddressInfo local_address_info, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) { struct PeerInformationMessage *msg; - size_t plugin_name_length = strlen (plugin_name) + 1; + size_t plugin_name_length = strlen(plugin_name) + 1; size_t msize = - sizeof (struct PeerInformationMessage) + + sizeof(struct PeerInformationMessage) + plugin_addr_len + plugin_name_length; char buf[msize] GNUNET_ALIGN; char *addrp; if (NULL != prop) - GNUNET_break (GNUNET_NT_UNSPECIFIED != prop->scope); - GNUNET_assert (msize < GNUNET_MAX_MESSAGE_SIZE); - msg = (struct PeerInformationMessage *) buf; - msg->header.size = htons (msize); - msg->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_PEER_INFORMATION); - msg->id = htonl (0); + GNUNET_break(GNUNET_NT_UNSPECIFIED != prop->scope); + GNUNET_assert(msize < GNUNET_MAX_MESSAGE_SIZE); + msg = (struct PeerInformationMessage *)buf; + msg->header.size = htons(msize); + msg->header.type = htons(GNUNET_MESSAGE_TYPE_ATS_PEER_INFORMATION); + msg->id = htonl(0); msg->peer = *peer; - msg->address_length = htons (plugin_addr_len); - msg->address_active = ntohl ((uint32_t) active); - msg->plugin_name_length = htons (plugin_name_length); + msg->address_length = htons(plugin_addr_len); + msg->address_active = ntohl((uint32_t)active); + msg->plugin_name_length = htons(plugin_name_length); msg->bandwidth_out = bandwidth_out; msg->bandwidth_in = bandwidth_in; if (NULL != prop) - GNUNET_ATS_properties_hton (&msg->properties, - prop); + GNUNET_ATS_properties_hton(&msg->properties, + prop); else - memset (&msg->properties, - 0, - sizeof (struct GNUNET_ATS_Properties)); - msg->address_local_info = htonl (local_address_info); - addrp = (char *) &msg[1]; - GNUNET_memcpy (addrp, plugin_addr, plugin_addr_len); - strcpy (&addrp[plugin_addr_len], plugin_name); + memset(&msg->properties, + 0, + sizeof(struct GNUNET_ATS_Properties)); + msg->address_local_info = htonl(local_address_info); + addrp = (char *)&msg[1]; + GNUNET_memcpy(addrp, plugin_addr, plugin_addr_len); + strcpy(&addrp[plugin_addr_len], plugin_name); if (NULL == client) - { - GNUNET_notification_context_broadcast (nc_pic, - &msg->header, - GNUNET_YES); - } + { + GNUNET_notification_context_broadcast(nc_pic, + &msg->header, + GNUNET_YES); + } else - { - struct GNUNET_MQ_Envelope *env; + { + struct GNUNET_MQ_Envelope *env; - env = GNUNET_MQ_msg_copy (&msg->header); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), - env); - } + env = GNUNET_MQ_msg_copy(&msg->header); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), + env); + } } @@ -142,32 +142,32 @@ notify_client (struct GNUNET_SERVICE_Client *client, * @param bandwidth_in assigned inbound bandwidth */ void -GAS_performance_notify_all_clients (const struct GNUNET_PeerIdentity *peer, - const char *plugin_name, - const void *plugin_addr, - size_t plugin_addr_len, - int active, - const struct GNUNET_ATS_Properties *prop, - enum GNUNET_HELLO_AddressInfo local_address_info, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) +GAS_performance_notify_all_clients(const struct GNUNET_PeerIdentity *peer, + const char *plugin_name, + const void *plugin_addr, + size_t plugin_addr_len, + int active, + const struct GNUNET_ATS_Properties *prop, + enum GNUNET_HELLO_AddressInfo local_address_info, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) { - GNUNET_break ( (NULL == prop) || - (GNUNET_NT_UNSPECIFIED != prop->scope) ); - notify_client (NULL, - peer, - plugin_name, - plugin_addr, - plugin_addr_len, - active, - prop, - local_address_info, - bandwidth_out, - bandwidth_in); - GNUNET_STATISTICS_update (GSA_stats, - "# performance updates given to clients", - 1, - GNUNET_NO); + GNUNET_break((NULL == prop) || + (GNUNET_NT_UNSPECIFIED != prop->scope)); + notify_client(NULL, + peer, + plugin_name, + plugin_addr, + plugin_addr_len, + active, + prop, + local_address_info, + bandwidth_out, + bandwidth_in); + GNUNET_STATISTICS_update(GSA_stats, + "# performance updates given to clients", + 1, + GNUNET_NO); } @@ -186,38 +186,38 @@ GAS_performance_notify_all_clients (const struct GNUNET_PeerIdentity *peer, * @param bandwidth_in current inbound bandwidth assigned to address */ static void -peerinfo_it (void *cls, - const struct GNUNET_PeerIdentity *id, - const char *plugin_name, - const void *plugin_addr, - size_t plugin_addr_len, - int active, - const struct GNUNET_ATS_Properties *prop, - enum GNUNET_HELLO_AddressInfo local_address_info, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) +peerinfo_it(void *cls, + const struct GNUNET_PeerIdentity *id, + const char *plugin_name, + const void *plugin_addr, + size_t plugin_addr_len, + int active, + const struct GNUNET_ATS_Properties *prop, + enum GNUNET_HELLO_AddressInfo local_address_info, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) { struct GNUNET_SERVICE_Client *client = cls; if (NULL == id) return; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Callback for peer `%s' plugin `%s' BW out %u, BW in %u \n", - GNUNET_i2s (id), - plugin_name, - (unsigned int) ntohl (bandwidth_out.value__), - (unsigned int) ntohl (bandwidth_in.value__)); - GNUNET_break (GNUNET_NT_UNSPECIFIED != prop->scope); - notify_client (client, - id, - plugin_name, - plugin_addr, - plugin_addr_len, - active, - prop, - local_address_info, - bandwidth_out, - bandwidth_in); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Callback for peer `%s' plugin `%s' BW out %u, BW in %u \n", + GNUNET_i2s(id), + plugin_name, + (unsigned int)ntohl(bandwidth_out.value__), + (unsigned int)ntohl(bandwidth_in.value__)); + GNUNET_break(GNUNET_NT_UNSPECIFIED != prop->scope); + notify_client(client, + id, + plugin_name, + plugin_addr, + plugin_addr_len, + active, + prop, + local_address_info, + bandwidth_out, + bandwidth_in); } @@ -228,25 +228,25 @@ peerinfo_it (void *cls, * @param flag flag specifying the type of the client */ void -GAS_performance_add_client (struct GNUNET_SERVICE_Client *client, - enum StartFlag flag) +GAS_performance_add_client(struct GNUNET_SERVICE_Client *client, + enum StartFlag flag) { struct GNUNET_MQ_Handle *mq; - mq = GNUNET_SERVICE_client_get_mq (client); + mq = GNUNET_SERVICE_client_get_mq(client); if (START_FLAG_PERFORMANCE_WITH_PIC == flag) - { - GNUNET_notification_context_add (nc_pic, - mq); - GAS_addresses_get_peer_info (NULL, - &peerinfo_it, - client); - } + { + GNUNET_notification_context_add(nc_pic, + mq); + GAS_addresses_get_peer_info(NULL, + &peerinfo_it, + client); + } else - { - GNUNET_notification_context_add (nc_no_pic, - mq); - } + { + GNUNET_notification_context_add(nc_no_pic, + mq); + } } @@ -256,10 +256,10 @@ GAS_performance_add_client (struct GNUNET_SERVICE_Client *client, * @param server handle to our server */ void -GAS_performance_init () +GAS_performance_init() { - nc_no_pic = GNUNET_notification_context_create (32); - nc_pic = GNUNET_notification_context_create (32); + nc_no_pic = GNUNET_notification_context_create(32); + nc_pic = GNUNET_notification_context_create(32); } @@ -267,11 +267,11 @@ GAS_performance_init () * Shutdown performance subsystem. */ void -GAS_performance_done () +GAS_performance_done() { - GNUNET_notification_context_destroy (nc_no_pic); + GNUNET_notification_context_destroy(nc_no_pic); nc_no_pic = NULL; - GNUNET_notification_context_destroy (nc_pic); + GNUNET_notification_context_destroy(nc_pic); nc_pic = NULL; } diff --git a/src/ats/gnunet-service-ats_performance.h b/src/ats/gnunet-service-ats_performance.h index e7ba3b554..3d5de0d85 100644 --- a/src/ats/gnunet-service-ats_performance.h +++ b/src/ats/gnunet-service-ats_performance.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats_performance.h @@ -50,15 +50,15 @@ * @param bandwidth_in assigned inbound bandwidth */ void -GAS_performance_notify_all_clients (const struct GNUNET_PeerIdentity *peer, - const char *plugin_name, - const void *plugin_addr, - size_t plugin_addr_len, - int active, - const struct GNUNET_ATS_Properties *prop, - enum GNUNET_HELLO_AddressInfo local_address_info, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in); +GAS_performance_notify_all_clients(const struct GNUNET_PeerIdentity *peer, + const char *plugin_name, + const void *plugin_addr, + size_t plugin_addr_len, + int active, + const struct GNUNET_ATS_Properties *prop, + enum GNUNET_HELLO_AddressInfo local_address_info, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in); /** @@ -68,8 +68,8 @@ GAS_performance_notify_all_clients (const struct GNUNET_PeerIdentity *peer, * @param flag flag specifying the type of the client */ void -GAS_performance_add_client (struct GNUNET_SERVICE_Client *client, - enum StartFlag flag); +GAS_performance_add_client(struct GNUNET_SERVICE_Client *client, + enum StartFlag flag); /** @@ -79,14 +79,14 @@ GAS_performance_add_client (struct GNUNET_SERVICE_Client *client, * @param addresses the address handle to use */ void -GAS_performance_init (void); +GAS_performance_init(void); /** * Shutdown performance subsystem. */ void -GAS_performance_done (void); +GAS_performance_done(void); #endif diff --git a/src/ats/gnunet-service-ats_plugins.c b/src/ats/gnunet-service-ats_plugins.c index 0b0e5ec4b..274f89e7a 100644 --- a/src/ats/gnunet-service-ats_plugins.c +++ b/src/ats/gnunet-service-ats_plugins.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2011-2014 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2011-2014 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -59,14 +59,14 @@ static char *plugin; * @param pref_rel the new relative preference value */ void -GAS_plugin_notify_preference_changed (const struct GNUNET_PeerIdentity *peer, - enum GNUNET_ATS_PreferenceKind kind, - double pref_rel) +GAS_plugin_notify_preference_changed(const struct GNUNET_PeerIdentity *peer, + enum GNUNET_ATS_PreferenceKind kind, + double pref_rel) { - sf->s_pref (sf->cls, - peer, - kind, - pref_rel); + sf->s_pref(sf->cls, + peer, + kind, + pref_rel); } @@ -76,10 +76,10 @@ GAS_plugin_notify_preference_changed (const struct GNUNET_PeerIdentity *peer, * @param address the peer for which a property changed */ void -GAS_plugin_notify_property_changed (struct ATS_Address *address) +GAS_plugin_notify_property_changed(struct ATS_Address *address) { - sf->s_address_update_property (sf->cls, - address); + sf->s_address_update_property(sf->cls, + address); } @@ -92,100 +92,116 @@ GAS_plugin_notify_property_changed (struct ATS_Address *address) * @param add additional information */ static void -solver_info_cb (void *cls, - enum GAS_Solver_Operation op, - enum GAS_Solver_Status status, - enum GAS_Solver_Additional_Information add) +solver_info_cb(void *cls, + enum GAS_Solver_Operation op, + enum GAS_Solver_Status status, + enum GAS_Solver_Additional_Information add) { const char *add_info; - switch (add) { + switch (add) + { case GAS_INFO_NONE: add_info = "GAS_INFO_NONE"; break; + case GAS_INFO_FULL: add_info = "GAS_INFO_MLP_FULL"; break; + case GAS_INFO_UPDATED: add_info = "GAS_INFO_MLP_UPDATED"; break; + case GAS_INFO_PROP_ALL: add_info = "GAS_INFO_PROP_ALL"; break; + case GAS_INFO_PROP_SINGLE: add_info = "GAS_INFO_PROP_SINGLE"; break; + default: add_info = "INVALID"; break; - } + } switch (op) - { - case GAS_OP_SOLVE_START: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s' `%s'\n", - "GAS_OP_SOLVE_START", - (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL", - add_info); - return; - case GAS_OP_SOLVE_STOP: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", - "GAS_OP_SOLVE_STOP", - (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); - return; - case GAS_OP_SOLVE_SETUP_START: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", - "GAS_OP_SOLVE_SETUP_START", - (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); - return; - case GAS_OP_SOLVE_SETUP_STOP: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", - "GAS_OP_SOLVE_SETUP_STOP", - (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); - return; - case GAS_OP_SOLVE_MLP_LP_START: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", - "GAS_OP_SOLVE_LP_START", - (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); - return; - case GAS_OP_SOLVE_MLP_LP_STOP: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", - "GAS_OP_SOLVE_LP_STOP", - (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); - return; - case GAS_OP_SOLVE_MLP_MLP_START: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", - "GAS_OP_SOLVE_MLP_START", - (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); - return; - case GAS_OP_SOLVE_MLP_MLP_STOP: - GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", - "GAS_OP_SOLVE_MLP_STOP", - (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); - return; - case GAS_OP_SOLVE_UPDATE_NOTIFICATION_START: - GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", - "GAS_OP_SOLVE_UPDATE_NOTIFICATION_START", - (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); - return; - case GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP: - GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Solver notifies `%s' with result `%s'\n", - "GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP", - (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); - return; - default: - GNUNET_break (0); - break; - } + { + case GAS_OP_SOLVE_START: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Solver notifies `%s' with result `%s' `%s'\n", + "GAS_OP_SOLVE_START", + (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL", + add_info); + return; + + case GAS_OP_SOLVE_STOP: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Solver notifies `%s' with result `%s'\n", + "GAS_OP_SOLVE_STOP", + (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); + return; + + case GAS_OP_SOLVE_SETUP_START: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Solver notifies `%s' with result `%s'\n", + "GAS_OP_SOLVE_SETUP_START", + (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); + return; + + case GAS_OP_SOLVE_SETUP_STOP: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Solver notifies `%s' with result `%s'\n", + "GAS_OP_SOLVE_SETUP_STOP", + (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); + return; + + case GAS_OP_SOLVE_MLP_LP_START: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Solver notifies `%s' with result `%s'\n", + "GAS_OP_SOLVE_LP_START", + (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); + return; + + case GAS_OP_SOLVE_MLP_LP_STOP: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Solver notifies `%s' with result `%s'\n", + "GAS_OP_SOLVE_LP_STOP", + (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); + return; + + case GAS_OP_SOLVE_MLP_MLP_START: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Solver notifies `%s' with result `%s'\n", + "GAS_OP_SOLVE_MLP_START", + (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); + return; + + case GAS_OP_SOLVE_MLP_MLP_STOP: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Solver notifies `%s' with result `%s'\n", + "GAS_OP_SOLVE_MLP_STOP", + (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); + return; + + case GAS_OP_SOLVE_UPDATE_NOTIFICATION_START: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Solver notifies `%s' with result `%s'\n", + "GAS_OP_SOLVE_UPDATE_NOTIFICATION_START", + (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); + return; + + case GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Solver notifies `%s' with result `%s'\n", + "GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP", + (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL"); + return; + + default: + GNUNET_break(0); + break; + } } @@ -196,69 +212,69 @@ solver_info_cb (void *cls, * @param address the address with changes */ static void -bandwidth_changed_cb (void *cls, - struct ATS_Address *address) +bandwidth_changed_cb(void *cls, + struct ATS_Address *address) { long long diff_out; long long diff_in; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Bandwidth assignment changed for peer %s to %u/%u\n", - GNUNET_i2s (&address->peer), - (unsigned int) address->assigned_bw_in, - (unsigned int) address->assigned_bw_out); - GAS_reservations_set_bandwidth (&address->peer, - GNUNET_BANDWIDTH_value_init (address->assigned_bw_in)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Bandwidth assignment changed for peer %s to %u/%u\n", + GNUNET_i2s(&address->peer), + (unsigned int)address->assigned_bw_in, + (unsigned int)address->assigned_bw_out); + GAS_reservations_set_bandwidth(&address->peer, + GNUNET_BANDWIDTH_value_init(address->assigned_bw_in)); /* Notify performance clients about changes to address */ - GAS_performance_notify_all_clients (&address->peer, - address->plugin, - address->addr, - address->addr_len, - address->active, - &address->properties, - address->local_address_info, - GNUNET_BANDWIDTH_value_init (address->assigned_bw_out), - GNUNET_BANDWIDTH_value_init (address->assigned_bw_in)); - - if ( (0 == address->assigned_bw_in) && - (0 == address->assigned_bw_out) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Telling transport to disconnect peer `%s'\n", - GNUNET_i2s (&address->peer)); - - /* Notify scheduling clients about suggestion */ - GAS_scheduling_transmit_address_suggestion (&address->peer, - address->session_id, - GNUNET_BANDWIDTH_ZERO, - GNUNET_BANDWIDTH_ZERO); - return; - } + GAS_performance_notify_all_clients(&address->peer, + address->plugin, + address->addr, + address->addr_len, + address->active, + &address->properties, + address->local_address_info, + GNUNET_BANDWIDTH_value_init(address->assigned_bw_out), + GNUNET_BANDWIDTH_value_init(address->assigned_bw_in)); + + if ((0 == address->assigned_bw_in) && + (0 == address->assigned_bw_out)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Telling transport to disconnect peer `%s'\n", + GNUNET_i2s(&address->peer)); + + /* Notify scheduling clients about suggestion */ + GAS_scheduling_transmit_address_suggestion(&address->peer, + address->session_id, + GNUNET_BANDWIDTH_ZERO, + GNUNET_BANDWIDTH_ZERO); + return; + } /* Do bandwidth stability check */ - diff_out = llabs ((long long) address->assigned_bw_out - - (long long) address->last_notified_bw_out); - diff_in = llabs ((long long) address->assigned_bw_in - - (long long) address->last_notified_bw_in); - if ( (diff_out < htonl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__)) && - (diff_in < htonl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__)) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Bandwidth change too small, not notifying client\n"); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending bandwidth update for peer `%s': %u/%u\n", - GNUNET_i2s (&address->peer), - address->assigned_bw_out, - address->assigned_bw_out); + diff_out = llabs((long long)address->assigned_bw_out - + (long long)address->last_notified_bw_out); + diff_in = llabs((long long)address->assigned_bw_in - + (long long)address->last_notified_bw_in); + if ((diff_out < htonl(GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__)) && + (diff_in < htonl(GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__))) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Bandwidth change too small, not notifying client\n"); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending bandwidth update for peer `%s': %u/%u\n", + GNUNET_i2s(&address->peer), + address->assigned_bw_out, + address->assigned_bw_out); /* *Notify scheduling clients about suggestion */ - GAS_scheduling_transmit_address_suggestion (&address->peer, - address->session_id, - GNUNET_BANDWIDTH_value_init (address->assigned_bw_out), - GNUNET_BANDWIDTH_value_init (address->assigned_bw_in)); + GAS_scheduling_transmit_address_suggestion(&address->peer, + address->session_id, + GNUNET_BANDWIDTH_value_init(address->assigned_bw_out), + GNUNET_BANDWIDTH_value_init(address->assigned_bw_in)); address->last_notified_bw_out = address->assigned_bw_out; address->last_notified_bw_in = address->assigned_bw_in; @@ -274,48 +290,48 @@ bandwidth_changed_cb (void *cls, * @return numeric quota value to use */ static unsigned long long -parse_quota (const char *quota_str, - const char *direction, - enum GNUNET_NetworkType network) +parse_quota(const char *quota_str, + const char *direction, + enum GNUNET_NetworkType network) { int res; unsigned long long ret; res = GNUNET_NO; - if (0 == strcmp (quota_str, GNUNET_ATS_MaxBandwidthString)) - { - ret = GNUNET_ATS_MaxBandwidth; - res = GNUNET_YES; - } + if (0 == strcmp(quota_str, GNUNET_ATS_MaxBandwidthString)) + { + ret = GNUNET_ATS_MaxBandwidth; + res = GNUNET_YES; + } if ((GNUNET_NO == res) && (GNUNET_OK == - GNUNET_STRINGS_fancy_size_to_bytes (quota_str, - &ret))) + GNUNET_STRINGS_fancy_size_to_bytes(quota_str, + &ret))) res = GNUNET_YES; if ((GNUNET_NO == res) && (1 == - sscanf (quota_str, - "%llu", - &ret))) + sscanf(quota_str, + "%llu", + &ret))) res = GNUNET_YES; if (GNUNET_NO == res) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Could not load %s quota for network `%s': `%s', assigning default bandwidth %llu\n"), - direction, - GNUNET_NT_to_string (network), - quota_str, - (unsigned long long) GNUNET_ATS_DefaultBandwidth); - ret = GNUNET_ATS_DefaultBandwidth; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Could not load %s quota for network `%s': `%s', assigning default bandwidth %llu\n"), + direction, + GNUNET_NT_to_string(network), + quota_str, + (unsigned long long)GNUNET_ATS_DefaultBandwidth); + ret = GNUNET_ATS_DefaultBandwidth; + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("%s quota configured for network `%s' is %llu\n"), - direction, - GNUNET_NT_to_string (network), - ret); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("%s quota configured for network `%s' is %llu\n"), + direction, + GNUNET_NT_to_string(network), + ret); + } return ret; } @@ -330,39 +346,39 @@ parse_quota (const char *quota_str, * @return quota to apply */ static unsigned long long -load_quota (const struct GNUNET_CONFIGURATION_Handle *cfg, - enum GNUNET_NetworkType type, - const char *direction) +load_quota(const struct GNUNET_CONFIGURATION_Handle *cfg, + enum GNUNET_NetworkType type, + const char *direction) { char *entry; char *quota_str; unsigned long long ret; - GNUNET_asprintf (&entry, - "%s_QUOTA_%s", - GNUNET_NT_to_string (type), - direction); + GNUNET_asprintf(&entry, + "%s_QUOTA_%s", + GNUNET_NT_to_string(type), + direction); if (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (cfg, - "ats", - entry, - "a_str)) - { - ret = parse_quota (quota_str, - direction, - type); - GNUNET_free (quota_str); - } + GNUNET_CONFIGURATION_get_value_string(cfg, + "ats", + entry, + "a_str)) + { + ret = parse_quota(quota_str, + direction, + type); + GNUNET_free(quota_str); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No %s-quota configured for network `%s', assigning default bandwidth %llu\n"), - direction, - GNUNET_NT_to_string (type), - (unsigned long long) GNUNET_ATS_DefaultBandwidth); - ret = GNUNET_ATS_DefaultBandwidth; - } - GNUNET_free (entry); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No %s-quota configured for network `%s', assigning default bandwidth %llu\n"), + direction, + GNUNET_NT_to_string(type), + (unsigned long long)GNUNET_ATS_DefaultBandwidth); + ret = GNUNET_ATS_DefaultBandwidth; + } + GNUNET_free(entry); return ret; } @@ -377,27 +393,27 @@ load_quota (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return number of networks loaded */ static unsigned int -load_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg, - unsigned long long *out_dest, - unsigned long long *in_dest, - int dest_length) +load_quotas(const struct GNUNET_CONFIGURATION_Handle *cfg, + unsigned long long *out_dest, + unsigned long long *in_dest, + int dest_length) { unsigned int c; for (c = 0; (c < GNUNET_NT_COUNT) && (c < dest_length); c++) - { - in_dest[c] = load_quota (cfg, - c, - "out"); - out_dest[c] = load_quota (cfg, + { + in_dest[c] = load_quota(cfg, c, - "in"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Loaded quota for network `%s' (in/out): %llu %llu\n", - GNUNET_NT_to_string (c), - in_dest[c], - out_dest[c]); - } + "out"); + out_dest[c] = load_quota(cfg, + c, + "in"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Loaded quota for network `%s' (in/out): %llu %llu\n", + GNUNET_NT_to_string(c), + in_dest[c], + out_dest[c]); + } return c; } @@ -410,21 +426,21 @@ load_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg, * solver plugin) */ int -GAS_plugin_init (const struct GNUNET_CONFIGURATION_Handle *cfg) +GAS_plugin_init(const struct GNUNET_CONFIGURATION_Handle *cfg) { char *mode_str; /* Figure out configured solution method */ if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, - "ats", - "MODE", - &mode_str)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "No resource assignment method configured, using proportional approach\n"); - mode_str = GNUNET_strdup ("proportional"); - } + GNUNET_CONFIGURATION_get_value_string(cfg, + "ats", + "MODE", + &mode_str)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "No resource assignment method configured, using proportional approach\n"); + mode_str = GNUNET_strdup("proportional"); + } env.cls = NULL; env.info_cb = &solver_info_cb; env.bandwidth_changed_cb = &bandwidth_changed_cb; @@ -434,24 +450,24 @@ GAS_plugin_init (const struct GNUNET_CONFIGURATION_Handle *cfg) env.stats = GSA_stats; env.addresses = GSA_addresses; env.network_count = GNUNET_NT_COUNT; - load_quotas (cfg, - env.out_quota, - env.in_quota, - GNUNET_NT_COUNT); - GNUNET_asprintf (&plugin, - "libgnunet_plugin_ats_%s", - mode_str); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Initializing solver `%s'\n", - mode_str); - GNUNET_free (mode_str); - if (NULL == (sf = GNUNET_PLUGIN_load (plugin, &env))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to initialize solver `%s'!\n"), - plugin); - return GNUNET_SYSERR; - } + load_quotas(cfg, + env.out_quota, + env.in_quota, + GNUNET_NT_COUNT); + GNUNET_asprintf(&plugin, + "libgnunet_plugin_ats_%s", + mode_str); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Initializing solver `%s'\n", + mode_str); + GNUNET_free(mode_str); + if (NULL == (sf = GNUNET_PLUGIN_load(plugin, &env))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to initialize solver `%s'!\n"), + plugin); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -460,12 +476,12 @@ GAS_plugin_init (const struct GNUNET_CONFIGURATION_Handle *cfg) * Shutdown address subsystem. */ void -GAS_plugin_done () +GAS_plugin_done() { - GNUNET_PLUGIN_unload (plugin, - sf); + GNUNET_PLUGIN_unload(plugin, + sf); sf = NULL; - GNUNET_free (plugin); + GNUNET_free(plugin); plugin = NULL; } @@ -477,11 +493,11 @@ GAS_plugin_done () * @param new_address the new address */ void -GAS_plugin_new_address (struct ATS_Address *new_address) +GAS_plugin_new_address(struct ATS_Address *new_address) { - sf->s_add (sf->cls, - new_address, - new_address->properties.scope); /* FIXME: remove 3rd arg here! */ + sf->s_add(sf->cls, + new_address, + new_address->properties.scope); /* FIXME: remove 3rd arg here! */ } @@ -492,10 +508,10 @@ GAS_plugin_new_address (struct ATS_Address *new_address) * @param address address that was deleted */ void -GAS_plugin_delete_address (struct ATS_Address *address) +GAS_plugin_delete_address(struct ATS_Address *address) { - sf->s_del (sf->cls, - address); + sf->s_del(sf->cls, + address); } @@ -510,18 +526,18 @@ GAS_plugin_delete_address (struct ATS_Address *address) * @param score_abs degree of the appreciation */ void -GAS_plugin_notify_feedback (struct GNUNET_SERVICE_Client *application, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_TIME_Relative scope, - enum GNUNET_ATS_PreferenceKind kind, - float score_abs) +GAS_plugin_notify_feedback(struct GNUNET_SERVICE_Client *application, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_TIME_Relative scope, + enum GNUNET_ATS_PreferenceKind kind, + float score_abs) { - sf->s_feedback (sf->cls, - application, - peer, - scope, - kind, - score_abs); + sf->s_feedback(sf->cls, + application, + peer, + scope, + kind, + score_abs); } @@ -530,9 +546,9 @@ GAS_plugin_notify_feedback (struct GNUNET_SERVICE_Client *application, * happening in bulk right now. */ void -GAS_plugin_solver_lock () +GAS_plugin_solver_lock() { - sf->s_bulk_start (sf->cls); + sf->s_bulk_start(sf->cls); } @@ -540,9 +556,9 @@ GAS_plugin_solver_lock () * Resume instant solving, we are done with the bulk state updates. */ void -GAS_plugin_solver_unlock () +GAS_plugin_solver_unlock() { - sf->s_bulk_stop (sf->cls); + sf->s_bulk_stop(sf->cls); } @@ -553,10 +569,10 @@ GAS_plugin_solver_unlock () * @param pid identity of peer we now care about */ void -GAS_plugin_request_connect_start (const struct GNUNET_PeerIdentity *pid) +GAS_plugin_request_connect_start(const struct GNUNET_PeerIdentity *pid) { - sf->s_get (sf->cls, - pid); + sf->s_get(sf->cls, + pid); } @@ -567,10 +583,10 @@ GAS_plugin_request_connect_start (const struct GNUNET_PeerIdentity *pid) * @param pid identity of peer we care now less about */ void -GAS_plugin_request_connect_stop (const struct GNUNET_PeerIdentity *pid) +GAS_plugin_request_connect_stop(const struct GNUNET_PeerIdentity *pid) { - sf->s_get_stop (sf->cls, - pid); + sf->s_get_stop(sf->cls, + pid); } diff --git a/src/ats/gnunet-service-ats_plugins.h b/src/ats/gnunet-service-ats_plugins.h index 70ae1d597..e2256f691 100644 --- a/src/ats/gnunet-service-ats_plugins.h +++ b/src/ats/gnunet-service-ats_plugins.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2011-2014 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2011-2014 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -41,14 +41,14 @@ * solver plugin) */ int -GAS_plugin_init (const struct GNUNET_CONFIGURATION_Handle *cfg); +GAS_plugin_init(const struct GNUNET_CONFIGURATION_Handle *cfg); /** * Shutdown address subsystem. */ void -GAS_plugin_done (void); +GAS_plugin_done(void); /** @@ -59,9 +59,9 @@ GAS_plugin_done (void); * @param pref_rel the new relative preference value */ void -GAS_plugin_notify_preference_changed (const struct GNUNET_PeerIdentity *peer, - enum GNUNET_ATS_PreferenceKind kind, - double pref_rel); +GAS_plugin_notify_preference_changed(const struct GNUNET_PeerIdentity *peer, + enum GNUNET_ATS_PreferenceKind kind, + double pref_rel); /** @@ -70,7 +70,7 @@ GAS_plugin_notify_preference_changed (const struct GNUNET_PeerIdentity *peer, * @param address the peer */ void -GAS_plugin_notify_property_changed (struct ATS_Address *address); +GAS_plugin_notify_property_changed(struct ATS_Address *address); /** @@ -81,7 +81,7 @@ GAS_plugin_notify_property_changed (struct ATS_Address *address); * @param addr_net network scope the address is in */ void -GAS_plugin_new_address (struct ATS_Address *new_address); +GAS_plugin_new_address(struct ATS_Address *new_address); /** @@ -91,7 +91,7 @@ GAS_plugin_new_address (struct ATS_Address *new_address); * @param address address that was deleted */ void -GAS_plugin_delete_address (struct ATS_Address *address); +GAS_plugin_delete_address(struct ATS_Address *address); /** @@ -105,11 +105,11 @@ GAS_plugin_delete_address (struct ATS_Address *address); * @param score_abs degree of the appreciation */ void -GAS_plugin_notify_feedback (struct GNUNET_SERVICE_Client *application, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_TIME_Relative scope, - enum GNUNET_ATS_PreferenceKind kind, - float score_abs); +GAS_plugin_notify_feedback(struct GNUNET_SERVICE_Client *application, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_TIME_Relative scope, + enum GNUNET_ATS_PreferenceKind kind, + float score_abs); /** @@ -117,14 +117,14 @@ GAS_plugin_notify_feedback (struct GNUNET_SERVICE_Client *application, * happening in bulk right now. */ void -GAS_plugin_solver_lock (void); +GAS_plugin_solver_lock(void); /** * Resume instant solving, we are done with the bulk state updates. */ void -GAS_plugin_solver_unlock (void); +GAS_plugin_solver_unlock(void); /** @@ -134,7 +134,7 @@ GAS_plugin_solver_unlock (void); * @param pid identity of peer we now care about */ void -GAS_plugin_request_connect_start (const struct GNUNET_PeerIdentity *pid); +GAS_plugin_request_connect_start(const struct GNUNET_PeerIdentity *pid); /** @@ -144,7 +144,7 @@ GAS_plugin_request_connect_start (const struct GNUNET_PeerIdentity *pid); * @param pid identity of peer we care now less about */ void -GAS_plugin_request_connect_stop (const struct GNUNET_PeerIdentity *pid); +GAS_plugin_request_connect_stop(const struct GNUNET_PeerIdentity *pid); #endif diff --git a/src/ats/gnunet-service-ats_preferences.c b/src/ats/gnunet-service-ats_preferences.c index 26929ea7c..0a12faaae 100644 --- a/src/ats/gnunet-service-ats_preferences.c +++ b/src/ats/gnunet-service-ats_preferences.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats_preferences.c * @brief manage preferences expressed by clients @@ -32,12 +32,12 @@ #include "gnunet-service-ats_reservations.h" #include "ats.h" -#define LOG(kind,...) GNUNET_log_from (kind, "ats-preferences",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "ats-preferences", __VA_ARGS__) /** * How frequently do we age preference values? */ -#define PREF_AGING_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) +#define PREF_AGING_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) /** * By which factor do we age preferences expressed during @@ -56,8 +56,7 @@ /** * Relative preferences for a peer. */ -struct PeerRelative -{ +struct PeerRelative { /** * Array of relative preference values, to be indexed by * an `enum GNUNET_ATS_PreferenceKind`. @@ -83,8 +82,7 @@ static struct PeerRelative defvalues; /** * Preference information per peer and client. */ -struct PreferencePeer -{ +struct PreferencePeer { /** * Next in DLL of preference entries for the same client. */ @@ -107,7 +105,6 @@ struct PreferencePeer * client scored other peers. */ double f_rel[GNUNET_ATS_PREFERENCE_END]; - }; @@ -116,9 +113,7 @@ struct PreferencePeer * for peers. This is the information we keep track of for each * such client. */ -struct PreferenceClient -{ - +struct PreferenceClient { /** * Next in client list */ @@ -145,7 +140,6 @@ struct PreferenceClient * peers as expressed by this client. */ double f_abs_sum[GNUNET_ATS_PREFERENCE_END]; - }; @@ -175,8 +169,7 @@ static struct GNUNET_SCHEDULER_Task *aging_task; /** * Closure for #sum_relative_preferences(). */ -struct SumContext -{ +struct SumContext { /** * Where to accumulate the result. */ @@ -200,9 +193,9 @@ struct SumContext * @return #GNUNET_OK */ static int -sum_relative_preferences (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *value) +sum_relative_preferences(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *value) { struct SumContext *sum_ctx = cls; struct PreferencePeer *p_cur = value; @@ -221,8 +214,8 @@ sum_relative_preferences (void *cls, * @return the new relative preference */ static void -update_relative_values_for_peer (const struct GNUNET_PeerIdentity *id, - enum GNUNET_ATS_PreferenceKind kind) +update_relative_values_for_peer(const struct GNUNET_PeerIdentity *id, + enum GNUNET_ATS_PreferenceKind kind) { struct PreferenceClient *c_cur; struct SumContext sum_ctx; @@ -231,25 +224,25 @@ update_relative_values_for_peer (const struct GNUNET_PeerIdentity *id, sum_ctx.f_rel_total = 0.0; sum_ctx.kind = kind; for (c_cur = pc_head; NULL != c_cur; c_cur = c_cur->next) - GNUNET_CONTAINER_multipeermap_get_multiple (c_cur->peer2pref, - id, - &sum_relative_preferences, - &sum_ctx); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Total relative preference for peer `%s' for `%s' is %.3f\n", - GNUNET_i2s (id), - GNUNET_ATS_print_preference_type (kind), - sum_ctx.f_rel_total); - rp = GNUNET_CONTAINER_multipeermap_get (preference_peers, - id); - GNUNET_assert (NULL != rp); + GNUNET_CONTAINER_multipeermap_get_multiple(c_cur->peer2pref, + id, + &sum_relative_preferences, + &sum_ctx); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Total relative preference for peer `%s' for `%s' is %.3f\n", + GNUNET_i2s(id), + GNUNET_ATS_print_preference_type(kind), + sum_ctx.f_rel_total); + rp = GNUNET_CONTAINER_multipeermap_get(preference_peers, + id); + GNUNET_assert(NULL != rp); if (rp->f_rel[kind] != sum_ctx.f_rel_total) - { - rp->f_rel[kind] = sum_ctx.f_rel_total; - GAS_plugin_notify_preference_changed (id, - kind, - rp->f_rel[kind]); - } + { + rp->f_rel[kind] = sum_ctx.f_rel_total; + GAS_plugin_notify_preference_changed(id, + kind, + rp->f_rel[kind]); + } } @@ -262,17 +255,17 @@ update_relative_values_for_peer (const struct GNUNET_PeerIdentity *id, * @return #GNUNET_OK to continue */ static int -free_peer (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +free_peer(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct PeerRelative *rp = value; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (preference_peers, - key, - value)); - GNUNET_free (rp); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(preference_peers, + key, + value)); + GNUNET_free(rp); return GNUNET_OK; } @@ -286,30 +279,30 @@ free_peer (void *cls, * @return #GNUNET_OK (continue to iterate) */ static int -free_preference (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +free_preference(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct PreferenceClient *pc = cls; struct PreferencePeer *p = value; struct PeerRelative *pr; - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_remove (pc->peer2pref, - key, - p)); - GNUNET_free (p); - pr = GNUNET_CONTAINER_multipeermap_get (preference_peers, - key); - GNUNET_assert (NULL != pr); - GNUNET_assert (pr->num_clients > 0); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_remove(pc->peer2pref, + key, + p)); + GNUNET_free(p); + pr = GNUNET_CONTAINER_multipeermap_get(preference_peers, + key); + GNUNET_assert(NULL != pr); + GNUNET_assert(pr->num_clients > 0); pr->num_clients--; if (0 == pr->num_clients) - { - free_peer (NULL, - key, - pr); - } + { + free_peer(NULL, + key, + pr); + } return GNUNET_OK; } @@ -317,8 +310,7 @@ free_preference (void *cls, /** * Closure for #age_values(). */ -struct AgeContext -{ +struct AgeContext { /** * Counter of values remaining to update, incremented for each value * changed (to a new non-zero value). @@ -329,7 +321,6 @@ struct AgeContext * Client we are currently aging values for. */ struct PreferenceClient *cur_client; - }; @@ -342,9 +333,9 @@ struct AgeContext * @return #GNUNET_OK (continue to iterate) */ static int -age_values (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *value) +age_values(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *value) { struct AgeContext *ac = cls; struct PreferencePeer *p = value; @@ -353,32 +344,32 @@ age_values (void *cls, dead = GNUNET_YES; for (i = 0; i < GNUNET_ATS_PREFERENCE_END; i++) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Aging preference for peer `%s'\n", - GNUNET_i2s (peer)); - if (p->f_abs[i] > DEFAULT_ABS_PREFERENCE) - p->f_abs[i] *= PREF_AGING_FACTOR; - if (p->f_abs[i] <= DEFAULT_ABS_PREFERENCE + PREF_EPSILON) { - p->f_abs[i] = DEFAULT_ABS_PREFERENCE; - p->f_rel[i] = DEFAULT_REL_PREFERENCE; - update_relative_values_for_peer (peer, - i); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Aging preference for peer `%s'\n", + GNUNET_i2s(peer)); + if (p->f_abs[i] > DEFAULT_ABS_PREFERENCE) + p->f_abs[i] *= PREF_AGING_FACTOR; + if (p->f_abs[i] <= DEFAULT_ABS_PREFERENCE + PREF_EPSILON) + { + p->f_abs[i] = DEFAULT_ABS_PREFERENCE; + p->f_rel[i] = DEFAULT_REL_PREFERENCE; + update_relative_values_for_peer(peer, + i); + } + else + { + ac->values_to_update++; + dead = GNUNET_NO; + } } - else + if (GNUNET_YES == dead) { - ac->values_to_update++; - dead = GNUNET_NO; + /* all preferences are zero, remove this entry */ + free_preference(ac->cur_client, + peer, + p); } - } - if (GNUNET_YES == dead) - { - /* all preferences are zero, remove this entry */ - free_preference (ac->cur_client, - peer, - p); - } return GNUNET_OK; } @@ -389,41 +380,40 @@ age_values (void *cls, * @param cls unused */ static void -preference_aging (void *cls) +preference_aging(void *cls) { struct AgeContext ac; aging_task = NULL; - GAS_plugin_solver_lock (); + GAS_plugin_solver_lock(); ac.values_to_update = 0; for (ac.cur_client = pc_head; NULL != ac.cur_client; ac.cur_client = ac.cur_client->next) - GNUNET_CONTAINER_multipeermap_iterate (ac.cur_client->peer2pref, - &age_values, - &ac); - GAS_plugin_solver_unlock (); + GNUNET_CONTAINER_multipeermap_iterate(ac.cur_client->peer2pref, + &age_values, + &ac); + GAS_plugin_solver_unlock(); if (ac.values_to_update > 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Rescheduling aging task due to %u elements remaining to age\n", - ac.values_to_update); - if (NULL == aging_task) - aging_task = GNUNET_SCHEDULER_add_delayed (PREF_AGING_INTERVAL, - &preference_aging, - NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Rescheduling aging task due to %u elements remaining to age\n", + ac.values_to_update); + if (NULL == aging_task) + aging_task = GNUNET_SCHEDULER_add_delayed(PREF_AGING_INTERVAL, + &preference_aging, + NULL); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "No values to age left, not rescheduling aging task\n"); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "No values to age left, not rescheduling aging task\n"); + } } /** * Closure for #update_rel_sum() and #update_abs_sum(). */ -struct UpdateContext -{ +struct UpdateContext { /** * Preference client with the sum of all absolute scores. */ @@ -433,7 +423,6 @@ struct UpdateContext * Which kind are we updating? */ enum GNUNET_ATS_PreferenceKind kind; - }; @@ -447,9 +436,9 @@ struct UpdateContext * @return #GNUNET_OK (continue to iterate) */ static int -update_abs_sum (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *value) +update_abs_sum(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *value) { struct UpdateContext *uc = cls; struct PreferencePeer *p_cur = value; @@ -469,19 +458,19 @@ update_abs_sum (void *cls, * @return #GNUNET_OK (continue to iterate) */ static int -update_rel_sum (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *value) +update_rel_sum(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *value) { struct UpdateContext *uc = cls; struct PreferencePeer *p_cur = value; p_cur->f_rel[uc->kind] = p_cur->f_abs[uc->kind] / uc->pc->f_abs_sum[uc->kind]; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Client has relative preference for %s for peer `%s' of %.3f\n", - GNUNET_ATS_print_preference_type (uc->kind), - GNUNET_i2s (peer), - p_cur->f_rel[uc->kind]); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Client has relative preference for %s for peer `%s' of %.3f\n", + GNUNET_ATS_print_preference_type(uc->kind), + GNUNET_i2s(peer), + p_cur->f_rel[uc->kind]); return GNUNET_OK; } @@ -494,8 +483,8 @@ update_rel_sum (void *cls, * @return the result */ static void -recalculate_relative_preferences (struct PreferenceClient *c, - enum GNUNET_ATS_PreferenceKind kind) +recalculate_relative_preferences(struct PreferenceClient *c, + enum GNUNET_ATS_PreferenceKind kind) { struct UpdateContext uc; @@ -505,18 +494,18 @@ recalculate_relative_preferences (struct PreferenceClient *c, c->f_abs_sum[kind] = 0.0; /* For all peers: calculate sum of absolute preferences */ - GNUNET_CONTAINER_multipeermap_iterate (c->peer2pref, - &update_abs_sum, - &uc); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Client has sum of total preferences for %s of %.3f\n", - GNUNET_ATS_print_preference_type (kind), - c->f_abs_sum[kind]); + GNUNET_CONTAINER_multipeermap_iterate(c->peer2pref, + &update_abs_sum, + &uc); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Client has sum of total preferences for %s of %.3f\n", + GNUNET_ATS_print_preference_type(kind), + c->f_abs_sum[kind]); /* For all peers: calculate relative preference */ - GNUNET_CONTAINER_multipeermap_iterate (c->peer2pref, - &update_rel_sum, - &uc); + GNUNET_CONTAINER_multipeermap_iterate(c->peer2pref, + &update_rel_sum, + &uc); } @@ -531,14 +520,14 @@ recalculate_relative_preferences (struct PreferenceClient *c, * @param value a `struct PeerRelative`, unused */ static int -update_iterator (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +update_iterator(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { enum GNUNET_ATS_PreferenceKind *kind = cls; - update_relative_values_for_peer (key, - *kind); + update_relative_values_for_peer(key, + *kind); return GNUNET_OK; } @@ -553,10 +542,10 @@ update_iterator (void *cls, * @param score_abs the normalized score */ static void -update_preference (struct GNUNET_SERVICE_Client *client, - const struct GNUNET_PeerIdentity *peer, - enum GNUNET_ATS_PreferenceKind kind, - float score_abs) +update_preference(struct GNUNET_SERVICE_Client *client, + const struct GNUNET_PeerIdentity *peer, + enum GNUNET_ATS_PreferenceKind kind, + float score_abs) { struct PreferenceClient *c_cur; struct PreferencePeer *p_cur; @@ -564,15 +553,15 @@ update_preference (struct GNUNET_SERVICE_Client *client, unsigned int i; if (kind >= GNUNET_ATS_PREFERENCE_END) - { - GNUNET_break(0); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Client changes preference for peer `%s' for `%s' to %.2f\n", - GNUNET_i2s (peer), - GNUNET_ATS_print_preference_type (kind), - score_abs); + { + GNUNET_break(0); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Client changes preference for peer `%s' for `%s' to %.2f\n", + GNUNET_i2s(peer), + GNUNET_ATS_print_preference_type(kind), + score_abs); /* Find preference client */ for (c_cur = pc_head; NULL != c_cur; c_cur = c_cur->next) @@ -580,66 +569,66 @@ update_preference (struct GNUNET_SERVICE_Client *client, break; /* Not found: create new preference client */ if (NULL == c_cur) - { - c_cur = GNUNET_new (struct PreferenceClient); - c_cur->client = client; - c_cur->peer2pref = GNUNET_CONTAINER_multipeermap_create (16, - GNUNET_NO); - for (i = 0; i < GNUNET_ATS_PREFERENCE_END; i++) - c_cur->f_abs_sum[i] = DEFAULT_ABS_PREFERENCE; - GNUNET_CONTAINER_DLL_insert (pc_head, - pc_tail, - c_cur); - } + { + c_cur = GNUNET_new(struct PreferenceClient); + c_cur->client = client; + c_cur->peer2pref = GNUNET_CONTAINER_multipeermap_create(16, + GNUNET_NO); + for (i = 0; i < GNUNET_ATS_PREFERENCE_END; i++) + c_cur->f_abs_sum[i] = DEFAULT_ABS_PREFERENCE; + GNUNET_CONTAINER_DLL_insert(pc_head, + pc_tail, + c_cur); + } /* check global peer entry exists */ if (NULL == - (r_cur = GNUNET_CONTAINER_multipeermap_get (preference_peers, - peer))) - { - /* Create struct for peer */ - r_cur = GNUNET_new (struct PeerRelative); - for (i = 0; i < GNUNET_ATS_PREFERENCE_END; i++) - r_cur->f_rel[i] = DEFAULT_REL_PREFERENCE; - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put (preference_peers, + (r_cur = GNUNET_CONTAINER_multipeermap_get(preference_peers, + peer))) + { + /* Create struct for peer */ + r_cur = GNUNET_new(struct PeerRelative); + for (i = 0; i < GNUNET_ATS_PREFERENCE_END; i++) + r_cur->f_rel[i] = DEFAULT_REL_PREFERENCE; + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_put(preference_peers, peer, r_cur, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - } + } /* Find entry for peer */ - p_cur = GNUNET_CONTAINER_multipeermap_get (c_cur->peer2pref, - peer); + p_cur = GNUNET_CONTAINER_multipeermap_get(c_cur->peer2pref, + peer); if (NULL == p_cur) - { - /* Not found: create new peer entry */ - p_cur = GNUNET_new (struct PreferencePeer); - for (i = 0; i < GNUNET_ATS_PREFERENCE_END; i++) { - /* Default value per peer absolute preference for a preference*/ - p_cur->f_abs[i] = DEFAULT_ABS_PREFERENCE; - /* Default value per peer relative preference for a quality */ - p_cur->f_rel[i] = DEFAULT_REL_PREFERENCE; - } - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_put (c_cur->peer2pref, + /* Not found: create new peer entry */ + p_cur = GNUNET_new(struct PreferencePeer); + for (i = 0; i < GNUNET_ATS_PREFERENCE_END; i++) + { + /* Default value per peer absolute preference for a preference*/ + p_cur->f_abs[i] = DEFAULT_ABS_PREFERENCE; + /* Default value per peer relative preference for a quality */ + p_cur->f_rel[i] = DEFAULT_REL_PREFERENCE; + } + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_put(c_cur->peer2pref, peer, p_cur, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - r_cur->num_clients++; - } + r_cur->num_clients++; + } p_cur->f_abs[kind] += score_abs; - recalculate_relative_preferences (c_cur, kind); - GNUNET_CONTAINER_multipeermap_iterate (preference_peers, - &update_iterator, - &kind); + recalculate_relative_preferences(c_cur, kind); + GNUNET_CONTAINER_multipeermap_iterate(preference_peers, + &update_iterator, + &kind); if (NULL == aging_task) - aging_task = GNUNET_SCHEDULER_add_delayed (PREF_AGING_INTERVAL, - &preference_aging, - NULL); + aging_task = GNUNET_SCHEDULER_add_delayed(PREF_AGING_INTERVAL, + &preference_aging, + NULL); } @@ -650,28 +639,28 @@ update_preference (struct GNUNET_SERVICE_Client *client, * @param msg the request message */ void -GAS_handle_preference_change (struct GNUNET_SERVICE_Client *client, - const struct ChangePreferenceMessage *msg) +GAS_handle_preference_change(struct GNUNET_SERVICE_Client *client, + const struct ChangePreferenceMessage *msg) { const struct PreferenceInformation *pi; uint32_t nump; - nump = ntohl (msg->num_preferences); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received PREFERENCE_CHANGE message for peer `%s'\n", - GNUNET_i2s (&msg->peer)); - GNUNET_STATISTICS_update (GSA_stats, - "# preference change requests processed", - 1, - GNUNET_NO); - pi = (const struct PreferenceInformation *) &msg[1]; - GAS_plugin_solver_lock (); + nump = ntohl(msg->num_preferences); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received PREFERENCE_CHANGE message for peer `%s'\n", + GNUNET_i2s(&msg->peer)); + GNUNET_STATISTICS_update(GSA_stats, + "# preference change requests processed", + 1, + GNUNET_NO); + pi = (const struct PreferenceInformation *)&msg[1]; + GAS_plugin_solver_lock(); for (uint32_t i = 0; i < nump; i++) - update_preference (client, - &msg->peer, - (enum GNUNET_ATS_PreferenceKind) ntohl (pi[i].preference_kind), - pi[i].preference_value); - GAS_plugin_solver_unlock (); + update_preference(client, + &msg->peer, + (enum GNUNET_ATS_PreferenceKind)ntohl(pi[i].preference_kind), + pi[i].preference_value); + GAS_plugin_solver_unlock(); } @@ -679,12 +668,12 @@ GAS_handle_preference_change (struct GNUNET_SERVICE_Client *client, * Initialize preferences subsystem. */ void -GAS_preference_init () +GAS_preference_init() { unsigned int i; - preference_peers = GNUNET_CONTAINER_multipeermap_create (16, - GNUNET_NO); + preference_peers = GNUNET_CONTAINER_multipeermap_create(16, + GNUNET_NO); for (i = 0; i < GNUNET_ATS_PREFERENCE_END; i++) defvalues.f_rel[i] = DEFAULT_REL_PREFERENCE; } @@ -694,34 +683,33 @@ GAS_preference_init () * Shutdown preferences subsystem. */ void -GAS_preference_done () +GAS_preference_done() { struct PreferenceClient *pc; struct PreferenceClient *next_pc; if (NULL != aging_task) - { - GNUNET_SCHEDULER_cancel (aging_task); - aging_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(aging_task); + aging_task = NULL; + } next_pc = pc_head; while (NULL != (pc = next_pc)) - { - next_pc = pc->next; - GNUNET_CONTAINER_DLL_remove (pc_head, - pc_tail, - pc); - GNUNET_CONTAINER_multipeermap_iterate (pc->peer2pref, - &free_preference, - pc); - GNUNET_CONTAINER_multipeermap_destroy (pc->peer2pref); - GNUNET_free (pc); - } - GNUNET_CONTAINER_multipeermap_iterate (preference_peers, - &free_peer, - NULL); - GNUNET_CONTAINER_multipeermap_destroy (preference_peers); - + { + next_pc = pc->next; + GNUNET_CONTAINER_DLL_remove(pc_head, + pc_tail, + pc); + GNUNET_CONTAINER_multipeermap_iterate(pc->peer2pref, + &free_preference, + pc); + GNUNET_CONTAINER_multipeermap_destroy(pc->peer2pref); + GNUNET_free(pc); + } + GNUNET_CONTAINER_multipeermap_iterate(preference_peers, + &free_peer, + NULL); + GNUNET_CONTAINER_multipeermap_destroy(preference_peers); } @@ -735,17 +723,17 @@ GAS_preference_done () * default preferences if peer does not exist */ const double * -GAS_preference_get_by_peer (void *cls, - const struct GNUNET_PeerIdentity *id) +GAS_preference_get_by_peer(void *cls, + const struct GNUNET_PeerIdentity *id) { struct PeerRelative *rp; if (NULL == - (rp = GNUNET_CONTAINER_multipeermap_get (preference_peers, - id))) - { - return defvalues.f_rel; - } + (rp = GNUNET_CONTAINER_multipeermap_get(preference_peers, + id))) + { + return defvalues.f_rel; + } return rp->f_rel; } @@ -756,7 +744,7 @@ GAS_preference_get_by_peer (void *cls, * @param client the client */ void -GAS_preference_client_disconnect (struct GNUNET_SERVICE_Client *client) +GAS_preference_client_disconnect(struct GNUNET_SERVICE_Client *client) { struct PreferenceClient *c_cur; @@ -765,14 +753,14 @@ GAS_preference_client_disconnect (struct GNUNET_SERVICE_Client *client) break; if (NULL == c_cur) return; - GNUNET_CONTAINER_DLL_remove (pc_head, - pc_tail, - c_cur); - GNUNET_CONTAINER_multipeermap_iterate (c_cur->peer2pref, - &free_preference, - c_cur); - GNUNET_CONTAINER_multipeermap_destroy (c_cur->peer2pref); - GNUNET_free (c_cur); + GNUNET_CONTAINER_DLL_remove(pc_head, + pc_tail, + c_cur); + GNUNET_CONTAINER_multipeermap_iterate(c_cur->peer2pref, + &free_preference, + c_cur); + GNUNET_CONTAINER_multipeermap_destroy(c_cur->peer2pref); + GNUNET_free(c_cur); } diff --git a/src/ats/gnunet-service-ats_preferences.h b/src/ats/gnunet-service-ats_preferences.h index e0c7aa2e3..48aa33ea6 100644 --- a/src/ats/gnunet-service-ats_preferences.h +++ b/src/ats/gnunet-service-ats_preferences.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2011-2014 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2011-2014 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -50,22 +50,22 @@ * @param msg the request message */ void -GAS_handle_preference_change (struct GNUNET_SERVICE_Client *client, - const struct ChangePreferenceMessage *msg); +GAS_handle_preference_change(struct GNUNET_SERVICE_Client *client, + const struct ChangePreferenceMessage *msg); /** * Initialize preferences subsystem. */ void -GAS_preference_init (void); +GAS_preference_init(void); /** * Shutdown preferences subsystem. */ void -GAS_preference_done (void); +GAS_preference_done(void); /** @@ -77,8 +77,8 @@ GAS_preference_done (void); * with `enum GNUNET_ATS_PreferenceKind`, never NULL */ const double * -GAS_preference_get_by_peer (void *cls, - const struct GNUNET_PeerIdentity *id); +GAS_preference_get_by_peer(void *cls, + const struct GNUNET_PeerIdentity *id); /** @@ -87,7 +87,7 @@ GAS_preference_get_by_peer (void *cls, * @param client the disconnecting client */ void -GAS_preference_client_disconnect (struct GNUNET_SERVICE_Client *client); +GAS_preference_client_disconnect(struct GNUNET_SERVICE_Client *client); #endif diff --git a/src/ats/gnunet-service-ats_reservations.c b/src/ats/gnunet-service-ats_reservations.c index 41de442c7..ec1f4b0d5 100644 --- a/src/ats/gnunet-service-ats_reservations.c +++ b/src/ats/gnunet-service-ats_reservations.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats_reservations.c * @brief ats service, inbound bandwidth reservation management @@ -53,38 +53,38 @@ static struct GNUNET_CONTAINER_MultiPeerMap *trackers; * until the reservation might succeed */ static struct GNUNET_TIME_Relative -reservations_reserve (const struct GNUNET_PeerIdentity *peer, - int32_t amount) +reservations_reserve(const struct GNUNET_PeerIdentity *peer, + int32_t amount) { struct GNUNET_BANDWIDTH_Tracker *tracker; struct GNUNET_TIME_Relative ret; - tracker = GNUNET_CONTAINER_multipeermap_get (trackers, - peer); + tracker = GNUNET_CONTAINER_multipeermap_get(trackers, + peer); if (NULL == tracker) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Not connected, allowing reservation of %d bytes\n", - (int) amount); - return GNUNET_TIME_UNIT_ZERO; /* not connected, satisfy now */ - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Not connected, allowing reservation of %d bytes\n", + (int)amount); + return GNUNET_TIME_UNIT_ZERO; /* not connected, satisfy now */ + } if (amount >= 0) - { - ret = GNUNET_BANDWIDTH_tracker_get_delay (tracker, amount); - if (ret.rel_value_us > 0) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Delay to satisfy reservation for %d bytes is %s\n", - (int) amount, - GNUNET_STRINGS_relative_time_to_string (ret, - GNUNET_YES)); - return ret; + ret = GNUNET_BANDWIDTH_tracker_get_delay(tracker, amount); + if (ret.rel_value_us > 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Delay to satisfy reservation for %d bytes is %s\n", + (int)amount, + GNUNET_STRINGS_relative_time_to_string(ret, + GNUNET_YES)); + return ret; + } } - } - (void) GNUNET_BANDWIDTH_tracker_consume (tracker, amount); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Reserved %d bytes\n", - (int) amount); + (void)GNUNET_BANDWIDTH_tracker_consume(tracker, amount); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Reserved %d bytes\n", + (int)amount); return GNUNET_TIME_UNIT_ZERO; } @@ -98,40 +98,40 @@ reservations_reserve (const struct GNUNET_PeerIdentity *peer, * this peer (estimate) */ void -GAS_reservations_set_bandwidth (const struct GNUNET_PeerIdentity *peer, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) +GAS_reservations_set_bandwidth(const struct GNUNET_PeerIdentity *peer, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) { struct GNUNET_BANDWIDTH_Tracker *tracker; - tracker = GNUNET_CONTAINER_multipeermap_get (trackers, peer); - if (0 == ntohl (bandwidth_in.value__)) - { - if (NULL == tracker) - return; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (trackers, + tracker = GNUNET_CONTAINER_multipeermap_get(trackers, peer); + if (0 == ntohl(bandwidth_in.value__)) + { + if (NULL == tracker) + return; + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(trackers, peer, tracker)); - GNUNET_free (tracker); - return; - } + GNUNET_free(tracker); + return; + } if (NULL == tracker) - { - tracker = GNUNET_new (struct GNUNET_BANDWIDTH_Tracker); - GNUNET_BANDWIDTH_tracker_init (tracker, - NULL, - NULL, - bandwidth_in, - MAX_BANDWIDTH_CARRY_S); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put (trackers, + { + tracker = GNUNET_new(struct GNUNET_BANDWIDTH_Tracker); + GNUNET_BANDWIDTH_tracker_init(tracker, + NULL, + NULL, + bandwidth_in, + MAX_BANDWIDTH_CARRY_S); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_put(trackers, peer, tracker, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - return; - } - GNUNET_BANDWIDTH_tracker_update_quota (tracker, - bandwidth_in); + return; + } + GNUNET_BANDWIDTH_tracker_update_quota(tracker, + bandwidth_in); } @@ -142,31 +142,31 @@ GAS_reservations_set_bandwidth (const struct GNUNET_PeerIdentity *peer, * @param msg the request message */ void -GAS_handle_reservation_request (struct GNUNET_SERVICE_Client *client, - const struct ReservationRequestMessage *msg) +GAS_handle_reservation_request(struct GNUNET_SERVICE_Client *client, + const struct ReservationRequestMessage *msg) { struct GNUNET_MQ_Envelope *env; struct ReservationResultMessage *result; int32_t amount; struct GNUNET_TIME_Relative res_delay; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received RESERVATION_REQUEST message\n"); - amount = (int32_t) ntohl (msg->amount); - res_delay = reservations_reserve (&msg->peer, amount); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received RESERVATION_REQUEST message\n"); + amount = (int32_t)ntohl(msg->amount); + res_delay = reservations_reserve(&msg->peer, amount); if (res_delay.rel_value_us > 0) amount = 0; - env = GNUNET_MQ_msg (result, - GNUNET_MESSAGE_TYPE_ATS_RESERVATION_RESULT); - result->amount = htonl (amount); + env = GNUNET_MQ_msg(result, + GNUNET_MESSAGE_TYPE_ATS_RESERVATION_RESULT); + result->amount = htonl(amount); result->peer = msg->peer; - result->res_delay = GNUNET_TIME_relative_hton (res_delay); - GNUNET_STATISTICS_update (GSA_stats, - "# reservation requests processed", - 1, - GNUNET_NO); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), - env); + result->res_delay = GNUNET_TIME_relative_hton(res_delay); + GNUNET_STATISTICS_update(GSA_stats, + "# reservation requests processed", + 1, + GNUNET_NO); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), + env); } @@ -174,10 +174,10 @@ GAS_handle_reservation_request (struct GNUNET_SERVICE_Client *client, * Initialize reservations subsystem. */ void -GAS_reservations_init () +GAS_reservations_init() { - trackers = GNUNET_CONTAINER_multipeermap_create (128, - GNUNET_NO); + trackers = GNUNET_CONTAINER_multipeermap_create(128, + GNUNET_NO); } @@ -190,13 +190,13 @@ GAS_reservations_init () * @return #GNUNET_OK (continue to iterate) */ static int -free_tracker (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +free_tracker(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct GNUNET_BANDWIDTH_Tracker *tracker = value; - GNUNET_free (tracker); + GNUNET_free(tracker); return GNUNET_OK; } @@ -205,12 +205,12 @@ free_tracker (void *cls, * Shutdown reservations subsystem. */ void -GAS_reservations_done () +GAS_reservations_done() { - GNUNET_CONTAINER_multipeermap_iterate (trackers, - &free_tracker, - NULL); - GNUNET_CONTAINER_multipeermap_destroy (trackers); + GNUNET_CONTAINER_multipeermap_iterate(trackers, + &free_tracker, + NULL); + GNUNET_CONTAINER_multipeermap_destroy(trackers); } /* end of gnunet-service-ats_reservations.c */ diff --git a/src/ats/gnunet-service-ats_reservations.h b/src/ats/gnunet-service-ats_reservations.h index 525236e8c..100cd9a90 100644 --- a/src/ats/gnunet-service-ats_reservations.h +++ b/src/ats/gnunet-service-ats_reservations.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats_reservations.h @@ -39,9 +39,9 @@ * this peer (estimate) */ void -GAS_reservations_set_bandwidth (const struct GNUNET_PeerIdentity *peer, - struct GNUNET_BANDWIDTH_Value32NBO - bandwidth_in); +GAS_reservations_set_bandwidth(const struct GNUNET_PeerIdentity *peer, + struct GNUNET_BANDWIDTH_Value32NBO + bandwidth_in); /** @@ -51,8 +51,8 @@ GAS_reservations_set_bandwidth (const struct GNUNET_PeerIdentity *peer, * @param message the request message */ void -GAS_handle_reservation_request (struct GNUNET_SERVICE_Client *client, - const struct ReservationRequestMessage *message); +GAS_handle_reservation_request(struct GNUNET_SERVICE_Client *client, + const struct ReservationRequestMessage *message); /** @@ -61,13 +61,13 @@ GAS_handle_reservation_request (struct GNUNET_SERVICE_Client *client, * @param server handle to our server */ void -GAS_reservations_init (void); +GAS_reservations_init(void); /** * Shutdown reservations subsystem. */ void -GAS_reservations_done (void); +GAS_reservations_done(void); #endif diff --git a/src/ats/gnunet-service-ats_scheduling.c b/src/ats/gnunet-service-ats_scheduling.c index 870912dc7..d50df9b2e 100644 --- a/src/ats/gnunet-service-ats_scheduling.c +++ b/src/ats/gnunet-service-ats_scheduling.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats_scheduling.c @@ -42,14 +42,14 @@ static struct GNUNET_SERVICE_Client *my_client; * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GAS_scheduling_add_client (struct GNUNET_SERVICE_Client *client) +GAS_scheduling_add_client(struct GNUNET_SERVICE_Client *client) { if (NULL != my_client) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "This ATS already has a scheduling client, refusing new scheduling client for now.\n"); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "This ATS already has a scheduling client, refusing new scheduling client for now.\n"); + return GNUNET_SYSERR; + } my_client = client; return GNUNET_OK; } @@ -62,11 +62,11 @@ GAS_scheduling_add_client (struct GNUNET_SERVICE_Client *client) * @param client handle of the (now dead) client */ void -GAS_scheduling_remove_client (struct GNUNET_SERVICE_Client *client) +GAS_scheduling_remove_client(struct GNUNET_SERVICE_Client *client) { if (my_client != client) return; - GAS_addresses_destroy_all (); + GAS_addresses_destroy_all(); my_client = NULL; } @@ -81,33 +81,33 @@ GAS_scheduling_remove_client (struct GNUNET_SERVICE_Client *client) * @param bandwidth_in assigned inbound bandwidth */ void -GAS_scheduling_transmit_address_suggestion (const struct GNUNET_PeerIdentity *peer, - uint32_t session_id, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) +GAS_scheduling_transmit_address_suggestion(const struct GNUNET_PeerIdentity *peer, + uint32_t session_id, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) { struct GNUNET_MQ_Envelope *env; struct AddressSuggestionMessage *msg; if (NULL == my_client) return; - GNUNET_STATISTICS_update (GSA_stats, - "# address suggestions made", - 1, - GNUNET_NO); - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_ATS_ADDRESS_SUGGESTION); + GNUNET_STATISTICS_update(GSA_stats, + "# address suggestions made", + 1, + GNUNET_NO); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_ATS_ADDRESS_SUGGESTION); msg->peer = *peer; - msg->session_id = htonl (session_id); + msg->session_id = htonl(session_id); msg->bandwidth_out = bandwidth_out; msg->bandwidth_in = bandwidth_in; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "ATS sends quota for peer `%s': (in/out) %u/%u\n", - GNUNET_i2s (peer), - (unsigned int) ntohl (bandwidth_in.value__), - (unsigned int) ntohl (bandwidth_out.value__)); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (my_client), - env); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "ATS sends quota for peer `%s': (in/out) %u/%u\n", + GNUNET_i2s(peer), + (unsigned int)ntohl(bandwidth_in.value__), + (unsigned int)ntohl(bandwidth_out.value__)); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(my_client), + env); } @@ -117,7 +117,7 @@ GAS_scheduling_transmit_address_suggestion (const struct GNUNET_PeerIdentity *pe * @param m the request message */ void -GAS_handle_address_add (const struct AddressAddMessage *m) +GAS_handle_address_add(const struct AddressAddMessage *m) { const char *address; const char *plugin_name; @@ -125,30 +125,30 @@ GAS_handle_address_add (const struct AddressAddMessage *m) uint16_t plugin_name_length; struct GNUNET_ATS_Properties prop; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received `%s' message\n", - "ADDRESS_ADD"); - address_length = ntohs (m->address_length); - plugin_name_length = ntohs (m->plugin_name_length); - address = (const char *) &m[1]; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received `%s' message\n", + "ADDRESS_ADD"); + address_length = ntohs(m->address_length); + plugin_name_length = ntohs(m->plugin_name_length); + address = (const char *)&m[1]; if (plugin_name_length != 0) plugin_name = &address[address_length]; else plugin_name = ""; - GNUNET_STATISTICS_update (GSA_stats, - "# addresses created", - 1, - GNUNET_NO); - GNUNET_ATS_properties_ntoh (&prop, - &m->properties); - GNUNET_break (GNUNET_NT_UNSPECIFIED != prop.scope); - GAS_addresses_add (&m->peer, - plugin_name, - address, - address_length, - ntohl (m->address_local_info), - ntohl (m->session_id), - &prop); + GNUNET_STATISTICS_update(GSA_stats, + "# addresses created", + 1, + GNUNET_NO); + GNUNET_ATS_properties_ntoh(&prop, + &m->properties); + GNUNET_break(GNUNET_NT_UNSPECIFIED != prop.scope); + GAS_addresses_add(&m->peer, + plugin_name, + address, + address_length, + ntohl(m->address_local_info), + ntohl(m->session_id), + &prop); } @@ -158,19 +158,19 @@ GAS_handle_address_add (const struct AddressAddMessage *m) * @param m the request message */ void -GAS_handle_address_update (const struct AddressUpdateMessage *m) +GAS_handle_address_update(const struct AddressUpdateMessage *m) { struct GNUNET_ATS_Properties prop; - GNUNET_STATISTICS_update (GSA_stats, - "# address updates received", - 1, - GNUNET_NO); - GNUNET_ATS_properties_ntoh (&prop, - &m->properties); - GAS_addresses_update (&m->peer, - ntohl (m->session_id), - &prop); + GNUNET_STATISTICS_update(GSA_stats, + "# address updates received", + 1, + GNUNET_NO); + GNUNET_ATS_properties_ntoh(&prop, + &m->properties); + GAS_addresses_update(&m->peer, + ntohl(m->session_id), + &prop); } @@ -180,26 +180,26 @@ GAS_handle_address_update (const struct AddressUpdateMessage *m) * @param m the request message */ void -GAS_handle_address_destroyed (const struct AddressDestroyedMessage *m) +GAS_handle_address_destroyed(const struct AddressDestroyedMessage *m) { struct GNUNET_MQ_Envelope *env; struct GNUNET_ATS_SessionReleaseMessage *srm; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received `%s' message\n", - "ADDRESS_DESTROYED"); - GNUNET_STATISTICS_update (GSA_stats, - "# addresses destroyed", - 1, - GNUNET_NO); - GAS_addresses_destroy (&m->peer, - ntohl (m->session_id)); - env = GNUNET_MQ_msg (srm, - GNUNET_MESSAGE_TYPE_ATS_SESSION_RELEASE); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received `%s' message\n", + "ADDRESS_DESTROYED"); + GNUNET_STATISTICS_update(GSA_stats, + "# addresses destroyed", + 1, + GNUNET_NO); + GAS_addresses_destroy(&m->peer, + ntohl(m->session_id)); + env = GNUNET_MQ_msg(srm, + GNUNET_MESSAGE_TYPE_ATS_SESSION_RELEASE); srm->session_id = m->session_id; srm->peer = m->peer; - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (my_client), - env); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(my_client), + env); } diff --git a/src/ats/gnunet-service-ats_scheduling.h b/src/ats/gnunet-service-ats_scheduling.h index 30cceb97b..b2575ca60 100644 --- a/src/ats/gnunet-service-ats_scheduling.h +++ b/src/ats/gnunet-service-ats_scheduling.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/gnunet-service-ats_scheduling.h @@ -37,7 +37,7 @@ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GAS_scheduling_add_client (struct GNUNET_SERVICE_Client *client); +GAS_scheduling_add_client(struct GNUNET_SERVICE_Client *client); /** @@ -47,7 +47,7 @@ GAS_scheduling_add_client (struct GNUNET_SERVICE_Client *client); * @param client handle of the (now dead) client */ void -GAS_scheduling_remove_client (struct GNUNET_SERVICE_Client *client); +GAS_scheduling_remove_client(struct GNUNET_SERVICE_Client *client); /** @@ -60,10 +60,10 @@ GAS_scheduling_remove_client (struct GNUNET_SERVICE_Client *client); * @param bandwidth_in assigned inbound bandwidth */ void -GAS_scheduling_transmit_address_suggestion (const struct GNUNET_PeerIdentity *peer, - uint32_t session_id, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in); +GAS_scheduling_transmit_address_suggestion(const struct GNUNET_PeerIdentity *peer, + uint32_t session_id, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in); /** @@ -73,7 +73,7 @@ GAS_scheduling_transmit_address_suggestion (const struct GNUNET_PeerIdentity *pe * @param m the request message */ void -GAS_handle_address_add (const struct AddressAddMessage *m); +GAS_handle_address_add(const struct AddressAddMessage *m); /** @@ -82,7 +82,7 @@ GAS_handle_address_add (const struct AddressAddMessage *m); * @param m the request message */ void -GAS_handle_address_update (const struct AddressUpdateMessage *m); +GAS_handle_address_update(const struct AddressUpdateMessage *m); /** @@ -91,7 +91,7 @@ GAS_handle_address_update (const struct AddressUpdateMessage *m); * @param m the request message */ void -GAS_handle_address_destroyed (const struct AddressDestroyedMessage *m); +GAS_handle_address_destroyed(const struct AddressDestroyedMessage *m); #endif diff --git a/src/ats/perf_ats_solver.c b/src/ats/perf_ats_solver.c index 33180a953..6a4eadad7 100644 --- a/src/ats/perf_ats_solver.c +++ b/src/ats/perf_ats_solver.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010,2011 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010,2011 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -49,8 +49,7 @@ struct GNUNET_STATISTICS_Handle *GSA_stats; /** * Handle for ATS address component */ -struct PerfHandle -{ +struct PerfHandle { /** * Performance peers */ @@ -165,8 +164,7 @@ struct PerfHandle /** * Data structure to store results for a single iteration */ -struct Iteration -{ +struct Iteration { struct Result **results_array; struct Result **update_results_array; @@ -176,8 +174,7 @@ struct Iteration /** * Result for a solver calculcation */ -struct Result -{ +struct Result { /** * Previous element in the linked list */ @@ -283,8 +280,7 @@ struct Result /** * Peer used for the benchmarking */ -struct PerfPeer -{ +struct PerfPeer { /** * Peer identitity */ @@ -317,19 +313,19 @@ static int ret; * Do shutdown */ static void -end_now (int res) +end_now(int res) { if (NULL != ph.stat) - { - GNUNET_STATISTICS_destroy (ph.stat, GNUNET_NO); - ph.stat = NULL; - } + { + GNUNET_STATISTICS_destroy(ph.stat, GNUNET_NO); + ph.stat = NULL; + } - GNUNET_free_non_null (ph.peers); - GNUNET_free_non_null (ph.iterations_results); + GNUNET_free_non_null(ph.peers); + GNUNET_free_non_null(ph.iterations_results); - GAS_normalization_stop (); - GAS_preference_done (); + GAS_normalization_stop(); + GAS_preference_done(); ret = res; } @@ -340,13 +336,12 @@ end_now (int res) * @param cp the number of the peer */ static void -perf_create_peer (int cp) +perf_create_peer(int cp) { - - GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, - &ph.peers[cp].id, sizeof (struct GNUNET_PeerIdentity)); + GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_WEAK, + &ph.peers[cp].id, sizeof(struct GNUNET_PeerIdentity)); GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Creating peer #%u: %s \n", cp, - GNUNET_i2s (&ph.peers[cp].id)); + GNUNET_i2s(&ph.peers[cp].id)); } @@ -356,91 +351,94 @@ perf_create_peer (int cp) * @param cur the address to update */ static void -perf_update_address (struct ATS_Address *cur) +perf_update_address(struct ATS_Address *cur) { int r_type; int abs_val; double rel_val; - r_type = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 2); + r_type = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 2); switch (r_type) - { - case 0: - abs_val = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100); - rel_val = (100 + (double) abs_val) / 100; - - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Updating peer `%s' address %p type %s abs val %u rel val %.3f\n", - GNUNET_i2s (&cur->peer), cur, - "GNUNET_ATS_QUALITY_NET_DELAY", - abs_val, rel_val); - ph.sf->s_address_update_property (ph.sf->cls, cur, - GNUNET_ATS_QUALITY_NET_DELAY, - abs_val, rel_val); - break; - case 1: - abs_val = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 10); - rel_val = (100 + (double) abs_val) / 100; - - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Updating peer `%s' address %p type %s abs val %u rel val %.3f\n", - GNUNET_i2s (&cur->peer), cur, "GNUNET_ATS_QUALITY_NET_DISTANCE", - abs_val, rel_val); - ph.sf->s_address_update_property (ph.sf->cls, cur, - GNUNET_ATS_QUALITY_NET_DISTANCE, - abs_val, rel_val); - break; - default: - break; - } + { + case 0: + abs_val = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 100); + rel_val = (100 + (double)abs_val) / 100; + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Updating peer `%s' address %p type %s abs val %u rel val %.3f\n", + GNUNET_i2s(&cur->peer), cur, + "GNUNET_ATS_QUALITY_NET_DELAY", + abs_val, rel_val); + ph.sf->s_address_update_property(ph.sf->cls, cur, + GNUNET_ATS_QUALITY_NET_DELAY, + abs_val, rel_val); + break; + + case 1: + abs_val = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 10); + rel_val = (100 + (double)abs_val) / 100; + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Updating peer `%s' address %p type %s abs val %u rel val %.3f\n", + GNUNET_i2s(&cur->peer), cur, "GNUNET_ATS_QUALITY_NET_DISTANCE", + abs_val, rel_val); + ph.sf->s_address_update_property(ph.sf->cls, cur, + GNUNET_ATS_QUALITY_NET_DISTANCE, + abs_val, rel_val); + break; + + default: + break; + } } static void -bandwidth_changed_cb (void *cls, - struct ATS_Address *address) +bandwidth_changed_cb(void *cls, + struct ATS_Address *address) { - if ( (0 == address->assigned_bw_out) && (0 == address->assigned_bw_in) ) + if ((0 == address->assigned_bw_out) && (0 == address->assigned_bw_in)) return; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Bandwidth changed addresses %s %p to %u Bps out / %u Bps in\n", - GNUNET_i2s (&address->peer), - address, - address->assigned_bw_out, - address->assigned_bw_in); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Bandwidth changed addresses %s %p to %u Bps out / %u Bps in\n", + GNUNET_i2s(&address->peer), + address, + address->assigned_bw_out, + address->assigned_bw_in); if (GNUNET_YES == ph.bulk_running) - GNUNET_break (0); + GNUNET_break(0); return; } static const double * -get_preferences_cb (void *cls, const struct GNUNET_PeerIdentity *id) +get_preferences_cb(void *cls, const struct GNUNET_PeerIdentity *id) { - return GAS_preference_get_by_peer (NULL, id); + return GAS_preference_get_by_peer(NULL, id); } static void -perf_address_initial_update (void *dead, - struct GNUNET_CONTAINER_MultiPeerMap * addresses, - struct ATS_Address *address) +perf_address_initial_update(void *dead, + struct GNUNET_CONTAINER_MultiPeerMap * addresses, + struct ATS_Address *address) { double delay; double distance; - uint32_t random = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100); - delay = (100 + (double) random) / 100; - ph.sf->s_address_update_property (ph.sf->cls, - address, GNUNET_ATS_QUALITY_NET_DELAY, - 100, delay); + uint32_t random = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 100); - random = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100); - distance = (100 + (double) random) / 100; + delay = (100 + (double)random) / 100; + ph.sf->s_address_update_property(ph.sf->cls, + address, GNUNET_ATS_QUALITY_NET_DELAY, + 100, delay); - ph.sf->s_address_update_property (ph.sf->cls, address, - GNUNET_ATS_QUALITY_NET_DISTANCE, - 10, distance); + random = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 100); + distance = (100 + (double)random) / 100; + + ph.sf->s_address_update_property(ph.sf->cls, address, + GNUNET_ATS_QUALITY_NET_DISTANCE, + 10, distance); GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Initial update address %p : %.2f %.2f\n", @@ -448,23 +446,22 @@ perf_address_initial_update (void *dead, } -struct DUA_Ctx -{ +struct DUA_Ctx { int r; int c_cur_a; }; static int -do_update_address (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *value) +do_update_address(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *value) { struct DUA_Ctx *ctx = cls; struct ATS_Address *addr = value; if (ctx->c_cur_a == ctx->r) - perf_update_address (addr); + perf_update_address(addr); ctx->c_cur_a++; return GNUNET_OK; } @@ -478,7 +475,7 @@ do_update_address (void *cls, * @param percentage_peers the percentage of peers to update */ static void -perf_update_all_addresses (unsigned int cp, unsigned int ca, unsigned int percentage_peers) +perf_update_all_addresses(unsigned int cp, unsigned int ca, unsigned int percentage_peers) { int c_peer; int c_select; @@ -488,9 +485,9 @@ perf_update_all_addresses (unsigned int cp, unsigned int ca, unsigned int percen unsigned int m[cp]; struct DUA_Ctx dua_ctx; - count = cp * ((double) percentage_peers / 100); + count = cp * ((double)percentage_peers / 100); GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Updating %u of %u peers \n", count, cp); + "Updating %u of %u peers \n", count, cp); for (c_peer = 0; c_peer < cp; c_peer++) m[c_peer] = 0; @@ -498,32 +495,32 @@ perf_update_all_addresses (unsigned int cp, unsigned int ca, unsigned int percen c_select = 0; while (c_select < count) - { - r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, cp); - if (0 == m[r]) { - m[r] = 1; - GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Updating peer [%u] \n", r); - c_select++; + r = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, cp); + if (0 == m[r]) + { + m[r] = 1; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Updating peer [%u] \n", r); + c_select++; + } } - } for (c_cur_p = 0; c_cur_p < cp; c_cur_p++) - { - if (1 == m[c_cur_p]) { - r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, ca); - GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, - "Updating peer [%u] address [%u]\n", c_cur_p, r); - - dua_ctx.c_cur_a = 0; - dua_ctx.r = r; - GNUNET_CONTAINER_multipeermap_get_multiple (ph.addresses, - &ph.peers[c_cur_p].id, - &do_update_address, - &dua_ctx); + if (1 == m[c_cur_p]) + { + r = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, ca); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Updating peer [%u] address [%u]\n", c_cur_p, r); + + dua_ctx.c_cur_a = 0; + dua_ctx.r = r; + GNUNET_CONTAINER_multipeermap_get_multiple(ph.addresses, + &ph.peers[c_cur_p].id, + &do_update_address, + &dua_ctx); + } } - } } /** @@ -534,14 +531,14 @@ perf_update_all_addresses (unsigned int cp, unsigned int ca, unsigned int percen * @return the address */ static struct ATS_Address * -perf_create_address (int cp, int ca) +perf_create_address(int cp, int ca) { struct ATS_Address *a; - a = create_address (&ph.peers[cp].id, - "Test 1", "test 1", strlen ("test 1") + 1, 0); - GNUNET_CONTAINER_multipeermap_put (ph.addresses, &ph.peers[cp].id, a, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + a = create_address(&ph.peers[cp].id, + "Test 1", "test 1", strlen("test 1") + 1, 0); + GNUNET_CONTAINER_multipeermap_put(ph.addresses, &ph.peers[cp].id, a, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); return a; } @@ -554,93 +551,100 @@ perf_create_address (int cp, int ca) * @param add additional solver information */ static void -solver_info_cb (void *cls, - enum GAS_Solver_Operation op, - enum GAS_Solver_Status stat, - enum GAS_Solver_Additional_Information add) +solver_info_cb(void *cls, + enum GAS_Solver_Operation op, + enum GAS_Solver_Status stat, + enum GAS_Solver_Additional_Information add) { char *add_info; - switch (add) { + + switch (add) + { case GAS_INFO_NONE: add_info = "GAS_INFO_NONE"; break; + case GAS_INFO_FULL: add_info = "GAS_INFO_MLP_FULL"; break; + case GAS_INFO_UPDATED: add_info = "GAS_INFO_MLP_UPDATED"; break; + case GAS_INFO_PROP_ALL: add_info = "GAS_INFO_PROP_ALL"; break; + case GAS_INFO_PROP_SINGLE: add_info = "GAS_INFO_PROP_SINGLE"; break; + default: add_info = "INVALID"; break; - } + } struct Result *tmp; switch (op) - { + { case GAS_OP_SOLVE_START: GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Solver notifies `%s' with result `%s' `%s'\n", "GAS_OP_SOLVE_START", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL", add_info); + "Solver notifies `%s' with result `%s' `%s'\n", "GAS_OP_SOLVE_START", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL", add_info); if (GNUNET_NO == ph.expecting_solution) - { - /* We do not expect a solution at the moment */ - GNUNET_break (0); - return; - } - - if ((GAS_STAT_SUCCESS == stat) && (NULL == ph.current_result)) - { - tmp = GNUNET_new (struct Result); - /* Create new result */ - if ((add == GAS_INFO_UPDATED) || (GNUNET_YES == ph.performed_update)) - { - ph.current_result = tmp; - //fprintf (stderr,"UPDATE %u %u\n",ph.current_iteration-1, ph.current_p); - ph.iterations_results[ph.current_iteration-1].update_results_array[ph.current_p] = tmp; - } - else { - ph.current_result = tmp; - //fprintf (stderr,"FULL %u %u\n",ph.current_iteration-1, ph.current_p); - ph.iterations_results[ph.current_iteration-1].results_array[ph.current_p] = tmp; + /* We do not expect a solution at the moment */ + GNUNET_break(0); + return; } - ph.current_result->addresses = ph.current_a; - ph.current_result->peers = ph.current_p; - ph.current_result->s_total = GNUNET_TIME_absolute_get(); - ph.current_result->d_total_full = GNUNET_TIME_UNIT_FOREVER_REL; - ph.current_result->d_setup_full = GNUNET_TIME_UNIT_FOREVER_REL; - ph.current_result->d_lp_full = GNUNET_TIME_UNIT_FOREVER_REL; - ph.current_result->d_mlp_full = GNUNET_TIME_UNIT_FOREVER_REL; - ph.current_result->info = add; - if ((add == GAS_INFO_UPDATED) || (GNUNET_YES == ph.performed_update)) - { - ph.current_result->update = GNUNET_YES; - } - else + if ((GAS_STAT_SUCCESS == stat) && (NULL == ph.current_result)) { - ph.current_result->update = GNUNET_NO; + tmp = GNUNET_new(struct Result); + /* Create new result */ + if ((add == GAS_INFO_UPDATED) || (GNUNET_YES == ph.performed_update)) + { + ph.current_result = tmp; + //fprintf (stderr,"UPDATE %u %u\n",ph.current_iteration-1, ph.current_p); + ph.iterations_results[ph.current_iteration - 1].update_results_array[ph.current_p] = tmp; + } + else + { + ph.current_result = tmp; + //fprintf (stderr,"FULL %u %u\n",ph.current_iteration-1, ph.current_p); + ph.iterations_results[ph.current_iteration - 1].results_array[ph.current_p] = tmp; + } + + ph.current_result->addresses = ph.current_a; + ph.current_result->peers = ph.current_p; + ph.current_result->s_total = GNUNET_TIME_absolute_get(); + ph.current_result->d_total_full = GNUNET_TIME_UNIT_FOREVER_REL; + ph.current_result->d_setup_full = GNUNET_TIME_UNIT_FOREVER_REL; + ph.current_result->d_lp_full = GNUNET_TIME_UNIT_FOREVER_REL; + ph.current_result->d_mlp_full = GNUNET_TIME_UNIT_FOREVER_REL; + ph.current_result->info = add; + if ((add == GAS_INFO_UPDATED) || (GNUNET_YES == ph.performed_update)) + { + ph.current_result->update = GNUNET_YES; + } + else + { + ph.current_result->update = GNUNET_NO; + } } - - } return; + case GAS_OP_SOLVE_STOP: GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Solver notifies `%s' with result `%s', `%s'\n", "GAS_OP_SOLVE_STOP", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL", add_info); + "Solver notifies `%s' with result `%s', `%s'\n", "GAS_OP_SOLVE_STOP", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL", add_info); if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result)) - { - /* We do not expect a solution at the moment */ - GNUNET_break (0); - return; - } + { + /* We do not expect a solution at the moment */ + GNUNET_break(0); + return; + } if (GAS_STAT_SUCCESS == stat) ph.current_result->valid = GNUNET_YES; @@ -648,143 +652,148 @@ solver_info_cb (void *cls, ph.current_result->valid = GNUNET_NO; if (NULL != ph.current_result) - { - /* Finalize result */ - ph.current_result->e_total = GNUNET_TIME_absolute_get (); - ph.current_result->d_total_full = GNUNET_TIME_absolute_get_difference ( + { + /* Finalize result */ + ph.current_result->e_total = GNUNET_TIME_absolute_get(); + ph.current_result->d_total_full = GNUNET_TIME_absolute_get_difference( ph.current_result->s_total, ph.current_result->e_total); - } + } ph.current_result = NULL; return; case GAS_OP_SOLVE_SETUP_START: GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_SETUP_START", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_SETUP_START", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result)) - { - GNUNET_break(0); - return; - } + { + GNUNET_break(0); + return; + } if (GAS_STAT_SUCCESS == stat) ph.current_result->valid = GNUNET_YES; else ph.current_result->valid = GNUNET_NO; - ph.current_result->s_setup = GNUNET_TIME_absolute_get (); + ph.current_result->s_setup = GNUNET_TIME_absolute_get(); return; case GAS_OP_SOLVE_SETUP_STOP: GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_SETUP_STOP", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_SETUP_STOP", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result)) - { - GNUNET_break(0); - return; - } + { + GNUNET_break(0); + return; + } if (GAS_STAT_SUCCESS == stat) ph.current_result->valid = GNUNET_YES; else ph.current_result->valid = GNUNET_NO; - ph.current_result->e_setup = GNUNET_TIME_absolute_get (); - ph.current_result->d_setup_full = GNUNET_TIME_absolute_get_difference ( - ph.current_result->s_setup, ph.current_result->e_setup); + ph.current_result->e_setup = GNUNET_TIME_absolute_get(); + ph.current_result->d_setup_full = GNUNET_TIME_absolute_get_difference( + ph.current_result->s_setup, ph.current_result->e_setup); return; case GAS_OP_SOLVE_MLP_LP_START: GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_LP_START", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_LP_START", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result)) - { - GNUNET_break(0); - return; - } + { + GNUNET_break(0); + return; + } if (GAS_STAT_SUCCESS == stat) ph.current_result->valid = GNUNET_YES; else ph.current_result->valid = GNUNET_NO; - ph.current_result->s_lp = GNUNET_TIME_absolute_get (); + ph.current_result->s_lp = GNUNET_TIME_absolute_get(); return; + case GAS_OP_SOLVE_MLP_LP_STOP: GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_LP_STOP", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_LP_STOP", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result)) - { - GNUNET_break(0); - return; - } + { + GNUNET_break(0); + return; + } if (GAS_STAT_SUCCESS == stat) ph.current_result->valid = GNUNET_YES; else ph.current_result->valid = GNUNET_NO; - ph.current_result->e_lp = GNUNET_TIME_absolute_get (); - ph.current_result->d_lp_full = GNUNET_TIME_absolute_get_difference ( - ph.current_result->s_lp, ph.current_result->e_lp); + ph.current_result->e_lp = GNUNET_TIME_absolute_get(); + ph.current_result->d_lp_full = GNUNET_TIME_absolute_get_difference( + ph.current_result->s_lp, ph.current_result->e_lp); return; case GAS_OP_SOLVE_MLP_MLP_START: GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_MLP_START", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_MLP_START", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result)) - { - GNUNET_break(0); - return; - } + { + GNUNET_break(0); + return; + } if (GAS_STAT_SUCCESS == stat) ph.current_result->valid = GNUNET_YES; else ph.current_result->valid = GNUNET_NO; - ph.current_result->s_mlp = GNUNET_TIME_absolute_get (); + ph.current_result->s_mlp = GNUNET_TIME_absolute_get(); return; + case GAS_OP_SOLVE_MLP_MLP_STOP: GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_MLP_STOP", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_MLP_STOP", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); if ((GNUNET_NO == ph.expecting_solution) || (NULL == ph.current_result)) - { - GNUNET_break(0); - return; - } + { + GNUNET_break(0); + return; + } if (GAS_STAT_SUCCESS == stat) ph.current_result->valid = GNUNET_YES; else ph.current_result->valid = GNUNET_NO; - ph.current_result->e_mlp = GNUNET_TIME_absolute_get (); - ph.current_result->d_mlp_full = GNUNET_TIME_absolute_get_difference ( - ph.current_result->s_mlp, ph.current_result->e_mlp); + ph.current_result->e_mlp = GNUNET_TIME_absolute_get(); + ph.current_result->d_mlp_full = GNUNET_TIME_absolute_get_difference( + ph.current_result->s_mlp, ph.current_result->e_mlp); return; + case GAS_OP_SOLVE_UPDATE_NOTIFICATION_START: GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_UPDATE_NOTIFICATION_START", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_UPDATE_NOTIFICATION_START", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); return; + case GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP: GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP", - (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); + "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP", + (GAS_STAT_SUCCESS == stat) ? "SUCCESS" : "FAIL"); if (GAS_STAT_SUCCESS != stat) - { - GNUNET_log(GNUNET_ERROR_TYPE_ERROR, - "Solver `%s' failed to update problem with %u peers and %u address!\n", - ph.ats_string, ph.current_p, ph.current_a); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Solver `%s' failed to update problem with %u peers and %u address!\n", + ph.ats_string, ph.current_p, ph.current_a); + } return; + default: break; } @@ -796,82 +805,82 @@ solver_info_cb (void *cls, * @param iteration the iteration to evaluate */ static void -evaluate (int iteration) +evaluate(int iteration) { struct Result *cur; int cp; - for (cp = ph.N_peers_start; cp <= ph.N_peers_end; cp ++) - { - cur = ph.iterations_results[ph.current_iteration-1].results_array[cp]; - if (0 == cp) - continue; - if (NULL == cur) + for (cp = ph.N_peers_start; cp <= ph.N_peers_end; cp++) { - GNUNET_break (0); - fprintf (stderr, - "Missing result for %u peers\n", cp); - continue; - } + cur = ph.iterations_results[ph.current_iteration - 1].results_array[cp]; + if (0 == cp) + continue; + if (NULL == cur) + { + GNUNET_break(0); + fprintf(stderr, + "Missing result for %u peers\n", cp); + continue; + } - if (GNUNET_NO == cur->valid) - { - fprintf (stderr, - "Total time to solve %s for %u peers %u addresses: %s\n", - (GNUNET_YES == cur->update) ? "updated" : "full", - cur->peers, cur->addresses, "Failed to solve!"); - continue; - } + if (GNUNET_NO == cur->valid) + { + fprintf(stderr, + "Total time to solve %s for %u peers %u addresses: %s\n", + (GNUNET_YES == cur->update) ? "updated" : "full", + cur->peers, cur->addresses, "Failed to solve!"); + continue; + } - if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us != cur->d_total_full.rel_value_us) - { - fprintf (stderr, - "Total time to solve %s for %u peers %u addresses: %llu us\n", - (GNUNET_YES == cur->update) ? "updated" : "full", - cur->peers, cur->addresses, - (unsigned long long) cur->d_total_full.rel_value_us); - } + if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us != cur->d_total_full.rel_value_us) + { + fprintf(stderr, + "Total time to solve %s for %u peers %u addresses: %llu us\n", + (GNUNET_YES == cur->update) ? "updated" : "full", + cur->peers, cur->addresses, + (unsigned long long)cur->d_total_full.rel_value_us); + } - if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us != cur->d_setup_full.rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Total time to setup %s %u peers %u addresses: %llu us\n", - (GNUNET_YES == cur->update) ? "updated" : "full", - cur->peers, cur->addresses, - (unsigned long long) cur->d_setup_full.rel_value_us); - } + if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us != cur->d_setup_full.rel_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Total time to setup %s %u peers %u addresses: %llu us\n", + (GNUNET_YES == cur->update) ? "updated" : "full", + cur->peers, cur->addresses, + (unsigned long long)cur->d_setup_full.rel_value_us); + } - if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us != cur->d_lp_full.rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Total time to solve %s LP for %u peers %u addresses: %llu us\n", - (GNUNET_YES == cur->update) ? "updated" : "full", - cur->peers, - cur->addresses, - (unsigned long long )cur->d_lp_full.rel_value_us); - } + if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us != cur->d_lp_full.rel_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Total time to solve %s LP for %u peers %u addresses: %llu us\n", + (GNUNET_YES == cur->update) ? "updated" : "full", + cur->peers, + cur->addresses, + (unsigned long long )cur->d_lp_full.rel_value_us); + } - if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us != cur->d_mlp_full.rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Total time to solve %s MLP for %u peers %u addresses: %llu us\n", - (GNUNET_YES == cur->update) ? "updated" : "full", - cur->peers, cur->addresses, - (unsigned long long )cur->d_mlp_full.rel_value_us); + if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us != cur->d_mlp_full.rel_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Total time to solve %s MLP for %u peers %u addresses: %llu us\n", + (GNUNET_YES == cur->update) ? "updated" : "full", + cur->peers, cur->addresses, + (unsigned long long )cur->d_mlp_full.rel_value_us); + } } - } } static unsigned int -get_connectivity_cb (void *cls, - const struct GNUNET_PeerIdentity *peer) +get_connectivity_cb(void *cls, + const struct GNUNET_PeerIdentity *peer) { - return GNUNET_CONTAINER_multipeermap_contains (ph.addresses, - peer); + return GNUNET_CONTAINER_multipeermap_contains(ph.addresses, + peer); } @@ -879,7 +888,7 @@ get_connectivity_cb (void *cls, * Evaluate average results for all iterations */ static void -write_all_iterations (void) +write_all_iterations(void) { int c_iteration; int c_peer; @@ -898,180 +907,179 @@ write_all_iterations (void) if (GNUNET_NO == ph.create_datafile) return; - GNUNET_asprintf (&data_fn_full, - "perf_%s_full_%u-%u_%u_%u.data", - ph.ats_string, - ph.total_iterations, - ph.N_peers_start, - ph.N_peers_end, - ph.N_address); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Using data file `%s'\n", - data_fn_full); - - f_full = GNUNET_DISK_file_open (data_fn_full, - GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); + GNUNET_asprintf(&data_fn_full, + "perf_%s_full_%u-%u_%u_%u.data", + ph.ats_string, + ph.total_iterations, + ph.N_peers_start, + ph.N_peers_end, + ph.N_address); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Using data file `%s'\n", + data_fn_full); + + f_full = GNUNET_DISK_file_open(data_fn_full, + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); if (NULL == f_full) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot open data file `%s'\n", - data_fn_full); - GNUNET_free (data_fn_full); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot open data file `%s'\n", + data_fn_full); + GNUNET_free(data_fn_full); + return; + } data = "#peers;addresses;time total in us;#time setup in us;#time lp in us;#time mlp in us;\n"; if (GNUNET_SYSERR == GNUNET_DISK_file_write(f_full, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot write data to log file `%s'\n", - data_fn_full); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot write data to log file `%s'\n", + data_fn_full); data_fn_update = NULL; if (GNUNET_YES == ph.measure_updates) - { - GNUNET_asprintf (&data_fn_update, "perf_%s_update_%u-%u_%u_%u.data", - ph.ats_string, - ph.total_iterations, - ph.N_peers_start, - ph.N_peers_end, - ph.N_address); - f_update = GNUNET_DISK_file_open (data_fn_update, - GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); - if (NULL == f_update) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot open gnuplot file `%s'\n", data_fn_update); - GNUNET_free (data_fn_update); - if (NULL != f_full) - GNUNET_DISK_file_close (f_full); - GNUNET_free (data_fn_full); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Using update data file `%s'\n", - data_fn_update); - - data = "#peers;addresses;time total in us;#time setup in us;#time lp in us;#time mlp in us;\n"; - if (GNUNET_SYSERR == GNUNET_DISK_file_write (f_update, data, strlen(data))) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot write data to log file `%s'\n", - data_fn_update); - } - - for (c_peer = ph.N_peers_start; c_peer <= ph.N_peers_end; c_peer ++) - { - char * data_str; - char * data_tmp; - char * data_upd_str; - char * data_upd_tmp; - GNUNET_asprintf(&data_str, "%u;%u",c_peer, ph.N_address); - if (ph.measure_updates) - GNUNET_asprintf(&data_upd_str, "%u;%u",c_peer, ph.N_address); - for (c_iteration = 0; c_iteration < ph.total_iterations; c_iteration ++) - { - struct Result *cur_full_res; - struct Result *cur_upd_res; - + GNUNET_asprintf(&data_fn_update, "perf_%s_update_%u-%u_%u_%u.data", + ph.ats_string, + ph.total_iterations, + ph.N_peers_start, + ph.N_peers_end, + ph.N_address); + f_update = GNUNET_DISK_file_open(data_fn_update, + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_EXEC | GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE); + if (NULL == f_update) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot open gnuplot file `%s'\n", data_fn_update); + GNUNET_free(data_fn_update); + if (NULL != f_full) + GNUNET_DISK_file_close(f_full); + GNUNET_free(data_fn_full); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Using update data file `%s'\n", + data_fn_update); - //fprintf (stderr, "P: %u I: %u == %p \n", c_peer, c_iteration, cur_res); - cur_full_res = ph.iterations_results[c_iteration].results_array[c_peer]; - if (c_peer == 0) - continue; - if (NULL == cur_full_res) - continue; + data = "#peers;addresses;time total in us;#time setup in us;#time lp in us;#time mlp in us;\n"; + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f_update, data, strlen(data))) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot write data to log file `%s'\n", + data_fn_update); + } + for (c_peer = ph.N_peers_start; c_peer <= ph.N_peers_end; c_peer++) + { + char * data_str; + char * data_tmp; + char * data_upd_str; + char * data_upd_tmp; + GNUNET_asprintf(&data_str, "%u;%u", c_peer, ph.N_address); if (ph.measure_updates) - { - cur_upd_res = ph.iterations_results[c_iteration].update_results_array[c_peer]; - data_upd_tmp = GNUNET_strdup (data_upd_str); - GNUNET_free (data_upd_str); - if (GNUNET_YES == cur_full_res->valid) + GNUNET_asprintf(&data_upd_str, "%u;%u", c_peer, ph.N_address); + for (c_iteration = 0; c_iteration < ph.total_iterations; c_iteration++) { - GNUNET_asprintf (&data_upd_str, "%s;%llu", data_upd_tmp, - (NULL == cur_upd_res) ? 0 : cur_upd_res->d_total_full.rel_value_us); + struct Result *cur_full_res; + struct Result *cur_upd_res; + + + + //fprintf (stderr, "P: %u I: %u == %p \n", c_peer, c_iteration, cur_res); + cur_full_res = ph.iterations_results[c_iteration].results_array[c_peer]; + if (c_peer == 0) + continue; + if (NULL == cur_full_res) + continue; + + if (ph.measure_updates) + { + cur_upd_res = ph.iterations_results[c_iteration].update_results_array[c_peer]; + data_upd_tmp = GNUNET_strdup(data_upd_str); + GNUNET_free(data_upd_str); + if (GNUNET_YES == cur_full_res->valid) + { + GNUNET_asprintf(&data_upd_str, "%s;%llu", data_upd_tmp, + (NULL == cur_upd_res) ? 0 : cur_upd_res->d_total_full.rel_value_us); + } + else + { + GNUNET_asprintf(&data_upd_str, "%s;", data_upd_tmp); + } + GNUNET_free(data_upd_tmp); + } + + //fprintf (stderr, "P: %u I: %u: P %i A %i\n", c_peer, c_iteration, cur_res->peers, cur_res->addresses); + //fprintf (stderr, "D total: %llu\n", (long long unsigned int) cur_res->d_total.rel_value_us); + + data_tmp = GNUNET_strdup(data_str); + GNUNET_free(data_str); + if (GNUNET_YES == cur_full_res->valid) + { + GNUNET_asprintf(&data_str, "%s;%llu", data_tmp, + cur_full_res->d_total_full.rel_value_us); + } + else + { + GNUNET_asprintf(&data_str, "%s;", data_tmp); + } + + GNUNET_free(data_tmp); } - else - { - GNUNET_asprintf (&data_upd_str, "%s;", data_upd_tmp); - } - GNUNET_free (data_upd_tmp); - - } - - //fprintf (stderr, "P: %u I: %u: P %i A %i\n", c_peer, c_iteration, cur_res->peers, cur_res->addresses); - //fprintf (stderr, "D total: %llu\n", (long long unsigned int) cur_res->d_total.rel_value_us); - - data_tmp = GNUNET_strdup (data_str); - GNUNET_free (data_str); - if (GNUNET_YES == cur_full_res->valid) - { - GNUNET_asprintf (&data_str, "%s;%llu", data_tmp, - cur_full_res->d_total_full.rel_value_us); - } - else - { - GNUNET_asprintf (&data_str, "%s;", data_tmp); - } + data_tmp = GNUNET_strdup(data_str); + GNUNET_free(data_str); + GNUNET_asprintf(&data_str, "%s\n", data_tmp); + GNUNET_free(data_tmp); - GNUNET_free (data_tmp); - } - data_tmp = GNUNET_strdup (data_str); - GNUNET_free (data_str); - GNUNET_asprintf (&data_str, "%s\n", data_tmp); - GNUNET_free (data_tmp); - - fprintf (stderr, "Result full solution: %s\n", data_str); - if (GNUNET_SYSERR == GNUNET_DISK_file_write (f_full, data_str, strlen(data_str))) - GNUNET_break (0); - GNUNET_free (data_str); + fprintf(stderr, "Result full solution: %s\n", data_str); + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f_full, data_str, strlen(data_str))) + GNUNET_break(0); + GNUNET_free(data_str); - if (ph.measure_updates) - { - data_upd_tmp = GNUNET_strdup (data_upd_str); - GNUNET_free (data_upd_str); - GNUNET_asprintf (&data_upd_str, "%s\n", data_upd_tmp); - GNUNET_free (data_upd_tmp); - - fprintf (stderr, "Result updated solution: `%s'\n", data_upd_str); - if (GNUNET_SYSERR == GNUNET_DISK_file_write (f_update, data_upd_str, strlen(data_upd_str))) - GNUNET_break (0); - GNUNET_free (data_upd_str); + if (ph.measure_updates) + { + data_upd_tmp = GNUNET_strdup(data_upd_str); + GNUNET_free(data_upd_str); + GNUNET_asprintf(&data_upd_str, "%s\n", data_upd_tmp); + GNUNET_free(data_upd_tmp); + + fprintf(stderr, "Result updated solution: `%s'\n", data_upd_str); + if (GNUNET_SYSERR == GNUNET_DISK_file_write(f_update, data_upd_str, strlen(data_upd_str))) + GNUNET_break(0); + GNUNET_free(data_upd_str); + } } - } - if ((NULL != f_full) && (GNUNET_SYSERR == GNUNET_DISK_file_close (f_full))) + if ((NULL != f_full) && (GNUNET_SYSERR == GNUNET_DISK_file_close(f_full))) GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot close log file `%s'\n", - data_fn_full); - GNUNET_free_non_null (data_fn_full); + data_fn_full); + GNUNET_free_non_null(data_fn_full); - if ((NULL != f_update) && (GNUNET_SYSERR == GNUNET_DISK_file_close (f_update))) + if ((NULL != f_update) && (GNUNET_SYSERR == GNUNET_DISK_file_close(f_update))) GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot close log file `%s'\n", - data_fn_update); - GNUNET_free_non_null (data_fn_update); + data_fn_update); + GNUNET_free_non_null(data_fn_update); } static int -do_delete_address (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *value) +do_delete_address(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *value) { struct ATS_Address *cur = value; GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Deleting addresses for peer %u\n", pid); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_remove (ph.addresses, - pid, - cur)); - ph.sf->s_del (ph.sf->cls, cur); - GNUNET_free_non_null (cur->atsi); - GNUNET_free (cur); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_remove(ph.addresses, + pid, + cur)); + ph.sf->s_del(ph.sf->cls, cur); + GNUNET_free_non_null(cur->atsi); + GNUNET_free(cur); return GNUNET_OK; } @@ -1080,7 +1088,7 @@ do_delete_address (void *cls, * Run a performance iteration */ static void -perf_run_iteration (void) +perf_run_iteration(void) { int cp; int ca; @@ -1089,125 +1097,125 @@ perf_run_iteration (void) struct ATS_Address * cur_addr; uint32_t net; - ph.iterations_results[ph.current_iteration-1].results_array = GNUNET_malloc ((count_p + 1) * sizeof (struct Result *)); + ph.iterations_results[ph.current_iteration - 1].results_array = GNUNET_malloc((count_p + 1) * sizeof(struct Result *)); if (ph.measure_updates) - ph.iterations_results[ph.current_iteration-1].update_results_array = GNUNET_malloc ((count_p + 1) * sizeof (struct Result *)); - ph.peers = GNUNET_malloc ((count_p) * sizeof (struct PerfPeer)); + ph.iterations_results[ph.current_iteration - 1].update_results_array = GNUNET_malloc((count_p + 1) * sizeof(struct Result *)); + ph.peers = GNUNET_malloc((count_p) * sizeof(struct PerfPeer)); for (cp = 0; cp < count_p; cp++) - perf_create_peer (cp); + perf_create_peer(cp); GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Iteration %u of %u, added %u peers\n", ph.current_iteration, ph.total_iterations, cp); + "Iteration %u of %u, added %u peers\n", ph.current_iteration, ph.total_iterations, cp); for (cp = 0; cp < count_p; cp++) - { - fprintf (stderr,"%u..", cp); - if (GNUNET_NO == ph.bulk_running) - { - ph.bulk_running = GNUNET_YES; - ph.sf->s_bulk_start (ph.sf->cls); - } - ph.current_p = cp + 1; - for (ca = 0; ca < count_a; ca++) - { - cur_addr = perf_create_address (cp, ca); - /* Add address */ - - /* Random network selection */ - //net = 1 + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, GNUNET_NT_COUNT - 1); - /* Random equally distributed network selection */ - net = 1 + (ca % (GNUNET_NT_COUNT - 1)); - /* fprintf (stderr, "Network: %u `%s'\n", - * mod_net , GNUNET_NT_to_string(mod_net)); */ - - cur_addr->atsi = GNUNET_new (struct GNUNET_ATS_Information); - cur_addr->atsi_count = 1; - cur_addr->atsi[0].type = htonl (GNUNET_ATS_NETWORK_TYPE); - cur_addr->atsi[0].value = htonl (net); - ph.sf->s_add (ph.sf->cls, cur_addr, net); - - ph.current_a = ca + 1; - perf_address_initial_update (NULL, ph.addresses, cur_addr); - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Adding address for peer %u address %u in network %s\n", cp, ca, - GNUNET_NT_to_string(net)); - } - /* Notify solver about request */ - ph.sf->s_get (ph.sf->cls, &ph.peers[cp].id); - - if (cp + 1 >= ph.N_peers_start) { - /* Disable bulk to solve the problem */ - if (GNUNET_YES == ph.bulk_running) - { - ph.expecting_solution = GNUNET_YES; - ph.bulk_running = GNUNET_NO; - ph.sf->s_bulk_stop (ph.sf->cls); - } - else - GNUNET_break (0); - - /* Problem is solved by the solver here due to unlocking */ - ph.expecting_solution = GNUNET_NO; - - /* Update the problem */ - if ((0 < ph.opt_update_percent) && (GNUNET_YES == ph.measure_updates)) - { - /* Update */ - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Updating problem with %u peers and %u addresses\n", cp + 1, ca); - - ph.expecting_solution = GNUNET_YES; - ph.performed_update = GNUNET_YES; - if (GNUNET_NO == ph.bulk_running) + fprintf(stderr, "%u..", cp); + if (GNUNET_NO == ph.bulk_running) { ph.bulk_running = GNUNET_YES; - ph.sf->s_bulk_start (ph.sf->cls); + ph.sf->s_bulk_start(ph.sf->cls); + } + ph.current_p = cp + 1; + for (ca = 0; ca < count_a; ca++) + { + cur_addr = perf_create_address(cp, ca); + /* Add address */ + + /* Random network selection */ + //net = 1 + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, GNUNET_NT_COUNT - 1); + /* Random equally distributed network selection */ + net = 1 + (ca % (GNUNET_NT_COUNT - 1)); + /* fprintf (stderr, "Network: %u `%s'\n", + * mod_net , GNUNET_NT_to_string(mod_net)); */ + + cur_addr->atsi = GNUNET_new(struct GNUNET_ATS_Information); + cur_addr->atsi_count = 1; + cur_addr->atsi[0].type = htonl(GNUNET_ATS_NETWORK_TYPE); + cur_addr->atsi[0].value = htonl(net); + ph.sf->s_add(ph.sf->cls, cur_addr, net); + + ph.current_a = ca + 1; + perf_address_initial_update(NULL, ph.addresses, cur_addr); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Adding address for peer %u address %u in network %s\n", cp, ca, + GNUNET_NT_to_string(net)); + } + /* Notify solver about request */ + ph.sf->s_get(ph.sf->cls, &ph.peers[cp].id); + + if (cp + 1 >= ph.N_peers_start) + { + /* Disable bulk to solve the problem */ + if (GNUNET_YES == ph.bulk_running) + { + ph.expecting_solution = GNUNET_YES; + ph.bulk_running = GNUNET_NO; + ph.sf->s_bulk_stop(ph.sf->cls); + } + else + GNUNET_break(0); + + /* Problem is solved by the solver here due to unlocking */ + ph.expecting_solution = GNUNET_NO; + + /* Update the problem */ + if ((0 < ph.opt_update_percent) && (GNUNET_YES == ph.measure_updates)) + { + /* Update */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Updating problem with %u peers and %u addresses\n", cp + 1, ca); + + ph.expecting_solution = GNUNET_YES; + ph.performed_update = GNUNET_YES; + if (GNUNET_NO == ph.bulk_running) + { + ph.bulk_running = GNUNET_YES; + ph.sf->s_bulk_start(ph.sf->cls); + } + perf_update_all_addresses(cp + 1, ca, ph.opt_update_percent); + ph.bulk_running = GNUNET_NO; + ph.sf->s_bulk_stop(ph.sf->cls); + /* Problem is solved by the solver here due to unlocking */ + ph.performed_update = GNUNET_NO; + ph.expecting_solution = GNUNET_NO; + } + GNUNET_assert(GNUNET_NO == ph.bulk_running); } - perf_update_all_addresses (cp + 1, ca, ph.opt_update_percent); - ph.bulk_running = GNUNET_NO; - ph.sf->s_bulk_stop (ph.sf->cls); - /* Problem is solved by the solver here due to unlocking */ - ph.performed_update = GNUNET_NO; - ph.expecting_solution = GNUNET_NO; - } - GNUNET_assert (GNUNET_NO == ph.bulk_running); } - } - fprintf (stderr,"\n"); + fprintf(stderr, "\n"); GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Done, cleaning up addresses\n"); + "Done, cleaning up addresses\n"); if (GNUNET_NO == ph.bulk_running) - { - ph.sf->s_bulk_start (ph.sf->cls); - ph.bulk_running = GNUNET_YES; - } + { + ph.sf->s_bulk_start(ph.sf->cls); + ph.bulk_running = GNUNET_YES; + } for (cp = 0; cp < count_p; cp++) - { - GNUNET_CONTAINER_multipeermap_get_multiple (ph.addresses, - &ph.peers[cp].id, - &do_delete_address, - NULL); - } + { + GNUNET_CONTAINER_multipeermap_get_multiple(ph.addresses, + &ph.peers[cp].id, + &do_delete_address, + NULL); + } if (GNUNET_NO == ph.bulk_running) - { - ph.sf->s_bulk_stop (ph.sf->cls); - ph.bulk_running = GNUNET_NO; - } + { + ph.sf->s_bulk_stop(ph.sf->cls); + ph.bulk_running = GNUNET_NO; + } GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Iteration done\n"); + "Iteration done\n"); GNUNET_free(ph.peers); } static void -run (void *cls, char * const *args, const char *cfgfile, +run(void *cls, char * const *args, const char *cfgfile, const struct GNUNET_CONFIGURATION_Handle *cfg) { - GNUNET_log_setup ("perf-ats-solver", "WARNING", NULL); + GNUNET_log_setup("perf-ats-solver", "WARNING", NULL); char *sep; - char *src_filename = GNUNET_strdup (__FILE__); + char *src_filename = GNUNET_strdup(__FILE__); char *test_filename = cls; char *solver; char *plugin; @@ -1218,92 +1226,92 @@ run (void *cls, char * const *args, const char *cfgfile, int c2; /* Extract test name */ - if (NULL == (sep = (strstr (src_filename,".c")))) - { - GNUNET_free (src_filename); - GNUNET_break (0); - ret = 1; - return ; - } + if (NULL == (sep = (strstr(src_filename, ".c")))) + { + GNUNET_free(src_filename); + GNUNET_break(0); + ret = 1; + return; + } sep[0] = '\0'; - if (NULL != (sep = strstr (test_filename, ".exe"))) + if (NULL != (sep = strstr(test_filename, ".exe"))) sep[0] = '\0'; - if (NULL == (solver = strstr (test_filename, src_filename))) - { - GNUNET_free (src_filename); - GNUNET_break (0); - ret = 1; - return ; - } - solver += strlen (src_filename) +1; + if (NULL == (solver = strstr(test_filename, src_filename))) + { + GNUNET_free(src_filename); + GNUNET_break(0); + ret = 1; + return; + } + solver += strlen(src_filename) + 1; if (0 == strcmp(solver, "proportional")) - { - ph.ats_string = "proportional"; - } + { + ph.ats_string = "proportional"; + } else if (0 == strcmp(solver, "mlp")) - { - ph.ats_string = "mlp"; - } + { + ph.ats_string = "mlp"; + } else if ((0 == strcmp(solver, "ril"))) - { - ph.ats_string = "ril"; - } + { + ph.ats_string = "ril"; + } else - { - GNUNET_free (src_filename); - GNUNET_break (0); - ret = 1; - return ; - } - GNUNET_free (src_filename); + { + GNUNET_free(src_filename); + GNUNET_break(0); + ret = 1; + return; + } + GNUNET_free(src_filename); /* Calculcate peers */ if ((0 == ph.N_peers_start) && (0 == ph.N_peers_end)) - { - ph.N_peers_start = DEFAULT_PEERS_START; - ph.N_peers_end = DEFAULT_PEERS_END; - } + { + ph.N_peers_start = DEFAULT_PEERS_START; + ph.N_peers_end = DEFAULT_PEERS_END; + } if (0 == ph.N_address) ph.N_address = DEFAULT_ADDRESSES; if (ph.N_peers_start != ph.N_peers_end) - fprintf (stderr, "Benchmarking solver `%s' with %u to %u peers and %u addresses in %u iterations\n", - ph.ats_string, ph.N_peers_start, ph.N_peers_end, ph.N_address, ph.total_iterations); + fprintf(stderr, "Benchmarking solver `%s' with %u to %u peers and %u addresses in %u iterations\n", + ph.ats_string, ph.N_peers_start, ph.N_peers_end, ph.N_address, ph.total_iterations); else - fprintf (stderr, "Benchmarking solver `%s' with %u peers and %u addresses in %u iterations\n", - ph.ats_string, ph.N_peers_end, ph.N_address, ph.total_iterations); + fprintf(stderr, "Benchmarking solver `%s' with %u peers and %u addresses in %u iterations\n", + ph.ats_string, ph.N_peers_end, ph.N_address, ph.total_iterations); if (0 == ph.opt_update_percent) ph.opt_update_percent = DEFAULT_UPDATE_PERCENTAGE; /* Load quotas */ solver_cfg = GNUNET_CONFIGURATION_create(); - if ((NULL == solver_cfg) || (GNUNET_SYSERR == (GNUNET_CONFIGURATION_load ( solver_cfg, "perf_ats_solver.conf")))) - { - GNUNET_break(0); - end_now (1); - return; - } - if (GNUNET_NT_COUNT != load_quotas (solver_cfg, - quotas_out, quotas_in, GNUNET_NT_COUNT)) - { - GNUNET_break(0); - end_now (1); - return; - } + if ((NULL == solver_cfg) || (GNUNET_SYSERR == (GNUNET_CONFIGURATION_load(solver_cfg, "perf_ats_solver.conf")))) + { + GNUNET_break(0); + end_now(1); + return; + } + if (GNUNET_NT_COUNT != load_quotas(solver_cfg, + quotas_out, quotas_in, GNUNET_NT_COUNT)) + { + GNUNET_break(0); + end_now(1); + return; + } /* Create array of DLL to store results for iterations */ - ph.iterations_results = GNUNET_malloc (sizeof (struct Iteration) * ph.total_iterations); + ph.iterations_results = GNUNET_malloc(sizeof(struct Iteration) * ph.total_iterations); /* Load solver */ ph.env.cfg = solver_cfg; - ph.stat = GNUNET_STATISTICS_create ("ats", cfg); + ph.stat = GNUNET_STATISTICS_create("ats", cfg); ph.env.stats = ph.stat; - ph.addresses = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO); + ph.addresses = GNUNET_CONTAINER_multipeermap_create(128, GNUNET_NO); ph.env.addresses = ph.addresses; ph.env.bandwidth_changed_cb = bandwidth_changed_cb; ph.env.get_connectivity = &get_connectivity_cb; @@ -1312,75 +1320,75 @@ run (void *cls, char * const *args, const char *cfgfile, ph.env.info_cb = &solver_info_cb; for (c = 0; c < GNUNET_NT_COUNT; c++) - { - ph.env.out_quota[c] = quotas_out[c]; - ph.env.in_quota[c] = quotas_in[c]; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Loading network quotas: `%s' %llu %llu \n", - GNUNET_NT_to_string (c), - ph.env.out_quota[c], - ph.env.in_quota[c]); - } - GAS_normalization_start (); - GAS_preference_init (); - - GNUNET_asprintf (&plugin, - "libgnunet_plugin_ats_%s", - ph.ats_string); + { + ph.env.out_quota[c] = quotas_out[c]; + ph.env.in_quota[c] = quotas_in[c]; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Loading network quotas: `%s' %llu %llu \n", + GNUNET_NT_to_string(c), + ph.env.out_quota[c], + ph.env.in_quota[c]); + } + GAS_normalization_start(); + GAS_preference_init(); + + GNUNET_asprintf(&plugin, + "libgnunet_plugin_ats_%s", + ph.ats_string); GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Initializing solver `%s'\n"), ph.ats_string); - if (NULL == (ph.sf = GNUNET_PLUGIN_load (plugin, &ph.env))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to initialize solver `%s'!\n"), - plugin); - ret = 1; - return; - } + if (NULL == (ph.sf = GNUNET_PLUGIN_load(plugin, &ph.env))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to initialize solver `%s'!\n"), + plugin); + ret = 1; + return; + } /* Do the benchmark */ for (ph.current_iteration = 1; ph.current_iteration <= ph.total_iterations; ph.current_iteration++) - { - fprintf (stderr, - "Iteration %u of %u starting\n", - ph.current_iteration, - ph.total_iterations); - perf_run_iteration (); - evaluate (ph.current_iteration); - fprintf (stderr, - "Iteration %u of %u done\n", - ph.current_iteration, - ph.total_iterations); - } + { + fprintf(stderr, + "Iteration %u of %u starting\n", + ph.current_iteration, + ph.total_iterations); + perf_run_iteration(); + evaluate(ph.current_iteration); + fprintf(stderr, + "Iteration %u of %u done\n", + ph.current_iteration, + ph.total_iterations); + } if (ph.create_datafile) - write_all_iterations (); + write_all_iterations(); /* Unload solver*/ GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Unloading solver `%s'\n"), ph.ats_string); - GNUNET_PLUGIN_unload (plugin, ph.sf); + GNUNET_PLUGIN_unload(plugin, ph.sf); ph.sf = NULL; - GNUNET_free (plugin); - for (c = 0; c < ph.total_iterations; c++ ) - { - for (c2 = ph.N_peers_start; c2 < ph.N_peers_end; c2++ ) + GNUNET_free(plugin); + for (c = 0; c < ph.total_iterations; c++) { - if (0 == c2) - continue; + for (c2 = ph.N_peers_start; c2 < ph.N_peers_end; c2++) + { + if (0 == c2) + continue; + if (ph.measure_updates) + GNUNET_free_non_null(ph.iterations_results[c].update_results_array[c2]); + GNUNET_free(ph.iterations_results[c].results_array[c2]); + } if (ph.measure_updates) - GNUNET_free_non_null (ph.iterations_results[c].update_results_array[c2]); - GNUNET_free (ph.iterations_results[c].results_array[c2]); + GNUNET_free(ph.iterations_results[c].update_results_array); + GNUNET_free(ph.iterations_results[c].results_array); } - if (ph.measure_updates) - GNUNET_free (ph.iterations_results[c].update_results_array); - GNUNET_free(ph.iterations_results[c].results_array); - } - GNUNET_free (ph.iterations_results); - - GNUNET_CONFIGURATION_destroy (solver_cfg); - GNUNET_STATISTICS_destroy (ph.stat, GNUNET_NO); + GNUNET_free(ph.iterations_results); + + GNUNET_CONFIGURATION_destroy(solver_cfg); + GNUNET_STATISTICS_destroy(ph.stat, GNUNET_NO); } @@ -1391,7 +1399,7 @@ run (void *cls, char * const *args, const char *cfgfile, * @param argv argument values */ int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { /* extract command line arguments */ ph.opt_update_percent = 0; @@ -1404,46 +1412,45 @@ main (int argc, char *argv[]) ph.total_iterations = 1; static struct GNUNET_GETOPT_CommandLineOption options[] = { - - GNUNET_GETOPT_option_uint ('a', - "addresses", - gettext_noop ("addresses to use"), - &ph.N_address), - - GNUNET_GETOPT_option_uint ('s', - "start", - gettext_noop ("start with peer"), - &ph.N_peers_start), - - GNUNET_GETOPT_option_uint ('e', - "end", - gettext_noop ("end with peer"), - &ph.N_peers_end), - - GNUNET_GETOPT_option_uint ('i', - "iterations", - gettext_noop ("number of iterations used for averaging (default: 1)"), - &ph.total_iterations), - - GNUNET_GETOPT_option_uint ('p', - "percentage", - gettext_noop ("update a fix percentage of addresses"), - &ph.opt_update_percent), - - GNUNET_GETOPT_option_flag ('d', - "data", - gettext_noop ("create data file"), - &ph.create_datafile), - - GNUNET_GETOPT_option_flag ('u', - "update", - gettext_noop ("measure updates"), - &ph.measure_updates), - - GNUNET_GETOPT_OPTION_END + GNUNET_GETOPT_option_uint('a', + "addresses", + gettext_noop("addresses to use"), + &ph.N_address), + + GNUNET_GETOPT_option_uint('s', + "start", + gettext_noop("start with peer"), + &ph.N_peers_start), + + GNUNET_GETOPT_option_uint('e', + "end", + gettext_noop("end with peer"), + &ph.N_peers_end), + + GNUNET_GETOPT_option_uint('i', + "iterations", + gettext_noop("number of iterations used for averaging (default: 1)"), + &ph.total_iterations), + + GNUNET_GETOPT_option_uint('p', + "percentage", + gettext_noop("update a fix percentage of addresses"), + &ph.opt_update_percent), + + GNUNET_GETOPT_option_flag('d', + "data", + gettext_noop("create data file"), + &ph.create_datafile), + + GNUNET_GETOPT_option_flag('u', + "update", + gettext_noop("measure updates"), + &ph.measure_updates), + + GNUNET_GETOPT_OPTION_END }; - GNUNET_PROGRAM_run (argc, argv, argv[0], NULL, options, &run, argv[0]); + GNUNET_PROGRAM_run(argc, argv, argv[0], NULL, options, &run, argv[0]); return ret; } diff --git a/src/ats/plugin_ats2_common.c b/src/ats/plugin_ats2_common.c index faa2f0edf..c12d2a06f 100644 --- a/src/ats/plugin_ats2_common.c +++ b/src/ats/plugin_ats2_common.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2011-2015, 2018 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2011-2015, 2018 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -40,59 +40,59 @@ * @param quota[out] set to quota, #DEFAULT_BANDWIDTH if @a cfg does not say anything useful */ static void -get_quota (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *nts, - const char *direction, - unsigned long long *quota) +get_quota(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *nts, + const char *direction, + unsigned long long *quota) { char *quota_str; char *quota_s; int res; - GNUNET_asprintf ("a_s, - "%s_QUOTA_%s", - nts, - direction); + GNUNET_asprintf("a_s, + "%s_QUOTA_%s", + nts, + direction); if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "ATS", - quota_s, - "a_str)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING, - "ATS", - quota_s); - GNUNET_free (quota_s); - return; - } - GNUNET_free (quota_s); + GNUNET_CONFIGURATION_get_value_string(cfg, + "ATS", + quota_s, + "a_str)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_WARNING, + "ATS", + quota_s); + GNUNET_free(quota_s); + return; + } + GNUNET_free(quota_s); res = GNUNET_NO; - if (0 == strcmp (quota_str, - "unlimited")) - { - *quota = ULONG_MAX; + if (0 == strcmp(quota_str, + "unlimited")) + { + *quota = ULONG_MAX; + res = GNUNET_YES; + } + if ((GNUNET_NO == res) && + (GNUNET_OK == + GNUNET_STRINGS_fancy_size_to_bytes(quota_str, + quota))) res = GNUNET_YES; - } - if ( (GNUNET_NO == res) && - (GNUNET_OK == - GNUNET_STRINGS_fancy_size_to_bytes (quota_str, - quota)) ) - res = GNUNET_YES; - if ( (GNUNET_NO == res) && - (1 == - sscanf (quota_str, - "%llu", - quota)) ) + if ((GNUNET_NO == res) && + (1 == + sscanf(quota_str, + "%llu", + quota))) res = GNUNET_YES; if (GNUNET_NO == res) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Could not load %s quota for network `%s': `%s', assigning default bandwidth %llu\n"), - direction, - nts, - quota_str, - (unsigned long long) DEFAULT_BANDWIDTH); - *quota = DEFAULT_BANDWIDTH; - } - GNUNET_free (quota_str); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Could not load %s quota for network `%s': `%s', assigning default bandwidth %llu\n"), + direction, + nts, + quota_str, + (unsigned long long)DEFAULT_BANDWIDTH); + *quota = DEFAULT_BANDWIDTH; + } + GNUNET_free(quota_str); } diff --git a/src/ats/plugin_ats2_simple.c b/src/ats/plugin_ats2_simple.c index 14bd2b99d..90566c561 100644 --- a/src/ats/plugin_ats2_simple.c +++ b/src/ats/plugin_ats2_simple.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2011-2015, 2018 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2011-2015, 2018 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -31,7 +31,7 @@ #include "gnunet_hello_lib.h" #include "gnunet_peerstore_service.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "ats-simple", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "ats-simple", __VA_ARGS__) /** @@ -68,9 +68,7 @@ struct Peer; /** * Entry in list of addresses we could try per peer. */ -struct Hello -{ - +struct Hello { /** * Kept in a DLL. */ @@ -123,9 +121,7 @@ struct Hello * Internal representation of a session by the plugin. * (If desired, plugin may just use NULL.) */ -struct GNUNET_ATS_SessionHandle -{ - +struct GNUNET_ATS_SessionHandle { /** * Kept in DLL per peer. */ @@ -193,9 +189,7 @@ struct GNUNET_ATS_SessionHandle * Information about preferences and sessions we track * per peer. */ -struct Peer -{ - +struct Peer { /** * Kept in DLL per peer. */ @@ -253,9 +247,7 @@ struct Peer /** * Representation of a network (to be expanded...) */ -struct Network -{ - +struct Network { /** * Total inbound quota */ @@ -276,9 +268,7 @@ struct Network /** * A handle for the proportional solver */ -struct SimpleHandle -{ - +struct SimpleHandle { /** * Our execution environment. */ @@ -316,9 +306,9 @@ struct SimpleHandle * @return NULL for not found */ struct Peer * -lookup_peer (struct SimpleHandle *h, const struct GNUNET_PeerIdentity *pid) +lookup_peer(struct SimpleHandle *h, const struct GNUNET_PeerIdentity *pid) { - return GNUNET_CONTAINER_multipeermap_get (h->peers, pid); + return GNUNET_CONTAINER_multipeermap_get(h->peers, pid); } @@ -330,7 +320,7 @@ lookup_peer (struct SimpleHandle *h, const struct GNUNET_PeerIdentity *pid) * @return #GNUNET_YES if no information is left in @a p */ static int -peer_test_dead (struct Peer *p) +peer_test_dead(struct Peer *p) { for (enum GNUNET_MQ_PreferenceKind pk = 0; pk < GNUNET_MQ_PREFERENCE_COUNT; pk++) @@ -350,17 +340,17 @@ peer_test_dead (struct Peer *p) * @param hello[in,out] address suggestion to make */ static void -suggest_hello (struct Hello *hello) +suggest_hello(struct Hello *hello) { struct Peer *p = hello->peer; struct SimpleHandle *h = p->h; - p->last_suggestion = hello->last_attempt = GNUNET_TIME_absolute_get (); + p->last_suggestion = hello->last_attempt = GNUNET_TIME_absolute_get(); hello->backoff = - GNUNET_TIME_randomized_backoff (hello->backoff, - GNUNET_TIME_absolute_get_remaining ( - hello->expiration)); - h->env->suggest_cb (h->env->cls, &p->pid, hello->address); + GNUNET_TIME_randomized_backoff(hello->backoff, + GNUNET_TIME_absolute_get_remaining( + hello->expiration)); + h->env->suggest_cb(h->env->cls, &p->pid, hello->address); } @@ -379,7 +369,7 @@ suggest_hello (struct Hello *hello) * @param cls a `struct Peer` */ static void -suggest_start_cb (void *cls) +suggest_start_cb(void *cls) { struct Peer *p = cls; struct GNUNET_TIME_Relative delay = GNUNET_TIME_UNIT_ZERO; @@ -397,63 +387,63 @@ suggest_start_cb (void *cls) /* calculate square of number of sessions */ num_sessions++; /* start with 1, even if we have zero sessions */ if (num_sessions < UINT16_MAX) - sq = num_sessions * (uint32_t) num_sessions; + sq = num_sessions * (uint32_t)num_sessions; else sq = UINT32_MAX; xdelay = - GNUNET_TIME_randomized_backoff (GNUNET_TIME_relative_multiply (SUGGEST_FREQ, - sq), - GNUNET_TIME_UNIT_FOREVER_REL); - xnext = GNUNET_TIME_relative_to_absolute (xdelay); + GNUNET_TIME_randomized_backoff(GNUNET_TIME_relative_multiply(SUGGEST_FREQ, + sq), + GNUNET_TIME_UNIT_FOREVER_REL); + xnext = GNUNET_TIME_relative_to_absolute(xdelay); p->task = NULL; while (0 == delay.rel_value_us) - { - struct Hello *next; - struct GNUNET_TIME_Absolute xmax; - - if (NULL != hello) - { - /* We went through the loop already once and found - a HELLO that is due *now*, so make a suggestion! */ - GNUNET_break (NULL == hello->sh); - suggest_hello (hello); - hello = NULL; - hpt = GNUNET_TIME_UNIT_FOREVER_ABS; - } - for (struct Hello *pos = p->h_head; NULL != pos; pos = next) { - struct GNUNET_TIME_Absolute pt; - - next = pos->next; - if (NULL != pos->sh) - continue; - if (0 == - GNUNET_TIME_absolute_get_remaining (pos->expiration).rel_value_us) - { - /* expired, remove! */ - GNUNET_CONTAINER_DLL_remove (p->h_head, p->h_tail, pos); - GNUNET_free (pos); - continue; - } - pt = GNUNET_TIME_absolute_add (pos->last_attempt, pos->backoff); - if ((NULL == hello) || (pt.abs_value_us < hpt.abs_value_us)) - { - hello = pos; - hpt = pt; - } + struct Hello *next; + struct GNUNET_TIME_Absolute xmax; + + if (NULL != hello) + { + /* We went through the loop already once and found + a HELLO that is due *now*, so make a suggestion! */ + GNUNET_break(NULL == hello->sh); + suggest_hello(hello); + hello = NULL; + hpt = GNUNET_TIME_UNIT_FOREVER_ABS; + } + for (struct Hello *pos = p->h_head; NULL != pos; pos = next) + { + struct GNUNET_TIME_Absolute pt; + + next = pos->next; + if (NULL != pos->sh) + continue; + if (0 == + GNUNET_TIME_absolute_get_remaining(pos->expiration).rel_value_us) + { + /* expired, remove! */ + GNUNET_CONTAINER_DLL_remove(p->h_head, p->h_tail, pos); + GNUNET_free(pos); + continue; + } + pt = GNUNET_TIME_absolute_add(pos->last_attempt, pos->backoff); + if ((NULL == hello) || (pt.abs_value_us < hpt.abs_value_us)) + { + hello = pos; + hpt = pt; + } + } + if (NULL == hello) + return; /* no HELLOs that could still be tried */ + + /* hpt is now the *earliest* possible time for any HELLO + but we might not want to go for as early as possible for + this peer. So the actual time is the max of the earliest + HELLO and the 'xnext' */ + xmax = GNUNET_TIME_absolute_max(hpt, xnext); + delay = GNUNET_TIME_absolute_get_remaining(xmax); } - if (NULL == hello) - return; /* no HELLOs that could still be tried */ - - /* hpt is now the *earliest* possible time for any HELLO - but we might not want to go for as early as possible for - this peer. So the actual time is the max of the earliest - HELLO and the 'xnext' */ - xmax = GNUNET_TIME_absolute_max (hpt, xnext); - delay = GNUNET_TIME_absolute_get_remaining (xmax); - } - p->task = GNUNET_SCHEDULER_add_delayed (delay, &suggest_start_cb, p); + p->task = GNUNET_SCHEDULER_add_delayed(delay, &suggest_start_cb, p); } @@ -465,9 +455,9 @@ suggest_start_cb (void *cls) * @param emsg error message, or NULL if no errors */ static void -watch_cb (void *cls, - const struct GNUNET_PEERSTORE_Record *record, - const char *emsg) +watch_cb(void *cls, + const struct GNUNET_PEERSTORE_Record *record, + const char *emsg) { struct Peer *p = cls; char *addr; @@ -476,65 +466,65 @@ watch_cb (void *cls, struct GNUNET_TIME_Absolute expiration; struct Hello *hello; - if (0 != GNUNET_memcmp (&p->pid, &record->peer)) - { - GNUNET_break (0); - return; - } - if (0 != strcmp (record->key, GNUNET_PEERSTORE_TRANSPORT_URLADDRESS_KEY)) - { - GNUNET_break (0); - return; - } - addr = GNUNET_HELLO_extract_address (record->value, - record->value_size, - &p->pid, - &nt, - &expiration); + if (0 != GNUNET_memcmp(&p->pid, &record->peer)) + { + GNUNET_break(0); + return; + } + if (0 != strcmp(record->key, GNUNET_PEERSTORE_TRANSPORT_URLADDRESS_KEY)) + { + GNUNET_break(0); + return; + } + addr = GNUNET_HELLO_extract_address(record->value, + record->value_size, + &p->pid, + &nt, + &expiration); if (NULL == addr) return; /* invalid hello, bad signature, other problem */ - if (0 == GNUNET_TIME_absolute_get_remaining (expiration).rel_value_us) - { - /* expired, ignore */ - GNUNET_free (addr); - return; - } + if (0 == GNUNET_TIME_absolute_get_remaining(expiration).rel_value_us) + { + /* expired, ignore */ + GNUNET_free(addr); + return; + } /* check if addr is already known */ for (struct Hello *he = p->h_head; NULL != he; he = he->next) - { - if (0 != strcmp (he->address, addr)) - continue; - if (he->expiration.abs_value_us < expiration.abs_value_us) { - he->expiration = expiration; - he->nt = nt; + if (0 != strcmp(he->address, addr)) + continue; + if (he->expiration.abs_value_us < expiration.abs_value_us) + { + he->expiration = expiration; + he->nt = nt; + } + GNUNET_free(addr); + return; } - GNUNET_free (addr); - return; - } /* create new HELLO */ - alen = strlen (addr) + 1; - hello = GNUNET_malloc (sizeof (struct Hello) + alen); - hello->address = (const char *) &hello[1]; + alen = strlen(addr) + 1; + hello = GNUNET_malloc(sizeof(struct Hello) + alen); + hello->address = (const char *)&hello[1]; hello->expiration = expiration; hello->nt = nt; hello->peer = p; - memcpy (&hello[1], addr, alen); - GNUNET_CONTAINER_DLL_insert (p->h_head, p->h_tail, hello); + memcpy(&hello[1], addr, alen); + GNUNET_CONTAINER_DLL_insert(p->h_head, p->h_tail, hello); /* check if sh for this HELLO already exists */ for (struct GNUNET_ATS_SessionHandle *sh = p->sh_head; NULL != sh; sh = sh->next) - { - if ((NULL == sh->address) || (0 != strcmp (sh->address, addr))) - continue; - GNUNET_assert (NULL == sh->hello); - sh->hello = hello; - hello->sh = sh; - break; - } - GNUNET_free (addr); + { + if ((NULL == sh->address) || (0 != strcmp(sh->address, addr))) + continue; + GNUNET_assert(NULL == sh->hello); + sh->hello = hello; + hello->sh = sh; + break; + } + GNUNET_free(addr); if (NULL == p->task) - p->task = GNUNET_SCHEDULER_add_now (&suggest_start_cb, p); + p->task = GNUNET_SCHEDULER_add_now(&suggest_start_cb, p); } @@ -546,27 +536,27 @@ watch_cb (void *cls, * @return a peer handle */ static struct Peer * -peer_add (struct SimpleHandle *h, const struct GNUNET_PeerIdentity *pid) +peer_add(struct SimpleHandle *h, const struct GNUNET_PeerIdentity *pid) { - struct Peer *p = lookup_peer (h, pid); + struct Peer *p = lookup_peer(h, pid); if (NULL != p) return p; - p = GNUNET_new (struct Peer); + p = GNUNET_new(struct Peer); p->h = h; p->pid = *pid; - p->wc = GNUNET_PEERSTORE_watch (h->ps, - "transport", - &p->pid, - GNUNET_PEERSTORE_TRANSPORT_URLADDRESS_KEY, - &watch_cb, - p); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_put ( - h->peers, - &p->pid, - p, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + p->wc = GNUNET_PEERSTORE_watch(h->ps, + "transport", + &p->pid, + GNUNET_PEERSTORE_TRANSPORT_URLADDRESS_KEY, + &watch_cb, + p); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_put( + h->peers, + &p->pid, + p, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); return p; } @@ -579,31 +569,31 @@ peer_add (struct SimpleHandle *h, const struct GNUNET_PeerIdentity *pid) * @param p the peer to free */ static void -peer_free (struct Peer *p) +peer_free(struct Peer *p) { struct SimpleHandle *h = p->h; struct Hello *hello; - GNUNET_assert (NULL == p->sh_head); + GNUNET_assert(NULL == p->sh_head); while (NULL != (hello = p->h_head)) - { - GNUNET_CONTAINER_DLL_remove (p->h_head, p->h_tail, hello); - GNUNET_assert (NULL == hello->sh); - GNUNET_free (hello); - } + { + GNUNET_CONTAINER_DLL_remove(p->h_head, p->h_tail, hello); + GNUNET_assert(NULL == hello->sh); + GNUNET_free(hello); + } if (NULL != p->task) - { - GNUNET_SCHEDULER_cancel (p->task); - p->task = NULL; - } + { + GNUNET_SCHEDULER_cancel(p->task); + p->task = NULL; + } if (NULL != p->wc) - { - GNUNET_PEERSTORE_watch_cancel (p->wc); - p->wc = NULL; - } - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (h->peers, &p->pid, p)); - GNUNET_free (p); + { + GNUNET_PEERSTORE_watch_cancel(p->wc); + p->wc = NULL; + } + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(h->peers, &p->pid, p)); + GNUNET_free(p); } @@ -614,7 +604,7 @@ peer_free (struct Peer *p) * @param sh session handle to consider updating transport for */ static void -consider_notify_transport (struct GNUNET_ATS_SessionHandle *sh) +consider_notify_transport(struct GNUNET_ATS_SessionHandle *sh) { struct Peer *peer = sh->peer; struct SimpleHandle *h = peer->h; @@ -625,15 +615,15 @@ consider_notify_transport (struct GNUNET_ATS_SessionHandle *sh) int64_t delta_in; int64_t delta_out; - delay = GNUNET_TIME_absolute_get_duration (sh->last_allocation); + delay = GNUNET_TIME_absolute_get_duration(sh->last_allocation); /* A significant change is more than 10% of the quota, which is given in bytes/second */ sig_in = h->networks[nt].total_quota_in * (delay.rel_value_us / 1000LL) / 1000LL / 10; sig_out = h->networks[nt].total_quota_out * (delay.rel_value_us / 1000LL) / 1000LL / 10; - delta_in = ((int64_t) ntohl (sh->bw_in.value__)) - ((int64_t) sh->target_in); - delta_out = ((int64_t) ntohl (sh->bw_in.value__)) - ((int64_t) sh->target_in); + delta_in = ((int64_t)ntohl(sh->bw_in.value__)) - ((int64_t)sh->target_in); + delta_out = ((int64_t)ntohl(sh->bw_in.value__)) - ((int64_t)sh->target_in); /* we want the absolute values */ if (delta_in < 0) delta_in = -delta_in; @@ -648,24 +638,23 @@ consider_notify_transport (struct GNUNET_ATS_SessionHandle *sh) /* change is significant, tell transport! */ if (sh->target_in > UINT32_MAX) sh->target_in = UINT32_MAX; - sh->bw_in.value__ = htonl ((uint32_t) sh->target_in); + sh->bw_in.value__ = htonl((uint32_t)sh->target_in); if (sh->target_out > UINT32_MAX) sh->target_out = UINT32_MAX; - sh->bw_out.value__ = htonl ((uint32_t) sh->target_out); - sh->last_allocation = GNUNET_TIME_absolute_get (); - h->env->allocate_cb (h->env->cls, - sh->session, - &peer->pid, - sh->bw_in, - sh->bw_out); + sh->bw_out.value__ = htonl((uint32_t)sh->target_out); + sh->last_allocation = GNUNET_TIME_absolute_get(); + h->env->allocate_cb(h->env->cls, + sh->session, + &peer->pid, + sh->bw_in, + sh->bw_out); } /** * Closure for #update_counters and #update_allocation. */ -struct Counters -{ +struct Counters { /** * Plugin's state. */ @@ -709,100 +698,103 @@ struct Counters * @return #GNUNET_YES (continue to iterate) */ static int -update_counters (void *cls, const struct GNUNET_PeerIdentity *pid, void *value) +update_counters(void *cls, const struct GNUNET_PeerIdentity *pid, void *value) { struct Counters *c = cls; struct Peer *peer = value; struct GNUNET_ATS_SessionHandle *best[GNUNET_MQ_PREFERENCE_COUNT]; - (void) pid; + (void)pid; if (NULL == peer->sh_head) return GNUNET_YES; /* no available session, cannot allocate bandwidth */ - memset (best, 0, sizeof (best)); + memset(best, 0, sizeof(best)); for (struct GNUNET_ATS_SessionHandle *sh = peer->sh_head; NULL != sh; sh = sh->next) - { - enum GNUNET_NetworkType nt = sh->data->prop.nt; - - sh->target_out = MIN_BANDWIDTH_PER_SESSION; - c->bw_out_by_nt[nt] += MIN_BANDWIDTH_PER_SESSION; - c->bw_in_by_nt[nt] += - GNUNET_MAX (MIN_BANDWIDTH_PER_SESSION, sh->data->prop.goodput_in); - for (enum GNUNET_MQ_PreferenceKind pk = 0; pk < GNUNET_MQ_PREFERENCE_COUNT; - pk++) { - /* General rule: always prefer smaller distance if possible, - otherwise decide by pk: */ - switch (pk) - { - case GNUNET_MQ_PREFERENCE_NONE: - break; - case GNUNET_MQ_PREFERENCE_BANDWIDTH: - /* For bandwidth, we compare the sum of transmitted bytes and - confirmed transmitted bytes, so confirmed data counts twice */ - if ((NULL == best[pk]) || - (sh->data->prop.distance < best[pk]->data->prop.distance) || - (sh->data->prop.utilization_out + sh->data->prop.goodput_out > - best[pk]->data->prop.utilization_out + - best[pk]->data->prop.goodput_out)) - best[pk] = sh; - /* If both are equal (i.e. usually this happens if there is a zero), use - latency as a yardstick */ - if ((sh->data->prop.utilization_out + sh->data->prop.goodput_out == - best[pk]->data->prop.utilization_out + - best[pk]->data->prop.goodput_out) && - (sh->data->prop.distance == best[pk]->data->prop.distance) && - (sh->data->prop.delay.rel_value_us < - best[pk]->data->prop.delay.rel_value_us)) - best[pk] = sh; - break; - case GNUNET_MQ_PREFERENCE_LATENCY: - if ((NULL == best[pk]) || - (sh->data->prop.distance < best[pk]->data->prop.distance) || - ((sh->data->prop.distance == best[pk]->data->prop.distance) && - (sh->data->prop.delay.rel_value_us < - best[pk]->data->prop.delay.rel_value_us))) - best[pk] = sh; - break; - case GNUNET_MQ_PREFERENCE_RELIABILITY: - /* For reliability, we consider the ratio of goodput to utilization - (but use multiplicative formultations to avoid division by zero) */ - if ((NULL == best[pk]) || (1ULL * sh->data->prop.goodput_out * - best[pk]->data->prop.utilization_out > - 1ULL * sh->data->prop.utilization_out * - best[pk]->data->prop.goodput_out)) - best[pk] = sh; - /* If both are equal (i.e. usually this happens if there is a zero), use - latency as a yardstick */ - if ((1ULL * sh->data->prop.goodput_out * - best[pk]->data->prop.utilization_out == - 1ULL * sh->data->prop.utilization_out * - best[pk]->data->prop.goodput_out) && - (sh->data->prop.distance == best[pk]->data->prop.distance) && - (sh->data->prop.delay.rel_value_us < - best[pk]->data->prop.delay.rel_value_us)) - best[pk] = sh; - break; - } + enum GNUNET_NetworkType nt = sh->data->prop.nt; + + sh->target_out = MIN_BANDWIDTH_PER_SESSION; + c->bw_out_by_nt[nt] += MIN_BANDWIDTH_PER_SESSION; + c->bw_in_by_nt[nt] += + GNUNET_MAX(MIN_BANDWIDTH_PER_SESSION, sh->data->prop.goodput_in); + for (enum GNUNET_MQ_PreferenceKind pk = 0; pk < GNUNET_MQ_PREFERENCE_COUNT; + pk++) + { + /* General rule: always prefer smaller distance if possible, + otherwise decide by pk: */ + switch (pk) + { + case GNUNET_MQ_PREFERENCE_NONE: + break; + + case GNUNET_MQ_PREFERENCE_BANDWIDTH: + /* For bandwidth, we compare the sum of transmitted bytes and + confirmed transmitted bytes, so confirmed data counts twice */ + if ((NULL == best[pk]) || + (sh->data->prop.distance < best[pk]->data->prop.distance) || + (sh->data->prop.utilization_out + sh->data->prop.goodput_out > + best[pk]->data->prop.utilization_out + + best[pk]->data->prop.goodput_out)) + best[pk] = sh; + /* If both are equal (i.e. usually this happens if there is a zero), use + latency as a yardstick */ + if ((sh->data->prop.utilization_out + sh->data->prop.goodput_out == + best[pk]->data->prop.utilization_out + + best[pk]->data->prop.goodput_out) && + (sh->data->prop.distance == best[pk]->data->prop.distance) && + (sh->data->prop.delay.rel_value_us < + best[pk]->data->prop.delay.rel_value_us)) + best[pk] = sh; + break; + + case GNUNET_MQ_PREFERENCE_LATENCY: + if ((NULL == best[pk]) || + (sh->data->prop.distance < best[pk]->data->prop.distance) || + ((sh->data->prop.distance == best[pk]->data->prop.distance) && + (sh->data->prop.delay.rel_value_us < + best[pk]->data->prop.delay.rel_value_us))) + best[pk] = sh; + break; + + case GNUNET_MQ_PREFERENCE_RELIABILITY: + /* For reliability, we consider the ratio of goodput to utilization + (but use multiplicative formultations to avoid division by zero) */ + if ((NULL == best[pk]) || (1ULL * sh->data->prop.goodput_out * + best[pk]->data->prop.utilization_out > + 1ULL * sh->data->prop.utilization_out * + best[pk]->data->prop.goodput_out)) + best[pk] = sh; + /* If both are equal (i.e. usually this happens if there is a zero), use + latency as a yardstick */ + if ((1ULL * sh->data->prop.goodput_out * + best[pk]->data->prop.utilization_out == + 1ULL * sh->data->prop.utilization_out * + best[pk]->data->prop.goodput_out) && + (sh->data->prop.distance == best[pk]->data->prop.distance) && + (sh->data->prop.delay.rel_value_us < + best[pk]->data->prop.delay.rel_value_us)) + best[pk] = sh; + break; + } + } } - } /* for first round, assign target bandwidth simply to sum of requested bandwidth */ for (enum GNUNET_MQ_PreferenceKind pk = 1 /* skip GNUNET_MQ_PREFERENCE_NONE */; pk < GNUNET_MQ_PREFERENCE_COUNT; pk++) - { - const struct GNUNET_ATS_SessionData *data = best[pk]->data; - enum GNUNET_NetworkType nt; - - GNUNET_assert (NULL != data); - nt = data->prop.nt; - best[pk]->target_out = - GNUNET_MIN (peer->bw_by_pk[pk], MIN_BANDWIDTH_PER_SESSION); - c->bw_out_by_nt[nt] += - (uint64_t) (best[pk]->target_out - MIN_BANDWIDTH_PER_SESSION); - } + { + const struct GNUNET_ATS_SessionData *data = best[pk]->data; + enum GNUNET_NetworkType nt; + + GNUNET_assert(NULL != data); + nt = data->prop.nt; + best[pk]->target_out = + GNUNET_MIN(peer->bw_by_pk[pk], MIN_BANDWIDTH_PER_SESSION); + c->bw_out_by_nt[nt] += + (uint64_t)(best[pk]->target_out - MIN_BANDWIDTH_PER_SESSION); + } return GNUNET_YES; } @@ -817,23 +809,23 @@ update_counters (void *cls, const struct GNUNET_PeerIdentity *pid, void *value) * @return #GNUNET_YES (continue to iterate) */ static int -update_allocation (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *value) +update_allocation(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *value) { struct Counters *c = cls; struct Peer *peer = value; - (void) pid; + (void)pid; for (struct GNUNET_ATS_SessionHandle *sh = peer->sh_head; NULL != sh; sh = sh->next) - { - enum GNUNET_NetworkType nt = sh->data->prop.nt; + { + enum GNUNET_NetworkType nt = sh->data->prop.nt; - sh->target_out = (uint64_t) (c->scale_out[nt] * sh->target_out); - sh->target_in = (uint64_t) (c->scale_in[nt] * sh->target_in); - consider_notify_transport (sh); - } + sh->target_out = (uint64_t)(c->scale_out[nt] * sh->target_out); + sh->target_in = (uint64_t)(c->scale_in[nt] * sh->target_in); + consider_notify_transport(sh); + } return GNUNET_YES; } @@ -842,23 +834,23 @@ update_allocation (void *cls, * The world changed, recalculate our allocations. */ static void -update (struct SimpleHandle *h) +update(struct SimpleHandle *h) { - struct Counters cnt = {.h = h}; + struct Counters cnt = { .h = h }; - GNUNET_CONTAINER_multipeermap_iterate (h->peers, &update_counters, &cnt); + GNUNET_CONTAINER_multipeermap_iterate(h->peers, &update_counters, &cnt); /* calculate how badly the missmatch between requested allocations and available bandwidth is per network type */ for (enum GNUNET_NetworkType nt = 0; nt < GNUNET_NT_COUNT; nt++) - { - cnt.scale_out[nt] = - 1.0 * cnt.bw_out_by_nt[nt] / h->networks[nt].total_quota_out; - cnt.scale_in[nt] = - 1.0 * cnt.bw_in_by_nt[nt] / h->networks[nt].total_quota_in; - } + { + cnt.scale_out[nt] = + 1.0 * cnt.bw_out_by_nt[nt] / h->networks[nt].total_quota_out; + cnt.scale_in[nt] = + 1.0 * cnt.bw_in_by_nt[nt] / h->networks[nt].total_quota_in; + } /* recalculate allocations, considering scaling factor, and update transport if the change is significant */ - GNUNET_CONTAINER_multipeermap_iterate (h->peers, &update_allocation, &cnt); + GNUNET_CONTAINER_multipeermap_iterate(h->peers, &update_allocation, &cnt); } @@ -870,15 +862,15 @@ update (struct SimpleHandle *h) * @return plugin's internal representation, or NULL */ static struct GNUNET_ATS_PreferenceHandle * -simple_preference_add (void *cls, const struct GNUNET_ATS_Preference *pref) +simple_preference_add(void *cls, const struct GNUNET_ATS_Preference *pref) { struct SimpleHandle *h = cls; - struct Peer *p = peer_add (h, &pref->peer); + struct Peer *p = peer_add(h, &pref->peer); - GNUNET_assert (pref->pk < GNUNET_MQ_PREFERENCE_COUNT); - p->bw_by_pk[pref->pk] += ntohl (pref->bw.value__); - h->bw_by_pk[pref->pk] += ntohl (pref->bw.value__); - update (h); + GNUNET_assert(pref->pk < GNUNET_MQ_PREFERENCE_COUNT); + p->bw_by_pk[pref->pk] += ntohl(pref->bw.value__); + h->bw_by_pk[pref->pk] += ntohl(pref->bw.value__); + update(h); return NULL; } @@ -892,20 +884,20 @@ simple_preference_add (void *cls, const struct GNUNET_ATS_Preference *pref) * @return plugin's internal representation, or NULL */ static void -simple_preference_del (void *cls, - struct GNUNET_ATS_PreferenceHandle *ph, - const struct GNUNET_ATS_Preference *pref) +simple_preference_del(void *cls, + struct GNUNET_ATS_PreferenceHandle *ph, + const struct GNUNET_ATS_Preference *pref) { struct SimpleHandle *h = cls; - struct Peer *p = lookup_peer (h, &pref->peer); - - GNUNET_assert (NULL != p); - GNUNET_assert (pref->pk < GNUNET_MQ_PREFERENCE_COUNT); - p->bw_by_pk[pref->pk] -= ntohl (pref->bw.value__); - h->bw_by_pk[pref->pk] -= ntohl (pref->bw.value__); - if ((0 == p->bw_by_pk[pref->pk]) && (GNUNET_YES == peer_test_dead (p))) - peer_free (p); - update (h); + struct Peer *p = lookup_peer(h, &pref->peer); + + GNUNET_assert(NULL != p); + GNUNET_assert(pref->pk < GNUNET_MQ_PREFERENCE_COUNT); + p->bw_by_pk[pref->pk] -= ntohl(pref->bw.value__); + h->bw_by_pk[pref->pk] -= ntohl(pref->bw.value__); + if ((0 == p->bw_by_pk[pref->pk]) && (GNUNET_YES == peer_test_dead(p))) + peer_free(p); + update(h); } @@ -919,50 +911,50 @@ simple_preference_del (void *cls, * @return handle by which the plugin will identify this session */ static struct GNUNET_ATS_SessionHandle * -simple_session_add (void *cls, - const struct GNUNET_ATS_SessionData *data, - const char *address) +simple_session_add(void *cls, + const struct GNUNET_ATS_SessionData *data, + const char *address) { struct SimpleHandle *h = cls; - struct Peer *p = peer_add (h, &data->peer); + struct Peer *p = peer_add(h, &data->peer); struct Hello *hello; size_t alen; struct GNUNET_ATS_SessionHandle *sh; /* setup session handle */ - GNUNET_assert (NULL != data); + GNUNET_assert(NULL != data); if (NULL == address) alen = 0; else - alen = strlen (address) + 1; - sh = GNUNET_malloc (sizeof (struct GNUNET_ATS_SessionHandle) + alen); + alen = strlen(address) + 1; + sh = GNUNET_malloc(sizeof(struct GNUNET_ATS_SessionHandle) + alen); sh->peer = p; sh->session = data->session; sh->data = data; if (NULL == address) - { - sh->address = NULL; - } + { + sh->address = NULL; + } else - { - memcpy (&sh[1], address, alen); - sh->address = (const char *) &sh[1]; - } - GNUNET_CONTAINER_DLL_insert (p->sh_head, p->sh_tail, sh); + { + memcpy(&sh[1], address, alen); + sh->address = (const char *)&sh[1]; + } + GNUNET_CONTAINER_DLL_insert(p->sh_head, p->sh_tail, sh); if (NULL != address) - { - /* match HELLO */ - hello = p->h_head; - while ((NULL != hello) && (0 != strcmp (address, hello->address))) - hello = hello->next; - if (NULL != hello) { - hello->sh = sh; - hello->backoff = GNUNET_TIME_UNIT_ZERO; - sh->hello = hello; + /* match HELLO */ + hello = p->h_head; + while ((NULL != hello) && (0 != strcmp(address, hello->address))) + hello = hello->next; + if (NULL != hello) + { + hello->sh = sh; + hello->backoff = GNUNET_TIME_UNIT_ZERO; + sh->hello = hello; + } } - } - update (h); + update(h); return sh; } @@ -976,15 +968,15 @@ simple_session_add (void *cls, * @param data performance characteristics of @a sh */ static void -simple_session_update (void *cls, - struct GNUNET_ATS_SessionHandle *sh, - const struct GNUNET_ATS_SessionData *data) +simple_session_update(void *cls, + struct GNUNET_ATS_SessionHandle *sh, + const struct GNUNET_ATS_SessionData *data) { struct SimpleHandle *h = cls; - GNUNET_assert (NULL != data); + GNUNET_assert(NULL != data); sh->data = data; /* this statement should not really do anything... */ - update (h); + update(h); } @@ -996,30 +988,30 @@ simple_session_update (void *cls, * @param data (last) performance characteristics of @a sh */ static void -simple_session_del (void *cls, - struct GNUNET_ATS_SessionHandle *sh, - const struct GNUNET_ATS_SessionData *data) +simple_session_del(void *cls, + struct GNUNET_ATS_SessionHandle *sh, + const struct GNUNET_ATS_SessionData *data) { struct SimpleHandle *h = cls; struct Peer *p = sh->peer; struct Hello *hello = sh->hello; /* clean up sh */ - GNUNET_CONTAINER_DLL_remove (p->sh_head, p->sh_tail, sh); + GNUNET_CONTAINER_DLL_remove(p->sh_head, p->sh_tail, sh); if (NULL != hello) - { - GNUNET_assert (sh == hello->sh); - hello->sh = NULL; - /* session went down, if necessary restart suggesting - addresses */ - if (NULL == p->task) - p->task = GNUNET_SCHEDULER_add_now (&suggest_start_cb, p); - } - GNUNET_free (sh); + { + GNUNET_assert(sh == hello->sh); + hello->sh = NULL; + /* session went down, if necessary restart suggesting + addresses */ + if (NULL == p->task) + p->task = GNUNET_SCHEDULER_add_now(&suggest_start_cb, p); + } + GNUNET_free(sh); /* del peer if otherwise dead */ - if ((NULL == p->sh_head) && (GNUNET_YES == peer_test_dead (p))) - peer_free (p); - update (h); + if ((NULL == p->sh_head) && (GNUNET_YES == peer_test_dead(p))) + peer_free(p); + update(h); } @@ -1034,16 +1026,16 @@ simple_session_del (void *cls, * @return the `struct SimpleHandle` to pass as a closure */ void * -libgnunet_plugin_ats2_simple_init (void *cls) +libgnunet_plugin_ats2_simple_init(void *cls) { static struct GNUNET_ATS_SolverFunctions sf; struct GNUNET_ATS_PluginEnvironment *env = cls; struct SimpleHandle *s; - s = GNUNET_new (struct SimpleHandle); + s = GNUNET_new(struct SimpleHandle); s->env = env; - s->peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES); - s->ps = GNUNET_PEERSTORE_connect (env->cfg); + s->peers = GNUNET_CONTAINER_multipeermap_create(128, GNUNET_YES); + s->ps = GNUNET_PEERSTORE_connect(env->cfg); sf.cls = s; sf.preference_add = &simple_preference_add; sf.preference_del = &simple_preference_del; @@ -1051,18 +1043,18 @@ libgnunet_plugin_ats2_simple_init (void *cls) sf.session_update = &simple_session_update; sf.session_del = &simple_session_del; for (enum GNUNET_NetworkType nt = 0; nt < GNUNET_NT_COUNT; nt++) - { - const char *name = GNUNET_NT_to_string (nt); - - if (NULL == name) { - GNUNET_break (0); - break; + const char *name = GNUNET_NT_to_string(nt); + + if (NULL == name) + { + GNUNET_break(0); + break; + } + get_quota(env->cfg, name, "IN", &s->networks[nt].total_quota_in); + get_quota(env->cfg, name, "OUT", &s->networks[nt].total_quota_out); + s->networks[nt].type = nt; } - get_quota (env->cfg, name, "IN", &s->networks[nt].total_quota_in); - get_quota (env->cfg, name, "OUT", &s->networks[nt].total_quota_out); - s->networks[nt].type = nt; - } return &sf; } @@ -1073,15 +1065,15 @@ libgnunet_plugin_ats2_simple_init (void *cls) * @param cls return value from #libgnunet_plugin_ats_proportional_init() */ void * -libgnunet_plugin_ats2_simple_done (void *cls) +libgnunet_plugin_ats2_simple_done(void *cls) { struct GNUNET_ATS_SolverFunctions *sf = cls; struct SimpleHandle *s = sf->cls; - GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (s->peers)); - GNUNET_CONTAINER_multipeermap_destroy (s->peers); - GNUNET_PEERSTORE_disconnect (s->ps, GNUNET_NO); - GNUNET_free (s); + GNUNET_break(0 == GNUNET_CONTAINER_multipeermap_size(s->peers)); + GNUNET_CONTAINER_multipeermap_destroy(s->peers); + GNUNET_PEERSTORE_disconnect(s->ps, GNUNET_NO); + GNUNET_free(s); return NULL; } diff --git a/src/ats/plugin_ats_mlp.c b/src/ats/plugin_ats_mlp.c index 0f3a727a7..8d3c9e23a 100644 --- a/src/ats/plugin_ats_mlp.c +++ b/src/ats/plugin_ats_mlp.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/plugin_ats_mlp.c @@ -34,7 +34,7 @@ #include -#define BIG_M_VALUE (UINT32_MAX) /10 +#define BIG_M_VALUE (UINT32_MAX) / 10 #define BIG_M_STRING "unlimited" #define MLP_AVERAGING_QUEUE_LENGTH 3 @@ -54,16 +54,14 @@ #define GLP_YES 1.0 #define GLP_NO 0.0 -enum MLP_Output_Format -{ +enum MLP_Output_Format { MLP_MPS, MLP_CPLEX, MLP_GLPK }; -enum QualityMetrics -{ +enum QualityMetrics { RQ_QUALITY_METRIC_DELAY = 0, RQ_QUALITY_METRIC_DISTANCE = 1, RQ_QUALITY_METRIC_COUNT = 2 @@ -71,22 +69,24 @@ enum QualityMetrics static const char * -print_quality_type (enum QualityMetrics qm) +print_quality_type(enum QualityMetrics qm) { - switch (qm){ - case RQ_QUALITY_METRIC_DELAY: - return "delay"; - case RQ_QUALITY_METRIC_DISTANCE: - return "distance"; - default: - GNUNET_break (0); - return NULL; - } + switch (qm) + { + case RQ_QUALITY_METRIC_DELAY: + return "delay"; + + case RQ_QUALITY_METRIC_DISTANCE: + return "distance"; + + default: + GNUNET_break(0); + return NULL; + } } -struct MLP_Solution -{ +struct MLP_Solution { int lp_res; int lp_presolv; int mip_res; @@ -103,11 +103,9 @@ struct MLP_Solution int n_peers; int n_addresses; - }; -struct ATS_Peer -{ +struct ATS_Peer { struct GNUNET_PeerIdentity id; /* Was this peer already added to the current problem? */ @@ -123,8 +121,7 @@ struct ATS_Peer double f; }; -struct MLP_Problem -{ +struct MLP_Problem { /** * GLPK (MLP) problem object */ @@ -170,11 +167,9 @@ struct MLP_Problem int *ja; /* Column index value */ double *ar; - }; -struct MLP_Variables -{ +struct MLP_Variables { /* Big M value for bandwidth capping */ double BIG_M; @@ -225,14 +220,12 @@ struct MLP_Variables * contains mapping to GNUNET_ATS_Property * */ int rc[RQ_QUALITY_METRIC_COUNT]; - }; /** * MLP Handle */ -struct GAS_MLP_Handle -{ +struct GAS_MLP_Handle { struct GNUNET_ATS_PluginEnvironment *env; /** @@ -367,9 +360,7 @@ struct GAS_MLP_Handle /** * Address specific MLP information */ -struct MLP_information -{ - +struct MLP_information { /** * Bandwidth assigned outbound */ @@ -512,7 +503,7 @@ struct MLP_information */ -#define LOG(kind,...) GNUNET_log_from (kind, "ats-mlp",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "ats-mlp", __VA_ARGS__) /** * Print debug output for mlp problem creation @@ -527,12 +518,12 @@ struct MLP_information * @return 0: glpk prints output on terminal, 0 != surpress output */ static int -mlp_term_hook (void *info, const char *s) +mlp_term_hook(void *info, const char *s) { struct GAS_MLP_Handle *mlp = info; if (mlp->opt_dbg_glpk_verbose) - LOG (GNUNET_ERROR_TYPE_ERROR, "%s", s); + LOG(GNUNET_ERROR_TYPE_ERROR, "%s", s); return 1; } @@ -546,14 +537,15 @@ mlp_term_hook (void *info, const char *s) * @return #GNUNET_OK */ static int -reset_peers (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) - { - struct ATS_Peer *peer = value; - peer->processed = GNUNET_NO; - return GNUNET_OK; - } +reset_peers(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) +{ + struct ATS_Peer *peer = value; + + peer->processed = GNUNET_NO; + return GNUNET_OK; +} /** * Delete the MLP problem and free the constrain matrix @@ -561,37 +553,38 @@ reset_peers (void *cls, * @param mlp the MLP handle */ static void -mlp_delete_problem (struct GAS_MLP_Handle *mlp) +mlp_delete_problem(struct GAS_MLP_Handle *mlp) { int c; + if (mlp == NULL) return; if (mlp->p.prob != NULL) - { - glp_delete_prob(mlp->p.prob); - mlp->p.prob = NULL; - } + { + glp_delete_prob(mlp->p.prob); + mlp->p.prob = NULL; + } /* delete row index */ if (mlp->p.ia != NULL) - { - GNUNET_free (mlp->p.ia); - mlp->p.ia = NULL; - } + { + GNUNET_free(mlp->p.ia); + mlp->p.ia = NULL; + } /* delete column index */ if (mlp->p.ja != NULL) - { - GNUNET_free (mlp->p.ja); - mlp->p.ja = NULL; - } + { + GNUNET_free(mlp->p.ja); + mlp->p.ja = NULL; + } /* delete coefficients */ if (mlp->p.ar != NULL) - { - GNUNET_free (mlp->p.ar); - mlp->p.ar = NULL; - } + { + GNUNET_free(mlp->p.ar); + mlp->p.ar = NULL; + } mlp->p.ci = 0; mlp->p.prob = NULL; @@ -601,15 +594,15 @@ mlp_delete_problem (struct GAS_MLP_Handle *mlp) mlp->p.r_c4 = MLP_UNDEFINED; mlp->p.r_c6 = MLP_UNDEFINED; mlp->p.r_c9 = MLP_UNDEFINED; - for (c = 0; c < RQ_QUALITY_METRIC_COUNT ; c ++) + for (c = 0; c < RQ_QUALITY_METRIC_COUNT; c++) mlp->p.r_q[c] = MLP_UNDEFINED; - for (c = 0; c < GNUNET_NT_COUNT; c ++) + for (c = 0; c < GNUNET_NT_COUNT; c++) mlp->p.r_quota[c] = MLP_UNDEFINED; mlp->p.ci = MLP_UNDEFINED; - GNUNET_CONTAINER_multipeermap_iterate (mlp->requested_peers, - &reset_peers, NULL); + GNUNET_CONTAINER_multipeermap_iterate(mlp->requested_peers, + &reset_peers, NULL); } @@ -619,25 +612,32 @@ mlp_delete_problem (struct GAS_MLP_Handle *mlp) * @return string with result */ static const char * -mlp_status_to_string (int retcode) +mlp_status_to_string(int retcode) { - switch (retcode) { + switch (retcode) + { case GLP_UNDEF: return "solution is undefined"; + case GLP_FEAS: return "solution is feasible"; + case GLP_INFEAS: return "solution is infeasible"; + case GLP_NOFEAS: return "no feasible solution exists"; + case GLP_OPT: return "solution is optimal"; + case GLP_UNBND: return "solution is unbounded"; + default: - GNUNET_break (0); + GNUNET_break(0); return "unknown error"; - } + } } @@ -647,114 +647,134 @@ mlp_status_to_string (int retcode) * @return string with result */ static const char * -mlp_solve_to_string (int retcode) +mlp_solve_to_string(int retcode) { - switch (retcode) { + switch (retcode) + { case 0: return "ok"; + case GLP_EBADB: return "invalid basis"; + case GLP_ESING: return "singular matrix"; + case GLP_ECOND: return "ill-conditioned matrix"; + case GLP_EBOUND: return "invalid bounds"; + case GLP_EFAIL: return "solver failed"; + case GLP_EOBJLL: return "objective lower limit reached"; + case GLP_EOBJUL: return "objective upper limit reached"; + case GLP_EITLIM: return "iteration limit exceeded"; + case GLP_ETMLIM: return "time limit exceeded"; + case GLP_ENOPFS: return "no primal feasible solution"; + case GLP_ENODFS: return "no dual feasible solution"; + case GLP_EROOT: return "root LP optimum not provided"; + case GLP_ESTOP: return "search terminated by application"; + case GLP_EMIPGAP: return "relative mip gap tolerance reached"; + case GLP_ENOFEAS: return "no dual feasible solution"; + case GLP_ENOCVG: return "no convergence"; + case GLP_EINSTAB: return "numerical instability"; + case GLP_EDATA: return "invalid data"; + case GLP_ERANGE: return "result out of range"; + default: - GNUNET_break (0); + GNUNET_break(0); return "unknown error"; - } + } } -struct CountContext -{ +struct CountContext { const struct GNUNET_CONTAINER_MultiPeerMap *map; int result; }; static int -mlp_create_problem_count_addresses_it (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +mlp_create_problem_count_addresses_it(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct CountContext *cctx = cls; /* Check if we have to add this peer due to a pending request */ - if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (cctx->map, key)) + if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains(cctx->map, key)) cctx->result++; return GNUNET_OK; } static int -mlp_create_problem_count_addresses (const struct GNUNET_CONTAINER_MultiPeerMap *requested_peers, - const struct GNUNET_CONTAINER_MultiPeerMap *addresses) +mlp_create_problem_count_addresses(const struct GNUNET_CONTAINER_MultiPeerMap *requested_peers, + const struct GNUNET_CONTAINER_MultiPeerMap *addresses) { struct CountContext cctx; cctx.map = requested_peers; cctx.result = 0; - GNUNET_CONTAINER_multipeermap_iterate (addresses, - &mlp_create_problem_count_addresses_it, &cctx); + GNUNET_CONTAINER_multipeermap_iterate(addresses, + &mlp_create_problem_count_addresses_it, &cctx); return cctx.result; } static int -mlp_create_problem_count_peers_it (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +mlp_create_problem_count_peers_it(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct CountContext *cctx = cls; /* Check if we have to addresses for the requested peer */ - if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (cctx->map, key)) + if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains(cctx->map, key)) cctx->result++; return GNUNET_OK; } static int -mlp_create_problem_count_peers (const struct GNUNET_CONTAINER_MultiPeerMap *requested_peers, - const struct GNUNET_CONTAINER_MultiPeerMap *addresses) +mlp_create_problem_count_peers(const struct GNUNET_CONTAINER_MultiPeerMap *requested_peers, + const struct GNUNET_CONTAINER_MultiPeerMap *addresses) { struct CountContext cctx; cctx.map = addresses; cctx.result = 0; - GNUNET_CONTAINER_multipeermap_iterate (requested_peers, - &mlp_create_problem_count_peers_it, &cctx); + GNUNET_CONTAINER_multipeermap_iterate(requested_peers, + &mlp_create_problem_count_peers_it, &cctx); return cctx.result; } @@ -773,9 +793,9 @@ mlp_create_problem_count_peers (const struct GNUNET_CONTAINER_MultiPeerMap *requ * on error */ static int -mlp_create_problem_update_value (struct MLP_Problem *p, - int row, int col, double val, - int line) +mlp_create_problem_update_value(struct MLP_Problem *p, + int row, int col, double val, + int line) { int c_cols; int c_elems; @@ -785,59 +805,59 @@ mlp_create_problem_update_value (struct MLP_Problem *p, double *val_array; int *ind_array; - GNUNET_assert (NULL != p->prob); + GNUNET_assert(NULL != p->prob); /* Get number of columns and prepare data structure */ c_cols = glp_get_num_cols(p->prob); if (0 >= c_cols) return GNUNET_SYSERR; - val_array = GNUNET_malloc ((c_cols +1)* sizeof (double)); - GNUNET_assert (NULL != val_array); - ind_array = GNUNET_malloc ((c_cols+1) * sizeof (int)); - GNUNET_assert (NULL != ind_array); + val_array = GNUNET_malloc((c_cols + 1) * sizeof(double)); + GNUNET_assert(NULL != val_array); + ind_array = GNUNET_malloc((c_cols + 1) * sizeof(int)); + GNUNET_assert(NULL != ind_array); /* Extract the row */ /* Update the value */ - c_elems = glp_get_mat_row (p->prob, row, ind_array, val_array); + c_elems = glp_get_mat_row(p->prob, row, ind_array, val_array); found = GNUNET_NO; - for (c1 = 1; c1 < (c_elems+1); c1++) - { - if (ind_array[c1] == col) + for (c1 = 1; c1 < (c_elems + 1); c1++) { - found = GNUNET_YES; - break; + if (ind_array[c1] == col) + { + found = GNUNET_YES; + break; + } } - } if (GNUNET_NO == found) - { - ind_array[c_elems+1] = col; - val_array[c_elems+1] = val; - LOG (GNUNET_ERROR_TYPE_DEBUG, "[P] Setting value in [%s : %s] to `%.2f'\n", - glp_get_row_name (p->prob, row), glp_get_col_name (p->prob, col), - val); - glp_set_mat_row (p->prob, row, c_elems+1, ind_array, val_array); - GNUNET_free (ind_array); - GNUNET_free (val_array); - return GNUNET_YES; - } + { + ind_array[c_elems + 1] = col; + val_array[c_elems + 1] = val; + LOG(GNUNET_ERROR_TYPE_DEBUG, "[P] Setting value in [%s : %s] to `%.2f'\n", + glp_get_row_name(p->prob, row), glp_get_col_name(p->prob, col), + val); + glp_set_mat_row(p->prob, row, c_elems + 1, ind_array, val_array); + GNUNET_free(ind_array); + GNUNET_free(val_array); + return GNUNET_YES; + } else - { - /* Update value */ - LOG (GNUNET_ERROR_TYPE_DEBUG, "[P] Updating value in [%s : %s] from `%.2f' to `%.2f'\n", - glp_get_row_name (p->prob, row), glp_get_col_name (p->prob, col), - val_array[c1], val); - if (val != val_array[c1]) - res = GNUNET_YES; - else - res = GNUNET_NO; - val_array[c1] = val; - /* Update the row in the matrix */ - glp_set_mat_row (p->prob, row, c_elems, ind_array, val_array); - } - - GNUNET_free (ind_array); - GNUNET_free (val_array); + { + /* Update value */ + LOG(GNUNET_ERROR_TYPE_DEBUG, "[P] Updating value in [%s : %s] from `%.2f' to `%.2f'\n", + glp_get_row_name(p->prob, row), glp_get_col_name(p->prob, col), + val_array[c1], val); + if (val != val_array[c1]) + res = GNUNET_YES; + else + res = GNUNET_NO; + val_array[c1] = val; + /* Update the row in the matrix */ + glp_set_mat_row(p->prob, row, c_elems, ind_array, val_array); + } + + GNUNET_free(ind_array); + GNUNET_free(val_array); return res; } @@ -854,83 +874,89 @@ mlp_create_problem_update_value (struct MLP_Problem *p, * @param line calling line for debbuging */ static void -mlp_create_problem_set_value (struct MLP_Problem *p, - int row, int col, double val, - int line) +mlp_create_problem_set_value(struct MLP_Problem *p, + int row, int col, double val, + int line) { if ((p->ci) >= p->num_elements) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: line %u: Request for index %u bigger than array size of %u\n", - line, p->ci + 1, p->num_elements); - GNUNET_break (0); - return; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "[P]: line %u: Request for index %u bigger than array size of %u\n", + line, p->ci + 1, p->num_elements); + GNUNET_break(0); + return; + } if ((0 == row) || (0 == col)) - { - GNUNET_break (0); - LOG (GNUNET_ERROR_TYPE_ERROR, "[P]: Invalid call from line %u: row = %u, col = %u\n", - line, row, col); - } - p->ia[p->ci] = row ; + { + GNUNET_break(0); + LOG(GNUNET_ERROR_TYPE_ERROR, "[P]: Invalid call from line %u: row = %u, col = %u\n", + line, row, col); + } + p->ia[p->ci] = row; p->ja[p->ci] = col; p->ar[p->ci] = val; #if DEBUG_MLP_PROBLEM_CREATION - LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: line %u: Set value [%u,%u] in index %u == %.2f\n", + LOG(GNUNET_ERROR_TYPE_DEBUG, "[P]: line %u: Set value [%u,%u] in index %u == %.2f\n", line, p->ia[p->ci], p->ja[p->ci], p->ci, p->ar[p->ci]); #endif p->ci++; } static int -mlp_create_problem_create_column (struct MLP_Problem *p, char *name, - unsigned int type, unsigned int bound, double lb, double ub, - double coef) +mlp_create_problem_create_column(struct MLP_Problem *p, char *name, + unsigned int type, unsigned int bound, double lb, double ub, + double coef) { - int col = glp_add_cols (p->prob, 1); - glp_set_col_name (p->prob, col, name); - glp_set_col_bnds (p->prob, col, bound, lb, ub); - glp_set_col_kind (p->prob, col, type); - glp_set_obj_coef (p->prob, col, coef); + int col = glp_add_cols(p->prob, 1); + + glp_set_col_name(p->prob, col, name); + glp_set_col_bnds(p->prob, col, bound, lb, ub); + glp_set_col_kind(p->prob, col, type); + glp_set_obj_coef(p->prob, col, coef); #if DEBUG_MLP_PROBLEM_CREATION - LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: Added column [%u] `%s': %.2f\n", + LOG(GNUNET_ERROR_TYPE_DEBUG, "[P]: Added column [%u] `%s': %.2f\n", col, name, coef); #endif return col; } static int -mlp_create_problem_create_constraint (struct MLP_Problem *p, char *name, - unsigned int bound, double lb, double ub) +mlp_create_problem_create_constraint(struct MLP_Problem *p, char *name, + unsigned int bound, double lb, double ub) { char * op; - int row = glp_add_rows (p->prob, 1); + int row = glp_add_rows(p->prob, 1); + /* set row name */ - glp_set_row_name (p->prob, row, name); + glp_set_row_name(p->prob, row, name); /* set row bounds: <= 0 */ - glp_set_row_bnds (p->prob, row, bound, lb, ub); + glp_set_row_bnds(p->prob, row, bound, lb, ub); switch (bound) - { + { case GLP_UP: - GNUNET_asprintf(&op, "-inf <= x <= %.2f", ub); - break; + GNUNET_asprintf(&op, "-inf <= x <= %.2f", ub); + break; + case GLP_DB: - GNUNET_asprintf(&op, "%.2f <= x <= %.2f", lb, ub); - break; + GNUNET_asprintf(&op, "%.2f <= x <= %.2f", lb, ub); + break; + case GLP_FX: - GNUNET_asprintf(&op, "%.2f == x == %.2f", lb, ub); - break; + GNUNET_asprintf(&op, "%.2f == x == %.2f", lb, ub); + break; + case GLP_LO: - GNUNET_asprintf(&op, "%.2f <= x <= inf", lb); - break; + GNUNET_asprintf(&op, "%.2f <= x <= inf", lb); + break; + default: - GNUNET_asprintf(&op, "ERROR"); - break; - } + GNUNET_asprintf(&op, "ERROR"); + break; + } #if DEBUG_MLP_PROBLEM_CREATION - LOG (GNUNET_ERROR_TYPE_DEBUG, "[P]: Added row [%u] `%s': %s\n", - row, name, op); + LOG(GNUNET_ERROR_TYPE_DEBUG, "[P]: Added row [%u] `%s': %s\n", + row, name, op); #endif - GNUNET_free (op); + GNUNET_free(op); return row; } @@ -942,9 +968,9 @@ mlp_create_problem_create_constraint (struct MLP_Problem *p, char *name, * - Set address dependent entries in problem matrix as well */ static int -mlp_create_problem_add_address_information (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +mlp_create_problem_add_address_information(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct GAS_MLP_Handle *mlp = cls; struct MLP_Problem *p = &mlp->p; @@ -964,63 +990,63 @@ mlp_create_problem_add_address_information (void *cls, mlpi = address->solver_information; if (NULL == mlpi) - { - fprintf (stderr, "%s %p\n",GNUNET_i2s (&address->peer), address); - GNUNET_break (0); + { + fprintf(stderr, "%s %p\n", GNUNET_i2s(&address->peer), address); + GNUNET_break(0); return GNUNET_OK; - } + } addr_net = address->properties.scope; for (addr_net_index = 0; addr_net_index < GNUNET_NT_COUNT; addr_net_index++) - { - if (mlp->pv.quota_index[addr_net_index] == addr_net) - break; - } + { + if (mlp->pv.quota_index[addr_net_index] == addr_net) + break; + } if (addr_net_index >= GNUNET_NT_COUNT) - { - GNUNET_break (0); - return GNUNET_OK; - } + { + GNUNET_break(0); + return GNUNET_OK; + } max_quota = 0; for (c = 0; c < GNUNET_NT_COUNT; c++) - { - if (mlp->pv.quota_out[c] > max_quota) - max_quota = mlp->pv.quota_out[c]; - if (mlp->pv.quota_in[c] > max_quota) - max_quota = mlp->pv.quota_in[c]; - } + { + if (mlp->pv.quota_out[c] > max_quota) + max_quota = mlp->pv.quota_out[c]; + if (mlp->pv.quota_in[c] > max_quota) + max_quota = mlp->pv.quota_in[c]; + } if (max_quota > mlp->pv.BIG_M) - cur_bigm = (double) mlp->pv.BIG_M; + cur_bigm = (double)mlp->pv.BIG_M; else cur_bigm = max_quota; /* Get peer */ - peer = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, key); - GNUNET_assert (NULL != peer); + peer = GNUNET_CONTAINER_multipeermap_get(mlp->requested_peers, key); + GNUNET_assert(NULL != peer); if (peer->processed == GNUNET_NO) - { + { /* Add peer dependent constraints */ /* Add c2) One address active per peer */ GNUNET_asprintf(&name, "c2_%s", GNUNET_i2s(&address->peer)); - peer->r_c2 = mlp_create_problem_create_constraint (p, name, GLP_FX, 1.0, 1.0); - GNUNET_free (name); + peer->r_c2 = mlp_create_problem_create_constraint(p, name, GLP_FX, 1.0, 1.0); + GNUNET_free(name); if (GNUNET_NO == mlp->opt_dbg_feasibility_only) - { - if (GNUNET_YES == mlp->opt_dbg_optimize_relativity) { - /* Add c9) Relativity */ - GNUNET_asprintf(&name, "c9_%s", GNUNET_i2s(&address->peer)); - peer->r_c9 = mlp_create_problem_create_constraint (p, name, GLP_LO, 0.0, 0.0); - GNUNET_free (name); - /* c9) set coefficient */ - mlp_create_problem_set_value (p, peer->r_c9, p->c_r, -peer->f , __LINE__); + if (GNUNET_YES == mlp->opt_dbg_optimize_relativity) + { + /* Add c9) Relativity */ + GNUNET_asprintf(&name, "c9_%s", GNUNET_i2s(&address->peer)); + peer->r_c9 = mlp_create_problem_create_constraint(p, name, GLP_LO, 0.0, 0.0); + GNUNET_free(name); + /* c9) set coefficient */ + mlp_create_problem_set_value(p, peer->r_c9, p->c_r, -peer->f, __LINE__); + } } - } peer->processed = GNUNET_YES; - } + } /* Reset addresses' solver information */ mlpi->c_b = 0; @@ -1030,47 +1056,47 @@ mlp_create_problem_add_address_information (void *cls, mlpi->r_c3 = 0; /* Add bandwidth column */ - GNUNET_asprintf (&name, "b_%s_%s_%p", GNUNET_i2s (&address->peer), address->plugin, address); + GNUNET_asprintf(&name, "b_%s_%s_%p", GNUNET_i2s(&address->peer), address->plugin, address); if (GNUNET_NO == mlp->opt_dbg_feasibility_only) - { - mlpi->c_b = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, 0.0); - } + { + mlpi->c_b = mlp_create_problem_create_column(p, name, GLP_CV, GLP_LO, 0.0, 0.0, 0.0); + } else - { - /* Maximize for bandwidth assignment in feasibility testing */ - mlpi->c_b = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, 1.0); - } - GNUNET_free (name); + { + /* Maximize for bandwidth assignment in feasibility testing */ + mlpi->c_b = mlp_create_problem_create_column(p, name, GLP_CV, GLP_LO, 0.0, 0.0, 1.0); + } + GNUNET_free(name); /* Add address active column */ - GNUNET_asprintf (&name, "n_%s_%s_%p", GNUNET_i2s (&address->peer), address->plugin, address); - mlpi->c_n = mlp_create_problem_create_column (p, name, GLP_IV, GLP_DB, 0.0, 1.0, 0.0); - GNUNET_free (name); + GNUNET_asprintf(&name, "n_%s_%s_%p", GNUNET_i2s(&address->peer), address->plugin, address); + mlpi->c_n = mlp_create_problem_create_column(p, name, GLP_IV, GLP_DB, 0.0, 1.0, 0.0); + GNUNET_free(name); /* Add address dependent constraints */ /* Add c1) bandwidth capping: b_t + (-M) * n_t <= 0 */ GNUNET_asprintf(&name, "c1_%s_%s_%p", GNUNET_i2s(&address->peer), address->plugin, address); - mlpi->r_c1 = mlp_create_problem_create_constraint (p, name, GLP_UP, 0.0, 0.0); - GNUNET_free (name); + mlpi->r_c1 = mlp_create_problem_create_constraint(p, name, GLP_UP, 0.0, 0.0); + GNUNET_free(name); /* c1) set b = 1 coefficient */ - mlp_create_problem_set_value (p, mlpi->r_c1, mlpi->c_b, 1, __LINE__); + mlp_create_problem_set_value(p, mlpi->r_c1, mlpi->c_b, 1, __LINE__); /* c1) set n = - min (M, quota) coefficient */ - cur_bigm = (double) mlp->pv.quota_out[addr_net_index]; + cur_bigm = (double)mlp->pv.quota_out[addr_net_index]; if (cur_bigm > mlp->pv.BIG_M) - cur_bigm = (double) mlp->pv.BIG_M; - mlp_create_problem_set_value (p, mlpi->r_c1, mlpi->c_n, -cur_bigm, __LINE__); + cur_bigm = (double)mlp->pv.BIG_M; + mlp_create_problem_set_value(p, mlpi->r_c1, mlpi->c_n, -cur_bigm, __LINE__); /* Add constraint c 3) minimum bandwidth * b_t + (-n_t * b_min) >= 0 * */ GNUNET_asprintf(&name, "c3_%s_%s_%p", GNUNET_i2s(&address->peer), address->plugin, address); - mlpi->r_c3 = mlp_create_problem_create_constraint (p, name, GLP_LO, 0.0, 0.0); - GNUNET_free (name); + mlpi->r_c3 = mlp_create_problem_create_constraint(p, name, GLP_LO, 0.0, 0.0); + GNUNET_free(name); /* c3) set b = 1 coefficient */ - mlp_create_problem_set_value (p, mlpi->r_c3, mlpi->c_b, 1, __LINE__); + mlp_create_problem_set_value(p, mlpi->r_c3, mlpi->c_b, 1, __LINE__); /* c3) set n = -b_min coefficient */ - mlp_create_problem_set_value (p, mlpi->r_c3, mlpi->c_n, - ((double )mlp->pv.b_min), __LINE__); + mlp_create_problem_set_value(p, mlpi->r_c3, mlpi->c_n, -((double )mlp->pv.b_min), __LINE__); /* Set coefficient entries in invariant rows */ @@ -1078,41 +1104,41 @@ mlp_create_problem_add_address_information (void *cls, /* Feasbility */ /* c 4) minimum connections */ - mlp_create_problem_set_value (p, p->r_c4, mlpi->c_n, 1, __LINE__); + mlp_create_problem_set_value(p, p->r_c4, mlpi->c_n, 1, __LINE__); /* c 2) 1 address peer peer */ - mlp_create_problem_set_value (p, peer->r_c2, mlpi->c_n, 1, __LINE__); + mlp_create_problem_set_value(p, peer->r_c2, mlpi->c_n, 1, __LINE__); /* c 10) obey network specific quotas * (1)*b_1 + ... + (1)*b_m <= quota_n */ - mlp_create_problem_set_value (p, p->r_quota[addr_net_index], mlpi->c_b, 1, __LINE__); + mlp_create_problem_set_value(p, p->r_quota[addr_net_index], mlpi->c_b, 1, __LINE__); /* Optimality */ if (GNUNET_NO == mlp->opt_dbg_feasibility_only) - { - /* c 6) maximize diversity */ - mlp_create_problem_set_value (p, p->r_c6, mlpi->c_n, 1, __LINE__); - /* c 9) relativity */ - if (GNUNET_YES == mlp->opt_dbg_optimize_relativity) - mlp_create_problem_set_value (p, peer->r_c9, mlpi->c_b, 1, __LINE__); - /* c 8) utility */ - if (GNUNET_YES == mlp->opt_dbg_optimize_utility) - mlp_create_problem_set_value (p, p->r_c8, mlpi->c_b, 1, __LINE__); - /* c 7) Optimize quality */ - /* For all quality metrics, set quality of this address */ - if (GNUNET_YES == mlp->opt_dbg_optimize_quality) - { - mlp_create_problem_set_value (p, - p->r_q[RQ_QUALITY_METRIC_DELAY], - mlpi->c_b, - address->norm_delay.norm, - __LINE__); - mlp_create_problem_set_value (p, - p->r_q[RQ_QUALITY_METRIC_DISTANCE], - mlpi->c_b, - address->norm_distance.norm, - __LINE__); - } - } + { + /* c 6) maximize diversity */ + mlp_create_problem_set_value(p, p->r_c6, mlpi->c_n, 1, __LINE__); + /* c 9) relativity */ + if (GNUNET_YES == mlp->opt_dbg_optimize_relativity) + mlp_create_problem_set_value(p, peer->r_c9, mlpi->c_b, 1, __LINE__); + /* c 8) utility */ + if (GNUNET_YES == mlp->opt_dbg_optimize_utility) + mlp_create_problem_set_value(p, p->r_c8, mlpi->c_b, 1, __LINE__); + /* c 7) Optimize quality */ + /* For all quality metrics, set quality of this address */ + if (GNUNET_YES == mlp->opt_dbg_optimize_quality) + { + mlp_create_problem_set_value(p, + p->r_q[RQ_QUALITY_METRIC_DELAY], + mlpi->c_b, + address->norm_delay.norm, + __LINE__); + mlp_create_problem_set_value(p, + p->r_q[RQ_QUALITY_METRIC_DISTANCE], + mlpi->c_b, + address->norm_distance.norm, + __LINE__); + } + } return GNUNET_OK; } @@ -1122,7 +1148,7 @@ mlp_create_problem_add_address_information (void *cls, * Create the invariant columns c4, c6, c10, c8, c7 */ static void -mlp_create_problem_add_invariant_rows (struct GAS_MLP_Handle *mlp, struct MLP_Problem *p) +mlp_create_problem_add_invariant_rows(struct GAS_MLP_Handle *mlp, struct MLP_Problem *p) { int c; @@ -1130,55 +1156,55 @@ mlp_create_problem_add_invariant_rows (struct GAS_MLP_Handle *mlp, struct MLP_Pr /* Row for c4) minimum connection */ /* Number of minimum connections is min(|Peers|, n_min) */ - p->r_c4 = mlp_create_problem_create_constraint (p, "c4", GLP_LO, (mlp->pv.n_min > p->num_peers) ? p->num_peers : mlp->pv.n_min, 0.0); + p->r_c4 = mlp_create_problem_create_constraint(p, "c4", GLP_LO, (mlp->pv.n_min > p->num_peers) ? p->num_peers : mlp->pv.n_min, 0.0); /* Rows for c 10) Enforce network quotas */ for (c = 0; c < GNUNET_NT_COUNT; c++) - { - char * text; - GNUNET_asprintf(&text, "c10_quota_ats_%s", - GNUNET_NT_to_string(mlp->pv.quota_index[c])); - p->r_quota[c] = mlp_create_problem_create_constraint (p, text, GLP_DB, 0.0, mlp->pv.quota_out[c]); - GNUNET_free (text); - } + { + char * text; + GNUNET_asprintf(&text, "c10_quota_ats_%s", + GNUNET_NT_to_string(mlp->pv.quota_index[c])); + p->r_quota[c] = mlp_create_problem_create_constraint(p, text, GLP_DB, 0.0, mlp->pv.quota_out[c]); + GNUNET_free(text); + } /* Optimality */ if (GNUNET_NO == mlp->opt_dbg_feasibility_only) - { - char *name; - /* Add row for c6) Maximize for diversity */ - if (GNUNET_YES == mlp->opt_dbg_optimize_diversity) { - p->r_c6 = mlp_create_problem_create_constraint (p, "c6", GLP_FX, 0.0, 0.0); - /* Set c6 ) Setting -D */ - mlp_create_problem_set_value (p, p->r_c6, p->c_d, -1, __LINE__); - } + char *name; + /* Add row for c6) Maximize for diversity */ + if (GNUNET_YES == mlp->opt_dbg_optimize_diversity) + { + p->r_c6 = mlp_create_problem_create_constraint(p, "c6", GLP_FX, 0.0, 0.0); + /* Set c6 ) Setting -D */ + mlp_create_problem_set_value(p, p->r_c6, p->c_d, -1, __LINE__); + } - /* Adding rows for c 8) Maximize utility */ - if (GNUNET_YES == mlp->opt_dbg_optimize_utility) - { - p->r_c8 = mlp_create_problem_create_constraint (p, "c8", GLP_FX, 0.0, 0.0); - /* -u */ - mlp_create_problem_set_value (p, p->r_c8, p->c_u, -1, __LINE__); - } + /* Adding rows for c 8) Maximize utility */ + if (GNUNET_YES == mlp->opt_dbg_optimize_utility) + { + p->r_c8 = mlp_create_problem_create_constraint(p, "c8", GLP_FX, 0.0, 0.0); + /* -u */ + mlp_create_problem_set_value(p, p->r_c8, p->c_u, -1, __LINE__); + } - /* For all quality metrics: - * c 7) Maximize quality, austerity */ - if (GNUNET_YES == mlp->opt_dbg_optimize_quality) - { - for (c = 0; c < mlp->pv.m_q; c++) - { - GNUNET_asprintf (&name, - "c7_q%i_%s", c, - print_quality_type (c)); - p->r_q[c] = mlp_create_problem_create_constraint (p, name, GLP_FX, 0.0, 0.0); - GNUNET_free (name); - mlp_create_problem_set_value (p, - p->r_q[c], - p->c_q[c], -1, __LINE__); - } + /* For all quality metrics: + * c 7) Maximize quality, austerity */ + if (GNUNET_YES == mlp->opt_dbg_optimize_quality) + { + for (c = 0; c < mlp->pv.m_q; c++) + { + GNUNET_asprintf(&name, + "c7_q%i_%s", c, + print_quality_type(c)); + p->r_q[c] = mlp_create_problem_create_constraint(p, name, GLP_FX, 0.0, 0.0); + GNUNET_free(name); + mlp_create_problem_set_value(p, + p->r_q[c], + p->c_q[c], -1, __LINE__); + } + } } - } } @@ -1186,36 +1212,36 @@ mlp_create_problem_add_invariant_rows (struct GAS_MLP_Handle *mlp, struct MLP_Pr * Create the invariant columns d, u, r, q0 ... qm */ static void -mlp_create_problem_add_invariant_columns (struct GAS_MLP_Handle *mlp, struct MLP_Problem *p) +mlp_create_problem_add_invariant_columns(struct GAS_MLP_Handle *mlp, struct MLP_Problem *p) { if (GNUNET_NO == mlp->opt_dbg_feasibility_only) - { - char *name; - int c; + { + char *name; + int c; - /* Diversity d column */ - if (GNUNET_YES == mlp->opt_dbg_optimize_diversity) - p->c_d = mlp_create_problem_create_column (p, "d", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_D); + /* Diversity d column */ + if (GNUNET_YES == mlp->opt_dbg_optimize_diversity) + p->c_d = mlp_create_problem_create_column(p, "d", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_D); - /* Utilization u column */ - if (GNUNET_YES == mlp->opt_dbg_optimize_utility) - p->c_u = mlp_create_problem_create_column (p, "u", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_U); + /* Utilization u column */ + if (GNUNET_YES == mlp->opt_dbg_optimize_utility) + p->c_u = mlp_create_problem_create_column(p, "u", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_U); - /* Relativity r column */ - if (GNUNET_YES == mlp->opt_dbg_optimize_relativity) - p->c_r = mlp_create_problem_create_column (p, "r", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_R); + /* Relativity r column */ + if (GNUNET_YES == mlp->opt_dbg_optimize_relativity) + p->c_r = mlp_create_problem_create_column(p, "r", GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_R); - /* Quality metric columns */ - if (GNUNET_YES == mlp->opt_dbg_optimize_quality) - { - for (c = 0; c < mlp->pv.m_q; c++) - { - GNUNET_asprintf (&name, "q_%u", c); - p->c_q[c] = mlp_create_problem_create_column (p, name, GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_Q[c]); - GNUNET_free (name); - } + /* Quality metric columns */ + if (GNUNET_YES == mlp->opt_dbg_optimize_quality) + { + for (c = 0; c < mlp->pv.m_q; c++) + { + GNUNET_asprintf(&name, "q_%u", c); + p->c_q[c] = mlp_create_problem_create_column(p, name, GLP_CV, GLP_LO, 0.0, 0.0, mlp->pv.co_Q[c]); + GNUNET_free(name); + } + } } - } } @@ -1226,73 +1252,73 @@ mlp_create_problem_add_invariant_columns (struct GAS_MLP_Handle *mlp, struct MLP * @return #GNUNET_OK or #GNUNET_SYSERR */ static int -mlp_create_problem (struct GAS_MLP_Handle *mlp) +mlp_create_problem(struct GAS_MLP_Handle *mlp) { struct MLP_Problem *p = &mlp->p; int res = GNUNET_OK; - GNUNET_assert (p->prob == NULL); - GNUNET_assert (p->ia == NULL); - GNUNET_assert (p->ja == NULL); - GNUNET_assert (p->ar == NULL); + GNUNET_assert(p->prob == NULL); + GNUNET_assert(p->ia == NULL); + GNUNET_assert(p->ja == NULL); + GNUNET_assert(p->ar == NULL); /* Reset MLP problem struct */ /* create the glpk problem */ - p->prob = glp_create_prob (); - GNUNET_assert (NULL != p->prob); - p->num_peers = mlp_create_problem_count_peers (mlp->requested_peers, mlp->env->addresses); - p->num_addresses = mlp_create_problem_count_addresses (mlp->requested_peers, - mlp->env->addresses); + p->prob = glp_create_prob(); + GNUNET_assert(NULL != p->prob); + p->num_peers = mlp_create_problem_count_peers(mlp->requested_peers, mlp->env->addresses); + p->num_addresses = mlp_create_problem_count_addresses(mlp->requested_peers, + mlp->env->addresses); /* Create problem matrix: 10 * #addresses + #q * #addresses + #q, + #peer + 2 + 1 */ p->num_elements = (10 * p->num_addresses + mlp->pv.m_q * p->num_addresses + - mlp->pv.m_q + p->num_peers + 2 + 1); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Rebuilding problem for %u peer(s) and %u addresse(s) and %u quality metrics == %u elements\n", - p->num_peers, - p->num_addresses, - mlp->pv.m_q, - p->num_elements); + mlp->pv.m_q + p->num_peers + 2 + 1); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Rebuilding problem for %u peer(s) and %u addresse(s) and %u quality metrics == %u elements\n", + p->num_peers, + p->num_addresses, + mlp->pv.m_q, + p->num_elements); /* Set a problem name */ - glp_set_prob_name (p->prob, "GNUnet ATS bandwidth distribution"); + glp_set_prob_name(p->prob, "GNUnet ATS bandwidth distribution"); /* Set optimization direction to maximize */ - glp_set_obj_dir (p->prob, GLP_MAX); + glp_set_obj_dir(p->prob, GLP_MAX); /* Create problem matrix */ /* last +1 caused by glpk index starting with one: [1..elements]*/ p->ci = 1; /* row index */ - p->ia = GNUNET_malloc (p->num_elements * sizeof (int)); + p->ia = GNUNET_malloc(p->num_elements * sizeof(int)); /* column index */ - p->ja = GNUNET_malloc (p->num_elements * sizeof (int)); + p->ja = GNUNET_malloc(p->num_elements * sizeof(int)); /* coefficient */ - p->ar = GNUNET_malloc (p->num_elements * sizeof (double)); + p->ar = GNUNET_malloc(p->num_elements * sizeof(double)); if ((NULL == p->ia) || (NULL == p->ja) || (NULL == p->ar)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Problem size too large, cannot allocate memory!\n")); + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Problem size too large, cannot allocate memory!\n")); return GNUNET_SYSERR; - } + } /* Adding invariant columns */ - mlp_create_problem_add_invariant_columns (mlp, p); + mlp_create_problem_add_invariant_columns(mlp, p); /* Adding address independent constraint rows */ - mlp_create_problem_add_invariant_rows (mlp, p); + mlp_create_problem_add_invariant_rows(mlp, p); /* Adding address dependent columns constraint rows */ - GNUNET_CONTAINER_multipeermap_iterate (mlp->env->addresses, - &mlp_create_problem_add_address_information, - mlp); + GNUNET_CONTAINER_multipeermap_iterate(mlp->env->addresses, + &mlp_create_problem_add_address_information, + mlp); /* Load the matrix */ - LOG (GNUNET_ERROR_TYPE_DEBUG, "Loading matrix\n"); - glp_load_matrix(p->prob, (p->ci)-1, p->ia, p->ja, p->ar); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Loading matrix\n"); + glp_load_matrix(p->prob, (p->ci) - 1, p->ia, p->ja, p->ar); if (GNUNET_YES == mlp->opt_dbg_autoscale_problem) - { - glp_scale_prob (p->prob, GLP_SF_AUTO); - } + { + glp_scale_prob(p->prob, GLP_SF_AUTO); + } return res; } @@ -1305,34 +1331,37 @@ mlp_create_problem (struct GAS_MLP_Handle *mlp) * @return #GNUNET_OK if could be solved, #GNUNET_SYSERR on failure */ static int -mlp_solve_lp_problem (struct GAS_MLP_Handle *mlp) +mlp_solve_lp_problem(struct GAS_MLP_Handle *mlp) { int res = 0; int res_status = 0; + res = glp_simplex(mlp->p.prob, &mlp->control_param_lp); if (0 == res) LOG(GNUNET_ERROR_TYPE_DEBUG, "Solving LP problem: %s\n", - mlp_solve_to_string (res)); + mlp_solve_to_string(res)); else LOG(GNUNET_ERROR_TYPE_DEBUG, "Solving LP problem failed: %s\n", - mlp_solve_to_string (res)); + mlp_solve_to_string(res)); /* Analyze problem status */ - res_status = glp_get_status (mlp->p.prob); - switch (res_status) { + res_status = glp_get_status(mlp->p.prob); + switch (res_status) + { case GLP_OPT: /* solution is optimal */ - LOG (GNUNET_ERROR_TYPE_INFO, + LOG(GNUNET_ERROR_TYPE_INFO, "Solving LP problem: %s, %s\n", mlp_solve_to_string(res), mlp_status_to_string(res_status)); return GNUNET_OK; + default: - LOG (GNUNET_ERROR_TYPE_ERROR, + LOG(GNUNET_ERROR_TYPE_ERROR, "Solving LP problem failed: %s %s\n", mlp_solve_to_string(res), mlp_status_to_string(res_status)); return GNUNET_SYSERR; - } + } } @@ -1345,9 +1374,9 @@ mlp_solve_lp_problem (struct GAS_MLP_Handle *mlp) * @return #GNUNET_OK to continue */ static int -mlp_propagate_results (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +mlp_propagate_results(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct GAS_MLP_Handle *mlp = cls; struct ATS_Address *address; @@ -1357,27 +1386,27 @@ mlp_propagate_results (void *cls, double mlp_use = MLP_NaN; /* Check if we have to add this peer due to a pending request */ - if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (mlp->requested_peers, - key)) - { - return GNUNET_OK; - } + if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains(mlp->requested_peers, + key)) + { + return GNUNET_OK; + } address = value; - GNUNET_assert (address->solver_information != NULL); + GNUNET_assert(address->solver_information != NULL); mlpi = address->solver_information; mlp_bw_in = glp_mip_col_val(mlp->p.prob, mlpi->c_b);/* FIXME */ - if (mlp_bw_in > (double) UINT32_MAX) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, "Overflow in assigned bandwidth, reducing ...\n" ); - mlp_bw_in = (double) UINT32_MAX; - } + if (mlp_bw_in > (double)UINT32_MAX) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "Overflow in assigned bandwidth, reducing ...\n"); + mlp_bw_in = (double)UINT32_MAX; + } mlp_bw_out = glp_mip_col_val(mlp->p.prob, mlpi->c_b); - if (mlp_bw_out > (double) UINT32_MAX) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, "Overflow in assigned bandwidth, reducing ...\n" ); - mlp_bw_out = (double) UINT32_MAX; - } + if (mlp_bw_out > (double)UINT32_MAX) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "Overflow in assigned bandwidth, reducing ...\n"); + mlp_bw_out = (double)UINT32_MAX; + } mlp_use = glp_mip_col_val(mlp->p.prob, mlpi->c_n); /* @@ -1388,147 +1417,154 @@ mlp_propagate_results (void *cls, */ if (GLP_YES == mlp_use) - { - /* This address was selected by the solver to be used */ - mlpi->n = GNUNET_YES; - if (GNUNET_NO == address->active) - { - /* Address was not used before, enabling address */ - LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : enabling address\n", - (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out); - address->active = GNUNET_YES; - address->assigned_bw_in = mlp_bw_in; - mlpi->b_in = mlp_bw_in; - address->assigned_bw_out = mlp_bw_out; - mlpi->b_out = mlp_bw_out; - if ((NULL == mlp->exclude_peer) || (0 != GNUNET_memcmp (&address->peer, mlp->exclude_peer))) - mlp->env->bandwidth_changed_cb (mlp->env->cls, address); - return GNUNET_OK; - } - else if (GNUNET_YES == address->active) { - /* Address was used before, check for bandwidth change */ - if ((mlp_bw_out != address->assigned_bw_out) || - (mlp_bw_in != address->assigned_bw_in)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : bandwidth changed\n", - (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out); + /* This address was selected by the solver to be used */ + mlpi->n = GNUNET_YES; + if (GNUNET_NO == address->active) + { + /* Address was not used before, enabling address */ + LOG(GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : enabling address\n", + (1 == mlp_use) ? "[x]" : "[ ]", mlp_bw_out); + address->active = GNUNET_YES; address->assigned_bw_in = mlp_bw_in; mlpi->b_in = mlp_bw_in; address->assigned_bw_out = mlp_bw_out; mlpi->b_out = mlp_bw_out; - if ((NULL == mlp->exclude_peer) || (0 != GNUNET_memcmp (&address->peer, mlp->exclude_peer))) - mlp->env->bandwidth_changed_cb (mlp->env->cls, address); + if ((NULL == mlp->exclude_peer) || (0 != GNUNET_memcmp(&address->peer, mlp->exclude_peer))) + mlp->env->bandwidth_changed_cb(mlp->env->cls, address); return GNUNET_OK; - } + } + else if (GNUNET_YES == address->active) + { + /* Address was used before, check for bandwidth change */ + if ((mlp_bw_out != address->assigned_bw_out) || + (mlp_bw_in != address->assigned_bw_in)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : bandwidth changed\n", + (1 == mlp_use) ? "[x]" : "[ ]", mlp_bw_out); + address->assigned_bw_in = mlp_bw_in; + mlpi->b_in = mlp_bw_in; + address->assigned_bw_out = mlp_bw_out; + mlpi->b_out = mlp_bw_out; + if ((NULL == mlp->exclude_peer) || (0 != GNUNET_memcmp(&address->peer, mlp->exclude_peer))) + mlp->env->bandwidth_changed_cb(mlp->env->cls, address); + return GNUNET_OK; + } + } + else + GNUNET_break(0); } - else - GNUNET_break (0); - } else if (GLP_NO == mlp_use) - { - /* This address was selected by the solver to be not used */ - mlpi->n = GNUNET_NO; - if (GNUNET_NO == address->active) - { - /* Address was not used before, nothing to do */ - LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : no change\n", - (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out); - return GNUNET_OK; - } - else if (GNUNET_YES == address->active) - { - /* Address was used before, disabling address */ - LOG (GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : disabling address\n", - (1 == mlp_use) ? "[x]": "[ ]", mlp_bw_out); - address->active = GNUNET_NO; - /* Set bandwidth to 0 */ - address->assigned_bw_in = 0; - mlpi->b_in = 0; - address->assigned_bw_out = 0; - mlpi->b_out = 0; - return GNUNET_OK; + { + /* This address was selected by the solver to be not used */ + mlpi->n = GNUNET_NO; + if (GNUNET_NO == address->active) + { + /* Address was not used before, nothing to do */ + LOG(GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : no change\n", + (1 == mlp_use) ? "[x]" : "[ ]", mlp_bw_out); + return GNUNET_OK; + } + else if (GNUNET_YES == address->active) + { + /* Address was used before, disabling address */ + LOG(GNUNET_ERROR_TYPE_DEBUG, "%s %.2f : disabling address\n", + (1 == mlp_use) ? "[x]" : "[ ]", mlp_bw_out); + address->active = GNUNET_NO; + /* Set bandwidth to 0 */ + address->assigned_bw_in = 0; + mlpi->b_in = 0; + address->assigned_bw_out = 0; + mlpi->b_out = 0; + return GNUNET_OK; + } + else + GNUNET_break(0); } - else - GNUNET_break (0); - } else - GNUNET_break (0); + GNUNET_break(0); return GNUNET_OK; } static void -notify (struct GAS_MLP_Handle *mlp, - enum GAS_Solver_Operation op, - enum GAS_Solver_Status stat, - enum GAS_Solver_Additional_Information add) +notify(struct GAS_MLP_Handle *mlp, + enum GAS_Solver_Operation op, + enum GAS_Solver_Status stat, + enum GAS_Solver_Additional_Information add) { - mlp->env->info_cb (mlp->env->cls, - op, - stat, - add); + mlp->env->info_cb(mlp->env->cls, + op, + stat, + add); } static void -mlp_branch_and_cut_cb (glp_tree *tree, void *info) +mlp_branch_and_cut_cb(glp_tree *tree, void *info) { struct GAS_MLP_Handle *mlp = info; double mlp_obj = 0; - switch (glp_ios_reason (tree)) - { + switch (glp_ios_reason(tree)) + { case GLP_ISELECT: - /* Do nothing here */ + /* Do nothing here */ break; + case GLP_IPREPRO: - /* Do nothing here */ + /* Do nothing here */ break; + case GLP_IROWGEN: - /* Do nothing here */ + /* Do nothing here */ break; + case GLP_IHEUR: - /* Do nothing here */ + /* Do nothing here */ break; + case GLP_ICUTGEN: - /* Do nothing here */ + /* Do nothing here */ break; + case GLP_IBRANCH: - /* Do nothing here */ + /* Do nothing here */ break; + case GLP_IBINGO: - /* A better solution was found */ - mlp->ps.mlp_gap = glp_ios_mip_gap (tree); - mlp_obj = glp_mip_obj_val (mlp->p.prob); + /* A better solution was found */ + mlp->ps.mlp_gap = glp_ios_mip_gap(tree); + mlp_obj = glp_mip_obj_val(mlp->p.prob); mlp->ps.lp_mlp_gap = (abs(mlp_obj - mlp->ps.lp_objective_value)) / (abs(mlp_obj) + DBL_EPSILON); - LOG (GNUNET_ERROR_TYPE_INFO, + LOG(GNUNET_ERROR_TYPE_INFO, "Found better integer solution, current gaps: %.3f <= %.3f, %.3f <= %.3f\n", mlp->ps.mlp_gap, mlp->pv.mip_gap, mlp->ps.lp_mlp_gap, mlp->pv.lp_mip_gap); if (mlp->ps.mlp_gap <= mlp->pv.mip_gap) - { - LOG (GNUNET_ERROR_TYPE_INFO, - "Current LP/MLP gap of %.3f smaller than tolerated gap of %.3f, terminating search\n", - mlp->ps.lp_mlp_gap, mlp->pv.lp_mip_gap); - glp_ios_terminate (tree); - } + { + LOG(GNUNET_ERROR_TYPE_INFO, + "Current LP/MLP gap of %.3f smaller than tolerated gap of %.3f, terminating search\n", + mlp->ps.lp_mlp_gap, mlp->pv.lp_mip_gap); + glp_ios_terminate(tree); + } if (mlp->ps.lp_mlp_gap <= mlp->pv.lp_mip_gap) - { - LOG (GNUNET_ERROR_TYPE_INFO, - "Current LP/MLP gap of %.3f smaller than tolerated gap of %.3f, terminating search\n", - mlp->ps.lp_mlp_gap, mlp->pv.lp_mip_gap); - glp_ios_terminate (tree); - } + { + LOG(GNUNET_ERROR_TYPE_INFO, + "Current LP/MLP gap of %.3f smaller than tolerated gap of %.3f, terminating search\n", + mlp->ps.lp_mlp_gap, mlp->pv.lp_mip_gap); + glp_ios_terminate(tree); + } break; + default: break; - } + } //GNUNET_break (0); } @@ -1540,7 +1576,7 @@ mlp_branch_and_cut_cb (glp_tree *tree, void *info) * @return #GNUNET_OK if could be solved, #GNUNET_SYSERR on failure */ static int -GAS_mlp_solve_problem (void *solver) +GAS_mlp_solve_problem(void *solver) { struct GAS_MLP_Handle *mlp = solver; char *filename; @@ -1556,7 +1592,7 @@ GAS_mlp_solve_problem (void *solver) struct GNUNET_TIME_Relative dur_mlp; GNUNET_assert(NULL != solver); - dur_lp = GNUNET_TIME_UNIT_ZERO; + dur_lp = GNUNET_TIME_UNIT_ZERO; if (GNUNET_YES == mlp->stat_bulk_lock) { @@ -1564,7 +1600,7 @@ GAS_mlp_solve_problem (void *solver) return GNUNET_NO; } notify(mlp, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS, - (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); + (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); start_total = GNUNET_TIME_absolute_get(); if (0 == GNUNET_CONTAINER_multipeermap_size(mlp->requested_peers)) @@ -1586,32 +1622,32 @@ GAS_mlp_solve_problem (void *solver) return GNUNET_OK; } if (GNUNET_YES == mlp->stat_mlp_prob_changed) - { - LOG(GNUNET_ERROR_TYPE_DEBUG, "Problem size changed, rebuilding\n"); - notify(mlp, GAS_OP_SOLVE_SETUP_START, GAS_STAT_SUCCESS, GAS_INFO_FULL); - mlp_delete_problem (mlp); - if (GNUNET_SYSERR == mlp_create_problem (mlp)) - { - notify(mlp, GAS_OP_SOLVE_SETUP_STOP, GAS_STAT_FAIL, GAS_INFO_FULL); - return GNUNET_SYSERR; - } - notify(mlp, GAS_OP_SOLVE_SETUP_STOP, GAS_STAT_SUCCESS, GAS_INFO_FULL); - if (GNUNET_NO == mlp->opt_dbg_intopt_presolver) - { - mlp->control_param_lp.presolve = GLP_YES; /* LP presolver, we need lp solution */ - mlp->control_param_mlp.presolve = GNUNET_NO; /* No presolver, we have LP solution */ - } - else - { - mlp->control_param_lp.presolve = GNUNET_NO; /* LP presolver, we need lp solution */ - mlp->control_param_mlp.presolve = GLP_YES; /* No presolver, we have LP solution */ - dur_lp = GNUNET_TIME_UNIT_ZERO; - } - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "Problem size changed, rebuilding\n"); + notify(mlp, GAS_OP_SOLVE_SETUP_START, GAS_STAT_SUCCESS, GAS_INFO_FULL); + mlp_delete_problem(mlp); + if (GNUNET_SYSERR == mlp_create_problem(mlp)) + { + notify(mlp, GAS_OP_SOLVE_SETUP_STOP, GAS_STAT_FAIL, GAS_INFO_FULL); + return GNUNET_SYSERR; + } + notify(mlp, GAS_OP_SOLVE_SETUP_STOP, GAS_STAT_SUCCESS, GAS_INFO_FULL); + if (GNUNET_NO == mlp->opt_dbg_intopt_presolver) + { + mlp->control_param_lp.presolve = GLP_YES; /* LP presolver, we need lp solution */ + mlp->control_param_mlp.presolve = GNUNET_NO; /* No presolver, we have LP solution */ + } + else + { + mlp->control_param_lp.presolve = GNUNET_NO; /* LP presolver, we need lp solution */ + mlp->control_param_mlp.presolve = GLP_YES; /* No presolver, we have LP solution */ + dur_lp = GNUNET_TIME_UNIT_ZERO; + } + } else - { - LOG(GNUNET_ERROR_TYPE_DEBUG, "Problem was updated, resolving\n"); - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "Problem was updated, resolving\n"); + } /* Reset solution info */ mlp->ps.lp_objective_value = 0.0; @@ -1619,156 +1655,160 @@ GAS_mlp_solve_problem (void *solver) mlp->ps.mlp_objective_value = 0.0; mlp->ps.lp_mlp_gap = 0.0; - dur_setup = GNUNET_TIME_absolute_get_duration (start_total); + dur_setup = GNUNET_TIME_absolute_get_duration(start_total); /* Run LP solver */ if (GNUNET_NO == mlp->opt_dbg_intopt_presolver) - { - notify(mlp, GAS_OP_SOLVE_MLP_LP_START, GAS_STAT_SUCCESS, - (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); - LOG(GNUNET_ERROR_TYPE_DEBUG, - "Running LP solver %s\n", - (GLP_YES == mlp->control_param_lp.presolve)? "with presolver": "without presolver"); - start_cur_op = GNUNET_TIME_absolute_get(); - - /* Solve LP */ - /* Only for debugging: - * Always use LP presolver: - * mlp->control_param_lp.presolve = GLP_YES; */ - res_lp = mlp_solve_lp_problem(mlp); - if (GNUNET_OK == res_lp) - { - mlp->ps.lp_objective_value = glp_get_obj_val (mlp->p.prob); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "LP solution was: %.3f\n", - mlp->ps.lp_objective_value); - } - - dur_lp = GNUNET_TIME_absolute_get_duration (start_cur_op); - notify(mlp, GAS_OP_SOLVE_MLP_LP_STOP, - (GNUNET_OK == res_lp) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL, - (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); - } + { + notify(mlp, GAS_OP_SOLVE_MLP_LP_START, GAS_STAT_SUCCESS, + (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Running LP solver %s\n", + (GLP_YES == mlp->control_param_lp.presolve) ? "with presolver" : "without presolver"); + start_cur_op = GNUNET_TIME_absolute_get(); + + /* Solve LP */ + /* Only for debugging: + * Always use LP presolver: + * mlp->control_param_lp.presolve = GLP_YES; */ + res_lp = mlp_solve_lp_problem(mlp); + if (GNUNET_OK == res_lp) + { + mlp->ps.lp_objective_value = glp_get_obj_val(mlp->p.prob); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "LP solution was: %.3f\n", + mlp->ps.lp_objective_value); + } + + dur_lp = GNUNET_TIME_absolute_get_duration(start_cur_op); + notify(mlp, GAS_OP_SOLVE_MLP_LP_STOP, + (GNUNET_OK == res_lp) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL, + (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); + } if (GNUNET_YES == mlp->opt_dbg_intopt_presolver) res_lp = GNUNET_OK; /* Run MLP solver */ if ((GNUNET_OK == res_lp) || (GNUNET_YES == mlp->opt_dbg_intopt_presolver)) - { - LOG(GNUNET_ERROR_TYPE_DEBUG, "Running MLP solver \n"); - notify(mlp, GAS_OP_SOLVE_MLP_MLP_START, GAS_STAT_SUCCESS, - (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); - start_cur_op = GNUNET_TIME_absolute_get(); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "Running MLP solver \n"); + notify(mlp, GAS_OP_SOLVE_MLP_MLP_START, GAS_STAT_SUCCESS, + (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); + start_cur_op = GNUNET_TIME_absolute_get(); - /* Solve MIP */ + /* Solve MIP */ - /* Only for debugging, always use LP presolver */ - if (GNUNET_YES == mlp->opt_dbg_intopt_presolver) - mlp->control_param_mlp.presolve = GNUNET_YES; + /* Only for debugging, always use LP presolver */ + if (GNUNET_YES == mlp->opt_dbg_intopt_presolver) + mlp->control_param_mlp.presolve = GNUNET_YES; - mip_res = glp_intopt (mlp->p.prob, &mlp->control_param_mlp); - switch (mip_res) - { + mip_res = glp_intopt(mlp->p.prob, &mlp->control_param_mlp); + switch (mip_res) + { case 0: /* Successful */ - LOG (GNUNET_ERROR_TYPE_INFO, - "Solving MLP problem: %s\n", - mlp_solve_to_string (mip_res)); + LOG(GNUNET_ERROR_TYPE_INFO, + "Solving MLP problem: %s\n", + mlp_solve_to_string(mip_res)); break; + case GLP_ETMLIM: /* Time limit reached */ case GLP_EMIPGAP: /* MIP gap tolerance limit reached */ case GLP_ESTOP: /* Solver was instructed to stop*/ /* Semi-successful */ - LOG (GNUNET_ERROR_TYPE_INFO, - "Solving MLP problem solution was interupted: %s\n", - mlp_solve_to_string (mip_res)); + LOG(GNUNET_ERROR_TYPE_INFO, + "Solving MLP problem solution was interupted: %s\n", + mlp_solve_to_string(mip_res)); break; + case GLP_EBOUND: case GLP_EROOT: case GLP_ENOPFS: case GLP_ENODFS: case GLP_EFAIL: default: - /* Fail */ - LOG (GNUNET_ERROR_TYPE_INFO, + /* Fail */ + LOG(GNUNET_ERROR_TYPE_INFO, "Solving MLP problem failed: %s\n", - mlp_solve_to_string (mip_res)); - break; - } - - /* Analyze problem status */ - mip_status = glp_mip_status(mlp->p.prob); - switch (mip_status) - { - case GLP_OPT: /* solution is optimal */ - LOG (GNUNET_ERROR_TYPE_WARNING, - "Solution of MLP problem is optimal: %s, %s\n", - mlp_solve_to_string (mip_res), - mlp_status_to_string (mip_status)); - mip_res = GNUNET_OK; - break; - case GLP_FEAS: /* solution is feasible but not proven optimal */ + mlp_solve_to_string(mip_res)); + break; + } - if ( (mlp->ps.mlp_gap <= mlp->pv.mip_gap) || - (mlp->ps.lp_mlp_gap <= mlp->pv.lp_mip_gap) ) + /* Analyze problem status */ + mip_status = glp_mip_status(mlp->p.prob); + switch (mip_status) { - LOG (GNUNET_ERROR_TYPE_INFO, - "Solution of MLP problem is feasible and solution within gap constraints: %s, %s\n", - mlp_solve_to_string (mip_res), - mlp_status_to_string (mip_status)); + case GLP_OPT: /* solution is optimal */ + LOG(GNUNET_ERROR_TYPE_WARNING, + "Solution of MLP problem is optimal: %s, %s\n", + mlp_solve_to_string(mip_res), + mlp_status_to_string(mip_status)); mip_res = GNUNET_OK; - } - else - { - LOG (GNUNET_ERROR_TYPE_WARNING, - "Solution of MLP problem is feasible but solution not within gap constraints: %s, %s\n", - mlp_solve_to_string (mip_res), - mlp_status_to_string (mip_status)); + break; + + case GLP_FEAS: /* solution is feasible but not proven optimal */ + + if ((mlp->ps.mlp_gap <= mlp->pv.mip_gap) || + (mlp->ps.lp_mlp_gap <= mlp->pv.lp_mip_gap)) + { + LOG(GNUNET_ERROR_TYPE_INFO, + "Solution of MLP problem is feasible and solution within gap constraints: %s, %s\n", + mlp_solve_to_string(mip_res), + mlp_status_to_string(mip_status)); + mip_res = GNUNET_OK; + } + else + { + LOG(GNUNET_ERROR_TYPE_WARNING, + "Solution of MLP problem is feasible but solution not within gap constraints: %s, %s\n", + mlp_solve_to_string(mip_res), + mlp_status_to_string(mip_status)); + mip_res = GNUNET_SYSERR; + } + break; + + case GLP_UNDEF: /* Solution undefined */ + case GLP_NOFEAS: /* No feasible solution */ + default: + LOG(GNUNET_ERROR_TYPE_ERROR, + "Solving MLP problem failed: %s %s\n", + mlp_solve_to_string(mip_res), + mlp_status_to_string(mip_status)); mip_res = GNUNET_SYSERR; + break; } - break; - case GLP_UNDEF: /* Solution undefined */ - case GLP_NOFEAS: /* No feasible solution */ - default: - LOG (GNUNET_ERROR_TYPE_ERROR, - "Solving MLP problem failed: %s %s\n", - mlp_solve_to_string (mip_res), - mlp_status_to_string (mip_status)); - mip_res = GNUNET_SYSERR; - break; - } - dur_mlp = GNUNET_TIME_absolute_get_duration (start_cur_op); - dur_total = GNUNET_TIME_absolute_get_duration (start_total); + dur_mlp = GNUNET_TIME_absolute_get_duration(start_cur_op); + dur_total = GNUNET_TIME_absolute_get_duration(start_total); - notify(mlp, GAS_OP_SOLVE_MLP_MLP_STOP, - (GNUNET_OK == mip_res) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL, - (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); - } + notify(mlp, GAS_OP_SOLVE_MLP_MLP_STOP, + (GNUNET_OK == mip_res) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL, + (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); + } else - { - /* Do not execute mip solver since lp solution is invalid */ - dur_mlp = GNUNET_TIME_UNIT_ZERO; - dur_total = GNUNET_TIME_absolute_get_duration (start_total); + { + /* Do not execute mip solver since lp solution is invalid */ + dur_mlp = GNUNET_TIME_UNIT_ZERO; + dur_total = GNUNET_TIME_absolute_get_duration(start_total); - notify(mlp, GAS_OP_SOLVE_MLP_MLP_STOP, GAS_STAT_FAIL, - (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); - mip_res = GNUNET_SYSERR; - } + notify(mlp, GAS_OP_SOLVE_MLP_MLP_STOP, GAS_STAT_FAIL, + (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); + mip_res = GNUNET_SYSERR; + } /* Notify about end */ notify(mlp, GAS_OP_SOLVE_STOP, - ((GNUNET_OK == mip_res) && (GNUNET_OK == mip_res)) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL, - (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); + ((GNUNET_OK == mip_res) && (GNUNET_OK == mip_res)) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL, + (GNUNET_YES == mlp->stat_mlp_prob_changed) ? GAS_INFO_FULL : GAS_INFO_UPDATED); - LOG (GNUNET_ERROR_TYPE_DEBUG, + LOG(GNUNET_ERROR_TYPE_DEBUG, "Execution time for %s solve: (total/setup/lp/mlp) : %llu %llu %llu %llu\n", (GNUNET_YES == mlp->stat_mlp_prob_changed) ? "full" : "updated", - (unsigned long long) dur_total.rel_value_us, - (unsigned long long) dur_setup.rel_value_us, - (unsigned long long) dur_lp.rel_value_us, - (unsigned long long) dur_mlp.rel_value_us); + (unsigned long long)dur_total.rel_value_us, + (unsigned long long)dur_setup.rel_value_us, + (unsigned long long)dur_lp.rel_value_us, + (unsigned long long)dur_mlp.rel_value_us); /* Save stats */ mlp->ps.lp_res = res_lp; @@ -1780,55 +1820,59 @@ GAS_mlp_solve_problem (void *solver) mlp->ps.p_elements = mlp->p.num_elements; /* Propagate result*/ - notify (mlp, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, - (GNUNET_OK == res_lp) && (GNUNET_OK == mip_res) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL, - GAS_INFO_NONE); + notify(mlp, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, + (GNUNET_OK == res_lp) && (GNUNET_OK == mip_res) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL, + GAS_INFO_NONE); if ((GNUNET_OK == res_lp) && (GNUNET_OK == mip_res)) { GNUNET_CONTAINER_multipeermap_iterate(mlp->env->addresses, - &mlp_propagate_results, mlp); + &mlp_propagate_results, mlp); } - notify (mlp, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, - (GNUNET_OK == res_lp) && (GNUNET_OK == mip_res) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL, - GAS_INFO_NONE); + notify(mlp, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, + (GNUNET_OK == res_lp) && (GNUNET_OK == mip_res) ? GAS_STAT_SUCCESS : GAS_STAT_FAIL, + GAS_INFO_NONE); struct GNUNET_TIME_Absolute time = GNUNET_TIME_absolute_get(); - if ( (GNUNET_YES == mlp->opt_dump_problem_all) || - (mlp->opt_dump_problem_on_fail && ((GNUNET_OK != res_lp) || (GNUNET_OK != mip_res))) ) + if ((GNUNET_YES == mlp->opt_dump_problem_all) || + (mlp->opt_dump_problem_on_fail && ((GNUNET_OK != res_lp) || (GNUNET_OK != mip_res)))) { /* Write problem to disk */ - switch (mlp->opt_log_format) { + switch (mlp->opt_log_format) + { case MLP_CPLEX: GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.cplex", mlp->p.num_peers, - mlp->p.num_addresses, time.abs_value_us); - glp_write_lp (mlp->p.prob, NULL, filename); + mlp->p.num_addresses, time.abs_value_us); + glp_write_lp(mlp->p.prob, NULL, filename); break; + case MLP_GLPK: GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.glpk", mlp->p.num_peers, - mlp->p.num_addresses, time.abs_value_us); - glp_write_prob (mlp->p.prob, 0, filename); + mlp->p.num_addresses, time.abs_value_us); + glp_write_prob(mlp->p.prob, 0, filename); break; + case MLP_MPS: GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.mps", mlp->p.num_peers, - mlp->p.num_addresses, time.abs_value_us); - glp_write_mps (mlp->p.prob, GLP_MPS_FILE, NULL, filename); + mlp->p.num_addresses, time.abs_value_us); + glp_write_mps(mlp->p.prob, GLP_MPS_FILE, NULL, filename); break; + default: break; - } + } LOG(GNUNET_ERROR_TYPE_ERROR, "Dumped problem to file: `%s' \n", filename); GNUNET_free(filename); } - if ( (mlp->opt_dump_solution_all) || - (mlp->opt_dump_solution_on_fail && ((GNUNET_OK != res_lp) || (GNUNET_OK != mip_res))) ) - { - /* Write solution to disk */ - GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.sol", mlp->p.num_peers, - mlp->p.num_addresses, time.abs_value_us); - glp_print_mip(mlp->p.prob, filename); - LOG(GNUNET_ERROR_TYPE_ERROR, "Dumped solution to file: `%s' \n", filename); - GNUNET_free(filename); - } + if ((mlp->opt_dump_solution_all) || + (mlp->opt_dump_solution_on_fail && ((GNUNET_OK != res_lp) || (GNUNET_OK != mip_res)))) + { + /* Write solution to disk */ + GNUNET_asprintf(&filename, "problem_p_%u_a%u_%llu.sol", mlp->p.num_peers, + mlp->p.num_addresses, time.abs_value_us); + glp_print_mip(mlp->p.prob, filename); + LOG(GNUNET_ERROR_TYPE_ERROR, "Dumped solution to file: `%s' \n", filename); + GNUNET_free(filename); + } /* Reset change and update marker */ mlp->control_param_lp.presolve = GLP_NO; @@ -1849,46 +1893,46 @@ GAS_mlp_solve_problem (void *solver) * @param network network type of this address */ static void -GAS_mlp_address_add (void *solver, +GAS_mlp_address_add(void *solver, struct ATS_Address *address, uint32_t network) { struct GAS_MLP_Handle *mlp = solver; if (GNUNET_NT_COUNT <= network) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } if (NULL == address->solver_information) - { - address->solver_information = GNUNET_new (struct MLP_information); - } + { + address->solver_information = GNUNET_new(struct MLP_information); + } else - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Adding address for peer `%s' multiple times\n"), - GNUNET_i2s(&address->peer)); + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Adding address for peer `%s' multiple times\n"), + GNUNET_i2s(&address->peer)); /* Is this peer included in the problem? */ if (NULL == - GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, - &address->peer)) - { - /* FIXME: should this be an error? */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Adding address for peer `%s' without address request\n", - GNUNET_i2s(&address->peer)); - return; - } + GNUNET_CONTAINER_multipeermap_get(mlp->requested_peers, + &address->peer)) + { + /* FIXME: should this be an error? */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Adding address for peer `%s' without address request\n", + GNUNET_i2s(&address->peer)); + return; + } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Adding address for peer `%s' with address request \n", - GNUNET_i2s(&address->peer)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Adding address for peer `%s' with address request \n", + GNUNET_i2s(&address->peer)); /* Problem size changed: new address for peer with pending request */ mlp->stat_mlp_prob_changed = GNUNET_YES; if (GNUNET_YES == mlp->opt_mlp_auto_solve) - GAS_mlp_solve_problem (solver); + GAS_mlp_solve_problem(solver); } @@ -1899,8 +1943,8 @@ GAS_mlp_address_add (void *solver, * @param address the address */ static void -GAS_mlp_address_property_changed (void *solver, - struct ATS_Address *address) +GAS_mlp_address_property_changed(void *solver, + struct ATS_Address *address) { struct MLP_information *mlpi = address->solver_information; struct GAS_MLP_Handle *mlp = solver; @@ -1909,47 +1953,46 @@ GAS_mlp_address_property_changed (void *solver, return; /* There is no MLP problem to update yet */ if (NULL == mlpi) - { - LOG (GNUNET_ERROR_TYPE_INFO, - _("Updating address property for peer `%s' %p not added before\n"), - GNUNET_i2s (&address->peer), - address); - GNUNET_break (0); - return; - } + { + LOG(GNUNET_ERROR_TYPE_INFO, + _("Updating address property for peer `%s' %p not added before\n"), + GNUNET_i2s(&address->peer), + address); + GNUNET_break(0); + return; + } if (NULL == - GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, - &address->peer)) - { - /* Peer is not requested, so no need to update problem */ - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Updating properties for peer `%s'\n", - GNUNET_i2s(&address->peer)); + GNUNET_CONTAINER_multipeermap_get(mlp->requested_peers, + &address->peer)) + { + /* Peer is not requested, so no need to update problem */ + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Updating properties for peer `%s'\n", + GNUNET_i2s(&address->peer)); if (GNUNET_YES == mlp->opt_dbg_feasibility_only) return; /* Update c7) [r_q[index]][c_b] = f_q * q_averaged[type_index] */ - if ( (GNUNET_YES == - mlp_create_problem_update_value (&mlp->p, - mlp->p.r_q[RQ_QUALITY_METRIC_DELAY], - mlpi->c_b, - address->norm_delay.norm, - __LINE__)) || - (GNUNET_YES == - mlp_create_problem_update_value (&mlp->p, - mlp->p.r_q[RQ_QUALITY_METRIC_DISTANCE], - mlpi->c_b, - address->norm_distance.norm, - __LINE__)) ) - { - mlp->stat_mlp_prob_updated = GNUNET_YES; - if (GNUNET_YES == mlp->opt_mlp_auto_solve) - GAS_mlp_solve_problem (solver); - } - + if ((GNUNET_YES == + mlp_create_problem_update_value(&mlp->p, + mlp->p.r_q[RQ_QUALITY_METRIC_DELAY], + mlpi->c_b, + address->norm_delay.norm, + __LINE__)) || + (GNUNET_YES == + mlp_create_problem_update_value(&mlp->p, + mlp->p.r_q[RQ_QUALITY_METRIC_DISTANCE], + mlpi->c_b, + address->norm_distance.norm, + __LINE__))) + { + mlp->stat_mlp_prob_updated = GNUNET_YES; + if (GNUNET_YES == mlp->opt_mlp_auto_solve) + GAS_mlp_solve_problem(solver); + } } @@ -1961,9 +2004,9 @@ GAS_mlp_address_property_changed (void *solver, * @return #GNUNET_OK */ static int -mlp_get_preferred_address_it (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +mlp_get_preferred_address_it(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { static int counter = 0; struct ATS_Address **aa = cls; @@ -1983,41 +2026,40 @@ mlp_get_preferred_address_it (void *cls, */ if (GNUNET_YES == mlpi->n) - { - - (*aa) = addr; - (*aa)->assigned_bw_in = mlpi->b_in; - (*aa)->assigned_bw_out = mlpi->b_out; - return GNUNET_NO; - } + { + (*aa) = addr; + (*aa)->assigned_bw_in = mlpi->b_in; + (*aa)->assigned_bw_out = mlpi->b_out; + return GNUNET_NO; + } counter++; return GNUNET_YES; } static double -get_peer_pref_value (struct GAS_MLP_Handle *mlp, - const struct GNUNET_PeerIdentity *peer) +get_peer_pref_value(struct GAS_MLP_Handle *mlp, + const struct GNUNET_PeerIdentity *peer) { double res; const double *preferences; int c; - preferences = mlp->env->get_preferences (mlp->env->cls, peer); + preferences = mlp->env->get_preferences(mlp->env->cls, peer); res = 0.0; for (c = 0; c < GNUNET_ATS_PREFERENCE_END; c++) - { - /* fprintf (stderr, "VALUE[%u] %s %.3f \n", - * c, GNUNET_i2s (&cur->addr->peer), t[c]); */ - res += preferences[c]; - } + { + /* fprintf (stderr, "VALUE[%u] %s %.3f \n", + * c, GNUNET_i2s (&cur->addr->peer), t[c]); */ + res += preferences[c]; + } res /= GNUNET_ATS_PREFERENCE_END; res += 1.0; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Peer preference for peer `%s' == %.2f\n", - GNUNET_i2s(peer), res); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Peer preference for peer `%s' == %.2f\n", + GNUNET_i2s(peer), res); return res; } @@ -2030,51 +2072,51 @@ get_peer_pref_value (struct GAS_MLP_Handle *mlp, * @param peer the peer */ static void -GAS_mlp_get_preferred_address (void *solver, - const struct GNUNET_PeerIdentity *peer) +GAS_mlp_get_preferred_address(void *solver, + const struct GNUNET_PeerIdentity *peer) { struct GAS_MLP_Handle *mlp = solver; struct ATS_Peer *p; struct ATS_Address *res; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Getting preferred address for `%s'\n", - GNUNET_i2s (peer)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Getting preferred address for `%s'\n", + GNUNET_i2s(peer)); /* Is this peer included in the problem? */ if (NULL == - GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, - peer)) + GNUNET_CONTAINER_multipeermap_get(mlp->requested_peers, + peer)) { - LOG (GNUNET_ERROR_TYPE_INFO, "Adding peer `%s' to list of requested_peers with requests\n", - GNUNET_i2s (peer)); + LOG(GNUNET_ERROR_TYPE_INFO, "Adding peer `%s' to list of requested_peers with requests\n", + GNUNET_i2s(peer)); - p = GNUNET_new (struct ATS_Peer); + p = GNUNET_new(struct ATS_Peer); p->id = (*peer); - p->f = get_peer_pref_value (mlp, peer); - GNUNET_CONTAINER_multipeermap_put (mlp->requested_peers, - peer, p, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST); + p->f = get_peer_pref_value(mlp, peer); + GNUNET_CONTAINER_multipeermap_put(mlp->requested_peers, + peer, p, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST); /* Added new peer, we have to rebuild problem before solving */ mlp->stat_mlp_prob_changed = GNUNET_YES; - if ((GNUNET_YES == mlp->opt_mlp_auto_solve)&& + if ((GNUNET_YES == mlp->opt_mlp_auto_solve) && (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains(mlp->env->addresses, - peer))) - { - mlp->exclude_peer = peer; - GAS_mlp_solve_problem (mlp); - mlp->exclude_peer = NULL; - } - } + peer))) + { + mlp->exclude_peer = peer; + GAS_mlp_solve_problem(mlp); + mlp->exclude_peer = NULL; + } + } /* Get prefered address */ res = NULL; - GNUNET_CONTAINER_multipeermap_get_multiple (mlp->env->addresses, peer, - &mlp_get_preferred_address_it, &res); + GNUNET_CONTAINER_multipeermap_get_multiple(mlp->env->addresses, peer, + &mlp_get_preferred_address_it, &res); if (NULL != res) - mlp->env->bandwidth_changed_cb (mlp->env->cls, - res); + mlp->env->bandwidth_changed_cb(mlp->env->cls, + res); } @@ -2087,8 +2129,8 @@ GAS_mlp_get_preferred_address (void *solver, * @param address the address to delete */ static void -GAS_mlp_address_delete (void *solver, - struct ATS_Address *address) +GAS_mlp_address_delete(void *solver, + struct ATS_Address *address) { struct GAS_MLP_Handle *mlp = solver; struct MLP_information *mlpi; @@ -2097,11 +2139,11 @@ GAS_mlp_address_delete (void *solver, mlpi = address->solver_information; if (NULL != mlpi) - { - /* Remove full address */ - GNUNET_free (mlpi); - address->solver_information = NULL; - } + { + /* Remove full address */ + GNUNET_free(mlpi); + address->solver_information = NULL; + } was_active = address->active; address->active = GNUNET_NO; address->assigned_bw_in = 0; @@ -2109,38 +2151,38 @@ GAS_mlp_address_delete (void *solver, /* Is this peer included in the problem? */ if (NULL == - GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, - &address->peer)) - { - LOG (GNUNET_ERROR_TYPE_INFO, - "Deleting address for peer `%s' without address request \n", - GNUNET_i2s(&address->peer)); - return; - } - LOG (GNUNET_ERROR_TYPE_INFO, - "Deleting address for peer `%s' with address request \n", - GNUNET_i2s (&address->peer)); + GNUNET_CONTAINER_multipeermap_get(mlp->requested_peers, + &address->peer)) + { + LOG(GNUNET_ERROR_TYPE_INFO, + "Deleting address for peer `%s' without address request \n", + GNUNET_i2s(&address->peer)); + return; + } + LOG(GNUNET_ERROR_TYPE_INFO, + "Deleting address for peer `%s' with address request \n", + GNUNET_i2s(&address->peer)); /* Problem size changed: new address for peer with pending request */ mlp->stat_mlp_prob_changed = GNUNET_YES; if (GNUNET_YES == mlp->opt_mlp_auto_solve) - { - GAS_mlp_solve_problem (solver); - } + { + GAS_mlp_solve_problem(solver); + } if (GNUNET_YES == was_active) - { - GAS_mlp_get_preferred_address (solver, &address->peer); - res = NULL; - GNUNET_CONTAINER_multipeermap_get_multiple (mlp->env->addresses, - &address->peer, - &mlp_get_preferred_address_it, - &res); - if (NULL == res) - { - /* No alternative address, disconnecting peer */ - mlp->env->bandwidth_changed_cb (mlp->env->cls, address); - } - } + { + GAS_mlp_get_preferred_address(solver, &address->peer); + res = NULL; + GNUNET_CONTAINER_multipeermap_get_multiple(mlp->env->addresses, + &address->peer, + &mlp_get_preferred_address_it, + &res); + if (NULL == res) + { + /* No alternative address, disconnecting peer */ + mlp->env->bandwidth_changed_cb(mlp->env->cls, address); + } + } } @@ -2150,38 +2192,38 @@ GAS_mlp_address_delete (void *solver, * @param solver the solver */ static void -GAS_mlp_bulk_start (void *solver) +GAS_mlp_bulk_start(void *solver) { struct GAS_MLP_Handle *s = solver; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Locking solver for bulk operation ...\n"); - GNUNET_assert (NULL != solver); - s->stat_bulk_lock ++; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Locking solver for bulk operation ...\n"); + GNUNET_assert(NULL != solver); + s->stat_bulk_lock++; } static void -GAS_mlp_bulk_stop (void *solver) +GAS_mlp_bulk_stop(void *solver) { struct GAS_MLP_Handle *s = solver; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Unlocking solver from bulk operation ...\n"); - GNUNET_assert (NULL != solver); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Unlocking solver from bulk operation ...\n"); + GNUNET_assert(NULL != solver); if (s->stat_bulk_lock < 1) - { - GNUNET_break (0); - return; - } - s->stat_bulk_lock --; + { + GNUNET_break(0); + return; + } + s->stat_bulk_lock--; if (0 < s->stat_bulk_requests) - { - GAS_mlp_solve_problem (solver); - s->stat_bulk_requests= 0; - } + { + GAS_mlp_solve_problem(solver); + s->stat_bulk_requests = 0; + } } @@ -2193,26 +2235,26 @@ GAS_mlp_bulk_stop (void *solver) * @param peer the peer */ static void -GAS_mlp_stop_get_preferred_address (void *solver, - const struct GNUNET_PeerIdentity *peer) +GAS_mlp_stop_get_preferred_address(void *solver, + const struct GNUNET_PeerIdentity *peer) { struct GAS_MLP_Handle *mlp = solver; struct ATS_Peer *p = NULL; - GNUNET_assert (NULL != solver); - GNUNET_assert (NULL != peer); - if (NULL != (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, peer))) - { - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (mlp->requested_peers, peer, p)); - GNUNET_free (p); - - mlp->stat_mlp_prob_changed = GNUNET_YES; - if (GNUNET_YES == mlp->opt_mlp_auto_solve) + GNUNET_assert(NULL != solver); + GNUNET_assert(NULL != peer); + if (NULL != (p = GNUNET_CONTAINER_multipeermap_get(mlp->requested_peers, peer))) { - GAS_mlp_solve_problem (solver); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(mlp->requested_peers, peer, p)); + GNUNET_free(p); + + mlp->stat_mlp_prob_changed = GNUNET_YES; + if (GNUNET_YES == mlp->opt_mlp_auto_solve) + { + GAS_mlp_solve_problem(solver); + } } - } } @@ -2225,48 +2267,48 @@ GAS_mlp_stop_get_preferred_address (void *solver, * @param pref_rel the relative score */ static void -GAS_mlp_address_change_preference (void *solver, - const struct GNUNET_PeerIdentity *peer, - enum GNUNET_ATS_PreferenceKind kind, - double pref_rel) +GAS_mlp_address_change_preference(void *solver, + const struct GNUNET_PeerIdentity *peer, + enum GNUNET_ATS_PreferenceKind kind, + double pref_rel) { struct GAS_MLP_Handle *mlp = solver; struct ATS_Peer *p; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Changing preference for address for peer `%s' to %.2f\n", - GNUNET_i2s(peer), - pref_rel); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Changing preference for address for peer `%s' to %.2f\n", + GNUNET_i2s(peer), + pref_rel); - GNUNET_STATISTICS_update (mlp->env->stats, - "# LP address preference changes", 1, GNUNET_NO); + GNUNET_STATISTICS_update(mlp->env->stats, + "# LP address preference changes", 1, GNUNET_NO); /* Update the constraints with changed preferences */ /* Update relativity constraint c9 */ - if (NULL == (p = GNUNET_CONTAINER_multipeermap_get (mlp->requested_peers, peer))) - { - LOG (GNUNET_ERROR_TYPE_INFO, - "Updating preference for unknown peer `%s'\n", - GNUNET_i2s(peer)); - return; - } + if (NULL == (p = GNUNET_CONTAINER_multipeermap_get(mlp->requested_peers, peer))) + { + LOG(GNUNET_ERROR_TYPE_INFO, + "Updating preference for unknown peer `%s'\n", + GNUNET_i2s(peer)); + return; + } if (GNUNET_NO == mlp->opt_dbg_feasibility_only) - { - p->f = get_peer_pref_value (mlp, peer); - mlp_create_problem_update_value (&mlp->p, - p->r_c9, - mlp->p.c_r, - - p->f, - __LINE__); - - /* Problem size changed: new address for peer with pending request */ - mlp->stat_mlp_prob_updated = GNUNET_YES; - if (GNUNET_YES == mlp->opt_mlp_auto_solve) - GAS_mlp_solve_problem (solver); - } + { + p->f = get_peer_pref_value(mlp, peer); + mlp_create_problem_update_value(&mlp->p, + p->r_c9, + mlp->p.c_r, + -p->f, + __LINE__); + + /* Problem size changed: new address for peer with pending request */ + mlp->stat_mlp_prob_updated = GNUNET_YES; + if (GNUNET_YES == mlp->opt_mlp_auto_solve) + GAS_mlp_solve_problem(solver); + } } @@ -2281,31 +2323,31 @@ GAS_mlp_address_change_preference (void *solver, * @param score the score */ static void -GAS_mlp_address_preference_feedback (void *solver, - struct GNUNET_SERVICE_Client *application, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_TIME_Relative scope, - enum GNUNET_ATS_PreferenceKind kind, - double score) +GAS_mlp_address_preference_feedback(void *solver, + struct GNUNET_SERVICE_Client *application, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_TIME_Relative scope, + enum GNUNET_ATS_PreferenceKind kind, + double score) { struct GAS_PROPORTIONAL_Handle *s = solver; - GNUNET_assert (NULL != solver); - GNUNET_assert (NULL != peer); - GNUNET_assert (NULL != s); + GNUNET_assert(NULL != solver); + GNUNET_assert(NULL != peer); + GNUNET_assert(NULL != s); } static int -mlp_free_peers (void *cls, - const struct GNUNET_PeerIdentity *key, void *value) +mlp_free_peers(void *cls, + const struct GNUNET_PeerIdentity *key, void *value) { struct GNUNET_CONTAINER_MultiPeerMap *map = cls; struct ATS_Peer *p = value; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (map, key, value)); - GNUNET_free (p); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(map, key, value)); + GNUNET_free(p); return GNUNET_OK; } @@ -2318,36 +2360,36 @@ mlp_free_peers (void *cls, * @return NULL */ void * -libgnunet_plugin_ats_mlp_done (void *cls) +libgnunet_plugin_ats_mlp_done(void *cls) { struct GNUNET_ATS_SolverFunctions *sf = cls; struct GAS_MLP_Handle *mlp = sf->cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Shutting down mlp solver\n"); - mlp_delete_problem (mlp); - GNUNET_CONTAINER_multipeermap_iterate (mlp->requested_peers, - &mlp_free_peers, - mlp->requested_peers); - GNUNET_CONTAINER_multipeermap_destroy (mlp->requested_peers); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Shutting down mlp solver\n"); + mlp_delete_problem(mlp); + GNUNET_CONTAINER_multipeermap_iterate(mlp->requested_peers, + &mlp_free_peers, + mlp->requested_peers); + GNUNET_CONTAINER_multipeermap_destroy(mlp->requested_peers); mlp->requested_peers = NULL; /* Clean up GLPK environment */ glp_free_env(); - GNUNET_free (mlp); + GNUNET_free(mlp); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Shutdown down of mlp solver complete\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Shutdown down of mlp solver complete\n"); return NULL; } void * -libgnunet_plugin_ats_mlp_init (void *cls) +libgnunet_plugin_ats_mlp_init(void *cls) { static struct GNUNET_ATS_SolverFunctions sf; struct GNUNET_ATS_PluginEnvironment *env = cls; - struct GAS_MLP_Handle * mlp = GNUNET_new (struct GAS_MLP_Handle); + struct GAS_MLP_Handle * mlp = GNUNET_new(struct GAS_MLP_Handle); float f_tmp; unsigned long long tmp; unsigned int b_min; @@ -2360,349 +2402,355 @@ libgnunet_plugin_ats_mlp_init (void *cls) /* Init GLPK environment */ int res = glp_init_env(); - switch (res) { + + switch (res) + { case 0: - LOG (GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n", + LOG(GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n", "initialization successful"); break; + case 1: - LOG (GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n", + LOG(GNUNET_ERROR_TYPE_DEBUG, "GLPK: `%s'\n", "environment is already initialized"); break; + case 2: - LOG (GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n", + LOG(GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n", "initialization failed (insufficient memory)"); GNUNET_free(mlp); return NULL; break; + case 3: - LOG (GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n", + LOG(GNUNET_ERROR_TYPE_ERROR, "Could not init GLPK: `%s'\n", "initialization failed (unsupported programming model)"); GNUNET_free(mlp); return NULL; break; + default: break; - } + } - mlp->opt_dump_problem_all = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "ats", "MLP_DUMP_PROBLEM_ALL"); + mlp->opt_dump_problem_all = GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "ats", "MLP_DUMP_PROBLEM_ALL"); if (GNUNET_SYSERR == mlp->opt_dump_problem_all) - mlp->opt_dump_problem_all = GNUNET_NO; + mlp->opt_dump_problem_all = GNUNET_NO; - mlp->opt_dump_solution_all = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "ats", "MLP_DUMP_SOLUTION_ALL"); + mlp->opt_dump_solution_all = GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "ats", "MLP_DUMP_SOLUTION_ALL"); if (GNUNET_SYSERR == mlp->opt_dump_solution_all) - mlp->opt_dump_solution_all = GNUNET_NO; + mlp->opt_dump_solution_all = GNUNET_NO; - mlp->opt_dump_problem_on_fail = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "ats", "MLP_DUMP_PROBLEM_ON_FAIL"); + mlp->opt_dump_problem_on_fail = GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "ats", "MLP_DUMP_PROBLEM_ON_FAIL"); if (GNUNET_SYSERR == mlp->opt_dump_problem_on_fail) - mlp->opt_dump_problem_on_fail = GNUNET_NO; + mlp->opt_dump_problem_on_fail = GNUNET_NO; - mlp->opt_dump_solution_on_fail = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "ats", "MLP_DUMP_SOLUTION_ON_FAIL"); + mlp->opt_dump_solution_on_fail = GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "ats", "MLP_DUMP_SOLUTION_ON_FAIL"); if (GNUNET_SYSERR == mlp->opt_dump_solution_on_fail) - mlp->opt_dump_solution_on_fail = GNUNET_NO; + mlp->opt_dump_solution_on_fail = GNUNET_NO; - mlp->opt_dbg_glpk_verbose = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "ats", "MLP_DBG_GLPK_VERBOSE"); + mlp->opt_dbg_glpk_verbose = GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "ats", "MLP_DBG_GLPK_VERBOSE"); if (GNUNET_SYSERR == mlp->opt_dbg_glpk_verbose) - mlp->opt_dbg_glpk_verbose = GNUNET_NO; + mlp->opt_dbg_glpk_verbose = GNUNET_NO; - mlp->opt_dbg_feasibility_only = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "ats", "MLP_DBG_FEASIBILITY_ONLY"); + mlp->opt_dbg_feasibility_only = GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "ats", "MLP_DBG_FEASIBILITY_ONLY"); if (GNUNET_SYSERR == mlp->opt_dbg_feasibility_only) - mlp->opt_dbg_feasibility_only = GNUNET_NO; + mlp->opt_dbg_feasibility_only = GNUNET_NO; if (GNUNET_YES == mlp->opt_dbg_feasibility_only) - LOG (GNUNET_ERROR_TYPE_WARNING, + LOG(GNUNET_ERROR_TYPE_WARNING, "MLP solver is configured to check feasibility only!\n"); - mlp->opt_dbg_autoscale_problem = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "ats", "MLP_DBG_AUTOSCALE_PROBLEM"); + mlp->opt_dbg_autoscale_problem = GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "ats", "MLP_DBG_AUTOSCALE_PROBLEM"); if (GNUNET_SYSERR == mlp->opt_dbg_autoscale_problem) - mlp->opt_dbg_autoscale_problem = GNUNET_NO; + mlp->opt_dbg_autoscale_problem = GNUNET_NO; if (GNUNET_YES == mlp->opt_dbg_autoscale_problem) - LOG (GNUNET_ERROR_TYPE_WARNING, + LOG(GNUNET_ERROR_TYPE_WARNING, "MLP solver is configured automatically scale the problem!\n"); - mlp->opt_dbg_intopt_presolver = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "ats", "MLP_DBG_INTOPT_PRESOLVE"); + mlp->opt_dbg_intopt_presolver = GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "ats", "MLP_DBG_INTOPT_PRESOLVE"); if (GNUNET_SYSERR == mlp->opt_dbg_intopt_presolver) - mlp->opt_dbg_intopt_presolver = GNUNET_NO; + mlp->opt_dbg_intopt_presolver = GNUNET_NO; if (GNUNET_YES == mlp->opt_dbg_intopt_presolver) - LOG (GNUNET_ERROR_TYPE_WARNING, + LOG(GNUNET_ERROR_TYPE_WARNING, "MLP solver is configured use the mlp presolver\n"); - mlp->opt_dbg_optimize_diversity = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "ats", "MLP_DBG_OPTIMIZE_DIVERSITY"); + mlp->opt_dbg_optimize_diversity = GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "ats", "MLP_DBG_OPTIMIZE_DIVERSITY"); if (GNUNET_SYSERR == mlp->opt_dbg_optimize_diversity) - mlp->opt_dbg_optimize_diversity = GNUNET_YES; + mlp->opt_dbg_optimize_diversity = GNUNET_YES; if (GNUNET_NO == mlp->opt_dbg_optimize_diversity) - LOG (GNUNET_ERROR_TYPE_WARNING, + LOG(GNUNET_ERROR_TYPE_WARNING, "MLP solver is not optimizing for diversity\n"); - mlp->opt_dbg_optimize_relativity= GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "ats", "MLP_DBG_OPTIMIZE_RELATIVITY"); + mlp->opt_dbg_optimize_relativity = GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "ats", "MLP_DBG_OPTIMIZE_RELATIVITY"); if (GNUNET_SYSERR == mlp->opt_dbg_optimize_relativity) - mlp->opt_dbg_optimize_relativity = GNUNET_YES; + mlp->opt_dbg_optimize_relativity = GNUNET_YES; if (GNUNET_NO == mlp->opt_dbg_optimize_relativity) - LOG (GNUNET_ERROR_TYPE_WARNING, + LOG(GNUNET_ERROR_TYPE_WARNING, "MLP solver is not optimizing for relativity\n"); - mlp->opt_dbg_optimize_quality = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "ats", "MLP_DBG_OPTIMIZE_QUALITY"); + mlp->opt_dbg_optimize_quality = GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "ats", "MLP_DBG_OPTIMIZE_QUALITY"); if (GNUNET_SYSERR == mlp->opt_dbg_optimize_quality) - mlp->opt_dbg_optimize_quality = GNUNET_YES; + mlp->opt_dbg_optimize_quality = GNUNET_YES; if (GNUNET_NO == mlp->opt_dbg_optimize_quality) - LOG (GNUNET_ERROR_TYPE_WARNING, + LOG(GNUNET_ERROR_TYPE_WARNING, "MLP solver is not optimizing for quality\n"); - mlp->opt_dbg_optimize_utility = GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "ats", "MLP_DBG_OPTIMIZE_UTILITY"); + mlp->opt_dbg_optimize_utility = GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "ats", "MLP_DBG_OPTIMIZE_UTILITY"); if (GNUNET_SYSERR == mlp->opt_dbg_optimize_utility) - mlp->opt_dbg_optimize_utility = GNUNET_YES; + mlp->opt_dbg_optimize_utility = GNUNET_YES; if (GNUNET_NO == mlp->opt_dbg_optimize_utility) - LOG (GNUNET_ERROR_TYPE_WARNING, + LOG(GNUNET_ERROR_TYPE_WARNING, "MLP solver is not optimizing for utility\n"); - if ( (GNUNET_NO == mlp->opt_dbg_optimize_utility) && - (GNUNET_NO == mlp->opt_dbg_optimize_quality) && - (GNUNET_NO == mlp->opt_dbg_optimize_relativity) && - (GNUNET_NO == mlp->opt_dbg_optimize_utility) && - (GNUNET_NO == mlp->opt_dbg_feasibility_only)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _("MLP solver is not optimizing for anything, changing to feasibility check\n")); - mlp->opt_dbg_feasibility_only = GNUNET_YES; - } - - if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (env->cfg, - "ats", "MLP_LOG_FORMAT", &outputformat)) - mlp->opt_log_format = MLP_CPLEX; - else - { - GNUNET_STRINGS_utf8_toupper(outputformat, outputformat); - if (0 == strcmp (outputformat, "MPS")) - { - mlp->opt_log_format = MLP_MPS; - } - else if (0 == strcmp (outputformat, "CPLEX")) + if ((GNUNET_NO == mlp->opt_dbg_optimize_utility) && + (GNUNET_NO == mlp->opt_dbg_optimize_quality) && + (GNUNET_NO == mlp->opt_dbg_optimize_relativity) && + (GNUNET_NO == mlp->opt_dbg_optimize_utility) && + (GNUNET_NO == mlp->opt_dbg_feasibility_only)) { - mlp->opt_log_format = MLP_CPLEX; + LOG(GNUNET_ERROR_TYPE_ERROR, + _("MLP solver is not optimizing for anything, changing to feasibility check\n")); + mlp->opt_dbg_feasibility_only = GNUNET_YES; } - else if (0 == strcmp (outputformat, "GLPK")) - { - mlp->opt_log_format = MLP_GLPK; - } - else + + if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(env->cfg, + "ats", "MLP_LOG_FORMAT", &outputformat)) + mlp->opt_log_format = MLP_CPLEX; + else { - LOG (GNUNET_ERROR_TYPE_WARNING, - "Invalid log format `%s' in configuration, using CPLEX!\n", - outputformat); - mlp->opt_log_format = MLP_CPLEX; + GNUNET_STRINGS_utf8_toupper(outputformat, outputformat); + if (0 == strcmp(outputformat, "MPS")) + { + mlp->opt_log_format = MLP_MPS; + } + else if (0 == strcmp(outputformat, "CPLEX")) + { + mlp->opt_log_format = MLP_CPLEX; + } + else if (0 == strcmp(outputformat, "GLPK")) + { + mlp->opt_log_format = MLP_GLPK; + } + else + { + LOG(GNUNET_ERROR_TYPE_WARNING, + "Invalid log format `%s' in configuration, using CPLEX!\n", + outputformat); + mlp->opt_log_format = MLP_CPLEX; + } + GNUNET_free(outputformat); } - GNUNET_free (outputformat); - } - mlp->pv.BIG_M = (double) BIG_M_VALUE; + mlp->pv.BIG_M = (double)BIG_M_VALUE; - mlp->pv.mip_gap = (double) 0.0; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "MLP_MAX_MIP_GAP", &f_tmp)) - { - if ((f_tmp < 0.0) || (f_tmp > 1.0)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "MIP gap", f_tmp); - } - else + mlp->pv.mip_gap = (double)0.0; + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "MLP_MAX_MIP_GAP", &f_tmp)) { - mlp->pv.mip_gap = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", - "MIP gap", f_tmp); + if ((f_tmp < 0.0) || (f_tmp > 1.0)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "MIP gap", f_tmp); + } + else + { + mlp->pv.mip_gap = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", + "MIP gap", f_tmp); + } } - } - mlp->pv.lp_mip_gap = (double) 0.0; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "MLP_MAX_LP_MIP_GAP", &f_tmp)) - { - if ((f_tmp < 0.0) || (f_tmp > 1.0)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "LP/MIP", f_tmp); - } - else + mlp->pv.lp_mip_gap = (double)0.0; + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "MLP_MAX_LP_MIP_GAP", &f_tmp)) { - mlp->pv.lp_mip_gap = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n", - "LP/MIP", f_tmp); + if ((f_tmp < 0.0) || (f_tmp > 1.0)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "LP/MIP", f_tmp); + } + else + { + mlp->pv.lp_mip_gap = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n", + "LP/MIP", f_tmp); + } } - } /* Get timeout for iterations */ if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time(env->cfg, "ats", - "MLP_MAX_DURATION", &max_duration)) - { - max_duration = MLP_MAX_EXEC_DURATION; - } + "MLP_MAX_DURATION", &max_duration)) + { + max_duration = MLP_MAX_EXEC_DURATION; + } /* Get maximum number of iterations */ if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_size(env->cfg, "ats", - "MLP_MAX_ITERATIONS", &max_iterations)) - { - max_iterations = MLP_MAX_ITERATIONS; - } + "MLP_MAX_ITERATIONS", &max_iterations)) + { + max_iterations = MLP_MAX_ITERATIONS; + } /* Get diversity coefficient from configuration */ mlp->pv.co_D = MLP_DEFAULT_D; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "MLP_COEFFICIENT_D", &f_tmp)) - { - if ((f_tmp < 0.0)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "MLP_COEFFICIENT_D", f_tmp); - } - else + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "MLP_COEFFICIENT_D", &f_tmp)) { - mlp->pv.co_D = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n", - "MLP_COEFFICIENT_D", f_tmp); + if ((f_tmp < 0.0)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "MLP_COEFFICIENT_D", f_tmp); + } + else + { + mlp->pv.co_D = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n", + "MLP_COEFFICIENT_D", f_tmp); + } } - } /* Get relativity coefficient from configuration */ mlp->pv.co_R = MLP_DEFAULT_R; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "MLP_COEFFICIENT_R", &f_tmp)) - { - if ((f_tmp < 0.0)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "MLP_COEFFICIENT_R", f_tmp); - } - else + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "MLP_COEFFICIENT_R", &f_tmp)) { - mlp->pv.co_R = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n", - "MLP_COEFFICIENT_R", f_tmp); + if ((f_tmp < 0.0)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "MLP_COEFFICIENT_R", f_tmp); + } + else + { + mlp->pv.co_R = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n", + "MLP_COEFFICIENT_R", f_tmp); + } } - } /* Get utilization coefficient from configuration */ mlp->pv.co_U = MLP_DEFAULT_U; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "MLP_COEFFICIENT_U", &f_tmp)) - { - if ((f_tmp < 0.0)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "MLP_COEFFICIENT_U", f_tmp); - } - else + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "MLP_COEFFICIENT_U", &f_tmp)) { - mlp->pv.co_U = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n", - "MLP_COEFFICIENT_U", f_tmp); + if ((f_tmp < 0.0)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "MLP_COEFFICIENT_U", f_tmp); + } + else + { + mlp->pv.co_U = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s gap of %.3f\n", + "MLP_COEFFICIENT_U", f_tmp); + } } - } /* Get quality metric coefficients from configuration */ for (c = 0; c < RQ_QUALITY_METRIC_COUNT; c++) - { - /* initialize quality coefficients with default value 1.0 */ - mlp->pv.co_Q[c] = MLP_DEFAULT_QUALITY; - } + { + /* initialize quality coefficients with default value 1.0 */ + mlp->pv.co_Q[c] = MLP_DEFAULT_QUALITY; + } if (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats", - "MLP_COEFFICIENT_QUALITY_DELAY", - &tmp)) - mlp->pv.co_Q[RQ_QUALITY_METRIC_DELAY] = (double) tmp / 100; + GNUNET_CONFIGURATION_get_value_size(env->cfg, "ats", + "MLP_COEFFICIENT_QUALITY_DELAY", + &tmp)) + mlp->pv.co_Q[RQ_QUALITY_METRIC_DELAY] = (double)tmp / 100; else mlp->pv.co_Q[RQ_QUALITY_METRIC_DELAY] = MLP_DEFAULT_QUALITY; if (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats", - "MLP_COEFFICIENT_QUALITY_DISTANCE", - &tmp)) - mlp->pv.co_Q[RQ_QUALITY_METRIC_DISTANCE] = (double) tmp / 100; + GNUNET_CONFIGURATION_get_value_size(env->cfg, "ats", + "MLP_COEFFICIENT_QUALITY_DISTANCE", + &tmp)) + mlp->pv.co_Q[RQ_QUALITY_METRIC_DISTANCE] = (double)tmp / 100; else mlp->pv.co_Q[RQ_QUALITY_METRIC_DISTANCE] = MLP_DEFAULT_QUALITY; /* Get minimum bandwidth per used address from configuration */ - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats", - "MLP_MIN_BANDWIDTH", - &tmp)) + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size(env->cfg, "ats", + "MLP_MIN_BANDWIDTH", + &tmp)) b_min = tmp; else - { - b_min = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__); - } + { + b_min = ntohl(GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__); + } /* Get minimum number of connections from configuration */ - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats", - "MLP_MIN_CONNECTIONS", - &tmp)) + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size(env->cfg, "ats", + "MLP_MIN_CONNECTIONS", + &tmp)) n_min = tmp; else n_min = MLP_DEFAULT_MIN_CONNECTIONS; /* Init network quotas */ for (c = 0; c < GNUNET_NT_COUNT; c++) - { - mlp->pv.quota_index[c] = c; - mlp->pv.quota_out[c] = env->out_quota[c]; - mlp->pv.quota_in[c] = env->in_quota[c]; - - LOG (GNUNET_ERROR_TYPE_INFO, - "Quota for network `%s' (in/out) %llu/%llu\n", - GNUNET_NT_to_string (c), - mlp->pv.quota_out[c], - mlp->pv.quota_in[c]); - /* Check if defined quota could make problem unsolvable */ - if ((n_min * b_min) > mlp->pv.quota_out[c]) - { - LOG (GNUNET_ERROR_TYPE_INFO, - _("Adjusting inconsistent outbound quota configuration for network `%s', is %llu must be at least %llu\n"), - GNUNET_NT_to_string(mlp->pv.quota_index[c]), - mlp->pv.quota_out[c], - (n_min * b_min)); - mlp->pv.quota_out[c] = (n_min * b_min); - } - if ((n_min * b_min) > mlp->pv.quota_in[c]) - { - LOG (GNUNET_ERROR_TYPE_INFO, - _("Adjusting inconsistent inbound quota configuration for network `%s', is %llu must be at least %llu\n"), - GNUNET_NT_to_string(mlp->pv.quota_index[c]), - mlp->pv.quota_in[c], - (n_min * b_min)); - mlp->pv.quota_in[c] = (n_min * b_min); - } - /* Check if bandwidth is too big to make problem solvable */ - if (mlp->pv.BIG_M < mlp->pv.quota_out[c]) - { - LOG (GNUNET_ERROR_TYPE_INFO, - _("Adjusting outbound quota configuration for network `%s'from %llu to %.0f\n"), - GNUNET_NT_to_string(mlp->pv.quota_index[c]), - mlp->pv.quota_out[c], - mlp->pv.BIG_M); - mlp->pv.quota_out[c] = mlp->pv.BIG_M ; - } - if (mlp->pv.BIG_M < mlp->pv.quota_in[c]) - { - LOG (GNUNET_ERROR_TYPE_INFO, - _("Adjusting inbound quota configuration for network `%s' from %llu to %.0f\n"), - GNUNET_NT_to_string(mlp->pv.quota_index[c]), - mlp->pv.quota_in[c], - mlp->pv.BIG_M); - mlp->pv.quota_in[c] = mlp->pv.BIG_M ; - } - } + { + mlp->pv.quota_index[c] = c; + mlp->pv.quota_out[c] = env->out_quota[c]; + mlp->pv.quota_in[c] = env->in_quota[c]; + + LOG(GNUNET_ERROR_TYPE_INFO, + "Quota for network `%s' (in/out) %llu/%llu\n", + GNUNET_NT_to_string(c), + mlp->pv.quota_out[c], + mlp->pv.quota_in[c]); + /* Check if defined quota could make problem unsolvable */ + if ((n_min * b_min) > mlp->pv.quota_out[c]) + { + LOG(GNUNET_ERROR_TYPE_INFO, + _("Adjusting inconsistent outbound quota configuration for network `%s', is %llu must be at least %llu\n"), + GNUNET_NT_to_string(mlp->pv.quota_index[c]), + mlp->pv.quota_out[c], + (n_min * b_min)); + mlp->pv.quota_out[c] = (n_min * b_min); + } + if ((n_min * b_min) > mlp->pv.quota_in[c]) + { + LOG(GNUNET_ERROR_TYPE_INFO, + _("Adjusting inconsistent inbound quota configuration for network `%s', is %llu must be at least %llu\n"), + GNUNET_NT_to_string(mlp->pv.quota_index[c]), + mlp->pv.quota_in[c], + (n_min * b_min)); + mlp->pv.quota_in[c] = (n_min * b_min); + } + /* Check if bandwidth is too big to make problem solvable */ + if (mlp->pv.BIG_M < mlp->pv.quota_out[c]) + { + LOG(GNUNET_ERROR_TYPE_INFO, + _("Adjusting outbound quota configuration for network `%s'from %llu to %.0f\n"), + GNUNET_NT_to_string(mlp->pv.quota_index[c]), + mlp->pv.quota_out[c], + mlp->pv.BIG_M); + mlp->pv.quota_out[c] = mlp->pv.BIG_M; + } + if (mlp->pv.BIG_M < mlp->pv.quota_in[c]) + { + LOG(GNUNET_ERROR_TYPE_INFO, + _("Adjusting inbound quota configuration for network `%s' from %llu to %.0f\n"), + GNUNET_NT_to_string(mlp->pv.quota_index[c]), + mlp->pv.quota_in[c], + mlp->pv.BIG_M); + mlp->pv.quota_in[c] = mlp->pv.BIG_M; + } + } mlp->env = env; sf.cls = mlp; sf.s_add = &GAS_mlp_address_add; @@ -2722,13 +2770,13 @@ libgnunet_plugin_ats_mlp_init (void *cls) mlp->stat_mlp_prob_changed = GNUNET_NO; mlp->stat_mlp_prob_updated = GNUNET_NO; mlp->opt_mlp_auto_solve = GNUNET_YES; - mlp->requested_peers = GNUNET_CONTAINER_multipeermap_create (10, GNUNET_NO); + mlp->requested_peers = GNUNET_CONTAINER_multipeermap_create(10, GNUNET_NO); mlp->stat_bulk_requests = 0; mlp->stat_bulk_lock = 0; /* Setup GLPK */ /* Redirect GLPK output to GNUnet logging */ - glp_term_hook (&mlp_term_hook, (void *) mlp); + glp_term_hook(&mlp_term_hook, (void *)mlp); /* Init LP solving parameters */ glp_init_smcp(&mlp->control_param_lp); @@ -2750,7 +2798,7 @@ libgnunet_plugin_ats_mlp_init (void *cls) mlp->control_param_mlp.msg_lev = GLP_MSG_ALL; mlp->control_param_mlp.tm_lim = max_duration.rel_value_us / 1000LL; - LOG (GNUNET_ERROR_TYPE_DEBUG, "solver ready\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, "solver ready\n"); return &sf; } diff --git a/src/ats/plugin_ats_proportional.c b/src/ats/plugin_ats_proportional.c index 3fab09fb3..bdb5d6cf0 100644 --- a/src/ats/plugin_ats_proportional.c +++ b/src/ats/plugin_ats_proportional.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2011-2015 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2011-2015 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -29,7 +29,7 @@ #include "gnunet_ats_plugin.h" #include "gnunet-service-ats_addresses.h" -#define LOG(kind,...) GNUNET_log_from (kind, "ats-proportional",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "ats-proportional", __VA_ARGS__) /** * How much do we value stability over adaptation by default. A low @@ -58,8 +58,7 @@ * They are also stored in the respective `struct Network`'s linked * list. */ -struct AddressWrapper -{ +struct AddressWrapper { /** * Next in DLL */ @@ -75,7 +74,7 @@ struct AddressWrapper */ struct ATS_Address *addr; - /** + /** * Network scope this address is in */ struct Network *network; @@ -94,15 +93,13 @@ struct AddressWrapper * When was this address activated */ struct GNUNET_TIME_Absolute activated; - }; /** * Representation of a network */ -struct Network -{ +struct Network { /** * Network description */ @@ -152,16 +149,13 @@ struct Network * Number of total addresses for this network */ unsigned int total_addresses; - }; /** * A handle for the proportional solver */ -struct GAS_PROPORTIONAL_Handle -{ - +struct GAS_PROPORTIONAL_Handle { /** * Our execution environment. */ @@ -197,7 +191,6 @@ struct GAS_PROPORTIONAL_Handle * Number of active addresses for solver */ unsigned int active_addresses; - }; @@ -209,18 +202,18 @@ struct GAS_PROPORTIONAL_Handle * @return #GNUNET_YES or #GNUNET_NO */ static int -is_bandwidth_available_in_network (struct Network *net, - int extra) +is_bandwidth_available_in_network(struct Network *net, + int extra) { unsigned int na; - uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__); + uint32_t min_bw = ntohl(GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__); - GNUNET_assert (((int)net->active_addresses) + extra >= 0); + GNUNET_assert(((int)net->active_addresses) + extra >= 0); na = net->active_addresses + extra; if (0 == na) return GNUNET_YES; - if ( ((net->total_quota_in / na) > min_bw) && - ((net->total_quota_out / na) > min_bw) ) + if (((net->total_quota_in / na) > min_bw) && + ((net->total_quota_out / na) > min_bw)) return GNUNET_YES; return GNUNET_NO; } @@ -236,16 +229,16 @@ is_bandwidth_available_in_network (struct Network *net, * @return #GNUNET_YES or #GNUNET_NO */ static int -all_require_connectivity (struct GAS_PROPORTIONAL_Handle *s, - struct Network *net, - unsigned int con) +all_require_connectivity(struct GAS_PROPORTIONAL_Handle *s, + struct Network *net, + unsigned int con) { struct AddressWrapper *aw; for (aw = net->head; NULL != aw; aw = aw->next) if (con > - s->env->get_connectivity (s->env->cls, - &aw->addr->peer)) + s->env->get_connectivity(s->env->cls, + &aw->addr->peer)) return GNUNET_NO; return GNUNET_YES; } @@ -261,10 +254,10 @@ all_require_connectivity (struct GAS_PROPORTIONAL_Handle *s, * @param net the network type to update */ static void -distribute_bandwidth (struct GAS_PROPORTIONAL_Handle *s, - struct Network *net) +distribute_bandwidth(struct GAS_PROPORTIONAL_Handle *s, + struct Network *net) { - const uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__); + const uint32_t min_bw = ntohl(GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__); struct AddressWrapper *aw; unsigned long long remaining_quota_in; unsigned long long quota_out_used; @@ -276,110 +269,110 @@ distribute_bandwidth (struct GAS_PROPORTIONAL_Handle *s, double total_weight; const double *peer_relative_prefs; - LOG (GNUNET_ERROR_TYPE_INFO, - "Recalculate quota for network type `%s' for %u addresses (in/out): %llu/%llu \n", - net->desc, - net->active_addresses, - net->total_quota_in, - net->total_quota_in); + LOG(GNUNET_ERROR_TYPE_INFO, + "Recalculate quota for network type `%s' for %u addresses (in/out): %llu/%llu \n", + net->desc, + net->active_addresses, + net->total_quota_in, + net->total_quota_in); if (0 == net->active_addresses) return; /* no addresses to update */ /* sanity checks */ if ((net->active_addresses * min_bw) > net->total_quota_in) - { - GNUNET_break(0); - return; - } + { + GNUNET_break(0); + return; + } if ((net->active_addresses * min_bw) > net->total_quota_out) - { - GNUNET_break(0); - return; - } + { + GNUNET_break(0); + return; + } /* Calculate sum of relative preference for active addresses in this network */ sum_relative_peer_prefences = 0.0; count_addresses = 0; for (aw = net->head; NULL != aw; aw = aw->next) - { - if (GNUNET_YES != aw->addr->active) - continue; - peer_relative_prefs = s->env->get_preferences (s->env->cls, - &aw->addr->peer); - sum_relative_peer_prefences - += peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH]; - count_addresses++; - } + { + if (GNUNET_YES != aw->addr->active) + continue; + peer_relative_prefs = s->env->get_preferences(s->env->cls, + &aw->addr->peer); + sum_relative_peer_prefences + += peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH]; + count_addresses++; + } if (count_addresses != net->active_addresses) - { - GNUNET_break (0); - LOG (GNUNET_ERROR_TYPE_WARNING, - "%s: Counted %u active addresses, expected %u active addresses\n", - net->desc, - count_addresses, - net->active_addresses); - /* try to fix... */ - net->active_addresses = count_addresses; - } - LOG (GNUNET_ERROR_TYPE_INFO, - "Total relative preference %.3f for %u addresses in network %s\n", - sum_relative_peer_prefences, - net->active_addresses, - net->desc); + { + GNUNET_break(0); + LOG(GNUNET_ERROR_TYPE_WARNING, + "%s: Counted %u active addresses, expected %u active addresses\n", + net->desc, + count_addresses, + net->active_addresses); + /* try to fix... */ + net->active_addresses = count_addresses; + } + LOG(GNUNET_ERROR_TYPE_INFO, + "Total relative preference %.3f for %u addresses in network %s\n", + sum_relative_peer_prefences, + net->active_addresses, + net->desc); /* check how much we have to distribute */ remaining_quota_in = net->total_quota_in - (net->active_addresses * min_bw); remaining_quota_out = net->total_quota_out - (net->active_addresses * min_bw); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Proportionally distributable bandwidth (in/out): %llu/%llu\n", - remaining_quota_in, - remaining_quota_out); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Proportionally distributable bandwidth (in/out): %llu/%llu\n", + remaining_quota_in, + remaining_quota_out); /* distribute remaining quota; we do not do it exactly proportional, but balance "even" distribution ("net->active_addresses") with the preference sum using the "prop_factor". */ total_weight = net->active_addresses + - s->prop_factor * sum_relative_peer_prefences; + s->prop_factor * sum_relative_peer_prefences; quota_out_used = 0; quota_in_used = 0; for (aw = net->head; NULL != aw; aw = aw->next) - { - if (GNUNET_YES != aw->addr->active) { - /* set to 0, just to be sure */ - aw->calculated_quota_in = 0; - aw->calculated_quota_out = 0; - continue; + if (GNUNET_YES != aw->addr->active) + { + /* set to 0, just to be sure */ + aw->calculated_quota_in = 0; + aw->calculated_quota_out = 0; + continue; + } + peer_relative_prefs = s->env->get_preferences(s->env->cls, + &aw->addr->peer); + peer_weight = 1.0 + + s->prop_factor * peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH]; + + aw->calculated_quota_in = min_bw + + (peer_weight / total_weight) * remaining_quota_in; + aw->calculated_quota_out = min_bw + + (peer_weight / total_weight) * remaining_quota_out; + + LOG(GNUNET_ERROR_TYPE_INFO, + "New quotas for peer `%s' with weight (cur/total) %.3f/%.3f (in/out) are: %u/%u\n", + GNUNET_i2s(&aw->addr->peer), + peer_weight, + total_weight, + (unsigned int)aw->calculated_quota_in, + (unsigned int)aw->calculated_quota_out); + quota_in_used += aw->calculated_quota_in; + quota_out_used += aw->calculated_quota_out; } - peer_relative_prefs = s->env->get_preferences (s->env->cls, - &aw->addr->peer); - peer_weight = 1.0 - + s->prop_factor * peer_relative_prefs[GNUNET_ATS_PREFERENCE_BANDWIDTH]; - - aw->calculated_quota_in = min_bw - + (peer_weight / total_weight) * remaining_quota_in; - aw->calculated_quota_out = min_bw - + (peer_weight / total_weight) * remaining_quota_out; - - LOG (GNUNET_ERROR_TYPE_INFO, - "New quotas for peer `%s' with weight (cur/total) %.3f/%.3f (in/out) are: %u/%u\n", - GNUNET_i2s (&aw->addr->peer), - peer_weight, - total_weight, - (unsigned int) aw->calculated_quota_in, - (unsigned int) aw->calculated_quota_out); - quota_in_used += aw->calculated_quota_in; - quota_out_used += aw->calculated_quota_out; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Total bandwidth assigned is (in/out): %llu /%llu\n", - quota_in_used, - quota_out_used); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Total bandwidth assigned is (in/out): %llu /%llu\n", + quota_in_used, + quota_out_used); /* +1 due to possible rounding errors */ - GNUNET_break (quota_out_used <= net->total_quota_out + 1); - GNUNET_break (quota_in_used <= net->total_quota_in + 1); + GNUNET_break(quota_out_used <= net->total_quota_out + 1); + GNUNET_break(quota_in_used <= net->total_quota_in + 1); } @@ -390,22 +383,22 @@ distribute_bandwidth (struct GAS_PROPORTIONAL_Handle *s, * @param net the network to propagate changes in */ static void -propagate_bandwidth (struct GAS_PROPORTIONAL_Handle *s, - struct Network *net) +propagate_bandwidth(struct GAS_PROPORTIONAL_Handle *s, + struct Network *net) { struct AddressWrapper *cur; for (cur = net->head; NULL != cur; cur = cur->next) - { - if ( (cur->addr->assigned_bw_in == cur->calculated_quota_in) && - (cur->addr->assigned_bw_out == cur->calculated_quota_out) ) - continue; - cur->addr->assigned_bw_in = cur->calculated_quota_in; - cur->addr->assigned_bw_out = cur->calculated_quota_out; - if (GNUNET_YES == cur->addr->active) - s->env->bandwidth_changed_cb (s->env->cls, - cur->addr); - } + { + if ((cur->addr->assigned_bw_in == cur->calculated_quota_in) && + (cur->addr->assigned_bw_out == cur->calculated_quota_out)) + continue; + cur->addr->assigned_bw_in = cur->calculated_quota_in; + cur->addr->assigned_bw_out = cur->calculated_quota_out; + if (GNUNET_YES == cur->addr->active) + s->env->bandwidth_changed_cb(s->env->cls, + cur->addr); + } } @@ -417,81 +410,80 @@ propagate_bandwidth (struct GAS_PROPORTIONAL_Handle *s, * @param n the network, can be NULL for all networks */ static void -distribute_bandwidth_in_network (struct GAS_PROPORTIONAL_Handle *s, - struct Network *n) +distribute_bandwidth_in_network(struct GAS_PROPORTIONAL_Handle *s, + struct Network *n) { unsigned int i; if (0 != s->bulk_lock) - { - s->bulk_requests++; - return; - } + { + s->bulk_requests++; + return; + } if (NULL != n) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Redistributing bandwidth in network %s with %u active and %u total addresses\n", - GNUNET_NT_to_string(n->type), - n->active_addresses, - n->total_addresses); - s->env->info_cb (s->env->cls, - GAS_OP_SOLVE_START, - GAS_STAT_SUCCESS, - GAS_INFO_PROP_SINGLE); - distribute_bandwidth(s, - n); - s->env->info_cb (s->env->cls, - GAS_OP_SOLVE_STOP, - GAS_STAT_SUCCESS, - GAS_INFO_PROP_SINGLE); - s->env->info_cb (s->env->cls, - GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, - GAS_STAT_SUCCESS, - GAS_INFO_PROP_SINGLE); - propagate_bandwidth (s, - n); - - s->env->info_cb (s->env->cls, - GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, - GAS_STAT_SUCCESS, - GAS_INFO_PROP_SINGLE); - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Redistributing bandwidth in network %s with %u active and %u total addresses\n", + GNUNET_NT_to_string(n->type), + n->active_addresses, + n->total_addresses); + s->env->info_cb(s->env->cls, + GAS_OP_SOLVE_START, + GAS_STAT_SUCCESS, + GAS_INFO_PROP_SINGLE); + distribute_bandwidth(s, + n); + s->env->info_cb(s->env->cls, + GAS_OP_SOLVE_STOP, + GAS_STAT_SUCCESS, + GAS_INFO_PROP_SINGLE); + s->env->info_cb(s->env->cls, + GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, + GAS_STAT_SUCCESS, + GAS_INFO_PROP_SINGLE); + propagate_bandwidth(s, + n); + + s->env->info_cb(s->env->cls, + GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, + GAS_STAT_SUCCESS, + GAS_INFO_PROP_SINGLE); + } else - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Redistributing bandwidth in all %u networks\n", - s->env->network_count); - s->env->info_cb (s->env->cls, - GAS_OP_SOLVE_START, - GAS_STAT_SUCCESS, - GAS_INFO_PROP_ALL); - for (i = 0; i < s->env->network_count; i++) - distribute_bandwidth (s, + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Redistributing bandwidth in all %u networks\n", + s->env->network_count); + s->env->info_cb(s->env->cls, + GAS_OP_SOLVE_START, + GAS_STAT_SUCCESS, + GAS_INFO_PROP_ALL); + for (i = 0; i < s->env->network_count; i++) + distribute_bandwidth(s, + &s->network_entries[i]); + s->env->info_cb(s->env->cls, + GAS_OP_SOLVE_STOP, + GAS_STAT_SUCCESS, + GAS_INFO_PROP_ALL); + s->env->info_cb(s->env->cls, + GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, + GAS_STAT_SUCCESS, + GAS_INFO_PROP_ALL); + for (i = 0; i < s->env->network_count; i++) + propagate_bandwidth(s, &s->network_entries[i]); - s->env->info_cb (s->env->cls, - GAS_OP_SOLVE_STOP, - GAS_STAT_SUCCESS, - GAS_INFO_PROP_ALL); - s->env->info_cb (s->env->cls, - GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, - GAS_STAT_SUCCESS, - GAS_INFO_PROP_ALL); - for (i = 0; i < s->env->network_count; i++) - propagate_bandwidth (s, - &s->network_entries[i]); - s->env->info_cb (s->env->cls, - GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, - GAS_STAT_SUCCESS, - GAS_INFO_PROP_ALL); - } + s->env->info_cb(s->env->cls, + GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, + GAS_STAT_SUCCESS, + GAS_INFO_PROP_ALL); + } } /** * Context for finding the best address* Linked list of addresses in this network: head */ -struct FindBestAddressCtx -{ +struct FindBestAddressCtx { /** * The solver handle */ @@ -516,9 +508,9 @@ struct FindBestAddressCtx * @return #GNUNET_OK (continue to iterate) */ static int -find_best_address_it (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +find_best_address_it(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct FindBestAddressCtx *ctx = cls; struct ATS_Address *current = value; @@ -536,48 +528,48 @@ find_best_address_it (void *cls, need = (GNUNET_YES == current->active) ? 0 : 1; /* we save -1 slot if 'best' is active and belongs to the same network (as we would replace it) */ - if ( (NULL != ctx->best) && - (GNUNET_YES == ctx->best->active) && - (((struct AddressWrapper *) ctx->best->solver_information)->network == - asi->network) ) + if ((NULL != ctx->best) && + (GNUNET_YES == ctx->best->active) && + (((struct AddressWrapper *)ctx->best->solver_information)->network == + asi->network)) need--; /* we can gain -1 slot if this peers connectivity requirement is higher than that of another peer in that network scope */ - con = ctx->s->env->get_connectivity (ctx->s->env->cls, - key); + con = ctx->s->env->get_connectivity(ctx->s->env->cls, + key); if (GNUNET_YES != - all_require_connectivity (ctx->s, - asi->network, - con)) + all_require_connectivity(ctx->s, + asi->network, + con)) need--; /* test if minimum bandwidth for 'current' would be available */ bw_available - = is_bandwidth_available_in_network (asi->network, - need); - if (! bw_available) - { - /* Bandwidth for this address is unavailable, so we cannot use - it. */ - return GNUNET_OK; - } + = is_bandwidth_available_in_network(asi->network, + need); + if (!bw_available) + { + /* Bandwidth for this address is unavailable, so we cannot use + it. */ + return GNUNET_OK; + } if (GNUNET_YES == current->active) - { - active_time = GNUNET_TIME_absolute_get_duration (asi->activated); - if (active_time.rel_value_us <= - ((double) GNUNET_TIME_UNIT_SECONDS.rel_value_us) * ctx->s->stability_factor) { - /* Keep active address for stability reasons */ - ctx->best = current; - return GNUNET_NO; + active_time = GNUNET_TIME_absolute_get_duration(asi->activated); + if (active_time.rel_value_us <= + ((double)GNUNET_TIME_UNIT_SECONDS.rel_value_us) * ctx->s->stability_factor) + { + /* Keep active address for stability reasons */ + ctx->best = current; + return GNUNET_NO; + } } - } if (NULL == ctx->best) - { - /* We so far have nothing else, so go with it! */ - ctx->best = current; - return GNUNET_OK; - } + { + /* We so far have nothing else, so go with it! */ + ctx->best = current; + return GNUNET_OK; + } /* Now compare ATS information */ cur_distance = current->norm_distance.norm; @@ -587,33 +579,33 @@ find_best_address_it (void *cls, /* user shorter distance */ if (cur_distance < best_distance) - { - if (GNUNET_NO == ctx->best->active) - { - /* Activity doesn't influence the equation, use current */ - ctx->best = current; - } - else if ((best_distance / cur_distance) > ctx->s->stability_factor) { - /* Distance change is significant, switch active address! */ - ctx->best = current; + if (GNUNET_NO == ctx->best->active) + { + /* Activity doesn't influence the equation, use current */ + ctx->best = current; + } + else if ((best_distance / cur_distance) > ctx->s->stability_factor) + { + /* Distance change is significant, switch active address! */ + ctx->best = current; + } } - } /* User connection with less delay */ if (cur_delay < best_delay) - { - if (GNUNET_NO == ctx->best->active) { - /* Activity doesn't influence the equation, use current */ - ctx->best = current; - } - else if ((best_delay / cur_delay) > ctx->s->stability_factor) - { - /* Latency change is significant, switch active address! */ - ctx->best = current; + if (GNUNET_NO == ctx->best->active) + { + /* Activity doesn't influence the equation, use current */ + ctx->best = current; + } + else if ((best_delay / cur_delay) > ctx->s->stability_factor) + { + /* Latency change is significant, switch active address! */ + ctx->best = current; + } } - } return GNUNET_OK; } @@ -628,18 +620,18 @@ find_best_address_it (void *cls, * @return the address or NULL */ struct ATS_Address * -get_best_address (struct GAS_PROPORTIONAL_Handle *s, - struct GNUNET_CONTAINER_MultiPeerMap *addresses, - const struct GNUNET_PeerIdentity *id) +get_best_address(struct GAS_PROPORTIONAL_Handle *s, + struct GNUNET_CONTAINER_MultiPeerMap *addresses, + const struct GNUNET_PeerIdentity *id) { struct FindBestAddressCtx fba_ctx; fba_ctx.best = NULL; fba_ctx.s = s; - GNUNET_CONTAINER_multipeermap_get_multiple (addresses, - id, - &find_best_address_it, - &fba_ctx); + GNUNET_CONTAINER_multipeermap_get_multiple(addresses, + id, + &find_best_address_it, + &fba_ctx); return fba_ctx.best; } @@ -651,21 +643,21 @@ get_best_address (struct GAS_PROPORTIONAL_Handle *s, * @param net the network type */ static void -address_decrement_active (struct GAS_PROPORTIONAL_Handle *s, - struct Network *net) +address_decrement_active(struct GAS_PROPORTIONAL_Handle *s, + struct Network *net) { - GNUNET_assert (net->active_addresses > 0); + GNUNET_assert(net->active_addresses > 0); net->active_addresses--; - GNUNET_STATISTICS_update (s->env->stats, - net->stat_active, - -1, - GNUNET_NO); - GNUNET_assert (s->active_addresses > 0); + GNUNET_STATISTICS_update(s->env->stats, + net->stat_active, + -1, + GNUNET_NO); + GNUNET_assert(s->active_addresses > 0); s->active_addresses--; - GNUNET_STATISTICS_update (s->env->stats, - "# ATS addresses total", - -1, - GNUNET_NO); + GNUNET_STATISTICS_update(s->env->stats, + "# ATS addresses total", + -1, + GNUNET_NO); } @@ -679,16 +671,16 @@ address_decrement_active (struct GAS_PROPORTIONAL_Handle *s, * @return #GNUNET_NO on double active address else #GNUNET_YES; */ static int -get_active_address_it (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +get_active_address_it(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct ATS_Address **dest = cls; struct ATS_Address *aa = value; if (GNUNET_YES != aa->active) return GNUNET_OK; - GNUNET_assert (NULL == (*dest)); + GNUNET_assert(NULL == (*dest)); (*dest) = aa; return GNUNET_OK; } @@ -702,16 +694,16 @@ get_active_address_it (void *cls, * @return active address or NULL */ static struct ATS_Address * -get_active_address (struct GAS_PROPORTIONAL_Handle *s, - const struct GNUNET_PeerIdentity *peer) +get_active_address(struct GAS_PROPORTIONAL_Handle *s, + const struct GNUNET_PeerIdentity *peer) { struct ATS_Address *dest; dest = NULL; - GNUNET_CONTAINER_multipeermap_get_multiple (s->env->addresses, - peer, - &get_active_address_it, - &dest); + GNUNET_CONTAINER_multipeermap_get_multiple(s->env->addresses, + peer, + &get_active_address_it, + &dest); return dest; } @@ -727,9 +719,9 @@ get_active_address (struct GAS_PROPORTIONAL_Handle *s, * @param peer the peer to check */ static void -update_active_address (struct GAS_PROPORTIONAL_Handle *s, - struct ATS_Address *current_address, - const struct GNUNET_PeerIdentity *peer) +update_active_address(struct GAS_PROPORTIONAL_Handle *s, + struct ATS_Address *current_address, + const struct GNUNET_PeerIdentity *peer) { struct ATS_Address *best_address; struct AddressWrapper *asi_cur; @@ -739,9 +731,9 @@ update_active_address (struct GAS_PROPORTIONAL_Handle *s, unsigned int a_con; unsigned int con_min; - best_address = get_best_address (s, - s->env->addresses, - peer); + best_address = get_best_address(s, + s->env->addresses, + peer); if (NULL != best_address) asi_best = best_address->solver_information; else @@ -749,98 +741,98 @@ update_active_address (struct GAS_PROPORTIONAL_Handle *s, if (current_address == best_address) return; /* no changes */ if (NULL != current_address) - { - /* We switch to a new address (or to none); - mark old address as inactive. */ - asi_cur = current_address->solver_information; - GNUNET_assert (GNUNET_YES == current_address->active); - LOG (GNUNET_ERROR_TYPE_INFO, - "Disabling previous active address for peer `%s'\n", - GNUNET_i2s (peer)); - asi_cur->activated = GNUNET_TIME_UNIT_ZERO_ABS; - current_address->active = GNUNET_NO; - current_address->assigned_bw_in = 0; - current_address->assigned_bw_out = 0; - address_decrement_active (s, - asi_cur->network); - if ( (NULL == best_address) || - (asi_best->network != asi_cur->network) ) - distribute_bandwidth_in_network (s, - asi_cur->network); - if (NULL == best_address) { - /* We previously had an active address, but now we cannot - * suggest one. Therefore we have to disconnect the peer. - * The above call to "distribute_bandwidth_in_network() - * does not see 'current_address' so we need to trigger - * the update here. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Disconnecting peer `%s'.\n", - GNUNET_i2s (peer)); - s->env->bandwidth_changed_cb (s->env->cls, - current_address); - return; + /* We switch to a new address (or to none); + mark old address as inactive. */ + asi_cur = current_address->solver_information; + GNUNET_assert(GNUNET_YES == current_address->active); + LOG(GNUNET_ERROR_TYPE_INFO, + "Disabling previous active address for peer `%s'\n", + GNUNET_i2s(peer)); + asi_cur->activated = GNUNET_TIME_UNIT_ZERO_ABS; + current_address->active = GNUNET_NO; + current_address->assigned_bw_in = 0; + current_address->assigned_bw_out = 0; + address_decrement_active(s, + asi_cur->network); + if ((NULL == best_address) || + (asi_best->network != asi_cur->network)) + distribute_bandwidth_in_network(s, + asi_cur->network); + if (NULL == best_address) + { + /* We previously had an active address, but now we cannot + * suggest one. Therefore we have to disconnect the peer. + * The above call to "distribute_bandwidth_in_network() + * does not see 'current_address' so we need to trigger + * the update here. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Disconnecting peer `%s'.\n", + GNUNET_i2s(peer)); + s->env->bandwidth_changed_cb(s->env->cls, + current_address); + return; + } } - } if (NULL == best_address) - { - /* We do not have a new address, so we are done. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Cannot suggest address for peer `%s'\n", - GNUNET_i2s (peer)); - return; - } + { + /* We do not have a new address, so we are done. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Cannot suggest address for peer `%s'\n", + GNUNET_i2s(peer)); + return; + } /* We do have a new address, activate it */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Selecting new address %p for peer `%s'\n", - best_address, - GNUNET_i2s (peer)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Selecting new address %p for peer `%s'\n", + best_address, + GNUNET_i2s(peer)); /* Mark address as active */ best_address->active = GNUNET_YES; - asi_best->activated = GNUNET_TIME_absolute_get (); + asi_best->activated = GNUNET_TIME_absolute_get(); asi_best->network->active_addresses++; s->active_addresses++; - GNUNET_STATISTICS_update (s->env->stats, - "# ATS active addresses total", - 1, - GNUNET_NO); - GNUNET_STATISTICS_update (s->env->stats, - asi_best->network->stat_active, - 1, - GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_INFO, - "Address %p for peer `%s' is now active\n", - best_address, - GNUNET_i2s (peer)); + GNUNET_STATISTICS_update(s->env->stats, + "# ATS active addresses total", + 1, + GNUNET_NO); + GNUNET_STATISTICS_update(s->env->stats, + asi_best->network->stat_active, + 1, + GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_INFO, + "Address %p for peer `%s' is now active\n", + best_address, + GNUNET_i2s(peer)); if (GNUNET_NO == - is_bandwidth_available_in_network (asi_best->network, - 0)) - { - /* we went over the maximum number of addresses for - this scope; remove the address with the smallest - connectivity requirement */ - con_min = UINT32_MAX; - aw_min = NULL; - for (aw = asi_best->network->head; NULL != aw; aw = aw->next) + is_bandwidth_available_in_network(asi_best->network, + 0)) { - if ( (con_min > - (a_con = s->env->get_connectivity (s->env->cls, - &aw->addr->peer))) && - (GNUNET_YES == aw->addr->active) ) - { - aw_min = aw; - con_min = a_con; - if (0 == con_min) - break; - } + /* we went over the maximum number of addresses for + this scope; remove the address with the smallest + connectivity requirement */ + con_min = UINT32_MAX; + aw_min = NULL; + for (aw = asi_best->network->head; NULL != aw; aw = aw->next) + { + if ((con_min > + (a_con = s->env->get_connectivity(s->env->cls, + &aw->addr->peer))) && + (GNUNET_YES == aw->addr->active)) + { + aw_min = aw; + con_min = a_con; + if (0 == con_min) + break; + } + } + update_active_address(s, + aw_min->addr, + &aw_min->addr->peer); } - update_active_address (s, - aw_min->addr, - &aw_min->addr->peer); - } - distribute_bandwidth_in_network (s, - asi_best->network); + distribute_bandwidth_in_network(s, + asi_best->network); } @@ -853,17 +845,17 @@ update_active_address (struct GAS_PROPORTIONAL_Handle *s, * @param pref_rel the normalized preference value for this kind over all clients */ static void -GAS_proportional_change_preference (void *solver, - const struct GNUNET_PeerIdentity *peer, - enum GNUNET_ATS_PreferenceKind kind, - double pref_rel) +GAS_proportional_change_preference(void *solver, + const struct GNUNET_PeerIdentity *peer, + enum GNUNET_ATS_PreferenceKind kind, + double pref_rel) { struct GAS_PROPORTIONAL_Handle *s = solver; if (GNUNET_ATS_PREFERENCE_BANDWIDTH != kind) return; /* we do not care */ - distribute_bandwidth_in_network (s, - NULL); + distribute_bandwidth_in_network(s, + NULL); } @@ -878,12 +870,12 @@ GAS_proportional_change_preference (void *solver, * @param score the score */ static void -GAS_proportional_feedback (void *solver, - struct GNUNET_SERVICE_Client *application, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_TIME_Relative scope, - enum GNUNET_ATS_PreferenceKind kind, - double score) +GAS_proportional_feedback(void *solver, + struct GNUNET_SERVICE_Client *application, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_TIME_Relative scope, + enum GNUNET_ATS_PreferenceKind kind, + double score) { /* Proportional does not care about feedback */ } @@ -896,15 +888,15 @@ GAS_proportional_feedback (void *solver, * @param peer the identity of the peer */ static void -GAS_proportional_start_get_address (void *solver, - const struct GNUNET_PeerIdentity *peer) +GAS_proportional_start_get_address(void *solver, + const struct GNUNET_PeerIdentity *peer) { struct GAS_PROPORTIONAL_Handle *s = solver; - update_active_address (s, - get_active_address (s, - peer), - peer); + update_active_address(s, + get_active_address(s, + peer), + peer); } @@ -915,20 +907,20 @@ GAS_proportional_start_get_address (void *solver, * @param peer the peer */ static void -GAS_proportional_stop_get_address (void *solver, - const struct GNUNET_PeerIdentity *peer) +GAS_proportional_stop_get_address(void *solver, + const struct GNUNET_PeerIdentity *peer) { struct GAS_PROPORTIONAL_Handle *s = solver; struct ATS_Address *cur; struct AddressWrapper *asi; - cur = get_active_address (s, - peer); + cur = get_active_address(s, + peer); if (NULL == cur) return; asi = cur->solver_information; - distribute_bandwidth_in_network (s, - asi->network); + distribute_bandwidth_in_network(s, + asi->network); } @@ -938,13 +930,13 @@ GAS_proportional_stop_get_address (void *solver, * @param solver the solver */ static void -GAS_proportional_bulk_start (void *solver) +GAS_proportional_bulk_start(void *solver) { struct GAS_PROPORTIONAL_Handle *s = solver; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Locking solver for bulk operation ...\n"); - GNUNET_assert (NULL != solver); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Locking solver for bulk operation ...\n"); + GNUNET_assert(NULL != solver); s->bulk_lock++; } @@ -955,27 +947,27 @@ GAS_proportional_bulk_start (void *solver) * @param solver our `struct GAS_PROPORTIONAL_Handle *` */ static void -GAS_proportional_bulk_stop (void *solver) +GAS_proportional_bulk_stop(void *solver) { struct GAS_PROPORTIONAL_Handle *s = solver; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Unlocking solver from bulk operation ...\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Unlocking solver from bulk operation ...\n"); if (s->bulk_lock < 1) - { - GNUNET_break(0); - return; - } + { + GNUNET_break(0); + return; + } s->bulk_lock--; - if ( (0 == s->bulk_lock) && - (0 < s->bulk_requests) ) - { - LOG (GNUNET_ERROR_TYPE_INFO, - "No lock pending, recalculating\n"); - distribute_bandwidth_in_network (s, - NULL); - s->bulk_requests = 0; - } + if ((0 == s->bulk_lock) && + (0 < s->bulk_requests)) + { + LOG(GNUNET_ERROR_TYPE_INFO, + "No lock pending, recalculating\n"); + distribute_bandwidth_in_network(s, + NULL); + s->bulk_requests = 0; + } } @@ -986,14 +978,14 @@ GAS_proportional_bulk_stop (void *solver) * @param address the address */ static void -GAS_proportional_address_property_changed (void *solver, - struct ATS_Address *address) +GAS_proportional_address_property_changed(void *solver, + struct ATS_Address *address) { struct GAS_PROPORTIONAL_Handle *s = solver; struct AddressWrapper *asi = address->solver_information; - distribute_bandwidth_in_network (s, - asi->network); + distribute_bandwidth_in_network(s, + asi->network); } @@ -1005,43 +997,43 @@ GAS_proportional_address_property_changed (void *solver, * @param network network type of this address */ static void -GAS_proportional_address_add (void *solver, - struct ATS_Address *address, - uint32_t network) +GAS_proportional_address_add(void *solver, + struct ATS_Address *address, + uint32_t network) { struct GAS_PROPORTIONAL_Handle *s = solver; struct Network *net; struct AddressWrapper *aw; - GNUNET_assert (network < s->env->network_count); + GNUNET_assert(network < s->env->network_count); net = &s->network_entries[network]; net->total_addresses++; - aw = GNUNET_new (struct AddressWrapper); + aw = GNUNET_new(struct AddressWrapper); aw->addr = address; aw->network = net; address->solver_information = aw; - GNUNET_CONTAINER_DLL_insert (net->head, - net->tail, - aw); - GNUNET_STATISTICS_update (s->env->stats, - "# ATS addresses total", - 1, - GNUNET_NO); - GNUNET_STATISTICS_update (s->env->stats, - net->stat_total, - 1, - GNUNET_NO); - update_active_address (s, - get_active_address (s, - &address->peer), - &address->peer); - LOG (GNUNET_ERROR_TYPE_INFO, - "Added new address for `%s', now total %u and active %u addresses in network `%s'\n", - GNUNET_i2s (&address->peer), - net->total_addresses, - net->active_addresses, - net->desc); + GNUNET_CONTAINER_DLL_insert(net->head, + net->tail, + aw); + GNUNET_STATISTICS_update(s->env->stats, + "# ATS addresses total", + 1, + GNUNET_NO); + GNUNET_STATISTICS_update(s->env->stats, + net->stat_total, + 1, + GNUNET_NO); + update_active_address(s, + get_active_address(s, + &address->peer), + &address->peer); + LOG(GNUNET_ERROR_TYPE_INFO, + "Added new address for `%s', now total %u and active %u addresses in network `%s'\n", + GNUNET_i2s(&address->peer), + net->total_addresses, + net->active_addresses, + net->desc); } @@ -1057,45 +1049,45 @@ GAS_proportional_address_add (void *solver, * @param address the address to remove */ static void -GAS_proportional_address_delete (void *solver, - struct ATS_Address *address) +GAS_proportional_address_delete(void *solver, + struct ATS_Address *address) { struct GAS_PROPORTIONAL_Handle *s = solver; struct AddressWrapper *aw = address->solver_information; struct Network *net = aw->network; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Deleting %s address for peer `%s' from network `%s' (total: %u/active: %u)\n", - (GNUNET_NO == address->active) ? "inactive" : "active", - GNUNET_i2s (&address->peer), - net->desc, - net->total_addresses, - net->active_addresses); - - GNUNET_CONTAINER_DLL_remove (net->head, - net->tail, - aw); - GNUNET_assert (net->total_addresses > 0); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Deleting %s address for peer `%s' from network `%s' (total: %u/active: %u)\n", + (GNUNET_NO == address->active) ? "inactive" : "active", + GNUNET_i2s(&address->peer), + net->desc, + net->total_addresses, + net->active_addresses); + + GNUNET_CONTAINER_DLL_remove(net->head, + net->tail, + aw); + GNUNET_assert(net->total_addresses > 0); net->total_addresses--; - GNUNET_STATISTICS_update (s->env->stats, - net->stat_total, - -1, - GNUNET_NO); + GNUNET_STATISTICS_update(s->env->stats, + net->stat_total, + -1, + GNUNET_NO); if (GNUNET_YES == address->active) - { - /* Address was active, remove from network and update quotas */ - update_active_address (s, - address, - &address->peer); - distribute_bandwidth_in_network (s, net); - } - GNUNET_free (aw); + { + /* Address was active, remove from network and update quotas */ + update_active_address(s, + address, + &address->peer); + distribute_bandwidth_in_network(s, net); + } + GNUNET_free(aw); address->solver_information = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "After deleting address now total %u and active %u addresses in network `%s'\n", - net->total_addresses, - net->active_addresses, - net->desc); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "After deleting address now total %u and active %u addresses in network `%s'\n", + net->total_addresses, + net->active_addresses, + net->desc); } @@ -1107,7 +1099,7 @@ GAS_proportional_address_delete (void *solver, * @return the `struct GAS_PROPORTIONAL_Handle` to pass as a closure */ void * -libgnunet_plugin_ats_proportional_init (void *cls) +libgnunet_plugin_ats_proportional_init(void *cls) { static struct GNUNET_ATS_SolverFunctions sf; struct GNUNET_ATS_PluginEnvironment *env = cls; @@ -1116,7 +1108,7 @@ libgnunet_plugin_ats_proportional_init (void *cls) float f_tmp; unsigned int c; - s = GNUNET_new (struct GAS_PROPORTIONAL_Handle); + s = GNUNET_new(struct GAS_PROPORTIONAL_Handle); s->env = env; sf.cls = s; sf.s_add = &GAS_proportional_address_add; @@ -1130,73 +1122,73 @@ libgnunet_plugin_ats_proportional_init (void *cls) sf.s_bulk_stop = &GAS_proportional_bulk_stop; s->stability_factor = PROP_STABILITY_FACTOR; if (GNUNET_SYSERR != - GNUNET_CONFIGURATION_get_value_float (env->cfg, - "ats", - "PROP_STABILITY_FACTOR", - &f_tmp)) - { - if ((f_tmp < 1.0) || (f_tmp > 2.0)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Invalid %s configuration %f \n"), - "PROP_STABILITY_FACTOR", - f_tmp); - } - else + GNUNET_CONFIGURATION_get_value_float(env->cfg, + "ats", + "PROP_STABILITY_FACTOR", + &f_tmp)) { - s->stability_factor = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, - "Using %s of %.3f\n", - "PROP_STABILITY_FACTOR", - f_tmp); + if ((f_tmp < 1.0) || (f_tmp > 2.0)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Invalid %s configuration %f \n"), + "PROP_STABILITY_FACTOR", + f_tmp); + } + else + { + s->stability_factor = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, + "Using %s of %.3f\n", + "PROP_STABILITY_FACTOR", + f_tmp); + } } - } s->prop_factor = PROPORTIONALITY_FACTOR; if (GNUNET_SYSERR != - GNUNET_CONFIGURATION_get_value_float (env->cfg, - "ats", - "PROP_PROPORTIONALITY_FACTOR", - &f_tmp)) - { - if (f_tmp < 1.0) + GNUNET_CONFIGURATION_get_value_float(env->cfg, + "ats", + "PROP_PROPORTIONALITY_FACTOR", + &f_tmp)) { - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Invalid %s configuration %f\n"), - "PROP_PROPORTIONALITY_FACTOR", - f_tmp); + if (f_tmp < 1.0) + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Invalid %s configuration %f\n"), + "PROP_PROPORTIONALITY_FACTOR", + f_tmp); + } + else + { + s->prop_factor = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, + "Using %s of %.3f\n", + "PROP_PROPORTIONALITY_FACTOR", + f_tmp); + } } - else - { - s->prop_factor = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, - "Using %s of %.3f\n", - "PROP_PROPORTIONALITY_FACTOR", - f_tmp); - } - } - s->network_entries = GNUNET_malloc (env->network_count * - sizeof (struct Network)); + s->network_entries = GNUNET_malloc(env->network_count * + sizeof(struct Network)); for (c = 0; c < env->network_count; c++) - { - cur = &s->network_entries[c]; - cur->type = c; - cur->total_quota_in = env->in_quota[c]; - cur->total_quota_out = env->out_quota[c]; - cur->desc = GNUNET_NT_to_string (c); - GNUNET_asprintf (&cur->stat_total, - "# ATS addresses %s total", - cur->desc); - GNUNET_asprintf (&cur->stat_active, - "# ATS active addresses %s total", - cur->desc); - LOG (GNUNET_ERROR_TYPE_INFO, - "Added network %u `%s' (%llu/%llu)\n", - c, - cur->desc, - cur->total_quota_in, - cur->total_quota_out); - } + { + cur = &s->network_entries[c]; + cur->type = c; + cur->total_quota_in = env->in_quota[c]; + cur->total_quota_out = env->out_quota[c]; + cur->desc = GNUNET_NT_to_string(c); + GNUNET_asprintf(&cur->stat_total, + "# ATS addresses %s total", + cur->desc); + GNUNET_asprintf(&cur->stat_active, + "# ATS active addresses %s total", + cur->desc); + LOG(GNUNET_ERROR_TYPE_INFO, + "Added network %u `%s' (%llu/%llu)\n", + c, + cur->desc, + cur->total_quota_in, + cur->total_quota_out); + } return &sf; } @@ -1207,7 +1199,7 @@ libgnunet_plugin_ats_proportional_init (void *cls) * @param cls return value from #libgnunet_plugin_ats_proportional_init() */ void * -libgnunet_plugin_ats_proportional_done (void *cls) +libgnunet_plugin_ats_proportional_done(void *cls) { struct GNUNET_ATS_SolverFunctions *sf = cls; struct GAS_PROPORTIONAL_Handle *s = sf->cls; @@ -1216,25 +1208,25 @@ libgnunet_plugin_ats_proportional_done (void *cls) unsigned int c; for (c = 0; c < s->env->network_count; c++) - { - GNUNET_break (0 == s->network_entries[c].total_addresses); - GNUNET_break (0 == s->network_entries[c].active_addresses); - next = s->network_entries[c].head; - while (NULL != (cur = next)) { - next = cur->next; - GNUNET_CONTAINER_DLL_remove (s->network_entries[c].head, - s->network_entries[c].tail, - cur); - GNUNET_free_non_null (cur->addr->solver_information); - GNUNET_free(cur); + GNUNET_break(0 == s->network_entries[c].total_addresses); + GNUNET_break(0 == s->network_entries[c].active_addresses); + next = s->network_entries[c].head; + while (NULL != (cur = next)) + { + next = cur->next; + GNUNET_CONTAINER_DLL_remove(s->network_entries[c].head, + s->network_entries[c].tail, + cur); + GNUNET_free_non_null(cur->addr->solver_information); + GNUNET_free(cur); + } + GNUNET_free(s->network_entries[c].stat_total); + GNUNET_free(s->network_entries[c].stat_active); } - GNUNET_free (s->network_entries[c].stat_total); - GNUNET_free (s->network_entries[c].stat_active); - } - GNUNET_break (0 == s->active_addresses); - GNUNET_free (s->network_entries); - GNUNET_free (s); + GNUNET_break(0 == s->active_addresses); + GNUNET_free(s->network_entries); + GNUNET_free(s); return NULL; } diff --git a/src/ats/plugin_ats_ril.c b/src/ats/plugin_ats_ril.c index 9f78450c2..abf265f19 100644 --- a/src/ats/plugin_ats_ril.c +++ b/src/ats/plugin_ats_ril.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2011-2014 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2011-2014 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -32,17 +32,17 @@ -#define LOG(kind,...) GNUNET_log_from (kind, "ats-ril",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "ats-ril", __VA_ARGS__) -#define RIL_MIN_BW (5 * ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__)) +#define RIL_MIN_BW (5 * ntohl(GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__)) #define RIL_MAX_BW GNUNET_ATS_MaxBandwidth #define RIL_ACTION_INVALID -1 #define RIL_INTERVAL_EXPONENT 10 #define RIL_UTILITY_DELAY_MAX 1000 -#define RIL_DEFAULT_STEP_TIME_MIN GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 200) -#define RIL_DEFAULT_STEP_TIME_MAX GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 2000) +#define RIL_DEFAULT_STEP_TIME_MIN GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 200) +#define RIL_DEFAULT_STEP_TIME_MAX GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 2000) #define RIL_DEFAULT_ALGORITHM RIL_ALGO_SARSA #define RIL_DEFAULT_SELECT RIL_SELECT_SOFTMAX #define RIL_DEFAULT_WELFARE RIL_WELFARE_NASH @@ -71,8 +71,7 @@ * to a particular address. The action of switching to address with index i is depicted by the * number (RIL_ACTION_TYPE_NUM + i). */ -enum RIL_Action_Type -{ +enum RIL_Action_Type { RIL_ACTION_NOTHING = 0, RIL_ACTION_BW_IN_DBL = -2, //TODO? Potentially add more actions RIL_ACTION_BW_IN_HLV = -3, @@ -85,26 +84,22 @@ enum RIL_Action_Type RIL_ACTION_TYPE_NUM = 5 }; -enum RIL_Algorithm -{ +enum RIL_Algorithm { RIL_ALGO_SARSA = 0, RIL_ALGO_Q = 1 }; -enum RIL_Select -{ +enum RIL_Select { RIL_SELECT_SOFTMAX = 0, RIL_SELECT_EGREEDY = 1 }; -enum RIL_Welfare -{ +enum RIL_Welfare { RIL_WELFARE_NASH, RIL_WELFARE_EGALITARIAN }; -enum RIL_E_Modification -{ +enum RIL_E_Modification { RIL_E_DECAY, RIL_E_ZERO, RIL_E_ACCUMULATE, @@ -114,8 +109,7 @@ enum RIL_E_Modification /** * Global learning parameters */ -struct RIL_Learning_Parameters -{ +struct RIL_Learning_Parameters { /** * The TD-algorithm to use */ @@ -205,8 +199,7 @@ struct RIL_Learning_Parameters /** * Wrapper for addresses to store them in agent's linked list */ -struct RIL_Address_Wrapped -{ +struct RIL_Address_Wrapped { /** * Next in DLL */ @@ -224,8 +217,7 @@ struct RIL_Address_Wrapped }; -struct RIL_Peer_Agent -{ +struct RIL_Peer_Agent { /** * Next agent in solver's linked list */ @@ -337,8 +329,7 @@ struct RIL_Peer_Agent double nop_bonus; }; -struct RIL_Scope -{ +struct RIL_Scope { /** * ATS network type */ @@ -388,8 +379,7 @@ struct RIL_Scope /** * A handle for the reinforcement learning solver */ -struct GAS_RIL_Handle -{ +struct GAS_RIL_Handle { /** * The solver-plugin environment of the solver-plugin API */ @@ -476,9 +466,9 @@ struct GAS_RIL_Handle * @return estimation value */ static double -agent_q (struct RIL_Peer_Agent *agent, - const double *state, - int action) +agent_q(struct RIL_Peer_Agent *agent, + const double *state, + int action) { unsigned int i; double result = 0.0; @@ -488,7 +478,7 @@ agent_q (struct RIL_Peer_Agent *agent, /* prevent crashes if learning diverges */ if (isnan(result)) - return isnan(result) * UINT32_MAX; + return isnan(result) * UINT32_MAX; if (isinf(result)) return isinf(result) * UINT32_MAX; return result; @@ -503,18 +493,18 @@ agent_q (struct RIL_Peer_Agent *agent, * @return the index, starting with zero */ static int -agent_address_get_index (struct RIL_Peer_Agent *agent, struct ATS_Address *address) +agent_address_get_index(struct RIL_Peer_Agent *agent, struct ATS_Address *address) { int i; struct RIL_Address_Wrapped *cur; i = -1; for (cur = agent->addresses_head; NULL != cur; cur = cur->next) - { - i++; - if (cur->address_naked == address) - return i; - } + { + i++; + if (cur->address_naked == address) + return i; + } return i; } @@ -527,7 +517,7 @@ agent_address_get_index (struct RIL_Peer_Agent *agent, struct ATS_Address *addre * @return wrapped address */ static struct RIL_Address_Wrapped * -agent_address_get_wrapped (struct RIL_Peer_Agent *agent, struct ATS_Address *address) +agent_address_get_wrapped(struct RIL_Peer_Agent *agent, struct ATS_Address *address) { struct RIL_Address_Wrapped *cur; @@ -539,62 +529,67 @@ agent_address_get_wrapped (struct RIL_Peer_Agent *agent, struct ATS_Address *add static int -agent_action_is_possible (struct RIL_Peer_Agent *agent, int action) +agent_action_is_possible(struct RIL_Peer_Agent *agent, int action) { int address_index; switch (action) - { - case RIL_ACTION_NOTHING: - return GNUNET_YES; - break; - case RIL_ACTION_BW_IN_INC: - case RIL_ACTION_BW_IN_DBL: - if (agent->bw_in >= RIL_MAX_BW) - return GNUNET_NO; - else - return GNUNET_YES; - break; - case RIL_ACTION_BW_IN_DEC: - case RIL_ACTION_BW_IN_HLV: - if (agent->bw_in <= 0) - return GNUNET_NO; - else - return GNUNET_YES; - break; - case RIL_ACTION_BW_OUT_INC: - case RIL_ACTION_BW_OUT_DBL: - if (agent->bw_out >= RIL_MAX_BW) - return GNUNET_NO; - else - return GNUNET_YES; - break; - case RIL_ACTION_BW_OUT_DEC: - case RIL_ACTION_BW_OUT_HLV: - if (agent->bw_out <= 0) - return GNUNET_NO; - else - return GNUNET_YES; - break; - default: - if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action { - address_index = action - RIL_ACTION_TYPE_NUM; + case RIL_ACTION_NOTHING: + return GNUNET_YES; + break; + + case RIL_ACTION_BW_IN_INC: + case RIL_ACTION_BW_IN_DBL: + if (agent->bw_in >= RIL_MAX_BW) + return GNUNET_NO; + else + return GNUNET_YES; + break; - GNUNET_assert(address_index >= 0); - GNUNET_assert( - address_index <= agent_address_get_index (agent, agent->addresses_tail->address_naked)); + case RIL_ACTION_BW_IN_DEC: + case RIL_ACTION_BW_IN_HLV: + if (agent->bw_in <= 0) + return GNUNET_NO; + else + return GNUNET_YES; + break; + + case RIL_ACTION_BW_OUT_INC: + case RIL_ACTION_BW_OUT_DBL: + if (agent->bw_out >= RIL_MAX_BW) + return GNUNET_NO; + else + return GNUNET_YES; + break; - if ((agent_address_get_index(agent, agent->address_inuse) == address_index) || - agent->address_inuse->active) + case RIL_ACTION_BW_OUT_DEC: + case RIL_ACTION_BW_OUT_HLV: + if (agent->bw_out <= 0) return GNUNET_NO; else return GNUNET_YES; break; + + default: + if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action + { + address_index = action - RIL_ACTION_TYPE_NUM; + + GNUNET_assert(address_index >= 0); + GNUNET_assert( + address_index <= agent_address_get_index(agent, agent->addresses_tail->address_naked)); + + if ((agent_address_get_index(agent, agent->address_inuse) == address_index) || + agent->address_inuse->active) + return GNUNET_NO; + else + return GNUNET_YES; + break; + } + // error - action does not exist + GNUNET_assert(GNUNET_NO); } - // error - action does not exist - GNUNET_assert(GNUNET_NO); - } } @@ -607,7 +602,7 @@ agent_action_is_possible (struct RIL_Peer_Agent *agent, int action) * @return the action promising most future reward */ static int -agent_get_action_max (struct RIL_Peer_Agent *agent, double *state) +agent_get_action_max(struct RIL_Peer_Agent *agent, double *state) { int i; int max_i = RIL_ACTION_INVALID; @@ -615,17 +610,17 @@ agent_get_action_max (struct RIL_Peer_Agent *agent, double *state) double max_q = -DBL_MAX; for (i = 0; i < agent->n; i++) - { - if (agent_action_is_possible(agent, i)) { - cur_q = agent_q (agent, state, i); - if (cur_q > max_q) - { - max_q = cur_q; - max_i = i; - } + if (agent_action_is_possible(agent, i)) + { + cur_q = agent_q(agent, state, i); + if (cur_q > max_q) + { + max_q = cur_q; + max_i = i; + } + } } - } GNUNET_assert(RIL_ACTION_INVALID != max_i); @@ -639,38 +634,38 @@ agent_get_action_max (struct RIL_Peer_Agent *agent, double *state) * @return the action index */ static int -agent_get_action_random (struct RIL_Peer_Agent *agent) +agent_get_action_random(struct RIL_Peer_Agent *agent) { int i; int is_possible[agent->n]; int sum = 0; int r; - for (i = 0; in; i++) - { - if (agent_action_is_possible(agent, i)) - { - is_possible[i] = GNUNET_YES; - sum++; - } - else + for (i = 0; i < agent->n; i++) { - is_possible[i] = GNUNET_NO; + if (agent_action_is_possible(agent, i)) + { + is_possible[i] = GNUNET_YES; + sum++; + } + else + { + is_possible[i] = GNUNET_NO; + } } - } - r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, sum); + r = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, sum); sum = -1; - for (i = 0; in; i++) - { - if (is_possible[i]) + for (i = 0; i < agent->n; i++) { - sum++; - if (sum == r) - return i; + if (is_possible[i]) + { + sum++; + if (sum == r) + return i; + } } - } GNUNET_assert(GNUNET_NO); return RIL_ACTION_INVALID; @@ -686,7 +681,7 @@ agent_get_action_random (struct RIL_Peer_Agent *agent) * @param a_prime the new */ static void -agent_update (struct RIL_Peer_Agent *agent, double reward, double *s_next, int a_prime) +agent_update(struct RIL_Peer_Agent *agent, double reward, double *s_next, int a_prime) { int i; int k; @@ -694,8 +689,8 @@ agent_update (struct RIL_Peer_Agent *agent, double reward, double *s_next, int a double **theta = agent->W; delta = agent->envi->global_discount_integrated * reward; //reward - delta += agent->envi->global_discount_variable * agent_q (agent, s_next, a_prime); //discounted future value - delta -= agent_q (agent, agent->s_old, agent->a_old); //one step + delta += agent->envi->global_discount_variable * agent_q(agent, s_next, a_prime); //discounted future value + delta -= agent_q(agent, agent->s_old, agent->a_old); //one step // LOG(GNUNET_ERROR_TYPE_INFO, "update() Step# %llu Q(s,a): %f a: %f r: %f y: %f Q(s+1,a+1) = %f delta: %f\n", // agent->step_count, @@ -707,17 +702,17 @@ agent_update (struct RIL_Peer_Agent *agent, double reward, double *s_next, int a // delta); for (k = 0; k < agent->n; k++) - { - for (i = 0; i < agent->m; i++) { - // LOG(GNUNET_ERROR_TYPE_INFO, "alpha = %f delta = %f e[%d] = %f\n", - // agent->envi->parameters.alpha, - // delta, - // i, - // agent->e[i]); - theta[k][i] += agent->envi->parameters.alpha * delta * agent->E[k][i]; + for (i = 0; i < agent->m; i++) + { + // LOG(GNUNET_ERROR_TYPE_INFO, "alpha = %f delta = %f e[%d] = %f\n", + // agent->envi->parameters.alpha, + // delta, + // i, + // agent->e[i]); + theta[k][i] += agent->envi->parameters.alpha * delta * agent->E[k][i]; + } } - } } @@ -734,38 +729,41 @@ agent_update (struct RIL_Peer_Agent *agent, double reward, double *s_next, int a * @param action the action to take */ static void -agent_modify_eligibility (struct RIL_Peer_Agent *agent, - enum RIL_E_Modification mod, - double *feature, - int action) +agent_modify_eligibility(struct RIL_Peer_Agent *agent, + enum RIL_E_Modification mod, + double *feature, + int action) { int i; int k; for (i = 0; i < agent->m; i++) - { - switch (mod) { - case RIL_E_ACCUMULATE: - agent->E[action][i] += feature[i]; - break; - case RIL_E_REPLACE: - agent->E[action][i] = agent->E[action][i] > feature[i] ? agent->E[action][i] : feature[i]; - break; - case RIL_E_DECAY: - for (k = 0; k < agent->n; k++) - { - agent->E[k][i] *= agent->envi->global_discount_variable * agent->envi->parameters.lambda; - } - break; - case RIL_E_ZERO: - for (k = 0; k < agent->n; k++) - { - agent->E[k][i] = 0; - } - break; + switch (mod) + { + case RIL_E_ACCUMULATE: + agent->E[action][i] += feature[i]; + break; + + case RIL_E_REPLACE: + agent->E[action][i] = agent->E[action][i] > feature[i] ? agent->E[action][i] : feature[i]; + break; + + case RIL_E_DECAY: + for (k = 0; k < agent->n; k++) + { + agent->E[k][i] *= agent->envi->global_discount_variable * agent->envi->parameters.lambda; + } + break; + + case RIL_E_ZERO: + for (k = 0; k < agent->n; k++) + { + agent->E[k][i] = 0; + } + break; + } } - } } /** @@ -776,14 +774,14 @@ agent_modify_eligibility (struct RIL_Peer_Agent *agent, * @param stat */ static void -ril_inform (struct GAS_RIL_Handle *solver, - enum GAS_Solver_Operation op, - enum GAS_Solver_Status stat) -{ - solver->env->info_cb (solver->env->cls, - op, - stat, - GAS_INFO_NONE); +ril_inform(struct GAS_RIL_Handle *solver, + enum GAS_Solver_Operation op, + enum GAS_Solver_Status stat) +{ + solver->env->info_cb(solver->env->cls, + op, + stat, + GAS_INFO_NONE); } /** @@ -792,7 +790,7 @@ ril_inform (struct GAS_RIL_Handle *solver, * @param net */ static unsigned long long -ril_get_max_bw (struct RIL_Scope *net) +ril_get_max_bw(struct RIL_Scope *net) { return GNUNET_MIN(2 * GNUNET_MAX(net->bw_in_available, net->bw_out_available), GNUNET_ATS_MaxBandwidth); } @@ -809,82 +807,82 @@ ril_get_max_bw (struct RIL_Scope *net) * @param silent disables invocation of the bw_changed callback, if #GNUNET_YES */ static void -envi_set_active_suggestion (struct GAS_RIL_Handle *solver, - struct RIL_Peer_Agent *agent, - struct ATS_Address *new_address, - unsigned long long new_bw_in, - unsigned long long new_bw_out, - int silent) +envi_set_active_suggestion(struct GAS_RIL_Handle *solver, + struct RIL_Peer_Agent *agent, + struct ATS_Address *new_address, + unsigned long long new_bw_in, + unsigned long long new_bw_out, + int silent) { int notify = GNUNET_NO; LOG(GNUNET_ERROR_TYPE_DEBUG, " set_active_suggestion() for peer '%s'\n", - GNUNET_i2s (&agent->peer)); + GNUNET_i2s(&agent->peer)); //address change if (agent->address_inuse != new_address) - { - if (NULL != agent->address_inuse) { - agent->address_inuse->active = GNUNET_NO; - agent->address_inuse->assigned_bw_in = 0; - agent->address_inuse->assigned_bw_out = 0; - } - if (NULL != new_address) - { - LOG(GNUNET_ERROR_TYPE_DEBUG, " set address active: %s\n", agent->is_active ? "yes" : "no"); - new_address->active = agent->is_active; - new_address->assigned_bw_in = agent->bw_in; - new_address->assigned_bw_out = agent->bw_out; - } - notify |= GNUNET_YES; - } - - if (new_address) - { - //activity change - if (new_address->active != agent->is_active) - { - new_address->active = agent->is_active; + if (NULL != agent->address_inuse) + { + agent->address_inuse->active = GNUNET_NO; + agent->address_inuse->assigned_bw_in = 0; + agent->address_inuse->assigned_bw_out = 0; + } + if (NULL != new_address) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, " set address active: %s\n", agent->is_active ? "yes" : "no"); + new_address->active = agent->is_active; + new_address->assigned_bw_in = agent->bw_in; + new_address->assigned_bw_out = agent->bw_out; + } notify |= GNUNET_YES; } - //bw change - if (agent->bw_in != new_bw_in) - { - agent->bw_in = new_bw_in; - new_address->assigned_bw_in = new_bw_in; - notify |= GNUNET_YES; - } - if (agent->bw_out != new_bw_out) + if (new_address) { - agent->bw_out = new_bw_out; - new_address->assigned_bw_out = new_bw_out; - notify |= GNUNET_YES; + //activity change + if (new_address->active != agent->is_active) + { + new_address->active = agent->is_active; + notify |= GNUNET_YES; + } + + //bw change + if (agent->bw_in != new_bw_in) + { + agent->bw_in = new_bw_in; + new_address->assigned_bw_in = new_bw_in; + notify |= GNUNET_YES; + } + if (agent->bw_out != new_bw_out) + { + agent->bw_out = new_bw_out; + new_address->assigned_bw_out = new_bw_out; + notify |= GNUNET_YES; + } } - } if (notify && agent->is_active && (GNUNET_NO == silent)) - { - if (new_address) - { - LOG(GNUNET_ERROR_TYPE_DEBUG, " envi_set_active_suggestion() notify\n"); - agent->suggestion_issue = GNUNET_YES; - agent->suggestion_address = new_address; - } - else if (agent->address_inuse) { - /* disconnect case, no new address */ - GNUNET_assert(0 == agent->address_inuse->assigned_bw_in); - GNUNET_assert(0 == agent->address_inuse->assigned_bw_out); - agent->bw_in = 0; - agent->bw_out = 0; - - agent->suggestion_issue = GNUNET_YES; - agent->suggestion_address = agent->address_inuse; + if (new_address) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, " envi_set_active_suggestion() notify\n"); + agent->suggestion_issue = GNUNET_YES; + agent->suggestion_address = new_address; + } + else if (agent->address_inuse) + { + /* disconnect case, no new address */ + GNUNET_assert(0 == agent->address_inuse->assigned_bw_in); + GNUNET_assert(0 == agent->address_inuse->assigned_bw_out); + agent->bw_in = 0; + agent->bw_out = 0; + + agent->suggestion_issue = GNUNET_YES; + agent->suggestion_address = agent->address_inuse; + } } - } agent->address_inuse = new_address; } @@ -896,7 +894,7 @@ envi_set_active_suggestion (struct GAS_RIL_Handle *solver, * @return pointer to the state vector */ static double * -envi_get_state (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) +envi_get_state(struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) { double *state; double y[2]; @@ -909,27 +907,27 @@ envi_get_state (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) int k; unsigned long long max_bw; - state = GNUNET_malloc (sizeof(double) * agent->m); + state = GNUNET_malloc(sizeof(double) * agent->m); - max_bw = ril_get_max_bw((struct RIL_Scope *) agent->address_inuse->solver_information); + max_bw = ril_get_max_bw((struct RIL_Scope *)agent->address_inuse->solver_information); - y[0] = (double) agent->bw_out; - y[1] = (double) agent->bw_in; + y[0] = (double)agent->bw_out; + y[1] = (double)agent->bw_in; - m = agent_address_get_index (agent, agent->address_inuse) * (solver->parameters.rbf_divisor+1) * (solver->parameters.rbf_divisor+1); + m = agent_address_get_index(agent, agent->address_inuse) * (solver->parameters.rbf_divisor + 1) * (solver->parameters.rbf_divisor + 1); for (i = 0; i <= solver->parameters.rbf_divisor; i++) - { - for (k = 0; k <= solver->parameters.rbf_divisor; k++) { - x[0] = (double) i * (double) max_bw / (double) solver->parameters.rbf_divisor; - x[1] = (double) k * (double) max_bw / (double) solver->parameters.rbf_divisor; - d[0] = x[0]-y[0]; - d[1] = x[1]-y[1]; - sigma = (((double) max_bw / ((double) solver->parameters.rbf_divisor + 1)) * 0.5); - f = exp(-((d[0]*d[0] + d[1]*d[1]) / (2 * sigma * sigma))); - state[m++] = f; + for (k = 0; k <= solver->parameters.rbf_divisor; k++) + { + x[0] = (double)i * (double)max_bw / (double)solver->parameters.rbf_divisor; + x[1] = (double)k * (double)max_bw / (double)solver->parameters.rbf_divisor; + d[0] = x[0] - y[0]; + d[1] = x[1] - y[1]; + sigma = (((double)max_bw / ((double)solver->parameters.rbf_divisor + 1)) * 0.5); + f = exp(-((d[0] * d[0] + d[1] * d[1]) / (2 * sigma * sigma))); + state[m++] = f; + } } - } return state; } @@ -942,22 +940,22 @@ envi_get_state (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) * @return the utility value */ static double -agent_get_utility (struct RIL_Peer_Agent *agent) +agent_get_utility(struct RIL_Peer_Agent *agent) { const double *preferences; double delay_atsi; double delay_norm; double pref_match; - preferences = agent->envi->env->get_preferences (agent->envi->env->cls, - &agent->peer); + preferences = agent->envi->env->get_preferences(agent->envi->env->cls, + &agent->peer); delay_atsi = agent->address_inuse->norm_delay.norm; - delay_norm = RIL_UTILITY_DELAY_MAX*exp(-delay_atsi*0.00001); + delay_norm = RIL_UTILITY_DELAY_MAX * exp(-delay_atsi * 0.00001); pref_match = preferences[GNUNET_ATS_PREFERENCE_LATENCY] * delay_norm; pref_match += preferences[GNUNET_ATS_PREFERENCE_BANDWIDTH] * - sqrt((double) (agent->bw_in/RIL_MIN_BW) * (double) (agent->bw_out/RIL_MIN_BW)); + sqrt((double)(agent->bw_in / RIL_MIN_BW) * (double)(agent->bw_out / RIL_MIN_BW)); return pref_match; } @@ -970,41 +968,41 @@ agent_get_utility (struct RIL_Peer_Agent *agent) * @return the social welfare value */ static double -ril_network_get_social_welfare (struct GAS_RIL_Handle *solver, struct RIL_Scope *scope) +ril_network_get_social_welfare(struct GAS_RIL_Handle *solver, struct RIL_Scope *scope) { struct RIL_Peer_Agent *cur; double result; switch (solver->parameters.social_welfare) - { - case RIL_WELFARE_EGALITARIAN: - result = DBL_MAX; - for (cur = solver->agents_head; NULL != cur; cur = cur->next) - { - if (cur->is_active && cur->address_inuse && (cur->address_inuse->solver_information == scope)) - { - result = GNUNET_MIN(result, agent_get_utility(cur)); - } - } - return result; - - case RIL_WELFARE_NASH: - result = 0; - for (cur = solver->agents_head; NULL != cur; cur = cur->next) { - if (cur->is_active && cur->address_inuse && (cur->address_inuse->solver_information == scope)) - { - result *= pow(agent_get_utility(cur), 1.0 / (double) scope->active_agent_count); - } + case RIL_WELFARE_EGALITARIAN: + result = DBL_MAX; + for (cur = solver->agents_head; NULL != cur; cur = cur->next) + { + if (cur->is_active && cur->address_inuse && (cur->address_inuse->solver_information == scope)) + { + result = GNUNET_MIN(result, agent_get_utility(cur)); + } + } + return result; + + case RIL_WELFARE_NASH: + result = 0; + for (cur = solver->agents_head; NULL != cur; cur = cur->next) + { + if (cur->is_active && cur->address_inuse && (cur->address_inuse->solver_information == scope)) + { + result *= pow(agent_get_utility(cur), 1.0 / (double)scope->active_agent_count); + } + } + return result; } - return result; - } GNUNET_assert(GNUNET_NO); return 1; } static double -envi_get_penalty (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) +envi_get_penalty(struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) { struct RIL_Scope *net; unsigned long long over_max; @@ -1014,26 +1012,26 @@ envi_get_penalty (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) net = agent->address_inuse->solver_information; if (net->bw_in_utilized > net->bw_in_available) - { - over_in = net->bw_in_utilized - net->bw_in_available; - if (RIL_ACTION_BW_IN_INC == agent->a_old) { - /* increase quadratically */ - over_in *= over_in; + over_in = net->bw_in_utilized - net->bw_in_available; + if (RIL_ACTION_BW_IN_INC == agent->a_old) + { + /* increase quadratically */ + over_in *= over_in; + } } - } if (net->bw_out_utilized > net->bw_out_available) - { - over_out = net->bw_out_utilized - net->bw_out_available; - if (RIL_ACTION_BW_OUT_INC == agent->a_old) { - /* increase quadratically */ - over_out *= over_out; + over_out = net->bw_out_utilized - net->bw_out_available; + if (RIL_ACTION_BW_OUT_INC == agent->a_old) + { + /* increase quadratically */ + over_out *= over_out; + } } - } over_max = (over_in + over_out) / (RIL_MIN_BW * RIL_MIN_BW); - return -1.0 * (double) over_max; + return -1.0 * (double)over_max; } /** @@ -1046,7 +1044,7 @@ envi_get_penalty (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) * @return the reward */ static double -envi_get_reward (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) +envi_get_reward(struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) { struct RIL_Scope *net; double objective; @@ -1058,18 +1056,18 @@ envi_get_reward (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) net = agent->address_inuse->solver_information; penalty = envi_get_penalty(solver, agent); - objective = (agent_get_utility (agent) + net->social_welfare) / 2; + objective = (agent_get_utility(agent) + net->social_welfare) / 2; delta = objective - agent->objective_old; agent->objective_old = objective; if (delta != 0 && penalty == 0) - { - agent->nop_bonus = delta * RIL_NOP_DECAY; - } + { + agent->nop_bonus = delta * RIL_NOP_DECAY; + } else - { - agent->nop_bonus *= RIL_NOP_DECAY; - } + { + agent->nop_bonus *= RIL_NOP_DECAY; + } steady = (RIL_ACTION_NOTHING == agent->a_old) ? agent->nop_bonus : 0; @@ -1085,31 +1083,31 @@ envi_get_reward (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise the outbound bandwidth */ static void -envi_action_bw_double (struct GAS_RIL_Handle *solver, - struct RIL_Peer_Agent *agent, - int direction_in) +envi_action_bw_double(struct GAS_RIL_Handle *solver, + struct RIL_Peer_Agent *agent, + int direction_in) { unsigned long long new_bw; unsigned long long max_bw; - max_bw = ril_get_max_bw((struct RIL_Scope *) agent->address_inuse->solver_information); + max_bw = ril_get_max_bw((struct RIL_Scope *)agent->address_inuse->solver_information); if (direction_in) - { - new_bw = agent->bw_in * 2; - if (new_bw < agent->bw_in || new_bw > max_bw) - new_bw = max_bw; - envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, - agent->bw_out, GNUNET_NO); - } + { + new_bw = agent->bw_in * 2; + if (new_bw < agent->bw_in || new_bw > max_bw) + new_bw = max_bw; + envi_set_active_suggestion(solver, agent, agent->address_inuse, new_bw, + agent->bw_out, GNUNET_NO); + } else - { - new_bw = agent->bw_out * 2; - if (new_bw < agent->bw_out || new_bw > max_bw) - new_bw = max_bw; - envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, - new_bw, GNUNET_NO); - } + { + new_bw = agent->bw_out * 2; + if (new_bw < agent->bw_out || new_bw > max_bw) + new_bw = max_bw; + envi_set_active_suggestion(solver, agent, agent->address_inuse, agent->bw_in, + new_bw, GNUNET_NO); + } } /** @@ -1122,28 +1120,28 @@ envi_action_bw_double (struct GAS_RIL_Handle *solver, * bandwidth */ static void -envi_action_bw_halven (struct GAS_RIL_Handle *solver, - struct RIL_Peer_Agent *agent, - int direction_in) +envi_action_bw_halven(struct GAS_RIL_Handle *solver, + struct RIL_Peer_Agent *agent, + int direction_in) { unsigned long long new_bw; if (direction_in) - { - new_bw = agent->bw_in / 2; - if (new_bw <= 0 || new_bw > agent->bw_in) - new_bw = 0; - envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out, - GNUNET_NO); - } + { + new_bw = agent->bw_in / 2; + if (new_bw <= 0 || new_bw > agent->bw_in) + new_bw = 0; + envi_set_active_suggestion(solver, agent, agent->address_inuse, new_bw, agent->bw_out, + GNUNET_NO); + } else - { - new_bw = agent->bw_out / 2; - if (new_bw <= 0 || new_bw > agent->bw_out) - new_bw = 0; - envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw, - GNUNET_NO); - } + { + new_bw = agent->bw_out / 2; + if (new_bw <= 0 || new_bw > agent->bw_out) + new_bw = 0; + envi_set_active_suggestion(solver, agent, agent->address_inuse, agent->bw_in, new_bw, + GNUNET_NO); + } } /** @@ -1155,29 +1153,29 @@ envi_action_bw_halven (struct GAS_RIL_Handle *solver, * bandwidth */ static void -envi_action_bw_inc (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in) +envi_action_bw_inc(struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in) { unsigned long long new_bw; unsigned long long max_bw; - max_bw = ril_get_max_bw((struct RIL_Scope *) agent->address_inuse->solver_information); + max_bw = ril_get_max_bw((struct RIL_Scope *)agent->address_inuse->solver_information); if (direction_in) - { - new_bw = agent->bw_in + (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW); - if (new_bw < agent->bw_in || new_bw > max_bw) - new_bw = max_bw; - envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, - agent->bw_out, GNUNET_NO); - } + { + new_bw = agent->bw_in + (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW); + if (new_bw < agent->bw_in || new_bw > max_bw) + new_bw = max_bw; + envi_set_active_suggestion(solver, agent, agent->address_inuse, new_bw, + agent->bw_out, GNUNET_NO); + } else - { - new_bw = agent->bw_out + (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW); - if (new_bw < agent->bw_out || new_bw > max_bw) - new_bw = max_bw; - envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, - new_bw, GNUNET_NO); - } + { + new_bw = agent->bw_out + (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW); + if (new_bw < agent->bw_out || new_bw > max_bw) + new_bw = max_bw; + envi_set_active_suggestion(solver, agent, agent->address_inuse, agent->bw_in, + new_bw, GNUNET_NO); + } } /** @@ -1190,26 +1188,26 @@ envi_action_bw_inc (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, * bandwidth */ static void -envi_action_bw_dec (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in) +envi_action_bw_dec(struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in) { unsigned long long new_bw; if (direction_in) - { - new_bw = agent->bw_in - (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW); - if (new_bw <= 0 || new_bw > agent->bw_in) - new_bw = 0; - envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out, - GNUNET_NO); - } + { + new_bw = agent->bw_in - (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW); + if (new_bw <= 0 || new_bw > agent->bw_in) + new_bw = 0; + envi_set_active_suggestion(solver, agent, agent->address_inuse, new_bw, agent->bw_out, + GNUNET_NO); + } else - { - new_bw = agent->bw_out - (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW); - if (new_bw <= 0 || new_bw > agent->bw_out) - new_bw = 0; - envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw, - GNUNET_NO); - } + { + new_bw = agent->bw_out - (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW); + if (new_bw <= 0 || new_bw > agent->bw_out) + new_bw = 0; + envi_set_active_suggestion(solver, agent, agent->address_inuse, agent->bw_in, new_bw, + GNUNET_NO); + } } /** @@ -1220,9 +1218,9 @@ envi_action_bw_dec (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, * @param address_index index of the address as it is saved in the agent's list, starting with zero */ static void -envi_action_address_switch (struct GAS_RIL_Handle *solver, - struct RIL_Peer_Agent *agent, - unsigned int address_index) +envi_action_address_switch(struct GAS_RIL_Handle *solver, + struct RIL_Peer_Agent *agent, + unsigned int address_index) { struct RIL_Address_Wrapped *cur; int i = 0; @@ -1230,17 +1228,17 @@ envi_action_address_switch (struct GAS_RIL_Handle *solver, //cur = agent_address_get_wrapped(agent, agent->address_inuse); for (cur = agent->addresses_head; NULL != cur; cur = cur->next) - { - if (i == address_index) { - envi_set_active_suggestion (solver, agent, cur->address_naked, agent->bw_in, agent->bw_out, - GNUNET_NO); - return; + if (i == address_index) + { + envi_set_active_suggestion(solver, agent, cur->address_naked, agent->bw_in, agent->bw_out, + GNUNET_NO); + return; + } + + i++; } - i++; - } - //no address with address_index exists, in this case this action should not be callable GNUNET_assert(GNUNET_NO); } @@ -1253,53 +1251,62 @@ envi_action_address_switch (struct GAS_RIL_Handle *solver, * @param action the action to perform by the solver */ static void -envi_do_action (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int action) +envi_do_action(struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int action) { int address_index; switch (action) - { - case RIL_ACTION_NOTHING: - break; - case RIL_ACTION_BW_IN_DBL: - envi_action_bw_double (solver, agent, GNUNET_YES); - break; - case RIL_ACTION_BW_IN_HLV: - envi_action_bw_halven (solver, agent, GNUNET_YES); - break; - case RIL_ACTION_BW_IN_INC: - envi_action_bw_inc (solver, agent, GNUNET_YES); - break; - case RIL_ACTION_BW_IN_DEC: - envi_action_bw_dec (solver, agent, GNUNET_YES); - break; - case RIL_ACTION_BW_OUT_DBL: - envi_action_bw_double (solver, agent, GNUNET_NO); - break; - case RIL_ACTION_BW_OUT_HLV: - envi_action_bw_halven (solver, agent, GNUNET_NO); - break; - case RIL_ACTION_BW_OUT_INC: - envi_action_bw_inc (solver, agent, GNUNET_NO); - break; - case RIL_ACTION_BW_OUT_DEC: - envi_action_bw_dec (solver, agent, GNUNET_NO); - break; - default: - if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action - { - address_index = action - RIL_ACTION_TYPE_NUM; - - GNUNET_assert(address_index >= 0); - GNUNET_assert( - address_index <= agent_address_get_index (agent, agent->addresses_tail->address_naked)); - - envi_action_address_switch (solver, agent, address_index); + { + case RIL_ACTION_NOTHING: + break; + + case RIL_ACTION_BW_IN_DBL: + envi_action_bw_double(solver, agent, GNUNET_YES); + break; + + case RIL_ACTION_BW_IN_HLV: + envi_action_bw_halven(solver, agent, GNUNET_YES); + break; + + case RIL_ACTION_BW_IN_INC: + envi_action_bw_inc(solver, agent, GNUNET_YES); + break; + + case RIL_ACTION_BW_IN_DEC: + envi_action_bw_dec(solver, agent, GNUNET_YES); + break; + + case RIL_ACTION_BW_OUT_DBL: + envi_action_bw_double(solver, agent, GNUNET_NO); + break; + + case RIL_ACTION_BW_OUT_HLV: + envi_action_bw_halven(solver, agent, GNUNET_NO); break; + + case RIL_ACTION_BW_OUT_INC: + envi_action_bw_inc(solver, agent, GNUNET_NO); + break; + + case RIL_ACTION_BW_OUT_DEC: + envi_action_bw_dec(solver, agent, GNUNET_NO); + break; + + default: + if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action + { + address_index = action - RIL_ACTION_TYPE_NUM; + + GNUNET_assert(address_index >= 0); + GNUNET_assert( + address_index <= agent_address_get_index(agent, agent->addresses_tail->address_naked)); + + envi_action_address_switch(solver, agent, address_index); + break; + } + // error - action does not exist + GNUNET_assert(GNUNET_NO); } - // error - action does not exist - GNUNET_assert(GNUNET_NO); - } } /** @@ -1314,27 +1321,27 @@ envi_do_action (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int * @return the action index */ static int -agent_select_egreedy (struct RIL_Peer_Agent *agent, double *state) +agent_select_egreedy(struct RIL_Peer_Agent *agent, double *state) { int action; - double r = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT32_MAX) / (double) UINT32_MAX; + double r = (double)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + UINT32_MAX) / (double)UINT32_MAX; if (r < agent->envi->parameters.epsilon) //explore - { - action = agent_get_action_random(agent); - if (RIL_ALGO_Q == agent->envi->parameters.algorithm) { - agent->eligibility_reset = GNUNET_YES; + action = agent_get_action_random(agent); + if (RIL_ALGO_Q == agent->envi->parameters.algorithm) + { + agent->eligibility_reset = GNUNET_YES; + } + agent->envi->parameters.epsilon *= agent->envi->parameters.epsilon_decay; + return action; } - agent->envi->parameters.epsilon *= agent->envi->parameters.epsilon_decay; - return action; - } else //exploit - { - action = agent_get_action_max(agent, state); - return action; - } + { + action = agent_get_action_max(agent, state); + return action; + } } /** @@ -1348,7 +1355,7 @@ agent_select_egreedy (struct RIL_Peer_Agent *agent, double *state) * @return */ static int -agent_select_softmax (struct RIL_Peer_Agent *agent, double *state) +agent_select_softmax(struct RIL_Peer_Agent *agent, double *state) { int i; int a_max; @@ -1359,44 +1366,44 @@ agent_select_softmax (struct RIL_Peer_Agent *agent, double *state) a_max = agent_get_action_max(agent, state); - for (i=0; in; i++) - { - if (agent_action_is_possible(agent, i)) - { - eqt[i] = exp(agent_q(agent,state,i) / agent->envi->parameters.temperature); - if (isinf (eqt[i])) - eqt[i] = isinf(eqt[i]) * UINT32_MAX; - sum += eqt[i]; - } - } - for (i=0; in; i++) - { - if (agent_action_is_possible(agent, i)) + for (i = 0; i < agent->n; i++) { - p[i] = eqt[i]/sum; + if (agent_action_is_possible(agent, i)) + { + eqt[i] = exp(agent_q(agent, state, i) / agent->envi->parameters.temperature); + if (isinf(eqt[i])) + eqt[i] = isinf(eqt[i]) * UINT32_MAX; + sum += eqt[i]; + } } - else + for (i = 0; i < agent->n; i++) { - p[i] = 0; + if (agent_action_is_possible(agent, i)) + { + p[i] = eqt[i] / sum; + } + else + { + p[i] = 0; + } } - } - r = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT32_MAX) / (double) UINT32_MAX; + r = (double)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + UINT32_MAX) / (double)UINT32_MAX; sum = 0; - for (i=0; in; i++) - { - if (sum + p[i] > r) + for (i = 0; i < agent->n; i++) { - if (i != a_max) - { - if (RIL_ALGO_Q == agent->envi->parameters.algorithm) - agent->eligibility_reset = GNUNET_YES; - agent->envi->parameters.temperature *= agent->envi->parameters.temperature_decay; - } - return i; + if (sum + p[i] > r) + { + if (i != a_max) + { + if (RIL_ALGO_Q == agent->envi->parameters.algorithm) + agent->eligibility_reset = GNUNET_YES; + agent->envi->parameters.temperature *= agent->envi->parameters.temperature_decay; + } + return i; + } + sum += p[i]; } - sum += p[i]; - } GNUNET_assert(GNUNET_NO); return RIL_ACTION_INVALID; } @@ -1410,16 +1417,16 @@ agent_select_softmax (struct RIL_Peer_Agent *agent, double *state) * @return the action index */ static int -agent_select_action (struct RIL_Peer_Agent *agent, double *state) +agent_select_action(struct RIL_Peer_Agent *agent, double *state) { if (agent->envi->parameters.select == RIL_SELECT_EGREEDY) - { - return agent_select_egreedy(agent, state); - } + { + return agent_select_egreedy(agent, state); + } else - { - return agent_select_softmax(agent, state); - } + { + return agent_select_softmax(agent, state); + } } /** @@ -1431,7 +1438,7 @@ agent_select_action (struct RIL_Peer_Agent *agent, double *state) * @param agent the agent performing the step */ static void -agent_step (struct RIL_Peer_Agent *agent) +agent_step(struct RIL_Peer_Agent *agent) { int a_next = RIL_ACTION_INVALID; int a_max; @@ -1439,58 +1446,58 @@ agent_step (struct RIL_Peer_Agent *agent) double reward; LOG(GNUNET_ERROR_TYPE_DEBUG, " agent_step() Peer '%s', algorithm %s\n", - GNUNET_i2s (&agent->peer), + GNUNET_i2s(&agent->peer), agent->envi->parameters.algorithm ? "Q" : "SARSA"); - s_next = envi_get_state (agent->envi, agent); - reward = envi_get_reward (agent->envi, agent); + s_next = envi_get_state(agent->envi, agent); + reward = envi_get_reward(agent->envi, agent); if (agent->eligibility_reset) - { - agent_modify_eligibility(agent, RIL_E_ZERO, NULL, -1); - agent->eligibility_reset = GNUNET_NO; - } + { + agent_modify_eligibility(agent, RIL_E_ZERO, NULL, -1); + agent->eligibility_reset = GNUNET_NO; + } else - { - agent_modify_eligibility (agent, RIL_E_DECAY, NULL, -1); - } + { + agent_modify_eligibility(agent, RIL_E_DECAY, NULL, -1); + } if (RIL_ACTION_INVALID != agent->a_old) - { - agent_modify_eligibility (agent, agent->envi->parameters.eligibility_trace_mode, agent->s_old, agent->a_old); - } - - switch (agent->envi->parameters.algorithm) - { - case RIL_ALGO_SARSA: - a_next = agent_select_action (agent, s_next); - if (RIL_ACTION_INVALID != agent->a_old) { - //updates weights with selected action (on-policy), if not first step - agent_update (agent, reward, s_next, a_next); + agent_modify_eligibility(agent, agent->envi->parameters.eligibility_trace_mode, agent->s_old, agent->a_old); } - break; - case RIL_ALGO_Q: - a_max = agent_get_action_max (agent, s_next); - if (RIL_ACTION_INVALID != agent->a_old) + switch (agent->envi->parameters.algorithm) { - //updates weights with best action, disregarding actually selected action (off-policy), if not first step - agent_update (agent, reward, s_next, a_max); + case RIL_ALGO_SARSA: + a_next = agent_select_action(agent, s_next); + if (RIL_ACTION_INVALID != agent->a_old) + { + //updates weights with selected action (on-policy), if not first step + agent_update(agent, reward, s_next, a_next); + } + break; + + case RIL_ALGO_Q: + a_max = agent_get_action_max(agent, s_next); + if (RIL_ACTION_INVALID != agent->a_old) + { + //updates weights with best action, disregarding actually selected action (off-policy), if not first step + agent_update(agent, reward, s_next, a_max); + } + a_next = agent_select_action(agent, s_next); + break; } - a_next = agent_select_action (agent, s_next); - break; - } GNUNET_assert(RIL_ACTION_INVALID != a_next); - LOG (GNUNET_ERROR_TYPE_DEBUG, "step() Step# %llu R: %f IN %llu OUT %llu A: %d\n", - agent->step_count, - reward, - agent->bw_in/1024, - agent->bw_out/1024, - a_next); + LOG(GNUNET_ERROR_TYPE_DEBUG, "step() Step# %llu R: %f IN %llu OUT %llu A: %d\n", + agent->step_count, + reward, + agent->bw_in / 1024, + agent->bw_out / 1024, + a_next); - envi_do_action (agent->envi, agent, a_next); + envi_do_action(agent->envi, agent, a_next); GNUNET_free(agent->s_old); agent->s_old = s_next; @@ -1505,7 +1512,7 @@ agent_step (struct RIL_Peer_Agent *agent) * @param solver the solver handle */ static void -ril_step (struct GAS_RIL_Handle *solver); +ril_step(struct GAS_RIL_Handle *solver); /** @@ -1515,12 +1522,12 @@ ril_step (struct GAS_RIL_Handle *solver); * @param cls the solver handle */ static void -ril_step_scheduler_task (void *cls) +ril_step_scheduler_task(void *cls) { struct GAS_RIL_Handle *solver = cls; solver->step_next_task_id = NULL; - ril_step (solver); + ril_step(solver); } /** @@ -1532,7 +1539,7 @@ ril_step_scheduler_task (void *cls) * @return the ratio */ static double -ril_get_used_resource_ratio (struct GAS_RIL_Handle *solver) +ril_get_used_resource_ratio(struct GAS_RIL_Handle *solver) { int i; struct RIL_Scope net; @@ -1541,24 +1548,24 @@ ril_get_used_resource_ratio (struct GAS_RIL_Handle *solver) double ratio; for (i = 0; i < solver->networks_count; i++) - { - net = solver->network_entries[i]; - if (net.bw_in_assigned > 0) //only consider scopes where an address is actually active { - sum_assigned += net.bw_in_utilized; - sum_assigned += net.bw_out_utilized; - sum_available += net.bw_in_available; - sum_available += net.bw_out_available; + net = solver->network_entries[i]; + if (net.bw_in_assigned > 0) //only consider scopes where an address is actually active + { + sum_assigned += net.bw_in_utilized; + sum_assigned += net.bw_out_utilized; + sum_available += net.bw_in_available; + sum_available += net.bw_out_available; + } } - } if (sum_available > 0) - { - ratio = ((double) sum_assigned) / ((double) sum_available); - } + { + ratio = ((double)sum_assigned) / ((double)sum_available); + } else - { - ratio = 0; - } + { + ratio = 0; + } return ratio > 1 ? 1 : ratio; //overutilization is possible, cap at 1 } @@ -1571,18 +1578,18 @@ ril_get_used_resource_ratio (struct GAS_RIL_Handle *solver) * @return the network struct */ static struct RIL_Scope * -ril_get_network (struct GAS_RIL_Handle *s, uint32_t type) +ril_get_network(struct GAS_RIL_Handle *s, uint32_t type) { int i; for (i = 0; i < s->networks_count; i++) - { - if (s->network_entries[i].type == type) { - return &s->network_entries[i]; + if (s->network_entries[i].type == type) + { + return &s->network_entries[i]; + } } - } - return NULL ; + return NULL; } /** @@ -1595,25 +1602,25 @@ ril_get_network (struct GAS_RIL_Handle *s, uint32_t type) * @return GNUNET_YES if there are theoretically enough resources left */ static int -ril_network_is_not_full (struct GAS_RIL_Handle *solver, enum GNUNET_NetworkType network) +ril_network_is_not_full(struct GAS_RIL_Handle *solver, enum GNUNET_NetworkType network) { struct RIL_Scope *net; struct RIL_Peer_Agent *agent; unsigned long long address_count = 0; for (agent = solver->agents_head; NULL != agent; agent = agent->next) - { - if (agent->address_inuse && agent->is_active) { - net = agent->address_inuse->solver_information; - if (net->type == network) - { - address_count++; - } + if (agent->address_inuse && agent->is_active) + { + net = agent->address_inuse->solver_information; + if (net->type == network) + { + address_count++; + } + } } - } - net = ril_get_network (solver, network); + net = ril_get_network(solver, network); return (net->bw_in_available > RIL_MIN_BW * address_count) && (net->bw_out_available > RIL_MIN_BW * address_count); } @@ -1628,7 +1635,7 @@ ril_network_is_not_full (struct GAS_RIL_Handle *solver, enum GNUNET_NetworkType * @param silent */ static void -ril_try_unblock_agent (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int silent) +ril_try_unblock_agent(struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int silent) { struct RIL_Address_Wrapped *addr_wrap; struct RIL_Scope *net; @@ -1636,19 +1643,19 @@ ril_try_unblock_agent (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *age unsigned long long start_out; for (addr_wrap = agent->addresses_head; NULL != addr_wrap; addr_wrap = addr_wrap->next) - { - net = addr_wrap->address_naked->solver_information; - if (ril_network_is_not_full(solver, net->type)) - { - if (NULL == agent->address_inuse) - { - start_in = net->bw_in_available < net->bw_in_utilized ? (net->bw_in_available - net->bw_in_utilized) / 2 : RIL_MIN_BW; - start_out = net->bw_out_available < net->bw_out_utilized ? (net->bw_out_available - net->bw_out_utilized) / 2 : RIL_MIN_BW; - envi_set_active_suggestion (solver, agent, addr_wrap->address_naked, start_in, start_out, silent); - } - return; + { + net = addr_wrap->address_naked->solver_information; + if (ril_network_is_not_full(solver, net->type)) + { + if (NULL == agent->address_inuse) + { + start_in = net->bw_in_available < net->bw_in_utilized ? (net->bw_in_available - net->bw_in_utilized) / 2 : RIL_MIN_BW; + start_out = net->bw_out_available < net->bw_out_utilized ? (net->bw_out_available - net->bw_out_utilized) / 2 : RIL_MIN_BW; + envi_set_active_suggestion(solver, agent, addr_wrap->address_naked, start_in, start_out, silent); + } + return; + } } - } agent->address_inuse = NULL; } @@ -1659,7 +1666,7 @@ ril_try_unblock_agent (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *age * @param solver the solver handle */ static void -ril_calculate_discount (struct GAS_RIL_Handle *solver) +ril_calculate_discount(struct GAS_RIL_Handle *solver) { struct GNUNET_TIME_Absolute time_now; struct GNUNET_TIME_Relative time_delta; @@ -1667,25 +1674,25 @@ ril_calculate_discount (struct GAS_RIL_Handle *solver) // MDP case only for debugging purposes if (solver->simulate) - { - solver->global_discount_variable = solver->parameters.gamma; - solver->global_discount_integrated = 1; - return; - } + { + solver->global_discount_variable = solver->parameters.gamma; + solver->global_discount_integrated = 1; + return; + } // semi-MDP case //calculate tau, i.e. how many real valued time units have passed, one time unit is one minimum time step - time_now = GNUNET_TIME_absolute_get (); - time_delta = GNUNET_TIME_absolute_get_difference (solver->step_time_last, time_now); + time_now = GNUNET_TIME_absolute_get(); + time_delta = GNUNET_TIME_absolute_get_difference(solver->step_time_last, time_now); solver->step_time_last = time_now; - tau = (double) time_delta.rel_value_us - / (double) solver->parameters.step_time_min.rel_value_us; + tau = (double)time_delta.rel_value_us + / (double)solver->parameters.step_time_min.rel_value_us; //calculate reward discounts (once per step for all agents) - solver->global_discount_variable = pow (M_E, ((-1.0) * ((double) solver->parameters.beta) * tau)); + solver->global_discount_variable = pow(M_E, ((-1.0) * ((double)solver->parameters.beta) * tau)); solver->global_discount_integrated = (1.0 - solver->global_discount_variable) - / (double) solver->parameters.beta; + / (double)solver->parameters.beta; } /** @@ -1696,18 +1703,18 @@ ril_calculate_discount (struct GAS_RIL_Handle *solver) * @return the number of allocated connections */ static int -ril_network_count_active_agents (struct GAS_RIL_Handle *solver, struct RIL_Scope *scope) +ril_network_count_active_agents(struct GAS_RIL_Handle *solver, struct RIL_Scope *scope) { int c = 0; struct RIL_Peer_Agent *cur_agent; for (cur_agent = solver->agents_head; NULL != cur_agent; cur_agent = cur_agent->next) - { - if (cur_agent->is_active && cur_agent->address_inuse && (cur_agent->address_inuse->solver_information == scope)) { - c++; + if (cur_agent->is_active && cur_agent->address_inuse && (cur_agent->address_inuse->solver_information == scope)) + { + c++; + } } - } return c; } @@ -1722,26 +1729,26 @@ ril_network_count_active_agents (struct GAS_RIL_Handle *solver, struct RIL_Scope * @return the sum of the assigned bandwidths */ static unsigned long long -ril_network_get_assigned (struct GAS_RIL_Handle *solver, enum GNUNET_NetworkType type, int direction_in) +ril_network_get_assigned(struct GAS_RIL_Handle *solver, enum GNUNET_NetworkType type, int direction_in) { struct RIL_Peer_Agent *cur; struct RIL_Scope *net; unsigned long long sum = 0; for (cur = solver->agents_head; NULL != cur; cur = cur->next) - { - if (cur->is_active && cur->address_inuse) { - net = cur->address_inuse->solver_information; - if (net->type == type) - { - if (direction_in) - sum += cur->bw_in; - else - sum += cur->bw_out; - } + if (cur->is_active && cur->address_inuse) + { + net = cur->address_inuse->solver_information; + if (net->type == type) + { + if (direction_in) + sum += cur->bw_in; + else + sum += cur->bw_out; + } + } } - } return sum; } @@ -1757,26 +1764,26 @@ ril_network_get_assigned (struct GAS_RIL_Handle *solver, enum GNUNET_NetworkType * @return the sum of the utilized bandwidths (in bytes/second) */ static unsigned long long -ril_network_get_utilized (struct GAS_RIL_Handle *solver, enum GNUNET_NetworkType type, int direction_in) +ril_network_get_utilized(struct GAS_RIL_Handle *solver, enum GNUNET_NetworkType type, int direction_in) { struct RIL_Peer_Agent *cur; struct RIL_Scope *net; unsigned long long sum = 0; for (cur = solver->agents_head; NULL != cur; cur = cur->next) - { - if (cur->is_active && cur->address_inuse) { - net = cur->address_inuse->solver_information; - if (net->type == type) - { - if (direction_in) - sum += cur->address_inuse->norm_utilization_in.norm; - else - sum += cur->address_inuse->norm_utilization_out.norm; - } + if (cur->is_active && cur->address_inuse) + { + net = cur->address_inuse->solver_information; + if (net->type == type) + { + if (direction_in) + sum += cur->address_inuse->norm_utilization_in.norm; + else + sum += cur->address_inuse->norm_utilization_out.norm; + } + } } - } return sum; } @@ -1788,21 +1795,21 @@ ril_network_get_utilized (struct GAS_RIL_Handle *solver, enum GNUNET_NetworkType * @param solver the solver handle */ static void -ril_networks_update_state (struct GAS_RIL_Handle *solver) +ril_networks_update_state(struct GAS_RIL_Handle *solver) { int c; struct RIL_Scope *net; for (c = 0; c < solver->networks_count; c++) - { - net = &solver->network_entries[c]; - net->bw_in_assigned = ril_network_get_assigned(solver, net->type, GNUNET_YES); - net->bw_in_utilized = ril_network_get_utilized(solver, net->type, GNUNET_YES); - net->bw_out_assigned = ril_network_get_assigned(solver, net->type, GNUNET_NO); - net->bw_out_utilized = ril_network_get_utilized(solver, net->type, GNUNET_NO); - net->active_agent_count = ril_network_count_active_agents(solver, net); - net->social_welfare = ril_network_get_social_welfare(solver, net); - } + { + net = &solver->network_entries[c]; + net->bw_in_assigned = ril_network_get_assigned(solver, net->type, GNUNET_YES); + net->bw_in_utilized = ril_network_get_utilized(solver, net->type, GNUNET_YES); + net->bw_out_assigned = ril_network_get_assigned(solver, net->type, GNUNET_NO); + net->bw_out_utilized = ril_network_get_utilized(solver, net->type, GNUNET_NO); + net->active_agent_count = ril_network_count_active_agents(solver, net); + net->social_welfare = ril_network_get_social_welfare(solver, net); + } } /** @@ -1813,7 +1820,7 @@ ril_networks_update_state (struct GAS_RIL_Handle *solver) * @param solver the solver handle */ static void -ril_step_schedule_next (struct GAS_RIL_Handle *solver) +ril_step_schedule_next(struct GAS_RIL_Handle *solver) { double used_ratio; double factor; @@ -1821,21 +1828,21 @@ ril_step_schedule_next (struct GAS_RIL_Handle *solver) double offset; struct GNUNET_TIME_Relative time_next; - used_ratio = ril_get_used_resource_ratio (solver); + used_ratio = ril_get_used_resource_ratio(solver); GNUNET_assert( - solver->parameters.step_time_min.rel_value_us - <= solver->parameters.step_time_max.rel_value_us); + solver->parameters.step_time_min.rel_value_us + <= solver->parameters.step_time_max.rel_value_us); - factor = (double) GNUNET_TIME_relative_subtract (solver->parameters.step_time_max, - solver->parameters.step_time_min).rel_value_us; - offset = (double) solver->parameters.step_time_min.rel_value_us; - y = factor * pow (used_ratio, RIL_INTERVAL_EXPONENT) + offset; + factor = (double)GNUNET_TIME_relative_subtract(solver->parameters.step_time_max, + solver->parameters.step_time_min).rel_value_us; + offset = (double)solver->parameters.step_time_min.rel_value_us; + y = factor * pow(used_ratio, RIL_INTERVAL_EXPONENT) + offset; - GNUNET_assert(y <= (double) solver->parameters.step_time_max.rel_value_us); - GNUNET_assert(y >= (double) solver->parameters.step_time_min.rel_value_us); + GNUNET_assert(y <= (double)solver->parameters.step_time_max.rel_value_us); + GNUNET_assert(y >= (double)solver->parameters.step_time_min.rel_value_us); - time_next = GNUNET_TIME_relative_saturating_multiply (GNUNET_TIME_UNIT_MICROSECONDS, (unsigned long long) y); + time_next = GNUNET_TIME_relative_saturating_multiply(GNUNET_TIME_UNIT_MICROSECONDS, (unsigned long long)y); // LOG (GNUNET_ERROR_TYPE_INFO, "ratio: %f, factor: %f, offset: %f, y: %f\n", // used_ratio, @@ -1844,15 +1851,15 @@ ril_step_schedule_next (struct GAS_RIL_Handle *solver) // y); if (solver->simulate) - { - time_next = GNUNET_TIME_UNIT_ZERO; - } + { + time_next = GNUNET_TIME_UNIT_ZERO; + } if ((NULL == solver->step_next_task_id) && (GNUNET_NO == solver->done)) - { - solver->step_next_task_id = GNUNET_SCHEDULER_add_delayed (time_next, &ril_step_scheduler_task, - solver); - } + { + solver->step_next_task_id = GNUNET_SCHEDULER_add_delayed(time_next, &ril_step_scheduler_task, + solver); + } } /** @@ -1861,61 +1868,62 @@ ril_step_schedule_next (struct GAS_RIL_Handle *solver) * @param solver */ static void -ril_step (struct GAS_RIL_Handle *solver) +ril_step(struct GAS_RIL_Handle *solver) { struct RIL_Peer_Agent *cur; if (GNUNET_YES == solver->bulk_lock) - { - solver->bulk_changes++; - return; - } + { + solver->bulk_changes++; + return; + } - ril_inform (solver, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS); + ril_inform(solver, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS); LOG(GNUNET_ERROR_TYPE_DEBUG, " RIL step number %d\n", solver->step_count); if (0 == solver->step_count) - { - solver->step_time_last = GNUNET_TIME_absolute_get (); - } + { + solver->step_time_last = GNUNET_TIME_absolute_get(); + } - ril_calculate_discount (solver); - ril_networks_update_state (solver); + ril_calculate_discount(solver); + ril_networks_update_state(solver); //trigger one step per active, unblocked agent for (cur = solver->agents_head; NULL != cur; cur = cur->next) - { - if (cur->is_active) { - if (NULL == cur->address_inuse) - { - ril_try_unblock_agent(solver, cur, GNUNET_NO); - } - if (cur->address_inuse) - { - agent_step (cur); - } + if (cur->is_active) + { + if (NULL == cur->address_inuse) + { + ril_try_unblock_agent(solver, cur, GNUNET_NO); + } + if (cur->address_inuse) + { + agent_step(cur); + } + } } - } - ril_networks_update_state (solver); + ril_networks_update_state(solver); solver->step_count++; - ril_step_schedule_next (solver); + ril_step_schedule_next(solver); - ril_inform (solver, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS); + ril_inform(solver, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS); - ril_inform (solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, GAS_STAT_SUCCESS); + ril_inform(solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, GAS_STAT_SUCCESS); for (cur = solver->agents_head; NULL != cur; cur = cur->next) - { - if (cur->suggestion_issue) { - solver->env->bandwidth_changed_cb (solver->env->cls, - cur->suggestion_address); - cur->suggestion_issue = GNUNET_NO; - } - } - ril_inform (solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, GAS_STAT_SUCCESS); + { + if (cur->suggestion_issue) + { + solver->env->bandwidth_changed_cb(solver->env->cls, + cur->suggestion_address); + cur->suggestion_issue = GNUNET_NO; + } + } + ril_inform(solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, GAS_STAT_SUCCESS); } /** @@ -1924,18 +1932,18 @@ ril_step (struct GAS_RIL_Handle *solver) * @param agent The respective agent */ static void -agent_w_init (struct RIL_Peer_Agent *agent) +agent_w_init(struct RIL_Peer_Agent *agent) { int i; int k; for (i = 0; i < agent->n; i++) - { - for (k = 0; k < agent->m; k++) { - agent->W[i][k] = agent->envi->parameters.alpha * (1.0 - 2.0 * ((double) GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX)/(double) UINT32_MAX)); + for (k = 0; k < agent->m; k++) + { + agent->W[i][k] = agent->envi->parameters.alpha * (1.0 - 2.0 * ((double)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX) / (double)UINT32_MAX)); + } } - } } /** @@ -1946,11 +1954,11 @@ agent_w_init (struct RIL_Peer_Agent *agent) * @return handle to the new agent */ static struct RIL_Peer_Agent * -agent_init (void *s, const struct GNUNET_PeerIdentity *peer) +agent_init(void *s, const struct GNUNET_PeerIdentity *peer) { int i; struct GAS_RIL_Handle * solver = s; - struct RIL_Peer_Agent * agent = GNUNET_new (struct RIL_Peer_Agent); + struct RIL_Peer_Agent * agent = GNUNET_new(struct RIL_Peer_Agent); agent->envi = solver; agent->peer = *peer; @@ -1961,17 +1969,17 @@ agent_init (void *s, const struct GNUNET_PeerIdentity *peer) agent->suggestion_issue = GNUNET_NO; agent->n = RIL_ACTION_TYPE_NUM; agent->m = 0; - agent->W = (double **) GNUNET_malloc (sizeof (double *) * agent->n); - agent->E = (double **) GNUNET_malloc (sizeof (double *) * agent->n); + agent->W = (double **)GNUNET_malloc(sizeof(double *) * agent->n); + agent->E = (double **)GNUNET_malloc(sizeof(double *) * agent->n); for (i = 0; i < agent->n; i++) - { - agent->W[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m); - agent->E[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m); - } + { + agent->W[i] = (double *)GNUNET_malloc(sizeof(double) * agent->m); + agent->E[i] = (double *)GNUNET_malloc(sizeof(double) * agent->m); + } agent_w_init(agent); agent->eligibility_reset = GNUNET_NO; agent->a_old = RIL_ACTION_INVALID; - agent->s_old = GNUNET_malloc (sizeof (double) * agent->m); + agent->s_old = GNUNET_malloc(sizeof(double) * agent->m); agent->address_inuse = NULL; agent->objective_old = 0; agent->nop_bonus = 0; @@ -1986,15 +1994,15 @@ agent_init (void *s, const struct GNUNET_PeerIdentity *peer) * @param agent the agent to retire */ static void -agent_die (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) +agent_die(struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) { int i; for (i = 0; i < agent->n; i++) - { - GNUNET_free_non_null(agent->W[i]); - GNUNET_free_non_null(agent->E[i]); - } + { + GNUNET_free_non_null(agent->W[i]); + GNUNET_free_non_null(agent->E[i]); + } GNUNET_free_non_null(agent->W); GNUNET_free_non_null(agent->E); GNUNET_free_non_null(agent->s_old); @@ -2010,25 +2018,25 @@ agent_die (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent) * @return the agent */ static struct RIL_Peer_Agent * -ril_get_agent (struct GAS_RIL_Handle *solver, const struct GNUNET_PeerIdentity *peer, int create) +ril_get_agent(struct GAS_RIL_Handle *solver, const struct GNUNET_PeerIdentity *peer, int create) { struct RIL_Peer_Agent *cur; for (cur = solver->agents_head; NULL != cur; cur = cur->next) - { - if (0 == GNUNET_memcmp (peer, &cur->peer)) { - return cur; + if (0 == GNUNET_memcmp(peer, &cur->peer)) + { + return cur; + } } - } if (create) - { - cur = agent_init (solver, peer); - GNUNET_CONTAINER_DLL_insert_tail(solver->agents_head, solver->agents_tail, cur); - return cur; - } - return NULL ; + { + cur = agent_init(solver, peer); + GNUNET_CONTAINER_DLL_insert_tail(solver->agents_head, solver->agents_tail, cur); + return cur; + } + return NULL; } /** @@ -2040,11 +2048,11 @@ ril_get_agent (struct GAS_RIL_Handle *solver, const struct GNUNET_PeerIdentity * * @return whether or not the network is considered active */ static int -ril_network_is_active (struct GAS_RIL_Handle *solver, enum GNUNET_NetworkType network) +ril_network_is_active(struct GAS_RIL_Handle *solver, enum GNUNET_NetworkType network) { struct RIL_Scope *net; - net = ril_get_network (solver, network); + net = ril_get_network(solver, network); return net->bw_out_available >= RIL_MIN_BW; } @@ -2060,14 +2068,14 @@ ril_network_is_active (struct GAS_RIL_Handle *solver, enum GNUNET_NetworkType ne * @param old_length the length of the old vector */ static void -ril_cut_from_vector (void **old, - size_t element_size, - unsigned int hole_start, - unsigned int hole_length, - unsigned int old_length) +ril_cut_from_vector(void **old, + size_t element_size, + unsigned int hole_start, + unsigned int hole_length, + unsigned int old_length) { char *tmpptr; - char *oldptr = (char *) *old; + char *oldptr = (char *)*old; size_t size; unsigned int bytes_before; unsigned int bytes_hole; @@ -2083,20 +2091,20 @@ ril_cut_from_vector (void **old, bytes_after = element_size * (old_length - hole_start - hole_length); if (0 == size) - { - tmpptr = NULL; - } + { + tmpptr = NULL; + } else - { - tmpptr = GNUNET_malloc (size); - GNUNET_memcpy (tmpptr, oldptr, bytes_before); - GNUNET_memcpy (tmpptr + bytes_before, oldptr + (bytes_before + bytes_hole), bytes_after); - } + { + tmpptr = GNUNET_malloc(size); + GNUNET_memcpy(tmpptr, oldptr, bytes_before); + GNUNET_memcpy(tmpptr + bytes_before, oldptr + (bytes_before + bytes_hole), bytes_after); + } if (NULL != *old) - { - GNUNET_free(*old); - } - *old = (void *) tmpptr; + { + GNUNET_free(*old); + } + *old = (void *)tmpptr; } /* @@ -2113,20 +2121,20 @@ ril_cut_from_vector (void **old, * @param pref_rel the normalized preference value for this kind over all clients */ static void -GAS_ril_address_change_preference (void *solver, - const struct GNUNET_PeerIdentity *peer, - enum GNUNET_ATS_PreferenceKind kind, - double pref_rel) +GAS_ril_address_change_preference(void *solver, + const struct GNUNET_PeerIdentity *peer, + enum GNUNET_ATS_PreferenceKind kind, + double pref_rel) { LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_change_preference() Preference '%s' for peer '%s' changed to %.2f \n", - GNUNET_ATS_print_preference_type (kind), GNUNET_i2s (peer), pref_rel); + GNUNET_ATS_print_preference_type(kind), GNUNET_i2s(peer), pref_rel); struct GAS_RIL_Handle *s = solver; s->parameters.temperature = s->parameters.temperature_init; s->parameters.epsilon = s->parameters.epsilon_init; - ril_step (s); + ril_step(s); } @@ -2140,9 +2148,9 @@ GAS_ril_address_change_preference (void *solver, * @param network network type of this address */ static void -GAS_ril_address_add (void *solver, - struct ATS_Address *address, - uint32_t network) +GAS_ril_address_add(void *solver, + struct ATS_Address *address, + uint32_t network) { struct GAS_RIL_Handle *s = solver; struct RIL_Peer_Agent *agent; @@ -2155,32 +2163,32 @@ GAS_ril_address_add (void *solver, int i; unsigned int zero; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "API_address_add()\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "API_address_add()\n"); - net = ril_get_network (s, network); + net = ril_get_network(s, network); address->solver_information = net; - if (!ril_network_is_active (s, network)) - { - LOG(GNUNET_ERROR_TYPE_DEBUG, - "API_address_add() Did not add %s address %s for peer '%s', network does not have enough bandwidth\n", - address->plugin, address->addr, GNUNET_i2s (&address->peer)); - return; - } + if (!ril_network_is_active(s, network)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "API_address_add() Did not add %s address %s for peer '%s', network does not have enough bandwidth\n", + address->plugin, address->addr, GNUNET_i2s(&address->peer)); + return; + } s->parameters.temperature = s->parameters.temperature_init; s->parameters.epsilon = s->parameters.epsilon_init; - agent = ril_get_agent (s, &address->peer, GNUNET_YES); + agent = ril_get_agent(s, &address->peer, GNUNET_YES); //add address - address_wrapped = GNUNET_new (struct RIL_Address_Wrapped); + address_wrapped = GNUNET_new(struct RIL_Address_Wrapped); address_wrapped->address_naked = address; GNUNET_CONTAINER_DLL_insert_tail(agent->addresses_head, agent->addresses_tail, address_wrapped); //increase size of W - m_new = agent->m + ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)); + m_new = agent->m + ((s->parameters.rbf_divisor + 1) * (s->parameters.rbf_divisor + 1)); m_old = agent->m; n_new = agent->n + 1; n_old = agent->n; @@ -2189,22 +2197,22 @@ GAS_ril_address_add (void *solver, agent->n = n_old; GNUNET_array_grow(agent->E, agent->n, n_new); for (i = 0; i < n_new; i++) - { - if (i < n_old) - { - agent->m = m_old; - GNUNET_array_grow(agent->W[i], agent->m, m_new); - agent->m = m_old; - GNUNET_array_grow(agent->E[i], agent->m, m_new); - } - else { - zero = 0; - GNUNET_array_grow(agent->W[i], zero, m_new); - zero = 0; - GNUNET_array_grow(agent->E[i], zero, m_new); + if (i < n_old) + { + agent->m = m_old; + GNUNET_array_grow(agent->W[i], agent->m, m_new); + agent->m = m_old; + GNUNET_array_grow(agent->E[i], agent->m, m_new); + } + else + { + zero = 0; + GNUNET_array_grow(agent->W[i], zero, m_new); + zero = 0; + GNUNET_array_grow(agent->E[i], zero, m_new); + } } - } //increase size of old state vector agent->m = m_old; @@ -2212,11 +2220,11 @@ GAS_ril_address_add (void *solver, ril_try_unblock_agent(s, agent, GNUNET_NO); - ril_step (s); + ril_step(s); LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_add() Added %s %s address %s for peer '%s'\n", address->active ? "active" : "inactive", address->plugin, address->addr, - GNUNET_i2s (&address->peer)); + GNUNET_i2s(&address->peer)); } /** @@ -2228,8 +2236,8 @@ GAS_ril_address_add (void *solver, * @param address the address to remove */ static void -GAS_ril_address_delete (void *solver, - struct ATS_Address *address) +GAS_ril_address_delete(void *solver, + struct ATS_Address *address) { struct GAS_RIL_Handle *s = solver; struct RIL_Peer_Agent *agent; @@ -2240,103 +2248,103 @@ GAS_ril_address_delete (void *solver, int i; struct RIL_Scope *net; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "API_address_delete() Delete %s %s address %s for peer '%s'\n", - address->active ? "active" : "inactive", - address->plugin, - address->addr, - GNUNET_i2s (&address->peer)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "API_address_delete() Delete %s %s address %s for peer '%s'\n", + address->active ? "active" : "inactive", + address->plugin, + address->addr, + GNUNET_i2s(&address->peer)); - agent = ril_get_agent (s, &address->peer, GNUNET_NO); + agent = ril_get_agent(s, &address->peer, GNUNET_NO); if (NULL == agent) - { - net = address->solver_information; - GNUNET_assert(! ril_network_is_active (s, net->type)); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "No agent allocated for peer yet, since address was in inactive network\n"); - return; - } + { + net = address->solver_information; + GNUNET_assert(!ril_network_is_active(s, net->type)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "No agent allocated for peer yet, since address was in inactive network\n"); + return; + } s->parameters.temperature = s->parameters.temperature_init; s->parameters.epsilon = s->parameters.epsilon_init; - address_index = agent_address_get_index (agent, address); - address_wrapped = agent_address_get_wrapped (agent, address); + address_index = agent_address_get_index(agent, address); + address_wrapped = agent_address_get_wrapped(agent, address); if (NULL == address_wrapped) - { - net = address->solver_information; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Address not considered by agent, address was in inactive network\n"); - return; - } - GNUNET_CONTAINER_DLL_remove (agent->addresses_head, - agent->addresses_tail, - address_wrapped); - GNUNET_free (address_wrapped); + { + net = address->solver_information; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Address not considered by agent, address was in inactive network\n"); + return; + } + GNUNET_CONTAINER_DLL_remove(agent->addresses_head, + agent->addresses_tail, + address_wrapped); + GNUNET_free(address_wrapped); //decrease W - m_new = agent->m - ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)); + m_new = agent->m - ((s->parameters.rbf_divisor + 1) * (s->parameters.rbf_divisor + 1)); n_new = agent->n - 1; for (i = 0; i < agent->n; i++) - { - ril_cut_from_vector ((void **) &agent->W[i], sizeof(double), - address_index * ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)), - ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)), agent->m); - ril_cut_from_vector ((void **) &agent->E[i], sizeof(double), - address_index * ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)), - ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)), agent->m); - } + { + ril_cut_from_vector((void **)&agent->W[i], sizeof(double), + address_index * ((s->parameters.rbf_divisor + 1) * (s->parameters.rbf_divisor + 1)), + ((s->parameters.rbf_divisor + 1) * (s->parameters.rbf_divisor + 1)), agent->m); + ril_cut_from_vector((void **)&agent->E[i], sizeof(double), + address_index * ((s->parameters.rbf_divisor + 1) * (s->parameters.rbf_divisor + 1)), + ((s->parameters.rbf_divisor + 1) * (s->parameters.rbf_divisor + 1)), agent->m); + } GNUNET_free_non_null(agent->W[RIL_ACTION_TYPE_NUM + address_index]); GNUNET_free_non_null(agent->E[RIL_ACTION_TYPE_NUM + address_index]); - ril_cut_from_vector ((void **) &agent->W, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index, - 1, agent->n); - ril_cut_from_vector ((void **) &agent->E, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index, - 1, agent->n); + ril_cut_from_vector((void **)&agent->W, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index, + 1, agent->n); + ril_cut_from_vector((void **)&agent->E, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index, + 1, agent->n); //correct last action if (agent->a_old > (RIL_ACTION_TYPE_NUM + address_index)) - { - agent->a_old -= 1; - } + { + agent->a_old -= 1; + } else if (agent->a_old == (RIL_ACTION_TYPE_NUM + address_index)) - { - agent->a_old = RIL_ACTION_INVALID; - } + { + agent->a_old = RIL_ACTION_INVALID; + } //decrease old state vector - ril_cut_from_vector ((void **) &agent->s_old, sizeof(double), - address_index * ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)), - ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)), agent->m); + ril_cut_from_vector((void **)&agent->s_old, sizeof(double), + address_index * ((s->parameters.rbf_divisor + 1) * (s->parameters.rbf_divisor + 1)), + ((s->parameters.rbf_divisor + 1) * (s->parameters.rbf_divisor + 1)), agent->m); agent->m = m_new; agent->n = n_new; if (agent->address_inuse == address) - { - if (NULL != agent->addresses_head) //if peer has an address left, use it - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Active address died, suggesting alternative!\n"); - envi_set_active_suggestion (s, - agent, - agent->addresses_head->address_naked, - agent->bw_in, - agent->bw_out, - GNUNET_YES); - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Active address died, suggesting disconnect!\n"); - envi_set_active_suggestion (s, agent, NULL, 0, 0, GNUNET_NO); - } - } - ril_step (solver); + { + if (NULL != agent->addresses_head) //if peer has an address left, use it + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Active address died, suggesting alternative!\n"); + envi_set_active_suggestion(s, + agent, + agent->addresses_head->address_naked, + agent->bw_in, + agent->bw_out, + GNUNET_YES); + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Active address died, suggesting disconnect!\n"); + envi_set_active_suggestion(s, agent, NULL, 0, 0, GNUNET_NO); + } + } + ril_step(solver); if (agent->suggestion_address == address) - { - agent->suggestion_issue = GNUNET_NO; - agent->suggestion_address = NULL; - } - GNUNET_assert (agent->address_inuse != address); + { + agent->suggestion_issue = GNUNET_NO; + agent->suggestion_address = NULL; + } + GNUNET_assert(agent->address_inuse != address); } @@ -2347,17 +2355,17 @@ GAS_ril_address_delete (void *solver, * @param address the address */ static void -GAS_ril_address_property_changed (void *solver, - struct ATS_Address *address) +GAS_ril_address_property_changed(void *solver, + struct ATS_Address *address) { struct GAS_RIL_Handle *s = solver; LOG(GNUNET_ERROR_TYPE_DEBUG, "Properties for peer '%s' address changed\n", - GNUNET_i2s (&address->peer)); + GNUNET_i2s(&address->peer)); s->parameters.temperature = s->parameters.temperature_init; s->parameters.epsilon = s->parameters.epsilon_init; - ril_step (s); + ril_step(s); } @@ -2372,20 +2380,20 @@ GAS_ril_address_property_changed (void *solver, * @param score the score */ static void -GAS_ril_address_preference_feedback (void *solver, - struct GNUNET_SERVICE_Client *application, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_TIME_Relative scope, - enum GNUNET_ATS_PreferenceKind kind, - double score) +GAS_ril_address_preference_feedback(void *solver, + struct GNUNET_SERVICE_Client *application, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_TIME_Relative scope, + enum GNUNET_ATS_PreferenceKind kind, + double score) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "API_address_preference_feedback() Peer '%s' got a feedback of %+.3f from application %s for " - "preference %s for %d seconds\n", - GNUNET_i2s (peer), - "UNKNOWN", - GNUNET_ATS_print_preference_type (kind), - scope.rel_value_us / 1000000); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "API_address_preference_feedback() Peer '%s' got a feedback of %+.3f from application %s for " + "preference %s for %d seconds\n", + GNUNET_i2s(peer), + "UNKNOWN", + GNUNET_ATS_print_preference_type(kind), + scope.rel_value_us / 1000000); } @@ -2395,12 +2403,12 @@ GAS_ril_address_preference_feedback (void *solver, * @param solver the solver */ static void -GAS_ril_bulk_start (void *solver) +GAS_ril_bulk_start(void *solver) { struct GAS_RIL_Handle *s = solver; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "API_bulk_start() lock: %d\n", s->bulk_lock+1); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "API_bulk_start() lock: %d\n", s->bulk_lock + 1); s->bulk_lock++; } @@ -2412,7 +2420,7 @@ GAS_ril_bulk_start (void *solver) * @param solver the solver handle */ static void -GAS_ril_bulk_stop (void *solver) +GAS_ril_bulk_stop(void *solver) { struct GAS_RIL_Handle *s = solver; @@ -2421,17 +2429,17 @@ GAS_ril_bulk_stop (void *solver) s->bulk_lock - 1); if (s->bulk_lock < 1) - { - GNUNET_break(0); - return; - } + { + GNUNET_break(0); + return; + } s->bulk_lock--; if (0 < s->bulk_changes) - { - ril_step (solver); - s->bulk_changes = 0; - } + { + ril_step(solver); + s->bulk_changes = 0; + } } @@ -2446,38 +2454,38 @@ GAS_ril_bulk_stop (void *solver) * @param peer the identity of the peer */ static void -GAS_ril_get_preferred_address (void *solver, - const struct GNUNET_PeerIdentity *peer) +GAS_ril_get_preferred_address(void *solver, + const struct GNUNET_PeerIdentity *peer) { struct GAS_RIL_Handle *s = solver; struct RIL_Peer_Agent *agent; LOG(GNUNET_ERROR_TYPE_DEBUG, "API_get_preferred_address()\n"); - agent = ril_get_agent (s, peer, GNUNET_YES); + agent = ril_get_agent(s, peer, GNUNET_YES); agent->is_active = GNUNET_YES; - envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, agent->bw_out, GNUNET_YES); + envi_set_active_suggestion(solver, agent, agent->address_inuse, agent->bw_in, agent->bw_out, GNUNET_YES); ril_try_unblock_agent(solver, agent, GNUNET_YES); if (agent->address_inuse) - { - LOG(GNUNET_ERROR_TYPE_DEBUG, - "API_get_preferred_address() Activated agent for peer '%s' with %s address %s\n", - GNUNET_i2s (peer), agent->address_inuse->plugin, agent->address_inuse->addr); - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "API_get_preferred_address() Activated agent for peer '%s' with %s address %s\n", + GNUNET_i2s(peer), agent->address_inuse->plugin, agent->address_inuse->addr); + } else - { - LOG(GNUNET_ERROR_TYPE_DEBUG, - "API_get_preferred_address() Activated agent for peer '%s', but no address available\n", - GNUNET_i2s (peer)); - s->parameters.temperature = s->parameters.temperature_init; - s->parameters.epsilon = s->parameters.epsilon_init; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "API_get_preferred_address() Activated agent for peer '%s', but no address available\n", + GNUNET_i2s(peer)); + s->parameters.temperature = s->parameters.temperature_init; + s->parameters.epsilon = s->parameters.epsilon_init; + } if (NULL != agent->address_inuse) - s->env->bandwidth_changed_cb (s->env->cls, - agent->address_inuse); + s->env->bandwidth_changed_cb(s->env->cls, + agent->address_inuse); } @@ -2491,41 +2499,41 @@ GAS_ril_get_preferred_address (void *solver, * @param peer the peer */ static void -GAS_ril_stop_get_preferred_address (void *solver, - const struct GNUNET_PeerIdentity *peer) +GAS_ril_stop_get_preferred_address(void *solver, + const struct GNUNET_PeerIdentity *peer) { struct GAS_RIL_Handle *s = solver; struct RIL_Peer_Agent *agent; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "API_stop_get_preferred_address()"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "API_stop_get_preferred_address()"); - agent = ril_get_agent (s, peer, GNUNET_NO); + agent = ril_get_agent(s, peer, GNUNET_NO); if (NULL == agent) - { - GNUNET_break(0); - return; - } + { + GNUNET_break(0); + return; + } if (GNUNET_NO == agent->is_active) - { - GNUNET_break(0); - return; - } + { + GNUNET_break(0); + return; + } s->parameters.temperature = s->parameters.temperature_init; s->parameters.epsilon = s->parameters.epsilon_init; agent->is_active = GNUNET_NO; - envi_set_active_suggestion (s, agent, agent->address_inuse, agent->bw_in, agent->bw_out, - GNUNET_YES); + envi_set_active_suggestion(s, agent, agent->address_inuse, agent->bw_in, agent->bw_out, + GNUNET_YES); - ril_step (s); + ril_step(s); LOG(GNUNET_ERROR_TYPE_DEBUG, "API_stop_get_preferred_address() Paused agent for peer '%s'\n", - GNUNET_i2s (peer)); + GNUNET_i2s(peer)); } @@ -2535,233 +2543,233 @@ GAS_ril_stop_get_preferred_address (void *solver, * @param cls pointer to the 'struct GNUNET_ATS_PluginEnvironment' */ void * -libgnunet_plugin_ats_ril_init (void *cls) +libgnunet_plugin_ats_ril_init(void *cls) { static struct GNUNET_ATS_SolverFunctions sf; struct GNUNET_ATS_PluginEnvironment *env = cls; - struct GAS_RIL_Handle *solver = GNUNET_new (struct GAS_RIL_Handle); + struct GAS_RIL_Handle *solver = GNUNET_new(struct GAS_RIL_Handle); struct RIL_Scope * cur; int c; char *string; float f_tmp; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "API_init() Initializing RIL solver\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "API_init() Initializing RIL solver\n"); - GNUNET_assert (NULL != env); - GNUNET_assert (NULL != env->cfg); - GNUNET_assert (NULL != env->stats); - GNUNET_assert (NULL != env->bandwidth_changed_cb); - GNUNET_assert (NULL != env->get_preferences); + GNUNET_assert(NULL != env); + GNUNET_assert(NULL != env->cfg); + GNUNET_assert(NULL != env->stats); + GNUNET_assert(NULL != env->bandwidth_changed_cb); + GNUNET_assert(NULL != env->get_preferences); if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(env->cfg, "ats", "RIL_RBF_DIVISOR", &solver->parameters.rbf_divisor)) - { - solver->parameters.rbf_divisor = RIL_DEFAULT_RBF_DIVISOR; - } + { + solver->parameters.rbf_divisor = RIL_DEFAULT_RBF_DIVISOR; + } if (GNUNET_OK - != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MIN", - &solver->parameters.step_time_min)) - { - solver->parameters.step_time_min = RIL_DEFAULT_STEP_TIME_MIN; - } + != GNUNET_CONFIGURATION_get_value_time(env->cfg, "ats", "RIL_STEP_TIME_MIN", + &solver->parameters.step_time_min)) + { + solver->parameters.step_time_min = RIL_DEFAULT_STEP_TIME_MIN; + } if (GNUNET_OK - != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MAX", - &solver->parameters.step_time_max)) - { - solver->parameters.step_time_max = RIL_DEFAULT_STEP_TIME_MAX; - } + != GNUNET_CONFIGURATION_get_value_time(env->cfg, "ats", "RIL_STEP_TIME_MAX", + &solver->parameters.step_time_max)) + { + solver->parameters.step_time_max = RIL_DEFAULT_STEP_TIME_MAX; + } - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_ALGORITHM", &string)) - { - GNUNET_STRINGS_utf8_toupper (string, string); - if (0 == strcmp (string, "SARSA")) + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(env->cfg, "ats", "RIL_ALGORITHM", &string)) { - solver->parameters.algorithm = RIL_ALGO_SARSA; + GNUNET_STRINGS_utf8_toupper(string, string); + if (0 == strcmp(string, "SARSA")) + { + solver->parameters.algorithm = RIL_ALGO_SARSA; + } + if (0 == strcmp(string, "Q-LEARNING")) + { + solver->parameters.algorithm = RIL_ALGO_Q; + } + + GNUNET_free(string); } - if (0 == strcmp (string, "Q-LEARNING")) + else { - solver->parameters.algorithm = RIL_ALGO_Q; + solver->parameters.algorithm = RIL_DEFAULT_ALGORITHM; } - GNUNET_free (string); - } - else - { - solver->parameters.algorithm = RIL_DEFAULT_ALGORITHM; - } - - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_SELECT", &string)) - { - solver->parameters.select = !strcmp (string, "EGREEDY") ? RIL_SELECT_EGREEDY : RIL_SELECT_SOFTMAX; - GNUNET_free (string); - } + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(env->cfg, "ats", "RIL_SELECT", &string)) + { + solver->parameters.select = !strcmp(string, "EGREEDY") ? RIL_SELECT_EGREEDY : RIL_SELECT_SOFTMAX; + GNUNET_free(string); + } else - { - solver->parameters.select = RIL_DEFAULT_SELECT; - } + { + solver->parameters.select = RIL_DEFAULT_SELECT; + } solver->parameters.beta = RIL_DEFAULT_DISCOUNT_BETA; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "RIL_DISCOUNT_BETA", &f_tmp)) - { - if (f_tmp < 0.0) - { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "RIL_DISCOUNT_BETA", f_tmp); - } - else + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "RIL_DISCOUNT_BETA", &f_tmp)) { - solver->parameters.beta = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", - "RIL_DISCOUNT_BETA", f_tmp); + if (f_tmp < 0.0) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "RIL_DISCOUNT_BETA", f_tmp); + } + else + { + solver->parameters.beta = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", + "RIL_DISCOUNT_BETA", f_tmp); + } } - } solver->parameters.gamma = RIL_DEFAULT_DISCOUNT_GAMMA; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "RIL_DISCOUNT_GAMMA", &f_tmp)) - { - if ((f_tmp < 0.0) || (f_tmp > 1.0)) + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "RIL_DISCOUNT_GAMMA", &f_tmp)) { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "RIL_DISCOUNT_GAMMA", f_tmp); - } - else - { - solver->parameters.gamma = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", - "RIL_DISCOUNT_GAMMA", f_tmp); + if ((f_tmp < 0.0) || (f_tmp > 1.0)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "RIL_DISCOUNT_GAMMA", f_tmp); + } + else + { + solver->parameters.gamma = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", + "RIL_DISCOUNT_GAMMA", f_tmp); + } } - } solver->parameters.alpha = RIL_DEFAULT_GRADIENT_STEP_SIZE; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "RIL_GRADIENT_STEP_SIZE", &f_tmp)) - { - if ((f_tmp < 0.0) || (f_tmp > 1.0)) + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "RIL_GRADIENT_STEP_SIZE", &f_tmp)) { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "RIL_GRADIENT_STEP_SIZE", f_tmp); - } - else - { - solver->parameters.alpha = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", - "RIL_GRADIENT_STEP_SIZE", f_tmp); + if ((f_tmp < 0.0) || (f_tmp > 1.0)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "RIL_GRADIENT_STEP_SIZE", f_tmp); + } + else + { + solver->parameters.alpha = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", + "RIL_GRADIENT_STEP_SIZE", f_tmp); + } } - } solver->parameters.lambda = RIL_DEFAULT_TRACE_DECAY; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "RIL_TRACE_DECAY", &f_tmp)) - { - if ((f_tmp < 0.0) || (f_tmp > 1.0)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "RIL_TRACE_DECAY", f_tmp); - } - else + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "RIL_TRACE_DECAY", &f_tmp)) { - solver->parameters.lambda = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", - "RIL_TRACE_DECAY", f_tmp); + if ((f_tmp < 0.0) || (f_tmp > 1.0)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "RIL_TRACE_DECAY", f_tmp); + } + else + { + solver->parameters.lambda = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", + "RIL_TRACE_DECAY", f_tmp); + } } - } solver->parameters.epsilon_init = RIL_DEFAULT_EXPLORE_RATIO; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "RIL_EXPLORE_RATIO", &f_tmp)) - { - if ((f_tmp < 0.0) || (f_tmp > 1.0)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "RIL_EXPLORE_RATIO", f_tmp); - } - else + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "RIL_EXPLORE_RATIO", &f_tmp)) { - solver->parameters.epsilon_init = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", - "RIL_EXPLORE_RATIO", f_tmp); + if ((f_tmp < 0.0) || (f_tmp > 1.0)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "RIL_EXPLORE_RATIO", f_tmp); + } + else + { + solver->parameters.epsilon_init = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", + "RIL_EXPLORE_RATIO", f_tmp); + } } - } solver->parameters.epsilon_decay = RIL_DEFAULT_EXPLORE_DECAY; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "RIL_EXPLORE_DECAY", &f_tmp)) - { - if ((f_tmp < 0.0) || (f_tmp > 1.0)) + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "RIL_EXPLORE_DECAY", &f_tmp)) { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "RIL_EXPLORE_DECAY", f_tmp); - } - else - { - solver->parameters.epsilon_decay = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", - "RIL_EXPLORE_DECAY", f_tmp); + if ((f_tmp < 0.0) || (f_tmp > 1.0)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "RIL_EXPLORE_DECAY", f_tmp); + } + else + { + solver->parameters.epsilon_decay = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", + "RIL_EXPLORE_DECAY", f_tmp); + } } - } solver->parameters.temperature_init = RIL_DEFAULT_TEMPERATURE; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "RIL_TEMPERATURE", &f_tmp)) - { - if (f_tmp <= 0.0) - { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "RIL_TEMPERATURE", f_tmp); - } - else + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "RIL_TEMPERATURE", &f_tmp)) { - solver->parameters.temperature_init = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", - "RIL_TEMPERATURE", f_tmp); + if (f_tmp <= 0.0) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "RIL_TEMPERATURE", f_tmp); + } + else + { + solver->parameters.temperature_init = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", + "RIL_TEMPERATURE", f_tmp); + } } - } solver->parameters.temperature_decay = RIL_DEFAULT_TEMPERATURE_DECAY; - if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats", - "RIL_TEMPERATURE_DECAY", &f_tmp)) - { - if ((f_tmp <= 0.0) || solver->parameters.temperature_decay > 1) + if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float(env->cfg, "ats", + "RIL_TEMPERATURE_DECAY", &f_tmp)) { - LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), - "RIL_TEMPERATURE_DECAY", f_tmp); + if ((f_tmp <= 0.0) || solver->parameters.temperature_decay > 1) + { + LOG(GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"), + "RIL_TEMPERATURE_DECAY", f_tmp); + } + else + { + solver->parameters.temperature_decay = f_tmp; + LOG(GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", + "RIL_TEMPERATURE_DECAY", f_tmp); + } } - else + + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(env->cfg, "ats", "RIL_SIMULATE", &solver->simulate)) { - solver->parameters.temperature_decay = f_tmp; - LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n", - "RIL_TEMPERATURE_DECAY", f_tmp); + solver->simulate = GNUNET_NO; } - } - - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (env->cfg, "ats", "RIL_SIMULATE", &solver->simulate)) - { - solver->simulate = GNUNET_NO; - } if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(env->cfg, "ats", "RIL_REPLACE_TRACES")) - { - solver->parameters.eligibility_trace_mode = RIL_E_REPLACE; - } + { + solver->parameters.eligibility_trace_mode = RIL_E_REPLACE; + } else - { - solver->parameters.eligibility_trace_mode = RIL_E_ACCUMULATE; - } - - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_SOCIAL_WELFARE", &string)) - { - solver->parameters.social_welfare = !strcmp (string, "NASH") ? RIL_WELFARE_NASH : RIL_WELFARE_EGALITARIAN; - GNUNET_free (string); - } + { + solver->parameters.eligibility_trace_mode = RIL_E_ACCUMULATE; + } + + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(env->cfg, "ats", "RIL_SOCIAL_WELFARE", &string)) + { + solver->parameters.social_welfare = !strcmp(string, "NASH") ? RIL_WELFARE_NASH : RIL_WELFARE_EGALITARIAN; + GNUNET_free(string); + } else - { - solver->parameters.social_welfare = RIL_DEFAULT_WELFARE; - } + { + solver->parameters.social_welfare = RIL_DEFAULT_WELFARE; + } solver->env = env; sf.cls = solver; @@ -2776,22 +2784,22 @@ libgnunet_plugin_ats_ril_init (void *cls) sf.s_bulk_stop = &GAS_ril_bulk_stop; solver->networks_count = env->network_count; - solver->network_entries = GNUNET_malloc (env->network_count * sizeof (struct RIL_Scope)); + solver->network_entries = GNUNET_malloc(env->network_count * sizeof(struct RIL_Scope)); solver->step_count = 0; solver->done = GNUNET_NO; for (c = 0; c < env->network_count; c++) - { - cur = &solver->network_entries[c]; - cur->type = c; - cur->bw_in_available = env->in_quota[c]; - cur->bw_out_available = env->out_quota[c]; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "init() Quotas for %s network: IN %llu - OUT %llu\n", - GNUNET_NT_to_string(cur->type), - cur->bw_in_available/1024, - cur->bw_out_available/1024); - } + { + cur = &solver->network_entries[c]; + cur->type = c; + cur->bw_in_available = env->in_quota[c]; + cur->bw_out_available = env->out_quota[c]; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "init() Quotas for %s network: IN %llu - OUT %llu\n", + GNUNET_NT_to_string(cur->type), + cur->bw_in_available / 1024, + cur->bw_out_available / 1024); + } LOG(GNUNET_ERROR_TYPE_DEBUG, "init() Parameters:\n"); LOG(GNUNET_ERROR_TYPE_DEBUG, "init() Algorithm = %s, alpha = %f, beta = %f, lambda = %f\n", @@ -2816,7 +2824,7 @@ libgnunet_plugin_ats_ril_init (void *cls) * @param cls the solver handle */ void * -libgnunet_plugin_ats_ril_done (void *cls) +libgnunet_plugin_ats_ril_done(void *cls) { struct GNUNET_ATS_SolverFunctions *sf = cls; struct GAS_RIL_Handle *s = sf->cls; @@ -2829,17 +2837,17 @@ libgnunet_plugin_ats_ril_done (void *cls) cur_agent = s->agents_head; while (NULL != cur_agent) - { - next_agent = cur_agent->next; - GNUNET_CONTAINER_DLL_remove(s->agents_head, s->agents_tail, cur_agent); - agent_die (s, cur_agent); - cur_agent = next_agent; - } + { + next_agent = cur_agent->next; + GNUNET_CONTAINER_DLL_remove(s->agents_head, s->agents_tail, cur_agent); + agent_die(s, cur_agent); + cur_agent = next_agent; + } if (NULL != s->step_next_task_id) - { - GNUNET_SCHEDULER_cancel (s->step_next_task_id); - } + { + GNUNET_SCHEDULER_cancel(s->step_next_task_id); + } GNUNET_free(s->network_entries); GNUNET_free(s); diff --git a/src/ats/test_ats2_lib.c b/src/ats/test_ats2_lib.c index 2c6dafa1a..1b9f0e234 100644 --- a/src/ats/test_ats2_lib.c +++ b/src/ats/test_ats2_lib.c @@ -14,7 +14,7 @@ You should have received a copy of the GNU Affero General Public License along with this program. If not, see . -*/ + */ /** * @file ats/test_ats2_lib.c * @brief test ATS library with a generic interpreter for running ATS tests @@ -76,13 +76,13 @@ static struct GNUNET_ATS_SessionRecord *sr; * @return */ static void -allocation_cb (void *cls, - struct GNUNET_ATS_Session *session, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) +allocation_cb(void *cls, + struct GNUNET_ATS_Session *session, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "allocation_cb() called\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "allocation_cb() called\n"); } @@ -96,12 +96,12 @@ allocation_cb (void *cls, * @param address */ static void -suggestion_cb (void *cls, - const struct GNUNET_PeerIdentity *pid, - const char *address) +suggestion_cb(void *cls, + const struct GNUNET_PeerIdentity *pid, + const char *address) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "suggestion_cb() called\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "suggestion_cb() called\n"); ret = 0; } @@ -112,16 +112,16 @@ suggestion_cb (void *cls, * Initialises the application and transportation side of ATS. */ static void -init_both (const struct GNUNET_CONFIGURATION_Handle *cfg) +init_both(const struct GNUNET_CONFIGURATION_Handle *cfg) { - ah = GNUNET_ATS_application_init (cfg); - GNUNET_assert (NULL != ah); - th = GNUNET_ATS_transport_init (cfg, - &allocation_cb, - NULL, - &suggestion_cb, - NULL); - GNUNET_assert (NULL != ah); + ah = GNUNET_ATS_application_init(cfg); + GNUNET_assert(NULL != ah); + th = GNUNET_ATS_transport_init(cfg, + &allocation_cb, + NULL, + &suggestion_cb, + NULL); + GNUNET_assert(NULL != ah); } @@ -129,11 +129,11 @@ init_both (const struct GNUNET_CONFIGURATION_Handle *cfg) * @brief Disconnect both 'sides' of ATS */ static void -finish_both (void) +finish_both(void) { - GNUNET_ATS_application_done (ah); + GNUNET_ATS_application_done(ah); ah = NULL; - GNUNET_ATS_transport_done (th); + GNUNET_ATS_transport_done(th); th = NULL; } @@ -142,7 +142,7 @@ finish_both (void) * @brief Provide information about the start of an imaginary connection */ static void -provide_info_start (void) +provide_info_start(void) { struct GNUNET_ATS_Properties prop = { @@ -157,12 +157,12 @@ provide_info_start (void) .cc = GNUNET_TRANSPORT_CC_UNKNOWN, }; - sr = GNUNET_ATS_session_add (th, - &other_peer, - "test-address", - NULL, - &prop); - GNUNET_assert (NULL != sr); + sr = GNUNET_ATS_session_add(th, + &other_peer, + "test-address", + NULL, + &prop); + GNUNET_assert(NULL != sr); } @@ -170,9 +170,9 @@ provide_info_start (void) * @brief Provide information about the end of an imaginary connection */ static void -provide_info_end (void) +provide_info_end(void) { - GNUNET_ATS_session_del (sr); + GNUNET_ATS_session_del(sr); } @@ -180,24 +180,24 @@ provide_info_end (void) * @brief Inform ATS about the need of a connection towards a peer */ static void -get_suggestion (void) +get_suggestion(void) { struct GNUNET_ATS_ApplicationSuggestHandle *ash; - ash = GNUNET_ATS_application_suggest (ah, - &other_peer, - GNUNET_MQ_PREFERENCE_NONE, - GNUNET_BANDWIDTH_VALUE_MAX); - GNUNET_assert (NULL != ash); + ash = GNUNET_ATS_application_suggest(ah, + &other_peer, + GNUNET_MQ_PREFERENCE_NONE, + GNUNET_BANDWIDTH_VALUE_MAX); + GNUNET_assert(NULL != ash); } static void -on_shutdown (void *cls) +on_shutdown(void *cls) { - provide_info_end (); - finish_both (); - GNUNET_SCHEDULER_shutdown (); + provide_info_end(); + finish_both(); + GNUNET_SCHEDULER_shutdown(); } @@ -209,16 +209,16 @@ on_shutdown (void *cls) * @param peer handle to the peer */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - init_both (cfg); - provide_info_start (); - get_suggestion (); - (void) GNUNET_SCHEDULER_add_delayed (timeout, - &on_shutdown, - NULL); + init_both(cfg); + provide_info_start(); + get_suggestion(); + (void)GNUNET_SCHEDULER_add_delayed(timeout, + &on_shutdown, + NULL); } @@ -231,27 +231,27 @@ run (void *cls, * @return */ int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { ret = 1; - memset (&other_peer, 0, sizeof (struct GNUNET_PeerIdentity)); - timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, - 2); - if (0 != GNUNET_TESTING_peer_run ("test-ats2-lib", - "test_ats2_lib.conf", - &run, NULL)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Running the testing peer failed.\n"); - return 1; - } + memset(&other_peer, 0, sizeof(struct GNUNET_PeerIdentity)); + timeout = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, + 2); + if (0 != GNUNET_TESTING_peer_run("test-ats2-lib", + "test_ats2_lib.conf", + &run, NULL)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Running the testing peer failed.\n"); + return 1; + } if (0 != ret) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Global status indicates unsuccessful testrun - probably allocation_cb was not called.\n"); - ret = 77; // SKIP test, test not yet right! - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Global status indicates unsuccessful testrun - probably allocation_cb was not called.\n"); + ret = 77; // SKIP test, test not yet right! + } return ret; } diff --git a/src/ats/test_ats2_lib.h b/src/ats/test_ats2_lib.h index 5c1518792..f6d4d45b0 100644 --- a/src/ats/test_ats2_lib.h +++ b/src/ats/test_ats2_lib.h @@ -11,10 +11,10 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . -*/ + */ /** * @file ats/test_ats_lib.h * @brief test ATS library with a generic interpreter for running ATS tests @@ -515,9 +515,9 @@ * @return 0 on success */ int -TEST_ATS_run (int argc, - char *argv[], - struct Command *cmds, - struct GNUNET_TIME_Relative timeout); +TEST_ATS_run(int argc, + char *argv[], + struct Command *cmds, + struct GNUNET_TIME_Relative timeout); #endif diff --git a/src/ats/test_ats_api.c b/src/ats/test_ats_api.c index f04b4b08b..bc703a111 100644 --- a/src/ats/test_ats_api.c +++ b/src/ats/test_ats_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/test_ats_api.c * @brief test ATS @@ -28,7 +28,7 @@ /** * Global timeout for the testcase. */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 3) /** * Definition of the test as a sequence of commands. @@ -89,7 +89,7 @@ static struct Command test_commands[] = { .code = CMD_ADD_SESSION, .label = "add-session-0-0-1", .details.add_session = { - .add_label ="add-address-0-0", + .add_label = "add-address-0-0", .session = 1 } }, @@ -104,7 +104,7 @@ static struct Command test_commands[] = { .code = CMD_CHANGE_PREFERENCE, .details.change_preference = { .pid = 0 - /* FIXME: preference details */ + /* FIXME: preference details */ } }, { @@ -233,13 +233,13 @@ static struct Command test_commands[] = { int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { - return TEST_ATS_run (argc, - argv, - test_commands, - TIMEOUT); + return TEST_ATS_run(argc, + argv, + test_commands, + TIMEOUT); } diff --git a/src/ats/test_ats_lib.c b/src/ats/test_ats_lib.c index 33597e678..979dbde3e 100644 --- a/src/ats/test_ats_lib.c +++ b/src/ats/test_ats_lib.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/test_ats_lib.c * @brief test ATS library with a generic interpreter for running ATS tests @@ -31,8 +31,7 @@ /** * Information about the last address suggestion we got for a peer. */ -struct AddressSuggestData -{ +struct AddressSuggestData { /** * Which session were we given? */ @@ -63,8 +62,7 @@ struct AddressSuggestData /** * Information about the last address information we got for an address. */ -struct AddressInformationData -{ +struct AddressInformationData { /** * What address is this data about? */ @@ -156,18 +154,18 @@ static struct Command *test_commands; * @return #GNUNET_OK (continue to iterate) */ static int -free_asd (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +free_asd(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct AddressSuggestData *asd = value; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (p2asd, - key, - asd)); - GNUNET_free_non_null (asd->address); - GNUNET_free (asd); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(p2asd, + key, + asd)); + GNUNET_free_non_null(asd->address); + GNUNET_free(asd); return GNUNET_OK; } @@ -181,18 +179,18 @@ free_asd (void *cls, * @return #GNUNET_OK (continue to iterate) */ static int -free_aid (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +free_aid(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct AddressInformationData *aid = value; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (p2aid, - key, - aid)); - GNUNET_free (aid->address); - GNUNET_free (aid); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(p2aid, + key, + aid)); + GNUNET_free(aid->address); + GNUNET_free(aid); return GNUNET_OK; } @@ -204,18 +202,17 @@ free_aid (void *cls, * @return NULL if peer was never involved */ static struct AddressSuggestData * -find_address_suggestion (const struct GNUNET_PeerIdentity *pid) +find_address_suggestion(const struct GNUNET_PeerIdentity *pid) { - return GNUNET_CONTAINER_multipeermap_get (p2asd, - pid); + return GNUNET_CONTAINER_multipeermap_get(p2asd, + pid); } /** * Closure for #match_address() */ -struct MatchAddressContext -{ +struct MatchAddressContext { /** * Address to find. */ @@ -237,19 +234,19 @@ struct MatchAddressContext * @return #GNUNET_OK if not found */ static int -match_address (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +match_address(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct MatchAddressContext *mac = cls; struct AddressInformationData *aid = value; - if (0 == GNUNET_HELLO_address_cmp (mac->addr, - aid->address)) - { - mac->ret = aid; - return GNUNET_NO; - } + if (0 == GNUNET_HELLO_address_cmp(mac->addr, + aid->address)) + { + mac->ret = aid; + return GNUNET_NO; + } return GNUNET_OK; } @@ -261,16 +258,16 @@ match_address (void *cls, * @return NULL if peer was never involved */ static struct AddressInformationData * -find_address_information (const struct GNUNET_HELLO_Address *addr) +find_address_information(const struct GNUNET_HELLO_Address *addr) { struct MatchAddressContext mac; mac.ret = NULL; mac.addr = addr; - GNUNET_CONTAINER_multipeermap_get_multiple (p2aid, - &addr->peer, - &match_address, - &mac); + GNUNET_CONTAINER_multipeermap_get_multiple(p2aid, + &addr->peer, + &match_address, + &mac); return mac.ret; } @@ -281,51 +278,51 @@ find_address_information (const struct GNUNET_HELLO_Address *addr) * @param cls NULL */ static void -end (void *cls) +end(void *cls) { if (0 != ret) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Test failed at stage %u %s\n", - off, - (NULL != test_commands[off].label) - ? test_commands[off].label - : ""); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Test failed at stage %u %s\n", + off, + (NULL != test_commands[off].label) + ? test_commands[off].label + : ""); if (NULL != interpreter_task) - { - GNUNET_SCHEDULER_cancel (interpreter_task); - interpreter_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(interpreter_task); + interpreter_task = NULL; + } if (NULL != sched_ats) - { - GNUNET_ATS_scheduling_done (sched_ats); - sched_ats = NULL; - } + { + GNUNET_ATS_scheduling_done(sched_ats); + sched_ats = NULL; + } if (NULL != con_ats) - { - GNUNET_ATS_connectivity_done (con_ats); - con_ats = NULL; - } + { + GNUNET_ATS_connectivity_done(con_ats); + con_ats = NULL; + } if (NULL != perf_ats) - { - GNUNET_ATS_performance_done (perf_ats); - perf_ats = NULL; - } + { + GNUNET_ATS_performance_done(perf_ats); + perf_ats = NULL; + } if (NULL != p2asd) - { - GNUNET_CONTAINER_multipeermap_iterate (p2asd, - &free_asd, - NULL); - GNUNET_CONTAINER_multipeermap_destroy (p2asd); - p2asd = NULL; - } + { + GNUNET_CONTAINER_multipeermap_iterate(p2asd, + &free_asd, + NULL); + GNUNET_CONTAINER_multipeermap_destroy(p2asd); + p2asd = NULL; + } if (NULL != p2aid) - { - GNUNET_CONTAINER_multipeermap_iterate (p2aid, - &free_aid, - NULL); - GNUNET_CONTAINER_multipeermap_destroy (p2aid); - p2aid = NULL; - } + { + GNUNET_CONTAINER_multipeermap_iterate(p2aid, + &free_aid, + NULL); + GNUNET_CONTAINER_multipeermap_destroy(p2aid); + p2aid = NULL; + } } @@ -335,19 +332,19 @@ end (void *cls) * @param cls NULL */ static void -interpreter (void *cls); +interpreter(void *cls); /** * Run the interpreter next. */ static void -run_interpreter () +run_interpreter() { if (NULL != interpreter_task) - GNUNET_SCHEDULER_cancel (interpreter_task); - interpreter_task = GNUNET_SCHEDULER_add_now (&interpreter, - NULL); + GNUNET_SCHEDULER_cancel(interpreter_task); + interpreter_task = GNUNET_SCHEDULER_add_now(&interpreter, + NULL); } @@ -358,15 +355,15 @@ run_interpreter () * @param pk resulting fake public key */ static void -make_peer (uint32_t pid, - struct GNUNET_PeerIdentity *pk) +make_peer(uint32_t pid, + struct GNUNET_PeerIdentity *pk) { - memset (pk, - (int) pid, - sizeof (struct GNUNET_PeerIdentity)); - GNUNET_memcpy (pk, - &pid, - sizeof (uint32_t)); + memset(pk, + (int)pid, + sizeof(struct GNUNET_PeerIdentity)); + GNUNET_memcpy(pk, + &pid, + sizeof(uint32_t)); } @@ -379,29 +376,28 @@ make_peer (uint32_t pid, * @return the address */ static struct GNUNET_HELLO_Address * -make_address (uint32_t pid, - uint32_t num, - enum GNUNET_HELLO_AddressInfo addr_flags) +make_address(uint32_t pid, + uint32_t num, + enum GNUNET_HELLO_AddressInfo addr_flags) { struct GNUNET_PeerIdentity pk; uint32_t nbo; - nbo = htonl (num); - make_peer (pid, - &pk); - return GNUNET_HELLO_address_allocate (&pk, - "test", - &nbo, - sizeof (nbo), - addr_flags); + nbo = htonl(num); + make_peer(pid, + &pk); + return GNUNET_HELLO_address_allocate(&pk, + "test", + &nbo, + sizeof(nbo), + addr_flags); } /** * Our dummy sessions. */ -struct GNUNET_ATS_Session -{ +struct GNUNET_ATS_Session { /** * Field to avoid `0 == sizeof(struct GNUNET_ATS_Session)`. */ @@ -416,7 +412,7 @@ struct GNUNET_ATS_Session * @return NULL if @a i is 0, otherwise a pointer unique to @a i */ static struct GNUNET_ATS_Session * -make_session (unsigned int i) +make_session(unsigned int i) { struct GNUNET_ATS_Session *baseptr = NULL; @@ -438,19 +434,19 @@ make_session (unsigned int i) * @return previous command with the matching label */ static struct Command * -find_command (enum CommandCode code, - const char *label) +find_command(enum CommandCode code, + const char *label) { int i; if (NULL == label) return NULL; - for (i=off-1;i>=0;i--) - if ( (code == test_commands[i].code) && - (0 == strcmp (test_commands[i].label, - label)) ) + for (i = off - 1; i >= 0; i--) + if ((code == test_commands[i].code) && + (0 == strcmp(test_commands[i].label, + label))) return &test_commands[i]; - GNUNET_break (0); + GNUNET_break(0); return NULL; } @@ -470,51 +466,53 @@ find_command (enum CommandCode code, * @param prop performance data for the address */ static void -info_cb (void *cls, - const struct GNUNET_HELLO_Address *address, - int address_active, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, - const struct GNUNET_ATS_Properties *prop) +info_cb(void *cls, + const struct GNUNET_HELLO_Address *address, + int address_active, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, + const struct GNUNET_ATS_Properties *prop) { struct Command *c = cls; struct CommandListAddresses *cmd = &c->details.list_addresses; if (NULL == address) - { - cmd->alh = NULL; - /* we are done with the iteration, continue to execute */ - if ( (cmd->calls < cmd->min_calls) && - (cmd->active_calls < cmd->min_active_calls) ) { - GNUNET_SCHEDULER_shutdown (); + cmd->alh = NULL; + /* we are done with the iteration, continue to execute */ + if ((cmd->calls < cmd->min_calls) && + (cmd->active_calls < cmd->min_active_calls)) + { + GNUNET_SCHEDULER_shutdown(); + return; + } + off++; + run_interpreter(); return; } - off++; - run_interpreter (); - return; - } switch (address_active) - { - case GNUNET_YES: - cmd->active_calls++; - cmd->calls++; - break; - case GNUNET_NO: - cmd->calls++; - break; - case GNUNET_SYSERR: - return; - } - if ( (cmd->calls > cmd->max_calls) && - (cmd->active_calls < cmd->max_active_calls) ) - { - GNUNET_break (0); - GNUNET_ATS_performance_list_addresses_cancel (cmd->alh); - cmd->alh = NULL; - GNUNET_SCHEDULER_shutdown (); - return; - } + { + case GNUNET_YES: + cmd->active_calls++; + cmd->calls++; + break; + + case GNUNET_NO: + cmd->calls++; + break; + + case GNUNET_SYSERR: + return; + } + if ((cmd->calls > cmd->max_calls) && + (cmd->active_calls < cmd->max_active_calls)) + { + GNUNET_break(0); + GNUNET_ATS_performance_list_addresses_cancel(cmd->alh); + cmd->alh = NULL; + GNUNET_SCHEDULER_shutdown(); + return; + } } @@ -529,56 +527,58 @@ info_cb (void *cls, * long should the client wait until re-trying? */ static void -reservation_cb (void *cls, - const struct GNUNET_PeerIdentity *peer, - int32_t amount, - struct GNUNET_TIME_Relative res_delay) +reservation_cb(void *cls, + const struct GNUNET_PeerIdentity *peer, + int32_t amount, + struct GNUNET_TIME_Relative res_delay) { struct Command *cmd = cls; struct GNUNET_PeerIdentity pid; cmd->details.reserve_bandwidth.rc = NULL; - make_peer (cmd->details.reserve_bandwidth.pid, - &pid); - GNUNET_assert (0 == GNUNET_memcmp (peer, - &pid)); + make_peer(cmd->details.reserve_bandwidth.pid, + &pid); + GNUNET_assert(0 == GNUNET_memcmp(peer, + &pid)); switch (cmd->details.reserve_bandwidth.expected_result) - { - case GNUNET_OK: - if (amount != cmd->details.reserve_bandwidth.amount) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unexpectedly failed to reserve %d/%d bytes with delay %s!\n", - (int) amount, - (int) cmd->details.reserve_bandwidth.amount, - GNUNET_STRINGS_relative_time_to_string (res_delay, - GNUNET_YES)); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } - break; - case GNUNET_NO: - GNUNET_break ( (0 != amount) || - (0 != res_delay.rel_value_us) ); - break; - case GNUNET_SYSERR: - if ( (amount != 0) || - (0 == res_delay.rel_value_us) ) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unexpectedly reserved %d bytes with delay %s!\n", - (int) amount, - GNUNET_STRINGS_relative_time_to_string (res_delay, - GNUNET_YES)); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; + case GNUNET_OK: + if (amount != cmd->details.reserve_bandwidth.amount) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unexpectedly failed to reserve %d/%d bytes with delay %s!\n", + (int)amount, + (int)cmd->details.reserve_bandwidth.amount, + GNUNET_STRINGS_relative_time_to_string(res_delay, + GNUNET_YES)); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + break; + + case GNUNET_NO: + GNUNET_break((0 != amount) || + (0 != res_delay.rel_value_us)); + break; + + case GNUNET_SYSERR: + if ((amount != 0) || + (0 == res_delay.rel_value_us)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unexpectedly reserved %d bytes with delay %s!\n", + (int)amount, + GNUNET_STRINGS_relative_time_to_string(res_delay, + GNUNET_YES)); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + break; } - break; - } off++; - run_interpreter (); + run_interpreter(); } @@ -588,282 +588,297 @@ reservation_cb (void *cls, * @param cls NULL */ static void -interpreter (void *cls) +interpreter(void *cls) { struct Command *cmd; interpreter_task = NULL; while (1) - { - cmd = &test_commands[off]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "#%u: %d %s\n", - off, - (int) cmd->code, - (NULL != cmd->label) ? cmd->label : ""); - switch (cmd->code) { - case CMD_END_PASS: - ret = 0; - GNUNET_SCHEDULER_shutdown (); - return; - case CMD_ADD_ADDRESS: - { - struct GNUNET_HELLO_Address *addr; - struct GNUNET_ATS_Session *session; - - addr = make_address (cmd->details.add_address.pid, - cmd->details.add_address.addr_num, - cmd->details.add_address.addr_flags); - session = make_session (cmd->details.add_address.session); - if (cmd->details.add_address.expect_fail) - GNUNET_log_skip (1, GNUNET_NO); - cmd->details.add_address.ar - = GNUNET_ATS_address_add (sched_ats, - addr, - session, - &cmd->details.add_address.properties); - GNUNET_free (addr); - if (cmd->details.add_address.expect_fail) + cmd = &test_commands[off]; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "#%u: %d %s\n", + off, + (int)cmd->code, + (NULL != cmd->label) ? cmd->label : ""); + switch (cmd->code) + { + case CMD_END_PASS: + ret = 0; + GNUNET_SCHEDULER_shutdown(); + return; + + case CMD_ADD_ADDRESS: { - GNUNET_log_skip (0, GNUNET_YES); + struct GNUNET_HELLO_Address *addr; + struct GNUNET_ATS_Session *session; + + addr = make_address(cmd->details.add_address.pid, + cmd->details.add_address.addr_num, + cmd->details.add_address.addr_flags); + session = make_session(cmd->details.add_address.session); + if (cmd->details.add_address.expect_fail) + GNUNET_log_skip(1, GNUNET_NO); + cmd->details.add_address.ar + = GNUNET_ATS_address_add(sched_ats, + addr, + session, + &cmd->details.add_address.properties); + GNUNET_free(addr); + if (cmd->details.add_address.expect_fail) + { + GNUNET_log_skip(0, GNUNET_YES); + } + else if (NULL == cmd->details.add_address.ar) + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + off++; + break; } - else if (NULL == cmd->details.add_address.ar) + + case CMD_DEL_ADDRESS: { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; + struct Command *add; + + add = find_command(CMD_ADD_ADDRESS, + cmd->details.del_address.add_label); + GNUNET_assert(NULL != add->details.add_address.ar); + GNUNET_ATS_address_destroy(add->details.add_address.ar); + add->details.add_address.ar = NULL; + off++; + break; } - off++; - break; - } - case CMD_DEL_ADDRESS: - { - struct Command *add; - - add = find_command (CMD_ADD_ADDRESS, - cmd->details.del_address.add_label); - GNUNET_assert (NULL != add->details.add_address.ar); - GNUNET_ATS_address_destroy (add->details.add_address.ar); - add->details.add_address.ar = NULL; - off++; - break; - } - case CMD_AWAIT_ADDRESS_SUGGESTION: - { - struct GNUNET_PeerIdentity pid; - struct GNUNET_HELLO_Address *addr; - struct Command *add; - struct AddressSuggestData *asd; - int done; - - make_peer (cmd->details.await_address_suggestion.pid, - &pid); - asd = find_address_suggestion (&pid); - if (NULL == asd) - return; - if (GNUNET_NO == asd->active) - return; /* last suggestion was to disconnect, wait longer */ - done = GNUNET_YES; - if (NULL != cmd->details.await_address_suggestion.add_label) + + case CMD_AWAIT_ADDRESS_SUGGESTION: { - done = GNUNET_NO; - add = find_command (CMD_ADD_ADDRESS, - cmd->details.await_address_suggestion.add_label); - addr = make_address (add->details.add_address.pid, - add->details.add_address.addr_num, - add->details.add_address.addr_flags); - if ( (asd->session == - make_session (add->details.add_address.session)) && - (0 == - GNUNET_HELLO_address_cmp (addr, - asd->address)) ) - done = GNUNET_YES; - GNUNET_free (addr); + struct GNUNET_PeerIdentity pid; + struct GNUNET_HELLO_Address *addr; + struct Command *add; + struct AddressSuggestData *asd; + int done; + + make_peer(cmd->details.await_address_suggestion.pid, + &pid); + asd = find_address_suggestion(&pid); + if (NULL == asd) + return; + if (GNUNET_NO == asd->active) + return; /* last suggestion was to disconnect, wait longer */ + done = GNUNET_YES; + if (NULL != cmd->details.await_address_suggestion.add_label) + { + done = GNUNET_NO; + add = find_command(CMD_ADD_ADDRESS, + cmd->details.await_address_suggestion.add_label); + addr = make_address(add->details.add_address.pid, + add->details.add_address.addr_num, + add->details.add_address.addr_flags); + if ((asd->session == + make_session(add->details.add_address.session)) && + (0 == + GNUNET_HELLO_address_cmp(addr, + asd->address))) + done = GNUNET_YES; + GNUNET_free(addr); + } + if (GNUNET_NO == done) + return; + off++; + break; } - if (GNUNET_NO == done) - return; - off++; - break; - } - case CMD_AWAIT_DISCONNECT_SUGGESTION: - { - struct GNUNET_PeerIdentity pid; - struct AddressSuggestData *asd; - - make_peer (cmd->details.await_disconnect_suggestion.pid, - &pid); - asd = find_address_suggestion (&pid); - if (NULL == asd) - return; /* odd, no suggestion at all yet!? */ - if (GNUNET_YES == asd->active) - return; /* last suggestion was to activate, wait longer */ - /* last suggestion was to deactivate, condition satisfied! */ - off++; - break; - } - case CMD_REQUEST_CONNECTION_START: - { - struct GNUNET_PeerIdentity pid; - - make_peer (cmd->details.request_connection_start.pid, - &pid); - cmd->details.request_connection_start.csh - = GNUNET_ATS_connectivity_suggest (con_ats, - &pid, - 1); - off++; - break; - } - case CMD_REQUEST_CONNECTION_STOP: - { - struct Command *start; - - start = find_command (CMD_REQUEST_CONNECTION_START, - cmd->details.request_connection_stop.connect_label); - GNUNET_ATS_connectivity_suggest_cancel (start->details.request_connection_start.csh); - start->details.request_connection_start.csh = NULL; - off++; - break; - } - case CMD_AWAIT_ADDRESS_INFORMATION: - { - struct AddressInformationData *aid; - struct Command *add; - struct Command *update; - struct GNUNET_HELLO_Address *addr; - const struct GNUNET_ATS_Properties *cmp; - - add = find_command (CMD_ADD_ADDRESS, - cmd->details.await_address_information.add_label); - update = find_command (CMD_UPDATE_ADDRESS, - cmd->details.await_address_information.update_label); - addr = make_address (add->details.add_address.pid, - add->details.add_address.addr_num, - add->details.add_address.addr_flags); - aid = find_address_information (addr); - GNUNET_free (addr); - if (NULL == update) - cmp = &add->details.add_address.properties; - else - cmp = &update->details.update_address.properties; - if ( (NULL != aid) && - (cmp->delay.rel_value_us == aid->properties.delay.rel_value_us) && - (cmp->utilization_out == aid->properties.utilization_out) && - (cmp->utilization_in == aid->properties.utilization_in) && - (cmp->distance == aid->properties.distance) && - (cmp->scope == aid->properties.scope) ) + + case CMD_AWAIT_DISCONNECT_SUGGESTION: { + struct GNUNET_PeerIdentity pid; + struct AddressSuggestData *asd; + + make_peer(cmd->details.await_disconnect_suggestion.pid, + &pid); + asd = find_address_suggestion(&pid); + if (NULL == asd) + return; /* odd, no suggestion at all yet!? */ + if (GNUNET_YES == asd->active) + return; /* last suggestion was to activate, wait longer */ + /* last suggestion was to deactivate, condition satisfied! */ off++; break; } - return; - } - case CMD_UPDATE_ADDRESS: - { - struct Command *add; - - add = find_command (CMD_ADD_ADDRESS, - cmd->details.update_address.add_label); - GNUNET_assert (NULL != add->details.add_address.ar); - GNUNET_ATS_address_update (add->details.add_address.ar, - &cmd->details.update_address.properties); - off++; - break; - } - case CMD_ADD_SESSION: - { - struct Command *add; - struct GNUNET_ATS_Session *session; - - add = find_command (CMD_ADD_ADDRESS, - cmd->details.add_session.add_label); - session = make_session (cmd->details.add_session.session); - GNUNET_assert (NULL != add->details.add_address.ar); - GNUNET_ATS_address_add_session (add->details.add_address.ar, - session); - off++; - break; - } - case CMD_DEL_SESSION: - { - struct Command *add_address; - struct Command *add_session; - struct GNUNET_ATS_Session *session; - - add_session = find_command (CMD_ADD_SESSION, - cmd->details.del_session.add_session_label); - add_address = find_command (CMD_ADD_ADDRESS, - add_session->details.add_session.add_label); - GNUNET_assert (NULL != add_address->details.add_address.ar); - session = make_session (add_session->details.add_session.session); - GNUNET_ATS_address_del_session (add_address->details.add_address.ar, - session); - off++; - break; - } - case CMD_CHANGE_PREFERENCE: - { - struct GNUNET_PeerIdentity pid; - - make_peer (cmd->details.change_preference.pid, - &pid); - GNUNET_ATS_performance_change_preference (perf_ats, - &pid, - GNUNET_ATS_PREFERENCE_END); - off++; - break; - } - case CMD_PROVIDE_FEEDBACK: - { - struct GNUNET_PeerIdentity pid; - - make_peer (cmd->details.provide_feedback.pid, - &pid); - GNUNET_ATS_performance_give_feedback (perf_ats, + + case CMD_REQUEST_CONNECTION_START: + { + struct GNUNET_PeerIdentity pid; + + make_peer(cmd->details.request_connection_start.pid, + &pid); + cmd->details.request_connection_start.csh + = GNUNET_ATS_connectivity_suggest(con_ats, &pid, - cmd->details.provide_feedback.scope, - GNUNET_ATS_PREFERENCE_END); - off++; - break; - } - case CMD_LIST_ADDRESSES: - { - struct GNUNET_PeerIdentity pid; - - make_peer (cmd->details.list_addresses.pid, - &pid); - cmd->details.list_addresses.alh - = GNUNET_ATS_performance_list_addresses (perf_ats, + 1); + off++; + break; + } + + case CMD_REQUEST_CONNECTION_STOP: + { + struct Command *start; + + start = find_command(CMD_REQUEST_CONNECTION_START, + cmd->details.request_connection_stop.connect_label); + GNUNET_ATS_connectivity_suggest_cancel(start->details.request_connection_start.csh); + start->details.request_connection_start.csh = NULL; + off++; + break; + } + + case CMD_AWAIT_ADDRESS_INFORMATION: + { + struct AddressInformationData *aid; + struct Command *add; + struct Command *update; + struct GNUNET_HELLO_Address *addr; + const struct GNUNET_ATS_Properties *cmp; + + add = find_command(CMD_ADD_ADDRESS, + cmd->details.await_address_information.add_label); + update = find_command(CMD_UPDATE_ADDRESS, + cmd->details.await_address_information.update_label); + addr = make_address(add->details.add_address.pid, + add->details.add_address.addr_num, + add->details.add_address.addr_flags); + aid = find_address_information(addr); + GNUNET_free(addr); + if (NULL == update) + cmp = &add->details.add_address.properties; + else + cmp = &update->details.update_address.properties; + if ((NULL != aid) && + (cmp->delay.rel_value_us == aid->properties.delay.rel_value_us) && + (cmp->utilization_out == aid->properties.utilization_out) && + (cmp->utilization_in == aid->properties.utilization_in) && + (cmp->distance == aid->properties.distance) && + (cmp->scope == aid->properties.scope)) + { + off++; + break; + } + return; + } + + case CMD_UPDATE_ADDRESS: + { + struct Command *add; + + add = find_command(CMD_ADD_ADDRESS, + cmd->details.update_address.add_label); + GNUNET_assert(NULL != add->details.add_address.ar); + GNUNET_ATS_address_update(add->details.add_address.ar, + &cmd->details.update_address.properties); + off++; + break; + } + + case CMD_ADD_SESSION: + { + struct Command *add; + struct GNUNET_ATS_Session *session; + + add = find_command(CMD_ADD_ADDRESS, + cmd->details.add_session.add_label); + session = make_session(cmd->details.add_session.session); + GNUNET_assert(NULL != add->details.add_address.ar); + GNUNET_ATS_address_add_session(add->details.add_address.ar, + session); + off++; + break; + } + + case CMD_DEL_SESSION: + { + struct Command *add_address; + struct Command *add_session; + struct GNUNET_ATS_Session *session; + + add_session = find_command(CMD_ADD_SESSION, + cmd->details.del_session.add_session_label); + add_address = find_command(CMD_ADD_ADDRESS, + add_session->details.add_session.add_label); + GNUNET_assert(NULL != add_address->details.add_address.ar); + session = make_session(add_session->details.add_session.session); + GNUNET_ATS_address_del_session(add_address->details.add_address.ar, + session); + off++; + break; + } + + case CMD_CHANGE_PREFERENCE: + { + struct GNUNET_PeerIdentity pid; + + make_peer(cmd->details.change_preference.pid, + &pid); + GNUNET_ATS_performance_change_preference(perf_ats, &pid, - cmd->details.list_addresses.all, - &info_cb, - cmd); - return; - } - case CMD_RESERVE_BANDWIDTH: - { - struct GNUNET_PeerIdentity pid; - - make_peer (cmd->details.reserve_bandwidth.pid, - &pid); - cmd->details.reserve_bandwidth.rc - = GNUNET_ATS_reserve_bandwidth (perf_ats, - &pid, - cmd->details.reserve_bandwidth.amount, - &reservation_cb, - cmd); - return; - } - case CMD_SLEEP: - off++; - interpreter_task = GNUNET_SCHEDULER_add_delayed (cmd->details.sleep.delay, - &interpreter, - NULL); - return; - } /* end switch */ - } /* end while(1) */ + GNUNET_ATS_PREFERENCE_END); + off++; + break; + } + + case CMD_PROVIDE_FEEDBACK: + { + struct GNUNET_PeerIdentity pid; + + make_peer(cmd->details.provide_feedback.pid, + &pid); + GNUNET_ATS_performance_give_feedback(perf_ats, + &pid, + cmd->details.provide_feedback.scope, + GNUNET_ATS_PREFERENCE_END); + off++; + break; + } + + case CMD_LIST_ADDRESSES: + { + struct GNUNET_PeerIdentity pid; + + make_peer(cmd->details.list_addresses.pid, + &pid); + cmd->details.list_addresses.alh + = GNUNET_ATS_performance_list_addresses(perf_ats, + &pid, + cmd->details.list_addresses.all, + &info_cb, + cmd); + return; + } + + case CMD_RESERVE_BANDWIDTH: + { + struct GNUNET_PeerIdentity pid; + + make_peer(cmd->details.reserve_bandwidth.pid, + &pid); + cmd->details.reserve_bandwidth.rc + = GNUNET_ATS_reserve_bandwidth(perf_ats, + &pid, + cmd->details.reserve_bandwidth.amount, + &reservation_cb, + cmd); + return; + } + + case CMD_SLEEP: + off++; + interpreter_task = GNUNET_SCHEDULER_add_delayed(cmd->details.sleep.delay, + &interpreter, + NULL); + return; + } /* end switch */ + } /* end while(1) */ } @@ -882,59 +897,59 @@ interpreter (void *cls) * 0 to signal disconnect */ static void -address_suggest_cb (void *cls, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_ATS_Session *session, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) +address_suggest_cb(void *cls, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_ATS_Session *session, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in) { const char *asc_cls = cls; struct AddressSuggestData *asd; - GNUNET_break (0 == strcmp (asc_cls, "asc-closure")); + GNUNET_break(0 == strcmp(asc_cls, "asc-closure")); if (NULL == peer) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Connection to ATS died, likely a crash!\n"); - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Connection to ATS died, likely a crash!\n"); + GNUNET_SCHEDULER_shutdown(); #if 0 - /* This is what we should do if we wanted to continue past - the ATS crash. */ - GNUNET_CONTAINER_multipeermap_iterate (p2asd, - &free_asd, - NULL); - GNUNET_CONTAINER_multipeermap_iterate (p2aid, - &free_aid, - NULL); + /* This is what we should do if we wanted to continue past + the ATS crash. */ + GNUNET_CONTAINER_multipeermap_iterate(p2asd, + &free_asd, + NULL); + GNUNET_CONTAINER_multipeermap_iterate(p2aid, + &free_aid, + NULL); #endif - return; - } + return; + } - asd = find_address_suggestion (peer); + asd = find_address_suggestion(peer); if (NULL == asd) - { - asd = GNUNET_new (struct AddressSuggestData); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_put (p2asd, + { + asd = GNUNET_new(struct AddressSuggestData); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_put(p2asd, peer, asd, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - } - if ( (0 == ntohl (bandwidth_out.value__)) && - (0 == ntohl (bandwidth_in.value__)) ) + } + if ((0 == ntohl(bandwidth_out.value__)) && + (0 == ntohl(bandwidth_in.value__))) asd->active = GNUNET_NO; else asd->active = GNUNET_YES; asd->bandwidth_out = bandwidth_out; asd->bandwidth_in = bandwidth_in; asd->session = session; - GNUNET_free_non_null (asd->address); + GNUNET_free_non_null(asd->address); asd->address = NULL; if (NULL != address) - asd->address = GNUNET_HELLO_address_copy (address); + asd->address = GNUNET_HELLO_address_copy(address); if (NULL == interpreter_task) - run_interpreter (); + run_interpreter(); } @@ -952,44 +967,44 @@ address_suggest_cb (void *cls, * @param prop performance data for the address */ static void -address_information_cb (void *cls, - const struct GNUNET_HELLO_Address *address, - int address_active, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, - const struct GNUNET_ATS_Properties *prop) +address_information_cb(void *cls, + const struct GNUNET_HELLO_Address *address, + int address_active, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, + const struct GNUNET_ATS_Properties *prop) { const char *aic_cls = cls; struct AddressInformationData *aid; - GNUNET_break (0 == strcmp (aic_cls, "aic-closure")); + GNUNET_break(0 == strcmp(aic_cls, "aic-closure")); if (NULL == address) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Connection to ATS died, likely a crash!\n"); - GNUNET_CONTAINER_multipeermap_iterate (p2aid, - &free_aid, - NULL); - return; - } - - aid = find_address_information (address); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Connection to ATS died, likely a crash!\n"); + GNUNET_CONTAINER_multipeermap_iterate(p2aid, + &free_aid, + NULL); + return; + } + + aid = find_address_information(address); if (NULL == aid) - { - aid = GNUNET_new (struct AddressInformationData); - aid->address = GNUNET_HELLO_address_copy (address); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_put (p2aid, + { + aid = GNUNET_new(struct AddressInformationData); + aid->address = GNUNET_HELLO_address_copy(address); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_put(p2aid, &address->peer, aid, GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); - } + } aid->active = address_active; aid->bandwidth_out = bandwidth_out; aid->bandwidth_in = bandwidth_in; aid->properties = *prop; if (NULL == interpreter_task) - run_interpreter (); + run_interpreter(); } @@ -1001,44 +1016,44 @@ address_information_cb (void *cls, * @param peer handle to the peer */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - p2asd = GNUNET_CONTAINER_multipeermap_create (128, - GNUNET_NO); - p2aid = GNUNET_CONTAINER_multipeermap_create (128, - GNUNET_NO); - GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &end, - NULL); - - sched_ats = GNUNET_ATS_scheduling_init (cfg, - &address_suggest_cb, - "asc-closure"); + p2asd = GNUNET_CONTAINER_multipeermap_create(128, + GNUNET_NO); + p2aid = GNUNET_CONTAINER_multipeermap_create(128, + GNUNET_NO); + GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &end, + NULL); + + sched_ats = GNUNET_ATS_scheduling_init(cfg, + &address_suggest_cb, + "asc-closure"); if (NULL == sched_ats) - { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } - con_ats = GNUNET_ATS_connectivity_init (cfg); + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + con_ats = GNUNET_ATS_connectivity_init(cfg); if (NULL == con_ats) - { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } - perf_ats = GNUNET_ATS_performance_init (cfg, - &address_information_cb, - "aic-closure"); + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + perf_ats = GNUNET_ATS_performance_init(cfg, + &address_information_cb, + "aic-closure"); if (NULL == perf_ats) - { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } - run_interpreter (); + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + run_interpreter(); } @@ -1052,32 +1067,32 @@ run (void *cls, * @return 0 on success */ int -TEST_ATS_run (int argc, - char *argv[], - struct Command *cmds, - struct GNUNET_TIME_Relative timeout) +TEST_ATS_run(int argc, + char *argv[], + struct Command *cmds, + struct GNUNET_TIME_Relative timeout) { - char *test_filename = GNUNET_strdup (argv[0]); + char *test_filename = GNUNET_strdup(argv[0]); char *sep; char *config_file; char *underscore; test_commands = cmds; TIMEOUT = timeout; - if (NULL != (sep = strstr (test_filename, ".exe"))) + if (NULL != (sep = strstr(test_filename, ".exe"))) sep[0] = '\0'; - underscore = strrchr (test_filename, (int) '_'); - GNUNET_assert (NULL != underscore); - GNUNET_asprintf (&config_file, - "test_ats_api_%s.conf", - underscore + 1); + underscore = strrchr(test_filename, (int)'_'); + GNUNET_assert(NULL != underscore); + GNUNET_asprintf(&config_file, + "test_ats_api_%s.conf", + underscore + 1); ret = 2; - if (0 != GNUNET_TESTING_peer_run ("test-ats-api", - config_file, - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-ats-api", + config_file, + &run, NULL)) ret = 1; - GNUNET_free (test_filename); - GNUNET_free (config_file); + GNUNET_free(test_filename); + GNUNET_free(config_file); return ret; } diff --git a/src/ats/test_ats_lib.h b/src/ats/test_ats_lib.h index cc9f8ec73..db083d2d7 100644 --- a/src/ats/test_ats_lib.h +++ b/src/ats/test_ats_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/test_ats_lib.h * @brief test ATS library with a generic interpreter for running ATS tests @@ -33,8 +33,7 @@ /** * Commands for the interpreter. */ -enum CommandCode -{ +enum CommandCode { /** * End the test (passing). */ @@ -123,15 +122,13 @@ enum CommandCode * Wait for a bit. */ CMD_SLEEP - }; /** * Details for the #CMD_ADD_ADDRESS command. */ -struct CommandAddAddress -{ +struct CommandAddAddress { /** * Number of the peer (used to generate PID). */ @@ -172,8 +169,7 @@ struct CommandAddAddress /** * Details for the #CMD_DEL_ADDRESS command. */ -struct CommandDelAddress -{ +struct CommandDelAddress { /** * Label of the corresponding #CMD_ADD_ADDRESS that * we are now to remove. @@ -185,8 +181,7 @@ struct CommandDelAddress /** * Details for the #CMD_AWAIT_ADDRESS_SUGGESTION command. */ -struct CommandAwaitAddressSuggestion -{ +struct CommandAwaitAddressSuggestion { /** * For which peer do we expect a suggestion? */ @@ -198,28 +193,24 @@ struct CommandAwaitAddressSuggestion * use NULL for "any" available address. */ const char *add_label; - }; /** * Details for the #CMD_AWAIT_DISCONNECT_SUGGESTION command. */ -struct CommandAwaitDisconnectSuggestion -{ +struct CommandAwaitDisconnectSuggestion { /** * For which peer do we expect the disconnect? */ unsigned int pid; - }; /** * Details for the #CMD_REQUEST_CONNECTION_START command. */ -struct CommandRequestConnectionStart -{ +struct CommandRequestConnectionStart { /** * Identity of the peer we would like to connect to. */ @@ -236,8 +227,7 @@ struct CommandRequestConnectionStart /** * Details for the #CMD_REQUEST_CONNECTION_STOP command. */ -struct CommandRequestConnectionStop -{ +struct CommandRequestConnectionStop { /** * Label of the corresponding #CMD_REQUEST_CONNECTION_START that * we are now stopping. @@ -249,8 +239,7 @@ struct CommandRequestConnectionStop /** * Details for the #CMD_AWAIT_ADDRESS_INFORMATION command. */ -struct CommandAwaitAddressInformation -{ +struct CommandAwaitAddressInformation { /** * For which address do we expect information? * The address is identified by the respective @@ -264,15 +253,13 @@ struct CommandAwaitAddressInformation * the properties from the @e add_label. */ const char *update_label; - }; /** * Details for the #CMD_UPDATE_ADDRESS command. */ -struct CommandUpdateAddress -{ +struct CommandUpdateAddress { /** * Label of the addresses's add operation. */ @@ -282,16 +269,14 @@ struct CommandUpdateAddress * Performance properties to supply. */ struct GNUNET_ATS_Properties properties; - }; /** * Details for the #CMD_ADD_SESSION command. */ -struct CommandAddSession -{ - /** +struct CommandAddSession { + /** * Label of the addresses's add operation. */ const char *add_label; @@ -300,43 +285,37 @@ struct CommandAddSession * Session to supply. */ unsigned int session; - }; /** * Details for the #CMD_DEL_SESSION command. */ -struct CommandDelSession -{ - /** +struct CommandDelSession { + /** * Label of the addresses's add operation. */ const char *add_session_label; - }; /** * Details for the #CMD_CHANGE_PREFERENCE command. */ -struct CommandChangePreference -{ +struct CommandChangePreference { /** * Identity of the peer we have a preference change towards. */ unsigned int pid; /* FIXME: preference details! */ - }; /** * Details for the #CMD_PROVIDE_FEEDBACK command. */ -struct CommandProvideFeedback -{ +struct CommandProvideFeedback { /** * Identity of the peer we have a feedback for. */ @@ -354,8 +333,7 @@ struct CommandProvideFeedback /** * Details for the #CMD_LIST_ADDRESSES command. */ -struct CommandListAddresses -{ +struct CommandListAddresses { /** * Identity of the peer we want a list for. */ @@ -403,15 +381,13 @@ struct CommandListAddresses * #GNUNET_ATS_performance_list_addresses(). */ struct GNUNET_ATS_AddressListHandle *alh; - }; /** * Details for the #CMD_RESERVE_BANDWIDTH command. */ -struct CommandReserveBandwidth -{ +struct CommandReserveBandwidth { /** * For which peer do we reserve bandwidth? */ @@ -435,15 +411,13 @@ struct CommandReserveBandwidth * #GNUNET_ATS_reserve_bandwidth(). */ struct GNUNET_ATS_ReservationContext *rc; - }; /** * Details for the #CMD_SLEEP command. */ -struct CommandSleep -{ +struct CommandSleep { /** * How long should we wait before running the next command? */ @@ -454,8 +428,7 @@ struct CommandSleep /** * A command for the test case interpreter. */ -struct Command -{ +struct Command { /** * Command code to run. */ @@ -470,7 +443,6 @@ struct Command * Additional arguments to commands, if any. */ union { - struct CommandAddAddress add_address; struct CommandDelAddress del_address; @@ -500,9 +472,7 @@ struct Command struct CommandReserveBandwidth reserve_bandwidth; struct CommandSleep sleep; - } details; - }; @@ -516,9 +486,9 @@ struct Command * @return 0 on success */ int -TEST_ATS_run (int argc, - char *argv[], - struct Command *cmds, - struct GNUNET_TIME_Relative timeout); +TEST_ATS_run(int argc, + char *argv[], + struct Command *cmds, + struct GNUNET_TIME_Relative timeout); #endif diff --git a/src/ats/test_ats_reservation_api.c b/src/ats/test_ats_reservation_api.c index e7791343e..f6b0573e1 100644 --- a/src/ats/test_ats_reservation_api.c +++ b/src/ats/test_ats_reservation_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file ats/test_ats_reservation_api.c * @brief test ATS bandwidth reservation API @@ -28,7 +28,7 @@ /** * Global timeout for the testcase. */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15) /** * Definition of the test as a sequence of commands. @@ -146,13 +146,13 @@ static struct Command test_commands[] = { int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { - return TEST_ATS_run (argc, - argv, - test_commands, - TIMEOUT); + return TEST_ATS_run(argc, + argv, + test_commands, + TIMEOUT); } diff --git a/src/auction/auction.h b/src/auction/auction.h index 74da53fdb..8324e1cb1 100644 --- a/src/auction/auction.h +++ b/src/auction/auction.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Markus Teich @@ -34,8 +34,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Auction creation request sent from the client to the service */ -struct GNUNET_AUCTION_ClientCreateMessage -{ +struct GNUNET_AUCTION_ClientCreateMessage { /** * Type: GNUNET_MESSAGE_TYPE_AUCTION_CLIENT_CREATE */ diff --git a/src/auction/gnunet-auction-create.c b/src/auction/gnunet-auction-create.c index 3ee4d3554..42ab14aca 100644 --- a/src/auction/gnunet-auction-create.c +++ b/src/auction/gnunet-auction-create.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @file auction/gnunet-auction-create.c @@ -54,94 +54,94 @@ static int interactive; /** keep running in foreground */ * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - unsigned int i; - double cur, prev = DBL_MAX; - json_t *pmap; - json_t *parray; - json_t *pnode; - json_error_t jerr; - - /* cmdline parsing */ - if (GNUNET_TIME_UNIT_ZERO.rel_value_us == dstart.rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "required argument --regtime missing or invalid (zero)\n"); - goto fail; - } - if (GNUNET_TIME_UNIT_ZERO.rel_value_us == dround.rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "required argument --roundtime missing or invalid (zero)\n"); - goto fail; - } - if (!fndesc) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "required argument --description missing\n"); - goto fail; - } - if (!fnprices) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "required argument --pricemap missing\n"); - goto fail; - } - - /* parse and check pricemap validity */ - if (!(pmap = json_load_file (fnprices, JSON_DECODE_INT_AS_REAL, &jerr))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "parsing pricemap json at %d:%d: %s\n", - jerr.line, jerr.column, jerr.text); - goto fail; - } - if (-1 == json_unpack_ex (pmap, &jerr, JSON_VALIDATE_ONLY, - "{s:s, s:[]}", "currency", "prices")) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "validating pricemap: %s\n", jerr.text); - goto fail; - } - if (!(parray = json_object_get (pmap, "prices")) || !json_is_array (parray)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "could not get `prices` array node from pricemap\n"); - goto fail; - } - if (0 == json_array_size (parray)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "empty pricemap array\n"); - goto fail; - } - json_array_foreach (parray, i, pnode) - { - if (-1 == json_unpack_ex (pnode, &jerr, 0, "F", &cur)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "validating pricearray index %d: %s\n", i, jerr.text); - goto fail; - } - if (prev <= cur) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "validating pricearray index %d: " - "prices must be strictly monotonically decreasing\n", - i); - goto fail; - } - prev = cur; - } - - return; + unsigned int i; + double cur, prev = DBL_MAX; + json_t *pmap; + json_t *parray; + json_t *pnode; + json_error_t jerr; + + /* cmdline parsing */ + if (GNUNET_TIME_UNIT_ZERO.rel_value_us == dstart.rel_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "required argument --regtime missing or invalid (zero)\n"); + goto fail; + } + if (GNUNET_TIME_UNIT_ZERO.rel_value_us == dround.rel_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "required argument --roundtime missing or invalid (zero)\n"); + goto fail; + } + if (!fndesc) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "required argument --description missing\n"); + goto fail; + } + if (!fnprices) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "required argument --pricemap missing\n"); + goto fail; + } + + /* parse and check pricemap validity */ + if (!(pmap = json_load_file(fnprices, JSON_DECODE_INT_AS_REAL, &jerr))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "parsing pricemap json at %d:%d: %s\n", + jerr.line, jerr.column, jerr.text); + goto fail; + } + if (-1 == json_unpack_ex(pmap, &jerr, JSON_VALIDATE_ONLY, + "{s:s, s:[]}", "currency", "prices")) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "validating pricemap: %s\n", jerr.text); + goto fail; + } + if (!(parray = json_object_get(pmap, "prices")) || !json_is_array(parray)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "could not get `prices` array node from pricemap\n"); + goto fail; + } + if (0 == json_array_size(parray)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "empty pricemap array\n"); + goto fail; + } + json_array_foreach(parray, i, pnode) + { + if (-1 == json_unpack_ex(pnode, &jerr, 0, "F", &cur)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "validating pricearray index %d: %s\n", i, jerr.text); + goto fail; + } + if (prev <= cur) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "validating pricearray index %d: " + "prices must be strictly monotonically decreasing\n", + i); + goto fail; + } + prev = cur; + } + + return; fail: - ret = 1; - return; + ret = 1; + return; } @@ -153,64 +153,64 @@ fail: * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { - struct GNUNET_GETOPT_CommandLineOption options[] = { - - GNUNET_GETOPT_option_filename ('d', - "description", - "FILE", - gettext_noop ("description of the item to be sold"), - &fndesc), - - GNUNET_GETOPT_option_filename ('p', - "pricemap", - "FILE", - gettext_noop ("mapping of possible prices"), - &fnprices), - - GNUNET_GETOPT_option_relative_time ('r', - "roundtime", - "DURATION", - gettext_noop ("max duration per round"), - &dround), - - GNUNET_GETOPT_option_relative_time ('s', - "regtime", - "DURATION", - gettext_noop ("duration until auction starts"), - &dstart), - GNUNET_GETOPT_option_uint ('m', - "m", - "NUMBER", - gettext_noop ("number of items to sell\n" - "0 for first price auction\n" - ">0 for vickrey/M+1st price auction"), - &m), - - GNUNET_GETOPT_option_flag ('u', - "public", - gettext_noop ("public auction outcome"), - &outcome), - - GNUNET_GETOPT_option_flag ('i', - "interactive", - gettext_noop ("keep running in foreground until auction completes"), - &interactive), - - GNUNET_GETOPT_OPTION_END - }; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) - return 2; - - ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, - "gnunet-auction-create", - gettext_noop ("create a new auction and " - "start listening for bidders"), - options, - &run, - NULL)) ? ret : 1; - GNUNET_free ((void*) argv); - return ret; + struct GNUNET_GETOPT_CommandLineOption options[] = { + GNUNET_GETOPT_option_filename('d', + "description", + "FILE", + gettext_noop("description of the item to be sold"), + &fndesc), + + GNUNET_GETOPT_option_filename('p', + "pricemap", + "FILE", + gettext_noop("mapping of possible prices"), + &fnprices), + + GNUNET_GETOPT_option_relative_time('r', + "roundtime", + "DURATION", + gettext_noop("max duration per round"), + &dround), + + GNUNET_GETOPT_option_relative_time('s', + "regtime", + "DURATION", + gettext_noop("duration until auction starts"), + &dstart), + GNUNET_GETOPT_option_uint('m', + "m", + "NUMBER", + gettext_noop("number of items to sell\n" + "0 for first price auction\n" + ">0 for vickrey/M+1st price auction"), + &m), + + GNUNET_GETOPT_option_flag('u', + "public", + gettext_noop("public auction outcome"), + &outcome), + + GNUNET_GETOPT_option_flag('i', + "interactive", + gettext_noop("keep running in foreground until auction completes"), + &interactive), + + GNUNET_GETOPT_OPTION_END + }; + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) + return 2; + + ret = (GNUNET_OK == + GNUNET_PROGRAM_run(argc, argv, + "gnunet-auction-create", + gettext_noop("create a new auction and " + "start listening for bidders"), + options, + &run, + NULL)) ? ret : 1; + GNUNET_free((void*)argv); + return ret; } diff --git a/src/auction/gnunet-auction-info.c b/src/auction/gnunet-auction-info.c index 58639a57c..ef46ca212 100644 --- a/src/auction/gnunet-auction-info.c +++ b/src/auction/gnunet-auction-info.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file auction/gnunet-auction.c @@ -42,10 +42,10 @@ static int ret; * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { /* main code here */ } @@ -59,25 +59,26 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { static const struct GNUNET_GETOPT_CommandLineOption options[] = { /* FIMXE: add options here */ GNUNET_GETOPT_OPTION_END }; + if (GNUNET_OK != - GNUNET_STRINGS_get_utf8_args (argc, argv, - &argc, &argv)) + GNUNET_STRINGS_get_utf8_args(argc, argv, + &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, - "gnunet-auction", - gettext_noop ("help text"), - options, - &run, - NULL)) ? ret : 1; - GNUNET_free ((void*) argv); + GNUNET_PROGRAM_run(argc, argv, + "gnunet-auction", + gettext_noop("help text"), + options, + &run, + NULL)) ? ret : 1; + GNUNET_free((void*)argv); return ret; } diff --git a/src/auction/gnunet-auction-join.c b/src/auction/gnunet-auction-join.c index 58639a57c..ef46ca212 100644 --- a/src/auction/gnunet-auction-join.c +++ b/src/auction/gnunet-auction-join.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file auction/gnunet-auction.c @@ -42,10 +42,10 @@ static int ret; * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { /* main code here */ } @@ -59,25 +59,26 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { static const struct GNUNET_GETOPT_CommandLineOption options[] = { /* FIMXE: add options here */ GNUNET_GETOPT_OPTION_END }; + if (GNUNET_OK != - GNUNET_STRINGS_get_utf8_args (argc, argv, - &argc, &argv)) + GNUNET_STRINGS_get_utf8_args(argc, argv, + &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, - "gnunet-auction", - gettext_noop ("help text"), - options, - &run, - NULL)) ? ret : 1; - GNUNET_free ((void*) argv); + GNUNET_PROGRAM_run(argc, argv, + "gnunet-auction", + gettext_noop("help text"), + options, + &run, + NULL)) ? ret : 1; + GNUNET_free((void*)argv); return ret; } diff --git a/src/auction/gnunet-service-auction.c b/src/auction/gnunet-service-auction.c index a5518b0f3..ed1be20d8 100644 --- a/src/auction/gnunet-service-auction.c +++ b/src/auction/gnunet-service-auction.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @file auction/gnunet-service-auction.c @@ -36,10 +36,10 @@ * @return #GNUNET_OK (always) */ static int -check_create (void *cls, const struct GNUNET_AUCTION_ClientCreateMessage *msg) +check_create(void *cls, const struct GNUNET_AUCTION_ClientCreateMessage *msg) { - /* always well-formed due to arbitrary length description */ - return GNUNET_OK; + /* always well-formed due to arbitrary length description */ + return GNUNET_OK; } @@ -50,26 +50,26 @@ check_create (void *cls, const struct GNUNET_AUCTION_ClientCreateMessage *msg) * @param msg the actual message received */ static void -handle_create (void *cls, const struct GNUNET_AUCTION_ClientCreateMessage *msg) +handle_create(void *cls, const struct GNUNET_AUCTION_ClientCreateMessage *msg) { - struct GNUNET_SERVICE_Client *client = cls; + struct GNUNET_SERVICE_Client *client = cls; // struct GNUNET_MQ_Handle *mq; // struct GNUNET_MQ_Envelope *env; // struct GNUNET_AUCTION_blabla em; - uint16_t size; + uint16_t size; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received CREATE message from client\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received CREATE message from client\n"); - size = ntohs (msg->header.size); + size = ntohs(msg->header.size); - /**TODO: create auction and return auction object */ + /**TODO: create auction and return auction object */ // mq = GNUNET_SERVICE_client_get_mq (client); // setup_info_message (&em); // env = GNUNET_MQ_msg_copy (&em.header); // GNUNET_MQ_send (mq, env); - GNUNET_SERVICE_client_continue (client); + GNUNET_SERVICE_client_continue(client); } @@ -79,9 +79,9 @@ handle_create (void *cls, const struct GNUNET_AUCTION_ClientCreateMessage *msg) * @param cls unused */ static void -cleanup_task (void *cls) +cleanup_task(void *cls) { - /* FIXME: do clean up here */ + /* FIXME: do clean up here */ } @@ -94,11 +94,11 @@ cleanup_task (void *cls) * @return @a c */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + struct GNUNET_MQ_Handle *mq) { - return c; + return c; } @@ -110,11 +110,11 @@ client_connect_cb (void *cls, * @param internal_cls should be equal to @a c */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - void *internal_cls) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + void *internal_cls) { - GNUNET_assert (c == internal_cls); + GNUNET_assert(c == internal_cls); } @@ -126,12 +126,12 @@ client_disconnect_cb (void *cls, * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_SERVICE_Handle *service) { - /* FIXME: do setup here */ - GNUNET_SCHEDULER_add_shutdown (&cleanup_task, NULL); + /* FIXME: do setup here */ + GNUNET_SCHEDULER_add_shutdown(&cleanup_task, NULL); } @@ -139,17 +139,17 @@ run (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("auction", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_var_size (create, + ("auction", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_var_size(create, GNUNET_MESSAGE_TYPE_AUCTION_CLIENT_CREATE, struct GNUNET_AUCTION_ClientCreateMessage, NULL), - GNUNET_MQ_handler_end ()) + GNUNET_MQ_handler_end()) /* end of gnunet-service-auction.c */ diff --git a/src/auction/test_auction_api.c b/src/auction/test_auction_api.c index 56b2a8192..39a002a5f 100644 --- a/src/auction/test_auction_api.c +++ b/src/auction/test_auction_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file auction/test_auction_api.c * @brief testcase for auction.c @@ -24,17 +24,17 @@ #include "platform.h" static int -check () +check() { return 0; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { int ret; - ret = check (); + ret = check(); return ret; } diff --git a/src/block/bg_bf.c b/src/block/bg_bf.c index 20aa59bbc..9814a28ec 100644 --- a/src/block/bg_bf.c +++ b/src/block/bg_bf.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file block/bg_bf.c * @brief implementation of a block group using a Bloom filter @@ -32,8 +32,7 @@ /** * Internal data structure for a block group. */ -struct BfGroupInternals -{ +struct BfGroupInternals { /** * A Bloom filter to weed out duplicate replies probabilistically. */ @@ -48,7 +47,6 @@ struct BfGroupInternals * Size of @a bf. */ uint32_t bf_size; - }; @@ -63,24 +61,24 @@ struct BfGroupInternals * supported, #GNUNET_SYSERR on error */ static int -bf_group_serialize_cb (struct GNUNET_BLOCK_Group *bg, - uint32_t *nonce, - void **raw_data, - size_t *raw_data_size) +bf_group_serialize_cb(struct GNUNET_BLOCK_Group *bg, + uint32_t *nonce, + void **raw_data, + size_t *raw_data_size) { struct BfGroupInternals *gi = bg->internal_cls; char *raw; - raw = GNUNET_malloc (gi->bf_size); + raw = GNUNET_malloc(gi->bf_size); if (GNUNET_OK != - GNUNET_CONTAINER_bloomfilter_get_raw_data (gi->bf, - raw, - gi->bf_size)) - { - GNUNET_free (raw); - GNUNET_break (0); - return GNUNET_SYSERR; - } + GNUNET_CONTAINER_bloomfilter_get_raw_data(gi->bf, + raw, + gi->bf_size)) + { + GNUNET_free(raw); + GNUNET_break(0); + return GNUNET_SYSERR; + } *nonce = gi->bf_mutator; *raw_data = raw; *raw_data_size = gi->bf_size; @@ -97,22 +95,22 @@ bf_group_serialize_cb (struct GNUNET_BLOCK_Group *bg, * @param seen_results_count number of entries in @a seen_results */ static void -bf_group_mark_seen_cb (struct GNUNET_BLOCK_Group *bg, - const struct GNUNET_HashCode *seen_results, - unsigned int seen_results_count) +bf_group_mark_seen_cb(struct GNUNET_BLOCK_Group *bg, + const struct GNUNET_HashCode *seen_results, + unsigned int seen_results_count) { struct BfGroupInternals *gi = bg->internal_cls; - for (unsigned int i=0;ibf_mutator, - &mhash); - GNUNET_CONTAINER_bloomfilter_add (gi->bf, - &mhash); - } + GNUNET_BLOCK_mingle_hash(&seen_results[i], + gi->bf_mutator, + &mhash); + GNUNET_CONTAINER_bloomfilter_add(gi->bf, + &mhash); + } } @@ -126,8 +124,8 @@ bf_group_mark_seen_cb (struct GNUNET_BLOCK_Group *bg, * we failed. */ static int -bf_group_merge_cb (struct GNUNET_BLOCK_Group *bg1, - const struct GNUNET_BLOCK_Group *bg2) +bf_group_merge_cb(struct GNUNET_BLOCK_Group *bg1, + const struct GNUNET_BLOCK_Group *bg2) { struct BfGroupInternals *gi1 = bg1->internal_cls; struct BfGroupInternals *gi2 = bg2->internal_cls; @@ -136,8 +134,8 @@ bf_group_merge_cb (struct GNUNET_BLOCK_Group *bg1, return GNUNET_NO; if (gi1->bf_size != gi2->bf_size) return GNUNET_NO; - GNUNET_CONTAINER_bloomfilter_or2 (gi1->bf, - gi2->bf); + GNUNET_CONTAINER_bloomfilter_or2(gi1->bf, + gi2->bf); return GNUNET_OK; } @@ -148,13 +146,13 @@ bf_group_merge_cb (struct GNUNET_BLOCK_Group *bg1, * @param bg group to destroy, NULL is allowed */ static void -bf_group_destroy_cb (struct GNUNET_BLOCK_Group *bg) +bf_group_destroy_cb(struct GNUNET_BLOCK_Group *bg) { struct BfGroupInternals *gi = bg->internal_cls; - GNUNET_CONTAINER_bloomfilter_free (gi->bf); - GNUNET_free (gi); - GNUNET_free (bg); + GNUNET_CONTAINER_bloomfilter_free(gi->bf); + GNUNET_free(gi); + GNUNET_free(bg); } @@ -172,24 +170,24 @@ bf_group_destroy_cb (struct GNUNET_BLOCK_Group *bg) * by this @a type of block (this is not an error) */ struct GNUNET_BLOCK_Group * -GNUNET_BLOCK_GROUP_bf_create (void *cls, - size_t bf_size, - unsigned int bf_k, - enum GNUNET_BLOCK_Type type, - uint32_t nonce, - const void *raw_data, - size_t raw_data_size) +GNUNET_BLOCK_GROUP_bf_create(void *cls, + size_t bf_size, + unsigned int bf_k, + enum GNUNET_BLOCK_Type type, + uint32_t nonce, + const void *raw_data, + size_t raw_data_size) { struct BfGroupInternals *gi; struct GNUNET_BLOCK_Group *bg; - gi = GNUNET_new (struct BfGroupInternals); - gi->bf = GNUNET_CONTAINER_bloomfilter_init ((bf_size != raw_data_size) ? NULL : raw_data, - bf_size, - bf_k); + gi = GNUNET_new(struct BfGroupInternals); + gi->bf = GNUNET_CONTAINER_bloomfilter_init((bf_size != raw_data_size) ? NULL : raw_data, + bf_size, + bf_k); gi->bf_mutator = nonce; gi->bf_size = bf_size; - bg = GNUNET_new (struct GNUNET_BLOCK_Group); + bg = GNUNET_new(struct GNUNET_BLOCK_Group); bg->type = type; bg->serialize_cb = &bf_group_serialize_cb; bg->mark_seen_cb = &bf_group_mark_seen_cb; @@ -211,8 +209,8 @@ GNUNET_BLOCK_GROUP_bf_create (void *cls, * #GNUNET_NO if @a hc was definitively not in @bg (but now is) */ int -GNUNET_BLOCK_GROUP_bf_test_and_set (struct GNUNET_BLOCK_Group *bg, - const struct GNUNET_HashCode *hc) +GNUNET_BLOCK_GROUP_bf_test_and_set(struct GNUNET_BLOCK_Group *bg, + const struct GNUNET_HashCode *hc) { struct BfGroupInternals *gi; struct GNUNET_HashCode mhash; @@ -220,15 +218,15 @@ GNUNET_BLOCK_GROUP_bf_test_and_set (struct GNUNET_BLOCK_Group *bg, if (NULL == bg) return GNUNET_NO; gi = bg->internal_cls; - GNUNET_BLOCK_mingle_hash (hc, - gi->bf_mutator, - &mhash); + GNUNET_BLOCK_mingle_hash(hc, + gi->bf_mutator, + &mhash); if (GNUNET_YES == - GNUNET_CONTAINER_bloomfilter_test (gi->bf, - &mhash)) + GNUNET_CONTAINER_bloomfilter_test(gi->bf, + &mhash)) return GNUNET_YES; - GNUNET_CONTAINER_bloomfilter_add (gi->bf, - &mhash); + GNUNET_CONTAINER_bloomfilter_add(gi->bf, + &mhash); return GNUNET_NO; } @@ -247,8 +245,8 @@ GNUNET_BLOCK_GROUP_bf_test_and_set (struct GNUNET_BLOCK_Group *bg, * @return must be a power of two and smaller or equal to 2^15. */ size_t -GNUNET_BLOCK_GROUP_compute_bloomfilter_size (unsigned int entry_count, - unsigned int k) +GNUNET_BLOCK_GROUP_compute_bloomfilter_size(unsigned int entry_count, + unsigned int k) { size_t size; unsigned int ideal = (entry_count * k) / 4; diff --git a/src/block/block.c b/src/block/block.c index ecc98f88d..78e9bc2dd 100644 --- a/src/block/block.c +++ b/src/block/block.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file block/block.c @@ -34,8 +34,7 @@ /** * Handle for a plugin. */ -struct Plugin -{ +struct Plugin { /** * Name of the shared library. */ @@ -51,8 +50,7 @@ struct Plugin /** * Handle to an initialized block library. */ -struct GNUNET_BLOCK_Context -{ +struct GNUNET_BLOCK_Context { /** * Array of our plugins. */ @@ -78,18 +76,18 @@ struct GNUNET_BLOCK_Context * @param hc where to store the result. */ void -GNUNET_BLOCK_mingle_hash (const struct GNUNET_HashCode *in, - uint32_t mingle_number, - struct GNUNET_HashCode *hc) +GNUNET_BLOCK_mingle_hash(const struct GNUNET_HashCode *in, + uint32_t mingle_number, + struct GNUNET_HashCode *hc) { struct GNUNET_HashCode m; - GNUNET_CRYPTO_hash (&mingle_number, - sizeof (uint32_t), - &m); - GNUNET_CRYPTO_hash_xor (&m, - in, - hc); + GNUNET_CRYPTO_hash(&mingle_number, + sizeof(uint32_t), + &m); + GNUNET_CRYPTO_hash_xor(&m, + in, + hc); } @@ -101,23 +99,23 @@ GNUNET_BLOCK_mingle_hash (const struct GNUNET_HashCode *in, * @param lib_ret the plugin API */ static void -add_plugin (void *cls, - const char *library_name, - void *lib_ret) +add_plugin(void *cls, + const char *library_name, + void *lib_ret) { struct GNUNET_BLOCK_Context *ctx = cls; struct GNUNET_BLOCK_PluginFunctions *api = lib_ret; struct Plugin *plugin; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Loading block plugin `%s'\n", - library_name); - plugin = GNUNET_new (struct Plugin); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Loading block plugin `%s'\n", + library_name); + plugin = GNUNET_new(struct Plugin); plugin->api = api; - plugin->library_name = GNUNET_strdup (library_name); - GNUNET_array_append (ctx->plugins, - ctx->num_plugins, - plugin); + plugin->library_name = GNUNET_strdup(library_name); + GNUNET_array_append(ctx->plugins, + ctx->num_plugins, + plugin); } @@ -129,16 +127,16 @@ add_plugin (void *cls, * @return NULL on error */ struct GNUNET_BLOCK_Context * -GNUNET_BLOCK_context_create (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_BLOCK_context_create(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_BLOCK_Context *ctx; - ctx = GNUNET_new (struct GNUNET_BLOCK_Context); + ctx = GNUNET_new(struct GNUNET_BLOCK_Context); ctx->cfg = cfg; - GNUNET_PLUGIN_load_all ("libgnunet_plugin_block_", - (void *) cfg, - &add_plugin, - ctx); + GNUNET_PLUGIN_load_all("libgnunet_plugin_block_", + (void *)cfg, + &add_plugin, + ctx); return ctx; } @@ -149,21 +147,21 @@ GNUNET_BLOCK_context_create (const struct GNUNET_CONFIGURATION_Handle *cfg) * @param ctx context to destroy */ void -GNUNET_BLOCK_context_destroy (struct GNUNET_BLOCK_Context *ctx) +GNUNET_BLOCK_context_destroy(struct GNUNET_BLOCK_Context *ctx) { struct Plugin *plugin; for (unsigned int i = 0; i < ctx->num_plugins; i++) - { - plugin = ctx->plugins[i]; - GNUNET_break (NULL == - GNUNET_PLUGIN_unload (plugin->library_name, + { + plugin = ctx->plugins[i]; + GNUNET_break(NULL == + GNUNET_PLUGIN_unload(plugin->library_name, plugin->api)); - GNUNET_free (plugin->library_name); - GNUNET_free (plugin); - } - GNUNET_free (ctx->plugins); - GNUNET_free (ctx); + GNUNET_free(plugin->library_name); + GNUNET_free(plugin); + } + GNUNET_free(ctx->plugins); + GNUNET_free(ctx); } @@ -178,10 +176,10 @@ GNUNET_BLOCK_context_destroy (struct GNUNET_BLOCK_Context *ctx) * supported, #GNUNET_SYSERR on error */ int -GNUNET_BLOCK_group_serialize (struct GNUNET_BLOCK_Group *bg, - uint32_t *nonce, - void **raw_data, - size_t *raw_data_size) +GNUNET_BLOCK_group_serialize(struct GNUNET_BLOCK_Group *bg, + uint32_t *nonce, + void **raw_data, + size_t *raw_data_size) { *nonce = 0; *raw_data = NULL; @@ -190,10 +188,10 @@ GNUNET_BLOCK_group_serialize (struct GNUNET_BLOCK_Group *bg, return GNUNET_NO; if (NULL == bg->serialize_cb) return GNUNET_NO; - return bg->serialize_cb (bg, - nonce, - raw_data, - raw_data_size); + return bg->serialize_cb(bg, + nonce, + raw_data, + raw_data_size); } @@ -203,11 +201,11 @@ GNUNET_BLOCK_group_serialize (struct GNUNET_BLOCK_Group *bg, * @param bg group to destroy, NULL is allowed */ void -GNUNET_BLOCK_group_destroy (struct GNUNET_BLOCK_Group *bg) +GNUNET_BLOCK_group_destroy(struct GNUNET_BLOCK_Group *bg) { if (NULL == bg) return; - bg->destroy_cb (bg); + bg->destroy_cb(bg); } @@ -224,24 +222,24 @@ GNUNET_BLOCK_group_destroy (struct GNUNET_BLOCK_Group *bg) * #GNUNET_SYSERR if merging is not supported */ int -GNUNET_BLOCK_group_merge (struct GNUNET_BLOCK_Group *bg1, - struct GNUNET_BLOCK_Group *bg2) +GNUNET_BLOCK_group_merge(struct GNUNET_BLOCK_Group *bg1, + struct GNUNET_BLOCK_Group *bg2) { int ret; if (NULL == bg2) return GNUNET_OK; if (NULL == bg1) - { - bg2->destroy_cb (bg2); - return GNUNET_OK; - } + { + bg2->destroy_cb(bg2); + return GNUNET_OK; + } if (NULL == bg1->merge_cb) return GNUNET_SYSERR; - GNUNET_assert (bg1->merge_cb == bg1->merge_cb); - ret = bg1->merge_cb (bg1, - bg2); - bg2->destroy_cb (bg2); + GNUNET_assert(bg1->merge_cb == bg1->merge_cb); + ret = bg1->merge_cb(bg1, + bg2); + bg2->destroy_cb(bg2); return ret; } @@ -254,23 +252,23 @@ GNUNET_BLOCK_group_merge (struct GNUNET_BLOCK_Group *bg1, * @return NULL if no matching plugin exists */ static struct GNUNET_BLOCK_PluginFunctions * -find_plugin (struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type) +find_plugin(struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type) { struct Plugin *plugin; unsigned int j; for (unsigned i = 0; i < ctx->num_plugins; i++) - { - plugin = ctx->plugins[i]; - j = 0; - while (0 != (plugin->api->types[j])) { - if (type == plugin->api->types[j]) - return plugin->api; - j++; + plugin = ctx->plugins[i]; + j = 0; + while (0 != (plugin->api->types[j])) + { + if (type == plugin->api->types[j]) + return plugin->api; + j++; + } } - } return NULL; } @@ -287,32 +285,32 @@ find_plugin (struct GNUNET_BLOCK_Context *ctx, * by this @a type of block (this is not an error) */ struct GNUNET_BLOCK_Group * -GNUNET_BLOCK_group_create (struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - uint32_t nonce, - const void *raw_data, - size_t raw_data_size, - ...) +GNUNET_BLOCK_group_create(struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + uint32_t nonce, + const void *raw_data, + size_t raw_data_size, + ...) { struct GNUNET_BLOCK_PluginFunctions *plugin; struct GNUNET_BLOCK_Group *bg; va_list ap; - plugin = find_plugin (ctx, - type); + plugin = find_plugin(ctx, + type); if (NULL == plugin) return NULL; if (NULL == plugin->create_group) return NULL; - va_start (ap, - raw_data_size); - bg = plugin->create_group (plugin->cls, - type, - nonce, - raw_data, - raw_data_size, - ap); - va_end (ap); + va_start(ap, + raw_data_size); + bg = plugin->create_group(plugin->cls, + type, + nonce, + raw_data, + raw_data_size, + ap); + va_end(ap); return bg; } @@ -336,31 +334,31 @@ GNUNET_BLOCK_group_create (struct GNUNET_BLOCK_Context *ctx, * @return characterization of result */ enum GNUNET_BLOCK_EvaluationResult -GNUNET_BLOCK_evaluate (struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *group, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode *query, - const void *xquery, - size_t xquery_size, - const void *reply_block, - size_t reply_block_size) +GNUNET_BLOCK_evaluate(struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *group, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode *query, + const void *xquery, + size_t xquery_size, + const void *reply_block, + size_t reply_block_size) { - struct GNUNET_BLOCK_PluginFunctions *plugin = find_plugin (ctx, - type); + struct GNUNET_BLOCK_PluginFunctions *plugin = find_plugin(ctx, + type); if (NULL == plugin) return GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED; - return plugin->evaluate (plugin->cls, - ctx, - type, - group, - eo, - query, - xquery, - xquery_size, - reply_block, - reply_block_size); + return plugin->evaluate(plugin->cls, + ctx, + type, + group, + eo, + query, + xquery, + xquery_size, + reply_block, + reply_block_size); } @@ -376,22 +374,22 @@ GNUNET_BLOCK_evaluate (struct GNUNET_BLOCK_Context *ctx, * (or if extracting a key from a block of this type does not work) */ int -GNUNET_BLOCK_get_key (struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - const void *block, - size_t block_size, - struct GNUNET_HashCode *key) +GNUNET_BLOCK_get_key(struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + const void *block, + size_t block_size, + struct GNUNET_HashCode *key) { - struct GNUNET_BLOCK_PluginFunctions *plugin = find_plugin (ctx, - type); + struct GNUNET_BLOCK_PluginFunctions *plugin = find_plugin(ctx, + type); if (plugin == NULL) return GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED; - return plugin->get_key (plugin->cls, - type, - block, - block_size, - key); + return plugin->get_key(plugin->cls, + type, + block, + block_size, + key); } @@ -407,17 +405,17 @@ GNUNET_BLOCK_get_key (struct GNUNET_BLOCK_Context *ctx, * @return #GNUNET_SYSERR if not supported, #GNUNET_OK on success */ int -GNUNET_BLOCK_group_set_seen (struct GNUNET_BLOCK_Group *bg, - const struct GNUNET_HashCode *seen_results, - unsigned int seen_results_count) +GNUNET_BLOCK_group_set_seen(struct GNUNET_BLOCK_Group *bg, + const struct GNUNET_HashCode *seen_results, + unsigned int seen_results_count) { if (NULL == bg) return GNUNET_OK; if (NULL == bg->mark_seen_cb) return GNUNET_SYSERR; - bg->mark_seen_cb (bg, - seen_results, - seen_results_count); + bg->mark_seen_cb(bg, + seen_results, + seen_results_count); return GNUNET_OK; } diff --git a/src/block/plugin_block_template.c b/src/block/plugin_block_template.c index 1918f00aa..5bfacb660 100644 --- a/src/block/plugin_block_template.c +++ b/src/block/plugin_block_template.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file block/plugin_block_template.c @@ -56,37 +56,37 @@ * by this @a type of block (this is not an error) */ static struct GNUNET_BLOCK_Group * -block_plugin_template_create_group (void *cls, - enum GNUNET_BLOCK_Type type, - uint32_t nonce, - const void *raw_data, - size_t raw_data_size, - va_list va) +block_plugin_template_create_group(void *cls, + enum GNUNET_BLOCK_Type type, + uint32_t nonce, + const void *raw_data, + size_t raw_data_size, + va_list va) { unsigned int bf_size; const char *guard; - guard = va_arg (va, const char *); - if (0 == strcmp (guard, - "seen-set-size")) - bf_size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size (va_arg (va, unsigned int), - BLOOMFILTER_K); - else if (0 == strcmp (guard, - "filter-size")) - bf_size = va_arg (va, unsigned int); + guard = va_arg(va, const char *); + if (0 == strcmp(guard, + "seen-set-size")) + bf_size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size(va_arg(va, unsigned int), + BLOOMFILTER_K); + else if (0 == strcmp(guard, + "filter-size")) + bf_size = va_arg(va, unsigned int); else - { - GNUNET_break (0); - bf_size = TEMPLATE_BF_SIZE; - } - GNUNET_break (NULL == va_arg (va, const char *)); - return GNUNET_BLOCK_GROUP_bf_create (cls, - bf_size, - BLOOMFILTER_K, - type, - nonce, - raw_data, - raw_data_size); + { + GNUNET_break(0); + bf_size = TEMPLATE_BF_SIZE; + } + GNUNET_break(NULL == va_arg(va, const char *)); + return GNUNET_BLOCK_GROUP_bf_create(cls, + bf_size, + BLOOMFILTER_K, + type, + nonce, + raw_data, + raw_data_size); } @@ -107,27 +107,27 @@ block_plugin_template_create_group (void *cls, * @return characterization of result */ static enum GNUNET_BLOCK_EvaluationResult -block_plugin_template_evaluate (void *cls, - struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *group, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode *query, - const void *xquery, - size_t xquery_size, - const void *reply_block, - size_t reply_block_size) +block_plugin_template_evaluate(void *cls, + struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *group, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode *query, + const void *xquery, + size_t xquery_size, + const void *reply_block, + size_t reply_block_size) { struct GNUNET_HashCode chash; if (NULL == reply_block) return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; - GNUNET_CRYPTO_hash (reply_block, - reply_block_size, - &chash); + GNUNET_CRYPTO_hash(reply_block, + reply_block_size, + &chash); if (GNUNET_YES == - GNUNET_BLOCK_GROUP_bf_test_and_set (group, - &chash)) + GNUNET_BLOCK_GROUP_bf_test_and_set(group, + &chash)) return GNUNET_BLOCK_EVALUATION_OK_DUPLICATE; return GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED; } @@ -145,11 +145,11 @@ block_plugin_template_evaluate (void *cls, * (or if extracting a key from a block of this type does not work) */ static int -block_plugin_template_get_key (void *cls, - enum GNUNET_BLOCK_Type type, - const void *block, - size_t block_size, - struct GNUNET_HashCode *key) +block_plugin_template_get_key(void *cls, + enum GNUNET_BLOCK_Type type, + const void *block, + size_t block_size, + struct GNUNET_HashCode *key) { return GNUNET_SYSERR; } @@ -161,7 +161,7 @@ block_plugin_template_get_key (void *cls, * @param cls a `const struct GNUNET_CONFIGURATION_Handle` */ void * -libgnunet_plugin_block_template_init (void *cls) +libgnunet_plugin_block_template_init(void *cls) { static enum GNUNET_BLOCK_Type types[] = { @@ -170,7 +170,7 @@ libgnunet_plugin_block_template_init (void *cls) }; struct GNUNET_BLOCK_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_BLOCK_PluginFunctions); + api = GNUNET_new(struct GNUNET_BLOCK_PluginFunctions); api->evaluate = &block_plugin_template_evaluate; api->get_key = &block_plugin_template_get_key; api->create_group = &block_plugin_template_create_group; @@ -183,11 +183,11 @@ libgnunet_plugin_block_template_init (void *cls) * Exit point from the plugin. */ void * -libgnunet_plugin_block_template_done (void *cls) +libgnunet_plugin_block_template_done(void *cls) { struct GNUNET_BLOCK_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/block/plugin_block_test.c b/src/block/plugin_block_test.c index 4543847aa..815fc15cc 100644 --- a/src/block/plugin_block_test.c +++ b/src/block/plugin_block_test.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file block/plugin_block_test.c @@ -54,37 +54,37 @@ * by this @a type of block (this is not an error) */ static struct GNUNET_BLOCK_Group * -block_plugin_test_create_group (void *cls, - enum GNUNET_BLOCK_Type type, - uint32_t nonce, - const void *raw_data, - size_t raw_data_size, - va_list va) +block_plugin_test_create_group(void *cls, + enum GNUNET_BLOCK_Type type, + uint32_t nonce, + const void *raw_data, + size_t raw_data_size, + va_list va) { unsigned int bf_size; const char *guard; - guard = va_arg (va, const char *); - if (0 == strcmp (guard, - "seen-set-size")) - bf_size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size (va_arg (va, unsigned int), - BLOOMFILTER_K); - else if (0 == strcmp (guard, - "filter-size")) - bf_size = va_arg (va, unsigned int); + guard = va_arg(va, const char *); + if (0 == strcmp(guard, + "seen-set-size")) + bf_size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size(va_arg(va, unsigned int), + BLOOMFILTER_K); + else if (0 == strcmp(guard, + "filter-size")) + bf_size = va_arg(va, unsigned int); else - { - GNUNET_break (0); - bf_size = TEST_BF_SIZE; - } - GNUNET_break (NULL == va_arg (va, const char *)); - return GNUNET_BLOCK_GROUP_bf_create (cls, - bf_size, - BLOOMFILTER_K, - type, - nonce, - raw_data, - raw_data_size); + { + GNUNET_break(0); + bf_size = TEST_BF_SIZE; + } + GNUNET_break(NULL == va_arg(va, const char *)); + return GNUNET_BLOCK_GROUP_bf_create(cls, + bf_size, + BLOOMFILTER_K, + type, + nonce, + raw_data, + raw_data_size); } @@ -105,37 +105,37 @@ block_plugin_test_create_group (void *cls, * @return characterization of result */ static enum GNUNET_BLOCK_EvaluationResult -block_plugin_test_evaluate (void *cls, - struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *group, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode *query, - const void *xquery, - size_t xquery_size, - const void *reply_block, - size_t reply_block_size) +block_plugin_test_evaluate(void *cls, + struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *group, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode *query, + const void *xquery, + size_t xquery_size, + const void *reply_block, + size_t reply_block_size) { struct GNUNET_HashCode chash; - if ( GNUNET_BLOCK_TYPE_TEST != type) - { - GNUNET_break (0); - return GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED; - } + if (GNUNET_BLOCK_TYPE_TEST != type) + { + GNUNET_break(0); + return GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED; + } if (0 != xquery_size) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; - } + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; + } if (NULL == reply_block) return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; - GNUNET_CRYPTO_hash (reply_block, - reply_block_size, - &chash); + GNUNET_CRYPTO_hash(reply_block, + reply_block_size, + &chash); if (GNUNET_YES == - GNUNET_BLOCK_GROUP_bf_test_and_set (group, - &chash)) + GNUNET_BLOCK_GROUP_bf_test_and_set(group, + &chash)) return GNUNET_BLOCK_EVALUATION_OK_DUPLICATE; return GNUNET_BLOCK_EVALUATION_OK_MORE; } @@ -153,11 +153,11 @@ block_plugin_test_evaluate (void *cls, * (or if extracting a key from a block of this type does not work) */ static int -block_plugin_test_get_key (void *cls, - enum GNUNET_BLOCK_Type type, - const void *block, - size_t block_size, - struct GNUNET_HashCode *key) +block_plugin_test_get_key(void *cls, + enum GNUNET_BLOCK_Type type, + const void *block, + size_t block_size, + struct GNUNET_HashCode *key) { /* always fails since there is no fixed relationship between * keys and values for test values */ @@ -172,7 +172,7 @@ block_plugin_test_get_key (void *cls, * @return the exported block API */ void * -libgnunet_plugin_block_test_init (void *cls) +libgnunet_plugin_block_test_init(void *cls) { static enum GNUNET_BLOCK_Type types[] = { @@ -181,7 +181,7 @@ libgnunet_plugin_block_test_init (void *cls) }; struct GNUNET_BLOCK_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_BLOCK_PluginFunctions); + api = GNUNET_new(struct GNUNET_BLOCK_PluginFunctions); api->evaluate = &block_plugin_test_evaluate; api->get_key = &block_plugin_test_get_key; api->create_group = &block_plugin_test_create_group; @@ -197,11 +197,11 @@ libgnunet_plugin_block_test_init (void *cls) * @return NULL */ void * -libgnunet_plugin_block_test_done (void *cls) +libgnunet_plugin_block_test_done(void *cls) { struct GNUNET_BLOCK_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/cadet/cadet.h b/src/cadet/cadet.h index ff3e47d19..9b2050e67 100644 --- a/src/cadet/cadet.h +++ b/src/cadet/cadet.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Bartlomiej Polot @@ -35,18 +35,18 @@ extern "C" { #include -#if ! defined(GNUNET_CULL_LOGGING) +#if !defined(GNUNET_CULL_LOGGING) #define CADET_TIMING_START \ struct GNUNET_TIME_Absolute __timestamp; \ - __timestamp = GNUNET_TIME_absolute_get () + __timestamp = GNUNET_TIME_absolute_get() #define CADET_TIMING_END \ struct GNUNET_TIME_Relative __duration; \ - __duration = GNUNET_TIME_absolute_get_duration (__timestamp); \ - LOG (GNUNET_ERROR_TYPE_INFO, \ - " %s duration %s\n", \ - __FUNCTION__, \ - GNUNET_STRINGS_relative_time_to_string (__duration, GNUNET_YES)); + __duration = GNUNET_TIME_absolute_get_duration(__timestamp); \ + LOG(GNUNET_ERROR_TYPE_INFO, \ + " %s duration %s\n", \ + __FUNCTION__, \ + GNUNET_STRINGS_relative_time_to_string(__duration, GNUNET_YES)); #else #define CADET_TIMING_START #define CADET_TIMING_END @@ -99,8 +99,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Number uniquely identifying a channel of a client. */ -struct GNUNET_CADET_ClientChannelNumber -{ +struct GNUNET_CADET_ClientChannelNumber { /** * Values for channel numbering. * Local channel numbers given by the service (incoming) are @@ -115,8 +114,7 @@ struct GNUNET_CADET_ClientChannelNumber /** * Message for a client to create and destroy channels. */ -struct GNUNET_CADET_PortMessage -{ +struct GNUNET_CADET_PortMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN * or #GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE @@ -135,8 +133,7 @@ struct GNUNET_CADET_PortMessage /** * Message for a client to create channels. */ -struct GNUNET_CADET_LocalChannelCreateMessage -{ +struct GNUNET_CADET_LocalChannelCreateMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE * @@ -169,8 +166,7 @@ struct GNUNET_CADET_LocalChannelCreateMessage /** * Message for or to a client to destroy tunnel. */ -struct GNUNET_CADET_LocalChannelDestroyMessage -{ +struct GNUNET_CADET_LocalChannelDestroyMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY */ @@ -186,8 +182,7 @@ struct GNUNET_CADET_LocalChannelDestroyMessage /** * Message for cadet data traffic. */ -struct GNUNET_CADET_LocalData -{ +struct GNUNET_CADET_LocalData { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA */ @@ -214,8 +209,7 @@ struct GNUNET_CADET_LocalData * Message to allow the client send more data to the service * (always service -> client). */ -struct GNUNET_CADET_LocalAck -{ +struct GNUNET_CADET_LocalAck { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK */ @@ -233,8 +227,7 @@ struct GNUNET_CADET_LocalAck * * TODO: split into two messages! */ -struct GNUNET_CADET_LocalInfo -{ +struct GNUNET_CADET_LocalInfo { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL or * #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER @@ -256,8 +249,7 @@ struct GNUNET_CADET_LocalInfo /** * Message to inform the client about channels in the service. */ -struct GNUNET_CADET_RequestPathInfoMessage -{ +struct GNUNET_CADET_RequestPathInfoMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_PATH */ @@ -278,8 +270,7 @@ struct GNUNET_CADET_RequestPathInfoMessage /** * Message to inform the client about channels in the service. */ -struct GNUNET_CADET_ChannelInfoMessage -{ +struct GNUNET_CADET_ChannelInfoMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNEL. */ @@ -302,8 +293,7 @@ struct GNUNET_CADET_ChannelInfoMessage /** * Message to as the service about information on a channel. */ -struct GNUNET_CADET_RequestChannelInfoMessage -{ +struct GNUNET_CADET_RequestChannelInfoMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_CHANNEL. */ @@ -319,8 +309,7 @@ struct GNUNET_CADET_RequestChannelInfoMessage /** * Message to inform the client about one of the paths known to the service. */ -struct GNUNET_CADET_LocalInfoPath -{ +struct GNUNET_CADET_LocalInfoPath { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PATH. */ @@ -336,8 +325,7 @@ struct GNUNET_CADET_LocalInfoPath /** * Message to inform the client about one of the peers in the service. */ -struct GNUNET_CADET_LocalInfoPeers -{ +struct GNUNET_CADET_LocalInfoPeers { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS */ @@ -370,8 +358,7 @@ struct GNUNET_CADET_LocalInfoPeers * * TODO: split into two messages! */ -struct GNUNET_CADET_LocalInfoTunnel -{ +struct GNUNET_CADET_LocalInfoTunnel { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL * or #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS @@ -419,7 +406,7 @@ GNUNET_NETWORK_STRUCT_END * @return String representing FWD or BCK. */ char * -GC_f2s (int fwd); +GC_f2s(int fwd); /** @@ -431,7 +418,7 @@ GC_f2s (int fwd); * @return True if bigger (arg1) has a higher value than smaller (arg 2). */ int -GC_is_pid_bigger (uint32_t bigger, uint32_t smaller); +GC_is_pid_bigger(uint32_t bigger, uint32_t smaller); /** @@ -443,7 +430,7 @@ GC_is_pid_bigger (uint32_t bigger, uint32_t smaller); * @return Highest ACK value from the two. */ uint32_t -GC_max_pid (uint32_t a, uint32_t b); +GC_max_pid(uint32_t a, uint32_t b); /** @@ -455,7 +442,7 @@ GC_max_pid (uint32_t a, uint32_t b); * @return Lowest ACK value from the two. */ uint32_t -GC_min_pid (uint32_t a, uint32_t b); +GC_min_pid(uint32_t a, uint32_t b); /** @@ -468,7 +455,7 @@ GC_min_pid (uint32_t a, uint32_t b); * @return The size of the output. */ size_t -GC_bin2s (void *bin, unsigned int len, char **output); +GC_bin2s(void *bin, unsigned int len, char **output); /** @@ -482,7 +469,7 @@ GC_bin2s (void *bin, unsigned int len, char **output); * @return Human readable string description. */ const char * -GC_m2s (uint16_t m); +GC_m2s(uint16_t m); #if 0 /* keep Emacsens' auto-indent happy */ { diff --git a/src/cadet/cadet_api.c b/src/cadet/cadet_api.c index 7148ab956..61ff71b31 100644 --- a/src/cadet/cadet_api.c +++ b/src/cadet/cadet_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/cadet_api.c * @brief cadet api: client implementation of cadet service @@ -30,13 +30,12 @@ #include "cadet.h" #include "cadet_protocol.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "cadet-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "cadet-api", __VA_ARGS__) /** * Opaque handle to the service. */ -struct GNUNET_CADET_Handle -{ +struct GNUNET_CADET_Handle { /** * Message queue. */ @@ -77,9 +76,7 @@ struct GNUNET_CADET_Handle /** * Opaque handle to a channel. */ -struct GNUNET_CADET_Channel -{ - +struct GNUNET_CADET_Channel { /** * Other end of the channel. */ @@ -143,9 +140,7 @@ struct GNUNET_CADET_Channel /** * Opaque handle to a port. */ -struct GNUNET_CADET_Port -{ - +struct GNUNET_CADET_Port { /** * Port "number" */ @@ -196,10 +191,10 @@ struct GNUNET_CADET_Port * @return The port handle if known, NULL otherwise. */ static struct GNUNET_CADET_Port * -find_port (const struct GNUNET_CADET_Handle *h, - const struct GNUNET_HashCode *hash) +find_port(const struct GNUNET_CADET_Handle *h, + const struct GNUNET_HashCode *hash) { - return GNUNET_CONTAINER_multihashmap_get (h->ports, hash); + return GNUNET_CONTAINER_multihashmap_get(h->ports, hash); } @@ -211,11 +206,11 @@ find_port (const struct GNUNET_CADET_Handle *h, * @return handle to the required channel or NULL if not found */ static struct GNUNET_CADET_Channel * -find_channel (struct GNUNET_CADET_Handle *h, - struct GNUNET_CADET_ClientChannelNumber ccn) +find_channel(struct GNUNET_CADET_Handle *h, + struct GNUNET_CADET_ClientChannelNumber ccn) { - return GNUNET_CONTAINER_multihashmap32_get (h->channels, - ntohl (ccn.channel_of_client)); + return GNUNET_CONTAINER_multihashmap32_get(h->channels, + ntohl(ccn.channel_of_client)); } @@ -227,33 +222,33 @@ find_channel (struct GNUNET_CADET_Handle *h, * @return Handle to the created channel. */ static struct GNUNET_CADET_Channel * -create_channel (struct GNUNET_CADET_Handle *h, - const struct GNUNET_CADET_ClientChannelNumber *ccnp) +create_channel(struct GNUNET_CADET_Handle *h, + const struct GNUNET_CADET_ClientChannelNumber *ccnp) { struct GNUNET_CADET_Channel *ch; struct GNUNET_CADET_ClientChannelNumber ccn; - ch = GNUNET_new (struct GNUNET_CADET_Channel); + ch = GNUNET_new(struct GNUNET_CADET_Channel); ch->cadet = h; if (NULL == ccnp) - { - while (NULL != find_channel (h, h->next_ccn)) - h->next_ccn.channel_of_client = - htonl (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI | - (1 + ntohl (h->next_ccn.channel_of_client))); - ccn = h->next_ccn; - } + { + while (NULL != find_channel(h, h->next_ccn)) + h->next_ccn.channel_of_client = + htonl(GNUNET_CADET_LOCAL_CHANNEL_ID_CLI | + (1 + ntohl(h->next_ccn.channel_of_client))); + ccn = h->next_ccn; + } else - { - ccn = *ccnp; - } + { + ccn = *ccnp; + } ch->ccn = ccn; - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap32_put ( - h->channels, - ntohl (ch->ccn.channel_of_client), - ch, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap32_put( + h->channels, + ntohl(ch->ccn.channel_of_client), + ch, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); return ch; } @@ -269,31 +264,31 @@ create_channel (struct GNUNET_CADET_Handle *h, * @param call_cleaner Whether to call the cleaner handler. */ static void -destroy_channel (struct GNUNET_CADET_Channel *ch) +destroy_channel(struct GNUNET_CADET_Channel *ch) { struct GNUNET_CADET_Handle *h = ch->cadet; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Destroying channel %X of %p\n", - htonl (ch->ccn.channel_of_client), - h); - GNUNET_assert ( + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Destroying channel %X of %p\n", + htonl(ch->ccn.channel_of_client), + h); + GNUNET_assert( GNUNET_YES == - GNUNET_CONTAINER_multihashmap32_remove (h->channels, - ntohl (ch->ccn.channel_of_client), - ch)); + GNUNET_CONTAINER_multihashmap32_remove(h->channels, + ntohl(ch->ccn.channel_of_client), + ch)); if (NULL != ch->mq_cont) - { - GNUNET_SCHEDULER_cancel (ch->mq_cont); - ch->mq_cont = NULL; - } + { + GNUNET_SCHEDULER_cancel(ch->mq_cont); + ch->mq_cont = NULL; + } /* signal channel destruction */ if (NULL != ch->disconnects) - ch->disconnects (ch->ctx, ch); + ch->disconnects(ch->ctx, ch); if (NULL != ch->pending_env) - GNUNET_MQ_discard (ch->pending_env); - GNUNET_MQ_destroy (ch->mq); - GNUNET_free (ch); + GNUNET_MQ_discard(ch->pending_env); + GNUNET_MQ_destroy(ch->mq); + GNUNET_free(ch); } @@ -304,7 +299,7 @@ destroy_channel (struct GNUNET_CADET_Channel *ch) * @param h handle to the cadet */ static void -reconnect (struct GNUNET_CADET_Handle *h); +reconnect(struct GNUNET_CADET_Handle *h); /** @@ -317,17 +312,17 @@ reconnect (struct GNUNET_CADET_Handle *h); * @return #GNUNET_OK (continue to iterate) */ static int -open_port_cb (void *cls, const struct GNUNET_HashCode *id, void *value) +open_port_cb(void *cls, const struct GNUNET_HashCode *id, void *value) { struct GNUNET_CADET_Handle *h = cls; struct GNUNET_CADET_Port *port = value; struct GNUNET_CADET_PortMessage *msg; struct GNUNET_MQ_Envelope *env; - (void) id; - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN); + (void)id; + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN); msg->port = port->id; - GNUNET_MQ_send (h->mq, env); + GNUNET_MQ_send(h->mq, env); return GNUNET_OK; } @@ -339,14 +334,14 @@ open_port_cb (void *cls, const struct GNUNET_HashCode *id, void *value) * @param cls closure (cadet handle) */ static void -reconnect_cbk (void *cls) +reconnect_cbk(void *cls) { struct GNUNET_CADET_Handle *h = cls; h->reconnect_task = NULL; - h->reconnect_time = GNUNET_TIME_STD_BACKOFF (h->reconnect_time); - reconnect (h); - GNUNET_CONTAINER_multihashmap_iterate (h->ports, &open_port_cb, h); + h->reconnect_time = GNUNET_TIME_STD_BACKOFF(h->reconnect_time); + reconnect(h); + GNUNET_CONTAINER_multihashmap_iterate(h->ports, &open_port_cb, h); } @@ -356,12 +351,12 @@ reconnect_cbk (void *cls) * @param ch Channel to notify about. */ static void -notify_window_size (struct GNUNET_CADET_Channel *ch) +notify_window_size(struct GNUNET_CADET_Channel *ch) { if (NULL != ch->window_changes) - ch->window_changes (ch->ctx, - ch, /* FIXME: remove 'ch'? */ - ch->allow_send); + ch->window_changes(ch->ctx, + ch, /* FIXME: remove 'ch'? */ + ch->allow_send); } @@ -371,32 +366,32 @@ notify_window_size (struct GNUNET_CADET_Channel *ch) * @param cls Closure (channel whose mq to activate). */ static void -cadet_mq_send_now (void *cls) +cadet_mq_send_now(void *cls) { struct GNUNET_CADET_Channel *ch = cls; struct GNUNET_MQ_Envelope *env = ch->pending_env; ch->mq_cont = NULL; if (0 == ch->allow_send) - { - /* how did we get here? */ - GNUNET_break (0); - return; - } + { + /* how did we get here? */ + GNUNET_break(0); + return; + } if (NULL == env) - { - /* how did we get here? */ - GNUNET_break (0); - return; - } + { + /* how did we get here? */ + GNUNET_break(0); + return; + } ch->allow_send--; ch->pending_env = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending message on channel %s to CADET, new window size is %u\n", - GNUNET_i2s (&ch->peer), - ch->allow_send); - GNUNET_MQ_send (ch->cadet->mq, env); - GNUNET_MQ_impl_send_continue (ch->mq); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending message on channel %s to CADET, new window size is %u\n", + GNUNET_i2s(&ch->peer), + ch->allow_send); + GNUNET_MQ_send(ch->cadet->mq, env); + GNUNET_MQ_impl_send_continue(ch->mq); } @@ -413,9 +408,9 @@ cadet_mq_send_now (void *cls) * @param impl_state state of the implementation */ static void -cadet_mq_send_impl (struct GNUNET_MQ_Handle *mq, - const struct GNUNET_MessageHeader *msg, - void *impl_state) +cadet_mq_send_impl(struct GNUNET_MQ_Handle *mq, + const struct GNUNET_MessageHeader *msg, + void *impl_state) { struct GNUNET_CADET_Channel *ch = impl_state; struct GNUNET_CADET_Handle *h = ch->cadet; @@ -426,31 +421,31 @@ cadet_mq_send_impl (struct GNUNET_MQ_Handle *mq, enum GNUNET_MQ_PriorityPreferences pp; if (NULL == h->mq) - { - /* We're currently reconnecting, pretend this worked */ - GNUNET_MQ_impl_send_continue (mq); - return; - } - orig_env = GNUNET_MQ_get_current_envelope (mq); - pp = GNUNET_MQ_env_get_options (orig_env); + { + /* We're currently reconnecting, pretend this worked */ + GNUNET_MQ_impl_send_continue(mq); + return; + } + orig_env = GNUNET_MQ_get_current_envelope(mq); + pp = GNUNET_MQ_env_get_options(orig_env); /* check message size for sanity */ - msize = ntohs (msg->size); + msize = ntohs(msg->size); if (msize > GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE) - { - GNUNET_break (0); - GNUNET_MQ_impl_send_continue (mq); - return; - } - env = GNUNET_MQ_msg_nested_mh (cadet_msg, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA, - msg); + { + GNUNET_break(0); + GNUNET_MQ_impl_send_continue(mq); + return; + } + env = GNUNET_MQ_msg_nested_mh(cadet_msg, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA, + msg); cadet_msg->ccn = ch->ccn; - cadet_msg->pp = htonl ((uint32_t) pp); - GNUNET_assert (NULL == ch->pending_env); + cadet_msg->pp = htonl((uint32_t)pp); + GNUNET_assert(NULL == ch->pending_env); ch->pending_env = env; if (0 < ch->allow_send) - ch->mq_cont = GNUNET_SCHEDULER_add_now (&cadet_mq_send_now, ch); + ch->mq_cont = GNUNET_SCHEDULER_add_now(&cadet_mq_send_now, ch); } @@ -462,11 +457,11 @@ cadet_mq_send_impl (struct GNUNET_MQ_Handle *mq, * @param impl_state state of the implementation */ static void -cadet_mq_destroy_impl (struct GNUNET_MQ_Handle *mq, void *impl_state) +cadet_mq_destroy_impl(struct GNUNET_MQ_Handle *mq, void *impl_state) { struct GNUNET_CADET_Channel *ch = impl_state; - GNUNET_assert (mq == ch->mq); + GNUNET_assert(mq == ch->mq); ch->mq = NULL; } @@ -480,25 +475,25 @@ cadet_mq_destroy_impl (struct GNUNET_MQ_Handle *mq, void *impl_state) * @param error error code */ static void -cadet_mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +cadet_mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_CADET_Channel *ch = cls; if (GNUNET_MQ_ERROR_NO_MATCH == error) - { - /* Got a message we did not understand, still try to continue! */ - GNUNET_break_op (0); - GNUNET_CADET_receive_done (ch); - } + { + /* Got a message we did not understand, still try to continue! */ + GNUNET_break_op(0); + GNUNET_CADET_receive_done(ch); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "MQ error in communication with CADET: %d\n", - error); - if (NULL != ch->disconnects) - ch->disconnects (ch->ctx, ch); - GNUNET_CADET_channel_destroy (ch); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "MQ error in communication with CADET: %d\n", + error); + if (NULL != ch->disconnects) + ch->disconnects(ch->ctx, ch); + GNUNET_CADET_channel_destroy(ch); + } } @@ -510,19 +505,19 @@ cadet_mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @param impl_state state specific to the implementation */ static void -cadet_mq_cancel_impl (struct GNUNET_MQ_Handle *mq, void *impl_state) +cadet_mq_cancel_impl(struct GNUNET_MQ_Handle *mq, void *impl_state) { struct GNUNET_CADET_Channel *ch = impl_state; - (void) mq; - GNUNET_assert (NULL != ch->pending_env); - GNUNET_MQ_discard (ch->pending_env); + (void)mq; + GNUNET_assert(NULL != ch->pending_env); + GNUNET_MQ_discard(ch->pending_env); ch->pending_env = NULL; if (NULL != ch->mq_cont) - { - GNUNET_SCHEDULER_cancel (ch->mq_cont); - ch->mq_cont = NULL; - } + { + GNUNET_SCHEDULER_cancel(ch->mq_cont); + ch->mq_cont = NULL; + } } @@ -533,7 +528,7 @@ cadet_mq_cancel_impl (struct GNUNET_MQ_Handle *mq, void *impl_state) * @param msg A message with the details of the new incoming channel */ static void -handle_channel_created ( +handle_channel_created( void *cls, const struct GNUNET_CADET_LocalChannelCreateMessage *msg) { @@ -545,52 +540,52 @@ handle_channel_created ( ccn = msg->ccn; port_number = &msg->port; - if (ntohl (ccn.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI) - { - GNUNET_break (0); - return; - } - port = find_port (h, port_number); + if (ntohl(ccn.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI) + { + GNUNET_break(0); + return; + } + port = find_port(h, port_number); if (NULL == port) - { - /* We could have closed the port but the service didn't know about it yet - * This is not an error. - */ - struct GNUNET_CADET_LocalChannelDestroyMessage *d_msg; - struct GNUNET_MQ_Envelope *env; - - LOG (GNUNET_ERROR_TYPE_DEBUG, - "No handler for incoming channel %X (on port %s, recently closed?)\n", - ntohl (ccn.channel_of_client), - GNUNET_h2s (port_number)); - env = - GNUNET_MQ_msg (d_msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY); - d_msg->ccn = msg->ccn; - GNUNET_MQ_send (h->mq, env); - return; - } - - ch = create_channel (h, &ccn); + { + /* We could have closed the port but the service didn't know about it yet + * This is not an error. + */ + struct GNUNET_CADET_LocalChannelDestroyMessage *d_msg; + struct GNUNET_MQ_Envelope *env; + + LOG(GNUNET_ERROR_TYPE_DEBUG, + "No handler for incoming channel %X (on port %s, recently closed?)\n", + ntohl(ccn.channel_of_client), + GNUNET_h2s(port_number)); + env = + GNUNET_MQ_msg(d_msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY); + d_msg->ccn = msg->ccn; + GNUNET_MQ_send(h->mq, env); + return; + } + + ch = create_channel(h, &ccn); ch->peer = msg->peer; ch->incoming_port = port; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Creating incoming channel %X [%s] %p\n", - ntohl (ccn.channel_of_client), - GNUNET_h2s (port_number), - ch); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Creating incoming channel %X [%s] %p\n", + ntohl(ccn.channel_of_client), + GNUNET_h2s(port_number), + ch); - GNUNET_assert (NULL != port->connects); + GNUNET_assert(NULL != port->connects); ch->window_changes = port->window_changes; ch->disconnects = port->disconnects; - ch->mq = GNUNET_MQ_queue_for_callbacks (&cadet_mq_send_impl, - &cadet_mq_destroy_impl, - &cadet_mq_cancel_impl, - ch, - port->handlers, - &cadet_mq_error_handler, - ch); - ch->ctx = port->connects (port->cls, ch, &msg->peer); - GNUNET_MQ_set_handlers_closure (ch->mq, ch->ctx); + ch->mq = GNUNET_MQ_queue_for_callbacks(&cadet_mq_send_impl, + &cadet_mq_destroy_impl, + &cadet_mq_cancel_impl, + ch, + port->handlers, + &cadet_mq_error_handler, + ch); + ch->ctx = port->connects(port->cls, ch, &msg->peer); + GNUNET_MQ_set_handlers_closure(ch->mq, ch->ctx); } @@ -601,25 +596,25 @@ handle_channel_created ( * @param msg A message with the details of the channel being destroyed */ static void -handle_channel_destroy ( +handle_channel_destroy( void *cls, const struct GNUNET_CADET_LocalChannelDestroyMessage *msg) { struct GNUNET_CADET_Handle *h = cls; struct GNUNET_CADET_Channel *ch; - ch = find_channel (h, msg->ccn); + ch = find_channel(h, msg->ccn); if (NULL == ch) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received channel destroy for unknown channel %X from CADET service (recently close?)\n", - ntohl (msg->ccn.channel_of_client)); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received channel destroy for channel %X from CADET service\n", - ntohl (msg->ccn.channel_of_client)); - destroy_channel (ch); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received channel destroy for unknown channel %X from CADET service (recently close?)\n", + ntohl(msg->ccn.channel_of_client)); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received channel destroy for channel %X from CADET service\n", + ntohl(msg->ccn.channel_of_client)); + destroy_channel(ch); } @@ -632,17 +627,17 @@ handle_channel_destroy ( * #GNUNET_SYSERR otherwise */ static int -check_local_data (void *cls, const struct GNUNET_CADET_LocalData *message) +check_local_data(void *cls, const struct GNUNET_CADET_LocalData *message) { uint16_t size; - (void) cls; - size = ntohs (message->header.size); - if (sizeof (*message) + sizeof (struct GNUNET_MessageHeader) > size) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + (void)cls; + size = ntohs(message->header.size); + if (sizeof(*message) + sizeof(struct GNUNET_MessageHeader) > size) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -654,7 +649,7 @@ check_local_data (void *cls, const struct GNUNET_CADET_LocalData *message) * @param message A message encapsulating the data */ static void -handle_local_data (void *cls, const struct GNUNET_CADET_LocalData *message) +handle_local_data(void *cls, const struct GNUNET_CADET_LocalData *message) { struct GNUNET_CADET_Handle *h = cls; const struct GNUNET_MessageHeader *payload; @@ -662,25 +657,25 @@ handle_local_data (void *cls, const struct GNUNET_CADET_LocalData *message) uint16_t type; int fwd; - ch = find_channel (h, message->ccn); + ch = find_channel(h, message->ccn); if (NULL == ch) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Unknown channel %X for incoming data (recently closed?)\n", - ntohl (message->ccn.channel_of_client)); - return; - } - - payload = (const struct GNUNET_MessageHeader *) &message[1]; - type = ntohs (payload->type); - fwd = ntohl (ch->ccn.channel_of_client) <= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got a %s data on channel %s [%X] of type %u\n", - fwd ? "FWD" : "BWD", - GNUNET_i2s (&ch->peer), - ntohl (message->ccn.channel_of_client), - type); - GNUNET_MQ_inject_message (ch->mq, payload); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Unknown channel %X for incoming data (recently closed?)\n", + ntohl(message->ccn.channel_of_client)); + return; + } + + payload = (const struct GNUNET_MessageHeader *)&message[1]; + type = ntohs(payload->type); + fwd = ntohl(ch->ccn.channel_of_client) <= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got a %s data on channel %s [%X] of type %u\n", + fwd ? "FWD" : "BWD", + GNUNET_i2s(&ch->peer), + ntohl(message->ccn.channel_of_client), + type); + GNUNET_MQ_inject_message(ch->mq, payload); } @@ -692,37 +687,37 @@ handle_local_data (void *cls, const struct GNUNET_CADET_LocalData *message) * @param message Message itself. */ static void -handle_local_ack (void *cls, const struct GNUNET_CADET_LocalAck *message) +handle_local_ack(void *cls, const struct GNUNET_CADET_LocalAck *message) { struct GNUNET_CADET_Handle *h = cls; struct GNUNET_CADET_Channel *ch; - ch = find_channel (h, message->ccn); + ch = find_channel(h, message->ccn); if (NULL == ch) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "ACK on unknown channel %X\n", - ntohl (message->ccn.channel_of_client)); - return; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "ACK on unknown channel %X\n", + ntohl(message->ccn.channel_of_client)); + return; + } ch->allow_send++; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got an ACK on mq channel %X (peer %s); new window size is %u!\n", - ntohl (ch->ccn.channel_of_client), - GNUNET_i2s (&ch->peer), - ch->allow_send); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got an ACK on mq channel %X (peer %s); new window size is %u!\n", + ntohl(ch->ccn.channel_of_client), + GNUNET_i2s(&ch->peer), + ch->allow_send); if (NULL == ch->pending_env) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got an ACK on mq channel %X, allow send now %u!\n", - ntohl (ch->ccn.channel_of_client), - ch->allow_send); - notify_window_size (ch); - return; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got an ACK on mq channel %X, allow send now %u!\n", + ntohl(ch->ccn.channel_of_client), + ch->allow_send); + notify_window_size(ch); + return; + } if (NULL != ch->mq_cont) return; /* already working on it! */ - ch->mq_cont = GNUNET_SCHEDULER_add_now (&cadet_mq_send_now, ch); + ch->mq_cont = GNUNET_SCHEDULER_add_now(&cadet_mq_send_now, ch); } @@ -736,16 +731,16 @@ handle_local_ack (void *cls, const struct GNUNET_CADET_LocalAck *message) * @return #GNUNET_OK (continue to iterate) */ static int -destroy_channel_cb (void *cls, uint32_t cid, void *value) +destroy_channel_cb(void *cls, uint32_t cid, void *value) { /* struct GNUNET_CADET_Handle *handle = cls; */ struct GNUNET_CADET_Channel *ch = value; - (void) cls; - (void) cid; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Destroying channel due to GNUNET_CADET_disconnect()\n"); - destroy_channel (ch); + (void)cls; + (void)cid; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Destroying channel due to GNUNET_CADET_disconnect()\n"); + destroy_channel(ch); return GNUNET_OK; } @@ -759,17 +754,17 @@ destroy_channel_cb (void *cls, uint32_t cid, void *value) * @param error error code */ static void -handle_mq_error (void *cls, enum GNUNET_MQ_Error error) +handle_mq_error(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_CADET_Handle *h = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MQ ERROR: %u\n", error); - GNUNET_CONTAINER_multihashmap32_iterate (h->channels, &destroy_channel_cb, h); - GNUNET_MQ_destroy (h->mq); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MQ ERROR: %u\n", error); + GNUNET_CONTAINER_multihashmap32_iterate(h->channels, &destroy_channel_cb, h); + GNUNET_MQ_destroy(h->mq); h->mq = NULL; - GNUNET_assert (NULL == h->reconnect_task); + GNUNET_assert(NULL == h->reconnect_task); h->reconnect_task = - GNUNET_SCHEDULER_add_delayed (h->reconnect_time, &reconnect_cbk, h); + GNUNET_SCHEDULER_add_delayed(h->reconnect_time, &reconnect_cbk, h); } @@ -780,30 +775,30 @@ handle_mq_error (void *cls, enum GNUNET_MQ_Error error) * @param h handle to the cadet */ static void -reconnect (struct GNUNET_CADET_Handle *h) +reconnect(struct GNUNET_CADET_Handle *h) { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_fixed_size (channel_created, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE, - struct GNUNET_CADET_LocalChannelCreateMessage, - h), - GNUNET_MQ_hd_fixed_size (channel_destroy, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY, - struct GNUNET_CADET_LocalChannelDestroyMessage, - h), - GNUNET_MQ_hd_var_size (local_data, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA, - struct GNUNET_CADET_LocalData, + { GNUNET_MQ_hd_fixed_size(channel_created, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE, + struct GNUNET_CADET_LocalChannelCreateMessage, + h), + GNUNET_MQ_hd_fixed_size(channel_destroy, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY, + struct GNUNET_CADET_LocalChannelDestroyMessage, + h), + GNUNET_MQ_hd_var_size(local_data, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA, + struct GNUNET_CADET_LocalData, + h), + GNUNET_MQ_hd_fixed_size(local_ack, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK, + struct GNUNET_CADET_LocalAck, h), - GNUNET_MQ_hd_fixed_size (local_ack, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK, - struct GNUNET_CADET_LocalAck, - h), - GNUNET_MQ_handler_end ()}; + GNUNET_MQ_handler_end() }; - GNUNET_assert (NULL == h->mq); + GNUNET_assert(NULL == h->mq); h->mq = - GNUNET_CLIENT_connect (h->cfg, "cadet", handlers, &handle_mq_error, h); + GNUNET_CLIENT_connect(h->cfg, "cadet", handlers, &handle_mq_error, h); } @@ -817,16 +812,16 @@ reconnect (struct GNUNET_CADET_Handle *h) * @return #GNUNET_OK (continue to iterate) */ static int -destroy_port_cb (void *cls, const struct GNUNET_HashCode *id, void *value) +destroy_port_cb(void *cls, const struct GNUNET_HashCode *id, void *value) { /* struct GNUNET_CADET_Handle *handle = cls; */ struct GNUNET_CADET_Port *port = value; - (void) cls; - (void) id; + (void)cls; + (void)id; /* This is a warning, the app should have cleanly closed all open ports */ - GNUNET_break (0); - GNUNET_CADET_close_port (port); + GNUNET_break(0); + GNUNET_CADET_close_port(port); return GNUNET_OK; } @@ -840,29 +835,29 @@ destroy_port_cb (void *cls, const struct GNUNET_HashCode *id, void *value) * @param handle connection to cadet to disconnect */ void -GNUNET_CADET_disconnect (struct GNUNET_CADET_Handle *handle) +GNUNET_CADET_disconnect(struct GNUNET_CADET_Handle *handle) { - GNUNET_CONTAINER_multihashmap_iterate (handle->ports, - &destroy_port_cb, - handle); - GNUNET_CONTAINER_multihashmap_destroy (handle->ports); + GNUNET_CONTAINER_multihashmap_iterate(handle->ports, + &destroy_port_cb, + handle); + GNUNET_CONTAINER_multihashmap_destroy(handle->ports); handle->ports = NULL; - GNUNET_CONTAINER_multihashmap32_iterate (handle->channels, - &destroy_channel_cb, - handle); - GNUNET_CONTAINER_multihashmap32_destroy (handle->channels); + GNUNET_CONTAINER_multihashmap32_iterate(handle->channels, + &destroy_channel_cb, + handle); + GNUNET_CONTAINER_multihashmap32_destroy(handle->channels); handle->channels = NULL; if (NULL != handle->mq) - { - GNUNET_MQ_destroy (handle->mq); - handle->mq = NULL; - } + { + GNUNET_MQ_destroy(handle->mq); + handle->mq = NULL; + } if (NULL != handle->reconnect_task) - { - GNUNET_SCHEDULER_cancel (handle->reconnect_task); - handle->reconnect_task = NULL; - } - GNUNET_free (handle); + { + GNUNET_SCHEDULER_cancel(handle->reconnect_task); + handle->reconnect_task = NULL; + } + GNUNET_free(handle); } @@ -873,22 +868,22 @@ GNUNET_CADET_disconnect (struct GNUNET_CADET_Handle *handle) * @param p Port handle. */ void -GNUNET_CADET_close_port (struct GNUNET_CADET_Port *p) +GNUNET_CADET_close_port(struct GNUNET_CADET_Port *p) { - GNUNET_assert ( + GNUNET_assert( GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (p->cadet->ports, &p->id, p)); + GNUNET_CONTAINER_multihashmap_remove(p->cadet->ports, &p->id, p)); if (NULL != p->cadet->mq) - { - struct GNUNET_CADET_PortMessage *msg; - struct GNUNET_MQ_Envelope *env; - - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE); - msg->port = p->id; - GNUNET_MQ_send (p->cadet->mq, env); - } - GNUNET_free_non_null (p->handlers); - GNUNET_free (p); + { + struct GNUNET_CADET_PortMessage *msg; + struct GNUNET_MQ_Envelope *env; + + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE); + msg->port = p->id; + GNUNET_MQ_send(p->cadet->mq, env); + } + GNUNET_free_non_null(p->handlers); + GNUNET_free(p); } @@ -902,22 +897,22 @@ GNUNET_CADET_close_port (struct GNUNET_CADET_Port *p) * @param channel Channel handle, becomes invalid after this call. */ void -GNUNET_CADET_channel_destroy (struct GNUNET_CADET_Channel *channel) +GNUNET_CADET_channel_destroy(struct GNUNET_CADET_Channel *channel) { struct GNUNET_CADET_Handle *h = channel->cadet; struct GNUNET_CADET_LocalChannelDestroyMessage *msg; struct GNUNET_MQ_Envelope *env; if (NULL != h->mq) - { - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY); - msg->ccn = channel->ccn; - GNUNET_MQ_send (h->mq, env); - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Destroying channel due to GNUNET_CADET_channel_destroy()\n"); + { + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY); + msg->ccn = channel->ccn; + GNUNET_MQ_send(h->mq, env); + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Destroying channel due to GNUNET_CADET_channel_destroy()\n"); channel->disconnects = NULL; - destroy_channel (channel); + destroy_channel(channel); } @@ -931,18 +926,19 @@ GNUNET_CADET_channel_destroy (struct GNUNET_CADET_Channel *channel) * @return Union with an answer to the query. */ const union GNUNET_CADET_ChannelInfo * -GNUNET_CADET_channel_get_info (struct GNUNET_CADET_Channel *channel, - enum GNUNET_CADET_ChannelInfoOption option, - ...) +GNUNET_CADET_channel_get_info(struct GNUNET_CADET_Channel *channel, + enum GNUNET_CADET_ChannelInfoOption option, + ...) { switch (option) - { - case GNUNET_CADET_OPTION_PEER: - return (const union GNUNET_CADET_ChannelInfo *) &channel->peer; - default: - GNUNET_break (0); - return NULL; - } + { + case GNUNET_CADET_OPTION_PEER: + return (const union GNUNET_CADET_ChannelInfo *)&channel->peer; + + default: + GNUNET_break(0); + return NULL; + } } @@ -952,17 +948,17 @@ GNUNET_CADET_channel_get_info (struct GNUNET_CADET_Channel *channel, * @param ch Channel on which to send the ACK. */ void -GNUNET_CADET_receive_done (struct GNUNET_CADET_Channel *channel) +GNUNET_CADET_receive_done(struct GNUNET_CADET_Channel *channel) { struct GNUNET_CADET_LocalAck *msg; struct GNUNET_MQ_Envelope *env; - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending ACK on channel %X\n", - ntohl (channel->ccn.channel_of_client)); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending ACK on channel %X\n", + ntohl(channel->ccn.channel_of_client)); msg->ccn = channel->ccn; - GNUNET_MQ_send (channel->cadet->mq, env); + GNUNET_MQ_send(channel->cadet->mq, env); } @@ -974,23 +970,23 @@ GNUNET_CADET_receive_done (struct GNUNET_CADET_Channel *channel) * @return Handle to the cadet service NULL on error. */ struct GNUNET_CADET_Handle * -GNUNET_CADET_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_CADET_connect(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_CADET_Handle *h; - LOG (GNUNET_ERROR_TYPE_DEBUG, "GNUNET_CADET_connect()\n"); - h = GNUNET_new (struct GNUNET_CADET_Handle); + LOG(GNUNET_ERROR_TYPE_DEBUG, "GNUNET_CADET_connect()\n"); + h = GNUNET_new(struct GNUNET_CADET_Handle); h->cfg = cfg; - h->ports = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_YES); - h->channels = GNUNET_CONTAINER_multihashmap32_create (4); - reconnect (h); + h->ports = GNUNET_CONTAINER_multihashmap_create(4, GNUNET_YES); + h->channels = GNUNET_CONTAINER_multihashmap32_create(4); + reconnect(h); if (NULL == h->mq) - { - GNUNET_break (0); - GNUNET_CADET_disconnect (h); - return NULL; - } - h->next_ccn.channel_of_client = htonl (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI); + { + GNUNET_break(0); + GNUNET_CADET_disconnect(h); + return NULL; + } + h->next_ccn.channel_of_client = htonl(GNUNET_CADET_LOCAL_CHANNEL_ID_CLI); return h; } @@ -1008,41 +1004,41 @@ GNUNET_CADET_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) * @return Port handle, NULL if port is in use */ struct GNUNET_CADET_Port * -GNUNET_CADET_open_port (struct GNUNET_CADET_Handle *h, - const struct GNUNET_HashCode *port, - GNUNET_CADET_ConnectEventHandler connects, - void *connects_cls, - GNUNET_CADET_WindowSizeEventHandler window_changes, - GNUNET_CADET_DisconnectEventHandler disconnects, - const struct GNUNET_MQ_MessageHandler *handlers) +GNUNET_CADET_open_port(struct GNUNET_CADET_Handle *h, + const struct GNUNET_HashCode *port, + GNUNET_CADET_ConnectEventHandler connects, + void *connects_cls, + GNUNET_CADET_WindowSizeEventHandler window_changes, + GNUNET_CADET_DisconnectEventHandler disconnects, + const struct GNUNET_MQ_MessageHandler *handlers) { struct GNUNET_CADET_Port *p; - GNUNET_assert (NULL != connects); - GNUNET_assert (NULL != disconnects); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Listening to CADET port %s\n", - GNUNET_h2s (port)); + GNUNET_assert(NULL != connects); + GNUNET_assert(NULL != disconnects); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Listening to CADET port %s\n", + GNUNET_h2s(port)); - p = GNUNET_new (struct GNUNET_CADET_Port); + p = GNUNET_new(struct GNUNET_CADET_Port); p->cadet = h; p->id = *port; - if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put ( - h->ports, - &p->id, - p, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - GNUNET_free (p); - return NULL; - } + if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put( + h->ports, + &p->id, + p, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_free(p); + return NULL; + } p->connects = connects; p->cls = connects_cls; p->window_changes = window_changes; p->disconnects = disconnects; - p->handlers = GNUNET_MQ_copy_handlers (handlers); + p->handlers = GNUNET_MQ_copy_handlers(handlers); - GNUNET_assert (GNUNET_OK == open_port_cb (h, &p->id, p)); + GNUNET_assert(GNUNET_OK == open_port_cb(h, &p->id, p)); return p; } @@ -1066,45 +1062,45 @@ GNUNET_CADET_open_port (struct GNUNET_CADET_Handle *h, * @return Handle to the channel. */ struct GNUNET_CADET_Channel * -GNUNET_CADET_channel_create (struct GNUNET_CADET_Handle *h, - void *channel_cls, - const struct GNUNET_PeerIdentity *destination, - const struct GNUNET_HashCode *port, - GNUNET_CADET_WindowSizeEventHandler window_changes, - GNUNET_CADET_DisconnectEventHandler disconnects, - const struct GNUNET_MQ_MessageHandler *handlers) +GNUNET_CADET_channel_create(struct GNUNET_CADET_Handle *h, + void *channel_cls, + const struct GNUNET_PeerIdentity *destination, + const struct GNUNET_HashCode *port, + GNUNET_CADET_WindowSizeEventHandler window_changes, + GNUNET_CADET_DisconnectEventHandler disconnects, + const struct GNUNET_MQ_MessageHandler *handlers) { struct GNUNET_CADET_Channel *ch; struct GNUNET_CADET_LocalChannelCreateMessage *msg; struct GNUNET_MQ_Envelope *env; - GNUNET_assert (NULL != disconnects); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Creating channel to peer %s at port %s\n", - GNUNET_i2s (destination), - GNUNET_h2s (port)); - ch = create_channel (h, NULL); + GNUNET_assert(NULL != disconnects); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Creating channel to peer %s at port %s\n", + GNUNET_i2s(destination), + GNUNET_h2s(port)); + ch = create_channel(h, NULL); ch->ctx = channel_cls; ch->peer = *destination; ch->window_changes = window_changes; ch->disconnects = disconnects; /* Create MQ for channel */ - ch->mq = GNUNET_MQ_queue_for_callbacks (&cadet_mq_send_impl, - &cadet_mq_destroy_impl, - &cadet_mq_cancel_impl, - ch, - handlers, - &cadet_mq_error_handler, - ch); - GNUNET_MQ_set_handlers_closure (ch->mq, channel_cls); + ch->mq = GNUNET_MQ_queue_for_callbacks(&cadet_mq_send_impl, + &cadet_mq_destroy_impl, + &cadet_mq_cancel_impl, + ch, + handlers, + &cadet_mq_error_handler, + ch); + GNUNET_MQ_set_handlers_closure(ch->mq, channel_cls); /* Request channel creation to service */ - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE); msg->ccn = ch->ccn; msg->port = *port; msg->peer = *destination; - GNUNET_MQ_send (h->mq, env); + GNUNET_MQ_send(h->mq, env); return ch; } @@ -1117,7 +1113,7 @@ GNUNET_CADET_channel_create (struct GNUNET_CADET_Handle *h, * @return NULL if @a channel is not yet connected. */ struct GNUNET_MQ_Handle * -GNUNET_CADET_get_mq (const struct GNUNET_CADET_Channel *channel) +GNUNET_CADET_get_mq(const struct GNUNET_CADET_Channel *channel) { return channel->mq; } diff --git a/src/cadet/cadet_api_get_channel.c b/src/cadet/cadet_api_get_channel.c index 81f0691f1..5479f4238 100644 --- a/src/cadet/cadet_api_get_channel.c +++ b/src/cadet/cadet_api_get_channel.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/cadet_api_get_channel.c * @brief cadet api: client implementation of cadet service @@ -34,9 +34,7 @@ /** * Operation handle. */ -struct GNUNET_CADET_ChannelMonitor -{ - +struct GNUNET_CADET_ChannelMonitor { /** * Channel callback. */ @@ -56,7 +54,7 @@ struct GNUNET_CADET_ChannelMonitor * Message queue to talk to CADET service. */ struct GNUNET_MQ_Handle *mq; - + /** * Task to reconnect. */ @@ -71,7 +69,6 @@ struct GNUNET_CADET_ChannelMonitor * Peer we want information about. */ struct GNUNET_PeerIdentity peer; - }; @@ -84,11 +81,11 @@ struct GNUNET_CADET_ChannelMonitor * #GNUNET_SYSERR otherwise */ static int -check_channel_info (void *cls, - const struct GNUNET_CADET_ChannelInfoMessage *message) +check_channel_info(void *cls, + const struct GNUNET_CADET_ChannelInfoMessage *message) { - (void) cls; - + (void)cls; + return GNUNET_OK; } @@ -96,39 +93,39 @@ check_channel_info (void *cls, /** * Process a local peer info reply, pass info to the user. * - * @param cls Closure + * @param cls Closure * @param message Message itself. */ static void -handle_channel_info (void *cls, - const struct GNUNET_CADET_ChannelInfoMessage *message) +handle_channel_info(void *cls, + const struct GNUNET_CADET_ChannelInfoMessage *message) { struct GNUNET_CADET_ChannelMonitor *cm = cls; struct GNUNET_CADET_ChannelInternals ci; ci.root = message->root; ci.dest = message->dest; - cm->channel_cb (cm->channel_cb_cls, - &ci); - GNUNET_CADET_get_channel_cancel (cm); + cm->channel_cb(cm->channel_cb_cls, + &ci); + GNUNET_CADET_get_channel_cancel(cm); } /** * Process a local peer info reply, pass info to the user. * - * @param cls Closure + * @param cls Closure * @param message Message itself. */ static void -handle_channel_info_end (void *cls, - const struct GNUNET_MessageHeader *message) +handle_channel_info_end(void *cls, + const struct GNUNET_MessageHeader *message) { struct GNUNET_CADET_ChannelMonitor *cm = cls; - cm->channel_cb (cm->channel_cb_cls, - NULL); - GNUNET_CADET_get_channel_cancel (cm); + cm->channel_cb(cm->channel_cb_cls, + NULL); + GNUNET_CADET_get_channel_cancel(cm); } @@ -138,7 +135,7 @@ handle_channel_info_end (void *cls, * @param cls a `struct GNUNET_CADET_ChannelMonitor` operation */ static void -reconnect (void *cls); +reconnect(void *cls); /** @@ -148,18 +145,18 @@ reconnect (void *cls); * @param error error code from MQ */ static void -error_handler (void *cls, - enum GNUNET_MQ_Error error) +error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_CADET_ChannelMonitor *cm = cls; - GNUNET_MQ_destroy (cm->mq); + GNUNET_MQ_destroy(cm->mq); cm->mq = NULL; - cm->backoff = GNUNET_TIME_randomized_backoff (cm->backoff, - GNUNET_TIME_UNIT_MINUTES); - cm->reconnect_task = GNUNET_SCHEDULER_add_delayed (cm->backoff, - &reconnect, - cm); + cm->backoff = GNUNET_TIME_randomized_backoff(cm->backoff, + GNUNET_TIME_UNIT_MINUTES); + cm->reconnect_task = GNUNET_SCHEDULER_add_delayed(cm->backoff, + &reconnect, + cm); } @@ -169,36 +166,36 @@ error_handler (void *cls, * @param cls a `struct GNUNET_CADET_ChannelMonitor` operation */ static void -reconnect (void *cls) +reconnect(void *cls) { struct GNUNET_CADET_ChannelMonitor *cm = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (channel_info_end, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNEL_END, - struct GNUNET_MessageHeader, - cm), - GNUNET_MQ_hd_var_size (channel_info, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNEL, - struct GNUNET_CADET_ChannelInfoMessage, - cm), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(channel_info_end, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNEL_END, + struct GNUNET_MessageHeader, + cm), + GNUNET_MQ_hd_var_size(channel_info, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNEL, + struct GNUNET_CADET_ChannelInfoMessage, + cm), + GNUNET_MQ_handler_end() }; struct GNUNET_CADET_RequestChannelInfoMessage *msg; struct GNUNET_MQ_Envelope *env; - + cm->reconnect_task = NULL; - cm->mq = GNUNET_CLIENT_connect (cm->cfg, - "cadet", - handlers, - &error_handler, - cm); + cm->mq = GNUNET_CLIENT_connect(cm->cfg, + "cadet", + handlers, + &error_handler, + cm); if (NULL == cm->mq) - return; - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_CHANNEL); + return; + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_CHANNEL); msg->target = cm->peer; - GNUNET_MQ_send (cm->mq, - env); + GNUNET_MQ_send(cm->mq, + env); } @@ -212,29 +209,29 @@ reconnect (void *cls) * @return NULL on error */ struct GNUNET_CADET_ChannelMonitor * -GNUNET_CADET_get_channel (const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_PeerIdentity *peer, - GNUNET_CADET_ChannelCB callback, - void *callback_cls) +GNUNET_CADET_get_channel(const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_PeerIdentity *peer, + GNUNET_CADET_ChannelCB callback, + void *callback_cls) { struct GNUNET_CADET_ChannelMonitor *cm; if (NULL == callback) - { - GNUNET_break (0); - return NULL; - } - cm = GNUNET_new (struct GNUNET_CADET_ChannelMonitor); + { + GNUNET_break(0); + return NULL; + } + cm = GNUNET_new(struct GNUNET_CADET_ChannelMonitor); cm->channel_cb = callback; cm->channel_cb_cls = callback_cls; cm->cfg = cfg; cm->peer = *peer; - reconnect (cm); + reconnect(cm); if (NULL == cm->mq) - { - GNUNET_free (cm); - return NULL; - } + { + GNUNET_free(cm); + return NULL; + } return cm; } @@ -246,15 +243,15 @@ GNUNET_CADET_get_channel (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return Closure that was given to #GNUNET_CADET_get_channel(). */ void * -GNUNET_CADET_get_channel_cancel (struct GNUNET_CADET_ChannelMonitor *cm) +GNUNET_CADET_get_channel_cancel(struct GNUNET_CADET_ChannelMonitor *cm) { void *ret = cm->channel_cb_cls; if (NULL != cm->mq) - GNUNET_MQ_destroy (cm->mq); + GNUNET_MQ_destroy(cm->mq); if (NULL != cm->reconnect_task) - GNUNET_SCHEDULER_cancel (cm->reconnect_task); - GNUNET_free (cm); + GNUNET_SCHEDULER_cancel(cm->reconnect_task); + GNUNET_free(cm); return ret; } diff --git a/src/cadet/cadet_api_get_path.c b/src/cadet/cadet_api_get_path.c index fcc79c3d5..0f18014c3 100644 --- a/src/cadet/cadet_api_get_path.c +++ b/src/cadet/cadet_api_get_path.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/cadet_api_get_path.c * @brief cadet api: client implementation of cadet service @@ -34,9 +34,7 @@ /** * Operation handle. */ -struct GNUNET_CADET_GetPath -{ - +struct GNUNET_CADET_GetPath { /** * Monitor callback */ @@ -71,7 +69,6 @@ struct GNUNET_CADET_GetPath * Peer we want information about. */ struct GNUNET_PeerIdentity id; - }; @@ -84,24 +81,24 @@ struct GNUNET_CADET_GetPath * #GNUNET_SYSERR otherwise */ static int -check_get_path (void *cls, - const struct GNUNET_CADET_LocalInfoPath *message) +check_get_path(void *cls, + const struct GNUNET_CADET_LocalInfoPath *message) { - size_t msize = sizeof (struct GNUNET_CADET_LocalInfoPath); + size_t msize = sizeof(struct GNUNET_CADET_LocalInfoPath); size_t esize; - (void) cls; - esize = ntohs (message->header.size); + (void)cls; + esize = ntohs(message->header.size); if (esize < msize) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (0 != ((esize - msize) % sizeof (struct GNUNET_PeerIdentity))) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (0 != ((esize - msize) % sizeof(struct GNUNET_PeerIdentity))) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -113,19 +110,19 @@ check_get_path (void *cls, * @param message Message itself. */ static void -handle_get_path (void *cls, - const struct GNUNET_CADET_LocalInfoPath *message) +handle_get_path(void *cls, + const struct GNUNET_CADET_LocalInfoPath *message) { struct GNUNET_CADET_GetPath *gp = cls; struct GNUNET_CADET_PeerPathDetail ppd; ppd.peer = gp->id; - ppd.path = (const struct GNUNET_PeerIdentity *) &message[1]; - ppd.target_offset = ntohl (message->off); - ppd.path_length = (ntohs (message->header.size) - sizeof (*message)) - / sizeof (struct GNUNET_PeerIdentity); - gp->path_cb (gp->path_cb_cls, - &ppd); + ppd.path = (const struct GNUNET_PeerIdentity *)&message[1]; + ppd.target_offset = ntohl(message->off); + ppd.path_length = (ntohs(message->header.size) - sizeof(*message)) + / sizeof(struct GNUNET_PeerIdentity); + gp->path_cb(gp->path_cb_cls, + &ppd); } @@ -136,15 +133,15 @@ handle_get_path (void *cls, * @param message Message itself. */ static void -handle_get_path_end (void *cls, - const struct GNUNET_MessageHeader *message) +handle_get_path_end(void *cls, + const struct GNUNET_MessageHeader *message) { struct GNUNET_CADET_GetPath *gp = cls; - (void) message; - gp->path_cb (gp->path_cb_cls, - NULL); - GNUNET_CADET_get_path_cancel (gp); + (void)message; + gp->path_cb(gp->path_cb_cls, + NULL); + GNUNET_CADET_get_path_cancel(gp); } @@ -154,7 +151,7 @@ handle_get_path_end (void *cls, * @param cls a `struct GNUNET_CADET_GetPath` operation */ static void -reconnect (void *cls); +reconnect(void *cls); /** @@ -164,18 +161,18 @@ reconnect (void *cls); * @param error error code from MQ */ static void -error_handler (void *cls, - enum GNUNET_MQ_Error error) +error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_CADET_GetPath *gp = cls; - GNUNET_MQ_destroy (gp->mq); + GNUNET_MQ_destroy(gp->mq); gp->mq = NULL; - gp->backoff = GNUNET_TIME_randomized_backoff (gp->backoff, - GNUNET_TIME_UNIT_MINUTES); - gp->reconnect_task = GNUNET_SCHEDULER_add_delayed (gp->backoff, - &reconnect, - gp); + gp->backoff = GNUNET_TIME_randomized_backoff(gp->backoff, + GNUNET_TIME_UNIT_MINUTES); + gp->reconnect_task = GNUNET_SCHEDULER_add_delayed(gp->backoff, + &reconnect, + gp); } @@ -185,36 +182,36 @@ error_handler (void *cls, * @param cls a `struct GNUNET_CADET_GetPath` operation */ static void -reconnect (void *cls) +reconnect(void *cls) { struct GNUNET_CADET_GetPath *gp = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (get_path, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PATH, - struct GNUNET_CADET_LocalInfoPath, - gp), - GNUNET_MQ_hd_fixed_size (get_path_end, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PATH_END, - struct GNUNET_MessageHeader, - gp), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(get_path, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PATH, + struct GNUNET_CADET_LocalInfoPath, + gp), + GNUNET_MQ_hd_fixed_size(get_path_end, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PATH_END, + struct GNUNET_MessageHeader, + gp), + GNUNET_MQ_handler_end() }; struct GNUNET_CADET_RequestPathInfoMessage *msg; struct GNUNET_MQ_Envelope *env; gp->reconnect_task = NULL; - gp->mq = GNUNET_CLIENT_connect (gp->cfg, - "cadet", - handlers, - &error_handler, - gp); + gp->mq = GNUNET_CLIENT_connect(gp->cfg, + "cadet", + handlers, + &error_handler, + gp); if (NULL == gp->mq) return; - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_PATH); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_PATH); msg->peer = gp->id; - GNUNET_MQ_send (gp->mq, - env); + GNUNET_MQ_send(gp->mq, + env); } @@ -228,29 +225,29 @@ reconnect (void *cls) * @return NULL on error */ struct GNUNET_CADET_GetPath * -GNUNET_CADET_get_path (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_PeerIdentity *id, - GNUNET_CADET_PathCB callback, - void *callback_cls) +GNUNET_CADET_get_path(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_PeerIdentity *id, + GNUNET_CADET_PathCB callback, + void *callback_cls) { struct GNUNET_CADET_GetPath *gp; if (NULL == callback) - { - GNUNET_break (0); - return NULL; - } - gp = GNUNET_new (struct GNUNET_CADET_GetPath); + { + GNUNET_break(0); + return NULL; + } + gp = GNUNET_new(struct GNUNET_CADET_GetPath); gp->path_cb = callback; gp->path_cb_cls = callback_cls; gp->cfg = cfg; gp->id = *id; - reconnect (gp); + reconnect(gp); if (NULL == gp->mq) - { - GNUNET_free (gp); - return NULL; - } + { + GNUNET_free(gp); + return NULL; + } return gp; } @@ -262,15 +259,15 @@ GNUNET_CADET_get_path (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return closure from #GNUNET_CADET_get_path(). */ void * -GNUNET_CADET_get_path_cancel (struct GNUNET_CADET_GetPath *gp) +GNUNET_CADET_get_path_cancel(struct GNUNET_CADET_GetPath *gp) { void *ret = gp->path_cb_cls; if (NULL != gp->mq) - GNUNET_MQ_destroy (gp->mq); + GNUNET_MQ_destroy(gp->mq); if (NULL != gp->reconnect_task) - GNUNET_SCHEDULER_cancel (gp->reconnect_task); - GNUNET_free (gp); + GNUNET_SCHEDULER_cancel(gp->reconnect_task); + GNUNET_free(gp); return ret; } diff --git a/src/cadet/cadet_api_helper.c b/src/cadet/cadet_api_helper.c index 6f7634068..78e5eb45c 100644 --- a/src/cadet/cadet_api_helper.c +++ b/src/cadet/cadet_api_helper.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/cadet_api_helper.c * @brief cadet api: client implementation of cadet service @@ -41,15 +41,15 @@ * @return A GNUNET_HashCode usable for the new CADET API. */ const struct GNUNET_HashCode * -GC_u2h (uint32_t port) +GC_u2h(uint32_t port) { static struct GNUNET_HashCode hash; - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "This is a transitional function, use proper crypto hashes as CADET ports\n"); - GNUNET_CRYPTO_hash (&port, - sizeof (port), - &hash); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "This is a transitional function, use proper crypto hashes as CADET ports\n"); + GNUNET_CRYPTO_hash(&port, + sizeof(port), + &hash); return &hash; } diff --git a/src/cadet/cadet_api_list_peers.c b/src/cadet/cadet_api_list_peers.c index 4dc6d02f5..65e9ad4da 100644 --- a/src/cadet/cadet_api_list_peers.c +++ b/src/cadet/cadet_api_list_peers.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/cadet_api_list_peers.c * @brief cadet api: client implementation of cadet service @@ -34,9 +34,7 @@ /** * Operation handle. */ -struct GNUNET_CADET_PeersLister -{ - +struct GNUNET_CADET_PeersLister { /** * Monitor callback */ @@ -66,7 +64,6 @@ struct GNUNET_CADET_PeersLister * Backoff for reconnect attempts. */ struct GNUNET_TIME_Relative backoff; - }; @@ -77,18 +74,18 @@ struct GNUNET_CADET_PeersLister * @param info Message itself. */ static void -handle_get_peers (void *cls, - const struct GNUNET_CADET_LocalInfoPeers *info) +handle_get_peers(void *cls, + const struct GNUNET_CADET_LocalInfoPeers *info) { struct GNUNET_CADET_PeersLister *pl = cls; struct GNUNET_CADET_PeerListEntry ple; ple.peer = info->destination; - ple.have_tunnel = (int) ntohs (info->tunnel); - ple.n_paths = (unsigned int) ntohs (info->paths); - ple.best_path_length = (unsigned int) ntohl (info->best_path_length); - pl->peers_cb (pl->peers_cb_cls, - &ple); + ple.have_tunnel = (int)ntohs(info->tunnel); + ple.n_paths = (unsigned int)ntohs(info->paths); + ple.best_path_length = (unsigned int)ntohl(info->best_path_length); + pl->peers_cb(pl->peers_cb_cls, + &ple); } @@ -99,15 +96,16 @@ handle_get_peers (void *cls, * @param msg Message itself. */ static void -handle_get_peers_end (void *cls, - const struct GNUNET_MessageHeader *msg) +handle_get_peers_end(void *cls, + const struct GNUNET_MessageHeader *msg) { struct GNUNET_CADET_PeersLister *pl = cls; - (void) msg; - pl->peers_cb (pl->peers_cb_cls, - NULL); - GNUNET_CADET_list_peers_cancel (pl); + (void)msg; + + pl->peers_cb(pl->peers_cb_cls, + NULL); + GNUNET_CADET_list_peers_cancel(pl); } @@ -117,7 +115,7 @@ handle_get_peers_end (void *cls, * @param cls a `struct GNUNET_CADET_PeersLister` operation */ static void -reconnect (void *cls); +reconnect(void *cls); /** @@ -127,18 +125,18 @@ reconnect (void *cls); * @param error error code from MQ */ static void -error_handler (void *cls, - enum GNUNET_MQ_Error error) +error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_CADET_PeersLister *pl = cls; - GNUNET_MQ_destroy (pl->mq); + GNUNET_MQ_destroy(pl->mq); pl->mq = NULL; - pl->backoff = GNUNET_TIME_randomized_backoff (pl->backoff, - GNUNET_TIME_UNIT_MINUTES); - pl->reconnect_task = GNUNET_SCHEDULER_add_delayed (pl->backoff, - &reconnect, - pl); + pl->backoff = GNUNET_TIME_randomized_backoff(pl->backoff, + GNUNET_TIME_UNIT_MINUTES); + pl->reconnect_task = GNUNET_SCHEDULER_add_delayed(pl->backoff, + &reconnect, + pl); } @@ -148,35 +146,35 @@ error_handler (void *cls, * @param cls a `struct GNUNET_CADET_PeersLister` operation */ static void -reconnect (void *cls) +reconnect(void *cls) { struct GNUNET_CADET_PeersLister *pl = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (get_peers, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS, - struct GNUNET_CADET_LocalInfoPeers, - pl), - GNUNET_MQ_hd_fixed_size (get_peers_end, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS_END, - struct GNUNET_MessageHeader, - pl), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(get_peers, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS, + struct GNUNET_CADET_LocalInfoPeers, + pl), + GNUNET_MQ_hd_fixed_size(get_peers_end, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS_END, + struct GNUNET_MessageHeader, + pl), + GNUNET_MQ_handler_end() }; struct GNUNET_MessageHeader *msg; struct GNUNET_MQ_Envelope *env; pl->reconnect_task = NULL; - pl->mq = GNUNET_CLIENT_connect (pl->cfg, - "cadet", - handlers, - &error_handler, - pl); + pl->mq = GNUNET_CLIENT_connect(pl->cfg, + "cadet", + handlers, + &error_handler, + pl); if (NULL == pl->mq) return; - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_PEERS); - GNUNET_MQ_send (pl->mq, - env); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_PEERS); + GNUNET_MQ_send(pl->mq, + env); } @@ -191,27 +189,27 @@ reconnect (void *cls) * @return NULL on error */ struct GNUNET_CADET_PeersLister * -GNUNET_CADET_list_peers (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_CADET_PeersCB callback, - void *callback_cls) +GNUNET_CADET_list_peers(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_CADET_PeersCB callback, + void *callback_cls) { struct GNUNET_CADET_PeersLister *pl; if (NULL == callback) - { - GNUNET_break (0); - return NULL; - } - pl = GNUNET_new (struct GNUNET_CADET_PeersLister); + { + GNUNET_break(0); + return NULL; + } + pl = GNUNET_new(struct GNUNET_CADET_PeersLister); pl->peers_cb = callback; pl->peers_cb_cls = callback_cls; pl->cfg = cfg; - reconnect (pl); + reconnect(pl); if (NULL == pl->mq) - { - GNUNET_free (pl); - return NULL; - } + { + GNUNET_free(pl); + return NULL; + } return pl; } @@ -223,15 +221,15 @@ GNUNET_CADET_list_peers (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return Closure given to GNUNET_CADET_get_peers(). */ void * -GNUNET_CADET_list_peers_cancel (struct GNUNET_CADET_PeersLister *pl) +GNUNET_CADET_list_peers_cancel(struct GNUNET_CADET_PeersLister *pl) { void *ret = pl->peers_cb_cls; if (NULL != pl->mq) - GNUNET_MQ_destroy (pl->mq); + GNUNET_MQ_destroy(pl->mq); if (NULL != pl->reconnect_task) - GNUNET_SCHEDULER_cancel (pl->reconnect_task); - GNUNET_free (pl); + GNUNET_SCHEDULER_cancel(pl->reconnect_task); + GNUNET_free(pl); return ret; } diff --git a/src/cadet/cadet_api_list_tunnels.c b/src/cadet/cadet_api_list_tunnels.c index a2ba65993..2ea8cf26c 100644 --- a/src/cadet/cadet_api_list_tunnels.c +++ b/src/cadet/cadet_api_list_tunnels.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/cadet_api_list_tunnels.c * @brief cadet api: client implementation of cadet service @@ -34,9 +34,7 @@ /** * Operation handle. */ -struct GNUNET_CADET_ListTunnels -{ - +struct GNUNET_CADET_ListTunnels { /** * Monitor callback */ @@ -46,7 +44,7 @@ struct GNUNET_CADET_ListTunnels * Info callback closure for @c tunnels_cb. */ void *tunnels_cb_cls; - + /** * Message queue to talk to CADET service. */ @@ -66,7 +64,6 @@ struct GNUNET_CADET_ListTunnels * Backoff for reconnect attempts. */ struct GNUNET_TIME_Relative backoff; - }; @@ -77,19 +74,19 @@ struct GNUNET_CADET_ListTunnels * @param info Message itself. */ static void -handle_get_tunnels (void *cls, - const struct GNUNET_CADET_LocalInfoTunnel *info) +handle_get_tunnels(void *cls, + const struct GNUNET_CADET_LocalInfoTunnel *info) { struct GNUNET_CADET_ListTunnels *lt = cls; struct GNUNET_CADET_TunnelDetails td; - + td.peer = info->destination; - td.channels = ntohl (info->channels); - td.connections = ntohl (info->connections); - td.estate = ntohs (info->estate); - td.cstate = ntohs (info->cstate); - lt->tunnels_cb (lt->tunnels_cb_cls, - &td); + td.channels = ntohl(info->channels); + td.connections = ntohl(info->connections); + td.estate = ntohs(info->estate); + td.cstate = ntohs(info->cstate); + lt->tunnels_cb(lt->tunnels_cb_cls, + &td); } @@ -100,15 +97,16 @@ handle_get_tunnels (void *cls, * @param message Message itself. */ static void -handle_get_tunnels_end (void *cls, - const struct GNUNET_MessageHeader *msg) +handle_get_tunnels_end(void *cls, + const struct GNUNET_MessageHeader *msg) { struct GNUNET_CADET_ListTunnels *lt = cls; - (void) msg; - - lt->tunnels_cb (lt->tunnels_cb_cls, - NULL); - GNUNET_CADET_list_tunnels_cancel (lt); + + (void)msg; + + lt->tunnels_cb(lt->tunnels_cb_cls, + NULL); + GNUNET_CADET_list_tunnels_cancel(lt); } @@ -118,7 +116,7 @@ handle_get_tunnels_end (void *cls, * @param cls a `struct GNUNET_CADET_ListTunnels` operation */ static void -reconnect (void *cls); +reconnect(void *cls); /** @@ -128,18 +126,18 @@ reconnect (void *cls); * @param error error code from MQ */ static void -error_handler (void *cls, - enum GNUNET_MQ_Error error) +error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_CADET_ListTunnels *lt = cls; - GNUNET_MQ_destroy (lt->mq); + GNUNET_MQ_destroy(lt->mq); lt->mq = NULL; - lt->backoff = GNUNET_TIME_randomized_backoff (lt->backoff, - GNUNET_TIME_UNIT_MINUTES); - lt->reconnect_task = GNUNET_SCHEDULER_add_delayed (lt->backoff, - &reconnect, - lt); + lt->backoff = GNUNET_TIME_randomized_backoff(lt->backoff, + GNUNET_TIME_UNIT_MINUTES); + lt->reconnect_task = GNUNET_SCHEDULER_add_delayed(lt->backoff, + &reconnect, + lt); } @@ -149,35 +147,35 @@ error_handler (void *cls, * @param cls a `struct GNUNET_CADET_ListTunnels` operation */ static void -reconnect (void *cls) +reconnect(void *cls) { struct GNUNET_CADET_ListTunnels *lt = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (get_tunnels, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS, - struct GNUNET_CADET_LocalInfoTunnel, - lt), - GNUNET_MQ_hd_fixed_size (get_tunnels_end, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS_END, - struct GNUNET_MessageHeader, - lt), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(get_tunnels, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS, + struct GNUNET_CADET_LocalInfoTunnel, + lt), + GNUNET_MQ_hd_fixed_size(get_tunnels_end, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS_END, + struct GNUNET_MessageHeader, + lt), + GNUNET_MQ_handler_end() }; struct GNUNET_MessageHeader *msg; struct GNUNET_MQ_Envelope *env; lt->reconnect_task = NULL; - lt->mq = GNUNET_CLIENT_connect (lt->cfg, - "cadet", - handlers, - &error_handler, - lt); + lt->mq = GNUNET_CLIENT_connect(lt->cfg, + "cadet", + handlers, + &error_handler, + lt); if (NULL == lt->mq) return; - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_TUNNELS); - GNUNET_MQ_send (lt->mq, - env); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_TUNNELS); + GNUNET_MQ_send(lt->mq, + env); } @@ -192,27 +190,27 @@ reconnect (void *cls) * @return NULL on error */ struct GNUNET_CADET_ListTunnels * -GNUNET_CADET_list_tunnels (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_CADET_TunnelsCB callback, - void *callback_cls) +GNUNET_CADET_list_tunnels(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_CADET_TunnelsCB callback, + void *callback_cls) { struct GNUNET_CADET_ListTunnels *lt; if (NULL == callback) - { - GNUNET_break (0); - return NULL; - } - lt = GNUNET_new (struct GNUNET_CADET_ListTunnels); + { + GNUNET_break(0); + return NULL; + } + lt = GNUNET_new(struct GNUNET_CADET_ListTunnels); lt->tunnels_cb = callback; lt->tunnels_cb_cls = callback_cls; lt->cfg = cfg; - reconnect (lt); + reconnect(lt); if (NULL == lt->mq) - { - GNUNET_free (lt); - return NULL; - } + { + GNUNET_free(lt); + return NULL; + } return lt; } @@ -224,15 +222,15 @@ GNUNET_CADET_list_tunnels (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return Closure given to GNUNET_CADET_list_tunnels(). */ void * -GNUNET_CADET_list_tunnels_cancel (struct GNUNET_CADET_ListTunnels *lt) +GNUNET_CADET_list_tunnels_cancel(struct GNUNET_CADET_ListTunnels *lt) { void *ret = lt->tunnels_cb_cls; if (NULL != lt->mq) - GNUNET_MQ_destroy (lt->mq); + GNUNET_MQ_destroy(lt->mq); if (NULL != lt->reconnect_task) - GNUNET_SCHEDULER_cancel (lt->reconnect_task); - GNUNET_free (lt); + GNUNET_SCHEDULER_cancel(lt->reconnect_task); + GNUNET_free(lt); return ret; } diff --git a/src/cadet/cadet_protocol.h b/src/cadet/cadet_protocol.h index 762babb8a..6252a1da5 100644 --- a/src/cadet/cadet_protocol.h +++ b/src/cadet/cadet_protocol.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/cadet_protocol.h @@ -46,7 +46,7 @@ struct GNUNET_CADET_TunnelMessage; extern "C" { #if 0 - /* keep Emacsens' auto-indent happy */ +/* keep Emacsens' auto-indent happy */ } #endif #endif @@ -66,8 +66,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Message for cadet connection creation. */ -struct GNUNET_CADET_ConnectionCreateMessage -{ +struct GNUNET_CADET_ConnectionCreateMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE * @@ -100,8 +99,7 @@ struct GNUNET_CADET_ConnectionCreateMessage /** * Message for ack'ing a connection */ -struct GNUNET_CADET_ConnectionCreateAckMessage -{ +struct GNUNET_CADET_ConnectionCreateAckMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE_ACK */ @@ -116,15 +114,13 @@ struct GNUNET_CADET_ConnectionCreateAckMessage * ID of the connection. */ struct GNUNET_CADET_ConnectionTunnelIdentifier cid; - }; /** * Message for notifying a disconnection in a path */ -struct GNUNET_CADET_ConnectionBrokenMessage -{ +struct GNUNET_CADET_ConnectionBrokenMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN. */ @@ -155,8 +151,7 @@ struct GNUNET_CADET_ConnectionBrokenMessage /** * Message to destroy a connection. */ -struct GNUNET_CADET_ConnectionDestroyMessage -{ +struct GNUNET_CADET_ConnectionDestroyMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY */ @@ -185,8 +180,7 @@ struct GNUNET_CADET_ConnectionDestroyMessage * against the respective #GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED * messages. */ -struct CadetEncryptedMessageIdentifier -{ +struct CadetEncryptedMessageIdentifier { /** * This number is incremented by one per message. It may wrap around. * In network byte order. @@ -199,7 +193,6 @@ struct CadetEncryptedMessageIdentifier * Flags to be used in GNUNET_CADET_KX. */ enum GNUNET_CADET_KX_Flags { - /** * Should the peer reply with its KX details? */ @@ -215,8 +208,7 @@ enum GNUNET_CADET_KX_Flags { /** * Message for a Key eXchange for a tunnel. */ -struct GNUNET_CADET_TunnelKeyExchangeMessage -{ +struct GNUNET_CADET_TunnelKeyExchangeMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX or * #GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH as part @@ -264,7 +256,6 @@ struct GNUNET_CADET_TunnelKeyExchangeMessage * using 'gcry_sexp_sprint'. */ struct GNUNET_CRYPTO_EcdhePublicKey ratchet_key; - }; @@ -272,9 +263,7 @@ struct GNUNET_CADET_TunnelKeyExchangeMessage * Message for a Key eXchange for a tunnel, with authentication. * Used as a response to the initial KX as well as for rekeying. */ -struct GNUNET_CADET_TunnelKeyExchangeAuthMessage -{ - +struct GNUNET_CADET_TunnelKeyExchangeAuthMessage { /** * Message header with key material. */ @@ -294,7 +283,6 @@ struct GNUNET_CADET_TunnelKeyExchangeAuthMessage * signature or payload data. */ struct GNUNET_HashCode auth; - }; @@ -302,9 +290,7 @@ struct GNUNET_CADET_TunnelKeyExchangeAuthMessage * Encrypted axolotl header with numbers that identify which * keys in which ratchet are to be used to decrypt the body. */ -struct GNUNET_CADET_AxHeader -{ - +struct GNUNET_CADET_AxHeader { /** * Number of messages sent with the current ratchet key. */ @@ -319,15 +305,13 @@ struct GNUNET_CADET_AxHeader * Current ratchet key. */ struct GNUNET_CRYPTO_EcdhePublicKey DHRs; - }; /** * Axolotl-encrypted tunnel message with application payload. */ -struct GNUNET_CADET_TunnelEncryptedMessage -{ +struct GNUNET_CADET_TunnelEncryptedMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED */ @@ -370,8 +354,7 @@ struct GNUNET_CADET_TunnelEncryptedMessage /** * Message to create a Channel. */ -struct GNUNET_CADET_ChannelOpenMessage -{ +struct GNUNET_CADET_ChannelOpenMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN */ @@ -398,8 +381,7 @@ struct GNUNET_CADET_ChannelOpenMessage * Message to acknowledge opening a channel of type * #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK. */ -struct GNUNET_CADET_ChannelOpenAckMessage -{ +struct GNUNET_CADET_ChannelOpenAckMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK */ @@ -427,8 +409,7 @@ struct GNUNET_CADET_ChannelOpenAckMessage * Message to destroy a channel of type * #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY. */ -struct GNUNET_CADET_ChannelDestroyMessage -{ +struct GNUNET_CADET_ChannelDestroyMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY */ @@ -449,8 +430,7 @@ struct GNUNET_CADET_ChannelDestroyMessage /** * Number used to uniquely identify messages in a CADET Channel. */ -struct ChannelMessageIdentifier -{ +struct ChannelMessageIdentifier { /** * Unique ID of the message, cycles around, in NBO. */ @@ -461,8 +441,7 @@ struct ChannelMessageIdentifier /** * Message for cadet data traffic. */ -struct GNUNET_CADET_ChannelAppDataMessage -{ +struct GNUNET_CADET_ChannelAppDataMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA. */ @@ -487,8 +466,7 @@ struct GNUNET_CADET_ChannelAppDataMessage /** * Message to acknowledge end-to-end data. */ -struct GNUNET_CADET_ChannelDataAckMessage -{ +struct GNUNET_CADET_ChannelDataAckMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK */ diff --git a/src/cadet/cadet_test_lib.c b/src/cadet/cadet_test_lib.c index db16e4015..ae1eb6f00 100644 --- a/src/cadet/cadet_test_lib.c +++ b/src/cadet/cadet_test_lib.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/cadet_test_lib.c * @author Bartlomiej Polot @@ -31,8 +31,7 @@ /** * Test context for a CADET Test. */ -struct GNUNET_CADET_TEST_Context -{ +struct GNUNET_CADET_TEST_Context { /** * Array of running peers. */ @@ -92,15 +91,13 @@ struct GNUNET_CADET_TEST_Context * Number of ports in #ports. */ unsigned int port_count; - }; /** * Context for a cadet adapter callback. */ -struct GNUNET_CADET_TEST_AdapterContext -{ +struct GNUNET_CADET_TEST_AdapterContext { /** * Peer number for the particular peer. */ @@ -129,33 +126,33 @@ struct GNUNET_CADET_TEST_AdapterContext * @return service handle to return in 'op_result', NULL on error */ static void * -cadet_connect_adapter (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +cadet_connect_adapter(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_CADET_TEST_AdapterContext *actx = cls; struct GNUNET_CADET_TEST_Context *ctx = actx->ctx; struct GNUNET_CADET_Handle *h; - h = GNUNET_CADET_connect (cfg); + h = GNUNET_CADET_connect(cfg); if (NULL == h) - { - GNUNET_break(0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } if (NULL == ctx->ports) return h; - actx->ports = GNUNET_new_array (ctx->port_count, - struct GNUNET_CADET_Port *); + actx->ports = GNUNET_new_array(ctx->port_count, + struct GNUNET_CADET_Port *); for (unsigned int i = 0; i < ctx->port_count; i++) - { - actx->ports[i] = GNUNET_CADET_open_port (h, - ctx->ports[i], - ctx->connects, - (void *) (long) actx->peer, - ctx->window_changes, - ctx->disconnects, - ctx->handlers); - } + { + actx->ports[i] = GNUNET_CADET_open_port(h, + ctx->ports[i], + ctx->connects, + (void *)(long)actx->peer, + ctx->window_changes, + ctx->disconnects, + ctx->handlers); + } return h; } @@ -168,23 +165,23 @@ cadet_connect_adapter (void *cls, * @param op_result service handle returned from the connect adapter */ static void -cadet_disconnect_adapter (void *cls, - void *op_result) +cadet_disconnect_adapter(void *cls, + void *op_result) { struct GNUNET_CADET_Handle *cadet = op_result; struct GNUNET_CADET_TEST_AdapterContext *actx = cls; if (NULL != actx->ports) - { - for (unsigned int i = 0; i < actx->ctx->port_count; i++) { - GNUNET_CADET_close_port (actx->ports[i]); - actx->ports[i] = NULL; + for (unsigned int i = 0; i < actx->ctx->port_count; i++) + { + GNUNET_CADET_close_port(actx->ports[i]); + actx->ports[i] = NULL; + } + GNUNET_free(actx->ports); } - GNUNET_free (actx->ports); - } - GNUNET_free (actx); - GNUNET_CADET_disconnect (cadet); + GNUNET_free(actx); + GNUNET_CADET_disconnect(cadet); } @@ -199,7 +196,7 @@ cadet_disconnect_adapter (void *cls, * NULL if operation has executed successfully. */ static void -cadet_connect_cb (void *cls, +cadet_connect_cb(void *cls, struct GNUNET_TESTBED_Operation *op, void *ca_result, const char *emsg) @@ -207,47 +204,48 @@ cadet_connect_cb (void *cls, struct GNUNET_CADET_TEST_Context *ctx = cls; if (NULL != emsg) - { - fprintf (stderr, - "Failed to connect to CADET service: %s\n", - emsg); - GNUNET_SCHEDULER_shutdown (); - return; - } - for (unsigned int i = 0; i < ctx->num_peers; i++) - if (op == ctx->ops[i]) { - ctx->cadets[i] = ca_result; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "...cadet %u connected\n", - i); + fprintf(stderr, + "Failed to connect to CADET service: %s\n", + emsg); + GNUNET_SCHEDULER_shutdown(); + return; } + for (unsigned int i = 0; i < ctx->num_peers; i++) + if (op == ctx->ops[i]) + { + ctx->cadets[i] = ca_result; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "...cadet %u connected\n", + i); + } for (unsigned int i = 0; i < ctx->num_peers; i++) if (NULL == ctx->cadets[i]) - return; /* still some CADET connections missing */ + return; + /* still some CADET connections missing */ /* all CADET connections ready! */ - ctx->app_main (ctx->app_main_cls, - ctx, - ctx->num_peers, - ctx->peers, - ctx->cadets); + ctx->app_main(ctx->app_main_cls, + ctx, + ctx->num_peers, + ctx->peers, + ctx->cadets); } void -GNUNET_CADET_TEST_cleanup (struct GNUNET_CADET_TEST_Context *ctx) +GNUNET_CADET_TEST_cleanup(struct GNUNET_CADET_TEST_Context *ctx) { for (unsigned int i = 0; i < ctx->num_peers; i++) - { - GNUNET_assert (NULL != ctx->ops[i]); - GNUNET_TESTBED_operation_done (ctx->ops[i]); - ctx->ops[i] = NULL; - } - GNUNET_free (ctx->ops); - GNUNET_free (ctx->cadets); - GNUNET_free (ctx->handlers); - GNUNET_free (ctx); - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_assert(NULL != ctx->ops[i]); + GNUNET_TESTBED_operation_done(ctx->ops[i]); + ctx->ops[i] = NULL; + } + GNUNET_free(ctx->ops); + GNUNET_free(ctx->cadets); + GNUNET_free(ctx->handlers); + GNUNET_free(ctx); + GNUNET_SCHEDULER_shutdown(); } @@ -265,7 +263,7 @@ GNUNET_CADET_TEST_cleanup (struct GNUNET_CADET_TEST_Context *ctx) * failed */ static void -cadet_test_run (void *cls, +cadet_test_run(void *cls, struct GNUNET_TESTBED_RunHandle *h, unsigned int num_peers, struct GNUNET_TESTBED_Peer **peers, @@ -275,47 +273,47 @@ cadet_test_run (void *cls, struct GNUNET_CADET_TEST_Context *ctx = cls; if (0 != links_failed) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Some links failed (%u), ending\n", - links_failed); - exit (77); - } - if (num_peers != ctx->num_peers) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Peers started %u/%u, ending\n", - num_peers, - ctx->num_peers); - exit (1); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testbed up, %u peers and %u links\n", - num_peers, - links_succeeded); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Some links failed (%u), ending\n", + links_failed); + exit(77); + } + if (num_peers != ctx->num_peers) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Peers started %u/%u, ending\n", + num_peers, + ctx->num_peers); + exit(1); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testbed up, %u peers and %u links\n", + num_peers, + links_succeeded); ctx->peers = peers; for (unsigned int i = 0; i < num_peers; i++) - { - struct GNUNET_CADET_TEST_AdapterContext *newctx; - - newctx = GNUNET_new (struct GNUNET_CADET_TEST_AdapterContext); - newctx->peer = i; - newctx->ctx = ctx; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Connecting to cadet %u\n", - i); - ctx->ops[i] = GNUNET_TESTBED_service_connect (ctx, - peers[i], - "cadet", - &cadet_connect_cb, - ctx, - &cadet_connect_adapter, - &cadet_disconnect_adapter, - newctx); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "op handle %p\n", - ctx->ops[i]); - } + { + struct GNUNET_CADET_TEST_AdapterContext *newctx; + + newctx = GNUNET_new(struct GNUNET_CADET_TEST_AdapterContext); + newctx->peer = i; + newctx->ctx = ctx; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Connecting to cadet %u\n", + i); + ctx->ops[i] = GNUNET_TESTBED_service_connect(ctx, + peers[i], + "cadet", + &cadet_connect_cb, + ctx, + &cadet_connect_adapter, + &cadet_disconnect_adapter, + newctx); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "op handle %p\n", + ctx->ops[i]); + } } @@ -335,41 +333,41 @@ cadet_test_run (void *cls, * @param ports Ports the peers offer, NULL-terminated. */ void -GNUNET_CADET_TEST_ruN (const char *testname, - const char *cfgfile, - unsigned int num_peers, - GNUNET_CADET_TEST_AppMain tmain, - void *tmain_cls, - GNUNET_CADET_ConnectEventHandler connects, - GNUNET_CADET_WindowSizeEventHandler window_changes, - GNUNET_CADET_DisconnectEventHandler disconnects, - struct GNUNET_MQ_MessageHandler *handlers, - const struct GNUNET_HashCode **ports) +GNUNET_CADET_TEST_ruN(const char *testname, + const char *cfgfile, + unsigned int num_peers, + GNUNET_CADET_TEST_AppMain tmain, + void *tmain_cls, + GNUNET_CADET_ConnectEventHandler connects, + GNUNET_CADET_WindowSizeEventHandler window_changes, + GNUNET_CADET_DisconnectEventHandler disconnects, + struct GNUNET_MQ_MessageHandler *handlers, + const struct GNUNET_HashCode **ports) { struct GNUNET_CADET_TEST_Context *ctx; - ctx = GNUNET_new (struct GNUNET_CADET_TEST_Context); + ctx = GNUNET_new(struct GNUNET_CADET_TEST_Context); ctx->num_peers = num_peers; - ctx->ops = GNUNET_new_array (num_peers, - struct GNUNET_TESTBED_Operation *); - ctx->cadets = GNUNET_new_array (num_peers, - struct GNUNET_CADET_Handle *); + ctx->ops = GNUNET_new_array(num_peers, + struct GNUNET_TESTBED_Operation *); + ctx->cadets = GNUNET_new_array(num_peers, + struct GNUNET_CADET_Handle *); ctx->app_main = tmain; ctx->app_main_cls = tmain_cls; ctx->connects = connects; ctx->window_changes = window_changes; ctx->disconnects = disconnects; - ctx->handlers = GNUNET_MQ_copy_handlers (handlers); + ctx->handlers = GNUNET_MQ_copy_handlers(handlers); ctx->ports = ports; ctx->port_count = 0; while (NULL != ctx->ports[ctx->port_count]) ctx->port_count++; - GNUNET_TESTBED_test_run (testname, - cfgfile, - num_peers, - 0LL, NULL, NULL, - &cadet_test_run, - ctx); + GNUNET_TESTBED_test_run(testname, + cfgfile, + num_peers, + 0LL, NULL, NULL, + &cadet_test_run, + ctx); } /* end of cadet_test_lib.c */ diff --git a/src/cadet/cadet_test_lib.h b/src/cadet/cadet_test_lib.h index 69c519d07..f526831a6 100644 --- a/src/cadet/cadet_test_lib.h +++ b/src/cadet/cadet_test_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/cadet_test_lib.h * @author Bartlomiej Polot @@ -52,10 +52,10 @@ struct GNUNET_CADET_TEST_Context; * @param cadets Handle to each of the CADETs of the peers. */ typedef void (*GNUNET_CADET_TEST_AppMain) (void *cls, - struct GNUNET_CADET_TEST_Context *ctx, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - struct GNUNET_CADET_Handle **cadets); + struct GNUNET_CADET_TEST_Context *ctx, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + struct GNUNET_CADET_Handle **cadets); /** @@ -74,16 +74,16 @@ typedef void (*GNUNET_CADET_TEST_AppMain) (void *cls, * @param ports Ports the peers offer, NULL-terminated. */ void -GNUNET_CADET_TEST_ruN (const char *testname, - const char *cfgfile, - unsigned int num_peers, - GNUNET_CADET_TEST_AppMain tmain, - void *tmain_cls, - GNUNET_CADET_ConnectEventHandler connects, - GNUNET_CADET_WindowSizeEventHandler window_changes, - GNUNET_CADET_DisconnectEventHandler disconnects, - struct GNUNET_MQ_MessageHandler *handlers, - const struct GNUNET_HashCode **ports); +GNUNET_CADET_TEST_ruN(const char *testname, + const char *cfgfile, + unsigned int num_peers, + GNUNET_CADET_TEST_AppMain tmain, + void *tmain_cls, + GNUNET_CADET_ConnectEventHandler connects, + GNUNET_CADET_WindowSizeEventHandler window_changes, + GNUNET_CADET_DisconnectEventHandler disconnects, + struct GNUNET_MQ_MessageHandler *handlers, + const struct GNUNET_HashCode **ports); /** * Clean up the testbed. @@ -91,7 +91,7 @@ GNUNET_CADET_TEST_ruN (const char *testname, * @param ctx handle for the testbed */ void -GNUNET_CADET_TEST_cleanup (struct GNUNET_CADET_TEST_Context *ctx); +GNUNET_CADET_TEST_cleanup(struct GNUNET_CADET_TEST_Context *ctx); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/cadet/desirability_table.c b/src/cadet/desirability_table.c index 21ec3e388..5c23de76b 100644 --- a/src/cadet/desirability_table.c +++ b/src/cadet/desirability_table.c @@ -8,28 +8,26 @@ #include int -main () +main() { - for (unsigned int num_alts=1; num_alts<10; num_alts++) - for (unsigned int off=0; off<10; off++) - for (double delta=-(int) off;delta<=5;delta += 0.25) - { - double weight_alts; - - if (delta <= - 1.0) - weight_alts = - 1.0 * num_alts / delta; /* discount alternative paths */ - else if (delta >= 1.0) - weight_alts = 1.0 * num_alts * delta; /* overcount alternative paths */ - else - weight_alts = 1.0 * num_alts; /* count alternative paths normally */ - - fprintf (stderr, - "Paths: %u Offset: %u Delta: %5.2f SCORE: %f\n", - num_alts, - off, - delta, - ((off + 1.0) / (weight_alts * weight_alts))); - } + for (unsigned int num_alts = 1; num_alts < 10; num_alts++) + for (unsigned int off = 0; off < 10; off++) + for (double delta = -(int)off; delta <= 5; delta += 0.25) + { + double weight_alts; + if (delta <= -1.0) + weight_alts = -1.0 * num_alts / delta; /* discount alternative paths */ + else if (delta >= 1.0) + weight_alts = 1.0 * num_alts * delta; /* overcount alternative paths */ + else + weight_alts = 1.0 * num_alts; /* count alternative paths normally */ + fprintf(stderr, + "Paths: %u Offset: %u Delta: %5.2f SCORE: %f\n", + num_alts, + off, + delta, + ((off + 1.0) / (weight_alts * weight_alts))); + } } diff --git a/src/cadet/gnunet-cadet-profiler.c b/src/cadet/gnunet-cadet-profiler.c index 34ea53a57..b3e7fa30d 100644 --- a/src/cadet/gnunet-cadet-profiler.c +++ b/src/cadet/gnunet-cadet-profiler.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-cadet-profiler.c * @@ -41,28 +41,27 @@ /** * How long until we give up on connecting the peers? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 120) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 120) /** * Time to wait for stuff that should be rather fast */ -#define SHORT_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300) +#define SHORT_TIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 300) /** * Total number of rounds. */ -#define number_rounds sizeof(rounds)/sizeof(rounds[0]) +#define number_rounds sizeof(rounds) / sizeof(rounds[0]) /** * Ratio of peers active. First round always is 1.0. */ -static float rounds[] = {0.8, 0.6, 0.8, 0.5, 0.3, 0.8, 0.0}; +static float rounds[] = { 0.8, 0.6, 0.8, 0.5, 0.3, 0.8, 0.0 }; /** * Message type for pings. */ -struct CadetPingMessage -{ +struct CadetPingMessage { /** * Header. Type PING/PONG. */ @@ -87,8 +86,7 @@ struct CadetPingMessage /** * Peer description. */ -struct CadetPeer -{ +struct CadetPeer { /** * Testbed Operation (to get peer id, etc). */ @@ -158,7 +156,6 @@ struct CadetPeer float var[number_rounds]; unsigned int pongs[number_rounds]; unsigned int pings[number_rounds]; - }; /** @@ -256,7 +253,7 @@ static struct GNUNET_SCHEDULER_Task *round_task; * @param cls Closure (unsued). */ static void -start_test (void *cls); +start_test(void *cls); /** @@ -267,12 +264,12 @@ start_test (void *cls); * @return A time between 0 a max-1 ms. */ static struct GNUNET_TIME_Relative -delay_ms_rnd (unsigned int max) +delay_ms_rnd(unsigned int max) { unsigned int rnd; - rnd = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max); - return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, rnd); + rnd = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, max); + return GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, rnd); } @@ -284,7 +281,7 @@ delay_ms_rnd (unsigned int max) * @return Index of peer in peers. */ static unsigned int -get_index (struct CadetPeer *peer) +get_index(struct CadetPeer *peer) { return peer - peers; } @@ -294,23 +291,23 @@ get_index (struct CadetPeer *peer) * Show the results of the test (banwidth acheived) and log them to GAUGER */ static void -show_end_data (void) +show_end_data(void) { struct CadetPeer *peer; unsigned int i; unsigned int j; for (i = 0; i < number_rounds; i++) - { - for (j = 0; j < peers_pinging; j++) { - peer = &peers[j]; - fprintf (stdout, - "ROUND %3u PEER %3u: %10.2f / %10.2f, PINGS: %3u, PONGS: %3u\n", - i, j, peer->mean[i], sqrt (peer->var[i] / (peer->pongs[i] - 1)), - peer->pings[i], peer->pongs[i]); + for (j = 0; j < peers_pinging; j++) + { + peer = &peers[j]; + fprintf(stdout, + "ROUND %3u PEER %3u: %10.2f / %10.2f, PINGS: %3u, PONGS: %3u\n", + i, j, peer->mean[i], sqrt(peer->var[i] / (peer->pongs[i] - 1)), + peer->pings[i], peer->pongs[i]); + } } - } } @@ -320,46 +317,46 @@ show_end_data (void) * @param cls Closure (unused). */ static void -disconnect_cadet_peers (void *cls) +disconnect_cadet_peers(void *cls) { - long line = (long) cls; + long line = (long)cls; unsigned int i; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "disconnecting cadet service, called from line %ld\n", - line); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "disconnecting cadet service, called from line %ld\n", + line); disconnect_task = NULL; for (i = 0; i < peers_total; i++) - { - if (NULL != peers[i].op) - GNUNET_TESTBED_operation_done (peers[i].op); - - if (peers[i].up != GNUNET_YES) - continue; - - if (NULL != peers[i].ch) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "%u: channel %p\n", i, peers[i].ch); - GNUNET_CADET_channel_destroy (peers[i].ch); + if (NULL != peers[i].op) + GNUNET_TESTBED_operation_done(peers[i].op); + + if (peers[i].up != GNUNET_YES) + continue; + + if (NULL != peers[i].ch) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "%u: channel %p\n", i, peers[i].ch); + GNUNET_CADET_channel_destroy(peers[i].ch); + } + if (NULL != peers[i].warmup_ch) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "%u: warmup channel %p\n", + i, peers[i].warmup_ch); + GNUNET_CADET_channel_destroy(peers[i].warmup_ch); + } + if (NULL != peers[i].incoming_ch) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "%u: incoming channel %p\n", + i, peers[i].incoming_ch); + GNUNET_CADET_channel_destroy(peers[i].incoming_ch); + } } - if (NULL != peers[i].warmup_ch) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "%u: warmup channel %p\n", - i, peers[i].warmup_ch); - GNUNET_CADET_channel_destroy (peers[i].warmup_ch); - } - if (NULL != peers[i].incoming_ch) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "%u: incoming channel %p\n", - i, peers[i].incoming_ch); - GNUNET_CADET_channel_destroy (peers[i].incoming_ch); - } - } - GNUNET_CADET_TEST_cleanup (test_ctx); - GNUNET_SCHEDULER_shutdown (); + GNUNET_CADET_TEST_cleanup(test_ctx); + GNUNET_SCHEDULER_shutdown(); } @@ -369,26 +366,26 @@ disconnect_cadet_peers (void *cls) * @param cls Closure (unused). */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Ending test.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Ending test.\n"); if (NULL != disconnect_task) - { - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = GNUNET_SCHEDULER_add_now (&disconnect_cadet_peers, - (void *) __LINE__); - } + { + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = GNUNET_SCHEDULER_add_now(&disconnect_cadet_peers, + (void *)__LINE__); + } if (NULL != round_task) - { - GNUNET_SCHEDULER_cancel (round_task); - round_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(round_task); + round_task = NULL; + } if (NULL != test_task) - { - GNUNET_SCHEDULER_cancel (test_task); - test_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(test_task); + test_task = NULL; + } } @@ -398,14 +395,14 @@ shutdown_task (void *cls) * @param line Line in the code the abort is requested from (__LINE__). */ static void -abort_test (long line) +abort_test(long line) { if (disconnect_task != NULL) - { - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = GNUNET_SCHEDULER_add_now (&disconnect_cadet_peers, - (void *) line); - } + { + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = GNUNET_SCHEDULER_add_now(&disconnect_cadet_peers, + (void *)line); + } } /** @@ -418,16 +415,15 @@ abort_test (long line) * operation has executed successfully. */ static void -stats_cont (void *cls, struct GNUNET_TESTBED_Operation *op, const char *emsg) +stats_cont(void *cls, struct GNUNET_TESTBED_Operation *op, const char *emsg) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "... collecting statistics done.\n"); - GNUNET_TESTBED_operation_done (stats_op); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "... collecting statistics done.\n"); + GNUNET_TESTBED_operation_done(stats_op); if (NULL != disconnect_task) - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = GNUNET_SCHEDULER_add_now (&disconnect_cadet_peers, - (void *) __LINE__); - + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = GNUNET_SCHEDULER_add_now(&disconnect_cadet_peers, + (void *)__LINE__); } @@ -443,20 +439,20 @@ stats_cont (void *cls, struct GNUNET_TESTBED_Operation *op, const char *emsg) * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration */ static int -stats_iterator (void *cls, - const struct GNUNET_TESTBED_Peer *peer, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +stats_iterator(void *cls, + const struct GNUNET_TESTBED_Peer *peer, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { uint32_t i; - i = GNUNET_TESTBED_get_index (peer); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - " STATS %u - %s [%s]: %llu\n", - i, subsystem, name, - (unsigned long long) value); + i = GNUNET_TESTBED_get_index(peer); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + " STATS %u - %s [%s]: %llu\n", + i, subsystem, name, + (unsigned long long)value); return GNUNET_OK; } @@ -468,15 +464,15 @@ stats_iterator (void *cls, * @param cls Closure (NULL). */ static void -collect_stats (void *cls) +collect_stats(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Start collecting statistics...\n"); - stats_op = GNUNET_TESTBED_get_statistics (peers_total, - testbed_handles, - NULL, NULL, - &stats_iterator, - &stats_cont, NULL); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Start collecting statistics...\n"); + stats_op = GNUNET_TESTBED_get_statistics(peers_total, + testbed_handles, + NULL, NULL, + &stats_iterator, + &stats_cont, NULL); } @@ -486,11 +482,11 @@ collect_stats (void *cls) * @param cls Closure (unused). */ static void -finish_profiler (void *cls) +finish_profiler(void *cls) { test_finished = GNUNET_YES; - show_end_data (); - GNUNET_SCHEDULER_add_now (&collect_stats, NULL); + show_end_data(); + GNUNET_SCHEDULER_add_now(&collect_stats, NULL); } @@ -500,7 +496,7 @@ finish_profiler (void *cls) * @param target Desired number of running peers. */ static void -adjust_running_peers (unsigned int target) +adjust_running_peers(unsigned int target) { struct GNUNET_TESTBED_Operation *op; unsigned int delta; @@ -508,58 +504,60 @@ adjust_running_peers (unsigned int target) unsigned int i; unsigned int r; - GNUNET_assert (target <= peers_total); + GNUNET_assert(target <= peers_total); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "adjust peers to %u\n", target); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "adjust peers to %u\n", target); if (target > peers_running) - { - delta = target - peers_running; - run = GNUNET_YES; - } - else - { - delta = peers_running - target; - run = GNUNET_NO; - } - - for (i = 0; i < delta; i++) - { - do { - r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - peers_total - peers_pinging); - r += peers_pinging; - } while (peers[r].up == run || NULL != peers[r].incoming); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "St%s peer %u: %s\n", - run ? "arting" : "opping", r, GNUNET_i2s (&peers[r].id)); - - if (NULL != peers[r].ping_task) { - GNUNET_SCHEDULER_cancel (peers[r].ping_task); - peers[r].ping_task = NULL; + delta = target - peers_running; + run = GNUNET_YES; } - if (NULL != peers[r].ping_ntr) + else { - GNUNET_CADET_notify_transmit_ready_cancel (peers[r].ping_ntr); - peers[r].ping_ntr = NULL; + delta = peers_running - target; + run = GNUNET_NO; } - peers[r].up = run; - if (NULL != peers[r].ch) - GNUNET_CADET_channel_destroy (peers[r].ch); - peers[r].ch = NULL; - if (NULL != peers[r].dest) + for (i = 0; i < delta; i++) { - if (NULL != peers[r].dest->incoming_ch) - GNUNET_CADET_channel_destroy (peers[r].dest->incoming_ch); - peers[r].dest->incoming_ch = NULL; + do + { + r = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + peers_total - peers_pinging); + r += peers_pinging; + } + while (peers[r].up == run || NULL != peers[r].incoming); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "St%s peer %u: %s\n", + run ? "arting" : "opping", r, GNUNET_i2s(&peers[r].id)); + + if (NULL != peers[r].ping_task) + { + GNUNET_SCHEDULER_cancel(peers[r].ping_task); + peers[r].ping_task = NULL; + } + if (NULL != peers[r].ping_ntr) + { + GNUNET_CADET_notify_transmit_ready_cancel(peers[r].ping_ntr); + peers[r].ping_ntr = NULL; + } + peers[r].up = run; + + if (NULL != peers[r].ch) + GNUNET_CADET_channel_destroy(peers[r].ch); + peers[r].ch = NULL; + if (NULL != peers[r].dest) + { + if (NULL != peers[r].dest->incoming_ch) + GNUNET_CADET_channel_destroy(peers[r].dest->incoming_ch); + peers[r].dest->incoming_ch = NULL; + } + + op = GNUNET_TESTBED_peer_manage_service(&peers[r], testbed_handles[r], + "cadet", NULL, NULL, run); + GNUNET_break(NULL != op); + peers_running += run ? 1 : -1; + GNUNET_assert(peers_running > 0); } - - op = GNUNET_TESTBED_peer_manage_service (&peers[r], testbed_handles[r], - "cadet", NULL, NULL, run); - GNUNET_break (NULL != op); - peers_running += run ? 1 : -1; - GNUNET_assert (peers_running > 0); - } } @@ -569,23 +567,23 @@ adjust_running_peers (unsigned int target) * @param cls Closure (round #). */ static void -next_rnd (void *cls) +next_rnd(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "ROUND %u\n", - current_round); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "ROUND %u\n", + current_round); if (0.0 == rounds[current_round]) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Finishing\n"); - GNUNET_SCHEDULER_add_now (&finish_profiler, NULL); - return; - } - adjust_running_peers (rounds[current_round] * peers_total); + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Finishing\n"); + GNUNET_SCHEDULER_add_now(&finish_profiler, NULL); + return; + } + adjust_running_peers(rounds[current_round] * peers_total); current_round++; - round_task = GNUNET_SCHEDULER_add_delayed (round_time, - &next_rnd, - NULL); + round_task = GNUNET_SCHEDULER_add_delayed(round_time, + &next_rnd, + NULL); } @@ -599,7 +597,7 @@ next_rnd (void *cls) * @return Number of bytes written to buf. */ static size_t -tmt_rdy_ping (void *cls, size_t size, void *buf); +tmt_rdy_ping(void *cls, size_t size, void *buf); /** @@ -610,22 +608,22 @@ tmt_rdy_ping (void *cls, size_t size, void *buf); * @param buf Buffer to copy data to. */ static size_t -tmt_rdy_pong (void *cls, size_t size, void *buf) +tmt_rdy_pong(void *cls, size_t size, void *buf) { struct CadetPingMessage *ping = cls; struct CadetPingMessage *pong; if (0 == size || NULL == buf) - { - GNUNET_free (ping); - return 0; - } - pong = (struct CadetPingMessage *) buf; - GNUNET_memcpy (pong, ping, sizeof (*ping)); - pong->header.type = htons (PONG); - - GNUNET_free (ping); - return sizeof (*ping); + { + GNUNET_free(ping); + return 0; + } + pong = (struct CadetPingMessage *)buf; + GNUNET_memcpy(pong, ping, sizeof(*ping)); + pong->header.type = htons(PONG); + + GNUNET_free(ping); + return sizeof(*ping); } @@ -635,22 +633,22 @@ tmt_rdy_pong (void *cls, size_t size, void *buf) * @param cls Closure (peer). */ static void -ping (void *cls) +ping(void *cls) { struct CadetPeer *peer = cls; peer->ping_task = NULL; if (GNUNET_YES == test_finished) return; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "%u -> %u (%u)\n", - get_index (peer), - get_index (peer->dest), - peer->data_sent); - peer->ping_ntr = GNUNET_CADET_notify_transmit_ready (peer->ch, GNUNET_NO, - GNUNET_TIME_UNIT_FOREVER_REL, - sizeof (struct CadetPingMessage), - &tmt_rdy_ping, peer); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "%u -> %u (%u)\n", + get_index(peer), + get_index(peer->dest), + peer->data_sent); + peer->ping_ntr = GNUNET_CADET_notify_transmit_ready(peer->ch, GNUNET_NO, + GNUNET_TIME_UNIT_FOREVER_REL, + sizeof(struct CadetPingMessage), + &tmt_rdy_ping, peer); } /** @@ -660,16 +658,16 @@ ping (void *cls) * @param tc Task context. */ static void -pong (struct GNUNET_CADET_Channel *channel, - const struct CadetPingMessage *ping) +pong(struct GNUNET_CADET_Channel *channel, + const struct CadetPingMessage *ping) { struct CadetPingMessage *copy; - copy = GNUNET_new (struct CadetPingMessage); + copy = GNUNET_new(struct CadetPingMessage); *copy = *ping; - GNUNET_CADET_notify_transmit_ready (channel, GNUNET_NO, + GNUNET_CADET_notify_transmit_ready(channel, GNUNET_NO, GNUNET_TIME_UNIT_FOREVER_REL, - sizeof (struct CadetPingMessage), + sizeof(struct CadetPingMessage), &tmt_rdy_pong, copy); } @@ -682,39 +680,39 @@ pong (struct GNUNET_CADET_Channel *channel, * @param buf Buffer to copy data to. */ static size_t -tmt_rdy_ping (void *cls, size_t size, void *buf) +tmt_rdy_ping(void *cls, size_t size, void *buf) { struct CadetPeer *peer = cls; struct CadetPingMessage *msg = buf; peer->ping_ntr = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "tmt_rdy called, filling buffer\n"); - if (size < sizeof (struct CadetPingMessage) || NULL == buf) - { - GNUNET_break (GNUNET_YES == test_finished); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "size %u, buf %p, data_sent %u, data_received %u\n", - (unsigned int) size, - buf, - peer->data_sent, - peer->data_received); - - return 0; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending: msg %d\n", - peer->data_sent); - msg->header.size = htons (size); - msg->header.type = htons (PING); - msg->counter = htonl (peer->data_sent++); - msg->round_number = htonl (current_round); - msg->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ()); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "tmt_rdy called, filling buffer\n"); + if (size < sizeof(struct CadetPingMessage) || NULL == buf) + { + GNUNET_break(GNUNET_YES == test_finished); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "size %u, buf %p, data_sent %u, data_received %u\n", + (unsigned int)size, + buf, + peer->data_sent, + peer->data_received); + + return 0; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending: msg %d\n", + peer->data_sent); + msg->header.size = htons(size); + msg->header.type = htons(PING); + msg->counter = htonl(peer->data_sent++); + msg->round_number = htonl(current_round); + msg->timestamp = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get()); peer->pings[current_round]++; - peer->ping_task = GNUNET_SCHEDULER_add_delayed (delay_ms_rnd (PING_PERIOD), - &ping, peer); + peer->ping_task = GNUNET_SCHEDULER_add_delayed(delay_ms_rnd(PING_PERIOD), + &ping, peer); - return sizeof (struct CadetPingMessage); + return sizeof(struct CadetPingMessage); } @@ -729,18 +727,18 @@ tmt_rdy_ping (void *cls, size_t size, void *buf) * GNUNET_SYSERR to close it (signal serious error) */ int -ping_handler (void *cls, struct GNUNET_CADET_Channel *channel, - void **channel_ctx, - const struct GNUNET_MessageHeader *message) +ping_handler(void *cls, struct GNUNET_CADET_Channel *channel, + void **channel_ctx, + const struct GNUNET_MessageHeader *message) { - long n = (long) cls; + long n = (long)cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "%u got PING\n", - (unsigned int) n); - GNUNET_CADET_receive_done (channel); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "%u got PING\n", + (unsigned int)n); + GNUNET_CADET_receive_done(channel); if (GNUNET_NO == test_finished) - pong (channel, (struct CadetPingMessage *) message); + pong(channel, (struct CadetPingMessage *)message); return GNUNET_OK; } @@ -757,11 +755,11 @@ ping_handler (void *cls, struct GNUNET_CADET_Channel *channel, * GNUNET_SYSERR to close it (signal serious error) */ int -pong_handler (void *cls, struct GNUNET_CADET_Channel *channel, - void **channel_ctx, - const struct GNUNET_MessageHeader *message) +pong_handler(void *cls, struct GNUNET_CADET_Channel *channel, + void **channel_ctx, + const struct GNUNET_MessageHeader *message) { - long n = (long) cls; + long n = (long)cls; struct CadetPeer *peer; struct CadetPingMessage *msg; struct GNUNET_TIME_Absolute send_time; @@ -769,24 +767,24 @@ pong_handler (void *cls, struct GNUNET_CADET_Channel *channel, unsigned int r /* Ping round */; float delta; - GNUNET_CADET_receive_done (channel); + GNUNET_CADET_receive_done(channel); peer = &peers[n]; - msg = (struct CadetPingMessage *) message; + msg = (struct CadetPingMessage *)message; - send_time = GNUNET_TIME_absolute_ntoh (msg->timestamp); - latency = GNUNET_TIME_absolute_get_duration (send_time); - r = ntohl (msg->round_number); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u <- %u (%u) latency: %s\n", - get_index (peer), - get_index (peer->dest), - (uint32_t) ntohl (msg->counter), - GNUNET_STRINGS_relative_time_to_string (latency, GNUNET_NO)); + send_time = GNUNET_TIME_absolute_ntoh(msg->timestamp); + latency = GNUNET_TIME_absolute_get_duration(send_time); + r = ntohl(msg->round_number); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "%u <- %u (%u) latency: %s\n", + get_index(peer), + get_index(peer->dest), + (uint32_t)ntohl(msg->counter), + GNUNET_STRINGS_relative_time_to_string(latency, GNUNET_NO)); /* Online variance calculation */ peer->pongs[r]++; delta = latency.rel_value_us - peer->mean[r]; - peer->mean[r] = peer->mean[r] + delta/peer->pongs[r]; + peer->mean[r] = peer->mean[r] + delta / peer->pongs[r]; peer->var[r] += delta * (latency.rel_value_us - peer->mean[r]); return GNUNET_OK; @@ -797,9 +795,9 @@ pong_handler (void *cls, struct GNUNET_CADET_Channel *channel, * Handlers, for diverse services */ static struct GNUNET_CADET_MessageHandler handlers[] = { - {&ping_handler, PING, sizeof (struct CadetPingMessage)}, - {&pong_handler, PONG, sizeof (struct CadetPingMessage)}, - {NULL, 0, 0} + { &ping_handler, PING, sizeof(struct CadetPingMessage) }, + { &pong_handler, PONG, sizeof(struct CadetPingMessage) }, + { NULL, 0, 0 } }; @@ -816,41 +814,41 @@ static struct GNUNET_CADET_MessageHandler handlers[] = { * (can be NULL -- that's not an error). */ static void * -incoming_channel (void *cls, struct GNUNET_CADET_Channel *channel, +incoming_channel(void *cls, struct GNUNET_CADET_Channel *channel, const struct GNUNET_PeerIdentity *initiator, const struct GNUNET_HashCode *port, - enum GNUNET_CADET_ChannelOption options) + enum GNUNET_CADET_ChannelOption options) { - long n = (long) cls; + long n = (long)cls; struct CadetPeer *peer; - peer = GNUNET_CONTAINER_multipeermap_get (ids, initiator); - GNUNET_assert (NULL != peer); + peer = GNUNET_CONTAINER_multipeermap_get(ids, initiator); + GNUNET_assert(NULL != peer); if (NULL == peers[n].incoming) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "WARMUP %3u: %u <= %u\n", - peers_warmup, - (unsigned int) n, - get_index (peer)); - peers_warmup++; - if (peers_warmup < peers_total) - return NULL; - if (NULL != test_task) { - GNUNET_SCHEDULER_cancel (test_task); - test_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &start_test, NULL); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "WARMUP %3u: %u <= %u\n", + peers_warmup, + (unsigned int)n, + get_index(peer)); + peers_warmup++; + if (peers_warmup < peers_total) + return NULL; + if (NULL != test_task) + { + GNUNET_SCHEDULER_cancel(test_task); + test_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &start_test, NULL); + } + return NULL; } - return NULL; - } - GNUNET_assert (peer == peers[n].incoming); - GNUNET_assert (peer->dest == &peers[n]); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "%u <= %u %p\n", - (unsigned int) n, - get_index (peer), - channel); + GNUNET_assert(peer == peers[n].incoming); + GNUNET_assert(peer->dest == &peers[n]); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "%u <= %u %p\n", + (unsigned int)n, + get_index(peer), + channel); peers[n].incoming_ch = channel; return NULL; @@ -866,15 +864,15 @@ incoming_channel (void *cls, struct GNUNET_CADET_Channel *channel, * with the channel is stored */ static void -channel_cleaner (void *cls, - const struct GNUNET_CADET_Channel *channel, - void *channel_ctx) +channel_cleaner(void *cls, + const struct GNUNET_CADET_Channel *channel, + void *channel_ctx) { - long n = (long) cls; + long n = (long)cls; struct CadetPeer *peer = &peers[n]; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Channel %p disconnected at peer %ld\n", channel, n); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Channel %p disconnected at peer %ld\n", channel, n); if (peer->ch == channel) peer->ch = NULL; } @@ -888,14 +886,15 @@ channel_cleaner (void *cls, * @return Random peer not yet connected to. */ static struct CadetPeer * -select_random_peer (struct CadetPeer *peer) +select_random_peer(struct CadetPeer *peer) { unsigned int r; do - { - r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, peers_total); - } while (NULL != peers[r].incoming); + { + r = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, peers_total); + } + while (NULL != peers[r].incoming); peers[r].incoming = peer; return &peers[r]; @@ -910,45 +909,45 @@ select_random_peer (struct CadetPeer *peer) * @param cls Closure (unsued). */ static void -start_test (void *cls) +start_test(void *cls) { unsigned long i; test_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Start profiler\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Start profiler\n"); for (i = 0; i < peers_pinging; i++) - { - peers[i].dest = select_random_peer (&peers[i]); - peers[i].ch = GNUNET_CADET_channel_create (peers[i].cadet, NULL, - &peers[i].dest->id, - GC_u2h (1)); - if (NULL == peers[i].ch) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Channel %lu failed\n", i); - GNUNET_CADET_TEST_cleanup (test_ctx); - return; + peers[i].dest = select_random_peer(&peers[i]); + peers[i].ch = GNUNET_CADET_channel_create(peers[i].cadet, NULL, + &peers[i].dest->id, + GC_u2h(1)); + if (NULL == peers[i].ch) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Channel %lu failed\n", i); + GNUNET_CADET_TEST_cleanup(test_ctx); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "%lu => %u %p\n", + i, + get_index(peers[i].dest), + peers[i].ch); + peers[i].ping_task = GNUNET_SCHEDULER_add_delayed(delay_ms_rnd(2000), + &ping, &peers[i]); } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "%lu => %u %p\n", - i, - get_index (peers[i].dest), - peers[i].ch); - peers[i].ping_task = GNUNET_SCHEDULER_add_delayed (delay_ms_rnd (2000), - &ping, &peers[i]); - } peers_running = peers_total; if (NULL != disconnect_task) - GNUNET_SCHEDULER_cancel (disconnect_task); + GNUNET_SCHEDULER_cancel(disconnect_task); disconnect_task = - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(round_time, - number_rounds + 1), - &disconnect_cadet_peers, - (void *) __LINE__); - round_task = GNUNET_SCHEDULER_add_delayed (round_time, - &next_rnd, - NULL); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(round_time, + number_rounds + 1), + &disconnect_cadet_peers, + (void *)__LINE__); + round_task = GNUNET_SCHEDULER_add_delayed(round_time, + &next_rnd, + NULL); } @@ -956,26 +955,26 @@ start_test (void *cls) * Do warmup: create some channels to spread information about the topology. */ static void -warmup (void) +warmup(void) { struct CadetPeer *peer; unsigned int i; for (i = 0; i < peers_total; i++) - { - peer = select_random_peer (NULL); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "WARMUP %u => %u\n", - i, get_index (peer)); - peers[i].warmup_ch = - GNUNET_CADET_channel_create (peers[i].cadet, NULL, &peer->id, - GC_u2h (1)); - if (NULL == peers[i].warmup_ch) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Warmup %u failed\n", i); - GNUNET_CADET_TEST_cleanup (test_ctx); - return; + peer = select_random_peer(NULL); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "WARMUP %u => %u\n", + i, get_index(peer)); + peers[i].warmup_ch = + GNUNET_CADET_channel_create(peers[i].cadet, NULL, &peer->id, + GC_u2h(1)); + if (NULL == peers[i].warmup_ch) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Warmup %u failed\n", i); + GNUNET_CADET_TEST_cleanup(test_ctx); + return; + } } - } } @@ -989,48 +988,48 @@ warmup (void) * NULL if the operation is successfull */ static void -peer_id_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - const struct GNUNET_TESTBED_PeerInformation *pinfo, - const char *emsg) +peer_id_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + const struct GNUNET_TESTBED_PeerInformation *pinfo, + const char *emsg) { - long n = (long) cls; + long n = (long)cls; if (NULL == pinfo || NULL != emsg) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "pi_cb: %s\n", emsg); - abort_test (__LINE__); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "pi_cb: %s\n", emsg); + abort_test(__LINE__); + return; + } peers[n].id = *(pinfo->result.id); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "%ld id: %s\n", - n, - GNUNET_i2s (&peers[n].id)); - GNUNET_break (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put (ids, &peers[n].id, &peers[n], - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)); - - GNUNET_TESTBED_operation_done (peers[n].op); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "%ld id: %s\n", + n, + GNUNET_i2s(&peers[n].id)); + GNUNET_break(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_put(ids, &peers[n].id, &peers[n], + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)); + + GNUNET_TESTBED_operation_done(peers[n].op); peers[n].op = NULL; p_ids++; if (p_ids < peers_total) return; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Got all IDs, starting profiler\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Got all IDs, starting profiler\n"); if (do_warmup) - { - struct GNUNET_TIME_Relative delay; - - warmup(); - delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, - 100 * peers_total); - test_task = GNUNET_SCHEDULER_add_delayed (delay, &start_test, NULL); - return; /* start_test from incoming_channel */ - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Starting in a second...\n"); - test_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &start_test, NULL); + { + struct GNUNET_TIME_Relative delay; + + warmup(); + delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, + 100 * peers_total); + test_task = GNUNET_SCHEDULER_add_delayed(delay, &start_test, NULL); + return; /* start_test from incoming_channel */ + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Starting in a second...\n"); + test_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &start_test, NULL); } @@ -1044,37 +1043,37 @@ peer_id_cb (void *cls, * @param cadetes Handle to each of the CADETs of the peers. */ static void -tmain (void *cls, - struct GNUNET_CADET_TEST_Context *ctx, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **testbed_peers, - struct GNUNET_CADET_Handle **cadetes) +tmain(void *cls, + struct GNUNET_CADET_TEST_Context *ctx, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **testbed_peers, + struct GNUNET_CADET_Handle **cadetes) { unsigned long i; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "test main\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "test main\n"); test_ctx = ctx; - GNUNET_assert (peers_total == num_peers); + GNUNET_assert(peers_total == num_peers); peers_running = num_peers; testbed_handles = testbed_peers; - disconnect_task = GNUNET_SCHEDULER_add_delayed (SHORT_TIME, - &disconnect_cadet_peers, - (void *) __LINE__); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + disconnect_task = GNUNET_SCHEDULER_add_delayed(SHORT_TIME, + &disconnect_cadet_peers, + (void *)__LINE__); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); for (i = 0; i < peers_total; i++) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "requesting id %ld\n", - i); - peers[i].up = GNUNET_YES; - peers[i].cadet = cadetes[i]; - peers[i].op = - GNUNET_TESTBED_peer_get_information (testbed_handles[i], - GNUNET_TESTBED_PIT_IDENTITY, - &peer_id_cb, (void *) i); - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "requested peer ids\n"); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "requesting id %ld\n", + i); + peers[i].up = GNUNET_YES; + peers[i].cadet = cadetes[i]; + peers[i].op = + GNUNET_TESTBED_peer_get_information(testbed_handles[i], + GNUNET_TESTBED_PIT_IDENTITY, + &peer_id_cb, (void *)i); + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "requested peer ids\n"); /* Continues from pi_cb -> do_test */ } @@ -1083,7 +1082,7 @@ tmain (void *cls, * Main: start profiler. */ int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { static const struct GNUNET_HashCode *ports[2]; const char *config_file; @@ -1091,59 +1090,59 @@ main (int argc, char *argv[]) config_file = ".profiler.conf"; if (4 > argc) - { - fprintf (stderr, - "usage: %s ROUND_TIME PEERS PINGS [DO_WARMUP]\n", - argv[0]); - fprintf (stderr, - "example: %s 30s 16 1 Y\n", - argv[0]); - return 1; - } + { + fprintf(stderr, + "usage: %s ROUND_TIME PEERS PINGS [DO_WARMUP]\n", + argv[0]); + fprintf(stderr, + "example: %s 30s 16 1 Y\n", + argv[0]); + return 1; + } if (GNUNET_OK != - GNUNET_STRINGS_fancy_time_to_relative (argv[1], - &round_time)) - { - fprintf (stderr, - "%s is not a valid time\n", - argv[1]); - return 1; - } - - peers_total = atoll (argv[2]); + GNUNET_STRINGS_fancy_time_to_relative(argv[1], + &round_time)) + { + fprintf(stderr, + "%s is not a valid time\n", + argv[1]); + return 1; + } + + peers_total = atoll(argv[2]); if (2 > peers_total) - { - fprintf (stderr, - "%s peers is not valid (> 2)\n", - argv[1]); - return 1; - } - peers = GNUNET_new_array (peers_total, - struct CadetPeer); - peers_pinging = atoll (argv[3]); + { + fprintf(stderr, + "%s peers is not valid (> 2)\n", + argv[1]); + return 1; + } + peers = GNUNET_new_array(peers_total, + struct CadetPeer); + peers_pinging = atoll(argv[3]); if (peers_total < 2 * peers_pinging) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "not enough peers, total should be > 2 * peers_pinging\n"); - return 1; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "not enough peers, total should be > 2 * peers_pinging\n"); + return 1; + } do_warmup = (5 > argc || argv[4][0] != 'N'); - ids = GNUNET_CONTAINER_multipeermap_create (2 * peers_total, - GNUNET_YES); - GNUNET_assert (NULL != ids); + ids = GNUNET_CONTAINER_multipeermap_create(2 * peers_total, + GNUNET_YES); + GNUNET_assert(NULL != ids); p_ids = 0; test_finished = GNUNET_NO; - ports[0] = GC_u2h (1); + ports[0] = GC_u2h(1); ports[1] = 0; - GNUNET_CADET_TEST_run ("cadet-profiler", config_file, peers_total, + GNUNET_CADET_TEST_run("cadet-profiler", config_file, peers_total, &tmain, NULL, /* tmain cls */ &incoming_channel, &channel_cleaner, handlers, ports); - GNUNET_free (peers); + GNUNET_free(peers); return 0; } diff --git a/src/cadet/gnunet-cadet.c b/src/cadet/gnunet-cadet.c index 4e81d52f2..f5cf86211 100644 --- a/src/cadet/gnunet-cadet.c +++ b/src/cadet/gnunet-cadet.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-cadet.c @@ -143,7 +143,7 @@ static unsigned int sent_pkt; * Wait for input on STDIO and send it out over the #ch. */ static void -listen_stdio (void); +listen_stdio(void); /** @@ -154,21 +154,25 @@ listen_stdio (void); * @return Human readable string. */ static const char * -enc_2s (uint16_t status) +enc_2s(uint16_t status) { switch (status) - { - case 0: - return "NULL "; - case 1: - return "KSENT"; - case 2: - return "KRECV"; - case 3: - return "READY"; - default: - return ""; - } + { + case 0: + return "NULL "; + + case 1: + return "KSENT"; + + case 2: + return "KRECV"; + + case 3: + return "READY"; + + default: + return ""; + } } @@ -180,23 +184,28 @@ enc_2s (uint16_t status) * @return Human readable string. */ static const char * -conn_2s (uint16_t status) +conn_2s(uint16_t status) { switch (status) - { - case 0: - return "NEW "; - case 1: - return "SRCH "; - case 2: - return "WAIT "; - case 3: - return "READY"; - case 4: - return "SHUTD"; - default: - return ""; - } + { + case 0: + return "NEW "; + + case 1: + return "SRCH "; + + case 2: + return "WAIT "; + + case 3: + return "READY"; + + case 4: + return "SHUTD"; + + default: + return ""; + } } @@ -206,60 +215,60 @@ conn_2s (uint16_t status) * @param cls Closure (unused). */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Shutdown\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Shutdown\n"); if (NULL != lp) - { - GNUNET_CADET_close_port (lp); - lp = NULL; - } + { + GNUNET_CADET_close_port(lp); + lp = NULL; + } if (NULL != ch) - { - GNUNET_CADET_channel_destroy (ch); - ch = NULL; - } + { + GNUNET_CADET_channel_destroy(ch); + ch = NULL; + } if (NULL != gpo) - { - GNUNET_CADET_get_path_cancel (gpo); - gpo = NULL; - } + { + GNUNET_CADET_get_path_cancel(gpo); + gpo = NULL; + } if (NULL != plo) - { - GNUNET_CADET_list_peers_cancel (plo); - plo = NULL; - } + { + GNUNET_CADET_list_peers_cancel(plo); + plo = NULL; + } if (NULL != tio) - { - GNUNET_CADET_list_tunnels_cancel (tio); - tio = NULL; - } + { + GNUNET_CADET_list_tunnels_cancel(tio); + tio = NULL; + } if (NULL != mh) - { - GNUNET_CADET_disconnect (mh); - mh = NULL; - } + { + GNUNET_CADET_disconnect(mh); + mh = NULL; + } if (NULL != rd_task) - { - GNUNET_SCHEDULER_cancel (rd_task); - rd_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(rd_task); + rd_task = NULL; + } if (NULL != echo_task) - { - GNUNET_SCHEDULER_cancel (echo_task); - echo_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(echo_task); + echo_task = NULL; + } if (NULL != job) - { - GNUNET_SCHEDULER_cancel (job); - job = NULL; - } + { + GNUNET_SCHEDULER_cancel(job); + job = NULL; + } } void -mq_cb (void *cls) +mq_cb(void *cls) { - listen_stdio (); + listen_stdio(); } @@ -269,7 +278,7 @@ mq_cb (void *cls) * @param cls Closure (unused). */ static void -read_stdio (void *cls) +read_stdio(void *cls) { struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; @@ -277,41 +286,41 @@ read_stdio (void *cls) ssize_t data_size; rd_task = NULL; - data_size = read (0, buf, 60000); + data_size = read(0, buf, 60000); if (data_size < 1) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "read() returned %s\n", - strerror (errno)); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Read %u bytes from stdio\n", - (unsigned int) data_size); - env = GNUNET_MQ_msg_extra (msg, data_size, GNUNET_MESSAGE_TYPE_CADET_CLI); - GNUNET_memcpy (&msg[1], buf, data_size); - GNUNET_MQ_send (GNUNET_CADET_get_mq (ch), env); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "read() returned %s\n", + strerror(errno)); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Read %u bytes from stdio\n", + (unsigned int)data_size); + env = GNUNET_MQ_msg_extra(msg, data_size, GNUNET_MESSAGE_TYPE_CADET_CLI); + GNUNET_memcpy(&msg[1], buf, data_size); + GNUNET_MQ_send(GNUNET_CADET_get_mq(ch), env); sent_pkt++; if (GNUNET_NO == echo) - { - // Use MQ's notification if too much data of stdin is pooring in too fast. - if (STREAM_BUFFER_SIZE < sent_pkt) { - GNUNET_MQ_notify_sent (env, mq_cb, cls); - sent_pkt = 0; + // Use MQ's notification if too much data of stdin is pooring in too fast. + if (STREAM_BUFFER_SIZE < sent_pkt) + { + GNUNET_MQ_notify_sent(env, mq_cb, cls); + sent_pkt = 0; + } + else + { + listen_stdio(); + } } - else + else { - listen_stdio (); + echo_time = GNUNET_TIME_absolute_get(); } - } - else - { - echo_time = GNUNET_TIME_absolute_get (); - } } @@ -319,20 +328,20 @@ read_stdio (void *cls) * Wait for input on STDIO and send it out over the #ch. */ static void -listen_stdio () +listen_stdio() { struct GNUNET_NETWORK_FDSet *rs; /* FIXME: why use 'rs' here, seems overly complicated... */ - rs = GNUNET_NETWORK_fdset_create (); - GNUNET_NETWORK_fdset_set_native (rs, 0); /* STDIN */ - rd_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, - GNUNET_TIME_UNIT_FOREVER_REL, - rs, - NULL, - &read_stdio, - NULL); - GNUNET_NETWORK_fdset_destroy (rs); + rs = GNUNET_NETWORK_fdset_create(); + GNUNET_NETWORK_fdset_set_native(rs, 0); /* STDIN */ + rd_task = GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT, + GNUNET_TIME_UNIT_FOREVER_REL, + rs, + NULL, + &read_stdio, + NULL); + GNUNET_NETWORK_fdset_destroy(rs); } @@ -346,12 +355,12 @@ listen_stdio () * @param channel connection to the other end (henceforth invalid) */ static void -channel_ended (void *cls, const struct GNUNET_CADET_Channel *channel) +channel_ended(void *cls, const struct GNUNET_CADET_Channel *channel) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel ended!\n"); - GNUNET_assert (channel == ch); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Channel ended!\n"); + GNUNET_assert(channel == ch); ch = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -370,20 +379,20 @@ channel_ended (void *cls, const struct GNUNET_CADET_Channel *channel) * @return initial channel context for the channel, we use @a channel */ static void * -channel_incoming (void *cls, - struct GNUNET_CADET_Channel *channel, - const struct GNUNET_PeerIdentity *initiator) +channel_incoming(void *cls, + struct GNUNET_CADET_Channel *channel, + const struct GNUNET_PeerIdentity *initiator) { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "Incoming connection from %s\n", - GNUNET_i2s_full (initiator)); - GNUNET_assert (NULL == ch); - GNUNET_assert (NULL != lp); - GNUNET_CADET_close_port (lp); + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "Incoming connection from %s\n", + GNUNET_i2s_full(initiator)); + GNUNET_assert(NULL == ch); + GNUNET_assert(NULL != lp); + GNUNET_CADET_close_port(lp); lp = NULL; ch = channel; if (GNUNET_NO == echo) - listen_stdio (); + listen_stdio(); return channel; } @@ -394,7 +403,7 @@ channel_incoming (void *cls, * @param cls Closure (NULL). */ static void -send_echo (void *cls) +send_echo(void *cls) { struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; @@ -402,8 +411,8 @@ send_echo (void *cls) echo_task = NULL; if (NULL == ch) return; - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CADET_CLI); - GNUNET_MQ_send (GNUNET_CADET_get_mq (ch), env); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_CADET_CLI); + GNUNET_MQ_send(GNUNET_CADET_get_mq(ch), env); } @@ -416,7 +425,7 @@ send_echo (void *cls) * #GNUNET_SYSERR to close it (signal serious error). */ static int -check_data (void *cls, const struct GNUNET_MessageHeader *message) +check_data(void *cls, const struct GNUNET_MessageHeader *message) { return GNUNET_OK; /* all is well-formed */ } @@ -433,59 +442,59 @@ check_data (void *cls, const struct GNUNET_MessageHeader *message) * @param message The actual message. */ static void -handle_data (void *cls, const struct GNUNET_MessageHeader *message) +handle_data(void *cls, const struct GNUNET_MessageHeader *message) { - size_t payload_size = ntohs (message->size) - sizeof (*message); + size_t payload_size = ntohs(message->size) - sizeof(*message); uint16_t len; ssize_t done; uint16_t off; const char *buf; - GNUNET_CADET_receive_done (ch); + GNUNET_CADET_receive_done(ch); if (GNUNET_YES == echo) - { - if (NULL != listen_port) - { - struct GNUNET_MQ_Envelope *env; - struct GNUNET_MessageHeader *msg; - - env = - GNUNET_MQ_msg_extra (msg, payload_size, GNUNET_MESSAGE_TYPE_CADET_CLI); - GNUNET_memcpy (&msg[1], &message[1], payload_size); - GNUNET_MQ_send (GNUNET_CADET_get_mq (ch), env); - return; - } - else { - struct GNUNET_TIME_Relative latency; - - latency = GNUNET_TIME_absolute_get_duration (echo_time); - echo_time = GNUNET_TIME_UNIT_FOREVER_ABS; - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "time: %s\n", - GNUNET_STRINGS_relative_time_to_string (latency, GNUNET_NO)); - echo_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &send_echo, - NULL); + if (NULL != listen_port) + { + struct GNUNET_MQ_Envelope *env; + struct GNUNET_MessageHeader *msg; + + env = + GNUNET_MQ_msg_extra(msg, payload_size, GNUNET_MESSAGE_TYPE_CADET_CLI); + GNUNET_memcpy(&msg[1], &message[1], payload_size); + GNUNET_MQ_send(GNUNET_CADET_get_mq(ch), env); + return; + } + else + { + struct GNUNET_TIME_Relative latency; + + latency = GNUNET_TIME_absolute_get_duration(echo_time); + echo_time = GNUNET_TIME_UNIT_FOREVER_ABS; + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "time: %s\n", + GNUNET_STRINGS_relative_time_to_string(latency, GNUNET_NO)); + echo_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &send_echo, + NULL); + } } - } - len = ntohs (message->size) - sizeof (*message); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got %u bytes\n", len); - buf = (const char *) &message[1]; + len = ntohs(message->size) - sizeof(*message); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Got %u bytes\n", len); + buf = (const char *)&message[1]; off = 0; while (off < len) - { - done = write (1, &buf[off], len - off); - if (done <= 0) { - if (-1 == done) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write"); - GNUNET_SCHEDULER_shutdown (); - return; + done = write(1, &buf[off], len - off); + if (done <= 0) + { + if (-1 == done) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "write"); + GNUNET_SCHEDULER_shutdown(); + return; + } + off += done; } - off += done; - } } @@ -499,19 +508,19 @@ handle_data (void *cls, const struct GNUNET_MessageHeader *message) * @param ple information about peer, or NULL on "EOF". */ static void -peers_callback (void *cls, const struct GNUNET_CADET_PeerListEntry *ple) +peers_callback(void *cls, const struct GNUNET_CADET_PeerListEntry *ple) { if (NULL == ple) - { - plo = NULL; - GNUNET_SCHEDULER_shutdown (); - return; - } - fprintf (stdout, - "%s tunnel: %c, paths: %u\n", - GNUNET_i2s_full (&ple->peer), - ple->have_tunnel ? 'Y' : 'N', - ple->n_paths); + { + plo = NULL; + GNUNET_SCHEDULER_shutdown(); + return; + } + fprintf(stdout, + "%s tunnel: %c, paths: %u\n", + GNUNET_i2s_full(&ple->peer), + ple->have_tunnel ? 'Y' : 'N', + ple->n_paths); } @@ -523,20 +532,20 @@ peers_callback (void *cls, const struct GNUNET_CADET_PeerListEntry *ple) * @param ppd path detail */ static void -path_callback (void *cls, const struct GNUNET_CADET_PeerPathDetail *ppd) +path_callback(void *cls, const struct GNUNET_CADET_PeerPathDetail *ppd) { if (NULL == ppd) - { - gpo = NULL; - GNUNET_SCHEDULER_shutdown (); - return; - } - fprintf (stdout, "Path of length %u: ", ppd->path_length); + { + gpo = NULL; + GNUNET_SCHEDULER_shutdown(); + return; + } + fprintf(stdout, "Path of length %u: ", ppd->path_length); for (unsigned int i = 0; i < ppd->path_length; i++) - fprintf (stdout, - (i == ppd->target_offset) ? "*%s* " : "%s ", - GNUNET_i2s (&ppd->path[i])); - fprintf (stdout, "\n"); + fprintf(stdout, + (i == ppd->target_offset) ? "*%s* " : "%s ", + GNUNET_i2s(&ppd->path[i])); + fprintf(stdout, "\n"); } @@ -547,21 +556,21 @@ path_callback (void *cls, const struct GNUNET_CADET_PeerPathDetail *ppd) * @param td tunnel details */ static void -tunnels_callback (void *cls, const struct GNUNET_CADET_TunnelDetails *td) +tunnels_callback(void *cls, const struct GNUNET_CADET_TunnelDetails *td) { if (NULL == td) - { - tio = NULL; - GNUNET_SCHEDULER_shutdown (); - return; - } - fprintf (stdout, - "%s [ENC: %s, CON: %s] CHs: %u, CONNs: %u\n", - GNUNET_i2s_full (&td->peer), - enc_2s (td->estate), - conn_2s (td->cstate), - td->channels, - td->connections); + { + tio = NULL; + GNUNET_SCHEDULER_shutdown(); + return; + } + fprintf(stdout, + "%s [ENC: %s, CON: %s] CHs: %u, CONNs: %u\n", + GNUNET_i2s_full(&td->peer), + enc_2s(td->estate), + conn_2s(td->cstate), + td->channels, + td->connections); } @@ -571,10 +580,10 @@ tunnels_callback (void *cls, const struct GNUNET_CADET_TunnelDetails *td) * @param cls Closure (unused). */ static void -get_peers (void *cls) +get_peers(void *cls) { job = NULL; - plo = GNUNET_CADET_list_peers (my_cfg, &peers_callback, NULL); + plo = GNUNET_CADET_list_peers(my_cfg, &peers_callback, NULL); } @@ -584,20 +593,20 @@ get_peers (void *cls) * @param cls Closure (unused). */ static void -show_peer (void *cls) +show_peer(void *cls) { struct GNUNET_PeerIdentity pid; job = NULL; - if (GNUNET_OK != GNUNET_CRYPTO_eddsa_public_key_from_string (peer_id, - strlen (peer_id), - &pid.public_key)) - { - fprintf (stderr, _ ("Invalid peer ID `%s'\n"), peer_id); - GNUNET_SCHEDULER_shutdown (); - return; - } - gpo = GNUNET_CADET_get_path (my_cfg, &pid, &path_callback, NULL); + if (GNUNET_OK != GNUNET_CRYPTO_eddsa_public_key_from_string(peer_id, + strlen(peer_id), + &pid.public_key)) + { + fprintf(stderr, _("Invalid peer ID `%s'\n"), peer_id); + GNUNET_SCHEDULER_shutdown(); + return; + } + gpo = GNUNET_CADET_get_path(my_cfg, &pid, &path_callback, NULL); } @@ -607,10 +616,10 @@ show_peer (void *cls) * @param cls Closure (unused). */ static void -get_tunnels (void *cls) +get_tunnels(void *cls) { job = NULL; - tio = GNUNET_CADET_list_tunnels (my_cfg, &tunnels_callback, NULL); + tio = GNUNET_CADET_list_tunnels(my_cfg, &tunnels_callback, NULL); } @@ -620,10 +629,10 @@ get_tunnels (void *cls) * @param cls Closure (unused). */ static void -show_channel (void *cls) +show_channel(void *cls) { job = NULL; - GNUNET_break (0); + GNUNET_break(0); } @@ -633,10 +642,10 @@ show_channel (void *cls) * @param cls Closure (unused). */ static void -show_connection (void *cls) +show_connection(void *cls) { job = NULL; - GNUNET_break (0); + GNUNET_break(0); } @@ -649,17 +658,17 @@ show_connection (void *cls) * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_var_size (data, - GNUNET_MESSAGE_TYPE_CADET_CLI, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_var_size(data, + GNUNET_MESSAGE_TYPE_CADET_CLI, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end() }; /* FIXME add option to monitor apps */ my_cfg = cfg; @@ -670,102 +679,102 @@ run (void *cls, if ((0 != (request_peers | request_tunnels) || NULL != conn_id || NULL != channel_id) && target_id != NULL) - { - fprintf (stderr, - _ ("Extra arguments are not applicable " + { + fprintf(stderr, + _("Extra arguments are not applicable " "in combination with this option.\n")); - return; - } + return; + } if (NULL != peer_id) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Show peer\n"); - job = GNUNET_SCHEDULER_add_now (&show_peer, NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Show peer\n"); + job = GNUNET_SCHEDULER_add_now(&show_peer, NULL); + } else if (NULL != channel_id) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Show channel\n"); - job = GNUNET_SCHEDULER_add_now (&show_channel, NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Show channel\n"); + job = GNUNET_SCHEDULER_add_now(&show_channel, NULL); + } else if (NULL != conn_id) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Show connection\n"); - job = GNUNET_SCHEDULER_add_now (&show_connection, NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Show connection\n"); + job = GNUNET_SCHEDULER_add_now(&show_connection, NULL); + } else if (GNUNET_YES == request_peers) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Show all peers\n"); - job = GNUNET_SCHEDULER_add_now (&get_peers, NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Show all peers\n"); + job = GNUNET_SCHEDULER_add_now(&get_peers, NULL); + } else if (GNUNET_YES == request_tunnels) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Show all tunnels\n"); - job = GNUNET_SCHEDULER_add_now (&get_tunnels, NULL); - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting to CADET service\n"); - mh = GNUNET_CADET_connect (cfg); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); - if (NULL == mh) - { - GNUNET_SCHEDULER_shutdown (); - return; - } - if (NULL != listen_port) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Opening CADET listen port\n"); - GNUNET_CRYPTO_hash (listen_port, strlen (listen_port), &porthash); - lp = GNUNET_CADET_open_port (mh, - &porthash, - &channel_incoming, - NULL, - NULL /* window changes */, - &channel_ended, - handlers); - } - if (NULL != target_id) - { - struct GNUNET_PeerIdentity pid; + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Show all tunnels\n"); + job = GNUNET_SCHEDULER_add_now(&get_tunnels, NULL); + } - if (GNUNET_OK != - GNUNET_CRYPTO_eddsa_public_key_from_string (target_id, - strlen (target_id), - &pid.public_key)) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting to CADET service\n"); + mh = GNUNET_CADET_connect(cfg); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); + if (NULL == mh) { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - _ ("Invalid target `%s'\n"), - target_id); - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); return; } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connecting to `%s:%s'\n", - target_id, - target_port); - GNUNET_CRYPTO_hash (target_port, strlen (target_port), &porthash); - ch = GNUNET_CADET_channel_create (mh, - NULL, - &pid, - &porthash, - NULL /* window changes */, - &channel_ended, - handlers); - if (GNUNET_YES == echo) + if (NULL != listen_port) { - echo_task = GNUNET_SCHEDULER_add_now (&send_echo, NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Opening CADET listen port\n"); + GNUNET_CRYPTO_hash(listen_port, strlen(listen_port), &porthash); + lp = GNUNET_CADET_open_port(mh, + &porthash, + &channel_incoming, + NULL, + NULL /* window changes */, + &channel_ended, + handlers); } - else + if (NULL != target_id) { - listen_stdio (); + struct GNUNET_PeerIdentity pid; + + if (GNUNET_OK != + GNUNET_CRYPTO_eddsa_public_key_from_string(target_id, + strlen(target_id), + &pid.public_key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + _("Invalid target `%s'\n"), + target_id); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connecting to `%s:%s'\n", + target_id, + target_port); + GNUNET_CRYPTO_hash(target_port, strlen(target_port), &porthash); + ch = GNUNET_CADET_channel_create(mh, + NULL, + &pid, + &porthash, + NULL /* window changes */, + &channel_ended, + handlers); + if (GNUNET_YES == echo) + { + echo_task = GNUNET_SCHEDULER_add_now(&send_echo, NULL); + } + else + { + listen_stdio(); + } } - } if ((NULL == lp) && (NULL == job) && (NULL == ch)) - { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, _ ("No action requested\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, _("No action requested\n")); + GNUNET_SCHEDULER_shutdown(); + return; + } } @@ -777,60 +786,61 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { int res; const char helpstr[] = "Create tunnels and retrieve info about CADET's status."; struct GNUNET_GETOPT_CommandLineOption options[] = - {/* I would use the terminology 'circuit' here... --lynX */ - GNUNET_GETOPT_option_string ( - 'C', - "connection", - "CONNECTION_ID", - gettext_noop ("Provide information about a particular connection"), - &conn_id), - GNUNET_GETOPT_option_flag ('e', - "echo", - gettext_noop ("Activate echo mode"), - &echo), - GNUNET_GETOPT_option_string ( - 'o', - "open-port", - "SHARED_SECRET", - gettext_noop ( - "Listen for connections using a shared secret among sender and recipient"), - &listen_port), - GNUNET_GETOPT_option_string ('p', - "peer", - "PEER_ID", - gettext_noop ( - "Provide information about a patricular peer"), - &peer_id), - GNUNET_GETOPT_option_flag ('P', - "peers", - gettext_noop ( - "Provide information about all peers"), - &request_peers), - GNUNET_GETOPT_option_flag ('T', - "tunnels", - gettext_noop ( - "Provide information about all tunnels"), - &request_tunnels), - GNUNET_GETOPT_OPTION_END}; - - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + { /* I would use the terminology 'circuit' here... --lynX */ + GNUNET_GETOPT_option_string( + 'C', + "connection", + "CONNECTION_ID", + gettext_noop("Provide information about a particular connection"), + &conn_id), + GNUNET_GETOPT_option_flag('e', + "echo", + gettext_noop("Activate echo mode"), + &echo), + GNUNET_GETOPT_option_string( + 'o', + "open-port", + "SHARED_SECRET", + gettext_noop( + "Listen for connections using a shared secret among sender and recipient"), + &listen_port), + GNUNET_GETOPT_option_string('p', + "peer", + "PEER_ID", + gettext_noop( + "Provide information about a patricular peer"), + &peer_id), + GNUNET_GETOPT_option_flag('P', + "peers", + gettext_noop( + "Provide information about all peers"), + &request_peers), + GNUNET_GETOPT_option_flag('T', + "tunnels", + gettext_noop( + "Provide information about all tunnels"), + &request_tunnels), + GNUNET_GETOPT_OPTION_END + }; + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; - res = GNUNET_PROGRAM_run (argc, - argv, - "gnunet-cadet (OPTIONS | PEER_ID SHARED_SECRET)", - gettext_noop (helpstr), - options, - &run, - NULL); + res = GNUNET_PROGRAM_run(argc, + argv, + "gnunet-cadet (OPTIONS | PEER_ID SHARED_SECRET)", + gettext_noop(helpstr), + options, + &run, + NULL); - GNUNET_free ((void *) argv); + GNUNET_free((void *)argv); if (GNUNET_OK == res) return 0; diff --git a/src/cadet/gnunet-service-cadet.c b/src/cadet/gnunet-service-cadet.c index 209f7d392..a06cd184f 100644 --- a/src/cadet/gnunet-service-cadet.c +++ b/src/cadet/gnunet-service-cadet.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet.c @@ -46,14 +46,13 @@ #include "gnunet-service-cadet_peer.h" #include "gnunet-service-cadet_paths.h" -#define LOG(level, ...) GNUNET_log (level,__VA_ARGS__) +#define LOG(level, ...) GNUNET_log(level, __VA_ARGS__) /** * Struct containing information about a client of the service */ -struct CadetClient -{ +struct CadetClient { /** * Linked list next */ @@ -202,11 +201,11 @@ unsigned long long drop_percent; * @param env envelope with the message */ void -GSC_send_to_client (struct CadetClient *c, - struct GNUNET_MQ_Envelope *env) +GSC_send_to_client(struct CadetClient *c, + struct GNUNET_MQ_Envelope *env) { - GNUNET_MQ_send (c->mq, - env); + GNUNET_MQ_send(c->mq, + env); } @@ -217,14 +216,14 @@ GSC_send_to_client (struct CadetClient *c, * @return string for debugging */ const char * -GSC_2s (struct CadetClient *c) +GSC_2s(struct CadetClient *c) { static char buf[32]; - GNUNET_snprintf (buf, - sizeof (buf), - "Client(%u)", - c->id); + GNUNET_snprintf(buf, + sizeof(buf), + "Client(%u)", + c->id); return buf; } @@ -237,11 +236,11 @@ GSC_2s (struct CadetClient *c) * @return NULL if no such channel exists */ static struct CadetChannel * -lookup_channel (struct CadetClient *c, - struct GNUNET_CADET_ClientChannelNumber ccn) +lookup_channel(struct CadetClient *c, + struct GNUNET_CADET_ClientChannelNumber ccn) { - return GNUNET_CONTAINER_multihashmap32_get (c->channels, - ntohl (ccn.channel_of_client)); + return GNUNET_CONTAINER_multihashmap32_get(c->channels, + ntohl(ccn.channel_of_client)); } @@ -252,23 +251,23 @@ lookup_channel (struct CadetClient *c, * @param c client handle */ static struct GNUNET_CADET_ClientChannelNumber -client_get_next_ccn (struct CadetClient *c) +client_get_next_ccn(struct CadetClient *c) { struct GNUNET_CADET_ClientChannelNumber ccn = c->next_ccn; /* increment until we have a free one... */ while (NULL != - lookup_channel (c, - ccn)) - { - ccn.channel_of_client - = htonl (1 + (ntohl (ccn.channel_of_client))); - if (ntohl (ccn.channel_of_client) >= - GNUNET_CADET_LOCAL_CHANNEL_ID_CLI) - ccn.channel_of_client = htonl (0); - } + lookup_channel(c, + ccn)) + { + ccn.channel_of_client + = htonl(1 + (ntohl(ccn.channel_of_client))); + if (ntohl(ccn.channel_of_client) >= + GNUNET_CADET_LOCAL_CHANNEL_ID_CLI) + ccn.channel_of_client = htonl(0); + } c->next_ccn.channel_of_client - = htonl (1 + (ntohl (ccn.channel_of_client))); + = htonl(1 + (ntohl(ccn.channel_of_client))); return ccn; } @@ -286,38 +285,38 @@ client_get_next_ccn (struct CadetClient *c) * @return local channel number assigned to the new client */ struct GNUNET_CADET_ClientChannelNumber -GSC_bind (struct CadetClient *c, - struct CadetChannel *ch, - struct CadetPeer *dest, - const struct GNUNET_HashCode *port, - uint32_t options) +GSC_bind(struct CadetClient *c, + struct CadetChannel *ch, + struct CadetPeer *dest, + const struct GNUNET_HashCode *port, + uint32_t options) { struct GNUNET_MQ_Envelope *env; struct GNUNET_CADET_LocalChannelCreateMessage *cm; struct GNUNET_CADET_ClientChannelNumber ccn; - ccn = client_get_next_ccn (c); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap32_put (c->channels, - ntohl (ccn.channel_of_client), - ch, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Accepting incoming %s from %s on open port %s (%u), assigning ccn %X\n", - GCCH_2s (ch), - GCP_2s (dest), - GNUNET_h2s (port), - (uint32_t) ntohl (options), - (uint32_t) ntohl (ccn.channel_of_client)); + ccn = client_get_next_ccn(c); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap32_put(c->channels, + ntohl(ccn.channel_of_client), + ch, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Accepting incoming %s from %s on open port %s (%u), assigning ccn %X\n", + GCCH_2s(ch), + GCP_2s(dest), + GNUNET_h2s(port), + (uint32_t)ntohl(options), + (uint32_t)ntohl(ccn.channel_of_client)); /* notify local client about incoming connection! */ - env = GNUNET_MQ_msg (cm, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE); + env = GNUNET_MQ_msg(cm, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE); cm->ccn = ccn; cm->port = *port; - cm->opt = htonl (options); - cm->peer = *GCP_get_id (dest); - GSC_send_to_client (c, - env); + cm->opt = htonl(options); + cm->peer = *GCP_get_id(dest); + GSC_send_to_client(c, + env); return ccn; } @@ -332,16 +331,16 @@ GSC_bind (struct CadetClient *c, * @return #GNUNET_OK (iterate over all entries) */ static int -destroy_tunnels_now (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *value) +destroy_tunnels_now(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *value) { struct CadetPeer *cp = value; - struct CadetTunnel *t = GCP_get_tunnel (cp, - GNUNET_NO); + struct CadetTunnel *t = GCP_get_tunnel(cp, + GNUNET_NO); if (NULL != t) - GCT_destroy_tunnel_now (t); + GCT_destroy_tunnel_now(t); return GNUNET_OK; } @@ -356,13 +355,13 @@ destroy_tunnels_now (void *cls, * @return #GNUNET_OK (iterate over all entries) */ static int -destroy_paths_now (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *value) +destroy_paths_now(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *value) { struct CadetPeer *cp = value; - GCP_drop_owned_paths (cp); + GCP_drop_owned_paths(cp); return GNUNET_OK; } @@ -371,50 +370,50 @@ destroy_paths_now (void *cls, * Shutdown everything once the clients have disconnected. */ static void -shutdown_rest () +shutdown_rest() { if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, - GNUNET_NO); - stats = NULL; - } + { + GNUNET_STATISTICS_destroy(stats, + GNUNET_NO); + stats = NULL; + } /* Destroy tunnels. Note that all channels must be destroyed first! */ - GCP_iterate_all (&destroy_tunnels_now, - NULL); + GCP_iterate_all(&destroy_tunnels_now, + NULL); /* All tunnels, channels, connections and CORE must be down before this point. */ - GCP_iterate_all (&destroy_paths_now, - NULL); + GCP_iterate_all(&destroy_paths_now, + NULL); /* All paths, tunnels, channels, connections and CORE must be down before this point. */ - GCP_destroy_all_peers (); + GCP_destroy_all_peers(); if (NULL != open_ports) - { - GNUNET_CONTAINER_multihashmap_destroy (open_ports); - open_ports = NULL; - } + { + GNUNET_CONTAINER_multihashmap_destroy(open_ports); + open_ports = NULL; + } if (NULL != loose_channels) - { - GNUNET_CONTAINER_multihashmap_destroy (loose_channels); - loose_channels = NULL; - } + { + GNUNET_CONTAINER_multihashmap_destroy(loose_channels); + loose_channels = NULL; + } if (NULL != peers) - { - GNUNET_CONTAINER_multipeermap_destroy (peers); - peers = NULL; - } + { + GNUNET_CONTAINER_multipeermap_destroy(peers); + peers = NULL; + } if (NULL != connections) - { - GNUNET_CONTAINER_multishortmap_destroy (connections); - connections = NULL; - } + { + GNUNET_CONTAINER_multishortmap_destroy(connections); + connections = NULL; + } if (NULL != ats_ch) - { - GNUNET_ATS_connectivity_done (ats_ch); - ats_ch = NULL; - } - GCD_shutdown (); - GCH_shutdown (); - GNUNET_free_non_null (my_private_key); + { + GNUNET_ATS_connectivity_done(ats_ch); + ats_ch = NULL; + } + GCD_shutdown(); + GCH_shutdown(); + GNUNET_free_non_null(my_private_key); my_private_key = NULL; } @@ -425,14 +424,14 @@ shutdown_rest () * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Shutting down\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Shutting down\n"); shutting_down = GNUNET_YES; - GCO_shutdown (); + GCO_shutdown(); if (NULL == clients_head) - shutdown_rest (); + shutdown_rest(); } @@ -446,20 +445,20 @@ shutdown_task (void *cls) * @return #GNUNET_YES (iterate over all such channels) */ static int -bind_loose_channel (void *cls, - const struct GNUNET_HashCode *port, - void *value) +bind_loose_channel(void *cls, + const struct GNUNET_HashCode *port, + void *value) { struct OpenPort *op = cls; struct CadetChannel *ch = value; - GCCH_bind (ch, - op->c, - &op->port); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (loose_channels, - &op->h_port, - ch)); + GCCH_bind(ch, + op->c, + &op->port); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(loose_channels, + &op->h_port, + ch)); return GNUNET_YES; } @@ -474,44 +473,44 @@ bind_loose_channel (void *cls, * @param pmsg The actual message. */ static void -handle_port_open (void *cls, - const struct GNUNET_CADET_PortMessage *pmsg) +handle_port_open(void *cls, + const struct GNUNET_CADET_PortMessage *pmsg) { struct CadetClient *c = cls; struct OpenPort *op; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Open port %s requested by %s\n", - GNUNET_h2s (&pmsg->port), - GSC_2s (c)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Open port %s requested by %s\n", + GNUNET_h2s(&pmsg->port), + GSC_2s(c)); if (NULL == c->ports) - c->ports = GNUNET_CONTAINER_multihashmap_create (4, - GNUNET_NO); - op = GNUNET_new (struct OpenPort); + c->ports = GNUNET_CONTAINER_multihashmap_create(4, + GNUNET_NO); + op = GNUNET_new(struct OpenPort); op->c = c; op->port = pmsg->port; - GCCH_hash_port (&op->h_port, - &pmsg->port, - &my_full_id); + GCCH_hash_port(&op->h_port, + &pmsg->port, + &my_full_id); if (GNUNET_OK != - GNUNET_CONTAINER_multihashmap_put (c->ports, - &op->port, - op, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - (void) GNUNET_CONTAINER_multihashmap_put (open_ports, - &op->h_port, - op, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - GNUNET_CONTAINER_multihashmap_get_multiple (loose_channels, - &op->h_port, - &bind_loose_channel, - op); - GNUNET_SERVICE_client_continue (c->client); + GNUNET_CONTAINER_multihashmap_put(c->ports, + &op->port, + op, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + (void)GNUNET_CONTAINER_multihashmap_put(open_ports, + &op->h_port, + op, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + GNUNET_CONTAINER_multihashmap_get_multiple(loose_channels, + &op->h_port, + &bind_loose_channel, + op); + GNUNET_SERVICE_client_continue(c->client); } @@ -525,41 +524,41 @@ handle_port_open (void *cls, * @param pmsg The actual message. */ static void -handle_port_close (void *cls, - const struct GNUNET_CADET_PortMessage *pmsg) +handle_port_close(void *cls, + const struct GNUNET_CADET_PortMessage *pmsg) { struct CadetClient *c = cls; struct OpenPort *op; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Closing port %s as requested by %s\n", - GNUNET_h2s (&pmsg->port), - GSC_2s (c)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Closing port %s as requested by %s\n", + GNUNET_h2s(&pmsg->port), + GSC_2s(c)); if (NULL == c->ports) - { - /* Client closed a port despite _never_ having opened one? */ - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - op = GNUNET_CONTAINER_multihashmap_get (c->ports, - &pmsg->port); + { + /* Client closed a port despite _never_ having opened one? */ + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + op = GNUNET_CONTAINER_multihashmap_get(c->ports, + &pmsg->port); if (NULL == op) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (c->ports, - &op->port, - op)); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (open_ports, - &op->h_port, - op)); - GNUNET_free (op); - GNUNET_SERVICE_client_continue (c->client); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(c->ports, + &op->port, + op)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(open_ports, + &op->h_port, + op)); + GNUNET_free(op); + GNUNET_SERVICE_client_continue(c->client); } @@ -570,54 +569,54 @@ handle_port_close (void *cls, * @param tcm The actual message. */ static void -handle_channel_create (void *cls, - const struct GNUNET_CADET_LocalChannelCreateMessage *tcm) +handle_channel_create(void *cls, + const struct GNUNET_CADET_LocalChannelCreateMessage *tcm) { struct CadetClient *c = cls; struct CadetChannel *ch; - if (ntohl (tcm->ccn.channel_of_client) < GNUNET_CADET_LOCAL_CHANNEL_ID_CLI) - { - /* Channel ID not in allowed range. */ - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - ch = lookup_channel (c, - tcm->ccn); + if (ntohl(tcm->ccn.channel_of_client) < GNUNET_CADET_LOCAL_CHANNEL_ID_CLI) + { + /* Channel ID not in allowed range. */ + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + ch = lookup_channel(c, + tcm->ccn); if (NULL != ch) - { - /* Channel ID already in use. Not allowed. */ - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "New channel to %s at port %s requested by %s\n", - GNUNET_i2s (&tcm->peer), - GNUNET_h2s (&tcm->port), - GSC_2s (c)); + { + /* Channel ID already in use. Not allowed. */ + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "New channel to %s at port %s requested by %s\n", + GNUNET_i2s(&tcm->peer), + GNUNET_h2s(&tcm->port), + GSC_2s(c)); /* Create channel */ - ch = GCCH_channel_local_new (c, - tcm->ccn, - GCP_get (&tcm->peer, - GNUNET_YES), - &tcm->port, - ntohl (tcm->opt)); + ch = GCCH_channel_local_new(c, + tcm->ccn, + GCP_get(&tcm->peer, + GNUNET_YES), + &tcm->port, + ntohl(tcm->opt)); if (NULL == ch) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap32_put (c->channels, - ntohl (tcm->ccn.channel_of_client), - ch, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - - GNUNET_SERVICE_client_continue (c->client); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap32_put(c->channels, + ntohl(tcm->ccn.channel_of_client), + ch, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + + GNUNET_SERVICE_client_continue(c->client); } @@ -628,37 +627,37 @@ handle_channel_create (void *cls, * @param msg the actual message */ static void -handle_channel_destroy (void *cls, - const struct GNUNET_CADET_LocalChannelDestroyMessage *msg) +handle_channel_destroy(void *cls, + const struct GNUNET_CADET_LocalChannelDestroyMessage *msg) { struct CadetClient *c = cls; struct CadetChannel *ch; - ch = lookup_channel (c, - msg->ccn); + ch = lookup_channel(c, + msg->ccn); if (NULL == ch) - { - /* Client attempted to destroy unknown channel. - Can happen if the other side went down at the same time.*/ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "%s tried to destroy unknown channel %X\n", - GSC_2s(c), - (uint32_t) ntohl (msg->ccn.channel_of_client)); - GNUNET_SERVICE_client_continue (c->client); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "%s is destroying %s\n", - GSC_2s(c), - GCCH_2s (ch)); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap32_remove (c->channels, - ntohl (msg->ccn.channel_of_client), - ch)); - GCCH_channel_local_destroy (ch, - c, - msg->ccn); - GNUNET_SERVICE_client_continue (c->client); + { + /* Client attempted to destroy unknown channel. + Can happen if the other side went down at the same time.*/ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "%s tried to destroy unknown channel %X\n", + GSC_2s(c), + (uint32_t)ntohl(msg->ccn.channel_of_client)); + GNUNET_SERVICE_client_continue(c->client); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "%s is destroying %s\n", + GSC_2s(c), + GCCH_2s(ch)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap32_remove(c->channels, + ntohl(msg->ccn.channel_of_client), + ch)); + GCCH_channel_local_destroy(ch, + c, + msg->ccn); + GNUNET_SERVICE_client_continue(c->client); } @@ -670,8 +669,8 @@ handle_channel_destroy (void *cls, * @return #GNUNET_OK if @a msg is OK, #GNUNET_SYSERR if not */ static int -check_local_data (void *cls, - const struct GNUNET_CADET_LocalData *msg) +check_local_data(void *cls, + const struct GNUNET_CADET_LocalData *msg) { size_t payload_size; size_t payload_claimed_size; @@ -684,36 +683,36 @@ check_local_data (void *cls, cadet_api will likely no more, so we could then simplify this mess again. */ /* Sanity check for message size */ - payload_size = ntohs (msg->header.size) - sizeof (*msg); - buf = (const char *) &msg[1]; - while (payload_size >= sizeof (struct GNUNET_MessageHeader)) - { - /* need to memcpy() for alignment */ - GNUNET_memcpy (&pa, - buf, - sizeof (pa)); - payload_claimed_size = ntohs (pa.size); - if ( (payload_size < payload_claimed_size) || - (payload_claimed_size < sizeof (struct GNUNET_MessageHeader)) || - (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < payload_claimed_size) ) + payload_size = ntohs(msg->header.size) - sizeof(*msg); + buf = (const char *)&msg[1]; + while (payload_size >= sizeof(struct GNUNET_MessageHeader)) { - GNUNET_break (0); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Local data of %u total size had sub-message %u at %u with %u bytes\n", - ntohs (msg->header.size), - ntohs (pa.type), - (unsigned int) (buf - (const char *) &msg[1]), - (unsigned int) payload_claimed_size); - return GNUNET_SYSERR; + /* need to memcpy() for alignment */ + GNUNET_memcpy(&pa, + buf, + sizeof(pa)); + payload_claimed_size = ntohs(pa.size); + if ((payload_size < payload_claimed_size) || + (payload_claimed_size < sizeof(struct GNUNET_MessageHeader)) || + (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < payload_claimed_size)) + { + GNUNET_break(0); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Local data of %u total size had sub-message %u at %u with %u bytes\n", + ntohs(msg->header.size), + ntohs(pa.type), + (unsigned int)(buf - (const char *)&msg[1]), + (unsigned int)payload_claimed_size); + return GNUNET_SYSERR; + } + payload_size -= payload_claimed_size; + buf += payload_claimed_size; } - payload_size -= payload_claimed_size; - buf += payload_claimed_size; - } if (0 != payload_size) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -726,47 +725,47 @@ check_local_data (void *cls, * @param msg the actual message */ static void -handle_local_data (void *cls, - const struct GNUNET_CADET_LocalData *msg) +handle_local_data(void *cls, + const struct GNUNET_CADET_LocalData *msg) { struct CadetClient *c = cls; struct CadetChannel *ch; size_t payload_size; const char *buf; - ch = lookup_channel (c, - msg->ccn); + ch = lookup_channel(c, + msg->ccn); if (NULL == ch) - { - /* Channel does not exist (anymore) */ - LOG (GNUNET_ERROR_TYPE_WARNING, - "Dropping payload for channel %u from client (channel unknown, other endpoint may have disconnected)\n", - (unsigned int) ntohl (msg->ccn.channel_of_client)); - GNUNET_SERVICE_client_continue (c->client); - return; - } - payload_size = ntohs (msg->header.size) - sizeof (*msg); - GNUNET_STATISTICS_update (stats, - "# payload received from clients", - payload_size, - GNUNET_NO); - buf = (const char *) &msg[1]; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received %u bytes payload from %s for %s\n", - (unsigned int) payload_size, - GSC_2s (c), - GCCH_2s (ch)); + { + /* Channel does not exist (anymore) */ + LOG(GNUNET_ERROR_TYPE_WARNING, + "Dropping payload for channel %u from client (channel unknown, other endpoint may have disconnected)\n", + (unsigned int)ntohl(msg->ccn.channel_of_client)); + GNUNET_SERVICE_client_continue(c->client); + return; + } + payload_size = ntohs(msg->header.size) - sizeof(*msg); + GNUNET_STATISTICS_update(stats, + "# payload received from clients", + payload_size, + GNUNET_NO); + buf = (const char *)&msg[1]; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received %u bytes payload from %s for %s\n", + (unsigned int)payload_size, + GSC_2s(c), + GCCH_2s(ch)); if (GNUNET_OK != - GCCH_handle_local_data (ch, - msg->ccn, - buf, - payload_size)) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (c->client); - return; - } - GNUNET_SERVICE_client_continue (c->client); + GCCH_handle_local_data(ch, + msg->ccn, + buf, + payload_size)) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(c->client); + return; + } + GNUNET_SERVICE_client_continue(c->client); } @@ -777,30 +776,30 @@ handle_local_data (void *cls, * @param msg The actual message. */ static void -handle_local_ack (void *cls, - const struct GNUNET_CADET_LocalAck *msg) +handle_local_ack(void *cls, + const struct GNUNET_CADET_LocalAck *msg) { struct CadetClient *c = cls; struct CadetChannel *ch; - ch = lookup_channel (c, - msg->ccn); + ch = lookup_channel(c, + msg->ccn); if (NULL == ch) - { - /* Channel does not exist (anymore) */ - LOG (GNUNET_ERROR_TYPE_WARNING, - "Ignoring local ACK for channel %u from client (channel unknown, other endpoint may have disconnected)\n", - (unsigned int) ntohl (msg->ccn.channel_of_client)); - GNUNET_SERVICE_client_continue (c->client); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got a local ACK from %s for %s\n", - GSC_2s(c), - GCCH_2s (ch)); - GCCH_handle_local_ack (ch, - msg->ccn); - GNUNET_SERVICE_client_continue (c->client); + { + /* Channel does not exist (anymore) */ + LOG(GNUNET_ERROR_TYPE_WARNING, + "Ignoring local ACK for channel %u from client (channel unknown, other endpoint may have disconnected)\n", + (unsigned int)ntohl(msg->ccn.channel_of_client)); + GNUNET_SERVICE_client_continue(c->client); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got a local ACK from %s for %s\n", + GSC_2s(c), + GCCH_2s(ch)); + GCCH_handle_local_ack(ch, + msg->ccn); + GNUNET_SERVICE_client_continue(c->client); } @@ -813,24 +812,24 @@ handle_local_ack (void *cls, * @return #GNUNET_YES, to keep iterating. */ static int -get_all_peers_iterator (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *value) +get_all_peers_iterator(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *value) { struct CadetClient *c = cls; struct CadetPeer *p = value; struct GNUNET_MQ_Envelope *env; struct GNUNET_CADET_LocalInfoPeers *msg; - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS); msg->destination = *peer; - msg->paths = htons (GCP_count_paths (p)); - msg->tunnel = htons (NULL != GCP_get_tunnel (p, - GNUNET_NO)); - msg->best_path_length = htonl (0); // FIXME: get length of shortest known path! - GNUNET_MQ_send (c->mq, - env); + msg->paths = htons(GCP_count_paths(p)); + msg->tunnel = htons(NULL != GCP_get_tunnel(p, + GNUNET_NO)); + msg->best_path_length = htonl(0); // FIXME: get length of shortest known path! + GNUNET_MQ_send(c->mq, + env); return GNUNET_YES; } @@ -842,20 +841,20 @@ get_all_peers_iterator (void *cls, * @param message The actual message. */ static void -handle_get_peers (void *cls, - const struct GNUNET_MessageHeader *message) +handle_get_peers(void *cls, + const struct GNUNET_MessageHeader *message) { struct CadetClient *c = cls; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *reply; - GCP_iterate_all (&get_all_peers_iterator, - c); - env = GNUNET_MQ_msg (reply, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS_END); - GNUNET_MQ_send (c->mq, - env); - GNUNET_SERVICE_client_continue (c->client); + GCP_iterate_all(&get_all_peers_iterator, + c); + env = GNUNET_MQ_msg(reply, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS_END); + GNUNET_MQ_send(c->mq, + env); + GNUNET_SERVICE_client_continue(c->client); } @@ -870,9 +869,9 @@ handle_get_peers (void *cls, * #GNUNET_NO otherwise. */ static int -path_info_iterator (void *cls, - struct CadetPeerPath *path, - unsigned int off) +path_info_iterator(void *cls, + struct CadetPeerPath *path, + unsigned int off) { struct GNUNET_MQ_Handle *mq = cls; struct GNUNET_MQ_Envelope *env; @@ -881,36 +880,36 @@ path_info_iterator (void *cls, size_t path_size; unsigned int path_length; - path_length = GCPP_get_length (path); - path_size = sizeof (struct GNUNET_PeerIdentity) * path_length; - if (sizeof (*resp) + path_size > UINT16_MAX) - { - /* try just giving the relevant path */ - path_length = GNUNET_MIN ((UINT16_MAX - sizeof (*resp)) / sizeof (struct GNUNET_PeerIdentity), - off); - path_size = sizeof (struct GNUNET_PeerIdentity) * path_length; - } - if (sizeof (*resp) + path_size > UINT16_MAX) - { - LOG (GNUNET_ERROR_TYPE_WARNING, - "Path of %u entries is too long for info message\n", - path_length); - return GNUNET_YES; - } - env = GNUNET_MQ_msg_extra (resp, - path_size, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PATH); - id = (struct GNUNET_PeerIdentity *) &resp[1]; + path_length = GCPP_get_length(path); + path_size = sizeof(struct GNUNET_PeerIdentity) * path_length; + if (sizeof(*resp) + path_size > UINT16_MAX) + { + /* try just giving the relevant path */ + path_length = GNUNET_MIN((UINT16_MAX - sizeof(*resp)) / sizeof(struct GNUNET_PeerIdentity), + off); + path_size = sizeof(struct GNUNET_PeerIdentity) * path_length; + } + if (sizeof(*resp) + path_size > UINT16_MAX) + { + LOG(GNUNET_ERROR_TYPE_WARNING, + "Path of %u entries is too long for info message\n", + path_length); + return GNUNET_YES; + } + env = GNUNET_MQ_msg_extra(resp, + path_size, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PATH); + id = (struct GNUNET_PeerIdentity *)&resp[1]; /* Don't copy first peer. First peer is always the local one. Last * peer is always the destination (leave as 0, EOL). */ for (unsigned int i = 0; i < path_length; i++) - id[i] = *GCP_get_id (GCPP_get_peer_at_offset (path, - i)); - resp->off = htonl (off); - GNUNET_MQ_send (mq, - env); + id[i] = *GCP_get_id(GCPP_get_peer_at_offset(path, + i)); + resp->off = htonl(off); + GNUNET_MQ_send(mq, + env); return GNUNET_YES; } @@ -922,25 +921,25 @@ path_info_iterator (void *cls, * @param msg The actual message. */ static void -handle_show_path (void *cls, - const struct GNUNET_CADET_RequestPathInfoMessage *msg) +handle_show_path(void *cls, + const struct GNUNET_CADET_RequestPathInfoMessage *msg) { struct CadetClient *c = cls; struct CadetPeer *p; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *resp; - p = GCP_get (&msg->peer, - GNUNET_NO); + p = GCP_get(&msg->peer, + GNUNET_NO); if (NULL != p) - GCP_iterate_indirect_paths (p, - &path_info_iterator, - c->mq); - env = GNUNET_MQ_msg (resp, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PATH_END); - GNUNET_MQ_send (c->mq, - env); - GNUNET_SERVICE_client_continue (c->client); + GCP_iterate_indirect_paths(p, + &path_info_iterator, + c->mq); + env = GNUNET_MQ_msg(resp, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PATH_END); + GNUNET_MQ_send(c->mq, + env); + GNUNET_SERVICE_client_continue(c->client); } @@ -953,9 +952,9 @@ handle_show_path (void *cls, * @return #GNUNET_YES, to keep iterating. */ static int -get_all_tunnels_iterator (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *value) +get_all_tunnels_iterator(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *value) { struct CadetClient *c = cls; struct CadetPeer *p = value; @@ -963,19 +962,19 @@ get_all_tunnels_iterator (void *cls, struct GNUNET_CADET_LocalInfoTunnel *msg; struct CadetTunnel *t; - t = GCP_get_tunnel (p, - GNUNET_NO); + t = GCP_get_tunnel(p, + GNUNET_NO); if (NULL == t) return GNUNET_YES; - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS); msg->destination = *peer; - msg->channels = htonl (GCT_count_channels (t)); - msg->connections = htonl (GCT_count_any_connections (t)); - msg->cstate = htons (0); - msg->estate = htons ((uint16_t) GCT_get_estate (t)); - GNUNET_MQ_send (c->mq, - env); + msg->channels = htonl(GCT_count_channels(t)); + msg->connections = htonl(GCT_count_any_connections(t)); + msg->cstate = htons(0); + msg->estate = htons((uint16_t)GCT_get_estate(t)); + GNUNET_MQ_send(c->mq, + env); return GNUNET_YES; } @@ -987,20 +986,20 @@ get_all_tunnels_iterator (void *cls, * @param message The actual message. */ static void -handle_info_tunnels (void *cls, - const struct GNUNET_MessageHeader *message) +handle_info_tunnels(void *cls, + const struct GNUNET_MessageHeader *message) { struct CadetClient *c = cls; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *reply; - GCP_iterate_all (&get_all_tunnels_iterator, - c); - env = GNUNET_MQ_msg (reply, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS_END); - GNUNET_MQ_send (c->mq, - env); - GNUNET_SERVICE_client_continue (c->client); + GCP_iterate_all(&get_all_tunnels_iterator, + c); + env = GNUNET_MQ_msg(reply, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS_END); + GNUNET_MQ_send(c->mq, + env); + GNUNET_SERVICE_client_continue(c->client); } @@ -1013,28 +1012,28 @@ handle_info_tunnels (void *cls, * @return @a c */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { struct CadetClient *c; - c = GNUNET_new (struct CadetClient); + c = GNUNET_new(struct CadetClient); c->client = client; c->mq = mq; c->id = next_client_id++; /* overflow not important: just for debug */ c->channels - = GNUNET_CONTAINER_multihashmap32_create (32); - GNUNET_CONTAINER_DLL_insert (clients_head, - clients_tail, - c); - GNUNET_STATISTICS_update (stats, - "# clients", - +1, - GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "%s connected\n", - GSC_2s (c)); + = GNUNET_CONTAINER_multihashmap32_create(32); + GNUNET_CONTAINER_DLL_insert(clients_head, + clients_tail, + c); + GNUNET_STATISTICS_update(stats, + "# clients", + +1, + GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "%s connected\n", + GSC_2s(c)); return c; } @@ -1047,22 +1046,22 @@ client_connect_cb (void *cls, * @param ch the channel object */ void -GSC_handle_remote_channel_destroy (struct CadetClient *c, - struct GNUNET_CADET_ClientChannelNumber ccn, - struct CadetChannel *ch) +GSC_handle_remote_channel_destroy(struct CadetClient *c, + struct GNUNET_CADET_ClientChannelNumber ccn, + struct CadetChannel *ch) { struct GNUNET_MQ_Envelope *env; struct GNUNET_CADET_LocalChannelDestroyMessage *tdm; - env = GNUNET_MQ_msg (tdm, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY); + env = GNUNET_MQ_msg(tdm, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY); tdm->ccn = ccn; - GSC_send_to_client (c, - env); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap32_remove (c->channels, - ntohl (ccn.channel_of_client), - ch)); + GSC_send_to_client(c, + env); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap32_remove(c->channels, + ntohl(ccn.channel_of_client), + ch)); } @@ -1074,13 +1073,13 @@ GSC_handle_remote_channel_destroy (struct CadetClient *c, * @param ch the channel that was lost */ void -GSC_drop_loose_channel (const struct GNUNET_HashCode *h_port, - struct CadetChannel *ch) +GSC_drop_loose_channel(const struct GNUNET_HashCode *h_port, + struct CadetChannel *ch) { - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (loose_channels, - h_port, - ch)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(loose_channels, + h_port, + ch)); } @@ -1093,26 +1092,26 @@ GSC_drop_loose_channel (const struct GNUNET_HashCode *h_port, * @return #GNUNET_OK, keep iterating. */ static int -channel_destroy_iterator (void *cls, - uint32_t key, - void *value) +channel_destroy_iterator(void *cls, + uint32_t key, + void *value) { struct CadetClient *c = cls; struct GNUNET_CADET_ClientChannelNumber ccn; struct CadetChannel *ch = value; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Destroying %s, due to %s disconnecting.\n", - GCCH_2s (ch), - GSC_2s (c)); - ccn.channel_of_client = htonl (key); - GCCH_channel_local_destroy (ch, - c, - ccn); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap32_remove (c->channels, - key, - ch)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Destroying %s, due to %s disconnecting.\n", + GCCH_2s(ch), + GSC_2s(c)); + ccn.channel_of_client = htonl(key); + GCCH_channel_local_destroy(ch, + c, + ccn); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap32_remove(c->channels, + key, + ch)); return GNUNET_OK; } @@ -1126,27 +1125,27 @@ channel_destroy_iterator (void *cls, * @return #GNUNET_OK, keep iterating. */ static int -client_release_ports (void *cls, - const struct GNUNET_HashCode *port, - void *value) +client_release_ports(void *cls, + const struct GNUNET_HashCode *port, + void *value) { struct CadetClient *c = cls; struct OpenPort *op = value; - GNUNET_assert (c == op->c); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Closing port %s due to %s disconnect.\n", - GNUNET_h2s (port), - GSC_2s (c)); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (open_ports, - &op->h_port, - op)); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (c->ports, - port, - op)); - GNUNET_free (op); + GNUNET_assert(c == op->c); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Closing port %s due to %s disconnect.\n", + GNUNET_h2s(port), + GSC_2s(c)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(open_ports, + &op->h_port, + op)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(c->ports, + port, + op)); + GNUNET_free(op); return GNUNET_OK; } @@ -1159,42 +1158,42 @@ client_release_ports (void *cls, * @param internal_cls should be equal to @a c */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *internal_cls) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *internal_cls) { struct CadetClient *c = internal_cls; - GNUNET_assert (c->client == client); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "%s is disconnecting.\n", - GSC_2s (c)); + GNUNET_assert(c->client == client); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "%s is disconnecting.\n", + GSC_2s(c)); if (NULL != c->channels) - { - GNUNET_CONTAINER_multihashmap32_iterate (c->channels, - &channel_destroy_iterator, - c); - GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (c->channels)); - GNUNET_CONTAINER_multihashmap32_destroy (c->channels); - } + { + GNUNET_CONTAINER_multihashmap32_iterate(c->channels, + &channel_destroy_iterator, + c); + GNUNET_assert(0 == GNUNET_CONTAINER_multihashmap32_size(c->channels)); + GNUNET_CONTAINER_multihashmap32_destroy(c->channels); + } if (NULL != c->ports) - { - GNUNET_CONTAINER_multihashmap_iterate (c->ports, - &client_release_ports, - c); - GNUNET_CONTAINER_multihashmap_destroy (c->ports); - } - GNUNET_CONTAINER_DLL_remove (clients_head, - clients_tail, - c); - GNUNET_STATISTICS_update (stats, - "# clients", - -1, - GNUNET_NO); - GNUNET_free (c); - if ( (NULL == clients_head) && - (GNUNET_YES == shutting_down) ) - shutdown_rest (); + { + GNUNET_CONTAINER_multihashmap_iterate(c->ports, + &client_release_ports, + c); + GNUNET_CONTAINER_multihashmap_destroy(c->ports); + } + GNUNET_CONTAINER_DLL_remove(clients_head, + clients_tail, + c); + GNUNET_STATISTICS_update(stats, + "# clients", + -1, + GNUNET_NO); + GNUNET_free(c); + if ((NULL == clients_head) && + (GNUNET_YES == shutting_down)) + shutdown_rest(); } @@ -1206,93 +1205,92 @@ client_disconnect_cb (void *cls, * @param c configuration to use */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *service) { cfg = c; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (c, - "CADET", - "RATCHET_MESSAGES", - &ratchet_messages)) - { - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING, - "CADET", - "RATCHET_MESSAGES", - "needs to be a number"); - ratchet_messages = 64; - } + GNUNET_CONFIGURATION_get_value_number(c, + "CADET", + "RATCHET_MESSAGES", + &ratchet_messages)) + { + GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_WARNING, + "CADET", + "RATCHET_MESSAGES", + "needs to be a number"); + ratchet_messages = 64; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_time (c, - "CADET", - "RATCHET_TIME", - &ratchet_time)) - { - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING, - "CADET", - "RATCHET_TIME", - "need delay value"); - ratchet_time = GNUNET_TIME_UNIT_HOURS; - } + GNUNET_CONFIGURATION_get_value_time(c, + "CADET", + "RATCHET_TIME", + &ratchet_time)) + { + GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_WARNING, + "CADET", + "RATCHET_TIME", + "need delay value"); + ratchet_time = GNUNET_TIME_UNIT_HOURS; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_time (c, - "CADET", - "REFRESH_CONNECTION_TIME", - &keepalive_period)) - { - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING, - "CADET", - "REFRESH_CONNECTION_TIME", - "need delay value"); - keepalive_period = GNUNET_TIME_UNIT_MINUTES; - } + GNUNET_CONFIGURATION_get_value_time(c, + "CADET", + "REFRESH_CONNECTION_TIME", + &keepalive_period)) + { + GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_WARNING, + "CADET", + "REFRESH_CONNECTION_TIME", + "need delay value"); + keepalive_period = GNUNET_TIME_UNIT_MINUTES; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (c, - "CADET", - "DROP_PERCENT", - &drop_percent)) - { - drop_percent = 0; - } + GNUNET_CONFIGURATION_get_value_number(c, + "CADET", + "DROP_PERCENT", + &drop_percent)) + { + drop_percent = 0; + } else - { - LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n"); - LOG (GNUNET_ERROR_TYPE_WARNING, "Cadet is running with DROP enabled.\n"); - LOG (GNUNET_ERROR_TYPE_WARNING, "This is NOT a good idea!\n"); - LOG (GNUNET_ERROR_TYPE_WARNING, "Remove DROP_PERCENT from config file.\n"); - LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n"); - } - my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (c); + { + LOG(GNUNET_ERROR_TYPE_WARNING, "**************************************\n"); + LOG(GNUNET_ERROR_TYPE_WARNING, "Cadet is running with DROP enabled.\n"); + LOG(GNUNET_ERROR_TYPE_WARNING, "This is NOT a good idea!\n"); + LOG(GNUNET_ERROR_TYPE_WARNING, "Remove DROP_PERCENT from config file.\n"); + LOG(GNUNET_ERROR_TYPE_WARNING, "**************************************\n"); + } + my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration(c); if (NULL == my_private_key) - { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_CRYPTO_eddsa_key_get_public (my_private_key, - &my_full_id.public_key); - stats = GNUNET_STATISTICS_create ("cadet", - c); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); - ats_ch = GNUNET_ATS_connectivity_init (c); + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_CRYPTO_eddsa_key_get_public(my_private_key, + &my_full_id.public_key); + stats = GNUNET_STATISTICS_create("cadet", + c); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); + ats_ch = GNUNET_ATS_connectivity_init(c); /* FIXME: optimize code to allow GNUNET_YES here! */ - open_ports = GNUNET_CONTAINER_multihashmap_create (16, - GNUNET_NO); - loose_channels = GNUNET_CONTAINER_multihashmap_create (16, - GNUNET_NO); - peers = GNUNET_CONTAINER_multipeermap_create (16, - GNUNET_YES); - connections = GNUNET_CONTAINER_multishortmap_create (256, - GNUNET_YES); - GCH_init (c); - GCD_init (c); - GCO_init (c); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "CADET started for peer %s\n", - GNUNET_i2s (&my_full_id)); - + open_ports = GNUNET_CONTAINER_multihashmap_create(16, + GNUNET_NO); + loose_channels = GNUNET_CONTAINER_multihashmap_create(16, + GNUNET_NO); + peers = GNUNET_CONTAINER_multipeermap_create(16, + GNUNET_YES); + connections = GNUNET_CONTAINER_multishortmap_create(256, + GNUNET_YES); + GCH_init(c); + GCD_init(c); + GCO_init(c); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "CADET started for peer %s\n", + GNUNET_i2s(&my_full_id)); } @@ -1300,48 +1298,48 @@ run (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("cadet", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_fixed_size (port_open, + ("cadet", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_fixed_size(port_open, GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN, struct GNUNET_CADET_PortMessage, NULL), - GNUNET_MQ_hd_fixed_size (port_close, + GNUNET_MQ_hd_fixed_size(port_close, GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE, struct GNUNET_CADET_PortMessage, NULL), - GNUNET_MQ_hd_fixed_size (channel_create, + GNUNET_MQ_hd_fixed_size(channel_create, GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE, struct GNUNET_CADET_LocalChannelCreateMessage, NULL), - GNUNET_MQ_hd_fixed_size (channel_destroy, + GNUNET_MQ_hd_fixed_size(channel_destroy, GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY, struct GNUNET_CADET_LocalChannelDestroyMessage, NULL), - GNUNET_MQ_hd_var_size (local_data, + GNUNET_MQ_hd_var_size(local_data, GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA, struct GNUNET_CADET_LocalData, NULL), - GNUNET_MQ_hd_fixed_size (local_ack, + GNUNET_MQ_hd_fixed_size(local_ack, GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK, struct GNUNET_CADET_LocalAck, NULL), - GNUNET_MQ_hd_fixed_size (get_peers, + GNUNET_MQ_hd_fixed_size(get_peers, GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_PEERS, struct GNUNET_MessageHeader, NULL), - GNUNET_MQ_hd_fixed_size (show_path, + GNUNET_MQ_hd_fixed_size(show_path, GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_PATH, struct GNUNET_CADET_RequestPathInfoMessage, NULL), - GNUNET_MQ_hd_fixed_size (info_tunnels, + GNUNET_MQ_hd_fixed_size(info_tunnels, GNUNET_MESSAGE_TYPE_CADET_LOCAL_REQUEST_INFO_TUNNELS, struct GNUNET_MessageHeader, NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_handler_end()); /* end of gnunet-service-cadet-new.c */ diff --git a/src/cadet/gnunet-service-cadet.h b/src/cadet/gnunet-service-cadet.h index 3daeeff74..8decdba0d 100644 --- a/src/cadet/gnunet-service-cadet.h +++ b/src/cadet/gnunet-service-cadet.h @@ -12,12 +12,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet.h @@ -64,8 +64,7 @@ struct CadetPeerPath; /** * Entry in a peer path. */ -struct CadetPeerPathEntry -{ +struct CadetPeerPathEntry { /** * DLL of paths where the same @e peer is at the same offset. */ @@ -99,14 +98,12 @@ struct CadetPeerPathEntry * against overflows. */ int score; - }; /** * Entry in list of connections used by tunnel, with metadata. */ -struct CadetTConnection -{ +struct CadetTConnection { /** * Next in DLL. */ @@ -147,9 +144,7 @@ struct CadetTConnection /** * Port opened by a client. */ -struct OpenPort -{ - +struct OpenPort { /** * Client that opened the port. */ @@ -164,7 +159,6 @@ struct OpenPort * Port hashed with our PID (matches incoming OPEN messages). */ struct GNUNET_HashCode h_port; - }; @@ -272,8 +266,8 @@ extern unsigned long long drop_percent; * @param env envelope with the message */ void -GSC_send_to_client (struct CadetClient *c, - struct GNUNET_MQ_Envelope *env); +GSC_send_to_client(struct CadetClient *c, + struct GNUNET_MQ_Envelope *env); /** @@ -284,9 +278,9 @@ GSC_send_to_client (struct CadetClient *c, * @param ch the channel object */ void -GSC_handle_remote_channel_destroy (struct CadetClient *c, - struct GNUNET_CADET_ClientChannelNumber ccn, - struct CadetChannel *ch); +GSC_handle_remote_channel_destroy(struct CadetClient *c, + struct GNUNET_CADET_ClientChannelNumber ccn, + struct CadetChannel *ch); /** * A client that created a loose channel that was not bound to a port @@ -296,8 +290,8 @@ GSC_handle_remote_channel_destroy (struct CadetClient *c, * @param ch the channel that was lost */ void -GSC_drop_loose_channel (const struct GNUNET_HashCode *h_port, - struct CadetChannel *ch); +GSC_drop_loose_channel(const struct GNUNET_HashCode *h_port, + struct CadetChannel *ch); /** @@ -312,11 +306,11 @@ GSC_drop_loose_channel (const struct GNUNET_HashCode *h_port, * @return local channel number assigned to the new client */ struct GNUNET_CADET_ClientChannelNumber -GSC_bind (struct CadetClient *c, - struct CadetChannel *ch, - struct CadetPeer *dest, - const struct GNUNET_HashCode *port, - uint32_t options); +GSC_bind(struct CadetClient *c, + struct CadetChannel *ch, + struct CadetPeer *dest, + const struct GNUNET_HashCode *port, + uint32_t options); /** @@ -326,7 +320,7 @@ GSC_bind (struct CadetClient *c, * @return string for debugging */ const char * -GSC_2s (struct CadetClient *c); +GSC_2s(struct CadetClient *c); #endif diff --git a/src/cadet/gnunet-service-cadet_channel.c b/src/cadet/gnunet-service-cadet_channel.c index 664b8a7c1..dad5325fc 100644 --- a/src/cadet/gnunet-service-cadet_channel.c +++ b/src/cadet/gnunet-service-cadet_channel.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_channel.c * @brief logical links between CADET clients @@ -41,26 +41,26 @@ #include "gnunet-service-cadet_tunnels.h" #include "gnunet-service-cadet_paths.h" -#define LOG(level, ...) GNUNET_log_from (level, "cadet-chn", __VA_ARGS__) +#define LOG(level, ...) GNUNET_log_from(level, "cadet-chn", __VA_ARGS__) /** * How long do we initially wait before retransmitting? */ #define CADET_INITIAL_RETRANSMIT_TIME \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250) /** * How long do we wait before dropping state about incoming * connection to closed port? */ #define TIMEOUT_CLOSED_PORT \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30) /** * How long do we wait at least before retransmitting ever? */ #define MIN_RTT_DELAY \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 75) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 75) /** * Maximum message ID into the future we accept for out-of-order messages. @@ -78,8 +78,7 @@ /** * All the states a channel can be in. */ -enum CadetChannelState -{ +enum CadetChannelState { /** * Uninitialized status, should never appear in operation. */ @@ -108,8 +107,7 @@ enum CadetChannelState * Note that we DO use this structure also for unreliable * messages. */ -struct CadetReliableMessage -{ +struct CadetReliableMessage { /** * Double linked list, FIFO style */ @@ -173,8 +171,7 @@ struct CadetReliableMessage /** * List of received out-of-order data messages. */ -struct CadetOutOfOrderMessage -{ +struct CadetOutOfOrderMessage { /** * Double linked list, FIFO style */ @@ -203,8 +200,7 @@ struct CadetOutOfOrderMessage * loopback channel, in which case it has two of these endpoints. * Note that flow control also is required in both directions. */ -struct CadetChannelClient -{ +struct CadetChannelClient { /** * Client handle. Not by itself sufficient to designate * the client endpoint, as the same client handle may @@ -245,8 +241,7 @@ struct CadetChannelClient /** * Struct containing all information regarding a channel to a remote client. */ -struct CadetChannel -{ +struct CadetChannel { /** * Tunnel this channel is in. */ @@ -391,24 +386,24 @@ struct CadetChannel * @return Static string with the channel IDs. */ const char * -GCCH_2s (const struct CadetChannel *ch) +GCCH_2s(const struct CadetChannel *ch) { static char buf[128]; - GNUNET_snprintf (buf, - sizeof (buf), - "Channel %s:%s ctn:%X(%X/%X)", - (GNUNET_YES == ch->is_loopback) - ? "loopback" - : GNUNET_i2s (GCP_get_id (GCT_get_destination (ch->t))), - GNUNET_h2s (&ch->port), - ch->ctn, - (NULL == ch->owner) - ? 0 - : ntohl (ch->owner->ccn.channel_of_client), - (NULL == ch->dest) - ? 0 - : ntohl (ch->dest->ccn.channel_of_client)); + GNUNET_snprintf(buf, + sizeof(buf), + "Channel %s:%s ctn:%X(%X/%X)", + (GNUNET_YES == ch->is_loopback) + ? "loopback" + : GNUNET_i2s(GCP_get_id(GCT_get_destination(ch->t))), + GNUNET_h2s(&ch->port), + ch->ctn, + (NULL == ch->owner) + ? 0 + : ntohl(ch->owner->ccn.channel_of_client), + (NULL == ch->dest) + ? 0 + : ntohl(ch->dest->ccn.channel_of_client)); return buf; } @@ -423,19 +418,19 @@ GCCH_2s (const struct CadetChannel *ch) * @param listener peer that is listining on @a port */ void -GCCH_hash_port (struct GNUNET_HashCode *h_port, - const struct GNUNET_HashCode *port, - const struct GNUNET_PeerIdentity *listener) +GCCH_hash_port(struct GNUNET_HashCode *h_port, + const struct GNUNET_HashCode *port, + const struct GNUNET_PeerIdentity *listener) { struct GNUNET_HashContext *hc; - hc = GNUNET_CRYPTO_hash_context_start (); - GNUNET_CRYPTO_hash_context_read (hc, port, sizeof (*port)); - GNUNET_CRYPTO_hash_context_read (hc, listener, sizeof (*listener)); - GNUNET_CRYPTO_hash_context_finish (hc, h_port); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Calculated port hash %s\n", - GNUNET_h2s (h_port)); + hc = GNUNET_CRYPTO_hash_context_start(); + GNUNET_CRYPTO_hash_context_read(hc, port, sizeof(*port)); + GNUNET_CRYPTO_hash_context_read(hc, listener, sizeof(*listener)); + GNUNET_CRYPTO_hash_context_finish(hc, h_port); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Calculated port hash %s\n", + GNUNET_h2s(h_port)); } @@ -447,7 +442,7 @@ GCCH_hash_port (struct GNUNET_HashCode *h_port, * @return ID used to identify the channel with the remote peer. */ struct GNUNET_CADET_ChannelTunnelNumber -GCCH_get_id (const struct CadetChannel *ch) +GCCH_get_id(const struct CadetChannel *ch) { return ch->ctn; } @@ -459,18 +454,18 @@ GCCH_get_id (const struct CadetChannel *ch) * @param ccc data structure to clean up */ static void -free_channel_client (struct CadetChannelClient *ccc) +free_channel_client(struct CadetChannelClient *ccc) { struct CadetOutOfOrderMessage *com; while (NULL != (com = ccc->head_recv)) - { - GNUNET_CONTAINER_DLL_remove (ccc->head_recv, ccc->tail_recv, com); - ccc->num_recv--; - GNUNET_MQ_discard (com->env); - GNUNET_free (com); - } - GNUNET_free (ccc); + { + GNUNET_CONTAINER_DLL_remove(ccc->head_recv, ccc->tail_recv, com); + ccc->num_recv--; + GNUNET_MQ_discard(com->env); + GNUNET_free(com); + } + GNUNET_free(ccc); } @@ -480,57 +475,57 @@ free_channel_client (struct CadetChannelClient *ccc) * @param ch channel to destroy */ static void -channel_destroy (struct CadetChannel *ch) +channel_destroy(struct CadetChannel *ch) { struct CadetReliableMessage *crm; while (NULL != (crm = ch->head_sent)) - { - GNUNET_assert (ch == crm->ch); - if (NULL != crm->qe) { - GCT_send_cancel (crm->qe); - crm->qe = NULL; + GNUNET_assert(ch == crm->ch); + if (NULL != crm->qe) + { + GCT_send_cancel(crm->qe); + crm->qe = NULL; + } + GNUNET_CONTAINER_DLL_remove(ch->head_sent, ch->tail_sent, crm); + GNUNET_free(crm->data_message); + GNUNET_free(crm); } - GNUNET_CONTAINER_DLL_remove (ch->head_sent, ch->tail_sent, crm); - GNUNET_free (crm->data_message); - GNUNET_free (crm); - } if (CADET_CHANNEL_LOOSE == ch->state) - { - GSC_drop_loose_channel (&ch->h_port, ch); - } + { + GSC_drop_loose_channel(&ch->h_port, ch); + } if (NULL != ch->owner) - { - free_channel_client (ch->owner); - ch->owner = NULL; - } + { + free_channel_client(ch->owner); + ch->owner = NULL; + } if (NULL != ch->dest) - { - free_channel_client (ch->dest); - ch->dest = NULL; - } + { + free_channel_client(ch->dest); + ch->dest = NULL; + } if (NULL != ch->last_control_qe) - { - GCT_send_cancel (ch->last_control_qe); - ch->last_control_qe = NULL; - } + { + GCT_send_cancel(ch->last_control_qe); + ch->last_control_qe = NULL; + } if (NULL != ch->retry_data_task) - { - GNUNET_SCHEDULER_cancel (ch->retry_data_task); - ch->retry_data_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(ch->retry_data_task); + ch->retry_data_task = NULL; + } if (NULL != ch->retry_control_task) - { - GNUNET_SCHEDULER_cancel (ch->retry_control_task); - ch->retry_control_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(ch->retry_control_task); + ch->retry_control_task = NULL; + } if (GNUNET_NO == ch->is_loopback) - { - GCT_remove_channel (ch->t, ch, ch->ctn); - ch->t = NULL; - } - GNUNET_free (ch); + { + GCT_remove_channel(ch->t, ch, ch->ctn); + ch->t = NULL; + } + GNUNET_free(ch); } @@ -540,7 +535,7 @@ channel_destroy (struct CadetChannel *ch) * @param cls Channel for which to send. */ static void -send_channel_open (void *cls); +send_channel_open(void *cls); /** @@ -552,20 +547,20 @@ send_channel_open (void *cls); * if transmission failed */ static void -channel_open_sent_cb (void *cls, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) +channel_open_sent_cb(void *cls, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) { struct CadetChannel *ch = cls; - GNUNET_assert (NULL != ch->last_control_qe); + GNUNET_assert(NULL != ch->last_control_qe); ch->last_control_qe = NULL; - ch->retry_time = GNUNET_TIME_STD_BACKOFF (ch->retry_time); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sent CADET_CHANNEL_OPEN on %s, retrying in %s\n", - GCCH_2s (ch), - GNUNET_STRINGS_relative_time_to_string (ch->retry_time, GNUNET_YES)); + ch->retry_time = GNUNET_TIME_STD_BACKOFF(ch->retry_time); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sent CADET_CHANNEL_OPEN on %s, retrying in %s\n", + GCCH_2s(ch), + GNUNET_STRINGS_relative_time_to_string(ch->retry_time, GNUNET_YES)); ch->retry_control_task = - GNUNET_SCHEDULER_add_delayed (ch->retry_time, &send_channel_open, ch); + GNUNET_SCHEDULER_add_delayed(ch->retry_time, &send_channel_open, ch); } @@ -575,27 +570,27 @@ channel_open_sent_cb (void *cls, * @param cls Channel for which to send. */ static void -send_channel_open (void *cls) +send_channel_open(void *cls) { struct CadetChannel *ch = cls; struct GNUNET_CADET_ChannelOpenMessage msgcc; ch->retry_control_task = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending CHANNEL_OPEN message for %s\n", - GCCH_2s (ch)); - msgcc.header.size = htons (sizeof (msgcc)); - msgcc.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending CHANNEL_OPEN message for %s\n", + GCCH_2s(ch)); + msgcc.header.size = htons(sizeof(msgcc)); + msgcc.header.type = htons(GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN); //TODO This will be removed in a major release, because this will be a protocol breaking change. We set the deprecated "reliable" bit here that was removed. msgcc.opt = 2; msgcc.h_port = ch->h_port; msgcc.ctn = ch->ctn; ch->state = CADET_CHANNEL_OPEN_SENT; if (NULL != ch->last_control_qe) - GCT_send_cancel (ch->last_control_qe); + GCT_send_cancel(ch->last_control_qe); ch->last_control_qe = - GCT_send (ch->t, &msgcc.header, &channel_open_sent_cb, ch); - GNUNET_assert (NULL == ch->retry_control_task); + GCT_send(ch->t, &msgcc.header, &channel_open_sent_cb, ch); + GNUNET_assert(NULL == ch->retry_control_task); } @@ -610,13 +605,13 @@ send_channel_open (void *cls) * @param ch the channel for which the tunnel is now ready */ void -GCCH_tunnel_up (struct CadetChannel *ch) +GCCH_tunnel_up(struct CadetChannel *ch) { - GNUNET_assert (NULL == ch->retry_control_task); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Tunnel up, sending CHANNEL_OPEN on %s now\n", - GCCH_2s (ch)); - ch->retry_control_task = GNUNET_SCHEDULER_add_now (&send_channel_open, ch); + GNUNET_assert(NULL == ch->retry_control_task); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Tunnel up, sending CHANNEL_OPEN on %s now\n", + GCCH_2s(ch)); + ch->retry_control_task = GNUNET_SCHEDULER_add_now(&send_channel_open, ch); } @@ -631,22 +626,22 @@ GCCH_tunnel_up (struct CadetChannel *ch) * @return handle to the new channel */ struct CadetChannel * -GCCH_channel_local_new (struct CadetClient *owner, - struct GNUNET_CADET_ClientChannelNumber ccn, - struct CadetPeer *destination, - const struct GNUNET_HashCode *port, - uint32_t options) +GCCH_channel_local_new(struct CadetClient *owner, + struct GNUNET_CADET_ClientChannelNumber ccn, + struct CadetPeer *destination, + const struct GNUNET_HashCode *port, + uint32_t options) { struct CadetChannel *ch; struct CadetChannelClient *ccco; - ccco = GNUNET_new (struct CadetChannelClient); + ccco = GNUNET_new(struct CadetChannelClient); ccco->c = owner; ccco->ccn = ccn; ccco->client_ready = GNUNET_YES; - ch = GNUNET_new (struct CadetChannel); - ch->mid_recv.mid = htonl (1); /* The OPEN_ACK counts as message 0! */ + ch = GNUNET_new(struct CadetChannel); + ch->mid_recv.mid = htonl(1); /* The OPEN_ACK counts as message 0! */ ch->nobuffer = GNUNET_NO; ch->reliable = GNUNET_YES; ch->out_of_order = GNUNET_NO; @@ -654,44 +649,44 @@ GCCH_channel_local_new (struct CadetClient *owner, (ch->nobuffer) ? 1 : 4; /* FIXME: 4!? Do not hardcode! */ ch->owner = ccco; ch->port = *port; - GCCH_hash_port (&ch->h_port, port, GCP_get_id (destination)); - if (0 == GNUNET_memcmp (&my_full_id, GCP_get_id (destination))) - { - struct OpenPort *op; - - ch->is_loopback = GNUNET_YES; - op = GNUNET_CONTAINER_multihashmap_get (open_ports, &ch->h_port); - if (NULL == op) + GCCH_hash_port(&ch->h_port, port, GCP_get_id(destination)); + if (0 == GNUNET_memcmp(&my_full_id, GCP_get_id(destination))) { - /* port closed, wait for it to possibly open */ - ch->state = CADET_CHANNEL_LOOSE; - (void) GNUNET_CONTAINER_multihashmap_put ( - loose_channels, - &ch->h_port, - ch, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Created loose incoming loopback channel to port %s\n", - GNUNET_h2s (&ch->port)); + struct OpenPort *op; + + ch->is_loopback = GNUNET_YES; + op = GNUNET_CONTAINER_multihashmap_get(open_ports, &ch->h_port); + if (NULL == op) + { + /* port closed, wait for it to possibly open */ + ch->state = CADET_CHANNEL_LOOSE; + (void)GNUNET_CONTAINER_multihashmap_put( + loose_channels, + &ch->h_port, + ch, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Created loose incoming loopback channel to port %s\n", + GNUNET_h2s(&ch->port)); + } + else + { + GCCH_bind(ch, op->c, &op->port); + } } - else + else { - GCCH_bind (ch, op->c, &op->port); + ch->t = GCP_get_tunnel(destination, GNUNET_YES); + ch->retry_time = CADET_INITIAL_RETRANSMIT_TIME; + ch->ctn = GCT_add_channel(ch->t, ch); } - } - else - { - ch->t = GCP_get_tunnel (destination, GNUNET_YES); - ch->retry_time = CADET_INITIAL_RETRANSMIT_TIME; - ch->ctn = GCT_add_channel (ch->t, ch); - } - GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Created channel to port %s at peer %s for %s using %s\n", - GNUNET_h2s (port), - GCP_2s (destination), - GSC_2s (owner), - (GNUNET_YES == ch->is_loopback) ? "loopback" : GCT_2s (ch->t)); + GNUNET_STATISTICS_update(stats, "# channels", 1, GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Created channel to port %s at peer %s for %s using %s\n", + GNUNET_h2s(port), + GCP_2s(destination), + GSC_2s(owner), + (GNUNET_YES == ch->is_loopback) ? "loopback" : GCT_2s(ch->t)); return ch; } @@ -703,16 +698,16 @@ GCCH_channel_local_new (struct CadetClient *owner, * @param cls the channel to drop */ static void -timeout_closed_cb (void *cls) +timeout_closed_cb(void *cls) { struct CadetChannel *ch = cls; ch->retry_control_task = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Closing incoming channel to port %s from peer %s due to timeout\n", - GNUNET_h2s (&ch->port), - GCP_2s (GCT_get_destination (ch->t))); - channel_destroy (ch); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Closing incoming channel to port %s from peer %s due to timeout\n", + GNUNET_h2s(&ch->port), + GCP_2s(GCT_get_destination(ch->t))); + channel_destroy(ch); } @@ -726,15 +721,15 @@ timeout_closed_cb (void *cls) * @return handle to the new channel */ struct CadetChannel * -GCCH_channel_incoming_new (struct CadetTunnel *t, - struct GNUNET_CADET_ChannelTunnelNumber ctn, - const struct GNUNET_HashCode *h_port, - uint32_t options) +GCCH_channel_incoming_new(struct CadetTunnel *t, + struct GNUNET_CADET_ChannelTunnelNumber ctn, + const struct GNUNET_HashCode *h_port, + uint32_t options) { struct CadetChannel *ch; struct OpenPort *op; - ch = GNUNET_new (struct CadetChannel); + ch = GNUNET_new(struct CadetChannel); ch->h_port = *h_port; ch->t = t; ch->ctn = ctn; @@ -744,32 +739,32 @@ GCCH_channel_incoming_new (struct CadetTunnel *t, ch->out_of_order = GNUNET_NO; ch->max_pending_messages = (ch->nobuffer) ? 1 : 4; /* FIXME: 4!? Do not hardcode! */ - GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO); + GNUNET_STATISTICS_update(stats, "# channels", 1, GNUNET_NO); - op = GNUNET_CONTAINER_multihashmap_get (open_ports, h_port); + op = GNUNET_CONTAINER_multihashmap_get(open_ports, h_port); if (NULL == op) - { - /* port closed, wait for it to possibly open */ - ch->state = CADET_CHANNEL_LOOSE; - (void) GNUNET_CONTAINER_multihashmap_put ( - loose_channels, - &ch->h_port, - ch, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - GNUNET_assert (NULL == ch->retry_control_task); - ch->retry_control_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT_CLOSED_PORT, - &timeout_closed_cb, - ch); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Created loose incoming channel to port %s from peer %s\n", - GNUNET_h2s (&ch->port), - GCP_2s (GCT_get_destination (ch->t))); - } + { + /* port closed, wait for it to possibly open */ + ch->state = CADET_CHANNEL_LOOSE; + (void)GNUNET_CONTAINER_multihashmap_put( + loose_channels, + &ch->h_port, + ch, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + GNUNET_assert(NULL == ch->retry_control_task); + ch->retry_control_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT_CLOSED_PORT, + &timeout_closed_cb, + ch); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Created loose incoming channel to port %s from peer %s\n", + GNUNET_h2s(&ch->port), + GCP_2s(GCT_get_destination(ch->t))); + } else - { - GCCH_bind (ch, op->c, &op->port); - } - GNUNET_STATISTICS_update (stats, "# channels", 1, GNUNET_NO); + { + GCCH_bind(ch, op->c, &op->port); + } + GNUNET_STATISTICS_update(stats, "# channels", 1, GNUNET_NO); return ch; } @@ -784,12 +779,12 @@ GCCH_channel_incoming_new (struct CadetTunnel *t, * if transmission failed */ static void -send_ack_cb (void *cls, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) +send_ack_cb(void *cls, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) { struct CadetChannel *ch = cls; - GNUNET_assert (NULL != ch->last_control_qe); + GNUNET_assert(NULL != ch->last_control_qe); ch->last_control_qe = NULL; } @@ -800,25 +795,25 @@ send_ack_cb (void *cls, * @param ch channel to send the #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK for */ static void -send_channel_data_ack (struct CadetChannel *ch) +send_channel_data_ack(struct CadetChannel *ch) { struct GNUNET_CADET_ChannelDataAckMessage msg; if (GNUNET_NO == ch->reliable) return; /* no ACKs */ - msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK); - msg.header.size = htons (sizeof (msg)); + msg.header.type = htons(GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK); + msg.header.size = htons(sizeof(msg)); msg.ctn = ch->ctn; - msg.mid.mid = htonl (ntohl (ch->mid_recv.mid)); - msg.futures = GNUNET_htonll (ch->mid_futures); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending DATA_ACK %u:%llX via %s\n", - (unsigned int) ntohl (msg.mid.mid), - (unsigned long long) ch->mid_futures, - GCCH_2s (ch)); + msg.mid.mid = htonl(ntohl(ch->mid_recv.mid)); + msg.futures = GNUNET_htonll(ch->mid_futures); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending DATA_ACK %u:%llX via %s\n", + (unsigned int)ntohl(msg.mid.mid), + (unsigned long long)ch->mid_futures, + GCCH_2s(ch)); if (NULL != ch->last_control_qe) - GCT_send_cancel (ch->last_control_qe); - ch->last_control_qe = GCT_send (ch->t, &msg.header, &send_ack_cb, ch); + GCT_send_cancel(ch->last_control_qe); + ch->last_control_qe = GCT_send(ch->t, &msg.header, &send_ack_cb, ch); } @@ -829,23 +824,23 @@ send_channel_data_ack (struct CadetChannel *ch) * @param cls the `struct CadetChannel` */ static void -send_open_ack (void *cls) +send_open_ack(void *cls) { struct CadetChannel *ch = cls; struct GNUNET_CADET_ChannelOpenAckMessage msg; ch->retry_control_task = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending CHANNEL_OPEN_ACK on %s\n", - GCCH_2s (ch)); - msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK); - msg.header.size = htons (sizeof (msg)); - msg.reserved = htonl (0); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending CHANNEL_OPEN_ACK on %s\n", + GCCH_2s(ch)); + msg.header.type = htons(GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK); + msg.header.size = htons(sizeof(msg)); + msg.reserved = htonl(0); msg.ctn = ch->ctn; msg.port = ch->port; if (NULL != ch->last_control_qe) - GCT_send_cancel (ch->last_control_qe); - ch->last_control_qe = GCT_send (ch->t, &msg.header, &send_ack_cb, ch); + GCT_send_cancel(ch->last_control_qe); + ch->last_control_qe = GCT_send(ch->t, &msg.header, &send_ack_cb, ch); } @@ -858,28 +853,28 @@ send_open_ack (void *cls) * @param cti identifier of the connection that delivered the message */ void -GCCH_handle_duplicate_open ( +GCCH_handle_duplicate_open( struct CadetChannel *ch, const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti) { if (NULL == ch->dest) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ignoring duplicate CHANNEL_OPEN on %s: port is closed\n", - GCCH_2s (ch)); - return; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ignoring duplicate CHANNEL_OPEN on %s: port is closed\n", + GCCH_2s(ch)); + return; + } if (NULL != ch->retry_control_task) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ignoring duplicate CHANNEL_OPEN on %s: control message is pending\n", - GCCH_2s (ch)); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Retransmitting CHANNEL_OPEN_ACK on %s\n", - GCCH_2s (ch)); - ch->retry_control_task = GNUNET_SCHEDULER_add_now (&send_open_ack, ch); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ignoring duplicate CHANNEL_OPEN on %s: control message is pending\n", + GCCH_2s(ch)); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Retransmitting CHANNEL_OPEN_ACK on %s\n", + GCCH_2s(ch)); + ch->retry_control_task = GNUNET_SCHEDULER_add_now(&send_open_ack, ch); } @@ -891,7 +886,7 @@ GCCH_handle_duplicate_open ( * #GNUNET_NO to send to dest */ static void -send_ack_to_client (struct CadetChannel *ch, int to_owner) +send_ack_to_client(struct CadetChannel *ch, int to_owner) { struct GNUNET_MQ_Envelope *env; struct GNUNET_CADET_LocalAck *ack; @@ -899,22 +894,22 @@ send_ack_to_client (struct CadetChannel *ch, int to_owner) ccc = (GNUNET_YES == to_owner) ? ch->owner : ch->dest; if (NULL == ccc) - { - /* This can happen if we are just getting ACKs after - our local client already disconnected. */ - GNUNET_assert (GNUNET_YES == ch->destroy); - return; - } - env = GNUNET_MQ_msg (ack, GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK); + { + /* This can happen if we are just getting ACKs after + our local client already disconnected. */ + GNUNET_assert(GNUNET_YES == ch->destroy); + return; + } + env = GNUNET_MQ_msg(ack, GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK); ack->ccn = ccc->ccn; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending CADET_LOCAL_ACK to %s (%s) at ccn %X (%u/%u pending)\n", - GSC_2s (ccc->c), - (GNUNET_YES == to_owner) ? "owner" : "dest", - ntohl (ack->ccn.channel_of_client), - ch->pending_messages, - ch->max_pending_messages); - GSC_send_to_client (ccc->c, env); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending CADET_LOCAL_ACK to %s (%s) at ccn %X (%u/%u pending)\n", + GSC_2s(ccc->c), + (GNUNET_YES == to_owner) ? "owner" : "dest", + ntohl(ack->ccn.channel_of_client), + ch->pending_messages, + ch->max_pending_messages); + GSC_send_to_client(ccc->c, env); } @@ -928,58 +923,58 @@ send_ack_to_client (struct CadetChannel *ch, int to_owner) * @param port the port @a is listening on */ void -GCCH_bind (struct CadetChannel *ch, - struct CadetClient *c, - const struct GNUNET_HashCode *port) +GCCH_bind(struct CadetChannel *ch, + struct CadetClient *c, + const struct GNUNET_HashCode *port) { uint32_t options; struct CadetChannelClient *cccd; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Binding %s from %s to port %s of %s\n", - GCCH_2s (ch), - GCT_2s (ch->t), - GNUNET_h2s (&ch->port), - GSC_2s (c)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Binding %s from %s to port %s of %s\n", + GCCH_2s(ch), + GCT_2s(ch->t), + GNUNET_h2s(&ch->port), + GSC_2s(c)); if (NULL != ch->retry_control_task) - { - /* there might be a timeout task here */ - GNUNET_SCHEDULER_cancel (ch->retry_control_task); - ch->retry_control_task = NULL; - } + { + /* there might be a timeout task here */ + GNUNET_SCHEDULER_cancel(ch->retry_control_task); + ch->retry_control_task = NULL; + } options = 0; - cccd = GNUNET_new (struct CadetChannelClient); - GNUNET_assert (NULL == ch->dest); + cccd = GNUNET_new(struct CadetChannelClient); + GNUNET_assert(NULL == ch->dest); ch->dest = cccd; ch->port = *port; cccd->c = c; cccd->client_ready = GNUNET_YES; - cccd->ccn = GSC_bind (c, - ch, - (GNUNET_YES == ch->is_loopback) - ? GCP_get (&my_full_id, GNUNET_YES) - : GCT_get_destination (ch->t), - port, - options); - GNUNET_assert (ntohl (cccd->ccn.channel_of_client) < - GNUNET_CADET_LOCAL_CHANNEL_ID_CLI); - ch->mid_recv.mid = htonl (1); /* The OPEN counts as message 0! */ + cccd->ccn = GSC_bind(c, + ch, + (GNUNET_YES == ch->is_loopback) + ? GCP_get(&my_full_id, GNUNET_YES) + : GCT_get_destination(ch->t), + port, + options); + GNUNET_assert(ntohl(cccd->ccn.channel_of_client) < + GNUNET_CADET_LOCAL_CHANNEL_ID_CLI); + ch->mid_recv.mid = htonl(1); /* The OPEN counts as message 0! */ if (GNUNET_YES == ch->is_loopback) - { - ch->state = CADET_CHANNEL_OPEN_SENT; - GCCH_handle_channel_open_ack (ch, NULL, port); - } + { + ch->state = CADET_CHANNEL_OPEN_SENT; + GCCH_handle_channel_open_ack(ch, NULL, port); + } else - { - /* notify other peer that we accepted the connection */ - ch->state = CADET_CHANNEL_READY; - ch->retry_control_task = GNUNET_SCHEDULER_add_now (&send_open_ack, ch); - } + { + /* notify other peer that we accepted the connection */ + ch->state = CADET_CHANNEL_READY; + ch->retry_control_task = GNUNET_SCHEDULER_add_now(&send_open_ack, ch); + } /* give client it's initial supply of ACKs */ - GNUNET_assert (ntohl (cccd->ccn.channel_of_client) < - GNUNET_CADET_LOCAL_CHANNEL_ID_CLI); + GNUNET_assert(ntohl(cccd->ccn.channel_of_client) < + GNUNET_CADET_LOCAL_CHANNEL_ID_CLI); for (unsigned int i = 0; i < ch->max_pending_messages; i++) - send_ack_to_client (ch, GNUNET_NO); + send_ack_to_client(ch, GNUNET_NO); } @@ -991,7 +986,7 @@ GCCH_bind (struct CadetChannel *ch, * @param cls the `struct CadetChannel` where one of the ends is now dead */ static void -signal_remote_destroy_cb (void *cls) +signal_remote_destroy_cb(void *cls) { struct CadetChannel *ch = cls; struct CadetChannelClient *ccc; @@ -999,8 +994,8 @@ signal_remote_destroy_cb (void *cls) /* Find which end is left... */ ch->retry_control_task = NULL; ccc = (NULL != ch->owner) ? ch->owner : ch->dest; - GSC_handle_remote_channel_destroy (ccc->c, ccc->ccn, ch); - channel_destroy (ch); + GSC_handle_remote_channel_destroy(ccc->c, ccc->ccn, ch); + channel_destroy(ch); } @@ -1013,72 +1008,74 @@ signal_remote_destroy_cb (void *cls) * @param ccn client number of the client @a c */ void -GCCH_channel_local_destroy (struct CadetChannel *ch, - struct CadetClient *c, - struct GNUNET_CADET_ClientChannelNumber ccn) +GCCH_channel_local_destroy(struct CadetChannel *ch, + struct CadetClient *c, + struct GNUNET_CADET_ClientChannelNumber ccn) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "%s asks for destruction of %s\n", - GSC_2s (c), - GCCH_2s (ch)); - GNUNET_assert (NULL != c); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "%s asks for destruction of %s\n", + GSC_2s(c), + GCCH_2s(ch)); + GNUNET_assert(NULL != c); if ((NULL != ch->owner) && (c == ch->owner->c) && (ccn.channel_of_client == ch->owner->ccn.channel_of_client)) - { - free_channel_client (ch->owner); - ch->owner = NULL; - } + { + free_channel_client(ch->owner); + ch->owner = NULL; + } else if ((NULL != ch->dest) && (c == ch->dest->c) && (ccn.channel_of_client == ch->dest->ccn.channel_of_client)) - { - free_channel_client (ch->dest); - ch->dest = NULL; - } + { + free_channel_client(ch->dest); + ch->dest = NULL; + } else - { - GNUNET_assert (0); - } + { + GNUNET_assert(0); + } if (GNUNET_YES == ch->destroy) - { - /* other end already destroyed, with the local client gone, no need - to finish transmissions, just destroy immediately. */ - channel_destroy (ch); - return; - } + { + /* other end already destroyed, with the local client gone, no need + to finish transmissions, just destroy immediately. */ + channel_destroy(ch); + return; + } if ((NULL != ch->head_sent) && ((NULL != ch->owner) || (NULL != ch->dest))) - { - /* Wait for other end to destroy us as well, - and otherwise allow send queue to be transmitted first */ - ch->destroy = GNUNET_YES; - return; - } + { + /* Wait for other end to destroy us as well, + and otherwise allow send queue to be transmitted first */ + ch->destroy = GNUNET_YES; + return; + } if ((GNUNET_YES == ch->is_loopback) && ((NULL != ch->owner) || (NULL != ch->dest))) - { - if (NULL != ch->retry_control_task) - GNUNET_SCHEDULER_cancel (ch->retry_control_task); - ch->retry_control_task = - GNUNET_SCHEDULER_add_now (&signal_remote_destroy_cb, ch); - return; - } + { + if (NULL != ch->retry_control_task) + GNUNET_SCHEDULER_cancel(ch->retry_control_task); + ch->retry_control_task = + GNUNET_SCHEDULER_add_now(&signal_remote_destroy_cb, ch); + return; + } if (GNUNET_NO == ch->is_loopback) - { - /* If the we ever sent the CHANNEL_CREATE, we need to send a destroy message. */ - switch (ch->state) { - case CADET_CHANNEL_NEW: - /* We gave up on a channel that we created as a client to a remote - target, but that never went anywhere. Nothing to do here. */ - break; - case CADET_CHANNEL_LOOSE: - break; - default: - GCT_send_channel_destroy (ch->t, ch->ctn); + /* If the we ever sent the CHANNEL_CREATE, we need to send a destroy message. */ + switch (ch->state) + { + case CADET_CHANNEL_NEW: + /* We gave up on a channel that we created as a client to a remote + target, but that never went anywhere. Nothing to do here. */ + break; + + case CADET_CHANNEL_LOOSE: + break; + + default: + GCT_send_channel_destroy(ch->t, ch->ctn); + } } - } /* Nothing left to do, just finish destruction */ - channel_destroy (ch); + channel_destroy(ch); } @@ -1092,57 +1089,60 @@ GCCH_channel_local_destroy (struct CadetChannel *ch, * @param port port number (needed to verify receiver knows the port) */ void -GCCH_handle_channel_open_ack ( +GCCH_handle_channel_open_ack( struct CadetChannel *ch, const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, const struct GNUNET_HashCode *port) { switch (ch->state) - { - case CADET_CHANNEL_NEW: - /* this should be impossible */ - GNUNET_break (0); - break; - case CADET_CHANNEL_LOOSE: - /* This makes no sense. */ - GNUNET_break_op (0); - break; - case CADET_CHANNEL_OPEN_SENT: - if (NULL == ch->owner) - { - /* We're not the owner, wrong direction! */ - GNUNET_break_op (0); - return; - } - if (0 != GNUNET_memcmp (&ch->port, port)) - { - /* Other peer failed to provide the right port, - refuse connection. */ - GNUNET_break_op (0); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received CHANNEL_OPEN_ACK for waiting %s, entering READY state\n", - GCCH_2s (ch)); - if (NULL != ch->retry_control_task) /* can be NULL if ch->is_loopback */ { - GNUNET_SCHEDULER_cancel (ch->retry_control_task); - ch->retry_control_task = NULL; + case CADET_CHANNEL_NEW: + /* this should be impossible */ + GNUNET_break(0); + break; + + case CADET_CHANNEL_LOOSE: + /* This makes no sense. */ + GNUNET_break_op(0); + break; + + case CADET_CHANNEL_OPEN_SENT: + if (NULL == ch->owner) + { + /* We're not the owner, wrong direction! */ + GNUNET_break_op(0); + return; + } + if (0 != GNUNET_memcmp(&ch->port, port)) + { + /* Other peer failed to provide the right port, + refuse connection. */ + GNUNET_break_op(0); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received CHANNEL_OPEN_ACK for waiting %s, entering READY state\n", + GCCH_2s(ch)); + if (NULL != ch->retry_control_task) /* can be NULL if ch->is_loopback */ + { + GNUNET_SCHEDULER_cancel(ch->retry_control_task); + ch->retry_control_task = NULL; + } + ch->state = CADET_CHANNEL_READY; + /* On first connect, send client as many ACKs as we allow messages + to be buffered! */ + for (unsigned int i = 0; i < ch->max_pending_messages; i++) + send_ack_to_client(ch, GNUNET_YES); + break; + + case CADET_CHANNEL_READY: + /* duplicate ACK, maybe we retried the CREATE. Ignore. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received duplicate channel OPEN_ACK for %s\n", + GCCH_2s(ch)); + GNUNET_STATISTICS_update(stats, "# duplicate CREATE_ACKs", 1, GNUNET_NO); + break; } - ch->state = CADET_CHANNEL_READY; - /* On first connect, send client as many ACKs as we allow messages - to be buffered! */ - for (unsigned int i = 0; i < ch->max_pending_messages; i++) - send_ack_to_client (ch, GNUNET_YES); - break; - case CADET_CHANNEL_READY: - /* duplicate ACK, maybe we retried the CREATE. Ignore. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received duplicate channel OPEN_ACK for %s\n", - GCCH_2s (ch)); - GNUNET_STATISTICS_update (stats, "# duplicate CREATE_ACKs", 1, GNUNET_NO); - break; - } } @@ -1155,28 +1155,28 @@ GCCH_handle_channel_open_ack ( * @return #GNUNET_YES if @e1 < @e2, otherwise #GNUNET_NO */ static int -is_before (void *cls, - struct CadetOutOfOrderMessage *m1, - struct CadetOutOfOrderMessage *m2) +is_before(void *cls, + struct CadetOutOfOrderMessage *m1, + struct CadetOutOfOrderMessage *m2) { int *duplicate = cls; - uint32_t v1 = ntohl (m1->mid.mid); - uint32_t v2 = ntohl (m2->mid.mid); + uint32_t v1 = ntohl(m1->mid.mid); + uint32_t v2 = ntohl(m2->mid.mid); uint32_t delta; delta = v2 - v1; if (0 == delta) *duplicate = GNUNET_YES; - if (delta > (uint32_t) INT_MAX) - { - /* in overflow range, we can safely assume we wrapped around */ - return GNUNET_NO; - } + if (delta > (uint32_t)INT_MAX) + { + /* in overflow range, we can safely assume we wrapped around */ + return GNUNET_NO; + } else - { - /* result is small, thus v2 > v1, thus m1 < m2 */ - return GNUNET_YES; - } + { + /* result is small, thus v2 > v1, thus m1 < m2 */ + return GNUNET_YES; + } } @@ -1189,7 +1189,7 @@ is_before (void *cls, * @param msg message that was received */ void -GCCH_handle_channel_plaintext_data ( +GCCH_handle_channel_plaintext_data( struct CadetChannel *ch, const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, const struct GNUNET_CADET_ChannelAppDataMessage *msg) @@ -1205,239 +1205,239 @@ GCCH_handle_channel_plaintext_data ( uint32_t mid_msg; uint32_t delta; - GNUNET_assert (GNUNET_NO == ch->is_loopback); + GNUNET_assert(GNUNET_NO == ch->is_loopback); if ((NULL == ch->owner) && (NULL == ch->dest)) - { - /* This client is gone, but we still have messages to send to - the other end (which is why @a ch is not yet dead). However, - we cannot pass messages to our client anymore. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Dropping incoming payload on %s as this end is already closed\n", - GCCH_2s (ch)); - /* send back DESTROY notification to stop further retransmissions! */ - if (GNUNET_YES == ch->destroy) - GCT_send_channel_destroy (ch->t, ch->ctn); - return; - } - payload_size = ntohs (msg->header.size) - sizeof (*msg); - env = GNUNET_MQ_msg_extra (ld, - payload_size, - GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA); + { + /* This client is gone, but we still have messages to send to + the other end (which is why @a ch is not yet dead). However, + we cannot pass messages to our client anymore. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Dropping incoming payload on %s as this end is already closed\n", + GCCH_2s(ch)); + /* send back DESTROY notification to stop further retransmissions! */ + if (GNUNET_YES == ch->destroy) + GCT_send_channel_destroy(ch->t, ch->ctn); + return; + } + payload_size = ntohs(msg->header.size) - sizeof(*msg); + env = GNUNET_MQ_msg_extra(ld, + payload_size, + GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA); ld->ccn = (NULL == ch->dest) ? ch->owner->ccn : ch->dest->ccn; - GNUNET_memcpy (&ld[1], &msg[1], payload_size); + GNUNET_memcpy(&ld[1], &msg[1], payload_size); ccc = (NULL != ch->owner) ? ch->owner : ch->dest; if (GNUNET_YES == ccc->client_ready) - { - /* - * We ad-hoc send the message if - * - The channel is out-of-order - * - The channel is reliable and MID matches next expected MID - * - The channel is unreliable and MID is before lowest seen MID - */ - if ((GNUNET_YES == ch->out_of_order) || - ((msg->mid.mid == ch->mid_recv.mid) && (GNUNET_YES == ch->reliable)) || - ((GNUNET_NO == ch->reliable) && - (ntohl (msg->mid.mid) >= ntohl (ch->mid_recv.mid)) && - ((NULL == ccc->head_recv) || - (ntohl (msg->mid.mid) < ntohl (ccc->head_recv->mid.mid))))) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Giving %u bytes of payload with MID %u from %s to client %s\n", - (unsigned int) payload_size, - ntohl (msg->mid.mid), - GCCH_2s (ch), - GSC_2s (ccc->c)); - ccc->client_ready = GNUNET_NO; - GSC_send_to_client (ccc->c, env); - if (GNUNET_NO == ch->out_of_order) - ch->mid_recv.mid = htonl (1 + ntohl (msg->mid.mid)); - else - ch->mid_recv.mid = htonl (1 + ntohl (ch->mid_recv.mid)); - ch->mid_futures >>= 1; - if ((GNUNET_YES == ch->out_of_order) && (GNUNET_NO == ch->reliable)) - { - /* possibly shift by more if we skipped messages */ - uint64_t delta = htonl (msg->mid.mid) - 1 - ntohl (ch->mid_recv.mid); - - if (delta > 63) - ch->mid_futures = 0; - else - ch->mid_futures >>= delta; - ch->mid_recv.mid = htonl (1 + ntohl (msg->mid.mid)); - } - send_channel_data_ack (ch); - return; + /* + * We ad-hoc send the message if + * - The channel is out-of-order + * - The channel is reliable and MID matches next expected MID + * - The channel is unreliable and MID is before lowest seen MID + */ + if ((GNUNET_YES == ch->out_of_order) || + ((msg->mid.mid == ch->mid_recv.mid) && (GNUNET_YES == ch->reliable)) || + ((GNUNET_NO == ch->reliable) && + (ntohl(msg->mid.mid) >= ntohl(ch->mid_recv.mid)) && + ((NULL == ccc->head_recv) || + (ntohl(msg->mid.mid) < ntohl(ccc->head_recv->mid.mid))))) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Giving %u bytes of payload with MID %u from %s to client %s\n", + (unsigned int)payload_size, + ntohl(msg->mid.mid), + GCCH_2s(ch), + GSC_2s(ccc->c)); + ccc->client_ready = GNUNET_NO; + GSC_send_to_client(ccc->c, env); + if (GNUNET_NO == ch->out_of_order) + ch->mid_recv.mid = htonl(1 + ntohl(msg->mid.mid)); + else + ch->mid_recv.mid = htonl(1 + ntohl(ch->mid_recv.mid)); + ch->mid_futures >>= 1; + if ((GNUNET_YES == ch->out_of_order) && (GNUNET_NO == ch->reliable)) + { + /* possibly shift by more if we skipped messages */ + uint64_t delta = htonl(msg->mid.mid) - 1 - ntohl(ch->mid_recv.mid); + + if (delta > 63) + ch->mid_futures = 0; + else + ch->mid_futures >>= delta; + ch->mid_recv.mid = htonl(1 + ntohl(msg->mid.mid)); + } + send_channel_data_ack(ch); + return; + } } - } if (GNUNET_YES == ch->reliable) - { - /* check if message ought to be dropped because it is ancient/too distant/duplicate */ - mid_min = ntohl (ch->mid_recv.mid); - mid_max = mid_min + ch->max_pending_messages; - mid_msg = ntohl (msg->mid.mid); - if (((uint32_t) (mid_msg - mid_min) > ch->max_pending_messages) || - ((uint32_t) (mid_max - mid_msg) > ch->max_pending_messages)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "%s at %u drops ancient or far-future message %u\n", - GCCH_2s (ch), - (unsigned int) mid_min, - ntohl (msg->mid.mid)); - - GNUNET_STATISTICS_update (stats, - "# duplicate DATA (ancient or future)", - 1, - GNUNET_NO); - GNUNET_MQ_discard (env); - send_channel_data_ack (ch); - return; - } - /* mark bit for future ACKs */ - delta = mid_msg - mid_min - 1; /* overflow/underflow are OK here */ - if (delta < 64) { - if (0 != (ch->mid_futures & (1LLU << delta))) - { - /* Duplicate within the queue, drop also */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Duplicate payload of %u bytes on %s (mid %u) dropped\n", - (unsigned int) payload_size, - GCCH_2s (ch), - ntohl (msg->mid.mid)); - GNUNET_STATISTICS_update (stats, "# duplicate DATA", 1, GNUNET_NO); - GNUNET_MQ_discard (env); - send_channel_data_ack (ch); - return; - } - ch->mid_futures |= (1LLU << delta); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Marked bit %llX for mid %u (base: %u); now: %llX\n", - (1LLU << delta), - mid_msg, - mid_min, - ch->mid_futures); + /* check if message ought to be dropped because it is ancient/too distant/duplicate */ + mid_min = ntohl(ch->mid_recv.mid); + mid_max = mid_min + ch->max_pending_messages; + mid_msg = ntohl(msg->mid.mid); + if (((uint32_t)(mid_msg - mid_min) > ch->max_pending_messages) || + ((uint32_t)(mid_max - mid_msg) > ch->max_pending_messages)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "%s at %u drops ancient or far-future message %u\n", + GCCH_2s(ch), + (unsigned int)mid_min, + ntohl(msg->mid.mid)); + + GNUNET_STATISTICS_update(stats, + "# duplicate DATA (ancient or future)", + 1, + GNUNET_NO); + GNUNET_MQ_discard(env); + send_channel_data_ack(ch); + return; + } + /* mark bit for future ACKs */ + delta = mid_msg - mid_min - 1; /* overflow/underflow are OK here */ + if (delta < 64) + { + if (0 != (ch->mid_futures & (1LLU << delta))) + { + /* Duplicate within the queue, drop also */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Duplicate payload of %u bytes on %s (mid %u) dropped\n", + (unsigned int)payload_size, + GCCH_2s(ch), + ntohl(msg->mid.mid)); + GNUNET_STATISTICS_update(stats, "# duplicate DATA", 1, GNUNET_NO); + GNUNET_MQ_discard(env); + send_channel_data_ack(ch); + return; + } + ch->mid_futures |= (1LLU << delta); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Marked bit %llX for mid %u (base: %u); now: %llX\n", + (1LLU << delta), + mid_msg, + mid_min, + ch->mid_futures); + } } - } else /* ! ch->reliable */ - { - struct CadetOutOfOrderMessage *next_msg; - - /** - * We always send if possible in this case. - * It is guaranteed that the queued MID < received MID - **/ - if ((NULL != ccc->head_recv) && (GNUNET_YES == ccc->client_ready)) - { - next_msg = ccc->head_recv; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Giving queued MID %u from %s to client %s\n", - ntohl (next_msg->mid.mid), - GCCH_2s (ch), - GSC_2s (ccc->c)); - ccc->client_ready = GNUNET_NO; - GSC_send_to_client (ccc->c, next_msg->env); - ch->mid_recv.mid = htonl (1 + ntohl (next_msg->mid.mid)); - ch->mid_futures >>= 1; - send_channel_data_ack (ch); - GNUNET_CONTAINER_DLL_remove (ccc->head_recv, ccc->tail_recv, next_msg); - ccc->num_recv--; - /* Do not process duplicate MID */ - if (msg->mid.mid == next_msg->mid.mid) /* Duplicate */ - { - /* Duplicate within the queue, drop */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Message on %s (mid %u) dropped, duplicate\n", - GCCH_2s (ch), - ntohl (msg->mid.mid)); - GNUNET_free (next_msg); - GNUNET_MQ_discard (env); - return; - } - GNUNET_free (next_msg); - } - - if (ntohl (msg->mid.mid) < ntohl (ch->mid_recv.mid)) /* Old */ - { - /* Duplicate within the queue, drop */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Message on %s (mid %u) dropped, old.\n", - GCCH_2s (ch), - ntohl (msg->mid.mid)); - GNUNET_MQ_discard (env); - return; - } - - /* Channel is unreliable, so we do not ACK. But we also cannot - allow buffering everything, so check if we have space... */ - if (ccc->num_recv >= ch->max_pending_messages) { - struct CadetOutOfOrderMessage *drop; - - /* Yep, need to drop. Drop the oldest message in - the buffer. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Queue full due slow client on %s, dropping oldest message\n", - GCCH_2s (ch)); - GNUNET_STATISTICS_update (stats, - "# messages dropped due to slow client", - 1, - GNUNET_NO); - drop = ccc->head_recv; - GNUNET_assert (NULL != drop); - GNUNET_CONTAINER_DLL_remove (ccc->head_recv, ccc->tail_recv, drop); - ccc->num_recv--; - GNUNET_MQ_discard (drop->env); - GNUNET_free (drop); + struct CadetOutOfOrderMessage *next_msg; + + /** + * We always send if possible in this case. + * It is guaranteed that the queued MID < received MID + **/ + if ((NULL != ccc->head_recv) && (GNUNET_YES == ccc->client_ready)) + { + next_msg = ccc->head_recv; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Giving queued MID %u from %s to client %s\n", + ntohl(next_msg->mid.mid), + GCCH_2s(ch), + GSC_2s(ccc->c)); + ccc->client_ready = GNUNET_NO; + GSC_send_to_client(ccc->c, next_msg->env); + ch->mid_recv.mid = htonl(1 + ntohl(next_msg->mid.mid)); + ch->mid_futures >>= 1; + send_channel_data_ack(ch); + GNUNET_CONTAINER_DLL_remove(ccc->head_recv, ccc->tail_recv, next_msg); + ccc->num_recv--; + /* Do not process duplicate MID */ + if (msg->mid.mid == next_msg->mid.mid) /* Duplicate */ + { + /* Duplicate within the queue, drop */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Message on %s (mid %u) dropped, duplicate\n", + GCCH_2s(ch), + ntohl(msg->mid.mid)); + GNUNET_free(next_msg); + GNUNET_MQ_discard(env); + return; + } + GNUNET_free(next_msg); + } + + if (ntohl(msg->mid.mid) < ntohl(ch->mid_recv.mid)) /* Old */ + { + /* Duplicate within the queue, drop */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Message on %s (mid %u) dropped, old.\n", + GCCH_2s(ch), + ntohl(msg->mid.mid)); + GNUNET_MQ_discard(env); + return; + } + + /* Channel is unreliable, so we do not ACK. But we also cannot + allow buffering everything, so check if we have space... */ + if (ccc->num_recv >= ch->max_pending_messages) + { + struct CadetOutOfOrderMessage *drop; + + /* Yep, need to drop. Drop the oldest message in + the buffer. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Queue full due slow client on %s, dropping oldest message\n", + GCCH_2s(ch)); + GNUNET_STATISTICS_update(stats, + "# messages dropped due to slow client", + 1, + GNUNET_NO); + drop = ccc->head_recv; + GNUNET_assert(NULL != drop); + GNUNET_CONTAINER_DLL_remove(ccc->head_recv, ccc->tail_recv, drop); + ccc->num_recv--; + GNUNET_MQ_discard(drop->env); + GNUNET_free(drop); + } } - } /* Insert message into sorted out-of-order queue */ - com = GNUNET_new (struct CadetOutOfOrderMessage); + com = GNUNET_new(struct CadetOutOfOrderMessage); com->mid = msg->mid; com->env = env; duplicate = GNUNET_NO; - GNUNET_CONTAINER_DLL_insert_sorted (struct CadetOutOfOrderMessage, - is_before, - &duplicate, - ccc->head_recv, - ccc->tail_recv, - com); + GNUNET_CONTAINER_DLL_insert_sorted(struct CadetOutOfOrderMessage, + is_before, + &duplicate, + ccc->head_recv, + ccc->tail_recv, + com); ccc->num_recv++; if (GNUNET_YES == duplicate) - { - /* Duplicate within the queue, drop also (this is not covered by - the case above if "delta" >= 64, which could be the case if - max_pending_messages is also >= 64 or if our client is unready - and we are seeing retransmissions of the message our client is - blocked on. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Duplicate payload of %u bytes on %s (mid %u) dropped\n", - (unsigned int) payload_size, - GCCH_2s (ch), - ntohl (msg->mid.mid)); - GNUNET_STATISTICS_update (stats, "# duplicate DATA", 1, GNUNET_NO); - GNUNET_CONTAINER_DLL_remove (ccc->head_recv, ccc->tail_recv, com); - ccc->num_recv--; - GNUNET_MQ_discard (com->env); - GNUNET_free (com); - send_channel_data_ack (ch); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Queued %s payload of %u bytes on %s-%X(%p) (mid %u, need %u first)\n", - (GNUNET_YES == ccc->client_ready) ? "out-of-order" : "client-not-ready", - (unsigned int) payload_size, - GCCH_2s (ch), - ntohl (ccc->ccn.channel_of_client), - ccc, - ntohl (msg->mid.mid), - ntohl (ch->mid_recv.mid)); + { + /* Duplicate within the queue, drop also (this is not covered by + the case above if "delta" >= 64, which could be the case if + max_pending_messages is also >= 64 or if our client is unready + and we are seeing retransmissions of the message our client is + blocked on. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Duplicate payload of %u bytes on %s (mid %u) dropped\n", + (unsigned int)payload_size, + GCCH_2s(ch), + ntohl(msg->mid.mid)); + GNUNET_STATISTICS_update(stats, "# duplicate DATA", 1, GNUNET_NO); + GNUNET_CONTAINER_DLL_remove(ccc->head_recv, ccc->tail_recv, com); + ccc->num_recv--; + GNUNET_MQ_discard(com->env); + GNUNET_free(com); + send_channel_data_ack(ch); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Queued %s payload of %u bytes on %s-%X(%p) (mid %u, need %u first)\n", + (GNUNET_YES == ccc->client_ready) ? "out-of-order" : "client-not-ready", + (unsigned int)payload_size, + GCCH_2s(ch), + ntohl(ccc->ccn.channel_of_client), + ccc, + ntohl(msg->mid.mid), + ntohl(ch->mid_recv.mid)); /* NOTE: this ACK we _could_ skip, as the packet is out-of-order and the sender may already be transmitting the previous one. Needs experimental evaluation to see if/when this ACK helps or hurts. (We might even want another option.) */ - send_channel_data_ack (ch); + send_channel_data_ack(ch); } @@ -1452,8 +1452,8 @@ GCCH_handle_channel_plaintext_data ( * if transmission failed */ static void -data_sent_cb (void *cls, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid); +data_sent_cb(void *cls, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid); /** @@ -1463,19 +1463,19 @@ data_sent_cb (void *cls, * @param cls the `struct CadetChannel` where we need to retransmit */ static void -retry_transmission (void *cls) +retry_transmission(void *cls) { struct CadetChannel *ch = cls; struct CadetReliableMessage *crm = ch->head_sent; ch->retry_data_task = NULL; - GNUNET_assert (NULL == crm->qe); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Retrying transmission on %s of message %u\n", - GCCH_2s (ch), - (unsigned int) ntohl (crm->data_message->mid.mid)); - crm->qe = GCT_send (ch->t, &crm->data_message->header, &data_sent_cb, crm); - GNUNET_assert (NULL == ch->retry_data_task); + GNUNET_assert(NULL == crm->qe); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Retrying transmission on %s of message %u\n", + GCCH_2s(ch), + (unsigned int)ntohl(crm->data_message->mid.mid)); + crm->qe = GCT_send(ch->t, &crm->data_message->header, &data_sent_cb, crm); + GNUNET_assert(NULL == ch->retry_data_task); } @@ -1488,36 +1488,36 @@ retry_transmission (void *cls) * @param crm the message that got acknowledged */ static void -handle_matching_ack (struct CadetChannel *ch, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, - struct CadetReliableMessage *crm) +handle_matching_ack(struct CadetChannel *ch, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, + struct CadetReliableMessage *crm) { - GNUNET_CONTAINER_DLL_remove (ch->head_sent, ch->tail_sent, crm); + GNUNET_CONTAINER_DLL_remove(ch->head_sent, ch->tail_sent, crm); ch->pending_messages--; - GNUNET_assert (ch->pending_messages < ch->max_pending_messages); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received DATA_ACK on %s for message %u (%u ACKs pending)\n", - GCCH_2s (ch), - (unsigned int) ntohl (crm->data_message->mid.mid), - ch->pending_messages); + GNUNET_assert(ch->pending_messages < ch->max_pending_messages); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received DATA_ACK on %s for message %u (%u ACKs pending)\n", + GCCH_2s(ch), + (unsigned int)ntohl(crm->data_message->mid.mid), + ch->pending_messages); if (NULL != crm->qe) - { - GCT_send_cancel (crm->qe); - crm->qe = NULL; - } + { + GCT_send_cancel(crm->qe); + crm->qe = NULL; + } if ((1 == crm->num_transmissions) && (NULL != cti)) - { - GCC_ack_observed (cti); - if (0 == GNUNET_memcmp (cti, &crm->connection_taken)) { - GCC_latency_observed (cti, - GNUNET_TIME_absolute_get_duration ( - crm->first_transmission_time)); + GCC_ack_observed(cti); + if (0 == GNUNET_memcmp(cti, &crm->connection_taken)) + { + GCC_latency_observed(cti, + GNUNET_TIME_absolute_get_duration( + crm->first_transmission_time)); + } } - } - GNUNET_free (crm->data_message); - GNUNET_free (crm); - send_ack_to_client (ch, (NULL == ch->owner) ? GNUNET_NO : GNUNET_YES); + GNUNET_free(crm->data_message); + GNUNET_free(crm); + send_ack_to_client(ch, (NULL == ch->owner) ? GNUNET_NO : GNUNET_YES); } @@ -1530,7 +1530,7 @@ handle_matching_ack (struct CadetChannel *ch, * @param ack details about what was received */ void -GCCH_handle_channel_plaintext_data_ack ( +GCCH_handle_channel_plaintext_data_ack( struct CadetChannel *ch, const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, const struct GNUNET_CADET_ChannelDataAckMessage *ack) @@ -1542,72 +1542,72 @@ GCCH_handle_channel_plaintext_data_ack ( uint64_t mid_mask; unsigned int delta; - GNUNET_break (GNUNET_NO == ch->is_loopback); + GNUNET_break(GNUNET_NO == ch->is_loopback); if (GNUNET_NO == ch->reliable) - { - /* not expecting ACKs on unreliable channel, odd */ - GNUNET_break_op (0); - return; - } + { + /* not expecting ACKs on unreliable channel, odd */ + GNUNET_break_op(0); + return; + } /* mid_base is the MID of the next message that the other peer expects (i.e. that is missing!), everything LOWER (but excluding mid_base itself) was received. */ - mid_base = ntohl (ack->mid.mid); - mid_mask = GNUNET_htonll (ack->futures); + mid_base = ntohl(ack->mid.mid); + mid_mask = GNUNET_htonll(ack->futures); found = GNUNET_NO; for (crm = ch->head_sent; NULL != crm; crm = crmn) - { - crmn = crm->next; - delta = (unsigned int) (ntohl (crm->data_message->mid.mid) - mid_base); - if (delta >= UINT_MAX - ch->max_pending_messages) { - /* overflow, means crm was a bit in the past, so this ACK counts for it. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got DATA_ACK with base %u satisfying past message %u on %s\n", - (unsigned int) mid_base, - ntohl (crm->data_message->mid.mid), - GCCH_2s (ch)); - handle_matching_ack (ch, cti, crm); - found = GNUNET_YES; - continue; + crmn = crm->next; + delta = (unsigned int)(ntohl(crm->data_message->mid.mid) - mid_base); + if (delta >= UINT_MAX - ch->max_pending_messages) + { + /* overflow, means crm was a bit in the past, so this ACK counts for it. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got DATA_ACK with base %u satisfying past message %u on %s\n", + (unsigned int)mid_base, + ntohl(crm->data_message->mid.mid), + GCCH_2s(ch)); + handle_matching_ack(ch, cti, crm); + found = GNUNET_YES; + continue; + } + delta--; + if (delta >= 64) + continue; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Testing bit %llX for mid %u (base: %u)\n", + (1LLU << delta), + ntohl(crm->data_message->mid.mid), + mid_base); + if (0 != (mid_mask & (1LLU << delta))) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got DATA_ACK with mask for %u on %s\n", + ntohl(crm->data_message->mid.mid), + GCCH_2s(ch)); + handle_matching_ack(ch, cti, crm); + found = GNUNET_YES; + } } - delta--; - if (delta >= 64) - continue; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Testing bit %llX for mid %u (base: %u)\n", - (1LLU << delta), - ntohl (crm->data_message->mid.mid), - mid_base); - if (0 != (mid_mask & (1LLU << delta))) + if (GNUNET_NO == found) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got DATA_ACK with mask for %u on %s\n", - ntohl (crm->data_message->mid.mid), - GCCH_2s (ch)); - handle_matching_ack (ch, cti, crm); - found = GNUNET_YES; + /* ACK for message we already dropped, might have been a + duplicate ACK? Ignore. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Duplicate DATA_ACK on %s, ignoring\n", + GCCH_2s(ch)); + GNUNET_STATISTICS_update(stats, "# duplicate DATA_ACKs", 1, GNUNET_NO); + return; } - } - if (GNUNET_NO == found) - { - /* ACK for message we already dropped, might have been a - duplicate ACK? Ignore. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Duplicate DATA_ACK on %s, ignoring\n", - GCCH_2s (ch)); - GNUNET_STATISTICS_update (stats, "# duplicate DATA_ACKs", 1, GNUNET_NO); - return; - } if (NULL != ch->retry_data_task) - { - GNUNET_SCHEDULER_cancel (ch->retry_data_task); - ch->retry_data_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(ch->retry_data_task); + ch->retry_data_task = NULL; + } if ((NULL != ch->head_sent) && (NULL == ch->head_sent->qe)) - ch->retry_data_task = GNUNET_SCHEDULER_add_at (ch->head_sent->next_retry, - &retry_transmission, - ch); + ch->retry_data_task = GNUNET_SCHEDULER_add_at(ch->head_sent->next_retry, + &retry_transmission, + ch); } @@ -1621,34 +1621,34 @@ GCCH_handle_channel_plaintext_data_ack ( * NULL if we are simulating receiving a destroy due to shutdown */ void -GCCH_handle_remote_destroy ( +GCCH_handle_remote_destroy( struct CadetChannel *ch, const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti) { struct CadetChannelClient *ccc; - GNUNET_assert (GNUNET_NO == ch->is_loopback); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received remote channel DESTROY for %s\n", - GCCH_2s (ch)); + GNUNET_assert(GNUNET_NO == ch->is_loopback); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received remote channel DESTROY for %s\n", + GCCH_2s(ch)); if (GNUNET_YES == ch->destroy) - { - /* Local client already gone, this is instant-death. */ - channel_destroy (ch); - return; - } + { + /* Local client already gone, this is instant-death. */ + channel_destroy(ch); + return; + } ccc = (NULL != ch->owner) ? ch->owner : ch->dest; if ((NULL != ccc) && (NULL != ccc->head_recv)) - { - LOG (GNUNET_ERROR_TYPE_WARNING, - "Lost end of transmission due to remote shutdown on %s\n", - GCCH_2s (ch)); - /* FIXME: change API to notify client about truncated transmission! */ - } + { + LOG(GNUNET_ERROR_TYPE_WARNING, + "Lost end of transmission due to remote shutdown on %s\n", + GCCH_2s(ch)); + /* FIXME: change API to notify client about truncated transmission! */ + } ch->destroy = GNUNET_YES; if (NULL != ccc) - GSC_handle_remote_channel_destroy (ccc->c, ccc->ccn, ch); - channel_destroy (ch); + GSC_handle_remote_channel_destroy(ccc->c, ccc->ccn, ch); + channel_destroy(ch); } @@ -1661,9 +1661,9 @@ GCCH_handle_remote_destroy ( * @return #GNUNET_YES if @e1 < @e2, otherwise #GNUNET_NO */ static int -cmp_crm_by_next_retry (void *cls, - struct CadetReliableMessage *crm1, - struct CadetReliableMessage *crm2) +cmp_crm_by_next_retry(void *cls, + struct CadetReliableMessage *crm1, + struct CadetReliableMessage *crm2) { if (crm1->next_retry.abs_value_us < crm2->next_retry.abs_value_us) return GNUNET_YES; @@ -1682,75 +1682,75 @@ cmp_crm_by_next_retry (void *cls, * if transmission failed */ static void -data_sent_cb (void *cls, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) +data_sent_cb(void *cls, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) { struct CadetReliableMessage *crm = cls; struct CadetChannel *ch = crm->ch; - GNUNET_assert (GNUNET_NO == ch->is_loopback); - GNUNET_assert (NULL != crm->qe); + GNUNET_assert(GNUNET_NO == ch->is_loopback); + GNUNET_assert(NULL != crm->qe); crm->qe = NULL; - GNUNET_CONTAINER_DLL_remove (ch->head_sent, ch->tail_sent, crm); + GNUNET_CONTAINER_DLL_remove(ch->head_sent, ch->tail_sent, crm); if (GNUNET_NO == ch->reliable) - { - GNUNET_free (crm->data_message); - GNUNET_free (crm); - ch->pending_messages--; - send_ack_to_client (ch, (NULL == ch->owner) ? GNUNET_NO : GNUNET_YES); - return; - } + { + GNUNET_free(crm->data_message); + GNUNET_free(crm); + ch->pending_messages--; + send_ack_to_client(ch, (NULL == ch->owner) ? GNUNET_NO : GNUNET_YES); + return; + } if (NULL == cid) - { - /* There was an error sending. */ - crm->num_transmissions = GNUNET_SYSERR; - } + { + /* There was an error sending. */ + crm->num_transmissions = GNUNET_SYSERR; + } else if (GNUNET_SYSERR != crm->num_transmissions) - { - /* Increment transmission counter, and possibly store @a cid - if this was the first transmission. */ - crm->num_transmissions++; - if (1 == crm->num_transmissions) { - crm->first_transmission_time = GNUNET_TIME_absolute_get (); - crm->connection_taken = *cid; - GCC_ack_expected (cid); + /* Increment transmission counter, and possibly store @a cid + if this was the first transmission. */ + crm->num_transmissions++; + if (1 == crm->num_transmissions) + { + crm->first_transmission_time = GNUNET_TIME_absolute_get(); + crm->connection_taken = *cid; + GCC_ack_expected(cid); + } } - } if ((0 == crm->retry_delay.rel_value_us) && (NULL != cid)) - { - struct CadetConnection *cc = GCC_lookup (cid); - - if (NULL != cc) - crm->retry_delay = GCC_get_metrics (cc)->aged_latency; - else - crm->retry_delay = ch->retry_time; - } - crm->retry_delay = GNUNET_TIME_STD_BACKOFF (crm->retry_delay); - crm->retry_delay = GNUNET_TIME_relative_max (crm->retry_delay, MIN_RTT_DELAY); - crm->next_retry = GNUNET_TIME_relative_to_absolute (crm->retry_delay); - - GNUNET_CONTAINER_DLL_insert_sorted (struct CadetReliableMessage, - cmp_crm_by_next_retry, - NULL, - ch->head_sent, - ch->tail_sent, - crm); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Message %u sent, next transmission on %s in %s\n", - (unsigned int) ntohl (crm->data_message->mid.mid), - GCCH_2s (ch), - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining ( - ch->head_sent->next_retry), - GNUNET_YES)); + { + struct CadetConnection *cc = GCC_lookup(cid); + + if (NULL != cc) + crm->retry_delay = GCC_get_metrics(cc)->aged_latency; + else + crm->retry_delay = ch->retry_time; + } + crm->retry_delay = GNUNET_TIME_STD_BACKOFF(crm->retry_delay); + crm->retry_delay = GNUNET_TIME_relative_max(crm->retry_delay, MIN_RTT_DELAY); + crm->next_retry = GNUNET_TIME_relative_to_absolute(crm->retry_delay); + + GNUNET_CONTAINER_DLL_insert_sorted(struct CadetReliableMessage, + cmp_crm_by_next_retry, + NULL, + ch->head_sent, + ch->tail_sent, + crm); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Message %u sent, next transmission on %s in %s\n", + (unsigned int)ntohl(crm->data_message->mid.mid), + GCCH_2s(ch), + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_remaining( + ch->head_sent->next_retry), + GNUNET_YES)); if (NULL == ch->head_sent->qe) - { - if (NULL != ch->retry_data_task) - GNUNET_SCHEDULER_cancel (ch->retry_data_task); - ch->retry_data_task = GNUNET_SCHEDULER_add_at (ch->head_sent->next_retry, - &retry_transmission, - ch); - } + { + if (NULL != ch->retry_data_task) + GNUNET_SCHEDULER_cancel(ch->retry_data_task); + ch->retry_data_task = GNUNET_SCHEDULER_add_at(ch->head_sent->next_retry, + &retry_transmission, + ch); + } } @@ -1769,100 +1769,100 @@ data_sent_cb (void *cls, * #GNUNET_SYSERR in case of an error. */ int -GCCH_handle_local_data (struct CadetChannel *ch, - struct GNUNET_CADET_ClientChannelNumber sender_ccn, - const char *buf, - size_t buf_len) +GCCH_handle_local_data(struct CadetChannel *ch, + struct GNUNET_CADET_ClientChannelNumber sender_ccn, + const char *buf, + size_t buf_len) { struct CadetReliableMessage *crm; if (ch->pending_messages >= ch->max_pending_messages) - { - GNUNET_break (0); /* Fails: #5370 */ - return GNUNET_SYSERR; - } - if (GNUNET_YES == ch->destroy) - { - /* we are going down, drop messages */ - return GNUNET_OK; - } - ch->pending_messages++; - - if (GNUNET_YES == ch->is_loopback) - { - struct CadetChannelClient *receiver; - struct GNUNET_MQ_Envelope *env; - struct GNUNET_CADET_LocalData *ld; - int ack_to_owner; - - env = - GNUNET_MQ_msg_extra (ld, buf_len, GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA); - if ((NULL != ch->owner) && - (sender_ccn.channel_of_client == ch->owner->ccn.channel_of_client)) - { - receiver = ch->dest; - ack_to_owner = GNUNET_YES; - } - else if ((NULL != ch->dest) && - (sender_ccn.channel_of_client == ch->dest->ccn.channel_of_client)) - { - receiver = ch->owner; - ack_to_owner = GNUNET_NO; - } - else { - GNUNET_break (0); + GNUNET_break(0); /* Fails: #5370 */ return GNUNET_SYSERR; } - GNUNET_assert (NULL != receiver); - ld->ccn = receiver->ccn; - GNUNET_memcpy (&ld[1], buf, buf_len); - if (GNUNET_YES == receiver->client_ready) + if (GNUNET_YES == ch->destroy) { - ch->pending_messages--; - GSC_send_to_client (receiver->c, env); - send_ack_to_client (ch, ack_to_owner); + /* we are going down, drop messages */ + return GNUNET_OK; } - else + ch->pending_messages++; + + if (GNUNET_YES == ch->is_loopback) { - struct CadetOutOfOrderMessage *oom; - - oom = GNUNET_new (struct CadetOutOfOrderMessage); - oom->env = env; - GNUNET_CONTAINER_DLL_insert_tail (receiver->head_recv, - receiver->tail_recv, - oom); - receiver->num_recv++; + struct CadetChannelClient *receiver; + struct GNUNET_MQ_Envelope *env; + struct GNUNET_CADET_LocalData *ld; + int ack_to_owner; + + env = + GNUNET_MQ_msg_extra(ld, buf_len, GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA); + if ((NULL != ch->owner) && + (sender_ccn.channel_of_client == ch->owner->ccn.channel_of_client)) + { + receiver = ch->dest; + ack_to_owner = GNUNET_YES; + } + else if ((NULL != ch->dest) && + (sender_ccn.channel_of_client == ch->dest->ccn.channel_of_client)) + { + receiver = ch->owner; + ack_to_owner = GNUNET_NO; + } + else + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + GNUNET_assert(NULL != receiver); + ld->ccn = receiver->ccn; + GNUNET_memcpy(&ld[1], buf, buf_len); + if (GNUNET_YES == receiver->client_ready) + { + ch->pending_messages--; + GSC_send_to_client(receiver->c, env); + send_ack_to_client(ch, ack_to_owner); + } + else + { + struct CadetOutOfOrderMessage *oom; + + oom = GNUNET_new(struct CadetOutOfOrderMessage); + oom->env = env; + GNUNET_CONTAINER_DLL_insert_tail(receiver->head_recv, + receiver->tail_recv, + oom); + receiver->num_recv++; + } + return GNUNET_OK; } - return GNUNET_OK; - } /* Everything is correct, send the message. */ - crm = GNUNET_malloc (sizeof (*crm)); + crm = GNUNET_malloc(sizeof(*crm)); crm->ch = ch; - crm->data_message = GNUNET_malloc ( - sizeof (struct GNUNET_CADET_ChannelAppDataMessage) + buf_len); + crm->data_message = GNUNET_malloc( + sizeof(struct GNUNET_CADET_ChannelAppDataMessage) + buf_len); crm->data_message->header.size = - htons (sizeof (struct GNUNET_CADET_ChannelAppDataMessage) + buf_len); + htons(sizeof(struct GNUNET_CADET_ChannelAppDataMessage) + buf_len); crm->data_message->header.type = - htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA); - ch->mid_send.mid = htonl (ntohl (ch->mid_send.mid) + 1); + htons(GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA); + ch->mid_send.mid = htonl(ntohl(ch->mid_send.mid) + 1); crm->data_message->mid = ch->mid_send; crm->data_message->ctn = ch->ctn; - GNUNET_memcpy (&crm->data_message[1], buf, buf_len); - GNUNET_CONTAINER_DLL_insert_tail (ch->head_sent, ch->tail_sent, crm); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending message %u from local client to %s with %u bytes\n", - ntohl (crm->data_message->mid.mid), - GCCH_2s (ch), - buf_len); + GNUNET_memcpy(&crm->data_message[1], buf, buf_len); + GNUNET_CONTAINER_DLL_insert_tail(ch->head_sent, ch->tail_sent, crm); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending message %u from local client to %s with %u bytes\n", + ntohl(crm->data_message->mid.mid), + GCCH_2s(ch), + buf_len); if (NULL != ch->retry_data_task) - { - GNUNET_SCHEDULER_cancel (ch->retry_data_task); - ch->retry_data_task = NULL; - } - crm->qe = GCT_send (ch->t, &crm->data_message->header, &data_sent_cb, crm); - GNUNET_assert (NULL == ch->retry_data_task); + { + GNUNET_SCHEDULER_cancel(ch->retry_data_task); + ch->retry_data_task = NULL; + } + crm->qe = GCT_send(ch->t, &crm->data_message->header, &data_sent_cb, crm); + GNUNET_assert(NULL == ch->retry_data_task); return GNUNET_OK; } @@ -1875,8 +1875,8 @@ GCCH_handle_local_data (struct CadetChannel *ch, * @param client_ccn ccn of the client sending the ack */ void -GCCH_handle_local_ack (struct CadetChannel *ch, - struct GNUNET_CADET_ClientChannelNumber client_ccn) +GCCH_handle_local_ack(struct CadetChannel *ch, + struct GNUNET_CADET_ClientChannelNumber client_ccn) { struct CadetChannelClient *ccc; struct CadetOutOfOrderMessage *com; @@ -1888,87 +1888,87 @@ GCCH_handle_local_ack (struct CadetChannel *ch, (ch->dest->ccn.channel_of_client == client_ccn.channel_of_client)) ccc = ch->dest; else - GNUNET_assert (0); + GNUNET_assert(0); ccc->client_ready = GNUNET_YES; com = ccc->head_recv; if (NULL == com) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got LOCAL_ACK, %s-%X ready to receive more data, but none pending on %s-%X(%p)!\n", - GSC_2s (ccc->c), - ntohl (client_ccn.channel_of_client), - GCCH_2s (ch), - ntohl (ccc->ccn.channel_of_client), - ccc); - return; /* none pending */ - } - if (GNUNET_YES == ch->is_loopback) - { - int to_owner; - - /* Messages are always in-order, just send */ - GNUNET_CONTAINER_DLL_remove (ccc->head_recv, ccc->tail_recv, com); - ccc->num_recv--; - GSC_send_to_client (ccc->c, com->env); - /* Notify sender that we can receive more */ - if ((NULL != ch->owner) && - (ccc->ccn.channel_of_client == ch->owner->ccn.channel_of_client)) { - to_owner = GNUNET_NO; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got LOCAL_ACK, %s-%X ready to receive more data, but none pending on %s-%X(%p)!\n", + GSC_2s(ccc->c), + ntohl(client_ccn.channel_of_client), + GCCH_2s(ch), + ntohl(ccc->ccn.channel_of_client), + ccc); + return; /* none pending */ } - else + if (GNUNET_YES == ch->is_loopback) { - GNUNET_assert ((NULL != ch->dest) && (ccc->ccn.channel_of_client == - ch->dest->ccn.channel_of_client)); - to_owner = GNUNET_YES; + int to_owner; + + /* Messages are always in-order, just send */ + GNUNET_CONTAINER_DLL_remove(ccc->head_recv, ccc->tail_recv, com); + ccc->num_recv--; + GSC_send_to_client(ccc->c, com->env); + /* Notify sender that we can receive more */ + if ((NULL != ch->owner) && + (ccc->ccn.channel_of_client == ch->owner->ccn.channel_of_client)) + { + to_owner = GNUNET_NO; + } + else + { + GNUNET_assert((NULL != ch->dest) && (ccc->ccn.channel_of_client == + ch->dest->ccn.channel_of_client)); + to_owner = GNUNET_YES; + } + send_ack_to_client(ch, to_owner); + GNUNET_free(com); + return; } - send_ack_to_client (ch, to_owner); - GNUNET_free (com); - return; - } if ((com->mid.mid != ch->mid_recv.mid) && (GNUNET_NO == ch->out_of_order) && (GNUNET_YES == ch->reliable)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got LOCAL_ACK, %s-%X ready to receive more data (but next one is out-of-order %u vs. %u)!\n", - GSC_2s (ccc->c), - ntohl (ccc->ccn.channel_of_client), - ntohl (com->mid.mid), - ntohl (ch->mid_recv.mid)); - return; /* missing next one in-order */ - } - - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got LOCAL_ACK, giving payload message %u to %s-%X on %s\n", - ntohl (com->mid.mid), - GSC_2s (ccc->c), - ntohl (ccc->ccn.channel_of_client), - GCCH_2s (ch)); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got LOCAL_ACK, %s-%X ready to receive more data (but next one is out-of-order %u vs. %u)!\n", + GSC_2s(ccc->c), + ntohl(ccc->ccn.channel_of_client), + ntohl(com->mid.mid), + ntohl(ch->mid_recv.mid)); + return; /* missing next one in-order */ + } + + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got LOCAL_ACK, giving payload message %u to %s-%X on %s\n", + ntohl(com->mid.mid), + GSC_2s(ccc->c), + ntohl(ccc->ccn.channel_of_client), + GCCH_2s(ch)); /* all good, pass next message to client */ - GNUNET_CONTAINER_DLL_remove (ccc->head_recv, ccc->tail_recv, com); + GNUNET_CONTAINER_DLL_remove(ccc->head_recv, ccc->tail_recv, com); ccc->num_recv--; /* FIXME: if unreliable, this is not aggressive enough, as it would be OK to have lost some! */ - ch->mid_recv.mid = htonl (1 + ntohl (com->mid.mid)); + ch->mid_recv.mid = htonl(1 + ntohl(com->mid.mid)); ch->mid_futures >>= 1; /* equivalent to division by 2 */ ccc->client_ready = GNUNET_NO; - GSC_send_to_client (ccc->c, com->env); - GNUNET_free (com); - send_channel_data_ack (ch); + GSC_send_to_client(ccc->c, com->env); + GNUNET_free(com); + send_channel_data_ack(ch); if (NULL != ccc->head_recv) return; if (GNUNET_NO == ch->destroy) return; - GCT_send_channel_destroy (ch->t, ch->ctn); - channel_destroy (ch); + GCT_send_channel_destroy(ch->t, ch->ctn); + channel_destroy(ch); } #define LOG2(level, ...) \ - GNUNET_log_from_nocheck (level, "cadet-chn", __VA_ARGS__) + GNUNET_log_from_nocheck(level, "cadet-chn", __VA_ARGS__) /** @@ -1978,46 +1978,46 @@ GCCH_handle_local_ack (struct CadetChannel *ch, * @param level Debug level to use. */ void -GCCH_debug (struct CadetChannel *ch, enum GNUNET_ErrorType level) +GCCH_debug(struct CadetChannel *ch, enum GNUNET_ErrorType level) { -#if ! defined(GNUNET_CULL_LOGGING) +#if !defined(GNUNET_CULL_LOGGING) int do_log; - do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK), - "cadet-chn", - __FILE__, - __FUNCTION__, - __LINE__); + do_log = GNUNET_get_log_call_status(level & (~GNUNET_ERROR_TYPE_BULK), + "cadet-chn", + __FILE__, + __FUNCTION__, + __LINE__); if (0 == do_log) return; if (NULL == ch) - { - LOG2 (level, "CHN *** DEBUG NULL CHANNEL ***\n"); - return; - } - LOG2 (level, "CHN %s:%X (%p)\n", GCT_2s (ch->t), ch->ctn, ch); + { + LOG2(level, "CHN *** DEBUG NULL CHANNEL ***\n"); + return; + } + LOG2(level, "CHN %s:%X (%p)\n", GCT_2s(ch->t), ch->ctn, ch); if (NULL != ch->owner) - { - LOG2 (level, - "CHN origin %s ready %s local-id: %u\n", - GSC_2s (ch->owner->c), - ch->owner->client_ready ? "YES" : "NO", - ntohl (ch->owner->ccn.channel_of_client)); - } + { + LOG2(level, + "CHN origin %s ready %s local-id: %u\n", + GSC_2s(ch->owner->c), + ch->owner->client_ready ? "YES" : "NO", + ntohl(ch->owner->ccn.channel_of_client)); + } if (NULL != ch->dest) - { - LOG2 (level, - "CHN destination %s ready %s local-id: %u\n", - GSC_2s (ch->dest->c), - ch->dest->client_ready ? "YES" : "NO", - ntohl (ch->dest->ccn.channel_of_client)); - } - LOG2 (level, - "CHN Message IDs recv: %d (%LLX), send: %d\n", - ntohl (ch->mid_recv.mid), - (unsigned long long) ch->mid_futures, - ntohl (ch->mid_send.mid)); + { + LOG2(level, + "CHN destination %s ready %s local-id: %u\n", + GSC_2s(ch->dest->c), + ch->dest->client_ready ? "YES" : "NO", + ntohl(ch->dest->ccn.channel_of_client)); + } + LOG2(level, + "CHN Message IDs recv: %d (%LLX), send: %d\n", + ntohl(ch->mid_recv.mid), + (unsigned long long)ch->mid_futures, + ntohl(ch->mid_send.mid)); #endif } diff --git a/src/cadet/gnunet-service-cadet_channel.h b/src/cadet/gnunet-service-cadet_channel.h index 2eb28262d..a64d4058e 100644 --- a/src/cadet/gnunet-service-cadet_channel.h +++ b/src/cadet/gnunet-service-cadet_channel.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_channel.h @@ -44,7 +44,7 @@ struct CadetChannel; /** - * Hash the @a port and @a initiator and @a listener to + * Hash the @a port and @a initiator and @a listener to * calculate the "challenge" @a h_port we send to the other * peer on #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN. * @@ -53,9 +53,9 @@ struct CadetChannel; * @param listener peer that is listining on @a port */ void -GCCH_hash_port (struct GNUNET_HashCode *h_port, - const struct GNUNET_HashCode *port, - const struct GNUNET_PeerIdentity *listener); +GCCH_hash_port(struct GNUNET_HashCode *h_port, + const struct GNUNET_HashCode *port, + const struct GNUNET_PeerIdentity *listener); /** @@ -66,7 +66,7 @@ GCCH_hash_port (struct GNUNET_HashCode *h_port, * @return Static string with the channel IDs. */ const char * -GCCH_2s (const struct CadetChannel *ch); +GCCH_2s(const struct CadetChannel *ch); /** @@ -76,8 +76,8 @@ GCCH_2s (const struct CadetChannel *ch); * @param level Debug level to use. */ void -GCCH_debug (struct CadetChannel *ch, - enum GNUNET_ErrorType level); +GCCH_debug(struct CadetChannel *ch, + enum GNUNET_ErrorType level); /** @@ -88,7 +88,7 @@ GCCH_debug (struct CadetChannel *ch, * @return ID used to identify the channel with the remote peer. */ struct GNUNET_CADET_ChannelTunnelNumber -GCCH_get_id (const struct CadetChannel *ch); +GCCH_get_id(const struct CadetChannel *ch); /** @@ -102,11 +102,11 @@ GCCH_get_id (const struct CadetChannel *ch); * @return handle to the new channel */ struct CadetChannel * -GCCH_channel_local_new (struct CadetClient *owner, - struct GNUNET_CADET_ClientChannelNumber owner_id, - struct CadetPeer *destination, - const struct GNUNET_HashCode *port, - uint32_t options); +GCCH_channel_local_new(struct CadetClient *owner, + struct GNUNET_CADET_ClientChannelNumber owner_id, + struct CadetPeer *destination, + const struct GNUNET_HashCode *port, + uint32_t options); /** @@ -119,9 +119,9 @@ GCCH_channel_local_new (struct CadetClient *owner, * @param port port number @a c is listening on */ void -GCCH_bind (struct CadetChannel *ch, - struct CadetClient *c, - const struct GNUNET_HashCode *port); +GCCH_bind(struct CadetChannel *ch, + struct CadetClient *c, + const struct GNUNET_HashCode *port); /** @@ -133,9 +133,9 @@ GCCH_bind (struct CadetChannel *ch, * @param ccn client number of the client @a c */ void -GCCH_channel_local_destroy (struct CadetChannel *ch, - struct CadetClient *c, - struct GNUNET_CADET_ClientChannelNumber ccn); +GCCH_channel_local_destroy(struct CadetChannel *ch, + struct CadetClient *c, + struct GNUNET_CADET_ClientChannelNumber ccn); /** @@ -149,7 +149,7 @@ GCCH_channel_local_destroy (struct CadetChannel *ch, * @param ch the channel for which the tunnel is now ready */ void -GCCH_tunnel_up (struct CadetChannel *ch); +GCCH_tunnel_up(struct CadetChannel *ch); /** @@ -163,10 +163,10 @@ GCCH_tunnel_up (struct CadetChannel *ch); * @return handle to the new channel */ struct CadetChannel * -GCCH_channel_incoming_new (struct CadetTunnel *t, - struct GNUNET_CADET_ChannelTunnelNumber chid, - const struct GNUNET_HashCode *h_port, - uint32_t options); +GCCH_channel_incoming_new(struct CadetTunnel *t, + struct GNUNET_CADET_ChannelTunnelNumber chid, + const struct GNUNET_HashCode *h_port, + uint32_t options); /** @@ -178,8 +178,8 @@ GCCH_channel_incoming_new (struct CadetTunnel *t, * @param cti identifier of the connection that delivered the message */ void -GCCH_handle_duplicate_open (struct CadetChannel *ch, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti); +GCCH_handle_duplicate_open(struct CadetChannel *ch, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti); @@ -191,9 +191,9 @@ GCCH_handle_duplicate_open (struct CadetChannel *ch, * @param msg message that was received */ void -GCCH_handle_channel_plaintext_data (struct CadetChannel *ch, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, - const struct GNUNET_CADET_ChannelAppDataMessage *msg); +GCCH_handle_channel_plaintext_data(struct CadetChannel *ch, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, + const struct GNUNET_CADET_ChannelAppDataMessage *msg); /** @@ -205,9 +205,9 @@ GCCH_handle_channel_plaintext_data (struct CadetChannel *ch, * @param ack details about what was received */ void -GCCH_handle_channel_plaintext_data_ack (struct CadetChannel *ch, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, - const struct GNUNET_CADET_ChannelDataAckMessage *ack); +GCCH_handle_channel_plaintext_data_ack(struct CadetChannel *ch, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, + const struct GNUNET_CADET_ChannelDataAckMessage *ack); /** @@ -220,9 +220,9 @@ GCCH_handle_channel_plaintext_data_ack (struct CadetChannel *ch, * @param port port number (needed to verify receiver knows the port) */ void -GCCH_handle_channel_open_ack (struct CadetChannel *ch, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, - const struct GNUNET_HashCode *port); +GCCH_handle_channel_open_ack(struct CadetChannel *ch, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, + const struct GNUNET_HashCode *port); /** @@ -242,8 +242,8 @@ GCCH_handle_channel_open_ack (struct CadetChannel *ch, * NULL during shutdown */ void -GCCH_handle_remote_destroy (struct CadetChannel *ch, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti); +GCCH_handle_remote_destroy(struct CadetChannel *ch, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti); /** @@ -261,10 +261,10 @@ GCCH_handle_remote_destroy (struct CadetChannel *ch, * #GNUNET_SYSERR in case of an error. */ int -GCCH_handle_local_data (struct CadetChannel *ch, - struct GNUNET_CADET_ClientChannelNumber sender_ccn, - const char *buf, - size_t buf_len); +GCCH_handle_local_data(struct CadetChannel *ch, + struct GNUNET_CADET_ClientChannelNumber sender_ccn, + const char *buf, + size_t buf_len); /** @@ -274,7 +274,7 @@ GCCH_handle_local_data (struct CadetChannel *ch, * @param client_ccn ccn of the client sending the ack */ void -GCCH_handle_local_ack (struct CadetChannel *ch, - struct GNUNET_CADET_ClientChannelNumber client_ccn); +GCCH_handle_local_ack(struct CadetChannel *ch, + struct GNUNET_CADET_ClientChannelNumber client_ccn); #endif diff --git a/src/cadet/gnunet-service-cadet_connection.c b/src/cadet/gnunet-service-cadet_connection.c index 8849e563f..e3c1a4124 100644 --- a/src/cadet/gnunet-service-cadet_connection.c +++ b/src/cadet/gnunet-service-cadet_connection.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_connection.c @@ -35,7 +35,7 @@ #include "cadet_protocol.h" -#define LOG(level, ...) GNUNET_log_from (level, "cadet-con", __VA_ARGS__) +#define LOG(level, ...) GNUNET_log_from(level, "cadet-con", __VA_ARGS__) /** @@ -43,14 +43,13 @@ * TODO: replace by 2 RTT if/once we have connection-level RTT data! */ #define INITIAL_CONNECTION_CREATE_RETRY_DELAY \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 200) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 200) /** * All the states a connection can be in. */ -enum CadetConnectionState -{ +enum CadetConnectionState { /** * Uninitialized status, we have not yet even gotten the message queue. */ @@ -76,16 +75,13 @@ enum CadetConnectionState * Connection confirmed, ready to carry traffic. */ CADET_CONNECTION_READY - }; /** * Low-level connection to a destination. */ -struct CadetConnection -{ - +struct CadetConnection { /** * ID of the connection. */ @@ -185,10 +181,10 @@ struct CadetConnection * @return NULL if connection was not found */ struct CadetConnection * -GCC_lookup (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) +GCC_lookup(const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) { - return GNUNET_CONTAINER_multishortmap_get (connections, - &cid->connection_of_tunnel); + return GNUNET_CONTAINER_multishortmap_get(connections, + &cid->connection_of_tunnel); } @@ -201,9 +197,9 @@ GCC_lookup (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) * @param new_mqm_ready new `mqm_ready` state for @a cc */ static void -update_state (struct CadetConnection *cc, - enum CadetConnectionState new_state, - int new_mqm_ready) +update_state(struct CadetConnection *cc, + enum CadetConnectionState new_state, + int new_mqm_ready) { int old_ready; int new_ready; @@ -217,7 +213,7 @@ update_state (struct CadetConnection *cc, cc->state = new_state; cc->mqm_ready = new_mqm_ready; if (old_ready != new_ready) - cc->ready_cb (cc->ready_cb_cls, new_ready); + cc->ready_cb(cc->ready_cb_cls, new_ready); } @@ -228,34 +224,34 @@ update_state (struct CadetConnection *cc, * @param cc connection to destroy */ static void -GCC_destroy (struct CadetConnection *cc) +GCC_destroy(struct CadetConnection *cc) { - LOG (GNUNET_ERROR_TYPE_DEBUG, "Destroying %s\n", GCC_2s (cc)); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Destroying %s\n", GCC_2s(cc)); if (NULL != cc->mq_man) - { - GCP_request_mq_cancel (cc->mq_man, NULL); - cc->mq_man = NULL; - } + { + GCP_request_mq_cancel(cc->mq_man, NULL); + cc->mq_man = NULL; + } if (NULL != cc->task) - { - GNUNET_SCHEDULER_cancel (cc->task); - cc->task = NULL; - } + { + GNUNET_SCHEDULER_cancel(cc->task); + cc->task = NULL; + } if (NULL != cc->keepalive_qe) - { - GCT_send_cancel (cc->keepalive_qe); - cc->keepalive_qe = NULL; - } - GCPP_del_connection (cc->path, cc->off, cc); + { + GCT_send_cancel(cc->keepalive_qe); + cc->keepalive_qe = NULL; + } + GCPP_del_connection(cc->path, cc->off, cc); for (unsigned int i = 0; i < cc->off; i++) - GCP_remove_connection (GCPP_get_peer_at_offset (cc->path, i), cc); - GNUNET_assert ( + GCP_remove_connection(GCPP_get_peer_at_offset(cc->path, i), cc); + GNUNET_assert( GNUNET_YES == - GNUNET_CONTAINER_multishortmap_remove (connections, - &GCC_get_id (cc) - ->connection_of_tunnel, - cc)); - GNUNET_free (cc); + GNUNET_CONTAINER_multishortmap_remove(connections, + &GCC_get_id(cc) + ->connection_of_tunnel, + cc)); + GNUNET_free(cc); } @@ -268,14 +264,14 @@ GCC_destroy (struct CadetConnection *cc) * @param cc connection to destroy */ void -GCC_destroy_without_core (struct CadetConnection *cc) +GCC_destroy_without_core(struct CadetConnection *cc) { if (NULL != cc->ct) - { - GCT_connection_lost (cc->ct); - cc->ct = NULL; - } - GCC_destroy (cc); + { + GCT_connection_lost(cc->ct); + cc->ct = NULL; + } + GCC_destroy(cc); } @@ -287,22 +283,22 @@ GCC_destroy_without_core (struct CadetConnection *cc) * @param cc connection to destroy */ void -GCC_destroy_without_tunnel (struct CadetConnection *cc) +GCC_destroy_without_tunnel(struct CadetConnection *cc) { cc->ct = NULL; if ((CADET_CONNECTION_SENDING_CREATE != cc->state) && (NULL != cc->mq_man)) - { - struct GNUNET_MQ_Envelope *env; - struct GNUNET_CADET_ConnectionDestroyMessage *destroy_msg; - - /* Need to notify next hop that we are down. */ - env = - GNUNET_MQ_msg (destroy_msg, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY); - destroy_msg->cid = cc->cid; - GCP_request_mq_cancel (cc->mq_man, env); - cc->mq_man = NULL; - } - GCC_destroy (cc); + { + struct GNUNET_MQ_Envelope *env; + struct GNUNET_CADET_ConnectionDestroyMessage *destroy_msg; + + /* Need to notify next hop that we are down. */ + env = + GNUNET_MQ_msg(destroy_msg, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY); + destroy_msg->cid = cc->cid; + GCP_request_mq_cancel(cc->mq_man, env); + cc->mq_man = NULL; + } + GCC_destroy(cc); } @@ -313,7 +309,7 @@ GCC_destroy_without_tunnel (struct CadetConnection *cc) * @return corresponding entry in the tunnel's connection list */ struct CadetTConnection * -GCC_get_ct (struct CadetConnection *cc) +GCC_get_ct(struct CadetConnection *cc) { return cc->ct; } @@ -326,7 +322,7 @@ GCC_get_ct (struct CadetConnection *cc) * @return the metrics */ const struct CadetConnectionMetrics * -GCC_get_metrics (struct CadetConnection *cc) +GCC_get_metrics(struct CadetConnection *cc) { return &cc->metrics; } @@ -339,7 +335,7 @@ GCC_get_metrics (struct CadetConnection *cc) * @param cls the `struct CadetConnection` to keep alive. */ static void -send_keepalive (void *cls); +send_keepalive(void *cls); /** @@ -351,15 +347,15 @@ send_keepalive (void *cls); * if transmission failed */ static void -keepalive_done (void *cls, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) +keepalive_done(void *cls, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) { struct CadetConnection *cc = cls; cc->keepalive_qe = NULL; if ((GNUNET_YES == cc->mqm_ready) && (NULL == cc->task)) cc->task = - GNUNET_SCHEDULER_add_delayed (keepalive_period, &send_keepalive, cc); + GNUNET_SCHEDULER_add_delayed(keepalive_period, &send_keepalive, cc); } @@ -370,31 +366,31 @@ keepalive_done (void *cls, * @param cls the `struct CadetConnection` to keep alive. */ static void -send_keepalive (void *cls) +send_keepalive(void *cls) { struct CadetConnection *cc = cls; struct GNUNET_MessageHeader msg; cc->task = NULL; - if (CADET_TUNNEL_KEY_OK != GCT_get_estate (cc->ct->t)) - { - /* Tunnel not yet ready, wait with keepalives... */ - cc->task = - GNUNET_SCHEDULER_add_delayed (keepalive_period, &send_keepalive, cc); - return; - } - GNUNET_assert (NULL != cc->ct); - GNUNET_assert (GNUNET_YES == cc->mqm_ready); - GNUNET_assert (NULL == cc->keepalive_qe); - LOG (GNUNET_ERROR_TYPE_INFO, - "Sending KEEPALIVE on behalf of %s via %s\n", - GCC_2s (cc), - GCT_2s (cc->ct->t)); - GNUNET_STATISTICS_update (stats, "# keepalives sent", 1, GNUNET_NO); - msg.size = htons (sizeof (msg)); - msg.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE); - - cc->keepalive_qe = GCT_send (cc->ct->t, &msg, &keepalive_done, cc); + if (CADET_TUNNEL_KEY_OK != GCT_get_estate(cc->ct->t)) + { + /* Tunnel not yet ready, wait with keepalives... */ + cc->task = + GNUNET_SCHEDULER_add_delayed(keepalive_period, &send_keepalive, cc); + return; + } + GNUNET_assert(NULL != cc->ct); + GNUNET_assert(GNUNET_YES == cc->mqm_ready); + GNUNET_assert(NULL == cc->keepalive_qe); + LOG(GNUNET_ERROR_TYPE_INFO, + "Sending KEEPALIVE on behalf of %s via %s\n", + GCC_2s(cc), + GCT_2s(cc->ct->t)); + GNUNET_STATISTICS_update(stats, "# keepalives sent", 1, GNUNET_NO); + msg.size = htons(sizeof(msg)); + msg.type = htons(GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE); + + cc->keepalive_qe = GCT_send(cc->ct->t, &msg, &keepalive_done, cc); } @@ -405,11 +401,11 @@ send_keepalive (void *cls) * @param cid connection identifier where we expect an ACK */ void -GCC_ack_expected (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) +GCC_ack_expected(const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) { struct CadetConnection *cc; - cc = GCC_lookup (cid); + cc = GCC_lookup(cid); if (NULL == cc) return; /* whopise, connection alredy down? */ cc->metrics.num_acked_transmissions++; @@ -425,11 +421,11 @@ GCC_ack_expected (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) * may have gotten back to us via a different connection). */ void -GCC_ack_observed (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) +GCC_ack_observed(const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) { struct CadetConnection *cc; - cc = GCC_lookup (cid); + cc = GCC_lookup(cid); if (NULL == cc) return; /* whopise, connection alredy down? */ cc->metrics.num_successes++; @@ -445,17 +441,17 @@ GCC_ack_observed (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) * @param latency the observed latency */ void -GCC_latency_observed (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, - struct GNUNET_TIME_Relative latency) +GCC_latency_observed(const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, + struct GNUNET_TIME_Relative latency) { struct CadetConnection *cc; double weight; double result; - cc = GCC_lookup (cid); + cc = GCC_lookup(cid); if (NULL == cc) return; /* whopise, connection alredy down? */ - GNUNET_STATISTICS_update (stats, "# latencies observed", 1, GNUNET_NO); + GNUNET_STATISTICS_update(stats, "# latencies observed", 1, GNUNET_NO); cc->latency_datapoints++; if (cc->latency_datapoints >= 7) weight = 7.0; @@ -467,7 +463,7 @@ GCC_latency_observed (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, result = (weight * cc->metrics.aged_latency.rel_value_us) + 1.0 * latency.rel_value_us; result /= (weight + 1.0); - cc->metrics.aged_latency.rel_value_us = (uint64_t) result; + cc->metrics.aged_latency.rel_value_us = (uint64_t)result; } @@ -479,26 +475,26 @@ GCC_latency_observed (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, * @param cc the connection that got the ACK. */ void -GCC_handle_connection_create_ack (struct CadetConnection *cc) +GCC_handle_connection_create_ack(struct CadetConnection *cc) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received CADET_CONNECTION_CREATE_ACK for %s in state %d (%s)\n", - GCC_2s (cc), - cc->state, - (GNUNET_YES == cc->mqm_ready) ? "MQM ready" : "MQM busy"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received CADET_CONNECTION_CREATE_ACK for %s in state %d (%s)\n", + GCC_2s(cc), + cc->state, + (GNUNET_YES == cc->mqm_ready) ? "MQM ready" : "MQM busy"); if (CADET_CONNECTION_READY == cc->state) return; /* Duplicate ACK, ignore */ if (NULL != cc->task) - { - GNUNET_SCHEDULER_cancel (cc->task); - cc->task = NULL; - } - cc->metrics.age = GNUNET_TIME_absolute_get (); - update_state (cc, CADET_CONNECTION_READY, cc->mqm_ready); + { + GNUNET_SCHEDULER_cancel(cc->task); + cc->task = NULL; + } + cc->metrics.age = GNUNET_TIME_absolute_get(); + update_state(cc, CADET_CONNECTION_READY, cc->mqm_ready); if ((NULL == cc->keepalive_qe) && (GNUNET_YES == cc->mqm_ready) && (NULL == cc->task)) cc->task = - GNUNET_SCHEDULER_add_delayed (keepalive_period, &send_keepalive, cc); + GNUNET_SCHEDULER_add_delayed(keepalive_period, &send_keepalive, cc); } @@ -509,24 +505,24 @@ GCC_handle_connection_create_ack (struct CadetConnection *cc) * @param msg the key exchange message */ void -GCC_handle_kx (struct CadetConnection *cc, - const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg) +GCC_handle_kx(struct CadetConnection *cc, + const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received KX message with ephermal %s on CC %s in state %d\n", - GNUNET_e2s (&msg->ephemeral_key), - GNUNET_sh2s (&cc->cid.connection_of_tunnel), - cc->state); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received KX message with ephermal %s on CC %s in state %d\n", + GNUNET_e2s(&msg->ephemeral_key), + GNUNET_sh2s(&cc->cid.connection_of_tunnel), + cc->state); if (CADET_CONNECTION_SENT == cc->state) - { - /* We didn't get the CADET_CONNECTION_CREATE_ACK, but instead got payload. That's fine, - clearly something is working, so pretend we got an ACK. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Faking connection CADET_CONNECTION_CREATE_ACK for %s due to KX\n", - GCC_2s (cc)); - GCC_handle_connection_create_ack (cc); - } - GCT_handle_kx (cc->ct, msg); + { + /* We didn't get the CADET_CONNECTION_CREATE_ACK, but instead got payload. That's fine, + clearly something is working, so pretend we got an ACK. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Faking connection CADET_CONNECTION_CREATE_ACK for %s due to KX\n", + GCC_2s(cc)); + GCC_handle_connection_create_ack(cc); + } + GCT_handle_kx(cc->ct, msg); } @@ -537,24 +533,24 @@ GCC_handle_kx (struct CadetConnection *cc, * @param msg the key exchange message */ void -GCC_handle_kx_auth (struct CadetConnection *cc, - const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg) +GCC_handle_kx_auth(struct CadetConnection *cc, + const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received KX AUTH message with ephermal %s on CC %s in state %d\n", - GNUNET_e2s (&msg->kx.ephemeral_key), - GNUNET_sh2s (&cc->cid.connection_of_tunnel), - cc->state); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received KX AUTH message with ephermal %s on CC %s in state %d\n", + GNUNET_e2s(&msg->kx.ephemeral_key), + GNUNET_sh2s(&cc->cid.connection_of_tunnel), + cc->state); if (CADET_CONNECTION_SENT == cc->state) - { - /* We didn't get the CADET_CONNECTION_CREATE_ACK, but instead got payload. That's fine, - clearly something is working, so pretend we got an ACK. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Faking connection CADET_CONNECTION_CREATE_ACK for %s due to KX\n", - GCC_2s (cc)); - GCC_handle_connection_create_ack (cc); - } - GCT_handle_kx_auth (cc->ct, msg); + { + /* We didn't get the CADET_CONNECTION_CREATE_ACK, but instead got payload. That's fine, + clearly something is working, so pretend we got an ACK. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Faking connection CADET_CONNECTION_CREATE_ACK for %s due to KX\n", + GCC_2s(cc)); + GCC_handle_connection_create_ack(cc); + } + GCT_handle_kx_auth(cc->ct, msg); } @@ -565,20 +561,20 @@ GCC_handle_kx_auth (struct CadetConnection *cc, * @param msg the encrypted message to decrypt */ void -GCC_handle_encrypted (struct CadetConnection *cc, - const struct GNUNET_CADET_TunnelEncryptedMessage *msg) +GCC_handle_encrypted(struct CadetConnection *cc, + const struct GNUNET_CADET_TunnelEncryptedMessage *msg) { if (CADET_CONNECTION_SENT == cc->state) - { - /* We didn't get the CREATE_ACK, but instead got payload. That's fine, - clearly something is working, so pretend we got an ACK. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Faking connection ACK for %s due to ENCRYPTED payload\n", - GCC_2s (cc)); - GCC_handle_connection_create_ack (cc); - } - cc->metrics.last_use = GNUNET_TIME_absolute_get (); - GCT_handle_encrypted (cc->ct, msg); + { + /* We didn't get the CREATE_ACK, but instead got payload. That's fine, + clearly something is working, so pretend we got an ACK. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Faking connection ACK for %s due to ENCRYPTED payload\n", + GCC_2s(cc)); + GCC_handle_connection_create_ack(cc); + } + cc->metrics.last_use = GNUNET_TIME_absolute_get(); + GCT_handle_encrypted(cc->ct, msg); } @@ -589,7 +585,7 @@ GCC_handle_encrypted (struct CadetConnection *cc, * @param cls the `struct CadetConnection` to initiate */ static void -send_create (void *cls) +send_create(void *cls) { struct CadetConnection *cc = cls; struct GNUNET_CADET_ConnectionCreateMessage *create_msg; @@ -597,27 +593,27 @@ send_create (void *cls) struct GNUNET_MQ_Envelope *env; cc->task = NULL; - GNUNET_assert (GNUNET_YES == cc->mqm_ready); + GNUNET_assert(GNUNET_YES == cc->mqm_ready); env = - GNUNET_MQ_msg_extra (create_msg, - (2 + cc->off) * sizeof (struct GNUNET_PeerIdentity), - GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE); + GNUNET_MQ_msg_extra(create_msg, + (2 + cc->off) * sizeof(struct GNUNET_PeerIdentity), + GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE); //TODO This will be removed in a major release, because this will be a protocol breaking change. We set the deprecated 'reliable' bit here that was removed. create_msg->options = 2; create_msg->cid = cc->cid; - pids = (struct GNUNET_PeerIdentity *) &create_msg[1]; + pids = (struct GNUNET_PeerIdentity *)&create_msg[1]; pids[0] = my_full_id; for (unsigned int i = 0; i <= cc->off; i++) - pids[i + 1] = *GCP_get_id (GCPP_get_peer_at_offset (cc->path, i)); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending CADET_CONNECTION_CREATE message for %s with %u hops\n", - GCC_2s (cc), - cc->off + 2); + pids[i + 1] = *GCP_get_id(GCPP_get_peer_at_offset(cc->path, i)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending CADET_CONNECTION_CREATE message for %s with %u hops\n", + GCC_2s(cc), + cc->off + 2); cc->env = env; - cc->retry_delay = GNUNET_TIME_STD_BACKOFF (cc->retry_delay); - cc->create_at = GNUNET_TIME_relative_to_absolute (cc->retry_delay); - update_state (cc, CADET_CONNECTION_SENT, GNUNET_NO); - GCP_send (cc->mq_man, env); + cc->retry_delay = GNUNET_TIME_STD_BACKOFF(cc->retry_delay); + cc->create_at = GNUNET_TIME_relative_to_absolute(cc->retry_delay); + update_state(cc, CADET_CONNECTION_SENT, GNUNET_NO); + GCP_send(cc->mq_man, env); } @@ -627,29 +623,29 @@ send_create (void *cls) * @param cls the `struct CadetConnection` to initiate */ static void -send_create_ack (void *cls) +send_create_ack(void *cls) { struct CadetConnection *cc = cls; struct GNUNET_CADET_ConnectionCreateAckMessage *ack_msg; struct GNUNET_MQ_Envelope *env; cc->task = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending CONNECTION_CREATE_ACK message for %s\n", - GCC_2s (cc)); - GNUNET_assert (GNUNET_YES == cc->mqm_ready); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending CONNECTION_CREATE_ACK message for %s\n", + GCC_2s(cc)); + GNUNET_assert(GNUNET_YES == cc->mqm_ready); env = - GNUNET_MQ_msg (ack_msg, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE_ACK); + GNUNET_MQ_msg(ack_msg, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE_ACK); ack_msg->cid = cc->cid; cc->env = env; - cc->retry_delay = GNUNET_TIME_STD_BACKOFF (cc->retry_delay); - cc->create_ack_at = GNUNET_TIME_relative_to_absolute (cc->retry_delay); + cc->retry_delay = GNUNET_TIME_STD_BACKOFF(cc->retry_delay); + cc->create_ack_at = GNUNET_TIME_relative_to_absolute(cc->retry_delay); if (CADET_CONNECTION_CREATE_RECEIVED == cc->state) - update_state (cc, CADET_CONNECTION_READY, GNUNET_NO); + update_state(cc, CADET_CONNECTION_READY, GNUNET_NO); if (CADET_CONNECTION_READY == cc->state) cc->task = - GNUNET_SCHEDULER_add_delayed (keepalive_period, &send_keepalive, cc); - GCP_send (cc->mq_man, env); + GNUNET_SCHEDULER_add_delayed(keepalive_period, &send_keepalive, cc); + GCP_send(cc->mq_man, env); } @@ -661,31 +657,31 @@ send_create_ack (void *cls) * @param cc connection that got the duplicate CREATE */ void -GCC_handle_duplicate_create (struct CadetConnection *cc) +GCC_handle_duplicate_create(struct CadetConnection *cc) { if (GNUNET_YES == cc->mqm_ready) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got duplicate CREATE for %s, scheduling another ACK (%s)\n", - GCC_2s (cc), - (GNUNET_YES == cc->mqm_ready) ? "MQM ready" : "MQM busy"); - /* Revert back to the state of having only received the 'CREATE', - and immediately proceed to send the CREATE_ACK. */ - update_state (cc, CADET_CONNECTION_CREATE_RECEIVED, cc->mqm_ready); - if (NULL != cc->task) - GNUNET_SCHEDULER_cancel (cc->task); - cc->task = - GNUNET_SCHEDULER_add_at (cc->create_ack_at, &send_create_ack, cc); - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got duplicate CREATE for %s, scheduling another ACK (%s)\n", + GCC_2s(cc), + (GNUNET_YES == cc->mqm_ready) ? "MQM ready" : "MQM busy"); + /* Revert back to the state of having only received the 'CREATE', + and immediately proceed to send the CREATE_ACK. */ + update_state(cc, CADET_CONNECTION_CREATE_RECEIVED, cc->mqm_ready); + if (NULL != cc->task) + GNUNET_SCHEDULER_cancel(cc->task); + cc->task = + GNUNET_SCHEDULER_add_at(cc->create_ack_at, &send_create_ack, cc); + } else - { - /* We are currently sending something else back, which - can only be an ACK or payload, either of which would - do. So actually no need to do anything. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got duplicate CREATE for %s. MQ is busy, not queueing another ACK\n", - GCC_2s (cc)); - } + { + /* We are currently sending something else back, which + can only be an ACK or payload, either of which would + do. So actually no need to do anything. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got duplicate CREATE for %s. MQ is busy, not queueing another ACK\n", + GCC_2s(cc)); + } } @@ -700,63 +696,67 @@ GCC_handle_duplicate_create (struct CadetConnection *cc) * and the last envelope was discarded */ static void -manage_first_hop_mq (void *cls, int available) +manage_first_hop_mq(void *cls, int available) { struct CadetConnection *cc = cls; if (GNUNET_YES != available) - { - /* Connection is down, for now... */ - LOG (GNUNET_ERROR_TYPE_DEBUG, "Core MQ for %s went down\n", GCC_2s (cc)); - update_state (cc, CADET_CONNECTION_NEW, GNUNET_NO); - cc->retry_delay = INITIAL_CONNECTION_CREATE_RETRY_DELAY; - if (NULL != cc->task) { - GNUNET_SCHEDULER_cancel (cc->task); - cc->task = NULL; + /* Connection is down, for now... */ + LOG(GNUNET_ERROR_TYPE_DEBUG, "Core MQ for %s went down\n", GCC_2s(cc)); + update_state(cc, CADET_CONNECTION_NEW, GNUNET_NO); + cc->retry_delay = INITIAL_CONNECTION_CREATE_RETRY_DELAY; + if (NULL != cc->task) + { + GNUNET_SCHEDULER_cancel(cc->task); + cc->task = NULL; + } + return; } - return; - } - update_state (cc, cc->state, GNUNET_YES); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Core MQ for %s became available in state %d\n", - GCC_2s (cc), - cc->state); + update_state(cc, cc->state, GNUNET_YES); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Core MQ for %s became available in state %d\n", + GCC_2s(cc), + cc->state); switch (cc->state) - { - case CADET_CONNECTION_NEW: - /* Transmit immediately */ - cc->task = GNUNET_SCHEDULER_add_at (cc->create_at, &send_create, cc); - break; - case CADET_CONNECTION_SENDING_CREATE: - /* Should not be possible to be called in this state. */ - GNUNET_assert (0); - break; - case CADET_CONNECTION_SENT: - /* Retry a bit later... */ - cc->task = GNUNET_SCHEDULER_add_at (cc->create_at, &send_create, cc); - break; - case CADET_CONNECTION_CREATE_RECEIVED: - /* We got the 'CREATE' (incoming connection), should send the CREATE_ACK */ - cc->metrics.age = GNUNET_TIME_absolute_get (); - cc->task = - GNUNET_SCHEDULER_add_at (cc->create_ack_at, &send_create_ack, cc); - break; - case CADET_CONNECTION_READY: - if ((NULL == cc->keepalive_qe) && (GNUNET_YES == cc->mqm_ready) && - (NULL == cc->task)) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Scheduling keepalive for %s in %s\n", - GCC_2s (cc), - GNUNET_STRINGS_relative_time_to_string (keepalive_period, - GNUNET_YES)); + case CADET_CONNECTION_NEW: + /* Transmit immediately */ + cc->task = GNUNET_SCHEDULER_add_at(cc->create_at, &send_create, cc); + break; + + case CADET_CONNECTION_SENDING_CREATE: + /* Should not be possible to be called in this state. */ + GNUNET_assert(0); + break; + + case CADET_CONNECTION_SENT: + /* Retry a bit later... */ + cc->task = GNUNET_SCHEDULER_add_at(cc->create_at, &send_create, cc); + break; + + case CADET_CONNECTION_CREATE_RECEIVED: + /* We got the 'CREATE' (incoming connection), should send the CREATE_ACK */ + cc->metrics.age = GNUNET_TIME_absolute_get(); cc->task = - GNUNET_SCHEDULER_add_delayed (keepalive_period, &send_keepalive, cc); + GNUNET_SCHEDULER_add_at(cc->create_ack_at, &send_create_ack, cc); + break; + + case CADET_CONNECTION_READY: + if ((NULL == cc->keepalive_qe) && (GNUNET_YES == cc->mqm_ready) && + (NULL == cc->task)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Scheduling keepalive for %s in %s\n", + GCC_2s(cc), + GNUNET_STRINGS_relative_time_to_string(keepalive_period, + GNUNET_YES)); + cc->task = + GNUNET_SCHEDULER_add_delayed(keepalive_period, &send_keepalive, cc); + } + break; } - break; - } } @@ -775,44 +775,44 @@ manage_first_hop_mq (void *cls, int available) * @return handle to the connection */ static struct CadetConnection * -connection_create (struct CadetPeer *destination, - struct CadetPeerPath *path, - unsigned int off, - struct CadetTConnection *ct, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, - enum CadetConnectionState init_state, - GCC_ReadyCallback ready_cb, - void *ready_cb_cls) +connection_create(struct CadetPeer *destination, + struct CadetPeerPath *path, + unsigned int off, + struct CadetTConnection *ct, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, + enum CadetConnectionState init_state, + GCC_ReadyCallback ready_cb, + void *ready_cb_cls) { struct CadetConnection *cc; struct CadetPeer *first_hop; - cc = GNUNET_new (struct CadetConnection); + cc = GNUNET_new(struct CadetConnection); cc->state = init_state; cc->ct = ct; cc->cid = *cid; cc->retry_delay = - GNUNET_TIME_relative_multiply (INITIAL_CONNECTION_CREATE_RETRY_DELAY, off); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multishortmap_put ( - connections, - &GCC_get_id (cc)->connection_of_tunnel, - cc, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_TIME_relative_multiply(INITIAL_CONNECTION_CREATE_RETRY_DELAY, off); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multishortmap_put( + connections, + &GCC_get_id(cc)->connection_of_tunnel, + cc, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); cc->ready_cb = ready_cb; cc->ready_cb_cls = ready_cb_cls; cc->path = path; cc->off = off; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Creating %s using path %s (offset: %u)\n", - GCC_2s (cc), - GCPP_2s (path), - off); - GCPP_add_connection (path, off, cc); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Creating %s using path %s (offset: %u)\n", + GCC_2s(cc), + GCPP_2s(path), + off); + GCPP_add_connection(path, off, cc); for (unsigned int i = 0; i < off; i++) - GCP_add_connection (GCPP_get_peer_at_offset (path, i), cc); - first_hop = GCPP_get_peer_at_offset (path, 0); - cc->mq_man = GCP_request_mq (first_hop, &manage_first_hop_mq, cc); + GCP_add_connection(GCPP_get_peer_at_offset(path, i), cc); + first_hop = GCPP_get_peer_at_offset(path, 0); + cc->mq_man = GCP_request_mq(first_hop, &manage_first_hop_mq, cc); return cc; } @@ -831,64 +831,64 @@ connection_create (struct CadetPeer *destination, * a connection that takes precedence on @a path */ struct CadetConnection * -GCC_create_inbound (struct CadetPeer *destination, - struct CadetPeerPath *path, - struct CadetTConnection *ct, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, - GCC_ReadyCallback ready_cb, - void *ready_cb_cls) +GCC_create_inbound(struct CadetPeer *destination, + struct CadetPeerPath *path, + struct CadetTConnection *ct, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, + GCC_ReadyCallback ready_cb, + void *ready_cb_cls) { struct CadetConnection *cc; unsigned int off; - off = GCPP_find_peer (path, destination); - GNUNET_assert (UINT_MAX != off); - cc = GCPP_get_connection (path, destination, off); + off = GCPP_find_peer(path, destination); + GNUNET_assert(UINT_MAX != off); + cc = GCPP_get_connection(path, destination, off); if (NULL != cc) - { - int cmp; - - cmp = GNUNET_memcmp (cid, &cc->cid); - if (0 == cmp) - { - /* Two peers picked the SAME random connection identifier at the - same time for the same path? Must be malicious. Drop - connection (existing and inbound), even if it is the only - one. */ - GNUNET_break_op (0); - GCT_connection_lost (cc->ct); - GCC_destroy_without_tunnel (cc); - return NULL; - } - if (0 < cmp) { - /* drop existing */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got two connections on %s, dropping my existing %s\n", - GCPP_2s (path), - GCC_2s (cc)); - GCT_connection_lost (cc->ct); - GCC_destroy_without_tunnel (cc); + int cmp; + + cmp = GNUNET_memcmp(cid, &cc->cid); + if (0 == cmp) + { + /* Two peers picked the SAME random connection identifier at the + same time for the same path? Must be malicious. Drop + connection (existing and inbound), even if it is the only + one. */ + GNUNET_break_op(0); + GCT_connection_lost(cc->ct); + GCC_destroy_without_tunnel(cc); + return NULL; + } + if (0 < cmp) + { + /* drop existing */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got two connections on %s, dropping my existing %s\n", + GCPP_2s(path), + GCC_2s(cc)); + GCT_connection_lost(cc->ct); + GCC_destroy_without_tunnel(cc); + } + else + { + /* keep existing */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got two connections on %s, keeping my existing %s\n", + GCPP_2s(path), + GCC_2s(cc)); + return NULL; + } } - else - { - /* keep existing */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got two connections on %s, keeping my existing %s\n", - GCPP_2s (path), - GCC_2s (cc)); - return NULL; - } - } - - return connection_create (destination, - path, - off, - ct, - cid, - CADET_CONNECTION_CREATE_RECEIVED, - ready_cb, - ready_cb_cls); + + return connection_create(destination, + path, + off, + ct, + cid, + CADET_CONNECTION_CREATE_RECEIVED, + ready_cb, + ready_cb_cls); } @@ -905,24 +905,24 @@ GCC_create_inbound (struct CadetPeer *destination, * @return handle to the connection */ struct CadetConnection * -GCC_create (struct CadetPeer *destination, - struct CadetPeerPath *path, - unsigned int off, - struct CadetTConnection *ct, - GCC_ReadyCallback ready_cb, - void *ready_cb_cls) +GCC_create(struct CadetPeer *destination, + struct CadetPeerPath *path, + unsigned int off, + struct CadetTConnection *ct, + GCC_ReadyCallback ready_cb, + void *ready_cb_cls) { struct GNUNET_CADET_ConnectionTunnelIdentifier cid; - GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof (cid)); - return connection_create (destination, - path, - off, - ct, - &cid, - CADET_CONNECTION_NEW, - ready_cb, - ready_cb_cls); + GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_NONCE, &cid, sizeof(cid)); + return connection_create(destination, + path, + off, + ct, + &cid, + CADET_CONNECTION_NEW, + ready_cb, + ready_cb_cls); } @@ -937,21 +937,21 @@ GCC_create (struct CadetPeer *destination, * yet have a #GNUNET_MQ_notify_sent() callback attached to it */ void -GCC_transmit (struct CadetConnection *cc, struct GNUNET_MQ_Envelope *env) +GCC_transmit(struct CadetConnection *cc, struct GNUNET_MQ_Envelope *env) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Scheduling message for transmission on %s\n", - GCC_2s (cc)); - GNUNET_assert (GNUNET_YES == cc->mqm_ready); - GNUNET_assert (CADET_CONNECTION_READY == cc->state); - cc->metrics.last_use = GNUNET_TIME_absolute_get (); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Scheduling message for transmission on %s\n", + GCC_2s(cc)); + GNUNET_assert(GNUNET_YES == cc->mqm_ready); + GNUNET_assert(CADET_CONNECTION_READY == cc->state); + cc->metrics.last_use = GNUNET_TIME_absolute_get(); cc->mqm_ready = GNUNET_NO; if (NULL != cc->task) - { - GNUNET_SCHEDULER_cancel (cc->task); - cc->task = NULL; - } - GCP_send (cc->mq_man, env); + { + GNUNET_SCHEDULER_cancel(cc->task); + cc->task = NULL; + } + GCP_send(cc->mq_man, env); } @@ -963,7 +963,7 @@ GCC_transmit (struct CadetConnection *cc, struct GNUNET_MQ_Envelope *env) * @return path to @a cc */ struct CadetPeerPath * -GCC_get_path (struct CadetConnection *cc, unsigned int *off) +GCC_get_path(struct CadetConnection *cc, unsigned int *off) { *off = cc->off; return cc->path; @@ -977,7 +977,7 @@ GCC_get_path (struct CadetConnection *cc, unsigned int *off) * @return unique number of the connection */ const struct GNUNET_CADET_ConnectionTunnelIdentifier * -GCC_get_id (struct CadetConnection *cc) +GCC_get_id(struct CadetConnection *cc) { return &cc->cid; } @@ -989,7 +989,7 @@ GCC_get_id (struct CadetConnection *cc) * @param cc Connection. */ const char * -GCC_2s (const struct CadetConnection *cc) +GCC_2s(const struct CadetConnection *cc) { static char buf[128]; @@ -997,24 +997,24 @@ GCC_2s (const struct CadetConnection *cc) return "Connection(NULL)"; if (NULL != cc->ct) - { - GNUNET_snprintf (buf, - sizeof (buf), - "Connection %s (%s)", - GNUNET_sh2s (&cc->cid.connection_of_tunnel), - GCT_2s (cc->ct->t)); - return buf; - } - GNUNET_snprintf (buf, - sizeof (buf), - "Connection %s", - GNUNET_sh2s (&cc->cid.connection_of_tunnel)); + { + GNUNET_snprintf(buf, + sizeof(buf), + "Connection %s (%s)", + GNUNET_sh2s(&cc->cid.connection_of_tunnel), + GCT_2s(cc->ct->t)); + return buf; + } + GNUNET_snprintf(buf, + sizeof(buf), + "Connection %s", + GNUNET_sh2s(&cc->cid.connection_of_tunnel)); return buf; } #define LOG2(level, ...) \ - GNUNET_log_from_nocheck (level, "cadet-con", __VA_ARGS__) + GNUNET_log_from_nocheck(level, "cadet-con", __VA_ARGS__) /** @@ -1024,30 +1024,30 @@ GCC_2s (const struct CadetConnection *cc) * @param level Debug level to use. */ void -GCC_debug (struct CadetConnection *cc, enum GNUNET_ErrorType level) +GCC_debug(struct CadetConnection *cc, enum GNUNET_ErrorType level) { -#if ! defined(GNUNET_CULL_LOGGING) +#if !defined(GNUNET_CULL_LOGGING) int do_log; - do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK), - "cadet-con", - __FILE__, - __FUNCTION__, - __LINE__); + do_log = GNUNET_get_log_call_status(level & (~GNUNET_ERROR_TYPE_BULK), + "cadet-con", + __FILE__, + __FUNCTION__, + __LINE__); if (0 == do_log) return; if (NULL == cc) - { - LOG2 (level, "Connection (NULL)\n"); - return; - } - LOG2 (level, - "%s to %s via path %s in state %d is %s\n", - GCC_2s (cc), - GCP_2s (cc->destination), - GCPP_2s (cc->path), - cc->state, - (GNUNET_YES == cc->mqm_ready) ? "ready" : "busy"); + { + LOG2(level, "Connection (NULL)\n"); + return; + } + LOG2(level, + "%s to %s via path %s in state %d is %s\n", + GCC_2s(cc), + GCP_2s(cc->destination), + GCPP_2s(cc->path), + cc->state, + (GNUNET_YES == cc->mqm_ready) ? "ready" : "busy"); #endif } diff --git a/src/cadet/gnunet-service-cadet_connection.h b/src/cadet/gnunet-service-cadet_connection.h index d3de3347c..47b654cbb 100644 --- a/src/cadet/gnunet-service-cadet_connection.h +++ b/src/cadet/gnunet-service-cadet_connection.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_connection.h @@ -57,7 +57,7 @@ typedef void * @param cc connection to destroy */ void -GCC_destroy_without_core (struct CadetConnection *cc); +GCC_destroy_without_core(struct CadetConnection *cc); /** @@ -68,7 +68,7 @@ GCC_destroy_without_core (struct CadetConnection *cc); * @param cc connection to destroy */ void -GCC_destroy_without_tunnel (struct CadetConnection *cc); +GCC_destroy_without_tunnel(struct CadetConnection *cc); /** @@ -78,7 +78,7 @@ GCC_destroy_without_tunnel (struct CadetConnection *cc); * @return NULL if connection was not found */ struct CadetConnection * -GCC_lookup (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid); +GCC_lookup(const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid); /** @@ -94,12 +94,12 @@ GCC_lookup (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid); * @return handle to the connection */ struct CadetConnection * -GCC_create (struct CadetPeer *destination, - struct CadetPeerPath *path, - unsigned int off, - struct CadetTConnection *ct, - GCC_ReadyCallback ready_cb, - void *ready_cb_cls); +GCC_create(struct CadetPeer *destination, + struct CadetPeerPath *path, + unsigned int off, + struct CadetTConnection *ct, + GCC_ReadyCallback ready_cb, + void *ready_cb_cls); /** @@ -116,12 +116,12 @@ GCC_create (struct CadetPeer *destination, * a connection that takes precedence on @a path */ struct CadetConnection * -GCC_create_inbound (struct CadetPeer *destination, - struct CadetPeerPath *path, - struct CadetTConnection *ct, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, - GCC_ReadyCallback ready_cb, - void *ready_cb_cls); +GCC_create_inbound(struct CadetPeer *destination, + struct CadetPeerPath *path, + struct CadetTConnection *ct, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, + GCC_ReadyCallback ready_cb, + void *ready_cb_cls); /** @@ -137,8 +137,8 @@ GCC_create_inbound (struct CadetPeer *destination, * connection identifier of this connection... */ void -GCC_transmit (struct CadetConnection *cc, - struct GNUNET_MQ_Envelope *env); +GCC_transmit(struct CadetConnection *cc, + struct GNUNET_MQ_Envelope *env); /** @@ -147,7 +147,7 @@ GCC_transmit (struct CadetConnection *cc, * @param cc the connection that got the ACK. */ void -GCC_handle_connection_create_ack (struct CadetConnection *cc); +GCC_handle_connection_create_ack(struct CadetConnection *cc); /** @@ -158,7 +158,7 @@ GCC_handle_connection_create_ack (struct CadetConnection *cc); * @param cc connection that got the duplicate CREATE */ void -GCC_handle_duplicate_create (struct CadetConnection *cc); +GCC_handle_duplicate_create(struct CadetConnection *cc); /** @@ -168,8 +168,8 @@ GCC_handle_duplicate_create (struct CadetConnection *cc); * @param msg the key exchange message */ void -GCC_handle_kx (struct CadetConnection *cc, - const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg); +GCC_handle_kx(struct CadetConnection *cc, + const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg); /** @@ -179,16 +179,14 @@ GCC_handle_kx (struct CadetConnection *cc, * @param msg the key exchange message */ void -GCC_handle_kx_auth (struct CadetConnection *cc, - const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg); +GCC_handle_kx_auth(struct CadetConnection *cc, + const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg); /** * Performance metrics for a connection. */ -struct CadetConnectionMetrics -{ - +struct CadetConnectionMetrics { /** * Our current best estimate of the latency, based on a weighted * average of at least @a latency_datapoints values. @@ -221,7 +219,6 @@ struct CadetConnectionMetrics * connections.) */ unsigned long long num_successes; - }; @@ -232,7 +229,7 @@ struct CadetConnectionMetrics * @return the metrics */ const struct CadetConnectionMetrics * -GCC_get_metrics (struct CadetConnection *cc); +GCC_get_metrics(struct CadetConnection *cc); /** @@ -242,8 +239,8 @@ GCC_get_metrics (struct CadetConnection *cc); * @param msg the encrypted message to decrypt */ void -GCC_handle_encrypted (struct CadetConnection *cc, - const struct GNUNET_CADET_TunnelEncryptedMessage *msg); +GCC_handle_encrypted(struct CadetConnection *cc, + const struct GNUNET_CADET_TunnelEncryptedMessage *msg); /** @@ -253,7 +250,7 @@ GCC_handle_encrypted (struct CadetConnection *cc, * @param cid connection identifier where we expect an ACK */ void -GCC_ack_expected (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid); +GCC_ack_expected(const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid); /** @@ -265,7 +262,7 @@ GCC_ack_expected (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid); * may have gotten back to us via a different connection). */ void -GCC_ack_observed (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid); +GCC_ack_observed(const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid); /** @@ -277,8 +274,8 @@ GCC_ack_observed (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid); * @param latency the observed latency */ void -GCC_latency_observed (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, - struct GNUNET_TIME_Relative latency); +GCC_latency_observed(const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, + struct GNUNET_TIME_Relative latency); /** @@ -288,7 +285,7 @@ GCC_latency_observed (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cti, * @return corresponding entry in the tunnel's connection list */ struct CadetTConnection * -GCC_get_ct (struct CadetConnection *cc); +GCC_get_ct(struct CadetConnection *cc); /** @@ -299,8 +296,8 @@ GCC_get_ct (struct CadetConnection *cc); * @return path to @a cc */ struct CadetPeerPath * -GCC_get_path (struct CadetConnection *cc, - unsigned int *off); +GCC_get_path(struct CadetConnection *cc, + unsigned int *off); /** @@ -310,7 +307,7 @@ GCC_get_path (struct CadetConnection *cc, * @return unique number of the connection */ const struct GNUNET_CADET_ConnectionTunnelIdentifier * -GCC_get_id (struct CadetConnection *cc); +GCC_get_id(struct CadetConnection *cc); /** @@ -319,7 +316,7 @@ GCC_get_id (struct CadetConnection *cc); * @param cc Connection. */ const char * -GCC_2s (const struct CadetConnection *cc); +GCC_2s(const struct CadetConnection *cc); /** @@ -329,8 +326,8 @@ GCC_2s (const struct CadetConnection *cc); * @param level Debug level to use. */ void -GCC_debug (struct CadetConnection *cc, - enum GNUNET_ErrorType level); +GCC_debug(struct CadetConnection *cc, + enum GNUNET_ErrorType level); #endif diff --git a/src/cadet/gnunet-service-cadet_core.c b/src/cadet/gnunet-service-cadet_core.c index ec70a968b..a08c80aae 100644 --- a/src/cadet/gnunet-service-cadet_core.c +++ b/src/cadet/gnunet-service-cadet_core.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_core.c @@ -39,7 +39,7 @@ #include "gnunet_statistics_service.h" #include "cadet_protocol.h" -#define LOG(level, ...) GNUNET_log_from (level, "cadet-cor", __VA_ARGS__) +#define LOG(level, ...) GNUNET_log_from(level, "cadet-cor", __VA_ARGS__) /** * Information we keep per direction for a route. @@ -52,9 +52,7 @@ struct RouteDirection; * routes that have the current maximum of messages in the buffer (in * case we have to purge). */ -struct Rung -{ - +struct Rung { /** * Rung of RouteDirections with one more buffer entry each. */ @@ -91,9 +89,7 @@ struct Rung /** * Information we keep per direction for a route. */ -struct RouteDirection -{ - +struct RouteDirection { /** * DLL of other route directions within the same `struct Rung`. */ @@ -149,9 +145,7 @@ struct RouteDirection * the complete `struct CadetPath` that is formed by the individual * routes. */ -struct CadetRoute -{ - +struct CadetRoute { /** * Information about the next hop on this route. */ @@ -237,10 +231,10 @@ static struct GNUNET_SCHEDULER_Task *timeout_task; * @param cid hash generated from the connection identifier */ static struct CadetRoute * -get_route (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) +get_route(const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) { - return GNUNET_CONTAINER_multishortmap_get (routes, - &cid->connection_of_tunnel); + return GNUNET_CONTAINER_multishortmap_get(routes, + &cid->connection_of_tunnel); } @@ -250,22 +244,22 @@ get_route (const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid) * @param dir direction to lower in rung. */ static void -lower_rung (struct RouteDirection *dir) +lower_rung(struct RouteDirection *dir) { struct Rung *rung = dir->rung; struct Rung *prev; - GNUNET_CONTAINER_DLL_remove (rung->rd_head, rung->rd_tail, dir); + GNUNET_CONTAINER_DLL_remove(rung->rd_head, rung->rd_tail, dir); prev = rung->prev; - GNUNET_assert (NULL != prev); + GNUNET_assert(NULL != prev); if (prev->rung_off != rung->rung_off - 1) - { - prev = GNUNET_new (struct Rung); - prev->rung_off = rung->rung_off - 1; - GNUNET_CONTAINER_DLL_insert_after (rung_head, rung_tail, rung->prev, prev); - } - GNUNET_assert (NULL != prev); - GNUNET_CONTAINER_DLL_insert (prev->rd_head, prev->rd_tail, dir); + { + prev = GNUNET_new(struct Rung); + prev->rung_off = rung->rung_off - 1; + GNUNET_CONTAINER_DLL_insert_after(rung_head, rung_tail, rung->prev, prev); + } + GNUNET_assert(NULL != prev); + GNUNET_CONTAINER_DLL_insert(prev->rd_head, prev->rd_tail, dir); dir->rung = prev; } @@ -278,13 +272,13 @@ lower_rung (struct RouteDirection *dir) * @param env envelope to discard */ static void -discard_buffer (struct RouteDirection *dir, struct GNUNET_MQ_Envelope *env) +discard_buffer(struct RouteDirection *dir, struct GNUNET_MQ_Envelope *env) { - GNUNET_MQ_dll_remove (&dir->env_head, &dir->env_tail, env); + GNUNET_MQ_dll_remove(&dir->env_head, &dir->env_tail, env); cur_buffers--; - GNUNET_MQ_discard (env); - lower_rung (dir); - GNUNET_STATISTICS_set (stats, "# buffer use", cur_buffers, GNUNET_NO); + GNUNET_MQ_discard(env); + lower_rung(dir); + GNUNET_STATISTICS_set(stats, "# buffer use", cur_buffers, GNUNET_NO); } @@ -292,24 +286,24 @@ discard_buffer (struct RouteDirection *dir, struct GNUNET_MQ_Envelope *env) * Discard all messages from the highest rung, to make space. */ static void -discard_all_from_rung_tail () +discard_all_from_rung_tail() { struct Rung *tail = rung_tail; struct RouteDirection *dir; while (NULL != (dir = tail->rd_head)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Queue full due new message %s on connection %s, dropping old message\n", - GNUNET_sh2s (&dir->my_route->cid.connection_of_tunnel)); - GNUNET_STATISTICS_update (stats, - "# messages dropped due to full buffer", - 1, - GNUNET_NO); - discard_buffer (dir, dir->env_head); - } - GNUNET_CONTAINER_DLL_remove (rung_head, rung_tail, tail); - GNUNET_free (tail); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Queue full due new message %s on connection %s, dropping old message\n", + GNUNET_sh2s(&dir->my_route->cid.connection_of_tunnel)); + GNUNET_STATISTICS_update(stats, + "# messages dropped due to full buffer", + 1, + GNUNET_NO); + discard_buffer(dir, dir->env_head); + } + GNUNET_CONTAINER_DLL_remove(rung_head, rung_tail, tail); + GNUNET_free(tail); } @@ -323,10 +317,10 @@ discard_all_from_rung_tail () * @param msg the message to forward */ static void -route_message (struct CadetPeer *prev, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, - const struct GNUNET_MessageHeader *msg, - const enum GNUNET_MQ_PriorityPreferences priority) +route_message(struct CadetPeer *prev, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, + const struct GNUNET_MessageHeader *msg, + const enum GNUNET_MQ_PriorityPreferences priority) { struct CadetRoute *route; struct RouteDirection *dir; @@ -334,133 +328,133 @@ route_message (struct CadetPeer *prev, struct Rung *nxt; struct GNUNET_MQ_Envelope *env; - route = get_route (cid); + route = get_route(cid); if (NULL == route) - { - struct GNUNET_MQ_Envelope *env; - struct GNUNET_CADET_ConnectionBrokenMessage *bm; - - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Failed to route message of type %u from %s on connection %s: no route\n", - ntohs (msg->type), - GCP_2s (prev), - GNUNET_sh2s (&cid->connection_of_tunnel)); - switch (ntohs (msg->type)) { - case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY: - case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN: - /* No need to respond to these! */ + struct GNUNET_MQ_Envelope *env; + struct GNUNET_CADET_ConnectionBrokenMessage *bm; + + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Failed to route message of type %u from %s on connection %s: no route\n", + ntohs(msg->type), + GCP_2s(prev), + GNUNET_sh2s(&cid->connection_of_tunnel)); + switch (ntohs(msg->type)) + { + case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY: + case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN: + /* No need to respond to these! */ + return; + } + env = GNUNET_MQ_msg(bm, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN); + bm->cid = *cid; + bm->peer1 = my_full_id; + GCP_send_ooo(prev, env); return; } - env = GNUNET_MQ_msg (bm, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN); - bm->cid = *cid; - bm->peer1 = my_full_id; - GCP_send_ooo (prev, env); - return; - } - route->last_use = GNUNET_TIME_absolute_get (); - GNUNET_CONTAINER_heap_update_cost (route->hn, route->last_use.abs_value_us); + route->last_use = GNUNET_TIME_absolute_get(); + GNUNET_CONTAINER_heap_update_cost(route->hn, route->last_use.abs_value_us); dir = (prev == route->prev.hop) ? &route->next : &route->prev; if (GNUNET_YES == dir->is_ready) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Routing message of type %u from %s to %s on connection %s\n", - ntohs (msg->type), - GCP_2s (prev), - GNUNET_i2s (GCP_get_id (dir->hop)), - GNUNET_sh2s (&cid->connection_of_tunnel)); - dir->is_ready = GNUNET_NO; - GCP_send (dir->mqm, GNUNET_MQ_msg_copy (msg)); - return; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Routing message of type %u from %s to %s on connection %s\n", + ntohs(msg->type), + GCP_2s(prev), + GNUNET_i2s(GCP_get_id(dir->hop)), + GNUNET_sh2s(&cid->connection_of_tunnel)); + dir->is_ready = GNUNET_NO; + GCP_send(dir->mqm, GNUNET_MQ_msg_copy(msg)); + return; + } /* Check if low latency is required and if the previous message was unreliable; if so, make sure we only queue one message per direction (no buffering). */ if ((0 != (priority & GNUNET_MQ_PREF_LOW_LATENCY)) && (NULL != dir->env_head) && (0 == - (GNUNET_MQ_env_get_options (dir->env_head) & GNUNET_MQ_PREF_UNRELIABLE))) - discard_buffer (dir, dir->env_head); + (GNUNET_MQ_env_get_options(dir->env_head) & GNUNET_MQ_PREF_UNRELIABLE))) + discard_buffer(dir, dir->env_head); /* Check for duplicates */ for (const struct GNUNET_MQ_Envelope *env = dir->env_head; NULL != env; - env = GNUNET_MQ_env_next (env)) - { - const struct GNUNET_MessageHeader *hdr = GNUNET_MQ_env_get_msg (env); - - if ((hdr->size == msg->size) && (0 == memcmp (hdr, msg, ntohs (msg->size)))) + env = GNUNET_MQ_env_next(env)) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received duplicate of message already in buffer, dropping\n"); - GNUNET_STATISTICS_update (stats, - "# messages dropped due to duplicate in buffer", - 1, - GNUNET_NO); - return; + const struct GNUNET_MessageHeader *hdr = GNUNET_MQ_env_get_msg(env); + + if ((hdr->size == msg->size) && (0 == memcmp(hdr, msg, ntohs(msg->size)))) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received duplicate of message already in buffer, dropping\n"); + GNUNET_STATISTICS_update(stats, + "# messages dropped due to duplicate in buffer", + 1, + GNUNET_NO); + return; + } } - } rung = dir->rung; if (cur_buffers == max_buffers) - { - /* Need to make room. */ - if (NULL != rung->next) - { - /* Easy case, drop messages from route directions in highest rung */ - discard_all_from_rung_tail (); - } - else { - /* We are in the highest rung, drop our own! */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Queue full due new message %s on connection %s, dropping old message\n", - GNUNET_sh2s (&dir->my_route->cid.connection_of_tunnel)); - GNUNET_STATISTICS_update (stats, - "# messages dropped due to full buffer", - 1, - GNUNET_NO); - discard_buffer (dir, dir->env_head); - rung = dir->rung; + /* Need to make room. */ + if (NULL != rung->next) + { + /* Easy case, drop messages from route directions in highest rung */ + discard_all_from_rung_tail(); + } + else + { + /* We are in the highest rung, drop our own! */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Queue full due new message %s on connection %s, dropping old message\n", + GNUNET_sh2s(&dir->my_route->cid.connection_of_tunnel)); + GNUNET_STATISTICS_update(stats, + "# messages dropped due to full buffer", + 1, + GNUNET_NO); + discard_buffer(dir, dir->env_head); + rung = dir->rung; + } } - } /* remove 'dir' from current rung */ - GNUNET_CONTAINER_DLL_remove (rung->rd_head, rung->rd_tail, dir); + GNUNET_CONTAINER_DLL_remove(rung->rd_head, rung->rd_tail, dir); /* make 'nxt' point to the next higher rung, create if necessary */ nxt = rung->next; if ((NULL == nxt) || (rung->rung_off + 1 != nxt->rung_off)) - { - nxt = GNUNET_new (struct Rung); - nxt->rung_off = rung->rung_off + 1; - GNUNET_CONTAINER_DLL_insert_after (rung_head, rung_tail, rung, nxt); - } + { + nxt = GNUNET_new(struct Rung); + nxt->rung_off = rung->rung_off + 1; + GNUNET_CONTAINER_DLL_insert_after(rung_head, rung_tail, rung, nxt); + } /* insert 'dir' into next higher rung */ - GNUNET_CONTAINER_DLL_insert (nxt->rd_head, nxt->rd_tail, dir); + GNUNET_CONTAINER_DLL_insert(nxt->rd_head, nxt->rd_tail, dir); dir->rung = nxt; /* add message into 'dir' buffer */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Queueing new message of type %u from %s to %s on connection %s\n", - ntohs (msg->type), - GCP_2s (prev), - GNUNET_i2s (GCP_get_id (dir->hop)), - GNUNET_sh2s (&cid->connection_of_tunnel)); - env = GNUNET_MQ_msg_copy (msg); - GNUNET_MQ_env_set_options (env, priority); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Queueing new message of type %u from %s to %s on connection %s\n", + ntohs(msg->type), + GCP_2s(prev), + GNUNET_i2s(GCP_get_id(dir->hop)), + GNUNET_sh2s(&cid->connection_of_tunnel)); + env = GNUNET_MQ_msg_copy(msg); + GNUNET_MQ_env_set_options(env, priority); if ((0 != (priority & GNUNET_MQ_PREF_LOW_LATENCY)) && (0 != (priority & GNUNET_MQ_PREF_OUT_OF_ORDER)) && (NULL != dir->env_head) && - (0 == (GNUNET_MQ_env_get_options (dir->env_head) & + (0 == (GNUNET_MQ_env_get_options(dir->env_head) & GNUNET_MQ_PREF_LOW_LATENCY))) - GNUNET_MQ_dll_insert_head (&dir->env_head, &dir->env_tail, env); + GNUNET_MQ_dll_insert_head(&dir->env_head, &dir->env_tail, env); else - GNUNET_MQ_dll_insert_tail (&dir->env_head, &dir->env_tail, env); + GNUNET_MQ_dll_insert_tail(&dir->env_head, &dir->env_tail, env); cur_buffers++; - GNUNET_STATISTICS_set (stats, "# buffer use", cur_buffers, GNUNET_NO); + GNUNET_STATISTICS_set(stats, "# buffer use", cur_buffers, GNUNET_NO); /* Clean up 'rung' if now empty (and not head) */ if ((NULL == rung->rd_head) && (rung != rung_head)) - { - GNUNET_CONTAINER_DLL_remove (rung_head, rung_tail, rung); - GNUNET_free (rung); - } + { + GNUNET_CONTAINER_DLL_remove(rung_head, rung_tail, rung); + GNUNET_free(rung); + } } @@ -473,16 +467,16 @@ route_message (struct CadetPeer *prev, * @return #GNUNET_YES if size is correct, #GNUNET_NO otherwise. */ static int -check_connection_create (void *cls, - const struct GNUNET_CADET_ConnectionCreateMessage *msg) +check_connection_create(void *cls, + const struct GNUNET_CADET_ConnectionCreateMessage *msg) { - uint16_t size = ntohs (msg->header.size) - sizeof (*msg); + uint16_t size = ntohs(msg->header.size) - sizeof(*msg); - if (0 != (size % sizeof (struct GNUNET_PeerIdentity))) - { - GNUNET_break_op (0); - return GNUNET_NO; - } + if (0 != (size % sizeof(struct GNUNET_PeerIdentity))) + { + GNUNET_break_op(0); + return GNUNET_NO; + } return GNUNET_YES; } @@ -493,24 +487,24 @@ check_connection_create (void *cls, * @param dir direction to destroy (do NOT free memory of 'dir' itself) */ static void -destroy_direction (struct RouteDirection *dir) +destroy_direction(struct RouteDirection *dir) { struct GNUNET_MQ_Envelope *env; while (NULL != (env = dir->env_head)) - { - GNUNET_STATISTICS_update (stats, - "# messages dropped due to route destruction", - 1, - GNUNET_NO); - discard_buffer (dir, env); - } + { + GNUNET_STATISTICS_update(stats, + "# messages dropped due to route destruction", + 1, + GNUNET_NO); + discard_buffer(dir, env); + } if (NULL != dir->mqm) - { - GCP_request_mq_cancel (dir->mqm, NULL); - dir->mqm = NULL; - } - GNUNET_CONTAINER_DLL_remove (rung_head->rd_head, rung_head->rd_tail, dir); + { + GCP_request_mq_cancel(dir->mqm, NULL); + dir->mqm = NULL; + } + GNUNET_CONTAINER_DLL_remove(rung_head->rd_head, rung_head->rd_tail, dir); } @@ -520,26 +514,26 @@ destroy_direction (struct RouteDirection *dir) * @param route route to destroy */ static void -destroy_route (struct CadetRoute *route) +destroy_route(struct CadetRoute *route) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Destroying route from %s to %s of connection %s\n", - GNUNET_i2s (GCP_get_id (route->prev.hop)), - GNUNET_i2s2 (GCP_get_id (route->next.hop)), - GNUNET_sh2s (&route->cid.connection_of_tunnel)); - GNUNET_assert (route == GNUNET_CONTAINER_heap_remove_node (route->hn)); - GNUNET_assert ( + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Destroying route from %s to %s of connection %s\n", + GNUNET_i2s(GCP_get_id(route->prev.hop)), + GNUNET_i2s2(GCP_get_id(route->next.hop)), + GNUNET_sh2s(&route->cid.connection_of_tunnel)); + GNUNET_assert(route == GNUNET_CONTAINER_heap_remove_node(route->hn)); + GNUNET_assert( GNUNET_YES == - GNUNET_CONTAINER_multishortmap_remove (routes, - &route->cid.connection_of_tunnel, - route)); - GNUNET_STATISTICS_set (stats, - "# routes", - GNUNET_CONTAINER_multishortmap_size (routes), - GNUNET_NO); - destroy_direction (&route->prev); - destroy_direction (&route->next); - GNUNET_free (route); + GNUNET_CONTAINER_multishortmap_remove(routes, + &route->cid.connection_of_tunnel, + route)); + GNUNET_STATISTICS_set(stats, + "# routes", + GNUNET_CONTAINER_multishortmap_size(routes), + GNUNET_NO); + destroy_direction(&route->prev); + destroy_direction(&route->next); + GNUNET_free(route); } @@ -552,30 +546,30 @@ destroy_route (struct CadetRoute *route) * @param peer2 another one of the peers where a link is broken */ static void -send_broken (struct RouteDirection *target, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, - const struct GNUNET_PeerIdentity *peer1, - const struct GNUNET_PeerIdentity *peer2) +send_broken(struct RouteDirection *target, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, + const struct GNUNET_PeerIdentity *peer1, + const struct GNUNET_PeerIdentity *peer2) { struct GNUNET_MQ_Envelope *env; struct GNUNET_CADET_ConnectionBrokenMessage *bm; if (NULL == target->mqm) return; /* Can't send notification, connection is down! */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Notifying %s about BROKEN route at %s-%s of connection %s\n", - GCP_2s (target->hop), - GNUNET_i2s (peer1), - GNUNET_i2s2 (peer2), - GNUNET_sh2s (&cid->connection_of_tunnel)); - - env = GNUNET_MQ_msg (bm, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Notifying %s about BROKEN route at %s-%s of connection %s\n", + GCP_2s(target->hop), + GNUNET_i2s(peer1), + GNUNET_i2s2(peer2), + GNUNET_sh2s(&cid->connection_of_tunnel)); + + env = GNUNET_MQ_msg(bm, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN); bm->cid = *cid; if (NULL != peer1) bm->peer1 = *peer1; if (NULL != peer2) bm->peer2 = *peer2; - GCP_request_mq_cancel (target->mqm, env); + GCP_request_mq_cancel(target->mqm, env); target->mqm = NULL; } @@ -588,31 +582,31 @@ send_broken (struct RouteDirection *target, * @param cls NULL */ static void -timeout_cb (void *cls) +timeout_cb(void *cls) { struct CadetRoute *r; struct GNUNET_TIME_Relative linger; struct GNUNET_TIME_Absolute exp; timeout_task = NULL; - linger = GNUNET_TIME_relative_multiply (keepalive_period, 3); - while (NULL != (r = GNUNET_CONTAINER_heap_peek (route_heap))) - { - exp = GNUNET_TIME_absolute_add (r->last_use, linger); - if (0 != GNUNET_TIME_absolute_get_remaining (exp).rel_value_us) + linger = GNUNET_TIME_relative_multiply(keepalive_period, 3); + while (NULL != (r = GNUNET_CONTAINER_heap_peek(route_heap))) { - /* Route not yet timed out, wait until it does. */ - timeout_task = GNUNET_SCHEDULER_add_at (exp, &timeout_cb, NULL); - return; + exp = GNUNET_TIME_absolute_add(r->last_use, linger); + if (0 != GNUNET_TIME_absolute_get_remaining(exp).rel_value_us) + { + /* Route not yet timed out, wait until it does. */ + timeout_task = GNUNET_SCHEDULER_add_at(exp, &timeout_cb, NULL); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Sending BROKEN due to timeout (%s was last use, %s linger)\n", + GNUNET_STRINGS_absolute_time_to_string(r->last_use), + GNUNET_STRINGS_relative_time_to_string(linger, GNUNET_YES)); + send_broken(&r->prev, &r->cid, NULL, NULL); + send_broken(&r->next, &r->cid, NULL, NULL); + destroy_route(r); } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Sending BROKEN due to timeout (%s was last use, %s linger)\n", - GNUNET_STRINGS_absolute_time_to_string (r->last_use), - GNUNET_STRINGS_relative_time_to_string (linger, GNUNET_YES)); - send_broken (&r->prev, &r->cid, NULL, NULL); - send_broken (&r->next, &r->cid, NULL, NULL); - destroy_route (r); - } /* No more routes left, so no need for a #timeout_task */ } @@ -630,32 +624,32 @@ timeout_cb (void *cls) * and the last envelope was discarded */ static void -dir_ready_cb (void *cls, int ready) +dir_ready_cb(void *cls, int ready) { struct RouteDirection *dir = cls; struct CadetRoute *route = dir->my_route; struct RouteDirection *odir; if (GNUNET_YES == ready) - { - struct GNUNET_MQ_Envelope *env; - - dir->is_ready = GNUNET_YES; - if (NULL != (env = dir->env_head)) { - GNUNET_MQ_dll_remove (&dir->env_head, &dir->env_tail, env); - cur_buffers--; - GNUNET_STATISTICS_set (stats, "# buffer use", cur_buffers, GNUNET_NO); - lower_rung (dir); - dir->is_ready = GNUNET_NO; - GCP_send (dir->mqm, env); + struct GNUNET_MQ_Envelope *env; + + dir->is_ready = GNUNET_YES; + if (NULL != (env = dir->env_head)) + { + GNUNET_MQ_dll_remove(&dir->env_head, &dir->env_tail, env); + cur_buffers--; + GNUNET_STATISTICS_set(stats, "# buffer use", cur_buffers, GNUNET_NO); + lower_rung(dir); + dir->is_ready = GNUNET_NO; + GCP_send(dir->mqm, env); + } + return; } - return; - } odir = (dir == &route->next) ? &route->prev : &route->next; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending BROKEN due to MQ going down\n"); - send_broken (&route->next, &route->cid, GCP_get_id (odir->hop), &my_full_id); - destroy_route (route); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending BROKEN due to MQ going down\n"); + send_broken(&route->next, &route->cid, GCP_get_id(odir->hop), &my_full_id); + destroy_route(route); } @@ -667,16 +661,16 @@ dir_ready_cb (void *cls, int ready) * @param hop next hop on in the @a dir */ static void -dir_init (struct RouteDirection *dir, - struct CadetRoute *route, - struct CadetPeer *hop) +dir_init(struct RouteDirection *dir, + struct CadetRoute *route, + struct CadetPeer *hop) { dir->hop = hop; dir->my_route = route; - dir->mqm = GCP_request_mq (hop, &dir_ready_cb, dir); - GNUNET_CONTAINER_DLL_insert (rung_head->rd_head, rung_head->rd_tail, dir); + dir->mqm = GCP_request_mq(hop, &dir_ready_cb, dir); + GNUNET_CONTAINER_DLL_insert(rung_head->rd_head, rung_head->rd_tail, dir); dir->rung = rung_head; - GNUNET_assert (GNUNET_YES == dir->is_ready); + GNUNET_assert(GNUNET_YES == dir->is_ready); } @@ -691,7 +685,7 @@ dir_init (struct RouteDirection *dir, * or NULL. */ static void -send_broken_without_mqm ( +send_broken_without_mqm( struct CadetPeer *target, const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, const struct GNUNET_PeerIdentity *failure_at) @@ -699,12 +693,12 @@ send_broken_without_mqm ( struct GNUNET_MQ_Envelope *env; struct GNUNET_CADET_ConnectionBrokenMessage *bm; - env = GNUNET_MQ_msg (bm, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN); + env = GNUNET_MQ_msg(bm, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN); bm->cid = *cid; bm->peer1 = my_full_id; if (NULL != failure_at) bm->peer2 = *failure_at; - GCP_send_ooo (target, env); + GCP_send_ooo(target, env); } @@ -715,193 +709,193 @@ send_broken_without_mqm ( * @param msg Message itself. */ static void -handle_connection_create ( +handle_connection_create( void *cls, const struct GNUNET_CADET_ConnectionCreateMessage *msg) { struct CadetPeer *sender = cls; struct CadetPeer *next; const struct GNUNET_PeerIdentity *pids = - (const struct GNUNET_PeerIdentity *) &msg[1]; + (const struct GNUNET_PeerIdentity *)&msg[1]; struct CadetRoute *route; - uint16_t size = ntohs (msg->header.size) - sizeof (*msg); + uint16_t size = ntohs(msg->header.size) - sizeof(*msg); unsigned int path_length; unsigned int off; - path_length = size / sizeof (struct GNUNET_PeerIdentity); + path_length = size / sizeof(struct GNUNET_PeerIdentity); if (0 == path_length) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Dropping CADET_CONNECTION_CREATE with empty path\n"); - GNUNET_break_op (0); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Handling CADET_CONNECTION_CREATE from %s for CID %s with %u hops\n", - GCP_2s (sender), - GNUNET_sh2s (&msg->cid.connection_of_tunnel), - path_length); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Dropping CADET_CONNECTION_CREATE with empty path\n"); + GNUNET_break_op(0); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Handling CADET_CONNECTION_CREATE from %s for CID %s with %u hops\n", + GCP_2s(sender), + GNUNET_sh2s(&msg->cid.connection_of_tunnel), + path_length); /* Check for loops */ { struct GNUNET_CONTAINER_MultiPeerMap *map; - map = GNUNET_CONTAINER_multipeermap_create (path_length * 2, GNUNET_YES); - GNUNET_assert (NULL != map); + map = GNUNET_CONTAINER_multipeermap_create(path_length * 2, GNUNET_YES); + GNUNET_assert(NULL != map); for (unsigned int i = 0; i < path_length; i++) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "CADET_CONNECTION_CREATE has peer %s at offset %u\n", - GNUNET_i2s (&pids[i]), - i); - if (GNUNET_SYSERR == GNUNET_CONTAINER_multipeermap_put ( - map, - &pids[i], - NULL, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) { - /* bogus request */ - GNUNET_CONTAINER_multipeermap_destroy (map); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Dropping CADET_CONNECTION_CREATE with cyclic path\n"); - GNUNET_break_op (0); - return; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "CADET_CONNECTION_CREATE has peer %s at offset %u\n", + GNUNET_i2s(&pids[i]), + i); + if (GNUNET_SYSERR == GNUNET_CONTAINER_multipeermap_put( + map, + &pids[i], + NULL, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + /* bogus request */ + GNUNET_CONTAINER_multipeermap_destroy(map); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Dropping CADET_CONNECTION_CREATE with cyclic path\n"); + GNUNET_break_op(0); + return; + } } - } - GNUNET_CONTAINER_multipeermap_destroy (map); + GNUNET_CONTAINER_multipeermap_destroy(map); } /* Initiator is at offset 0, find us */ for (off = 1; off < path_length; off++) - if (0 == GNUNET_memcmp (&my_full_id, &pids[off])) + if (0 == GNUNET_memcmp(&my_full_id, &pids[off])) break; if (off == path_length) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Dropping CADET_CONNECTION_CREATE without us in the path\n"); - GNUNET_break_op (0); - return; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Dropping CADET_CONNECTION_CREATE without us in the path\n"); + GNUNET_break_op(0); + return; + } /* Check previous hop */ - if (sender != GCP_get (&pids[off - 1], GNUNET_NO)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Dropping CADET_CONNECTION_CREATE without sender at previous hop in the path\n"); - GNUNET_break_op (0); - return; - } - if (NULL != (route = get_route (&msg->cid))) - { - /* Duplicate CREATE, pass it on, previous one might have been lost! */ - - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Passing on duplicate CADET_CONNECTION_CREATE message on connection %s\n", - GNUNET_sh2s (&msg->cid.connection_of_tunnel)); - route_message (sender, - &msg->cid, - &msg->header, - GNUNET_MQ_PRIO_CRITICAL_CONTROL | - GNUNET_MQ_PREF_LOW_LATENCY); - return; - } - if (off == path_length - 1) - { - /* We are the destination, create connection */ - struct CadetConnection *cc; - struct CadetPeerPath *path; - struct CadetPeer *origin; - - cc = GCC_lookup (&msg->cid); - if (NULL != cc) + if (sender != GCP_get(&pids[off - 1], GNUNET_NO)) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received duplicate CADET_CONNECTION_CREATE message on connection %s\n", - GNUNET_sh2s (&msg->cid.connection_of_tunnel)); - GCC_handle_duplicate_create (cc); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Dropping CADET_CONNECTION_CREATE without sender at previous hop in the path\n"); + GNUNET_break_op(0); return; } - - origin = GCP_get (&pids[0], GNUNET_YES); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "I am destination for CADET_CONNECTION_CREATE message from %s for connection %s, building inverse path\n", - GCP_2s (origin), - GNUNET_sh2s (&msg->cid.connection_of_tunnel)); - path = GCPP_get_path_from_route (path_length - 1, pids); - if (GNUNET_OK != - GCT_add_inbound_connection (GCP_get_tunnel (origin, GNUNET_YES), - &msg->cid, - path)) + if (NULL != (route = get_route(&msg->cid))) { - /* Send back BROKEN: duplicate connection on the same path, - we will use the other one. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received CADET_CONNECTION_CREATE from %s for %s, but %s already has a connection. Sending BROKEN\n", - GCP_2s (sender), - GNUNET_sh2s (&msg->cid.connection_of_tunnel), - GCPP_2s (path)); - send_broken_without_mqm (sender, &msg->cid, NULL); + /* Duplicate CREATE, pass it on, previous one might have been lost! */ + + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Passing on duplicate CADET_CONNECTION_CREATE message on connection %s\n", + GNUNET_sh2s(&msg->cid.connection_of_tunnel)); + route_message(sender, + &msg->cid, + &msg->header, + GNUNET_MQ_PRIO_CRITICAL_CONTROL | + GNUNET_MQ_PREF_LOW_LATENCY); + return; + } + if (off == path_length - 1) + { + /* We are the destination, create connection */ + struct CadetConnection *cc; + struct CadetPeerPath *path; + struct CadetPeer *origin; + + cc = GCC_lookup(&msg->cid); + if (NULL != cc) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received duplicate CADET_CONNECTION_CREATE message on connection %s\n", + GNUNET_sh2s(&msg->cid.connection_of_tunnel)); + GCC_handle_duplicate_create(cc); + return; + } + + origin = GCP_get(&pids[0], GNUNET_YES); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "I am destination for CADET_CONNECTION_CREATE message from %s for connection %s, building inverse path\n", + GCP_2s(origin), + GNUNET_sh2s(&msg->cid.connection_of_tunnel)); + path = GCPP_get_path_from_route(path_length - 1, pids); + if (GNUNET_OK != + GCT_add_inbound_connection(GCP_get_tunnel(origin, GNUNET_YES), + &msg->cid, + path)) + { + /* Send back BROKEN: duplicate connection on the same path, + we will use the other one. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received CADET_CONNECTION_CREATE from %s for %s, but %s already has a connection. Sending BROKEN\n", + GCP_2s(sender), + GNUNET_sh2s(&msg->cid.connection_of_tunnel), + GCPP_2s(path)); + send_broken_without_mqm(sender, &msg->cid, NULL); + return; + } return; } - return; - } /* We are merely a hop on the way, check if we can support the route */ - next = GCP_get (&pids[off + 1], GNUNET_NO); - if ((NULL == next) || (GNUNET_NO == GCP_has_core_connection (next))) - { - /* unworkable, send back BROKEN notification */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received CADET_CONNECTION_CREATE from %s for %s. Next hop %s:%u is down. Sending BROKEN\n", - GCP_2s (sender), - GNUNET_sh2s (&msg->cid.connection_of_tunnel), - GNUNET_i2s (&pids[off + 1]), - off + 1); - send_broken_without_mqm (sender, &msg->cid, &pids[off + 1]); - return; - } - if (max_routes <= GNUNET_CONTAINER_multishortmap_size (routes)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received CADET_CONNECTION_CREATE from %s for %s. We have reached our route limit. Sending BROKEN\n", - GCP_2s (sender), - GNUNET_sh2s (&msg->cid.connection_of_tunnel)); - send_broken_without_mqm (sender, &msg->cid, &pids[off - 1]); - return; - } + next = GCP_get(&pids[off + 1], GNUNET_NO); + if ((NULL == next) || (GNUNET_NO == GCP_has_core_connection(next))) + { + /* unworkable, send back BROKEN notification */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received CADET_CONNECTION_CREATE from %s for %s. Next hop %s:%u is down. Sending BROKEN\n", + GCP_2s(sender), + GNUNET_sh2s(&msg->cid.connection_of_tunnel), + GNUNET_i2s(&pids[off + 1]), + off + 1); + send_broken_without_mqm(sender, &msg->cid, &pids[off + 1]); + return; + } + if (max_routes <= GNUNET_CONTAINER_multishortmap_size(routes)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received CADET_CONNECTION_CREATE from %s for %s. We have reached our route limit. Sending BROKEN\n", + GCP_2s(sender), + GNUNET_sh2s(&msg->cid.connection_of_tunnel)); + send_broken_without_mqm(sender, &msg->cid, &pids[off - 1]); + return; + } /* Workable route, create routing entry */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received CADET_CONNECTION_CREATE from %s for %s. Next hop %s:%u is up. Creating route\n", - GCP_2s (sender), - GNUNET_sh2s (&msg->cid.connection_of_tunnel), - GNUNET_i2s (&pids[off + 1]), - off + 1); - route = GNUNET_new (struct CadetRoute); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received CADET_CONNECTION_CREATE from %s for %s. Next hop %s:%u is up. Creating route\n", + GCP_2s(sender), + GNUNET_sh2s(&msg->cid.connection_of_tunnel), + GNUNET_i2s(&pids[off + 1]), + off + 1); + route = GNUNET_new(struct CadetRoute); route->cid = msg->cid; - route->last_use = GNUNET_TIME_absolute_get (); - dir_init (&route->prev, route, sender); - dir_init (&route->next, route, next); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multishortmap_put ( - routes, - &route->cid.connection_of_tunnel, - route, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - GNUNET_STATISTICS_set (stats, - "# routes", - GNUNET_CONTAINER_multishortmap_size (routes), - GNUNET_NO); - route->hn = GNUNET_CONTAINER_heap_insert (route_heap, - route, - route->last_use.abs_value_us); + route->last_use = GNUNET_TIME_absolute_get(); + dir_init(&route->prev, route, sender); + dir_init(&route->next, route, next); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multishortmap_put( + routes, + &route->cid.connection_of_tunnel, + route, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_STATISTICS_set(stats, + "# routes", + GNUNET_CONTAINER_multishortmap_size(routes), + GNUNET_NO); + route->hn = GNUNET_CONTAINER_heap_insert(route_heap, + route, + route->last_use.abs_value_us); if (NULL == timeout_task) timeout_task = - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply (keepalive_period, - 3), - &timeout_cb, - NULL); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(keepalive_period, + 3), + &timeout_cb, + NULL); /* also pass CREATE message along to next hop */ - route_message (sender, - &msg->cid, - &msg->header, - GNUNET_MQ_PRIO_CRITICAL_CONTROL | GNUNET_MQ_PREF_LOW_LATENCY); + route_message(sender, + &msg->cid, + &msg->header, + GNUNET_MQ_PRIO_CRITICAL_CONTROL | GNUNET_MQ_PREF_LOW_LATENCY); } @@ -912,7 +906,7 @@ handle_connection_create ( * @param msg Message itself. */ static void -handle_connection_create_ack ( +handle_connection_create_ack( void *cls, const struct GNUNET_CADET_ConnectionCreateAckMessage *msg) { @@ -920,31 +914,31 @@ handle_connection_create_ack ( struct CadetConnection *cc; /* First, check if ACK belongs to a connection that ends here. */ - cc = GCC_lookup (&msg->cid); + cc = GCC_lookup(&msg->cid); if (NULL != cc) - { - /* verify ACK came from the right direction */ - unsigned int len; - struct CadetPeerPath *path = GCC_get_path (cc, &len); - - if (peer != GCPP_get_peer_at_offset (path, 0)) { - /* received ACK from unexpected direction, ignore! */ - GNUNET_break_op (0); + /* verify ACK came from the right direction */ + unsigned int len; + struct CadetPeerPath *path = GCC_get_path(cc, &len); + + if (peer != GCPP_get_peer_at_offset(path, 0)) + { + /* received ACK from unexpected direction, ignore! */ + GNUNET_break_op(0); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received CONNECTION_CREATE_ACK for connection %s.\n", + GNUNET_sh2s(&msg->cid.connection_of_tunnel)); + GCC_handle_connection_create_ack(cc); return; } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received CONNECTION_CREATE_ACK for connection %s.\n", - GNUNET_sh2s (&msg->cid.connection_of_tunnel)); - GCC_handle_connection_create_ack (cc); - return; - } /* We're just an intermediary peer, route the message along its path */ - route_message (peer, - &msg->cid, - &msg->header, - GNUNET_MQ_PRIO_CRITICAL_CONTROL | GNUNET_MQ_PREF_LOW_LATENCY); + route_message(peer, + &msg->cid, + &msg->header, + GNUNET_MQ_PRIO_CRITICAL_CONTROL | GNUNET_MQ_PREF_LOW_LATENCY); } @@ -956,7 +950,7 @@ handle_connection_create_ack ( * @deprecated duplicate logic with #handle_destroy(); dedup! */ static void -handle_connection_broken ( +handle_connection_broken( void *cls, const struct GNUNET_CADET_ConnectionBrokenMessage *msg) { @@ -965,36 +959,36 @@ handle_connection_broken ( struct CadetRoute *route; /* First, check if message belongs to a connection that ends here. */ - cc = GCC_lookup (&msg->cid); + cc = GCC_lookup(&msg->cid); if (NULL != cc) - { - /* verify message came from the right direction */ - unsigned int len; - struct CadetPeerPath *path = GCC_get_path (cc, &len); - - if (peer != GCPP_get_peer_at_offset (path, 0)) { - /* received message from unexpected direction, ignore! */ - GNUNET_break_op (0); + /* verify message came from the right direction */ + unsigned int len; + struct CadetPeerPath *path = GCC_get_path(cc, &len); + + if (peer != GCPP_get_peer_at_offset(path, 0)) + { + /* received message from unexpected direction, ignore! */ + GNUNET_break_op(0); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received CONNECTION_BROKEN for connection %s. Destroying it.\n", + GNUNET_sh2s(&msg->cid.connection_of_tunnel)); + GCC_destroy_without_core(cc); + + /* FIXME: also destroy the path up to the specified link! */ return; } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received CONNECTION_BROKEN for connection %s. Destroying it.\n", - GNUNET_sh2s (&msg->cid.connection_of_tunnel)); - GCC_destroy_without_core (cc); - - /* FIXME: also destroy the path up to the specified link! */ - return; - } /* We're just an intermediary peer, route the message along its path */ - route_message (peer, - &msg->cid, - &msg->header, - GNUNET_MQ_PREF_LOW_LATENCY | GNUNET_MQ_PRIO_CRITICAL_CONTROL); - route = get_route (&msg->cid); + route_message(peer, + &msg->cid, + &msg->header, + GNUNET_MQ_PREF_LOW_LATENCY | GNUNET_MQ_PRIO_CRITICAL_CONTROL); + route = get_route(&msg->cid); if (NULL != route) - destroy_route (route); + destroy_route(route); /* FIXME: also destroy paths we MAY have up to the specified link! */ } @@ -1006,7 +1000,7 @@ handle_connection_broken ( * @param msg Message itself. */ static void -handle_connection_destroy ( +handle_connection_destroy( void *cls, const struct GNUNET_CADET_ConnectionDestroyMessage *msg) { @@ -1015,38 +1009,38 @@ handle_connection_destroy ( struct CadetRoute *route; /* First, check if message belongs to a connection that ends here. */ - cc = GCC_lookup (&msg->cid); + cc = GCC_lookup(&msg->cid); if (NULL != cc) - { - /* verify message came from the right direction */ - unsigned int len; - struct CadetPeerPath *path = GCC_get_path (cc, &len); - - if (peer != GCPP_get_peer_at_offset (path, 0)) { - /* received message from unexpected direction, ignore! */ - GNUNET_break_op (0); + /* verify message came from the right direction */ + unsigned int len; + struct CadetPeerPath *path = GCC_get_path(cc, &len); + + if (peer != GCPP_get_peer_at_offset(path, 0)) + { + /* received message from unexpected direction, ignore! */ + GNUNET_break_op(0); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received CONNECTION_DESTROY for connection %s. Destroying connection.\n", + GNUNET_sh2s(&msg->cid.connection_of_tunnel)); + + GCC_destroy_without_core(cc); return; } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received CONNECTION_DESTROY for connection %s. Destroying connection.\n", - GNUNET_sh2s (&msg->cid.connection_of_tunnel)); - - GCC_destroy_without_core (cc); - return; - } /* We're just an intermediary peer, route the message along its path */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received CONNECTION_DESTROY for connection %s. Destroying route.\n", - GNUNET_sh2s (&msg->cid.connection_of_tunnel)); - route_message (peer, - &msg->cid, - &msg->header, - GNUNET_MQ_PREF_LOW_LATENCY | GNUNET_MQ_PRIO_CRITICAL_CONTROL); - route = get_route (&msg->cid); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received CONNECTION_DESTROY for connection %s. Destroying route.\n", + GNUNET_sh2s(&msg->cid.connection_of_tunnel)); + route_message(peer, + &msg->cid, + &msg->header, + GNUNET_MQ_PREF_LOW_LATENCY | GNUNET_MQ_PRIO_CRITICAL_CONTROL); + route = get_route(&msg->cid); if (NULL != route) - destroy_route (route); + destroy_route(route); } @@ -1057,41 +1051,41 @@ handle_connection_destroy ( * @param msg Message itself. */ static void -handle_tunnel_kx (void *cls, - const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg) +handle_tunnel_kx(void *cls, + const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg) { struct CadetPeer *peer = cls; struct CadetConnection *cc; /* First, check if message belongs to a connection that ends here. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Routing KX with ephemeral %s on CID %s\n", - GNUNET_e2s (&msg->ephemeral_key), - GNUNET_sh2s (&msg->cid.connection_of_tunnel)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Routing KX with ephemeral %s on CID %s\n", + GNUNET_e2s(&msg->ephemeral_key), + GNUNET_sh2s(&msg->cid.connection_of_tunnel)); - cc = GCC_lookup (&msg->cid); + cc = GCC_lookup(&msg->cid); if (NULL != cc) - { - /* verify message came from the right direction */ - unsigned int len; - struct CadetPeerPath *path = GCC_get_path (cc, &len); - - if (peer != GCPP_get_peer_at_offset (path, 0)) { - /* received message from unexpected direction, ignore! */ - GNUNET_break_op (0); + /* verify message came from the right direction */ + unsigned int len; + struct CadetPeerPath *path = GCC_get_path(cc, &len); + + if (peer != GCPP_get_peer_at_offset(path, 0)) + { + /* received message from unexpected direction, ignore! */ + GNUNET_break_op(0); + return; + } + GCC_handle_kx(cc, msg); return; } - GCC_handle_kx (cc, msg); - return; - } /* We're just an intermediary peer, route the message along its path */ - route_message (peer, - &msg->cid, - &msg->header, - GNUNET_MQ_PRIO_CRITICAL_CONTROL | GNUNET_MQ_PREF_LOW_LATENCY); + route_message(peer, + &msg->cid, + &msg->header, + GNUNET_MQ_PRIO_CRITICAL_CONTROL | GNUNET_MQ_PREF_LOW_LATENCY); } @@ -1102,7 +1096,7 @@ handle_tunnel_kx (void *cls, * @param msg Message itself. */ static void -handle_tunnel_kx_auth ( +handle_tunnel_kx_auth( void *cls, const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg) { @@ -1110,28 +1104,28 @@ handle_tunnel_kx_auth ( struct CadetConnection *cc; /* First, check if message belongs to a connection that ends here. */ - cc = GCC_lookup (&msg->kx.cid); + cc = GCC_lookup(&msg->kx.cid); if (NULL != cc) - { - /* verify message came from the right direction */ - unsigned int len; - struct CadetPeerPath *path = GCC_get_path (cc, &len); - - if (peer != GCPP_get_peer_at_offset (path, 0)) { - /* received message from unexpected direction, ignore! */ - GNUNET_break_op (0); + /* verify message came from the right direction */ + unsigned int len; + struct CadetPeerPath *path = GCC_get_path(cc, &len); + + if (peer != GCPP_get_peer_at_offset(path, 0)) + { + /* received message from unexpected direction, ignore! */ + GNUNET_break_op(0); + return; + } + GCC_handle_kx_auth(cc, msg); return; } - GCC_handle_kx_auth (cc, msg); - return; - } /* We're just an intermediary peer, route the message along its path */ - route_message (peer, - &msg->kx.cid, - &msg->kx.header, - GNUNET_MQ_PRIO_CRITICAL_CONTROL | GNUNET_MQ_PREF_LOW_LATENCY); + route_message(peer, + &msg->kx.cid, + &msg->kx.header, + GNUNET_MQ_PRIO_CRITICAL_CONTROL | GNUNET_MQ_PREF_LOW_LATENCY); } @@ -1144,8 +1138,8 @@ handle_tunnel_kx_auth ( * @return #GNUNET_YES if size is correct, #GNUNET_NO otherwise. */ static int -check_tunnel_encrypted (void *cls, - const struct GNUNET_CADET_TunnelEncryptedMessage *msg) +check_tunnel_encrypted(void *cls, + const struct GNUNET_CADET_TunnelEncryptedMessage *msg) { return GNUNET_YES; } @@ -1158,31 +1152,31 @@ check_tunnel_encrypted (void *cls, * @param msg Message itself. */ static void -handle_tunnel_encrypted (void *cls, - const struct GNUNET_CADET_TunnelEncryptedMessage *msg) +handle_tunnel_encrypted(void *cls, + const struct GNUNET_CADET_TunnelEncryptedMessage *msg) { struct CadetPeer *peer = cls; struct CadetConnection *cc; /* First, check if message belongs to a connection that ends here. */ - cc = GCC_lookup (&msg->cid); + cc = GCC_lookup(&msg->cid); if (NULL != cc) - { - /* verify message came from the right direction */ - unsigned int len; - struct CadetPeerPath *path = GCC_get_path (cc, &len); - - if (peer != GCPP_get_peer_at_offset (path, 0)) { - /* received message from unexpected direction, ignore! */ - GNUNET_break_op (0); + /* verify message came from the right direction */ + unsigned int len; + struct CadetPeerPath *path = GCC_get_path(cc, &len); + + if (peer != GCPP_get_peer_at_offset(path, 0)) + { + /* received message from unexpected direction, ignore! */ + GNUNET_break_op(0); + return; + } + GCC_handle_encrypted(cc, msg); return; } - GCC_handle_encrypted (cc, msg); - return; - } /* We're just an intermediary peer, route the message along its path */ - route_message (peer, &msg->cid, &msg->header, GNUNET_MQ_PRIO_BEST_EFFORT); + route_message(peer, &msg->cid, &msg->header, GNUNET_MQ_PRIO_BEST_EFFORT); } @@ -1199,14 +1193,14 @@ handle_tunnel_encrypted (void *cls, * @param my_identity ID of this peer, NULL if we failed */ static void -core_init_cb (void *cls, const struct GNUNET_PeerIdentity *my_identity) +core_init_cb(void *cls, const struct GNUNET_PeerIdentity *my_identity) { if (NULL == my_identity) - { - GNUNET_break (0); - return; - } - GNUNET_break (0 == GNUNET_memcmp (my_identity, &my_full_id)); + { + GNUNET_break(0); + return; + } + GNUNET_break(0 == GNUNET_memcmp(my_identity, &my_full_id)); } @@ -1217,17 +1211,17 @@ core_init_cb (void *cls, const struct GNUNET_PeerIdentity *my_identity) * @param peer peer identity this notification is about */ static void * -core_connect_cb (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +core_connect_cb(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { struct CadetPeer *cp; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "CORE connection to peer %s was established.\n", - GNUNET_i2s (peer)); - cp = GCP_get (peer, GNUNET_YES); - GCP_set_mq (cp, mq); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "CORE connection to peer %s was established.\n", + GNUNET_i2s(peer)); + cp = GCP_get(peer, GNUNET_YES); + GCP_set_mq(cp, mq); return cp; } @@ -1239,16 +1233,16 @@ core_connect_cb (void *cls, * @param peer peer identity this notification is about */ static void -core_disconnect_cb (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *peer_cls) +core_disconnect_cb(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *peer_cls) { struct CadetPeer *cp = peer_cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "CORE connection to peer %s went down.\n", - GNUNET_i2s (peer)); - GCP_set_mq (cp, NULL); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "CORE connection to peer %s went down.\n", + GNUNET_i2s(peer)); + GCP_set_mq(cp, NULL); } @@ -1258,57 +1252,57 @@ core_disconnect_cb (void *cls, * @param c Configuration. */ void -GCO_init (const struct GNUNET_CONFIGURATION_Handle *c) +GCO_init(const struct GNUNET_CONFIGURATION_Handle *c) { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_var_size (connection_create, - GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE, - struct GNUNET_CADET_ConnectionCreateMessage, + { GNUNET_MQ_hd_var_size(connection_create, + GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE, + struct GNUNET_CADET_ConnectionCreateMessage, + NULL), + GNUNET_MQ_hd_fixed_size(connection_create_ack, + GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE_ACK, + struct GNUNET_CADET_ConnectionCreateAckMessage, NULL), - GNUNET_MQ_hd_fixed_size (connection_create_ack, - GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE_ACK, - struct GNUNET_CADET_ConnectionCreateAckMessage, - NULL), - GNUNET_MQ_hd_fixed_size (connection_broken, - GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN, - struct GNUNET_CADET_ConnectionBrokenMessage, - NULL), - GNUNET_MQ_hd_fixed_size (connection_destroy, - GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY, - struct GNUNET_CADET_ConnectionDestroyMessage, - NULL), - GNUNET_MQ_hd_fixed_size (tunnel_kx, - GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX, - struct GNUNET_CADET_TunnelKeyExchangeMessage, - NULL), - GNUNET_MQ_hd_fixed_size (tunnel_kx_auth, - GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH, - struct GNUNET_CADET_TunnelKeyExchangeAuthMessage, - NULL), - GNUNET_MQ_hd_var_size (tunnel_encrypted, - GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED, - struct GNUNET_CADET_TunnelEncryptedMessage, + GNUNET_MQ_hd_fixed_size(connection_broken, + GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN, + struct GNUNET_CADET_ConnectionBrokenMessage, NULL), - GNUNET_MQ_handler_end ()}; - - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (c, - "CADET", - "MAX_ROUTES", - &max_routes)) + GNUNET_MQ_hd_fixed_size(connection_destroy, + GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY, + struct GNUNET_CADET_ConnectionDestroyMessage, + NULL), + GNUNET_MQ_hd_fixed_size(tunnel_kx, + GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX, + struct GNUNET_CADET_TunnelKeyExchangeMessage, + NULL), + GNUNET_MQ_hd_fixed_size(tunnel_kx_auth, + GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH, + struct GNUNET_CADET_TunnelKeyExchangeAuthMessage, + NULL), + GNUNET_MQ_hd_var_size(tunnel_encrypted, + GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED, + struct GNUNET_CADET_TunnelEncryptedMessage, + NULL), + GNUNET_MQ_handler_end() }; + + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(c, + "CADET", + "MAX_ROUTES", + &max_routes)) max_routes = 5000; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (c, - "CADET", - "MAX_MSGS_QUEUE", - &max_buffers)) + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(c, + "CADET", + "MAX_MSGS_QUEUE", + &max_buffers)) max_buffers = 10000; - routes = GNUNET_CONTAINER_multishortmap_create (1024, GNUNET_NO); - route_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); - core = GNUNET_CORE_connect (c, - NULL, - &core_init_cb, - &core_connect_cb, - &core_disconnect_cb, - handlers); + routes = GNUNET_CONTAINER_multishortmap_create(1024, GNUNET_NO); + route_heap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN); + core = GNUNET_CORE_connect(c, + NULL, + &core_init_cb, + &core_connect_cb, + &core_disconnect_cb, + handlers); } @@ -1316,23 +1310,23 @@ GCO_init (const struct GNUNET_CONFIGURATION_Handle *c) * Shut down the CORE subsystem. */ void -GCO_shutdown () +GCO_shutdown() { if (NULL != core) - { - GNUNET_CORE_disconnect (core); - core = NULL; - } - GNUNET_assert (0 == GNUNET_CONTAINER_multishortmap_size (routes)); - GNUNET_CONTAINER_multishortmap_destroy (routes); + { + GNUNET_CORE_disconnect(core); + core = NULL; + } + GNUNET_assert(0 == GNUNET_CONTAINER_multishortmap_size(routes)); + GNUNET_CONTAINER_multishortmap_destroy(routes); routes = NULL; - GNUNET_CONTAINER_heap_destroy (route_heap); + GNUNET_CONTAINER_heap_destroy(route_heap); route_heap = NULL; if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } } /* end of gnunet-cadet-service_core.c */ diff --git a/src/cadet/gnunet-service-cadet_core.h b/src/cadet/gnunet-service-cadet_core.h index ec676c679..b049dc2af 100644 --- a/src/cadet/gnunet-service-cadet_core.h +++ b/src/cadet/gnunet-service-cadet_core.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_core.h @@ -47,14 +47,14 @@ extern "C" * @param c Configuration. */ void -GCO_init (const struct GNUNET_CONFIGURATION_Handle *c); +GCO_init(const struct GNUNET_CONFIGURATION_Handle *c); /** * Shut down the CORE subsystem. */ void -GCO_shutdown (void); +GCO_shutdown(void); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/cadet/gnunet-service-cadet_dht.c b/src/cadet/gnunet-service-cadet_dht.c index 0b87eeab7..c208c7f29 100644 --- a/src/cadet/gnunet-service-cadet_dht.c +++ b/src/cadet/gnunet-service-cadet_dht.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_dht.c * @brief Information we track per peer. @@ -40,29 +40,27 @@ * notifications when our HELLO is ready, so this is just the maximum * we wait for the first notification. */ -#define STARTUP_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500) +#define STARTUP_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 500) /** * How long do we wait after we get an updated HELLO before publishing? * Allows for the HELLO to be updated again quickly, for example in * case multiple addresses changed and we got a partial update. */ -#define CHANGE_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100) +#define CHANGE_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100) -#define LOG(level, ...) GNUNET_log_from (level,"cadet-dht",__VA_ARGS__) +#define LOG(level, ...) GNUNET_log_from(level, "cadet-dht", __VA_ARGS__) /** * Handle for DHT searches. */ -struct GCD_search_handle -{ +struct GCD_search_handle { /** * DHT_GET handle. */ struct GNUNET_DHT_GetHandle *dhtget; - }; @@ -109,35 +107,35 @@ static struct GNUNET_TIME_Relative announce_delay; * @param data pointer to the result data */ static void -dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - enum GNUNET_BLOCK_Type type, - size_t size, - const void *data) +dht_get_id_handler(void *cls, struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + enum GNUNET_BLOCK_Type type, + size_t size, + const void *data) { const struct GNUNET_HELLO_Message *hello = data; struct CadetPeer *peer; - GCPP_try_path_from_dht (get_path, - get_path_length, - put_path, - put_path_length); - if ( (size >= sizeof (struct GNUNET_HELLO_Message)) && - (ntohs (hello->header.size) == size) && - (size == GNUNET_HELLO_size (hello)) ) - { - peer = GCP_get (&put_path[0], - GNUNET_YES); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got HELLO for %s\n", - GCP_2s (peer)); - GCP_set_hello (peer, - hello); - } + GCPP_try_path_from_dht(get_path, + get_path_length, + put_path, + put_path_length); + if ((size >= sizeof(struct GNUNET_HELLO_Message)) && + (ntohs(hello->header.size) == size) && + (size == GNUNET_HELLO_size(hello))) + { + peer = GCP_get(&put_path[0], + GNUNET_YES); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got HELLO for %s\n", + GCP_2s(peer)); + GCP_set_hello(peer, + hello); + } } @@ -147,7 +145,7 @@ dht_get_id_handler (void *cls, struct GNUNET_TIME_Absolute exp, * @param cls closure */ static void -announce_id (void *cls) +announce_id(void *cls) { struct GNUNET_HashCode phash; const struct GNUNET_HELLO_Message *hello; @@ -155,58 +153,58 @@ announce_id (void *cls) struct GNUNET_TIME_Absolute expiration; struct GNUNET_TIME_Relative next_put; - hello = GCH_get_mine (); - size = (NULL != hello) ? GNUNET_HELLO_size (hello) : 0; + hello = GCH_get_mine(); + size = (NULL != hello) ? GNUNET_HELLO_size(hello) : 0; if (0 == size) - { - expiration = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (), - announce_delay); - announce_delay = GNUNET_TIME_STD_BACKOFF (announce_delay); - } + { + expiration = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), + announce_delay); + announce_delay = GNUNET_TIME_STD_BACKOFF(announce_delay); + } else - { - expiration = GNUNET_HELLO_get_last_expiration (hello); - announce_delay = GNUNET_TIME_UNIT_SECONDS; - } + { + expiration = GNUNET_HELLO_get_last_expiration(hello); + announce_delay = GNUNET_TIME_UNIT_SECONDS; + } /* Call again in id_announce_time, unless HELLO expires first, * but wait at least 1s. */ next_put - = GNUNET_TIME_absolute_get_remaining (expiration); + = GNUNET_TIME_absolute_get_remaining(expiration); next_put - = GNUNET_TIME_relative_min (next_put, - id_announce_time); + = GNUNET_TIME_relative_min(next_put, + id_announce_time); next_put - = GNUNET_TIME_relative_max (next_put, - GNUNET_TIME_UNIT_SECONDS); + = GNUNET_TIME_relative_max(next_put, + GNUNET_TIME_UNIT_SECONDS); announce_id_task - = GNUNET_SCHEDULER_add_delayed (next_put, - &announce_id, - cls); - GNUNET_STATISTICS_update (stats, - "# DHT announce", - 1, - GNUNET_NO); - memset (&phash, - 0, - sizeof (phash)); - GNUNET_memcpy (&phash, - &my_full_id, - sizeof (my_full_id)); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Announcing my HELLO (%u bytes) in the DHT\n", - size); - GNUNET_DHT_put (dht_handle, /* DHT handle */ - &phash, /* Key to use */ - dht_replication_level, /* Replication level */ - GNUNET_DHT_RO_RECORD_ROUTE - | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, /* DHT options */ - GNUNET_BLOCK_TYPE_DHT_HELLO, /* Block type */ - size, /* Size of the data */ - (const char *) hello, /* Data itself */ - expiration, /* Data expiration */ - NULL, /* Continuation */ - NULL); /* Continuation closure */ + = GNUNET_SCHEDULER_add_delayed(next_put, + &announce_id, + cls); + GNUNET_STATISTICS_update(stats, + "# DHT announce", + 1, + GNUNET_NO); + memset(&phash, + 0, + sizeof(phash)); + GNUNET_memcpy(&phash, + &my_full_id, + sizeof(my_full_id)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Announcing my HELLO (%u bytes) in the DHT\n", + size); + GNUNET_DHT_put(dht_handle, /* DHT handle */ + &phash, /* Key to use */ + dht_replication_level, /* Replication level */ + GNUNET_DHT_RO_RECORD_ROUTE + | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, /* DHT options */ + GNUNET_BLOCK_TYPE_DHT_HELLO, /* Block type */ + size, /* Size of the data */ + (const char *)hello, /* Data itself */ + expiration, /* Data expiration */ + NULL, /* Continuation */ + NULL); /* Continuation closure */ } @@ -215,15 +213,15 @@ announce_id (void *cls) * changes. Re-triggers the DHT PUT immediately. */ void -GCD_hello_update () +GCD_hello_update() { if (NULL == announce_id_task) return; /* too early */ - GNUNET_SCHEDULER_cancel (announce_id_task); + GNUNET_SCHEDULER_cancel(announce_id_task); announce_id_task - = GNUNET_SCHEDULER_add_delayed (CHANGE_DELAY, - &announce_id, - NULL); + = GNUNET_SCHEDULER_add_delayed(CHANGE_DELAY, + &announce_id, + NULL); } @@ -233,42 +231,42 @@ GCD_hello_update () * @param c Configuration. */ void -GCD_init (const struct GNUNET_CONFIGURATION_Handle *c) +GCD_init(const struct GNUNET_CONFIGURATION_Handle *c) { if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (c, - "CADET", - "DHT_REPLICATION_LEVEL", - &dht_replication_level)) - { - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING, - "CADET", - "DHT_REPLICATION_LEVEL", - "USING DEFAULT"); - dht_replication_level = 3; - } + GNUNET_CONFIGURATION_get_value_number(c, + "CADET", + "DHT_REPLICATION_LEVEL", + &dht_replication_level)) + { + GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_WARNING, + "CADET", + "DHT_REPLICATION_LEVEL", + "USING DEFAULT"); + dht_replication_level = 3; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_time (c, - "CADET", - "ID_ANNOUNCE_TIME", - &id_announce_time)) - { - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, - "CADET", - "ID_ANNOUNCE_TIME", - "MISSING"); - GNUNET_SCHEDULER_shutdown (); - return; - } - - dht_handle = GNUNET_DHT_connect (c, - 64); - GNUNET_break (NULL != dht_handle); + GNUNET_CONFIGURATION_get_value_time(c, + "CADET", + "ID_ANNOUNCE_TIME", + &id_announce_time)) + { + GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_ERROR, + "CADET", + "ID_ANNOUNCE_TIME", + "MISSING"); + GNUNET_SCHEDULER_shutdown(); + return; + } + + dht_handle = GNUNET_DHT_connect(c, + 64); + GNUNET_break(NULL != dht_handle); announce_delay = GNUNET_TIME_UNIT_SECONDS; - announce_id_task = GNUNET_SCHEDULER_add_delayed (STARTUP_DELAY, - &announce_id, - NULL); + announce_id_task = GNUNET_SCHEDULER_add_delayed(STARTUP_DELAY, + &announce_id, + NULL); } @@ -276,18 +274,18 @@ GCD_init (const struct GNUNET_CONFIGURATION_Handle *c) * Shut down the DHT subsystem. */ void -GCD_shutdown (void) +GCD_shutdown(void) { if (NULL != dht_handle) - { - GNUNET_DHT_disconnect (dht_handle); - dht_handle = NULL; - } + { + GNUNET_DHT_disconnect(dht_handle); + dht_handle = NULL; + } if (NULL != announce_id_task) - { - GNUNET_SCHEDULER_cancel (announce_id_task); - announce_id_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(announce_id_task); + announce_id_task = NULL; + } } @@ -298,37 +296,37 @@ GCD_shutdown (void) * @return handle to abort search */ struct GCD_search_handle * -GCD_search (const struct GNUNET_PeerIdentity *peer_id) +GCD_search(const struct GNUNET_PeerIdentity *peer_id) { struct GNUNET_HashCode phash; struct GCD_search_handle *h; - GNUNET_STATISTICS_update (stats, - "# DHT search", - 1, - GNUNET_NO); - memset (&phash, - 0, - sizeof (phash)); - GNUNET_memcpy (&phash, - peer_id, - sizeof (*peer_id)); - - h = GNUNET_new (struct GCD_search_handle); - h->dhtget = GNUNET_DHT_get_start (dht_handle, /* handle */ - GNUNET_BLOCK_TYPE_DHT_HELLO, /* type */ - &phash, /* key to search */ - dht_replication_level, /* replication level */ - GNUNET_DHT_RO_RECORD_ROUTE | - GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, - NULL, /* xquery */ - 0, /* xquery bits */ - &dht_get_id_handler, - h); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Starting DHT GET for peer %s (%p)\n", - GNUNET_i2s (peer_id), - h); + GNUNET_STATISTICS_update(stats, + "# DHT search", + 1, + GNUNET_NO); + memset(&phash, + 0, + sizeof(phash)); + GNUNET_memcpy(&phash, + peer_id, + sizeof(*peer_id)); + + h = GNUNET_new(struct GCD_search_handle); + h->dhtget = GNUNET_DHT_get_start(dht_handle, /* handle */ + GNUNET_BLOCK_TYPE_DHT_HELLO, /* type */ + &phash, /* key to search */ + dht_replication_level, /* replication level */ + GNUNET_DHT_RO_RECORD_ROUTE | + GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, + NULL, /* xquery */ + 0, /* xquery bits */ + &dht_get_id_handler, + h); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Starting DHT GET for peer %s (%p)\n", + GNUNET_i2s(peer_id), + h); return h; } @@ -339,13 +337,13 @@ GCD_search (const struct GNUNET_PeerIdentity *peer_id) * @param h handle to search to stop */ void -GCD_search_stop (struct GCD_search_handle *h) +GCD_search_stop(struct GCD_search_handle *h) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Stopping DHT GET %p\n", - h); - GNUNET_DHT_get_stop (h->dhtget); - GNUNET_free (h); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Stopping DHT GET %p\n", + h); + GNUNET_DHT_get_stop(h->dhtget); + GNUNET_free(h); } /* end of gnunet-service-cadet_dht.c */ diff --git a/src/cadet/gnunet-service-cadet_dht.h b/src/cadet/gnunet-service-cadet_dht.h index 03f045938..4cb6e9fff 100644 --- a/src/cadet/gnunet-service-cadet_dht.h +++ b/src/cadet/gnunet-service-cadet_dht.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_dht.h @@ -52,14 +52,14 @@ struct GCD_search_handle; * @param c Configuration. */ void -GCD_init (const struct GNUNET_CONFIGURATION_Handle *c); +GCD_init(const struct GNUNET_CONFIGURATION_Handle *c); /** * Shut down the DHT subsystem. */ void -GCD_shutdown (void); +GCD_shutdown(void); /** @@ -67,7 +67,7 @@ GCD_shutdown (void); * changes. Re-triggers the DHT PUT immediately. */ void -GCD_hello_update (void); +GCD_hello_update(void); /** * Search DHT for paths to @a peeR_id @@ -76,7 +76,7 @@ GCD_hello_update (void); * @return handle to abort search */ struct GCD_search_handle * -GCD_search (const struct GNUNET_PeerIdentity *peer_id); +GCD_search(const struct GNUNET_PeerIdentity *peer_id); /** @@ -85,7 +85,7 @@ GCD_search (const struct GNUNET_PeerIdentity *peer_id); * @param h handle to search to stop */ void -GCD_search_stop (struct GCD_search_handle *h); +GCD_search_stop(struct GCD_search_handle *h); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/cadet/gnunet-service-cadet_hello.c b/src/cadet/gnunet-service-cadet_hello.c index fe2477c34..7d6d2b0ce 100644 --- a/src/cadet/gnunet-service-cadet_hello.c +++ b/src/cadet/gnunet-service-cadet_hello.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_hello.c * @brief spread knowledge about how to contact us (get HELLO from peerinfo), @@ -35,7 +35,7 @@ #include "gnunet-service-cadet_hello.h" #include "gnunet-service-cadet_peer.h" -#define LOG(level, ...) GNUNET_log_from(level,"cadet-hll",__VA_ARGS__) +#define LOG(level, ...) GNUNET_log_from(level, "cadet-hll", __VA_ARGS__) /** * Hello message of local peer. @@ -62,34 +62,34 @@ static struct GNUNET_PEERINFO_NotifyContext *nc; * @param err_msg Error message. */ static void -got_hello (void *cls, - const struct GNUNET_PeerIdentity *id, - const struct GNUNET_HELLO_Message *hello, - const char *err_msg) +got_hello(void *cls, + const struct GNUNET_PeerIdentity *id, + const struct GNUNET_HELLO_Message *hello, + const char *err_msg) { struct CadetPeer *peer; - if ( (NULL == id) || - (NULL == hello) ) - return; - if (0 == GNUNET_memcmp (id, - &my_full_id)) - { - GNUNET_free_non_null (mine); - mine = (struct GNUNET_HELLO_Message *) GNUNET_copy_message (&hello->header); - GCD_hello_update (); + if ((NULL == id) || + (NULL == hello)) return; - } - - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Hello for %s (%d bytes), expires on %s\n", - GNUNET_i2s (id), - GNUNET_HELLO_size (hello), - GNUNET_STRINGS_absolute_time_to_string (GNUNET_HELLO_get_last_expiration (hello))); - peer = GCP_get (id, - GNUNET_YES); - GCP_set_hello (peer, - hello); + if (0 == GNUNET_memcmp(id, + &my_full_id)) + { + GNUNET_free_non_null(mine); + mine = (struct GNUNET_HELLO_Message *)GNUNET_copy_message(&hello->header); + GCD_hello_update(); + return; + } + + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Hello for %s (%d bytes), expires on %s\n", + GNUNET_i2s(id), + GNUNET_HELLO_size(hello), + GNUNET_STRINGS_absolute_time_to_string(GNUNET_HELLO_get_last_expiration(hello))); + peer = GCP_get(id, + GNUNET_YES); + GCP_set_hello(peer, + hello); } @@ -99,14 +99,14 @@ got_hello (void *cls, * @param c Configuration. */ void -GCH_init (const struct GNUNET_CONFIGURATION_Handle *c) +GCH_init(const struct GNUNET_CONFIGURATION_Handle *c) { - GNUNET_assert (NULL == nc); - peerinfo = GNUNET_PEERINFO_connect (c); - nc = GNUNET_PEERINFO_notify (c, - GNUNET_NO, - &got_hello, - NULL); + GNUNET_assert(NULL == nc); + peerinfo = GNUNET_PEERINFO_connect(c); + nc = GNUNET_PEERINFO_notify(c, + GNUNET_NO, + &got_hello, + NULL); } @@ -114,23 +114,23 @@ GCH_init (const struct GNUNET_CONFIGURATION_Handle *c) * Shut down the hello subsystem. */ void -GCH_shutdown () +GCH_shutdown() { if (NULL != nc) - { - GNUNET_PEERINFO_notify_cancel (nc); - nc = NULL; - } + { + GNUNET_PEERINFO_notify_cancel(nc); + nc = NULL; + } if (NULL != peerinfo) - { - GNUNET_PEERINFO_disconnect (peerinfo); - peerinfo = NULL; - } + { + GNUNET_PEERINFO_disconnect(peerinfo); + peerinfo = NULL; + } if (NULL != mine) - { - GNUNET_free (mine); - mine = NULL; - } + { + GNUNET_free(mine); + mine = NULL; + } } @@ -140,7 +140,7 @@ GCH_shutdown () * @return Own hello message. */ const struct GNUNET_HELLO_Message * -GCH_get_mine (void) +GCH_get_mine(void) { return mine; } diff --git a/src/cadet/gnunet-service-cadet_hello.h b/src/cadet/gnunet-service-cadet_hello.h index 821cd4ff4..99b6c807d 100644 --- a/src/cadet/gnunet-service-cadet_hello.h +++ b/src/cadet/gnunet-service-cadet_hello.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_hello.h @@ -49,14 +49,14 @@ extern "C" * @param c Configuration. */ void -GCH_init (const struct GNUNET_CONFIGURATION_Handle *c); +GCH_init(const struct GNUNET_CONFIGURATION_Handle *c); /** * Shut down the hello subsystem. */ void -GCH_shutdown (void); +GCH_shutdown(void); /** @@ -65,7 +65,7 @@ GCH_shutdown (void); * @return Own hello message. */ const struct GNUNET_HELLO_Message * -GCH_get_mine (void); +GCH_get_mine(void); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/cadet/gnunet-service-cadet_paths.c b/src/cadet/gnunet-service-cadet_paths.c index bdc92668e..149ac659a 100644 --- a/src/cadet/gnunet-service-cadet_paths.c +++ b/src/cadet/gnunet-service-cadet_paths.c @@ -11,15 +11,15 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_paths.c - * @brief Information we track per path. + * @brief Information we track per path. * @author Bartlomiej Polot * @author Christian Grothoff */ @@ -30,15 +30,13 @@ #include "gnunet-service-cadet_paths.h" -#define LOG(level, ...) GNUNET_log_from(level,"cadet-pat",__VA_ARGS__) +#define LOG(level, ...) GNUNET_log_from(level, "cadet-pat", __VA_ARGS__) /** * Information regarding a possible path to reach a peer. */ -struct CadetPeerPath -{ - +struct CadetPeerPath { /** * Array of all the peers on the path. If @e hn is non-NULL, the * last one is our owner. @@ -61,7 +59,6 @@ struct CadetPeerPath * Length of the @e entries array. */ unsigned int entries_length; - }; @@ -71,18 +68,18 @@ struct CadetPeerPath * @param path path to calculate the score for */ static void -recalculate_path_desirability (struct CadetPeerPath *path) +recalculate_path_desirability(struct CadetPeerPath *path) { double result = 0.0; - for (unsigned int i=0;ientries_length;i++) - { - struct CadetPeer *cp = path->entries[i]->peer; + for (unsigned int i = 0; i < path->entries_length; i++) + { + struct CadetPeer *cp = path->entries[i]->peer; - result += GCP_get_desirability_of_path (cp, - i); - } - path->desirability = (GNUNET_CONTAINER_HeapCostType) result; + result += GCP_get_desirability_of_path(cp, + i); + } + path->desirability = (GNUNET_CONTAINER_HeapCostType)result; } @@ -100,7 +97,7 @@ recalculate_path_desirability (struct CadetPeerPath *path) * @return desirability of the path, larger is more desirable */ GNUNET_CONTAINER_HeapCostType -GCPP_get_desirability (const struct CadetPeerPath *path) +GCPP_get_desirability(const struct CadetPeerPath *path) { return path->desirability; } @@ -117,15 +114,15 @@ GCPP_get_desirability (const struct CadetPeerPath *path) * otherwise connection from us to @a destination via @a path */ struct CadetConnection * -GCPP_get_connection (struct CadetPeerPath *path, - struct CadetPeer *destination, - unsigned int off) +GCPP_get_connection(struct CadetPeerPath *path, + struct CadetPeer *destination, + unsigned int off) { struct CadetPeerPathEntry *entry; - GNUNET_assert (off < path->entries_length); + GNUNET_assert(off < path->entries_length); entry = path->entries[off]; - GNUNET_assert (entry->peer == destination); + GNUNET_assert(entry->peer == destination); return entry->cc; } @@ -139,21 +136,21 @@ GCPP_get_connection (struct CadetPeerPath *path, * @param cc the connection to remember */ void -GCPP_add_connection (struct CadetPeerPath *path, - unsigned int off, - struct CadetConnection *cc) +GCPP_add_connection(struct CadetPeerPath *path, + unsigned int off, + struct CadetConnection *cc) { struct CadetPeerPathEntry *entry; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Adding %s to path %s at offset %u\n", - GCC_2s (cc), - GCPP_2s (path), - off); - GNUNET_assert (off < path->entries_length); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Adding %s to path %s at offset %u\n", + GCC_2s(cc), + GCPP_2s(path), + off); + GNUNET_assert(off < path->entries_length); entry = path->entries[off]; - GNUNET_assert (NULL == entry->cc); - GNUNET_assert (NULL != cc); + GNUNET_assert(NULL == entry->cc); + GNUNET_assert(NULL != cc); entry->cc = cc; } @@ -168,20 +165,20 @@ GCPP_add_connection (struct CadetPeerPath *path, * @param cc the connection to forget */ void -GCPP_del_connection (struct CadetPeerPath *path, - unsigned int off, - struct CadetConnection *cc) +GCPP_del_connection(struct CadetPeerPath *path, + unsigned int off, + struct CadetConnection *cc) { struct CadetPeerPathEntry *entry; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Removing connection %s to path %s at offset %u\n", - GCC_2s (cc), - GCPP_2s (path), - off); - GNUNET_assert (off < path->entries_length); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Removing connection %s to path %s at offset %u\n", + GCC_2s(cc), + GCPP_2s(path), + off); + GNUNET_assert(off < path->entries_length); entry = path->entries[off]; - GNUNET_assert (cc == entry->cc); + GNUNET_assert(cc == entry->cc); entry->cc = NULL; } @@ -196,42 +193,42 @@ GCPP_del_connection (struct CadetPeerPath *path, * @param stop_at the path length at which to stop trying */ static void -attach_path (struct CadetPeerPath *path, unsigned int stop_at) +attach_path(struct CadetPeerPath *path, unsigned int stop_at) { - GNUNET_assert (NULL == path->hn); + GNUNET_assert(NULL == path->hn); /* Try to attach this path to a peer, working backwards from the end. */ while (path->entries_length > stop_at) - { - unsigned int end = path->entries_length - 1; - struct CadetPeerPathEntry *entry = path->entries[end]; - int force = GNUNET_NO; - - recalculate_path_desirability (path); - /* If the entry already has a connection using it, force attach. */ - if (NULL != entry->cc) - force = GNUNET_YES; - path->hn = GCP_attach_path (entry->peer, - path, - end, - force); - if (NULL != path->hn) - break; - - /* Attach failed, trim this entry from the path. */ - GNUNET_assert (NULL == entry->cc); - GCP_path_entry_remove (entry->peer, - entry, - end); - GNUNET_free (entry); - path->entries[end] = NULL; - path->entries_length--; - } + { + unsigned int end = path->entries_length - 1; + struct CadetPeerPathEntry *entry = path->entries[end]; + int force = GNUNET_NO; + + recalculate_path_desirability(path); + /* If the entry already has a connection using it, force attach. */ + if (NULL != entry->cc) + force = GNUNET_YES; + path->hn = GCP_attach_path(entry->peer, + path, + end, + force); + if (NULL != path->hn) + break; + + /* Attach failed, trim this entry from the path. */ + GNUNET_assert(NULL == entry->cc); + GCP_path_entry_remove(entry->peer, + entry, + end); + GNUNET_free(entry); + path->entries[end] = NULL; + path->entries_length--; + } /* Shrink array to actual path length. */ - GNUNET_array_grow (path->entries, - path->entries_length, - path->entries_length); + GNUNET_array_grow(path->entries, + path->entries_length, + path->entries_length); } @@ -243,33 +240,33 @@ attach_path (struct CadetPeerPath *path, unsigned int stop_at) * @param path the path that is being released */ void -GCPP_release (struct CadetPeerPath *path) +GCPP_release(struct CadetPeerPath *path) { struct CadetPeerPathEntry *entry; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Owner releases path %s\n", - GCPP_2s (path)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Owner releases path %s\n", + GCPP_2s(path)); path->hn = NULL; entry = path->entries[path->entries_length - 1]; - GNUNET_assert (path == entry->path); - GNUNET_assert (NULL == entry->cc); + GNUNET_assert(path == entry->path); + GNUNET_assert(NULL == entry->cc); /* cut 'off' end of path */ - GCP_path_entry_remove (entry->peer, - entry, - path->entries_length - 1); - GNUNET_free (entry); + GCP_path_entry_remove(entry->peer, + entry, + path->entries_length - 1); + GNUNET_free(entry); path->entries[path->entries_length - 1] = NULL; path->entries_length--; /* see if new peer at the end likes this path any better */ - attach_path (path, 0); + attach_path(path, 0); if (NULL == path->hn) - { - /* nobody wants us, discard the path */ - GNUNET_assert (0 == path->entries_length); - GNUNET_assert (NULL == path->entries); - GNUNET_free (path); - } + { + /* nobody wants us, discard the path */ + GNUNET_assert(0 == path->entries_length); + GNUNET_assert(NULL == path->entries); + GNUNET_free(path); + } } @@ -282,40 +279,38 @@ GCPP_release (struct CadetPeerPath *path) * @param delta change in the score to apply */ void -GCPP_update_score (struct CadetPeerPath *path, - unsigned int off, - int delta) +GCPP_update_score(struct CadetPeerPath *path, + unsigned int off, + int delta) { struct CadetPeerPathEntry *entry; - GNUNET_assert (off < path->entries_length); + GNUNET_assert(off < path->entries_length); entry = path->entries[off]; /* Add delta, with checks for overflows */ if (delta >= 0) - { - if (delta + entry->score < entry->score) - entry->score = INT_MAX; - else - entry->score += delta; - } + { + if (delta + entry->score < entry->score) + entry->score = INT_MAX; + else + entry->score += delta; + } else - { - if (delta + entry->score > entry->score) - entry->score = INT_MIN; - else - entry->score += delta; - } - recalculate_path_desirability (path); + { + if (delta + entry->score > entry->score) + entry->score = INT_MIN; + else + entry->score += delta; + } + recalculate_path_desirability(path); } /** * Closure for #find_peer_at() and #check_match(). */ -struct CheckMatchContext -{ - +struct CheckMatchContext { /** * Set to a matching path, if any. */ @@ -330,7 +325,6 @@ struct CheckMatchContext * How long is the @e cpath array? */ unsigned int cpath_length; - }; @@ -345,38 +339,38 @@ struct CheckMatchContext * @return #GNUNET_YES (continue to iterate), or if found #GNUNET_NO */ static int -check_match (void *cls, - struct CadetPeerPath *path, - unsigned int off) +check_match(void *cls, + struct CadetPeerPath *path, + unsigned int off) { struct CheckMatchContext *cm_ctx = cls; - GNUNET_assert (path->entries_length > off); - if ( (path->entries_length != off + 1) && - (off + 1 != cm_ctx->cpath_length) ) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "check_match mismatch because path %s is too long (%u vs. %u vs. %u)\n", - GCPP_2s (path), - path->entries_length, - off + 1, - cm_ctx->cpath_length); - return GNUNET_YES; /* too long, goes somewhere else already, thus cannot be useful */ - } - for (unsigned int i=0;icpath[i] != - GCPP_get_peer_at_offset (path, - i)) + GNUNET_assert(path->entries_length > off); + if ((path->entries_length != off + 1) && + (off + 1 != cm_ctx->cpath_length)) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "check_match path %s mismatches at offset %u\n", - GCPP_2s (path), - i); - return GNUNET_YES; /* mismatch, ignore */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "check_match mismatch because path %s is too long (%u vs. %u vs. %u)\n", + GCPP_2s(path), + path->entries_length, + off + 1, + cm_ctx->cpath_length); + return GNUNET_YES; /* too long, goes somewhere else already, thus cannot be useful */ } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "check_match found match with path %s\n", - GCPP_2s (path)); + for (unsigned int i = 0; i < off; i++) + if (cm_ctx->cpath[i] != + GCPP_get_peer_at_offset(path, + i)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "check_match path %s mismatches at offset %u\n", + GCPP_2s(path), + i); + return GNUNET_YES; /* mismatch, ignore */ + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "check_match found match with path %s\n", + GCPP_2s(path)); cm_ctx->match = path; return GNUNET_NO; /* match, we are done! */ } @@ -393,68 +387,70 @@ check_match (void *cls, * paths already */ static void -extend_path (struct CadetPeerPath *path, - struct CadetPeer **peers, - unsigned int num_peers, - int force) +extend_path(struct CadetPeerPath *path, + struct CadetPeer **peers, + unsigned int num_peers, + int force) { unsigned int old_len = path->entries_length; int i; /* Expand path */ - GNUNET_array_grow (path->entries, - path->entries_length, - old_len + num_peers); - for (i=num_peers-1;i >= 0;i--) - { - struct CadetPeerPathEntry *entry = GNUNET_new (struct CadetPeerPathEntry); - - path->entries[old_len + i] = entry; - entry->peer = peers[i]; - entry->path = path; - } - for (i=num_peers-1;i >= 0;i--) - { - struct CadetPeerPathEntry *entry = path->entries[old_len + i]; - - GCP_path_entry_add (entry->peer, - entry, - old_len + i); - } + GNUNET_array_grow(path->entries, + path->entries_length, + old_len + num_peers); + for (i = num_peers - 1; i >= 0; i--) + { + struct CadetPeerPathEntry *entry = GNUNET_new(struct CadetPeerPathEntry); + + path->entries[old_len + i] = entry; + entry->peer = peers[i]; + entry->path = path; + } + for (i = num_peers - 1; i >= 0; i--) + { + struct CadetPeerPathEntry *entry = path->entries[old_len + i]; + + GCP_path_entry_add(entry->peer, + entry, + old_len + i); + } /* If we extend an existing path, detach it from the old owner and re-attach to the new one */ - GCP_detach_path (path->entries[old_len-1]->peer, - path, - path->hn); + GCP_detach_path(path->entries[old_len - 1]->peer, + path, + path->hn); path->hn = NULL; path->entries_length = old_len + num_peers; if (GNUNET_YES == force) - { - int end = path->entries_length - 1; - - path->hn = GCP_attach_path (path->entries[end]->peer, - path, - end, - GNUNET_YES); - } else { - attach_path (path, old_len); - } + { + int end = path->entries_length - 1; + + path->hn = GCP_attach_path(path->entries[end]->peer, + path, + end, + GNUNET_YES); + } + else + { + attach_path(path, old_len); + } if (NULL == path->hn) - { - /* none of the peers is interested in this path; - re-attach. */ - GNUNET_assert (old_len == path->entries_length); - path->hn = GCP_attach_path (path->entries[old_len - 1]->peer, - path, - old_len - 1, - GNUNET_YES); - GNUNET_assert (NULL != path->hn); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Extended path %s\n", - GCPP_2s (path)); + { + /* none of the peers is interested in this path; + re-attach. */ + GNUNET_assert(old_len == path->entries_length); + path->hn = GCP_attach_path(path->entries[old_len - 1]->peer, + path, + old_len - 1, + GNUNET_YES); + GNUNET_assert(NULL != path->hn); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Extended path %s\n", + GCPP_2s(path)); } @@ -471,10 +467,10 @@ extend_path (struct CadetPeerPath *path, * @return a path through the network */ void -GCPP_try_path_from_dht (const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length) +GCPP_try_path_from_dht(const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length) { struct CadetPeer *cpath[get_path_length + put_path_length]; struct CheckMatchContext cm_ctx; @@ -484,42 +480,42 @@ GCPP_try_path_from_dht (const struct GNUNET_PeerIdentity *get_path, /* precompute 'cpath' so we can avoid doing the lookups lots of times */ skip = 0; - memset (cpath, - 0, - sizeof (cpath)); /* Just to trigger harder errors later. */ + memset(cpath, + 0, + sizeof(cpath)); /* Just to trigger harder errors later. */ total_len = get_path_length + put_path_length; - for (unsigned int off=0;off= total_len) { - if (cpath[i] == cpath[off - skip]) - { - skip = off - i; - break; - } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Path discovered from DHT is one big cycle?\n"); + return; } - } - if (skip >= total_len) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Path discovered from DHT is one big cycle?\n"); - return; - } total_len -= skip; /* First figure out if this path is a subset of an existing path, an @@ -527,73 +523,73 @@ GCPP_try_path_from_dht (const struct GNUNET_PeerIdentity *get_path, cm_ctx.cpath_length = total_len; cm_ctx.cpath = cpath; cm_ctx.match = NULL; - for (int i=total_len-1;i>=0;i--) - { - GCP_iterate_paths_at (cpath[i], - (unsigned int) i, - &check_match, - &cm_ctx); - if (NULL != cm_ctx.match) + for (int i = total_len - 1; i >= 0; i--) { - if (i == total_len - 1) - { - /* Existing path includes this one, nothing to do! */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Path discovered from DHT is already known\n"); - return; - } - if (cm_ctx.match->entries_length == i + 1) - { - /* Existing path ends in the middle of new path, extend it! */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Trying to extend existing path %s by additional links discovered from DHT\n", - GCPP_2s (cm_ctx.match)); - extend_path (cm_ctx.match, - &cpath[i + 1], - total_len - i - 1, - GNUNET_NO); - return; - } + GCP_iterate_paths_at(cpath[i], + (unsigned int)i, + &check_match, + &cm_ctx); + if (NULL != cm_ctx.match) + { + if (i == total_len - 1) + { + /* Existing path includes this one, nothing to do! */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Path discovered from DHT is already known\n"); + return; + } + if (cm_ctx.match->entries_length == i + 1) + { + /* Existing path ends in the middle of new path, extend it! */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Trying to extend existing path %s by additional links discovered from DHT\n", + GCPP_2s(cm_ctx.match)); + extend_path(cm_ctx.match, + &cpath[i + 1], + total_len - i - 1, + GNUNET_NO); + return; + } + } } - } /* No match at all, create completely new path */ - path = GNUNET_new (struct CadetPeerPath); + path = GNUNET_new(struct CadetPeerPath); path->entries_length = total_len; - path->entries = GNUNET_new_array (path->entries_length, - struct CadetPeerPathEntry *); - for (int i=path->entries_length-1;i>=0;i--) - { - struct CadetPeerPathEntry *entry = GNUNET_new (struct CadetPeerPathEntry); - - path->entries[i] = entry; - entry->peer = cpath[i]; - entry->path = path; - } - for (int i=path->entries_length-1;i>=0;i--) - { - struct CadetPeerPathEntry *entry = path->entries[i]; - - GCP_path_entry_add (entry->peer, - entry, - i); - } + path->entries = GNUNET_new_array(path->entries_length, + struct CadetPeerPathEntry *); + for (int i = path->entries_length - 1; i >= 0; i--) + { + struct CadetPeerPathEntry *entry = GNUNET_new(struct CadetPeerPathEntry); + + path->entries[i] = entry; + entry->peer = cpath[i]; + entry->path = path; + } + for (int i = path->entries_length - 1; i >= 0; i--) + { + struct CadetPeerPathEntry *entry = path->entries[i]; + + GCP_path_entry_add(entry->peer, + entry, + i); + } /* Finally, try to attach it */ - attach_path (path, 0); + attach_path(path, 0); if (NULL == path->hn) - { - /* None of the peers on the path care about it. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Path discovered from DHT is not interesting to us\n"); - GNUNET_assert (0 == path->entries_length); - GNUNET_assert (NULL == path->entries); - GNUNET_free (path); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Created new path %s based on information from DHT\n", - GCPP_2s (path)); + { + /* None of the peers on the path care about it. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Path discovered from DHT is not interesting to us\n"); + GNUNET_assert(0 == path->entries_length); + GNUNET_assert(NULL == path->entries); + GNUNET_free(path); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Created new path %s based on information from DHT\n", + GCPP_2s(path)); } @@ -605,8 +601,8 @@ GCPP_try_path_from_dht (const struct GNUNET_PeerIdentity *get_path, * @return corresponding path object */ struct CadetPeerPath * -GCPP_get_path_from_route (unsigned int path_length, - const struct GNUNET_PeerIdentity *pids) +GCPP_get_path_from_route(unsigned int path_length, + const struct GNUNET_PeerIdentity *pids) { struct CheckMatchContext cm_ctx; struct CadetPeer *cpath[path_length]; @@ -614,79 +610,79 @@ GCPP_get_path_from_route (unsigned int path_length, /* precompute inverted 'cpath' so we can avoid doing the lookups and have the correct order */ - for (unsigned int off=0;off=0;i--) - { - GCP_iterate_paths_at (cpath[i], - (unsigned int) i, - &check_match, - &cm_ctx); - if (NULL != cm_ctx.match) + for (int i = path_length - 1; i >= 0; i--) { - if (i == path_length - 1) - { - /* Existing path includes this one, return the match! */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Returning existing path %s as inverse for incoming connection\n", - GCPP_2s (cm_ctx.match)); - return cm_ctx.match; - } - if (cm_ctx.match->entries_length == i + 1) - { - /* Existing path ends in the middle of new path, extend it! */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Extending existing path %s to create inverse for incoming connection\n", - GCPP_2s (cm_ctx.match)); - extend_path (cm_ctx.match, - &cpath[i + 1], - path_length - i - 1, - GNUNET_YES); - /* Check that extension was successful */ - GNUNET_assert (cm_ctx.match->entries_length == path_length); - return cm_ctx.match; - } - /* Eh, we found a match but couldn't use it? Something is wrong. */ - GNUNET_break (0); + GCP_iterate_paths_at(cpath[i], + (unsigned int)i, + &check_match, + &cm_ctx); + if (NULL != cm_ctx.match) + { + if (i == path_length - 1) + { + /* Existing path includes this one, return the match! */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Returning existing path %s as inverse for incoming connection\n", + GCPP_2s(cm_ctx.match)); + return cm_ctx.match; + } + if (cm_ctx.match->entries_length == i + 1) + { + /* Existing path ends in the middle of new path, extend it! */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Extending existing path %s to create inverse for incoming connection\n", + GCPP_2s(cm_ctx.match)); + extend_path(cm_ctx.match, + &cpath[i + 1], + path_length - i - 1, + GNUNET_YES); + /* Check that extension was successful */ + GNUNET_assert(cm_ctx.match->entries_length == path_length); + return cm_ctx.match; + } + /* Eh, we found a match but couldn't use it? Something is wrong. */ + GNUNET_break(0); + } } - } /* No match at all, create completely new path */ - path = GNUNET_new (struct CadetPeerPath); + path = GNUNET_new(struct CadetPeerPath); path->entries_length = path_length; - path->entries = GNUNET_new_array (path->entries_length, - struct CadetPeerPathEntry *); - for (int i=path_length-1;i>=0;i--) - { - struct CadetPeerPathEntry *entry = GNUNET_new (struct CadetPeerPathEntry); - - path->entries[i] = entry; - entry->peer = cpath[i]; - entry->path = path; - } - for (int i=path_length-1;i>=0;i--) - { - struct CadetPeerPathEntry *entry = path->entries[i]; - - GCP_path_entry_add (entry->peer, - entry, - i); - } - recalculate_path_desirability (path); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Created new path %s to create inverse for incoming connection\n", - GCPP_2s (path)); - path->hn = GCP_attach_path (cpath[path_length - 1], - path, - path_length - 1, - GNUNET_YES); + path->entries = GNUNET_new_array(path->entries_length, + struct CadetPeerPathEntry *); + for (int i = path_length - 1; i >= 0; i--) + { + struct CadetPeerPathEntry *entry = GNUNET_new(struct CadetPeerPathEntry); + + path->entries[i] = entry; + entry->peer = cpath[i]; + entry->path = path; + } + for (int i = path_length - 1; i >= 0; i--) + { + struct CadetPeerPathEntry *entry = path->entries[i]; + + GCP_path_entry_add(entry->peer, + entry, + i); + } + recalculate_path_desirability(path); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Created new path %s to create inverse for incoming connection\n", + GCPP_2s(path)); + path->hn = GCP_attach_path(cpath[path_length - 1], + path, + path_length - 1, + GNUNET_YES); return path; } @@ -699,7 +695,7 @@ GCPP_get_path_from_route (unsigned int path_length, * @return number of peers on the path */ unsigned int -GCPP_get_length (struct CadetPeerPath *path) +GCPP_get_length(struct CadetPeerPath *path) { return path->entries_length; } @@ -713,14 +709,14 @@ GCPP_get_length (struct CadetPeerPath *path) * @return offset of @a cp on @a path, or UINT_MAX if not found */ unsigned int -GCPP_find_peer (struct CadetPeerPath *path, - struct CadetPeer *cp) +GCPP_find_peer(struct CadetPeerPath *path, + struct CadetPeer *cp) { for (unsigned int off = 0; off < path->entries_length; off++) - if (cp == GCPP_get_peer_at_offset (path, - off)) + if (cp == GCPP_get_peer_at_offset(path, + off)) return off; return UINT_MAX; } @@ -734,10 +730,10 @@ GCPP_find_peer (struct CadetPeerPath *path, * @return the peer at offset @a off */ struct CadetPeer * -GCPP_get_peer_at_offset (struct CadetPeerPath *path, - unsigned int off) +GCPP_get_peer_at_offset(struct CadetPeerPath *path, + unsigned int off) { - GNUNET_assert (off < path->entries_length); + GNUNET_assert(off < path->entries_length); return path->entries[off]->peer; } @@ -749,7 +745,7 @@ GCPP_get_peer_at_offset (struct CadetPeerPath *path, * @return string, to be freed by caller (unlike other *_2s APIs!) */ const char * -GCPP_2s (struct CadetPeerPath *path) +GCPP_2s(struct CadetPeerPath *path) { static char buf[2048]; size_t off; @@ -759,27 +755,27 @@ GCPP_2s (struct CadetPeerPath *path) for (unsigned int i = 0; i < path->entries_length; i++) - { - if ( (path->entries_length > max_plen) && - (i == max_plen / 2) ) - off += GNUNET_snprintf (&buf[off], - sizeof (buf) - off, - "...-"); - if ( (path->entries_length > max_plen) && - (i > max_plen / 2) && - (i < path->entries_length - max_plen / 2) ) - continue; - off += GNUNET_snprintf (&buf[off], - sizeof (buf) - off, - "%s%s", - GNUNET_i2s (GCP_get_id (GCPP_get_peer_at_offset (path, - i))), - (i == path->entries_length -1) ? "" : "-"); - } - GNUNET_snprintf (&buf[off], - sizeof (buf) - off, - "(%p)", - path); + { + if ((path->entries_length > max_plen) && + (i == max_plen / 2)) + off += GNUNET_snprintf(&buf[off], + sizeof(buf) - off, + "...-"); + if ((path->entries_length > max_plen) && + (i > max_plen / 2) && + (i < path->entries_length - max_plen / 2)) + continue; + off += GNUNET_snprintf(&buf[off], + sizeof(buf) - off, + "%s%s", + GNUNET_i2s(GCP_get_id(GCPP_get_peer_at_offset(path, + i))), + (i == path->entries_length - 1) ? "" : "-"); + } + GNUNET_snprintf(&buf[off], + sizeof(buf) - off, + "(%p)", + path); return buf; } diff --git a/src/cadet/gnunet-service-cadet_paths.h b/src/cadet/gnunet-service-cadet_paths.h index ca2c79ca4..399f91516 100644 --- a/src/cadet/gnunet-service-cadet_paths.h +++ b/src/cadet/gnunet-service-cadet_paths.h @@ -12,12 +12,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet-new_paths.h @@ -43,10 +43,10 @@ * @param put_path_length length of the @a put_path */ void -GCPP_try_path_from_dht (const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length); +GCPP_try_path_from_dht(const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length); /** @@ -57,8 +57,8 @@ GCPP_try_path_from_dht (const struct GNUNET_PeerIdentity *get_path, * @return corresponding path object */ struct CadetPeerPath * -GCPP_get_path_from_route (unsigned int path_length, - const struct GNUNET_PeerIdentity *pids); +GCPP_get_path_from_route(unsigned int path_length, + const struct GNUNET_PeerIdentity *pids); /** @@ -69,7 +69,7 @@ GCPP_get_path_from_route (unsigned int path_length, * @return number of peers on the path */ unsigned int -GCPP_get_length (struct CadetPeerPath *path); +GCPP_get_length(struct CadetPeerPath *path); /** @@ -83,9 +83,9 @@ GCPP_get_length (struct CadetPeerPath *path); * otherwise connection from us to @a destination via @a path */ struct CadetConnection * -GCPP_get_connection (struct CadetPeerPath *path, - struct CadetPeer *destination, - unsigned int off); +GCPP_get_connection(struct CadetPeerPath *path, + struct CadetPeer *destination, + unsigned int off); /** @@ -97,9 +97,9 @@ GCPP_get_connection (struct CadetPeerPath *path, * @param cc the connection to remember */ void -GCPP_add_connection (struct CadetPeerPath *path, - unsigned int off, - struct CadetConnection *cc); +GCPP_add_connection(struct CadetPeerPath *path, + unsigned int off, + struct CadetConnection *cc); /** @@ -111,9 +111,9 @@ GCPP_add_connection (struct CadetPeerPath *path, * @param cc the connection to forget */ void -GCPP_del_connection (struct CadetPeerPath *path, - unsigned int off, - struct CadetConnection *cc); +GCPP_del_connection(struct CadetPeerPath *path, + unsigned int off, + struct CadetConnection *cc); /** @@ -124,8 +124,8 @@ GCPP_del_connection (struct CadetPeerPath *path, * @return offset of @a cp on @a path, or UINT_MAX if not found */ unsigned int -GCPP_find_peer (struct CadetPeerPath *path, - struct CadetPeer *cp); +GCPP_find_peer(struct CadetPeerPath *path, + struct CadetPeer *cp); /** @@ -142,7 +142,7 @@ GCPP_find_peer (struct CadetPeerPath *path, * @return desirability of the path, larger is more desirable */ GNUNET_CONTAINER_HeapCostType -GCPP_get_desirability (const struct CadetPeerPath *path); +GCPP_get_desirability(const struct CadetPeerPath *path); /** @@ -154,7 +154,7 @@ GCPP_get_desirability (const struct CadetPeerPath *path); * @param path the path that is being released */ void -GCPP_release (struct CadetPeerPath *path); +GCPP_release(struct CadetPeerPath *path); /** @@ -165,8 +165,8 @@ GCPP_release (struct CadetPeerPath *path); * @return peer at offset @a off */ struct CadetPeer * -GCPP_get_peer_at_offset (struct CadetPeerPath *path, - unsigned int off); +GCPP_get_peer_at_offset(struct CadetPeerPath *path, + unsigned int off); /** @@ -176,7 +176,7 @@ GCPP_get_peer_at_offset (struct CadetPeerPath *path, * @return string, statically allocated */ const char * -GCPP_2s (struct CadetPeerPath *p); +GCPP_2s(struct CadetPeerPath *p); #endif diff --git a/src/cadet/gnunet-service-cadet_peer.c b/src/cadet/gnunet-service-cadet_peer.c index d6cc6f914..23eb6b225 100644 --- a/src/cadet/gnunet-service-cadet_peer.c +++ b/src/cadet/gnunet-service-cadet_peer.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_peer.c @@ -46,7 +46,7 @@ #include "gnunet-service-cadet_tunnels.h" -#define LOG(level, ...) GNUNET_log_from(level,"cadet-per",__VA_ARGS__) +#define LOG(level, ...) GNUNET_log_from(level, "cadet-per", __VA_ARGS__) /** @@ -69,9 +69,7 @@ * Data structure used to track whom we have to notify about changes * to our message queue. */ -struct GCP_MessageQueueManager -{ - +struct GCP_MessageQueueManager { /** * Kept in a DLL. */ @@ -101,15 +99,13 @@ struct GCP_MessageQueueManager * Envelope this manager would like to transmit once it is its turn. */ struct GNUNET_MQ_Envelope *env; - }; /** * Struct containing all information regarding a given peer */ -struct CadetPeer -{ +struct CadetPeer { /** * ID of the peer */ @@ -229,7 +225,6 @@ struct CadetPeer * The arrays should be grown as needed. */ unsigned int path_dll_length; - }; @@ -240,23 +235,23 @@ struct CadetPeer * @return Static string for it's ID. */ const char * -GCP_2s (const struct CadetPeer *cp) +GCP_2s(const struct CadetPeer *cp) { static char buf[5]; char *ret; if ((NULL == cp) || - (0 == GNUNET_is_zero (&cp->pid.public_key))) + (0 == GNUNET_is_zero(&cp->pid.public_key))) return "NULL"; - ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&cp->pid.public_key); + ret = GNUNET_CRYPTO_eddsa_public_key_to_string(&cp->pid.public_key); if (NULL == ret) return "NULL"; - GNUNET_strlcpy (buf, - ret, - sizeof (buf)); - GNUNET_free (ret); + GNUNET_strlcpy(buf, + ret, + sizeof(buf)); + GNUNET_free(ret); return buf; } @@ -277,8 +272,8 @@ GCP_2s (const struct CadetPeer *cp) * positive scores mean path is more desirable */ double -GCP_get_desirability_of_path (struct CadetPeer *cp, - unsigned int off) +GCP_get_desirability_of_path(struct CadetPeer *cp, + unsigned int off) { unsigned int num_alts = cp->num_paths; unsigned int off_sum; @@ -286,20 +281,20 @@ GCP_get_desirability_of_path (struct CadetPeer *cp, double path_delta; double weight_alts; - GNUNET_assert (num_alts >= 1); /* 'path' should be in there! */ - GNUNET_assert (0 != cp->path_dll_length); + GNUNET_assert(num_alts >= 1); /* 'path' should be in there! */ + GNUNET_assert(0 != cp->path_dll_length); /* We maintain 'off_sum' in 'peer' and thereby avoid the SLOW recalculation each time. Kept here just to document what is going on. */ #if SLOW off_sum = 0; - for (unsigned int j=0;jpath_dll_length;j++) + for (unsigned int j = 0; j < cp->path_dll_length; j++) for (struct CadetPeerPathEntry *pe = cp->path_heads[j]; NULL != pe; pe = pe->next) off_sum += j; - GNUNET_assert (off_sum == cp->off_sum); + GNUNET_assert(off_sum == cp->off_sum); #else off_sum = cp->off_sum; #endif @@ -307,8 +302,8 @@ GCP_get_desirability_of_path (struct CadetPeer *cp, path_delta = off - avg_sum; /* path_delta positiv: path off of peer above average (bad path for peer), path_delta negativ: path off of peer below average (good path for peer) */ - if (path_delta <= - 1.0) - weight_alts = - num_alts / path_delta; /* discount alternative paths */ + if (path_delta <= -1.0) + weight_alts = -num_alts / path_delta; /* discount alternative paths */ else if (path_delta >= 1.0) weight_alts = num_alts * path_delta; /* overcount alternative paths */ else @@ -328,63 +323,63 @@ GCP_get_desirability_of_path (struct CadetPeer *cp, * @param cls peer to clean up */ static void -destroy_peer (void *cls) +destroy_peer(void *cls) { struct CadetPeer *cp = cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Destroying state about peer %s\n", - GCP_2s (cp)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Destroying state about peer %s\n", + GCP_2s(cp)); cp->destroy_task = NULL; - GNUNET_assert (NULL == cp->t); - GNUNET_assert (NULL == cp->core_mq); - GNUNET_assert (0 == cp->num_paths); - for (unsigned int i=0;ipath_dll_length;i++) - GNUNET_assert (NULL == cp->path_heads[i]); - GNUNET_assert (0 == GNUNET_CONTAINER_multishortmap_size (cp->connections)); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (peers, - &cp->pid, - cp)); - GNUNET_free_non_null (cp->path_heads); - GNUNET_free_non_null (cp->path_tails); + GNUNET_assert(NULL == cp->t); + GNUNET_assert(NULL == cp->core_mq); + GNUNET_assert(0 == cp->num_paths); + for (unsigned int i = 0; i < cp->path_dll_length; i++) + GNUNET_assert(NULL == cp->path_heads[i]); + GNUNET_assert(0 == GNUNET_CONTAINER_multishortmap_size(cp->connections)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(peers, + &cp->pid, + cp)); + GNUNET_free_non_null(cp->path_heads); + GNUNET_free_non_null(cp->path_tails); cp->path_dll_length = 0; if (NULL != cp->search_h) - { - GCD_search_stop (cp->search_h); - cp->search_h = NULL; - } + { + GCD_search_stop(cp->search_h); + cp->search_h = NULL; + } /* FIXME: clean up search_delayedXXX! */ if (NULL != cp->hello_offer) - { - GNUNET_TRANSPORT_offer_hello_cancel (cp->hello_offer); - cp->hello_offer = NULL; - } + { + GNUNET_TRANSPORT_offer_hello_cancel(cp->hello_offer); + cp->hello_offer = NULL; + } if (NULL != cp->connectivity_suggestion) - { - GNUNET_ATS_connectivity_suggest_cancel (cp->connectivity_suggestion); - cp->connectivity_suggestion = NULL; - } - GNUNET_CONTAINER_multishortmap_destroy (cp->connections); + { + GNUNET_ATS_connectivity_suggest_cancel(cp->connectivity_suggestion); + cp->connectivity_suggestion = NULL; + } + GNUNET_CONTAINER_multishortmap_destroy(cp->connections); if (NULL != cp->path_heap) - { - GNUNET_CONTAINER_heap_destroy (cp->path_heap); - cp->path_heap = NULL; - } + { + GNUNET_CONTAINER_heap_destroy(cp->path_heap); + cp->path_heap = NULL; + } if (NULL != cp->heap_cleanup_task) - { - GNUNET_SCHEDULER_cancel (cp->heap_cleanup_task); - cp->heap_cleanup_task = NULL; - } - GNUNET_free_non_null (cp->hello); + { + GNUNET_SCHEDULER_cancel(cp->heap_cleanup_task); + cp->heap_cleanup_task = NULL; + } + GNUNET_free_non_null(cp->hello); /* Peer should not be freed if paths exist; if there are no paths, there ought to be no connections, and without connections, no notifications. Thus we can assert that mqm_head is empty at this point. */ - GNUNET_assert (NULL == cp->mqm_head); - GNUNET_assert (NULL == cp->mqm_ready_ptr); - GNUNET_free (cp); + GNUNET_assert(NULL == cp->mqm_head); + GNUNET_assert(NULL == cp->mqm_ready_ptr); + GNUNET_free(cp); } @@ -394,64 +389,64 @@ destroy_peer (void *cls) * @param cp the more-active peer */ static void -consider_peer_activate (struct CadetPeer *cp) +consider_peer_activate(struct CadetPeer *cp) { uint32_t strength; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Updating peer %s activation state (%u connections)%s%s\n", - GCP_2s (cp), - GNUNET_CONTAINER_multishortmap_size (cp->connections), - (NULL == cp->t) ? "" : " with tunnel", - (NULL == cp->core_mq) ? "" : " with CORE link"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Updating peer %s activation state (%u connections)%s%s\n", + GCP_2s(cp), + GNUNET_CONTAINER_multishortmap_size(cp->connections), + (NULL == cp->t) ? "" : " with tunnel", + (NULL == cp->core_mq) ? "" : " with CORE link"); if (NULL != cp->destroy_task) - { - /* It's active, do not destory! */ - GNUNET_SCHEDULER_cancel (cp->destroy_task); - cp->destroy_task = NULL; - } - if ( (0 == GNUNET_CONTAINER_multishortmap_size (cp->connections)) && - (NULL == cp->t) ) - { - /* We're just on a path or directly connected; don't bother too much */ - if (NULL != cp->connectivity_suggestion) { - GNUNET_ATS_connectivity_suggest_cancel (cp->connectivity_suggestion); - cp->connectivity_suggestion = NULL; + /* It's active, do not destory! */ + GNUNET_SCHEDULER_cancel(cp->destroy_task); + cp->destroy_task = NULL; } - if (NULL != cp->search_h) + if ((0 == GNUNET_CONTAINER_multishortmap_size(cp->connections)) && + (NULL == cp->t)) { - GCD_search_stop (cp->search_h); - cp->search_h = NULL; + /* We're just on a path or directly connected; don't bother too much */ + if (NULL != cp->connectivity_suggestion) + { + GNUNET_ATS_connectivity_suggest_cancel(cp->connectivity_suggestion); + cp->connectivity_suggestion = NULL; + } + if (NULL != cp->search_h) + { + GCD_search_stop(cp->search_h); + cp->search_h = NULL; + } + return; } - return; - } if (NULL == cp->core_mq) - { - /* Lacks direct connection, try to create one by querying the DHT */ - if ( (NULL == cp->search_h) && - (DESIRED_CONNECTIONS_PER_TUNNEL > cp->num_paths) ) - cp->search_h - = GCD_search (&cp->pid); - } + { + /* Lacks direct connection, try to create one by querying the DHT */ + if ((NULL == cp->search_h) && + (DESIRED_CONNECTIONS_PER_TUNNEL > cp->num_paths)) + cp->search_h + = GCD_search(&cp->pid); + } else - { - /* Have direct connection, stop DHT search if active */ - if (NULL != cp->search_h) { - GCD_search_stop (cp->search_h); - cp->search_h = NULL; + /* Have direct connection, stop DHT search if active */ + if (NULL != cp->search_h) + { + GCD_search_stop(cp->search_h); + cp->search_h = NULL; + } } - } /* If we have a tunnel, our urge for connections is much bigger */ strength = (NULL != cp->t) ? 32 : 1; if (NULL != cp->connectivity_suggestion) - GNUNET_ATS_connectivity_suggest_cancel (cp->connectivity_suggestion); + GNUNET_ATS_connectivity_suggest_cancel(cp->connectivity_suggestion); cp->connectivity_suggestion - = GNUNET_ATS_connectivity_suggest (ats_ch, - &cp->pid, - strength); + = GNUNET_ATS_connectivity_suggest(ats_ch, + &cp->pid, + strength); } @@ -461,7 +456,7 @@ consider_peer_activate (struct CadetPeer *cp) * @param cp peer to clean up */ static void -consider_peer_destroy (struct CadetPeer *cp); +consider_peer_destroy(struct CadetPeer *cp); /** @@ -471,15 +466,15 @@ consider_peer_destroy (struct CadetPeer *cp); * @param cls a `struct CadetPeer`. */ static void -drop_paths (void *cls) +drop_paths(void *cls) { struct CadetPeer *cp = cls; struct CadetPeerPath *path; cp->destroy_task = NULL; - while (NULL != (path = GNUNET_CONTAINER_heap_remove_root (cp->path_heap))) - GCPP_release (path); - consider_peer_destroy (cp); + while (NULL != (path = GNUNET_CONTAINER_heap_remove_root(cp->path_heap))) + GCPP_release(path); + consider_peer_destroy(cp); } @@ -489,43 +484,43 @@ drop_paths (void *cls) * @param cp peer to clean up */ static void -consider_peer_destroy (struct CadetPeer *cp) +consider_peer_destroy(struct CadetPeer *cp) { struct GNUNET_TIME_Relative exp; if (NULL != cp->destroy_task) - { - GNUNET_SCHEDULER_cancel (cp->destroy_task); - cp->destroy_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(cp->destroy_task); + cp->destroy_task = NULL; + } if (NULL != cp->t) return; /* still relevant! */ if (NULL != cp->core_mq) return; /* still relevant! */ - if (0 != GNUNET_CONTAINER_multishortmap_size (cp->connections)) + if (0 != GNUNET_CONTAINER_multishortmap_size(cp->connections)) return; /* still relevant! */ - if ( (NULL != cp->path_heap) && - (0 < GNUNET_CONTAINER_heap_get_size (cp->path_heap)) ) - { - cp->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_PATH_TIMEOUT, - &drop_paths, - cp); - return; - } + if ((NULL != cp->path_heap) && + (0 < GNUNET_CONTAINER_heap_get_size(cp->path_heap))) + { + cp->destroy_task = GNUNET_SCHEDULER_add_delayed(IDLE_PATH_TIMEOUT, + &drop_paths, + cp); + return; + } if (0 != cp->num_paths) return; /* still relevant! */ if (NULL != cp->hello) - { - /* relevant only until HELLO expires */ - exp = GNUNET_TIME_absolute_get_remaining (GNUNET_HELLO_get_last_expiration (cp->hello)); - cp->destroy_task = GNUNET_SCHEDULER_add_delayed (exp, - &destroy_peer, - cp); - return; - } - cp->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_PEER_TIMEOUT, - &destroy_peer, - cp); + { + /* relevant only until HELLO expires */ + exp = GNUNET_TIME_absolute_get_remaining(GNUNET_HELLO_get_last_expiration(cp->hello)); + cp->destroy_task = GNUNET_SCHEDULER_add_delayed(exp, + &destroy_peer, + cp); + return; + } + cp->destroy_task = GNUNET_SCHEDULER_add_delayed(IDLE_PEER_TIMEOUT, + &destroy_peer, + cp); } @@ -536,60 +531,60 @@ consider_peer_destroy (struct CadetPeer *cp) * @param mq message queue to set (can be NULL) */ void -GCP_set_mq (struct CadetPeer *cp, - struct GNUNET_MQ_Handle *mq) +GCP_set_mq(struct CadetPeer *cp, + struct GNUNET_MQ_Handle *mq) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Message queue for peer %s is now %p\n", - GCP_2s (cp), - mq); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Message queue for peer %s is now %p\n", + GCP_2s(cp), + mq); cp->core_mq = mq; for (struct GCP_MessageQueueManager *mqm = cp->mqm_head, *next; NULL != mqm; mqm = next) - { - /* Save next pointer in case mqm gets freed by the callback */ - next = mqm->next; - if (NULL == mq) { - if (NULL != mqm->env) - { - GNUNET_MQ_discard (mqm->env); - mqm->env = NULL; - mqm->cb (mqm->cb_cls, - GNUNET_SYSERR); - } + /* Save next pointer in case mqm gets freed by the callback */ + next = mqm->next; + if (NULL == mq) + { + if (NULL != mqm->env) + { + GNUNET_MQ_discard(mqm->env); + mqm->env = NULL; + mqm->cb(mqm->cb_cls, + GNUNET_SYSERR); + } + else + { + mqm->cb(mqm->cb_cls, + GNUNET_NO); + } + } else - { - mqm->cb (mqm->cb_cls, - GNUNET_NO); - } + { + GNUNET_assert(NULL == mqm->env); + mqm->cb(mqm->cb_cls, + GNUNET_YES); + } } - else + if ((NULL != mq) || + (NULL != cp->t)) + consider_peer_activate(cp); + else + consider_peer_destroy(cp); + + if ((NULL != mq) && + (NULL != cp->t)) { - GNUNET_assert (NULL == mqm->env); - mqm->cb (mqm->cb_cls, - GNUNET_YES); + /* have a new, direct path to the target, notify tunnel */ + struct CadetPeerPath *path; + + path = GCPP_get_path_from_route(1, + &cp->pid); + GCT_consider_path(cp->t, + path, + 0); } - } - if ( (NULL != mq) || - (NULL != cp->t) ) - consider_peer_activate (cp); - else - consider_peer_destroy (cp); - - if ( (NULL != mq) && - (NULL != cp->t) ) - { - /* have a new, direct path to the target, notify tunnel */ - struct CadetPeerPath *path; - - path = GCPP_get_path_from_route (1, - &cp->pid); - GCT_consider_path (cp->t, - path, - 0); - } } @@ -600,12 +595,12 @@ GCP_set_mq (struct CadetPeer *cp, * @return #GNUNET_YES or #GNUNET_NO with the decision to drop. */ static int -should_I_drop (void) +should_I_drop(void) { if (0 == drop_percent) return GNUNET_NO; - if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - 101) < drop_percent) + if (GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + 101) < drop_percent) return GNUNET_YES; return GNUNET_NO; } @@ -618,7 +613,7 @@ should_I_drop (void) * @param cls the `struct CadetPeeer` where we made progress */ static void -mqm_send_done (void *cls); +mqm_send_done(void *cls); /** @@ -627,68 +622,69 @@ mqm_send_done (void *cls); * @param mqm mqm to transmit message for now */ static void -mqm_execute (struct GCP_MessageQueueManager *mqm) +mqm_execute(struct GCP_MessageQueueManager *mqm) { struct CadetPeer *cp = mqm->cp; /* Move ready pointer to the next entry that might be ready. */ - if ( (mqm == cp->mqm_ready_ptr) && - (NULL != mqm->next) ) + if ((mqm == cp->mqm_ready_ptr) && + (NULL != mqm->next)) cp->mqm_ready_ptr = mqm->next; /* Move entry to the end of the DLL, to be fair. */ if (mqm != cp->mqm_tail) - { - GNUNET_CONTAINER_DLL_remove (cp->mqm_head, - cp->mqm_tail, - mqm); - GNUNET_CONTAINER_DLL_insert_tail (cp->mqm_head, - cp->mqm_tail, - mqm); - } + { + GNUNET_CONTAINER_DLL_remove(cp->mqm_head, + cp->mqm_tail, + mqm); + GNUNET_CONTAINER_DLL_insert_tail(cp->mqm_head, + cp->mqm_tail, + mqm); + } cp->mqm_ready_counter--; - if (GNUNET_YES == should_I_drop ()) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "DROPPING message to peer %s from MQM %p\n", - GCP_2s (cp), - mqm); - GNUNET_MQ_discard (mqm->env); - mqm->env = NULL; - mqm_send_done (cp); - } + if (GNUNET_YES == should_I_drop()) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "DROPPING message to peer %s from MQM %p\n", + GCP_2s(cp), + mqm); + GNUNET_MQ_discard(mqm->env); + mqm->env = NULL; + mqm_send_done(cp); + } else - { { - const struct GNUNET_MessageHeader *mh; - - mh = GNUNET_MQ_env_get_msg (mqm->env); - switch (ntohs (mh->type)) { - case GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX: - { - const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg - = (const struct GNUNET_CADET_TunnelKeyExchangeMessage *) mh; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "P2P forwarding KX with ephemeral %s to %s on CID %s\n", - GNUNET_e2s (&msg->ephemeral_key), - GCP_2s (cp), - GNUNET_sh2s (&msg->cid.connection_of_tunnel)); - } - break; - default: - break; + const struct GNUNET_MessageHeader *mh; + + mh = GNUNET_MQ_env_get_msg(mqm->env); + switch (ntohs(mh->type)) + { + case GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX: + { + const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg + = (const struct GNUNET_CADET_TunnelKeyExchangeMessage *)mh; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "P2P forwarding KX with ephemeral %s to %s on CID %s\n", + GNUNET_e2s(&msg->ephemeral_key), + GCP_2s(cp), + GNUNET_sh2s(&msg->cid.connection_of_tunnel)); + } + break; + + default: + break; + } } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending to peer %s from MQM %p\n", + GCP_2s(cp), + mqm); + GNUNET_MQ_send(cp->core_mq, + mqm->env); + mqm->env = NULL; } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending to peer %s from MQM %p\n", - GCP_2s (cp), - mqm); - GNUNET_MQ_send (cp->core_mq, - mqm->env); - mqm->env = NULL; - } - mqm->cb (mqm->cb_cls, - GNUNET_YES); + mqm->cb(mqm->cb_cls, + GNUNET_YES); } @@ -700,18 +696,18 @@ mqm_execute (struct GCP_MessageQueueManager *mqm) * @param cp peer to try to send the next ready message to */ static void -send_next_ready (struct CadetPeer *cp) +send_next_ready(struct CadetPeer *cp) { struct GCP_MessageQueueManager *mqm; if (0 == cp->mqm_ready_counter) return; - while ( (NULL != (mqm = cp->mqm_ready_ptr)) && - (NULL == mqm->env) ) + while ((NULL != (mqm = cp->mqm_ready_ptr)) && + (NULL == mqm->env)) cp->mqm_ready_ptr = mqm->next; if (NULL == mqm) return; /* nothing to do */ - mqm_execute (mqm); + mqm_execute(mqm); } @@ -722,14 +718,14 @@ send_next_ready (struct CadetPeer *cp) * @param cls the `struct CadetPeeer` where we made progress */ static void -mqm_send_done (void *cls) +mqm_send_done(void *cls) { struct CadetPeer *cp = cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending to peer %s completed\n", - GCP_2s (cp)); - send_next_ready (cp); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending to peer %s completed\n", + GCP_2s(cp)); + send_next_ready(cp); } @@ -741,30 +737,30 @@ mqm_send_done (void *cls) * yet have a #GNUNET_MQ_notify_sent() callback attached to it */ void -GCP_send (struct GCP_MessageQueueManager *mqm, - struct GNUNET_MQ_Envelope *env) +GCP_send(struct GCP_MessageQueueManager *mqm, + struct GNUNET_MQ_Envelope *env) { struct CadetPeer *cp = mqm->cp; - GNUNET_assert (NULL != env); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Queueing message to peer %s in MQM %p\n", - GCP_2s (cp), - mqm); - GNUNET_assert (NULL != cp->core_mq); - GNUNET_assert (NULL == mqm->env); - GNUNET_MQ_notify_sent (env, - &mqm_send_done, - cp); + GNUNET_assert(NULL != env); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Queueing message to peer %s in MQM %p\n", + GCP_2s(cp), + mqm); + GNUNET_assert(NULL != cp->core_mq); + GNUNET_assert(NULL == mqm->env); + GNUNET_MQ_notify_sent(env, + &mqm_send_done, + cp); mqm->env = env; cp->mqm_ready_counter++; if (mqm != cp->mqm_ready_ptr) cp->mqm_ready_ptr = cp->mqm_head; if (1 == cp->mqm_ready_counter) cp->mqm_ready_ptr = mqm; - if (0 != GNUNET_MQ_get_length (cp->core_mq)) + if (0 != GNUNET_MQ_get_length(cp->core_mq)) return; - send_next_ready (cp); + send_next_ready(cp); } @@ -777,18 +773,18 @@ GCP_send (struct GCP_MessageQueueManager *mqm, * @return #GNUNET_OK (continue to iterate) */ static int -destroy_iterator_cb (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *value) +destroy_iterator_cb(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *value) { struct CadetPeer *cp = value; if (NULL != cp->destroy_task) - { - GNUNET_SCHEDULER_cancel (cp->destroy_task); - cp->destroy_task = NULL; - } - destroy_peer (cp); + { + GNUNET_SCHEDULER_cancel(cp->destroy_task); + cp->destroy_task = NULL; + } + destroy_peer(cp); return GNUNET_OK; } @@ -799,13 +795,13 @@ destroy_iterator_cb (void *cls, * connections are down. */ void -GCP_destroy_all_peers () +GCP_destroy_all_peers() { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Destroying all peers now\n"); - GNUNET_CONTAINER_multipeermap_iterate (peers, - &destroy_iterator_cb, - NULL); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Destroying all peers now\n"); + GNUNET_CONTAINER_multipeermap_iterate(peers, + &destroy_iterator_cb, + NULL); } @@ -816,17 +812,17 @@ GCP_destroy_all_peers () * @param cp peer to drop paths to */ void -GCP_drop_owned_paths (struct CadetPeer *cp) +GCP_drop_owned_paths(struct CadetPeer *cp) { struct CadetPeerPath *path; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Destroying all paths to %s\n", - GCP_2s (cp)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Destroying all paths to %s\n", + GCP_2s(cp)); while (NULL != (path = - GNUNET_CONTAINER_heap_remove_root (cp->path_heap))) - GCPP_release (path); - GNUNET_CONTAINER_heap_destroy (cp->path_heap); + GNUNET_CONTAINER_heap_remove_root(cp->path_heap))) + GCPP_release(path); + GNUNET_CONTAINER_heap_destroy(cp->path_heap); cp->path_heap = NULL; } @@ -839,55 +835,55 @@ GCP_drop_owned_paths (struct CadetPeer *cp) * @param off offset of this peer on the path */ void -GCP_path_entry_add (struct CadetPeer *cp, - struct CadetPeerPathEntry *entry, - unsigned int off) +GCP_path_entry_add(struct CadetPeer *cp, + struct CadetPeerPathEntry *entry, + unsigned int off) { - GNUNET_assert (cp == GCPP_get_peer_at_offset (entry->path, - off)); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Discovered that peer %s is on path %s at offset %u\n", - GCP_2s (cp), - GCPP_2s (entry->path), - off); + GNUNET_assert(cp == GCPP_get_peer_at_offset(entry->path, + off)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Discovered that peer %s is on path %s at offset %u\n", + GCP_2s(cp), + GCPP_2s(entry->path), + off); if (off >= cp->path_dll_length) - { - unsigned int len = cp->path_dll_length; - - GNUNET_array_grow (cp->path_heads, - len, - off + 4); - GNUNET_array_grow (cp->path_tails, - cp->path_dll_length, - off + 4); - } - GNUNET_CONTAINER_DLL_insert (cp->path_heads[off], - cp->path_tails[off], - entry); + { + unsigned int len = cp->path_dll_length; + + GNUNET_array_grow(cp->path_heads, + len, + off + 4); + GNUNET_array_grow(cp->path_tails, + cp->path_dll_length, + off + 4); + } + GNUNET_CONTAINER_DLL_insert(cp->path_heads[off], + cp->path_tails[off], + entry); cp->off_sum += off; cp->num_paths++; /* If we have a tunnel to this peer, tell the tunnel that there is a new path available. */ if (NULL != cp->t) - GCT_consider_path (cp->t, - entry->path, - off); - - if ( (NULL != cp->search_h) && - (DESIRED_CONNECTIONS_PER_TUNNEL <= cp->num_paths) ) - { - /* Now I have enough paths, stop search */ - GCD_search_stop (cp->search_h); - cp->search_h = NULL; - } + GCT_consider_path(cp->t, + entry->path, + off); + + if ((NULL != cp->search_h) && + (DESIRED_CONNECTIONS_PER_TUNNEL <= cp->num_paths)) + { + /* Now I have enough paths, stop search */ + GCD_search_stop(cp->search_h); + cp->search_h = NULL; + } if (NULL != cp->destroy_task) - { - /* paths changed, this resets the destroy timeout counter - and aborts a destroy task that may no longer be valid - to have (as we now have more paths via this peer). */ - consider_peer_destroy (cp); - } + { + /* paths changed, this resets the destroy timeout counter + and aborts a destroy task that may no longer be valid + to have (as we now have more paths via this peer). */ + consider_peer_destroy(cp); + } } @@ -899,32 +895,32 @@ GCP_path_entry_add (struct CadetPeer *cp, * @param off offset of this peer on the path */ void -GCP_path_entry_remove (struct CadetPeer *cp, - struct CadetPeerPathEntry *entry, - unsigned int off) +GCP_path_entry_remove(struct CadetPeer *cp, + struct CadetPeerPathEntry *entry, + unsigned int off) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Removing knowledge about peer %s beging on path %s at offset %u\n", - GCP_2s (cp), - GCPP_2s (entry->path), - off); - GNUNET_CONTAINER_DLL_remove (cp->path_heads[off], - cp->path_tails[off], - entry); - GNUNET_assert (0 < cp->num_paths); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Removing knowledge about peer %s beging on path %s at offset %u\n", + GCP_2s(cp), + GCPP_2s(entry->path), + off); + GNUNET_CONTAINER_DLL_remove(cp->path_heads[off], + cp->path_tails[off], + entry); + GNUNET_assert(0 < cp->num_paths); cp->off_sum -= off; cp->num_paths--; - if ( (NULL == cp->core_mq) && - (NULL != cp->t) && - (NULL == cp->search_h) && - (DESIRED_CONNECTIONS_PER_TUNNEL > cp->num_paths) ) + if ((NULL == cp->core_mq) && + (NULL != cp->t) && + (NULL == cp->search_h) && + (DESIRED_CONNECTIONS_PER_TUNNEL > cp->num_paths)) cp->search_h - = GCD_search (&cp->pid); + = GCD_search(&cp->pid); if (NULL == cp->destroy_task) - { - /* paths changed, we might now be ready for destruction, check again */ - consider_peer_destroy (cp); - } + { + /* paths changed, we might now be ready for destruction, check again */ + consider_peer_destroy(cp); + } } @@ -935,32 +931,32 @@ GCP_path_entry_remove (struct CadetPeer *cp, * @param cls the `struct CadetPeer` to maintain the path heap for */ static void -path_heap_cleanup (void *cls) +path_heap_cleanup(void *cls) { struct CadetPeer *cp = cls; struct CadetPeerPath *root; cp->heap_cleanup_task = NULL; - while (GNUNET_CONTAINER_heap_get_size (cp->path_heap) >= + while (GNUNET_CONTAINER_heap_get_size(cp->path_heap) >= 2 * DESIRED_CONNECTIONS_PER_TUNNEL) - { - /* Now we have way too many, drop least desirable UNLESS it is in use! - (Note that this intentionally keeps highly desireable, but currently - unused paths around in the hope that we might be able to switch, even - if the number of paths exceeds the threshold.) */ - root = GNUNET_CONTAINER_heap_peek (cp->path_heap); - GNUNET_assert (NULL != root); - if (NULL != - GCPP_get_connection (root, - cp, - GCPP_get_length (root) - 1)) - break; /* can't fix */ - /* Got plenty of paths to this destination, and this is a low-quality - one that we don't care about. Allow it to die. */ - GNUNET_assert (root == - GNUNET_CONTAINER_heap_remove_root (cp->path_heap)); - GCPP_release (root); - } + { + /* Now we have way too many, drop least desirable UNLESS it is in use! + (Note that this intentionally keeps highly desireable, but currently + unused paths around in the hope that we might be able to switch, even + if the number of paths exceeds the threshold.) */ + root = GNUNET_CONTAINER_heap_peek(cp->path_heap); + GNUNET_assert(NULL != root); + if (NULL != + GCPP_get_connection(root, + cp, + GCPP_get_length(root) - 1)) + break; /* can't fix */ + /* Got plenty of paths to this destination, and this is a low-quality + one that we don't care about. Allow it to die. */ + GNUNET_assert(root == + GNUNET_CONTAINER_heap_remove_root(cp->path_heap)); + GCPP_release(root); + } } @@ -976,66 +972,66 @@ path_heap_cleanup (void *cls) * otherwise the node in the peer's path heap for the @a path. */ struct GNUNET_CONTAINER_HeapNode * -GCP_attach_path (struct CadetPeer *cp, - struct CadetPeerPath *path, - unsigned int off, - int force) +GCP_attach_path(struct CadetPeer *cp, + struct CadetPeerPath *path, + unsigned int off, + int force) { GNUNET_CONTAINER_HeapCostType desirability; struct CadetPeerPath *root; GNUNET_CONTAINER_HeapCostType root_desirability; struct GNUNET_CONTAINER_HeapNode *hn; - GNUNET_assert (off == GCPP_get_length (path) - 1); - GNUNET_assert (cp == GCPP_get_peer_at_offset (path, - off)); + GNUNET_assert(off == GCPP_get_length(path) - 1); + GNUNET_assert(cp == GCPP_get_peer_at_offset(path, + off)); if (NULL == cp->path_heap) - { - /* #GCP_drop_owned_paths() was already called, we cannot take new ones! */ - GNUNET_assert (GNUNET_NO == force); - return NULL; - } - desirability = GCPP_get_desirability (path); - if (GNUNET_NO == force) - { - /* FIXME: desirability is not yet initialized; tricky! */ - if (GNUNET_NO == - GNUNET_CONTAINER_heap_peek2 (cp->path_heap, - (void **) &root, - &root_desirability)) { - root = NULL; - root_desirability = 0; + /* #GCP_drop_owned_paths() was already called, we cannot take new ones! */ + GNUNET_assert(GNUNET_NO == force); + return NULL; } - - if ( (DESIRED_CONNECTIONS_PER_TUNNEL > cp->num_paths) && - (desirability < root_desirability) ) + desirability = GCPP_get_desirability(path); + if (GNUNET_NO == force) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Decided to not attach path %s to peer %s due to undesirability\n", - GCPP_2s (path), - GCP_2s (cp)); - return NULL; + /* FIXME: desirability is not yet initialized; tricky! */ + if (GNUNET_NO == + GNUNET_CONTAINER_heap_peek2(cp->path_heap, + (void **)&root, + &root_desirability)) + { + root = NULL; + root_desirability = 0; + } + + if ((DESIRED_CONNECTIONS_PER_TUNNEL > cp->num_paths) && + (desirability < root_desirability)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Decided to not attach path %s to peer %s due to undesirability\n", + GCPP_2s(path), + GCP_2s(cp)); + return NULL; + } } - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Attaching path %s to peer %s (%s)\n", - GCPP_2s (path), - GCP_2s (cp), - (GNUNET_NO == force) ? "desirable" : "forced"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Attaching path %s to peer %s (%s)\n", + GCPP_2s(path), + GCP_2s(cp), + (GNUNET_NO == force) ? "desirable" : "forced"); /* Yes, we'd like to add this path, add to our heap */ - hn = GNUNET_CONTAINER_heap_insert (cp->path_heap, - path, - desirability); + hn = GNUNET_CONTAINER_heap_insert(cp->path_heap, + path, + desirability); /* Consider maybe dropping other paths because of the new one */ - if ( (GNUNET_CONTAINER_heap_get_size (cp->path_heap) >= - 2 * DESIRED_CONNECTIONS_PER_TUNNEL) && - (NULL != cp->heap_cleanup_task) ) - cp->heap_cleanup_task = GNUNET_SCHEDULER_add_now (&path_heap_cleanup, - cp); + if ((GNUNET_CONTAINER_heap_get_size(cp->path_heap) >= + 2 * DESIRED_CONNECTIONS_PER_TUNNEL) && + (NULL != cp->heap_cleanup_task)) + cp->heap_cleanup_task = GNUNET_SCHEDULER_add_now(&path_heap_cleanup, + cp); return hn; } @@ -1050,16 +1046,16 @@ GCP_attach_path (struct CadetPeer *cp, * @param hn note in @a cp's path heap that must be deleted */ void -GCP_detach_path (struct CadetPeer *cp, - struct CadetPeerPath *path, - struct GNUNET_CONTAINER_HeapNode *hn) +GCP_detach_path(struct CadetPeer *cp, + struct CadetPeerPath *path, + struct GNUNET_CONTAINER_HeapNode *hn) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Detatching path %s from peer %s\n", - GCPP_2s (path), - GCP_2s (cp)); - GNUNET_assert (path == - GNUNET_CONTAINER_heap_remove_node (hn)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Detatching path %s from peer %s\n", + GCPP_2s(path), + GCP_2s(cp)); + GNUNET_assert(path == + GNUNET_CONTAINER_heap_remove_node(hn)); } @@ -1070,23 +1066,23 @@ GCP_detach_path (struct CadetPeer *cp, * @param cc the connection to add */ void -GCP_add_connection (struct CadetPeer *cp, - struct CadetConnection *cc) +GCP_add_connection(struct CadetPeer *cp, + struct CadetConnection *cc) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Adding %s to peer %s\n", - GCC_2s (cc), - GCP_2s (cp)); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multishortmap_put (cp->connections, - &GCC_get_id (cc)->connection_of_tunnel, - cc, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Adding %s to peer %s\n", + GCC_2s(cc), + GCP_2s(cp)); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multishortmap_put(cp->connections, + &GCC_get_id(cc)->connection_of_tunnel, + cc, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); if (NULL != cp->destroy_task) - { - GNUNET_SCHEDULER_cancel (cp->destroy_task); - cp->destroy_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(cp->destroy_task); + cp->destroy_task = NULL; + } } @@ -1097,18 +1093,18 @@ GCP_add_connection (struct CadetPeer *cp, * @param cc the connection to remove */ void -GCP_remove_connection (struct CadetPeer *cp, - struct CadetConnection *cc) +GCP_remove_connection(struct CadetPeer *cp, + struct CadetConnection *cc) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Removing connection %s from peer %s\n", - GCC_2s (cc), - GCP_2s (cp)); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multishortmap_remove (cp->connections, - &GCC_get_id (cc)->connection_of_tunnel, - cc)); - consider_peer_destroy (cp); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Removing connection %s from peer %s\n", + GCC_2s(cc), + GCP_2s(cp)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multishortmap_remove(cp->connections, + &GCC_get_id(cc)->connection_of_tunnel, + cc)); + consider_peer_destroy(cp); } @@ -1124,30 +1120,30 @@ GCP_remove_connection (struct CadetPeer *cp, * NULL if unknown and not requested @a create */ struct CadetPeer * -GCP_get (const struct GNUNET_PeerIdentity *peer_id, - int create) +GCP_get(const struct GNUNET_PeerIdentity *peer_id, + int create) { struct CadetPeer *cp; - cp = GNUNET_CONTAINER_multipeermap_get (peers, - peer_id); + cp = GNUNET_CONTAINER_multipeermap_get(peers, + peer_id); if (NULL != cp) return cp; if (GNUNET_NO == create) return NULL; - cp = GNUNET_new (struct CadetPeer); + cp = GNUNET_new(struct CadetPeer); cp->pid = *peer_id; - cp->connections = GNUNET_CONTAINER_multishortmap_create (32, - GNUNET_YES); - cp->path_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_put (peers, - &cp->pid, - cp, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Creating peer %s\n", - GCP_2s (cp)); + cp->connections = GNUNET_CONTAINER_multishortmap_create(32, + GNUNET_YES); + cp->path_heap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_put(peers, + &cp->pid, + cp, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Creating peer %s\n", + GCP_2s(cp)); return cp; } @@ -1159,7 +1155,7 @@ GCP_get (const struct GNUNET_PeerIdentity *peer_id, * @return the peer identity */ const struct GNUNET_PeerIdentity * -GCP_get_id (struct CadetPeer *cp) +GCP_get_id(struct CadetPeer *cp) { return &cp->pid; } @@ -1172,12 +1168,12 @@ GCP_get_id (struct CadetPeer *cp) * @param cls Closure for @c iter. */ void -GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, - void *cls) +GCP_iterate_all(GNUNET_CONTAINER_PeerMapIterator iter, + void *cls) { - GNUNET_CONTAINER_multipeermap_iterate (peers, - iter, - cls); + GNUNET_CONTAINER_multipeermap_iterate(peers, + iter, + cls); } @@ -1188,7 +1184,7 @@ GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, * @return Number of known paths. */ unsigned int -GCP_count_paths (const struct CadetPeer *cp) +GCP_count_paths(const struct CadetPeer *cp) { return cp->num_paths; } @@ -1203,45 +1199,45 @@ GCP_count_paths (const struct CadetPeer *cp) * @return Number of iterated paths. */ unsigned int -GCP_iterate_paths (struct CadetPeer *cp, - GCP_PathIterator callback, - void *callback_cls) +GCP_iterate_paths(struct CadetPeer *cp, + GCP_PathIterator callback, + void *callback_cls) { unsigned int ret = 0; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Iterating over paths to peer %s%s\n", - GCP_2s (cp), - (NULL == cp->core_mq) ? "" : " including direct link"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Iterating over paths to peer %s%s\n", + GCP_2s(cp), + (NULL == cp->core_mq) ? "" : " including direct link"); if (NULL != cp->core_mq) - { - /* FIXME: this branch seems to duplicate the - i=0 case below (direct link). Leave out!??? -CG */ - struct CadetPeerPath *path; - - path = GCPP_get_path_from_route (1, - &cp->pid); - ret++; - if (GNUNET_NO == - callback (callback_cls, - path, - 0)) - return ret; - } - for (unsigned int i=0;ipath_dll_length;i++) - { - for (struct CadetPeerPathEntry *pe = cp->path_heads[i]; - NULL != pe; - pe = pe->next) { + /* FIXME: this branch seems to duplicate the + i=0 case below (direct link). Leave out!??? -CG */ + struct CadetPeerPath *path; + + path = GCPP_get_path_from_route(1, + &cp->pid); ret++; if (GNUNET_NO == - callback (callback_cls, - pe->path, - i)) + callback(callback_cls, + path, + 0)) return ret; } - } + for (unsigned int i = 0; i < cp->path_dll_length; i++) + { + for (struct CadetPeerPathEntry *pe = cp->path_heads[i]; + NULL != pe; + pe = pe->next) + { + ret++; + if (GNUNET_NO == + callback(callback_cls, + pe->path, + i)) + return ret; + } + } return ret; } @@ -1254,29 +1250,29 @@ GCP_iterate_paths (struct CadetPeer *cp, * @return Number of iterated paths. */ unsigned int -GCP_iterate_indirect_paths (struct CadetPeer *cp, - GCP_PathIterator callback, - void *callback_cls) +GCP_iterate_indirect_paths(struct CadetPeer *cp, + GCP_PathIterator callback, + void *callback_cls) { unsigned int ret = 0; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Iterating over paths to peer %s without direct link\n", - GCP_2s (cp)); - for (unsigned int i=1;ipath_dll_length;i++) - { - for (struct CadetPeerPathEntry *pe = cp->path_heads[i]; - NULL != pe; - pe = pe->next) + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Iterating over paths to peer %s without direct link\n", + GCP_2s(cp)); + for (unsigned int i = 1; i < cp->path_dll_length; i++) { - ret++; - if (GNUNET_NO == - callback (callback_cls, - pe->path, - i)) - return ret; + for (struct CadetPeerPathEntry *pe = cp->path_heads[i]; + NULL != pe; + pe = pe->next) + { + ret++; + if (GNUNET_NO == + callback(callback_cls, + pe->path, + i)) + return ret; + } } - } return ret; } @@ -1292,32 +1288,32 @@ GCP_iterate_indirect_paths (struct CadetPeer *cp, * @return Number of iterated paths. */ unsigned int -GCP_iterate_paths_at (struct CadetPeer *cp, - unsigned int dist, - GCP_PathIterator callback, - void *callback_cls) +GCP_iterate_paths_at(struct CadetPeer *cp, + unsigned int dist, + GCP_PathIterator callback, + void *callback_cls) { unsigned int ret = 0; if (dist >= cp->path_dll_length) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Asked to look for paths at distance %u, but maximum for me is < %u\n", - dist, - cp->path_dll_length); - return 0; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Asked to look for paths at distance %u, but maximum for me is < %u\n", + dist, + cp->path_dll_length); + return 0; + } for (struct CadetPeerPathEntry *pe = cp->path_heads[dist]; NULL != pe; pe = pe->next) - { - if (GNUNET_NO == - callback (callback_cls, - pe->path, - dist)) - return ret; - ret++; - } + { + if (GNUNET_NO == + callback(callback_cls, + pe->path, + dist)) + return ret; + ret++; + } return ret; } @@ -1330,16 +1326,16 @@ GCP_iterate_paths_at (struct CadetPeer *cp, * @return Tunnel towards peer. */ struct CadetTunnel * -GCP_get_tunnel (struct CadetPeer *cp, - int create) +GCP_get_tunnel(struct CadetPeer *cp, + int create) { if (NULL == cp) return NULL; - if ( (NULL != cp->t) || - (GNUNET_NO == create) ) + if ((NULL != cp->t) || + (GNUNET_NO == create)) return cp->t; - cp->t = GCT_create_tunnel (cp); - consider_peer_activate (cp); + cp->t = GCT_create_tunnel(cp); + consider_peer_activate(cp); return cp->t; } @@ -1351,7 +1347,7 @@ GCP_get_tunnel (struct CadetPeer *cp, * @param cls the `struct CadetPeer` where the offer completed */ static void -hello_offer_done (void *cls) +hello_offer_done(void *cls) { struct CadetPeer *cp = cls; @@ -1367,39 +1363,39 @@ hello_offer_done (void *cls) * @param hello the HELLO to remember */ void -GCP_set_hello (struct CadetPeer *cp, - const struct GNUNET_HELLO_Message *hello) +GCP_set_hello(struct CadetPeer *cp, + const struct GNUNET_HELLO_Message *hello) { struct GNUNET_HELLO_Message *mrg; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got %u byte HELLO for peer %s\n", - (unsigned int) GNUNET_HELLO_size (hello), - GCP_2s (cp)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got %u byte HELLO for peer %s\n", + (unsigned int)GNUNET_HELLO_size(hello), + GCP_2s(cp)); if (NULL != cp->hello_offer) - { - GNUNET_TRANSPORT_offer_hello_cancel (cp->hello_offer); - cp->hello_offer = NULL; - } + { + GNUNET_TRANSPORT_offer_hello_cancel(cp->hello_offer); + cp->hello_offer = NULL; + } if (NULL != cp->hello) - { - mrg = GNUNET_HELLO_merge (hello, - cp->hello); - GNUNET_free (cp->hello); - cp->hello = mrg; - } + { + mrg = GNUNET_HELLO_merge(hello, + cp->hello); + GNUNET_free(cp->hello); + cp->hello = mrg; + } else - { - cp->hello = GNUNET_memdup (hello, - GNUNET_HELLO_size (hello)); - } + { + cp->hello = GNUNET_memdup(hello, + GNUNET_HELLO_size(hello)); + } cp->hello_offer - = GNUNET_TRANSPORT_offer_hello (cfg, - GNUNET_HELLO_get_header (cp->hello) , - &hello_offer_done, - cp); + = GNUNET_TRANSPORT_offer_hello(cfg, + GNUNET_HELLO_get_header(cp->hello), + &hello_offer_done, + cp); /* New HELLO means cp's destruction time may change... */ - consider_peer_destroy (cp); + consider_peer_destroy(cp); } @@ -1411,16 +1407,16 @@ GCP_set_hello (struct CadetPeer *cp, * @param t the dead tunnel */ void -GCP_drop_tunnel (struct CadetPeer *cp, - struct CadetTunnel *t) +GCP_drop_tunnel(struct CadetPeer *cp, + struct CadetTunnel *t) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Dropping tunnel %s to peer %s\n", - GCT_2s (t), - GCP_2s (cp)); - GNUNET_assert (cp->t == t); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Dropping tunnel %s to peer %s\n", + GCT_2s(t), + GCP_2s(cp)); + GNUNET_assert(cp->t == t); cp->t = NULL; - consider_peer_destroy (cp); + consider_peer_destroy(cp); } @@ -1431,7 +1427,7 @@ GCP_drop_tunnel (struct CadetPeer *cp, * @return #GNUNET_YES if @a cp has a core-level connection */ int -GCP_has_core_connection (struct CadetPeer *cp) +GCP_has_core_connection(struct CadetPeer *cp) { return (NULL != cp->core_mq) ? GNUNET_YES : GNUNET_NO; } @@ -1446,26 +1442,26 @@ GCP_has_core_connection (struct CadetPeer *cp) * @return handle to cancel request */ struct GCP_MessageQueueManager * -GCP_request_mq (struct CadetPeer *cp, - GCP_MessageQueueNotificationCallback cb, - void *cb_cls) +GCP_request_mq(struct CadetPeer *cp, + GCP_MessageQueueNotificationCallback cb, + void *cb_cls) { struct GCP_MessageQueueManager *mqm; - mqm = GNUNET_new (struct GCP_MessageQueueManager); + mqm = GNUNET_new(struct GCP_MessageQueueManager); mqm->cb = cb; mqm->cb_cls = cb_cls; mqm->cp = cp; - GNUNET_CONTAINER_DLL_insert (cp->mqm_head, - cp->mqm_tail, - mqm); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Creating MQM %p for peer %s\n", - mqm, - GCP_2s (cp)); + GNUNET_CONTAINER_DLL_insert(cp->mqm_head, + cp->mqm_tail, + mqm); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Creating MQM %p for peer %s\n", + mqm, + GCP_2s(cp)); if (NULL != cp->core_mq) - cb (cb_cls, - GNUNET_YES); + cb(cb_cls, + GNUNET_YES); return mqm; } @@ -1477,39 +1473,39 @@ GCP_request_mq (struct CadetPeer *cp, * @param last_env final message to transmit, or NULL */ void -GCP_request_mq_cancel (struct GCP_MessageQueueManager *mqm, - struct GNUNET_MQ_Envelope *last_env) +GCP_request_mq_cancel(struct GCP_MessageQueueManager *mqm, + struct GNUNET_MQ_Envelope *last_env) { struct CadetPeer *cp = mqm->cp; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Destroying MQM %p for peer %s%s\n", - mqm, - GCP_2s (cp), - (NULL == last_env) ? "" : " with last ditch transmission"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Destroying MQM %p for peer %s%s\n", + mqm, + GCP_2s(cp), + (NULL == last_env) ? "" : " with last ditch transmission"); if (NULL != mqm->env) - GNUNET_MQ_discard (mqm->env); + GNUNET_MQ_discard(mqm->env); if (NULL != last_env) - { - if (NULL != cp->core_mq) - { - GNUNET_MQ_notify_sent (last_env, - &mqm_send_done, - cp); - GNUNET_MQ_send (cp->core_mq, - last_env); - } - else { - GNUNET_MQ_discard (last_env); + if (NULL != cp->core_mq) + { + GNUNET_MQ_notify_sent(last_env, + &mqm_send_done, + cp); + GNUNET_MQ_send(cp->core_mq, + last_env); + } + else + { + GNUNET_MQ_discard(last_env); + } } - } if (cp->mqm_ready_ptr == mqm) cp->mqm_ready_ptr = mqm->next; - GNUNET_CONTAINER_DLL_remove (cp->mqm_head, - cp->mqm_tail, - mqm); - GNUNET_free (mqm); + GNUNET_CONTAINER_DLL_remove(cp->mqm_head, + cp->mqm_tail, + mqm); + GNUNET_free(mqm); } @@ -1523,27 +1519,27 @@ GCP_request_mq_cancel (struct GCP_MessageQueueManager *mqm, * @param env envelope with the message to send */ void -GCP_send_ooo (struct CadetPeer *cp, - struct GNUNET_MQ_Envelope *env) +GCP_send_ooo(struct CadetPeer *cp, + struct GNUNET_MQ_Envelope *env) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending message to %s out of management\n", - GCP_2s (cp)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending message to %s out of management\n", + GCP_2s(cp)); if (NULL == cp->core_mq) - { - GNUNET_MQ_discard (env); - return; - } - if (GNUNET_MQ_get_length (cp->core_mq) > MAX_OOO_QUEUE_SIZE) - { - GNUNET_MQ_discard (env); - return; - } - GNUNET_MQ_notify_sent (env, - &mqm_send_done, - cp); - GNUNET_MQ_send (cp->core_mq, - env); + { + GNUNET_MQ_discard(env); + return; + } + if (GNUNET_MQ_get_length(cp->core_mq) > MAX_OOO_QUEUE_SIZE) + { + GNUNET_MQ_discard(env); + return; + } + GNUNET_MQ_notify_sent(env, + &mqm_send_done, + cp); + GNUNET_MQ_send(cp->core_mq, + env); } diff --git a/src/cadet/gnunet-service-cadet_peer.h b/src/cadet/gnunet-service-cadet_peer.h index 4eee7e9e8..09c6f64c9 100644 --- a/src/cadet/gnunet-service-cadet_peer.h +++ b/src/cadet/gnunet-service-cadet_peer.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_peer.h @@ -39,7 +39,7 @@ * @return Static string for it's ID. */ const char * -GCP_2s (const struct CadetPeer *peer); +GCP_2s(const struct CadetPeer *peer); /** @@ -54,8 +54,8 @@ GCP_2s (const struct CadetPeer *peer); * NULL if unknown and not requested @a create */ struct CadetPeer * -GCP_get (const struct GNUNET_PeerIdentity *peer_id, - int create); +GCP_get(const struct GNUNET_PeerIdentity *peer_id, + int create); /** @@ -68,8 +68,8 @@ GCP_get (const struct GNUNET_PeerIdentity *peer_id, * positive scores mean path is more desirable */ double -GCP_get_desirability_of_path (struct CadetPeer *cp, - unsigned int off); +GCP_get_desirability_of_path(struct CadetPeer *cp, + unsigned int off); /** @@ -79,7 +79,7 @@ GCP_get_desirability_of_path (struct CadetPeer *cp, * @return the peer identity */ const struct GNUNET_PeerIdentity * -GCP_get_id (struct CadetPeer *cp); +GCP_get_id(struct CadetPeer *cp); /** @@ -89,8 +89,8 @@ GCP_get_id (struct CadetPeer *cp); * @param cls Closure for @c iter. */ void -GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, - void *cls); +GCP_iterate_all(GNUNET_CONTAINER_PeerMapIterator iter, + void *cls); /** @@ -100,7 +100,7 @@ GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, * @return Number of known paths. */ unsigned int -GCP_count_paths (const struct CadetPeer *cp); +GCP_count_paths(const struct CadetPeer *cp); /** @@ -110,7 +110,7 @@ GCP_count_paths (const struct CadetPeer *cp); * @param cp peer to drop paths to */ void -GCP_drop_owned_paths (struct CadetPeer *cp); +GCP_drop_owned_paths(struct CadetPeer *cp); /** @@ -137,9 +137,9 @@ typedef int * @return Number of iterated paths. */ unsigned int -GCP_iterate_paths (struct CadetPeer *cp, - GCP_PathIterator callback, - void *callback_cls); +GCP_iterate_paths(struct CadetPeer *cp, + GCP_PathIterator callback, + void *callback_cls); /** * Iterate over the paths to a peer without direct link. @@ -150,9 +150,9 @@ GCP_iterate_paths (struct CadetPeer *cp, * @return Number of iterated paths. */ unsigned int -GCP_iterate_indirect_paths (struct CadetPeer *cp, - GCP_PathIterator callback, - void *callback_cls); +GCP_iterate_indirect_paths(struct CadetPeer *cp, + GCP_PathIterator callback, + void *callback_cls); /** @@ -166,10 +166,10 @@ GCP_iterate_indirect_paths (struct CadetPeer *cp, * @return Number of iterated paths. */ unsigned int -GCP_iterate_paths_at (struct CadetPeer *cp, - unsigned int dist, - GCP_PathIterator callback, - void *callback_cls); +GCP_iterate_paths_at(struct CadetPeer *cp, + unsigned int dist, + GCP_PathIterator callback, + void *callback_cls); /** @@ -180,9 +180,9 @@ GCP_iterate_paths_at (struct CadetPeer *cp, * @param off offset of this peer on the path */ void -GCP_path_entry_remove (struct CadetPeer *cp, - struct CadetPeerPathEntry *entry, - unsigned int off); +GCP_path_entry_remove(struct CadetPeer *cp, + struct CadetPeerPathEntry *entry, + unsigned int off); /** @@ -193,9 +193,9 @@ GCP_path_entry_remove (struct CadetPeer *cp, * @param off offset of this peer on the path */ void -GCP_path_entry_add (struct CadetPeer *cp, - struct CadetPeerPathEntry *entry, - unsigned int off); +GCP_path_entry_add(struct CadetPeer *cp, + struct CadetPeerPathEntry *entry, + unsigned int off); /** @@ -206,8 +206,8 @@ GCP_path_entry_add (struct CadetPeer *cp, * @return Tunnel towards peer. */ struct CadetTunnel * -GCP_get_tunnel (struct CadetPeer *cp, - int create); +GCP_get_tunnel(struct CadetPeer *cp, + int create); /** @@ -218,8 +218,8 @@ GCP_get_tunnel (struct CadetPeer *cp, * @param t the dead tunnel */ void -GCP_drop_tunnel (struct CadetPeer *cp, - struct CadetTunnel *t); +GCP_drop_tunnel(struct CadetPeer *cp, + struct CadetTunnel *t); /** @@ -234,10 +234,10 @@ GCP_drop_tunnel (struct CadetPeer *cp, * otherwise the node in the peer's path heap for the @a path. */ struct GNUNET_CONTAINER_HeapNode * -GCP_attach_path (struct CadetPeer *cp, - struct CadetPeerPath *path, - unsigned int off, - int force); +GCP_attach_path(struct CadetPeer *cp, + struct CadetPeerPath *path, + unsigned int off, + int force); /** @@ -250,9 +250,9 @@ GCP_attach_path (struct CadetPeer *cp, * @param hn note in @a cp's path heap that must be deleted */ void -GCP_detach_path (struct CadetPeer *cp, - struct CadetPeerPath *path, - struct GNUNET_CONTAINER_HeapNode *hn); +GCP_detach_path(struct CadetPeer *cp, + struct CadetPeerPath *path, + struct GNUNET_CONTAINER_HeapNode *hn); /** @@ -262,8 +262,8 @@ GCP_detach_path (struct CadetPeer *cp, * @param cc the connection to add */ void -GCP_add_connection (struct CadetPeer *cp, - struct CadetConnection *cc); +GCP_add_connection(struct CadetPeer *cp, + struct CadetConnection *cc); /** @@ -273,8 +273,8 @@ GCP_add_connection (struct CadetPeer *cp, * @param cc the connection to remove */ void -GCP_remove_connection (struct CadetPeer *cp, - struct CadetConnection *cc); +GCP_remove_connection(struct CadetPeer *cp, + struct CadetConnection *cc); /** @@ -285,8 +285,8 @@ GCP_remove_connection (struct CadetPeer *cp, * @param hello the HELLO to remember */ void -GCP_set_hello (struct CadetPeer *cp, - const struct GNUNET_HELLO_Message *hello); +GCP_set_hello(struct CadetPeer *cp, + const struct GNUNET_HELLO_Message *hello); /** @@ -295,7 +295,7 @@ GCP_set_hello (struct CadetPeer *cp, * connections are down. */ void -GCP_destroy_all_peers (void); +GCP_destroy_all_peers(void); /** @@ -334,9 +334,9 @@ typedef void * @return handle to cancel request */ struct GCP_MessageQueueManager * -GCP_request_mq (struct CadetPeer *cp, - GCP_MessageQueueNotificationCallback cb, - void *cb_cls); +GCP_request_mq(struct CadetPeer *cp, + GCP_MessageQueueNotificationCallback cb, + void *cb_cls); /** @@ -346,7 +346,7 @@ GCP_request_mq (struct CadetPeer *cp, * @return #GNUNET_YES if @a cp has a core-level connection */ int -GCP_has_core_connection (struct CadetPeer *cp); +GCP_has_core_connection(struct CadetPeer *cp); /** @@ -361,8 +361,8 @@ GCP_has_core_connection (struct CadetPeer *cp); * yet have a #GNUNET_MQ_notify_sent() callback attached to it */ void -GCP_send (struct GCP_MessageQueueManager *mqm, - struct GNUNET_MQ_Envelope *env); +GCP_send(struct GCP_MessageQueueManager *mqm, + struct GNUNET_MQ_Envelope *env); /** @@ -375,8 +375,8 @@ GCP_send (struct GCP_MessageQueueManager *mqm, * @param env envelope with the message to send */ void -GCP_send_ooo (struct CadetPeer *cp, - struct GNUNET_MQ_Envelope *env); +GCP_send_ooo(struct CadetPeer *cp, + struct GNUNET_MQ_Envelope *env); /** @@ -388,8 +388,8 @@ GCP_send_ooo (struct CadetPeer *cp, * @param last_env final message to transmit, or NULL */ void -GCP_request_mq_cancel (struct GCP_MessageQueueManager *mqm, - struct GNUNET_MQ_Envelope *last_env); +GCP_request_mq_cancel(struct GCP_MessageQueueManager *mqm, + struct GNUNET_MQ_Envelope *last_env); /** @@ -399,8 +399,8 @@ GCP_request_mq_cancel (struct GCP_MessageQueueManager *mqm, * @param mq message queue to set (can be NULL) */ void -GCP_set_mq (struct CadetPeer *cp, - struct GNUNET_MQ_Handle *mq); +GCP_set_mq(struct CadetPeer *cp, + struct GNUNET_MQ_Handle *mq); #endif diff --git a/src/cadet/gnunet-service-cadet_tunnels.c b/src/cadet/gnunet-service-cadet_tunnels.c index 11be2bce0..c73f8cdbe 100644 --- a/src/cadet/gnunet-service-cadet_tunnels.c +++ b/src/cadet/gnunet-service-cadet_tunnels.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_tunnels.c * @brief Information we track per tunnel. @@ -42,7 +42,7 @@ #include "gnunet-service-cadet_paths.h" -#define LOG(level, ...) GNUNET_log_from(level,"cadet-tun",__VA_ARGS__) +#define LOG(level, ...) GNUNET_log_from(level, "cadet-tun", __VA_ARGS__) /** * How often do we try to decrypt payload with unverified key @@ -77,8 +77,7 @@ /** * Struct to old keys for skipped messages while advancing the Axolotl ratchet. */ -struct CadetTunnelSkippedKey -{ +struct CadetTunnelSkippedKey { /** * DLL next. */ @@ -114,8 +113,7 @@ struct CadetTunnelSkippedKey /** * Axolotl data, according to https://github.com/trevp/axolotl/wiki . */ -struct CadetTunnelAxolotl -{ +struct CadetTunnelAxolotl { /** * A (double linked) list of stored message keys and associated header keys * for "skipped" messages, i.e. messages that have not been @@ -248,15 +246,13 @@ struct CadetTunnelAxolotl * @e ratchet_allowed is #GNUNET_YES, we advance the ratchet. */ unsigned int ratchet_counter; - }; /** * Struct used to save messages in a non-ready tunnel to send once connected. */ -struct CadetTunnelQueueEntry -{ +struct CadetTunnelQueueEntry { /** * We are entries in a DLL */ @@ -298,8 +294,7 @@ struct CadetTunnelQueueEntry /** * Struct containing all information regarding a tunnel to a peer. */ -struct CadetTunnel -{ +struct CadetTunnel { /** * Destination of the tunnel. */ @@ -454,7 +449,6 @@ struct CadetTunnel * Force triggering KX_AUTH independent of @e estate. */ int kx_auth_requested; - }; @@ -465,19 +459,19 @@ struct CadetTunnel * @return #GNUNET_YES for Alice, #GNUNET_NO for Betty, #GNUNET_SYSERR if talking to myself */ static int -alice_or_betty (const struct GNUNET_PeerIdentity *other) +alice_or_betty(const struct GNUNET_PeerIdentity *other) { - if (0 > GNUNET_memcmp (&my_full_id, - other)) + if (0 > GNUNET_memcmp(&my_full_id, + other)) return GNUNET_YES; - else if (0 < GNUNET_memcmp (&my_full_id, - other)) + else if (0 < GNUNET_memcmp(&my_full_id, + other)) return GNUNET_NO; else - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } } @@ -488,20 +482,20 @@ alice_or_betty (const struct GNUNET_PeerIdentity *other) * @param ct connection to move to unready status */ static void -mark_connection_unready (struct CadetTConnection *ct) +mark_connection_unready(struct CadetTConnection *ct) { struct CadetTunnel *t = ct->t; - GNUNET_assert (GNUNET_YES == ct->is_ready); - GNUNET_CONTAINER_DLL_remove (t->connection_ready_head, - t->connection_ready_tail, - ct); - GNUNET_assert (0 < t->num_ready_connections); + GNUNET_assert(GNUNET_YES == ct->is_ready); + GNUNET_CONTAINER_DLL_remove(t->connection_ready_head, + t->connection_ready_tail, + ct); + GNUNET_assert(0 < t->num_ready_connections); t->num_ready_connections--; ct->is_ready = GNUNET_NO; - GNUNET_CONTAINER_DLL_insert (t->connection_busy_head, - t->connection_busy_tail, - ct); + GNUNET_CONTAINER_DLL_insert(t->connection_busy_head, + t->connection_busy_tail, + ct); t->num_busy_connections++; } @@ -514,16 +508,16 @@ mark_connection_unready (struct CadetTConnection *ct) * @return Static string the destination peer's ID. */ const char * -GCT_2s (const struct CadetTunnel *t) +GCT_2s(const struct CadetTunnel *t) { static char buf[64]; if (NULL == t) return "Tunnel(NULL)"; - GNUNET_snprintf (buf, - sizeof (buf), - "Tunnel %s", - GNUNET_i2s (GCP_get_id (t->destination))); + GNUNET_snprintf(buf, + sizeof(buf), + "Tunnel %s", + GNUNET_i2s(GCP_get_id(t->destination))); return buf; } @@ -536,31 +530,37 @@ GCT_2s (const struct CadetTunnel *t) * @return String representation. */ static const char * -estate2s (enum CadetTunnelEState es) +estate2s(enum CadetTunnelEState es) { static char buf[32]; switch (es) - { - case CADET_TUNNEL_KEY_UNINITIALIZED: - return "CADET_TUNNEL_KEY_UNINITIALIZED"; - case CADET_TUNNEL_KEY_AX_RECV: - return "CADET_TUNNEL_KEY_AX_RECV"; - case CADET_TUNNEL_KEY_AX_SENT: - return "CADET_TUNNEL_KEY_AX_SENT"; - case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: - return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV"; - case CADET_TUNNEL_KEY_AX_AUTH_SENT: - return "CADET_TUNNEL_KEY_AX_AUTH_SENT"; - case CADET_TUNNEL_KEY_OK: - return "CADET_TUNNEL_KEY_OK"; - default: - GNUNET_snprintf (buf, - sizeof (buf), - "%u (UNKNOWN STATE)", - es); - return buf; - } + { + case CADET_TUNNEL_KEY_UNINITIALIZED: + return "CADET_TUNNEL_KEY_UNINITIALIZED"; + + case CADET_TUNNEL_KEY_AX_RECV: + return "CADET_TUNNEL_KEY_AX_RECV"; + + case CADET_TUNNEL_KEY_AX_SENT: + return "CADET_TUNNEL_KEY_AX_SENT"; + + case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: + return "CADET_TUNNEL_KEY_AX_SENT_AND_RECV"; + + case CADET_TUNNEL_KEY_AX_AUTH_SENT: + return "CADET_TUNNEL_KEY_AX_AUTH_SENT"; + + case CADET_TUNNEL_KEY_OK: + return "CADET_TUNNEL_KEY_OK"; + + default: + GNUNET_snprintf(buf, + sizeof(buf), + "%u (UNKNOWN STATE)", + es); + return buf; + } } @@ -571,7 +571,7 @@ estate2s (enum CadetTunnelEState es) * @return the destination of the tunnel */ struct CadetPeer * -GCT_get_destination (struct CadetTunnel *t) +GCT_get_destination(struct CadetTunnel *t) { return t->destination; } @@ -585,9 +585,9 @@ GCT_get_destination (struct CadetTunnel *t) * @return Number of channels. */ unsigned int -GCT_count_channels (struct CadetTunnel *t) +GCT_count_channels(struct CadetTunnel *t) { - return GNUNET_CONTAINER_multihashmap32_size (t->channels); + return GNUNET_CONTAINER_multihashmap32_size(t->channels); } @@ -599,11 +599,11 @@ GCT_count_channels (struct CadetTunnel *t) * @return NULL if channel does not exist */ struct CadetChannel * -lookup_channel (struct CadetTunnel *t, - struct GNUNET_CADET_ChannelTunnelNumber ctn) +lookup_channel(struct CadetTunnel *t, + struct GNUNET_CADET_ChannelTunnelNumber ctn) { - return GNUNET_CONTAINER_multihashmap32_get (t->channels, - ntohl (ctn.cn)); + return GNUNET_CONTAINER_multihashmap32_get(t->channels, + ntohl(ctn.cn)); } @@ -615,7 +615,7 @@ lookup_channel (struct CadetTunnel *t, * @return Number of connections created, either being established or ready. */ unsigned int -GCT_count_any_connections (const struct CadetTunnel *t) +GCT_count_any_connections(const struct CadetTunnel *t) { return t->num_ready_connections + t->num_busy_connections; } @@ -629,12 +629,12 @@ GCT_count_any_connections (const struct CadetTunnel *t) * @return NULL if we have no connection that is ready */ static struct CadetTConnection * -get_ready_connection (struct CadetTunnel *t) +get_ready_connection(struct CadetTunnel *t) { struct CadetTConnection *hd = t->connection_ready_head; - GNUNET_assert ( (NULL == hd) || - (GNUNET_YES == hd->is_ready) ); + GNUNET_assert((NULL == hd) || + (GNUNET_YES == hd->is_ready)); return hd; } @@ -647,7 +647,7 @@ get_ready_connection (struct CadetTunnel *t) * @return Tunnel's encryption state. */ enum CadetTunnelEState -GCT_get_estate (struct CadetTunnel *t) +GCT_get_estate(struct CadetTunnel *t) { return t->estate; } @@ -662,7 +662,7 @@ GCT_get_estate (struct CadetTunnel *t) * @param cls the `struct CadetTunnel` to process messages on */ static void -trigger_transmissions (void *cls); +trigger_transmissions(void *cls); /* ************************************** start core crypto ***************************** */ @@ -674,12 +674,12 @@ trigger_transmissions (void *cls); * @param ax key material to update */ static void -new_ephemeral (struct CadetTunnelAxolotl *ax) +new_ephemeral(struct CadetTunnelAxolotl *ax) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Creating new ephemeral ratchet key (DHRs)\n"); - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_ecdhe_key_create2 (&ax->DHRs)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Creating new ephemeral ratchet key (DHRs)\n"); + GNUNET_assert(GNUNET_OK == + GNUNET_CRYPTO_ecdhe_key_create2(&ax->DHRs)); } @@ -693,31 +693,31 @@ new_ephemeral (struct CadetTunnelAxolotl *ax) * @param hmac[out] Destination to store the HMAC. */ static void -t_hmac (const void *plaintext, - size_t size, - uint32_t iv, - const struct GNUNET_CRYPTO_SymmetricSessionKey *key, - struct GNUNET_ShortHashCode *hmac) +t_hmac(const void *plaintext, + size_t size, + uint32_t iv, + const struct GNUNET_CRYPTO_SymmetricSessionKey *key, + struct GNUNET_ShortHashCode *hmac) { static const char ctx[] = "cadet authentication key"; struct GNUNET_CRYPTO_AuthKey auth_key; struct GNUNET_HashCode hash; - GNUNET_CRYPTO_hmac_derive_key (&auth_key, - key, - &iv, sizeof (iv), - key, sizeof (*key), - ctx, sizeof (ctx), - NULL); + GNUNET_CRYPTO_hmac_derive_key(&auth_key, + key, + &iv, sizeof(iv), + key, sizeof(*key), + ctx, sizeof(ctx), + NULL); /* Two step: GNUNET_ShortHash is only 256 bits, GNUNET_HashCode is 512, so we truncate. */ - GNUNET_CRYPTO_hmac (&auth_key, - plaintext, - size, - &hash); - GNUNET_memcpy (hmac, - &hash, - sizeof (*hmac)); + GNUNET_CRYPTO_hmac(&auth_key, + plaintext, + size, + &hash); + GNUNET_memcpy(hmac, + &hash, + sizeof(*hmac)); } @@ -730,22 +730,22 @@ t_hmac (const void *plaintext, * @param len Length of @a source. */ static void -t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key, - struct GNUNET_HashCode *hash, - const void *source, - unsigned int len) +t_ax_hmac_hash(const struct GNUNET_CRYPTO_SymmetricSessionKey *key, + struct GNUNET_HashCode *hash, + const void *source, + unsigned int len) { static const char ctx[] = "axolotl HMAC-HASH"; struct GNUNET_CRYPTO_AuthKey auth_key; - GNUNET_CRYPTO_hmac_derive_key (&auth_key, - key, - ctx, sizeof (ctx), - NULL); - GNUNET_CRYPTO_hmac (&auth_key, - source, - len, - hash); + GNUNET_CRYPTO_hmac_derive_key(&auth_key, + key, + ctx, sizeof(ctx), + NULL); + GNUNET_CRYPTO_hmac(&auth_key, + source, + len, + hash); } @@ -758,22 +758,22 @@ t_ax_hmac_hash (const struct GNUNET_CRYPTO_SymmetricSessionKey *key, * @param len Length of @a source. */ static void -t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key, - struct GNUNET_CRYPTO_SymmetricSessionKey *out, - const void *source, - unsigned int len) +t_hmac_derive_key(const struct GNUNET_CRYPTO_SymmetricSessionKey *key, + struct GNUNET_CRYPTO_SymmetricSessionKey *out, + const void *source, + unsigned int len) { static const char ctx[] = "axolotl derive key"; struct GNUNET_HashCode h; - t_ax_hmac_hash (key, - &h, - source, - len); - GNUNET_CRYPTO_kdf (out, sizeof (*out), - ctx, sizeof (ctx), - &h, sizeof (h), - NULL); + t_ax_hmac_hash(key, + &h, + source, + len); + GNUNET_CRYPTO_kdf(out, sizeof(*out), + ctx, sizeof(ctx), + &h, sizeof(h), + NULL); } @@ -786,78 +786,78 @@ t_hmac_derive_key (const struct GNUNET_CRYPTO_SymmetricSessionKey *key, * @param size Size of the buffers at @a src and @a dst */ static void -t_ax_encrypt (struct CadetTunnelAxolotl *ax, - void *dst, - const void *src, - size_t size) +t_ax_encrypt(struct CadetTunnelAxolotl *ax, + void *dst, + const void *src, + size_t size) { struct GNUNET_CRYPTO_SymmetricSessionKey MK; struct GNUNET_CRYPTO_SymmetricInitializationVector iv; size_t out_size; ax->ratchet_counter++; - if ( (GNUNET_YES == ax->ratchet_allowed) && - ( (ratchet_messages <= ax->ratchet_counter) || - (0 == GNUNET_TIME_absolute_get_remaining (ax->ratchet_expiration).rel_value_us)) ) - { - ax->ratchet_flag = GNUNET_YES; - } + if ((GNUNET_YES == ax->ratchet_allowed) && + ((ratchet_messages <= ax->ratchet_counter) || + (0 == GNUNET_TIME_absolute_get_remaining(ax->ratchet_expiration).rel_value_us))) + { + ax->ratchet_flag = GNUNET_YES; + } if (GNUNET_YES == ax->ratchet_flag) - { - /* Advance ratchet */ - struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; - struct GNUNET_HashCode dh; - struct GNUNET_HashCode hmac; - static const char ctx[] = "axolotl ratchet"; - - new_ephemeral (ax); - ax->HKs = ax->NHKs; - - /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */ - GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs, - &ax->DHRr, - &dh); - t_ax_hmac_hash (&ax->RK, - &hmac, - &dh, - sizeof (dh)); - GNUNET_CRYPTO_kdf (keys, sizeof (keys), - ctx, sizeof (ctx), - &hmac, sizeof (hmac), - NULL); - ax->RK = keys[0]; - ax->NHKs = keys[1]; - ax->CKs = keys[2]; - - ax->PNs = ax->Ns; - ax->Ns = 0; - ax->ratchet_flag = GNUNET_NO; - ax->ratchet_allowed = GNUNET_NO; - ax->ratchet_counter = 0; - ax->ratchet_expiration - = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), - ratchet_time); - } - - t_hmac_derive_key (&ax->CKs, - &MK, - "0", - 1); - GNUNET_CRYPTO_symmetric_derive_iv (&iv, - &MK, - NULL, 0, - NULL); - - out_size = GNUNET_CRYPTO_symmetric_encrypt (src, - size, - &MK, - &iv, - dst); - GNUNET_assert (size == out_size); - t_hmac_derive_key (&ax->CKs, - &ax->CKs, - "1", - 1); + { + /* Advance ratchet */ + struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; + struct GNUNET_HashCode dh; + struct GNUNET_HashCode hmac; + static const char ctx[] = "axolotl ratchet"; + + new_ephemeral(ax); + ax->HKs = ax->NHKs; + + /* RK, NHKs, CKs = KDF( HMAC-HASH(RK, DH(DHRs, DHRr)) ) */ + GNUNET_CRYPTO_ecc_ecdh(&ax->DHRs, + &ax->DHRr, + &dh); + t_ax_hmac_hash(&ax->RK, + &hmac, + &dh, + sizeof(dh)); + GNUNET_CRYPTO_kdf(keys, sizeof(keys), + ctx, sizeof(ctx), + &hmac, sizeof(hmac), + NULL); + ax->RK = keys[0]; + ax->NHKs = keys[1]; + ax->CKs = keys[2]; + + ax->PNs = ax->Ns; + ax->Ns = 0; + ax->ratchet_flag = GNUNET_NO; + ax->ratchet_allowed = GNUNET_NO; + ax->ratchet_counter = 0; + ax->ratchet_expiration + = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), + ratchet_time); + } + + t_hmac_derive_key(&ax->CKs, + &MK, + "0", + 1); + GNUNET_CRYPTO_symmetric_derive_iv(&iv, + &MK, + NULL, 0, + NULL); + + out_size = GNUNET_CRYPTO_symmetric_encrypt(src, + size, + &MK, + &iv, + dst); + GNUNET_assert(size == out_size); + t_hmac_derive_key(&ax->CKs, + &ax->CKs, + "1", + 1); } @@ -870,34 +870,34 @@ t_ax_encrypt (struct CadetTunnelAxolotl *ax, * @param size Size of the @a src and @a dst buffers */ static void -t_ax_decrypt (struct CadetTunnelAxolotl *ax, - void *dst, - const void *src, - size_t size) +t_ax_decrypt(struct CadetTunnelAxolotl *ax, + void *dst, + const void *src, + size_t size) { struct GNUNET_CRYPTO_SymmetricSessionKey MK; struct GNUNET_CRYPTO_SymmetricInitializationVector iv; size_t out_size; - t_hmac_derive_key (&ax->CKr, - &MK, - "0", - 1); - GNUNET_CRYPTO_symmetric_derive_iv (&iv, - &MK, - NULL, 0, - NULL); - GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader)); - out_size = GNUNET_CRYPTO_symmetric_decrypt (src, - size, - &MK, - &iv, - dst); - GNUNET_assert (out_size == size); - t_hmac_derive_key (&ax->CKr, - &ax->CKr, - "1", - 1); + t_hmac_derive_key(&ax->CKr, + &MK, + "0", + 1); + GNUNET_CRYPTO_symmetric_derive_iv(&iv, + &MK, + NULL, 0, + NULL); + GNUNET_assert(size >= sizeof(struct GNUNET_MessageHeader)); + out_size = GNUNET_CRYPTO_symmetric_decrypt(src, + size, + &MK, + &iv, + dst); + GNUNET_assert(out_size == size); + t_hmac_derive_key(&ax->CKr, + &ax->CKr, + "1", + 1); } @@ -908,22 +908,22 @@ t_ax_decrypt (struct CadetTunnelAxolotl *ax, * @param[in|out] msg Message whose header to encrypt. */ static void -t_h_encrypt (struct CadetTunnelAxolotl *ax, - struct GNUNET_CADET_TunnelEncryptedMessage *msg) +t_h_encrypt(struct CadetTunnelAxolotl *ax, + struct GNUNET_CADET_TunnelEncryptedMessage *msg) { struct GNUNET_CRYPTO_SymmetricInitializationVector iv; size_t out_size; - GNUNET_CRYPTO_symmetric_derive_iv (&iv, - &ax->HKs, - NULL, 0, - NULL); - out_size = GNUNET_CRYPTO_symmetric_encrypt (&msg->ax_header, - sizeof (struct GNUNET_CADET_AxHeader), - &ax->HKs, - &iv, - &msg->ax_header); - GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size); + GNUNET_CRYPTO_symmetric_derive_iv(&iv, + &ax->HKs, + NULL, 0, + NULL); + out_size = GNUNET_CRYPTO_symmetric_encrypt(&msg->ax_header, + sizeof(struct GNUNET_CADET_AxHeader), + &ax->HKs, + &iv, + &msg->ax_header); + GNUNET_assert(sizeof(struct GNUNET_CADET_AxHeader) == out_size); } @@ -935,23 +935,23 @@ t_h_encrypt (struct CadetTunnelAxolotl *ax, * @param dst Where to decrypt header to. */ static void -t_h_decrypt (struct CadetTunnelAxolotl *ax, - const struct GNUNET_CADET_TunnelEncryptedMessage *src, - struct GNUNET_CADET_TunnelEncryptedMessage *dst) +t_h_decrypt(struct CadetTunnelAxolotl *ax, + const struct GNUNET_CADET_TunnelEncryptedMessage *src, + struct GNUNET_CADET_TunnelEncryptedMessage *dst) { struct GNUNET_CRYPTO_SymmetricInitializationVector iv; size_t out_size; - GNUNET_CRYPTO_symmetric_derive_iv (&iv, - &ax->HKr, - NULL, 0, - NULL); - out_size = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns, - sizeof (struct GNUNET_CADET_AxHeader), - &ax->HKr, - &iv, - &dst->ax_header.Ns); - GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == out_size); + GNUNET_CRYPTO_symmetric_derive_iv(&iv, + &ax->HKr, + NULL, 0, + NULL); + out_size = GNUNET_CRYPTO_symmetric_decrypt(&src->ax_header.Ns, + sizeof(struct GNUNET_CADET_AxHeader), + &ax->HKr, + &iv, + &dst->ax_header.Ns); + GNUNET_assert(sizeof(struct GNUNET_CADET_AxHeader) == out_size); } @@ -962,13 +962,13 @@ t_h_decrypt (struct CadetTunnelAxolotl *ax, * @param key Key to delete. */ static void -delete_skipped_key (struct CadetTunnelAxolotl *ax, - struct CadetTunnelSkippedKey *key) +delete_skipped_key(struct CadetTunnelAxolotl *ax, + struct CadetTunnelSkippedKey *key) { - GNUNET_CONTAINER_DLL_remove (ax->skipped_head, - ax->skipped_tail, - key); - GNUNET_free (key); + GNUNET_CONTAINER_DLL_remove(ax->skipped_head, + ax->skipped_tail, + key); + GNUNET_free(key); ax->skipped--; } @@ -984,10 +984,10 @@ delete_skipped_key (struct CadetTunnelAxolotl *ax, * @return Size of the decrypted data, -1 if an error was encountered. */ static ssize_t -try_old_ax_keys (struct CadetTunnelAxolotl *ax, - void *dst, - const struct GNUNET_CADET_TunnelEncryptedMessage *src, - size_t size) +try_old_ax_keys(struct CadetTunnelAxolotl *ax, + void *dst, + const struct GNUNET_CADET_TunnelEncryptedMessage *src, + size_t size) { struct CadetTunnelSkippedKey *key; struct GNUNET_ShortHashCode *hmac; @@ -999,70 +999,70 @@ try_old_ax_keys (struct CadetTunnelAxolotl *ax, size_t len; unsigned int N; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Trying skipped keys\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Trying skipped keys\n"); hmac = &plaintext_header.hmac; - esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage); + esize = size - sizeof(struct GNUNET_CADET_TunnelEncryptedMessage); /* Find a correct Header Key */ valid_HK = NULL; for (key = ax->skipped_head; NULL != key; key = key->next) - { - t_hmac (&src->ax_header, - sizeof (struct GNUNET_CADET_AxHeader) + esize, - 0, - &key->HK, - hmac); - if (0 == GNUNET_memcmp (hmac, - &src->hmac)) - { - valid_HK = &key->HK; - break; + { + t_hmac(&src->ax_header, + sizeof(struct GNUNET_CADET_AxHeader) + esize, + 0, + &key->HK, + hmac); + if (0 == GNUNET_memcmp(hmac, + &src->hmac)) + { + valid_HK = &key->HK; + break; + } } - } if (NULL == key) return -1; /* Should've been checked in -cadet_connection.c handle_cadet_encrypted. */ - GNUNET_assert (size > sizeof (struct GNUNET_CADET_TunnelEncryptedMessage)); - len = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage); - GNUNET_assert (len >= sizeof (struct GNUNET_MessageHeader)); + GNUNET_assert(size > sizeof(struct GNUNET_CADET_TunnelEncryptedMessage)); + len = size - sizeof(struct GNUNET_CADET_TunnelEncryptedMessage); + GNUNET_assert(len >= sizeof(struct GNUNET_MessageHeader)); /* Decrypt header */ - GNUNET_CRYPTO_symmetric_derive_iv (&iv, - &key->HK, - NULL, 0, - NULL); - res = GNUNET_CRYPTO_symmetric_decrypt (&src->ax_header.Ns, - sizeof (struct GNUNET_CADET_AxHeader), - &key->HK, - &iv, - &plaintext_header.ax_header.Ns); - GNUNET_assert (sizeof (struct GNUNET_CADET_AxHeader) == res); + GNUNET_CRYPTO_symmetric_derive_iv(&iv, + &key->HK, + NULL, 0, + NULL); + res = GNUNET_CRYPTO_symmetric_decrypt(&src->ax_header.Ns, + sizeof(struct GNUNET_CADET_AxHeader), + &key->HK, + &iv, + &plaintext_header.ax_header.Ns); + GNUNET_assert(sizeof(struct GNUNET_CADET_AxHeader) == res); /* Find the correct message key */ - N = ntohl (plaintext_header.ax_header.Ns); - while ( (NULL != key) && - (N != key->Kn) ) + N = ntohl(plaintext_header.ax_header.Ns); + while ((NULL != key) && + (N != key->Kn)) key = key->next; - if ( (NULL == key) || - (0 != GNUNET_memcmp (&key->HK, - valid_HK)) ) + if ((NULL == key) || + (0 != GNUNET_memcmp(&key->HK, + valid_HK))) return -1; /* Decrypt payload */ - GNUNET_CRYPTO_symmetric_derive_iv (&iv, - &key->MK, - NULL, - 0, - NULL); - res = GNUNET_CRYPTO_symmetric_decrypt (&src[1], - len, - &key->MK, - &iv, - dst); - delete_skipped_key (ax, - key); + GNUNET_CRYPTO_symmetric_derive_iv(&iv, + &key->MK, + NULL, + 0, + NULL); + res = GNUNET_CRYPTO_symmetric_decrypt(&src[1], + len, + &key->MK, + &iv, + dst); + delete_skipped_key(ax, + key); return res; } @@ -1074,26 +1074,26 @@ try_old_ax_keys (struct CadetTunnelAxolotl *ax, * @param HKr Header Key to use. */ static void -store_skipped_key (struct CadetTunnelAxolotl *ax, - const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr) +store_skipped_key(struct CadetTunnelAxolotl *ax, + const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr) { struct CadetTunnelSkippedKey *key; - key = GNUNET_new (struct CadetTunnelSkippedKey); - key->timestamp = GNUNET_TIME_absolute_get (); + key = GNUNET_new(struct CadetTunnelSkippedKey); + key->timestamp = GNUNET_TIME_absolute_get(); key->Kn = ax->Nr; key->HK = ax->HKr; - t_hmac_derive_key (&ax->CKr, - &key->MK, - "0", - 1); - t_hmac_derive_key (&ax->CKr, - &ax->CKr, - "1", - 1); - GNUNET_CONTAINER_DLL_insert (ax->skipped_head, - ax->skipped_tail, - key); + t_hmac_derive_key(&ax->CKr, + &key->MK, + "0", + 1); + t_hmac_derive_key(&ax->CKr, + &ax->CKr, + "1", + 1); + GNUNET_CONTAINER_DLL_insert(ax->skipped_head, + ax->skipped_tail, + key); ax->skipped++; ax->Nr++; } @@ -1110,41 +1110,41 @@ store_skipped_key (struct CadetTunnelAxolotl *ax, * #GNUNET_SYSERR if an error ocurred (@a Np not expected). */ static int -store_ax_keys (struct CadetTunnelAxolotl *ax, - const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr, - uint32_t Np) +store_ax_keys(struct CadetTunnelAxolotl *ax, + const struct GNUNET_CRYPTO_SymmetricSessionKey *HKr, + uint32_t Np) { int gap; gap = Np - ax->Nr; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Storing skipped keys [%u, %u)\n", - ax->Nr, - Np); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Storing skipped keys [%u, %u)\n", + ax->Nr, + Np); if (MAX_KEY_GAP < gap) - { - /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */ - /* TODO: start new key exchange on return */ - GNUNET_break_op (0); - LOG (GNUNET_ERROR_TYPE_WARNING, - "Got message %u, expected %u+\n", - Np, - ax->Nr); - return GNUNET_SYSERR; - } + { + /* Avoid DoS (forcing peer to do more than #MAX_KEY_GAP HMAC operations) */ + /* TODO: start new key exchange on return */ + GNUNET_break_op(0); + LOG(GNUNET_ERROR_TYPE_WARNING, + "Got message %u, expected %u+\n", + Np, + ax->Nr); + return GNUNET_SYSERR; + } if (0 > gap) - { - /* Delayed message: don't store keys, flag to try old keys. */ - return GNUNET_SYSERR; - } + { + /* Delayed message: don't store keys, flag to try old keys. */ + return GNUNET_SYSERR; + } while (ax->Nr < Np) - store_skipped_key (ax, - HKr); + store_skipped_key(ax, + HKr); while (ax->skipped > MAX_SKIPPED_KEYS) - delete_skipped_key (ax, - ax->skipped_tail); + delete_skipped_key(ax, + ax->skipped_tail); return GNUNET_OK; } @@ -1160,10 +1160,10 @@ store_ax_keys (struct CadetTunnelAxolotl *ax, * @return Size of the decrypted data, -1 if an error was encountered. */ static ssize_t -t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax, - void *dst, - const struct GNUNET_CADET_TunnelEncryptedMessage *src, - size_t size) +t_ax_decrypt_and_validate(struct CadetTunnelAxolotl *ax, + void *dst, + const struct GNUNET_CADET_TunnelEncryptedMessage *src, + size_t size) { struct GNUNET_ShortHashCode msg_hmac; struct GNUNET_HashCode hmac; @@ -1172,93 +1172,93 @@ t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax, uint32_t PNp; size_t esize; /* Size of encryped payload */ - esize = size - sizeof (struct GNUNET_CADET_TunnelEncryptedMessage); + esize = size - sizeof(struct GNUNET_CADET_TunnelEncryptedMessage); /* Try current HK */ - t_hmac (&src->ax_header, - sizeof (struct GNUNET_CADET_AxHeader) + esize, - 0, &ax->HKr, - &msg_hmac); - if (0 != GNUNET_memcmp (&msg_hmac, - &src->hmac)) - { - static const char ctx[] = "axolotl ratchet"; - struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */ - struct GNUNET_CRYPTO_SymmetricSessionKey HK; - struct GNUNET_HashCode dh; - struct GNUNET_CRYPTO_EcdhePublicKey *DHRp; - - /* Try Next HK */ - t_hmac (&src->ax_header, - sizeof (struct GNUNET_CADET_AxHeader) + esize, - 0, - &ax->NHKr, - &msg_hmac); - if (0 != GNUNET_memcmp (&msg_hmac, - &src->hmac)) + t_hmac(&src->ax_header, + sizeof(struct GNUNET_CADET_AxHeader) + esize, + 0, &ax->HKr, + &msg_hmac); + if (0 != GNUNET_memcmp(&msg_hmac, + &src->hmac)) { - /* Try the skipped keys, if that fails, we're out of luck. */ - return try_old_ax_keys (ax, - dst, - src, - size); - } - HK = ax->HKr; - ax->HKr = ax->NHKr; - t_h_decrypt (ax, - src, - &plaintext_header); - Np = ntohl (plaintext_header.ax_header.Ns); - PNp = ntohl (plaintext_header.ax_header.PNs); - DHRp = &plaintext_header.ax_header.DHRs; - store_ax_keys (ax, - &HK, - PNp); - - /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */ - GNUNET_CRYPTO_ecc_ecdh (&ax->DHRs, - DHRp, - &dh); - t_ax_hmac_hash (&ax->RK, - &hmac, - &dh, sizeof (dh)); - GNUNET_CRYPTO_kdf (keys, sizeof (keys), - ctx, sizeof (ctx), - &hmac, sizeof (hmac), - NULL); - - /* Commit "purported" keys */ - ax->RK = keys[0]; - ax->NHKr = keys[1]; - ax->CKr = keys[2]; - ax->DHRr = *DHRp; - ax->Nr = 0; - ax->ratchet_allowed = GNUNET_YES; - } + static const char ctx[] = "axolotl ratchet"; + struct GNUNET_CRYPTO_SymmetricSessionKey keys[3]; /* RKp, NHKp, CKp */ + struct GNUNET_CRYPTO_SymmetricSessionKey HK; + struct GNUNET_HashCode dh; + struct GNUNET_CRYPTO_EcdhePublicKey *DHRp; + + /* Try Next HK */ + t_hmac(&src->ax_header, + sizeof(struct GNUNET_CADET_AxHeader) + esize, + 0, + &ax->NHKr, + &msg_hmac); + if (0 != GNUNET_memcmp(&msg_hmac, + &src->hmac)) + { + /* Try the skipped keys, if that fails, we're out of luck. */ + return try_old_ax_keys(ax, + dst, + src, + size); + } + HK = ax->HKr; + ax->HKr = ax->NHKr; + t_h_decrypt(ax, + src, + &plaintext_header); + Np = ntohl(plaintext_header.ax_header.Ns); + PNp = ntohl(plaintext_header.ax_header.PNs); + DHRp = &plaintext_header.ax_header.DHRs; + store_ax_keys(ax, + &HK, + PNp); + + /* RKp, NHKp, CKp = KDF (HMAC-HASH (RK, DH (DHRp, DHRs))) */ + GNUNET_CRYPTO_ecc_ecdh(&ax->DHRs, + DHRp, + &dh); + t_ax_hmac_hash(&ax->RK, + &hmac, + &dh, sizeof(dh)); + GNUNET_CRYPTO_kdf(keys, sizeof(keys), + ctx, sizeof(ctx), + &hmac, sizeof(hmac), + NULL); + + /* Commit "purported" keys */ + ax->RK = keys[0]; + ax->NHKr = keys[1]; + ax->CKr = keys[2]; + ax->DHRr = *DHRp; + ax->Nr = 0; + ax->ratchet_allowed = GNUNET_YES; + } else - { - t_h_decrypt (ax, - src, - &plaintext_header); - Np = ntohl (plaintext_header.ax_header.Ns); - PNp = ntohl (plaintext_header.ax_header.PNs); - } - if ( (Np != ax->Nr) && - (GNUNET_OK != store_ax_keys (ax, - &ax->HKr, - Np)) ) - { - /* Try the skipped keys, if that fails, we're out of luck. */ - return try_old_ax_keys (ax, - dst, - src, - size); - } - - t_ax_decrypt (ax, - dst, - &src[1], - esize); + { + t_h_decrypt(ax, + src, + &plaintext_header); + Np = ntohl(plaintext_header.ax_header.Ns); + PNp = ntohl(plaintext_header.ax_header.PNs); + } + if ((Np != ax->Nr) && + (GNUNET_OK != store_ax_keys(ax, + &ax->HKr, + Np))) + { + /* Try the skipped keys, if that fails, we're out of luck. */ + return try_old_ax_keys(ax, + dst, + src, + size); + } + + t_ax_decrypt(ax, + dst, + &src[1], + esize); ax->Nr = Np + 1; return esize; } @@ -1274,13 +1274,13 @@ t_ax_decrypt_and_validate (struct CadetTunnelAxolotl *ax, * @return #GNUNET_OK (continue to iterate) */ static int -notify_tunnel_up_cb (void *cls, - uint32_t key, - void *value) +notify_tunnel_up_cb(void *cls, + uint32_t key, + void *value) { struct CadetChannel *ch = value; - GCCH_tunnel_up (ch); + GCCH_tunnel_up(ch); return GNUNET_OK; } @@ -1293,35 +1293,35 @@ notify_tunnel_up_cb (void *cls, * @param state New encryption state. */ void -GCT_change_estate (struct CadetTunnel *t, - enum CadetTunnelEState state) +GCT_change_estate(struct CadetTunnel *t, + enum CadetTunnelEState state) { enum CadetTunnelEState old = t->estate; t->estate = state; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "%s estate changed from %s to %s\n", - GCT_2s (t), - estate2s (old), - estate2s (state)); - - if ( (CADET_TUNNEL_KEY_OK != old) && - (CADET_TUNNEL_KEY_OK == t->estate) ) - { - if (NULL != t->kx_task) - { - GNUNET_SCHEDULER_cancel (t->kx_task); - t->kx_task = NULL; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "%s estate changed from %s to %s\n", + GCT_2s(t), + estate2s(old), + estate2s(state)); + + if ((CADET_TUNNEL_KEY_OK != old) && + (CADET_TUNNEL_KEY_OK == t->estate)) + { + if (NULL != t->kx_task) + { + GNUNET_SCHEDULER_cancel(t->kx_task); + t->kx_task = NULL; + } + /* notify all channels that have been waiting */ + GNUNET_CONTAINER_multihashmap32_iterate(t->channels, + ¬ify_tunnel_up_cb, + t); + if (NULL != t->send_task) + GNUNET_SCHEDULER_cancel(t->send_task); + t->send_task = GNUNET_SCHEDULER_add_now(&trigger_transmissions, + t); } - /* notify all channels that have been waiting */ - GNUNET_CONTAINER_multihashmap32_iterate (t->channels, - ¬ify_tunnel_up_cb, - t); - if (NULL != t->send_task) - GNUNET_SCHEDULER_cancel (t->send_task); - t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions, - t); - } } @@ -1334,63 +1334,63 @@ GCT_change_estate (struct CadetTunnel *t, * @param ax axolotl key context to use */ static void -send_kx (struct CadetTunnel *t, - struct CadetTConnection *ct, - struct CadetTunnelAxolotl *ax) +send_kx(struct CadetTunnel *t, + struct CadetTConnection *ct, + struct CadetTunnelAxolotl *ax) { struct CadetConnection *cc; struct GNUNET_MQ_Envelope *env; struct GNUNET_CADET_TunnelKeyExchangeMessage *msg; enum GNUNET_CADET_KX_Flags flags; - if (GNUNET_YES != alice_or_betty (GCP_get_id (t->destination))) + if (GNUNET_YES != alice_or_betty(GCP_get_id(t->destination))) return; /* only Alice may send KX */ - if ( (NULL == ct) || - (GNUNET_NO == ct->is_ready) ) - ct = get_ready_connection (t); + if ((NULL == ct) || + (GNUNET_NO == ct->is_ready)) + ct = get_ready_connection(t); if (NULL == ct) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Wanted to send %s in state %s, but no connection is ready, deferring\n", - GCT_2s (t), - estate2s (t->estate)); - t->next_kx_attempt = GNUNET_TIME_absolute_get (); - return; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Wanted to send %s in state %s, but no connection is ready, deferring\n", + GCT_2s(t), + estate2s(t->estate)); + t->next_kx_attempt = GNUNET_TIME_absolute_get(); + return; + } cc = ct->cc; - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX); flags = GNUNET_CADET_KX_FLAG_FORCE_REPLY; /* always for KX */ - msg->flags = htonl (flags); - msg->cid = *GCC_get_id (cc); - GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0, - &msg->ephemeral_key); + msg->flags = htonl(flags); + msg->cid = *GCC_get_id(cc); + GNUNET_CRYPTO_ecdhe_key_get_public(&ax->kx_0, + &msg->ephemeral_key); #if DEBUG_KX msg->ephemeral_key_XXX = ax->kx_0; msg->private_key_XXX = *my_private_key; #endif - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending KX message to %s with ephemeral %s on CID %s\n", - GCT_2s (t), - GNUNET_e2s (&msg->ephemeral_key), - GNUNET_sh2s (&msg->cid.connection_of_tunnel)); - GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs, - &msg->ratchet_key); - mark_connection_unready (ct); - t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay); - t->next_kx_attempt = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending KX message to %s with ephemeral %s on CID %s\n", + GCT_2s(t), + GNUNET_e2s(&msg->ephemeral_key), + GNUNET_sh2s(&msg->cid.connection_of_tunnel)); + GNUNET_CRYPTO_ecdhe_key_get_public(&ax->DHRs, + &msg->ratchet_key); + mark_connection_unready(ct); + t->kx_retry_delay = GNUNET_TIME_STD_BACKOFF(t->kx_retry_delay); + t->next_kx_attempt = GNUNET_TIME_relative_to_absolute(t->kx_retry_delay); if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) - GCT_change_estate (t, - CADET_TUNNEL_KEY_AX_SENT); + GCT_change_estate(t, + CADET_TUNNEL_KEY_AX_SENT); else if (CADET_TUNNEL_KEY_AX_RECV == t->estate) - GCT_change_estate (t, - CADET_TUNNEL_KEY_AX_SENT_AND_RECV); - GCC_transmit (cc, - env); - GNUNET_STATISTICS_update (stats, - "# KX transmitted", - 1, - GNUNET_NO); + GCT_change_estate(t, + CADET_TUNNEL_KEY_AX_SENT_AND_RECV); + GCC_transmit(cc, + env); + GNUNET_STATISTICS_update(stats, + "# KX transmitted", + 1, + GNUNET_NO); } @@ -1405,76 +1405,76 @@ send_kx (struct CadetTunnel *t, * (set if we would like to transmit right now, but cannot) */ static void -send_kx_auth (struct CadetTunnel *t, - struct CadetTConnection *ct, - struct CadetTunnelAxolotl *ax, - int force_reply) +send_kx_auth(struct CadetTunnel *t, + struct CadetTConnection *ct, + struct CadetTunnelAxolotl *ax, + int force_reply) { struct CadetConnection *cc; struct GNUNET_MQ_Envelope *env; struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg; enum GNUNET_CADET_KX_Flags flags; - if ( (NULL == ct) || - (GNUNET_NO == ct->is_ready) ) - ct = get_ready_connection (t); + if ((NULL == ct) || + (GNUNET_NO == ct->is_ready)) + ct = get_ready_connection(t); if (NULL == ct) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n", - GCT_2s (t)); - t->next_kx_attempt = GNUNET_TIME_absolute_get (); - t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */ - return; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Wanted to send KX_AUTH on %s, but no connection is ready, deferring\n", + GCT_2s(t)); + t->next_kx_attempt = GNUNET_TIME_absolute_get(); + t->kx_auth_requested = GNUNET_YES; /* queue KX_AUTH independent of estate */ + return; + } t->kx_auth_requested = GNUNET_NO; /* clear flag */ cc = ct->cc; - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_CADET_TUNNEL_KX_AUTH); flags = GNUNET_CADET_KX_FLAG_NONE; if (GNUNET_YES == force_reply) flags |= GNUNET_CADET_KX_FLAG_FORCE_REPLY; - msg->kx.flags = htonl (flags); - msg->kx.cid = *GCC_get_id (cc); - GNUNET_CRYPTO_ecdhe_key_get_public (&ax->kx_0, - &msg->kx.ephemeral_key); - GNUNET_CRYPTO_ecdhe_key_get_public (&ax->DHRs, - &msg->kx.ratchet_key); + msg->kx.flags = htonl(flags); + msg->kx.cid = *GCC_get_id(cc); + GNUNET_CRYPTO_ecdhe_key_get_public(&ax->kx_0, + &msg->kx.ephemeral_key); + GNUNET_CRYPTO_ecdhe_key_get_public(&ax->DHRs, + &msg->kx.ratchet_key); #if DEBUG_KX msg->kx.ephemeral_key_XXX = ax->kx_0; msg->kx.private_key_XXX = *my_private_key; msg->r_ephemeral_key_XXX = ax->last_ephemeral; #endif - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending KX_AUTH message to %s with ephemeral %s on CID %s\n", - GCT_2s (t), - GNUNET_e2s (&msg->kx.ephemeral_key), - GNUNET_sh2s (&msg->kx.cid.connection_of_tunnel)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending KX_AUTH message to %s with ephemeral %s on CID %s\n", + GCT_2s(t), + GNUNET_e2s(&msg->kx.ephemeral_key), + GNUNET_sh2s(&msg->kx.cid.connection_of_tunnel)); /* Compute authenticator (this is the main difference to #send_kx()) */ - GNUNET_CRYPTO_hash (&ax->RK, - sizeof (ax->RK), - &msg->auth); + GNUNET_CRYPTO_hash(&ax->RK, + sizeof(ax->RK), + &msg->auth); /* Compute when to be triggered again; actual job will be scheduled via #connection_ready_cb() */ t->kx_retry_delay - = GNUNET_TIME_STD_BACKOFF (t->kx_retry_delay); + = GNUNET_TIME_STD_BACKOFF(t->kx_retry_delay); t->next_kx_attempt - = GNUNET_TIME_relative_to_absolute (t->kx_retry_delay); + = GNUNET_TIME_relative_to_absolute(t->kx_retry_delay); /* Send via cc, mark it as unready */ - mark_connection_unready (ct); + mark_connection_unready(ct); /* Update state machine, unless we are already OK */ if (CADET_TUNNEL_KEY_OK != t->estate) - GCT_change_estate (t, - CADET_TUNNEL_KEY_AX_AUTH_SENT); - GCC_transmit (cc, - env); - GNUNET_STATISTICS_update (stats, - "# KX_AUTH transmitted", - 1, - GNUNET_NO); + GCT_change_estate(t, + CADET_TUNNEL_KEY_AX_AUTH_SENT); + GCC_transmit(cc, + env); + GNUNET_STATISTICS_update(stats, + "# KX_AUTH transmitted", + 1, + GNUNET_NO); } @@ -1484,14 +1484,14 @@ send_kx_auth (struct CadetTunnel *t, * @param ax state to free, but not memory of @a ax itself */ static void -cleanup_ax (struct CadetTunnelAxolotl *ax) +cleanup_ax(struct CadetTunnelAxolotl *ax) { while (NULL != ax->skipped_head) - delete_skipped_key (ax, - ax->skipped_head); - GNUNET_assert (0 == ax->skipped); - GNUNET_CRYPTO_ecdhe_key_clear (&ax->kx_0); - GNUNET_CRYPTO_ecdhe_key_clear (&ax->DHRs); + delete_skipped_key(ax, + ax->skipped_head); + GNUNET_assert(0 == ax->skipped); + GNUNET_CRYPTO_ecdhe_key_clear(&ax->kx_0); + GNUNET_CRYPTO_ecdhe_key_clear(&ax->DHRs); } @@ -1509,105 +1509,105 @@ cleanup_ax (struct CadetTunnelAxolotl *ax) * #GNUNET_SYSERR on hard errors (i.e. @a pid is #my_full_id) */ static int -update_ax_by_kx (struct CadetTunnelAxolotl *ax, - const struct GNUNET_PeerIdentity *pid, - const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key, - const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key) +update_ax_by_kx(struct CadetTunnelAxolotl *ax, + const struct GNUNET_PeerIdentity *pid, + const struct GNUNET_CRYPTO_EcdhePublicKey *ephemeral_key, + const struct GNUNET_CRYPTO_EcdhePublicKey *ratchet_key) { struct GNUNET_HashCode key_material[3]; struct GNUNET_CRYPTO_SymmetricSessionKey keys[5]; const char salt[] = "CADET Axolotl salt"; int am_I_alice; - if (GNUNET_SYSERR == (am_I_alice = alice_or_betty (pid))) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if (0 == GNUNET_memcmp (&ax->DHRr, - ratchet_key)) - { - GNUNET_STATISTICS_update (stats, - "# Ratchet key already known", - 1, - GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ratchet key already known. Ignoring KX.\n"); - return GNUNET_NO; - } + if (GNUNET_SYSERR == (am_I_alice = alice_or_betty(pid))) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if (0 == GNUNET_memcmp(&ax->DHRr, + ratchet_key)) + { + GNUNET_STATISTICS_update(stats, + "# Ratchet key already known", + 1, + GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ratchet key already known. Ignoring KX.\n"); + return GNUNET_NO; + } ax->DHRr = *ratchet_key; ax->last_ephemeral = *ephemeral_key; /* ECDH A B0 */ if (GNUNET_YES == am_I_alice) - { - GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* a */ - ephemeral_key, /* B0 */ - &key_material[0]); - } + { + GNUNET_CRYPTO_eddsa_ecdh(my_private_key, /* a */ + ephemeral_key, /* B0 */ + &key_material[0]); + } else - { - GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0, /* b0 */ - &pid->public_key, /* A */ - &key_material[0]); - } + { + GNUNET_CRYPTO_ecdh_eddsa(&ax->kx_0, /* b0 */ + &pid->public_key, /* A */ + &key_material[0]); + } /* ECDH A0 B */ if (GNUNET_YES == am_I_alice) - { - GNUNET_CRYPTO_ecdh_eddsa (&ax->kx_0, /* a0 */ - &pid->public_key, /* B */ - &key_material[1]); - } + { + GNUNET_CRYPTO_ecdh_eddsa(&ax->kx_0, /* a0 */ + &pid->public_key, /* B */ + &key_material[1]); + } else - { - GNUNET_CRYPTO_eddsa_ecdh (my_private_key, /* b */ - ephemeral_key, /* A0 */ - &key_material[1]); - } + { + GNUNET_CRYPTO_eddsa_ecdh(my_private_key, /* b */ + ephemeral_key, /* A0 */ + &key_material[1]); + } /* ECDH A0 B0 */ - GNUNET_CRYPTO_ecc_ecdh (&ax->kx_0, /* a0 or b0 */ - ephemeral_key, /* B0 or A0 */ - &key_material[2]); + GNUNET_CRYPTO_ecc_ecdh(&ax->kx_0, /* a0 or b0 */ + ephemeral_key, /* B0 or A0 */ + &key_material[2]); /* KDF */ - GNUNET_CRYPTO_kdf (keys, sizeof (keys), - salt, sizeof (salt), - &key_material, sizeof (key_material), - NULL); - - if (0 == memcmp (&ax->RK, - &keys[0], - sizeof (ax->RK))) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Root key already known. Ignoring KX.\n"); - GNUNET_STATISTICS_update (stats, - "# Root key already known", - 1, - GNUNET_NO); - return GNUNET_NO; - } + GNUNET_CRYPTO_kdf(keys, sizeof(keys), + salt, sizeof(salt), + &key_material, sizeof(key_material), + NULL); + + if (0 == memcmp(&ax->RK, + &keys[0], + sizeof(ax->RK))) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Root key already known. Ignoring KX.\n"); + GNUNET_STATISTICS_update(stats, + "# Root key already known", + 1, + GNUNET_NO); + return GNUNET_NO; + } ax->RK = keys[0]; if (GNUNET_YES == am_I_alice) - { - ax->HKr = keys[1]; - ax->NHKs = keys[2]; - ax->NHKr = keys[3]; - ax->CKr = keys[4]; - ax->ratchet_flag = GNUNET_YES; - } + { + ax->HKr = keys[1]; + ax->NHKs = keys[2]; + ax->NHKr = keys[3]; + ax->CKr = keys[4]; + ax->ratchet_flag = GNUNET_YES; + } else - { - ax->HKs = keys[1]; - ax->NHKr = keys[2]; - ax->NHKs = keys[3]; - ax->CKs = keys[4]; - ax->ratchet_flag = GNUNET_NO; - ax->ratchet_expiration - = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), - ratchet_time); - } + { + ax->HKs = keys[1]; + ax->NHKr = keys[2]; + ax->NHKs = keys[3]; + ax->CKs = keys[4]; + ax->ratchet_flag = GNUNET_NO; + ax->ratchet_expiration + = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), + ratchet_time); + } return GNUNET_OK; } @@ -1618,24 +1618,25 @@ update_ax_by_kx (struct CadetTunnelAxolotl *ax, * @param cls the `struct CadetTunnel` to do KX for. */ static void -retry_kx (void *cls) +retry_kx(void *cls) { struct CadetTunnel *t = cls; struct CadetTunnelAxolotl *ax; t->kx_task = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Trying to make KX progress on %s in state %s\n", - GCT_2s (t), - estate2s (t->estate)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Trying to make KX progress on %s in state %s\n", + GCT_2s(t), + estate2s(t->estate)); switch (t->estate) { case CADET_TUNNEL_KEY_UNINITIALIZED: /* first attempt */ case CADET_TUNNEL_KEY_AX_SENT: /* trying again */ - send_kx (t, - NULL, - &t->ax); + send_kx(t, + NULL, + &t->ax); break; + case CADET_TUNNEL_KEY_AX_RECV: case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* We are responding, so only require reply @@ -1648,16 +1649,17 @@ retry_kx (void *cls) else { /* How can this be? */ - GNUNET_break (0); + GNUNET_break(0); ax = &t->ax; } - send_kx_auth (t, - NULL, - ax, - (0 == GCT_count_channels (t)) - ? GNUNET_NO - : GNUNET_YES); + send_kx_auth(t, + NULL, + ax, + (0 == GCT_count_channels(t)) + ? GNUNET_NO + : GNUNET_YES); break; + case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* We are responding, so only require reply if WE have a channel waiting. */ @@ -1669,16 +1671,17 @@ retry_kx (void *cls) else { /* How can this be? */ - GNUNET_break (0); + GNUNET_break(0); ax = &t->ax; } - send_kx_auth (t, - NULL, - ax, - (0 == GCT_count_channels (t)) - ? GNUNET_NO - : GNUNET_YES); + send_kx_auth(t, + NULL, + ax, + (0 == GCT_count_channels(t)) + ? GNUNET_NO + : GNUNET_YES); break; + case CADET_TUNNEL_KEY_OK: /* Must have been the *other* peer asking us to respond with a KX_AUTH. */ @@ -1692,10 +1695,10 @@ retry_kx (void *cls) /* Sending AX_AUTH in response to AX_AUTH */ ax = &t->ax; } - send_kx_auth (t, - NULL, - ax, - GNUNET_NO); + send_kx_auth(t, + NULL, + ax, + GNUNET_NO); break; } } @@ -1710,101 +1713,101 @@ retry_kx (void *cls) * @param msg the key exchange message */ void -GCT_handle_kx (struct CadetTConnection *ct, - const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg) +GCT_handle_kx(struct CadetTConnection *ct, + const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg) { struct CadetTunnel *t = ct->t; int ret; - GNUNET_STATISTICS_update (stats, - "# KX received", - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(stats, + "# KX received", + 1, + GNUNET_NO); if (GNUNET_YES == - alice_or_betty (GCP_get_id (t->destination))) - { - /* Betty/Bob is not allowed to send KX! */ - GNUNET_break_op (0); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received KX message from %s with ephemeral %s from %s on connection %s\n", - GCT_2s (t), - GNUNET_e2s (&msg->ephemeral_key), - GNUNET_i2s (GCP_get_id (t->destination)), - GCC_2s (ct->cc)); + alice_or_betty(GCP_get_id(t->destination))) + { + /* Betty/Bob is not allowed to send KX! */ + GNUNET_break_op(0); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received KX message from %s with ephemeral %s from %s on connection %s\n", + GCT_2s(t), + GNUNET_e2s(&msg->ephemeral_key), + GNUNET_i2s(GCP_get_id(t->destination)), + GCC_2s(ct->cc)); #if 1 - if ( (0 == - memcmp (&t->ax.DHRr, - &msg->ratchet_key, - sizeof (msg->ratchet_key))) && - (0 == - memcmp (&t->ax.last_ephemeral, - &msg->ephemeral_key, - sizeof (msg->ephemeral_key))) ) - - { - GNUNET_STATISTICS_update (stats, - "# Duplicate KX received", - 1, - GNUNET_NO); - send_kx_auth (t, - ct, - &t->ax, - GNUNET_NO); + if ((0 == + memcmp(&t->ax.DHRr, + &msg->ratchet_key, + sizeof(msg->ratchet_key))) && + (0 == + memcmp(&t->ax.last_ephemeral, + &msg->ephemeral_key, + sizeof(msg->ephemeral_key)))) + + { + GNUNET_STATISTICS_update(stats, + "# Duplicate KX received", + 1, + GNUNET_NO); + send_kx_auth(t, + ct, + &t->ax, + GNUNET_NO); return; } #endif /* We only keep ONE unverified KX around, so if there is an existing one, clean it up. */ if (NULL != t->unverified_ax) - { - if ( (0 == - memcmp (&t->unverified_ax->DHRr, + { + if ((0 == + memcmp(&t->unverified_ax->DHRr, &msg->ratchet_key, - sizeof (msg->ratchet_key))) && - (0 == - memcmp (&t->unverified_ax->last_ephemeral, + sizeof(msg->ratchet_key))) && + (0 == + memcmp(&t->unverified_ax->last_ephemeral, &msg->ephemeral_key, - sizeof (msg->ephemeral_key))) ) - { - GNUNET_STATISTICS_update (stats, - "# Duplicate unverified KX received", - 1, - GNUNET_NO); + sizeof(msg->ephemeral_key)))) + { + GNUNET_STATISTICS_update(stats, + "# Duplicate unverified KX received", + 1, + GNUNET_NO); #if 1 - send_kx_auth (t, - ct, - t->unverified_ax, - GNUNET_NO); - return; + send_kx_auth(t, + ct, + t->unverified_ax, + GNUNET_NO); + return; #endif + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Dropping old unverified KX state.\n"); + GNUNET_STATISTICS_update(stats, + "# Unverified KX dropped for fresh KX", + 1, + GNUNET_NO); + GNUNET_break(NULL == t->unverified_ax->skipped_head); + memset(t->unverified_ax, + 0, + sizeof(struct CadetTunnelAxolotl)); } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Dropping old unverified KX state.\n"); - GNUNET_STATISTICS_update (stats, - "# Unverified KX dropped for fresh KX", - 1, - GNUNET_NO); - GNUNET_break (NULL == t->unverified_ax->skipped_head); - memset (t->unverified_ax, - 0, - sizeof (struct CadetTunnelAxolotl)); - } else - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Creating fresh unverified KX for %s\n", - GCT_2s (t)); - GNUNET_STATISTICS_update (stats, - "# Fresh KX setup", - 1, - GNUNET_NO); - t->unverified_ax = GNUNET_new (struct CadetTunnelAxolotl); - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Creating fresh unverified KX for %s\n", + GCT_2s(t)); + GNUNET_STATISTICS_update(stats, + "# Fresh KX setup", + 1, + GNUNET_NO); + t->unverified_ax = GNUNET_new(struct CadetTunnelAxolotl); + } /* Set as the 'current' RK/DHRr the one we are currently using, so that the duplicate-detection logic of - #update_ax_by_kx can work. */ + #update_ax_by_kx can work. */ t->unverified_ax->RK = t->ax.RK; t->unverified_ax->DHRr = t->ax.DHRr; t->unverified_ax->DHRs = t->ax.DHRs; @@ -1812,101 +1815,101 @@ GCT_handle_kx (struct CadetTConnection *ct, t->unverified_attempts = 0; /* Update 'ax' by the new key material */ - ret = update_ax_by_kx (t->unverified_ax, - GCP_get_id (t->destination), - &msg->ephemeral_key, - &msg->ratchet_key); - GNUNET_break (GNUNET_SYSERR != ret); + ret = update_ax_by_kx(t->unverified_ax, + GCP_get_id(t->destination), + &msg->ephemeral_key, + &msg->ratchet_key); + GNUNET_break(GNUNET_SYSERR != ret); if (GNUNET_OK != ret) - { - GNUNET_STATISTICS_update (stats, - "# Useless KX", - 1, - GNUNET_NO); - return; /* duplicate KX, nothing to do */ - } + { + GNUNET_STATISTICS_update(stats, + "# Useless KX", + 1, + GNUNET_NO); + return; /* duplicate KX, nothing to do */ + } /* move ahead in our state machine */ if (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) - GCT_change_estate (t, - CADET_TUNNEL_KEY_AX_RECV); + GCT_change_estate(t, + CADET_TUNNEL_KEY_AX_RECV); else if (CADET_TUNNEL_KEY_AX_SENT == t->estate) - GCT_change_estate (t, - CADET_TUNNEL_KEY_AX_SENT_AND_RECV); + GCT_change_estate(t, + CADET_TUNNEL_KEY_AX_SENT_AND_RECV); /* KX is still not done, try again our end. */ if (CADET_TUNNEL_KEY_OK != t->estate) - { - if (NULL != t->kx_task) - GNUNET_SCHEDULER_cancel (t->kx_task); - t->kx_task - = GNUNET_SCHEDULER_add_now (&retry_kx, - t); - } + { + if (NULL != t->kx_task) + GNUNET_SCHEDULER_cancel(t->kx_task); + t->kx_task + = GNUNET_SCHEDULER_add_now(&retry_kx, + t); + } } #if DEBUG_KX static void -check_ee (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1, - const struct GNUNET_CRYPTO_EcdhePrivateKey *e2) +check_ee(const struct GNUNET_CRYPTO_EcdhePrivateKey *e1, + const struct GNUNET_CRYPTO_EcdhePrivateKey *e2) { struct GNUNET_CRYPTO_EcdhePublicKey p1; struct GNUNET_CRYPTO_EcdhePublicKey p2; struct GNUNET_HashCode hc1; struct GNUNET_HashCode hc2; - GNUNET_CRYPTO_ecdhe_key_get_public (e1, - &p1); - GNUNET_CRYPTO_ecdhe_key_get_public (e2, - &p2); - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_ecc_ecdh (e1, - &p2, - &hc1)); - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_ecc_ecdh (e2, - &p1, - &hc2)); - GNUNET_break (0 == GNUNET_memcmp (&hc1, - &hc2)); + GNUNET_CRYPTO_ecdhe_key_get_public(e1, + &p1); + GNUNET_CRYPTO_ecdhe_key_get_public(e2, + &p2); + GNUNET_assert(GNUNET_OK == + GNUNET_CRYPTO_ecc_ecdh(e1, + &p2, + &hc1)); + GNUNET_assert(GNUNET_OK == + GNUNET_CRYPTO_ecc_ecdh(e2, + &p1, + &hc2)); + GNUNET_break(0 == GNUNET_memcmp(&hc1, + &hc2)); } static void -check_ed (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1, - const struct GNUNET_CRYPTO_EddsaPrivateKey *e2) +check_ed(const struct GNUNET_CRYPTO_EcdhePrivateKey *e1, + const struct GNUNET_CRYPTO_EddsaPrivateKey *e2) { struct GNUNET_CRYPTO_EcdhePublicKey p1; struct GNUNET_CRYPTO_EddsaPublicKey p2; struct GNUNET_HashCode hc1; struct GNUNET_HashCode hc2; - GNUNET_CRYPTO_ecdhe_key_get_public (e1, - &p1); - GNUNET_CRYPTO_eddsa_key_get_public (e2, - &p2); - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_ecdh_eddsa (e1, - &p2, - &hc1)); - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_eddsa_ecdh (e2, - &p1, - &hc2)); - GNUNET_break (0 == GNUNET_memcmp (&hc1, - &hc2)); + GNUNET_CRYPTO_ecdhe_key_get_public(e1, + &p1); + GNUNET_CRYPTO_eddsa_key_get_public(e2, + &p2); + GNUNET_assert(GNUNET_OK == + GNUNET_CRYPTO_ecdh_eddsa(e1, + &p2, + &hc1)); + GNUNET_assert(GNUNET_OK == + GNUNET_CRYPTO_eddsa_ecdh(e2, + &p1, + &hc2)); + GNUNET_break(0 == GNUNET_memcmp(&hc1, + &hc2)); } static void -test_crypto_bug (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1, - const struct GNUNET_CRYPTO_EcdhePrivateKey *e2, - const struct GNUNET_CRYPTO_EddsaPrivateKey *d1, - const struct GNUNET_CRYPTO_EddsaPrivateKey *d2) +test_crypto_bug(const struct GNUNET_CRYPTO_EcdhePrivateKey *e1, + const struct GNUNET_CRYPTO_EcdhePrivateKey *e2, + const struct GNUNET_CRYPTO_EddsaPrivateKey *d1, + const struct GNUNET_CRYPTO_EddsaPrivateKey *d2) { - check_ee (e1, e2); - check_ed (e1, d2); - check_ed (e2, d1); + check_ee(e1, e2); + check_ed(e1, d2); + check_ed(e2, d1); } #endif @@ -1919,133 +1922,135 @@ test_crypto_bug (const struct GNUNET_CRYPTO_EcdhePrivateKey *e1, * @param msg the key exchange message */ void -GCT_handle_kx_auth (struct CadetTConnection *ct, - const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg) +GCT_handle_kx_auth(struct CadetTConnection *ct, + const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg) { struct CadetTunnel *t = ct->t; struct CadetTunnelAxolotl ax_tmp; struct GNUNET_HashCode kx_auth; int ret; - GNUNET_STATISTICS_update (stats, - "# KX_AUTH received", - 1, - GNUNET_NO); - if ( (CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) || - (CADET_TUNNEL_KEY_AX_RECV == t->estate) ) - { - /* Confusing, we got a KX_AUTH before we even send our own - KX. This should not happen. We'll send our own KX ASAP anyway, - so let's ignore this here. */ - GNUNET_break_op (0); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Handling KX_AUTH message from %s with ephemeral %s\n", - GCT_2s (t), - GNUNET_e2s (&msg->kx.ephemeral_key)); + GNUNET_STATISTICS_update(stats, + "# KX_AUTH received", + 1, + GNUNET_NO); + if ((CADET_TUNNEL_KEY_UNINITIALIZED == t->estate) || + (CADET_TUNNEL_KEY_AX_RECV == t->estate)) + { + /* Confusing, we got a KX_AUTH before we even send our own + KX. This should not happen. We'll send our own KX ASAP anyway, + so let's ignore this here. */ + GNUNET_break_op(0); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Handling KX_AUTH message from %s with ephemeral %s\n", + GCT_2s(t), + GNUNET_e2s(&msg->kx.ephemeral_key)); /* We do everything in ax_tmp until we've checked the authentication so we don't clobber anything we care about by accident. */ ax_tmp = t->ax; /* Update 'ax' by the new key material */ - ret = update_ax_by_kx (&ax_tmp, - GCP_get_id (t->destination), - &msg->kx.ephemeral_key, - &msg->kx.ratchet_key); + ret = update_ax_by_kx(&ax_tmp, + GCP_get_id(t->destination), + &msg->kx.ephemeral_key, + &msg->kx.ratchet_key); if (GNUNET_OK != ret) - { - if (GNUNET_NO == ret) - GNUNET_STATISTICS_update (stats, - "# redundant KX_AUTH received", - 1, - GNUNET_NO); - else - GNUNET_break (0); /* connect to self!? */ - return; - } - GNUNET_CRYPTO_hash (&ax_tmp.RK, - sizeof (ax_tmp.RK), - &kx_auth); - if (0 != GNUNET_memcmp (&kx_auth, - &msg->auth)) - { - /* This KX_AUTH is not using the latest KX/KX_AUTH data - we transmitted to the sender, refuse it, try KX again. */ - GNUNET_STATISTICS_update (stats, - "# KX_AUTH not using our last KX received (auth failure)", - 1, - GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_WARNING, - "KX AUTH mismatch!\n"); -#if DEBUG_KX { - struct GNUNET_CRYPTO_EcdhePublicKey ephemeral_key; - - GNUNET_CRYPTO_ecdhe_key_get_public (&ax_tmp.kx_0, - &ephemeral_key); - if (0 != GNUNET_memcmp (&ephemeral_key, - &msg->r_ephemeral_key_XXX)) - { - LOG (GNUNET_ERROR_TYPE_WARNING, - "My ephemeral is %s!\n", - GNUNET_e2s (&ephemeral_key)); - LOG (GNUNET_ERROR_TYPE_WARNING, - "Response is for ephemeral %s!\n", - GNUNET_e2s (&msg->r_ephemeral_key_XXX)); - } + if (GNUNET_NO == ret) + GNUNET_STATISTICS_update(stats, + "# redundant KX_AUTH received", + 1, + GNUNET_NO); else + GNUNET_break(0); /* connect to self!? */ + return; + } + GNUNET_CRYPTO_hash(&ax_tmp.RK, + sizeof(ax_tmp.RK), + &kx_auth); + if (0 != GNUNET_memcmp(&kx_auth, + &msg->auth)) + { + /* This KX_AUTH is not using the latest KX/KX_AUTH data + we transmitted to the sender, refuse it, try KX again. */ + GNUNET_STATISTICS_update(stats, + "# KX_AUTH not using our last KX received (auth failure)", + 1, + GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_WARNING, + "KX AUTH mismatch!\n"); +#if DEBUG_KX { - test_crypto_bug (&ax_tmp.kx_0, - &msg->kx.ephemeral_key_XXX, - my_private_key, - &msg->kx.private_key_XXX); + struct GNUNET_CRYPTO_EcdhePublicKey ephemeral_key; + + GNUNET_CRYPTO_ecdhe_key_get_public(&ax_tmp.kx_0, + &ephemeral_key); + if (0 != GNUNET_memcmp(&ephemeral_key, + &msg->r_ephemeral_key_XXX)) + { + LOG(GNUNET_ERROR_TYPE_WARNING, + "My ephemeral is %s!\n", + GNUNET_e2s(&ephemeral_key)); + LOG(GNUNET_ERROR_TYPE_WARNING, + "Response is for ephemeral %s!\n", + GNUNET_e2s(&msg->r_ephemeral_key_XXX)); + } + else + { + test_crypto_bug(&ax_tmp.kx_0, + &msg->kx.ephemeral_key_XXX, + my_private_key, + &msg->kx.private_key_XXX); + } } - } #endif - if (NULL == t->kx_task) - t->kx_task - = GNUNET_SCHEDULER_add_at (t->next_kx_attempt, - &retry_kx, - t); - return; - } + if (NULL == t->kx_task) + t->kx_task + = GNUNET_SCHEDULER_add_at(t->next_kx_attempt, + &retry_kx, + t); + return; + } /* Yep, we're good. */ t->ax = ax_tmp; if (NULL != t->unverified_ax) - { - /* We got some "stale" KX before, drop that. */ - cleanup_ax (t->unverified_ax); - GNUNET_free (t->unverified_ax); - t->unverified_ax = NULL; - } + { + /* We got some "stale" KX before, drop that. */ + cleanup_ax(t->unverified_ax); + GNUNET_free(t->unverified_ax); + t->unverified_ax = NULL; + } /* move ahead in our state machine */ switch (t->estate) - { - case CADET_TUNNEL_KEY_UNINITIALIZED: - case CADET_TUNNEL_KEY_AX_RECV: - /* Checked above, this is impossible. */ - GNUNET_assert (0); - break; - case CADET_TUNNEL_KEY_AX_SENT: /* This is the normal case */ - case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */ - case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */ - GCT_change_estate (t, - CADET_TUNNEL_KEY_OK); - break; - case CADET_TUNNEL_KEY_OK: - /* Did not expect another KX_AUTH, but so what, still acceptable. - Nothing to do here. */ - break; - } - if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl (msg->kx.flags))) - { - send_kx_auth (t, - NULL, - &t->ax, - GNUNET_NO); - } + { + case CADET_TUNNEL_KEY_UNINITIALIZED: + case CADET_TUNNEL_KEY_AX_RECV: + /* Checked above, this is impossible. */ + GNUNET_assert(0); + break; + + case CADET_TUNNEL_KEY_AX_SENT: /* This is the normal case */ + case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: /* both peers started KX */ + case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* both peers now did KX_AUTH */ + GCT_change_estate(t, + CADET_TUNNEL_KEY_OK); + break; + + case CADET_TUNNEL_KEY_OK: + /* Did not expect another KX_AUTH, but so what, still acceptable. + Nothing to do here. */ + break; + } + if (0 != (GNUNET_CADET_KX_FLAG_FORCE_REPLY & ntohl(msg->kx.flags))) + { + send_kx_auth(t, + NULL, + &t->ax, + GNUNET_NO); + } } @@ -2060,7 +2065,7 @@ GCT_handle_kx_auth (struct CadetTConnection *ct, * @return unused number that can uniquely identify a channel in the tunnel */ static struct GNUNET_CADET_ChannelTunnelNumber -get_next_free_ctn (struct CadetTunnel *t) +get_next_free_ctn(struct CadetTunnel *t) { #define HIGH_BIT 0x8000000 struct GNUNET_CADET_ChannelTunnelNumber ret; @@ -2068,23 +2073,23 @@ get_next_free_ctn (struct CadetTunnel *t) int cmp; uint32_t highbit; - cmp = GNUNET_memcmp (&my_full_id, - GCP_get_id (GCT_get_destination (t))); + cmp = GNUNET_memcmp(&my_full_id, + GCP_get_id(GCT_get_destination(t))); if (0 < cmp) highbit = HIGH_BIT; else if (0 > cmp) highbit = 0; else - GNUNET_assert (0); // loopback must never go here! - ctn = ntohl (t->next_ctn.cn); + GNUNET_assert(0); // loopback must never go here! + ctn = ntohl(t->next_ctn.cn); while (NULL != - GNUNET_CONTAINER_multihashmap32_get (t->channels, - ctn | highbit)) - { - ctn = ((ctn + 1) & (~ HIGH_BIT)); - } - t->next_ctn.cn = htonl ((ctn + 1) & (~ HIGH_BIT)); - ret.cn = htonl (ctn | highbit); + GNUNET_CONTAINER_multihashmap32_get(t->channels, + ctn | highbit)) + { + ctn = ((ctn + 1) & (~HIGH_BIT)); + } + t->next_ctn.cn = htonl((ctn + 1) & (~HIGH_BIT)); + ret.cn = htonl(ctn | highbit); return ret; } @@ -2099,50 +2104,53 @@ get_next_free_ctn (struct CadetTunnel *t) * @return unique number identifying @a ch within @a t */ struct GNUNET_CADET_ChannelTunnelNumber -GCT_add_channel (struct CadetTunnel *t, - struct CadetChannel *ch) +GCT_add_channel(struct CadetTunnel *t, + struct CadetChannel *ch) { struct GNUNET_CADET_ChannelTunnelNumber ctn; - ctn = get_next_free_ctn (t); + ctn = get_next_free_ctn(t); if (NULL != t->destroy_task) - { - GNUNET_SCHEDULER_cancel (t->destroy_task); - t->destroy_task = NULL; - } - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap32_put (t->channels, - ntohl (ctn.cn), - ch, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Adding %s to %s\n", - GCCH_2s (ch), - GCT_2s (t)); + { + GNUNET_SCHEDULER_cancel(t->destroy_task); + t->destroy_task = NULL; + } + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap32_put(t->channels, + ntohl(ctn.cn), + ch, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Adding %s to %s\n", + GCCH_2s(ch), + GCT_2s(t)); switch (t->estate) - { - case CADET_TUNNEL_KEY_UNINITIALIZED: - /* waiting for connection to start KX */ - break; - case CADET_TUNNEL_KEY_AX_RECV: - case CADET_TUNNEL_KEY_AX_SENT: - case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: - /* we're currently waiting for KX to complete */ - break; - case CADET_TUNNEL_KEY_AX_AUTH_SENT: - /* waiting for OTHER peer to send us data, - we might need to prompt more aggressively! */ - if (NULL == t->kx_task) - t->kx_task - = GNUNET_SCHEDULER_add_at (t->next_kx_attempt, - &retry_kx, - t); - break; - case CADET_TUNNEL_KEY_OK: - /* We are ready. Tell the new channel that we are up. */ - GCCH_tunnel_up (ch); - break; - } + { + case CADET_TUNNEL_KEY_UNINITIALIZED: + /* waiting for connection to start KX */ + break; + + case CADET_TUNNEL_KEY_AX_RECV: + case CADET_TUNNEL_KEY_AX_SENT: + case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: + /* we're currently waiting for KX to complete */ + break; + + case CADET_TUNNEL_KEY_AX_AUTH_SENT: + /* waiting for OTHER peer to send us data, + we might need to prompt more aggressively! */ + if (NULL == t->kx_task) + t->kx_task + = GNUNET_SCHEDULER_add_at(t->next_kx_attempt, + &retry_kx, + t); + break; + + case CADET_TUNNEL_KEY_OK: + /* We are ready. Tell the new channel that we are up. */ + GCCH_tunnel_up(ch); + break; + } return ctn; } @@ -2154,25 +2162,25 @@ GCT_add_channel (struct CadetTunnel *t, * @param ct binding of connection to tunnel of the connection that was lost. */ void -GCT_connection_lost (struct CadetTConnection *ct) +GCT_connection_lost(struct CadetTConnection *ct) { struct CadetTunnel *t = ct->t; if (GNUNET_YES == ct->is_ready) - { - GNUNET_CONTAINER_DLL_remove (t->connection_ready_head, - t->connection_ready_tail, - ct); - t->num_ready_connections--; - } + { + GNUNET_CONTAINER_DLL_remove(t->connection_ready_head, + t->connection_ready_tail, + ct); + t->num_ready_connections--; + } else - { - GNUNET_CONTAINER_DLL_remove (t->connection_busy_head, - t->connection_busy_tail, - ct); - t->num_busy_connections--; - } - GNUNET_free (ct); + { + GNUNET_CONTAINER_DLL_remove(t->connection_busy_head, + t->connection_busy_tail, + ct); + t->num_busy_connections--; + } + GNUNET_free(ct); } @@ -2183,15 +2191,15 @@ GCT_connection_lost (struct CadetTConnection *ct) * @param ct connection to clean up */ static void -destroy_t_connection (void *cls, - struct CadetTConnection *ct) +destroy_t_connection(void *cls, + struct CadetTConnection *ct) { struct CadetTunnel *t = cls; struct CadetConnection *cc = ct->cc; - GNUNET_assert (ct->t == t); - GCT_connection_lost (ct); - GCC_destroy_without_tunnel (cc); + GNUNET_assert(ct->t == t); + GCT_connection_lost(ct); + GCC_destroy_without_tunnel(cc); } @@ -2201,56 +2209,56 @@ destroy_t_connection (void *cls, * @param cls the idle tunnel */ static void -destroy_tunnel (void *cls) +destroy_tunnel(void *cls) { struct CadetTunnel *t = cls; struct CadetTunnelQueueEntry *tq; t->destroy_task = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Destroying idle %s\n", - GCT_2s (t)); - GNUNET_assert (0 == GCT_count_channels (t)); - GCT_iterate_connections (t, - &destroy_t_connection, - t); - GNUNET_assert (NULL == t->connection_ready_head); - GNUNET_assert (NULL == t->connection_busy_head); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Destroying idle %s\n", + GCT_2s(t)); + GNUNET_assert(0 == GCT_count_channels(t)); + GCT_iterate_connections(t, + &destroy_t_connection, + t); + GNUNET_assert(NULL == t->connection_ready_head); + GNUNET_assert(NULL == t->connection_busy_head); while (NULL != (tq = t->tq_head)) - { - if (NULL != tq->cont) - tq->cont (tq->cont_cls, - NULL); - GCT_send_cancel (tq); - } - GCP_drop_tunnel (t->destination, - t); - GNUNET_CONTAINER_multihashmap32_destroy (t->channels); + { + if (NULL != tq->cont) + tq->cont(tq->cont_cls, + NULL); + GCT_send_cancel(tq); + } + GCP_drop_tunnel(t->destination, + t); + GNUNET_CONTAINER_multihashmap32_destroy(t->channels); if (NULL != t->maintain_connections_task) - { - GNUNET_SCHEDULER_cancel (t->maintain_connections_task); - t->maintain_connections_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(t->maintain_connections_task); + t->maintain_connections_task = NULL; + } if (NULL != t->send_task) - { - GNUNET_SCHEDULER_cancel (t->send_task); - t->send_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(t->send_task); + t->send_task = NULL; + } if (NULL != t->kx_task) - { - GNUNET_SCHEDULER_cancel (t->kx_task); - t->kx_task = NULL; - } - GNUNET_MST_destroy (t->mst); - GNUNET_MQ_destroy (t->mq); + { + GNUNET_SCHEDULER_cancel(t->kx_task); + t->kx_task = NULL; + } + GNUNET_MST_destroy(t->mst); + GNUNET_MQ_destroy(t->mq); if (NULL != t->unverified_ax) - { - cleanup_ax (t->unverified_ax); - GNUNET_free (t->unverified_ax); - } - cleanup_ax (&t->ax); - GNUNET_assert (NULL == t->destroy_task); - GNUNET_free (t); + { + cleanup_ax(t->unverified_ax); + GNUNET_free(t->unverified_ax); + } + cleanup_ax(&t->ax); + GNUNET_assert(NULL == t->destroy_task); + GNUNET_free(t); } @@ -2262,27 +2270,27 @@ destroy_tunnel (void *cls) * @param ctn unique number identifying @a ch within @a t */ void -GCT_remove_channel (struct CadetTunnel *t, - struct CadetChannel *ch, - struct GNUNET_CADET_ChannelTunnelNumber ctn) -{ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Removing %s from %s\n", - GCCH_2s (ch), - GCT_2s (t)); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap32_remove (t->channels, - ntohl (ctn.cn), - ch)); - if ( (0 == - GCT_count_channels (t)) && - (NULL == t->destroy_task) ) - { - t->destroy_task - = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY, - &destroy_tunnel, - t); - } +GCT_remove_channel(struct CadetTunnel *t, + struct CadetChannel *ch, + struct GNUNET_CADET_ChannelTunnelNumber ctn) +{ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Removing %s from %s\n", + GCCH_2s(ch), + GCT_2s(t)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap32_remove(t->channels, + ntohl(ctn.cn), + ch)); + if ((0 == + GCT_count_channels(t)) && + (NULL == t->destroy_task)) + { + t->destroy_task + = GNUNET_SCHEDULER_add_delayed(IDLE_DESTROY_DELAY, + &destroy_tunnel, + t); + } } @@ -2295,14 +2303,14 @@ GCT_remove_channel (struct CadetTunnel *t, * @return #GNUNET_OK (continue to iterate) */ static int -destroy_remaining_channels (void *cls, - uint32_t key, - void *value) +destroy_remaining_channels(void *cls, + uint32_t key, + void *value) { struct CadetChannel *ch = value; - GCCH_handle_remote_destroy (ch, - NULL); + GCCH_handle_remote_destroy(ch, + NULL); return GNUNET_OK; } @@ -2313,20 +2321,20 @@ destroy_remaining_channels (void *cls, * @param t tunnel to destroy */ void -GCT_destroy_tunnel_now (struct CadetTunnel *t) -{ - GNUNET_assert (GNUNET_YES == shutting_down); - GNUNET_CONTAINER_multihashmap32_iterate (t->channels, - &destroy_remaining_channels, - t); - GNUNET_assert (0 == - GCT_count_channels (t)); +GCT_destroy_tunnel_now(struct CadetTunnel *t) +{ + GNUNET_assert(GNUNET_YES == shutting_down); + GNUNET_CONTAINER_multihashmap32_iterate(t->channels, + &destroy_remaining_channels, + t); + GNUNET_assert(0 == + GCT_count_channels(t)); if (NULL != t->destroy_task) - { - GNUNET_SCHEDULER_cancel (t->destroy_task); - t->destroy_task = NULL; - } - destroy_tunnel (t); + { + GNUNET_SCHEDULER_cancel(t->destroy_task); + t->destroy_task = NULL; + } + destroy_tunnel(t); } @@ -2338,40 +2346,40 @@ GCT_destroy_tunnel_now (struct CadetTunnel *t) * @param ct connection to use for transmission (is ready) */ static void -try_send_normal_payload (struct CadetTunnel *t, - struct CadetTConnection *ct) +try_send_normal_payload(struct CadetTunnel *t, + struct CadetTConnection *ct) { struct CadetTunnelQueueEntry *tq; - GNUNET_assert (GNUNET_YES == ct->is_ready); + GNUNET_assert(GNUNET_YES == ct->is_ready); tq = t->tq_head; if (NULL == tq) - { - /* no messages pending right now */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Not sending payload of %s on ready %s (nothing pending)\n", - GCT_2s (t), - GCC_2s (ct->cc)); - return; - } + { + /* no messages pending right now */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Not sending payload of %s on ready %s (nothing pending)\n", + GCT_2s(t), + GCC_2s(ct->cc)); + return; + } /* ready to send message 'tq' on tunnel 'ct' */ - GNUNET_assert (t == tq->t); - GNUNET_CONTAINER_DLL_remove (t->tq_head, - t->tq_tail, - tq); + GNUNET_assert(t == tq->t); + GNUNET_CONTAINER_DLL_remove(t->tq_head, + t->tq_tail, + tq); if (NULL != tq->cid) - *tq->cid = *GCC_get_id (ct->cc); - mark_connection_unready (ct); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending payload of %s on %s\n", - GCT_2s (t), - GCC_2s (ct->cc)); - GCC_transmit (ct->cc, - tq->env); + *tq->cid = *GCC_get_id(ct->cc); + mark_connection_unready(ct); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending payload of %s on %s\n", + GCT_2s(t), + GCC_2s(ct->cc)); + GCC_transmit(ct->cc, + tq->env); if (NULL != tq->cont) - tq->cont (tq->cont_cls, - GCC_get_id (ct->cc)); - GNUNET_free (tq); + tq->cont(tq->cont_cls, + GCC_get_id(ct->cc)); + GNUNET_free(tq); } @@ -2384,95 +2392,97 @@ try_send_normal_payload (struct CadetTunnel *t, * #GNUNET_NO if connection are no longer ready */ static void -connection_ready_cb (void *cls, - int is_ready) +connection_ready_cb(void *cls, + int is_ready) { struct CadetTConnection *ct = cls; struct CadetTunnel *t = ct->t; if (GNUNET_NO == is_ready) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "%s no longer ready for %s\n", - GCC_2s (ct->cc), - GCT_2s (t)); - mark_connection_unready (ct); - return; - } - GNUNET_assert (GNUNET_NO == ct->is_ready); - GNUNET_CONTAINER_DLL_remove (t->connection_busy_head, - t->connection_busy_tail, - ct); - GNUNET_assert (0 < t->num_busy_connections); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "%s no longer ready for %s\n", + GCC_2s(ct->cc), + GCT_2s(t)); + mark_connection_unready(ct); + return; + } + GNUNET_assert(GNUNET_NO == ct->is_ready); + GNUNET_CONTAINER_DLL_remove(t->connection_busy_head, + t->connection_busy_tail, + ct); + GNUNET_assert(0 < t->num_busy_connections); t->num_busy_connections--; ct->is_ready = GNUNET_YES; - GNUNET_CONTAINER_DLL_insert_tail (t->connection_ready_head, - t->connection_ready_tail, - ct); + GNUNET_CONTAINER_DLL_insert_tail(t->connection_ready_head, + t->connection_ready_tail, + ct); t->num_ready_connections++; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "%s now ready for %s in state %s\n", - GCC_2s (ct->cc), - GCT_2s (t), - estate2s (t->estate)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "%s now ready for %s in state %s\n", + GCC_2s(ct->cc), + GCT_2s(t), + estate2s(t->estate)); switch (t->estate) - { - case CADET_TUNNEL_KEY_UNINITIALIZED: - /* Do not begin KX if WE have no channels waiting! */ - if (0 != GNUNET_TIME_absolute_get_remaining (t->next_kx_attempt).rel_value_us) - return; /* wait for timeout before retrying */ - /* We are uninitialized, just transmit immediately, - without undue delay. */ - if (NULL != t->kx_task) - { - GNUNET_SCHEDULER_cancel (t->kx_task); - t->kx_task = NULL; - } - send_kx (t, - ct, - &t->ax); - if ( (0 == - GCT_count_channels (t)) && - (NULL == t->destroy_task) ) - { - t->destroy_task - = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY, - &destroy_tunnel, - t); - } - break; - case CADET_TUNNEL_KEY_AX_RECV: - case CADET_TUNNEL_KEY_AX_SENT: - case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: - case CADET_TUNNEL_KEY_AX_AUTH_SENT: - /* we're currently waiting for KX to complete, schedule job */ - if (NULL == t->kx_task) - t->kx_task - = GNUNET_SCHEDULER_add_at (t->next_kx_attempt, - &retry_kx, - t); - break; - case CADET_TUNNEL_KEY_OK: - if (GNUNET_YES == t->kx_auth_requested) { - if (0 != GNUNET_TIME_absolute_get_remaining (t->next_kx_attempt).rel_value_us) - return; /* wait for timeout */ + case CADET_TUNNEL_KEY_UNINITIALIZED: + /* Do not begin KX if WE have no channels waiting! */ + if (0 != GNUNET_TIME_absolute_get_remaining(t->next_kx_attempt).rel_value_us) + return; /* wait for timeout before retrying */ + /* We are uninitialized, just transmit immediately, + without undue delay. */ if (NULL != t->kx_task) - { - GNUNET_SCHEDULER_cancel (t->kx_task); - t->kx_task = NULL; - } - send_kx_auth (t, - ct, - &t->ax, - GNUNET_NO); - return; + { + GNUNET_SCHEDULER_cancel(t->kx_task); + t->kx_task = NULL; + } + send_kx(t, + ct, + &t->ax); + if ((0 == + GCT_count_channels(t)) && + (NULL == t->destroy_task)) + { + t->destroy_task + = GNUNET_SCHEDULER_add_delayed(IDLE_DESTROY_DELAY, + &destroy_tunnel, + t); + } + break; + + case CADET_TUNNEL_KEY_AX_RECV: + case CADET_TUNNEL_KEY_AX_SENT: + case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: + case CADET_TUNNEL_KEY_AX_AUTH_SENT: + /* we're currently waiting for KX to complete, schedule job */ + if (NULL == t->kx_task) + t->kx_task + = GNUNET_SCHEDULER_add_at(t->next_kx_attempt, + &retry_kx, + t); + break; + + case CADET_TUNNEL_KEY_OK: + if (GNUNET_YES == t->kx_auth_requested) + { + if (0 != GNUNET_TIME_absolute_get_remaining(t->next_kx_attempt).rel_value_us) + return; /* wait for timeout */ + if (NULL != t->kx_task) + { + GNUNET_SCHEDULER_cancel(t->kx_task); + t->kx_task = NULL; + } + send_kx_auth(t, + ct, + &t->ax, + GNUNET_NO); + return; + } + try_send_normal_payload(t, + ct); + break; } - try_send_normal_payload (t, - ct); - break; - } } @@ -2485,7 +2495,7 @@ connection_ready_cb (void *cls, * @param cls the `struct CadetTunnel` to process messages on */ static void -trigger_transmissions (void *cls) +trigger_transmissions(void *cls) { struct CadetTunnel *t = cls; struct CadetTConnection *ct; @@ -2493,11 +2503,11 @@ trigger_transmissions (void *cls) t->send_task = NULL; if (NULL == t->tq_head) return; /* no messages pending right now */ - ct = get_ready_connection (t); + ct = get_ready_connection(t); if (NULL == ct) return; /* no connections ready */ - try_send_normal_payload (t, - ct); + try_send_normal_payload(t, + ct); } @@ -2505,9 +2515,7 @@ trigger_transmissions (void *cls) * Closure for #evaluate_connection. Used to assemble summary information * about the existing connections so we can evaluate a new path. */ -struct EvaluationSummary -{ - +struct EvaluationSummary { /** * Minimum length of any of our connections, `UINT_MAX` if we have none. */ @@ -2548,7 +2556,6 @@ struct EvaluationSummary * Set to #GNUNET_YES if we have a connection over @e path already. */ int duplicate; - }; @@ -2560,8 +2567,8 @@ struct EvaluationSummary * @param ct a connection to include in the summary */ static void -evaluate_connection (void *cls, - struct CadetTConnection *ct) +evaluate_connection(void *cls, + struct CadetTConnection *ct) { struct EvaluationSummary *es = cls; struct CadetConnection *cc = ct->cc; @@ -2574,79 +2581,79 @@ evaluate_connection (void *cls, double score; double success_rate; - ps = GCC_get_path (cc, - &ct_length); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Evaluating path %s of existing %s\n", - GCPP_2s (ps), - GCC_2s (cc)); + ps = GCC_get_path(cc, + &ct_length); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Evaluating path %s of existing %s\n", + GCPP_2s(ps), + GCC_2s(cc)); if (ps == es->path) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ignoring duplicate path %s.\n", - GCPP_2s (es->path)); - es->duplicate = GNUNET_YES; - return; - } - if (NULL != es->path) - { - int duplicate = GNUNET_YES; - - for (unsigned int i=0;ipath) > i); - if (GCPP_get_peer_at_offset (es->path, - i) != - GCPP_get_peer_at_offset (ps, - i)) - { - duplicate = GNUNET_NO; - break; - } - } - if (GNUNET_YES == duplicate) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ignoring overlapping path %s.\n", - GCPP_2s (es->path)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ignoring duplicate path %s.\n", + GCPP_2s(es->path)); es->duplicate = GNUNET_YES; return; } - else + if (NULL != es->path) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Known path %s differs from proposed path\n", - GCPP_2s (ps)); + int duplicate = GNUNET_YES; + + for (unsigned int i = 0; i < ct_length; i++) + { + GNUNET_assert(GCPP_get_length(es->path) > i); + if (GCPP_get_peer_at_offset(es->path, + i) != + GCPP_get_peer_at_offset(ps, + i)) + { + duplicate = GNUNET_NO; + break; + } + } + if (GNUNET_YES == duplicate) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ignoring overlapping path %s.\n", + GCPP_2s(es->path)); + es->duplicate = GNUNET_YES; + return; + } + else + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Known path %s differs from proposed path\n", + GCPP_2s(ps)); + } } - } - ct_desirability = GCPP_get_desirability (ps); - metrics = GCC_get_metrics (cc); - uptime = GNUNET_TIME_absolute_get_duration (metrics->age); - last_use = GNUNET_TIME_absolute_get_duration (metrics->last_use); + ct_desirability = GCPP_get_desirability(ps); + metrics = GCC_get_metrics(cc); + uptime = GNUNET_TIME_absolute_get_duration(metrics->age); + last_use = GNUNET_TIME_absolute_get_duration(metrics->last_use); /* We add 1.0 here to avoid division by zero. */ success_rate = (metrics->num_acked_transmissions + 1.0) / (metrics->num_successes + 1.0); score = ct_desirability - + 100.0 / (1.0 + ct_length) /* longer paths = better */ - + sqrt (uptime.rel_value_us / 60000000LL) /* larger uptime = better */ - - last_use.rel_value_us / 1000L; /* longer idle = worse */ + + 100.0 / (1.0 + ct_length) /* longer paths = better */ + + sqrt(uptime.rel_value_us / 60000000LL) /* larger uptime = better */ + - last_use.rel_value_us / 1000L; /* longer idle = worse */ score *= success_rate; /* weigh overall by success rate */ - if ( (NULL == es->worst) || - (score < es->worst_score) ) - { - es->worst = ct; - es->worst_score = score; - } - es->min_length = GNUNET_MIN (es->min_length, - ct_length); - es->max_length = GNUNET_MAX (es->max_length, - ct_length); - es->min_desire = GNUNET_MIN (es->min_desire, - ct_desirability); - es->max_desire = GNUNET_MAX (es->max_desire, - ct_desirability); + if ((NULL == es->worst) || + (score < es->worst_score)) + { + es->worst = ct; + es->worst_score = score; + } + es->min_length = GNUNET_MIN(es->min_length, + ct_length); + es->max_length = GNUNET_MAX(es->max_length, + ct_length); + es->min_desire = GNUNET_MIN(es->min_desire, + ct_desirability); + es->max_desire = GNUNET_MAX(es->max_desire, + ct_desirability); } @@ -2660,17 +2667,17 @@ evaluate_connection (void *cls, * @return #GNUNET_YES (should keep iterating) */ static int -consider_path_cb (void *cls, - struct CadetPeerPath *path, - unsigned int off) +consider_path_cb(void *cls, + struct CadetPeerPath *path, + unsigned int off) { struct CadetTunnel *t = cls; struct EvaluationSummary es; struct CadetTConnection *ct; - GNUNET_assert (off < GCPP_get_length (path)); - GNUNET_assert (GCPP_get_peer_at_offset (path, - off) == t->destination); + GNUNET_assert(off < GCPP_get_length(path)); + GNUNET_assert(GCPP_get_peer_at_offset(path, + off) == t->destination); es.min_length = UINT_MAX; es.max_length = 0; es.max_desire = 0; @@ -2680,16 +2687,16 @@ consider_path_cb (void *cls, es.worst = NULL; /* Compute evaluation summary over existing connections. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Evaluating proposed path %s for target %s\n", - GCPP_2s (path), - GCT_2s (t)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Evaluating proposed path %s for target %s\n", + GCPP_2s(path), + GCT_2s(t)); /* FIXME: suspect this does not ACTUALLY iterate over all existing paths, otherwise dup detection should work!!! */ - GCT_iterate_connections (t, - &evaluate_connection, - &es); + GCT_iterate_connections(t, + &evaluate_connection, + &es); if (GNUNET_YES == es.duplicate) return GNUNET_YES; @@ -2700,54 +2707,54 @@ consider_path_cb (void *cls, /* We iterate by increasing path length; if we have enough paths and this one is more than twice as long than what we are currently using, then ignore all of these super-long ones! */ - if ( (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) && - (es.min_length * 2 < off) && - (es.max_length < off) ) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ignoring paths of length %u, they are way too long.\n", - es.min_length * 2); - return GNUNET_NO; - } + if ((GCT_count_any_connections(t) > DESIRED_CONNECTIONS_PER_TUNNEL) && + (es.min_length * 2 < off) && + (es.max_length < off)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ignoring paths of length %u, they are way too long.\n", + es.min_length * 2); + return GNUNET_NO; + } /* If we have enough paths and this one looks no better, ignore it. */ - if ( (GCT_count_any_connections (t) >= DESIRED_CONNECTIONS_PER_TUNNEL) && - (es.min_length < GCPP_get_length (path)) && - (es.min_desire > GCPP_get_desirability (path)) && - (es.max_length < off) ) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ignoring path (%u/%llu) to %s, got something better already.\n", - GCPP_get_length (path), - (unsigned long long) GCPP_get_desirability (path), - GCP_2s (t->destination)); - return GNUNET_YES; - } + if ((GCT_count_any_connections(t) >= DESIRED_CONNECTIONS_PER_TUNNEL) && + (es.min_length < GCPP_get_length(path)) && + (es.min_desire > GCPP_get_desirability(path)) && + (es.max_length < off)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ignoring path (%u/%llu) to %s, got something better already.\n", + GCPP_get_length(path), + (unsigned long long)GCPP_get_desirability(path), + GCP_2s(t->destination)); + return GNUNET_YES; + } /* Path is interesting (better by some metric, or we don't have enough paths yet). */ - ct = GNUNET_new (struct CadetTConnection); - ct->created = GNUNET_TIME_absolute_get (); + ct = GNUNET_new(struct CadetTConnection); + ct->created = GNUNET_TIME_absolute_get(); ct->t = t; - ct->cc = GCC_create (t->destination, - path, - off, - ct, - &connection_ready_cb, - ct); + ct->cc = GCC_create(t->destination, + path, + off, + ct, + &connection_ready_cb, + ct); /* FIXME: schedule job to kill connection (and path?) if it takes too long to get ready! (And track performance data on how long other connections took with the tunnel!) => Note: to be done within 'connection'-logic! */ - GNUNET_CONTAINER_DLL_insert (t->connection_busy_head, - t->connection_busy_tail, - ct); + GNUNET_CONTAINER_DLL_insert(t->connection_busy_head, + t->connection_busy_tail, + ct); t->num_busy_connections++; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Found interesting path %s for %s, created %s\n", - GCPP_2s (path), - GCT_2s (t), - GCC_2s (ct->cc)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Found interesting path %s for %s, created %s\n", + GCPP_2s(path), + GCT_2s(t), + GCC_2s(ct->cc)); return GNUNET_YES; } @@ -2766,16 +2773,16 @@ consider_path_cb (void *cls, * @param cls the `struct CadetTunnel` */ static void -maintain_connections_cb (void *cls) +maintain_connections_cb(void *cls) { struct CadetTunnel *t = cls; struct GNUNET_TIME_Relative delay; struct EvaluationSummary es; t->maintain_connections_task = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Performing connection maintenance for %s.\n", - GCT_2s (t)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Performing connection maintenance for %s.\n", + GCT_2s(t)); es.min_length = UINT_MAX; es.max_length = 0; @@ -2784,21 +2791,21 @@ maintain_connections_cb (void *cls) es.path = NULL; es.worst = NULL; es.duplicate = GNUNET_NO; - GCT_iterate_connections (t, - &evaluate_connection, - &es); - if ( (NULL != es.worst) && - (GCT_count_any_connections (t) > DESIRED_CONNECTIONS_PER_TUNNEL) ) - { - /* Clear out worst-performing connection 'es.worst'. */ - destroy_t_connection (t, - es.worst); - } + GCT_iterate_connections(t, + &evaluate_connection, + &es); + if ((NULL != es.worst) && + (GCT_count_any_connections(t) > DESIRED_CONNECTIONS_PER_TUNNEL)) + { + /* Clear out worst-performing connection 'es.worst'. */ + destroy_t_connection(t, + es.worst); + } /* Consider additional paths */ - (void) GCP_iterate_paths (t->destination, - &consider_path_cb, - t); + (void)GCP_iterate_paths(t->destination, + &consider_path_cb, + t); /* FIXME: calculate when to try again based on how well we are doing; in particular, if we have to few connections, we might be able @@ -2810,9 +2817,9 @@ maintain_connections_cb (void *cls) and then reduce the frequency accordingly. */ delay = GNUNET_TIME_UNIT_MINUTES; t->maintain_connections_task - = GNUNET_SCHEDULER_add_delayed (delay, - &maintain_connections_cb, - t); + = GNUNET_SCHEDULER_add_delayed(delay, + &maintain_connections_cb, + t); } @@ -2825,18 +2832,18 @@ maintain_connections_cb (void *cls) * @param off offset of the destination on path @a path */ void -GCT_consider_path (struct CadetTunnel *t, - struct CadetPeerPath *p, - unsigned int off) +GCT_consider_path(struct CadetTunnel *t, + struct CadetPeerPath *p, + unsigned int off) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Considering %s for %s (offset %u)\n", - GCPP_2s (p), - GCT_2s (t), - off); - (void) consider_path_cb (t, - p, - off); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Considering %s for %s (offset %u)\n", + GCPP_2s(p), + GCT_2s(t), + off); + (void)consider_path_cb(t, + p, + off); } @@ -2847,18 +2854,18 @@ GCT_consider_path (struct CadetTunnel *t, * @param msg the message we received on the tunnel */ static void -handle_plaintext_keepalive (void *cls, - const struct GNUNET_MessageHeader *msg) +handle_plaintext_keepalive(void *cls, + const struct GNUNET_MessageHeader *msg) { struct CadetTunnel *t = cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received KEEPALIVE on %s\n", - GCT_2s (t)); - GNUNET_STATISTICS_update (stats, - "# keepalives received", - 1, - GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received KEEPALIVE on %s\n", + GCT_2s(t)); + GNUNET_STATISTICS_update(stats, + "# keepalives received", + 1, + GNUNET_NO); } @@ -2870,8 +2877,8 @@ handle_plaintext_keepalive (void *cls, * @return #GNUNET_OK (any variable-size payload goes) */ static int -check_plaintext_data (void *cls, - const struct GNUNET_CADET_ChannelAppDataMessage *msg) +check_plaintext_data(void *cls, + const struct GNUNET_CADET_ChannelAppDataMessage *msg) { return GNUNET_OK; } @@ -2885,29 +2892,29 @@ check_plaintext_data (void *cls, * @param msg the message we received on the tunnel */ static void -handle_plaintext_data (void *cls, - const struct GNUNET_CADET_ChannelAppDataMessage *msg) +handle_plaintext_data(void *cls, + const struct GNUNET_CADET_ChannelAppDataMessage *msg) { struct CadetTunnel *t = cls; struct CadetChannel *ch; - ch = lookup_channel (t, - msg->ctn); + ch = lookup_channel(t, + msg->ctn); if (NULL == ch) - { - /* We don't know about such a channel, might have been destroyed on our - end in the meantime, or never existed. Send back a DESTROY. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received %u bytes of application data for unknown channel %u, sending DESTROY\n", - (unsigned int) (ntohs (msg->header.size) - sizeof (*msg)), - ntohl (msg->ctn.cn)); - GCT_send_channel_destroy (t, - msg->ctn); - return; - } - GCCH_handle_channel_plaintext_data (ch, - GCC_get_id (t->current_ct->cc), - msg); + { + /* We don't know about such a channel, might have been destroyed on our + end in the meantime, or never existed. Send back a DESTROY. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received %u bytes of application data for unknown channel %u, sending DESTROY\n", + (unsigned int)(ntohs(msg->header.size) - sizeof(*msg)), + ntohl(msg->ctn.cn)); + GCT_send_channel_destroy(t, + msg->ctn); + return; + } + GCCH_handle_channel_plaintext_data(ch, + GCC_get_id(t->current_ct->cc), + msg); } @@ -2920,28 +2927,28 @@ handle_plaintext_data (void *cls, * @param ack the message we received on the tunnel */ static void -handle_plaintext_data_ack (void *cls, - const struct GNUNET_CADET_ChannelDataAckMessage *ack) +handle_plaintext_data_ack(void *cls, + const struct GNUNET_CADET_ChannelDataAckMessage *ack) { struct CadetTunnel *t = cls; struct CadetChannel *ch; - ch = lookup_channel (t, - ack->ctn); + ch = lookup_channel(t, + ack->ctn); if (NULL == ch) - { - /* We don't know about such a channel, might have been destroyed on our - end in the meantime, or never existed. Send back a DESTROY. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received DATA_ACK for unknown channel %u, sending DESTROY\n", - ntohl (ack->ctn.cn)); - GCT_send_channel_destroy (t, - ack->ctn); - return; - } - GCCH_handle_channel_plaintext_data_ack (ch, - GCC_get_id (t->current_ct->cc), - ack); + { + /* We don't know about such a channel, might have been destroyed on our + end in the meantime, or never existed. Send back a DESTROY. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received DATA_ACK for unknown channel %u, sending DESTROY\n", + ntohl(ack->ctn.cn)); + GCT_send_channel_destroy(t, + ack->ctn); + return; + } + GCCH_handle_channel_plaintext_data_ack(ch, + GCC_get_id(t->current_ct->cc), + ack); } @@ -2953,43 +2960,43 @@ handle_plaintext_data_ack (void *cls, * @param copen the message we received on the tunnel */ static void -handle_plaintext_channel_open (void *cls, - const struct GNUNET_CADET_ChannelOpenMessage *copen) +handle_plaintext_channel_open(void *cls, + const struct GNUNET_CADET_ChannelOpenMessage *copen) { struct CadetTunnel *t = cls; struct CadetChannel *ch; - ch = GNUNET_CONTAINER_multihashmap32_get (t->channels, - ntohl (copen->ctn.cn)); + ch = GNUNET_CONTAINER_multihashmap32_get(t->channels, + ntohl(copen->ctn.cn)); if (NULL != ch) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received duplicate channel CHANNEL_OPEN on h_port %s from %s (%s), resending ACK\n", - GNUNET_h2s (&copen->h_port), - GCT_2s (t), - GCCH_2s (ch)); - GCCH_handle_duplicate_open (ch, - GCC_get_id (t->current_ct->cc)); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received CHANNEL_OPEN on h_port %s from %s\n", - GNUNET_h2s (&copen->h_port), - GCT_2s (t)); - ch = GCCH_channel_incoming_new (t, - copen->ctn, - &copen->h_port, - ntohl (copen->opt)); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received duplicate channel CHANNEL_OPEN on h_port %s from %s (%s), resending ACK\n", + GNUNET_h2s(&copen->h_port), + GCT_2s(t), + GCCH_2s(ch)); + GCCH_handle_duplicate_open(ch, + GCC_get_id(t->current_ct->cc)); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received CHANNEL_OPEN on h_port %s from %s\n", + GNUNET_h2s(&copen->h_port), + GCT_2s(t)); + ch = GCCH_channel_incoming_new(t, + copen->ctn, + &copen->h_port, + ntohl(copen->opt)); if (NULL != t->destroy_task) - { - GNUNET_SCHEDULER_cancel (t->destroy_task); - t->destroy_task = NULL; - } - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap32_put (t->channels, - ntohl (copen->ctn.cn), - ch, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + { + GNUNET_SCHEDULER_cancel(t->destroy_task); + t->destroy_task = NULL; + } + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap32_put(t->channels, + ntohl(copen->ctn.cn), + ch, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); } @@ -3000,22 +3007,22 @@ handle_plaintext_channel_open (void *cls, * @param ctn ID of the channel to destroy */ void -GCT_send_channel_destroy (struct CadetTunnel *t, - struct GNUNET_CADET_ChannelTunnelNumber ctn) +GCT_send_channel_destroy(struct CadetTunnel *t, + struct GNUNET_CADET_ChannelTunnelNumber ctn) { struct GNUNET_CADET_ChannelDestroyMessage msg; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending DESTORY message for channel ID %u\n", - ntohl (ctn.cn)); - msg.header.size = htons (sizeof (msg)); - msg.header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY); - msg.reserved = htonl (0); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending DESTORY message for channel ID %u\n", + ntohl(ctn.cn)); + msg.header.size = htons(sizeof(msg)); + msg.header.type = htons(GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY); + msg.reserved = htonl(0); msg.ctn = ctn; - GCT_send (t, - &msg.header, - NULL, - NULL); + GCT_send(t, + &msg.header, + NULL, + NULL); } @@ -3028,32 +3035,32 @@ GCT_send_channel_destroy (struct CadetTunnel *t, * @param cm the message we received on the tunnel */ static void -handle_plaintext_channel_open_ack (void *cls, - const struct GNUNET_CADET_ChannelOpenAckMessage *cm) +handle_plaintext_channel_open_ack(void *cls, + const struct GNUNET_CADET_ChannelOpenAckMessage *cm) { struct CadetTunnel *t = cls; struct CadetChannel *ch; - ch = lookup_channel (t, - cm->ctn); + ch = lookup_channel(t, + cm->ctn); if (NULL == ch) - { - /* We don't know about such a channel, might have been destroyed on our - end in the meantime, or never existed. Send back a DESTROY. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n", - ntohl (cm->ctn.cn)); - GCT_send_channel_destroy (t, - cm->ctn); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received channel OPEN_ACK on channel %s from %s\n", - GCCH_2s (ch), - GCT_2s (t)); - GCCH_handle_channel_open_ack (ch, - GCC_get_id (t->current_ct->cc), - &cm->port); + { + /* We don't know about such a channel, might have been destroyed on our + end in the meantime, or never existed. Send back a DESTROY. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received channel OPEN_ACK for unknown channel %u, sending DESTROY\n", + ntohl(cm->ctn.cn)); + GCT_send_channel_destroy(t, + cm->ctn); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received channel OPEN_ACK on channel %s from %s\n", + GCCH_2s(ch), + GCT_2s(t)); + GCCH_handle_channel_open_ack(ch, + GCC_get_id(t->current_ct->cc), + &cm->port); } @@ -3065,29 +3072,29 @@ handle_plaintext_channel_open_ack (void *cls, * @param cm the message we received on the tunnel */ static void -handle_plaintext_channel_destroy (void *cls, - const struct GNUNET_CADET_ChannelDestroyMessage *cm) +handle_plaintext_channel_destroy(void *cls, + const struct GNUNET_CADET_ChannelDestroyMessage *cm) { struct CadetTunnel *t = cls; struct CadetChannel *ch; - ch = lookup_channel (t, - cm->ctn); + ch = lookup_channel(t, + cm->ctn); if (NULL == ch) - { - /* We don't know about such a channel, might have been destroyed on our - end in the meantime, or never existed. */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received channel DESTORY for unknown channel %u. Ignoring.\n", - ntohl (cm->ctn.cn)); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received channel DESTROY on %s from %s\n", - GCCH_2s (ch), - GCT_2s (t)); - GCCH_handle_remote_destroy (ch, - GCC_get_id (t->current_ct->cc)); + { + /* We don't know about such a channel, might have been destroyed on our + end in the meantime, or never existed. */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received channel DESTORY for unknown channel %u. Ignoring.\n", + ntohl(cm->ctn.cn)); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received channel DESTROY on %s from %s\n", + GCCH_2s(ch), + GCT_2s(t)); + GCCH_handle_remote_destroy(ch, + GCC_get_id(t->current_ct->cc)); } @@ -3102,14 +3109,14 @@ handle_plaintext_channel_destroy (void *cls, * #GNUNET_SYSERR to stop further processing with error */ static int -handle_decrypted (void *cls, - const struct GNUNET_MessageHeader *msg) +handle_decrypted(void *cls, + const struct GNUNET_MessageHeader *msg) { struct CadetTunnel *t = cls; - GNUNET_assert (NULL != t->current_ct); - GNUNET_MQ_inject_message (t->mq, - msg); + GNUNET_assert(NULL != t->current_ct); + GNUNET_MQ_inject_message(t->mq, + msg); return GNUNET_OK; } @@ -3122,10 +3129,10 @@ handle_decrypted (void *cls, * @param error error code */ static void -decrypted_error_cb (void *cls, - enum GNUNET_MQ_Error error) +decrypted_error_cb(void *cls, + enum GNUNET_MQ_Error error) { - GNUNET_break_op (0); + GNUNET_break_op(0); } @@ -3137,55 +3144,55 @@ decrypted_error_cb (void *cls, * @return new tunnel to @a destination */ struct CadetTunnel * -GCT_create_tunnel (struct CadetPeer *destination) +GCT_create_tunnel(struct CadetPeer *destination) { - struct CadetTunnel *t = GNUNET_new (struct CadetTunnel); + struct CadetTunnel *t = GNUNET_new(struct CadetTunnel); struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (plaintext_keepalive, - GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE, - struct GNUNET_MessageHeader, - t), - GNUNET_MQ_hd_var_size (plaintext_data, - GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA, - struct GNUNET_CADET_ChannelAppDataMessage, - t), - GNUNET_MQ_hd_fixed_size (plaintext_data_ack, - GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK, - struct GNUNET_CADET_ChannelDataAckMessage, - t), - GNUNET_MQ_hd_fixed_size (plaintext_channel_open, - GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN, - struct GNUNET_CADET_ChannelOpenMessage, - t), - GNUNET_MQ_hd_fixed_size (plaintext_channel_open_ack, - GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK, - struct GNUNET_CADET_ChannelOpenAckMessage, - t), - GNUNET_MQ_hd_fixed_size (plaintext_channel_destroy, - GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY, - struct GNUNET_CADET_ChannelDestroyMessage, - t), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(plaintext_keepalive, + GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE, + struct GNUNET_MessageHeader, + t), + GNUNET_MQ_hd_var_size(plaintext_data, + GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA, + struct GNUNET_CADET_ChannelAppDataMessage, + t), + GNUNET_MQ_hd_fixed_size(plaintext_data_ack, + GNUNET_MESSAGE_TYPE_CADET_CHANNEL_APP_DATA_ACK, + struct GNUNET_CADET_ChannelDataAckMessage, + t), + GNUNET_MQ_hd_fixed_size(plaintext_channel_open, + GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN, + struct GNUNET_CADET_ChannelOpenMessage, + t), + GNUNET_MQ_hd_fixed_size(plaintext_channel_open_ack, + GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_ACK, + struct GNUNET_CADET_ChannelOpenAckMessage, + t), + GNUNET_MQ_hd_fixed_size(plaintext_channel_destroy, + GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY, + struct GNUNET_CADET_ChannelDestroyMessage, + t), + GNUNET_MQ_handler_end() }; t->kx_retry_delay = INITIAL_KX_RETRY_DELAY; - new_ephemeral (&t->ax); - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_ecdhe_key_create2 (&t->ax.kx_0)); + new_ephemeral(&t->ax); + GNUNET_assert(GNUNET_OK == + GNUNET_CRYPTO_ecdhe_key_create2(&t->ax.kx_0)); t->destination = destination; - t->channels = GNUNET_CONTAINER_multihashmap32_create (8); + t->channels = GNUNET_CONTAINER_multihashmap32_create(8); t->maintain_connections_task - = GNUNET_SCHEDULER_add_now (&maintain_connections_cb, - t); - t->mq = GNUNET_MQ_queue_for_callbacks (NULL, - NULL, - NULL, - NULL, - handlers, - &decrypted_error_cb, - t); - t->mst = GNUNET_MST_create (&handle_decrypted, - t); + = GNUNET_SCHEDULER_add_now(&maintain_connections_cb, + t); + t->mq = GNUNET_MQ_queue_for_callbacks(NULL, + NULL, + NULL, + NULL, + handlers, + &decrypted_error_cb, + t); + t->mst = GNUNET_MST_create(&handle_decrypted, + t); return t; } @@ -3201,42 +3208,42 @@ GCT_create_tunnel (struct CadetPeer *destination) * #GNUNET_SYSERR on failure (duplicate connection) */ int -GCT_add_inbound_connection (struct CadetTunnel *t, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, - struct CadetPeerPath *path) +GCT_add_inbound_connection(struct CadetTunnel *t, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, + struct CadetPeerPath *path) { struct CadetTConnection *ct; - ct = GNUNET_new (struct CadetTConnection); - ct->created = GNUNET_TIME_absolute_get (); + ct = GNUNET_new(struct CadetTConnection); + ct->created = GNUNET_TIME_absolute_get(); ct->t = t; - ct->cc = GCC_create_inbound (t->destination, - path, - ct, - cid, - &connection_ready_cb, - ct); + ct->cc = GCC_create_inbound(t->destination, + path, + ct, + cid, + &connection_ready_cb, + ct); if (NULL == ct->cc) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "%s refused inbound %s (duplicate)\n", - GCT_2s (t), - GCC_2s (ct->cc)); - GNUNET_free (ct); - return GNUNET_SYSERR; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "%s refused inbound %s (duplicate)\n", + GCT_2s(t), + GCC_2s(ct->cc)); + GNUNET_free(ct); + return GNUNET_SYSERR; + } /* FIXME: schedule job to kill connection (and path?) if it takes too long to get ready! (And track performance data on how long other connections took with the tunnel!) => Note: to be done within 'connection'-logic! */ - GNUNET_CONTAINER_DLL_insert (t->connection_busy_head, - t->connection_busy_tail, - ct); + GNUNET_CONTAINER_DLL_insert(t->connection_busy_head, + t->connection_busy_tail, + ct); t->num_busy_connections++; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "%s has new %s\n", - GCT_2s (t), - GCC_2s (ct->cc)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "%s has new %s\n", + GCT_2s(t), + GCC_2s(ct->cc)); return GNUNET_OK; } @@ -3248,174 +3255,177 @@ GCT_add_inbound_connection (struct CadetTunnel *t, * @param msg the encrypted message to decrypt */ void -GCT_handle_encrypted (struct CadetTConnection *ct, - const struct GNUNET_CADET_TunnelEncryptedMessage *msg) +GCT_handle_encrypted(struct CadetTConnection *ct, + const struct GNUNET_CADET_TunnelEncryptedMessage *msg) { struct CadetTunnel *t = ct->t; - uint16_t size = ntohs (msg->header.size); + uint16_t size = ntohs(msg->header.size); char cbuf [size] GNUNET_ALIGN; ssize_t decrypted_size; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "%s received %u bytes of encrypted data in state %d\n", - GCT_2s (t), - (unsigned int) size, - t->estate); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "%s received %u bytes of encrypted data in state %d\n", + GCT_2s(t), + (unsigned int)size, + t->estate); switch (t->estate) - { - case CADET_TUNNEL_KEY_UNINITIALIZED: - case CADET_TUNNEL_KEY_AX_RECV: - /* We did not even SEND our KX, how can the other peer - send us encrypted data? Must have been that we went - down and the other peer still things we are up. - Let's send it KX back. */ - GNUNET_STATISTICS_update (stats, - "# received encrypted without any KX", - 1, - GNUNET_NO); - if (NULL != t->kx_task) - { - GNUNET_SCHEDULER_cancel (t->kx_task); - t->kx_task = NULL; - } - send_kx (t, - ct, - &t->ax); - return; - case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: - /* We send KX, and other peer send KX to us at the same time. - Neither KX is AUTH'ed, so let's try KX_AUTH this time. */ - GNUNET_STATISTICS_update (stats, - "# received encrypted without KX_AUTH", - 1, - GNUNET_NO); - if (NULL != t->kx_task) - { - GNUNET_SCHEDULER_cancel (t->kx_task); - t->kx_task = NULL; - } - send_kx_auth (t, - ct, - &t->ax, - GNUNET_YES); - return; - case CADET_TUNNEL_KEY_AX_SENT: - /* We did not get the KX of the other peer, but that - might have been lost. Send our KX again immediately. */ - GNUNET_STATISTICS_update (stats, - "# received encrypted without KX", - 1, - GNUNET_NO); - if (NULL != t->kx_task) - { - GNUNET_SCHEDULER_cancel (t->kx_task); - t->kx_task = NULL; - } - send_kx (t, - ct, - &t->ax); - return; - case CADET_TUNNEL_KEY_AX_AUTH_SENT: + { + case CADET_TUNNEL_KEY_UNINITIALIZED: + case CADET_TUNNEL_KEY_AX_RECV: + /* We did not even SEND our KX, how can the other peer + send us encrypted data? Must have been that we went + down and the other peer still things we are up. + Let's send it KX back. */ + GNUNET_STATISTICS_update(stats, + "# received encrypted without any KX", + 1, + GNUNET_NO); + if (NULL != t->kx_task) + { + GNUNET_SCHEDULER_cancel(t->kx_task); + t->kx_task = NULL; + } + send_kx(t, + ct, + &t->ax); + return; + + case CADET_TUNNEL_KEY_AX_SENT_AND_RECV: + /* We send KX, and other peer send KX to us at the same time. + Neither KX is AUTH'ed, so let's try KX_AUTH this time. */ + GNUNET_STATISTICS_update(stats, + "# received encrypted without KX_AUTH", + 1, + GNUNET_NO); + if (NULL != t->kx_task) + { + GNUNET_SCHEDULER_cancel(t->kx_task); + t->kx_task = NULL; + } + send_kx_auth(t, + ct, + &t->ax, + GNUNET_YES); + return; + + case CADET_TUNNEL_KEY_AX_SENT: + /* We did not get the KX of the other peer, but that + might have been lost. Send our KX again immediately. */ + GNUNET_STATISTICS_update(stats, + "# received encrypted without KX", + 1, + GNUNET_NO); + if (NULL != t->kx_task) + { + GNUNET_SCHEDULER_cancel(t->kx_task); + t->kx_task = NULL; + } + send_kx(t, + ct, + &t->ax); + return; + + case CADET_TUNNEL_KEY_AX_AUTH_SENT: /* Great, first payload, we might graduate to OK! */ - case CADET_TUNNEL_KEY_OK: - /* We are up and running, all good. */ - break; - } + case CADET_TUNNEL_KEY_OK: + /* We are up and running, all good. */ + break; + } decrypted_size = -1; if (CADET_TUNNEL_KEY_OK == t->estate) - { - /* We have well-established key material available, - try that. (This is the common case.) */ - decrypted_size = t_ax_decrypt_and_validate (&t->ax, - cbuf, - msg, - size); - } - - if ( (-1 == decrypted_size) && - (NULL != t->unverified_ax) ) - { - /* We have un-authenticated KX material available. We should try - this as a back-up option, in case the sender crashed and - switched keys. */ - decrypted_size = t_ax_decrypt_and_validate (t->unverified_ax, - cbuf, - msg, - size); - if (-1 != decrypted_size) - { - /* It worked! Treat this as authentication of the AX data! */ - cleanup_ax (&t->ax); - t->ax = *t->unverified_ax; - GNUNET_free (t->unverified_ax); - t->unverified_ax = NULL; + { + /* We have well-established key material available, + try that. (This is the common case.) */ + decrypted_size = t_ax_decrypt_and_validate(&t->ax, + cbuf, + msg, + size); } - if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate) + + if ((-1 == decrypted_size) && + (NULL != t->unverified_ax)) { - /* First time it worked, move tunnel into production! */ - GCT_change_estate (t, - CADET_TUNNEL_KEY_OK); - if (NULL != t->send_task) - GNUNET_SCHEDULER_cancel (t->send_task); - t->send_task = GNUNET_SCHEDULER_add_now (&trigger_transmissions, - t); + /* We have un-authenticated KX material available. We should try + this as a back-up option, in case the sender crashed and + switched keys. */ + decrypted_size = t_ax_decrypt_and_validate(t->unverified_ax, + cbuf, + msg, + size); + if (-1 != decrypted_size) + { + /* It worked! Treat this as authentication of the AX data! */ + cleanup_ax(&t->ax); + t->ax = *t->unverified_ax; + GNUNET_free(t->unverified_ax); + t->unverified_ax = NULL; + } + if (CADET_TUNNEL_KEY_AX_AUTH_SENT == t->estate) + { + /* First time it worked, move tunnel into production! */ + GCT_change_estate(t, + CADET_TUNNEL_KEY_OK); + if (NULL != t->send_task) + GNUNET_SCHEDULER_cancel(t->send_task); + t->send_task = GNUNET_SCHEDULER_add_now(&trigger_transmissions, + t); + } } - } if (NULL != t->unverified_ax) - { - /* We had unverified KX material that was useless; so increment - counter and eventually move to ignore it. Note that we even do - this increment if we successfully decrypted with the old KX - material and thus didn't even both with the new one. This is - the ideal case, as a malicious injection of bogus KX data - basically only causes us to increment a counter a few times. */ - t->unverified_attempts++; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Failed to decrypt message with unverified KX data %u times\n", - t->unverified_attempts); - if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS) - { - cleanup_ax (t->unverified_ax); - GNUNET_free (t->unverified_ax); - t->unverified_ax = NULL; + { + /* We had unverified KX material that was useless; so increment + counter and eventually move to ignore it. Note that we even do + this increment if we successfully decrypted with the old KX + material and thus didn't even both with the new one. This is + the ideal case, as a malicious injection of bogus KX data + basically only causes us to increment a counter a few times. */ + t->unverified_attempts++; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Failed to decrypt message with unverified KX data %u times\n", + t->unverified_attempts); + if (t->unverified_attempts > MAX_UNVERIFIED_ATTEMPTS) + { + cleanup_ax(t->unverified_ax); + GNUNET_free(t->unverified_ax); + t->unverified_ax = NULL; + } } - } if (-1 == decrypted_size) - { - /* Decryption failed for good, complain. */ - LOG (GNUNET_ERROR_TYPE_WARNING, - "%s failed to decrypt and validate encrypted data, retrying KX\n", - GCT_2s (t)); - GNUNET_STATISTICS_update (stats, - "# unable to decrypt", - 1, - GNUNET_NO); - if (NULL != t->kx_task) - { - GNUNET_SCHEDULER_cancel (t->kx_task); - t->kx_task = NULL; + { + /* Decryption failed for good, complain. */ + LOG(GNUNET_ERROR_TYPE_WARNING, + "%s failed to decrypt and validate encrypted data, retrying KX\n", + GCT_2s(t)); + GNUNET_STATISTICS_update(stats, + "# unable to decrypt", + 1, + GNUNET_NO); + if (NULL != t->kx_task) + { + GNUNET_SCHEDULER_cancel(t->kx_task); + t->kx_task = NULL; + } + send_kx(t, + ct, + &t->ax); + return; } - send_kx (t, - ct, - &t->ax); - return; - } - GNUNET_STATISTICS_update (stats, - "# decrypted bytes", - decrypted_size, - GNUNET_NO); + GNUNET_STATISTICS_update(stats, + "# decrypted bytes", + decrypted_size, + GNUNET_NO); /* The MST will ultimately call #handle_decrypted() on each message. */ t->current_ct = ct; - GNUNET_break_op (GNUNET_OK == - GNUNET_MST_from_buffer (t->mst, - cbuf, - decrypted_size, - GNUNET_YES, - GNUNET_NO)); + GNUNET_break_op(GNUNET_OK == + GNUNET_MST_from_buffer(t->mst, + cbuf, + decrypted_size, + GNUNET_YES, + GNUNET_NO)); t->current_ct = NULL; } @@ -3431,10 +3441,10 @@ GCT_handle_encrypted (struct CadetTConnection *ct, * @return Handle to cancel message */ struct CadetTunnelQueueEntry * -GCT_send (struct CadetTunnel *t, - const struct GNUNET_MessageHeader *message, - GCT_SendContinuation cont, - void *cont_cls) +GCT_send(struct CadetTunnel *t, + const struct GNUNET_MessageHeader *message, + GCT_SendContinuation cont, + void *cont_cls) { struct CadetTunnelQueueEntry *tq; uint16_t payload_size; @@ -3442,55 +3452,55 @@ GCT_send (struct CadetTunnel *t, struct GNUNET_CADET_TunnelEncryptedMessage *ax_msg; if (CADET_TUNNEL_KEY_OK != t->estate) - { - GNUNET_break (0); - return NULL; - } - payload_size = ntohs (message->size); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Encrypting %u bytes for %s\n", - (unsigned int) payload_size, - GCT_2s (t)); - env = GNUNET_MQ_msg_extra (ax_msg, - payload_size, - GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED); - t_ax_encrypt (&t->ax, - &ax_msg[1], - message, - payload_size); - GNUNET_STATISTICS_update (stats, - "# encrypted bytes", + { + GNUNET_break(0); + return NULL; + } + payload_size = ntohs(message->size); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Encrypting %u bytes for %s\n", + (unsigned int)payload_size, + GCT_2s(t)); + env = GNUNET_MQ_msg_extra(ax_msg, payload_size, - GNUNET_NO); - ax_msg->ax_header.Ns = htonl (t->ax.Ns++); - ax_msg->ax_header.PNs = htonl (t->ax.PNs); + GNUNET_MESSAGE_TYPE_CADET_TUNNEL_ENCRYPTED); + t_ax_encrypt(&t->ax, + &ax_msg[1], + message, + payload_size); + GNUNET_STATISTICS_update(stats, + "# encrypted bytes", + payload_size, + GNUNET_NO); + ax_msg->ax_header.Ns = htonl(t->ax.Ns++); + ax_msg->ax_header.PNs = htonl(t->ax.PNs); /* FIXME: we should do this once, not once per message; this is a point multiplication, and DHRs does not change all the time. */ - GNUNET_CRYPTO_ecdhe_key_get_public (&t->ax.DHRs, - &ax_msg->ax_header.DHRs); - t_h_encrypt (&t->ax, - ax_msg); - t_hmac (&ax_msg->ax_header, - sizeof (struct GNUNET_CADET_AxHeader) + payload_size, - 0, - &t->ax.HKs, - &ax_msg->hmac); - - tq = GNUNET_malloc (sizeof (*tq)); + GNUNET_CRYPTO_ecdhe_key_get_public(&t->ax.DHRs, + &ax_msg->ax_header.DHRs); + t_h_encrypt(&t->ax, + ax_msg); + t_hmac(&ax_msg->ax_header, + sizeof(struct GNUNET_CADET_AxHeader) + payload_size, + 0, + &t->ax.HKs, + &ax_msg->hmac); + + tq = GNUNET_malloc(sizeof(*tq)); tq->t = t; tq->env = env; tq->cid = &ax_msg->cid; /* will initialize 'ax_msg->cid' once we know the connection */ tq->cont = cont; tq->cont_cls = cont_cls; - GNUNET_CONTAINER_DLL_insert_tail (t->tq_head, - t->tq_tail, - tq); + GNUNET_CONTAINER_DLL_insert_tail(t->tq_head, + t->tq_tail, + tq); if (NULL != t->send_task) - GNUNET_SCHEDULER_cancel (t->send_task); + GNUNET_SCHEDULER_cancel(t->send_task); t->send_task - = GNUNET_SCHEDULER_add_now (&trigger_transmissions, - t); + = GNUNET_SCHEDULER_add_now(&trigger_transmissions, + t); return tq; } @@ -3505,15 +3515,15 @@ GCT_send (struct CadetTunnel *t, * @param tq Handle to the queue entry to cancel. */ void -GCT_send_cancel (struct CadetTunnelQueueEntry *tq) +GCT_send_cancel(struct CadetTunnelQueueEntry *tq) { struct CadetTunnel *t = tq->t; - GNUNET_CONTAINER_DLL_remove (t->tq_head, - t->tq_tail, - tq); - GNUNET_MQ_discard (tq->env); - GNUNET_free (tq); + GNUNET_CONTAINER_DLL_remove(t->tq_head, + t->tq_tail, + tq); + GNUNET_MQ_discard(tq->env); + GNUNET_free(tq); } @@ -3525,35 +3535,35 @@ GCT_send_cancel (struct CadetTunnelQueueEntry *tq) * @param iter_cls Closure for @c iter. */ void -GCT_iterate_connections (struct CadetTunnel *t, - GCT_ConnectionIterator iter, - void *iter_cls) +GCT_iterate_connections(struct CadetTunnel *t, + GCT_ConnectionIterator iter, + void *iter_cls) { struct CadetTConnection *n; + for (struct CadetTConnection *ct = t->connection_ready_head; NULL != ct; ct = n) - { - n = ct->next; - iter (iter_cls, - ct); - } + { + n = ct->next; + iter(iter_cls, + ct); + } for (struct CadetTConnection *ct = t->connection_busy_head; NULL != ct; ct = n) - { - n = ct->next; - iter (iter_cls, - ct); - } + { + n = ct->next; + iter(iter_cls, + ct); + } } /** * Closure for #iterate_channels_cb. */ -struct ChanIterCls -{ +struct ChanIterCls { /** * Function to call. */ @@ -3575,15 +3585,15 @@ struct ChanIterCls * @return #GNUNET_OK */ static int -iterate_channels_cb (void *cls, - uint32_t key, - void *value) +iterate_channels_cb(void *cls, + uint32_t key, + void *value) { struct ChanIterCls *ctx = cls; struct CadetChannel *ch = value; - ctx->iter (ctx->iter_cls, - ch); + ctx->iter(ctx->iter_cls, + ch); return GNUNET_OK; } @@ -3596,18 +3606,17 @@ iterate_channels_cb (void *cls, * @param iter_cls Closure for @c iter. */ void -GCT_iterate_channels (struct CadetTunnel *t, - GCT_ChannelIterator iter, - void *iter_cls) +GCT_iterate_channels(struct CadetTunnel *t, + GCT_ChannelIterator iter, + void *iter_cls) { struct ChanIterCls ctx; ctx.iter = iter; ctx.iter_cls = iter_cls; - GNUNET_CONTAINER_multihashmap32_iterate (t->channels, - &iterate_channels_cb, - &ctx); - + GNUNET_CONTAINER_multihashmap32_iterate(t->channels, + &iterate_channels_cb, + &ctx); } @@ -3620,19 +3629,19 @@ GCT_iterate_channels (struct CadetTunnel *t, * @return #GNUNET_OK (continue iteration) */ static int -debug_channel (void *cls, - uint32_t key, - void *value) +debug_channel(void *cls, + uint32_t key, + void *value) { const enum GNUNET_ErrorType *level = cls; struct CadetChannel *ch = value; - GCCH_debug (ch, *level); + GCCH_debug(ch, *level); return GNUNET_OK; } -#define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__) +#define LOG2(level, ...) GNUNET_log_from_nocheck(level, "cadet-tun", __VA_ARGS__) /** @@ -3642,41 +3651,41 @@ debug_channel (void *cls, * @param level Debug level to use. */ void -GCT_debug (const struct CadetTunnel *t, - enum GNUNET_ErrorType level) +GCT_debug(const struct CadetTunnel *t, + enum GNUNET_ErrorType level) { #if !defined(GNUNET_CULL_LOGGING) struct CadetTConnection *iter_c; int do_log; - do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK), - "cadet-tun", - __FILE__, __FUNCTION__, __LINE__); + do_log = GNUNET_get_log_call_status(level & (~GNUNET_ERROR_TYPE_BULK), + "cadet-tun", + __FILE__, __FUNCTION__, __LINE__); if (0 == do_log) return; - LOG2 (level, - "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n", - GCT_2s (t), - estate2s (t->estate), - t->tq_len, - GCT_count_any_connections (t)); - LOG2 (level, - "TTT channels:\n"); - GNUNET_CONTAINER_multihashmap32_iterate (t->channels, - &debug_channel, - &level); - LOG2 (level, - "TTT connections:\n"); + LOG2(level, + "TTT TUNNEL TOWARDS %s in estate %s tq_len: %u #cons: %u\n", + GCT_2s(t), + estate2s(t->estate), + t->tq_len, + GCT_count_any_connections(t)); + LOG2(level, + "TTT channels:\n"); + GNUNET_CONTAINER_multihashmap32_iterate(t->channels, + &debug_channel, + &level); + LOG2(level, + "TTT connections:\n"); for (iter_c = t->connection_ready_head; NULL != iter_c; iter_c = iter_c->next) - GCC_debug (iter_c->cc, - level); + GCC_debug(iter_c->cc, + level); for (iter_c = t->connection_busy_head; NULL != iter_c; iter_c = iter_c->next) - GCC_debug (iter_c->cc, - level); + GCC_debug(iter_c->cc, + level); - LOG2 (level, - "TTT TUNNEL END\n"); + LOG2(level, + "TTT TUNNEL END\n"); #endif } diff --git a/src/cadet/gnunet-service-cadet_tunnels.h b/src/cadet/gnunet-service-cadet_tunnels.h index 47d9f98bf..0df35cd23 100644 --- a/src/cadet/gnunet-service-cadet_tunnels.h +++ b/src/cadet/gnunet-service-cadet_tunnels.h @@ -12,12 +12,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/gnunet-service-cadet_tunnels.h @@ -41,8 +41,7 @@ /** * All the encryption states a tunnel can be in. */ -enum CadetTunnelEState -{ +enum CadetTunnelEState { /** * Uninitialized status, we need to send KX. We will stay * in this state until the first connection is up. @@ -79,7 +78,6 @@ enum CadetTunnelEState * Handshake completed: session key available. */ CADET_TUNNEL_KEY_OK - }; @@ -91,7 +89,7 @@ enum CadetTunnelEState * @return Static string the destination peer's ID. */ const char * -GCT_2s (const struct CadetTunnel *t); +GCT_2s(const struct CadetTunnel *t); /** @@ -102,7 +100,7 @@ GCT_2s (const struct CadetTunnel *t); * @return new tunnel to @a destination */ struct CadetTunnel * -GCT_create_tunnel (struct CadetPeer *destination); +GCT_create_tunnel(struct CadetPeer *destination); /** @@ -111,7 +109,7 @@ GCT_create_tunnel (struct CadetPeer *destination); * @param t tunnel to destroy */ void -GCT_destroy_tunnel_now (struct CadetTunnel *t); +GCT_destroy_tunnel_now(struct CadetTunnel *t); /** @@ -124,9 +122,9 @@ GCT_destroy_tunnel_now (struct CadetTunnel *t); * #GNUNET_SYSERR on failure (duplicate connection) */ int -GCT_add_inbound_connection (struct CadetTunnel *t, - const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, - struct CadetPeerPath *path); +GCT_add_inbound_connection(struct CadetTunnel *t, + const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid, + struct CadetPeerPath *path); /** @@ -136,7 +134,7 @@ GCT_add_inbound_connection (struct CadetTunnel *t, * @param ct binding of connection to tunnel of the connection that was lost. */ void -GCT_connection_lost (struct CadetTConnection *ct); +GCT_connection_lost(struct CadetTConnection *ct); /** @@ -146,7 +144,7 @@ GCT_connection_lost (struct CadetTConnection *ct); * @return the destination of the tunnel */ struct CadetPeer * -GCT_get_destination (struct CadetTunnel *t); +GCT_get_destination(struct CadetTunnel *t); /** @@ -158,9 +156,9 @@ GCT_get_destination (struct CadetTunnel *t); * @param off offset of the destination on path @a path */ void -GCT_consider_path (struct CadetTunnel *t, - struct CadetPeerPath *p, - unsigned int off); +GCT_consider_path(struct CadetTunnel *t, + struct CadetPeerPath *p, + unsigned int off); /** @@ -171,8 +169,8 @@ GCT_consider_path (struct CadetTunnel *t, * @return unique number identifying @a ch within @a t */ struct GNUNET_CADET_ChannelTunnelNumber -GCT_add_channel (struct CadetTunnel *t, - struct CadetChannel *ch); +GCT_add_channel(struct CadetTunnel *t, + struct CadetChannel *ch); /** @@ -183,9 +181,9 @@ GCT_add_channel (struct CadetTunnel *t, * @param ctn unique number identifying @a ch within @a t */ void -GCT_remove_channel (struct CadetTunnel *t, - struct CadetChannel *ch, - struct GNUNET_CADET_ChannelTunnelNumber ctn); +GCT_remove_channel(struct CadetTunnel *t, + struct CadetChannel *ch, + struct GNUNET_CADET_ChannelTunnelNumber ctn); /** @@ -195,8 +193,8 @@ GCT_remove_channel (struct CadetTunnel *t, * @param ctn ID of the channel to destroy */ void -GCT_send_channel_destroy (struct CadetTunnel *t, - struct GNUNET_CADET_ChannelTunnelNumber ctn); +GCT_send_channel_destroy(struct CadetTunnel *t, + struct GNUNET_CADET_ChannelTunnelNumber ctn); /** @@ -223,10 +221,10 @@ typedef void * @return Handle to cancel message. */ struct CadetTunnelQueueEntry * -GCT_send (struct CadetTunnel *t, - const struct GNUNET_MessageHeader *message, - GCT_SendContinuation cont, - void *cont_cls); +GCT_send(struct CadetTunnel *t, + const struct GNUNET_MessageHeader *message, + GCT_SendContinuation cont, + void *cont_cls); /** @@ -239,7 +237,7 @@ GCT_send (struct CadetTunnel *t, * @param q Handle to the queue entry to cancel. */ void -GCT_send_cancel (struct CadetTunnelQueueEntry *q); +GCT_send_cancel(struct CadetTunnelQueueEntry *q); /** @@ -249,7 +247,7 @@ GCT_send_cancel (struct CadetTunnelQueueEntry *q); * @return number of channels using the tunnel */ unsigned int -GCT_count_channels (struct CadetTunnel *t); +GCT_count_channels(struct CadetTunnel *t); /** @@ -259,7 +257,7 @@ GCT_count_channels (struct CadetTunnel *t); * @return number of connections available for the tunnel */ unsigned int -GCT_count_any_connections (const struct CadetTunnel *t); +GCT_count_any_connections(const struct CadetTunnel *t); /** @@ -281,9 +279,9 @@ typedef void * @param iter_cls Closure for @c iter. */ void -GCT_iterate_connections (struct CadetTunnel *t, - GCT_ConnectionIterator iter, - void *iter_cls); +GCT_iterate_connections(struct CadetTunnel *t, + GCT_ConnectionIterator iter, + void *iter_cls); /** @@ -305,9 +303,9 @@ typedef void * @param iter_cls Closure for @c iter. */ void -GCT_iterate_channels (struct CadetTunnel *t, - GCT_ChannelIterator iter, - void *iter_cls); +GCT_iterate_channels(struct CadetTunnel *t, + GCT_ChannelIterator iter, + void *iter_cls); /** @@ -318,7 +316,7 @@ GCT_iterate_channels (struct CadetTunnel *t, * @return Tunnel's encryption state. */ enum CadetTunnelEState -GCT_get_estate (struct CadetTunnel *t); +GCT_get_estate(struct CadetTunnel *t); /** @@ -328,8 +326,8 @@ GCT_get_estate (struct CadetTunnel *t); * @param msg the key exchange message */ void -GCT_handle_kx (struct CadetTConnection *ct, - const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg); +GCT_handle_kx(struct CadetTConnection *ct, + const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg); /** @@ -339,8 +337,8 @@ GCT_handle_kx (struct CadetTConnection *ct, * @param msg the key exchange message */ void -GCT_handle_kx_auth (struct CadetTConnection *ct, - const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg); +GCT_handle_kx_auth(struct CadetTConnection *ct, + const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg); /** @@ -350,8 +348,8 @@ GCT_handle_kx_auth (struct CadetTConnection *ct, * @param msg the encrypted message to decrypt */ void -GCT_handle_encrypted (struct CadetTConnection *ct, - const struct GNUNET_CADET_TunnelEncryptedMessage *msg); +GCT_handle_encrypted(struct CadetTConnection *ct, + const struct GNUNET_CADET_TunnelEncryptedMessage *msg); /** @@ -361,8 +359,8 @@ GCT_handle_encrypted (struct CadetTConnection *ct, * @param level Debug level to use. */ void -GCT_debug (const struct CadetTunnel *t, - enum GNUNET_ErrorType level); +GCT_debug(const struct CadetTunnel *t, + enum GNUNET_ErrorType level); #endif diff --git a/src/cadet/test_cadet.c b/src/cadet/test_cadet.c index 5a28b439e..de5e4eef0 100644 --- a/src/cadet/test_cadet.c +++ b/src/cadet/test_cadet.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/test_cadet.c * @author Bart Polot @@ -34,8 +34,7 @@ /** * Ugly workaround to unify data handlers on incoming and outgoing channels. */ -struct CadetTestChannelWrapper -{ +struct CadetTestChannelWrapper { /** * Channel pointer. */ @@ -50,17 +49,17 @@ struct CadetTestChannelWrapper /** * How long until we give up on connecting the peers? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 120) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 120) /** * Time to wait by default for stuff that should be rather fast. */ -#define SHORT_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20) +#define SHORT_TIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20) /** * How fast do we send messages? */ -#define SEND_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 10) +#define SEND_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 10) /** * DIFFERENT TESTS TO RUN @@ -112,7 +111,7 @@ static int ok_goal; /** * Size of each test packet's payload */ -static size_t size_payload = sizeof (uint32_t); +static size_t size_payload = sizeof(uint32_t); /** * Operation to get peer ids. @@ -260,7 +259,7 @@ static unsigned int msg_dropped; * or the last peer in the line (for other tests). */ static struct GNUNET_CADET_Channel * -get_target_channel () +get_target_channel() { if (SPEED == test && GNUNET_YES == test_backwards) return outgoing_ch; @@ -273,29 +272,29 @@ get_target_channel () * Show the results of the test (banwidth acheived) and log them to GAUGER */ static void -show_end_data (void) +show_end_data(void) { static struct GNUNET_TIME_Absolute end_time; static struct GNUNET_TIME_Relative total_time; - end_time = GNUNET_TIME_absolute_get (); - total_time = GNUNET_TIME_absolute_get_difference (start_time, end_time); - fprintf (stderr, - "\nResults of test \"%s\"\n", - test_name); - fprintf (stderr, - "Test time %s\n", - GNUNET_STRINGS_relative_time_to_string (total_time, GNUNET_YES)); - fprintf (stderr, - "Test bandwidth: %f kb/s\n", - 4 * total_packets * 1.0 / (total_time.rel_value_us / 1000)); // 4bytes * ms - fprintf (stderr, - "Test throughput: %f packets/s\n\n", - total_packets * 1000.0 / (total_time.rel_value_us / 1000)); // packets * ms - GAUGER ("CADET", - test_name, - total_packets * 1000.0 / (total_time.rel_value_us / 1000), - "packets/s"); + end_time = GNUNET_TIME_absolute_get(); + total_time = GNUNET_TIME_absolute_get_difference(start_time, end_time); + fprintf(stderr, + "\nResults of test \"%s\"\n", + test_name); + fprintf(stderr, + "Test time %s\n", + GNUNET_STRINGS_relative_time_to_string(total_time, GNUNET_YES)); + fprintf(stderr, + "Test bandwidth: %f kb/s\n", + 4 * total_packets * 1.0 / (total_time.rel_value_us / 1000)); // 4bytes * ms + fprintf(stderr, + "Test throughput: %f packets/s\n\n", + total_packets * 1000.0 / (total_time.rel_value_us / 1000)); // packets * ms + GAUGER("CADET", + test_name, + total_packets * 1000.0 / (total_time.rel_value_us / 1000), + "packets/s"); } @@ -306,30 +305,30 @@ show_end_data (void) * @param tc Task Context. */ static void -disconnect_cadet_peers (void *cls) +disconnect_cadet_peers(void *cls) { - long line = (long) cls; + long line = (long)cls; disconnect_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "disconnecting cadet service of peers, called from line %ld\n", - line); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "disconnecting cadet service of peers, called from line %ld\n", + line); for (unsigned int i = 0; i < 2; i++) - { - GNUNET_TESTBED_operation_done (t_op[i]); - } + { + GNUNET_TESTBED_operation_done(t_op[i]); + } if (NULL != outgoing_ch) - { - GNUNET_CADET_channel_destroy (outgoing_ch); - outgoing_ch = NULL; - } + { + GNUNET_CADET_channel_destroy(outgoing_ch); + outgoing_ch = NULL; + } if (NULL != incoming_ch) - { - GNUNET_CADET_channel_destroy (incoming_ch); - incoming_ch = NULL; - } - GNUNET_CADET_TEST_cleanup (test_ctx); - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_CADET_channel_destroy(incoming_ch); + incoming_ch = NULL; + } + GNUNET_CADET_TEST_cleanup(test_ctx); + GNUNET_SCHEDULER_shutdown(); } @@ -340,27 +339,27 @@ disconnect_cadet_peers (void *cls) * @param tc Task Context. */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Ending test.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Ending test.\n"); if (NULL != send_next_msg_task) - { - GNUNET_SCHEDULER_cancel (send_next_msg_task); - send_next_msg_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(send_next_msg_task); + send_next_msg_task = NULL; + } if (NULL != test_task) - { - GNUNET_SCHEDULER_cancel (test_task); - test_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(test_task); + test_task = NULL; + } if (NULL != disconnect_task) - { - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = - GNUNET_SCHEDULER_add_now (&disconnect_cadet_peers, - (void *) __LINE__); - } + { + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = + GNUNET_SCHEDULER_add_now(&disconnect_cadet_peers, + (void *)__LINE__); + } } @@ -374,26 +373,26 @@ shutdown_task (void *cls) * operation has executed successfully. */ static void -stats_cont (void *cls, - struct GNUNET_TESTBED_Operation *op, - const char *emsg) +stats_cont(void *cls, + struct GNUNET_TESTBED_Operation *op, + const char *emsg) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "KA sent: %u, KA received: %u\n", - ka_sent, - ka_received); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "KA sent: %u, KA received: %u\n", + ka_sent, + ka_received); if ((KEEPALIVE == test || REOPEN == test) && ((ka_sent < 2) || (ka_sent > ka_received + 1))) - { - GNUNET_break (0); - ok--; - } - GNUNET_TESTBED_operation_done (stats_op); + { + GNUNET_break(0); + ok--; + } + GNUNET_TESTBED_operation_done(stats_op); if (NULL != disconnect_task) - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = GNUNET_SCHEDULER_add_now (&disconnect_cadet_peers, - cls); + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = GNUNET_SCHEDULER_add_now(&disconnect_cadet_peers, + cls); } @@ -409,12 +408,12 @@ stats_cont (void *cls, * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration */ static int -stats_iterator (void *cls, - const struct GNUNET_TESTBED_Peer *peer, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +stats_iterator(void *cls, + const struct GNUNET_TESTBED_Peer *peer, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { static const char *s_sent = "# keepalives sent"; static const char *s_recv = "# keepalives received"; @@ -422,16 +421,16 @@ stats_iterator (void *cls, static const char *cdrops = "# messages dropped due to slow client"; uint32_t i; - i = GNUNET_TESTBED_get_index (peer); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "STATS PEER %u - %s [%s]: %llu\n", i, - subsystem, name, (unsigned long long) value); - if (0 == strncmp (s_sent, name, strlen (s_sent)) && 0 == i) + i = GNUNET_TESTBED_get_index(peer); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "STATS PEER %u - %s [%s]: %llu\n", i, + subsystem, name, (unsigned long long)value); + if (0 == strncmp(s_sent, name, strlen(s_sent)) && 0 == i) ka_sent = value; - if (0 == strncmp (s_recv, name, strlen (s_recv)) && peers_requested - 1 == i) + if (0 == strncmp(s_recv, name, strlen(s_recv)) && peers_requested - 1 == i) ka_received = value; - if (0 == strncmp (rdrops, name, strlen (rdrops))) + if (0 == strncmp(rdrops, name, strlen(rdrops))) msg_dropped += value; - if (0 == strncmp (cdrops, name, strlen (cdrops))) + if (0 == strncmp(cdrops, name, strlen(cdrops))) msg_dropped += value; return GNUNET_OK; @@ -444,26 +443,26 @@ stats_iterator (void *cls, * @param cls Closure (line from which the task was scheduled). */ static void -gather_stats_and_exit (void *cls) +gather_stats_and_exit(void *cls) { - long l = (long) cls; + long l = (long)cls; disconnect_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "gathering statistics from line %ld\n", - l); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "gathering statistics from line %ld\n", + l); if (NULL != outgoing_ch) - { - GNUNET_CADET_channel_destroy (outgoing_ch); - outgoing_ch = NULL; - } - stats_op = GNUNET_TESTBED_get_statistics (peers_running, - testbed_peers, - "cadet", - NULL, - &stats_iterator, - stats_cont, - cls); + { + GNUNET_CADET_channel_destroy(outgoing_ch); + outgoing_ch = NULL; + } + stats_op = GNUNET_TESTBED_get_statistics(peers_running, + testbed_peers, + "cadet", + NULL, + &stats_iterator, + stats_cont, + cls); } @@ -475,7 +474,7 @@ gather_stats_and_exit (void *cls) * @param channel Channel to send the message on. */ static void -send_test_message (struct GNUNET_CADET_Channel *channel); +send_test_message(struct GNUNET_CADET_Channel *channel); /** * Check if payload is sane (size contains payload). @@ -486,8 +485,8 @@ send_test_message (struct GNUNET_CADET_Channel *channel); * #GNUNET_SYSERR to close it (signal serious error). */ static int -check_data (void *cls, - const struct GNUNET_MessageHeader *message); +check_data(void *cls, + const struct GNUNET_MessageHeader *message); /** * Function is called whenever a message is received. @@ -496,8 +495,8 @@ check_data (void *cls, * @param message the actual message */ static void -handle_data (void *cls, - const struct GNUNET_MessageHeader *message); +handle_data(void *cls, + const struct GNUNET_MessageHeader *message); /** * Function called whenever an MQ-channel is destroyed, unless the destruction @@ -511,8 +510,8 @@ handle_data (void *cls, * @param channel Connection to the other end (henceforth invalid). */ static void -disconnect_handler (void *cls, - const struct GNUNET_CADET_Channel *channel); +disconnect_handler(void *cls, + const struct GNUNET_CADET_Channel *channel); /** @@ -521,37 +520,37 @@ disconnect_handler (void *cls, * @param cls Closure (line from which the task was scheduled). */ static void -reconnect_op (void *cls) +reconnect_op(void *cls) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (data, - GNUNET_MESSAGE_TYPE_DUMMY, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(data, + GNUNET_MESSAGE_TYPE_DUMMY, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end() }; - long l = (long) cls; + long l = (long)cls; struct CadetTestChannelWrapper *ch; reconnect_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "reconnecting from line %ld\n", - l); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "reconnecting from line %ld\n", + l); if (NULL != outgoing_ch) - { - GNUNET_CADET_channel_destroy (outgoing_ch); - outgoing_ch = NULL; - } - ch = GNUNET_new (struct CadetTestChannelWrapper); - outgoing_ch = GNUNET_CADET_channel_create (h1, - ch, - p_id[1], - &port, - NULL, - &disconnect_handler, - handlers); + { + GNUNET_CADET_channel_destroy(outgoing_ch); + outgoing_ch = NULL; + } + ch = GNUNET_new(struct CadetTestChannelWrapper); + outgoing_ch = GNUNET_CADET_channel_create(h1, + ch, + p_id[1], + &port, + NULL, + &disconnect_handler, + handlers); ch->ch = outgoing_ch; - send_test_message (outgoing_ch); + send_test_message(outgoing_ch); } /** @@ -566,47 +565,47 @@ reconnect_op (void *cls) * @param channel Connection to the other end (henceforth invalid). */ static void -disconnect_handler (void *cls, - const struct GNUNET_CADET_Channel *channel) +disconnect_handler(void *cls, + const struct GNUNET_CADET_Channel *channel) { struct CadetTestChannelWrapper *ch_w = cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Channel disconnected at %d\n", - ok); - GNUNET_assert (ch_w->ch == channel); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Channel disconnected at %d\n", + ok); + GNUNET_assert(ch_w->ch == channel); if (channel == incoming_ch) - { - ok++; - incoming_ch = NULL; - } - else if (outgoing_ch == channel) - { - if (P2P_SIGNAL == test) { ok++; + incoming_ch = NULL; + } + else if (outgoing_ch == channel) + { + if (P2P_SIGNAL == test) + { + ok++; + } + outgoing_ch = NULL; } - outgoing_ch = NULL; - } else - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Unknown channel! %p\n", - channel); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Unknown channel! %p\n", + channel); if (NULL != disconnect_task && REOPEN != test) - { - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = - GNUNET_SCHEDULER_add_now (&gather_stats_and_exit, - (void *) __LINE__); - } + { + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = + GNUNET_SCHEDULER_add_now(&gather_stats_and_exit, + (void *)__LINE__); + } else if (NULL != reconnect_task && REOPEN == test) - { - GNUNET_SCHEDULER_cancel (reconnect_task); - reconnect_task = - GNUNET_SCHEDULER_add_now (&reconnect_op, - (void *) __LINE__); - } - GNUNET_free (ch_w); + { + GNUNET_SCHEDULER_cancel(reconnect_task); + reconnect_task = + GNUNET_SCHEDULER_add_now(&reconnect_op, + (void *)__LINE__); + } + GNUNET_free(ch_w); } @@ -616,18 +615,18 @@ disconnect_handler (void *cls, * @param line Line in the code the abort is requested from (__LINE__). */ static void -abort_test (long line) +abort_test(long line) { if (NULL != disconnect_task) - { - GNUNET_SCHEDULER_cancel (disconnect_task); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Aborting test from %ld\n", - line); - disconnect_task = - GNUNET_SCHEDULER_add_now (&disconnect_cadet_peers, - (void *) line); - } + { + GNUNET_SCHEDULER_cancel(disconnect_task); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Aborting test from %ld\n", + line); + disconnect_task = + GNUNET_SCHEDULER_add_now(&disconnect_cadet_peers, + (void *)line); + } } @@ -639,7 +638,7 @@ abort_test (long line) * @param channel Channel to send the message on. */ static void -send_test_message (struct GNUNET_CADET_Channel *channel) +send_test_message(struct GNUNET_CADET_Channel *channel) { struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; @@ -647,64 +646,64 @@ send_test_message (struct GNUNET_CADET_Channel *channel) int payload; int size; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending test message on channel %p\n", - channel); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending test message on channel %p\n", + channel); size = size_payload; if (GNUNET_NO == initialized) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending INITIALIZER\n"); - size += 1000; - payload = data_sent; - if (SPEED_ACK == test) // FIXME unify SPEED_ACK with an initializer + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending INITIALIZER\n"); + size += 1000; + payload = data_sent; + if (SPEED_ACK == test) // FIXME unify SPEED_ACK with an initializer data_sent++; - } + } else if (SPEED == test || SPEED_ACK == test) - { - if (get_target_channel() == channel) + { + if (get_target_channel() == channel) + { + payload = ack_sent; + size += ack_sent; + ack_sent++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending ACK %u [%d bytes]\n", + payload, size); + } + else + { + payload = data_sent; + size += data_sent; + data_sent++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending DATA %u [%d bytes]\n", + data_sent, size); + } + } + else if (FORWARD == test) { payload = ack_sent; - size += ack_sent; - ack_sent++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending ACK %u [%d bytes]\n", - payload, size); } - else + else if (P2P_SIGNAL == test) { payload = data_sent; - size += data_sent; - data_sent++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending DATA %u [%d bytes]\n", - data_sent, size); } - } - else if (FORWARD == test) - { - payload = ack_sent; - } - else if (P2P_SIGNAL == test) - { - payload = data_sent; - } else if (REOPEN == test) - { - payload = data_sent; - data_sent++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending DATA %u [%d bytes]\n", - data_sent, size); - } + { + payload = data_sent; + data_sent++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending DATA %u [%d bytes]\n", + data_sent, size); + } else - { - GNUNET_assert (0); - } - env = GNUNET_MQ_msg_extra (msg, size, GNUNET_MESSAGE_TYPE_DUMMY); - - data = (uint32_t *) &msg[1]; - *data = htonl (payload); - GNUNET_MQ_send (GNUNET_CADET_get_mq (channel), env); + { + GNUNET_assert(0); + } + env = GNUNET_MQ_msg_extra(msg, size, GNUNET_MESSAGE_TYPE_DUMMY); + + data = (uint32_t *)&msg[1]; + *data = htonl(payload); + GNUNET_MQ_send(GNUNET_CADET_get_mq(channel), env); } @@ -715,30 +714,30 @@ send_test_message (struct GNUNET_CADET_Channel *channel) * @param cls Closure (unused). */ static void -send_next_msg (void *cls) +send_next_msg(void *cls) { struct GNUNET_CADET_Channel *channel; send_next_msg_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending next message: %d\n", - data_sent); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending next message: %d\n", + data_sent); channel = GNUNET_YES == test_backwards ? incoming_ch : outgoing_ch; - GNUNET_assert (NULL != channel); - GNUNET_assert (SPEED == test); - send_test_message (channel); + GNUNET_assert(NULL != channel); + GNUNET_assert(SPEED == test); + send_test_message(channel); if (data_sent < total_packets) - { - /* SPEED test: Send all messages as soon as possible */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Scheduling message %d\n", - data_sent + 1); - send_next_msg_task = - GNUNET_SCHEDULER_add_delayed (SEND_INTERVAL, - &send_next_msg, - NULL); - } + { + /* SPEED test: Send all messages as soon as possible */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Scheduling message %d\n", + data_sent + 1); + send_next_msg_task = + GNUNET_SCHEDULER_add_delayed(SEND_INTERVAL, + &send_next_msg, + NULL); + } } @@ -749,20 +748,20 @@ send_next_msg (void *cls) * @param line Code line number to log if a timeout occurs. */ static void -reschedule_timeout_task (long line) +reschedule_timeout_task(long line) { if ((ok % 10) == 0) - { - if (NULL != disconnect_task) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "reschedule timeout every 10 messages\n"); - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = GNUNET_SCHEDULER_add_delayed (short_time, - &gather_stats_and_exit, - (void *) line); + if (NULL != disconnect_task) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "reschedule timeout every 10 messages\n"); + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = GNUNET_SCHEDULER_add_delayed(short_time, + &gather_stats_and_exit, + (void *)line); + } } - } } @@ -775,8 +774,8 @@ reschedule_timeout_task (long line) * #GNUNET_SYSERR to close it (signal serious error). */ static int -check_data (void *cls, - const struct GNUNET_MessageHeader *message) +check_data(void *cls, + const struct GNUNET_MessageHeader *message) { return GNUNET_OK; /* all is well-formed */ } @@ -789,8 +788,8 @@ check_data (void *cls, * @param message the actual message */ static void -handle_data (void *cls, - const struct GNUNET_MessageHeader *message) +handle_data(void *cls, + const struct GNUNET_MessageHeader *message) { struct CadetTestChannelWrapper *ch = cls; struct GNUNET_CADET_Channel *channel = ch->ch; @@ -799,101 +798,101 @@ handle_data (void *cls, int *counter; ok++; - GNUNET_CADET_receive_done (channel); - counter = get_target_channel () == channel ? &data_received : &ack_received; + GNUNET_CADET_receive_done(channel); + counter = get_target_channel() == channel ? &data_received : &ack_received; - reschedule_timeout_task ((long) __LINE__); + reschedule_timeout_task((long)__LINE__); if (channel == outgoing_ch) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Root client got a message.\n"); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Root client got a message.\n"); + } else if (channel == incoming_ch) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Leaf client got a message.\n"); - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unknown channel %p.\n", - channel); - GNUNET_assert (0); - } - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - " ok: (%d/%d)\n", - ok, - ok_goal); - data = (uint32_t *) &message[1]; - payload = ntohl (*data); - if (payload == *counter) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - " payload as expected: %u\n", - payload); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Leaf client got a message.\n"); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - " payload %u, expected: %u\n", - payload, *counter); - } - - if (GNUNET_NO == initialized) - { - initialized = GNUNET_YES; - start_time = GNUNET_TIME_absolute_get (); - if (SPEED == test) { - GNUNET_assert (incoming_ch == channel); - send_next_msg_task = GNUNET_SCHEDULER_add_now (&send_next_msg, - NULL); - return; + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unknown channel %p.\n", + channel); + GNUNET_assert(0); } - } - (*counter)++; - if (get_target_channel () == channel) /* Got "data" */ - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, " received data %u\n", data_received); - if (SPEED != test || (ok_goal - 2) == ok) + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + " ok: (%d/%d)\n", + ok, + ok_goal); + data = (uint32_t *)&message[1]; + payload = ntohl(*data); + if (payload == *counter) { - /* Send ACK */ - send_test_message (channel); - return; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + " payload as expected: %u\n", + payload); } - else + else { - if (data_received < total_packets) - return; + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + " payload %u, expected: %u\n", + payload, *counter); } - } - else /* Got "ack" */ - { - if (SPEED_ACK == test || SPEED == test) + + if (GNUNET_NO == initialized) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, " received ack %u\n", ack_received); - /* Send more data */ - send_test_message (channel); - if (ack_received < total_packets && SPEED != test) - return; - if (ok == 2 && SPEED == test) - return; - show_end_data (); + initialized = GNUNET_YES; + start_time = GNUNET_TIME_absolute_get(); + if (SPEED == test) + { + GNUNET_assert(incoming_ch == channel); + send_next_msg_task = GNUNET_SCHEDULER_add_now(&send_next_msg, + NULL); + return; + } } - if (test == P2P_SIGNAL) + + (*counter)++; + if (get_target_channel() == channel) /* Got "data" */ { - GNUNET_CADET_channel_destroy (incoming_ch); - incoming_ch = NULL; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, " received data %u\n", data_received); + if (SPEED != test || (ok_goal - 2) == ok) + { + /* Send ACK */ + send_test_message(channel); + return; + } + else + { + if (data_received < total_packets) + return; + } } - else + else /* Got "ack" */ { - GNUNET_CADET_channel_destroy (outgoing_ch); - outgoing_ch = NULL; + if (SPEED_ACK == test || SPEED == test) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, " received ack %u\n", ack_received); + /* Send more data */ + send_test_message(channel); + if (ack_received < total_packets && SPEED != test) + return; + if (ok == 2 && SPEED == test) + return; + show_end_data(); + } + if (test == P2P_SIGNAL) + { + GNUNET_CADET_channel_destroy(incoming_ch); + incoming_ch = NULL; + } + else + { + GNUNET_CADET_channel_destroy(outgoing_ch); + outgoing_ch = NULL; + } } - } } @@ -910,66 +909,66 @@ handle_data (void *cls, * received on the @a channel. */ static void * -connect_handler (void *cls, - struct GNUNET_CADET_Channel *channel, - const struct GNUNET_PeerIdentity *source) +connect_handler(void *cls, + struct GNUNET_CADET_Channel *channel, + const struct GNUNET_PeerIdentity *source) { struct CadetTestChannelWrapper *ch; - long peer = (long) cls; + long peer = (long)cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Incoming channel from %s to %ld: %p\n", - GNUNET_i2s (source), - peer, - channel); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Incoming channel from %s to %ld: %p\n", + GNUNET_i2s(source), + peer, + channel); ok++; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - " ok: %d\n", - ok); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + " ok: %d\n", + ok); if (peer == peers_requested - 1) - { - if (NULL != incoming_ch) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Duplicate incoming channel for client %lu\n", - (long) cls); - GNUNET_assert (0); + if (NULL != incoming_ch) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Duplicate incoming channel for client %lu\n", + (long)cls); + GNUNET_assert(0); + } + incoming_ch = channel; } - incoming_ch = channel; - } else - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Incoming channel for unexpected peer #%lu\n", - (long) cls); - GNUNET_assert (0); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Incoming channel for unexpected peer #%lu\n", + (long)cls); + GNUNET_assert(0); + } if (NULL != disconnect_task && REOPEN != test) - { - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = GNUNET_SCHEDULER_add_delayed (short_time, - &gather_stats_and_exit, - (void *) __LINE__); - } + { + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = GNUNET_SCHEDULER_add_delayed(short_time, + &gather_stats_and_exit, + (void *)__LINE__); + } else if ((NULL != disconnect_task) && (REOPEN == test)) - { - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = GNUNET_SCHEDULER_add_delayed ( - GNUNET_TIME_relative_multiply (short_time, 2), + { + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = GNUNET_SCHEDULER_add_delayed( + GNUNET_TIME_relative_multiply(short_time, 2), &gather_stats_and_exit, - (void *) __LINE__); - } + (void *)__LINE__); + } if ((NULL != reconnect_task) && (REOPEN == test)) - { - GNUNET_SCHEDULER_cancel (reconnect_task); - reconnect_task = GNUNET_SCHEDULER_add_delayed (short_time, - &reconnect_op, - (void *) __LINE__); - } + { + GNUNET_SCHEDULER_cancel(reconnect_task); + reconnect_task = GNUNET_SCHEDULER_add_delayed(short_time, + &reconnect_op, + (void *)__LINE__); + } /* TODO: cannot return channel as-is, in order to unify the data handlers */ - ch = GNUNET_new (struct CadetTestChannelWrapper); + ch = GNUNET_new(struct CadetTestChannelWrapper); ch->ch = channel; return ch; @@ -985,44 +984,44 @@ connect_handler (void *cls, * @param cls Closure (unused). */ static void -start_test (void *cls) +start_test(void *cls) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (data, - GNUNET_MESSAGE_TYPE_DUMMY, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(data, + GNUNET_MESSAGE_TYPE_DUMMY, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end() }; struct CadetTestChannelWrapper *ch; test_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "start_test: %s\n", test_name); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "start_test: %s\n", test_name); if (NULL != disconnect_task) - { - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = NULL; + } if (SPEED_REL == test) - { - test = SPEED; - } - - ch = GNUNET_new (struct CadetTestChannelWrapper); - outgoing_ch = GNUNET_CADET_channel_create (h1, - ch, - p_id[1], - &port, - NULL, - &disconnect_handler, - handlers); + { + test = SPEED; + } + + ch = GNUNET_new(struct CadetTestChannelWrapper); + outgoing_ch = GNUNET_CADET_channel_create(h1, + ch, + p_id[1], + &port, + NULL, + &disconnect_handler, + handlers); ch->ch = outgoing_ch; - disconnect_task = GNUNET_SCHEDULER_add_delayed (short_time, - &gather_stats_and_exit, - (void *) __LINE__); + disconnect_task = GNUNET_SCHEDULER_add_delayed(short_time, + &gather_stats_and_exit, + (void *)__LINE__); if (KEEPALIVE == test) return; /* Don't send any data. */ @@ -1030,22 +1029,21 @@ start_test (void *cls) data_sent = 0; ack_received = 0; ack_sent = 0; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending data initializer on channel %p...\n", - outgoing_ch); - send_test_message (outgoing_ch); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending data initializer on channel %p...\n", + outgoing_ch); + send_test_message(outgoing_ch); if (REOPEN == test) - { - reconnect_task = GNUNET_SCHEDULER_add_delayed (short_time, - &reconnect_op, - (void *) __LINE__); - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = GNUNET_SCHEDULER_add_delayed ( - GNUNET_TIME_relative_multiply (short_time, 2), + { + reconnect_task = GNUNET_SCHEDULER_add_delayed(short_time, + &reconnect_op, + (void *)__LINE__); + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = GNUNET_SCHEDULER_add_delayed( + GNUNET_TIME_relative_multiply(short_time, 2), &gather_stats_and_exit, - (void *) __LINE__); - } - + (void *)__LINE__); + } } @@ -1059,35 +1057,35 @@ start_test (void *cls) * NULL if the operation is successfull */ static void -pi_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - const struct GNUNET_TESTBED_PeerInformation *pinfo, - const char *emsg) +pi_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + const struct GNUNET_TESTBED_PeerInformation *pinfo, + const char *emsg) { - long i = (long) cls; - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "ID callback for %ld\n", - i); - if ( (NULL == pinfo) || - (NULL != emsg) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "pi_cb: %s\n", - emsg); - abort_test (__LINE__); - return; - } + long i = (long)cls; + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "ID callback for %ld\n", + i); + if ((NULL == pinfo) || + (NULL != emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "pi_cb: %s\n", + emsg); + abort_test(__LINE__); + return; + } p_id[i] = pinfo->result.id; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "id: %s\n", - GNUNET_i2s (p_id[i])); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "id: %s\n", + GNUNET_i2s(p_id[i])); p_ids++; if (p_ids < 2) return; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got all IDs, starting test\n"); - test_task = GNUNET_SCHEDULER_add_now (&start_test, NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got all IDs, starting test\n"); + test_task = GNUNET_SCHEDULER_add_now(&start_test, NULL); } @@ -1101,34 +1099,34 @@ pi_cb (void *cls, * @param cadets Handle to each of the CADETs of the peers. */ static void -tmain (void *cls, - struct GNUNET_CADET_TEST_Context *ctx, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - struct GNUNET_CADET_Handle **cadets) +tmain(void *cls, + struct GNUNET_CADET_TEST_Context *ctx, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + struct GNUNET_CADET_Handle **cadets) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "test main\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "test main\n"); ok = 0; test_ctx = ctx; peers_running = num_peers; - GNUNET_assert (peers_running == peers_requested); + GNUNET_assert(peers_running == peers_requested); testbed_peers = peers; h1 = cadets[0]; h2 = cadets[num_peers - 1]; - disconnect_task = GNUNET_SCHEDULER_add_delayed (short_time, - &disconnect_cadet_peers, - (void *) __LINE__); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); - t_op[0] = GNUNET_TESTBED_peer_get_information (peers[0], - GNUNET_TESTBED_PIT_IDENTITY, - &pi_cb, - (void *) 0L); - t_op[1] = GNUNET_TESTBED_peer_get_information (peers[num_peers - 1], - GNUNET_TESTBED_PIT_IDENTITY, - &pi_cb, - (void *) 1L); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "requested peer ids\n"); + disconnect_task = GNUNET_SCHEDULER_add_delayed(short_time, + &disconnect_cadet_peers, + (void *)__LINE__); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); + t_op[0] = GNUNET_TESTBED_peer_get_information(peers[0], + GNUNET_TESTBED_PIT_IDENTITY, + &pi_cb, + (void *)0L); + t_op[1] = GNUNET_TESTBED_peer_get_information(peers[num_peers - 1], + GNUNET_TESTBED_PIT_IDENTITY, + &pi_cb, + (void *)1L); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "requested peer ids\n"); } @@ -1136,179 +1134,179 @@ tmain (void *cls, * Main: start test */ int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { static const struct GNUNET_HashCode *ports[2]; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (data, - GNUNET_MESSAGE_TYPE_DUMMY, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(data, + GNUNET_MESSAGE_TYPE_DUMMY, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end() }; const char *config_file; char port_id[] = "test port"; struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_option_relative_time ('t', - "time", - "short_time", - gettext_noop ("set short timeout"), - &short_time), - GNUNET_GETOPT_option_uint ('m', - "messages", - "NUM_MESSAGES", - gettext_noop ("set number of messages to send"), - &total_packets), + GNUNET_GETOPT_option_relative_time('t', + "time", + "short_time", + gettext_noop("set short timeout"), + &short_time), + GNUNET_GETOPT_option_uint('m', + "messages", + "NUM_MESSAGES", + gettext_noop("set number of messages to send"), + &total_packets), GNUNET_GETOPT_OPTION_END }; initialized = GNUNET_NO; - GNUNET_log_setup ("test", "DEBUG", NULL); + GNUNET_log_setup("test", "DEBUG", NULL); total_packets = TOTAL_PACKETS; short_time = SHORT_TIME; - if (-1 == GNUNET_GETOPT_run (argv[0], options, argc, argv)) - { - fprintf (stderr, "test failed: problem with CLI parameters\n"); - exit (1); - } + if (-1 == GNUNET_GETOPT_run(argv[0], options, argc, argv)) + { + fprintf(stderr, "test failed: problem with CLI parameters\n"); + exit(1); + } config_file = "test_cadet.conf"; - GNUNET_CRYPTO_hash (port_id, sizeof (port_id), &port); + GNUNET_CRYPTO_hash(port_id, sizeof(port_id), &port); /* Find out requested size */ - if (strstr (argv[0], "_2_") != NULL) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "DIRECT CONNECTIONs\n"); - peers_requested = 2; - } - else if (strstr (argv[0], "_5_") != NULL) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "5 PEER LINE\n"); - peers_requested = 5; - } - else if (strstr (argv[0], "_6_") != NULL) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "6 PEER LINE\n"); - peers_requested = 6; - } + if (strstr(argv[0], "_2_") != NULL) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "DIRECT CONNECTIONs\n"); + peers_requested = 2; + } + else if (strstr(argv[0], "_5_") != NULL) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "5 PEER LINE\n"); + peers_requested = 5; + } + else if (strstr(argv[0], "_6_") != NULL) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "6 PEER LINE\n"); + peers_requested = 6; + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "SIZE UNKNOWN, USING 2\n"); - peers_requested = 2; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "SIZE UNKNOWN, USING 2\n"); + peers_requested = 2; + } /* Find out requested test */ - if (strstr (argv[0], "_forward") != NULL) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "FORWARD\n"); - test = FORWARD; - test_name = "unicast"; - ok_goal = 4; - } - else if (strstr (argv[0], "_signal") != NULL) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "SIGNAL\n"); - test = P2P_SIGNAL; - test_name = "signal"; - ok_goal = 4; - } - else if (strstr (argv[0], "_speed_ack") != NULL) - { - /* Test is supposed to generate the following callbacks: - * 1 incoming channel (@dest) - * total_packets received data packet (@dest) - * total_packets received data packet (@orig) - * 1 received channel destroy (@dest) FIXME #5818 - */ - ok_goal = total_packets * 2 + 2; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "SPEED_ACK\n"); - test = SPEED_ACK; - test_name = "speed ack"; - } - else if (strstr (argv[0], "_speed") != NULL) - { - /* Test is supposed to generate the following callbacks: - * 1 incoming channel (@dest) - * 1 initial packet (@dest) - * total_packets received data packet (@dest) - * 1 received data packet (@orig) - * 1 received channel destroy (@dest) FIXME #5818 - */ - ok_goal = total_packets + 4; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "SPEED\n"); - if (strstr (argv[0], "_reliable") != NULL) + if (strstr(argv[0], "_forward") != NULL) { - test = SPEED_REL; - test_name = "speed reliable"; - config_file = "test_cadet_drop.conf"; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "FORWARD\n"); + test = FORWARD; + test_name = "unicast"; + ok_goal = 4; } - else + else if (strstr(argv[0], "_signal") != NULL) { - test = SPEED; - test_name = "speed"; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "SIGNAL\n"); + test = P2P_SIGNAL; + test_name = "signal"; + ok_goal = 4; + } + else if (strstr(argv[0], "_speed_ack") != NULL) + { + /* Test is supposed to generate the following callbacks: + * 1 incoming channel (@dest) + * total_packets received data packet (@dest) + * total_packets received data packet (@orig) + * 1 received channel destroy (@dest) FIXME #5818 + */ + ok_goal = total_packets * 2 + 2; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "SPEED_ACK\n"); + test = SPEED_ACK; + test_name = "speed ack"; + } + else if (strstr(argv[0], "_speed") != NULL) + { + /* Test is supposed to generate the following callbacks: + * 1 incoming channel (@dest) + * 1 initial packet (@dest) + * total_packets received data packet (@dest) + * 1 received data packet (@orig) + * 1 received channel destroy (@dest) FIXME #5818 + */ + ok_goal = total_packets + 4; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "SPEED\n"); + if (strstr(argv[0], "_reliable") != NULL) + { + test = SPEED_REL; + test_name = "speed reliable"; + config_file = "test_cadet_drop.conf"; + } + else + { + test = SPEED; + test_name = "speed"; + } + } + else if (strstr(argv[0], "_keepalive") != NULL) + { + test = KEEPALIVE; + test_name = "keepalive"; + /* Test is supposed to generate the following callbacks: + * 1 incoming channel (@dest) + * [wait] + * 1 received channel destroy (@dest) FIXME #5818 + */ + ok_goal = 1; + } + else if (strstr(argv[0], "_reopen") != NULL) + { + test = REOPEN; + test_name = "reopen"; + ///* Test is supposed to generate the following callbacks: + // * 1 incoming channel (@dest) + // * [wait] + // * 1 received channel destroy (@dest) FIXME #5818 + // */ + ok_goal = 6; } - } - else if (strstr (argv[0], "_keepalive") != NULL) - { - test = KEEPALIVE; - test_name = "keepalive"; - /* Test is supposed to generate the following callbacks: - * 1 incoming channel (@dest) - * [wait] - * 1 received channel destroy (@dest) FIXME #5818 - */ - ok_goal = 1; - } - else if (strstr (argv[0], "_reopen") != NULL) - { - test = REOPEN; - test_name = "reopen"; - ///* Test is supposed to generate the following callbacks: - // * 1 incoming channel (@dest) - // * [wait] - // * 1 received channel destroy (@dest) FIXME #5818 - // */ - ok_goal = 6; - } else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "UNKNOWN\n"); - test = SETUP; - ok_goal = 0; - } - - if (strstr (argv[0], "backwards") != NULL) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "BACKWARDS (LEAF TO ROOT)\n"); - test_backwards = GNUNET_YES; - GNUNET_asprintf (&test_name, "backwards %s", test_name); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "UNKNOWN\n"); + test = SETUP; + ok_goal = 0; + } + + if (strstr(argv[0], "backwards") != NULL) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "BACKWARDS (LEAF TO ROOT)\n"); + test_backwards = GNUNET_YES; + GNUNET_asprintf(&test_name, "backwards %s", test_name); + } p_ids = 0; ports[0] = &port; ports[1] = NULL; - GNUNET_CADET_TEST_ruN ("test_cadet_small", - config_file, - peers_requested, - &tmain, - NULL, /* tmain cls */ - &connect_handler, - NULL, - &disconnect_handler, - handlers, - ports); - if (NULL != strstr (argv[0], "_reliable")) + GNUNET_CADET_TEST_ruN("test_cadet_small", + config_file, + peers_requested, + &tmain, + NULL, /* tmain cls */ + &connect_handler, + NULL, + &disconnect_handler, + handlers, + ports); + if (NULL != strstr(argv[0], "_reliable")) msg_dropped = 0; /* dropped should be retransmitted */ if (ok_goal > ok - msg_dropped) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "FAILED! (%d/%d)\n", ok, ok_goal); - return 1; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "success\n"); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "FAILED! (%d/%d)\n", ok, ok_goal); + return 1; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "success\n"); return 0; } diff --git a/src/cadet/test_cadet_flow.c b/src/cadet/test_cadet_flow.c index 87e7b9a03..5278dc00f 100644 --- a/src/cadet/test_cadet_flow.c +++ b/src/cadet/test_cadet_flow.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/test_cadet_flow.c * @author Bart Polot @@ -34,8 +34,7 @@ /** * Ugly workaround to unify data handlers on incoming and outgoing channels. */ -struct CadetTestChannelWrapper -{ +struct CadetTestChannelWrapper { /** * Channel pointer. */ @@ -50,17 +49,17 @@ struct CadetTestChannelWrapper /** * How long until we give up on connecting the peers? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 120) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 120) /** * Time to wait by default for stuff that should be rather fast. */ -#define SHORT_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 20) +#define SHORT_TIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 20) /** * How fast do we send messages? */ -#define SEND_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 10) +#define SEND_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 10) /** @@ -76,7 +75,7 @@ static struct GNUNET_TIME_Relative short_time; /** * Size of each test packet's payload */ -static size_t size_payload = sizeof (uint32_t); +static size_t size_payload = sizeof(uint32_t); /** * Operation to get peer ids. @@ -209,29 +208,29 @@ static unsigned int msg_dropped; * Show the results of the test (banwidth acheived) and log them to GAUGER */ static void -show_end_data (void) +show_end_data(void) { static struct GNUNET_TIME_Absolute end_time; static struct GNUNET_TIME_Relative total_time; - end_time = GNUNET_TIME_absolute_get (); - total_time = GNUNET_TIME_absolute_get_difference (start_time, end_time); - fprintf (stderr, - "\nResults of test \"%s\"\n", - test_name); - fprintf (stderr, - "Test time %s\n", - GNUNET_STRINGS_relative_time_to_string (total_time, GNUNET_YES)); - fprintf (stderr, - "Test bandwidth: %f kb/s\n", - 4 * total_packets * 1.0 / (total_time.rel_value_us / 1000)); // 4bytes * ms - fprintf (stderr, - "Test throughput: %f packets/s\n\n", - total_packets * 1000.0 / (total_time.rel_value_us / 1000)); // packets * ms - GAUGER ("CADET", - test_name, - total_packets * 1000.0 / (total_time.rel_value_us / 1000), - "packets/s"); + end_time = GNUNET_TIME_absolute_get(); + total_time = GNUNET_TIME_absolute_get_difference(start_time, end_time); + fprintf(stderr, + "\nResults of test \"%s\"\n", + test_name); + fprintf(stderr, + "Test time %s\n", + GNUNET_STRINGS_relative_time_to_string(total_time, GNUNET_YES)); + fprintf(stderr, + "Test bandwidth: %f kb/s\n", + 4 * total_packets * 1.0 / (total_time.rel_value_us / 1000)); // 4bytes * ms + fprintf(stderr, + "Test throughput: %f packets/s\n\n", + total_packets * 1000.0 / (total_time.rel_value_us / 1000)); // packets * ms + GAUGER("CADET", + test_name, + total_packets * 1000.0 / (total_time.rel_value_us / 1000), + "packets/s"); } @@ -242,33 +241,33 @@ show_end_data (void) * @param tc Task Context. */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Ending test.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Ending test.\n"); if (NULL != send_next_msg_task) - { - GNUNET_SCHEDULER_cancel (send_next_msg_task); - send_next_msg_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(send_next_msg_task); + send_next_msg_task = NULL; + } if (NULL != test_task) - { - GNUNET_SCHEDULER_cancel (test_task); - test_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(test_task); + test_task = NULL; + } for (unsigned int i = 0; i < 2; i++) - GNUNET_TESTBED_operation_done (t_op[i]); + GNUNET_TESTBED_operation_done(t_op[i]); if (NULL != outgoing_ch) - { - GNUNET_CADET_channel_destroy (outgoing_ch); - outgoing_ch = NULL; - } + { + GNUNET_CADET_channel_destroy(outgoing_ch); + outgoing_ch = NULL; + } if (NULL != incoming_ch) - { - GNUNET_CADET_channel_destroy (incoming_ch); - incoming_ch = NULL; - } - GNUNET_CADET_TEST_cleanup (test_ctx); + { + GNUNET_CADET_channel_destroy(incoming_ch); + incoming_ch = NULL; + } + GNUNET_CADET_TEST_cleanup(test_ctx); } @@ -282,25 +281,25 @@ shutdown_task (void *cls) * operation has executed successfully. */ static void -stats_cont (void *cls, - struct GNUNET_TESTBED_Operation *op, - const char *emsg) +stats_cont(void *cls, + struct GNUNET_TESTBED_Operation *op, + const char *emsg) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "KA sent: %u, KA received: %u\n", - ka_sent, - ka_received); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "KA sent: %u, KA received: %u\n", + ka_sent, + ka_received); if ((KEEPALIVE == test) && ((ka_sent < 2) || (ka_sent > ka_received + 1))) - { - GNUNET_break (0); - ok--; - } - GNUNET_TESTBED_operation_done (stats_op); + { + GNUNET_break(0); + ok--; + } + GNUNET_TESTBED_operation_done(stats_op); if (NULL != disconnect_task) - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = GNUNET_SCHEDULER_add_now (&disconnect_cadet_peers, - cls); + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = GNUNET_SCHEDULER_add_now(&disconnect_cadet_peers, + cls); } @@ -316,12 +315,12 @@ stats_cont (void *cls, * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration */ static int -stats_iterator (void *cls, - const struct GNUNET_TESTBED_Peer *peer, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +stats_iterator(void *cls, + const struct GNUNET_TESTBED_Peer *peer, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { static const char *s_sent = "# keepalives sent"; static const char *s_recv = "# keepalives received"; @@ -329,16 +328,16 @@ stats_iterator (void *cls, static const char *cdrops = "# messages dropped due to slow client"; uint32_t i; - i = GNUNET_TESTBED_get_index (peer); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "STATS PEER %u - %s [%s]: %llu\n", i, - subsystem, name, (unsigned long long) value); - if (0 == strncmp (s_sent, name, strlen (s_sent)) && 0 == i) + i = GNUNET_TESTBED_get_index(peer); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "STATS PEER %u - %s [%s]: %llu\n", i, + subsystem, name, (unsigned long long)value); + if (0 == strncmp(s_sent, name, strlen(s_sent)) && 0 == i) ka_sent = value; - if (0 == strncmp (s_recv, name, strlen (s_recv)) && peers_requested - 1 == i) + if (0 == strncmp(s_recv, name, strlen(s_recv)) && peers_requested - 1 == i) ka_received = value; - if (0 == strncmp (rdrops, name, strlen (rdrops))) + if (0 == strncmp(rdrops, name, strlen(rdrops))) msg_dropped += value; - if (0 == strncmp (cdrops, name, strlen (cdrops))) + if (0 == strncmp(cdrops, name, strlen(cdrops))) msg_dropped += value; return GNUNET_OK; @@ -351,26 +350,26 @@ stats_iterator (void *cls, * @param cls Closure (line from which the task was scheduled). */ static void -gather_stats_and_exit (void *cls) +gather_stats_and_exit(void *cls) { - long l = (long) cls; + long l = (long)cls; disconnect_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "gathering statistics from line %ld\n", - l); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "gathering statistics from line %ld\n", + l); if (NULL != outgoing_ch) - { - GNUNET_CADET_channel_destroy (outgoing_ch); - outgoing_ch = NULL; - } - stats_op = GNUNET_TESTBED_get_statistics (peers_running, - testbed_peers, - "cadet", - NULL, - &stats_iterator, - stats_cont, - cls); + { + GNUNET_CADET_channel_destroy(outgoing_ch); + outgoing_ch = NULL; + } + stats_op = GNUNET_TESTBED_get_statistics(peers_running, + testbed_peers, + "cadet", + NULL, + &stats_iterator, + stats_cont, + cls); } @@ -380,18 +379,18 @@ gather_stats_and_exit (void *cls) * @param line Line in the code the abort is requested from (__LINE__). */ static void -abort_test (long line) +abort_test(long line) { if (NULL != disconnect_task) - { - GNUNET_SCHEDULER_cancel (disconnect_task); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Aborting test from %ld\n", - line); - disconnect_task = - GNUNET_SCHEDULER_add_now (&disconnect_cadet_peers, - (void *) line); - } + { + GNUNET_SCHEDULER_cancel(disconnect_task); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Aborting test from %ld\n", + line); + disconnect_task = + GNUNET_SCHEDULER_add_now(&disconnect_cadet_peers, + (void *)line); + } } @@ -403,7 +402,7 @@ abort_test (long line) * @param channel Channel to send the message on. */ static void -send_test_message (struct GNUNET_CADET_Channel *channel) +send_test_message(struct GNUNET_CADET_Channel *channel) { struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; @@ -411,56 +410,56 @@ send_test_message (struct GNUNET_CADET_Channel *channel) int payload; int size; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending test message on channel %p\n", - channel); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending test message on channel %p\n", + channel); size = size_payload; if (GNUNET_NO == initialized) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending INITIALIZER\n"); - size += 1000; - payload = data_sent; - if (SPEED_ACK == test) // FIXME unify SPEED_ACK with an initializer + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending INITIALIZER\n"); + size += 1000; + payload = data_sent; + if (SPEED_ACK == test) // FIXME unify SPEED_ACK with an initializer data_sent++; - } + } else if (SPEED == test || SPEED_ACK == test) - { - if (get_target_channel() == channel) + { + if (get_target_channel() == channel) + { + payload = ack_sent; + size += ack_sent; + ack_sent++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending ACK %u [%d bytes]\n", + payload, size); + } + else + { + payload = data_sent; + size += data_sent; + data_sent++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending DATA %u [%d bytes]\n", + data_sent, size); + } + } + else if (FORWARD == test) { payload = ack_sent; - size += ack_sent; - ack_sent++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending ACK %u [%d bytes]\n", - payload, size); } - else + else if (P2P_SIGNAL == test) { payload = data_sent; - size += data_sent; - data_sent++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending DATA %u [%d bytes]\n", - data_sent, size); } - } - else if (FORWARD == test) - { - payload = ack_sent; - } - else if (P2P_SIGNAL == test) - { - payload = data_sent; - } else - { - GNUNET_assert (0); - } - env = GNUNET_MQ_msg_extra (msg, size, GNUNET_MESSAGE_TYPE_DUMMY); - - data = (uint32_t *) &msg[1]; - *data = htonl (payload); - GNUNET_MQ_send (GNUNET_CADET_get_mq (channel), env); + { + GNUNET_assert(0); + } + env = GNUNET_MQ_msg_extra(msg, size, GNUNET_MESSAGE_TYPE_DUMMY); + + data = (uint32_t *)&msg[1]; + *data = htonl(payload); + GNUNET_MQ_send(GNUNET_CADET_get_mq(channel), env); } @@ -471,30 +470,30 @@ send_test_message (struct GNUNET_CADET_Channel *channel) * @param cls Closure (unused). */ static void -send_next_msg (void *cls) +send_next_msg(void *cls) { struct GNUNET_CADET_Channel *channel; send_next_msg_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending next message: %d\n", - data_sent); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending next message: %d\n", + data_sent); channel = GNUNET_YES == test_backwards ? incoming_ch : outgoing_ch; - GNUNET_assert (NULL != channel); - GNUNET_assert (SPEED == test); - send_test_message (channel); + GNUNET_assert(NULL != channel); + GNUNET_assert(SPEED == test); + send_test_message(channel); if (data_sent < total_packets) - { - /* SPEED test: Send all messages as soon as possible */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Scheduling message %d\n", - data_sent + 1); - send_next_msg_task = - GNUNET_SCHEDULER_add_delayed (SEND_INTERVAL, - &send_next_msg, - NULL); - } + { + /* SPEED test: Send all messages as soon as possible */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Scheduling message %d\n", + data_sent + 1); + send_next_msg_task = + GNUNET_SCHEDULER_add_delayed(SEND_INTERVAL, + &send_next_msg, + NULL); + } } @@ -507,8 +506,8 @@ send_next_msg (void *cls) * #GNUNET_SYSERR to close it (signal serious error). */ static int -check_data (void *cls, - const struct GNUNET_MessageHeader *message) +check_data(void *cls, + const struct GNUNET_MessageHeader *message) { return GNUNET_OK; /* all is well-formed */ } @@ -521,8 +520,8 @@ check_data (void *cls, * @param message the actual message */ static void -handle_data (void *cls, - const struct GNUNET_MessageHeader *message) +handle_data(void *cls, + const struct GNUNET_MessageHeader *message) { struct CadetTestChannelWrapper *ch = cls; struct GNUNET_CADET_Channel *channel = ch->ch; @@ -530,73 +529,73 @@ handle_data (void *cls, uint32_t payload; int *counter; - GNUNET_CADET_receive_done (channel); - counter = get_target_channel () == channel ? &data_received : &ack_received; + GNUNET_CADET_receive_done(channel); + counter = get_target_channel() == channel ? &data_received : &ack_received; if (channel == outgoing_ch) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Root client got a message.\n"); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Root client got a message.\n"); + } else if (channel == incoming_ch) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Leaf client got a message.\n"); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Leaf client got a message.\n"); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unknown channel %p.\n", - channel); - GNUNET_assert (0); - } - - data = (uint32_t *) &message[1]; - payload = ntohl (*data); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unknown channel %p.\n", + channel); + GNUNET_assert(0); + } + + data = (uint32_t *)&message[1]; + payload = ntohl(*data); if (payload == *counter) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Payload as expected: %u\n", - payload); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Payload as expected: %u\n", + payload); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Received payload %u, expected: %u\n", - payload, *counter); - } - (*counter)++; - if (get_target_channel () == channel) /* Got "data" */ - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - " received data %u\n", - data_received); - if (data_received < total_packets) - return; - } - else /* Got "ack" */ - { - if (SPEED_ACK == test || SPEED == test) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, " received ack %u\n", ack_received); - /* Send more data */ - send_test_message (channel); - if (ack_received < total_packets && SPEED != test) - return; - if (ok == 2 && SPEED == test) - return; - show_end_data (); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Received payload %u, expected: %u\n", + payload, *counter); } - if (test == P2P_SIGNAL) + (*counter)++; + if (get_target_channel() == channel) /* Got "data" */ { - GNUNET_CADET_channel_destroy (incoming_ch); - incoming_ch = NULL; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + " received data %u\n", + data_received); + if (data_received < total_packets) + return; } - else + else /* Got "ack" */ { - GNUNET_CADET_channel_destroy (outgoing_ch); - outgoing_ch = NULL; + if (SPEED_ACK == test || SPEED == test) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, " received ack %u\n", ack_received); + /* Send more data */ + send_test_message(channel); + if (ack_received < total_packets && SPEED != test) + return; + if (ok == 2 && SPEED == test) + return; + show_end_data(); + } + if (test == P2P_SIGNAL) + { + GNUNET_CADET_channel_destroy(incoming_ch); + incoming_ch = NULL; + } + else + { + GNUNET_CADET_channel_destroy(outgoing_ch); + outgoing_ch = NULL; + } } - } } @@ -613,37 +612,37 @@ handle_data (void *cls, * received on the @a channel. */ static void * -connect_handler (void *cls, - struct GNUNET_CADET_Channel *channel, - const struct GNUNET_PeerIdentity *source) +connect_handler(void *cls, + struct GNUNET_CADET_Channel *channel, + const struct GNUNET_PeerIdentity *source) { struct CadetTestChannelWrapper *ch; - long peer = (long) cls; + long peer = (long)cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Incoming channel from %s to %ld: %p\n", - GNUNET_i2s (source), - peer, - channel); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Incoming channel from %s to %ld: %p\n", + GNUNET_i2s(source), + peer, + channel); if (peer == peers_requested - 1) - { - if (NULL != incoming_ch) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Duplicate incoming channel for client %lu\n", - (long) cls); - GNUNET_assert (0); + if (NULL != incoming_ch) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Duplicate incoming channel for client %lu\n", + (long)cls); + GNUNET_assert(0); + } + incoming_ch = channel; } - incoming_ch = channel; - } else - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Incoming channel for unexpected peer #%lu\n", - (long) cls); - GNUNET_assert (0); - } - ch = GNUNET_new (struct CadetTestChannelWrapper); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Incoming channel for unexpected peer #%lu\n", + (long)cls); + GNUNET_assert(0); + } + ch = GNUNET_new(struct CadetTestChannelWrapper); ch->ch = channel; return ch; @@ -662,28 +661,28 @@ connect_handler (void *cls, * @param channel Connection to the other end (henceforth invalid). */ static void -disconnect_handler (void *cls, - const struct GNUNET_CADET_Channel *channel) +disconnect_handler(void *cls, + const struct GNUNET_CADET_Channel *channel) { struct CadetTestChannelWrapper *ch_w = cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Channel disconnected at %d\n", - ok); - GNUNET_assert (ch_w->ch == channel); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Channel disconnected at %d\n", + ok); + GNUNET_assert(ch_w->ch == channel); if (channel == incoming_ch) incoming_ch = NULL; else if (outgoing_ch == channel) outgoing_ch = NULL; else - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Disconnect on unknown channel %p\n", - channel); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Disconnect on unknown channel %p\n", + channel); if (NULL != disconnect_task) - GNUNET_SCHEDULER_cancel (disconnect_task); - disconnect_task = GNUNET_SCHEDULER_add_now (&gather_stats_and_exit, - (void *) __LINE__); - GNUNET_free (ch_w); + GNUNET_SCHEDULER_cancel(disconnect_task); + disconnect_task = GNUNET_SCHEDULER_add_now(&gather_stats_and_exit, + (void *)__LINE__); + GNUNET_free(ch_w); } @@ -696,41 +695,41 @@ disconnect_handler (void *cls, * @param cls Closure (unused). */ static void -start_test (void *cls) +start_test(void *cls) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (data, - GNUNET_MESSAGE_TYPE_DUMMY, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(data, + GNUNET_MESSAGE_TYPE_DUMMY, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end() }; struct CadetTestChannelWrapper *ch; enum GNUNET_CADET_ChannelOption flags; test_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "In start_test\n"); - start_time = GNUNET_TIME_absolute_get (); - ch = GNUNET_new (struct CadetTestChannelWrapper); - outgoing_ch = GNUNET_CADET_channel_create (h1, - ch, - p_id[1], - &port, - flags, - NULL, - &disconnect_handler, - handlers); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "In start_test\n"); + start_time = GNUNET_TIME_absolute_get(); + ch = GNUNET_new(struct CadetTestChannelWrapper); + outgoing_ch = GNUNET_CADET_channel_create(h1, + ch, + p_id[1], + &port, + flags, + NULL, + &disconnect_handler, + handlers); ch->ch = outgoing_ch; - GNUNET_assert (NULL == disconnect_task); + GNUNET_assert(NULL == disconnect_task); disconnect_task - = GNUNET_SCHEDULER_add_delayed (short_time, - &gather_stats_and_exit, - (void *) __LINE__); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending data initializer on channel %p...\n", - outgoing_ch); - send_test_message (outgoing_ch); + = GNUNET_SCHEDULER_add_delayed(short_time, + &gather_stats_and_exit, + (void *)__LINE__); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending data initializer on channel %p...\n", + outgoing_ch); + send_test_message(outgoing_ch); } @@ -744,36 +743,36 @@ start_test (void *cls) * NULL if the operation is successfull */ static void -pi_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - const struct GNUNET_TESTBED_PeerInformation *pinfo, - const char *emsg) +pi_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + const struct GNUNET_TESTBED_PeerInformation *pinfo, + const char *emsg) { - long i = (long) cls; - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "ID callback for %ld\n", - i); - if ( (NULL == pinfo) || - (NULL != emsg) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "pi_cb: %s\n", - emsg); - abort_test (__LINE__); - return; - } + long i = (long)cls; + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "ID callback for %ld\n", + i); + if ((NULL == pinfo) || + (NULL != emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "pi_cb: %s\n", + emsg); + abort_test(__LINE__); + return; + } p_id[i] = pinfo->result.id; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "id: %s\n", - GNUNET_i2s (p_id[i])); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "id: %s\n", + GNUNET_i2s(p_id[i])); p_ids++; if (p_ids < 2) return; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got all IDs, starting test\n"); - test_task = GNUNET_SCHEDULER_add_now (&start_test, - NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got all IDs, starting test\n"); + test_task = GNUNET_SCHEDULER_add_now(&start_test, + NULL); } @@ -787,33 +786,33 @@ pi_cb (void *cls, * @param cadets Handle to each of the CADETs of the peers. */ static void -tmain (void *cls, - struct GNUNET_CADET_TEST_Context *ctx, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - struct GNUNET_CADET_Handle **cadets) +tmain(void *cls, + struct GNUNET_CADET_TEST_Context *ctx, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + struct GNUNET_CADET_Handle **cadets) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "test main\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "test main\n"); test_ctx = ctx; peers_running = num_peers; - GNUNET_assert (peers_running == peers_requested); + GNUNET_assert(peers_running == peers_requested); testbed_peers = peers; h1 = cadets[0]; h2 = cadets[num_peers - 1]; - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); p_ids = 0; - t_op[0] = GNUNET_TESTBED_peer_get_information (peers[0], - GNUNET_TESTBED_PIT_IDENTITY, - &pi_cb, - (void *) 0L); - t_op[1] = GNUNET_TESTBED_peer_get_information (peers[num_peers - 1], - GNUNET_TESTBED_PIT_IDENTITY, - &pi_cb, - (void *) 1L); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "requested peer ids\n"); + t_op[0] = GNUNET_TESTBED_peer_get_information(peers[0], + GNUNET_TESTBED_PIT_IDENTITY, + &pi_cb, + (void *)0L); + t_op[1] = GNUNET_TESTBED_peer_get_information(peers[num_peers - 1], + GNUNET_TESTBED_PIT_IDENTITY, + &pi_cb, + (void *)1L); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "requested peer ids\n"); } @@ -821,67 +820,67 @@ tmain (void *cls, * Main: start test */ int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { static const struct GNUNET_HashCode *ports[2]; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (data, - GNUNET_MESSAGE_TYPE_DUMMY, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(data, + GNUNET_MESSAGE_TYPE_DUMMY, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end() }; const char *config_file = "test_cadet.conf"; char port_id[] = "test port"; struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_option_relative_time ('t', - "time", - "short_time", - gettext_noop ("set short timeout"), - &short_time), - GNUNET_GETOPT_option_uint ('m', - "messages", - "NUM_MESSAGES", - gettext_noop ("set number of messages to send"), - &total_packets), - GNUNET_GETOPT_option_uint ('p', - "peers", - "NUM_PEERS", - gettext_noop ("number of peers to launch"), - &peers_requested), + GNUNET_GETOPT_option_relative_time('t', + "time", + "short_time", + gettext_noop("set short timeout"), + &short_time), + GNUNET_GETOPT_option_uint('m', + "messages", + "NUM_MESSAGES", + gettext_noop("set number of messages to send"), + &total_packets), + GNUNET_GETOPT_option_uint('p', + "peers", + "NUM_PEERS", + gettext_noop("number of peers to launch"), + &peers_requested), GNUNET_GETOPT_OPTION_END }; - GNUNET_log_setup ("test-cadet-flow", - "DEBUG", - NULL); + GNUNET_log_setup("test-cadet-flow", + "DEBUG", + NULL); total_packets = TOTAL_PACKETS; short_time = SHORT_TIME; - if (-1 == GNUNET_GETOPT_run (argv[0], - options, - argc, - argv)) - { - fprintf (stderr, - "test failed: problem with CLI parameters\n"); - return 1; - } - GNUNET_CRYPTO_hash (port_id, - sizeof (port_id), - &port); + if (-1 == GNUNET_GETOPT_run(argv[0], + options, + argc, + argv)) + { + fprintf(stderr, + "test failed: problem with CLI parameters\n"); + return 1; + } + GNUNET_CRYPTO_hash(port_id, + sizeof(port_id), + &port); ports[0] = &port; ports[1] = NULL; - GNUNET_CADET_TEST_ruN ("test_cadet_flow", - config_file, - peers_requested, - &tmain, - NULL, /* tmain cls */ - &connect_handler, - NULL, - &disconnect_handler, - handlers, - ports); + GNUNET_CADET_TEST_ruN("test_cadet_flow", + config_file, + peers_requested, + &tmain, + NULL, /* tmain cls */ + &connect_handler, + NULL, + &disconnect_handler, + handlers, + ports); return 0; } diff --git a/src/cadet/test_cadet_local_mq.c b/src/cadet/test_cadet_local_mq.c index b2fed5bd6..7ae0a90c4 100644 --- a/src/cadet/test_cadet_local_mq.c +++ b/src/cadet/test_cadet_local_mq.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file cadet/test_cadet_local_mq.c @@ -36,8 +36,7 @@ /** * Test message structure. */ -struct GNUNET_CADET_TestMsg -{ +struct GNUNET_CADET_TestMsg { /** * Type: #TEST_MESSAGE_TYPE * @@ -74,46 +73,46 @@ static struct GNUNET_SCHEDULER_Task *connect_task; * @param cls Closue (unused). */ static void -do_connect (void *cls); +do_connect(void *cls); /** * Shutdown nicely */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "shutdown\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "shutdown\n"); if (NULL != abort_task) - { - GNUNET_SCHEDULER_cancel (abort_task); - abort_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(abort_task); + abort_task = NULL; + } if (NULL != ch) - { - GNUNET_CADET_channel_destroy (ch); - ch = NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Disconnect client 1\n"); + { + GNUNET_CADET_channel_destroy(ch); + ch = NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Disconnect client 1\n"); if (NULL != cadet_peer_1) - { - GNUNET_CADET_disconnect (cadet_peer_1); - cadet_peer_1 = NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Disconnect client 2\n"); + { + GNUNET_CADET_disconnect(cadet_peer_1); + cadet_peer_1 = NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Disconnect client 2\n"); if (NULL != cadet_peer_2) - { - GNUNET_CADET_disconnect (cadet_peer_2); - cadet_peer_2 = NULL; - } + { + GNUNET_CADET_disconnect(cadet_peer_2); + cadet_peer_2 = NULL; + } if (NULL != connect_task) - { - GNUNET_SCHEDULER_cancel (connect_task); - connect_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(connect_task); + connect_task = NULL; + } } @@ -121,14 +120,14 @@ do_shutdown (void *cls) * Something went wrong and timed out. Kill everything and set error flag */ static void -do_abort (void *cls) +do_abort(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "ABORT from line %ld\n", - (long) cls); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "ABORT from line %ld\n", + (long)cls); result = GNUNET_SYSERR; abort_task = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } /** @@ -144,14 +143,14 @@ do_abort (void *cls) * received on the @a channel. */ static void * -connected (void *cls, - struct GNUNET_CADET_Channel *channel, - const struct GNUNET_PeerIdentity *source) +connected(void *cls, + struct GNUNET_CADET_Channel *channel, + const struct GNUNET_PeerIdentity *source) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "connected %s, cls: %p\n", - GNUNET_i2s(source), - cls); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "connected %s, cls: %p\n", + GNUNET_i2s(source), + cls); return channel; } @@ -167,12 +166,12 @@ connected (void *cls, * @param channel Connection to the other end (henceforth invalid). */ static void -disconnected (void *cls, - const struct GNUNET_CADET_Channel *channel) +disconnected(void *cls, + const struct GNUNET_CADET_Channel *channel) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "disconnected channel %p, cls: %p\n", - channel, cls); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "disconnected channel %p, cls: %p\n", + channel, cls); if (channel == ch) ch = NULL; } @@ -185,19 +184,19 @@ disconnected (void *cls, * @param msg A message with the details of the new incoming channel */ static void -handle_data_received (void *cls, - const struct GNUNET_CADET_TestMsg *msg) +handle_data_received(void *cls, + const struct GNUNET_CADET_TestMsg *msg) { uint64_t payload; - payload = GNUNET_ntohll (msg->payload); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Data callback payload %llu with cls: %p! Shutting down.\n", - (unsigned long long) payload, - cls); - GNUNET_assert (42 == payload); + payload = GNUNET_ntohll(msg->payload); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Data callback payload %llu with cls: %p! Shutting down.\n", + (unsigned long long)payload, + cls); + GNUNET_assert(42 == payload); got_data = GNUNET_YES; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -207,10 +206,10 @@ handle_data_received (void *cls, * @param cls Closure (unused). */ static void -message_sent (void *cls) +message_sent(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "message sent\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "message sent\n"); } @@ -220,7 +219,7 @@ message_sent (void *cls) * @param cls Closure (unused). */ static void -do_connect (void *cls) +do_connect(void *cls) { struct GNUNET_PeerIdentity id; struct GNUNET_MQ_Handle *mq; @@ -228,32 +227,32 @@ do_connect (void *cls) struct GNUNET_CADET_TestMsg *msg; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (data_received, - TEST_MESSAGE_TYPE, - struct GNUNET_CADET_TestMsg, - cadet_peer_1), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(data_received, + TEST_MESSAGE_TYPE, + struct GNUNET_CADET_TestMsg, + cadet_peer_1), + GNUNET_MQ_handler_end() }; connect_task = NULL; - GNUNET_TESTING_peer_get_identity (me, &id); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "creating channel\n"); - ch = GNUNET_CADET_channel_create (cadet_peer_1, /* cadet handle */ - NULL, /* channel cls */ - &id, /* destination */ - GC_u2h (TEST_MESSAGE_TYPE), /* port */ - NULL, /* window change */ - &disconnected, /* disconnect handler */ - handlers /* traffic handlers */ + GNUNET_TESTING_peer_get_identity(me, &id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "creating channel\n"); + ch = GNUNET_CADET_channel_create(cadet_peer_1, /* cadet handle */ + NULL, /* channel cls */ + &id, /* destination */ + GC_u2h(TEST_MESSAGE_TYPE), /* port */ + NULL, /* window change */ + &disconnected, /* disconnect handler */ + handlers /* traffic handlers */ ); - env = GNUNET_MQ_msg (msg, TEST_MESSAGE_TYPE); - msg->payload = GNUNET_htonll (42); - mq = GNUNET_CADET_get_mq (ch); - GNUNET_MQ_notify_sent (env, &message_sent, NULL); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "sending message\n"); - GNUNET_MQ_send (mq, env); + env = GNUNET_MQ_msg(msg, TEST_MESSAGE_TYPE); + msg->payload = GNUNET_htonll(42); + mq = GNUNET_CADET_get_mq(ch); + GNUNET_MQ_notify_sent(env, &message_sent, NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "sending message\n"); + GNUNET_MQ_send(mq, env); } @@ -265,53 +264,53 @@ do_connect (void *cls) * @param peer Testing peer handle. */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (data_received, - TEST_MESSAGE_TYPE, - struct GNUNET_CADET_TestMsg, - cadet_peer_2), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(data_received, + TEST_MESSAGE_TYPE, + struct GNUNET_CADET_TestMsg, + cadet_peer_2), + GNUNET_MQ_handler_end() }; struct GNUNET_TIME_Relative delay; me = peer; - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15); - abort_task = GNUNET_SCHEDULER_add_delayed (delay, - &do_abort, - (void *) (long) __LINE__); - cadet_peer_1 = GNUNET_CADET_connect (cfg); - cadet_peer_2 = GNUNET_CADET_connect (cfg); - - if ( (NULL == cadet_peer_1) || - (NULL == cadet_peer_2) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Couldn't connect to cadet\n"); - result = GNUNET_SYSERR; - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CADET 1: %p\n", cadet_peer_1); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CADET 2: %p\n", cadet_peer_2); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "handlers 2: %p\n", handlers); - GNUNET_CADET_open_port (cadet_peer_2, /* cadet handle */ - GC_u2h (TEST_PORT_ID), /* port id */ - &connected, /* connect handler */ - (void *) 2L, /* handle for #connected */ - NULL, /* window size handler */ - &disconnected, /* disconnect handler */ - handlers); /* traffic handlers */ - delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); + delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15); + abort_task = GNUNET_SCHEDULER_add_delayed(delay, + &do_abort, + (void *)(long)__LINE__); + cadet_peer_1 = GNUNET_CADET_connect(cfg); + cadet_peer_2 = GNUNET_CADET_connect(cfg); + + if ((NULL == cadet_peer_1) || + (NULL == cadet_peer_2)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Couldn't connect to cadet\n"); + result = GNUNET_SYSERR; + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "CADET 1: %p\n", cadet_peer_1); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "CADET 2: %p\n", cadet_peer_2); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "handlers 2: %p\n", handlers); + GNUNET_CADET_open_port(cadet_peer_2, /* cadet handle */ + GC_u2h(TEST_PORT_ID), /* port id */ + &connected, /* connect handler */ + (void *)2L, /* handle for #connected */ + NULL, /* window size handler */ + &disconnected, /* disconnect handler */ + handlers); /* traffic handlers */ + delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 2); if (NULL == connect_task) - connect_task = GNUNET_SCHEDULER_add_delayed (delay, - &do_connect, - NULL); + connect_task = GNUNET_SCHEDULER_add_delayed(delay, + &do_connect, + NULL); } @@ -319,16 +318,16 @@ run (void *cls, * Main */ int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-cadet-local", - "test_cadet.conf", - &run, NULL)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "run failed\n"); - return 2; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Final result: %d\n", result); + if (0 != GNUNET_TESTING_peer_run("test-cadet-local", + "test_cadet.conf", + &run, NULL)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "run failed\n"); + return 2; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Final result: %d\n", result); return (result == GNUNET_OK) ? 0 : 1; } diff --git a/src/consensus/consensus.h b/src/consensus/consensus.h index 683e16104..f110b23b2 100644 --- a/src/consensus/consensus.h +++ b/src/consensus/consensus.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Florian Dold @@ -34,8 +34,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * Sent by the client to the service, * when the client wants the service to join a consensus session. */ -struct GNUNET_CONSENSUS_JoinMessage -{ +struct GNUNET_CONSENSUS_JoinMessage { /** * Type: GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_JOIN */ @@ -69,9 +68,7 @@ struct GNUNET_CONSENSUS_JoinMessage /** * Message with an element */ -struct GNUNET_CONSENSUS_ElementMessage -{ - +struct GNUNET_CONSENSUS_ElementMessage { /** * Type: * Either GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_RECEIVED_ELEMENT diff --git a/src/consensus/consensus_api.c b/src/consensus/consensus_api.c index 4a584a410..2da145932 100644 --- a/src/consensus/consensus_api.c +++ b/src/consensus/consensus_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file consensus/consensus_api.c @@ -31,14 +31,13 @@ #include "consensus.h" -#define LOG(kind,...) GNUNET_log_from (kind, "consensus-api",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "consensus-api", __VA_ARGS__) /** * Handle for the service. */ -struct GNUNET_CONSENSUS_Handle -{ +struct GNUNET_CONSENSUS_Handle { /** * Configuration to use. */ @@ -90,8 +89,7 @@ struct GNUNET_CONSENSUS_Handle * FIXME: this should not bee necessary when the API * issue has been fixed */ -struct InsertDoneInfo -{ +struct InsertDoneInfo { GNUNET_CONSENSUS_InsertDoneCallback idc; void *cls; }; @@ -104,8 +102,8 @@ struct InsertDoneInfo * @param msg element message */ static int -check_new_element (void *cls, - const struct GNUNET_CONSENSUS_ElementMessage *msg) +check_new_element(void *cls, + const struct GNUNET_CONSENSUS_ElementMessage *msg) { /* any size is fine, elements are variable-size */ return GNUNET_OK; @@ -119,19 +117,19 @@ check_new_element (void *cls, * @param msg element message */ static void -handle_new_element (void *cls, - const struct GNUNET_CONSENSUS_ElementMessage *msg) +handle_new_element(void *cls, + const struct GNUNET_CONSENSUS_ElementMessage *msg) { struct GNUNET_CONSENSUS_Handle *consensus = cls; struct GNUNET_SET_Element element; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "received new element\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "received new element\n"); element.element_type = msg->element_type; - element.size = ntohs (msg->header.size) - sizeof (struct GNUNET_CONSENSUS_ElementMessage); + element.size = ntohs(msg->header.size) - sizeof(struct GNUNET_CONSENSUS_ElementMessage); element.data = &msg[1]; - consensus->new_element_cb (consensus->new_element_cls, - &element); + consensus->new_element_cb(consensus->new_element_cls, + &element); } @@ -143,17 +141,17 @@ handle_new_element (void *cls, * @param msg conclude done message */ static void -handle_conclude_done (void *cls, - const struct GNUNET_MessageHeader *msg) +handle_conclude_done(void *cls, + const struct GNUNET_MessageHeader *msg) { struct GNUNET_CONSENSUS_Handle *consensus = cls; GNUNET_CONSENSUS_ConcludeCallback cc; - GNUNET_MQ_destroy (consensus->mq); + GNUNET_MQ_destroy(consensus->mq); consensus->mq = NULL; - GNUNET_assert (NULL != (cc = consensus->conclude_cb)); + GNUNET_assert(NULL != (cc = consensus->conclude_cb)); consensus->conclude_cb = NULL; - cc (consensus->conclude_cls); + cc(consensus->conclude_cls); } @@ -167,11 +165,11 @@ handle_conclude_done (void *cls, * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { - LOG (GNUNET_ERROR_TYPE_WARNING, - "consensus service disconnected us\n"); + LOG(GNUNET_ERROR_TYPE_WARNING, + "consensus service disconnected us\n"); } @@ -193,27 +191,27 @@ mq_error_handler (void *cls, * @return handle to use, NULL on error */ struct GNUNET_CONSENSUS_Handle * -GNUNET_CONSENSUS_create (const struct GNUNET_CONFIGURATION_Handle *cfg, - unsigned int num_peers, - const struct GNUNET_PeerIdentity *peers, - const struct GNUNET_HashCode *session_id, - struct GNUNET_TIME_Absolute start, - struct GNUNET_TIME_Absolute deadline, - GNUNET_CONSENSUS_ElementCallback new_element_cb, - void *new_element_cls) +GNUNET_CONSENSUS_create(const struct GNUNET_CONFIGURATION_Handle *cfg, + unsigned int num_peers, + const struct GNUNET_PeerIdentity *peers, + const struct GNUNET_HashCode *session_id, + struct GNUNET_TIME_Absolute start, + struct GNUNET_TIME_Absolute deadline, + GNUNET_CONSENSUS_ElementCallback new_element_cb, + void *new_element_cls) { struct GNUNET_CONSENSUS_Handle *consensus - = GNUNET_new (struct GNUNET_CONSENSUS_Handle); + = GNUNET_new(struct GNUNET_CONSENSUS_Handle); struct GNUNET_MQ_MessageHandler mq_handlers[] = { - GNUNET_MQ_hd_var_size (new_element, - GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_RECEIVED_ELEMENT, - struct GNUNET_CONSENSUS_ElementMessage, - consensus), - GNUNET_MQ_hd_fixed_size (conclude_done, - GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_CONCLUDE_DONE, - struct GNUNET_MessageHeader, - consensus), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(new_element, + GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_RECEIVED_ELEMENT, + struct GNUNET_CONSENSUS_ElementMessage, + consensus), + GNUNET_MQ_hd_fixed_size(conclude_done, + GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_CONCLUDE_DONE, + struct GNUNET_MessageHeader, + consensus), + GNUNET_MQ_handler_end() }; struct GNUNET_CONSENSUS_JoinMessage *join_msg; struct GNUNET_MQ_Envelope *ev; @@ -222,39 +220,40 @@ GNUNET_CONSENSUS_create (const struct GNUNET_CONFIGURATION_Handle *cfg, consensus->new_element_cb = new_element_cb; consensus->new_element_cls = new_element_cls; consensus->session_id = *session_id; - consensus->mq = GNUNET_CLIENT_connect (cfg, - "consensus", - mq_handlers, - &mq_error_handler, - consensus); + consensus->mq = GNUNET_CLIENT_connect(cfg, + "consensus", + mq_handlers, + &mq_error_handler, + consensus); if (NULL == consensus->mq) - { - GNUNET_free (consensus); - return NULL; - } - ev = GNUNET_MQ_msg_extra (join_msg, - (num_peers * sizeof (struct GNUNET_PeerIdentity)), - GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_JOIN); + { + GNUNET_free(consensus); + return NULL; + } + ev = GNUNET_MQ_msg_extra(join_msg, + (num_peers * sizeof(struct GNUNET_PeerIdentity)), + GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_JOIN); join_msg->session_id = consensus->session_id; - join_msg->start = GNUNET_TIME_absolute_hton (start); - join_msg->deadline = GNUNET_TIME_absolute_hton (deadline); - join_msg->num_peers = htonl (num_peers); + join_msg->start = GNUNET_TIME_absolute_hton(start); + join_msg->deadline = GNUNET_TIME_absolute_hton(deadline); + join_msg->num_peers = htonl(num_peers); GNUNET_memcpy(&join_msg[1], - peers, - num_peers * sizeof (struct GNUNET_PeerIdentity)); + peers, + num_peers * sizeof(struct GNUNET_PeerIdentity)); - GNUNET_MQ_send (consensus->mq, ev); + GNUNET_MQ_send(consensus->mq, ev); return consensus; } static void -idc_adapter (void *cls) +idc_adapter(void *cls) { struct InsertDoneInfo *i = cls; - i->idc (i->cls, GNUNET_OK); - GNUNET_free (i); + + i->idc(i->cls, GNUNET_OK); + GNUNET_free(i); } /** @@ -268,30 +267,30 @@ idc_adapter (void *cls) * @param idc_cls closure for 'idc' */ void -GNUNET_CONSENSUS_insert (struct GNUNET_CONSENSUS_Handle *consensus, - const struct GNUNET_SET_Element *element, - GNUNET_CONSENSUS_InsertDoneCallback idc, - void *idc_cls) +GNUNET_CONSENSUS_insert(struct GNUNET_CONSENSUS_Handle *consensus, + const struct GNUNET_SET_Element *element, + GNUNET_CONSENSUS_InsertDoneCallback idc, + void *idc_cls) { struct GNUNET_CONSENSUS_ElementMessage *element_msg; struct GNUNET_MQ_Envelope *ev; struct InsertDoneInfo *i; - LOG (GNUNET_ERROR_TYPE_DEBUG, "inserting, size=%llu\n", element->size); + LOG(GNUNET_ERROR_TYPE_DEBUG, "inserting, size=%llu\n", element->size); - ev = GNUNET_MQ_msg_extra (element_msg, element->size, - GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_INSERT); + ev = GNUNET_MQ_msg_extra(element_msg, element->size, + GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_INSERT); - GNUNET_memcpy (&element_msg[1], element->data, element->size); + GNUNET_memcpy(&element_msg[1], element->data, element->size); if (NULL != idc) - { - i = GNUNET_new (struct InsertDoneInfo); - i->idc = idc; - i->cls = idc_cls; - GNUNET_MQ_notify_sent (ev, idc_adapter, i); - } - GNUNET_MQ_send (consensus->mq, ev); + { + i = GNUNET_new(struct InsertDoneInfo); + i->idc = idc; + i->cls = idc_cls; + GNUNET_MQ_notify_sent(ev, idc_adapter, i); + } + GNUNET_MQ_send(consensus->mq, ev); } @@ -308,20 +307,20 @@ GNUNET_CONSENSUS_insert (struct GNUNET_CONSENSUS_Handle *consensus, * @param conclude_cls closure for the conclude callback */ void -GNUNET_CONSENSUS_conclude (struct GNUNET_CONSENSUS_Handle *consensus, - GNUNET_CONSENSUS_ConcludeCallback conclude, - void *conclude_cls) +GNUNET_CONSENSUS_conclude(struct GNUNET_CONSENSUS_Handle *consensus, + GNUNET_CONSENSUS_ConcludeCallback conclude, + void *conclude_cls) { struct GNUNET_MQ_Envelope *ev; - GNUNET_assert (NULL != conclude); - GNUNET_assert (NULL == consensus->conclude_cb); + GNUNET_assert(NULL != conclude); + GNUNET_assert(NULL == consensus->conclude_cb); consensus->conclude_cls = conclude_cls; consensus->conclude_cb = conclude; - ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_CONCLUDE); - GNUNET_MQ_send (consensus->mq, ev); + ev = GNUNET_MQ_msg_header(GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_CONCLUDE); + GNUNET_MQ_send(consensus->mq, ev); } @@ -332,14 +331,14 @@ GNUNET_CONSENSUS_conclude (struct GNUNET_CONSENSUS_Handle *consensus, * @param consensus handle to destroy */ void -GNUNET_CONSENSUS_destroy (struct GNUNET_CONSENSUS_Handle *consensus) +GNUNET_CONSENSUS_destroy(struct GNUNET_CONSENSUS_Handle *consensus) { if (NULL != consensus->mq) - { - GNUNET_MQ_destroy (consensus->mq); - consensus->mq = NULL; - } - GNUNET_free (consensus); + { + GNUNET_MQ_destroy(consensus->mq); + consensus->mq = NULL; + } + GNUNET_free(consensus); } /* end of consensus_api.c */ diff --git a/src/consensus/consensus_protocol.h b/src/consensus/consensus_protocol.h index 77641e2b4..fc8ae7533 100644 --- a/src/consensus/consensus_protocol.h +++ b/src/consensus/consensus_protocol.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** @@ -42,8 +42,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * Essentially contains all the fields * from 'struct TaskKey', but in NBO. */ -struct GNUNET_CONSENSUS_RoundContextMessage -{ +struct GNUNET_CONSENSUS_RoundContextMessage { /** * Type: #GNUNET_MESSAGE_TYPE_CONSENSUS_P2P_ROUND_CONTEXT */ @@ -98,8 +97,7 @@ enum { /** * Consensus element, either marker or payload. */ -struct ConsensusElement -{ +struct ConsensusElement { /** * Payload element_type, only valid * if this is not a marker element. @@ -115,16 +113,14 @@ struct ConsensusElement }; -struct ConsensusSizeElement -{ +struct ConsensusSizeElement { struct ConsensusElement ce; uint64_t size GNUNET_PACKED; uint8_t sender_index; }; -struct ConsensusStuffedElement -{ +struct ConsensusStuffedElement { struct ConsensusElement ce; struct GNUNET_HashCode rand GNUNET_PACKED; }; diff --git a/src/consensus/gnunet-consensus-profiler.c b/src/consensus/gnunet-consensus-profiler.c index e088904aa..9feee87cd 100644 --- a/src/consensus/gnunet-consensus-profiler.c +++ b/src/consensus/gnunet-consensus-profiler.c @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -92,26 +92,26 @@ static struct GNUNET_TIME_Absolute deadline; * @param event information about the event */ static void -controller_cb (void *cls, - const struct GNUNET_TESTBED_EventInformation *event) +controller_cb(void *cls, + const struct GNUNET_TESTBED_EventInformation *event) { - GNUNET_assert (0); + GNUNET_assert(0); } static void -statistics_done_cb (void *cls, - struct - GNUNET_TESTBED_Operation - *op, - const char *emsg) +statistics_done_cb(void *cls, + struct + GNUNET_TESTBED_Operation + *op, + const char *emsg) { - GNUNET_assert (NULL == emsg); - GNUNET_TESTBED_operation_done (op); + GNUNET_assert(NULL == emsg); + GNUNET_TESTBED_operation_done(op); if (NULL != statistics_file) - fclose (statistics_file); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "got statistics, shutting down\n"); - GNUNET_SCHEDULER_shutdown (); + fclose(statistics_file); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "got statistics, shutting down\n"); + GNUNET_SCHEDULER_shutdown(); } @@ -127,47 +127,47 @@ statistics_done_cb (void *cls, * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration */ static int -statistics_cb (void *cls, - const struct GNUNET_TESTBED_Peer *peer, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +statistics_cb(void *cls, + const struct GNUNET_TESTBED_Peer *peer, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { if (NULL != statistics_file) - { - fprintf (statistics_file, "P%u\t%s\t%s\t%lu\n", GNUNET_TESTBED_get_index (peer), subsystem, name, (unsigned long) value); - } + { + fprintf(statistics_file, "P%u\t%s\t%s\t%lu\n", GNUNET_TESTBED_get_index(peer), subsystem, name, (unsigned long)value); + } return GNUNET_OK; } static void -destroy (void *cls) +destroy(void *cls) { struct GNUNET_CONSENSUS_Handle *consensus = cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "destroying consensus\n"); - GNUNET_CONSENSUS_destroy (consensus); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "destroying consensus\n"); + GNUNET_CONSENSUS_destroy(consensus); peers_done++; if (peers_done == num_peers) - { - unsigned int i; - for (i = 0; i < num_peers; i++) - GNUNET_TESTBED_operation_done (testbed_operations[i]); - for (i = 0; i < num_peers; i++) - printf ("P%u got %u of %u elements\n", - i, - results_for_peer[i], - num_values); - if (NULL != statistics_filename) - statistics_file = fopen (statistics_filename, "w"); - GNUNET_TESTBED_get_statistics (num_peers, peers, NULL, NULL, - statistics_cb, - statistics_done_cb, - NULL); - } + { + unsigned int i; + for (i = 0; i < num_peers; i++) + GNUNET_TESTBED_operation_done(testbed_operations[i]); + for (i = 0; i < num_peers; i++) + printf("P%u got %u of %u elements\n", + i, + results_for_peer[i], + num_values); + if (NULL != statistics_filename) + statistics_file = fopen(statistics_filename, "w"); + GNUNET_TESTBED_get_statistics(num_peers, peers, NULL, NULL, + statistics_cb, + statistics_done_cb, + NULL); + } } @@ -179,43 +179,44 @@ destroy (void *cls) * #GNUNET_NO if not */ static void -conclude_cb (void *cls) +conclude_cb(void *cls) { struct GNUNET_CONSENSUS_Handle **chp = cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "consensus %d done\n", - (int) (chp - consensus_handles)); - GNUNET_SCHEDULER_add_now (destroy, *chp); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "consensus %d done\n", + (int)(chp - consensus_handles)); + GNUNET_SCHEDULER_add_now(destroy, *chp); } static void -generate_indices (int *indices) +generate_indices(int *indices) { int j; + j = 0; while (j < replication) - { - int n; - int k; - int repeat; - n = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, num_peers); - repeat = GNUNET_NO; - for (k = 0; k < j; k++) - if (indices[k] == n) - { - repeat = GNUNET_YES; - break; - } - if (GNUNET_NO == repeat) - indices[j++] = n; - } + { + int n; + int k; + int repeat; + n = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, num_peers); + repeat = GNUNET_NO; + for (k = 0; k < j; k++) + if (indices[k] == n) + { + repeat = GNUNET_YES; + break; + } + if (GNUNET_NO == repeat) + indices[j++] = n; + } } static void -do_consensus () +do_consensus() { int unique_indices[replication]; unsigned int i; @@ -224,49 +225,48 @@ do_consensus () struct GNUNET_SET_Element element; if (dist_static) - { - for (i = 0; i < num_values; i++) { - - GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_WEAK, &val); - - element.data = &val; - element.size = sizeof (val); - for (j = 0; j < replication; j++) - { - GNUNET_CONSENSUS_insert (consensus_handles[j], - &element, - NULL, NULL); - } + for (i = 0; i < num_values; i++) + { + GNUNET_CRYPTO_hash_create_random(GNUNET_CRYPTO_QUALITY_WEAK, &val); + + element.data = &val; + element.size = sizeof(val); + for (j = 0; j < replication; j++) + { + GNUNET_CONSENSUS_insert(consensus_handles[j], + &element, + NULL, NULL); + } + } } - } else - { - for (i = 0; i < num_values; i++) { - generate_indices (unique_indices); - GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_WEAK, &val); - - element.data = &val; - element.size = sizeof (val); - for (j = 0; j < replication; j++) - { - int cid; - - cid = unique_indices[j]; - GNUNET_CONSENSUS_insert (consensus_handles[cid], - &element, - NULL, NULL); - } + for (i = 0; i < num_values; i++) + { + generate_indices(unique_indices); + GNUNET_CRYPTO_hash_create_random(GNUNET_CRYPTO_QUALITY_WEAK, &val); + + element.data = &val; + element.size = sizeof(val); + for (j = 0; j < replication; j++) + { + int cid; + + cid = unique_indices[j]; + GNUNET_CONSENSUS_insert(consensus_handles[cid], + &element, + NULL, NULL); + } + } } - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "all elements inserted, calling conclude\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "all elements inserted, calling conclude\n"); for (i = 0; i < num_peers; i++) - GNUNET_CONSENSUS_conclude (consensus_handles[i], - conclude_cb, &consensus_handles[i]); + GNUNET_CONSENSUS_conclude(consensus_handles[i], + conclude_cb, &consensus_handles[i]); } @@ -280,51 +280,50 @@ do_consensus () * operation has executed successfully. */ static void -connect_complete (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg) +connect_complete(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg) { - if (NULL != emsg) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "testbed connect emsg: %s\n", - emsg); - GNUNET_assert (0); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "testbed connect emsg: %s\n", + emsg); + GNUNET_assert(0); + } num_connected_handles++; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "connect complete\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "connect complete\n"); if (num_connected_handles == num_peers) - { - do_consensus (); - } + { + do_consensus(); + } } static void -new_element_cb (void *cls, - const struct GNUNET_SET_Element *element) +new_element_cb(void *cls, + const struct GNUNET_SET_Element *element) { struct GNUNET_CONSENSUS_Handle **chp = cls; int idx = chp - consensus_handles; - GNUNET_assert (NULL != cls); + GNUNET_assert(NULL != cls); results_for_peer[idx]++; - GNUNET_assert (sizeof (struct GNUNET_HashCode) == element->size); + GNUNET_assert(sizeof(struct GNUNET_HashCode) == element->size); if (GNUNET_YES == verbose) - { - printf ("P%d received %s\n", - idx, - GNUNET_h2s ((struct GNUNET_HashCode *) element->data)); - } + { + printf("P%d received %s\n", + idx, + GNUNET_h2s((struct GNUNET_HashCode *)element->data)); + } } @@ -339,23 +338,24 @@ new_element_cb (void *cls, * @return service handle to return in 'op_result', NULL on error */ static void * -connect_adapter (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +connect_adapter(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_CONSENSUS_Handle **chp = cls; struct GNUNET_CONSENSUS_Handle *consensus; - chp = (struct GNUNET_CONSENSUS_Handle **) cls; - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "connect adapter, %d peers\n", - num_peers); - consensus = GNUNET_CONSENSUS_create (cfg, - num_peers, peer_ids, - &session_id, - start, - deadline, - &new_element_cb, chp); - *chp = (struct GNUNET_CONSENSUS_Handle *) consensus; + + chp = (struct GNUNET_CONSENSUS_Handle **)cls; + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "connect adapter, %d peers\n", + num_peers); + consensus = GNUNET_CONSENSUS_create(cfg, + num_peers, peer_ids, + &session_id, + start, + deadline, + &new_element_cb, chp); + *chp = (struct GNUNET_CONSENSUS_Handle *)consensus; return consensus; } @@ -371,8 +371,8 @@ static void disconnect_adapter(void *cls, void *op_result) { /* FIXME: what to do here? */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "disconnect adapter called\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "disconnect adapter called\n"); } @@ -386,34 +386,34 @@ disconnect_adapter(void *cls, void *op_result) * operation is successfull */ static void -peer_info_cb (void *cb_cls, - struct GNUNET_TESTBED_Operation *op, - const struct GNUNET_TESTBED_PeerInformation *pinfo, - const char *emsg) +peer_info_cb(void *cb_cls, + struct GNUNET_TESTBED_Operation *op, + const struct GNUNET_TESTBED_PeerInformation *pinfo, + const char *emsg) { struct GNUNET_PeerIdentity *p; int i; - GNUNET_assert (NULL == emsg); + GNUNET_assert(NULL == emsg); - p = (struct GNUNET_PeerIdentity *) cb_cls; + p = (struct GNUNET_PeerIdentity *)cb_cls; if (pinfo->pit == GNUNET_TESTBED_PIT_IDENTITY) - { - *p = *pinfo->result.id; - num_retrieved_peer_ids++; - if (num_retrieved_peer_ids == num_peers) - for (i = 0; i < num_peers; i++) - testbed_operations[i] = - GNUNET_TESTBED_service_connect (NULL, peers[i], "consensus", connect_complete, NULL, - connect_adapter, disconnect_adapter, &consensus_handles[i]); - } + { + *p = *pinfo->result.id; + num_retrieved_peer_ids++; + if (num_retrieved_peer_ids == num_peers) + for (i = 0; i < num_peers; i++) + testbed_operations[i] = + GNUNET_TESTBED_service_connect(NULL, peers[i], "consensus", connect_complete, NULL, + connect_adapter, disconnect_adapter, &consensus_handles[i]); + } else - { - GNUNET_assert (0); - } + { + GNUNET_assert(0); + } - GNUNET_TESTBED_operation_done (op); + GNUNET_TESTBED_operation_done(op); } @@ -431,144 +431,144 @@ peer_info_cb (void *cb_cls, * failed */ static void -test_master (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **started_peers, - unsigned int links_succeeded, - unsigned int links_failed) +test_master(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **started_peers, + unsigned int links_succeeded, + unsigned int links_failed) { int i; - GNUNET_log_setup ("gnunet-consensus", "INFO", NULL); + GNUNET_log_setup("gnunet-consensus", "INFO", NULL); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "test master\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "test master\n"); peers = started_peers; - peer_ids = GNUNET_malloc (num_peers * sizeof (struct GNUNET_PeerIdentity)); + peer_ids = GNUNET_malloc(num_peers * sizeof(struct GNUNET_PeerIdentity)); - results_for_peer = GNUNET_malloc (num_peers * sizeof (unsigned int)); - consensus_handles = GNUNET_malloc (num_peers * sizeof (struct ConsensusHandle *)); - testbed_operations = GNUNET_malloc (num_peers * sizeof (struct ConsensusHandle *)); + results_for_peer = GNUNET_malloc(num_peers * sizeof(unsigned int)); + consensus_handles = GNUNET_malloc(num_peers * sizeof(struct ConsensusHandle *)); + testbed_operations = GNUNET_malloc(num_peers * sizeof(struct ConsensusHandle *)); for (i = 0; i < num_peers; i++) - GNUNET_TESTBED_peer_get_information (peers[i], - GNUNET_TESTBED_PIT_IDENTITY, - peer_info_cb, - &peer_ids[i]); + GNUNET_TESTBED_peer_get_information(peers[i], + GNUNET_TESTBED_PIT_IDENTITY, + peer_info_cb, + &peer_ids[i]); } static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { static char *session_str = "gnunet-consensus/test"; char *topology; int topology_cmp_result; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "testbed", "OVERLAY_TOPOLOGY", &topology)) - { - fprintf (stderr, - "'OVERLAY_TOPOLOGY' not found in 'testbed' config section, " - "seems like you passed the wrong configuration file\n"); - return; - } + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, "testbed", "OVERLAY_TOPOLOGY", &topology)) + { + fprintf(stderr, + "'OVERLAY_TOPOLOGY' not found in 'testbed' config section, " + "seems like you passed the wrong configuration file\n"); + return; + } - topology_cmp_result = strcasecmp (topology, "NONE"); - GNUNET_free (topology); + topology_cmp_result = strcasecmp(topology, "NONE"); + GNUNET_free(topology); if (0 == topology_cmp_result) - { - fprintf (stderr, - "'OVERLAY_TOPOLOGY' set to 'NONE', " - "seems like you passed the wrong configuration file\n"); - return; - } + { + fprintf(stderr, + "'OVERLAY_TOPOLOGY' set to 'NONE', " + "seems like you passed the wrong configuration file\n"); + return; + } if (num_peers < replication) - { - fprintf (stderr, "k must be <=n\n"); - return; - } - - start = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (), consensus_delay); - deadline = GNUNET_TIME_absolute_add (start, conclude_timeout); - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "running gnunet-consensus\n"); - - GNUNET_CRYPTO_hash (session_str, strlen(session_str), &session_id); - - (void) GNUNET_TESTBED_test_run ("gnunet-consensus", - cfgfile, - num_peers, - 0, - controller_cb, - NULL, - test_master, - NULL); + { + fprintf(stderr, "k must be <=n\n"); + return; + } + + start = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), consensus_delay); + deadline = GNUNET_TIME_absolute_add(start, conclude_timeout); + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "running gnunet-consensus\n"); + + GNUNET_CRYPTO_hash(session_str, strlen(session_str), &session_id); + + (void)GNUNET_TESTBED_test_run("gnunet-consensus", + cfgfile, + num_peers, + 0, + controller_cb, + NULL, + test_master, + NULL); } int -main (int argc, char **argv) +main(int argc, char **argv) { - struct GNUNET_GETOPT_CommandLineOption options[] = { - - GNUNET_GETOPT_option_uint ('n', - "num-peers", - NULL, - gettext_noop ("number of peers in consensus"), - &num_peers), - - GNUNET_GETOPT_option_uint ('k', - "value-replication", - NULL, - gettext_noop ("how many peers (random selection without replacement) receive one value?"), - &replication), - - GNUNET_GETOPT_option_uint ('x', - "num-values", - NULL, - gettext_noop ("number of values"), - &num_values), - - GNUNET_GETOPT_option_relative_time ('t', - "timeout", - NULL, - gettext_noop ("consensus timeout"), - &conclude_timeout), - - - GNUNET_GETOPT_option_relative_time ('d', - "delay", - NULL, - gettext_noop ("delay until consensus starts"), - &consensus_delay), - - GNUNET_GETOPT_option_filename ('s', - "statistics", - "FILENAME", - gettext_noop ("write statistics to file"), - &statistics_filename), - - GNUNET_GETOPT_option_flag ('S', - "dist-static", - gettext_noop ("distribute elements to a static subset of good peers"), - &dist_static), - - GNUNET_GETOPT_option_flag ('V', - "verbose", - gettext_noop ("be more verbose (print received values)"), - &verbose), - - GNUNET_GETOPT_OPTION_END + struct GNUNET_GETOPT_CommandLineOption options[] = { + GNUNET_GETOPT_option_uint('n', + "num-peers", + NULL, + gettext_noop("number of peers in consensus"), + &num_peers), + + GNUNET_GETOPT_option_uint('k', + "value-replication", + NULL, + gettext_noop("how many peers (random selection without replacement) receive one value?"), + &replication), + + GNUNET_GETOPT_option_uint('x', + "num-values", + NULL, + gettext_noop("number of values"), + &num_values), + + GNUNET_GETOPT_option_relative_time('t', + "timeout", + NULL, + gettext_noop("consensus timeout"), + &conclude_timeout), + + + GNUNET_GETOPT_option_relative_time('d', + "delay", + NULL, + gettext_noop("delay until consensus starts"), + &consensus_delay), + + GNUNET_GETOPT_option_filename('s', + "statistics", + "FILENAME", + gettext_noop("write statistics to file"), + &statistics_filename), + + GNUNET_GETOPT_option_flag('S', + "dist-static", + gettext_noop("distribute elements to a static subset of good peers"), + &dist_static), + + GNUNET_GETOPT_option_flag('V', + "verbose", + gettext_noop("be more verbose (print received values)"), + &verbose), + + GNUNET_GETOPT_OPTION_END }; + conclude_timeout = GNUNET_TIME_UNIT_SECONDS; - GNUNET_PROGRAM_run2 (argc, argv, "gnunet-consensus-profiler", - "help", - options, &run, NULL, GNUNET_YES); + GNUNET_PROGRAM_run2(argc, argv, "gnunet-consensus-profiler", + "help", + options, &run, NULL, GNUNET_YES); return 0; } diff --git a/src/consensus/gnunet-service-consensus.c b/src/consensus/gnunet-service-consensus.c index 912d3de6a..98fd551b2 100644 --- a/src/consensus/gnunet-service-consensus.c +++ b/src/consensus/gnunet-service-consensus.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file consensus/gnunet-service-consensus.c @@ -36,8 +36,7 @@ #include "consensus.h" -enum ReferendumVote -{ +enum ReferendumVote { /** * Vote that nothing should change. * This option is never voted explicitly. @@ -54,8 +53,7 @@ enum ReferendumVote }; -enum EarlyStoppingPhase -{ +enum EarlyStoppingPhase { EARLY_STOPPING_NONE = 0, EARLY_STOPPING_ONE_MORE = 1, EARLY_STOPPING_DONE = 2, @@ -100,16 +98,14 @@ struct TaskKey { -struct SetKey -{ +struct SetKey { int set_kind GNUNET_PACKED; int k1 GNUNET_PACKED; int k2 GNUNET_PACKED; }; -struct SetEntry -{ +struct SetEntry { struct SetKey key; struct GNUNET_SET_Handle *h; /** @@ -121,15 +117,13 @@ struct SetEntry }; -struct DiffKey -{ +struct DiffKey { int diff_kind GNUNET_PACKED; int k1 GNUNET_PACKED; int k2 GNUNET_PACKED; }; -struct RfnKey -{ +struct RfnKey { int rfn_kind GNUNET_PACKED; int k1 GNUNET_PACKED; int k2 GNUNET_PACKED; @@ -138,8 +132,7 @@ struct RfnKey GNUNET_NETWORK_STRUCT_END -enum PhaseKind -{ +enum PhaseKind { PHASE_KIND_ALL_TO_ALL, PHASE_KIND_ALL_TO_ALL_2, PHASE_KIND_GRADECAST_LEADER, @@ -156,8 +149,7 @@ enum PhaseKind }; -enum SetKind -{ +enum SetKind { SET_KIND_NONE = 0, SET_KIND_CURRENT, /** @@ -168,16 +160,14 @@ enum SetKind SET_KIND_ECHO_RESULT, }; -enum DiffKind -{ +enum DiffKind { DIFF_KIND_NONE = 0, DIFF_KIND_LEADER_PROPOSAL, DIFF_KIND_LEADER_CONSENSUS, DIFF_KIND_GRADECAST_RESULT, }; -enum RfnKind -{ +enum RfnKind { RFN_KIND_NONE = 0, RFN_KIND_ECHO, RFN_KIND_CONFIRM, @@ -185,8 +175,7 @@ enum RfnKind }; -struct SetOpCls -{ +struct SetOpCls { struct SetKey input_set; struct SetKey output_set; @@ -201,8 +190,7 @@ struct SetOpCls }; -struct FinishCls -{ +struct FinishCls { struct SetKey input_set; }; @@ -210,8 +198,7 @@ struct FinishCls * Closure for both @a start_task * and @a cancel_task. */ -union TaskFuncCls -{ +union TaskFuncCls { struct SetOpCls setop; struct FinishCls finish; }; @@ -223,8 +210,7 @@ typedef void (*TaskFunc) (struct TaskEntry *task); /* * Node in the consensus task graph. */ -struct TaskEntry -{ +struct TaskEntry { struct TaskKey key; struct Step *step; @@ -240,8 +226,7 @@ struct TaskEntry }; -struct Step -{ +struct Step { /** * All steps of one session are in a * linked list for easier deallocation. @@ -319,8 +304,7 @@ struct Step }; -struct RfnElementInfo -{ +struct RfnElementInfo { const struct GNUNET_SET_Element *element; /* @@ -336,8 +320,7 @@ struct RfnElementInfo }; -struct ReferendumEntry -{ +struct ReferendumEntry { struct RfnKey key; /* @@ -372,8 +355,7 @@ struct ReferendumEntry }; -struct DiffElementInfo -{ +struct DiffElementInfo { const struct GNUNET_SET_Element *element; /** @@ -387,14 +369,12 @@ struct DiffElementInfo /** * Weighted diff. */ -struct DiffEntry -{ +struct DiffEntry { struct DiffKey key; struct GNUNET_CONTAINER_MultiHashMap *changes; }; -struct SetHandle -{ +struct SetHandle { struct SetHandle *prev; struct SetHandle *next; @@ -406,8 +386,7 @@ struct SetHandle /** * A consensus session consists of one local client and the remote authorities. */ -struct ConsensusSession -{ +struct ConsensusSession { /** * Consensus sessions are kept in a DLL. */ @@ -446,9 +425,9 @@ struct ConsensusSession int conclude_done; /** - * Global consensus identification, computed - * from the session id and participating authorities. - */ + * Global consensus identification, computed + * from the session id and participating authorities. + */ struct GNUNET_HashCode global_id; /** @@ -539,128 +518,147 @@ struct GNUNET_STATISTICS_Handle *statistics; static void -finish_task (struct TaskEntry *task); +finish_task(struct TaskEntry *task); static void -run_ready_steps (struct ConsensusSession *session); +run_ready_steps(struct ConsensusSession *session); static const char * -phasename (uint16_t phase) +phasename(uint16_t phase) { switch (phase) - { + { case PHASE_KIND_ALL_TO_ALL: return "ALL_TO_ALL"; + case PHASE_KIND_ALL_TO_ALL_2: return "ALL_TO_ALL_2"; + case PHASE_KIND_FINISH: return "FINISH"; + case PHASE_KIND_GRADECAST_LEADER: return "GRADECAST_LEADER"; + case PHASE_KIND_GRADECAST_ECHO: return "GRADECAST_ECHO"; + case PHASE_KIND_GRADECAST_ECHO_GRADE: return "GRADECAST_ECHO_GRADE"; + case PHASE_KIND_GRADECAST_CONFIRM: return "GRADECAST_CONFIRM"; + case PHASE_KIND_GRADECAST_CONFIRM_GRADE: return "GRADECAST_CONFIRM_GRADE"; + case PHASE_KIND_APPLY_REP: return "APPLY_REP"; + default: return "(unknown)"; - } + } } static const char * -setname (uint16_t kind) +setname(uint16_t kind) { switch (kind) - { + { case SET_KIND_CURRENT: return "CURRENT"; + case SET_KIND_LEADER_PROPOSAL: return "LEADER_PROPOSAL"; + case SET_KIND_NONE: return "NONE"; + default: return "(unknown)"; - } + } } static const char * -rfnname (uint16_t kind) +rfnname(uint16_t kind) { switch (kind) - { + { case RFN_KIND_NONE: return "NONE"; + case RFN_KIND_ECHO: return "ECHO"; + case RFN_KIND_CONFIRM: return "CONFIRM"; + default: return "(unknown)"; - } + } } static const char * -diffname (uint16_t kind) +diffname(uint16_t kind) { switch (kind) - { + { case DIFF_KIND_NONE: return "NONE"; + case DIFF_KIND_LEADER_CONSENSUS: return "LEADER_CONSENSUS"; + case DIFF_KIND_GRADECAST_RESULT: return "GRADECAST_RESULT"; + case DIFF_KIND_LEADER_PROPOSAL: return "LEADER_PROPOSAL"; + default: return "(unknown)"; - } + } } #ifdef GNUNET_EXTRA_LOGGING static const char * -debug_str_element (const struct GNUNET_SET_Element *el) +debug_str_element(const struct GNUNET_SET_Element *el) { struct GNUNET_HashCode hash; - GNUNET_SET_element_hash (el, &hash); + GNUNET_SET_element_hash(el, &hash); - return GNUNET_h2s (&hash); + return GNUNET_h2s(&hash); } static const char * -debug_str_task_key (struct TaskKey *tk) +debug_str_task_key(struct TaskKey *tk) { static char buf[256]; - snprintf (buf, sizeof (buf), - "TaskKey kind=%s, p1=%d, p2=%d, l=%d, rep=%d", - phasename (tk->kind), tk->peer1, tk->peer2, - tk->leader, tk->repetition); + snprintf(buf, sizeof(buf), + "TaskKey kind=%s, p1=%d, p2=%d, l=%d, rep=%d", + phasename(tk->kind), tk->peer1, tk->peer2, + tk->leader, tk->repetition); return buf; } static const char * -debug_str_diff_key (struct DiffKey *dk) +debug_str_diff_key(struct DiffKey *dk) { static char buf[256]; - snprintf (buf, sizeof (buf), - "DiffKey kind=%s, k1=%d, k2=%d", - diffname (dk->diff_kind), dk->k1, dk->k2); + snprintf(buf, sizeof(buf), + "DiffKey kind=%s, k1=%d, k2=%d", + diffname(dk->diff_kind), dk->k1, dk->k2); return buf; } static const char * -debug_str_set_key (const struct SetKey *sk) +debug_str_set_key(const struct SetKey *sk) { static char buf[256]; - snprintf (buf, sizeof (buf), - "SetKey kind=%s, k1=%d, k2=%d", - setname (sk->set_kind), sk->k1, sk->k2); + snprintf(buf, sizeof(buf), + "SetKey kind=%s, k1=%d, k2=%d", + setname(sk->set_kind), sk->k1, sk->k2); return buf; } static const char * -debug_str_rfn_key (const struct RfnKey *rk) +debug_str_rfn_key(const struct RfnKey *rk) { static char buf[256]; - snprintf (buf, sizeof (buf), - "RfnKey kind=%s, k1=%d, k2=%d", - rfnname (rk->rfn_kind), rk->k1, rk->k2); + snprintf(buf, sizeof(buf), + "RfnKey kind=%s, k1=%d, k2=%d", + rfnname(rk->rfn_kind), rk->k1, rk->k2); return buf; } @@ -678,164 +676,164 @@ debug_str_rfn_key (const struct RfnKey *rk) * @return #GNUNET_YES to continue iterating, #GNUNET_NO to stop. */ static int -send_to_client_iter (void *cls, - const struct GNUNET_SET_Element *element) +send_to_client_iter(void *cls, + const struct GNUNET_SET_Element *element) { - struct TaskEntry *task = (struct TaskEntry *) cls; + struct TaskEntry *task = (struct TaskEntry *)cls; struct ConsensusSession *session = task->step->session; struct GNUNET_MQ_Envelope *ev; if (NULL != element) - { - struct GNUNET_CONSENSUS_ElementMessage *m; - const struct ConsensusElement *ce; + { + struct GNUNET_CONSENSUS_ElementMessage *m; + const struct ConsensusElement *ce; - GNUNET_assert (GNUNET_BLOCK_TYPE_CONSENSUS_ELEMENT == element->element_type); - ce = element->data; + GNUNET_assert(GNUNET_BLOCK_TYPE_CONSENSUS_ELEMENT == element->element_type); + ce = element->data; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "marker is %u\n", (unsigned) ce->marker); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "marker is %u\n", (unsigned)ce->marker); - if (0 != ce->marker) - return GNUNET_YES; + if (0 != ce->marker) + return GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%d: sending element %s to client\n", - session->local_peer_idx, - debug_str_element (element)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%d: sending element %s to client\n", + session->local_peer_idx, + debug_str_element(element)); - ev = GNUNET_MQ_msg_extra (m, element->size - sizeof (struct ConsensusElement), - GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_RECEIVED_ELEMENT); - m->element_type = ce->payload_type; - GNUNET_memcpy (&m[1], &ce[1], element->size - sizeof (struct ConsensusElement)); - GNUNET_MQ_send (session->client_mq, ev); - } + ev = GNUNET_MQ_msg_extra(m, element->size - sizeof(struct ConsensusElement), + GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_RECEIVED_ELEMENT); + m->element_type = ce->payload_type; + GNUNET_memcpy(&m[1], &ce[1], element->size - sizeof(struct ConsensusElement)); + GNUNET_MQ_send(session->client_mq, ev); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%d: finished iterating elements for client\n", - session->local_peer_idx); - ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_CONCLUDE_DONE); - GNUNET_MQ_send (session->client_mq, ev); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%d: finished iterating elements for client\n", + session->local_peer_idx); + ev = GNUNET_MQ_msg_header(GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_CONCLUDE_DONE); + GNUNET_MQ_send(session->client_mq, ev); + } return GNUNET_YES; } static struct SetEntry * -lookup_set (struct ConsensusSession *session, struct SetKey *key) +lookup_set(struct ConsensusSession *session, struct SetKey *key) { struct GNUNET_HashCode hash; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: looking up set {%s}\n", - session->local_peer_idx, - debug_str_set_key (key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: looking up set {%s}\n", + session->local_peer_idx, + debug_str_set_key(key)); - GNUNET_assert (SET_KIND_NONE != key->set_kind); - GNUNET_CRYPTO_hash (key, sizeof (struct SetKey), &hash); - return GNUNET_CONTAINER_multihashmap_get (session->setmap, &hash); + GNUNET_assert(SET_KIND_NONE != key->set_kind); + GNUNET_CRYPTO_hash(key, sizeof(struct SetKey), &hash); + return GNUNET_CONTAINER_multihashmap_get(session->setmap, &hash); } static struct DiffEntry * -lookup_diff (struct ConsensusSession *session, struct DiffKey *key) +lookup_diff(struct ConsensusSession *session, struct DiffKey *key) { struct GNUNET_HashCode hash; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: looking up diff {%s}\n", - session->local_peer_idx, - debug_str_diff_key (key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: looking up diff {%s}\n", + session->local_peer_idx, + debug_str_diff_key(key)); - GNUNET_assert (DIFF_KIND_NONE != key->diff_kind); - GNUNET_CRYPTO_hash (key, sizeof (struct DiffKey), &hash); - return GNUNET_CONTAINER_multihashmap_get (session->diffmap, &hash); + GNUNET_assert(DIFF_KIND_NONE != key->diff_kind); + GNUNET_CRYPTO_hash(key, sizeof(struct DiffKey), &hash); + return GNUNET_CONTAINER_multihashmap_get(session->diffmap, &hash); } static struct ReferendumEntry * -lookup_rfn (struct ConsensusSession *session, struct RfnKey *key) +lookup_rfn(struct ConsensusSession *session, struct RfnKey *key) { struct GNUNET_HashCode hash; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: looking up rfn {%s}\n", - session->local_peer_idx, - debug_str_rfn_key (key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: looking up rfn {%s}\n", + session->local_peer_idx, + debug_str_rfn_key(key)); - GNUNET_assert (RFN_KIND_NONE != key->rfn_kind); - GNUNET_CRYPTO_hash (key, sizeof (struct RfnKey), &hash); - return GNUNET_CONTAINER_multihashmap_get (session->rfnmap, &hash); + GNUNET_assert(RFN_KIND_NONE != key->rfn_kind); + GNUNET_CRYPTO_hash(key, sizeof(struct RfnKey), &hash); + return GNUNET_CONTAINER_multihashmap_get(session->rfnmap, &hash); } static void -diff_insert (struct DiffEntry *diff, - int weight, - const struct GNUNET_SET_Element *element) +diff_insert(struct DiffEntry *diff, + int weight, + const struct GNUNET_SET_Element *element) { struct DiffElementInfo *di; struct GNUNET_HashCode hash; - GNUNET_assert ( (1 == weight) || (-1 == weight)); + GNUNET_assert((1 == weight) || (-1 == weight)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "diff_insert with element size %u\n", - element->size); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "diff_insert with element size %u\n", + element->size); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "hashing element\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "hashing element\n"); - GNUNET_SET_element_hash (element, &hash); + GNUNET_SET_element_hash(element, &hash); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "hashed element\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "hashed element\n"); - di = GNUNET_CONTAINER_multihashmap_get (diff->changes, &hash); + di = GNUNET_CONTAINER_multihashmap_get(diff->changes, &hash); if (NULL == di) - { - di = GNUNET_new (struct DiffElementInfo); - di->element = GNUNET_SET_element_dup (element); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (diff->changes, + { + di = GNUNET_new(struct DiffElementInfo); + di->element = GNUNET_SET_element_dup(element); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(diff->changes, &hash, di, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)); - } + } di->weight = weight; } static void -rfn_commit (struct ReferendumEntry *rfn, - uint16_t commit_peer) +rfn_commit(struct ReferendumEntry *rfn, + uint16_t commit_peer) { - GNUNET_assert (commit_peer < rfn->num_peers); + GNUNET_assert(commit_peer < rfn->num_peers); rfn->peer_commited[commit_peer] = GNUNET_YES; } static void -rfn_contest (struct ReferendumEntry *rfn, - uint16_t contested_peer) +rfn_contest(struct ReferendumEntry *rfn, + uint16_t contested_peer) { - GNUNET_assert (contested_peer < rfn->num_peers); + GNUNET_assert(contested_peer < rfn->num_peers); rfn->peer_contested[contested_peer] = GNUNET_YES; } static uint16_t -rfn_noncontested (struct ReferendumEntry *rfn) +rfn_noncontested(struct ReferendumEntry *rfn) { uint16_t i; uint16_t ret; ret = 0; for (i = 0; i < rfn->num_peers; i++) - if ( (GNUNET_YES == rfn->peer_commited[i]) && (GNUNET_NO == rfn->peer_contested[i]) ) + if ((GNUNET_YES == rfn->peer_commited[i]) && (GNUNET_NO == rfn->peer_contested[i])) ret++; return ret; @@ -843,33 +841,33 @@ rfn_noncontested (struct ReferendumEntry *rfn) static void -rfn_vote (struct ReferendumEntry *rfn, - uint16_t voting_peer, - enum ReferendumVote vote, - const struct GNUNET_SET_Element *element) +rfn_vote(struct ReferendumEntry *rfn, + uint16_t voting_peer, + enum ReferendumVote vote, + const struct GNUNET_SET_Element *element) { struct RfnElementInfo *ri; struct GNUNET_HashCode hash; - GNUNET_assert (voting_peer < rfn->num_peers); + GNUNET_assert(voting_peer < rfn->num_peers); /* Explicit voting only makes sense with VOTE_ADD or VOTE_REMOTE, since VOTE_KEEP is implicit in not voting. */ - GNUNET_assert ( (VOTE_ADD == vote) || (VOTE_REMOVE == vote) ); + GNUNET_assert((VOTE_ADD == vote) || (VOTE_REMOVE == vote)); - GNUNET_SET_element_hash (element, &hash); - ri = GNUNET_CONTAINER_multihashmap_get (rfn->rfn_elements, &hash); + GNUNET_SET_element_hash(element, &hash); + ri = GNUNET_CONTAINER_multihashmap_get(rfn->rfn_elements, &hash); if (NULL == ri) - { - ri = GNUNET_new (struct RfnElementInfo); - ri->element = GNUNET_SET_element_dup (element); - ri->votes = GNUNET_new_array (rfn->num_peers, int); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (rfn->rfn_elements, + { + ri = GNUNET_new(struct RfnElementInfo); + ri->element = GNUNET_SET_element_dup(element); + ri->votes = GNUNET_new_array(rfn->num_peers, int); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(rfn->rfn_elements, &hash, ri, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)); - } + } ri->votes[voting_peer] = GNUNET_YES; ri->proposal = vote; @@ -877,9 +875,10 @@ rfn_vote (struct ReferendumEntry *rfn, static uint16_t -task_other_peer (struct TaskEntry *task) +task_other_peer(struct TaskEntry *task) { uint16_t me = task->step->session->local_peer_idx; + if (task->key.peer1 == me) return task->key.peer2; return task->key.peer1; @@ -887,10 +886,10 @@ task_other_peer (struct TaskEntry *task) static int -cmp_uint64_t (const void *pa, const void *pb) +cmp_uint64_t(const void *pa, const void *pb) { - uint64_t a = *(uint64_t *) pa; - uint64_t b = *(uint64_t *) pb; + uint64_t a = *(uint64_t *)pa; + uint64_t b = *(uint64_t *)pb; if (a == b) return 0; @@ -910,10 +909,10 @@ cmp_uint64_t (const void *pa, const void *pb) * @param status see enum GNUNET_SET_Status */ static void -set_result_cb (void *cls, - const struct GNUNET_SET_Element *element, - uint64_t current_size, - enum GNUNET_SET_Status status) +set_result_cb(void *cls, + const struct GNUNET_SET_Element *element, + uint64_t current_size, + enum GNUNET_SET_Status status) { struct TaskEntry *task = cls; struct ConsensusSession *session = task->step->session; @@ -925,244 +924,246 @@ set_result_cb (void *cls, const struct ConsensusElement *consensus_element = NULL; if (NULL != element) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: got element of type %u, status %u\n", - session->local_peer_idx, - (unsigned) element->element_type, - (unsigned) status); - GNUNET_assert (GNUNET_BLOCK_TYPE_CONSENSUS_ELEMENT == element->element_type); - consensus_element = element->data; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: got element of type %u, status %u\n", + session->local_peer_idx, + (unsigned)element->element_type, + (unsigned)status); + GNUNET_assert(GNUNET_BLOCK_TYPE_CONSENSUS_ELEMENT == element->element_type); + consensus_element = element->data; + } setop = &task->cls.setop; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: got set result for {%s}, status %u\n", - session->local_peer_idx, - debug_str_task_key (&task->key), - status); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: got set result for {%s}, status %u\n", + session->local_peer_idx, + debug_str_task_key(&task->key), + status); if (GNUNET_NO == task->is_started) - { - GNUNET_break_op (0); - return; - } + { + GNUNET_break_op(0); + return; + } if (GNUNET_YES == task->is_finished) - { - GNUNET_break_op (0); - return; - } + { + GNUNET_break_op(0); + return; + } - other_idx = task_other_peer (task); + other_idx = task_other_peer(task); if (SET_KIND_NONE != setop->output_set.set_kind) - { - output_set = lookup_set (session, &setop->output_set); - GNUNET_assert (NULL != output_set); - } + { + output_set = lookup_set(session, &setop->output_set); + GNUNET_assert(NULL != output_set); + } if (DIFF_KIND_NONE != setop->output_diff.diff_kind) - { - output_diff = lookup_diff (session, &setop->output_diff); - GNUNET_assert (NULL != output_diff); - } + { + output_diff = lookup_diff(session, &setop->output_diff); + GNUNET_assert(NULL != output_diff); + } if (RFN_KIND_NONE != setop->output_rfn.rfn_kind) - { - output_rfn = lookup_rfn (session, &setop->output_rfn); - GNUNET_assert (NULL != output_rfn); - } + { + output_rfn = lookup_rfn(session, &setop->output_rfn); + GNUNET_assert(NULL != output_rfn); + } if (GNUNET_YES == session->peers_blacklisted[other_idx]) - { - /* Peer might have been blacklisted - by a gradecast running in parallel, ignore elements from now */ - if (GNUNET_SET_STATUS_ADD_LOCAL == status) - return; - if (GNUNET_SET_STATUS_ADD_REMOTE == status) - return; - } - - if ( (NULL != consensus_element) && (0 != consensus_element->marker) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: got some marker\n", - session->local_peer_idx); - if ( (GNUNET_YES == setop->transceive_contested) && - (CONSENSUS_MARKER_CONTESTED == consensus_element->marker) ) - { - GNUNET_assert (NULL != output_rfn); - rfn_contest (output_rfn, task_other_peer (task)); - return; + { + /* Peer might have been blacklisted + by a gradecast running in parallel, ignore elements from now */ + if (GNUNET_SET_STATUS_ADD_LOCAL == status) + return; + if (GNUNET_SET_STATUS_ADD_REMOTE == status) + return; } - if (CONSENSUS_MARKER_SIZE == consensus_element->marker) + if ((NULL != consensus_element) && (0 != consensus_element->marker)) { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: got some marker\n", + session->local_peer_idx); + if ((GNUNET_YES == setop->transceive_contested) && + (CONSENSUS_MARKER_CONTESTED == consensus_element->marker)) + { + GNUNET_assert(NULL != output_rfn); + rfn_contest(output_rfn, task_other_peer(task)); + return; + } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: got size marker\n", - session->local_peer_idx); - - - struct ConsensusSizeElement *cse = (void *) consensus_element; + if (CONSENSUS_MARKER_SIZE == consensus_element->marker) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: got size marker\n", + session->local_peer_idx); + + + struct ConsensusSizeElement *cse = (void *)consensus_element; + + if (cse->sender_index == other_idx) + { + if (NULL == session->first_sizes_received) + session->first_sizes_received = GNUNET_new_array(session->num_peers, uint64_t); + session->first_sizes_received[other_idx] = GNUNET_ntohll(cse->size); + + uint64_t *copy = GNUNET_memdup(session->first_sizes_received, sizeof(uint64_t) * session->num_peers); + qsort(copy, session->num_peers, sizeof(uint64_t), cmp_uint64_t); + session->lower_bound = copy[session->num_peers / 3 + 1]; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: lower bound %llu\n", + session->local_peer_idx, + (long long)session->lower_bound); + GNUNET_free(copy); + } + return; + } - if (cse->sender_index == other_idx) - { - if (NULL == session->first_sizes_received) - session->first_sizes_received = GNUNET_new_array (session->num_peers, uint64_t); - session->first_sizes_received[other_idx] = GNUNET_ntohll (cse->size); - - uint64_t *copy = GNUNET_memdup (session->first_sizes_received, sizeof (uint64_t) * session->num_peers); - qsort (copy, session->num_peers, sizeof (uint64_t), cmp_uint64_t); - session->lower_bound = copy[session->num_peers / 3 + 1]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: lower bound %llu\n", - session->local_peer_idx, - (long long) session->lower_bound); - GNUNET_free (copy); - } return; } - return; - } - switch (status) - { + { case GNUNET_SET_STATUS_ADD_LOCAL: - GNUNET_assert (NULL != consensus_element); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding element in Task {%s}\n", - debug_str_task_key (&task->key)); + GNUNET_assert(NULL != consensus_element); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding element in Task {%s}\n", + debug_str_task_key(&task->key)); if (NULL != output_set) - { - // FIXME: record pending adds, use callback - GNUNET_SET_add_element (output_set->h, - element, - NULL, - NULL); + { + // FIXME: record pending adds, use callback + GNUNET_SET_add_element(output_set->h, + element, + NULL, + NULL); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: adding element %s into set {%s} of task {%s}\n", - session->local_peer_idx, - debug_str_element (element), - debug_str_set_key (&setop->output_set), - debug_str_task_key (&task->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: adding element %s into set {%s} of task {%s}\n", + session->local_peer_idx, + debug_str_element(element), + debug_str_set_key(&setop->output_set), + debug_str_task_key(&task->key)); #endif - } + } if (NULL != output_diff) - { - diff_insert (output_diff, 1, element); + { + diff_insert(output_diff, 1, element); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: adding element %s into diff {%s} of task {%s}\n", - session->local_peer_idx, - debug_str_element (element), - debug_str_diff_key (&setop->output_diff), - debug_str_task_key (&task->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: adding element %s into diff {%s} of task {%s}\n", + session->local_peer_idx, + debug_str_element(element), + debug_str_diff_key(&setop->output_diff), + debug_str_task_key(&task->key)); #endif - } + } if (NULL != output_rfn) - { - rfn_vote (output_rfn, task_other_peer (task), VOTE_ADD, element); + { + rfn_vote(output_rfn, task_other_peer(task), VOTE_ADD, element); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: adding element %s into rfn {%s} of task {%s}\n", - session->local_peer_idx, - debug_str_element (element), - debug_str_rfn_key (&setop->output_rfn), - debug_str_task_key (&task->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: adding element %s into rfn {%s} of task {%s}\n", + session->local_peer_idx, + debug_str_element(element), + debug_str_rfn_key(&setop->output_rfn), + debug_str_task_key(&task->key)); #endif - } + } // XXX: add result to structures in task break; + case GNUNET_SET_STATUS_ADD_REMOTE: - GNUNET_assert (NULL != consensus_element); + GNUNET_assert(NULL != consensus_element); if (GNUNET_YES == setop->do_not_remove) break; if (CONSENSUS_MARKER_CONTESTED == consensus_element->marker) break; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Removing element in Task {%s}\n", - debug_str_task_key (&task->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Removing element in Task {%s}\n", + debug_str_task_key(&task->key)); if (NULL != output_set) - { - // FIXME: record pending adds, use callback - GNUNET_SET_remove_element (output_set->h, - element, - NULL, - NULL); + { + // FIXME: record pending adds, use callback + GNUNET_SET_remove_element(output_set->h, + element, + NULL, + NULL); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: removing element %s from set {%s} of task {%s}\n", - session->local_peer_idx, - debug_str_element (element), - debug_str_set_key (&setop->output_set), - debug_str_task_key (&task->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: removing element %s from set {%s} of task {%s}\n", + session->local_peer_idx, + debug_str_element(element), + debug_str_set_key(&setop->output_set), + debug_str_task_key(&task->key)); #endif - } + } if (NULL != output_diff) - { - diff_insert (output_diff, -1, element); + { + diff_insert(output_diff, -1, element); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: removing element %s from diff {%s} of task {%s}\n", - session->local_peer_idx, - debug_str_element (element), - debug_str_diff_key (&setop->output_diff), - debug_str_task_key (&task->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: removing element %s from diff {%s} of task {%s}\n", + session->local_peer_idx, + debug_str_element(element), + debug_str_diff_key(&setop->output_diff), + debug_str_task_key(&task->key)); #endif - } + } if (NULL != output_rfn) - { - rfn_vote (output_rfn, task_other_peer (task), VOTE_REMOVE, element); + { + rfn_vote(output_rfn, task_other_peer(task), VOTE_REMOVE, element); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: removing element %s from rfn {%s} of task {%s}\n", - session->local_peer_idx, - debug_str_element (element), - debug_str_rfn_key (&setop->output_rfn), - debug_str_task_key (&task->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: removing element %s from rfn {%s} of task {%s}\n", + session->local_peer_idx, + debug_str_element(element), + debug_str_rfn_key(&setop->output_rfn), + debug_str_task_key(&task->key)); #endif - } + } break; + case GNUNET_SET_STATUS_DONE: // XXX: check first if any changes to the underlying // set are still pending - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: Finishing setop in Task {%s} (%u/%u)\n", - session->local_peer_idx, - debug_str_task_key (&task->key), - (unsigned int) task->step->finished_tasks, - (unsigned int) task->step->tasks_len); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: Finishing setop in Task {%s} (%u/%u)\n", + session->local_peer_idx, + debug_str_task_key(&task->key), + (unsigned int)task->step->finished_tasks, + (unsigned int)task->step->tasks_len); if (NULL != output_rfn) - { - rfn_commit (output_rfn, task_other_peer (task)); - } + { + rfn_commit(output_rfn, task_other_peer(task)); + } if (PHASE_KIND_ALL_TO_ALL == task->key.kind) - { - session->first_size = current_size; - } - finish_task (task); + { + session->first_size = current_size; + } + finish_task(task); break; + case GNUNET_SET_STATUS_FAILURE: // XXX: cleanup - GNUNET_break_op (0); - finish_task (task); + GNUNET_break_op(0); + finish_task(task); return; + default: /* not reached */ - GNUNET_assert (0); - } + GNUNET_assert(0); + } } #ifdef EVIL -enum EvilnessType -{ +enum EvilnessType { EVILNESS_NONE, EVILNESS_CRAM_ALL, EVILNESS_CRAM_LEAD, @@ -1171,15 +1172,13 @@ enum EvilnessType EVILNESS_SLACK_A2A, }; -enum EvilnessSubType -{ +enum EvilnessSubType { EVILNESS_SUB_NONE, EVILNESS_SUB_REPLACEMENT, EVILNESS_SUB_NO_REPLACEMENT, }; -struct Evilness -{ +struct Evilness { enum EvilnessType type; enum EvilnessSubType subtype; unsigned int num; @@ -1187,129 +1186,129 @@ struct Evilness static int -parse_evilness_cram_subtype (const char *evil_subtype_str, struct Evilness *evil) +parse_evilness_cram_subtype(const char *evil_subtype_str, struct Evilness *evil) { - if (0 == strcmp ("replace", evil_subtype_str)) - { - evil->subtype = EVILNESS_SUB_REPLACEMENT; - } - else if (0 == strcmp ("noreplace", evil_subtype_str)) - { - evil->subtype = EVILNESS_SUB_NO_REPLACEMENT; - } + if (0 == strcmp("replace", evil_subtype_str)) + { + evil->subtype = EVILNESS_SUB_REPLACEMENT; + } + else if (0 == strcmp("noreplace", evil_subtype_str)) + { + evil->subtype = EVILNESS_SUB_NO_REPLACEMENT; + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed field '%s' in EVIL_SPEC (unknown subtype), behaving like a good peer.\n", - evil_subtype_str); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed field '%s' in EVIL_SPEC (unknown subtype), behaving like a good peer.\n", + evil_subtype_str); + return GNUNET_SYSERR; + } return GNUNET_OK; } static void -get_evilness (struct ConsensusSession *session, struct Evilness *evil) +get_evilness(struct ConsensusSession *session, struct Evilness *evil) { char *evil_spec; char *field; char *evil_type_str = NULL; char *evil_subtype_str = NULL; - GNUNET_assert (NULL != evil); + GNUNET_assert(NULL != evil); - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "consensus", "EVIL_SPEC", &evil_spec)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: no evilness\n", - session->local_peer_idx); - evil->type = EVILNESS_NONE; - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: got evilness spec\n", - session->local_peer_idx); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, "consensus", "EVIL_SPEC", &evil_spec)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: no evilness\n", + session->local_peer_idx); + evil->type = EVILNESS_NONE; + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: got evilness spec\n", + session->local_peer_idx); - for (field = strtok (evil_spec, "/"); + for (field = strtok(evil_spec, "/"); NULL != field; - field = strtok (NULL, "/")) - { - unsigned int peer_num; - unsigned int evil_num; - int ret; + field = strtok(NULL, "/")) + { + unsigned int peer_num; + unsigned int evil_num; + int ret; - evil_type_str = NULL; - evil_subtype_str = NULL; + evil_type_str = NULL; + evil_subtype_str = NULL; - ret = sscanf (field, "%u;%m[a-z-];%m[a-z-];%u", &peer_num, &evil_type_str, &evil_subtype_str, &evil_num); + ret = sscanf(field, "%u;%m[a-z-];%m[a-z-];%u", &peer_num, &evil_type_str, &evil_subtype_str, &evil_num); - if (ret != 4) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed field '%s' in EVIL_SPEC (expected 4 components got %d), behaving like a good peer.\n", - field, - ret); - goto not_evil; - } + if (ret != 4) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed field '%s' in EVIL_SPEC (expected 4 components got %d), behaving like a good peer.\n", + field, + ret); + goto not_evil; + } - GNUNET_assert (NULL != evil_type_str); - GNUNET_assert (NULL != evil_subtype_str); + GNUNET_assert(NULL != evil_type_str); + GNUNET_assert(NULL != evil_subtype_str); - if (peer_num == session->local_peer_idx) - { - if (0 == strcmp ("slack", evil_type_str)) - { - evil->type = EVILNESS_SLACK; - } - if (0 == strcmp ("slack-a2a", evil_type_str)) - { - evil->type = EVILNESS_SLACK_A2A; - } - else if (0 == strcmp ("cram-all", evil_type_str)) - { - evil->type = EVILNESS_CRAM_ALL; - evil->num = evil_num; - if (GNUNET_OK != parse_evilness_cram_subtype (evil_subtype_str, evil)) - goto not_evil; - } - else if (0 == strcmp ("cram-lead", evil_type_str)) - { - evil->type = EVILNESS_CRAM_LEAD; - evil->num = evil_num; - if (GNUNET_OK != parse_evilness_cram_subtype (evil_subtype_str, evil)) - goto not_evil; - } - else if (0 == strcmp ("cram-echo", evil_type_str)) - { - evil->type = EVILNESS_CRAM_ECHO; - evil->num = evil_num; - if (GNUNET_OK != parse_evilness_cram_subtype (evil_subtype_str, evil)) - goto not_evil; - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed field '%s' in EVIL_SPEC (unknown type), behaving like a good peer.\n", - evil_type_str); - goto not_evil; - } - goto cleanup; + if (peer_num == session->local_peer_idx) + { + if (0 == strcmp("slack", evil_type_str)) + { + evil->type = EVILNESS_SLACK; + } + if (0 == strcmp("slack-a2a", evil_type_str)) + { + evil->type = EVILNESS_SLACK_A2A; + } + else if (0 == strcmp("cram-all", evil_type_str)) + { + evil->type = EVILNESS_CRAM_ALL; + evil->num = evil_num; + if (GNUNET_OK != parse_evilness_cram_subtype(evil_subtype_str, evil)) + goto not_evil; + } + else if (0 == strcmp("cram-lead", evil_type_str)) + { + evil->type = EVILNESS_CRAM_LEAD; + evil->num = evil_num; + if (GNUNET_OK != parse_evilness_cram_subtype(evil_subtype_str, evil)) + goto not_evil; + } + else if (0 == strcmp("cram-echo", evil_type_str)) + { + evil->type = EVILNESS_CRAM_ECHO; + evil->num = evil_num; + if (GNUNET_OK != parse_evilness_cram_subtype(evil_subtype_str, evil)) + goto not_evil; + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed field '%s' in EVIL_SPEC (unknown type), behaving like a good peer.\n", + evil_type_str); + goto not_evil; + } + goto cleanup; + } + /* No GNUNET_free since memory was allocated by libc */ + free(evil_type_str); + evil_type_str = NULL; + evil_subtype_str = NULL; } - /* No GNUNET_free since memory was allocated by libc */ - free (evil_type_str); - evil_type_str = NULL; - evil_subtype_str = NULL; - } not_evil: evil->type = EVILNESS_NONE; cleanup: - GNUNET_free (evil_spec); + GNUNET_free(evil_spec); /* no GNUNET_free_non_null since it wasn't * allocated with GNUNET_malloc */ if (NULL != evil_type_str) - free (evil_type_str); + free(evil_type_str); if (NULL != evil_subtype_str) - free (evil_subtype_str); + free(evil_subtype_str); } #endif @@ -1320,60 +1319,60 @@ cleanup: * task. */ static void -commit_set (struct ConsensusSession *session, - struct TaskEntry *task) +commit_set(struct ConsensusSession *session, + struct TaskEntry *task) { struct SetEntry *set; struct SetOpCls *setop = &task->cls.setop; - GNUNET_assert (NULL != setop->op); - set = lookup_set (session, &setop->input_set); - GNUNET_assert (NULL != set); + GNUNET_assert(NULL != setop->op); + set = lookup_set(session, &setop->input_set); + GNUNET_assert(NULL != set); - if ( (GNUNET_YES == setop->transceive_contested) && (GNUNET_YES == set->is_contested) ) - { - struct GNUNET_SET_Element element; - struct ConsensusElement ce = { 0 }; - ce.marker = CONSENSUS_MARKER_CONTESTED; - element.data = &ce; - element.size = sizeof (struct ConsensusElement); - element.element_type = GNUNET_BLOCK_TYPE_CONSENSUS_ELEMENT; - GNUNET_SET_add_element (set->h, &element, NULL, NULL); - } + if ((GNUNET_YES == setop->transceive_contested) && (GNUNET_YES == set->is_contested)) + { + struct GNUNET_SET_Element element; + struct ConsensusElement ce = { 0 }; + ce.marker = CONSENSUS_MARKER_CONTESTED; + element.data = &ce; + element.size = sizeof(struct ConsensusElement); + element.element_type = GNUNET_BLOCK_TYPE_CONSENSUS_ELEMENT; + GNUNET_SET_add_element(set->h, &element, NULL, NULL); + } if (PHASE_KIND_ALL_TO_ALL_2 == task->key.kind) - { - struct GNUNET_SET_Element element; - struct ConsensusSizeElement cse = { - .size = 0, - .sender_index = 0 - }; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "inserting size marker\n"); - cse.ce.marker = CONSENSUS_MARKER_SIZE; - cse.size = GNUNET_htonll (session->first_size); - cse.sender_index = session->local_peer_idx; - element.data = &cse; - element.size = sizeof (struct ConsensusSizeElement); - element.element_type = GNUNET_BLOCK_TYPE_CONSENSUS_ELEMENT; - GNUNET_SET_add_element (set->h, &element, NULL, NULL); - } + { + struct GNUNET_SET_Element element; + struct ConsensusSizeElement cse = { + .size = 0, + .sender_index = 0 + }; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "inserting size marker\n"); + cse.ce.marker = CONSENSUS_MARKER_SIZE; + cse.size = GNUNET_htonll(session->first_size); + cse.sender_index = session->local_peer_idx; + element.data = &cse; + element.size = sizeof(struct ConsensusSizeElement); + element.element_type = GNUNET_BLOCK_TYPE_CONSENSUS_ELEMENT; + GNUNET_SET_add_element(set->h, &element, NULL, NULL); + } #ifdef EVIL { unsigned int i; struct Evilness evil; - get_evilness (session, &evil); + get_evilness(session, &evil); if (EVILNESS_NONE != evil.type) - { - /* Useful for evaluation */ - GNUNET_STATISTICS_set (statistics, - "is evil", - 1, - GNUNET_NO); - } + { + /* Useful for evaluation */ + GNUNET_STATISTICS_set(statistics, + "is evil", + 1, + GNUNET_NO); + } switch (evil.type) - { + { case EVILNESS_CRAM_ALL: case EVILNESS_CRAM_LEAD: case EVILNESS_CRAM_ECHO: @@ -1382,236 +1381,239 @@ commit_set (struct ConsensusSession *session, add more elements to the result set, but wouldn't test robustness. */ if (PHASE_KIND_ALL_TO_ALL == task->key.kind) - { - GNUNET_SET_commit (setop->op, set->h); - break; - } + { + GNUNET_SET_commit(setop->op, set->h); + break; + } if ((EVILNESS_CRAM_LEAD == evil.type) && ((PHASE_KIND_GRADECAST_LEADER != task->key.kind) || SET_KIND_CURRENT != set->key.set_kind)) - { - GNUNET_SET_commit (setop->op, set->h); - break; - } - if (EVILNESS_CRAM_ECHO == evil.type && (PHASE_KIND_GRADECAST_ECHO != task->key.kind)) - { - GNUNET_SET_commit (setop->op, set->h); - break; - } - for (i = 0; i < evil.num; i++) - { - struct GNUNET_SET_Element element; - struct ConsensusStuffedElement se = { - .ce.payload_type = 0, - .ce.marker = 0, - }; - element.data = &se; - element.size = sizeof (struct ConsensusStuffedElement); - element.element_type = GNUNET_BLOCK_TYPE_CONSENSUS_ELEMENT; - - if (EVILNESS_SUB_REPLACEMENT == evil.subtype) { - /* Always generate a new element. */ - GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_WEAK, &se.rand); + GNUNET_SET_commit(setop->op, set->h); + break; } - else if (EVILNESS_SUB_NO_REPLACEMENT == evil.subtype) + if (EVILNESS_CRAM_ECHO == evil.type && (PHASE_KIND_GRADECAST_ECHO != task->key.kind)) { - /* Always cram the same elements, derived from counter. */ - GNUNET_CRYPTO_hash (&i, sizeof (i), &se.rand); + GNUNET_SET_commit(setop->op, set->h); + break; } - else + for (i = 0; i < evil.num; i++) { - GNUNET_assert (0); - } - GNUNET_SET_add_element (set->h, &element, NULL, NULL); + struct GNUNET_SET_Element element; + struct ConsensusStuffedElement se = { + .ce.payload_type = 0, + .ce.marker = 0, + }; + element.data = &se; + element.size = sizeof(struct ConsensusStuffedElement); + element.element_type = GNUNET_BLOCK_TYPE_CONSENSUS_ELEMENT; + + if (EVILNESS_SUB_REPLACEMENT == evil.subtype) + { + /* Always generate a new element. */ + GNUNET_CRYPTO_hash_create_random(GNUNET_CRYPTO_QUALITY_WEAK, &se.rand); + } + else if (EVILNESS_SUB_NO_REPLACEMENT == evil.subtype) + { + /* Always cram the same elements, derived from counter. */ + GNUNET_CRYPTO_hash(&i, sizeof(i), &se.rand); + } + else + { + GNUNET_assert(0); + } + GNUNET_SET_add_element(set->h, &element, NULL, NULL); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: evil peer: cramming element %s into set {%s} of task {%s}\n", - session->local_peer_idx, - debug_str_element (&element), - debug_str_set_key (&setop->input_set), - debug_str_task_key (&task->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: evil peer: cramming element %s into set {%s} of task {%s}\n", + session->local_peer_idx, + debug_str_element(&element), + debug_str_set_key(&setop->input_set), + debug_str_task_key(&task->key)); #endif - } - GNUNET_STATISTICS_update (statistics, - "# stuffed elements", - evil.num, - GNUNET_NO); - GNUNET_SET_commit (setop->op, set->h); + } + GNUNET_STATISTICS_update(statistics, + "# stuffed elements", + evil.num, + GNUNET_NO); + GNUNET_SET_commit(setop->op, set->h); break; + case EVILNESS_SLACK: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: evil peer: slacking\n", - (unsigned int) session->local_peer_idx); - /* Do nothing. */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: evil peer: slacking\n", + (unsigned int)session->local_peer_idx); + + /* Do nothing. */ case EVILNESS_SLACK_A2A: - if ( (PHASE_KIND_ALL_TO_ALL_2 == task->key.kind ) || - (PHASE_KIND_ALL_TO_ALL == task->key.kind) ) - { - struct GNUNET_SET_Handle *empty_set; - empty_set = GNUNET_SET_create (cfg, GNUNET_SET_OPERATION_UNION); - GNUNET_SET_commit (setop->op, empty_set); - GNUNET_SET_destroy (empty_set); - } + if ((PHASE_KIND_ALL_TO_ALL_2 == task->key.kind) || + (PHASE_KIND_ALL_TO_ALL == task->key.kind)) + { + struct GNUNET_SET_Handle *empty_set; + empty_set = GNUNET_SET_create(cfg, GNUNET_SET_OPERATION_UNION); + GNUNET_SET_commit(setop->op, empty_set); + GNUNET_SET_destroy(empty_set); + } else - { - GNUNET_SET_commit (setop->op, set->h); - } - break; + { + GNUNET_SET_commit(setop->op, set->h); + } + break; + case EVILNESS_NONE: - GNUNET_SET_commit (setop->op, set->h); + GNUNET_SET_commit(setop->op, set->h); break; - } + } } #else - if (GNUNET_NO == session->peers_blacklisted[task_other_peer (task)]) - { - GNUNET_SET_commit (setop->op, set->h); - } + if (GNUNET_NO == session->peers_blacklisted[task_other_peer(task)]) + { + GNUNET_SET_commit(setop->op, set->h); + } else - { - /* For our testcases, we don't want the blacklisted - peers to wait. */ - GNUNET_SET_operation_cancel (setop->op); - setop->op = NULL; - finish_task (task); - } + { + /* For our testcases, we don't want the blacklisted + peers to wait. */ + GNUNET_SET_operation_cancel(setop->op); + setop->op = NULL; + finish_task(task); + } #endif } static void -put_diff (struct ConsensusSession *session, +put_diff(struct ConsensusSession *session, struct DiffEntry *diff) { struct GNUNET_HashCode hash; - GNUNET_assert (NULL != diff); + GNUNET_assert(NULL != diff); - GNUNET_CRYPTO_hash (&diff->key, sizeof (struct DiffKey), &hash); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (session->diffmap, &hash, diff, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_CRYPTO_hash(&diff->key, sizeof(struct DiffKey), &hash); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(session->diffmap, &hash, diff, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); } static void -put_set (struct ConsensusSession *session, - struct SetEntry *set) +put_set(struct ConsensusSession *session, + struct SetEntry *set) { struct GNUNET_HashCode hash; - GNUNET_assert (NULL != set->h); + GNUNET_assert(NULL != set->h); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Putting set %s\n", - debug_str_set_key (&set->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Putting set %s\n", + debug_str_set_key(&set->key)); - GNUNET_CRYPTO_hash (&set->key, sizeof (struct SetKey), &hash); - GNUNET_assert (GNUNET_SYSERR != - GNUNET_CONTAINER_multihashmap_put (session->setmap, &hash, set, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE)); + GNUNET_CRYPTO_hash(&set->key, sizeof(struct SetKey), &hash); + GNUNET_assert(GNUNET_SYSERR != + GNUNET_CONTAINER_multihashmap_put(session->setmap, &hash, set, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE)); } static void -put_rfn (struct ConsensusSession *session, - struct ReferendumEntry *rfn) +put_rfn(struct ConsensusSession *session, + struct ReferendumEntry *rfn) { struct GNUNET_HashCode hash; - GNUNET_CRYPTO_hash (&rfn->key, sizeof (struct RfnKey), &hash); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (session->rfnmap, &hash, rfn, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_CRYPTO_hash(&rfn->key, sizeof(struct RfnKey), &hash); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(session->rfnmap, &hash, rfn, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); } static void -task_cancel_reconcile (struct TaskEntry *task) +task_cancel_reconcile(struct TaskEntry *task) { /* not implemented yet */ - GNUNET_assert (0); + GNUNET_assert(0); } static void -apply_diff_to_rfn (struct DiffEntry *diff, - struct ReferendumEntry *rfn, - uint16_t voting_peer, - uint16_t num_peers) +apply_diff_to_rfn(struct DiffEntry *diff, + struct ReferendumEntry *rfn, + uint16_t voting_peer, + uint16_t num_peers) { struct GNUNET_CONTAINER_MultiHashMapIterator *iter; struct DiffElementInfo *di; - iter = GNUNET_CONTAINER_multihashmap_iterator_create (diff->changes); + iter = GNUNET_CONTAINER_multihashmap_iterator_create(diff->changes); while (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_iterator_next (iter, - NULL, - (const void **) &di)) - { - if (di->weight > 0) + GNUNET_CONTAINER_multihashmap_iterator_next(iter, + NULL, + (const void **)&di)) { - rfn_vote (rfn, voting_peer, VOTE_ADD, di->element); - } - if (di->weight < 0) - { - rfn_vote (rfn, voting_peer, VOTE_REMOVE, di->element); + if (di->weight > 0) + { + rfn_vote(rfn, voting_peer, VOTE_ADD, di->element); + } + if (di->weight < 0) + { + rfn_vote(rfn, voting_peer, VOTE_REMOVE, di->element); + } } - } - GNUNET_CONTAINER_multihashmap_iterator_destroy (iter); + GNUNET_CONTAINER_multihashmap_iterator_destroy(iter); } struct DiffEntry * -diff_create () +diff_create() { - struct DiffEntry *d = GNUNET_new (struct DiffEntry); + struct DiffEntry *d = GNUNET_new(struct DiffEntry); - d->changes = GNUNET_CONTAINER_multihashmap_create (8, GNUNET_NO); + d->changes = GNUNET_CONTAINER_multihashmap_create(8, GNUNET_NO); return d; } struct DiffEntry * -diff_compose (struct DiffEntry *diff_1, - struct DiffEntry *diff_2) +diff_compose(struct DiffEntry *diff_1, + struct DiffEntry *diff_2) { struct DiffEntry *diff_new; struct GNUNET_CONTAINER_MultiHashMapIterator *iter; struct DiffElementInfo *di; - diff_new = diff_create (); + diff_new = diff_create(); - iter = GNUNET_CONTAINER_multihashmap_iterator_create (diff_1->changes); - while (GNUNET_YES == GNUNET_CONTAINER_multihashmap_iterator_next (iter, NULL, (const void **) &di)) - { - diff_insert (diff_new, di->weight, di->element); - } - GNUNET_CONTAINER_multihashmap_iterator_destroy (iter); + iter = GNUNET_CONTAINER_multihashmap_iterator_create(diff_1->changes); + while (GNUNET_YES == GNUNET_CONTAINER_multihashmap_iterator_next(iter, NULL, (const void **)&di)) + { + diff_insert(diff_new, di->weight, di->element); + } + GNUNET_CONTAINER_multihashmap_iterator_destroy(iter); - iter = GNUNET_CONTAINER_multihashmap_iterator_create (diff_2->changes); - while (GNUNET_YES == GNUNET_CONTAINER_multihashmap_iterator_next (iter, NULL, (const void **) &di)) - { - diff_insert (diff_new, di->weight, di->element); - } - GNUNET_CONTAINER_multihashmap_iterator_destroy (iter); + iter = GNUNET_CONTAINER_multihashmap_iterator_create(diff_2->changes); + while (GNUNET_YES == GNUNET_CONTAINER_multihashmap_iterator_next(iter, NULL, (const void **)&di)) + { + diff_insert(diff_new, di->weight, di->element); + } + GNUNET_CONTAINER_multihashmap_iterator_destroy(iter); return diff_new; } struct ReferendumEntry * -rfn_create (uint16_t size) +rfn_create(uint16_t size) { struct ReferendumEntry *rfn; - rfn = GNUNET_new (struct ReferendumEntry); - rfn->rfn_elements = GNUNET_CONTAINER_multihashmap_create (8, GNUNET_NO); - rfn->peer_commited = GNUNET_new_array (size, int); - rfn->peer_contested = GNUNET_new_array (size, int); + rfn = GNUNET_new(struct ReferendumEntry); + rfn->rfn_elements = GNUNET_CONTAINER_multihashmap_create(8, GNUNET_NO); + rfn->peer_commited = GNUNET_new_array(size, int); + rfn->peer_contested = GNUNET_new_array(size, int); rfn->num_peers = size; return rfn; @@ -1620,10 +1622,10 @@ rfn_create (uint16_t size) #if UNUSED static void -diff_destroy (struct DiffEntry *diff) +diff_destroy(struct DiffEntry *diff) { - GNUNET_CONTAINER_multihashmap_destroy (diff->changes); - GNUNET_free (diff); + GNUNET_CONTAINER_multihashmap_destroy(diff->changes); + GNUNET_free(diff); } #endif @@ -1634,71 +1636,70 @@ diff_destroy (struct DiffEntry *diff) * of peers that voted for this outcome. */ static void -rfn_majority (const struct ReferendumEntry *rfn, - const struct RfnElementInfo *ri, - uint16_t *ret_majority, - enum ReferendumVote *ret_vote) +rfn_majority(const struct ReferendumEntry *rfn, + const struct RfnElementInfo *ri, + uint16_t *ret_majority, + enum ReferendumVote *ret_vote) { uint16_t votes_yes = 0; uint16_t num_commited = 0; uint16_t i; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Computing rfn majority for element %s of rfn {%s}\n", - debug_str_element (ri->element), - debug_str_rfn_key (&rfn->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Computing rfn majority for element %s of rfn {%s}\n", + debug_str_element(ri->element), + debug_str_rfn_key(&rfn->key)); for (i = 0; i < rfn->num_peers; i++) - { - if (GNUNET_NO == rfn->peer_commited[i]) - continue; - num_commited++; + { + if (GNUNET_NO == rfn->peer_commited[i]) + continue; + num_commited++; - if (GNUNET_YES == ri->votes[i]) - votes_yes++; - } + if (GNUNET_YES == ri->votes[i]) + votes_yes++; + } if (votes_yes > (num_commited) / 2) - { - *ret_vote = ri->proposal; - *ret_majority = votes_yes; - } + { + *ret_vote = ri->proposal; + *ret_majority = votes_yes; + } else - { - *ret_vote = VOTE_STAY; - *ret_majority = num_commited - votes_yes; - } + { + *ret_vote = VOTE_STAY; + *ret_majority = num_commited - votes_yes; + } } -struct SetCopyCls -{ +struct SetCopyCls { struct TaskEntry *task; struct SetKey dst_set_key; }; static void -set_copy_cb (void *cls, struct GNUNET_SET_Handle *copy) +set_copy_cb(void *cls, struct GNUNET_SET_Handle *copy) { struct SetCopyCls *scc = cls; struct TaskEntry *task = scc->task; struct SetKey dst_set_key = scc->dst_set_key; struct SetEntry *set; - struct SetHandle *sh = GNUNET_new (struct SetHandle); + struct SetHandle *sh = GNUNET_new(struct SetHandle); sh->h = copy; - GNUNET_CONTAINER_DLL_insert (task->step->session->set_handles_head, - task->step->session->set_handles_tail, - sh); + GNUNET_CONTAINER_DLL_insert(task->step->session->set_handles_head, + task->step->session->set_handles_tail, + sh); - GNUNET_free (scc); - set = GNUNET_new (struct SetEntry); + GNUNET_free(scc); + set = GNUNET_new(struct SetEntry); set->h = copy; set->key = dst_set_key; - put_set (task->step->session, set); + put_set(task->step->session, set); - task->start (task); + task->start(task); } @@ -1707,31 +1708,30 @@ set_copy_cb (void *cls, struct GNUNET_SET_Handle *copy) * task again after we created a copy of the given set. */ static void -create_set_copy_for_task (struct TaskEntry *task, - struct SetKey *src_set_key, - struct SetKey *dst_set_key) +create_set_copy_for_task(struct TaskEntry *task, + struct SetKey *src_set_key, + struct SetKey *dst_set_key) { struct SetEntry *src_set; - struct SetCopyCls *scc = GNUNET_new (struct SetCopyCls); + struct SetCopyCls *scc = GNUNET_new(struct SetCopyCls); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Copying set {%s} to {%s} for task {%s}\n", - debug_str_set_key (src_set_key), - debug_str_set_key (dst_set_key), - debug_str_task_key (&task->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Copying set {%s} to {%s} for task {%s}\n", + debug_str_set_key(src_set_key), + debug_str_set_key(dst_set_key), + debug_str_task_key(&task->key)); scc->task = task; scc->dst_set_key = *dst_set_key; - src_set = lookup_set (task->step->session, src_set_key); - GNUNET_assert (NULL != src_set); - GNUNET_SET_copy_lazy (src_set->h, - set_copy_cb, - scc); + src_set = lookup_set(task->step->session, src_set_key); + GNUNET_assert(NULL != src_set); + GNUNET_SET_copy_lazy(src_set->h, + set_copy_cb, + scc); } -struct SetMutationProgressCls -{ +struct SetMutationProgressCls { int num_pending; /** * Task to finish once all changes are through. @@ -1741,25 +1741,25 @@ struct SetMutationProgressCls static void -set_mutation_done (void *cls) +set_mutation_done(void *cls) { struct SetMutationProgressCls *pc = cls; - GNUNET_assert (pc->num_pending > 0); + GNUNET_assert(pc->num_pending > 0); pc->num_pending--; if (0 == pc->num_pending) - { - struct TaskEntry *task = pc->task; - GNUNET_free (pc); - finish_task (task); - } + { + struct TaskEntry *task = pc->task; + GNUNET_free(pc); + finish_task(task); + } } static void -try_finish_step_early (struct Step *step) +try_finish_step_early(struct Step *step) { unsigned int i; @@ -1773,63 +1773,61 @@ try_finish_step_early (struct Step *step) step->is_finished = GNUNET_YES; #ifdef GNUNET_EXTRA_LOGGING - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finishing step `%s' early.\n", - step->debug_name); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finishing step `%s' early.\n", + step->debug_name); #endif for (i = 0; i < step->subordinates_len; i++) - { - GNUNET_assert (step->subordinates[i]->pending_prereq > 0); - step->subordinates[i]->pending_prereq--; + { + GNUNET_assert(step->subordinates[i]->pending_prereq > 0); + step->subordinates[i]->pending_prereq--; #ifdef GNUNET_EXTRA_LOGGING - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Decreased pending_prereq to %u for step `%s'.\n", - (unsigned int) step->subordinates[i]->pending_prereq, - step->subordinates[i]->debug_name); - + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Decreased pending_prereq to %u for step `%s'.\n", + (unsigned int)step->subordinates[i]->pending_prereq, + step->subordinates[i]->debug_name); #endif - try_finish_step_early (step->subordinates[i]); - } + try_finish_step_early(step->subordinates[i]); + } // XXX: maybe schedule as task to avoid recursion? - run_ready_steps (step->session); + run_ready_steps(step->session); } static void -finish_step (struct Step *step) +finish_step(struct Step *step) { unsigned int i; - GNUNET_assert (step->finished_tasks == step->tasks_len); - GNUNET_assert (GNUNET_YES == step->is_running); - GNUNET_assert (GNUNET_NO == step->is_finished); + GNUNET_assert(step->finished_tasks == step->tasks_len); + GNUNET_assert(GNUNET_YES == step->is_running); + GNUNET_assert(GNUNET_NO == step->is_finished); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "All tasks of step `%s' with %u subordinates finished.\n", - step->debug_name, - step->subordinates_len); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "All tasks of step `%s' with %u subordinates finished.\n", + step->debug_name, + step->subordinates_len); #endif for (i = 0; i < step->subordinates_len; i++) - { - GNUNET_assert (step->subordinates[i]->pending_prereq > 0); - step->subordinates[i]->pending_prereq--; + { + GNUNET_assert(step->subordinates[i]->pending_prereq > 0); + step->subordinates[i]->pending_prereq--; #ifdef GNUNET_EXTRA_LOGGING - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Decreased pending_prereq to %u for step `%s'.\n", - (unsigned int) step->subordinates[i]->pending_prereq, - step->subordinates[i]->debug_name); - + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Decreased pending_prereq to %u for step `%s'.\n", + (unsigned int)step->subordinates[i]->pending_prereq, + step->subordinates[i]->debug_name); #endif - } + } step->is_finished = GNUNET_YES; // XXX: maybe schedule as task to avoid recursion? - run_ready_steps (step->session); + run_ready_steps(step->session); } @@ -1841,7 +1839,7 @@ finish_step (struct Step *step) * @param task the task with context information */ static void -task_start_apply_round (struct TaskEntry *task) +task_start_apply_round(struct TaskEntry *task) { struct ConsensusSession *session = task->step->session; struct SetKey sk_in; @@ -1858,130 +1856,136 @@ task_start_apply_round (struct TaskEntry *task) rk_in = (struct RfnKey) { RFN_KIND_GRADECAST_RESULT, task->key.repetition }; sk_out = (struct SetKey) { SET_KIND_CURRENT, task->key.repetition + 1 }; - set_out = lookup_set (session, &sk_out); + set_out = lookup_set(session, &sk_out); if (NULL == set_out) - { - create_set_copy_for_task (task, &sk_in, &sk_out); - return; - } + { + create_set_copy_for_task(task, &sk_in, &sk_out); + return; + } - rfn_in = lookup_rfn (session, &rk_in); - GNUNET_assert (NULL != rfn_in); + rfn_in = lookup_rfn(session, &rk_in); + GNUNET_assert(NULL != rfn_in); - progress_cls = GNUNET_new (struct SetMutationProgressCls); + progress_cls = GNUNET_new(struct SetMutationProgressCls); progress_cls->task = task; - iter = GNUNET_CONTAINER_multihashmap_iterator_create (rfn_in->rfn_elements); + iter = GNUNET_CONTAINER_multihashmap_iterator_create(rfn_in->rfn_elements); while (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_iterator_next (iter, - NULL, - (const void **) &ri)) - { - uint16_t majority_num; - enum ReferendumVote majority_vote; + GNUNET_CONTAINER_multihashmap_iterator_next(iter, + NULL, + (const void **)&ri)) + { + uint16_t majority_num; + enum ReferendumVote majority_vote; - rfn_majority (rfn_in, ri, &majority_num, &majority_vote); + rfn_majority(rfn_in, ri, &majority_num, &majority_vote); - if (worst_majority > majority_num) - worst_majority = majority_num; + if (worst_majority > majority_num) + worst_majority = majority_num; - switch (majority_vote) - { - case VOTE_ADD: - progress_cls->num_pending++; - GNUNET_assert (GNUNET_OK == - GNUNET_SET_add_element (set_out->h, + switch (majority_vote) + { + case VOTE_ADD: + progress_cls->num_pending++; + GNUNET_assert(GNUNET_OK == + GNUNET_SET_add_element(set_out->h, ri->element, &set_mutation_done, progress_cls)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: apply round: adding element %s with %u-majority.\n", - session->local_peer_idx, - debug_str_element (ri->element), majority_num); - break; - case VOTE_REMOVE: - progress_cls->num_pending++; - GNUNET_assert (GNUNET_OK == - GNUNET_SET_remove_element (set_out->h, + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: apply round: adding element %s with %u-majority.\n", + session->local_peer_idx, + debug_str_element(ri->element), majority_num); + break; + + case VOTE_REMOVE: + progress_cls->num_pending++; + GNUNET_assert(GNUNET_OK == + GNUNET_SET_remove_element(set_out->h, ri->element, &set_mutation_done, progress_cls)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: apply round: deleting element %s with %u-majority.\n", - session->local_peer_idx, - debug_str_element (ri->element), majority_num); - break; - case VOTE_STAY: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: apply round: keeping element %s with %u-majority.\n", - session->local_peer_idx, - debug_str_element (ri->element), majority_num); - // do nothing - break; - default: - GNUNET_assert (0); - break; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: apply round: deleting element %s with %u-majority.\n", + session->local_peer_idx, + debug_str_element(ri->element), majority_num); + break; + + case VOTE_STAY: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: apply round: keeping element %s with %u-majority.\n", + session->local_peer_idx, + debug_str_element(ri->element), majority_num); + // do nothing + break; + + default: + GNUNET_assert(0); + break; + } } - } if (0 == progress_cls->num_pending) - { - // call closure right now, no pending ops - GNUNET_free (progress_cls); - finish_task (task); - } + { + // call closure right now, no pending ops + GNUNET_free(progress_cls); + finish_task(task); + } { uint16_t thresh = (session->num_peers / 3) * 2; if (worst_majority >= thresh) - { - switch (session->early_stopping) { - case EARLY_STOPPING_NONE: - session->early_stopping = EARLY_STOPPING_ONE_MORE; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "P%u: Stopping early (after one more superround)\n", - session->local_peer_idx); - break; - case EARLY_STOPPING_ONE_MORE: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: finishing steps due to early finish\n", - session->local_peer_idx); - session->early_stopping = EARLY_STOPPING_DONE; + switch (session->early_stopping) { - struct Step *step; - for (step = session->steps_head; NULL != step; step = step->next) - try_finish_step_early (step); + case EARLY_STOPPING_NONE: + session->early_stopping = EARLY_STOPPING_ONE_MORE; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "P%u: Stopping early (after one more superround)\n", + session->local_peer_idx); + break; + + case EARLY_STOPPING_ONE_MORE: + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "P%u: finishing steps due to early finish\n", + session->local_peer_idx); + session->early_stopping = EARLY_STOPPING_DONE; + { + struct Step *step; + for (step = session->steps_head; NULL != step; step = step->next) + try_finish_step_early(step); + } + break; + + case EARLY_STOPPING_DONE: + /* We shouldn't be here anymore after early stopping */ + GNUNET_break(0); + break; + + default: + GNUNET_assert(0); + break; } - break; - case EARLY_STOPPING_DONE: - /* We shouldn't be here anymore after early stopping */ - GNUNET_break (0); - break; - default: - GNUNET_assert (0); - break; } - } else if (EARLY_STOPPING_NONE != session->early_stopping) - { - // Our assumption about the number of bad peers - // has been broken. - GNUNET_break_op (0); - } + { + // Our assumption about the number of bad peers + // has been broken. + GNUNET_break_op(0); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: NOT finishing early (majority not good enough)\n", - session->local_peer_idx); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "P%u: NOT finishing early (majority not good enough)\n", + session->local_peer_idx); + } } - GNUNET_CONTAINER_multihashmap_iterator_destroy (iter); + GNUNET_CONTAINER_multihashmap_iterator_destroy(iter); } static void -task_start_grade (struct TaskEntry *task) +task_start_grade(struct TaskEntry *task) { struct ConsensusSession *session = task->step->session; struct ReferendumEntry *output_rfn; @@ -1994,90 +1998,93 @@ task_start_grade (struct TaskEntry *task) unsigned int gradecast_confidence = 2; rfn_key = (struct RfnKey) { RFN_KIND_GRADECAST_RESULT, task->key.repetition }; - output_rfn = lookup_rfn (session, &rfn_key); + output_rfn = lookup_rfn(session, &rfn_key); if (NULL == output_rfn) - { - output_rfn = rfn_create (session->num_peers); - output_rfn->key = rfn_key; - put_rfn (session, output_rfn); - } + { + output_rfn = rfn_create(session->num_peers); + output_rfn->key = rfn_key; + put_rfn(session, output_rfn); + } diff_key = (struct DiffKey) { DIFF_KIND_LEADER_PROPOSAL, task->key.repetition, task->key.leader }; - input_diff = lookup_diff (session, &diff_key); - GNUNET_assert (NULL != input_diff); + input_diff = lookup_diff(session, &diff_key); + GNUNET_assert(NULL != input_diff); rfn_key = (struct RfnKey) { RFN_KIND_ECHO, task->key.repetition, task->key.leader }; - input_rfn = lookup_rfn (session, &rfn_key); - GNUNET_assert (NULL != input_rfn); + input_rfn = lookup_rfn(session, &rfn_key); + GNUNET_assert(NULL != input_rfn); - iter = GNUNET_CONTAINER_multihashmap_iterator_create (input_rfn->rfn_elements); + iter = GNUNET_CONTAINER_multihashmap_iterator_create(input_rfn->rfn_elements); - apply_diff_to_rfn (input_diff, output_rfn, task->key.leader, session->num_peers); + apply_diff_to_rfn(input_diff, output_rfn, task->key.leader, session->num_peers); while (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_iterator_next (iter, - NULL, - (const void **) &ri)) - { - uint16_t majority_num; - enum ReferendumVote majority_vote; + GNUNET_CONTAINER_multihashmap_iterator_next(iter, + NULL, + (const void **)&ri)) + { + uint16_t majority_num; + enum ReferendumVote majority_vote; - // XXX: we need contested votes and non-contested votes here - rfn_majority (input_rfn, ri, &majority_num, &majority_vote); + // XXX: we need contested votes and non-contested votes here + rfn_majority(input_rfn, ri, &majority_num, &majority_vote); - if (majority_num <= session->num_peers / 3) - majority_vote = VOTE_REMOVE; + if (majority_num <= session->num_peers / 3) + majority_vote = VOTE_REMOVE; - switch (majority_vote) - { - case VOTE_STAY: - break; - case VOTE_ADD: - rfn_vote (output_rfn, task->key.leader, VOTE_ADD, ri->element); - break; - case VOTE_REMOVE: - rfn_vote (output_rfn, task->key.leader, VOTE_REMOVE, ri->element); - break; - default: - GNUNET_assert (0); - break; + switch (majority_vote) + { + case VOTE_STAY: + break; + + case VOTE_ADD: + rfn_vote(output_rfn, task->key.leader, VOTE_ADD, ri->element); + break; + + case VOTE_REMOVE: + rfn_vote(output_rfn, task->key.leader, VOTE_REMOVE, ri->element); + break; + + default: + GNUNET_assert(0); + break; + } } - } - GNUNET_CONTAINER_multihashmap_iterator_destroy (iter); + GNUNET_CONTAINER_multihashmap_iterator_destroy(iter); { uint16_t noncontested; - noncontested = rfn_noncontested (input_rfn); + noncontested = rfn_noncontested(input_rfn); if (noncontested < (session->num_peers / 3) * 2) - { - gradecast_confidence = GNUNET_MIN(1, gradecast_confidence); - } + { + gradecast_confidence = GNUNET_MIN(1, gradecast_confidence); + } if (noncontested < (session->num_peers / 3) + 1) - { - gradecast_confidence = 0; - } + { + gradecast_confidence = 0; + } } if (gradecast_confidence >= 1) - rfn_commit (output_rfn, task->key.leader); + rfn_commit(output_rfn, task->key.leader); if (gradecast_confidence <= 1) session->peers_blacklisted[task->key.leader] = GNUNET_YES; - finish_task (task); + finish_task(task); } static void -task_start_reconcile (struct TaskEntry *task) +task_start_reconcile(struct TaskEntry *task) { struct SetEntry *input; struct SetOpCls *setop = &task->cls.setop; struct ConsensusSession *session = task->step->session; - input = lookup_set (session, &setop->input_set); - GNUNET_assert (NULL != input); - GNUNET_assert (NULL != input->h); + input = lookup_set(session, &setop->input_set); + GNUNET_assert(NULL != input); + GNUNET_assert(NULL != input->h); /* We create the outputs for the operation here (rather than in the set operation callback) @@ -2085,113 +2092,113 @@ task_start_reconcile (struct TaskEntry *task) if the other peer doesn't talk to us */ if (SET_KIND_NONE != setop->output_set.set_kind) - { - /* If we don't have an existing output set, - we clone the input set. */ - if (NULL == lookup_set (session, &setop->output_set)) { - create_set_copy_for_task (task, &setop->input_set, &setop->output_set); - return; + /* If we don't have an existing output set, + we clone the input set. */ + if (NULL == lookup_set(session, &setop->output_set)) + { + create_set_copy_for_task(task, &setop->input_set, &setop->output_set); + return; + } } - } if (RFN_KIND_NONE != setop->output_rfn.rfn_kind) - { - if (NULL == lookup_rfn (session, &setop->output_rfn)) { - struct ReferendumEntry *rfn; + if (NULL == lookup_rfn(session, &setop->output_rfn)) + { + struct ReferendumEntry *rfn; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: output rfn <%s> missing, creating.\n", - session->local_peer_idx, - debug_str_rfn_key (&setop->output_rfn)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: output rfn <%s> missing, creating.\n", + session->local_peer_idx, + debug_str_rfn_key(&setop->output_rfn)); - rfn = rfn_create (session->num_peers); - rfn->key = setop->output_rfn; - put_rfn (session, rfn); + rfn = rfn_create(session->num_peers); + rfn->key = setop->output_rfn; + put_rfn(session, rfn); + } } - } if (DIFF_KIND_NONE != setop->output_diff.diff_kind) - { - if (NULL == lookup_diff (session, &setop->output_diff)) { - struct DiffEntry *diff; + if (NULL == lookup_diff(session, &setop->output_diff)) + { + struct DiffEntry *diff; - diff = diff_create (); - diff->key = setop->output_diff; - put_diff (session, diff); + diff = diff_create(); + diff->key = setop->output_diff; + put_diff(session, diff); + } } - } - if ( (task->key.peer1 == session->local_peer_idx) && (task->key.peer2 == session->local_peer_idx) ) - { - /* XXX: mark the corresponding rfn as commited if necessary */ - finish_task (task); - return; - } + if ((task->key.peer1 == session->local_peer_idx) && (task->key.peer2 == session->local_peer_idx)) + { + /* XXX: mark the corresponding rfn as commited if necessary */ + finish_task(task); + return; + } if (task->key.peer1 == session->local_peer_idx) - { - struct GNUNET_CONSENSUS_RoundContextMessage rcm; - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: Looking up set {%s} to run remote union\n", - session->local_peer_idx, - debug_str_set_key (&setop->input_set)); - - rcm.header.type = htons (GNUNET_MESSAGE_TYPE_CONSENSUS_P2P_ROUND_CONTEXT); - rcm.header.size = htons (sizeof (struct GNUNET_CONSENSUS_RoundContextMessage)); - - rcm.kind = htons (task->key.kind); - rcm.peer1 = htons (task->key.peer1); - rcm.peer2 = htons (task->key.peer2); - rcm.leader = htons (task->key.leader); - rcm.repetition = htons (task->key.repetition); - rcm.is_contested = htons (0); - - GNUNET_assert (NULL == setop->op); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: initiating set op with P%u, our set is %s\n", - session->local_peer_idx, task->key.peer2, debug_str_set_key (&setop->input_set)); - - struct GNUNET_SET_Option opts[] = { - { GNUNET_SET_OPTION_BYZANTINE, { .num = session->lower_bound } }, - { GNUNET_SET_OPTION_END }, - }; - - // XXX: maybe this should be done while - // setting up tasks alreays? - setop->op = GNUNET_SET_prepare (&session->peers[task->key.peer2], - &session->global_id, - &rcm.header, - GNUNET_SET_RESULT_SYMMETRIC, - opts, - set_result_cb, - task); - - commit_set (session, task); - } + { + struct GNUNET_CONSENSUS_RoundContextMessage rcm; + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: Looking up set {%s} to run remote union\n", + session->local_peer_idx, + debug_str_set_key(&setop->input_set)); + + rcm.header.type = htons(GNUNET_MESSAGE_TYPE_CONSENSUS_P2P_ROUND_CONTEXT); + rcm.header.size = htons(sizeof(struct GNUNET_CONSENSUS_RoundContextMessage)); + + rcm.kind = htons(task->key.kind); + rcm.peer1 = htons(task->key.peer1); + rcm.peer2 = htons(task->key.peer2); + rcm.leader = htons(task->key.leader); + rcm.repetition = htons(task->key.repetition); + rcm.is_contested = htons(0); + + GNUNET_assert(NULL == setop->op); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "P%u: initiating set op with P%u, our set is %s\n", + session->local_peer_idx, task->key.peer2, debug_str_set_key(&setop->input_set)); + + struct GNUNET_SET_Option opts[] = { + { GNUNET_SET_OPTION_BYZANTINE, { .num = session->lower_bound } }, + { GNUNET_SET_OPTION_END }, + }; + + // XXX: maybe this should be done while + // setting up tasks alreays? + setop->op = GNUNET_SET_prepare(&session->peers[task->key.peer2], + &session->global_id, + &rcm.header, + GNUNET_SET_RESULT_SYMMETRIC, + opts, + set_result_cb, + task); + + commit_set(session, task); + } else if (task->key.peer2 == session->local_peer_idx) - { - /* Wait for the other peer to contact us */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: waiting set op with P%u\n", - session->local_peer_idx, task->key.peer1); - - if (NULL != setop->op) { - commit_set (session, task); + /* Wait for the other peer to contact us */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "P%u: waiting set op with P%u\n", + session->local_peer_idx, task->key.peer1); + + if (NULL != setop->op) + { + commit_set(session, task); + } } - } else - { - /* We made an error while constructing the task graph. */ - GNUNET_assert (0); - } + { + /* We made an error while constructing the task graph. */ + GNUNET_assert(0); + } } static void -task_start_eval_echo (struct TaskEntry *task) +task_start_eval_echo(struct TaskEntry *task) { struct GNUNET_CONTAINER_MultiHashMapIterator *iter; struct ReferendumEntry *input_rfn; @@ -2205,123 +2212,126 @@ task_start_eval_echo (struct TaskEntry *task) sk_in = (struct SetKey) { SET_KIND_LEADER_PROPOSAL, task->key.repetition, task->key.leader }; sk_out = (struct SetKey) { SET_KIND_ECHO_RESULT, task->key.repetition, task->key.leader }; - output_set = lookup_set (session, &sk_out); + output_set = lookup_set(session, &sk_out); if (NULL == output_set) - { - create_set_copy_for_task (task, &sk_in, &sk_out); - return; - } + { + create_set_copy_for_task(task, &sk_in, &sk_out); + return; + } { // FIXME: should be marked as a shallow copy, so // we can destroy everything correctly - struct SetEntry *last_set = GNUNET_new (struct SetEntry); + struct SetEntry *last_set = GNUNET_new(struct SetEntry); last_set->h = output_set->h; last_set->key = (struct SetKey) { SET_KIND_LAST_GRADECAST }; - put_set (session, last_set); + put_set(session, last_set); } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Evaluating referendum in Task {%s}\n", - debug_str_task_key (&task->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Evaluating referendum in Task {%s}\n", + debug_str_task_key(&task->key)); - progress_cls = GNUNET_new (struct SetMutationProgressCls); + progress_cls = GNUNET_new(struct SetMutationProgressCls); progress_cls->task = task; rk_in = (struct RfnKey) { RFN_KIND_ECHO, task->key.repetition, task->key.leader }; - input_rfn = lookup_rfn (session, &rk_in); + input_rfn = lookup_rfn(session, &rk_in); - GNUNET_assert (NULL != input_rfn); + GNUNET_assert(NULL != input_rfn); - iter = GNUNET_CONTAINER_multihashmap_iterator_create (input_rfn->rfn_elements); - GNUNET_assert (NULL != iter); + iter = GNUNET_CONTAINER_multihashmap_iterator_create(input_rfn->rfn_elements); + GNUNET_assert(NULL != iter); while (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_iterator_next (iter, - NULL, - (const void **) &ri)) - { - enum ReferendumVote majority_vote; - uint16_t majority_num; + GNUNET_CONTAINER_multihashmap_iterator_next(iter, + NULL, + (const void **)&ri)) + { + enum ReferendumVote majority_vote; + uint16_t majority_num; - rfn_majority (input_rfn, ri, &majority_num, &majority_vote); + rfn_majority(input_rfn, ri, &majority_num, &majority_vote); - if (majority_num < session->num_peers / 3) - { - /* It is not the case that all nonfaulty peers - echoed the same value. Since we're doing a set reconciliation, we - can't simply send "nothing" for the value. Thus we mark our 'confirm' - reconciliation as contested. Other peers might not know that the - leader is faulty, thus we still re-distribute in the confirmation - round. */ - output_set->is_contested = GNUNET_YES; - } + if (majority_num < session->num_peers / 3) + { + /* It is not the case that all nonfaulty peers + echoed the same value. Since we're doing a set reconciliation, we + can't simply send "nothing" for the value. Thus we mark our 'confirm' + reconciliation as contested. Other peers might not know that the + leader is faulty, thus we still re-distribute in the confirmation + round. */ + output_set->is_contested = GNUNET_YES; + } - switch (majority_vote) - { - case VOTE_ADD: - progress_cls->num_pending++; - GNUNET_assert (GNUNET_OK == - GNUNET_SET_add_element (output_set->h, + switch (majority_vote) + { + case VOTE_ADD: + progress_cls->num_pending++; + GNUNET_assert(GNUNET_OK == + GNUNET_SET_add_element(output_set->h, ri->element, set_mutation_done, progress_cls)); - break; - case VOTE_REMOVE: - progress_cls->num_pending++; - GNUNET_assert (GNUNET_OK == - GNUNET_SET_remove_element (output_set->h, + break; + + case VOTE_REMOVE: + progress_cls->num_pending++; + GNUNET_assert(GNUNET_OK == + GNUNET_SET_remove_element(output_set->h, ri->element, set_mutation_done, progress_cls)); - break; - case VOTE_STAY: - /* Nothing to do. */ - break; - default: - /* not reached */ - GNUNET_assert (0); + break; + + case VOTE_STAY: + /* Nothing to do. */ + break; + + default: + /* not reached */ + GNUNET_assert(0); + } } - } - GNUNET_CONTAINER_multihashmap_iterator_destroy (iter); + GNUNET_CONTAINER_multihashmap_iterator_destroy(iter); if (0 == progress_cls->num_pending) - { - // call closure right now, no pending ops - GNUNET_free (progress_cls); - finish_task (task); - } + { + // call closure right now, no pending ops + GNUNET_free(progress_cls); + finish_task(task); + } } static void -task_start_finish (struct TaskEntry *task) +task_start_finish(struct TaskEntry *task) { struct SetEntry *final_set; struct ConsensusSession *session = task->step->session; - final_set = lookup_set (session, &task->cls.finish.input_set); + final_set = lookup_set(session, &task->cls.finish.input_set); - GNUNET_assert (NULL != final_set); + GNUNET_assert(NULL != final_set); - GNUNET_SET_iterate (final_set->h, - send_to_client_iter, - task); + GNUNET_SET_iterate(final_set->h, + send_to_client_iter, + task); } static void -start_task (struct ConsensusSession *session, struct TaskEntry *task) +start_task(struct ConsensusSession *session, struct TaskEntry *task) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: starting task {%s}\n", session->local_peer_idx, debug_str_task_key (&task->key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "P%u: starting task {%s}\n", session->local_peer_idx, debug_str_task_key(&task->key)); - GNUNET_assert (GNUNET_NO == task->is_started); - GNUNET_assert (GNUNET_NO == task->is_finished); - GNUNET_assert (NULL != task->start); + GNUNET_assert(GNUNET_NO == task->is_started); + GNUNET_assert(GNUNET_NO == task->is_finished); + GNUNET_assert(NULL != task->start); - task->start (task); + task->start(task); task->is_started = GNUNET_YES; } @@ -2334,40 +2344,40 @@ start_task (struct ConsensusSession *session, struct TaskEntry *task) * more dependencies. */ static void -run_ready_steps (struct ConsensusSession *session) +run_ready_steps(struct ConsensusSession *session) { struct Step *step; step = session->steps_head; while (NULL != step) - { - if ( (GNUNET_NO == step->is_running) && (0 == step->pending_prereq) && (GNUNET_NO == step->is_finished) ) { - size_t i; + if ((GNUNET_NO == step->is_running) && (0 == step->pending_prereq) && (GNUNET_NO == step->is_finished)) + { + size_t i; - GNUNET_assert (0 == step->finished_tasks); + GNUNET_assert(0 == step->finished_tasks); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Running step `%s' of round %d with %d tasks and %d subordinates\n", - session->local_peer_idx, - step->debug_name, - step->round, step->tasks_len, step->subordinates_len); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "P%u: Running step `%s' of round %d with %d tasks and %d subordinates\n", + session->local_peer_idx, + step->debug_name, + step->round, step->tasks_len, step->subordinates_len); #endif - step->is_running = GNUNET_YES; - for (i = 0; i < step->tasks_len; i++) - start_task (session, step->tasks[i]); + step->is_running = GNUNET_YES; + for (i = 0; i < step->tasks_len; i++) + start_task(session, step->tasks[i]); - /* Sometimes there is no task to trigger finishing the step, so we have to do it here. */ - if ( (step->finished_tasks == step->tasks_len) && (GNUNET_NO == step->is_finished)) - finish_step (step); + /* Sometimes there is no task to trigger finishing the step, so we have to do it here. */ + if ((step->finished_tasks == step->tasks_len) && (GNUNET_NO == step->is_finished)) + finish_step(step); - /* Running the next ready steps will be triggered by task completion */ - return; + /* Running the next ready steps will be triggered by task completion */ + return; + } + step = step->next; } - step = step->next; - } return; } @@ -2375,22 +2385,22 @@ run_ready_steps (struct ConsensusSession *session) static void -finish_task (struct TaskEntry *task) +finish_task(struct TaskEntry *task) { - GNUNET_assert (GNUNET_NO == task->is_finished); + GNUNET_assert(GNUNET_NO == task->is_finished); task->is_finished = GNUNET_YES; task->step->finished_tasks++; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "P%u: Finishing Task {%s} (now %u/%u tasks finished in step)\n", - task->step->session->local_peer_idx, - debug_str_task_key (&task->key), - (unsigned int) task->step->finished_tasks, - (unsigned int) task->step->tasks_len); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "P%u: Finishing Task {%s} (now %u/%u tasks finished in step)\n", + task->step->session->local_peer_idx, + debug_str_task_key(&task->key), + (unsigned int)task->step->finished_tasks, + (unsigned int)task->step->tasks_len); if (task->step->finished_tasks == task->step->tasks_len) - finish_step (task->step); + finish_step(task->step); } @@ -2402,11 +2412,12 @@ finish_task (struct TaskEntry *task) * @return index of peer, -1 if peer is not in session */ static int -get_peer_idx (const struct GNUNET_PeerIdentity *peer, const struct ConsensusSession *session) +get_peer_idx(const struct GNUNET_PeerIdentity *peer, const struct ConsensusSession *session) { int i; + for (i = 0; i < session->num_peers; i++) - if (0 == GNUNET_memcmp (peer, &session->peers[i])) + if (0 == GNUNET_memcmp(peer, &session->peers[i])) return i; return -1; } @@ -2422,21 +2433,21 @@ get_peer_idx (const struct GNUNET_PeerIdentity *peer, const struct ConsensusSess * @param local_session_id local id of the consensus session */ static void -compute_global_id (struct ConsensusSession *session, - const struct GNUNET_HashCode *local_session_id) +compute_global_id(struct ConsensusSession *session, + const struct GNUNET_HashCode *local_session_id) { const char *salt = "gnunet-service-consensus/session_id"; - GNUNET_assert (GNUNET_YES == - GNUNET_CRYPTO_kdf (&session->global_id, - sizeof (struct GNUNET_HashCode), - salt, - strlen (salt), - session->peers, - session->num_peers * sizeof (struct GNUNET_PeerIdentity), - local_session_id, - sizeof (struct GNUNET_HashCode), - NULL)); + GNUNET_assert(GNUNET_YES == + GNUNET_CRYPTO_kdf(&session->global_id, + sizeof(struct GNUNET_HashCode), + salt, + strlen(salt), + session->peers, + session->num_peers * sizeof(struct GNUNET_PeerIdentity), + local_session_id, + sizeof(struct GNUNET_HashCode), + NULL)); } @@ -2448,9 +2459,9 @@ compute_global_id (struct ConsensusSession *session, * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2. */ static int -peer_id_cmp (const void *h1, const void *h2) +peer_id_cmp(const void *h1, const void *h2) { - return memcmp (h1, h2, sizeof (struct GNUNET_PeerIdentity)); + return memcmp(h1, h2, sizeof(struct GNUNET_PeerIdentity)); } @@ -2462,56 +2473,56 @@ peer_id_cmp (const void *h1, const void *h2) * @param join_msg join message with the list of peers participating at the end */ static void -initialize_session_peer_list (struct ConsensusSession *session, - const struct GNUNET_CONSENSUS_JoinMessage *join_msg) +initialize_session_peer_list(struct ConsensusSession *session, + const struct GNUNET_CONSENSUS_JoinMessage *join_msg) { const struct GNUNET_PeerIdentity *msg_peers - = (const struct GNUNET_PeerIdentity *) &join_msg[1]; + = (const struct GNUNET_PeerIdentity *)&join_msg[1]; int local_peer_in_list; - session->num_peers = ntohl (join_msg->num_peers); + session->num_peers = ntohl(join_msg->num_peers); /* Peers in the join message, may or may not include the local peer, Add it if it is missing. */ local_peer_in_list = GNUNET_NO; for (unsigned int i = 0; i < session->num_peers; i++) - { - if (0 == GNUNET_memcmp (&msg_peers[i], - &my_peer)) { - local_peer_in_list = GNUNET_YES; - break; + if (0 == GNUNET_memcmp(&msg_peers[i], + &my_peer)) + { + local_peer_in_list = GNUNET_YES; + break; + } } - } if (GNUNET_NO == local_peer_in_list) session->num_peers++; - session->peers = GNUNET_new_array (session->num_peers, - struct GNUNET_PeerIdentity); + session->peers = GNUNET_new_array(session->num_peers, + struct GNUNET_PeerIdentity); if (GNUNET_NO == local_peer_in_list) session->peers[session->num_peers - 1] = my_peer; - GNUNET_memcpy (session->peers, - msg_peers, - ntohl (join_msg->num_peers) * sizeof (struct GNUNET_PeerIdentity)); - qsort (session->peers, - session->num_peers, - sizeof (struct GNUNET_PeerIdentity), - &peer_id_cmp); + GNUNET_memcpy(session->peers, + msg_peers, + ntohl(join_msg->num_peers) * sizeof(struct GNUNET_PeerIdentity)); + qsort(session->peers, + session->num_peers, + sizeof(struct GNUNET_PeerIdentity), + &peer_id_cmp); } static struct TaskEntry * -lookup_task (struct ConsensusSession *session, - struct TaskKey *key) +lookup_task(struct ConsensusSession *session, + struct TaskKey *key) { struct GNUNET_HashCode hash; - GNUNET_CRYPTO_hash (key, sizeof (struct TaskKey), &hash); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Looking up task hash %s\n", - GNUNET_h2s (&hash)); - return GNUNET_CONTAINER_multihashmap_get (session->taskmap, &hash); + GNUNET_CRYPTO_hash(key, sizeof(struct TaskKey), &hash); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Looking up task hash %s\n", + GNUNET_h2s(&hash)); + return GNUNET_CONTAINER_multihashmap_get(session->taskmap, &hash); } @@ -2531,10 +2542,10 @@ lookup_task (struct ConsensusSession *session, * Also necessary to specify the timeout. */ static void -set_listen_cb (void *cls, - const struct GNUNET_PeerIdentity *other_peer, - const struct GNUNET_MessageHeader *context_msg, - struct GNUNET_SET_Request *request) +set_listen_cb(void *cls, + const struct GNUNET_PeerIdentity *other_peer, + const struct GNUNET_MessageHeader *context_msg, + struct GNUNET_SET_Request *request) { struct ConsensusSession *session = cls; struct TaskKey tk; @@ -2542,122 +2553,122 @@ set_listen_cb (void *cls, struct GNUNET_CONSENSUS_RoundContextMessage *cm; if (NULL == context_msg) - { - GNUNET_break_op (0); - return; - } + { + GNUNET_break_op(0); + return; + } - if (GNUNET_MESSAGE_TYPE_CONSENSUS_P2P_ROUND_CONTEXT != ntohs (context_msg->type)) - { - GNUNET_break_op (0); - return; - } + if (GNUNET_MESSAGE_TYPE_CONSENSUS_P2P_ROUND_CONTEXT != ntohs(context_msg->type)) + { + GNUNET_break_op(0); + return; + } - if (sizeof (struct GNUNET_CONSENSUS_RoundContextMessage) != ntohs (context_msg->size)) - { - GNUNET_break_op (0); - return; - } + if (sizeof(struct GNUNET_CONSENSUS_RoundContextMessage) != ntohs(context_msg->size)) + { + GNUNET_break_op(0); + return; + } - cm = (struct GNUNET_CONSENSUS_RoundContextMessage *) context_msg; + cm = (struct GNUNET_CONSENSUS_RoundContextMessage *)context_msg; tk = ((struct TaskKey) { - .kind = ntohs (cm->kind), - .peer1 = ntohs (cm->peer1), - .peer2 = ntohs (cm->peer2), - .repetition = ntohs (cm->repetition), - .leader = ntohs (cm->leader), + .kind = ntohs(cm->kind), + .peer1 = ntohs(cm->peer1), + .peer2 = ntohs(cm->peer2), + .repetition = ntohs(cm->repetition), + .leader = ntohs(cm->leader), }); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: got req for task %s\n", - session->local_peer_idx, debug_str_task_key (&tk)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "P%u: got req for task %s\n", + session->local_peer_idx, debug_str_task_key(&tk)); - task = lookup_task (session, &tk); + task = lookup_task(session, &tk); if (NULL == task) - { - GNUNET_break_op (0); - return; - } + { + GNUNET_break_op(0); + return; + } if (GNUNET_YES == task->is_finished) - { - GNUNET_break_op (0); - return; - } + { + GNUNET_break_op(0); + return; + } if (task->key.peer2 != session->local_peer_idx) - { - /* We're being asked, so we must be thne 2nd peer. */ - GNUNET_break_op (0); - return; - } + { + /* We're being asked, so we must be thne 2nd peer. */ + GNUNET_break_op(0); + return; + } - GNUNET_assert (! ((task->key.peer1 == session->local_peer_idx) && - (task->key.peer2 == session->local_peer_idx))); + GNUNET_assert(!((task->key.peer1 == session->local_peer_idx) && + (task->key.peer2 == session->local_peer_idx))); struct GNUNET_SET_Option opts[] = { { GNUNET_SET_OPTION_BYZANTINE, { .num = session->lower_bound } }, { GNUNET_SET_OPTION_END }, }; - task->cls.setop.op = GNUNET_SET_accept (request, - GNUNET_SET_RESULT_SYMMETRIC, - opts, - set_result_cb, - task); + task->cls.setop.op = GNUNET_SET_accept(request, + GNUNET_SET_RESULT_SYMMETRIC, + opts, + set_result_cb, + task); /* If the task hasn't been started yet, we wait for that until we commit. */ if (GNUNET_YES == task->is_started) - { - commit_set (session, task); - } + { + commit_set(session, task); + } } static void -put_task (struct GNUNET_CONTAINER_MultiHashMap *taskmap, - struct TaskEntry *t) +put_task(struct GNUNET_CONTAINER_MultiHashMap *taskmap, + struct TaskEntry *t) { struct GNUNET_HashCode round_hash; struct Step *s; - GNUNET_assert (NULL != t->step); + GNUNET_assert(NULL != t->step); - t = GNUNET_memdup (t, sizeof (struct TaskEntry)); + t = GNUNET_memdup(t, sizeof(struct TaskEntry)); s = t->step; if (s->tasks_len == s->tasks_cap) - { - unsigned int target_size = 3 * (s->tasks_cap + 1) / 2; - GNUNET_array_grow (s->tasks, - s->tasks_cap, - target_size); - } + { + unsigned int target_size = 3 * (s->tasks_cap + 1) / 2; + GNUNET_array_grow(s->tasks, + s->tasks_cap, + target_size); + } #ifdef GNUNET_EXTRA_LOGGING - GNUNET_assert (NULL != s->debug_name); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Putting task <%s> into step `%s'\n", - debug_str_task_key (&t->key), - s->debug_name); + GNUNET_assert(NULL != s->debug_name); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Putting task <%s> into step `%s'\n", + debug_str_task_key(&t->key), + s->debug_name); #endif s->tasks[s->tasks_len] = t; s->tasks_len++; - GNUNET_CRYPTO_hash (&t->key, sizeof (struct TaskKey), &round_hash); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (taskmap, &round_hash, t, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_CRYPTO_hash(&t->key, sizeof(struct TaskKey), &round_hash); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(taskmap, &round_hash, t, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); } static void -install_step_timeouts (struct ConsensusSession *session) +install_step_timeouts(struct ConsensusSession *session) { /* Given the fully constructed task graph with rounds for tasks, we can give the tasks timeouts. */ @@ -2673,37 +2684,37 @@ install_step_timeouts (struct ConsensusSession *session) * Arrange two peers in some canonical order. */ static void -arrange_peers (uint16_t *p1, uint16_t *p2, uint16_t n) +arrange_peers(uint16_t *p1, uint16_t *p2, uint16_t n) { uint16_t a; uint16_t b; - GNUNET_assert (*p1 < n); - GNUNET_assert (*p2 < n); + GNUNET_assert(*p1 < n); + GNUNET_assert(*p2 < n); if (*p1 < *p2) - { - a = *p1; - b = *p2; - } + { + a = *p1; + b = *p2; + } else - { - a = *p2; - b = *p1; - } + { + a = *p2; + b = *p1; + } /* For uniformly random *p1, *p2, this condition is true with 50% chance */ if (((b - a) + n) % n <= n / 2) - { - *p1 = a; - *p2 = b; - } + { + *p1 = a; + *p2 = b; + } else - { - *p1 = b; - *p2 = a; - } + { + *p1 = b; + *p2 = a; + } } @@ -2711,36 +2722,36 @@ arrange_peers (uint16_t *p1, uint16_t *p2, uint16_t n) * Record @a dep as a dependency of @a step. */ static void -step_depend_on (struct Step *step, struct Step *dep) +step_depend_on(struct Step *step, struct Step *dep) { /* We're not checking for cyclic dependencies, but this is a cheap sanity check. */ - GNUNET_assert (step != dep); - GNUNET_assert (NULL != step); - GNUNET_assert (NULL != dep); - GNUNET_assert (dep->round <= step->round); + GNUNET_assert(step != dep); + GNUNET_assert(NULL != step); + GNUNET_assert(NULL != dep); + GNUNET_assert(dep->round <= step->round); #ifdef GNUNET_EXTRA_LOGGING /* Make sure we have complete debugging information. Also checks that we don't screw up too badly constructing the task graph. */ - GNUNET_assert (NULL != step->debug_name); - GNUNET_assert (NULL != dep->debug_name); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Making step `%s' depend on `%s'\n", - step->debug_name, - dep->debug_name); + GNUNET_assert(NULL != step->debug_name); + GNUNET_assert(NULL != dep->debug_name); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Making step `%s' depend on `%s'\n", + step->debug_name, + dep->debug_name); #endif if (dep->subordinates_cap == dep->subordinates_len) - { - unsigned int target_size = 3 * (dep->subordinates_cap + 1) / 2; - GNUNET_array_grow (dep->subordinates, - dep->subordinates_cap, - target_size); - } + { + unsigned int target_size = 3 * (dep->subordinates_cap + 1) / 2; + GNUNET_array_grow(dep->subordinates, + dep->subordinates_cap, + target_size); + } - GNUNET_assert (dep->subordinates_len <= dep->subordinates_cap); + GNUNET_assert(dep->subordinates_len <= dep->subordinates_cap); dep->subordinates[dep->subordinates_len] = step; dep->subordinates_len++; @@ -2750,16 +2761,17 @@ step_depend_on (struct Step *step, struct Step *dep) static struct Step * -create_step (struct ConsensusSession *session, int round, int early_finishable) +create_step(struct ConsensusSession *session, int round, int early_finishable) { struct Step *step; - step = GNUNET_new (struct Step); + + step = GNUNET_new(struct Step); step->session = session; step->round = round; step->early_finishable = early_finishable; - GNUNET_CONTAINER_DLL_insert_tail (session->steps_head, - session->steps_tail, - step); + GNUNET_CONTAINER_DLL_insert_tail(session->steps_head, + session->steps_tail, + step); return step; } @@ -2769,11 +2781,11 @@ create_step (struct ConsensusSession *session, int round, int early_finishable) * gradecast. */ static void -construct_task_graph_gradecast (struct ConsensusSession *session, - uint16_t rep, - uint16_t lead, - struct Step *step_before, - struct Step *step_after) +construct_task_graph_gradecast(struct ConsensusSession *session, + uint16_t rep, + uint16_t lead, + struct Step *step_before, + struct Step *step_after) { uint16_t n = session->num_peers; uint16_t me = session->local_peer_idx; @@ -2795,155 +2807,155 @@ construct_task_graph_gradecast (struct ConsensusSession *session, /* gcast step 1: leader disseminates */ - step = create_step (session, round, GNUNET_YES); + step = create_step(session, round, GNUNET_YES); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_asprintf (&step->debug_name, "disseminate leader %u rep %u", lead, rep); + GNUNET_asprintf(&step->debug_name, "disseminate leader %u rep %u", lead, rep); #endif - step_depend_on (step, step_before); + step_depend_on(step, step_before); if (lead == me) - { - for (k = 0; k < n; k++) { - if (k == me) - continue; - p1 = me; - p2 = k; - arrange_peers (&p1, &p2, n); - task = ((struct TaskEntry) { + for (k = 0; k < n; k++) + { + if (k == me) + continue; + p1 = me; + p2 = k; + arrange_peers(&p1, &p2, n); + task = ((struct TaskEntry) { .step = step, .start = task_start_reconcile, .cancel = task_cancel_reconcile, .key = (struct TaskKey) { PHASE_KIND_GRADECAST_LEADER, p1, p2, rep, me }, }); - task.cls.setop.input_set = (struct SetKey) { SET_KIND_CURRENT, rep }; - put_task (session->taskmap, &task); - } - /* We run this task to make sure that the leader - has the stored the SET_KIND_LEADER set of himself, - so it can participate in the rest of the gradecast - without the code having to handle any special cases. */ - task = ((struct TaskEntry) { + task.cls.setop.input_set = (struct SetKey) { SET_KIND_CURRENT, rep }; + put_task(session->taskmap, &task); + } + /* We run this task to make sure that the leader + has the stored the SET_KIND_LEADER set of himself, + so it can participate in the rest of the gradecast + without the code having to handle any special cases. */ + task = ((struct TaskEntry) { .step = step, .key = (struct TaskKey) { PHASE_KIND_GRADECAST_LEADER, me, me, rep, me }, .start = task_start_reconcile, .cancel = task_cancel_reconcile, }); - task.cls.setop.input_set = (struct SetKey) { SET_KIND_CURRENT, rep }; - task.cls.setop.output_set = (struct SetKey) { SET_KIND_LEADER_PROPOSAL, rep, me }; - task.cls.setop.output_diff = (struct DiffKey) { DIFF_KIND_LEADER_PROPOSAL, rep, me }; - put_task (session->taskmap, &task); - } + task.cls.setop.input_set = (struct SetKey) { SET_KIND_CURRENT, rep }; + task.cls.setop.output_set = (struct SetKey) { SET_KIND_LEADER_PROPOSAL, rep, me }; + task.cls.setop.output_diff = (struct DiffKey) { DIFF_KIND_LEADER_PROPOSAL, rep, me }; + put_task(session->taskmap, &task); + } else - { - p1 = me; - p2 = lead; - arrange_peers (&p1, &p2, n); - task = ((struct TaskEntry) { + { + p1 = me; + p2 = lead; + arrange_peers(&p1, &p2, n); + task = ((struct TaskEntry) { .step = step, .key = (struct TaskKey) { PHASE_KIND_GRADECAST_LEADER, p1, p2, rep, lead }, .start = task_start_reconcile, .cancel = task_cancel_reconcile, }); - task.cls.setop.input_set = (struct SetKey) { SET_KIND_CURRENT, rep }; - task.cls.setop.output_set = (struct SetKey) { SET_KIND_LEADER_PROPOSAL, rep, lead }; - task.cls.setop.output_diff = (struct DiffKey) { DIFF_KIND_LEADER_PROPOSAL, rep, lead }; - put_task (session->taskmap, &task); - } + task.cls.setop.input_set = (struct SetKey) { SET_KIND_CURRENT, rep }; + task.cls.setop.output_set = (struct SetKey) { SET_KIND_LEADER_PROPOSAL, rep, lead }; + task.cls.setop.output_diff = (struct DiffKey) { DIFF_KIND_LEADER_PROPOSAL, rep, lead }; + put_task(session->taskmap, &task); + } /* gcast phase 2: echo */ prev_step = step; round += 1; - step = create_step (session, round, GNUNET_YES); + step = create_step(session, round, GNUNET_YES); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_asprintf (&step->debug_name, "echo leader %u rep %u", lead, rep); + GNUNET_asprintf(&step->debug_name, "echo leader %u rep %u", lead, rep); #endif - step_depend_on (step, prev_step); + step_depend_on(step, prev_step); for (k = 0; k < n; k++) - { - p1 = k; - p2 = me; - arrange_peers (&p1, &p2, n); - task = ((struct TaskEntry) { + { + p1 = k; + p2 = me; + arrange_peers(&p1, &p2, n); + task = ((struct TaskEntry) { .step = step, .key = (struct TaskKey) { PHASE_KIND_GRADECAST_ECHO, p1, p2, rep, lead }, .start = task_start_reconcile, .cancel = task_cancel_reconcile, }); - task.cls.setop.input_set = (struct SetKey) { SET_KIND_LEADER_PROPOSAL, rep, lead }; - task.cls.setop.output_rfn = (struct RfnKey) { RFN_KIND_ECHO, rep, lead }; - put_task (session->taskmap, &task); - } + task.cls.setop.input_set = (struct SetKey) { SET_KIND_LEADER_PROPOSAL, rep, lead }; + task.cls.setop.output_rfn = (struct RfnKey) { RFN_KIND_ECHO, rep, lead }; + put_task(session->taskmap, &task); + } prev_step = step; /* Same round, since step only has local tasks */ - step = create_step (session, round, GNUNET_YES); + step = create_step(session, round, GNUNET_YES); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_asprintf (&step->debug_name, "echo grade leader %u rep %u", lead, rep); + GNUNET_asprintf(&step->debug_name, "echo grade leader %u rep %u", lead, rep); #endif - step_depend_on (step, prev_step); + step_depend_on(step, prev_step); - arrange_peers (&p1, &p2, n); + arrange_peers(&p1, &p2, n); task = ((struct TaskEntry) { .key = (struct TaskKey) { PHASE_KIND_GRADECAST_ECHO_GRADE, -1, -1, rep, lead }, .step = step, .start = task_start_eval_echo }); - put_task (session->taskmap, &task); + put_task(session->taskmap, &task); prev_step = step; round += 1; - step = create_step (session, round, GNUNET_YES); + step = create_step(session, round, GNUNET_YES); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_asprintf (&step->debug_name, "confirm leader %u rep %u", lead, rep); + GNUNET_asprintf(&step->debug_name, "confirm leader %u rep %u", lead, rep); #endif - step_depend_on (step, prev_step); + step_depend_on(step, prev_step); /* gcast phase 3: confirmation and grading */ for (k = 0; k < n; k++) - { - p1 = k; - p2 = me; - arrange_peers (&p1, &p2, n); - task = ((struct TaskEntry) { + { + p1 = k; + p2 = me; + arrange_peers(&p1, &p2, n); + task = ((struct TaskEntry) { .step = step, .start = task_start_reconcile, .cancel = task_cancel_reconcile, - .key = (struct TaskKey) { PHASE_KIND_GRADECAST_CONFIRM, p1, p2, rep, lead}, + .key = (struct TaskKey) { PHASE_KIND_GRADECAST_CONFIRM, p1, p2, rep, lead }, }); - task.cls.setop.input_set = (struct SetKey) { SET_KIND_ECHO_RESULT, rep, lead }; - task.cls.setop.output_rfn = (struct RfnKey) { RFN_KIND_CONFIRM, rep, lead }; - /* If there was at least one element in the echo round that was - contested (i.e. it had no n-t majority), then we let the other peers - know, and other peers let us know. The contested flag for each peer is - stored in the rfn. */ - task.cls.setop.transceive_contested = GNUNET_YES; - put_task (session->taskmap, &task); - } + task.cls.setop.input_set = (struct SetKey) { SET_KIND_ECHO_RESULT, rep, lead }; + task.cls.setop.output_rfn = (struct RfnKey) { RFN_KIND_CONFIRM, rep, lead }; + /* If there was at least one element in the echo round that was + contested (i.e. it had no n-t majority), then we let the other peers + know, and other peers let us know. The contested flag for each peer is + stored in the rfn. */ + task.cls.setop.transceive_contested = GNUNET_YES; + put_task(session->taskmap, &task); + } prev_step = step; /* Same round, since step only has local tasks */ - step = create_step (session, round, GNUNET_YES); + step = create_step(session, round, GNUNET_YES); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_asprintf (&step->debug_name, "confirm grade leader %u rep %u", lead, rep); + GNUNET_asprintf(&step->debug_name, "confirm grade leader %u rep %u", lead, rep); #endif - step_depend_on (step, prev_step); + step_depend_on(step, prev_step); task = ((struct TaskEntry) { .step = step, .key = (struct TaskKey) { PHASE_KIND_GRADECAST_CONFIRM_GRADE, -1, -1, rep, lead }, .start = task_start_grade, }); - put_task (session->taskmap, &task); + put_task(session->taskmap, &task); - step_depend_on (step_after, step); + step_depend_on(step_after, step); } static void -construct_task_graph (struct ConsensusSession *session) +construct_task_graph(struct ConsensusSession *session) { uint16_t n = session->num_peers; uint16_t t = n / 3; @@ -2973,60 +2985,60 @@ construct_task_graph (struct ConsensusSession *session) /* all-to-all step */ - step = create_step (session, round, GNUNET_NO); + step = create_step(session, round, GNUNET_NO); #ifdef GNUNET_EXTRA_LOGGING - step->debug_name = GNUNET_strdup ("all to all"); + step->debug_name = GNUNET_strdup("all to all"); #endif for (i = 0; i < n; i++) - { - uint16_t p1; - uint16_t p2; + { + uint16_t p1; + uint16_t p2; - p1 = me; - p2 = i; - arrange_peers (&p1, &p2, n); - task = ((struct TaskEntry) { + p1 = me; + p2 = i; + arrange_peers(&p1, &p2, n); + task = ((struct TaskEntry) { .key = (struct TaskKey) { PHASE_KIND_ALL_TO_ALL, p1, p2, -1, -1 }, .step = step, .start = task_start_reconcile, .cancel = task_cancel_reconcile, }); - task.cls.setop.input_set = (struct SetKey) { SET_KIND_CURRENT, 0 }; - task.cls.setop.output_set = task.cls.setop.input_set; - task.cls.setop.do_not_remove = GNUNET_YES; - put_task (session->taskmap, &task); - } + task.cls.setop.input_set = (struct SetKey) { SET_KIND_CURRENT, 0 }; + task.cls.setop.output_set = task.cls.setop.input_set; + task.cls.setop.do_not_remove = GNUNET_YES; + put_task(session->taskmap, &task); + } round += 1; prev_step = step; - step = create_step (session, round, GNUNET_NO);; + step = create_step(session, round, GNUNET_NO);; #ifdef GNUNET_EXTRA_LOGGING - step->debug_name = GNUNET_strdup ("all to all 2"); + step->debug_name = GNUNET_strdup("all to all 2"); #endif - step_depend_on (step, prev_step); + step_depend_on(step, prev_step); for (i = 0; i < n; i++) - { - uint16_t p1; - uint16_t p2; + { + uint16_t p1; + uint16_t p2; - p1 = me; - p2 = i; - arrange_peers (&p1, &p2, n); - task = ((struct TaskEntry) { + p1 = me; + p2 = i; + arrange_peers(&p1, &p2, n); + task = ((struct TaskEntry) { .key = (struct TaskKey) { PHASE_KIND_ALL_TO_ALL_2, p1, p2, -1, -1 }, .step = step, .start = task_start_reconcile, .cancel = task_cancel_reconcile, }); - task.cls.setop.input_set = (struct SetKey) { SET_KIND_CURRENT, 0 }; - task.cls.setop.output_set = task.cls.setop.input_set; - task.cls.setop.do_not_remove = GNUNET_YES; - put_task (session->taskmap, &task); - } + task.cls.setop.input_set = (struct SetKey) { SET_KIND_CURRENT, 0 }; + task.cls.setop.output_set = task.cls.setop.input_set; + task.cls.setop.do_not_remove = GNUNET_YES; + put_task(session->taskmap, &task); + } round += 1; @@ -3039,47 +3051,47 @@ construct_task_graph (struct ConsensusSession *session) /* sequential repetitions of the gradecasts */ for (i = 0; i < t + 1; i++) - { - struct Step *step_rep_start; - struct Step *step_rep_end; + { + struct Step *step_rep_start; + struct Step *step_rep_end; - /* Every repetition is in a separate round. */ - step_rep_start = create_step (session, round, GNUNET_YES); + /* Every repetition is in a separate round. */ + step_rep_start = create_step(session, round, GNUNET_YES); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_asprintf (&step_rep_start->debug_name, "gradecast start rep %u", i); + GNUNET_asprintf(&step_rep_start->debug_name, "gradecast start rep %u", i); #endif - step_depend_on (step_rep_start, prev_step); + step_depend_on(step_rep_start, prev_step); - /* gradecast has three rounds */ - round += 3; - step_rep_end = create_step (session, round, GNUNET_YES); + /* gradecast has three rounds */ + round += 3; + step_rep_end = create_step(session, round, GNUNET_YES); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_asprintf (&step_rep_end->debug_name, "gradecast end rep %u", i); + GNUNET_asprintf(&step_rep_end->debug_name, "gradecast end rep %u", i); #endif - /* parallel gradecasts */ - for (lead = 0; lead < n; lead++) - construct_task_graph_gradecast (session, i, lead, step_rep_start, step_rep_end); + /* parallel gradecasts */ + for (lead = 0; lead < n; lead++) + construct_task_graph_gradecast(session, i, lead, step_rep_start, step_rep_end); - task = ((struct TaskEntry) { + task = ((struct TaskEntry) { .step = step_rep_end, - .key = (struct TaskKey) { PHASE_KIND_APPLY_REP, -1, -1, i, -1}, + .key = (struct TaskKey) { PHASE_KIND_APPLY_REP, -1, -1, i, -1 }, .start = task_start_apply_round, }); - put_task (session->taskmap, &task); + put_task(session->taskmap, &task); - prev_step = step_rep_end; - } + prev_step = step_rep_end; + } - /* There is no next gradecast round, thus the final - start step is the overall end step of the gradecasts */ + /* There is no next gradecast round, thus the final + start step is the overall end step of the gradecasts */ round += 1; - step = create_step (session, round, GNUNET_NO); + step = create_step(session, round, GNUNET_NO); #ifdef GNUNET_EXTRA_LOGGING - GNUNET_asprintf (&step->debug_name, "finish"); + GNUNET_asprintf(&step->debug_name, "finish"); #endif - step_depend_on (step, prev_step); + step_depend_on(step, prev_step); task = ((struct TaskEntry) { .step = step, @@ -3088,7 +3100,7 @@ construct_task_graph (struct ConsensusSession *session) }); task.cls.finish.input_set = (struct SetKey) { SET_KIND_LAST_GRADECAST }; - put_task (session->taskmap, &task); + put_task(session->taskmap, &task); } @@ -3101,17 +3113,17 @@ construct_task_graph (struct ConsensusSession *session) * @return #GNUNET_OK if @a m is well-formed */ static int -check_client_join (void *cls, - const struct GNUNET_CONSENSUS_JoinMessage *m) +check_client_join(void *cls, + const struct GNUNET_CONSENSUS_JoinMessage *m) { - uint32_t listed_peers = ntohl (m->num_peers); + uint32_t listed_peers = ntohl(m->num_peers); - if ( (ntohs (m->header.size) - sizeof (*m)) != - listed_peers * sizeof (struct GNUNET_PeerIdentity)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + if ((ntohs(m->header.size) - sizeof(*m)) != + listed_peers * sizeof(struct GNUNET_PeerIdentity)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -3123,16 +3135,16 @@ check_client_join (void *cls, * @param m message sent by the client */ static void -handle_client_join (void *cls, - const struct GNUNET_CONSENSUS_JoinMessage *m) +handle_client_join(void *cls, + const struct GNUNET_CONSENSUS_JoinMessage *m) { struct ConsensusSession *session = cls; struct ConsensusSession *other_session; - initialize_session_peer_list (session, - m); - compute_global_id (session, - &m->session_id); + initialize_session_peer_list(session, + m); + compute_global_id(session, + &m->session_id); /* Check if some local client already owns the session. It is only legal to have a session with an existing global id @@ -3140,75 +3152,75 @@ handle_client_join (void *cls, for (other_session = sessions_head; NULL != other_session; other_session = other_session->next) - { - if ( (other_session != session) && - (0 == GNUNET_CRYPTO_hash_cmp (&session->global_id, - &other_session->global_id)) ) - break; - } + { + if ((other_session != session) && + (0 == GNUNET_CRYPTO_hash_cmp(&session->global_id, + &other_session->global_id))) + break; + } session->conclude_deadline - = GNUNET_TIME_absolute_ntoh (m->deadline); + = GNUNET_TIME_absolute_ntoh(m->deadline); session->conclude_start - = GNUNET_TIME_absolute_ntoh (m->start); - session->local_peer_idx = get_peer_idx (&my_peer, - session); - GNUNET_assert (-1 != session->local_peer_idx); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Joining consensus session %s containing %u peers as %u with timeout %s\n", - GNUNET_h2s (&m->session_id), - session->num_peers, - session->local_peer_idx, - GNUNET_STRINGS_relative_time_to_string - (GNUNET_TIME_absolute_get_difference (session->conclude_start, + = GNUNET_TIME_absolute_ntoh(m->start); + session->local_peer_idx = get_peer_idx(&my_peer, + session); + GNUNET_assert(-1 != session->local_peer_idx); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Joining consensus session %s containing %u peers as %u with timeout %s\n", + GNUNET_h2s(&m->session_id), + session->num_peers, + session->local_peer_idx, + GNUNET_STRINGS_relative_time_to_string + (GNUNET_TIME_absolute_get_difference(session->conclude_start, session->conclude_deadline), GNUNET_YES)); session->set_listener - = GNUNET_SET_listen (cfg, - GNUNET_SET_OPERATION_UNION, - &session->global_id, - &set_listen_cb, - session); - - session->setmap = GNUNET_CONTAINER_multihashmap_create (1, + = GNUNET_SET_listen(cfg, + GNUNET_SET_OPERATION_UNION, + &session->global_id, + &set_listen_cb, + session); + + session->setmap = GNUNET_CONTAINER_multihashmap_create(1, + GNUNET_NO); + session->taskmap = GNUNET_CONTAINER_multihashmap_create(1, GNUNET_NO); - session->taskmap = GNUNET_CONTAINER_multihashmap_create (1, - GNUNET_NO); - session->diffmap = GNUNET_CONTAINER_multihashmap_create (1, - GNUNET_NO); - session->rfnmap = GNUNET_CONTAINER_multihashmap_create (1, + session->diffmap = GNUNET_CONTAINER_multihashmap_create(1, GNUNET_NO); + session->rfnmap = GNUNET_CONTAINER_multihashmap_create(1, + GNUNET_NO); { struct SetEntry *client_set; - client_set = GNUNET_new (struct SetEntry); - client_set->h = GNUNET_SET_create (cfg, - GNUNET_SET_OPERATION_UNION); - struct SetHandle *sh = GNUNET_new (struct SetHandle); + client_set = GNUNET_new(struct SetEntry); + client_set->h = GNUNET_SET_create(cfg, + GNUNET_SET_OPERATION_UNION); + struct SetHandle *sh = GNUNET_new(struct SetHandle); sh->h = client_set->h; - GNUNET_CONTAINER_DLL_insert (session->set_handles_head, - session->set_handles_tail, - sh); + GNUNET_CONTAINER_DLL_insert(session->set_handles_head, + session->set_handles_tail, + sh); client_set->key = ((struct SetKey) { SET_KIND_CURRENT, 0, 0 }); - put_set (session, - client_set); + put_set(session, + client_set); } - session->peers_blacklisted = GNUNET_new_array (session->num_peers, - int); + session->peers_blacklisted = GNUNET_new_array(session->num_peers, + int); /* Just construct the task graph, but don't run anything until the client calls conclude. */ - construct_task_graph (session); - GNUNET_SERVICE_client_continue (session->client); + construct_task_graph(session); + GNUNET_SERVICE_client_continue(session->client); } static void -client_insert_done (void *cls) +client_insert_done(void *cls) { // FIXME: implement } @@ -3222,8 +3234,8 @@ client_insert_done (void *cls) * @return #GNUNET_OK (always well-formed) */ static int -check_client_insert (void *cls, - const struct GNUNET_CONSENSUS_ElementMessage *msg) +check_client_insert(void *cls, + const struct GNUNET_CONSENSUS_ElementMessage *msg) { return GNUNET_OK; } @@ -3236,8 +3248,8 @@ check_client_insert (void *cls, * @param msg message sent by the client */ static void -handle_client_insert (void *cls, - const struct GNUNET_CONSENSUS_ElementMessage *msg) +handle_client_insert(void *cls, + const struct GNUNET_CONSENSUS_ElementMessage *msg) { struct ConsensusSession *session = cls; ssize_t element_size; @@ -3245,20 +3257,20 @@ handle_client_insert (void *cls, struct ConsensusElement *ce; if (GNUNET_YES == session->conclude_started) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (session->client); - return; - } + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(session->client); + return; + } - element_size = ntohs (msg->header.size) - sizeof (struct GNUNET_CONSENSUS_ElementMessage); - ce = GNUNET_malloc (sizeof (struct ConsensusElement) + element_size); - GNUNET_memcpy (&ce[1], &msg[1], element_size); + element_size = ntohs(msg->header.size) - sizeof(struct GNUNET_CONSENSUS_ElementMessage); + ce = GNUNET_malloc(sizeof(struct ConsensusElement) + element_size); + GNUNET_memcpy(&ce[1], &msg[1], element_size); ce->payload_type = msg->element_type; struct GNUNET_SET_Element element = { .element_type = GNUNET_BLOCK_TYPE_CONSENSUS_ELEMENT, - .size = sizeof (struct ConsensusElement) + element_size, + .size = sizeof(struct ConsensusElement) + element_size, .data = ce, }; @@ -3266,28 +3278,28 @@ handle_client_insert (void *cls, struct SetKey key = { SET_KIND_CURRENT, 0, 0 }; struct SetEntry *entry; - entry = lookup_set (session, - &key); - GNUNET_assert (NULL != entry); + entry = lookup_set(session, + &key); + GNUNET_assert(NULL != entry); initial_set = entry->h; } session->num_client_insert_pending++; - GNUNET_SET_add_element (initial_set, - &element, - &client_insert_done, - session); + GNUNET_SET_add_element(initial_set, + &element, + &client_insert_done, + session); #ifdef GNUNET_EXTRA_LOGGING { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "P%u: element %s added\n", - session->local_peer_idx, - debug_str_element (&element)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "P%u: element %s added\n", + session->local_peer_idx, + debug_str_element(&element)); } #endif - GNUNET_free (ce); - GNUNET_SERVICE_client_continue (session->client); + GNUNET_free(ce); + GNUNET_SERVICE_client_continue(session->client); } @@ -3298,24 +3310,24 @@ handle_client_insert (void *cls, * @param message message sent by the client */ static void -handle_client_conclude (void *cls, - const struct GNUNET_MessageHeader *message) +handle_client_conclude(void *cls, + const struct GNUNET_MessageHeader *message) { struct ConsensusSession *session = cls; if (GNUNET_YES == session->conclude_started) - { - /* conclude started twice */ - GNUNET_break (0); - GNUNET_SERVICE_client_drop (session->client); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "conclude requested\n"); + { + /* conclude started twice */ + GNUNET_break(0); + GNUNET_SERVICE_client_drop(session->client); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "conclude requested\n"); session->conclude_started = GNUNET_YES; - install_step_timeouts (session); - run_ready_steps (session); - GNUNET_SERVICE_client_continue (session->client); + install_step_timeouts(session); + run_ready_steps(session); + GNUNET_SERVICE_client_continue(session->client); } @@ -3325,12 +3337,12 @@ handle_client_conclude (void *cls, * @param cls closure */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "shutting down\n"); - GNUNET_STATISTICS_destroy (statistics, - GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "shutting down\n"); + GNUNET_STATISTICS_destroy(statistics, + GNUNET_NO); statistics = NULL; } @@ -3343,24 +3355,24 @@ shutdown_task (void *cls) * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *service) { cfg = c; if (GNUNET_OK != - GNUNET_CRYPTO_get_peer_identity (cfg, - &my_peer)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not retrieve host identity\n"); - GNUNET_SCHEDULER_shutdown (); - return; - } - statistics = GNUNET_STATISTICS_create ("consensus", - cfg); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); + GNUNET_CRYPTO_get_peer_identity(cfg, + &my_peer)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not retrieve host identity\n"); + GNUNET_SCHEDULER_shutdown(); + return; + } + statistics = GNUNET_STATISTICS_create("consensus", + cfg); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); } @@ -3373,17 +3385,17 @@ run (void *cls, * @return @a c */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + struct GNUNET_MQ_Handle *mq) { - struct ConsensusSession *session = GNUNET_new (struct ConsensusSession); + struct ConsensusSession *session = GNUNET_new(struct ConsensusSession); session->client = c; session->client_mq = mq; - GNUNET_CONTAINER_DLL_insert (sessions_head, - sessions_tail, - session); + GNUNET_CONTAINER_DLL_insert(sessions_head, + sessions_tail, + session); return session; } @@ -3396,29 +3408,29 @@ client_connect_cb (void *cls, * @param internal_cls should be equal to @a c */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - void *internal_cls) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + void *internal_cls) { struct ConsensusSession *session = internal_cls; if (NULL != session->set_listener) - { - GNUNET_SET_listen_cancel (session->set_listener); - session->set_listener = NULL; - } - GNUNET_CONTAINER_DLL_remove (sessions_head, - sessions_tail, - session); + { + GNUNET_SET_listen_cancel(session->set_listener); + session->set_listener = NULL; + } + GNUNET_CONTAINER_DLL_remove(sessions_head, + sessions_tail, + session); while (session->set_handles_head) - { - struct SetHandle *sh = session->set_handles_head; - session->set_handles_head = sh->next; - GNUNET_SET_destroy (sh->h); - GNUNET_free (sh); - } - GNUNET_free (session); + { + struct SetHandle *sh = session->set_handles_head; + session->set_handles_head = sh->next; + GNUNET_SET_destroy(sh->h); + GNUNET_free(sh); + } + GNUNET_free(session); } @@ -3426,24 +3438,24 @@ client_disconnect_cb (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("consensus", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_fixed_size (client_conclude, + ("consensus", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_fixed_size(client_conclude, GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_CONCLUDE, struct GNUNET_MessageHeader, NULL), - GNUNET_MQ_hd_var_size (client_insert, + GNUNET_MQ_hd_var_size(client_insert, GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_INSERT, struct GNUNET_CONSENSUS_ElementMessage, NULL), - GNUNET_MQ_hd_var_size (client_join, + GNUNET_MQ_hd_var_size(client_join, GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_JOIN, struct GNUNET_CONSENSUS_JoinMessage, NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_handler_end()); /* end of gnunet-service-consensus.c */ diff --git a/src/consensus/plugin_block_consensus.c b/src/consensus/plugin_block_consensus.c index ca19b7c8d..a90b451d2 100644 --- a/src/consensus/plugin_block_consensus.c +++ b/src/consensus/plugin_block_consensus.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file consensus/plugin_block_consensus.c @@ -47,35 +47,35 @@ * @return characterization of result */ static enum GNUNET_BLOCK_EvaluationResult -block_plugin_consensus_evaluate (void *cls, - struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *group, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode *query, - const void *xquery, - size_t xquery_size, - const void *reply_block, - size_t reply_block_size) +block_plugin_consensus_evaluate(void *cls, + struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *group, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode *query, + const void *xquery, + size_t xquery_size, + const void *reply_block, + size_t reply_block_size) { - if (reply_block_size < sizeof (struct ConsensusElement)) + if (reply_block_size < sizeof(struct ConsensusElement)) return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; const struct ConsensusElement *ce = reply_block; - if ( (0 != ce->marker) || - (0 == ce->payload_type ) ) + if ((0 != ce->marker) || + (0 == ce->payload_type)) return GNUNET_BLOCK_EVALUATION_OK_MORE; - return GNUNET_BLOCK_evaluate (ctx, - type, - group, - eo, - query, - xquery, - xquery_size, - &ce[1], - reply_block_size - sizeof (struct ConsensusElement)); + return GNUNET_BLOCK_evaluate(ctx, + type, + group, + eo, + query, + xquery, + xquery_size, + &ce[1], + reply_block_size - sizeof(struct ConsensusElement)); } @@ -91,11 +91,11 @@ block_plugin_consensus_evaluate (void *cls, * (or if extracting a key from a block of this type does not work) */ static int -block_plugin_consensus_get_key (void *cls, +block_plugin_consensus_get_key(void *cls, enum GNUNET_BLOCK_Type type, const void *block, size_t block_size, - struct GNUNET_HashCode *key) + struct GNUNET_HashCode *key) { return GNUNET_SYSERR; } @@ -105,7 +105,7 @@ block_plugin_consensus_get_key (void *cls, * Entry point for the plugin. */ void * -libgnunet_plugin_block_consensus_init (void *cls) +libgnunet_plugin_block_consensus_init(void *cls) { static enum GNUNET_BLOCK_Type types[] = { @@ -114,7 +114,7 @@ libgnunet_plugin_block_consensus_init (void *cls) }; struct GNUNET_BLOCK_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_BLOCK_PluginFunctions); + api = GNUNET_new(struct GNUNET_BLOCK_PluginFunctions); api->evaluate = &block_plugin_consensus_evaluate; api->get_key = &block_plugin_consensus_get_key; api->types = types; @@ -126,11 +126,11 @@ libgnunet_plugin_block_consensus_init (void *cls) * Exit point from the plugin. */ void * -libgnunet_plugin_block_consensus_done (void *cls) +libgnunet_plugin_block_consensus_done(void *cls) { struct GNUNET_BLOCK_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/consensus/test_consensus_api.c b/src/consensus/test_consensus_api.c index 46e582afe..a2ae36222 100644 --- a/src/consensus/test_consensus_api.c +++ b/src/consensus/test_consensus_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file consensus/test_consensus_api.c @@ -36,30 +36,31 @@ static unsigned int elements_received; static void -conclude_done (void *cls) +conclude_done(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "conclude over\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "conclude over\n"); if (2 != elements_received) - GNUNET_assert (0); - GNUNET_SCHEDULER_shutdown (); + GNUNET_assert(0); + GNUNET_SCHEDULER_shutdown(); } static void -on_new_element (void *cls, - const struct GNUNET_SET_Element *element) +on_new_element(void *cls, + const struct GNUNET_SET_Element *element) { elements_received++; } static void -insert_done (void *cls, int success) +insert_done(void *cls, int success) { /* make sure cb is only called once */ static int called = GNUNET_NO; - GNUNET_assert (GNUNET_NO == called); + + GNUNET_assert(GNUNET_NO == called); called = GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "insert done\n"); - GNUNET_CONSENSUS_conclude (consensus, &conclude_done, NULL); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "insert done\n"); + GNUNET_CONSENSUS_conclude(consensus, &conclude_done, NULL); } @@ -69,47 +70,47 @@ insert_done (void *cls, int success) * @param cls closure */ static void -on_shutdown (void *cls) +on_shutdown(void *cls) { if (NULL != consensus) - { - GNUNET_CONSENSUS_destroy (consensus); - consensus = NULL; - } + { + GNUNET_CONSENSUS_destroy(consensus); + consensus = NULL; + } } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { char *str = "foo"; - struct GNUNET_SET_Element el1 = {4, 0, "foo"}; - struct GNUNET_SET_Element el2 = {5, 0, "quux"}; + struct GNUNET_SET_Element el1 = { 4, 0, "foo" }; + struct GNUNET_SET_Element el2 = { 5, 0, "quux" }; - GNUNET_log_setup ("test_consensus_api", - "INFO", - NULL); - GNUNET_SCHEDULER_add_shutdown (&on_shutdown, NULL); + GNUNET_log_setup("test_consensus_api", + "INFO", + NULL); + GNUNET_SCHEDULER_add_shutdown(&on_shutdown, NULL); - GNUNET_CRYPTO_hash (str, strlen (str), &session_id); - consensus = GNUNET_CONSENSUS_create (cfg, 0, NULL, &session_id, - GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_SECONDS), - GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES), - on_new_element, &consensus); - GNUNET_assert (consensus != NULL); + GNUNET_CRYPTO_hash(str, strlen(str), &session_id); + consensus = GNUNET_CONSENSUS_create(cfg, 0, NULL, &session_id, + GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_SECONDS), + GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_MINUTES), + on_new_element, &consensus); + GNUNET_assert(consensus != NULL); - GNUNET_CONSENSUS_insert (consensus, &el1, NULL, &consensus); - GNUNET_CONSENSUS_insert (consensus, &el2, &insert_done, &consensus); + GNUNET_CONSENSUS_insert(consensus, &el1, NULL, &consensus); + GNUNET_CONSENSUS_insert(consensus, &el2, &insert_done, &consensus); } int -main (int argc, char **argv) +main(int argc, char **argv) { - return GNUNET_TESTING_peer_run ("test_consensus_api", - "test_consensus.conf", - &run, NULL); + return GNUNET_TESTING_peer_run("test_consensus_api", + "test_consensus.conf", + &run, NULL); } diff --git a/src/conversation/conversation.h b/src/conversation/conversation.h index 69f868e6c..0a9e2b5fb 100644 --- a/src/conversation/conversation.h +++ b/src/conversation/conversation.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/conversation.h @@ -30,13 +30,13 @@ #ifdef __cplusplus extern "C" { -#if 0 /* keep Emacsens' auto-indent happy */ +#if 0 /* keep Emacsens' auto-indent happy */ } #endif #endif -#define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** @@ -44,7 +44,7 @@ extern "C" * bit set if we are making an outgoing call, * bit unset for local lines. */ -#define HIGH_BIT ((uint32_t) (1LL << 31)) +#define HIGH_BIT ((uint32_t)(1LL << 31)) GNUNET_NETWORK_STRUCT_BEGIN @@ -52,23 +52,20 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Message to transmit the audio (between client and helpers). */ -struct AudioMessage -{ +struct AudioMessage { /** * Type is #GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO */ struct GNUNET_MessageHeader header; /* followed by audio data */ - }; /** * Client -> Service message to register a phone. */ -struct ClientPhoneRegisterMessage -{ +struct ClientPhoneRegisterMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_REGISTER */ @@ -89,8 +86,7 @@ struct ClientPhoneRegisterMessage /** * Service -> Client message for phone is ringing. */ -struct ClientPhoneRingMessage -{ +struct ClientPhoneRingMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RING */ @@ -106,15 +102,13 @@ struct ClientPhoneRingMessage * Who is calling us? */ struct GNUNET_CRYPTO_EcdsaPublicKey caller_id; - }; /** * Service <-> Client message for phone was suspended. */ -struct ClientPhoneSuspendMessage -{ +struct ClientPhoneSuspendMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND */ @@ -125,15 +119,13 @@ struct ClientPhoneSuspendMessage * talking about. */ uint32_t cid GNUNET_PACKED; - }; /** * Service <-> Client message for phone was resumed. */ -struct ClientPhoneResumeMessage -{ +struct ClientPhoneResumeMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME */ @@ -144,15 +136,13 @@ struct ClientPhoneResumeMessage * talking about. */ uint32_t cid GNUNET_PACKED; - }; /** * Client -> Service pick up phone that is ringing. */ -struct ClientPhonePickupMessage -{ +struct ClientPhonePickupMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_PICK_UP */ @@ -163,7 +153,6 @@ struct ClientPhonePickupMessage * talking about. */ uint32_t cid GNUNET_PACKED; - }; @@ -171,8 +160,7 @@ struct ClientPhonePickupMessage * Client <-> Service hang up phone that may or may not be ringing. * Also sent in response to a (failed) `struct ClientCallMessage`. */ -struct ClientPhoneHangupMessage -{ +struct ClientPhoneHangupMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP */ @@ -183,15 +171,13 @@ struct ClientPhoneHangupMessage * talking about. */ uint32_t cid GNUNET_PACKED; - }; /** * Message Client <-> Service to transmit the audio. */ -struct ClientAudioMessage -{ +struct ClientAudioMessage { /** * Type is #GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO */ @@ -204,15 +190,13 @@ struct ClientAudioMessage uint32_t cid GNUNET_PACKED; /* followed by audio data */ - }; /** * Client -> Service message to call a phone. */ -struct ClientCallMessage -{ +struct ClientCallMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_CALL */ @@ -244,8 +228,7 @@ struct ClientCallMessage * Service -> Client: other peer has picked up the phone, we are * now talking. */ -struct ClientPhonePickedupMessage -{ +struct ClientPhonePickedupMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_PICKED_UP */ @@ -256,7 +239,6 @@ struct ClientPhonePickedupMessage * #GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_CALL */ uint32_t cid GNUNET_PACKED; - }; @@ -264,8 +246,7 @@ struct ClientPhonePickedupMessage * Information signed in a `struct CadetPhoneRingMessage` * whereby the caller self-identifies to the receiver. */ -struct CadetPhoneRingInfoPS -{ +struct CadetPhoneRingInfoPS { /** * Purpose for the signature, must be * #GNUNET_SIGNATURE_PURPOSE_CONVERSATION_RING. @@ -293,8 +274,7 @@ struct CadetPhoneRingInfoPS * Cadet message to make a phone ring. Sent to the port * of the respective phone. */ -struct CadetPhoneRingMessage -{ +struct CadetPhoneRingMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_RING */ @@ -319,81 +299,70 @@ struct CadetPhoneRingMessage * Signature over a `struct CadetPhoneRingInfoPS` */ struct GNUNET_CRYPTO_EcdsaSignature signature; - }; /** * Cadet message for hanging up. */ -struct CadetPhoneHangupMessage -{ +struct CadetPhoneHangupMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_HANG_UP */ struct GNUNET_MessageHeader header; - }; /** * Cadet message for picking up. */ -struct CadetPhonePickupMessage -{ +struct CadetPhonePickupMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_PICK_UP */ struct GNUNET_MessageHeader header; - }; /** * Cadet message for phone suspended. */ -struct CadetPhoneSuspendMessage -{ +struct CadetPhoneSuspendMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_SUSPEND */ struct GNUNET_MessageHeader header; - }; /** * Cadet message for phone resumed. */ -struct CadetPhoneResumeMessage -{ +struct CadetPhoneResumeMessage { /** * Type is: #GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_RESUME */ struct GNUNET_MessageHeader header; - }; /** * Cadet message to transmit the audio. */ -struct CadetAudioMessage -{ +struct CadetAudioMessage { /** * Type is #GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_AUDIO */ struct GNUNET_MessageHeader header; /* followed by audio data */ - }; GNUNET_NETWORK_STRUCT_END -#if 0 /* keep Emacsens' auto-indent happy */ +#if 0 /* keep Emacsens' auto-indent happy */ { #endif #ifdef __cplusplus diff --git a/src/conversation/conversation_api.c b/src/conversation/conversation_api.c index cd777c285..4c19a7d2d 100644 --- a/src/conversation/conversation_api.c +++ b/src/conversation/conversation_api.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet - Copyright (C) 2013, 2014 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet + Copyright (C) 2013, 2014 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -33,8 +33,7 @@ /** * Possible states of a caller. */ -enum CallerState -{ +enum CallerState { /** * The phone is ringing (user knows about incoming call). */ @@ -66,9 +65,7 @@ enum CallerState /** * A caller is the handle we have for an incoming call. */ -struct GNUNET_CONVERSATION_Caller -{ - +struct GNUNET_CONVERSATION_Caller { /** * We keep all callers in a DLL. */ @@ -118,15 +115,13 @@ struct GNUNET_CONVERSATION_Caller * State machine for the phone. */ enum CallerState state; - }; /** * Possible states of a phone. */ -enum PhoneState -{ +enum PhoneState { /** * We still need to register the phone. */ @@ -136,7 +131,6 @@ enum PhoneState * We are waiting for calls. */ PS_READY - }; @@ -151,8 +145,7 @@ enum PhoneState * something rather internal to a phone and not obvious from it). * You can only have one conversation per phone at any time. */ -struct GNUNET_CONVERSATION_Phone -{ +struct GNUNET_CONVERSATION_Phone { /** * Our configuration. */ @@ -202,7 +195,6 @@ struct GNUNET_CONVERSATION_Phone * State machine for the phone. */ enum PhoneState state; - }; @@ -212,7 +204,7 @@ struct GNUNET_CONVERSATION_Phone * @param phone phone to reconnect */ static void -reconnect_phone (struct GNUNET_CONVERSATION_Phone *phone); +reconnect_phone(struct GNUNET_CONVERSATION_Phone *phone); /** @@ -223,24 +215,24 @@ reconnect_phone (struct GNUNET_CONVERSATION_Phone *phone); * @param data audio data to play */ static void -transmit_phone_audio (void *cls, - size_t data_size, - const void *data) +transmit_phone_audio(void *cls, + size_t data_size, + const void *data) { struct GNUNET_CONVERSATION_Caller *caller = cls; struct GNUNET_CONVERSATION_Phone *phone = caller->phone; struct GNUNET_MQ_Envelope *e; struct ClientAudioMessage *am; - e = GNUNET_MQ_msg_extra (am, - data_size, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO); + e = GNUNET_MQ_msg_extra(am, + data_size, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO); am->cid = caller->cid; - GNUNET_memcpy (&am[1], - data, - data_size); - GNUNET_MQ_send (phone->mq, - e); + GNUNET_memcpy(&am[1], + data, + data_size); + GNUNET_MQ_send(phone->mq, + e); } @@ -251,32 +243,33 @@ transmit_phone_audio (void *cls, * @param ring the message */ static void -handle_phone_ring (void *cls, - const struct ClientPhoneRingMessage *ring) +handle_phone_ring(void *cls, + const struct ClientPhoneRingMessage *ring) { struct GNUNET_CONVERSATION_Phone *phone = cls; struct GNUNET_CONVERSATION_Caller *caller; switch (phone->state) - { - case PS_REGISTER: - GNUNET_assert (0); - break; - case PS_READY: - caller = GNUNET_new (struct GNUNET_CONVERSATION_Caller); - caller->phone = phone; - GNUNET_CONTAINER_DLL_insert (phone->caller_head, - phone->caller_tail, - caller); - caller->caller_id = ring->caller_id; - caller->cid = ring->cid; - caller->state = CS_RINGING; - phone->event_handler (phone->event_handler_cls, - GNUNET_CONVERSATION_EC_PHONE_RING, - caller, - &caller->caller_id); - break; - } + { + case PS_REGISTER: + GNUNET_assert(0); + break; + + case PS_READY: + caller = GNUNET_new(struct GNUNET_CONVERSATION_Caller); + caller->phone = phone; + GNUNET_CONTAINER_DLL_insert(phone->caller_head, + phone->caller_tail, + caller); + caller->caller_id = ring->caller_id; + caller->cid = ring->cid; + caller->state = CS_RINGING; + phone->event_handler(phone->event_handler_cls, + GNUNET_CONVERSATION_EC_PHONE_RING, + caller, + &caller->caller_id); + break; + } } @@ -288,12 +281,12 @@ handle_phone_ring (void *cls, * @return NULL if @a cid was not found */ static struct GNUNET_CONVERSATION_Caller * -find_caller (struct GNUNET_CONVERSATION_Phone *phone, - uint32_t cid) +find_caller(struct GNUNET_CONVERSATION_Phone *phone, + uint32_t cid) { struct GNUNET_CONVERSATION_Caller *caller; - for (caller = phone->caller_head;NULL != caller;caller = caller->next) + for (caller = phone->caller_head; NULL != caller; caller = caller->next) if (cid == caller->cid) return caller; return NULL; @@ -307,54 +300,56 @@ find_caller (struct GNUNET_CONVERSATION_Phone *phone, * @param msg the message */ static void -handle_phone_hangup (void *cls, - const struct ClientPhoneHangupMessage *hang) +handle_phone_hangup(void *cls, + const struct ClientPhoneHangupMessage *hang) { struct GNUNET_CONVERSATION_Phone *phone = cls; struct GNUNET_CONVERSATION_Caller *caller; - caller = find_caller (phone, - hang->cid); + caller = find_caller(phone, + hang->cid); if (NULL == caller) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received HANG_UP message for unknown caller ID %u\n", - (unsigned int) hang->cid); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received HANG_UP message for unknown caller ID %u\n", + (unsigned int)hang->cid); + return; + } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received HANG_UP message, terminating call with `%s'\n", - GNUNET_GNSRECORD_pkey_to_zkey (&caller->caller_id)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received HANG_UP message, terminating call with `%s'\n", + GNUNET_GNSRECORD_pkey_to_zkey(&caller->caller_id)); switch (caller->state) - { - case CS_RINGING: - phone->event_handler (phone->event_handler_cls, - GNUNET_CONVERSATION_EC_PHONE_HUNG_UP, - caller, - &caller->caller_id); - break; - case CS_ACTIVE: - caller->speaker->disable_speaker (caller->speaker->cls); - caller->mic->disable_microphone (caller->mic->cls); - phone->event_handler (phone->event_handler_cls, - GNUNET_CONVERSATION_EC_PHONE_HUNG_UP, - caller, - &caller->caller_id); - break; - case CS_CALLEE_SUSPENDED: - case CS_CALLER_SUSPENDED: - case CS_BOTH_SUSPENDED: - phone->event_handler (phone->event_handler_cls, - GNUNET_CONVERSATION_EC_PHONE_HUNG_UP, - caller, - &caller->caller_id); - break; - } - GNUNET_CONTAINER_DLL_remove (phone->caller_head, - phone->caller_tail, - caller); - GNUNET_free (caller); + { + case CS_RINGING: + phone->event_handler(phone->event_handler_cls, + GNUNET_CONVERSATION_EC_PHONE_HUNG_UP, + caller, + &caller->caller_id); + break; + + case CS_ACTIVE: + caller->speaker->disable_speaker(caller->speaker->cls); + caller->mic->disable_microphone(caller->mic->cls); + phone->event_handler(phone->event_handler_cls, + GNUNET_CONVERSATION_EC_PHONE_HUNG_UP, + caller, + &caller->caller_id); + break; + + case CS_CALLEE_SUSPENDED: + case CS_CALLER_SUSPENDED: + case CS_BOTH_SUSPENDED: + phone->event_handler(phone->event_handler_cls, + GNUNET_CONVERSATION_EC_PHONE_HUNG_UP, + caller, + &caller->caller_id); + break; + } + GNUNET_CONTAINER_DLL_remove(phone->caller_head, + phone->caller_tail, + caller); + GNUNET_free(caller); } @@ -365,38 +360,41 @@ handle_phone_hangup (void *cls, * @param suspend the message */ static void -handle_phone_suspend (void *cls, - const struct ClientPhoneSuspendMessage *suspend) +handle_phone_suspend(void *cls, + const struct ClientPhoneSuspendMessage *suspend) { struct GNUNET_CONVERSATION_Phone *phone = cls; struct GNUNET_CONVERSATION_Caller *caller; - caller = find_caller (phone, - suspend->cid); + caller = find_caller(phone, + suspend->cid); if (NULL == caller) return; switch (caller->state) - { - case CS_RINGING: - GNUNET_break_op (0); - break; - case CS_ACTIVE: - caller->state = CS_CALLER_SUSPENDED; - caller->speaker->disable_speaker (caller->speaker->cls); - caller->mic->disable_microphone (caller->mic->cls); - caller->event_handler (caller->event_handler_cls, - GNUNET_CONVERSATION_EC_CALLER_SUSPEND); - break; - case CS_CALLEE_SUSPENDED: - caller->state = CS_BOTH_SUSPENDED; - caller->event_handler (caller->event_handler_cls, - GNUNET_CONVERSATION_EC_CALLER_SUSPEND); - break; - case CS_CALLER_SUSPENDED: - case CS_BOTH_SUSPENDED: - GNUNET_break_op (0); - break; - } + { + case CS_RINGING: + GNUNET_break_op(0); + break; + + case CS_ACTIVE: + caller->state = CS_CALLER_SUSPENDED; + caller->speaker->disable_speaker(caller->speaker->cls); + caller->mic->disable_microphone(caller->mic->cls); + caller->event_handler(caller->event_handler_cls, + GNUNET_CONVERSATION_EC_CALLER_SUSPEND); + break; + + case CS_CALLEE_SUSPENDED: + caller->state = CS_BOTH_SUSPENDED; + caller->event_handler(caller->event_handler_cls, + GNUNET_CONVERSATION_EC_CALLER_SUSPEND); + break; + + case CS_CALLER_SUSPENDED: + case CS_BOTH_SUSPENDED: + GNUNET_break_op(0); + break; + } } @@ -407,40 +405,43 @@ handle_phone_suspend (void *cls, * @param resume the message */ static void -handle_phone_resume (void *cls, - const struct ClientPhoneResumeMessage *resume) +handle_phone_resume(void *cls, + const struct ClientPhoneResumeMessage *resume) { struct GNUNET_CONVERSATION_Phone *phone = cls; struct GNUNET_CONVERSATION_Caller *caller; - caller = find_caller (phone, - resume->cid); + caller = find_caller(phone, + resume->cid); if (NULL == caller) return; switch (caller->state) - { - case CS_RINGING: - GNUNET_break_op (0); - break; - case CS_ACTIVE: - case CS_CALLEE_SUSPENDED: - GNUNET_break_op (0); - break; - case CS_CALLER_SUSPENDED: - caller->state = CS_ACTIVE; - caller->speaker->enable_speaker (caller->speaker->cls); - caller->mic->enable_microphone (caller->mic->cls, - &transmit_phone_audio, - caller); - caller->event_handler (caller->event_handler_cls, - GNUNET_CONVERSATION_EC_CALLER_RESUME); - break; - case CS_BOTH_SUSPENDED: - caller->state = CS_CALLEE_SUSPENDED; - caller->event_handler (caller->event_handler_cls, - GNUNET_CONVERSATION_EC_CALLER_RESUME); - break; - } + { + case CS_RINGING: + GNUNET_break_op(0); + break; + + case CS_ACTIVE: + case CS_CALLEE_SUSPENDED: + GNUNET_break_op(0); + break; + + case CS_CALLER_SUSPENDED: + caller->state = CS_ACTIVE; + caller->speaker->enable_speaker(caller->speaker->cls); + caller->mic->enable_microphone(caller->mic->cls, + &transmit_phone_audio, + caller); + caller->event_handler(caller->event_handler_cls, + GNUNET_CONVERSATION_EC_CALLER_RESUME); + break; + + case CS_BOTH_SUSPENDED: + caller->state = CS_CALLEE_SUSPENDED; + caller->event_handler(caller->event_handler_cls, + GNUNET_CONVERSATION_EC_CALLER_RESUME); + break; + } } @@ -452,12 +453,12 @@ handle_phone_resume (void *cls, * @return #GNUNET_OK if @a am is well-formed */ static int -check_phone_audio (void *cls, - const struct ClientAudioMessage *am) +check_phone_audio(void *cls, + const struct ClientAudioMessage *am) { - (void) cls; - (void) am; - + (void)cls; + (void)am; + /* any variable-size payload is OK */ return GNUNET_OK; } @@ -470,31 +471,33 @@ check_phone_audio (void *cls, * @param am the message */ static void -handle_phone_audio (void *cls, - const struct ClientAudioMessage *am) +handle_phone_audio(void *cls, + const struct ClientAudioMessage *am) { struct GNUNET_CONVERSATION_Phone *phone = cls; struct GNUNET_CONVERSATION_Caller *caller; - caller = find_caller (phone, - am->cid); + caller = find_caller(phone, + am->cid); if (NULL == caller) return; switch (caller->state) - { - case CS_RINGING: - GNUNET_break_op (0); - break; - case CS_ACTIVE: - caller->speaker->play (caller->speaker->cls, - ntohs (am->header.size) - sizeof (struct ClientAudioMessage), - &am[1]); - break; - case CS_CALLEE_SUSPENDED: - case CS_CALLER_SUSPENDED: - case CS_BOTH_SUSPENDED: - break; - } + { + case CS_RINGING: + GNUNET_break_op(0); + break; + + case CS_ACTIVE: + caller->speaker->play(caller->speaker->cls, + ntohs(am->header.size) - sizeof(struct ClientAudioMessage), + &am[1]); + break; + + case CS_CALLEE_SUSPENDED: + case CS_CALLER_SUSPENDED: + case CS_BOTH_SUSPENDED: + break; + } } @@ -505,15 +508,15 @@ handle_phone_audio (void *cls, * @param error details about the error */ static void -phone_error_handler (void *cls, - enum GNUNET_MQ_Error error) +phone_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_CONVERSATION_Phone *phone = cls; - (void) error; - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Connection to conversation service lost, trying to reconnect\n")); - reconnect_phone (phone); + (void)error; + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Connection to conversation service lost, trying to reconnect\n")); + reconnect_phone(phone); } @@ -523,25 +526,25 @@ phone_error_handler (void *cls, * @param phone phone to clean up callers for */ static void -clean_up_callers (struct GNUNET_CONVERSATION_Phone *phone) +clean_up_callers(struct GNUNET_CONVERSATION_Phone *phone) { struct GNUNET_CONVERSATION_Caller *caller; while (NULL != (caller = phone->caller_head)) - { - /* make sure mic/speaker are disabled *before* callback */ - if (CS_ACTIVE == caller->state) { - caller->speaker->disable_speaker (caller->speaker->cls); - caller->mic->disable_microphone (caller->mic->cls); - caller->state = CS_CALLER_SUSPENDED; + /* make sure mic/speaker are disabled *before* callback */ + if (CS_ACTIVE == caller->state) + { + caller->speaker->disable_speaker(caller->speaker->cls); + caller->mic->disable_microphone(caller->mic->cls); + caller->state = CS_CALLER_SUSPENDED; + } + phone->event_handler(phone->event_handler_cls, + GNUNET_CONVERSATION_EC_PHONE_HUNG_UP, + caller, + &caller->caller_id); + GNUNET_CONVERSATION_caller_hang_up(caller); } - phone->event_handler (phone->event_handler_cls, - GNUNET_CONVERSATION_EC_PHONE_HUNG_UP, - caller, - &caller->caller_id); - GNUNET_CONVERSATION_caller_hang_up (caller); - } } @@ -551,53 +554,53 @@ clean_up_callers (struct GNUNET_CONVERSATION_Phone *phone) * @param phone phone to reconnect */ static void -reconnect_phone (struct GNUNET_CONVERSATION_Phone *phone) +reconnect_phone(struct GNUNET_CONVERSATION_Phone *phone) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (phone_ring, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RING, - struct ClientPhoneRingMessage, - phone), - GNUNET_MQ_hd_fixed_size (phone_hangup, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP, - struct ClientPhoneHangupMessage, - phone), - GNUNET_MQ_hd_fixed_size (phone_suspend, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND, - struct ClientPhoneSuspendMessage, - phone), - GNUNET_MQ_hd_fixed_size (phone_resume, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME, - struct ClientPhoneResumeMessage, - phone), - GNUNET_MQ_hd_var_size (phone_audio, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO, - struct ClientAudioMessage, - phone), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(phone_ring, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RING, + struct ClientPhoneRingMessage, + phone), + GNUNET_MQ_hd_fixed_size(phone_hangup, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP, + struct ClientPhoneHangupMessage, + phone), + GNUNET_MQ_hd_fixed_size(phone_suspend, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND, + struct ClientPhoneSuspendMessage, + phone), + GNUNET_MQ_hd_fixed_size(phone_resume, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME, + struct ClientPhoneResumeMessage, + phone), + GNUNET_MQ_hd_var_size(phone_audio, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO, + struct ClientAudioMessage, + phone), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *e; struct ClientPhoneRegisterMessage *reg; - clean_up_callers (phone); + clean_up_callers(phone); if (NULL != phone->mq) - { - GNUNET_MQ_destroy (phone->mq); - phone->mq = NULL; - } + { + GNUNET_MQ_destroy(phone->mq); + phone->mq = NULL; + } phone->state = PS_REGISTER; - phone->mq = GNUNET_CLIENT_connect (phone->cfg, - "conversation", - handlers, - &phone_error_handler, - phone); + phone->mq = GNUNET_CLIENT_connect(phone->cfg, + "conversation", + handlers, + &phone_error_handler, + phone); if (NULL == phone->mq) return; - e = GNUNET_MQ_msg (reg, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_REGISTER); + e = GNUNET_MQ_msg(reg, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_REGISTER); reg->line_port = phone->my_record.line_port; - GNUNET_MQ_send (phone->mq, - e); + GNUNET_MQ_send(phone->mq, + e); phone->state = PS_READY; } @@ -613,54 +616,54 @@ reconnect_phone (struct GNUNET_CONVERSATION_Phone *phone) * @return NULL on error (no valid line configured) */ struct GNUNET_CONVERSATION_Phone * -GNUNET_CONVERSATION_phone_create (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_IDENTITY_Ego *ego, - GNUNET_CONVERSATION_PhoneEventHandler event_handler, - void *event_handler_cls) +GNUNET_CONVERSATION_phone_create(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_IDENTITY_Ego *ego, + GNUNET_CONVERSATION_PhoneEventHandler event_handler, + void *event_handler_cls) { struct GNUNET_CONVERSATION_Phone *phone; char *line; struct GNUNET_HashCode line_port; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "CONVERSATION", - "LINE", - &line)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "CONVERSATION", - "LINE"); - return NULL; - } - GNUNET_CRYPTO_hash (line, - strlen (line), - &line_port); - phone = GNUNET_new (struct GNUNET_CONVERSATION_Phone); + GNUNET_CONFIGURATION_get_value_string(cfg, + "CONVERSATION", + "LINE", + &line)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "CONVERSATION", + "LINE"); + return NULL; + } + GNUNET_CRYPTO_hash(line, + strlen(line), + &line_port); + phone = GNUNET_new(struct GNUNET_CONVERSATION_Phone); if (GNUNET_OK != - GNUNET_CRYPTO_get_peer_identity (cfg, - &phone->my_record.peer)) - { - GNUNET_break (0); - GNUNET_free (phone); - return NULL; - } + GNUNET_CRYPTO_get_peer_identity(cfg, + &phone->my_record.peer)) + { + GNUNET_break(0); + GNUNET_free(phone); + return NULL; + } phone->cfg = cfg; - phone->my_zone = *GNUNET_IDENTITY_ego_get_private_key (ego); + phone->my_zone = *GNUNET_IDENTITY_ego_get_private_key(ego); phone->event_handler = event_handler; phone->event_handler_cls = event_handler_cls; - phone->ns = GNUNET_NAMESTORE_connect (cfg); - phone->my_record.version = htonl (1); - phone->my_record.reserved = htonl (0); + phone->ns = GNUNET_NAMESTORE_connect(cfg); + phone->my_record.version = htonl(1); + phone->my_record.reserved = htonl(0); phone->my_record.line_port = line_port; - reconnect_phone (phone); - if ( (NULL == phone->mq) || - (NULL == phone->ns) ) - { - GNUNET_break (0); - GNUNET_CONVERSATION_phone_destroy (phone); - return NULL; - } + reconnect_phone(phone); + if ((NULL == phone->mq) || + (NULL == phone->ns)) + { + GNUNET_break(0); + GNUNET_CONVERSATION_phone_destroy(phone); + return NULL; + } return phone; } @@ -674,12 +677,12 @@ GNUNET_CONVERSATION_phone_create (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param rd namestore record to fill in */ void -GNUNET_CONVERSATION_phone_get_record (struct GNUNET_CONVERSATION_Phone *phone, - struct GNUNET_GNSRECORD_Data *rd) +GNUNET_CONVERSATION_phone_get_record(struct GNUNET_CONVERSATION_Phone *phone, + struct GNUNET_GNSRECORD_Data *rd) { rd->data = &phone->my_record; rd->expiration_time = 0; - rd->data_size = sizeof (struct GNUNET_CONVERSATION_PhoneRecord); + rd->data_size = sizeof(struct GNUNET_CONVERSATION_PhoneRecord); rd->record_type = GNUNET_GNSRECORD_TYPE_PHONE; rd->flags = GNUNET_GNSRECORD_RF_NONE; } @@ -696,31 +699,31 @@ GNUNET_CONVERSATION_phone_get_record (struct GNUNET_CONVERSATION_Phone *phone, * @param mic microphone to use */ void -GNUNET_CONVERSATION_caller_pick_up (struct GNUNET_CONVERSATION_Caller *caller, - GNUNET_CONVERSATION_CallerEventHandler event_handler, - void *event_handler_cls, - struct GNUNET_SPEAKER_Handle *speaker, - struct GNUNET_MICROPHONE_Handle *mic) +GNUNET_CONVERSATION_caller_pick_up(struct GNUNET_CONVERSATION_Caller *caller, + GNUNET_CONVERSATION_CallerEventHandler event_handler, + void *event_handler_cls, + struct GNUNET_SPEAKER_Handle *speaker, + struct GNUNET_MICROPHONE_Handle *mic) { struct GNUNET_CONVERSATION_Phone *phone = caller->phone; struct GNUNET_MQ_Envelope *e; struct ClientPhonePickupMessage *pick; - GNUNET_assert (CS_RINGING == caller->state); + GNUNET_assert(CS_RINGING == caller->state); caller->speaker = speaker; caller->mic = mic; - e = GNUNET_MQ_msg (pick, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_PICK_UP); + e = GNUNET_MQ_msg(pick, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_PICK_UP); pick->cid = caller->cid; - GNUNET_MQ_send (phone->mq, - e); + GNUNET_MQ_send(phone->mq, + e); caller->state = CS_ACTIVE; caller->event_handler = event_handler; caller->event_handler_cls = event_handler_cls; - caller->speaker->enable_speaker (caller->speaker->cls); - caller->mic->enable_microphone (caller->mic->cls, - &transmit_phone_audio, - caller); + caller->speaker->enable_speaker(caller->speaker->cls); + caller->mic->enable_microphone(caller->mic->cls, + &transmit_phone_audio, + caller); } @@ -731,30 +734,31 @@ GNUNET_CONVERSATION_caller_pick_up (struct GNUNET_CONVERSATION_Caller *caller, * @param caller conversation to hang up on */ void -GNUNET_CONVERSATION_caller_hang_up (struct GNUNET_CONVERSATION_Caller *caller) +GNUNET_CONVERSATION_caller_hang_up(struct GNUNET_CONVERSATION_Caller *caller) { struct GNUNET_CONVERSATION_Phone *phone = caller->phone; struct GNUNET_MQ_Envelope *e; struct ClientPhoneHangupMessage *hang; switch (caller->state) - { - case CS_ACTIVE: - caller->speaker->disable_speaker (caller->speaker->cls); - caller->mic->disable_microphone (caller->mic->cls); - break; - default: - break; - } - GNUNET_CONTAINER_DLL_remove (phone->caller_head, - phone->caller_tail, - caller); - e = GNUNET_MQ_msg (hang, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP); + { + case CS_ACTIVE: + caller->speaker->disable_speaker(caller->speaker->cls); + caller->mic->disable_microphone(caller->mic->cls); + break; + + default: + break; + } + GNUNET_CONTAINER_DLL_remove(phone->caller_head, + phone->caller_tail, + caller); + e = GNUNET_MQ_msg(hang, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP); hang->cid = caller->cid; - GNUNET_MQ_send (phone->mq, - e); - GNUNET_free (caller); + GNUNET_MQ_send(phone->mq, + e); + GNUNET_free(caller); } @@ -764,20 +768,20 @@ GNUNET_CONVERSATION_caller_hang_up (struct GNUNET_CONVERSATION_Caller *caller) * @param phone phone to destroy */ void -GNUNET_CONVERSATION_phone_destroy (struct GNUNET_CONVERSATION_Phone *phone) +GNUNET_CONVERSATION_phone_destroy(struct GNUNET_CONVERSATION_Phone *phone) { - clean_up_callers (phone); + clean_up_callers(phone); if (NULL != phone->ns) - { - GNUNET_NAMESTORE_disconnect (phone->ns); - phone->ns = NULL; - } + { + GNUNET_NAMESTORE_disconnect(phone->ns); + phone->ns = NULL; + } if (NULL != phone->mq) - { - GNUNET_MQ_destroy (phone->mq); - phone->mq = NULL; - } - GNUNET_free (phone); + { + GNUNET_MQ_destroy(phone->mq); + phone->mq = NULL; + } + GNUNET_free(phone); } @@ -789,26 +793,26 @@ GNUNET_CONVERSATION_phone_destroy (struct GNUNET_CONVERSATION_Phone *phone) * @param caller call to suspend */ void -GNUNET_CONVERSATION_caller_suspend (struct GNUNET_CONVERSATION_Caller *caller) +GNUNET_CONVERSATION_caller_suspend(struct GNUNET_CONVERSATION_Caller *caller) { struct GNUNET_CONVERSATION_Phone *phone = caller->phone; struct GNUNET_MQ_Envelope *e; struct ClientPhoneSuspendMessage *suspend; - GNUNET_assert ( (CS_ACTIVE == caller->state) || - (CS_CALLER_SUSPENDED == caller->state) ); + GNUNET_assert((CS_ACTIVE == caller->state) || + (CS_CALLER_SUSPENDED == caller->state)); if (CS_ACTIVE == caller->state) - { - caller->speaker->disable_speaker (caller->speaker->cls); - caller->mic->disable_microphone (caller->mic->cls); - } + { + caller->speaker->disable_speaker(caller->speaker->cls); + caller->mic->disable_microphone(caller->mic->cls); + } caller->speaker = NULL; caller->mic = NULL; - e = GNUNET_MQ_msg (suspend, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND); + e = GNUNET_MQ_msg(suspend, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND); suspend->cid = caller->cid; - GNUNET_MQ_send (phone->mq, - e); + GNUNET_MQ_send(phone->mq, + e); if (CS_ACTIVE == caller->state) caller->state = CS_CALLEE_SUSPENDED; else @@ -824,35 +828,35 @@ GNUNET_CONVERSATION_caller_suspend (struct GNUNET_CONVERSATION_Caller *caller) * @param mic microphone to use */ void -GNUNET_CONVERSATION_caller_resume (struct GNUNET_CONVERSATION_Caller *caller, - struct GNUNET_SPEAKER_Handle *speaker, - struct GNUNET_MICROPHONE_Handle *mic) +GNUNET_CONVERSATION_caller_resume(struct GNUNET_CONVERSATION_Caller *caller, + struct GNUNET_SPEAKER_Handle *speaker, + struct GNUNET_MICROPHONE_Handle *mic) { struct GNUNET_CONVERSATION_Phone *phone = caller->phone; struct GNUNET_MQ_Envelope *e; struct ClientPhoneResumeMessage *resume; - GNUNET_assert ( (CS_CALLEE_SUSPENDED == caller->state) || - (CS_BOTH_SUSPENDED == caller->state) ); + GNUNET_assert((CS_CALLEE_SUSPENDED == caller->state) || + (CS_BOTH_SUSPENDED == caller->state)); caller->speaker = speaker; caller->mic = mic; - e = GNUNET_MQ_msg (resume, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME); + e = GNUNET_MQ_msg(resume, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME); resume->cid = caller->cid; - GNUNET_MQ_send (phone->mq, - e); + GNUNET_MQ_send(phone->mq, + e); if (CS_CALLEE_SUSPENDED == caller->state) - { - caller->state = CS_ACTIVE; - caller->speaker->enable_speaker (caller->speaker->cls); - caller->mic->enable_microphone (caller->mic->cls, - &transmit_phone_audio, - caller); - } + { + caller->state = CS_ACTIVE; + caller->speaker->enable_speaker(caller->speaker->cls); + caller->mic->enable_microphone(caller->mic->cls, + &transmit_phone_audio, + caller); + } else - { - caller->state = CS_CALLER_SUSPENDED; - } + { + caller->state = CS_CALLER_SUSPENDED; + } } /* end of conversation_api.c */ diff --git a/src/conversation/conversation_api_call.c b/src/conversation/conversation_api_call.c index 5353c3e2d..08fab57b4 100644 --- a/src/conversation/conversation_api_call.c +++ b/src/conversation/conversation_api_call.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet - Copyright (C) 2013, 2016 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet + Copyright (C) 2013, 2016 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -35,8 +35,7 @@ /** * Possible states of the phone. */ -enum CallState -{ +enum CallState { /** * We still need to lookup the callee. */ @@ -77,9 +76,7 @@ enum CallState /** * Handle for an outgoing call. */ -struct GNUNET_CONVERSATION_Call -{ - +struct GNUNET_CONVERSATION_Call { /** * Our configuration. */ @@ -139,7 +136,6 @@ struct GNUNET_CONVERSATION_Call * State machine for the call. */ enum CallState state; - }; @@ -149,7 +145,7 @@ struct GNUNET_CONVERSATION_Call * @param call call to reconnect */ static void -fail_call (struct GNUNET_CONVERSATION_Call *call); +fail_call(struct GNUNET_CONVERSATION_Call *call); /** @@ -160,23 +156,23 @@ fail_call (struct GNUNET_CONVERSATION_Call *call); * @param data audio data to play */ static void -transmit_call_audio (void *cls, - size_t data_size, - const void *data) +transmit_call_audio(void *cls, + size_t data_size, + const void *data) { struct GNUNET_CONVERSATION_Call *call = cls; struct GNUNET_MQ_Envelope *e; struct ClientAudioMessage *am; - GNUNET_assert (CS_ACTIVE == call->state); - e = GNUNET_MQ_msg_extra (am, - data_size, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO); - GNUNET_memcpy (&am[1], - data, - data_size); - GNUNET_MQ_send (call->mq, - e); + GNUNET_assert(CS_ACTIVE == call->state); + e = GNUNET_MQ_msg_extra(am, + data_size, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO); + GNUNET_memcpy(&am[1], + data, + data_size); + GNUNET_MQ_send(call->mq, + e); } @@ -187,42 +183,47 @@ transmit_call_audio (void *cls, * @param msg the message */ static void -handle_call_suspend (void *cls, - const struct ClientPhoneSuspendMessage *msg) +handle_call_suspend(void *cls, + const struct ClientPhoneSuspendMessage *msg) { struct GNUNET_CONVERSATION_Call *call = cls; - (void) msg; + (void)msg; switch (call->state) - { - case CS_LOOKUP: - GNUNET_break (0); - fail_call (call); - break; - case CS_RINGING: - GNUNET_break_op (0); - fail_call (call); - break; - case CS_SUSPENDED_CALLER: - call->state = CS_SUSPENDED_BOTH; - call->event_handler (call->event_handler_cls, - GNUNET_CONVERSATION_EC_CALL_SUSPENDED); - break; - case CS_SUSPENDED_CALLEE: - case CS_SUSPENDED_BOTH: - GNUNET_break_op (0); - break; - case CS_ACTIVE: - call->state = CS_SUSPENDED_CALLEE; - call->speaker->disable_speaker (call->speaker->cls); - call->mic->disable_microphone (call->mic->cls); - call->event_handler (call->event_handler_cls, - GNUNET_CONVERSATION_EC_CALL_SUSPENDED); - break; - case CS_SHUTDOWN: - GNUNET_CONVERSATION_call_stop (call); - break; - } + { + case CS_LOOKUP: + GNUNET_break(0); + fail_call(call); + break; + + case CS_RINGING: + GNUNET_break_op(0); + fail_call(call); + break; + + case CS_SUSPENDED_CALLER: + call->state = CS_SUSPENDED_BOTH; + call->event_handler(call->event_handler_cls, + GNUNET_CONVERSATION_EC_CALL_SUSPENDED); + break; + + case CS_SUSPENDED_CALLEE: + case CS_SUSPENDED_BOTH: + GNUNET_break_op(0); + break; + + case CS_ACTIVE: + call->state = CS_SUSPENDED_CALLEE; + call->speaker->disable_speaker(call->speaker->cls); + call->mic->disable_microphone(call->mic->cls); + call->event_handler(call->event_handler_cls, + GNUNET_CONVERSATION_EC_CALL_SUSPENDED); + break; + + case CS_SHUTDOWN: + GNUNET_CONVERSATION_call_stop(call); + break; + } } @@ -233,46 +234,52 @@ handle_call_suspend (void *cls, * @param msg the message */ static void -handle_call_resume (void *cls, - const struct ClientPhoneResumeMessage *msg) +handle_call_resume(void *cls, + const struct ClientPhoneResumeMessage *msg) { struct GNUNET_CONVERSATION_Call *call = cls; - (void) msg; + (void)msg; switch (call->state) - { - case CS_LOOKUP: - GNUNET_break (0); - fail_call (call); - break; - case CS_RINGING: - GNUNET_break_op (0); - fail_call (call); - break; - case CS_SUSPENDED_CALLER: - GNUNET_break_op (0); - break; - case CS_SUSPENDED_CALLEE: - call->state = CS_ACTIVE; - call->speaker->enable_speaker (call->speaker->cls); - call->mic->enable_microphone (call->mic->cls, - &transmit_call_audio, - call); - call->event_handler (call->event_handler_cls, - GNUNET_CONVERSATION_EC_CALL_RESUMED); - break; - case CS_SUSPENDED_BOTH: - call->state = CS_SUSPENDED_CALLER; - call->event_handler (call->event_handler_cls, - GNUNET_CONVERSATION_EC_CALL_RESUMED); - break; - case CS_ACTIVE: - GNUNET_break_op (0); - break; - case CS_SHUTDOWN: - GNUNET_CONVERSATION_call_stop (call); - break; - } + { + case CS_LOOKUP: + GNUNET_break(0); + fail_call(call); + break; + + case CS_RINGING: + GNUNET_break_op(0); + fail_call(call); + break; + + case CS_SUSPENDED_CALLER: + GNUNET_break_op(0); + break; + + case CS_SUSPENDED_CALLEE: + call->state = CS_ACTIVE; + call->speaker->enable_speaker(call->speaker->cls); + call->mic->enable_microphone(call->mic->cls, + &transmit_call_audio, + call); + call->event_handler(call->event_handler_cls, + GNUNET_CONVERSATION_EC_CALL_RESUMED); + break; + + case CS_SUSPENDED_BOTH: + call->state = CS_SUSPENDED_CALLER; + call->event_handler(call->event_handler_cls, + GNUNET_CONVERSATION_EC_CALL_RESUMED); + break; + + case CS_ACTIVE: + GNUNET_break_op(0); + break; + + case CS_SHUTDOWN: + GNUNET_CONVERSATION_call_stop(call); + break; + } } @@ -283,38 +290,41 @@ handle_call_resume (void *cls, * @param msg the message */ static void -handle_call_picked_up (void *cls, - const struct ClientPhonePickedupMessage *msg) +handle_call_picked_up(void *cls, + const struct ClientPhonePickedupMessage *msg) { struct GNUNET_CONVERSATION_Call *call = cls; - (void) msg; + (void)msg; switch (call->state) - { - case CS_LOOKUP: - GNUNET_break (0); - fail_call (call); - break; - case CS_RINGING: - call->state = CS_ACTIVE; - call->speaker->enable_speaker (call->speaker->cls); - call->mic->enable_microphone (call->mic->cls, - &transmit_call_audio, - call); - call->event_handler (call->event_handler_cls, - GNUNET_CONVERSATION_EC_CALL_PICKED_UP); - break; - case CS_SUSPENDED_CALLER: - case CS_SUSPENDED_CALLEE: - case CS_SUSPENDED_BOTH: - case CS_ACTIVE: - GNUNET_break (0); - fail_call (call); - break; - case CS_SHUTDOWN: - GNUNET_CONVERSATION_call_stop (call); - break; - } + { + case CS_LOOKUP: + GNUNET_break(0); + fail_call(call); + break; + + case CS_RINGING: + call->state = CS_ACTIVE; + call->speaker->enable_speaker(call->speaker->cls); + call->mic->enable_microphone(call->mic->cls, + &transmit_call_audio, + call); + call->event_handler(call->event_handler_cls, + GNUNET_CONVERSATION_EC_CALL_PICKED_UP); + break; + + case CS_SUSPENDED_CALLER: + case CS_SUSPENDED_CALLEE: + case CS_SUSPENDED_BOTH: + case CS_ACTIVE: + GNUNET_break(0); + fail_call(call); + break; + + case CS_SHUTDOWN: + GNUNET_CONVERSATION_call_stop(call); + break; + } } @@ -325,35 +335,37 @@ handle_call_picked_up (void *cls, * @param msg the message */ static void -handle_call_hangup (void *cls, - const struct ClientPhoneHangupMessage *msg) +handle_call_hangup(void *cls, + const struct ClientPhoneHangupMessage *msg) { struct GNUNET_CONVERSATION_Call *call = cls; GNUNET_CONVERSATION_CallEventHandler eh; void *eh_cls; - (void) msg; + (void)msg; switch (call->state) - { - case CS_LOOKUP: - GNUNET_break (0); - fail_call (call); - break; - case CS_RINGING: - case CS_SUSPENDED_CALLER: - case CS_SUSPENDED_CALLEE: - case CS_SUSPENDED_BOTH: - case CS_ACTIVE: - eh = call->event_handler; - eh_cls = call->event_handler_cls; - GNUNET_CONVERSATION_call_stop (call); - eh (eh_cls, - GNUNET_CONVERSATION_EC_CALL_HUNG_UP); - return; - case CS_SHUTDOWN: - GNUNET_CONVERSATION_call_stop (call); - break; - } + { + case CS_LOOKUP: + GNUNET_break(0); + fail_call(call); + break; + + case CS_RINGING: + case CS_SUSPENDED_CALLER: + case CS_SUSPENDED_CALLEE: + case CS_SUSPENDED_BOTH: + case CS_ACTIVE: + eh = call->event_handler; + eh_cls = call->event_handler_cls; + GNUNET_CONVERSATION_call_stop(call); + eh(eh_cls, + GNUNET_CONVERSATION_EC_CALL_HUNG_UP); + return; + + case CS_SHUTDOWN: + GNUNET_CONVERSATION_call_stop(call); + break; + } } @@ -365,11 +377,11 @@ handle_call_hangup (void *cls, * @return #GNUNET_OK (always well-formed) */ static int -check_call_audio (void *cls, - const struct ClientAudioMessage *am) +check_call_audio(void *cls, + const struct ClientAudioMessage *am) { - (void) cls; - (void) am; + (void)cls; + (void)am; /* any payload is OK */ return GNUNET_OK; } @@ -382,39 +394,44 @@ check_call_audio (void *cls, * @param msg the message */ static void -handle_call_audio (void *cls, - const struct ClientAudioMessage *am) +handle_call_audio(void *cls, + const struct ClientAudioMessage *am) { struct GNUNET_CONVERSATION_Call *call = cls; switch (call->state) - { - case CS_LOOKUP: - GNUNET_break (0); - fail_call (call); - break; - case CS_RINGING: - GNUNET_break (0); - fail_call (call); - break; - case CS_SUSPENDED_CALLER: - /* can happen: we suspended, other peer did not yet - learn about this. */ - break; - case CS_SUSPENDED_CALLEE: - case CS_SUSPENDED_BOTH: - /* can (rarely) also happen: other peer suspended, but cadet might - have had delayed data on the unreliable channel */ - break; - case CS_ACTIVE: - call->speaker->play (call->speaker->cls, - ntohs (am->header.size) - sizeof (struct ClientAudioMessage), - &am[1]); - break; - case CS_SHUTDOWN: - GNUNET_CONVERSATION_call_stop (call); - break; - } + { + case CS_LOOKUP: + GNUNET_break(0); + fail_call(call); + break; + + case CS_RINGING: + GNUNET_break(0); + fail_call(call); + break; + + case CS_SUSPENDED_CALLER: + /* can happen: we suspended, other peer did not yet + learn about this. */ + break; + + case CS_SUSPENDED_CALLEE: + case CS_SUSPENDED_BOTH: + /* can (rarely) also happen: other peer suspended, but cadet might + have had delayed data on the unreliable channel */ + break; + + case CS_ACTIVE: + call->speaker->play(call->speaker->cls, + ntohs(am->header.size) - sizeof(struct ClientAudioMessage), + &am[1]); + break; + + case CS_SHUTDOWN: + GNUNET_CONVERSATION_call_stop(call); + break; + } } @@ -427,48 +444,48 @@ handle_call_audio (void *cls, * @param rd the records in reply */ static void -handle_gns_response (void *cls, - int was_gns, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +handle_gns_response(void *cls, + int was_gns, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_CONVERSATION_Call *call = cls; struct GNUNET_MQ_Envelope *e; struct ClientCallMessage *ccm; - (void) was_gns; - GNUNET_break (NULL != call->gns_lookup); - GNUNET_break (CS_LOOKUP == call->state); + (void)was_gns; + GNUNET_break(NULL != call->gns_lookup); + GNUNET_break(CS_LOOKUP == call->state); call->gns_lookup = NULL; - for (uint32_t i=0;iphone_record, - rd[i].data, - rd[i].data_size); - e = GNUNET_MQ_msg (ccm, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_CALL); - ccm->line_port = call->phone_record.line_port; - ccm->target = call->phone_record.peer; - ccm->caller_id = *GNUNET_IDENTITY_ego_get_private_key (call->caller_id); - GNUNET_MQ_send (call->mq, - e); - call->state = CS_RINGING; - call->event_handler (call->event_handler_cls, - GNUNET_CONVERSATION_EC_CALL_RINGING); - return; + if (GNUNET_GNSRECORD_TYPE_PHONE == rd[i].record_type) + { + if (rd[i].data_size != sizeof(struct GNUNET_CONVERSATION_PhoneRecord)) + { + GNUNET_break_op(0); + continue; + } + GNUNET_memcpy(&call->phone_record, + rd[i].data, + rd[i].data_size); + e = GNUNET_MQ_msg(ccm, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_CALL); + ccm->line_port = call->phone_record.line_port; + ccm->target = call->phone_record.peer; + ccm->caller_id = *GNUNET_IDENTITY_ego_get_private_key(call->caller_id); + GNUNET_MQ_send(call->mq, + e); + call->state = CS_RINGING; + call->event_handler(call->event_handler_cls, + GNUNET_CONVERSATION_EC_CALL_RINGING); + return; + } } - } /* not found */ - call->event_handler (call->event_handler_cls, - GNUNET_CONVERSATION_EC_CALL_GNS_FAIL); - GNUNET_CONVERSATION_call_stop (call); + call->event_handler(call->event_handler_cls, + GNUNET_CONVERSATION_EC_CALL_GNS_FAIL); + GNUNET_CONVERSATION_call_stop(call); } @@ -479,20 +496,20 @@ handle_gns_response (void *cls, * @param error details about the error */ static void -call_error_handler (void *cls, - enum GNUNET_MQ_Error error) +call_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_CONVERSATION_Call *call = cls; - (void) error; + (void)error; if (CS_SHUTDOWN == call->state) - { - GNUNET_CONVERSATION_call_stop (call); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Connection to conversation service lost, trying to reconnect\n")); - fail_call (call); + { + GNUNET_CONVERSATION_call_stop(call); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Connection to conversation service lost, trying to reconnect\n")); + fail_call(call); } @@ -502,22 +519,22 @@ call_error_handler (void *cls, * @param call call to reconnect */ static void -fail_call (struct GNUNET_CONVERSATION_Call *call) +fail_call(struct GNUNET_CONVERSATION_Call *call) { if (CS_ACTIVE == call->state) - { - call->speaker->disable_speaker (call->speaker->cls); - call->mic->disable_microphone (call->mic->cls); - } + { + call->speaker->disable_speaker(call->speaker->cls); + call->mic->disable_microphone(call->mic->cls); + } if (NULL != call->mq) - { - GNUNET_MQ_destroy (call->mq); - call->mq = NULL; - } + { + GNUNET_MQ_destroy(call->mq); + call->mq = NULL; + } call->state = CS_SHUTDOWN; - call->event_handler (call->event_handler_cls, - GNUNET_CONVERSATION_EC_CALL_ERROR); - GNUNET_CONVERSATION_call_stop (call); + call->event_handler(call->event_handler_cls, + GNUNET_CONVERSATION_EC_CALL_ERROR); + GNUNET_CONVERSATION_call_stop(call); } @@ -537,76 +554,76 @@ fail_call (struct GNUNET_CONVERSATION_Call *call) * @return handle for the call, NULL on hard errors */ struct GNUNET_CONVERSATION_Call * -GNUNET_CONVERSATION_call_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_IDENTITY_Ego *caller_id, - const char *callee, - struct GNUNET_SPEAKER_Handle *speaker, - struct GNUNET_MICROPHONE_Handle *mic, - GNUNET_CONVERSATION_CallEventHandler event_handler, - void *event_handler_cls) +GNUNET_CONVERSATION_call_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_IDENTITY_Ego *caller_id, + const char *callee, + struct GNUNET_SPEAKER_Handle *speaker, + struct GNUNET_MICROPHONE_Handle *mic, + GNUNET_CONVERSATION_CallEventHandler event_handler, + void *event_handler_cls) { struct GNUNET_CONVERSATION_Call *call - = GNUNET_new (struct GNUNET_CONVERSATION_Call); + = GNUNET_new(struct GNUNET_CONVERSATION_Call); struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (call_suspend, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND, - struct ClientPhoneSuspendMessage, - call), - GNUNET_MQ_hd_fixed_size (call_resume, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME, - struct ClientPhoneResumeMessage, - call), - GNUNET_MQ_hd_fixed_size (call_picked_up, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_PICKED_UP, - struct ClientPhonePickedupMessage, - call), - GNUNET_MQ_hd_fixed_size (call_hangup, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP, - struct ClientPhoneHangupMessage, - call), - GNUNET_MQ_hd_var_size (call_audio, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO, - struct ClientAudioMessage, - call), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(call_suspend, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND, + struct ClientPhoneSuspendMessage, + call), + GNUNET_MQ_hd_fixed_size(call_resume, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME, + struct ClientPhoneResumeMessage, + call), + GNUNET_MQ_hd_fixed_size(call_picked_up, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_PICKED_UP, + struct ClientPhonePickedupMessage, + call), + GNUNET_MQ_hd_fixed_size(call_hangup, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP, + struct ClientPhoneHangupMessage, + call), + GNUNET_MQ_hd_var_size(call_audio, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO, + struct ClientAudioMessage, + call), + GNUNET_MQ_handler_end() }; - call->mq = GNUNET_CLIENT_connect (cfg, - "conversation", - handlers, - &call_error_handler, - call); + call->mq = GNUNET_CLIENT_connect(cfg, + "conversation", + handlers, + &call_error_handler, + call); if (NULL == call->mq) - { - GNUNET_break (0); - GNUNET_free (call); - return NULL; - } + { + GNUNET_break(0); + GNUNET_free(call); + return NULL; + } call->cfg = cfg; call->caller_id = caller_id; - call->callee = GNUNET_strdup (callee); + call->callee = GNUNET_strdup(callee); call->speaker = speaker; call->mic = mic; call->event_handler = event_handler; call->event_handler_cls = event_handler_cls; - call->gns = GNUNET_GNS_connect (cfg); + call->gns = GNUNET_GNS_connect(cfg); if (NULL == call->gns) - { - GNUNET_CONVERSATION_call_stop (call); - return NULL; - } + { + GNUNET_CONVERSATION_call_stop(call); + return NULL; + } call->state = CS_LOOKUP; - call->gns_lookup = GNUNET_GNS_lookup_with_tld (call->gns, - call->callee, - GNUNET_GNSRECORD_TYPE_PHONE, - GNUNET_NO, - &handle_gns_response, - call); + call->gns_lookup = GNUNET_GNS_lookup_with_tld(call->gns, + call->callee, + GNUNET_GNSRECORD_TYPE_PHONE, + GNUNET_NO, + &handle_gns_response, + call); if (NULL == call->gns_lookup) - { - GNUNET_CONVERSATION_call_stop (call); - return NULL; - } + { + GNUNET_CONVERSATION_call_stop(call); + return NULL; + } return call; } @@ -617,35 +634,35 @@ GNUNET_CONVERSATION_call_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param call call to terminate */ void -GNUNET_CONVERSATION_call_stop (struct GNUNET_CONVERSATION_Call *call) +GNUNET_CONVERSATION_call_stop(struct GNUNET_CONVERSATION_Call *call) { - if ( (NULL != call->speaker) && - (CS_ACTIVE == call->state) ) - call->speaker->disable_speaker (call->speaker->cls); - if ( (NULL != call->mic) && - (CS_ACTIVE == call->state) ) - call->mic->disable_microphone (call->mic->cls); + if ((NULL != call->speaker) && + (CS_ACTIVE == call->state)) + call->speaker->disable_speaker(call->speaker->cls); + if ((NULL != call->mic) && + (CS_ACTIVE == call->state)) + call->mic->disable_microphone(call->mic->cls); if (CS_SHUTDOWN != call->state) - { - call->state = CS_SHUTDOWN; - } + { + call->state = CS_SHUTDOWN; + } if (NULL != call->mq) - { - GNUNET_MQ_destroy (call->mq); - call->mq = NULL; - } + { + GNUNET_MQ_destroy(call->mq); + call->mq = NULL; + } if (NULL != call->gns_lookup) - { - GNUNET_GNS_lookup_with_tld_cancel (call->gns_lookup); - call->gns_lookup = NULL; - } + { + GNUNET_GNS_lookup_with_tld_cancel(call->gns_lookup); + call->gns_lookup = NULL; + } if (NULL != call->gns) - { - GNUNET_GNS_disconnect (call->gns); - call->gns = NULL; - } - GNUNET_free (call->callee); - GNUNET_free (call); + { + GNUNET_GNS_disconnect(call->gns); + call->gns = NULL; + } + GNUNET_free(call->callee); + GNUNET_free(call); } @@ -656,24 +673,24 @@ GNUNET_CONVERSATION_call_stop (struct GNUNET_CONVERSATION_Call *call) * @param call call to pause */ void -GNUNET_CONVERSATION_call_suspend (struct GNUNET_CONVERSATION_Call *call) +GNUNET_CONVERSATION_call_suspend(struct GNUNET_CONVERSATION_Call *call) { struct GNUNET_MQ_Envelope *e; struct ClientPhoneSuspendMessage *suspend; - GNUNET_assert ( (CS_SUSPENDED_CALLEE == call->state) || - (CS_ACTIVE == call->state) ); + GNUNET_assert((CS_SUSPENDED_CALLEE == call->state) || + (CS_ACTIVE == call->state)); if (CS_ACTIVE == call->state) - { - call->speaker->disable_speaker (call->speaker->cls); - call->mic->disable_microphone (call->mic->cls); - } + { + call->speaker->disable_speaker(call->speaker->cls); + call->mic->disable_microphone(call->mic->cls); + } call->speaker = NULL; call->mic = NULL; - e = GNUNET_MQ_msg (suspend, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND); - GNUNET_MQ_send (call->mq, - e); + e = GNUNET_MQ_msg(suspend, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND); + GNUNET_MQ_send(call->mq, + e); if (CS_SUSPENDED_CALLER == call->state) call->state = CS_SUSPENDED_BOTH; else @@ -690,31 +707,31 @@ GNUNET_CONVERSATION_call_suspend (struct GNUNET_CONVERSATION_Call *call) * @param mic microphone to use */ void -GNUNET_CONVERSATION_call_resume (struct GNUNET_CONVERSATION_Call *call, - struct GNUNET_SPEAKER_Handle *speaker, - struct GNUNET_MICROPHONE_Handle *mic) +GNUNET_CONVERSATION_call_resume(struct GNUNET_CONVERSATION_Call *call, + struct GNUNET_SPEAKER_Handle *speaker, + struct GNUNET_MICROPHONE_Handle *mic) { struct GNUNET_MQ_Envelope *e; struct ClientPhoneResumeMessage *resume; - GNUNET_assert ( (CS_SUSPENDED_CALLER == call->state) || - (CS_SUSPENDED_BOTH == call->state) ); - e = GNUNET_MQ_msg (resume, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME); - GNUNET_MQ_send (call->mq, e); + GNUNET_assert((CS_SUSPENDED_CALLER == call->state) || + (CS_SUSPENDED_BOTH == call->state)); + e = GNUNET_MQ_msg(resume, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME); + GNUNET_MQ_send(call->mq, e); call->speaker = speaker; call->mic = mic; if (CS_SUSPENDED_CALLER == call->state) - { - call->state = CS_ACTIVE; - call->speaker->enable_speaker (call->speaker->cls); - call->mic->enable_microphone (call->mic->cls, - &transmit_call_audio, - call); - } + { + call->state = CS_ACTIVE; + call->speaker->enable_speaker(call->speaker->cls); + call->mic->enable_microphone(call->mic->cls, + &transmit_call_audio, + call); + } else - { - call->state = CS_SUSPENDED_CALLEE; - } + { + call->state = CS_SUSPENDED_CALLEE; + } } diff --git a/src/conversation/gnunet-conversation-test.c b/src/conversation/gnunet-conversation-test.c index 201156f7f..871058233 100644 --- a/src/conversation/gnunet-conversation-test.c +++ b/src/conversation/gnunet-conversation-test.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/gnunet-conversation-test.c @@ -31,14 +31,13 @@ /** * How long do we record before we replay? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) /** * A recording we made. */ -struct Recording -{ +struct Recording { /** * Kept in a DLL. */ @@ -98,26 +97,26 @@ static struct Recording *rec_tail; * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { struct Recording *rec; - (void) cls; + (void)cls; if (NULL != switch_task) - GNUNET_SCHEDULER_cancel (switch_task); + GNUNET_SCHEDULER_cancel(switch_task); if (NULL != microphone) - GNUNET_MICROPHONE_destroy (microphone); + GNUNET_MICROPHONE_destroy(microphone); if (NULL != speaker) - GNUNET_SPEAKER_destroy (speaker); + GNUNET_SPEAKER_destroy(speaker); while (NULL != (rec = rec_head)) - { - GNUNET_CONTAINER_DLL_remove (rec_head, - rec_tail, - rec); - GNUNET_free (rec); - } - fprintf (stderr, - _("\nEnd of transmission. Have a GNU day.\n")); + { + GNUNET_CONTAINER_DLL_remove(rec_head, + rec_tail, + rec); + GNUNET_free(rec); + } + fprintf(stderr, + _("\nEnd of transmission. Have a GNU day.\n")); } @@ -127,35 +126,35 @@ do_shutdown (void *cls) * @param cls NULL */ static void -switch_to_speaker (void *cls) +switch_to_speaker(void *cls) { - (void) cls; + (void)cls; switch_task = NULL; - microphone->disable_microphone (microphone->cls); + microphone->disable_microphone(microphone->cls); if (GNUNET_OK != - speaker->enable_speaker (speaker->cls)) - { - fprintf (stderr, - "Failed to enable microphone\n"); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } - fprintf (stderr, - _("\nWe are now playing your recording back. If you can hear it, your audio settings are working...")); - for (struct Recording *rec=rec_head; NULL != rec; rec = rec->next) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Replaying %u bytes\n", - (unsigned int) rec->size); - speaker->play (speaker->cls, - rec->size, - &rec[1]); - } - GNUNET_SCHEDULER_cancel (st); - st = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &do_shutdown, - NULL); + speaker->enable_speaker(speaker->cls)) + { + fprintf(stderr, + "Failed to enable microphone\n"); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } + fprintf(stderr, + _("\nWe are now playing your recording back. If you can hear it, your audio settings are working...")); + for (struct Recording *rec = rec_head; NULL != rec; rec = rec->next) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Replaying %u bytes\n", + (unsigned int)rec->size); + speaker->play(speaker->cls, + rec->size, + &rec[1]); + } + GNUNET_SCHEDULER_cancel(st); + st = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &do_shutdown, + NULL); } @@ -167,22 +166,22 @@ switch_to_speaker (void *cls) * @param data audio data to play */ static void -record (void *cls, - size_t data_size, - const void *data) +record(void *cls, + size_t data_size, + const void *data) { struct Recording *rec; - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Recorded %u bytes\n", - (unsigned int) data_size); - rec = GNUNET_malloc (sizeof (struct Recording) + data_size); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Recorded %u bytes\n", + (unsigned int)data_size); + rec = GNUNET_malloc(sizeof(struct Recording) + data_size); rec->size = data_size; - GNUNET_memcpy (&rec[1], data, data_size); - GNUNET_CONTAINER_DLL_insert_tail (rec_head, - rec_tail, - rec); + GNUNET_memcpy(&rec[1], data, data_size); + GNUNET_CONTAINER_DLL_insert_tail(rec_head, + rec_tail, + rec); } @@ -195,36 +194,36 @@ record (void *cls, * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - (void) cls; - (void) args; - (void) cfgfile; - microphone = GNUNET_MICROPHONE_create_from_hardware (cfg); - GNUNET_assert (NULL != microphone); - speaker = GNUNET_SPEAKER_create_from_hardware (cfg); - GNUNET_assert (NULL != speaker); - switch_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &switch_to_speaker, - NULL); - st = GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - fprintf (stderr, - _("We will now be recording you for %s. After that time, the recording will be played back to you..."), - GNUNET_STRINGS_relative_time_to_string (TIMEOUT, GNUNET_YES)); + (void)cls; + (void)args; + (void)cfgfile; + microphone = GNUNET_MICROPHONE_create_from_hardware(cfg); + GNUNET_assert(NULL != microphone); + speaker = GNUNET_SPEAKER_create_from_hardware(cfg); + GNUNET_assert(NULL != speaker); + switch_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &switch_to_speaker, + NULL); + st = GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); + fprintf(stderr, + _("We will now be recording you for %s. After that time, the recording will be played back to you..."), + GNUNET_STRINGS_relative_time_to_string(TIMEOUT, GNUNET_YES)); if (GNUNET_OK != - microphone->enable_microphone (microphone->cls, - &record, NULL)) - { - fprintf (stderr, - "Failed to enable microphone\n"); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } + microphone->enable_microphone(microphone->cls, + &record, NULL)) + { + fprintf(stderr, + "Failed to enable microphone\n"); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } } @@ -236,26 +235,26 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, - char *const *argv) +main(int argc, + char *const *argv) { static const struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; - + if (GNUNET_OK != - GNUNET_STRINGS_get_utf8_args (argc, argv, - &argc, &argv)) + GNUNET_STRINGS_get_utf8_args(argc, argv, + &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, - "gnunet-conversation-test", - gettext_noop ("help text"), - options, - &run, - NULL)) ? ret : 1; - GNUNET_free ((void*) argv); + GNUNET_PROGRAM_run(argc, argv, + "gnunet-conversation-test", + gettext_noop("help text"), + options, + &run, + NULL)) ? ret : 1; + GNUNET_free((void*)argv); return ret; } diff --git a/src/conversation/gnunet-conversation.c b/src/conversation/gnunet-conversation.c index 4c5407cd7..20765bbf6 100644 --- a/src/conversation/gnunet-conversation.c +++ b/src/conversation/gnunet-conversation.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet. - Copyright (C) 2013 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet. + Copyright (C) 2013 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/gnunet-conversation.c * @brief conversation implementation @@ -38,7 +38,7 @@ */ #define MAX_MESSAGE_LENGTH 1024 -#define XSTRINGIFY(x) STRINGIFY (x) +#define XSTRINGIFY(x) STRINGIFY(x) #define STRINGIFY(x) (#x) @@ -52,8 +52,7 @@ struct GNUNET_HELPER_Handle *stdin_hlp; /** * Possible states of the phone. */ -enum PhoneState -{ +enum PhoneState { /** * We're waiting for our own idenitty. */ @@ -79,8 +78,7 @@ enum PhoneState /** * States for current outgoing call. */ -enum CallState -{ +enum CallState { /** * We are looking up some other participant. */ @@ -100,16 +98,13 @@ enum CallState * The call is currently suspended (by us). */ CS_SUSPENDED - }; /** * List of incoming calls */ -struct CallList -{ - +struct CallList { /** * A DLL. */ @@ -253,63 +248,64 @@ static int verbose; * @param caller_id public key of the caller (in GNS) */ static void -phone_event_handler (void *cls, - enum GNUNET_CONVERSATION_PhoneEventCode code, - struct GNUNET_CONVERSATION_Caller *caller, - const struct GNUNET_CRYPTO_EcdsaPublicKey *caller_id) +phone_event_handler(void *cls, + enum GNUNET_CONVERSATION_PhoneEventCode code, + struct GNUNET_CONVERSATION_Caller *caller, + const struct GNUNET_CRYPTO_EcdsaPublicKey *caller_id) { struct CallList *cl; - (void) cls; + (void)cls; switch (code) - { - case GNUNET_CONVERSATION_EC_PHONE_RING: - /* - * FIXME: we should be playing our ringtones from contrib/sounds now! - * - ring_my_bell(); - * - * see https://gstreamer.freedesktop.org/documentation/application-development/highlevel/playback-components.html on how to play a wav using the gst framework being used here - */ - fprintf ( - stdout, - _ ( - "Incoming call from `%s'. Please /accept %u or /cancel %u the call.\n"), - GNUNET_GNSRECORD_pkey_to_zkey (caller_id), - caller_num_gen, - caller_num_gen); - cl = GNUNET_new (struct CallList); - cl->caller = caller; - cl->caller_id = *caller_id; - cl->caller_num = caller_num_gen++; - GNUNET_CONTAINER_DLL_insert (cl_head, cl_tail, cl); - break; - case GNUNET_CONVERSATION_EC_PHONE_HUNG_UP: - for (cl = cl_head; NULL != cl; cl = cl->next) - if (caller == cl->caller) - break; - if ((NULL == cl) && (caller == cl_active->caller)) - cl = cl_active; - if (NULL == cl) - { - GNUNET_break (0); - return; - } - fprintf (stdout, - _ ("Call from `%s' terminated\n"), - GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id)); - if (cl == cl_active) { - cl_active = NULL; - phone_state = PS_LISTEN; - } - else - { - GNUNET_CONTAINER_DLL_remove (cl_head, cl_tail, cl); + case GNUNET_CONVERSATION_EC_PHONE_RING: + /* + * FIXME: we should be playing our ringtones from contrib/sounds now! + * + ring_my_bell(); + * + * see https://gstreamer.freedesktop.org/documentation/application-development/highlevel/playback-components.html on how to play a wav using the gst framework being used here + */ + fprintf( + stdout, + _( + "Incoming call from `%s'. Please /accept %u or /cancel %u the call.\n"), + GNUNET_GNSRECORD_pkey_to_zkey(caller_id), + caller_num_gen, + caller_num_gen); + cl = GNUNET_new(struct CallList); + cl->caller = caller; + cl->caller_id = *caller_id; + cl->caller_num = caller_num_gen++; + GNUNET_CONTAINER_DLL_insert(cl_head, cl_tail, cl); + break; + + case GNUNET_CONVERSATION_EC_PHONE_HUNG_UP: + for (cl = cl_head; NULL != cl; cl = cl->next) + if (caller == cl->caller) + break; + if ((NULL == cl) && (caller == cl_active->caller)) + cl = cl_active; + if (NULL == cl) + { + GNUNET_break(0); + return; + } + fprintf(stdout, + _("Call from `%s' terminated\n"), + GNUNET_GNSRECORD_pkey_to_zkey(&cl->caller_id)); + if (cl == cl_active) + { + cl_active = NULL; + phone_state = PS_LISTEN; + } + else + { + GNUNET_CONTAINER_DLL_remove(cl_head, cl_tail, cl); + } + GNUNET_free(cl); + break; } - GNUNET_free (cl); - break; - } } @@ -320,23 +316,24 @@ phone_event_handler (void *cls, * @param code type of the event issued by the caller */ static void -caller_event_handler (void *cls, enum GNUNET_CONVERSATION_CallerEventCode code) +caller_event_handler(void *cls, enum GNUNET_CONVERSATION_CallerEventCode code) { struct CallList *cl = cls; switch (code) - { - case GNUNET_CONVERSATION_EC_CALLER_SUSPEND: - fprintf (stdout, - _ ("Call from `%s' suspended by other user\n"), - GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id)); - break; - case GNUNET_CONVERSATION_EC_CALLER_RESUME: - fprintf (stdout, - _ ("Call from `%s' resumed by other user\n"), - GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id)); - break; - } + { + case GNUNET_CONVERSATION_EC_CALLER_SUSPEND: + fprintf(stdout, + _("Call from `%s' suspended by other user\n"), + GNUNET_GNSRECORD_pkey_to_zkey(&cl->caller_id)); + break; + + case GNUNET_CONVERSATION_EC_CALLER_RESUME: + fprintf(stdout, + _("Call from `%s' resumed by other user\n"), + GNUNET_GNSRECORD_pkey_to_zkey(&cl->caller_id)); + break; + } } @@ -344,42 +341,42 @@ caller_event_handler (void *cls, enum GNUNET_CONVERSATION_CallerEventCode code) * Start our phone. */ static void -start_phone () +start_phone() { struct GNUNET_GNSRECORD_Data rd; if (NULL == my_caller_id) - { - fprintf (stderr, - _ ("Ego `%s' no longer available, phone is now down.\n"), - ego_name); - phone_state = PS_LOOKUP_EGO; - return; - } - GNUNET_assert (NULL == phone); - phone = GNUNET_CONVERSATION_phone_create (cfg, - my_caller_id, - &phone_event_handler, - NULL); + { + fprintf(stderr, + _("Ego `%s' no longer available, phone is now down.\n"), + ego_name); + phone_state = PS_LOOKUP_EGO; + return; + } + GNUNET_assert(NULL == phone); + phone = GNUNET_CONVERSATION_phone_create(cfg, + my_caller_id, + &phone_event_handler, + NULL); /* FIXME: get record and print full GNS record info later here... */ if (NULL == phone) - { - fprintf (stderr, "%s", _ ("Failed to setup phone (internal error)\n")); - phone_state = PS_ERROR; - } + { + fprintf(stderr, "%s", _("Failed to setup phone (internal error)\n")); + phone_state = PS_ERROR; + } else - { - GNUNET_CONVERSATION_phone_get_record (phone, &rd); - GNUNET_free_non_null (address); - address = - GNUNET_GNSRECORD_value_to_string (rd.record_type, rd.data, rd.data_size); - fprintf ( - stdout, - _ ( - "Phone active at `%s'. Type `/help' for a list of available commands\n"), - address); - phone_state = PS_LISTEN; - } + { + GNUNET_CONVERSATION_phone_get_record(phone, &rd); + GNUNET_free_non_null(address); + address = + GNUNET_GNSRECORD_value_to_string(rd.record_type, rd.data, rd.data_size); + fprintf( + stdout, + _( + "Phone active at `%s'. Type `/help' for a list of available commands\n"), + address); + phone_state = PS_LISTEN; + } } @@ -390,56 +387,62 @@ start_phone () * @param code type of the event on the call */ static void -call_event_handler (void *cls, enum GNUNET_CONVERSATION_CallEventCode code) +call_event_handler(void *cls, enum GNUNET_CONVERSATION_CallEventCode code) { - (void) cls; + (void)cls; switch (code) - { - case GNUNET_CONVERSATION_EC_CALL_RINGING: - GNUNET_break (CS_RESOLVING == call_state); - fprintf (stdout, - _ ("Resolved address of `%s'. Now ringing other party.\n"), - peer_name); - call_state = CS_RINGING; - break; - case GNUNET_CONVERSATION_EC_CALL_PICKED_UP: - GNUNET_break (CS_RINGING == call_state); - fprintf (stdout, _ ("Connection established to `%s'\n"), peer_name); - call_state = CS_CONNECTED; - break; - case GNUNET_CONVERSATION_EC_CALL_GNS_FAIL: - GNUNET_break (CS_RESOLVING == call_state); - fprintf (stdout, _ ("Failed to resolve `%s'\n"), peer_name); - GNUNET_free (peer_name); - peer_name = NULL; - call = NULL; - break; - case GNUNET_CONVERSATION_EC_CALL_HUNG_UP: - fprintf (stdout, _ ("Call to `%s' terminated\n"), peer_name); - GNUNET_free (peer_name); - peer_name = NULL; - call = NULL; - break; - case GNUNET_CONVERSATION_EC_CALL_SUSPENDED: - GNUNET_break (CS_CONNECTED == call_state); - fprintf (stdout, - _ ("Connection to `%s' suspended (by other user)\n"), - peer_name); - break; - case GNUNET_CONVERSATION_EC_CALL_RESUMED: - GNUNET_break (CS_CONNECTED == call_state); - fprintf (stdout, - _ ("Connection to `%s' resumed (by other user)\n"), - peer_name); - break; - case GNUNET_CONVERSATION_EC_CALL_ERROR: - fprintf (stdout, _ ("Error with the call, restarting it\n")); - GNUNET_free (peer_name); - peer_name = NULL; - call = NULL; - break; - } + { + case GNUNET_CONVERSATION_EC_CALL_RINGING: + GNUNET_break(CS_RESOLVING == call_state); + fprintf(stdout, + _("Resolved address of `%s'. Now ringing other party.\n"), + peer_name); + call_state = CS_RINGING; + break; + + case GNUNET_CONVERSATION_EC_CALL_PICKED_UP: + GNUNET_break(CS_RINGING == call_state); + fprintf(stdout, _("Connection established to `%s'\n"), peer_name); + call_state = CS_CONNECTED; + break; + + case GNUNET_CONVERSATION_EC_CALL_GNS_FAIL: + GNUNET_break(CS_RESOLVING == call_state); + fprintf(stdout, _("Failed to resolve `%s'\n"), peer_name); + GNUNET_free(peer_name); + peer_name = NULL; + call = NULL; + break; + + case GNUNET_CONVERSATION_EC_CALL_HUNG_UP: + fprintf(stdout, _("Call to `%s' terminated\n"), peer_name); + GNUNET_free(peer_name); + peer_name = NULL; + call = NULL; + break; + + case GNUNET_CONVERSATION_EC_CALL_SUSPENDED: + GNUNET_break(CS_CONNECTED == call_state); + fprintf(stdout, + _("Connection to `%s' suspended (by other user)\n"), + peer_name); + break; + + case GNUNET_CONVERSATION_EC_CALL_RESUMED: + GNUNET_break(CS_CONNECTED == call_state); + fprintf(stdout, + _("Connection to `%s' resumed (by other user)\n"), + peer_name); + break; + + case GNUNET_CONVERSATION_EC_CALL_ERROR: + fprintf(stdout, _("Error with the call, restarting it\n")); + GNUNET_free(peer_name); + peer_name = NULL; + call = NULL; + break; + } } @@ -454,8 +457,7 @@ typedef void (*ActionFunction) (const char *arguments); /** * Structure which defines a command */ -struct VoipCommand -{ +struct VoipCommand { /** * Command the user needs to enter. */ @@ -479,7 +481,7 @@ struct VoipCommand * @param args arguments given to the command */ static void -do_help (const char *args); +do_help(const char *args); /** @@ -488,10 +490,10 @@ do_help (const char *args); * @param args arguments given to the command */ static void -do_quit (const char *args) +do_quit(const char *args) { - (void) args; - GNUNET_SCHEDULER_shutdown (); + (void)args; + GNUNET_SCHEDULER_shutdown(); } @@ -501,9 +503,9 @@ do_quit (const char *args) * @param msg arguments given to the command */ static void -do_unknown (const char *msg) +do_unknown(const char *msg) { - fprintf (stderr, _ ("Unknown command `%s'\n"), msg); + fprintf(stderr, _("Unknown command `%s'\n"), msg); } @@ -513,54 +515,57 @@ do_unknown (const char *msg) * @param arg arguments given to the command */ static void -do_call (const char *arg) +do_call(const char *arg) { if (NULL == my_caller_id) - { - fprintf (stderr, _ ("Ego `%s' not available\n"), ego_name); - return; - } + { + fprintf(stderr, _("Ego `%s' not available\n"), ego_name); + return; + } if (NULL != call) - { - fprintf (stderr, - _ ("You are calling someone else already, hang up first!\n")); - return; - } + { + fprintf(stderr, + _("You are calling someone else already, hang up first!\n")); + return; + } switch (phone_state) - { - case PS_LOOKUP_EGO: - fprintf (stderr, _ ("Ego `%s' not available\n"), ego_name); - return; - case PS_LISTEN: - /* ok to call! */ - break; - case PS_ACCEPTED: - fprintf ( - stderr, - _ ( - "You are answering call from `%s', hang up or suspend that call first!\n"), - GNUNET_GNSRECORD_pkey_to_zkey (&peer_key)); - return; - case PS_ERROR: - /* ok to call */ - break; - } + { + case PS_LOOKUP_EGO: + fprintf(stderr, _("Ego `%s' not available\n"), ego_name); + return; + + case PS_LISTEN: + /* ok to call! */ + break; + + case PS_ACCEPTED: + fprintf( + stderr, + _( + "You are answering call from `%s', hang up or suspend that call first!\n"), + GNUNET_GNSRECORD_pkey_to_zkey(&peer_key)); + return; + + case PS_ERROR: + /* ok to call */ + break; + } if (NULL == arg) - { - fprintf (stderr, _ ("Call recipient missing.\n")); - do_help ("/call"); - return; - } - peer_name = GNUNET_strdup (arg); + { + fprintf(stderr, _("Call recipient missing.\n")); + do_help("/call"); + return; + } + peer_name = GNUNET_strdup(arg); call_state = CS_RESOLVING; - GNUNET_assert (NULL == call); - call = GNUNET_CONVERSATION_call_start (cfg, - my_caller_id, - arg, - speaker, - mic, - &call_event_handler, - NULL); + GNUNET_assert(NULL == call); + call = GNUNET_CONVERSATION_call_start(cfg, + my_caller_id, + arg, + speaker, + mic, + &call_event_handler, + NULL); } @@ -570,67 +575,70 @@ do_call (const char *arg) * @param args arguments given to the command */ static void -do_accept (const char *args) +do_accept(const char *args) { struct CallList *cl; char buf[32]; if ((NULL != call) && (CS_SUSPENDED != call_state)) - { - fprintf (stderr, - _ ("You are calling someone else already, hang up first!\n")); - return; - } + { + fprintf(stderr, + _("You are calling someone else already, hang up first!\n")); + return; + } switch (phone_state) - { - case PS_LOOKUP_EGO: - GNUNET_break (0); - break; - case PS_LISTEN: - /* this is the expected state */ - break; - case PS_ACCEPTED: - fprintf ( - stderr, - _ ( - "You are answering call from `%s', hang up or suspend that call first!\n"), - GNUNET_GNSRECORD_pkey_to_zkey (&peer_key)); - return; - case PS_ERROR: - GNUNET_break (0); - break; - } + { + case PS_LOOKUP_EGO: + GNUNET_break(0); + break; + + case PS_LISTEN: + /* this is the expected state */ + break; + + case PS_ACCEPTED: + fprintf( + stderr, + _( + "You are answering call from `%s', hang up or suspend that call first!\n"), + GNUNET_GNSRECORD_pkey_to_zkey(&peer_key)); + return; + + case PS_ERROR: + GNUNET_break(0); + break; + } cl = cl_head; if (NULL == cl) - { - fprintf (stderr, _ ("There is no incoming call to accept here!\n")); - return; - } + { + fprintf(stderr, _("There is no incoming call to accept here!\n")); + return; + } if ((NULL != cl->next) || (NULL != args)) - { - for (cl = cl_head; NULL != cl; cl = cl->next) { - GNUNET_snprintf (buf, sizeof (buf), "%u", cl->caller_num); - if (0 == strcmp (buf, args)) - break; + for (cl = cl_head; NULL != cl; cl = cl->next) + { + GNUNET_snprintf(buf, sizeof(buf), "%u", cl->caller_num); + if (0 == strcmp(buf, args)) + break; + } } - } if (NULL == cl) - { - fprintf (stderr, - _ ("There is no incoming call `%s' to accept right now!\n"), - args); - return; - } - GNUNET_CONTAINER_DLL_remove (cl_head, cl_tail, cl); + { + fprintf(stderr, + _("There is no incoming call `%s' to accept right now!\n"), + args); + return; + } + GNUNET_CONTAINER_DLL_remove(cl_head, cl_tail, cl); cl_active = cl; peer_key = cl->caller_id; phone_state = PS_ACCEPTED; - GNUNET_CONVERSATION_caller_pick_up (cl->caller, - &caller_event_handler, - cl, - speaker, - mic); + GNUNET_CONVERSATION_caller_pick_up(cl->caller, + &caller_event_handler, + cl, + speaker, + mic); } @@ -640,15 +648,15 @@ do_accept (const char *args) * @param args arguments given to the command */ static void -do_address (const char *args) +do_address(const char *args) { - (void) args; + (void)args; if (NULL == address) - { - fprintf (stdout, "%s", _ ("We currently do not have an address.\n")); - return; - } - fprintf (stdout, "%s\n", address); + { + fprintf(stdout, "%s", _("We currently do not have an address.\n")); + return; + } + fprintf(stdout, "%s\n", address); } @@ -658,78 +666,84 @@ do_address (const char *args) * @param args arguments given to the command */ static void -do_status (const char *args) +do_status(const char *args) { struct CallList *cl; - (void) args; + (void)args; switch (phone_state) - { - case PS_LOOKUP_EGO: - fprintf ( - stdout, - _ ( - "We are currently trying to locate the private key for the ego `%s'.\n"), - ego_name); - break; - case PS_LISTEN: - fprintf (stdout, - _ ( - "We are listening for incoming calls for ego `%s' on line `%s'.\n"), - ego_name, - line); - break; - case PS_ACCEPTED: - fprintf (stdout, - _ ("You are having a conversation with `%s'.\n"), - GNUNET_GNSRECORD_pkey_to_zkey (&peer_key)); - ; - break; - case PS_ERROR: - fprintf ( - stdout, - _ ( - "We had an internal error setting up our phone line. You can still make calls.\n")); - break; - } - if (NULL != call) - { - switch (call_state) { - case CS_RESOLVING: - fprintf (stdout, - _ ("We are trying to find the network address to call `%s'.\n"), - peer_name); + case PS_LOOKUP_EGO: + fprintf( + stdout, + _( + "We are currently trying to locate the private key for the ego `%s'.\n"), + ego_name); break; - case CS_RINGING: - fprintf (stdout, - _ ("We are calling `%s', their phone should be ringing.\n"), - peer_name); + + case PS_LISTEN: + fprintf(stdout, + _( + "We are listening for incoming calls for ego `%s' on line `%s'.\n"), + ego_name, + line); break; - case CS_CONNECTED: - fprintf (stdout, - _ ("You are having a conversation with `%s'.\n"), - peer_name); + + case PS_ACCEPTED: + fprintf(stdout, + _("You are having a conversation with `%s'.\n"), + GNUNET_GNSRECORD_pkey_to_zkey(&peer_key)); + ; break; - case CS_SUSPENDED: - /* ok to accept incoming call right now */ + + case PS_ERROR: + fprintf( + stdout, + _( + "We had an internal error setting up our phone line. You can still make calls.\n")); break; } - } + if (NULL != call) + { + switch (call_state) + { + case CS_RESOLVING: + fprintf(stdout, + _("We are trying to find the network address to call `%s'.\n"), + peer_name); + break; + + case CS_RINGING: + fprintf(stdout, + _("We are calling `%s', their phone should be ringing.\n"), + peer_name); + break; + + case CS_CONNECTED: + fprintf(stdout, + _("You are having a conversation with `%s'.\n"), + peer_name); + break; + + case CS_SUSPENDED: + /* ok to accept incoming call right now */ + break; + } + } if ((NULL != cl_head) && ((cl_head != cl_active) || (cl_head != cl_tail))) - { - fprintf (stdout, "%s", _ ("Calls waiting:\n")); - for (cl = cl_head; NULL != cl; cl = cl->next) { - if (cl == cl_active) - continue; - fprintf (stdout, - _ ("#%u: `%s'\n"), - cl->caller_num, - GNUNET_GNSRECORD_pkey_to_zkey (&cl->caller_id)); + fprintf(stdout, "%s", _("Calls waiting:\n")); + for (cl = cl_head; NULL != cl; cl = cl->next) + { + if (cl == cl_active) + continue; + fprintf(stdout, + _("#%u: `%s'\n"), + cl->caller_num, + GNUNET_GNSRECORD_pkey_to_zkey(&cl->caller_id)); + } + fprintf(stdout, "%s", "\n"); } - fprintf (stdout, "%s", "\n"); - } } @@ -739,41 +753,43 @@ do_status (const char *args) * @param args arguments given to the command */ static void -do_suspend (const char *args) +do_suspend(const char *args) { - (void) args; + (void)args; if (NULL != call) - { - switch (call_state) { - case CS_RESOLVING: - case CS_RINGING: - case CS_SUSPENDED: - fprintf (stderr, - "%s", - _ ("There is no call that could be suspended right now.\n")); - return; - case CS_CONNECTED: - call_state = CS_SUSPENDED; - GNUNET_CONVERSATION_call_suspend (call); - return; + switch (call_state) + { + case CS_RESOLVING: + case CS_RINGING: + case CS_SUSPENDED: + fprintf(stderr, + "%s", + _("There is no call that could be suspended right now.\n")); + return; + + case CS_CONNECTED: + call_state = CS_SUSPENDED; + GNUNET_CONVERSATION_call_suspend(call); + return; + } } - } switch (phone_state) - { - case PS_LOOKUP_EGO: - case PS_LISTEN: - case PS_ERROR: - fprintf (stderr, - "%s", - _ ("There is no call that could be suspended right now.\n")); - return; - case PS_ACCEPTED: - /* expected state, do rejection logic */ - break; - } - GNUNET_assert (NULL != cl_active); - GNUNET_CONVERSATION_caller_suspend (cl_active->caller); + { + case PS_LOOKUP_EGO: + case PS_LISTEN: + case PS_ERROR: + fprintf(stderr, + "%s", + _("There is no call that could be suspended right now.\n")); + return; + + case PS_ACCEPTED: + /* expected state, do rejection logic */ + break; + } + GNUNET_assert(NULL != cl_active); + GNUNET_CONVERSATION_caller_suspend(cl_active->caller); cl_active = NULL; phone_state = PS_LISTEN; } @@ -785,70 +801,73 @@ do_suspend (const char *args) * @param args arguments given to the command */ static void -do_resume (const char *args) +do_resume(const char *args) { struct CallList *cl; char buf[32]; if (NULL != call) - { - switch (call_state) { - case CS_RESOLVING: - case CS_RINGING: - case CS_CONNECTED: - fprintf (stderr, - "%s", - _ ("There is no call that could be resumed right now.\n")); + switch (call_state) + { + case CS_RESOLVING: + case CS_RINGING: + case CS_CONNECTED: + fprintf(stderr, + "%s", + _("There is no call that could be resumed right now.\n")); + return; + + case CS_SUSPENDED: + call_state = CS_CONNECTED; + GNUNET_CONVERSATION_call_resume(call, speaker, mic); + return; + } + } + switch (phone_state) + { + case PS_LOOKUP_EGO: + case PS_ERROR: + fprintf(stderr, + "%s", + _("There is no call that could be resumed right now.\n")); return; - case CS_SUSPENDED: - call_state = CS_CONNECTED; - GNUNET_CONVERSATION_call_resume (call, speaker, mic); + + case PS_LISTEN: + /* expected state, do resume logic */ + break; + + case PS_ACCEPTED: + fprintf(stderr, + _("Already talking with `%s', cannot resume a call right now.\n"), + GNUNET_GNSRECORD_pkey_to_zkey(&peer_key)); return; } - } - switch (phone_state) - { - case PS_LOOKUP_EGO: - case PS_ERROR: - fprintf (stderr, - "%s", - _ ("There is no call that could be resumed right now.\n")); - return; - case PS_LISTEN: - /* expected state, do resume logic */ - break; - case PS_ACCEPTED: - fprintf (stderr, - _ ("Already talking with `%s', cannot resume a call right now.\n"), - GNUNET_GNSRECORD_pkey_to_zkey (&peer_key)); - return; - } - GNUNET_assert (NULL == cl_active); + GNUNET_assert(NULL == cl_active); cl = cl_head; if (NULL == cl) - { - fprintf (stderr, _ ("There is no incoming call to resume here!\n")); - return; - } + { + fprintf(stderr, _("There is no incoming call to resume here!\n")); + return; + } if ((NULL != cl->next) || (NULL != args)) - { - for (cl = cl_head; NULL != cl; cl = cl->next) { - GNUNET_snprintf (buf, sizeof (buf), "%u", cl->caller_num); - if (0 == strcmp (buf, args)) - break; + for (cl = cl_head; NULL != cl; cl = cl->next) + { + GNUNET_snprintf(buf, sizeof(buf), "%u", cl->caller_num); + if (0 == strcmp(buf, args)) + break; + } } - } if (NULL == cl) - { - fprintf (stderr, - _ ("There is no incoming call `%s' to resume right now!\n"), - args); - return; - } + { + fprintf(stderr, + _("There is no incoming call `%s' to resume right now!\n"), + args); + return; + } cl_active = cl; - GNUNET_CONVERSATION_caller_resume (cl_active->caller, speaker, mic); + GNUNET_CONVERSATION_caller_resume(cl_active->caller, speaker, mic); phone_state = PS_ACCEPTED; } @@ -859,61 +878,63 @@ do_resume (const char *args) * @param args arguments given to the command */ static void -do_reject (const char *args) +do_reject(const char *args) { struct CallList *cl; char buf[32]; if (NULL != call) - { - GNUNET_CONVERSATION_call_stop (call); - call = NULL; - return; - } - switch (phone_state) - { - case PS_LOOKUP_EGO: - case PS_ERROR: - fprintf (stderr, - "%s", - _ ("There is no call that could be cancelled right now.\n")); - return; - case PS_LISTEN: - /* look for active incoming calls to refuse */ - cl = cl_head; - if (NULL == cl) { - fprintf (stderr, _ ("There is no incoming call to refuse here!\n")); + GNUNET_CONVERSATION_call_stop(call); + call = NULL; return; } - if ((NULL != cl->next) || (NULL != args)) - { - for (cl = cl_head; NULL != cl; cl = cl->next) - { - GNUNET_snprintf (buf, sizeof (buf), "%u", cl->caller_num); - if (0 == strcmp (buf, args)) - break; - } - } - if (NULL == cl) + switch (phone_state) { - fprintf (stderr, - _ ("There is no incoming call `%s' to refuse right now!\n"), - args); + case PS_LOOKUP_EGO: + case PS_ERROR: + fprintf(stderr, + "%s", + _("There is no call that could be cancelled right now.\n")); return; + + case PS_LISTEN: + /* look for active incoming calls to refuse */ + cl = cl_head; + if (NULL == cl) + { + fprintf(stderr, _("There is no incoming call to refuse here!\n")); + return; + } + if ((NULL != cl->next) || (NULL != args)) + { + for (cl = cl_head; NULL != cl; cl = cl->next) + { + GNUNET_snprintf(buf, sizeof(buf), "%u", cl->caller_num); + if (0 == strcmp(buf, args)) + break; + } + } + if (NULL == cl) + { + fprintf(stderr, + _("There is no incoming call `%s' to refuse right now!\n"), + args); + return; + } + GNUNET_CONVERSATION_caller_hang_up(cl->caller); + GNUNET_CONTAINER_DLL_remove(cl_head, cl_tail, cl); + GNUNET_free(cl); + break; + + case PS_ACCEPTED: + /* expected state, do rejection logic */ + GNUNET_assert(NULL != cl_active); + GNUNET_CONVERSATION_caller_hang_up(cl_active->caller); + cl_active = NULL; + phone_state = PS_LISTEN; + break; } - GNUNET_CONVERSATION_caller_hang_up (cl->caller); - GNUNET_CONTAINER_DLL_remove (cl_head, cl_tail, cl); - GNUNET_free (cl); - break; - case PS_ACCEPTED: - /* expected state, do rejection logic */ - GNUNET_assert (NULL != cl_active); - GNUNET_CONVERSATION_caller_hang_up (cl_active->caller); - cl_active = NULL; - phone_state = PS_LISTEN; - break; - } } @@ -921,35 +942,35 @@ do_reject (const char *args) * List of supported commands. */ static struct VoipCommand commands[] = { - {"/address", - &do_address, - gettext_noop ( - "Use `/address' to find out which address this phone should have in GNS")}, - {"/call", &do_call, gettext_noop ("Use `/call USER.gnu' to call USER")}, - {"/accept", - &do_accept, - gettext_noop ("Use `/accept #NUM' to accept incoming call #NUM")}, - {"/suspend", - &do_suspend, - gettext_noop ("Use `/suspend' to suspend the active call")}, - {"/resume", - &do_resume, - gettext_noop ( - "Use `/resume [#NUM]' to resume a call, #NUM is needed to resume incoming calls, no argument is needed to resume the current outgoing call.")}, - {"/cancel", - &do_reject, - gettext_noop ("Use `/cancel' to reject or terminate a call")}, - {"/status", - &do_status, - gettext_noop ("Use `/status' to print status information")}, - {"/quit", - &do_quit, - gettext_noop ("Use `/quit' to terminate gnunet-conversation")}, - {"/help", - &do_help, - gettext_noop ("Use `/help command' to get help for a specific command")}, - {"", &do_unknown, NULL}, - {NULL, NULL, NULL}, + { "/address", + &do_address, + gettext_noop( + "Use `/address' to find out which address this phone should have in GNS") }, + { "/call", &do_call, gettext_noop("Use `/call USER.gnu' to call USER") }, + { "/accept", + &do_accept, + gettext_noop("Use `/accept #NUM' to accept incoming call #NUM") }, + { "/suspend", + &do_suspend, + gettext_noop("Use `/suspend' to suspend the active call") }, + { "/resume", + &do_resume, + gettext_noop( + "Use `/resume [#NUM]' to resume a call, #NUM is needed to resume incoming calls, no argument is needed to resume the current outgoing call.") }, + { "/cancel", + &do_reject, + gettext_noop("Use `/cancel' to reject or terminate a call") }, + { "/status", + &do_status, + gettext_noop("Use `/status' to print status information") }, + { "/quit", + &do_quit, + gettext_noop("Use `/quit' to terminate gnunet-conversation") }, + { "/help", + &do_help, + gettext_noop("Use `/help command' to get help for a specific command") }, + { "", &do_unknown, NULL }, + { NULL, NULL, NULL }, }; @@ -959,30 +980,30 @@ static struct VoipCommand commands[] = { * @param args arguments given to the command */ static void -do_help (const char *args) +do_help(const char *args) { unsigned int i; i = 0; - while ((NULL != args) && (0 != strlen (args)) && + while ((NULL != args) && (0 != strlen(args)) && (commands[i].Action != &do_help)) - { - if (0 == strncasecmp (&args[1], &commands[i].command[1], strlen (args) - 1)) { - fprintf (stdout, "%s\n", gettext (commands[i].helptext)); - return; + if (0 == strncasecmp(&args[1], &commands[i].command[1], strlen(args) - 1)) + { + fprintf(stdout, "%s\n", gettext(commands[i].helptext)); + return; + } + i++; } - i++; - } i = 0; - fprintf (stdout, "%s", "Available commands:\n"); + fprintf(stdout, "%s", "Available commands:\n"); while (commands[i].Action != &do_help) - { - fprintf (stdout, "%s\n", gettext (commands[i].command)); - i++; - } - fprintf (stdout, "%s", "\n"); - fprintf (stdout, "%s\n", gettext (commands[i].helptext)); + { + fprintf(stdout, "%s\n", gettext(commands[i].command)); + i++; + } + fprintf(stdout, "%s", "\n"); + fprintf(stdout, "%s\n", gettext(commands[i].helptext)); } @@ -992,43 +1013,43 @@ do_help (const char *args) * @param cls NULL */ static void -do_stop_task (void *cls) +do_stop_task(void *cls) { - (void) cls; + (void)cls; #ifdef WINDOWS if (NULL != stdin_hlp) - { - GNUNET_HELPER_stop (stdin_hlp, GNUNET_NO); - stdin_hlp = NULL; - } + { + GNUNET_HELPER_stop(stdin_hlp, GNUNET_NO); + stdin_hlp = NULL; + } #endif if (NULL != call) - { - GNUNET_CONVERSATION_call_stop (call); - call = NULL; - } + { + GNUNET_CONVERSATION_call_stop(call); + call = NULL; + } if (NULL != phone) - { - GNUNET_CONVERSATION_phone_destroy (phone); - phone = NULL; - } + { + GNUNET_CONVERSATION_phone_destroy(phone); + phone = NULL; + } if (NULL != handle_cmd_task) - { - GNUNET_SCHEDULER_cancel (handle_cmd_task); - handle_cmd_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(handle_cmd_task); + handle_cmd_task = NULL; + } if (NULL != id) - { - GNUNET_IDENTITY_disconnect (id); - id = NULL; - } - GNUNET_SPEAKER_destroy (speaker); + { + GNUNET_IDENTITY_disconnect(id); + id = NULL; + } + GNUNET_SPEAKER_destroy(speaker); speaker = NULL; - GNUNET_MICROPHONE_destroy (mic); + GNUNET_MICROPHONE_destroy(mic); mic = NULL; - GNUNET_free (ego_name); + GNUNET_free(ego_name); ego_name = NULL; - GNUNET_free_non_null (peer_name); + GNUNET_free_non_null(peer_name); peer_name = NULL; phone_state = PS_ERROR; } @@ -1041,7 +1062,7 @@ do_stop_task (void *cls) * @param str_len number of bytes to process in @a message */ static void -handle_command_string (char *message, size_t str_len) +handle_command_string(char *message, size_t str_len) { size_t i; const char *ptr; @@ -1052,49 +1073,50 @@ handle_command_string (char *message, size_t str_len) message[str_len - 1] = '\0'; if (message[str_len - 2] == '\r') message[str_len - 2] = '\0'; - if (0 == strlen (message)) + if (0 == strlen(message)) return; i = 0; while ( (NULL != commands[i].command) && (0 != - strncasecmp (commands[i].command, message, strlen (commands[i].command)))) + strncasecmp(commands[i].command, message, strlen(commands[i].command)))) i++; - ptr = &message[strlen (commands[i].command)]; - while (isspace ((unsigned char) *ptr)) + ptr = &message[strlen(commands[i].command)]; + while (isspace((unsigned char)*ptr)) ptr++; if ('\0' == *ptr) ptr = NULL; - commands[i].Action (ptr); + commands[i].Action(ptr); } #ifdef WINDOWS static int -console_reader_chars (void *cls, - void *client, - const struct GNUNET_MessageHeader *message) +console_reader_chars(void *cls, + void *client, + const struct GNUNET_MessageHeader *message) { char *chars; size_t str_size; - (void) cls; - switch (ntohs (message->type)) - { - case GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_CHARS: - chars = (char *) &message[1]; - str_size = ntohs (message->size) - sizeof (struct GNUNET_MessageHeader); - if (chars[str_size - 1] != '\0') - return GNUNET_SYSERR; - /* FIXME: is it ok that we pass part of a const struct to - * this function that may mangle the contents? - */ - handle_command_string (chars, str_size - 1); - break; - default: - GNUNET_break (0); - break; - } + (void)cls; + switch (ntohs(message->type)) + { + case GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_CHARS: + chars = (char *)&message[1]; + str_size = ntohs(message->size) - sizeof(struct GNUNET_MessageHeader); + if (chars[str_size - 1] != '\0') + return GNUNET_SYSERR; + /* FIXME: is it ok that we pass part of a const struct to + * this function that may mangle the contents? + */ + handle_command_string(chars, str_size - 1); + break; + + default: + GNUNET_break(0); + break; + } return GNUNET_OK; } #endif @@ -1106,21 +1128,21 @@ console_reader_chars (void *cls, * @param cls NULL */ static void -handle_command (void *cls) +handle_command(void *cls) { char message[MAX_MESSAGE_LENGTH + 1]; - (void) cls; + (void)cls; handle_cmd_task = - GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, - stdin_fh, - &handle_command, - NULL); + GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL, + stdin_fh, + &handle_command, + NULL); /* read message from command line and handle it */ - memset (message, 0, MAX_MESSAGE_LENGTH + 1); - if (NULL == fgets (message, MAX_MESSAGE_LENGTH, stdin)) + memset(message, 0, MAX_MESSAGE_LENGTH + 1); + if (NULL == fgets(message, MAX_MESSAGE_LENGTH, stdin)) return; - handle_command_string (message, strlen (message)); + handle_command_string(message, strlen(message)); } @@ -1133,35 +1155,35 @@ handle_command (void *cls) * @param name name of the ego */ static void -identity_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +identity_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { - (void) cls; - (void) ctx; + (void)cls; + (void)ctx; if (NULL == name) return; if (ego == my_caller_id) - { - if (verbose) - fprintf (stdout, _ ("Name of our ego changed to `%s'\n"), name); - GNUNET_free (ego_name); - ego_name = GNUNET_strdup (name); - return; - } - if (0 != strcmp (name, ego_name)) + { + if (verbose) + fprintf(stdout, _("Name of our ego changed to `%s'\n"), name); + GNUNET_free(ego_name); + ego_name = GNUNET_strdup(name); + return; + } + if (0 != strcmp(name, ego_name)) return; if (NULL == ego) - { - if (verbose) - fprintf (stdout, _ ("Our ego `%s' was deleted!\n"), ego_name); - my_caller_id = NULL; - return; - } + { + if (verbose) + fprintf(stdout, _("Our ego `%s' was deleted!\n"), ego_name); + my_caller_id = NULL; + return; + } my_caller_id = ego; - GNUNET_CONFIGURATION_set_value_string (cfg, "CONVERSATION", "LINE", line); - start_phone (); + GNUNET_CONFIGURATION_set_value_string(cfg, "CONVERSATION", "LINE", line); + start_phone(); } @@ -1174,52 +1196,52 @@ identity_cb (void *cls, * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { - (void) cls; - (void) args; - (void) cfgfile; - cfg = GNUNET_CONFIGURATION_dup (c); - speaker = GNUNET_SPEAKER_create_from_hardware (cfg); - mic = GNUNET_MICROPHONE_create_from_hardware (cfg); + (void)cls; + (void)args; + (void)cfgfile; + cfg = GNUNET_CONFIGURATION_dup(c); + speaker = GNUNET_SPEAKER_create_from_hardware(cfg); + mic = GNUNET_MICROPHONE_create_from_hardware(cfg); if (NULL == ego_name) - { - fprintf (stderr, "%s", _ ("You must specify the NAME of an ego to use\n")); - return; - } - id = GNUNET_IDENTITY_connect (cfg, &identity_cb, NULL); + { + fprintf(stderr, "%s", _("You must specify the NAME of an ego to use\n")); + return; + } + id = GNUNET_IDENTITY_connect(cfg, &identity_cb, NULL); #ifdef WINDOWS if (stdin_fh == NULL) - { - static char cpid[64]; - static char *args[] = {"gnunet-helper-w32-console.exe", - "chars", - XSTRINGIFY (MAX_MESSAGE_LENGTH), - cpid, - NULL}; - snprintf (cpid, 64, "%d", GetCurrentProcessId ()); - stdin_hlp = GNUNET_HELPER_start (GNUNET_NO, - "gnunet-helper-w32-console", - args, - console_reader_chars, - NULL, - NULL); - if (NULL == stdin_hlp) { - fprintf (stderr, "%s", _ ("Failed to start gnunet-helper-w32-console\n")); - return; + static char cpid[64]; + static char *args[] = { "gnunet-helper-w32-console.exe", + "chars", + XSTRINGIFY(MAX_MESSAGE_LENGTH), + cpid, + NULL }; + snprintf(cpid, 64, "%d", GetCurrentProcessId()); + stdin_hlp = GNUNET_HELPER_start(GNUNET_NO, + "gnunet-helper-w32-console", + args, + console_reader_chars, + NULL, + NULL); + if (NULL == stdin_hlp) + { + fprintf(stderr, "%s", _("Failed to start gnunet-helper-w32-console\n")); + return; + } } - } else #endif - handle_cmd_task = - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_UI, - &handle_command, - NULL); - GNUNET_SCHEDULER_add_shutdown (&do_stop_task, NULL); + handle_cmd_task = + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_UI, + &handle_command, + NULL); + GNUNET_SCHEDULER_add_shutdown(&do_stop_task, NULL); } @@ -1231,56 +1253,57 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_string ( - 'e', - "ego", - "NAME", - gettext_noop ("sets the NAME of the ego to use for the caller ID"), - &ego_name), - GNUNET_GETOPT_option_string ('p', - "phone", - "LINE", - gettext_noop ( - "sets the LINE to use for the phone"), - &line), - GNUNET_GETOPT_OPTION_END}; + { GNUNET_GETOPT_option_string( + 'e', + "ego", + "NAME", + gettext_noop("sets the NAME of the ego to use for the caller ID"), + &ego_name), + GNUNET_GETOPT_option_string('p', + "phone", + "LINE", + gettext_noop( + "sets the LINE to use for the phone"), + &line), + GNUNET_GETOPT_OPTION_END }; int ret; + #ifndef WINDOWS int flags; - flags = fcntl (0, F_GETFL, 0); + flags = fcntl(0, F_GETFL, 0); flags |= O_NONBLOCK; - if (0 != fcntl (0, F_SETFL, flags)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "fcntl"); - stdin_fh = GNUNET_DISK_get_handle_from_int_fd (0); + if (0 != fcntl(0, F_SETFL, flags)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "fcntl"); + stdin_fh = GNUNET_DISK_get_handle_from_int_fd(0); #else - if (FILE_TYPE_CHAR == GetFileType ((HANDLE) _get_osfhandle (0))) - { - stdin_fh = NULL; - } + if (FILE_TYPE_CHAR == GetFileType((HANDLE)_get_osfhandle(0))) + { + stdin_fh = NULL; + } else - stdin_fh = GNUNET_DISK_get_handle_from_int_fd (0); + stdin_fh = GNUNET_DISK_get_handle_from_int_fd(0); #endif - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; ret = - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-conversation", - gettext_noop ( - "Enables having a conversation with other GNUnet users."), - options, - &run, - NULL); - GNUNET_free ((void *) argv); + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-conversation", + gettext_noop( + "Enables having a conversation with other GNUnet users."), + options, + &run, + NULL); + GNUNET_free((void *)argv); if (NULL != cfg) - { - GNUNET_CONFIGURATION_destroy (cfg); - cfg = NULL; - } + { + GNUNET_CONFIGURATION_destroy(cfg); + cfg = NULL; + } return (GNUNET_OK == ret) ? 0 : 1; } diff --git a/src/conversation/gnunet-helper-audio-playback-gst.c b/src/conversation/gnunet-helper-audio-playback-gst.c index 51450af90..b268fa215 100644 --- a/src/conversation/gnunet-helper-audio-playback-gst.c +++ b/src/conversation/gnunet-helper-audio-playback-gst.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/gnunet-helper-audio-playback-gst.c * @brief program to playback audio data to the speaker (GStreamer version) @@ -81,140 +81,144 @@ static int abort_read; static void -sink_child_added (GstChildProxy *child_proxy, - GObject *object, - gchar *name, - gpointer user_data) +sink_child_added(GstChildProxy *child_proxy, + GObject *object, + gchar *name, + gpointer user_data) { - if (GST_IS_AUDIO_BASE_SRC (object)) - g_object_set (object, - "buffer-time", (gint64) BUFFER_TIME, - "latency-time", (gint64) LATENCY_TIME, - NULL); + if (GST_IS_AUDIO_BASE_SRC(object)) + g_object_set(object, + "buffer-time", (gint64)BUFFER_TIME, + "latency-time", (gint64)LATENCY_TIME, + NULL); } static void -ogg_pad_added (GstElement *element, - GstPad *pad, - gpointer data) +ogg_pad_added(GstElement *element, + GstPad *pad, + gpointer data) { GstPad *sinkpad; - GstElement *decoder = (GstElement *) data; + GstElement *decoder = (GstElement *)data; /* We can now link this pad with the opus-decoder sink pad */ - sinkpad = gst_element_get_static_pad (decoder, "sink"); + sinkpad = gst_element_get_static_pad(decoder, "sink"); - gst_pad_link (pad, sinkpad); + gst_pad_link(pad, sinkpad); - gst_element_link_many (decoder, conv, resampler, sink, NULL); + gst_element_link_many(decoder, conv, resampler, sink, NULL); - gst_object_unref (sinkpad); + gst_object_unref(sinkpad); } static void -quit () +quit() { if (NULL != source) - gst_app_src_end_of_stream (GST_APP_SRC (source)); + gst_app_src_end_of_stream(GST_APP_SRC(source)); if (NULL != pipeline) - gst_element_set_state (pipeline, GST_STATE_NULL); + gst_element_set_state(pipeline, GST_STATE_NULL); abort_read = 1; } static gboolean -bus_call (GstBus *bus, GstMessage *msg, gpointer data) +bus_call(GstBus *bus, GstMessage *msg, gpointer data) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Bus message\n"); - switch (GST_MESSAGE_TYPE (msg)) - { - case GST_MESSAGE_EOS: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "End of stream\n"); - quit (); - break; - - case GST_MESSAGE_ERROR: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Bus message\n"); + switch (GST_MESSAGE_TYPE(msg)) + { + case GST_MESSAGE_EOS: + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "End of stream\n"); + quit(); + break; + + case GST_MESSAGE_ERROR: { gchar *debug; GError *error; - gst_message_parse_error (msg, &error, &debug); - g_free (debug); + gst_message_parse_error(msg, &error, &debug); + g_free(debug); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error: %s\n", - error->message); - g_error_free (error); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error: %s\n", + error->message); + g_error_free(error); - quit (); + quit(); + break; + } + + default: break; } - default: - break; - } return TRUE; } static void -signalhandler (int s) +signalhandler(int s) { - quit (); + quit(); } static int -feed_buffer_to_gst (const char *audio, size_t b_len) +feed_buffer_to_gst(const char *audio, size_t b_len) { GstBuffer *b; gchar *bufspace; GstFlowReturn flow; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Feeding %u bytes to GStreamer\n", - (unsigned int) b_len); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Feeding %u bytes to GStreamer\n", + (unsigned int)b_len); - bufspace = g_memdup (audio, b_len); - b = gst_buffer_new_wrapped (bufspace, b_len); + bufspace = g_memdup(audio, b_len); + b = gst_buffer_new_wrapped(bufspace, b_len); if (NULL == b) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Failed to wrap a buffer\n"); - g_free (bufspace); - return GNUNET_SYSERR; - } - flow = gst_app_src_push_buffer (GST_APP_SRC (source), b); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Failed to wrap a buffer\n"); + g_free(bufspace); + return GNUNET_SYSERR; + } + flow = gst_app_src_push_buffer(GST_APP_SRC(source), b); /* They all return GNUNET_OK, because currently player stops when * data stops coming. This might need to be changed for the player * to also stop when pipeline breaks. */ switch (flow) - { - case GST_FLOW_OK: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Fed %u bytes to the pipeline\n", - (unsigned int) b_len); - break; - case GST_FLOW_FLUSHING: - /* buffer was dropped, because pipeline state is not PAUSED or PLAYING */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Dropped a buffer\n"); - break; - case GST_FLOW_EOS: - /* end of stream */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "EOS\n"); - break; - default: - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Unexpected push result\n"); - break; - } + { + case GST_FLOW_OK: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Fed %u bytes to the pipeline\n", + (unsigned int)b_len); + break; + + case GST_FLOW_FLUSHING: + /* buffer was dropped, because pipeline state is not PAUSED or PLAYING */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Dropped a buffer\n"); + break; + + case GST_FLOW_EOS: + /* end of stream */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "EOS\n"); + break; + + default: + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Unexpected push result\n"); + break; + } return GNUNET_OK; } @@ -228,29 +232,30 @@ feed_buffer_to_gst (const char *audio, size_t b_len) * #GNUNET_SYSERR to stop further processing due to error */ static int -stdin_receiver (void *cls, - const struct GNUNET_MessageHeader *msg) +stdin_receiver(void *cls, + const struct GNUNET_MessageHeader *msg) { struct AudioMessage *audio; size_t b_len; - switch (ntohs (msg->type)) - { - case GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO: - audio = (struct AudioMessage *) msg; - - b_len = ntohs (audio->header.size) - sizeof (struct AudioMessage); - feed_buffer_to_gst ((const char *) &audio[1], b_len); - break; - default: - break; - } + switch (ntohs(msg->type)) + { + case GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO: + audio = (struct AudioMessage *)msg; + + b_len = ntohs(audio->header.size) - sizeof(struct AudioMessage); + feed_buffer_to_gst((const char *)&audio[1], b_len); + break; + + default: + break; + } return GNUNET_OK; } int -main (int argc, char **argv) +main(int argc, char **argv) { GstBus *bus; guint bus_watch_id; @@ -260,144 +265,144 @@ main (int argc, char **argv) SignalHandlerPointer inthandler, termhandler; #ifdef DEBUG_READ_PURE_OGG - int read_pure_ogg = getenv ("GNUNET_READ_PURE_OGG") ? 1 : 0; + int read_pure_ogg = getenv("GNUNET_READ_PURE_OGG") ? 1 : 0; #endif - inthandler = signal (SIGINT, - &signalhandler); - termhandler = signal (SIGTERM, - &signalhandler); + inthandler = signal(SIGINT, + &signalhandler); + termhandler = signal(SIGTERM, + &signalhandler); #ifdef WINDOWS - setmode (0, _O_BINARY); + setmode(0, _O_BINARY); #endif /* Initialisation */ - gst_init (&argc, &argv); + gst_init(&argc, &argv); - GNUNET_assert (GNUNET_OK == - GNUNET_log_setup ("gnunet-helper-audio-playback-gst", - "WARNING", - NULL)); + GNUNET_assert(GNUNET_OK == + GNUNET_log_setup("gnunet-helper-audio-playback-gst", + "WARNING", + NULL)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Audio sink starts\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Audio sink starts\n"); - stdin_mst = GNUNET_MST_create (&stdin_receiver, - NULL); + stdin_mst = GNUNET_MST_create(&stdin_receiver, + NULL); /* Create gstreamer elements */ - pipeline = gst_pipeline_new ("audio-player"); - source = gst_element_factory_make ("appsrc", "audio-input"); - demuxer = gst_element_factory_make ("oggdemux", "ogg-demuxer"); - decoder = gst_element_factory_make ("opusdec", "opus-decoder"); - conv = gst_element_factory_make ("audioconvert", "converter"); - resampler= gst_element_factory_make ("audioresample", "resampler"); - sink = gst_element_factory_make ("autoaudiosink", "audiosink"); + pipeline = gst_pipeline_new("audio-player"); + source = gst_element_factory_make("appsrc", "audio-input"); + demuxer = gst_element_factory_make("oggdemux", "ogg-demuxer"); + decoder = gst_element_factory_make("opusdec", "opus-decoder"); + conv = gst_element_factory_make("audioconvert", "converter"); + resampler = gst_element_factory_make("audioresample", "resampler"); + sink = gst_element_factory_make("autoaudiosink", "audiosink"); if (!pipeline || !source || !conv || !resampler || !decoder || !demuxer || !sink) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "One element could not be created. Exiting.\n"); - return -1; - } - - g_signal_connect (sink, - "child-added", - G_CALLBACK (sink_child_added), - NULL); - g_signal_connect (demuxer, - "pad-added", - G_CALLBACK (ogg_pad_added), - decoder); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "One element could not be created. Exiting.\n"); + return -1; + } + + g_signal_connect(sink, + "child-added", + G_CALLBACK(sink_child_added), + NULL); + g_signal_connect(demuxer, + "pad-added", + G_CALLBACK(ogg_pad_added), + decoder); /* Keep a reference to it, we operate on it */ - gst_object_ref (GST_OBJECT (source)); + gst_object_ref(GST_OBJECT(source)); /* Set up the pipeline */ /* we feed appsrc as fast as possible, it just blocks when it's full */ - g_object_set (G_OBJECT (source), + g_object_set(G_OBJECT(source), /* "format", GST_FORMAT_TIME,*/ - "block", TRUE, - "is-live", TRUE, - NULL); + "block", TRUE, + "is-live", TRUE, + NULL); - g_object_set (G_OBJECT (decoder), + g_object_set(G_OBJECT(decoder), /* "plc", FALSE,*/ /* "apply-gain", TRUE,*/ - "use-inband-fec", TRUE, - NULL); + "use-inband-fec", TRUE, + NULL); /* we add a message handler */ - bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); - bus_watch_id = gst_bus_add_watch (bus, bus_call, pipeline); - gst_object_unref (bus); + bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline)); + bus_watch_id = gst_bus_add_watch(bus, bus_call, pipeline); + gst_object_unref(bus); /* we add all elements into the pipeline */ /* audio-input | ogg-demuxer | opus-decoder | converter | resampler | audiosink */ - gst_bin_add_many (GST_BIN (pipeline), source, demuxer, decoder, conv, - resampler, sink, NULL); + gst_bin_add_many(GST_BIN(pipeline), source, demuxer, decoder, conv, + resampler, sink, NULL); /* we link the elements together */ - gst_element_link_many (source, demuxer, NULL); + gst_element_link_many(source, demuxer, NULL); /* Set the pipeline to "playing" state*/ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Now playing\n"); - gst_element_set_state (pipeline, GST_STATE_PLAYING); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Now playing\n"); + gst_element_set_state(pipeline, GST_STATE_PLAYING); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Running...\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Running...\n"); /* Iterate */ toff = 0; while (!abort_read) - { - char readbuf[MAXLINE]; - int ret; - - ret = read (0, readbuf, sizeof (readbuf)); - if (0 > ret) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Read error from STDIN: %d %s\n"), - ret, strerror (errno)); - break; - } - toff += ret; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received %d bytes of audio data (total: %llu)\n", - (int) ret, - (unsigned long long) toff); - if (0 == ret) - break; + char readbuf[MAXLINE]; + int ret; + + ret = read(0, readbuf, sizeof(readbuf)); + if (0 > ret) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Read error from STDIN: %d %s\n"), + ret, strerror(errno)); + break; + } + toff += ret; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received %d bytes of audio data (total: %llu)\n", + (int)ret, + (unsigned long long)toff); + if (0 == ret) + break; #ifdef DEBUG_READ_PURE_OGG - if (read_pure_ogg) - { - feed_buffer_to_gst (readbuf, ret); - } - else + if (read_pure_ogg) + { + feed_buffer_to_gst(readbuf, ret); + } + else #endif - GNUNET_MST_from_buffer (stdin_mst, - readbuf, - ret, - GNUNET_NO, - GNUNET_NO); - } - GNUNET_MST_destroy (stdin_mst); - - signal (SIGINT, inthandler); - signal (SIGINT, termhandler); - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Returned, stopping playback\n"); - quit (); - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Deleting pipeline\n"); - gst_object_unref (GST_OBJECT (source)); + GNUNET_MST_from_buffer(stdin_mst, + readbuf, + ret, + GNUNET_NO, + GNUNET_NO); + } + GNUNET_MST_destroy(stdin_mst); + + signal(SIGINT, inthandler); + signal(SIGINT, termhandler); + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Returned, stopping playback\n"); + quit(); + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Deleting pipeline\n"); + gst_object_unref(GST_OBJECT(source)); source = NULL; - gst_object_unref (GST_OBJECT (pipeline)); + gst_object_unref(GST_OBJECT(pipeline)); pipeline = NULL; - g_source_remove (bus_watch_id); + g_source_remove(bus_watch_id); return 0; } diff --git a/src/conversation/gnunet-helper-audio-playback.c b/src/conversation/gnunet-helper-audio-playback.c index e86bb6508..34e61c100 100644 --- a/src/conversation/gnunet-helper-audio-playback.c +++ b/src/conversation/gnunet-helper-audio-playback.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/gnunet-helper-audio-playback.c * @brief program to playback audio data to the speaker @@ -124,8 +124,7 @@ static float gain; GNUNET_NETWORK_STRUCT_BEGIN /* OggOpus spec says the numbers must be in little-endian order */ -struct OpusHeadPacket -{ +struct OpusHeadPacket { uint8_t magic[8]; uint8_t version; uint8_t channels; @@ -143,71 +142,71 @@ GNUNET_NETWORK_STRUCT_END * elsewhere in the code. */ static OpusDecoder * -process_header (ogg_packet *op) +process_header(ogg_packet *op) { int err; OpusDecoder *dec; struct OpusHeadPacket header; - if ( ((unsigned int) op->bytes) < sizeof (header)) + if (((unsigned int)op->bytes) < sizeof(header)) return NULL; - GNUNET_memcpy (&header, - op->packet, - sizeof (header)); - header.preskip = GNUNET_le16toh (header.preskip); - header.sampling_rate = GNUNET_le32toh (header.sampling_rate); - header.gain = GNUNET_le16toh (header.gain); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Header: v%u, %u-ch, skip %u, %uHz, %u gain\n", - header.version, - header.channels, - header.preskip, - header.sampling_rate, - header.gain); + GNUNET_memcpy(&header, + op->packet, + sizeof(header)); + header.preskip = GNUNET_le16toh(header.preskip); + header.sampling_rate = GNUNET_le32toh(header.sampling_rate); + header.gain = GNUNET_le16toh(header.gain); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Header: v%u, %u-ch, skip %u, %uHz, %u gain\n", + header.version, + header.channels, + header.preskip, + header.sampling_rate, + header.gain); channels = header.channels; preskip = header.preskip; if (header.channel_mapping != 0) - { - fprintf (stderr, - "This implementation does not support non-mono streams\n"); - return NULL; - } + { + fprintf(stderr, + "This implementation does not support non-mono streams\n"); + return NULL; + } - dec = opus_decoder_create (SAMPLING_RATE, channels, &err); + dec = opus_decoder_create(SAMPLING_RATE, channels, &err); if (OPUS_OK != err) - { - fprintf (stderr, - "Cannot create encoder: %s\n", - opus_strerror (err)); - return NULL; - } - if (! dec) - { - fprintf (stderr, - "Decoder initialization failed: %s\n", - opus_strerror (err)); - return NULL; - } - - if (0 != header.gain) - { - /*Gain API added in a newer libopus version, if we don't have it - we apply the gain ourselves. We also add in a user provided - manual gain at the same time.*/ - int gainadj = (int) header.gain; - err = opus_decoder_ctl (dec, OPUS_SET_GAIN (gainadj)); - if(OPUS_UNIMPLEMENTED == err) { - gain = pow (10.0, gainadj / 5120.0); + fprintf(stderr, + "Cannot create encoder: %s\n", + opus_strerror(err)); + return NULL; } - else if (OPUS_OK != err) + if (!dec) { - fprintf (stderr, "Error setting gain: %s\n", opus_strerror (err)); + fprintf(stderr, + "Decoder initialization failed: %s\n", + opus_strerror(err)); return NULL; } - } + + if (0 != header.gain) + { + /*Gain API added in a newer libopus version, if we don't have it + we apply the gain ourselves. We also add in a user provided + manual gain at the same time.*/ + int gainadj = (int)header.gain; + err = opus_decoder_ctl(dec, OPUS_SET_GAIN(gainadj)); + if (OPUS_UNIMPLEMENTED == err) + { + gain = pow(10.0, gainadj / 5120.0); + } + else if (OPUS_OK != err) + { + fprintf(stderr, "Error setting gain: %s\n", opus_strerror(err)); + return NULL; + } + } return dec; } @@ -217,122 +216,126 @@ process_header (ogg_packet *op) static size_t fwrite_le32(opus_int32 i32, FILE *file) { - unsigned char buf[4]; - buf[0]=(unsigned char)(i32&0xFF); - buf[1]=(unsigned char)(i32>>8&0xFF); - buf[2]=(unsigned char)(i32>>16&0xFF); - buf[3]=(unsigned char)(i32>>24&0xFF); - return fwrite(buf,4,1,file); + unsigned char buf[4]; + + buf[0] = (unsigned char)(i32 & 0xFF); + buf[1] = (unsigned char)(i32 >> 8 & 0xFF); + buf[2] = (unsigned char)(i32 >> 16 & 0xFF); + buf[3] = (unsigned char)(i32 >> 24 & 0xFF); + return fwrite(buf, 4, 1, file); } static size_t fwrite_le16(int i16, FILE *file) { - unsigned char buf[2]; - buf[0]=(unsigned char)(i16&0xFF); - buf[1]=(unsigned char)(i16>>8&0xFF); - return fwrite(buf,2,1,file); + unsigned char buf[2]; + + buf[0] = (unsigned char)(i16 & 0xFF); + buf[1] = (unsigned char)(i16 >> 8 & 0xFF); + return fwrite(buf, 2, 1, file); } static int write_wav_header() { - int ret; - FILE *file = stdout; + int ret; + FILE *file = stdout; - ret = fprintf (file, "RIFF") >= 0; - ret &= fwrite_le32 (0x7fffffff, file); + ret = fprintf(file, "RIFF") >= 0; + ret &= fwrite_le32(0x7fffffff, file); - ret &= fprintf (file, "WAVEfmt ") >= 0; - ret &= fwrite_le32 (16, file); - ret &= fwrite_le16 (1, file); - ret &= fwrite_le16 (channels, file); - ret &= fwrite_le32 (SAMPLING_RATE, file); - ret &= fwrite_le32 (2*channels*SAMPLING_RATE, file); - ret &= fwrite_le16 (2*channels, file); - ret &= fwrite_le16 (16, file); + ret &= fprintf(file, "WAVEfmt ") >= 0; + ret &= fwrite_le32(16, file); + ret &= fwrite_le16(1, file); + ret &= fwrite_le16(channels, file); + ret &= fwrite_le32(SAMPLING_RATE, file); + ret &= fwrite_le32(2 * channels * SAMPLING_RATE, file); + ret &= fwrite_le16(2 * channels, file); + ret &= fwrite_le16(16, file); - ret &= fprintf (file, "data") >= 0; - ret &= fwrite_le32 (0x7fffffff, file); + ret &= fprintf(file, "data") >= 0; + ret &= fwrite_le32(0x7fffffff, file); - return !ret ? -1 : 16; + return !ret ? -1 : 16; } #endif static int64_t -audio_write (int64_t maxout) +audio_write(int64_t maxout) { int64_t sampout = 0; int tmp_skip; unsigned out_len; unsigned to_write; float *output; + #ifdef DEBUG_DUMP_DECODED_OGG static int wrote_wav_header; if (dump_to_stdout && !wrote_wav_header) - { - write_wav_header (); - wrote_wav_header = 1; - } + { + write_wav_header(); + wrote_wav_header = 1; + } #endif maxout = 0 > maxout ? 0 : maxout; do - { - tmp_skip = (preskip > frame_size) ? (int) frame_size : preskip; - preskip -= tmp_skip; - output = pcm_buffer + channels * tmp_skip; - out_len = frame_size - tmp_skip; - if (out_len > MAX_FRAME_SIZE) - exit (6); - frame_size = 0; - - to_write = out_len < maxout ? out_len : (unsigned) maxout; - if (0 < maxout) { - int64_t wrote = 0; - wrote = to_write; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Writing %u * %u * %u = %llu bytes into PA\n", - to_write, - channels, - (unsigned int) sizeof (float), - (unsigned long long) (to_write * channels * sizeof (float))); + tmp_skip = (preskip > frame_size) ? (int)frame_size : preskip; + preskip -= tmp_skip; + output = pcm_buffer + channels * tmp_skip; + out_len = frame_size - tmp_skip; + if (out_len > MAX_FRAME_SIZE) + exit(6); + frame_size = 0; + + to_write = out_len < maxout ? out_len : (unsigned)maxout; + if (0 < maxout) + { + int64_t wrote = 0; + wrote = to_write; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Writing %u * %u * %u = %llu bytes into PA\n", + to_write, + channels, + (unsigned int)sizeof(float), + (unsigned long long)(to_write * channels * sizeof(float))); #ifdef DEBUG_DUMP_DECODED_OGG - if (dump_to_stdout) - { -# define fminf(_x,_y) ((_x)<(_y)?(_x):(_y)) -# define fmaxf(_x,_y) ((_x)>(_y)?(_x):(_y)) -# define float2int(flt) ((int)(floor(.5+flt))) - int i; - int16_t *out = alloca(sizeof(short)*MAX_FRAME_SIZE*channels); - for (i=0;i<(int)out_len*channels;i++) - out[i]=(short)float2int(fmaxf(-32768,fminf(output[i]*32768.f,32767))); - - fwrite (out, 2 * channels, out_len (_y) ? (_x) : (_y)) +# define float2int(flt) ((int)(floor(.5 + flt))) + int i; + int16_t *out = alloca(sizeof(short) * MAX_FRAME_SIZE * channels); + for (i = 0; i < (int)out_len * channels; i++) + out[i] = (short)float2int(fmaxf(-32768, fminf(output[i] * 32768.f, 32767))); + + fwrite(out, 2 * channels, out_len < maxout ? out_len : maxout, stdout); + } + else #endif - if (pa_stream_write - (stream_out, output, to_write * channels * sizeof (float), NULL, 0, - PA_SEEK_RELATIVE) < 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_stream_write() failed: %s\n"), - pa_strerror (pa_context_errno (context))); - } - sampout += wrote; - maxout -= wrote; + if (pa_stream_write + (stream_out, output, to_write * channels * sizeof(float), NULL, 0, + PA_SEEK_RELATIVE) < 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_stream_write() failed: %s\n"), + pa_strerror(pa_context_errno(context))); + } + sampout += wrote; + maxout -= wrote; + } } - } while (0 < frame_size && 0 < maxout); + while (0 < frame_size && 0 < maxout); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Wrote %" PRId64 " samples\n", - sampout); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Wrote %" PRId64 " samples\n", + sampout); return sampout; } @@ -341,16 +344,16 @@ audio_write (int64_t maxout) * Pulseaudio shutdown task */ static void -quit (int ret) +quit(int ret) { - mainloop_api->quit (mainloop_api, - ret); - exit (ret); + mainloop_api->quit(mainloop_api, + ret); + exit(ret); } static void -ogg_demux_and_decode () +ogg_demux_and_decode() { ogg_page og; static int stream_init; @@ -365,189 +368,189 @@ ogg_demux_and_decode () static int total_links; static int gran_offset; - while (1 == ogg_sync_pageout (&oy, &og)) - { - if (0 == stream_init) + while (1 == ogg_sync_pageout(&oy, &og)) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Initialized the stream\n"); - ogg_stream_init (&os, ogg_page_serialno (&og)); - stream_init = 1; - } - if (ogg_page_serialno (&og) != os.serialno) - { - /* so all streams are read. */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Re-set serial number\n"); - ogg_stream_reset_serialno (&os, ogg_page_serialno (&og)); - } - /*Add page to the bitstream*/ - ogg_stream_pagein (&os, &og); - page_granule = ogg_page_granulepos (&og); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Reading page that ends at %" PRId64 "\n", - page_granule); - /*Extract all available packets*/ - while (1 == ogg_stream_packetout (&os, &op)) - { - /*OggOpus streams are identified by a magic string in the initial - stream header.*/ - if (op.b_o_s && op.bytes >= 8 && !memcmp (op.packet, "OpusHead", 8)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got Opus Header\n"); - if (has_opus_stream && has_tags_packet) - { - /*If we're seeing another BOS OpusHead now it means - the stream is chained without an EOS. - This can easily happen if record helper is terminated unexpectedly. - */ - has_opus_stream = 0; - if (dec) - opus_decoder_destroy (dec); - dec = NULL; - fprintf (stderr, "\nWarning: stream %" PRId64 " ended without EOS and a new stream began.\n", (int64_t) os.serialno); - } - if (!has_opus_stream) + if (0 == stream_init) { - if (packet_count > 0 && opus_serialno == os.serialno) - { - fprintf (stderr, "\nError: Apparent chaining without changing serial number (%" PRId64 "==%" PRId64 ").\n", - (int64_t) opus_serialno, (int64_t) os.serialno); - quit(1); - } - opus_serialno = os.serialno; - has_opus_stream = 1; - has_tags_packet = 0; - link_out = 0; - packet_count = 0; - eos = 0; - total_links++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got header for stream %" PRId64 ", this is %dth link\n", - (int64_t) opus_serialno, total_links); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Initialized the stream\n"); + ogg_stream_init(&os, ogg_page_serialno(&og)); + stream_init = 1; } - else + if (ogg_page_serialno(&og) != os.serialno) { - fprintf (stderr, "\nWarning: ignoring opus stream %" PRId64 "\n", (int64_t) os.serialno); + /* so all streams are read. */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Re-set serial number\n"); + ogg_stream_reset_serialno(&os, ogg_page_serialno(&og)); } - } - if (!has_opus_stream || os.serialno != opus_serialno) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "breaking out\n"); - break; - } - /*If first packet in a logical stream, process the Opus header*/ - if (0 == packet_count) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Decoding header\n"); - dec = process_header (&op); - if (!dec) - quit (1); - - if (0 != ogg_stream_packetout (&os, &op) || 255 == og.header[og.header_len - 1]) - { - /*The format specifies that the initial header and tags packets are on their - own pages. To aid implementors in discovering that their files are wrong - we reject them explicitly here. In some player designs files like this would - fail even without an explicit test.*/ - fprintf (stderr, "Extra packets on initial header page. Invalid stream.\n"); - quit (1); - } - - /*Remember how many samples at the front we were told to skip - so that we can adjust the timestamp counting.*/ - gran_offset = preskip; - - if (! pcm_buffer) + /*Add page to the bitstream*/ + ogg_stream_pagein(&os, &og); + page_granule = ogg_page_granulepos(&og); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Reading page that ends at %" PRId64 "\n", + page_granule); + /*Extract all available packets*/ + while (1 == ogg_stream_packetout(&os, &op)) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Allocating %u * %u * %u = %llu bytes of buffer space\n", - MAX_FRAME_SIZE, - channels, - (unsigned int) sizeof (float), - (unsigned long long) (MAX_FRAME_SIZE * channels * sizeof (float))); - pcm_buffer = pa_xmalloc (sizeof (float) * MAX_FRAME_SIZE * channels); + /*OggOpus streams are identified by a magic string in the initial + stream header.*/ + if (op.b_o_s && op.bytes >= 8 && !memcmp(op.packet, "OpusHead", 8)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got Opus Header\n"); + if (has_opus_stream && has_tags_packet) + { + /*If we're seeing another BOS OpusHead now it means + the stream is chained without an EOS. + This can easily happen if record helper is terminated unexpectedly. + */ + has_opus_stream = 0; + if (dec) + opus_decoder_destroy(dec); + dec = NULL; + fprintf(stderr, "\nWarning: stream %" PRId64 " ended without EOS and a new stream began.\n", (int64_t)os.serialno); + } + if (!has_opus_stream) + { + if (packet_count > 0 && opus_serialno == os.serialno) + { + fprintf(stderr, "\nError: Apparent chaining without changing serial number (%" PRId64 "==%" PRId64 ").\n", + (int64_t)opus_serialno, (int64_t)os.serialno); + quit(1); + } + opus_serialno = os.serialno; + has_opus_stream = 1; + has_tags_packet = 0; + link_out = 0; + packet_count = 0; + eos = 0; + total_links++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got header for stream %" PRId64 ", this is %dth link\n", + (int64_t)opus_serialno, total_links); + } + else + { + fprintf(stderr, "\nWarning: ignoring opus stream %" PRId64 "\n", (int64_t)os.serialno); + } + } + if (!has_opus_stream || os.serialno != opus_serialno) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "breaking out\n"); + break; + } + /*If first packet in a logical stream, process the Opus header*/ + if (0 == packet_count) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Decoding header\n"); + dec = process_header(&op); + if (!dec) + quit(1); + + if (0 != ogg_stream_packetout(&os, &op) || 255 == og.header[og.header_len - 1]) + { + /*The format specifies that the initial header and tags packets are on their + own pages. To aid implementors in discovering that their files are wrong + we reject them explicitly here. In some player designs files like this would + fail even without an explicit test.*/ + fprintf(stderr, "Extra packets on initial header page. Invalid stream.\n"); + quit(1); + } + + /*Remember how many samples at the front we were told to skip + so that we can adjust the timestamp counting.*/ + gran_offset = preskip; + + if (!pcm_buffer) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Allocating %u * %u * %u = %llu bytes of buffer space\n", + MAX_FRAME_SIZE, + channels, + (unsigned int)sizeof(float), + (unsigned long long)(MAX_FRAME_SIZE * channels * sizeof(float))); + pcm_buffer = pa_xmalloc(sizeof(float) * MAX_FRAME_SIZE * channels); + } + } + else if (1 == packet_count) + { + has_tags_packet = 1; + if (0 != ogg_stream_packetout(&os, &op) || 255 == og.header[og.header_len - 1]) + { + fprintf(stderr, "Extra packets on initial tags page. Invalid stream.\n"); + quit(1); + } + } + else + { + int ret; + int64_t maxout; + int64_t outsamp; + + /*End of stream condition*/ + if (op.e_o_s && os.serialno == opus_serialno) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got EOS\n"); + eos = 1; /* don't care for anything except opus eos */ + } + + /*Decode Opus packet*/ + ret = opus_decode_float(dec, + (const unsigned char *)op.packet, + op.bytes, + pcm_buffer, + MAX_FRAME_SIZE, 0); + + /*If the decoder returned less than zero, we have an error.*/ + if (0 > ret) + { + fprintf(stderr, "Decoding error: %s\n", opus_strerror(ret)); + break; + } + frame_size = ret; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Decoded %d bytes/channel (%d bytes) from %u compressed bytes\n", + ret, + ret * channels, + (unsigned int)op.bytes); + + /*Apply header gain, if we're not using an opus library new + enough to do this internally.*/ + if (0 != gain) + { + int i; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Applying gain %f\n", + gain); + for (i = 0; i < frame_size * channels; i++) + pcm_buffer[i] *= gain; + } + + /*This handles making sure that our output duration respects + the final end-trim by not letting the output sample count + get ahead of the granpos indicated value.*/ + maxout = ((page_granule - gran_offset) * SAMPLING_RATE / 48000) - link_out; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Writing audio packet %" PRId64 ", at most %" PRId64 " samples\n", + packet_count, maxout); + + outsamp = audio_write(0 > maxout ? 0 : maxout); + link_out += outsamp; + } + packet_count++; } - } - else if (1 == packet_count) - { - has_tags_packet = 1; - if (0 != ogg_stream_packetout (&os, &op) || 255 == og.header[og.header_len - 1]) + if (eos) { - fprintf (stderr, "Extra packets on initial tags page. Invalid stream.\n"); - quit (1); - } - } - else - { - int ret; - int64_t maxout; - int64_t outsamp; - - /*End of stream condition*/ - if (op.e_o_s && os.serialno == opus_serialno) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got EOS\n"); - eos = 1; /* don't care for anything except opus eos */ - } - - /*Decode Opus packet*/ - ret = opus_decode_float (dec, - (const unsigned char *) op.packet, - op.bytes, - pcm_buffer, - MAX_FRAME_SIZE, 0); - - /*If the decoder returned less than zero, we have an error.*/ - if (0 > ret) - { - fprintf (stderr, "Decoding error: %s\n", opus_strerror (ret)); - break; - } - frame_size = ret; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Decoded %d bytes/channel (%d bytes) from %u compressed bytes\n", - ret, - ret * channels, - (unsigned int) op.bytes); - - /*Apply header gain, if we're not using an opus library new - enough to do this internally.*/ - if (0 != gain) - { - int i; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Applying gain %f\n", - gain); - for (i = 0; i < frame_size * channels; i++) - pcm_buffer[i] *= gain; + has_opus_stream = 0; + if (dec) + opus_decoder_destroy(dec); + dec = NULL; } - - /*This handles making sure that our output duration respects - the final end-trim by not letting the output sample count - get ahead of the granpos indicated value.*/ - maxout = ((page_granule - gran_offset) * SAMPLING_RATE / 48000) - link_out; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Writing audio packet %" PRId64 ", at most %" PRId64 " samples\n", - packet_count, maxout); - - outsamp = audio_write (0 > maxout ? 0 : maxout); - link_out += outsamp; - } - packet_count++; - } - if (eos) - { - has_opus_stream = 0; - if (dec) - opus_decoder_destroy (dec); - dec = NULL; } - } } @@ -560,31 +563,32 @@ ogg_demux_and_decode () * #GNUNET_SYSERR to stop further processing due to error */ static int -stdin_receiver (void *cls, - const struct GNUNET_MessageHeader *msg) +stdin_receiver(void *cls, + const struct GNUNET_MessageHeader *msg) { struct AudioMessage *audio; char *data; size_t payload_len; - (void) cls; - switch (ntohs (msg->type)) - { - case GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO: - audio = (struct AudioMessage *) msg; - payload_len = ntohs (audio->header.size) - sizeof (struct AudioMessage); - - /*Get the ogg buffer for writing*/ - data = ogg_sync_buffer (&oy, payload_len); - /*Read bitstream from input file*/ - GNUNET_memcpy (data, (const unsigned char *) &audio[1], payload_len); - ogg_sync_wrote (&oy, payload_len); - - ogg_demux_and_decode (); - break; - default: - break; - } + (void)cls; + switch (ntohs(msg->type)) + { + case GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO: + audio = (struct AudioMessage *)msg; + payload_len = ntohs(audio->header.size) - sizeof(struct AudioMessage); + + /*Get the ogg buffer for writing*/ + data = ogg_sync_buffer(&oy, payload_len); + /*Read bitstream from input file*/ + GNUNET_memcpy(data, (const unsigned char *)&audio[1], payload_len); + ogg_sync_wrote(&oy, payload_len); + + ogg_demux_and_decode(); + break; + + default: + break; + } return GNUNET_OK; } @@ -593,20 +597,20 @@ stdin_receiver (void *cls, * Callback when data is there for playback */ static void -stream_write_callback (pa_stream *s, - size_t length, - void *userdata) +stream_write_callback(pa_stream *s, + size_t length, + void *userdata) { /* unblock 'main' */ - (void) userdata; - (void) length; - (void) s; + (void)userdata; + (void)length; + (void)s; if (-1 != ready_pipe[1]) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Unblocking main loop!\n"); - (void) write (ready_pipe[1], "r", 1); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Unblocking main loop!\n"); + (void)write(ready_pipe[1], "r", 1); + } } @@ -614,18 +618,18 @@ stream_write_callback (pa_stream *s, * Exit callback for SIGTERM and SIGINT */ static void -exit_signal_callback (pa_mainloop_api *m, - pa_signal_event *e, - int sig, - void *userdata) +exit_signal_callback(pa_mainloop_api *m, + pa_signal_event *e, + int sig, + void *userdata) { - (void) m; - (void) e; - (void) sig; - (void) userdata; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("gnunet-helper-audio-playback - Got signal, exiting\n")); - quit (1); + (void)m; + (void)e; + (void)sig; + (void)userdata; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("gnunet-helper-audio-playback - Got signal, exiting\n")); + quit(1); } @@ -633,62 +637,64 @@ exit_signal_callback (pa_mainloop_api *m, * Pulseaudio stream state callback */ static void -context_state_callback (pa_context *c, - void *userdata) +context_state_callback(pa_context *c, + void *userdata) { int p; - (void) userdata; - GNUNET_assert (NULL != c); - switch (pa_context_get_state (c)) - { - case PA_CONTEXT_CONNECTING: - case PA_CONTEXT_AUTHORIZING: - case PA_CONTEXT_SETTING_NAME: - break; - case PA_CONTEXT_READY: - { - GNUNET_assert (! stream_out); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Connection established.\n")); - if (! (stream_out = - pa_stream_new (c, "GNUNET VoIP playback", &sample_spec, NULL))) + (void)userdata; + GNUNET_assert(NULL != c); + switch (pa_context_get_state(c)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_stream_new() failed: %s\n"), - pa_strerror (pa_context_errno (c))); - goto fail; - } - pa_stream_set_write_callback (stream_out, - &stream_write_callback, - NULL); - if ((p = - pa_stream_connect_playback (stream_out, NULL, - NULL, - PA_STREAM_ADJUST_LATENCY | PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE, - NULL, NULL)) < 0) + case PA_CONTEXT_CONNECTING: + case PA_CONTEXT_AUTHORIZING: + case PA_CONTEXT_SETTING_NAME: + break; + + case PA_CONTEXT_READY: { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_stream_connect_playback() failed: %s\n"), - pa_strerror (pa_context_errno (c))); + GNUNET_assert(!stream_out); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Connection established.\n")); + if (!(stream_out = + pa_stream_new(c, "GNUNET VoIP playback", &sample_spec, NULL))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_stream_new() failed: %s\n"), + pa_strerror(pa_context_errno(c))); + goto fail; + } + pa_stream_set_write_callback(stream_out, + &stream_write_callback, + NULL); + if ((p = + pa_stream_connect_playback(stream_out, NULL, + NULL, + PA_STREAM_ADJUST_LATENCY | PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE, + NULL, NULL)) < 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_stream_connect_playback() failed: %s\n"), + pa_strerror(pa_context_errno(c))); + goto fail; + } + break; + } + + case PA_CONTEXT_TERMINATED: + quit(0); + break; + + case PA_CONTEXT_FAILED: + default: + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Connection failure: %s\n"), + pa_strerror(pa_context_errno(c))); goto fail; } - break; - } - case PA_CONTEXT_TERMINATED: - quit (0); - break; - - case PA_CONTEXT_FAILED: - default: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Connection failure: %s\n"), - pa_strerror (pa_context_errno (c))); - goto fail; - } return; - fail: - quit (1); +fail: + quit(1); } @@ -696,66 +702,66 @@ context_state_callback (pa_context *c, * Pulseaudio initialization */ static void -pa_init () +pa_init() { int r; - if (!pa_sample_spec_valid (&sample_spec)) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Wrong Spec\n")); - } + if (!pa_sample_spec_valid(&sample_spec)) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Wrong Spec\n")); + } /* set up threaded playback mainloop */ - if (!(m = pa_threaded_mainloop_new ())) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_mainloop_new() failed.\n")); - } - mainloop_api = pa_threaded_mainloop_get_api (m); + if (!(m = pa_threaded_mainloop_new())) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_mainloop_new() failed.\n")); + } + mainloop_api = pa_threaded_mainloop_get_api(m); /* listen to signals */ - r = pa_signal_init (mainloop_api); - GNUNET_assert (r == 0); - pa_signal_new (SIGINT, exit_signal_callback, NULL); - pa_signal_new (SIGTERM, exit_signal_callback, NULL); + r = pa_signal_init(mainloop_api); + GNUNET_assert(r == 0); + pa_signal_new(SIGINT, exit_signal_callback, NULL); + pa_signal_new(SIGTERM, exit_signal_callback, NULL); /* connect to the main pulseaudio context */ - if (!(context = pa_context_new (mainloop_api, "GNUnet VoIP"))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_context_new() failed.\n")); - } - pa_context_set_state_callback (context, context_state_callback, NULL); - - if (pa_context_connect (context, NULL, 0, NULL) < 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_context_connect() failed: %s\n"), - pa_strerror (pa_context_errno (context))); - } - if (pa_threaded_mainloop_start (m) < 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_mainloop_run() failed.\n")); - } + if (!(context = pa_context_new(mainloop_api, "GNUnet VoIP"))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_context_new() failed.\n")); + } + pa_context_set_state_callback(context, context_state_callback, NULL); + + if (pa_context_connect(context, NULL, 0, NULL) < 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_context_connect() failed: %s\n"), + pa_strerror(pa_context_errno(context))); + } + if (pa_threaded_mainloop_start(m) < 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_mainloop_run() failed.\n")); + } } static void -ogg_init () +ogg_init() { - ogg_sync_init (&oy); + ogg_sync_init(&oy); } static void -drain_callback (pa_stream*s, int success, void *userdata) +drain_callback(pa_stream*s, int success, void *userdata) { - (void) s; - (void) success; - (void) userdata; - pa_threaded_mainloop_signal (m, - 0); + (void)s; + (void)success; + (void)userdata; + pa_threaded_mainloop_signal(m, + 0); } @@ -767,95 +773,96 @@ drain_callback (pa_stream*s, int success, void *userdata) * @return 0 ok, 1 on error */ int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { static unsigned long long toff; char readbuf[MAXLINE]; struct GNUNET_MessageStreamTokenizer *stdin_mst; char c; ssize_t ret; + #ifdef DEBUG_READ_PURE_OGG - int read_pure_ogg = getenv ("GNUNET_READ_PURE_OGG") ? 1 : 0; + int read_pure_ogg = getenv("GNUNET_READ_PURE_OGG") ? 1 : 0; #endif - (void) argc; - (void) argv; - GNUNET_assert (GNUNET_OK == - GNUNET_log_setup ("gnunet-helper-audio-playback", - "WARNING", - NULL)); - if (0 != pipe (ready_pipe)) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe"); - return 1; - } - stdin_mst = GNUNET_MST_create (&stdin_receiver, NULL); - ogg_init (); - pa_init (); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Waiting for PulseAudio to be ready.\n"); - GNUNET_assert (1 == read (ready_pipe[0], &c, 1)); - close (ready_pipe[0]); - close (ready_pipe[1]); + (void)argc; + (void)argv; + GNUNET_assert(GNUNET_OK == + GNUNET_log_setup("gnunet-helper-audio-playback", + "WARNING", + NULL)); + if (0 != pipe(ready_pipe)) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "pipe"); + return 1; + } + stdin_mst = GNUNET_MST_create(&stdin_receiver, NULL); + ogg_init(); + pa_init(); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Waiting for PulseAudio to be ready.\n"); + GNUNET_assert(1 == read(ready_pipe[0], &c, 1)); + close(ready_pipe[0]); + close(ready_pipe[1]); ready_pipe[0] = -1; ready_pipe[1] = -1; #ifdef DEBUG_DUMP_DECODED_OGG - dump_to_stdout = getenv ("GNUNET_DUMP_DECODED_OGG") ? 1 : 0; + dump_to_stdout = getenv("GNUNET_DUMP_DECODED_OGG") ? 1 : 0; #endif while (1) - { - ret = read (STDIN_FILENO, - readbuf, - sizeof (readbuf)); - toff += ret; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received %d bytes of audio data (total: %llu)\n", - (int) ret, - toff); - if (0 > ret) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Read error from STDIN: %s\n"), - strerror (errno)); - break; - } - if (0 == ret) - break; + ret = read(STDIN_FILENO, + readbuf, + sizeof(readbuf)); + toff += ret; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received %d bytes of audio data (total: %llu)\n", + (int)ret, + toff); + if (0 > ret) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Read error from STDIN: %s\n"), + strerror(errno)); + break; + } + if (0 == ret) + break; #ifdef DEBUG_READ_PURE_OGG - if (read_pure_ogg) - { - char *data = ogg_sync_buffer (&oy, ret); - GNUNET_memcpy (data, readbuf, ret); - ogg_sync_wrote (&oy, ret); - ogg_demux_and_decode (); - } - else + if (read_pure_ogg) + { + char *data = ogg_sync_buffer(&oy, ret); + GNUNET_memcpy(data, readbuf, ret); + ogg_sync_wrote(&oy, ret); + ogg_demux_and_decode(); + } + else #endif - GNUNET_MST_from_buffer (stdin_mst, - readbuf, ret, - GNUNET_NO, GNUNET_NO); - } - GNUNET_MST_destroy (stdin_mst); + GNUNET_MST_from_buffer(stdin_mst, + readbuf, ret, + GNUNET_NO, GNUNET_NO); + } + GNUNET_MST_destroy(stdin_mst); if (stream_out) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Locking\n"); - pa_threaded_mainloop_lock (m); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Draining\n"); - pa_operation *o = pa_stream_drain (stream_out, drain_callback, NULL); - while (pa_operation_get_state (o) == PA_OPERATION_RUNNING) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Waiting\n"); - pa_threaded_mainloop_wait (m); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Locking\n"); + pa_threaded_mainloop_lock(m); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Draining\n"); + pa_operation *o = pa_stream_drain(stream_out, drain_callback, NULL); + while (pa_operation_get_state(o) == PA_OPERATION_RUNNING) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Waiting\n"); + pa_threaded_mainloop_wait(m); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Unreffing\n"); + pa_operation_unref(o); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Unlocking\n"); + pa_threaded_mainloop_unlock(m); } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Unreffing\n"); - pa_operation_unref (o); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Unlocking\n"); - pa_threaded_mainloop_unlock (m); - } return 0; } diff --git a/src/conversation/gnunet-helper-audio-record-gst.c b/src/conversation/gnunet-helper-audio-record-gst.c index 78c94c83e..98ee97d15 100644 --- a/src/conversation/gnunet-helper-audio-record-gst.c +++ b/src/conversation/gnunet-helper-audio-record-gst.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/gnunet-helper-audio-record-gst.c * @brief program to record audio data from the microphone (GStreamer version) @@ -102,60 +102,61 @@ static int dump_pure_ogg; #endif static void -quit () +quit() { if (NULL != pipeline) - gst_element_set_state (pipeline, GST_STATE_NULL); + gst_element_set_state(pipeline, GST_STATE_NULL); } static gboolean -bus_call (GstBus *bus, GstMessage *msg, gpointer data) +bus_call(GstBus *bus, GstMessage *msg, gpointer data) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Bus message\n"); - switch (GST_MESSAGE_TYPE (msg)) - { - case GST_MESSAGE_EOS: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "End of stream\n"); - quit (); - break; - - case GST_MESSAGE_ERROR: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Bus message\n"); + switch (GST_MESSAGE_TYPE(msg)) + { + case GST_MESSAGE_EOS: + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "End of stream\n"); + quit(); + break; + + case GST_MESSAGE_ERROR: { gchar *debug; GError *error; - gst_message_parse_error (msg, &error, &debug); - g_free (debug); + gst_message_parse_error(msg, &error, &debug); + g_free(debug); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error: %s\n", error->message); - g_error_free (error); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error: %s\n", error->message); + g_error_free(error); - quit (); + quit(); + break; + } + + default: break; } - default: - break; - } return TRUE; } void -source_child_added (GstChildProxy *child_proxy, GObject *object, gchar *name, gpointer user_data) +source_child_added(GstChildProxy *child_proxy, GObject *object, gchar *name, gpointer user_data) { - if (GST_IS_AUDIO_BASE_SRC (object)) - g_object_set (object, "buffer-time", (gint64) BUFFER_TIME, "latency-time", (gint64) LATENCY_TIME, NULL); + if (GST_IS_AUDIO_BASE_SRC(object)) + g_object_set(object, "buffer-time", (gint64)BUFFER_TIME, "latency-time", (gint64)LATENCY_TIME, NULL); } static void -signalhandler (int s) +signalhandler(int s) { - quit (); + quit(); } int -main (int argc, char **argv) +main(int argc, char **argv) { GstElement *source, *filter, *encoder, *conv, *resampler, *sink, *oggmux; GstCaps *caps; @@ -167,218 +168,218 @@ main (int argc, char **argv) typedef void (*SignalHandlerPointer) (int); SignalHandlerPointer inthandler, termhandler; - inthandler = signal (SIGINT, signalhandler); - termhandler = signal (SIGTERM, signalhandler); + inthandler = signal(SIGINT, signalhandler); + termhandler = signal(SIGTERM, signalhandler); #ifdef DEBUG_RECORD_PURE_OGG - dump_pure_ogg = getenv ("GNUNET_RECORD_PURE_OGG") ? 1 : 0; + dump_pure_ogg = getenv("GNUNET_RECORD_PURE_OGG") ? 1 : 0; #endif #ifdef WINDOWS - setmode (1, _O_BINARY); + setmode(1, _O_BINARY); #endif /* Initialisation */ - gst_init (&argc, &argv); + gst_init(&argc, &argv); - GNUNET_assert (GNUNET_OK == - GNUNET_log_setup ("gnunet-helper-audio-record", - "WARNING", - NULL)); + GNUNET_assert(GNUNET_OK == + GNUNET_log_setup("gnunet-helper-audio-record", + "WARNING", + NULL)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Audio source starts\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Audio source starts\n"); - audio_message.header.type = htons (GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO); + audio_message.header.type = htons(GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO); /* Create gstreamer elements */ - pipeline = gst_pipeline_new ("audio-recorder"); - source = gst_element_factory_make ("autoaudiosrc", "audiosource"); - filter = gst_element_factory_make ("capsfilter", "filter"); - conv = gst_element_factory_make ("audioconvert", "converter"); - resampler= gst_element_factory_make ("audioresample", "resampler"); - encoder = gst_element_factory_make ("opusenc", "opus-encoder"); - oggmux = gst_element_factory_make ("oggmux", "ogg-muxer"); - sink = gst_element_factory_make ("appsink", "audio-output"); + pipeline = gst_pipeline_new("audio-recorder"); + source = gst_element_factory_make("autoaudiosrc", "audiosource"); + filter = gst_element_factory_make("capsfilter", "filter"); + conv = gst_element_factory_make("audioconvert", "converter"); + resampler = gst_element_factory_make("audioresample", "resampler"); + encoder = gst_element_factory_make("opusenc", "opus-encoder"); + oggmux = gst_element_factory_make("oggmux", "ogg-muxer"); + sink = gst_element_factory_make("appsink", "audio-output"); if (!pipeline || !filter || !source || !conv || !resampler || !encoder || !oggmux || !sink) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "One element could not be created. Exiting.\n"); - return -1; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "One element could not be created. Exiting.\n"); + return -1; + } - g_signal_connect (source, "child-added", G_CALLBACK (source_child_added), NULL); + g_signal_connect(source, "child-added", G_CALLBACK(source_child_added), NULL); /* Set up the pipeline */ - caps = gst_caps_new_simple ("audio/x-raw", - "format", G_TYPE_STRING, "S16LE", + caps = gst_caps_new_simple("audio/x-raw", + "format", G_TYPE_STRING, "S16LE", /* "rate", G_TYPE_INT, SAMPLING_RATE,*/ - "channels", G_TYPE_INT, OPUS_CHANNELS, + "channels", G_TYPE_INT, OPUS_CHANNELS, /* "layout", G_TYPE_STRING, "interleaved",*/ - NULL); - g_object_set (G_OBJECT (filter), - "caps", caps, - NULL); - gst_caps_unref (caps); + NULL); + g_object_set(G_OBJECT(filter), + "caps", caps, + NULL); + gst_caps_unref(caps); - g_object_set (G_OBJECT (encoder), + g_object_set(G_OBJECT(encoder), /* "bitrate", 64000, */ /* "bandwidth", OPUS_BANDWIDTH_FULLBAND, */ - "inband-fec", INBAND_FEC_MODE, - "packet-loss-percentage", PACKET_LOSS_PERCENTAGE, - "max-payload-size", MAX_PAYLOAD_SIZE, - "audio", FALSE, /* VoIP, not audio */ - "frame-size", OPUS_FRAME_SIZE, - NULL); - - g_object_set (G_OBJECT (oggmux), - "max-delay", OGG_MAX_DELAY, - "max-page-delay", OGG_MAX_PAGE_DELAY, - NULL); + "inband-fec", INBAND_FEC_MODE, + "packet-loss-percentage", PACKET_LOSS_PERCENTAGE, + "max-payload-size", MAX_PAYLOAD_SIZE, + "audio", FALSE, /* VoIP, not audio */ + "frame-size", OPUS_FRAME_SIZE, + NULL); + + g_object_set(G_OBJECT(oggmux), + "max-delay", OGG_MAX_DELAY, + "max-page-delay", OGG_MAX_PAGE_DELAY, + NULL); /* we add a message handler */ - bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); - bus_watch_id = gst_bus_add_watch (bus, bus_call, pipeline); - gst_object_unref (bus); + bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline)); + bus_watch_id = gst_bus_add_watch(bus, bus_call, pipeline); + gst_object_unref(bus); /* we add all elements into the pipeline */ /* audiosource | converter | resampler | opus-encoder | audio-output */ - gst_bin_add_many (GST_BIN (pipeline), source, filter, conv, resampler, encoder, - oggmux, sink, NULL); + gst_bin_add_many(GST_BIN(pipeline), source, filter, conv, resampler, encoder, + oggmux, sink, NULL); /* we link the elements together */ - gst_element_link_many (source, filter, conv, resampler, encoder, oggmux, sink, NULL); + gst_element_link_many(source, filter, conv, resampler, encoder, oggmux, sink, NULL); /* Set the pipeline to "playing" state*/ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Now playing\n"); - gst_element_set_state (pipeline, GST_STATE_PLAYING); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Now playing\n"); + gst_element_set_state(pipeline, GST_STATE_PLAYING); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Running...\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Running...\n"); /* Iterate */ while (!abort_send) - { - GstSample *s; - GstBuffer *b; - GstMapInfo m; - size_t len, msg_size; - const char *ptr; - int phase; - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "pulling...\n"); - s = gst_app_sink_pull_sample (GST_APP_SINK (sink)); - if (NULL == s) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "pulled NULL\n"); - break; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "...pulled!\n"); - { - const GstStructure *si; - char *si_str; - GstCaps *s_caps; - char *caps_str; - si = gst_sample_get_info (s); - if (si) - { - si_str = gst_structure_to_string (si); - if (si_str) + GstSample *s; + GstBuffer *b; + GstMapInfo m; + size_t len, msg_size; + const char *ptr; + int phase; + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "pulling...\n"); + s = gst_app_sink_pull_sample(GST_APP_SINK(sink)); + if (NULL == s) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got sample %s\n", si_str); - g_free (si_str); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "pulled NULL\n"); + break; } - } - else - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got sample with no info\n"); - s_caps = gst_sample_get_caps (s); - if (s_caps) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "...pulled!\n"); { - caps_str = gst_caps_to_string (s_caps); - if (caps_str) + const GstStructure *si; + char *si_str; + GstCaps *s_caps; + char *caps_str; + si = gst_sample_get_info(s); + if (si) + { + si_str = gst_structure_to_string(si); + if (si_str) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Got sample %s\n", si_str); + g_free(si_str); + } + } + else + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Got sample with no info\n"); + s_caps = gst_sample_get_caps(s); + if (s_caps) + { + caps_str = gst_caps_to_string(s_caps); + if (caps_str) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Got sample with caps %s\n", caps_str); + g_free(caps_str); + } + } + else + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Got sample with no caps\n"); + } + b = gst_sample_get_buffer(s); + if (NULL == b || !gst_buffer_map(b, &m, GST_MAP_READ)) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got sample with caps %s\n", caps_str); - g_free (caps_str); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "got NULL buffer %p or failed to map the buffer\n", b); + gst_sample_unref(s); + continue; } - } - else - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got sample with no caps\n"); - } - b = gst_sample_get_buffer (s); - if (NULL == b || !gst_buffer_map (b, &m, GST_MAP_READ)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got NULL buffer %p or failed to map the buffer\n", b); - gst_sample_unref (s); - continue; - } - len = m.size; - if (len > UINT16_MAX - sizeof (struct AudioMessage)) - { - GNUNET_break (0); - len = UINT16_MAX - sizeof (struct AudioMessage); - } - msg_size = sizeof (struct AudioMessage) + len; - audio_message.header.size = htons ((uint16_t) msg_size); + len = m.size; + if (len > UINT16_MAX - sizeof(struct AudioMessage)) + { + GNUNET_break(0); + len = UINT16_MAX - sizeof(struct AudioMessage); + } + msg_size = sizeof(struct AudioMessage) + len; + audio_message.header.size = htons((uint16_t)msg_size); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending %u bytes of audio data\n", (unsigned int) msg_size); - for (phase = 0; phase < 2; phase++) - { - size_t offset; - size_t to_send; - ssize_t ret; - if (0 == phase) - { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending %u bytes of audio data\n", (unsigned int)msg_size); + for (phase = 0; phase < 2; phase++) + { + size_t offset; + size_t to_send; + ssize_t ret; + if (0 == phase) + { #ifdef DEBUG_RECORD_PURE_OGG - if (dump_pure_ogg) - continue; + if (dump_pure_ogg) + continue; #endif - ptr = (const char *) &audio_message; - to_send = sizeof (audio_message); - } - else - { - ptr = (const char *) m.data; - to_send = len; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending %u bytes on phase %d\n", (unsigned int) to_send, phase); - for (offset = 0; offset < to_send; offset += ret) - { - ret = write (1, &ptr[offset], to_send - offset); - if (0 >= ret) - { - if (-1 == ret) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Failed to write %u bytes at offset %u (total %u) in phase %d: %s\n", - (unsigned int) (to_send - offset), - (unsigned int) offset, - (unsigned int) (to_send + offset), - phase, - strerror (errno)); - abort_send = 1; - break; + ptr = (const char *)&audio_message; + to_send = sizeof(audio_message); + } + else + { + ptr = (const char *)m.data; + to_send = len; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending %u bytes on phase %d\n", (unsigned int)to_send, phase); + for (offset = 0; offset < to_send; offset += ret) + { + ret = write(1, &ptr[offset], to_send - offset); + if (0 >= ret) + { + if (-1 == ret) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Failed to write %u bytes at offset %u (total %u) in phase %d: %s\n", + (unsigned int)(to_send - offset), + (unsigned int)offset, + (unsigned int)(to_send + offset), + phase, + strerror(errno)); + abort_send = 1; + break; + } + } + if (abort_send) + break; } - } - if (abort_send) - break; + gst_buffer_unmap(b, &m); + gst_sample_unref(s); } - gst_buffer_unmap (b, &m); - gst_sample_unref (s); - } - signal (SIGINT, inthandler); - signal (SIGINT, termhandler); + signal(SIGINT, inthandler); + signal(SIGINT, termhandler); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Returned, stopping playback\n"); - quit (); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Returned, stopping playback\n"); + quit(); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Deleting pipeline\n"); - gst_object_unref (GST_OBJECT (pipeline)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Deleting pipeline\n"); + gst_object_unref(GST_OBJECT(pipeline)); pipeline = NULL; - g_source_remove (bus_watch_id); + g_source_remove(bus_watch_id); return 0; } diff --git a/src/conversation/gnunet-helper-audio-record.c b/src/conversation/gnunet-helper-audio-record.c index f3f51e681..0cfc04578 100644 --- a/src/conversation/gnunet-helper-audio-record.c +++ b/src/conversation/gnunet-helper-audio-record.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/gnunet-helper-audio-record.c * @brief program to record audio data from the microphone @@ -149,8 +149,7 @@ static pa_sample_spec sample_spec = { GNUNET_NETWORK_STRUCT_BEGIN /* OggOpus spec says the numbers must be in little-endian order */ -struct OpusHeadPacket -{ +struct OpusHeadPacket { uint8_t magic[8]; uint8_t version; uint8_t channels; @@ -160,8 +159,7 @@ struct OpusHeadPacket uint8_t channel_mapping; }; -struct OpusCommentsPacket -{ +struct OpusCommentsPacket { uint8_t magic[8]; uint32_t vendor_length; /* followed by: @@ -267,61 +265,63 @@ static int dump_pure_ogg; * Pulseaudio shutdown task */ static void -quit (int ret) +quit(int ret) { - mainloop_api->quit (mainloop_api, - ret); - exit (ret); + mainloop_api->quit(mainloop_api, + ret); + exit(ret); } static void -write_data (const char *ptr, - size_t msg_size) +write_data(const char *ptr, + size_t msg_size) { ssize_t ret; size_t off; + off = 0; while (off < msg_size) - { - ret = write (STDOUT_FILENO, - &ptr[off], - msg_size - off); - if (0 >= ret) { - if (-1 == ret) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "write"); - quit (2); + ret = write(STDOUT_FILENO, + &ptr[off], + msg_size - off); + if (0 >= ret) + { + if (-1 == ret) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "write"); + quit(2); + } + off += ret; } - off += ret; - } } static void -write_page (ogg_page *og) +write_page(ogg_page *og) { static unsigned long long toff; size_t msg_size; - msg_size = sizeof (struct AudioMessage) + og->header_len + og->body_len; - audio_message->header.size = htons ((uint16_t) msg_size); - GNUNET_memcpy (&audio_message[1], og->header, og->header_len); - GNUNET_memcpy (((char *) &audio_message[1]) + og->header_len, og->body, og->body_len); + + msg_size = sizeof(struct AudioMessage) + og->header_len + og->body_len; + audio_message->header.size = htons((uint16_t)msg_size); + GNUNET_memcpy(&audio_message[1], og->header, og->header_len); + GNUNET_memcpy(((char *)&audio_message[1]) + og->header_len, og->body, og->body_len); toff += msg_size; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending %u bytes of audio data (total: %llu)\n", - (unsigned int) msg_size, - toff); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending %u bytes of audio data (total: %llu)\n", + (unsigned int)msg_size, + toff); #ifdef DEBUG_RECORD_PURE_OGG if (dump_pure_ogg) - write_data ((const char *) &audio_message[1], - og->header_len + og->body_len); + write_data((const char *)&audio_message[1], + og->header_len + og->body_len); else #endif - write_data ((const char *) audio_message, - msg_size); + write_data((const char *)audio_message, + msg_size); } @@ -329,7 +329,7 @@ write_page (ogg_page *og) * Creates OPUS packets from PCM data */ static void -packetizer () +packetizer() { char *nbuf; size_t new_size; @@ -338,68 +338,68 @@ packetizer () ogg_page og; while (transmit_buffer_length >= transmit_buffer_index + pcm_length) - { - GNUNET_memcpy (pcm_buffer, - &transmit_buffer[transmit_buffer_index], - pcm_length); - transmit_buffer_index += pcm_length; - len = - opus_encode_float (enc, pcm_buffer, FRAME_SIZE, opus_data, - MAX_PAYLOAD_BYTES); - - if (len < 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("opus_encode_float() failed: %s. Aborting\n"), - opus_strerror (len)); - quit (5); - } - if (((uint32_t)len) > UINT16_MAX - sizeof (struct AudioMessage)) - { - GNUNET_break (0); - continue; - } - - /* As per OggOpus spec, granule is calculated as if the audio - had 48kHz sampling rate. */ - enc_granulepos += FRAME_SIZE * 48000 / SAMPLING_RATE; - - op.packet = (unsigned char *) opus_data; - op.bytes = len; - op.b_o_s = 0; - op.e_o_s = 0; - op.granulepos = enc_granulepos; - op.packetno = packet_id++; - ogg_stream_packetin (&os, &op); - - while (ogg_stream_flush_fill (&os, &og, PAGE_WATERLINE)) { - if ( ((unsigned long long) og.header_len) + - ((unsigned long long) og.body_len) > - UINT16_MAX - sizeof (struct AudioMessage)) - { - GNUNET_assert (0); - continue; - } - write_page (&og); + GNUNET_memcpy(pcm_buffer, + &transmit_buffer[transmit_buffer_index], + pcm_length); + transmit_buffer_index += pcm_length; + len = + opus_encode_float(enc, pcm_buffer, FRAME_SIZE, opus_data, + MAX_PAYLOAD_BYTES); + + if (len < 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("opus_encode_float() failed: %s. Aborting\n"), + opus_strerror(len)); + quit(5); + } + if (((uint32_t)len) > UINT16_MAX - sizeof(struct AudioMessage)) + { + GNUNET_break(0); + continue; + } + + /* As per OggOpus spec, granule is calculated as if the audio + had 48kHz sampling rate. */ + enc_granulepos += FRAME_SIZE * 48000 / SAMPLING_RATE; + + op.packet = (unsigned char *)opus_data; + op.bytes = len; + op.b_o_s = 0; + op.e_o_s = 0; + op.granulepos = enc_granulepos; + op.packetno = packet_id++; + ogg_stream_packetin(&os, &op); + + while (ogg_stream_flush_fill(&os, &og, PAGE_WATERLINE)) + { + if (((unsigned long long)og.header_len) + + ((unsigned long long)og.body_len) > + UINT16_MAX - sizeof(struct AudioMessage)) + { + GNUNET_assert(0); + continue; + } + write_page(&og); + } } - } new_size = transmit_buffer_length - transmit_buffer_index; if (0 != new_size) - { - nbuf = pa_xmalloc (new_size); - memmove (nbuf, - &transmit_buffer[transmit_buffer_index], - new_size); - pa_xfree (transmit_buffer); - transmit_buffer = nbuf; - } + { + nbuf = pa_xmalloc(new_size); + memmove(nbuf, + &transmit_buffer[transmit_buffer_index], + new_size); + pa_xfree(transmit_buffer); + transmit_buffer = nbuf; + } else - { - pa_xfree (transmit_buffer); - transmit_buffer = NULL; - } + { + pa_xfree(transmit_buffer); + transmit_buffer = NULL; + } transmit_buffer_index = 0; transmit_buffer_length = new_size; } @@ -409,51 +409,51 @@ packetizer () * Pulseaudio callback when new data is available. */ static void -stream_read_callback (pa_stream * s, - size_t length, - void *userdata) +stream_read_callback(pa_stream * s, + size_t length, + void *userdata) { const void *data; - (void) userdata; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got %u/%d bytes of PCM data\n", - (unsigned int) length, - pcm_length); + (void)userdata; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got %u/%d bytes of PCM data\n", + (unsigned int)length, + pcm_length); - GNUNET_assert (NULL != s); - GNUNET_assert (length > 0); + GNUNET_assert(NULL != s); + GNUNET_assert(length > 0); if (stdio_event) - mainloop_api->io_enable (stdio_event, PA_IO_EVENT_OUTPUT); + mainloop_api->io_enable(stdio_event, PA_IO_EVENT_OUTPUT); - if (pa_stream_peek (s, (const void **) &data, &length) < 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_stream_peek() failed: %s\n"), - pa_strerror (pa_context_errno (context))); - quit (1); - return; - } - GNUNET_assert (NULL != data); - GNUNET_assert (length > 0); + if (pa_stream_peek(s, (const void **)&data, &length) < 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_stream_peek() failed: %s\n"), + pa_strerror(pa_context_errno(context))); + quit(1); + return; + } + GNUNET_assert(NULL != data); + GNUNET_assert(length > 0); if (NULL != transmit_buffer) - { - transmit_buffer = pa_xrealloc (transmit_buffer, - transmit_buffer_length + length); - GNUNET_memcpy (&transmit_buffer[transmit_buffer_length], - data, - length); - transmit_buffer_length += length; - } + { + transmit_buffer = pa_xrealloc(transmit_buffer, + transmit_buffer_length + length); + GNUNET_memcpy(&transmit_buffer[transmit_buffer_length], + data, + length); + transmit_buffer_length += length; + } else - { - transmit_buffer = pa_xmalloc (length); - GNUNET_memcpy (transmit_buffer, data, length); - transmit_buffer_length = length; - transmit_buffer_index = 0; - } - pa_stream_drop (s); - packetizer (); + { + transmit_buffer = pa_xmalloc(length); + GNUNET_memcpy(transmit_buffer, data, length); + transmit_buffer_length = length; + transmit_buffer_index = 0; + } + pa_stream_drop(s); + packetizer(); } @@ -461,18 +461,18 @@ stream_read_callback (pa_stream * s, * Exit callback for SIGTERM and SIGINT */ static void -exit_signal_callback (pa_mainloop_api * m, - pa_signal_event * e, - int sig, - void *userdata) +exit_signal_callback(pa_mainloop_api * m, + pa_signal_event * e, + int sig, + void *userdata) { - (void) m; - (void) e; - (void) sig; - (void) userdata; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Got signal, exiting.\n")); - quit (1); + (void)m; + (void)e; + (void)sig; + (void)userdata; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Got signal, exiting.\n")); + quit(1); } @@ -480,60 +480,61 @@ exit_signal_callback (pa_mainloop_api * m, * Pulseaudio stream state callback */ static void -stream_state_callback (pa_stream * s, - void *userdata) +stream_state_callback(pa_stream * s, + void *userdata) { - (void) userdata; - GNUNET_assert (NULL != s); - switch (pa_stream_get_state (s)) - { - case PA_STREAM_CREATING: - case PA_STREAM_TERMINATED: - break; - case PA_STREAM_READY: + (void)userdata; + GNUNET_assert(NULL != s); + switch (pa_stream_get_state(s)) + { + case PA_STREAM_CREATING: + case PA_STREAM_TERMINATED: + break; + + case PA_STREAM_READY: { const pa_buffer_attr *a; char cmt[PA_CHANNEL_MAP_SNPRINT_MAX]; char sst[PA_SAMPLE_SPEC_SNPRINT_MAX]; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Stream successfully created.\n")); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Stream successfully created.\n")); - if (!(a = pa_stream_get_buffer_attr (s))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_stream_get_buffer_attr() failed: %s\n"), - pa_strerror (pa_context_errno - (pa_stream_get_context (s)))); - - } + if (!(a = pa_stream_get_buffer_attr(s))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_stream_get_buffer_attr() failed: %s\n"), + pa_strerror(pa_context_errno + (pa_stream_get_context(s)))); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Buffer metrics: maxlength=%u, fragsize=%u\n"), - a->maxlength, a->fragsize); - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Using sample spec '%s', channel map '%s'.\n"), - pa_sample_spec_snprint (sst, sizeof (sst), - pa_stream_get_sample_spec (s)), - pa_channel_map_snprint (cmt, sizeof (cmt), - pa_stream_get_channel_map (s))); - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Connected to device %s (%u, %ssuspended).\n"), - pa_stream_get_device_name (s), - pa_stream_get_device_index (s), - pa_stream_is_suspended (s) ? "" : "not "); + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Buffer metrics: maxlength=%u, fragsize=%u\n"), + a->maxlength, a->fragsize); + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Using sample spec '%s', channel map '%s'.\n"), + pa_sample_spec_snprint(sst, sizeof(sst), + pa_stream_get_sample_spec(s)), + pa_channel_map_snprint(cmt, sizeof(cmt), + pa_stream_get_channel_map(s))); + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Connected to device %s (%u, %ssuspended).\n"), + pa_stream_get_device_name(s), + pa_stream_get_device_index(s), + pa_stream_is_suspended(s) ? "" : "not "); } break; - case PA_STREAM_FAILED: - default: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Stream error: %s\n"), - pa_strerror (pa_context_errno (pa_stream_get_context (s)))); - quit (1); - } + + case PA_STREAM_FAILED: + default: + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Stream error: %s\n"), + pa_strerror(pa_context_errno(pa_stream_get_context(s)))); + quit(1); + } } @@ -541,64 +542,67 @@ stream_state_callback (pa_stream * s, * Pulseaudio context state callback */ static void -context_state_callback (pa_context * c, - void *userdata) +context_state_callback(pa_context * c, + void *userdata) { - (void) userdata; - GNUNET_assert (c); + (void)userdata; + GNUNET_assert(c); - switch (pa_context_get_state (c)) - { - case PA_CONTEXT_CONNECTING: - case PA_CONTEXT_AUTHORIZING: - case PA_CONTEXT_SETTING_NAME: - break; - case PA_CONTEXT_READY: - { - int r; - pa_buffer_attr na; - - GNUNET_assert (!stream_in); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Connection established.\n")); - if (! (stream_in = - pa_stream_new (c, "GNUNET_VoIP recorder", &sample_spec, NULL))) + switch (pa_context_get_state(c)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_stream_new() failed: %s\n"), - pa_strerror (pa_context_errno (c))); - goto fail; - } - pa_stream_set_state_callback (stream_in, &stream_state_callback, NULL); - pa_stream_set_read_callback (stream_in, &stream_read_callback, NULL); - memset (&na, 0, sizeof (na)); - na.maxlength = UINT32_MAX; - na.fragsize = pcm_length; - if ((r = pa_stream_connect_record (stream_in, NULL, &na, - PA_STREAM_ADJUST_LATENCY)) < 0) + case PA_CONTEXT_CONNECTING: + case PA_CONTEXT_AUTHORIZING: + case PA_CONTEXT_SETTING_NAME: + break; + + case PA_CONTEXT_READY: { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_stream_connect_record() failed: %s\n"), - pa_strerror (pa_context_errno (c))); - goto fail; + int r; + pa_buffer_attr na; + + GNUNET_assert(!stream_in); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Connection established.\n")); + if (!(stream_in = + pa_stream_new(c, "GNUNET_VoIP recorder", &sample_spec, NULL))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_stream_new() failed: %s\n"), + pa_strerror(pa_context_errno(c))); + goto fail; + } + pa_stream_set_state_callback(stream_in, &stream_state_callback, NULL); + pa_stream_set_read_callback(stream_in, &stream_read_callback, NULL); + memset(&na, 0, sizeof(na)); + na.maxlength = UINT32_MAX; + na.fragsize = pcm_length; + if ((r = pa_stream_connect_record(stream_in, NULL, &na, + PA_STREAM_ADJUST_LATENCY)) < 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_stream_connect_record() failed: %s\n"), + pa_strerror(pa_context_errno(c))); + goto fail; + } + + break; } - break; - } - case PA_CONTEXT_TERMINATED: - quit (0); - break; - case PA_CONTEXT_FAILED: - default: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Connection failure: %s\n"), - pa_strerror (pa_context_errno (c))); - goto fail; - } + case PA_CONTEXT_TERMINATED: + quit(0); + break; + + case PA_CONTEXT_FAILED: + default: + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Connection failure: %s\n"), + pa_strerror(pa_context_errno(c))); + goto fail; + } return; fail: - quit (1); + quit(1); } @@ -606,49 +610,49 @@ fail: * Pulsaudio init */ static void -pa_init () +pa_init() { int r; int i; - if (!pa_sample_spec_valid (&sample_spec)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Wrong Spec\n")); - } + if (!pa_sample_spec_valid(&sample_spec)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Wrong Spec\n")); + } /* set up main record loop */ - if (!(m = pa_mainloop_new ())) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_mainloop_new() failed.\n")); - } - mainloop_api = pa_mainloop_get_api (m); + if (!(m = pa_mainloop_new())) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_mainloop_new() failed.\n")); + } + mainloop_api = pa_mainloop_get_api(m); /* listen to signals */ - r = pa_signal_init (mainloop_api); - GNUNET_assert (r == 0); - pa_signal_new (SIGINT, &exit_signal_callback, NULL); - pa_signal_new (SIGTERM, &exit_signal_callback, NULL); + r = pa_signal_init(mainloop_api); + GNUNET_assert(r == 0); + pa_signal_new(SIGINT, &exit_signal_callback, NULL); + pa_signal_new(SIGTERM, &exit_signal_callback, NULL); /* connect to the main pulseaudio context */ - if (!(context = pa_context_new (mainloop_api, "GNUNET VoIP"))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_context_new() failed.\n")); - } - pa_context_set_state_callback (context, &context_state_callback, NULL); - if (pa_context_connect (context, NULL, 0, NULL) < 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_context_connect() failed: %s\n"), - pa_strerror (pa_context_errno (context))); - } - if (pa_mainloop_run (m, &i) < 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("pa_mainloop_run() failed.\n")); - } + if (!(context = pa_context_new(mainloop_api, "GNUNET VoIP"))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_context_new() failed.\n")); + } + pa_context_set_state_callback(context, &context_state_callback, NULL); + if (pa_context_connect(context, NULL, 0, NULL) < 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_context_connect() failed: %s\n"), + pa_strerror(pa_context_errno(context))); + } + if (pa_mainloop_run(m, &i) < 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("pa_mainloop_run() failed.\n")); + } } @@ -656,45 +660,45 @@ pa_init () * OPUS init */ static void -opus_init () +opus_init() { int err; - pcm_length = FRAME_SIZE * CHANNELS * sizeof (float); - pcm_buffer = pa_xmalloc (pcm_length); - opus_data = GNUNET_malloc (MAX_PAYLOAD_BYTES); - enc = opus_encoder_create (SAMPLING_RATE, - CHANNELS, - CONV_OPUS_APP_TYPE, - &err); - opus_encoder_ctl (enc, - OPUS_SET_PACKET_LOSS_PERC (CONV_OPUS_PACKET_LOSS_PERCENTAGE)); - opus_encoder_ctl (enc, - OPUS_SET_COMPLEXITY (CONV_OPUS_ENCODING_COMPLEXITY)); - opus_encoder_ctl (enc, - OPUS_SET_INBAND_FEC (CONV_OPUS_INBAND_FEC)); - opus_encoder_ctl (enc, - OPUS_SET_SIGNAL (CONV_OPUS_SIGNAL)); + pcm_length = FRAME_SIZE * CHANNELS * sizeof(float); + pcm_buffer = pa_xmalloc(pcm_length); + opus_data = GNUNET_malloc(MAX_PAYLOAD_BYTES); + enc = opus_encoder_create(SAMPLING_RATE, + CHANNELS, + CONV_OPUS_APP_TYPE, + &err); + opus_encoder_ctl(enc, + OPUS_SET_PACKET_LOSS_PERC(CONV_OPUS_PACKET_LOSS_PERCENTAGE)); + opus_encoder_ctl(enc, + OPUS_SET_COMPLEXITY(CONV_OPUS_ENCODING_COMPLEXITY)); + opus_encoder_ctl(enc, + OPUS_SET_INBAND_FEC(CONV_OPUS_INBAND_FEC)); + opus_encoder_ctl(enc, + OPUS_SET_SIGNAL(CONV_OPUS_SIGNAL)); } static void -ogg_init () +ogg_init() { int serialno; struct OpusHeadPacket headpacket; struct OpusCommentsPacket *commentspacket; size_t commentspacket_len; - serialno = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, - 0x7FFFFFFF); + serialno = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, + 0x7FFFFFFF); /*Initialize Ogg stream struct*/ - if (-1 == ogg_stream_init (&os, serialno)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("ogg_stream_init() failed.\n")); - exit (3); - } + if (-1 == ogg_stream_init(&os, serialno)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("ogg_stream_init() failed.\n")); + exit(3); + } packet_id = 0; @@ -705,64 +709,64 @@ ogg_init () const char *opusver; int vendor_length; - GNUNET_memcpy (headpacket.magic, "OpusHead", 8); + GNUNET_memcpy(headpacket.magic, "OpusHead", 8); headpacket.version = 1; headpacket.channels = CHANNELS; - headpacket.preskip = GNUNET_htole16 (0); - headpacket.sampling_rate = GNUNET_htole32 (SAMPLING_RATE); - headpacket.gain = GNUNET_htole16 (0); + headpacket.preskip = GNUNET_htole16(0); + headpacket.sampling_rate = GNUNET_htole32(SAMPLING_RATE); + headpacket.gain = GNUNET_htole16(0); headpacket.channel_mapping = 0; /* Mono or stereo */ - op.packet = (unsigned char *) &headpacket; - op.bytes = sizeof (headpacket); + op.packet = (unsigned char *)&headpacket; + op.bytes = sizeof(headpacket); op.b_o_s = 1; op.e_o_s = 0; op.granulepos = 0; op.packetno = packet_id++; - ogg_stream_packetin (&os, &op); + ogg_stream_packetin(&os, &op); /* Head packet must be alone on its page */ - while (ogg_stream_flush (&os, &og)) - { - write_page (&og); - } + while (ogg_stream_flush(&os, &og)) + { + write_page(&og); + } - commentspacket_len = sizeof (*commentspacket); - opusver = opus_get_version_string (); - vendor_length = strlen (opusver); + commentspacket_len = sizeof(*commentspacket); + opusver = opus_get_version_string(); + vendor_length = strlen(opusver); commentspacket_len += vendor_length; - commentspacket_len += sizeof (uint32_t); + commentspacket_len += sizeof(uint32_t); - commentspacket = (struct OpusCommentsPacket *) malloc (commentspacket_len); + commentspacket = (struct OpusCommentsPacket *)malloc(commentspacket_len); if (NULL == commentspacket) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to allocate %u bytes for second packet\n"), - (unsigned int) commentspacket_len); - exit (5); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to allocate %u bytes for second packet\n"), + (unsigned int)commentspacket_len); + exit(5); + } - GNUNET_memcpy (commentspacket->magic, "OpusTags", 8); - commentspacket->vendor_length = GNUNET_htole32 (vendor_length); - GNUNET_memcpy (&commentspacket[1], opusver, vendor_length); - *(uint32_t *) &((char *) &commentspacket[1])[vendor_length] = \ - GNUNET_htole32 (0); /* no tags */ + GNUNET_memcpy(commentspacket->magic, "OpusTags", 8); + commentspacket->vendor_length = GNUNET_htole32(vendor_length); + GNUNET_memcpy(&commentspacket[1], opusver, vendor_length); + *(uint32_t *)&((char *)&commentspacket[1])[vendor_length] = \ + GNUNET_htole32(0); /* no tags */ - op.packet = (unsigned char *) commentspacket; + op.packet = (unsigned char *)commentspacket; op.bytes = commentspacket_len; op.b_o_s = 0; op.e_o_s = 0; op.granulepos = 0; op.packetno = packet_id++; - ogg_stream_packetin (&os, &op); + ogg_stream_packetin(&os, &op); /* Comment packets must not be mixed with audio packets on their pages */ - while (ogg_stream_flush (&os, &og)) - { - write_page (&og); - } + while (ogg_stream_flush(&os, &og)) + { + write_page(&og); + } - free (commentspacket); + free(commentspacket); } } @@ -774,25 +778,25 @@ ogg_init () * @return 0 ok, 1 on error */ int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { - (void) argc; - (void) argv; - GNUNET_assert (GNUNET_OK == - GNUNET_log_setup ("gnunet-helper-audio-record", - "WARNING", - NULL)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Audio source starts\n"); - audio_message = GNUNET_malloc (UINT16_MAX); - audio_message->header.type = htons (GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO); + (void)argc; + (void)argv; + GNUNET_assert(GNUNET_OK == + GNUNET_log_setup("gnunet-helper-audio-record", + "WARNING", + NULL)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Audio source starts\n"); + audio_message = GNUNET_malloc(UINT16_MAX); + audio_message->header.type = htons(GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO); #ifdef DEBUG_RECORD_PURE_OGG - dump_pure_ogg = getenv ("GNUNET_RECORD_PURE_OGG") ? 1 : 0; + dump_pure_ogg = getenv("GNUNET_RECORD_PURE_OGG") ? 1 : 0; #endif - ogg_init (); - opus_init (); - pa_init (); + ogg_init(); + opus_init(); + pa_init(); return 0; } diff --git a/src/conversation/gnunet-service-conversation.c b/src/conversation/gnunet-service-conversation.c index 3e531e202..e5e225623 100644 --- a/src/conversation/gnunet-service-conversation.c +++ b/src/conversation/gnunet-service-conversation.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet. - Copyright (C) 2013, 2016, 2017 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2013, 2016, 2017 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/gnunet-service-conversation.c * @brief conversation service implementation @@ -52,8 +52,7 @@ struct Line; /** * The possible connection status */ -enum ChannelStatus -{ +enum ChannelStatus { /** * We just got the connection, but no introduction yet. */ @@ -88,7 +87,6 @@ enum ChannelStatus * We're in shutdown, sending hangup messages before cleaning up. */ CS_CALLER_SHUTDOWN - }; @@ -98,9 +96,7 @@ enum ChannelStatus * be attached the the same `struct Line`, which represents a local * client. We keep them in a linked list. */ -struct Channel -{ - +struct Channel { /** * This is a DLL. */ @@ -156,8 +152,7 @@ struct Channel /** * A `struct Line` connects a local client with cadet channels. */ -struct Line -{ +struct Line { /** * This is a DLL. */ @@ -221,7 +216,7 @@ static struct GNUNET_PeerIdentity my_identity; * @return NULL for not found */ static struct Channel * -find_channel_by_line (struct Line *line, uint32_t cid) +find_channel_by_line(struct Line *line, uint32_t cid) { for (struct Channel *ch = line->channel_head; NULL != ch; ch = ch->next) if (cid == ch->cid) @@ -237,8 +232,8 @@ find_channel_by_line (struct Line *line, uint32_t cid) * @param msg the message from the client */ static void -handle_client_pickup_message (void *cls, - const struct ClientPhonePickupMessage *msg) +handle_client_pickup_message(void *cls, + const struct ClientPhonePickupMessage *msg) { struct Line *line = cls; struct CadetPhonePickupMessage *mppm; @@ -246,52 +241,56 @@ handle_client_pickup_message (void *cls, struct Channel *ch; if (NULL == line->port) - { - /* we never opened the port, bad client! */ - GNUNET_break_op (0); - GNUNET_SERVICE_client_drop (line->client); - return; - } + { + /* we never opened the port, bad client! */ + GNUNET_break_op(0); + GNUNET_SERVICE_client_drop(line->client); + return; + } for (ch = line->channel_head; NULL != ch; ch = ch->next) if (msg->cid == ch->cid) break; if (NULL == ch) - { - /* could have been destroyed asynchronously, ignore message */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel %u not found\n", msg->cid); - GNUNET_SERVICE_client_continue (line->client); - return; - } + { + /* could have been destroyed asynchronously, ignore message */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Channel %u not found\n", msg->cid); + GNUNET_SERVICE_client_continue(line->client); + return; + } switch (ch->status) - { - case CS_CALLEE_INIT: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - case CS_CALLEE_RINGING: - ch->status = CS_CALLEE_CONNECTED; - break; - case CS_CALLEE_CONNECTED: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - case CS_CALLEE_SHUTDOWN: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Ignoring client's PICKUP message, line is in SHUTDOWN\n"); - break; - case CS_CALLER_CALLING: - case CS_CALLER_CONNECTED: - case CS_CALLER_SHUTDOWN: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - } - GNUNET_break (CS_CALLEE_CONNECTED == ch->status); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending PICK_UP message to cadet\n"); + { + case CS_CALLEE_INIT: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + + case CS_CALLEE_RINGING: + ch->status = CS_CALLEE_CONNECTED; + break; + + case CS_CALLEE_CONNECTED: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + + case CS_CALLEE_SHUTDOWN: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Ignoring client's PICKUP message, line is in SHUTDOWN\n"); + break; + + case CS_CALLER_CALLING: + case CS_CALLER_CONNECTED: + case CS_CALLER_SHUTDOWN: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + } + GNUNET_break(CS_CALLEE_CONNECTED == ch->status); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending PICK_UP message to cadet\n"); env = - GNUNET_MQ_msg (mppm, GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_PICK_UP); - GNUNET_MQ_send (ch->mq, env); - GNUNET_SERVICE_client_continue (line->client); + GNUNET_MQ_msg(mppm, GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_PICK_UP); + GNUNET_MQ_send(ch->mq, env); + GNUNET_SERVICE_client_continue(line->client); } @@ -302,34 +301,35 @@ handle_client_pickup_message (void *cls, * @param ch channel that went down */ static void -clean_up_channel (struct Channel *ch) +clean_up_channel(struct Channel *ch) { struct Line *line = ch->line; struct GNUNET_MQ_Envelope *env; struct ClientPhoneHangupMessage *hup; switch (ch->status) - { - case CS_CALLEE_INIT: - case CS_CALLEE_SHUTDOWN: - case CS_CALLER_SHUTDOWN: - break; - case CS_CALLEE_RINGING: - case CS_CALLEE_CONNECTED: - case CS_CALLER_CALLING: - case CS_CALLER_CONNECTED: - if (NULL != line) { - env = - GNUNET_MQ_msg (hup, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP); - hup->cid = ch->cid; - GNUNET_MQ_send (line->mq, env); + case CS_CALLEE_INIT: + case CS_CALLEE_SHUTDOWN: + case CS_CALLER_SHUTDOWN: + break; + + case CS_CALLEE_RINGING: + case CS_CALLEE_CONNECTED: + case CS_CALLER_CALLING: + case CS_CALLER_CONNECTED: + if (NULL != line) + { + env = + GNUNET_MQ_msg(hup, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP); + hup->cid = ch->cid; + GNUNET_MQ_send(line->mq, env); + } + break; } - break; - } if (NULL != line) - GNUNET_CONTAINER_DLL_remove (line->channel_head, line->channel_tail, ch); - GNUNET_free (ch); + GNUNET_CONTAINER_DLL_remove(line->channel_head, line->channel_tail, ch); + GNUNET_free(ch); } @@ -339,15 +339,15 @@ clean_up_channel (struct Channel *ch) * @param ch channel to destroy. */ static void -destroy_line_cadet_channels (struct Channel *ch) +destroy_line_cadet_channels(struct Channel *ch) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Destroying cadet channels\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Destroying cadet channels\n"); if (NULL != ch->channel) - { - GNUNET_CADET_channel_destroy (ch->channel); - ch->channel = NULL; - } - clean_up_channel (ch); + { + GNUNET_CADET_channel_destroy(ch->channel); + ch->channel = NULL; + } + clean_up_channel(ch); } @@ -358,34 +358,40 @@ destroy_line_cadet_channels (struct Channel *ch) * @param cls the `struct Channel` to reset/terminate */ static void -mq_done_finish_caller_shutdown (void *cls) +mq_done_finish_caller_shutdown(void *cls) { struct Channel *ch = cls; switch (ch->status) - { - case CS_CALLEE_INIT: - GNUNET_break (0); - break; - case CS_CALLEE_RINGING: - GNUNET_break (0); - break; - case CS_CALLEE_CONNECTED: - GNUNET_break (0); - break; - case CS_CALLEE_SHUTDOWN: - destroy_line_cadet_channels (ch); - break; - case CS_CALLER_CALLING: - GNUNET_break (0); - break; - case CS_CALLER_CONNECTED: - GNUNET_break (0); - break; - case CS_CALLER_SHUTDOWN: - destroy_line_cadet_channels (ch); - break; - } + { + case CS_CALLEE_INIT: + GNUNET_break(0); + break; + + case CS_CALLEE_RINGING: + GNUNET_break(0); + break; + + case CS_CALLEE_CONNECTED: + GNUNET_break(0); + break; + + case CS_CALLEE_SHUTDOWN: + destroy_line_cadet_channels(ch); + break; + + case CS_CALLER_CALLING: + GNUNET_break(0); + break; + + case CS_CALLER_CONNECTED: + GNUNET_break(0); + break; + + case CS_CALLER_SHUTDOWN: + destroy_line_cadet_channels(ch); + break; + } } @@ -396,8 +402,8 @@ mq_done_finish_caller_shutdown (void *cls) * @param msg the message from the client */ static void -handle_client_hangup_message (void *cls, - const struct ClientPhoneHangupMessage *msg) +handle_client_hangup_message(void *cls, + const struct ClientPhoneHangupMessage *msg) { struct Line *line = cls; struct GNUNET_MQ_Envelope *e; @@ -408,49 +414,55 @@ handle_client_hangup_message (void *cls, if (msg->cid == ch->cid) break; if (NULL == ch) - { - /* could have been destroyed asynchronously, ignore message */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel %u not found\n", msg->cid); - GNUNET_SERVICE_client_continue (line->client); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received HANGUP for channel %u which is in state %d\n", - msg->cid, - ch->status); + { + /* could have been destroyed asynchronously, ignore message */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Channel %u not found\n", msg->cid); + GNUNET_SERVICE_client_continue(line->client); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received HANGUP for channel %u which is in state %d\n", + msg->cid, + ch->status); switch (ch->status) - { - case CS_CALLEE_INIT: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - case CS_CALLEE_RINGING: - ch->status = CS_CALLEE_SHUTDOWN; - break; - case CS_CALLEE_CONNECTED: - ch->status = CS_CALLEE_SHUTDOWN; - break; - case CS_CALLEE_SHUTDOWN: - /* maybe the other peer closed asynchronously... */ - GNUNET_SERVICE_client_continue (line->client); - return; - case CS_CALLER_CALLING: - ch->status = CS_CALLER_SHUTDOWN; - break; - case CS_CALLER_CONNECTED: - ch->status = CS_CALLER_SHUTDOWN; - break; - case CS_CALLER_SHUTDOWN: - /* maybe the other peer closed asynchronously... */ - GNUNET_SERVICE_client_continue (line->client); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending HANG_UP message via cadet\n"); + { + case CS_CALLEE_INIT: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + + case CS_CALLEE_RINGING: + ch->status = CS_CALLEE_SHUTDOWN; + break; + + case CS_CALLEE_CONNECTED: + ch->status = CS_CALLEE_SHUTDOWN; + break; + + case CS_CALLEE_SHUTDOWN: + /* maybe the other peer closed asynchronously... */ + GNUNET_SERVICE_client_continue(line->client); + return; + + case CS_CALLER_CALLING: + ch->status = CS_CALLER_SHUTDOWN; + break; + + case CS_CALLER_CONNECTED: + ch->status = CS_CALLER_SHUTDOWN; + break; + + case CS_CALLER_SHUTDOWN: + /* maybe the other peer closed asynchronously... */ + GNUNET_SERVICE_client_continue(line->client); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending HANG_UP message via cadet\n"); e = - GNUNET_MQ_msg (mhum, GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_HANG_UP); - GNUNET_MQ_notify_sent (e, &mq_done_finish_caller_shutdown, ch); - GNUNET_MQ_send (ch->mq, e); - GNUNET_SERVICE_client_continue (line->client); + GNUNET_MQ_msg(mhum, GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_HANG_UP); + GNUNET_MQ_notify_sent(e, &mq_done_finish_caller_shutdown, ch); + GNUNET_MQ_send(ch->mq, e); + GNUNET_SERVICE_client_continue(line->client); } @@ -461,8 +473,8 @@ handle_client_hangup_message (void *cls, * @param msg the message from the client */ static void -handle_client_suspend_message (void *cls, - const struct ClientPhoneSuspendMessage *msg) +handle_client_suspend_message(void *cls, + const struct ClientPhoneSuspendMessage *msg) { struct Line *line = cls; struct GNUNET_MQ_Envelope *e; @@ -473,56 +485,62 @@ handle_client_suspend_message (void *cls, if (msg->cid == ch->cid) break; if (NULL == ch) - { - /* could have been destroyed asynchronously, ignore message */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel %u not found\n", msg->cid); - GNUNET_SERVICE_client_continue (line->client); - return; - } + { + /* could have been destroyed asynchronously, ignore message */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Channel %u not found\n", msg->cid); + GNUNET_SERVICE_client_continue(line->client); + return; + } if (GNUNET_YES == ch->suspended_local) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received SUSPEND for channel %u which is in state %d\n", - msg->cid, - ch->status); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received SUSPEND for channel %u which is in state %d\n", + msg->cid, + ch->status); switch (ch->status) - { - case CS_CALLEE_INIT: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - case CS_CALLEE_RINGING: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - case CS_CALLEE_CONNECTED: - ch->suspended_local = GNUNET_YES; - break; - case CS_CALLEE_SHUTDOWN: - /* maybe the other peer closed asynchronously... */ - GNUNET_SERVICE_client_continue (line->client); - return; - case CS_CALLER_CALLING: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - case CS_CALLER_CONNECTED: - ch->suspended_local = GNUNET_YES; - break; - case CS_CALLER_SHUTDOWN: - /* maybe the other peer closed asynchronously... */ - GNUNET_SERVICE_client_continue (line->client); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending SUSPEND message via cadet\n"); + { + case CS_CALLEE_INIT: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + + case CS_CALLEE_RINGING: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + + case CS_CALLEE_CONNECTED: + ch->suspended_local = GNUNET_YES; + break; + + case CS_CALLEE_SHUTDOWN: + /* maybe the other peer closed asynchronously... */ + GNUNET_SERVICE_client_continue(line->client); + return; + + case CS_CALLER_CALLING: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + + case CS_CALLER_CONNECTED: + ch->suspended_local = GNUNET_YES; + break; + + case CS_CALLER_SHUTDOWN: + /* maybe the other peer closed asynchronously... */ + GNUNET_SERVICE_client_continue(line->client); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending SUSPEND message via cadet\n"); e = - GNUNET_MQ_msg (mhum, GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_SUSPEND); - GNUNET_MQ_send (ch->mq, e); - GNUNET_SERVICE_client_continue (line->client); + GNUNET_MQ_msg(mhum, GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_SUSPEND); + GNUNET_MQ_send(ch->mq, e); + GNUNET_SERVICE_client_continue(line->client); } @@ -533,8 +551,8 @@ handle_client_suspend_message (void *cls, * @param msg the message from the client */ static void -handle_client_resume_message (void *cls, - const struct ClientPhoneResumeMessage *msg) +handle_client_resume_message(void *cls, + const struct ClientPhoneResumeMessage *msg) { struct Line *line = cls; struct GNUNET_MQ_Envelope *e; @@ -545,55 +563,61 @@ handle_client_resume_message (void *cls, if (msg->cid == ch->cid) break; if (NULL == ch) - { - /* could have been destroyed asynchronously, ignore message */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel %u not found\n", msg->cid); - GNUNET_SERVICE_client_continue (line->client); - return; - } + { + /* could have been destroyed asynchronously, ignore message */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Channel %u not found\n", msg->cid); + GNUNET_SERVICE_client_continue(line->client); + return; + } if (GNUNET_YES != ch->suspended_local) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received RESUME for channel %u which is in state %d\n", - msg->cid, - ch->status); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received RESUME for channel %u which is in state %d\n", + msg->cid, + ch->status); switch (ch->status) - { - case CS_CALLEE_INIT: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - case CS_CALLEE_RINGING: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - case CS_CALLEE_CONNECTED: - ch->suspended_local = GNUNET_NO; - break; - case CS_CALLEE_SHUTDOWN: - /* maybe the other peer closed asynchronously... */ - GNUNET_SERVICE_client_continue (line->client); - return; - case CS_CALLER_CALLING: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - case CS_CALLER_CONNECTED: - ch->suspended_local = GNUNET_NO; - break; - case CS_CALLER_SHUTDOWN: - /* maybe the other peer closed asynchronously... */ - GNUNET_SERVICE_client_drop (line->client); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending RESUME message via cadet\n"); - e = GNUNET_MQ_msg (mhum, GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_RESUME); - GNUNET_MQ_send (ch->mq, e); - GNUNET_SERVICE_client_continue (line->client); + { + case CS_CALLEE_INIT: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + + case CS_CALLEE_RINGING: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + + case CS_CALLEE_CONNECTED: + ch->suspended_local = GNUNET_NO; + break; + + case CS_CALLEE_SHUTDOWN: + /* maybe the other peer closed asynchronously... */ + GNUNET_SERVICE_client_continue(line->client); + return; + + case CS_CALLER_CALLING: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + + case CS_CALLER_CONNECTED: + ch->suspended_local = GNUNET_NO; + break; + + case CS_CALLER_SHUTDOWN: + /* maybe the other peer closed asynchronously... */ + GNUNET_SERVICE_client_drop(line->client); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending RESUME message via cadet\n"); + e = GNUNET_MQ_msg(mhum, GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_RESUME); + GNUNET_MQ_send(ch->mq, e); + GNUNET_SERVICE_client_continue(line->client); } @@ -603,7 +627,7 @@ handle_client_resume_message (void *cls, * @param cls the `struct Channel` we are transmitting for */ static void -channel_audio_sent_notify (void *cls) +channel_audio_sent_notify(void *cls) { struct Channel *ch = cls; @@ -619,10 +643,10 @@ channel_audio_sent_notify (void *cls) * @return #GNUNET_OK (any data is ok) */ static int -check_client_audio_message (void *cls, const struct ClientAudioMessage *msg) +check_client_audio_message(void *cls, const struct ClientAudioMessage *msg) { - (void) cls; - (void) msg; + (void)cls; + (void)msg; return GNUNET_OK; } @@ -634,70 +658,72 @@ check_client_audio_message (void *cls, const struct ClientAudioMessage *msg) * @param msg the message from the client */ static void -handle_client_audio_message (void *cls, const struct ClientAudioMessage *msg) +handle_client_audio_message(void *cls, const struct ClientAudioMessage *msg) { struct Line *line = cls; struct CadetAudioMessage *mam; struct Channel *ch; size_t size; - size = ntohs (msg->header.size) - sizeof (struct ClientAudioMessage); - ch = find_channel_by_line (line, msg->cid); + size = ntohs(msg->header.size) - sizeof(struct ClientAudioMessage); + ch = find_channel_by_line(line, msg->cid); if (NULL == ch) - { - /* could have been destroyed asynchronously, ignore message */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Channel %u not found\n", msg->cid); - GNUNET_SERVICE_client_continue (line->client); - return; - } + { + /* could have been destroyed asynchronously, ignore message */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Channel %u not found\n", msg->cid); + GNUNET_SERVICE_client_continue(line->client); + return; + } switch (ch->status) - { - case CS_CALLEE_INIT: - case CS_CALLEE_RINGING: - case CS_CALLER_CALLING: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (line->client); - return; - case CS_CALLEE_CONNECTED: - case CS_CALLER_CONNECTED: - /* common case, handled below */ - break; - case CS_CALLEE_SHUTDOWN: - case CS_CALLER_SHUTDOWN: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, - "Cadet audio channel in shutdown; audio data dropped\n"); - GNUNET_SERVICE_client_continue (line->client); - return; - } + { + case CS_CALLEE_INIT: + case CS_CALLEE_RINGING: + case CS_CALLER_CALLING: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(line->client); + return; + + case CS_CALLEE_CONNECTED: + case CS_CALLER_CONNECTED: + /* common case, handled below */ + break; + + case CS_CALLEE_SHUTDOWN: + case CS_CALLER_SHUTDOWN: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, + "Cadet audio channel in shutdown; audio data dropped\n"); + GNUNET_SERVICE_client_continue(line->client); + return; + } if (GNUNET_YES == ch->suspended_local) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "This channel is suspended locally\n"); - GNUNET_SERVICE_client_drop (line->client); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "This channel is suspended locally\n"); + GNUNET_SERVICE_client_drop(line->client); + return; + } if (NULL != ch->env) - { - /* NOTE: we may want to not do this and instead combine the data */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Bandwidth insufficient; dropping previous audio data segment\n"); - GNUNET_MQ_send_cancel (ch->env); - ch->env = NULL; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received %u bytes of AUDIO data from client CID %u\n", - (unsigned int) size, - msg->cid); - ch->env = GNUNET_MQ_msg_extra (mam, - size, - GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_AUDIO); - GNUNET_memcpy (&mam[1], &msg[1], size); + { + /* NOTE: we may want to not do this and instead combine the data */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Bandwidth insufficient; dropping previous audio data segment\n"); + GNUNET_MQ_send_cancel(ch->env); + ch->env = NULL; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received %u bytes of AUDIO data from client CID %u\n", + (unsigned int)size, + msg->cid); + ch->env = GNUNET_MQ_msg_extra(mam, + size, + GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_AUDIO); + GNUNET_memcpy(&mam[1], &msg[1], size); /* FIXME: set options for unreliable transmission */ - GNUNET_MQ_notify_sent (ch->env, &channel_audio_sent_notify, ch); - GNUNET_MQ_send (ch->mq, ch->env); - GNUNET_SERVICE_client_continue (line->client); + GNUNET_MQ_notify_sent(ch->env, &channel_audio_sent_notify, ch); + GNUNET_MQ_send(ch->mq, ch->env); + GNUNET_SERVICE_client_continue(line->client); } @@ -708,7 +734,7 @@ handle_client_audio_message (void *cls, const struct ClientAudioMessage *msg) * @param msg the incoming message */ static void -handle_cadet_ring_message (void *cls, const struct CadetPhoneRingMessage *msg) +handle_cadet_ring_message(void *cls, const struct CadetPhoneRingMessage *msg) { struct Channel *ch = cls; struct Line *line = ch->line; @@ -716,49 +742,49 @@ handle_cadet_ring_message (void *cls, const struct CadetPhoneRingMessage *msg) struct ClientPhoneRingMessage *cring; struct CadetPhoneRingInfoPS rs; - rs.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CONVERSATION_RING); - rs.purpose.size = htonl (sizeof (struct CadetPhoneRingInfoPS)); + rs.purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_CONVERSATION_RING); + rs.purpose.size = htonl(sizeof(struct CadetPhoneRingInfoPS)); rs.line_port = line->line_port; rs.target_peer = my_identity; rs.expiration_time = msg->expiration_time; if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_CONVERSATION_RING, - &rs.purpose, - &msg->signature, - &msg->caller_id)) - { - GNUNET_break_op (0); - destroy_line_cadet_channels (ch); - return; - } - if (0 == GNUNET_TIME_absolute_get_remaining ( - GNUNET_TIME_absolute_ntoh (msg->expiration_time)) - .rel_value_us) - { - /* ancient call, replay? */ - GNUNET_break_op (0); - /* Note that our reliance on time here is awkward; better would be - to use a more complex challenge-response protocol against - replay attacks. Left for future work ;-). */ - destroy_line_cadet_channels (ch); - return; - } + GNUNET_CRYPTO_ecdsa_verify(GNUNET_SIGNATURE_PURPOSE_CONVERSATION_RING, + &rs.purpose, + &msg->signature, + &msg->caller_id)) + { + GNUNET_break_op(0); + destroy_line_cadet_channels(ch); + return; + } + if (0 == GNUNET_TIME_absolute_get_remaining( + GNUNET_TIME_absolute_ntoh(msg->expiration_time)) + .rel_value_us) + { + /* ancient call, replay? */ + GNUNET_break_op(0); + /* Note that our reliance on time here is awkward; better would be + to use a more complex challenge-response protocol against + replay attacks. Left for future work ;-). */ + destroy_line_cadet_channels(ch); + return; + } if (CS_CALLEE_INIT != ch->status) - { - GNUNET_break_op (0); - destroy_line_cadet_channels (ch); - return; - } - GNUNET_CADET_receive_done (ch->channel); + { + GNUNET_break_op(0); + destroy_line_cadet_channels(ch); + return; + } + GNUNET_CADET_receive_done(ch->channel); ch->status = CS_CALLEE_RINGING; - env = GNUNET_MQ_msg (cring, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RING); + env = GNUNET_MQ_msg(cring, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RING); cring->cid = ch->cid; cring->caller_id = msg->caller_id; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending RING message to client. CID is %u\n", - (unsigned int) ch->cid); - GNUNET_MQ_send (line->mq, env); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending RING message to client. CID is %u\n", + (unsigned int)ch->cid); + GNUNET_MQ_send(line->mq, env); } @@ -769,8 +795,8 @@ handle_cadet_ring_message (void *cls, const struct CadetPhoneRingMessage *msg) * @param message the incoming message */ static void -handle_cadet_hangup_message (void *cls, - const struct CadetPhoneHangupMessage *message) +handle_cadet_hangup_message(void *cls, + const struct CadetPhoneHangupMessage *message) { struct Channel *ch = cls; struct Line *line = ch->line; @@ -779,31 +805,35 @@ handle_cadet_hangup_message (void *cls, enum ChannelStatus status; uint32_t cid; - (void) message; - GNUNET_CADET_receive_done (ch->channel); + (void)message; + GNUNET_CADET_receive_done(ch->channel); cid = ch->cid; status = ch->status; - destroy_line_cadet_channels (ch); + destroy_line_cadet_channels(ch); switch (status) - { - case CS_CALLEE_INIT: - GNUNET_break_op (0); - return; - case CS_CALLEE_RINGING: - case CS_CALLEE_CONNECTED: - break; - case CS_CALLEE_SHUTDOWN: - return; - case CS_CALLER_CALLING: - case CS_CALLER_CONNECTED: - break; - case CS_CALLER_SHUTDOWN: - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending HANG UP message to client\n"); - env = GNUNET_MQ_msg (hup, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP); + { + case CS_CALLEE_INIT: + GNUNET_break_op(0); + return; + + case CS_CALLEE_RINGING: + case CS_CALLEE_CONNECTED: + break; + + case CS_CALLEE_SHUTDOWN: + return; + + case CS_CALLER_CALLING: + case CS_CALLER_CONNECTED: + break; + + case CS_CALLER_SHUTDOWN: + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending HANG UP message to client\n"); + env = GNUNET_MQ_msg(hup, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP); hup->cid = cid; - GNUNET_MQ_send (line->mq, env); + GNUNET_MQ_send(line->mq, env); } @@ -814,44 +844,48 @@ handle_cadet_hangup_message (void *cls, * @param message the incoming message */ static void -handle_cadet_pickup_message (void *cls, - const struct CadetPhonePickupMessage *message) +handle_cadet_pickup_message(void *cls, + const struct CadetPhonePickupMessage *message) { struct Channel *ch = cls; struct Line *line = ch->line; struct GNUNET_MQ_Envelope *env; struct ClientPhonePickedupMessage *pick; - (void) message; - GNUNET_CADET_receive_done (ch->channel); + (void)message; + GNUNET_CADET_receive_done(ch->channel); switch (ch->status) - { - case CS_CALLEE_INIT: - case CS_CALLEE_RINGING: - case CS_CALLEE_CONNECTED: - GNUNET_break_op (0); - destroy_line_cadet_channels (ch); - return; - case CS_CALLEE_SHUTDOWN: - GNUNET_break_op (0); - destroy_line_cadet_channels (ch); - return; - case CS_CALLER_CALLING: - ch->status = CS_CALLER_CONNECTED; - break; - case CS_CALLER_CONNECTED: - GNUNET_break_op (0); - return; - case CS_CALLER_SHUTDOWN: - GNUNET_break_op (0); - mq_done_finish_caller_shutdown (ch); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending PICKED UP message to client\n"); + { + case CS_CALLEE_INIT: + case CS_CALLEE_RINGING: + case CS_CALLEE_CONNECTED: + GNUNET_break_op(0); + destroy_line_cadet_channels(ch); + return; + + case CS_CALLEE_SHUTDOWN: + GNUNET_break_op(0); + destroy_line_cadet_channels(ch); + return; + + case CS_CALLER_CALLING: + ch->status = CS_CALLER_CONNECTED; + break; + + case CS_CALLER_CONNECTED: + GNUNET_break_op(0); + return; + + case CS_CALLER_SHUTDOWN: + GNUNET_break_op(0); + mq_done_finish_caller_shutdown(ch); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending PICKED UP message to client\n"); env = - GNUNET_MQ_msg (pick, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_PICKED_UP); + GNUNET_MQ_msg(pick, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_PICKED_UP); pick->cid = ch->cid; - GNUNET_MQ_send (line->mq, env); + GNUNET_MQ_send(line->mq, env); } @@ -862,43 +896,49 @@ handle_cadet_pickup_message (void *cls, * @param message the incoming message */ static void -handle_cadet_suspend_message (void *cls, - const struct CadetPhoneSuspendMessage *message) +handle_cadet_suspend_message(void *cls, + const struct CadetPhoneSuspendMessage *message) { struct Channel *ch = cls; struct Line *line = ch->line; struct GNUNET_MQ_Envelope *env; struct ClientPhoneSuspendMessage *suspend; - (void) message; - GNUNET_CADET_receive_done (ch->channel); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Suspending channel CID: %u\n", ch->cid); + (void)message; + GNUNET_CADET_receive_done(ch->channel); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Suspending channel CID: %u\n", ch->cid); switch (ch->status) - { - case CS_CALLEE_INIT: - GNUNET_break_op (0); - break; - case CS_CALLEE_RINGING: - GNUNET_break_op (0); - break; - case CS_CALLEE_CONNECTED: - ch->suspended_remote = GNUNET_YES; - break; - case CS_CALLEE_SHUTDOWN: - return; - case CS_CALLER_CALLING: - GNUNET_break_op (0); - break; - case CS_CALLER_CONNECTED: - ch->suspended_remote = GNUNET_YES; - break; - case CS_CALLER_SHUTDOWN: - return; - } + { + case CS_CALLEE_INIT: + GNUNET_break_op(0); + break; + + case CS_CALLEE_RINGING: + GNUNET_break_op(0); + break; + + case CS_CALLEE_CONNECTED: + ch->suspended_remote = GNUNET_YES; + break; + + case CS_CALLEE_SHUTDOWN: + return; + + case CS_CALLER_CALLING: + GNUNET_break_op(0); + break; + + case CS_CALLER_CONNECTED: + ch->suspended_remote = GNUNET_YES; + break; + + case CS_CALLER_SHUTDOWN: + return; + } env = - GNUNET_MQ_msg (suspend, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND); + GNUNET_MQ_msg(suspend, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND); suspend->cid = ch->cid; - GNUNET_MQ_send (line->mq, env); + GNUNET_MQ_send(line->mq, env); } @@ -909,51 +949,57 @@ handle_cadet_suspend_message (void *cls, * @param msg the incoming message */ static void -handle_cadet_resume_message (void *cls, - const struct CadetPhoneResumeMessage *msg) +handle_cadet_resume_message(void *cls, + const struct CadetPhoneResumeMessage *msg) { struct Channel *ch = cls; struct Line *line; struct GNUNET_MQ_Envelope *env; struct ClientPhoneResumeMessage *resume; - (void) msg; + (void)msg; line = ch->line; - GNUNET_CADET_receive_done (ch->channel); + GNUNET_CADET_receive_done(ch->channel); if (GNUNET_YES != ch->suspended_remote) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "RESUME message received for non-suspended channel, dropping channel.\n"); - destroy_line_cadet_channels (ch); - return; - } + { + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "RESUME message received for non-suspended channel, dropping channel.\n"); + destroy_line_cadet_channels(ch); + return; + } switch (ch->status) - { - case CS_CALLEE_INIT: - GNUNET_break (0); - break; - case CS_CALLEE_RINGING: - GNUNET_break (0); - break; - case CS_CALLEE_CONNECTED: - ch->suspended_remote = GNUNET_NO; - break; - case CS_CALLEE_SHUTDOWN: - return; - case CS_CALLER_CALLING: - GNUNET_break (0); - break; - case CS_CALLER_CONNECTED: - ch->suspended_remote = GNUNET_NO; - break; - case CS_CALLER_SHUTDOWN: - return; - } + { + case CS_CALLEE_INIT: + GNUNET_break(0); + break; + + case CS_CALLEE_RINGING: + GNUNET_break(0); + break; + + case CS_CALLEE_CONNECTED: + ch->suspended_remote = GNUNET_NO; + break; + + case CS_CALLEE_SHUTDOWN: + return; + + case CS_CALLER_CALLING: + GNUNET_break(0); + break; + + case CS_CALLER_CONNECTED: + ch->suspended_remote = GNUNET_NO; + break; + + case CS_CALLER_SHUTDOWN: + return; + } env = - GNUNET_MQ_msg (resume, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME); + GNUNET_MQ_msg(resume, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME); resume->cid = ch->cid; - GNUNET_MQ_send (line->mq, env); + GNUNET_MQ_send(line->mq, env); } @@ -965,10 +1011,10 @@ handle_cadet_resume_message (void *cls, * @return #GNUNET_OK (always) */ static int -check_cadet_audio_message (void *cls, const struct CadetAudioMessage *msg) +check_cadet_audio_message(void *cls, const struct CadetAudioMessage *msg) { - (void) cls; - (void) msg; + (void)cls; + (void)msg; return GNUNET_OK; /* any payload is fine */ } @@ -980,33 +1026,33 @@ check_cadet_audio_message (void *cls, const struct CadetAudioMessage *msg) * @param msg the incoming message */ static void -handle_cadet_audio_message (void *cls, const struct CadetAudioMessage *msg) +handle_cadet_audio_message(void *cls, const struct CadetAudioMessage *msg) { struct Channel *ch = cls; - size_t msize = ntohs (msg->header.size) - sizeof (struct CadetAudioMessage); + size_t msize = ntohs(msg->header.size) - sizeof(struct CadetAudioMessage); struct GNUNET_MQ_Envelope *env; struct ClientAudioMessage *cam; - GNUNET_CADET_receive_done (ch->channel); + GNUNET_CADET_receive_done(ch->channel); if ((GNUNET_YES == ch->suspended_local) || (GNUNET_YES == ch->suspended_remote)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Received %u bytes of AUDIO data on suspended channel CID %u; dropping\n", - (unsigned int) msize, - ch->cid); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Forwarding %u bytes of AUDIO data to client CID %u\n", - (unsigned int) msize, - ch->cid); + { + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Received %u bytes of AUDIO data on suspended channel CID %u; dropping\n", + (unsigned int)msize, + ch->cid); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Forwarding %u bytes of AUDIO data to client CID %u\n", + (unsigned int)msize, + ch->cid); env = - GNUNET_MQ_msg_extra (cam, msize, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO); + GNUNET_MQ_msg_extra(cam, msize, GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO); cam->cid = ch->cid; - GNUNET_memcpy (&cam[1], &msg[1], msize); - GNUNET_MQ_send (ch->line->mq, env); + GNUNET_memcpy(&cam[1], &msg[1], msize); + GNUNET_MQ_send(ch->line->mq, env); } @@ -1018,16 +1064,16 @@ handle_cadet_audio_message (void *cls, const struct CadetAudioMessage *msg) * @param channel connection to the other end (henceforth invalid) */ static void -inbound_end (void *cls, const struct GNUNET_CADET_Channel *channel) +inbound_end(void *cls, const struct GNUNET_CADET_Channel *channel) { struct Channel *ch = cls; - GNUNET_assert (channel == ch->channel); + GNUNET_assert(channel == ch->channel); ch->channel = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Channel destroyed by CADET in state %d\n", - ch->status); - clean_up_channel (ch); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Channel destroyed by CADET in state %d\n", + ch->status); + clean_up_channel(ch); } @@ -1038,63 +1084,63 @@ inbound_end (void *cls, const struct GNUNET_CADET_Channel *channel) * @param msg the message from the client */ static void -handle_client_call_message (void *cls, const struct ClientCallMessage *msg) +handle_client_call_message(void *cls, const struct ClientCallMessage *msg) { struct Line *line = cls; - struct Channel *ch = GNUNET_new (struct Channel); + struct Channel *ch = GNUNET_new(struct Channel); struct GNUNET_MQ_MessageHandler cadet_handlers[] = - {GNUNET_MQ_hd_fixed_size (cadet_hangup_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_HANG_UP, - struct CadetPhoneHangupMessage, - ch), - GNUNET_MQ_hd_fixed_size (cadet_pickup_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_PICK_UP, - struct CadetPhonePickupMessage, - ch), - GNUNET_MQ_hd_fixed_size (cadet_suspend_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_SUSPEND, - struct CadetPhoneSuspendMessage, - ch), - GNUNET_MQ_hd_fixed_size (cadet_resume_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_RESUME, - struct CadetPhoneResumeMessage, - ch), - GNUNET_MQ_hd_var_size (cadet_audio_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_AUDIO, - struct CadetAudioMessage, + { GNUNET_MQ_hd_fixed_size(cadet_hangup_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_HANG_UP, + struct CadetPhoneHangupMessage, + ch), + GNUNET_MQ_hd_fixed_size(cadet_pickup_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_PICK_UP, + struct CadetPhonePickupMessage, + ch), + GNUNET_MQ_hd_fixed_size(cadet_suspend_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_SUSPEND, + struct CadetPhoneSuspendMessage, + ch), + GNUNET_MQ_hd_fixed_size(cadet_resume_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_RESUME, + struct CadetPhoneResumeMessage, ch), - GNUNET_MQ_handler_end ()}; + GNUNET_MQ_hd_var_size(cadet_audio_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_AUDIO, + struct CadetAudioMessage, + ch), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *e; struct CadetPhoneRingMessage *ring; struct CadetPhoneRingInfoPS rs; line->line_port = msg->line_port; - rs.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CONVERSATION_RING); - rs.purpose.size = htonl (sizeof (struct CadetPhoneRingInfoPS)); + rs.purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_CONVERSATION_RING); + rs.purpose.size = htonl(sizeof(struct CadetPhoneRingInfoPS)); rs.line_port = line->line_port; rs.target_peer = msg->target; rs.expiration_time = - GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (RING_TIMEOUT)); + GNUNET_TIME_absolute_hton(GNUNET_TIME_relative_to_absolute(RING_TIMEOUT)); ch->line = line; - GNUNET_CONTAINER_DLL_insert (line->channel_head, line->channel_tail, ch); + GNUNET_CONTAINER_DLL_insert(line->channel_head, line->channel_tail, ch); ch->status = CS_CALLER_CALLING; - ch->channel = GNUNET_CADET_channel_create (cadet, - ch, - &msg->target, - &msg->line_port, - NULL, - &inbound_end, - cadet_handlers); - ch->mq = GNUNET_CADET_get_mq (ch->channel); - e = GNUNET_MQ_msg (ring, GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_RING); - GNUNET_CRYPTO_ecdsa_key_get_public (&msg->caller_id, &ring->caller_id); + ch->channel = GNUNET_CADET_channel_create(cadet, + ch, + &msg->target, + &msg->line_port, + NULL, + &inbound_end, + cadet_handlers); + ch->mq = GNUNET_CADET_get_mq(ch->channel); + e = GNUNET_MQ_msg(ring, GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_RING); + GNUNET_CRYPTO_ecdsa_key_get_public(&msg->caller_id, &ring->caller_id); ring->expiration_time = rs.expiration_time; - GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_ecdsa_sign (&msg->caller_id, - &rs.purpose, - &ring->signature)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending RING message via CADET\n"); - GNUNET_MQ_send (ch->mq, e); - GNUNET_SERVICE_client_continue (line->client); + GNUNET_assert(GNUNET_OK == GNUNET_CRYPTO_ecdsa_sign(&msg->caller_id, + &rs.purpose, + &ring->signature)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending RING message via CADET\n"); + GNUNET_MQ_send(ch->mq, e); + GNUNET_SERVICE_client_continue(line->client); } @@ -1108,24 +1154,24 @@ handle_client_call_message (void *cls, const struct ClientCallMessage *msg) * @return initial channel context for the channel */ static void * -inbound_channel (void *cls, - struct GNUNET_CADET_Channel *channel, - const struct GNUNET_PeerIdentity *initiator) +inbound_channel(void *cls, + struct GNUNET_CADET_Channel *channel, + const struct GNUNET_PeerIdentity *initiator) { struct Line *line = cls; struct Channel *ch; - (void) initiator; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received incoming cadet channel on line %p\n", - line); - ch = GNUNET_new (struct Channel); + (void)initiator; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received incoming cadet channel on line %p\n", + line); + ch = GNUNET_new(struct Channel); ch->status = CS_CALLEE_INIT; ch->line = line; ch->channel = channel; - ch->mq = GNUNET_CADET_get_mq (ch->channel); + ch->mq = GNUNET_CADET_get_mq(ch->channel); ch->cid = line->cid_gen++; - GNUNET_CONTAINER_DLL_insert (line->channel_head, line->channel_tail, ch); + GNUNET_CONTAINER_DLL_insert(line->channel_head, line->channel_tail, ch); return ch; } @@ -1139,14 +1185,14 @@ inbound_channel (void *cls, * @return the `struct Line` for the client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { struct Line *line; - (void) cls; - line = GNUNET_new (struct Line); + (void)cls; + line = GNUNET_new(struct Line); line->client = client; line->mq = mq; return line; @@ -1161,28 +1207,28 @@ client_connect_cb (void *cls, * @param app_ctx our `struct Line *` for @a client */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { struct Line *line = app_ctx; struct Channel *chn; - (void) cls; - (void) client; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client disconnected, closing line\n"); + (void)cls; + (void)client; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Client disconnected, closing line\n"); if (NULL != line->port) - { - GNUNET_CADET_close_port (line->port); - line->port = NULL; - } + { + GNUNET_CADET_close_port(line->port); + line->port = NULL; + } for (struct Channel *ch = line->channel_head; NULL != ch; ch = chn) - { - chn = ch->next; - ch->line = NULL; - destroy_line_cadet_channels (ch); - } - GNUNET_free (line); + { + chn = ch->next; + ch->line = NULL; + destroy_line_cadet_channels(ch); + } + GNUNET_free(line); } @@ -1193,54 +1239,54 @@ client_disconnect_cb (void *cls, * @param msg the message from the client */ static void -handle_client_register_message (void *cls, - const struct ClientPhoneRegisterMessage *msg) +handle_client_register_message(void *cls, + const struct ClientPhoneRegisterMessage *msg) { struct Line *line = cls; struct GNUNET_MQ_MessageHandler cadet_handlers[] = - {GNUNET_MQ_hd_fixed_size (cadet_ring_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_RING, - struct CadetPhoneRingMessage, - NULL), - GNUNET_MQ_hd_fixed_size (cadet_hangup_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_HANG_UP, - struct CadetPhoneHangupMessage, - NULL), - GNUNET_MQ_hd_fixed_size (cadet_pickup_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_PICK_UP, - struct CadetPhonePickupMessage, - NULL), - GNUNET_MQ_hd_fixed_size (cadet_suspend_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_SUSPEND, - struct CadetPhoneSuspendMessage, - NULL), - GNUNET_MQ_hd_fixed_size (cadet_resume_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_RESUME, - struct CadetPhoneResumeMessage, - NULL), - GNUNET_MQ_hd_var_size (cadet_audio_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_AUDIO, - struct CadetAudioMessage, + { GNUNET_MQ_hd_fixed_size(cadet_ring_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_RING, + struct CadetPhoneRingMessage, + NULL), + GNUNET_MQ_hd_fixed_size(cadet_hangup_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_HANG_UP, + struct CadetPhoneHangupMessage, NULL), - GNUNET_MQ_handler_end ()}; + GNUNET_MQ_hd_fixed_size(cadet_pickup_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_PICK_UP, + struct CadetPhonePickupMessage, + NULL), + GNUNET_MQ_hd_fixed_size(cadet_suspend_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_SUSPEND, + struct CadetPhoneSuspendMessage, + NULL), + GNUNET_MQ_hd_fixed_size(cadet_resume_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_PHONE_RESUME, + struct CadetPhoneResumeMessage, + NULL), + GNUNET_MQ_hd_var_size(cadet_audio_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CADET_AUDIO, + struct CadetAudioMessage, + NULL), + GNUNET_MQ_handler_end() }; line->line_port = msg->line_port; - line->port = GNUNET_CADET_open_port (cadet, - &msg->line_port, - &inbound_channel, - line, - NULL, - &inbound_end, - cadet_handlers); + line->port = GNUNET_CADET_open_port(cadet, + &msg->line_port, + &inbound_channel, + line, + NULL, + &inbound_end, + cadet_handlers); if (NULL == line->port) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Could not open line, port %s already in use!\n"), - GNUNET_h2s (&msg->line_port)); - GNUNET_SERVICE_client_drop (line->client); - return; - } - GNUNET_SERVICE_client_continue (line->client); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Could not open line, port %s already in use!\n"), + GNUNET_h2s(&msg->line_port)); + GNUNET_SERVICE_client_drop(line->client); + return; + } + GNUNET_SERVICE_client_continue(line->client); } @@ -1250,14 +1296,14 @@ handle_client_register_message (void *cls, * @param cls closure, NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - (void) cls; + (void)cls; if (NULL != cadet) - { - GNUNET_CADET_disconnect (cadet); - cadet = NULL; - } + { + GNUNET_CADET_disconnect(cadet); + cadet = NULL; + } } @@ -1269,65 +1315,65 @@ do_shutdown (void *cls) * @param service service handle */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *service) { - (void) cls; - (void) service; + (void)cls; + (void)service; cfg = c; - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_get_peer_identity (cfg, &my_identity)); - cadet = GNUNET_CADET_connect (cfg); + GNUNET_assert(GNUNET_OK == + GNUNET_CRYPTO_get_peer_identity(cfg, &my_identity)); + cadet = GNUNET_CADET_connect(cfg); if (NULL == cadet) - { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL); + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); } /** * Define "main" method using service macro. */ -GNUNET_SERVICE_MAIN ( +GNUNET_SERVICE_MAIN( "conversation", GNUNET_SERVICE_OPTION_NONE, &run, &client_connect_cb, &client_disconnect_cb, NULL, - GNUNET_MQ_hd_fixed_size (client_register_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_REGISTER, - struct ClientPhoneRegisterMessage, - NULL), - GNUNET_MQ_hd_fixed_size (client_pickup_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_PICK_UP, - struct ClientPhonePickupMessage, - NULL), - GNUNET_MQ_hd_fixed_size (client_suspend_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND, - struct ClientPhoneSuspendMessage, - NULL), - GNUNET_MQ_hd_fixed_size (client_resume_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME, - struct ClientPhoneResumeMessage, - NULL), - GNUNET_MQ_hd_fixed_size (client_hangup_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP, - struct ClientPhoneHangupMessage, - NULL), - GNUNET_MQ_hd_fixed_size (client_call_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_CALL, - struct ClientCallMessage, - NULL), - GNUNET_MQ_hd_var_size (client_audio_message, - GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO, - struct ClientAudioMessage, - NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_hd_fixed_size(client_register_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_REGISTER, + struct ClientPhoneRegisterMessage, + NULL), + GNUNET_MQ_hd_fixed_size(client_pickup_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_PICK_UP, + struct ClientPhonePickupMessage, + NULL), + GNUNET_MQ_hd_fixed_size(client_suspend_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_SUSPEND, + struct ClientPhoneSuspendMessage, + NULL), + GNUNET_MQ_hd_fixed_size(client_resume_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_RESUME, + struct ClientPhoneResumeMessage, + NULL), + GNUNET_MQ_hd_fixed_size(client_hangup_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_HANG_UP, + struct ClientPhoneHangupMessage, + NULL), + GNUNET_MQ_hd_fixed_size(client_call_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_PHONE_CALL, + struct ClientCallMessage, + NULL), + GNUNET_MQ_hd_var_size(client_audio_message, + GNUNET_MESSAGE_TYPE_CONVERSATION_CS_AUDIO, + struct ClientAudioMessage, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-conversation.c */ diff --git a/src/conversation/gnunet_gst.c b/src/conversation/gnunet_gst.c index c08468996..5db0d350c 100644 --- a/src/conversation/gnunet_gst.c +++ b/src/conversation/gnunet_gst.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet. - Copyright (C) 2016 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet. + Copyright (C) 2016 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/gnunet_gst.c * @brief FIXME @@ -38,23 +38,26 @@ dump_buffer(unsigned n, const unsigned char* buf) end = buf + n; - for (i = 0; ; i += 16) { - p = buf + i; - for (j = 0; j < 16; j++) { - fprintf(stderr, "%02X ", p[j]); - if (p + j >= end) - goto BREAKOUT; - } - fprintf(stderr, " "); - p = buf + i; - for (j = 0; j < 16; j++) { - fprintf(stderr, "%c", isprint(p[j]) ? p[j] : - '.'); - if (p + j >= end) - goto BREAKOUT; + for (i = 0; ; i += 16) + { + p = buf + i; + for (j = 0; j < 16; j++) + { + fprintf(stderr, "%02X ", p[j]); + if (p + j >= end) + goto BREAKOUT; + } + fprintf(stderr, " "); + p = buf + i; + for (j = 0; j < 16; j++) + { + fprintf(stderr, "%c", isprint(p[j]) ? p[j] : + '.'); + if (p + j >= end) + goto BREAKOUT; + } + fprintf(stderr, "\n"); } - fprintf(stderr, "\n"); - } BREAKOUT: return; } @@ -66,7 +69,8 @@ void gg_load_configuration(GNUNET_gstData * d) { char *audiobackend_string; - cfg = GNUNET_CONFIGURATION_create(); + + cfg = GNUNET_CONFIGURATION_create(); GNUNET_CONFIGURATION_load(cfg, "mediahelper.conf"); GNUNET_CONFIGURATION_get_value_string(cfg, "MEDIAHELPER", "JACK_PP_IN", &d->jack_pp_in); @@ -74,77 +78,88 @@ gg_load_configuration(GNUNET_gstData * d) GNUNET_CONFIGURATION_get_value_string(cfg, "MEDIAHELPER", "AUDIOBACKEND", &audiobackend_string); - // printf("abstring: %s \n", audiobackend_string); - - if (0 == strcasecmp (audiobackend_string, "AUTO")) - { - d->audiobackend = AUTO; - } else if (0 == strcasecmp (audiobackend_string, "JACK")) - { - d->audiobackend = JACK; - } else if (0 == strcasecmp (audiobackend_string, "ALSA")) - { - d->audiobackend = ALSA; - } else if (0 == strcasecmp (audiobackend_string, "FAKE")) - { - d->audiobackend = FAKE; - } else if (0 == strcasecmp (audiobackend_string, "TEST")) - { - d->audiobackend = TEST; - } else - { - d->audiobackend = AUTO; - } + // printf("abstring: %s \n", audiobackend_string); + + if (0 == strcasecmp(audiobackend_string, "AUTO")) + { + d->audiobackend = AUTO; + } + else if (0 == strcasecmp(audiobackend_string, "JACK")) + { + d->audiobackend = JACK; + } + else if (0 == strcasecmp(audiobackend_string, "ALSA")) + { + d->audiobackend = ALSA; + } + else if (0 == strcasecmp(audiobackend_string, "FAKE")) + { + d->audiobackend = FAKE; + } + else if (0 == strcasecmp(audiobackend_string, "TEST")) + { + d->audiobackend = TEST; + } + else + { + d->audiobackend = AUTO; + } if (GNUNET_CONFIGURATION_get_value_yesno(cfg, "MEDIAHELPER", "REMOVESILENCE") == GNUNET_YES) - { - d->dropsilence = TRUE; - } else { - d->dropsilence = FALSE; - } + { + d->dropsilence = TRUE; + } + else + { + d->dropsilence = FALSE; + } if (GNUNET_CONFIGURATION_get_value_yesno(cfg, "MEDIAHELPER", "NO_GN_HEADERS") == GNUNET_YES) - { - d->pure_ogg = TRUE; - } else { - d->pure_ogg = FALSE; - } + { + d->pure_ogg = TRUE; + } + else + { + d->pure_ogg = FALSE; + } if (GNUNET_CONFIGURATION_get_value_yesno(cfg, "MEDIAHELPER", "USERTP") == GNUNET_YES) - { - d->usertp = TRUE; - } else { - d->usertp = FALSE; - } + { + d->usertp = TRUE; + } + else + { + d->usertp = FALSE; + } // GNUNET_CONFIGURATION_write(cfg, "mediahelper.conf"); - } static void -write_data (const char *ptr, size_t msg_size) +write_data(const char *ptr, size_t msg_size) { ssize_t ret; size_t off; + off = 0; while (off < msg_size) - { - ret = write (1, &ptr[off], msg_size - off); - if (0 >= ret) { - if (-1 == ret) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "write"); + ret = write(1, &ptr[off], msg_size - off); + if (0 >= ret) + { + if (-1 == ret) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "write"); // quit (2); + } + off += ret; } - off += ret; - } } extern GstFlowReturn -on_appsink_new_sample (GstElement * element, GNUNET_gstData * d) +on_appsink_new_sample(GstElement * element, GNUNET_gstData * d) { //size of message including gnunet header size_t msg_size; @@ -152,72 +167,70 @@ on_appsink_new_sample (GstElement * element, GNUNET_gstData * d) GstSample *s; GstBuffer *b; GstMapInfo map; + /* - const GstStructure *si; - char *si_str; - GstCaps *s_caps; - char *caps_str; -*/ + const GstStructure *si; + char *si_str; + GstCaps *s_caps; + char *caps_str; + */ if (gst_app_sink_is_eos(GST_APP_SINK(element))) return GST_FLOW_OK; //pull sample from appsink - s = gst_app_sink_pull_sample (GST_APP_SINK(element)); + s = gst_app_sink_pull_sample(GST_APP_SINK(element)); - if (s == NULL) - return GST_FLOW_OK; + if (s == NULL) + return GST_FLOW_OK; - if (!GST_IS_SAMPLE (s)) - return GST_FLOW_OK; + if (!GST_IS_SAMPLE(s)) + return GST_FLOW_OK; - b = gst_sample_get_buffer(s); + b = gst_sample_get_buffer(s); - GST_WARNING ("caps are %" GST_PTR_FORMAT, gst_sample_get_caps(s)); + GST_WARNING("caps are %" GST_PTR_FORMAT, gst_sample_get_caps(s)); - gst_buffer_map (b, &map, GST_MAP_READ); + gst_buffer_map(b, &map, GST_MAP_READ); - size_t len; - len = map.size; - if (len > UINT16_MAX - sizeof (struct AudioMessage)) - { - // this should never happen? - printf("GSTREAMER sample too big! \n"); - exit(20); - len = UINT16_MAX - sizeof (struct AudioMessage); - } + size_t len; + len = map.size; + if (len > UINT16_MAX - sizeof(struct AudioMessage)) + { + // this should never happen? + printf("GSTREAMER sample too big! \n"); + exit(20); + len = UINT16_MAX - sizeof(struct AudioMessage); + } - msg_size = sizeof (struct AudioMessage) + len; + msg_size = sizeof(struct AudioMessage) + len; // copy the data into audio_message - GNUNET_memcpy (((char *) &(d->audio_message)[1]), map.data, len); - (d->audio_message)->header.size = htons ((uint16_t) msg_size); + GNUNET_memcpy(((char *)&(d->audio_message)[1]), map.data, len); + (d->audio_message)->header.size = htons((uint16_t)msg_size); if (d->pure_ogg) // write the audio_message without the gnunet headers - write_data ((const char *) &(d->audio_message)[1], len); + write_data((const char *)&(d->audio_message)[1], len); else - write_data ((const char *) d->audio_message, msg_size); + write_data((const char *)d->audio_message, msg_size); - gst_sample_unref(s); + gst_sample_unref(s); return GST_FLOW_OK; } /*** * Dump a pipeline graph */ - extern void +extern void pl_graph(GstElement * pipeline) { - #ifdef IS_SPEAKER gst_debug_bin_to_dot_file_with_ts(GST_BIN(pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "playback_helper.dot"); - #endif #ifdef IS_MIC gst_debug_bin_to_dot_file_with_ts(GST_BIN(pipeline), GST_DEBUG_GRAPH_SHOW_ALL, "record_helper.dot"); - #endif @@ -227,142 +240,145 @@ pl_graph(GstElement * pipeline) extern gboolean -gnunet_gst_bus_call (GstBus *bus, GstMessage *msg, gpointer data) +gnunet_gst_bus_call(GstBus *bus, GstMessage *msg, gpointer data) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Bus message\n"); - switch (GST_MESSAGE_TYPE (msg)) - { - case GST_MESSAGE_EOS: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "End of stream\n"); - exit (10); - break; - - case GST_MESSAGE_ERROR: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Bus message\n"); + switch (GST_MESSAGE_TYPE(msg)) + { + case GST_MESSAGE_EOS: + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "End of stream\n"); + exit(10); + break; + + case GST_MESSAGE_ERROR: { gchar *debug; GError *error; - gst_message_parse_error (msg, &error, &debug); - g_free (debug); + gst_message_parse_error(msg, &error, &debug); + g_free(debug); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error: %s\n", - error->message); - g_error_free (error); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error: %s\n", + error->message); + g_error_free(error); - exit (10); + exit(10); + break; + } + + default: break; } - default: - break; - } return TRUE; } /* called when pipeline changes state */ - extern void -state_changed_cb (GstBus * bus, GstMessage * msg, GNUNET_gstData * d) +extern void +state_changed_cb(GstBus * bus, GstMessage * msg, GNUNET_gstData * d) { GstState old_state, new_state, pending_state; - gst_message_parse_state_changed (msg, &old_state, &new_state, - &pending_state); + gst_message_parse_state_changed(msg, &old_state, &new_state, + &pending_state); switch (new_state) - { - + { case GST_STATE_READY: // printf("ready.... \n"); //pl_graph(GST_ELEMENT(d->pipeline)); break; + case GST_STATE_PLAYING: - //GST_LOG ("caps are %" GST_PTR_FORMAT, caps); + //GST_LOG ("caps are %" GST_PTR_FORMAT, caps); - // printf("Playing.... \n"); + // printf("Playing.... \n"); pl_graph(GST_ELEMENT(d->pipeline)); break; + case GST_STATE_VOID_PENDING: - // printf("void_pending.... \n"); + // printf("void_pending.... \n"); //pl_graph(GST_ELEMENT(d->pipeline)); break; + case GST_STATE_NULL: - // printf("null.... \n"); + // printf("null.... \n"); //pl_graph(GST_ELEMENT(d->pipeline)); break; case GST_STATE_PAUSED: - // printf("paused.... \n"); + // printf("paused.... \n"); //pl_graph(GST_ELEMENT(d->pipeline)); break; - } + } } - static void - application_cb (GstBus * bus, GstMessage * msg, GNUNET_gstData * data) +static void +application_cb(GstBus * bus, GstMessage * msg, GNUNET_gstData * data) { - // printf("application cb"); + // printf("application cb"); return; } - static void - error_cb (GstBus * bus, GstMessage * msg, GNUNET_gstData * data) +static void +error_cb(GstBus * bus, GstMessage * msg, GNUNET_gstData * data) { - // printf("error cb"); + // printf("error cb"); return; } - static void - eos_cb (GstBus * bus, GstMessage * msg, GNUNET_gstData * data) +static void +eos_cb(GstBus * bus, GstMessage * msg, GNUNET_gstData * data) { - // printf("eos cb"); + // printf("eos cb"); return; } extern void -gg_setup_gst_bus (GNUNET_gstData * d) +gg_setup_gst_bus(GNUNET_gstData * d) { GstBus *bus; - bus = gst_element_get_bus (GST_ELEMENT(d->pipeline)); - gst_bus_add_signal_watch (bus); - g_signal_connect (G_OBJECT (bus), "message::error", (GCallback) error_cb, - d); - g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback) eos_cb, - d); - g_signal_connect (G_OBJECT (bus), "message::state-changed", - (GCallback) state_changed_cb, d); - g_signal_connect (G_OBJECT (bus), "message::application", - (GCallback) application_cb, d); - g_signal_connect (G_OBJECT (bus), "message::about-to-finish", - (GCallback) application_cb, d); - gst_object_unref (bus); + bus = gst_element_get_bus(GST_ELEMENT(d->pipeline)); + gst_bus_add_signal_watch(bus); + g_signal_connect(G_OBJECT(bus), "message::error", (GCallback)error_cb, + d); + g_signal_connect(G_OBJECT(bus), "message::eos", (GCallback)eos_cb, + d); + g_signal_connect(G_OBJECT(bus), "message::state-changed", + (GCallback)state_changed_cb, d); + g_signal_connect(G_OBJECT(bus), "message::application", + (GCallback)application_cb, d); + g_signal_connect(G_OBJECT(bus), "message::about-to-finish", + (GCallback)application_cb, d); + gst_object_unref(bus); } /* * take buffer from gstreamer and feed it to gnunet */ /* - extern int -feed_buffer_to_gnunet (GNUNET_gstData * d) -{ - GstSample *s; - GstBuffer *b; - GstMapInfo m; - size_t len, msg_size; - const char *ptr; - int phase; - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "pulling...\n"); - s = gst_app_sink_pull_sample (GST_APP_SINK(d->appsink)); - if (NULL == s) - { + extern int + feed_buffer_to_gnunet (GNUNET_gstData * d) + { + GstSample *s; + GstBuffer *b; + GstMapInfo m; + size_t len, msg_size; + const char *ptr; + int phase; + + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "pulling...\n"); + s = gst_app_sink_pull_sample (GST_APP_SINK(d->appsink)); + if (NULL == s) + { GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "pulled NULL\n"); return OK; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "...pulled!\n"); + } + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "...pulled!\n"); const GstStructure *si; char *si_str; @@ -393,39 +409,39 @@ feed_buffer_to_gnunet (GNUNET_gstData * d) else GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got sample with no caps\n"); - b = gst_sample_get_buffer (s); - if (NULL == b || !gst_buffer_map (b, &m, GST_MAP_READ)) - { + b = gst_sample_get_buffer (s); + if (NULL == b || !gst_buffer_map (b, &m, GST_MAP_READ)) + { GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got NULL buffer %p or failed to map the buffer\n", b); gst_sample_unref (s); return FAIL; - } + } - len = m.size; - if (len > UINT16_MAX - sizeof (struct AudioMessage)) - { + len = m.size; + if (len > UINT16_MAX - sizeof (struct AudioMessage)) + { GNUNET_break (0); len = UINT16_MAX - sizeof (struct AudioMessage); - } - msg_size = sizeof (struct AudioMessage) + len; - audio_message.header.size = htons ((uint16_t) msg_size); + } + msg_size = sizeof (struct AudioMessage) + len; + audio_message.header.size = htons ((uint16_t) msg_size); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending %u bytes of audio data\n", (unsigned int) msg_size); - for (phase = 0; phase < 2; phase++) - { + for (phase = 0; phase < 2; phase++) + { size_t offset; size_t to_send; ssize_t ret; if (0 == phase && !d->pure_ogg) { -//#ifdef DEBUG_RECORD_PURE_OGG + //#ifdef DEBUG_RECORD_PURE_OGG -// if (d->pure_ogg) -// break; + // if (d->pure_ogg) + // break; -//#endif + //#endif ptr = (const char *) &audio_message; to_send = sizeof (audio_message); } @@ -451,65 +467,68 @@ feed_buffer_to_gnunet (GNUNET_gstData * d) } } - // if (abort_send) + // if (abort_send) // break; - } - gst_buffer_unmap (b, &m); - gst_sample_unref (s); -} -*/ + } + gst_buffer_unmap (b, &m); + gst_sample_unref (s); + } + */ - extern int -feed_buffer_to_gst (const char *audio, size_t b_len, GNUNET_gstData * d) +extern int +feed_buffer_to_gst(const char *audio, size_t b_len, GNUNET_gstData * d) { GstBuffer *b; gchar *bufspace; GstFlowReturn flow; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Feeding %u bytes to GStreamer\n", - (unsigned int) b_len); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Feeding %u bytes to GStreamer\n", + (unsigned int)b_len); - bufspace = g_memdup (audio, b_len); - b = gst_buffer_new_wrapped (bufspace, b_len); + bufspace = g_memdup(audio, b_len); + b = gst_buffer_new_wrapped(bufspace, b_len); if (NULL == b) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Failed to wrap a buffer\n"); - g_free (bufspace); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Failed to wrap a buffer\n"); + g_free(bufspace); + return GNUNET_SYSERR; + } if (GST_APP_SRC(d->appsrc) == NULL) exit(10); - flow = gst_app_src_push_buffer (GST_APP_SRC(d->appsrc), b); + flow = gst_app_src_push_buffer(GST_APP_SRC(d->appsrc), b); /* They all return GNUNET_OK, because currently player stops when * data stops coming. This might need to be changed for the player * to also stop when pipeline breaks. */ switch (flow) - { - case GST_FLOW_OK: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Fed %u bytes to the pipeline\n", - (unsigned int) b_len); - break; - case GST_FLOW_FLUSHING: - /* buffer was dropped, because pipeline state is not PAUSED or PLAYING */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Dropped a buffer\n"); - break; - case GST_FLOW_EOS: - /* end of stream */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "EOS\n"); - break; - default: - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Unexpected push result\n"); - break; - } + { + case GST_FLOW_OK: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Fed %u bytes to the pipeline\n", + (unsigned int)b_len); + break; + + case GST_FLOW_FLUSHING: + /* buffer was dropped, because pipeline state is not PAUSED or PLAYING */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Dropped a buffer\n"); + break; + + case GST_FLOW_EOS: + /* end of stream */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "EOS\n"); + break; + + default: + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Unexpected push result\n"); + break; + } return GNUNET_OK; } @@ -518,35 +537,37 @@ feed_buffer_to_gst (const char *audio, size_t b_len, GNUNET_gstData * d) /** * debug making elements */ - extern GstElement * -gst_element_factory_make_debug( gchar *factoryname, gchar *name) +extern GstElement * +gst_element_factory_make_debug(gchar *factoryname, gchar *name) { GstElement *element; - element = gst_element_factory_make(factoryname,name); - - if (element == NULL) { + element = gst_element_factory_make(factoryname, name); - printf ("\n Failed to create element - type: %s name: %s \n", factoryname, name); - exit(10); - return element; - } else { - return element; - } + if (element == NULL) + { + printf("\n Failed to create element - type: %s name: %s \n", factoryname, name); + exit(10); + return element; + } + else + { + return element; + } } /* - static gboolean -gst_element_link_many_debug(...) -{ - va_list arguments; - gst_element_link_many(argptr); -} + static gboolean + gst_element_link_many_debug(...) + { + va_list arguments; + gst_element_link_many(argptr); + } -#define gst_element_link_many(...) \ + #define gst_element_link_many(...) \ gst_element_link_many_debug(__VA_ARGS__) -*/ - extern void + */ +extern void lf(char * msg) { printf("linking elements failed: %s", msg); @@ -557,26 +578,26 @@ lf(char * msg) * used to set properties on autoaudiosink's chosen sink */ static void -autoaudiosink_child_added (GstChildProxy *child_proxy, - GObject *object, - gchar *name, - gpointer user_data) +autoaudiosink_child_added(GstChildProxy *child_proxy, + GObject *object, + gchar *name, + gpointer user_data) { - if (GST_IS_AUDIO_BASE_SRC (object)) - g_object_set (object, - "buffer-time", (gint64) BUFFER_TIME, - "latency-time", (gint64) LATENCY_TIME, - NULL); + if (GST_IS_AUDIO_BASE_SRC(object)) + g_object_set(object, + "buffer-time", (gint64)BUFFER_TIME, + "latency-time", (gint64)LATENCY_TIME, + NULL); } /*** * used to set properties on autoaudiosource's chosen sink */ -static void -autoaudiosource_child_added (GstChildProxy *child_proxy, GObject *object, gchar *name, gpointer user_data) +static void +autoaudiosource_child_added(GstChildProxy *child_proxy, GObject *object, gchar *name, gpointer user_data) { - if (GST_IS_AUDIO_BASE_SRC (object)) - g_object_set (object, "buffer-time", (gint64) BUFFER_TIME, "latency-time", (gint64) LATENCY_TIME, NULL); + if (GST_IS_AUDIO_BASE_SRC(object)) + g_object_set(object, "buffer-time", (gint64)BUFFER_TIME, "latency-time", (gint64)LATENCY_TIME, NULL); } @@ -585,66 +606,67 @@ get_pipeline(GstElement *element) { GstPipeline *p; - p = GST_PIPELINE (gst_object_get_parent(GST_OBJECT (element))); + p = GST_PIPELINE(gst_object_get_parent(GST_OBJECT(element))); - return GST_ELEMENT (p); + return GST_ELEMENT(p); } - static void -decoder_ogg_pad_added (GstElement *element, - GstPad *pad, - gpointer data) +static void +decoder_ogg_pad_added(GstElement *element, + GstPad *pad, + gpointer data) { GstPad *sinkpad; - GstElement *decoder = (GstElement *) data; + GstElement *decoder = (GstElement *)data; printf("==== ogg pad added callback \n"); /* We can now link this pad with the opus-decoder sink pad */ // pl_graph(get_pipeline(element)); - sinkpad = gst_element_get_static_pad (decoder, "sink"); + sinkpad = gst_element_get_static_pad(decoder, "sink"); - gst_pad_link (pad, sinkpad); + gst_pad_link(pad, sinkpad); gst_element_link_many(element, decoder, NULL); - gst_object_unref (sinkpad); + gst_object_unref(sinkpad); } int -gnunet_read (GNUNET_gstData * d) +gnunet_read(GNUNET_gstData * d) { char readbuf[MAXLINE]; int ret; + printf("read \n"); - ret = read (0, readbuf, sizeof (readbuf)); + ret = read(0, readbuf, sizeof(readbuf)); if (0 > ret) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Read error from STDIN: %d %s\n"), - ret, strerror (errno)); - return FAIL; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Read error from STDIN: %d %s\n"), + ret, strerror(errno)); + return FAIL; + } //toff += ret; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received %d bytes of audio data\n", - (int) ret); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received %d bytes of audio data\n", + (int)ret); if (0 == ret) return FAIL; //#ifdef DEBUG_READ_PURE_OGG - if (d->pure_ogg) - { - feed_buffer_to_gst (readbuf, ret, d); - } - else - { - //#endif - GNUNET_MST_from_buffer (d->stdin_mst, - readbuf, - ret, - GNUNET_NO, - GNUNET_NO); - } - return 0; + if (d->pure_ogg) + { + feed_buffer_to_gst(readbuf, ret, d); + } + else + { + //#endif + GNUNET_MST_from_buffer(d->stdin_mst, + readbuf, + ret, + GNUNET_NO, + GNUNET_NO); + } + return 0; } /** @@ -656,29 +678,30 @@ gnunet_read (GNUNET_gstData * d) * #GNUNET_SYSERR to stop further processing due to error */ static int -stdin_receiver (void *cls, - const struct GNUNET_MessageHeader *msg) +stdin_receiver(void *cls, + const struct GNUNET_MessageHeader *msg) { struct AudioMessage *audio; size_t b_len; printf("stdin receiver \n "); - dump_buffer (sizeof(msg), - (const unsigned char *) msg); - - switch (ntohs (msg->type)) - { - case GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO: - audio = (struct AudioMessage *) msg; - - b_len = ntohs (audio->header.size) - sizeof (struct AudioMessage); - printf("feeding buffer to gst \n "); - feed_buffer_to_gst ((const char *) &audio[1], b_len, cls); - break; - default: - printf("No audio message: %u \n ", ntohs(msg->type)); - break; - } + dump_buffer(sizeof(msg), + (const unsigned char *)msg); + + switch (ntohs(msg->type)) + { + case GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO: + audio = (struct AudioMessage *)msg; + + b_len = ntohs(audio->header.size) - sizeof(struct AudioMessage); + printf("feeding buffer to gst \n "); + feed_buffer_to_gst((const char *)&audio[1], b_len, cls); + break; + + default: + printf("No audio message: %u \n ", ntohs(msg->type)); + break; + } return GNUNET_OK; } @@ -689,92 +712,92 @@ get_app(GNUNET_gstData *d, int type) GstBin *bin; GstPad *pad, *ghostpad; - if ( type == SOURCE ) - { - bin = GST_BIN(gst_bin_new("Gnunet appsrc")); + if (type == SOURCE) + { + bin = GST_BIN(gst_bin_new("Gnunet appsrc")); - GNUNET_assert (GNUNET_OK == - GNUNET_log_setup ("gnunet-helper-audio-playback", - "WARNING", - NULL)); + GNUNET_assert(GNUNET_OK == + GNUNET_log_setup("gnunet-helper-audio-playback", + "WARNING", + NULL)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Audio playback starts\n"); - printf(" creating appsrc \n "); - //d->audio_message.header.type = htons (GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Audio playback starts\n"); + printf(" creating appsrc \n "); + //d->audio_message.header.type = htons (GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO); // d->audio_message = GNUNET_malloc (UINT16_MAX); - // d->audio_message = (AudioMessage*)malloc(sizeof(struct AudioMessage)); +// d->audio_message = (AudioMessage*)malloc(sizeof(struct AudioMessage)); // d->audio_message = GNUNET_malloc(sizeof(struct AudioMessage)); - //d->audio_message.header.type = htons (GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO); + //d->audio_message.header.type = htons (GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO); - d->stdin_mst = GNUNET_MST_create (&stdin_receiver, d); + d->stdin_mst = GNUNET_MST_create(&stdin_receiver, d); - if ( d->stdin_mst == NULL) - printf("stdin_mst = NULL"); + if (d->stdin_mst == NULL) + printf("stdin_mst = NULL"); - d->appsrc = gst_element_factory_make ("appsrc", "appsrc"); + d->appsrc = gst_element_factory_make("appsrc", "appsrc"); - gst_bin_add_many( bin, d->appsrc, NULL); + gst_bin_add_many(bin, d->appsrc, NULL); // gst_element_link_many ( encoder, muxer, NULL); - pad = gst_element_get_static_pad (d->appsrc, "src"); - ghostpad = gst_ghost_pad_new ("src", pad); - } - if ( type == SINK ) - { - bin = GST_BIN(gst_bin_new("Gnunet appsink")); + pad = gst_element_get_static_pad(d->appsrc, "src"); + ghostpad = gst_ghost_pad_new("src", pad); + } + if (type == SINK) + { + bin = GST_BIN(gst_bin_new("Gnunet appsink")); - GNUNET_assert (GNUNET_OK == - GNUNET_log_setup ("gnunet-helper-audio-record", - "WARNING", - NULL)); + GNUNET_assert(GNUNET_OK == + GNUNET_log_setup("gnunet-helper-audio-record", + "WARNING", + NULL)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Audio source starts\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Audio source starts\n"); - d->appsink = gst_element_factory_make ("appsink", "appsink"); + d->appsink = gst_element_factory_make("appsink", "appsink"); - // Move this out of here! - d->audio_message = GNUNET_malloc (UINT16_MAX); - (d->audio_message)->header.type = htons (GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO); - g_object_set (G_OBJECT (d->appsink), "emit-signals", TRUE, "sync", TRUE, NULL); + // Move this out of here! + d->audio_message = GNUNET_malloc(UINT16_MAX); + (d->audio_message)->header.type = htons(GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO); + g_object_set(G_OBJECT(d->appsink), "emit-signals", TRUE, "sync", TRUE, NULL); - g_signal_connect (d->appsink, "new-sample", - G_CALLBACK (on_appsink_new_sample), &d); + g_signal_connect(d->appsink, "new-sample", + G_CALLBACK(on_appsink_new_sample), &d); - gst_bin_add_many( bin, d->appsink, NULL); + gst_bin_add_many(bin, d->appsink, NULL); // gst_element_link_many ( encoder, muxer, NULL); - pad = gst_element_get_static_pad (d->appsink, "sink"); - ghostpad = gst_ghost_pad_new ("sink", pad); - } + pad = gst_element_get_static_pad(d->appsink, "sink"); + ghostpad = gst_ghost_pad_new("sink", pad); + } /* set the bin pads */ - gst_pad_set_active (ghostpad, TRUE); - gst_element_add_pad (GST_ELEMENT(bin), ghostpad); + gst_pad_set_active(ghostpad, TRUE); + gst_element_add_pad(GST_ELEMENT(bin), ghostpad); - gst_object_unref (pad); + gst_object_unref(pad); return bin; } - extern GstBin * -get_coder(GNUNET_gstData *d , int type) +extern GstBin * +get_coder(GNUNET_gstData *d, int type) { GstBin *bin; GstPad *srcpad, *sinkpad, *srcghostpad, *sinkghostpad; GstCaps *rtpcaps; GstElement *encoder, *muxer, *decoder, *demuxer, *jitterbuffer, *rtpcapsfilter; - if ( d->usertp == TRUE ) - { - /* + if (d->usertp == TRUE) + { + /* * application/x-rtp, media=(string)audio, clock-rate=(int)48000, encoding-name=(string)OPUS, sprop-maxcapturerate=(string)48000, sprop-stereo=(string)0, payload=(int)96, encoding-params=(string)2, ssrc=(uint)630297634, timestamp-offset=(uint)678334141, seqnum-offset=(uint)16938 */ /* rtpcaps = gst_caps_new_simple ("application/x-rtp", @@ -785,110 +808,110 @@ get_coder(GNUNET_gstData *d , int type) "sprop-stereo", G_TYPE_STRING, "0", "encoding-params", G_TYPE_STRING, "2", NULL); -*/ - rtpcaps = gst_caps_new_simple ("application/x-rtp", - "media", G_TYPE_STRING, "audio", - "clock-rate", G_TYPE_INT, SAMPLING_RATE, - "encoding-name", G_TYPE_STRING, "OPUS", - "payload", G_TYPE_INT, 96, - "sprop-stereo", G_TYPE_STRING, "0", - "encoding-params", G_TYPE_STRING, "2", - NULL); - - - rtpcapsfilter = gst_element_factory_make ("capsfilter", "rtpcapsfilter"); - - g_object_set (G_OBJECT (rtpcapsfilter), - "caps", rtpcaps, - NULL); - gst_caps_unref (rtpcaps); - - } - + */ + rtpcaps = gst_caps_new_simple("application/x-rtp", + "media", G_TYPE_STRING, "audio", + "clock-rate", G_TYPE_INT, SAMPLING_RATE, + "encoding-name", G_TYPE_STRING, "OPUS", + "payload", G_TYPE_INT, 96, + "sprop-stereo", G_TYPE_STRING, "0", + "encoding-params", G_TYPE_STRING, "2", + NULL); + + + rtpcapsfilter = gst_element_factory_make("capsfilter", "rtpcapsfilter"); + + g_object_set(G_OBJECT(rtpcapsfilter), + "caps", rtpcaps, + NULL); + gst_caps_unref(rtpcaps); + } - if ( type == ENCODER ) - { - bin = GST_BIN(gst_bin_new("Gnunet audioencoder")); - encoder = gst_element_factory_make ("opusenc", "opus-encoder"); - if ( d->usertp == TRUE ) + if (type == ENCODER) { - muxer = gst_element_factory_make ("rtpopuspay", "rtp-payloader"); - } else { - muxer = gst_element_factory_make ("oggmux", "ogg-muxer"); - } - g_object_set (G_OBJECT (encoder), - /* "bitrate", 64000, */ - /* "bandwidth", OPUS_BANDWIDTH_FULLBAND, */ - "inband-fec", INBAND_FEC_MODE, - "packet-loss-percentage", PACKET_LOSS_PERCENTAGE, - "max-payload-size", MAX_PAYLOAD_SIZE, - "audio", TRUE, /* VoIP, not audio */ - "frame-size", OPUS_FRAME_SIZE, - NULL); - - if ( d->usertp != TRUE) - { - g_object_set (G_OBJECT (muxer), - "max-delay", OGG_MAX_DELAY, - "max-page-delay", OGG_MAX_PAGE_DELAY, - NULL); - } + bin = GST_BIN(gst_bin_new("Gnunet audioencoder")); - gst_bin_add_many( bin, encoder, muxer, NULL); - gst_element_link_many ( encoder, muxer, NULL); - sinkpad = gst_element_get_static_pad(encoder, "sink"); - sinkghostpad = gst_ghost_pad_new ("sink", sinkpad); - - srcpad = gst_element_get_static_pad(muxer, "src"); - srcghostpad = gst_ghost_pad_new ("src", srcpad); + encoder = gst_element_factory_make("opusenc", "opus-encoder"); + if (d->usertp == TRUE) + { + muxer = gst_element_factory_make("rtpopuspay", "rtp-payloader"); + } + else + { + muxer = gst_element_factory_make("oggmux", "ogg-muxer"); + } + g_object_set(G_OBJECT(encoder), + /* "bitrate", 64000, */ + /* "bandwidth", OPUS_BANDWIDTH_FULLBAND, */ + "inband-fec", INBAND_FEC_MODE, + "packet-loss-percentage", PACKET_LOSS_PERCENTAGE, + "max-payload-size", MAX_PAYLOAD_SIZE, + "audio", TRUE, /* VoIP, not audio */ + "frame-size", OPUS_FRAME_SIZE, + NULL); + + if (d->usertp != TRUE) + { + g_object_set(G_OBJECT(muxer), + "max-delay", OGG_MAX_DELAY, + "max-page-delay", OGG_MAX_PAGE_DELAY, + NULL); + } - } - if ( type == DECODER ) - { - bin = GST_BIN(gst_bin_new("Gnunet audiodecoder")); + gst_bin_add_many(bin, encoder, muxer, NULL); + gst_element_link_many(encoder, muxer, NULL); + sinkpad = gst_element_get_static_pad(encoder, "sink"); + sinkghostpad = gst_ghost_pad_new("sink", sinkpad); - // decoder - if ( d->usertp == TRUE ) - { - - demuxer = gst_element_factory_make ("rtpopusdepay", "ogg-demuxer"); - jitterbuffer = gst_element_factory_make ("rtpjitterbuffer", "rtpjitterbuffer"); - } else { - demuxer = gst_element_factory_make ("oggdemux", "ogg-demuxer"); + srcpad = gst_element_get_static_pad(muxer, "src"); + srcghostpad = gst_ghost_pad_new("src", srcpad); } - decoder = gst_element_factory_make ("opusdec", "opus-decoder"); - - if ( d->usertp == TRUE ) + if (type == DECODER) { - gst_bin_add_many( bin, rtpcapsfilter, jitterbuffer, demuxer, decoder, NULL); - gst_element_link_many ( rtpcapsfilter, jitterbuffer, demuxer, decoder, NULL); - sinkpad = gst_element_get_static_pad(rtpcapsfilter, "sink"); + bin = GST_BIN(gst_bin_new("Gnunet audiodecoder")); + // decoder + if (d->usertp == TRUE) + { + demuxer = gst_element_factory_make("rtpopusdepay", "ogg-demuxer"); + jitterbuffer = gst_element_factory_make("rtpjitterbuffer", "rtpjitterbuffer"); + } + else + { + demuxer = gst_element_factory_make("oggdemux", "ogg-demuxer"); + } + decoder = gst_element_factory_make("opusdec", "opus-decoder"); - } else { - gst_bin_add_many( bin, demuxer, decoder, NULL); - - g_signal_connect (demuxer, - "pad-added", - G_CALLBACK (decoder_ogg_pad_added), - decoder); + if (d->usertp == TRUE) + { + gst_bin_add_many(bin, rtpcapsfilter, jitterbuffer, demuxer, decoder, NULL); + gst_element_link_many(rtpcapsfilter, jitterbuffer, demuxer, decoder, NULL); + sinkpad = gst_element_get_static_pad(rtpcapsfilter, "sink"); + } + else + { + gst_bin_add_many(bin, demuxer, decoder, NULL); - sinkpad = gst_element_get_static_pad(demuxer, "sink"); - } - sinkghostpad = gst_ghost_pad_new ("sink", sinkpad); + g_signal_connect(demuxer, + "pad-added", + G_CALLBACK(decoder_ogg_pad_added), + decoder); - srcpad = gst_element_get_static_pad(decoder, "src"); - srcghostpad = gst_ghost_pad_new ("src", srcpad); + sinkpad = gst_element_get_static_pad(demuxer, "sink"); + } + sinkghostpad = gst_ghost_pad_new("sink", sinkpad); - } + srcpad = gst_element_get_static_pad(decoder, "src"); + srcghostpad = gst_ghost_pad_new("src", srcpad); + } // add pads to the bin - gst_pad_set_active (sinkghostpad, TRUE); - gst_element_add_pad (GST_ELEMENT(bin), sinkghostpad); + gst_pad_set_active(sinkghostpad, TRUE); + gst_element_add_pad(GST_ELEMENT(bin), sinkghostpad); - gst_pad_set_active (srcghostpad, TRUE); - gst_element_add_pad (GST_ELEMENT(bin), srcghostpad); + gst_pad_set_active(srcghostpad, TRUE); + gst_element_add_pad(GST_ELEMENT(bin), srcghostpad); return bin; @@ -896,82 +919,80 @@ get_coder(GNUNET_gstData *d , int type) extern GstBin * -get_audiobin(GNUNET_gstData *d , int type) +get_audiobin(GNUNET_gstData *d, int type) { GstBin *bin; GstElement *sink, *source, *queue, *conv, *resampler, *removesilence, *filter; GstPad *pad, *ghostpad; GstCaps *caps; - if ( type == SINK ) { - - bin = GST_BIN(gst_bin_new("Gnunet audiosink")); - /* Create all the elements */ - if ( d->dropsilence == TRUE ) + if (type == SINK) { - queue = gst_element_factory_make ("queue", "queue"); - removesilence = gst_element_factory_make ("removesilence", "removesilence"); - } + bin = GST_BIN(gst_bin_new("Gnunet audiosink")); - conv = gst_element_factory_make ("audioconvert", "converter"); - resampler= gst_element_factory_make ("audioresample", "resampler"); - - if ( d->audiobackend == AUTO ) - { - sink = gst_element_factory_make ("autoaudiosink", "audiosink"); - g_signal_connect (sink, "child-added", G_CALLBACK (autoaudiosink_child_added), NULL); + /* Create all the elements */ + if (d->dropsilence == TRUE) + { + queue = gst_element_factory_make("queue", "queue"); + removesilence = gst_element_factory_make("removesilence", "removesilence"); + } - } + conv = gst_element_factory_make("audioconvert", "converter"); + resampler = gst_element_factory_make("audioresample", "resampler"); - if ( d->audiobackend == ALSA ) - { - sink = gst_element_factory_make ("alsaaudiosink", "audiosink"); - } + if (d->audiobackend == AUTO) + { + sink = gst_element_factory_make("autoaudiosink", "audiosink"); + g_signal_connect(sink, "child-added", G_CALLBACK(autoaudiosink_child_added), NULL); + } - if ( d->audiobackend == JACK ) - { - sink = gst_element_factory_make ("jackaudiosink", "audiosink"); + if (d->audiobackend == ALSA) + { + sink = gst_element_factory_make("alsaaudiosink", "audiosink"); + } - g_object_set (G_OBJECT (sink), "client-name", "gnunet", NULL); + if (d->audiobackend == JACK) + { + sink = gst_element_factory_make("jackaudiosink", "audiosink"); - if (g_object_class_find_property - (G_OBJECT_GET_CLASS (sink), "port-pattern")) - { + g_object_set(G_OBJECT(sink), "client-name", "gnunet", NULL); + if (g_object_class_find_property + (G_OBJECT_GET_CLASS(sink), "port-pattern")) + { // char *portpattern = "system"; - g_object_set (G_OBJECT (sink), "port-pattern", d->jack_pp_out, - NULL); - } - - } + g_object_set(G_OBJECT(sink), "port-pattern", d->jack_pp_out, + NULL); + } + } - if ( d->audiobackend == FAKE ) - { - sink = gst_element_factory_make ("fakesink", "audiosink"); - } + if (d->audiobackend == FAKE) + { + sink = gst_element_factory_make("fakesink", "audiosink"); + } - g_object_set (sink, - "buffer-time", (gint64) BUFFER_TIME, - "latency-time", (gint64) LATENCY_TIME, - NULL); + g_object_set(sink, + "buffer-time", (gint64)BUFFER_TIME, + "latency-time", (gint64)LATENCY_TIME, + NULL); - if ( d->dropsilence == TRUE ) - { - // Do not remove silence by default - g_object_set( removesilence, "remove", FALSE, NULL); - g_object_set( queue, "max-size-buffers", 12, NULL); - /* - g_signal_connect (source, - "need-data", - G_CALLBACK(appsrc_need_data), - NULL); - - g_signal_connect (source, - "enough-data", - G_CALLBACK(appsrc_enough_data), - NULL); - */ + if (d->dropsilence == TRUE) + { + // Do not remove silence by default + g_object_set(removesilence, "remove", FALSE, NULL); + g_object_set(queue, "max-size-buffers", 12, NULL); + /* + g_signal_connect (source, + "need-data", + G_CALLBACK(appsrc_need_data), + NULL); + + g_signal_connect (source, + "enough-data", + G_CALLBACK(appsrc_enough_data), + NULL); + */ /* g_signal_connect (queue, "notify::current-level-bytes", @@ -998,109 +1019,109 @@ get_audiobin(GNUNET_gstData *d , int type) G_CALLBACK(queue_pushing), NULL); */ + } - } - - - - - - gst_bin_add_many (bin , conv, resampler, sink, NULL); - gst_element_link_many ( conv, resampler, sink, NULL); - - if ( d->dropsilence == TRUE ) - { - gst_bin_add_many (bin , queue ,removesilence , NULL); - - if ( !gst_element_link_many ( queue, removesilence, conv, NULL) ) - lf ("queue, removesilence, conv "); - - pad = gst_element_get_static_pad (queue, "sink"); - } else { - pad = gst_element_get_static_pad(conv, "sink"); - } - ghostpad = gst_ghost_pad_new ("sink", pad); + gst_bin_add_many(bin, conv, resampler, sink, NULL); + gst_element_link_many(conv, resampler, sink, NULL); - } else { - // SOURCE + if (d->dropsilence == TRUE) + { + gst_bin_add_many(bin, queue, removesilence, NULL); - bin = GST_BIN(gst_bin_new("Gnunet audiosource")); + if (!gst_element_link_many(queue, removesilence, conv, NULL)) + lf("queue, removesilence, conv "); - // source = gst_element_factory_make("audiotestsrc", "audiotestsrcbla"); + pad = gst_element_get_static_pad(queue, "sink"); + } + else + { + pad = gst_element_get_static_pad(conv, "sink"); + } - if (d->audiobackend == AUTO ) - { - source = gst_element_factory_make ("autoaudiosrc", "audiosource"); - } - if (d->audiobackend == ALSA ) - { - source = gst_element_factory_make ("alsasrc", "audiosource"); - } - if (d->audiobackend == JACK ) - { - source = gst_element_factory_make ("jackaudiosrc", "audiosource"); + ghostpad = gst_ghost_pad_new("sink", pad); } - if (d->audiobackend == TEST ) + else { - source = gst_element_factory_make ("audiotestsrc", "audiosource"); - } + // SOURCE - filter = gst_element_factory_make ("capsfilter", "filter"); - conv = gst_element_factory_make ("audioconvert", "converter"); - resampler= gst_element_factory_make ("audioresample", "resampler"); + bin = GST_BIN(gst_bin_new("Gnunet audiosource")); - if (d->audiobackend == AUTO ) { - g_signal_connect (source, "child-added", G_CALLBACK (autoaudiosource_child_added), NULL); + // source = gst_element_factory_make("audiotestsrc", "audiotestsrcbla"); - } else { - if (GST_IS_AUDIO_BASE_SRC (source)) - g_object_set (source, "buffer-time", (gint64) BUFFER_TIME, "latency-time", (gint64) LATENCY_TIME, NULL); - if ( d->audiobackend == JACK ) { - g_object_set (G_OBJECT (source), "client-name", "gnunet", NULL); - if (g_object_class_find_property - (G_OBJECT_GET_CLASS (source), "port-pattern")) + if (d->audiobackend == AUTO) + { + source = gst_element_factory_make("autoaudiosrc", "audiosource"); + } + if (d->audiobackend == ALSA) + { + source = gst_element_factory_make("alsasrc", "audiosource"); + } + if (d->audiobackend == JACK) + { + source = gst_element_factory_make("jackaudiosrc", "audiosource"); + } + if (d->audiobackend == TEST) { + source = gst_element_factory_make("audiotestsrc", "audiosource"); + } - char *portpattern = "moc"; + filter = gst_element_factory_make("capsfilter", "filter"); + conv = gst_element_factory_make("audioconvert", "converter"); + resampler = gst_element_factory_make("audioresample", "resampler"); - g_object_set (G_OBJECT (source), "port-pattern", portpattern, - NULL); + if (d->audiobackend == AUTO) + { + g_signal_connect(source, "child-added", G_CALLBACK(autoaudiosource_child_added), NULL); + } + else + { + if (GST_IS_AUDIO_BASE_SRC(source)) + g_object_set(source, "buffer-time", (gint64)BUFFER_TIME, "latency-time", (gint64)LATENCY_TIME, NULL); + if (d->audiobackend == JACK) + { + g_object_set(G_OBJECT(source), "client-name", "gnunet", NULL); + if (g_object_class_find_property + (G_OBJECT_GET_CLASS(source), "port-pattern")) + { + char *portpattern = "moc"; + + g_object_set(G_OBJECT(source), "port-pattern", portpattern, + NULL); + } + } } - } - } - - caps = gst_caps_new_simple ("audio/x-raw", - /* "format", G_TYPE_STRING, "S16LE", */ - /* "rate", G_TYPE_INT, SAMPLING_RATE,*/ - "channels", G_TYPE_INT, OPUS_CHANNELS, - /* "layout", G_TYPE_STRING, "interleaved",*/ - NULL); - g_object_set (G_OBJECT (filter), - "caps", caps, - NULL); - gst_caps_unref (caps); + caps = gst_caps_new_simple("audio/x-raw", + /* "format", G_TYPE_STRING, "S16LE", */ + /* "rate", G_TYPE_INT, SAMPLING_RATE,*/ + "channels", G_TYPE_INT, OPUS_CHANNELS, + /* "layout", G_TYPE_STRING, "interleaved",*/ + NULL); - gst_bin_add_many (bin , source, filter, conv, resampler, NULL); - gst_element_link_many ( source, filter, conv, resampler, NULL); + g_object_set(G_OBJECT(filter), + "caps", caps, + NULL); + gst_caps_unref(caps); - pad = gst_element_get_static_pad (resampler, "src"); + gst_bin_add_many(bin, source, filter, conv, resampler, NULL); + gst_element_link_many(source, filter, conv, resampler, NULL); + pad = gst_element_get_static_pad(resampler, "src"); - /* pads */ - ghostpad = gst_ghost_pad_new ("src", pad); - } + /* pads */ + ghostpad = gst_ghost_pad_new("src", pad); + } /* set the bin pads */ - gst_pad_set_active (ghostpad, TRUE); - gst_element_add_pad (GST_ELEMENT(bin), ghostpad); + gst_pad_set_active(ghostpad, TRUE); + gst_element_add_pad(GST_ELEMENT(bin), ghostpad); - gst_object_unref (pad); + gst_object_unref(pad); return bin; } diff --git a/src/conversation/gnunet_gst.h b/src/conversation/gnunet_gst.h index 88e2dc100..8667a823b 100644 --- a/src/conversation/gnunet_gst.h +++ b/src/conversation/gnunet_gst.h @@ -1,22 +1,22 @@ /* - This file is part of GNUnet. - Copyright (C) 2016 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet. + Copyright (C) 2016 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/gnunet_gst.c * @brief FIXME @@ -27,35 +27,35 @@ // /* -int audiobackend = JACK; -int dropsilence = TRUE; -int enough = 0; -int usertp = TRUE; -*/ + int audiobackend = JACK; + int dropsilence = TRUE; + int enough = 0; + int usertp = TRUE; + */ -#define gst_element_factory_make(element, name) gst_element_factory_make_debug (element, name); +#define gst_element_factory_make(element, name) gst_element_factory_make_debug(element, name); extern void pl_graph(); extern GstElement * - gst_element_factory_make_debug( gchar *, gchar *); +gst_element_factory_make_debug(gchar *, gchar *); extern GstBin * - get_audiobin(GNUNET_gstData *, int); +get_audiobin(GNUNET_gstData *, int); extern GstBin * - get_coder(GNUNET_gstData *, int); +get_coder(GNUNET_gstData *, int); extern gboolean -gnunet_gst_bus_call (GstBus *bus, GstMessage *msg, gpointer data); +gnunet_gst_bus_call(GstBus *bus, GstMessage *msg, gpointer data); extern void -gg_setup_gst_bus (GNUNET_gstData * d); +gg_setup_gst_bus(GNUNET_gstData * d); extern void -gg_load_configuration (GNUNET_gstData * d); +gg_load_configuration(GNUNET_gstData * d); extern GstFlowReturn -on_appsink_new_sample (GstElement *, GNUNET_gstData *); +on_appsink_new_sample(GstElement *, GNUNET_gstData *); diff --git a/src/conversation/gnunet_gst_def.h b/src/conversation/gnunet_gst_def.h index 131dc4f7d..341341f24 100644 --- a/src/conversation/gnunet_gst_def.h +++ b/src/conversation/gnunet_gst_def.h @@ -1,22 +1,22 @@ /* - This file is part of GNUnet. - Copyright (C) 2016 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet. + Copyright (C) 2016 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/gnunet_gst_def.h * @brief FIXME @@ -43,20 +43,20 @@ #include "gnunet_common.h" /* -#include -#include -#include -*/ + #include + #include + #include + */ /* huh -#include + #include -#include -#include -#include -#include -#include -*/ + #include + #include + #include + #include + #include + */ #include #include @@ -190,29 +190,29 @@ struct GNUNET_gstData { #define SAMPLING_RATE 48000 enum { - AUTO, - JACK, - ALSA, - FAKE, - TEST + AUTO, + JACK, + ALSA, + FAKE, + TEST }; enum { - SOURCE, - SINK + SOURCE, + SINK }; enum { - ENCODER, - DECODER + ENCODER, + DECODER }; enum { - FAIL, - OK + FAIL, + OK }; enum { - SPEAKER, - MICROPHONE + SPEAKER, + MICROPHONE }; diff --git a/src/conversation/gnunet_gst_test.c b/src/conversation/gnunet_gst_test.c index f52130fa4..60e920f10 100644 --- a/src/conversation/gnunet_gst_test.c +++ b/src/conversation/gnunet_gst_test.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet. - Copyright (C) 2016 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet. + Copyright (C) 2016 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/gnunet_gst_test.c * @brief FIXME @@ -27,7 +27,7 @@ #include "gnunet_gst.h" int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { struct GNUNET_gstData *gst; // GstBus *bus; @@ -48,14 +48,14 @@ main (int argc, char *argv[]) gg_load_configuration(gst); /* - gst->audiobackend = JACK; - gst->dropsilence = TRUE; - gst->usertp = FALSE; - */ + gst->audiobackend = JACK; + gst->dropsilence = TRUE; + gst->usertp = FALSE; + */ /* Initialize GStreamer */ - gst_init (&argc, &argv); + gst_init(&argc, &argv); - gst->pipeline = GST_PIPELINE(gst_pipeline_new ("gnunet-media-helper")); + gst->pipeline = GST_PIPELINE(gst_pipeline_new("gnunet-media-helper")); #ifdef IS_SPEAKER int type = SPEAKER; @@ -64,39 +64,34 @@ main (int argc, char *argv[]) #ifdef IS_MIC int type = MICROPHONE; printf("this is the microphone \n"); - #endif - if ( type == SPEAKER) - { - - gnunetsrc = GST_ELEMENT(get_app(gst, SOURCE)); - - sink = GST_ELEMENT(get_audiobin(gst, SINK)); - decoder = GST_ELEMENT(get_coder(gst, DECODER)); - gst_bin_add_many( GST_BIN(gst->pipeline), gnunetsrc, decoder, sink, NULL); - gst_element_link_many( gnunetsrc, decoder, sink , NULL); - - } - if ( type == MICROPHONE ) { - - source = GST_ELEMENT(get_audiobin(gst, SOURCE)); - - encoder = GST_ELEMENT(get_coder(gst, ENCODER)); - - gnunetsink = GST_ELEMENT(get_app(gst, SINK)); + if (type == SPEAKER) + { + gnunetsrc = GST_ELEMENT(get_app(gst, SOURCE)); + + sink = GST_ELEMENT(get_audiobin(gst, SINK)); + decoder = GST_ELEMENT(get_coder(gst, DECODER)); + gst_bin_add_many(GST_BIN(gst->pipeline), gnunetsrc, decoder, sink, NULL); + gst_element_link_many(gnunetsrc, decoder, sink, NULL); + } + if (type == MICROPHONE) + { + source = GST_ELEMENT(get_audiobin(gst, SOURCE)); - gst_bin_add_many( GST_BIN(gst->pipeline), source, encoder, gnunetsink, NULL); - gst_element_link_many( source, encoder, gnunetsink , NULL); + encoder = GST_ELEMENT(get_coder(gst, ENCODER)); + gnunetsink = GST_ELEMENT(get_app(gst, SINK)); - } + gst_bin_add_many(GST_BIN(gst->pipeline), source, encoder, gnunetsink, NULL); + gst_element_link_many(source, encoder, gnunetsink, NULL); + } /* - gst_bin_add_many( GST_BIN(gst->pipeline), appsource, appsink, source, encoder, decoder, sink, NULL); - gst_element_link_many( source, encoder, decoder, sink , NULL); -*/ + gst_bin_add_many( GST_BIN(gst->pipeline), appsource, appsink, source, encoder, decoder, sink, NULL); + gst_element_link_many( source, encoder, decoder, sink , NULL); + */ pl_graph(gst->pipeline); /* Start playing */ - gst_element_set_state (GST_ELEMENT(gst->pipeline), GST_STATE_PLAYING); + gst_element_set_state(GST_ELEMENT(gst->pipeline), GST_STATE_PLAYING); //pl_graph(gst->pipeline); @@ -109,14 +104,12 @@ main (int argc, char *argv[]) // start pushing buffers - if ( type == MICROPHONE ) - { - + if (type == MICROPHONE) + { + GMainLoop *loop; + loop = g_main_loop_new(NULL, FALSE); - GMainLoop *loop; - loop = g_main_loop_new (NULL, FALSE); - - g_main_loop_run (loop); + g_main_loop_run(loop); /* while ( 1 ) @@ -124,21 +117,21 @@ main (int argc, char *argv[]) GstFlowReturn flow; flow = on_appsink_new_sample (gst->appsink, gst); } -*/ + */ } - if ( type == SPEAKER ) - { - while ( 1 ) - { + if (type == SPEAKER) + { + while (1) + { // printf("read.. \n"); - gnunet_read(gst); - } - } - g_print ("Returned, stopping playback\n"); + gnunet_read(gst); + } + } + g_print("Returned, stopping playback\n"); // gst_object_unref (bus); - gst_element_set_state (GST_ELEMENT(gst->pipeline), GST_STATE_NULL); - gst_object_unref (gst->pipeline); + gst_element_set_state(GST_ELEMENT(gst->pipeline), GST_STATE_NULL); + gst_object_unref(gst->pipeline); return 0; } diff --git a/src/conversation/microphone.c b/src/conversation/microphone.c index 57588f05a..01f8adb1e 100644 --- a/src/conversation/microphone.c +++ b/src/conversation/microphone.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet - Copyright (C) 2013 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet + Copyright (C) 2013 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -34,9 +34,7 @@ /** * Internal data structures for the microphone. */ -struct Microphone -{ - +struct Microphone { /** * Our configuration. */ @@ -56,7 +54,6 @@ struct Microphone * Closure for @e rdc. */ void *rdc_cls; - }; @@ -70,21 +67,21 @@ struct Microphone * #GNUNET_SYSERR to stop further processing with error */ static int -process_record_messages (void *cls, - const struct GNUNET_MessageHeader *msg) +process_record_messages(void *cls, + const struct GNUNET_MessageHeader *msg) { struct Microphone *mic = cls; const struct AudioMessage *am; - if (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - am = (const struct AudioMessage *) msg; - mic->rdc (mic->rdc_cls, - ntohs (msg->size) - sizeof (struct AudioMessage), - &am[1]); + if (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + am = (const struct AudioMessage *)msg; + mic->rdc(mic->rdc_cls, + ntohs(msg->size) - sizeof(struct AudioMessage), + &am[1]); return GNUNET_OK; } @@ -97,9 +94,9 @@ process_record_messages (void *cls, * @param rdc_cls closure for @a dc */ static int -enable (void *cls, - GNUNET_MICROPHONE_RecordedDataCallback rdc, - void *rdc_cls) +enable(void *cls, + GNUNET_MICROPHONE_RecordedDataCallback rdc, + void *rdc_cls) { struct Microphone *mic = cls; static char * const record_helper_argv[] = @@ -110,17 +107,17 @@ enable (void *cls, mic->rdc = rdc; mic->rdc_cls = rdc_cls; - mic->record_helper = GNUNET_HELPER_start (GNUNET_NO, - "gnunet-helper-audio-record", - record_helper_argv, - &process_record_messages, - NULL, mic); + mic->record_helper = GNUNET_HELPER_start(GNUNET_NO, + "gnunet-helper-audio-record", + record_helper_argv, + &process_record_messages, + NULL, mic); if (NULL == mic->record_helper) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Could not start record audio helper\n")); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Could not start record audio helper\n")); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -131,18 +128,18 @@ enable (void *cls, * @param cls clsoure */ static void -disable (void *cls) +disable(void *cls) { struct Microphone *mic = cls; if (NULL == mic->record_helper) - { - GNUNET_break (0); - return; - } - GNUNET_break (GNUNET_OK == - GNUNET_HELPER_kill (mic->record_helper, GNUNET_NO)); - GNUNET_HELPER_destroy (mic->record_helper); + { + GNUNET_break(0); + return; + } + GNUNET_break(GNUNET_OK == + GNUNET_HELPER_kill(mic->record_helper, GNUNET_NO)); + GNUNET_HELPER_destroy(mic->record_helper); mic->record_helper = NULL; } @@ -153,12 +150,12 @@ disable (void *cls) * @param cls clsoure */ static void -destroy (void *cls) +destroy(void *cls) { struct Microphone *mic = cls; if (NULL != mic->record_helper) - disable (mic); + disable(mic); } @@ -170,14 +167,14 @@ destroy (void *cls) * @return NULL on error */ struct GNUNET_MICROPHONE_Handle * -GNUNET_MICROPHONE_create_from_hardware (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_MICROPHONE_create_from_hardware(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_MICROPHONE_Handle *microphone; struct Microphone *mic; - mic = GNUNET_new (struct Microphone); + mic = GNUNET_new(struct Microphone); mic->cfg = cfg; - microphone = GNUNET_new (struct GNUNET_MICROPHONE_Handle); + microphone = GNUNET_new(struct GNUNET_MICROPHONE_Handle); microphone->cls = mic; microphone->enable_microphone = &enable; microphone->disable_microphone = &disable; @@ -192,10 +189,10 @@ GNUNET_MICROPHONE_create_from_hardware (const struct GNUNET_CONFIGURATION_Handle * @param microphone microphone to destroy */ void -GNUNET_MICROPHONE_destroy (struct GNUNET_MICROPHONE_Handle *microphone) +GNUNET_MICROPHONE_destroy(struct GNUNET_MICROPHONE_Handle *microphone) { - microphone->destroy_microphone (microphone->cls); - GNUNET_free (microphone); + microphone->destroy_microphone(microphone->cls); + GNUNET_free(microphone); } /* end of microphone.c */ diff --git a/src/conversation/plugin_gnsrecord_conversation.c b/src/conversation/plugin_gnsrecord_conversation.c index 41c09ade9..adf397333 100644 --- a/src/conversation/plugin_gnsrecord_conversation.c +++ b/src/conversation/plugin_gnsrecord_conversation.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/plugin_gnsrecord_conversation.c @@ -44,50 +44,51 @@ * @return NULL on error, otherwise human-readable representation of the value */ static char * -conversation_value_to_string (void *cls, - uint32_t type, - const void *data, - size_t data_size) +conversation_value_to_string(void *cls, + uint32_t type, + const void *data, + size_t data_size) { char *s; - (void) cls; + (void)cls; switch (type) - { - case GNUNET_GNSRECORD_TYPE_PHONE: + { + case GNUNET_GNSRECORD_TYPE_PHONE: { const struct GNUNET_CONVERSATION_PhoneRecord *pr; char *ret; char *pkey; - if (data_size != sizeof (struct GNUNET_CONVERSATION_PhoneRecord)) - { - GNUNET_break_op (0); - return NULL; - } + if (data_size != sizeof(struct GNUNET_CONVERSATION_PhoneRecord)) + { + GNUNET_break_op(0); + return NULL; + } pr = data; - if (1 != ntohl (pr->version)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("PHONE version %u not supported\n"), - ntohl (pr->version)); - return NULL; - } - pkey = GNUNET_CRYPTO_eddsa_public_key_to_string (&pr->peer.public_key); - s = GNUNET_STRINGS_data_to_string_alloc (&pr->line_port, - sizeof (struct GNUNET_HashCode)); + if (1 != ntohl(pr->version)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("PHONE version %u not supported\n"), + ntohl(pr->version)); + return NULL; + } + pkey = GNUNET_CRYPTO_eddsa_public_key_to_string(&pr->peer.public_key); + s = GNUNET_STRINGS_data_to_string_alloc(&pr->line_port, + sizeof(struct GNUNET_HashCode)); - GNUNET_asprintf (&ret, - "%s-%s", - s, - pkey); - GNUNET_free (s); - GNUNET_free (pkey); + GNUNET_asprintf(&ret, + "%s-%s", + s, + pkey); + GNUNET_free(s); + GNUNET_free(pkey); return ret; } - default: - return NULL; - } + + default: + return NULL; + } } @@ -103,62 +104,63 @@ conversation_value_to_string (void *cls, * @return #GNUNET_OK on success */ static int -conversation_string_to_value (void *cls, - uint32_t type, - const char *s, - void **data, - size_t *data_size) +conversation_string_to_value(void *cls, + uint32_t type, + const char *s, + void **data, + size_t *data_size) { - (void) cls; + (void)cls; if (NULL == s) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } switch (type) - { - case GNUNET_GNSRECORD_TYPE_PHONE: + { + case GNUNET_GNSRECORD_TYPE_PHONE: { struct GNUNET_CONVERSATION_PhoneRecord *pr; char line_port[103]; const char *dash; struct GNUNET_PeerIdentity peer; - if ( (NULL == (dash = strchr (s, '-'))) || - (1 != sscanf (s, "%103s-", line_port)) || - (GNUNET_OK != - GNUNET_CRYPTO_eddsa_public_key_from_string (dash + 1, - strlen (dash + 1), - &peer.public_key)) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to parse PHONE record `%s'\n"), - s); - return GNUNET_SYSERR; - } - pr = GNUNET_new (struct GNUNET_CONVERSATION_PhoneRecord); - pr->version = htonl (1); - pr->reserved = htonl (0); + if ((NULL == (dash = strchr(s, '-'))) || + (1 != sscanf(s, "%103s-", line_port)) || + (GNUNET_OK != + GNUNET_CRYPTO_eddsa_public_key_from_string(dash + 1, + strlen(dash + 1), + &peer.public_key))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse PHONE record `%s'\n"), + s); + return GNUNET_SYSERR; + } + pr = GNUNET_new(struct GNUNET_CONVERSATION_PhoneRecord); + pr->version = htonl(1); + pr->reserved = htonl(0); if (GNUNET_OK != - GNUNET_STRINGS_string_to_data (line_port, - strlen (line_port), - &pr->line_port, - sizeof (struct GNUNET_HashCode))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to parse PHONE record `%s'\n"), - s); - GNUNET_free (pr); - return GNUNET_SYSERR; - } + GNUNET_STRINGS_string_to_data(line_port, + strlen(line_port), + &pr->line_port, + sizeof(struct GNUNET_HashCode))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse PHONE record `%s'\n"), + s); + GNUNET_free(pr); + return GNUNET_SYSERR; + } pr->peer = peer; *data = pr; - *data_size = sizeof (struct GNUNET_CONVERSATION_PhoneRecord); + *data_size = sizeof(struct GNUNET_CONVERSATION_PhoneRecord); return GNUNET_OK; } - default: - return GNUNET_SYSERR; - } + + default: + return GNUNET_SYSERR; + } } @@ -170,7 +172,7 @@ static struct { const char *name; uint32_t number; } name_map[] = { - { "PHONE", GNUNET_GNSRECORD_TYPE_PHONE }, + { "PHONE", GNUNET_GNSRECORD_TYPE_PHONE }, { NULL, UINT32_MAX } }; @@ -183,15 +185,15 @@ static struct { * @return corresponding number, UINT32_MAX on error */ static uint32_t -conversation_typename_to_number (void *cls, - const char *gns_typename) +conversation_typename_to_number(void *cls, + const char *gns_typename) { unsigned int i; - (void) cls; - i=0; - while ( (name_map[i].name != NULL) && - (0 != strcasecmp (gns_typename, name_map[i].name)) ) + (void)cls; + i = 0; + while ((name_map[i].name != NULL) && + (0 != strcasecmp(gns_typename, name_map[i].name))) i++; return name_map[i].number; } @@ -205,15 +207,15 @@ conversation_typename_to_number (void *cls, * @return corresponding typestring, NULL on error */ static const char * -conversation_number_to_typename (void *cls, - uint32_t type) +conversation_number_to_typename(void *cls, + uint32_t type) { unsigned int i; - (void) cls; - i=0; - while ( (name_map[i].name != NULL) && - (type != name_map[i].number) ) + (void)cls; + i = 0; + while ((name_map[i].name != NULL) && + (type != name_map[i].number)) i++; return name_map[i].name; } @@ -226,12 +228,12 @@ conversation_number_to_typename (void *cls, * @return the exported block API */ void * -libgnunet_plugin_gnsrecord_conversation_init (void *cls) +libgnunet_plugin_gnsrecord_conversation_init(void *cls) { struct GNUNET_GNSRECORD_PluginFunctions *api; - (void) cls; - api = GNUNET_new (struct GNUNET_GNSRECORD_PluginFunctions); + (void)cls; + api = GNUNET_new(struct GNUNET_GNSRECORD_PluginFunctions); api->value_to_string = &conversation_value_to_string; api->string_to_value = &conversation_string_to_value; api->typename_to_number = &conversation_typename_to_number; @@ -247,11 +249,11 @@ libgnunet_plugin_gnsrecord_conversation_init (void *cls) * @return NULL */ void * -libgnunet_plugin_gnsrecord_conversation_done (void *cls) +libgnunet_plugin_gnsrecord_conversation_done(void *cls) { struct GNUNET_GNSRECORD_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/conversation/speaker.c b/src/conversation/speaker.c index e2ace9115..96fd42b8d 100644 --- a/src/conversation/speaker.c +++ b/src/conversation/speaker.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet - Copyright (C) 2013 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet + Copyright (C) 2013 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -33,8 +33,7 @@ /** * Internal data structures for the speaker. */ -struct Speaker -{ +struct Speaker { /** * Our configuration. */ @@ -44,7 +43,6 @@ struct Speaker * Handle for the playback helper */ struct GNUNET_HELPER_Handle *playback_helper; - }; @@ -55,7 +53,7 @@ struct Speaker * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -enable (void *cls) +enable(void *cls) { struct Speaker *spe = cls; static char *playback_helper_argv[] = @@ -64,17 +62,17 @@ enable (void *cls) NULL }; - spe->playback_helper = GNUNET_HELPER_start (GNUNET_NO, - "gnunet-helper-audio-playback", - playback_helper_argv, - NULL, - NULL, spe); + spe->playback_helper = GNUNET_HELPER_start(GNUNET_NO, + "gnunet-helper-audio-playback", + playback_helper_argv, + NULL, + NULL, spe); if (NULL == spe->playback_helper) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Could not start playback audio helper.\n")); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Could not start playback audio helper.\n")); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -85,18 +83,18 @@ enable (void *cls) * @param cls closure with the `struct Speaker` */ static void -disable (void *cls) +disable(void *cls) { struct Speaker *spe = cls; if (NULL == spe->playback_helper) - { - GNUNET_break (0); - return; - } - GNUNET_break (GNUNET_OK == - GNUNET_HELPER_kill (spe->playback_helper, GNUNET_NO)); - GNUNET_HELPER_destroy (spe->playback_helper); + { + GNUNET_break(0); + return; + } + GNUNET_break(GNUNET_OK == + GNUNET_HELPER_kill(spe->playback_helper, GNUNET_NO)); + GNUNET_HELPER_destroy(spe->playback_helper); spe->playback_helper = NULL; } @@ -107,12 +105,12 @@ disable (void *cls) * @param cls closure with the `struct Speaker` */ static void -destroy (void *cls) +destroy(void *cls) { struct Speaker *spe = cls; if (NULL != spe->playback_helper) - disable (spe); + disable(spe); } @@ -125,27 +123,27 @@ destroy (void *cls) * opaque to the API but should be OPUS. */ static void -play (void *cls, - size_t data_size, - const void *data) +play(void *cls, + size_t data_size, + const void *data) { struct Speaker *spe = cls; - char buf[sizeof (struct AudioMessage) + data_size]; + char buf[sizeof(struct AudioMessage) + data_size]; struct AudioMessage *am; if (NULL == spe->playback_helper) - { - GNUNET_break (0); - return; - } - am = (struct AudioMessage *) buf; - am->header.size = htons (sizeof (struct AudioMessage) + data_size); - am->header.type = htons (GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO); - GNUNET_memcpy (&am[1], data, data_size); - (void) GNUNET_HELPER_send (spe->playback_helper, - &am->header, - GNUNET_NO, - NULL, NULL); + { + GNUNET_break(0); + return; + } + am = (struct AudioMessage *)buf; + am->header.size = htons(sizeof(struct AudioMessage) + data_size); + am->header.type = htons(GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO); + GNUNET_memcpy(&am[1], data, data_size); + (void)GNUNET_HELPER_send(spe->playback_helper, + &am->header, + GNUNET_NO, + NULL, NULL); } @@ -157,14 +155,14 @@ play (void *cls, * @return NULL on error */ struct GNUNET_SPEAKER_Handle * -GNUNET_SPEAKER_create_from_hardware (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_SPEAKER_create_from_hardware(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_SPEAKER_Handle *speaker; struct Speaker *spe; - spe = GNUNET_new (struct Speaker); + spe = GNUNET_new(struct Speaker); spe->cfg = cfg; - speaker = GNUNET_new (struct GNUNET_SPEAKER_Handle); + speaker = GNUNET_new(struct GNUNET_SPEAKER_Handle); speaker->cls = spe; speaker->enable_speaker = &enable; speaker->play = &play; @@ -180,10 +178,10 @@ GNUNET_SPEAKER_create_from_hardware (const struct GNUNET_CONFIGURATION_Handle *c * @param speaker speaker to destroy */ void -GNUNET_SPEAKER_destroy (struct GNUNET_SPEAKER_Handle *speaker) +GNUNET_SPEAKER_destroy(struct GNUNET_SPEAKER_Handle *speaker) { - speaker->destroy_speaker (speaker->cls); - GNUNET_free (speaker); + speaker->destroy_speaker(speaker->cls); + GNUNET_free(speaker); } /* end of speaker.c */ diff --git a/src/conversation/test_conversation_api.c b/src/conversation/test_conversation_api.c index a7b394dc3..e58f89e7a 100644 --- a/src/conversation/test_conversation_api.c +++ b/src/conversation/test_conversation_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/test_conversation_api.c * @brief testcase for conversation_api.c @@ -33,9 +33,9 @@ #include "gnunet_identity_service.h" #include "gnunet_namestore_service.h" -#define FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250) +#define FREQ GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250) -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 25) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 25) static int ok = 1; @@ -73,174 +73,174 @@ static struct GNUNET_SCHEDULER_Task *call_task; static void -phone_send (void *cls) +phone_send(void *cls) { static unsigned int i; char buf[32]; - (void) cls; - GNUNET_assert (NULL != phone_rdc); - GNUNET_snprintf (buf, sizeof (buf), "phone-%u", i++); - phone_rdc (phone_rdc_cls, strlen (buf) + 1, buf); - phone_task = GNUNET_SCHEDULER_add_delayed (FREQ, &phone_send, NULL); + (void)cls; + GNUNET_assert(NULL != phone_rdc); + GNUNET_snprintf(buf, sizeof(buf), "phone-%u", i++); + phone_rdc(phone_rdc_cls, strlen(buf) + 1, buf); + phone_task = GNUNET_SCHEDULER_add_delayed(FREQ, &phone_send, NULL); } static void -call_send (void *cls) +call_send(void *cls) { static unsigned int i; char buf[32]; - (void) cls; - GNUNET_assert (NULL != call_rdc); - GNUNET_snprintf (buf, sizeof (buf), "call-%u", i++); - call_rdc (call_rdc_cls, strlen (buf) + 1, buf); - call_task = GNUNET_SCHEDULER_add_delayed (FREQ, &call_send, NULL); + (void)cls; + GNUNET_assert(NULL != call_rdc); + GNUNET_snprintf(buf, sizeof(buf), "call-%u", i++); + call_rdc(call_rdc_cls, strlen(buf) + 1, buf); + call_task = GNUNET_SCHEDULER_add_delayed(FREQ, &call_send, NULL); } static int -enable_speaker (void *cls) +enable_speaker(void *cls) { const char *origin = cls; - fprintf (stderr, "Speaker %s enabled\n", origin); + fprintf(stderr, "Speaker %s enabled\n", origin); return GNUNET_OK; } static void -disable_speaker (void *cls) +disable_speaker(void *cls) { const char *origin = cls; - fprintf (stderr, "Speaker %s disabled\n", origin); + fprintf(stderr, "Speaker %s disabled\n", origin); } static void -play (void *cls, size_t data_size, const void *data) +play(void *cls, size_t data_size, const void *data) { const char *origin = cls; static unsigned int phone_i = 1; static unsigned int call_i; char buf[32]; - if (0 == strcmp (origin, "phone")) - GNUNET_snprintf (buf, sizeof (buf), "call-%u", call_i++); + if (0 == strcmp(origin, "phone")) + GNUNET_snprintf(buf, sizeof(buf), "call-%u", call_i++); else - GNUNET_snprintf (buf, sizeof (buf), "phone-%u", phone_i++); - if ((data_size != strlen (buf) + 1) || (0 != strncmp (buf, data, data_size))) - { - fprintf (stderr, - "Expected %s, received %.*s\n", - buf, - (int) data_size, - (const char *) data); - } + GNUNET_snprintf(buf, sizeof(buf), "phone-%u", phone_i++); + if ((data_size != strlen(buf) + 1) || (0 != strncmp(buf, data, data_size))) + { + fprintf(stderr, + "Expected %s, received %.*s\n", + buf, + (int)data_size, + (const char *)data); + } else - { - fprintf (stderr, "."); - } + { + fprintf(stderr, "."); + } if ((20 < call_i) && (20 < phone_i) && (NULL != call)) - { - /* time to hang up ... */ - GNUNET_CONVERSATION_call_stop (call); - call = NULL; - } + { + /* time to hang up ... */ + GNUNET_CONVERSATION_call_stop(call); + call = NULL; + } } static void -destroy_speaker (void *cls) +destroy_speaker(void *cls) { const char *origin = cls; - fprintf (stderr, "Speaker %s destroyed\n", origin); + fprintf(stderr, "Speaker %s destroyed\n", origin); } -static struct GNUNET_SPEAKER_Handle call_speaker = {&enable_speaker, - &play, - &disable_speaker, - &destroy_speaker, - "caller"}; - - -static struct GNUNET_SPEAKER_Handle phone_speaker = {&enable_speaker, +static struct GNUNET_SPEAKER_Handle call_speaker = { &enable_speaker, &play, &disable_speaker, &destroy_speaker, - "phone"}; + "caller" }; + + +static struct GNUNET_SPEAKER_Handle phone_speaker = { &enable_speaker, + &play, + &disable_speaker, + &destroy_speaker, + "phone" }; static int -enable_mic (void *cls, - GNUNET_MICROPHONE_RecordedDataCallback rdc, - void *rdc_cls) +enable_mic(void *cls, + GNUNET_MICROPHONE_RecordedDataCallback rdc, + void *rdc_cls) { const char *origin = cls; - fprintf (stderr, "Mic %s enabled\n", origin); - if (0 == strcmp (origin, "phone")) - { - phone_rdc = rdc; - phone_rdc_cls = rdc_cls; - phone_task = GNUNET_SCHEDULER_add_now (&phone_send, NULL); - } + fprintf(stderr, "Mic %s enabled\n", origin); + if (0 == strcmp(origin, "phone")) + { + phone_rdc = rdc; + phone_rdc_cls = rdc_cls; + phone_task = GNUNET_SCHEDULER_add_now(&phone_send, NULL); + } else - { - call_rdc = rdc; - call_rdc_cls = rdc_cls; - call_task = GNUNET_SCHEDULER_add_now (&call_send, NULL); - } + { + call_rdc = rdc; + call_rdc_cls = rdc_cls; + call_task = GNUNET_SCHEDULER_add_now(&call_send, NULL); + } return GNUNET_OK; } static void -disable_mic (void *cls) +disable_mic(void *cls) { const char *origin = cls; - fprintf (stderr, "Mic %s disabled\n", origin); - if (0 == strcmp (origin, "phone")) - { - phone_rdc = NULL; - phone_rdc_cls = NULL; - GNUNET_SCHEDULER_cancel (phone_task); - phone_task = NULL; - } + fprintf(stderr, "Mic %s disabled\n", origin); + if (0 == strcmp(origin, "phone")) + { + phone_rdc = NULL; + phone_rdc_cls = NULL; + GNUNET_SCHEDULER_cancel(phone_task); + phone_task = NULL; + } else - { - call_rdc = NULL; - call_rdc_cls = NULL; - GNUNET_SCHEDULER_cancel (call_task); - call_task = NULL; - } + { + call_rdc = NULL; + call_rdc_cls = NULL; + GNUNET_SCHEDULER_cancel(call_task); + call_task = NULL; + } } static void -destroy_mic (void *cls) +destroy_mic(void *cls) { const char *origin = cls; - fprintf (stderr, "Mic %s destroyed\n", origin); + fprintf(stderr, "Mic %s destroyed\n", origin); } -static struct GNUNET_MICROPHONE_Handle call_mic = {&enable_mic, - &disable_mic, - &destroy_mic, - "caller"}; - - -static struct GNUNET_MICROPHONE_Handle phone_mic = {&enable_mic, +static struct GNUNET_MICROPHONE_Handle call_mic = { &enable_mic, &disable_mic, &destroy_mic, - "phone"}; + "caller" }; + + +static struct GNUNET_MICROPHONE_Handle phone_mic = { &enable_mic, + &disable_mic, + &destroy_mic, + "phone" }; /** @@ -249,248 +249,254 @@ static struct GNUNET_MICROPHONE_Handle phone_mic = {&enable_mic, * @param cls closure */ static void -end_test (void *cls) +end_test(void *cls) { - (void) cls; - GNUNET_SCHEDULER_shutdown (); + (void)cls; + GNUNET_SCHEDULER_shutdown(); if (NULL != op) - { - GNUNET_IDENTITY_cancel (op); - op = NULL; - } + { + GNUNET_IDENTITY_cancel(op); + op = NULL; + } if (NULL != call) - { - GNUNET_CONVERSATION_call_stop (call); - call = NULL; - } + { + GNUNET_CONVERSATION_call_stop(call); + call = NULL; + } if (NULL != phone) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from PHONE service.\n"); - GNUNET_CONVERSATION_phone_destroy (phone); - phone = NULL; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from PHONE service.\n"); + GNUNET_CONVERSATION_phone_destroy(phone); + phone = NULL; + } if (NULL != id) - { - GNUNET_IDENTITY_disconnect (id); - id = NULL; - } + { + GNUNET_IDENTITY_disconnect(id); + id = NULL; + } if (NULL != qe) - { - GNUNET_NAMESTORE_cancel (qe); - qe = NULL; - } + { + GNUNET_NAMESTORE_cancel(qe); + qe = NULL; + } if (NULL != ns) - { - GNUNET_NAMESTORE_disconnect (ns); - ns = NULL; - } + { + GNUNET_NAMESTORE_disconnect(ns); + ns = NULL; + } } static void -caller_event_handler (void *cls, enum GNUNET_CONVERSATION_CallerEventCode code) +caller_event_handler(void *cls, enum GNUNET_CONVERSATION_CallerEventCode code) { - (void) cls; + (void)cls; switch (code) - { - case GNUNET_CONVERSATION_EC_CALLER_SUSPEND: - case GNUNET_CONVERSATION_EC_CALLER_RESUME: - fprintf (stderr, "Unexpected caller code: %d\n", code); - break; - } + { + case GNUNET_CONVERSATION_EC_CALLER_SUSPEND: + case GNUNET_CONVERSATION_EC_CALLER_RESUME: + fprintf(stderr, "Unexpected caller code: %d\n", code); + break; + } } static void -phone_event_handler (void *cls, - enum GNUNET_CONVERSATION_PhoneEventCode code, - struct GNUNET_CONVERSATION_Caller *caller, - const struct GNUNET_CRYPTO_EcdsaPublicKey *caller_id) +phone_event_handler(void *cls, + enum GNUNET_CONVERSATION_PhoneEventCode code, + struct GNUNET_CONVERSATION_Caller *caller, + const struct GNUNET_CRYPTO_EcdsaPublicKey *caller_id) { static enum GNUNET_CONVERSATION_PhoneEventCode expect = GNUNET_CONVERSATION_EC_PHONE_RING; - (void) cls; - (void) caller_id; - GNUNET_break (code == expect); + (void)cls; + (void)caller_id; + GNUNET_break(code == expect); switch (code) - { - case GNUNET_CONVERSATION_EC_PHONE_RING: - active_caller = caller; - GNUNET_CONVERSATION_caller_pick_up (caller, - &caller_event_handler, - NULL, - &phone_speaker, - &phone_mic); - expect = GNUNET_CONVERSATION_EC_PHONE_HUNG_UP; - break; - case GNUNET_CONVERSATION_EC_PHONE_HUNG_UP: - GNUNET_break (caller == active_caller); - active_caller = NULL; - if (1 == ok) - ok = 0; - GNUNET_SCHEDULER_shutdown (); - break; - default: - fprintf (stderr, "Unexpected phone code: %d\n", code); - break; - } + { + case GNUNET_CONVERSATION_EC_PHONE_RING: + active_caller = caller; + GNUNET_CONVERSATION_caller_pick_up(caller, + &caller_event_handler, + NULL, + &phone_speaker, + &phone_mic); + expect = GNUNET_CONVERSATION_EC_PHONE_HUNG_UP; + break; + + case GNUNET_CONVERSATION_EC_PHONE_HUNG_UP: + GNUNET_break(caller == active_caller); + active_caller = NULL; + if (1 == ok) + ok = 0; + GNUNET_SCHEDULER_shutdown(); + break; + + default: + fprintf(stderr, "Unexpected phone code: %d\n", code); + break; + } } static void -call_event_handler (void *cls, enum GNUNET_CONVERSATION_CallEventCode code) +call_event_handler(void *cls, enum GNUNET_CONVERSATION_CallEventCode code) { static enum GNUNET_CONVERSATION_CallEventCode expect = GNUNET_CONVERSATION_EC_CALL_RINGING; - (void) cls; - GNUNET_break (code == expect); + (void)cls; + GNUNET_break(code == expect); switch (code) - { - case GNUNET_CONVERSATION_EC_CALL_RINGING: - expect = GNUNET_CONVERSATION_EC_CALL_PICKED_UP; - break; - case GNUNET_CONVERSATION_EC_CALL_PICKED_UP: - expect = -1; - break; - case GNUNET_CONVERSATION_EC_CALL_GNS_FAIL: - case GNUNET_CONVERSATION_EC_CALL_HUNG_UP: - call = NULL; - ok = 2; - GNUNET_break (0); - fprintf (stderr, "Unexpected call code: %d\n", code); - break; - case GNUNET_CONVERSATION_EC_CALL_SUSPENDED: - case GNUNET_CONVERSATION_EC_CALL_RESUMED: - GNUNET_break (0); - fprintf (stderr, "Unexpected call code: %d\n", code); - ok = 2; - break; - case GNUNET_CONVERSATION_EC_CALL_ERROR: - GNUNET_break (0); - fprintf (stderr, "Unexpected call code: %d\n", code); - call = NULL; - ok = 2; - break; - } + { + case GNUNET_CONVERSATION_EC_CALL_RINGING: + expect = GNUNET_CONVERSATION_EC_CALL_PICKED_UP; + break; + + case GNUNET_CONVERSATION_EC_CALL_PICKED_UP: + expect = -1; + break; + + case GNUNET_CONVERSATION_EC_CALL_GNS_FAIL: + case GNUNET_CONVERSATION_EC_CALL_HUNG_UP: + call = NULL; + ok = 2; + GNUNET_break(0); + fprintf(stderr, "Unexpected call code: %d\n", code); + break; + + case GNUNET_CONVERSATION_EC_CALL_SUSPENDED: + case GNUNET_CONVERSATION_EC_CALL_RESUMED: + GNUNET_break(0); + fprintf(stderr, "Unexpected call code: %d\n", code); + ok = 2; + break; + + case GNUNET_CONVERSATION_EC_CALL_ERROR: + GNUNET_break(0); + fprintf(stderr, "Unexpected call code: %d\n", code); + call = NULL; + ok = 2; + break; + } } static void -caller_ego_create_cont (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, - const char *emsg) +caller_ego_create_cont(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, + const char *emsg) { - (void) cls; + (void)cls; op = NULL; - GNUNET_assert (NULL == emsg); + GNUNET_assert(NULL == emsg); } static void -namestore_put_cont (void *cls, int32_t success, const char *emsg) +namestore_put_cont(void *cls, int32_t success, const char *emsg) { - (void) cls; + (void)cls; qe = NULL; - GNUNET_assert (GNUNET_YES == success); - GNUNET_assert (NULL == emsg); - GNUNET_assert (NULL == op); - op = GNUNET_IDENTITY_create (id, "caller-ego", &caller_ego_create_cont, NULL); + GNUNET_assert(GNUNET_YES == success); + GNUNET_assert(NULL == emsg); + GNUNET_assert(NULL == op); + op = GNUNET_IDENTITY_create(id, "caller-ego", &caller_ego_create_cont, NULL); } static void -identity_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +identity_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { struct GNUNET_GNSRECORD_Data rd; struct GNUNET_CRYPTO_EcdsaPublicKey pub; - (void) cls; - (void) ctx; + (void)cls; + (void)ctx; if (NULL == name) return; if (NULL == ego) return; - if (0 == strcmp (name, "phone-ego")) - { - GNUNET_IDENTITY_ego_get_public_key (ego, &pub); - GNUNET_asprintf (&gns_name, - "phone.%s", - GNUNET_GNSRECORD_pkey_to_zkey (&pub)); - phone = - GNUNET_CONVERSATION_phone_create (cfg, ego, &phone_event_handler, NULL); - GNUNET_assert (NULL != phone); - memset (&rd, 0, sizeof (rd)); - GNUNET_CONVERSATION_phone_get_record (phone, &rd); - GNUNET_assert (rd.record_type == GNUNET_GNSRECORD_TYPE_PHONE); - rd.expiration_time = UINT64_MAX; - qe = - GNUNET_NAMESTORE_records_store (ns, - GNUNET_IDENTITY_ego_get_private_key (ego), - "phone" /* GNS label */, - 1, - &rd, - &namestore_put_cont, - NULL); - return; - } - if (0 == strcmp (name, "caller-ego")) - { - GNUNET_IDENTITY_ego_get_public_key (ego, &pub); - GNUNET_asprintf (&gns_caller_id, - "%s", - GNUNET_GNSRECORD_pkey_to_zkey (&pub)); - call = GNUNET_CONVERSATION_call_start (cfg, - ego, - gns_name, - &call_speaker, - &call_mic, - &call_event_handler, - NULL); - return; - } + if (0 == strcmp(name, "phone-ego")) + { + GNUNET_IDENTITY_ego_get_public_key(ego, &pub); + GNUNET_asprintf(&gns_name, + "phone.%s", + GNUNET_GNSRECORD_pkey_to_zkey(&pub)); + phone = + GNUNET_CONVERSATION_phone_create(cfg, ego, &phone_event_handler, NULL); + GNUNET_assert(NULL != phone); + memset(&rd, 0, sizeof(rd)); + GNUNET_CONVERSATION_phone_get_record(phone, &rd); + GNUNET_assert(rd.record_type == GNUNET_GNSRECORD_TYPE_PHONE); + rd.expiration_time = UINT64_MAX; + qe = + GNUNET_NAMESTORE_records_store(ns, + GNUNET_IDENTITY_ego_get_private_key(ego), + "phone" /* GNS label */, + 1, + &rd, + &namestore_put_cont, + NULL); + return; + } + if (0 == strcmp(name, "caller-ego")) + { + GNUNET_IDENTITY_ego_get_public_key(ego, &pub); + GNUNET_asprintf(&gns_caller_id, + "%s", + GNUNET_GNSRECORD_pkey_to_zkey(&pub)); + call = GNUNET_CONVERSATION_call_start(cfg, + ego, + gns_name, + &call_speaker, + &call_mic, + &call_event_handler, + NULL); + return; + } } static void -phone_ego_create_cont (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, - const char *emsg) +phone_ego_create_cont(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, + const char *emsg) { - (void) cls; + (void)cls; op = NULL; - GNUNET_assert (NULL == emsg); + GNUNET_assert(NULL == emsg); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_TESTING_Peer *peer) { - (void) cls; - (void) peer; + (void)cls; + (void)peer; cfg = c; - GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_test, NULL); - id = GNUNET_IDENTITY_connect (cfg, &identity_cb, NULL); - op = GNUNET_IDENTITY_create (id, "phone-ego", &phone_ego_create_cont, NULL); - ns = GNUNET_NAMESTORE_connect (cfg); + GNUNET_SCHEDULER_add_delayed(TIMEOUT, &end_test, NULL); + id = GNUNET_IDENTITY_connect(cfg, &identity_cb, NULL); + op = GNUNET_IDENTITY_create(id, "phone-ego", &phone_ego_create_cont, NULL); + ns = GNUNET_NAMESTORE_connect(cfg); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - (void) argc; - (void) argv; - if (0 != GNUNET_TESTING_peer_run ("test_conversation_api", - "test_conversation.conf", - &run, - NULL)) + (void)argc; + (void)argv; + if (0 != GNUNET_TESTING_peer_run("test_conversation_api", + "test_conversation.conf", + &run, + NULL)) return 1; return ok; } diff --git a/src/conversation/test_conversation_api_reject.c b/src/conversation/test_conversation_api_reject.c index b0a479dc2..2d7a56e3d 100644 --- a/src/conversation/test_conversation_api_reject.c +++ b/src/conversation/test_conversation_api_reject.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/test_conversation_api_reject.c * @brief testcase for conversation_api.c @@ -33,7 +33,7 @@ #include "gnunet_identity_service.h" #include "gnunet_namestore_service.h" -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 25) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 25) static int ok = 1; @@ -57,78 +57,78 @@ static char *gns_caller_id; static int -enable_speaker (void *cls) +enable_speaker(void *cls) { - (void) cls; - GNUNET_break (0); + (void)cls; + GNUNET_break(0); return GNUNET_SYSERR; } static void -disable_speaker (void *cls) +disable_speaker(void *cls) { - (void) cls; - GNUNET_break (0); + (void)cls; + GNUNET_break(0); } static void -play (void *cls, size_t data_size, const void *data) +play(void *cls, size_t data_size, const void *data) { - (void) cls; - (void) data_size; - (void) data; - GNUNET_break (0); + (void)cls; + (void)data_size; + (void)data; + GNUNET_break(0); } static void -destroy_speaker (void *cls) +destroy_speaker(void *cls) { - (void) cls; + (void)cls; } -static struct GNUNET_SPEAKER_Handle call_speaker = {&enable_speaker, - &play, - &disable_speaker, - &destroy_speaker, - "caller"}; +static struct GNUNET_SPEAKER_Handle call_speaker = { &enable_speaker, + &play, + &disable_speaker, + &destroy_speaker, + "caller" }; static int -enable_mic (void *cls, - GNUNET_MICROPHONE_RecordedDataCallback rdc, - void *rdc_cls) +enable_mic(void *cls, + GNUNET_MICROPHONE_RecordedDataCallback rdc, + void *rdc_cls) { - (void) cls; - (void) rdc; - (void) rdc_cls; - GNUNET_break (0); + (void)cls; + (void)rdc; + (void)rdc_cls; + GNUNET_break(0); return GNUNET_SYSERR; } static void -disable_mic (void *cls) +disable_mic(void *cls) { - (void) cls; - GNUNET_break (0); + (void)cls; + GNUNET_break(0); } static void -destroy_mic (void *cls) +destroy_mic(void *cls) { - (void) cls; + (void)cls; } -static struct GNUNET_MICROPHONE_Handle call_mic = {&enable_mic, - &disable_mic, - &destroy_mic, - "caller"}; +static struct GNUNET_MICROPHONE_Handle call_mic = { &enable_mic, + &disable_mic, + &destroy_mic, + "caller" }; /** @@ -137,215 +137,219 @@ static struct GNUNET_MICROPHONE_Handle call_mic = {&enable_mic, * @param cls closure */ static void -end_test (void *cls) +end_test(void *cls) { - (void) cls; - GNUNET_SCHEDULER_shutdown (); + (void)cls; + GNUNET_SCHEDULER_shutdown(); if (NULL != op) - { - GNUNET_IDENTITY_cancel (op); - op = NULL; - } + { + GNUNET_IDENTITY_cancel(op); + op = NULL; + } if (NULL != call) - { - GNUNET_CONVERSATION_call_stop (call); - call = NULL; - } + { + GNUNET_CONVERSATION_call_stop(call); + call = NULL; + } if (NULL != phone) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from PHONE service.\n"); - GNUNET_CONVERSATION_phone_destroy (phone); - phone = NULL; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from PHONE service.\n"); + GNUNET_CONVERSATION_phone_destroy(phone); + phone = NULL; + } if (NULL != id) - { - GNUNET_IDENTITY_disconnect (id); - id = NULL; - } + { + GNUNET_IDENTITY_disconnect(id); + id = NULL; + } if (NULL != qe) - { - GNUNET_NAMESTORE_cancel (qe); - qe = NULL; - } + { + GNUNET_NAMESTORE_cancel(qe); + qe = NULL; + } if (NULL != ns) - { - GNUNET_NAMESTORE_disconnect (ns); - ns = NULL; - } + { + GNUNET_NAMESTORE_disconnect(ns); + ns = NULL; + } } static void -phone_event_handler (void *cls, - enum GNUNET_CONVERSATION_PhoneEventCode code, - struct GNUNET_CONVERSATION_Caller *caller, - const struct GNUNET_CRYPTO_EcdsaPublicKey *caller_id) +phone_event_handler(void *cls, + enum GNUNET_CONVERSATION_PhoneEventCode code, + struct GNUNET_CONVERSATION_Caller *caller, + const struct GNUNET_CRYPTO_EcdsaPublicKey *caller_id) { static enum GNUNET_CONVERSATION_PhoneEventCode expect = GNUNET_CONVERSATION_EC_PHONE_RING; - (void) cls; - (void) caller_id; - GNUNET_break (code == expect); + (void)cls; + (void)caller_id; + GNUNET_break(code == expect); switch (code) - { - case GNUNET_CONVERSATION_EC_PHONE_RING: - GNUNET_CONVERSATION_caller_hang_up (caller); - break; - default: - fprintf (stderr, "Unexpected phone code: %d\n", code); - break; - } + { + case GNUNET_CONVERSATION_EC_PHONE_RING: + GNUNET_CONVERSATION_caller_hang_up(caller); + break; + + default: + fprintf(stderr, "Unexpected phone code: %d\n", code); + break; + } } static void -call_event_handler (void *cls, enum GNUNET_CONVERSATION_CallEventCode code) +call_event_handler(void *cls, enum GNUNET_CONVERSATION_CallEventCode code) { static enum GNUNET_CONVERSATION_CallEventCode expect = GNUNET_CONVERSATION_EC_CALL_RINGING; - (void) cls; - GNUNET_break (code == expect); + (void)cls; + GNUNET_break(code == expect); switch (code) - { - case GNUNET_CONVERSATION_EC_CALL_RINGING: - expect = GNUNET_CONVERSATION_EC_CALL_HUNG_UP; - break; - case GNUNET_CONVERSATION_EC_CALL_HUNG_UP: - call = NULL; - ok = 0; - GNUNET_SCHEDULER_shutdown (); - expect = -1; - break; - case GNUNET_CONVERSATION_EC_CALL_PICKED_UP: - case GNUNET_CONVERSATION_EC_CALL_GNS_FAIL: - case GNUNET_CONVERSATION_EC_CALL_SUSPENDED: - case GNUNET_CONVERSATION_EC_CALL_RESUMED: - fprintf (stderr, "Unexpected call code: %d\n", code); - break; - case GNUNET_CONVERSATION_EC_CALL_ERROR: - fprintf (stderr, "Unexpected call code: %d\n", code); - call = NULL; - break; - } + { + case GNUNET_CONVERSATION_EC_CALL_RINGING: + expect = GNUNET_CONVERSATION_EC_CALL_HUNG_UP; + break; + + case GNUNET_CONVERSATION_EC_CALL_HUNG_UP: + call = NULL; + ok = 0; + GNUNET_SCHEDULER_shutdown(); + expect = -1; + break; + + case GNUNET_CONVERSATION_EC_CALL_PICKED_UP: + case GNUNET_CONVERSATION_EC_CALL_GNS_FAIL: + case GNUNET_CONVERSATION_EC_CALL_SUSPENDED: + case GNUNET_CONVERSATION_EC_CALL_RESUMED: + fprintf(stderr, "Unexpected call code: %d\n", code); + break; + + case GNUNET_CONVERSATION_EC_CALL_ERROR: + fprintf(stderr, "Unexpected call code: %d\n", code); + call = NULL; + break; + } } static void -caller_ego_create_cont (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, - const char *emsg) +caller_ego_create_cont(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, + const char *emsg) { - (void) cls; + (void)cls; op = NULL; - GNUNET_assert (NULL == emsg); + GNUNET_assert(NULL == emsg); } static void -namestore_put_cont (void *cls, int32_t success, const char *emsg) +namestore_put_cont(void *cls, int32_t success, const char *emsg) { - (void) cls; + (void)cls; qe = NULL; - GNUNET_assert (GNUNET_YES == success); - GNUNET_assert (NULL == emsg); - GNUNET_assert (NULL == op); - op = GNUNET_IDENTITY_create (id, "caller-ego", &caller_ego_create_cont, NULL); + GNUNET_assert(GNUNET_YES == success); + GNUNET_assert(NULL == emsg); + GNUNET_assert(NULL == op); + op = GNUNET_IDENTITY_create(id, "caller-ego", &caller_ego_create_cont, NULL); } static void -identity_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +identity_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { struct GNUNET_GNSRECORD_Data rd; struct GNUNET_CRYPTO_EcdsaPublicKey pub; - (void) cls; - (void) ctx; + (void)cls; + (void)ctx; if (NULL == name) return; if (NULL == ego) return; - if (0 == strcmp (name, "phone-ego")) - { - GNUNET_IDENTITY_ego_get_public_key (ego, &pub); - GNUNET_asprintf (&gns_name, - "phone.%s", - GNUNET_GNSRECORD_pkey_to_zkey (&pub)); - phone = - GNUNET_CONVERSATION_phone_create (cfg, ego, &phone_event_handler, NULL); - GNUNET_assert (NULL != phone); - memset (&rd, 0, sizeof (rd)); - GNUNET_CONVERSATION_phone_get_record (phone, &rd); - GNUNET_assert (rd.record_type == GNUNET_GNSRECORD_TYPE_PHONE); - rd.expiration_time = UINT64_MAX; - qe = - GNUNET_NAMESTORE_records_store (ns, - GNUNET_IDENTITY_ego_get_private_key (ego), - "phone" /* GNS label */, - 1, - &rd, - &namestore_put_cont, - NULL); - return; - } - if (0 == strcmp (name, "caller-ego")) - { - GNUNET_IDENTITY_ego_get_public_key (ego, &pub); - GNUNET_asprintf (&gns_caller_id, - "%s", - GNUNET_GNSRECORD_pkey_to_zkey (&pub)); - call = GNUNET_CONVERSATION_call_start (cfg, - ego, - gns_name, - &call_speaker, - &call_mic, - &call_event_handler, - NULL); - return; - } + if (0 == strcmp(name, "phone-ego")) + { + GNUNET_IDENTITY_ego_get_public_key(ego, &pub); + GNUNET_asprintf(&gns_name, + "phone.%s", + GNUNET_GNSRECORD_pkey_to_zkey(&pub)); + phone = + GNUNET_CONVERSATION_phone_create(cfg, ego, &phone_event_handler, NULL); + GNUNET_assert(NULL != phone); + memset(&rd, 0, sizeof(rd)); + GNUNET_CONVERSATION_phone_get_record(phone, &rd); + GNUNET_assert(rd.record_type == GNUNET_GNSRECORD_TYPE_PHONE); + rd.expiration_time = UINT64_MAX; + qe = + GNUNET_NAMESTORE_records_store(ns, + GNUNET_IDENTITY_ego_get_private_key(ego), + "phone" /* GNS label */, + 1, + &rd, + &namestore_put_cont, + NULL); + return; + } + if (0 == strcmp(name, "caller-ego")) + { + GNUNET_IDENTITY_ego_get_public_key(ego, &pub); + GNUNET_asprintf(&gns_caller_id, + "%s", + GNUNET_GNSRECORD_pkey_to_zkey(&pub)); + call = GNUNET_CONVERSATION_call_start(cfg, + ego, + gns_name, + &call_speaker, + &call_mic, + &call_event_handler, + NULL); + return; + } } static void -phone_ego_create_cont (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, - const char *emsg) +phone_ego_create_cont(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, + const char *emsg) { - (void) cls; + (void)cls; op = NULL; - GNUNET_assert (NULL == emsg); + GNUNET_assert(NULL == emsg); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_TESTING_Peer *peer) { - (void) cls; - (void) peer; + (void)cls; + (void)peer; cfg = c; - GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_test, NULL); - id = GNUNET_IDENTITY_connect (cfg, &identity_cb, NULL); - op = GNUNET_IDENTITY_create (id, "phone-ego", &phone_ego_create_cont, NULL); - ns = GNUNET_NAMESTORE_connect (cfg); + GNUNET_SCHEDULER_add_delayed(TIMEOUT, &end_test, NULL); + id = GNUNET_IDENTITY_connect(cfg, &identity_cb, NULL); + op = GNUNET_IDENTITY_create(id, "phone-ego", &phone_ego_create_cont, NULL); + ns = GNUNET_NAMESTORE_connect(cfg); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - (void) argc; - (void) argv; - if (0 != GNUNET_TESTING_peer_run ("test_conversation_api", - "test_conversation.conf", - &run, - NULL)) + (void)argc; + (void)argv; + if (0 != GNUNET_TESTING_peer_run("test_conversation_api", + "test_conversation.conf", + &run, + NULL)) return 1; return ok; } diff --git a/src/conversation/test_conversation_api_twocalls.c b/src/conversation/test_conversation_api_twocalls.c index f3bb87fd2..797563d7a 100644 --- a/src/conversation/test_conversation_api_twocalls.c +++ b/src/conversation/test_conversation_api_twocalls.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file conversation/test_conversation_api_twocalls.c * @brief testcase for conversation_api.c @@ -35,13 +35,13 @@ #include "gnunet_identity_service.h" #include "gnunet_namestore_service.h" -#define FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250) +#define FREQ GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250) -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 25) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 25) -#define LOG(kind, ...) GNUNET_log (kind, __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__) -#define LOG_DEBUG(...) GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__) +#define LOG_DEBUG(...) GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__) static const struct GNUNET_CONFIGURATION_Handle *cfg; @@ -95,7 +95,7 @@ static const char *phone0 = "phone"; #define CALLER2 &caller2 #define PHONE0 &phone0 -#define CLS_STR(caller) (*((char **) caller)) +#define CLS_STR(caller) (*((char **)caller)) /** @@ -108,8 +108,7 @@ static int call1_finished; */ static int call2_finished; -struct MicContext -{ +struct MicContext { GNUNET_MICROPHONE_RecordedDataCallback rdc; void *rdc_cls; @@ -123,198 +122,198 @@ static struct MicContext call2_mic_ctx; static void -phone_send (void *cls) +phone_send(void *cls) { char buf[32]; - (void) cls; - GNUNET_assert (NULL != phone_rdc); - GNUNET_snprintf (buf, sizeof (buf), "phone"); - phone_rdc (phone_rdc_cls, strlen (buf) + 1, buf); - phone_task = GNUNET_SCHEDULER_add_delayed (FREQ, &phone_send, NULL); + (void)cls; + GNUNET_assert(NULL != phone_rdc); + GNUNET_snprintf(buf, sizeof(buf), "phone"); + phone_rdc(phone_rdc_cls, strlen(buf) + 1, buf); + phone_task = GNUNET_SCHEDULER_add_delayed(FREQ, &phone_send, NULL); } static void -call_send (void *cls) +call_send(void *cls) { struct MicContext *mc = cls; char buf[32]; - (void) cls; - GNUNET_assert (NULL != mc->rdc); - GNUNET_snprintf (buf, sizeof (buf), "call"); - mc->rdc (mc->rdc_cls, strlen (buf) + 1, buf); - mc->call_task = GNUNET_SCHEDULER_add_delayed (FREQ, &call_send, mc); + (void)cls; + GNUNET_assert(NULL != mc->rdc); + GNUNET_snprintf(buf, sizeof(buf), "call"); + mc->rdc(mc->rdc_cls, strlen(buf) + 1, buf); + mc->call_task = GNUNET_SCHEDULER_add_delayed(FREQ, &call_send, mc); } static int -enable_speaker (void *cls) +enable_speaker(void *cls) { - const char *origin = CLS_STR (cls); + const char *origin = CLS_STR(cls); - (void) cls; - LOG_DEBUG ("Speaker %s enabled\n", origin); + (void)cls; + LOG_DEBUG("Speaker %s enabled\n", origin); return GNUNET_OK; } static void -disable_speaker (void *cls) +disable_speaker(void *cls) { - const char *origin = CLS_STR (cls); + const char *origin = CLS_STR(cls); - (void) cls; - LOG_DEBUG ("Speaker %s disabled\n", origin); + (void)cls; + LOG_DEBUG("Speaker %s disabled\n", origin); } static void -play (void *cls, size_t data_size, const void *data) +play(void *cls, size_t data_size, const void *data) { static unsigned int phone_i; static unsigned int call_i; - (void) cls; - if (0 == strncmp ("call", data, data_size)) + (void)cls; + if (0 == strncmp("call", data, data_size)) call_i++; - else if (0 == strncmp ("phone", data, data_size)) + else if (0 == strncmp("phone", data, data_size)) phone_i++; else - { - LOG_DEBUG ("Received %u bytes of unexpected data `%.*s'\n", - (unsigned int) data_size, - (int) data_size, - (const char *) data); - } + { + LOG_DEBUG("Received %u bytes of unexpected data `%.*s'\n", + (unsigned int)data_size, + (int)data_size, + (const char *)data); + } if ((20 < call_i) && (20 < phone_i) && (CALLER2 == cls)) - { - /* time to hang up ... */ - GNUNET_CONVERSATION_call_stop (call2); - call2 = NULL; - /* reset counters */ - call_i = 0; - phone_i = 0; - call2_finished = GNUNET_YES; - } + { + /* time to hang up ... */ + GNUNET_CONVERSATION_call_stop(call2); + call2 = NULL; + /* reset counters */ + call_i = 0; + phone_i = 0; + call2_finished = GNUNET_YES; + } if ((20 < call_i) && (20 < phone_i) && (CALLER1 == cls)) - { - /* time to hang up ... */ - GNUNET_CONVERSATION_call_stop (call1); - call1 = NULL; - call_i = 0; - phone_i = 0; - call1_finished = GNUNET_YES; - } + { + /* time to hang up ... */ + GNUNET_CONVERSATION_call_stop(call1); + call1 = NULL; + call_i = 0; + phone_i = 0; + call1_finished = GNUNET_YES; + } } static void -destroy_speaker (void *cls) +destroy_speaker(void *cls) { - const char *origin = CLS_STR (cls); + const char *origin = CLS_STR(cls); - LOG_DEBUG ("Speaker %s destroyed\n", origin); + LOG_DEBUG("Speaker %s destroyed\n", origin); } -static struct GNUNET_SPEAKER_Handle call1_speaker = {&enable_speaker, - &play, - &disable_speaker, - &destroy_speaker, - CALLER1}; +static struct GNUNET_SPEAKER_Handle call1_speaker = { &enable_speaker, + &play, + &disable_speaker, + &destroy_speaker, + CALLER1 }; -static struct GNUNET_SPEAKER_Handle call2_speaker = {&enable_speaker, - &play, - &disable_speaker, - &destroy_speaker, - CALLER2}; +static struct GNUNET_SPEAKER_Handle call2_speaker = { &enable_speaker, + &play, + &disable_speaker, + &destroy_speaker, + CALLER2 }; -static struct GNUNET_SPEAKER_Handle phone_speaker = {&enable_speaker, - &play, - &disable_speaker, - &destroy_speaker, - PHONE0}; +static struct GNUNET_SPEAKER_Handle phone_speaker = { &enable_speaker, + &play, + &disable_speaker, + &destroy_speaker, + PHONE0 }; static int -enable_mic (void *cls, - GNUNET_MICROPHONE_RecordedDataCallback rdc, - void *rdc_cls) +enable_mic(void *cls, + GNUNET_MICROPHONE_RecordedDataCallback rdc, + void *rdc_cls) { - const char *origin = CLS_STR (cls); + const char *origin = CLS_STR(cls); struct MicContext *mc; - LOG_DEBUG ("Mic %s enabled\n", origin); + LOG_DEBUG("Mic %s enabled\n", origin); if (PHONE0 == cls) - { - phone_rdc = rdc; - phone_rdc_cls = rdc_cls; - GNUNET_break (NULL == phone_task); - phone_task = GNUNET_SCHEDULER_add_now (&phone_send, NULL); - return GNUNET_OK; - } + { + phone_rdc = rdc; + phone_rdc_cls = rdc_cls; + GNUNET_break(NULL == phone_task); + phone_task = GNUNET_SCHEDULER_add_now(&phone_send, NULL); + return GNUNET_OK; + } mc = (CALLER1 == cls) ? &call1_mic_ctx : &call2_mic_ctx; mc->rdc = rdc; mc->rdc_cls = rdc_cls; - GNUNET_break (NULL == mc->call_task); - mc->call_task = GNUNET_SCHEDULER_add_now (&call_send, mc); + GNUNET_break(NULL == mc->call_task); + mc->call_task = GNUNET_SCHEDULER_add_now(&call_send, mc); return GNUNET_OK; } static void -disable_mic (void *cls) +disable_mic(void *cls) { - const char *origin = CLS_STR (cls); + const char *origin = CLS_STR(cls); struct MicContext *mc; - LOG_DEBUG ("Mic %s disabled\n", origin); + LOG_DEBUG("Mic %s disabled\n", origin); if (PHONE0 == cls) - { - phone_rdc = NULL; - phone_rdc_cls = NULL; - GNUNET_SCHEDULER_cancel (phone_task); - phone_task = NULL; - return; - } + { + phone_rdc = NULL; + phone_rdc_cls = NULL; + GNUNET_SCHEDULER_cancel(phone_task); + phone_task = NULL; + return; + } mc = (CALLER1 == cls) ? &call1_mic_ctx : &call2_mic_ctx; mc->rdc = NULL; mc->rdc_cls = NULL; - GNUNET_SCHEDULER_cancel (mc->call_task); + GNUNET_SCHEDULER_cancel(mc->call_task); mc->call_task = NULL; } static void -destroy_mic (void *cls) +destroy_mic(void *cls) { - const char *origin = CLS_STR (cls); + const char *origin = CLS_STR(cls); - LOG_DEBUG ("Mic %s destroyed\n", origin); + LOG_DEBUG("Mic %s destroyed\n", origin); } -static struct GNUNET_MICROPHONE_Handle call1_mic = {&enable_mic, - &disable_mic, - &destroy_mic, - CALLER1}; +static struct GNUNET_MICROPHONE_Handle call1_mic = { &enable_mic, + &disable_mic, + &destroy_mic, + CALLER1 }; -static struct GNUNET_MICROPHONE_Handle call2_mic = {&enable_mic, - &disable_mic, - &destroy_mic, - CALLER2}; +static struct GNUNET_MICROPHONE_Handle call2_mic = { &enable_mic, + &disable_mic, + &destroy_mic, + CALLER2 }; -static struct GNUNET_MICROPHONE_Handle phone_mic = {&enable_mic, - &disable_mic, - &destroy_mic, - PHONE0}; +static struct GNUNET_MICROPHONE_Handle phone_mic = { &enable_mic, + &disable_mic, + &destroy_mic, + PHONE0 }; /** @@ -323,12 +322,12 @@ static struct GNUNET_MICROPHONE_Handle phone_mic = {&enable_mic, * @param cls closure */ static void -end_test (void *cls) +end_test(void *cls) { - (void) cls; + (void)cls; timeout_task = NULL; - fprintf (stderr, "Timeout!\n"); - GNUNET_SCHEDULER_shutdown (); + fprintf(stderr, "Timeout!\n"); + GNUNET_SCHEDULER_shutdown(); } @@ -338,286 +337,295 @@ end_test (void *cls) * @param cls closure */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - (void) cls; + (void)cls; if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } if (NULL != op) - { - GNUNET_IDENTITY_cancel (op); - op = NULL; - } + { + GNUNET_IDENTITY_cancel(op); + op = NULL; + } if (NULL != call1) - { - GNUNET_CONVERSATION_call_stop (call1); - call1 = NULL; - } + { + GNUNET_CONVERSATION_call_stop(call1); + call1 = NULL; + } if (NULL != call2) - { - GNUNET_CONVERSATION_call_stop (call2); - call2 = NULL; - } + { + GNUNET_CONVERSATION_call_stop(call2); + call2 = NULL; + } if (NULL != phone) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from PHONE service.\n"); - GNUNET_CONVERSATION_phone_destroy (phone); - phone = NULL; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from PHONE service.\n"); + GNUNET_CONVERSATION_phone_destroy(phone); + phone = NULL; + } if (NULL != id) - { - GNUNET_IDENTITY_disconnect (id); - id = NULL; - } + { + GNUNET_IDENTITY_disconnect(id); + id = NULL; + } if (NULL != qe) - { - GNUNET_NAMESTORE_cancel (qe); - qe = NULL; - } + { + GNUNET_NAMESTORE_cancel(qe); + qe = NULL; + } if (NULL != ns) - { - GNUNET_NAMESTORE_disconnect (ns); - ns = NULL; - } + { + GNUNET_NAMESTORE_disconnect(ns); + ns = NULL; + } } static void -caller_event_handler (void *cls, enum GNUNET_CONVERSATION_CallerEventCode code) +caller_event_handler(void *cls, enum GNUNET_CONVERSATION_CallerEventCode code) { - (void) cls; + (void)cls; switch (code) - { - case GNUNET_CONVERSATION_EC_CALLER_SUSPEND: - case GNUNET_CONVERSATION_EC_CALLER_RESUME: - LOG (GNUNET_ERROR_TYPE_WARNING, "Unexpected caller code: %d\n", code); - break; - } + { + case GNUNET_CONVERSATION_EC_CALLER_SUSPEND: + case GNUNET_CONVERSATION_EC_CALLER_RESUME: + LOG(GNUNET_ERROR_TYPE_WARNING, "Unexpected caller code: %d\n", code); + break; + } } static void -phone_event_handler (void *cls, - enum GNUNET_CONVERSATION_PhoneEventCode code, - struct GNUNET_CONVERSATION_Caller *caller, - const struct GNUNET_CRYPTO_EcdsaPublicKey *caller_id) +phone_event_handler(void *cls, + enum GNUNET_CONVERSATION_PhoneEventCode code, + struct GNUNET_CONVERSATION_Caller *caller, + const struct GNUNET_CRYPTO_EcdsaPublicKey *caller_id) { const char *cid; - (void) cls; - (void) caller_id; + + (void)cls; + (void)caller_id; switch (code) - { - case GNUNET_CONVERSATION_EC_PHONE_RING: - if (NULL == active_caller1) { - active_caller1 = caller; - cid = "caller1"; - GNUNET_CONVERSATION_caller_pick_up (caller, - &caller_event_handler, - (void *) cid, - &phone_speaker, - &phone_mic); + case GNUNET_CONVERSATION_EC_PHONE_RING: + if (NULL == active_caller1) + { + active_caller1 = caller; + cid = "caller1"; + GNUNET_CONVERSATION_caller_pick_up(caller, + &caller_event_handler, + (void *)cid, + &phone_speaker, + &phone_mic); + } + else + { + GNUNET_CONVERSATION_caller_suspend(active_caller1); + active_caller2 = caller; + cid = "caller2"; + GNUNET_CONVERSATION_caller_pick_up(caller, + &caller_event_handler, + (void *)cid, + &phone_speaker, + &phone_mic); + } + break; + + case GNUNET_CONVERSATION_EC_PHONE_HUNG_UP: + if (caller == active_caller2) + { + active_caller2 = NULL; + GNUNET_CONVERSATION_caller_resume(active_caller1, + &phone_speaker, + &phone_mic); + } + else if (caller == active_caller1) + { + active_caller1 = NULL; + GNUNET_break(NULL == active_caller2); + GNUNET_SCHEDULER_shutdown(); + } + break; + + default: + LOG(GNUNET_ERROR_TYPE_WARNING, "Unexpected phone code: %d\n", code); + break; } - else - { - GNUNET_CONVERSATION_caller_suspend (active_caller1); - active_caller2 = caller; - cid = "caller2"; - GNUNET_CONVERSATION_caller_pick_up (caller, - &caller_event_handler, - (void *) cid, - &phone_speaker, - &phone_mic); - } - break; - case GNUNET_CONVERSATION_EC_PHONE_HUNG_UP: - if (caller == active_caller2) - { - active_caller2 = NULL; - GNUNET_CONVERSATION_caller_resume (active_caller1, - &phone_speaker, - &phone_mic); - } - else if (caller == active_caller1) - { - active_caller1 = NULL; - GNUNET_break (NULL == active_caller2); - GNUNET_SCHEDULER_shutdown (); - } - break; - default: - LOG (GNUNET_ERROR_TYPE_WARNING, "Unexpected phone code: %d\n", code); - break; - } } static void -call_event_handler (void *cls, enum GNUNET_CONVERSATION_CallEventCode code) +call_event_handler(void *cls, enum GNUNET_CONVERSATION_CallEventCode code) { const char *cid = cls; switch (code) - { - case GNUNET_CONVERSATION_EC_CALL_RINGING: - break; - case GNUNET_CONVERSATION_EC_CALL_PICKED_UP: - LOG_DEBUG ("Call %s picked\n", cid); - break; - case GNUNET_CONVERSATION_EC_CALL_GNS_FAIL: - LOG_DEBUG ("Call %s GNS lookup failed \n", cid); - break; - case GNUNET_CONVERSATION_EC_CALL_HUNG_UP: - LOG_DEBUG ("Call %s hungup\n", cid); - if (0 == strcmp (cid, "call1")) - call1 = NULL; - else - call2 = NULL; - break; - case GNUNET_CONVERSATION_EC_CALL_SUSPENDED: - LOG_DEBUG ("Call %s suspended\n", cid); - break; - case GNUNET_CONVERSATION_EC_CALL_RESUMED: - LOG_DEBUG ("Call %s resumed\n", cid); - break; - case GNUNET_CONVERSATION_EC_CALL_ERROR: - GNUNET_break (0); - if (0 == strcmp (cid, "call1")) - call1 = NULL; - else - call2 = NULL; - GNUNET_SCHEDULER_shutdown (); - break; - } + { + case GNUNET_CONVERSATION_EC_CALL_RINGING: + break; + + case GNUNET_CONVERSATION_EC_CALL_PICKED_UP: + LOG_DEBUG("Call %s picked\n", cid); + break; + + case GNUNET_CONVERSATION_EC_CALL_GNS_FAIL: + LOG_DEBUG("Call %s GNS lookup failed \n", cid); + break; + + case GNUNET_CONVERSATION_EC_CALL_HUNG_UP: + LOG_DEBUG("Call %s hungup\n", cid); + if (0 == strcmp(cid, "call1")) + call1 = NULL; + else + call2 = NULL; + break; + + case GNUNET_CONVERSATION_EC_CALL_SUSPENDED: + LOG_DEBUG("Call %s suspended\n", cid); + break; + + case GNUNET_CONVERSATION_EC_CALL_RESUMED: + LOG_DEBUG("Call %s resumed\n", cid); + break; + + case GNUNET_CONVERSATION_EC_CALL_ERROR: + GNUNET_break(0); + if (0 == strcmp(cid, "call1")) + call1 = NULL; + else + call2 = NULL; + GNUNET_SCHEDULER_shutdown(); + break; + } } static void -caller_ego_create_cont (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, - const char *emsg) +caller_ego_create_cont(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, + const char *emsg) { - (void) cls; + (void)cls; op = NULL; - GNUNET_assert (NULL == emsg); + GNUNET_assert(NULL == emsg); } static void -namestore_put_cont (void *cls, int32_t success, const char *emsg) +namestore_put_cont(void *cls, int32_t success, const char *emsg) { - (void) cls; + (void)cls; qe = NULL; - GNUNET_assert (GNUNET_YES == success); - GNUNET_assert (NULL == emsg); - GNUNET_assert (NULL == op); - op = GNUNET_IDENTITY_create (id, "caller-ego", &caller_ego_create_cont, NULL); + GNUNET_assert(GNUNET_YES == success); + GNUNET_assert(NULL == emsg); + GNUNET_assert(NULL == op); + op = GNUNET_IDENTITY_create(id, "caller-ego", &caller_ego_create_cont, NULL); } static void -identity_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +identity_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { struct GNUNET_GNSRECORD_Data rd; struct GNUNET_CRYPTO_EcdsaPublicKey pub; - (void) cls; - (void) ctx; + (void)cls; + (void)ctx; if (NULL == name) return; if (NULL == ego) return; - if (0 == strcmp (name, "phone-ego")) - { - GNUNET_IDENTITY_ego_get_public_key (ego, &pub); - GNUNET_asprintf (&gns_name, - "phone.%s", - GNUNET_GNSRECORD_pkey_to_zkey (&pub)); - phone = - GNUNET_CONVERSATION_phone_create (cfg, ego, &phone_event_handler, NULL); - GNUNET_assert (NULL != phone); - memset (&rd, 0, sizeof (rd)); - GNUNET_CONVERSATION_phone_get_record (phone, &rd); - GNUNET_assert (rd.record_type == GNUNET_GNSRECORD_TYPE_PHONE); - rd.expiration_time = UINT64_MAX; - qe = - GNUNET_NAMESTORE_records_store (ns, - GNUNET_IDENTITY_ego_get_private_key (ego), - "phone" /* GNS label */, - 1, - &rd, - &namestore_put_cont, - NULL); - return; - } - if (0 == strcmp (name, "caller-ego")) - { - GNUNET_IDENTITY_ego_get_public_key (ego, &pub); - GNUNET_asprintf (&gns_caller_id, - "%s", - GNUNET_GNSRECORD_pkey_to_zkey (&pub)); - call1 = GNUNET_CONVERSATION_call_start (cfg, - ego, - gns_name, - &call1_speaker, - &call1_mic, - &call_event_handler, - (void *) "call1"); - call2 = GNUNET_CONVERSATION_call_start (cfg, - ego, - gns_name, - &call2_speaker, - &call2_mic, - &call_event_handler, - (void *) "call2"); - return; - } + if (0 == strcmp(name, "phone-ego")) + { + GNUNET_IDENTITY_ego_get_public_key(ego, &pub); + GNUNET_asprintf(&gns_name, + "phone.%s", + GNUNET_GNSRECORD_pkey_to_zkey(&pub)); + phone = + GNUNET_CONVERSATION_phone_create(cfg, ego, &phone_event_handler, NULL); + GNUNET_assert(NULL != phone); + memset(&rd, 0, sizeof(rd)); + GNUNET_CONVERSATION_phone_get_record(phone, &rd); + GNUNET_assert(rd.record_type == GNUNET_GNSRECORD_TYPE_PHONE); + rd.expiration_time = UINT64_MAX; + qe = + GNUNET_NAMESTORE_records_store(ns, + GNUNET_IDENTITY_ego_get_private_key(ego), + "phone" /* GNS label */, + 1, + &rd, + &namestore_put_cont, + NULL); + return; + } + if (0 == strcmp(name, "caller-ego")) + { + GNUNET_IDENTITY_ego_get_public_key(ego, &pub); + GNUNET_asprintf(&gns_caller_id, + "%s", + GNUNET_GNSRECORD_pkey_to_zkey(&pub)); + call1 = GNUNET_CONVERSATION_call_start(cfg, + ego, + gns_name, + &call1_speaker, + &call1_mic, + &call_event_handler, + (void *)"call1"); + call2 = GNUNET_CONVERSATION_call_start(cfg, + ego, + gns_name, + &call2_speaker, + &call2_mic, + &call_event_handler, + (void *)"call2"); + return; + } } static void -phone_ego_create_cont (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, - const char *emsg) +phone_ego_create_cont(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, + const char *emsg) { - (void) cls; + (void)cls; op = NULL; - GNUNET_assert (NULL == emsg); + GNUNET_assert(NULL == emsg); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_TESTING_Peer *peer) { - (void) cls; - (void) peer; + (void)cls; + (void)peer; cfg = c; - timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_test, NULL); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL); - id = GNUNET_IDENTITY_connect (cfg, &identity_cb, NULL); - op = GNUNET_IDENTITY_create (id, "phone-ego", &phone_ego_create_cont, NULL); - ns = GNUNET_NAMESTORE_connect (cfg); + timeout_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, &end_test, NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); + id = GNUNET_IDENTITY_connect(cfg, &identity_cb, NULL); + op = GNUNET_IDENTITY_create(id, "phone-ego", &phone_ego_create_cont, NULL); + ns = GNUNET_NAMESTORE_connect(cfg); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - (void) argc; - (void) argv; - if (0 != GNUNET_TESTING_peer_run ("test_conversation_api_twocalls", - "test_conversation.conf", - &run, - NULL)) + (void)argc; + (void)argv; + if (0 != GNUNET_TESTING_peer_run("test_conversation_api_twocalls", + "test_conversation.conf", + &run, + NULL)) return 1; if (call1_finished && call2_finished) return 0; diff --git a/src/core/core.h b/src/core/core.h index 95d506fbd..44933b4a0 100644 --- a/src/core/core.h +++ b/src/core/core.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/core.h @@ -80,9 +80,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * uint16_t type values specifying which messages this * client is interested in. */ -struct InitMessage -{ - +struct InitMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_CORE_INIT. */ @@ -99,9 +97,7 @@ struct InitMessage * Message transmitted by the gnunet-service-core process * to its clients in response to an INIT message. */ -struct InitReplyMessage -{ - +struct InitReplyMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY */ @@ -123,8 +119,7 @@ struct InitReplyMessage * Message sent by the service to clients to notify them * about a peer connecting. */ -struct ConnectNotifyMessage -{ +struct ConnectNotifyMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT */ @@ -146,8 +141,7 @@ struct ConnectNotifyMessage * Message sent by the service to clients to notify them * about a peer disconnecting. */ -struct DisconnectNotifyMessage -{ +struct DisconnectNotifyMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT. */ @@ -174,8 +168,7 @@ struct DisconnectNotifyMessage * looking at the size field in the header of NotifyTrafficMessage and * checking it with the size field in the message that follows. */ -struct NotifyTrafficMessage -{ +struct NotifyTrafficMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND * or #GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND. @@ -195,8 +188,7 @@ struct NotifyTrafficMessage * Client notifying core about the maximum-priority * message it has in the queue for a particular target. */ -struct SendMessageRequest -{ +struct SendMessageRequest { /** * Header with type #GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST */ @@ -240,8 +232,7 @@ struct SendMessageRequest * transmit a message to the given target * (response to #GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST). */ -struct SendMessageReady -{ +struct SendMessageReady { /** * Header with type #GNUNET_MESSAGE_TYPE_CORE_SEND_READY */ @@ -271,8 +262,7 @@ struct SendMessageReady * Client asking core to transmit a particular message to a particular * target (response to #GNUNET_MESSAGE_TYPE_CORE_SEND_READY). */ -struct SendMessage -{ +struct SendMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_CORE_SEND */ @@ -301,8 +291,7 @@ struct SendMessage * Message sent by the service to monitor clients to notify them * about a peer changing status. */ -struct MonitorNotifyMessage -{ +struct MonitorNotifyMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY */ diff --git a/src/core/core_api.c b/src/core/core_api.c index 223677a5b..010d0eb69 100644 --- a/src/core/core_api.c +++ b/src/core/core_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/core_api.c * @brief core service; this is the main API for encrypted P2P @@ -29,15 +29,13 @@ #include "gnunet_core_service.h" #include "core.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "core-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "core-api", __VA_ARGS__) /** * Information we track for each peer. */ -struct PeerRecord -{ - +struct PeerRecord { /** * Corresponding CORE handle. */ @@ -75,9 +73,7 @@ struct PeerRecord /** * Context for the core service connection. */ -struct GNUNET_CORE_Handle -{ - +struct GNUNET_CORE_Handle { /** * Configuration we're using. */ @@ -153,7 +149,7 @@ struct GNUNET_CORE_Handle * @param h our handle to the core service */ static void -reconnect (struct GNUNET_CORE_Handle *h); +reconnect(struct GNUNET_CORE_Handle *h); /** @@ -163,13 +159,13 @@ reconnect (struct GNUNET_CORE_Handle *h); * @param tc task context */ static void -reconnect_task (void *cls) +reconnect_task(void *cls) { struct GNUNET_CORE_Handle *h = cls; h->reconnect_task = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Connecting to CORE service after delay\n"); - reconnect (h); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Connecting to CORE service after delay\n"); + reconnect(h); } @@ -183,26 +179,26 @@ reconnect_task (void *cls) * @return #GNUNET_YES (continue) */ static int -disconnect_and_free_peer_entry (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +disconnect_and_free_peer_entry(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct GNUNET_CORE_Handle *h = cls; struct PeerRecord *pr = value; - GNUNET_assert (pr->h == h); + GNUNET_assert(pr->h == h); if (NULL != h->disconnects) - h->disconnects (h->cls, &pr->peer, pr->client_cls); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (h->peers, key, pr)); - GNUNET_MQ_destroy (pr->mq); - GNUNET_assert (NULL == pr->mq); + h->disconnects(h->cls, &pr->peer, pr->client_cls); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(h->peers, key, pr)); + GNUNET_MQ_destroy(pr->mq); + GNUNET_assert(NULL == pr->mq); if (NULL != pr->env) - { - GNUNET_MQ_discard (pr->env); - pr->env = NULL; - } - GNUNET_free (pr); + { + GNUNET_MQ_discard(pr->env); + pr->env = NULL; + } + GNUNET_free(pr); return GNUNET_YES; } @@ -214,21 +210,21 @@ disconnect_and_free_peer_entry (void *cls, * @param h our handle */ static void -reconnect_later (struct GNUNET_CORE_Handle *h) +reconnect_later(struct GNUNET_CORE_Handle *h) { - GNUNET_assert (NULL == h->reconnect_task); + GNUNET_assert(NULL == h->reconnect_task); if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } - GNUNET_assert (NULL == h->reconnect_task); + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } + GNUNET_assert(NULL == h->reconnect_task); h->reconnect_task = - GNUNET_SCHEDULER_add_delayed (h->retry_backoff, &reconnect_task, h); - GNUNET_CONTAINER_multipeermap_iterate (h->peers, - &disconnect_and_free_peer_entry, - h); - h->retry_backoff = GNUNET_TIME_STD_BACKOFF (h->retry_backoff); + GNUNET_SCHEDULER_add_delayed(h->retry_backoff, &reconnect_task, h); + GNUNET_CONTAINER_multipeermap_iterate(h->peers, + &disconnect_and_free_peer_entry, + h); + h->retry_backoff = GNUNET_TIME_STD_BACKOFF(h->retry_backoff); } @@ -240,12 +236,12 @@ reconnect_later (struct GNUNET_CORE_Handle *h) * @param error error code */ static void -handle_mq_error (void *cls, enum GNUNET_MQ_Error error) +handle_mq_error(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_CORE_Handle *h = cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, "MQ ERROR: %d\n", error); - reconnect_later (h); + LOG(GNUNET_ERROR_TYPE_DEBUG, "MQ ERROR: %d\n", error); + reconnect_later(h); } @@ -258,9 +254,9 @@ handle_mq_error (void *cls, enum GNUNET_MQ_Error error) * @param impl_state state of the implementation */ static void -core_mq_send_impl (struct GNUNET_MQ_Handle *mq, - const struct GNUNET_MessageHeader *msg, - void *impl_state) +core_mq_send_impl(struct GNUNET_MQ_Handle *mq, + const struct GNUNET_MessageHeader *msg, + void *impl_state) { struct PeerRecord *pr = impl_state; struct GNUNET_CORE_Handle *h = pr->h; @@ -271,44 +267,44 @@ core_mq_send_impl (struct GNUNET_MQ_Handle *mq, enum GNUNET_MQ_PriorityPreferences flags; if (NULL == h->mq) - { - /* We're currently reconnecting, pretend this worked */ - GNUNET_MQ_impl_send_continue (mq); - return; - } - GNUNET_assert (NULL == pr->env); + { + /* We're currently reconnecting, pretend this worked */ + GNUNET_MQ_impl_send_continue(mq); + return; + } + GNUNET_assert(NULL == pr->env); /* extract options from envelope */ - env = GNUNET_MQ_get_current_envelope (mq); - flags = GNUNET_MQ_env_get_options (env); + env = GNUNET_MQ_get_current_envelope(mq); + flags = GNUNET_MQ_env_get_options(env); /* check message size for sanity */ - msize = ntohs (msg->size); - if (msize >= GNUNET_MAX_MESSAGE_SIZE - sizeof (struct SendMessage)) - { - GNUNET_break (0); - GNUNET_MQ_impl_send_continue (mq); - return; - } + msize = ntohs(msg->size); + if (msize >= GNUNET_MAX_MESSAGE_SIZE - sizeof(struct SendMessage)) + { + GNUNET_break(0); + GNUNET_MQ_impl_send_continue(mq); + return; + } /* ask core for transmission */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Asking core for transmission of %u bytes to `%s'\n", - (unsigned int) msize, - GNUNET_i2s (&pr->peer)); - env = GNUNET_MQ_msg (smr, GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST); - smr->priority = htonl ((uint32_t) flags); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Asking core for transmission of %u bytes to `%s'\n", + (unsigned int)msize, + GNUNET_i2s(&pr->peer)); + env = GNUNET_MQ_msg(smr, GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST); + smr->priority = htonl((uint32_t)flags); smr->peer = pr->peer; - smr->size = htons (msize); - smr->smr_id = htons (++pr->smr_id_gen); - GNUNET_MQ_send (h->mq, env); + smr->size = htons(msize); + smr->smr_id = htons(++pr->smr_id_gen); + GNUNET_MQ_send(h->mq, env); /* prepare message with actual transmission data */ - pr->env = GNUNET_MQ_msg_nested_mh (sm, GNUNET_MESSAGE_TYPE_CORE_SEND, msg); - sm->priority = htonl ((uint32_t) flags); + pr->env = GNUNET_MQ_msg_nested_mh(sm, GNUNET_MESSAGE_TYPE_CORE_SEND, msg); + sm->priority = htonl((uint32_t)flags); sm->peer = pr->peer; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Calling get_message with buffer of %u bytes\n", - (unsigned int) msize); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Calling get_message with buffer of %u bytes\n", + (unsigned int)msize); } @@ -320,11 +316,11 @@ core_mq_send_impl (struct GNUNET_MQ_Handle *mq, * @param impl_state state of the implementation */ static void -core_mq_destroy_impl (struct GNUNET_MQ_Handle *mq, void *impl_state) +core_mq_destroy_impl(struct GNUNET_MQ_Handle *mq, void *impl_state) { struct PeerRecord *pr = impl_state; - GNUNET_assert (mq == pr->mq); + GNUNET_assert(mq == pr->mq); pr->mq = NULL; } @@ -337,13 +333,13 @@ core_mq_destroy_impl (struct GNUNET_MQ_Handle *mq, void *impl_state) * @param impl_state state specific to the implementation */ static void -core_mq_cancel_impl (struct GNUNET_MQ_Handle *mq, void *impl_state) +core_mq_cancel_impl(struct GNUNET_MQ_Handle *mq, void *impl_state) { struct PeerRecord *pr = impl_state; - (void) mq; - GNUNET_assert (NULL != pr->env); - GNUNET_MQ_discard (pr->env); + (void)mq; + GNUNET_assert(NULL != pr->env); + GNUNET_MQ_discard(pr->env); pr->env = NULL; } @@ -357,12 +353,12 @@ core_mq_cancel_impl (struct GNUNET_MQ_Handle *mq, void *impl_state) * @param error error code */ static void -core_mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +core_mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { /* struct PeerRecord *pr = cls; */ - (void) cls; - (void) error; - GNUNET_break_op (0); + (void)cls; + (void)error; + GNUNET_break_op(0); } @@ -375,32 +371,32 @@ core_mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @param peer the peer that is connecting to us */ static void -connect_peer (struct GNUNET_CORE_Handle *h, - const struct GNUNET_PeerIdentity *peer) +connect_peer(struct GNUNET_CORE_Handle *h, + const struct GNUNET_PeerIdentity *peer) { struct PeerRecord *pr; - pr = GNUNET_new (struct PeerRecord); + pr = GNUNET_new(struct PeerRecord); pr->peer = *peer; pr->h = h; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_put ( - h->peers, - &pr->peer, - pr, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - pr->mq = GNUNET_MQ_queue_for_callbacks (&core_mq_send_impl, - &core_mq_destroy_impl, - &core_mq_cancel_impl, - pr, - h->handlers, - &core_mq_error_handler, - pr); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_put( + h->peers, + &pr->peer, + pr, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + pr->mq = GNUNET_MQ_queue_for_callbacks(&core_mq_send_impl, + &core_mq_destroy_impl, + &core_mq_cancel_impl, + pr, + h->handlers, + &core_mq_error_handler, + pr); if (NULL != h->connects) - { - pr->client_cls = h->connects (h->cls, &pr->peer, pr->mq); - GNUNET_MQ_set_handlers_closure (pr->mq, pr->client_cls); - } + { + pr->client_cls = h->connects(h->cls, &pr->peer, pr->mq); + GNUNET_MQ_set_handlers_closure(pr->mq, pr->client_cls); + } } @@ -413,42 +409,42 @@ connect_peer (struct GNUNET_CORE_Handle *h, * @param m the init reply */ static void -handle_init_reply (void *cls, const struct InitReplyMessage *m) +handle_init_reply(void *cls, const struct InitReplyMessage *m) { struct GNUNET_CORE_Handle *h = cls; GNUNET_CORE_StartupCallback init; - GNUNET_break (0 == ntohl (m->reserved)); + GNUNET_break(0 == ntohl(m->reserved)); h->retry_backoff = GNUNET_TIME_UNIT_MILLISECONDS; if (NULL != (init = h->init)) - { - /* mark so we don't call init on reconnect */ - h->init = NULL; - h->me = m->my_identity; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Connected to core service of peer `%s'.\n", - GNUNET_i2s (&h->me)); - h->have_init = GNUNET_YES; - init (h->cls, &h->me); - } - else - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Successfully reconnected to core service.\n"); - if (GNUNET_NO == h->have_init) { + /* mark so we don't call init on reconnect */ + h->init = NULL; h->me = m->my_identity; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Connected to core service of peer `%s'.\n", + GNUNET_i2s(&h->me)); h->have_init = GNUNET_YES; + init(h->cls, &h->me); } - else + else { - GNUNET_break (0 == memcmp (&h->me, - &m->my_identity, - sizeof (struct GNUNET_PeerIdentity))); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Successfully reconnected to core service.\n"); + if (GNUNET_NO == h->have_init) + { + h->me = m->my_identity; + h->have_init = GNUNET_YES; + } + else + { + GNUNET_break(0 == memcmp(&h->me, + &m->my_identity, + sizeof(struct GNUNET_PeerIdentity))); + } } - } /* fake 'connect to self' */ - connect_peer (h, &h->me); + connect_peer(h, &h->me); } @@ -460,28 +456,28 @@ handle_init_reply (void *cls, const struct InitReplyMessage *m) * @param cnm the connect message */ static void -handle_connect_notify (void *cls, const struct ConnectNotifyMessage *cnm) +handle_connect_notify(void *cls, const struct ConnectNotifyMessage *cnm) { struct GNUNET_CORE_Handle *h = cls; struct PeerRecord *pr; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received notification about connection from `%s'.\n", - GNUNET_i2s (&cnm->peer)); - if (0 == memcmp (&h->me, &cnm->peer, sizeof (struct GNUNET_PeerIdentity))) - { - /* connect to self!? */ - GNUNET_break (0); - return; - } - pr = GNUNET_CONTAINER_multipeermap_get (h->peers, &cnm->peer); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received notification about connection from `%s'.\n", + GNUNET_i2s(&cnm->peer)); + if (0 == memcmp(&h->me, &cnm->peer, sizeof(struct GNUNET_PeerIdentity))) + { + /* connect to self!? */ + GNUNET_break(0); + return; + } + pr = GNUNET_CONTAINER_multipeermap_get(h->peers, &cnm->peer); if (NULL != pr) - { - GNUNET_break (0); - reconnect_later (h); - return; - } - connect_peer (h, &cnm->peer); + { + GNUNET_break(0); + reconnect_later(h); + return; + } + connect_peer(h, &cnm->peer); } @@ -493,29 +489,29 @@ handle_connect_notify (void *cls, const struct ConnectNotifyMessage *cnm) * @param dnm message about the disconnect event */ static void -handle_disconnect_notify (void *cls, const struct DisconnectNotifyMessage *dnm) +handle_disconnect_notify(void *cls, const struct DisconnectNotifyMessage *dnm) { struct GNUNET_CORE_Handle *h = cls; struct PeerRecord *pr; - if (0 == memcmp (&h->me, &dnm->peer, sizeof (struct GNUNET_PeerIdentity))) - { - /* disconnect from self!? */ - GNUNET_break (0); - return; - } - GNUNET_break (0 == ntohl (dnm->reserved)); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received notification about disconnect from `%s'.\n", - GNUNET_i2s (&dnm->peer)); - pr = GNUNET_CONTAINER_multipeermap_get (h->peers, &dnm->peer); + if (0 == memcmp(&h->me, &dnm->peer, sizeof(struct GNUNET_PeerIdentity))) + { + /* disconnect from self!? */ + GNUNET_break(0); + return; + } + GNUNET_break(0 == ntohl(dnm->reserved)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received notification about disconnect from `%s'.\n", + GNUNET_i2s(&dnm->peer)); + pr = GNUNET_CONTAINER_multipeermap_get(h->peers, &dnm->peer); if (NULL == pr) - { - GNUNET_break (0); - reconnect_later (h); - return; - } - disconnect_and_free_peer_entry (h, &pr->peer, pr); + { + GNUNET_break(0); + reconnect_later(h); + return; + } + disconnect_and_free_peer_entry(h, &pr->peer, pr); } @@ -527,24 +523,24 @@ handle_disconnect_notify (void *cls, const struct DisconnectNotifyMessage *dnm) * @return #GNUNET_OK if the message is well-formed */ static int -check_notify_inbound (void *cls, const struct NotifyTrafficMessage *ntm) +check_notify_inbound(void *cls, const struct NotifyTrafficMessage *ntm) { uint16_t msize; const struct GNUNET_MessageHeader *em; - (void) cls; - msize = ntohs (ntm->header.size) - sizeof (struct NotifyTrafficMessage); - if (msize < sizeof (struct GNUNET_MessageHeader)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - em = (const struct GNUNET_MessageHeader *) &ntm[1]; - if (msize != ntohs (em->size)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + (void)cls; + msize = ntohs(ntm->header.size) - sizeof(struct NotifyTrafficMessage); + if (msize < sizeof(struct GNUNET_MessageHeader)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + em = (const struct GNUNET_MessageHeader *)&ntm[1]; + if (msize != ntohs(em->size)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -557,24 +553,24 @@ check_notify_inbound (void *cls, const struct NotifyTrafficMessage *ntm) * @param ntm the message we got from CORE. */ static void -handle_notify_inbound (void *cls, const struct NotifyTrafficMessage *ntm) +handle_notify_inbound(void *cls, const struct NotifyTrafficMessage *ntm) { struct GNUNET_CORE_Handle *h = cls; const struct GNUNET_MessageHeader *em; struct PeerRecord *pr; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received inbound message from `%s'.\n", - GNUNET_i2s (&ntm->peer)); - em = (const struct GNUNET_MessageHeader *) &ntm[1]; - pr = GNUNET_CONTAINER_multipeermap_get (h->peers, &ntm->peer); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received inbound message from `%s'.\n", + GNUNET_i2s(&ntm->peer)); + em = (const struct GNUNET_MessageHeader *)&ntm[1]; + pr = GNUNET_CONTAINER_multipeermap_get(h->peers, &ntm->peer); if (NULL == pr) - { - GNUNET_break (0); - reconnect_later (h); - return; - } - GNUNET_MQ_inject_message (pr->mq, em); + { + GNUNET_break(0); + reconnect_later(h); + return; + } + GNUNET_MQ_inject_message(pr->mq, em); } @@ -587,38 +583,38 @@ handle_notify_inbound (void *cls, const struct NotifyTrafficMessage *ntm) * @param smr the message we got */ static void -handle_send_ready (void *cls, const struct SendMessageReady *smr) +handle_send_ready(void *cls, const struct SendMessageReady *smr) { struct GNUNET_CORE_Handle *h = cls; struct PeerRecord *pr; - pr = GNUNET_CONTAINER_multipeermap_get (h->peers, &smr->peer); + pr = GNUNET_CONTAINER_multipeermap_get(h->peers, &smr->peer); if (NULL == pr) - { - GNUNET_break (0); - reconnect_later (h); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received notification about transmission readiness to `%s'.\n", - GNUNET_i2s (&smr->peer)); + { + GNUNET_break(0); + reconnect_later(h); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received notification about transmission readiness to `%s'.\n", + GNUNET_i2s(&smr->peer)); if (NULL == pr->env) - { - /* request must have been cancelled between the original request - * and the response from CORE, ignore CORE's readiness */ - return; - } - if (ntohs (smr->smr_id) != pr->smr_id_gen) - { - /* READY message is for expired or cancelled message, - * ignore! (we should have already sent another request) */ - return; - } + { + /* request must have been cancelled between the original request + * and the response from CORE, ignore CORE's readiness */ + return; + } + if (ntohs(smr->smr_id) != pr->smr_id_gen) + { + /* READY message is for expired or cancelled message, + * ignore! (we should have already sent another request) */ + return; + } /* ok, all good, send message out! */ - GNUNET_MQ_send (h->mq, pr->env); + GNUNET_MQ_send(h->mq, pr->env); pr->env = NULL; - GNUNET_MQ_impl_send_continue (pr->mq); + GNUNET_MQ_impl_send_continue(pr->mq); } @@ -629,50 +625,50 @@ handle_send_ready (void *cls, const struct SendMessageReady *smr) * @param h our handle to the core service */ static void -reconnect (struct GNUNET_CORE_Handle *h) +reconnect(struct GNUNET_CORE_Handle *h) { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_fixed_size (init_reply, - GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY, - struct InitReplyMessage, - h), - GNUNET_MQ_hd_fixed_size (connect_notify, - GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT, - struct ConnectNotifyMessage, - h), - GNUNET_MQ_hd_fixed_size (disconnect_notify, - GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT, - struct DisconnectNotifyMessage, - h), - GNUNET_MQ_hd_var_size (notify_inbound, - GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND, - struct NotifyTrafficMessage, + { GNUNET_MQ_hd_fixed_size(init_reply, + GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY, + struct InitReplyMessage, h), - GNUNET_MQ_hd_fixed_size (send_ready, - GNUNET_MESSAGE_TYPE_CORE_SEND_READY, - struct SendMessageReady, - h), - GNUNET_MQ_handler_end ()}; + GNUNET_MQ_hd_fixed_size(connect_notify, + GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT, + struct ConnectNotifyMessage, + h), + GNUNET_MQ_hd_fixed_size(disconnect_notify, + GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT, + struct DisconnectNotifyMessage, + h), + GNUNET_MQ_hd_var_size(notify_inbound, + GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND, + struct NotifyTrafficMessage, + h), + GNUNET_MQ_hd_fixed_size(send_ready, + GNUNET_MESSAGE_TYPE_CORE_SEND_READY, + struct SendMessageReady, + h), + GNUNET_MQ_handler_end() }; struct InitMessage *init; struct GNUNET_MQ_Envelope *env; uint16_t *ts; - GNUNET_assert (NULL == h->mq); - h->mq = GNUNET_CLIENT_connect (h->cfg, "core", handlers, &handle_mq_error, h); + GNUNET_assert(NULL == h->mq); + h->mq = GNUNET_CLIENT_connect(h->cfg, "core", handlers, &handle_mq_error, h); if (NULL == h->mq) - { - reconnect_later (h); - return; - } - env = GNUNET_MQ_msg_extra (init, - sizeof (uint16_t) * h->hcnt, - GNUNET_MESSAGE_TYPE_CORE_INIT); - LOG (GNUNET_ERROR_TYPE_INFO, "(Re)connecting to CORE service\n"); - init->options = htonl (0); - ts = (uint16_t *) &init[1]; + { + reconnect_later(h); + return; + } + env = GNUNET_MQ_msg_extra(init, + sizeof(uint16_t) * h->hcnt, + GNUNET_MESSAGE_TYPE_CORE_INIT); + LOG(GNUNET_ERROR_TYPE_INFO, "(Re)connecting to CORE service\n"); + init->options = htonl(0); + ts = (uint16_t *)&init[1]; for (unsigned int hpos = 0; hpos < h->hcnt; hpos++) - ts[hpos] = htons (h->handlers[hpos].type); - GNUNET_MQ_send (h->mq, env); + ts[hpos] = htons(h->handlers[hpos].type); + GNUNET_MQ_send(h->mq, env); } @@ -691,34 +687,34 @@ reconnect (struct GNUNET_CORE_Handle *h) * NULL on error (in this case, init is never called) */ struct GNUNET_CORE_Handle * -GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - void *cls, - GNUNET_CORE_StartupCallback init, - GNUNET_CORE_ConnectEventHandler connects, - GNUNET_CORE_DisconnectEventHandler disconnects, - const struct GNUNET_MQ_MessageHandler *handlers) +GNUNET_CORE_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + void *cls, + GNUNET_CORE_StartupCallback init, + GNUNET_CORE_ConnectEventHandler connects, + GNUNET_CORE_DisconnectEventHandler disconnects, + const struct GNUNET_MQ_MessageHandler *handlers) { struct GNUNET_CORE_Handle *h; - h = GNUNET_new (struct GNUNET_CORE_Handle); + h = GNUNET_new(struct GNUNET_CORE_Handle); h->cfg = cfg; h->cls = cls; h->init = init; h->connects = connects; h->disconnects = disconnects; - h->peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO); - h->handlers = GNUNET_MQ_copy_handlers (handlers); - h->hcnt = GNUNET_MQ_count_handlers (handlers); - GNUNET_assert (h->hcnt < - (GNUNET_MAX_MESSAGE_SIZE - sizeof (struct InitMessage)) / - sizeof (uint16_t)); - LOG (GNUNET_ERROR_TYPE_DEBUG, "Connecting to CORE service\n"); - reconnect (h); + h->peers = GNUNET_CONTAINER_multipeermap_create(128, GNUNET_NO); + h->handlers = GNUNET_MQ_copy_handlers(handlers); + h->hcnt = GNUNET_MQ_count_handlers(handlers); + GNUNET_assert(h->hcnt < + (GNUNET_MAX_MESSAGE_SIZE - sizeof(struct InitMessage)) / + sizeof(uint16_t)); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Connecting to CORE service\n"); + reconnect(h); if (NULL == h->mq) - { - GNUNET_CORE_disconnect (h); - return NULL; - } + { + GNUNET_CORE_disconnect(h); + return NULL; + } return h; } @@ -729,26 +725,26 @@ GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param handle connection to core to disconnect */ void -GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle) +GNUNET_CORE_disconnect(struct GNUNET_CORE_Handle *handle) { - LOG (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from CORE service\n"); - GNUNET_CONTAINER_multipeermap_iterate (handle->peers, - &disconnect_and_free_peer_entry, - handle); - GNUNET_CONTAINER_multipeermap_destroy (handle->peers); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from CORE service\n"); + GNUNET_CONTAINER_multipeermap_iterate(handle->peers, + &disconnect_and_free_peer_entry, + handle); + GNUNET_CONTAINER_multipeermap_destroy(handle->peers); handle->peers = NULL; if (NULL != handle->reconnect_task) - { - GNUNET_SCHEDULER_cancel (handle->reconnect_task); - handle->reconnect_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(handle->reconnect_task); + handle->reconnect_task = NULL; + } if (NULL != handle->mq) - { - GNUNET_MQ_destroy (handle->mq); - handle->mq = NULL; - } - GNUNET_free_non_null (handle->handlers); - GNUNET_free (handle); + { + GNUNET_MQ_destroy(handle->mq); + handle->mq = NULL; + } + GNUNET_free_non_null(handle->handlers); + GNUNET_free(handle); } @@ -760,12 +756,12 @@ GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle) * @return NULL if peer is not connected */ struct GNUNET_MQ_Handle * -GNUNET_CORE_get_mq (const struct GNUNET_CORE_Handle *h, - const struct GNUNET_PeerIdentity *pid) +GNUNET_CORE_get_mq(const struct GNUNET_CORE_Handle *h, + const struct GNUNET_PeerIdentity *pid) { struct PeerRecord *pr; - pr = GNUNET_CONTAINER_multipeermap_get (h->peers, pid); + pr = GNUNET_CONTAINER_multipeermap_get(h->peers, pid); if (NULL == pr) return NULL; return pr->mq; diff --git a/src/core/core_api_monitor_peers.c b/src/core/core_api_monitor_peers.c index 165f741d2..90f4a3d15 100644 --- a/src/core/core_api_monitor_peers.c +++ b/src/core/core_api_monitor_peers.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/core_api_monitor_peers.c @@ -32,9 +32,7 @@ /** * Handle to a CORE monitoring operation. */ -struct GNUNET_CORE_MonitorHandle -{ - +struct GNUNET_CORE_MonitorHandle { /** * Our configuration. */ @@ -64,7 +62,7 @@ struct GNUNET_CORE_MonitorHandle * @param mh monitoring session to reconnect to CORE */ static void -reconnect (struct GNUNET_CORE_MonitorHandle *mh); +reconnect(struct GNUNET_CORE_MonitorHandle *mh); /** @@ -76,12 +74,12 @@ reconnect (struct GNUNET_CORE_MonitorHandle *mh); * @param error error code */ static void -handle_mq_error (void *cls, enum GNUNET_MQ_Error error) +handle_mq_error(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_CORE_MonitorHandle *mh = cls; - (void) error; - reconnect (mh); + (void)error; + reconnect(mh); } @@ -92,14 +90,14 @@ handle_mq_error (void *cls, enum GNUNET_MQ_Error error) * @param mon_message monitor message */ static void -handle_receive_info (void *cls, const struct MonitorNotifyMessage *mon_message) +handle_receive_info(void *cls, const struct MonitorNotifyMessage *mon_message) { struct GNUNET_CORE_MonitorHandle *mh = cls; - mh->peer_cb (mh->peer_cb_cls, - &mon_message->peer, - (enum GNUNET_CORE_KxState) ntohl (mon_message->state), - GNUNET_TIME_absolute_ntoh (mon_message->timeout)); + mh->peer_cb(mh->peer_cb_cls, + &mon_message->peer, + (enum GNUNET_CORE_KxState)ntohl(mon_message->state), + GNUNET_TIME_absolute_ntoh(mon_message->timeout)); } @@ -110,32 +108,32 @@ handle_receive_info (void *cls, const struct MonitorNotifyMessage *mon_message) * @param mh monitoring session to reconnect to CORE */ static void -reconnect (struct GNUNET_CORE_MonitorHandle *mh) +reconnect(struct GNUNET_CORE_MonitorHandle *mh) { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_fixed_size (receive_info, - GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY, - struct MonitorNotifyMessage, - mh), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_fixed_size(receive_info, + GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY, + struct MonitorNotifyMessage, + mh), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; if (NULL != mh->mq) - GNUNET_MQ_destroy (mh->mq); + GNUNET_MQ_destroy(mh->mq); /* FIXME: use backoff? */ mh->mq = - GNUNET_CLIENT_connect (mh->cfg, "core", handlers, &handle_mq_error, mh); + GNUNET_CLIENT_connect(mh->cfg, "core", handlers, &handle_mq_error, mh); if (NULL == mh->mq) return; /* notify callback about reconnect */ if (NULL != mh->peer_cb) - mh->peer_cb (mh->peer_cb_cls, - NULL, - GNUNET_CORE_KX_CORE_DISCONNECT, - GNUNET_TIME_UNIT_FOREVER_ABS); - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CORE_MONITOR_PEERS); - GNUNET_MQ_send (mh->mq, env); + mh->peer_cb(mh->peer_cb_cls, + NULL, + GNUNET_CORE_KX_CORE_DISCONNECT, + GNUNET_TIME_UNIT_FOREVER_ABS); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_CORE_MONITOR_PEERS); + GNUNET_MQ_send(mh->mq, env); } @@ -156,23 +154,23 @@ reconnect (struct GNUNET_CORE_MonitorHandle *mh) * @return NULL on error */ struct GNUNET_CORE_MonitorHandle * -GNUNET_CORE_monitor_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_CORE_MonitorCallback peer_cb, - void *peer_cb_cls) +GNUNET_CORE_monitor_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_CORE_MonitorCallback peer_cb, + void *peer_cb_cls) { struct GNUNET_CORE_MonitorHandle *mh; - GNUNET_assert (NULL != peer_cb); - mh = GNUNET_new (struct GNUNET_CORE_MonitorHandle); + GNUNET_assert(NULL != peer_cb); + mh = GNUNET_new(struct GNUNET_CORE_MonitorHandle); mh->cfg = cfg; - reconnect (mh); + reconnect(mh); mh->peer_cb = peer_cb; mh->peer_cb_cls = peer_cb_cls; if (NULL == mh->mq) - { - GNUNET_free (mh); - return NULL; - } + { + GNUNET_free(mh); + return NULL; + } return mh; } @@ -183,14 +181,14 @@ GNUNET_CORE_monitor_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param mh monitor to stop */ void -GNUNET_CORE_monitor_stop (struct GNUNET_CORE_MonitorHandle *mh) +GNUNET_CORE_monitor_stop(struct GNUNET_CORE_MonitorHandle *mh) { if (NULL != mh->mq) - { - GNUNET_MQ_destroy (mh->mq); - mh->mq = NULL; - } - GNUNET_free (mh); + { + GNUNET_MQ_destroy(mh->mq); + mh->mq = NULL; + } + GNUNET_free(mh); } diff --git a/src/core/gnunet-core.c b/src/core/gnunet-core.c index aeb3ba61f..2ffafc075 100644 --- a/src/core/gnunet-core.c +++ b/src/core/gnunet-core.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/gnunet-core.c @@ -46,14 +46,14 @@ static struct GNUNET_CORE_MonitorHandle *mh; * @param cls NULL */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - (void) cls; + (void)cls; if (NULL != mh) - { - GNUNET_CORE_monitor_stop (mh); - mh = NULL; - } + { + GNUNET_CORE_monitor_stop(mh); + mh = NULL; + } } @@ -67,64 +67,72 @@ shutdown_task (void *cls) * @param timeout timeout for the new state */ static void -monitor_cb (void *cls, - const struct GNUNET_PeerIdentity *peer, - enum GNUNET_CORE_KxState state, - struct GNUNET_TIME_Absolute timeout) +monitor_cb(void *cls, + const struct GNUNET_PeerIdentity *peer, + enum GNUNET_CORE_KxState state, + struct GNUNET_TIME_Absolute timeout) { - struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get (); + struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get(); const char *now_str; const char *state_str; - (void) cls; + (void)cls; if (((NULL == peer) || (GNUNET_CORE_KX_ITERATION_FINISHED == state)) && (GNUNET_NO == monitor_connections)) - { - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_SCHEDULER_shutdown(); + return; + } switch (state) - { - case GNUNET_CORE_KX_STATE_DOWN: - /* should never happen, as we immediately send the key */ - state_str = _ ("fresh connection"); - break; - case GNUNET_CORE_KX_STATE_KEY_SENT: - state_str = _ ("key sent"); - break; - case GNUNET_CORE_KX_STATE_KEY_RECEIVED: - state_str = _ ("key received"); - break; - case GNUNET_CORE_KX_STATE_UP: - state_str = _ ("connection established"); - break; - case GNUNET_CORE_KX_STATE_REKEY_SENT: - state_str = _ ("rekeying"); - break; - case GNUNET_CORE_KX_PEER_DISCONNECT: - state_str = _ ("disconnected"); - break; - case GNUNET_CORE_KX_ITERATION_FINISHED: - return; - case GNUNET_CORE_KX_CORE_DISCONNECT: - fprintf (stderr, - "%s\n", - _ ("Connection to CORE service lost (reconnecting)")); - return; - default: - state_str = _ ("unknown state"); - break; - } - now_str = GNUNET_STRINGS_absolute_time_to_string (now); - fprintf (stdout, - _ ("%24s: %-30s %4s (timeout in %6s)\n"), - now_str, - state_str, - GNUNET_i2s (peer), - GNUNET_STRINGS_relative_time_to_string ( - GNUNET_TIME_absolute_get_remaining (timeout), - GNUNET_YES)); + { + case GNUNET_CORE_KX_STATE_DOWN: + /* should never happen, as we immediately send the key */ + state_str = _("fresh connection"); + break; + + case GNUNET_CORE_KX_STATE_KEY_SENT: + state_str = _("key sent"); + break; + + case GNUNET_CORE_KX_STATE_KEY_RECEIVED: + state_str = _("key received"); + break; + + case GNUNET_CORE_KX_STATE_UP: + state_str = _("connection established"); + break; + + case GNUNET_CORE_KX_STATE_REKEY_SENT: + state_str = _("rekeying"); + break; + + case GNUNET_CORE_KX_PEER_DISCONNECT: + state_str = _("disconnected"); + break; + + case GNUNET_CORE_KX_ITERATION_FINISHED: + return; + + case GNUNET_CORE_KX_CORE_DISCONNECT: + fprintf(stderr, + "%s\n", + _("Connection to CORE service lost (reconnecting)")); + return; + + default: + state_str = _("unknown state"); + break; + } + now_str = GNUNET_STRINGS_absolute_time_to_string(now); + fprintf(stdout, + _("%24s: %-30s %4s (timeout in %6s)\n"), + now_str, + state_str, + GNUNET_i2s(peer), + GNUNET_STRINGS_relative_time_to_string( + GNUNET_TIME_absolute_get_remaining(timeout), + GNUNET_YES)); } @@ -137,25 +145,25 @@ monitor_cb (void *cls, * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - (void) cls; - (void) cfgfile; + (void)cls; + (void)cfgfile; if (NULL != args[0]) - { - fprintf (stderr, _ ("Invalid command line argument `%s'\n"), args[0]); - return; - } - mh = GNUNET_CORE_monitor_start (cfg, &monitor_cb, NULL); + { + fprintf(stderr, _("Invalid command line argument `%s'\n"), args[0]); + return; + } + mh = GNUNET_CORE_monitor_start(cfg, &monitor_cb, NULL); if (NULL == mh) - { - fprintf (stderr, "%s", _ ("Failed to connect to CORE service!\n")); - return; - } - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + { + fprintf(stderr, "%s", _("Failed to connect to CORE service!\n")); + return; + } + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); } @@ -167,30 +175,30 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { int res; struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_flag ( - 'm', - "monitor", - gettext_noop ( - "provide information about all current connections (continuously)"), - &monitor_connections), - GNUNET_GETOPT_OPTION_END}; - - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + { GNUNET_GETOPT_option_flag( + 'm', + "monitor", + gettext_noop( + "provide information about all current connections (continuously)"), + &monitor_connections), + GNUNET_GETOPT_OPTION_END }; + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; - res = GNUNET_PROGRAM_run (argc, - argv, - "gnunet-core", - gettext_noop ( - "Print information about connected peers."), - options, - &run, - NULL); - - GNUNET_free ((void *) argv); + res = GNUNET_PROGRAM_run(argc, + argv, + "gnunet-core", + gettext_noop( + "Print information about connected peers."), + options, + &run, + NULL); + + GNUNET_free((void *)argv); if (GNUNET_OK == res) return 0; return 1; diff --git a/src/core/gnunet-service-core.c b/src/core/gnunet-service-core.c index 740707ce1..505798683 100644 --- a/src/core/gnunet-service-core.c +++ b/src/core/gnunet-service-core.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/gnunet-service-core.c @@ -50,8 +50,7 @@ /** * Data structure for each client connected to the CORE service. */ -struct GSC_Client -{ +struct GSC_Client { /** * Clients are kept in a linked list. */ @@ -149,11 +148,11 @@ static struct GSC_Client *client_tail; * @return #GNUNET_YES if @a c is interested, #GNUNET_NO if not. */ static int -type_match (uint16_t type, struct GSC_Client *c) +type_match(uint16_t type, struct GSC_Client *c) { if ((0 == c->tcnt) && (0 != c->options)) return GNUNET_YES; /* peer without handlers and inbound/outbond - callbacks matches ALL */ + callbacks matches ALL */ if (NULL == c->types) return GNUNET_NO; for (unsigned int i = 0; i < c->tcnt; i++) @@ -171,7 +170,7 @@ type_match (uint16_t type, struct GSC_Client *c) * @return #GNUNET_OK if @a im is well-formed */ static int -check_client_init (void *cls, const struct InitMessage *im) +check_client_init(void *cls, const struct InitMessage *im) { return GNUNET_OK; } @@ -184,7 +183,7 @@ check_client_init (void *cls, const struct InitMessage *im) * @param im the `struct InitMessage` */ static void -handle_client_init (void *cls, const struct InitMessage *im) +handle_client_init(void *cls, const struct InitMessage *im) { struct GSC_Client *c = cls; struct GNUNET_MQ_Envelope *env; @@ -193,33 +192,33 @@ handle_client_init (void *cls, const struct InitMessage *im) const uint16_t *types; /* check that we don't have an entry already */ - msize = ntohs (im->header.size) - sizeof (struct InitMessage); - types = (const uint16_t *) &im[1]; - c->tcnt = msize / sizeof (uint16_t); - c->options = ntohl (im->options); + msize = ntohs(im->header.size) - sizeof(struct InitMessage); + types = (const uint16_t *)&im[1]; + c->tcnt = msize / sizeof(uint16_t); + c->options = ntohl(im->options); c->got_init = GNUNET_YES; all_client_options |= c->options; - c->types = GNUNET_malloc (msize); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_put ( - c->connectmap, - &GSC_my_identity, - NULL, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + c->types = GNUNET_malloc(msize); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_put( + c->connectmap, + &GSC_my_identity, + NULL, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); for (unsigned int i = 0; i < c->tcnt; i++) - c->types[i] = ntohs (types[i]); - GSC_TYPEMAP_add (c->types, c->tcnt); - GNUNET_log ( + c->types[i] = ntohs(types[i]); + GSC_TYPEMAP_add(c->types, c->tcnt); + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "Client connecting to core service is interested in %u message types\n", - (unsigned int) c->tcnt); + (unsigned int)c->tcnt); /* send init reply message */ - env = GNUNET_MQ_msg (irm, GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY); - irm->reserved = htonl (0); + env = GNUNET_MQ_msg(irm, GNUNET_MESSAGE_TYPE_CORE_INIT_REPLY); + irm->reserved = htonl(0); irm->my_identity = GSC_my_identity; - GNUNET_MQ_send (c->mq, env); - GSC_SESSIONS_notify_client_about_sessions (c); - GNUNET_SERVICE_client_continue (c->client); + GNUNET_MQ_send(c->mq, env); + GSC_SESSIONS_notify_client_about_sessions(c); + GNUNET_SERVICE_client_continue(c->client); } @@ -236,17 +235,17 @@ handle_client_init (void *cls, const struct InitMessage *im) * and we should thus drop the connection */ void -GSC_CLIENTS_reject_request (struct GSC_ClientActiveRequest *car, - int drop_client) +GSC_CLIENTS_reject_request(struct GSC_ClientActiveRequest *car, + int drop_client) { - GNUNET_assert ( + GNUNET_assert( GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (car->client_handle->requests, - &car->target, - car)); + GNUNET_CONTAINER_multipeermap_remove(car->client_handle->requests, + &car->target, + car)); if (GNUNET_YES == drop_client) - GNUNET_SERVICE_client_drop (car->client_handle->client); - GNUNET_free (car); + GNUNET_SERVICE_client_drop(car->client_handle->client); + GNUNET_free(car); } @@ -258,7 +257,7 @@ GSC_CLIENTS_reject_request (struct GSC_ClientActiveRequest *car, * and SESSIONS after this call. */ void -GSC_CLIENTS_solicit_request (struct GSC_ClientActiveRequest *car) +GSC_CLIENTS_solicit_request(struct GSC_ClientActiveRequest *car) { struct GSC_Client *c; struct GNUNET_MQ_Envelope *env; @@ -268,31 +267,31 @@ GSC_CLIENTS_solicit_request (struct GSC_ClientActiveRequest *car) c = car->client_handle; if (GNUNET_YES != - GNUNET_CONTAINER_multipeermap_contains (c->connectmap, &car->target)) - { - /* connection has gone down since, drop request */ - GNUNET_assert (0 != memcmp (&car->target, + GNUNET_CONTAINER_multipeermap_contains(c->connectmap, &car->target)) + { + /* connection has gone down since, drop request */ + GNUNET_assert(0 != memcmp(&car->target, &GSC_my_identity, - sizeof (struct GNUNET_PeerIdentity))); - GSC_SESSIONS_dequeue_request (car); - GSC_CLIENTS_reject_request (car, GNUNET_NO); - return; - } - delay = GNUNET_TIME_absolute_get_duration (car->received_time); - left = GNUNET_TIME_absolute_get_duration (car->deadline); + sizeof(struct GNUNET_PeerIdentity))); + GSC_SESSIONS_dequeue_request(car); + GSC_CLIENTS_reject_request(car, GNUNET_NO); + return; + } + delay = GNUNET_TIME_absolute_get_duration(car->received_time); + left = GNUNET_TIME_absolute_get_duration(car->deadline); if (delay.rel_value_us > GNUNET_CONSTANTS_LATENCY_WARN.rel_value_us) - GNUNET_log ( + GNUNET_log( GNUNET_ERROR_TYPE_WARNING, "Client waited %s for permission to transmit to `%s'%s (priority %u)\n", - GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES), - GNUNET_i2s (&car->target), + GNUNET_STRINGS_relative_time_to_string(delay, GNUNET_YES), + GNUNET_i2s(&car->target), (0 == left.rel_value_us) ? " (past deadline)" : "", car->priority); - env = GNUNET_MQ_msg (smr, GNUNET_MESSAGE_TYPE_CORE_SEND_READY); - smr->size = htons (car->msize); + env = GNUNET_MQ_msg(smr, GNUNET_MESSAGE_TYPE_CORE_SEND_READY); + smr->size = htons(car->msize); smr->smr_id = car->smr_id; smr->peer = car->target; - GNUNET_MQ_send (c->mq, env); + GNUNET_MQ_send(c->mq, env); } @@ -303,87 +302,85 @@ GSC_CLIENTS_solicit_request (struct GSC_ClientActiveRequest *car) * @param req the `struct SendMessageRequest` */ static void -handle_client_send_request (void *cls, const struct SendMessageRequest *req) +handle_client_send_request(void *cls, const struct SendMessageRequest *req) { struct GSC_Client *c = cls; struct GSC_ClientActiveRequest *car; int is_loopback; if (NULL == c->requests) - c->requests = GNUNET_CONTAINER_multipeermap_create (16, GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Client asked for transmission to `%s'\n", - GNUNET_i2s (&req->peer)); - is_loopback = (0 == memcmp (&req->peer, - &GSC_my_identity, - sizeof (struct GNUNET_PeerIdentity))); - if ((! is_loopback) && + c->requests = GNUNET_CONTAINER_multipeermap_create(16, GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Client asked for transmission to `%s'\n", + GNUNET_i2s(&req->peer)); + is_loopback = (0 == memcmp(&req->peer, + &GSC_my_identity, + sizeof(struct GNUNET_PeerIdentity))); + if ((!is_loopback) && (GNUNET_YES != - GNUNET_CONTAINER_multipeermap_contains (c->connectmap, &req->peer))) - { - /* neighbour must have disconnected since request was issued, - * ignore (client will realize it once it processes the - * disconnect notification) */ - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# send requests dropped (disconnected)"), - 1, - GNUNET_NO); - GNUNET_SERVICE_client_continue (c->client); - return; - } + GNUNET_CONTAINER_multipeermap_contains(c->connectmap, &req->peer))) + { + /* neighbour must have disconnected since request was issued, + * ignore (client will realize it once it processes the + * disconnect notification) */ + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# send requests dropped (disconnected)"), + 1, + GNUNET_NO); + GNUNET_SERVICE_client_continue(c->client); + return; + } - car = GNUNET_CONTAINER_multipeermap_get (c->requests, &req->peer); + car = GNUNET_CONTAINER_multipeermap_get(c->requests, &req->peer); if (NULL == car) - { - /* create new entry */ - car = GNUNET_new (struct GSC_ClientActiveRequest); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put ( - c->requests, - &req->peer, - car, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)); - car->client_handle = c; - } + { + /* create new entry */ + car = GNUNET_new(struct GSC_ClientActiveRequest); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_put( + c->requests, + &req->peer, + car, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)); + car->client_handle = c; + } else - { - /* dequeue and recycle memory from pending request, there can only - be at most one per client and peer */ - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# dequeuing CAR (duplicate request)"), - 1, - GNUNET_NO); - GSC_SESSIONS_dequeue_request (car); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Transmission request to `%s' was a duplicate!\n", - GNUNET_i2s (&req->peer)); - } + { + /* dequeue and recycle memory from pending request, there can only + be at most one per client and peer */ + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# dequeuing CAR (duplicate request)"), + 1, + GNUNET_NO); + GSC_SESSIONS_dequeue_request(car); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Transmission request to `%s' was a duplicate!\n", + GNUNET_i2s(&req->peer)); + } car->target = req->peer; - car->received_time = GNUNET_TIME_absolute_get (); - car->deadline = GNUNET_TIME_absolute_ntoh (req->deadline); - car->priority = (enum GNUNET_MQ_PriorityPreferences) ntohl (req->priority); - car->msize = ntohs (req->size); + car->received_time = GNUNET_TIME_absolute_get(); + car->deadline = GNUNET_TIME_absolute_ntoh(req->deadline); + car->priority = (enum GNUNET_MQ_PriorityPreferences)ntohl(req->priority); + car->msize = ntohs(req->size); car->smr_id = req->smr_id; car->was_solicited = GNUNET_NO; - GNUNET_SERVICE_client_continue (c->client); + GNUNET_SERVICE_client_continue(c->client); if (is_loopback) - { - /* loopback, satisfy immediately */ - GSC_CLIENTS_solicit_request (car); - return; - } - GSC_SESSIONS_queue_request (car); + { + /* loopback, satisfy immediately */ + GSC_CLIENTS_solicit_request(car); + return; + } + GSC_SESSIONS_queue_request(car); } /** * Closure for the #client_tokenizer_callback(). */ -struct TokenizerContext -{ - +struct TokenizerContext { /** * Active request handle for the message. */ @@ -409,58 +406,58 @@ struct TokenizerContext * #GNUNET_SYSERR to stop further processing with error */ static int -tokenized_cb (void *cls, const struct GNUNET_MessageHeader *message) +tokenized_cb(void *cls, const struct GNUNET_MessageHeader *message) { struct TokenizerContext *tc = cls; struct GSC_ClientActiveRequest *car = tc->car; char buf[92]; - GNUNET_snprintf (buf, - sizeof (buf), - gettext_noop ("# bytes of messages of type %u received"), - (unsigned int) ntohs (message->type)); - GNUNET_STATISTICS_update (GSC_stats, buf, ntohs (message->size), GNUNET_NO); - if (0 == memcmp (&car->target, - &GSC_my_identity, - sizeof (struct GNUNET_PeerIdentity))) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Delivering message of type %u to myself\n", - ntohs (message->type)); - GSC_CLIENTS_deliver_message (&GSC_my_identity, - message, - ntohs (message->size), - GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND); - GSC_CLIENTS_deliver_message (&GSC_my_identity, - message, - sizeof (struct GNUNET_MessageHeader), - GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND); - GSC_CLIENTS_deliver_message (&GSC_my_identity, - message, - ntohs (message->size), - GNUNET_CORE_OPTION_SEND_FULL_INBOUND); - GSC_CLIENTS_deliver_message (&GSC_my_identity, - message, - sizeof (struct GNUNET_MessageHeader), - GNUNET_CORE_OPTION_SEND_HDR_INBOUND); - } + GNUNET_snprintf(buf, + sizeof(buf), + gettext_noop("# bytes of messages of type %u received"), + (unsigned int)ntohs(message->type)); + GNUNET_STATISTICS_update(GSC_stats, buf, ntohs(message->size), GNUNET_NO); + if (0 == memcmp(&car->target, + &GSC_my_identity, + sizeof(struct GNUNET_PeerIdentity))) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Delivering message of type %u to myself\n", + ntohs(message->type)); + GSC_CLIENTS_deliver_message(&GSC_my_identity, + message, + ntohs(message->size), + GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND); + GSC_CLIENTS_deliver_message(&GSC_my_identity, + message, + sizeof(struct GNUNET_MessageHeader), + GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND); + GSC_CLIENTS_deliver_message(&GSC_my_identity, + message, + ntohs(message->size), + GNUNET_CORE_OPTION_SEND_FULL_INBOUND); + GSC_CLIENTS_deliver_message(&GSC_my_identity, + message, + sizeof(struct GNUNET_MessageHeader), + GNUNET_CORE_OPTION_SEND_HDR_INBOUND); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Delivering message of type %u and size %u to %s\n", - ntohs (message->type), - ntohs (message->size), - GNUNET_i2s (&car->target)); - GSC_CLIENTS_deliver_message (&car->target, - message, - ntohs (message->size), - GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND); - GSC_CLIENTS_deliver_message (&car->target, - message, - sizeof (struct GNUNET_MessageHeader), - GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND); - GSC_SESSIONS_transmit (car, message, tc->priority); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Delivering message of type %u and size %u to %s\n", + ntohs(message->type), + ntohs(message->size), + GNUNET_i2s(&car->target)); + GSC_CLIENTS_deliver_message(&car->target, + message, + ntohs(message->size), + GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND); + GSC_CLIENTS_deliver_message(&car->target, + message, + sizeof(struct GNUNET_MessageHeader), + GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND); + GSC_SESSIONS_transmit(car, message, tc->priority); + } return GNUNET_OK; } @@ -473,7 +470,7 @@ tokenized_cb (void *cls, const struct GNUNET_MessageHeader *message) * @return #GNUNET_OK if @a sm is well-formed */ static int -check_client_send (void *cls, const struct SendMessage *sm) +check_client_send(void *cls, const struct SendMessage *sm) { return GNUNET_OK; } @@ -486,7 +483,7 @@ check_client_send (void *cls, const struct SendMessage *sm) * @param sm the `struct SendMessage` */ static void -handle_client_send (void *cls, const struct SendMessage *sm) +handle_client_send(void *cls, const struct SendMessage *sm) { struct GSC_Client *c = cls; struct TokenizerContext tc; @@ -494,51 +491,51 @@ handle_client_send (void *cls, const struct SendMessage *sm) struct GNUNET_TIME_Relative delay; struct GNUNET_MessageStreamTokenizer *mst; - msize = ntohs (sm->header.size) - sizeof (struct SendMessage); - tc.car = GNUNET_CONTAINER_multipeermap_get (c->requests, &sm->peer); + msize = ntohs(sm->header.size) - sizeof(struct SendMessage); + tc.car = GNUNET_CONTAINER_multipeermap_get(c->requests, &sm->peer); if (NULL == tc.car) - { - /* Must have been that we first approved the request, then got disconnected - * (which triggered removal of the 'car') and now the client gives us a message - * just *before* the client learns about the disconnect. Theoretically, we - * might also now be *again* connected. So this can happen (but should be - * rare). If it does happen, the message is discarded. */ - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# messages discarded (session disconnected)"), - 1, - GNUNET_NO); - GNUNET_SERVICE_client_continue (c->client); - return; - } - delay = GNUNET_TIME_absolute_get_duration (tc.car->received_time); - tc.priority = (enum GNUNET_MQ_PriorityPreferences) ntohl (sm->priority); + { + /* Must have been that we first approved the request, then got disconnected + * (which triggered removal of the 'car') and now the client gives us a message + * just *before* the client learns about the disconnect. Theoretically, we + * might also now be *again* connected. So this can happen (but should be + * rare). If it does happen, the message is discarded. */ + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# messages discarded (session disconnected)"), + 1, + GNUNET_NO); + GNUNET_SERVICE_client_continue(c->client); + return; + } + delay = GNUNET_TIME_absolute_get_duration(tc.car->received_time); + tc.priority = (enum GNUNET_MQ_PriorityPreferences)ntohl(sm->priority); if (delay.rel_value_us > GNUNET_CONSTANTS_LATENCY_WARN.rel_value_us) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Client waited %s for transmission of %u bytes to `%s'\n", - GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES), - msize, - GNUNET_i2s (&sm->peer)); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Client waited %s for transmission of %u bytes to `%s'\n", + GNUNET_STRINGS_relative_time_to_string(delay, GNUNET_YES), + msize, + GNUNET_i2s(&sm->peer)); else - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Client waited %s for transmission of %u bytes to `%s'\n", - GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES), - msize, - GNUNET_i2s (&sm->peer)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Client waited %s for transmission of %u bytes to `%s'\n", + GNUNET_STRINGS_relative_time_to_string(delay, GNUNET_YES), + msize, + GNUNET_i2s(&sm->peer)); - GNUNET_assert ( + GNUNET_assert( GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (c->requests, &sm->peer, tc.car)); - mst = GNUNET_MST_create (&tokenized_cb, &tc); - GNUNET_MST_from_buffer (mst, - (const char *) &sm[1], - msize, - GNUNET_YES, - GNUNET_NO); - GNUNET_MST_destroy (mst); - GSC_SESSIONS_dequeue_request (tc.car); - GNUNET_free (tc.car); - GNUNET_SERVICE_client_continue (c->client); + GNUNET_CONTAINER_multipeermap_remove(c->requests, &sm->peer, tc.car)); + mst = GNUNET_MST_create(&tokenized_cb, &tc); + GNUNET_MST_from_buffer(mst, + (const char *)&sm[1], + msize, + GNUNET_YES, + GNUNET_NO); + GNUNET_MST_destroy(mst); + GSC_SESSIONS_dequeue_request(tc.car); + GNUNET_free(tc.car); + GNUNET_SERVICE_client_continue(c->client); } @@ -551,19 +548,19 @@ handle_client_send (void *cls, const struct SendMessage *sm) * @return #GNUNET_YES (continue iteration) */ static int -destroy_active_client_request (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +destroy_active_client_request(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct GSC_ClientActiveRequest *car = value; - GNUNET_assert ( + GNUNET_assert( GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (car->client_handle->requests, - &car->target, - car)); - GSC_SESSIONS_dequeue_request (car); - GNUNET_free (car); + GNUNET_CONTAINER_multipeermap_remove(car->client_handle->requests, + &car->target, + car)); + GSC_SESSIONS_dequeue_request(car); + GNUNET_free(car); return GNUNET_YES; } @@ -577,17 +574,17 @@ destroy_active_client_request (void *cls, * @return our client handle */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { struct GSC_Client *c; - c = GNUNET_new (struct GSC_Client); + c = GNUNET_new(struct GSC_Client); c->client = client; c->mq = mq; - c->connectmap = GNUNET_CONTAINER_multipeermap_create (16, GNUNET_NO); - GNUNET_CONTAINER_DLL_insert (client_head, client_tail, c); + c->connectmap = GNUNET_CONTAINER_multipeermap_create(16, GNUNET_NO); + GNUNET_CONTAINER_DLL_insert(client_head, client_tail, c); return c; } @@ -600,31 +597,31 @@ client_connect_cb (void *cls, * @param app_ctx our `struct GST_Client` for @a client */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { struct GSC_Client *c = app_ctx; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Client %p has disconnected from core service.\n", - client); - GNUNET_CONTAINER_DLL_remove (client_head, client_tail, c); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Client %p has disconnected from core service.\n", + client); + GNUNET_CONTAINER_DLL_remove(client_head, client_tail, c); if (NULL != c->requests) - { - GNUNET_CONTAINER_multipeermap_iterate (c->requests, - &destroy_active_client_request, - NULL); - GNUNET_CONTAINER_multipeermap_destroy (c->requests); - } - GNUNET_CONTAINER_multipeermap_destroy (c->connectmap); + { + GNUNET_CONTAINER_multipeermap_iterate(c->requests, + &destroy_active_client_request, + NULL); + GNUNET_CONTAINER_multipeermap_destroy(c->requests); + } + GNUNET_CONTAINER_multipeermap_destroy(c->connectmap); c->connectmap = NULL; if (NULL != c->types) - { - GSC_TYPEMAP_remove (c->types, c->tcnt); - GNUNET_free (c->types); - } - GNUNET_free (c); + { + GSC_TYPEMAP_remove(c->types, c->tcnt); + GNUNET_free(c->types); + } + GNUNET_free(c); /* recalculate 'all_client_options' */ all_client_options = 0; @@ -644,7 +641,7 @@ client_disconnect_cb (void *cls, * @param tmap_new updated type map for the neighbour, NULL for disconnect */ void -GSC_CLIENTS_notify_client_about_neighbour ( +GSC_CLIENTS_notify_client_about_neighbour( struct GSC_Client *client, const struct GNUNET_PeerIdentity *neighbour, const struct GSC_TypeMap *tmap_old, @@ -656,62 +653,62 @@ GSC_CLIENTS_notify_client_about_neighbour ( if (GNUNET_YES != client->got_init) return; - old_match = GSC_TYPEMAP_test_match (tmap_old, client->types, client->tcnt); - new_match = GSC_TYPEMAP_test_match (tmap_new, client->types, client->tcnt); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Notifying client about neighbour %s (%d/%d)\n", - GNUNET_i2s (neighbour), - old_match, - new_match); + old_match = GSC_TYPEMAP_test_match(tmap_old, client->types, client->tcnt); + new_match = GSC_TYPEMAP_test_match(tmap_new, client->types, client->tcnt); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Notifying client about neighbour %s (%d/%d)\n", + GNUNET_i2s(neighbour), + old_match, + new_match); if (old_match == new_match) - { - GNUNET_assert ( - old_match == - GNUNET_CONTAINER_multipeermap_contains (client->connectmap, neighbour)); - return; /* no change */ - } + { + GNUNET_assert( + old_match == + GNUNET_CONTAINER_multipeermap_contains(client->connectmap, neighbour)); + return; /* no change */ + } if (GNUNET_NO == old_match) - { - struct ConnectNotifyMessage *cnm; - - /* send connect */ - GNUNET_assert ( - GNUNET_NO == - GNUNET_CONTAINER_multipeermap_contains (client->connectmap, neighbour)); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_put ( - client->connectmap, - neighbour, - NULL, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - env = GNUNET_MQ_msg (cnm, GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT); - cnm->reserved = htonl (0); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending NOTIFY_CONNECT message about peer %s to client.\n", - GNUNET_i2s (neighbour)); - cnm->peer = *neighbour; - GNUNET_MQ_send (client->mq, env); - } + { + struct ConnectNotifyMessage *cnm; + + /* send connect */ + GNUNET_assert( + GNUNET_NO == + GNUNET_CONTAINER_multipeermap_contains(client->connectmap, neighbour)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_put( + client->connectmap, + neighbour, + NULL, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + env = GNUNET_MQ_msg(cnm, GNUNET_MESSAGE_TYPE_CORE_NOTIFY_CONNECT); + cnm->reserved = htonl(0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending NOTIFY_CONNECT message about peer %s to client.\n", + GNUNET_i2s(neighbour)); + cnm->peer = *neighbour; + GNUNET_MQ_send(client->mq, env); + } else - { - struct DisconnectNotifyMessage *dcm; - - /* send disconnect */ - GNUNET_assert ( - GNUNET_YES == - GNUNET_CONTAINER_multipeermap_contains (client->connectmap, neighbour)); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (client->connectmap, + { + struct DisconnectNotifyMessage *dcm; + + /* send disconnect */ + GNUNET_assert( + GNUNET_YES == + GNUNET_CONTAINER_multipeermap_contains(client->connectmap, neighbour)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(client->connectmap, neighbour, NULL)); - env = GNUNET_MQ_msg (dcm, GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT); - dcm->reserved = htonl (0); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending NOTIFY_DISCONNECT message about peer %s to client.\n", - GNUNET_i2s (neighbour)); - dcm->peer = *neighbour; - GNUNET_MQ_send (client->mq, env); - } + env = GNUNET_MQ_msg(dcm, GNUNET_MESSAGE_TYPE_CORE_NOTIFY_DISCONNECT); + dcm->reserved = htonl(0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending NOTIFY_DISCONNECT message about peer %s to client.\n", + GNUNET_i2s(neighbour)); + dcm->peer = *neighbour; + GNUNET_MQ_send(client->mq, env); + } } @@ -725,7 +722,7 @@ GSC_CLIENTS_notify_client_about_neighbour ( * @param tmap_new updated type map for the neighbour, NULL for disconnect */ void -GSC_CLIENTS_notify_clients_about_neighbour ( +GSC_CLIENTS_notify_clients_about_neighbour( const struct GNUNET_PeerIdentity *neighbour, const struct GSC_TypeMap *tmap_old, const struct GSC_TypeMap *tmap_new) @@ -733,10 +730,10 @@ GSC_CLIENTS_notify_clients_about_neighbour ( struct GSC_Client *c; for (c = client_head; NULL != c; c = c->next) - GSC_CLIENTS_notify_client_about_neighbour (c, - neighbour, - tmap_old, - tmap_new); + GSC_CLIENTS_notify_client_about_neighbour(c, + neighbour, + tmap_old, + tmap_new); } @@ -752,108 +749,108 @@ GSC_CLIENTS_notify_clients_about_neighbour ( * receive the message */ void -GSC_CLIENTS_deliver_message (const struct GNUNET_PeerIdentity *sender, - const struct GNUNET_MessageHeader *msg, - uint16_t msize, - uint32_t options) +GSC_CLIENTS_deliver_message(const struct GNUNET_PeerIdentity *sender, + const struct GNUNET_MessageHeader *msg, + uint16_t msize, + uint32_t options) { - size_t size = msize + sizeof (struct NotifyTrafficMessage); + size_t size = msize + sizeof(struct NotifyTrafficMessage); if (size >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return; - } - if (! ((0 != (all_client_options & options)) || - (0 != (options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)))) + { + GNUNET_break(0); + return; + } + if (!((0 != (all_client_options & options)) || + (0 != (options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)))) return; /* no client cares about this message notification */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Core service passes message from `%s' of type %u to client.\n", - GNUNET_i2s (sender), - (unsigned int) ntohs (msg->type)); - GSC_SESSIONS_add_to_typemap (sender, ntohs (msg->type)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Core service passes message from `%s' of type %u to client.\n", + GNUNET_i2s(sender), + (unsigned int)ntohs(msg->type)); + GSC_SESSIONS_add_to_typemap(sender, ntohs(msg->type)); for (struct GSC_Client *c = client_head; NULL != c; c = c->next) - { - struct GNUNET_MQ_Envelope *env; - struct NotifyTrafficMessage *ntm; - uint16_t mtype; - unsigned int qlen; - int tm; - - tm = type_match (ntohs (msg->type), c); - if (! ((0 != (c->options & options)) || - ((0 != (options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)) && - (GNUNET_YES == tm)))) - continue; /* neither options nor type match permit the message */ - if ((0 != (options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)) && - ((0 != (c->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)) || - (GNUNET_YES == tm))) - continue; - if ((0 != (options & GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND)) && - (0 != (c->options & GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND))) - continue; - - /* Drop messages if: - 1) We are above the hard limit, or - 2) We are above the soft limit, and a coin toss limited - to the message size (giving larger messages a - proportionally higher chance of being queued) falls - below the threshold. The threshold is based on where - we are between the soft and the hard limit, scaled - to match the range of message sizes we usually encounter - (i.e. up to 32k); so a 64k message has a 50% chance of - being kept if we are just barely below the hard max, - and a 99% chance of being kept if we are at the soft max. - The reason is to make it more likely to drop control traffic - (ACK, queries) which may be cummulative or highly redundant, - and cheap to drop than data traffic. */ - qlen = GNUNET_MQ_get_length (c->mq); - if ((qlen >= HARD_MAX_QUEUE) || - ((qlen > SOFT_MAX_QUEUE) && - ((GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - ntohs (msg->size))) < - (qlen - SOFT_MAX_QUEUE) * 0x8000 / - (HARD_MAX_QUEUE - SOFT_MAX_QUEUE)))) { - char buf[1024]; - - GNUNET_log ( - GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK, - "Dropping decrypted message of type %u as client is too busy (queue full)\n", - (unsigned int) ntohs (msg->type)); - GNUNET_snprintf (buf, - sizeof (buf), - gettext_noop ( - "# messages of type %u discarded (client busy)"), - (unsigned int) ntohs (msg->type)); - GNUNET_STATISTICS_update (GSC_stats, buf, 1, GNUNET_NO); - continue; + struct GNUNET_MQ_Envelope *env; + struct NotifyTrafficMessage *ntm; + uint16_t mtype; + unsigned int qlen; + int tm; + + tm = type_match(ntohs(msg->type), c); + if (!((0 != (c->options & options)) || + ((0 != (options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)) && + (GNUNET_YES == tm)))) + continue; /* neither options nor type match permit the message */ + if ((0 != (options & GNUNET_CORE_OPTION_SEND_HDR_INBOUND)) && + ((0 != (c->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)) || + (GNUNET_YES == tm))) + continue; + if ((0 != (options & GNUNET_CORE_OPTION_SEND_HDR_OUTBOUND)) && + (0 != (c->options & GNUNET_CORE_OPTION_SEND_FULL_OUTBOUND))) + continue; + + /* Drop messages if: + 1) We are above the hard limit, or + 2) We are above the soft limit, and a coin toss limited + to the message size (giving larger messages a + proportionally higher chance of being queued) falls + below the threshold. The threshold is based on where + we are between the soft and the hard limit, scaled + to match the range of message sizes we usually encounter + (i.e. up to 32k); so a 64k message has a 50% chance of + being kept if we are just barely below the hard max, + and a 99% chance of being kept if we are at the soft max. + The reason is to make it more likely to drop control traffic + (ACK, queries) which may be cummulative or highly redundant, + and cheap to drop than data traffic. */ + qlen = GNUNET_MQ_get_length(c->mq); + if ((qlen >= HARD_MAX_QUEUE) || + ((qlen > SOFT_MAX_QUEUE) && + ((GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + ntohs(msg->size))) < + (qlen - SOFT_MAX_QUEUE) * 0x8000 / + (HARD_MAX_QUEUE - SOFT_MAX_QUEUE)))) + { + char buf[1024]; + + GNUNET_log( + GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK, + "Dropping decrypted message of type %u as client is too busy (queue full)\n", + (unsigned int)ntohs(msg->type)); + GNUNET_snprintf(buf, + sizeof(buf), + gettext_noop( + "# messages of type %u discarded (client busy)"), + (unsigned int)ntohs(msg->type)); + GNUNET_STATISTICS_update(GSC_stats, buf, 1, GNUNET_NO); + continue; + } + + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Sending %u message with %u bytes to client interested in messages of type %u.\n", + options, + ntohs(msg->size), + (unsigned int)ntohs(msg->type)); + + if (0 != (options & (GNUNET_CORE_OPTION_SEND_FULL_INBOUND | + GNUNET_CORE_OPTION_SEND_HDR_INBOUND))) + mtype = GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND; + else + mtype = GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND; + env = GNUNET_MQ_msg_extra(ntm, msize, mtype); + ntm->peer = *sender; + GNUNET_memcpy(&ntm[1], msg, msize); + + GNUNET_assert( + (0 == (c->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)) || + (GNUNET_YES != tm) || + (GNUNET_YES == + GNUNET_CONTAINER_multipeermap_contains(c->connectmap, sender))); + GNUNET_MQ_send(c->mq, env); } - - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Sending %u message with %u bytes to client interested in messages of type %u.\n", - options, - ntohs (msg->size), - (unsigned int) ntohs (msg->type)); - - if (0 != (options & (GNUNET_CORE_OPTION_SEND_FULL_INBOUND | - GNUNET_CORE_OPTION_SEND_HDR_INBOUND))) - mtype = GNUNET_MESSAGE_TYPE_CORE_NOTIFY_INBOUND; - else - mtype = GNUNET_MESSAGE_TYPE_CORE_NOTIFY_OUTBOUND; - env = GNUNET_MQ_msg_extra (ntm, msize, mtype); - ntm->peer = *sender; - GNUNET_memcpy (&ntm[1], msg, msize); - - GNUNET_assert ( - (0 == (c->options & GNUNET_CORE_OPTION_SEND_FULL_INBOUND)) || - (GNUNET_YES != tm) || - (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_contains (c->connectmap, sender))); - GNUNET_MQ_send (c->mq, env); - } } @@ -864,21 +861,21 @@ GSC_CLIENTS_deliver_message (const struct GNUNET_PeerIdentity *sender, * @param cls NULL, unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { struct GSC_Client *c; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Core service shutting down.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Core service shutting down.\n"); while (NULL != (c = client_head)) - GNUNET_SERVICE_client_drop (c->client); - GSC_SESSIONS_done (); - GSC_KX_done (); - GSC_TYPEMAP_done (); + GNUNET_SERVICE_client_drop(c->client); + GSC_SESSIONS_done(); + GSC_KX_done(); + GSC_TYPEMAP_done(); if (NULL != GSC_stats) - { - GNUNET_STATISTICS_destroy (GSC_stats, GNUNET_NO); - GSC_stats = NULL; - } + { + GNUNET_STATISTICS_destroy(GSC_stats, GNUNET_NO); + GSC_stats = NULL; + } GSC_cfg = NULL; } @@ -893,13 +890,13 @@ shutdown_task (void *cls) * @param message iteration request message */ static void -handle_client_monitor_peers (void *cls, - const struct GNUNET_MessageHeader *message) +handle_client_monitor_peers(void *cls, + const struct GNUNET_MessageHeader *message) { struct GSC_Client *c = cls; - GNUNET_SERVICE_client_continue (c->client); - GSC_KX_handle_client_monitor_peers (c->mq); + GNUNET_SERVICE_client_continue(c->client); + GSC_KX_handle_client_monitor_peers(c->mq); } @@ -911,72 +908,72 @@ handle_client_monitor_peers (void *cls, * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *service) { struct GNUNET_CRYPTO_EddsaPrivateKey *pk; char *keyfile; GSC_cfg = c; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (GSC_cfg, - "PEER", - "PRIVATE_KEY", - &keyfile)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_ERROR, - _ ("Core service is lacking HOSTKEY configuration setting. Exiting.\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } - GSC_stats = GNUNET_STATISTICS_create ("core", GSC_cfg); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); - GNUNET_SERVICE_suspend (service); - GSC_TYPEMAP_init (); - pk = GNUNET_CRYPTO_eddsa_key_create_from_file (keyfile); - GNUNET_free (keyfile); - GNUNET_assert (NULL != pk); - if (GNUNET_OK != GSC_KX_init (pk)) - { - GNUNET_SCHEDULER_shutdown (); - return; - } - GSC_SESSIONS_init (); - GNUNET_SERVICE_resume (service); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Core service of `%s' ready.\n"), - GNUNET_i2s (&GSC_my_identity)); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(GSC_cfg, + "PEER", + "PRIVATE_KEY", + &keyfile)) + { + GNUNET_log( + GNUNET_ERROR_TYPE_ERROR, + _("Core service is lacking HOSTKEY configuration setting. Exiting.\n")); + GNUNET_SCHEDULER_shutdown(); + return; + } + GSC_stats = GNUNET_STATISTICS_create("core", GSC_cfg); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); + GNUNET_SERVICE_suspend(service); + GSC_TYPEMAP_init(); + pk = GNUNET_CRYPTO_eddsa_key_create_from_file(keyfile); + GNUNET_free(keyfile); + GNUNET_assert(NULL != pk); + if (GNUNET_OK != GSC_KX_init(pk)) + { + GNUNET_SCHEDULER_shutdown(); + return; + } + GSC_SESSIONS_init(); + GNUNET_SERVICE_resume(service); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Core service of `%s' ready.\n"), + GNUNET_i2s(&GSC_my_identity)); } /** * Define "main" method using service macro. */ -GNUNET_SERVICE_MAIN ( +GNUNET_SERVICE_MAIN( "core", GNUNET_SERVICE_OPTION_NONE, &run, &client_connect_cb, &client_disconnect_cb, NULL, - GNUNET_MQ_hd_var_size (client_init, - GNUNET_MESSAGE_TYPE_CORE_INIT, - struct InitMessage, - NULL), - GNUNET_MQ_hd_fixed_size (client_monitor_peers, - GNUNET_MESSAGE_TYPE_CORE_MONITOR_PEERS, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_hd_fixed_size (client_send_request, - GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST, - struct SendMessageRequest, - NULL), - GNUNET_MQ_hd_var_size (client_send, - GNUNET_MESSAGE_TYPE_CORE_SEND, - struct SendMessage, - NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_hd_var_size(client_init, + GNUNET_MESSAGE_TYPE_CORE_INIT, + struct InitMessage, + NULL), + GNUNET_MQ_hd_fixed_size(client_monitor_peers, + GNUNET_MESSAGE_TYPE_CORE_MONITOR_PEERS, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_hd_fixed_size(client_send_request, + GNUNET_MESSAGE_TYPE_CORE_SEND_REQUEST, + struct SendMessageRequest, + NULL), + GNUNET_MQ_hd_var_size(client_send, + GNUNET_MESSAGE_TYPE_CORE_SEND, + struct SendMessage, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-core.c */ diff --git a/src/core/gnunet-service-core.h b/src/core/gnunet-service-core.h index 154596933..7cb4dffa9 100644 --- a/src/core/gnunet-service-core.h +++ b/src/core/gnunet-service-core.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/gnunet-service-core.h @@ -43,9 +43,7 @@ struct GSC_Client; * client that is still pending. (This struct is used by * both the 'CLIENTS' and 'SESSIONS' subsystems.) */ -struct GSC_ClientActiveRequest -{ - +struct GSC_ClientActiveRequest { /** * Active requests are kept in a doubly-linked list of * the respective target peer. @@ -108,7 +106,7 @@ struct GSC_ClientActiveRequest * and SESSIONS after this call. */ void -GSC_CLIENTS_solicit_request (struct GSC_ClientActiveRequest *car); +GSC_CLIENTS_solicit_request(struct GSC_ClientActiveRequest *car); /** @@ -124,8 +122,8 @@ GSC_CLIENTS_solicit_request (struct GSC_ClientActiveRequest *car); * and we should thus drop the connection */ void -GSC_CLIENTS_reject_request (struct GSC_ClientActiveRequest *car, - int drop_client); +GSC_CLIENTS_reject_request(struct GSC_ClientActiveRequest *car, + int drop_client); /** @@ -139,7 +137,7 @@ GSC_CLIENTS_reject_request (struct GSC_ClientActiveRequest *car, * @param tmap_new updated type map for the neighbour, NULL for disconnect */ void -GSC_CLIENTS_notify_client_about_neighbour ( +GSC_CLIENTS_notify_client_about_neighbour( struct GSC_Client *client, const struct GNUNET_PeerIdentity *neighbour, const struct GSC_TypeMap *tmap_old, @@ -158,10 +156,10 @@ GSC_CLIENTS_notify_client_about_neighbour ( * receive the message */ void -GSC_CLIENTS_deliver_message (const struct GNUNET_PeerIdentity *sender, - const struct GNUNET_MessageHeader *msg, - uint16_t msize, - uint32_t options); +GSC_CLIENTS_deliver_message(const struct GNUNET_PeerIdentity *sender, + const struct GNUNET_MessageHeader *msg, + uint16_t msize, + uint32_t options); /** @@ -174,7 +172,7 @@ GSC_CLIENTS_deliver_message (const struct GNUNET_PeerIdentity *sender, * @param tmap_new updated type map for the neighbour, NULL for disconnect */ void -GSC_CLIENTS_notify_clients_about_neighbour ( +GSC_CLIENTS_notify_clients_about_neighbour( const struct GNUNET_PeerIdentity *neighbour, const struct GSC_TypeMap *tmap_old, const struct GSC_TypeMap *tmap_new); diff --git a/src/core/gnunet-service-core_kx.c b/src/core/gnunet-service-core_kx.c index d226b65e2..e73dc2430 100644 --- a/src/core/gnunet-service-core_kx.c +++ b/src/core/gnunet-service-core_kx.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/gnunet-service-core_kx.c @@ -44,25 +44,25 @@ * How long do we wait for SET_KEY confirmation initially? */ #define INITIAL_SET_KEY_RETRY_FREQUENCY \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) /** * What is the minimum frequency for a PING message? */ #define MIN_PING_FREQUENCY \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) /** * How often do we rekey? */ #define REKEY_FREQUENCY \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_HOURS, 12) /** * What time difference do we tolerate? */ #define REKEY_TOLERANCE \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5) /** * What is the maximum age of a message for us to consider processing @@ -80,9 +80,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * Message transmitted with the signed ephemeral key of a peer. The * session key is then derived from the two ephemeral keys (ECDHE). */ -struct EphemeralKeyMessage -{ - +struct EphemeralKeyMessage { /** * Message type is #GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY. */ @@ -132,8 +130,7 @@ struct EphemeralKeyMessage * can decrypt. The other peer should respond with a PONG with the * same content, except this time encrypted with the receiver's key. */ -struct PingMessage -{ +struct PingMessage { /** * Message type is #GNUNET_MESSAGE_TYPE_CORE_PING. */ @@ -160,8 +157,7 @@ struct PingMessage /** * Response to a PING. Includes data from the original PING. */ -struct PongMessage -{ +struct PongMessage { /** * Message type is #GNUNET_MESSAGE_TYPE_CORE_PONG. */ @@ -194,8 +190,7 @@ struct PongMessage * Encapsulation for encrypted messages exchanged between * peers. Followed by the actual encrypted data. */ -struct EncryptedMessage -{ +struct EncryptedMessage { /** * Message type is #GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE. */ @@ -240,15 +235,13 @@ GNUNET_NETWORK_STRUCT_END * that are NOT encrypted. */ #define ENCRYPTED_HEADER_SIZE \ - (offsetof (struct EncryptedMessage, sequence_number)) + (offsetof(struct EncryptedMessage, sequence_number)) /** * Information about the status of a key exchange with another peer. */ -struct GSC_KeyExchangeInfo -{ - +struct GSC_KeyExchangeInfo { /** * DLL. */ @@ -408,13 +401,13 @@ static struct GNUNET_NotificationContext *nc; * @param kx key exchange context */ static uint32_t -calculate_seed (struct GSC_KeyExchangeInfo *kx) +calculate_seed(struct GSC_KeyExchangeInfo *kx) { /* Note: may want to make this non-random and instead derive from key material to avoid having an undetectable side-channel */ - return htonl ( - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX)); + return htonl( + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX)); } @@ -424,16 +417,16 @@ calculate_seed (struct GSC_KeyExchangeInfo *kx) * @param kx key exchange state to inform about */ static void -monitor_notify_all (struct GSC_KeyExchangeInfo *kx) +monitor_notify_all(struct GSC_KeyExchangeInfo *kx) { struct MonitorNotifyMessage msg; - msg.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY); - msg.header.size = htons (sizeof (msg)); - msg.state = htonl ((uint32_t) kx->status); + msg.header.type = htons(GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY); + msg.header.size = htons(sizeof(msg)); + msg.state = htonl((uint32_t)kx->status); msg.peer = *kx->peer; - msg.timeout = GNUNET_TIME_absolute_hton (kx->timeout); - GNUNET_notification_context_broadcast (nc, &msg.header, GNUNET_NO); + msg.timeout = GNUNET_TIME_absolute_hton(kx->timeout); + GNUNET_notification_context_broadcast(nc, &msg.header, GNUNET_NO); kx->last_notify_timeout = kx->timeout; } @@ -446,30 +439,31 @@ monitor_notify_all (struct GSC_KeyExchangeInfo *kx) * @param seed seed to use */ static void -derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey, - const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, - uint32_t seed) +derive_auth_key(struct GNUNET_CRYPTO_AuthKey *akey, + const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, + uint32_t seed) { static const char ctx[] = "authentication key"; + #if DEBUG_KX struct GNUNET_HashCode sh; - GNUNET_CRYPTO_hash (skey, sizeof (*skey), &sh); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Deriving Auth key from SKEY %s and seed %u\n", - GNUNET_h2s (&sh), - (unsigned int) seed); + GNUNET_CRYPTO_hash(skey, sizeof(*skey), &sh); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Deriving Auth key from SKEY %s and seed %u\n", + GNUNET_h2s(&sh), + (unsigned int)seed); #endif - GNUNET_CRYPTO_hmac_derive_key (akey, - skey, - &seed, - sizeof (seed), - skey, - sizeof ( - struct GNUNET_CRYPTO_SymmetricSessionKey), - ctx, - sizeof (ctx), - NULL); + GNUNET_CRYPTO_hmac_derive_key(akey, + skey, + &seed, + sizeof(seed), + skey, + sizeof( + struct GNUNET_CRYPTO_SymmetricSessionKey), + ctx, + sizeof(ctx), + NULL); } @@ -482,31 +476,32 @@ derive_auth_key (struct GNUNET_CRYPTO_AuthKey *akey, * @param identity identity of the other peer to use */ static void -derive_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, - const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, - uint32_t seed, - const struct GNUNET_PeerIdentity *identity) +derive_iv(struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, + const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, + uint32_t seed, + const struct GNUNET_PeerIdentity *identity) { static const char ctx[] = "initialization vector"; + #if DEBUG_KX struct GNUNET_HashCode sh; - GNUNET_CRYPTO_hash (skey, sizeof (*skey), &sh); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Deriving IV from SKEY %s and seed %u for peer %s\n", - GNUNET_h2s (&sh), - (unsigned int) seed, - GNUNET_i2s (identity)); + GNUNET_CRYPTO_hash(skey, sizeof(*skey), &sh); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Deriving IV from SKEY %s and seed %u for peer %s\n", + GNUNET_h2s(&sh), + (unsigned int)seed, + GNUNET_i2s(identity)); #endif - GNUNET_CRYPTO_symmetric_derive_iv (iv, - skey, - &seed, - sizeof (seed), - identity, - sizeof (struct GNUNET_PeerIdentity), - ctx, - sizeof (ctx), - NULL); + GNUNET_CRYPTO_symmetric_derive_iv(iv, + skey, + &seed, + sizeof(seed), + identity, + sizeof(struct GNUNET_PeerIdentity), + ctx, + sizeof(ctx), + NULL); } @@ -520,35 +515,36 @@ derive_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, * @param identity identity of the other peer to use */ static void -derive_pong_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, - const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, - uint32_t seed, - uint32_t challenge, - const struct GNUNET_PeerIdentity *identity) +derive_pong_iv(struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, + const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, + uint32_t seed, + uint32_t challenge, + const struct GNUNET_PeerIdentity *identity) { static const char ctx[] = "pong initialization vector"; + #if DEBUG_KX struct GNUNET_HashCode sh; - GNUNET_CRYPTO_hash (skey, sizeof (*skey), &sh); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Deriving PONG IV from SKEY %s and seed %u/%u for %s\n", - GNUNET_h2s (&sh), - (unsigned int) seed, - (unsigned int) challenge, - GNUNET_i2s (identity)); + GNUNET_CRYPTO_hash(skey, sizeof(*skey), &sh); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Deriving PONG IV from SKEY %s and seed %u/%u for %s\n", + GNUNET_h2s(&sh), + (unsigned int)seed, + (unsigned int)challenge, + GNUNET_i2s(identity)); #endif - GNUNET_CRYPTO_symmetric_derive_iv (iv, - skey, - &seed, - sizeof (seed), - identity, - sizeof (struct GNUNET_PeerIdentity), - &challenge, - sizeof (challenge), - ctx, - sizeof (ctx), - NULL); + GNUNET_CRYPTO_symmetric_derive_iv(iv, + skey, + &seed, + sizeof(seed), + identity, + sizeof(struct GNUNET_PeerIdentity), + &challenge, + sizeof(challenge), + ctx, + sizeof(ctx), + NULL); } @@ -561,33 +557,34 @@ derive_pong_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, * @param skey set to derived session key */ static void -derive_aes_key (const struct GNUNET_PeerIdentity *sender, - const struct GNUNET_PeerIdentity *receiver, - const struct GNUNET_HashCode *key_material, - struct GNUNET_CRYPTO_SymmetricSessionKey *skey) +derive_aes_key(const struct GNUNET_PeerIdentity *sender, + const struct GNUNET_PeerIdentity *receiver, + const struct GNUNET_HashCode *key_material, + struct GNUNET_CRYPTO_SymmetricSessionKey *skey) { static const char ctx[] = "aes key generation vector"; + #if DEBUG_KX struct GNUNET_HashCode sh; - GNUNET_CRYPTO_hash (skey, sizeof (*skey), &sh); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Deriving AES Keys for %s to %s from %s\n", - GNUNET_i2s (sender), - GNUNET_i2s2 (receiver), - GNUNET_h2s (key_material)); + GNUNET_CRYPTO_hash(skey, sizeof(*skey), &sh); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Deriving AES Keys for %s to %s from %s\n", + GNUNET_i2s(sender), + GNUNET_i2s2(receiver), + GNUNET_h2s(key_material)); #endif - GNUNET_CRYPTO_kdf (skey, - sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey), - ctx, - sizeof (ctx), - key_material, - sizeof (struct GNUNET_HashCode), - sender, - sizeof (struct GNUNET_PeerIdentity), - receiver, - sizeof (struct GNUNET_PeerIdentity), - NULL); + GNUNET_CRYPTO_kdf(skey, + sizeof(struct GNUNET_CRYPTO_SymmetricSessionKey), + ctx, + sizeof(ctx), + key_material, + sizeof(struct GNUNET_HashCode), + sender, + sizeof(struct GNUNET_PeerIdentity), + receiver, + sizeof(struct GNUNET_PeerIdentity), + NULL); } @@ -603,35 +600,35 @@ derive_aes_key (const struct GNUNET_PeerIdentity *sender, * @return #GNUNET_OK on success */ static int -do_encrypt (struct GSC_KeyExchangeInfo *kx, - const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, - const void *in, - void *out, - size_t size) +do_encrypt(struct GSC_KeyExchangeInfo *kx, + const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, + const void *in, + void *out, + size_t size) { - if (size != (uint16_t) size) - { - GNUNET_break (0); - return GNUNET_NO; - } - GNUNET_assert (size == GNUNET_CRYPTO_symmetric_encrypt (in, - (uint16_t) size, - &kx->encrypt_key, - iv, - out)); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# bytes encrypted"), - size, - GNUNET_NO); + if (size != (uint16_t)size) + { + GNUNET_break(0); + return GNUNET_NO; + } + GNUNET_assert(size == GNUNET_CRYPTO_symmetric_encrypt(in, + (uint16_t)size, + &kx->encrypt_key, + iv, + out)); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# bytes encrypted"), + size, + GNUNET_NO); /* the following is too sensitive to write to log files by accident, so we require manual intervention to get this one... */ #if DEBUG_KX - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Encrypted %u bytes for `%s' using key %u, IV %u\n", - (unsigned int) size, - GNUNET_i2s (kx->peer), - (unsigned int) kx->encrypt_key.crc32, - GNUNET_CRYPTO_crc32_n (iv, sizeof (iv))); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Encrypted %u bytes for `%s' using key %u, IV %u\n", + (unsigned int)size, + GNUNET_i2s(kx->peer), + (unsigned int)kx->encrypt_key.crc32, + GNUNET_CRYPTO_crc32_n(iv, sizeof(iv))); #endif return GNUNET_OK; } @@ -650,46 +647,46 @@ do_encrypt (struct GSC_KeyExchangeInfo *kx, * @return #GNUNET_OK on success */ static int -do_decrypt (struct GSC_KeyExchangeInfo *kx, - const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, - const void *in, - void *out, - size_t size) +do_decrypt(struct GSC_KeyExchangeInfo *kx, + const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, + const void *in, + void *out, + size_t size) { - if (size != (uint16_t) size) - { - GNUNET_break (0); - return GNUNET_NO; - } + if (size != (uint16_t)size) + { + GNUNET_break(0); + return GNUNET_NO; + } if ((kx->status != GNUNET_CORE_KX_STATE_KEY_RECEIVED) && (kx->status != GNUNET_CORE_KX_STATE_UP) && (kx->status != GNUNET_CORE_KX_STATE_REKEY_SENT)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if (size != GNUNET_CRYPTO_symmetric_decrypt (in, - (uint16_t) size, - &kx->decrypt_key, - iv, - out)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# bytes decrypted"), - size, - GNUNET_NO); + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if (size != GNUNET_CRYPTO_symmetric_decrypt(in, + (uint16_t)size, + &kx->decrypt_key, + iv, + out)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# bytes decrypted"), + size, + GNUNET_NO); /* the following is too sensitive to write to log files by accident, so we require manual intervention to get this one... */ #if DEBUG_KX - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Decrypted %u bytes from `%s' using key %u, IV %u\n", - (unsigned int) size, - GNUNET_i2s (kx->peer), - (unsigned int) kx->decrypt_key.crc32, - GNUNET_CRYPTO_crc32_n (iv, sizeof (*iv))); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Decrypted %u bytes from `%s' using key %u, IV %u\n", + (unsigned int)size, + GNUNET_i2s(kx->peer), + (unsigned int)kx->decrypt_key.crc32, + GNUNET_CRYPTO_crc32_n(iv, sizeof(*iv))); #endif return GNUNET_OK; } @@ -701,7 +698,7 @@ do_decrypt (struct GSC_KeyExchangeInfo *kx, * @param kx key exchange context */ static void -send_key (struct GSC_KeyExchangeInfo *kx); +send_key(struct GSC_KeyExchangeInfo *kx); /** @@ -710,15 +707,15 @@ send_key (struct GSC_KeyExchangeInfo *kx); * @param cls our `struct GSC_KeyExchangeInfo` */ static void -set_key_retry_task (void *cls) +set_key_retry_task(void *cls) { struct GSC_KeyExchangeInfo *kx = cls; kx->retry_set_key_task = NULL; kx->set_key_retry_frequency = - GNUNET_TIME_STD_BACKOFF (kx->set_key_retry_frequency); - GNUNET_assert (GNUNET_CORE_KX_STATE_DOWN != kx->status); - send_key (kx); + GNUNET_TIME_STD_BACKOFF(kx->set_key_retry_frequency); + GNUNET_assert(GNUNET_CORE_KX_STATE_DOWN != kx->status); + send_key(kx); } @@ -728,7 +725,7 @@ set_key_retry_task (void *cls) * @param kx key exchange context to create PING for */ static void -setup_fresh_ping (struct GSC_KeyExchangeInfo *kx) +setup_fresh_ping(struct GSC_KeyExchangeInfo *kx) { struct PingMessage pp; struct PingMessage *pm; @@ -736,19 +733,19 @@ setup_fresh_ping (struct GSC_KeyExchangeInfo *kx) pm = &kx->ping; kx->ping_challenge = - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX); - pm->header.size = htons (sizeof (struct PingMessage)); - pm->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_PING); - pm->iv_seed = calculate_seed (kx); - derive_iv (&iv, &kx->encrypt_key, pm->iv_seed, kx->peer); + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX); + pm->header.size = htons(sizeof(struct PingMessage)); + pm->header.type = htons(GNUNET_MESSAGE_TYPE_CORE_PING); + pm->iv_seed = calculate_seed(kx); + derive_iv(&iv, &kx->encrypt_key, pm->iv_seed, kx->peer); pp.challenge = kx->ping_challenge; pp.target = *kx->peer; - do_encrypt (kx, - &iv, - &pp.target, - &pm->target, - sizeof (struct PingMessage) - - ((void *) &pm->target - (void *) pm)); + do_encrypt(kx, + &iv, + &pp.target, + &pm->target, + sizeof(struct PingMessage) - + ((void *)&pm->target - (void *)pm)); } @@ -764,41 +761,43 @@ setup_fresh_ping (struct GSC_KeyExchangeInfo *kx) * #GNUNET_SYSERR to stop further processing with error */ static int -deliver_message (void *cls, const struct GNUNET_MessageHeader *m) +deliver_message(void *cls, const struct GNUNET_MessageHeader *m) { struct GSC_KeyExchangeInfo *kx = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Decrypted message of type %d from %s\n", - ntohs (m->type), - GNUNET_i2s (kx->peer)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Decrypted message of type %d from %s\n", + ntohs(m->type), + GNUNET_i2s(kx->peer)); if (GNUNET_CORE_KX_STATE_UP != kx->status) - { - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# PAYLOAD dropped (out of order)"), - 1, - GNUNET_NO); - return GNUNET_OK; - } - switch (ntohs (m->type)) - { - case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP: - case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP: - GSC_SESSIONS_set_typemap (kx->peer, m); - return GNUNET_OK; - case GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP: - GSC_SESSIONS_confirm_typemap (kx->peer, m); - return GNUNET_OK; - default: - GSC_CLIENTS_deliver_message (kx->peer, - m, - ntohs (m->size), - GNUNET_CORE_OPTION_SEND_FULL_INBOUND); - GSC_CLIENTS_deliver_message (kx->peer, - m, - sizeof (struct GNUNET_MessageHeader), - GNUNET_CORE_OPTION_SEND_HDR_INBOUND); - } + { + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# PAYLOAD dropped (out of order)"), + 1, + GNUNET_NO); + return GNUNET_OK; + } + switch (ntohs(m->type)) + { + case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP: + case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP: + GSC_SESSIONS_set_typemap(kx->peer, m); + return GNUNET_OK; + + case GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP: + GSC_SESSIONS_confirm_typemap(kx->peer, m); + return GNUNET_OK; + + default: + GSC_CLIENTS_deliver_message(kx->peer, + m, + ntohs(m->size), + GNUNET_CORE_OPTION_SEND_FULL_INBOUND); + GSC_CLIENTS_deliver_message(kx->peer, + m, + sizeof(struct GNUNET_MessageHeader), + GNUNET_CORE_OPTION_SEND_HDR_INBOUND); + } return GNUNET_OK; } @@ -813,49 +812,49 @@ deliver_message (void *cls, const struct GNUNET_MessageHeader *m) * @return key exchange information context */ static void * -handle_transport_notify_connect (void *cls, - const struct GNUNET_PeerIdentity *pid, - struct GNUNET_MQ_Handle *mq) +handle_transport_notify_connect(void *cls, + const struct GNUNET_PeerIdentity *pid, + struct GNUNET_MQ_Handle *mq) { struct GSC_KeyExchangeInfo *kx; struct GNUNET_HashCode h1; struct GNUNET_HashCode h2; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Initiating key exchange with `%s'\n", - GNUNET_i2s (pid)); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# key exchanges initiated"), - 1, - GNUNET_NO); - kx = GNUNET_new (struct GSC_KeyExchangeInfo); - kx->mst = GNUNET_MST_create (&deliver_message, kx); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Initiating key exchange with `%s'\n", + GNUNET_i2s(pid)); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# key exchanges initiated"), + 1, + GNUNET_NO); + kx = GNUNET_new(struct GSC_KeyExchangeInfo); + kx->mst = GNUNET_MST_create(&deliver_message, kx); kx->mq = mq; kx->peer = pid; kx->set_key_retry_frequency = INITIAL_SET_KEY_RETRY_FREQUENCY; - GNUNET_CONTAINER_DLL_insert (kx_head, kx_tail, kx); + GNUNET_CONTAINER_DLL_insert(kx_head, kx_tail, kx); kx->status = GNUNET_CORE_KX_STATE_KEY_SENT; - monitor_notify_all (kx); - GNUNET_CRYPTO_hash (pid, sizeof (struct GNUNET_PeerIdentity), &h1); - GNUNET_CRYPTO_hash (&GSC_my_identity, - sizeof (struct GNUNET_PeerIdentity), - &h2); - if (0 < GNUNET_CRYPTO_hash_cmp (&h1, &h2)) - { - /* peer with "lower" identity starts KX, otherwise we typically end up - with both peers starting the exchange and transmit the 'set key' - message twice */ - send_key (kx); - } + monitor_notify_all(kx); + GNUNET_CRYPTO_hash(pid, sizeof(struct GNUNET_PeerIdentity), &h1); + GNUNET_CRYPTO_hash(&GSC_my_identity, + sizeof(struct GNUNET_PeerIdentity), + &h2); + if (0 < GNUNET_CRYPTO_hash_cmp(&h1, &h2)) + { + /* peer with "lower" identity starts KX, otherwise we typically end up + with both peers starting the exchange and transmit the 'set key' + message twice */ + send_key(kx); + } else - { - /* peer with "higher" identity starts a delayed KX, if the "lower" peer - * does not start a KX since it sees no reasons to do so */ - kx->retry_set_key_task = - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &set_key_retry_task, - kx); - } + { + /* peer with "higher" identity starts a delayed KX, if the "lower" peer + * does not start a KX since it sees no reasons to do so */ + kx->retry_set_key_task = + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &set_key_retry_task, + kx); + } return kx; } @@ -870,35 +869,35 @@ handle_transport_notify_connect (void *cls, * @param handler_cls the `struct GSC_KeyExchangeInfo` of the peer */ static void -handle_transport_notify_disconnect (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *handler_cls) +handle_transport_notify_disconnect(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *handler_cls) { struct GSC_KeyExchangeInfo *kx = handler_cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Peer `%s' disconnected from us.\n", - GNUNET_i2s (peer)); - GSC_SESSIONS_end (kx->peer); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# key exchanges stopped"), - 1, - GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Peer `%s' disconnected from us.\n", + GNUNET_i2s(peer)); + GSC_SESSIONS_end(kx->peer); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# key exchanges stopped"), + 1, + GNUNET_NO); if (NULL != kx->retry_set_key_task) - { - GNUNET_SCHEDULER_cancel (kx->retry_set_key_task); - kx->retry_set_key_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(kx->retry_set_key_task); + kx->retry_set_key_task = NULL; + } if (NULL != kx->keep_alive_task) - { - GNUNET_SCHEDULER_cancel (kx->keep_alive_task); - kx->keep_alive_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(kx->keep_alive_task); + kx->keep_alive_task = NULL; + } kx->status = GNUNET_CORE_KX_PEER_DISCONNECT; - monitor_notify_all (kx); - GNUNET_CONTAINER_DLL_remove (kx_head, kx_tail, kx); - GNUNET_MST_destroy (kx->mst); - GNUNET_free (kx); + monitor_notify_all(kx); + GNUNET_CONTAINER_DLL_remove(kx_head, kx_tail, kx); + GNUNET_MST_destroy(kx->mst); + GNUNET_free(kx); } @@ -908,16 +907,16 @@ handle_transport_notify_disconnect (void *cls, * @param kx key exchange context */ static void -send_ping (struct GSC_KeyExchangeInfo *kx) +send_ping(struct GSC_KeyExchangeInfo *kx) { struct GNUNET_MQ_Envelope *env; - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# PING messages transmitted"), - 1, - GNUNET_NO); - env = GNUNET_MQ_msg_copy (&kx->ping.header); - GNUNET_MQ_send (kx->mq, env); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# PING messages transmitted"), + 1, + GNUNET_NO); + env = GNUNET_MQ_msg_copy(&kx->ping.header); + GNUNET_MQ_send(kx->mq, env); } @@ -927,24 +926,24 @@ send_ping (struct GSC_KeyExchangeInfo *kx) * @param kx session to derive keys for */ static void -derive_session_keys (struct GSC_KeyExchangeInfo *kx) +derive_session_keys(struct GSC_KeyExchangeInfo *kx) { struct GNUNET_HashCode key_material; - if (GNUNET_OK != GNUNET_CRYPTO_ecc_ecdh (my_ephemeral_key, - &kx->other_ephemeral_key, - &key_material)) - { - GNUNET_break (0); - return; - } - derive_aes_key (&GSC_my_identity, kx->peer, &key_material, &kx->encrypt_key); - derive_aes_key (kx->peer, &GSC_my_identity, &key_material, &kx->decrypt_key); - memset (&key_material, 0, sizeof (key_material)); + if (GNUNET_OK != GNUNET_CRYPTO_ecc_ecdh(my_ephemeral_key, + &kx->other_ephemeral_key, + &key_material)) + { + GNUNET_break(0); + return; + } + derive_aes_key(&GSC_my_identity, kx->peer, &key_material, &kx->encrypt_key); + derive_aes_key(kx->peer, &GSC_my_identity, &key_material, &kx->decrypt_key); + memset(&key_material, 0, sizeof(key_material)); /* fresh key, reset sequence numbers */ kx->last_sequence_number_received = 0; kx->last_packets_bitmap = 0; - setup_fresh_ping (kx); + setup_fresh_ping(kx); } @@ -956,7 +955,7 @@ derive_session_keys (struct GSC_KeyExchangeInfo *kx) * @param m the set key message we received */ static void -handle_ephemeral_key (void *cls, const struct EphemeralKeyMessage *m) +handle_ephemeral_key(void *cls, const struct EphemeralKeyMessage *m) { struct GSC_KeyExchangeInfo *kx = cls; struct GNUNET_TIME_Absolute start_t; @@ -964,183 +963,193 @@ handle_ephemeral_key (void *cls, const struct EphemeralKeyMessage *m) struct GNUNET_TIME_Absolute now; enum GNUNET_CORE_KxState sender_status; - end_t = GNUNET_TIME_absolute_ntoh (m->expiration_time); + end_t = GNUNET_TIME_absolute_ntoh(m->expiration_time); if (((GNUNET_CORE_KX_STATE_KEY_RECEIVED == kx->status) || (GNUNET_CORE_KX_STATE_UP == kx->status) || (GNUNET_CORE_KX_STATE_REKEY_SENT == kx->status)) && (end_t.abs_value_us < kx->foreign_key_expires.abs_value_us)) - { - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# old ephemeral keys ignored"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Received expired EPHEMERAL_KEY from %s\n", - GNUNET_i2s (&m->origin_identity)); - return; - } - if (0 == memcmp (&m->ephemeral_key, - &kx->other_ephemeral_key, - sizeof (m->ephemeral_key))) - { - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# duplicate ephemeral keys ignored"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Ignoring duplicate EPHEMERAL_KEY from %s\n", - GNUNET_i2s (&m->origin_identity)); - return; - } - if (0 != memcmp (&m->origin_identity, - kx->peer, - sizeof (struct GNUNET_PeerIdentity))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Received EPHEMERAL_KEY from %s, but expected %s\n", - GNUNET_i2s (&m->origin_identity), - GNUNET_i2s_full (kx->peer)); - GNUNET_break_op (0); - return; - } - if ((ntohl (m->purpose.size) != - sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) + - sizeof (struct GNUNET_TIME_AbsoluteNBO) + - sizeof (struct GNUNET_TIME_AbsoluteNBO) + - sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) + - sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)) || + { + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# old ephemeral keys ignored"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Received expired EPHEMERAL_KEY from %s\n", + GNUNET_i2s(&m->origin_identity)); + return; + } + if (0 == memcmp(&m->ephemeral_key, + &kx->other_ephemeral_key, + sizeof(m->ephemeral_key))) + { + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# duplicate ephemeral keys ignored"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Ignoring duplicate EPHEMERAL_KEY from %s\n", + GNUNET_i2s(&m->origin_identity)); + return; + } + if (0 != memcmp(&m->origin_identity, + kx->peer, + sizeof(struct GNUNET_PeerIdentity))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Received EPHEMERAL_KEY from %s, but expected %s\n", + GNUNET_i2s(&m->origin_identity), + GNUNET_i2s_full(kx->peer)); + GNUNET_break_op(0); + return; + } + if ((ntohl(m->purpose.size) != + sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose) + + sizeof(struct GNUNET_TIME_AbsoluteNBO) + + sizeof(struct GNUNET_TIME_AbsoluteNBO) + + sizeof(struct GNUNET_CRYPTO_EddsaPublicKey) + + sizeof(struct GNUNET_CRYPTO_EddsaPublicKey)) || (GNUNET_OK != - GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY, - &m->purpose, - &m->signature, - &m->origin_identity.public_key))) - { - /* invalid signature */ - GNUNET_break_op (0); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# EPHEMERAL_KEYs rejected (bad signature)"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Received EPHEMERAL_KEY from %s with bad signature\n", - GNUNET_i2s (&m->origin_identity)); - return; - } - now = GNUNET_TIME_absolute_get (); - start_t = GNUNET_TIME_absolute_ntoh (m->creation_time); + GNUNET_CRYPTO_eddsa_verify(GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY, + &m->purpose, + &m->signature, + &m->origin_identity.public_key))) + { + /* invalid signature */ + GNUNET_break_op(0); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# EPHEMERAL_KEYs rejected (bad signature)"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Received EPHEMERAL_KEY from %s with bad signature\n", + GNUNET_i2s(&m->origin_identity)); + return; + } + now = GNUNET_TIME_absolute_get(); + start_t = GNUNET_TIME_absolute_ntoh(m->creation_time); if ((end_t.abs_value_us < - GNUNET_TIME_absolute_subtract (now, REKEY_TOLERANCE).abs_value_us) || + GNUNET_TIME_absolute_subtract(now, REKEY_TOLERANCE).abs_value_us) || (start_t.abs_value_us > - GNUNET_TIME_absolute_add (now, REKEY_TOLERANCE).abs_value_us)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_WARNING, - _ ( - "EPHEMERAL_KEY from peer `%s' rejected as its validity range does not match our system time (%llu not in [%llu,%llu]).\n"), - GNUNET_i2s (kx->peer), - (unsigned long long) now.abs_value_us, - (unsigned long long) start_t.abs_value_us, - (unsigned long long) end_t.abs_value_us); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# EPHEMERAL_KEY messages rejected due to time"), - 1, - GNUNET_NO); - return; - } + GNUNET_TIME_absolute_add(now, REKEY_TOLERANCE).abs_value_us)) + { + GNUNET_log( + GNUNET_ERROR_TYPE_WARNING, + _( + "EPHEMERAL_KEY from peer `%s' rejected as its validity range does not match our system time (%llu not in [%llu,%llu]).\n"), + GNUNET_i2s(kx->peer), + (unsigned long long)now.abs_value_us, + (unsigned long long)start_t.abs_value_us, + (unsigned long long)end_t.abs_value_us); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# EPHEMERAL_KEY messages rejected due to time"), + 1, + GNUNET_NO); + return; + } #if DEBUG_KX { struct GNUNET_HashCode eh; - GNUNET_CRYPTO_hash (&m->ephemeral_key, sizeof (m->ephemeral_key), &eh); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received valid EPHEMERAL_KEY `%s' from `%s' in state %d.\n", - GNUNET_h2s (&eh), - GNUNET_i2s (kx->peer), - kx->status); + GNUNET_CRYPTO_hash(&m->ephemeral_key, sizeof(m->ephemeral_key), &eh); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received valid EPHEMERAL_KEY `%s' from `%s' in state %d.\n", + GNUNET_h2s(&eh), + GNUNET_i2s(kx->peer), + kx->status); } #endif - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# valid ephemeral keys received"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# valid ephemeral keys received"), + 1, + GNUNET_NO); kx->other_ephemeral_key = m->ephemeral_key; kx->foreign_key_expires = end_t; - derive_session_keys (kx); + derive_session_keys(kx); /* check if we still need to send the sender our key */ - sender_status = (enum GNUNET_CORE_KxState) ntohl (m->sender_status); + sender_status = (enum GNUNET_CORE_KxState)ntohl(m->sender_status); switch (sender_status) - { - case GNUNET_CORE_KX_STATE_DOWN: - GNUNET_break_op (0); - break; - case GNUNET_CORE_KX_STATE_KEY_SENT: - /* fine, need to send our key after updating our status, see below */ - GSC_SESSIONS_reinit (kx->peer); - break; - case GNUNET_CORE_KX_STATE_KEY_RECEIVED: - /* other peer already got our key, but typemap did go down */ - GSC_SESSIONS_reinit (kx->peer); - break; - case GNUNET_CORE_KX_STATE_UP: - /* other peer already got our key, typemap NOT down */ - break; - case GNUNET_CORE_KX_STATE_REKEY_SENT: - /* other peer already got our key, typemap NOT down */ - break; - default: - GNUNET_break (0); - break; - } + { + case GNUNET_CORE_KX_STATE_DOWN: + GNUNET_break_op(0); + break; + + case GNUNET_CORE_KX_STATE_KEY_SENT: + /* fine, need to send our key after updating our status, see below */ + GSC_SESSIONS_reinit(kx->peer); + break; + + case GNUNET_CORE_KX_STATE_KEY_RECEIVED: + /* other peer already got our key, but typemap did go down */ + GSC_SESSIONS_reinit(kx->peer); + break; + + case GNUNET_CORE_KX_STATE_UP: + /* other peer already got our key, typemap NOT down */ + break; + + case GNUNET_CORE_KX_STATE_REKEY_SENT: + /* other peer already got our key, typemap NOT down */ + break; + + default: + GNUNET_break(0); + break; + } /* check if we need to confirm everything is fine via PING + PONG */ switch (kx->status) - { - case GNUNET_CORE_KX_STATE_DOWN: - GNUNET_assert (NULL == kx->keep_alive_task); - kx->status = GNUNET_CORE_KX_STATE_KEY_RECEIVED; - monitor_notify_all (kx); - if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status) - send_key (kx); - else - send_ping (kx); - break; - case GNUNET_CORE_KX_STATE_KEY_SENT: - GNUNET_assert (NULL == kx->keep_alive_task); - kx->status = GNUNET_CORE_KX_STATE_KEY_RECEIVED; - monitor_notify_all (kx); - if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status) - send_key (kx); - else - send_ping (kx); - break; - case GNUNET_CORE_KX_STATE_KEY_RECEIVED: - GNUNET_assert (NULL == kx->keep_alive_task); - if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status) - send_key (kx); - else - send_ping (kx); - break; - case GNUNET_CORE_KX_STATE_UP: - kx->status = GNUNET_CORE_KX_STATE_REKEY_SENT; - monitor_notify_all (kx); - if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status) - send_key (kx); - else - send_ping (kx); - break; - case GNUNET_CORE_KX_STATE_REKEY_SENT: - if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status) - send_key (kx); - else - send_ping (kx); - break; - default: - GNUNET_break (0); - break; - } + { + case GNUNET_CORE_KX_STATE_DOWN: + GNUNET_assert(NULL == kx->keep_alive_task); + kx->status = GNUNET_CORE_KX_STATE_KEY_RECEIVED; + monitor_notify_all(kx); + if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status) + send_key(kx); + else + send_ping(kx); + break; + + case GNUNET_CORE_KX_STATE_KEY_SENT: + GNUNET_assert(NULL == kx->keep_alive_task); + kx->status = GNUNET_CORE_KX_STATE_KEY_RECEIVED; + monitor_notify_all(kx); + if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status) + send_key(kx); + else + send_ping(kx); + break; + + case GNUNET_CORE_KX_STATE_KEY_RECEIVED: + GNUNET_assert(NULL == kx->keep_alive_task); + if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status) + send_key(kx); + else + send_ping(kx); + break; + + case GNUNET_CORE_KX_STATE_UP: + kx->status = GNUNET_CORE_KX_STATE_REKEY_SENT; + monitor_notify_all(kx); + if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status) + send_key(kx); + else + send_ping(kx); + break; + + case GNUNET_CORE_KX_STATE_REKEY_SENT: + if (GNUNET_CORE_KX_STATE_KEY_SENT == sender_status) + send_key(kx); + else + send_ping(kx); + break; + + default: + GNUNET_break(0); + break; + } } @@ -1152,7 +1161,7 @@ handle_ephemeral_key (void *cls, const struct EphemeralKeyMessage *m) * @param m the encrypted PING message itself */ static void -handle_ping (void *cls, const struct PingMessage *m) +handle_ping(void *cls, const struct PingMessage *m) { struct GSC_KeyExchangeInfo *kx = cls; struct PingMessage t; @@ -1161,70 +1170,70 @@ handle_ping (void *cls, const struct PingMessage *m) struct GNUNET_MQ_Envelope *env; struct GNUNET_CRYPTO_SymmetricInitializationVector iv; - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# PING messages received"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# PING messages received"), + 1, + GNUNET_NO); if ((kx->status != GNUNET_CORE_KX_STATE_KEY_RECEIVED) && (kx->status != GNUNET_CORE_KX_STATE_UP) && (kx->status != GNUNET_CORE_KX_STATE_REKEY_SENT)) - { - /* ignore */ - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# PING messages dropped (out of order)"), - 1, - GNUNET_NO); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Core service receives PING request from `%s'.\n", - GNUNET_i2s (kx->peer)); - derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity); - if (GNUNET_OK != do_decrypt (kx, - &iv, - &m->target, - &t.target, - sizeof (struct PingMessage) - - ((void *) &m->target - (void *) m))) - { - GNUNET_break_op (0); - return; - } + { + /* ignore */ + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# PING messages dropped (out of order)"), + 1, + GNUNET_NO); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Core service receives PING request from `%s'.\n", + GNUNET_i2s(kx->peer)); + derive_iv(&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity); + if (GNUNET_OK != do_decrypt(kx, + &iv, + &m->target, + &t.target, + sizeof(struct PingMessage) - + ((void *)&m->target - (void *)m))) + { + GNUNET_break_op(0); + return; + } if (0 != - memcmp (&t.target, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity))) - { - if (GNUNET_CORE_KX_STATE_REKEY_SENT != kx->status) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Decryption of PING from peer `%s' failed, PING for `%s'?\n", - GNUNET_i2s (kx->peer), - GNUNET_i2s2 (&t.target)); - else - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Decryption of PING from peer `%s' failed after rekey (harmless)\n", - GNUNET_i2s (kx->peer)); - GNUNET_break_op (0); - return; - } + memcmp(&t.target, &GSC_my_identity, sizeof(struct GNUNET_PeerIdentity))) + { + if (GNUNET_CORE_KX_STATE_REKEY_SENT != kx->status) + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Decryption of PING from peer `%s' failed, PING for `%s'?\n", + GNUNET_i2s(kx->peer), + GNUNET_i2s2(&t.target)); + else + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Decryption of PING from peer `%s' failed after rekey (harmless)\n", + GNUNET_i2s(kx->peer)); + GNUNET_break_op(0); + return; + } /* construct PONG */ tx.reserved = 0; tx.challenge = t.challenge; tx.target = t.target; - env = GNUNET_MQ_msg (tp, GNUNET_MESSAGE_TYPE_CORE_PONG); - tp->iv_seed = calculate_seed (kx); - derive_pong_iv (&iv, &kx->encrypt_key, tp->iv_seed, t.challenge, kx->peer); - do_encrypt (kx, - &iv, - &tx.challenge, - &tp->challenge, - sizeof (struct PongMessage) - - ((void *) &tp->challenge - (void *) tp)); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# PONG messages created"), - 1, - GNUNET_NO); - GNUNET_MQ_send (kx->mq, env); + env = GNUNET_MQ_msg(tp, GNUNET_MESSAGE_TYPE_CORE_PONG); + tp->iv_seed = calculate_seed(kx); + derive_pong_iv(&iv, &kx->encrypt_key, tp->iv_seed, t.challenge, kx->peer); + do_encrypt(kx, + &iv, + &tx.challenge, + &tp->challenge, + sizeof(struct PongMessage) - + ((void *)&tp->challenge - (void *)tp)); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# PONG messages created"), + 1, + GNUNET_NO); + GNUNET_MQ_send(kx->mq, env); } @@ -1235,39 +1244,39 @@ handle_ping (void *cls, const struct PingMessage *m) * @param cls the `struct GSC_KeyExchangeInfo` */ static void -send_keep_alive (void *cls) +send_keep_alive(void *cls) { struct GSC_KeyExchangeInfo *kx = cls; struct GNUNET_TIME_Relative retry; struct GNUNET_TIME_Relative left; kx->keep_alive_task = NULL; - left = GNUNET_TIME_absolute_get_remaining (kx->timeout); + left = GNUNET_TIME_absolute_get_remaining(kx->timeout); if (0 == left.rel_value_us) - { - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# sessions terminated by timeout"), - 1, - GNUNET_NO); - GSC_SESSIONS_end (kx->peer); - kx->status = GNUNET_CORE_KX_STATE_KEY_SENT; - monitor_notify_all (kx); - send_key (kx); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending KEEPALIVE to `%s'\n", - GNUNET_i2s (kx->peer)); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# keepalive messages sent"), - 1, - GNUNET_NO); - setup_fresh_ping (kx); - send_ping (kx); - retry = GNUNET_TIME_relative_max (GNUNET_TIME_relative_divide (left, 2), - MIN_PING_FREQUENCY); + { + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# sessions terminated by timeout"), + 1, + GNUNET_NO); + GSC_SESSIONS_end(kx->peer); + kx->status = GNUNET_CORE_KX_STATE_KEY_SENT; + monitor_notify_all(kx); + send_key(kx); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending KEEPALIVE to `%s'\n", + GNUNET_i2s(kx->peer)); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# keepalive messages sent"), + 1, + GNUNET_NO); + setup_fresh_ping(kx); + send_ping(kx); + retry = GNUNET_TIME_relative_max(GNUNET_TIME_relative_divide(left, 2), + MIN_PING_FREQUENCY); kx->keep_alive_task = - GNUNET_SCHEDULER_add_delayed (retry, &send_keep_alive, kx); + GNUNET_SCHEDULER_add_delayed(retry, &send_keep_alive, kx); } @@ -1279,24 +1288,24 @@ send_keep_alive (void *cls) * @param kx key exchange where we saw activity */ static void -update_timeout (struct GSC_KeyExchangeInfo *kx) +update_timeout(struct GSC_KeyExchangeInfo *kx) { struct GNUNET_TIME_Relative delta; kx->timeout = - GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT); + GNUNET_TIME_relative_to_absolute(GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT); delta = - GNUNET_TIME_absolute_get_difference (kx->last_notify_timeout, kx->timeout); + GNUNET_TIME_absolute_get_difference(kx->last_notify_timeout, kx->timeout); if (delta.rel_value_us > 5LL * 1000LL * 1000LL) - { - /* we only notify monitors about timeout changes if those - are bigger than the threshold (5s) */ - monitor_notify_all (kx); - } + { + /* we only notify monitors about timeout changes if those + are bigger than the threshold (5s) */ + monitor_notify_all(kx); + } if (NULL != kx->keep_alive_task) - GNUNET_SCHEDULER_cancel (kx->keep_alive_task); - kx->keep_alive_task = GNUNET_SCHEDULER_add_delayed ( - GNUNET_TIME_relative_divide (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2), + GNUNET_SCHEDULER_cancel(kx->keep_alive_task); + kx->keep_alive_task = GNUNET_SCHEDULER_add_delayed( + GNUNET_TIME_relative_divide(GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2), &send_keep_alive, kx); } @@ -1309,131 +1318,141 @@ update_timeout (struct GSC_KeyExchangeInfo *kx) * @param m the encrypted PONG message itself */ static void -handle_pong (void *cls, const struct PongMessage *m) +handle_pong(void *cls, const struct PongMessage *m) { struct GSC_KeyExchangeInfo *kx = cls; struct PongMessage t; struct GNUNET_CRYPTO_SymmetricInitializationVector iv; - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# PONG messages received"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# PONG messages received"), + 1, + GNUNET_NO); switch (kx->status) - { - case GNUNET_CORE_KX_STATE_DOWN: - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# PONG messages dropped (connection down)"), - 1, - GNUNET_NO); - return; - case GNUNET_CORE_KX_STATE_KEY_SENT: - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# PONG messages dropped (out of order)"), - 1, - GNUNET_NO); - return; - case GNUNET_CORE_KX_STATE_KEY_RECEIVED: - break; - case GNUNET_CORE_KX_STATE_UP: - break; - case GNUNET_CORE_KX_STATE_REKEY_SENT: - break; - default: - GNUNET_break (0); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Core service receives PONG response from `%s'.\n", - GNUNET_i2s (kx->peer)); + { + case GNUNET_CORE_KX_STATE_DOWN: + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# PONG messages dropped (connection down)"), + 1, + GNUNET_NO); + return; + + case GNUNET_CORE_KX_STATE_KEY_SENT: + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# PONG messages dropped (out of order)"), + 1, + GNUNET_NO); + return; + + case GNUNET_CORE_KX_STATE_KEY_RECEIVED: + break; + + case GNUNET_CORE_KX_STATE_UP: + break; + + case GNUNET_CORE_KX_STATE_REKEY_SENT: + break; + + default: + GNUNET_break(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Core service receives PONG response from `%s'.\n", + GNUNET_i2s(kx->peer)); /* mark as garbage, just to be sure */ - memset (&t, 255, sizeof (t)); - derive_pong_iv (&iv, - &kx->decrypt_key, - m->iv_seed, - kx->ping_challenge, - &GSC_my_identity); - if (GNUNET_OK != do_decrypt (kx, - &iv, - &m->challenge, - &t.challenge, - sizeof (struct PongMessage) - - ((void *) &m->challenge - (void *) m))) - { - GNUNET_break_op (0); - return; - } - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# PONG messages decrypted"), - 1, - GNUNET_NO); + memset(&t, 255, sizeof(t)); + derive_pong_iv(&iv, + &kx->decrypt_key, + m->iv_seed, + kx->ping_challenge, + &GSC_my_identity); + if (GNUNET_OK != do_decrypt(kx, + &iv, + &m->challenge, + &t.challenge, + sizeof(struct PongMessage) - + ((void *)&m->challenge - (void *)m))) + { + GNUNET_break_op(0); + return; + } + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# PONG messages decrypted"), + 1, + GNUNET_NO); if ((0 != - memcmp (&t.target, kx->peer, sizeof (struct GNUNET_PeerIdentity))) || + memcmp(&t.target, kx->peer, sizeof(struct GNUNET_PeerIdentity))) || (kx->ping_challenge != t.challenge)) - { - /* PONG malformed */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received malformed PONG wanted sender `%s' with challenge %u\n", - GNUNET_i2s (kx->peer), - (unsigned int) kx->ping_challenge); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received malformed PONG received from `%s' with challenge %u\n", - GNUNET_i2s (&t.target), - (unsigned int) t.challenge); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received valid PONG from `%s'\n", - GNUNET_i2s (kx->peer)); + { + /* PONG malformed */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received malformed PONG wanted sender `%s' with challenge %u\n", + GNUNET_i2s(kx->peer), + (unsigned int)kx->ping_challenge); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received malformed PONG received from `%s' with challenge %u\n", + GNUNET_i2s(&t.target), + (unsigned int)t.challenge); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received valid PONG from `%s'\n", + GNUNET_i2s(kx->peer)); /* no need to resend key any longer */ if (NULL != kx->retry_set_key_task) - { - GNUNET_SCHEDULER_cancel (kx->retry_set_key_task); - kx->retry_set_key_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(kx->retry_set_key_task); + kx->retry_set_key_task = NULL; + } switch (kx->status) - { - case GNUNET_CORE_KX_STATE_DOWN: - GNUNET_assert (0); /* should be impossible */ - return; - case GNUNET_CORE_KX_STATE_KEY_SENT: - GNUNET_assert (0); /* should be impossible */ - return; - case GNUNET_CORE_KX_STATE_KEY_RECEIVED: - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# session keys confirmed via PONG"), - 1, - GNUNET_NO); - kx->status = GNUNET_CORE_KX_STATE_UP; - monitor_notify_all (kx); - GSC_SESSIONS_create (kx->peer, kx); - GNUNET_assert (NULL == kx->keep_alive_task); - update_timeout (kx); - break; - case GNUNET_CORE_KX_STATE_UP: - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# timeouts prevented via PONG"), - 1, - GNUNET_NO); - update_timeout (kx); - break; - case GNUNET_CORE_KX_STATE_REKEY_SENT: - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# rekey operations confirmed via PONG"), - 1, - GNUNET_NO); - kx->status = GNUNET_CORE_KX_STATE_UP; - monitor_notify_all (kx); - update_timeout (kx); - break; - default: - GNUNET_break (0); - break; - } + { + case GNUNET_CORE_KX_STATE_DOWN: + GNUNET_assert(0); /* should be impossible */ + return; + + case GNUNET_CORE_KX_STATE_KEY_SENT: + GNUNET_assert(0); /* should be impossible */ + return; + + case GNUNET_CORE_KX_STATE_KEY_RECEIVED: + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# session keys confirmed via PONG"), + 1, + GNUNET_NO); + kx->status = GNUNET_CORE_KX_STATE_UP; + monitor_notify_all(kx); + GSC_SESSIONS_create(kx->peer, kx); + GNUNET_assert(NULL == kx->keep_alive_task); + update_timeout(kx); + break; + + case GNUNET_CORE_KX_STATE_UP: + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# timeouts prevented via PONG"), + 1, + GNUNET_NO); + update_timeout(kx); + break; + + case GNUNET_CORE_KX_STATE_REKEY_SENT: + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# rekey operations confirmed via PONG"), + 1, + GNUNET_NO); + kx->status = GNUNET_CORE_KX_STATE_UP; + monitor_notify_all(kx); + update_timeout(kx); + break; + + default: + GNUNET_break(0); + break; + } } @@ -1443,40 +1462,40 @@ handle_pong (void *cls, const struct PongMessage *m) * @param kx key exchange context */ static void -send_key (struct GSC_KeyExchangeInfo *kx) +send_key(struct GSC_KeyExchangeInfo *kx) { struct GNUNET_MQ_Envelope *env; - GNUNET_assert (GNUNET_CORE_KX_STATE_DOWN != kx->status); + GNUNET_assert(GNUNET_CORE_KX_STATE_DOWN != kx->status); if (NULL != kx->retry_set_key_task) - { - GNUNET_SCHEDULER_cancel (kx->retry_set_key_task); - kx->retry_set_key_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(kx->retry_set_key_task); + kx->retry_set_key_task = NULL; + } /* always update sender status in SET KEY message */ #if DEBUG_KX { struct GNUNET_HashCode hc; - GNUNET_CRYPTO_hash (¤t_ekm.ephemeral_key, - sizeof (current_ekm.ephemeral_key), - &hc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending EPHEMERAL_KEY %s to `%s' (my status: %d)\n", - GNUNET_h2s (&hc), - GNUNET_i2s (kx->peer), - kx->status); + GNUNET_CRYPTO_hash(¤t_ekm.ephemeral_key, + sizeof(current_ekm.ephemeral_key), + &hc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending EPHEMERAL_KEY %s to `%s' (my status: %d)\n", + GNUNET_h2s(&hc), + GNUNET_i2s(kx->peer), + kx->status); } #endif - current_ekm.sender_status = htonl ((int32_t) (kx->status)); - env = GNUNET_MQ_msg_copy (¤t_ekm.header); - GNUNET_MQ_send (kx->mq, env); + current_ekm.sender_status = htonl((int32_t)(kx->status)); + env = GNUNET_MQ_msg_copy(¤t_ekm.header); + GNUNET_MQ_send(kx->mq, env); if (GNUNET_CORE_KX_STATE_KEY_SENT != kx->status) - send_ping (kx); + send_ping(kx); kx->retry_set_key_task = - GNUNET_SCHEDULER_add_delayed (kx->set_key_retry_frequency, - &set_key_retry_task, - kx); + GNUNET_SCHEDULER_add_delayed(kx->set_key_retry_frequency, + &set_key_retry_task, + kx); } @@ -1488,11 +1507,11 @@ send_key (struct GSC_KeyExchangeInfo *kx) * @param payload_size number of bytes in @a payload */ void -GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx, - const void *payload, - size_t payload_size) +GSC_KX_encrypt_and_transmit(struct GSC_KeyExchangeInfo *kx, + const void *payload, + size_t payload_size) { - size_t used = payload_size + sizeof (struct EncryptedMessage); + size_t used = payload_size + sizeof(struct EncryptedMessage); char pbuf[used]; /* plaintext */ struct EncryptedMessage *em; /* encrypted message */ struct EncryptedMessage *ph; /* plaintext header */ @@ -1500,55 +1519,55 @@ GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx, struct GNUNET_CRYPTO_SymmetricInitializationVector iv; struct GNUNET_CRYPTO_AuthKey auth_key; - ph = (struct EncryptedMessage *) pbuf; - ph->sequence_number = htonl (++kx->last_sequence_number_sent); - ph->iv_seed = calculate_seed (kx); + ph = (struct EncryptedMessage *)pbuf; + ph->sequence_number = htonl(++kx->last_sequence_number_sent); + ph->iv_seed = calculate_seed(kx); ph->reserved = 0; - ph->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ()); - GNUNET_memcpy (&ph[1], payload, payload_size); - env = GNUNET_MQ_msg_extra (em, - payload_size, - GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE); + ph->timestamp = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get()); + GNUNET_memcpy(&ph[1], payload, payload_size); + env = GNUNET_MQ_msg_extra(em, + payload_size, + GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE); em->iv_seed = ph->iv_seed; - derive_iv (&iv, &kx->encrypt_key, ph->iv_seed, kx->peer); - GNUNET_assert (GNUNET_OK == do_encrypt (kx, - &iv, - &ph->sequence_number, - &em->sequence_number, - used - ENCRYPTED_HEADER_SIZE)); + derive_iv(&iv, &kx->encrypt_key, ph->iv_seed, kx->peer); + GNUNET_assert(GNUNET_OK == do_encrypt(kx, + &iv, + &ph->sequence_number, + &em->sequence_number, + used - ENCRYPTED_HEADER_SIZE)); #if DEBUG_KX { struct GNUNET_HashCode hc; - GNUNET_CRYPTO_hash (&ph->sequence_number, - used - ENCRYPTED_HEADER_SIZE, - &hc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Encrypted payload `%s' of %u bytes for %s\n", - GNUNET_h2s (&hc), - (unsigned int) (used - ENCRYPTED_HEADER_SIZE), - GNUNET_i2s (kx->peer)); + GNUNET_CRYPTO_hash(&ph->sequence_number, + used - ENCRYPTED_HEADER_SIZE, + &hc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Encrypted payload `%s' of %u bytes for %s\n", + GNUNET_h2s(&hc), + (unsigned int)(used - ENCRYPTED_HEADER_SIZE), + GNUNET_i2s(kx->peer)); } #endif - derive_auth_key (&auth_key, &kx->encrypt_key, ph->iv_seed); - GNUNET_CRYPTO_hmac (&auth_key, - &em->sequence_number, - used - ENCRYPTED_HEADER_SIZE, - &em->hmac); + derive_auth_key(&auth_key, &kx->encrypt_key, ph->iv_seed); + GNUNET_CRYPTO_hmac(&auth_key, + &em->sequence_number, + used - ENCRYPTED_HEADER_SIZE, + &em->hmac); #if DEBUG_KX { struct GNUNET_HashCode hc; - GNUNET_CRYPTO_hash (&auth_key, sizeof (auth_key), &hc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "For peer %s, used AC %s to create hmac %s\n", - GNUNET_i2s (kx->peer), - GNUNET_h2s (&hc), - GNUNET_h2s2 (&em->hmac)); + GNUNET_CRYPTO_hash(&auth_key, sizeof(auth_key), &hc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "For peer %s, used AC %s to create hmac %s\n", + GNUNET_i2s(kx->peer), + GNUNET_h2s(&hc), + GNUNET_h2s2(&em->hmac)); } #endif kx->has_excess_bandwidth = GNUNET_NO; - GNUNET_MQ_send (kx->mq, env); + GNUNET_MQ_send(kx->mq, env); } @@ -1561,15 +1580,15 @@ GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx, * @return #GNUNET_OK if @a msg is well-formed (size-wise) */ static int -check_encrypted (void *cls, const struct EncryptedMessage *m) +check_encrypted(void *cls, const struct EncryptedMessage *m) { - uint16_t size = ntohs (m->header.size) - sizeof (*m); + uint16_t size = ntohs(m->header.size) - sizeof(*m); - if (size < sizeof (struct GNUNET_MessageHeader)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + if (size < sizeof(struct GNUNET_MessageHeader)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1582,7 +1601,7 @@ check_encrypted (void *cls, const struct EncryptedMessage *m) * @param m encrypted message */ static void -handle_encrypted (void *cls, const struct EncryptedMessage *m) +handle_encrypted(void *cls, const struct EncryptedMessage *m) { struct GSC_KeyExchangeInfo *kx = cls; struct EncryptedMessage *pt; /* plaintext */ @@ -1591,183 +1610,183 @@ handle_encrypted (void *cls, const struct EncryptedMessage *m) struct GNUNET_TIME_Absolute t; struct GNUNET_CRYPTO_SymmetricInitializationVector iv; struct GNUNET_CRYPTO_AuthKey auth_key; - uint16_t size = ntohs (m->header.size); + uint16_t size = ntohs(m->header.size); char buf[size] GNUNET_ALIGN; if (GNUNET_CORE_KX_STATE_UP != kx->status) - { - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# DATA message dropped (out of order)"), - 1, - GNUNET_NO); - return; - } + { + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# DATA message dropped (out of order)"), + 1, + GNUNET_NO); + return; + } if (0 == - GNUNET_TIME_absolute_get_remaining (kx->foreign_key_expires).rel_value_us) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_WARNING, - _ ( - "Session to peer `%s' went down due to key expiration (should not happen)\n"), - GNUNET_i2s (kx->peer)); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# sessions terminated by key expiration"), - 1, - GNUNET_NO); - GSC_SESSIONS_end (kx->peer); - if (NULL != kx->keep_alive_task) + GNUNET_TIME_absolute_get_remaining(kx->foreign_key_expires).rel_value_us) { - GNUNET_SCHEDULER_cancel (kx->keep_alive_task); - kx->keep_alive_task = NULL; + GNUNET_log( + GNUNET_ERROR_TYPE_WARNING, + _( + "Session to peer `%s' went down due to key expiration (should not happen)\n"), + GNUNET_i2s(kx->peer)); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# sessions terminated by key expiration"), + 1, + GNUNET_NO); + GSC_SESSIONS_end(kx->peer); + if (NULL != kx->keep_alive_task) + { + GNUNET_SCHEDULER_cancel(kx->keep_alive_task); + kx->keep_alive_task = NULL; + } + kx->status = GNUNET_CORE_KX_STATE_KEY_SENT; + monitor_notify_all(kx); + send_key(kx); + return; } - kx->status = GNUNET_CORE_KX_STATE_KEY_SENT; - monitor_notify_all (kx); - send_key (kx); - return; - } /* validate hash */ #if DEBUG_KX { struct GNUNET_HashCode hc; - GNUNET_CRYPTO_hash (&m->sequence_number, size - ENCRYPTED_HEADER_SIZE, &hc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received encrypted payload `%s' of %u bytes from %s\n", - GNUNET_h2s (&hc), - (unsigned int) (size - ENCRYPTED_HEADER_SIZE), - GNUNET_i2s (kx->peer)); + GNUNET_CRYPTO_hash(&m->sequence_number, size - ENCRYPTED_HEADER_SIZE, &hc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received encrypted payload `%s' of %u bytes from %s\n", + GNUNET_h2s(&hc), + (unsigned int)(size - ENCRYPTED_HEADER_SIZE), + GNUNET_i2s(kx->peer)); } #endif - derive_auth_key (&auth_key, &kx->decrypt_key, m->iv_seed); - GNUNET_CRYPTO_hmac (&auth_key, - &m->sequence_number, - size - ENCRYPTED_HEADER_SIZE, - &ph); + derive_auth_key(&auth_key, &kx->decrypt_key, m->iv_seed); + GNUNET_CRYPTO_hmac(&auth_key, + &m->sequence_number, + size - ENCRYPTED_HEADER_SIZE, + &ph); #if DEBUG_KX { struct GNUNET_HashCode hc; - GNUNET_CRYPTO_hash (&auth_key, sizeof (auth_key), &hc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "For peer %s, used AC %s to verify hmac %s\n", - GNUNET_i2s (kx->peer), - GNUNET_h2s (&hc), - GNUNET_h2s2 (&m->hmac)); + GNUNET_CRYPTO_hash(&auth_key, sizeof(auth_key), &hc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "For peer %s, used AC %s to verify hmac %s\n", + GNUNET_i2s(kx->peer), + GNUNET_h2s(&hc), + GNUNET_h2s2(&m->hmac)); } #endif - if (0 != memcmp (&ph, &m->hmac, sizeof (struct GNUNET_HashCode))) - { - /* checksum failed */ - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Failed checksum validation for a message from `%s'\n", - GNUNET_i2s (kx->peer)); - return; - } - derive_iv (&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity); + if (0 != memcmp(&ph, &m->hmac, sizeof(struct GNUNET_HashCode))) + { + /* checksum failed */ + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Failed checksum validation for a message from `%s'\n", + GNUNET_i2s(kx->peer)); + return; + } + derive_iv(&iv, &kx->decrypt_key, m->iv_seed, &GSC_my_identity); /* decrypt */ - if (GNUNET_OK != do_decrypt (kx, - &iv, - &m->sequence_number, - &buf[ENCRYPTED_HEADER_SIZE], - size - ENCRYPTED_HEADER_SIZE)) - { - GNUNET_break_op (0); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Decrypted %u bytes from %s\n", - (unsigned int) (size - ENCRYPTED_HEADER_SIZE), - GNUNET_i2s (kx->peer)); - pt = (struct EncryptedMessage *) buf; + if (GNUNET_OK != do_decrypt(kx, + &iv, + &m->sequence_number, + &buf[ENCRYPTED_HEADER_SIZE], + size - ENCRYPTED_HEADER_SIZE)) + { + GNUNET_break_op(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Decrypted %u bytes from %s\n", + (unsigned int)(size - ENCRYPTED_HEADER_SIZE), + GNUNET_i2s(kx->peer)); + pt = (struct EncryptedMessage *)buf; /* validate sequence number */ - snum = ntohl (pt->sequence_number); + snum = ntohl(pt->sequence_number); if (kx->last_sequence_number_received == snum) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received duplicate message, ignoring.\n"); - /* duplicate, ignore */ - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# bytes dropped (duplicates)"), - size, - GNUNET_NO); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received duplicate message, ignoring.\n"); + /* duplicate, ignore */ + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# bytes dropped (duplicates)"), + size, + GNUNET_NO); + return; + } if ((kx->last_sequence_number_received > snum) && (kx->last_sequence_number_received - snum > 32)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ancient out of sequence message, ignoring.\n"); - /* ancient out of sequence, ignore */ - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# bytes dropped (out of sequence)"), - size, - GNUNET_NO); - return; - } - if (kx->last_sequence_number_received > snum) - { - uint32_t rotbit = 1U << (kx->last_sequence_number_received - snum - 1); - - if ((kx->last_packets_bitmap & rotbit) != 0) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received duplicate message, ignoring.\n"); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# bytes dropped (duplicates)"), - size, - GNUNET_NO); - /* duplicate, ignore */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ancient out of sequence message, ignoring.\n"); + /* ancient out of sequence, ignore */ + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# bytes dropped (out of sequence)"), + size, + GNUNET_NO); return; } - kx->last_packets_bitmap |= rotbit; - } + if (kx->last_sequence_number_received > snum) + { + uint32_t rotbit = 1U << (kx->last_sequence_number_received - snum - 1); + + if ((kx->last_packets_bitmap & rotbit) != 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received duplicate message, ignoring.\n"); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# bytes dropped (duplicates)"), + size, + GNUNET_NO); + /* duplicate, ignore */ + return; + } + kx->last_packets_bitmap |= rotbit; + } if (kx->last_sequence_number_received < snum) - { - unsigned int shift = (snum - kx->last_sequence_number_received); + { + unsigned int shift = (snum - kx->last_sequence_number_received); - if (shift >= 8 * sizeof (kx->last_packets_bitmap)) - kx->last_packets_bitmap = 0; - else - kx->last_packets_bitmap <<= shift; - kx->last_sequence_number_received = snum; - } + if (shift >= 8 * sizeof(kx->last_packets_bitmap)) + kx->last_packets_bitmap = 0; + else + kx->last_packets_bitmap <<= shift; + kx->last_sequence_number_received = snum; + } /* check timestamp */ - t = GNUNET_TIME_absolute_ntoh (pt->timestamp); - if (GNUNET_TIME_absolute_get_duration (t).rel_value_us > + t = GNUNET_TIME_absolute_ntoh(pt->timestamp); + if (GNUNET_TIME_absolute_get_duration(t).rel_value_us > MAX_MESSAGE_AGE.rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Message received far too old (%s). Content ignored.\n", - GNUNET_STRINGS_relative_time_to_string ( - GNUNET_TIME_absolute_get_duration (t), - GNUNET_YES)); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# bytes dropped (ancient message)"), - size, - GNUNET_NO); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Message received far too old (%s). Content ignored.\n", + GNUNET_STRINGS_relative_time_to_string( + GNUNET_TIME_absolute_get_duration(t), + GNUNET_YES)); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# bytes dropped (ancient message)"), + size, + GNUNET_NO); + return; + } /* process decrypted message(s) */ - update_timeout (kx); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# bytes of payload decrypted"), - size - sizeof (struct EncryptedMessage), - GNUNET_NO); + update_timeout(kx); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# bytes of payload decrypted"), + size - sizeof(struct EncryptedMessage), + GNUNET_NO); if (GNUNET_OK != - GNUNET_MST_from_buffer (kx->mst, - &buf[sizeof (struct EncryptedMessage)], - size - sizeof (struct EncryptedMessage), - GNUNET_YES, - GNUNET_NO)) - GNUNET_break_op (0); + GNUNET_MST_from_buffer(kx->mst, + &buf[sizeof(struct EncryptedMessage)], + size - sizeof(struct EncryptedMessage), + GNUNET_YES, + GNUNET_NO)) + GNUNET_break_op(0); } @@ -1779,17 +1798,17 @@ handle_encrypted (void *cls, const struct EncryptedMessage *m) * @param connect_cls the `struct Neighbour` */ static void -handle_transport_notify_excess_bw (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *connect_cls) +handle_transport_notify_excess_bw(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *connect_cls) { struct GSC_KeyExchangeInfo *kx = connect_cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Peer %s has excess bandwidth available\n", - GNUNET_i2s (pid)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Peer %s has excess bandwidth available\n", + GNUNET_i2s(pid)); kx->has_excess_bandwidth = GNUNET_YES; - GSC_SESSIONS_solicit (pid); + GSC_SESSIONS_solicit(pid); } @@ -1798,40 +1817,40 @@ handle_transport_notify_excess_bw (void *cls, * public key and generate the appropriate signature. */ static void -sign_ephemeral_key () +sign_ephemeral_key() { - current_ekm.header.size = htons (sizeof (struct EphemeralKeyMessage)); - current_ekm.header.type = htons (GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY); + current_ekm.header.size = htons(sizeof(struct EphemeralKeyMessage)); + current_ekm.header.type = htons(GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY); current_ekm.sender_status = 0; /* to be set later */ - current_ekm.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY); + current_ekm.purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_SET_ECC_KEY); current_ekm.purpose.size = - htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) + - sizeof (struct GNUNET_TIME_AbsoluteNBO) + - sizeof (struct GNUNET_TIME_AbsoluteNBO) + - sizeof (struct GNUNET_CRYPTO_EcdhePublicKey) + - sizeof (struct GNUNET_PeerIdentity)); + htonl(sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose) + + sizeof(struct GNUNET_TIME_AbsoluteNBO) + + sizeof(struct GNUNET_TIME_AbsoluteNBO) + + sizeof(struct GNUNET_CRYPTO_EcdhePublicKey) + + sizeof(struct GNUNET_PeerIdentity)); current_ekm.creation_time = - GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ()); - if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (GSC_cfg, - "core", - "USE_EPHEMERAL_KEYS")) - { - current_ekm.expiration_time = - GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute ( - GNUNET_TIME_relative_add (REKEY_FREQUENCY, REKEY_TOLERANCE))); - } + GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get()); + if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(GSC_cfg, + "core", + "USE_EPHEMERAL_KEYS")) + { + current_ekm.expiration_time = + GNUNET_TIME_absolute_hton(GNUNET_TIME_relative_to_absolute( + GNUNET_TIME_relative_add(REKEY_FREQUENCY, REKEY_TOLERANCE))); + } else - { - current_ekm.expiration_time = - GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS); - } - GNUNET_CRYPTO_ecdhe_key_get_public (my_ephemeral_key, - ¤t_ekm.ephemeral_key); + { + current_ekm.expiration_time = + GNUNET_TIME_absolute_hton(GNUNET_TIME_UNIT_FOREVER_ABS); + } + GNUNET_CRYPTO_ecdhe_key_get_public(my_ephemeral_key, + ¤t_ekm.ephemeral_key); current_ekm.origin_identity = GSC_my_identity; - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_eddsa_sign (my_private_key, - ¤t_ekm.purpose, - ¤t_ekm.signature)); + GNUNET_assert(GNUNET_OK == + GNUNET_CRYPTO_eddsa_sign(my_private_key, + ¤t_ekm.purpose, + ¤t_ekm.signature)); } @@ -1841,40 +1860,40 @@ sign_ephemeral_key () * @param cls closure, NULL */ static void -do_rekey (void *cls) +do_rekey(void *cls) { struct GSC_KeyExchangeInfo *pos; - rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY, &do_rekey, NULL); + rekey_task = GNUNET_SCHEDULER_add_delayed(REKEY_FREQUENCY, &do_rekey, NULL); if (NULL != my_ephemeral_key) - GNUNET_free (my_ephemeral_key); - my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create (); - GNUNET_assert (NULL != my_ephemeral_key); - sign_ephemeral_key (); + GNUNET_free(my_ephemeral_key); + my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create(); + GNUNET_assert(NULL != my_ephemeral_key); + sign_ephemeral_key(); { struct GNUNET_HashCode eh; - GNUNET_CRYPTO_hash (¤t_ekm.ephemeral_key, - sizeof (current_ekm.ephemeral_key), - &eh); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Rekeying to %s\n", GNUNET_h2s (&eh)); + GNUNET_CRYPTO_hash(¤t_ekm.ephemeral_key, + sizeof(current_ekm.ephemeral_key), + &eh); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Rekeying to %s\n", GNUNET_h2s(&eh)); } for (pos = kx_head; NULL != pos; pos = pos->next) - { - if (GNUNET_CORE_KX_STATE_UP == pos->status) - { - pos->status = GNUNET_CORE_KX_STATE_REKEY_SENT; - monitor_notify_all (pos); - derive_session_keys (pos); - } - if (GNUNET_CORE_KX_STATE_DOWN == pos->status) { - pos->status = GNUNET_CORE_KX_STATE_KEY_SENT; - monitor_notify_all (pos); + if (GNUNET_CORE_KX_STATE_UP == pos->status) + { + pos->status = GNUNET_CORE_KX_STATE_REKEY_SENT; + monitor_notify_all(pos); + derive_session_keys(pos); + } + if (GNUNET_CORE_KX_STATE_DOWN == pos->status) + { + pos->status = GNUNET_CORE_KX_STATE_KEY_SENT; + monitor_notify_all(pos); + } + monitor_notify_all(pos); + send_key(pos); } - monitor_notify_all (pos); - send_key (pos); - } } @@ -1885,65 +1904,65 @@ do_rekey (void *cls) * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure */ int -GSC_KX_init (struct GNUNET_CRYPTO_EddsaPrivateKey *pk) +GSC_KX_init(struct GNUNET_CRYPTO_EddsaPrivateKey *pk) { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_fixed_size (ephemeral_key, - GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY, - struct EphemeralKeyMessage, - NULL), - GNUNET_MQ_hd_fixed_size (ping, - GNUNET_MESSAGE_TYPE_CORE_PING, - struct PingMessage, - NULL), - GNUNET_MQ_hd_fixed_size (pong, - GNUNET_MESSAGE_TYPE_CORE_PONG, - struct PongMessage, - NULL), - GNUNET_MQ_hd_var_size (encrypted, - GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE, - struct EncryptedMessage, + { GNUNET_MQ_hd_fixed_size(ephemeral_key, + GNUNET_MESSAGE_TYPE_CORE_EPHEMERAL_KEY, + struct EphemeralKeyMessage, NULL), - GNUNET_MQ_handler_end ()}; + GNUNET_MQ_hd_fixed_size(ping, + GNUNET_MESSAGE_TYPE_CORE_PING, + struct PingMessage, + NULL), + GNUNET_MQ_hd_fixed_size(pong, + GNUNET_MESSAGE_TYPE_CORE_PONG, + struct PongMessage, + NULL), + GNUNET_MQ_hd_var_size(encrypted, + GNUNET_MESSAGE_TYPE_CORE_ENCRYPTED_MESSAGE, + struct EncryptedMessage, + NULL), + GNUNET_MQ_handler_end() }; my_private_key = pk; - GNUNET_CRYPTO_eddsa_key_get_public (my_private_key, - &GSC_my_identity.public_key); - my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create (); + GNUNET_CRYPTO_eddsa_key_get_public(my_private_key, + &GSC_my_identity.public_key); + my_ephemeral_key = GNUNET_CRYPTO_ecdhe_key_create(); if (NULL == my_ephemeral_key) - { - GNUNET_break (0); - GNUNET_free (my_private_key); - my_private_key = NULL; - return GNUNET_SYSERR; - } - sign_ephemeral_key (); + { + GNUNET_break(0); + GNUNET_free(my_private_key); + my_private_key = NULL; + return GNUNET_SYSERR; + } + sign_ephemeral_key(); { struct GNUNET_HashCode eh; - GNUNET_CRYPTO_hash (¤t_ekm.ephemeral_key, - sizeof (current_ekm.ephemeral_key), - &eh); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Starting with ephemeral key %s\n", - GNUNET_h2s (&eh)); + GNUNET_CRYPTO_hash(¤t_ekm.ephemeral_key, + sizeof(current_ekm.ephemeral_key), + &eh); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Starting with ephemeral key %s\n", + GNUNET_h2s(&eh)); } - nc = GNUNET_notification_context_create (1); - rekey_task = GNUNET_SCHEDULER_add_delayed (REKEY_FREQUENCY, &do_rekey, NULL); + nc = GNUNET_notification_context_create(1); + rekey_task = GNUNET_SCHEDULER_add_delayed(REKEY_FREQUENCY, &do_rekey, NULL); transport = - GNUNET_TRANSPORT_core_connect (GSC_cfg, - &GSC_my_identity, - handlers, - NULL, - &handle_transport_notify_connect, - &handle_transport_notify_disconnect, - &handle_transport_notify_excess_bw); + GNUNET_TRANSPORT_core_connect(GSC_cfg, + &GSC_my_identity, + handlers, + NULL, + &handle_transport_notify_connect, + &handle_transport_notify_disconnect, + &handle_transport_notify_excess_bw); if (NULL == transport) - { - GSC_KX_done (); - return GNUNET_SYSERR; - } + { + GSC_KX_done(); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1952,33 +1971,33 @@ GSC_KX_init (struct GNUNET_CRYPTO_EddsaPrivateKey *pk) * Shutdown KX subsystem. */ void -GSC_KX_done () +GSC_KX_done() { if (NULL != transport) - { - GNUNET_TRANSPORT_core_disconnect (transport); - transport = NULL; - } + { + GNUNET_TRANSPORT_core_disconnect(transport); + transport = NULL; + } if (NULL != rekey_task) - { - GNUNET_SCHEDULER_cancel (rekey_task); - rekey_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(rekey_task); + rekey_task = NULL; + } if (NULL != my_ephemeral_key) - { - GNUNET_free (my_ephemeral_key); - my_ephemeral_key = NULL; - } + { + GNUNET_free(my_ephemeral_key); + my_ephemeral_key = NULL; + } if (NULL != my_private_key) - { - GNUNET_free (my_private_key); - my_private_key = NULL; - } + { + GNUNET_free(my_private_key); + my_private_key = NULL; + } if (NULL != nc) - { - GNUNET_notification_context_destroy (nc); - nc = NULL; - } + { + GNUNET_notification_context_destroy(nc); + nc = NULL; + } } @@ -1989,9 +2008,9 @@ GSC_KX_done () * @return number of items in the message queue */ unsigned int -GSC_NEIGHBOURS_get_queue_length (const struct GSC_KeyExchangeInfo *kxinfo) +GSC_NEIGHBOURS_get_queue_length(const struct GSC_KeyExchangeInfo *kxinfo) { - return GNUNET_MQ_get_length (kxinfo->mq); + return GNUNET_MQ_get_length(kxinfo->mq); } @@ -2002,7 +2021,7 @@ GSC_NEIGHBOURS_get_queue_length (const struct GSC_KeyExchangeInfo *kxinfo) * @return #GNUNET_YES if excess bandwidth is available, #GNUNET_NO if not */ int -GSC_NEIGHBOURS_check_excess_bandwidth (const struct GSC_KeyExchangeInfo *kxinfo) +GSC_NEIGHBOURS_check_excess_bandwidth(const struct GSC_KeyExchangeInfo *kxinfo) { return kxinfo->has_excess_bandwidth; } @@ -2017,28 +2036,28 @@ GSC_NEIGHBOURS_check_excess_bandwidth (const struct GSC_KeyExchangeInfo *kxinfo) * @param mq message queue to add for monitoring */ void -GSC_KX_handle_client_monitor_peers (struct GNUNET_MQ_Handle *mq) +GSC_KX_handle_client_monitor_peers(struct GNUNET_MQ_Handle *mq) { struct GNUNET_MQ_Envelope *env; struct MonitorNotifyMessage *done_msg; struct GSC_KeyExchangeInfo *kx; - GNUNET_notification_context_add (nc, mq); + GNUNET_notification_context_add(nc, mq); for (kx = kx_head; NULL != kx; kx = kx->next) - { - struct GNUNET_MQ_Envelope *env; - struct MonitorNotifyMessage *msg; - - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY); - msg->state = htonl ((uint32_t) kx->status); - msg->peer = *kx->peer; - msg->timeout = GNUNET_TIME_absolute_hton (kx->timeout); - GNUNET_MQ_send (mq, env); - } - env = GNUNET_MQ_msg (done_msg, GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY); - done_msg->state = htonl ((uint32_t) GNUNET_CORE_KX_ITERATION_FINISHED); - done_msg->timeout = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS); - GNUNET_MQ_send (mq, env); + { + struct GNUNET_MQ_Envelope *env; + struct MonitorNotifyMessage *msg; + + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY); + msg->state = htonl((uint32_t)kx->status); + msg->peer = *kx->peer; + msg->timeout = GNUNET_TIME_absolute_hton(kx->timeout); + GNUNET_MQ_send(mq, env); + } + env = GNUNET_MQ_msg(done_msg, GNUNET_MESSAGE_TYPE_CORE_MONITOR_NOTIFY); + done_msg->state = htonl((uint32_t)GNUNET_CORE_KX_ITERATION_FINISHED); + done_msg->timeout = GNUNET_TIME_absolute_hton(GNUNET_TIME_UNIT_FOREVER_ABS); + GNUNET_MQ_send(mq, env); } diff --git a/src/core/gnunet-service-core_kx.h b/src/core/gnunet-service-core_kx.h index d27c3687a..d8928f7d3 100644 --- a/src/core/gnunet-service-core_kx.h +++ b/src/core/gnunet-service-core_kx.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/gnunet-service-core_kx.h @@ -44,9 +44,9 @@ struct GSC_KeyExchangeInfo; * @param payload_size number of bytes in 'payload' */ void -GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx, - const void *payload, - size_t payload_size); +GSC_KX_encrypt_and_transmit(struct GSC_KeyExchangeInfo *kx, + const void *payload, + size_t payload_size); /** @@ -56,14 +56,14 @@ GSC_KX_encrypt_and_transmit (struct GSC_KeyExchangeInfo *kx, * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure */ int -GSC_KX_init (struct GNUNET_CRYPTO_EddsaPrivateKey *pk); +GSC_KX_init(struct GNUNET_CRYPTO_EddsaPrivateKey *pk); /** * Shutdown KX subsystem. */ void -GSC_KX_done (void); +GSC_KX_done(void); /** @@ -73,7 +73,7 @@ GSC_KX_done (void); * @return #GNUNET_YES if excess bandwidth is available, #GNUNET_NO if not */ int -GSC_NEIGHBOURS_check_excess_bandwidth (const struct GSC_KeyExchangeInfo *target); +GSC_NEIGHBOURS_check_excess_bandwidth(const struct GSC_KeyExchangeInfo *target); /** @@ -83,7 +83,7 @@ GSC_NEIGHBOURS_check_excess_bandwidth (const struct GSC_KeyExchangeInfo *target) * @return number of items in the message queue */ unsigned int -GSC_NEIGHBOURS_get_queue_length (const struct GSC_KeyExchangeInfo *target); +GSC_NEIGHBOURS_get_queue_length(const struct GSC_KeyExchangeInfo *target); /** @@ -95,7 +95,7 @@ GSC_NEIGHBOURS_get_queue_length (const struct GSC_KeyExchangeInfo *target); * @param mq message queue to add for monitoring */ void -GSC_KX_handle_client_monitor_peers (struct GNUNET_MQ_Handle *mq); +GSC_KX_handle_client_monitor_peers(struct GNUNET_MQ_Handle *mq); #endif diff --git a/src/core/gnunet-service-core_sessions.c b/src/core/gnunet-service-core_sessions.c index 8ff61ec20..daca22aef 100644 --- a/src/core/gnunet-service-core_sessions.c +++ b/src/core/gnunet-service-core_sessions.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/gnunet-service-core_sessions.c @@ -43,9 +43,7 @@ * Message ready for encryption. This struct is followed by the * actual content of the message. */ -struct SessionMessageEntry -{ - +struct SessionMessageEntry { /** * We keep messages in a doubly linked list. */ @@ -90,8 +88,7 @@ struct SessionMessageEntry /** * Data kept per session. */ -struct Session -{ +struct Session { /** * Identity of the other peer. */ @@ -159,9 +156,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Message sent to confirm that a typemap was received. */ -struct TypeMapConfirmationMessage -{ - +struct TypeMapConfirmationMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP. */ @@ -195,11 +190,11 @@ static struct GNUNET_CONTAINER_MultiPeerMap *sessions; * session handle */ static struct Session * -find_session (const struct GNUNET_PeerIdentity *peer) +find_session(const struct GNUNET_PeerIdentity *peer) { if (NULL == sessions) return NULL; - return GNUNET_CONTAINER_multipeermap_get (sessions, peer); + return GNUNET_CONTAINER_multipeermap_get(sessions, peer); } @@ -210,53 +205,53 @@ find_session (const struct GNUNET_PeerIdentity *peer) * @param pid identity of peer to kill session with */ void -GSC_SESSIONS_end (const struct GNUNET_PeerIdentity *pid) +GSC_SESSIONS_end(const struct GNUNET_PeerIdentity *pid) { struct Session *session; struct GSC_ClientActiveRequest *car; struct SessionMessageEntry *sme; - session = find_session (pid); + session = find_session(pid); if (NULL == session) return; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Destroying session for peer `%s'\n", - GNUNET_i2s (session->peer)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Destroying session for peer `%s'\n", + GNUNET_i2s(session->peer)); if (NULL != session->cork_task) - { - GNUNET_SCHEDULER_cancel (session->cork_task); - session->cork_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(session->cork_task); + session->cork_task = NULL; + } while (NULL != (car = session->active_client_request_head)) - { - GNUNET_CONTAINER_DLL_remove (session->active_client_request_head, - session->active_client_request_tail, - car); - GSC_CLIENTS_reject_request (car, GNUNET_NO); - } + { + GNUNET_CONTAINER_DLL_remove(session->active_client_request_head, + session->active_client_request_tail, + car); + GSC_CLIENTS_reject_request(car, GNUNET_NO); + } while (NULL != (sme = session->sme_head)) - { - GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, sme); - GNUNET_free (sme); - } + { + GNUNET_CONTAINER_DLL_remove(session->sme_head, session->sme_tail, sme); + GNUNET_free(sme); + } if (NULL != session->typemap_task) - { - GNUNET_SCHEDULER_cancel (session->typemap_task); - session->typemap_task = NULL; - } - GSC_CLIENTS_notify_clients_about_neighbour (session->peer, - session->tmap, - NULL); - GNUNET_assert ( + { + GNUNET_SCHEDULER_cancel(session->typemap_task); + session->typemap_task = NULL; + } + GSC_CLIENTS_notify_clients_about_neighbour(session->peer, + session->tmap, + NULL); + GNUNET_assert( GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (sessions, session->peer, session)); - GNUNET_STATISTICS_set (GSC_stats, - gettext_noop ("# peers connected"), - GNUNET_CONTAINER_multipeermap_size (sessions), - GNUNET_NO); - GSC_TYPEMAP_destroy (session->tmap); + GNUNET_CONTAINER_multipeermap_remove(sessions, session->peer, session)); + GNUNET_STATISTICS_set(GSC_stats, + gettext_noop("# peers connected"), + GNUNET_CONTAINER_multipeermap_size(sessions), + GNUNET_NO); + GSC_TYPEMAP_destroy(session->tmap); session->tmap = NULL; - GNUNET_free (session); + GNUNET_free(session); } @@ -267,29 +262,29 @@ GSC_SESSIONS_end (const struct GNUNET_PeerIdentity *pid) * @param cls the `struct Session *` */ static void -transmit_typemap_task (void *cls) +transmit_typemap_task(void *cls) { struct Session *session = cls; struct GNUNET_MessageHeader *hdr; struct GNUNET_TIME_Relative delay; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending TYPEMAP to %s\n", - GNUNET_i2s (session->peer)); - session->typemap_delay = GNUNET_TIME_STD_BACKOFF (session->typemap_delay); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending TYPEMAP to %s\n", + GNUNET_i2s(session->peer)); + session->typemap_delay = GNUNET_TIME_STD_BACKOFF(session->typemap_delay); delay = session->typemap_delay; /* randomize a bit to avoid spont. sync */ delay.rel_value_us += - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000 * 1000); + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 1000 * 1000); session->typemap_task = - GNUNET_SCHEDULER_add_delayed (delay, &transmit_typemap_task, session); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# type map refreshes sent"), - 1, - GNUNET_NO); - hdr = GSC_TYPEMAP_compute_type_map_message (); - GSC_KX_encrypt_and_transmit (session->kx, hdr, ntohs (hdr->size)); - GNUNET_free (hdr); + GNUNET_SCHEDULER_add_delayed(delay, &transmit_typemap_task, session); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# type map refreshes sent"), + 1, + GNUNET_NO); + hdr = GSC_TYPEMAP_compute_type_map_message(); + GSC_KX_encrypt_and_transmit(session->kx, hdr, ntohs(hdr->size)); + GNUNET_free(hdr); } @@ -299,14 +294,14 @@ transmit_typemap_task (void *cls) * @param session session to restart typemap transmission for */ static void -start_typemap_task (struct Session *session) +start_typemap_task(struct Session *session) { if (NULL != session->typemap_task) - GNUNET_SCHEDULER_cancel (session->typemap_task); + GNUNET_SCHEDULER_cancel(session->typemap_task); session->typemap_delay = GNUNET_TIME_UNIT_SECONDS; - session->typemap_task = GNUNET_SCHEDULER_add_delayed (session->typemap_delay, - &transmit_typemap_task, - session); + session->typemap_task = GNUNET_SCHEDULER_add_delayed(session->typemap_delay, + &transmit_typemap_task, + session); } @@ -317,30 +312,30 @@ start_typemap_task (struct Session *session) * @param kx key exchange that completed */ void -GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer, - struct GSC_KeyExchangeInfo *kx) +GSC_SESSIONS_create(const struct GNUNET_PeerIdentity *peer, + struct GSC_KeyExchangeInfo *kx) { struct Session *session; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Creating session for peer `%s'\n", - GNUNET_i2s (peer)); - session = GNUNET_new (struct Session); - session->tmap = GSC_TYPEMAP_create (); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Creating session for peer `%s'\n", + GNUNET_i2s(peer)); + session = GNUNET_new(struct Session); + session->tmap = GSC_TYPEMAP_create(); session->peer = peer; session->kx = kx; - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put ( - sessions, - session->peer, - session, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - GNUNET_STATISTICS_set (GSC_stats, - gettext_noop ("# peers connected"), - GNUNET_CONTAINER_multipeermap_size (sessions), - GNUNET_NO); - GSC_CLIENTS_notify_clients_about_neighbour (peer, NULL, session->tmap); - start_typemap_task (session); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_put( + sessions, + session->peer, + session, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_STATISTICS_set(GSC_stats, + gettext_noop("# peers connected"), + GNUNET_CONTAINER_multipeermap_size(sessions), + GNUNET_NO); + GSC_CLIENTS_notify_clients_about_neighbour(peer, NULL, session->tmap); + start_typemap_task(session); } @@ -352,18 +347,18 @@ GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer, * @param peer peer that is now connected */ void -GSC_SESSIONS_reinit (const struct GNUNET_PeerIdentity *peer) +GSC_SESSIONS_reinit(const struct GNUNET_PeerIdentity *peer) { struct Session *session; - session = find_session (peer); + session = find_session(peer); if (NULL == session) - { - /* KX/session is new for both sides; thus no need to restart what - has not yet begun */ - return; - } - start_typemap_task (session); + { + /* KX/session is new for both sides; thus no need to restart what + has not yet begun */ + return; + } + start_typemap_task(session); } @@ -375,51 +370,51 @@ GSC_SESSIONS_reinit (const struct GNUNET_PeerIdentity *peer) * @param msg confirmation message we received */ void -GSC_SESSIONS_confirm_typemap (const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_MessageHeader *msg) +GSC_SESSIONS_confirm_typemap(const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_MessageHeader *msg) { const struct TypeMapConfirmationMessage *cmsg; struct Session *session; - session = find_session (peer); + session = find_session(peer); if (NULL == session) - { - GNUNET_break (0); - return; - } - if (ntohs (msg->size) != sizeof (struct TypeMapConfirmationMessage)) - { - GNUNET_break_op (0); - return; - } - cmsg = (const struct TypeMapConfirmationMessage *) msg; - if (GNUNET_YES != GSC_TYPEMAP_check_hash (&cmsg->tm_hash)) - { - /* our typemap has changed in the meantime, do not - accept confirmation */ - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# outdated typemap confirmations received"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got outdated typemap confirmated from peer `%s'\n", - GNUNET_i2s (session->peer)); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got typemap confirmation from peer `%s'\n", - GNUNET_i2s (session->peer)); + { + GNUNET_break(0); + return; + } + if (ntohs(msg->size) != sizeof(struct TypeMapConfirmationMessage)) + { + GNUNET_break_op(0); + return; + } + cmsg = (const struct TypeMapConfirmationMessage *)msg; + if (GNUNET_YES != GSC_TYPEMAP_check_hash(&cmsg->tm_hash)) + { + /* our typemap has changed in the meantime, do not + accept confirmation */ + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# outdated typemap confirmations received"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got outdated typemap confirmated from peer `%s'\n", + GNUNET_i2s(session->peer)); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got typemap confirmation from peer `%s'\n", + GNUNET_i2s(session->peer)); if (NULL != session->typemap_task) - { - GNUNET_SCHEDULER_cancel (session->typemap_task); - session->typemap_task = NULL; - } - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ( - "# valid typemap confirmations received"), - 1, - GNUNET_NO); + { + GNUNET_SCHEDULER_cancel(session->typemap_task); + session->typemap_task = NULL; + } + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop( + "# valid typemap confirmations received"), + 1, + GNUNET_NO); } @@ -432,17 +427,17 @@ GSC_SESSIONS_confirm_typemap (const struct GNUNET_PeerIdentity *peer, * @return #GNUNET_OK (continue to iterate) */ static int -notify_client_about_session (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +notify_client_about_session(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct GSC_Client *client = cls; struct Session *session = value; - GSC_CLIENTS_notify_client_about_neighbour (client, - session->peer, - NULL, /* old TMAP: none */ - session->tmap); + GSC_CLIENTS_notify_client_about_neighbour(client, + session->peer, + NULL, /* old TMAP: none */ + session->tmap); return GNUNET_OK; } @@ -453,12 +448,12 @@ notify_client_about_session (void *cls, * @param client the new client */ void -GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client) +GSC_SESSIONS_notify_client_about_sessions(struct GSC_Client *client) { /* notify new client about existing sessions */ - GNUNET_CONTAINER_multipeermap_iterate (sessions, - ¬ify_client_about_session, - client); + GNUNET_CONTAINER_multipeermap_iterate(sessions, + ¬ify_client_about_session, + client); } @@ -469,7 +464,7 @@ GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client) * @param session session to transmit messages from */ static void -try_transmission (struct Session *session); +try_transmission(struct Session *session); /** @@ -482,31 +477,31 @@ try_transmission (struct Session *session); * have been invoked on it */ void -GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car) +GSC_SESSIONS_queue_request(struct GSC_ClientActiveRequest *car) { struct Session *session; - session = find_session (&car->target); + session = find_session(&car->target); if (NULL == session) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Dropped client request for transmission (am disconnected)\n"); - GNUNET_break (0); /* should have been rejected earlier */ - GSC_CLIENTS_reject_request (car, GNUNET_NO); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Dropped client request for transmission (am disconnected)\n"); + GNUNET_break(0); /* should have been rejected earlier */ + GSC_CLIENTS_reject_request(car, GNUNET_NO); + return; + } if (car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE) - { - GNUNET_break (0); - GSC_CLIENTS_reject_request (car, GNUNET_YES); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received client transmission request. queueing\n"); - GNUNET_CONTAINER_DLL_insert_tail (session->active_client_request_head, - session->active_client_request_tail, - car); - try_transmission (session); + { + GNUNET_break(0); + GSC_CLIENTS_reject_request(car, GNUNET_YES); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received client transmission request. queueing\n"); + GNUNET_CONTAINER_DLL_insert_tail(session->active_client_request_head, + session->active_client_request_tail, + car); + try_transmission(session); } @@ -517,23 +512,23 @@ GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car) * the caller (CLIENTS sysbsystem) */ void -GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car) +GSC_SESSIONS_dequeue_request(struct GSC_ClientActiveRequest *car) { struct Session *session; - if (0 == memcmp (&car->target, - &GSC_my_identity, - sizeof (struct GNUNET_PeerIdentity))) + if (0 == memcmp(&car->target, + &GSC_my_identity, + sizeof(struct GNUNET_PeerIdentity))) return; - session = find_session (&car->target); - GNUNET_assert (NULL != session); - GNUNET_CONTAINER_DLL_remove (session->active_client_request_head, - session->active_client_request_tail, - car); + session = find_session(&car->target); + GNUNET_assert(NULL != session); + GNUNET_CONTAINER_DLL_remove(session->active_client_request_head, + session->active_client_request_tail, + car); /* dequeueing of 'high' priority messages may unblock transmission for lower-priority messages, so we also need to try in this case. */ - try_transmission (session); + try_transmission(session); } @@ -545,7 +540,7 @@ GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car) * @param msize how many bytes do we have already */ static void -solicit_messages (struct Session *session, size_t msize) +solicit_messages(struct Session *session, size_t msize) { struct GSC_ClientActiveRequest *car; struct GSC_ClientActiveRequest *nxt; @@ -555,33 +550,33 @@ solicit_messages (struct Session *session, size_t msize) so_size = msize; pmax = GNUNET_MQ_PRIO_BACKGROUND; for (car = session->active_client_request_head; NULL != car; car = car->next) - { - if (GNUNET_YES == car->was_solicited) - continue; - pmax = GNUNET_MAX (pmax, car->priority & GNUNET_MQ_PRIORITY_MASK); - } + { + if (GNUNET_YES == car->was_solicited) + continue; + pmax = GNUNET_MAX(pmax, car->priority & GNUNET_MQ_PRIORITY_MASK); + } nxt = session->active_client_request_head; while (NULL != (car = nxt)) - { - nxt = car->next; - if (car->priority < pmax) - continue; - if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE) - break; - so_size += car->msize; - if (GNUNET_YES == car->was_solicited) - continue; - car->was_solicited = GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Soliciting message with priority %u\n", - car->priority); - GSC_CLIENTS_solicit_request (car); - /* The above call may *dequeue* requests and thereby - clobber 'nxt'. Hence we need to restart from the - head of the list. */ - nxt = session->active_client_request_head; - so_size = msize; - } + { + nxt = car->next; + if (car->priority < pmax) + continue; + if (so_size + car->msize > GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE) + break; + so_size += car->msize; + if (GNUNET_YES == car->was_solicited) + continue; + car->was_solicited = GNUNET_YES; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Soliciting message with priority %u\n", + car->priority); + GSC_CLIENTS_solicit_request(car); + /* The above call may *dequeue* requests and thereby + clobber 'nxt'. Hence we need to restart from the + head of the list. */ + nxt = session->active_client_request_head; + so_size = msize; + } } @@ -592,12 +587,12 @@ solicit_messages (struct Session *session, size_t msize) * @param cls `struct Session` with the messages to transmit now */ static void -pop_cork_task (void *cls) +pop_cork_task(void *cls) { struct Session *session = cls; session->cork_task = NULL; - try_transmission (session); + try_transmission(session); } @@ -609,7 +604,7 @@ pop_cork_task (void *cls) * @param session session to transmit messages from */ static void -try_transmission (struct Session *session) +try_transmission(struct Session *session) { struct SessionMessageEntry *pos; size_t msize; @@ -625,13 +620,13 @@ try_transmission (struct Session *session) /* if the peer has excess bandwidth, background traffic is allowed, otherwise not */ if (MAX_ENCRYPTED_MESSAGE_QUEUE_SIZE <= - GSC_NEIGHBOURS_get_queue_length (session->kx)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Transmission queue already very long, waiting...\n"); - return; /* queue already too long */ - } - excess = GSC_NEIGHBOURS_check_excess_bandwidth (session->kx); + GSC_NEIGHBOURS_get_queue_length(session->kx)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Transmission queue already very long, waiting...\n"); + return; /* queue already too long */ + } + excess = GSC_NEIGHBOURS_check_excess_bandwidth(session->kx); if (GNUNET_YES == excess) maxp = GNUNET_MQ_PRIO_BACKGROUND; else @@ -640,98 +635,98 @@ try_transmission (struct Session *session) pos = session->sme_head; while ((NULL != pos) && (msize + pos->size <= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)) - { - GNUNET_assert (pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE); - msize += pos->size; - maxp = GNUNET_MAX (maxp, pos->priority & GNUNET_MQ_PRIORITY_MASK); - min_deadline = GNUNET_TIME_absolute_min (min_deadline, pos->deadline); - pos = pos->next; - } - GNUNET_log ( + { + GNUNET_assert(pos->size < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE); + msize += pos->size; + maxp = GNUNET_MAX(maxp, pos->priority & GNUNET_MQ_PRIORITY_MASK); + min_deadline = GNUNET_TIME_absolute_min(min_deadline, pos->deadline); + pos = pos->next; + } + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "Calculating transmission set with %u priority (%s) and %s earliest deadline\n", maxp, (GNUNET_YES == excess) ? "excess bandwidth" : "limited bandwidth", - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining ( - min_deadline), - GNUNET_YES)); + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_remaining( + min_deadline), + GNUNET_YES)); if (maxp < GNUNET_MQ_PRIO_CRITICAL_CONTROL) - { - /* if highest already solicited priority from clients is not critical, - check if there are higher-priority messages to be solicited from clients */ - if (GNUNET_YES == excess) - maxpc = GNUNET_MQ_PRIO_BACKGROUND; - else - maxpc = GNUNET_MQ_PRIO_BEST_EFFORT; - for (car = session->active_client_request_head; NULL != car; - car = car->next) { - if (GNUNET_YES == car->was_solicited) - continue; - maxpc = GNUNET_MAX (maxpc, car->priority & GNUNET_MQ_PRIORITY_MASK); + /* if highest already solicited priority from clients is not critical, + check if there are higher-priority messages to be solicited from clients */ + if (GNUNET_YES == excess) + maxpc = GNUNET_MQ_PRIO_BACKGROUND; + else + maxpc = GNUNET_MQ_PRIO_BEST_EFFORT; + for (car = session->active_client_request_head; NULL != car; + car = car->next) + { + if (GNUNET_YES == car->was_solicited) + continue; + maxpc = GNUNET_MAX(maxpc, car->priority & GNUNET_MQ_PRIORITY_MASK); + } + if (maxpc > maxp) + { + /* we have messages waiting for solicitation that have a higher + priority than those that we already accepted; solicit the + high-priority messages first */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Soliciting messages based on priority (%u > %u)\n", + maxpc, + maxp); + solicit_messages(session, 0); + return; + } } - if (maxpc > maxp) + else { - /* we have messages waiting for solicitation that have a higher - priority than those that we already accepted; solicit the - high-priority messages first */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Soliciting messages based on priority (%u > %u)\n", - maxpc, - maxp); - solicit_messages (session, 0); - return; + /* never solicit more, we have critical messages to process */ + excess = GNUNET_NO; + maxpc = GNUNET_MQ_PRIO_BACKGROUND; } - } - else - { - /* never solicit more, we have critical messages to process */ - excess = GNUNET_NO; - maxpc = GNUNET_MQ_PRIO_BACKGROUND; - } - now = GNUNET_TIME_absolute_get (); + now = GNUNET_TIME_absolute_get(); if (((GNUNET_YES == excess) || (maxpc >= GNUNET_MQ_PRIO_BEST_EFFORT)) && ((0 == msize) || ((msize < GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / 2) && (min_deadline.abs_value_us > now.abs_value_us)))) - { - /* not enough ready yet (tiny message & cork possible), or no messages at all, - and either excess bandwidth or best-effort or higher message waiting at - client; in this case, we try to solicit more */ - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Soliciting messages (excess %d, maxpc %d, message size %u, deadline %s)\n", - excess, - maxpc, - (unsigned int) msize, - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining ( - min_deadline), - GNUNET_YES)); - solicit_messages (session, msize); - if (msize > 0) - { - /* if there is data to send, just not yet, make sure we do transmit - * it once the deadline is reached */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Corking until %s\n", - GNUNET_STRINGS_relative_time_to_string ( - GNUNET_TIME_absolute_get_remaining (min_deadline), - GNUNET_YES)); - if (NULL != session->cork_task) - GNUNET_SCHEDULER_cancel (session->cork_task); - session->cork_task = - GNUNET_SCHEDULER_add_at (min_deadline, &pop_cork_task, session); - } - else { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Queue empty, waiting for solicitations\n"); + /* not enough ready yet (tiny message & cork possible), or no messages at all, + and either excess bandwidth or best-effort or higher message waiting at + client; in this case, we try to solicit more */ + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Soliciting messages (excess %d, maxpc %d, message size %u, deadline %s)\n", + excess, + maxpc, + (unsigned int)msize, + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_remaining( + min_deadline), + GNUNET_YES)); + solicit_messages(session, msize); + if (msize > 0) + { + /* if there is data to send, just not yet, make sure we do transmit + * it once the deadline is reached */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Corking until %s\n", + GNUNET_STRINGS_relative_time_to_string( + GNUNET_TIME_absolute_get_remaining(min_deadline), + GNUNET_YES)); + if (NULL != session->cork_task) + GNUNET_SCHEDULER_cancel(session->cork_task); + session->cork_task = + GNUNET_SCHEDULER_add_at(min_deadline, &pop_cork_task, session); + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Queue empty, waiting for solicitations\n"); + } + return; } - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Building combined plaintext buffer to transmit message!\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Building combined plaintext buffer to transmit message!\n"); /* create plaintext buffer of all messages (that fit), encrypt and transmit */ { @@ -742,33 +737,33 @@ try_transmission (struct Session *session) used = 0; while ((NULL != (pos = session->sme_head)) && (used + pos->size <= msize)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding message of type %d (%d/%d) to payload for %s\n", - ntohs (((const struct GNUNET_MessageHeader *) &pos[1])->type), - pos->is_typemap, - pos->is_typemap_confirm, - GNUNET_i2s (session->peer)); - GNUNET_memcpy (&pbuf[used], &pos[1], pos->size); - used += pos->size; - GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, pos); - GNUNET_free (pos); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding message of type %d (%d/%d) to payload for %s\n", + ntohs(((const struct GNUNET_MessageHeader *)&pos[1])->type), + pos->is_typemap, + pos->is_typemap_confirm, + GNUNET_i2s(session->peer)); + GNUNET_memcpy(&pbuf[used], &pos[1], pos->size); + used += pos->size; + GNUNET_CONTAINER_DLL_remove(session->sme_head, session->sme_tail, pos); + GNUNET_free(pos); + } /* compute average payload size */ total_bytes += used; total_msgs++; if (0 == total_msgs) - { - /* 2^32 messages, wrap around... */ - total_msgs = 1; - total_bytes = used; - } - GNUNET_STATISTICS_set (GSC_stats, - "# avg payload per encrypted message", - total_bytes / total_msgs, - GNUNET_NO); + { + /* 2^32 messages, wrap around... */ + total_msgs = 1; + total_bytes = used; + } + GNUNET_STATISTICS_set(GSC_stats, + "# avg payload per encrypted message", + total_bytes / total_msgs, + GNUNET_NO); /* now actually transmit... */ - GSC_KX_encrypt_and_transmit (session->kx, pbuf, used); + GSC_KX_encrypt_and_transmit(session->kx, pbuf, used); } } @@ -783,36 +778,36 @@ try_transmission (struct Session *session) * @return always #GNUNET_OK */ static int -do_restart_typemap_message (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +do_restart_typemap_message(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { const struct GNUNET_MessageHeader *hdr = cls; struct Session *session = value; struct SessionMessageEntry *sme; uint16_t size; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Restarting sending TYPEMAP to %s\n", - GNUNET_i2s (session->peer)); - size = ntohs (hdr->size); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Restarting sending TYPEMAP to %s\n", + GNUNET_i2s(session->peer)); + size = ntohs(hdr->size); for (sme = session->sme_head; NULL != sme; sme = sme->next) - { - if (GNUNET_YES == sme->is_typemap) { - GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, sme); - GNUNET_free (sme); - break; + if (GNUNET_YES == sme->is_typemap) + { + GNUNET_CONTAINER_DLL_remove(session->sme_head, session->sme_tail, sme); + GNUNET_free(sme); + break; + } } - } - sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + size); + sme = GNUNET_malloc(sizeof(struct SessionMessageEntry) + size); sme->is_typemap = GNUNET_YES; - GNUNET_memcpy (&sme[1], hdr, size); + GNUNET_memcpy(&sme[1], hdr, size); sme->size = size; sme->priority = GNUNET_MQ_PRIO_CRITICAL_CONTROL; - GNUNET_CONTAINER_DLL_insert (session->sme_head, session->sme_tail, sme); - try_transmission (session); - start_typemap_task (session); + GNUNET_CONTAINER_DLL_insert(session->sme_head, session->sme_tail, sme); + try_transmission(session); + start_typemap_task(session); return GNUNET_OK; } @@ -824,13 +819,13 @@ do_restart_typemap_message (void *cls, * @param msg message to transmit */ void -GSC_SESSIONS_broadcast_typemap (const struct GNUNET_MessageHeader *msg) +GSC_SESSIONS_broadcast_typemap(const struct GNUNET_MessageHeader *msg) { if (NULL == sessions) return; - GNUNET_CONTAINER_multipeermap_iterate (sessions, - &do_restart_typemap_message, - (void *) msg); + GNUNET_CONTAINER_multipeermap_iterate(sessions, + &do_restart_typemap_message, + (void *)msg); } @@ -842,17 +837,17 @@ GSC_SESSIONS_broadcast_typemap (const struct GNUNET_MessageHeader *msg) * @param pid identity of peer ready to receive data */ void -GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid) +GSC_SESSIONS_solicit(const struct GNUNET_PeerIdentity *pid) { struct Session *session; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Transport solicits for %s\n", - GNUNET_i2s (pid)); - session = find_session (pid); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Transport solicits for %s\n", + GNUNET_i2s(pid)); + session = find_session(pid); if (NULL == session) return; - try_transmission (session); + try_transmission(session); } @@ -865,43 +860,43 @@ GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid) * @param priority how important is this message */ void -GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car, - const struct GNUNET_MessageHeader *msg, - enum GNUNET_MQ_PriorityPreferences priority) +GSC_SESSIONS_transmit(struct GSC_ClientActiveRequest *car, + const struct GNUNET_MessageHeader *msg, + enum GNUNET_MQ_PriorityPreferences priority) { struct Session *session; struct SessionMessageEntry *sme; struct SessionMessageEntry *pos; size_t msize; - session = find_session (&car->target); + session = find_session(&car->target); if (NULL == session) return; - msize = ntohs (msg->size); - sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + msize); - GNUNET_memcpy (&sme[1], msg, msize); + msize = ntohs(msg->size); + sme = GNUNET_malloc(sizeof(struct SessionMessageEntry) + msize); + GNUNET_memcpy(&sme[1], msg, msize); sme->size = msize; sme->priority = priority; if (0 != (GNUNET_MQ_PREF_CORK_ALLOWED & priority)) - { - sme->deadline = - GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_MAX_CORK_DELAY); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Mesage corked, delaying transmission\n"); - } + { + sme->deadline = + GNUNET_TIME_relative_to_absolute(GNUNET_CONSTANTS_MAX_CORK_DELAY); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Mesage corked, delaying transmission\n"); + } pos = session->sme_head; while ((NULL != pos) && (pos->priority >= sme->priority)) pos = pos->next; if (NULL == pos) - GNUNET_CONTAINER_DLL_insert_tail (session->sme_head, + GNUNET_CONTAINER_DLL_insert_tail(session->sme_head, + session->sme_tail, + sme); + else + GNUNET_CONTAINER_DLL_insert_after(session->sme_head, session->sme_tail, + pos->prev, sme); - else - GNUNET_CONTAINER_DLL_insert_after (session->sme_head, - session->sme_tail, - pos->prev, - sme); - try_transmission (session); + try_transmission(session); } @@ -913,54 +908,54 @@ GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car, * @param msg typemap update message */ void -GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_MessageHeader *msg) +GSC_SESSIONS_set_typemap(const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_MessageHeader *msg) { struct Session *session; struct GSC_TypeMap *nmap; struct SessionMessageEntry *sme; struct TypeMapConfirmationMessage *tmc; - nmap = GSC_TYPEMAP_get_from_message (msg); + nmap = GSC_TYPEMAP_get_from_message(msg); if (NULL == nmap) - { - GNUNET_break_op (0); - return; /* malformed */ - } - session = find_session (peer); + { + GNUNET_break_op(0); + return; /* malformed */ + } + session = find_session(peer); if (NULL == session) - { - GSC_TYPEMAP_destroy (nmap); - GNUNET_break (0); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received TYPEMAP from %s\n", - GNUNET_i2s (session->peer)); + { + GSC_TYPEMAP_destroy(nmap); + GNUNET_break(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received TYPEMAP from %s\n", + GNUNET_i2s(session->peer)); for (sme = session->sme_head; NULL != sme; sme = sme->next) - { - if (GNUNET_YES == sme->is_typemap_confirm) { - GNUNET_CONTAINER_DLL_remove (session->sme_head, session->sme_tail, sme); - GNUNET_free (sme); - break; + if (GNUNET_YES == sme->is_typemap_confirm) + { + GNUNET_CONTAINER_DLL_remove(session->sme_head, session->sme_tail, sme); + GNUNET_free(sme); + break; + } } - } - sme = GNUNET_malloc (sizeof (struct SessionMessageEntry) + - sizeof (struct TypeMapConfirmationMessage)); - sme->deadline = GNUNET_TIME_absolute_get (); - sme->size = sizeof (struct TypeMapConfirmationMessage); + sme = GNUNET_malloc(sizeof(struct SessionMessageEntry) + + sizeof(struct TypeMapConfirmationMessage)); + sme->deadline = GNUNET_TIME_absolute_get(); + sme->size = sizeof(struct TypeMapConfirmationMessage); sme->priority = GNUNET_MQ_PRIO_CRITICAL_CONTROL; sme->is_typemap_confirm = GNUNET_YES; - tmc = (struct TypeMapConfirmationMessage *) &sme[1]; - tmc->header.size = htons (sizeof (struct TypeMapConfirmationMessage)); - tmc->header.type = htons (GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP); - tmc->reserved = htonl (0); - GSC_TYPEMAP_hash (nmap, &tmc->tm_hash); - GNUNET_CONTAINER_DLL_insert (session->sme_head, session->sme_tail, sme); - try_transmission (session); - GSC_CLIENTS_notify_clients_about_neighbour (peer, session->tmap, nmap); - GSC_TYPEMAP_destroy (session->tmap); + tmc = (struct TypeMapConfirmationMessage *)&sme[1]; + tmc->header.size = htons(sizeof(struct TypeMapConfirmationMessage)); + tmc->header.type = htons(GNUNET_MESSAGE_TYPE_CORE_CONFIRM_TYPE_MAP); + tmc->reserved = htonl(0); + GSC_TYPEMAP_hash(nmap, &tmc->tm_hash); + GNUNET_CONTAINER_DLL_insert(session->sme_head, session->sme_tail, sme); + try_transmission(session); + GSC_CLIENTS_notify_clients_about_neighbour(peer, session->tmap, nmap); + GSC_TYPEMAP_destroy(session->tmap); session->tmap = nmap; } @@ -974,21 +969,21 @@ GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer, * @param type type of the message */ void -GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer, - uint16_t type) +GSC_SESSIONS_add_to_typemap(const struct GNUNET_PeerIdentity *peer, + uint16_t type) { struct Session *session; struct GSC_TypeMap *nmap; - if (0 == memcmp (peer, &GSC_my_identity, sizeof (struct GNUNET_PeerIdentity))) + if (0 == memcmp(peer, &GSC_my_identity, sizeof(struct GNUNET_PeerIdentity))) return; - session = find_session (peer); - GNUNET_assert (NULL != session); - if (GNUNET_YES == GSC_TYPEMAP_test_match (session->tmap, &type, 1)) + session = find_session(peer); + GNUNET_assert(NULL != session); + if (GNUNET_YES == GSC_TYPEMAP_test_match(session->tmap, &type, 1)) return; /* already in it */ - nmap = GSC_TYPEMAP_extend (session->tmap, &type, 1); - GSC_CLIENTS_notify_clients_about_neighbour (peer, session->tmap, nmap); - GSC_TYPEMAP_destroy (session->tmap); + nmap = GSC_TYPEMAP_extend(session->tmap, &type, 1); + GSC_CLIENTS_notify_clients_about_neighbour(peer, session->tmap, nmap); + GSC_TYPEMAP_destroy(session->tmap); session->tmap = nmap; } @@ -997,9 +992,9 @@ GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer, * Initialize sessions subsystem. */ void -GSC_SESSIONS_init () +GSC_SESSIONS_init() { - sessions = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES); + sessions = GNUNET_CONTAINER_multipeermap_create(128, GNUNET_YES); } @@ -1013,13 +1008,13 @@ GSC_SESSIONS_init () * @return #GNUNET_OK (continue to iterate) */ static int -free_session_helper (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +free_session_helper(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { /* struct Session *session = value; */ - GSC_SESSIONS_end (key); + GSC_SESSIONS_end(key); return GNUNET_OK; } @@ -1028,16 +1023,16 @@ free_session_helper (void *cls, * Shutdown sessions subsystem. */ void -GSC_SESSIONS_done () +GSC_SESSIONS_done() { if (NULL != sessions) - { - GNUNET_CONTAINER_multipeermap_iterate (sessions, - &free_session_helper, - NULL); - GNUNET_CONTAINER_multipeermap_destroy (sessions); - sessions = NULL; - } + { + GNUNET_CONTAINER_multipeermap_iterate(sessions, + &free_session_helper, + NULL); + GNUNET_CONTAINER_multipeermap_destroy(sessions); + sessions = NULL; + } } /* end of gnunet-service-core_sessions.c */ diff --git a/src/core/gnunet-service-core_sessions.h b/src/core/gnunet-service-core_sessions.h index e92ce0962..ba0f0a0db 100644 --- a/src/core/gnunet-service-core_sessions.h +++ b/src/core/gnunet-service-core_sessions.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/gnunet-service-core_neighbours.h @@ -37,8 +37,8 @@ * @param kx key exchange that completed */ void -GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer, - struct GSC_KeyExchangeInfo *kx); +GSC_SESSIONS_create(const struct GNUNET_PeerIdentity *peer, + struct GSC_KeyExchangeInfo *kx); /** @@ -49,7 +49,7 @@ GSC_SESSIONS_create (const struct GNUNET_PeerIdentity *peer, * @param peer peer that is now connected */ void -GSC_SESSIONS_reinit (const struct GNUNET_PeerIdentity *peer); +GSC_SESSIONS_reinit(const struct GNUNET_PeerIdentity *peer); /** @@ -60,8 +60,8 @@ GSC_SESSIONS_reinit (const struct GNUNET_PeerIdentity *peer); * @param msg confirmation message we received */ void -GSC_SESSIONS_confirm_typemap (const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_MessageHeader *msg); +GSC_SESSIONS_confirm_typemap(const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_MessageHeader *msg); /** @@ -71,7 +71,7 @@ GSC_SESSIONS_confirm_typemap (const struct GNUNET_PeerIdentity *peer, * @param pid identity of peer to kill session with */ void -GSC_SESSIONS_end (const struct GNUNET_PeerIdentity *pid); +GSC_SESSIONS_end(const struct GNUNET_PeerIdentity *pid); /** @@ -82,7 +82,7 @@ GSC_SESSIONS_end (const struct GNUNET_PeerIdentity *pid); * @param pid identity of peer ready to receive data */ void -GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid); +GSC_SESSIONS_solicit(const struct GNUNET_PeerIdentity *pid); /** @@ -95,7 +95,7 @@ GSC_SESSIONS_solicit (const struct GNUNET_PeerIdentity *pid); * have been invoked on it */ void -GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car); +GSC_SESSIONS_queue_request(struct GSC_ClientActiveRequest *car); /** @@ -105,7 +105,7 @@ GSC_SESSIONS_queue_request (struct GSC_ClientActiveRequest *car); * the caller (CLIENTS sysbsystem) */ void -GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car); +GSC_SESSIONS_dequeue_request(struct GSC_ClientActiveRequest *car); /** @@ -117,9 +117,9 @@ GSC_SESSIONS_dequeue_request (struct GSC_ClientActiveRequest *car); * @param priority how important is this message */ void -GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car, - const struct GNUNET_MessageHeader *msg, - enum GNUNET_MQ_PriorityPreferences priority); +GSC_SESSIONS_transmit(struct GSC_ClientActiveRequest *car, + const struct GNUNET_MessageHeader *msg, + enum GNUNET_MQ_PriorityPreferences priority); /** @@ -129,7 +129,7 @@ GSC_SESSIONS_transmit (struct GSC_ClientActiveRequest *car, * @param msg message to transmit */ void -GSC_SESSIONS_broadcast_typemap (const struct GNUNET_MessageHeader *msg); +GSC_SESSIONS_broadcast_typemap(const struct GNUNET_MessageHeader *msg); /** @@ -138,7 +138,7 @@ GSC_SESSIONS_broadcast_typemap (const struct GNUNET_MessageHeader *msg); * @param client the new client */ void -GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client); +GSC_SESSIONS_notify_client_about_sessions(struct GSC_Client *client); /** @@ -149,8 +149,8 @@ GSC_SESSIONS_notify_client_about_sessions (struct GSC_Client *client); * @param msg typemap update message */ void -GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_MessageHeader *msg); +GSC_SESSIONS_set_typemap(const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_MessageHeader *msg); /** @@ -162,22 +162,22 @@ GSC_SESSIONS_set_typemap (const struct GNUNET_PeerIdentity *peer, * @param type type of the message */ void -GSC_SESSIONS_add_to_typemap (const struct GNUNET_PeerIdentity *peer, - uint16_t type); +GSC_SESSIONS_add_to_typemap(const struct GNUNET_PeerIdentity *peer, + uint16_t type); /** * Initialize sessions subsystem. */ void -GSC_SESSIONS_init (void); +GSC_SESSIONS_init(void); /** * Shutdown sessions subsystem. */ void -GSC_SESSIONS_done (void); +GSC_SESSIONS_done(void); #endif diff --git a/src/core/gnunet-service-core_typemap.c b/src/core/gnunet-service-core_typemap.c index 9dd3c71c8..55cd9fb14 100644 --- a/src/core/gnunet-service-core_typemap.c +++ b/src/core/gnunet-service-core_typemap.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/gnunet-service-core_typemap.c @@ -36,8 +36,7 @@ * A type map describing which messages a given neighbour is able * to process. */ -struct GSC_TypeMap -{ +struct GSC_TypeMap { uint32_t bits[(UINT16_MAX + 1) / 32]; }; @@ -67,7 +66,7 @@ static int hash_current; * Our type map changed, recompute its hash. */ static void -rehash_typemap () +rehash_typemap() { hash_current = GNUNET_NO; } @@ -80,9 +79,9 @@ rehash_typemap () * @param hc where to store the hash code */ void -GSC_TYPEMAP_hash (const struct GSC_TypeMap *tm, struct GNUNET_HashCode *hc) +GSC_TYPEMAP_hash(const struct GSC_TypeMap *tm, struct GNUNET_HashCode *hc) { - GNUNET_CRYPTO_hash (tm, sizeof (struct GSC_TypeMap), hc); + GNUNET_CRYPTO_hash(tm, sizeof(struct GSC_TypeMap), hc); } @@ -93,16 +92,16 @@ GSC_TYPEMAP_hash (const struct GSC_TypeMap *tm, struct GNUNET_HashCode *hc) * @return #GNUNET_YES if the hash matches, #GNUNET_NO if not */ int -GSC_TYPEMAP_check_hash (const struct GNUNET_HashCode *hc) +GSC_TYPEMAP_check_hash(const struct GNUNET_HashCode *hc) { if (GNUNET_NO == hash_current) - { - GSC_TYPEMAP_hash (&my_type_map, &my_tm_hash); - hash_current = GNUNET_YES; - } - return (0 == memcmp (hc, &my_tm_hash, sizeof (struct GNUNET_HashCode))) - ? GNUNET_YES - : GNUNET_NO; + { + GSC_TYPEMAP_hash(&my_type_map, &my_tm_hash); + hash_current = GNUNET_YES; + } + return (0 == memcmp(hc, &my_tm_hash, sizeof(struct GNUNET_HashCode))) + ? GNUNET_YES + : GNUNET_NO; } @@ -112,39 +111,39 @@ GSC_TYPEMAP_check_hash (const struct GNUNET_HashCode *hc) * @return this peers current type map message. */ struct GNUNET_MessageHeader * -GSC_TYPEMAP_compute_type_map_message () +GSC_TYPEMAP_compute_type_map_message() { char *tmp; uLongf dlen; struct GNUNET_MessageHeader *hdr; #ifdef compressBound - dlen = compressBound (sizeof (my_type_map)); + dlen = compressBound(sizeof(my_type_map)); #else - dlen = sizeof (my_type_map) + (sizeof (my_type_map) / 100) + 20; + dlen = sizeof(my_type_map) + (sizeof(my_type_map) / 100) + 20; /* documentation says 100.1% oldSize + 12 bytes, but we * should be able to overshoot by more to be safe */ #endif - hdr = GNUNET_malloc (dlen + sizeof (struct GNUNET_MessageHeader)); - tmp = (char *) &hdr[1]; - if ((Z_OK != compress2 ((Bytef *) tmp, - &dlen, - (const Bytef *) &my_type_map, - sizeof (my_type_map), - 9)) || - (dlen >= sizeof (my_type_map))) - { - /* compression failed, use uncompressed map */ - dlen = sizeof (my_type_map); - GNUNET_memcpy (tmp, &my_type_map, sizeof (my_type_map)); - hdr->type = htons (GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP); - } + hdr = GNUNET_malloc(dlen + sizeof(struct GNUNET_MessageHeader)); + tmp = (char *)&hdr[1]; + if ((Z_OK != compress2((Bytef *)tmp, + &dlen, + (const Bytef *)&my_type_map, + sizeof(my_type_map), + 9)) || + (dlen >= sizeof(my_type_map))) + { + /* compression failed, use uncompressed map */ + dlen = sizeof(my_type_map); + GNUNET_memcpy(tmp, &my_type_map, sizeof(my_type_map)); + hdr->type = htons(GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP); + } else - { - /* compression worked, use compressed map */ - hdr->type = htons (GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP); - } - hdr->size = htons ((uint16_t) dlen + sizeof (struct GNUNET_MessageHeader)); + { + /* compression worked, use compressed map */ + hdr->type = htons(GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP); + } + hdr->size = htons((uint16_t)dlen + sizeof(struct GNUNET_MessageHeader)); return hdr; } @@ -156,50 +155,52 @@ GSC_TYPEMAP_compute_type_map_message () * @return NULL on error */ struct GSC_TypeMap * -GSC_TYPEMAP_get_from_message (const struct GNUNET_MessageHeader *msg) +GSC_TYPEMAP_get_from_message(const struct GNUNET_MessageHeader *msg) { struct GSC_TypeMap *ret; uint16_t size; uLongf dlen; - size = ntohs (msg->size); - switch (ntohs (msg->type)) - { - case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP: - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# type maps received"), - 1, - GNUNET_NO); - if (size != sizeof (struct GSC_TypeMap)) + size = ntohs(msg->size); + switch (ntohs(msg->type)) { - GNUNET_break_op (0); + case GNUNET_MESSAGE_TYPE_CORE_BINARY_TYPE_MAP: + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# type maps received"), + 1, + GNUNET_NO); + if (size != sizeof(struct GSC_TypeMap)) + { + GNUNET_break_op(0); + return NULL; + } + ret = GNUNET_new(struct GSC_TypeMap); + GNUNET_memcpy(ret, &msg[1], sizeof(struct GSC_TypeMap)); + return ret; + + case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP: + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# type maps received"), + 1, + GNUNET_NO); + ret = GNUNET_new(struct GSC_TypeMap); + dlen = sizeof(struct GSC_TypeMap); + if ((Z_OK != uncompress((Bytef *)ret, + &dlen, + (const Bytef *)&msg[1], + (uLong)size)) || + (dlen != sizeof(struct GSC_TypeMap))) + { + GNUNET_break_op(0); + GNUNET_free(ret); + return NULL; + } + return ret; + + default: + GNUNET_break(0); return NULL; } - ret = GNUNET_new (struct GSC_TypeMap); - GNUNET_memcpy (ret, &msg[1], sizeof (struct GSC_TypeMap)); - return ret; - case GNUNET_MESSAGE_TYPE_CORE_COMPRESSED_TYPE_MAP: - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# type maps received"), - 1, - GNUNET_NO); - ret = GNUNET_new (struct GSC_TypeMap); - dlen = sizeof (struct GSC_TypeMap); - if ((Z_OK != uncompress ((Bytef *) ret, - &dlen, - (const Bytef *) &msg[1], - (uLong) size)) || - (dlen != sizeof (struct GSC_TypeMap))) - { - GNUNET_break_op (0); - GNUNET_free (ret); - return NULL; - } - return ret; - default: - GNUNET_break (0); - return NULL; - } } @@ -207,17 +208,17 @@ GSC_TYPEMAP_get_from_message (const struct GNUNET_MessageHeader *msg) * Send my type map to all connected peers (it got changed). */ static void -broadcast_my_type_map () +broadcast_my_type_map() { struct GNUNET_MessageHeader *hdr; - hdr = GSC_TYPEMAP_compute_type_map_message (); - GNUNET_STATISTICS_update (GSC_stats, - gettext_noop ("# updates to my type map"), - 1, - GNUNET_NO); - GSC_SESSIONS_broadcast_typemap (hdr); - GNUNET_free (hdr); + hdr = GSC_TYPEMAP_compute_type_map_message(); + GNUNET_STATISTICS_update(GSC_stats, + gettext_noop("# updates to my type map"), + 1, + GNUNET_NO); + GSC_SESSIONS_broadcast_typemap(hdr); + GNUNET_free(hdr); } @@ -228,26 +229,26 @@ broadcast_my_type_map () * @param tlen number of entries in @a types */ void -GSC_TYPEMAP_add (const uint16_t *types, unsigned int tlen) +GSC_TYPEMAP_add(const uint16_t *types, unsigned int tlen) { unsigned int i; int changed; changed = GNUNET_NO; for (i = 0; i < tlen; i++) - { - if (0 == map_counters[types[i]]++) { - my_type_map.bits[types[i] / 32] |= (1 << (types[i] % 32)); - changed = GNUNET_YES; + if (0 == map_counters[types[i]]++) + { + my_type_map.bits[types[i] / 32] |= (1 << (types[i] % 32)); + changed = GNUNET_YES; + } } - } if (GNUNET_YES == changed) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Typemap changed, broadcasting!\n"); - rehash_typemap (); - broadcast_my_type_map (); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Typemap changed, broadcasting!\n"); + rehash_typemap(); + broadcast_my_type_map(); + } } @@ -258,24 +259,24 @@ GSC_TYPEMAP_add (const uint16_t *types, unsigned int tlen) * @param tlen length of the @a types array */ void -GSC_TYPEMAP_remove (const uint16_t *types, unsigned int tlen) +GSC_TYPEMAP_remove(const uint16_t *types, unsigned int tlen) { int changed; changed = GNUNET_NO; for (unsigned int i = 0; i < tlen; i++) - { - if (0 == --map_counters[types[i]]) { - my_type_map.bits[types[i] / 32] &= ~(1 << (types[i] % 32)); - changed = GNUNET_YES; + if (0 == --map_counters[types[i]]) + { + my_type_map.bits[types[i] / 32] &= ~(1 << (types[i] % 32)); + changed = GNUNET_YES; + } } - } if (GNUNET_YES == changed) - { - rehash_typemap (); - broadcast_my_type_map (); - } + { + rehash_typemap(); + broadcast_my_type_map(); + } } @@ -289,9 +290,9 @@ GSC_TYPEMAP_remove (const uint16_t *types, unsigned int tlen) * @return #GNUNET_YES if a type is in the map, #GNUNET_NO if not */ int -GSC_TYPEMAP_test_match (const struct GSC_TypeMap *tmap, - const uint16_t *types, - unsigned int tcnt) +GSC_TYPEMAP_test_match(const struct GSC_TypeMap *tmap, + const uint16_t *types, + unsigned int tcnt) { if (NULL == tmap) return GNUNET_NO; @@ -313,15 +314,15 @@ GSC_TYPEMAP_test_match (const struct GSC_TypeMap *tmap, * @return updated type map (fresh copy) */ struct GSC_TypeMap * -GSC_TYPEMAP_extend (const struct GSC_TypeMap *tmap, - const uint16_t *types, - unsigned int tcnt) +GSC_TYPEMAP_extend(const struct GSC_TypeMap *tmap, + const uint16_t *types, + unsigned int tcnt) { struct GSC_TypeMap *ret; - ret = GNUNET_new (struct GSC_TypeMap); + ret = GNUNET_new(struct GSC_TypeMap); if (NULL != tmap) - GNUNET_memcpy (ret, tmap, sizeof (struct GSC_TypeMap)); + GNUNET_memcpy(ret, tmap, sizeof(struct GSC_TypeMap)); for (unsigned int i = 0; i < tcnt; i++) ret->bits[types[i] / 32] |= (1 << (types[i] % 32)); return ret; @@ -334,9 +335,9 @@ GSC_TYPEMAP_extend (const struct GSC_TypeMap *tmap, * @return an empty type map */ struct GSC_TypeMap * -GSC_TYPEMAP_create () +GSC_TYPEMAP_create() { - return GNUNET_new (struct GSC_TypeMap); + return GNUNET_new(struct GSC_TypeMap); } @@ -346,9 +347,9 @@ GSC_TYPEMAP_create () * @param tmap a type map */ void -GSC_TYPEMAP_destroy (struct GSC_TypeMap *tmap) +GSC_TYPEMAP_destroy(struct GSC_TypeMap *tmap) { - GNUNET_free (tmap); + GNUNET_free(tmap); } @@ -356,7 +357,7 @@ GSC_TYPEMAP_destroy (struct GSC_TypeMap *tmap) * Initialize typemap subsystem. */ void -GSC_TYPEMAP_init () +GSC_TYPEMAP_init() { /* nothing to do */ } @@ -366,7 +367,7 @@ GSC_TYPEMAP_init () * Shutdown typemap subsystem. */ void -GSC_TYPEMAP_done () +GSC_TYPEMAP_done() { /* nothing to do */ } diff --git a/src/core/gnunet-service-core_typemap.h b/src/core/gnunet-service-core_typemap.h index 7b4f8d0f1..0fdb918f3 100644 --- a/src/core/gnunet-service-core_typemap.h +++ b/src/core/gnunet-service-core_typemap.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/gnunet-service-core_typemap.h @@ -42,8 +42,8 @@ struct GSC_TypeMap; * @param tlen number of entries in @a types */ void -GSC_TYPEMAP_add (const uint16_t *types, - unsigned int tlen); +GSC_TYPEMAP_add(const uint16_t *types, + unsigned int tlen); /** @@ -53,8 +53,8 @@ GSC_TYPEMAP_add (const uint16_t *types, * @param tlen number of entries in @a types */ void -GSC_TYPEMAP_remove (const uint16_t *types, - unsigned int tlen); +GSC_TYPEMAP_remove(const uint16_t *types, + unsigned int tlen); /** @@ -63,7 +63,7 @@ GSC_TYPEMAP_remove (const uint16_t *types, * @return this peers current type map message. */ struct GNUNET_MessageHeader * -GSC_TYPEMAP_compute_type_map_message (void); +GSC_TYPEMAP_compute_type_map_message(void); /** @@ -73,7 +73,7 @@ GSC_TYPEMAP_compute_type_map_message (void); * @return #GNUNET_YES if the hash matches, #GNUNET_NO if not */ int -GSC_TYPEMAP_check_hash (const struct GNUNET_HashCode *hc); +GSC_TYPEMAP_check_hash(const struct GNUNET_HashCode *hc); /** @@ -83,8 +83,8 @@ GSC_TYPEMAP_check_hash (const struct GNUNET_HashCode *hc); * @param hc where to store the hash code */ void -GSC_TYPEMAP_hash (const struct GSC_TypeMap *tm, - struct GNUNET_HashCode *hc); +GSC_TYPEMAP_hash(const struct GSC_TypeMap *tm, + struct GNUNET_HashCode *hc); /** @@ -96,7 +96,7 @@ GSC_TYPEMAP_hash (const struct GSC_TypeMap *tm, * @return NULL on error */ struct GSC_TypeMap * -GSC_TYPEMAP_get_from_message (const struct GNUNET_MessageHeader *msg); +GSC_TYPEMAP_get_from_message(const struct GNUNET_MessageHeader *msg); /** @@ -109,9 +109,9 @@ GSC_TYPEMAP_get_from_message (const struct GNUNET_MessageHeader *msg); * @return #GNUNET_YES if a type is in the map, #GNUNET_NO if not */ int -GSC_TYPEMAP_test_match (const struct GSC_TypeMap *tmap, - const uint16_t *types, - unsigned int tcnt); +GSC_TYPEMAP_test_match(const struct GSC_TypeMap *tmap, + const uint16_t *types, + unsigned int tcnt); /** @@ -123,9 +123,9 @@ GSC_TYPEMAP_test_match (const struct GSC_TypeMap *tmap, * @return updated type map (fresh copy) */ struct GSC_TypeMap * -GSC_TYPEMAP_extend (const struct GSC_TypeMap *tmap, - const uint16_t *types, - unsigned int tcnt); +GSC_TYPEMAP_extend(const struct GSC_TypeMap *tmap, + const uint16_t *types, + unsigned int tcnt); /** @@ -134,7 +134,7 @@ GSC_TYPEMAP_extend (const struct GSC_TypeMap *tmap, * @return an empty type map */ struct GSC_TypeMap * -GSC_TYPEMAP_create (void); +GSC_TYPEMAP_create(void); /** @@ -143,21 +143,21 @@ GSC_TYPEMAP_create (void); * @param tmap a type map */ void -GSC_TYPEMAP_destroy (struct GSC_TypeMap *tmap); +GSC_TYPEMAP_destroy(struct GSC_TypeMap *tmap); /** * Initialize typemap subsystem. */ void -GSC_TYPEMAP_init (void); +GSC_TYPEMAP_init(void); /** * Shutdown typemap subsystem. */ void -GSC_TYPEMAP_done (void); +GSC_TYPEMAP_done(void); #endif /* end of gnunet-service-core_typemap.h */ diff --git a/src/core/test_core_api.c b/src/core/test_core_api.c index 1e268c3a6..d29a5f04d 100644 --- a/src/core/test_core_api.c +++ b/src/core/test_core_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/test_core_api.c * @brief testcase for core_api.c @@ -32,8 +32,7 @@ #define MTYPE 12345 -struct PeerContext -{ +struct PeerContext { struct GNUNET_CONFIGURATION_Handle *cfg; struct GNUNET_CORE_Handle *ch; struct GNUNET_PeerIdentity id; @@ -56,18 +55,18 @@ static int ok; #define OKPP \ do \ - { \ - ok++; \ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, \ - "Now at stage %u at %s:%u\n", \ - ok, \ - __FILE__, \ - __LINE__); \ - } while (0) + { \ + ok++; \ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, \ + "Now at stage %u at %s:%u\n", \ + ok, \ + __FILE__, \ + __LINE__); \ + } while (0) static void -offer_hello_done (void *cls) +offer_hello_done(void *cls) { struct PeerContext *p = cls; @@ -76,263 +75,264 @@ offer_hello_done (void *cls) static void -process_hello (void *cls, const struct GNUNET_MessageHeader *message) +process_hello(void *cls, const struct GNUNET_MessageHeader *message) { struct PeerContext *p = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received (my) HELLO from transport service\n"); - GNUNET_assert (message != NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received (my) HELLO from transport service\n"); + GNUNET_assert(message != NULL); if ((p == &p1) && (NULL == p2.oh)) p2.oh = - GNUNET_TRANSPORT_offer_hello (p2.cfg, message, &offer_hello_done, &p2); + GNUNET_TRANSPORT_offer_hello(p2.cfg, message, &offer_hello_done, &p2); if ((p == &p2) && (NULL == p1.oh)) p1.oh = - GNUNET_TRANSPORT_offer_hello (p1.cfg, message, &offer_hello_done, &p1); + GNUNET_TRANSPORT_offer_hello(p1.cfg, message, &offer_hello_done, &p1); } static void -terminate_peer (struct PeerContext *p) +terminate_peer(struct PeerContext *p) { if (NULL != p->ch) - { - GNUNET_CORE_disconnect (p->ch); - p->ch = NULL; - } + { + GNUNET_CORE_disconnect(p->ch); + p->ch = NULL; + } if (NULL != p->ghh) - { - GNUNET_TRANSPORT_hello_get_cancel (p->ghh); - p->ghh = NULL; - } + { + GNUNET_TRANSPORT_hello_get_cancel(p->ghh); + p->ghh = NULL; + } if (NULL != p->oh) - { - GNUNET_TRANSPORT_offer_hello_cancel (p->oh); - p->oh = NULL; - } + { + GNUNET_TRANSPORT_offer_hello_cancel(p->oh); + p->oh = NULL; + } if (NULL != p->ats_sh) - { - GNUNET_ATS_connectivity_suggest_cancel (p->ats_sh); - p->ats_sh = NULL; - } + { + GNUNET_ATS_connectivity_suggest_cancel(p->ats_sh); + p->ats_sh = NULL; + } if (NULL != p->ats) - { - GNUNET_ATS_connectivity_done (p->ats); - p->ats = NULL; - } + { + GNUNET_ATS_connectivity_done(p->ats); + p->ats = NULL; + } } static void -terminate_task (void *cls) +terminate_task(void *cls) { - GNUNET_assert (ok == 6); - terminate_peer (&p1); - terminate_peer (&p2); + GNUNET_assert(ok == 6); + terminate_peer(&p1); + terminate_peer(&p2); ok = 0; } static void -terminate_task_error (void *cls) +terminate_task_error(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ENDING ANGRILY %u\n", ok); - GNUNET_break (0); - terminate_peer (&p1); - terminate_peer (&p2); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "ENDING ANGRILY %u\n", ok); + GNUNET_break(0); + terminate_peer(&p1); + terminate_peer(&p2); ok = 42; } static void * -connect_notify (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +connect_notify(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { struct PeerContext *pc = cls; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; - if (0 == memcmp (&pc->id, peer, sizeof (struct GNUNET_PeerIdentity))) - return (void *) peer; - GNUNET_assert (pc->connect_status == 0); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Encrypted connection established to peer `%s'\n", - GNUNET_i2s (peer)); + if (0 == memcmp(&pc->id, peer, sizeof(struct GNUNET_PeerIdentity))) + return (void *)peer; + GNUNET_assert(pc->connect_status == 0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Encrypted connection established to peer `%s'\n", + GNUNET_i2s(peer)); pc->connect_status = 1; if (pc == &p1) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Asking core (1) for transmission to peer `%s'\n", - GNUNET_i2s (&p2.id)); - env = GNUNET_MQ_msg (msg, MTYPE); - /* enable corking for this test */ - GNUNET_MQ_env_set_options (env, - GNUNET_MQ_PRIO_BEST_EFFORT | - GNUNET_MQ_PREF_CORK_ALLOWED); - /* now actually transmit message */ - GNUNET_assert (ok == 4); - OKPP; - GNUNET_MQ_send (mq, env); - } - return (void *) peer; + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Asking core (1) for transmission to peer `%s'\n", + GNUNET_i2s(&p2.id)); + env = GNUNET_MQ_msg(msg, MTYPE); + /* enable corking for this test */ + GNUNET_MQ_env_set_options(env, + GNUNET_MQ_PRIO_BEST_EFFORT | + GNUNET_MQ_PREF_CORK_ALLOWED); + /* now actually transmit message */ + GNUNET_assert(ok == 4); + OKPP; + GNUNET_MQ_send(mq, env); + } + return (void *)peer; } static void -disconnect_notify (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *internal_cls) +disconnect_notify(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *internal_cls) { struct PeerContext *pc = cls; - if (0 == memcmp (&pc->id, peer, sizeof (struct GNUNET_PeerIdentity))) + if (0 == memcmp(&pc->id, peer, sizeof(struct GNUNET_PeerIdentity))) return; pc->connect_status = 0; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Encrypted connection to `%s' cut\n", - GNUNET_i2s (peer)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Encrypted connection to `%s' cut\n", + GNUNET_i2s(peer)); } static void -handle_test (void *cls, const struct GNUNET_MessageHeader *message) +handle_test(void *cls, const struct GNUNET_MessageHeader *message) { const struct GNUNET_PeerIdentity *peer = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Receiving message from `%s'.\n", - GNUNET_i2s (peer)); - GNUNET_assert (ok == 5); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Receiving message from `%s'.\n", + GNUNET_i2s(peer)); + GNUNET_assert(ok == 5); OKPP; - GNUNET_SCHEDULER_cancel (err_task); - err_task = GNUNET_SCHEDULER_add_now (&terminate_task, NULL); + GNUNET_SCHEDULER_cancel(err_task); + err_task = GNUNET_SCHEDULER_add_now(&terminate_task, NULL); } static void -init_notify (void *cls, const struct GNUNET_PeerIdentity *my_identity) +init_notify(void *cls, const struct GNUNET_PeerIdentity *my_identity) { struct PeerContext *p = cls; struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_fixed_size (test, MTYPE, struct GNUNET_MessageHeader, NULL), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_fixed_size(test, MTYPE, struct GNUNET_MessageHeader, NULL), + GNUNET_MQ_handler_end() }; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Core connection to `%s' established\n", - GNUNET_i2s (my_identity)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Core connection to `%s' established\n", + GNUNET_i2s(my_identity)); p->id = *my_identity; if (cls == &p1) - { - GNUNET_assert (ok == 2); - OKPP; - /* connect p2 */ - p2.ch = GNUNET_CORE_connect (p2.cfg, - &p2, - &init_notify, - &connect_notify, - &disconnect_notify, - handlers); - } + { + GNUNET_assert(ok == 2); + OKPP; + /* connect p2 */ + p2.ch = GNUNET_CORE_connect(p2.cfg, + &p2, + &init_notify, + &connect_notify, + &disconnect_notify, + handlers); + } else - { - GNUNET_assert (ok == 3); - OKPP; - GNUNET_assert (cls == &p2); - p1.ats_sh = GNUNET_ATS_connectivity_suggest (p1.ats, &p2.id, 1); - } + { + GNUNET_assert(ok == 3); + OKPP; + GNUNET_assert(cls == &p2); + p1.ats_sh = GNUNET_ATS_connectivity_suggest(p1.ats, &p2.id, 1); + } } static void -setup_peer (struct PeerContext *p, const char *cfgname) +setup_peer(struct PeerContext *p, const char *cfgname) { char *binary; - binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-arm"); - p->cfg = GNUNET_CONFIGURATION_create (); - p->arm_proc = GNUNET_OS_start_process (GNUNET_YES, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - NULL, - NULL, - NULL, - binary, - "gnunet-service-arm", - "-c", - cfgname, - NULL); - GNUNET_assert (GNUNET_OK == GNUNET_CONFIGURATION_load (p->cfg, cfgname)); - p->ats = GNUNET_ATS_connectivity_init (p->cfg); - GNUNET_assert (NULL != p->ats); - p->ghh = GNUNET_TRANSPORT_hello_get (p->cfg, - GNUNET_TRANSPORT_AC_ANY, - &process_hello, - p); - GNUNET_free (binary); + binary = GNUNET_OS_get_libexec_binary_path("gnunet-service-arm"); + p->cfg = GNUNET_CONFIGURATION_create(); + p->arm_proc = GNUNET_OS_start_process(GNUNET_YES, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + NULL, + NULL, + NULL, + binary, + "gnunet-service-arm", + "-c", + cfgname, + NULL); + GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_load(p->cfg, cfgname)); + p->ats = GNUNET_ATS_connectivity_init(p->cfg); + GNUNET_assert(NULL != p->ats); + p->ghh = GNUNET_TRANSPORT_hello_get(p->cfg, + GNUNET_TRANSPORT_AC_ANY, + &process_hello, + p); + GNUNET_free(binary); } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_fixed_size (test, MTYPE, struct GNUNET_MessageHeader, NULL), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_fixed_size(test, MTYPE, struct GNUNET_MessageHeader, NULL), + GNUNET_MQ_handler_end() }; - GNUNET_assert (ok == 1); + GNUNET_assert(ok == 1); OKPP; - setup_peer (&p1, "test_core_api_peer1.conf"); - setup_peer (&p2, "test_core_api_peer2.conf"); - err_task = GNUNET_SCHEDULER_add_delayed ( - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300), + setup_peer(&p1, "test_core_api_peer1.conf"); + setup_peer(&p2, "test_core_api_peer2.conf"); + err_task = GNUNET_SCHEDULER_add_delayed( + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 300), &terminate_task_error, NULL); - p1.ch = GNUNET_CORE_connect (p1.cfg, - &p1, - &init_notify, - &connect_notify, - &disconnect_notify, - handlers); + p1.ch = GNUNET_CORE_connect(p1.cfg, + &p1, + &init_notify, + &connect_notify, + &disconnect_notify, + handlers); } static void -stop_arm (struct PeerContext *p) +stop_arm(struct PeerContext *p) { - if (0 != GNUNET_OS_process_kill (p->arm_proc, GNUNET_TERM_SIG)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill"); - if (GNUNET_OK != GNUNET_OS_process_wait (p->arm_proc)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "waitpid"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "ARM process %u stopped\n", - GNUNET_OS_process_get_pid (p->arm_proc)); - GNUNET_OS_process_destroy (p->arm_proc); + if (0 != GNUNET_OS_process_kill(p->arm_proc, GNUNET_TERM_SIG)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill"); + if (GNUNET_OK != GNUNET_OS_process_wait(p->arm_proc)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "waitpid"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "ARM process %u stopped\n", + GNUNET_OS_process_get_pid(p->arm_proc)); + GNUNET_OS_process_destroy(p->arm_proc); p->arm_proc = NULL; - GNUNET_CONFIGURATION_destroy (p->cfg); + GNUNET_CONFIGURATION_destroy(p->cfg); } int -main (int argc, char *argv1[]) +main(int argc, char *argv1[]) { - char *const argv[] = {"test-core-api", "-c", "test_core_api_data.conf", NULL}; - struct GNUNET_GETOPT_CommandLineOption options[] = {GNUNET_GETOPT_OPTION_END}; + char *const argv[] = { "test-core-api", "-c", "test_core_api_data.conf", NULL }; + struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; + ok = 1; - GNUNET_log_setup ("test-core-api", "WARNING", NULL); - GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, - argv, - "test-core-api", - "nohelp", - options, - &run, - &ok); - stop_arm (&p1); - stop_arm (&p2); - GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-peer-1"); - GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-peer-2"); + GNUNET_log_setup("test-core-api", "WARNING", NULL); + GNUNET_PROGRAM_run((sizeof(argv) / sizeof(char *)) - 1, + argv, + "test-core-api", + "nohelp", + options, + &run, + &ok); + stop_arm(&p1); + stop_arm(&p2); + GNUNET_DISK_directory_remove("/tmp/test-gnunet-core-peer-1"); + GNUNET_DISK_directory_remove("/tmp/test-gnunet-core-peer-2"); return ok; } diff --git a/src/core/test_core_api_reliability.c b/src/core/test_core_api_reliability.c index 7bd4bfea0..745b0b7d9 100644 --- a/src/core/test_core_api_reliability.c +++ b/src/core/test_core_api_reliability.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/test_core_api_reliability.c * @brief testcase for core_api.c focusing on reliable transmission (with TCP) @@ -41,7 +41,7 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 600) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 600) #define MTYPE 12345 @@ -53,8 +53,7 @@ static struct GNUNET_TIME_Absolute start_time; static struct GNUNET_SCHEDULER_Task *err_task; -struct PeerContext -{ +struct PeerContext { struct GNUNET_CONFIGURATION_Handle *cfg; struct GNUNET_CORE_Handle *ch; struct GNUNET_MQ_Handle *mq; @@ -77,296 +76,294 @@ static int ok; static int32_t tr_n; -#define OKPP do { ok++; GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Now at stage %u at %s:%u\n", ok, __FILE__, __LINE__); } while (0) +#define OKPP do { ok++; GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Now at stage %u at %s:%u\n", ok, __FILE__, __LINE__); } while (0) -struct TestMessage -{ +struct TestMessage { struct GNUNET_MessageHeader header; uint32_t num GNUNET_PACKED; }; static unsigned int -get_size (unsigned int iter) +get_size(unsigned int iter) { unsigned int ret; if (iter < 60000) - return iter + sizeof (struct TestMessage); + return iter + sizeof(struct TestMessage); ret = (iter * iter * iter); - return sizeof (struct TestMessage) + (ret % 60000); + return sizeof(struct TestMessage) + (ret % 60000); } static void -terminate_peer (struct PeerContext *p) +terminate_peer(struct PeerContext *p) { if (NULL != p->ch) - { - GNUNET_CORE_disconnect (p->ch); - p->ch = NULL; - } + { + GNUNET_CORE_disconnect(p->ch); + p->ch = NULL; + } if (NULL != p->ghh) - { - GNUNET_TRANSPORT_hello_get_cancel (p->ghh); - p->ghh = NULL; - } + { + GNUNET_TRANSPORT_hello_get_cancel(p->ghh); + p->ghh = NULL; + } if (NULL != p->oh) - { - GNUNET_TRANSPORT_offer_hello_cancel (p->oh); - p->oh = NULL; - } + { + GNUNET_TRANSPORT_offer_hello_cancel(p->oh); + p->oh = NULL; + } if (NULL != p->ats_sh) - { - GNUNET_ATS_connectivity_suggest_cancel (p->ats_sh); - p->ats_sh = NULL; - } + { + GNUNET_ATS_connectivity_suggest_cancel(p->ats_sh); + p->ats_sh = NULL; + } if (NULL != p->ats) - { - GNUNET_ATS_connectivity_done (p->ats); - p->ats = NULL; - } + { + GNUNET_ATS_connectivity_done(p->ats); + p->ats = NULL; + } } static void -terminate_task_error (void *cls) +terminate_task_error(void *cls) { err_task = NULL; - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); ok = 42; } static void -do_shutdown (void *cls) +do_shutdown(void *cls) { unsigned long long delta; - delta = GNUNET_TIME_absolute_get_duration (start_time).rel_value_us; + delta = GNUNET_TIME_absolute_get_duration(start_time).rel_value_us; if (0 == delta) delta = 1; - fprintf (stderr, - "\nThroughput was %llu kb/s\n", - total_bytes * 1000000LL / 1024 / delta); - GAUGER ("CORE", - "Core throughput/s", - total_bytes * 1000000LL / 1024 / delta, - "kb/s"); + fprintf(stderr, + "\nThroughput was %llu kb/s\n", + total_bytes * 1000000LL / 1024 / delta); + GAUGER("CORE", + "Core throughput/s", + total_bytes * 1000000LL / 1024 / delta, + "kb/s"); if (NULL != err_task) - { - GNUNET_SCHEDULER_cancel (err_task); - err_task = NULL; - } - terminate_peer (&p1); - terminate_peer (&p2); - + { + GNUNET_SCHEDULER_cancel(err_task); + err_task = NULL; + } + terminate_peer(&p1); + terminate_peer(&p2); } static void -send_message (struct GNUNET_MQ_Handle *mq, - int32_t num) +send_message(struct GNUNET_MQ_Handle *mq, + int32_t num) { struct GNUNET_MQ_Envelope *env; struct TestMessage *hdr; unsigned int s; - GNUNET_assert (NULL != mq); - GNUNET_assert (tr_n < TOTAL_MSGS); - s = get_size (tr_n); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending message %u of size %u\n", - tr_n, - s); - env = GNUNET_MQ_msg_extra (hdr, - s - sizeof (struct TestMessage), - MTYPE); - hdr->num = htonl (tr_n); - memset (&hdr[1], - tr_n, - s - sizeof (struct TestMessage)); + GNUNET_assert(NULL != mq); + GNUNET_assert(tr_n < TOTAL_MSGS); + s = get_size(tr_n); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending message %u of size %u\n", + tr_n, + s); + env = GNUNET_MQ_msg_extra(hdr, + s - sizeof(struct TestMessage), + MTYPE); + hdr->num = htonl(tr_n); + memset(&hdr[1], + tr_n, + s - sizeof(struct TestMessage)); tr_n++; - GNUNET_SCHEDULER_cancel (err_task); + GNUNET_SCHEDULER_cancel(err_task); err_task = - GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &terminate_task_error, - NULL); + GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &terminate_task_error, + NULL); total_bytes += s; - GNUNET_MQ_send (mq, - env); + GNUNET_MQ_send(mq, + env); } static void * -connect_notify (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +connect_notify(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { struct PeerContext *pc = cls; - if (0 == memcmp (&pc->id, - peer, - sizeof (struct GNUNET_PeerIdentity))) - return (void *) peer; + if (0 == memcmp(&pc->id, + peer, + sizeof(struct GNUNET_PeerIdentity))) + return (void *)peer; pc->mq = mq; - GNUNET_assert (0 == pc->connect_status); + GNUNET_assert(0 == pc->connect_status); pc->connect_status = 1; if (pc == &p1) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Encrypted connection established to peer `%s'\n", - GNUNET_i2s (peer)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Asking core (1) for transmission to peer `%s'\n", - GNUNET_i2s (&p2.id)); - GNUNET_SCHEDULER_cancel (err_task); - err_task = - GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &terminate_task_error, - NULL); - start_time = GNUNET_TIME_absolute_get (); - send_message (mq, - 0); - } - return (void *) peer; + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Encrypted connection established to peer `%s'\n", + GNUNET_i2s(peer)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Asking core (1) for transmission to peer `%s'\n", + GNUNET_i2s(&p2.id)); + GNUNET_SCHEDULER_cancel(err_task); + err_task = + GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &terminate_task_error, + NULL); + start_time = GNUNET_TIME_absolute_get(); + send_message(mq, + 0); + } + return (void *)peer; } static void -disconnect_notify (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *internal_cls) +disconnect_notify(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *internal_cls) { struct PeerContext *pc = cls; - if (0 == memcmp (&pc->id, - peer, - sizeof (struct GNUNET_PeerIdentity))) + if (0 == memcmp(&pc->id, + peer, + sizeof(struct GNUNET_PeerIdentity))) return; pc->mq = NULL; pc->connect_status = 0; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Encrypted connection to `%s' cut\n", - GNUNET_i2s (peer)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Encrypted connection to `%s' cut\n", + GNUNET_i2s(peer)); } static int -check_test (void *cls, - const struct TestMessage *hdr) +check_test(void *cls, + const struct TestMessage *hdr) { return GNUNET_OK; /* accept all */ } static void -handle_test (void *cls, - const struct TestMessage *hdr) +handle_test(void *cls, + const struct TestMessage *hdr) { static int n; unsigned int s; - s = get_size (n); - if (ntohs (hdr->header.size) != s) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Expected message %u of size %u, got %u bytes of message %u\n", - n, - s, - ntohs (hdr->header.size), - ntohl (hdr->num)); - GNUNET_SCHEDULER_cancel (err_task); - err_task = GNUNET_SCHEDULER_add_now (&terminate_task_error, - NULL); - return; - } - if (ntohl (hdr->num) != n) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Expected message %u of size %u, got %u bytes of message %u\n", - n, - s, - (unsigned int) ntohs (hdr->header.size), - (unsigned int) ntohl (hdr->num)); - GNUNET_SCHEDULER_cancel (err_task); - err_task = GNUNET_SCHEDULER_add_now (&terminate_task_error, - NULL); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got message %u of size %u\n", - (unsigned int) ntohl (hdr->num), - (unsigned int) ntohs (hdr->header.size)); + s = get_size(n); + if (ntohs(hdr->header.size) != s) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Expected message %u of size %u, got %u bytes of message %u\n", + n, + s, + ntohs(hdr->header.size), + ntohl(hdr->num)); + GNUNET_SCHEDULER_cancel(err_task); + err_task = GNUNET_SCHEDULER_add_now(&terminate_task_error, + NULL); + return; + } + if (ntohl(hdr->num) != n) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Expected message %u of size %u, got %u bytes of message %u\n", + n, + s, + (unsigned int)ntohs(hdr->header.size), + (unsigned int)ntohl(hdr->num)); + GNUNET_SCHEDULER_cancel(err_task); + err_task = GNUNET_SCHEDULER_add_now(&terminate_task_error, + NULL); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got message %u of size %u\n", + (unsigned int)ntohl(hdr->num), + (unsigned int)ntohs(hdr->header.size)); n++; if (0 == (n % (TOTAL_MSGS / 100))) - fprintf (stderr, - "%s", - "."); + fprintf(stderr, + "%s", + "."); if (n == TOTAL_MSGS) - { - ok = 0; - GNUNET_SCHEDULER_shutdown (); - } + { + ok = 0; + GNUNET_SCHEDULER_shutdown(); + } else - { - if (n == tr_n) { - send_message (p1.mq, - tr_n); + if (n == tr_n) + { + send_message(p1.mq, + tr_n); + } } - } } static void -init_notify (void *cls, - const struct GNUNET_PeerIdentity *my_identity) +init_notify(void *cls, + const struct GNUNET_PeerIdentity *my_identity) { struct PeerContext *p = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (test, - MTYPE, - struct TestMessage, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(test, + MTYPE, + struct TestMessage, + NULL), + GNUNET_MQ_handler_end() }; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connection to CORE service of `%s' established\n", - GNUNET_i2s (my_identity)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connection to CORE service of `%s' established\n", + GNUNET_i2s(my_identity)); p->id = *my_identity; if (cls == &p1) - { - GNUNET_assert (ok == 2); - OKPP; - /* connect p2 */ - GNUNET_assert (NULL != - (p2.ch = GNUNET_CORE_connect (p2.cfg, - &p2, - &init_notify, - &connect_notify, - &disconnect_notify, - handlers))); - } + { + GNUNET_assert(ok == 2); + OKPP; + /* connect p2 */ + GNUNET_assert(NULL != + (p2.ch = GNUNET_CORE_connect(p2.cfg, + &p2, + &init_notify, + &connect_notify, + &disconnect_notify, + handlers))); + } else - { - GNUNET_assert (ok == 3); - OKPP; - GNUNET_assert (cls == &p2); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Asking transport (1) to connect to peer `%s'\n", - GNUNET_i2s (&p2.id)); - p1.ats_sh = GNUNET_ATS_connectivity_suggest (p1.ats, - &p2.id, - 1); - } + { + GNUNET_assert(ok == 3); + OKPP; + GNUNET_assert(cls == &p2); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Asking transport (1) to connect to peer `%s'\n", + GNUNET_i2s(&p2.id)); + p1.ats_sh = GNUNET_ATS_connectivity_suggest(p1.ats, + &p2.id, + 1); + } } static void -offer_hello_done (void *cls) +offer_hello_done(void *cls) { struct PeerContext *p = cls; @@ -375,129 +372,129 @@ offer_hello_done (void *cls) static void -process_hello (void *cls, - const struct GNUNET_MessageHeader *message) +process_hello(void *cls, + const struct GNUNET_MessageHeader *message) { struct PeerContext *p = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received (my) `%s' from transport service\n", "HELLO"); - GNUNET_assert (message != NULL); - GNUNET_free_non_null (p->hello); - p->hello = GNUNET_copy_message (message); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received (my) `%s' from transport service\n", "HELLO"); + GNUNET_assert(message != NULL); + GNUNET_free_non_null(p->hello); + p->hello = GNUNET_copy_message(message); if ((p == &p1) && (NULL == p2.oh)) - p2.oh = GNUNET_TRANSPORT_offer_hello (p2.cfg, - message, - &offer_hello_done, - &p2); + p2.oh = GNUNET_TRANSPORT_offer_hello(p2.cfg, + message, + &offer_hello_done, + &p2); if ((p == &p2) && (NULL == p1.oh)) - p1.oh = GNUNET_TRANSPORT_offer_hello (p1.cfg, - message, - &offer_hello_done, - &p1); - - if ((p == &p1) && (p2.hello != NULL) && (NULL == p1.oh) ) - p1.oh = GNUNET_TRANSPORT_offer_hello (p1.cfg, - p2.hello, - &offer_hello_done, - &p1); - if ((p == &p2) && (p1.hello != NULL) && (NULL == p2.oh) ) - p2.oh = GNUNET_TRANSPORT_offer_hello (p2.cfg, - p1.hello, - &offer_hello_done, - &p2); + p1.oh = GNUNET_TRANSPORT_offer_hello(p1.cfg, + message, + &offer_hello_done, + &p1); + + if ((p == &p1) && (p2.hello != NULL) && (NULL == p1.oh)) + p1.oh = GNUNET_TRANSPORT_offer_hello(p1.cfg, + p2.hello, + &offer_hello_done, + &p1); + if ((p == &p2) && (p1.hello != NULL) && (NULL == p2.oh)) + p2.oh = GNUNET_TRANSPORT_offer_hello(p2.cfg, + p1.hello, + &offer_hello_done, + &p2); } static void -setup_peer (struct PeerContext *p, - const char *cfgname) +setup_peer(struct PeerContext *p, + const char *cfgname) { char *binary; - binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-arm"); - p->cfg = GNUNET_CONFIGURATION_create (); + binary = GNUNET_OS_get_libexec_binary_path("gnunet-service-arm"); + p->cfg = GNUNET_CONFIGURATION_create(); p->arm_proc - = GNUNET_OS_start_process (GNUNET_YES, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - NULL, NULL, NULL, - binary, - "gnunet-service-arm", - "-c", - cfgname, - NULL); - GNUNET_assert (GNUNET_OK == - GNUNET_CONFIGURATION_load (p->cfg, - cfgname)); - p->ats = GNUNET_ATS_connectivity_init (p->cfg); - GNUNET_assert (NULL != p->ats); - p->ghh = GNUNET_TRANSPORT_hello_get (p->cfg, - GNUNET_TRANSPORT_AC_ANY, - &process_hello, - p); - GNUNET_free (binary); + = GNUNET_OS_start_process(GNUNET_YES, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + NULL, NULL, NULL, + binary, + "gnunet-service-arm", + "-c", + cfgname, + NULL); + GNUNET_assert(GNUNET_OK == + GNUNET_CONFIGURATION_load(p->cfg, + cfgname)); + p->ats = GNUNET_ATS_connectivity_init(p->cfg); + GNUNET_assert(NULL != p->ats); + p->ghh = GNUNET_TRANSPORT_hello_get(p->cfg, + GNUNET_TRANSPORT_AC_ANY, + &process_hello, + p); + GNUNET_free(binary); } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (test, - MTYPE, - struct TestMessage, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(test, + MTYPE, + struct TestMessage, + NULL), + GNUNET_MQ_handler_end() }; - GNUNET_assert (ok == 1); + GNUNET_assert(ok == 1); OKPP; - setup_peer (&p1, - "test_core_api_peer1.conf"); - setup_peer (&p2, - "test_core_api_peer2.conf"); + setup_peer(&p1, + "test_core_api_peer1.conf"); + setup_peer(&p2, + "test_core_api_peer2.conf"); err_task = - GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &terminate_task_error, - NULL); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - - GNUNET_assert (NULL != - (p1.ch = GNUNET_CORE_connect (p1.cfg, - &p1, - &init_notify, - &connect_notify, - &disconnect_notify, - handlers))); + GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &terminate_task_error, + NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); + + GNUNET_assert(NULL != + (p1.ch = GNUNET_CORE_connect(p1.cfg, + &p1, + &init_notify, + &connect_notify, + &disconnect_notify, + handlers))); } static void -stop_arm (struct PeerContext *p) +stop_arm(struct PeerContext *p) { - if (0 != GNUNET_OS_process_kill (p->arm_proc, - GNUNET_TERM_SIG)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "kill"); - if (GNUNET_OK != GNUNET_OS_process_wait (p->arm_proc)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "waitpid"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "ARM process %u stopped\n", - GNUNET_OS_process_get_pid (p->arm_proc)); - GNUNET_OS_process_destroy (p->arm_proc); + if (0 != GNUNET_OS_process_kill(p->arm_proc, + GNUNET_TERM_SIG)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "kill"); + if (GNUNET_OK != GNUNET_OS_process_wait(p->arm_proc)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "waitpid"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "ARM process %u stopped\n", + GNUNET_OS_process_get_pid(p->arm_proc)); + GNUNET_OS_process_destroy(p->arm_proc); p->arm_proc = NULL; - GNUNET_CONFIGURATION_destroy (p->cfg); + GNUNET_CONFIGURATION_destroy(p->cfg); } int -main (int argc, - char *argv1[]) +main(int argc, + char *argv1[]) { char *const argv[] = { "test-core-api-reliability", @@ -508,23 +505,24 @@ main (int argc, struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; + ok = 1; - GNUNET_log_setup ("test-core-api-reliability", - "WARNING", - NULL); - GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, - argv, - "test-core-api-reliability", - "nohelp", - options, - &run, - &ok); - stop_arm (&p1); - stop_arm (&p2); - GNUNET_free_non_null (p1.hello); - GNUNET_free_non_null (p2.hello); - GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-peer-1"); - GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-peer-2"); + GNUNET_log_setup("test-core-api-reliability", + "WARNING", + NULL); + GNUNET_PROGRAM_run((sizeof(argv) / sizeof(char *)) - 1, + argv, + "test-core-api-reliability", + "nohelp", + options, + &run, + &ok); + stop_arm(&p1); + stop_arm(&p2); + GNUNET_free_non_null(p1.hello); + GNUNET_free_non_null(p2.hello); + GNUNET_DISK_directory_remove("/tmp/test-gnunet-core-peer-1"); + GNUNET_DISK_directory_remove("/tmp/test-gnunet-core-peer-2"); return ok; } diff --git a/src/core/test_core_api_send_to_self.c b/src/core/test_core_api_send_to_self.c index 703a635e3..dc132380f 100644 --- a/src/core/test_core_api_send_to_self.c +++ b/src/core/test_core_api_send_to_self.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/test_core_api_send_to_self.c @@ -56,20 +56,20 @@ static struct GNUNET_CORE_Handle *core; * Function scheduled as very last function, cleans up after us */ static void -cleanup (void *cls) +cleanup(void *cls) { if (NULL != die_task) - { - GNUNET_SCHEDULER_cancel (die_task); - die_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(die_task); + die_task = NULL; + } if (NULL != core) - { - GNUNET_CORE_disconnect (core); - core = NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Ending test.\n"); + { + GNUNET_CORE_disconnect(core); + core = NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Ending test.\n"); } @@ -77,64 +77,64 @@ cleanup (void *cls) * Function scheduled as very last function, cleans up after us */ static void -do_timeout (void *cls) +do_timeout(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Test timeout.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Test timeout.\n"); die_task = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } static void -handle_test (void *cls, - const struct GNUNET_MessageHeader *message) +handle_test(void *cls, + const struct GNUNET_MessageHeader *message) { - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); ret = 0; } static void -init (void *cls, - const struct GNUNET_PeerIdentity *my_identity) +init(void *cls, + const struct GNUNET_PeerIdentity *my_identity) { if (NULL == my_identity) - { - GNUNET_break (0); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Correctly connected to CORE; we are the peer %s.\n", - GNUNET_i2s (my_identity)); - GNUNET_memcpy (&myself, - my_identity, - sizeof (struct GNUNET_PeerIdentity)); + { + GNUNET_break(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Correctly connected to CORE; we are the peer %s.\n", + GNUNET_i2s(my_identity)); + GNUNET_memcpy(&myself, + my_identity, + sizeof(struct GNUNET_PeerIdentity)); } static void * -connect_cb (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +connect_cb(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connected to peer %s.\n", - GNUNET_i2s (peer)); - if (0 == memcmp (peer, - &myself, - sizeof (struct GNUNET_PeerIdentity))) - { - struct GNUNET_MQ_Envelope *env; - struct GNUNET_MessageHeader *msg; - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connected to myself; sending message!\n"); - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_DUMMY); - GNUNET_MQ_send (mq, - env); - } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connected to peer %s.\n", + GNUNET_i2s(peer)); + if (0 == memcmp(peer, + &myself, + sizeof(struct GNUNET_PeerIdentity))) + { + struct GNUNET_MQ_Envelope *env; + struct GNUNET_MessageHeader *msg; + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connected to myself; sending message!\n"); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_DUMMY); + GNUNET_MQ_send(mq, + env); + } return NULL; } @@ -146,30 +146,30 @@ connect_cb (void *cls, * @param cfg configuration */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (test, - GNUNET_MESSAGE_TYPE_DUMMY, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(test, + GNUNET_MESSAGE_TYPE_DUMMY, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end() }; core = - GNUNET_CORE_connect (cfg, - NULL, - &init, - &connect_cb, - NULL, - handlers); - GNUNET_SCHEDULER_add_shutdown (&cleanup, - NULL); - die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, - &do_timeout, - NULL); + GNUNET_CORE_connect(cfg, + NULL, + &init, + &connect_cb, + NULL, + handlers); + GNUNET_SCHEDULER_add_shutdown(&cleanup, + NULL); + die_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES, + &do_timeout, + NULL); } @@ -181,12 +181,12 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { ret = 1; - if (0 != GNUNET_TESTING_peer_run ("test-core-api-send-to-self", - "test_core_api_peer1.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-core-api-send-to-self", + "test_core_api_peer1.conf", + &run, NULL)) return 1; return ret; } diff --git a/src/core/test_core_api_start_only.c b/src/core/test_core_api_start_only.c index 92574e3d4..c8a848359 100644 --- a/src/core/test_core_api_start_only.c +++ b/src/core/test_core_api_start_only.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file transport/test_core_api_start_only.c * @brief testcase for core_api.c that only starts two peers, @@ -32,8 +32,7 @@ #define MTYPE 12345 -struct PeerContext -{ +struct PeerContext { struct GNUNET_CONFIGURATION_Handle *cfg; struct GNUNET_CORE_Handle *ch; struct GNUNET_PeerIdentity id; @@ -50,157 +49,157 @@ static int ok; static void * -connect_notify (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +connect_notify(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { return NULL; } static void -disconnect_notify (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *internal_cls) +disconnect_notify(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *internal_cls) { } static struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_handler_end () + GNUNET_MQ_handler_end() }; static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - GNUNET_CORE_disconnect (p1.ch); + GNUNET_CORE_disconnect(p1.ch); p1.ch = NULL; - GNUNET_CORE_disconnect (p2.ch); + GNUNET_CORE_disconnect(p2.ch); p2.ch = NULL; ok = 0; } static void -init_notify (void *cls, - const struct GNUNET_PeerIdentity *my_identity) +init_notify(void *cls, + const struct GNUNET_PeerIdentity *my_identity) { struct PeerContext *p = cls; if (p == &p1) - { - /* connect p2 */ - p2.ch = GNUNET_CORE_connect (p2.cfg, - &p2, - &init_notify, - &connect_notify, - &disconnect_notify, - handlers); - } + { + /* connect p2 */ + p2.ch = GNUNET_CORE_connect(p2.cfg, + &p2, + &init_notify, + &connect_notify, + &disconnect_notify, + handlers); + } else - { - GNUNET_assert (p == &p2); - GNUNET_SCHEDULER_cancel (timeout_task_id); - timeout_task_id = NULL; - GNUNET_SCHEDULER_add_now (&shutdown_task, - NULL); - } + { + GNUNET_assert(p == &p2); + GNUNET_SCHEDULER_cancel(timeout_task_id); + timeout_task_id = NULL; + GNUNET_SCHEDULER_add_now(&shutdown_task, + NULL); + } } static void -setup_peer (struct PeerContext *p, - const char *cfgname) +setup_peer(struct PeerContext *p, + const char *cfgname) { char *binary; - binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-arm"); - p->cfg = GNUNET_CONFIGURATION_create (); + binary = GNUNET_OS_get_libexec_binary_path("gnunet-service-arm"); + p->cfg = GNUNET_CONFIGURATION_create(); p->arm_proc = - GNUNET_OS_start_process (GNUNET_YES, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - NULL, NULL, NULL, - binary, - "gnunet-service-arm", - "-c", cfgname, - NULL); - GNUNET_assert (GNUNET_OK == - GNUNET_CONFIGURATION_load (p->cfg, - cfgname)); - GNUNET_free (binary); + GNUNET_OS_start_process(GNUNET_YES, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + NULL, NULL, NULL, + binary, + "gnunet-service-arm", + "-c", cfgname, + NULL); + GNUNET_assert(GNUNET_OK == + GNUNET_CONFIGURATION_load(p->cfg, + cfgname)); + GNUNET_free(binary); } static void -timeout_task (void *cls) +timeout_task(void *cls) { - fprintf (stderr, - "%s", - "Timeout.\n"); + fprintf(stderr, + "%s", + "Timeout.\n"); if (NULL != p1.ch) - { - GNUNET_CORE_disconnect (p1.ch); - p1.ch = NULL; - } + { + GNUNET_CORE_disconnect(p1.ch); + p1.ch = NULL; + } if (NULL != p2.ch) - { - GNUNET_CORE_disconnect (p2.ch); - p2.ch = NULL; - } + { + GNUNET_CORE_disconnect(p2.ch); + p2.ch = NULL; + } ok = 42; } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - GNUNET_assert (ok == 1); + GNUNET_assert(ok == 1); ok++; - setup_peer (&p1, "test_core_api_peer1.conf"); - setup_peer (&p2, "test_core_api_peer2.conf"); + setup_peer(&p1, "test_core_api_peer1.conf"); + setup_peer(&p2, "test_core_api_peer2.conf"); timeout_task_id = - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply - (GNUNET_TIME_UNIT_MINUTES, - TIMEOUT), - &timeout_task, - NULL); - p1.ch = GNUNET_CORE_connect (p1.cfg, - &p1, - &init_notify, - &connect_notify, - &disconnect_notify, - handlers); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply + (GNUNET_TIME_UNIT_MINUTES, + TIMEOUT), + &timeout_task, + NULL); + p1.ch = GNUNET_CORE_connect(p1.cfg, + &p1, + &init_notify, + &connect_notify, + &disconnect_notify, + handlers); } static void -stop_arm (struct PeerContext *p) +stop_arm(struct PeerContext *p) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Stopping peer\n"); - if (0 != GNUNET_OS_process_kill (p->arm_proc, - GNUNET_TERM_SIG)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "kill"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Stopping peer\n"); + if (0 != GNUNET_OS_process_kill(p->arm_proc, + GNUNET_TERM_SIG)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "kill"); if (GNUNET_OK != - GNUNET_OS_process_wait (p->arm_proc)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "waitpid"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "ARM process %u stopped\n", - (unsigned int) GNUNET_OS_process_get_pid (p->arm_proc)); - GNUNET_OS_process_destroy (p->arm_proc); + GNUNET_OS_process_wait(p->arm_proc)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "waitpid"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "ARM process %u stopped\n", + (unsigned int)GNUNET_OS_process_get_pid(p->arm_proc)); + GNUNET_OS_process_destroy(p->arm_proc); p->arm_proc = NULL; - GNUNET_CONFIGURATION_destroy (p->cfg); + GNUNET_CONFIGURATION_destroy(p->cfg); } static int -check () +check() { char *const argv[] = { "test-core-api-start-only", @@ -211,37 +210,38 @@ check () struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; - GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-peer-1"); - GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-peer-2"); + + GNUNET_DISK_directory_remove("/tmp/test-gnunet-core-peer-1"); + GNUNET_DISK_directory_remove("/tmp/test-gnunet-core-peer-2"); ok = 1; - GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, - argv, - "test-core-api-start-only", - "nohelp", - options, - &run, - &ok); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Test finished\n"); - stop_arm (&p1); - stop_arm (&p2); + GNUNET_PROGRAM_run((sizeof(argv) / sizeof(char *)) - 1, + argv, + "test-core-api-start-only", + "nohelp", + options, + &run, + &ok); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Test finished\n"); + stop_arm(&p1); + stop_arm(&p2); return ok; } int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { int ret; - GNUNET_log_setup ("test-core-api-start-only", - "WARNING", - NULL); - ret = check (); - GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-peer-1"); - GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-peer-2"); + GNUNET_log_setup("test-core-api-start-only", + "WARNING", + NULL); + ret = check(); + GNUNET_DISK_directory_remove("/tmp/test-gnunet-core-peer-1"); + GNUNET_DISK_directory_remove("/tmp/test-gnunet-core-peer-2"); return ret; } diff --git a/src/core/test_core_quota_compliance.c b/src/core/test_core_quota_compliance.c index 908d90ac3..9db9ab750 100644 --- a/src/core/test_core_quota_compliance.c +++ b/src/core/test_core_quota_compliance.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file core/test_core_quota_compliance.c * @brief testcase for core_api.c focusing quota compliance on core level @@ -46,16 +46,16 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 300) /** * What delay do we request from the core service for transmission? */ -#define FAST_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 150) +#define FAST_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 150) #define MTYPE 12345 #define MESSAGESIZE (1024 - 8) -#define MEASUREMENT_LENGTH GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30) +#define MEASUREMENT_LENGTH GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30) static unsigned long long total_bytes_sent; static unsigned long long total_bytes_recv; @@ -67,8 +67,7 @@ static struct GNUNET_SCHEDULER_Task *err_task; static struct GNUNET_SCHEDULER_Task *measure_task; -struct PeerContext -{ +struct PeerContext { struct GNUNET_CONFIGURATION_Handle *cfg; struct GNUNET_CORE_Handle *ch; struct GNUNET_MQ_Handle *mq; @@ -99,13 +98,12 @@ static int running; #if VERBOSE -#define OKPP do { ok++; GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Now at stage %u at %s:%u\n", ok, __FILE__, __LINE__); } while (0) +#define OKPP do { ok++; GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Now at stage %u at %s:%u\n", ok, __FILE__, __LINE__); } while (0) #else #define OKPP do { ok++; } while (0) #endif -struct TestMessage -{ +struct TestMessage { struct GNUNET_MessageHeader header; uint32_t num GNUNET_PACKED; uint8_t pad[MESSAGESIZE]; @@ -113,71 +111,71 @@ struct TestMessage static void -terminate_peer (struct PeerContext *p) +terminate_peer(struct PeerContext *p) { if (NULL != p->ch) - { - GNUNET_CORE_disconnect (p->ch); - p->ch = NULL; - } + { + GNUNET_CORE_disconnect(p->ch); + p->ch = NULL; + } if (NULL != p->ghh) - { - GNUNET_TRANSPORT_hello_get_cancel (p->ghh); - p->ghh = NULL; - } + { + GNUNET_TRANSPORT_hello_get_cancel(p->ghh); + p->ghh = NULL; + } if (NULL != p->oh) - { - GNUNET_TRANSPORT_offer_hello_cancel (p->oh); - p->oh = NULL; - } + { + GNUNET_TRANSPORT_offer_hello_cancel(p->oh); + p->oh = NULL; + } if (NULL != p->ats_sh) - { - GNUNET_ATS_connectivity_suggest_cancel (p->ats_sh); - p->ats_sh = NULL; - } + { + GNUNET_ATS_connectivity_suggest_cancel(p->ats_sh); + p->ats_sh = NULL; + } if (NULL != p->ats) - { - GNUNET_ATS_connectivity_done (p->ats); - p->ats = NULL; - } + { + GNUNET_ATS_connectivity_done(p->ats); + p->ats = NULL; + } if (NULL != p->stats) - { - GNUNET_STATISTICS_destroy (p->stats, GNUNET_NO); - p->stats = NULL; - } + { + GNUNET_STATISTICS_destroy(p->stats, GNUNET_NO); + p->stats = NULL; + } if (NULL != p->hello) - { - GNUNET_free (p->hello); - p->hello = NULL; - } + { + GNUNET_free(p->hello); + p->hello = NULL; + } } static void -shutdown_task (void *cls) +shutdown_task(void *cls) { if (NULL != err_task) - { - GNUNET_SCHEDULER_cancel (err_task); - err_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(err_task); + err_task = NULL; + } if (NULL != measure_task) - { - GNUNET_SCHEDULER_cancel (measure_task); - measure_task = NULL; - } - terminate_peer (&p1); - terminate_peer (&p2); + { + GNUNET_SCHEDULER_cancel(measure_task); + measure_task = NULL; + } + terminate_peer(&p1); + terminate_peer(&p2); } static void -terminate_task_error (void *cls) +terminate_task_error(void *cls) { err_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Testcase failed (timeout)!\n"); - GNUNET_SCHEDULER_shutdown (); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Testcase failed (timeout)!\n"); + GNUNET_SCHEDULER_shutdown(); ok = 42; } @@ -193,28 +191,28 @@ terminate_task_error (void *cls) * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration */ static int -print_stat (void *cls, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +print_stat(void *cls, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { if (cls == &p1) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Peer1 %50s = %12llu\n", - name, - (unsigned long long) value); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Peer1 %50s = %12llu\n", + name, + (unsigned long long)value); if (cls == &p2) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Peer2 %50s = %12llu\n", - name, - (unsigned long long) value); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Peer2 %50s = %12llu\n", + name, + (unsigned long long)value); return GNUNET_OK; } static void -measurement_stop (void *cls) +measurement_stop(void *cls) { unsigned long long delta; unsigned long long throughput_out; @@ -225,17 +223,17 @@ measurement_stop (void *cls) enum GNUNET_ErrorType kind = GNUNET_ERROR_TYPE_DEBUG; measure_task = NULL; - fprintf (stdout, "%s", "\n"); + fprintf(stdout, "%s", "\n"); running = GNUNET_NO; - delta = GNUNET_TIME_absolute_get_duration (start_time).rel_value_us; + delta = GNUNET_TIME_absolute_get_duration(start_time).rel_value_us; if (0 == delta) delta = 1; throughput_out = total_bytes_sent * 1000000LL / delta; /* convert to bytes/s */ throughput_in = total_bytes_recv * 1000000LL / delta; /* convert to bytes/s */ - max_quota_in = GNUNET_MIN (current_quota_p1_in, current_quota_p2_in); - max_quota_out = GNUNET_MIN (current_quota_p1_out, current_quota_p2_out); + max_quota_in = GNUNET_MIN(current_quota_p1_in, current_quota_p2_in); + max_quota_out = GNUNET_MIN(current_quota_p1_out, current_quota_p2_out); if (max_quota_out < max_quota_in) quota_delta = max_quota_in / 3; else @@ -246,167 +244,170 @@ measurement_stop (void *cls) ok = 1; /* fail */ else ok = 0; /* pass */ - GNUNET_STATISTICS_get (p1.stats, - "core", - "# discarded CORE_SEND requests", - NULL, - &print_stat, - &p1); - GNUNET_STATISTICS_get (p1.stats, - "core", - "# discarded CORE_SEND request bytes", - NULL, - &print_stat, - &p1); - GNUNET_STATISTICS_get (p1.stats, - "core", - "# discarded lower priority CORE_SEND requests", - NULL, - &print_stat, - NULL); - GNUNET_STATISTICS_get (p1.stats, - "core", - "# discarded lower priority CORE_SEND request bytes", - NULL, - &print_stat, - &p1); - GNUNET_STATISTICS_get (p2.stats, - "core", - "# discarded CORE_SEND requests", - NULL, - &print_stat, - &p2); - - GNUNET_STATISTICS_get (p2.stats, - "core", - "# discarded CORE_SEND request bytes", - NULL, - &print_stat, - &p2); - GNUNET_STATISTICS_get (p2.stats, - "core", - "# discarded lower priority CORE_SEND requests", - NULL, - &print_stat, - &p2); - GNUNET_STATISTICS_get (p2.stats, - "core", - "# discarded lower priority CORE_SEND request bytes", - NULL, - &print_stat, - &p2); + GNUNET_STATISTICS_get(p1.stats, + "core", + "# discarded CORE_SEND requests", + NULL, + &print_stat, + &p1); + GNUNET_STATISTICS_get(p1.stats, + "core", + "# discarded CORE_SEND request bytes", + NULL, + &print_stat, + &p1); + GNUNET_STATISTICS_get(p1.stats, + "core", + "# discarded lower priority CORE_SEND requests", + NULL, + &print_stat, + NULL); + GNUNET_STATISTICS_get(p1.stats, + "core", + "# discarded lower priority CORE_SEND request bytes", + NULL, + &print_stat, + &p1); + GNUNET_STATISTICS_get(p2.stats, + "core", + "# discarded CORE_SEND requests", + NULL, + &print_stat, + &p2); + + GNUNET_STATISTICS_get(p2.stats, + "core", + "# discarded CORE_SEND request bytes", + NULL, + &print_stat, + &p2); + GNUNET_STATISTICS_get(p2.stats, + "core", + "# discarded lower priority CORE_SEND requests", + NULL, + &print_stat, + &p2); + GNUNET_STATISTICS_get(p2.stats, + "core", + "# discarded lower priority CORE_SEND request bytes", + NULL, + &print_stat, + &p2); if (ok != 0) kind = GNUNET_ERROR_TYPE_ERROR; switch (test) - { - case SYMMETRIC: - GNUNET_log (kind, - "Core quota compliance test with symmetric quotas: %s\n", - (0 == ok) ? "PASSED" : "FAILED"); - break; - case ASYMMETRIC_SEND_LIMITED: - GNUNET_log (kind, - "Core quota compliance test with limited sender quota: %s\n", - (0 == ok) ? "PASSED" : "FAILED"); - break; - case ASYMMETRIC_RECV_LIMITED: - GNUNET_log (kind, - "Core quota compliance test with limited receiver quota: %s\n", - (0 == ok) ? "PASSED" : "FAILED"); - break; - }; - GNUNET_log (kind, - "Peer 1 send rate: %llu b/s (%llu bytes in %llu ms)\n", - throughput_out, - total_bytes_sent, - delta); - GNUNET_log (kind, - "Peer 1 send quota: %llu b/s\n", - current_quota_p1_out); - GNUNET_log (kind, - "Peer 2 receive rate: %llu b/s (%llu bytes in %llu ms)\n", - throughput_in, - total_bytes_recv, - delta); - GNUNET_log (kind, - "Peer 2 receive quota: %llu b/s\n", - current_quota_p2_in); + { + case SYMMETRIC: + GNUNET_log(kind, + "Core quota compliance test with symmetric quotas: %s\n", + (0 == ok) ? "PASSED" : "FAILED"); + break; + + case ASYMMETRIC_SEND_LIMITED: + GNUNET_log(kind, + "Core quota compliance test with limited sender quota: %s\n", + (0 == ok) ? "PASSED" : "FAILED"); + break; + + case ASYMMETRIC_RECV_LIMITED: + GNUNET_log(kind, + "Core quota compliance test with limited receiver quota: %s\n", + (0 == ok) ? "PASSED" : "FAILED"); + break; + } + ; + GNUNET_log(kind, + "Peer 1 send rate: %llu b/s (%llu bytes in %llu ms)\n", + throughput_out, + total_bytes_sent, + delta); + GNUNET_log(kind, + "Peer 1 send quota: %llu b/s\n", + current_quota_p1_out); + GNUNET_log(kind, + "Peer 2 receive rate: %llu b/s (%llu bytes in %llu ms)\n", + throughput_in, + total_bytes_recv, + delta); + GNUNET_log(kind, + "Peer 2 receive quota: %llu b/s\n", + current_quota_p2_in); /* - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Max. inbound quota allowed: %llu b/s\n",max_quota_in ); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Max. outbound quota allowed: %llu b/s\n",max_quota_out); -*/ - GNUNET_SCHEDULER_shutdown (); + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Max. inbound quota allowed: %llu b/s\n",max_quota_in ); + GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,"Max. outbound quota allowed: %llu b/s\n",max_quota_out); + */ + GNUNET_SCHEDULER_shutdown(); } static void -do_transmit (void *cls) +do_transmit(void *cls) { struct TestMessage *hdr; struct GNUNET_MQ_Envelope *env; - env = GNUNET_MQ_msg (hdr, - MTYPE); - hdr->num = htonl (tr_n); - memset (&hdr->pad, - tr_n, - MESSAGESIZE); + env = GNUNET_MQ_msg(hdr, + MTYPE); + hdr->num = htonl(tr_n); + memset(&hdr->pad, + tr_n, + MESSAGESIZE); tr_n++; - GNUNET_SCHEDULER_cancel (err_task); + GNUNET_SCHEDULER_cancel(err_task); err_task = - GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &terminate_task_error, - NULL); - total_bytes_sent += sizeof (struct TestMessage); - GNUNET_MQ_send (p1.mq, - env); + GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &terminate_task_error, + NULL); + total_bytes_sent += sizeof(struct TestMessage); + GNUNET_MQ_send(p1.mq, + env); } static void * -connect_notify (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +connect_notify(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { struct PeerContext *pc = cls; - if (0 == memcmp (&pc->id, - peer, - sizeof (struct GNUNET_PeerIdentity))) + if (0 == memcmp(&pc->id, + peer, + sizeof(struct GNUNET_PeerIdentity))) return NULL; /* loopback */ - GNUNET_assert (0 == pc->connect_status); + GNUNET_assert(0 == pc->connect_status); pc->connect_status = 1; pc->mq = mq; if (pc == &p1) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Encrypted connection established to peer `%s'\n", - GNUNET_i2s (peer)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Asking core (1) for transmission to peer `%s'\n", - GNUNET_i2s (&p2.id)); - GNUNET_SCHEDULER_cancel (err_task); - err_task = - GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &terminate_task_error, - NULL); - start_time = GNUNET_TIME_absolute_get (); - running = GNUNET_YES; - measure_task = - GNUNET_SCHEDULER_add_delayed (MEASUREMENT_LENGTH, - &measurement_stop, - NULL); - do_transmit (NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Encrypted connection established to peer `%s'\n", + GNUNET_i2s(peer)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Asking core (1) for transmission to peer `%s'\n", + GNUNET_i2s(&p2.id)); + GNUNET_SCHEDULER_cancel(err_task); + err_task = + GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &terminate_task_error, + NULL); + start_time = GNUNET_TIME_absolute_get(); + running = GNUNET_YES; + measure_task = + GNUNET_SCHEDULER_add_delayed(MEASUREMENT_LENGTH, + &measurement_stop, + NULL); + do_transmit(NULL); + } return pc; } static void -disconnect_notify (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *internal_cls) +disconnect_notify(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *internal_cls) { struct PeerContext *pc = cls; @@ -415,99 +416,99 @@ disconnect_notify (void *cls, pc->connect_status = 0; pc->mq = NULL; if (NULL != measure_task) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Measurement aborted due to disconnect!\n"); - GNUNET_SCHEDULER_cancel (measure_task); - measure_task = NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Encrypted connection to `%s' cut\n", - GNUNET_i2s (peer)); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Measurement aborted due to disconnect!\n"); + GNUNET_SCHEDULER_cancel(measure_task); + measure_task = NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Encrypted connection to `%s' cut\n", + GNUNET_i2s(peer)); } static void -handle_test (void *cls, - const struct TestMessage *hdr) +handle_test(void *cls, + const struct TestMessage *hdr) { static int n; - total_bytes_recv += sizeof (struct TestMessage); - if (ntohl (hdr->num) != n) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Expected message %u, got message %u\n", - n, - ntohl (hdr->num)); - GNUNET_SCHEDULER_cancel (err_task); - err_task = GNUNET_SCHEDULER_add_now (&terminate_task_error, - NULL); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got message %u\n", - ntohl (hdr->num)); + total_bytes_recv += sizeof(struct TestMessage); + if (ntohl(hdr->num) != n) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Expected message %u, got message %u\n", + n, + ntohl(hdr->num)); + GNUNET_SCHEDULER_cancel(err_task); + err_task = GNUNET_SCHEDULER_add_now(&terminate_task_error, + NULL); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got message %u\n", + ntohl(hdr->num)); n++; if (0 == (n % 10)) - fprintf (stderr, "%s", "."); + fprintf(stderr, "%s", "."); if (GNUNET_YES == running) - do_transmit (NULL); + do_transmit(NULL); } static void -init_notify (void *cls, - const struct GNUNET_PeerIdentity *my_identity) +init_notify(void *cls, + const struct GNUNET_PeerIdentity *my_identity) { struct PeerContext *p = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (test, - MTYPE, - struct TestMessage, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(test, + MTYPE, + struct TestMessage, + NULL), + GNUNET_MQ_handler_end() }; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connection to CORE service of `%s' established\n", - GNUNET_i2s (my_identity)); - GNUNET_assert (NULL != my_identity); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connection to CORE service of `%s' established\n", + GNUNET_i2s(my_identity)); + GNUNET_assert(NULL != my_identity); p->id = *my_identity; if (cls == &p1) - { - GNUNET_assert (ok == 2); - OKPP; - /* connect p2 */ - p2.ch = GNUNET_CORE_connect (p2.cfg, - &p2, - &init_notify, - &connect_notify, - &disconnect_notify, - handlers); - } + { + GNUNET_assert(ok == 2); + OKPP; + /* connect p2 */ + p2.ch = GNUNET_CORE_connect(p2.cfg, + &p2, + &init_notify, + &connect_notify, + &disconnect_notify, + handlers); + } else - { - GNUNET_assert (ok == 3); - OKPP; - GNUNET_assert (cls == &p2); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Asking core (1) to connect to peer `%s' and vice-versa\n", - GNUNET_i2s (&p2.id)); - p1.ats_sh = GNUNET_ATS_connectivity_suggest (p1.ats, - &p2.id, - 1); - p2.ats_sh = GNUNET_ATS_connectivity_suggest (p2.ats, - &p1.id, - 1); - } + { + GNUNET_assert(ok == 3); + OKPP; + GNUNET_assert(cls == &p2); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Asking core (1) to connect to peer `%s' and vice-versa\n", + GNUNET_i2s(&p2.id)); + p1.ats_sh = GNUNET_ATS_connectivity_suggest(p1.ats, + &p2.id, + 1); + p2.ats_sh = GNUNET_ATS_connectivity_suggest(p2.ats, + &p1.id, + 1); + } } static void -offer_hello_done (void *cls) +offer_hello_done(void *cls) { struct PeerContext *p = cls; @@ -516,175 +517,175 @@ offer_hello_done (void *cls) static void -process_hello (void *cls, - const struct GNUNET_MessageHeader *message) +process_hello(void *cls, + const struct GNUNET_MessageHeader *message) { struct PeerContext *p = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received (my) HELLO from transport service\n"); - GNUNET_assert (message != NULL); - p->hello = GNUNET_malloc (ntohs (message->size)); - GNUNET_memcpy (p->hello, message, ntohs (message->size)); - if ( (p == &p1) && - (NULL == p2.oh) ) - p2.oh = GNUNET_TRANSPORT_offer_hello (p2.cfg, - message, - &offer_hello_done, - &p2); - if ( (p == &p2) && - (NULL == p1.oh) ) - p1.oh = GNUNET_TRANSPORT_offer_hello (p1.cfg, message, - &offer_hello_done, - &p1); - - if ( (p == &p1) && - (NULL != p2.hello) && - (NULL == p1.oh) ) - p1.oh = GNUNET_TRANSPORT_offer_hello (p1.cfg, - p2.hello, - &offer_hello_done, - &p1); - if ( (p == &p2) && - (NULL != p1.hello) && - (NULL == p2.oh) ) - p2.oh = GNUNET_TRANSPORT_offer_hello (p2.cfg, - p1.hello, - &offer_hello_done, - &p2); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received (my) HELLO from transport service\n"); + GNUNET_assert(message != NULL); + p->hello = GNUNET_malloc(ntohs(message->size)); + GNUNET_memcpy(p->hello, message, ntohs(message->size)); + if ((p == &p1) && + (NULL == p2.oh)) + p2.oh = GNUNET_TRANSPORT_offer_hello(p2.cfg, + message, + &offer_hello_done, + &p2); + if ((p == &p2) && + (NULL == p1.oh)) + p1.oh = GNUNET_TRANSPORT_offer_hello(p1.cfg, message, + &offer_hello_done, + &p1); + + if ((p == &p1) && + (NULL != p2.hello) && + (NULL == p1.oh)) + p1.oh = GNUNET_TRANSPORT_offer_hello(p1.cfg, + p2.hello, + &offer_hello_done, + &p1); + if ((p == &p2) && + (NULL != p1.hello) && + (NULL == p2.oh)) + p2.oh = GNUNET_TRANSPORT_offer_hello(p2.cfg, + p1.hello, + &offer_hello_done, + &p2); } static void -setup_peer (struct PeerContext *p, - const char *cfgname) +setup_peer(struct PeerContext *p, + const char *cfgname) { char *binary; - binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-arm"); - p->cfg = GNUNET_CONFIGURATION_create (); + binary = GNUNET_OS_get_libexec_binary_path("gnunet-service-arm"); + p->cfg = GNUNET_CONFIGURATION_create(); p->arm_proc = - GNUNET_OS_start_process (GNUNET_YES, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - NULL, NULL, NULL, - binary, - "gnunet-service-arm", - "-c", - cfgname, - NULL); - GNUNET_assert (GNUNET_OK == - GNUNET_CONFIGURATION_load (p->cfg, - cfgname)); - p->stats = GNUNET_STATISTICS_create ("core", - p->cfg); - GNUNET_assert (NULL != p->stats); - p->ats = GNUNET_ATS_connectivity_init (p->cfg); - GNUNET_assert (NULL != p->ats); - p->ghh = GNUNET_TRANSPORT_hello_get (p->cfg, - GNUNET_TRANSPORT_AC_ANY, - &process_hello, - p); - GNUNET_free (binary); + GNUNET_OS_start_process(GNUNET_YES, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + NULL, NULL, NULL, + binary, + "gnunet-service-arm", + "-c", + cfgname, + NULL); + GNUNET_assert(GNUNET_OK == + GNUNET_CONFIGURATION_load(p->cfg, + cfgname)); + p->stats = GNUNET_STATISTICS_create("core", + p->cfg); + GNUNET_assert(NULL != p->stats); + p->ats = GNUNET_ATS_connectivity_init(p->cfg); + GNUNET_assert(NULL != p->ats); + p->ghh = GNUNET_TRANSPORT_hello_get(p->cfg, + GNUNET_TRANSPORT_AC_ANY, + &process_hello, + p); + GNUNET_free(binary); } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (test, - MTYPE, - struct TestMessage, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(test, + MTYPE, + struct TestMessage, + NULL), + GNUNET_MQ_handler_end() }; - GNUNET_assert (ok == 1); + GNUNET_assert(ok == 1); OKPP; err_task = - GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &terminate_task_error, - NULL); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); + GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &terminate_task_error, + NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); if (test == SYMMETRIC) - { - setup_peer (&p1, - "test_core_quota_peer1.conf"); - setup_peer (&p2, - "test_core_quota_peer2.conf"); - } + { + setup_peer(&p1, + "test_core_quota_peer1.conf"); + setup_peer(&p2, + "test_core_quota_peer2.conf"); + } else if (test == ASYMMETRIC_SEND_LIMITED) - { - setup_peer (&p1, - "test_core_quota_asymmetric_send_limit_peer1.conf"); - setup_peer (&p2, - "test_core_quota_asymmetric_send_limit_peer2.conf"); - } + { + setup_peer(&p1, + "test_core_quota_asymmetric_send_limit_peer1.conf"); + setup_peer(&p2, + "test_core_quota_asymmetric_send_limit_peer2.conf"); + } else if (test == ASYMMETRIC_RECV_LIMITED) - { - setup_peer (&p1, - "test_core_quota_asymmetric_recv_limited_peer1.conf"); - setup_peer (&p2, - "test_core_quota_asymmetric_recv_limited_peer2.conf"); - } - - GNUNET_assert (test != -1); - GNUNET_assert (GNUNET_SYSERR != - GNUNET_CONFIGURATION_get_value_size (p1.cfg, - "ATS", - "WAN_QUOTA_IN", - ¤t_quota_p1_in)); - GNUNET_assert (GNUNET_SYSERR != - GNUNET_CONFIGURATION_get_value_size (p2.cfg, - "ATS", - "WAN_QUOTA_IN", - ¤t_quota_p2_in)); - GNUNET_assert (GNUNET_SYSERR != - GNUNET_CONFIGURATION_get_value_size (p1.cfg, - "ATS", - "WAN_QUOTA_OUT", - ¤t_quota_p1_out)); - GNUNET_assert (GNUNET_SYSERR != - GNUNET_CONFIGURATION_get_value_size (p2.cfg, - "ATS", - "WAN_QUOTA_OUT", - ¤t_quota_p2_out)); - - p1.ch = GNUNET_CORE_connect (p1.cfg, - &p1, - &init_notify, - &connect_notify, - &disconnect_notify, - handlers); + { + setup_peer(&p1, + "test_core_quota_asymmetric_recv_limited_peer1.conf"); + setup_peer(&p2, + "test_core_quota_asymmetric_recv_limited_peer2.conf"); + } + + GNUNET_assert(test != -1); + GNUNET_assert(GNUNET_SYSERR != + GNUNET_CONFIGURATION_get_value_size(p1.cfg, + "ATS", + "WAN_QUOTA_IN", + ¤t_quota_p1_in)); + GNUNET_assert(GNUNET_SYSERR != + GNUNET_CONFIGURATION_get_value_size(p2.cfg, + "ATS", + "WAN_QUOTA_IN", + ¤t_quota_p2_in)); + GNUNET_assert(GNUNET_SYSERR != + GNUNET_CONFIGURATION_get_value_size(p1.cfg, + "ATS", + "WAN_QUOTA_OUT", + ¤t_quota_p1_out)); + GNUNET_assert(GNUNET_SYSERR != + GNUNET_CONFIGURATION_get_value_size(p2.cfg, + "ATS", + "WAN_QUOTA_OUT", + ¤t_quota_p2_out)); + + p1.ch = GNUNET_CORE_connect(p1.cfg, + &p1, + &init_notify, + &connect_notify, + &disconnect_notify, + handlers); } static void -stop_arm (struct PeerContext *p) +stop_arm(struct PeerContext *p) { - if (0 != GNUNET_OS_process_kill (p->arm_proc, - GNUNET_TERM_SIG)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "kill"); + if (0 != GNUNET_OS_process_kill(p->arm_proc, + GNUNET_TERM_SIG)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "kill"); if (GNUNET_OK != - GNUNET_OS_process_wait (p->arm_proc)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "waitpid"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "ARM process %u stopped\n", - GNUNET_OS_process_get_pid (p->arm_proc)); - GNUNET_OS_process_destroy (p->arm_proc); + GNUNET_OS_process_wait(p->arm_proc)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "waitpid"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "ARM process %u stopped\n", + GNUNET_OS_process_get_pid(p->arm_proc)); + GNUNET_OS_process_destroy(p->arm_proc); p->arm_proc = NULL; - GNUNET_CONFIGURATION_destroy (p->cfg); + GNUNET_CONFIGURATION_destroy(p->cfg); } static int -check () +check() { char *const argv[] = { "test-core-quota-compliance", @@ -695,73 +696,77 @@ check () struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; + ok = 1; - GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, - argv, - "test-core-quota-compliance", - "nohelp", - options, - &run, - &ok); - stop_arm (&p1); - stop_arm (&p2); + GNUNET_PROGRAM_run((sizeof(argv) / sizeof(char *)) - 1, + argv, + "test-core-quota-compliance", + "nohelp", + options, + &run, + &ok); + stop_arm(&p1); + stop_arm(&p2); return ok; } static void -cleanup_directory (int test) +cleanup_directory(int test) { - switch (test) { - case SYMMETRIC: - GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-quota-sym-peer-1/"); - GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-quota-sym-peer-2/"); - break; - case ASYMMETRIC_SEND_LIMITED: - GNUNET_DISK_directory_remove + switch (test) + { + case SYMMETRIC: + GNUNET_DISK_directory_remove("/tmp/test-gnunet-core-quota-sym-peer-1/"); + GNUNET_DISK_directory_remove("/tmp/test-gnunet-core-quota-sym-peer-2/"); + break; + + case ASYMMETRIC_SEND_LIMITED: + GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-quota-asym-send-lim-peer-1/"); - GNUNET_DISK_directory_remove + GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-quota-asym-send-lim-peer-2/"); - break; - case ASYMMETRIC_RECV_LIMITED: - GNUNET_DISK_directory_remove + break; + + case ASYMMETRIC_RECV_LIMITED: + GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-quota-asym-recv-lim-peer-1/"); - GNUNET_DISK_directory_remove + GNUNET_DISK_directory_remove ("/tmp/test-gnunet-core-quota-asym-recv-lim-peer-2/"); - break; - } + break; + } } int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { int ret; test = -1; - if (NULL != strstr (argv[0], - "_symmetric")) - { - test = SYMMETRIC; - } - else if (NULL != strstr (argv[0], - "_asymmetric_send")) - { - test = ASYMMETRIC_SEND_LIMITED; - } - else if (NULL != strstr (argv[0], - "_asymmetric_recv")) - { - test = ASYMMETRIC_RECV_LIMITED; - } - GNUNET_assert (test != -1); - cleanup_directory (test); - GNUNET_log_setup ("test-core-quota-compliance", - "WARNING", - NULL); - ret = check (); - cleanup_directory (test); + if (NULL != strstr(argv[0], + "_symmetric")) + { + test = SYMMETRIC; + } + else if (NULL != strstr(argv[0], + "_asymmetric_send")) + { + test = ASYMMETRIC_SEND_LIMITED; + } + else if (NULL != strstr(argv[0], + "_asymmetric_recv")) + { + test = ASYMMETRIC_RECV_LIMITED; + } + GNUNET_assert(test != -1); + cleanup_directory(test); + GNUNET_log_setup("test-core-quota-compliance", + "WARNING", + NULL); + ret = check(); + cleanup_directory(test); return ret; } diff --git a/src/credential/credential.h b/src/credential/credential.h index 23db51e99..fcc81de6c 100644 --- a/src/credential/credential.h +++ b/src/credential/credential.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -32,8 +32,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Message from client to Credential service to collect credentials. */ -struct CollectMessage -{ +struct CollectMessage { /** * Header of type #GNUNET_MESSAGE_TYPE_CREDENTIAL_VERIFY */ @@ -60,15 +59,13 @@ struct CollectMessage uint32_t id GNUNET_PACKED; /* Followed by the zero-terminated attribute */ - }; /** * Message from client to Credential service to verify attributes. */ -struct VerifyMessage -{ +struct VerifyMessage { /** * Header of type #GNUNET_MESSAGE_TYPE_CREDENTIAL_VERIFY */ @@ -100,17 +97,15 @@ struct VerifyMessage uint32_t id GNUNET_PACKED; /* Followed by the zero-terminated attribute and credentials to look up */ - }; /** * Message from CREDENTIAL service to client: new results. */ -struct DelegationChainResultMessage -{ +struct DelegationChainResultMessage { /** - * Header of type #GNUNET_MESSAGE_TYPE_CREDENTIAL_VERIFY_RESULT + * Header of type #GNUNET_MESSAGE_TYPE_CREDENTIAL_VERIFY_RESULT */ struct GNUNET_MessageHeader header; @@ -118,7 +113,7 @@ struct DelegationChainResultMessage * Unique identifier for this request (for key collisions). */ uint32_t id GNUNET_PACKED; - + /** * Indicates if credential has been found at all */ @@ -135,16 +130,14 @@ struct DelegationChainResultMessage uint32_t c_count GNUNET_PACKED; /* followed by ad_count GNUNET_CREDENTIAL_RecordData structs*/ - }; -struct DelegationRecordData -{ +struct DelegationRecordData { /** * Subject key */ struct GNUNET_CRYPTO_EcdsaPublicKey subject_key; - + /** * Subject attributes */ @@ -152,23 +145,22 @@ struct DelegationRecordData }; -struct ChainEntry -{ +struct ChainEntry { /** * Issuer key */ struct GNUNET_CRYPTO_EcdsaPublicKey issuer_key; - + /** * Subject key */ struct GNUNET_CRYPTO_EcdsaPublicKey subject_key; - + /** * Issuer attributes */ uint32_t issuer_attribute_len GNUNET_PACKED; - + /** * Subject attributes */ @@ -176,9 +168,7 @@ struct ChainEntry }; -struct CredentialEntry -{ - +struct CredentialEntry { /** * The signature for this credential by the issuer */ @@ -203,7 +193,7 @@ struct CredentialEntry * Expiration time of this credential */ uint64_t expiration GNUNET_PACKED; - + /** * Issuer attribute length */ diff --git a/src/credential/credential_api.c b/src/credential/credential_api.c index 84c32a724..dc1052484 100644 --- a/src/credential/credential_api.c +++ b/src/credential/credential_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file credential/credential_api.c * @brief library to access the CREDENTIAL service @@ -35,14 +35,12 @@ #include "gnunet_identity_service.h" -#define LOG(kind,...) GNUNET_log_from (kind, "credential-api",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "credential-api", __VA_ARGS__) /** * Handle to a verify request */ -struct GNUNET_CREDENTIAL_Request -{ - +struct GNUNET_CREDENTIAL_Request { /** * DLL */ @@ -77,16 +75,13 @@ struct GNUNET_CREDENTIAL_Request * request id */ uint32_t r_id; - }; /** * Connection to the CREDENTIAL service. */ -struct GNUNET_CREDENTIAL_Handle -{ - +struct GNUNET_CREDENTIAL_Handle { /** * Configuration to use. */ @@ -121,7 +116,6 @@ struct GNUNET_CREDENTIAL_Handle * Request Id generator. Incremented by one for each request. */ uint32_t r_id_gen; - }; @@ -131,7 +125,7 @@ struct GNUNET_CREDENTIAL_Handle * @param handle the handle to the CREDENTIAL service */ static void -reconnect (struct GNUNET_CREDENTIAL_Handle *handle); +reconnect(struct GNUNET_CREDENTIAL_Handle *handle); /** @@ -140,12 +134,12 @@ reconnect (struct GNUNET_CREDENTIAL_Handle *handle); * @param cls the handle */ static void -reconnect_task (void *cls) +reconnect_task(void *cls) { struct GNUNET_CREDENTIAL_Handle *handle = cls; handle->reconnect_task = NULL; - reconnect (handle); + reconnect(handle); } @@ -155,16 +149,16 @@ reconnect_task (void *cls) * @param handle our handle */ static void -force_reconnect (struct GNUNET_CREDENTIAL_Handle *handle) +force_reconnect(struct GNUNET_CREDENTIAL_Handle *handle) { - GNUNET_MQ_destroy (handle->mq); + GNUNET_MQ_destroy(handle->mq); handle->mq = NULL; handle->reconnect_backoff - = GNUNET_TIME_STD_BACKOFF (handle->reconnect_backoff); + = GNUNET_TIME_STD_BACKOFF(handle->reconnect_backoff); handle->reconnect_task - = GNUNET_SCHEDULER_add_delayed (handle->reconnect_backoff, - &reconnect_task, - handle); + = GNUNET_SCHEDULER_add_delayed(handle->reconnect_backoff, + &reconnect_task, + handle); } @@ -177,12 +171,12 @@ force_reconnect (struct GNUNET_CREDENTIAL_Handle *handle) * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_CREDENTIAL_Handle *handle = cls; - force_reconnect (handle); + force_reconnect(handle); } /** @@ -192,8 +186,8 @@ mq_error_handler (void *cls, * @param vr_msg the incoming message */ static int -check_result (void *cls, - const struct DelegationChainResultMessage *vr_msg) +check_result(void *cls, + const struct DelegationChainResultMessage *vr_msg) { //TODO return GNUNET_OK; @@ -207,22 +201,22 @@ check_result (void *cls, * @param vr_msg the incoming message */ static void -handle_result (void *cls, - const struct DelegationChainResultMessage *vr_msg) +handle_result(void *cls, + const struct DelegationChainResultMessage *vr_msg) { struct GNUNET_CREDENTIAL_Handle *handle = cls; - uint32_t r_id = ntohl (vr_msg->id); + uint32_t r_id = ntohl(vr_msg->id); struct GNUNET_CREDENTIAL_Request *vr; - size_t mlen = ntohs (vr_msg->header.size) - sizeof (*vr_msg); - uint32_t d_count = ntohl (vr_msg->d_count); - uint32_t c_count = ntohl (vr_msg->c_count); + size_t mlen = ntohs(vr_msg->header.size) - sizeof(*vr_msg); + uint32_t d_count = ntohl(vr_msg->d_count); + uint32_t c_count = ntohl(vr_msg->c_count); struct GNUNET_CREDENTIAL_Delegation d_chain[d_count]; struct GNUNET_CREDENTIAL_Credential creds[c_count]; GNUNET_CREDENTIAL_CredentialResultProcessor proc; void *proc_cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received verify reply from CREDENTIAL service\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received verify reply from CREDENTIAL service\n"); for (vr = handle->request_head; NULL != vr; vr = vr->next) if (vr->r_id == r_id) break; @@ -230,32 +224,34 @@ handle_result (void *cls, return; proc = vr->verify_proc; proc_cls = vr->proc_cls; - GNUNET_CONTAINER_DLL_remove (handle->request_head, - handle->request_tail, - vr); - GNUNET_MQ_discard (vr->env); - GNUNET_free (vr); - GNUNET_assert (GNUNET_OK == - GNUNET_CREDENTIAL_delegation_chain_deserialize (mlen, - (const char*) &vr_msg[1], - d_count, - d_chain, - c_count, - creds)); - if (GNUNET_NO == ntohl (vr_msg->cred_found)) - { - proc (proc_cls, - 0, - NULL, - 0, - NULL); // TODO - } else { - proc (proc_cls, - d_count, - d_chain, - c_count, - creds); - } + GNUNET_CONTAINER_DLL_remove(handle->request_head, + handle->request_tail, + vr); + GNUNET_MQ_discard(vr->env); + GNUNET_free(vr); + GNUNET_assert(GNUNET_OK == + GNUNET_CREDENTIAL_delegation_chain_deserialize(mlen, + (const char*)&vr_msg[1], + d_count, + d_chain, + c_count, + creds)); + if (GNUNET_NO == ntohl(vr_msg->cred_found)) + { + proc(proc_cls, + 0, + NULL, + 0, + NULL); // TODO + } + else + { + proc(proc_cls, + d_count, + d_chain, + c_count, + creds); + } } @@ -265,34 +261,34 @@ handle_result (void *cls, * @param handle the handle to the CREDENTIAL service */ static void -reconnect (struct GNUNET_CREDENTIAL_Handle *handle) +reconnect(struct GNUNET_CREDENTIAL_Handle *handle) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (result, - GNUNET_MESSAGE_TYPE_CREDENTIAL_VERIFY_RESULT, - struct DelegationChainResultMessage, - handle), - GNUNET_MQ_hd_var_size (result, - GNUNET_MESSAGE_TYPE_CREDENTIAL_COLLECT_RESULT, - struct DelegationChainResultMessage, - handle), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(result, + GNUNET_MESSAGE_TYPE_CREDENTIAL_VERIFY_RESULT, + struct DelegationChainResultMessage, + handle), + GNUNET_MQ_hd_var_size(result, + GNUNET_MESSAGE_TYPE_CREDENTIAL_COLLECT_RESULT, + struct DelegationChainResultMessage, + handle), + GNUNET_MQ_handler_end() }; struct GNUNET_CREDENTIAL_Request *vr; - GNUNET_assert (NULL == handle->mq); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Trying to connect to CREDENTIAL\n"); - handle->mq = GNUNET_CLIENT_connect (handle->cfg, - "credential", - handlers, - &mq_error_handler, - handle); + GNUNET_assert(NULL == handle->mq); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Trying to connect to CREDENTIAL\n"); + handle->mq = GNUNET_CLIENT_connect(handle->cfg, + "credential", + handlers, + &mq_error_handler, + handle); if (NULL == handle->mq) return; for (vr = handle->request_head; NULL != vr; vr = vr->next) - GNUNET_MQ_send_copy (handle->mq, - vr->env); + GNUNET_MQ_send_copy(handle->mq, + vr->env); } @@ -303,18 +299,18 @@ reconnect (struct GNUNET_CREDENTIAL_Handle *handle) * @return handle to the CREDENTIAL service, or NULL on error */ struct GNUNET_CREDENTIAL_Handle * -GNUNET_CREDENTIAL_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_CREDENTIAL_connect(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_CREDENTIAL_Handle *handle; - handle = GNUNET_new (struct GNUNET_CREDENTIAL_Handle); + handle = GNUNET_new(struct GNUNET_CREDENTIAL_Handle); handle->cfg = cfg; - reconnect (handle); + reconnect(handle); if (NULL == handle->mq) - { - GNUNET_free (handle); - return NULL; - } + { + GNUNET_free(handle); + return NULL; + } return handle; } @@ -325,20 +321,20 @@ GNUNET_CREDENTIAL_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) * @param handle handle of the CREDENTIAL connection to stop */ void -GNUNET_CREDENTIAL_disconnect (struct GNUNET_CREDENTIAL_Handle *handle) +GNUNET_CREDENTIAL_disconnect(struct GNUNET_CREDENTIAL_Handle *handle) { if (NULL != handle->mq) - { - GNUNET_MQ_destroy (handle->mq); - handle->mq = NULL; - } + { + GNUNET_MQ_destroy(handle->mq); + handle->mq = NULL; + } if (NULL != handle->reconnect_task) - { - GNUNET_SCHEDULER_cancel (handle->reconnect_task); - handle->reconnect_task = NULL; - } - GNUNET_assert (NULL == handle->request_head); - GNUNET_free (handle); + { + GNUNET_SCHEDULER_cancel(handle->reconnect_task); + handle->reconnect_task = NULL; + } + GNUNET_assert(NULL == handle->request_head); + GNUNET_free(handle); } @@ -348,21 +344,21 @@ GNUNET_CREDENTIAL_disconnect (struct GNUNET_CREDENTIAL_Handle *handle) * @param lr the verify request to cancel */ void -GNUNET_CREDENTIAL_request_cancel (struct GNUNET_CREDENTIAL_Request *lr) +GNUNET_CREDENTIAL_request_cancel(struct GNUNET_CREDENTIAL_Request *lr) { struct GNUNET_CREDENTIAL_Handle *handle = lr->credential_handle; - GNUNET_CONTAINER_DLL_remove (handle->request_head, - handle->request_tail, - lr); - GNUNET_MQ_discard (lr->env); - GNUNET_free (lr); + GNUNET_CONTAINER_DLL_remove(handle->request_head, + handle->request_tail, + lr); + GNUNET_MQ_discard(lr->env); + GNUNET_free(lr); } /** * Performs attribute collection. - * Collects all credentials of subject to fulfill the + * Collects all credentials of subject to fulfill the * attribute, if possible * * @param handle handle to the Credential service @@ -374,12 +370,12 @@ GNUNET_CREDENTIAL_request_cancel (struct GNUNET_CREDENTIAL_Request *lr) * @return handle to the queued request */ struct GNUNET_CREDENTIAL_Request* -GNUNET_CREDENTIAL_collect (struct GNUNET_CREDENTIAL_Handle *handle, - const struct GNUNET_CRYPTO_EcdsaPublicKey *issuer_key, - const char *issuer_attribute, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *subject_key, - GNUNET_CREDENTIAL_CredentialResultProcessor proc, - void *proc_cls) +GNUNET_CREDENTIAL_collect(struct GNUNET_CREDENTIAL_Handle *handle, + const struct GNUNET_CRYPTO_EcdsaPublicKey *issuer_key, + const char *issuer_attribute, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *subject_key, + GNUNET_CREDENTIAL_CredentialResultProcessor proc, + void *proc_cls) { /* IPC to shorten credential names, return shorten_handle */ struct CollectMessage *c_msg; @@ -387,42 +383,42 @@ GNUNET_CREDENTIAL_collect (struct GNUNET_CREDENTIAL_Handle *handle, size_t nlen; if (NULL == issuer_attribute) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } //DEBUG LOG - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Trying to collect `%s' in CREDENTIAL\n", - issuer_attribute); - nlen = strlen (issuer_attribute) + 1; - if (nlen >= GNUNET_MAX_MESSAGE_SIZE - sizeof (*vr)) - { - GNUNET_break (0); - return NULL; - } - vr = GNUNET_new (struct GNUNET_CREDENTIAL_Request); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Trying to collect `%s' in CREDENTIAL\n", + issuer_attribute); + nlen = strlen(issuer_attribute) + 1; + if (nlen >= GNUNET_MAX_MESSAGE_SIZE - sizeof(*vr)) + { + GNUNET_break(0); + return NULL; + } + vr = GNUNET_new(struct GNUNET_CREDENTIAL_Request); vr->credential_handle = handle; vr->verify_proc = proc; vr->proc_cls = proc_cls; vr->r_id = handle->r_id_gen++; - vr->env = GNUNET_MQ_msg_extra (c_msg, - nlen, - GNUNET_MESSAGE_TYPE_CREDENTIAL_COLLECT); - c_msg->id = htonl (vr->r_id); + vr->env = GNUNET_MQ_msg_extra(c_msg, + nlen, + GNUNET_MESSAGE_TYPE_CREDENTIAL_COLLECT); + c_msg->id = htonl(vr->r_id); c_msg->subject_key = *subject_key; - c_msg->issuer_key = *issuer_key; + c_msg->issuer_key = *issuer_key; c_msg->issuer_attribute_len = htons(strlen(issuer_attribute)); - GNUNET_memcpy (&c_msg[1], - issuer_attribute, - strlen (issuer_attribute)); - GNUNET_CONTAINER_DLL_insert (handle->request_head, - handle->request_tail, - vr); + GNUNET_memcpy(&c_msg[1], + issuer_attribute, + strlen(issuer_attribute)); + GNUNET_CONTAINER_DLL_insert(handle->request_head, + handle->request_tail, + vr); if (NULL != handle->mq) - GNUNET_MQ_send_copy (handle->mq, - vr->env); + GNUNET_MQ_send_copy(handle->mq, + vr->env); return vr; } /** @@ -444,14 +440,14 @@ GNUNET_CREDENTIAL_collect (struct GNUNET_CREDENTIAL_Handle *handle, * @return handle to the queued request */ struct GNUNET_CREDENTIAL_Request* -GNUNET_CREDENTIAL_verify (struct GNUNET_CREDENTIAL_Handle *handle, - const struct GNUNET_CRYPTO_EcdsaPublicKey *issuer_key, - const char *issuer_attribute, - const struct GNUNET_CRYPTO_EcdsaPublicKey *subject_key, - uint32_t credential_count, - const struct GNUNET_CREDENTIAL_Credential *credentials, - GNUNET_CREDENTIAL_CredentialResultProcessor proc, - void *proc_cls) +GNUNET_CREDENTIAL_verify(struct GNUNET_CREDENTIAL_Handle *handle, + const struct GNUNET_CRYPTO_EcdsaPublicKey *issuer_key, + const char *issuer_attribute, + const struct GNUNET_CRYPTO_EcdsaPublicKey *subject_key, + uint32_t credential_count, + const struct GNUNET_CREDENTIAL_Credential *credentials, + GNUNET_CREDENTIAL_CredentialResultProcessor proc, + void *proc_cls) { /* IPC to shorten credential names, return shorten_handle */ struct VerifyMessage *v_msg; @@ -460,51 +456,51 @@ GNUNET_CREDENTIAL_verify (struct GNUNET_CREDENTIAL_Handle *handle, size_t clen; if (NULL == issuer_attribute || NULL == credentials) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } - clen = GNUNET_CREDENTIAL_credentials_get_size (credential_count, - credentials); + clen = GNUNET_CREDENTIAL_credentials_get_size(credential_count, + credentials); //DEBUG LOG - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Trying to verify `%s' in CREDENTIAL\n", - issuer_attribute); - nlen = strlen (issuer_attribute) + 1 + clen; - if (nlen >= GNUNET_MAX_MESSAGE_SIZE - sizeof (*vr)) - { - GNUNET_break (0); - return NULL; - } - vr = GNUNET_new (struct GNUNET_CREDENTIAL_Request); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Trying to verify `%s' in CREDENTIAL\n", + issuer_attribute); + nlen = strlen(issuer_attribute) + 1 + clen; + if (nlen >= GNUNET_MAX_MESSAGE_SIZE - sizeof(*vr)) + { + GNUNET_break(0); + return NULL; + } + vr = GNUNET_new(struct GNUNET_CREDENTIAL_Request); vr->credential_handle = handle; vr->verify_proc = proc; vr->proc_cls = proc_cls; vr->r_id = handle->r_id_gen++; - vr->env = GNUNET_MQ_msg_extra (v_msg, - nlen, - GNUNET_MESSAGE_TYPE_CREDENTIAL_VERIFY); - v_msg->id = htonl (vr->r_id); + vr->env = GNUNET_MQ_msg_extra(v_msg, + nlen, + GNUNET_MESSAGE_TYPE_CREDENTIAL_VERIFY); + v_msg->id = htonl(vr->r_id); v_msg->subject_key = *subject_key; v_msg->c_count = htonl(credential_count); - v_msg->issuer_key = *issuer_key; + v_msg->issuer_key = *issuer_key; v_msg->issuer_attribute_len = htons(strlen(issuer_attribute)); - GNUNET_memcpy (&v_msg[1], - issuer_attribute, - strlen (issuer_attribute)); - GNUNET_CREDENTIAL_credentials_serialize (credential_count, - credentials, - clen, - ((char*)&v_msg[1]) - + strlen (issuer_attribute) + 1); - GNUNET_CONTAINER_DLL_insert (handle->request_head, - handle->request_tail, - vr); + GNUNET_memcpy(&v_msg[1], + issuer_attribute, + strlen(issuer_attribute)); + GNUNET_CREDENTIAL_credentials_serialize(credential_count, + credentials, + clen, + ((char*)&v_msg[1]) + + strlen(issuer_attribute) + 1); + GNUNET_CONTAINER_DLL_insert(handle->request_head, + handle->request_tail, + vr); if (NULL != handle->mq) - GNUNET_MQ_send_copy (handle->mq, - vr->env); + GNUNET_MQ_send_copy(handle->mq, + vr->env); return vr; } diff --git a/src/credential/credential_misc.c b/src/credential/credential_misc.c index ae208f31f..be6d124a6 100644 --- a/src/credential/credential_misc.c +++ b/src/credential/credential_misc.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** @@ -34,7 +34,7 @@ #include char* -GNUNET_CREDENTIAL_credential_to_string (const struct GNUNET_CREDENTIAL_Credential *cred) +GNUNET_CREDENTIAL_credential_to_string(const struct GNUNET_CREDENTIAL_Credential *cred) { char *cred_str; char *subject_pkey; @@ -42,29 +42,30 @@ GNUNET_CREDENTIAL_credential_to_string (const struct GNUNET_CREDENTIAL_Credentia char *signature; - subject_pkey = GNUNET_CRYPTO_ecdsa_public_key_to_string (&cred->subject_key); - issuer_pkey = GNUNET_CRYPTO_ecdsa_public_key_to_string (&cred->issuer_key); - GNUNET_STRINGS_base64_encode ((char*)&cred->signature, - sizeof (struct GNUNET_CRYPTO_EcdsaSignature), - &signature); - GNUNET_asprintf (&cred_str, - "%s.%s -> %s | %s | %"SCNu64, - issuer_pkey, - cred->issuer_attribute, - subject_pkey, - signature, - cred->expiration.abs_value_us); - GNUNET_free (subject_pkey); - GNUNET_free (issuer_pkey); - GNUNET_free (signature); + subject_pkey = GNUNET_CRYPTO_ecdsa_public_key_to_string(&cred->subject_key); + issuer_pkey = GNUNET_CRYPTO_ecdsa_public_key_to_string(&cred->issuer_key); + GNUNET_STRINGS_base64_encode((char*)&cred->signature, + sizeof(struct GNUNET_CRYPTO_EcdsaSignature), + &signature); + GNUNET_asprintf(&cred_str, + "%s.%s -> %s | %s | %" SCNu64, + issuer_pkey, + cred->issuer_attribute, + subject_pkey, + signature, + cred->expiration.abs_value_us); + GNUNET_free(subject_pkey); + GNUNET_free(issuer_pkey); + GNUNET_free(signature); return cred_str; } struct GNUNET_CREDENTIAL_Credential* -GNUNET_CREDENTIAL_credential_from_string (const char* s) +GNUNET_CREDENTIAL_credential_from_string(const char* s) { struct GNUNET_CREDENTIAL_Credential *cred; - size_t enclen = (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)) * 8; + size_t enclen = (sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey)) * 8; + if (enclen % 5 > 0) enclen += 5 - enclen % 5; enclen /= 5; /* 260/5 = 52 */ @@ -76,36 +77,36 @@ GNUNET_CREDENTIAL_credential_from_string (const char* s) struct GNUNET_CRYPTO_EcdsaSignature *sig; struct GNUNET_TIME_Absolute etime_abs; - if (5 != SSCANF (s, - "%52s.%253s -> %52s | %s | %"SCNu64, - issuer_pkey, - name, - subject_pkey, - signature, - &etime_abs.abs_value_us)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to parse CRED record string `%s'\n"), - s); - return NULL; - } - cred = GNUNET_malloc (sizeof (struct GNUNET_CREDENTIAL_Credential) + strlen (name) + 1); - GNUNET_CRYPTO_ecdsa_public_key_from_string (subject_pkey, - strlen (subject_pkey), - &cred->subject_key); - GNUNET_CRYPTO_ecdsa_public_key_from_string (issuer_pkey, - strlen (issuer_pkey), - &cred->issuer_key); - GNUNET_assert (sizeof (struct GNUNET_CRYPTO_EcdsaSignature) == GNUNET_STRINGS_base64_decode (signature, - strlen (signature), - (char**)&sig)); + if (5 != SSCANF(s, + "%52s.%253s -> %52s | %s | %" SCNu64, + issuer_pkey, + name, + subject_pkey, + signature, + &etime_abs.abs_value_us)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse CRED record string `%s'\n"), + s); + return NULL; + } + cred = GNUNET_malloc(sizeof(struct GNUNET_CREDENTIAL_Credential) + strlen(name) + 1); + GNUNET_CRYPTO_ecdsa_public_key_from_string(subject_pkey, + strlen(subject_pkey), + &cred->subject_key); + GNUNET_CRYPTO_ecdsa_public_key_from_string(issuer_pkey, + strlen(issuer_pkey), + &cred->issuer_key); + GNUNET_assert(sizeof(struct GNUNET_CRYPTO_EcdsaSignature) == GNUNET_STRINGS_base64_decode(signature, + strlen(signature), + (char**)&sig)); cred->signature = *sig; cred->expiration = etime_abs; - GNUNET_free (sig); - GNUNET_memcpy (&cred[1], - name, - strlen (name)+1); - cred->issuer_attribute_len = strlen ((char*)&cred[1]); + GNUNET_free(sig); + GNUNET_memcpy(&cred[1], + name, + strlen(name) + 1); + cred->issuer_attribute_len = strlen((char*)&cred[1]); cred->issuer_attribute = (char*)&cred[1]; return cred; } @@ -119,50 +120,50 @@ GNUNET_CREDENTIAL_credential_from_string (const char* s) * @return handle to the queued request */ struct GNUNET_CREDENTIAL_Credential * -GNUNET_CREDENTIAL_credential_issue (const struct GNUNET_CRYPTO_EcdsaPrivateKey *issuer, - struct GNUNET_CRYPTO_EcdsaPublicKey *subject, - const char *attribute, - struct GNUNET_TIME_Absolute *expiration) +GNUNET_CREDENTIAL_credential_issue(const struct GNUNET_CRYPTO_EcdsaPrivateKey *issuer, + struct GNUNET_CRYPTO_EcdsaPublicKey *subject, + const char *attribute, + struct GNUNET_TIME_Absolute *expiration) { struct CredentialEntry *crd; struct GNUNET_CREDENTIAL_Credential *cred; size_t size; - size = sizeof (struct CredentialEntry) + strlen (attribute) + 1; - crd = GNUNET_malloc (size); - cred = GNUNET_malloc (sizeof (struct GNUNET_CREDENTIAL_Credential) + strlen (attribute) + 1); - crd->purpose.size = htonl (size - sizeof (struct GNUNET_CRYPTO_EcdsaSignature)); + size = sizeof(struct CredentialEntry) + strlen(attribute) + 1; + crd = GNUNET_malloc(size); + cred = GNUNET_malloc(sizeof(struct GNUNET_CREDENTIAL_Credential) + strlen(attribute) + 1); + crd->purpose.size = htonl(size - sizeof(struct GNUNET_CRYPTO_EcdsaSignature)); - crd->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CREDENTIAL); - GNUNET_CRYPTO_ecdsa_key_get_public (issuer, - &crd->issuer_key); + crd->purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_CREDENTIAL); + GNUNET_CRYPTO_ecdsa_key_get_public(issuer, + &crd->issuer_key); crd->subject_key = *subject; - crd->expiration = GNUNET_htonll (expiration->abs_value_us); - crd->issuer_attribute_len = htonl (strlen (attribute)+1); - GNUNET_memcpy ((char*)&crd[1], - attribute, - strlen (attribute)+1); + crd->expiration = GNUNET_htonll(expiration->abs_value_us); + crd->issuer_attribute_len = htonl(strlen(attribute) + 1); + GNUNET_memcpy((char*)&crd[1], + attribute, + strlen(attribute) + 1); if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_sign (issuer, - &crd->purpose, - &crd->signature)) - { - GNUNET_break (0); - GNUNET_free (crd); - GNUNET_free (cred); - return NULL; - } + GNUNET_CRYPTO_ecdsa_sign(issuer, + &crd->purpose, + &crd->signature)) + { + GNUNET_break(0); + GNUNET_free(crd); + GNUNET_free(cred); + return NULL; + } cred->signature = crd->signature; cred->expiration = *expiration; - GNUNET_CRYPTO_ecdsa_key_get_public (issuer, - &cred->issuer_key); + GNUNET_CRYPTO_ecdsa_key_get_public(issuer, + &cred->issuer_key); cred->subject_key = *subject; - GNUNET_memcpy (&cred[1], - attribute, - strlen (attribute)+1); + GNUNET_memcpy(&cred[1], + attribute, + strlen(attribute) + 1); cred->issuer_attribute = (char*)&cred[1]; - GNUNET_free (crd); + GNUNET_free(crd); return cred; } diff --git a/src/credential/credential_misc.h b/src/credential/credential_misc.h index b06ee98cf..0411f0af3 100644 --- a/src/credential/credential_misc.h +++ b/src/credential/credential_misc.h @@ -27,10 +27,10 @@ #include "gnunet_credential_service.h" char * -GNUNET_CREDENTIAL_credential_to_string ( - const struct GNUNET_CREDENTIAL_Credential *cred); +GNUNET_CREDENTIAL_credential_to_string( + const struct GNUNET_CREDENTIAL_Credential *cred); struct GNUNET_CREDENTIAL_Credential * -GNUNET_CREDENTIAL_credential_from_string (const char *str); +GNUNET_CREDENTIAL_credential_from_string(const char *str); #endif diff --git a/src/credential/credential_serialization.c b/src/credential/credential_serialization.c index 5ee3cfb07..eac310272 100644 --- a/src/credential/credential_serialization.c +++ b/src/credential/credential_serialization.c @@ -11,17 +11,17 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file credential/credential_serialization.c - * @brief API to serialize and deserialize delegation chains + * @brief API to serialize and deserialize delegation chains * and credentials * @author Martin Schanzenbach */ @@ -41,19 +41,19 @@ * @return the required size to serialize */ size_t -GNUNET_CREDENTIAL_delegation_set_get_size (unsigned int ds_count, - const struct GNUNET_CREDENTIAL_DelegationSet *dsr) +GNUNET_CREDENTIAL_delegation_set_get_size(unsigned int ds_count, + const struct GNUNET_CREDENTIAL_DelegationSet *dsr) { unsigned int i; size_t ret; - ret = sizeof (struct DelegationRecordData) * (ds_count); + ret = sizeof(struct DelegationRecordData) * (ds_count); - for (i=0; i= ret); - ret += dsr[i].subject_attribute_len; - } + for (i = 0; i < ds_count; i++) + { + GNUNET_assert((ret + dsr[i].subject_attribute_len) >= ret); + ret += dsr[i].subject_attribute_len; + } return ret; } @@ -67,35 +67,35 @@ GNUNET_CREDENTIAL_delegation_set_get_size (unsigned int ds_count, * @return the size of the data, -1 on failure */ ssize_t -GNUNET_CREDENTIAL_delegation_set_serialize (unsigned int d_count, - const struct GNUNET_CREDENTIAL_DelegationSet *dsr, - size_t dest_size, - char *dest) +GNUNET_CREDENTIAL_delegation_set_serialize(unsigned int d_count, + const struct GNUNET_CREDENTIAL_DelegationSet *dsr, + size_t dest_size, + char *dest) { struct DelegationRecordData rec; unsigned int i; size_t off; off = 0; - for (i=0;i dest_size) - return -1; - GNUNET_memcpy (&dest[off], - &rec, - sizeof (rec)); - off += sizeof (rec); - if (0 == dsr[i].subject_attribute_len) - continue; - if (off + dsr[i].subject_attribute_len > dest_size) - return -1; - GNUNET_memcpy (&dest[off], - dsr[i].subject_attribute, - dsr[i].subject_attribute_len); - off += dsr[i].subject_attribute_len; - } + for (i = 0; i < d_count; i++) + { + rec.subject_attribute_len = htonl((uint32_t)dsr[i].subject_attribute_len); + rec.subject_key = dsr[i].subject_key; + if (off + sizeof(rec) > dest_size) + return -1; + GNUNET_memcpy(&dest[off], + &rec, + sizeof(rec)); + off += sizeof(rec); + if (0 == dsr[i].subject_attribute_len) + continue; + if (off + dsr[i].subject_attribute_len > dest_size) + return -1; + GNUNET_memcpy(&dest[off], + dsr[i].subject_attribute, + dsr[i].subject_attribute_len); + off += dsr[i].subject_attribute_len; + } return off; } @@ -110,29 +110,29 @@ GNUNET_CREDENTIAL_delegation_set_serialize (unsigned int d_count, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CREDENTIAL_delegation_set_deserialize (size_t len, - const char *src, - unsigned int d_count, - struct GNUNET_CREDENTIAL_DelegationSet *dsr) +GNUNET_CREDENTIAL_delegation_set_deserialize(size_t len, + const char *src, + unsigned int d_count, + struct GNUNET_CREDENTIAL_DelegationSet *dsr) { struct DelegationRecordData rec; unsigned int i; size_t off; off = 0; - for (i=0;i len) - return GNUNET_SYSERR; - GNUNET_memcpy (&rec, &src[off], sizeof (rec)); - dsr[i].subject_key = rec.subject_key; - off += sizeof (rec); - dsr[i].subject_attribute_len = ntohl ((uint32_t) rec.subject_attribute_len); - if (off + dsr[i].subject_attribute_len > len) - return GNUNET_SYSERR; - dsr[i].subject_attribute = (char*)&src[off]; - off += dsr[i].subject_attribute_len; - } + for (i = 0; i < d_count; i++) + { + if (off + sizeof(rec) > len) + return GNUNET_SYSERR; + GNUNET_memcpy(&rec, &src[off], sizeof(rec)); + dsr[i].subject_key = rec.subject_key; + off += sizeof(rec); + dsr[i].subject_attribute_len = ntohl((uint32_t)rec.subject_attribute_len); + if (off + dsr[i].subject_attribute_len > len) + return GNUNET_SYSERR; + dsr[i].subject_attribute = (char*)&src[off]; + off += dsr[i].subject_attribute_len; + } return GNUNET_OK; } @@ -146,19 +146,19 @@ GNUNET_CREDENTIAL_delegation_set_deserialize (size_t len, * @return the required size to serialize */ size_t -GNUNET_CREDENTIAL_credentials_get_size (unsigned int c_count, - const struct GNUNET_CREDENTIAL_Credential *cd) +GNUNET_CREDENTIAL_credentials_get_size(unsigned int c_count, + const struct GNUNET_CREDENTIAL_Credential *cd) { unsigned int i; size_t ret; - ret = sizeof (struct CredentialEntry) * (c_count); + ret = sizeof(struct CredentialEntry) * (c_count); - for (i=0; i= ret); - ret += cd[i].issuer_attribute_len; - } + for (i = 0; i < c_count; i++) + { + GNUNET_assert((ret + cd[i].issuer_attribute_len) >= ret); + ret += cd[i].issuer_attribute_len; + } return ret; } /** @@ -171,38 +171,38 @@ GNUNET_CREDENTIAL_credentials_get_size (unsigned int c_count, * @return the size of the data, -1 on failure */ ssize_t -GNUNET_CREDENTIAL_credentials_serialize (unsigned int c_count, - const struct GNUNET_CREDENTIAL_Credential *cd, - size_t dest_size, - char *dest) +GNUNET_CREDENTIAL_credentials_serialize(unsigned int c_count, + const struct GNUNET_CREDENTIAL_Credential *cd, + size_t dest_size, + char *dest) { struct CredentialEntry c_rec; unsigned int i; size_t off; off = 0; - for (i=0;i dest_size) - return -1; - GNUNET_memcpy (&dest[off], - &c_rec, - sizeof (c_rec)); - off += sizeof (c_rec); - if (off + cd[i].issuer_attribute_len > dest_size) - return -1; - GNUNET_memcpy (&dest[off], - cd[i].issuer_attribute, - cd[i].issuer_attribute_len); - off += cd[i].issuer_attribute_len; - } + for (i = 0; i < c_count; i++) + { + c_rec.issuer_attribute_len = htonl((uint32_t)cd[i].issuer_attribute_len); + c_rec.issuer_key = cd[i].issuer_key; + c_rec.subject_key = cd[i].subject_key; + c_rec.signature = cd[i].signature; + c_rec.purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_CREDENTIAL); + c_rec.purpose.size = htonl((sizeof(struct CredentialEntry) + cd[i].issuer_attribute_len) - sizeof(struct GNUNET_CRYPTO_EcdsaSignature)); + c_rec.expiration = GNUNET_htonll(cd[i].expiration.abs_value_us); + if (off + sizeof(c_rec) > dest_size) + return -1; + GNUNET_memcpy(&dest[off], + &c_rec, + sizeof(c_rec)); + off += sizeof(c_rec); + if (off + cd[i].issuer_attribute_len > dest_size) + return -1; + GNUNET_memcpy(&dest[off], + cd[i].issuer_attribute, + cd[i].issuer_attribute_len); + off += cd[i].issuer_attribute_len; + } return off; } @@ -219,32 +219,32 @@ GNUNET_CREDENTIAL_credentials_serialize (unsigned int c_count, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CREDENTIAL_credentials_deserialize (size_t len, - const char *src, - unsigned int c_count, - struct GNUNET_CREDENTIAL_Credential *cd) +GNUNET_CREDENTIAL_credentials_deserialize(size_t len, + const char *src, + unsigned int c_count, + struct GNUNET_CREDENTIAL_Credential *cd) { struct CredentialEntry c_rec; unsigned int i; size_t off; off = 0; - for (i=0;i len) - return GNUNET_SYSERR; - GNUNET_memcpy (&c_rec, &src[off], sizeof (c_rec)); - cd[i].issuer_attribute_len = ntohl ((uint32_t) c_rec.issuer_attribute_len); - cd[i].issuer_key = c_rec.issuer_key; - cd[i].subject_key = c_rec.subject_key; - cd[i].signature = c_rec.signature; - cd[i].expiration.abs_value_us = GNUNET_ntohll(c_rec.expiration); - off += sizeof (c_rec); - if (off + cd[i].issuer_attribute_len > len) - return GNUNET_SYSERR; - cd[i].issuer_attribute = &src[off]; - off += cd[i].issuer_attribute_len; - } + for (i = 0; i < c_count; i++) + { + if (off + sizeof(c_rec) > len) + return GNUNET_SYSERR; + GNUNET_memcpy(&c_rec, &src[off], sizeof(c_rec)); + cd[i].issuer_attribute_len = ntohl((uint32_t)c_rec.issuer_attribute_len); + cd[i].issuer_key = c_rec.issuer_key; + cd[i].subject_key = c_rec.subject_key; + cd[i].signature = c_rec.signature; + cd[i].expiration.abs_value_us = GNUNET_ntohll(c_rec.expiration); + off += sizeof(c_rec); + if (off + cd[i].issuer_attribute_len > len) + return GNUNET_SYSERR; + cd[i].issuer_attribute = &src[off]; + off += cd[i].issuer_attribute_len; + } return GNUNET_OK; } @@ -261,24 +261,24 @@ GNUNET_CREDENTIAL_credentials_deserialize (size_t len, * @return the required size to serialize */ size_t -GNUNET_CREDENTIAL_delegation_chain_get_size (unsigned int d_count, - const struct GNUNET_CREDENTIAL_Delegation *dd, - unsigned int c_count, - const struct GNUNET_CREDENTIAL_Credential *cd) +GNUNET_CREDENTIAL_delegation_chain_get_size(unsigned int d_count, + const struct GNUNET_CREDENTIAL_Delegation *dd, + unsigned int c_count, + const struct GNUNET_CREDENTIAL_Credential *cd) { unsigned int i; size_t ret; - ret = sizeof (struct ChainEntry) * (d_count); + ret = sizeof(struct ChainEntry) * (d_count); - for (i=0; i= ret); - ret += dd[i].issuer_attribute_len + dd[i].subject_attribute_len; - } - return ret+GNUNET_CREDENTIAL_credentials_get_size(c_count, cd); + for (i = 0; i < d_count; i++) + { + GNUNET_assert((ret + + dd[i].issuer_attribute_len + + dd[i].subject_attribute_len) >= ret); + ret += dd[i].issuer_attribute_len + dd[i].subject_attribute_len; + } + return ret + GNUNET_CREDENTIAL_credentials_get_size(c_count, cd); } /** @@ -293,49 +293,49 @@ GNUNET_CREDENTIAL_delegation_chain_get_size (unsigned int d_count, * @return the size of the data, -1 on failure */ ssize_t -GNUNET_CREDENTIAL_delegation_chain_serialize (unsigned int d_count, - const struct GNUNET_CREDENTIAL_Delegation *dd, - unsigned int c_count, - const struct GNUNET_CREDENTIAL_Credential *cd, - size_t dest_size, - char *dest) +GNUNET_CREDENTIAL_delegation_chain_serialize(unsigned int d_count, + const struct GNUNET_CREDENTIAL_Delegation *dd, + unsigned int c_count, + const struct GNUNET_CREDENTIAL_Credential *cd, + size_t dest_size, + char *dest) { struct ChainEntry rec; unsigned int i; size_t off; off = 0; - for (i=0;i dest_size) - return -1; - GNUNET_memcpy (&dest[off], - &rec, - sizeof (rec)); - off += sizeof (rec); - if (off + dd[i].issuer_attribute_len > dest_size) - return -1; - GNUNET_memcpy (&dest[off], - dd[i].issuer_attribute, - dd[i].issuer_attribute_len); - off += dd[i].issuer_attribute_len; - if (0 == dd[i].subject_attribute_len) - continue; - if (off + dd[i].subject_attribute_len > dest_size) - return -1; - GNUNET_memcpy (&dest[off], - dd[i].subject_attribute, - dd[i].subject_attribute_len); - off += dd[i].subject_attribute_len; - } - return off+GNUNET_CREDENTIAL_credentials_serialize (c_count, - cd, - dest_size-off, - &dest[off]); + for (i = 0; i < d_count; i++) + { + rec.issuer_attribute_len = htonl((uint32_t)dd[i].issuer_attribute_len); + rec.subject_attribute_len = htonl((uint32_t)dd[i].subject_attribute_len); + rec.issuer_key = dd[i].issuer_key; + rec.subject_key = dd[i].subject_key; + if (off + sizeof(rec) > dest_size) + return -1; + GNUNET_memcpy(&dest[off], + &rec, + sizeof(rec)); + off += sizeof(rec); + if (off + dd[i].issuer_attribute_len > dest_size) + return -1; + GNUNET_memcpy(&dest[off], + dd[i].issuer_attribute, + dd[i].issuer_attribute_len); + off += dd[i].issuer_attribute_len; + if (0 == dd[i].subject_attribute_len) + continue; + if (off + dd[i].subject_attribute_len > dest_size) + return -1; + GNUNET_memcpy(&dest[off], + dd[i].subject_attribute, + dd[i].subject_attribute_len); + off += dd[i].subject_attribute_len; + } + return off + GNUNET_CREDENTIAL_credentials_serialize(c_count, + cd, + dest_size - off, + &dest[off]); } @@ -351,107 +351,107 @@ GNUNET_CREDENTIAL_delegation_chain_serialize (unsigned int d_count, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CREDENTIAL_delegation_chain_deserialize (size_t len, - const char *src, - unsigned int d_count, - struct GNUNET_CREDENTIAL_Delegation *dd, - unsigned int c_count, - struct GNUNET_CREDENTIAL_Credential *cd) +GNUNET_CREDENTIAL_delegation_chain_deserialize(size_t len, + const char *src, + unsigned int d_count, + struct GNUNET_CREDENTIAL_Delegation *dd, + unsigned int c_count, + struct GNUNET_CREDENTIAL_Credential *cd) { struct ChainEntry rec; unsigned int i; size_t off; off = 0; - for (i=0;i len) - return GNUNET_SYSERR; - GNUNET_memcpy (&rec, &src[off], sizeof (rec)); - dd[i].issuer_attribute_len = ntohl ((uint32_t) rec.issuer_attribute_len); - dd[i].issuer_key = rec.issuer_key; - dd[i].subject_key = rec.subject_key; - off += sizeof (rec); - if (off + dd[i].issuer_attribute_len > len) - return GNUNET_SYSERR; - dd[i].issuer_attribute = &src[off]; - off += dd[i].issuer_attribute_len; - dd[i].subject_attribute_len = ntohl ((uint32_t) rec.subject_attribute_len); - if (off + dd[i].subject_attribute_len > len) - return GNUNET_SYSERR; - dd[i].subject_attribute = &src[off]; - off += dd[i].subject_attribute_len; - } - return GNUNET_CREDENTIAL_credentials_deserialize (len-off, - &src[off], - c_count, - cd); + for (i = 0; i < d_count; i++) + { + if (off + sizeof(rec) > len) + return GNUNET_SYSERR; + GNUNET_memcpy(&rec, &src[off], sizeof(rec)); + dd[i].issuer_attribute_len = ntohl((uint32_t)rec.issuer_attribute_len); + dd[i].issuer_key = rec.issuer_key; + dd[i].subject_key = rec.subject_key; + off += sizeof(rec); + if (off + dd[i].issuer_attribute_len > len) + return GNUNET_SYSERR; + dd[i].issuer_attribute = &src[off]; + off += dd[i].issuer_attribute_len; + dd[i].subject_attribute_len = ntohl((uint32_t)rec.subject_attribute_len); + if (off + dd[i].subject_attribute_len > len) + return GNUNET_SYSERR; + dd[i].subject_attribute = &src[off]; + off += dd[i].subject_attribute_len; + } + return GNUNET_CREDENTIAL_credentials_deserialize(len - off, + &src[off], + c_count, + cd); } int -GNUNET_CREDENTIAL_credential_serialize (struct GNUNET_CREDENTIAL_Credential *cred, - char **data) +GNUNET_CREDENTIAL_credential_serialize(struct GNUNET_CREDENTIAL_Credential *cred, + char **data) { size_t size; struct CredentialEntry *cdata; - size = sizeof (struct CredentialEntry) + strlen (cred->issuer_attribute) + 1; - *data = GNUNET_malloc (size); + size = sizeof(struct CredentialEntry) + strlen(cred->issuer_attribute) + 1; + *data = GNUNET_malloc(size); cdata = (struct CredentialEntry*)*data; cdata->subject_key = cred->subject_key; cdata->issuer_key = cred->issuer_key; - cdata->expiration = GNUNET_htonll (cred->expiration.abs_value_us); + cdata->expiration = GNUNET_htonll(cred->expiration.abs_value_us); cdata->signature = cred->signature; - cdata->issuer_attribute_len = htonl (strlen (cred->issuer_attribute) + 1); - cdata->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_CREDENTIAL); - cdata->purpose.size = htonl (size - sizeof (struct GNUNET_CRYPTO_EcdsaSignature)); - GNUNET_memcpy (&cdata[1], - cred->issuer_attribute, - strlen (cred->issuer_attribute)); - - if(GNUNET_OK != GNUNET_CRYPTO_ecdsa_verify(GNUNET_SIGNATURE_PURPOSE_CREDENTIAL, - &cdata->purpose, - &cdata->signature, - &cdata->issuer_key)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Invalid credential\n"); - //return NULL; - } + cdata->issuer_attribute_len = htonl(strlen(cred->issuer_attribute) + 1); + cdata->purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_CREDENTIAL); + cdata->purpose.size = htonl(size - sizeof(struct GNUNET_CRYPTO_EcdsaSignature)); + GNUNET_memcpy(&cdata[1], + cred->issuer_attribute, + strlen(cred->issuer_attribute)); + + if (GNUNET_OK != GNUNET_CRYPTO_ecdsa_verify(GNUNET_SIGNATURE_PURPOSE_CREDENTIAL, + &cdata->purpose, + &cdata->signature, + &cdata->issuer_key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Invalid credential\n"); + //return NULL; + } return size; } struct GNUNET_CREDENTIAL_Credential* -GNUNET_CREDENTIAL_credential_deserialize (const char* data, - size_t data_size) +GNUNET_CREDENTIAL_credential_deserialize(const char* data, + size_t data_size) { struct GNUNET_CREDENTIAL_Credential *cred; struct CredentialEntry *cdata; char *issuer_attribute; - if (data_size < sizeof (struct CredentialEntry)) + if (data_size < sizeof(struct CredentialEntry)) return NULL; cdata = (struct CredentialEntry*)data; - if(GNUNET_OK != GNUNET_CRYPTO_ecdsa_verify(GNUNET_SIGNATURE_PURPOSE_CREDENTIAL, - &cdata->purpose, - &cdata->signature, - &cdata->issuer_key)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Invalid credential\n"); - //return NULL; - } + if (GNUNET_OK != GNUNET_CRYPTO_ecdsa_verify(GNUNET_SIGNATURE_PURPOSE_CREDENTIAL, + &cdata->purpose, + &cdata->signature, + &cdata->issuer_key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Invalid credential\n"); + //return NULL; + } issuer_attribute = (char*)&cdata[1]; - cred = GNUNET_malloc (sizeof (struct GNUNET_CREDENTIAL_Credential) + ntohl(cdata->issuer_attribute_len)); + cred = GNUNET_malloc(sizeof(struct GNUNET_CREDENTIAL_Credential) + ntohl(cdata->issuer_attribute_len)); cred->issuer_key = cdata->issuer_key; cred->subject_key = cdata->subject_key; - GNUNET_memcpy (&cred[1], - issuer_attribute, - ntohl (cdata->issuer_attribute_len)); + GNUNET_memcpy(&cred[1], + issuer_attribute, + ntohl(cdata->issuer_attribute_len)); cred->signature = cdata->signature; cred->issuer_attribute = (char*)&cred[1]; - cred->expiration.abs_value_us = GNUNET_ntohll (cdata->expiration); + cred->expiration.abs_value_us = GNUNET_ntohll(cdata->expiration); return cred; } diff --git a/src/credential/credential_serialization.h b/src/credential/credential_serialization.h index 90ec0f56f..426034164 100644 --- a/src/credential/credential_serialization.h +++ b/src/credential/credential_serialization.h @@ -11,17 +11,17 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file credential/credential_serialization.h - * @brief API to serialize and deserialize delegation chains + * @brief API to serialize and deserialize delegation chains * and credentials * @author Martin Schanzenbach */ @@ -42,8 +42,8 @@ * @return the required size to serialize */ size_t -GNUNET_CREDENTIAL_delegation_set_get_size (unsigned int ds_count, - const struct GNUNET_CREDENTIAL_DelegationSet *dsr); +GNUNET_CREDENTIAL_delegation_set_get_size(unsigned int ds_count, + const struct GNUNET_CREDENTIAL_DelegationSet *dsr); /** * Serizalize the given delegation record entries @@ -55,10 +55,10 @@ GNUNET_CREDENTIAL_delegation_set_get_size (unsigned int ds_count, * @return the size of the data, -1 on failure */ ssize_t -GNUNET_CREDENTIAL_delegation_set_serialize (unsigned int d_count, - const struct GNUNET_CREDENTIAL_DelegationSet *dsr, - size_t dest_size, - char *dest); +GNUNET_CREDENTIAL_delegation_set_serialize(unsigned int d_count, + const struct GNUNET_CREDENTIAL_DelegationSet *dsr, + size_t dest_size, + char *dest); /** @@ -71,89 +71,89 @@ GNUNET_CREDENTIAL_delegation_set_serialize (unsigned int d_count, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CREDENTIAL_delegation_set_deserialize (size_t len, - const char *src, - unsigned int d_count, - struct GNUNET_CREDENTIAL_DelegationSet *dsr); - - /** - * Calculate how many bytes we will need to serialize - * the given delegation chain and credential - * - * @param d_count number of delegation chain entries - * @param dd array of #GNUNET_CREDENTIAL_Delegation - * @param c_count number of credential entries - * @param cd a #GNUNET_CREDENTIAL_Credential - * @return the required size to serialize - */ - size_t - GNUNET_CREDENTIAL_delegation_chain_get_size (unsigned int d_count, - const struct GNUNET_CREDENTIAL_Delegation *dd, - unsigned int c_count, - const struct GNUNET_CREDENTIAL_Credential *cd); - - /** - * Serizalize the given delegation chain entries and credential - * - * @param d_count number of delegation chain entries - * @param dd array of #GNUNET_CREDENTIAL_Delegation - * @param c_count number of credential entries - * @param cd a #GNUNET_CREDENTIAL_Credential - * @param dest_size size of the destination - * @param dest where to store the result - * @return the size of the data, -1 on failure - */ - ssize_t - GNUNET_CREDENTIAL_delegation_chain_serialize (unsigned int d_count, - const struct GNUNET_CREDENTIAL_Delegation *dd, - unsigned int c_count, - const struct GNUNET_CREDENTIAL_Credential *cd, - size_t dest_size, - char *dest); - - - /** - * Deserialize the given destination - * - * @param len size of the serialized delegation chain and cred - * @param src the serialized data - * @param d_count the number of delegation chain entries - * @param dd where to put the delegation chain entries - * @param c_count number of credential entries - * @param cd where to put the credential data - * @return #GNUNET_OK on success, #GNUNET_SYSERR on error - */ - int - GNUNET_CREDENTIAL_delegation_chain_deserialize (size_t len, - const char *src, - unsigned int d_count, - struct GNUNET_CREDENTIAL_Delegation *dd, - unsigned int c_count, - struct GNUNET_CREDENTIAL_Credential *cd); - size_t - GNUNET_CREDENTIAL_credentials_get_size (unsigned int c_count, - const struct GNUNET_CREDENTIAL_Credential *cd); +GNUNET_CREDENTIAL_delegation_set_deserialize(size_t len, + const char *src, + unsigned int d_count, + struct GNUNET_CREDENTIAL_DelegationSet *dsr); + +/** + * Calculate how many bytes we will need to serialize + * the given delegation chain and credential + * + * @param d_count number of delegation chain entries + * @param dd array of #GNUNET_CREDENTIAL_Delegation + * @param c_count number of credential entries + * @param cd a #GNUNET_CREDENTIAL_Credential + * @return the required size to serialize + */ +size_t +GNUNET_CREDENTIAL_delegation_chain_get_size(unsigned int d_count, + const struct GNUNET_CREDENTIAL_Delegation *dd, + unsigned int c_count, + const struct GNUNET_CREDENTIAL_Credential *cd); + +/** + * Serizalize the given delegation chain entries and credential + * + * @param d_count number of delegation chain entries + * @param dd array of #GNUNET_CREDENTIAL_Delegation + * @param c_count number of credential entries + * @param cd a #GNUNET_CREDENTIAL_Credential + * @param dest_size size of the destination + * @param dest where to store the result + * @return the size of the data, -1 on failure + */ +ssize_t +GNUNET_CREDENTIAL_delegation_chain_serialize(unsigned int d_count, + const struct GNUNET_CREDENTIAL_Delegation *dd, + unsigned int c_count, + const struct GNUNET_CREDENTIAL_Credential *cd, + size_t dest_size, + char *dest); + + +/** + * Deserialize the given destination + * + * @param len size of the serialized delegation chain and cred + * @param src the serialized data + * @param d_count the number of delegation chain entries + * @param dd where to put the delegation chain entries + * @param c_count number of credential entries + * @param cd where to put the credential data + * @return #GNUNET_OK on success, #GNUNET_SYSERR on error + */ +int +GNUNET_CREDENTIAL_delegation_chain_deserialize(size_t len, + const char *src, + unsigned int d_count, + struct GNUNET_CREDENTIAL_Delegation *dd, + unsigned int c_count, + struct GNUNET_CREDENTIAL_Credential *cd); +size_t +GNUNET_CREDENTIAL_credentials_get_size(unsigned int c_count, + const struct GNUNET_CREDENTIAL_Credential *cd); ssize_t -GNUNET_CREDENTIAL_credentials_serialize (unsigned int c_count, - const struct GNUNET_CREDENTIAL_Credential *cd, - size_t dest_size, - char *dest); +GNUNET_CREDENTIAL_credentials_serialize(unsigned int c_count, + const struct GNUNET_CREDENTIAL_Credential *cd, + size_t dest_size, + char *dest); int -GNUNET_CREDENTIAL_credentials_deserialize (size_t len, - const char *src, - unsigned int c_count, - struct GNUNET_CREDENTIAL_Credential *cd); +GNUNET_CREDENTIAL_credentials_deserialize(size_t len, + const char *src, + unsigned int c_count, + struct GNUNET_CREDENTIAL_Credential *cd); int -GNUNET_CREDENTIAL_credential_serialize (struct GNUNET_CREDENTIAL_Credential *cred, - char **data); +GNUNET_CREDENTIAL_credential_serialize(struct GNUNET_CREDENTIAL_Credential *cred, + char **data); struct GNUNET_CREDENTIAL_Credential* -GNUNET_CREDENTIAL_credential_deserialize (const char* data, - size_t data_size); +GNUNET_CREDENTIAL_credential_deserialize(const char* data, + size_t data_size); #endif /* end of credential_serialization.h */ diff --git a/src/credential/gnunet-credential.c b/src/credential/gnunet-credential.c index 7873e4230..415525e9a 100644 --- a/src/credential/gnunet-credential.c +++ b/src/credential/gnunet-credential.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnunet-credential.c * @brief command line tool to access command line Credential service @@ -126,23 +126,23 @@ static int collect; * @param cls unused */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { if (NULL != verify_request) - { - GNUNET_CREDENTIAL_request_cancel (verify_request); - verify_request = NULL; - } + { + GNUNET_CREDENTIAL_request_cancel(verify_request); + verify_request = NULL; + } if (NULL != credential) - { - GNUNET_CREDENTIAL_disconnect (credential); - credential = NULL; - } + { + GNUNET_CREDENTIAL_disconnect(credential); + credential = NULL; + } if (NULL != tt) - { - GNUNET_SCHEDULER_cancel (tt); - tt = NULL; - } + { + GNUNET_SCHEDULER_cancel(tt); + tt = NULL; + } } @@ -152,14 +152,14 @@ do_shutdown (void *cls) * @param cls unused */ static void -do_timeout (void *cls) +do_timeout(void *cls) { tt = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } static void -handle_collect_result (void *cls, +handle_collect_result(void *cls, unsigned int d_count, struct GNUNET_CREDENTIAL_Delegation *dc, unsigned int c_count, @@ -170,27 +170,27 @@ handle_collect_result (void *cls, verify_request = NULL; if (NULL != cred) - { - for (i=0;iissuer_attribute); + tok = strtok(NULL, ","); + GNUNET_free(cred); + } + + verify_request = GNUNET_CREDENTIAL_verify(credential, + &issuer_pkey, + issuer_attr, //TODO argument + &subject_pkey, + count, + credentials, + &handle_verify_result, + NULL); + for (i = 0; i < count; i++) + { + GNUNET_free((char*)credentials[i].issuer_attribute); + } + GNUNET_free(tmp); } - - //Subject credentials are comma separated - char *tmp = GNUNET_strdup (subject_credential); - char *tok = strtok (tmp, ","); - if (NULL == tok) + else if (GNUNET_YES == create_cred) { - fprintf (stderr, - "Invalid subject credentials\n"); - GNUNET_free (tmp); - GNUNET_SCHEDULER_shutdown (); + if (NULL == ego_name) + { + fprintf(stderr, + _("Issuer ego required\n")); + GNUNET_SCHEDULER_shutdown(); + return; + } + el = GNUNET_IDENTITY_ego_lookup(cfg, + ego_name, + &identity_cb, + (void *)cfg); return; } - int count = 1; - int i; - while (NULL != (tok = strtok(NULL, ","))) - count++; - struct GNUNET_CREDENTIAL_Credential credentials[count]; - struct GNUNET_CREDENTIAL_Credential *cred; - GNUNET_free (tmp); - tmp = GNUNET_strdup (subject_credential); - tok = strtok (tmp, ","); - for (i=0;iissuer_attribute); - tok = strtok(NULL, ","); - GNUNET_free (cred); - } - - verify_request = GNUNET_CREDENTIAL_verify(credential, - &issuer_pkey, - issuer_attr, //TODO argument - &subject_pkey, - count, - credentials, - &handle_verify_result, - NULL); - for (i=0;i. SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file credential/gnunet-service-credential.c * @brief GNUnet Credential Service (main service) @@ -46,8 +46,7 @@ struct VerifyRequestHandle; struct DelegationSetQueueEntry; -struct DelegationChainEntry -{ +struct DelegationChainEntry { /** * DLL */ @@ -82,8 +81,7 @@ struct DelegationChainEntry /** * DLL for record */ -struct CredentialRecordEntry -{ +struct CredentialRecordEntry { /** * DLL */ @@ -109,8 +107,7 @@ struct CredentialRecordEntry * DLL used for delegations * Used for OR delegations */ -struct DelegationQueueEntry -{ +struct DelegationQueueEntry { /** * DLL */ @@ -146,8 +143,7 @@ struct DelegationQueueEntry * DLL for delegation sets * Used for AND delegation set */ -struct DelegationSetQueueEntry -{ +struct DelegationSetQueueEntry { /** * DLL */ @@ -223,9 +219,7 @@ struct DelegationSetQueueEntry /** * Handle to a lookup operation from api */ -struct VerifyRequestHandle -{ - +struct VerifyRequestHandle { /** * We keep these in a DLL. */ @@ -350,7 +344,7 @@ static struct GNUNET_GNS_Handle *gns; static struct GNUNET_NAMESTORE_Handle *namestore; static void -cleanup_delegation_set (struct DelegationSetQueueEntry *ds_entry) +cleanup_delegation_set(struct DelegationSetQueueEntry *ds_entry) { struct DelegationQueueEntry *dq_entry; struct DelegationSetQueueEntry *child; @@ -359,88 +353,99 @@ cleanup_delegation_set (struct DelegationSetQueueEntry *ds_entry) return; for (dq_entry = ds_entry->queue_entries_head; NULL != dq_entry; - dq_entry = ds_entry->queue_entries_head) { - GNUNET_CONTAINER_DLL_remove (ds_entry->queue_entries_head, - ds_entry->queue_entries_tail, - dq_entry); - for (child = dq_entry->set_entries_head; NULL != child; - child = dq_entry->set_entries_head) { - GNUNET_CONTAINER_DLL_remove (dq_entry->set_entries_head, - dq_entry->set_entries_tail, - child); - cleanup_delegation_set (child); + dq_entry = ds_entry->queue_entries_head) + { + GNUNET_CONTAINER_DLL_remove(ds_entry->queue_entries_head, + ds_entry->queue_entries_tail, + dq_entry); + for (child = dq_entry->set_entries_head; NULL != child; + child = dq_entry->set_entries_head) + { + GNUNET_CONTAINER_DLL_remove(dq_entry->set_entries_head, + dq_entry->set_entries_tail, + child); + cleanup_delegation_set(child); + } + GNUNET_free(dq_entry); + } + GNUNET_free_non_null(ds_entry->issuer_key); + GNUNET_free_non_null(ds_entry->lookup_attribute); + GNUNET_free_non_null(ds_entry->issuer_attribute); + GNUNET_free_non_null(ds_entry->unresolved_attribute_delegation); + GNUNET_free_non_null(ds_entry->attr_trailer); + if (NULL != ds_entry->lookup_request) + { + GNUNET_GNS_lookup_cancel(ds_entry->lookup_request); + ds_entry->lookup_request = NULL; } - GNUNET_free (dq_entry); - } - GNUNET_free_non_null (ds_entry->issuer_key); - GNUNET_free_non_null (ds_entry->lookup_attribute); - GNUNET_free_non_null (ds_entry->issuer_attribute); - GNUNET_free_non_null (ds_entry->unresolved_attribute_delegation); - GNUNET_free_non_null (ds_entry->attr_trailer); - if (NULL != ds_entry->lookup_request) { - GNUNET_GNS_lookup_cancel (ds_entry->lookup_request); - ds_entry->lookup_request = NULL; - } - if (NULL != ds_entry->delegation_chain_entry) { - GNUNET_free_non_null (ds_entry->delegation_chain_entry->subject_attribute); - GNUNET_free_non_null (ds_entry->delegation_chain_entry->issuer_attribute); - GNUNET_free (ds_entry->delegation_chain_entry); - } - GNUNET_free (ds_entry); + if (NULL != ds_entry->delegation_chain_entry) + { + GNUNET_free_non_null(ds_entry->delegation_chain_entry->subject_attribute); + GNUNET_free_non_null(ds_entry->delegation_chain_entry->issuer_attribute); + GNUNET_free(ds_entry->delegation_chain_entry); + } + GNUNET_free(ds_entry); } static void -cleanup_handle (struct VerifyRequestHandle *vrh) +cleanup_handle(struct VerifyRequestHandle *vrh) { struct CredentialRecordEntry *cr_entry; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up...\n"); - if (NULL != vrh->lookup_request) { - GNUNET_GNS_lookup_cancel (vrh->lookup_request); - vrh->lookup_request = NULL; - } - cleanup_delegation_set (vrh->root_set); - GNUNET_free_non_null (vrh->issuer_attribute); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Cleaning up...\n"); + if (NULL != vrh->lookup_request) + { + GNUNET_GNS_lookup_cancel(vrh->lookup_request); + vrh->lookup_request = NULL; + } + cleanup_delegation_set(vrh->root_set); + GNUNET_free_non_null(vrh->issuer_attribute); for (cr_entry = vrh->cred_chain_head; NULL != vrh->cred_chain_head; - cr_entry = vrh->cred_chain_head) { - GNUNET_CONTAINER_DLL_remove (vrh->cred_chain_head, - vrh->cred_chain_tail, - cr_entry); - GNUNET_free_non_null (cr_entry->credential); - GNUNET_free (cr_entry); - } - GNUNET_free (vrh); + cr_entry = vrh->cred_chain_head) + { + GNUNET_CONTAINER_DLL_remove(vrh->cred_chain_head, + vrh->cred_chain_tail, + cr_entry); + GNUNET_free_non_null(cr_entry->credential); + GNUNET_free(cr_entry); + } + GNUNET_free(vrh); } static void -shutdown_task (void *cls) +shutdown_task(void *cls) { struct VerifyRequestHandle *vrh; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Shutting down!\n"); - - while (NULL != (vrh = vrh_head)) { - // CREDENTIAL_resolver_lookup_cancel (clh->lookup); - GNUNET_CONTAINER_DLL_remove (vrh_head, vrh_tail, vrh); - cleanup_handle (vrh); - } - - if (NULL != gns) { - GNUNET_GNS_disconnect (gns); - gns = NULL; - } - if (NULL != namestore) { - GNUNET_NAMESTORE_disconnect (namestore); - namestore = NULL; - } - if (NULL != statistics) { - GNUNET_STATISTICS_destroy (statistics, GNUNET_NO); - statistics = NULL; - } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Shutting down!\n"); + + while (NULL != (vrh = vrh_head)) + { + // CREDENTIAL_resolver_lookup_cancel (clh->lookup); + GNUNET_CONTAINER_DLL_remove(vrh_head, vrh_tail, vrh); + cleanup_handle(vrh); + } + + if (NULL != gns) + { + GNUNET_GNS_disconnect(gns); + gns = NULL; + } + if (NULL != namestore) + { + GNUNET_NAMESTORE_disconnect(namestore); + namestore = NULL; + } + if (NULL != statistics) + { + GNUNET_STATISTICS_destroy(statistics, GNUNET_NO); + statistics = NULL; + } } static void -send_lookup_response (struct VerifyRequestHandle *vrh) +send_lookup_response(struct VerifyRequestHandle *vrh) { struct GNUNET_MQ_Envelope *env; struct DelegationChainResultMessage *rmsg; @@ -451,99 +456,103 @@ send_lookup_response (struct VerifyRequestHandle *vrh) struct CredentialRecordEntry *tmp; size_t size; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending response\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending response\n"); dce = vrh->delegation_chain_head; - for (uint32_t i = 0; i < vrh->delegation_chain_size; i++) { - dd[i].issuer_key = dce->issuer_key; - dd[i].subject_key = dce->subject_key; - dd[i].issuer_attribute = dce->issuer_attribute; - dd[i].issuer_attribute_len = strlen (dce->issuer_attribute) + 1; - dd[i].subject_attribute_len = 0; - dd[i].subject_attribute = NULL; - if (NULL != dce->subject_attribute) { - dd[i].subject_attribute = dce->subject_attribute; - dd[i].subject_attribute_len = strlen (dce->subject_attribute) + 1; + for (uint32_t i = 0; i < vrh->delegation_chain_size; i++) + { + dd[i].issuer_key = dce->issuer_key; + dd[i].subject_key = dce->subject_key; + dd[i].issuer_attribute = dce->issuer_attribute; + dd[i].issuer_attribute_len = strlen(dce->issuer_attribute) + 1; + dd[i].subject_attribute_len = 0; + dd[i].subject_attribute = NULL; + if (NULL != dce->subject_attribute) + { + dd[i].subject_attribute = dce->subject_attribute; + dd[i].subject_attribute_len = strlen(dce->subject_attribute) + 1; + } + dce = dce->next; } - dce = dce->next; - } /** * Remove all credentials not needed */ - for (cd = vrh->cred_chain_head; NULL != cd;) { - if (cd->refcount > 0) { + for (cd = vrh->cred_chain_head; NULL != cd;) + { + if (cd->refcount > 0) + { + cd = cd->next; + continue; + } + tmp = cd; cd = cd->next; - continue; + GNUNET_CONTAINER_DLL_remove(vrh->cred_chain_head, + vrh->cred_chain_tail, + tmp); + GNUNET_free(tmp->credential); + GNUNET_free(tmp); + vrh->cred_chain_size--; } - tmp = cd; - cd = cd->next; - GNUNET_CONTAINER_DLL_remove (vrh->cred_chain_head, - vrh->cred_chain_tail, - tmp); - GNUNET_free (tmp->credential); - GNUNET_free (tmp); - vrh->cred_chain_size--; - } /** * Get serialized record data * Append at the end of rmsg */ cd = vrh->cred_chain_head; - for (uint32_t i = 0; i < vrh->cred_chain_size; i++) { - cred[i].issuer_key = cd->credential->issuer_key; - cred[i].subject_key = cd->credential->subject_key; - cred[i].issuer_attribute_len - = strlen (cd->credential->issuer_attribute) + 1; - cred[i].issuer_attribute = cd->credential->issuer_attribute; - cred[i].expiration = cd->credential->expiration; - cred[i].signature = cd->credential->signature; - cd = cd->next; - } + for (uint32_t i = 0; i < vrh->cred_chain_size; i++) + { + cred[i].issuer_key = cd->credential->issuer_key; + cred[i].subject_key = cd->credential->subject_key; + cred[i].issuer_attribute_len + = strlen(cd->credential->issuer_attribute) + 1; + cred[i].issuer_attribute = cd->credential->issuer_attribute; + cred[i].expiration = cd->credential->expiration; + cred[i].signature = cd->credential->signature; + cd = cd->next; + } size - = GNUNET_CREDENTIAL_delegation_chain_get_size (vrh->delegation_chain_size, - dd, - vrh->cred_chain_size, - cred); - env = GNUNET_MQ_msg_extra (rmsg, - size, - GNUNET_MESSAGE_TYPE_CREDENTIAL_VERIFY_RESULT); + = GNUNET_CREDENTIAL_delegation_chain_get_size(vrh->delegation_chain_size, + dd, + vrh->cred_chain_size, + cred); + env = GNUNET_MQ_msg_extra(rmsg, + size, + GNUNET_MESSAGE_TYPE_CREDENTIAL_VERIFY_RESULT); // Assign id so that client can find associated request rmsg->id = vrh->request_id; - rmsg->d_count = htonl (vrh->delegation_chain_size); - rmsg->c_count = htonl (vrh->cred_chain_size); + rmsg->d_count = htonl(vrh->delegation_chain_size); + rmsg->c_count = htonl(vrh->cred_chain_size); if (0 < vrh->cred_chain_size) - rmsg->cred_found = htonl (GNUNET_YES); + rmsg->cred_found = htonl(GNUNET_YES); else - rmsg->cred_found = htonl (GNUNET_NO); + rmsg->cred_found = htonl(GNUNET_NO); - GNUNET_assert ( + GNUNET_assert( -1 - != GNUNET_CREDENTIAL_delegation_chain_serialize (vrh->delegation_chain_size, - dd, - vrh->cred_chain_size, - cred, - size, - (char *)&rmsg[1])); - - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (vrh->client), env); - GNUNET_CONTAINER_DLL_remove (vrh_head, vrh_tail, vrh); - cleanup_handle (vrh); - - GNUNET_STATISTICS_update (statistics, - "Completed verifications", - 1, - GNUNET_NO); + != GNUNET_CREDENTIAL_delegation_chain_serialize(vrh->delegation_chain_size, + dd, + vrh->cred_chain_size, + cred, + size, + (char *)&rmsg[1])); + + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(vrh->client), env); + GNUNET_CONTAINER_DLL_remove(vrh_head, vrh_tail, vrh); + cleanup_handle(vrh); + + GNUNET_STATISTICS_update(statistics, + "Completed verifications", + 1, + GNUNET_NO); } static void -backward_resolution (void *cls, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +backward_resolution(void *cls, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { - struct VerifyRequestHandle *vrh; const struct GNUNET_CREDENTIAL_DelegationRecord *sets; struct CredentialRecordEntry *cred_pointer; @@ -559,176 +568,194 @@ backward_resolution (void *cls, current_set->lookup_request = NULL; vrh = current_set->handle; vrh->pending_lookups--; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got %d attrs\n", rd_count); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Got %d attrs\n", rd_count); // Each OR - for (uint32_t i = 0; i < rd_count; i++) { - if (GNUNET_GNSRECORD_TYPE_ATTRIBUTE != rd[i].record_type) - continue; - - sets = rd[i].data; - struct GNUNET_CREDENTIAL_DelegationSet set[ntohl (sets->set_count)]; - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Found new attribute delegation with %d sets. Creating new Job...\n", - ntohl (sets->set_count)); - - if (GNUNET_OK - != GNUNET_CREDENTIAL_delegation_set_deserialize ( - GNUNET_ntohll (sets->data_size), - (const char *)&sets[1], - ntohl (sets->set_count), - set)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to deserialize!\n"); - continue; - } - dq_entry = GNUNET_new (struct DelegationQueueEntry); - dq_entry->required_solutions = ntohl (sets->set_count); - dq_entry->parent_set = current_set; - GNUNET_CONTAINER_DLL_insert (current_set->queue_entries_head, - current_set->queue_entries_tail, - dq_entry); - // Each AND - for (uint32_t j = 0; j < ntohl (sets->set_count); j++) { - ds_entry = GNUNET_new (struct DelegationSetQueueEntry); - if (NULL != current_set->attr_trailer) { - if (0 == set[j].subject_attribute_len) { - GNUNET_asprintf (&expanded_attr, "%s", current_set->attr_trailer); - - } else { - GNUNET_asprintf (&expanded_attr, - "%s.%s", - set[j].subject_attribute, - current_set->attr_trailer); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Expanded to %s\n", expanded_attr); - ds_entry->unresolved_attribute_delegation = expanded_attr; - } else { - if (0 != set[j].subject_attribute_len) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Not Expanding %s\n", - set[j].subject_attribute); - ds_entry->unresolved_attribute_delegation - = GNUNET_strdup (set[j].subject_attribute); - } - } - - // Add a credential chain entry - ds_entry->delegation_chain_entry - = GNUNET_new (struct DelegationChainEntry); - ds_entry->delegation_chain_entry->subject_key = set[j].subject_key; - ds_entry->issuer_key = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPublicKey); - GNUNET_memcpy (ds_entry->issuer_key, - &set[j].subject_key, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)); - if (0 < set[j].subject_attribute_len) - ds_entry->delegation_chain_entry->subject_attribute - = GNUNET_strdup (set[j].subject_attribute); - ds_entry->delegation_chain_entry->issuer_key = *current_set->issuer_key; - ds_entry->delegation_chain_entry->issuer_attribute - = GNUNET_strdup (current_set->lookup_attribute); - - ds_entry->parent_queue_entry = dq_entry; // current_delegation; - GNUNET_CONTAINER_DLL_insert (dq_entry->set_entries_head, - dq_entry->set_entries_tail, - ds_entry); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Checking for cred match\n"); - /** - * Check if this delegation already matches one of our credentials - */ - for (cred_pointer = vrh->cred_chain_head; cred_pointer != NULL; - cred_pointer = cred_pointer->next) { - if (0 - != GNUNET_memcmp (&set->subject_key, - &cred_pointer->credential->issuer_key)) - continue; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Checking if %s matches %s\n", - ds_entry->unresolved_attribute_delegation, - cred_pointer->credential->issuer_attribute); - - if (0 - != strcmp (ds_entry->unresolved_attribute_delegation, - cred_pointer->credential->issuer_attribute)) - continue; + for (uint32_t i = 0; i < rd_count; i++) + { + if (GNUNET_GNSRECORD_TYPE_ATTRIBUTE != rd[i].record_type) + continue; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found issuer\n"); - cred_pointer->refcount++; - // Backtrack - for (tmp_set = ds_entry; NULL != tmp_set->parent_queue_entry; - tmp_set = tmp_set->parent_queue_entry->parent_set) { - tmp_set->parent_queue_entry->required_solutions--; - if (NULL != tmp_set->delegation_chain_entry) { - vrh->delegation_chain_size++; - GNUNET_CONTAINER_DLL_insert (vrh->delegation_chain_head, - vrh->delegation_chain_tail, - tmp_set->delegation_chain_entry); - } - if (0 < tmp_set->parent_queue_entry->required_solutions) - break; + sets = rd[i].data; + struct GNUNET_CREDENTIAL_DelegationSet set[ntohl(sets->set_count)]; + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Found new attribute delegation with %d sets. Creating new Job...\n", + ntohl(sets->set_count)); + + if (GNUNET_OK + != GNUNET_CREDENTIAL_delegation_set_deserialize( + GNUNET_ntohll(sets->data_size), + (const char *)&sets[1], + ntohl(sets->set_count), + set)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Failed to deserialize!\n"); + continue; } - - if (NULL == tmp_set->parent_queue_entry) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "All solutions found\n"); - // Found match - send_lookup_response (vrh); - return; + dq_entry = GNUNET_new(struct DelegationQueueEntry); + dq_entry->required_solutions = ntohl(sets->set_count); + dq_entry->parent_set = current_set; + GNUNET_CONTAINER_DLL_insert(current_set->queue_entries_head, + current_set->queue_entries_tail, + dq_entry); + // Each AND + for (uint32_t j = 0; j < ntohl(sets->set_count); j++) + { + ds_entry = GNUNET_new(struct DelegationSetQueueEntry); + if (NULL != current_set->attr_trailer) + { + if (0 == set[j].subject_attribute_len) + { + GNUNET_asprintf(&expanded_attr, "%s", current_set->attr_trailer); + } + else + { + GNUNET_asprintf(&expanded_attr, + "%s.%s", + set[j].subject_attribute, + current_set->attr_trailer); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Expanded to %s\n", expanded_attr); + ds_entry->unresolved_attribute_delegation = expanded_attr; + } + else + { + if (0 != set[j].subject_attribute_len) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Not Expanding %s\n", + set[j].subject_attribute); + ds_entry->unresolved_attribute_delegation + = GNUNET_strdup(set[j].subject_attribute); + } + } + + // Add a credential chain entry + ds_entry->delegation_chain_entry + = GNUNET_new(struct DelegationChainEntry); + ds_entry->delegation_chain_entry->subject_key = set[j].subject_key; + ds_entry->issuer_key = GNUNET_new(struct GNUNET_CRYPTO_EcdsaPublicKey); + GNUNET_memcpy(ds_entry->issuer_key, + &set[j].subject_key, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey)); + if (0 < set[j].subject_attribute_len) + ds_entry->delegation_chain_entry->subject_attribute + = GNUNET_strdup(set[j].subject_attribute); + ds_entry->delegation_chain_entry->issuer_key = *current_set->issuer_key; + ds_entry->delegation_chain_entry->issuer_attribute + = GNUNET_strdup(current_set->lookup_attribute); + + ds_entry->parent_queue_entry = dq_entry; // current_delegation; + GNUNET_CONTAINER_DLL_insert(dq_entry->set_entries_head, + dq_entry->set_entries_tail, + ds_entry); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Checking for cred match\n"); + /** + * Check if this delegation already matches one of our credentials + */ + for (cred_pointer = vrh->cred_chain_head; cred_pointer != NULL; + cred_pointer = cred_pointer->next) + { + if (0 + != GNUNET_memcmp(&set->subject_key, + &cred_pointer->credential->issuer_key)) + continue; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Checking if %s matches %s\n", + ds_entry->unresolved_attribute_delegation, + cred_pointer->credential->issuer_attribute); + + if (0 + != strcmp(ds_entry->unresolved_attribute_delegation, + cred_pointer->credential->issuer_attribute)) + continue; + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Found issuer\n"); + cred_pointer->refcount++; + // Backtrack + for (tmp_set = ds_entry; NULL != tmp_set->parent_queue_entry; + tmp_set = tmp_set->parent_queue_entry->parent_set) + { + tmp_set->parent_queue_entry->required_solutions--; + if (NULL != tmp_set->delegation_chain_entry) + { + vrh->delegation_chain_size++; + GNUNET_CONTAINER_DLL_insert(vrh->delegation_chain_head, + vrh->delegation_chain_tail, + tmp_set->delegation_chain_entry); + } + if (0 < tmp_set->parent_queue_entry->required_solutions) + break; + } + + if (NULL == tmp_set->parent_queue_entry) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "All solutions found\n"); + // Found match + send_lookup_response(vrh); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Not all solutions found yet.\n"); + continue; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Building new lookup request from %s\n", + ds_entry->unresolved_attribute_delegation); + // Continue with backward resolution + char + issuer_attribute_name[strlen(ds_entry->unresolved_attribute_delegation) + + 1]; + strcpy(issuer_attribute_name, ds_entry->unresolved_attribute_delegation); + char *next_attr = strtok(issuer_attribute_name, "."); + if (NULL == next_attr) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to parse next attribute\n"); + continue; + } + GNUNET_asprintf(&lookup_attribute, "%s", next_attr); + GNUNET_asprintf(&ds_entry->lookup_attribute, "%s", next_attr); + if (strlen(next_attr) + == strlen(ds_entry->unresolved_attribute_delegation)) + { + ds_entry->attr_trailer = NULL; + } + else + { + next_attr += strlen(next_attr) + 1; + ds_entry->attr_trailer = GNUNET_strdup(next_attr); + } + + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Looking up %s\n", + ds_entry->lookup_attribute); + if (NULL != ds_entry->attr_trailer) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "%s still to go...\n", + ds_entry->attr_trailer); + + vrh->pending_lookups++; + ds_entry->handle = vrh; + ds_entry->lookup_request + = GNUNET_GNS_lookup(gns, + lookup_attribute, + ds_entry->issuer_key, // issuer_key, + GNUNET_GNSRECORD_TYPE_ATTRIBUTE, + GNUNET_GNS_LO_DEFAULT, + &backward_resolution, + ds_entry); + GNUNET_free(lookup_attribute); } - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Not all solutions found yet.\n"); - continue; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Building new lookup request from %s\n", - ds_entry->unresolved_attribute_delegation); - // Continue with backward resolution - char - issuer_attribute_name[strlen (ds_entry->unresolved_attribute_delegation) - + 1]; - strcpy (issuer_attribute_name, ds_entry->unresolved_attribute_delegation); - char *next_attr = strtok (issuer_attribute_name, "."); - if (NULL == next_attr) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to parse next attribute\n"); - continue; - } - GNUNET_asprintf (&lookup_attribute, "%s", next_attr); - GNUNET_asprintf (&ds_entry->lookup_attribute, "%s", next_attr); - if (strlen (next_attr) - == strlen (ds_entry->unresolved_attribute_delegation)) { - ds_entry->attr_trailer = NULL; - } else { - next_attr += strlen (next_attr) + 1; - ds_entry->attr_trailer = GNUNET_strdup (next_attr); - } - - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Looking up %s\n", - ds_entry->lookup_attribute); - if (NULL != ds_entry->attr_trailer) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "%s still to go...\n", - ds_entry->attr_trailer); - - vrh->pending_lookups++; - ds_entry->handle = vrh; - ds_entry->lookup_request - = GNUNET_GNS_lookup (gns, - lookup_attribute, - ds_entry->issuer_key, // issuer_key, - GNUNET_GNSRECORD_TYPE_ATTRIBUTE, - GNUNET_GNS_LO_DEFAULT, - &backward_resolution, - ds_entry); - GNUNET_free (lookup_attribute); } - } - if (0 == vrh->pending_lookups) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "We are all out of attributes...\n"); - send_lookup_response (vrh); - return; - } + if (0 == vrh->pending_lookups) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "We are all out of attributes...\n"); + send_lookup_response(vrh); + return; + } } @@ -738,90 +765,96 @@ backward_resolution (void *cls, * @param cls the closure (our client lookup handle) */ static void -delegation_chain_resolution_start (void *cls) +delegation_chain_resolution_start(void *cls) { struct VerifyRequestHandle *vrh = cls; struct DelegationSetQueueEntry *ds_entry; struct CredentialRecordEntry *cr_entry; + vrh->lookup_request = NULL; - if (0 == vrh->cred_chain_size) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No credentials found\n"); - send_lookup_response (vrh); - return; - } + if (0 == vrh->cred_chain_size) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No credentials found\n"); + send_lookup_response(vrh); + return; + } for (cr_entry = vrh->cred_chain_head; cr_entry != NULL; - cr_entry = cr_entry->next) { - if (0 - != GNUNET_memcmp (&cr_entry->credential->issuer_key, - &vrh->issuer_key)) - continue; - if (0 - != strcmp (cr_entry->credential->issuer_attribute, - vrh->issuer_attribute)) - continue; - cr_entry->refcount++; - // Found match prematurely - send_lookup_response (vrh); - return; - } + cr_entry = cr_entry->next) + { + if (0 + != GNUNET_memcmp(&cr_entry->credential->issuer_key, + &vrh->issuer_key)) + continue; + if (0 + != strcmp(cr_entry->credential->issuer_attribute, + vrh->issuer_attribute)) + continue; + cr_entry->refcount++; + // Found match prematurely + send_lookup_response(vrh); + return; + } /** * Check for attributes from the issuer and follow the chain * till you get the required subject's attributes */ - char issuer_attribute_name[strlen (vrh->issuer_attribute) + 1]; - strcpy (issuer_attribute_name, vrh->issuer_attribute); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Looking up %s\n", - issuer_attribute_name); - ds_entry = GNUNET_new (struct DelegationSetQueueEntry); - ds_entry->issuer_key = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPublicKey); - GNUNET_memcpy (ds_entry->issuer_key, - &vrh->issuer_key, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)); - ds_entry->issuer_attribute = GNUNET_strdup (vrh->issuer_attribute); + char issuer_attribute_name[strlen(vrh->issuer_attribute) + 1]; + strcpy(issuer_attribute_name, vrh->issuer_attribute); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Looking up %s\n", + issuer_attribute_name); + ds_entry = GNUNET_new(struct DelegationSetQueueEntry); + ds_entry->issuer_key = GNUNET_new(struct GNUNET_CRYPTO_EcdsaPublicKey); + GNUNET_memcpy(ds_entry->issuer_key, + &vrh->issuer_key, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey)); + ds_entry->issuer_attribute = GNUNET_strdup(vrh->issuer_attribute); ds_entry->handle = vrh; - ds_entry->lookup_attribute = GNUNET_strdup (vrh->issuer_attribute); + ds_entry->lookup_attribute = GNUNET_strdup(vrh->issuer_attribute); vrh->root_set = ds_entry; vrh->pending_lookups = 1; // Start with backward resolution - ds_entry->lookup_request = GNUNET_GNS_lookup (gns, - issuer_attribute_name, - &vrh->issuer_key, // issuer_key, - GNUNET_GNSRECORD_TYPE_ATTRIBUTE, - GNUNET_GNS_LO_DEFAULT, - &backward_resolution, - ds_entry); + ds_entry->lookup_request = GNUNET_GNS_lookup(gns, + issuer_attribute_name, + &vrh->issuer_key, // issuer_key, + GNUNET_GNSRECORD_TYPE_ATTRIBUTE, + GNUNET_GNS_LO_DEFAULT, + &backward_resolution, + ds_entry); } static int -check_verify (void *cls, const struct VerifyMessage *v_msg) +check_verify(void *cls, const struct VerifyMessage *v_msg) { size_t msg_size; const char *attr; - msg_size = ntohs (v_msg->header.size); - if (msg_size < sizeof (struct VerifyMessage)) { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (ntohs (v_msg->issuer_attribute_len) > GNUNET_CREDENTIAL_MAX_LENGTH) { - GNUNET_break (0); - return GNUNET_SYSERR; - } + msg_size = ntohs(v_msg->header.size); + if (msg_size < sizeof(struct VerifyMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (ntohs(v_msg->issuer_attribute_len) > GNUNET_CREDENTIAL_MAX_LENGTH) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } attr = (const char *)&v_msg[1]; - if (strlen (attr) > GNUNET_CREDENTIAL_MAX_LENGTH) { - GNUNET_break (0); - return GNUNET_SYSERR; - } + if (strlen(attr) > GNUNET_CREDENTIAL_MAX_LENGTH) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } static void -handle_verify (void *cls, const struct VerifyMessage *v_msg) +handle_verify(void *cls, const struct VerifyMessage *v_msg) { struct VerifyRequestHandle *vrh; struct GNUNET_SERVICE_Client *client = cls; @@ -834,96 +867,101 @@ handle_verify (void *cls, const struct VerifyMessage *v_msg) char *credential_data; const char *utf_in; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received VERIFY message\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received VERIFY message\n"); utf_in = (const char *)&v_msg[1]; - GNUNET_STRINGS_utf8_tolower (utf_in, attrptr); - GNUNET_memcpy (issuer_attribute, attr, ntohs (v_msg->issuer_attribute_len)); - issuer_attribute[ntohs (v_msg->issuer_attribute_len)] = '\0'; - vrh = GNUNET_new (struct VerifyRequestHandle); - GNUNET_CONTAINER_DLL_insert (vrh_head, vrh_tail, vrh); + GNUNET_STRINGS_utf8_tolower(utf_in, attrptr); + GNUNET_memcpy(issuer_attribute, attr, ntohs(v_msg->issuer_attribute_len)); + issuer_attribute[ntohs(v_msg->issuer_attribute_len)] = '\0'; + vrh = GNUNET_new(struct VerifyRequestHandle); + GNUNET_CONTAINER_DLL_insert(vrh_head, vrh_tail, vrh); vrh->client = client; vrh->request_id = v_msg->id; vrh->issuer_key = v_msg->issuer_key; vrh->subject_key = v_msg->subject_key; - vrh->issuer_attribute = GNUNET_strdup (issuer_attribute); - GNUNET_SERVICE_client_continue (vrh->client); - if (0 == strlen (issuer_attribute)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No issuer attribute provided!\n"); - send_lookup_response (vrh); - return; - } + vrh->issuer_attribute = GNUNET_strdup(issuer_attribute); + GNUNET_SERVICE_client_continue(vrh->client); + if (0 == strlen(issuer_attribute)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No issuer attribute provided!\n"); + send_lookup_response(vrh); + return; + } /** * First, collect credentials * TODO: cleanup! */ - credentials_count = ntohl (v_msg->c_count); - credential_data_size = ntohs (v_msg->header.size) - - sizeof (struct VerifyMessage) - - ntohs (v_msg->issuer_attribute_len) - 1; + credentials_count = ntohl(v_msg->c_count); + credential_data_size = ntohs(v_msg->header.size) + - sizeof(struct VerifyMessage) + - ntohs(v_msg->issuer_attribute_len) - 1; struct GNUNET_CREDENTIAL_Credential credentials[credentials_count]; - memset (credentials, - 0, - sizeof (struct GNUNET_CREDENTIAL_Credential) * credentials_count); - credential_data = (char *)&v_msg[1] + ntohs (v_msg->issuer_attribute_len) + 1; + memset(credentials, + 0, + sizeof(struct GNUNET_CREDENTIAL_Credential) * credentials_count); + credential_data = (char *)&v_msg[1] + ntohs(v_msg->issuer_attribute_len) + 1; if (GNUNET_OK - != GNUNET_CREDENTIAL_credentials_deserialize (credential_data_size, - credential_data, - credentials_count, - credentials)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot deserialize credentials!\n"); - send_lookup_response (vrh); - return; - } - - for (uint32_t i = 0; i < credentials_count; i++) { - cr_entry = GNUNET_new (struct CredentialRecordEntry); - cr_entry->credential - = GNUNET_malloc (sizeof (struct GNUNET_CREDENTIAL_Credential) - + credentials[i].issuer_attribute_len + 1); - GNUNET_memcpy (cr_entry->credential, - &credentials[i], - sizeof (struct GNUNET_CREDENTIAL_Credential)); - GNUNET_memcpy (&cr_entry->credential[1], - credentials[i].issuer_attribute, - credentials[i].issuer_attribute_len); - cr_entry->credential->issuer_attribute_len - = credentials[i].issuer_attribute_len; - cr_entry->credential->issuer_attribute = (char *)&cr_entry->credential[1]; - GNUNET_CONTAINER_DLL_insert_tail (vrh->cred_chain_head, - vrh->cred_chain_tail, - cr_entry); - vrh->cred_chain_size++; - } - - delegation_chain_resolution_start (vrh); + != GNUNET_CREDENTIAL_credentials_deserialize(credential_data_size, + credential_data, + credentials_count, + credentials)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot deserialize credentials!\n"); + send_lookup_response(vrh); + return; + } + + for (uint32_t i = 0; i < credentials_count; i++) + { + cr_entry = GNUNET_new(struct CredentialRecordEntry); + cr_entry->credential + = GNUNET_malloc(sizeof(struct GNUNET_CREDENTIAL_Credential) + + credentials[i].issuer_attribute_len + 1); + GNUNET_memcpy(cr_entry->credential, + &credentials[i], + sizeof(struct GNUNET_CREDENTIAL_Credential)); + GNUNET_memcpy(&cr_entry->credential[1], + credentials[i].issuer_attribute, + credentials[i].issuer_attribute_len); + cr_entry->credential->issuer_attribute_len + = credentials[i].issuer_attribute_len; + cr_entry->credential->issuer_attribute = (char *)&cr_entry->credential[1]; + GNUNET_CONTAINER_DLL_insert_tail(vrh->cred_chain_head, + vrh->cred_chain_tail, + cr_entry); + vrh->cred_chain_size++; + } + + delegation_chain_resolution_start(vrh); } static void -handle_cred_collection_error_cb (void *cls) +handle_cred_collection_error_cb(void *cls) { struct VerifyRequestHandle *vrh = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got disconnected from namestore database.\n"); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got disconnected from namestore database.\n"); vrh->cred_collection_iter = NULL; - send_lookup_response (vrh); + send_lookup_response(vrh); } static void -collect_next (void *cls) +collect_next(void *cls) { struct VerifyRequestHandle *vrh = cls; + vrh->collect_next_task = NULL; - GNUNET_assert (NULL != vrh->cred_collection_iter); - GNUNET_NAMESTORE_zone_iterator_next (vrh->cred_collection_iter, 1); + GNUNET_assert(NULL != vrh->cred_collection_iter); + GNUNET_NAMESTORE_zone_iterator_next(vrh->cred_collection_iter, 1); } static void -handle_cred_collection_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +handle_cred_collection_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct VerifyRequestHandle *vrh = cls; struct GNUNET_CREDENTIAL_Credential *crd; @@ -931,37 +969,40 @@ handle_cred_collection_cb (void *cls, int cred_record_count; cred_record_count = 0; - for (uint32_t i = 0; i < rd_count; i++) { - if (GNUNET_GNSRECORD_TYPE_CREDENTIAL != rd[i].record_type) - continue; - cred_record_count++; - crd - = GNUNET_CREDENTIAL_credential_deserialize (rd[i].data, rd[i].data_size); - if (NULL == crd) { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Invalid credential found\n"); - continue; + for (uint32_t i = 0; i < rd_count; i++) + { + if (GNUNET_GNSRECORD_TYPE_CREDENTIAL != rd[i].record_type) + continue; + cred_record_count++; + crd + = GNUNET_CREDENTIAL_credential_deserialize(rd[i].data, rd[i].data_size); + if (NULL == crd) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Invalid credential found\n"); + continue; + } + cr_entry = GNUNET_new(struct CredentialRecordEntry); + cr_entry->credential = crd; + GNUNET_CONTAINER_DLL_insert_tail(vrh->cred_chain_head, + vrh->cred_chain_tail, + cr_entry); + vrh->cred_chain_size++; } - cr_entry = GNUNET_new (struct CredentialRecordEntry); - cr_entry->credential = crd; - GNUNET_CONTAINER_DLL_insert_tail (vrh->cred_chain_head, - vrh->cred_chain_tail, - cr_entry); - vrh->cred_chain_size++; - } - vrh->collect_next_task = GNUNET_SCHEDULER_add_now (&collect_next, vrh); + vrh->collect_next_task = GNUNET_SCHEDULER_add_now(&collect_next, vrh); } static void -handle_cred_collection_finished_cb (void *cls) +handle_cred_collection_finished_cb(void *cls) { struct VerifyRequestHandle *vrh = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Done collecting credentials.\n"); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Done collecting credentials.\n"); vrh->cred_collection_iter = NULL; - delegation_chain_resolution_start (vrh); + delegation_chain_resolution_start(vrh); } static void -handle_collect (void *cls, const struct CollectMessage *c_msg) +handle_collect(void *cls, const struct CollectMessage *c_msg) { char attr[GNUNET_CREDENTIAL_MAX_LENGTH + 1]; char issuer_attribute[GNUNET_CREDENTIAL_MAX_LENGTH + 1]; @@ -970,31 +1011,32 @@ handle_collect (void *cls, const struct CollectMessage *c_msg) char *attrptr = attr; const char *utf_in; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received COLLECT message\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received COLLECT message\n"); utf_in = (const char *)&c_msg[1]; - GNUNET_STRINGS_utf8_tolower (utf_in, attrptr); + GNUNET_STRINGS_utf8_tolower(utf_in, attrptr); - GNUNET_memcpy (issuer_attribute, attr, ntohs (c_msg->issuer_attribute_len)); - issuer_attribute[ntohs (c_msg->issuer_attribute_len)] = '\0'; - vrh = GNUNET_new (struct VerifyRequestHandle); - GNUNET_CONTAINER_DLL_insert (vrh_head, vrh_tail, vrh); + GNUNET_memcpy(issuer_attribute, attr, ntohs(c_msg->issuer_attribute_len)); + issuer_attribute[ntohs(c_msg->issuer_attribute_len)] = '\0'; + vrh = GNUNET_new(struct VerifyRequestHandle); + GNUNET_CONTAINER_DLL_insert(vrh_head, vrh_tail, vrh); vrh->client = client; vrh->request_id = c_msg->id; vrh->issuer_key = c_msg->issuer_key; - GNUNET_CRYPTO_ecdsa_key_get_public (&c_msg->subject_key, &vrh->subject_key); - vrh->issuer_attribute = GNUNET_strdup (issuer_attribute); - - if (0 == strlen (issuer_attribute)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No issuer attribute provided!\n"); - send_lookup_response (vrh); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Getting credentials for subject\n"); + GNUNET_CRYPTO_ecdsa_key_get_public(&c_msg->subject_key, &vrh->subject_key); + vrh->issuer_attribute = GNUNET_strdup(issuer_attribute); + + if (0 == strlen(issuer_attribute)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No issuer attribute provided!\n"); + send_lookup_response(vrh); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Getting credentials for subject\n"); /** * First, get attribute from subject */ - vrh->cred_collection_iter = GNUNET_NAMESTORE_zone_iteration_start ( + vrh->cred_collection_iter = GNUNET_NAMESTORE_zone_iteration_start( namestore, &c_msg->subject_key, &handle_cred_collection_error_cb, @@ -1003,49 +1045,52 @@ handle_collect (void *cls, const struct CollectMessage *c_msg) vrh, &handle_cred_collection_finished_cb, vrh); - GNUNET_SERVICE_client_continue (vrh->client); + GNUNET_SERVICE_client_continue(vrh->client); } static int -check_collect (void *cls, const struct CollectMessage *c_msg) +check_collect(void *cls, const struct CollectMessage *c_msg) { size_t msg_size; const char *attr; - msg_size = ntohs (c_msg->header.size); - if (msg_size < sizeof (struct CollectMessage)) { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (ntohs (c_msg->issuer_attribute_len) > GNUNET_CREDENTIAL_MAX_LENGTH) { - GNUNET_break (0); - return GNUNET_SYSERR; - } + msg_size = ntohs(c_msg->header.size); + if (msg_size < sizeof(struct CollectMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (ntohs(c_msg->issuer_attribute_len) > GNUNET_CREDENTIAL_MAX_LENGTH) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } attr = (const char *)&c_msg[1]; - if (('\0' != attr[msg_size - sizeof (struct CollectMessage) - 1]) - || (strlen (attr) > GNUNET_CREDENTIAL_MAX_LENGTH)) { - GNUNET_break (0); - return GNUNET_SYSERR; - } + if (('\0' != attr[msg_size - sizeof(struct CollectMessage) - 1]) + || (strlen(attr) > GNUNET_CREDENTIAL_MAX_LENGTH)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p disconnected\n", client); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Client %p disconnected\n", client); } static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p connected\n", client); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Client %p connected\n", client); return client; } @@ -1057,43 +1102,44 @@ client_connect_cb (void *cls, * @param handle service handle */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *handle) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *handle) { + gns = GNUNET_GNS_connect(c); + if (NULL == gns) + { + fprintf(stderr, _("Failed to connect to GNS\n")); + } + namestore = GNUNET_NAMESTORE_connect(c); + if (NULL == namestore) + { + fprintf(stderr, _("Failed to connect to namestore\n")); + } - gns = GNUNET_GNS_connect (c); - if (NULL == gns) { - fprintf (stderr, _ ("Failed to connect to GNS\n")); - } - namestore = GNUNET_NAMESTORE_connect (c); - if (NULL == namestore) { - fprintf (stderr, _ ("Failed to connect to namestore\n")); - } - - statistics = GNUNET_STATISTICS_create ("credential", c); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + statistics = GNUNET_STATISTICS_create("credential", c); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); } /** * Define "main" method using service macro */ -GNUNET_SERVICE_MAIN ( +GNUNET_SERVICE_MAIN( "credential", GNUNET_SERVICE_OPTION_NONE, &run, &client_connect_cb, &client_disconnect_cb, NULL, - GNUNET_MQ_hd_var_size (verify, - GNUNET_MESSAGE_TYPE_CREDENTIAL_VERIFY, - struct VerifyMessage, - NULL), - GNUNET_MQ_hd_var_size (collect, - GNUNET_MESSAGE_TYPE_CREDENTIAL_COLLECT, - struct CollectMessage, - NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_hd_var_size(verify, + GNUNET_MESSAGE_TYPE_CREDENTIAL_VERIFY, + struct VerifyMessage, + NULL), + GNUNET_MQ_hd_var_size(collect, + GNUNET_MESSAGE_TYPE_CREDENTIAL_COLLECT, + struct CollectMessage, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-credential.c */ diff --git a/src/credential/plugin_gnsrecord_credential.c b/src/credential/plugin_gnsrecord_credential.c index c03f2b3e4..9207aa7ad 100644 --- a/src/credential/plugin_gnsrecord_credential.c +++ b/src/credential/plugin_gnsrecord_credential.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file credential/plugin_gnsrecord_credential.c @@ -43,72 +43,85 @@ * @return NULL on error, otherwise human-readable representation of the value */ static char * -credential_value_to_string (void *cls, uint32_t type, const void *data, - size_t data_size) +credential_value_to_string(void *cls, uint32_t type, const void *data, + size_t data_size) { - const char *cdata; - switch (type) { - case GNUNET_GNSRECORD_TYPE_ATTRIBUTE: { - struct GNUNET_CREDENTIAL_DelegationRecord sets; - char *attr_str; - char *subject_pkey; - char *tmp_str; - int i; - if (data_size < sizeof (struct GNUNET_CREDENTIAL_DelegationRecord)) - return NULL; /* malformed */ - GNUNET_memcpy (&sets, data, sizeof (sets)); - cdata = data; - struct GNUNET_CREDENTIAL_DelegationSet set[ntohl (sets.set_count)]; - if (GNUNET_OK != GNUNET_CREDENTIAL_delegation_set_deserialize ( - GNUNET_ntohll (sets.data_size), &cdata[sizeof (sets)], - ntohl (sets.set_count), set)) - return NULL; - - for (i = 0; i < ntohl (sets.set_count); i++) { - subject_pkey = - GNUNET_CRYPTO_ecdsa_public_key_to_string (&set[i].subject_key); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%d len attr\n", - set[i].subject_attribute_len); - if (0 == set[i].subject_attribute_len) { - if (0 == i) { - GNUNET_asprintf (&attr_str, "%s", subject_pkey); - } else { - GNUNET_asprintf (&tmp_str, "%s,%s", attr_str, subject_pkey); - GNUNET_free (attr_str); - attr_str = tmp_str; + switch (type) + { + case GNUNET_GNSRECORD_TYPE_ATTRIBUTE: { + struct GNUNET_CREDENTIAL_DelegationRecord sets; + char *attr_str; + char *subject_pkey; + char *tmp_str; + int i; + if (data_size < sizeof(struct GNUNET_CREDENTIAL_DelegationRecord)) + return NULL; /* malformed */ + GNUNET_memcpy(&sets, data, sizeof(sets)); + cdata = data; + struct GNUNET_CREDENTIAL_DelegationSet set[ntohl(sets.set_count)]; + if (GNUNET_OK != GNUNET_CREDENTIAL_delegation_set_deserialize( + GNUNET_ntohll(sets.data_size), &cdata[sizeof(sets)], + ntohl(sets.set_count), set)) + return NULL; + + for (i = 0; i < ntohl(sets.set_count); i++) + { + subject_pkey = + GNUNET_CRYPTO_ecdsa_public_key_to_string(&set[i].subject_key); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%d len attr\n", + set[i].subject_attribute_len); + if (0 == set[i].subject_attribute_len) + { + if (0 == i) + { + GNUNET_asprintf(&attr_str, "%s", subject_pkey); + } + else + { + GNUNET_asprintf(&tmp_str, "%s,%s", attr_str, subject_pkey); + GNUNET_free(attr_str); + attr_str = tmp_str; + } + } + else + { + if (0 == i) + { + GNUNET_asprintf(&attr_str, "%s %s", subject_pkey, + set[i].subject_attribute); + } + else + { + GNUNET_asprintf(&tmp_str, "%s,%s %s", attr_str, subject_pkey, + set[i].subject_attribute); + GNUNET_free(attr_str); + attr_str = tmp_str; + } + } + GNUNET_free(subject_pkey); } - } else { - if (0 == i) { - GNUNET_asprintf (&attr_str, "%s %s", subject_pkey, - set[i].subject_attribute); - } else { - GNUNET_asprintf (&tmp_str, "%s,%s %s", attr_str, subject_pkey, - set[i].subject_attribute); - GNUNET_free (attr_str); - attr_str = tmp_str; - } - } - GNUNET_free (subject_pkey); + return attr_str; + } + + case GNUNET_GNSRECORD_TYPE_CREDENTIAL: { + struct GNUNET_CREDENTIAL_Credential *cred; + char *cred_str; + + cred = GNUNET_CREDENTIAL_credential_deserialize(data, data_size); + cred_str = GNUNET_CREDENTIAL_credential_to_string(cred); + GNUNET_free(cred); + return cred_str; + } + + case GNUNET_GNSRECORD_TYPE_POLICY: { + return GNUNET_strndup(data, data_size); + } + + default: + return NULL; } - return attr_str; - } - case GNUNET_GNSRECORD_TYPE_CREDENTIAL: { - struct GNUNET_CREDENTIAL_Credential *cred; - char *cred_str; - - cred = GNUNET_CREDENTIAL_credential_deserialize (data, data_size); - cred_str = GNUNET_CREDENTIAL_credential_to_string (cred); - GNUNET_free (cred); - return cred_str; - } - case GNUNET_GNSRECORD_TYPE_POLICY: { - return GNUNET_strndup (data, data_size); - } - default: - return NULL; - } } @@ -124,100 +137,114 @@ credential_value_to_string (void *cls, uint32_t type, const void *data, * @return #GNUNET_OK on success */ static int -credential_string_to_value (void *cls, uint32_t type, const char *s, - void **data, size_t *data_size) +credential_string_to_value(void *cls, uint32_t type, const char *s, + void **data, size_t *data_size) { if (NULL == s) return GNUNET_SYSERR; - switch (type) { - case GNUNET_GNSRECORD_TYPE_ATTRIBUTE: { - struct GNUNET_CREDENTIAL_DelegationRecord *sets; - char attr_str[253 + 1]; - char subject_pkey[52 + 1]; - char *token; - char *tmp_str; - int matches = 0; - int entries; - size_t tmp_data_size; - int i; - - tmp_str = GNUNET_strdup (s); - token = strtok (tmp_str, ","); - entries = 0; - tmp_data_size = 0; - *data_size = sizeof (struct GNUNET_CREDENTIAL_DelegationRecord); - while (NULL != token) { - matches = SSCANF (token, "%s %s", subject_pkey, attr_str); - if (0 == matches) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse ATTR record string `%s'\n"), s); - GNUNET_free (tmp_str); - return GNUNET_SYSERR; - } - if (1 == matches) { - tmp_data_size += sizeof (struct GNUNET_CREDENTIAL_DelegationRecordSet); - } else if (2 == matches) { - tmp_data_size += sizeof (struct GNUNET_CREDENTIAL_DelegationRecordSet) + - strlen (attr_str) + 1; - } - entries++; - token = strtok (NULL, ","); + switch (type) + { + case GNUNET_GNSRECORD_TYPE_ATTRIBUTE: { + struct GNUNET_CREDENTIAL_DelegationRecord *sets; + char attr_str[253 + 1]; + char subject_pkey[52 + 1]; + char *token; + char *tmp_str; + int matches = 0; + int entries; + size_t tmp_data_size; + int i; + + tmp_str = GNUNET_strdup(s); + token = strtok(tmp_str, ","); + entries = 0; + tmp_data_size = 0; + *data_size = sizeof(struct GNUNET_CREDENTIAL_DelegationRecord); + while (NULL != token) + { + matches = SSCANF(token, "%s %s", subject_pkey, attr_str); + if (0 == matches) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse ATTR record string `%s'\n"), s); + GNUNET_free(tmp_str); + return GNUNET_SYSERR; + } + if (1 == matches) + { + tmp_data_size += sizeof(struct GNUNET_CREDENTIAL_DelegationRecordSet); + } + else if (2 == matches) + { + tmp_data_size += sizeof(struct GNUNET_CREDENTIAL_DelegationRecordSet) + + strlen(attr_str) + 1; + } + entries++; + token = strtok(NULL, ","); + } + GNUNET_free(tmp_str); + tmp_str = GNUNET_strdup(s); + token = strtok(tmp_str, ","); + if (NULL == token) + { + GNUNET_free(tmp_str); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Malformed string %s\n", s); + return GNUNET_SYSERR; + } + struct GNUNET_CREDENTIAL_DelegationSet set[entries]; + memset(set, 0, sizeof(struct GNUNET_CREDENTIAL_DelegationSet) * entries); + for (i = 0; i < entries; i++) + { + matches = SSCANF(token, "%s %s", subject_pkey, attr_str); + GNUNET_CRYPTO_ecdsa_public_key_from_string( + subject_pkey, strlen(subject_pkey), &set[i].subject_key); + if (2 == matches) + { + set[i].subject_attribute_len = strlen(attr_str) + 1; + set[i].subject_attribute = GNUNET_strdup(attr_str); + } + token = strtok(NULL, ","); + } + tmp_data_size = GNUNET_CREDENTIAL_delegation_set_get_size(entries, set); + + if (-1 == tmp_data_size) + { + GNUNET_free(tmp_str); + return GNUNET_SYSERR; + } + *data_size += tmp_data_size; + *data = sets = GNUNET_malloc(*data_size); + GNUNET_CREDENTIAL_delegation_set_serialize(entries, set, tmp_data_size, + (char *)&sets[1]); + for (i = 0; i < entries; i++) + { + if (0 != set[i].subject_attribute_len) + GNUNET_free((char *)set[i].subject_attribute); + } + sets->set_count = htonl(entries); + sets->data_size = GNUNET_htonll(tmp_data_size); + + GNUNET_free(tmp_str); + return GNUNET_OK; } - GNUNET_free (tmp_str); - tmp_str = GNUNET_strdup (s); - token = strtok (tmp_str, ","); - if (NULL == token) { - GNUNET_free (tmp_str); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Malformed string %s\n", s); - return GNUNET_SYSERR; + + case GNUNET_GNSRECORD_TYPE_CREDENTIAL: { + struct GNUNET_CREDENTIAL_Credential *cred; + cred = GNUNET_CREDENTIAL_credential_from_string(s); + + *data_size = GNUNET_CREDENTIAL_credential_serialize(cred, (char **)data); + return GNUNET_OK; } - struct GNUNET_CREDENTIAL_DelegationSet set[entries]; - memset (set, 0, sizeof (struct GNUNET_CREDENTIAL_DelegationSet) * entries); - for (i = 0; i < entries; i++) { - matches = SSCANF (token, "%s %s", subject_pkey, attr_str); - GNUNET_CRYPTO_ecdsa_public_key_from_string ( - subject_pkey, strlen (subject_pkey), &set[i].subject_key); - if (2 == matches) { - set[i].subject_attribute_len = strlen (attr_str) + 1; - set[i].subject_attribute = GNUNET_strdup (attr_str); - } - token = strtok (NULL, ","); + + case GNUNET_GNSRECORD_TYPE_POLICY: { + *data_size = strlen(s); + *data = GNUNET_strdup(s); + return GNUNET_OK; } - tmp_data_size = GNUNET_CREDENTIAL_delegation_set_get_size (entries, set); - if (-1 == tmp_data_size) { - GNUNET_free (tmp_str); + default: return GNUNET_SYSERR; } - *data_size += tmp_data_size; - *data = sets = GNUNET_malloc (*data_size); - GNUNET_CREDENTIAL_delegation_set_serialize (entries, set, tmp_data_size, - (char *)&sets[1]); - for (i = 0; i < entries; i++) { - if (0 != set[i].subject_attribute_len) - GNUNET_free ((char *)set[i].subject_attribute); - } - sets->set_count = htonl (entries); - sets->data_size = GNUNET_htonll (tmp_data_size); - - GNUNET_free (tmp_str); - return GNUNET_OK; - } - case GNUNET_GNSRECORD_TYPE_CREDENTIAL: { - struct GNUNET_CREDENTIAL_Credential *cred; - cred = GNUNET_CREDENTIAL_credential_from_string (s); - - *data_size = GNUNET_CREDENTIAL_credential_serialize (cred, (char **)data); - return GNUNET_OK; - } - case GNUNET_GNSRECORD_TYPE_POLICY: { - *data_size = strlen (s); - *data = GNUNET_strdup (s); - return GNUNET_OK; - } - default: - return GNUNET_SYSERR; - } } @@ -225,14 +252,13 @@ credential_string_to_value (void *cls, uint32_t type, const char *s, * Mapping of record type numbers to human-readable * record type names. */ -static struct -{ +static struct { const char *name; uint32_t number; -} name_map[] = {{"CRED", GNUNET_GNSRECORD_TYPE_CREDENTIAL}, - {"ATTR", GNUNET_GNSRECORD_TYPE_ATTRIBUTE}, - {"POLICY", GNUNET_GNSRECORD_TYPE_POLICY}, - {NULL, UINT32_MAX}}; +} name_map[] = { { "CRED", GNUNET_GNSRECORD_TYPE_CREDENTIAL }, + { "ATTR", GNUNET_GNSRECORD_TYPE_ATTRIBUTE }, + { "POLICY", GNUNET_GNSRECORD_TYPE_POLICY }, + { NULL, UINT32_MAX } }; /** @@ -243,13 +269,13 @@ static struct * @return corresponding number, UINT32_MAX on error */ static uint32_t -credential_typename_to_number (void *cls, const char *gns_typename) +credential_typename_to_number(void *cls, const char *gns_typename) { unsigned int i; i = 0; while ((name_map[i].name != NULL) && - (0 != strcasecmp (gns_typename, name_map[i].name))) + (0 != strcasecmp(gns_typename, name_map[i].name))) i++; return name_map[i].number; } @@ -263,7 +289,7 @@ credential_typename_to_number (void *cls, const char *gns_typename) * @return corresponding typestring, NULL on error */ static const char * -credential_number_to_typename (void *cls, uint32_t type) +credential_number_to_typename(void *cls, uint32_t type) { unsigned int i; @@ -281,11 +307,11 @@ credential_number_to_typename (void *cls, uint32_t type) * @return the exported block API */ void * -libgnunet_plugin_gnsrecord_credential_init (void *cls) +libgnunet_plugin_gnsrecord_credential_init(void *cls) { struct GNUNET_GNSRECORD_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_GNSRECORD_PluginFunctions); + api = GNUNET_new(struct GNUNET_GNSRECORD_PluginFunctions); api->value_to_string = &credential_value_to_string; api->string_to_value = &credential_string_to_value; api->typename_to_number = &credential_typename_to_number; @@ -301,11 +327,11 @@ libgnunet_plugin_gnsrecord_credential_init (void *cls) * @return NULL */ void * -libgnunet_plugin_gnsrecord_credential_done (void *cls) +libgnunet_plugin_gnsrecord_credential_done(void *cls) { struct GNUNET_GNSRECORD_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/credential/plugin_rest_credential.c b/src/credential/plugin_rest_credential.c index 78267b54e..51c1f8b8c 100644 --- a/src/credential/plugin_rest_credential.c +++ b/src/credential/plugin_rest_credential.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach * @file credential/plugin_rest_credential.c @@ -62,15 +62,13 @@ /** * @brief struct returned by the initialization function of the plugin */ -struct Plugin -{ +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; }; const struct GNUNET_CONFIGURATION_Handle *cfg; -struct RequestHandle -{ +struct RequestHandle { /** * Handle to Credential service. */ @@ -155,7 +153,6 @@ struct RequestHandle * Timeout */ struct GNUNET_TIME_Relative timeout; - }; @@ -165,44 +162,44 @@ struct RequestHandle * @param handle Handle to clean up */ static void -cleanup_handle (struct RequestHandle *handle) +cleanup_handle(struct RequestHandle *handle) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Cleaning up\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Cleaning up\n"); if (NULL != handle->json_root) - json_decref (handle->json_root); + json_decref(handle->json_root); if (NULL != handle->issuer_attr) - GNUNET_free (handle->issuer_attr); + GNUNET_free(handle->issuer_attr); if (NULL != handle->subject_attr) - GNUNET_free (handle->subject_attr); + GNUNET_free(handle->subject_attr); if (NULL != handle->verify_request) - GNUNET_CREDENTIAL_request_cancel (handle->verify_request); + GNUNET_CREDENTIAL_request_cancel(handle->verify_request); if (NULL != handle->credential) - GNUNET_CREDENTIAL_disconnect (handle->credential); + GNUNET_CREDENTIAL_disconnect(handle->credential); if (NULL != handle->id_op) - GNUNET_IDENTITY_cancel (handle->id_op); + GNUNET_IDENTITY_cancel(handle->id_op); if (NULL != handle->ego_lookup) - GNUNET_IDENTITY_ego_lookup_cancel (handle->ego_lookup); + GNUNET_IDENTITY_ego_lookup_cancel(handle->ego_lookup); if (NULL != handle->identity) - GNUNET_IDENTITY_disconnect (handle->identity); + GNUNET_IDENTITY_disconnect(handle->identity); if (NULL != handle->timeout_task) - { - GNUNET_SCHEDULER_cancel (handle->timeout_task); - } - GNUNET_free (handle); + { + GNUNET_SCHEDULER_cancel(handle->timeout_task); + } + GNUNET_free(handle); } static void -do_error (void *cls) +do_error(void *cls) { struct RequestHandle *handle = cls; struct MHD_Response *resp; - resp = GNUNET_REST_create_response (NULL); - handle->proc (handle->proc_cls, resp, handle->response_code); - cleanup_handle (handle); + resp = GNUNET_REST_create_response(NULL); + handle->proc(handle->proc_cls, resp, handle->response_code); + cleanup_handle(handle); } /** @@ -212,41 +209,41 @@ do_error (void *cls) * @return JSON, NULL if failed */ static json_t* -attribute_delegation_to_json (struct GNUNET_CREDENTIAL_Delegation *delegation_chain_entry) +attribute_delegation_to_json(struct GNUNET_CREDENTIAL_Delegation *delegation_chain_entry) { char *subject; char *issuer; json_t *attr_obj; - issuer = GNUNET_CRYPTO_ecdsa_public_key_to_string (&delegation_chain_entry->issuer_key); + issuer = GNUNET_CRYPTO_ecdsa_public_key_to_string(&delegation_chain_entry->issuer_key); if (NULL == issuer) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Issuer in delegation malformed\n"); - return NULL; - } - subject = GNUNET_CRYPTO_ecdsa_public_key_to_string (&delegation_chain_entry->subject_key); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Issuer in delegation malformed\n"); + return NULL; + } + subject = GNUNET_CRYPTO_ecdsa_public_key_to_string(&delegation_chain_entry->subject_key); if (NULL == subject) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Subject in credential malformed\n"); - GNUNET_free (issuer); - return NULL; - } - attr_obj = json_object (); - - json_object_set_new (attr_obj, "issuer", json_string (issuer)); - json_object_set_new (attr_obj, "issuer_attribute", - json_string (delegation_chain_entry->issuer_attribute)); - - json_object_set_new (attr_obj, "subject", json_string (subject)); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Subject in credential malformed\n"); + GNUNET_free(issuer); + return NULL; + } + attr_obj = json_object(); + + json_object_set_new(attr_obj, "issuer", json_string(issuer)); + json_object_set_new(attr_obj, "issuer_attribute", + json_string(delegation_chain_entry->issuer_attribute)); + + json_object_set_new(attr_obj, "subject", json_string(subject)); if (0 < delegation_chain_entry->subject_attribute_len) - { - json_object_set_new (attr_obj, "subject_attribute", - json_string (delegation_chain_entry->subject_attribute)); - } - GNUNET_free (issuer); - GNUNET_free (subject); + { + json_object_set_new(attr_obj, "subject_attribute", + json_string(delegation_chain_entry->subject_attribute)); + } + GNUNET_free(issuer); + GNUNET_free(subject); return attr_obj; } @@ -257,7 +254,7 @@ attribute_delegation_to_json (struct GNUNET_CREDENTIAL_Delegation *delegation_ch * @return the resulting credential, NULL if failed */ static struct GNUNET_CREDENTIAL_Credential* -json_to_credential (json_t *res) +json_to_credential(json_t *res) { struct GNUNET_CREDENTIAL_Credential *cred; json_t *tmp; @@ -265,58 +262,58 @@ json_to_credential (json_t *res) const char *signature; char *sig; - tmp = json_object_get (res, "attribute"); - if (0 == json_is_string (tmp)) - { - return NULL; - } - attribute = json_string_value (tmp); - cred = GNUNET_malloc (sizeof (struct GNUNET_CREDENTIAL_Credential) - + strlen (attribute)); + tmp = json_object_get(res, "attribute"); + if (0 == json_is_string(tmp)) + { + return NULL; + } + attribute = json_string_value(tmp); + cred = GNUNET_malloc(sizeof(struct GNUNET_CREDENTIAL_Credential) + + strlen(attribute)); cred->issuer_attribute = attribute; - cred->issuer_attribute_len = strlen (attribute); - tmp = json_object_get (res, "issuer"); - if (0 == json_is_string (tmp)) - { - GNUNET_free (cred); - return NULL; - } - - GNUNET_CRYPTO_ecdsa_public_key_from_string (json_string_value(tmp), - strlen (json_string_value(tmp)), - &cred->issuer_key); - tmp = json_object_get (res, "subject"); - if (0 == json_is_string (tmp)) - { - GNUNET_free (cred); - return NULL; - } - GNUNET_CRYPTO_ecdsa_public_key_from_string (json_string_value(tmp), - strlen (json_string_value(tmp)), - &cred->subject_key); - - tmp = json_object_get (res, "signature"); - if (0 == json_is_string (tmp)) - { - GNUNET_free (cred); - return NULL; - } - signature = json_string_value (tmp); - GNUNET_STRINGS_base64_decode (signature, - strlen (signature), - (char**)&sig); - GNUNET_memcpy (&cred->signature, - sig, - sizeof (struct GNUNET_CRYPTO_EcdsaSignature)); - GNUNET_free (sig); - - tmp = json_object_get (res, "expiration"); - if (0 == json_is_integer (tmp)) - { - GNUNET_free (cred); - return NULL; - } - cred->expiration.abs_value_us = json_integer_value (tmp); + cred->issuer_attribute_len = strlen(attribute); + tmp = json_object_get(res, "issuer"); + if (0 == json_is_string(tmp)) + { + GNUNET_free(cred); + return NULL; + } + + GNUNET_CRYPTO_ecdsa_public_key_from_string(json_string_value(tmp), + strlen(json_string_value(tmp)), + &cred->issuer_key); + tmp = json_object_get(res, "subject"); + if (0 == json_is_string(tmp)) + { + GNUNET_free(cred); + return NULL; + } + GNUNET_CRYPTO_ecdsa_public_key_from_string(json_string_value(tmp), + strlen(json_string_value(tmp)), + &cred->subject_key); + + tmp = json_object_get(res, "signature"); + if (0 == json_is_string(tmp)) + { + GNUNET_free(cred); + return NULL; + } + signature = json_string_value(tmp); + GNUNET_STRINGS_base64_decode(signature, + strlen(signature), + (char**)&sig); + GNUNET_memcpy(&cred->signature, + sig, + sizeof(struct GNUNET_CRYPTO_EcdsaSignature)); + GNUNET_free(sig); + + tmp = json_object_get(res, "expiration"); + if (0 == json_is_integer(tmp)) + { + GNUNET_free(cred); + return NULL; + } + cred->expiration.abs_value_us = json_integer_value(tmp); return cred; } @@ -328,7 +325,7 @@ json_to_credential (json_t *res) * @return the resulting json, NULL if failed */ static json_t* -credential_to_json (struct GNUNET_CREDENTIAL_Credential *cred) +credential_to_json(struct GNUNET_CREDENTIAL_Credential *cred) { char *issuer; char *subject; @@ -336,42 +333,42 @@ credential_to_json (struct GNUNET_CREDENTIAL_Credential *cred) char attribute[cred->issuer_attribute_len + 1]; json_t *cred_obj; - issuer = GNUNET_CRYPTO_ecdsa_public_key_to_string (&cred->issuer_key); + issuer = GNUNET_CRYPTO_ecdsa_public_key_to_string(&cred->issuer_key); if (NULL == issuer) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Issuer in credential malformed\n"); - return NULL; - } - subject = GNUNET_CRYPTO_ecdsa_public_key_to_string (&cred->subject_key); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Issuer in credential malformed\n"); + return NULL; + } + subject = GNUNET_CRYPTO_ecdsa_public_key_to_string(&cred->subject_key); if (NULL == subject) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Subject in credential malformed\n"); - GNUNET_free (issuer); - return NULL; - } - GNUNET_STRINGS_base64_encode ((char*)&cred->signature, - sizeof (struct GNUNET_CRYPTO_EcdsaSignature), - &signature); - GNUNET_memcpy (attribute, - cred->issuer_attribute, - cred->issuer_attribute_len); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Subject in credential malformed\n"); + GNUNET_free(issuer); + return NULL; + } + GNUNET_STRINGS_base64_encode((char*)&cred->signature, + sizeof(struct GNUNET_CRYPTO_EcdsaSignature), + &signature); + GNUNET_memcpy(attribute, + cred->issuer_attribute, + cred->issuer_attribute_len); attribute[cred->issuer_attribute_len] = '\0'; - cred_obj = json_object (); - json_object_set_new (cred_obj, "issuer", json_string (issuer)); - json_object_set_new (cred_obj, "subject", json_string (subject)); - json_object_set_new (cred_obj, "attribute", json_string (attribute)); - json_object_set_new (cred_obj, "signature", json_string (signature)); - json_object_set_new (cred_obj, "expiration", json_integer (cred->expiration.abs_value_us)); - GNUNET_free (issuer); - GNUNET_free (subject); - GNUNET_free (signature); + cred_obj = json_object(); + json_object_set_new(cred_obj, "issuer", json_string(issuer)); + json_object_set_new(cred_obj, "subject", json_string(subject)); + json_object_set_new(cred_obj, "attribute", json_string(attribute)); + json_object_set_new(cred_obj, "signature", json_string(signature)); + json_object_set_new(cred_obj, "expiration", json_integer(cred->expiration.abs_value_us)); + GNUNET_free(issuer); + GNUNET_free(subject); + GNUNET_free(signature); return cred_obj; } static void -handle_collect_response (void *cls, +handle_collect_response(void *cls, unsigned int d_count, struct GNUNET_CREDENTIAL_Delegation *delegation_chain, unsigned int c_count, @@ -389,85 +386,86 @@ handle_collect_response (void *cls, uint32_t i; handle->verify_request = NULL; - if (NULL == cred) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Verify failed.\n"); - handle->response_code = MHD_HTTP_NOT_FOUND; - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - issuer = GNUNET_CRYPTO_ecdsa_public_key_to_string (&handle->issuer_key); + if (NULL == cred) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Verify failed.\n"); + handle->response_code = MHD_HTTP_NOT_FOUND; + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + issuer = GNUNET_CRYPTO_ecdsa_public_key_to_string(&handle->issuer_key); if (NULL == issuer) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Issuer in delegation malformed\n"); - return; - } - GNUNET_asprintf (&id, - "%s.%s", - issuer, - handle->issuer_attr); - GNUNET_free (issuer); - json_document = GNUNET_JSONAPI_document_new (); - json_resource = GNUNET_JSONAPI_resource_new (GNUNET_REST_JSONAPI_CREDENTIAL_TYPEINFO, - id); - GNUNET_free (id); - cred_array = json_array (); - for (i=0;iissuer_attr); + GNUNET_free(issuer); + json_document = GNUNET_JSONAPI_document_new(); + json_resource = GNUNET_JSONAPI_resource_new(GNUNET_REST_JSONAPI_CREDENTIAL_TYPEINFO, + id); + GNUNET_free(id); + cred_array = json_array(); + for (i = 0; i < c_count; i++) + { + cred_obj = credential_to_json(&cred[i]); + json_array_append_new(cred_array, cred_obj); + } + GNUNET_JSONAPI_resource_add_attr(json_resource, + GNUNET_REST_JSONAPI_CREDENTIAL, + cred_array); + GNUNET_JSONAPI_document_resource_add(json_document, json_resource); + GNUNET_JSONAPI_document_serialize(json_document, &result); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Result %s\n", + result); + json_decref(cred_array); + GNUNET_JSONAPI_document_delete(json_document); + resp = GNUNET_REST_create_response(result); GNUNET_free(result); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - cleanup_handle (handle); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + cleanup_handle(handle); } static void -subject_ego_lookup (void *cls, - const struct GNUNET_IDENTITY_Ego *ego) +subject_ego_lookup(void *cls, + const struct GNUNET_IDENTITY_Ego *ego) { struct RequestHandle *handle = cls; const struct GNUNET_CRYPTO_EcdsaPrivateKey *sub_key; + handle->ego_lookup = NULL; if (NULL == ego) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Subject not found\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - sub_key = GNUNET_IDENTITY_ego_get_private_key (ego); - handle->verify_request = GNUNET_CREDENTIAL_collect (handle->credential, - &handle->issuer_key, - handle->issuer_attr, - sub_key, - &handle_collect_response, - handle); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Subject not found\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + sub_key = GNUNET_IDENTITY_ego_get_private_key(ego); + handle->verify_request = GNUNET_CREDENTIAL_collect(handle->credential, + &handle->issuer_key, + handle->issuer_attr, + sub_key, + &handle_collect_response, + handle); } static void -handle_verify_response (void *cls, - unsigned int d_count, - struct GNUNET_CREDENTIAL_Delegation *delegation_chain, - unsigned int c_count, - struct GNUNET_CREDENTIAL_Credential *cred) +handle_verify_response(void *cls, + unsigned int d_count, + struct GNUNET_CREDENTIAL_Delegation *delegation_chain, + unsigned int c_count, + struct GNUNET_CREDENTIAL_Credential *cred) { - struct RequestHandle *handle = cls; struct MHD_Response *resp; struct GNUNET_JSONAPI_Document *json_document; @@ -482,165 +480,166 @@ handle_verify_response (void *cls, uint32_t i; handle->verify_request = NULL; - if (NULL == cred) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Verify failed.\n"); - handle->response_code = MHD_HTTP_NOT_FOUND; - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - issuer = GNUNET_CRYPTO_ecdsa_public_key_to_string (&handle->issuer_key); + if (NULL == cred) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Verify failed.\n"); + handle->response_code = MHD_HTTP_NOT_FOUND; + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + issuer = GNUNET_CRYPTO_ecdsa_public_key_to_string(&handle->issuer_key); if (NULL == issuer) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Issuer in delegation malformed\n"); - return; - } - GNUNET_asprintf (&id, - "%s.%s", - issuer, - handle->issuer_attr); - GNUNET_free (issuer); - json_document = GNUNET_JSONAPI_document_new (); - json_resource = GNUNET_JSONAPI_resource_new (GNUNET_REST_JSONAPI_CREDENTIAL_TYPEINFO, - id); - GNUNET_free (id); - attr_array = json_array (); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Issuer in delegation malformed\n"); + return; + } + GNUNET_asprintf(&id, + "%s.%s", + issuer, + handle->issuer_attr); + GNUNET_free(issuer); + json_document = GNUNET_JSONAPI_document_new(); + json_resource = GNUNET_JSONAPI_resource_new(GNUNET_REST_JSONAPI_CREDENTIAL_TYPEINFO, + id); + GNUNET_free(id); + attr_array = json_array(); for (i = 0; i < d_count; i++) - { - attr_obj = attribute_delegation_to_json (&delegation_chain[i]); - json_array_append_new (attr_array, attr_obj); - } - cred_array = json_array (); - for (i=0;iproc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_free (result); - cleanup_handle (handle); + { + attr_obj = attribute_delegation_to_json(&delegation_chain[i]); + json_array_append_new(attr_array, attr_obj); + } + cred_array = json_array(); + for (i = 0; i < c_count; i++) + { + cred_obj = credential_to_json(&cred[i]); + json_array_append_new(cred_array, cred_obj); + } + GNUNET_JSONAPI_resource_add_attr(json_resource, + GNUNET_REST_JSONAPI_CREDENTIAL, + cred_array); + GNUNET_JSONAPI_resource_add_attr(json_resource, + GNUNET_REST_JSONAPI_DELEGATIONS, + attr_array); + GNUNET_JSONAPI_document_resource_add(json_document, json_resource); + GNUNET_JSONAPI_document_serialize(json_document, &result); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Result %s\n", + result); + json_decref(attr_array); + json_decref(cred_array); + GNUNET_JSONAPI_document_delete(json_document); + resp = GNUNET_REST_create_response(result); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_free(result); + cleanup_handle(handle); } static void -collect_cred_cont (struct GNUNET_REST_RequestHandle *conndata_handle, - const char* url, - void *cls) +collect_cred_cont(struct GNUNET_REST_RequestHandle *conndata_handle, + const char* url, + void *cls) { struct RequestHandle *handle = cls; struct GNUNET_HashCode key; char *tmp; char *entity_attr; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connecting...\n"); - handle->credential = GNUNET_CREDENTIAL_connect (cfg); - handle->timeout_task = GNUNET_SCHEDULER_add_delayed (handle->timeout, - &do_error, handle); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connected\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connecting...\n"); + handle->credential = GNUNET_CREDENTIAL_connect(cfg); + handle->timeout_task = GNUNET_SCHEDULER_add_delayed(handle->timeout, + &do_error, handle); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connected\n"); if (NULL == handle->credential) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Connecting to CREDENTIAL failed\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_CREDENTIAL_ISSUER_ATTR, - strlen (GNUNET_REST_JSONAPI_CREDENTIAL_ISSUER_ATTR), - &key); - if ( GNUNET_NO == - GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map, - &key) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Missing issuer attribute\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - tmp = GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map, - &key); - entity_attr = GNUNET_strdup (tmp); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Connecting to CREDENTIAL failed\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + GNUNET_CRYPTO_hash(GNUNET_REST_JSONAPI_CREDENTIAL_ISSUER_ATTR, + strlen(GNUNET_REST_JSONAPI_CREDENTIAL_ISSUER_ATTR), + &key); + if (GNUNET_NO == + GNUNET_CONTAINER_multihashmap_contains(conndata_handle->url_param_map, + &key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Missing issuer attribute\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + tmp = GNUNET_CONTAINER_multihashmap_get(conndata_handle->url_param_map, + &key); + entity_attr = GNUNET_strdup(tmp); tmp = strtok(entity_attr, "."); if (NULL == tmp) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed issuer or attribute\n"); - GNUNET_free (entity_attr); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed issuer or attribute\n"); + GNUNET_free(entity_attr); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (tmp, - strlen (tmp), - &handle->issuer_key)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed issuer key\n"); - GNUNET_free (entity_attr); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - tmp = strtok (NULL, "."); //Issuer attribute + GNUNET_CRYPTO_ecdsa_public_key_from_string(tmp, + strlen(tmp), + &handle->issuer_key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed issuer key\n"); + GNUNET_free(entity_attr); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + tmp = strtok(NULL, "."); //Issuer attribute if (NULL == tmp) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed attribute\n"); - GNUNET_free (entity_attr); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - handle->issuer_attr = GNUNET_strdup (tmp); - GNUNET_free (entity_attr); - - GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_CREDENTIAL_SUBJECT_EGO, - strlen (GNUNET_REST_JSONAPI_CREDENTIAL_SUBJECT_EGO), - &key); - if ( GNUNET_NO == - GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map, - &key) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Missing subject\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - tmp = GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map, - &key); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed attribute\n"); + GNUNET_free(entity_attr); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + handle->issuer_attr = GNUNET_strdup(tmp); + GNUNET_free(entity_attr); + + GNUNET_CRYPTO_hash(GNUNET_REST_JSONAPI_CREDENTIAL_SUBJECT_EGO, + strlen(GNUNET_REST_JSONAPI_CREDENTIAL_SUBJECT_EGO), + &key); + if (GNUNET_NO == + GNUNET_CONTAINER_multihashmap_contains(conndata_handle->url_param_map, + &key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Missing subject\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + tmp = GNUNET_CONTAINER_multihashmap_get(conndata_handle->url_param_map, + &key); if (NULL == tmp) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed subject\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - handle->ego_lookup = GNUNET_IDENTITY_ego_lookup (cfg, - tmp, - &subject_ego_lookup, - handle); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed subject\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + handle->ego_lookup = GNUNET_IDENTITY_ego_lookup(cfg, + tmp, + &subject_ego_lookup, + handle); } static void -verify_cred_cont (struct GNUNET_REST_RequestHandle *conndata_handle, - const char* url, - void *cls) +verify_cred_cont(struct GNUNET_REST_RequestHandle *conndata_handle, + const char* url, + void *cls) { struct RequestHandle *handle = cls; struct GNUNET_HashCode key; @@ -656,186 +655,186 @@ verify_cred_cont (struct GNUNET_REST_RequestHandle *conndata_handle, json_t *data_js; json_error_t err; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connecting...\n"); - handle->credential = GNUNET_CREDENTIAL_connect (cfg); - handle->timeout_task = GNUNET_SCHEDULER_add_delayed (handle->timeout, - &do_error, handle); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connected\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connecting...\n"); + handle->credential = GNUNET_CREDENTIAL_connect(cfg); + handle->timeout_task = GNUNET_SCHEDULER_add_delayed(handle->timeout, + &do_error, handle); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connected\n"); if (NULL == handle->credential) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Connecting to CREDENTIAL failed\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_CREDENTIAL_ISSUER_ATTR, - strlen (GNUNET_REST_JSONAPI_CREDENTIAL_ISSUER_ATTR), - &key); - if ( GNUNET_NO == - GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map, - &key) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Missing issuer attribute\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - tmp = GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map, - &key); - entity_attr = GNUNET_strdup (tmp); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Connecting to CREDENTIAL failed\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + GNUNET_CRYPTO_hash(GNUNET_REST_JSONAPI_CREDENTIAL_ISSUER_ATTR, + strlen(GNUNET_REST_JSONAPI_CREDENTIAL_ISSUER_ATTR), + &key); + if (GNUNET_NO == + GNUNET_CONTAINER_multihashmap_contains(conndata_handle->url_param_map, + &key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Missing issuer attribute\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + tmp = GNUNET_CONTAINER_multihashmap_get(conndata_handle->url_param_map, + &key); + entity_attr = GNUNET_strdup(tmp); tmp = strtok(entity_attr, "."); if (NULL == tmp) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed issuer or attribute\n"); - GNUNET_free (entity_attr); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed issuer or attribute\n"); + GNUNET_free(entity_attr); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (tmp, - strlen (tmp), - &handle->issuer_key)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed issuer key\n"); - GNUNET_free (entity_attr); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - tmp = strtok (NULL, "."); //Issuer attribute + GNUNET_CRYPTO_ecdsa_public_key_from_string(tmp, + strlen(tmp), + &handle->issuer_key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed issuer key\n"); + GNUNET_free(entity_attr); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + tmp = strtok(NULL, "."); //Issuer attribute if (NULL == tmp) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed attribute\n"); - GNUNET_free (entity_attr); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - handle->issuer_attr = GNUNET_strdup (tmp); - GNUNET_free (entity_attr); - - GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_CREDENTIAL_SUBJECT_KEY, - strlen (GNUNET_REST_JSONAPI_CREDENTIAL_SUBJECT_KEY), - &key); - if ( GNUNET_NO == - GNUNET_CONTAINER_multihashmap_contains (conndata_handle->url_param_map, - &key) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Missing subject key\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - tmp = GNUNET_CONTAINER_multihashmap_get (conndata_handle->url_param_map, - &key); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed attribute\n"); + GNUNET_free(entity_attr); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + handle->issuer_attr = GNUNET_strdup(tmp); + GNUNET_free(entity_attr); + + GNUNET_CRYPTO_hash(GNUNET_REST_JSONAPI_CREDENTIAL_SUBJECT_KEY, + strlen(GNUNET_REST_JSONAPI_CREDENTIAL_SUBJECT_KEY), + &key); + if (GNUNET_NO == + GNUNET_CONTAINER_multihashmap_contains(conndata_handle->url_param_map, + &key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Missing subject key\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + tmp = GNUNET_CONTAINER_multihashmap_get(conndata_handle->url_param_map, + &key); if (NULL == tmp) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed subject\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed subject\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (tmp, - strlen (tmp), - &handle->subject_key)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed subject key\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + GNUNET_CRYPTO_ecdsa_public_key_from_string(tmp, + strlen(tmp), + &handle->subject_key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed subject key\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } if (0 >= handle->rest_handle->data_size) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Missing credentials\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Missing credentials\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } struct GNUNET_JSON_Specification docspec[] = { - GNUNET_JSON_spec_jsonapi_document (&json_obj), + GNUNET_JSON_spec_jsonapi_document(&json_obj), GNUNET_JSON_spec_end() }; - char term_data[handle->rest_handle->data_size+1]; + char term_data[handle->rest_handle->data_size + 1]; term_data[handle->rest_handle->data_size] = '\0'; credential_count = 0; - GNUNET_memcpy (term_data, - handle->rest_handle->data, - handle->rest_handle->data_size); - data_js = json_loads (term_data, - JSON_DECODE_ANY, - &err); - GNUNET_assert (GNUNET_OK == GNUNET_JSON_parse (data_js, docspec, - NULL, NULL)); - json_decref (data_js); + GNUNET_memcpy(term_data, + handle->rest_handle->data, + handle->rest_handle->data_size); + data_js = json_loads(term_data, + JSON_DECODE_ANY, + &err); + GNUNET_assert(GNUNET_OK == GNUNET_JSON_parse(data_js, docspec, + NULL, NULL)); + json_decref(data_js); if (NULL == json_obj) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse JSONAPI Object from %s\n", - term_data); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse JSONAPI Object from %s\n", + term_data); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } resource_count = GNUNET_JSONAPI_document_resource_count(json_obj); - GNUNET_assert (1 == resource_count); + GNUNET_assert(1 == resource_count); res = (GNUNET_JSONAPI_document_get_resource(json_obj, 0)); if (GNUNET_NO == GNUNET_JSONAPI_resource_check_type(res, GNUNET_REST_JSONAPI_CREDENTIAL_TYPEINFO)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Resource not a credential!\n"); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse JSONAPI Object from %s\n", - term_data); - GNUNET_JSONAPI_document_delete (json_obj); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - cred_json = GNUNET_JSONAPI_resource_read_attr (res, - GNUNET_REST_JSONAPI_CREDENTIAL); - - GNUNET_assert (json_is_array (cred_json)); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Resource not a credential!\n"); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse JSONAPI Object from %s\n", + term_data); + GNUNET_JSONAPI_document_delete(json_obj); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + cred_json = GNUNET_JSONAPI_resource_read_attr(res, + GNUNET_REST_JSONAPI_CREDENTIAL); + + GNUNET_assert(json_is_array(cred_json)); credential_count = json_array_size(cred_json); struct GNUNET_CREDENTIAL_Credential credentials[credential_count]; - for (i=0;iissuer_attribute); + GNUNET_free(cred); } - GNUNET_memcpy (&credentials[i], - cred, - sizeof (struct GNUNET_CREDENTIAL_Credential)); - credentials[i].issuer_attribute = GNUNET_strdup (cred->issuer_attribute); - GNUNET_free (cred); - } GNUNET_JSONAPI_document_delete(json_obj); - handle->verify_request = GNUNET_CREDENTIAL_verify (handle->credential, - &handle->issuer_key, - handle->issuer_attr, - &handle->subject_key, - credential_count, - credentials, - &handle_verify_response, - handle); - for (i=0;iverify_request = GNUNET_CREDENTIAL_verify(handle->credential, + &handle->issuer_key, + handle->issuer_attr, + &handle->subject_key, + credential_count, + credentials, + &handle_verify_response, + handle); + for (i = 0; i < credential_count; i++) + GNUNET_free((char*)credentials[i].issuer_attribute); } void -send_cred_response (struct RequestHandle *handle, - struct GNUNET_CREDENTIAL_Credential *cred) +send_cred_response(struct RequestHandle *handle, + struct GNUNET_CREDENTIAL_Credential *cred) { struct MHD_Response *resp; struct GNUNET_JSONAPI_Document *json_document; @@ -847,64 +846,64 @@ send_cred_response (struct RequestHandle *handle, char *signature; char *id; - GNUNET_assert (NULL != cred); - issuer = GNUNET_CRYPTO_ecdsa_public_key_to_string (&cred->issuer_key); + GNUNET_assert(NULL != cred); + issuer = GNUNET_CRYPTO_ecdsa_public_key_to_string(&cred->issuer_key); if (NULL == issuer) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Subject malformed\n"); - GNUNET_free (issuer); - return; - } - GNUNET_asprintf (&id, - "%s.%s", - issuer, - (char*)&cred[1]); - subject = GNUNET_CRYPTO_ecdsa_public_key_to_string (&cred->subject_key); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Subject malformed\n"); + GNUNET_free(issuer); + return; + } + GNUNET_asprintf(&id, + "%s.%s", + issuer, + (char*)&cred[1]); + subject = GNUNET_CRYPTO_ecdsa_public_key_to_string(&cred->subject_key); if (NULL == subject) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Subject malformed\n"); - GNUNET_free (id); - GNUNET_free (issuer); - return; - } - GNUNET_STRINGS_base64_encode ((char*)&cred->signature, - sizeof (struct GNUNET_CRYPTO_EcdsaSignature), - &signature); - json_document = GNUNET_JSONAPI_document_new (); - json_resource = GNUNET_JSONAPI_resource_new (GNUNET_REST_JSONAPI_CREDENTIAL_TYPEINFO, - id); - GNUNET_free (id); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Subject malformed\n"); + GNUNET_free(id); + GNUNET_free(issuer); + return; + } + GNUNET_STRINGS_base64_encode((char*)&cred->signature, + sizeof(struct GNUNET_CRYPTO_EcdsaSignature), + &signature); + json_document = GNUNET_JSONAPI_document_new(); + json_resource = GNUNET_JSONAPI_resource_new(GNUNET_REST_JSONAPI_CREDENTIAL_TYPEINFO, + id); + GNUNET_free(id); cred_obj = json_object(); - json_object_set_new (cred_obj, "issuer", json_string (issuer)); - json_object_set_new (cred_obj, "subject", json_string (subject)); - json_object_set_new (cred_obj, "expiration", json_integer( cred->expiration.abs_value_us)); - json_object_set_new (cred_obj, "signature", json_string (signature)); - GNUNET_JSONAPI_resource_add_attr (json_resource, - GNUNET_REST_JSONAPI_CREDENTIAL, - cred_obj); - GNUNET_JSONAPI_document_resource_add (json_document, json_resource); - GNUNET_JSONAPI_document_serialize (json_document, &result); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Result %s\n", - result); - json_decref (cred_obj); - GNUNET_JSONAPI_document_delete (json_document); - resp = GNUNET_REST_create_response (result); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_free (result); - GNUNET_free (signature); - GNUNET_free (issuer); - GNUNET_free (subject); - cleanup_handle (handle); + json_object_set_new(cred_obj, "issuer", json_string(issuer)); + json_object_set_new(cred_obj, "subject", json_string(subject)); + json_object_set_new(cred_obj, "expiration", json_integer(cred->expiration.abs_value_us)); + json_object_set_new(cred_obj, "signature", json_string(signature)); + GNUNET_JSONAPI_resource_add_attr(json_resource, + GNUNET_REST_JSONAPI_CREDENTIAL, + cred_obj); + GNUNET_JSONAPI_document_resource_add(json_document, json_resource); + GNUNET_JSONAPI_document_serialize(json_document, &result); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Result %s\n", + result); + json_decref(cred_obj); + GNUNET_JSONAPI_document_delete(json_document); + resp = GNUNET_REST_create_response(result); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_free(result); + GNUNET_free(signature); + GNUNET_free(issuer); + GNUNET_free(subject); + cleanup_handle(handle); } void -get_cred_issuer_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +get_cred_issuer_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { struct RequestHandle *handle = cls; struct GNUNET_TIME_Absolute etime_abs; @@ -918,156 +917,158 @@ get_cred_issuer_cb (void *cls, handle->id_op = NULL; if (NULL == name) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Issuer not configured!\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connecting to credential service...\n"); - handle->credential = GNUNET_CREDENTIAL_connect (cfg); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connected\n"); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Issuer not configured!\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connecting to credential service...\n"); + handle->credential = GNUNET_CREDENTIAL_connect(cfg); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connected\n"); if (NULL == handle->credential) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Connecting to CREDENTIAL failed\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_CREDENTIAL_EXPIRATION, - strlen (GNUNET_REST_JSONAPI_CREDENTIAL_EXPIRATION), - &key); - if ( GNUNET_NO == - GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle->url_param_map, - &key) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Missing expiration\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - expiration_str = GNUNET_CONTAINER_multihashmap_get (handle->rest_handle->url_param_map, - &key); - if ( NULL == expiration_str ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Expiration malformed\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - - if (GNUNET_OK == GNUNET_STRINGS_fancy_time_to_relative (expiration_str, - &etime_rel)) - { - etime_abs = GNUNET_TIME_relative_to_absolute (etime_rel); - } else if (GNUNET_OK != GNUNET_STRINGS_fancy_time_to_absolute (expiration_str, - &etime_abs)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed expiration: %s\n", expiration_str); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_CREDENTIAL_ISSUER_ATTR, - strlen (GNUNET_REST_JSONAPI_CREDENTIAL_ISSUER_ATTR), - &key); - if ( GNUNET_NO == - GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle->url_param_map, - &key) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Missing issuer attribute\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Connecting to CREDENTIAL failed\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + GNUNET_CRYPTO_hash(GNUNET_REST_JSONAPI_CREDENTIAL_EXPIRATION, + strlen(GNUNET_REST_JSONAPI_CREDENTIAL_EXPIRATION), + &key); + if (GNUNET_NO == + GNUNET_CONTAINER_multihashmap_contains(handle->rest_handle->url_param_map, + &key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Missing expiration\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + expiration_str = GNUNET_CONTAINER_multihashmap_get(handle->rest_handle->url_param_map, + &key); + if (NULL == expiration_str) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Expiration malformed\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + + if (GNUNET_OK == GNUNET_STRINGS_fancy_time_to_relative(expiration_str, + &etime_rel)) + { + etime_abs = GNUNET_TIME_relative_to_absolute(etime_rel); + } + else if (GNUNET_OK != GNUNET_STRINGS_fancy_time_to_absolute(expiration_str, + &etime_abs)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed expiration: %s\n", expiration_str); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + GNUNET_CRYPTO_hash(GNUNET_REST_JSONAPI_CREDENTIAL_ISSUER_ATTR, + strlen(GNUNET_REST_JSONAPI_CREDENTIAL_ISSUER_ATTR), + &key); + if (GNUNET_NO == + GNUNET_CONTAINER_multihashmap_contains(handle->rest_handle->url_param_map, + &key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Missing issuer attribute\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } handle->issuer_attr = GNUNET_strdup(GNUNET_CONTAINER_multihashmap_get - (handle->rest_handle->url_param_map, - &key)); - GNUNET_CRYPTO_hash (GNUNET_REST_JSONAPI_CREDENTIAL_SUBJECT_KEY, - strlen (GNUNET_REST_JSONAPI_CREDENTIAL_SUBJECT_KEY), - &key); - if ( GNUNET_NO == - GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle->url_param_map, - &key) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Missing subject\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - tmp = GNUNET_CONTAINER_multihashmap_get (handle->rest_handle->url_param_map, - &key); + (handle->rest_handle->url_param_map, + &key)); + GNUNET_CRYPTO_hash(GNUNET_REST_JSONAPI_CREDENTIAL_SUBJECT_KEY, + strlen(GNUNET_REST_JSONAPI_CREDENTIAL_SUBJECT_KEY), + &key); + if (GNUNET_NO == + GNUNET_CONTAINER_multihashmap_contains(handle->rest_handle->url_param_map, + &key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Missing subject\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + tmp = GNUNET_CONTAINER_multihashmap_get(handle->rest_handle->url_param_map, + &key); if (NULL == tmp) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed subject\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed subject\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (tmp, - strlen (tmp), - &handle->subject_key)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Malformed subject key\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - issuer_key = GNUNET_IDENTITY_ego_get_private_key (ego); - cred = GNUNET_CREDENTIAL_credential_issue (issuer_key, - &handle->subject_key, - handle->issuer_attr, - &etime_abs); + GNUNET_CRYPTO_ecdsa_public_key_from_string(tmp, + strlen(tmp), + &handle->subject_key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Malformed subject key\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + issuer_key = GNUNET_IDENTITY_ego_get_private_key(ego); + cred = GNUNET_CREDENTIAL_credential_issue(issuer_key, + &handle->subject_key, + handle->issuer_attr, + &etime_abs); if (NULL == cred) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create credential\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - send_cred_response (handle, cred); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create credential\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + send_cred_response(handle, cred); } static void -issue_cred_cont (struct GNUNET_REST_RequestHandle *conndata_handle, - const char* url, - void *cls) +issue_cred_cont(struct GNUNET_REST_RequestHandle *conndata_handle, + const char* url, + void *cls) { struct RequestHandle *handle = cls; - handle->identity = GNUNET_IDENTITY_connect (cfg, - NULL, - NULL); + handle->identity = GNUNET_IDENTITY_connect(cfg, + NULL, + NULL); handle->id_op = GNUNET_IDENTITY_get(handle->identity, "credential-issuer", &get_cred_issuer_cb, handle); - handle->timeout_task = GNUNET_SCHEDULER_add_delayed (handle->timeout, - &do_error, - handle); + handle->timeout_task = GNUNET_SCHEDULER_add_delayed(handle->timeout, + &do_error, + handle); } static void -options_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char* url, - void *cls) +options_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char* url, + void *cls) { struct MHD_Response *resp; struct RequestHandle *handle = cls; //For GNS, independent of path return all options - resp = GNUNET_REST_create_response (NULL); - MHD_add_response_header (resp, - "Access-Control-Allow-Methods", - MHD_HTTP_METHOD_GET); - handle->proc (handle->proc_cls, - resp, - MHD_HTTP_OK); - cleanup_handle (handle); + resp = GNUNET_REST_create_response(NULL); + MHD_add_response_header(resp, + "Access-Control-Allow-Methods", + MHD_HTTP_METHOD_GET); + handle->proc(handle->proc_cls, + resp, + MHD_HTTP_OK); + cleanup_handle(handle); } @@ -1076,7 +1077,7 @@ rest_credential_process_request(struct GNUNET_REST_RequestHandle *conndata_handl GNUNET_REST_ResultProcessor proc, void *proc_cls) { - struct RequestHandle *handle = GNUNET_new (struct RequestHandle); + struct RequestHandle *handle = GNUNET_new(struct RequestHandle); struct GNUNET_REST_RequestHandlerError err; handle->timeout = GNUNET_TIME_UNIT_FOREVER_REL; @@ -1085,21 +1086,21 @@ rest_credential_process_request(struct GNUNET_REST_RequestHandle *conndata_handl handle->rest_handle = conndata_handle; static const struct GNUNET_REST_RequestHandler handlers[] = { - {MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_CREDENTIAL_VERIFY, &verify_cred_cont}, - {MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_CREDENTIAL_COLLECT, &collect_cred_cont}, - {MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_CREDENTIAL_ISSUE, &issue_cred_cont}, - {MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_CREDENTIAL, &options_cont}, + { MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_CREDENTIAL_VERIFY, &verify_cred_cont }, + { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_CREDENTIAL_COLLECT, &collect_cred_cont }, + { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_CREDENTIAL_ISSUE, &issue_cred_cont }, + { MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_CREDENTIAL, &options_cont }, GNUNET_REST_HANDLER_END }; - if (GNUNET_NO == GNUNET_JSONAPI_handle_request (conndata_handle, - handlers, - &err, - handle)) - { - handle->response_code = err.error_code; - GNUNET_SCHEDULER_add_now (&do_error, handle); - } + if (GNUNET_NO == GNUNET_JSONAPI_handle_request(conndata_handle, + handlers, + &err, + handle)) + { + handle->response_code = err.error_code; + GNUNET_SCHEDULER_add_now(&do_error, handle); + } } @@ -1110,22 +1111,23 @@ rest_credential_process_request(struct GNUNET_REST_RequestHandle *conndata_handl * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_rest_credential_init (void *cls) +libgnunet_plugin_rest_credential_init(void *cls) { static struct Plugin plugin; + cfg = cls; struct GNUNET_REST_Plugin *api; if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.cfg = cfg; - api = GNUNET_new (struct GNUNET_REST_Plugin); + api = GNUNET_new(struct GNUNET_REST_Plugin); api->cls = &plugin; api->name = GNUNET_REST_API_NS_CREDENTIAL; api->process_request = &rest_credential_process_request; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("GNS REST API initialized\n")); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("GNS REST API initialized\n")); return api; } @@ -1137,15 +1139,15 @@ libgnunet_plugin_rest_credential_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_rest_credential_done (void *cls) +libgnunet_plugin_rest_credential_done(void *cls) { struct GNUNET_REST_Plugin *api = cls; struct Plugin *plugin = api->cls; plugin->cfg = NULL; - GNUNET_free (api); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "GNS REST plugin is finished\n"); + GNUNET_free(api); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "GNS REST plugin is finished\n"); return NULL; } diff --git a/src/curl/curl.c b/src/curl/curl.c index 38a1f5fcd..8e66ba4cb 100644 --- a/src/curl/curl.c +++ b/src/curl/curl.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2014, 2015, 2016, 2018 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2014, 2015, 2016, 2018 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file curl/curl.c * @brief API for downloading JSON via CURL @@ -40,23 +40,23 @@ * @param code what was the curl error code */ #define CURL_STRERROR(type, function, code) \ - GNUNET_log (type, \ - "Curl function `%s' has failed at `%s:%d' with error: %s\n", \ - function, \ - __FILE__, \ - __LINE__, \ - curl_easy_strerror (code)); + GNUNET_log(type, \ + "Curl function `%s' has failed at `%s:%d' with error: %s\n", \ + function, \ + __FILE__, \ + __LINE__, \ + curl_easy_strerror(code)); /** * Print JSON parsing related error information */ #define JSON_WARN(error) \ - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, \ - "JSON parsing failed at %s:%u: %s (%s)\n", \ - __FILE__, \ - __LINE__, \ - error.text, \ - error.source) + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, \ + "JSON parsing failed at %s:%u: %s (%s)\n", \ + __FILE__, \ + __LINE__, \ + error.text, \ + error.source) /** @@ -68,9 +68,7 @@ static int curl_fail; /** * Jobs are CURL requests running within a `struct GNUNET_CURL_Context`. */ -struct GNUNET_CURL_Job -{ - +struct GNUNET_CURL_Job { /** * We keep jobs in a DLL. */ @@ -117,8 +115,7 @@ struct GNUNET_CURL_Job /** * Context */ -struct GNUNET_CURL_Context -{ +struct GNUNET_CURL_Context { /** * Curl multi handle */ @@ -172,30 +169,30 @@ struct GNUNET_CURL_Context * @return library context */ struct GNUNET_CURL_Context * -GNUNET_CURL_init (GNUNET_CURL_RescheduleCallback cb, void *cb_cls) +GNUNET_CURL_init(GNUNET_CURL_RescheduleCallback cb, void *cb_cls) { struct GNUNET_CURL_Context *ctx; CURLM *multi; CURLSH *share; if (curl_fail) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Curl was not initialised properly\n"); - return NULL; - } - if (NULL == (multi = curl_multi_init ())) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create a Curl multi handle\n"); - return NULL; - } - if (NULL == (share = curl_share_init ())) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create a Curl share handle\n"); - return NULL; - } - ctx = GNUNET_new (struct GNUNET_CURL_Context); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Curl was not initialised properly\n"); + return NULL; + } + if (NULL == (multi = curl_multi_init())) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create a Curl multi handle\n"); + return NULL; + } + if (NULL == (share = curl_share_init())) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create a Curl share handle\n"); + return NULL; + } + ctx = GNUNET_new(struct GNUNET_CURL_Context); ctx->cb = cb; ctx->cb_cls = cb_cls; ctx->multi = multi; @@ -211,8 +208,8 @@ GNUNET_CURL_init (GNUNET_CURL_RescheduleCallback cb, void *cb_cls) * @param header_name name of the header to send. */ void -GNUNET_CURL_enable_async_scope_header (struct GNUNET_CURL_Context *ctx, - const char *header_name) +GNUNET_CURL_enable_async_scope_header(struct GNUNET_CURL_Context *ctx, + const char *header_name) { ctx->async_scope_id_header = header_name; } @@ -232,26 +229,26 @@ GNUNET_CURL_enable_async_scope_header (struct GNUNET_CURL_Context *ctx, * @return number of bytes processed from @a bufptr */ static size_t -download_cb (char *bufptr, size_t size, size_t nitems, void *cls) +download_cb(char *bufptr, size_t size, size_t nitems, void *cls) { struct GNUNET_CURL_DownloadBuffer *db = cls; size_t msize; void *buf; if (0 == size * nitems) - { - /* Nothing (left) to do */ - return 0; - } + { + /* Nothing (left) to do */ + return 0; + } msize = size * nitems; if ((msize + db->buf_size) >= GNUNET_MAX_MALLOC_CHECKED) - { - db->eno = ENOMEM; - return 0; /* signals an error to curl */ - } - db->buf = GNUNET_realloc (db->buf, db->buf_size + msize); + { + db->eno = ENOMEM; + return 0; /* signals an error to curl */ + } + db->buf = GNUNET_realloc(db->buf, db->buf_size + msize); buf = db->buf + db->buf_size; - GNUNET_memcpy (buf, bufptr, msize); + GNUNET_memcpy(buf, bufptr, msize); db->buf_size += msize; return msize; } @@ -277,77 +274,77 @@ download_cb (char *bufptr, size_t size, size_t nitems, void *cls) * @return NULL on error (in this case, @eh is still released!) */ struct GNUNET_CURL_Job * -GNUNET_CURL_job_add2 (struct GNUNET_CURL_Context *ctx, - CURL *eh, - const struct curl_slist *job_headers, - GNUNET_CURL_JobCompletionCallback jcc, - void *jcc_cls) +GNUNET_CURL_job_add2(struct GNUNET_CURL_Context *ctx, + CURL *eh, + const struct curl_slist *job_headers, + GNUNET_CURL_JobCompletionCallback jcc, + void *jcc_cls) { struct GNUNET_CURL_Job *job; struct curl_slist *all_headers = NULL; for (const struct curl_slist *curr = job_headers; curr != NULL; curr = curr->next) - { - GNUNET_assert (NULL != - (all_headers = curl_slist_append (all_headers, curr->data))); - } + { + GNUNET_assert(NULL != + (all_headers = curl_slist_append(all_headers, curr->data))); + } for (const struct curl_slist *curr = ctx->common_headers; curr != NULL; curr = curr->next) - { - GNUNET_assert (NULL != - (all_headers = curl_slist_append (all_headers, curr->data))); - } + { + GNUNET_assert(NULL != + (all_headers = curl_slist_append(all_headers, curr->data))); + } if (NULL != ctx->async_scope_id_header) - { - struct GNUNET_AsyncScopeSave scope; - - GNUNET_async_scope_get (&scope); - if (GNUNET_YES == scope.have_scope) { - char *aid_header = NULL; - aid_header = - GNUNET_STRINGS_data_to_string_alloc (&scope.scope_id, - sizeof ( - struct GNUNET_AsyncScopeId)); - GNUNET_assert (NULL != aid_header); - GNUNET_assert (NULL != curl_slist_append (all_headers, aid_header)); - GNUNET_free (aid_header); + struct GNUNET_AsyncScopeSave scope; + + GNUNET_async_scope_get(&scope); + if (GNUNET_YES == scope.have_scope) + { + char *aid_header = NULL; + aid_header = + GNUNET_STRINGS_data_to_string_alloc(&scope.scope_id, + sizeof( + struct GNUNET_AsyncScopeId)); + GNUNET_assert(NULL != aid_header); + GNUNET_assert(NULL != curl_slist_append(all_headers, aid_header)); + GNUNET_free(aid_header); + } } - } - if (CURLE_OK != curl_easy_setopt (eh, CURLOPT_HTTPHEADER, all_headers)) - { - GNUNET_break (0); - curl_slist_free_all (all_headers); - curl_easy_cleanup (eh); - return NULL; - } + if (CURLE_OK != curl_easy_setopt(eh, CURLOPT_HTTPHEADER, all_headers)) + { + GNUNET_break(0); + curl_slist_free_all(all_headers); + curl_easy_cleanup(eh); + return NULL; + } - job = GNUNET_new (struct GNUNET_CURL_Job); + job = GNUNET_new(struct GNUNET_CURL_Job); job->job_headers = all_headers; - if ((CURLE_OK != curl_easy_setopt (eh, CURLOPT_PRIVATE, job)) || + if ((CURLE_OK != curl_easy_setopt(eh, CURLOPT_PRIVATE, job)) || (CURLE_OK != - curl_easy_setopt (eh, CURLOPT_WRITEFUNCTION, &download_cb)) || - (CURLE_OK != curl_easy_setopt (eh, CURLOPT_WRITEDATA, &job->db)) || - (CURLE_OK != curl_easy_setopt (eh, CURLOPT_SHARE, ctx->share)) || - (CURLM_OK != curl_multi_add_handle (ctx->multi, eh))) - { - GNUNET_break (0); - GNUNET_free (job); - curl_easy_cleanup (eh); - return NULL; - } + curl_easy_setopt(eh, CURLOPT_WRITEFUNCTION, &download_cb)) || + (CURLE_OK != curl_easy_setopt(eh, CURLOPT_WRITEDATA, &job->db)) || + (CURLE_OK != curl_easy_setopt(eh, CURLOPT_SHARE, ctx->share)) || + (CURLM_OK != curl_multi_add_handle(ctx->multi, eh))) + { + GNUNET_break(0); + GNUNET_free(job); + curl_easy_cleanup(eh); + return NULL; + } job->easy_handle = eh; job->ctx = ctx; job->jcc = jcc; job->jcc_cls = jcc_cls; - GNUNET_CONTAINER_DLL_insert (ctx->jobs_head, ctx->jobs_tail, job); - ctx->cb (ctx->cb_cls); + GNUNET_CONTAINER_DLL_insert(ctx->jobs_head, ctx->jobs_tail, job); + ctx->cb(ctx->cb_cls); return job; } @@ -369,24 +366,24 @@ GNUNET_CURL_job_add2 (struct GNUNET_CURL_Context *ctx, * @return NULL on error (in this case, @eh is still released!) */ struct GNUNET_CURL_Job * -GNUNET_CURL_job_add (struct GNUNET_CURL_Context *ctx, - CURL *eh, - int add_json, - GNUNET_CURL_JobCompletionCallback jcc, - void *jcc_cls) +GNUNET_CURL_job_add(struct GNUNET_CURL_Context *ctx, + CURL *eh, + int add_json, + GNUNET_CURL_JobCompletionCallback jcc, + void *jcc_cls) { struct GNUNET_CURL_Job *job; struct curl_slist *job_headers = NULL; if (GNUNET_YES == add_json) - { - GNUNET_assert ( - NULL != (job_headers = - curl_slist_append (NULL, "Content-Type: application/json"))); - } - - job = GNUNET_CURL_job_add2 (ctx, eh, job_headers, jcc, jcc_cls); - curl_slist_free_all (job_headers); + { + GNUNET_assert( + NULL != (job_headers = + curl_slist_append(NULL, "Content-Type: application/json"))); + } + + job = GNUNET_CURL_job_add2(ctx, eh, job_headers, jcc, jcc_cls); + curl_slist_free_all(job_headers); return job; } @@ -398,17 +395,17 @@ GNUNET_CURL_job_add (struct GNUNET_CURL_Context *ctx, * @param job job to cancel */ void -GNUNET_CURL_job_cancel (struct GNUNET_CURL_Job *job) +GNUNET_CURL_job_cancel(struct GNUNET_CURL_Job *job) { struct GNUNET_CURL_Context *ctx = job->ctx; - GNUNET_CONTAINER_DLL_remove (ctx->jobs_head, ctx->jobs_tail, job); - GNUNET_break (CURLM_OK == - curl_multi_remove_handle (ctx->multi, job->easy_handle)); - curl_easy_cleanup (job->easy_handle); - GNUNET_free_non_null (job->db.buf); - curl_slist_free_all (job->job_headers); - GNUNET_free (job); + GNUNET_CONTAINER_DLL_remove(ctx->jobs_head, ctx->jobs_tail, job); + GNUNET_break(CURLM_OK == + curl_multi_remove_handle(ctx->multi, job->easy_handle)); + curl_easy_cleanup(job->easy_handle); + GNUNET_free_non_null(job->db.buf); + curl_slist_free_all(job->job_headers); + GNUNET_free(job); } @@ -431,62 +428,62 @@ GNUNET_CURL_job_cancel (struct GNUNET_CURL_Job *job) * @return NULL if downloading a JSON reply failed. */ void * -GNUNET_CURL_download_get_result_ (struct GNUNET_CURL_DownloadBuffer *db, - CURL *eh, - long *response_code) +GNUNET_CURL_download_get_result_(struct GNUNET_CURL_DownloadBuffer *db, + CURL *eh, + long *response_code) { json_t *json; json_error_t error; char *ct; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Downloaded body: %.*s\n", - (int) db->buf_size, - (char *) db->buf); - - if ((CURLE_OK != curl_easy_getinfo (eh, CURLINFO_CONTENT_TYPE, &ct)) || - (NULL == ct) || (0 != strcasecmp (ct, "application/json"))) - { - /* No content type or explicitly not JSON, refuse to parse - (but keep response code) */ - if (CURLE_OK != - curl_easy_getinfo (eh, CURLINFO_RESPONSE_CODE, response_code)) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Downloaded body: %.*s\n", + (int)db->buf_size, + (char *)db->buf); + + if ((CURLE_OK != curl_easy_getinfo(eh, CURLINFO_CONTENT_TYPE, &ct)) || + (NULL == ct) || (0 != strcasecmp(ct, "application/json"))) { - /* unexpected error... */ - GNUNET_break (0); - *response_code = 0; + /* No content type or explicitly not JSON, refuse to parse + (but keep response code) */ + if (CURLE_OK != + curl_easy_getinfo(eh, CURLINFO_RESPONSE_CODE, response_code)) + { + /* unexpected error... */ + GNUNET_break(0); + *response_code = 0; + } + if (0 != db->buf_size) + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Did NOT detect response as JSON\n"); + return NULL; } - if (0 != db->buf_size) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Did NOT detect response as JSON\n"); - return NULL; - } json = NULL; if (0 == db->eno) - { - json = json_loadb (db->buf, - db->buf_size, - JSON_REJECT_DUPLICATES | JSON_DISABLE_EOF_CHECK, - &error); - if (NULL == json) { - JSON_WARN (error); - *response_code = 0; + json = json_loadb(db->buf, + db->buf_size, + JSON_REJECT_DUPLICATES | JSON_DISABLE_EOF_CHECK, + &error); + if (NULL == json) + { + JSON_WARN(error); + *response_code = 0; + } } - } - GNUNET_free_non_null (db->buf); + GNUNET_free_non_null(db->buf); db->buf = NULL; db->buf_size = 0; if (NULL != json) - { - if (CURLE_OK != - curl_easy_getinfo (eh, CURLINFO_RESPONSE_CODE, response_code)) { - /* unexpected error... */ - GNUNET_break (0); - *response_code = 0; + if (CURLE_OK != + curl_easy_getinfo(eh, CURLINFO_RESPONSE_CODE, response_code)) + { + /* unexpected error... */ + GNUNET_break(0); + *response_code = 0; + } } - } return json; } @@ -499,9 +496,9 @@ GNUNET_CURL_download_get_result_ (struct GNUNET_CURL_DownloadBuffer *db, * @return #GNUNET_OK if no errors occurred, #GNUNET_SYSERR otherwise. */ int -GNUNET_CURL_append_header (struct GNUNET_CURL_Context *ctx, const char *header) +GNUNET_CURL_append_header(struct GNUNET_CURL_Context *ctx, const char *header) { - ctx->common_headers = curl_slist_append (ctx->common_headers, header); + ctx->common_headers = curl_slist_append(ctx->common_headers, header); if (NULL == ctx->common_headers) return GNUNET_SYSERR; @@ -518,98 +515,98 @@ GNUNET_CURL_append_header (struct GNUNET_CURL_Context *ctx, const char *header) * @param rc cleans/frees the response */ void -GNUNET_CURL_perform2 (struct GNUNET_CURL_Context *ctx, - GNUNET_CURL_RawParser rp, - GNUNET_CURL_ResponseCleaner rc) +GNUNET_CURL_perform2(struct GNUNET_CURL_Context *ctx, + GNUNET_CURL_RawParser rp, + GNUNET_CURL_ResponseCleaner rc) { CURLMsg *cmsg; int n_running; int n_completed; - (void) curl_multi_perform (ctx->multi, &n_running); - while (NULL != (cmsg = curl_multi_info_read (ctx->multi, &n_completed))) - { - struct GNUNET_CURL_Job *job; - long response_code; - void *response; + (void)curl_multi_perform(ctx->multi, &n_running); + while (NULL != (cmsg = curl_multi_info_read(ctx->multi, &n_completed))) + { + struct GNUNET_CURL_Job *job; + long response_code; + void *response; - /* Only documented return value is CURLMSG_DONE */ - GNUNET_break (CURLMSG_DONE == cmsg->msg); - GNUNET_assert (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle, + /* Only documented return value is CURLMSG_DONE */ + GNUNET_break(CURLMSG_DONE == cmsg->msg); + GNUNET_assert(CURLE_OK == curl_easy_getinfo(cmsg->easy_handle, CURLINFO_PRIVATE, - (char **) &job)); - GNUNET_assert (job->ctx == ctx); - response_code = 0; - response = rp (&job->db, job->easy_handle, &response_code); + (char **)&job)); + GNUNET_assert(job->ctx == ctx); + response_code = 0; + response = rp(&job->db, job->easy_handle, &response_code); #if ENABLE_BENCHMARK - { - char *url = NULL; - double total_as_double = 0; - struct GNUNET_TIME_Relative total; - struct UrlRequestData *urd; - /* Some care required, as curl is using data types (long vs curl_off_t vs - * double) inconsistently to store byte count. */ - curl_off_t size_curl = 0; - long size_long = 0; - uint64_t bytes_sent = 0; - uint64_t bytes_received = 0; - - GNUNET_break (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle, + { + char *url = NULL; + double total_as_double = 0; + struct GNUNET_TIME_Relative total; + struct UrlRequestData *urd; + /* Some care required, as curl is using data types (long vs curl_off_t vs + * double) inconsistently to store byte count. */ + curl_off_t size_curl = 0; + long size_long = 0; + uint64_t bytes_sent = 0; + uint64_t bytes_received = 0; + + GNUNET_break(CURLE_OK == curl_easy_getinfo(cmsg->easy_handle, CURLINFO_TOTAL_TIME, &total_as_double)); - total.rel_value_us = total_as_double * 1000 * 1000; + total.rel_value_us = total_as_double * 1000 * 1000; - GNUNET_break (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle, + GNUNET_break(CURLE_OK == curl_easy_getinfo(cmsg->easy_handle, CURLINFO_EFFECTIVE_URL, &url)); - /* HEADER_SIZE + SIZE_DOWNLOAD_T is hopefully the total - number of bytes received, not clear from curl docs. */ + /* HEADER_SIZE + SIZE_DOWNLOAD_T is hopefully the total + number of bytes received, not clear from curl docs. */ - GNUNET_break (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle, + GNUNET_break(CURLE_OK == curl_easy_getinfo(cmsg->easy_handle, CURLINFO_HEADER_SIZE, &size_long)); - bytes_received += size_long; + bytes_received += size_long; - GNUNET_break (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle, + GNUNET_break(CURLE_OK == curl_easy_getinfo(cmsg->easy_handle, CURLINFO_SIZE_DOWNLOAD_T, &size_curl)); - bytes_received += size_curl; + bytes_received += size_curl; - /* REQUEST_SIZE + SIZE_UPLOAD_T is hopefully the total number of bytes - sent, again docs are not completely clear. */ + /* REQUEST_SIZE + SIZE_UPLOAD_T is hopefully the total number of bytes + sent, again docs are not completely clear. */ - GNUNET_break (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle, + GNUNET_break(CURLE_OK == curl_easy_getinfo(cmsg->easy_handle, CURLINFO_REQUEST_SIZE, &size_long)); - bytes_sent += size_long; + bytes_sent += size_long; - /* We obtain this value to check an invariant, but never use it otherwise. */ - GNUNET_break (CURLE_OK == curl_easy_getinfo (cmsg->easy_handle, + /* We obtain this value to check an invariant, but never use it otherwise. */ + GNUNET_break(CURLE_OK == curl_easy_getinfo(cmsg->easy_handle, CURLINFO_SIZE_UPLOAD_T, &size_curl)); - /* CURLINFO_SIZE_UPLOAD_T <= CURLINFO_REQUEST_SIZE should - be an invariant. - As verified with - curl -w "foo%{size_request} -XPOST --data "ABC" $URL - the CURLINFO_REQUEST_SIZE should be the whole size of the request - including headers and body. - */ - GNUNET_break (size_curl <= size_long); - - urd = get_url_benchmark_data (url, (unsigned int) response_code); - urd->count++; - urd->time = GNUNET_TIME_relative_add (urd->time, total); - urd->time_max = GNUNET_TIME_relative_max (total, urd->time_max); - urd->bytes_sent += bytes_sent; - urd->bytes_received += bytes_received; - } + /* CURLINFO_SIZE_UPLOAD_T <= CURLINFO_REQUEST_SIZE should + be an invariant. + As verified with + curl -w "foo%{size_request} -XPOST --data "ABC" $URL + the CURLINFO_REQUEST_SIZE should be the whole size of the request + including headers and body. + */ + GNUNET_break(size_curl <= size_long); + + urd = get_url_benchmark_data(url, (unsigned int)response_code); + urd->count++; + urd->time = GNUNET_TIME_relative_add(urd->time, total); + urd->time_max = GNUNET_TIME_relative_max(total, urd->time_max); + urd->bytes_sent += bytes_sent; + urd->bytes_received += bytes_received; + } #endif - job->jcc (job->jcc_cls, response_code, response); - rc (response); - GNUNET_CURL_job_cancel (job); - } + job->jcc(job->jcc_cls, response_code, response); + rc(response); + GNUNET_CURL_job_cancel(job); + } } @@ -619,11 +616,11 @@ GNUNET_CURL_perform2 (struct GNUNET_CURL_Context *ctx, * @param ctx the library context */ void -GNUNET_CURL_perform (struct GNUNET_CURL_Context *ctx) +GNUNET_CURL_perform(struct GNUNET_CURL_Context *ctx) { - GNUNET_CURL_perform2 (ctx, - &GNUNET_CURL_download_get_result_, - (GNUNET_CURL_ResponseCleaner) &json_decref); + GNUNET_CURL_perform2(ctx, + &GNUNET_CURL_download_get_result_, + (GNUNET_CURL_ResponseCleaner) & json_decref); } @@ -656,25 +653,25 @@ GNUNET_CURL_perform (struct GNUNET_CURL_Context *ctx) * proceed immediately with #GNUNET_CURL_perform(). */ void -GNUNET_CURL_get_select_info (struct GNUNET_CURL_Context *ctx, - fd_set *read_fd_set, - fd_set *write_fd_set, - fd_set *except_fd_set, - int *max_fd, - long *timeout) +GNUNET_CURL_get_select_info(struct GNUNET_CURL_Context *ctx, + fd_set *read_fd_set, + fd_set *write_fd_set, + fd_set *except_fd_set, + int *max_fd, + long *timeout) { long to; int m; m = -1; - GNUNET_assert (CURLM_OK == curl_multi_fdset (ctx->multi, - read_fd_set, - write_fd_set, - except_fd_set, - &m)); + GNUNET_assert(CURLM_OK == curl_multi_fdset(ctx->multi, + read_fd_set, + write_fd_set, + except_fd_set, + &m)); to = *timeout; - *max_fd = GNUNET_MAX (m, *max_fd); - GNUNET_assert (CURLM_OK == curl_multi_timeout (ctx->multi, &to)); + *max_fd = GNUNET_MAX(m, *max_fd); + GNUNET_assert(CURLM_OK == curl_multi_timeout(ctx->multi, &to)); /* Only if what we got back from curl is smaller than what we already had (-1 == infinity!), then update timeout */ @@ -693,14 +690,14 @@ GNUNET_CURL_get_select_info (struct GNUNET_CURL_Context *ctx, * @param ctx the library context */ void -GNUNET_CURL_fini (struct GNUNET_CURL_Context *ctx) +GNUNET_CURL_fini(struct GNUNET_CURL_Context *ctx) { /* all jobs must have been cancelled at this time, assert this */ - GNUNET_assert (NULL == ctx->jobs_head); - curl_share_cleanup (ctx->share); - curl_multi_cleanup (ctx->multi); - curl_slist_free_all (ctx->common_headers); - GNUNET_free (ctx); + GNUNET_assert(NULL == ctx->jobs_head); + curl_share_cleanup(ctx->share); + curl_multi_cleanup(ctx->multi); + curl_slist_free_all(ctx->common_headers); + GNUNET_free(ctx); } @@ -708,15 +705,15 @@ GNUNET_CURL_fini (struct GNUNET_CURL_Context *ctx) * Initial global setup logic, specifically runs the Curl setup. */ __attribute__ ((constructor)) void -GNUNET_CURL_constructor__ (void) +GNUNET_CURL_constructor__(void) { CURLcode ret; - if (CURLE_OK != (ret = curl_global_init (CURL_GLOBAL_DEFAULT))) - { - CURL_STRERROR (GNUNET_ERROR_TYPE_ERROR, "curl_global_init", ret); - curl_fail = 1; - } + if (CURLE_OK != (ret = curl_global_init(CURL_GLOBAL_DEFAULT))) + { + CURL_STRERROR(GNUNET_ERROR_TYPE_ERROR, "curl_global_init", ret); + curl_fail = 1; + } } @@ -724,11 +721,11 @@ GNUNET_CURL_constructor__ (void) * Cleans up after us, specifically runs the Curl cleanup. */ __attribute__ ((destructor)) void -GNUNET_CURL_destructor__ (void) +GNUNET_CURL_destructor__(void) { if (curl_fail) return; - curl_global_cleanup (); + curl_global_cleanup(); } /* end of curl.c */ diff --git a/src/curl/curl_reschedule.c b/src/curl/curl_reschedule.c index 354ba13df..0fdaa5e1f 100644 --- a/src/curl/curl_reschedule.c +++ b/src/curl/curl_reschedule.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2015, 2016 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet + Copyright (C) 2015, 2016 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file curl/curl_reschedule.c * @brief API for event loop integration with GNUnet SCHEDULER. @@ -28,15 +28,14 @@ #include "gnunet_util_lib.h" extern void * -GNUNET_CURL_download_get_result_ (struct GNUNET_CURL_DownloadBuffer *db, - CURL *eh, - long *response_code); +GNUNET_CURL_download_get_result_(struct GNUNET_CURL_DownloadBuffer *db, + CURL *eh, + long *response_code); /** * Closure for #GNUNET_CURL_gnunet_scheduler_reschedule(). */ -struct GNUNET_CURL_RescheduleContext -{ +struct GNUNET_CURL_RescheduleContext { /** * Just the task. */ @@ -66,13 +65,13 @@ struct GNUNET_CURL_RescheduleContext * @return closure for #GNUNET_CURL_gnunet_scheduler_reschedule(). */ struct GNUNET_CURL_RescheduleContext * -GNUNET_CURL_gnunet_rc_create_with_parser (struct GNUNET_CURL_Context *ctx, - GNUNET_CURL_RawParser rp, - GNUNET_CURL_ResponseCleaner rc) +GNUNET_CURL_gnunet_rc_create_with_parser(struct GNUNET_CURL_Context *ctx, + GNUNET_CURL_RawParser rp, + GNUNET_CURL_ResponseCleaner rc) { struct GNUNET_CURL_RescheduleContext *rctx; - rctx = GNUNET_new (struct GNUNET_CURL_RescheduleContext); + rctx = GNUNET_new(struct GNUNET_CURL_RescheduleContext); rctx->ctx = ctx; rctx->parser = rp; rctx->cleaner = rc; @@ -87,9 +86,9 @@ GNUNET_CURL_gnunet_rc_create_with_parser (struct GNUNET_CURL_Context *ctx, * @param response the (JSON) response to clean. */ static void -clean_result (void *response) +clean_result(void *response) { - json_decref (response); + json_decref(response); } /** @@ -99,11 +98,11 @@ clean_result (void *response) * @return closure for #GNUNET_CURL_gnunet_scheduler_reschedule(). */ struct GNUNET_CURL_RescheduleContext * -GNUNET_CURL_gnunet_rc_create (struct GNUNET_CURL_Context *ctx) +GNUNET_CURL_gnunet_rc_create(struct GNUNET_CURL_Context *ctx) { struct GNUNET_CURL_RescheduleContext *rc; - rc = GNUNET_new (struct GNUNET_CURL_RescheduleContext); + rc = GNUNET_new(struct GNUNET_CURL_RescheduleContext); rc->ctx = ctx; rc->parser = &GNUNET_CURL_download_get_result_; rc->cleaner = &clean_result; @@ -117,11 +116,11 @@ GNUNET_CURL_gnunet_rc_create (struct GNUNET_CURL_Context *ctx) * @param rc context to destroy */ void -GNUNET_CURL_gnunet_rc_destroy (struct GNUNET_CURL_RescheduleContext *rc) +GNUNET_CURL_gnunet_rc_destroy(struct GNUNET_CURL_RescheduleContext *rc) { if (NULL != rc->task) - GNUNET_SCHEDULER_cancel (rc->task); - GNUNET_free (rc); + GNUNET_SCHEDULER_cancel(rc->task); + GNUNET_free(rc); } @@ -131,7 +130,7 @@ GNUNET_CURL_gnunet_rc_destroy (struct GNUNET_CURL_RescheduleContext *rc) * @param cls a `struct GNUNET_CURL_RescheduleContext *` */ static void -context_task (void *cls) +context_task(void *cls) { struct GNUNET_CURL_RescheduleContext *rc = cls; long timeout; @@ -145,36 +144,36 @@ context_task (void *cls) rc->task = NULL; - GNUNET_CURL_perform2 (rc->ctx, rc->parser, rc->cleaner); + GNUNET_CURL_perform2(rc->ctx, rc->parser, rc->cleaner); max_fd = -1; timeout = -1; - FD_ZERO (&read_fd_set); - FD_ZERO (&write_fd_set); - FD_ZERO (&except_fd_set); - GNUNET_CURL_get_select_info (rc->ctx, - &read_fd_set, - &write_fd_set, - &except_fd_set, - &max_fd, - &timeout); + FD_ZERO(&read_fd_set); + FD_ZERO(&write_fd_set); + FD_ZERO(&except_fd_set); + GNUNET_CURL_get_select_info(rc->ctx, + &read_fd_set, + &write_fd_set, + &except_fd_set, + &max_fd, + &timeout); if (timeout >= 0) delay = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, timeout); + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, timeout); else delay = GNUNET_TIME_UNIT_FOREVER_REL; - rs = GNUNET_NETWORK_fdset_create (); - GNUNET_NETWORK_fdset_copy_native (rs, &read_fd_set, max_fd + 1); - ws = GNUNET_NETWORK_fdset_create (); - GNUNET_NETWORK_fdset_copy_native (ws, &write_fd_set, max_fd + 1); + rs = GNUNET_NETWORK_fdset_create(); + GNUNET_NETWORK_fdset_copy_native(rs, &read_fd_set, max_fd + 1); + ws = GNUNET_NETWORK_fdset_create(); + GNUNET_NETWORK_fdset_copy_native(ws, &write_fd_set, max_fd + 1); if (NULL == rc->task) - rc->task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, - delay, - rs, - ws, - &context_task, - rc); - GNUNET_NETWORK_fdset_destroy (rs); - GNUNET_NETWORK_fdset_destroy (ws); + rc->task = GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT, + delay, + rs, + ws, + &context_task, + rc); + GNUNET_NETWORK_fdset_destroy(rs); + GNUNET_NETWORK_fdset_destroy(ws); } @@ -188,13 +187,13 @@ context_task (void *cls) * (pointer to a pointer!) */ void -GNUNET_CURL_gnunet_scheduler_reschedule (void *cls) +GNUNET_CURL_gnunet_scheduler_reschedule(void *cls) { - struct GNUNET_CURL_RescheduleContext *rc = *(void **) cls; + struct GNUNET_CURL_RescheduleContext *rc = *(void **)cls; if (NULL != rc->task) - GNUNET_SCHEDULER_cancel (rc->task); - rc->task = GNUNET_SCHEDULER_add_now (&context_task, rc); + GNUNET_SCHEDULER_cancel(rc->task); + rc->task = GNUNET_SCHEDULER_add_now(&context_task, rc); } /* end of curl_reschedule.c */ diff --git a/src/datacache/datacache.c b/src/datacache/datacache.c index 57e0b0bb7..52c755a49 100644 --- a/src/datacache/datacache.c +++ b/src/datacache/datacache.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datacache/datacache.c * @brief datacache API implementation @@ -29,17 +29,15 @@ #include "gnunet_datacache_plugin.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "datacache", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "datacache", __VA_ARGS__) #define LOG_STRERROR_FILE(kind, op, fn) \ - GNUNET_log_from_strerror_file (kind, "datacache", op, fn) + GNUNET_log_from_strerror_file(kind, "datacache", op, fn) /** * Internal state of the datacache library. */ -struct GNUNET_DATACACHE_Handle -{ - +struct GNUNET_DATACACHE_Handle { /** * Bloomfilter to quickly tell if we don't have the content. */ @@ -102,24 +100,24 @@ struct GNUNET_DATACACHE_Handle * @param size number of bytes that were made available */ static void -env_delete_notify (void *cls, const struct GNUNET_HashCode *key, size_t size) +env_delete_notify(void *cls, const struct GNUNET_HashCode *key, size_t size) { struct GNUNET_DATACACHE_Handle *h = cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Content under key `%s' discarded\n", - GNUNET_h2s (key)); - GNUNET_assert (h->utilization >= size); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Content under key `%s' discarded\n", + GNUNET_h2s(key)); + GNUNET_assert(h->utilization >= size); h->utilization -= size; - GNUNET_CONTAINER_bloomfilter_remove (h->filter, key); - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# bytes stored"), - -(long long) size, - GNUNET_NO); - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# items stored"), - -1, - GNUNET_NO); + GNUNET_CONTAINER_bloomfilter_remove(h->filter, key); + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# bytes stored"), + -(long long)size, + GNUNET_NO); + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# items stored"), + -1, + GNUNET_NO); } @@ -131,8 +129,8 @@ env_delete_notify (void *cls, const struct GNUNET_HashCode *key, size_t size) * @return handle to use to access the service */ struct GNUNET_DATACACHE_Handle * -GNUNET_DATACACHE_create (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section) +GNUNET_DATACACHE_create(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section) { unsigned int bf_size; unsigned long long quota; @@ -141,65 +139,65 @@ GNUNET_DATACACHE_create (const struct GNUNET_CONFIGURATION_Handle *cfg, char *name; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_size (cfg, section, "QUOTA", "a)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, section, "QUOTA"); - return NULL; - } + GNUNET_CONFIGURATION_get_value_size(cfg, section, "QUOTA", "a)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, section, "QUOTA"); + return NULL; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, section, "DATABASE", &name)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, section, "DATABASE"); - return NULL; - } + GNUNET_CONFIGURATION_get_value_string(cfg, section, "DATABASE", &name)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, section, "DATABASE"); + return NULL; + } bf_size = quota / 32; /* 8 bit per entry, 1 bit per 32 kb in DB */ - ret = GNUNET_new (struct GNUNET_DATACACHE_Handle); + ret = GNUNET_new(struct GNUNET_DATACACHE_Handle); if (GNUNET_YES != - GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "DISABLE_BF")) - { - if (GNUNET_YES != - GNUNET_CONFIGURATION_get_value_yesno (cfg, section, "DISABLE_BF_RC")) - { - ret->bloom_name = GNUNET_DISK_mktemp ("gnunet-datacachebloom"); - } - if (NULL != ret->bloom_name) + GNUNET_CONFIGURATION_get_value_yesno(cfg, section, "DISABLE_BF")) { - ret->filter = GNUNET_CONTAINER_bloomfilter_load ( - ret->bloom_name, - quota / 1024, /* 8 bit per entry in DB, expect 1k entries */ - 5); + if (GNUNET_YES != + GNUNET_CONFIGURATION_get_value_yesno(cfg, section, "DISABLE_BF_RC")) + { + ret->bloom_name = GNUNET_DISK_mktemp("gnunet-datacachebloom"); + } + if (NULL != ret->bloom_name) + { + ret->filter = GNUNET_CONTAINER_bloomfilter_load( + ret->bloom_name, + quota / 1024, /* 8 bit per entry in DB, expect 1k entries */ + 5); + } + if (NULL == ret->filter) + { + ret->filter = + GNUNET_CONTAINER_bloomfilter_init(NULL, + bf_size, + 5); /* approx. 3% false positives at max use */ + } } - if (NULL == ret->filter) - { - ret->filter = - GNUNET_CONTAINER_bloomfilter_init (NULL, - bf_size, - 5); /* approx. 3% false positives at max use */ - } - } - ret->stats = GNUNET_STATISTICS_create ("datacache", cfg); - ret->section = GNUNET_strdup (section); + ret->stats = GNUNET_STATISTICS_create("datacache", cfg); + ret->section = GNUNET_strdup(section); ret->env.cfg = cfg; ret->env.delete_notify = &env_delete_notify; ret->env.section = ret->section; ret->env.cls = ret; ret->env.delete_notify = &env_delete_notify; ret->env.quota = quota; - LOG (GNUNET_ERROR_TYPE_INFO, _ ("Loading `%s' datacache plugin\n"), name); - GNUNET_asprintf (&libname, "libgnunet_plugin_datacache_%s", name); + LOG(GNUNET_ERROR_TYPE_INFO, _("Loading `%s' datacache plugin\n"), name); + GNUNET_asprintf(&libname, "libgnunet_plugin_datacache_%s", name); ret->short_name = name; ret->lib_name = libname; - ret->api = GNUNET_PLUGIN_load (libname, &ret->env); + ret->api = GNUNET_PLUGIN_load(libname, &ret->env); if (ret->api == NULL) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to load datacache plugin for `%s'\n"), - name); - GNUNET_DATACACHE_destroy (ret); - return NULL; - } + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Failed to load datacache plugin for `%s'\n"), + name); + GNUNET_DATACACHE_destroy(ret); + return NULL; + } return ret; } @@ -210,26 +208,26 @@ GNUNET_DATACACHE_create (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param h handle to the datastore */ void -GNUNET_DATACACHE_destroy (struct GNUNET_DATACACHE_Handle *h) +GNUNET_DATACACHE_destroy(struct GNUNET_DATACACHE_Handle *h) { if (NULL != h->filter) - GNUNET_CONTAINER_bloomfilter_free (h->filter); + GNUNET_CONTAINER_bloomfilter_free(h->filter); if (NULL != h->api) - GNUNET_break (NULL == GNUNET_PLUGIN_unload (h->lib_name, h->api)); - GNUNET_free (h->lib_name); - GNUNET_free (h->short_name); - GNUNET_free (h->section); + GNUNET_break(NULL == GNUNET_PLUGIN_unload(h->lib_name, h->api)); + GNUNET_free(h->lib_name); + GNUNET_free(h->short_name); + GNUNET_free(h->section); if (NULL != h->bloom_name) - { - if (0 != unlink (h->bloom_name)) - GNUNET_log_from_strerror_file (GNUNET_ERROR_TYPE_WARNING, - "datacache", - "unlink", - h->bloom_name); - GNUNET_free (h->bloom_name); - } - GNUNET_STATISTICS_destroy (h->stats, GNUNET_NO); - GNUNET_free (h); + { + if (0 != unlink(h->bloom_name)) + GNUNET_log_from_strerror_file(GNUNET_ERROR_TYPE_WARNING, + "datacache", + "unlink", + h->bloom_name); + GNUNET_free(h->bloom_name); + } + GNUNET_STATISTICS_destroy(h->stats, GNUNET_NO); + GNUNET_free(h); } @@ -248,52 +246,52 @@ GNUNET_DATACACHE_destroy (struct GNUNET_DATACACHE_Handle *h) * @return #GNUNET_OK on success, #GNUNET_SYSERR on error, #GNUNET_NO if duplicate */ int -GNUNET_DATACACHE_put (struct GNUNET_DATACACHE_Handle *h, - const struct GNUNET_HashCode *key, - uint32_t xor_distance, - size_t data_size, - const char *data, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute discard_time, - unsigned int path_info_len, - const struct GNUNET_PeerIdentity *path_info) +GNUNET_DATACACHE_put(struct GNUNET_DATACACHE_Handle *h, + const struct GNUNET_HashCode *key, + uint32_t xor_distance, + size_t data_size, + const char *data, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute discard_time, + unsigned int path_info_len, + const struct GNUNET_PeerIdentity *path_info) { ssize_t used; - used = h->api->put (h->api->cls, - key, - xor_distance, - data_size, - data, - type, - discard_time, - path_info_len, - path_info); + used = h->api->put(h->api->cls, + key, + xor_distance, + data_size, + data, + type, + discard_time, + path_info_len, + path_info); if (-1 == used) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } if (0 == used) - { - /* duplicate */ - return GNUNET_NO; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Stored data under key `%s' in cache\n", - GNUNET_h2s (key)); + { + /* duplicate */ + return GNUNET_NO; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Stored data under key `%s' in cache\n", + GNUNET_h2s(key)); if (NULL != h->filter) - GNUNET_CONTAINER_bloomfilter_add (h->filter, key); - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# bytes stored"), - used, - GNUNET_NO); - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# items stored"), - 1, - GNUNET_NO); + GNUNET_CONTAINER_bloomfilter_add(h->filter, key); + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# bytes stored"), + used, + GNUNET_NO); + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# items stored"), + 1, + GNUNET_NO); while (h->utilization + used > h->env.quota) - GNUNET_assert (GNUNET_OK == h->api->del (h->api->cls)); + GNUNET_assert(GNUNET_OK == h->api->del(h->api->cls)); h->utilization += used; return GNUNET_OK; } @@ -311,33 +309,33 @@ GNUNET_DATACACHE_put (struct GNUNET_DATACACHE_Handle *h, * @return the number of results found */ unsigned int -GNUNET_DATACACHE_get (struct GNUNET_DATACACHE_Handle *h, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +GNUNET_DATACACHE_get(struct GNUNET_DATACACHE_Handle *h, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# requests received"), - 1, - GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Processing request for key `%s'\n", - GNUNET_h2s (key)); + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# requests received"), + 1, + GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Processing request for key `%s'\n", + GNUNET_h2s(key)); if ((NULL != h->filter) && - (GNUNET_OK != GNUNET_CONTAINER_bloomfilter_test (h->filter, key))) - { - GNUNET_STATISTICS_update (h->stats, - gettext_noop ( - "# requests filtered by bloom filter"), - 1, - GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Bloomfilter filters request for key `%s'\n", - GNUNET_h2s (key)); - return 0; /* can not be present */ - } - return h->api->get (h->api->cls, key, type, iter, iter_cls); + (GNUNET_OK != GNUNET_CONTAINER_bloomfilter_test(h->filter, key))) + { + GNUNET_STATISTICS_update(h->stats, + gettext_noop( + "# requests filtered by bloom filter"), + 1, + GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Bloomfilter filters request for key `%s'\n", + GNUNET_h2s(key)); + return 0; /* can not be present */ + } + return h->api->get(h->api->cls, key, type, iter, iter_cls); } @@ -350,17 +348,17 @@ GNUNET_DATACACHE_get (struct GNUNET_DATACACHE_Handle *h, * @return the number of results found (zero or 1) */ unsigned int -GNUNET_DATACACHE_get_random (struct GNUNET_DATACACHE_Handle *h, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +GNUNET_DATACACHE_get_random(struct GNUNET_DATACACHE_Handle *h, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { - GNUNET_STATISTICS_update (h->stats, - gettext_noop ( - "# requests for random value received"), - 1, - GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_DEBUG, "Processing request for random value\n"); - return h->api->get_random (h->api->cls, iter, iter_cls); + GNUNET_STATISTICS_update(h->stats, + gettext_noop( + "# requests for random value received"), + 1, + GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Processing request for random value\n"); + return h->api->get_random(h->api->cls, iter, iter_cls); } @@ -378,21 +376,21 @@ GNUNET_DATACACHE_get_random (struct GNUNET_DATACACHE_Handle *h, * @return the number of results found */ unsigned int -GNUNET_DATACACHE_get_closest (struct GNUNET_DATACACHE_Handle *h, - const struct GNUNET_HashCode *key, - unsigned int num_results, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +GNUNET_DATACACHE_get_closest(struct GNUNET_DATACACHE_Handle *h, + const struct GNUNET_HashCode *key, + unsigned int num_results, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { - GNUNET_STATISTICS_update (h->stats, - gettext_noop ( - "# proximity search requests received"), - 1, - GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Processing proximity search at `%s'\n", - GNUNET_h2s (key)); - return h->api->get_closest (h->api->cls, key, num_results, iter, iter_cls); + GNUNET_STATISTICS_update(h->stats, + gettext_noop( + "# proximity search requests received"), + 1, + GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Processing proximity search at `%s'\n", + GNUNET_h2s(key)); + return h->api->get_closest(h->api->cls, key, num_results, iter, iter_cls); } diff --git a/src/datacache/perf_datacache.c b/src/datacache/perf_datacache.c index 1dfb46cf1..b470ceaa6 100644 --- a/src/datacache/perf_datacache.c +++ b/src/datacache/perf_datacache.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /* * @file datacache/perf_datacache.c * @brief Performance evaluation for the datacache implementations. @@ -29,7 +29,7 @@ #include -#define ASSERT(x) do { if (! (x)) { printf("Error at %s:%d\n", __FILE__, __LINE__); goto FAILURE;} } while (0) +#define ASSERT(x) do { if (!(x)) { printf("Error at %s:%d\n", __FILE__, __LINE__); goto FAILURE; } } while (0) #define ITERATIONS 10000 @@ -44,22 +44,22 @@ static const char *plugin_name; static int -checkIt (void *cls, - const struct GNUNET_HashCode * key, size_t size, const char *data, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute exp, - unsigned int path_len, - const struct GNUNET_PeerIdentity *path) +checkIt(void *cls, + const struct GNUNET_HashCode * key, size_t size, const char *data, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute exp, + unsigned int path_len, + const struct GNUNET_PeerIdentity *path) { - if ((size == sizeof (struct GNUNET_HashCode)) && (0 == memcmp (data, cls, size))) + if ((size == sizeof(struct GNUNET_HashCode)) && (0 == memcmp(data, cls, size))) found++; return GNUNET_OK; } static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_DATACACHE_Handle *h; struct GNUNET_HashCode k; @@ -70,67 +70,67 @@ run (void *cls, char *const *args, const char *cfgfile, char gstr[128]; ok = 0; - h = GNUNET_DATACACHE_create (cfg, "perfcache"); + h = GNUNET_DATACACHE_create(cfg, "perfcache"); if (h == NULL) - { - fprintf (stderr, "%s", "Failed to initialize datacache. Database likely not setup, skipping test.\n"); - ok = 77; /* mark test as skipped */ - return; - } - exp = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS); - start = GNUNET_TIME_absolute_get (); - memset (&k, 0, sizeof (struct GNUNET_HashCode)); + { + fprintf(stderr, "%s", "Failed to initialize datacache. Database likely not setup, skipping test.\n"); + ok = 77; /* mark test as skipped */ + return; + } + exp = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS); + start = GNUNET_TIME_absolute_get(); + memset(&k, 0, sizeof(struct GNUNET_HashCode)); for (i = 0; i < ITERATIONS; i++) - { - if (0 == i % (ITERATIONS / 80)) - fprintf (stderr, "%s", "."); - GNUNET_CRYPTO_hash (&k, sizeof (struct GNUNET_HashCode), &n); - ASSERT (GNUNET_OK == - GNUNET_DATACACHE_put (h, &k, sizeof (struct GNUNET_HashCode), - (const char *) &n, 1 + i % 16, exp, - 0, NULL)); - k = n; - } - fprintf (stderr, "%s", "\n"); - fprintf (stdout, "Stored %u items in %s\n", ITERATIONS, - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), GNUNET_YES)); - GNUNET_snprintf (gstr, sizeof (gstr), "DATACACHE-%s", plugin_name); - GAUGER (gstr, "Time to PUT item in datacache", - GNUNET_TIME_absolute_get_duration (start).rel_value_us / 1000LL / ITERATIONS, - "ms/item"); - start = GNUNET_TIME_absolute_get (); - memset (&k, 0, sizeof (struct GNUNET_HashCode)); + { + if (0 == i % (ITERATIONS / 80)) + fprintf(stderr, "%s", "."); + GNUNET_CRYPTO_hash(&k, sizeof(struct GNUNET_HashCode), &n); + ASSERT(GNUNET_OK == + GNUNET_DATACACHE_put(h, &k, sizeof(struct GNUNET_HashCode), + (const char *)&n, 1 + i % 16, exp, + 0, NULL)); + k = n; + } + fprintf(stderr, "%s", "\n"); + fprintf(stdout, "Stored %u items in %s\n", ITERATIONS, + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start), GNUNET_YES)); + GNUNET_snprintf(gstr, sizeof(gstr), "DATACACHE-%s", plugin_name); + GAUGER(gstr, "Time to PUT item in datacache", + GNUNET_TIME_absolute_get_duration(start).rel_value_us / 1000LL / ITERATIONS, + "ms/item"); + start = GNUNET_TIME_absolute_get(); + memset(&k, 0, sizeof(struct GNUNET_HashCode)); for (i = 0; i < ITERATIONS; i++) - { - if (0 == i % (ITERATIONS / 80)) - fprintf (stderr, "%s", "."); - GNUNET_CRYPTO_hash (&k, sizeof (struct GNUNET_HashCode), &n); - GNUNET_DATACACHE_get (h, &k, 1 + i % 16, &checkIt, &n); - k = n; - } - fprintf (stderr, "%s", "\n"); - fprintf (stdout, - "Found %u/%u items in %s (%u were deleted during storage processing)\n", - found, ITERATIONS, - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), GNUNET_YES), - ITERATIONS - found); + { + if (0 == i % (ITERATIONS / 80)) + fprintf(stderr, "%s", "."); + GNUNET_CRYPTO_hash(&k, sizeof(struct GNUNET_HashCode), &n); + GNUNET_DATACACHE_get(h, &k, 1 + i % 16, &checkIt, &n); + k = n; + } + fprintf(stderr, "%s", "\n"); + fprintf(stdout, + "Found %u/%u items in %s (%u were deleted during storage processing)\n", + found, ITERATIONS, + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start), GNUNET_YES), + ITERATIONS - found); if (found > 0) - GAUGER (gstr, "Time to GET item from datacache", - GNUNET_TIME_absolute_get_duration (start).rel_value_us / 1000LL / found, - "ms/item"); - GNUNET_DATACACHE_destroy (h); - ASSERT (ok == 0); + GAUGER(gstr, "Time to GET item from datacache", + GNUNET_TIME_absolute_get_duration(start).rel_value_us / 1000LL / found, + "ms/item"); + GNUNET_DATACACHE_destroy(h); + ASSERT(ok == 0); return; FAILURE: if (h != NULL) - GNUNET_DATACACHE_destroy (h); + GNUNET_DATACACHE_destroy(h); ok = GNUNET_SYSERR; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { char cfg_name[PATH_MAX]; char *const xargv[] = { @@ -143,16 +143,16 @@ main (int argc, char *argv[]) GNUNET_GETOPT_OPTION_END }; - GNUNET_log_setup ("perf-datacache", - "WARNING", - NULL); - plugin_name = GNUNET_TESTING_get_testname_from_underscore (argv[0]); - GNUNET_snprintf (cfg_name, sizeof (cfg_name), "perf_datacache_data_%s.conf", - plugin_name); - GNUNET_PROGRAM_run ((sizeof (xargv) / sizeof (char *)) - 1, xargv, - "perf-datacache", "nohelp", options, &run, NULL); - if ( (0 != ok) && (77 != ok) ) - fprintf (stderr, "Missed some perfcases: %d\n", ok); + GNUNET_log_setup("perf-datacache", + "WARNING", + NULL); + plugin_name = GNUNET_TESTING_get_testname_from_underscore(argv[0]); + GNUNET_snprintf(cfg_name, sizeof(cfg_name), "perf_datacache_data_%s.conf", + plugin_name); + GNUNET_PROGRAM_run((sizeof(xargv) / sizeof(char *)) - 1, xargv, + "perf-datacache", "nohelp", options, &run, NULL); + if ((0 != ok) && (77 != ok)) + fprintf(stderr, "Missed some perfcases: %d\n", ok); return ok; } diff --git a/src/datacache/plugin_datacache_heap.c b/src/datacache/plugin_datacache_heap.c index ff4893e99..face566a1 100644 --- a/src/datacache/plugin_datacache_heap.c +++ b/src/datacache/plugin_datacache_heap.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datacache/plugin_datacache_heap.c @@ -27,17 +27,16 @@ #include "gnunet_util_lib.h" #include "gnunet_datacache_plugin.h" -#define LOG(kind,...) GNUNET_log_from (kind, "datacache-heap", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "datacache-heap", __VA_ARGS__) -#define LOG_STRERROR_FILE(kind,op,fn) GNUNET_log_from_strerror_file (kind, "datacache-heap", op, fn) +#define LOG_STRERROR_FILE(kind, op, fn) GNUNET_log_from_strerror_file(kind, "datacache-heap", op, fn) #define NUM_HEAPS 24 /** * Context for all functions in this plugin. */ -struct Plugin -{ +struct Plugin { /** * Our execution environment. */ @@ -52,15 +51,13 @@ struct Plugin * Heaps sorted by distance. */ struct GNUNET_CONTAINER_Heap *heaps[NUM_HEAPS]; - }; /** * Entry in the hash map. */ -struct Value -{ +struct Value { /** * Key for the entry. */ @@ -100,18 +97,16 @@ struct Value * Type of the block. */ enum GNUNET_BLOCK_Type type; - }; -#define OVERHEAD (sizeof (struct Value) + 64) +#define OVERHEAD (sizeof(struct Value) + 64) /** * Closure for #put_cb(). */ -struct PutContext -{ +struct PutContext { /** * Expiration time for the new value. */ @@ -159,39 +154,39 @@ struct PutContext * @return #GNUNET_YES if not found (to continue to iterate) */ static int -put_cb (void *cls, - const struct GNUNET_HashCode *key, - void *value) +put_cb(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct PutContext *put_ctx = cls; struct Value *val = value; - if ( (val->size == put_ctx->size) && - (val->type == put_ctx->type) && - (0 == memcmp (&val[1], - put_ctx->data, - put_ctx->size)) ) - { - put_ctx->found = GNUNET_YES; - val->discard_time = GNUNET_TIME_absolute_max (val->discard_time, - put_ctx->discard_time); - /* replace old path with new path */ - GNUNET_array_grow (val->path_info, - val->path_info_len, - put_ctx->path_info_len); - GNUNET_memcpy (val->path_info, - put_ctx->path_info, - put_ctx->path_info_len * sizeof (struct GNUNET_PeerIdentity)); - GNUNET_CONTAINER_heap_update_cost (val->hn, - val->discard_time.abs_value_us); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got same value for key %s and type %d (size %u vs %u)\n", - GNUNET_h2s (key), - val->type, - (unsigned int) val->size, - (unsigned int) put_ctx->size); - return GNUNET_NO; - } + if ((val->size == put_ctx->size) && + (val->type == put_ctx->type) && + (0 == memcmp(&val[1], + put_ctx->data, + put_ctx->size))) + { + put_ctx->found = GNUNET_YES; + val->discard_time = GNUNET_TIME_absolute_max(val->discard_time, + put_ctx->discard_time); + /* replace old path with new path */ + GNUNET_array_grow(val->path_info, + val->path_info_len, + put_ctx->path_info_len); + GNUNET_memcpy(val->path_info, + put_ctx->path_info, + put_ctx->path_info_len * sizeof(struct GNUNET_PeerIdentity)); + GNUNET_CONTAINER_heap_update_cost(val->hn, + val->discard_time.abs_value_us); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got same value for key %s and type %d (size %u vs %u)\n", + GNUNET_h2s(key), + val->type, + (unsigned int)val->size, + (unsigned int)put_ctx->size); + return GNUNET_NO; + } return GNUNET_YES; } @@ -211,15 +206,15 @@ put_cb (void *cls, * @return 0 if duplicate, -1 on error, number of bytes used otherwise */ static ssize_t -heap_plugin_put (void *cls, - const struct GNUNET_HashCode *key, - uint32_t xor_distance, - size_t size, - const char *data, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute discard_time, - unsigned int path_info_len, - const struct GNUNET_PeerIdentity *path_info) +heap_plugin_put(void *cls, + const struct GNUNET_HashCode *key, + uint32_t xor_distance, + size_t size, + const char *data, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute discard_time, + unsigned int path_info_len, + const struct GNUNET_PeerIdentity *path_info) { struct Plugin *plugin = cls; struct Value *val; @@ -232,16 +227,16 @@ heap_plugin_put (void *cls, put_ctx.path_info_len = path_info_len; put_ctx.discard_time = discard_time; put_ctx.type = type; - GNUNET_CONTAINER_multihashmap_get_multiple (plugin->map, - key, - &put_cb, - &put_ctx); + GNUNET_CONTAINER_multihashmap_get_multiple(plugin->map, + key, + &put_cb, + &put_ctx); if (GNUNET_YES == put_ctx.found) return 0; - val = GNUNET_malloc (sizeof (struct Value) + size); - GNUNET_memcpy (&val[1], - data, - size); + val = GNUNET_malloc(sizeof(struct Value) + size); + GNUNET_memcpy(&val[1], + data, + size); val->key = *key; val->type = type; val->discard_time = discard_time; @@ -250,19 +245,19 @@ heap_plugin_put (void *cls, val->distance = NUM_HEAPS - 1; else val->distance = xor_distance; - GNUNET_array_grow (val->path_info, - val->path_info_len, - path_info_len); - GNUNET_memcpy (val->path_info, - path_info, - path_info_len * sizeof (struct GNUNET_PeerIdentity)); - (void) GNUNET_CONTAINER_multihashmap_put (plugin->map, - &val->key, - val, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - val->hn = GNUNET_CONTAINER_heap_insert (plugin->heaps[val->distance], - val, - val->discard_time.abs_value_us); + GNUNET_array_grow(val->path_info, + val->path_info_len, + path_info_len); + GNUNET_memcpy(val->path_info, + path_info, + path_info_len * sizeof(struct GNUNET_PeerIdentity)); + (void)GNUNET_CONTAINER_multihashmap_put(plugin->map, + &val->key, + val, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + val->hn = GNUNET_CONTAINER_heap_insert(plugin->heaps[val->distance], + val, + val->discard_time.abs_value_us); return size + OVERHEAD; } @@ -270,8 +265,7 @@ heap_plugin_put (void *cls, /** * Closure for #get_cb(). */ -struct GetContext -{ +struct GetContext { /** * Function to call for each result. */ @@ -305,29 +299,29 @@ struct GetContext * @return #GNUNET_YES to continue to iterate */ static int -get_cb (void *cls, - const struct GNUNET_HashCode *key, - void *value) +get_cb(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GetContext *get_ctx = cls; struct Value *val = value; int ret; - if ( (get_ctx->type != val->type) && - (GNUNET_BLOCK_TYPE_ANY != get_ctx->type) ) + if ((get_ctx->type != val->type) && + (GNUNET_BLOCK_TYPE_ANY != get_ctx->type)) return GNUNET_OK; if (0 == - GNUNET_TIME_absolute_get_remaining (val->discard_time).rel_value_us) + GNUNET_TIME_absolute_get_remaining(val->discard_time).rel_value_us) return GNUNET_OK; if (NULL != get_ctx->iter) - ret = get_ctx->iter (get_ctx->iter_cls, - key, - val->size, - (const char *) &val[1], - val->type, - val->discard_time, - val->path_info_len, - val->path_info); + ret = get_ctx->iter(get_ctx->iter_cls, + key, + val->size, + (const char *)&val[1], + val->type, + val->discard_time, + val->path_info_len, + val->path_info); else ret = GNUNET_YES; get_ctx->cnt++; @@ -347,11 +341,11 @@ get_cb (void *cls, * @return the number of results found */ static unsigned int -heap_plugin_get (void *cls, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +heap_plugin_get(void *cls, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { struct Plugin *plugin = cls; struct GetContext get_ctx; @@ -360,10 +354,10 @@ heap_plugin_get (void *cls, get_ctx.iter = iter; get_ctx.iter_cls = iter_cls; get_ctx.cnt = 0; - GNUNET_CONTAINER_multihashmap_get_multiple (plugin->map, - key, - &get_cb, - &get_ctx); + GNUNET_CONTAINER_multihashmap_get_multiple(plugin->map, + key, + &get_cb, + &get_ctx); return get_ctx.cnt; } @@ -376,28 +370,28 @@ heap_plugin_get (void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -heap_plugin_del (void *cls) +heap_plugin_del(void *cls) { struct Plugin *plugin = cls; struct Value *val; - for (unsigned int i=0;iheaps[i]); - if (NULL != val) - break; - } + for (unsigned int i = 0; i < NUM_HEAPS; i++) + { + val = GNUNET_CONTAINER_heap_remove_root(plugin->heaps[i]); + if (NULL != val) + break; + } if (NULL == val) return GNUNET_SYSERR; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (plugin->map, - &val->key, - val)); - plugin->env->delete_notify (plugin->env->cls, - &val->key, - val->size + OVERHEAD); - GNUNET_free_non_null (val->path_info); - GNUNET_free (val); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(plugin->map, + &val->key, + val)); + plugin->env->delete_notify(plugin->env->cls, + &val->key, + val->size + OVERHEAD); + GNUNET_free_non_null(val->path_info); + GNUNET_free(val); return GNUNET_OK; } @@ -411,9 +405,9 @@ heap_plugin_del (void *cls) * @return the number of results found */ static unsigned int -heap_plugin_get_random (void *cls, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +heap_plugin_get_random(void *cls, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { struct Plugin *plugin = cls; struct GetContext get_ctx; @@ -422,9 +416,9 @@ heap_plugin_get_random (void *cls, get_ctx.iter = iter; get_ctx.iter_cls = iter_cls; get_ctx.cnt = 0; - GNUNET_CONTAINER_multihashmap_get_random (plugin->map, - &get_cb, - &get_ctx); + GNUNET_CONTAINER_multihashmap_get_random(plugin->map, + &get_cb, + &get_ctx); return get_ctx.cnt; } @@ -432,8 +426,7 @@ heap_plugin_get_random (void *cls, /** * Closure for #find_closest(). */ -struct GetClosestContext -{ +struct GetClosestContext { struct Value **values; unsigned int num_results; @@ -443,32 +436,32 @@ struct GetClosestContext static int -find_closest (void *cls, - const struct GNUNET_HashCode *key, - void *value) +find_closest(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GetClosestContext *gcc = cls; struct Value *val = value; unsigned int j; - if (1 != GNUNET_CRYPTO_hash_cmp (key, - gcc->key)) + if (1 != GNUNET_CRYPTO_hash_cmp(key, + gcc->key)) return GNUNET_OK; /* useless */ j = gcc->num_results; - for (unsigned int i=0;inum_results;i++) - { - if (NULL == gcc->values[i]) - { - j = i; - break; - } - if (1 == GNUNET_CRYPTO_hash_cmp (&gcc->values[i]->key, - key)) + for (unsigned int i = 0; i < gcc->num_results; i++) { - j = i; - break; + if (NULL == gcc->values[i]) + { + j = i; + break; + } + if (1 == GNUNET_CRYPTO_hash_cmp(&gcc->values[i]->key, + key)) + { + j = i; + break; + } } - } if (j == gcc->num_results) return GNUNET_OK; gcc->values[j] = val; @@ -490,11 +483,11 @@ find_closest (void *cls, * @return the number of results found */ static unsigned int -heap_plugin_get_closest (void *cls, - const struct GNUNET_HashCode *key, - unsigned int num_results, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +heap_plugin_get_closest(void *cls, + const struct GNUNET_HashCode *key, + unsigned int num_results, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { struct Plugin *plugin = cls; struct Value *values[num_results]; @@ -503,22 +496,23 @@ heap_plugin_get_closest (void *cls, .num_results = num_results, .key = key }; - GNUNET_CONTAINER_multihashmap_iterate (plugin->map, - &find_closest, - &gcc); - for (unsigned int i=0;ikey, - values[i]->size, - (void *) &values[i][1], - values[i]->type, - values[i]->discard_time, - values[i]->path_info_len, - values[i]->path_info); - } + + GNUNET_CONTAINER_multihashmap_iterate(plugin->map, + &find_closest, + &gcc); + for (unsigned int i = 0; i < num_results; i++) + { + if (NULL == values[i]) + return i; + iter(iter_cls, + &values[i]->key, + values[i]->size, + (void *)&values[i][1], + values[i]->type, + values[i]->discard_time, + values[i]->path_info_len, + values[i]->path_info); + } return num_results; } @@ -530,27 +524,27 @@ heap_plugin_get_closest (void *cls, * @return the plugin's closure (our `struct Plugin`) */ void * -libgnunet_plugin_datacache_heap_init (void *cls) +libgnunet_plugin_datacache_heap_init(void *cls) { struct GNUNET_DATACACHE_PluginEnvironment *env = cls; struct GNUNET_DATACACHE_PluginFunctions *api; struct Plugin *plugin; - plugin = GNUNET_new (struct Plugin); - plugin->map = GNUNET_CONTAINER_multihashmap_create (1024, /* FIXME: base on quota! */ - GNUNET_YES); - for (unsigned int i=0;iheaps[i] = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); + plugin = GNUNET_new(struct Plugin); + plugin->map = GNUNET_CONTAINER_multihashmap_create(1024, /* FIXME: base on quota! */ + GNUNET_YES); + for (unsigned int i = 0; i < NUM_HEAPS; i++) + plugin->heaps[i] = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN); plugin->env = env; - api = GNUNET_new (struct GNUNET_DATACACHE_PluginFunctions); + api = GNUNET_new(struct GNUNET_DATACACHE_PluginFunctions); api->cls = plugin; api->get = &heap_plugin_get; api->put = &heap_plugin_put; api->del = &heap_plugin_del; api->get_random = &heap_plugin_get_random; api->get_closest = &heap_plugin_get_closest; - LOG (GNUNET_ERROR_TYPE_INFO, - _("Heap datacache running\n")); + LOG(GNUNET_ERROR_TYPE_INFO, + _("Heap datacache running\n")); return api; } @@ -562,28 +556,28 @@ libgnunet_plugin_datacache_heap_init (void *cls) * @return NULL */ void * -libgnunet_plugin_datacache_heap_done (void *cls) +libgnunet_plugin_datacache_heap_done(void *cls) { struct GNUNET_DATACACHE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; struct Value *val; - for (unsigned int i=0;iheaps[i]))) + for (unsigned int i = 0; i < NUM_HEAPS; i++) { - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (plugin->map, - &val->key, - val)); - GNUNET_free_non_null (val->path_info); - GNUNET_free (val); + while (NULL != (val = GNUNET_CONTAINER_heap_remove_root(plugin->heaps[i]))) + { + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(plugin->map, + &val->key, + val)); + GNUNET_free_non_null(val->path_info); + GNUNET_free(val); + } + GNUNET_CONTAINER_heap_destroy(plugin->heaps[i]); } - GNUNET_CONTAINER_heap_destroy (plugin->heaps[i]); - } - GNUNET_CONTAINER_multihashmap_destroy (plugin->map); - GNUNET_free (plugin); - GNUNET_free (api); + GNUNET_CONTAINER_multihashmap_destroy(plugin->map); + GNUNET_free(plugin); + GNUNET_free(api); return NULL; } diff --git a/src/datacache/plugin_datacache_postgres.c b/src/datacache/plugin_datacache_postgres.c index bf4ef108a..6666c850c 100644 --- a/src/datacache/plugin_datacache_postgres.c +++ b/src/datacache/plugin_datacache_postgres.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datacache/plugin_datacache_postgres.c @@ -28,7 +28,7 @@ #include "gnunet_pq_lib.h" #include "gnunet_datacache_plugin.h" -#define LOG(kind,...) GNUNET_log_from (kind, "datacache-postgres", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "datacache-postgres", __VA_ARGS__) /** * Per-entry overhead estimate @@ -38,8 +38,7 @@ /** * Context for all functions in this plugin. */ -struct Plugin -{ +struct Plugin { /** * Our execution environment. */ @@ -64,81 +63,81 @@ struct Plugin * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -init_connection (struct Plugin *plugin) +init_connection(struct Plugin *plugin) { struct GNUNET_PQ_ExecuteStatement es[] = { - GNUNET_PQ_make_execute ("CREATE TEMPORARY TABLE IF NOT EXISTS gn011dc (" - " type INTEGER NOT NULL," - " prox INTEGER NOT NULL," - " discard_time BIGINT NOT NULL," - " key BYTEA NOT NULL," - " value BYTEA NOT NULL," - " path BYTEA DEFAULT NULL)" - "WITH OIDS"), - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS idx_key ON gn011dc (key)"), - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS idx_dt ON gn011dc (discard_time)"), - GNUNET_PQ_make_execute ("ALTER TABLE gn011dc ALTER value SET STORAGE EXTERNAL"), - GNUNET_PQ_make_execute ("ALTER TABLE gn011dc ALTER key SET STORAGE PLAIN"), + GNUNET_PQ_make_execute("CREATE TEMPORARY TABLE IF NOT EXISTS gn011dc (" + " type INTEGER NOT NULL," + " prox INTEGER NOT NULL," + " discard_time BIGINT NOT NULL," + " key BYTEA NOT NULL," + " value BYTEA NOT NULL," + " path BYTEA DEFAULT NULL)" + "WITH OIDS"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS idx_key ON gn011dc (key)"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS idx_dt ON gn011dc (discard_time)"), + GNUNET_PQ_make_execute("ALTER TABLE gn011dc ALTER value SET STORAGE EXTERNAL"), + GNUNET_PQ_make_execute("ALTER TABLE gn011dc ALTER key SET STORAGE PLAIN"), GNUNET_PQ_EXECUTE_STATEMENT_END }; struct GNUNET_PQ_PreparedStatement ps[] = { - GNUNET_PQ_make_prepare ("getkt", - "SELECT discard_time,type,value,path FROM gn011dc " - "WHERE key=$1 AND type=$2 AND discard_time >= $3", - 3), - GNUNET_PQ_make_prepare ("getk", - "SELECT discard_time,type,value,path FROM gn011dc " - "WHERE key=$1 AND discard_time >= $2", - 2), - GNUNET_PQ_make_prepare ("getex", - "SELECT length(value) AS len,oid,key FROM gn011dc" - " WHERE discard_time < $1" - " ORDER BY discard_time ASC LIMIT 1", - 1), - GNUNET_PQ_make_prepare ("getm", - "SELECT length(value) AS len,oid,key FROM gn011dc" - " ORDER BY prox ASC, discard_time ASC LIMIT 1", - 0), - GNUNET_PQ_make_prepare ("get_random", - "SELECT discard_time,type,value,path,key FROM gn011dc" - " WHERE discard_time >= $1" - " ORDER BY key ASC LIMIT 1 OFFSET $2", - 2), - GNUNET_PQ_make_prepare ("get_closest", - "SELECT discard_time,type,value,path,key FROM gn011dc " - "WHERE key>=$1 AND discard_time >= $2 ORDER BY key ASC LIMIT $3", - 3), - GNUNET_PQ_make_prepare ("delrow", - "DELETE FROM gn011dc WHERE oid=$1", - 1), - GNUNET_PQ_make_prepare ("put", - "INSERT INTO gn011dc (type, prox, discard_time, key, value, path) " - "VALUES ($1, $2, $3, $4, $5, $6)", - 6), + GNUNET_PQ_make_prepare("getkt", + "SELECT discard_time,type,value,path FROM gn011dc " + "WHERE key=$1 AND type=$2 AND discard_time >= $3", + 3), + GNUNET_PQ_make_prepare("getk", + "SELECT discard_time,type,value,path FROM gn011dc " + "WHERE key=$1 AND discard_time >= $2", + 2), + GNUNET_PQ_make_prepare("getex", + "SELECT length(value) AS len,oid,key FROM gn011dc" + " WHERE discard_time < $1" + " ORDER BY discard_time ASC LIMIT 1", + 1), + GNUNET_PQ_make_prepare("getm", + "SELECT length(value) AS len,oid,key FROM gn011dc" + " ORDER BY prox ASC, discard_time ASC LIMIT 1", + 0), + GNUNET_PQ_make_prepare("get_random", + "SELECT discard_time,type,value,path,key FROM gn011dc" + " WHERE discard_time >= $1" + " ORDER BY key ASC LIMIT 1 OFFSET $2", + 2), + GNUNET_PQ_make_prepare("get_closest", + "SELECT discard_time,type,value,path,key FROM gn011dc " + "WHERE key>=$1 AND discard_time >= $2 ORDER BY key ASC LIMIT $3", + 3), + GNUNET_PQ_make_prepare("delrow", + "DELETE FROM gn011dc WHERE oid=$1", + 1), + GNUNET_PQ_make_prepare("put", + "INSERT INTO gn011dc (type, prox, discard_time, key, value, path) " + "VALUES ($1, $2, $3, $4, $5, $6)", + 6), GNUNET_PQ_PREPARED_STATEMENT_END }; - plugin->dbh = GNUNET_PQ_connect_with_cfg (plugin->env->cfg, - "datacache-postgres"); + plugin->dbh = GNUNET_PQ_connect_with_cfg(plugin->env->cfg, + "datacache-postgres"); if (NULL == plugin->dbh) return GNUNET_SYSERR; if (GNUNET_OK != - GNUNET_PQ_exec_statements (plugin->dbh, - es)) - { - PQfinish (plugin->dbh); - plugin->dbh = NULL; - return GNUNET_SYSERR; - } + GNUNET_PQ_exec_statements(plugin->dbh, + es)) + { + PQfinish(plugin->dbh); + plugin->dbh = NULL; + return GNUNET_SYSERR; + } if (GNUNET_OK != - GNUNET_PQ_prepare_statements (plugin->dbh, - ps)) - { - PQfinish (plugin->dbh); - plugin->dbh = NULL; - return GNUNET_SYSERR; - } + GNUNET_PQ_prepare_statements(plugin->dbh, + ps)) + { + PQfinish(plugin->dbh); + plugin->dbh = NULL; + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -158,33 +157,33 @@ init_connection (struct Plugin *plugin) * @return 0 if duplicate, -1 on error, number of bytes used otherwise */ static ssize_t -postgres_plugin_put (void *cls, - const struct GNUNET_HashCode *key, - uint32_t prox, - size_t data_size, - const char *data, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute discard_time, - unsigned int path_info_len, - const struct GNUNET_PeerIdentity *path_info) +postgres_plugin_put(void *cls, + const struct GNUNET_HashCode *key, + uint32_t prox, + size_t data_size, + const char *data, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute discard_time, + unsigned int path_info_len, + const struct GNUNET_PeerIdentity *path_info) { struct Plugin *plugin = cls; - uint32_t type32 = (uint32_t) type; + uint32_t type32 = (uint32_t)type; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_uint32 (&type32), - GNUNET_PQ_query_param_uint32 (&prox), - GNUNET_PQ_query_param_absolute_time (&discard_time), - GNUNET_PQ_query_param_auto_from_type (key), - GNUNET_PQ_query_param_fixed_size (data, data_size), - GNUNET_PQ_query_param_fixed_size (path_info, - path_info_len * sizeof (struct GNUNET_PeerIdentity)), + GNUNET_PQ_query_param_uint32(&type32), + GNUNET_PQ_query_param_uint32(&prox), + GNUNET_PQ_query_param_absolute_time(&discard_time), + GNUNET_PQ_query_param_auto_from_type(key), + GNUNET_PQ_query_param_fixed_size(data, data_size), + GNUNET_PQ_query_param_fixed_size(path_info, + path_info_len * sizeof(struct GNUNET_PeerIdentity)), GNUNET_PQ_query_param_end }; enum GNUNET_DB_QueryStatus ret; - ret = GNUNET_PQ_eval_prepared_non_select (plugin->dbh, - "put", - params); + ret = GNUNET_PQ_eval_prepared_non_select(plugin->dbh, + "put", + params); if (0 > ret) return -1; plugin->num_items++; @@ -195,9 +194,7 @@ postgres_plugin_put (void *cls, /** * Closure for #handle_results. */ -struct HandleResultContext -{ - +struct HandleResultContext { /** * Function to call on each result, may be NULL. */ @@ -225,70 +222,70 @@ struct HandleResultContext * @param num_result the number of results in @a result */ static void -handle_results (void *cls, - PGresult *result, - unsigned int num_results) +handle_results(void *cls, + PGresult *result, + unsigned int num_results) { struct HandleResultContext *hrc = cls; - for (unsigned int i=0;iiter) && - (GNUNET_SYSERR == - hrc->iter (hrc->iter_cls, + struct GNUNET_TIME_Absolute expiration_time; + uint32_t type; + void *data; + size_t data_size; + struct GNUNET_PeerIdentity *path; + size_t path_len; + struct GNUNET_PQ_ResultSpec rs[] = { + GNUNET_PQ_result_spec_absolute_time("discard_time", + &expiration_time), + GNUNET_PQ_result_spec_uint32("type", + &type), + GNUNET_PQ_result_spec_variable_size("value", + &data, + &data_size), + GNUNET_PQ_result_spec_variable_size("path", + (void **)&path, + &path_len), + GNUNET_PQ_result_spec_end + }; + + if (GNUNET_YES != + GNUNET_PQ_extract_result(result, + rs, + i)) + { + GNUNET_break(0); + return; + } + if (0 != (path_len % sizeof(struct GNUNET_PeerIdentity))) + { + GNUNET_break(0); + path_len = 0; + } + path_len %= sizeof(struct GNUNET_PeerIdentity); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Found result of size %u bytes and type %u in database\n", + (unsigned int)data_size, + (unsigned int)type); + if ((NULL != hrc->iter) && + (GNUNET_SYSERR == + hrc->iter(hrc->iter_cls, hrc->key, data_size, data, - (enum GNUNET_BLOCK_Type) type, + (enum GNUNET_BLOCK_Type)type, expiration_time, path_len, - path)) ) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ending iteration (client error)\n"); - GNUNET_PQ_cleanup_result (rs); - return; + path))) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ending iteration (client error)\n"); + GNUNET_PQ_cleanup_result(rs); + return; + } + GNUNET_PQ_cleanup_result(rs); } - GNUNET_PQ_cleanup_result (rs); - } } @@ -304,38 +301,38 @@ handle_results (void *cls, * @return the number of results found */ static unsigned int -postgres_plugin_get (void *cls, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +postgres_plugin_get(void *cls, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { struct Plugin *plugin = cls; - uint32_t type32 = (uint32_t) type; + uint32_t type32 = (uint32_t)type; struct GNUNET_TIME_Absolute now; struct GNUNET_PQ_QueryParam paramk[] = { - GNUNET_PQ_query_param_auto_from_type (key), - GNUNET_PQ_query_param_absolute_time (&now), + GNUNET_PQ_query_param_auto_from_type(key), + GNUNET_PQ_query_param_absolute_time(&now), GNUNET_PQ_query_param_end }; struct GNUNET_PQ_QueryParam paramkt[] = { - GNUNET_PQ_query_param_auto_from_type (key), - GNUNET_PQ_query_param_uint32 (&type32), - GNUNET_PQ_query_param_absolute_time (&now), + GNUNET_PQ_query_param_auto_from_type(key), + GNUNET_PQ_query_param_uint32(&type32), + GNUNET_PQ_query_param_absolute_time(&now), GNUNET_PQ_query_param_end }; enum GNUNET_DB_QueryStatus res; struct HandleResultContext hr_ctx; - now = GNUNET_TIME_absolute_get (); + now = GNUNET_TIME_absolute_get(); hr_ctx.iter = iter; hr_ctx.iter_cls = iter_cls; hr_ctx.key = key; - res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh, - (0 == type) ? "getk" : "getkt", - (0 == type) ? paramk : paramkt, - &handle_results, - &hr_ctx); + res = GNUNET_PQ_eval_prepared_multi_select(plugin->dbh, + (0 == type) ? "getk" : "getkt", + (0 == type) ? paramk : paramkt, + &handle_results, + &hr_ctx); if (res < 0) return 0; return res; @@ -350,7 +347,7 @@ postgres_plugin_get (void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -postgres_plugin_del (void *cls) +postgres_plugin_del(void *cls) { struct Plugin *plugin = cls; struct GNUNET_PQ_QueryParam pempty[] = { @@ -360,57 +357,57 @@ postgres_plugin_del (void *cls) uint32_t oid; struct GNUNET_HashCode key; struct GNUNET_PQ_ResultSpec rs[] = { - GNUNET_PQ_result_spec_uint32 ("len", - &size), - GNUNET_PQ_result_spec_uint32 ("oid", - &oid), - GNUNET_PQ_result_spec_auto_from_type ("key", - &key), + GNUNET_PQ_result_spec_uint32("len", + &size), + GNUNET_PQ_result_spec_uint32("oid", + &oid), + GNUNET_PQ_result_spec_auto_from_type("key", + &key), GNUNET_PQ_result_spec_end }; enum GNUNET_DB_QueryStatus res; struct GNUNET_PQ_QueryParam dparam[] = { - GNUNET_PQ_query_param_uint32 (&oid), + GNUNET_PQ_query_param_uint32(&oid), GNUNET_PQ_query_param_end }; struct GNUNET_TIME_Absolute now; struct GNUNET_PQ_QueryParam xparam[] = { - GNUNET_PQ_query_param_absolute_time (&now), + GNUNET_PQ_query_param_absolute_time(&now), GNUNET_PQ_query_param_end }; - now = GNUNET_TIME_absolute_get (); - res = GNUNET_PQ_eval_prepared_singleton_select (plugin->dbh, - "getex", - xparam, - rs); + now = GNUNET_TIME_absolute_get(); + res = GNUNET_PQ_eval_prepared_singleton_select(plugin->dbh, + "getex", + xparam, + rs); if (0 >= res) - res = GNUNET_PQ_eval_prepared_singleton_select (plugin->dbh, - "getm", - pempty, - rs); + res = GNUNET_PQ_eval_prepared_singleton_select(plugin->dbh, + "getm", + pempty, + rs); if (0 > res) return GNUNET_SYSERR; if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == res) - { - /* no result */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ending iteration (no more results)\n"); - return 0; - } - res = GNUNET_PQ_eval_prepared_non_select (plugin->dbh, - "delrow", - dparam); + { + /* no result */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ending iteration (no more results)\n"); + return 0; + } + res = GNUNET_PQ_eval_prepared_non_select(plugin->dbh, + "delrow", + dparam); if (0 > res) - { - GNUNET_PQ_cleanup_result (rs); - return GNUNET_SYSERR; - } + { + GNUNET_PQ_cleanup_result(rs); + return GNUNET_SYSERR; + } plugin->num_items--; - plugin->env->delete_notify (plugin->env->cls, - &key, - size + OVERHEAD); - GNUNET_PQ_cleanup_result (rs); + plugin->env->delete_notify(plugin->env->cls, + &key, + size + OVERHEAD); + GNUNET_PQ_cleanup_result(rs); return GNUNET_OK; } @@ -424,9 +421,9 @@ postgres_plugin_del (void *cls) * @return the number of results found, zero (datacache empty) or one */ static unsigned int -postgres_plugin_get_random (void *cls, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +postgres_plugin_get_random(void *cls, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { struct Plugin *plugin = cls; uint32_t off; @@ -440,23 +437,23 @@ postgres_plugin_get_random (void *cls, uint32_t type; enum GNUNET_DB_QueryStatus res; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_absolute_time (&now), - GNUNET_PQ_query_param_uint32 (&off), + GNUNET_PQ_query_param_absolute_time(&now), + GNUNET_PQ_query_param_uint32(&off), GNUNET_PQ_query_param_end }; struct GNUNET_PQ_ResultSpec rs[] = { - GNUNET_PQ_result_spec_absolute_time ("discard_time", - &expiration_time), - GNUNET_PQ_result_spec_uint32 ("type", - &type), - GNUNET_PQ_result_spec_variable_size ("value", - &data, - &data_size), - GNUNET_PQ_result_spec_variable_size ("path", - (void **) &path, - &path_len), - GNUNET_PQ_result_spec_auto_from_type ("key", - &key), + GNUNET_PQ_result_spec_absolute_time("discard_time", + &expiration_time), + GNUNET_PQ_result_spec_uint32("type", + &type), + GNUNET_PQ_result_spec_variable_size("value", + &data, + &data_size), + GNUNET_PQ_result_spec_variable_size("path", + (void **)&path, + &path_len), + GNUNET_PQ_result_spec_auto_from_type("key", + &key), GNUNET_PQ_result_spec_end }; @@ -464,43 +461,43 @@ postgres_plugin_get_random (void *cls, return 0; if (NULL == iter) return 1; - now = GNUNET_TIME_absolute_get (); - off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, - plugin->num_items); - res = GNUNET_PQ_eval_prepared_singleton_select (plugin->dbh, - "get_random", - params, - rs); + now = GNUNET_TIME_absolute_get(); + off = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, + plugin->num_items); + res = GNUNET_PQ_eval_prepared_singleton_select(plugin->dbh, + "get_random", + params, + rs); if (0 > res) - { - GNUNET_break (0); - return 0; - } + { + GNUNET_break(0); + return 0; + } if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == res) - { - GNUNET_break (0); - return 0; - } - if (0 != (path_len % sizeof (struct GNUNET_PeerIdentity))) - { - GNUNET_break (0); - path_len = 0; - } - path_len %= sizeof (struct GNUNET_PeerIdentity); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Found random value with key %s of size %u bytes and type %u in database\n", - GNUNET_h2s (&key), - (unsigned int) data_size, - (unsigned int) type); - (void) iter (iter_cls, - &key, - data_size, - data, - (enum GNUNET_BLOCK_Type) type, - expiration_time, - path_len, - path); - GNUNET_PQ_cleanup_result (rs); + { + GNUNET_break(0); + return 0; + } + if (0 != (path_len % sizeof(struct GNUNET_PeerIdentity))) + { + GNUNET_break(0); + path_len = 0; + } + path_len %= sizeof(struct GNUNET_PeerIdentity); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Found random value with key %s of size %u bytes and type %u in database\n", + GNUNET_h2s(&key), + (unsigned int)data_size, + (unsigned int)type); + (void)iter(iter_cls, + &key, + data_size, + data, + (enum GNUNET_BLOCK_Type)type, + expiration_time, + path_len, + path); + GNUNET_PQ_cleanup_result(rs); return 1; } @@ -508,8 +505,7 @@ postgres_plugin_get_random (void *cls, /** * Closure for #extract_result_cb. */ -struct ExtractResultContext -{ +struct ExtractResultContext { /** * Function to call for each result found. */ @@ -519,7 +515,6 @@ struct ExtractResultContext * Closure for @e iter. */ void *iter_cls; - }; @@ -533,74 +528,74 @@ struct ExtractResultContext * @param num_result the number of results in @a result */ static void -extract_result_cb (void *cls, - PGresult *result, - unsigned int num_results) +extract_result_cb(void *cls, + PGresult *result, + unsigned int num_results) { struct ExtractResultContext *erc = cls; if (NULL == erc->iter) return; - for (unsigned int i=0;iiter(erc->iter_cls, + &key, + data_size, + data, + (enum GNUNET_BLOCK_Type)type, + expiration_time, + path_len, + path)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ending iteration (client error)\n"); + GNUNET_PQ_cleanup_result(rs); + break; + } + GNUNET_PQ_cleanup_result(rs); } - path_len %= sizeof (struct GNUNET_PeerIdentity); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Found result of size %u bytes and type %u in database\n", - (unsigned int) data_size, - (unsigned int) type); - if (GNUNET_SYSERR == - erc->iter (erc->iter_cls, - &key, - data_size, - data, - (enum GNUNET_BLOCK_Type) type, - expiration_time, - path_len, - path)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ending iteration (client error)\n"); - GNUNET_PQ_cleanup_result (rs); - break; - } - GNUNET_PQ_cleanup_result (rs); - } } @@ -618,19 +613,19 @@ extract_result_cb (void *cls, * @return the number of results found */ static unsigned int -postgres_plugin_get_closest (void *cls, - const struct GNUNET_HashCode *key, - unsigned int num_results, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +postgres_plugin_get_closest(void *cls, + const struct GNUNET_HashCode *key, + unsigned int num_results, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { struct Plugin *plugin = cls; - uint32_t num_results32 = (uint32_t) num_results; + uint32_t num_results32 = (uint32_t)num_results; struct GNUNET_TIME_Absolute now; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_auto_from_type (key), - GNUNET_PQ_query_param_absolute_time (&now), - GNUNET_PQ_query_param_uint32 (&num_results32), + GNUNET_PQ_query_param_auto_from_type(key), + GNUNET_PQ_query_param_absolute_time(&now), + GNUNET_PQ_query_param_uint32(&num_results32), GNUNET_PQ_query_param_end }; enum GNUNET_DB_QueryStatus res; @@ -638,25 +633,25 @@ postgres_plugin_get_closest (void *cls, erc.iter = iter; erc.iter_cls = iter_cls; - now = GNUNET_TIME_absolute_get (); - res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh, - "get_closest", - params, - &extract_result_cb, - &erc); + now = GNUNET_TIME_absolute_get(); + res = GNUNET_PQ_eval_prepared_multi_select(plugin->dbh, + "get_closest", + params, + &extract_result_cb, + &erc); if (0 > res) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ending iteration (postgres error)\n"); - return 0; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ending iteration (postgres error)\n"); + return 0; + } if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == res) - { - /* no result */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ending iteration (no more results)\n"); - return 0; - } + { + /* no result */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ending iteration (no more results)\n"); + return 0; + } return res; } @@ -668,30 +663,30 @@ postgres_plugin_get_closest (void *cls, * @return the plugin's closure (our `struct Plugin`) */ void * -libgnunet_plugin_datacache_postgres_init (void *cls) +libgnunet_plugin_datacache_postgres_init(void *cls) { struct GNUNET_DATACACHE_PluginEnvironment *env = cls; struct GNUNET_DATACACHE_PluginFunctions *api; struct Plugin *plugin; - plugin = GNUNET_new (struct Plugin); + plugin = GNUNET_new(struct Plugin); plugin->env = env; - if (GNUNET_OK != init_connection (plugin)) - { - GNUNET_free (plugin); - return NULL; - } + if (GNUNET_OK != init_connection(plugin)) + { + GNUNET_free(plugin); + return NULL; + } - api = GNUNET_new (struct GNUNET_DATACACHE_PluginFunctions); + api = GNUNET_new(struct GNUNET_DATACACHE_PluginFunctions); api->cls = plugin; api->get = &postgres_plugin_get; api->put = &postgres_plugin_put; api->del = &postgres_plugin_del; api->get_random = &postgres_plugin_get_random; api->get_closest = &postgres_plugin_get_closest; - LOG (GNUNET_ERROR_TYPE_INFO, - "Postgres datacache running\n"); + LOG(GNUNET_ERROR_TYPE_INFO, + "Postgres datacache running\n"); return api; } @@ -703,14 +698,14 @@ libgnunet_plugin_datacache_postgres_init (void *cls) * @return NULL */ void * -libgnunet_plugin_datacache_postgres_done (void *cls) +libgnunet_plugin_datacache_postgres_done(void *cls) { struct GNUNET_DATACACHE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - PQfinish (plugin->dbh); - GNUNET_free (plugin); - GNUNET_free (api); + PQfinish(plugin->dbh); + GNUNET_free(plugin); + GNUNET_free(api); return NULL; } diff --git a/src/datacache/plugin_datacache_sqlite.c b/src/datacache/plugin_datacache_sqlite.c index 0cf77d6e6..3b901725e 100644 --- a/src/datacache/plugin_datacache_sqlite.c +++ b/src/datacache/plugin_datacache_sqlite.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datacache/plugin_datacache_sqlite.c @@ -29,23 +29,22 @@ #include "gnunet_sq_lib.h" #include -#define LOG(kind, ...) GNUNET_log_from (kind, "datacache-sqlite", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "datacache-sqlite", __VA_ARGS__) #define LOG_STRERROR_FILE(kind, op, fn) \ - GNUNET_log_from_strerror_file (kind, "datacache-sqlite", op, fn) + GNUNET_log_from_strerror_file(kind, "datacache-sqlite", op, fn) /** * How much overhead do we assume per entry in the * datacache? */ -#define OVERHEAD (sizeof (struct GNUNET_HashCode) + 36) +#define OVERHEAD (sizeof(struct GNUNET_HashCode) + 36) /** * Context for all functions in this plugin. */ -struct Plugin -{ +struct Plugin { /** * Our execution environment. */ @@ -118,14 +117,14 @@ struct Plugin */ #define LOG_SQLITE(db, level, cmd) \ do \ - { \ - LOG (level, \ - _ ("`%s' failed at %s:%d with error: %s\n"), \ - cmd, \ - __FILE__, \ - __LINE__, \ - sqlite3_errmsg (db)); \ - } while (0) + { \ + LOG(level, \ + _("`%s' failed at %s:%d with error: %s\n"), \ + cmd, \ + __FILE__, \ + __LINE__, \ + sqlite3_errmsg(db)); \ + } while (0) /** @@ -136,19 +135,19 @@ struct Plugin */ #define SQLITE3_EXEC(db, cmd) \ do \ - { \ - emsg = NULL; \ - if (SQLITE_OK != sqlite3_exec (db, cmd, NULL, NULL, &emsg)) \ - { \ - LOG (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, \ - _ ("`%s' failed at %s:%d with error: %s\n"), \ - "sqlite3_exec", \ - __FILE__, \ - __LINE__, \ - emsg); \ - sqlite3_free (emsg); \ - } \ - } while (0) + { \ + emsg = NULL; \ + if (SQLITE_OK != sqlite3_exec(db, cmd, NULL, NULL, &emsg)) \ + { \ + LOG(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, \ + _("`%s' failed at %s:%d with error: %s\n"), \ + "sqlite3_exec", \ + __FILE__, \ + __LINE__, \ + emsg); \ + sqlite3_free(emsg); \ + } \ + } while (0) /** @@ -160,17 +159,17 @@ struct Plugin * @return 0 on success */ static int -sq_prepare (sqlite3 *dbh, - const char *zSql, /* SQL statement, UTF-8 encoded */ - sqlite3_stmt **ppStmt) +sq_prepare(sqlite3 *dbh, + const char *zSql, /* SQL statement, UTF-8 encoded */ + sqlite3_stmt **ppStmt) { /* OUT: Statement handle */ char *dummy; - return sqlite3_prepare (dbh, - zSql, - strlen (zSql), - ppStmt, - (const char **) &dummy); + return sqlite3_prepare(dbh, + zSql, + strlen(zSql), + ppStmt, + (const char **)&dummy); } @@ -189,54 +188,54 @@ sq_prepare (sqlite3 *dbh, * @return 0 if duplicate, -1 on error, number of bytes used otherwise */ static ssize_t -sqlite_plugin_put (void *cls, - const struct GNUNET_HashCode *key, - uint32_t xor_distance, - size_t size, - const char *data, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute discard_time, - unsigned int path_info_len, - const struct GNUNET_PeerIdentity *path_info) +sqlite_plugin_put(void *cls, + const struct GNUNET_HashCode *key, + uint32_t xor_distance, + size_t size, + const char *data, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute discard_time, + unsigned int path_info_len, + const struct GNUNET_PeerIdentity *path_info) { struct Plugin *plugin = cls; uint32_t type32 = type; struct GNUNET_SQ_QueryParam params[] = - {GNUNET_SQ_query_param_uint32 (&type32), - GNUNET_SQ_query_param_absolute_time (&discard_time), - GNUNET_SQ_query_param_auto_from_type (key), - GNUNET_SQ_query_param_uint32 (&xor_distance), - GNUNET_SQ_query_param_fixed_size (data, size), - GNUNET_SQ_query_param_fixed_size (path_info, - path_info_len * - sizeof (struct GNUNET_PeerIdentity)), - GNUNET_SQ_query_param_end}; - - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Processing PUT of %u bytes with key `%s' and expiration %s\n", - (unsigned int) size, - GNUNET_h2s (key), - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining ( - discard_time), - GNUNET_YES)); - if (GNUNET_OK != GNUNET_SQ_bind (plugin->insert_stmt, params)) - { - LOG_SQLITE (plugin->dbh, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_xxx"); - GNUNET_SQ_reset (plugin->dbh, plugin->insert_stmt); - return -1; - } - if (SQLITE_DONE != sqlite3_step (plugin->insert_stmt)) - { - LOG_SQLITE (plugin->dbh, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - GNUNET_SQ_reset (plugin->dbh, plugin->insert_stmt); - return -1; - } + { GNUNET_SQ_query_param_uint32(&type32), + GNUNET_SQ_query_param_absolute_time(&discard_time), + GNUNET_SQ_query_param_auto_from_type(key), + GNUNET_SQ_query_param_uint32(&xor_distance), + GNUNET_SQ_query_param_fixed_size(data, size), + GNUNET_SQ_query_param_fixed_size(path_info, + path_info_len * + sizeof(struct GNUNET_PeerIdentity)), + GNUNET_SQ_query_param_end }; + + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Processing PUT of %u bytes with key `%s' and expiration %s\n", + (unsigned int)size, + GNUNET_h2s(key), + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_remaining( + discard_time), + GNUNET_YES)); + if (GNUNET_OK != GNUNET_SQ_bind(plugin->insert_stmt, params)) + { + LOG_SQLITE(plugin->dbh, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_xxx"); + GNUNET_SQ_reset(plugin->dbh, plugin->insert_stmt); + return -1; + } + if (SQLITE_DONE != sqlite3_step(plugin->insert_stmt)) + { + LOG_SQLITE(plugin->dbh, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + GNUNET_SQ_reset(plugin->dbh, plugin->insert_stmt); + return -1; + } plugin->num_items++; - GNUNET_SQ_reset (plugin->dbh, plugin->insert_stmt); + GNUNET_SQ_reset(plugin->dbh, plugin->insert_stmt); return size + OVERHEAD; } @@ -253,11 +252,11 @@ sqlite_plugin_put (void *cls, * @return the number of results found */ static unsigned int -sqlite_plugin_get (void *cls, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +sqlite_plugin_get(void *cls, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { struct Plugin *plugin = cls; uint32_t type32 = type; @@ -271,100 +270,100 @@ sqlite_plugin_get (void *cls, size_t psize; struct GNUNET_PeerIdentity *path; struct GNUNET_SQ_QueryParam params_count[] = - {GNUNET_SQ_query_param_auto_from_type (key), - GNUNET_SQ_query_param_uint32 (&type32), - GNUNET_SQ_query_param_absolute_time (&now), - GNUNET_SQ_query_param_end}; + { GNUNET_SQ_query_param_auto_from_type(key), + GNUNET_SQ_query_param_uint32(&type32), + GNUNET_SQ_query_param_absolute_time(&now), + GNUNET_SQ_query_param_end }; struct GNUNET_SQ_QueryParam params_select[] = - {GNUNET_SQ_query_param_auto_from_type (key), - GNUNET_SQ_query_param_uint32 (&type32), - GNUNET_SQ_query_param_absolute_time (&now), - GNUNET_SQ_query_param_uint32 (&off), - GNUNET_SQ_query_param_end}; + { GNUNET_SQ_query_param_auto_from_type(key), + GNUNET_SQ_query_param_uint32(&type32), + GNUNET_SQ_query_param_absolute_time(&now), + GNUNET_SQ_query_param_uint32(&off), + GNUNET_SQ_query_param_end }; struct GNUNET_SQ_ResultSpec rs[] = - {GNUNET_SQ_result_spec_variable_size (&dat, &size), - GNUNET_SQ_result_spec_absolute_time (&exp), - GNUNET_SQ_result_spec_variable_size ((void **) &path, &psize), - GNUNET_SQ_result_spec_end}; - - now = GNUNET_TIME_absolute_get (); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Processing GET for key `%s'\n", - GNUNET_h2s (key)); - - if (GNUNET_OK != GNUNET_SQ_bind (plugin->get_count_stmt, params_count)) - { - LOG_SQLITE (plugin->dbh, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_xxx"); - GNUNET_SQ_reset (plugin->dbh, plugin->get_count_stmt); - return 0; - } - if (SQLITE_ROW != sqlite3_step (plugin->get_count_stmt)) - { - LOG_SQLITE (plugin->dbh, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite_step"); - GNUNET_SQ_reset (plugin->dbh, plugin->get_count_stmt); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "No content found when processing GET for key `%s'\n", - GNUNET_h2s (key)); - return 0; - } - total = sqlite3_column_int (plugin->get_count_stmt, 0); - GNUNET_SQ_reset (plugin->dbh, plugin->get_count_stmt); - if ((0 == total) || (NULL == iter)) - { - if (0 == total) - LOG (GNUNET_ERROR_TYPE_DEBUG, - "No content found when processing GET for key `%s'\n", - GNUNET_h2s (key)); - return total; - } + { GNUNET_SQ_result_spec_variable_size(&dat, &size), + GNUNET_SQ_result_spec_absolute_time(&exp), + GNUNET_SQ_result_spec_variable_size((void **)&path, &psize), + GNUNET_SQ_result_spec_end }; - cnt = 0; - off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total); - while (cnt < total) - { - off = (off + 1) % total; - if (GNUNET_OK != GNUNET_SQ_bind (plugin->get_stmt, params_select)) + now = GNUNET_TIME_absolute_get(); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Processing GET for key `%s'\n", + GNUNET_h2s(key)); + + if (GNUNET_OK != GNUNET_SQ_bind(plugin->get_count_stmt, params_count)) { - LOG_SQLITE (plugin->dbh, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_xxx"); - GNUNET_SQ_reset (plugin->dbh, plugin->get_stmt); - return cnt; + LOG_SQLITE(plugin->dbh, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_xxx"); + GNUNET_SQ_reset(plugin->dbh, plugin->get_count_stmt); + return 0; } - if (SQLITE_ROW != sqlite3_step (plugin->get_stmt)) - break; - if (GNUNET_OK != GNUNET_SQ_extract_result (plugin->get_stmt, rs)) + if (SQLITE_ROW != sqlite3_step(plugin->get_count_stmt)) { - GNUNET_break (0); - GNUNET_SQ_reset (plugin->dbh, plugin->get_stmt); - break; + LOG_SQLITE(plugin->dbh, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite_step"); + GNUNET_SQ_reset(plugin->dbh, plugin->get_count_stmt); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "No content found when processing GET for key `%s'\n", + GNUNET_h2s(key)); + return 0; } - if (0 != psize % sizeof (struct GNUNET_PeerIdentity)) + total = sqlite3_column_int(plugin->get_count_stmt, 0); + GNUNET_SQ_reset(plugin->dbh, plugin->get_count_stmt); + if ((0 == total) || (NULL == iter)) { - GNUNET_break (0); - psize = 0; - path = NULL; + if (0 == total) + LOG(GNUNET_ERROR_TYPE_DEBUG, + "No content found when processing GET for key `%s'\n", + GNUNET_h2s(key)); + return total; } - psize /= sizeof (struct GNUNET_PeerIdentity); - cnt++; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Found %u-byte result when processing GET for key `%s'\n", - (unsigned int) size, - GNUNET_h2s (key)); - if (GNUNET_OK != iter (iter_cls, key, size, dat, type, exp, psize, path)) + + cnt = 0; + off = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, total); + while (cnt < total) { - GNUNET_SQ_cleanup_result (rs); - GNUNET_SQ_reset (plugin->dbh, plugin->get_stmt); - break; + off = (off + 1) % total; + if (GNUNET_OK != GNUNET_SQ_bind(plugin->get_stmt, params_select)) + { + LOG_SQLITE(plugin->dbh, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_xxx"); + GNUNET_SQ_reset(plugin->dbh, plugin->get_stmt); + return cnt; + } + if (SQLITE_ROW != sqlite3_step(plugin->get_stmt)) + break; + if (GNUNET_OK != GNUNET_SQ_extract_result(plugin->get_stmt, rs)) + { + GNUNET_break(0); + GNUNET_SQ_reset(plugin->dbh, plugin->get_stmt); + break; + } + if (0 != psize % sizeof(struct GNUNET_PeerIdentity)) + { + GNUNET_break(0); + psize = 0; + path = NULL; + } + psize /= sizeof(struct GNUNET_PeerIdentity); + cnt++; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Found %u-byte result when processing GET for key `%s'\n", + (unsigned int)size, + GNUNET_h2s(key)); + if (GNUNET_OK != iter(iter_cls, key, size, dat, type, exp, psize, path)) + { + GNUNET_SQ_cleanup_result(rs); + GNUNET_SQ_reset(plugin->dbh, plugin->get_stmt); + break; + } + GNUNET_SQ_cleanup_result(rs); + GNUNET_SQ_reset(plugin->dbh, plugin->get_stmt); } - GNUNET_SQ_cleanup_result (rs); - GNUNET_SQ_reset (plugin->dbh, plugin->get_stmt); - } - GNUNET_SQ_reset (plugin->dbh, plugin->get_stmt); + GNUNET_SQ_reset(plugin->dbh, plugin->get_stmt); return cnt; } @@ -377,7 +376,7 @@ sqlite_plugin_get (void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -sqlite_plugin_del (void *cls) +sqlite_plugin_del(void *cls) { struct Plugin *plugin = cls; uint64_t rowid; @@ -386,65 +385,65 @@ sqlite_plugin_del (void *cls) struct GNUNET_HashCode hc; struct GNUNET_TIME_Absolute now; struct GNUNET_SQ_ResultSpec rs[] = - {GNUNET_SQ_result_spec_uint64 (&rowid), - GNUNET_SQ_result_spec_auto_from_type (&hc), - GNUNET_SQ_result_spec_variable_size ((void **) &data, &dsize), - GNUNET_SQ_result_spec_end}; - struct GNUNET_SQ_QueryParam params[] = {GNUNET_SQ_query_param_uint64 (&rowid), - GNUNET_SQ_query_param_end}; + { GNUNET_SQ_result_spec_uint64(&rowid), + GNUNET_SQ_result_spec_auto_from_type(&hc), + GNUNET_SQ_result_spec_variable_size((void **)&data, &dsize), + GNUNET_SQ_result_spec_end }; + struct GNUNET_SQ_QueryParam params[] = { GNUNET_SQ_query_param_uint64(&rowid), + GNUNET_SQ_query_param_end }; struct GNUNET_SQ_QueryParam time_params[] = - {GNUNET_SQ_query_param_absolute_time (&now), GNUNET_SQ_query_param_end}; - - LOG (GNUNET_ERROR_TYPE_DEBUG, "Processing DEL\n"); - now = GNUNET_TIME_absolute_get (); - if (GNUNET_OK != GNUNET_SQ_bind (plugin->del_expired_stmt, time_params)) - { - LOG_SQLITE (plugin->dbh, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind"); - GNUNET_SQ_reset (plugin->dbh, plugin->del_expired_stmt); - return GNUNET_SYSERR; - } - if ((SQLITE_ROW != sqlite3_step (plugin->del_expired_stmt)) || - (GNUNET_OK != GNUNET_SQ_extract_result (plugin->del_expired_stmt, rs))) - { - GNUNET_SQ_reset (plugin->dbh, plugin->del_expired_stmt); - if (SQLITE_ROW != sqlite3_step (plugin->del_select_stmt)) + { GNUNET_SQ_query_param_absolute_time(&now), GNUNET_SQ_query_param_end }; + + LOG(GNUNET_ERROR_TYPE_DEBUG, "Processing DEL\n"); + now = GNUNET_TIME_absolute_get(); + if (GNUNET_OK != GNUNET_SQ_bind(plugin->del_expired_stmt, time_params)) + { + LOG_SQLITE(plugin->dbh, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind"); + GNUNET_SQ_reset(plugin->dbh, plugin->del_expired_stmt); + return GNUNET_SYSERR; + } + if ((SQLITE_ROW != sqlite3_step(plugin->del_expired_stmt)) || + (GNUNET_OK != GNUNET_SQ_extract_result(plugin->del_expired_stmt, rs))) { - LOG_SQLITE (plugin->dbh, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - GNUNET_SQ_reset (plugin->dbh, plugin->del_select_stmt); + GNUNET_SQ_reset(plugin->dbh, plugin->del_expired_stmt); + if (SQLITE_ROW != sqlite3_step(plugin->del_select_stmt)) + { + LOG_SQLITE(plugin->dbh, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + GNUNET_SQ_reset(plugin->dbh, plugin->del_select_stmt); + return GNUNET_SYSERR; + } + if (GNUNET_OK != GNUNET_SQ_extract_result(plugin->del_select_stmt, rs)) + { + GNUNET_SQ_reset(plugin->dbh, plugin->del_select_stmt); + GNUNET_break(0); + return GNUNET_SYSERR; + } + } + GNUNET_SQ_cleanup_result(rs); + GNUNET_SQ_reset(plugin->dbh, plugin->del_select_stmt); + if (GNUNET_OK != GNUNET_SQ_bind(plugin->del_stmt, params)) + { + LOG_SQLITE(plugin->dbh, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind"); + GNUNET_SQ_reset(plugin->dbh, plugin->del_stmt); return GNUNET_SYSERR; } - if (GNUNET_OK != GNUNET_SQ_extract_result (plugin->del_select_stmt, rs)) + if (SQLITE_DONE != sqlite3_step(plugin->del_stmt)) { - GNUNET_SQ_reset (plugin->dbh, plugin->del_select_stmt); - GNUNET_break (0); + LOG_SQLITE(plugin->dbh, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + GNUNET_SQ_reset(plugin->dbh, plugin->del_stmt); return GNUNET_SYSERR; } - } - GNUNET_SQ_cleanup_result (rs); - GNUNET_SQ_reset (plugin->dbh, plugin->del_select_stmt); - if (GNUNET_OK != GNUNET_SQ_bind (plugin->del_stmt, params)) - { - LOG_SQLITE (plugin->dbh, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind"); - GNUNET_SQ_reset (plugin->dbh, plugin->del_stmt); - return GNUNET_SYSERR; - } - if (SQLITE_DONE != sqlite3_step (plugin->del_stmt)) - { - LOG_SQLITE (plugin->dbh, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - GNUNET_SQ_reset (plugin->dbh, plugin->del_stmt); - return GNUNET_SYSERR; - } plugin->num_items--; - plugin->env->delete_notify (plugin->env->cls, &hc, dsize + OVERHEAD); - GNUNET_SQ_reset (plugin->dbh, plugin->del_stmt); + plugin->env->delete_notify(plugin->env->cls, &hc, dsize + OVERHEAD); + GNUNET_SQ_reset(plugin->dbh, plugin->del_stmt); return GNUNET_OK; } @@ -458,9 +457,9 @@ sqlite_plugin_del (void *cls) * @return the number of results found, zero (datacache empty) or one */ static unsigned int -sqlite_plugin_get_random (void *cls, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +sqlite_plugin_get_random(void *cls, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { struct Plugin *plugin = cls; struct GNUNET_TIME_Absolute exp; @@ -471,59 +470,59 @@ sqlite_plugin_get_random (void *cls, uint32_t type; struct GNUNET_PeerIdentity *path; struct GNUNET_HashCode key; - struct GNUNET_SQ_QueryParam params[] = {GNUNET_SQ_query_param_uint32 (&off), - GNUNET_SQ_query_param_end}; + struct GNUNET_SQ_QueryParam params[] = { GNUNET_SQ_query_param_uint32(&off), + GNUNET_SQ_query_param_end }; struct GNUNET_SQ_ResultSpec rs[] = - {GNUNET_SQ_result_spec_variable_size (&dat, &size), - GNUNET_SQ_result_spec_absolute_time (&exp), - GNUNET_SQ_result_spec_variable_size ((void **) &path, &psize), - GNUNET_SQ_result_spec_auto_from_type (&key), - GNUNET_SQ_result_spec_uint32 (&type), - GNUNET_SQ_result_spec_end}; + { GNUNET_SQ_result_spec_variable_size(&dat, &size), + GNUNET_SQ_result_spec_absolute_time(&exp), + GNUNET_SQ_result_spec_variable_size((void **)&path, &psize), + GNUNET_SQ_result_spec_auto_from_type(&key), + GNUNET_SQ_result_spec_uint32(&type), + GNUNET_SQ_result_spec_end }; if (0 == plugin->num_items) return 0; if (NULL == iter) return 1; off = - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, plugin->num_items); - if (GNUNET_OK != GNUNET_SQ_bind (plugin->get_random_stmt, params)) - { - return 0; - } - if (SQLITE_ROW != sqlite3_step (plugin->get_random_stmt)) - { - GNUNET_break (0); - GNUNET_SQ_reset (plugin->dbh, plugin->get_random_stmt); - return 0; - } - if (GNUNET_OK != GNUNET_SQ_extract_result (plugin->get_random_stmt, rs)) - { - GNUNET_break (0); - GNUNET_SQ_reset (plugin->dbh, plugin->get_random_stmt); - return 0; - } - if (0 != psize % sizeof (struct GNUNET_PeerIdentity)) - { - GNUNET_break (0); - psize = 0; - path = NULL; - } - psize /= sizeof (struct GNUNET_PeerIdentity); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Found %u-byte result with key %s when processing GET-RANDOM\n", - (unsigned int) size, - GNUNET_h2s (&key)); - (void) iter (iter_cls, - &key, - size, - dat, - (enum GNUNET_BLOCK_Type) type, - exp, - psize, - path); - GNUNET_SQ_cleanup_result (rs); - GNUNET_SQ_reset (plugin->dbh, plugin->get_random_stmt); + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, plugin->num_items); + if (GNUNET_OK != GNUNET_SQ_bind(plugin->get_random_stmt, params)) + { + return 0; + } + if (SQLITE_ROW != sqlite3_step(plugin->get_random_stmt)) + { + GNUNET_break(0); + GNUNET_SQ_reset(plugin->dbh, plugin->get_random_stmt); + return 0; + } + if (GNUNET_OK != GNUNET_SQ_extract_result(plugin->get_random_stmt, rs)) + { + GNUNET_break(0); + GNUNET_SQ_reset(plugin->dbh, plugin->get_random_stmt); + return 0; + } + if (0 != psize % sizeof(struct GNUNET_PeerIdentity)) + { + GNUNET_break(0); + psize = 0; + path = NULL; + } + psize /= sizeof(struct GNUNET_PeerIdentity); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Found %u-byte result with key %s when processing GET-RANDOM\n", + (unsigned int)size, + GNUNET_h2s(&key)); + (void)iter(iter_cls, + &key, + size, + dat, + (enum GNUNET_BLOCK_Type)type, + exp, + psize, + path); + GNUNET_SQ_cleanup_result(rs); + GNUNET_SQ_reset(plugin->dbh, plugin->get_random_stmt); return 1; } @@ -542,11 +541,11 @@ sqlite_plugin_get_random (void *cls, * @return the number of results found */ static unsigned int -sqlite_plugin_get_closest (void *cls, - const struct GNUNET_HashCode *key, - unsigned int num_results, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +sqlite_plugin_get_closest(void *cls, + const struct GNUNET_HashCode *key, + unsigned int num_results, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { struct Plugin *plugin = cls; uint32_t num_results32 = num_results; @@ -560,58 +559,58 @@ sqlite_plugin_get_closest (void *cls, struct GNUNET_HashCode hc; struct GNUNET_PeerIdentity *path; struct GNUNET_SQ_QueryParam params[] = - {GNUNET_SQ_query_param_auto_from_type (key), - GNUNET_SQ_query_param_absolute_time (&now), - GNUNET_SQ_query_param_uint32 (&num_results32), - GNUNET_SQ_query_param_end}; + { GNUNET_SQ_query_param_auto_from_type(key), + GNUNET_SQ_query_param_absolute_time(&now), + GNUNET_SQ_query_param_uint32(&num_results32), + GNUNET_SQ_query_param_end }; struct GNUNET_SQ_ResultSpec rs[] = - {GNUNET_SQ_result_spec_variable_size (&dat, &size), - GNUNET_SQ_result_spec_absolute_time (&exp), - GNUNET_SQ_result_spec_variable_size ((void **) &path, &psize), - GNUNET_SQ_result_spec_uint32 (&type), - GNUNET_SQ_result_spec_auto_from_type (&hc), - GNUNET_SQ_result_spec_end}; - - now = GNUNET_TIME_absolute_get (); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Processing GET_CLOSEST for key `%s'\n", - GNUNET_h2s (key)); - if (GNUNET_OK != GNUNET_SQ_bind (plugin->get_closest_stmt, params)) - { - LOG_SQLITE (plugin->dbh, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_xxx"); - GNUNET_SQ_reset (plugin->dbh, plugin->get_closest_stmt); - return 0; - } - cnt = 0; - while (SQLITE_ROW == sqlite3_step (plugin->get_closest_stmt)) - { - if (GNUNET_OK != GNUNET_SQ_extract_result (plugin->get_closest_stmt, rs)) + { GNUNET_SQ_result_spec_variable_size(&dat, &size), + GNUNET_SQ_result_spec_absolute_time(&exp), + GNUNET_SQ_result_spec_variable_size((void **)&path, &psize), + GNUNET_SQ_result_spec_uint32(&type), + GNUNET_SQ_result_spec_auto_from_type(&hc), + GNUNET_SQ_result_spec_end }; + + now = GNUNET_TIME_absolute_get(); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Processing GET_CLOSEST for key `%s'\n", + GNUNET_h2s(key)); + if (GNUNET_OK != GNUNET_SQ_bind(plugin->get_closest_stmt, params)) { - GNUNET_break (0); - break; + LOG_SQLITE(plugin->dbh, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_xxx"); + GNUNET_SQ_reset(plugin->dbh, plugin->get_closest_stmt); + return 0; } - if (0 != psize % sizeof (struct GNUNET_PeerIdentity)) - { - GNUNET_break (0); - psize = 0; - path = NULL; - } - psize /= sizeof (struct GNUNET_PeerIdentity); - cnt++; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Found %u-byte result at %s when processing GET_CLOSE\n", - (unsigned int) size, - GNUNET_h2s (&hc)); - if (GNUNET_OK != iter (iter_cls, &hc, size, dat, type, exp, psize, path)) + cnt = 0; + while (SQLITE_ROW == sqlite3_step(plugin->get_closest_stmt)) { - GNUNET_SQ_cleanup_result (rs); - break; + if (GNUNET_OK != GNUNET_SQ_extract_result(plugin->get_closest_stmt, rs)) + { + GNUNET_break(0); + break; + } + if (0 != psize % sizeof(struct GNUNET_PeerIdentity)) + { + GNUNET_break(0); + psize = 0; + path = NULL; + } + psize /= sizeof(struct GNUNET_PeerIdentity); + cnt++; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Found %u-byte result at %s when processing GET_CLOSE\n", + (unsigned int)size, + GNUNET_h2s(&hc)); + if (GNUNET_OK != iter(iter_cls, &hc, size, dat, type, exp, psize, path)) + { + GNUNET_SQ_cleanup_result(rs); + break; + } + GNUNET_SQ_cleanup_result(rs); } - GNUNET_SQ_cleanup_result (rs); - } - GNUNET_SQ_reset (plugin->dbh, plugin->get_closest_stmt); + GNUNET_SQ_reset(plugin->dbh, plugin->get_closest_stmt); return cnt; } @@ -623,7 +622,7 @@ sqlite_plugin_get_closest (void *cls, * @return the plugin's closure (our `struct Plugin`) */ void * -libgnunet_plugin_datacache_sqlite_init (void *cls) +libgnunet_plugin_datacache_sqlite_init(void *cls) { struct GNUNET_DATACACHE_PluginEnvironment *env = cls; struct GNUNET_DATACACHE_PluginFunctions *api; @@ -633,111 +632,111 @@ libgnunet_plugin_datacache_sqlite_init (void *cls) sqlite3 *dbh; char *emsg; - if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "datacache-sqlite", - "IN_MEMORY")) - { - if (SQLITE_OK != sqlite3_open (":memory:", &dbh)) - return NULL; - fn_utf8 = NULL; - } - else - { - fn = GNUNET_DISK_mktemp ("gnunet-datacache"); - if (fn == NULL) + if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "datacache-sqlite", + "IN_MEMORY")) { - GNUNET_break (0); - return NULL; + if (SQLITE_OK != sqlite3_open(":memory:", &dbh)) + return NULL; + fn_utf8 = NULL; } - /* fn should be UTF-8-encoded. If it isn't, it's a bug. */ - fn_utf8 = GNUNET_strdup (fn); - if (SQLITE_OK != sqlite3_open (fn_utf8, &dbh)) + else { - GNUNET_free (fn); - GNUNET_free (fn_utf8); - return NULL; + fn = GNUNET_DISK_mktemp("gnunet-datacache"); + if (fn == NULL) + { + GNUNET_break(0); + return NULL; + } + /* fn should be UTF-8-encoded. If it isn't, it's a bug. */ + fn_utf8 = GNUNET_strdup(fn); + if (SQLITE_OK != sqlite3_open(fn_utf8, &dbh)) + { + GNUNET_free(fn); + GNUNET_free(fn_utf8); + return NULL; + } + GNUNET_free(fn); } - GNUNET_free (fn); - } - - SQLITE3_EXEC (dbh, "PRAGMA temp_store=MEMORY"); - SQLITE3_EXEC (dbh, "PRAGMA locking_mode=EXCLUSIVE"); - SQLITE3_EXEC (dbh, "PRAGMA journal_mode=OFF"); - SQLITE3_EXEC (dbh, "PRAGMA synchronous=OFF"); - SQLITE3_EXEC (dbh, "PRAGMA page_size=4092"); - if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (env->cfg, - "datacache-sqlite", - "IN_MEMORY")) - SQLITE3_EXEC (dbh, "PRAGMA sqlite_temp_store=3"); - - SQLITE3_EXEC (dbh, - "CREATE TABLE ds091 (" - " type INTEGER NOT NULL DEFAULT 0," - " expire INTEGER NOT NULL," - " key BLOB NOT NULL DEFAULT ''," - " prox INTEGER NOT NULL," - " value BLOB NOT NULL," - " path BLOB DEFAULT '')"); - SQLITE3_EXEC (dbh, "CREATE INDEX idx_hashidx ON ds091 (key,type,expire)"); - SQLITE3_EXEC (dbh, "CREATE INDEX idx_prox_expire ON ds091 (prox,expire)"); - SQLITE3_EXEC (dbh, "CREATE INDEX idx_expire_only ON ds091 (expire)"); - plugin = GNUNET_new (struct Plugin); + + SQLITE3_EXEC(dbh, "PRAGMA temp_store=MEMORY"); + SQLITE3_EXEC(dbh, "PRAGMA locking_mode=EXCLUSIVE"); + SQLITE3_EXEC(dbh, "PRAGMA journal_mode=OFF"); + SQLITE3_EXEC(dbh, "PRAGMA synchronous=OFF"); + SQLITE3_EXEC(dbh, "PRAGMA page_size=4092"); + if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(env->cfg, + "datacache-sqlite", + "IN_MEMORY")) + SQLITE3_EXEC(dbh, "PRAGMA sqlite_temp_store=3"); + + SQLITE3_EXEC(dbh, + "CREATE TABLE ds091 (" + " type INTEGER NOT NULL DEFAULT 0," + " expire INTEGER NOT NULL," + " key BLOB NOT NULL DEFAULT ''," + " prox INTEGER NOT NULL," + " value BLOB NOT NULL," + " path BLOB DEFAULT '')"); + SQLITE3_EXEC(dbh, "CREATE INDEX idx_hashidx ON ds091 (key,type,expire)"); + SQLITE3_EXEC(dbh, "CREATE INDEX idx_prox_expire ON ds091 (prox,expire)"); + SQLITE3_EXEC(dbh, "CREATE INDEX idx_expire_only ON ds091 (expire)"); + plugin = GNUNET_new(struct Plugin); plugin->env = env; plugin->dbh = dbh; plugin->fn = fn_utf8; if ((SQLITE_OK != - sq_prepare (plugin->dbh, - "INSERT INTO ds091 (type, expire, key, prox, value, path) " - "VALUES (?, ?, ?, ?, ?, ?)", - &plugin->insert_stmt)) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT count(*) FROM ds091 " - "WHERE key=? AND type=? AND expire >= ?", - &plugin->get_count_stmt)) || + sq_prepare(plugin->dbh, + "INSERT INTO ds091 (type, expire, key, prox, value, path) " + "VALUES (?, ?, ?, ?, ?, ?)", + &plugin->insert_stmt)) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT count(*) FROM ds091 " + "WHERE key=? AND type=? AND expire >= ?", + &plugin->get_count_stmt)) || (SQLITE_OK != - sq_prepare (plugin->dbh, - "SELECT value,expire,path FROM ds091" - " WHERE key=? AND type=? AND expire >= ? LIMIT 1 OFFSET ?", - &plugin->get_stmt)) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT _ROWID_,key,value FROM ds091" - " WHERE expire < ?" - " ORDER BY expire ASC LIMIT 1", - &plugin->del_expired_stmt)) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT _ROWID_,key,value FROM ds091" - " ORDER BY prox ASC, expire ASC LIMIT 1", - &plugin->del_select_stmt)) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "DELETE FROM ds091 WHERE _ROWID_=?", - &plugin->del_stmt)) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT value,expire,path,key,type FROM ds091 " - "ORDER BY key LIMIT 1 OFFSET ?", - &plugin->get_random_stmt)) || + sq_prepare(plugin->dbh, + "SELECT value,expire,path FROM ds091" + " WHERE key=? AND type=? AND expire >= ? LIMIT 1 OFFSET ?", + &plugin->get_stmt)) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT _ROWID_,key,value FROM ds091" + " WHERE expire < ?" + " ORDER BY expire ASC LIMIT 1", + &plugin->del_expired_stmt)) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT _ROWID_,key,value FROM ds091" + " ORDER BY prox ASC, expire ASC LIMIT 1", + &plugin->del_select_stmt)) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "DELETE FROM ds091 WHERE _ROWID_=?", + &plugin->del_stmt)) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT value,expire,path,key,type FROM ds091 " + "ORDER BY key LIMIT 1 OFFSET ?", + &plugin->get_random_stmt)) || (SQLITE_OK != - sq_prepare (plugin->dbh, - "SELECT value,expire,path,type,key FROM ds091 " - "WHERE key>=? AND expire >= ? ORDER BY KEY ASC LIMIT ?", - &plugin->get_closest_stmt))) - { - LOG_SQLITE (plugin->dbh, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sq_prepare"); - GNUNET_break (SQLITE_OK == sqlite3_close (plugin->dbh)); - GNUNET_free (plugin); - return NULL; - } - - api = GNUNET_new (struct GNUNET_DATACACHE_PluginFunctions); + sq_prepare(plugin->dbh, + "SELECT value,expire,path,type,key FROM ds091 " + "WHERE key>=? AND expire >= ? ORDER BY KEY ASC LIMIT ?", + &plugin->get_closest_stmt))) + { + LOG_SQLITE(plugin->dbh, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sq_prepare"); + GNUNET_break(SQLITE_OK == sqlite3_close(plugin->dbh)); + GNUNET_free(plugin); + return NULL; + } + + api = GNUNET_new(struct GNUNET_DATACACHE_PluginFunctions); api->cls = plugin; api->get = &sqlite_plugin_get; api->put = &sqlite_plugin_put; api->del = &sqlite_plugin_del; api->get_random = &sqlite_plugin_get_random; api->get_closest = &sqlite_plugin_get_closest; - LOG (GNUNET_ERROR_TYPE_INFO, "Sqlite datacache running\n"); + LOG(GNUNET_ERROR_TYPE_INFO, "Sqlite datacache running\n"); return api; } @@ -749,7 +748,7 @@ libgnunet_plugin_datacache_sqlite_init (void *cls) * @return NULL */ void * -libgnunet_plugin_datacache_sqlite_done (void *cls) +libgnunet_plugin_datacache_sqlite_done(void *cls) { struct GNUNET_DATACACHE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; @@ -759,50 +758,50 @@ libgnunet_plugin_datacache_sqlite_done (void *cls) sqlite3_stmt *stmt; #endif -#if ! WINDOWS || defined(__CYGWIN__) - if ((NULL != plugin->fn) && (0 != unlink (plugin->fn))) - LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", plugin->fn); - GNUNET_free_non_null (plugin->fn); +#if !WINDOWS || defined(__CYGWIN__) + if ((NULL != plugin->fn) && (0 != unlink(plugin->fn))) + LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "unlink", plugin->fn); + GNUNET_free_non_null(plugin->fn); #endif - sqlite3_finalize (plugin->insert_stmt); - sqlite3_finalize (plugin->get_count_stmt); - sqlite3_finalize (plugin->get_stmt); - sqlite3_finalize (plugin->del_select_stmt); - sqlite3_finalize (plugin->del_expired_stmt); - sqlite3_finalize (plugin->del_stmt); - sqlite3_finalize (plugin->get_random_stmt); - sqlite3_finalize (plugin->get_closest_stmt); - result = sqlite3_close (plugin->dbh); + sqlite3_finalize(plugin->insert_stmt); + sqlite3_finalize(plugin->get_count_stmt); + sqlite3_finalize(plugin->get_stmt); + sqlite3_finalize(plugin->del_select_stmt); + sqlite3_finalize(plugin->del_expired_stmt); + sqlite3_finalize(plugin->del_stmt); + sqlite3_finalize(plugin->get_random_stmt); + sqlite3_finalize(plugin->get_closest_stmt); + result = sqlite3_close(plugin->dbh); #if SQLITE_VERSION_NUMBER >= 3007000 if (SQLITE_BUSY == result) - { - LOG (GNUNET_ERROR_TYPE_WARNING, - _ ( - "Tried to close sqlite without finalizing all prepared statements.\n")); - stmt = sqlite3_next_stmt (plugin->dbh, NULL); - while (NULL != stmt) { - result = sqlite3_finalize (stmt); - if (result != SQLITE_OK) - LOG (GNUNET_ERROR_TYPE_WARNING, - "Failed to close statement %p: %d\n", - stmt, - result); - stmt = sqlite3_next_stmt (plugin->dbh, NULL); + LOG(GNUNET_ERROR_TYPE_WARNING, + _( + "Tried to close sqlite without finalizing all prepared statements.\n")); + stmt = sqlite3_next_stmt(plugin->dbh, NULL); + while (NULL != stmt) + { + result = sqlite3_finalize(stmt); + if (result != SQLITE_OK) + LOG(GNUNET_ERROR_TYPE_WARNING, + "Failed to close statement %p: %d\n", + stmt, + result); + stmt = sqlite3_next_stmt(plugin->dbh, NULL); + } + result = sqlite3_close(plugin->dbh); } - result = sqlite3_close (plugin->dbh); - } #endif if (SQLITE_OK != result) - LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close"); + LOG_SQLITE(plugin->dbh, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close"); -#if WINDOWS && ! defined(__CYGWIN__) - if ((NULL != plugin->fn) && (0 != unlink (plugin->fn))) - LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", plugin->fn); - GNUNET_free_non_null (plugin->fn); +#if WINDOWS && !defined(__CYGWIN__) + if ((NULL != plugin->fn) && (0 != unlink(plugin->fn))) + LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "unlink", plugin->fn); + GNUNET_free_non_null(plugin->fn); #endif - GNUNET_free (plugin); - GNUNET_free (api); + GNUNET_free(plugin); + GNUNET_free(api); return NULL; } diff --git a/src/datacache/plugin_datacache_template.c b/src/datacache/plugin_datacache_template.c index 4775968c3..4c322d3ab 100644 --- a/src/datacache/plugin_datacache_template.c +++ b/src/datacache/plugin_datacache_template.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datacache/plugin_datacache_template.c @@ -31,8 +31,7 @@ /** * Context for all functions in this plugin. */ -struct Plugin -{ +struct Plugin { /** * Our execution environment. */ @@ -55,17 +54,17 @@ struct Plugin * @return 0 if duplicate, -1 on error, number of bytes used otherwise */ static ssize_t -template_plugin_put (void *cls, - const struct GNUNET_HashCode *key, - uint32_t xor_distance, - size_t size, - const char *data, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute discard_time, - unsigned int path_info_len, - const struct GNUNET_PeerIdentity *path_info) +template_plugin_put(void *cls, + const struct GNUNET_HashCode *key, + uint32_t xor_distance, + size_t size, + const char *data, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute discard_time, + unsigned int path_info_len, + const struct GNUNET_PeerIdentity *path_info) { - GNUNET_break (0); + GNUNET_break(0); return -1; } @@ -82,13 +81,13 @@ template_plugin_put (void *cls, * @return the number of results found */ static unsigned int -template_plugin_get (void *cls, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +template_plugin_get(void *cls, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { - GNUNET_break (0); + GNUNET_break(0); return 0; } @@ -101,9 +100,9 @@ template_plugin_get (void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -template_plugin_del (void *cls) +template_plugin_del(void *cls) { - GNUNET_break (0); + GNUNET_break(0); return GNUNET_SYSERR; } @@ -117,11 +116,11 @@ template_plugin_del (void *cls) * @return the number of results found (zero or one) */ static unsigned int -template_plugin_get_random (void *cls, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +template_plugin_get_random(void *cls, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { - GNUNET_break (0); + GNUNET_break(0); return 0; } @@ -141,13 +140,13 @@ template_plugin_get_random (void *cls, * @return the number of results found */ static unsigned int -template_plugin_get_closest (void *cls, - const struct GNUNET_HashCode *key, - unsigned int num_results, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls) +template_plugin_get_closest(void *cls, + const struct GNUNET_HashCode *key, + unsigned int num_results, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls) { - GNUNET_break (0); + GNUNET_break(0); return 0; } @@ -159,24 +158,24 @@ template_plugin_get_closest (void *cls, * @return the plugin's closure (our `struct Plugin`) */ void * -libgnunet_plugin_datacache_template_init (void *cls) +libgnunet_plugin_datacache_template_init(void *cls) { struct GNUNET_DATACACHE_PluginEnvironment *env = cls; struct GNUNET_DATACACHE_PluginFunctions *api; struct Plugin *plugin; - plugin = GNUNET_new (struct Plugin); + plugin = GNUNET_new(struct Plugin); plugin->env = env; - api = GNUNET_new (struct GNUNET_DATACACHE_PluginFunctions); + api = GNUNET_new(struct GNUNET_DATACACHE_PluginFunctions); api->cls = plugin; api->get = &template_plugin_get; api->put = &template_plugin_put; api->del = &template_plugin_del; api->get_random = &template_plugin_get_random; api->get_closest = &template_plugin_get_closest; - GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, - "template", - "Template datacache running\n"); + GNUNET_log_from(GNUNET_ERROR_TYPE_INFO, + "template", + "Template datacache running\n"); return api; } @@ -188,13 +187,13 @@ libgnunet_plugin_datacache_template_init (void *cls) * @return NULL */ void * -libgnunet_plugin_datacache_template_done (void *cls) +libgnunet_plugin_datacache_template_done(void *cls) { struct GNUNET_DATACACHE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - GNUNET_free (plugin); - GNUNET_free (api); + GNUNET_free(plugin); + GNUNET_free(api); return NULL; } diff --git a/src/datacache/test_datacache.c b/src/datacache/test_datacache.c index 572a775df..30ef81a70 100644 --- a/src/datacache/test_datacache.c +++ b/src/datacache/test_datacache.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /* * @file datacache/test_datacache.c * @brief Test for the datacache implementations. @@ -27,7 +27,7 @@ #include "gnunet_datacache_lib.h" #include "gnunet_testing_lib.h" -#define ASSERT(x) do { if (! (x)) { printf("Error at %s:%d\n", __FILE__, __LINE__); goto FAILURE;} } while (0) +#define ASSERT(x) do { if (!(x)) { printf("Error at %s:%d\n", __FILE__, __LINE__); goto FAILURE; } } while (0) static int ok; @@ -38,122 +38,122 @@ static const char *plugin_name; static int -checkIt (void *cls, - const struct GNUNET_HashCode *key, - size_t size, const char *data, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute exp, - unsigned int path_len, - const struct GNUNET_PeerIdentity *path) +checkIt(void *cls, + const struct GNUNET_HashCode *key, + size_t size, const char *data, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute exp, + unsigned int path_len, + const struct GNUNET_PeerIdentity *path) { - (void) key; - (void) type; - (void) exp; - (void) path_len; - (void) path; - if (size != sizeof (struct GNUNET_HashCode)) - { - GNUNET_break (0); - ok = 2; - } - if (0 != memcmp (data, cls, size)) - { - GNUNET_break (0); - ok = 3; - } + (void)key; + (void)type; + (void)exp; + (void)path_len; + (void)path; + if (size != sizeof(struct GNUNET_HashCode)) + { + GNUNET_break(0); + ok = 2; + } + if (0 != memcmp(data, cls, size)) + { + GNUNET_break(0); + ok = 3; + } return GNUNET_OK; } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_DATACACHE_Handle *h; struct GNUNET_HashCode k; struct GNUNET_HashCode n; struct GNUNET_TIME_Absolute exp; - (void) cls; - (void) args; - (void) cfgfile; + (void)cls; + (void)args; + (void)cfgfile; ok = 0; - h = GNUNET_DATACACHE_create (cfg, - "testcache"); + h = GNUNET_DATACACHE_create(cfg, + "testcache"); if (h == NULL) - { - fprintf (stderr, - "%s", - "Failed to initialize datacache. Database likely not setup, skipping test.\n"); - ok = 77; /* mark test as skipped */ - return; - } - exp = GNUNET_TIME_absolute_get (); + { + fprintf(stderr, + "%s", + "Failed to initialize datacache. Database likely not setup, skipping test.\n"); + ok = 77; /* mark test as skipped */ + return; + } + exp = GNUNET_TIME_absolute_get(); exp.abs_value_us += 5 * 60 * 1000 * 1000LL; - memset (&k, 0, sizeof (struct GNUNET_HashCode)); + memset(&k, 0, sizeof(struct GNUNET_HashCode)); for (unsigned int i = 0; i < 100; i++) - { - GNUNET_CRYPTO_hash (&k, sizeof (struct GNUNET_HashCode), &n); - ASSERT (GNUNET_OK == - GNUNET_DATACACHE_put (h, + { + GNUNET_CRYPTO_hash(&k, sizeof(struct GNUNET_HashCode), &n); + ASSERT(GNUNET_OK == + GNUNET_DATACACHE_put(h, &k, GNUNET_YES, - sizeof (struct GNUNET_HashCode), - (const char *) &n, 1 + i % 16, exp, - 0, NULL)); - k = n; - } - memset (&k, - 0, - sizeof (struct GNUNET_HashCode)); + sizeof(struct GNUNET_HashCode), + (const char *)&n, 1 + i % 16, exp, + 0, NULL)); + k = n; + } + memset(&k, + 0, + sizeof(struct GNUNET_HashCode)); for (unsigned int i = 0; i < 100; i++) - { - GNUNET_CRYPTO_hash (&k, - sizeof (struct GNUNET_HashCode), - &n); - ASSERT (1 == GNUNET_DATACACHE_get (h, - &k, - 1 + i % 16, - &checkIt, - &n)); - k = n; - } - - memset (&k, - 42, - sizeof (struct GNUNET_HashCode)); - GNUNET_CRYPTO_hash (&k, - sizeof (struct GNUNET_HashCode), - &n); - ASSERT (GNUNET_OK == - GNUNET_DATACACHE_put (h, - &k, - GNUNET_YES, - sizeof (struct GNUNET_HashCode), - (const char *) &n, - 792, - GNUNET_TIME_UNIT_FOREVER_ABS, - 0, - NULL)); - ASSERT (0 != GNUNET_DATACACHE_get (h, - &k, - 792, - &checkIt, - &n)); - GNUNET_DATACACHE_destroy (h); - ASSERT (ok == 0); + { + GNUNET_CRYPTO_hash(&k, + sizeof(struct GNUNET_HashCode), + &n); + ASSERT(1 == GNUNET_DATACACHE_get(h, + &k, + 1 + i % 16, + &checkIt, + &n)); + k = n; + } + + memset(&k, + 42, + sizeof(struct GNUNET_HashCode)); + GNUNET_CRYPTO_hash(&k, + sizeof(struct GNUNET_HashCode), + &n); + ASSERT(GNUNET_OK == + GNUNET_DATACACHE_put(h, + &k, + GNUNET_YES, + sizeof(struct GNUNET_HashCode), + (const char *)&n, + 792, + GNUNET_TIME_UNIT_FOREVER_ABS, + 0, + NULL)); + ASSERT(0 != GNUNET_DATACACHE_get(h, + &k, + 792, + &checkIt, + &n)); + GNUNET_DATACACHE_destroy(h); + ASSERT(ok == 0); return; FAILURE: if (h != NULL) - GNUNET_DATACACHE_destroy (h); + GNUNET_DATACACHE_destroy(h); ok = GNUNET_SYSERR; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { char cfg_name[PATH_MAX]; char *const xargv[] = { @@ -166,26 +166,26 @@ main (int argc, char *argv[]) GNUNET_GETOPT_OPTION_END }; - (void) argc; - GNUNET_log_setup ("test-datacache", - "WARNING", - NULL); - plugin_name = GNUNET_TESTING_get_testname_from_underscore (argv[0]); - GNUNET_snprintf (cfg_name, - sizeof (cfg_name), - "test_datacache_data_%s.conf", - plugin_name); - GNUNET_PROGRAM_run ((sizeof (xargv) / sizeof (char *)) - 1, - xargv, - "test-datacache", - "nohelp", - options, - &run, - NULL); - if ( (0 != ok) && (77 != ok) ) - fprintf (stderr, - "Missed some testcases: %d\n", - ok); + (void)argc; + GNUNET_log_setup("test-datacache", + "WARNING", + NULL); + plugin_name = GNUNET_TESTING_get_testname_from_underscore(argv[0]); + GNUNET_snprintf(cfg_name, + sizeof(cfg_name), + "test_datacache_data_%s.conf", + plugin_name); + GNUNET_PROGRAM_run((sizeof(xargv) / sizeof(char *)) - 1, + xargv, + "test-datacache", + "nohelp", + options, + &run, + NULL); + if ((0 != ok) && (77 != ok)) + fprintf(stderr, + "Missed some testcases: %d\n", + ok); return ok; } diff --git a/src/datacache/test_datacache_quota.c b/src/datacache/test_datacache_quota.c index 0201df3b3..36e369abb 100644 --- a/src/datacache/test_datacache_quota.c +++ b/src/datacache/test_datacache_quota.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /* * @file datacache/test_datacache_quota.c * @brief Test for the quota code of the datacache implementations. @@ -27,7 +27,7 @@ #include "gnunet_datacache_lib.h" #include "gnunet_testing_lib.h" -#define ASSERT(x) do { if (! (x)) { printf("Error at %s:%d\n", __FILE__, __LINE__); goto FAILURE;} } while (0) +#define ASSERT(x) do { if (!(x)) { printf("Error at %s:%d\n", __FILE__, __LINE__); goto FAILURE; } } while (0) static int ok; @@ -43,10 +43,10 @@ static const char *plugin_name; * some of the data from the last iteration is still there. */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_DATACACHE_Handle *h; struct GNUNET_HashCode k; @@ -54,74 +54,74 @@ run (void *cls, char buf[3200]; struct GNUNET_TIME_Absolute exp; - (void) cls; - (void) args; - (void) cfgfile; + (void)cls; + (void)args; + (void)cfgfile; ok = 0; - h = GNUNET_DATACACHE_create (cfg, - "testcache"); + h = GNUNET_DATACACHE_create(cfg, + "testcache"); if (h == NULL) - { - fprintf (stderr, - "%s", - "Failed to initialize datacache. Database likely not setup, skipping test.\n"); - return; - } - exp = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS); - memset (buf, 1, sizeof (buf)); - memset (&k, 0, sizeof (struct GNUNET_HashCode)); + { + fprintf(stderr, + "%s", + "Failed to initialize datacache. Database likely not setup, skipping test.\n"); + return; + } + exp = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS); + memset(buf, 1, sizeof(buf)); + memset(&k, 0, sizeof(struct GNUNET_HashCode)); for (unsigned int i = 0; i < 10; i++) - { - fprintf (stderr, - "%s", - "."); - GNUNET_CRYPTO_hash (&k, - sizeof (struct GNUNET_HashCode), - &n); - for (unsigned int j = i; j < sizeof (buf); j += 10) { - exp.abs_value_us++; - buf[j] = i; - ASSERT (GNUNET_OK == - GNUNET_DATACACHE_put (h, - &k, - GNUNET_YES, - j, - buf, - 1 + i, - exp, - 0, - NULL)); - ASSERT (0 < GNUNET_DATACACHE_get (h, &k, 1 + i, NULL, NULL)); + fprintf(stderr, + "%s", + "."); + GNUNET_CRYPTO_hash(&k, + sizeof(struct GNUNET_HashCode), + &n); + for (unsigned int j = i; j < sizeof(buf); j += 10) + { + exp.abs_value_us++; + buf[j] = i; + ASSERT(GNUNET_OK == + GNUNET_DATACACHE_put(h, + &k, + GNUNET_YES, + j, + buf, + 1 + i, + exp, + 0, + NULL)); + ASSERT(0 < GNUNET_DATACACHE_get(h, &k, 1 + i, NULL, NULL)); + } + k = n; } - k = n; - } - fprintf (stderr, "%s", "\n"); - memset (&k, 0, sizeof (struct GNUNET_HashCode)); + fprintf(stderr, "%s", "\n"); + memset(&k, 0, sizeof(struct GNUNET_HashCode)); for (unsigned int i = 0; i < 10; i++) - { - fprintf (stderr, "%s", "."); - GNUNET_CRYPTO_hash (&k, sizeof (struct GNUNET_HashCode), &n); - if (i < 2) - ASSERT (0 == GNUNET_DATACACHE_get (h, &k, 1 + i, NULL, NULL)); - if (i == 9) - ASSERT (0 < GNUNET_DATACACHE_get (h, &k, 1 + i, NULL, NULL)); - k = n; - } - fprintf (stderr, "%s", "\n"); - GNUNET_DATACACHE_destroy (h); + { + fprintf(stderr, "%s", "."); + GNUNET_CRYPTO_hash(&k, sizeof(struct GNUNET_HashCode), &n); + if (i < 2) + ASSERT(0 == GNUNET_DATACACHE_get(h, &k, 1 + i, NULL, NULL)); + if (i == 9) + ASSERT(0 < GNUNET_DATACACHE_get(h, &k, 1 + i, NULL, NULL)); + k = n; + } + fprintf(stderr, "%s", "\n"); + GNUNET_DATACACHE_destroy(h); return; FAILURE: if (h != NULL) - GNUNET_DATACACHE_destroy (h); + GNUNET_DATACACHE_destroy(h); ok = GNUNET_SYSERR; } int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { char cfg_name[PATH_MAX]; char *const xargv[] = { @@ -134,27 +134,27 @@ main (int argc, GNUNET_GETOPT_OPTION_END }; - (void) argc; - GNUNET_log_setup ("test-datacache-quota", - "WARNING", - NULL); + (void)argc; + GNUNET_log_setup("test-datacache-quota", + "WARNING", + NULL); - plugin_name = GNUNET_TESTING_get_testname_from_underscore (argv[0]); - GNUNET_snprintf (cfg_name, - sizeof (cfg_name), - "test_datacache_data_%s.conf", - plugin_name); - GNUNET_PROGRAM_run ((sizeof (xargv) / sizeof (char *)) - 1, - xargv, - "test-datacache-quota", - "nohelp", - options, - &run, - NULL); + plugin_name = GNUNET_TESTING_get_testname_from_underscore(argv[0]); + GNUNET_snprintf(cfg_name, + sizeof(cfg_name), + "test_datacache_data_%s.conf", + plugin_name); + GNUNET_PROGRAM_run((sizeof(xargv) / sizeof(char *)) - 1, + xargv, + "test-datacache-quota", + "nohelp", + options, + &run, + NULL); if (0 != ok) - fprintf (stderr, - "Missed some testcases: %d\n", - ok); + fprintf(stderr, + "Missed some testcases: %d\n", + ok); return ok; } diff --git a/src/datastore/datastore.h b/src/datastore/datastore.h index c2a20b9d3..b4a51dc02 100644 --- a/src/datastore/datastore.h +++ b/src/datastore/datastore.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datastore/datastore.h @@ -36,8 +36,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * Message from datastore service informing client about * the current size of the datastore. */ -struct ReserveMessage -{ +struct ReserveMessage { /** * Type is GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE. */ @@ -61,8 +60,7 @@ struct ReserveMessage * This header is optionally followed by a variable-size, * 0-terminated error message. */ -struct StatusMessage -{ +struct StatusMessage { /** * Type is GNUNET_MESSAGE_TYPE_DATASTORE_STATUS. */ @@ -78,7 +76,6 @@ struct StatusMessage * by the datacache at this time, zero for unknown or no limit. */ struct GNUNET_TIME_AbsoluteNBO min_expiration; - }; @@ -87,8 +84,7 @@ struct StatusMessage * the remainder of the reserved bytes can now be released * for other requests. */ -struct ReleaseReserveMessage -{ +struct ReleaseReserveMessage { /** * Type is GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE. */ @@ -98,7 +94,6 @@ struct ReleaseReserveMessage * Reservation id. */ int32_t rid GNUNET_PACKED; - }; @@ -106,8 +101,7 @@ struct ReleaseReserveMessage * Message to the datastore service asking about specific * content. */ -struct GetKeyMessage -{ +struct GetKeyMessage { /** * Type is #GNUNET_MESSAGE_TYPE_DATASTORE_GET_KEY. */ @@ -132,7 +126,6 @@ struct GetKeyMessage * Desired key. */ struct GNUNET_HashCode key; - }; @@ -140,8 +133,7 @@ struct GetKeyMessage * Message to the datastore service asking about specific * content. */ -struct GetMessage -{ +struct GetMessage { /** * Type is #GNUNET_MESSAGE_TYPE_DATASTORE_GET. */ @@ -161,7 +153,6 @@ struct GetMessage * If true return a random result */ uint32_t random GNUNET_PACKED; - }; @@ -169,8 +160,7 @@ struct GetMessage * Message to the datastore service asking about zero * anonymity content. */ -struct GetZeroAnonymityMessage -{ +struct GetZeroAnonymityMessage { /** * Type is GNUNET_MESSAGE_TYPE_DATASTORE_GET_ZERO_ANONYMITY. */ @@ -185,7 +175,6 @@ struct GetZeroAnonymityMessage * UID at which to start the search */ uint64_t next_uid GNUNET_PACKED; - }; @@ -193,8 +182,7 @@ struct GetZeroAnonymityMessage * Message transmitting content from or to the datastore * service. */ -struct DataMessage -{ +struct DataMessage { /** * Type is either GNUNET_MESSAGE_TYPE_DATASTORE_PUT, * GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE or @@ -255,7 +243,6 @@ struct DataMessage * Key under which the item can be found. */ struct GNUNET_HashCode key; - }; GNUNET_NETWORK_STRUCT_END diff --git a/src/datastore/datastore_api.c b/src/datastore/datastore_api.c index 636dbdd1a..7069975e4 100644 --- a/src/datastore/datastore_api.c +++ b/src/datastore/datastore_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datastore/datastore_api.c @@ -31,7 +31,7 @@ #include "gnunet_statistics_service.h" #include "datastore.h" -#define LOG(kind,...) GNUNET_log_from (kind, "datastore-api",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "datastore-api", __VA_ARGS__) #define DELAY_WARN_TIMEOUT GNUNET_TIME_UNIT_MINUTES @@ -51,8 +51,7 @@ /** * Context for processing status messages. */ -struct StatusContext -{ +struct StatusContext { /** * Continuation to call with the status. */ @@ -62,15 +61,13 @@ struct StatusContext * Closure for @e cont. */ void *cont_cls; - }; /** * Context for processing result messages. */ -struct ResultContext -{ +struct ResultContext { /** * Function to call with the result. */ @@ -80,29 +77,23 @@ struct ResultContext * Closure for @e proc. */ void *proc_cls; - }; /** * Context for a queue operation. */ -union QueueContext -{ - +union QueueContext { struct StatusContext sc; struct ResultContext rc; - }; /** * Entry in our priority queue. */ -struct GNUNET_DATASTORE_QueueEntry -{ - +struct GNUNET_DATASTORE_QueueEntry { /** * This is a linked list. */ @@ -160,16 +151,13 @@ struct GNUNET_DATASTORE_QueueEntry * Expected response type. */ uint16_t response_type; - }; /** * Handle to the datastore service. */ -struct GNUNET_DATASTORE_Handle -{ - +struct GNUNET_DATASTORE_Handle { /** * Our configuration. */ @@ -222,7 +210,6 @@ struct GNUNET_DATASTORE_Handle * We should ignore the next message(s) from the service. */ unsigned int skip_next_messages; - }; @@ -232,7 +219,7 @@ struct GNUNET_DATASTORE_Handle * @param cls the `struct GNUNET_DATASTORE_Handle` */ static void -try_reconnect (void *cls); +try_reconnect(void *cls); /** @@ -242,20 +229,20 @@ try_reconnect (void *cls); * @param h handle to datastore to disconnect and reconnect */ static void -do_disconnect (struct GNUNET_DATASTORE_Handle *h) +do_disconnect(struct GNUNET_DATASTORE_Handle *h) { if (NULL == h->mq) - { - GNUNET_break (0); - return; - } - GNUNET_MQ_destroy (h->mq); + { + GNUNET_break(0); + return; + } + GNUNET_MQ_destroy(h->mq); h->mq = NULL; h->skip_next_messages = 0; h->reconnect_task - = GNUNET_SCHEDULER_add_delayed (h->retry_time, - &try_reconnect, - h); + = GNUNET_SCHEDULER_add_delayed(h->retry_time, + &try_reconnect, + h); } @@ -267,19 +254,19 @@ do_disconnect (struct GNUNET_DATASTORE_Handle *h) * @param qe entry to free. */ static void -free_queue_entry (struct GNUNET_DATASTORE_QueueEntry *qe) +free_queue_entry(struct GNUNET_DATASTORE_QueueEntry *qe) { struct GNUNET_DATASTORE_Handle *h = qe->h; - GNUNET_CONTAINER_DLL_remove (h->queue_head, - h->queue_tail, - qe); + GNUNET_CONTAINER_DLL_remove(h->queue_head, + h->queue_tail, + qe); h->queue_size--; if (NULL != qe->env) - GNUNET_MQ_discard (qe->env); + GNUNET_MQ_discard(qe->env); if (NULL != qe->delay_warn_task) - GNUNET_SCHEDULER_cancel (qe->delay_warn_task); - GNUNET_free (qe); + GNUNET_SCHEDULER_cancel(qe->delay_warn_task); + GNUNET_free(qe); } @@ -289,20 +276,20 @@ free_queue_entry (struct GNUNET_DATASTORE_QueueEntry *qe) * @param qe `struct GNUNET_DATASTORE_QueueEntry` about which the error is */ static void -delay_warning (void *cls) +delay_warning(void *cls) { struct GNUNET_DATASTORE_QueueEntry *qe = cls; qe->delay_warn_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Request %p of type %u at head of datastore queue for more than %s\n", - qe, - (unsigned int) qe->response_type, - GNUNET_STRINGS_relative_time_to_string (DELAY_WARN_TIMEOUT, - GNUNET_YES)); - qe->delay_warn_task = GNUNET_SCHEDULER_add_delayed (DELAY_WARN_TIMEOUT, - &delay_warning, - qe); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Request %p of type %u at head of datastore queue for more than %s\n", + qe, + (unsigned int)qe->response_type, + GNUNET_STRINGS_relative_time_to_string(DELAY_WARN_TIMEOUT, + GNUNET_YES)); + qe->delay_warn_task = GNUNET_SCHEDULER_add_delayed(DELAY_WARN_TIMEOUT, + &delay_warning, + qe); } @@ -313,57 +300,59 @@ delay_warning (void *cls) * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_DATASTORE_Handle *h = cls; struct GNUNET_DATASTORE_QueueEntry *qe; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "MQ error, reconnecting to DATASTORE\n"); - do_disconnect (h); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "MQ error, reconnecting to DATASTORE\n"); + do_disconnect(h); qe = h->queue_head; if (NULL == qe) return; if (NULL != qe->delay_warn_task) - { - GNUNET_SCHEDULER_cancel (qe->delay_warn_task); - qe->delay_warn_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(qe->delay_warn_task); + qe->delay_warn_task = NULL; + } if (NULL == qe->env) - { - union QueueContext qc = qe->qc; - uint16_t rt = qe->response_type; - - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Failed to receive response from database.\n"); - free_queue_entry (qe); - switch (rt) { - case GNUNET_MESSAGE_TYPE_DATASTORE_STATUS: - if (NULL != qc.sc.cont) - qc.sc.cont (qc.sc.cont_cls, - GNUNET_SYSERR, - GNUNET_TIME_UNIT_ZERO_ABS, - _("DATASTORE disconnected")); - break; - case GNUNET_MESSAGE_TYPE_DATASTORE_DATA: - if (NULL != qc.rc.proc) - qc.rc.proc (qc.rc.proc_cls, - NULL, - 0, - NULL, - 0, - 0, - 0, - 0, - GNUNET_TIME_UNIT_ZERO_ABS, - 0); - break; - default: - GNUNET_break (0); + union QueueContext qc = qe->qc; + uint16_t rt = qe->response_type; + + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Failed to receive response from database.\n"); + free_queue_entry(qe); + switch (rt) + { + case GNUNET_MESSAGE_TYPE_DATASTORE_STATUS: + if (NULL != qc.sc.cont) + qc.sc.cont(qc.sc.cont_cls, + GNUNET_SYSERR, + GNUNET_TIME_UNIT_ZERO_ABS, + _("DATASTORE disconnected")); + break; + + case GNUNET_MESSAGE_TYPE_DATASTORE_DATA: + if (NULL != qc.rc.proc) + qc.rc.proc(qc.rc.proc_cls, + NULL, + 0, + NULL, + 0, + 0, + 0, + 0, + GNUNET_TIME_UNIT_ZERO_ABS, + 0); + break; + + default: + GNUNET_break(0); + } } - } } @@ -374,22 +363,22 @@ mq_error_handler (void *cls, * @return handle to use to access the service */ struct GNUNET_DATASTORE_Handle * -GNUNET_DATASTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_DATASTORE_connect(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_DATASTORE_Handle *h; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Establishing DATASTORE connection!\n"); - h = GNUNET_new (struct GNUNET_DATASTORE_Handle); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Establishing DATASTORE connection!\n"); + h = GNUNET_new(struct GNUNET_DATASTORE_Handle); h->cfg = cfg; - try_reconnect (h); + try_reconnect(h); if (NULL == h->mq) - { - GNUNET_free (h); - return NULL; - } - h->stats = GNUNET_STATISTICS_create ("datastore-api", - cfg); + { + GNUNET_free(h); + return NULL; + } + h->stats = GNUNET_STATISTICS_create("datastore-api", + cfg); return h; } @@ -401,14 +390,14 @@ GNUNET_DATASTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) * @param cls the datastore handle */ static void -disconnect_after_drop (void *cls) +disconnect_after_drop(void *cls) { struct GNUNET_DATASTORE_Handle *h = cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Drop sent, disconnecting\n"); - GNUNET_DATASTORE_disconnect (h, - GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Drop sent, disconnecting\n"); + GNUNET_DATASTORE_disconnect(h, + GNUNET_NO); } @@ -419,15 +408,15 @@ disconnect_after_drop (void *cls) * @param error error code */ static void -disconnect_on_mq_error (void *cls, - enum GNUNET_MQ_Error error) +disconnect_on_mq_error(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_DATASTORE_Handle *h = cls; - LOG (GNUNET_ERROR_TYPE_ERROR, - "Failed to ask datastore to drop tables\n"); - GNUNET_DATASTORE_disconnect (h, - GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_ERROR, + "Failed to ask datastore to drop tables\n"); + GNUNET_DATASTORE_disconnect(h, + GNUNET_NO); } @@ -439,82 +428,84 @@ disconnect_on_mq_error (void *cls, * @param drop set to #GNUNET_YES to delete all data in datastore (!) */ void -GNUNET_DATASTORE_disconnect (struct GNUNET_DATASTORE_Handle *h, - int drop) +GNUNET_DATASTORE_disconnect(struct GNUNET_DATASTORE_Handle *h, + int drop) { struct GNUNET_DATASTORE_QueueEntry *qe; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Datastore disconnect\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Datastore disconnect\n"); if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } if (NULL != h->reconnect_task) - { - GNUNET_SCHEDULER_cancel (h->reconnect_task); - h->reconnect_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(h->reconnect_task); + h->reconnect_task = NULL; + } while (NULL != (qe = h->queue_head)) - { - switch (qe->response_type) { - case GNUNET_MESSAGE_TYPE_DATASTORE_STATUS: - if (NULL != qe->qc.sc.cont) - qe->qc.sc.cont (qe->qc.sc.cont_cls, - GNUNET_SYSERR, - GNUNET_TIME_UNIT_ZERO_ABS, - _("Disconnected from DATASTORE")); - break; - case GNUNET_MESSAGE_TYPE_DATASTORE_DATA: - if (NULL != qe->qc.rc.proc) - qe->qc.rc.proc (qe->qc.rc.proc_cls, - NULL, - 0, - NULL, - 0, - 0, - 0, - 0, - GNUNET_TIME_UNIT_ZERO_ABS, - 0); - break; - default: - GNUNET_break (0); + switch (qe->response_type) + { + case GNUNET_MESSAGE_TYPE_DATASTORE_STATUS: + if (NULL != qe->qc.sc.cont) + qe->qc.sc.cont(qe->qc.sc.cont_cls, + GNUNET_SYSERR, + GNUNET_TIME_UNIT_ZERO_ABS, + _("Disconnected from DATASTORE")); + break; + + case GNUNET_MESSAGE_TYPE_DATASTORE_DATA: + if (NULL != qe->qc.rc.proc) + qe->qc.rc.proc(qe->qc.rc.proc_cls, + NULL, + 0, + NULL, + 0, + 0, + 0, + 0, + GNUNET_TIME_UNIT_ZERO_ABS, + 0); + break; + + default: + GNUNET_break(0); + } + free_queue_entry(qe); } - free_queue_entry (qe); - } if (GNUNET_YES == drop) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Re-connecting to issue DROP!\n"); - GNUNET_assert (NULL == h->mq); - h->mq = GNUNET_CLIENT_connect (h->cfg, - "datastore", - NULL, - &disconnect_on_mq_error, - h); - if (NULL != h->mq) { - struct GNUNET_MessageHeader *hdr; - struct GNUNET_MQ_Envelope *env; - - env = GNUNET_MQ_msg (hdr, - GNUNET_MESSAGE_TYPE_DATASTORE_DROP); - GNUNET_MQ_notify_sent (env, - &disconnect_after_drop, - h); - GNUNET_MQ_send (h->mq, - env); - return; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Re-connecting to issue DROP!\n"); + GNUNET_assert(NULL == h->mq); + h->mq = GNUNET_CLIENT_connect(h->cfg, + "datastore", + NULL, + &disconnect_on_mq_error, + h); + if (NULL != h->mq) + { + struct GNUNET_MessageHeader *hdr; + struct GNUNET_MQ_Envelope *env; + + env = GNUNET_MQ_msg(hdr, + GNUNET_MESSAGE_TYPE_DATASTORE_DROP); + GNUNET_MQ_notify_sent(env, + &disconnect_after_drop, + h); + GNUNET_MQ_send(h->mq, + env); + return; + } + GNUNET_break(0); } - GNUNET_break (0); - } - GNUNET_STATISTICS_destroy (h->stats, - GNUNET_NO); + GNUNET_STATISTICS_destroy(h->stats, + GNUNET_NO); h->stats = NULL; - GNUNET_free (h); + GNUNET_free(h); } @@ -534,45 +525,45 @@ GNUNET_DATASTORE_disconnect (struct GNUNET_DATASTORE_Handle *h, * @return NULL if the queue is full */ static struct GNUNET_DATASTORE_QueueEntry * -make_queue_entry (struct GNUNET_DATASTORE_Handle *h, - struct GNUNET_MQ_Envelope *env, - unsigned int queue_priority, - unsigned int max_queue_size, - uint16_t expected_type, - const union QueueContext *qc) +make_queue_entry(struct GNUNET_DATASTORE_Handle *h, + struct GNUNET_MQ_Envelope *env, + unsigned int queue_priority, + unsigned int max_queue_size, + uint16_t expected_type, + const union QueueContext *qc) { struct GNUNET_DATASTORE_QueueEntry *qe; struct GNUNET_DATASTORE_QueueEntry *pos; unsigned int c; - if ( (NULL != h->queue_tail) && - (h->queue_tail->priority >= queue_priority) ) - { - c = h->queue_size; - pos = NULL; - } + if ((NULL != h->queue_tail) && + (h->queue_tail->priority >= queue_priority)) + { + c = h->queue_size; + pos = NULL; + } else - { - c = 0; - pos = h->queue_head; - } - while ( (NULL != pos) && - (c < max_queue_size) && - (pos->priority >= queue_priority) ) - { - c++; - pos = pos->next; - } + { + c = 0; + pos = h->queue_head; + } + while ((NULL != pos) && + (c < max_queue_size) && + (pos->priority >= queue_priority)) + { + c++; + pos = pos->next; + } if (c >= max_queue_size) - { - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# queue overflows"), - 1, - GNUNET_NO); - GNUNET_MQ_discard (env); - return NULL; - } - qe = GNUNET_new (struct GNUNET_DATASTORE_QueueEntry); + { + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# queue overflows"), + 1, + GNUNET_NO); + GNUNET_MQ_discard(env); + return NULL; + } + qe = GNUNET_new(struct GNUNET_DATASTORE_QueueEntry); qe->h = h; qe->env = env; qe->response_type = expected_type; @@ -580,30 +571,30 @@ make_queue_entry (struct GNUNET_DATASTORE_Handle *h, qe->priority = queue_priority; qe->max_queue = max_queue_size; if (NULL == pos) - { - /* append at the tail */ - pos = h->queue_tail; - } + { + /* append at the tail */ + pos = h->queue_tail; + } else - { - pos = pos->prev; - /* do not insert at HEAD if HEAD query was already - * transmitted and we are still receiving replies! */ - if ( (NULL == pos) && - (NULL == h->queue_head->env) ) - pos = h->queue_head; - } + { + pos = pos->prev; + /* do not insert at HEAD if HEAD query was already + * transmitted and we are still receiving replies! */ + if ((NULL == pos) && + (NULL == h->queue_head->env)) + pos = h->queue_head; + } c++; #if INSANE_STATISTICS - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# queue entries created"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# queue entries created"), + 1, + GNUNET_NO); #endif - GNUNET_CONTAINER_DLL_insert_after (h->queue_head, - h->queue_tail, - pos, - qe); + GNUNET_CONTAINER_DLL_insert_after(h->queue_head, + h->queue_tail, + pos, + qe); h->queue_size++; return qe; } @@ -616,37 +607,37 @@ make_queue_entry (struct GNUNET_DATASTORE_Handle *h, * @param h handle to the datastore */ static void -process_queue (struct GNUNET_DATASTORE_Handle *h) +process_queue(struct GNUNET_DATASTORE_Handle *h) { struct GNUNET_DATASTORE_QueueEntry *qe; if (NULL == (qe = h->queue_head)) - { - /* no entry in queue */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Queue empty\n"); - return; - } + { + /* no entry in queue */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Queue empty\n"); + return; + } if (NULL == qe->env) - { - /* waiting for replies */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Head request already transmitted\n"); - return; - } + { + /* waiting for replies */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Head request already transmitted\n"); + return; + } if (NULL == h->mq) - { - /* waiting for reconnect */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Not connected\n"); - return; - } - GNUNET_assert (NULL == qe->delay_warn_task); - qe->delay_warn_task = GNUNET_SCHEDULER_add_delayed (DELAY_WARN_TIMEOUT, - &delay_warning, - qe); - GNUNET_MQ_send (h->mq, - qe->env); + { + /* waiting for reconnect */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Not connected\n"); + return; + } + GNUNET_assert(NULL == qe->delay_warn_task); + qe->delay_warn_task = GNUNET_SCHEDULER_add_delayed(DELAY_WARN_TIMEOUT, + &delay_warning, + qe); + GNUNET_MQ_send(h->mq, + qe->env); qe->env = NULL; } @@ -659,36 +650,36 @@ process_queue (struct GNUNET_DATASTORE_Handle *h) * @return the queue entry */ static struct GNUNET_DATASTORE_QueueEntry * -get_queue_head (struct GNUNET_DATASTORE_Handle *h, - uint16_t response_type) +get_queue_head(struct GNUNET_DATASTORE_Handle *h, + uint16_t response_type) { struct GNUNET_DATASTORE_QueueEntry *qe; if (h->skip_next_messages > 0) - { - h->skip_next_messages--; - process_queue (h); - return NULL; - } + { + h->skip_next_messages--; + process_queue(h); + return NULL; + } qe = h->queue_head; if (NULL == qe) - { - GNUNET_break (0); - do_disconnect (h); - return NULL; - } + { + GNUNET_break(0); + do_disconnect(h); + return NULL; + } if (NULL != qe->env) - { - GNUNET_break (0); - do_disconnect (h); - return NULL; - } + { + GNUNET_break(0); + do_disconnect(h); + return NULL; + } if (response_type != qe->response_type) - { - GNUNET_break (0); - do_disconnect (h); - return NULL; - } + { + GNUNET_break(0); + do_disconnect(h); + return NULL; + } return qe; } @@ -701,27 +692,27 @@ get_queue_head (struct GNUNET_DATASTORE_Handle *h, * @return #GNUNET_OK if the message is well-formed */ static int -check_status (void *cls, - const struct StatusMessage *sm) +check_status(void *cls, + const struct StatusMessage *sm) { - uint16_t msize = ntohs (sm->header.size) - sizeof (*sm); - int32_t status = ntohl (sm->status); + uint16_t msize = ntohs(sm->header.size) - sizeof(*sm); + int32_t status = ntohl(sm->status); if (msize > 0) - { - const char *emsg = (const char *) &sm[1]; + { + const char *emsg = (const char *)&sm[1]; - if ('\0' != emsg[msize - 1]) + if ('\0' != emsg[msize - 1]) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + } + else if (GNUNET_SYSERR == status) { - GNUNET_break (0); + GNUNET_break(0); return GNUNET_SYSERR; } - } - else if (GNUNET_SYSERR == status) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } return GNUNET_OK; } @@ -733,40 +724,40 @@ check_status (void *cls, * @param sm status message received */ static void -handle_status (void *cls, - const struct StatusMessage *sm) +handle_status(void *cls, + const struct StatusMessage *sm) { struct GNUNET_DATASTORE_Handle *h = cls; struct GNUNET_DATASTORE_QueueEntry *qe; struct StatusContext rc; const char *emsg; - int32_t status = ntohl (sm->status); + int32_t status = ntohl(sm->status); - qe = get_queue_head (h, - GNUNET_MESSAGE_TYPE_DATASTORE_STATUS); + qe = get_queue_head(h, + GNUNET_MESSAGE_TYPE_DATASTORE_STATUS); if (NULL == qe) return; rc = qe->qc.sc; - free_queue_entry (qe); - if (ntohs (sm->header.size) > sizeof (struct StatusMessage)) - emsg = (const char *) &sm[1]; + free_queue_entry(qe); + if (ntohs(sm->header.size) > sizeof(struct StatusMessage)) + emsg = (const char *)&sm[1]; else emsg = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received status %d/%s\n", - (int) status, - emsg); - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# status messages received"), - 1, - GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received status %d/%s\n", + (int)status, + emsg); + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# status messages received"), + 1, + GNUNET_NO); h->retry_time = GNUNET_TIME_UNIT_ZERO; - process_queue (h); + process_queue(h); if (NULL != rc.cont) - rc.cont (rc.cont_cls, - status, - GNUNET_TIME_absolute_ntoh (sm->min_expiration), - emsg); + rc.cont(rc.cont_cls, + status, + GNUNET_TIME_absolute_ntoh(sm->min_expiration), + emsg); } @@ -777,16 +768,16 @@ handle_status (void *cls, * @param dm message received */ static int -check_data (void *cls, - const struct DataMessage *dm) +check_data(void *cls, + const struct DataMessage *dm) { - uint16_t msize = ntohs (dm->header.size) - sizeof (*dm); + uint16_t msize = ntohs(dm->header.size) - sizeof(*dm); - if (msize != ntohl (dm->size)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + if (msize != ntohl(dm->size)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -798,44 +789,44 @@ check_data (void *cls, * @param dm message received */ static void -handle_data (void *cls, - const struct DataMessage *dm) +handle_data(void *cls, + const struct DataMessage *dm) { struct GNUNET_DATASTORE_Handle *h = cls; struct GNUNET_DATASTORE_QueueEntry *qe; struct ResultContext rc; - qe = get_queue_head (h, - GNUNET_MESSAGE_TYPE_DATASTORE_DATA); + qe = get_queue_head(h, + GNUNET_MESSAGE_TYPE_DATASTORE_DATA); if (NULL == qe) return; #if INSANE_STATISTICS - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# Results received"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# Results received"), + 1, + GNUNET_NO); #endif - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received result %llu with type %u and size %u with key %s\n", - (unsigned long long) GNUNET_ntohll (dm->uid), - ntohl (dm->type), - ntohl (dm->size), - GNUNET_h2s (&dm->key)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received result %llu with type %u and size %u with key %s\n", + (unsigned long long)GNUNET_ntohll(dm->uid), + ntohl(dm->type), + ntohl(dm->size), + GNUNET_h2s(&dm->key)); rc = qe->qc.rc; - free_queue_entry (qe); + free_queue_entry(qe); h->retry_time = GNUNET_TIME_UNIT_ZERO; - process_queue (h); + process_queue(h); if (NULL != rc.proc) - rc.proc (rc.proc_cls, - &dm->key, - ntohl (dm->size), - &dm[1], - ntohl (dm->type), - ntohl (dm->priority), - ntohl (dm->anonymity), - ntohl (dm->replication), - GNUNET_TIME_absolute_ntoh (dm->expiration), - GNUNET_ntohll (dm->uid)); + rc.proc(rc.proc_cls, + &dm->key, + ntohl(dm->size), + &dm[1], + ntohl(dm->type), + ntohl(dm->priority), + ntohl(dm->anonymity), + ntohl(dm->replication), + GNUNET_TIME_absolute_ntoh(dm->expiration), + GNUNET_ntohll(dm->uid)); } @@ -847,37 +838,37 @@ handle_data (void *cls, * @param msg message received */ static void -handle_data_end (void *cls, - const struct GNUNET_MessageHeader *msg) +handle_data_end(void *cls, + const struct GNUNET_MessageHeader *msg) { struct GNUNET_DATASTORE_Handle *h = cls; struct GNUNET_DATASTORE_QueueEntry *qe; struct ResultContext rc; - qe = get_queue_head (h, - GNUNET_MESSAGE_TYPE_DATASTORE_DATA); + qe = get_queue_head(h, + GNUNET_MESSAGE_TYPE_DATASTORE_DATA); if (NULL == qe) return; rc = qe->qc.rc; - free_queue_entry (qe); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received end of result set, new queue size is %u\n", - h->queue_size); + free_queue_entry(qe); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received end of result set, new queue size is %u\n", + h->queue_size); h->retry_time = GNUNET_TIME_UNIT_ZERO; h->result_count = 0; - process_queue (h); + process_queue(h); /* signal end of iteration */ if (NULL != rc.proc) - rc.proc (rc.proc_cls, - NULL, - 0, - NULL, - 0, - 0, - 0, - 0, - GNUNET_TIME_UNIT_ZERO_ABS, - 0); + rc.proc(rc.proc_cls, + NULL, + 0, + NULL, + 0, + 0, + 0, + 0, + GNUNET_TIME_UNIT_ZERO_ABS, + 0); } @@ -887,42 +878,42 @@ handle_data_end (void *cls, * @param cls the `struct GNUNET_DATASTORE_Handle` */ static void -try_reconnect (void *cls) +try_reconnect(void *cls) { struct GNUNET_DATASTORE_Handle *h = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (status, - GNUNET_MESSAGE_TYPE_DATASTORE_STATUS, - struct StatusMessage, - h), - GNUNET_MQ_hd_var_size (data, - GNUNET_MESSAGE_TYPE_DATASTORE_DATA, - struct DataMessage, - h), - GNUNET_MQ_hd_fixed_size (data_end, - GNUNET_MESSAGE_TYPE_DATASTORE_DATA_END, - struct GNUNET_MessageHeader, - h), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(status, + GNUNET_MESSAGE_TYPE_DATASTORE_STATUS, + struct StatusMessage, + h), + GNUNET_MQ_hd_var_size(data, + GNUNET_MESSAGE_TYPE_DATASTORE_DATA, + struct DataMessage, + h), + GNUNET_MQ_hd_fixed_size(data_end, + GNUNET_MESSAGE_TYPE_DATASTORE_DATA_END, + struct GNUNET_MessageHeader, + h), + GNUNET_MQ_handler_end() }; - h->retry_time = GNUNET_TIME_STD_BACKOFF (h->retry_time); + h->retry_time = GNUNET_TIME_STD_BACKOFF(h->retry_time); h->reconnect_task = NULL; - GNUNET_assert (NULL == h->mq); - h->mq = GNUNET_CLIENT_connect (h->cfg, - "datastore", - handlers, - &mq_error_handler, - h); + GNUNET_assert(NULL == h->mq); + h->mq = GNUNET_CLIENT_connect(h->cfg, + "datastore", + handlers, + &mq_error_handler, + h); if (NULL == h->mq) return; - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# datastore connections (re)created"), - 1, - GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Reconnected to DATASTORE\n"); - process_queue (h); + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# datastore connections (re)created"), + 1, + GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Reconnected to DATASTORE\n"); + process_queue(h); } @@ -935,10 +926,10 @@ try_reconnect (void *cls) * @param emsg error message */ static void -drop_status_cont (void *cls, - int32_t result, - struct GNUNET_TIME_Absolute min_expiration, - const char *emsg) +drop_status_cont(void *cls, + int32_t result, + struct GNUNET_TIME_Absolute min_expiration, + const char *emsg) { /* do nothing */ } @@ -970,71 +961,71 @@ drop_status_cont (void *cls, * (or rather, will already have been invoked) */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_put (struct GNUNET_DATASTORE_Handle *h, - uint32_t rid, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - unsigned int queue_priority, - unsigned int max_queue_size, - GNUNET_DATASTORE_ContinuationWithStatus cont, - void *cont_cls) +GNUNET_DATASTORE_put(struct GNUNET_DATASTORE_Handle *h, + uint32_t rid, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + unsigned int queue_priority, + unsigned int max_queue_size, + GNUNET_DATASTORE_ContinuationWithStatus cont, + void *cont_cls) { struct GNUNET_DATASTORE_QueueEntry *qe; struct GNUNET_MQ_Envelope *env; struct DataMessage *dm; union QueueContext qc; - if (size + sizeof (*dm) >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return NULL; - } - - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Asked to put %u bytes of data under key `%s' for %s\n", - size, - GNUNET_h2s (key), - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (expiration), - GNUNET_YES)); - env = GNUNET_MQ_msg_extra (dm, - size, - GNUNET_MESSAGE_TYPE_DATASTORE_PUT); - dm->rid = htonl (rid); - dm->size = htonl ((uint32_t) size); - dm->type = htonl (type); - dm->priority = htonl (priority); - dm->anonymity = htonl (anonymity); - dm->replication = htonl (replication); - dm->expiration = GNUNET_TIME_absolute_hton (expiration); + if (size + sizeof(*dm) >= GNUNET_MAX_MESSAGE_SIZE) + { + GNUNET_break(0); + return NULL; + } + + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Asked to put %u bytes of data under key `%s' for %s\n", + size, + GNUNET_h2s(key), + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_remaining(expiration), + GNUNET_YES)); + env = GNUNET_MQ_msg_extra(dm, + size, + GNUNET_MESSAGE_TYPE_DATASTORE_PUT); + dm->rid = htonl(rid); + dm->size = htonl((uint32_t)size); + dm->type = htonl(type); + dm->priority = htonl(priority); + dm->anonymity = htonl(anonymity); + dm->replication = htonl(replication); + dm->expiration = GNUNET_TIME_absolute_hton(expiration); dm->key = *key; - GNUNET_memcpy (&dm[1], - data, - size); + GNUNET_memcpy(&dm[1], + data, + size); qc.sc.cont = cont; qc.sc.cont_cls = cont_cls; - qe = make_queue_entry (h, - env, - queue_priority, - max_queue_size, - GNUNET_MESSAGE_TYPE_DATASTORE_STATUS, - &qc); + qe = make_queue_entry(h, + env, + queue_priority, + max_queue_size, + GNUNET_MESSAGE_TYPE_DATASTORE_STATUS, + &qc); if (NULL == qe) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Could not create queue entry for PUT\n"); - return NULL; - } - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# PUT requests executed"), - 1, - GNUNET_NO); - process_queue (h); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Could not create queue entry for PUT\n"); + return NULL; + } + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# PUT requests executed"), + 1, + GNUNET_NO); + process_queue(h); return qe; } @@ -1055,11 +1046,11 @@ GNUNET_DATASTORE_put (struct GNUNET_DATASTORE_Handle *h, * (or rather, will already have been invoked) */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_reserve (struct GNUNET_DATASTORE_Handle *h, - uint64_t amount, - uint32_t entries, - GNUNET_DATASTORE_ContinuationWithStatus cont, - void *cont_cls) +GNUNET_DATASTORE_reserve(struct GNUNET_DATASTORE_Handle *h, + uint64_t amount, + uint32_t entries, + GNUNET_DATASTORE_ContinuationWithStatus cont, + void *cont_cls) { struct GNUNET_DATASTORE_QueueEntry *qe; struct GNUNET_MQ_Envelope *env; @@ -1068,34 +1059,34 @@ GNUNET_DATASTORE_reserve (struct GNUNET_DATASTORE_Handle *h, if (NULL == cont) cont = &drop_status_cont; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Asked to reserve %llu bytes of data and %u entries\n", - (unsigned long long) amount, - (unsigned int) entries); - env = GNUNET_MQ_msg (rm, - GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE); - rm->entries = htonl (entries); - rm->amount = GNUNET_htonll (amount); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Asked to reserve %llu bytes of data and %u entries\n", + (unsigned long long)amount, + (unsigned int)entries); + env = GNUNET_MQ_msg(rm, + GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE); + rm->entries = htonl(entries); + rm->amount = GNUNET_htonll(amount); qc.sc.cont = cont; qc.sc.cont_cls = cont_cls; - qe = make_queue_entry (h, - env, - UINT_MAX, - UINT_MAX, - GNUNET_MESSAGE_TYPE_DATASTORE_STATUS, - &qc); + qe = make_queue_entry(h, + env, + UINT_MAX, + UINT_MAX, + GNUNET_MESSAGE_TYPE_DATASTORE_STATUS, + &qc); if (NULL == qe) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Could not create queue entry to reserve\n"); - return NULL; - } - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# RESERVE requests executed"), - 1, - GNUNET_NO); - process_queue (h); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Could not create queue entry to reserve\n"); + return NULL; + } + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# RESERVE requests executed"), + 1, + GNUNET_NO); + process_queue(h); return qe; } @@ -1121,12 +1112,12 @@ GNUNET_DATASTORE_reserve (struct GNUNET_DATASTORE_Handle *h, * (or rather, will already have been invoked) */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_release_reserve (struct GNUNET_DATASTORE_Handle *h, - uint32_t rid, - unsigned int queue_priority, - unsigned int max_queue_size, - GNUNET_DATASTORE_ContinuationWithStatus cont, - void *cont_cls) +GNUNET_DATASTORE_release_reserve(struct GNUNET_DATASTORE_Handle *h, + uint32_t rid, + unsigned int queue_priority, + unsigned int max_queue_size, + GNUNET_DATASTORE_ContinuationWithStatus cont, + void *cont_cls) { struct GNUNET_DATASTORE_QueueEntry *qe; struct GNUNET_MQ_Envelope *env; @@ -1135,31 +1126,31 @@ GNUNET_DATASTORE_release_reserve (struct GNUNET_DATASTORE_Handle *h, if (NULL == cont) cont = &drop_status_cont; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Asked to release reserve %d\n", - rid); - env = GNUNET_MQ_msg (rrm, - GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE); - rrm->rid = htonl (rid); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Asked to release reserve %d\n", + rid); + env = GNUNET_MQ_msg(rrm, + GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE); + rrm->rid = htonl(rid); qc.sc.cont = cont; qc.sc.cont_cls = cont_cls; - qe = make_queue_entry (h, - env, - queue_priority, - max_queue_size, - GNUNET_MESSAGE_TYPE_DATASTORE_STATUS, - &qc); + qe = make_queue_entry(h, + env, + queue_priority, + max_queue_size, + GNUNET_MESSAGE_TYPE_DATASTORE_STATUS, + &qc); if (NULL == qe) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Could not create queue entry to release reserve\n"); - return NULL; - } - GNUNET_STATISTICS_update (h->stats, - gettext_noop - ("# RELEASE RESERVE requests executed"), 1, - GNUNET_NO); - process_queue (h); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Could not create queue entry to release reserve\n"); + return NULL; + } + GNUNET_STATISTICS_update(h->stats, + gettext_noop + ("# RELEASE RESERVE requests executed"), 1, + GNUNET_NO); + process_queue(h); return qe; } @@ -1185,60 +1176,60 @@ GNUNET_DATASTORE_release_reserve (struct GNUNET_DATASTORE_Handle *h, * (or rather, will already have been invoked) */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_remove (struct GNUNET_DATASTORE_Handle *h, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - unsigned int queue_priority, - unsigned int max_queue_size, - GNUNET_DATASTORE_ContinuationWithStatus cont, - void *cont_cls) +GNUNET_DATASTORE_remove(struct GNUNET_DATASTORE_Handle *h, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + unsigned int queue_priority, + unsigned int max_queue_size, + GNUNET_DATASTORE_ContinuationWithStatus cont, + void *cont_cls) { struct GNUNET_DATASTORE_QueueEntry *qe; struct DataMessage *dm; struct GNUNET_MQ_Envelope *env; union QueueContext qc; - if (sizeof (*dm) + size >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return NULL; - } + if (sizeof(*dm) + size >= GNUNET_MAX_MESSAGE_SIZE) + { + GNUNET_break(0); + return NULL; + } if (NULL == cont) cont = &drop_status_cont; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Asked to remove %u bytes under key `%s'\n", - size, - GNUNET_h2s (key)); - env = GNUNET_MQ_msg_extra (dm, - size, - GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE); - dm->size = htonl (size); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Asked to remove %u bytes under key `%s'\n", + size, + GNUNET_h2s(key)); + env = GNUNET_MQ_msg_extra(dm, + size, + GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE); + dm->size = htonl(size); dm->key = *key; - GNUNET_memcpy (&dm[1], - data, - size); + GNUNET_memcpy(&dm[1], + data, + size); qc.sc.cont = cont; qc.sc.cont_cls = cont_cls; - qe = make_queue_entry (h, - env, - queue_priority, - max_queue_size, - GNUNET_MESSAGE_TYPE_DATASTORE_STATUS, - &qc); + qe = make_queue_entry(h, + env, + queue_priority, + max_queue_size, + GNUNET_MESSAGE_TYPE_DATASTORE_STATUS, + &qc); if (NULL == qe) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Could not create queue entry for REMOVE\n"); - return NULL; - } - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# REMOVE requests executed"), - 1, - GNUNET_NO); - process_queue (h); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Could not create queue entry for REMOVE\n"); + return NULL; + } + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# REMOVE requests executed"), + 1, + GNUNET_NO); + process_queue(h); return qe; } @@ -1263,41 +1254,41 @@ GNUNET_DATASTORE_remove (struct GNUNET_DATASTORE_Handle *h, * cancel */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_get_for_replication (struct GNUNET_DATASTORE_Handle *h, - unsigned int queue_priority, - unsigned int max_queue_size, - GNUNET_DATASTORE_DatumProcessor proc, - void *proc_cls) +GNUNET_DATASTORE_get_for_replication(struct GNUNET_DATASTORE_Handle *h, + unsigned int queue_priority, + unsigned int max_queue_size, + GNUNET_DATASTORE_DatumProcessor proc, + void *proc_cls) { struct GNUNET_DATASTORE_QueueEntry *qe; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *m; union QueueContext qc; - GNUNET_assert (NULL != proc); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Asked to get replication entry\n"); - env = GNUNET_MQ_msg (m, - GNUNET_MESSAGE_TYPE_DATASTORE_GET_REPLICATION); + GNUNET_assert(NULL != proc); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Asked to get replication entry\n"); + env = GNUNET_MQ_msg(m, + GNUNET_MESSAGE_TYPE_DATASTORE_GET_REPLICATION); qc.rc.proc = proc; qc.rc.proc_cls = proc_cls; - qe = make_queue_entry (h, - env, - queue_priority, - max_queue_size, - GNUNET_MESSAGE_TYPE_DATASTORE_DATA, - &qc); + qe = make_queue_entry(h, + env, + queue_priority, + max_queue_size, + GNUNET_MESSAGE_TYPE_DATASTORE_DATA, + &qc); if (NULL == qe) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Could not create queue entry for GET REPLICATION\n"); - return NULL; - } - GNUNET_STATISTICS_update (h->stats, - gettext_noop - ("# GET REPLICATION requests executed"), 1, - GNUNET_NO); - process_queue (h); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Could not create queue entry for GET REPLICATION\n"); + return NULL; + } + GNUNET_STATISTICS_update(h->stats, + gettext_noop + ("# GET REPLICATION requests executed"), 1, + GNUNET_NO); + process_queue(h); return qe; } @@ -1319,47 +1310,47 @@ GNUNET_DATASTORE_get_for_replication (struct GNUNET_DATASTORE_Handle *h, * cancel */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_get_zero_anonymity (struct GNUNET_DATASTORE_Handle *h, - uint64_t next_uid, - unsigned int queue_priority, - unsigned int max_queue_size, - enum GNUNET_BLOCK_Type type, - GNUNET_DATASTORE_DatumProcessor proc, - void *proc_cls) +GNUNET_DATASTORE_get_zero_anonymity(struct GNUNET_DATASTORE_Handle *h, + uint64_t next_uid, + unsigned int queue_priority, + unsigned int max_queue_size, + enum GNUNET_BLOCK_Type type, + GNUNET_DATASTORE_DatumProcessor proc, + void *proc_cls) { struct GNUNET_DATASTORE_QueueEntry *qe; struct GNUNET_MQ_Envelope *env; struct GetZeroAnonymityMessage *m; union QueueContext qc; - GNUNET_assert (NULL != proc); - GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Asked to get a zero-anonymity entry of type %d\n", - type); - env = GNUNET_MQ_msg (m, - GNUNET_MESSAGE_TYPE_DATASTORE_GET_ZERO_ANONYMITY); - m->type = htonl ((uint32_t) type); - m->next_uid = GNUNET_htonll (next_uid); + GNUNET_assert(NULL != proc); + GNUNET_assert(type != GNUNET_BLOCK_TYPE_ANY); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Asked to get a zero-anonymity entry of type %d\n", + type); + env = GNUNET_MQ_msg(m, + GNUNET_MESSAGE_TYPE_DATASTORE_GET_ZERO_ANONYMITY); + m->type = htonl((uint32_t)type); + m->next_uid = GNUNET_htonll(next_uid); qc.rc.proc = proc; qc.rc.proc_cls = proc_cls; - qe = make_queue_entry (h, - env, - queue_priority, - max_queue_size, - GNUNET_MESSAGE_TYPE_DATASTORE_DATA, - &qc); + qe = make_queue_entry(h, + env, + queue_priority, + max_queue_size, + GNUNET_MESSAGE_TYPE_DATASTORE_DATA, + &qc); if (NULL == qe) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Could not create queue entry for zero-anonymity procation\n"); - return NULL; - } - GNUNET_STATISTICS_update (h->stats, - gettext_noop - ("# GET ZERO ANONYMITY requests executed"), 1, - GNUNET_NO); - process_queue (h); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Could not create queue entry for zero-anonymity procation\n"); + return NULL; + } + GNUNET_STATISTICS_update(h->stats, + gettext_noop + ("# GET ZERO ANONYMITY requests executed"), 1, + GNUNET_NO); + process_queue(h); return qe; } @@ -1383,15 +1374,15 @@ GNUNET_DATASTORE_get_zero_anonymity (struct GNUNET_DATASTORE_Handle *h, * cancel */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_get_key (struct GNUNET_DATASTORE_Handle *h, - uint64_t next_uid, - bool random, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - unsigned int queue_priority, - unsigned int max_queue_size, - GNUNET_DATASTORE_DatumProcessor proc, - void *proc_cls) +GNUNET_DATASTORE_get_key(struct GNUNET_DATASTORE_Handle *h, + uint64_t next_uid, + bool random, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + unsigned int queue_priority, + unsigned int max_queue_size, + GNUNET_DATASTORE_DatumProcessor proc, + void *proc_cls) { struct GNUNET_DATASTORE_QueueEntry *qe; struct GNUNET_MQ_Envelope *env; @@ -1399,50 +1390,50 @@ GNUNET_DATASTORE_get_key (struct GNUNET_DATASTORE_Handle *h, struct GetMessage *gm; union QueueContext qc; - GNUNET_assert (NULL != proc); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Asked to look for data of type %u under key `%s'\n", - (unsigned int) type, - GNUNET_h2s (key)); + GNUNET_assert(NULL != proc); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Asked to look for data of type %u under key `%s'\n", + (unsigned int)type, + GNUNET_h2s(key)); if (NULL == key) - { - env = GNUNET_MQ_msg (gm, - GNUNET_MESSAGE_TYPE_DATASTORE_GET); - gm->type = htonl (type); - gm->next_uid = GNUNET_htonll (next_uid); - gm->random = random; - } + { + env = GNUNET_MQ_msg(gm, + GNUNET_MESSAGE_TYPE_DATASTORE_GET); + gm->type = htonl(type); + gm->next_uid = GNUNET_htonll(next_uid); + gm->random = random; + } else - { - env = GNUNET_MQ_msg (gkm, - GNUNET_MESSAGE_TYPE_DATASTORE_GET_KEY); - gkm->type = htonl (type); - gkm->next_uid = GNUNET_htonll (next_uid); - gkm->random = random; - gkm->key = *key; - } + { + env = GNUNET_MQ_msg(gkm, + GNUNET_MESSAGE_TYPE_DATASTORE_GET_KEY); + gkm->type = htonl(type); + gkm->next_uid = GNUNET_htonll(next_uid); + gkm->random = random; + gkm->key = *key; + } qc.rc.proc = proc; qc.rc.proc_cls = proc_cls; - qe = make_queue_entry (h, - env, - queue_priority, - max_queue_size, - GNUNET_MESSAGE_TYPE_DATASTORE_DATA, - &qc); + qe = make_queue_entry(h, + env, + queue_priority, + max_queue_size, + GNUNET_MESSAGE_TYPE_DATASTORE_DATA, + &qc); if (NULL == qe) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Could not queue request for `%s'\n", - GNUNET_h2s (key)); - return NULL; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Could not queue request for `%s'\n", + GNUNET_h2s(key)); + return NULL; + } #if INSANE_STATISTICS - GNUNET_STATISTICS_update (h->stats, - gettext_noop ("# GET requests executed"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(h->stats, + gettext_noop("# GET requests executed"), + 1, + GNUNET_NO); #endif - process_queue (h); + process_queue(h); return qe; } @@ -1454,23 +1445,23 @@ GNUNET_DATASTORE_get_key (struct GNUNET_DATASTORE_Handle *h, * @param qe operation to cancel */ void -GNUNET_DATASTORE_cancel (struct GNUNET_DATASTORE_QueueEntry *qe) +GNUNET_DATASTORE_cancel(struct GNUNET_DATASTORE_QueueEntry *qe) { struct GNUNET_DATASTORE_Handle *h = qe->h; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Pending DATASTORE request %p cancelled (%d, %d)\n", - qe, - NULL == qe->env, - h->queue_head == qe); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Pending DATASTORE request %p cancelled (%d, %d)\n", + qe, + NULL == qe->env, + h->queue_head == qe); if (NULL == qe->env) - { - free_queue_entry (qe); - h->skip_next_messages++; - return; - } - free_queue_entry (qe); - process_queue (h); + { + free_queue_entry(qe); + h->skip_next_messages++; + return; + } + free_queue_entry(qe); + process_queue(h); } diff --git a/src/datastore/gnunet-datastore.c b/src/datastore/gnunet-datastore.c index 4cf318777..46a0b2358 100644 --- a/src/datastore/gnunet-datastore.c +++ b/src/datastore/gnunet-datastore.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datastore/gnunet-datastore.c @@ -30,8 +30,7 @@ GNUNET_NETWORK_STRUCT_BEGIN -struct DataRecord -{ +struct DataRecord { /** * Number of bytes in the item (NBO). */ @@ -122,14 +121,14 @@ static uint64_t record_count; static void -do_shutdown (void *cls) +do_shutdown(void *cls) { if (NULL != qe) - GNUNET_DATASTORE_cancel (qe); + GNUNET_DATASTORE_cancel(qe); if (NULL != datastore) - GNUNET_DATASTORE_disconnect (datastore, GNUNET_NO); + GNUNET_DATASTORE_disconnect(datastore, GNUNET_NO); if (NULL != file_handle) - GNUNET_DISK_file_close (file_handle); + GNUNET_DISK_file_close(file_handle); } @@ -137,21 +136,21 @@ do_shutdown (void *cls) * Begin dumping the database. */ static void -start_dump (void); +start_dump(void); /** * Begin inserting into the database. */ static void -start_insert (void); +start_insert(void); /** * Perform next GET operation. */ static void -do_get (const uint64_t next_uid); +do_get(const uint64_t next_uid); /** @@ -170,69 +169,69 @@ do_get (const uint64_t next_uid); * maybe 0 if no unique identifier is available */ static void -get_cb (void *cls, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +get_cb(void *cls, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { qe = NULL; if (NULL == key) - { - fprintf (stderr, _ ("Dumped %" PRIu64 " records\n"), record_count); - GNUNET_DISK_file_close (file_handle); - file_handle = NULL; - if (insert) - start_insert (); - else { - ret = 0; - GNUNET_SCHEDULER_shutdown (); + fprintf(stderr, _("Dumped %" PRIu64 " records\n"), record_count); + GNUNET_DISK_file_close(file_handle); + file_handle = NULL; + if (insert) + start_insert(); + else + { + ret = 0; + GNUNET_SCHEDULER_shutdown(); + } + return; } - return; - } struct DataRecord dr; - dr.size = htonl ((uint32_t) size); - dr.type = htonl (type); - dr.priority = htonl (priority); - dr.anonymity = htonl (anonymity); - dr.replication = htonl (replication); - dr.expiration = GNUNET_TIME_absolute_hton (expiration); + dr.size = htonl((uint32_t)size); + dr.type = htonl(type); + dr.priority = htonl(priority); + dr.anonymity = htonl(anonymity); + dr.replication = htonl(replication); + dr.expiration = GNUNET_TIME_absolute_hton(expiration); dr.key = *key; ssize_t len; - len = GNUNET_DISK_file_write (file_handle, &dr, sizeof (dr)); - if (sizeof (dr) != len) - { - fprintf (stderr, - _ ("Short write to file: %zd bytes expecting %zd\n"), - len, - sizeof (dr)); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } + len = GNUNET_DISK_file_write(file_handle, &dr, sizeof(dr)); + if (sizeof(dr) != len) + { + fprintf(stderr, + _("Short write to file: %zd bytes expecting %zd\n"), + len, + sizeof(dr)); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } - len = GNUNET_DISK_file_write (file_handle, data, size); + len = GNUNET_DISK_file_write(file_handle, data, size); if (size != len) - { - fprintf (stderr, - _ ("Short write to file: %zd bytes expecting %zd\n"), - len, - size); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } + { + fprintf(stderr, + _("Short write to file: %zd bytes expecting %zd\n"), + len, + size); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } record_count++; - do_get (uid + 1); + do_get(uid + 1); } @@ -240,24 +239,24 @@ get_cb (void *cls, * Perform next GET operation. */ static void -do_get (const uint64_t next_uid) +do_get(const uint64_t next_uid) { - GNUNET_assert (NULL == qe); - qe = GNUNET_DATASTORE_get_key (datastore, - next_uid, - false /* random */, - NULL /* key */, - GNUNET_BLOCK_TYPE_ANY, - 0 /* queue_priority */, - 1 /* max_queue_size */, - &get_cb, - NULL /* proc_cls */); + GNUNET_assert(NULL == qe); + qe = GNUNET_DATASTORE_get_key(datastore, + next_uid, + false /* random */, + NULL /* key */, + GNUNET_BLOCK_TYPE_ANY, + 0 /* queue_priority */, + 1 /* max_queue_size */, + &get_cb, + NULL /* proc_cls */); if (NULL == qe) - { - fprintf (stderr, _ ("Error queueing datastore GET operation\n")); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - } + { + fprintf(stderr, _("Error queueing datastore GET operation\n")); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + } } @@ -265,32 +264,32 @@ do_get (const uint64_t next_uid) * Begin dumping the database. */ static void -start_dump () +start_dump() { record_count = 0; if (NULL != file_name) - { - file_handle = GNUNET_DISK_file_open (file_name, - GNUNET_DISK_OPEN_WRITE | - GNUNET_DISK_OPEN_TRUNCATE | - GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE); - if (NULL == file_handle) { - fprintf (stderr, _ ("Unable to open dump file: %s\n"), file_name); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; + file_handle = GNUNET_DISK_file_open(file_name, + GNUNET_DISK_OPEN_WRITE | + GNUNET_DISK_OPEN_TRUNCATE | + GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE); + if (NULL == file_handle) + { + fprintf(stderr, _("Unable to open dump file: %s\n"), file_name); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } } - } else - { - file_handle = GNUNET_DISK_get_handle_from_int_fd (STDOUT_FILENO); - } - GNUNET_DISK_file_write (file_handle, MAGIC_BYTES, MAGIC_LEN); - do_get (0); + { + file_handle = GNUNET_DISK_get_handle_from_int_fd(STDOUT_FILENO); + } + GNUNET_DISK_file_write(file_handle, MAGIC_BYTES, MAGIC_LEN); + do_get(0); } @@ -308,77 +307,77 @@ start_dump () * @param msg NULL on success, otherwise an error message */ static void -put_cb (void *cls, - int32_t success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +put_cb(void *cls, + int32_t success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { qe = NULL; if (GNUNET_SYSERR == success) - { - fprintf (stderr, _ ("Failed to store item: %s, aborting\n"), msg); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } + { + fprintf(stderr, _("Failed to store item: %s, aborting\n"), msg); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } struct DataRecord dr; ssize_t len; - len = GNUNET_DISK_file_read (file_handle, &dr, sizeof (dr)); + len = GNUNET_DISK_file_read(file_handle, &dr, sizeof(dr)); if (0 == len) - { - fprintf (stderr, _ ("Inserted %" PRIu64 " records\n"), record_count); - ret = 0; - GNUNET_SCHEDULER_shutdown (); - return; - } - else if (sizeof (dr) != len) - { - fprintf (stderr, - _ ("Short read from file: %zd bytes expecting %zd\n"), - len, - sizeof (dr)); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } + { + fprintf(stderr, _("Inserted %" PRIu64 " records\n"), record_count); + ret = 0; + GNUNET_SCHEDULER_shutdown(); + return; + } + else if (sizeof(dr) != len) + { + fprintf(stderr, + _("Short read from file: %zd bytes expecting %zd\n"), + len, + sizeof(dr)); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } - const size_t size = ntohl (dr.size); + const size_t size = ntohl(dr.size); uint8_t data[size]; - len = GNUNET_DISK_file_read (file_handle, data, size); + len = GNUNET_DISK_file_read(file_handle, data, size); if (size != len) - { - fprintf (stderr, - _ ("Short read from file: %zd bytes expecting %zd\n"), - len, - size); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } + { + fprintf(stderr, + _("Short read from file: %zd bytes expecting %zd\n"), + len, + size); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } record_count++; - qe = GNUNET_DATASTORE_put (datastore, - 0, - &dr.key, - size, - data, - ntohl (dr.type), - ntohl (dr.priority), - ntohl (dr.anonymity), - ntohl (dr.replication), - GNUNET_TIME_absolute_ntoh (dr.expiration), - 0, - 1, - &put_cb, - NULL); + qe = GNUNET_DATASTORE_put(datastore, + 0, + &dr.key, + size, + data, + ntohl(dr.type), + ntohl(dr.priority), + ntohl(dr.anonymity), + ntohl(dr.replication), + GNUNET_TIME_absolute_ntoh(dr.expiration), + 0, + 1, + &put_cb, + NULL); if (NULL == qe) - { - fprintf (stderr, _ ("Error queueing datastore PUT operation\n")); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - } + { + fprintf(stderr, _("Error queueing datastore PUT operation\n")); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + } } @@ -386,38 +385,38 @@ put_cb (void *cls, * Begin inserting into the database. */ static void -start_insert () +start_insert() { record_count = 0; if (NULL != file_name) - { - file_handle = GNUNET_DISK_file_open (file_name, - GNUNET_DISK_OPEN_READ, - GNUNET_DISK_PERM_NONE); - if (NULL == file_handle) { - fprintf (stderr, _ ("Unable to open dump file: %s\n"), file_name); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; + file_handle = GNUNET_DISK_file_open(file_name, + GNUNET_DISK_OPEN_READ, + GNUNET_DISK_PERM_NONE); + if (NULL == file_handle) + { + fprintf(stderr, _("Unable to open dump file: %s\n"), file_name); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } } - } else - { - file_handle = GNUNET_DISK_get_handle_from_int_fd (STDIN_FILENO); - } + { + file_handle = GNUNET_DISK_get_handle_from_int_fd(STDIN_FILENO); + } uint8_t buf[MAGIC_LEN]; ssize_t len; - len = GNUNET_DISK_file_read (file_handle, buf, MAGIC_LEN); - if (len != MAGIC_LEN || 0 != memcmp (buf, MAGIC_BYTES, MAGIC_LEN)) - { - fprintf (stderr, _ ("Input file is not of a supported format\n")); - return; - } - put_cb (NULL, GNUNET_YES, GNUNET_TIME_UNIT_ZERO_ABS, NULL); + len = GNUNET_DISK_file_read(file_handle, buf, MAGIC_LEN); + if (len != MAGIC_LEN || 0 != memcmp(buf, MAGIC_BYTES, MAGIC_LEN)) + { + fprintf(stderr, _("Input file is not of a supported format\n")); + return; + } + put_cb(NULL, GNUNET_YES, GNUNET_TIME_UNIT_ZERO_ABS, NULL); } @@ -430,33 +429,33 @@ start_insert () * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL); - datastore = GNUNET_DATASTORE_connect (cfg); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); + datastore = GNUNET_DATASTORE_connect(cfg); if (NULL == datastore) - { - fprintf (stderr, _ ("Failed connecting to the datastore.\n")); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } + { + fprintf(stderr, _("Failed connecting to the datastore.\n")); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } if (dump) - start_dump (); + start_dump(); else if (insert) - start_insert (); + start_insert(); else - { - fprintf (stderr, - _ ("Please choose at least one operation: %s, %s\n"), - "dump", - "insert"); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - } + { + fprintf(stderr, + _("Please choose at least one operation: %s, %s\n"), + "dump", + "insert"); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + } } @@ -468,38 +467,39 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_flag ('d', - "dump", - gettext_noop ( - "Dump all records from the datastore"), - &dump), - GNUNET_GETOPT_option_flag ('i', - "insert", - gettext_noop ( - "Insert records into the datastore"), - &insert), - GNUNET_GETOPT_option_filename ('f', - "file", - "FILENAME", - gettext_noop ("File to dump or insert"), - &file_name), - GNUNET_GETOPT_OPTION_END}; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + { GNUNET_GETOPT_option_flag('d', + "dump", + gettext_noop( + "Dump all records from the datastore"), + &dump), + GNUNET_GETOPT_option_flag('i', + "insert", + gettext_noop( + "Insert records into the datastore"), + &insert), + GNUNET_GETOPT_option_filename('f', + "file", + "FILENAME", + gettext_noop("File to dump or insert"), + &file_name), + GNUNET_GETOPT_OPTION_END }; + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; if (GNUNET_OK != - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-datastore", - gettext_noop ("Manipulate GNUnet datastore"), - options, - &run, - NULL)) + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-datastore", + gettext_noop("Manipulate GNUnet datastore"), + options, + &run, + NULL)) ret = 1; - GNUNET_free ((void *) argv); + GNUNET_free((void *)argv); return ret; } diff --git a/src/datastore/gnunet-service-datastore.c b/src/datastore/gnunet-service-datastore.c index 4596f6131..41abf77ca 100644 --- a/src/datastore/gnunet-service-datastore.c +++ b/src/datastore/gnunet-service-datastore.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datastore/gnunet-service-datastore.c @@ -39,21 +39,21 @@ /** * Limit size of bloom filter to 2 GB. */ -#define MAX_BF_SIZE ((uint32_t) (1LL << 31)) +#define MAX_BF_SIZE ((uint32_t)(1LL << 31)) /** * How long are we at most keeping "expired" content * past the expiration date in the database? */ #define MAX_EXPIRE_DELAY \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) /** * How fast are we allowed to query the database for deleting * expired content? (1 item per second). */ #define MIN_EXPIRE_DELAY \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1) /** * Name under which we store current space consumption. @@ -75,9 +75,7 @@ static struct GNUNET_SCHEDULER_Task *stat_timeout_task; /** * Our datastore plugin. */ -struct DatastorePlugin -{ - +struct DatastorePlugin { /** * API of the transport as returned by the plugin's * initialization function. @@ -105,9 +103,7 @@ struct DatastorePlugin /** * Linked list of active reservations. */ -struct ReservationList -{ - +struct ReservationList { /** * This is a linked list. */ @@ -231,13 +227,13 @@ static int stats_worked; * statistics service. */ static void -sync_stats () +sync_stats() { - GNUNET_STATISTICS_set (stats, quota_stat_name, payload, GNUNET_YES); - GNUNET_STATISTICS_set (stats, - "# utilization by current datastore", - payload, - GNUNET_NO); + GNUNET_STATISTICS_set(stats, quota_stat_name, payload, GNUNET_YES); + GNUNET_STATISTICS_set(stats, + "# utilization by current datastore", + payload, + GNUNET_NO); last_sync = 0; } @@ -267,7 +263,7 @@ static struct GNUNET_SERVICE_Handle *service; * @param cls not used */ static void -delete_expired (void *cls); +delete_expired(void *cls); /** @@ -292,57 +288,57 @@ delete_expired (void *cls); * #GNUNET_NO to delete the item and continue (if supported) */ static int -expired_processor (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +expired_processor(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct GNUNET_TIME_Absolute now; if (NULL == key) - { - expired_kill_task = - GNUNET_SCHEDULER_add_delayed_with_priority (MAX_EXPIRE_DELAY, - GNUNET_SCHEDULER_PRIORITY_IDLE, - &delete_expired, - NULL); - return GNUNET_SYSERR; - } - now = GNUNET_TIME_absolute_get (); + { + expired_kill_task = + GNUNET_SCHEDULER_add_delayed_with_priority(MAX_EXPIRE_DELAY, + GNUNET_SCHEDULER_PRIORITY_IDLE, + &delete_expired, + NULL); + return GNUNET_SYSERR; + } + now = GNUNET_TIME_absolute_get(); if (expiration.abs_value_us > now.abs_value_us) - { - /* finished processing */ - expired_kill_task = - GNUNET_SCHEDULER_add_delayed_with_priority (MAX_EXPIRE_DELAY, - GNUNET_SCHEDULER_PRIORITY_IDLE, - &delete_expired, - NULL); - return GNUNET_SYSERR; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Deleting content `%s' of type %u that expired %s ago\n", - GNUNET_h2s (key), - type, - GNUNET_STRINGS_relative_time_to_string ( - GNUNET_TIME_absolute_get_difference (expiration, now), - GNUNET_YES)); + { + /* finished processing */ + expired_kill_task = + GNUNET_SCHEDULER_add_delayed_with_priority(MAX_EXPIRE_DELAY, + GNUNET_SCHEDULER_PRIORITY_IDLE, + &delete_expired, + NULL); + return GNUNET_SYSERR; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Deleting content `%s' of type %u that expired %s ago\n", + GNUNET_h2s(key), + type, + GNUNET_STRINGS_relative_time_to_string( + GNUNET_TIME_absolute_get_difference(expiration, now), + GNUNET_YES)); min_expiration = now; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# bytes expired"), - size, - GNUNET_YES); - GNUNET_CONTAINER_bloomfilter_remove (filter, key); + GNUNET_STATISTICS_update(stats, + gettext_noop("# bytes expired"), + size, + GNUNET_YES); + GNUNET_CONTAINER_bloomfilter_remove(filter, key); expired_kill_task = - GNUNET_SCHEDULER_add_delayed_with_priority (MIN_EXPIRE_DELAY, - GNUNET_SCHEDULER_PRIORITY_IDLE, - &delete_expired, - NULL); + GNUNET_SCHEDULER_add_delayed_with_priority(MIN_EXPIRE_DELAY, + GNUNET_SCHEDULER_PRIORITY_IDLE, + &delete_expired, + NULL); return GNUNET_NO; } @@ -356,10 +352,10 @@ expired_processor (void *cls, * @param cls not used */ static void -delete_expired (void *cls) +delete_expired(void *cls) { expired_kill_task = NULL; - plugin->api->get_expiration (plugin->api->cls, &expired_processor, NULL); + plugin->api->get_expiration(plugin->api->cls, &expired_processor, NULL); } @@ -383,31 +379,31 @@ delete_expired (void *cls) * #GNUNET_NO to delete the item and continue (if supported) */ static int -quota_processor (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +quota_processor(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { unsigned long long *need = cls; if (NULL == key) return GNUNET_SYSERR; - GNUNET_log ( + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "Deleting %llu bytes of low-priority (%u) content `%s' of type %u at %s prior to expiration (still trying to free another %llu bytes)\n", - (unsigned long long) (size + GNUNET_DATASTORE_ENTRY_OVERHEAD), - (unsigned int) priority, - GNUNET_h2s (key), + (unsigned long long)(size + GNUNET_DATASTORE_ENTRY_OVERHEAD), + (unsigned int)priority, + GNUNET_h2s(key), type, - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining ( - expiration), - GNUNET_YES), + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_remaining( + expiration), + GNUNET_YES), *need); if (size + GNUNET_DATASTORE_ENTRY_OVERHEAD > *need) *need = 0; @@ -417,11 +413,11 @@ quota_processor (void *cls, min_expiration = GNUNET_TIME_UNIT_FOREVER_ABS; else min_expiration = expiration; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# bytes purged (low-priority)"), - size, - GNUNET_YES); - GNUNET_CONTAINER_bloomfilter_remove (filter, key); + GNUNET_STATISTICS_update(stats, + gettext_noop("# bytes purged (low-priority)"), + size, + GNUNET_YES); + GNUNET_CONTAINER_bloomfilter_remove(filter, key); return GNUNET_NO; } @@ -439,19 +435,19 @@ quota_processor (void *cls, * number of bytes that should be removed). */ static void -manage_space (unsigned long long need) +manage_space(unsigned long long need) { unsigned long long last; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Asked to free up %llu bytes of cache space\n", - need); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Asked to free up %llu bytes of cache space\n", + need); last = 0; while ((need > 0) && (last != need)) - { - last = need; - plugin->api->get_expiration (plugin->api->cls, "a_processor, &need); - } + { + last = need; + plugin->api->get_expiration(plugin->api->cls, "a_processor, &need); + } } @@ -463,25 +459,25 @@ manage_space (unsigned long long need) * @param msg optional error message (can be NULL) */ static void -transmit_status (struct GNUNET_SERVICE_Client *client, - int code, - const char *msg) +transmit_status(struct GNUNET_SERVICE_Client *client, + int code, + const char *msg) { struct GNUNET_MQ_Envelope *env; struct StatusMessage *sm; size_t slen; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Transmitting `%s' message with value %d and message `%s'\n", - "STATUS", - code, - msg != NULL ? msg : "(none)"); - slen = (msg == NULL) ? 0 : strlen (msg) + 1; - env = GNUNET_MQ_msg_extra (sm, slen, GNUNET_MESSAGE_TYPE_DATASTORE_STATUS); - sm->status = htonl (code); - sm->min_expiration = GNUNET_TIME_absolute_hton (min_expiration); - GNUNET_memcpy (&sm[1], msg, slen); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Transmitting `%s' message with value %d and message `%s'\n", + "STATUS", + code, + msg != NULL ? msg : "(none)"); + slen = (msg == NULL) ? 0 : strlen(msg) + 1; + env = GNUNET_MQ_msg_extra(sm, slen, GNUNET_MESSAGE_TYPE_DATASTORE_STATUS); + sm->status = htonl(code); + sm->min_expiration = GNUNET_TIME_absolute_hton(min_expiration); + GNUNET_memcpy(&sm[1], msg, slen); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); } @@ -504,16 +500,16 @@ transmit_status (struct GNUNET_SERVICE_Client *client, * #GNUNET_NO to delete the item and continue (if supported) */ static int -transmit_item (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +transmit_item(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct GNUNET_SERVICE_Client *client = cls; struct GNUNET_MQ_Envelope *env; @@ -521,39 +517,39 @@ transmit_item (void *cls, struct DataMessage *dm; if (NULL == key) - { - /* transmit 'DATA_END' */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting DATA_END message\n"); - env = GNUNET_MQ_msg (end, GNUNET_MESSAGE_TYPE_DATASTORE_DATA_END); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); - return GNUNET_OK; - } - GNUNET_assert (sizeof (struct DataMessage) + size < GNUNET_MAX_MESSAGE_SIZE); - env = GNUNET_MQ_msg_extra (dm, size, GNUNET_MESSAGE_TYPE_DATASTORE_DATA); - dm->rid = htonl (0); - dm->size = htonl (size); - dm->type = htonl (type); - dm->priority = htonl (priority); - dm->anonymity = htonl (anonymity); - dm->replication = htonl (replication); - dm->expiration = GNUNET_TIME_absolute_hton (expiration); - dm->uid = GNUNET_htonll (uid); + { + /* transmit 'DATA_END' */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Transmitting DATA_END message\n"); + env = GNUNET_MQ_msg(end, GNUNET_MESSAGE_TYPE_DATASTORE_DATA_END); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); + return GNUNET_OK; + } + GNUNET_assert(sizeof(struct DataMessage) + size < GNUNET_MAX_MESSAGE_SIZE); + env = GNUNET_MQ_msg_extra(dm, size, GNUNET_MESSAGE_TYPE_DATASTORE_DATA); + dm->rid = htonl(0); + dm->size = htonl(size); + dm->type = htonl(type); + dm->priority = htonl(priority); + dm->anonymity = htonl(anonymity); + dm->replication = htonl(replication); + dm->expiration = GNUNET_TIME_absolute_hton(expiration); + dm->uid = GNUNET_htonll(uid); dm->key = *key; - GNUNET_memcpy (&dm[1], data, size); - GNUNET_log ( + GNUNET_memcpy(&dm[1], data, size); + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "Transmitting DATA message for `%s' of type %u with expiration %s (in: %s)\n", - GNUNET_h2s (key), + GNUNET_h2s(key), type, - GNUNET_STRINGS_absolute_time_to_string (expiration), - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining ( - expiration), - GNUNET_YES)); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# results found"), - 1, - GNUNET_NO); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); + GNUNET_STRINGS_absolute_time_to_string(expiration), + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_remaining( + expiration), + GNUNET_YES)); + GNUNET_STATISTICS_update(stats, + gettext_noop("# results found"), + 1, + GNUNET_NO); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); return GNUNET_OK; } @@ -565,7 +561,7 @@ transmit_item (void *cls, * @param message the actual message */ static void -handle_reserve (void *cls, const struct ReserveMessage *msg) +handle_reserve(void *cls, const struct ReserveMessage *msg) { /** * Static counter to produce reservation identifiers. @@ -578,57 +574,57 @@ handle_reserve (void *cls, const struct ReserveMessage *msg) uint64_t amount; uint32_t entries; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing RESERVE request\n"); - amount = GNUNET_ntohll (msg->amount); - entries = ntohl (msg->entries); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Processing RESERVE request\n"); + amount = GNUNET_ntohll(msg->amount); + entries = ntohl(msg->entries); used = payload + reserved; req = - amount + ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * entries; + amount + ((unsigned long long)GNUNET_DATASTORE_ENTRY_OVERHEAD) * entries; if (used + req > quota) - { - if (quota < used) - used = - quota; /* cheat a bit for error message (to avoid negative numbers) */ - GNUNET_log ( - GNUNET_ERROR_TYPE_WARNING, - _ ( - "Insufficient space (%llu bytes are available) to satisfy RESERVE request for %llu bytes\n"), - quota - used, - req); - if (cache_size < req) { - /* TODO: document this in the FAQ; essentially, if this - * message happens, the insertion request could be blocked - * by less-important content from migration because it is - * larger than 1/8th of the overall available space, and - * we only reserve 1/8th for "fresh" insertions */ - GNUNET_log ( + if (quota < used) + used = + quota; /* cheat a bit for error message (to avoid negative numbers) */ + GNUNET_log( GNUNET_ERROR_TYPE_WARNING, - _ ( - "The requested amount (%llu bytes) is larger than the cache size (%llu bytes)\n"), - req, - cache_size); - transmit_status (client, - 0, - gettext_noop ( - "Insufficient space to satisfy request and " - "requested amount is larger than cache size")); - } - else - { - transmit_status (client, - 0, - gettext_noop ("Insufficient space to satisfy request")); + _( + "Insufficient space (%llu bytes are available) to satisfy RESERVE request for %llu bytes\n"), + quota - used, + req); + if (cache_size < req) + { + /* TODO: document this in the FAQ; essentially, if this + * message happens, the insertion request could be blocked + * by less-important content from migration because it is + * larger than 1/8th of the overall available space, and + * we only reserve 1/8th for "fresh" insertions */ + GNUNET_log( + GNUNET_ERROR_TYPE_WARNING, + _( + "The requested amount (%llu bytes) is larger than the cache size (%llu bytes)\n"), + req, + cache_size); + transmit_status(client, + 0, + gettext_noop( + "Insufficient space to satisfy request and " + "requested amount is larger than cache size")); + } + else + { + transmit_status(client, + 0, + gettext_noop("Insufficient space to satisfy request")); + } + GNUNET_SERVICE_client_continue(client); + return; } - GNUNET_SERVICE_client_continue (client); - return; - } reserved += req; - GNUNET_STATISTICS_set (stats, - gettext_noop ("# reserved"), - reserved, - GNUNET_NO); - e = GNUNET_new (struct ReservationList); + GNUNET_STATISTICS_set(stats, + gettext_noop("# reserved"), + reserved, + GNUNET_NO); + e = GNUNET_new(struct ReservationList); e->next = reservations; reservations = e; e->client = client; @@ -637,8 +633,8 @@ handle_reserve (void *cls, const struct ReserveMessage *msg) e->rid = ++reservation_gen; if (reservation_gen < 0) reservation_gen = 0; /* wrap around */ - transmit_status (client, e->rid, NULL); - GNUNET_SERVICE_client_continue (client); + transmit_status(client, e->rid, NULL); + GNUNET_SERVICE_client_continue(client); } @@ -649,51 +645,51 @@ handle_reserve (void *cls, const struct ReserveMessage *msg) * @param message the actual message */ static void -handle_release_reserve (void *cls, const struct ReleaseReserveMessage *msg) +handle_release_reserve(void *cls, const struct ReleaseReserveMessage *msg) { struct GNUNET_SERVICE_Client *client = cls; struct ReservationList *pos; struct ReservationList *prev; struct ReservationList *next; - int rid = ntohl (msg->rid); + int rid = ntohl(msg->rid); unsigned long long rem; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing RELEASE_RESERVE request\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Processing RELEASE_RESERVE request\n"); next = reservations; prev = NULL; while (NULL != (pos = next)) - { - next = pos->next; - if (rid == pos->rid) { - if (prev == NULL) - reservations = next; - else - prev->next = next; - rem = - pos->amount + - ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * pos->entries; - GNUNET_assert (reserved >= rem); - reserved -= rem; - GNUNET_STATISTICS_set (stats, - gettext_noop ("# reserved"), - reserved, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Returning %llu remaining reserved bytes to storage pool\n", - rem); - GNUNET_free (pos); - transmit_status (client, GNUNET_OK, NULL); - GNUNET_SERVICE_client_continue (client); - return; + next = pos->next; + if (rid == pos->rid) + { + if (prev == NULL) + reservations = next; + else + prev->next = next; + rem = + pos->amount + + ((unsigned long long)GNUNET_DATASTORE_ENTRY_OVERHEAD) * pos->entries; + GNUNET_assert(reserved >= rem); + reserved -= rem; + GNUNET_STATISTICS_set(stats, + gettext_noop("# reserved"), + reserved, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Returning %llu remaining reserved bytes to storage pool\n", + rem); + GNUNET_free(pos); + transmit_status(client, GNUNET_OK, NULL); + GNUNET_SERVICE_client_continue(client); + return; + } + prev = pos; } - prev = pos; - } - GNUNET_break (0); - transmit_status (client, - GNUNET_SYSERR, - gettext_noop ("Could not find matching reservation")); - GNUNET_SERVICE_client_continue (client); + GNUNET_break(0); + transmit_status(client, + GNUNET_SYSERR, + gettext_noop("Could not find matching reservation")); + GNUNET_SERVICE_client_continue(client); } @@ -704,18 +700,18 @@ handle_release_reserve (void *cls, const struct ReleaseReserveMessage *msg) * @return #GNUNET_SYSERR is not well-formed, otherwise #GNUNET_OK */ static int -check_data (const struct DataMessage *dm) +check_data(const struct DataMessage *dm) { uint16_t size; uint32_t dsize; - size = ntohs (dm->header.size); - dsize = ntohl (dm->size); - if (size != dsize + sizeof (struct DataMessage)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + size = ntohs(dm->header.size); + dsize = ntohl(dm->size); + if (size != dsize + sizeof(struct DataMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -731,38 +727,38 @@ check_data (const struct DataMessage *dm) * @param msg error message on error */ static void -put_continuation (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - int status, - const char *msg) +put_continuation(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + int status, + const char *msg) { struct GNUNET_SERVICE_Client *client = cls; if (GNUNET_OK == status) - { - GNUNET_STATISTICS_update (stats, - gettext_noop ("# bytes stored"), - size, - GNUNET_YES); - GNUNET_CONTAINER_bloomfilter_add (filter, key); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Successfully stored %u bytes under key `%s'\n", - size, - GNUNET_h2s (key)); - } - transmit_status (client, - GNUNET_SYSERR == status ? GNUNET_SYSERR : GNUNET_OK, - msg); + { + GNUNET_STATISTICS_update(stats, + gettext_noop("# bytes stored"), + size, + GNUNET_YES); + GNUNET_CONTAINER_bloomfilter_add(filter, key); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Successfully stored %u bytes under key `%s'\n", + size, + GNUNET_h2s(key)); + } + transmit_status(client, + GNUNET_SYSERR == status ? GNUNET_SYSERR : GNUNET_OK, + msg); if (quota - reserved - cache_size < payload) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Need %llu bytes more space (%llu allowed, using %llu)\n"), - (unsigned long long) size + GNUNET_DATASTORE_ENTRY_OVERHEAD, - (unsigned long long) (quota - reserved - cache_size), - (unsigned long long) payload); - manage_space (size + GNUNET_DATASTORE_ENTRY_OVERHEAD); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Need %llu bytes more space (%llu allowed, using %llu)\n"), + (unsigned long long)size + GNUNET_DATASTORE_ENTRY_OVERHEAD, + (unsigned long long)(quota - reserved - cache_size), + (unsigned long long)payload); + manage_space(size + GNUNET_DATASTORE_ENTRY_OVERHEAD); + } } @@ -774,13 +770,13 @@ put_continuation (void *cls, * @return #GNUNET_OK if @a dm is well-formed */ static int -check_put (void *cls, const struct DataMessage *dm) +check_put(void *cls, const struct DataMessage *dm) { - if (GNUNET_OK != check_data (dm)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + if (GNUNET_OK != check_data(dm)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -792,53 +788,53 @@ check_put (void *cls, const struct DataMessage *dm) * @param message the actual message */ static void -handle_put (void *cls, const struct DataMessage *dm) +handle_put(void *cls, const struct DataMessage *dm) { struct GNUNET_SERVICE_Client *client = cls; int rid; struct ReservationList *pos; uint32_t size; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Processing PUT request for `%s' of type %u\n", - GNUNET_h2s (&dm->key), - (uint32_t) ntohl (dm->type)); - rid = ntohl (dm->rid); - size = ntohl (dm->size); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Processing PUT request for `%s' of type %u\n", + GNUNET_h2s(&dm->key), + (uint32_t)ntohl(dm->type)); + rid = ntohl(dm->rid); + size = ntohl(dm->size); if (rid > 0) - { - pos = reservations; - while ((NULL != pos) && (rid != pos->rid)) - pos = pos->next; - GNUNET_break (pos != NULL); - if (NULL != pos) { - GNUNET_break (pos->entries > 0); - GNUNET_break (pos->amount >= size); - pos->entries--; - pos->amount -= size; - reserved -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD); - GNUNET_STATISTICS_set (stats, - gettext_noop ("# reserved"), - reserved, - GNUNET_NO); + pos = reservations; + while ((NULL != pos) && (rid != pos->rid)) + pos = pos->next; + GNUNET_break(pos != NULL); + if (NULL != pos) + { + GNUNET_break(pos->entries > 0); + GNUNET_break(pos->amount >= size); + pos->entries--; + pos->amount -= size; + reserved -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD); + GNUNET_STATISTICS_set(stats, + gettext_noop("# reserved"), + reserved, + GNUNET_NO); + } } - } bool absent = - GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (filter, &dm->key); - plugin->api->put (plugin->api->cls, - &dm->key, - absent, - ntohl (dm->size), - &dm[1], - ntohl (dm->type), - ntohl (dm->priority), - ntohl (dm->anonymity), - ntohl (dm->replication), - GNUNET_TIME_absolute_ntoh (dm->expiration), - &put_continuation, - client); - GNUNET_SERVICE_client_continue (client); + GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test(filter, &dm->key); + plugin->api->put(plugin->api->cls, + &dm->key, + absent, + ntohl(dm->size), + &dm[1], + ntohl(dm->type), + ntohl(dm->priority), + ntohl(dm->anonymity), + ntohl(dm->replication), + GNUNET_TIME_absolute_ntoh(dm->expiration), + &put_continuation, + client); + GNUNET_SERVICE_client_continue(client); } @@ -849,25 +845,25 @@ handle_put (void *cls, const struct DataMessage *dm) * @param msg the actual message */ static void -handle_get (void *cls, const struct GetMessage *msg) +handle_get(void *cls, const struct GetMessage *msg) { struct GNUNET_SERVICE_Client *client = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Processing GET request of type %u\n", - (uint32_t) ntohl (msg->type)); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# GET requests received"), - 1, - GNUNET_NO); - plugin->api->get_key (plugin->api->cls, - GNUNET_ntohll (msg->next_uid), - msg->random, - NULL, - ntohl (msg->type), - &transmit_item, - client); - GNUNET_SERVICE_client_continue (client); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Processing GET request of type %u\n", + (uint32_t)ntohl(msg->type)); + GNUNET_STATISTICS_update(stats, + gettext_noop("# GET requests received"), + 1, + GNUNET_NO); + plugin->api->get_key(plugin->api->cls, + GNUNET_ntohll(msg->next_uid), + msg->random, + NULL, + ntohl(msg->type), + &transmit_item, + client); + GNUNET_SERVICE_client_continue(client); } @@ -878,50 +874,50 @@ handle_get (void *cls, const struct GetMessage *msg) * @param msg the actual message */ static void -handle_get_key (void *cls, const struct GetKeyMessage *msg) +handle_get_key(void *cls, const struct GetKeyMessage *msg) { struct GNUNET_SERVICE_Client *client = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Processing GET request for `%s' of type %u\n", - GNUNET_h2s (&msg->key), - (uint32_t) ntohl (msg->type)); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# GET KEY requests received"), - 1, - GNUNET_NO); - if (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (filter, &msg->key)) - { - /* don't bother database... */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Empty result set for GET request for `%s' (bloomfilter).\n", - GNUNET_h2s (&msg->key)); - GNUNET_STATISTICS_update (stats, - gettext_noop ( - "# requests filtered by bloomfilter"), - 1, - GNUNET_NO); - transmit_item (client, - NULL, - 0, - NULL, - 0, - 0, - 0, - 0, - GNUNET_TIME_UNIT_ZERO_ABS, - 0); - GNUNET_SERVICE_client_continue (client); - return; - } - plugin->api->get_key (plugin->api->cls, - GNUNET_ntohll (msg->next_uid), - msg->random, - &msg->key, - ntohl (msg->type), - &transmit_item, - client); - GNUNET_SERVICE_client_continue (client); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Processing GET request for `%s' of type %u\n", + GNUNET_h2s(&msg->key), + (uint32_t)ntohl(msg->type)); + GNUNET_STATISTICS_update(stats, + gettext_noop("# GET KEY requests received"), + 1, + GNUNET_NO); + if (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test(filter, &msg->key)) + { + /* don't bother database... */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Empty result set for GET request for `%s' (bloomfilter).\n", + GNUNET_h2s(&msg->key)); + GNUNET_STATISTICS_update(stats, + gettext_noop( + "# requests filtered by bloomfilter"), + 1, + GNUNET_NO); + transmit_item(client, + NULL, + 0, + NULL, + 0, + 0, + 0, + 0, + GNUNET_TIME_UNIT_ZERO_ABS, + 0); + GNUNET_SERVICE_client_continue(client); + return; + } + plugin->api->get_key(plugin->api->cls, + GNUNET_ntohll(msg->next_uid), + msg->random, + &msg->key, + ntohl(msg->type), + &transmit_item, + client); + GNUNET_SERVICE_client_continue(client); } @@ -932,18 +928,18 @@ handle_get_key (void *cls, const struct GetKeyMessage *msg) * @param message the actual message */ static void -handle_get_replication (void *cls, const struct GNUNET_MessageHeader *message) +handle_get_replication(void *cls, const struct GNUNET_MessageHeader *message) { struct GNUNET_SERVICE_Client *client = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing GET_REPLICATION request\n"); - GNUNET_STATISTICS_update (stats, - gettext_noop ( - "# GET REPLICATION requests received"), - 1, - GNUNET_NO); - plugin->api->get_replication (plugin->api->cls, &transmit_item, client); - GNUNET_SERVICE_client_continue (client); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Processing GET_REPLICATION request\n"); + GNUNET_STATISTICS_update(stats, + gettext_noop( + "# GET REPLICATION requests received"), + 1, + GNUNET_NO); + plugin->api->get_replication(plugin->api->cls, &transmit_item, client); + GNUNET_SERVICE_client_continue(client); } @@ -954,31 +950,31 @@ handle_get_replication (void *cls, const struct GNUNET_MessageHeader *message) * @param message the actual message */ static void -handle_get_zero_anonymity (void *cls, const struct GetZeroAnonymityMessage *msg) +handle_get_zero_anonymity(void *cls, const struct GetZeroAnonymityMessage *msg) { struct GNUNET_SERVICE_Client *client = cls; enum GNUNET_BLOCK_Type type; - type = (enum GNUNET_BLOCK_Type) ntohl (msg->type); + type = (enum GNUNET_BLOCK_Type)ntohl(msg->type); if (type == GNUNET_BLOCK_TYPE_ANY) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (client); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Processing GET_ZERO_ANONYMITY request\n"); - GNUNET_STATISTICS_update (stats, - gettext_noop ( - "# GET ZERO ANONYMITY requests received"), - 1, - GNUNET_NO); - plugin->api->get_zero_anonymity (plugin->api->cls, - GNUNET_ntohll (msg->next_uid), - type, - &transmit_item, - client); - GNUNET_SERVICE_client_continue (client); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(client); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Processing GET_ZERO_ANONYMITY request\n"); + GNUNET_STATISTICS_update(stats, + gettext_noop( + "# GET ZERO ANONYMITY requests received"), + 1, + GNUNET_NO); + plugin->api->get_zero_anonymity(plugin->api->cls, + GNUNET_ntohll(msg->next_uid), + type, + &transmit_item, + client); + GNUNET_SERVICE_client_continue(client); } @@ -993,36 +989,36 @@ handle_get_zero_anonymity (void *cls, const struct GetZeroAnonymityMessage *msg) * @param msg error message on error */ static void -remove_continuation (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - int status, - const char *msg) +remove_continuation(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + int status, + const char *msg) { struct GNUNET_SERVICE_Client *client = cls; if (GNUNET_SYSERR == status) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "REMOVE request failed: %s.\n", msg); - transmit_status (client, GNUNET_NO, msg); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "REMOVE request failed: %s.\n", msg); + transmit_status(client, GNUNET_NO, msg); + return; + } if (GNUNET_NO == status) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Content not found for REMOVE request.\n"); - transmit_status (client, GNUNET_NO, _ ("Content not found")); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Item matches REMOVE request for key `%s'.\n", - GNUNET_h2s (key)); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# bytes removed (explicit request)"), - size, - GNUNET_YES); - GNUNET_CONTAINER_bloomfilter_remove (filter, key); - transmit_status (client, GNUNET_OK, NULL); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Content not found for REMOVE request.\n"); + transmit_status(client, GNUNET_NO, _("Content not found")); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Item matches REMOVE request for key `%s'.\n", + GNUNET_h2s(key)); + GNUNET_STATISTICS_update(stats, + gettext_noop("# bytes removed (explicit request)"), + size, + GNUNET_YES); + GNUNET_CONTAINER_bloomfilter_remove(filter, key); + transmit_status(client, GNUNET_OK, NULL); } @@ -1034,13 +1030,13 @@ remove_continuation (void *cls, * @return #GNUNET_OK if @a dm is well-formed */ static int -check_remove (void *cls, const struct DataMessage *dm) +check_remove(void *cls, const struct DataMessage *dm) { - if (GNUNET_OK != check_data (dm)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + if (GNUNET_OK != check_data(dm)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1053,24 +1049,24 @@ check_remove (void *cls, const struct DataMessage *dm) * @param message the actual message */ static void -handle_remove (void *cls, const struct DataMessage *dm) +handle_remove(void *cls, const struct DataMessage *dm) { struct GNUNET_SERVICE_Client *client = cls; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# REMOVE requests received"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Processing REMOVE request for `%s'\n", - GNUNET_h2s (&dm->key)); - plugin->api->remove_key (plugin->api->cls, - &dm->key, - ntohl (dm->size), - &dm[1], - &remove_continuation, - client); - GNUNET_SERVICE_client_continue (client); + GNUNET_STATISTICS_update(stats, + gettext_noop("# REMOVE requests received"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Processing REMOVE request for `%s'\n", + GNUNET_h2s(&dm->key)); + plugin->api->remove_key(plugin->api->cls, + &dm->key, + ntohl(dm->size), + &dm[1], + &remove_continuation, + client); + GNUNET_SERVICE_client_continue(client); } @@ -1081,13 +1077,13 @@ handle_remove (void *cls, const struct DataMessage *dm) * @param message the actual message */ static void -handle_drop (void *cls, const struct GNUNET_MessageHeader *message) +handle_drop(void *cls, const struct GNUNET_MessageHeader *message) { struct GNUNET_SERVICE_Client *client = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing DROP request\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Processing DROP request\n"); do_drop = GNUNET_YES; - GNUNET_SERVICE_client_continue (client); + GNUNET_SERVICE_client_continue(client); } @@ -1100,27 +1096,27 @@ handle_drop (void *cls, const struct GNUNET_MessageHeader *message) * 0 for "reset to empty" */ static void -disk_utilization_change_cb (void *cls, int delta) +disk_utilization_change_cb(void *cls, int delta) { if ((delta < 0) && (payload < -delta)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_WARNING, - _ ( - "Datastore payload must have been inaccurate (%lld < %lld). Recomputing it.\n"), - (long long) payload, - (long long) -delta); - plugin->api->estimate_size (plugin->api->cls, &payload); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("New payload: %lld\n"), - (long long) payload); - sync_stats (); - return; - } + { + GNUNET_log( + GNUNET_ERROR_TYPE_WARNING, + _( + "Datastore payload must have been inaccurate (%lld < %lld). Recomputing it.\n"), + (long long)payload, + (long long)-delta); + plugin->api->estimate_size(plugin->api->cls, &payload); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("New payload: %lld\n"), + (long long)payload); + sync_stats(); + return; + } payload += delta; last_sync++; if (last_sync >= MAX_STAT_SYNC_LAG) - sync_stats (); + sync_stats(); } @@ -1135,20 +1131,20 @@ disk_utilization_change_cb (void *cls, int delta) * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration */ static int -process_stat_in (void *cls, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +process_stat_in(void *cls, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { - GNUNET_assert (GNUNET_NO == stats_worked); + GNUNET_assert(GNUNET_NO == stats_worked); stats_worked = GNUNET_YES; payload += value; - GNUNET_log ( + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "Notification from statistics about existing payload (%llu), new payload is %llu\n", - (unsigned long long) value, - (unsigned long long) payload); + (unsigned long long)value, + (unsigned long long)payload); return GNUNET_OK; } @@ -1157,32 +1153,32 @@ process_stat_in (void *cls, * Load the datastore plugin. */ static struct DatastorePlugin * -load_plugin () +load_plugin() { struct DatastorePlugin *ret; char *libname; - ret = GNUNET_new (struct DatastorePlugin); + ret = GNUNET_new(struct DatastorePlugin); ret->env.cfg = cfg; ret->env.duc = &disk_utilization_change_cb; ret->env.cls = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Loading `%s' datastore plugin\n"), - plugin_name); - GNUNET_asprintf (&libname, "libgnunet_plugin_datastore_%s", plugin_name); - ret->short_name = GNUNET_strdup (plugin_name); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Loading `%s' datastore plugin\n"), + plugin_name); + GNUNET_asprintf(&libname, "libgnunet_plugin_datastore_%s", plugin_name); + ret->short_name = GNUNET_strdup(plugin_name); ret->lib_name = libname; - ret->api = GNUNET_PLUGIN_load (libname, &ret->env); + ret->api = GNUNET_PLUGIN_load(libname, &ret->env); if (NULL == ret->api) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to load datastore plugin for `%s'\n"), - plugin_name); - GNUNET_free (ret->short_name); - GNUNET_free (libname); - GNUNET_free (ret); - return NULL; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to load datastore plugin for `%s'\n"), + plugin_name); + GNUNET_free(ret->short_name); + GNUNET_free(libname); + GNUNET_free(ret); + return NULL; + } return ret; } @@ -1194,14 +1190,14 @@ load_plugin () * @param plug plugin to unload */ static void -unload_plugin (struct DatastorePlugin *plug) +unload_plugin(struct DatastorePlugin *plug) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Datastore service is unloading plugin...\n"); - GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api)); - GNUNET_free (plug->lib_name); - GNUNET_free (plug->short_name); - GNUNET_free (plug); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Datastore service is unloading plugin...\n"); + GNUNET_break(NULL == GNUNET_PLUGIN_unload(plug->lib_name, plug->api)); + GNUNET_free(plug->lib_name); + GNUNET_free(plug->short_name); + GNUNET_free(plug); } @@ -1209,13 +1205,13 @@ unload_plugin (struct DatastorePlugin *plug) * Initialization complete, start operating the service. */ static void -begin_service () +begin_service() { - GNUNET_SERVICE_resume (service); + GNUNET_SERVICE_resume(service); expired_kill_task = - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE, - &delete_expired, - NULL); + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_IDLE, + &delete_expired, + NULL); } @@ -1227,22 +1223,22 @@ begin_service () * @param count number of times to add key */ static void -add_key_to_bloomfilter (void *cls, - const struct GNUNET_HashCode *key, - unsigned int count) +add_key_to_bloomfilter(void *cls, + const struct GNUNET_HashCode *key, + unsigned int count) { struct GNUNET_CONTAINER_BloomFilter *bf = cls; if (NULL == key) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Bloomfilter construction complete.\n")); - begin_service (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Bloomfilter construction complete.\n")); + begin_service(); + return; + } while (0 < count--) - GNUNET_CONTAINER_bloomfilter_add (bf, key); + GNUNET_CONTAINER_bloomfilter_add(bf, key); } @@ -1254,54 +1250,54 @@ add_key_to_bloomfilter (void *cls, * @param success #GNUNET_NO if we failed to read the stat */ static void -process_stat_done (void *cls, int success) +process_stat_done(void *cls, int success) { stat_get = NULL; if (NULL != stat_timeout_task) - { - GNUNET_SCHEDULER_cancel (stat_timeout_task); - stat_timeout_task = NULL; - } - plugin = load_plugin (); + { + GNUNET_SCHEDULER_cancel(stat_timeout_task); + stat_timeout_task = NULL; + } + plugin = load_plugin(); if (NULL == plugin) - { - GNUNET_CONTAINER_bloomfilter_free (filter); - filter = NULL; - if (NULL != stats) { - GNUNET_STATISTICS_destroy (stats, GNUNET_YES); - stats = NULL; + GNUNET_CONTAINER_bloomfilter_free(filter); + filter = NULL; + if (NULL != stats) + { + GNUNET_STATISTICS_destroy(stats, GNUNET_YES); + stats = NULL; + } + return; } - return; - } if (GNUNET_NO == stats_worked) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Failed to obtain value from statistics service, recomputing it\n"); - plugin->api->estimate_size (plugin->api->cls, &payload); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("New payload: %lld\n"), - (long long) payload); - } - - if (GNUNET_YES == refresh_bf) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Rebuilding bloomfilter. Please be patient.\n")); - if (NULL != plugin->api->get_keys) { - plugin->api->get_keys (plugin->api->cls, &add_key_to_bloomfilter, filter); - return; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Failed to obtain value from statistics service, recomputing it\n"); + plugin->api->estimate_size(plugin->api->cls, &payload); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("New payload: %lld\n"), + (long long)payload); } - else + + if (GNUNET_YES == refresh_bf) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ( - "Plugin does not support get_keys function. Please fix!\n")); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Rebuilding bloomfilter. Please be patient.\n")); + if (NULL != plugin->api->get_keys) + { + plugin->api->get_keys(plugin->api->cls, &add_key_to_bloomfilter, filter); + return; + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _( + "Plugin does not support get_keys function. Please fix!\n")); + } } - } - begin_service (); + begin_service(); } @@ -1311,11 +1307,11 @@ process_stat_done (void *cls, int success) * @param cls NULL */ static void -stat_timeout (void *cls) +stat_timeout(void *cls) { stat_timeout_task = NULL; - GNUNET_STATISTICS_get_cancel (stat_get); - process_stat_done (NULL, GNUNET_NO); + GNUNET_STATISTICS_get_cancel(stat_get); + process_stat_done(NULL, GNUNET_NO); } @@ -1323,51 +1319,51 @@ stat_timeout (void *cls) * Task run during shutdown. */ static void -cleaning_task (void *cls) +cleaning_task(void *cls) { cleaning_done = GNUNET_YES; if (NULL != expired_kill_task) - { - GNUNET_SCHEDULER_cancel (expired_kill_task); - expired_kill_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(expired_kill_task); + expired_kill_task = NULL; + } if (GNUNET_YES == do_drop) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Dropping database!\n"); - plugin->api->drop (plugin->api->cls); - payload = 0; - last_sync++; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Dropping database!\n"); + plugin->api->drop(plugin->api->cls); + payload = 0; + last_sync++; + } if (NULL != plugin) - { - unload_plugin (plugin); - plugin = NULL; - } + { + unload_plugin(plugin); + plugin = NULL; + } if (NULL != filter) - { - GNUNET_CONTAINER_bloomfilter_free (filter); - filter = NULL; - } + { + GNUNET_CONTAINER_bloomfilter_free(filter); + filter = NULL; + } if (NULL != stat_get) - { - GNUNET_STATISTICS_get_cancel (stat_get); - stat_get = NULL; - } + { + GNUNET_STATISTICS_get_cancel(stat_get); + stat_get = NULL; + } if (NULL != stat_timeout_task) - { - GNUNET_SCHEDULER_cancel (stat_timeout_task); - stat_timeout_task = NULL; - } - GNUNET_free_non_null (plugin_name); + { + GNUNET_SCHEDULER_cancel(stat_timeout_task); + stat_timeout_task = NULL; + } + GNUNET_free_non_null(plugin_name); plugin_name = NULL; if (last_sync > 0) - sync_stats (); + sync_stats(); if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, GNUNET_YES); - stats = NULL; - } - GNUNET_free (quota_stat_name); + { + GNUNET_STATISTICS_destroy(stats, GNUNET_YES); + stats = NULL; + } + GNUNET_free(quota_stat_name); quota_stat_name = NULL; } @@ -1381,9 +1377,9 @@ cleaning_task (void *cls) * @return @a client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { return client; } @@ -1398,39 +1394,39 @@ client_connect_cb (void *cls, * @param app_ctx must match @a client */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { struct ReservationList *pos; struct ReservationList *prev; struct ReservationList *next; - GNUNET_assert (app_ctx == client); + GNUNET_assert(app_ctx == client); prev = NULL; pos = reservations; while (NULL != pos) - { - next = pos->next; - if (pos->client == client) { - if (NULL == prev) - reservations = next; + next = pos->next; + if (pos->client == client) + { + if (NULL == prev) + reservations = next; + else + prev->next = next; + reserved -= pos->amount + pos->entries * GNUNET_DATASTORE_ENTRY_OVERHEAD; + GNUNET_free(pos); + } else - prev->next = next; - reserved -= pos->amount + pos->entries * GNUNET_DATASTORE_ENTRY_OVERHEAD; - GNUNET_free (pos); - } - else - { - prev = pos; + { + prev = pos; + } + pos = next; } - pos = next; - } - GNUNET_STATISTICS_set (stats, - gettext_noop ("# reserved"), - reserved, - GNUNET_NO); + GNUNET_STATISTICS_set(stats, + gettext_noop("# reserved"), + reserved, + GNUNET_NO); } @@ -1442,9 +1438,9 @@ client_disconnect_cb (void *cls, * @param c configuration to use */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *serv) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *serv) { char *fn; char *pfn; @@ -1452,199 +1448,199 @@ run (void *cls, service = serv; cfg = c; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "DATASTORE", - "DATABASE", - &plugin_name)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "DATABASE", - "DATASTORE"); - return; - } - GNUNET_asprintf ("a_stat_name, - _ ("# bytes used in file-sharing datastore `%s'"), - plugin_name); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "DATASTORE", + "DATABASE", + &plugin_name)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "DATABASE", + "DATASTORE"); + return; + } + GNUNET_asprintf("a_stat_name, + _("# bytes used in file-sharing datastore `%s'"), + plugin_name); if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_size (cfg, "DATASTORE", "QUOTA", "a)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "QUOTA", "DATASTORE"); - return; - } - stats = GNUNET_STATISTICS_create ("datastore", cfg); - GNUNET_STATISTICS_set (stats, gettext_noop ("# quota"), quota, GNUNET_NO); + GNUNET_CONFIGURATION_get_value_size(cfg, "DATASTORE", "QUOTA", "a)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "QUOTA", "DATASTORE"); + return; + } + stats = GNUNET_STATISTICS_create("datastore", cfg); + GNUNET_STATISTICS_set(stats, gettext_noop("# quota"), quota, GNUNET_NO); cache_size = quota / 8; /* Or should we make this an option? */ - GNUNET_STATISTICS_set (stats, - gettext_noop ("# cache size"), - cache_size, - GNUNET_NO); + GNUNET_STATISTICS_set(stats, + gettext_noop("# cache size"), + cache_size, + GNUNET_NO); if (quota / (32 * 1024LL) > MAX_BF_SIZE) bf_size = MAX_BF_SIZE; else bf_size = quota / (32 * 1024LL); /* 8 bit per entry, 1 bit per 32 kb in DB */ fn = NULL; - if ((GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, - "DATASTORE", - "BLOOMFILTER", - &fn)) || - (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Could not use specified filename `%s' for bloomfilter.\n"), - NULL != fn ? fn : ""); - GNUNET_free_non_null (fn); - fn = NULL; - } + if ((GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(cfg, + "DATASTORE", + "BLOOMFILTER", + &fn)) || + (GNUNET_OK != GNUNET_DISK_directory_create_for_file(fn))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Could not use specified filename `%s' for bloomfilter.\n"), + NULL != fn ? fn : ""); + GNUNET_free_non_null(fn); + fn = NULL; + } if (NULL != fn) - { - GNUNET_asprintf (&pfn, "%s.%s", fn, plugin_name); - if (GNUNET_YES == GNUNET_DISK_file_test (pfn)) { - filter = - GNUNET_CONTAINER_bloomfilter_load (pfn, - bf_size, - 5); /* approx. 3% false positives at max use */ - if (NULL == filter) - { - /* file exists but not valid, remove and try again, but refresh */ - if (0 != unlink (pfn)) + GNUNET_asprintf(&pfn, "%s.%s", fn, plugin_name); + if (GNUNET_YES == GNUNET_DISK_file_test(pfn)) { - /* failed to remove, run without file */ - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to remove bogus bloomfilter file `%s'\n"), - pfn); - GNUNET_free (pfn); - pfn = NULL; - filter = GNUNET_CONTAINER_bloomfilter_load ( - NULL, - bf_size, - 5); /* approx. 3% false positives at max use */ - refresh_bf = GNUNET_YES; + filter = + GNUNET_CONTAINER_bloomfilter_load(pfn, + bf_size, + 5); /* approx. 3% false positives at max use */ + if (NULL == filter) + { + /* file exists but not valid, remove and try again, but refresh */ + if (0 != unlink(pfn)) + { + /* failed to remove, run without file */ + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to remove bogus bloomfilter file `%s'\n"), + pfn); + GNUNET_free(pfn); + pfn = NULL; + filter = GNUNET_CONTAINER_bloomfilter_load( + NULL, + bf_size, + 5); /* approx. 3% false positives at max use */ + refresh_bf = GNUNET_YES; + } + else + { + /* try again after remove */ + filter = GNUNET_CONTAINER_bloomfilter_load( + pfn, + bf_size, + 5); /* approx. 3% false positives at max use */ + refresh_bf = GNUNET_YES; + if (NULL == filter) + { + /* failed yet again, give up on using file */ + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to remove bogus bloomfilter file `%s'\n"), + pfn); + GNUNET_free(pfn); + pfn = NULL; + filter = GNUNET_CONTAINER_bloomfilter_init( + NULL, + bf_size, + 5); /* approx. 3% false positives at max use */ + } + } + } + else + { + /* normal case: have an existing valid bf file, no need to refresh */ + refresh_bf = GNUNET_NO; + } } - else + else { - /* try again after remove */ - filter = GNUNET_CONTAINER_bloomfilter_load ( - pfn, - bf_size, - 5); /* approx. 3% false positives at max use */ + filter = + GNUNET_CONTAINER_bloomfilter_load(pfn, + bf_size, + 5); /* approx. 3% false positives at max use */ refresh_bf = GNUNET_YES; - if (NULL == filter) - { - /* failed yet again, give up on using file */ - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to remove bogus bloomfilter file `%s'\n"), - pfn); - GNUNET_free (pfn); - pfn = NULL; - filter = GNUNET_CONTAINER_bloomfilter_init ( - NULL, - bf_size, - 5); /* approx. 3% false positives at max use */ - } } - } - else - { - /* normal case: have an existing valid bf file, no need to refresh */ - refresh_bf = GNUNET_NO; - } + GNUNET_free(pfn); } - else + else { filter = - GNUNET_CONTAINER_bloomfilter_load (pfn, - bf_size, - 5); /* approx. 3% false positives at max use */ + GNUNET_CONTAINER_bloomfilter_init(NULL, + bf_size, + 5); /* approx. 3% false positives at max use */ refresh_bf = GNUNET_YES; } - GNUNET_free (pfn); - } - else - { - filter = - GNUNET_CONTAINER_bloomfilter_init (NULL, - bf_size, - 5); /* approx. 3% false positives at max use */ - refresh_bf = GNUNET_YES; - } - GNUNET_free_non_null (fn); + GNUNET_free_non_null(fn); if (NULL == filter) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to initialize bloomfilter.\n")); - if (NULL != stats) { - GNUNET_STATISTICS_destroy (stats, GNUNET_YES); - stats = NULL; + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to initialize bloomfilter.\n")); + if (NULL != stats) + { + GNUNET_STATISTICS_destroy(stats, GNUNET_YES); + stats = NULL; + } + return; } - return; - } - GNUNET_SERVICE_suspend (service); - stat_get = GNUNET_STATISTICS_get (stats, - "datastore", - quota_stat_name, - &process_stat_done, - &process_stat_in, - NULL); + GNUNET_SERVICE_suspend(service); + stat_get = GNUNET_STATISTICS_get(stats, + "datastore", + quota_stat_name, + &process_stat_done, + &process_stat_in, + NULL); if (NULL == stat_get) - process_stat_done (NULL, GNUNET_SYSERR); + process_stat_done(NULL, GNUNET_SYSERR); else - stat_timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &stat_timeout, - NULL); - GNUNET_SCHEDULER_add_shutdown (&cleaning_task, NULL); + stat_timeout_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &stat_timeout, + NULL); + GNUNET_SCHEDULER_add_shutdown(&cleaning_task, NULL); } /** * Define "main" method using service macro. */ -GNUNET_SERVICE_MAIN ( +GNUNET_SERVICE_MAIN( "datastore", GNUNET_SERVICE_OPTION_NONE, &run, &client_connect_cb, &client_disconnect_cb, NULL, - GNUNET_MQ_hd_fixed_size (reserve, - GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE, - struct ReserveMessage, - NULL), - GNUNET_MQ_hd_fixed_size (release_reserve, - GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE, - struct ReleaseReserveMessage, - NULL), - GNUNET_MQ_hd_var_size (put, - GNUNET_MESSAGE_TYPE_DATASTORE_PUT, - struct DataMessage, - NULL), - GNUNET_MQ_hd_fixed_size (get, - GNUNET_MESSAGE_TYPE_DATASTORE_GET, - struct GetMessage, - NULL), - GNUNET_MQ_hd_fixed_size (get_key, - GNUNET_MESSAGE_TYPE_DATASTORE_GET_KEY, - struct GetKeyMessage, - NULL), - GNUNET_MQ_hd_fixed_size (get_replication, - GNUNET_MESSAGE_TYPE_DATASTORE_GET_REPLICATION, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_hd_fixed_size (get_zero_anonymity, - GNUNET_MESSAGE_TYPE_DATASTORE_GET_ZERO_ANONYMITY, - struct GetZeroAnonymityMessage, - NULL), - GNUNET_MQ_hd_var_size (remove, - GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE, - struct DataMessage, - NULL), - GNUNET_MQ_hd_fixed_size (drop, - GNUNET_MESSAGE_TYPE_DATASTORE_DROP, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_hd_fixed_size(reserve, + GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE, + struct ReserveMessage, + NULL), + GNUNET_MQ_hd_fixed_size(release_reserve, + GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE, + struct ReleaseReserveMessage, + NULL), + GNUNET_MQ_hd_var_size(put, + GNUNET_MESSAGE_TYPE_DATASTORE_PUT, + struct DataMessage, + NULL), + GNUNET_MQ_hd_fixed_size(get, + GNUNET_MESSAGE_TYPE_DATASTORE_GET, + struct GetMessage, + NULL), + GNUNET_MQ_hd_fixed_size(get_key, + GNUNET_MESSAGE_TYPE_DATASTORE_GET_KEY, + struct GetKeyMessage, + NULL), + GNUNET_MQ_hd_fixed_size(get_replication, + GNUNET_MESSAGE_TYPE_DATASTORE_GET_REPLICATION, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_hd_fixed_size(get_zero_anonymity, + GNUNET_MESSAGE_TYPE_DATASTORE_GET_ZERO_ANONYMITY, + struct GetZeroAnonymityMessage, + NULL), + GNUNET_MQ_hd_var_size(remove, + GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE, + struct DataMessage, + NULL), + GNUNET_MQ_hd_fixed_size(drop, + GNUNET_MESSAGE_TYPE_DATASTORE_DROP, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-datastore.c */ diff --git a/src/datastore/perf_datastore_api.c b/src/datastore/perf_datastore_api.c index 96ec9e924..e7eff0e6a 100644 --- a/src/datastore/perf_datastore_api.c +++ b/src/datastore/perf_datastore_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /* * @file datastore/perf_datastore_api.c * @brief performance measurement for the datastore implementation @@ -41,7 +41,7 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15) /** * Target datastore size (in bytes). @@ -114,8 +114,7 @@ static int ok; /** * Which phase of the process are we in? */ -enum RunPhase -{ +enum RunPhase { /** * We are done (shutting down normally). */ @@ -154,8 +153,7 @@ enum RunPhase * benchmark. Could right now be global, but this allows * us to theoretically run multiple clients "in parallel". */ -struct CpsRunContext -{ +struct CpsRunContext { /** * Execution phase we are in. */ @@ -188,7 +186,7 @@ struct CpsRunContext * @param cls the `struct CpsRunContext` */ static void -run_continuation (void *cls); +run_continuation(void *cls); /** @@ -203,55 +201,57 @@ run_continuation (void *cls); * @param msg NULL on success, otherwise an error message */ static void -check_success (void *cls, - int success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +check_success(void *cls, + int success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct CpsRunContext *crc = cls; #if REPORT_ID - fprintf (stderr, "%s", (GNUNET_OK == success) ? "I" : "i"); + fprintf(stderr, "%s", (GNUNET_OK == success) ? "I" : "i"); #endif if (GNUNET_OK != success) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Check success failed: `%s'\n", - msg); - crc->phase = RP_ERROR; - GNUNET_SCHEDULER_add_now (&run_continuation, - crc); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Check success failed: `%s'\n", + msg); + crc->phase = RP_ERROR; + GNUNET_SCHEDULER_add_now(&run_continuation, + crc); + return; + } stored_bytes += crc->size; stored_ops++; stored_entries++; crc->j++; switch (crc->phase) - { - case RP_PUT: - if (crc->j >= PUT_10) { - crc->j = 0; - crc->i++; - if (crc->i == ITERATIONS) - crc->phase = RP_PUT_QUOTA; - else - crc->phase = RP_CUT; + case RP_PUT: + if (crc->j >= PUT_10) + { + crc->j = 0; + crc->i++; + if (crc->i == ITERATIONS) + crc->phase = RP_PUT_QUOTA; + else + crc->phase = RP_CUT; + } + break; + + case RP_PUT_QUOTA: + if (crc->j >= QUOTA_PUTS) + { + crc->j = 0; + crc->phase = RP_DONE; + } + break; + + default: + GNUNET_assert(0); } - break; - case RP_PUT_QUOTA: - if (crc->j >= QUOTA_PUTS) - { - crc->j = 0; - crc->phase = RP_DONE; - } - break; - default: - GNUNET_assert (0); - } - GNUNET_SCHEDULER_add_now (&run_continuation, - crc); + GNUNET_SCHEDULER_add_now(&run_continuation, + crc); } @@ -267,29 +267,29 @@ check_success (void *cls, * @param msg NULL on success, otherwise an error message */ static void -remove_next (void *cls, - int success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +remove_next(void *cls, + int success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct CpsRunContext *crc = cls; if (GNUNET_OK != success) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "remove_next failed: `%s'\n", - msg); - crc->phase = RP_ERROR; - GNUNET_SCHEDULER_add_now (&run_continuation, - crc); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "remove_next failed: `%s'\n", + msg); + crc->phase = RP_ERROR; + GNUNET_SCHEDULER_add_now(&run_continuation, + crc); + return; + } #if REPORT_ID - fprintf (stderr, "%s", "D"); + fprintf(stderr, "%s", "D"); #endif - GNUNET_assert (GNUNET_OK == success); - GNUNET_SCHEDULER_add_now (&run_continuation, - crc); + GNUNET_assert(GNUNET_OK == success); + GNUNET_SCHEDULER_add_now(&run_continuation, + crc); } @@ -309,32 +309,32 @@ remove_next (void *cls, * maybe 0 if no unique identifier is available */ static void -delete_value (void *cls, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +delete_value(void *cls, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct CpsRunContext *crc = cls; - GNUNET_assert (NULL != key); + GNUNET_assert(NULL != key); stored_ops++; stored_bytes -= size; stored_entries--; stored_ops++; if (stored_bytes < MAX_SIZE) crc->phase = RP_PUT; - GNUNET_assert (NULL != - GNUNET_DATASTORE_remove (datastore, - key, - size, - data, 1, 1, - &remove_next, crc)); + GNUNET_assert(NULL != + GNUNET_DATASTORE_remove(datastore, + key, + size, + data, 1, 1, + &remove_next, crc)); } @@ -345,7 +345,7 @@ delete_value (void *cls, * @param cls the `struct CpsRunContext` */ static void -run_continuation (void *cls) +run_continuation(void *cls) { struct CpsRunContext *crc = cls; size_t size; @@ -353,156 +353,161 @@ run_continuation (void *cls) static char data[65536]; char gstr[128]; - ok = (int) crc->phase; + ok = (int)crc->phase; switch (crc->phase) - { - case RP_PUT: - memset (&key, - 256 - crc->i, - sizeof (struct GNUNET_HashCode)); - /* most content is 32k */ - size = 32 * 1024; - if (0 == - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - 16)) /* but some of it is less! */ - size = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - 32 * 1024); - crc->size = size = size - (size & 7); /* always multiple of 8 */ - GNUNET_CRYPTO_hash (&key, - sizeof (struct GNUNET_HashCode), - &key); - memset (data, - (int) crc->j, - size); - if (crc->j > 255) - memset (data, - (int) (crc->j - 255), - size / 2); - data[0] = crc->i; - GNUNET_assert (NULL != - GNUNET_DATASTORE_put (datastore, + { + case RP_PUT: + memset(&key, + 256 - crc->i, + sizeof(struct GNUNET_HashCode)); + /* most content is 32k */ + size = 32 * 1024; + if (0 == + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + 16)) /* but some of it is less! */ + size = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + 32 * 1024); + crc->size = size = size - (size & 7); /* always multiple of 8 */ + GNUNET_CRYPTO_hash(&key, + sizeof(struct GNUNET_HashCode), + &key); + memset(data, + (int)crc->j, + size); + if (crc->j > 255) + memset(data, + (int)(crc->j - 255), + size / 2); + data[0] = crc->i; + GNUNET_assert(NULL != + GNUNET_DATASTORE_put(datastore, 0, &key, size, data, crc->j + 1, GNUNET_CRYPTO_random_u32 - (GNUNET_CRYPTO_QUALITY_WEAK, 100), + (GNUNET_CRYPTO_QUALITY_WEAK, 100), crc->j, 0, GNUNET_TIME_relative_to_absolute - (GNUNET_TIME_relative_multiply - (GNUNET_TIME_UNIT_SECONDS, - GNUNET_CRYPTO_random_u32 - (GNUNET_CRYPTO_QUALITY_WEAK, 1000))), + (GNUNET_TIME_relative_multiply + (GNUNET_TIME_UNIT_SECONDS, + GNUNET_CRYPTO_random_u32 + (GNUNET_CRYPTO_QUALITY_WEAK, 1000))), 1, 1, &check_success, crc)); - break; - case RP_CUT: - /* trim down below MAX_SIZE again */ - GNUNET_assert (NULL != - GNUNET_DATASTORE_get_for_replication (datastore, + break; + + case RP_CUT: + /* trim down below MAX_SIZE again */ + GNUNET_assert(NULL != + GNUNET_DATASTORE_get_for_replication(datastore, 1, 1, &delete_value, crc)); - break; - case RP_REPORT: - printf ( + break; + + case RP_REPORT: + printf( #if REPORT_ID - "\n" + "\n" #endif - "Stored %llu kB / %lluk ops / %llu ops/s\n", - stored_bytes / 1024, /* used size in k */ - stored_ops / 1024, /* total operations (in k) */ - 1000LL * 1000LL * stored_ops / (1 + - GNUNET_TIME_absolute_get_duration - (start_time).rel_value_us)); - crc->phase = RP_PUT; - crc->j = 0; - GNUNET_SCHEDULER_add_now (&run_continuation, - crc); - break; - case RP_PUT_QUOTA: - memset (&key, - 256 - crc->i, - sizeof (struct GNUNET_HashCode)); - /* most content is 32k */ - size = 32 * 1024; - if (0 == - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - 16)) /* but some of it is less! */ - size = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - 32 * 1024); - crc->size = size = size - (size & 7); /* always multiple of 8 */ - GNUNET_CRYPTO_hash (&key, - sizeof (struct GNUNET_HashCode), - &key); - memset (data, - (int) crc->j, - size); - if (crc->j > 255) - memset (data, - (int) (crc->j - 255), - size / 2); - data[0] = crc->i; - GNUNET_assert (NULL != - GNUNET_DATASTORE_put (datastore, + "Stored %llu kB / %lluk ops / %llu ops/s\n", + stored_bytes / 1024, /* used size in k */ + stored_ops / 1024, /* total operations (in k) */ + 1000LL * 1000LL * stored_ops / (1 + + GNUNET_TIME_absolute_get_duration + (start_time).rel_value_us)); + crc->phase = RP_PUT; + crc->j = 0; + GNUNET_SCHEDULER_add_now(&run_continuation, + crc); + break; + + case RP_PUT_QUOTA: + memset(&key, + 256 - crc->i, + sizeof(struct GNUNET_HashCode)); + /* most content is 32k */ + size = 32 * 1024; + if (0 == + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + 16)) /* but some of it is less! */ + size = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + 32 * 1024); + crc->size = size = size - (size & 7); /* always multiple of 8 */ + GNUNET_CRYPTO_hash(&key, + sizeof(struct GNUNET_HashCode), + &key); + memset(data, + (int)crc->j, + size); + if (crc->j > 255) + memset(data, + (int)(crc->j - 255), + size / 2); + data[0] = crc->i; + GNUNET_assert(NULL != + GNUNET_DATASTORE_put(datastore, 0, /* reservation ID */ &key, size, data, crc->j + 1, /* type */ GNUNET_CRYPTO_random_u32 - (GNUNET_CRYPTO_QUALITY_WEAK, - 100), /* priority */ + (GNUNET_CRYPTO_QUALITY_WEAK, + 100), /* priority */ crc->j, /* anonymity */ 0, /* replication */ GNUNET_TIME_relative_to_absolute - (GNUNET_TIME_relative_multiply - (GNUNET_TIME_UNIT_SECONDS, - GNUNET_CRYPTO_random_u32 - (GNUNET_CRYPTO_QUALITY_WEAK, 1000))), + (GNUNET_TIME_relative_multiply + (GNUNET_TIME_UNIT_SECONDS, + GNUNET_CRYPTO_random_u32 + (GNUNET_CRYPTO_QUALITY_WEAK, 1000))), 1, 1, &check_success, crc)); - break; - - case RP_DONE: - GNUNET_snprintf (gstr, - sizeof (gstr), - "DATASTORE-%s", - plugin_name); - if ((crc->i == ITERATIONS) && (stored_ops > 0)) - { - GAUGER (gstr, - "PUT operation duration", - GNUNET_TIME_absolute_get_duration (start_time).rel_value_us / 1000LL / - stored_ops, - "ms/operation"); - fprintf (stdout, - "\nPUT performance: %s for %llu operations\n", - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start_time), - GNUNET_YES), - stored_ops); - fprintf (stdout, - "PUT performance: %llu ms/operation\n", - GNUNET_TIME_absolute_get_duration (start_time).rel_value_us / 1000LL / - stored_ops); + break; + + case RP_DONE: + GNUNET_snprintf(gstr, + sizeof(gstr), + "DATASTORE-%s", + plugin_name); + if ((crc->i == ITERATIONS) && (stored_ops > 0)) + { + GAUGER(gstr, + "PUT operation duration", + GNUNET_TIME_absolute_get_duration(start_time).rel_value_us / 1000LL / + stored_ops, + "ms/operation"); + fprintf(stdout, + "\nPUT performance: %s for %llu operations\n", + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start_time), + GNUNET_YES), + stored_ops); + fprintf(stdout, + "PUT performance: %llu ms/operation\n", + GNUNET_TIME_absolute_get_duration(start_time).rel_value_us / 1000LL / + stored_ops); + } + GNUNET_DATASTORE_disconnect(datastore, + GNUNET_YES); + GNUNET_free(crc); + ok = 0; + break; + + case RP_ERROR: + GNUNET_DATASTORE_disconnect(datastore, GNUNET_YES); + GNUNET_free(crc); + ok = 1; + break; + + default: + GNUNET_assert(0); } - GNUNET_DATASTORE_disconnect (datastore, - GNUNET_YES); - GNUNET_free (crc); - ok = 0; - break; - case RP_ERROR: - GNUNET_DATASTORE_disconnect (datastore, GNUNET_YES); - GNUNET_free (crc); - ok = 1; - break; - default: - GNUNET_assert (0); - } } @@ -519,25 +524,25 @@ run_continuation (void *cls) * @param msg NULL on success, otherwise an error message */ static void -run_tests (void *cls, - int success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +run_tests(void *cls, + int success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct CpsRunContext *crc = cls; if (success != GNUNET_YES) - { - fprintf (stderr, - "Test 'put' operation failed with error `%s' database likely not setup, skipping test.\n", - msg); - GNUNET_DATASTORE_disconnect (datastore, - GNUNET_YES); - GNUNET_free (crc); - return; - } - GNUNET_SCHEDULER_add_now (&run_continuation, - crc); + { + fprintf(stderr, + "Test 'put' operation failed with error `%s' database likely not setup, skipping test.\n", + msg); + GNUNET_DATASTORE_disconnect(datastore, + GNUNET_YES); + GNUNET_free(crc); + return; + } + GNUNET_SCHEDULER_add_now(&run_continuation, + crc); } @@ -551,34 +556,34 @@ run_tests (void *cls, * @param peer peer handle (unused) */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct CpsRunContext *crc; static struct GNUNET_HashCode zkey; - datastore = GNUNET_DATASTORE_connect (cfg); - start_time = GNUNET_TIME_absolute_get (); - crc = GNUNET_new (struct CpsRunContext); + datastore = GNUNET_DATASTORE_connect(cfg); + start_time = GNUNET_TIME_absolute_get(); + crc = GNUNET_new(struct CpsRunContext); crc->phase = RP_PUT; if (NULL == - GNUNET_DATASTORE_put (datastore, - 0, - &zkey, - 4, "TEST", - GNUNET_BLOCK_TYPE_TEST, - 0, 0, 0, - GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_SECONDS), - 0, 1, - &run_tests, crc)) - { - fprintf (stderr, - "%s", - "Test 'put' operation failed.\n"); - ok = 1; - GNUNET_free (crc); - } + GNUNET_DATASTORE_put(datastore, + 0, + &zkey, + 4, "TEST", + GNUNET_BLOCK_TYPE_TEST, + 0, 0, 0, + GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_SECONDS), + 0, 1, + &run_tests, crc)) + { + fprintf(stderr, + "%s", + "Test 'put' operation failed.\n"); + ok = 1; + GNUNET_free(crc); + } } @@ -592,23 +597,23 @@ run (void *cls, * @return 0 on success */ int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { char cfg_name[PATH_MAX]; - plugin_name = GNUNET_TESTING_get_testname_from_underscore (argv[0]); - GNUNET_snprintf (cfg_name, - sizeof (cfg_name), - "test_datastore_api_data_%s.conf", - plugin_name); + plugin_name = GNUNET_TESTING_get_testname_from_underscore(argv[0]); + GNUNET_snprintf(cfg_name, + sizeof(cfg_name), + "test_datastore_api_data_%s.conf", + plugin_name); if (0 != - GNUNET_TESTING_peer_run ("perf-gnunet-datastore", - cfg_name, - &run, - NULL)) + GNUNET_TESTING_peer_run("perf-gnunet-datastore", + cfg_name, + &run, + NULL)) return 1; - fprintf (stderr, "%s", "\n"); + fprintf(stderr, "%s", "\n"); return ok; } diff --git a/src/datastore/perf_plugin_datastore.c b/src/datastore/perf_plugin_datastore.c index 564f8f37b..a051f27ca 100644 --- a/src/datastore/perf_plugin_datastore.c +++ b/src/datastore/perf_plugin_datastore.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /* * @file perf_plugin_datastore.c * @brief Profile database plugin directly, focusing on iterators. @@ -59,8 +59,7 @@ static const char *plugin_name; static int ok; -enum RunPhase -{ +enum RunPhase { RP_ERROR = 0, RP_PUT, RP_REP_GET, @@ -70,8 +69,7 @@ enum RunPhase }; -struct CpsRunContext -{ +struct CpsRunContext { unsigned int i; struct GNUNET_TIME_Absolute start; struct GNUNET_TIME_Absolute end; @@ -93,13 +91,13 @@ struct CpsRunContext * 0 for "reset to empty" */ static void -disk_utilization_change_cb (void *cls, int delta) +disk_utilization_change_cb(void *cls, int delta) { } static void -test (void *cls); +test(void *cls); /** @@ -112,30 +110,30 @@ test (void *cls); * @param msg error message on error */ static void -put_continuation (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - int status, - const char *msg) +put_continuation(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + int status, + const char *msg) { struct CpsRunContext *crc = cls; if (GNUNET_OK != status) - { - fprintf (stderr, "ERROR: `%s'\n", msg); - } + { + fprintf(stderr, "ERROR: `%s'\n", msg); + } else - { - stored_bytes += size; - stored_ops++; - stored_entries++; - } - GNUNET_SCHEDULER_add_now (&test, crc); + { + stored_bytes += size; + stored_ops++; + stored_entries++; + } + GNUNET_SCHEDULER_add_now(&test, crc); } static void -do_put (struct CpsRunContext *crc) +do_put(struct CpsRunContext *crc) { char value[65536]; size_t size; @@ -144,66 +142,123 @@ do_put (struct CpsRunContext *crc) unsigned int prio; if (0 == i) - crc->start = GNUNET_TIME_absolute_get (); + crc->start = GNUNET_TIME_absolute_get(); if (PUT_10 == i) - { - i = 0; - crc->end = GNUNET_TIME_absolute_get (); { - printf ("%s took %s for %llu items\n", "Storing an item", - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_difference (crc->start, - crc->end), - GNUNET_YES), - PUT_10); - if (PUT_10 > 0) - GAUGER (category, "Storing an item", - (crc->end.abs_value_us - crc->start.abs_value_us) / 1000LL / PUT_10, - "ms/item"); + i = 0; + crc->end = GNUNET_TIME_absolute_get(); + { + printf("%s took %s for %llu items\n", "Storing an item", + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_difference(crc->start, + crc->end), + GNUNET_YES), + PUT_10); + if (PUT_10 > 0) + GAUGER(category, "Storing an item", + (crc->end.abs_value_us - crc->start.abs_value_us) / 1000LL / PUT_10, + "ms/item"); + } + crc->i++; + crc->start = GNUNET_TIME_absolute_get(); + crc->phase++; + GNUNET_SCHEDULER_add_now(&test, crc); + return; } - crc->i++; - crc->start = GNUNET_TIME_absolute_get (); - crc->phase++; - GNUNET_SCHEDULER_add_now (&test, crc); - return; - } /* most content is 32k */ size = 32 * 1024; - if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 16) == 0) /* but some of it is less! */ - size = 8 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 32 * 1024); + if (GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 16) == 0) /* but some of it is less! */ + size = 8 + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 32 * 1024); size = size - (size & 7); /* always multiple of 8 */ /* generate random key */ - key.bits[0] = (unsigned int) GNUNET_TIME_absolute_get ().abs_value_us; - GNUNET_CRYPTO_hash (&key, sizeof (struct GNUNET_HashCode), &key); - memset (value, i, size); + key.bits[0] = (unsigned int)GNUNET_TIME_absolute_get().abs_value_us; + GNUNET_CRYPTO_hash(&key, sizeof(struct GNUNET_HashCode), &key); + memset(value, i, size); if (i > 255) - memset (value, i - 255, size / 2); + memset(value, i - 255, size / 2); value[0] = crc->i; - GNUNET_memcpy (&value[4], &i, sizeof (i)); - prio = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100); - crc->api->put (crc->api->cls, - &key, - false /* absent */, - size, - value, - 1 + i % 4 /* type */ , - prio, - i % 4 /* anonymity */ , - 0 /* replication */ , - GNUNET_TIME_relative_to_absolute - (GNUNET_TIME_relative_multiply - (GNUNET_TIME_UNIT_MILLISECONDS, + GNUNET_memcpy(&value[4], &i, sizeof(i)); + prio = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 100); + crc->api->put(crc->api->cls, + &key, + false /* absent */, + size, + value, + 1 + i % 4 /* type */, + prio, + i % 4 /* anonymity */, + 0 /* replication */, + GNUNET_TIME_relative_to_absolute + (GNUNET_TIME_relative_multiply + (GNUNET_TIME_UNIT_MILLISECONDS, 60 * 60 * 60 * 1000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000))), - put_continuation, - crc); + put_continuation, + crc); i++; } static int -iterate_zeros (void *cls, +iterate_zeros(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) +{ + struct CpsRunContext *crc = cls; + int i; + const char *cdata = data; + + GNUNET_assert(key != NULL); + GNUNET_assert(size >= 8); + GNUNET_memcpy(&i, &cdata[4], sizeof(i)); + hits[i / 8] |= (1 << (i % 8)); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found result %d type=%u, priority=%u, size=%u, expire=%s\n", + i, + type, priority, size, + GNUNET_STRINGS_absolute_time_to_string(expiration)); + crc->cnt++; + if (crc->cnt == PUT_10 / 4 - 1) + { + unsigned int bc; + + bc = 0; + for (i = 0; i < PUT_10; i++) + if (0 != (hits[i / 8] & (1 << (i % 8)))) + bc++; + + crc->end = GNUNET_TIME_absolute_get(); + printf("%s took %s yielding %u/%u items\n", + "Select random zero-anonymity item", + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_difference(crc->start, + crc->end), + GNUNET_YES), + bc, crc->cnt); + if (crc->cnt > 0) + GAUGER(category, "Select random zero-anonymity item", + (crc->end.abs_value_us - crc->start.abs_value_us) / 1000LL / crc->cnt, + "ms/item"); + memset(hits, 0, sizeof(hits)); + crc->phase++; + crc->cnt = 0; + crc->start = GNUNET_TIME_absolute_get(); + } + GNUNET_SCHEDULER_add_now(&test, crc); + return GNUNET_OK; +} + + +static int +expiration_get(void *cls, const struct GNUNET_HashCode *key, uint32_t size, const void *data, @@ -218,49 +273,45 @@ iterate_zeros (void *cls, int i; const char *cdata = data; - GNUNET_assert (key != NULL); - GNUNET_assert (size >= 8); - GNUNET_memcpy (&i, &cdata[4], sizeof (i)); + GNUNET_assert(size >= 8); + GNUNET_memcpy(&i, &cdata[4], sizeof(i)); hits[i / 8] |= (1 << (i % 8)); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found result %d type=%u, priority=%u, size=%u, expire=%s\n", - i, - type, priority, size, - GNUNET_STRINGS_absolute_time_to_string (expiration)); crc->cnt++; - if (crc->cnt == PUT_10 / 4 - 1) - { - unsigned int bc; - - bc = 0; - for (i = 0; i < PUT_10; i++) - if (0 != (hits[i / 8] & (1 << (i % 8)))) - bc++; - - crc->end = GNUNET_TIME_absolute_get (); - printf ("%s took %s yielding %u/%u items\n", - "Select random zero-anonymity item", - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_difference (crc->start, - crc->end), - GNUNET_YES), - bc, crc->cnt); - if (crc->cnt > 0) - GAUGER (category, "Select random zero-anonymity item", - (crc->end.abs_value_us - crc->start.abs_value_us) / 1000LL / crc->cnt, - "ms/item"); - memset (hits, 0, sizeof (hits)); - crc->phase++; - crc->cnt = 0; - crc->start = GNUNET_TIME_absolute_get (); - } - GNUNET_SCHEDULER_add_now (&test, crc); - return GNUNET_OK; + if (PUT_10 <= crc->cnt) + { + unsigned int bc; + + bc = 0; + for (i = 0; i < PUT_10; i++) + if (0 != (hits[i / 8] & (1 << (i % 8)))) + bc++; + + crc->end = GNUNET_TIME_absolute_get(); + printf("%s took %s yielding %u/%u items\n", + "Selecting and deleting by expiration", + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_difference(crc->start, + crc->end), + GNUNET_YES), + bc, (unsigned int)PUT_10); + if (crc->cnt > 0) + GAUGER(category, "Selecting and deleting by expiration", + (crc->end.abs_value_us - crc->start.abs_value_us) / 1000LL / crc->cnt, + "ms/item"); + memset(hits, 0, sizeof(hits)); + if (++crc->iter == ITERATIONS) + crc->phase++; + else + crc->phase = RP_PUT; + crc->cnt = 0; + crc->start = GNUNET_TIME_absolute_get(); + } + GNUNET_SCHEDULER_add_now(&test, crc); + return GNUNET_NO; } static int -expiration_get (void *cls, +replication_get(void *cls, const struct GNUNET_HashCode *key, uint32_t size, const void *data, @@ -275,92 +326,39 @@ expiration_get (void *cls, int i; const char *cdata = data; - GNUNET_assert (size >= 8); - GNUNET_memcpy (&i, &cdata[4], sizeof (i)); + GNUNET_assert(NULL != key); + GNUNET_assert(size >= 8); + GNUNET_memcpy(&i, &cdata[4], sizeof(i)); hits[i / 8] |= (1 << (i % 8)); crc->cnt++; if (PUT_10 <= crc->cnt) - { - unsigned int bc; - - bc = 0; - for (i = 0; i < PUT_10; i++) - if (0 != (hits[i / 8] & (1 << (i % 8)))) - bc++; - - crc->end = GNUNET_TIME_absolute_get (); - printf ("%s took %s yielding %u/%u items\n", - "Selecting and deleting by expiration", - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_difference (crc->start, - crc->end), - GNUNET_YES), - bc, (unsigned int) PUT_10); - if (crc->cnt > 0) - GAUGER (category, "Selecting and deleting by expiration", - (crc->end.abs_value_us - crc->start.abs_value_us) / 1000LL / crc->cnt, - "ms/item"); - memset (hits, 0, sizeof (hits)); - if (++crc->iter == ITERATIONS) + { + unsigned int bc; + + bc = 0; + for (i = 0; i < PUT_10; i++) + if (0 != (hits[i / 8] & (1 << (i % 8)))) + bc++; + + crc->end = GNUNET_TIME_absolute_get(); + printf("%s took %s yielding %u/%u items\n", + "Selecting random item for replication", + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_difference(crc->start, + crc->end), + GNUNET_YES), + bc, (unsigned int)PUT_10); + if (crc->cnt > 0) + GAUGER(category, "Selecting random item for replication", + (crc->end.abs_value_us - crc->start.abs_value_us) / 1000LL / crc->cnt, + "ms/item"); + memset(hits, 0, sizeof(hits)); crc->phase++; - else - crc->phase = RP_PUT; - crc->cnt = 0; - crc->start = GNUNET_TIME_absolute_get (); - } - GNUNET_SCHEDULER_add_now (&test, crc); - return GNUNET_NO; -} - - -static int -replication_get (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) -{ - struct CpsRunContext *crc = cls; - int i; - const char *cdata = data; + crc->offset = 0; + crc->cnt = 0; + crc->start = GNUNET_TIME_absolute_get(); + } - GNUNET_assert (NULL != key); - GNUNET_assert (size >= 8); - GNUNET_memcpy (&i, &cdata[4], sizeof (i)); - hits[i / 8] |= (1 << (i % 8)); - crc->cnt++; - if (PUT_10 <= crc->cnt) - { - unsigned int bc; - - bc = 0; - for (i = 0; i < PUT_10; i++) - if (0 != (hits[i / 8] & (1 << (i % 8)))) - bc++; - - crc->end = GNUNET_TIME_absolute_get (); - printf ("%s took %s yielding %u/%u items\n", - "Selecting random item for replication", - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_difference (crc->start, - crc->end), - GNUNET_YES), - bc, (unsigned int) PUT_10); - if (crc->cnt > 0) - GAUGER (category, "Selecting random item for replication", - (crc->end.abs_value_us - crc->start.abs_value_us) / 1000LL / crc->cnt, - "ms/item"); - memset (hits, 0, sizeof (hits)); - crc->phase++; - crc->offset = 0; - crc->cnt = 0; - crc->start = GNUNET_TIME_absolute_get (); - } - - GNUNET_SCHEDULER_add_now (&test, crc); + GNUNET_SCHEDULER_add_now(&test, crc); return GNUNET_OK; } @@ -373,25 +371,25 @@ replication_get (void *cls, * @param cfg configuration to use */ static void -unload_plugin (struct GNUNET_DATASTORE_PluginFunctions *api, - const struct GNUNET_CONFIGURATION_Handle *cfg) +unload_plugin(struct GNUNET_DATASTORE_PluginFunctions *api, + const struct GNUNET_CONFIGURATION_Handle *cfg) { char *name; char *libname; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, "DATASTORE", "DATABASE", - &name)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No `%s' specified for `%s' in configuration!\n"), "DATABASE", - "DATASTORE"); - return; - } - GNUNET_asprintf (&libname, "libgnunet_plugin_datastore_%s", name); - GNUNET_break (NULL == GNUNET_PLUGIN_unload (libname, api)); - GNUNET_free (libname); - GNUNET_free (name); + GNUNET_CONFIGURATION_get_value_string(cfg, "DATASTORE", "DATABASE", + &name)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No `%s' specified for `%s' in configuration!\n"), "DATABASE", + "DATASTORE"); + return; + } + GNUNET_asprintf(&libname, "libgnunet_plugin_datastore_%s", name); + GNUNET_break(NULL == GNUNET_PLUGIN_unload(libname, api)); + GNUNET_free(libname); + GNUNET_free(name); } @@ -401,51 +399,56 @@ unload_plugin (struct GNUNET_DATASTORE_PluginFunctions *api, * the transport and core. */ static void -cleaning_task (void *cls) +cleaning_task(void *cls) { struct CpsRunContext *crc = cls; - unload_plugin (crc->api, crc->cfg); - GNUNET_free (crc); + unload_plugin(crc->api, crc->cfg); + GNUNET_free(crc); } static void -test (void *cls) +test(void *cls) { struct CpsRunContext *crc = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "In phase %d, iteration %u\n", crc->phase, crc->cnt); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "In phase %d, iteration %u\n", crc->phase, crc->cnt); switch (crc->phase) - { - case RP_ERROR: - GNUNET_break (0); - crc->api->drop (crc->api->cls); - ok = 1; - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE, - &cleaning_task, crc); - break; - case RP_PUT: - do_put (crc); - break; - case RP_REP_GET: - crc->api->get_replication (crc->api->cls, &replication_get, crc); - break; - case RP_ZA_GET: - crc->api->get_zero_anonymity (crc->api->cls, crc->offset++, 1, - &iterate_zeros, crc); - break; - case RP_EXP_GET: - crc->api->get_expiration (crc->api->cls, &expiration_get, crc); - break; - case RP_DONE: - crc->api->drop (crc->api->cls); - ok = 0; - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE, - &cleaning_task, crc); - break; - } + { + case RP_ERROR: + GNUNET_break(0); + crc->api->drop(crc->api->cls); + ok = 1; + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_IDLE, + &cleaning_task, crc); + break; + + case RP_PUT: + do_put(crc); + break; + + case RP_REP_GET: + crc->api->get_replication(crc->api->cls, &replication_get, crc); + break; + + case RP_ZA_GET: + crc->api->get_zero_anonymity(crc->api->cls, crc->offset++, 1, + &iterate_zeros, crc); + break; + + case RP_EXP_GET: + crc->api->get_expiration(crc->api->cls, &expiration_get, crc); + break; + + case RP_DONE: + crc->api->drop(crc->api->cls); + ok = 0; + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_IDLE, + &cleaning_task, crc); + break; + } } @@ -453,7 +456,7 @@ test (void *cls) * Load the datastore plugin. */ static struct GNUNET_DATASTORE_PluginFunctions * -load_plugin (const struct GNUNET_CONFIGURATION_Handle *cfg) +load_plugin(const struct GNUNET_CONFIGURATION_Handle *cfg) { static struct GNUNET_DATASTORE_PluginEnvironment env; struct GNUNET_DATASTORE_PluginFunctions *ret; @@ -461,63 +464,63 @@ load_plugin (const struct GNUNET_CONFIGURATION_Handle *cfg) char *libname; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, "DATASTORE", "DATABASE", - &name)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No `%s' specified for `%s' in configuration!\n"), "DATABASE", - "DATASTORE"); - return NULL; - } + GNUNET_CONFIGURATION_get_value_string(cfg, "DATASTORE", "DATABASE", + &name)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No `%s' specified for `%s' in configuration!\n"), "DATABASE", + "DATASTORE"); + return NULL; + } env.cfg = cfg; env.duc = &disk_utilization_change_cb; env.cls = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Loading `%s' datastore plugin\n"), - name); - GNUNET_asprintf (&libname, "libgnunet_plugin_datastore_%s", name); - if (NULL == (ret = GNUNET_PLUGIN_load (libname, &env))) - { - fprintf (stderr, "Failed to load plugin `%s'!\n", name); - GNUNET_free (name); - GNUNET_free (libname); - return NULL; - } - GNUNET_free (libname); - GNUNET_free (name); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Loading `%s' datastore plugin\n"), + name); + GNUNET_asprintf(&libname, "libgnunet_plugin_datastore_%s", name); + if (NULL == (ret = GNUNET_PLUGIN_load(libname, &env))) + { + fprintf(stderr, "Failed to load plugin `%s'!\n", name); + GNUNET_free(name); + GNUNET_free(libname); + return NULL; + } + GNUNET_free(libname); + GNUNET_free(name); return ret; } static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { struct GNUNET_DATASTORE_PluginFunctions *api; struct CpsRunContext *crc; if (NULL == c) - { - GNUNET_break (0); - return; - } - api = load_plugin (c); + { + GNUNET_break(0); + return; + } + api = load_plugin(c); if (api == NULL) - { - fprintf (stderr, - "%s", "Could not initialize plugin, assuming database not configured. Test not run!\n"); - return; - } - crc = GNUNET_new (struct CpsRunContext); + { + fprintf(stderr, + "%s", "Could not initialize plugin, assuming database not configured. Test not run!\n"); + return; + } + crc = GNUNET_new(struct CpsRunContext); crc->api = api; crc->cfg = c; crc->phase = RP_PUT; ok = 2; - GNUNET_SCHEDULER_add_now (&test, crc); + GNUNET_SCHEDULER_add_now(&test, crc); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { char dir_name[PATH_MAX]; char cfg_name[PATH_MAX]; @@ -531,21 +534,21 @@ main (int argc, char *argv[]) GNUNET_GETOPT_OPTION_END }; - plugin_name = GNUNET_TESTING_get_testname_from_underscore (argv[0]); - GNUNET_snprintf (dir_name, sizeof (dir_name), "/tmp/perf-gnunet-datastore-%s", - plugin_name); - GNUNET_DISK_directory_remove (dir_name); - GNUNET_log_setup ("perf-plugin-datastore", - "WARNING", - NULL); - GNUNET_snprintf (category, sizeof (category), "DATASTORE-%s", plugin_name); - GNUNET_snprintf (cfg_name, sizeof (cfg_name), - "perf_plugin_datastore_data_%s.conf", plugin_name); - GNUNET_PROGRAM_run ((sizeof (xargv) / sizeof (char *)) - 1, xargv, - "perf-plugin-datastore", "nohelp", options, &run, NULL); + plugin_name = GNUNET_TESTING_get_testname_from_underscore(argv[0]); + GNUNET_snprintf(dir_name, sizeof(dir_name), "/tmp/perf-gnunet-datastore-%s", + plugin_name); + GNUNET_DISK_directory_remove(dir_name); + GNUNET_log_setup("perf-plugin-datastore", + "WARNING", + NULL); + GNUNET_snprintf(category, sizeof(category), "DATASTORE-%s", plugin_name); + GNUNET_snprintf(cfg_name, sizeof(cfg_name), + "perf_plugin_datastore_data_%s.conf", plugin_name); + GNUNET_PROGRAM_run((sizeof(xargv) / sizeof(char *)) - 1, xargv, + "perf-plugin-datastore", "nohelp", options, &run, NULL); if (ok != 0) - fprintf (stderr, "Missed some testcases: %u\n", ok); - GNUNET_DISK_directory_remove (dir_name); + fprintf(stderr, "Missed some testcases: %u\n", ok); + GNUNET_DISK_directory_remove(dir_name); return ok; } diff --git a/src/datastore/plugin_datastore_heap.c b/src/datastore/plugin_datastore_heap.c index 30d271202..b7d73f0c4 100644 --- a/src/datastore/plugin_datastore_heap.c +++ b/src/datastore/plugin_datastore_heap.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datastore/plugin_datastore_heap.c @@ -34,9 +34,7 @@ /** * A value that we are storing. */ -struct Value -{ - +struct Value { /** * Key for the value. */ @@ -92,16 +90,13 @@ struct Value * Type of 'data'. */ enum GNUNET_BLOCK_Type type; - }; /** * We organize 0-anonymity values in arrays "by type". */ -struct ZeroAnonByType -{ - +struct ZeroAnonByType { /** * We keep these in a DLL. */ @@ -137,8 +132,7 @@ struct ZeroAnonByType /** * Context for all functions in this plugin. */ -struct Plugin -{ +struct Plugin { /** * Our execution environment. */ @@ -173,7 +167,6 @@ struct Plugin * Size of all values we're storing. */ unsigned long long size; - }; @@ -185,7 +178,7 @@ struct Plugin * @return number of bytes used on disk */ static void -heap_plugin_estimate_size (void *cls, unsigned long long *estimate) +heap_plugin_estimate_size(void *cls, unsigned long long *estimate) { struct Plugin *plugin = cls; @@ -197,8 +190,7 @@ heap_plugin_estimate_size (void *cls, unsigned long long *estimate) /** * Closure for iterator for updating. */ -struct UpdateContext -{ +struct UpdateContext { /** * Number of bytes in 'data'. */ @@ -240,25 +232,25 @@ struct UpdateContext * @return GNUNET_YES (continue iteration), GNUNET_NO if value was found */ static int -update_iterator (void *cls, - const struct GNUNET_HashCode *key, - void *val) +update_iterator(void *cls, + const struct GNUNET_HashCode *key, + void *val) { struct UpdateContext *uc = cls; struct Value *value = val; if (value->size != uc->size) return GNUNET_YES; - if (0 != memcmp (value->data, uc->data, uc->size)) + if (0 != memcmp(value->data, uc->data, uc->size)) return GNUNET_YES; - uc->expiration = GNUNET_TIME_absolute_max (value->expiration, - uc->expiration); + uc->expiration = GNUNET_TIME_absolute_max(value->expiration, + uc->expiration); if (value->expiration.abs_value_us != uc->expiration.abs_value_us) - { - value->expiration = uc->expiration; - GNUNET_CONTAINER_heap_update_cost (value->expire_heap, - value->expiration.abs_value_us); - } + { + value->expiration = uc->expiration; + GNUNET_CONTAINER_heap_update_cost(value->expire_heap, + value->expiration.abs_value_us); + } /* Saturating adds, don't overflow */ if (value->priority > UINT32_MAX - uc->priority) value->priority = UINT32_MAX; @@ -289,87 +281,88 @@ update_iterator (void *cls, * @param cont_cls continuation closure */ static void -heap_plugin_put (void *cls, - const struct GNUNET_HashCode *key, - bool absent, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - PluginPutCont cont, - void *cont_cls) +heap_plugin_put(void *cls, + const struct GNUNET_HashCode *key, + bool absent, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + PluginPutCont cont, + void *cont_cls) { struct Plugin *plugin = cls; struct Value *value; - if (!absent) { - struct UpdateContext uc; - - uc.size = size; - uc.data = data; - uc.priority = priority; - uc.replication = replication; - uc.expiration = expiration; - uc.updated = false; - GNUNET_CONTAINER_multihashmap_get_multiple (plugin->keyvalue, - key, - &update_iterator, - &uc); - if (uc.updated) + if (!absent) { - cont (cont_cls, key, size, GNUNET_NO, NULL); - return; + struct UpdateContext uc; + + uc.size = size; + uc.data = data; + uc.priority = priority; + uc.replication = replication; + uc.expiration = expiration; + uc.updated = false; + GNUNET_CONTAINER_multihashmap_get_multiple(plugin->keyvalue, + key, + &update_iterator, + &uc); + if (uc.updated) + { + cont(cont_cls, key, size, GNUNET_NO, NULL); + return; + } } - } - value = GNUNET_malloc (sizeof (struct Value) + size); + value = GNUNET_malloc(sizeof(struct Value) + size); value->key = *key; value->data = &value[1]; - value->expire_heap = GNUNET_CONTAINER_heap_insert (plugin->by_expiration, - value, - expiration.abs_value_us); - value->replication_heap = GNUNET_CONTAINER_heap_insert (plugin->by_replication, - value, - replication); + value->expire_heap = GNUNET_CONTAINER_heap_insert(plugin->by_expiration, + value, + expiration.abs_value_us); + value->replication_heap = GNUNET_CONTAINER_heap_insert(plugin->by_replication, + value, + replication); value->expiration = expiration; if (0 == anonymity) - { - struct ZeroAnonByType *zabt; - - for (zabt = plugin->zero_head; NULL != zabt; zabt = zabt->next) - if (zabt->type == type) - break; - if (NULL == zabt) - { - zabt = GNUNET_new (struct ZeroAnonByType); - zabt->type = type; - GNUNET_CONTAINER_DLL_insert (plugin->zero_head, - plugin->zero_tail, - zabt); - } - if (zabt->array_size == zabt->array_pos) { - GNUNET_array_grow (zabt->array, - zabt->array_size, - zabt->array_size * 2 + 4); + struct ZeroAnonByType *zabt; + + for (zabt = plugin->zero_head; NULL != zabt; zabt = zabt->next) + if (zabt->type == type) + break; + if (NULL == zabt) + { + zabt = GNUNET_new(struct ZeroAnonByType); + zabt->type = type; + GNUNET_CONTAINER_DLL_insert(plugin->zero_head, + plugin->zero_tail, + zabt); + } + if (zabt->array_size == zabt->array_pos) + { + GNUNET_array_grow(zabt->array, + zabt->array_size, + zabt->array_size * 2 + 4); + } + value->zero_anon_offset = zabt->array_pos; + zabt->array[zabt->array_pos++] = value; } - value->zero_anon_offset = zabt->array_pos; - zabt->array[zabt->array_pos++] = value; - } value->size = size; value->priority = priority; value->anonymity = anonymity; value->replication = replication; value->type = type; - GNUNET_memcpy (&value[1], data, size); - GNUNET_CONTAINER_multihashmap_put (plugin->keyvalue, - &value->key, - value, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + GNUNET_memcpy(&value[1], data, size); + GNUNET_CONTAINER_multihashmap_put(plugin->keyvalue, + &value->key, + value, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); plugin->size += size; - cont (cont_cls, key, size, GNUNET_OK, NULL); + cont(cont_cls, key, size, GNUNET_OK, NULL); } @@ -381,47 +374,45 @@ heap_plugin_put (void *cls, * @param value value to delete */ static void -delete_value (struct Plugin *plugin, - struct Value *value) +delete_value(struct Plugin *plugin, + struct Value *value) { - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (plugin->keyvalue, - &value->key, - value)); - GNUNET_assert (value == GNUNET_CONTAINER_heap_remove_node (value->expire_heap)); - GNUNET_assert (value == GNUNET_CONTAINER_heap_remove_node (value->replication_heap)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(plugin->keyvalue, + &value->key, + value)); + GNUNET_assert(value == GNUNET_CONTAINER_heap_remove_node(value->expire_heap)); + GNUNET_assert(value == GNUNET_CONTAINER_heap_remove_node(value->replication_heap)); if (0 == value->anonymity) - { - struct ZeroAnonByType *zabt; - - for (zabt = plugin->zero_head; NULL != zabt; zabt = zabt->next) - if (zabt->type == value->type) - break; - GNUNET_assert (NULL != zabt); - zabt->array[value->zero_anon_offset] = zabt->array[--zabt->array_pos]; - zabt->array[value->zero_anon_offset]->zero_anon_offset = value->zero_anon_offset; - if (0 == zabt->array_pos) { - GNUNET_array_grow (zabt->array, - zabt->array_size, - 0); - GNUNET_CONTAINER_DLL_remove (plugin->zero_head, - plugin->zero_tail, - zabt); - GNUNET_free (zabt); + struct ZeroAnonByType *zabt; + + for (zabt = plugin->zero_head; NULL != zabt; zabt = zabt->next) + if (zabt->type == value->type) + break; + GNUNET_assert(NULL != zabt); + zabt->array[value->zero_anon_offset] = zabt->array[--zabt->array_pos]; + zabt->array[value->zero_anon_offset]->zero_anon_offset = value->zero_anon_offset; + if (0 == zabt->array_pos) + { + GNUNET_array_grow(zabt->array, + zabt->array_size, + 0); + GNUNET_CONTAINER_DLL_remove(plugin->zero_head, + plugin->zero_tail, + zabt); + GNUNET_free(zabt); + } } - } plugin->size -= value->size; - GNUNET_free (value); + GNUNET_free(value); } /** * Closure for iterator called during 'get_key'. */ -struct GetContext -{ - +struct GetContext { /** * Lowest uid to consider. */ @@ -441,7 +432,6 @@ struct GetContext * If true, return a random value */ bool random; - }; @@ -454,25 +444,25 @@ struct GetContext * @return GNUNET_YES (continue iteration), GNUNET_NO if result was found */ static int -get_iterator (void *cls, - const struct GNUNET_HashCode *key, - void *val) +get_iterator(void *cls, + const struct GNUNET_HashCode *key, + void *val) { struct GetContext *gc = cls; struct Value *value = val; - if ( (gc->type != GNUNET_BLOCK_TYPE_ANY) && - (gc->type != value->type) ) + if ((gc->type != GNUNET_BLOCK_TYPE_ANY) && + (gc->type != value->type)) return GNUNET_OK; if (gc->random) - { - gc->value = value; - return GNUNET_NO; - } - if ( (uint64_t) (intptr_t) value < gc->next_uid) + { + gc->value = value; + return GNUNET_NO; + } + if ((uint64_t)(intptr_t)value < gc->next_uid) return GNUNET_OK; - if ( (NULL != gc->value) && - (value > gc->value) ) + if ((NULL != gc->value) && + (value > gc->value)) return GNUNET_OK; gc->value = value; return GNUNET_OK; @@ -493,13 +483,13 @@ get_iterator (void *cls, * @param proc_cls closure for @a proc */ static void -heap_plugin_get_key (void *cls, - uint64_t next_uid, - bool random, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - PluginDatumProcessor proc, - void *proc_cls) +heap_plugin_get_key(void *cls, + uint64_t next_uid, + bool random, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; struct GetContext gc; @@ -509,34 +499,34 @@ heap_plugin_get_key (void *cls, gc.random = random; gc.type = type; if (NULL == key) - { - GNUNET_CONTAINER_multihashmap_iterate (plugin->keyvalue, - &get_iterator, - &gc); - } + { + GNUNET_CONTAINER_multihashmap_iterate(plugin->keyvalue, + &get_iterator, + &gc); + } else - { - GNUNET_CONTAINER_multihashmap_get_multiple (plugin->keyvalue, - key, - &get_iterator, - &gc); - } + { + GNUNET_CONTAINER_multihashmap_get_multiple(plugin->keyvalue, + key, + &get_iterator, + &gc); + } if (NULL == gc.value) - { - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } - GNUNET_assert (GNUNET_OK == - proc (proc_cls, - &gc.value->key, - gc.value->size, - &gc.value[1], - gc.value->type, - gc.value->priority, - gc.value->anonymity, - gc.value->replication, - gc.value->expiration, - (uint64_t) (intptr_t) gc.value)); + { + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } + GNUNET_assert(GNUNET_OK == + proc(proc_cls, + &gc.value->key, + gc.value->size, + &gc.value[1], + gc.value->type, + gc.value->priority, + gc.value->anonymity, + gc.value->replication, + gc.value->expiration, + (uint64_t)(intptr_t)gc.value)); } @@ -552,45 +542,45 @@ heap_plugin_get_key (void *cls, * @param proc_cls closure for proc */ static void -heap_plugin_get_replication (void *cls, - PluginDatumProcessor proc, - void *proc_cls) +heap_plugin_get_replication(void *cls, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; struct Value *value; - value = GNUNET_CONTAINER_heap_remove_root (plugin->by_replication); + value = GNUNET_CONTAINER_heap_remove_root(plugin->by_replication); if (NULL == value) - { - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } + { + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } if (value->replication > 0) - { - value->replication--; - value->replication_heap = GNUNET_CONTAINER_heap_insert (plugin->by_replication, - value, - value->replication); - } + { + value->replication--; + value->replication_heap = GNUNET_CONTAINER_heap_insert(plugin->by_replication, + value, + value->replication); + } else - { - /* need a better way to pick a random item, replication level is always 0 */ - value->replication_heap = GNUNET_CONTAINER_heap_insert (plugin->by_replication, - value, - value->replication); - value = GNUNET_CONTAINER_heap_walk_get_next (plugin->by_replication); - } - GNUNET_assert (GNUNET_OK == - proc (proc_cls, - &value->key, - value->size, - &value[1], - value->type, - value->priority, - value->anonymity, - value->replication, - value->expiration, - (uint64_t) (intptr_t) value)); + { + /* need a better way to pick a random item, replication level is always 0 */ + value->replication_heap = GNUNET_CONTAINER_heap_insert(plugin->by_replication, + value, + value->replication); + value = GNUNET_CONTAINER_heap_walk_get_next(plugin->by_replication); + } + GNUNET_assert(GNUNET_OK == + proc(proc_cls, + &value->key, + value->size, + &value[1], + value->type, + value->priority, + value->anonymity, + value->replication, + value->expiration, + (uint64_t)(intptr_t)value)); } @@ -603,30 +593,30 @@ heap_plugin_get_replication (void *cls, * @param proc_cls closure for proc */ static void -heap_plugin_get_expiration (void *cls, PluginDatumProcessor proc, - void *proc_cls) +heap_plugin_get_expiration(void *cls, PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; struct Value *value; - value = GNUNET_CONTAINER_heap_peek (plugin->by_expiration); + value = GNUNET_CONTAINER_heap_peek(plugin->by_expiration); if (NULL == value) - { - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } + { + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } if (GNUNET_NO == - proc (proc_cls, - &value->key, - value->size, - &value[1], - value->type, - value->priority, - value->anonymity, - value->replication, - value->expiration, - (uint64_t) (intptr_t) value)) - delete_value (plugin, value); + proc(proc_cls, + &value->key, + value->size, + &value[1], + value->type, + value->priority, + value->anonymity, + value->replication, + value->expiration, + (uint64_t)(intptr_t)value)) + delete_value(plugin, value); } @@ -642,45 +632,45 @@ heap_plugin_get_expiration (void *cls, PluginDatumProcessor proc, * @param proc_cls closure for proc */ static void -heap_plugin_get_zero_anonymity (void *cls, uint64_t next_uid, - enum GNUNET_BLOCK_Type type, - PluginDatumProcessor proc, void *proc_cls) +heap_plugin_get_zero_anonymity(void *cls, uint64_t next_uid, + enum GNUNET_BLOCK_Type type, + PluginDatumProcessor proc, void *proc_cls) { struct Plugin *plugin = cls; struct ZeroAnonByType *zabt; struct Value *value = NULL; for (zabt = plugin->zero_head; NULL != zabt; zabt = zabt->next) - { - if ( (type != GNUNET_BLOCK_TYPE_ANY) && - (type != zabt->type) ) - continue; - for (int i = 0; i < zabt->array_pos; ++i) { - if ( (uint64_t) (intptr_t) zabt->array[i] < next_uid) - continue; - if ( (NULL != value) && - (zabt->array[i] > value) ) + if ((type != GNUNET_BLOCK_TYPE_ANY) && + (type != zabt->type)) continue; - value = zabt->array[i]; + for (int i = 0; i < zabt->array_pos; ++i) + { + if ((uint64_t)(intptr_t)zabt->array[i] < next_uid) + continue; + if ((NULL != value) && + (zabt->array[i] > value)) + continue; + value = zabt->array[i]; + } } - } if (NULL == value) - { - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } - GNUNET_assert (GNUNET_OK == - proc (proc_cls, - &value->key, - value->size, - &value[1], - value->type, - value->priority, - value->anonymity, - value->replication, - value->expiration, - (uint64_t) (intptr_t) value)); + { + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } + GNUNET_assert(GNUNET_OK == + proc(proc_cls, + &value->key, + value->size, + &value[1], + value->type, + value->priority, + value->anonymity, + value->replication, + value->expiration, + (uint64_t)(intptr_t)value)); } @@ -688,7 +678,7 @@ heap_plugin_get_zero_anonymity (void *cls, uint64_t next_uid, * Drop database. */ static void -heap_plugin_drop (void *cls) +heap_plugin_drop(void *cls) { /* nothing needs to be done */ } @@ -697,8 +687,7 @@ heap_plugin_drop (void *cls) /** * Closure for the 'return_value' function. */ -struct GetAllContext -{ +struct GetAllContext { /** * Function to call. */ @@ -720,15 +709,15 @@ struct GetAllContext * @return GNUNET_OK (continue to iterate) */ static int -return_value (void *cls, - const struct GNUNET_HashCode *key, - void *val) +return_value(void *cls, + const struct GNUNET_HashCode *key, + void *val) { struct GetAllContext *gac = cls; - gac->proc (gac->proc_cls, - key, - 1); + gac->proc(gac->proc_cls, + key, + 1); return GNUNET_OK; } @@ -741,28 +730,26 @@ return_value (void *cls, * @param proc_cls closure for proc */ static void -heap_get_keys (void *cls, - PluginKeyProcessor proc, - void *proc_cls) +heap_get_keys(void *cls, + PluginKeyProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; struct GetAllContext gac; gac.proc = proc; gac.proc_cls = proc_cls; - GNUNET_CONTAINER_multihashmap_iterate (plugin->keyvalue, - &return_value, - &gac); - proc (proc_cls, NULL, 0); + GNUNET_CONTAINER_multihashmap_iterate(plugin->keyvalue, + &return_value, + &gac); + proc(proc_cls, NULL, 0); } /** * Closure for iterator called during 'remove_key'. */ -struct RemoveContext -{ - +struct RemoveContext { /** * Value found. */ @@ -777,7 +764,6 @@ struct RemoveContext * Data to remove. */ const void *data; - }; @@ -790,16 +776,16 @@ struct RemoveContext * @return GNUNET_YES (continue iteration), GNUNET_NO if result was found */ static int -remove_iterator (void *cls, - const struct GNUNET_HashCode *key, - void *val) +remove_iterator(void *cls, + const struct GNUNET_HashCode *key, + void *val) { struct RemoveContext *rc = cls; struct Value *value = val; if (value->size != rc->size) return GNUNET_YES; - if (0 != memcmp (value->data, rc->data, rc->size)) + if (0 != memcmp(value->data, rc->data, rc->size)) return GNUNET_YES; rc->value = value; return GNUNET_NO; @@ -817,12 +803,12 @@ remove_iterator (void *cls, * @param cont_cls continuation closure for @a cont */ static void -heap_plugin_remove_key (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - PluginRemoveCont cont, - void *cont_cls) +heap_plugin_remove_key(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + PluginRemoveCont cont, + void *cont_cls) { struct Plugin *plugin = cls; struct RemoveContext rc; @@ -830,26 +816,26 @@ heap_plugin_remove_key (void *cls, rc.value = NULL; rc.size = size; rc.data = data; - GNUNET_CONTAINER_multihashmap_get_multiple (plugin->keyvalue, - key, - &remove_iterator, - &rc); + GNUNET_CONTAINER_multihashmap_get_multiple(plugin->keyvalue, + key, + &remove_iterator, + &rc); if (NULL == rc.value) - { - cont (cont_cls, - key, - size, - GNUNET_NO, - NULL); - return; - } - delete_value (plugin, - rc.value); - cont (cont_cls, - key, - size, - GNUNET_OK, - NULL); + { + cont(cont_cls, + key, + size, + GNUNET_NO, + NULL); + return; + } + delete_value(plugin, + rc.value); + cont(cont_cls, + key, + size, + GNUNET_OK, + NULL); } @@ -860,7 +846,7 @@ heap_plugin_remove_key (void *cls, * @return our "struct Plugin*" */ void * -libgnunet_plugin_datastore_heap_init (void *cls) +libgnunet_plugin_datastore_heap_init(void *cls) { struct GNUNET_DATASTORE_PluginEnvironment *env = cls; struct GNUNET_DATASTORE_PluginFunctions *api; @@ -868,17 +854,17 @@ libgnunet_plugin_datastore_heap_init (void *cls) unsigned long long esize; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (env->cfg, - "datastore-heap", - "HASHMAPSIZE", - &esize)) + GNUNET_CONFIGURATION_get_value_number(env->cfg, + "datastore-heap", + "HASHMAPSIZE", + &esize)) esize = 128 * 1024; - plugin = GNUNET_new (struct Plugin); + plugin = GNUNET_new(struct Plugin); plugin->env = env; - plugin->keyvalue = GNUNET_CONTAINER_multihashmap_create (esize, GNUNET_YES); - plugin->by_expiration = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); - plugin->by_replication = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MAX); - api = GNUNET_new (struct GNUNET_DATASTORE_PluginFunctions); + plugin->keyvalue = GNUNET_CONTAINER_multihashmap_create(esize, GNUNET_YES); + plugin->by_expiration = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN); + plugin->by_replication = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MAX); + api = GNUNET_new(struct GNUNET_DATASTORE_PluginFunctions); api->cls = plugin; api->estimate_size = &heap_plugin_estimate_size; api->put = &heap_plugin_put; @@ -889,8 +875,8 @@ libgnunet_plugin_datastore_heap_init (void *cls) api->drop = &heap_plugin_drop; api->get_keys = &heap_get_keys; api->remove_key = &heap_plugin_remove_key; - GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "heap", - _("Heap database running\n")); + GNUNET_log_from(GNUNET_ERROR_TYPE_INFO, "heap", + _("Heap database running\n")); return api; } @@ -904,14 +890,14 @@ libgnunet_plugin_datastore_heap_init (void *cls) * @return GNUNET_OK (continue to iterate) */ static int -free_value (void *cls, - const struct GNUNET_HashCode *key, - void *val) +free_value(void *cls, + const struct GNUNET_HashCode *key, + void *val) { struct Plugin *plugin = cls; struct Value *value = val; - delete_value (plugin, value); + delete_value(plugin, value); return GNUNET_OK; } @@ -922,19 +908,19 @@ free_value (void *cls, * @return always NULL */ void * -libgnunet_plugin_datastore_heap_done (void *cls) +libgnunet_plugin_datastore_heap_done(void *cls) { struct GNUNET_DATASTORE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - GNUNET_CONTAINER_multihashmap_iterate (plugin->keyvalue, - &free_value, - plugin); - GNUNET_CONTAINER_multihashmap_destroy (plugin->keyvalue); - GNUNET_CONTAINER_heap_destroy (plugin->by_expiration); - GNUNET_CONTAINER_heap_destroy (plugin->by_replication); - GNUNET_free (plugin); - GNUNET_free (api); + GNUNET_CONTAINER_multihashmap_iterate(plugin->keyvalue, + &free_value, + plugin); + GNUNET_CONTAINER_multihashmap_destroy(plugin->keyvalue); + GNUNET_CONTAINER_heap_destroy(plugin->by_expiration); + GNUNET_CONTAINER_heap_destroy(plugin->by_replication); + GNUNET_free(plugin); + GNUNET_free(api); return NULL; } diff --git a/src/datastore/plugin_datastore_mysql.c b/src/datastore/plugin_datastore_mysql.c index 68371d389..c670a6d99 100644 --- a/src/datastore/plugin_datastore_mysql.c +++ b/src/datastore/plugin_datastore_mysql.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datastore/plugin_datastore_mysql.c @@ -129,8 +129,7 @@ /** * Context for all functions in this plugin. */ -struct Plugin -{ +struct Plugin { /** * Our execution environment. */ @@ -150,41 +149,41 @@ struct Plugin #define DELETE_ENTRY_BY_UID "DELETE FROM gn090 WHERE uid=?" struct GNUNET_MYSQL_StatementHandle *delete_entry_by_uid; -#define DELETE_ENTRY_BY_HASH_VALUE "DELETE FROM gn090 "\ - "WHERE hash = ? AND "\ - "value = ? "\ +#define DELETE_ENTRY_BY_HASH_VALUE "DELETE FROM gn090 " \ + "WHERE hash = ? AND " \ + "value = ? " \ "LIMIT 1" struct GNUNET_MYSQL_StatementHandle *delete_entry_by_hash_value; #define RESULT_COLUMNS "repl, type, prio, anonLevel, expire, hash, value, uid" -#define SELECT_ENTRY "SELECT " RESULT_COLUMNS " FROM gn090 "\ - "WHERE uid >= ? AND "\ - "(rvalue >= ? OR 0 = ?) "\ +#define SELECT_ENTRY "SELECT " RESULT_COLUMNS " FROM gn090 " \ + "WHERE uid >= ? AND " \ + "(rvalue >= ? OR 0 = ?) " \ "ORDER BY uid LIMIT 1" struct GNUNET_MYSQL_StatementHandle *select_entry; -#define SELECT_ENTRY_BY_HASH "SELECT " RESULT_COLUMNS " FROM gn090 "\ - "FORCE INDEX (idx_hash_type_uid) "\ - "WHERE hash=? AND "\ - "uid >= ? AND "\ - "(rvalue >= ? OR 0 = ?) "\ +#define SELECT_ENTRY_BY_HASH "SELECT " RESULT_COLUMNS " FROM gn090 " \ + "FORCE INDEX (idx_hash_type_uid) " \ + "WHERE hash=? AND " \ + "uid >= ? AND " \ + "(rvalue >= ? OR 0 = ?) " \ "ORDER BY uid LIMIT 1" struct GNUNET_MYSQL_StatementHandle *select_entry_by_hash; -#define SELECT_ENTRY_BY_HASH_AND_TYPE "SELECT " RESULT_COLUMNS " FROM gn090 "\ - "FORCE INDEX (idx_hash_type_uid) "\ - "WHERE hash = ? AND "\ - "type = ? AND "\ - "uid >= ? AND "\ - "(rvalue >= ? OR 0 = ?) "\ +#define SELECT_ENTRY_BY_HASH_AND_TYPE "SELECT " RESULT_COLUMNS " FROM gn090 " \ + "FORCE INDEX (idx_hash_type_uid) " \ + "WHERE hash = ? AND " \ + "type = ? AND " \ + "uid >= ? AND " \ + "(rvalue >= ? OR 0 = ?) " \ "ORDER BY uid LIMIT 1" struct GNUNET_MYSQL_StatementHandle *select_entry_by_hash_and_type; -#define UPDATE_ENTRY "UPDATE gn090 SET "\ - "prio = prio + ?, "\ - "repl = repl + ?, "\ - "expire = GREATEST(expire, ?) "\ +#define UPDATE_ENTRY "UPDATE gn090 SET " \ + "prio = prio + ?, " \ + "repl = repl + ?, " \ + "expire = GREATEST(expire, ?) " \ "WHERE hash = ? AND vhash = ?" struct GNUNET_MYSQL_StatementHandle *update_entry; @@ -194,31 +193,31 @@ struct Plugin #define SELECT_SIZE "SELECT SUM(LENGTH(value)+256) FROM gn090" struct GNUNET_MYSQL_StatementHandle *get_size; -#define SELECT_IT_NON_ANONYMOUS "SELECT " RESULT_COLUMNS " FROM gn090 "\ - "FORCE INDEX (idx_anonLevel_type_rvalue) "\ - "WHERE anonLevel=0 AND "\ - "type=? AND "\ - "uid >= ? "\ +#define SELECT_IT_NON_ANONYMOUS "SELECT " RESULT_COLUMNS " FROM gn090 " \ + "FORCE INDEX (idx_anonLevel_type_rvalue) " \ + "WHERE anonLevel=0 AND " \ + "type=? AND " \ + "uid >= ? " \ "ORDER BY uid LIMIT 1" struct GNUNET_MYSQL_StatementHandle *zero_iter; -#define SELECT_IT_EXPIRATION "SELECT " RESULT_COLUMNS " FROM gn090 "\ - "FORCE INDEX (idx_expire) "\ - "WHERE expire < ? "\ +#define SELECT_IT_EXPIRATION "SELECT " RESULT_COLUMNS " FROM gn090 " \ + "FORCE INDEX (idx_expire) " \ + "WHERE expire < ? " \ "ORDER BY expire ASC LIMIT 1" struct GNUNET_MYSQL_StatementHandle *select_expiration; -#define SELECT_IT_PRIORITY "SELECT " RESULT_COLUMNS " FROM gn090 "\ - "FORCE INDEX (idx_prio) "\ +#define SELECT_IT_PRIORITY "SELECT " RESULT_COLUMNS " FROM gn090 " \ + "FORCE INDEX (idx_prio) " \ "ORDER BY prio ASC LIMIT 1" struct GNUNET_MYSQL_StatementHandle *select_priority; -#define SELECT_IT_REPLICATION "SELECT " RESULT_COLUMNS " FROM gn090 "\ - "FORCE INDEX (idx_repl_rvalue) "\ - "WHERE repl=? AND "\ - " (rvalue>=? OR"\ - " NOT EXISTS (SELECT 1 FROM gn090 FORCE INDEX (idx_repl_rvalue) WHERE repl=? AND rvalue>=?)) "\ - "ORDER BY rvalue ASC "\ +#define SELECT_IT_REPLICATION "SELECT " RESULT_COLUMNS " FROM gn090 " \ + "FORCE INDEX (idx_repl_rvalue) " \ + "WHERE repl=? AND " \ + " (rvalue>=? OR" \ + " NOT EXISTS (SELECT 1 FROM gn090 FORCE INDEX (idx_repl_rvalue) WHERE repl=? AND rvalue>=?)) " \ + "ORDER BY rvalue ASC " \ "LIMIT 1" struct GNUNET_MYSQL_StatementHandle *select_replication; @@ -227,7 +226,6 @@ struct Plugin #define GET_ALL_KEYS "SELECT hash from gn090" struct GNUNET_MYSQL_StatementHandle *get_all_keys; - }; #define MAX_PARAM 16 @@ -240,29 +238,29 @@ struct Plugin * @return #GNUNET_OK on success, #GNUNET_NO if no such value exists, #GNUNET_SYSERR on error */ static int -do_delete_entry (struct Plugin *plugin, - unsigned long long uid) +do_delete_entry(struct Plugin *plugin, + unsigned long long uid) { int ret; - uint64_t uid64 = (uint64_t) uid; + uint64_t uid64 = (uint64_t)uid; struct GNUNET_MY_QueryParam params_delete[] = { - GNUNET_MY_query_param_uint64 (&uid64), + GNUNET_MY_query_param_uint64(&uid64), GNUNET_MY_query_param_end }; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Deleting value %llu from gn090 table\n", - uid); - ret = GNUNET_MY_exec_prepared (plugin->mc, - plugin->delete_entry_by_uid, - params_delete); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Deleting value %llu from gn090 table\n", + uid); + ret = GNUNET_MY_exec_prepared(plugin->mc, + plugin->delete_entry_by_uid, + params_delete); if (ret >= 0) - { - return GNUNET_OK; - } - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Deleting value %llu from gn090 table failed\n", - (unsigned long long) uid); + { + return GNUNET_OK; + } + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Deleting value %llu from gn090 table failed\n", + (unsigned long long)uid); return ret; } @@ -275,8 +273,8 @@ do_delete_entry (struct Plugin *plugin, * @return number of bytes used on disk */ static void -mysql_plugin_estimate_size (void *cls, - unsigned long long *estimate) +mysql_plugin_estimate_size(void *cls, + unsigned long long *estimate) { struct Plugin *plugin = cls; uint64_t total; @@ -285,29 +283,29 @@ mysql_plugin_estimate_size (void *cls, GNUNET_MY_query_param_end }; struct GNUNET_MY_ResultSpec results_get[] = { - GNUNET_MY_result_spec_uint64 (&total), + GNUNET_MY_result_spec_uint64(&total), GNUNET_MY_result_spec_end }; - ret = GNUNET_MY_exec_prepared (plugin->mc, - plugin->get_size, - params_get); + ret = GNUNET_MY_exec_prepared(plugin->mc, + plugin->get_size, + params_get); *estimate = 0; total = UINT64_MAX; - if ( (GNUNET_OK == ret) && - (GNUNET_OK == - GNUNET_MY_extract_result (plugin->get_size, - results_get)) ) - { - *estimate = (unsigned long long) total; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Size estimate for MySQL payload is %lld\n", - (long long) total); - GNUNET_assert (UINT64_MAX != total); - GNUNET_break (GNUNET_NO == - GNUNET_MY_extract_result (plugin->get_size, + if ((GNUNET_OK == ret) && + (GNUNET_OK == + GNUNET_MY_extract_result(plugin->get_size, + results_get))) + { + *estimate = (unsigned long long)total; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Size estimate for MySQL payload is %lld\n", + (long long)total); + GNUNET_assert(UINT64_MAX != total); + GNUNET_break(GNUNET_NO == + GNUNET_MY_extract_result(plugin->get_size, NULL)); - } + } } @@ -328,116 +326,116 @@ mysql_plugin_estimate_size (void *cls, * @param cont_cls closure for @a cont */ static void -mysql_plugin_put (void *cls, - const struct GNUNET_HashCode *key, - bool absent, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - PluginPutCont cont, - void *cont_cls) +mysql_plugin_put(void *cls, + const struct GNUNET_HashCode *key, + bool absent, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + PluginPutCont cont, + void *cont_cls) { struct Plugin *plugin = cls; uint64_t lexpiration = expiration.abs_value_us; struct GNUNET_HashCode vhash; - GNUNET_CRYPTO_hash (data, - size, - &vhash); + GNUNET_CRYPTO_hash(data, + size, + &vhash); if (!absent) - { - struct GNUNET_MY_QueryParam params_update[] = { - GNUNET_MY_query_param_uint32 (&priority), - GNUNET_MY_query_param_uint32 (&replication), - GNUNET_MY_query_param_uint64 (&lexpiration), - GNUNET_MY_query_param_auto_from_type (key), - GNUNET_MY_query_param_auto_from_type (&vhash), - GNUNET_MY_query_param_end - }; - - if (GNUNET_OK != - GNUNET_MY_exec_prepared (plugin->mc, - plugin->update_entry, - params_update)) { - cont (cont_cls, - key, - size, - GNUNET_SYSERR, - _("MySQL statement run failure")); - return; - } - - MYSQL_STMT *stmt = GNUNET_MYSQL_statement_get_stmt (plugin->update_entry); - my_ulonglong rows = mysql_stmt_affected_rows (stmt); - - GNUNET_break (GNUNET_NO == - GNUNET_MY_extract_result (plugin->update_entry, + struct GNUNET_MY_QueryParam params_update[] = { + GNUNET_MY_query_param_uint32(&priority), + GNUNET_MY_query_param_uint32(&replication), + GNUNET_MY_query_param_uint64(&lexpiration), + GNUNET_MY_query_param_auto_from_type(key), + GNUNET_MY_query_param_auto_from_type(&vhash), + GNUNET_MY_query_param_end + }; + + if (GNUNET_OK != + GNUNET_MY_exec_prepared(plugin->mc, + plugin->update_entry, + params_update)) + { + cont(cont_cls, + key, + size, + GNUNET_SYSERR, + _("MySQL statement run failure")); + return; + } + + MYSQL_STMT *stmt = GNUNET_MYSQL_statement_get_stmt(plugin->update_entry); + my_ulonglong rows = mysql_stmt_affected_rows(stmt); + + GNUNET_break(GNUNET_NO == + GNUNET_MY_extract_result(plugin->update_entry, NULL)); - if (0 != rows) - { - cont (cont_cls, - key, - size, - GNUNET_NO, - NULL); - return; + if (0 != rows) + { + cont(cont_cls, + key, + size, + GNUNET_NO, + NULL); + return; + } } - } - uint64_t lrvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT64_MAX); + uint64_t lrvalue = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, + UINT64_MAX); struct GNUNET_MY_QueryParam params_insert[] = { - GNUNET_MY_query_param_uint32 (&replication), - GNUNET_MY_query_param_uint32 (&type), - GNUNET_MY_query_param_uint32 (&priority), - GNUNET_MY_query_param_uint32 (&anonymity), - GNUNET_MY_query_param_uint64 (&lexpiration), - GNUNET_MY_query_param_uint64 (&lrvalue), - GNUNET_MY_query_param_auto_from_type (key), - GNUNET_MY_query_param_auto_from_type (&vhash), - GNUNET_MY_query_param_fixed_size (data, size), + GNUNET_MY_query_param_uint32(&replication), + GNUNET_MY_query_param_uint32(&type), + GNUNET_MY_query_param_uint32(&priority), + GNUNET_MY_query_param_uint32(&anonymity), + GNUNET_MY_query_param_uint64(&lexpiration), + GNUNET_MY_query_param_uint64(&lrvalue), + GNUNET_MY_query_param_auto_from_type(key), + GNUNET_MY_query_param_auto_from_type(&vhash), + GNUNET_MY_query_param_fixed_size(data, size), GNUNET_MY_query_param_end }; if (size > MAX_DATUM_SIZE) - { - GNUNET_break (0); - cont (cont_cls, key, size, GNUNET_SYSERR, _("Data too large")); - return; - } + { + GNUNET_break(0); + cont(cont_cls, key, size, GNUNET_SYSERR, _("Data too large")); + return; + } if (GNUNET_OK != - GNUNET_MY_exec_prepared (plugin->mc, - plugin->insert_entry, - params_insert)) - { - cont (cont_cls, - key, - size, - GNUNET_SYSERR, - _("MySQL statement run failure")); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Inserted value `%s' with size %u into gn090 table\n", - GNUNET_h2s (key), - (unsigned int) size); + GNUNET_MY_exec_prepared(plugin->mc, + plugin->insert_entry, + params_insert)) + { + cont(cont_cls, + key, + size, + GNUNET_SYSERR, + _("MySQL statement run failure")); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Inserted value `%s' with size %u into gn090 table\n", + GNUNET_h2s(key), + (unsigned int)size); if (size > 0) - plugin->env->duc (plugin->env->cls, - size); - GNUNET_break (GNUNET_NO == - GNUNET_MY_extract_result (plugin->insert_entry, - NULL)); - cont (cont_cls, - key, - size, - GNUNET_OK, - NULL); + plugin->env->duc(plugin->env->cls, + size); + GNUNET_break(GNUNET_NO == + GNUNET_MY_extract_result(plugin->insert_entry, + NULL)); + cont(cont_cls, + key, + size, + GNUNET_OK, + NULL); } @@ -452,11 +450,11 @@ mysql_plugin_put (void *cls, * @param params_select arguments to initialize stmt */ static void -execute_select (struct Plugin *plugin, - struct GNUNET_MYSQL_StatementHandle *stmt, - PluginDatumProcessor proc, - void *proc_cls, - struct GNUNET_MY_QueryParam *params_select) +execute_select(struct Plugin *plugin, + struct GNUNET_MYSQL_StatementHandle *stmt, + PluginDatumProcessor proc, + void *proc_cls, + struct GNUNET_MY_QueryParam *params_select) { int ret; uint32_t replication; @@ -469,65 +467,65 @@ execute_select (struct Plugin *plugin, struct GNUNET_HashCode key; struct GNUNET_TIME_Absolute expiration; struct GNUNET_MY_ResultSpec results_select[] = { - GNUNET_MY_result_spec_uint32 (&replication), - GNUNET_MY_result_spec_uint32 (&type), - GNUNET_MY_result_spec_uint32 (&priority), - GNUNET_MY_result_spec_uint32 (&anonymity), - GNUNET_MY_result_spec_absolute_time (&expiration), - GNUNET_MY_result_spec_auto_from_type (&key), - GNUNET_MY_result_spec_variable_size (&value, &value_size), - GNUNET_MY_result_spec_uint64 (&uid), + GNUNET_MY_result_spec_uint32(&replication), + GNUNET_MY_result_spec_uint32(&type), + GNUNET_MY_result_spec_uint32(&priority), + GNUNET_MY_result_spec_uint32(&anonymity), + GNUNET_MY_result_spec_absolute_time(&expiration), + GNUNET_MY_result_spec_auto_from_type(&key), + GNUNET_MY_result_spec_variable_size(&value, &value_size), + GNUNET_MY_result_spec_uint64(&uid), GNUNET_MY_result_spec_end }; - ret = GNUNET_MY_exec_prepared (plugin->mc, - stmt, - params_select); + ret = GNUNET_MY_exec_prepared(plugin->mc, + stmt, + params_select); if (GNUNET_OK != ret) - { - proc (proc_cls, - NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } - - ret = GNUNET_MY_extract_result (stmt, - results_select); + { + proc(proc_cls, + NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } + + ret = GNUNET_MY_extract_result(stmt, + results_select); if (GNUNET_OK != ret) - { - proc (proc_cls, - NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found %u-byte value under key `%s' with prio %u, anon %u, expire %s selecting from gn090 table\n", - (unsigned int) value_size, - GNUNET_h2s (&key), - (unsigned int) priority, - (unsigned int) anonymity, - GNUNET_STRINGS_absolute_time_to_string (expiration)); - GNUNET_assert (value_size < MAX_DATUM_SIZE); - GNUNET_break (GNUNET_NO == - GNUNET_MY_extract_result (stmt, - NULL)); - ret = proc (proc_cls, - &key, - value_size, - value, - type, - priority, - anonymity, - replication, - expiration, - uid); - GNUNET_MY_cleanup_result (results_select); + { + proc(proc_cls, + NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found %u-byte value under key `%s' with prio %u, anon %u, expire %s selecting from gn090 table\n", + (unsigned int)value_size, + GNUNET_h2s(&key), + (unsigned int)priority, + (unsigned int)anonymity, + GNUNET_STRINGS_absolute_time_to_string(expiration)); + GNUNET_assert(value_size < MAX_DATUM_SIZE); + GNUNET_break(GNUNET_NO == + GNUNET_MY_extract_result(stmt, + NULL)); + ret = proc(proc_cls, + &key, + value_size, + value, + type, + priority, + anonymity, + replication, + expiration, + uid); + GNUNET_MY_cleanup_result(results_select); if (GNUNET_NO == ret) - { - do_delete_entry (plugin, uid); - if (0 != value_size) - plugin->env->duc (plugin->env->cls, - - value_size); - } + { + do_delete_entry(plugin, uid); + if (0 != value_size) + plugin->env->duc(plugin->env->cls, + -value_size); + } } @@ -545,74 +543,74 @@ execute_select (struct Plugin *plugin, * @param proc_cls closure for @a proc */ static void -mysql_plugin_get_key (void *cls, - uint64_t next_uid, - bool random, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - PluginDatumProcessor proc, - void *proc_cls) +mysql_plugin_get_key(void *cls, + uint64_t next_uid, + bool random, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; uint64_t rvalue; if (random) - { - rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT64_MAX); - next_uid = 0; - } + { + rvalue = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, + UINT64_MAX); + next_uid = 0; + } else rvalue = 0; if (NULL == key) - { - struct GNUNET_MY_QueryParam params_select[] = { - GNUNET_MY_query_param_uint64 (&next_uid), - GNUNET_MY_query_param_uint64 (&rvalue), - GNUNET_MY_query_param_uint64 (&rvalue), - GNUNET_MY_query_param_end - }; - - execute_select (plugin, - plugin->select_entry, - proc, - proc_cls, - params_select); - } + { + struct GNUNET_MY_QueryParam params_select[] = { + GNUNET_MY_query_param_uint64(&next_uid), + GNUNET_MY_query_param_uint64(&rvalue), + GNUNET_MY_query_param_uint64(&rvalue), + GNUNET_MY_query_param_end + }; + + execute_select(plugin, + plugin->select_entry, + proc, + proc_cls, + params_select); + } else if (type != GNUNET_BLOCK_TYPE_ANY) - { - struct GNUNET_MY_QueryParam params_select[] = { - GNUNET_MY_query_param_auto_from_type (key), - GNUNET_MY_query_param_uint32 (&type), - GNUNET_MY_query_param_uint64 (&next_uid), - GNUNET_MY_query_param_uint64 (&rvalue), - GNUNET_MY_query_param_uint64 (&rvalue), - GNUNET_MY_query_param_end - }; - - execute_select (plugin, - plugin->select_entry_by_hash_and_type, - proc, - proc_cls, - params_select); - } + { + struct GNUNET_MY_QueryParam params_select[] = { + GNUNET_MY_query_param_auto_from_type(key), + GNUNET_MY_query_param_uint32(&type), + GNUNET_MY_query_param_uint64(&next_uid), + GNUNET_MY_query_param_uint64(&rvalue), + GNUNET_MY_query_param_uint64(&rvalue), + GNUNET_MY_query_param_end + }; + + execute_select(plugin, + plugin->select_entry_by_hash_and_type, + proc, + proc_cls, + params_select); + } else - { - struct GNUNET_MY_QueryParam params_select[] = { - GNUNET_MY_query_param_auto_from_type (key), - GNUNET_MY_query_param_uint64 (&next_uid), - GNUNET_MY_query_param_uint64 (&rvalue), - GNUNET_MY_query_param_uint64 (&rvalue), - GNUNET_MY_query_param_end - }; - - execute_select (plugin, - plugin->select_entry_by_hash, - proc, - proc_cls, - params_select); - } + { + struct GNUNET_MY_QueryParam params_select[] = { + GNUNET_MY_query_param_auto_from_type(key), + GNUNET_MY_query_param_uint64(&next_uid), + GNUNET_MY_query_param_uint64(&rvalue), + GNUNET_MY_query_param_uint64(&rvalue), + GNUNET_MY_query_param_end + }; + + execute_select(plugin, + plugin->select_entry_by_hash, + proc, + proc_cls, + params_select); + } } @@ -628,35 +626,33 @@ mysql_plugin_get_key (void *cls, * @param proc_cls closure for @a proc */ static void -mysql_plugin_get_zero_anonymity (void *cls, - uint64_t next_uid, - enum GNUNET_BLOCK_Type type, - PluginDatumProcessor proc, - void *proc_cls) +mysql_plugin_get_zero_anonymity(void *cls, + uint64_t next_uid, + enum GNUNET_BLOCK_Type type, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; - uint32_t typei = (uint32_t) type; + uint32_t typei = (uint32_t)type; struct GNUNET_MY_QueryParam params_zero_iter[] = { - GNUNET_MY_query_param_uint32 (&typei), - GNUNET_MY_query_param_uint64 (&next_uid), + GNUNET_MY_query_param_uint32(&typei), + GNUNET_MY_query_param_uint64(&next_uid), GNUNET_MY_query_param_end }; - execute_select (plugin, - plugin->zero_iter, - proc, - proc_cls, - params_zero_iter); + execute_select(plugin, + plugin->zero_iter, + proc, + proc_cls, + params_zero_iter); } /** * Context for #repl_proc() function. */ -struct ReplCtx -{ - +struct ReplCtx { /** * Plugin handle. */ @@ -695,49 +691,49 @@ struct ReplCtx * #GNUNET_NO to delete the item and continue (if supported) */ static int -repl_proc (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +repl_proc(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct ReplCtx *rc = cls; struct Plugin *plugin = rc->plugin; int ret; int iret; - ret = rc->proc (rc->proc_cls, - key, - size, - data, - type, - priority, - anonymity, - replication, - expiration, - uid); + ret = rc->proc(rc->proc_cls, + key, + size, + data, + type, + priority, + anonymity, + replication, + expiration, + uid); if (NULL != key) - { - struct GNUNET_MY_QueryParam params_proc[] = { - GNUNET_MY_query_param_uint64 (&uid), - GNUNET_MY_query_param_end - }; - - iret = GNUNET_MY_exec_prepared (plugin->mc, - plugin->dec_repl, - params_proc); - if (GNUNET_SYSERR == iret) { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Failed to reduce replication counter\n"); - return GNUNET_SYSERR; + struct GNUNET_MY_QueryParam params_proc[] = { + GNUNET_MY_query_param_uint64(&uid), + GNUNET_MY_query_param_end + }; + + iret = GNUNET_MY_exec_prepared(plugin->mc, + plugin->dec_repl, + params_proc); + if (GNUNET_SYSERR == iret) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Failed to reduce replication counter\n"); + return GNUNET_SYSERR; + } } - } return ret; } @@ -754,9 +750,9 @@ repl_proc (void *cls, * @param proc_cls closure for @a proc */ static void -mysql_plugin_get_replication (void *cls, - PluginDatumProcessor proc, - void *proc_cls) +mysql_plugin_get_replication(void *cls, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; uint64_t rvalue; @@ -766,14 +762,14 @@ mysql_plugin_get_replication (void *cls, GNUNET_MY_query_param_end }; struct GNUNET_MY_ResultSpec results_get[] = { - GNUNET_MY_result_spec_uint32 (&repl), + GNUNET_MY_result_spec_uint32(&repl), GNUNET_MY_result_spec_end }; struct GNUNET_MY_QueryParam params_select[] = { - GNUNET_MY_query_param_uint32 (&repl), - GNUNET_MY_query_param_uint64 (&rvalue), - GNUNET_MY_query_param_uint32 (&repl), - GNUNET_MY_query_param_uint64 (&rvalue), + GNUNET_MY_query_param_uint32(&repl), + GNUNET_MY_query_param_uint64(&rvalue), + GNUNET_MY_query_param_uint32(&repl), + GNUNET_MY_query_param_uint64(&rvalue), GNUNET_MY_query_param_end }; @@ -782,32 +778,32 @@ mysql_plugin_get_replication (void *cls, rc.proc_cls = proc_cls; if (1 != - GNUNET_MY_exec_prepared (plugin->mc, - plugin->max_repl, - params_get)) - { - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } + GNUNET_MY_exec_prepared(plugin->mc, + plugin->max_repl, + params_get)) + { + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } if (GNUNET_OK != - GNUNET_MY_extract_result (plugin->max_repl, - results_get)) - { - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } - GNUNET_break (GNUNET_NO == - GNUNET_MY_extract_result (plugin->max_repl, - NULL)); - rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT64_MAX); - - execute_select (plugin, - plugin->select_replication, - &repl_proc, - &rc, - params_select); + GNUNET_MY_extract_result(plugin->max_repl, + results_get)) + { + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } + GNUNET_break(GNUNET_NO == + GNUNET_MY_extract_result(plugin->max_repl, + NULL)); + rvalue = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, + UINT64_MAX); + + execute_select(plugin, + plugin->select_replication, + &repl_proc, + &rc, + params_select); } @@ -819,9 +815,9 @@ mysql_plugin_get_replication (void *cls, * @param proc_cls closure for @a proc */ static void -mysql_plugin_get_keys (void *cls, - PluginKeyProcessor proc, - void *proc_cls) +mysql_plugin_get_keys(void *cls, + PluginKeyProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; int ret; @@ -833,78 +829,76 @@ mysql_plugin_get_keys (void *cls, GNUNET_MY_query_param_end }; struct GNUNET_MY_ResultSpec results_select[] = { - GNUNET_MY_result_spec_auto_from_type (&key), + GNUNET_MY_result_spec_auto_from_type(&key), GNUNET_MY_result_spec_end }; - GNUNET_assert (NULL != proc); - statement = GNUNET_MYSQL_statement_get_stmt (plugin->get_all_keys); + GNUNET_assert(NULL != proc); + statement = GNUNET_MYSQL_statement_get_stmt(plugin->get_all_keys); if (GNUNET_OK != - GNUNET_MY_exec_prepared (plugin->mc, - plugin->get_all_keys, - params_select)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("`%s' for `%s' failed at %s:%d with error: %s\n"), - "mysql_stmt_execute", - GET_ALL_KEYS, - __FILE__, - __LINE__, - mysql_stmt_error (statement)); - GNUNET_MYSQL_statements_invalidate (plugin->mc); - proc (proc_cls, NULL, 0); - return; - } - memset (&last, 0, sizeof (last)); /* make static analysis happy */ + GNUNET_MY_exec_prepared(plugin->mc, + plugin->get_all_keys, + params_select)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("`%s' for `%s' failed at %s:%d with error: %s\n"), + "mysql_stmt_execute", + GET_ALL_KEYS, + __FILE__, + __LINE__, + mysql_stmt_error(statement)); + GNUNET_MYSQL_statements_invalidate(plugin->mc); + proc(proc_cls, NULL, 0); + return; + } + memset(&last, 0, sizeof(last)); /* make static analysis happy */ ret = GNUNET_YES; cnt = 0; while (ret == GNUNET_YES) - { - ret = GNUNET_MY_extract_result (plugin->get_all_keys, - results_select); - if (0 != GNUNET_memcmp (&last, - &key)) { - if (0 != cnt) - proc (proc_cls, - &last, - cnt); - cnt = 1; - last = key; + ret = GNUNET_MY_extract_result(plugin->get_all_keys, + results_select); + if (0 != GNUNET_memcmp(&last, + &key)) + { + if (0 != cnt) + proc(proc_cls, + &last, + cnt); + cnt = 1; + last = key; + } + else + { + cnt++; + } } - else - { - cnt++; - } - } if (0 != cnt) - proc (proc_cls, - &last, - cnt); + proc(proc_cls, + &last, + cnt); /* finally, let app know we are done */ - proc (proc_cls, - NULL, - 0); + proc(proc_cls, + NULL, + 0); if (GNUNET_SYSERR == ret) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("`%s' failed at %s:%d with error: %s\n"), - "mysql_stmt_fetch", - __FILE__, - __LINE__, - mysql_stmt_error (statement)); - GNUNET_MYSQL_statements_invalidate (plugin->mc); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("`%s' failed at %s:%d with error: %s\n"), + "mysql_stmt_fetch", + __FILE__, + __LINE__, + mysql_stmt_error(statement)); + GNUNET_MYSQL_statements_invalidate(plugin->mc); + return; + } } /** * Context for #expi_proc() function. */ -struct ExpiCtx -{ - +struct ExpiCtx { /** * Plugin handle. */ @@ -944,16 +938,16 @@ struct ExpiCtx * #GNUNET_NO to delete the item and continue (if supported) */ static int -expi_proc (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +expi_proc(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct ExpiCtx *rc = cls; struct Plugin *plugin = rc->plugin; @@ -962,24 +956,24 @@ expi_proc (void *cls, }; if (NULL == key) - { - execute_select (plugin, - plugin->select_priority, - rc->proc, - rc->proc_cls, - params_select); - return GNUNET_SYSERR; - } - return rc->proc (rc->proc_cls, - key, - size, - data, - type, - priority, - anonymity, - replication, - expiration, - uid); + { + execute_select(plugin, + plugin->select_priority, + rc->proc, + rc->proc_cls, + params_select); + return GNUNET_SYSERR; + } + return rc->proc(rc->proc_cls, + key, + size, + data, + type, + priority, + anonymity, + replication, + expiration, + uid); } @@ -992,14 +986,14 @@ expi_proc (void *cls, * @param proc_cls closure for @a proc */ static void -mysql_plugin_get_expiration (void *cls, - PluginDatumProcessor proc, - void *proc_cls) +mysql_plugin_get_expiration(void *cls, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; struct GNUNET_TIME_Absolute now; struct GNUNET_MY_QueryParam params_select[] = { - GNUNET_MY_query_param_absolute_time (&now), + GNUNET_MY_query_param_absolute_time(&now), GNUNET_MY_query_param_end }; struct ExpiCtx rc; @@ -1007,12 +1001,12 @@ mysql_plugin_get_expiration (void *cls, rc.plugin = plugin; rc.proc = proc; rc.proc_cls = proc_cls; - now = GNUNET_TIME_absolute_get (); - execute_select (plugin, - plugin->select_expiration, - expi_proc, - &rc, - params_select); + now = GNUNET_TIME_absolute_get(); + execute_select(plugin, + plugin->select_expiration, + expi_proc, + &rc, + params_select); } @@ -1022,15 +1016,15 @@ mysql_plugin_get_expiration (void *cls, * @param cls the `struct Plugin *` */ static void -mysql_plugin_drop (void *cls) +mysql_plugin_drop(void *cls) { struct Plugin *plugin = cls; if (GNUNET_OK != - GNUNET_MYSQL_statement_run (plugin->mc, - "DROP TABLE gn090")) + GNUNET_MYSQL_statement_run(plugin->mc, + "DROP TABLE gn090")) return; /* error */ - plugin->env->duc (plugin->env->cls, 0); + plugin->env->duc(plugin->env->cls, 0); } @@ -1045,55 +1039,55 @@ mysql_plugin_drop (void *cls) * @param cont_cls continuation closure for @a cont */ static void -mysql_plugin_remove_key (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - PluginRemoveCont cont, - void *cont_cls) +mysql_plugin_remove_key(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + PluginRemoveCont cont, + void *cont_cls) { struct Plugin *plugin = cls; struct GNUNET_MY_QueryParam params_delete[] = { - GNUNET_MY_query_param_auto_from_type (key), - GNUNET_MY_query_param_fixed_size (data, size), + GNUNET_MY_query_param_auto_from_type(key), + GNUNET_MY_query_param_fixed_size(data, size), GNUNET_MY_query_param_end }; if (GNUNET_OK != - GNUNET_MY_exec_prepared (plugin->mc, - plugin->delete_entry_by_hash_value, - params_delete)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Removing key `%s' from gn090 table failed\n", - GNUNET_h2s (key)); - cont (cont_cls, - key, - size, - GNUNET_SYSERR, - _("MySQL statement run failure")); - return; - } - - MYSQL_STMT *stmt = GNUNET_MYSQL_statement_get_stmt (plugin->delete_entry_by_hash_value); - my_ulonglong rows = mysql_stmt_affected_rows (stmt); + GNUNET_MY_exec_prepared(plugin->mc, + plugin->delete_entry_by_hash_value, + params_delete)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Removing key `%s' from gn090 table failed\n", + GNUNET_h2s(key)); + cont(cont_cls, + key, + size, + GNUNET_SYSERR, + _("MySQL statement run failure")); + return; + } + + MYSQL_STMT *stmt = GNUNET_MYSQL_statement_get_stmt(plugin->delete_entry_by_hash_value); + my_ulonglong rows = mysql_stmt_affected_rows(stmt); if (0 == rows) - { - cont (cont_cls, - key, - size, - GNUNET_NO, - NULL); - return; - } - plugin->env->duc (plugin->env->cls, - -size); - cont (cont_cls, - key, - size, - GNUNET_OK, - NULL); + { + cont(cont_cls, + key, + size, + GNUNET_NO, + NULL); + return; + } + plugin->env->duc(plugin->env->cls, + -size); + cont(cont_cls, + key, + size, + GNUNET_OK, + NULL); } @@ -1104,67 +1098,67 @@ mysql_plugin_remove_key (void *cls, * @return our `struct Plugin *` */ void * -libgnunet_plugin_datastore_mysql_init (void *cls) +libgnunet_plugin_datastore_mysql_init(void *cls) { struct GNUNET_DATASTORE_PluginEnvironment *env = cls; struct GNUNET_DATASTORE_PluginFunctions *api; struct Plugin *plugin; - plugin = GNUNET_new (struct Plugin); + plugin = GNUNET_new(struct Plugin); plugin->env = env; - plugin->mc = GNUNET_MYSQL_context_create (env->cfg, - "datastore-mysql"); + plugin->mc = GNUNET_MYSQL_context_create(env->cfg, + "datastore-mysql"); if (NULL == plugin->mc) - { - GNUNET_free (plugin); - return NULL; - } -#define MRUNS(a) (GNUNET_OK != GNUNET_MYSQL_statement_run (plugin->mc, a) ) -#define PINIT(a,b) (NULL == (a = GNUNET_MYSQL_statement_prepare (plugin->mc, b))) + { + GNUNET_free(plugin); + return NULL; + } +#define MRUNS(a) (GNUNET_OK != GNUNET_MYSQL_statement_run(plugin->mc, a)) +#define PINIT(a, b) (NULL == (a = GNUNET_MYSQL_statement_prepare(plugin->mc, b))) if (MRUNS - ("CREATE TABLE IF NOT EXISTS gn090 (" - " repl INT(11) UNSIGNED NOT NULL DEFAULT 0," - " type INT(11) UNSIGNED NOT NULL DEFAULT 0," - " prio INT(11) UNSIGNED NOT NULL DEFAULT 0," - " anonLevel INT(11) UNSIGNED NOT NULL DEFAULT 0," - " expire BIGINT UNSIGNED NOT NULL DEFAULT 0," - " rvalue BIGINT UNSIGNED NOT NULL," - " hash BINARY(64) NOT NULL DEFAULT ''," - " vhash BINARY(64) NOT NULL DEFAULT ''," - " value BLOB NOT NULL DEFAULT ''," " uid BIGINT NOT NULL AUTO_INCREMENT," - " PRIMARY KEY (uid)," - " INDEX idx_hash_type_uid (hash(64),type,rvalue)," - " INDEX idx_prio (prio)," - " INDEX idx_repl_rvalue (repl,rvalue)," - " INDEX idx_expire (expire)," - " INDEX idx_anonLevel_type_rvalue (anonLevel,type,rvalue)" - ") ENGINE=InnoDB") || MRUNS ("SET AUTOCOMMIT = 1") || - PINIT (plugin->insert_entry, INSERT_ENTRY) || - PINIT (plugin->delete_entry_by_uid, DELETE_ENTRY_BY_UID) || - PINIT (plugin->delete_entry_by_hash_value, DELETE_ENTRY_BY_HASH_VALUE) || - PINIT (plugin->select_entry, SELECT_ENTRY) || - PINIT (plugin->select_entry_by_hash, SELECT_ENTRY_BY_HASH) || - PINIT (plugin->select_entry_by_hash_and_type, - SELECT_ENTRY_BY_HASH_AND_TYPE) || - PINIT (plugin->get_size, SELECT_SIZE) || - PINIT (plugin->update_entry, UPDATE_ENTRY) || - PINIT (plugin->dec_repl, DEC_REPL) || - PINIT (plugin->zero_iter, SELECT_IT_NON_ANONYMOUS) || - PINIT (plugin->select_expiration, SELECT_IT_EXPIRATION) || - PINIT (plugin->select_priority, SELECT_IT_PRIORITY) || - PINIT (plugin->max_repl, SELECT_MAX_REPL) || - PINIT (plugin->get_all_keys, GET_ALL_KEYS) || - PINIT (plugin->select_replication, SELECT_IT_REPLICATION) || + ("CREATE TABLE IF NOT EXISTS gn090 (" + " repl INT(11) UNSIGNED NOT NULL DEFAULT 0," + " type INT(11) UNSIGNED NOT NULL DEFAULT 0," + " prio INT(11) UNSIGNED NOT NULL DEFAULT 0," + " anonLevel INT(11) UNSIGNED NOT NULL DEFAULT 0," + " expire BIGINT UNSIGNED NOT NULL DEFAULT 0," + " rvalue BIGINT UNSIGNED NOT NULL," + " hash BINARY(64) NOT NULL DEFAULT ''," + " vhash BINARY(64) NOT NULL DEFAULT ''," + " value BLOB NOT NULL DEFAULT ''," " uid BIGINT NOT NULL AUTO_INCREMENT," + " PRIMARY KEY (uid)," + " INDEX idx_hash_type_uid (hash(64),type,rvalue)," + " INDEX idx_prio (prio)," + " INDEX idx_repl_rvalue (repl,rvalue)," + " INDEX idx_expire (expire)," + " INDEX idx_anonLevel_type_rvalue (anonLevel,type,rvalue)" + ") ENGINE=InnoDB") || MRUNS("SET AUTOCOMMIT = 1") || + PINIT(plugin->insert_entry, INSERT_ENTRY) || + PINIT(plugin->delete_entry_by_uid, DELETE_ENTRY_BY_UID) || + PINIT(plugin->delete_entry_by_hash_value, DELETE_ENTRY_BY_HASH_VALUE) || + PINIT(plugin->select_entry, SELECT_ENTRY) || + PINIT(plugin->select_entry_by_hash, SELECT_ENTRY_BY_HASH) || + PINIT(plugin->select_entry_by_hash_and_type, + SELECT_ENTRY_BY_HASH_AND_TYPE) || + PINIT(plugin->get_size, SELECT_SIZE) || + PINIT(plugin->update_entry, UPDATE_ENTRY) || + PINIT(plugin->dec_repl, DEC_REPL) || + PINIT(plugin->zero_iter, SELECT_IT_NON_ANONYMOUS) || + PINIT(plugin->select_expiration, SELECT_IT_EXPIRATION) || + PINIT(plugin->select_priority, SELECT_IT_PRIORITY) || + PINIT(plugin->max_repl, SELECT_MAX_REPL) || + PINIT(plugin->get_all_keys, GET_ALL_KEYS) || + PINIT(plugin->select_replication, SELECT_IT_REPLICATION) || false) - { - GNUNET_MYSQL_context_destroy (plugin->mc); - GNUNET_free (plugin); - return NULL; - } + { + GNUNET_MYSQL_context_destroy(plugin->mc); + GNUNET_free(plugin); + return NULL; + } #undef PINIT #undef MRUNS - api = GNUNET_new (struct GNUNET_DATASTORE_PluginFunctions); + api = GNUNET_new(struct GNUNET_DATASTORE_PluginFunctions); api->cls = plugin; api->estimate_size = &mysql_plugin_estimate_size; api->put = &mysql_plugin_put; @@ -1175,8 +1169,8 @@ libgnunet_plugin_datastore_mysql_init (void *cls) api->get_keys = &mysql_plugin_get_keys; api->drop = &mysql_plugin_drop; api->remove_key = &mysql_plugin_remove_key; - GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "mysql", - _("Mysql database running\n")); + GNUNET_log_from(GNUNET_ERROR_TYPE_INFO, "mysql", + _("Mysql database running\n")); return api; } @@ -1188,14 +1182,14 @@ libgnunet_plugin_datastore_mysql_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_datastore_mysql_done (void *cls) +libgnunet_plugin_datastore_mysql_done(void *cls) { struct GNUNET_DATASTORE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - GNUNET_MYSQL_context_destroy (plugin->mc); - GNUNET_free (plugin); - GNUNET_free (api); + GNUNET_MYSQL_context_destroy(plugin->mc); + GNUNET_free(plugin); + GNUNET_free(api); return NULL; } diff --git a/src/datastore/plugin_datastore_postgres.c b/src/datastore/plugin_datastore_postgres.c index 0a3018411..17b645585 100644 --- a/src/datastore/plugin_datastore_postgres.c +++ b/src/datastore/plugin_datastore_postgres.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datastore/plugin_datastore_postgres.c @@ -44,8 +44,7 @@ /** * Context for all functions in this plugin. */ -struct Plugin -{ +struct Plugin { /** * Our execution environment. */ @@ -55,7 +54,6 @@ struct Plugin * Native Postgres database handle. */ PGconn *dbh; - }; @@ -66,7 +64,7 @@ struct Plugin * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -init_connection (struct Plugin *plugin) +init_connection(struct Plugin *plugin) { struct GNUNET_PQ_ExecuteStatement es[] = { /* FIXME: PostgreSQL does not have unsigned integers! This is ok for the type column because @@ -75,110 +73,111 @@ init_connection (struct Plugin *plugin) * This will also cause problems for expiration times after 294247-01-10-04:00:54 UTC. * PostgreSQL also recommends against using WITH OIDS. */ - GNUNET_PQ_make_execute ("CREATE TABLE IF NOT EXISTS gn090 (" - " repl INTEGER NOT NULL DEFAULT 0," - " type INTEGER NOT NULL DEFAULT 0," - " prio INTEGER NOT NULL DEFAULT 0," - " anonLevel INTEGER NOT NULL DEFAULT 0," - " expire BIGINT NOT NULL DEFAULT 0," - " rvalue BIGINT NOT NULL DEFAULT 0," - " hash BYTEA NOT NULL DEFAULT ''," - " vhash BYTEA NOT NULL DEFAULT ''," - " value BYTEA NOT NULL DEFAULT '')" - "WITH OIDS"), - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS idx_hash ON gn090 (hash)"), - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS idx_prio ON gn090 (prio)"), - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS idx_expire ON gn090 (expire)"), - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS idx_prio_anon ON gn090 (prio,anonLevel)"), - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS idx_prio_hash_anon ON gn090 (prio,hash,anonLevel)"), - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS idx_repl_rvalue ON gn090 (repl,rvalue)"), - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS idx_expire_hash ON gn090 (expire,hash)"), - GNUNET_PQ_make_execute ("ALTER TABLE gn090 ALTER value SET STORAGE EXTERNAL"), - GNUNET_PQ_make_execute ("ALTER TABLE gn090 ALTER hash SET STORAGE PLAIN"), - GNUNET_PQ_make_execute ("ALTER TABLE gn090 ALTER vhash SET STORAGE PLAIN"), + GNUNET_PQ_make_execute("CREATE TABLE IF NOT EXISTS gn090 (" + " repl INTEGER NOT NULL DEFAULT 0," + " type INTEGER NOT NULL DEFAULT 0," + " prio INTEGER NOT NULL DEFAULT 0," + " anonLevel INTEGER NOT NULL DEFAULT 0," + " expire BIGINT NOT NULL DEFAULT 0," + " rvalue BIGINT NOT NULL DEFAULT 0," + " hash BYTEA NOT NULL DEFAULT ''," + " vhash BYTEA NOT NULL DEFAULT ''," + " value BYTEA NOT NULL DEFAULT '')" + "WITH OIDS"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS idx_hash ON gn090 (hash)"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS idx_prio ON gn090 (prio)"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS idx_expire ON gn090 (expire)"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS idx_prio_anon ON gn090 (prio,anonLevel)"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS idx_prio_hash_anon ON gn090 (prio,hash,anonLevel)"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS idx_repl_rvalue ON gn090 (repl,rvalue)"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS idx_expire_hash ON gn090 (expire,hash)"), + GNUNET_PQ_make_execute("ALTER TABLE gn090 ALTER value SET STORAGE EXTERNAL"), + GNUNET_PQ_make_execute("ALTER TABLE gn090 ALTER hash SET STORAGE PLAIN"), + GNUNET_PQ_make_execute("ALTER TABLE gn090 ALTER vhash SET STORAGE PLAIN"), GNUNET_PQ_EXECUTE_STATEMENT_END }; + #define RESULT_COLUMNS "repl, type, prio, anonLevel, expire, hash, value, oid" struct GNUNET_PQ_PreparedStatement ps[] = { - GNUNET_PQ_make_prepare ("get", - "SELECT " RESULT_COLUMNS " FROM gn090" - " WHERE oid >= $1::bigint AND" - " (rvalue >= $2 OR 0 = $3::smallint) AND" - " (hash = $4 OR 0 = $5::smallint) AND" - " (type = $6 OR 0 = $7::smallint)" - " ORDER BY oid ASC LIMIT 1", - 7), - GNUNET_PQ_make_prepare ("put", - "INSERT INTO gn090 (repl, type, prio, anonLevel, expire, rvalue, hash, vhash, value) " - "VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", - 9), - GNUNET_PQ_make_prepare ("update", - "UPDATE gn090" - " SET prio = prio + $1," - " repl = repl + $2," - " expire = GREATEST(expire, $3)" - " WHERE hash = $4 AND vhash = $5", - 5), - GNUNET_PQ_make_prepare ("decrepl", - "UPDATE gn090 SET repl = GREATEST (repl - 1, 0) " - "WHERE oid = $1", - 1), - GNUNET_PQ_make_prepare ("select_non_anonymous", - "SELECT " RESULT_COLUMNS " FROM gn090 " - "WHERE anonLevel = 0 AND type = $1 AND oid >= $2::bigint " - "ORDER BY oid ASC LIMIT 1", - 2), - GNUNET_PQ_make_prepare ("select_expiration_order", - "(SELECT " RESULT_COLUMNS " FROM gn090 " - "WHERE expire < $1 ORDER BY prio ASC LIMIT 1) " - "UNION " - "(SELECT " RESULT_COLUMNS " FROM gn090 " - "ORDER BY prio ASC LIMIT 1) " - "ORDER BY expire ASC LIMIT 1", - 1), - GNUNET_PQ_make_prepare ("select_replication_order", - "SELECT " RESULT_COLUMNS " FROM gn090 " - "ORDER BY repl DESC,RANDOM() LIMIT 1", - 0), - GNUNET_PQ_make_prepare ("delrow", - "DELETE FROM gn090 " - "WHERE oid=$1", - 1), - GNUNET_PQ_make_prepare ("remove", - "DELETE FROM gn090" - " WHERE hash = $1 AND" - " value = $2", - 2), - GNUNET_PQ_make_prepare ("get_keys", - "SELECT hash FROM gn090", - 0), - GNUNET_PQ_make_prepare ("estimate_size", - "SELECT CASE WHEN NOT EXISTS" - " (SELECT 1 FROM gn090)" - " THEN 0" - " ELSE (SELECT SUM(LENGTH(value))+256*COUNT(*) FROM gn090)" - "END AS total", - 0), + GNUNET_PQ_make_prepare("get", + "SELECT " RESULT_COLUMNS " FROM gn090" + " WHERE oid >= $1::bigint AND" + " (rvalue >= $2 OR 0 = $3::smallint) AND" + " (hash = $4 OR 0 = $5::smallint) AND" + " (type = $6 OR 0 = $7::smallint)" + " ORDER BY oid ASC LIMIT 1", + 7), + GNUNET_PQ_make_prepare("put", + "INSERT INTO gn090 (repl, type, prio, anonLevel, expire, rvalue, hash, vhash, value) " + "VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", + 9), + GNUNET_PQ_make_prepare("update", + "UPDATE gn090" + " SET prio = prio + $1," + " repl = repl + $2," + " expire = GREATEST(expire, $3)" + " WHERE hash = $4 AND vhash = $5", + 5), + GNUNET_PQ_make_prepare("decrepl", + "UPDATE gn090 SET repl = GREATEST (repl - 1, 0) " + "WHERE oid = $1", + 1), + GNUNET_PQ_make_prepare("select_non_anonymous", + "SELECT " RESULT_COLUMNS " FROM gn090 " + "WHERE anonLevel = 0 AND type = $1 AND oid >= $2::bigint " + "ORDER BY oid ASC LIMIT 1", + 2), + GNUNET_PQ_make_prepare("select_expiration_order", + "(SELECT " RESULT_COLUMNS " FROM gn090 " + "WHERE expire < $1 ORDER BY prio ASC LIMIT 1) " + "UNION " + "(SELECT " RESULT_COLUMNS " FROM gn090 " + "ORDER BY prio ASC LIMIT 1) " + "ORDER BY expire ASC LIMIT 1", + 1), + GNUNET_PQ_make_prepare("select_replication_order", + "SELECT " RESULT_COLUMNS " FROM gn090 " + "ORDER BY repl DESC,RANDOM() LIMIT 1", + 0), + GNUNET_PQ_make_prepare("delrow", + "DELETE FROM gn090 " + "WHERE oid=$1", + 1), + GNUNET_PQ_make_prepare("remove", + "DELETE FROM gn090" + " WHERE hash = $1 AND" + " value = $2", + 2), + GNUNET_PQ_make_prepare("get_keys", + "SELECT hash FROM gn090", + 0), + GNUNET_PQ_make_prepare("estimate_size", + "SELECT CASE WHEN NOT EXISTS" + " (SELECT 1 FROM gn090)" + " THEN 0" + " ELSE (SELECT SUM(LENGTH(value))+256*COUNT(*) FROM gn090)" + "END AS total", + 0), GNUNET_PQ_PREPARED_STATEMENT_END }; #undef RESULT_COLUMNS - plugin->dbh = GNUNET_PQ_connect_with_cfg (plugin->env->cfg, - "datastore-postgres"); + plugin->dbh = GNUNET_PQ_connect_with_cfg(plugin->env->cfg, + "datastore-postgres"); if (NULL == plugin->dbh) return GNUNET_SYSERR; - if ( (GNUNET_OK != - GNUNET_PQ_exec_statements (plugin->dbh, - es)) || - (GNUNET_OK != - GNUNET_PQ_prepare_statements (plugin->dbh, - ps)) ) - { - PQfinish (plugin->dbh); - plugin->dbh = NULL; - return GNUNET_SYSERR; - } + if ((GNUNET_OK != + GNUNET_PQ_exec_statements(plugin->dbh, + es)) || + (GNUNET_OK != + GNUNET_PQ_prepare_statements(plugin->dbh, + ps))) + { + PQfinish(plugin->dbh); + plugin->dbh = NULL; + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -191,8 +190,8 @@ init_connection (struct Plugin *plugin) * @return number of bytes used on disk */ static void -postgres_plugin_estimate_size (void *cls, - unsigned long long *estimate) +postgres_plugin_estimate_size(void *cls, + unsigned long long *estimate) { struct Plugin *plugin = cls; uint64_t total; @@ -200,23 +199,23 @@ postgres_plugin_estimate_size (void *cls, GNUNET_PQ_query_param_end }; struct GNUNET_PQ_ResultSpec rs[] = { - GNUNET_PQ_result_spec_uint64 ("total", - &total), + GNUNET_PQ_result_spec_uint64("total", + &total), GNUNET_PQ_result_spec_end }; enum GNUNET_DB_QueryStatus ret; if (NULL == estimate) return; - ret = GNUNET_PQ_eval_prepared_singleton_select (plugin->dbh, - "estimate_size", - params, - rs); + ret = GNUNET_PQ_eval_prepared_singleton_select(plugin->dbh, + "estimate_size", + params, + rs); if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != ret) - { - *estimate = 0LL; - return; - } + { + *estimate = 0LL; + return; + } *estimate = total; } @@ -238,110 +237,108 @@ postgres_plugin_estimate_size (void *cls, * @param cont_cls continuation closure */ static void -postgres_plugin_put (void *cls, - const struct GNUNET_HashCode *key, - bool absent, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - PluginPutCont cont, - void *cont_cls) +postgres_plugin_put(void *cls, + const struct GNUNET_HashCode *key, + bool absent, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + PluginPutCont cont, + void *cont_cls) { struct Plugin *plugin = cls; struct GNUNET_HashCode vhash; enum GNUNET_DB_QueryStatus ret; - GNUNET_CRYPTO_hash (data, - size, - &vhash); - if (! absent) - { - struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_uint32 (&priority), - GNUNET_PQ_query_param_uint32 (&replication), - GNUNET_PQ_query_param_absolute_time (&expiration), - GNUNET_PQ_query_param_auto_from_type (key), - GNUNET_PQ_query_param_auto_from_type (&vhash), - GNUNET_PQ_query_param_end - }; - ret = GNUNET_PQ_eval_prepared_non_select (plugin->dbh, - "update", - params); - if (0 > ret) - { - cont (cont_cls, - key, - size, - GNUNET_SYSERR, - _("Postgress exec failure")); - return; - } - bool affected = (0 != ret); - if (affected) + GNUNET_CRYPTO_hash(data, + size, + &vhash); + if (!absent) { - cont (cont_cls, - key, - size, - GNUNET_NO, - NULL); - return; + struct GNUNET_PQ_QueryParam params[] = { + GNUNET_PQ_query_param_uint32(&priority), + GNUNET_PQ_query_param_uint32(&replication), + GNUNET_PQ_query_param_absolute_time(&expiration), + GNUNET_PQ_query_param_auto_from_type(key), + GNUNET_PQ_query_param_auto_from_type(&vhash), + GNUNET_PQ_query_param_end + }; + ret = GNUNET_PQ_eval_prepared_non_select(plugin->dbh, + "update", + params); + if (0 > ret) + { + cont(cont_cls, + key, + size, + GNUNET_SYSERR, + _("Postgress exec failure")); + return; + } + bool affected = (0 != ret); + if (affected) + { + cont(cont_cls, + key, + size, + GNUNET_NO, + NULL); + return; + } } - } { - uint32_t utype = (uint32_t) type; - uint64_t rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT64_MAX); + uint32_t utype = (uint32_t)type; + uint64_t rvalue = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, + UINT64_MAX); struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_uint32 (&replication), - GNUNET_PQ_query_param_uint32 (&utype), - GNUNET_PQ_query_param_uint32 (&priority), - GNUNET_PQ_query_param_uint32 (&anonymity), - GNUNET_PQ_query_param_absolute_time (&expiration), - GNUNET_PQ_query_param_uint64 (&rvalue), - GNUNET_PQ_query_param_auto_from_type (key), - GNUNET_PQ_query_param_auto_from_type (&vhash), - GNUNET_PQ_query_param_fixed_size (data, size), + GNUNET_PQ_query_param_uint32(&replication), + GNUNET_PQ_query_param_uint32(&utype), + GNUNET_PQ_query_param_uint32(&priority), + GNUNET_PQ_query_param_uint32(&anonymity), + GNUNET_PQ_query_param_absolute_time(&expiration), + GNUNET_PQ_query_param_uint64(&rvalue), + GNUNET_PQ_query_param_auto_from_type(key), + GNUNET_PQ_query_param_auto_from_type(&vhash), + GNUNET_PQ_query_param_fixed_size(data, size), GNUNET_PQ_query_param_end }; - ret = GNUNET_PQ_eval_prepared_non_select (plugin->dbh, - "put", - params); + ret = GNUNET_PQ_eval_prepared_non_select(plugin->dbh, + "put", + params); if (0 > ret) - { - cont (cont_cls, - key, - size, - GNUNET_SYSERR, - "Postgress exec failure"); - return; - } + { + cont(cont_cls, + key, + size, + GNUNET_SYSERR, + "Postgress exec failure"); + return; + } } - plugin->env->duc (plugin->env->cls, - size + GNUNET_DATASTORE_ENTRY_OVERHEAD); - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "datastore-postgres", - "Stored %u bytes in database\n", - (unsigned int) size); - cont (cont_cls, - key, - size, - GNUNET_OK, - NULL); + plugin->env->duc(plugin->env->cls, + size + GNUNET_DATASTORE_ENTRY_OVERHEAD); + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "datastore-postgres", + "Stored %u bytes in database\n", + (unsigned int)size); + cont(cont_cls, + key, + size, + GNUNET_OK, + NULL); } /** * Closure for #process_result. */ -struct ProcessResultContext -{ - +struct ProcessResultContext { /** * The plugin handle. */ @@ -356,7 +353,6 @@ struct ProcessResultContext * Closure for @e proc. */ void *proc_cls; - }; @@ -369,111 +365,111 @@ struct ProcessResultContext * @param num_results number of results in @a res */ static void -process_result (void *cls, - PGresult *res, - unsigned int num_results) +process_result(void *cls, + PGresult *res, + unsigned int num_results) { struct ProcessResultContext *prc = cls; struct Plugin *plugin = prc->plugin; if (0 == num_results) - { - /* no result */ - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "datastore-postgres", - "Ending iteration (no more results)\n"); - prc->proc (prc->proc_cls, NULL, 0, NULL, 0, 0, 0, 0, - GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } + { + /* no result */ + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "datastore-postgres", + "Ending iteration (no more results)\n"); + prc->proc(prc->proc_cls, NULL, 0, NULL, 0, 0, 0, 0, + GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } if (1 != num_results) - { - GNUNET_break (0); - prc->proc (prc->proc_cls, NULL, 0, NULL, 0, 0, 0, 0, - GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } - /* Technically we don't need the loop here, but nicer in case - we ever relax the condition above. */ - for (unsigned int i=0;iproc (prc->proc_cls, NULL, 0, NULL, 0, 0, 0, 0, - GNUNET_TIME_UNIT_ZERO_ABS, 0); + GNUNET_break(0); + prc->proc(prc->proc_cls, NULL, 0, NULL, 0, 0, 0, 0, + GNUNET_TIME_UNIT_ZERO_ABS, 0); return; } - - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "datastore-postgres", - "Found result of size %u bytes and type %u in database\n", - (unsigned int) size, - (unsigned int) utype); - iret = prc->proc (prc->proc_cls, - &key, - size, - data, - (enum GNUNET_BLOCK_Type) utype, - priority, - anonymity, - replication, - expiration_time, - rowid); - if (iret == GNUNET_NO) + /* Technically we don't need the loop here, but nicer in case + we ever relax the condition above. */ + for (unsigned int i = 0; i < num_results; i++) { - struct GNUNET_PQ_QueryParam param[] = { - GNUNET_PQ_query_param_uint32 (&rowid), - GNUNET_PQ_query_param_end + int iret; + uint32_t rowid; + uint32_t utype; + uint32_t anonymity; + uint32_t replication; + uint32_t priority; + size_t size; + void *data; + struct GNUNET_TIME_Absolute expiration_time; + struct GNUNET_HashCode key; + struct GNUNET_PQ_ResultSpec rs[] = { + GNUNET_PQ_result_spec_uint32("repl", &replication), + GNUNET_PQ_result_spec_uint32("type", &utype), + GNUNET_PQ_result_spec_uint32("prio", &priority), + GNUNET_PQ_result_spec_uint32("anonLevel", &anonymity), + GNUNET_PQ_result_spec_absolute_time("expire", &expiration_time), + GNUNET_PQ_result_spec_auto_from_type("hash", &key), + GNUNET_PQ_result_spec_variable_size("value", &data, &size), + GNUNET_PQ_result_spec_uint32("oid", &rowid), + GNUNET_PQ_result_spec_end }; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Processor asked for item %u to be removed.\n", - (unsigned int) rowid); - if (0 < - GNUNET_PQ_eval_prepared_non_select (plugin->dbh, - "delrow", - param)) - { - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "datastore-postgres", - "Deleting %u bytes from database\n", - (unsigned int) size); - plugin->env->duc (plugin->env->cls, - - (size + GNUNET_DATASTORE_ENTRY_OVERHEAD)); - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "datastore-postgres", - "Deleted %u bytes from database\n", - (unsigned int) size); - } - } - GNUNET_PQ_cleanup_result (rs); - } /* for (i) */ + if (GNUNET_OK != + GNUNET_PQ_extract_result(res, + rs, + i)) + { + GNUNET_break(0); + prc->proc(prc->proc_cls, NULL, 0, NULL, 0, 0, 0, 0, + GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } + + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "datastore-postgres", + "Found result of size %u bytes and type %u in database\n", + (unsigned int)size, + (unsigned int)utype); + iret = prc->proc(prc->proc_cls, + &key, + size, + data, + (enum GNUNET_BLOCK_Type)utype, + priority, + anonymity, + replication, + expiration_time, + rowid); + if (iret == GNUNET_NO) + { + struct GNUNET_PQ_QueryParam param[] = { + GNUNET_PQ_query_param_uint32(&rowid), + GNUNET_PQ_query_param_end + }; + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Processor asked for item %u to be removed.\n", + (unsigned int)rowid); + if (0 < + GNUNET_PQ_eval_prepared_non_select(plugin->dbh, + "delrow", + param)) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "datastore-postgres", + "Deleting %u bytes from database\n", + (unsigned int)size); + plugin->env->duc(plugin->env->cls, + -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD)); + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "datastore-postgres", + "Deleted %u bytes from database\n", + (unsigned int)size); + } + } + GNUNET_PQ_cleanup_result(rs); + } /* for (i) */ } @@ -491,13 +487,13 @@ process_result (void *cls, * @param proc_cls closure for @a proc */ static void -postgres_plugin_get_key (void *cls, - uint64_t next_uid, - bool random, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - PluginDatumProcessor proc, - void *proc_cls) +postgres_plugin_get_key(void *cls, + uint64_t next_uid, + bool random, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; uint32_t utype = type; @@ -506,40 +502,40 @@ postgres_plugin_get_key (void *cls, uint16_t use_type = GNUNET_BLOCK_TYPE_ANY != type; uint64_t rvalue; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_uint64 (&next_uid), - GNUNET_PQ_query_param_uint64 (&rvalue), - GNUNET_PQ_query_param_uint16 (&use_rvalue), - GNUNET_PQ_query_param_auto_from_type (key), - GNUNET_PQ_query_param_uint16 (&use_key), - GNUNET_PQ_query_param_uint32 (&utype), - GNUNET_PQ_query_param_uint16 (&use_type), + GNUNET_PQ_query_param_uint64(&next_uid), + GNUNET_PQ_query_param_uint64(&rvalue), + GNUNET_PQ_query_param_uint16(&use_rvalue), + GNUNET_PQ_query_param_auto_from_type(key), + GNUNET_PQ_query_param_uint16(&use_key), + GNUNET_PQ_query_param_uint32(&utype), + GNUNET_PQ_query_param_uint16(&use_type), GNUNET_PQ_query_param_end }; struct ProcessResultContext prc; enum GNUNET_DB_QueryStatus res; if (random) - { - rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT64_MAX); - next_uid = 0; - } + { + rvalue = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, + UINT64_MAX); + next_uid = 0; + } else - { - rvalue = 0; - } + { + rvalue = 0; + } prc.plugin = plugin; prc.proc = proc; prc.proc_cls = proc_cls; - res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh, - "get", - params, - &process_result, - &prc); + res = GNUNET_PQ_eval_prepared_multi_select(plugin->dbh, + "get", + params, + &process_result, + &prc); if (0 > res) - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, - GNUNET_TIME_UNIT_ZERO_ABS, 0); + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, + GNUNET_TIME_UNIT_ZERO_ABS, 0); } @@ -556,17 +552,17 @@ postgres_plugin_get_key (void *cls, * @param proc_cls closure for @a proc */ static void -postgres_plugin_get_zero_anonymity (void *cls, - uint64_t next_uid, - enum GNUNET_BLOCK_Type type, - PluginDatumProcessor proc, - void *proc_cls) +postgres_plugin_get_zero_anonymity(void *cls, + uint64_t next_uid, + enum GNUNET_BLOCK_Type type, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; uint32_t utype = type; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_uint32 (&utype), - GNUNET_PQ_query_param_uint64 (&next_uid), + GNUNET_PQ_query_param_uint32(&utype), + GNUNET_PQ_query_param_uint64(&next_uid), GNUNET_PQ_query_param_end }; struct ProcessResultContext prc; @@ -575,23 +571,21 @@ postgres_plugin_get_zero_anonymity (void *cls, prc.plugin = plugin; prc.proc = proc; prc.proc_cls = proc_cls; - res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh, - "select_non_anonymous", - params, - &process_result, - &prc); + res = GNUNET_PQ_eval_prepared_multi_select(plugin->dbh, + "select_non_anonymous", + params, + &process_result, + &prc); if (0 > res) - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, - GNUNET_TIME_UNIT_ZERO_ABS, 0); + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, + GNUNET_TIME_UNIT_ZERO_ABS, 0); } /** * Context for #repl_iter() function. */ -struct ReplCtx -{ - +struct ReplCtx { /** * Plugin handle. */ @@ -631,42 +625,42 @@ struct ReplCtx * #GNUNET_NO to delete the item and continue (if supported) */ static int -repl_proc (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +repl_proc(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct ReplCtx *rc = cls; struct Plugin *plugin = rc->plugin; int ret; - uint32_t oid = (uint32_t) uid; + uint32_t oid = (uint32_t)uid; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_uint32 (&oid), + GNUNET_PQ_query_param_uint32(&oid), GNUNET_PQ_query_param_end }; enum GNUNET_DB_QueryStatus qret; - ret = rc->proc (rc->proc_cls, - key, - size, - data, - type, - priority, - anonymity, - replication, - expiration, - uid); + ret = rc->proc(rc->proc_cls, + key, + size, + data, + type, + priority, + anonymity, + replication, + expiration, + uid); if (NULL == key) return ret; - qret = GNUNET_PQ_eval_prepared_non_select (plugin->dbh, - "decrepl", - params); + qret = GNUNET_PQ_eval_prepared_non_select(plugin->dbh, + "decrepl", + params); if (0 > qret) return GNUNET_SYSERR; return ret; @@ -685,9 +679,9 @@ repl_proc (void *cls, * @param proc_cls closure for @a proc */ static void -postgres_plugin_get_replication (void *cls, - PluginDatumProcessor proc, - void *proc_cls) +postgres_plugin_get_replication(void *cls, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; struct GNUNET_PQ_QueryParam params[] = { @@ -703,14 +697,14 @@ postgres_plugin_get_replication (void *cls, prc.plugin = plugin; prc.proc = &repl_proc; prc.proc_cls = &rc; - res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh, - "select_replication_order", - params, - &process_result, - &prc); + res = GNUNET_PQ_eval_prepared_multi_select(plugin->dbh, + "select_replication_order", + params, + &process_result, + &prc); if (0 > res) - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, - GNUNET_TIME_UNIT_ZERO_ABS, 0); + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, + GNUNET_TIME_UNIT_ZERO_ABS, 0); } @@ -723,36 +717,34 @@ postgres_plugin_get_replication (void *cls, * @param proc_cls closure for @a proc */ static void -postgres_plugin_get_expiration (void *cls, - PluginDatumProcessor proc, - void *proc_cls) +postgres_plugin_get_expiration(void *cls, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; struct GNUNET_TIME_Absolute now; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_absolute_time (&now), + GNUNET_PQ_query_param_absolute_time(&now), GNUNET_PQ_query_param_end }; struct ProcessResultContext prc; - now = GNUNET_TIME_absolute_get (); + now = GNUNET_TIME_absolute_get(); prc.plugin = plugin; prc.proc = proc; prc.proc_cls = proc_cls; - (void) GNUNET_PQ_eval_prepared_multi_select (plugin->dbh, - "select_expiration_order", - params, - &process_result, - &prc); + (void)GNUNET_PQ_eval_prepared_multi_select(plugin->dbh, + "select_expiration_order", + params, + &process_result, + &prc); } /** * Closure for #process_keys. */ -struct ProcessKeysContext -{ - +struct ProcessKeysContext { /** * Function to call for each key. */ @@ -774,34 +766,34 @@ struct ProcessKeysContext * @param num_result the number of results in @a result */ static void -process_keys (void *cls, - PGresult *result, - unsigned int num_results) +process_keys(void *cls, + PGresult *result, + unsigned int num_results) { struct ProcessKeysContext *pkc = cls; - for (unsigned i=0;iproc(pkc->proc_cls, + &key, + 1); + GNUNET_PQ_cleanup_result(rs); } - pkc->proc (pkc->proc_cls, - &key, - 1); - GNUNET_PQ_cleanup_result (rs); - } } @@ -813,9 +805,9 @@ process_keys (void *cls, * @param proc_cls closure for @a proc */ static void -postgres_plugin_get_keys (void *cls, - PluginKeyProcessor proc, - void *proc_cls) +postgres_plugin_get_keys(void *cls, + PluginKeyProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; struct GNUNET_PQ_QueryParam params[] = { @@ -825,14 +817,14 @@ postgres_plugin_get_keys (void *cls, pkc.proc = proc; pkc.proc_cls = proc_cls; - (void) GNUNET_PQ_eval_prepared_multi_select (plugin->dbh, - "get_keys", - params, - &process_keys, - &pkc); - proc (proc_cls, - NULL, - 0); + (void)GNUNET_PQ_eval_prepared_multi_select(plugin->dbh, + "get_keys", + params, + &process_keys, + &pkc); + proc(proc_cls, + NULL, + 0); } @@ -842,20 +834,20 @@ postgres_plugin_get_keys (void *cls, * @param cls closure with the `struct Plugin *` */ static void -postgres_plugin_drop (void *cls) +postgres_plugin_drop(void *cls) { struct Plugin *plugin = cls; struct GNUNET_PQ_ExecuteStatement es[] = { - GNUNET_PQ_make_execute ("DROP TABLE gn090"), + GNUNET_PQ_make_execute("DROP TABLE gn090"), GNUNET_PQ_EXECUTE_STATEMENT_END }; if (GNUNET_OK != - GNUNET_PQ_exec_statements (plugin->dbh, - es)) - GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, - "postgres", - _("Failed to drop table from database.\n")); + GNUNET_PQ_exec_statements(plugin->dbh, + es)) + GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, + "postgres", + _("Failed to drop table from database.\n")); } @@ -870,53 +862,53 @@ postgres_plugin_drop (void *cls) * @param cont_cls continuation closure for @a cont */ static void -postgres_plugin_remove_key (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - PluginRemoveCont cont, - void *cont_cls) +postgres_plugin_remove_key(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + PluginRemoveCont cont, + void *cont_cls) { struct Plugin *plugin = cls; enum GNUNET_DB_QueryStatus ret; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_auto_from_type (key), - GNUNET_PQ_query_param_fixed_size (data, size), + GNUNET_PQ_query_param_auto_from_type(key), + GNUNET_PQ_query_param_fixed_size(data, size), GNUNET_PQ_query_param_end }; - ret = GNUNET_PQ_eval_prepared_non_select (plugin->dbh, - "remove", - params); + ret = GNUNET_PQ_eval_prepared_non_select(plugin->dbh, + "remove", + params); if (0 > ret) - { - cont (cont_cls, - key, - size, - GNUNET_SYSERR, - _("Postgress exec failure")); - return; - } + { + cont(cont_cls, + key, + size, + GNUNET_SYSERR, + _("Postgress exec failure")); + return; + } if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == ret) - { - cont (cont_cls, - key, - size, - GNUNET_NO, - NULL); - return; - } - plugin->env->duc (plugin->env->cls, - - (size + GNUNET_DATASTORE_ENTRY_OVERHEAD)); - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "datastore-postgres", - "Deleted %u bytes from database\n", - (unsigned int) size); - cont (cont_cls, - key, - size, - GNUNET_OK, - NULL); + { + cont(cont_cls, + key, + size, + GNUNET_NO, + NULL); + return; + } + plugin->env->duc(plugin->env->cls, + -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD)); + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "datastore-postgres", + "Deleted %u bytes from database\n", + (unsigned int)size); + cont(cont_cls, + key, + size, + GNUNET_OK, + NULL); } @@ -927,20 +919,20 @@ postgres_plugin_remove_key (void *cls, * @return our `struct Plugin *` */ void * -libgnunet_plugin_datastore_postgres_init (void *cls) +libgnunet_plugin_datastore_postgres_init(void *cls) { struct GNUNET_DATASTORE_PluginEnvironment *env = cls; struct GNUNET_DATASTORE_PluginFunctions *api; struct Plugin *plugin; - plugin = GNUNET_new (struct Plugin); + plugin = GNUNET_new(struct Plugin); plugin->env = env; - if (GNUNET_OK != init_connection (plugin)) - { - GNUNET_free (plugin); - return NULL; - } - api = GNUNET_new (struct GNUNET_DATASTORE_PluginFunctions); + if (GNUNET_OK != init_connection(plugin)) + { + GNUNET_free(plugin); + return NULL; + } + api = GNUNET_new(struct GNUNET_DATASTORE_PluginFunctions); api->cls = plugin; api->estimate_size = &postgres_plugin_estimate_size; api->put = &postgres_plugin_put; @@ -951,9 +943,9 @@ libgnunet_plugin_datastore_postgres_init (void *cls) api->get_keys = &postgres_plugin_get_keys; api->drop = &postgres_plugin_drop; api->remove_key = &postgres_plugin_remove_key; - GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, - "datastore-postgres", - _("Postgres database running\n")); + GNUNET_log_from(GNUNET_ERROR_TYPE_INFO, + "datastore-postgres", + _("Postgres database running\n")); return api; } @@ -965,14 +957,14 @@ libgnunet_plugin_datastore_postgres_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_datastore_postgres_done (void *cls) +libgnunet_plugin_datastore_postgres_done(void *cls) { struct GNUNET_DATASTORE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - PQfinish (plugin->dbh); - GNUNET_free (plugin); - GNUNET_free (api); + PQfinish(plugin->dbh); + GNUNET_free(plugin); + GNUNET_free(api); return NULL; } diff --git a/src/datastore/plugin_datastore_sqlite.c b/src/datastore/plugin_datastore_sqlite.c index 4bd2b39cb..7d8d06529 100644 --- a/src/datastore/plugin_datastore_sqlite.c +++ b/src/datastore/plugin_datastore_sqlite.c @@ -1,22 +1,22 @@ /* - * This file is part of GNUnet - * Copyright (C) 2009, 2011, 2017 GNUnet e.V. - * - * GNUnet is free software: you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * GNUnet is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . + * This file is part of GNUnet + * Copyright (C) 2009, 2011, 2017 GNUnet e.V. + * + * GNUnet is free software: you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * GNUnet is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @file datastore/plugin_datastore_sqlite.c @@ -57,15 +57,15 @@ */ #define LOG_SQLITE(db, level, cmd) \ do \ - { \ - GNUNET_log_from (level, \ - "sqlite", \ - _ ("`%s' failed at %s:%d with error: %s\n"), \ - cmd, \ - __FILE__, \ - __LINE__, \ - sqlite3_errmsg (db->dbh)); \ - } while (0) + { \ + GNUNET_log_from(level, \ + "sqlite", \ + _("`%s' failed at %s:%d with error: %s\n"), \ + cmd, \ + __FILE__, \ + __LINE__, \ + sqlite3_errmsg(db->dbh)); \ + } while (0) /** @@ -75,28 +75,27 @@ */ #define LOG_SQLITE_MSG(db, msg, level, cmd) \ do \ - { \ - GNUNET_log_from (level, \ - "sqlite", \ - _ ("`%s' failed at %s:%d with error: %s\n"), \ - cmd, \ - __FILE__, \ - __LINE__, \ - sqlite3_errmsg (db->dbh)); \ - GNUNET_asprintf (msg, \ - _ ("`%s' failed at %s:%u with error: %s"), \ - cmd, \ - __FILE__, \ - __LINE__, \ - sqlite3_errmsg (db->dbh)); \ - } while (0) + { \ + GNUNET_log_from(level, \ + "sqlite", \ + _("`%s' failed at %s:%d with error: %s\n"), \ + cmd, \ + __FILE__, \ + __LINE__, \ + sqlite3_errmsg(db->dbh)); \ + GNUNET_asprintf(msg, \ + _("`%s' failed at %s:%u with error: %s"), \ + cmd, \ + __FILE__, \ + __LINE__, \ + sqlite3_errmsg(db->dbh)); \ + } while (0) /** * Context for all functions in this plugin. */ -struct Plugin -{ +struct Plugin { /** * Our execution environment. */ @@ -178,22 +177,22 @@ struct Plugin * @return 0 on success */ static int -sq_prepare (sqlite3 *dbh, const char *zSql, sqlite3_stmt **ppStmt) +sq_prepare(sqlite3 *dbh, const char *zSql, sqlite3_stmt **ppStmt) { char *dummy; int result; - result = sqlite3_prepare_v2 (dbh, - zSql, - strlen (zSql), - ppStmt, - (const char **) &dummy); - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "sqlite", - "Prepared `%s' / %p: %d\n", - zSql, - *ppStmt, - result); + result = sqlite3_prepare_v2(dbh, + zSql, + strlen(zSql), + ppStmt, + (const char **)&dummy); + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "sqlite", + "Prepared `%s' / %p: %d\n", + zSql, + *ppStmt, + result); return result; } @@ -204,56 +203,56 @@ sq_prepare (sqlite3 *dbh, const char *zSql, sqlite3_stmt **ppStmt) * @param dbh handle to the database */ static void -create_indices (sqlite3 *dbh) +create_indices(sqlite3 *dbh) { /* create indices */ if ( 0 != (SQLITE_OK != - sqlite3_exec (dbh, - "CREATE INDEX IF NOT EXISTS idx_hash ON gn091 (hash)", - NULL, - NULL, - NULL)) + - (SQLITE_OK != - sqlite3_exec ( - dbh, - "CREATE INDEX IF NOT EXISTS idx_anon_type ON gn091 (anonLevel ASC,type)", - NULL, - NULL, - NULL)) + - (SQLITE_OK != - sqlite3_exec (dbh, - "CREATE INDEX IF NOT EXISTS idx_expire ON gn091 (expire ASC)", - NULL, - NULL, - NULL)) + - (SQLITE_OK != - sqlite3_exec ( - dbh, - "CREATE INDEX IF NOT EXISTS idx_repl_rvalue ON gn091 (repl,rvalue)", - NULL, - NULL, - NULL))) - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "sqlite", - "Failed to create indices: %s\n", - sqlite3_errmsg (dbh)); + sqlite3_exec(dbh, + "CREATE INDEX IF NOT EXISTS idx_hash ON gn091 (hash)", + NULL, + NULL, + NULL)) + + (SQLITE_OK != + sqlite3_exec( + dbh, + "CREATE INDEX IF NOT EXISTS idx_anon_type ON gn091 (anonLevel ASC,type)", + NULL, + NULL, + NULL)) + + (SQLITE_OK != + sqlite3_exec(dbh, + "CREATE INDEX IF NOT EXISTS idx_expire ON gn091 (expire ASC)", + NULL, + NULL, + NULL)) + + (SQLITE_OK != + sqlite3_exec( + dbh, + "CREATE INDEX IF NOT EXISTS idx_repl_rvalue ON gn091 (repl,rvalue)", + NULL, + NULL, + NULL))) + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "sqlite", + "Failed to create indices: %s\n", + sqlite3_errmsg(dbh)); } #if 0 -#define CHECK(a) GNUNET_break (a) +#define CHECK(a) GNUNET_break(a) #define ENULL NULL #else #define ENULL &e #define ENULL_DEFINED 1 #define CHECK(a) \ - if (! (a)) \ - { \ - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n", e); \ - sqlite3_free (e); \ - } + if (!(a)) \ + { \ + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", e); \ + sqlite3_free(e); \ + } #endif @@ -267,219 +266,220 @@ create_indices (sqlite3 *dbh) * @return #GNUNET_OK on success */ static int -database_setup (const struct GNUNET_CONFIGURATION_Handle *cfg, - struct Plugin *plugin) +database_setup(const struct GNUNET_CONFIGURATION_Handle *cfg, + struct Plugin *plugin) { sqlite3_stmt *stmt; char *afsdir; + #if ENULL_DEFINED char *e; #endif - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, - "datastore-sqlite", - "FILENAME", - &afsdir)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "datastore-sqlite", - "FILENAME"); - return GNUNET_SYSERR; - } - if (GNUNET_OK != GNUNET_DISK_file_test (afsdir)) - { - if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir)) + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(cfg, + "datastore-sqlite", + "FILENAME", + &afsdir)) { - GNUNET_break (0); - GNUNET_free (afsdir); + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "datastore-sqlite", + "FILENAME"); return GNUNET_SYSERR; } - /* database is new or got deleted, reset payload to zero! */ - if (NULL != plugin->env->duc) - plugin->env->duc (plugin->env->cls, 0); - } + if (GNUNET_OK != GNUNET_DISK_file_test(afsdir)) + { + if (GNUNET_OK != GNUNET_DISK_directory_create_for_file(afsdir)) + { + GNUNET_break(0); + GNUNET_free(afsdir); + return GNUNET_SYSERR; + } + /* database is new or got deleted, reset payload to zero! */ + if (NULL != plugin->env->duc) + plugin->env->duc(plugin->env->cls, 0); + } /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */ plugin->fn = afsdir; /* Open database and precompile statements */ - if (SQLITE_OK != sqlite3_open (plugin->fn, &plugin->dbh)) - { - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "sqlite", - _ ("Unable to initialize SQLite: %s.\n"), - sqlite3_errmsg (plugin->dbh)); - return GNUNET_SYSERR; - } - CHECK ( + if (SQLITE_OK != sqlite3_open(plugin->fn, &plugin->dbh)) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "sqlite", + _("Unable to initialize SQLite: %s.\n"), + sqlite3_errmsg(plugin->dbh)); + return GNUNET_SYSERR; + } + CHECK( SQLITE_OK == - sqlite3_exec (plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL, ENULL)); - CHECK ( + sqlite3_exec(plugin->dbh, "PRAGMA temp_store=MEMORY", NULL, NULL, ENULL)); + CHECK( SQLITE_OK == - sqlite3_exec (plugin->dbh, "PRAGMA synchronous=OFF", NULL, NULL, ENULL)); - CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, - "PRAGMA legacy_file_format=OFF", - NULL, - NULL, - ENULL)); - CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, - "PRAGMA auto_vacuum=INCREMENTAL", - NULL, - NULL, - ENULL)); - CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, - "PRAGMA locking_mode=EXCLUSIVE", - NULL, - NULL, - ENULL)); - CHECK ( + sqlite3_exec(plugin->dbh, "PRAGMA synchronous=OFF", NULL, NULL, ENULL)); + CHECK(SQLITE_OK == sqlite3_exec(plugin->dbh, + "PRAGMA legacy_file_format=OFF", + NULL, + NULL, + ENULL)); + CHECK(SQLITE_OK == sqlite3_exec(plugin->dbh, + "PRAGMA auto_vacuum=INCREMENTAL", + NULL, + NULL, + ENULL)); + CHECK(SQLITE_OK == sqlite3_exec(plugin->dbh, + "PRAGMA locking_mode=EXCLUSIVE", + NULL, + NULL, + ENULL)); + CHECK( SQLITE_OK == - sqlite3_exec (plugin->dbh, "PRAGMA page_size=4096", NULL, NULL, ENULL)); + sqlite3_exec(plugin->dbh, "PRAGMA page_size=4096", NULL, NULL, ENULL)); - CHECK (SQLITE_OK == sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS)); + CHECK(SQLITE_OK == sqlite3_busy_timeout(plugin->dbh, BUSY_TIMEOUT_MS)); /* We have to do it here, because otherwise precompiling SQL might fail */ - CHECK (SQLITE_OK == - sq_prepare (plugin->dbh, - "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn091'", - &stmt)); + CHECK(SQLITE_OK == + sq_prepare(plugin->dbh, + "SELECT 1 FROM sqlite_master WHERE tbl_name = 'gn091'", + &stmt)); /* FIXME: SQLite does not have unsigned integers! This is ok for the type column because * we only test equality on it and can cast it to/from uint32_t. For repl, prio, and anonLevel * we do math or inequality tests, so we can't handle the entire range of uint32_t. * This will also cause problems for expiration times after 294247-01-10-04:00:54 UTC. */ - if ((SQLITE_DONE == sqlite3_step (stmt)) && - (SQLITE_OK != sqlite3_exec (plugin->dbh, - "CREATE TABLE gn091 (" - " repl INT4 NOT NULL DEFAULT 0," - " type INT4 NOT NULL DEFAULT 0," - " prio INT4 NOT NULL DEFAULT 0," - " anonLevel INT4 NOT NULL DEFAULT 0," - " expire INT8 NOT NULL DEFAULT 0," - " rvalue INT8 NOT NULL," - " hash TEXT NOT NULL DEFAULT ''," - " vhash TEXT NOT NULL DEFAULT ''," - " value BLOB NOT NULL DEFAULT '')", - NULL, - NULL, - NULL))) - { - LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec"); - sqlite3_finalize (stmt); - return GNUNET_SYSERR; - } - sqlite3_finalize (stmt); - create_indices (plugin->dbh); + if ((SQLITE_DONE == sqlite3_step(stmt)) && + (SQLITE_OK != sqlite3_exec(plugin->dbh, + "CREATE TABLE gn091 (" + " repl INT4 NOT NULL DEFAULT 0," + " type INT4 NOT NULL DEFAULT 0," + " prio INT4 NOT NULL DEFAULT 0," + " anonLevel INT4 NOT NULL DEFAULT 0," + " expire INT8 NOT NULL DEFAULT 0," + " rvalue INT8 NOT NULL," + " hash TEXT NOT NULL DEFAULT ''," + " vhash TEXT NOT NULL DEFAULT ''," + " value BLOB NOT NULL DEFAULT '')", + NULL, + NULL, + NULL))) + { + LOG_SQLITE(plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_exec"); + sqlite3_finalize(stmt); + return GNUNET_SYSERR; + } + sqlite3_finalize(stmt); + create_indices(plugin->dbh); #define RESULT_COLUMNS \ "repl, type, prio, anonLevel, expire, hash, value, _ROWID_" if ( - (SQLITE_OK != sq_prepare (plugin->dbh, - "UPDATE gn091 " - "SET prio = prio + ?, " - "repl = repl + ?, " - "expire = MAX(expire, ?) " - "WHERE hash = ? AND vhash = ?", - &plugin->update)) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "UPDATE gn091 " - "SET repl = MAX (0, repl - 1) WHERE _ROWID_ = ?", - &plugin->updRepl)) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT " RESULT_COLUMNS " FROM gn091 " - "WHERE repl=?2 AND " - " (rvalue>=?1 OR " - " NOT EXISTS (SELECT 1 FROM gn091 " - "WHERE repl=?2 AND rvalue>=?1 LIMIT 1) ) " - "ORDER BY rvalue ASC LIMIT 1", - &plugin->selRepl)) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT MAX(repl) FROM gn091", - &plugin->maxRepl)) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "UPDATE gn091 " + "SET prio = prio + ?, " + "repl = repl + ?, " + "expire = MAX(expire, ?) " + "WHERE hash = ? AND vhash = ?", + &plugin->update)) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "UPDATE gn091 " + "SET repl = MAX (0, repl - 1) WHERE _ROWID_ = ?", + &plugin->updRepl)) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT " RESULT_COLUMNS " FROM gn091 " + "WHERE repl=?2 AND " + " (rvalue>=?1 OR " + " NOT EXISTS (SELECT 1 FROM gn091 " + "WHERE repl=?2 AND rvalue>=?1 LIMIT 1) ) " + "ORDER BY rvalue ASC LIMIT 1", + &plugin->selRepl)) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT MAX(repl) FROM gn091", + &plugin->maxRepl)) || (SQLITE_OK != - sq_prepare (plugin->dbh, - "SELECT " RESULT_COLUMNS " FROM gn091 " - "WHERE NOT EXISTS (SELECT 1 FROM gn091 WHERE expire < ?1 LIMIT 1) OR (expire < ?1) " - "ORDER BY expire ASC LIMIT 1", - &plugin->selExpi)) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT " RESULT_COLUMNS " FROM gn091 " - "WHERE _ROWID_ >= ? AND " - "anonLevel = 0 AND " - "type = ? " - "ORDER BY _ROWID_ ASC LIMIT 1", - &plugin->selZeroAnon)) || + sq_prepare(plugin->dbh, + "SELECT " RESULT_COLUMNS " FROM gn091 " + "WHERE NOT EXISTS (SELECT 1 FROM gn091 WHERE expire < ?1 LIMIT 1) OR (expire < ?1) " + "ORDER BY expire ASC LIMIT 1", + &plugin->selExpi)) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT " RESULT_COLUMNS " FROM gn091 " + "WHERE _ROWID_ >= ? AND " + "anonLevel = 0 AND " + "type = ? " + "ORDER BY _ROWID_ ASC LIMIT 1", + &plugin->selZeroAnon)) || (SQLITE_OK != - sq_prepare (plugin->dbh, - "INSERT INTO gn091 (repl, type, prio, anonLevel, expire, rvalue, hash, vhash, value) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", - &plugin->insertContent)) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT " RESULT_COLUMNS " FROM gn091 " - "WHERE _ROWID_ >= ?1 " - "ORDER BY _ROWID_ ASC LIMIT 1", - &plugin->get[0])) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT " RESULT_COLUMNS " FROM gn091 " - "WHERE _ROWID_ >= ?1 AND " - "type = ?4 " - "ORDER BY _ROWID_ ASC LIMIT 1", - &plugin->get[1])) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT " RESULT_COLUMNS " FROM gn091 " - "WHERE _ROWID_ >= ?1 AND " - "hash = ?3 " - "ORDER BY _ROWID_ ASC LIMIT 1", - &plugin->get[2])) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT " RESULT_COLUMNS " FROM gn091 " - "WHERE _ROWID_ >= ?1 AND " - "hash = ?3 AND " - "type = ?4 " - "ORDER BY _ROWID_ ASC LIMIT 1", - &plugin->get[3])) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT " RESULT_COLUMNS " FROM gn091 " - "WHERE _ROWID_ >= ?1 AND " - "rvalue >= ?2 " - "ORDER BY _ROWID_ ASC LIMIT 1", - &plugin->get[4])) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT " RESULT_COLUMNS " FROM gn091 " - "WHERE _ROWID_ >= ?1 AND " - "rvalue >= ?2 AND " - "type = ?4 " - "ORDER BY _ROWID_ ASC LIMIT 1", - &plugin->get[5])) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT " RESULT_COLUMNS " FROM gn091 " - "WHERE _ROWID_ >= ?1 AND " - "rvalue >= ?2 AND " - "hash = ?3 " - "ORDER BY _ROWID_ ASC LIMIT 1", - &plugin->get[6])) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "SELECT " RESULT_COLUMNS " FROM gn091 " - "WHERE _ROWID_ >= ?1 AND " - "rvalue >= ?2 AND " - "hash = ?3 AND " - "type = ?4 " - "ORDER BY _ROWID_ ASC LIMIT 1", - &plugin->get[7])) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "DELETE FROM gn091 WHERE _ROWID_ = ?", - &plugin->delRow)) || - (SQLITE_OK != sq_prepare (plugin->dbh, - "DELETE FROM gn091 " - "WHERE hash = ? AND " - "value = ? ", - &plugin->remove)) || + sq_prepare(plugin->dbh, + "INSERT INTO gn091 (repl, type, prio, anonLevel, expire, rvalue, hash, vhash, value) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + &plugin->insertContent)) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT " RESULT_COLUMNS " FROM gn091 " + "WHERE _ROWID_ >= ?1 " + "ORDER BY _ROWID_ ASC LIMIT 1", + &plugin->get[0])) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT " RESULT_COLUMNS " FROM gn091 " + "WHERE _ROWID_ >= ?1 AND " + "type = ?4 " + "ORDER BY _ROWID_ ASC LIMIT 1", + &plugin->get[1])) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT " RESULT_COLUMNS " FROM gn091 " + "WHERE _ROWID_ >= ?1 AND " + "hash = ?3 " + "ORDER BY _ROWID_ ASC LIMIT 1", + &plugin->get[2])) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT " RESULT_COLUMNS " FROM gn091 " + "WHERE _ROWID_ >= ?1 AND " + "hash = ?3 AND " + "type = ?4 " + "ORDER BY _ROWID_ ASC LIMIT 1", + &plugin->get[3])) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT " RESULT_COLUMNS " FROM gn091 " + "WHERE _ROWID_ >= ?1 AND " + "rvalue >= ?2 " + "ORDER BY _ROWID_ ASC LIMIT 1", + &plugin->get[4])) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT " RESULT_COLUMNS " FROM gn091 " + "WHERE _ROWID_ >= ?1 AND " + "rvalue >= ?2 AND " + "type = ?4 " + "ORDER BY _ROWID_ ASC LIMIT 1", + &plugin->get[5])) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT " RESULT_COLUMNS " FROM gn091 " + "WHERE _ROWID_ >= ?1 AND " + "rvalue >= ?2 AND " + "hash = ?3 " + "ORDER BY _ROWID_ ASC LIMIT 1", + &plugin->get[6])) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "SELECT " RESULT_COLUMNS " FROM gn091 " + "WHERE _ROWID_ >= ?1 AND " + "rvalue >= ?2 AND " + "hash = ?3 AND " + "type = ?4 " + "ORDER BY _ROWID_ ASC LIMIT 1", + &plugin->get[7])) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "DELETE FROM gn091 WHERE _ROWID_ = ?", + &plugin->delRow)) || + (SQLITE_OK != sq_prepare(plugin->dbh, + "DELETE FROM gn091 " + "WHERE hash = ? AND " + "value = ? ", + &plugin->remove)) || false) - { - LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "precompiling"); - return GNUNET_SYSERR; - } + { + LOG_SQLITE(plugin, GNUNET_ERROR_TYPE_ERROR, "precompiling"); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -491,65 +491,66 @@ database_setup (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param plugin the plugin context (state for this module) */ static void -database_shutdown (struct Plugin *plugin) +database_shutdown(struct Plugin *plugin) { int result; + #if SQLITE_VERSION_NUMBER >= 3007000 sqlite3_stmt *stmt; #endif if (NULL != plugin->remove) - sqlite3_finalize (plugin->remove); + sqlite3_finalize(plugin->remove); if (NULL != plugin->delRow) - sqlite3_finalize (plugin->delRow); + sqlite3_finalize(plugin->delRow); if (NULL != plugin->update) - sqlite3_finalize (plugin->update); + sqlite3_finalize(plugin->update); if (NULL != plugin->updRepl) - sqlite3_finalize (plugin->updRepl); + sqlite3_finalize(plugin->updRepl); if (NULL != plugin->selRepl) - sqlite3_finalize (plugin->selRepl); + sqlite3_finalize(plugin->selRepl); if (NULL != plugin->maxRepl) - sqlite3_finalize (plugin->maxRepl); + sqlite3_finalize(plugin->maxRepl); if (NULL != plugin->selExpi) - sqlite3_finalize (plugin->selExpi); + sqlite3_finalize(plugin->selExpi); if (NULL != plugin->selZeroAnon) - sqlite3_finalize (plugin->selZeroAnon); + sqlite3_finalize(plugin->selZeroAnon); if (NULL != plugin->insertContent) - sqlite3_finalize (plugin->insertContent); + sqlite3_finalize(plugin->insertContent); for (int i = 0; i < 8; ++i) if (NULL != plugin->get[i]) - sqlite3_finalize (plugin->get[i]); - result = sqlite3_close (plugin->dbh); + sqlite3_finalize(plugin->get[i]); + result = sqlite3_close(plugin->dbh); #if SQLITE_VERSION_NUMBER >= 3007000 if (result == SQLITE_BUSY) - { - GNUNET_log_from ( - GNUNET_ERROR_TYPE_WARNING, - "sqlite", - _ ( - "Tried to close sqlite without finalizing all prepared statements.\n")); - stmt = sqlite3_next_stmt (plugin->dbh, NULL); - while (NULL != stmt) { - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "sqlite", - "Closing statement %p\n", - stmt); - result = sqlite3_finalize (stmt); - if (result != SQLITE_OK) - GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, - "sqlite", - "Failed to close statement %p: %d\n", - stmt, - result); - stmt = sqlite3_next_stmt (plugin->dbh, NULL); + GNUNET_log_from( + GNUNET_ERROR_TYPE_WARNING, + "sqlite", + _( + "Tried to close sqlite without finalizing all prepared statements.\n")); + stmt = sqlite3_next_stmt(plugin->dbh, NULL); + while (NULL != stmt) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "sqlite", + "Closing statement %p\n", + stmt); + result = sqlite3_finalize(stmt); + if (result != SQLITE_OK) + GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, + "sqlite", + "Failed to close statement %p: %d\n", + stmt, + result); + stmt = sqlite3_next_stmt(plugin->dbh, NULL); + } + result = sqlite3_close(plugin->dbh); } - result = sqlite3_close (plugin->dbh); - } #endif if (SQLITE_OK != result) - LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close"); - GNUNET_free_non_null (plugin->fn); + LOG_SQLITE(plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close"); + GNUNET_free_non_null(plugin->fn); } @@ -561,22 +562,22 @@ database_shutdown (struct Plugin *plugin) * @param rid the ID of the row to delete */ static int -delete_by_rowid (struct Plugin *plugin, uint64_t rid) +delete_by_rowid(struct Plugin *plugin, uint64_t rid) { - struct GNUNET_SQ_QueryParam params[] = {GNUNET_SQ_query_param_uint64 (&rid), - GNUNET_SQ_query_param_end}; + struct GNUNET_SQ_QueryParam params[] = { GNUNET_SQ_query_param_uint64(&rid), + GNUNET_SQ_query_param_end }; - if (GNUNET_OK != GNUNET_SQ_bind (plugin->delRow, params)) - return GNUNET_SYSERR; - if (SQLITE_DONE != sqlite3_step (plugin->delRow)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - GNUNET_SQ_reset (plugin->dbh, plugin->delRow); + if (GNUNET_OK != GNUNET_SQ_bind(plugin->delRow, params)) return GNUNET_SYSERR; - } - GNUNET_SQ_reset (plugin->dbh, plugin->delRow); + if (SQLITE_DONE != sqlite3_step(plugin->delRow)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + GNUNET_SQ_reset(plugin->dbh, plugin->delRow); + return GNUNET_SYSERR; + } + GNUNET_SQ_reset(plugin->dbh, plugin->delRow); return GNUNET_OK; } @@ -598,135 +599,137 @@ delete_by_rowid (struct Plugin *plugin, uint64_t rid) * @param cont_cls continuation closure */ static void -sqlite_plugin_put (void *cls, - const struct GNUNET_HashCode *key, - bool absent, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - PluginPutCont cont, - void *cont_cls) +sqlite_plugin_put(void *cls, + const struct GNUNET_HashCode *key, + bool absent, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + PluginPutCont cont, + void *cont_cls) { struct Plugin *plugin = cls; struct GNUNET_HashCode vhash; char *msg = NULL; - GNUNET_CRYPTO_hash (data, size, &vhash); - - if (! absent) - { - struct GNUNET_SQ_QueryParam params[] = - {GNUNET_SQ_query_param_uint32 (&priority), - GNUNET_SQ_query_param_uint32 (&replication), - GNUNET_SQ_query_param_absolute_time (&expiration), - GNUNET_SQ_query_param_auto_from_type (key), - GNUNET_SQ_query_param_auto_from_type (&vhash), - GNUNET_SQ_query_param_end}; + GNUNET_CRYPTO_hash(data, size, &vhash); - if (GNUNET_OK != GNUNET_SQ_bind (plugin->update, params)) - { - cont (cont_cls, key, size, GNUNET_SYSERR, _ ("sqlite bind failure")); - return; - } - if (SQLITE_DONE != sqlite3_step (plugin->update)) - { - LOG_SQLITE_MSG (plugin, - &msg, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - cont (cont_cls, key, size, GNUNET_SYSERR, msg); - GNUNET_free_non_null (msg); - return; - } - int changes = sqlite3_changes (plugin->dbh); - GNUNET_SQ_reset (plugin->dbh, plugin->update); - if (0 != changes) + if (!absent) { - cont (cont_cls, key, size, GNUNET_NO, NULL); - return; + struct GNUNET_SQ_QueryParam params[] = + { GNUNET_SQ_query_param_uint32(&priority), + GNUNET_SQ_query_param_uint32(&replication), + GNUNET_SQ_query_param_absolute_time(&expiration), + GNUNET_SQ_query_param_auto_from_type(key), + GNUNET_SQ_query_param_auto_from_type(&vhash), + GNUNET_SQ_query_param_end }; + + if (GNUNET_OK != GNUNET_SQ_bind(plugin->update, params)) + { + cont(cont_cls, key, size, GNUNET_SYSERR, _("sqlite bind failure")); + return; + } + if (SQLITE_DONE != sqlite3_step(plugin->update)) + { + LOG_SQLITE_MSG(plugin, + &msg, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + cont(cont_cls, key, size, GNUNET_SYSERR, msg); + GNUNET_free_non_null(msg); + return; + } + int changes = sqlite3_changes(plugin->dbh); + GNUNET_SQ_reset(plugin->dbh, plugin->update); + if (0 != changes) + { + cont(cont_cls, key, size, GNUNET_NO, NULL); + return; + } } - } uint64_t rvalue; - uint32_t type32 = (uint32_t) type; + uint32_t type32 = (uint32_t)type; struct GNUNET_SQ_QueryParam params[] = - {GNUNET_SQ_query_param_uint32 (&replication), - GNUNET_SQ_query_param_uint32 (&type32), - GNUNET_SQ_query_param_uint32 (&priority), - GNUNET_SQ_query_param_uint32 (&anonymity), - GNUNET_SQ_query_param_absolute_time (&expiration), - GNUNET_SQ_query_param_uint64 (&rvalue), - GNUNET_SQ_query_param_auto_from_type (key), - GNUNET_SQ_query_param_auto_from_type (&vhash), - GNUNET_SQ_query_param_fixed_size (data, size), - GNUNET_SQ_query_param_end}; + { GNUNET_SQ_query_param_uint32(&replication), + GNUNET_SQ_query_param_uint32(&type32), + GNUNET_SQ_query_param_uint32(&priority), + GNUNET_SQ_query_param_uint32(&anonymity), + GNUNET_SQ_query_param_absolute_time(&expiration), + GNUNET_SQ_query_param_uint64(&rvalue), + GNUNET_SQ_query_param_auto_from_type(key), + GNUNET_SQ_query_param_auto_from_type(&vhash), + GNUNET_SQ_query_param_fixed_size(data, size), + GNUNET_SQ_query_param_end }; int n; int ret; sqlite3_stmt *stmt; if (size > MAX_ITEM_SIZE) - { - cont (cont_cls, key, size, GNUNET_SYSERR, _ ("Data too large")); - return; - } - GNUNET_log_from ( + { + cont(cont_cls, key, size, GNUNET_SYSERR, _("Data too large")); + return; + } + GNUNET_log_from( GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Storing in database block with type %u/key `%s'/priority %u/expiration in %s (%s).\n", type, - GNUNET_h2s (key), + GNUNET_h2s(key), priority, - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining ( - expiration), - GNUNET_YES), - GNUNET_STRINGS_absolute_time_to_string (expiration)); + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_remaining( + expiration), + GNUNET_YES), + GNUNET_STRINGS_absolute_time_to_string(expiration)); stmt = plugin->insertContent; - rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX); - if (GNUNET_OK != GNUNET_SQ_bind (stmt, params)) - { - cont (cont_cls, key, size, GNUNET_SYSERR, NULL); - return; - } - n = sqlite3_step (stmt); + rvalue = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX); + if (GNUNET_OK != GNUNET_SQ_bind(stmt, params)) + { + cont(cont_cls, key, size, GNUNET_SYSERR, NULL); + return; + } + n = sqlite3_step(stmt); switch (n) - { - case SQLITE_DONE: - if (NULL != plugin->env->duc) - plugin->env->duc (plugin->env->cls, - size + GNUNET_DATASTORE_ENTRY_OVERHEAD); - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "sqlite", - "Stored new entry (%u bytes)\n", - size + GNUNET_DATASTORE_ENTRY_OVERHEAD); - ret = GNUNET_OK; - break; - case SQLITE_BUSY: - GNUNET_break (0); - LOG_SQLITE_MSG (plugin, - &msg, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - ret = GNUNET_SYSERR; - break; - default: - LOG_SQLITE_MSG (plugin, - &msg, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - GNUNET_SQ_reset (plugin->dbh, stmt); - database_shutdown (plugin); - database_setup (plugin->env->cfg, plugin); - cont (cont_cls, key, size, GNUNET_SYSERR, msg); - GNUNET_free_non_null (msg); - return; - } - GNUNET_SQ_reset (plugin->dbh, stmt); - cont (cont_cls, key, size, ret, msg); - GNUNET_free_non_null (msg); + { + case SQLITE_DONE: + if (NULL != plugin->env->duc) + plugin->env->duc(plugin->env->cls, + size + GNUNET_DATASTORE_ENTRY_OVERHEAD); + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "sqlite", + "Stored new entry (%u bytes)\n", + size + GNUNET_DATASTORE_ENTRY_OVERHEAD); + ret = GNUNET_OK; + break; + + case SQLITE_BUSY: + GNUNET_break(0); + LOG_SQLITE_MSG(plugin, + &msg, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + ret = GNUNET_SYSERR; + break; + + default: + LOG_SQLITE_MSG(plugin, + &msg, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + GNUNET_SQ_reset(plugin->dbh, stmt); + database_shutdown(plugin); + database_setup(plugin->env->cfg, plugin); + cont(cont_cls, key, size, GNUNET_SYSERR, msg); + GNUNET_free_non_null(msg); + return; + } + GNUNET_SQ_reset(plugin->dbh, stmt); + cont(cont_cls, key, size, ret, msg); + GNUNET_free_non_null(msg); } @@ -740,10 +743,10 @@ sqlite_plugin_put (void *cls, * @param proc_cls closure for @a proc */ static void -execute_get (struct Plugin *plugin, - sqlite3_stmt *stmt, - PluginDatumProcessor proc, - void *proc_cls) +execute_get(struct Plugin *plugin, + sqlite3_stmt *stmt, + PluginDatumProcessor proc, + void *proc_cls) { int n; struct GNUNET_TIME_Absolute expiration; @@ -757,68 +760,70 @@ execute_get (struct Plugin *plugin, struct GNUNET_HashCode key; int ret; struct GNUNET_SQ_ResultSpec rs[] = - {GNUNET_SQ_result_spec_uint32 (&replication), - GNUNET_SQ_result_spec_uint32 (&type), - GNUNET_SQ_result_spec_uint32 (&priority), - GNUNET_SQ_result_spec_uint32 (&anonymity), - GNUNET_SQ_result_spec_absolute_time (&expiration), - GNUNET_SQ_result_spec_auto_from_type (&key), - GNUNET_SQ_result_spec_variable_size (&value, &value_size), - GNUNET_SQ_result_spec_uint64 (&rowid), - GNUNET_SQ_result_spec_end}; - - n = sqlite3_step (stmt); + { GNUNET_SQ_result_spec_uint32(&replication), + GNUNET_SQ_result_spec_uint32(&type), + GNUNET_SQ_result_spec_uint32(&priority), + GNUNET_SQ_result_spec_uint32(&anonymity), + GNUNET_SQ_result_spec_absolute_time(&expiration), + GNUNET_SQ_result_spec_auto_from_type(&key), + GNUNET_SQ_result_spec_variable_size(&value, &value_size), + GNUNET_SQ_result_spec_uint64(&rowid), + GNUNET_SQ_result_spec_end }; + + n = sqlite3_step(stmt); switch (n) - { - case SQLITE_ROW: - if (GNUNET_OK != GNUNET_SQ_extract_result (stmt, rs)) { - GNUNET_break (0); + case SQLITE_ROW: + if (GNUNET_OK != GNUNET_SQ_extract_result(stmt, rs)) + { + GNUNET_break(0); + break; + } + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "sqlite", + "Found reply in database with expiration %s\n", + GNUNET_STRINGS_absolute_time_to_string(expiration)); + ret = proc(proc_cls, + &key, + value_size, + value, + type, + priority, + anonymity, + replication, + expiration, + rowid); + GNUNET_SQ_cleanup_result(rs); + GNUNET_SQ_reset(plugin->dbh, stmt); + if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid(plugin, rowid)) && + (NULL != plugin->env->duc)) + plugin->env->duc(plugin->env->cls, + -(value_size + GNUNET_DATASTORE_ENTRY_OVERHEAD)); + return; + + case SQLITE_DONE: + /* database must be empty */ break; + + case SQLITE_BUSY: + case SQLITE_ERROR: + case SQLITE_MISUSE: + default: + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + if (SQLITE_OK != sqlite3_reset(stmt)) + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_reset"); + GNUNET_break(0); + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + database_shutdown(plugin); + database_setup(plugin->env->cfg, plugin); + return; } - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "sqlite", - "Found reply in database with expiration %s\n", - GNUNET_STRINGS_absolute_time_to_string (expiration)); - ret = proc (proc_cls, - &key, - value_size, - value, - type, - priority, - anonymity, - replication, - expiration, - rowid); - GNUNET_SQ_cleanup_result (rs); - GNUNET_SQ_reset (plugin->dbh, stmt); - if ((GNUNET_NO == ret) && (GNUNET_OK == delete_by_rowid (plugin, rowid)) && - (NULL != plugin->env->duc)) - plugin->env->duc (plugin->env->cls, - -(value_size + GNUNET_DATASTORE_ENTRY_OVERHEAD)); - return; - case SQLITE_DONE: - /* database must be empty */ - break; - case SQLITE_BUSY: - case SQLITE_ERROR: - case SQLITE_MISUSE: - default: - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - if (SQLITE_OK != sqlite3_reset (stmt)) - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_reset"); - GNUNET_break (0); - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - database_shutdown (plugin); - database_setup (plugin->env->cfg, plugin); - return; - } - GNUNET_SQ_reset (plugin->dbh, stmt); - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + GNUNET_SQ_reset(plugin->dbh, stmt); + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); } @@ -835,27 +840,27 @@ execute_get (struct Plugin *plugin, * @param proc_cls closure for @a proc */ static void -sqlite_plugin_get_zero_anonymity (void *cls, - uint64_t next_uid, - enum GNUNET_BLOCK_Type type, - PluginDatumProcessor proc, - void *proc_cls) +sqlite_plugin_get_zero_anonymity(void *cls, + uint64_t next_uid, + enum GNUNET_BLOCK_Type type, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; uint32_t type32 = type; - struct GNUNET_SQ_QueryParam params[] = {GNUNET_SQ_query_param_uint64 ( - &next_uid), - GNUNET_SQ_query_param_uint32 ( - &type32), - GNUNET_SQ_query_param_end}; - - GNUNET_assert (type != GNUNET_BLOCK_TYPE_ANY); - if (GNUNET_OK != GNUNET_SQ_bind (plugin->selZeroAnon, params)) - { - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } - execute_get (plugin, plugin->selZeroAnon, proc, proc_cls); + struct GNUNET_SQ_QueryParam params[] = { GNUNET_SQ_query_param_uint64( + &next_uid), + GNUNET_SQ_query_param_uint32( + &type32), + GNUNET_SQ_query_param_end }; + + GNUNET_assert(type != GNUNET_BLOCK_TYPE_ANY); + if (GNUNET_OK != GNUNET_SQ_bind(plugin->selZeroAnon, params)) + { + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } + execute_get(plugin, plugin->selZeroAnon, proc, proc_cls); } @@ -873,64 +878,62 @@ sqlite_plugin_get_zero_anonymity (void *cls, * @param proc_cls closure for @a proc */ static void -sqlite_plugin_get_key (void *cls, - uint64_t next_uid, - bool random, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - PluginDatumProcessor proc, - void *proc_cls) +sqlite_plugin_get_key(void *cls, + uint64_t next_uid, + bool random, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; uint64_t rvalue; int use_rvalue = random; - uint32_t type32 = (uint32_t) type; + uint32_t type32 = (uint32_t)type; int use_type = GNUNET_BLOCK_TYPE_ANY != type; int use_key = NULL != key; sqlite3_stmt *stmt = plugin->get[use_rvalue * 4 + use_key * 2 + use_type]; struct GNUNET_SQ_QueryParam params[] = - {GNUNET_SQ_query_param_uint64 (&next_uid), - GNUNET_SQ_query_param_uint64 (&rvalue), - GNUNET_SQ_query_param_auto_from_type (key), - GNUNET_SQ_query_param_uint32 (&type32), - GNUNET_SQ_query_param_end}; + { GNUNET_SQ_query_param_uint64(&next_uid), + GNUNET_SQ_query_param_uint64(&rvalue), + GNUNET_SQ_query_param_auto_from_type(key), + GNUNET_SQ_query_param_uint32(&type32), + GNUNET_SQ_query_param_end }; /* SQLite doesn't like it when you try to bind a parameter greater than the * last numbered parameter, but unused parameters in the middle are OK. */ - if (! use_type) - { - params[3] = (struct GNUNET_SQ_QueryParam) GNUNET_SQ_query_param_end; - if (! use_key) + if (!use_type) { - params[2] = (struct GNUNET_SQ_QueryParam) GNUNET_SQ_query_param_end; - if (! use_rvalue) - params[1] = (struct GNUNET_SQ_QueryParam) GNUNET_SQ_query_param_end; + params[3] = (struct GNUNET_SQ_QueryParam)GNUNET_SQ_query_param_end; + if (!use_key) + { + params[2] = (struct GNUNET_SQ_QueryParam)GNUNET_SQ_query_param_end; + if (!use_rvalue) + params[1] = (struct GNUNET_SQ_QueryParam)GNUNET_SQ_query_param_end; + } } - } if (random) - { - rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX); - next_uid = 0; - } + { + rvalue = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX); + next_uid = 0; + } else rvalue = 0; - if (GNUNET_OK != GNUNET_SQ_bind (stmt, params)) - { - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } - execute_get (plugin, stmt, proc, proc_cls); + if (GNUNET_OK != GNUNET_SQ_bind(stmt, params)) + { + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } + execute_get(plugin, stmt, proc, proc_cls); } /** * Context for #repl_proc() function. */ -struct ReplCtx -{ - +struct ReplCtx { /** * Function to call for the result (or the NULL). */ @@ -973,37 +976,37 @@ struct ReplCtx * #GNUNET_NO to delete the item */ static int -repl_proc (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +repl_proc(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct ReplCtx *rc = cls; int ret; if (GNUNET_SYSERR == rc->have_uid) rc->have_uid = GNUNET_NO; - ret = rc->proc (rc->proc_cls, - key, - size, - data, - type, - priority, - anonymity, - replication, - expiration, - uid); + ret = rc->proc(rc->proc_cls, + key, + size, + data, + type, + priority, + anonymity, + replication, + expiration, + uid); if (NULL != key) - { - rc->uid = uid; - rc->have_uid = GNUNET_YES; - } + { + rc->uid = uid; + rc->have_uid = GNUNET_YES; + } return ret; } @@ -1019,61 +1022,61 @@ repl_proc (void *cls, * @param proc_cls closure for @a proc */ static void -sqlite_plugin_get_replication (void *cls, - PluginDatumProcessor proc, - void *proc_cls) +sqlite_plugin_get_replication(void *cls, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; struct ReplCtx rc; uint64_t rvalue; uint32_t repl; struct GNUNET_SQ_QueryParam params_sel_repl[] = - {GNUNET_SQ_query_param_uint64 (&rvalue), - GNUNET_SQ_query_param_uint32 (&repl), - GNUNET_SQ_query_param_end}; + { GNUNET_SQ_query_param_uint64(&rvalue), + GNUNET_SQ_query_param_uint32(&repl), + GNUNET_SQ_query_param_end }; struct GNUNET_SQ_QueryParam params_upd_repl[] = - {GNUNET_SQ_query_param_uint64 (&rc.uid), GNUNET_SQ_query_param_end}; - - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "datastore-sqlite", - "Getting random block based on replication order.\n"); - if (SQLITE_ROW != sqlite3_step (plugin->maxRepl)) - { - GNUNET_SQ_reset (plugin->dbh, plugin->maxRepl); - /* DB empty */ - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } - repl = sqlite3_column_int (plugin->maxRepl, 0); - GNUNET_SQ_reset (plugin->dbh, plugin->maxRepl); - rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX); - if (GNUNET_OK != GNUNET_SQ_bind (plugin->selRepl, params_sel_repl)) - { - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } + { GNUNET_SQ_query_param_uint64(&rc.uid), GNUNET_SQ_query_param_end }; + + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "datastore-sqlite", + "Getting random block based on replication order.\n"); + if (SQLITE_ROW != sqlite3_step(plugin->maxRepl)) + { + GNUNET_SQ_reset(plugin->dbh, plugin->maxRepl); + /* DB empty */ + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } + repl = sqlite3_column_int(plugin->maxRepl, 0); + GNUNET_SQ_reset(plugin->dbh, plugin->maxRepl); + rvalue = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX); + if (GNUNET_OK != GNUNET_SQ_bind(plugin->selRepl, params_sel_repl)) + { + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } rc.have_uid = GNUNET_SYSERR; rc.proc = proc; rc.proc_cls = proc_cls; - execute_get (plugin, plugin->selRepl, &repl_proc, &rc); + execute_get(plugin, plugin->selRepl, &repl_proc, &rc); if (GNUNET_YES == rc.have_uid) - { - if (GNUNET_OK != GNUNET_SQ_bind (plugin->updRepl, params_upd_repl)) { - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; + if (GNUNET_OK != GNUNET_SQ_bind(plugin->updRepl, params_upd_repl)) + { + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } + if (SQLITE_DONE != sqlite3_step(plugin->updRepl)) + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + GNUNET_SQ_reset(plugin->dbh, plugin->updRepl); } - if (SQLITE_DONE != sqlite3_step (plugin->updRepl)) - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - GNUNET_SQ_reset (plugin->dbh, plugin->updRepl); - } if (GNUNET_SYSERR == rc.have_uid) - { - /* proc was not called at all so far, do it now. */ - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - } + { + /* proc was not called at all so far, do it now. */ + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + } } @@ -1086,29 +1089,29 @@ sqlite_plugin_get_replication (void *cls, * @param proc_cls closure for @a proc */ static void -sqlite_plugin_get_expiration (void *cls, - PluginDatumProcessor proc, - void *proc_cls) +sqlite_plugin_get_expiration(void *cls, + PluginDatumProcessor proc, + void *proc_cls) { struct Plugin *plugin = cls; sqlite3_stmt *stmt; struct GNUNET_TIME_Absolute now; - struct GNUNET_SQ_QueryParam params[] = {GNUNET_SQ_query_param_absolute_time ( - &now), - GNUNET_SQ_query_param_end}; + struct GNUNET_SQ_QueryParam params[] = { GNUNET_SQ_query_param_absolute_time( + &now), + GNUNET_SQ_query_param_end }; - GNUNET_log_from ( + GNUNET_log_from( GNUNET_ERROR_TYPE_DEBUG, "sqlite", "Getting random block based on expiration and priority order.\n"); - now = GNUNET_TIME_absolute_get (); + now = GNUNET_TIME_absolute_get(); stmt = plugin->selExpi; - if (GNUNET_OK != GNUNET_SQ_bind (stmt, params)) - { - proc (proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); - return; - } - execute_get (plugin, stmt, proc, proc_cls); + if (GNUNET_OK != GNUNET_SQ_bind(stmt, params)) + { + proc(proc_cls, NULL, 0, NULL, 0, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS, 0); + return; + } + execute_get(plugin, stmt, proc, proc_cls); } @@ -1120,35 +1123,35 @@ sqlite_plugin_get_expiration (void *cls, * @param proc_cls closure for @a proc */ static void -sqlite_plugin_get_keys (void *cls, PluginKeyProcessor proc, void *proc_cls) +sqlite_plugin_get_keys(void *cls, PluginKeyProcessor proc, void *proc_cls) { struct Plugin *plugin = cls; struct GNUNET_HashCode key; struct GNUNET_SQ_ResultSpec results[] = - {GNUNET_SQ_result_spec_auto_from_type (&key), GNUNET_SQ_result_spec_end}; + { GNUNET_SQ_result_spec_auto_from_type(&key), GNUNET_SQ_result_spec_end }; sqlite3_stmt *stmt; int ret; - GNUNET_assert (NULL != proc); - if (SQLITE_OK != sq_prepare (plugin->dbh, "SELECT hash FROM gn091", &stmt)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite_prepare"); - proc (proc_cls, NULL, 0); - return; - } - while (SQLITE_ROW == (ret = sqlite3_step (stmt))) - { - if (GNUNET_OK == GNUNET_SQ_extract_result (stmt, results)) - proc (proc_cls, &key, 1); - else - GNUNET_break (0); - } + GNUNET_assert(NULL != proc); + if (SQLITE_OK != sq_prepare(plugin->dbh, "SELECT hash FROM gn091", &stmt)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite_prepare"); + proc(proc_cls, NULL, 0); + return; + } + while (SQLITE_ROW == (ret = sqlite3_step(stmt))) + { + if (GNUNET_OK == GNUNET_SQ_extract_result(stmt, results)) + proc(proc_cls, &key, 1); + else + GNUNET_break(0); + } if (SQLITE_DONE != ret) - LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step"); - sqlite3_finalize (stmt); - proc (proc_cls, NULL, 0); + LOG_SQLITE(plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step"); + sqlite3_finalize(stmt); + proc(proc_cls, NULL, 0); } @@ -1158,7 +1161,7 @@ sqlite_plugin_get_keys (void *cls, PluginKeyProcessor proc, void *proc_cls) * @param cls our plugin context */ static void -sqlite_plugin_drop (void *cls) +sqlite_plugin_drop(void *cls) { struct Plugin *plugin = cls; @@ -1177,44 +1180,44 @@ sqlite_plugin_drop (void *cls) * @param cont_cls continuation closure for @a cont */ static void -sqlite_plugin_remove_key (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - PluginRemoveCont cont, - void *cont_cls) +sqlite_plugin_remove_key(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + PluginRemoveCont cont, + void *cont_cls) { struct Plugin *plugin = cls; struct GNUNET_SQ_QueryParam params[] = - {GNUNET_SQ_query_param_auto_from_type (key), - GNUNET_SQ_query_param_fixed_size (data, size), - GNUNET_SQ_query_param_end}; + { GNUNET_SQ_query_param_auto_from_type(key), + GNUNET_SQ_query_param_fixed_size(data, size), + GNUNET_SQ_query_param_end }; - if (GNUNET_OK != GNUNET_SQ_bind (plugin->remove, params)) - { - cont (cont_cls, key, size, GNUNET_SYSERR, "bind failed"); - return; - } - if (SQLITE_DONE != sqlite3_step (plugin->remove)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - GNUNET_SQ_reset (plugin->dbh, plugin->remove); - cont (cont_cls, key, size, GNUNET_SYSERR, "sqlite3_step failed"); - return; - } - int changes = sqlite3_changes (plugin->dbh); - GNUNET_SQ_reset (plugin->dbh, plugin->remove); + if (GNUNET_OK != GNUNET_SQ_bind(plugin->remove, params)) + { + cont(cont_cls, key, size, GNUNET_SYSERR, "bind failed"); + return; + } + if (SQLITE_DONE != sqlite3_step(plugin->remove)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + GNUNET_SQ_reset(plugin->dbh, plugin->remove); + cont(cont_cls, key, size, GNUNET_SYSERR, "sqlite3_step failed"); + return; + } + int changes = sqlite3_changes(plugin->dbh); + GNUNET_SQ_reset(plugin->dbh, plugin->remove); if (0 == changes) - { - cont (cont_cls, key, size, GNUNET_NO, NULL); - return; - } + { + cont(cont_cls, key, size, GNUNET_NO, NULL); + return; + } if (NULL != plugin->env->duc) - plugin->env->duc (plugin->env->cls, - -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD)); - cont (cont_cls, key, size, GNUNET_OK, NULL); + plugin->env->duc(plugin->env->cls, + -(size + GNUNET_DATASTORE_ENTRY_OVERHEAD)); + cont(cont_cls, key, size, GNUNET_OK, NULL); } @@ -1226,7 +1229,7 @@ sqlite_plugin_remove_key (void *cls, * @return the size of the database on disk (estimate) */ static void -sqlite_plugin_estimate_size (void *cls, unsigned long long *estimate) +sqlite_plugin_estimate_size(void *cls, unsigned long long *estimate) { struct Plugin *plugin = cls; sqlite3_stmt *stmt; @@ -1240,36 +1243,36 @@ sqlite_plugin_estimate_size (void *cls, unsigned long long *estimate) if (NULL == estimate) return; if (SQLITE_VERSION_NUMBER < 3006000) - { - GNUNET_log_from ( - GNUNET_ERROR_TYPE_WARNING, - "datastore-sqlite", - _ ("sqlite version to old to determine size, assuming zero\n")); - *estimate = 0; - return; - } - CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, "VACUUM", NULL, NULL, ENULL)); - CHECK (SQLITE_OK == sqlite3_exec (plugin->dbh, - "PRAGMA auto_vacuum=INCREMENTAL", - NULL, - NULL, - ENULL)); - CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_count", &stmt)); - if (SQLITE_ROW == sqlite3_step (stmt)) - pages = sqlite3_column_int64 (stmt, 0); + { + GNUNET_log_from( + GNUNET_ERROR_TYPE_WARNING, + "datastore-sqlite", + _("sqlite version to old to determine size, assuming zero\n")); + *estimate = 0; + return; + } + CHECK(SQLITE_OK == sqlite3_exec(plugin->dbh, "VACUUM", NULL, NULL, ENULL)); + CHECK(SQLITE_OK == sqlite3_exec(plugin->dbh, + "PRAGMA auto_vacuum=INCREMENTAL", + NULL, + NULL, + ENULL)); + CHECK(SQLITE_OK == sq_prepare(plugin->dbh, "PRAGMA page_count", &stmt)); + if (SQLITE_ROW == sqlite3_step(stmt)) + pages = sqlite3_column_int64(stmt, 0); else pages = 0; - sqlite3_finalize (stmt); - CHECK (SQLITE_OK == sq_prepare (plugin->dbh, "PRAGMA page_size", &stmt)); - CHECK (SQLITE_ROW == sqlite3_step (stmt)); - page_size = sqlite3_column_int64 (stmt, 0); - sqlite3_finalize (stmt); - GNUNET_log ( + sqlite3_finalize(stmt); + CHECK(SQLITE_OK == sq_prepare(plugin->dbh, "PRAGMA page_size", &stmt)); + CHECK(SQLITE_ROW == sqlite3_step(stmt)); + page_size = sqlite3_column_int64(stmt, 0); + sqlite3_finalize(stmt); + GNUNET_log( GNUNET_ERROR_TYPE_INFO, - _ ( + _( "Using sqlite page utilization to estimate payload (%llu pages of size %llu bytes)\n"), - (unsigned long long) pages, - (unsigned long long) page_size); + (unsigned long long)pages, + (unsigned long long)page_size); *estimate = pages * page_size; } @@ -1281,7 +1284,7 @@ sqlite_plugin_estimate_size (void *cls, unsigned long long *estimate) * @return NULL on error, othrewise the plugin context */ void * -libgnunet_plugin_datastore_sqlite_init (void *cls) +libgnunet_plugin_datastore_sqlite_init(void *cls) { static struct Plugin plugin; struct GNUNET_DATASTORE_PluginEnvironment *env = cls; @@ -1289,14 +1292,14 @@ libgnunet_plugin_datastore_sqlite_init (void *cls) if (NULL != plugin.env) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.env = env; - if (GNUNET_OK != database_setup (env->cfg, &plugin)) - { - database_shutdown (&plugin); - return NULL; - } - api = GNUNET_new (struct GNUNET_DATASTORE_PluginFunctions); + if (GNUNET_OK != database_setup(env->cfg, &plugin)) + { + database_shutdown(&plugin); + return NULL; + } + api = GNUNET_new(struct GNUNET_DATASTORE_PluginFunctions); api->cls = &plugin; api->estimate_size = &sqlite_plugin_estimate_size; api->put = &sqlite_plugin_put; @@ -1307,9 +1310,9 @@ libgnunet_plugin_datastore_sqlite_init (void *cls) api->get_keys = &sqlite_plugin_get_keys; api->drop = &sqlite_plugin_drop; api->remove_key = &sqlite_plugin_remove_key; - GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, - "sqlite", - _ ("Sqlite database running\n")); + GNUNET_log_from(GNUNET_ERROR_TYPE_INFO, + "sqlite", + _("Sqlite database running\n")); return api; } @@ -1321,27 +1324,27 @@ libgnunet_plugin_datastore_sqlite_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_datastore_sqlite_done (void *cls) +libgnunet_plugin_datastore_sqlite_done(void *cls) { char *fn; struct GNUNET_DATASTORE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "sqlite", - "sqlite plugin is done\n"); + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "sqlite", + "sqlite plugin is done\n"); fn = NULL; if (plugin->drop_on_shutdown) - fn = GNUNET_strdup (plugin->fn); - database_shutdown (plugin); + fn = GNUNET_strdup(plugin->fn); + database_shutdown(plugin); plugin->env = NULL; - GNUNET_free (api); + GNUNET_free(api); if (NULL != fn) - { - if (0 != unlink (fn)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn); - GNUNET_free (fn); - } + { + if (0 != unlink(fn)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", fn); + GNUNET_free(fn); + } return NULL; } diff --git a/src/datastore/plugin_datastore_template.c b/src/datastore/plugin_datastore_template.c index d2e42a170..dea6151ad 100644 --- a/src/datastore/plugin_datastore_template.c +++ b/src/datastore/plugin_datastore_template.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file datastore/plugin_datastore_template.c @@ -31,8 +31,7 @@ /** * Context for all functions in this plugin. */ -struct Plugin -{ +struct Plugin { /** * Our execution environment. */ @@ -48,11 +47,11 @@ struct Plugin * @return number of bytes used on disk */ static void -template_plugin_estimate_size (void *cls, unsigned long long *estimate) +template_plugin_estimate_size(void *cls, unsigned long long *estimate) { if (NULL == estimate) return; - GNUNET_break (0); + GNUNET_break(0); *estimate = 0; } @@ -74,21 +73,21 @@ template_plugin_estimate_size (void *cls, unsigned long long *estimate) * @param cont_cls continuation closure */ static void -template_plugin_put (void *cls, - const struct GNUNET_HashCode *key, - bool absent, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - PluginPutCont cont, - void *cont_cls) +template_plugin_put(void *cls, + const struct GNUNET_HashCode *key, + bool absent, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + PluginPutCont cont, + void *cont_cls) { - GNUNET_break (0); - cont (cont_cls, key, size, GNUNET_SYSERR, "not implemented"); + GNUNET_break(0); + cont(cont_cls, key, size, GNUNET_SYSERR, "not implemented"); } @@ -106,15 +105,15 @@ template_plugin_put (void *cls, * @param proc_cls closure for proc */ static void -template_plugin_get_key (void *cls, - uint64_t next_uid, - bool random, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - PluginDatumProcessor proc, - void *proc_cls) +template_plugin_get_key(void *cls, + uint64_t next_uid, + bool random, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + PluginDatumProcessor proc, + void *proc_cls) { - GNUNET_break (0); + GNUNET_break(0); } @@ -131,10 +130,10 @@ template_plugin_get_key (void *cls, * @param proc_cls closure for proc */ static void -template_plugin_get_replication (void *cls, PluginDatumProcessor proc, - void *proc_cls) +template_plugin_get_replication(void *cls, PluginDatumProcessor proc, + void *proc_cls) { - GNUNET_break (0); + GNUNET_break(0); } @@ -147,10 +146,10 @@ template_plugin_get_replication (void *cls, PluginDatumProcessor proc, * @param proc_cls closure for proc */ static void -template_plugin_get_expiration (void *cls, PluginDatumProcessor proc, - void *proc_cls) +template_plugin_get_expiration(void *cls, PluginDatumProcessor proc, + void *proc_cls) { - GNUNET_break (0); + GNUNET_break(0); } @@ -166,11 +165,11 @@ template_plugin_get_expiration (void *cls, PluginDatumProcessor proc, * @param proc_cls closure for proc */ static void -template_plugin_get_zero_anonymity (void *cls, uint64_t next_uid, - enum GNUNET_BLOCK_Type type, - PluginDatumProcessor proc, void *proc_cls) +template_plugin_get_zero_anonymity(void *cls, uint64_t next_uid, + enum GNUNET_BLOCK_Type type, + PluginDatumProcessor proc, void *proc_cls) { - GNUNET_break (0); + GNUNET_break(0); } @@ -178,9 +177,9 @@ template_plugin_get_zero_anonymity (void *cls, uint64_t next_uid, * Drop database. */ static void -template_plugin_drop (void *cls) +template_plugin_drop(void *cls) { - GNUNET_break (0); + GNUNET_break(0); } @@ -192,11 +191,11 @@ template_plugin_drop (void *cls) * @param proc_cls closure for proc */ static void -template_get_keys (void *cls, - PluginKeyProcessor proc, - void *proc_cls) +template_get_keys(void *cls, + PluginKeyProcessor proc, + void *proc_cls) { - proc (proc_cls, NULL, 0); + proc(proc_cls, NULL, 0); } @@ -211,15 +210,15 @@ template_get_keys (void *cls, * @param cont_cls continuation closure for @a cont */ static void -template_plugin_remove_key (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - PluginRemoveCont cont, - void *cont_cls) +template_plugin_remove_key(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + PluginRemoveCont cont, + void *cont_cls) { - GNUNET_break (0); - cont (cont_cls, key, size, GNUNET_SYSERR, "not implemented"); + GNUNET_break(0); + cont(cont_cls, key, size, GNUNET_SYSERR, "not implemented"); } @@ -230,15 +229,15 @@ template_plugin_remove_key (void *cls, * @return our "struct Plugin*" */ void * -libgnunet_plugin_datastore_template_init (void *cls) +libgnunet_plugin_datastore_template_init(void *cls) { struct GNUNET_DATASTORE_PluginEnvironment *env = cls; struct GNUNET_DATASTORE_PluginFunctions *api; struct Plugin *plugin; - plugin = GNUNET_new (struct Plugin); + plugin = GNUNET_new(struct Plugin); plugin->env = env; - api = GNUNET_new (struct GNUNET_DATASTORE_PluginFunctions); + api = GNUNET_new(struct GNUNET_DATASTORE_PluginFunctions); api->cls = plugin; api->estimate_size = &template_plugin_estimate_size; api->put = &template_plugin_put; @@ -249,8 +248,8 @@ libgnunet_plugin_datastore_template_init (void *cls) api->drop = &template_plugin_drop; api->get_keys = &template_get_keys; api->remove_key = &template_plugin_remove_key; - GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "template", - _("Template database running\n")); + GNUNET_log_from(GNUNET_ERROR_TYPE_INFO, "template", + _("Template database running\n")); return api; } @@ -261,13 +260,13 @@ libgnunet_plugin_datastore_template_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_datastore_template_done (void *cls) +libgnunet_plugin_datastore_template_done(void *cls) { struct GNUNET_DATASTORE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - GNUNET_free (plugin); - GNUNET_free (api); + GNUNET_free(plugin); + GNUNET_free(api); return NULL; } diff --git a/src/datastore/test_datastore_api.c b/src/datastore/test_datastore_api.c index ee78a8cfc..56a7cdd3b 100644 --- a/src/datastore/test_datastore_api.c +++ b/src/datastore/test_datastore_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /* * @file datastore/test_datastore_api.c * @brief Test for the basic datastore API. @@ -37,7 +37,7 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15) #define ITERATIONS 256 @@ -60,45 +60,45 @@ static const char *plugin_name; static size_t -get_size (int i) +get_size(int i) { return 8 * i; } static const void * -get_data (int i) +get_data(int i) { static char buf[60000]; - memset (buf, i, 8 * i); + memset(buf, i, 8 * i); return buf; } static int -get_type (int i) +get_type(int i) { return i + 1; } static int -get_priority (int i) +get_priority(int i) { return i + 1; } static int -get_anonymity (int i) +get_anonymity(int i) { return i; } static struct GNUNET_TIME_Absolute -get_expiration (int i) +get_expiration(int i) { struct GNUNET_TIME_Absolute av; @@ -110,8 +110,7 @@ get_expiration (int i) /** * Which phase of the process are we in? */ -enum RunPhase -{ +enum RunPhase { /** * We are done (shutting down normally). */ @@ -143,8 +142,7 @@ enum RunPhase * benchmark. Could right now be global, but this allows * us to theoretically run multiple clients "in parallel". */ -struct CpsRunContext -{ +struct CpsRunContext { /** * Execution phase we are in. */ @@ -167,7 +165,7 @@ struct CpsRunContext * @param cls the `struct CpsRunContext` */ static void -run_continuation (void *cls); +run_continuation(void *cls); /** @@ -182,49 +180,102 @@ run_continuation (void *cls); * @param msg NULL on success, otherwise an error message */ static void -check_success (void *cls, - int success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +check_success(void *cls, + int success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct CpsRunContext *crc = cls; if (GNUNET_OK != success) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Operation %d/%d not successful: `%s'\n", - crc->phase, - crc->i, - msg); - crc->phase = RP_ERROR; - } - GNUNET_free_non_null (crc->data); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Operation %d/%d not successful: `%s'\n", + crc->phase, + crc->i, + msg); + crc->phase = RP_ERROR; + } + GNUNET_free_non_null(crc->data); crc->data = NULL; - GNUNET_SCHEDULER_add_now (&run_continuation, crc); + GNUNET_SCHEDULER_add_now(&run_continuation, crc); } static void -get_reserved (void *cls, - int success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +get_reserved(void *cls, + int success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct CpsRunContext *crc = cls; if (0 >= success) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error obtaining reservation: `%s'\n", - msg); - GNUNET_assert (0 < success); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error obtaining reservation: `%s'\n", + msg); + GNUNET_assert(0 < success); crc->rid = success; - GNUNET_SCHEDULER_add_now (&run_continuation, - crc); + GNUNET_SCHEDULER_add_now(&run_continuation, + crc); } static void -check_value (void *cls, +check_value(void *cls, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) +{ + struct CpsRunContext *crc = cls; + int i; + + i = crc->i; + if (NULL == key) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Value check failed (got NULL key) in %d/%d\n", + crc->phase, + crc->i); + crc->phase = RP_ERROR; + GNUNET_SCHEDULER_add_now(&run_continuation, + crc); + return; + } +#if 0 + fprintf(stderr, + "Check value got `%s' of size %u, type %d, expire %s\n", + GNUNET_h2s(key), (unsigned int)size, type, + GNUNET_STRINGS_absolute_time_to_string(expiration)); + fprintf(stderr, + "Check value iteration %d wants size %u, type %d, expire %s\n", i, + (unsigned int)get_size(i), get_type(i), + GNUNET_STRINGS_absolute_time_to_string(get_expiration(i))); +#endif + GNUNET_assert(size == get_size(i)); + GNUNET_assert(0 == memcmp(data, get_data(i), size)); + GNUNET_assert(type == get_type(i)); + GNUNET_assert(priority == get_priority(i)); + GNUNET_assert(anonymity == get_anonymity(i)); + GNUNET_assert(expiration.abs_value_us == get_expiration(i).abs_value_us); + if (crc->i == 0) + { + crc->phase = RP_DEL; + crc->i = ITERATIONS; + } + GNUNET_SCHEDULER_add_now(&run_continuation, + crc); +} + + +static void +delete_value(void *cls, const struct GNUNET_HashCode *key, size_t size, const void *data, @@ -236,48 +287,21 @@ check_value (void *cls, uint64_t uid) { struct CpsRunContext *crc = cls; - int i; - i = crc->i; - if (NULL == key) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Value check failed (got NULL key) in %d/%d\n", - crc->phase, - crc->i); - crc->phase = RP_ERROR; - GNUNET_SCHEDULER_add_now (&run_continuation, - crc); - return; - } -#if 0 - fprintf (stderr, - "Check value got `%s' of size %u, type %d, expire %s\n", - GNUNET_h2s (key), (unsigned int) size, type, - GNUNET_STRINGS_absolute_time_to_string (expiration)); - fprintf (stderr, - "Check value iteration %d wants size %u, type %d, expire %s\n", i, - (unsigned int) get_size (i), get_type (i), - GNUNET_STRINGS_absolute_time_to_string (get_expiration(i))); -#endif - GNUNET_assert (size == get_size (i)); - GNUNET_assert (0 == memcmp (data, get_data (i), size)); - GNUNET_assert (type == get_type (i)); - GNUNET_assert (priority == get_priority (i)); - GNUNET_assert (anonymity == get_anonymity (i)); - GNUNET_assert (expiration.abs_value_us == get_expiration (i).abs_value_us); - if (crc->i == 0) - { - crc->phase = RP_DEL; - crc->i = ITERATIONS; - } - GNUNET_SCHEDULER_add_now (&run_continuation, - crc); + GNUNET_assert(NULL == crc->data); + GNUNET_assert(NULL != key); + crc->size = size; + crc->key = *key; + crc->data = GNUNET_malloc(size); + GNUNET_memcpy(crc->data, data, size); + crc->phase = RP_DO_DEL; + GNUNET_SCHEDULER_add_now(&run_continuation, + crc); } static void -delete_value (void *cls, +check_nothing(void *cls, const struct GNUNET_HashCode *key, size_t size, const void *data, @@ -290,20 +314,16 @@ delete_value (void *cls, { struct CpsRunContext *crc = cls; - GNUNET_assert (NULL == crc->data); - GNUNET_assert (NULL != key); - crc->size = size; - crc->key = *key; - crc->data = GNUNET_malloc (size); - GNUNET_memcpy (crc->data, data, size); - crc->phase = RP_DO_DEL; - GNUNET_SCHEDULER_add_now (&run_continuation, - crc); + GNUNET_assert(key == NULL); + if (crc->i == 0) + crc->phase = RP_RESERVE; + GNUNET_SCHEDULER_add_now(&run_continuation, + crc); } static void -check_nothing (void *cls, +check_multiple(void *cls, const struct GNUNET_HashCode *key, size_t size, const void *data, @@ -316,45 +336,25 @@ check_nothing (void *cls, { struct CpsRunContext *crc = cls; - GNUNET_assert (key == NULL); - if (crc->i == 0) - crc->phase = RP_RESERVE; - GNUNET_SCHEDULER_add_now (&run_continuation, - crc); -} - - -static void -check_multiple (void *cls, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) -{ - struct CpsRunContext *crc = cls; - - GNUNET_assert (key != NULL); + GNUNET_assert(key != NULL); switch (crc->phase) - { - case RP_GET_MULTIPLE: - crc->phase = RP_GET_MULTIPLE_NEXT; - crc->first_uid = uid; - break; - case RP_GET_MULTIPLE_NEXT: - GNUNET_assert (uid != crc->first_uid); - crc->phase = RP_DONE; - break; - default: - GNUNET_break (0); - crc->phase = RP_ERROR; - break; - } - GNUNET_SCHEDULER_add_now (&run_continuation, crc); + { + case RP_GET_MULTIPLE: + crc->phase = RP_GET_MULTIPLE_NEXT; + crc->first_uid = uid; + break; + + case RP_GET_MULTIPLE_NEXT: + GNUNET_assert(uid != crc->first_uid); + crc->phase = RP_DONE; + break; + + default: + GNUNET_break(0); + crc->phase = RP_ERROR; + break; + } + GNUNET_SCHEDULER_add_now(&run_continuation, crc); } @@ -365,166 +365,177 @@ check_multiple (void *cls, * @param cls the `struct CpsRunContext` */ static void -run_continuation (void *cls) +run_continuation(void *cls) { struct CpsRunContext *crc = cls; - ok = (int) crc->phase; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Test in phase %u\n", - crc->phase); + ok = (int)crc->phase; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Test in phase %u\n", + crc->phase); switch (crc->phase) - { - case RP_PUT: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Executing PUT number %u\n", - crc->i); - GNUNET_CRYPTO_hash (&crc->i, sizeof (int), &crc->key); - GNUNET_DATASTORE_put (datastore, 0, &crc->key, get_size (crc->i), - get_data (crc->i), get_type (crc->i), - get_priority (crc->i), get_anonymity (crc->i), 0, - get_expiration (crc->i), 1, 1, - &check_success, crc); - crc->i++; - if (crc->i == ITERATIONS) - crc->phase = RP_GET; - break; - case RP_GET: - crc->i--; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Executing GET number %u\n", - crc->i); - GNUNET_CRYPTO_hash (&crc->i, - sizeof (int), - &crc->key); - GNUNET_DATASTORE_get_key (datastore, - 0, - false, - &crc->key, - get_type (crc->i), - 1, - 1, - &check_value, - crc); - break; - case RP_DEL: - crc->i--; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Executing DEL number %u\n", - crc->i); - crc->data = NULL; - GNUNET_CRYPTO_hash (&crc->i, sizeof (int), &crc->key); - GNUNET_assert (NULL != - GNUNET_DATASTORE_get_key (datastore, + { + case RP_PUT: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Executing PUT number %u\n", + crc->i); + GNUNET_CRYPTO_hash(&crc->i, sizeof(int), &crc->key); + GNUNET_DATASTORE_put(datastore, 0, &crc->key, get_size(crc->i), + get_data(crc->i), get_type(crc->i), + get_priority(crc->i), get_anonymity(crc->i), 0, + get_expiration(crc->i), 1, 1, + &check_success, crc); + crc->i++; + if (crc->i == ITERATIONS) + crc->phase = RP_GET; + break; + + case RP_GET: + crc->i--; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Executing GET number %u\n", + crc->i); + GNUNET_CRYPTO_hash(&crc->i, + sizeof(int), + &crc->key); + GNUNET_DATASTORE_get_key(datastore, + 0, + false, + &crc->key, + get_type(crc->i), + 1, + 1, + &check_value, + crc); + break; + + case RP_DEL: + crc->i--; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Executing DEL number %u\n", + crc->i); + crc->data = NULL; + GNUNET_CRYPTO_hash(&crc->i, sizeof(int), &crc->key); + GNUNET_assert(NULL != + GNUNET_DATASTORE_get_key(datastore, 0, false, &crc->key, - get_type (crc->i), + get_type(crc->i), 1, 1, &delete_value, crc)); - break; - case RP_DO_DEL: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Executing DO_DEL number %u\n", - crc->i); - if (crc->i == 0) - { - crc->i = ITERATIONS; - crc->phase = RP_DELVALIDATE; - } - else - { - crc->phase = RP_DEL; - } - GNUNET_assert (NULL != - GNUNET_DATASTORE_remove (datastore, &crc->key, crc->size, + break; + + case RP_DO_DEL: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Executing DO_DEL number %u\n", + crc->i); + if (crc->i == 0) + { + crc->i = ITERATIONS; + crc->phase = RP_DELVALIDATE; + } + else + { + crc->phase = RP_DEL; + } + GNUNET_assert(NULL != + GNUNET_DATASTORE_remove(datastore, &crc->key, crc->size, crc->data, 1, 1, &check_success, crc)); - break; - case RP_DELVALIDATE: - crc->i--; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Executing DELVALIDATE number %u\n", - crc->i); - GNUNET_CRYPTO_hash (&crc->i, sizeof (int), &crc->key); - GNUNET_assert (NULL != - GNUNET_DATASTORE_get_key (datastore, + break; + + case RP_DELVALIDATE: + crc->i--; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Executing DELVALIDATE number %u\n", + crc->i); + GNUNET_CRYPTO_hash(&crc->i, sizeof(int), &crc->key); + GNUNET_assert(NULL != + GNUNET_DATASTORE_get_key(datastore, 0, false, &crc->key, - get_type (crc->i), + get_type(crc->i), 1, 1, &check_nothing, crc)); - break; - case RP_RESERVE: - crc->phase = RP_PUT_MULTIPLE; - GNUNET_DATASTORE_reserve (datastore, 128 * 1024, 2, - &get_reserved, crc); - break; - case RP_PUT_MULTIPLE: - crc->phase = RP_PUT_MULTIPLE_NEXT; - GNUNET_DATASTORE_put (datastore, crc->rid, &crc->key, get_size (42), - get_data (42), get_type (42), get_priority (42), - get_anonymity (42), 0, get_expiration (42), 1, 1, - &check_success, crc); - break; - case RP_PUT_MULTIPLE_NEXT: - crc->phase = RP_GET_MULTIPLE; - GNUNET_DATASTORE_put (datastore, crc->rid, - &crc->key, - get_size (43), - get_data (43), - get_type (42), - get_priority (43), - get_anonymity (43), - 0, - get_expiration (43), - 1, 1, - &check_success, crc); - break; - case RP_GET_MULTIPLE: - GNUNET_assert (NULL != - GNUNET_DATASTORE_get_key (datastore, + break; + + case RP_RESERVE: + crc->phase = RP_PUT_MULTIPLE; + GNUNET_DATASTORE_reserve(datastore, 128 * 1024, 2, + &get_reserved, crc); + break; + + case RP_PUT_MULTIPLE: + crc->phase = RP_PUT_MULTIPLE_NEXT; + GNUNET_DATASTORE_put(datastore, crc->rid, &crc->key, get_size(42), + get_data(42), get_type(42), get_priority(42), + get_anonymity(42), 0, get_expiration(42), 1, 1, + &check_success, crc); + break; + + case RP_PUT_MULTIPLE_NEXT: + crc->phase = RP_GET_MULTIPLE; + GNUNET_DATASTORE_put(datastore, crc->rid, + &crc->key, + get_size(43), + get_data(43), + get_type(42), + get_priority(43), + get_anonymity(43), + 0, + get_expiration(43), + 1, 1, + &check_success, crc); + break; + + case RP_GET_MULTIPLE: + GNUNET_assert(NULL != + GNUNET_DATASTORE_get_key(datastore, 0, false, &crc->key, - get_type (42), + get_type(42), 1, 1, &check_multiple, crc)); - break; - case RP_GET_MULTIPLE_NEXT: - GNUNET_assert (NULL != - GNUNET_DATASTORE_get_key (datastore, + break; + + case RP_GET_MULTIPLE_NEXT: + GNUNET_assert(NULL != + GNUNET_DATASTORE_get_key(datastore, crc->first_uid + 1, false, &crc->key, - get_type (42), + get_type(42), 1, 1, &check_multiple, crc)); - break; - case RP_DONE: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished, disconnecting\n"); - GNUNET_DATASTORE_disconnect (datastore, - GNUNET_YES); - GNUNET_free (crc); - ok = 0; - break; - case RP_ERROR: - GNUNET_DATASTORE_disconnect (datastore, - GNUNET_YES); - GNUNET_free (crc); - ok = 43; - break; - } + break; + + case RP_DONE: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished, disconnecting\n"); + GNUNET_DATASTORE_disconnect(datastore, + GNUNET_YES); + GNUNET_free(crc); + ok = 0; + break; + + case RP_ERROR: + GNUNET_DATASTORE_disconnect(datastore, + GNUNET_YES); + GNUNET_free(crc); + ok = 43; + break; + } } @@ -541,37 +552,40 @@ run_continuation (void *cls) * @param msg NULL on success, otherwise an error message */ static void -run_tests (void *cls, - int32_t success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +run_tests(void *cls, + int32_t success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct CpsRunContext *crc = cls; switch (success) - { - case GNUNET_YES: - GNUNET_SCHEDULER_add_now (&run_continuation, - crc); - return; - case GNUNET_NO: - fprintf (stderr, - "%s", "Test 'put' operation failed, key already exists (!?)\n"); - GNUNET_DATASTORE_disconnect (datastore, - GNUNET_YES); - GNUNET_free (crc); - return; - case GNUNET_SYSERR: - fprintf (stderr, - "Test 'put' operation failed with error `%s' database likely not setup, skipping test.\n", - msg); - GNUNET_DATASTORE_disconnect (datastore, - GNUNET_YES); - GNUNET_free (crc); - return; - default: - GNUNET_assert (0); - } + { + case GNUNET_YES: + GNUNET_SCHEDULER_add_now(&run_continuation, + crc); + return; + + case GNUNET_NO: + fprintf(stderr, + "%s", "Test 'put' operation failed, key already exists (!?)\n"); + GNUNET_DATASTORE_disconnect(datastore, + GNUNET_YES); + GNUNET_free(crc); + return; + + case GNUNET_SYSERR: + fprintf(stderr, + "Test 'put' operation failed with error `%s' database likely not setup, skipping test.\n", + msg); + GNUNET_DATASTORE_disconnect(datastore, + GNUNET_YES); + GNUNET_free(crc); + return; + + default: + GNUNET_assert(0); + } } @@ -585,36 +599,36 @@ run_tests (void *cls, * @param peer peer handle (unused) */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct CpsRunContext *crc; static struct GNUNET_HashCode zkey; - crc = GNUNET_new (struct CpsRunContext); + crc = GNUNET_new(struct CpsRunContext); crc->phase = RP_PUT; - now = GNUNET_TIME_absolute_get (); - datastore = GNUNET_DATASTORE_connect (cfg); + now = GNUNET_TIME_absolute_get(); + datastore = GNUNET_DATASTORE_connect(cfg); if (NULL == - GNUNET_DATASTORE_put (datastore, - 0, - &zkey, - 4, - "TEST", - GNUNET_BLOCK_TYPE_TEST, - 0, 0, 0, - GNUNET_TIME_relative_to_absolute - (GNUNET_TIME_UNIT_SECONDS), - 0, 1, - &run_tests, crc)) - { - fprintf (stderr, - "%s", - "Test 'put' operation failed.\n"); - ok = 1; - GNUNET_free (crc); - } + GNUNET_DATASTORE_put(datastore, + 0, + &zkey, + 4, + "TEST", + GNUNET_BLOCK_TYPE_TEST, + 0, 0, 0, + GNUNET_TIME_relative_to_absolute + (GNUNET_TIME_UNIT_SECONDS), + 0, 1, + &run_tests, crc)) + { + fprintf(stderr, + "%s", + "Test 'put' operation failed.\n"); + ok = 1; + GNUNET_free(crc); + } } @@ -627,8 +641,8 @@ run (void *cls, * 0 for "reset to empty" */ static void -duc_dummy (void *cls, - int delta) +duc_dummy(void *cls, + int delta) { /* intentionally empty */ } @@ -638,42 +652,42 @@ duc_dummy (void *cls, * check if plugin is actually working */ static int -test_plugin (const char *cfg_name) +test_plugin(const char *cfg_name) { char libname[128]; struct GNUNET_CONFIGURATION_Handle *cfg; struct GNUNET_DATASTORE_PluginFunctions *api; struct GNUNET_DATASTORE_PluginEnvironment env; - cfg = GNUNET_CONFIGURATION_create (); + cfg = GNUNET_CONFIGURATION_create(); if (GNUNET_OK != - GNUNET_CONFIGURATION_load (cfg, - cfg_name)) - { - GNUNET_CONFIGURATION_destroy (cfg); - fprintf (stderr, - "Failed to load configuration %s\n", - cfg_name); - return 1; - } - memset (&env, 0, sizeof (env)); + GNUNET_CONFIGURATION_load(cfg, + cfg_name)) + { + GNUNET_CONFIGURATION_destroy(cfg); + fprintf(stderr, + "Failed to load configuration %s\n", + cfg_name); + return 1; + } + memset(&env, 0, sizeof(env)); env.cfg = cfg; env.duc = &duc_dummy; - GNUNET_snprintf (libname, - sizeof (libname), - "libgnunet_plugin_datastore_%s", - plugin_name); - api = GNUNET_PLUGIN_load (libname, &env); + GNUNET_snprintf(libname, + sizeof(libname), + "libgnunet_plugin_datastore_%s", + plugin_name); + api = GNUNET_PLUGIN_load(libname, &env); if (NULL == api) - { - GNUNET_CONFIGURATION_destroy (cfg); - fprintf (stderr, - "Failed to load plugin `%s'\n", - libname); - return 77; - } - GNUNET_PLUGIN_unload (libname, api); - GNUNET_CONFIGURATION_destroy (cfg); + { + GNUNET_CONFIGURATION_destroy(cfg); + fprintf(stderr, + "Failed to load plugin `%s'\n", + libname); + return 77; + } + GNUNET_PLUGIN_unload(libname, api); + GNUNET_CONFIGURATION_destroy(cfg); return 0; } @@ -688,26 +702,26 @@ test_plugin (const char *cfg_name) * @return 0 on success */ int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { char cfg_name[PATH_MAX]; int ret; - plugin_name = GNUNET_TESTING_get_testname_from_underscore (argv[0]); - GNUNET_snprintf (cfg_name, - sizeof (cfg_name), - "test_datastore_api_data_%s.conf", - plugin_name); - ret = test_plugin (cfg_name); + plugin_name = GNUNET_TESTING_get_testname_from_underscore(argv[0]); + GNUNET_snprintf(cfg_name, + sizeof(cfg_name), + "test_datastore_api_data_%s.conf", + plugin_name); + ret = test_plugin(cfg_name); if (0 != ret) return ret; /* run actual test */ if (0 != - GNUNET_TESTING_peer_run ("test-gnunet-datastore", - cfg_name, - &run, - NULL)) + GNUNET_TESTING_peer_run("test-gnunet-datastore", + cfg_name, + &run, + NULL)) return 1; return ok; } diff --git a/src/datastore/test_datastore_api_management.c b/src/datastore/test_datastore_api_management.c index fc4c03885..e7599999f 100644 --- a/src/datastore/test_datastore_api_management.c +++ b/src/datastore/test_datastore_api_management.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /* * @file datastore/test_datastore_api_management.c * @brief Test for the space management functions of the datastore implementation. @@ -33,7 +33,7 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** * Number of iterations to run; must be large enough @@ -41,8 +41,7 @@ */ #define ITERATIONS 5000 -enum RunPhase -{ +enum RunPhase { RP_PUT, RP_GET, RP_DONE, @@ -50,8 +49,7 @@ enum RunPhase }; -struct CpsRunContext -{ +struct CpsRunContext { struct GNUNET_HashCode key; int i; int found; @@ -71,45 +69,45 @@ static const char *plugin_name; static size_t -get_size (int i) +get_size(int i) { return 8 + 8 * (i % 256); } static const void * -get_data (int i) +get_data(int i) { static char buf[60000]; - memset (buf, i, 8 + 8 * (i % 256)); + memset(buf, i, 8 + 8 * (i % 256)); return buf; } static int -get_type (int i) +get_type(int i) { return 1; } static int -get_priority (int i) +get_priority(int i) { return i + 1; } static int -get_anonymity (int i) +get_anonymity(int i) { return i; } static struct GNUNET_TIME_Absolute -get_expiration (int i) +get_expiration(int i) { struct GNUNET_TIME_Absolute av; @@ -119,201 +117,204 @@ get_expiration (int i) static void -run_continuation (void *cls); +run_continuation(void *cls); static void -check_success (void *cls, int success, struct GNUNET_TIME_Absolute min_expiration, const char *msg) +check_success(void *cls, int success, struct GNUNET_TIME_Absolute min_expiration, const char *msg) { struct CpsRunContext *crc = cls; if (GNUNET_OK != success) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n", msg); - GNUNET_assert (GNUNET_OK == success); - GNUNET_free_non_null (crc->data); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", msg); + GNUNET_assert(GNUNET_OK == success); + GNUNET_free_non_null(crc->data); crc->data = NULL; - GNUNET_SCHEDULER_add_now (&run_continuation, crc); + GNUNET_SCHEDULER_add_now(&run_continuation, crc); } static void -check_value (void *cls, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +check_value(void *cls, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct CpsRunContext *crc = cls; int i; if (NULL == key) - { - crc->phase = RP_GET_FAIL; - GNUNET_SCHEDULER_add_now (&run_continuation, crc); - return; - } + { + crc->phase = RP_GET_FAIL; + GNUNET_SCHEDULER_add_now(&run_continuation, crc); + return; + } i = crc->i; - GNUNET_assert (size == get_size (i)); - GNUNET_assert (0 == memcmp (data, get_data (i), size)); - GNUNET_assert (type == get_type (i)); - GNUNET_assert (priority == get_priority (i)); - GNUNET_assert (anonymity == get_anonymity (i)); - GNUNET_assert (expiration.abs_value_us == get_expiration (i).abs_value_us); + GNUNET_assert(size == get_size(i)); + GNUNET_assert(0 == memcmp(data, get_data(i), size)); + GNUNET_assert(type == get_type(i)); + GNUNET_assert(priority == get_priority(i)); + GNUNET_assert(anonymity == get_anonymity(i)); + GNUNET_assert(expiration.abs_value_us == get_expiration(i).abs_value_us); crc->i--; if (crc->i == 0) crc->phase = RP_DONE; - GNUNET_SCHEDULER_add_now (&run_continuation, crc); + GNUNET_SCHEDULER_add_now(&run_continuation, crc); } static void -check_nothing (void *cls, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +check_nothing(void *cls, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct CpsRunContext *crc = cls; - GNUNET_assert (key == NULL); + GNUNET_assert(key == NULL); if (0 == --crc->i) crc->phase = RP_DONE; - GNUNET_SCHEDULER_add_now (&run_continuation, crc); + GNUNET_SCHEDULER_add_now(&run_continuation, crc); } static void -run_continuation (void *cls) +run_continuation(void *cls) { struct CpsRunContext *crc = cls; - ok = (int) crc->phase; + ok = (int)crc->phase; switch (crc->phase) - { - case RP_PUT: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Executing `%s' number %u\n", "PUT", - crc->i); - GNUNET_CRYPTO_hash (&crc->i, sizeof (int), &crc->key); - GNUNET_DATASTORE_put (datastore, - 0, - &crc->key, - get_size (crc->i), - get_data (crc->i), - get_type (crc->i), - get_priority (crc->i), - get_anonymity (crc->i), - 0, - get_expiration (crc->i), - 1, - 1, - &check_success, crc); - crc->i++; - if (crc->i == ITERATIONS) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Sleeping to give datastore time to clean up\n"); - sleep (1); - crc->phase = RP_GET; - crc->i--; + case RP_PUT: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Executing `%s' number %u\n", "PUT", + crc->i); + GNUNET_CRYPTO_hash(&crc->i, sizeof(int), &crc->key); + GNUNET_DATASTORE_put(datastore, + 0, + &crc->key, + get_size(crc->i), + get_data(crc->i), + get_type(crc->i), + get_priority(crc->i), + get_anonymity(crc->i), + 0, + get_expiration(crc->i), + 1, + 1, + &check_success, crc); + crc->i++; + if (crc->i == ITERATIONS) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Sleeping to give datastore time to clean up\n"); + sleep(1); + crc->phase = RP_GET; + crc->i--; + } + break; + + case RP_GET: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Executing `%s' number %u\n", "GET", + crc->i); + GNUNET_CRYPTO_hash(&crc->i, sizeof(int), &crc->key); + GNUNET_DATASTORE_get_key(datastore, + 0, + false, + &crc->key, + get_type(crc->i), + 1, + 1, + &check_value, + crc); + break; + + case RP_GET_FAIL: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Executing `%s' number %u\n", "GET(f)", + crc->i); + GNUNET_CRYPTO_hash(&crc->i, sizeof(int), &crc->key); + GNUNET_DATASTORE_get_key(datastore, + 0, + false, + &crc->key, + get_type(crc->i), + 1, + 1, + &check_nothing, + crc); + break; + + case RP_DONE: + GNUNET_assert(0 == crc->i); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Finished, disconnecting\n"); + GNUNET_DATASTORE_disconnect(datastore, GNUNET_YES); + GNUNET_free(crc); + ok = 0; } - break; - case RP_GET: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Executing `%s' number %u\n", "GET", - crc->i); - GNUNET_CRYPTO_hash (&crc->i, sizeof (int), &crc->key); - GNUNET_DATASTORE_get_key (datastore, - 0, - false, - &crc->key, - get_type (crc->i), - 1, - 1, - &check_value, - crc); - break; - case RP_GET_FAIL: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Executing `%s' number %u\n", "GET(f)", - crc->i); - GNUNET_CRYPTO_hash (&crc->i, sizeof (int), &crc->key); - GNUNET_DATASTORE_get_key (datastore, - 0, - false, - &crc->key, - get_type (crc->i), - 1, - 1, - &check_nothing, - crc); - break; - case RP_DONE: - GNUNET_assert (0 == crc->i); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Finished, disconnecting\n"); - GNUNET_DATASTORE_disconnect (datastore, GNUNET_YES); - GNUNET_free (crc); - ok = 0; - } } static void -run_tests (void *cls, int success, struct GNUNET_TIME_Absolute min_expiration, const char *msg) +run_tests(void *cls, int success, struct GNUNET_TIME_Absolute min_expiration, const char *msg) { struct CpsRunContext *crc = cls; if (success != GNUNET_YES) - { - fprintf (stderr, - "Test 'put' operation failed with error `%s' database likely not setup, skipping test.\n", - msg); - GNUNET_DATASTORE_disconnect (datastore, GNUNET_YES); - GNUNET_free (crc); - return; - } - GNUNET_SCHEDULER_add_now (&run_continuation, crc); + { + fprintf(stderr, + "Test 'put' operation failed with error `%s' database likely not setup, skipping test.\n", + msg); + GNUNET_DATASTORE_disconnect(datastore, GNUNET_YES); + GNUNET_free(crc); + return; + } + GNUNET_SCHEDULER_add_now(&run_continuation, crc); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct CpsRunContext *crc; static struct GNUNET_HashCode zkey; - crc = GNUNET_new (struct CpsRunContext); + crc = GNUNET_new(struct CpsRunContext); crc->cfg = cfg; crc->phase = RP_PUT; - now = GNUNET_TIME_absolute_get (); - datastore = GNUNET_DATASTORE_connect (cfg); + now = GNUNET_TIME_absolute_get(); + datastore = GNUNET_DATASTORE_connect(cfg); if (NULL == - GNUNET_DATASTORE_put (datastore, - 0, - &zkey, - 4, - "TEST", - GNUNET_BLOCK_TYPE_TEST, - 0, 0, 0, - GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_SECONDS), - 0, - 1, - &run_tests, - crc)) - { - fprintf (stderr, "%s", "Test 'put' operation failed.\n"); - GNUNET_free (crc); - ok = 1; - } + GNUNET_DATASTORE_put(datastore, + 0, + &zkey, + 4, + "TEST", + GNUNET_BLOCK_TYPE_TEST, + 0, 0, 0, + GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_SECONDS), + 0, + 1, + &run_tests, + crc)) + { + fprintf(stderr, "%s", "Test 'put' operation failed.\n"); + GNUNET_free(crc); + ok = 1; + } } @@ -324,8 +325,8 @@ run (void *cls, * @param delta change in utilization */ static void -ignore_payload_cb (void *cls, - int delta) +ignore_payload_cb(void *cls, + int delta) { /* do nothing */ } @@ -335,65 +336,65 @@ ignore_payload_cb (void *cls, * check if plugin is actually working */ static int -test_plugin (const char *cfg_name) +test_plugin(const char *cfg_name) { char libname[PATH_MAX]; struct GNUNET_CONFIGURATION_Handle *cfg; struct GNUNET_DATASTORE_PluginFunctions *api; struct GNUNET_DATASTORE_PluginEnvironment env; - cfg = GNUNET_CONFIGURATION_create (); + cfg = GNUNET_CONFIGURATION_create(); if (GNUNET_OK != - GNUNET_CONFIGURATION_load (cfg, - cfg_name)) - { - GNUNET_CONFIGURATION_destroy (cfg); - fprintf (stderr, - "Failed to load configuration %s\n", - cfg_name); - return 1; - } - memset (&env, 0, sizeof (env)); + GNUNET_CONFIGURATION_load(cfg, + cfg_name)) + { + GNUNET_CONFIGURATION_destroy(cfg); + fprintf(stderr, + "Failed to load configuration %s\n", + cfg_name); + return 1; + } + memset(&env, 0, sizeof(env)); env.cfg = cfg; env.duc = &ignore_payload_cb; - GNUNET_snprintf (libname, - sizeof (libname), - "libgnunet_plugin_datastore_%s", - plugin_name); - api = GNUNET_PLUGIN_load (libname, &env); + GNUNET_snprintf(libname, + sizeof(libname), + "libgnunet_plugin_datastore_%s", + plugin_name); + api = GNUNET_PLUGIN_load(libname, &env); if (NULL == api) - { - GNUNET_CONFIGURATION_destroy (cfg); - fprintf (stderr, - "Failed to load plugin `%s'\n", - libname); - return 77; - } - GNUNET_PLUGIN_unload (libname, api); - GNUNET_CONFIGURATION_destroy (cfg); + { + GNUNET_CONFIGURATION_destroy(cfg); + fprintf(stderr, + "Failed to load plugin `%s'\n", + libname); + return 77; + } + GNUNET_PLUGIN_unload(libname, api); + GNUNET_CONFIGURATION_destroy(cfg); return 0; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { char cfg_name[PATH_MAX]; int ret; - plugin_name = GNUNET_TESTING_get_testname_from_underscore (argv[0]); - GNUNET_snprintf (cfg_name, - sizeof (cfg_name), - "test_datastore_api_data_%s.conf", - plugin_name); - ret = test_plugin (cfg_name); + plugin_name = GNUNET_TESTING_get_testname_from_underscore(argv[0]); + GNUNET_snprintf(cfg_name, + sizeof(cfg_name), + "test_datastore_api_data_%s.conf", + plugin_name); + ret = test_plugin(cfg_name); if (0 != ret) return ret; if (0 != - GNUNET_TESTING_peer_run ("test-gnunet-datastore-management", - cfg_name, - &run, - NULL)) + GNUNET_TESTING_peer_run("test-gnunet-datastore-management", + cfg_name, + &run, + NULL)) return 1; return ok; } diff --git a/src/datastore/test_plugin_datastore.c b/src/datastore/test_plugin_datastore.c index 2b7bf9ae4..a260e1575 100644 --- a/src/datastore/test_plugin_datastore.c +++ b/src/datastore/test_plugin_datastore.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /* * @file test_plugin_datastore.c * @brief Test database plugin directly, calling each API function once @@ -44,8 +44,7 @@ static const char *plugin_name; static int ok; -enum RunPhase -{ +enum RunPhase { RP_ERROR = 0, RP_PUT, RP_GET, @@ -57,8 +56,7 @@ enum RunPhase }; -struct CpsRunContext -{ +struct CpsRunContext { const struct GNUNET_CONFIGURATION_Handle *cfg; struct GNUNET_DATASTORE_PluginFunctions *api; enum RunPhase phase; @@ -76,14 +74,14 @@ struct CpsRunContext * 0 for "reset to empty" */ static void -disk_utilization_change_cb (void *cls, int delta) +disk_utilization_change_cb(void *cls, int delta) { /* do nothing */ } static void -test (void *cls); +test(void *cls); /** @@ -96,47 +94,47 @@ test (void *cls); * @param msg error message on error */ static void -put_continuation (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - int status, - const char *msg) +put_continuation(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + int status, + const char *msg) { struct CpsRunContext *crc = cls; static unsigned long long os; unsigned long long cs; if (GNUNET_OK != status) - { - fprintf (stderr, - "ERROR: `%s'\n", - msg); - } + { + fprintf(stderr, + "ERROR: `%s'\n", + msg); + } else - { - crc->api->estimate_size (crc->api->cls, - &cs); - GNUNET_assert (os <= cs); - os = cs; - stored_bytes += size; - stored_ops++; - stored_entries++; - } - GNUNET_SCHEDULER_add_now (&test, crc); + { + crc->api->estimate_size(crc->api->cls, + &cs); + GNUNET_assert(os <= cs); + os = cs; + stored_bytes += size; + stored_ops++; + stored_entries++; + } + GNUNET_SCHEDULER_add_now(&test, crc); } static void -gen_key (int i, struct GNUNET_HashCode * key) +gen_key(int i, struct GNUNET_HashCode * key) { - memset (key, 0, sizeof (struct GNUNET_HashCode)); - key->bits[0] = (unsigned int) i; - GNUNET_CRYPTO_hash (key, sizeof (struct GNUNET_HashCode), key); + memset(key, 0, sizeof(struct GNUNET_HashCode)); + key->bits[0] = (unsigned int)i; + GNUNET_CRYPTO_hash(key, sizeof(struct GNUNET_HashCode), key); } static void -do_put (struct CpsRunContext *crc) +do_put(struct CpsRunContext *crc) { char value[65536]; size_t size; @@ -145,45 +143,45 @@ do_put (struct CpsRunContext *crc) static int i; if (PUT_10 == i) - { - i = 0; - crc->phase++; - GNUNET_SCHEDULER_add_now (&test, crc); - return; - } + { + i = 0; + crc->phase++; + GNUNET_SCHEDULER_add_now(&test, crc); + return; + } /* most content is 32k */ size = 32 * 1024; - if (0 != i && GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 16) == 0) /* but some of it is less! */ - size = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 32 * 1024); + if (0 != i && GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 16) == 0) /* but some of it is less! */ + size = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 32 * 1024); size = size - (size & 7); /* always multiple of 8 */ /* generate random key */ - gen_key (i, &key); - memset (value, i, size); + gen_key(i, &key); + memset(value, i, size); if (i > 255) - memset (value, i - 255, size / 2); + memset(value, i - 255, size / 2); value[0] = crc->i; - prio = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "putting type %u, anon %u under key %s\n", i + 1, i, - GNUNET_h2s (&key)); - crc->api->put (crc->api->cls, - &key, - false /* absent */, - size, - value, i + 1 /* type */ , - prio, - i /* anonymity */ , - 0 /* replication */ , - GNUNET_TIME_relative_to_absolute - (GNUNET_TIME_relative_multiply - (GNUNET_TIME_UNIT_MILLISECONDS, - 60 * 60 * 60 * 1000 + - GNUNET_CRYPTO_random_u32 + prio = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 100); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "putting type %u, anon %u under key %s\n", i + 1, i, + GNUNET_h2s(&key)); + crc->api->put(crc->api->cls, + &key, + false /* absent */, + size, + value, i + 1 /* type */, + prio, + i /* anonymity */, + 0 /* replication */, + GNUNET_TIME_relative_to_absolute + (GNUNET_TIME_relative_multiply + (GNUNET_TIME_UNIT_MILLISECONDS, + 60 * 60 * 60 * 1000 + + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 1000))), - put_continuation, - crc); + put_continuation, + crc); i++; } @@ -192,51 +190,51 @@ static uint64_t guid; static int -iterate_one_shot (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +iterate_one_shot(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct CpsRunContext *crc = cls; - GNUNET_assert (NULL != key); + GNUNET_assert(NULL != key); guid = uid; crc->phase++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found result type=%u, priority=%u, size=%u, expire=%s, key %s\n", - (unsigned int) type, - (unsigned int) priority, - (unsigned int) size, - GNUNET_STRINGS_absolute_time_to_string (expiration), - GNUNET_h2s (key)); - GNUNET_SCHEDULER_add_now (&test, - crc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found result type=%u, priority=%u, size=%u, expire=%s, key %s\n", + (unsigned int)type, + (unsigned int)priority, + (unsigned int)size, + GNUNET_STRINGS_absolute_time_to_string(expiration), + GNUNET_h2s(key)); + GNUNET_SCHEDULER_add_now(&test, + crc); return GNUNET_OK; } static void -remove_continuation (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - int status, - const char *msg) +remove_continuation(void *cls, + const struct GNUNET_HashCode *key, + uint32_t size, + int status, + const char *msg) { struct CpsRunContext *crc = cls; - GNUNET_assert (NULL != key); - GNUNET_assert (32768 == size); - GNUNET_assert (GNUNET_OK == status); - GNUNET_assert (NULL == msg); + GNUNET_assert(NULL != key); + GNUNET_assert(32768 == size); + GNUNET_assert(GNUNET_OK == status); + GNUNET_assert(NULL == msg); crc->phase++; - GNUNET_SCHEDULER_add_now (&test, - crc); + GNUNET_SCHEDULER_add_now(&test, + crc); } @@ -248,28 +246,28 @@ remove_continuation (void *cls, * @param cfg configuration to use */ static void -unload_plugin (struct GNUNET_DATASTORE_PluginFunctions *api, - const struct GNUNET_CONFIGURATION_Handle *cfg) +unload_plugin(struct GNUNET_DATASTORE_PluginFunctions *api, + const struct GNUNET_CONFIGURATION_Handle *cfg) { char *name; char *libname; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "DATASTORE", - "DATABASE", - &name)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No `%s' specified for `%s' in configuration!\n"), - "DATABASE", - "DATASTORE"); - return; - } - GNUNET_asprintf (&libname, "libgnunet_plugin_datastore_%s", name); - GNUNET_break (NULL == GNUNET_PLUGIN_unload (libname, api)); - GNUNET_free (libname); - GNUNET_free (name); + GNUNET_CONFIGURATION_get_value_string(cfg, + "DATASTORE", + "DATABASE", + &name)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No `%s' specified for `%s' in configuration!\n"), + "DATABASE", + "DATASTORE"); + return; + } + GNUNET_asprintf(&libname, "libgnunet_plugin_datastore_%s", name); + GNUNET_break(NULL == GNUNET_PLUGIN_unload(libname, api)); + GNUNET_free(libname); + GNUNET_free(name); } @@ -279,92 +277,99 @@ unload_plugin (struct GNUNET_DATASTORE_PluginFunctions *api, * the transport and core. */ static void -cleaning_task (void *cls) +cleaning_task(void *cls) { struct CpsRunContext *crc = cls; - unload_plugin (crc->api, crc->cfg); - GNUNET_free (crc); + unload_plugin(crc->api, crc->cfg); + GNUNET_free(crc); } static void -test (void *cls) +test(void *cls) { struct CpsRunContext *crc = cls; struct GNUNET_HashCode key; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "In phase %d, iteration %u\n", crc->phase, crc->cnt); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "In phase %d, iteration %u\n", crc->phase, crc->cnt); switch (crc->phase) - { - case RP_ERROR: - ok = 1; - GNUNET_break (0); - crc->api->drop (crc->api->cls); - GNUNET_SCHEDULER_add_now (&cleaning_task, crc); - break; - case RP_PUT: - do_put (crc); - break; - case RP_GET: - if (crc->cnt == 1) { - crc->cnt = 0; - crc->phase++; - GNUNET_SCHEDULER_add_now (&test, crc); + case RP_ERROR: + ok = 1; + GNUNET_break(0); + crc->api->drop(crc->api->cls); + GNUNET_SCHEDULER_add_now(&cleaning_task, crc); break; - } - gen_key (5, &key); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Looking for %s\n", - GNUNET_h2s (&key)); - crc->api->get_key (crc->api->cls, - 0, - false, - &key, - GNUNET_BLOCK_TYPE_ANY, - &iterate_one_shot, - crc); - break; - case RP_ITER_ZERO: - if (crc->cnt == 1) - { - crc->cnt = 0; - crc->phase++; - GNUNET_SCHEDULER_add_now (&test, crc); + + case RP_PUT: + do_put(crc); break; - } - crc->api->get_zero_anonymity (crc->api->cls, 0, 1, &iterate_one_shot, crc); - break; - case RP_REPL_GET: - crc->api->get_replication (crc->api->cls, &iterate_one_shot, crc); - break; - case RP_EXPI_GET: - crc->api->get_expiration (crc->api->cls, &iterate_one_shot, crc); - break; - case RP_REMOVE: + + case RP_GET: + if (crc->cnt == 1) + { + crc->cnt = 0; + crc->phase++; + GNUNET_SCHEDULER_add_now(&test, crc); + break; + } + gen_key(5, &key); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Looking for %s\n", + GNUNET_h2s(&key)); + crc->api->get_key(crc->api->cls, + 0, + false, + &key, + GNUNET_BLOCK_TYPE_ANY, + &iterate_one_shot, + crc); + break; + + case RP_ITER_ZERO: + if (crc->cnt == 1) + { + crc->cnt = 0; + crc->phase++; + GNUNET_SCHEDULER_add_now(&test, crc); + break; + } + crc->api->get_zero_anonymity(crc->api->cls, 0, 1, &iterate_one_shot, crc); + break; + + case RP_REPL_GET: + crc->api->get_replication(crc->api->cls, &iterate_one_shot, crc); + break; + + case RP_EXPI_GET: + crc->api->get_expiration(crc->api->cls, &iterate_one_shot, crc); + break; + + case RP_REMOVE: { struct GNUNET_HashCode key; uint32_t size = 32768; char value[size]; - gen_key (0, &key); - memset (value, 0, size); + gen_key(0, &key); + memset(value, 0, size); value[0] = crc->i; - crc->api->remove_key (crc->api->cls, - &key, - size, - value, - &remove_continuation, - crc); + crc->api->remove_key(crc->api->cls, + &key, + size, + value, + &remove_continuation, + crc); + break; + } + + case RP_DROP: + crc->api->drop(crc->api->cls); + GNUNET_SCHEDULER_add_now(&cleaning_task, crc); break; } - case RP_DROP: - crc->api->drop (crc->api->cls); - GNUNET_SCHEDULER_add_now (&cleaning_task, crc); - break; - } } @@ -372,7 +377,7 @@ test (void *cls) * Load the datastore plugin. */ static struct GNUNET_DATASTORE_PluginFunctions * -load_plugin (const struct GNUNET_CONFIGURATION_Handle *cfg) +load_plugin(const struct GNUNET_CONFIGURATION_Handle *cfg) { static struct GNUNET_DATASTORE_PluginEnvironment env; struct GNUNET_DATASTORE_PluginFunctions *ret; @@ -380,61 +385,61 @@ load_plugin (const struct GNUNET_CONFIGURATION_Handle *cfg) char *libname; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "DATASTORE", - "DATABASE", - &name)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No `%s' specified for `%s' in configuration!\n"), - "DATABASE", - "DATASTORE"); - return NULL; - } + GNUNET_CONFIGURATION_get_value_string(cfg, + "DATASTORE", + "DATABASE", + &name)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No `%s' specified for `%s' in configuration!\n"), + "DATABASE", + "DATASTORE"); + return NULL; + } env.cfg = cfg; env.duc = &disk_utilization_change_cb; env.cls = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Loading `%s' datastore plugin\n"), - name); - GNUNET_asprintf (&libname, "libgnunet_plugin_datastore_%s", name); - if (NULL == (ret = GNUNET_PLUGIN_load (libname, &env))) - { - fprintf (stderr, "Failed to load plugin `%s'!\n", name); - GNUNET_free (libname); - GNUNET_free (name); - ok = 77; /* mark test as skipped */ - return NULL; - } - GNUNET_free (libname); - GNUNET_free (name); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Loading `%s' datastore plugin\n"), + name); + GNUNET_asprintf(&libname, "libgnunet_plugin_datastore_%s", name); + if (NULL == (ret = GNUNET_PLUGIN_load(libname, &env))) + { + fprintf(stderr, "Failed to load plugin `%s'!\n", name); + GNUNET_free(libname); + GNUNET_free(name); + ok = 77; /* mark test as skipped */ + return NULL; + } + GNUNET_free(libname); + GNUNET_free(name); return ret; } static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { struct GNUNET_DATASTORE_PluginFunctions *api; struct CpsRunContext *crc; - api = load_plugin (c); + api = load_plugin(c); if (api == NULL) - { - fprintf (stderr, - "%s", "Could not initialize plugin, assuming database not configured. Test not run!\n"); - return; - } - crc = GNUNET_new (struct CpsRunContext); + { + fprintf(stderr, + "%s", "Could not initialize plugin, assuming database not configured. Test not run!\n"); + return; + } + crc = GNUNET_new(struct CpsRunContext); crc->api = api; crc->cfg = c; crc->phase = RP_PUT; - GNUNET_SCHEDULER_add_now (&test, crc); + GNUNET_SCHEDULER_add_now(&test, crc); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { char dir_name[PATH_MAX]; char cfg_name[PATH_MAX]; @@ -449,20 +454,20 @@ main (int argc, char *argv[]) }; /* determine name of plugin to use */ - plugin_name = GNUNET_TESTING_get_testname_from_underscore (argv[0]); - GNUNET_snprintf (dir_name, sizeof (dir_name), - "/tmp/test-gnunet-datastore-plugin-%s", plugin_name); - GNUNET_DISK_directory_remove (dir_name); - GNUNET_log_setup ("test-plugin-datastore", - "WARNING", - NULL); - GNUNET_snprintf (cfg_name, sizeof (cfg_name), - "test_plugin_datastore_data_%s.conf", plugin_name); - GNUNET_PROGRAM_run ((sizeof (xargv) / sizeof (char *)) - 1, xargv, - "test-plugin-datastore", "nohelp", options, &run, NULL); - if ( (0 != ok) && (77 != ok) ) - fprintf (stderr, "Missed some testcases: %u\n", ok); - GNUNET_DISK_directory_remove (dir_name); + plugin_name = GNUNET_TESTING_get_testname_from_underscore(argv[0]); + GNUNET_snprintf(dir_name, sizeof(dir_name), + "/tmp/test-gnunet-datastore-plugin-%s", plugin_name); + GNUNET_DISK_directory_remove(dir_name); + GNUNET_log_setup("test-plugin-datastore", + "WARNING", + NULL); + GNUNET_snprintf(cfg_name, sizeof(cfg_name), + "test_plugin_datastore_data_%s.conf", plugin_name); + GNUNET_PROGRAM_run((sizeof(xargv) / sizeof(char *)) - 1, xargv, + "test-plugin-datastore", "nohelp", options, &run, NULL); + if ((0 != ok) && (77 != ok)) + fprintf(stderr, "Missed some testcases: %u\n", ok); + GNUNET_DISK_directory_remove(dir_name); return ok; } diff --git a/src/dht/dht.h b/src/dht/dht.h index 46fad3669..3d5fc0963 100644 --- a/src/dht/dht.h +++ b/src/dht/dht.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -40,8 +40,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * Message which indicates the DHT should cancel outstanding * requests and discard any state. */ -struct GNUNET_DHT_ClientGetStopMessage -{ +struct GNUNET_DHT_ClientGetStopMessage { /** * Type: #GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP */ @@ -61,7 +60,6 @@ struct GNUNET_DHT_ClientGetStopMessage * Key of this request */ struct GNUNET_HashCode key; - }; @@ -69,8 +67,7 @@ struct GNUNET_DHT_ClientGetStopMessage * DHT GET message sent from clients to service. Indicates that a GET * request should be issued. */ -struct GNUNET_DHT_ClientGetMessage -{ +struct GNUNET_DHT_ClientGetMessage { /** * Type: #GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET */ @@ -104,7 +101,6 @@ struct GNUNET_DHT_ClientGetMessage uint64_t unique_id GNUNET_PACKED; /* Possibly followed by xquery, copied to end of this dealy do */ - }; @@ -112,8 +108,7 @@ struct GNUNET_DHT_ClientGetMessage * DHT GET RESULTS KNOWN message sent from clients to service. Indicates that a GET * request should exclude certain results which are already known. */ -struct GNUNET_DHT_ClientGetResultSeenMessage -{ +struct GNUNET_DHT_ClientGetResultSeenMessage { /** * Type: #GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_RESULTS_KNOWN */ @@ -136,7 +131,6 @@ struct GNUNET_DHT_ClientGetResultSeenMessage uint64_t unique_id GNUNET_PACKED; /* Followed by an array of the hash codes of known results */ - }; @@ -144,8 +138,7 @@ struct GNUNET_DHT_ClientGetResultSeenMessage /** * Reply to a GET send from the service to a client. */ -struct GNUNET_DHT_ClientResultMessage -{ +struct GNUNET_DHT_ClientResultMessage { /** * Type: #GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT */ @@ -184,15 +177,13 @@ struct GNUNET_DHT_ClientResultMessage struct GNUNET_HashCode key GNUNET_PACKED; /* put path, get path and actual data are copied to end of this dealy do */ - }; /** * Message to insert data into the DHT, sent from clients to DHT service. */ -struct GNUNET_DHT_ClientPutMessage -{ +struct GNUNET_DHT_ClientPutMessage { /** * Type: #GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT */ @@ -224,15 +215,13 @@ struct GNUNET_DHT_ClientPutMessage struct GNUNET_HashCode key GNUNET_PACKED; /* DATA copied to end of this message */ - }; /** * Message to monitor put requests going through peer, DHT service -> clients. */ -struct GNUNET_DHT_MonitorPutMessage -{ +struct GNUNET_DHT_MonitorPutMessage { /** * Type: #GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT */ @@ -277,15 +266,13 @@ struct GNUNET_DHT_MonitorPutMessage /* put path (if tracked) */ /* Payload */ - }; /** * Message to request monitoring messages, clients -> DHT service. */ -struct GNUNET_DHT_MonitorStartStopMessage -{ +struct GNUNET_DHT_MonitorStartStopMessage { /** * Type: #GNUNET_MESSAGE_TYPE_DHT_MONITOR_START or * #GNUNET_MESSAGE_TYPE_DHT_MONITOR_STOP @@ -327,8 +314,7 @@ struct GNUNET_DHT_MonitorStartStopMessage /** * Message to monitor get requests going through peer, DHT service -> clients. */ -struct GNUNET_DHT_MonitorGetMessage -{ +struct GNUNET_DHT_MonitorGetMessage { /** * Type: #GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET */ @@ -366,14 +352,12 @@ struct GNUNET_DHT_MonitorGetMessage struct GNUNET_HashCode key GNUNET_PACKED; /* get path (if tracked) */ - }; /** * Message to monitor get results going through peer, DHT service -> clients. */ -struct GNUNET_DHT_MonitorGetRespMessage -{ +struct GNUNET_DHT_MonitorGetRespMessage { /** * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT */ @@ -409,7 +393,6 @@ struct GNUNET_DHT_MonitorGetRespMessage /* get path (if tracked) */ /* Payload */ - }; GNUNET_NETWORK_STRUCT_END diff --git a/src/dht/dht_api.c b/src/dht/dht_api.c index 69ac041cc..516c96479 100644 --- a/src/dht/dht_api.c +++ b/src/dht/dht_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/dht_api.c @@ -34,14 +34,13 @@ #include "gnunet_dht_service.h" #include "dht.h" -#define LOG(kind,...) GNUNET_log_from (kind, "dht-api",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "dht-api", __VA_ARGS__) /** * Handle to a PUT request. */ -struct GNUNET_DHT_PutHandle -{ +struct GNUNET_DHT_PutHandle { /** * Kept in a DLL. */ @@ -71,15 +70,12 @@ struct GNUNET_DHT_PutHandle * Envelope from the PUT operation. */ struct GNUNET_MQ_Envelope *env; - }; /** * Handle to a GET request */ -struct GNUNET_DHT_GetHandle -{ - +struct GNUNET_DHT_GetHandle { /** * Iterator to call on data receipt */ @@ -142,15 +138,13 @@ struct GNUNET_DHT_GetHandle * end of the positions that are actually used. */ unsigned int seen_results_end; - }; /** * Handle to a monitoring request. */ -struct GNUNET_DHT_MonitorHandle -{ +struct GNUNET_DHT_MonitorHandle { /** * DLL. */ @@ -195,16 +189,13 @@ struct GNUNET_DHT_MonitorHandle * Closure for @e get_cb, @e put_cb and @e get_resp_cb. */ void *cb_cls; - }; /** * Connection to the DHT service. */ -struct GNUNET_DHT_Handle -{ - +struct GNUNET_DHT_Handle { /** * Configuration to use. */ @@ -256,8 +247,6 @@ struct GNUNET_DHT_Handle * Generator for unique ids. */ uint64_t uid_gen; - - }; @@ -268,7 +257,7 @@ struct GNUNET_DHT_Handle * @return #GNUNET_YES on success, #GNUNET_NO on failure. */ static int -try_connect (struct GNUNET_DHT_Handle *h); +try_connect(struct GNUNET_DHT_Handle *h); /** @@ -277,25 +266,25 @@ try_connect (struct GNUNET_DHT_Handle *h); * @param gh GET to generate messages for. */ static void -send_get (struct GNUNET_DHT_GetHandle *gh) +send_get(struct GNUNET_DHT_GetHandle *gh) { struct GNUNET_DHT_Handle *h = gh->dht_handle; struct GNUNET_MQ_Envelope *env; struct GNUNET_DHT_ClientGetMessage *get_msg; - env = GNUNET_MQ_msg_extra (get_msg, - gh->xquery_size, - GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET); - get_msg->options = htonl ((uint32_t) gh->options); - get_msg->desired_replication_level = htonl (gh->desired_replication_level); - get_msg->type = htonl (gh->type); + env = GNUNET_MQ_msg_extra(get_msg, + gh->xquery_size, + GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET); + get_msg->options = htonl((uint32_t)gh->options); + get_msg->desired_replication_level = htonl(gh->desired_replication_level); + get_msg->type = htonl(gh->type); get_msg->key = gh->key; get_msg->unique_id = gh->unique_id; - GNUNET_memcpy (&get_msg[1], - &gh[1], - gh->xquery_size); - GNUNET_MQ_send (h->mq, - env); + GNUNET_memcpy(&get_msg[1], + &gh[1], + gh->xquery_size); + GNUNET_MQ_send(h->mq, + env); } @@ -309,8 +298,8 @@ send_get (struct GNUNET_DHT_GetHandle *gh) * @param transmission_offset_start at which offset should we start? */ static void -send_get_known_results (struct GNUNET_DHT_GetHandle *gh, - unsigned int transmission_offset_start) +send_get_known_results(struct GNUNET_DHT_GetHandle *gh, + unsigned int transmission_offset_start) { struct GNUNET_DHT_Handle *h = gh->dht_handle; struct GNUNET_MQ_Envelope *env; @@ -319,26 +308,26 @@ send_get_known_results (struct GNUNET_DHT_GetHandle *gh, unsigned int max; unsigned int transmission_offset; - max = (GNUNET_MAX_MESSAGE_SIZE - sizeof (*msg)) - / sizeof (struct GNUNET_HashCode); + max = (GNUNET_MAX_MESSAGE_SIZE - sizeof(*msg)) + / sizeof(struct GNUNET_HashCode); transmission_offset = transmission_offset_start; while (transmission_offset < gh->seen_results_end) - { - delta = gh->seen_results_end - transmission_offset; - if (delta > max) - delta = max; - env = GNUNET_MQ_msg_extra (msg, - delta * sizeof (struct GNUNET_HashCode), - GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_RESULTS_KNOWN); - msg->key = gh->key; - msg->unique_id = gh->unique_id; - GNUNET_memcpy (&msg[1], - &gh->seen_results[transmission_offset], - sizeof (struct GNUNET_HashCode) * delta); - GNUNET_MQ_send (h->mq, - env); - transmission_offset += delta; - } + { + delta = gh->seen_results_end - transmission_offset; + if (delta > max) + delta = max; + env = GNUNET_MQ_msg_extra(msg, + delta * sizeof(struct GNUNET_HashCode), + GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_RESULTS_KNOWN); + msg->key = gh->key; + msg->unique_id = gh->unique_id; + GNUNET_memcpy(&msg[1], + &gh->seen_results[transmission_offset], + sizeof(struct GNUNET_HashCode) * delta); + GNUNET_MQ_send(h->mq, + env); + transmission_offset += delta; + } } @@ -352,19 +341,19 @@ send_get_known_results (struct GNUNET_DHT_GetHandle *gh, * @return #GNUNET_YES (always) */ static int -add_get_request_to_pending (void *cls, - const struct GNUNET_HashCode *key, - void *value) +add_get_request_to_pending(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GNUNET_DHT_Handle *handle = cls; struct GNUNET_DHT_GetHandle *gh = value; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Retransmitting request related to %s to DHT %p\n", - GNUNET_h2s (key), - handle); - send_get (gh); - send_get_known_results (gh, 0); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Retransmitting request related to %s to DHT %p\n", + GNUNET_h2s(key), + handle); + send_get(gh); + send_get_known_results(gh, 0); return GNUNET_YES; } @@ -375,25 +364,25 @@ add_get_request_to_pending (void *cls, * @param mh monitor handle to generate start message for */ static void -send_monitor_start (struct GNUNET_DHT_MonitorHandle *mh) +send_monitor_start(struct GNUNET_DHT_MonitorHandle *mh) { struct GNUNET_DHT_Handle *h = mh->dht_handle; struct GNUNET_MQ_Envelope *env; struct GNUNET_DHT_MonitorStartStopMessage *m; - env = GNUNET_MQ_msg (m, - GNUNET_MESSAGE_TYPE_DHT_MONITOR_START); - m->type = htonl (mh->type); - m->get = htons (NULL != mh->get_cb); - m->get_resp = htons (NULL != mh->get_resp_cb); - m->put = htons (NULL != mh->put_cb); + env = GNUNET_MQ_msg(m, + GNUNET_MESSAGE_TYPE_DHT_MONITOR_START); + m->type = htonl(mh->type); + m->get = htons(NULL != mh->get_cb); + m->get_resp = htons(NULL != mh->get_resp_cb); + m->put = htons(NULL != mh->put_cb); if (NULL != mh->key) - { - m->filter_key = htons(1); - m->key = *mh->key; - } - GNUNET_MQ_send (h->mq, - env); + { + m->filter_key = htons(1); + m->key = *mh->key; + } + GNUNET_MQ_send(h->mq, + env); } @@ -403,31 +392,31 @@ send_monitor_start (struct GNUNET_DHT_MonitorHandle *mh) * @param cls a `struct GNUNET_DHT_Handle` */ static void -try_reconnect (void *cls) +try_reconnect(void *cls) { struct GNUNET_DHT_Handle *h = cls; struct GNUNET_DHT_MonitorHandle *mh; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Reconnecting with DHT %p\n", - h); - h->retry_time = GNUNET_TIME_STD_BACKOFF (h->retry_time); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Reconnecting with DHT %p\n", + h); + h->retry_time = GNUNET_TIME_STD_BACKOFF(h->retry_time); h->reconnect_task = NULL; - if (GNUNET_YES != try_connect (h)) - { - LOG (GNUNET_ERROR_TYPE_WARNING, - "DHT reconnect failed!\n"); - h->reconnect_task - = GNUNET_SCHEDULER_add_delayed (h->retry_time, - &try_reconnect, - h); - return; - } - GNUNET_CONTAINER_multihashmap_iterate (h->active_requests, - &add_get_request_to_pending, - h); + if (GNUNET_YES != try_connect(h)) + { + LOG(GNUNET_ERROR_TYPE_WARNING, + "DHT reconnect failed!\n"); + h->reconnect_task + = GNUNET_SCHEDULER_add_delayed(h->retry_time, + &try_reconnect, + h); + return; + } + GNUNET_CONTAINER_multihashmap_iterate(h->active_requests, + &add_get_request_to_pending, + h); for (mh = h->monitor_head; NULL != mh; mh = mh->next) - send_monitor_start (mh); + send_monitor_start(mh); } @@ -437,7 +426,7 @@ try_reconnect (void *cls) * @param h handle to dht to (possibly) disconnect and reconnect */ static void -do_disconnect (struct GNUNET_DHT_Handle *h) +do_disconnect(struct GNUNET_DHT_Handle *h) { struct GNUNET_DHT_PutHandle *ph; GNUNET_SCHEDULER_TaskCallback cont; @@ -445,27 +434,27 @@ do_disconnect (struct GNUNET_DHT_Handle *h) if (NULL == h->mq) return; - GNUNET_MQ_destroy (h->mq); + GNUNET_MQ_destroy(h->mq); h->mq = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Disconnecting from DHT service, will try to reconnect in %s\n", - GNUNET_STRINGS_relative_time_to_string (h->retry_time, - GNUNET_YES)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Disconnecting from DHT service, will try to reconnect in %s\n", + GNUNET_STRINGS_relative_time_to_string(h->retry_time, + GNUNET_YES)); /* notify client about all PUTs that (may) have failed due to disconnect */ while (NULL != (ph = h->put_head)) - { - cont = ph->cont; - cont_cls = ph->cont_cls; - ph->env = NULL; - GNUNET_DHT_put_cancel (ph); - if (NULL != cont) - cont (cont_cls); - } - GNUNET_assert (NULL == h->reconnect_task); + { + cont = ph->cont; + cont_cls = ph->cont_cls; + ph->env = NULL; + GNUNET_DHT_put_cancel(ph); + if (NULL != cont) + cont(cont_cls); + } + GNUNET_assert(NULL == h->reconnect_task); h->reconnect_task - = GNUNET_SCHEDULER_add_delayed (h->retry_time, - &try_reconnect, - h); + = GNUNET_SCHEDULER_add_delayed(h->retry_time, + &try_reconnect, + h); } @@ -478,12 +467,12 @@ do_disconnect (struct GNUNET_DHT_Handle *h) * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_DHT_Handle *h = cls; - do_disconnect (h); + do_disconnect(h); } @@ -496,18 +485,18 @@ mq_error_handler (void *cls, * #GNUNET_SYSERR if the message is malformed. */ static int -check_monitor_get (void *cls, - const struct GNUNET_DHT_MonitorGetMessage *msg) +check_monitor_get(void *cls, + const struct GNUNET_DHT_MonitorGetMessage *msg) { - uint32_t plen = ntohl (msg->get_path_length); - uint16_t msize = ntohs (msg->header.size) - sizeof (*msg); - - if ( (plen > UINT16_MAX) || - (plen * sizeof (struct GNUNET_PeerIdentity) != msize) ) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + uint32_t plen = ntohl(msg->get_path_length); + uint16_t msize = ntohs(msg->header.size) - sizeof(*msg); + + if ((plen > UINT16_MAX) || + (plen * sizeof(struct GNUNET_PeerIdentity) != msize)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -519,31 +508,31 @@ check_monitor_get (void *cls, * @param msg Monitor get message from the service. */ static void -handle_monitor_get (void *cls, - const struct GNUNET_DHT_MonitorGetMessage *msg) +handle_monitor_get(void *cls, + const struct GNUNET_DHT_MonitorGetMessage *msg) { struct GNUNET_DHT_Handle *handle = cls; struct GNUNET_DHT_MonitorHandle *mh; for (mh = handle->monitor_head; NULL != mh; mh = mh->next) - { - if (NULL == mh->get_cb) - continue; - if ( ( (GNUNET_BLOCK_TYPE_ANY == mh->type) || - (mh->type == ntohl (msg->type)) ) && - ( (NULL == mh->key) || - (0 == memcmp (mh->key, - &msg->key, - sizeof (struct GNUNET_HashCode))) ) ) - mh->get_cb (mh->cb_cls, - ntohl (msg->options), - (enum GNUNET_BLOCK_Type) ntohl(msg->type), - ntohl (msg->hop_count), - ntohl (msg->desired_replication_level), - ntohl (msg->get_path_length), - (struct GNUNET_PeerIdentity *) &msg[1], - &msg->key); - } + { + if (NULL == mh->get_cb) + continue; + if (((GNUNET_BLOCK_TYPE_ANY == mh->type) || + (mh->type == ntohl(msg->type))) && + ((NULL == mh->key) || + (0 == memcmp(mh->key, + &msg->key, + sizeof(struct GNUNET_HashCode))))) + mh->get_cb(mh->cb_cls, + ntohl(msg->options), + (enum GNUNET_BLOCK_Type)ntohl(msg->type), + ntohl(msg->hop_count), + ntohl(msg->desired_replication_level), + ntohl(msg->get_path_length), + (struct GNUNET_PeerIdentity *)&msg[1], + &msg->key); + } } @@ -556,19 +545,19 @@ handle_monitor_get (void *cls, * #GNUNET_SYSERR if the message is malformed. */ static int -check_monitor_get_resp (void *cls, - const struct GNUNET_DHT_MonitorGetRespMessage *msg) +check_monitor_get_resp(void *cls, + const struct GNUNET_DHT_MonitorGetRespMessage *msg) { - size_t msize = ntohs (msg->header.size) - sizeof (*msg); - uint32_t getl = ntohl (msg->get_path_length); - uint32_t putl = ntohl (msg->put_path_length); - - if ( (getl + putl < getl) || - ( (msize / sizeof (struct GNUNET_PeerIdentity)) < getl + putl) ) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + size_t msize = ntohs(msg->header.size) - sizeof(*msg); + uint32_t getl = ntohl(msg->get_path_length); + uint32_t putl = ntohl(msg->put_path_length); + + if ((getl + putl < getl) || + ((msize / sizeof(struct GNUNET_PeerIdentity)) < getl + putl)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -580,38 +569,38 @@ check_monitor_get_resp (void *cls, * @param msg monitor get response message from the service */ static void -handle_monitor_get_resp (void *cls, - const struct GNUNET_DHT_MonitorGetRespMessage *msg) +handle_monitor_get_resp(void *cls, + const struct GNUNET_DHT_MonitorGetRespMessage *msg) { struct GNUNET_DHT_Handle *handle = cls; - size_t msize = ntohs (msg->header.size) - sizeof (*msg); + size_t msize = ntohs(msg->header.size) - sizeof(*msg); const struct GNUNET_PeerIdentity *path; - uint32_t getl = ntohl (msg->get_path_length); - uint32_t putl = ntohl (msg->put_path_length); + uint32_t getl = ntohl(msg->get_path_length); + uint32_t putl = ntohl(msg->put_path_length); struct GNUNET_DHT_MonitorHandle *mh; - path = (const struct GNUNET_PeerIdentity *) &msg[1]; + path = (const struct GNUNET_PeerIdentity *)&msg[1]; for (mh = handle->monitor_head; NULL != mh; mh = mh->next) - { - if (NULL == mh->get_resp_cb) - continue; - if ( ( (GNUNET_BLOCK_TYPE_ANY == mh->type) || - (mh->type == ntohl(msg->type)) ) && - ( (NULL == mh->key) || - (0 == memcmp (mh->key, - &msg->key, - sizeof (struct GNUNET_HashCode))) ) ) - mh->get_resp_cb (mh->cb_cls, - (enum GNUNET_BLOCK_Type) ntohl (msg->type), - path, - getl, - &path[getl], - putl, - GNUNET_TIME_absolute_ntoh(msg->expiration_time), - &msg->key, - (const void *) &path[getl + putl], - msize - sizeof (struct GNUNET_PeerIdentity) * (putl + getl)); - } + { + if (NULL == mh->get_resp_cb) + continue; + if (((GNUNET_BLOCK_TYPE_ANY == mh->type) || + (mh->type == ntohl(msg->type))) && + ((NULL == mh->key) || + (0 == memcmp(mh->key, + &msg->key, + sizeof(struct GNUNET_HashCode))))) + mh->get_resp_cb(mh->cb_cls, + (enum GNUNET_BLOCK_Type)ntohl(msg->type), + path, + getl, + &path[getl], + putl, + GNUNET_TIME_absolute_ntoh(msg->expiration_time), + &msg->key, + (const void *)&path[getl + putl], + msize - sizeof(struct GNUNET_PeerIdentity) * (putl + getl)); + } } @@ -624,19 +613,19 @@ handle_monitor_get_resp (void *cls, * #GNUNET_SYSERR if the message is malformed. */ static int -check_monitor_put (void *cls, - const struct GNUNET_DHT_MonitorPutMessage *msg) +check_monitor_put(void *cls, + const struct GNUNET_DHT_MonitorPutMessage *msg) { size_t msize; uint32_t putl; - msize = ntohs (msg->header.size) - sizeof (*msg); - putl = ntohl (msg->put_path_length); - if ((msize / sizeof (struct GNUNET_PeerIdentity)) < putl) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + msize = ntohs(msg->header.size) - sizeof(*msg); + putl = ntohl(msg->put_path_length); + if ((msize / sizeof(struct GNUNET_PeerIdentity)) < putl) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -648,38 +637,38 @@ check_monitor_put (void *cls, * @param msg Monitor put message from the service. */ static void -handle_monitor_put (void *cls, - const struct GNUNET_DHT_MonitorPutMessage *msg) +handle_monitor_put(void *cls, + const struct GNUNET_DHT_MonitorPutMessage *msg) { struct GNUNET_DHT_Handle *handle = cls; - size_t msize = ntohs (msg->header.size) - sizeof (*msg); - uint32_t putl = ntohl (msg->put_path_length); + size_t msize = ntohs(msg->header.size) - sizeof(*msg); + uint32_t putl = ntohl(msg->put_path_length); const struct GNUNET_PeerIdentity *path; struct GNUNET_DHT_MonitorHandle *mh; - path = (const struct GNUNET_PeerIdentity *) &msg[1]; + path = (const struct GNUNET_PeerIdentity *)&msg[1]; for (mh = handle->monitor_head; NULL != mh; mh = mh->next) - { - if (NULL == mh->put_cb) - continue; - if ( ( (GNUNET_BLOCK_TYPE_ANY == mh->type) || - (mh->type == ntohl(msg->type)) ) && - ( (NULL == mh->key) || - (0 == memcmp (mh->key, - &msg->key, - sizeof (struct GNUNET_HashCode))) ) ) - mh->put_cb (mh->cb_cls, - ntohl (msg->options), - (enum GNUNET_BLOCK_Type) ntohl(msg->type), - ntohl (msg->hop_count), - ntohl (msg->desired_replication_level), - putl, - path, - GNUNET_TIME_absolute_ntoh(msg->expiration_time), - &msg->key, - (const void *) &path[putl], - msize - sizeof (struct GNUNET_PeerIdentity) * putl); - } + { + if (NULL == mh->put_cb) + continue; + if (((GNUNET_BLOCK_TYPE_ANY == mh->type) || + (mh->type == ntohl(msg->type))) && + ((NULL == mh->key) || + (0 == memcmp(mh->key, + &msg->key, + sizeof(struct GNUNET_HashCode))))) + mh->put_cb(mh->cb_cls, + ntohl(msg->options), + (enum GNUNET_BLOCK_Type)ntohl(msg->type), + ntohl(msg->hop_count), + ntohl(msg->desired_replication_level), + putl, + path, + GNUNET_TIME_absolute_ntoh(msg->expiration_time), + &msg->key, + (const void *)&path[putl], + msize - sizeof(struct GNUNET_PeerIdentity) * putl); + } } @@ -692,25 +681,25 @@ handle_monitor_put (void *cls, * #GNUNET_SYSERR if the message is malformed. */ static int -check_client_result (void *cls, - const struct GNUNET_DHT_ClientResultMessage *msg) +check_client_result(void *cls, + const struct GNUNET_DHT_ClientResultMessage *msg) { - size_t msize = ntohs (msg->header.size) - sizeof (*msg); - uint32_t put_path_length = ntohl (msg->put_path_length); - uint32_t get_path_length = ntohl (msg->get_path_length); + size_t msize = ntohs(msg->header.size) - sizeof(*msg); + uint32_t put_path_length = ntohl(msg->put_path_length); + uint32_t get_path_length = ntohl(msg->get_path_length); size_t meta_length; meta_length = - sizeof (struct GNUNET_PeerIdentity) * (get_path_length + put_path_length); - if ( (msize < meta_length) || - (get_path_length > - GNUNET_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) || - (put_path_length > - GNUNET_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + sizeof(struct GNUNET_PeerIdentity) * (get_path_length + put_path_length); + if ((msize < meta_length) || + (get_path_length > + GNUNET_MAX_MESSAGE_SIZE / sizeof(struct GNUNET_PeerIdentity)) || + (put_path_length > + GNUNET_MAX_MESSAGE_SIZE / sizeof(struct GNUNET_PeerIdentity))) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -724,15 +713,15 @@ check_client_result (void *cls, * @return #GNUNET_YES to continue to iterate over all results */ static int -process_client_result (void *cls, - const struct GNUNET_HashCode *key, - void *value) +process_client_result(void *cls, + const struct GNUNET_HashCode *key, + void *value) { const struct GNUNET_DHT_ClientResultMessage *crm = cls; struct GNUNET_DHT_GetHandle *get_handle = value; - size_t msize = ntohs (crm->header.size) - sizeof (*crm); - uint32_t put_path_length = ntohl (crm->put_path_length); - uint32_t get_path_length = ntohl (crm->get_path_length); + size_t msize = ntohs(crm->header.size) - sizeof(*crm); + uint32_t put_path_length = ntohl(crm->put_path_length); + uint32_t get_path_length = ntohl(crm->get_path_length); const struct GNUNET_PeerIdentity *put_path; const struct GNUNET_PeerIdentity *get_path; struct GNUNET_HashCode hc; @@ -741,59 +730,59 @@ process_client_result (void *cls, const void *data; if (crm->unique_id != get_handle->unique_id) - { - /* UID mismatch */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ignoring reply for %s: UID mismatch: %llu/%llu\n", - GNUNET_h2s (key), - crm->unique_id, - get_handle->unique_id); - return GNUNET_YES; - } + { + /* UID mismatch */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ignoring reply for %s: UID mismatch: %llu/%llu\n", + GNUNET_h2s(key), + crm->unique_id, + get_handle->unique_id); + return GNUNET_YES; + } /* FIXME: might want to check that type matches */ meta_length = - sizeof (struct GNUNET_PeerIdentity) * (get_path_length + put_path_length); + sizeof(struct GNUNET_PeerIdentity) * (get_path_length + put_path_length); data_length = msize - meta_length; - put_path = (const struct GNUNET_PeerIdentity *) &crm[1]; + put_path = (const struct GNUNET_PeerIdentity *)&crm[1]; get_path = &put_path[put_path_length]; { char *pp; char *gp; - gp = GNUNET_STRINGS_pp2s (get_path, - get_path_length); - pp = GNUNET_STRINGS_pp2s (put_path, - put_path_length); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Giving %u byte reply for %s to application (GP: %s, PP: %s)\n", - (unsigned int) data_length, - GNUNET_h2s (key), - gp, - pp); - GNUNET_free (gp); - GNUNET_free (pp); + gp = GNUNET_STRINGS_pp2s(get_path, + get_path_length); + pp = GNUNET_STRINGS_pp2s(put_path, + put_path_length); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Giving %u byte reply for %s to application (GP: %s, PP: %s)\n", + (unsigned int)data_length, + GNUNET_h2s(key), + gp, + pp); + GNUNET_free(gp); + GNUNET_free(pp); } data = &get_path[get_path_length]; /* remember that we've seen this result */ - GNUNET_CRYPTO_hash (data, - data_length, - &hc); + GNUNET_CRYPTO_hash(data, + data_length, + &hc); if (get_handle->seen_results_size == get_handle->seen_results_end) - GNUNET_array_grow (get_handle->seen_results, - get_handle->seen_results_size, - get_handle->seen_results_size * 2 + 1); + GNUNET_array_grow(get_handle->seen_results, + get_handle->seen_results_size, + get_handle->seen_results_size * 2 + 1); get_handle->seen_results[get_handle->seen_results_end++] = hc; /* no need to block it explicitly, service already knows about it! */ - get_handle->iter (get_handle->iter_cls, - GNUNET_TIME_absolute_ntoh (crm->expiration), - key, - get_path, - get_path_length, - put_path, - put_path_length, - ntohl (crm->type), - data_length, - data); + get_handle->iter(get_handle->iter_cls, + GNUNET_TIME_absolute_ntoh(crm->expiration), + key, + get_path, + get_path_length, + put_path, + put_path_length, + ntohl(crm->type), + data_length, + data); return GNUNET_YES; } @@ -805,15 +794,15 @@ process_client_result (void *cls, * @param msg Monitor put message from the service. */ static void -handle_client_result (void *cls, - const struct GNUNET_DHT_ClientResultMessage *msg) +handle_client_result(void *cls, + const struct GNUNET_DHT_ClientResultMessage *msg) { struct GNUNET_DHT_Handle *handle = cls; - GNUNET_CONTAINER_multihashmap_get_multiple (handle->active_requests, - &msg->key, - &process_client_result, - (void *) msg); + GNUNET_CONTAINER_multihashmap_get_multiple(handle->active_requests, + &msg->key, + &process_client_result, + (void *)msg); } @@ -823,7 +812,7 @@ handle_client_result (void *cls, * @param cls The DHT handle. */ static void -handle_put_cont (void *cls) +handle_put_cont(void *cls) { struct GNUNET_DHT_PutHandle *ph = cls; GNUNET_SCHEDULER_TaskCallback cont; @@ -832,9 +821,9 @@ handle_put_cont (void *cls) cont = ph->cont; cont_cls = ph->cont_cls; ph->env = NULL; - GNUNET_DHT_put_cancel (ph); + GNUNET_DHT_put_cancel(ph); if (NULL != cont) - cont (cont_cls); + cont(cont_cls); } @@ -845,40 +834,41 @@ handle_put_cont (void *cls) * @return #GNUNET_YES on success, #GNUNET_NO on failure. */ static int -try_connect (struct GNUNET_DHT_Handle *h) +try_connect(struct GNUNET_DHT_Handle *h) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (monitor_get, - GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET, - struct GNUNET_DHT_MonitorGetMessage, - h), - GNUNET_MQ_hd_var_size (monitor_get_resp, - GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET_RESP, - struct GNUNET_DHT_MonitorGetRespMessage, - h), - GNUNET_MQ_hd_var_size (monitor_put, - GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT, - struct GNUNET_DHT_MonitorPutMessage, - h), - GNUNET_MQ_hd_var_size (client_result, - GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT, - struct GNUNET_DHT_ClientResultMessage, - h), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(monitor_get, + GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET, + struct GNUNET_DHT_MonitorGetMessage, + h), + GNUNET_MQ_hd_var_size(monitor_get_resp, + GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET_RESP, + struct GNUNET_DHT_MonitorGetRespMessage, + h), + GNUNET_MQ_hd_var_size(monitor_put, + GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT, + struct GNUNET_DHT_MonitorPutMessage, + h), + GNUNET_MQ_hd_var_size(client_result, + GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT, + struct GNUNET_DHT_ClientResultMessage, + h), + GNUNET_MQ_handler_end() }; + if (NULL != h->mq) return GNUNET_OK; - h->mq = GNUNET_CLIENT_connect (h->cfg, - "dht", - handlers, - &mq_error_handler, - h); + h->mq = GNUNET_CLIENT_connect(h->cfg, + "dht", + handlers, + &mq_error_handler, + h); if (NULL == h->mq) - { - LOG (GNUNET_ERROR_TYPE_WARNING, - "Failed to connect to the DHT service!\n"); - return GNUNET_NO; - } + { + LOG(GNUNET_ERROR_TYPE_WARNING, + "Failed to connect to the DHT service!\n"); + return GNUNET_NO; + } return GNUNET_YES; } @@ -892,24 +882,24 @@ try_connect (struct GNUNET_DHT_Handle *h) * @return handle to the DHT service, or NULL on error */ struct GNUNET_DHT_Handle * -GNUNET_DHT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - unsigned int ht_len) +GNUNET_DHT_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + unsigned int ht_len) { struct GNUNET_DHT_Handle *handle; - handle = GNUNET_new (struct GNUNET_DHT_Handle); + handle = GNUNET_new(struct GNUNET_DHT_Handle); handle->cfg = cfg; handle->uid_gen - = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT64_MAX); + = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, + UINT64_MAX); handle->active_requests - = GNUNET_CONTAINER_multihashmap_create (ht_len, - GNUNET_YES); - if (GNUNET_NO == try_connect (handle)) - { - GNUNET_DHT_disconnect (handle); - return NULL; - } + = GNUNET_CONTAINER_multihashmap_create(ht_len, + GNUNET_YES); + if (GNUNET_NO == try_connect(handle)) + { + GNUNET_DHT_disconnect(handle); + return NULL; + } return handle; } @@ -920,30 +910,30 @@ GNUNET_DHT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param handle handle of the DHT connection to stop */ void -GNUNET_DHT_disconnect (struct GNUNET_DHT_Handle *handle) +GNUNET_DHT_disconnect(struct GNUNET_DHT_Handle *handle) { struct GNUNET_DHT_PutHandle *ph; - GNUNET_assert (0 == - GNUNET_CONTAINER_multihashmap_size (handle->active_requests)); + GNUNET_assert(0 == + GNUNET_CONTAINER_multihashmap_size(handle->active_requests)); while (NULL != (ph = handle->put_head)) - { - if (NULL != ph->cont) - ph->cont (ph->cont_cls); - GNUNET_DHT_put_cancel (ph); - } + { + if (NULL != ph->cont) + ph->cont(ph->cont_cls); + GNUNET_DHT_put_cancel(ph); + } if (NULL != handle->mq) - { - GNUNET_MQ_destroy (handle->mq); - handle->mq = NULL; - } + { + GNUNET_MQ_destroy(handle->mq); + handle->mq = NULL; + } if (NULL != handle->reconnect_task) - { - GNUNET_SCHEDULER_cancel (handle->reconnect_task); - handle->reconnect_task = NULL; - } - GNUNET_CONTAINER_multihashmap_destroy (handle->active_requests); - GNUNET_free (handle); + { + GNUNET_SCHEDULER_cancel(handle->reconnect_task); + handle->reconnect_task = NULL; + } + GNUNET_CONTAINER_multihashmap_destroy(handle->active_requests); + GNUNET_free(handle); } @@ -968,59 +958,59 @@ GNUNET_DHT_disconnect (struct GNUNET_DHT_Handle *handle) * @param cont_cls closure for @a cont */ struct GNUNET_DHT_PutHandle * -GNUNET_DHT_put (struct GNUNET_DHT_Handle *handle, - const struct GNUNET_HashCode *key, - uint32_t desired_replication_level, - enum GNUNET_DHT_RouteOption options, - enum GNUNET_BLOCK_Type type, - size_t size, - const void *data, - struct GNUNET_TIME_Absolute exp, - GNUNET_SCHEDULER_TaskCallback cont, - void *cont_cls) +GNUNET_DHT_put(struct GNUNET_DHT_Handle *handle, + const struct GNUNET_HashCode *key, + uint32_t desired_replication_level, + enum GNUNET_DHT_RouteOption options, + enum GNUNET_BLOCK_Type type, + size_t size, + const void *data, + struct GNUNET_TIME_Absolute exp, + GNUNET_SCHEDULER_TaskCallback cont, + void *cont_cls) { struct GNUNET_MQ_Envelope *env; struct GNUNET_DHT_ClientPutMessage *put_msg; size_t msize; struct GNUNET_DHT_PutHandle *ph; - msize = sizeof (struct GNUNET_DHT_ClientPutMessage) + size; + msize = sizeof(struct GNUNET_DHT_ClientPutMessage) + size; if ((msize >= GNUNET_MAX_MESSAGE_SIZE) || (size >= GNUNET_MAX_MESSAGE_SIZE)) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } if (NULL == handle->mq) return NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending PUT for %s to DHT via %p\n", - GNUNET_h2s (key), - handle); - ph = GNUNET_new (struct GNUNET_DHT_PutHandle); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending PUT for %s to DHT via %p\n", + GNUNET_h2s(key), + handle); + ph = GNUNET_new(struct GNUNET_DHT_PutHandle); ph->dht_handle = handle; ph->cont = cont; ph->cont_cls = cont_cls; - GNUNET_CONTAINER_DLL_insert_tail (handle->put_head, - handle->put_tail, - ph); - env = GNUNET_MQ_msg_extra (put_msg, - size, - GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT); - GNUNET_MQ_notify_sent (env, - &handle_put_cont, - ph); + GNUNET_CONTAINER_DLL_insert_tail(handle->put_head, + handle->put_tail, + ph); + env = GNUNET_MQ_msg_extra(put_msg, + size, + GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT); + GNUNET_MQ_notify_sent(env, + &handle_put_cont, + ph); ph->env = env; - put_msg->type = htonl ((uint32_t) type); - put_msg->options = htonl ((uint32_t) options); - put_msg->desired_replication_level = htonl (desired_replication_level); - put_msg->expiration = GNUNET_TIME_absolute_hton (exp); + put_msg->type = htonl((uint32_t)type); + put_msg->options = htonl((uint32_t)options); + put_msg->desired_replication_level = htonl(desired_replication_level); + put_msg->expiration = GNUNET_TIME_absolute_hton(exp); put_msg->key = *key; - GNUNET_memcpy (&put_msg[1], - data, - size); - GNUNET_MQ_send (handle->mq, - env); + GNUNET_memcpy(&put_msg[1], + data, + size); + GNUNET_MQ_send(handle->mq, + env); return ph; } @@ -1037,18 +1027,18 @@ GNUNET_DHT_put (struct GNUNET_DHT_Handle *handle, * @param ph put operation to cancel ('cont' will no longer be called) */ void -GNUNET_DHT_put_cancel (struct GNUNET_DHT_PutHandle *ph) +GNUNET_DHT_put_cancel(struct GNUNET_DHT_PutHandle *ph) { struct GNUNET_DHT_Handle *handle = ph->dht_handle; if (NULL != ph->env) - GNUNET_MQ_notify_sent (ph->env, - NULL, - NULL); - GNUNET_CONTAINER_DLL_remove (handle->put_head, - handle->put_tail, - ph); - GNUNET_free (ph); + GNUNET_MQ_notify_sent(ph->env, + NULL, + NULL); + GNUNET_CONTAINER_DLL_remove(handle->put_head, + handle->put_tail, + ph); + GNUNET_free(ph); } @@ -1069,32 +1059,32 @@ GNUNET_DHT_put_cancel (struct GNUNET_DHT_PutHandle *ph) * @return handle to stop the async get */ struct GNUNET_DHT_GetHandle * -GNUNET_DHT_get_start (struct GNUNET_DHT_Handle *handle, - enum GNUNET_BLOCK_Type type, - const struct GNUNET_HashCode *key, - uint32_t desired_replication_level, - enum GNUNET_DHT_RouteOption options, - const void *xquery, - size_t xquery_size, - GNUNET_DHT_GetIterator iter, - void *iter_cls) +GNUNET_DHT_get_start(struct GNUNET_DHT_Handle *handle, + enum GNUNET_BLOCK_Type type, + const struct GNUNET_HashCode *key, + uint32_t desired_replication_level, + enum GNUNET_DHT_RouteOption options, + const void *xquery, + size_t xquery_size, + GNUNET_DHT_GetIterator iter, + void *iter_cls) { struct GNUNET_DHT_GetHandle *gh; size_t msize; - msize = sizeof (struct GNUNET_DHT_ClientGetMessage) + xquery_size; + msize = sizeof(struct GNUNET_DHT_ClientGetMessage) + xquery_size; if ((msize >= GNUNET_MAX_MESSAGE_SIZE) || (xquery_size >= GNUNET_MAX_MESSAGE_SIZE)) - { - GNUNET_break (0); - return NULL; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending query for %s to DHT %p\n", - GNUNET_h2s (key), - handle); - gh = GNUNET_malloc (sizeof (struct GNUNET_DHT_GetHandle) + - xquery_size); + { + GNUNET_break(0); + return NULL; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending query for %s to DHT %p\n", + GNUNET_h2s(key), + handle); + gh = GNUNET_malloc(sizeof(struct GNUNET_DHT_GetHandle) + + xquery_size); gh->iter = iter; gh->iter_cls = iter_cls; gh->dht_handle = handle; @@ -1104,15 +1094,15 @@ GNUNET_DHT_get_start (struct GNUNET_DHT_Handle *handle, gh->desired_replication_level = desired_replication_level; gh->type = type; gh->options = options; - GNUNET_memcpy (&gh[1], - xquery, - xquery_size); - GNUNET_CONTAINER_multihashmap_put (handle->active_requests, - &gh->key, - gh, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + GNUNET_memcpy(&gh[1], + xquery, + xquery_size); + GNUNET_CONTAINER_multihashmap_put(handle->active_requests, + &gh->key, + gh, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); if (NULL != handle->mq) - send_get (gh); + send_get(gh); return gh; } @@ -1128,9 +1118,9 @@ GNUNET_DHT_get_start (struct GNUNET_DHT_Handle *handle, * to be blocked */ void -GNUNET_DHT_get_filter_known_results (struct GNUNET_DHT_GetHandle *get_handle, - unsigned int num_results, - const struct GNUNET_HashCode *results) +GNUNET_DHT_get_filter_known_results(struct GNUNET_DHT_GetHandle *get_handle, + unsigned int num_results, + const struct GNUNET_HashCode *results) { unsigned int needed; unsigned int had; @@ -1138,16 +1128,16 @@ GNUNET_DHT_get_filter_known_results (struct GNUNET_DHT_GetHandle *get_handle, had = get_handle->seen_results_end; needed = had + num_results; if (needed > get_handle->seen_results_size) - GNUNET_array_grow (get_handle->seen_results, - get_handle->seen_results_size, - needed); - GNUNET_memcpy (&get_handle->seen_results[get_handle->seen_results_end], - results, - num_results * sizeof (struct GNUNET_HashCode)); + GNUNET_array_grow(get_handle->seen_results, + get_handle->seen_results_size, + needed); + GNUNET_memcpy(&get_handle->seen_results[get_handle->seen_results_end], + results, + num_results * sizeof(struct GNUNET_HashCode)); get_handle->seen_results_end += num_results; if (NULL != get_handle->dht_handle->mq) - send_get_known_results (get_handle, - had); + send_get_known_results(get_handle, + had); } @@ -1157,35 +1147,35 @@ GNUNET_DHT_get_filter_known_results (struct GNUNET_DHT_GetHandle *get_handle, * @param get_handle handle to the GET operation to stop */ void -GNUNET_DHT_get_stop (struct GNUNET_DHT_GetHandle *get_handle) +GNUNET_DHT_get_stop(struct GNUNET_DHT_GetHandle *get_handle) { struct GNUNET_DHT_Handle *handle = get_handle->dht_handle; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending STOP for %s to DHT via %p\n", - GNUNET_h2s (&get_handle->key), - handle); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending STOP for %s to DHT via %p\n", + GNUNET_h2s(&get_handle->key), + handle); if (NULL != handle->mq) - { - struct GNUNET_MQ_Envelope *env; - struct GNUNET_DHT_ClientGetStopMessage *stop_msg; - - env = GNUNET_MQ_msg (stop_msg, - GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP); - stop_msg->reserved = htonl (0); - stop_msg->unique_id = get_handle->unique_id; - stop_msg->key = get_handle->key; - GNUNET_MQ_send (handle->mq, - env); - } - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (handle->active_requests, - &get_handle->key, - get_handle)); - GNUNET_array_grow (get_handle->seen_results, - get_handle->seen_results_end, - 0); - GNUNET_free (get_handle); + { + struct GNUNET_MQ_Envelope *env; + struct GNUNET_DHT_ClientGetStopMessage *stop_msg; + + env = GNUNET_MQ_msg(stop_msg, + GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP); + stop_msg->reserved = htonl(0); + stop_msg->unique_id = get_handle->unique_id; + stop_msg->key = get_handle->key; + GNUNET_MQ_send(handle->mq, + env); + } + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(handle->active_requests, + &get_handle->key, + get_handle)); + GNUNET_array_grow(get_handle->seen_results, + get_handle->seen_results_end, + 0); + GNUNET_free(get_handle); } @@ -1202,17 +1192,17 @@ GNUNET_DHT_get_stop (struct GNUNET_DHT_GetHandle *get_handle) * @return Handle to stop monitoring. */ struct GNUNET_DHT_MonitorHandle * -GNUNET_DHT_monitor_start (struct GNUNET_DHT_Handle *handle, - enum GNUNET_BLOCK_Type type, - const struct GNUNET_HashCode *key, - GNUNET_DHT_MonitorGetCB get_cb, - GNUNET_DHT_MonitorGetRespCB get_resp_cb, - GNUNET_DHT_MonitorPutCB put_cb, - void *cb_cls) +GNUNET_DHT_monitor_start(struct GNUNET_DHT_Handle *handle, + enum GNUNET_BLOCK_Type type, + const struct GNUNET_HashCode *key, + GNUNET_DHT_MonitorGetCB get_cb, + GNUNET_DHT_MonitorGetRespCB get_resp_cb, + GNUNET_DHT_MonitorPutCB put_cb, + void *cb_cls) { struct GNUNET_DHT_MonitorHandle *mh; - mh = GNUNET_new (struct GNUNET_DHT_MonitorHandle); + mh = GNUNET_new(struct GNUNET_DHT_MonitorHandle); mh->get_cb = get_cb; mh->get_resp_cb = get_resp_cb; mh->put_cb = put_cb; @@ -1220,15 +1210,15 @@ GNUNET_DHT_monitor_start (struct GNUNET_DHT_Handle *handle, mh->type = type; mh->dht_handle = handle; if (NULL != key) - { - mh->key = GNUNET_new (struct GNUNET_HashCode); - *mh->key = *key; - } - GNUNET_CONTAINER_DLL_insert (handle->monitor_head, - handle->monitor_tail, - mh); + { + mh->key = GNUNET_new(struct GNUNET_HashCode); + *mh->key = *key; + } + GNUNET_CONTAINER_DLL_insert(handle->monitor_head, + handle->monitor_tail, + mh); if (NULL != handle->mq) - send_monitor_start (mh); + send_monitor_start(mh); return mh; } @@ -1241,30 +1231,30 @@ GNUNET_DHT_monitor_start (struct GNUNET_DHT_Handle *handle, * On return get_handle will no longer be valid, caller must not use again!!! */ void -GNUNET_DHT_monitor_stop (struct GNUNET_DHT_MonitorHandle *mh) +GNUNET_DHT_monitor_stop(struct GNUNET_DHT_MonitorHandle *mh) { struct GNUNET_DHT_Handle *handle = mh->dht_handle; struct GNUNET_DHT_MonitorStartStopMessage *m; struct GNUNET_MQ_Envelope *env; - GNUNET_CONTAINER_DLL_remove (handle->monitor_head, - handle->monitor_tail, - mh); - env = GNUNET_MQ_msg (m, - GNUNET_MESSAGE_TYPE_DHT_MONITOR_STOP); - m->type = htonl (mh->type); - m->get = htons (NULL != mh->get_cb); + GNUNET_CONTAINER_DLL_remove(handle->monitor_head, + handle->monitor_tail, + mh); + env = GNUNET_MQ_msg(m, + GNUNET_MESSAGE_TYPE_DHT_MONITOR_STOP); + m->type = htonl(mh->type); + m->get = htons(NULL != mh->get_cb); m->get_resp = htons(NULL != mh->get_resp_cb); - m->put = htons (NULL != mh->put_cb); + m->put = htons(NULL != mh->put_cb); if (NULL != mh->key) - { - m->filter_key = htons (1); - m->key = *mh->key; - } - GNUNET_MQ_send (handle->mq, - env); - GNUNET_free_non_null (mh->key); - GNUNET_free (mh); + { + m->filter_key = htons(1); + m->key = *mh->key; + } + GNUNET_MQ_send(handle->mq, + env); + GNUNET_free_non_null(mh->key); + GNUNET_free(mh); } diff --git a/src/dht/dht_test_lib.c b/src/dht/dht_test_lib.c index b4afa3516..8ce3e98ea 100644 --- a/src/dht/dht_test_lib.c +++ b/src/dht/dht_test_lib.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/dht_test_lib.c * @author Christian Grothoff @@ -28,8 +28,7 @@ /** * Test context for a DHT Test. */ -struct GNUNET_DHT_TEST_Context -{ +struct GNUNET_DHT_TEST_Context { /** * Array of running peers. */ @@ -59,7 +58,6 @@ struct GNUNET_DHT_TEST_Context * Number of peers running, size of the arrays above. */ unsigned int num_peers; - }; @@ -74,10 +72,10 @@ struct GNUNET_DHT_TEST_Context * @return service handle to return in 'op_result', NULL on error */ static void * -dht_connect_adapter (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +dht_connect_adapter(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - return GNUNET_DHT_connect (cfg, 16); + return GNUNET_DHT_connect(cfg, 16); } @@ -89,12 +87,12 @@ dht_connect_adapter (void *cls, * @param op_result service handle returned from the connect adapter */ static void -dht_disconnect_adapter (void *cls, - void *op_result) +dht_disconnect_adapter(void *cls, + void *op_result) { struct GNUNET_DHT_Handle *dht = op_result; - GNUNET_DHT_disconnect (dht); + GNUNET_DHT_disconnect(dht); } @@ -108,33 +106,34 @@ dht_disconnect_adapter (void *cls, * operation has executed successfully. */ static void -dht_connect_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg) +dht_connect_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg) { struct GNUNET_DHT_TEST_Context *ctx = cls; if (NULL != emsg) - { - fprintf (stderr, - "Failed to connect to DHT service: %s\n", - emsg); - GNUNET_SCHEDULER_shutdown (); - return; - } - for (unsigned int i=0;inum_peers;i++) + { + fprintf(stderr, + "Failed to connect to DHT service: %s\n", + emsg); + GNUNET_SCHEDULER_shutdown(); + return; + } + for (unsigned int i = 0; i < ctx->num_peers; i++) if (op == ctx->ops[i]) ctx->dhts[i] = ca_result; - for (unsigned int i=0;inum_peers;i++) + for (unsigned int i = 0; i < ctx->num_peers; i++) if (NULL == ctx->dhts[i]) - return; /* still some DHT connections missing */ + return; + /* still some DHT connections missing */ /* all DHT connections ready! */ - ctx->app_main (ctx->app_main_cls, - ctx, - ctx->num_peers, - ctx->peers, - ctx->dhts); + ctx->app_main(ctx->app_main_cls, + ctx, + ctx->num_peers, + ctx->peers, + ctx->dhts); } @@ -144,38 +143,38 @@ dht_connect_cb (void *cls, * @param ctx handle for the testbed */ void -GNUNET_DHT_TEST_cleanup (struct GNUNET_DHT_TEST_Context *ctx) +GNUNET_DHT_TEST_cleanup(struct GNUNET_DHT_TEST_Context *ctx) { - for (unsigned int i=0;inum_peers;i++) - GNUNET_TESTBED_operation_done (ctx->ops[i]); - GNUNET_free (ctx->ops); - GNUNET_free (ctx->dhts); - GNUNET_free (ctx); - GNUNET_SCHEDULER_shutdown (); + for (unsigned int i = 0; i < ctx->num_peers; i++) + GNUNET_TESTBED_operation_done(ctx->ops[i]); + GNUNET_free(ctx->ops); + GNUNET_free(ctx->dhts); + GNUNET_free(ctx); + GNUNET_SCHEDULER_shutdown(); } static void -dht_test_run (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - unsigned int links_succeeded, - unsigned int links_failed) +dht_test_run(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + unsigned int links_succeeded, + unsigned int links_failed) { struct GNUNET_DHT_TEST_Context *ctx = cls; - GNUNET_assert (num_peers == ctx->num_peers); + GNUNET_assert(num_peers == ctx->num_peers); ctx->peers = peers; - for (unsigned int i=0;iops[i] = GNUNET_TESTBED_service_connect (ctx, - peers[i], - "dht", - &dht_connect_cb, - ctx, - &dht_connect_adapter, - &dht_disconnect_adapter, - ctx); + for (unsigned int i = 0; i < num_peers; i++) + ctx->ops[i] = GNUNET_TESTBED_service_connect(ctx, + peers[i], + "dht", + &dht_connect_cb, + ctx, + &dht_connect_adapter, + &dht_disconnect_adapter, + ctx); } @@ -190,27 +189,27 @@ dht_test_run (void *cls, * @param tmain_cls closure for 'tmain' */ void -GNUNET_DHT_TEST_run (const char *testname, - const char *cfgname, - unsigned int num_peers, - GNUNET_DHT_TEST_AppMain tmain, - void *tmain_cls) +GNUNET_DHT_TEST_run(const char *testname, + const char *cfgname, + unsigned int num_peers, + GNUNET_DHT_TEST_AppMain tmain, + void *tmain_cls) { struct GNUNET_DHT_TEST_Context *ctx; - ctx = GNUNET_new (struct GNUNET_DHT_TEST_Context); + ctx = GNUNET_new(struct GNUNET_DHT_TEST_Context); ctx->num_peers = num_peers; - ctx->ops = GNUNET_new_array (num_peers, - struct GNUNET_TESTBED_Operation *); - ctx->dhts = GNUNET_new_array (num_peers, - struct GNUNET_DHT_Handle *); + ctx->ops = GNUNET_new_array(num_peers, + struct GNUNET_TESTBED_Operation *); + ctx->dhts = GNUNET_new_array(num_peers, + struct GNUNET_DHT_Handle *); ctx->app_main = tmain; ctx->app_main_cls = tmain_cls; - (void) GNUNET_TESTBED_test_run (testname, - cfgname, - num_peers, - 0LL, NULL, NULL, - &dht_test_run, ctx); + (void)GNUNET_TESTBED_test_run(testname, + cfgname, + num_peers, + 0LL, NULL, NULL, + &dht_test_run, ctx); } /* end of dht_test_lib.c */ diff --git a/src/dht/dht_test_lib.h b/src/dht/dht_test_lib.h index c60cc7d1e..716daaacf 100644 --- a/src/dht/dht_test_lib.h +++ b/src/dht/dht_test_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/dht_test_lib.h * @author Christian Grothoff @@ -52,10 +52,10 @@ struct GNUNET_DHT_TEST_Context; * @param dhts handle to each of the DHTs of the peers */ typedef void (*GNUNET_DHT_TEST_AppMain) (void *cls, - struct GNUNET_DHT_TEST_Context *ctx, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - struct GNUNET_DHT_Handle **dhts); + struct GNUNET_DHT_TEST_Context *ctx, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + struct GNUNET_DHT_Handle **dhts); /** @@ -69,11 +69,11 @@ typedef void (*GNUNET_DHT_TEST_AppMain) (void *cls, * @param tmain_cls closure for 'tmain' */ void -GNUNET_DHT_TEST_run (const char *testname, - const char *cfgname, - unsigned int num_peers, - GNUNET_DHT_TEST_AppMain tmain, - void *tmain_cls); +GNUNET_DHT_TEST_run(const char *testname, + const char *cfgname, + unsigned int num_peers, + GNUNET_DHT_TEST_AppMain tmain, + void *tmain_cls); /** @@ -82,7 +82,7 @@ GNUNET_DHT_TEST_run (const char *testname, * @param ctx handle for the testbed */ void -GNUNET_DHT_TEST_cleanup (struct GNUNET_DHT_TEST_Context *ctx); +GNUNET_DHT_TEST_cleanup(struct GNUNET_DHT_TEST_Context *ctx); #if 0 /* keep Emacsens' auto-indent happy */ { diff --git a/src/dht/gnunet-dht-get.c b/src/dht/gnunet-dht-get.c index af667584b..901641660 100644 --- a/src/dht/gnunet-dht-get.c +++ b/src/dht/gnunet-dht-get.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-dht-get.c * @brief search for data in DHT @@ -26,7 +26,7 @@ #include "platform.h" #include "gnunet_dht_service.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "dht-clients", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "dht-clients", __VA_ARGS__) /** * The type of the query */ @@ -45,7 +45,7 @@ static char *query_key; /** * User supplied timeout value */ -static struct GNUNET_TIME_Relative timeout_request = {60000}; +static struct GNUNET_TIME_Relative timeout_request = { 60000 }; /** * Be verbose @@ -94,23 +94,23 @@ static struct GNUNET_SCHEDULER_Task *tt; * @param cls unused */ static void -cleanup_task (void *cls) +cleanup_task(void *cls) { if (NULL != get_handle) - { - GNUNET_DHT_get_stop (get_handle); - get_handle = NULL; - } + { + GNUNET_DHT_get_stop(get_handle); + get_handle = NULL; + } if (NULL != dht_handle) - { - GNUNET_DHT_disconnect (dht_handle); - dht_handle = NULL; - } + { + GNUNET_DHT_disconnect(dht_handle); + dht_handle = NULL; + } if (NULL != tt) - { - GNUNET_SCHEDULER_cancel (tt); - tt = NULL; - } + { + GNUNET_SCHEDULER_cancel(tt); + tt = NULL; + } } @@ -120,10 +120,10 @@ cleanup_task (void *cls) * @param cls unused */ static void -timeout_task (void *cls) +timeout_task(void *cls) { tt = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -143,34 +143,34 @@ timeout_task (void *cls) * @param data pointer to the result data */ static void -get_result_iterator (void *cls, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - enum GNUNET_BLOCK_Type type, - size_t size, - const void *data) +get_result_iterator(void *cls, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + enum GNUNET_BLOCK_Type type, + size_t size, + const void *data) { - fprintf (stdout, - (GNUNET_BLOCK_TYPE_TEST == type) ? _ ("Result %d, type %d:\n%.*s\n") - : _ ("Result %d, type %d:\n"), - result_count, - type, - (unsigned int) size, - (char *) data); + fprintf(stdout, + (GNUNET_BLOCK_TYPE_TEST == type) ? _("Result %d, type %d:\n%.*s\n") + : _("Result %d, type %d:\n"), + result_count, + type, + (unsigned int)size, + (char *)data); if (verbose) - { - fprintf (stdout, " GET path: "); - for (unsigned int i = 0; i < get_path_length; i++) - fprintf (stdout, "%s%s", (0 == i) ? "" : "-", GNUNET_i2s (&get_path[i])); - fprintf (stdout, "\n PUT path: "); - for (unsigned int i = 0; i < put_path_length; i++) - fprintf (stdout, "%s%s", (0 == i) ? "" : "-", GNUNET_i2s (&put_path[i])); - fprintf (stdout, "\n"); - } + { + fprintf(stdout, " GET path: "); + for (unsigned int i = 0; i < get_path_length; i++) + fprintf(stdout, "%s%s", (0 == i) ? "" : "-", GNUNET_i2s(&get_path[i])); + fprintf(stdout, "\n PUT path: "); + for (unsigned int i = 0; i < put_path_length; i++) + fprintf(stdout, "%s%s", (0 == i) ? "" : "-", GNUNET_i2s(&put_path[i])); + fprintf(stdout, "\n"); + } result_count++; } @@ -184,47 +184,47 @@ get_result_iterator (void *cls, * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { struct GNUNET_HashCode key; cfg = c; if (NULL == query_key) - { - fprintf (stderr, "%s", _ ("Must provide key for DHT GET!\n")); - ret = 1; - return; - } - if (NULL == (dht_handle = GNUNET_DHT_connect (cfg, 1))) - { - fprintf (stderr, "%s", _ ("Failed to connect to DHT service!\n")); - ret = 1; - return; - } + { + fprintf(stderr, "%s", _("Must provide key for DHT GET!\n")); + ret = 1; + return; + } + if (NULL == (dht_handle = GNUNET_DHT_connect(cfg, 1))) + { + fprintf(stderr, "%s", _("Failed to connect to DHT service!\n")); + ret = 1; + return; + } if (query_type == GNUNET_BLOCK_TYPE_ANY) /* Type of data not set */ query_type = GNUNET_BLOCK_TYPE_TEST; - GNUNET_CRYPTO_hash (query_key, strlen (query_key), &key); + GNUNET_CRYPTO_hash(query_key, strlen(query_key), &key); if (verbose) - fprintf (stderr, - "%s `%s' \n", - _ ("Issuing DHT GET with key"), - GNUNET_h2s_full (&key)); - GNUNET_SCHEDULER_add_shutdown (&cleanup_task, NULL); - tt = GNUNET_SCHEDULER_add_delayed (timeout_request, &timeout_task, NULL); - get_handle = GNUNET_DHT_get_start (dht_handle, - query_type, - &key, - replication, - (demultixplex_everywhere) - ? GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE - : GNUNET_DHT_RO_NONE, - NULL, - 0, - &get_result_iterator, - NULL); + fprintf(stderr, + "%s `%s' \n", + _("Issuing DHT GET with key"), + GNUNET_h2s_full(&key)); + GNUNET_SCHEDULER_add_shutdown(&cleanup_task, NULL); + tt = GNUNET_SCHEDULER_add_delayed(timeout_request, &timeout_task, NULL); + get_handle = GNUNET_DHT_get_start(dht_handle, + query_type, + &key, + replication, + (demultixplex_everywhere) + ? GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE + : GNUNET_DHT_RO_NONE, + NULL, + 0, + &get_result_iterator, + NULL); } @@ -236,54 +236,54 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_string ('k', - "key", - "KEY", - gettext_noop ("the query key"), - &query_key), - GNUNET_GETOPT_option_uint ( - 'r', - "replication", - "LEVEL", - gettext_noop ("how many parallel requests (replicas) to create"), - &replication), - GNUNET_GETOPT_option_uint ('t', - "type", - "TYPE", - gettext_noop ("the type of data to look for"), - &query_type), - GNUNET_GETOPT_option_relative_time ( - 'T', - "timeout", - "TIMEOUT", - gettext_noop ("how long to execute this query before giving up?"), - &timeout_request), - GNUNET_GETOPT_option_flag ('x', - "demultiplex", - gettext_noop ( - "use DHT's demultiplex everywhere option"), - &demultixplex_everywhere), - GNUNET_GETOPT_option_verbose (&verbose), - GNUNET_GETOPT_OPTION_END}; + { GNUNET_GETOPT_option_string('k', + "key", + "KEY", + gettext_noop("the query key"), + &query_key), + GNUNET_GETOPT_option_uint( + 'r', + "replication", + "LEVEL", + gettext_noop("how many parallel requests (replicas) to create"), + &replication), + GNUNET_GETOPT_option_uint('t', + "type", + "TYPE", + gettext_noop("the type of data to look for"), + &query_type), + GNUNET_GETOPT_option_relative_time( + 'T', + "timeout", + "TIMEOUT", + gettext_noop("how long to execute this query before giving up?"), + &timeout_request), + GNUNET_GETOPT_option_flag('x', + "demultiplex", + gettext_noop( + "use DHT's demultiplex everywhere option"), + &demultixplex_everywhere), + GNUNET_GETOPT_option_verbose(&verbose), + GNUNET_GETOPT_OPTION_END }; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; return (GNUNET_OK == - GNUNET_PROGRAM_run ( + GNUNET_PROGRAM_run( argc, argv, "gnunet-dht-get", - gettext_noop ( + gettext_noop( "Issue a GET request to the GNUnet DHT, prints results."), options, &run, NULL)) - ? ret - : 1; + ? ret + : 1; } /* end of gnunet-dht-get.c */ diff --git a/src/dht/gnunet-dht-monitor.c b/src/dht/gnunet-dht-monitor.c index 3787b7cfa..26989467c 100644 --- a/src/dht/gnunet-dht-monitor.c +++ b/src/dht/gnunet-dht-monitor.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-dht-monitor.c * @brief search for data in DHT @@ -39,7 +39,7 @@ static char *query_key; /** * User supplied timeout value (in seconds) */ -static struct GNUNET_TIME_Relative timeout_request = {60000}; +static struct GNUNET_TIME_Relative timeout_request = { 60000 }; /** * Be verbose @@ -47,7 +47,7 @@ static struct GNUNET_TIME_Relative timeout_request = {60000}; static int verbose; /** -* Handle to the DHT + * Handle to the DHT */ static struct GNUNET_DHT_Handle *dht_handle; @@ -83,25 +83,25 @@ static struct GNUNET_SCHEDULER_Task *tt; * @param cls closure (unused) */ static void -cleanup_task (void *cls) +cleanup_task(void *cls) { if (verbose) - fprintf (stderr, "%s", "Cleaning up!\n"); + fprintf(stderr, "%s", "Cleaning up!\n"); if (NULL != monitor_handle) - { - GNUNET_DHT_monitor_stop (monitor_handle); - monitor_handle = NULL; - } + { + GNUNET_DHT_monitor_stop(monitor_handle); + monitor_handle = NULL; + } if (NULL != dht_handle) - { - GNUNET_DHT_disconnect (dht_handle); - dht_handle = NULL; - } + { + GNUNET_DHT_disconnect(dht_handle); + dht_handle = NULL; + } if (NULL != tt) - { - GNUNET_SCHEDULER_cancel (tt); - tt = NULL; - } + { + GNUNET_SCHEDULER_cancel(tt); + tt = NULL; + } } @@ -111,10 +111,10 @@ cleanup_task (void *cls) * @param cls closure (unused) */ static void -timeout_task (void *cls) +timeout_task(void *cls) { tt = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -131,20 +131,20 @@ timeout_task (void *cls) * @param key Key of the requested data. */ static void -get_callback (void *cls, - enum GNUNET_DHT_RouteOption options, - enum GNUNET_BLOCK_Type type, - uint32_t hop_count, - uint32_t desired_replication_level, - unsigned int path_length, - const struct GNUNET_PeerIdentity *path, - const struct GNUNET_HashCode *key) +get_callback(void *cls, + enum GNUNET_DHT_RouteOption options, + enum GNUNET_BLOCK_Type type, + uint32_t hop_count, + uint32_t desired_replication_level, + unsigned int path_length, + const struct GNUNET_PeerIdentity *path, + const struct GNUNET_HashCode *key) { - fprintf (stdout, - "GET #%u: type %d, key `%s'\n", - result_count, - (int) type, - GNUNET_h2s_full (key)); + fprintf(stdout, + "GET #%u: type %d, key `%s'\n", + result_count, + (int)type, + GNUNET_h2s_full(key)); result_count++; } @@ -164,27 +164,27 @@ get_callback (void *cls, * @param size Number of bytes in data. */ static void -get_resp_callback (void *cls, - enum GNUNET_BLOCK_Type type, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const void *data, - size_t size) +get_resp_callback(void *cls, + enum GNUNET_BLOCK_Type type, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const void *data, + size_t size) { - fprintf (stdout, - (GNUNET_BLOCK_TYPE_TEST == type) - ? "RESPONSE #%u (%s): type %d, key `%s', data `%.*s'\n" - : "RESPONSE #%u (%s): type %d, key `%s'\n", - result_count, - GNUNET_STRINGS_absolute_time_to_string (exp), - (int) type, - GNUNET_h2s_full (key), - (unsigned int) size, - (char *) data); + fprintf(stdout, + (GNUNET_BLOCK_TYPE_TEST == type) + ? "RESPONSE #%u (%s): type %d, key `%s', data `%.*s'\n" + : "RESPONSE #%u (%s): type %d, key `%s'\n", + result_count, + GNUNET_STRINGS_absolute_time_to_string(exp), + (int)type, + GNUNET_h2s_full(key), + (unsigned int)size, + (char *)data); result_count++; } @@ -205,28 +205,28 @@ get_resp_callback (void *cls, * @param size Number of bytes in data. */ static void -put_callback (void *cls, - enum GNUNET_DHT_RouteOption options, - enum GNUNET_BLOCK_Type type, - uint32_t hop_count, - uint32_t desired_replication_level, - unsigned int path_length, - const struct GNUNET_PeerIdentity *path, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const void *data, - size_t size) +put_callback(void *cls, + enum GNUNET_DHT_RouteOption options, + enum GNUNET_BLOCK_Type type, + uint32_t hop_count, + uint32_t desired_replication_level, + unsigned int path_length, + const struct GNUNET_PeerIdentity *path, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const void *data, + size_t size) { - fprintf (stdout, - (GNUNET_BLOCK_TYPE_TEST == type) - ? "PUT %u (%s): type %d, key `%s', data `%.*s'\n" - : "PUT %u (%s): type %d, key `%s'\n", - result_count, - GNUNET_STRINGS_absolute_time_to_string (exp), - (int) type, - GNUNET_h2s_full (key), - (unsigned int) size, - (char *) data); + fprintf(stdout, + (GNUNET_BLOCK_TYPE_TEST == type) + ? "PUT %u (%s): type %d, key `%s', data `%.*s'\n" + : "PUT %u (%s): type %d, key `%s'\n", + result_count, + GNUNET_STRINGS_absolute_time_to_string(exp), + (int)type, + GNUNET_h2s_full(key), + (unsigned int)size, + (char *)data); result_count++; } @@ -240,48 +240,48 @@ put_callback (void *cls, * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { struct GNUNET_HashCode *key; struct GNUNET_HashCode hc; cfg = c; - if (NULL == (dht_handle = GNUNET_DHT_connect (cfg, 1))) - { - fprintf (stderr, "%s", _ ("Failed to connect to DHT service!\n")); - ret = 1; - return; - } + if (NULL == (dht_handle = GNUNET_DHT_connect(cfg, 1))) + { + fprintf(stderr, "%s", _("Failed to connect to DHT service!\n")); + ret = 1; + return; + } if (GNUNET_BLOCK_TYPE_ANY == block_type) /* Type of data not set */ block_type = GNUNET_BLOCK_TYPE_TEST; if (NULL != query_key) - { - key = &hc; - if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (query_key, key)) - GNUNET_CRYPTO_hash (query_key, strlen (query_key), key); - } + { + key = &hc; + if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string(query_key, key)) + GNUNET_CRYPTO_hash(query_key, strlen(query_key), key); + } else - { - key = NULL; - } + { + key = NULL; + } if (verbose) - fprintf (stderr, - "Monitoring for %s\n", - GNUNET_STRINGS_relative_time_to_string (timeout_request, - GNUNET_NO)); - tt = GNUNET_SCHEDULER_add_delayed (timeout_request, &timeout_task, NULL); - GNUNET_SCHEDULER_add_shutdown (&cleanup_task, NULL); - monitor_handle = GNUNET_DHT_monitor_start (dht_handle, - block_type, - key, - &get_callback, - &get_resp_callback, - &put_callback, - NULL); + fprintf(stderr, + "Monitoring for %s\n", + GNUNET_STRINGS_relative_time_to_string(timeout_request, + GNUNET_NO)); + tt = GNUNET_SCHEDULER_add_delayed(timeout_request, &timeout_task, NULL); + GNUNET_SCHEDULER_add_shutdown(&cleanup_task, NULL); + monitor_handle = GNUNET_DHT_monitor_start(dht_handle, + block_type, + key, + &get_callback, + &get_resp_callback, + &put_callback, + NULL); } /** @@ -292,52 +292,52 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { - - GNUNET_GETOPT_option_string ('k', - "key", - "KEY", - gettext_noop ("the query key"), - &query_key), - - GNUNET_GETOPT_option_uint ('t', - "type", - "TYPE", - gettext_noop ("the type of data to look for"), - &block_type), - - GNUNET_GETOPT_option_relative_time ( + GNUNET_GETOPT_option_string('k', + "key", + "KEY", + gettext_noop("the query key"), + &query_key), + + GNUNET_GETOPT_option_uint('t', + "type", + "TYPE", + gettext_noop("the type of data to look for"), + &block_type), + + GNUNET_GETOPT_option_relative_time( 'T', "timeout", "TIMEOUT", - gettext_noop ("how long should the monitor command run"), + gettext_noop("how long should the monitor command run"), &timeout_request), - GNUNET_GETOPT_option_flag ('V', - "verbose", - gettext_noop ( - "be verbose (print progress information)"), - &verbose), + GNUNET_GETOPT_option_flag('V', + "verbose", + gettext_noop( + "be verbose (print progress information)"), + &verbose), - GNUNET_GETOPT_OPTION_END}; + GNUNET_GETOPT_OPTION_END + }; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; return (GNUNET_OK == - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-dht-monitor", - gettext_noop ( - "Prints all packets that go through the DHT."), - options, - &run, - NULL)) - ? ret - : 1; + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-dht-monitor", + gettext_noop( + "Prints all packets that go through the DHT."), + options, + &run, + NULL)) + ? ret + : 1; } /* end of gnunet-dht-monitor.c */ diff --git a/src/dht/gnunet-dht-put.c b/src/dht/gnunet-dht-put.c index 0432dc4a0..330b2ac62 100644 --- a/src/dht/gnunet-dht-put.c +++ b/src/dht/gnunet-dht-put.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-dht-put.c * @brief search for data in DHT @@ -89,13 +89,13 @@ static char *data; static void -shutdown_task (void *cls) +shutdown_task(void *cls) { if (NULL != dht_handle) - { - GNUNET_DHT_disconnect (dht_handle); - dht_handle = NULL; - } + { + GNUNET_DHT_disconnect(dht_handle); + dht_handle = NULL; + } } @@ -105,9 +105,9 @@ shutdown_task (void *cls) * @param cls closure */ static void -message_sent_cont (void *cls) +message_sent_cont(void *cls) { - GNUNET_SCHEDULER_add_now (&shutdown_task, NULL); + GNUNET_SCHEDULER_add_now(&shutdown_task, NULL); } @@ -120,52 +120,52 @@ message_sent_cont (void *cls) * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { enum GNUNET_DHT_RouteOption ro; cfg = c; if ((NULL == query_key) || (NULL == data)) - { - fprintf (stderr, "%s", _ ("Must provide KEY and DATA for DHT put!\n")); - ret = 1; - return; - } - - if (NULL == (dht_handle = GNUNET_DHT_connect (cfg, 1))) - { - fprintf (stderr, _ ("Could not connect to DHT service!\n")); - ret = 1; - return; - } + { + fprintf(stderr, "%s", _("Must provide KEY and DATA for DHT put!\n")); + ret = 1; + return; + } + + if (NULL == (dht_handle = GNUNET_DHT_connect(cfg, 1))) + { + fprintf(stderr, _("Could not connect to DHT service!\n")); + ret = 1; + return; + } if (GNUNET_BLOCK_TYPE_ANY == query_type) /* Type of data not set */ query_type = GNUNET_BLOCK_TYPE_TEST; - GNUNET_CRYPTO_hash (query_key, strlen (query_key), &key); + GNUNET_CRYPTO_hash(query_key, strlen(query_key), &key); if (verbose) - fprintf (stderr, - _ ("Issuing put request for `%s' with data `%s'!\n"), - query_key, - data); + fprintf(stderr, + _("Issuing put request for `%s' with data `%s'!\n"), + query_key, + data); ro = GNUNET_DHT_RO_NONE; if (demultixplex_everywhere) ro |= GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE; if (record_route) ro |= GNUNET_DHT_RO_RECORD_ROUTE; - GNUNET_DHT_put (dht_handle, - &key, - replication, - ro, - query_type, - strlen (data), - data, - GNUNET_TIME_relative_to_absolute (expiration), - &message_sent_cont, - NULL); + GNUNET_DHT_put(dht_handle, + &key, + replication, + ro, + query_type, + strlen(data), + data, + GNUNET_TIME_relative_to_absolute(expiration), + &message_sent_cont, + NULL); } /** @@ -176,65 +176,64 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { - struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_string ('d', - "data", - "DATA", - gettext_noop ( - "the data to insert under the key"), - &data), - GNUNET_GETOPT_option_relative_time ( - 'e', - "expiration", - "EXPIRATION", - gettext_noop ("how long to store this entry in the dht (in seconds)"), - &expiration), - GNUNET_GETOPT_option_string ('k', - "key", - "KEY", - gettext_noop ("the query key"), - &query_key), - GNUNET_GETOPT_option_flag ('x', - "demultiplex", - gettext_noop ( - "use DHT's demultiplex everywhere option"), - &demultixplex_everywhere), - GNUNET_GETOPT_option_uint ('r', - "replication", - "LEVEL", - gettext_noop ("how many replicas to create"), - &replication), - GNUNET_GETOPT_option_flag ('R', - "record", - gettext_noop ("use DHT's record route option"), - &record_route), - GNUNET_GETOPT_option_uint ('t', - "type", - "TYPE", - gettext_noop ("the type to insert data as"), - &query_type), - GNUNET_GETOPT_option_verbose (&verbose), - GNUNET_GETOPT_OPTION_END}; - - - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + { GNUNET_GETOPT_option_string('d', + "data", + "DATA", + gettext_noop( + "the data to insert under the key"), + &data), + GNUNET_GETOPT_option_relative_time( + 'e', + "expiration", + "EXPIRATION", + gettext_noop("how long to store this entry in the dht (in seconds)"), + &expiration), + GNUNET_GETOPT_option_string('k', + "key", + "KEY", + gettext_noop("the query key"), + &query_key), + GNUNET_GETOPT_option_flag('x', + "demultiplex", + gettext_noop( + "use DHT's demultiplex everywhere option"), + &demultixplex_everywhere), + GNUNET_GETOPT_option_uint('r', + "replication", + "LEVEL", + gettext_noop("how many replicas to create"), + &replication), + GNUNET_GETOPT_option_flag('R', + "record", + gettext_noop("use DHT's record route option"), + &record_route), + GNUNET_GETOPT_option_uint('t', + "type", + "TYPE", + gettext_noop("the type to insert data as"), + &query_type), + GNUNET_GETOPT_option_verbose(&verbose), + GNUNET_GETOPT_OPTION_END }; + + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; expiration = GNUNET_TIME_UNIT_HOURS; return (GNUNET_OK == - GNUNET_PROGRAM_run ( + GNUNET_PROGRAM_run( argc, argv, "gnunet-dht-put", - gettext_noop ( + gettext_noop( "Issue a PUT request to the GNUnet DHT insert DATA under KEY."), options, &run, NULL)) - ? ret - : 1; + ? ret + : 1; } /* end of gnunet-dht-put.c */ diff --git a/src/dht/gnunet-service-dht.c b/src/dht/gnunet-service-dht.c index 705ffb86c..c1e4c03b0 100644 --- a/src/dht/gnunet-service-dht.c +++ b/src/dht/gnunet-service-dht.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht.c @@ -66,14 +66,14 @@ struct GNUNET_TIME_Relative hello_expiration; * @param message HELLO message of peer */ static void -process_hello (void *cls, - const struct GNUNET_MessageHeader *message) +process_hello(void *cls, + const struct GNUNET_MessageHeader *message) { - GNUNET_free_non_null (GDS_my_hello); - GDS_my_hello = GNUNET_malloc (ntohs (message->size)); - GNUNET_memcpy (GDS_my_hello, - message, - ntohs (message->size)); + GNUNET_free_non_null(GDS_my_hello); + GDS_my_hello = GNUNET_malloc(ntohs(message->size)); + GNUNET_memcpy(GDS_my_hello, + message, + ntohs(message->size)); } @@ -83,32 +83,32 @@ process_hello (void *cls, * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { if (NULL != ghh) - { - GNUNET_TRANSPORT_hello_get_cancel (ghh); - ghh = NULL; - } - GDS_NEIGHBOURS_done (); - GDS_DATACACHE_done (); - GDS_ROUTING_done (); - GDS_HELLO_done (); - GDS_NSE_done (); + { + GNUNET_TRANSPORT_hello_get_cancel(ghh); + ghh = NULL; + } + GDS_NEIGHBOURS_done(); + GDS_DATACACHE_done(); + GDS_ROUTING_done(); + GDS_HELLO_done(); + GDS_NSE_done(); if (NULL != GDS_block_context) - { - GNUNET_BLOCK_context_destroy (GDS_block_context); - GDS_block_context = NULL; - } + { + GNUNET_BLOCK_context_destroy(GDS_block_context); + GDS_block_context = NULL; + } if (NULL != GDS_stats) - { - GNUNET_STATISTICS_destroy (GDS_stats, - GNUNET_YES); - GDS_stats = NULL; - } - GNUNET_free_non_null (GDS_my_hello); + { + GNUNET_STATISTICS_destroy(GDS_stats, + GNUNET_YES); + GDS_stats = NULL; + } + GNUNET_free_non_null(GDS_my_hello); GDS_my_hello = NULL; - GDS_CLIENTS_stop (); + GDS_CLIENTS_stop(); } @@ -120,40 +120,40 @@ shutdown_task (void *cls) * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *service) { GDS_cfg = c; GDS_service = service; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_time (c, - "transport", - "HELLO_EXPIRATION", - &hello_expiration)) - { - hello_expiration = GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION; - } - GDS_block_context = GNUNET_BLOCK_context_create (GDS_cfg); - GDS_stats = GNUNET_STATISTICS_create ("dht", - GDS_cfg); - GNUNET_SERVICE_suspend (GDS_service); - GDS_CLIENTS_init (); - GDS_ROUTING_init (); - GDS_NSE_init (); - GDS_DATACACHE_init (); - GDS_HELLO_init (); - if (GNUNET_OK != GDS_NEIGHBOURS_init ()) - { - shutdown_task (NULL); - return; - } - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); - ghh = GNUNET_TRANSPORT_hello_get (GDS_cfg, - GNUNET_TRANSPORT_AC_GLOBAL, - &process_hello, - NULL); + GNUNET_CONFIGURATION_get_value_time(c, + "transport", + "HELLO_EXPIRATION", + &hello_expiration)) + { + hello_expiration = GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION; + } + GDS_block_context = GNUNET_BLOCK_context_create(GDS_cfg); + GDS_stats = GNUNET_STATISTICS_create("dht", + GDS_cfg); + GNUNET_SERVICE_suspend(GDS_service); + GDS_CLIENTS_init(); + GDS_ROUTING_init(); + GDS_NSE_init(); + GDS_DATACACHE_init(); + GDS_HELLO_init(); + if (GNUNET_OK != GDS_NEIGHBOURS_init()) + { + shutdown_task(NULL); + return; + } + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); + ghh = GNUNET_TRANSPORT_hello_get(GDS_cfg, + GNUNET_TRANSPORT_AC_GLOBAL, + &process_hello, + NULL); } diff --git a/src/dht/gnunet-service-dht.h b/src/dht/gnunet-service-dht.h index 8b41c648c..caf9dcbe8 100644 --- a/src/dht/gnunet-service-dht.h +++ b/src/dht/gnunet-service-dht.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht.h @@ -76,15 +76,15 @@ extern struct GNUNET_MessageHeader *GDS_my_hello; * @param data application payload data */ void -GDS_CLIENTS_handle_reply (struct GNUNET_TIME_Absolute expiration, - const struct GNUNET_HashCode *key, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *get_path, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path, - enum GNUNET_BLOCK_Type type, - size_t data_size, - const void *data); +GDS_CLIENTS_handle_reply(struct GNUNET_TIME_Absolute expiration, + const struct GNUNET_HashCode *key, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *get_path, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path, + enum GNUNET_BLOCK_Type type, + size_t data_size, + const void *data); /** @@ -100,13 +100,13 @@ GDS_CLIENTS_handle_reply (struct GNUNET_TIME_Absolute expiration, * @param key Key of the requested data. */ void -GDS_CLIENTS_process_get (uint32_t options, - enum GNUNET_BLOCK_Type type, - uint32_t hop_count, - uint32_t desired_replication_level, - unsigned int path_length, - const struct GNUNET_PeerIdentity *path, - const struct GNUNET_HashCode *key); +GDS_CLIENTS_process_get(uint32_t options, + enum GNUNET_BLOCK_Type type, + uint32_t hop_count, + uint32_t desired_replication_level, + unsigned int path_length, + const struct GNUNET_PeerIdentity *path, + const struct GNUNET_HashCode *key); /** @@ -124,15 +124,15 @@ GDS_CLIENTS_process_get (uint32_t options, * @param size Number of bytes in @a data. */ void -GDS_CLIENTS_process_get_resp (enum GNUNET_BLOCK_Type type, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode * key, - const void *data, - size_t size); +GDS_CLIENTS_process_get_resp(enum GNUNET_BLOCK_Type type, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode * key, + const void *data, + size_t size); /** @@ -151,15 +151,15 @@ GDS_CLIENTS_process_get_resp (enum GNUNET_BLOCK_Type type, * @param size Number of bytes in data. */ void -GDS_CLIENTS_process_put (uint32_t options, - enum GNUNET_BLOCK_Type type, - uint32_t hop_count, - uint32_t desired_replication_level, - unsigned int path_length, - const struct GNUNET_PeerIdentity *path, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const void *data, - size_t size); +GDS_CLIENTS_process_put(uint32_t options, + enum GNUNET_BLOCK_Type type, + uint32_t hop_count, + uint32_t desired_replication_level, + unsigned int path_length, + const struct GNUNET_PeerIdentity *path, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const void *data, + size_t size); #endif diff --git a/src/dht/gnunet-service-dht_clients.c b/src/dht/gnunet-service-dht_clients.c index 7e2440841..48017bfb4 100644 --- a/src/dht/gnunet-service-dht_clients.c +++ b/src/dht/gnunet-service-dht_clients.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht_clients.c @@ -38,9 +38,9 @@ /** * Should routing details be logged to stderr (for debugging)? */ -#define LOG_TRAFFIC(kind,...) GNUNET_log_from (kind, "dht-traffic",__VA_ARGS__) +#define LOG_TRAFFIC(kind, ...) GNUNET_log_from(kind, "dht-traffic", __VA_ARGS__) -#define LOG(kind,...) GNUNET_log_from (kind, "dht-clients",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "dht-clients", __VA_ARGS__) /** @@ -54,9 +54,7 @@ struct ClientHandle; /** * Entry in the local forwarding map for a client's GET request. */ -struct ClientQueryRecord -{ - +struct ClientQueryRecord { /** * The key this request was about */ @@ -132,16 +130,13 @@ struct ClientQueryRecord * The type for the data for the GET request. */ enum GNUNET_BLOCK_Type type; - }; /** * Struct containing paremeters of monitoring requests. */ -struct ClientMonitorRecord -{ - +struct ClientMonitorRecord { /** * Next element in DLL. */ @@ -189,8 +184,7 @@ struct ClientMonitorRecord * handle to connect to it, and any pending messages * that need to be sent to it. */ -struct ClientHandle -{ +struct ClientHandle { /** * Linked list of active queries of this client. */ @@ -210,7 +204,6 @@ struct ClientHandle * The message queue to this client */ struct GNUNET_MQ_Handle *mq; - }; /** @@ -265,23 +258,23 @@ static struct GNUNET_SCHEDULER_Task *retry_task; * @param record record to remove */ static void -remove_client_record (struct ClientQueryRecord *record) +remove_client_record(struct ClientQueryRecord *record) { struct ClientHandle *ch = record->ch; - GNUNET_CONTAINER_DLL_remove (ch->cqr_head, - ch->cqr_tail, - record); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (forward_map, - &record->key, - record)); + GNUNET_CONTAINER_DLL_remove(ch->cqr_head, + ch->cqr_tail, + record); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(forward_map, + &record->key, + record)); if (NULL != record->hnode) - GNUNET_CONTAINER_heap_remove_node (record->hnode); - GNUNET_array_grow (record->seen_replies, - record->seen_replies_count, - 0); - GNUNET_free (record); + GNUNET_CONTAINER_heap_remove_node(record->hnode); + GNUNET_array_grow(record->seen_replies, + record->seen_replies_count, + 0); + GNUNET_free(record); } @@ -295,13 +288,13 @@ remove_client_record (struct ClientQueryRecord *record) * @return our `struct ClientHandle` for @a client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { struct ClientHandle *ch; - ch = GNUNET_new (struct ClientHandle); + ch = GNUNET_new(struct ClientHandle); ch->client = client; ch->mq = mq; return ch; @@ -317,40 +310,40 @@ client_connect_cb (void *cls, * @param app_ctx our `struct ClientHandle` for @a client */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { struct ClientHandle *ch = app_ctx; struct ClientQueryRecord *cqr; struct ClientMonitorRecord *monitor; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Local client %p disconnects\n", - ch); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Local client %p disconnects\n", + ch); monitor = monitor_head; while (NULL != monitor) - { - if (monitor->ch == ch) - { - struct ClientMonitorRecord *next; - - next = monitor->next; - GNUNET_free_non_null (monitor->key); - GNUNET_CONTAINER_DLL_remove (monitor_head, - monitor_tail, - monitor); - GNUNET_free (monitor); - monitor = next; - } - else { - monitor = monitor->next; + if (monitor->ch == ch) + { + struct ClientMonitorRecord *next; + + next = monitor->next; + GNUNET_free_non_null(monitor->key); + GNUNET_CONTAINER_DLL_remove(monitor_head, + monitor_tail, + monitor); + GNUNET_free(monitor); + monitor = next; + } + else + { + monitor = monitor->next; + } } - } while (NULL != (cqr = ch->cqr_head)) - remove_client_record (cqr); - GNUNET_free (ch); + remove_client_record(cqr); + GNUNET_free(ch); } @@ -360,52 +353,52 @@ client_disconnect_cb (void *cls, * message and initiating the routing operation. */ static void -transmit_request (struct ClientQueryRecord *cqr) +transmit_request(struct ClientQueryRecord *cqr) { struct GNUNET_BLOCK_Group *bg; struct GNUNET_CONTAINER_BloomFilter *peer_bf; - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# GET requests from clients injected"), - 1, - GNUNET_NO); - bg = GNUNET_BLOCK_group_create (GDS_block_context, - cqr->type, - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT32_MAX), - NULL, - 0, - "seen-set-size", - cqr->seen_replies_count, - NULL); - GNUNET_BLOCK_group_set_seen (bg, - cqr->seen_replies, - cqr->seen_replies_count); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# GET requests from clients injected"), + 1, + GNUNET_NO); + bg = GNUNET_BLOCK_group_create(GDS_block_context, + cqr->type, + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + UINT32_MAX), + NULL, + 0, + "seen-set-size", + cqr->seen_replies_count, + NULL); + GNUNET_BLOCK_group_set_seen(bg, + cqr->seen_replies, + cqr->seen_replies_count); peer_bf - = GNUNET_CONTAINER_bloomfilter_init (NULL, - DHT_BLOOM_SIZE, - GNUNET_CONSTANTS_BLOOMFILTER_K); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Initiating GET for %s, replication %u, already have %u replies\n", - GNUNET_h2s (&cqr->key), - cqr->replication, - cqr->seen_replies_count); - GDS_NEIGHBOURS_handle_get (cqr->type, - cqr->msg_options, - cqr->replication, - 0 /* hop count */ , - &cqr->key, - cqr->xquery, - cqr->xquery_size, - bg, - peer_bf); - GNUNET_BLOCK_group_destroy (bg); - GNUNET_CONTAINER_bloomfilter_free (peer_bf); + = GNUNET_CONTAINER_bloomfilter_init(NULL, + DHT_BLOOM_SIZE, + GNUNET_CONSTANTS_BLOOMFILTER_K); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Initiating GET for %s, replication %u, already have %u replies\n", + GNUNET_h2s(&cqr->key), + cqr->replication, + cqr->seen_replies_count); + GDS_NEIGHBOURS_handle_get(cqr->type, + cqr->msg_options, + cqr->replication, + 0 /* hop count */, + &cqr->key, + cqr->xquery, + cqr->xquery_size, + bg, + peer_bf); + GNUNET_BLOCK_group_destroy(bg); + GNUNET_CONTAINER_bloomfilter_free(peer_bf); /* exponential back-off for retries. * max GNUNET_TIME_STD_EXPONENTIAL_BACKOFF_THRESHOLD (15 min) */ - cqr->retry_frequency = GNUNET_TIME_STD_BACKOFF (cqr->retry_frequency); - cqr->retry_time = GNUNET_TIME_relative_to_absolute (cqr->retry_frequency); + cqr->retry_frequency = GNUNET_TIME_STD_BACKOFF(cqr->retry_frequency); + cqr->retry_time = GNUNET_TIME_relative_to_absolute(cqr->retry_frequency); } @@ -417,34 +410,34 @@ transmit_request (struct ClientQueryRecord *cqr) * @param cls unused */ static void -transmit_next_request_task (void *cls) +transmit_next_request_task(void *cls) { struct ClientQueryRecord *cqr; struct GNUNET_TIME_Relative delay; retry_task = NULL; - while (NULL != (cqr = GNUNET_CONTAINER_heap_remove_root (retry_heap))) - { - cqr->hnode = NULL; - delay = GNUNET_TIME_absolute_get_remaining (cqr->retry_time); - if (delay.rel_value_us > 0) + while (NULL != (cqr = GNUNET_CONTAINER_heap_remove_root(retry_heap))) { + cqr->hnode = NULL; + delay = GNUNET_TIME_absolute_get_remaining(cqr->retry_time); + if (delay.rel_value_us > 0) + { + cqr->hnode + = GNUNET_CONTAINER_heap_insert(retry_heap, + cqr, + cqr->retry_time.abs_value_us); + retry_task + = GNUNET_SCHEDULER_add_at(cqr->retry_time, + &transmit_next_request_task, + NULL); + return; + } + transmit_request(cqr); cqr->hnode - = GNUNET_CONTAINER_heap_insert (retry_heap, - cqr, - cqr->retry_time.abs_value_us); - retry_task - = GNUNET_SCHEDULER_add_at (cqr->retry_time, - &transmit_next_request_task, - NULL); - return; + = GNUNET_CONTAINER_heap_insert(retry_heap, + cqr, + cqr->retry_time.abs_value_us); } - transmit_request (cqr); - cqr->hnode - = GNUNET_CONTAINER_heap_insert (retry_heap, - cqr, - cqr->retry_time.abs_value_us); - } } @@ -456,8 +449,8 @@ transmit_next_request_task (void *cls) * @return #GNUNET_OK (always) */ static int -check_dht_local_put (void *cls, - const struct GNUNET_DHT_ClientPutMessage *dht_msg) +check_dht_local_put(void *cls, + const struct GNUNET_DHT_ClientPutMessage *dht_msg) { /* always well-formed */ return GNUNET_OK; @@ -471,71 +464,71 @@ check_dht_local_put (void *cls, * @param dht_msg the actual message received */ static void -handle_dht_local_put (void *cls, - const struct GNUNET_DHT_ClientPutMessage *dht_msg) +handle_dht_local_put(void *cls, + const struct GNUNET_DHT_ClientPutMessage *dht_msg) { struct ClientHandle *ch = cls; struct GNUNET_CONTAINER_BloomFilter *peer_bf; uint16_t size; - size = ntohs (dht_msg->header.size); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# PUT requests received from clients"), - 1, - GNUNET_NO); - LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, - "CLIENT-PUT %s\n", - GNUNET_h2s_full (&dht_msg->key)); + size = ntohs(dht_msg->header.size); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# PUT requests received from clients"), + 1, + GNUNET_NO); + LOG_TRAFFIC(GNUNET_ERROR_TYPE_DEBUG, + "CLIENT-PUT %s\n", + GNUNET_h2s_full(&dht_msg->key)); /* give to local clients */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Handling local PUT of %u-bytes for query %s\n", - size - sizeof (struct GNUNET_DHT_ClientPutMessage), - GNUNET_h2s (&dht_msg->key)); - GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (dht_msg->expiration), - &dht_msg->key, - 0, - NULL, - 0, - NULL, - ntohl (dht_msg->type), - size - sizeof (struct GNUNET_DHT_ClientPutMessage), - &dht_msg[1]); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Handling local PUT of %u-bytes for query %s\n", + size - sizeof(struct GNUNET_DHT_ClientPutMessage), + GNUNET_h2s(&dht_msg->key)); + GDS_CLIENTS_handle_reply(GNUNET_TIME_absolute_ntoh(dht_msg->expiration), + &dht_msg->key, + 0, + NULL, + 0, + NULL, + ntohl(dht_msg->type), + size - sizeof(struct GNUNET_DHT_ClientPutMessage), + &dht_msg[1]); /* store locally */ - GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (dht_msg->expiration), + GDS_DATACACHE_handle_put(GNUNET_TIME_absolute_ntoh(dht_msg->expiration), + &dht_msg->key, + 0, + NULL, + ntohl(dht_msg->type), + size - sizeof(struct GNUNET_DHT_ClientPutMessage), + &dht_msg[1]); + /* route to other peers */ + peer_bf + = GNUNET_CONTAINER_bloomfilter_init(NULL, + DHT_BLOOM_SIZE, + GNUNET_CONSTANTS_BLOOMFILTER_K); + GDS_NEIGHBOURS_handle_put(ntohl(dht_msg->type), + ntohl(dht_msg->options), + ntohl(dht_msg->desired_replication_level), + GNUNET_TIME_absolute_ntoh(dht_msg->expiration), + 0 /* hop count */, + peer_bf, &dht_msg->key, 0, NULL, - ntohl (dht_msg->type), - size - sizeof (struct GNUNET_DHT_ClientPutMessage), - &dht_msg[1]); - /* route to other peers */ - peer_bf - = GNUNET_CONTAINER_bloomfilter_init (NULL, - DHT_BLOOM_SIZE, - GNUNET_CONSTANTS_BLOOMFILTER_K); - GDS_NEIGHBOURS_handle_put (ntohl (dht_msg->type), - ntohl (dht_msg->options), - ntohl (dht_msg->desired_replication_level), - GNUNET_TIME_absolute_ntoh (dht_msg->expiration), - 0 /* hop count */, - peer_bf, - &dht_msg->key, - 0, - NULL, - &dht_msg[1], - size - sizeof (struct GNUNET_DHT_ClientPutMessage)); - GDS_CLIENTS_process_put (ntohl (dht_msg->options), - ntohl (dht_msg->type), - 0, - ntohl (dht_msg->desired_replication_level), - 1, - GDS_NEIGHBOURS_get_id(), - GNUNET_TIME_absolute_ntoh (dht_msg->expiration), - &dht_msg->key, - &dht_msg[1], - size - sizeof (struct GNUNET_DHT_ClientPutMessage)); - GNUNET_CONTAINER_bloomfilter_free (peer_bf); - GNUNET_SERVICE_client_continue (ch->client); + &dht_msg[1], + size - sizeof(struct GNUNET_DHT_ClientPutMessage)); + GDS_CLIENTS_process_put(ntohl(dht_msg->options), + ntohl(dht_msg->type), + 0, + ntohl(dht_msg->desired_replication_level), + 1, + GDS_NEIGHBOURS_get_id(), + GNUNET_TIME_absolute_ntoh(dht_msg->expiration), + &dht_msg->key, + &dht_msg[1], + size - sizeof(struct GNUNET_DHT_ClientPutMessage)); + GNUNET_CONTAINER_bloomfilter_free(peer_bf); + GNUNET_SERVICE_client_continue(ch->client); } @@ -547,8 +540,8 @@ handle_dht_local_put (void *cls, * @return #GNUNET_OK (always) */ static int -check_dht_local_get (void *cls, - const struct GNUNET_DHT_ClientGetMessage *get) +check_dht_local_get(void *cls, + const struct GNUNET_DHT_ClientGetMessage *get) { /* always well-formed */ return GNUNET_OK; @@ -570,25 +563,25 @@ check_dht_local_get (void *cls, * @param data_size number of bytes in @a data */ static void -handle_local_result (void *cls, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute expiration_time, - const struct GNUNET_HashCode *key, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *get_path, - const void *data, - size_t data_size) +handle_local_result(void *cls, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute expiration_time, + const struct GNUNET_HashCode *key, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *get_path, + const void *data, + size_t data_size) { // FIXME: this needs some clean up: inline the function, // possibly avoid even looking up the client! - GDS_CLIENTS_handle_reply (expiration_time, - key, - 0, NULL, - put_path_length, put_path, - type, - data_size, data); + GDS_CLIENTS_handle_reply(expiration_time, + key, + 0, NULL, + put_path_length, put_path, + type, + data_size, data); } @@ -599,8 +592,8 @@ handle_local_result (void *cls, * @param message the actual message received */ static void -handle_dht_local_get (void *cls, - const struct GNUNET_DHT_ClientGetMessage *get) +handle_dht_local_get(void *cls, + const struct GNUNET_DHT_ClientGetMessage *get) { struct ClientHandle *ch = cls; struct ClientQueryRecord *cqr; @@ -608,72 +601,71 @@ handle_dht_local_get (void *cls, const char *xquery; uint16_t size; - size = ntohs (get->header.size); - xquery_size = size - sizeof (struct GNUNET_DHT_ClientGetMessage); - xquery = (const char *) &get[1]; - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# GET requests received from clients"), 1, - GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received GET request for %s from local client %p, xq: %.*s\n", - GNUNET_h2s (&get->key), - ch->client, - xquery_size, - xquery); - LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, - "CLIENT-GET %s\n", - GNUNET_h2s_full (&get->key)); - - cqr = GNUNET_malloc (sizeof (struct ClientQueryRecord) + xquery_size); + size = ntohs(get->header.size); + xquery_size = size - sizeof(struct GNUNET_DHT_ClientGetMessage); + xquery = (const char *)&get[1]; + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# GET requests received from clients"), 1, + GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received GET request for %s from local client %p, xq: %.*s\n", + GNUNET_h2s(&get->key), + ch->client, + xquery_size, + xquery); + LOG_TRAFFIC(GNUNET_ERROR_TYPE_DEBUG, + "CLIENT-GET %s\n", + GNUNET_h2s_full(&get->key)); + + cqr = GNUNET_malloc(sizeof(struct ClientQueryRecord) + xquery_size); cqr->key = get->key; cqr->ch = ch; - cqr->xquery = (void *) &cqr[1]; - GNUNET_memcpy (&cqr[1], xquery, xquery_size); - cqr->hnode = GNUNET_CONTAINER_heap_insert (retry_heap, cqr, 0); + cqr->xquery = (void *)&cqr[1]; + GNUNET_memcpy(&cqr[1], xquery, xquery_size); + cqr->hnode = GNUNET_CONTAINER_heap_insert(retry_heap, cqr, 0); cqr->retry_frequency = GNUNET_TIME_UNIT_SECONDS; - cqr->retry_time = GNUNET_TIME_absolute_get (); + cqr->retry_time = GNUNET_TIME_absolute_get(); cqr->unique_id = get->unique_id; cqr->xquery_size = xquery_size; - cqr->replication = ntohl (get->desired_replication_level); - cqr->msg_options = ntohl (get->options); - cqr->type = ntohl (get->type); - GNUNET_CONTAINER_DLL_insert (ch->cqr_head, - ch->cqr_tail, - cqr); - GNUNET_CONTAINER_multihashmap_put (forward_map, - &cqr->key, - cqr, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - GDS_CLIENTS_process_get (ntohl (get->options), - ntohl (get->type), - 0, - ntohl (get->desired_replication_level), - 1, - GDS_NEIGHBOURS_get_id(), - &get->key); + cqr->replication = ntohl(get->desired_replication_level); + cqr->msg_options = ntohl(get->options); + cqr->type = ntohl(get->type); + GNUNET_CONTAINER_DLL_insert(ch->cqr_head, + ch->cqr_tail, + cqr); + GNUNET_CONTAINER_multihashmap_put(forward_map, + &cqr->key, + cqr, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + GDS_CLIENTS_process_get(ntohl(get->options), + ntohl(get->type), + 0, + ntohl(get->desired_replication_level), + 1, + GDS_NEIGHBOURS_get_id(), + &get->key); /* start remote requests */ if (NULL != retry_task) - GNUNET_SCHEDULER_cancel (retry_task); - retry_task = GNUNET_SCHEDULER_add_now (&transmit_next_request_task, - NULL); + GNUNET_SCHEDULER_cancel(retry_task); + retry_task = GNUNET_SCHEDULER_add_now(&transmit_next_request_task, + NULL); /* perform local lookup */ - GDS_DATACACHE_handle_get (&get->key, - cqr->type, - cqr->xquery, - xquery_size, - NULL, - &handle_local_result, - ch); - GNUNET_SERVICE_client_continue (ch->client); + GDS_DATACACHE_handle_get(&get->key, + cqr->type, + cqr->xquery, + xquery_size, + NULL, + &handle_local_result, + ch); + GNUNET_SERVICE_client_continue(ch->client); } /** * Closure for #find_by_unique_id(). */ -struct FindByUniqueIdContext -{ +struct FindByUniqueIdContext { /** * Where to store the result, if found. */ @@ -694,9 +686,9 @@ struct FindByUniqueIdContext * @return #GNUNET_YES to continue iteration (result not yet found) */ static int -find_by_unique_id (void *cls, - const struct GNUNET_HashCode *key, - void *value) +find_by_unique_id(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct FindByUniqueIdContext *fui_ctx = cls; struct ClientQueryRecord *cqr = value; @@ -716,19 +708,19 @@ find_by_unique_id (void *cls, * @return #GNUNET_OK if @a seen is well-formed */ static int -check_dht_local_get_result_seen (void *cls, - const struct GNUNET_DHT_ClientGetResultSeenMessage *seen) +check_dht_local_get_result_seen(void *cls, + const struct GNUNET_DHT_ClientGetResultSeenMessage *seen) { uint16_t size; unsigned int hash_count; - size = ntohs (seen->header.size); - hash_count = (size - sizeof (struct GNUNET_DHT_ClientGetResultSeenMessage)) / sizeof (struct GNUNET_HashCode); - if (size != sizeof (struct GNUNET_DHT_ClientGetResultSeenMessage) + hash_count * sizeof (struct GNUNET_HashCode)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + size = ntohs(seen->header.size); + hash_count = (size - sizeof(struct GNUNET_DHT_ClientGetResultSeenMessage)) / sizeof(struct GNUNET_HashCode); + if (size != sizeof(struct GNUNET_DHT_ClientGetResultSeenMessage) + hash_count * sizeof(struct GNUNET_HashCode)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -740,8 +732,8 @@ check_dht_local_get_result_seen (void *cls, * @param message the actual message received */ static void -handle_dht_local_get_result_seen (void *cls, - const struct GNUNET_DHT_ClientGetResultSeenMessage *seen) +handle_dht_local_get_result_seen(void *cls, + const struct GNUNET_DHT_ClientGetResultSeenMessage *seen) { struct ClientHandle *ch = cls; uint16_t size; @@ -751,37 +743,36 @@ handle_dht_local_get_result_seen (void *cls, struct FindByUniqueIdContext fui_ctx; struct ClientQueryRecord *cqr; - size = ntohs (seen->header.size); - hash_count = (size - sizeof (struct GNUNET_DHT_ClientGetResultSeenMessage)) / sizeof (struct GNUNET_HashCode); - hc = (const struct GNUNET_HashCode*) &seen[1]; + size = ntohs(seen->header.size); + hash_count = (size - sizeof(struct GNUNET_DHT_ClientGetResultSeenMessage)) / sizeof(struct GNUNET_HashCode); + hc = (const struct GNUNET_HashCode*)&seen[1]; fui_ctx.unique_id = seen->unique_id; fui_ctx.cqr = NULL; - GNUNET_CONTAINER_multihashmap_get_multiple (forward_map, - &seen->key, - &find_by_unique_id, - &fui_ctx); + GNUNET_CONTAINER_multihashmap_get_multiple(forward_map, + &seen->key, + &find_by_unique_id, + &fui_ctx); if (NULL == (cqr = fui_ctx.cqr)) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (ch->client); - return; - } + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(ch->client); + return; + } /* finally, update 'seen' list */ old_count = cqr->seen_replies_count; - GNUNET_array_grow (cqr->seen_replies, - cqr->seen_replies_count, - cqr->seen_replies_count + hash_count); - GNUNET_memcpy (&cqr->seen_replies[old_count], - hc, - sizeof (struct GNUNET_HashCode) * hash_count); + GNUNET_array_grow(cqr->seen_replies, + cqr->seen_replies_count, + cqr->seen_replies_count + hash_count); + GNUNET_memcpy(&cqr->seen_replies[old_count], + hc, + sizeof(struct GNUNET_HashCode) * hash_count); } /** * Closure for #remove_by_unique_id(). */ -struct RemoveByUniqueIdContext -{ +struct RemoveByUniqueIdContext { /** * Client that issued the removal request. */ @@ -804,20 +795,20 @@ struct RemoveByUniqueIdContext * @return #GNUNET_YES (we should continue to iterate) */ static int -remove_by_unique_id (void *cls, - const struct GNUNET_HashCode *key, - void *value) +remove_by_unique_id(void *cls, + const struct GNUNET_HashCode *key, + void *value) { const struct RemoveByUniqueIdContext *ctx = cls; struct ClientQueryRecord *cqr = value; if (cqr->unique_id != ctx->unique_id) return GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Removing client %p's record for key %s (by unique id)\n", - ctx->ch->client, - GNUNET_h2s (key)); - remove_client_record (cqr); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Removing client %p's record for key %s (by unique id)\n", + ctx->ch->client, + GNUNET_h2s(key)); + remove_client_record(cqr); return GNUNET_YES; } @@ -831,27 +822,27 @@ remove_by_unique_id (void *cls, * */ static void -handle_dht_local_get_stop (void *cls, - const struct GNUNET_DHT_ClientGetStopMessage *dht_stop_msg) +handle_dht_local_get_stop(void *cls, + const struct GNUNET_DHT_ClientGetStopMessage *dht_stop_msg) { struct ClientHandle *ch = cls; struct RemoveByUniqueIdContext ctx; - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# GET STOP requests received from clients"), 1, - GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received GET STOP request for %s from local client %p\n", - GNUNET_h2s (&dht_stop_msg->key), - ch->client); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# GET STOP requests received from clients"), 1, + GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received GET STOP request for %s from local client %p\n", + GNUNET_h2s(&dht_stop_msg->key), + ch->client); ctx.ch = ch; ctx.unique_id = dht_stop_msg->unique_id; - GNUNET_CONTAINER_multihashmap_get_multiple (forward_map, - &dht_stop_msg->key, - &remove_by_unique_id, - &ctx); - GNUNET_SERVICE_client_continue (ch->client); + GNUNET_CONTAINER_multihashmap_get_multiple(forward_map, + &dht_stop_msg->key, + &remove_by_unique_id, + &ctx); + GNUNET_SERVICE_client_continue(ch->client); } @@ -863,33 +854,33 @@ handle_dht_local_get_stop (void *cls, * */ static void -handle_dht_local_monitor (void *cls, - const struct GNUNET_DHT_MonitorStartStopMessage *msg) +handle_dht_local_monitor(void *cls, + const struct GNUNET_DHT_MonitorStartStopMessage *msg) { struct ClientHandle *ch = cls; struct ClientMonitorRecord *r; - r = GNUNET_new (struct ClientMonitorRecord); + r = GNUNET_new(struct ClientMonitorRecord); r->ch = ch; - r->type = ntohl (msg->type); - r->get = ntohs (msg->get); - r->get_resp = ntohs (msg->get_resp); - r->put = ntohs (msg->put); - if (0 == ntohs (msg->filter_key)) - { - r->key = NULL; - } + r->type = ntohl(msg->type); + r->get = ntohs(msg->get); + r->get_resp = ntohs(msg->get_resp); + r->put = ntohs(msg->put); + if (0 == ntohs(msg->filter_key)) + { + r->key = NULL; + } else - { - r->key = GNUNET_new (struct GNUNET_HashCode); - GNUNET_memcpy (r->key, - &msg->key, - sizeof (struct GNUNET_HashCode)); - } - GNUNET_CONTAINER_DLL_insert (monitor_head, - monitor_tail, - r); - GNUNET_SERVICE_client_continue (ch->client); + { + r->key = GNUNET_new(struct GNUNET_HashCode); + GNUNET_memcpy(r->key, + &msg->key, + sizeof(struct GNUNET_HashCode)); + } + GNUNET_CONTAINER_DLL_insert(monitor_head, + monitor_tail, + r); + GNUNET_SERVICE_client_continue(ch->client); } @@ -900,51 +891,49 @@ handle_dht_local_monitor (void *cls, * @param msg the actual message received */ static void -handle_dht_local_monitor_stop (void *cls, - const struct GNUNET_DHT_MonitorStartStopMessage *msg) +handle_dht_local_monitor_stop(void *cls, + const struct GNUNET_DHT_MonitorStartStopMessage *msg) { struct ClientHandle *ch = cls; struct ClientMonitorRecord *r; int keys_match; - GNUNET_SERVICE_client_continue (ch->client); + GNUNET_SERVICE_client_continue(ch->client); for (r = monitor_head; NULL != r; r = r->next) - { - if (NULL == r->key) { - keys_match = (0 == ntohs(msg->filter_key)); + if (NULL == r->key) + { + keys_match = (0 == ntohs(msg->filter_key)); + } + else + { + keys_match = ((0 != ntohs(msg->filter_key)) && + (!memcmp(r->key, + &msg->key, + sizeof(struct GNUNET_HashCode)))); + } + if ((ch == r->ch) && + (ntohl(msg->type) == r->type) && + (r->get == msg->get) && + (r->get_resp == msg->get_resp) && + (r->put == msg->put) && + keys_match) + { + GNUNET_CONTAINER_DLL_remove(monitor_head, + monitor_tail, + r); + GNUNET_free_non_null(r->key); + GNUNET_free(r); + return; /* Delete only ONE entry */ + } } - else - { - keys_match = ( (0 != ntohs(msg->filter_key)) && - (! memcmp (r->key, - &msg->key, - sizeof(struct GNUNET_HashCode))) ); - } - if ( (ch == r->ch) && - (ntohl(msg->type) == r->type) && - (r->get == msg->get) && - (r->get_resp == msg->get_resp) && - (r->put == msg->put) && - keys_match ) - { - GNUNET_CONTAINER_DLL_remove (monitor_head, - monitor_tail, - r); - GNUNET_free_non_null (r->key); - GNUNET_free (r); - return; /* Delete only ONE entry */ - } - } } /** * Closure for #forward_reply() */ -struct ForwardReplyContext -{ - +struct ForwardReplyContext { /** * Expiration time of the reply. */ @@ -984,7 +973,6 @@ struct ForwardReplyContext * Type of the data. */ enum GNUNET_BLOCK_Type type; - }; @@ -1000,9 +988,9 @@ struct ForwardReplyContext * if the result is mal-formed, #GNUNET_NO */ static int -forward_reply (void *cls, - const struct GNUNET_HashCode *key, - void *value) +forward_reply(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct ForwardReplyContext *frc = cls; struct ClientQueryRecord *record = value; @@ -1013,116 +1001,124 @@ forward_reply (void *cls, struct GNUNET_HashCode ch; struct GNUNET_PeerIdentity *paths; - LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, - "CLIENT-RESULT %s\n", - GNUNET_h2s_full (key)); - if ( (record->type != GNUNET_BLOCK_TYPE_ANY) && - (record->type != frc->type)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Record type mismatch, not passing request for key %s to local client\n", - GNUNET_h2s (key)); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# Key match, type mismatches in REPLY to CLIENT"), - 1, GNUNET_NO); - return GNUNET_YES; /* type mismatch */ - } - GNUNET_CRYPTO_hash (frc->data, frc->data_size, &ch); - for (unsigned int i = 0; i < record->seen_replies_count; i++) - if (0 == memcmp (&record->seen_replies[i], - &ch, - sizeof (struct GNUNET_HashCode))) + LOG_TRAFFIC(GNUNET_ERROR_TYPE_DEBUG, + "CLIENT-RESULT %s\n", + GNUNET_h2s_full(key)); + if ((record->type != GNUNET_BLOCK_TYPE_ANY) && + (record->type != frc->type)) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Duplicate reply, not passing request for key %s to local client\n", - GNUNET_h2s (key)); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# Duplicate REPLIES to CLIENT request dropped"), - 1, GNUNET_NO); - return GNUNET_YES; /* duplicate */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Record type mismatch, not passing request for key %s to local client\n", + GNUNET_h2s(key)); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# Key match, type mismatches in REPLY to CLIENT"), + 1, GNUNET_NO); + return GNUNET_YES; /* type mismatch */ } + GNUNET_CRYPTO_hash(frc->data, frc->data_size, &ch); + for (unsigned int i = 0; i < record->seen_replies_count; i++) + if (0 == memcmp(&record->seen_replies[i], + &ch, + sizeof(struct GNUNET_HashCode))) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Duplicate reply, not passing request for key %s to local client\n", + GNUNET_h2s(key)); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# Duplicate REPLIES to CLIENT request dropped"), + 1, GNUNET_NO); + return GNUNET_YES; /* duplicate */ + } eval - = GNUNET_BLOCK_evaluate (GDS_block_context, - record->type, - NULL, - GNUNET_BLOCK_EO_NONE, - key, - record->xquery, - record->xquery_size, - frc->data, - frc->data_size); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Evaluation result is %d for key %s for local client's query\n", - (int) eval, - GNUNET_h2s (key)); + = GNUNET_BLOCK_evaluate(GDS_block_context, + record->type, + NULL, + GNUNET_BLOCK_EO_NONE, + key, + record->xquery, + record->xquery_size, + frc->data, + frc->data_size); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Evaluation result is %d for key %s for local client's query\n", + (int)eval, + GNUNET_h2s(key)); switch (eval) - { - case GNUNET_BLOCK_EVALUATION_OK_LAST: - do_free = GNUNET_YES; - break; - case GNUNET_BLOCK_EVALUATION_OK_MORE: - GNUNET_array_append (record->seen_replies, - record->seen_replies_count, - ch); - do_free = GNUNET_NO; - break; - case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE: - /* should be impossible to encounter here */ - GNUNET_break (0); - return GNUNET_YES; - case GNUNET_BLOCK_EVALUATION_RESULT_INVALID: - GNUNET_break_op (0); - return GNUNET_NO; - case GNUNET_BLOCK_EVALUATION_REQUEST_VALID: - GNUNET_break (0); - return GNUNET_NO; - case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID: - GNUNET_break (0); - return GNUNET_NO; - case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT: - return GNUNET_YES; - case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED: - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Unsupported block type (%u) in request!\n"), record->type); - return GNUNET_NO; - default: - GNUNET_break (0); - return GNUNET_NO; - } - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# RESULTS queued for clients"), - 1, - GNUNET_NO); - env = GNUNET_MQ_msg_extra (reply, - frc->data_size + - (frc->get_path_length + frc->put_path_length) * sizeof (struct GNUNET_PeerIdentity), - GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT); - reply->type = htonl (frc->type); - reply->get_path_length = htonl (frc->get_path_length); - reply->put_path_length = htonl (frc->put_path_length); + { + case GNUNET_BLOCK_EVALUATION_OK_LAST: + do_free = GNUNET_YES; + break; + + case GNUNET_BLOCK_EVALUATION_OK_MORE: + GNUNET_array_append(record->seen_replies, + record->seen_replies_count, + ch); + do_free = GNUNET_NO; + break; + + case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE: + /* should be impossible to encounter here */ + GNUNET_break(0); + return GNUNET_YES; + + case GNUNET_BLOCK_EVALUATION_RESULT_INVALID: + GNUNET_break_op(0); + return GNUNET_NO; + + case GNUNET_BLOCK_EVALUATION_REQUEST_VALID: + GNUNET_break(0); + return GNUNET_NO; + + case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID: + GNUNET_break(0); + return GNUNET_NO; + + case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT: + return GNUNET_YES; + + case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED: + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Unsupported block type (%u) in request!\n"), record->type); + return GNUNET_NO; + + default: + GNUNET_break(0); + return GNUNET_NO; + } + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# RESULTS queued for clients"), + 1, + GNUNET_NO); + env = GNUNET_MQ_msg_extra(reply, + frc->data_size + + (frc->get_path_length + frc->put_path_length) * sizeof(struct GNUNET_PeerIdentity), + GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT); + reply->type = htonl(frc->type); + reply->get_path_length = htonl(frc->get_path_length); + reply->put_path_length = htonl(frc->put_path_length); reply->unique_id = record->unique_id; - reply->expiration = GNUNET_TIME_absolute_hton (frc->expiration); + reply->expiration = GNUNET_TIME_absolute_hton(frc->expiration); reply->key = *key; - paths = (struct GNUNET_PeerIdentity *) &reply[1]; - GNUNET_memcpy (paths, - frc->put_path, - sizeof (struct GNUNET_PeerIdentity) * frc->put_path_length); - GNUNET_memcpy (&paths[frc->put_path_length], - frc->get_path, - sizeof (struct GNUNET_PeerIdentity) * frc->get_path_length); - GNUNET_memcpy (&paths[frc->get_path_length + frc->put_path_length], - frc->data, - frc->data_size); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending reply to query %s for client %p\n", - GNUNET_h2s (key), - record->ch->client); - GNUNET_MQ_send (record->ch->mq, - env); + paths = (struct GNUNET_PeerIdentity *)&reply[1]; + GNUNET_memcpy(paths, + frc->put_path, + sizeof(struct GNUNET_PeerIdentity) * frc->put_path_length); + GNUNET_memcpy(&paths[frc->put_path_length], + frc->get_path, + sizeof(struct GNUNET_PeerIdentity) * frc->get_path_length); + GNUNET_memcpy(&paths[frc->get_path_length + frc->put_path_length], + frc->data, + frc->data_size); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending reply to query %s for client %p\n", + GNUNET_h2s(key), + record->ch->client); + GNUNET_MQ_send(record->ch->mq, + env); if (GNUNET_YES == do_free) - remove_client_record (record); + remove_client_record(record); return GNUNET_YES; } @@ -1143,38 +1139,38 @@ forward_reply (void *cls, * @param data application payload data */ void -GDS_CLIENTS_handle_reply (struct GNUNET_TIME_Absolute expiration, - const struct GNUNET_HashCode *key, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *get_path, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path, - enum GNUNET_BLOCK_Type type, - size_t data_size, - const void *data) +GDS_CLIENTS_handle_reply(struct GNUNET_TIME_Absolute expiration, + const struct GNUNET_HashCode *key, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *get_path, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path, + enum GNUNET_BLOCK_Type type, + size_t data_size, + const void *data) { struct ForwardReplyContext frc; size_t msize; - msize = sizeof (struct GNUNET_DHT_ClientResultMessage) + data_size + - (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity); + msize = sizeof(struct GNUNET_DHT_ClientResultMessage) + data_size + + (get_path_length + put_path_length) * sizeof(struct GNUNET_PeerIdentity); if (msize >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return; - } - if (NULL == GNUNET_CONTAINER_multihashmap_get (forward_map, - key)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "No matching client for reply for key %s\n", - GNUNET_h2s (key)); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# REPLIES ignored for CLIENTS (no match)"), - 1, - GNUNET_NO); - return; /* no matching request, fast exit! */ - } + { + GNUNET_break(0); + return; + } + if (NULL == GNUNET_CONTAINER_multihashmap_get(forward_map, + key)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "No matching client for reply for key %s\n", + GNUNET_h2s(key)); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# REPLIES ignored for CLIENTS (no match)"), + 1, + GNUNET_NO); + return; /* no matching request, fast exit! */ + } frc.expiration = expiration; frc.get_path = get_path; frc.put_path = put_path; @@ -1183,14 +1179,13 @@ GDS_CLIENTS_handle_reply (struct GNUNET_TIME_Absolute expiration, frc.get_path_length = get_path_length; frc.put_path_length = put_path_length; frc.type = type; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Forwarding reply for key %s to client\n", - GNUNET_h2s (key)); - GNUNET_CONTAINER_multihashmap_get_multiple (forward_map, - key, - &forward_reply, - &frc); - + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Forwarding reply for key %s to client\n", + GNUNET_h2s(key)); + GNUNET_CONTAINER_multihashmap_get_multiple(forward_map, + key, + &forward_reply, + &frc); } @@ -1207,13 +1202,13 @@ GDS_CLIENTS_handle_reply (struct GNUNET_TIME_Absolute expiration, * @param key Key of the requested data. */ void -GDS_CLIENTS_process_get (uint32_t options, - enum GNUNET_BLOCK_Type type, - uint32_t hop_count, - uint32_t desired_replication_level, - unsigned int path_length, - const struct GNUNET_PeerIdentity *path, - const struct GNUNET_HashCode * key) +GDS_CLIENTS_process_get(uint32_t options, + enum GNUNET_BLOCK_Type type, + uint32_t hop_count, + uint32_t desired_replication_level, + unsigned int path_length, + const struct GNUNET_PeerIdentity *path, + const struct GNUNET_HashCode * key) { struct ClientMonitorRecord *m; struct ClientHandle **cl; @@ -1222,49 +1217,49 @@ GDS_CLIENTS_process_get (uint32_t options, cl = NULL; cl_size = 0; for (m = monitor_head; NULL != m; m = m->next) - { - if ( ( (GNUNET_BLOCK_TYPE_ANY == m->type) || - (m->type == type) ) && - ( (NULL == m->key) || - (0 == memcmp (key, - m->key, - sizeof(struct GNUNET_HashCode))) ) ) { - struct GNUNET_MQ_Envelope *env; - struct GNUNET_DHT_MonitorGetMessage *mmsg; - struct GNUNET_PeerIdentity *msg_path; - size_t msize; - unsigned int i; - - /* Don't send duplicates */ - for (i = 0; i < cl_size; i++) - if (cl[i] == m->ch) - break; - if (i < cl_size) - continue; - GNUNET_array_append (cl, - cl_size, - m->ch); - - msize = path_length * sizeof (struct GNUNET_PeerIdentity); - env = GNUNET_MQ_msg_extra (mmsg, - msize, - GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET); - mmsg->options = htonl(options); - mmsg->type = htonl(type); - mmsg->hop_count = htonl(hop_count); - mmsg->desired_replication_level = htonl(desired_replication_level); - mmsg->get_path_length = htonl(path_length); - mmsg->key = *key; - msg_path = (struct GNUNET_PeerIdentity *) &mmsg[1]; - GNUNET_memcpy (msg_path, - path, - path_length * sizeof (struct GNUNET_PeerIdentity)); - GNUNET_MQ_send (m->ch->mq, - env); + if (((GNUNET_BLOCK_TYPE_ANY == m->type) || + (m->type == type)) && + ((NULL == m->key) || + (0 == memcmp(key, + m->key, + sizeof(struct GNUNET_HashCode))))) + { + struct GNUNET_MQ_Envelope *env; + struct GNUNET_DHT_MonitorGetMessage *mmsg; + struct GNUNET_PeerIdentity *msg_path; + size_t msize; + unsigned int i; + + /* Don't send duplicates */ + for (i = 0; i < cl_size; i++) + if (cl[i] == m->ch) + break; + if (i < cl_size) + continue; + GNUNET_array_append(cl, + cl_size, + m->ch); + + msize = path_length * sizeof(struct GNUNET_PeerIdentity); + env = GNUNET_MQ_msg_extra(mmsg, + msize, + GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET); + mmsg->options = htonl(options); + mmsg->type = htonl(type); + mmsg->hop_count = htonl(hop_count); + mmsg->desired_replication_level = htonl(desired_replication_level); + mmsg->get_path_length = htonl(path_length); + mmsg->key = *key; + msg_path = (struct GNUNET_PeerIdentity *)&mmsg[1]; + GNUNET_memcpy(msg_path, + path, + path_length * sizeof(struct GNUNET_PeerIdentity)); + GNUNET_MQ_send(m->ch->mq, + env); + } } - } - GNUNET_free_non_null (cl); + GNUNET_free_non_null(cl); } @@ -1283,15 +1278,15 @@ GDS_CLIENTS_process_get (uint32_t options, * @param size Number of bytes in @a data. */ void -GDS_CLIENTS_process_get_resp (enum GNUNET_BLOCK_Type type, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode * key, - const void *data, - size_t size) +GDS_CLIENTS_process_get_resp(enum GNUNET_BLOCK_Type type, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode * key, + const void *data, + size_t size) { struct ClientMonitorRecord *m; struct ClientHandle **cl; @@ -1300,53 +1295,53 @@ GDS_CLIENTS_process_get_resp (enum GNUNET_BLOCK_Type type, cl = NULL; cl_size = 0; for (m = monitor_head; NULL != m; m = m->next) - { - if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) && - (NULL == m->key || - memcmp (key, m->key, sizeof(struct GNUNET_HashCode)) == 0)) { - struct GNUNET_MQ_Envelope *env; - struct GNUNET_DHT_MonitorGetRespMessage *mmsg; - struct GNUNET_PeerIdentity *path; - size_t msize; - unsigned int i; - - /* Don't send duplicates */ - for (i = 0; i < cl_size; i++) - if (cl[i] == m->ch) - break; - if (i < cl_size) - continue; - GNUNET_array_append (cl, - cl_size, - m->ch); - - msize = size; - msize += (get_path_length + put_path_length) - * sizeof (struct GNUNET_PeerIdentity); - env = GNUNET_MQ_msg_extra (mmsg, - msize, - GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET_RESP); - mmsg->type = htonl(type); - mmsg->put_path_length = htonl(put_path_length); - mmsg->get_path_length = htonl(get_path_length); - mmsg->expiration_time = GNUNET_TIME_absolute_hton(exp); - mmsg->key = *key; - path = (struct GNUNET_PeerIdentity *) &mmsg[1]; - GNUNET_memcpy (path, - put_path, - put_path_length * sizeof (struct GNUNET_PeerIdentity)); - GNUNET_memcpy (path, - get_path, - get_path_length * sizeof (struct GNUNET_PeerIdentity)); - GNUNET_memcpy (&path[get_path_length], - data, - size); - GNUNET_MQ_send (m->ch->mq, - env); + if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) && + (NULL == m->key || + memcmp(key, m->key, sizeof(struct GNUNET_HashCode)) == 0)) + { + struct GNUNET_MQ_Envelope *env; + struct GNUNET_DHT_MonitorGetRespMessage *mmsg; + struct GNUNET_PeerIdentity *path; + size_t msize; + unsigned int i; + + /* Don't send duplicates */ + for (i = 0; i < cl_size; i++) + if (cl[i] == m->ch) + break; + if (i < cl_size) + continue; + GNUNET_array_append(cl, + cl_size, + m->ch); + + msize = size; + msize += (get_path_length + put_path_length) + * sizeof(struct GNUNET_PeerIdentity); + env = GNUNET_MQ_msg_extra(mmsg, + msize, + GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET_RESP); + mmsg->type = htonl(type); + mmsg->put_path_length = htonl(put_path_length); + mmsg->get_path_length = htonl(get_path_length); + mmsg->expiration_time = GNUNET_TIME_absolute_hton(exp); + mmsg->key = *key; + path = (struct GNUNET_PeerIdentity *)&mmsg[1]; + GNUNET_memcpy(path, + put_path, + put_path_length * sizeof(struct GNUNET_PeerIdentity)); + GNUNET_memcpy(path, + get_path, + get_path_length * sizeof(struct GNUNET_PeerIdentity)); + GNUNET_memcpy(&path[get_path_length], + data, + size); + GNUNET_MQ_send(m->ch->mq, + env); + } } - } - GNUNET_free_non_null (cl); + GNUNET_free_non_null(cl); } @@ -1366,16 +1361,16 @@ GDS_CLIENTS_process_get_resp (enum GNUNET_BLOCK_Type type, * @param size Number of bytes in data. */ void -GDS_CLIENTS_process_put (uint32_t options, - enum GNUNET_BLOCK_Type type, - uint32_t hop_count, - uint32_t desired_replication_level, - unsigned int path_length, - const struct GNUNET_PeerIdentity *path, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const void *data, - size_t size) +GDS_CLIENTS_process_put(uint32_t options, + enum GNUNET_BLOCK_Type type, + uint32_t hop_count, + uint32_t desired_replication_level, + unsigned int path_length, + const struct GNUNET_PeerIdentity *path, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const void *data, + size_t size) { struct ClientMonitorRecord *m; struct ClientHandle **cl; @@ -1384,51 +1379,51 @@ GDS_CLIENTS_process_put (uint32_t options, cl = NULL; cl_size = 0; for (m = monitor_head; NULL != m; m = m->next) - { - if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) && - (NULL == m->key || - memcmp (key, m->key, sizeof(struct GNUNET_HashCode)) == 0)) { - struct GNUNET_MQ_Envelope *env; - struct GNUNET_DHT_MonitorPutMessage *mmsg; - struct GNUNET_PeerIdentity *msg_path; - size_t msize; - unsigned int i; - - /* Don't send duplicates */ - for (i = 0; i < cl_size; i++) - if (cl[i] == m->ch) - break; - if (i < cl_size) - continue; - GNUNET_array_append (cl, - cl_size, - m->ch); - - msize = size; - msize += path_length * sizeof (struct GNUNET_PeerIdentity); - env = GNUNET_MQ_msg_extra (mmsg, - msize, - GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT); - mmsg->options = htonl(options); - mmsg->type = htonl(type); - mmsg->hop_count = htonl(hop_count); - mmsg->desired_replication_level = htonl (desired_replication_level); - mmsg->put_path_length = htonl (path_length); - mmsg->key = *key; - mmsg->expiration_time = GNUNET_TIME_absolute_hton (exp); - msg_path = (struct GNUNET_PeerIdentity *) &mmsg[1]; - GNUNET_memcpy (msg_path, - path, - path_length * sizeof (struct GNUNET_PeerIdentity)); - GNUNET_memcpy (&msg_path[path_length], - data, - size); - GNUNET_MQ_send (m->ch->mq, - env); + if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) && + (NULL == m->key || + memcmp(key, m->key, sizeof(struct GNUNET_HashCode)) == 0)) + { + struct GNUNET_MQ_Envelope *env; + struct GNUNET_DHT_MonitorPutMessage *mmsg; + struct GNUNET_PeerIdentity *msg_path; + size_t msize; + unsigned int i; + + /* Don't send duplicates */ + for (i = 0; i < cl_size; i++) + if (cl[i] == m->ch) + break; + if (i < cl_size) + continue; + GNUNET_array_append(cl, + cl_size, + m->ch); + + msize = size; + msize += path_length * sizeof(struct GNUNET_PeerIdentity); + env = GNUNET_MQ_msg_extra(mmsg, + msize, + GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT); + mmsg->options = htonl(options); + mmsg->type = htonl(type); + mmsg->hop_count = htonl(hop_count); + mmsg->desired_replication_level = htonl(desired_replication_level); + mmsg->put_path_length = htonl(path_length); + mmsg->key = *key; + mmsg->expiration_time = GNUNET_TIME_absolute_hton(exp); + msg_path = (struct GNUNET_PeerIdentity *)&mmsg[1]; + GNUNET_memcpy(msg_path, + path, + path_length * sizeof(struct GNUNET_PeerIdentity)); + GNUNET_memcpy(&msg_path[path_length], + data, + size); + GNUNET_MQ_send(m->ch->mq, + env); + } } - } - GNUNET_free_non_null (cl); + GNUNET_free_non_null(cl); } @@ -1438,13 +1433,13 @@ GDS_CLIENTS_process_put (uint32_t options, * @param server the initialized server */ static void -GDS_CLIENTS_init () +GDS_CLIENTS_init() { forward_map - = GNUNET_CONTAINER_multihashmap_create (1024, - GNUNET_YES); + = GNUNET_CONTAINER_multihashmap_create(1024, + GNUNET_YES); retry_heap - = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); + = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN); } @@ -1452,13 +1447,13 @@ GDS_CLIENTS_init () * Shutdown client subsystem. */ static void -GDS_CLIENTS_stop () +GDS_CLIENTS_stop() { if (NULL != retry_task) - { - GNUNET_SCHEDULER_cancel (retry_task); - retry_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(retry_task); + retry_task = NULL; + } } @@ -1468,59 +1463,59 @@ GDS_CLIENTS_stop () * @param name name of the service, i.e. "dht" or "xdht" * @param run name of the initializaton method for the service */ -#define GDS_DHT_SERVICE_INIT(name,run) \ - GNUNET_SERVICE_MAIN \ - (name, \ - GNUNET_SERVICE_OPTION_NONE, \ - run, \ - &client_connect_cb, \ - &client_disconnect_cb, \ - NULL, \ - GNUNET_MQ_hd_var_size (dht_local_put, \ - GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT, \ - struct GNUNET_DHT_ClientPutMessage, \ - NULL), \ - GNUNET_MQ_hd_var_size (dht_local_get, \ - GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET, \ - struct GNUNET_DHT_ClientGetMessage, \ - NULL), \ - GNUNET_MQ_hd_fixed_size (dht_local_get_stop, \ - GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP, \ - struct GNUNET_DHT_ClientGetStopMessage, \ +#define GDS_DHT_SERVICE_INIT(name, run) \ + GNUNET_SERVICE_MAIN \ + (name, \ + GNUNET_SERVICE_OPTION_NONE, \ + run, \ + &client_connect_cb, \ + &client_disconnect_cb, \ + NULL, \ + GNUNET_MQ_hd_var_size(dht_local_put, \ + GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT, \ + struct GNUNET_DHT_ClientPutMessage, \ + NULL), \ + GNUNET_MQ_hd_var_size(dht_local_get, \ + GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET, \ + struct GNUNET_DHT_ClientGetMessage, \ NULL), \ - GNUNET_MQ_hd_fixed_size (dht_local_monitor, \ - GNUNET_MESSAGE_TYPE_DHT_MONITOR_START, \ - struct GNUNET_DHT_MonitorStartStopMessage, \ - NULL), \ - GNUNET_MQ_hd_fixed_size (dht_local_monitor_stop, \ - GNUNET_MESSAGE_TYPE_DHT_MONITOR_STOP, \ - struct GNUNET_DHT_MonitorStartStopMessage, \ - NULL), \ - GNUNET_MQ_hd_var_size (dht_local_get_result_seen, \ - GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_RESULTS_KNOWN, \ - struct GNUNET_DHT_ClientGetResultSeenMessage , \ - NULL), \ - GNUNET_MQ_handler_end ()) + GNUNET_MQ_hd_fixed_size(dht_local_get_stop, \ + GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP, \ + struct GNUNET_DHT_ClientGetStopMessage, \ + NULL), \ + GNUNET_MQ_hd_fixed_size(dht_local_monitor, \ + GNUNET_MESSAGE_TYPE_DHT_MONITOR_START, \ + struct GNUNET_DHT_MonitorStartStopMessage, \ + NULL), \ + GNUNET_MQ_hd_fixed_size(dht_local_monitor_stop, \ + GNUNET_MESSAGE_TYPE_DHT_MONITOR_STOP, \ + struct GNUNET_DHT_MonitorStartStopMessage, \ + NULL), \ + GNUNET_MQ_hd_var_size(dht_local_get_result_seen, \ + GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_RESULTS_KNOWN, \ + struct GNUNET_DHT_ClientGetResultSeenMessage, \ + NULL), \ + GNUNET_MQ_handler_end()) /** * MINIMIZE heap size (way below 128k) since this process doesn't need much. */ void __attribute__ ((destructor)) -GDS_CLIENTS_done () +GDS_CLIENTS_done() { if (NULL != retry_heap) - { - GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (retry_heap)); - GNUNET_CONTAINER_heap_destroy (retry_heap); - retry_heap = NULL; - } + { + GNUNET_assert(0 == GNUNET_CONTAINER_heap_get_size(retry_heap)); + GNUNET_CONTAINER_heap_destroy(retry_heap); + retry_heap = NULL; + } if (NULL != forward_map) - { - GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (forward_map)); - GNUNET_CONTAINER_multihashmap_destroy (forward_map); - forward_map = NULL; - } + { + GNUNET_assert(0 == GNUNET_CONTAINER_multihashmap_size(forward_map)); + GNUNET_CONTAINER_multihashmap_destroy(forward_map); + forward_map = NULL; + } } /* end of gnunet-service-dht_clients.c */ diff --git a/src/dht/gnunet-service-dht_datacache.c b/src/dht/gnunet-service-dht_datacache.c index da71e3fb7..e52dc27bf 100644 --- a/src/dht/gnunet-service-dht_datacache.c +++ b/src/dht/gnunet-service-dht_datacache.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht_datacache.c * @brief GNUnet DHT service's datacache integration @@ -30,7 +30,7 @@ #include "gnunet-service-dht_routing.h" #include "gnunet-service-dht.h" -#define LOG(kind,...) GNUNET_log_from (kind, "dht-dhtcache",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "dht-dhtcache", __VA_ARGS__) /** * How many "closest" results to we return for migration when @@ -57,56 +57,55 @@ static struct GNUNET_DATACACHE_Handle *datacache; * @param data application payload data */ void -GDS_DATACACHE_handle_put (struct GNUNET_TIME_Absolute expiration, - const struct GNUNET_HashCode *key, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path, - enum GNUNET_BLOCK_Type type, - size_t data_size, - const void *data) +GDS_DATACACHE_handle_put(struct GNUNET_TIME_Absolute expiration, + const struct GNUNET_HashCode *key, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path, + enum GNUNET_BLOCK_Type type, + size_t data_size, + const void *data) { int r; if (NULL == datacache) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("%s request received, but have no datacache!\n"), "PUT"); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("%s request received, but have no datacache!\n"), "PUT"); + return; + } if (data_size >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } /* Put size is actual data size plus struct overhead plus path length (if any) */ - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# ITEMS stored in datacache"), - 1, - GNUNET_NO); - r = GNUNET_DATACACHE_put (datacache, - key, - GNUNET_CRYPTO_hash_matching_bits (key, - &my_identity_hash), - data_size, - data, - type, - expiration, - put_path_length, - put_path); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "DATACACHE PUT for key %s [%u] completed (%d) after %u hops\n", - GNUNET_h2s (key), - data_size, - r, - put_path_length); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# ITEMS stored in datacache"), + 1, + GNUNET_NO); + r = GNUNET_DATACACHE_put(datacache, + key, + GNUNET_CRYPTO_hash_matching_bits(key, + &my_identity_hash), + data_size, + data, + type, + expiration, + put_path_length, + put_path); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "DATACACHE PUT for key %s [%u] completed (%d) after %u hops\n", + GNUNET_h2s(key), + data_size, + r, + put_path_length); } /** * Context containing information about a GET request. */ -struct GetRequestContext -{ +struct GetRequestContext { /** * extended query (see gnunet_block_lib.h). */ @@ -141,7 +140,6 @@ struct GetRequestContext * Return value to give back. */ enum GNUNET_BLOCK_EvaluationResult eval; - }; @@ -160,94 +158,100 @@ struct GetRequestContext * to stop iteration. */ static int -datacache_get_iterator (void *cls, - const struct GNUNET_HashCode *key, - size_t data_size, - const char *data, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute exp, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path) +datacache_get_iterator(void *cls, + const struct GNUNET_HashCode *key, + size_t data_size, + const char *data, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute exp, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path) { static char non_null; struct GetRequestContext *ctx = cls; enum GNUNET_BLOCK_EvaluationResult eval; - if (0 == GNUNET_TIME_absolute_get_remaining (exp).rel_value_us) - { - GNUNET_break (0); /* why does datacache return expired values? */ - return GNUNET_OK; /* skip expired record */ - } - if ( (NULL == data) && - (0 == data_size) ) + if (0 == GNUNET_TIME_absolute_get_remaining(exp).rel_value_us) + { + GNUNET_break(0); /* why does datacache return expired values? */ + return GNUNET_OK; /* skip expired record */ + } + if ((NULL == data) && + (0 == data_size)) data = &non_null; /* point anywhere, but not to NULL */ eval - = GNUNET_BLOCK_evaluate (GDS_block_context, - type, - ctx->bg, - GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO, - key, - ctx->xquery, - ctx->xquery_size, - data, - data_size); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Found reply for query %s in datacache, evaluation result is %d\n", - GNUNET_h2s (key), - (int) eval); + = GNUNET_BLOCK_evaluate(GDS_block_context, + type, + ctx->bg, + GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO, + key, + ctx->xquery, + ctx->xquery_size, + data, + data_size); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Found reply for query %s in datacache, evaluation result is %d\n", + GNUNET_h2s(key), + (int)eval); ctx->eval = eval; switch (eval) - { - case GNUNET_BLOCK_EVALUATION_OK_MORE: - case GNUNET_BLOCK_EVALUATION_OK_LAST: - /* forward to local clients */ - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# Good RESULTS found in datacache"), 1, - GNUNET_NO); - ctx->gc (ctx->gc_cls, - type, - exp, - key, - put_path_length, put_path, - 0, NULL, - data, data_size); - break; - case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE: - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# Duplicate RESULTS found in datacache"), - 1, - GNUNET_NO); - break; - case GNUNET_BLOCK_EVALUATION_RESULT_INVALID: - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# Invalid RESULTS found in datacache"), - 1, - GNUNET_NO); - break; - case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT: - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# Irrelevant RESULTS found in datacache"), - 1, - GNUNET_NO); - break; - case GNUNET_BLOCK_EVALUATION_REQUEST_VALID: - GNUNET_break (0); - break; - case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID: - GNUNET_break_op (0); - return GNUNET_SYSERR; - case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED: - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# Unsupported RESULTS found in datacache"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Unsupported block type (%u) in local response!\n"), - type); - break; - } + { + case GNUNET_BLOCK_EVALUATION_OK_MORE: + case GNUNET_BLOCK_EVALUATION_OK_LAST: + /* forward to local clients */ + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# Good RESULTS found in datacache"), 1, + GNUNET_NO); + ctx->gc(ctx->gc_cls, + type, + exp, + key, + put_path_length, put_path, + 0, NULL, + data, data_size); + break; + + case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE: + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# Duplicate RESULTS found in datacache"), + 1, + GNUNET_NO); + break; + + case GNUNET_BLOCK_EVALUATION_RESULT_INVALID: + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# Invalid RESULTS found in datacache"), + 1, + GNUNET_NO); + break; + + case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT: + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# Irrelevant RESULTS found in datacache"), + 1, + GNUNET_NO); + break; + + case GNUNET_BLOCK_EVALUATION_REQUEST_VALID: + GNUNET_break(0); + break; + + case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID: + GNUNET_break_op(0); + return GNUNET_SYSERR; + + case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED: + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# Unsupported RESULTS found in datacache"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Unsupported block type (%u) in local response!\n"), + type); + break; + } return (eval == GNUNET_BLOCK_EVALUATION_OK_LAST) ? GNUNET_NO : GNUNET_OK; } @@ -265,23 +269,23 @@ datacache_get_iterator (void *cls, * @return evaluation result for the local replies */ enum GNUNET_BLOCK_EvaluationResult -GDS_DATACACHE_handle_get (const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - const void *xquery, - size_t xquery_size, - struct GNUNET_BLOCK_Group *bg, - GDS_DATACACHE_GetCallback gc, - void *gc_cls) +GDS_DATACACHE_handle_get(const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + const void *xquery, + size_t xquery_size, + struct GNUNET_BLOCK_Group *bg, + GDS_DATACACHE_GetCallback gc, + void *gc_cls) { struct GetRequestContext ctx; unsigned int r; if (NULL == datacache) return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# GET requests given to datacache"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# GET requests given to datacache"), + 1, + GNUNET_NO); ctx.eval = GNUNET_BLOCK_EVALUATION_REQUEST_VALID; ctx.key = *key; ctx.xquery = xquery; @@ -289,16 +293,16 @@ GDS_DATACACHE_handle_get (const struct GNUNET_HashCode *key, ctx.bg = bg; ctx.gc = gc; ctx.gc_cls = gc_cls; - r = GNUNET_DATACACHE_get (datacache, - key, - type, - &datacache_get_iterator, - &ctx); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "DATACACHE GET for key %s completed (%d). %u results found.\n", - GNUNET_h2s (key), - ctx.eval, - r); + r = GNUNET_DATACACHE_get(datacache, + key, + type, + &datacache_get_iterator, + &ctx); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "DATACACHE GET for key %s completed (%d). %u results found.\n", + GNUNET_h2s(key), + ctx.eval, + r); return ctx.eval; } @@ -318,14 +322,14 @@ GDS_DATACACHE_handle_get (const struct GNUNET_HashCode *key, * @return #GNUNET_OK to continue iterating, #GNUNET_SYSERR to abort */ static int -datacache_random_iterator (void *cls, - const struct GNUNET_HashCode *key, - size_t data_size, - const char *data, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute exp, - unsigned int path_info_len, - const struct GNUNET_PeerIdentity *path_info) +datacache_random_iterator(void *cls, + const struct GNUNET_HashCode *key, + size_t data_size, + const char *data, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute exp, + unsigned int path_info_len, + const struct GNUNET_PeerIdentity *path_info) { struct GNUNET_HashCode *dest = cls; @@ -343,18 +347,18 @@ datacache_random_iterator (void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR if the datacache is empty */ int -GDS_DATACACHE_get_random_key (struct GNUNET_HashCode *key) +GDS_DATACACHE_get_random_key(struct GNUNET_HashCode *key) { if (0 == - GNUNET_DATACACHE_get_random (datacache, - &datacache_random_iterator, - key)) - { - /* randomize key in this case */ - GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE, - key); - return GNUNET_SYSERR; - } + GNUNET_DATACACHE_get_random(datacache, + &datacache_random_iterator, + key)) + { + /* randomize key in this case */ + GNUNET_CRYPTO_hash_create_random(GNUNET_CRYPTO_QUALITY_NONCE, + key); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -362,8 +366,7 @@ GDS_DATACACHE_get_random_key (struct GNUNET_HashCode *key) /** * Closure for #datacache_get_successors_iterator(). */ -struct SuccContext -{ +struct SuccContext { /** * Function to call on the result */ @@ -391,14 +394,14 @@ struct SuccContext * to stop iteration. */ static int -datacache_get_successors_iterator (void *cls, - const struct GNUNET_HashCode *key, - size_t size, - const char *data, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute exp, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path) +datacache_get_successors_iterator(void *cls, + const struct GNUNET_HashCode *key, + size_t size, + const char *data, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute exp, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path) { const struct SuccContext *sc = cls; @@ -406,14 +409,14 @@ datacache_get_successors_iterator (void *cls, the original 'put', so we don't know the 'correct' option at this point anymore. Thus, we conservatively assume that recording is desired (for now). */ - sc->cb (sc->cb_cls, - GNUNET_DHT_RO_RECORD_ROUTE, - key, - type, - put_path_length, put_path, - exp, - data, - size); + sc->cb(sc->cb_cls, + GNUNET_DHT_RO_RECORD_ROUTE, + key, + type, + put_path_length, put_path, + exp, + data, + size); return GNUNET_OK; } @@ -427,19 +430,19 @@ datacache_get_successors_iterator (void *cls, * @param cb_cls closure for @a cb */ void -GDS_DATACACHE_get_successors (const struct GNUNET_HashCode *key, - GDS_DATACACHE_SuccessorCallback cb, - void *cb_cls) +GDS_DATACACHE_get_successors(const struct GNUNET_HashCode *key, + GDS_DATACACHE_SuccessorCallback cb, + void *cb_cls) { struct SuccContext sc; sc.cb = cb; sc.cb_cls = cb_cls; - (void) GNUNET_DATACACHE_get_closest (datacache, - key, - NUM_CLOSEST, - &datacache_get_successors_iterator, - &sc); + (void)GNUNET_DATACACHE_get_closest(datacache, + key, + NUM_CLOSEST, + &datacache_get_successors_iterator, + &sc); } @@ -447,9 +450,9 @@ GDS_DATACACHE_get_successors (const struct GNUNET_HashCode *key, * Initialize datacache subsystem. */ void -GDS_DATACACHE_init () +GDS_DATACACHE_init() { - datacache = GNUNET_DATACACHE_create (GDS_cfg, "dhtcache"); + datacache = GNUNET_DATACACHE_create(GDS_cfg, "dhtcache"); } @@ -457,13 +460,13 @@ GDS_DATACACHE_init () * Shutdown datacache subsystem. */ void -GDS_DATACACHE_done () +GDS_DATACACHE_done() { if (NULL != datacache) - { - GNUNET_DATACACHE_destroy (datacache); - datacache = NULL; - } + { + GNUNET_DATACACHE_destroy(datacache); + datacache = NULL; + } } diff --git a/src/dht/gnunet-service-dht_datacache.h b/src/dht/gnunet-service-dht_datacache.h index bbbeb386e..e376aa1c1 100644 --- a/src/dht/gnunet-service-dht_datacache.h +++ b/src/dht/gnunet-service-dht_datacache.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht_datacache.h @@ -44,13 +44,13 @@ * @param data application payload data */ void -GDS_DATACACHE_handle_put (struct GNUNET_TIME_Absolute expiration, - const struct GNUNET_HashCode *key, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path, - enum GNUNET_BLOCK_Type type, - size_t data_size, - const void *data); +GDS_DATACACHE_handle_put(struct GNUNET_TIME_Absolute expiration, + const struct GNUNET_HashCode *key, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path, + enum GNUNET_BLOCK_Type type, + size_t data_size, + const void *data); /** @@ -93,13 +93,13 @@ typedef void * @return evaluation result for the local replies */ enum GNUNET_BLOCK_EvaluationResult -GDS_DATACACHE_handle_get (const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - const void *xquery, - size_t xquery_size, - struct GNUNET_BLOCK_Group *bg, - GDS_DATACACHE_GetCallback gc, - void *gc_cls); +GDS_DATACACHE_handle_get(const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + const void *xquery, + size_t xquery_size, + struct GNUNET_BLOCK_Group *bg, + GDS_DATACACHE_GetCallback gc, + void *gc_cls); /** @@ -111,7 +111,7 @@ GDS_DATACACHE_handle_get (const struct GNUNET_HashCode *key, * @return #GNUNET_OK on success, #GNUNET_SYSERR if the datacache is empty */ int -GDS_DATACACHE_get_random_key (struct GNUNET_HashCode *key); +GDS_DATACACHE_get_random_key(struct GNUNET_HashCode *key); /** @@ -148,22 +148,22 @@ typedef void * @param cb_cls closure for @a cb */ void -GDS_DATACACHE_get_successors (const struct GNUNET_HashCode *key, - GDS_DATACACHE_SuccessorCallback cb, - void *cb_cls); +GDS_DATACACHE_get_successors(const struct GNUNET_HashCode *key, + GDS_DATACACHE_SuccessorCallback cb, + void *cb_cls); /** * Initialize datacache subsystem. */ void -GDS_DATACACHE_init (void); +GDS_DATACACHE_init(void); /** * Shutdown datacache subsystem. */ void -GDS_DATACACHE_done (void); +GDS_DATACACHE_done(void); #endif diff --git a/src/dht/gnunet-service-dht_hello.c b/src/dht/gnunet-service-dht_hello.c index fd1003bd2..49641e649 100644 --- a/src/dht/gnunet-service-dht_hello.c +++ b/src/dht/gnunet-service-dht_hello.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht_hello.c @@ -50,11 +50,11 @@ static struct GNUNET_CONTAINER_MultiPeerMap *peer_to_hello; * @return HELLO for the given peer */ const struct GNUNET_HELLO_Message * -GDS_HELLO_get (const struct GNUNET_PeerIdentity *peer) +GDS_HELLO_get(const struct GNUNET_PeerIdentity *peer) { if (NULL == peer_to_hello) return NULL; - return GNUNET_CONTAINER_multipeermap_get (peer_to_hello, peer); + return GNUNET_CONTAINER_multipeermap_get(peer_to_hello, peer); } @@ -69,30 +69,30 @@ GDS_HELLO_get (const struct GNUNET_PeerIdentity *peer) * FIXME this is called once per address. Merge instead of replacing? */ static void -process_hello (void *cls, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello, - const char *err_msg) +process_hello(void *cls, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello, + const char *err_msg) { struct GNUNET_TIME_Absolute ex; struct GNUNET_HELLO_Message *hm; if (NULL == hello) return; - ex = GNUNET_HELLO_get_last_expiration (hello); - if (0 == GNUNET_TIME_absolute_get_remaining (ex).rel_value_us) + ex = GNUNET_HELLO_get_last_expiration(hello); + if (0 == GNUNET_TIME_absolute_get_remaining(ex).rel_value_us) return; - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# HELLOs obtained from peerinfo"), 1, - GNUNET_NO); - hm = GNUNET_CONTAINER_multipeermap_get (peer_to_hello, peer); - GNUNET_free_non_null (hm); - hm = GNUNET_malloc (GNUNET_HELLO_size (hello)); - GNUNET_memcpy (hm, hello, GNUNET_HELLO_size (hello)); - GNUNET_assert (GNUNET_SYSERR != - GNUNET_CONTAINER_multipeermap_put (peer_to_hello, - peer, hm, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE)); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# HELLOs obtained from peerinfo"), 1, + GNUNET_NO); + hm = GNUNET_CONTAINER_multipeermap_get(peer_to_hello, peer); + GNUNET_free_non_null(hm); + hm = GNUNET_malloc(GNUNET_HELLO_size(hello)); + GNUNET_memcpy(hm, hello, GNUNET_HELLO_size(hello)); + GNUNET_assert(GNUNET_SYSERR != + GNUNET_CONTAINER_multipeermap_put(peer_to_hello, + peer, hm, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE)); } @@ -100,14 +100,14 @@ process_hello (void *cls, * Initialize HELLO subsystem. */ void -GDS_HELLO_init () +GDS_HELLO_init() { - pnc = GNUNET_PEERINFO_notify (GDS_cfg, - GNUNET_NO, - &process_hello, - NULL); - peer_to_hello = GNUNET_CONTAINER_multipeermap_create (256, - GNUNET_NO); + pnc = GNUNET_PEERINFO_notify(GDS_cfg, + GNUNET_NO, + &process_hello, + NULL); + peer_to_hello = GNUNET_CONTAINER_multipeermap_create(256, + GNUNET_NO); } @@ -115,11 +115,11 @@ GDS_HELLO_init () * Free memory occopied by the HELLO. */ static int -free_hello (void *cls, - const struct GNUNET_PeerIdentity *key, - void *hello) +free_hello(void *cls, + const struct GNUNET_PeerIdentity *key, + void *hello) { - GNUNET_free (hello); + GNUNET_free(hello); return GNUNET_OK; } @@ -128,20 +128,20 @@ free_hello (void *cls, * Shutdown HELLO subsystem. */ void -GDS_HELLO_done () +GDS_HELLO_done() { if (NULL != pnc) - { - GNUNET_PEERINFO_notify_cancel (pnc); - pnc = NULL; - } + { + GNUNET_PEERINFO_notify_cancel(pnc); + pnc = NULL; + } if (NULL != peer_to_hello) - { - GNUNET_CONTAINER_multipeermap_iterate (peer_to_hello, - &free_hello, - NULL); - GNUNET_CONTAINER_multipeermap_destroy (peer_to_hello); - } + { + GNUNET_CONTAINER_multipeermap_iterate(peer_to_hello, + &free_hello, + NULL); + GNUNET_CONTAINER_multipeermap_destroy(peer_to_hello); + } } /* end of gnunet-service-dht_hello.c */ diff --git a/src/dht/gnunet-service-dht_hello.h b/src/dht/gnunet-service-dht_hello.h index 0927c89ee..929677839 100644 --- a/src/dht/gnunet-service-dht_hello.h +++ b/src/dht/gnunet-service-dht_hello.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht_hello.h @@ -36,20 +36,20 @@ * @return HELLO for the given peer */ const struct GNUNET_HELLO_Message * -GDS_HELLO_get (const struct GNUNET_PeerIdentity *peer); +GDS_HELLO_get(const struct GNUNET_PeerIdentity *peer); /** * Initialize HELLO subsystem. */ void -GDS_HELLO_init (void); +GDS_HELLO_init(void); /** * Shutdown HELLO subsystem. */ void -GDS_HELLO_done (void); +GDS_HELLO_done(void); #endif diff --git a/src/dht/gnunet-service-dht_neighbours.c b/src/dht/gnunet-service-dht_neighbours.c index 4f040558a..90ef5429f 100644 --- a/src/dht/gnunet-service-dht_neighbours.c +++ b/src/dht/gnunet-service-dht_neighbours.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht_neighbours.c @@ -46,7 +46,7 @@ #include "gnunet-service-dht_routing.h" #include "dht.h" -#define LOG_TRAFFIC(kind,...) GNUNET_log_from (kind, "dht-traffic",__VA_ARGS__) +#define LOG_TRAFFIC(kind, ...) GNUNET_log_from(kind, "dht-traffic", __VA_ARGS__) /** * Enable slow sanity checks to debug issues. @@ -56,7 +56,7 @@ /** * How many buckets will we allow total. */ -#define MAX_BUCKETS sizeof (struct GNUNET_HashCode) * 8 +#define MAX_BUCKETS sizeof(struct GNUNET_HashCode) * 8 /** * What is the maximum number of peers in a given bucket. @@ -104,8 +104,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * P2P PUT message */ -struct PeerPutMessage -{ +struct PeerPutMessage { /** * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_PUT */ @@ -154,15 +153,13 @@ struct PeerPutMessage /* put path (if tracked) */ /* Payload */ - }; /** * P2P Result message */ -struct PeerResultMessage -{ +struct PeerResultMessage { /** * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT */ @@ -198,15 +195,13 @@ struct PeerResultMessage /* get path (if tracked) */ /* Payload */ - }; /** * P2P GET message */ -struct PeerGetMessage -{ +struct PeerGetMessage { /** * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_GET */ @@ -255,7 +250,6 @@ struct PeerGetMessage /* xquery */ /* result bloomfilter */ - }; GNUNET_NETWORK_STRUCT_END @@ -263,8 +257,7 @@ GNUNET_NETWORK_STRUCT_END /** * Entry for a peer in a bucket. */ -struct PeerInfo -{ +struct PeerInfo { /** * Next peer entry (DLL) */ @@ -294,15 +287,13 @@ struct PeerInfo * Which bucket is this peer in? */ int peer_bucket; - }; /** * Peers are grouped into buckets. */ -struct PeerBucket -{ +struct PeerBucket { /** * Head of DLL */ @@ -323,9 +314,7 @@ struct PeerBucket /** * Information about a peer that we would like to connect to. */ -struct ConnectInfo -{ - +struct ConnectInfo { /** * Handle to active HELLO offer operation, or NULL. */ @@ -425,17 +414,17 @@ static struct GNUNET_ATS_ConnectivityHandle *ats_ch; * on error (same hashcode) */ static int -find_bucket (const struct GNUNET_HashCode *hc) +find_bucket(const struct GNUNET_HashCode *hc) { unsigned int bits; - bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, hc); + bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity_hash, hc); if (bits == MAX_BUCKETS) - { - /* How can all bits match? Got my own ID? */ - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + /* How can all bits match? Got my own ID? */ + GNUNET_break(0); + return GNUNET_SYSERR; + } return MAX_BUCKETS - bits - 1; } @@ -447,7 +436,7 @@ find_bucket (const struct GNUNET_HashCode *hc) * @param cls a `struct ConnectInfo` */ static void -offer_hello_done (void *cls) +offer_hello_done(void *cls) { struct ConnectInfo *ci = cls; @@ -464,28 +453,28 @@ offer_hello_done (void *cls) * @return #GNUNET_YES */ static int -free_connect_info (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *value) +free_connect_info(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *value) { struct ConnectInfo *ci = value; - (void) cls; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (all_desired_peers, - peer, - ci)); + (void)cls; + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(all_desired_peers, + peer, + ci)); if (NULL != ci->sh) - { - GNUNET_ATS_connectivity_suggest_cancel (ci->sh); - ci->sh = NULL; - } + { + GNUNET_ATS_connectivity_suggest_cancel(ci->sh); + ci->sh = NULL; + } if (NULL != ci->oh) - { - GNUNET_TRANSPORT_offer_hello_cancel (ci->oh); - ci->oh = NULL; - } - GNUNET_free (ci); + { + GNUNET_TRANSPORT_offer_hello_cancel(ci->oh); + ci->oh = NULL; + } + GNUNET_free(ci); return GNUNET_YES; } @@ -499,68 +488,68 @@ free_connect_info (void *cls, * @param h a HELLO message, or NULL */ static void -try_connect (const struct GNUNET_PeerIdentity *pid, - const struct GNUNET_MessageHeader *h) +try_connect(const struct GNUNET_PeerIdentity *pid, + const struct GNUNET_MessageHeader *h) { int bucket; struct GNUNET_HashCode pid_hash; struct ConnectInfo *ci; uint32_t strength; - GNUNET_CRYPTO_hash (pid, - sizeof (struct GNUNET_PeerIdentity), - &pid_hash); - bucket = find_bucket (&pid_hash); + GNUNET_CRYPTO_hash(pid, + sizeof(struct GNUNET_PeerIdentity), + &pid_hash); + bucket = find_bucket(&pid_hash); if (bucket < 0) return; /* self? */ - ci = GNUNET_CONTAINER_multipeermap_get (all_desired_peers, - pid); + ci = GNUNET_CONTAINER_multipeermap_get(all_desired_peers, + pid); if (k_buckets[bucket].peers_size < bucket_size) strength = (bucket_size - k_buckets[bucket].peers_size) * bucket; else strength = bucket; /* minimum value of connectivity */ if (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_contains (all_connected_peers, - pid)) + GNUNET_CONTAINER_multipeermap_contains(all_connected_peers, + pid)) strength *= 2; /* double for connected peers */ else if (k_buckets[bucket].peers_size > bucket_size) strength = 0; /* bucket full, we really do not care about more */ - if ( (0 == strength) && - (NULL != ci) ) - { - /* release request */ - GNUNET_assert (GNUNET_YES == - free_connect_info (NULL, + if ((0 == strength) && + (NULL != ci)) + { + /* release request */ + GNUNET_assert(GNUNET_YES == + free_connect_info(NULL, pid, ci)); - return; - } + return; + } if (NULL == ci) - { - ci = GNUNET_new (struct ConnectInfo); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put (all_desired_peers, + { + ci = GNUNET_new(struct ConnectInfo); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_put(all_desired_peers, pid, ci, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - } - if ( (NULL != ci->oh) && - (NULL != h) ) - GNUNET_TRANSPORT_offer_hello_cancel (ci->oh); + } + if ((NULL != ci->oh) && + (NULL != h)) + GNUNET_TRANSPORT_offer_hello_cancel(ci->oh); if (NULL != h) - ci->oh = GNUNET_TRANSPORT_offer_hello (GDS_cfg, - h, - &offer_hello_done, - ci); - if ( (NULL != ci->sh) && - (ci->strength != strength) ) - GNUNET_ATS_connectivity_suggest_cancel (ci->sh); + ci->oh = GNUNET_TRANSPORT_offer_hello(GDS_cfg, + h, + &offer_hello_done, + ci); + if ((NULL != ci->sh) && + (ci->strength != strength)) + GNUNET_ATS_connectivity_suggest_cancel(ci->sh); if (ci->strength != strength) - ci->sh = GNUNET_ATS_connectivity_suggest (ats_ch, - pid, - strength); + ci->sh = GNUNET_ATS_connectivity_suggest(ats_ch, + pid, + strength); ci->strength = strength; } @@ -578,14 +567,14 @@ try_connect (const struct GNUNET_PeerIdentity *pid, * @return #GNUNET_YES (continue to iterate) */ static int -update_desire_strength (void *cls, - const struct GNUNET_PeerIdentity *pid, - void *value) +update_desire_strength(void *cls, + const struct GNUNET_PeerIdentity *pid, + void *value) { - (void) cls; - (void) value; - try_connect (pid, - NULL); + (void)cls; + (void)value; + try_connect(pid, + NULL); return GNUNET_YES; } @@ -597,11 +586,11 @@ update_desire_strength (void *cls, * @param tc scheduler context. */ static void -update_connect_preferences () +update_connect_preferences() { - GNUNET_CONTAINER_multipeermap_iterate (all_desired_peers, - &update_desire_strength, - NULL); + GNUNET_CONTAINER_multipeermap_iterate(all_desired_peers, + &update_desire_strength, + NULL); } @@ -615,24 +604,24 @@ update_connect_preferences () * @return #GNUNET_YES (we should continue to iterate) */ static int -add_known_to_bloom (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +add_known_to_bloom(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct GNUNET_BLOCK_Group *bg = cls; struct GNUNET_HashCode key_hash; - (void) cls; - (void) value; - GNUNET_CRYPTO_hash (key, - sizeof (struct GNUNET_PeerIdentity), - &key_hash); - GNUNET_BLOCK_group_set_seen (bg, - &key_hash, - 1); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding known peer (%s) to bloomfilter for FIND PEER\n", - GNUNET_i2s (key)); + (void)cls; + (void)value; + GNUNET_CRYPTO_hash(key, + sizeof(struct GNUNET_PeerIdentity), + &key_hash); + GNUNET_BLOCK_group_set_seen(bg, + &key_hash, + 1); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding known peer (%s) to bloomfilter for FIND PEER\n", + GNUNET_i2s(key)); return GNUNET_YES; } @@ -645,68 +634,68 @@ add_known_to_bloom (void *cls, * @param cls closure for this task */ static void -send_find_peer_message (void *cls) +send_find_peer_message(void *cls) { struct GNUNET_TIME_Relative next_send_time; struct GNUNET_BLOCK_Group *bg; struct GNUNET_CONTAINER_BloomFilter *peer_bf; - (void) cls; - find_peer_task = NULL; + (void)cls; + find_peer_task = NULL; if (newly_found_peers > bucket_size) - { - /* If we are finding many peers already, no need to send out our request right now! */ - find_peer_task = - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, - &send_find_peer_message, - NULL); - newly_found_peers = 0; - return; - } - bg = GNUNET_BLOCK_group_create (GDS_block_context, - GNUNET_BLOCK_TYPE_DHT_HELLO, - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT32_MAX), - NULL, - 0, - "filter-size", - DHT_BLOOM_SIZE, - NULL); - GNUNET_CONTAINER_multipeermap_iterate (all_connected_peers, - &add_known_to_bloom, - bg); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# FIND PEER messages initiated"), - 1, - GNUNET_NO); + { + /* If we are finding many peers already, no need to send out our request right now! */ + find_peer_task = + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES, + &send_find_peer_message, + NULL); + newly_found_peers = 0; + return; + } + bg = GNUNET_BLOCK_group_create(GDS_block_context, + GNUNET_BLOCK_TYPE_DHT_HELLO, + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + UINT32_MAX), + NULL, + 0, + "filter-size", + DHT_BLOOM_SIZE, + NULL); + GNUNET_CONTAINER_multipeermap_iterate(all_connected_peers, + &add_known_to_bloom, + bg); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# FIND PEER messages initiated"), + 1, + GNUNET_NO); peer_bf - = GNUNET_CONTAINER_bloomfilter_init (NULL, - DHT_BLOOM_SIZE, - GNUNET_CONSTANTS_BLOOMFILTER_K); + = GNUNET_CONTAINER_bloomfilter_init(NULL, + DHT_BLOOM_SIZE, + GNUNET_CONSTANTS_BLOOMFILTER_K); // FIXME: pass priority!? - GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO, - GNUNET_DHT_RO_FIND_PEER | GNUNET_DHT_RO_RECORD_ROUTE, - FIND_PEER_REPLICATION_LEVEL, - 0, - &my_identity_hash, - NULL, - 0, - bg, - peer_bf); - GNUNET_CONTAINER_bloomfilter_free (peer_bf); - GNUNET_BLOCK_group_destroy (bg); + GDS_NEIGHBOURS_handle_get(GNUNET_BLOCK_TYPE_DHT_HELLO, + GNUNET_DHT_RO_FIND_PEER | GNUNET_DHT_RO_RECORD_ROUTE, + FIND_PEER_REPLICATION_LEVEL, + 0, + &my_identity_hash, + NULL, + 0, + bg, + peer_bf); + GNUNET_CONTAINER_bloomfilter_free(peer_bf); + GNUNET_BLOCK_group_destroy(bg); /* schedule next round */ next_send_time.rel_value_us = - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value_us + - GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, - DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value_us / - (newly_found_peers + 1)); + DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value_us + + GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, + DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value_us / + (newly_found_peers + 1)); newly_found_peers = 0; - GNUNET_assert (NULL == find_peer_task); + GNUNET_assert(NULL == find_peer_task); find_peer_task = - GNUNET_SCHEDULER_add_delayed (next_send_time, - &send_find_peer_message, - NULL); + GNUNET_SCHEDULER_add_delayed(next_send_time, + &send_find_peer_message, + NULL); } @@ -719,61 +708,61 @@ send_find_peer_message (void *cls) * @return our `struct PeerInfo` for @a peer */ static void * -handle_core_connect (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +handle_core_connect(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { struct PeerInfo *pi; - (void) cls; - /* Check for connect to self message */ - if (0 == GNUNET_memcmp (&my_identity, - peer)) + (void)cls; + /* Check for connect to self message */ + if (0 == GNUNET_memcmp(&my_identity, + peer)) return NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connected to %s\n", - GNUNET_i2s (peer)); - GNUNET_assert (GNUNET_NO == - GNUNET_CONTAINER_multipeermap_get (all_connected_peers, - peer)); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# peers connected"), - 1, - GNUNET_NO); - pi = GNUNET_new (struct PeerInfo); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connected to %s\n", + GNUNET_i2s(peer)); + GNUNET_assert(GNUNET_NO == + GNUNET_CONTAINER_multipeermap_get(all_connected_peers, + peer)); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# peers connected"), + 1, + GNUNET_NO); + pi = GNUNET_new(struct PeerInfo); pi->id = peer; pi->mq = mq; - GNUNET_CRYPTO_hash (peer, - sizeof (struct GNUNET_PeerIdentity), - &pi->phash); - pi->peer_bucket = find_bucket (&pi->phash); - GNUNET_assert ( (pi->peer_bucket >= 0) && - ((unsigned int) pi->peer_bucket < MAX_BUCKETS) ); - GNUNET_CONTAINER_DLL_insert_tail (k_buckets[pi->peer_bucket].head, - k_buckets[pi->peer_bucket].tail, - pi); + GNUNET_CRYPTO_hash(peer, + sizeof(struct GNUNET_PeerIdentity), + &pi->phash); + pi->peer_bucket = find_bucket(&pi->phash); + GNUNET_assert((pi->peer_bucket >= 0) && + ((unsigned int)pi->peer_bucket < MAX_BUCKETS)); + GNUNET_CONTAINER_DLL_insert_tail(k_buckets[pi->peer_bucket].head, + k_buckets[pi->peer_bucket].tail, + pi); k_buckets[pi->peer_bucket].peers_size++; - closest_bucket = GNUNET_MAX (closest_bucket, - (unsigned int) pi->peer_bucket); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put (all_connected_peers, - pi->id, - pi, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - if ( (pi->peer_bucket > 0) && - (k_buckets[pi->peer_bucket].peers_size <= bucket_size)) - { - update_connect_preferences (); - newly_found_peers++; - } - if ( (1 == GNUNET_CONTAINER_multipeermap_size (all_connected_peers)) && - (GNUNET_YES != disable_try_connect)) - { - /* got a first connection, good time to start with FIND PEER requests... */ - GNUNET_assert (NULL == find_peer_task); - find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message, - NULL); - } + closest_bucket = GNUNET_MAX(closest_bucket, + (unsigned int)pi->peer_bucket); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_put(all_connected_peers, + pi->id, + pi, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + if ((pi->peer_bucket > 0) && + (k_buckets[pi->peer_bucket].peers_size <= bucket_size)) + { + update_connect_preferences(); + newly_found_peers++; + } + if ((1 == GNUNET_CONTAINER_multipeermap_size(all_connected_peers)) && + (GNUNET_YES != disable_try_connect)) + { + /* got a first connection, good time to start with FIND PEER requests... */ + GNUNET_assert(NULL == find_peer_task); + find_peer_task = GNUNET_SCHEDULER_add_now(&send_find_peer_message, + NULL); + } return pi; } @@ -786,45 +775,45 @@ handle_core_connect (void *cls, * @param internal_cls our `struct PeerInfo` for @a peer */ static void -handle_core_disconnect (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *internal_cls) +handle_core_disconnect(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *internal_cls) { struct PeerInfo *to_remove = internal_cls; - (void) cls; + (void)cls; /* Check for disconnect from self message */ if (NULL == to_remove) return; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Disconnected %s\n", - GNUNET_i2s (peer)); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# peers connected"), - -1, - GNUNET_NO); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (all_connected_peers, - peer, - to_remove)); - if ( (0 == GNUNET_CONTAINER_multipeermap_size (all_connected_peers)) && - (GNUNET_YES != disable_try_connect) ) - { - GNUNET_SCHEDULER_cancel (find_peer_task); - find_peer_task = NULL; - } - GNUNET_assert (to_remove->peer_bucket >= 0); - GNUNET_CONTAINER_DLL_remove (k_buckets[to_remove->peer_bucket].head, - k_buckets[to_remove->peer_bucket].tail, - to_remove); - GNUNET_assert (k_buckets[to_remove->peer_bucket].peers_size > 0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Disconnected %s\n", + GNUNET_i2s(peer)); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# peers connected"), + -1, + GNUNET_NO); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(all_connected_peers, + peer, + to_remove)); + if ((0 == GNUNET_CONTAINER_multipeermap_size(all_connected_peers)) && + (GNUNET_YES != disable_try_connect)) + { + GNUNET_SCHEDULER_cancel(find_peer_task); + find_peer_task = NULL; + } + GNUNET_assert(to_remove->peer_bucket >= 0); + GNUNET_CONTAINER_DLL_remove(k_buckets[to_remove->peer_bucket].head, + k_buckets[to_remove->peer_bucket].tail, + to_remove); + GNUNET_assert(k_buckets[to_remove->peer_bucket].peers_size > 0); k_buckets[to_remove->peer_bucket].peers_size--; - while ( (closest_bucket > 0) && - (0 == k_buckets[to_remove->peer_bucket].peers_size) ) + while ((closest_bucket > 0) && + (0 == k_buckets[to_remove->peer_bucket].peers_size)) closest_bucket--; if (k_buckets[to_remove->peer_bucket].peers_size < bucket_size) - update_connect_preferences (); - GNUNET_free (to_remove); + update_connect_preferences(); + GNUNET_free(to_remove); } @@ -837,39 +826,39 @@ handle_core_disconnect (void *cls, * @return Some number of peers to forward the message to */ static unsigned int -get_forward_count (uint32_t hop_count, - uint32_t target_replication) +get_forward_count(uint32_t hop_count, + uint32_t target_replication) { uint32_t random_value; uint32_t forward_count; float target_value; - if (hop_count > GDS_NSE_get () * 4.0) - { - /* forcefully terminate */ - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# requests TTL-dropped"), - 1, GNUNET_NO); - return 0; - } - if (hop_count > GDS_NSE_get () * 2.0) - { - /* Once we have reached our ideal number of hops, only forward to 1 peer */ - return 1; - } + if (hop_count > GDS_NSE_get() * 4.0) + { + /* forcefully terminate */ + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# requests TTL-dropped"), + 1, GNUNET_NO); + return 0; + } + if (hop_count > GDS_NSE_get() * 2.0) + { + /* Once we have reached our ideal number of hops, only forward to 1 peer */ + return 1; + } /* bound by system-wide maximum */ target_replication = - GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication); + GNUNET_MIN(MAXIMUM_REPLICATION_LEVEL, target_replication); target_value = - 1 + (target_replication - 1.0) / (GDS_NSE_get () + - ((float) (target_replication - 1.0) * - hop_count)); + 1 + (target_replication - 1.0) / (GDS_NSE_get() + + ((float)(target_replication - 1.0) * + hop_count)); /* Set forward count to floor of target_value */ - forward_count = (uint32_t) target_value; + forward_count = (uint32_t)target_value; /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */ target_value = target_value - forward_count; random_value = - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX); + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX); if (random_value < (target_value * UINT32_MAX)) forward_count++; return forward_count; @@ -888,8 +877,8 @@ get_forward_count (uint32_t hop_count, * the two hash codes increases */ static unsigned int -get_distance (const struct GNUNET_HashCode *target, - const struct GNUNET_HashCode *have) +get_distance(const struct GNUNET_HashCode *target, + const struct GNUNET_HashCode *have) { unsigned int bucket; unsigned int msb; @@ -911,13 +900,13 @@ get_distance (const struct GNUNET_HashCode *target, /* first, calculate the most significant 9 bits of our * result, aka the number of LSBs */ - bucket = GNUNET_CRYPTO_hash_matching_bits (target, - have); + bucket = GNUNET_CRYPTO_hash_matching_bits(target, + have); /* bucket is now a value between 0 and 512 */ if (bucket == 512) return 0; /* perfect match */ if (bucket == 0) - return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting + return (unsigned int)-1; /* LSB differs; use max (if we did the bit-shifting * below, we'd end up with max+1 (overflow)) */ /* calculate the most significant bits of the final result */ @@ -927,14 +916,14 @@ get_distance (const struct GNUNET_HashCode *target, * mismatching bit at 'bucket' */ lsb = 0; for (i = bucket + 1; - (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++) - { - if (GNUNET_CRYPTO_hash_get_bit (target, i) != - GNUNET_CRYPTO_hash_get_bit (have, i)) - lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10, + (i < sizeof(struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++) + { + if (GNUNET_CRYPTO_hash_get_bit(target, i) != + GNUNET_CRYPTO_hash_get_bit(have, i)) + lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10, * last bit set will be 31 -- if * i does not reach 512 first... */ - } + } return msb | lsb; } @@ -950,40 +939,40 @@ get_distance (const struct GNUNET_HashCode *target, * #GNUNET_NO otherwise. */ int -GDS_am_closest_peer (const struct GNUNET_HashCode *key, - const struct GNUNET_CONTAINER_BloomFilter *bloom) +GDS_am_closest_peer(const struct GNUNET_HashCode *key, + const struct GNUNET_CONTAINER_BloomFilter *bloom) { int bits; int other_bits; int bucket_num; struct PeerInfo *pos; - if (0 == GNUNET_memcmp (&my_identity_hash, - key)) + if (0 == GNUNET_memcmp(&my_identity_hash, + key)) return GNUNET_YES; - bucket_num = find_bucket (key); - GNUNET_assert (bucket_num >= 0); - bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, - key); + bucket_num = find_bucket(key); + GNUNET_assert(bucket_num >= 0); + bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity_hash, + key); pos = k_buckets[bucket_num].head; - while (NULL != pos) - { - if ( (NULL != bloom) && - (GNUNET_YES == - GNUNET_CONTAINER_bloomfilter_test (bloom, - &pos->phash)) ) + while (NULL != pos) { + if ((NULL != bloom) && + (GNUNET_YES == + GNUNET_CONTAINER_bloomfilter_test(bloom, + &pos->phash))) + { + pos = pos->next; + continue; /* Skip already checked entries */ + } + other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->phash, + key); + if (other_bits > bits) + return GNUNET_NO; + if (other_bits == bits) /* We match the same number of bits */ + return GNUNET_YES; pos = pos->next; - continue; /* Skip already checked entries */ } - other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->phash, - key); - if (other_bits > bits) - return GNUNET_NO; - if (other_bits == bits) /* We match the same number of bits */ - return GNUNET_YES; - pos = pos->next; - } /* No peers closer, we are the closest! */ return GNUNET_YES; } @@ -1007,9 +996,9 @@ GDS_am_closest_peer (const struct GNUNET_HashCode *key, * @return Peer to route to, or NULL on error */ static struct PeerInfo * -select_peer (const struct GNUNET_HashCode *key, - const struct GNUNET_CONTAINER_BloomFilter *bloom, - uint32_t hops) +select_peer(const struct GNUNET_HashCode *key, + const struct GNUNET_CONTAINER_BloomFilter *bloom, + uint32_t hops) { unsigned int bc; unsigned int count; @@ -1019,126 +1008,126 @@ select_peer (const struct GNUNET_HashCode *key, unsigned int smallest_distance; struct PeerInfo *chosen; - if (hops >= GDS_NSE_get ()) - { - /* greedy selection (closest peer that is not in bloomfilter) */ - smallest_distance = UINT_MAX; - chosen = NULL; - for (bc = 0; bc <= closest_bucket; bc++) + if (hops >= GDS_NSE_get()) { - pos = k_buckets[bc].head; - count = 0; - while ((pos != NULL) && (count < bucket_size)) - { - if ( (NULL == bloom) || - (GNUNET_NO == - GNUNET_CONTAINER_bloomfilter_test (bloom, - &pos->phash))) + /* greedy selection (closest peer that is not in bloomfilter) */ + smallest_distance = UINT_MAX; + chosen = NULL; + for (bc = 0; bc <= closest_bucket; bc++) { - dist = get_distance (key, - &pos->phash); - if (dist < smallest_distance) - { - chosen = pos; - smallest_distance = dist; - } + pos = k_buckets[bc].head; + count = 0; + while ((pos != NULL) && (count < bucket_size)) + { + if ((NULL == bloom) || + (GNUNET_NO == + GNUNET_CONTAINER_bloomfilter_test(bloom, + &pos->phash))) + { + dist = get_distance(key, + &pos->phash); + if (dist < smallest_distance) + { + chosen = pos; + smallest_distance = dist; + } + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Excluded peer `%s' due to BF match in greedy routing for %s\n", + GNUNET_i2s(pos->id), + GNUNET_h2s(key)); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# Peers excluded from routing due to Bloomfilter"), + 1, + GNUNET_NO); + dist = get_distance(key, + &pos->phash); + if (dist < smallest_distance) + { + chosen = NULL; + smallest_distance = dist; + } + } + count++; + pos = pos->next; + } } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Excluded peer `%s' due to BF match in greedy routing for %s\n", - GNUNET_i2s (pos->id), - GNUNET_h2s (key)); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# Peers excluded from routing due to Bloomfilter"), - 1, - GNUNET_NO); - dist = get_distance (key, - &pos->phash); - if (dist < smallest_distance) - { - chosen = NULL; - smallest_distance = dist; - } - } - count++; - pos = pos->next; - } + if (NULL == chosen) + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# Peer selection failed"), + 1, + GNUNET_NO); + else + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Selected peer `%s' in greedy routing for %s\n", + GNUNET_i2s(chosen->id), + GNUNET_h2s(key)); + return chosen; } - if (NULL == chosen) - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# Peer selection failed"), - 1, - GNUNET_NO); - else - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Selected peer `%s' in greedy routing for %s\n", - GNUNET_i2s (chosen->id), - GNUNET_h2s (key)); - return chosen; - } /* select "random" peer */ /* count number of peers that are available and not filtered */ count = 0; for (bc = 0; bc <= closest_bucket; bc++) - { - pos = k_buckets[bc].head; - while ( (NULL != pos) && (count < bucket_size) ) { - if ( (NULL != bloom) && - (GNUNET_YES == - GNUNET_CONTAINER_bloomfilter_test (bloom, - &pos->phash)) ) - { - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# Peers excluded from routing due to Bloomfilter"), - 1, GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Excluded peer `%s' due to BF match in random routing for %s\n", - GNUNET_i2s (pos->id), - GNUNET_h2s (key)); - pos = pos->next; - continue; /* Ignore bloomfiltered peers */ - } - count++; - pos = pos->next; + pos = k_buckets[bc].head; + while ((NULL != pos) && (count < bucket_size)) + { + if ((NULL != bloom) && + (GNUNET_YES == + GNUNET_CONTAINER_bloomfilter_test(bloom, + &pos->phash))) + { + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# Peers excluded from routing due to Bloomfilter"), + 1, GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Excluded peer `%s' due to BF match in random routing for %s\n", + GNUNET_i2s(pos->id), + GNUNET_h2s(key)); + pos = pos->next; + continue; /* Ignore bloomfiltered peers */ + } + count++; + pos = pos->next; + } } - } if (0 == count) /* No peers to select from! */ - { - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# Peer selection failed"), 1, - GNUNET_NO); - return NULL; - } + { + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# Peer selection failed"), 1, + GNUNET_NO); + return NULL; + } /* Now actually choose a peer */ - selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - count); + selected = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + count); count = 0; for (bc = 0; bc <= closest_bucket; bc++) - { - for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next) { - if ((bloom != NULL) && - (GNUNET_YES == - GNUNET_CONTAINER_bloomfilter_test (bloom, - &pos->phash))) - { - continue; /* Ignore bloomfiltered peers */ - } - if (0 == selected--) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Selected peer `%s' in random routing for %s\n", - GNUNET_i2s (pos->id), - GNUNET_h2s (key)); - return pos; - } + for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next) + { + if ((bloom != NULL) && + (GNUNET_YES == + GNUNET_CONTAINER_bloomfilter_test(bloom, + &pos->phash))) + { + continue; /* Ignore bloomfiltered peers */ + } + if (0 == selected--) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Selected peer `%s' in random routing for %s\n", + GNUNET_i2s(pos->id), + GNUNET_h2s(key)); + return pos; + } + } } - } - GNUNET_break (0); + GNUNET_break(0); return NULL; } @@ -1157,60 +1146,60 @@ select_peer (const struct GNUNET_HashCode *key, * @return number of peers returned in 'targets'. */ static unsigned int -get_target_peers (const struct GNUNET_HashCode *key, - struct GNUNET_CONTAINER_BloomFilter *bloom, - uint32_t hop_count, - uint32_t target_replication, - struct PeerInfo ***targets) +get_target_peers(const struct GNUNET_HashCode *key, + struct GNUNET_CONTAINER_BloomFilter *bloom, + uint32_t hop_count, + uint32_t target_replication, + struct PeerInfo ***targets) { unsigned int ret; unsigned int off; struct PeerInfo **rtargets; struct PeerInfo *nxt; - GNUNET_assert (NULL != bloom); - ret = get_forward_count (hop_count, - target_replication); + GNUNET_assert(NULL != bloom); + ret = get_forward_count(hop_count, + target_replication); if (0 == ret) - { - *targets = NULL; - return 0; - } - rtargets = GNUNET_new_array (ret, - struct PeerInfo *); + { + *targets = NULL; + return 0; + } + rtargets = GNUNET_new_array(ret, + struct PeerInfo *); for (off = 0; off < ret; off++) - { - nxt = select_peer (key, - bloom, - hop_count); - if (NULL == nxt) - break; - rtargets[off] = nxt; - GNUNET_break (GNUNET_NO == - GNUNET_CONTAINER_bloomfilter_test (bloom, + { + nxt = select_peer(key, + bloom, + hop_count); + if (NULL == nxt) + break; + rtargets[off] = nxt; + GNUNET_break(GNUNET_NO == + GNUNET_CONTAINER_bloomfilter_test(bloom, &nxt->phash)); - GNUNET_CONTAINER_bloomfilter_add (bloom, - &nxt->phash); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Selected %u/%u peers at hop %u for %s (target was %u)\n", - off, - GNUNET_CONTAINER_multipeermap_size (all_connected_peers), - (unsigned int) hop_count, - GNUNET_h2s (key), - ret); + GNUNET_CONTAINER_bloomfilter_add(bloom, + &nxt->phash); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Selected %u/%u peers at hop %u for %s (target was %u)\n", + off, + GNUNET_CONTAINER_multipeermap_size(all_connected_peers), + (unsigned int)hop_count, + GNUNET_h2s(key), + ret); if (0 == off) - { - GNUNET_free (rtargets); - *targets = NULL; - return 0; - } + { + GNUNET_free(rtargets); + *targets = NULL; + return 0; + } *targets = rtargets; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Forwarding query `%s' to %u peers (goal was %u peers)\n", - GNUNET_h2s (key), - off, - ret); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Forwarding query `%s' to %u peers (goal was %u peers)\n", + GNUNET_h2s(key), + off, + ret); return off; } @@ -1236,17 +1225,17 @@ get_target_peers (const struct GNUNET_HashCode *key, * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not */ int -GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type, - enum GNUNET_DHT_RouteOption options, - uint32_t desired_replication_level, - struct GNUNET_TIME_Absolute expiration_time, - uint32_t hop_count, - struct GNUNET_CONTAINER_BloomFilter *bf, - const struct GNUNET_HashCode *key, - unsigned int put_path_length, - struct GNUNET_PeerIdentity *put_path, - const void *data, - size_t data_size) +GDS_NEIGHBOURS_handle_put(enum GNUNET_BLOCK_Type type, + enum GNUNET_DHT_RouteOption options, + uint32_t desired_replication_level, + struct GNUNET_TIME_Absolute expiration_time, + uint32_t hop_count, + struct GNUNET_CONTAINER_BloomFilter *bf, + const struct GNUNET_HashCode *key, + unsigned int put_path_length, + struct GNUNET_PeerIdentity *put_path, + const void *data, + size_t data_size) { unsigned int target_count; unsigned int i; @@ -1258,97 +1247,97 @@ GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type, struct GNUNET_PeerIdentity *pp; unsigned int skip_count; - GNUNET_assert (NULL != bf); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding myself (%s) to PUT bloomfilter for %s\n", - GNUNET_i2s (&my_identity), - GNUNET_h2s (key)); - GNUNET_CONTAINER_bloomfilter_add (bf, - &my_identity_hash); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# PUT requests routed"), - 1, - GNUNET_NO); + GNUNET_assert(NULL != bf); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding myself (%s) to PUT bloomfilter for %s\n", + GNUNET_i2s(&my_identity), + GNUNET_h2s(key)); + GNUNET_CONTAINER_bloomfilter_add(bf, + &my_identity_hash); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# PUT requests routed"), + 1, + GNUNET_NO); target_count - = get_target_peers (key, - bf, - hop_count, - desired_replication_level, - &targets); + = get_target_peers(key, + bf, + hop_count, + desired_replication_level, + &targets); if (0 == target_count) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Routing PUT for %s terminates after %u hops at %s\n", - GNUNET_h2s (key), - (unsigned int) hop_count, - GNUNET_i2s (&my_identity)); - return GNUNET_NO; - } - msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size; - if (msize + sizeof (struct PeerPutMessage) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Routing PUT for %s terminates after %u hops at %s\n", + GNUNET_h2s(key), + (unsigned int)hop_count, + GNUNET_i2s(&my_identity)); + return GNUNET_NO; + } + msize = put_path_length * sizeof(struct GNUNET_PeerIdentity) + data_size; + if (msize + sizeof(struct PeerPutMessage) >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE) - { - put_path_length = 0; - msize = data_size; - } - if (msize + sizeof (struct PeerPutMessage) + { + put_path_length = 0; + msize = data_size; + } + if (msize + sizeof(struct PeerPutMessage) >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE) - { - GNUNET_break (0); - GNUNET_free (targets); - return GNUNET_NO; - } - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# PUT messages queued for transmission"), - target_count, - GNUNET_NO); + { + GNUNET_break(0); + GNUNET_free(targets); + return GNUNET_NO; + } + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# PUT messages queued for transmission"), + target_count, + GNUNET_NO); skip_count = 0; for (i = 0; i < target_count; i++) - { - target = targets[i]; - if (GNUNET_MQ_get_length (target->mq) >= MAXIMUM_PENDING_PER_PEER) { - /* skip */ - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# P2P messages dropped due to full queue"), - 1, - GNUNET_NO); - skip_count++; - continue; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Routing PUT for %s after %u hops to %s\n", - GNUNET_h2s (key), - (unsigned int) hop_count, - GNUNET_i2s (target->id)); - env = GNUNET_MQ_msg_extra (ppm, - msize, - GNUNET_MESSAGE_TYPE_DHT_P2P_PUT); - ppm->options = htonl (options); - ppm->type = htonl (type); - ppm->hop_count = htonl (hop_count + 1); - ppm->desired_replication_level = htonl (desired_replication_level); - ppm->put_path_length = htonl (put_path_length); - ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time); - GNUNET_break (GNUNET_YES == - GNUNET_CONTAINER_bloomfilter_test (bf, + target = targets[i]; + if (GNUNET_MQ_get_length(target->mq) >= MAXIMUM_PENDING_PER_PEER) + { + /* skip */ + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# P2P messages dropped due to full queue"), + 1, + GNUNET_NO); + skip_count++; + continue; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Routing PUT for %s after %u hops to %s\n", + GNUNET_h2s(key), + (unsigned int)hop_count, + GNUNET_i2s(target->id)); + env = GNUNET_MQ_msg_extra(ppm, + msize, + GNUNET_MESSAGE_TYPE_DHT_P2P_PUT); + ppm->options = htonl(options); + ppm->type = htonl(type); + ppm->hop_count = htonl(hop_count + 1); + ppm->desired_replication_level = htonl(desired_replication_level); + ppm->put_path_length = htonl(put_path_length); + ppm->expiration_time = GNUNET_TIME_absolute_hton(expiration_time); + GNUNET_break(GNUNET_YES == + GNUNET_CONTAINER_bloomfilter_test(bf, &target->phash)); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_bloomfilter_get_raw_data (bf, + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_bloomfilter_get_raw_data(bf, ppm->bloomfilter, DHT_BLOOM_SIZE)); - ppm->key = *key; - pp = (struct GNUNET_PeerIdentity *) &ppm[1]; - GNUNET_memcpy (pp, - put_path, - sizeof (struct GNUNET_PeerIdentity) * put_path_length); - GNUNET_memcpy (&pp[put_path_length], - data, - data_size); - GNUNET_MQ_send (target->mq, - env); - } - GNUNET_free (targets); + ppm->key = *key; + pp = (struct GNUNET_PeerIdentity *)&ppm[1]; + GNUNET_memcpy(pp, + put_path, + sizeof(struct GNUNET_PeerIdentity) * put_path_length); + GNUNET_memcpy(&pp[put_path_length], + data, + data_size); + GNUNET_MQ_send(target->mq, + env); + } + GNUNET_free(targets); return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO; } @@ -1371,15 +1360,15 @@ GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type, * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not */ int -GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type, - enum GNUNET_DHT_RouteOption options, - uint32_t desired_replication_level, - uint32_t hop_count, - const struct GNUNET_HashCode *key, - const void *xquery, - size_t xquery_size, - struct GNUNET_BLOCK_Group *bg, - struct GNUNET_CONTAINER_BloomFilter *peer_bf) +GDS_NEIGHBOURS_handle_get(enum GNUNET_BLOCK_Type type, + enum GNUNET_DHT_RouteOption options, + uint32_t desired_replication_level, + uint32_t hop_count, + const struct GNUNET_HashCode *key, + const void *xquery, + size_t xquery_size, + struct GNUNET_BLOCK_Group *bg, + struct GNUNET_CONTAINER_BloomFilter *peer_bf) { unsigned int target_count; struct PeerInfo **targets; @@ -1393,102 +1382,102 @@ GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type, unsigned int skip_count; uint32_t bf_nonce; - GNUNET_assert (NULL != peer_bf); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# GET requests routed"), - 1, - GNUNET_NO); - target_count = get_target_peers (key, - peer_bf, - hop_count, - desired_replication_level, - &targets); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding myself (%s) to GET bloomfilter for %s\n", - GNUNET_i2s (&my_identity), - GNUNET_h2s (key)); - GNUNET_CONTAINER_bloomfilter_add (peer_bf, - &my_identity_hash); + GNUNET_assert(NULL != peer_bf); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# GET requests routed"), + 1, + GNUNET_NO); + target_count = get_target_peers(key, + peer_bf, + hop_count, + desired_replication_level, + &targets); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding myself (%s) to GET bloomfilter for %s\n", + GNUNET_i2s(&my_identity), + GNUNET_h2s(key)); + GNUNET_CONTAINER_bloomfilter_add(peer_bf, + &my_identity_hash); if (0 == target_count) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Routing GET for %s terminates after %u hops at %s\n", - GNUNET_h2s (key), - (unsigned int) hop_count, - GNUNET_i2s (&my_identity)); - return GNUNET_NO; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Routing GET for %s terminates after %u hops at %s\n", + GNUNET_h2s(key), + (unsigned int)hop_count, + GNUNET_i2s(&my_identity)); + return GNUNET_NO; + } if (GNUNET_OK != - GNUNET_BLOCK_group_serialize (bg, - &bf_nonce, - &reply_bf, - &reply_bf_size)) - { - reply_bf = NULL; - reply_bf_size = 0; - bf_nonce = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT32_MAX); - } + GNUNET_BLOCK_group_serialize(bg, + &bf_nonce, + &reply_bf, + &reply_bf_size)) + { + reply_bf = NULL; + reply_bf_size = 0; + bf_nonce = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + UINT32_MAX); + } msize = xquery_size + reply_bf_size; - if (msize + sizeof (struct PeerGetMessage) >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - GNUNET_free_non_null (reply_bf); - GNUNET_free (targets); - return GNUNET_NO; - } - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# GET messages queued for transmission"), - target_count, - GNUNET_NO); + if (msize + sizeof(struct PeerGetMessage) >= GNUNET_MAX_MESSAGE_SIZE) + { + GNUNET_break(0); + GNUNET_free_non_null(reply_bf); + GNUNET_free(targets); + return GNUNET_NO; + } + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# GET messages queued for transmission"), + target_count, + GNUNET_NO); /* forward request */ skip_count = 0; for (unsigned int i = 0; i < target_count; i++) - { - target = targets[i]; - if (GNUNET_MQ_get_length (target->mq) >= MAXIMUM_PENDING_PER_PEER) { - /* skip */ - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# P2P messages dropped due to full queue"), - 1, GNUNET_NO); - skip_count++; - continue; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Routing GET for %s after %u hops to %s\n", - GNUNET_h2s (key), - (unsigned int) hop_count, - GNUNET_i2s (target->id)); - env = GNUNET_MQ_msg_extra (pgm, - msize, - GNUNET_MESSAGE_TYPE_DHT_P2P_GET); - pgm->options = htonl (options); - pgm->type = htonl (type); - pgm->hop_count = htonl (hop_count + 1); - pgm->desired_replication_level = htonl (desired_replication_level); - pgm->xquery_size = htonl (xquery_size); - pgm->bf_mutator = bf_nonce; - GNUNET_break (GNUNET_YES == - GNUNET_CONTAINER_bloomfilter_test (peer_bf, + target = targets[i]; + if (GNUNET_MQ_get_length(target->mq) >= MAXIMUM_PENDING_PER_PEER) + { + /* skip */ + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# P2P messages dropped due to full queue"), + 1, GNUNET_NO); + skip_count++; + continue; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Routing GET for %s after %u hops to %s\n", + GNUNET_h2s(key), + (unsigned int)hop_count, + GNUNET_i2s(target->id)); + env = GNUNET_MQ_msg_extra(pgm, + msize, + GNUNET_MESSAGE_TYPE_DHT_P2P_GET); + pgm->options = htonl(options); + pgm->type = htonl(type); + pgm->hop_count = htonl(hop_count + 1); + pgm->desired_replication_level = htonl(desired_replication_level); + pgm->xquery_size = htonl(xquery_size); + pgm->bf_mutator = bf_nonce; + GNUNET_break(GNUNET_YES == + GNUNET_CONTAINER_bloomfilter_test(peer_bf, &target->phash)); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf, + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_bloomfilter_get_raw_data(peer_bf, pgm->bloomfilter, DHT_BLOOM_SIZE)); - pgm->key = *key; - xq = (char *) &pgm[1]; - GNUNET_memcpy (xq, - xquery, - xquery_size); - GNUNET_memcpy (&xq[xquery_size], - reply_bf, - reply_bf_size); - GNUNET_MQ_send (target->mq, - env); - } - GNUNET_free (targets); - GNUNET_free_non_null (reply_bf); + pgm->key = *key; + xq = (char *)&pgm[1]; + GNUNET_memcpy(xq, + xquery, + xquery_size); + GNUNET_memcpy(&xq[xquery_size], + reply_bf, + reply_bf_size); + GNUNET_MQ_send(target->mq, + env); + } + GNUNET_free(targets); + GNUNET_free_non_null(reply_bf); return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO; } @@ -1510,16 +1499,16 @@ GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type, * @param data_size number of bytes in @a data */ void -GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute expiration_time, - const struct GNUNET_HashCode *key, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *get_path, - const void *data, - size_t data_size) +GDS_NEIGHBOURS_handle_reply(const struct GNUNET_PeerIdentity *target, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute expiration_time, + const struct GNUNET_HashCode *key, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *get_path, + const void *data, + size_t data_size) { struct PeerInfo *pi; struct GNUNET_MQ_Envelope *env; @@ -1528,68 +1517,68 @@ GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target, struct GNUNET_PeerIdentity *paths; msize = data_size + (get_path_length + put_path_length) * - sizeof (struct GNUNET_PeerIdentity); - if ((msize + sizeof (struct PeerResultMessage) >= GNUNET_MAX_MESSAGE_SIZE) || + sizeof(struct GNUNET_PeerIdentity); + if ((msize + sizeof(struct PeerResultMessage) >= GNUNET_MAX_MESSAGE_SIZE) || (get_path_length > - GNUNET_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) || + GNUNET_MAX_MESSAGE_SIZE / sizeof(struct GNUNET_PeerIdentity)) || (put_path_length > - GNUNET_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) || + GNUNET_MAX_MESSAGE_SIZE / sizeof(struct GNUNET_PeerIdentity)) || (data_size > GNUNET_MAX_MESSAGE_SIZE)) - { - GNUNET_break (0); - return; - } - pi = GNUNET_CONTAINER_multipeermap_get (all_connected_peers, - target); + { + GNUNET_break(0); + return; + } + pi = GNUNET_CONTAINER_multipeermap_get(all_connected_peers, + target); if (NULL == pi) - { - /* peer disconnected in the meantime, drop reply */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "No matching peer for reply for key %s\n", - GNUNET_h2s (key)); - return; - } - if (GNUNET_MQ_get_length (pi->mq) >= MAXIMUM_PENDING_PER_PEER) - { - /* skip */ - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# P2P messages dropped due to full queue"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Peer queue full, ignoring reply for key %s\n", - GNUNET_h2s (key)); - return; - } + { + /* peer disconnected in the meantime, drop reply */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "No matching peer for reply for key %s\n", + GNUNET_h2s(key)); + return; + } + if (GNUNET_MQ_get_length(pi->mq) >= MAXIMUM_PENDING_PER_PEER) + { + /* skip */ + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# P2P messages dropped due to full queue"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Peer queue full, ignoring reply for key %s\n", + GNUNET_h2s(key)); + return; + } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Forwarding reply for key %s to peer %s\n", - GNUNET_h2s (key), - GNUNET_i2s (target)); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# RESULT messages queued for transmission"), 1, - GNUNET_NO); - env = GNUNET_MQ_msg_extra (prm, - msize, - GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT); - prm->type = htonl (type); - prm->put_path_length = htonl (put_path_length); - prm->get_path_length = htonl (get_path_length); - prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Forwarding reply for key %s to peer %s\n", + GNUNET_h2s(key), + GNUNET_i2s(target)); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# RESULT messages queued for transmission"), 1, + GNUNET_NO); + env = GNUNET_MQ_msg_extra(prm, + msize, + GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT); + prm->type = htonl(type); + prm->put_path_length = htonl(put_path_length); + prm->get_path_length = htonl(get_path_length); + prm->expiration_time = GNUNET_TIME_absolute_hton(expiration_time); prm->key = *key; - paths = (struct GNUNET_PeerIdentity *) &prm[1]; - GNUNET_memcpy (paths, - put_path, - put_path_length * sizeof (struct GNUNET_PeerIdentity)); - GNUNET_memcpy (&paths[put_path_length], - get_path, - get_path_length * sizeof (struct GNUNET_PeerIdentity)); - GNUNET_memcpy (&paths[put_path_length + get_path_length], - data, - data_size); - GNUNET_MQ_send (pi->mq, - env); + paths = (struct GNUNET_PeerIdentity *)&prm[1]; + GNUNET_memcpy(paths, + put_path, + put_path_length * sizeof(struct GNUNET_PeerIdentity)); + GNUNET_memcpy(&paths[put_path_length], + get_path, + get_path_length * sizeof(struct GNUNET_PeerIdentity)); + GNUNET_memcpy(&paths[put_path_length + get_path_length], + data, + data_size); + GNUNET_MQ_send(pi->mq, + env); } @@ -1600,18 +1589,18 @@ GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target, * @param identity the public identity of this peer */ static void -core_init (void *cls, - const struct GNUNET_PeerIdentity *identity) +core_init(void *cls, + const struct GNUNET_PeerIdentity *identity) { - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "CORE called, I am %s\n", - GNUNET_i2s (identity)); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "CORE called, I am %s\n", + GNUNET_i2s(identity)); my_identity = *identity; - GNUNET_CRYPTO_hash (identity, - sizeof (struct GNUNET_PeerIdentity), - &my_identity_hash); - GNUNET_SERVICE_resume (GDS_service); + GNUNET_CRYPTO_hash(identity, + sizeof(struct GNUNET_PeerIdentity), + &my_identity_hash); + GNUNET_SERVICE_resume(GDS_service); } @@ -1623,24 +1612,24 @@ core_init (void *cls, * @return #GNUNET_OK if the message is valid */ static int -check_dht_p2p_put (void *cls, - const struct PeerPutMessage *put) +check_dht_p2p_put(void *cls, + const struct PeerPutMessage *put) { uint32_t putlen; uint16_t msize; - (void) cls; - msize = ntohs (put->header.size); - putlen = ntohl (put->put_path_length); + (void)cls; + msize = ntohs(put->header.size); + putlen = ntohl(put->put_path_length); if ((msize < - sizeof (struct PeerPutMessage) + - putlen * sizeof (struct GNUNET_PeerIdentity)) || + sizeof(struct PeerPutMessage) + + putlen * sizeof(struct GNUNET_PeerIdentity)) || (putlen > - GNUNET_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity))) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + GNUNET_MAX_MESSAGE_SIZE / sizeof(struct GNUNET_PeerIdentity))) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1652,8 +1641,8 @@ check_dht_p2p_put (void *cls, * @param message message */ static void -handle_dht_p2p_put (void *cls, - const struct PeerPutMessage *put) +handle_dht_p2p_put(void *cls, + const struct PeerPutMessage *put) { struct PeerInfo *peer = cls; const struct GNUNET_PeerIdentity *put_path; @@ -1667,196 +1656,198 @@ handle_dht_p2p_put (void *cls, int forwarded; struct GNUNET_TIME_Absolute exp_time; - exp_time = GNUNET_TIME_absolute_ntoh (put->expiration_time); - if (0 == GNUNET_TIME_absolute_get_remaining (exp_time).rel_value_us) - { - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# Expired PUTs discarded"), - 1, - GNUNET_NO); - return; - } - msize = ntohs (put->header.size); - putlen = ntohl (put->put_path_length); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# P2P PUT requests received"), - 1, - GNUNET_NO); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# P2P PUT bytes received"), - msize, - GNUNET_NO); - put_path = (const struct GNUNET_PeerIdentity *) &put[1]; + exp_time = GNUNET_TIME_absolute_ntoh(put->expiration_time); + if (0 == GNUNET_TIME_absolute_get_remaining(exp_time).rel_value_us) + { + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# Expired PUTs discarded"), + 1, + GNUNET_NO); + return; + } + msize = ntohs(put->header.size); + putlen = ntohl(put->put_path_length); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# P2P PUT requests received"), + 1, + GNUNET_NO); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# P2P PUT bytes received"), + msize, + GNUNET_NO); + put_path = (const struct GNUNET_PeerIdentity *)&put[1]; payload = &put_path[putlen]; - options = ntohl (put->options); - payload_size = msize - (sizeof (struct PeerPutMessage) + - putlen * sizeof (struct GNUNET_PeerIdentity)); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "PUT for `%s' from %s\n", - GNUNET_h2s (&put->key), - GNUNET_i2s (peer->id)); + options = ntohl(put->options); + payload_size = msize - (sizeof(struct PeerPutMessage) + + putlen * sizeof(struct GNUNET_PeerIdentity)); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "PUT for `%s' from %s\n", + GNUNET_h2s(&put->key), + GNUNET_i2s(peer->id)); if (GNUNET_YES == log_route_details_stderr) - { - char *tmp; - char *pp; - - pp = GNUNET_STRINGS_pp2s (put_path, - putlen); - tmp = GNUNET_strdup (GNUNET_i2s (&my_identity)); - LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, - "R5N PUT %s: %s->%s (%u, %u=>%u, PP: %s)\n", - GNUNET_h2s (&put->key), - GNUNET_i2s (peer->id), - tmp, - ntohl(put->hop_count), - GNUNET_CRYPTO_hash_matching_bits (&peer->phash, + { + char *tmp; + char *pp; + + pp = GNUNET_STRINGS_pp2s(put_path, + putlen); + tmp = GNUNET_strdup(GNUNET_i2s(&my_identity)); + LOG_TRAFFIC(GNUNET_ERROR_TYPE_DEBUG, + "R5N PUT %s: %s->%s (%u, %u=>%u, PP: %s)\n", + GNUNET_h2s(&put->key), + GNUNET_i2s(peer->id), + tmp, + ntohl(put->hop_count), + GNUNET_CRYPTO_hash_matching_bits(&peer->phash, &put->key), - GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, + GNUNET_CRYPTO_hash_matching_bits(&my_identity_hash, &put->key), - pp); - GNUNET_free (pp); - GNUNET_free (tmp); - } - switch (GNUNET_BLOCK_get_key - (GDS_block_context, - ntohl (put->type), - payload, - payload_size, - &test_key)) - { - case GNUNET_YES: - if (0 != memcmp (&test_key, - &put->key, - sizeof (struct GNUNET_HashCode))) - { - char *put_s = GNUNET_strdup (GNUNET_h2s_full (&put->key)); - - GNUNET_break_op (0); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "PUT with key `%s' for block with key %s\n", - put_s, - GNUNET_h2s_full (&test_key)); - GNUNET_free (put_s); - return; + pp); + GNUNET_free(pp); + GNUNET_free(tmp); } - break; - case GNUNET_NO: - GNUNET_break_op (0); - return; - case GNUNET_SYSERR: - /* cannot verify, good luck */ - break; - } - if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */ - { - switch (GNUNET_BLOCK_evaluate (GDS_block_context, - ntohl (put->type), - NULL, /* query group */ - GNUNET_BLOCK_EO_NONE, - NULL, /* query */ - NULL, 0, /* xquery */ - payload, - payload_size)) + switch (GNUNET_BLOCK_get_key + (GDS_block_context, + ntohl(put->type), + payload, + payload_size, + &test_key)) { - case GNUNET_BLOCK_EVALUATION_OK_MORE: - case GNUNET_BLOCK_EVALUATION_OK_LAST: + case GNUNET_YES: + if (0 != memcmp(&test_key, + &put->key, + sizeof(struct GNUNET_HashCode))) + { + char *put_s = GNUNET_strdup(GNUNET_h2s_full(&put->key)); + + GNUNET_break_op(0); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "PUT with key `%s' for block with key %s\n", + put_s, + GNUNET_h2s_full(&test_key)); + GNUNET_free(put_s); + return; + } break; - case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE: - case GNUNET_BLOCK_EVALUATION_RESULT_INVALID: - case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT: - case GNUNET_BLOCK_EVALUATION_REQUEST_VALID: - case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID: - case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED: - default: - GNUNET_break_op (0); + case GNUNET_NO: + GNUNET_break_op(0); return; + + case GNUNET_SYSERR: + /* cannot verify, good luck */ + break; + } + if (ntohl(put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */ + { + switch (GNUNET_BLOCK_evaluate(GDS_block_context, + ntohl(put->type), + NULL, /* query group */ + GNUNET_BLOCK_EO_NONE, + NULL, /* query */ + NULL, 0, /* xquery */ + payload, + payload_size)) + { + case GNUNET_BLOCK_EVALUATION_OK_MORE: + case GNUNET_BLOCK_EVALUATION_OK_LAST: + break; + + case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE: + case GNUNET_BLOCK_EVALUATION_RESULT_INVALID: + case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT: + case GNUNET_BLOCK_EVALUATION_REQUEST_VALID: + case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID: + case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED: + default: + GNUNET_break_op(0); + return; + } } - } - bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, - DHT_BLOOM_SIZE, - GNUNET_CONSTANTS_BLOOMFILTER_K); - GNUNET_break_op (GNUNET_YES == - GNUNET_CONTAINER_bloomfilter_test (bf, - &peer->phash)); + bf = GNUNET_CONTAINER_bloomfilter_init(put->bloomfilter, + DHT_BLOOM_SIZE, + GNUNET_CONSTANTS_BLOOMFILTER_K); + GNUNET_break_op(GNUNET_YES == + GNUNET_CONTAINER_bloomfilter_test(bf, + &peer->phash)); { struct GNUNET_PeerIdentity pp[putlen + 1]; /* extend 'put path' by sender */ if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE)) - { -#if SANITY_CHECKS - for (unsigned int i=0;i<=putlen;i++) { - for (unsigned int j=0;jid, - sizeof (struct GNUNET_PeerIdentity))); - } +#if SANITY_CHECKS + for (unsigned int i = 0; i <= putlen; i++) + { + for (unsigned int j = 0; j < i; j++) + { + GNUNET_break(0 != memcmp(&pp[i], + &pp[j], + sizeof(struct GNUNET_PeerIdentity))); + } + GNUNET_break(0 != memcmp(&pp[i], + peer->id, + sizeof(struct GNUNET_PeerIdentity))); + } #endif - GNUNET_memcpy (pp, - put_path, - putlen * sizeof (struct GNUNET_PeerIdentity)); - pp[putlen] = *peer->id; - putlen++; - } + GNUNET_memcpy(pp, + put_path, + putlen * sizeof(struct GNUNET_PeerIdentity)); + pp[putlen] = *peer->id; + putlen++; + } else putlen = 0; /* give to local clients */ - GDS_CLIENTS_handle_reply (exp_time, - &put->key, - 0, - NULL, - putlen, - pp, - ntohl (put->type), - payload_size, - payload); + GDS_CLIENTS_handle_reply(exp_time, + &put->key, + 0, + NULL, + putlen, + pp, + ntohl(put->type), + payload_size, + payload); /* store locally */ if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) || - (GDS_am_closest_peer (&put->key, bf))) - GDS_DATACACHE_handle_put (exp_time, - &put->key, - putlen, - pp, - ntohl (put->type), - payload_size, - payload); + (GDS_am_closest_peer(&put->key, bf))) + GDS_DATACACHE_handle_put(exp_time, + &put->key, + putlen, + pp, + ntohl(put->type), + payload_size, + payload); /* route to other peers */ - forwarded = GDS_NEIGHBOURS_handle_put (ntohl (put->type), - options, - ntohl (put->desired_replication_level), - exp_time, - ntohl (put->hop_count), - bf, - &put->key, - putlen, - pp, - payload, - payload_size); + forwarded = GDS_NEIGHBOURS_handle_put(ntohl(put->type), + options, + ntohl(put->desired_replication_level), + exp_time, + ntohl(put->hop_count), + bf, + &put->key, + putlen, + pp, + payload, + payload_size); /* notify monitoring clients */ - GDS_CLIENTS_process_put (options - | ( (GNUNET_OK == forwarded) - ? GNUNET_DHT_RO_LAST_HOP - : 0 ), - ntohl (put->type), - ntohl (put->hop_count), - ntohl (put->desired_replication_level), - putlen, pp, - exp_time, - &put->key, - payload, - payload_size); + GDS_CLIENTS_process_put(options + | ((GNUNET_OK == forwarded) + ? GNUNET_DHT_RO_LAST_HOP + : 0), + ntohl(put->type), + ntohl(put->hop_count), + ntohl(put->desired_replication_level), + putlen, pp, + exp_time, + &put->key, + payload, + payload_size); } - GNUNET_CONTAINER_bloomfilter_free (bf); + GNUNET_CONTAINER_bloomfilter_free(bf); } @@ -1869,9 +1860,9 @@ handle_dht_p2p_put (void *cls, * @param bg group for filtering peers */ static void -handle_find_peer (const struct GNUNET_PeerIdentity *sender, - const struct GNUNET_HashCode *key, - struct GNUNET_BLOCK_Group *bg) +handle_find_peer(const struct GNUNET_PeerIdentity *sender, + const struct GNUNET_HashCode *key, + struct GNUNET_BLOCK_Group *bg) { int bucket_idx; struct PeerBucket *bucket; @@ -1882,98 +1873,99 @@ handle_find_peer (const struct GNUNET_PeerIdentity *sender, /* first, check about our own HELLO */ if (NULL != GDS_my_hello) - { - hello_size = GNUNET_HELLO_size ((const struct GNUNET_HELLO_Message *) GDS_my_hello); - GNUNET_break (hello_size >= sizeof (struct GNUNET_MessageHeader)); - if (GNUNET_BLOCK_EVALUATION_OK_MORE == - GNUNET_BLOCK_evaluate (GDS_block_context, - GNUNET_BLOCK_TYPE_DHT_HELLO, - bg, - GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO, - &my_identity_hash, - NULL, 0, - GDS_my_hello, - hello_size)) { - GDS_NEIGHBOURS_handle_reply (sender, - GNUNET_BLOCK_TYPE_DHT_HELLO, - GNUNET_TIME_relative_to_absolute (hello_expiration), - key, - 0, - NULL, - 0, - NULL, - GDS_my_hello, - hello_size); + hello_size = GNUNET_HELLO_size((const struct GNUNET_HELLO_Message *)GDS_my_hello); + GNUNET_break(hello_size >= sizeof(struct GNUNET_MessageHeader)); + if (GNUNET_BLOCK_EVALUATION_OK_MORE == + GNUNET_BLOCK_evaluate(GDS_block_context, + GNUNET_BLOCK_TYPE_DHT_HELLO, + bg, + GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO, + &my_identity_hash, + NULL, 0, + GDS_my_hello, + hello_size)) + { + GDS_NEIGHBOURS_handle_reply(sender, + GNUNET_BLOCK_TYPE_DHT_HELLO, + GNUNET_TIME_relative_to_absolute(hello_expiration), + key, + 0, + NULL, + 0, + NULL, + GDS_my_hello, + hello_size); + } + else + { + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# FIND PEER requests ignored due to Bloomfilter"), + 1, + GNUNET_NO); + } } - else + else { - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# FIND PEER requests ignored due to Bloomfilter"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# FIND PEER requests ignored due to lack of HELLO"), + 1, + GNUNET_NO); } - } - else - { - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# FIND PEER requests ignored due to lack of HELLO"), - 1, - GNUNET_NO); - } /* then, also consider sending a random HELLO from the closest bucket */ - if (0 == memcmp (&my_identity_hash, - key, - sizeof (struct GNUNET_HashCode))) + if (0 == memcmp(&my_identity_hash, + key, + sizeof(struct GNUNET_HashCode))) bucket_idx = closest_bucket; else - bucket_idx = GNUNET_MIN ((int) closest_bucket, - find_bucket (key)); + bucket_idx = GNUNET_MIN((int)closest_bucket, + find_bucket(key)); if (bucket_idx < 0) return; bucket = &k_buckets[bucket_idx]; if (bucket->peers_size == 0) return; - choice = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - bucket->peers_size); + choice = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + bucket->peers_size); peer = bucket->head; while (choice > 0) - { - GNUNET_assert (NULL != peer); - peer = peer->next; - choice--; - } + { + GNUNET_assert(NULL != peer); + peer = peer->next; + choice--; + } choice = bucket->peers_size; do - { - peer = peer->next; - if (0 == choice--) - return; /* no non-masked peer available */ - if (NULL == peer) - peer = bucket->head; - hello = GDS_HELLO_get (peer->id); - } while ( (NULL == hello) || - (GNUNET_BLOCK_EVALUATION_OK_MORE != - GNUNET_BLOCK_evaluate (GDS_block_context, - GNUNET_BLOCK_TYPE_DHT_HELLO, - bg, - GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO, - &peer->phash, - NULL, 0, - hello, - (hello_size = GNUNET_HELLO_size (hello)))) ); - GDS_NEIGHBOURS_handle_reply (sender, - GNUNET_BLOCK_TYPE_DHT_HELLO, - GNUNET_TIME_relative_to_absolute - (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), - key, - 0, - NULL, - 0, - NULL, - hello, - hello_size); + { + peer = peer->next; + if (0 == choice--) + return; /* no non-masked peer available */ + if (NULL == peer) + peer = bucket->head; + hello = GDS_HELLO_get(peer->id); + } + while ((NULL == hello) || + (GNUNET_BLOCK_EVALUATION_OK_MORE != + GNUNET_BLOCK_evaluate(GDS_block_context, + GNUNET_BLOCK_TYPE_DHT_HELLO, + bg, + GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO, + &peer->phash, + NULL, 0, + hello, + (hello_size = GNUNET_HELLO_size(hello))))); + GDS_NEIGHBOURS_handle_reply(sender, + GNUNET_BLOCK_TYPE_DHT_HELLO, + GNUNET_TIME_relative_to_absolute + (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), + key, + 0, + NULL, + 0, + NULL, + hello, + hello_size); } @@ -1992,34 +1984,34 @@ handle_find_peer (const struct GNUNET_PeerIdentity *sender, * @param data_size number of bytes in @a data */ static void -handle_local_result (void *cls, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute expiration_time, - const struct GNUNET_HashCode *key, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *get_path, - const void *data, - size_t data_size) +handle_local_result(void *cls, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute expiration_time, + const struct GNUNET_HashCode *key, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *get_path, + const void *data, + size_t data_size) { struct PeerInfo *peer = cls; char *pp; - pp = GNUNET_STRINGS_pp2s (put_path, - put_path_length); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found local result for %s (PP: %s)\n", - GNUNET_h2s (key), - pp); - GNUNET_free (pp); - GDS_NEIGHBOURS_handle_reply (peer->id, - type, - expiration_time, - key, - put_path_length, put_path, - get_path_length, get_path, - data, data_size); + pp = GNUNET_STRINGS_pp2s(put_path, + put_path_length); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found local result for %s (PP: %s)\n", + GNUNET_h2s(key), + pp); + GNUNET_free(pp); + GDS_NEIGHBOURS_handle_reply(peer->id, + type, + expiration_time, + key, + put_path_length, put_path, + get_path_length, get_path, + data, data_size); } @@ -2031,20 +2023,20 @@ handle_local_result (void *cls, * @return #GNUNET_OK if the message is well-formed */ static int -check_dht_p2p_get (void *cls, - const struct PeerGetMessage *get) +check_dht_p2p_get(void *cls, + const struct PeerGetMessage *get) { uint32_t xquery_size; uint16_t msize; - (void) cls; - msize = ntohs (get->header.size); - xquery_size = ntohl (get->xquery_size); - if (msize < sizeof (struct PeerGetMessage) + xquery_size) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + (void)cls; + msize = ntohs(get->header.size); + xquery_size = ntohl(get->xquery_size); + if (msize < sizeof(struct PeerGetMessage) + xquery_size) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -2056,8 +2048,8 @@ check_dht_p2p_get (void *cls, * @param get the message */ static void -handle_dht_p2p_get (void *cls, - const struct PeerGetMessage *get) +handle_dht_p2p_get(void *cls, + const struct PeerGetMessage *get) { struct PeerInfo *peer = cls; uint32_t xquery_size; @@ -2072,141 +2064,141 @@ handle_dht_p2p_get (void *cls, int forwarded; /* parse and validate message */ - msize = ntohs (get->header.size); - xquery_size = ntohl (get->xquery_size); - reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size); - type = ntohl (get->type); - options = ntohl (get->options); - xquery = (const char *) &get[1]; - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# P2P GET requests received"), - 1, - GNUNET_NO); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# P2P GET bytes received"), - msize, - GNUNET_NO); + msize = ntohs(get->header.size); + xquery_size = ntohl(get->xquery_size); + reply_bf_size = msize - (sizeof(struct PeerGetMessage) + xquery_size); + type = ntohl(get->type); + options = ntohl(get->options); + xquery = (const char *)&get[1]; + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# P2P GET requests received"), + 1, + GNUNET_NO); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# P2P GET bytes received"), + msize, + GNUNET_NO); if (GNUNET_YES == log_route_details_stderr) - { - char *tmp; - - tmp = GNUNET_strdup (GNUNET_i2s (&my_identity)); - LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, - "R5N GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n", - GNUNET_h2s (&get->key), - GNUNET_i2s (peer->id), - tmp, - ntohl(get->hop_count), - GNUNET_CRYPTO_hash_matching_bits (&peer->phash, - &get->key), - GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, - &get->key), - ntohl(get->xquery_size), - xquery); - GNUNET_free (tmp); - } + { + char *tmp; + + tmp = GNUNET_strdup(GNUNET_i2s(&my_identity)); + LOG_TRAFFIC(GNUNET_ERROR_TYPE_DEBUG, + "R5N GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n", + GNUNET_h2s(&get->key), + GNUNET_i2s(peer->id), + tmp, + ntohl(get->hop_count), + GNUNET_CRYPTO_hash_matching_bits(&peer->phash, + &get->key), + GNUNET_CRYPTO_hash_matching_bits(&my_identity_hash, + &get->key), + ntohl(get->xquery_size), + xquery); + GNUNET_free(tmp); + } eval - = GNUNET_BLOCK_evaluate (GDS_block_context, - type, - NULL, - GNUNET_BLOCK_EO_NONE, - &get->key, - xquery, - xquery_size, - NULL, - 0); + = GNUNET_BLOCK_evaluate(GDS_block_context, + type, + NULL, + GNUNET_BLOCK_EO_NONE, + &get->key, + xquery, + xquery_size, + NULL, + 0); if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID) - { - /* request invalid or block type not supported */ - GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED); - return; - } - peer_bf = GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, - DHT_BLOOM_SIZE, - GNUNET_CONSTANTS_BLOOMFILTER_K); - GNUNET_break_op (GNUNET_YES == - GNUNET_CONTAINER_bloomfilter_test (peer_bf, - &peer->phash)); - bg = GNUNET_BLOCK_group_create (GDS_block_context, - type, - get->bf_mutator, - &xquery[xquery_size], - reply_bf_size, - "filter-size", - reply_bf_size, - NULL); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "GET for %s at %s after %u hops\n", - GNUNET_h2s (&get->key), - GNUNET_i2s (&my_identity), - (unsigned int) ntohl (get->hop_count)); + { + /* request invalid or block type not supported */ + GNUNET_break_op(eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED); + return; + } + peer_bf = GNUNET_CONTAINER_bloomfilter_init(get->bloomfilter, + DHT_BLOOM_SIZE, + GNUNET_CONSTANTS_BLOOMFILTER_K); + GNUNET_break_op(GNUNET_YES == + GNUNET_CONTAINER_bloomfilter_test(peer_bf, + &peer->phash)); + bg = GNUNET_BLOCK_group_create(GDS_block_context, + type, + get->bf_mutator, + &xquery[xquery_size], + reply_bf_size, + "filter-size", + reply_bf_size, + NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "GET for %s at %s after %u hops\n", + GNUNET_h2s(&get->key), + GNUNET_i2s(&my_identity), + (unsigned int)ntohl(get->hop_count)); /* local lookup (this may update the reply_bf) */ if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) || - (GDS_am_closest_peer (&get->key, - peer_bf))) - { - if ((0 != (options & GNUNET_DHT_RO_FIND_PEER))) + (GDS_am_closest_peer(&get->key, + peer_bf))) { - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# P2P FIND PEER requests processed"), - 1, - GNUNET_NO); - handle_find_peer (peer->id, - &get->key, - bg); + if ((0 != (options & GNUNET_DHT_RO_FIND_PEER))) + { + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# P2P FIND PEER requests processed"), + 1, + GNUNET_NO); + handle_find_peer(peer->id, + &get->key, + bg); + } + else + { + eval = GDS_DATACACHE_handle_get(&get->key, + type, + xquery, + xquery_size, + bg, + &handle_local_result, + peer); + } } - else + else { - eval = GDS_DATACACHE_handle_get (&get->key, - type, - xquery, - xquery_size, - bg, - &handle_local_result, - peer); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# P2P GET requests ONLY routed"), + 1, + GNUNET_NO); } - } - else - { - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# P2P GET requests ONLY routed"), - 1, - GNUNET_NO); - } /* remember request for routing replies */ - GDS_ROUTING_add (peer->id, - type, - bg, /* bg now owned by routing, but valid at least until end of this function! */ - options, - &get->key, - xquery, - xquery_size); + GDS_ROUTING_add(peer->id, + type, + bg, /* bg now owned by routing, but valid at least until end of this function! */ + options, + &get->key, + xquery, + xquery_size); /* P2P forwarding */ forwarded = GNUNET_NO; if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST) - forwarded = GDS_NEIGHBOURS_handle_get (type, - options, - ntohl (get->desired_replication_level), - ntohl (get->hop_count), - &get->key, - xquery, - xquery_size, - bg, - peer_bf); - GDS_CLIENTS_process_get (options - | (GNUNET_OK == forwarded) - ? GNUNET_DHT_RO_LAST_HOP : 0, - type, - ntohl (get->hop_count), - ntohl (get->desired_replication_level), - 0, - NULL, - &get->key); + forwarded = GDS_NEIGHBOURS_handle_get(type, + options, + ntohl(get->desired_replication_level), + ntohl(get->hop_count), + &get->key, + xquery, + xquery_size, + bg, + peer_bf); + GDS_CLIENTS_process_get(options + | (GNUNET_OK == forwarded) + ? GNUNET_DHT_RO_LAST_HOP : 0, + type, + ntohl(get->hop_count), + ntohl(get->desired_replication_level), + 0, + NULL, + &get->key); /* clean up; note that 'bg' is owned by routing now! */ - GNUNET_CONTAINER_bloomfilter_free (peer_bf); + GNUNET_CONTAINER_bloomfilter_free(peer_bf); } @@ -2218,29 +2210,29 @@ handle_dht_p2p_get (void *cls, * @return #GNUNET_YES if the message is well-formed */ static int -check_dht_p2p_result (void *cls, - const struct PeerResultMessage *prm) +check_dht_p2p_result(void *cls, + const struct PeerResultMessage *prm) { uint32_t get_path_length; uint32_t put_path_length; uint16_t msize; - (void) cls; - msize = ntohs (prm->header.size); - put_path_length = ntohl (prm->put_path_length); - get_path_length = ntohl (prm->get_path_length); + (void)cls; + msize = ntohs(prm->header.size); + put_path_length = ntohl(prm->put_path_length); + get_path_length = ntohl(prm->get_path_length); if ((msize < - sizeof (struct PeerResultMessage) + (get_path_length + - put_path_length) * - sizeof (struct GNUNET_PeerIdentity)) || + sizeof(struct PeerResultMessage) + (get_path_length + + put_path_length) * + sizeof(struct GNUNET_PeerIdentity)) || (get_path_length > - GNUNET_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) || + GNUNET_MAX_MESSAGE_SIZE / sizeof(struct GNUNET_PeerIdentity)) || (put_path_length > - GNUNET_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity))) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + GNUNET_MAX_MESSAGE_SIZE / sizeof(struct GNUNET_PeerIdentity))) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -2259,64 +2251,64 @@ check_dht_p2p_result (void *cls, * @param data payload of the reply */ static void -process_reply_with_path (struct GNUNET_TIME_Absolute expiration_time, - const struct GNUNET_HashCode *key, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *get_path, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path, - enum GNUNET_BLOCK_Type type, - size_t data_size, - const void *data) +process_reply_with_path(struct GNUNET_TIME_Absolute expiration_time, + const struct GNUNET_HashCode *key, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *get_path, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path, + enum GNUNET_BLOCK_Type type, + size_t data_size, + const void *data) { /* forward to local clients */ - GDS_CLIENTS_handle_reply (expiration_time, - key, - get_path_length, - get_path, - put_path_length, - put_path, - type, - data_size, - data); - GDS_CLIENTS_process_get_resp (type, - get_path, - get_path_length, - put_path, - put_path_length, - expiration_time, - key, - data, - data_size); + GDS_CLIENTS_handle_reply(expiration_time, + key, + get_path_length, + get_path, + put_path_length, + put_path, + type, + data_size, + data); + GDS_CLIENTS_process_get_resp(type, + get_path, + get_path_length, + put_path, + put_path_length, + expiration_time, + key, + data, + data_size); if (GNUNET_YES == cache_results) - { - struct GNUNET_PeerIdentity xput_path[get_path_length + 1 + put_path_length]; + { + struct GNUNET_PeerIdentity xput_path[get_path_length + 1 + put_path_length]; - GNUNET_memcpy (xput_path, - put_path, - put_path_length * sizeof (struct GNUNET_PeerIdentity)); - GNUNET_memcpy (&xput_path[put_path_length], - get_path, - get_path_length * sizeof (struct GNUNET_PeerIdentity)); + GNUNET_memcpy(xput_path, + put_path, + put_path_length * sizeof(struct GNUNET_PeerIdentity)); + GNUNET_memcpy(&xput_path[put_path_length], + get_path, + get_path_length * sizeof(struct GNUNET_PeerIdentity)); - GDS_DATACACHE_handle_put (expiration_time, - key, - get_path_length + put_path_length, - xput_path, - type, - data_size, - data); - } + GDS_DATACACHE_handle_put(expiration_time, + key, + get_path_length + put_path_length, + xput_path, + type, + data_size, + data); + } /* forward to other peers */ - GDS_ROUTING_process (type, - expiration_time, - key, - put_path_length, - put_path, - get_path_length, - get_path, - data, - data_size); + GDS_ROUTING_process(type, + expiration_time, + key, + put_path_length, + put_path, + get_path_length, + get_path, + data, + data_size); } @@ -2327,8 +2319,8 @@ process_reply_with_path (struct GNUNET_TIME_Absolute expiration_time, * @param message message */ static void -handle_dht_p2p_result (void *cls, - const struct PeerResultMessage *prm) +handle_dht_p2p_result(void *cls, + const struct PeerResultMessage *prm) { struct PeerInfo *peer = cls; const struct GNUNET_PeerIdentity *put_path; @@ -2342,125 +2334,125 @@ handle_dht_p2p_result (void *cls, struct GNUNET_TIME_Absolute exp_time; /* parse and validate message */ - exp_time = GNUNET_TIME_absolute_ntoh (prm->expiration_time); - if (0 == GNUNET_TIME_absolute_get_remaining (exp_time).rel_value_us) - { - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# Expired results discarded"), - 1, - GNUNET_NO); - return; - } - msize = ntohs (prm->header.size); - put_path_length = ntohl (prm->put_path_length); - get_path_length = ntohl (prm->get_path_length); - put_path = (const struct GNUNET_PeerIdentity *) &prm[1]; - get_path = &put_path[put_path_length]; - type = ntohl (prm->type); - data = (const void *) &get_path[get_path_length]; - data_size = msize - (sizeof (struct PeerResultMessage) + - (get_path_length + - put_path_length) * sizeof (struct GNUNET_PeerIdentity)); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# P2P RESULTS received"), - 1, - GNUNET_NO); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# P2P RESULT bytes received"), - msize, - GNUNET_NO); - if (GNUNET_YES == log_route_details_stderr) - { - char *tmp; - char *pp; - char *gp; - - gp = GNUNET_STRINGS_pp2s (get_path, - get_path_length); - pp = GNUNET_STRINGS_pp2s (put_path, - put_path_length); - tmp = GNUNET_strdup (GNUNET_i2s (&my_identity)); - LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, - "R5N RESULT %s: %s->%s (GP: %s, PP: %s)\n", - GNUNET_h2s (&prm->key), - GNUNET_i2s (peer->id), - tmp, - gp, - pp); - GNUNET_free (gp); - GNUNET_free (pp); - GNUNET_free (tmp); - } - /* if we got a HELLO, consider it for our own routing table */ - if (GNUNET_BLOCK_TYPE_DHT_HELLO == type) - { - const struct GNUNET_MessageHeader *h; - struct GNUNET_PeerIdentity pid; - - /* Should be a HELLO, validate and consider using it! */ - if (data_size < sizeof (struct GNUNET_HELLO_Message)) + exp_time = GNUNET_TIME_absolute_ntoh(prm->expiration_time); + if (0 == GNUNET_TIME_absolute_get_remaining(exp_time).rel_value_us) { - GNUNET_break_op (0); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# Expired results discarded"), + 1, + GNUNET_NO); return; } - h = data; - if (data_size != ntohs (h->size)) + msize = ntohs(prm->header.size); + put_path_length = ntohl(prm->put_path_length); + get_path_length = ntohl(prm->get_path_length); + put_path = (const struct GNUNET_PeerIdentity *)&prm[1]; + get_path = &put_path[put_path_length]; + type = ntohl(prm->type); + data = (const void *)&get_path[get_path_length]; + data_size = msize - (sizeof(struct PeerResultMessage) + + (get_path_length + + put_path_length) * sizeof(struct GNUNET_PeerIdentity)); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# P2P RESULTS received"), + 1, + GNUNET_NO); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# P2P RESULT bytes received"), + msize, + GNUNET_NO); + if (GNUNET_YES == log_route_details_stderr) { - GNUNET_break_op (0); - return; + char *tmp; + char *pp; + char *gp; + + gp = GNUNET_STRINGS_pp2s(get_path, + get_path_length); + pp = GNUNET_STRINGS_pp2s(put_path, + put_path_length); + tmp = GNUNET_strdup(GNUNET_i2s(&my_identity)); + LOG_TRAFFIC(GNUNET_ERROR_TYPE_DEBUG, + "R5N RESULT %s: %s->%s (GP: %s, PP: %s)\n", + GNUNET_h2s(&prm->key), + GNUNET_i2s(peer->id), + tmp, + gp, + pp); + GNUNET_free(gp); + GNUNET_free(pp); + GNUNET_free(tmp); } - if (GNUNET_OK != - GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, - &pid)) + /* if we got a HELLO, consider it for our own routing table */ + if (GNUNET_BLOCK_TYPE_DHT_HELLO == type) { - GNUNET_break_op (0); - return; - } - if ( (GNUNET_YES != disable_try_connect) && - (0 != memcmp (&my_identity, + const struct GNUNET_MessageHeader *h; + struct GNUNET_PeerIdentity pid; + + /* Should be a HELLO, validate and consider using it! */ + if (data_size < sizeof(struct GNUNET_HELLO_Message)) + { + GNUNET_break_op(0); + return; + } + h = data; + if (data_size != ntohs(h->size)) + { + GNUNET_break_op(0); + return; + } + if (GNUNET_OK != + GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)h, + &pid)) + { + GNUNET_break_op(0); + return; + } + if ((GNUNET_YES != disable_try_connect) && + (0 != memcmp(&my_identity, &pid, - sizeof (struct GNUNET_PeerIdentity))) ) - try_connect (&pid, - h); - } + sizeof(struct GNUNET_PeerIdentity)))) + try_connect(&pid, + h); + } /* First, check if 'peer' is already on the path, and if so, truncate it instead of expanding. */ - for (unsigned int i=0;i<=get_path_length;i++) - if (0 == memcmp (&get_path[i], - peer->id, - sizeof (struct GNUNET_PeerIdentity))) - { - process_reply_with_path (exp_time, - &prm->key, - i, - get_path, - put_path_length, - put_path, - type, - data_size, - data); - return; - } + for (unsigned int i = 0; i <= get_path_length; i++) + if (0 == memcmp(&get_path[i], + peer->id, + sizeof(struct GNUNET_PeerIdentity))) + { + process_reply_with_path(exp_time, + &prm->key, + i, + get_path, + put_path_length, + put_path, + type, + data_size, + data); + return; + } /* Need to append 'peer' to 'get_path' (normal case) */ { struct GNUNET_PeerIdentity xget_path[get_path_length + 1]; - GNUNET_memcpy (xget_path, - get_path, - get_path_length * sizeof (struct GNUNET_PeerIdentity)); + GNUNET_memcpy(xget_path, + get_path, + get_path_length * sizeof(struct GNUNET_PeerIdentity)); xget_path[get_path_length] = *peer->id; - process_reply_with_path (exp_time, - &prm->key, - get_path_length + 1, - xget_path, - put_path_length, - put_path, - type, - data_size, - data); + process_reply_with_path(exp_time, + &prm->key, + get_path_length + 1, + xget_path, + put_path_length, + put_path, + type, + data_size, + data); } } @@ -2471,55 +2463,55 @@ handle_dht_p2p_result (void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GDS_NEIGHBOURS_init () +GDS_NEIGHBOURS_init() { struct GNUNET_MQ_MessageHandler core_handlers[] = { - GNUNET_MQ_hd_var_size (dht_p2p_get, - GNUNET_MESSAGE_TYPE_DHT_P2P_GET, - struct PeerGetMessage, - NULL), - GNUNET_MQ_hd_var_size (dht_p2p_put, - GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, - struct PeerPutMessage, - NULL), - GNUNET_MQ_hd_var_size (dht_p2p_result, - GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, - struct PeerResultMessage, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(dht_p2p_get, + GNUNET_MESSAGE_TYPE_DHT_P2P_GET, + struct PeerGetMessage, + NULL), + GNUNET_MQ_hd_var_size(dht_p2p_put, + GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, + struct PeerPutMessage, + NULL), + GNUNET_MQ_hd_var_size(dht_p2p_result, + GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, + struct PeerResultMessage, + NULL), + GNUNET_MQ_handler_end() }; unsigned long long temp_config_num; disable_try_connect - = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, - "DHT", - "DISABLE_TRY_CONNECT"); + = GNUNET_CONFIGURATION_get_value_yesno(GDS_cfg, + "DHT", + "DISABLE_TRY_CONNECT"); if (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_number (GDS_cfg, - "DHT", - "bucket_size", - &temp_config_num)) - bucket_size = (unsigned int) temp_config_num; + GNUNET_CONFIGURATION_get_value_number(GDS_cfg, + "DHT", + "bucket_size", + &temp_config_num)) + bucket_size = (unsigned int)temp_config_num; cache_results - = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, - "DHT", - "CACHE_RESULTS"); + = GNUNET_CONFIGURATION_get_value_yesno(GDS_cfg, + "DHT", + "CACHE_RESULTS"); log_route_details_stderr = (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO; - ats_ch = GNUNET_ATS_connectivity_init (GDS_cfg); - core_api = GNUNET_CORE_connect (GDS_cfg, - NULL, - &core_init, - &handle_core_connect, - &handle_core_disconnect, - core_handlers); + ats_ch = GNUNET_ATS_connectivity_init(GDS_cfg); + core_api = GNUNET_CORE_connect(GDS_cfg, + NULL, + &core_init, + &handle_core_connect, + &handle_core_disconnect, + core_handlers); if (NULL == core_api) return GNUNET_SYSERR; - all_connected_peers = GNUNET_CONTAINER_multipeermap_create (256, - GNUNET_YES); - all_desired_peers = GNUNET_CONTAINER_multipeermap_create (256, - GNUNET_NO); + all_connected_peers = GNUNET_CONTAINER_multipeermap_create(256, + GNUNET_YES); + all_desired_peers = GNUNET_CONTAINER_multipeermap_create(256, + GNUNET_NO); return GNUNET_OK; } @@ -2528,24 +2520,24 @@ GDS_NEIGHBOURS_init () * Shutdown neighbours subsystem. */ void -GDS_NEIGHBOURS_done () +GDS_NEIGHBOURS_done() { if (NULL == core_api) return; - GNUNET_CORE_disconnect (core_api); + GNUNET_CORE_disconnect(core_api); core_api = NULL; - GNUNET_assert (0 == - GNUNET_CONTAINER_multipeermap_size (all_connected_peers)); - GNUNET_CONTAINER_multipeermap_destroy (all_connected_peers); + GNUNET_assert(0 == + GNUNET_CONTAINER_multipeermap_size(all_connected_peers)); + GNUNET_CONTAINER_multipeermap_destroy(all_connected_peers); all_connected_peers = NULL; - GNUNET_CONTAINER_multipeermap_iterate (all_desired_peers, - &free_connect_info, - NULL); - GNUNET_CONTAINER_multipeermap_destroy (all_desired_peers); + GNUNET_CONTAINER_multipeermap_iterate(all_desired_peers, + &free_connect_info, + NULL); + GNUNET_CONTAINER_multipeermap_destroy(all_desired_peers); all_desired_peers = NULL; - GNUNET_ATS_connectivity_done (ats_ch); + GNUNET_ATS_connectivity_done(ats_ch); ats_ch = NULL; - GNUNET_assert (NULL == find_peer_task); + GNUNET_assert(NULL == find_peer_task); } @@ -2555,7 +2547,7 @@ GDS_NEIGHBOURS_done () * @return identity of the local node */ struct GNUNET_PeerIdentity * -GDS_NEIGHBOURS_get_id () +GDS_NEIGHBOURS_get_id() { return &my_identity; } diff --git a/src/dht/gnunet-service-dht_neighbours.h b/src/dht/gnunet-service-dht_neighbours.h index dae854fb8..8b7a22422 100644 --- a/src/dht/gnunet-service-dht_neighbours.h +++ b/src/dht/gnunet-service-dht_neighbours.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht_neighbours.h @@ -58,16 +58,16 @@ extern struct GNUNET_HashCode my_identity_hash; * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not */ int -GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type, - enum GNUNET_DHT_RouteOption options, - uint32_t desired_replication_level, - struct GNUNET_TIME_Absolute expiration_time, - uint32_t hop_count, - struct GNUNET_CONTAINER_BloomFilter *bf, - const struct GNUNET_HashCode *key, - unsigned int put_path_length, - struct GNUNET_PeerIdentity *put_path, - const void *data, size_t data_size); +GDS_NEIGHBOURS_handle_put(enum GNUNET_BLOCK_Type type, + enum GNUNET_DHT_RouteOption options, + uint32_t desired_replication_level, + struct GNUNET_TIME_Absolute expiration_time, + uint32_t hop_count, + struct GNUNET_CONTAINER_BloomFilter *bf, + const struct GNUNET_HashCode *key, + unsigned int put_path_length, + struct GNUNET_PeerIdentity *put_path, + const void *data, size_t data_size); /** @@ -88,15 +88,15 @@ GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type, * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not */ int -GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type, - enum GNUNET_DHT_RouteOption options, - uint32_t desired_replication_level, - uint32_t hop_count, - const struct GNUNET_HashCode *key, - const void *xquery, - size_t xquery_size, - struct GNUNET_BLOCK_Group *bg, - struct GNUNET_CONTAINER_BloomFilter *peer_bf); +GDS_NEIGHBOURS_handle_get(enum GNUNET_BLOCK_Type type, + enum GNUNET_DHT_RouteOption options, + uint32_t desired_replication_level, + uint32_t hop_count, + const struct GNUNET_HashCode *key, + const void *xquery, + size_t xquery_size, + struct GNUNET_BLOCK_Group *bg, + struct GNUNET_CONTAINER_BloomFilter *peer_bf); /** @@ -116,16 +116,16 @@ GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type, * @param data_size number of bytes in data */ void -GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute expiration_time, - const struct GNUNET_HashCode *key, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *get_path, - const void *data, - size_t data_size); +GDS_NEIGHBOURS_handle_reply(const struct GNUNET_PeerIdentity *target, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute expiration_time, + const struct GNUNET_HashCode *key, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *get_path, + const void *data, + size_t data_size); /** @@ -139,8 +139,8 @@ GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target, * #GNUNET_NO otherwise. */ int -GDS_am_closest_peer (const struct GNUNET_HashCode *key, - const struct GNUNET_CONTAINER_BloomFilter *bloom); +GDS_am_closest_peer(const struct GNUNET_HashCode *key, + const struct GNUNET_CONTAINER_BloomFilter *bloom); @@ -150,14 +150,14 @@ GDS_am_closest_peer (const struct GNUNET_HashCode *key, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GDS_NEIGHBOURS_init (void); +GDS_NEIGHBOURS_init(void); /** * Shutdown neighbours subsystem. */ void -GDS_NEIGHBOURS_done (void); +GDS_NEIGHBOURS_done(void); /** @@ -166,7 +166,7 @@ GDS_NEIGHBOURS_done (void); * @return identity of the local node */ struct GNUNET_PeerIdentity * -GDS_NEIGHBOURS_get_id (void); +GDS_NEIGHBOURS_get_id(void); #endif diff --git a/src/dht/gnunet-service-dht_nse.c b/src/dht/gnunet-service-dht_nse.c index d59d46dd3..07ebb5299 100644 --- a/src/dht/gnunet-service-dht_nse.c +++ b/src/dht/gnunet-service-dht_nse.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht_nse.c @@ -52,14 +52,14 @@ static struct GNUNET_NSE_Handle *nse; * */ static void -update_network_size_estimate (void *cls, struct GNUNET_TIME_Absolute timestamp, - double logestimate, double std_dev) +update_network_size_estimate(void *cls, struct GNUNET_TIME_Absolute timestamp, + double logestimate, double std_dev) { - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# Network size estimates received"), - 1, GNUNET_NO); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# Network size estimates received"), + 1, GNUNET_NO); /* do not allow estimates < 0.5 */ - log_of_network_size_estimate = GNUNET_MAX (0.5, logestimate); + log_of_network_size_estimate = GNUNET_MAX(0.5, logestimate); } @@ -69,7 +69,7 @@ update_network_size_estimate (void *cls, struct GNUNET_TIME_Absolute timestamp, * @return log of NSE */ double -GDS_NSE_get () +GDS_NSE_get() { return log_of_network_size_estimate; } @@ -79,24 +79,24 @@ GDS_NSE_get () * Initialize NSE subsystem. */ void -GDS_NSE_init () +GDS_NSE_init() { unsigned long long hops; - if ( (GNUNET_YES == - GNUNET_CONFIGURATION_have_value (GDS_cfg, - "dht", - "FORCE_NSE")) && - (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_number (GDS_cfg, - "dht", - "FORCE_NSE", - &hops)) ) - { - log_of_network_size_estimate = (double) hops; - return; - } - nse = GNUNET_NSE_connect (GDS_cfg, &update_network_size_estimate, NULL); + if ((GNUNET_YES == + GNUNET_CONFIGURATION_have_value(GDS_cfg, + "dht", + "FORCE_NSE")) && + (GNUNET_OK == + GNUNET_CONFIGURATION_get_value_number(GDS_cfg, + "dht", + "FORCE_NSE", + &hops))) + { + log_of_network_size_estimate = (double)hops; + return; + } + nse = GNUNET_NSE_connect(GDS_cfg, &update_network_size_estimate, NULL); } @@ -104,13 +104,13 @@ GDS_NSE_init () * Shutdown NSE subsystem. */ void -GDS_NSE_done () +GDS_NSE_done() { if (NULL != nse) - { - GNUNET_NSE_disconnect (nse); - nse = NULL; - } + { + GNUNET_NSE_disconnect(nse); + nse = NULL; + } } /* end of gnunet-service-dht_nse.c */ diff --git a/src/dht/gnunet-service-dht_nse.h b/src/dht/gnunet-service-dht_nse.h index 4402bb860..d3cc9f383 100644 --- a/src/dht/gnunet-service-dht_nse.h +++ b/src/dht/gnunet-service-dht_nse.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht_nse.h @@ -33,20 +33,20 @@ * @return log of NSE */ double -GDS_NSE_get (void); +GDS_NSE_get(void); /** * Initialize NSE subsystem. */ void -GDS_NSE_init (void); +GDS_NSE_init(void); /** * Shutdown NSE subsystem. */ void -GDS_NSE_done (void); +GDS_NSE_done(void); #endif diff --git a/src/dht/gnunet-service-dht_routing.c b/src/dht/gnunet-service-dht_routing.c index 1cee45a22..99c6b5e4f 100644 --- a/src/dht/gnunet-service-dht_routing.c +++ b/src/dht/gnunet-service-dht_routing.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht_routing.c @@ -39,9 +39,7 @@ * Information we keep about all recent GET requests * so that we can route replies. */ -struct RecentRequest -{ - +struct RecentRequest { /** * The peer this request was received from. */ @@ -82,7 +80,6 @@ struct RecentRequest * Request options. */ enum GNUNET_DHT_RouteOption options; - }; @@ -100,8 +97,7 @@ static struct GNUNET_CONTAINER_MultiHashMap *recent_map; /** * Closure for the 'process' function. */ -struct ProcessContext -{ +struct ProcessContext { /** * Path of the original PUT */ @@ -141,7 +137,6 @@ struct ProcessContext * Type of the reply. */ enum GNUNET_BLOCK_Type type; - }; @@ -155,9 +150,9 @@ struct ProcessContext * #GNUNET_SYSERR if the result is malformed or type unsupported */ static int -process (void *cls, - const struct GNUNET_HashCode *key, - void *value) +process(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct ProcessContext *pc = cls; struct RecentRequest *rr = value; @@ -167,104 +162,111 @@ process (void *cls, struct GNUNET_HashCode hc; const struct GNUNET_HashCode *eval_key; - if ( (rr->type != GNUNET_BLOCK_TYPE_ANY) && - (rr->type != pc->type) ) + if ((rr->type != GNUNET_BLOCK_TYPE_ANY) && + (rr->type != pc->type)) return GNUNET_OK; /* type missmatch */ if (0 != (rr->options & GNUNET_DHT_RO_RECORD_ROUTE)) - { - gpl = pc->get_path_length; - ppl = pc->put_path_length; - } + { + gpl = pc->get_path_length; + ppl = pc->put_path_length; + } else - { - gpl = 0; - ppl = 0; - } - if ( (0 != (rr->options & GNUNET_DHT_RO_FIND_PEER)) && - (pc->type == GNUNET_BLOCK_TYPE_DHT_HELLO) ) - { - /* key may not match HELLO, which is OK since - * the search is approximate. Still, the evaluation - * would fail since the match is not exact. So - * we fake it by changing the key to the actual PID ... */ - GNUNET_BLOCK_get_key (GDS_block_context, - GNUNET_BLOCK_TYPE_DHT_HELLO, - pc->data, - pc->data_size, - &hc); - eval_key = &hc; - } + { + gpl = 0; + ppl = 0; + } + if ((0 != (rr->options & GNUNET_DHT_RO_FIND_PEER)) && + (pc->type == GNUNET_BLOCK_TYPE_DHT_HELLO)) + { + /* key may not match HELLO, which is OK since + * the search is approximate. Still, the evaluation + * would fail since the match is not exact. So + * we fake it by changing the key to the actual PID ... */ + GNUNET_BLOCK_get_key(GDS_block_context, + GNUNET_BLOCK_TYPE_DHT_HELLO, + pc->data, + pc->data_size, + &hc); + eval_key = &hc; + } else - { - eval_key = key; - } + { + eval_key = key; + } eval - = GNUNET_BLOCK_evaluate (GDS_block_context, - pc->type, - rr->bg, - GNUNET_BLOCK_EO_NONE, - eval_key, - rr->xquery, - rr->xquery_size, - pc->data, - pc->data_size); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Result for %s of type %d was evaluated as %d\n", - GNUNET_h2s (key), - pc->type, - eval); + = GNUNET_BLOCK_evaluate(GDS_block_context, + pc->type, + rr->bg, + GNUNET_BLOCK_EO_NONE, + eval_key, + rr->xquery, + rr->xquery_size, + pc->data, + pc->data_size); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Result for %s of type %d was evaluated as %d\n", + GNUNET_h2s(key), + pc->type, + eval); switch (eval) - { - case GNUNET_BLOCK_EVALUATION_OK_MORE: - case GNUNET_BLOCK_EVALUATION_OK_LAST: - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# Good REPLIES matched against routing table"), - 1, GNUNET_NO); - GDS_NEIGHBOURS_handle_reply (&rr->peer, - pc->type, - pc->expiration_time, - key, - ppl, pc->put_path, - gpl, pc->get_path, - pc->data, - pc->data_size); - break; - case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE: - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# Duplicate REPLIES matched against routing table"), - 1, GNUNET_NO); - return GNUNET_OK; - case GNUNET_BLOCK_EVALUATION_RESULT_INVALID: - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# Invalid REPLIES matched against routing table"), - 1, GNUNET_NO); - return GNUNET_SYSERR; - case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT: - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# Irrelevant REPLIES matched against routing table"), - 1, GNUNET_NO); - return GNUNET_OK; - case GNUNET_BLOCK_EVALUATION_REQUEST_VALID: - GNUNET_break (0); - return GNUNET_OK; - case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID: - GNUNET_break (0); - return GNUNET_OK; - case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED: - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# Unsupported REPLIES matched against routing table"), - 1, GNUNET_NO); - return GNUNET_SYSERR; - default: - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + case GNUNET_BLOCK_EVALUATION_OK_MORE: + case GNUNET_BLOCK_EVALUATION_OK_LAST: + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# Good REPLIES matched against routing table"), + 1, GNUNET_NO); + GDS_NEIGHBOURS_handle_reply(&rr->peer, + pc->type, + pc->expiration_time, + key, + ppl, pc->put_path, + gpl, pc->get_path, + pc->data, + pc->data_size); + break; + + case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE: + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# Duplicate REPLIES matched against routing table"), + 1, GNUNET_NO); + return GNUNET_OK; + + case GNUNET_BLOCK_EVALUATION_RESULT_INVALID: + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# Invalid REPLIES matched against routing table"), + 1, GNUNET_NO); + return GNUNET_SYSERR; + + case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT: + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# Irrelevant REPLIES matched against routing table"), + 1, GNUNET_NO); + return GNUNET_OK; + + case GNUNET_BLOCK_EVALUATION_REQUEST_VALID: + GNUNET_break(0); + return GNUNET_OK; + + case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID: + GNUNET_break(0); + return GNUNET_OK; + + case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED: + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# Unsupported REPLIES matched against routing table"), + 1, GNUNET_NO); + return GNUNET_SYSERR; + + default: + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -287,15 +289,15 @@ process (void *cls, * @param data_size number of bytes in data */ void -GDS_ROUTING_process (enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute expiration_time, - const struct GNUNET_HashCode *key, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *get_path, - const void *data, - size_t data_size) +GDS_ROUTING_process(enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute expiration_time, + const struct GNUNET_HashCode *key, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *get_path, + const void *data, + size_t data_size) { struct ProcessContext pc; @@ -308,19 +310,19 @@ GDS_ROUTING_process (enum GNUNET_BLOCK_Type type, pc.data = data; pc.data_size = data_size; if (NULL == data) - { - /* Some apps might have an 'empty' reply as a valid reply; however, - 'process' will call GNUNET_BLOCK_evaluate' which treats a 'NULL' - reply as request-validation (but we need response-validation). - So we set 'data' to a 0-byte non-NULL value just to be sure */ - GNUNET_break (0 == data_size); - pc.data_size = 0; - pc.data = ""; /* something not null */ - } - GNUNET_CONTAINER_multihashmap_get_multiple (recent_map, - key, - &process, - &pc); + { + /* Some apps might have an 'empty' reply as a valid reply; however, + 'process' will call GNUNET_BLOCK_evaluate' which treats a 'NULL' + reply as request-validation (but we need response-validation). + So we set 'data' to a 0-byte non-NULL value just to be sure */ + GNUNET_break(0 == data_size); + pc.data_size = 0; + pc.data = ""; /* something not null */ + } + GNUNET_CONTAINER_multihashmap_get_multiple(recent_map, + key, + &process, + &pc); } @@ -330,23 +332,23 @@ GDS_ROUTING_process (enum GNUNET_BLOCK_Type type, * in the heap and hashmap. */ static void -expire_oldest_entry () +expire_oldest_entry() { struct RecentRequest *recent_req; - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# Entries removed from routing table"), 1, - GNUNET_NO); - recent_req = GNUNET_CONTAINER_heap_peek (recent_heap); - GNUNET_assert (recent_req != NULL); - GNUNET_CONTAINER_heap_remove_node (recent_req->heap_node); - GNUNET_BLOCK_group_destroy (recent_req->bg); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (recent_map, - &recent_req->key, - recent_req)); - GNUNET_free (recent_req); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# Entries removed from routing table"), 1, + GNUNET_NO); + recent_req = GNUNET_CONTAINER_heap_peek(recent_heap); + GNUNET_assert(recent_req != NULL); + GNUNET_CONTAINER_heap_remove_node(recent_req->heap_node); + GNUNET_BLOCK_group_destroy(recent_req->bg); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(recent_map, + &recent_req->key, + recent_req)); + GNUNET_free(recent_req); } @@ -361,26 +363,26 @@ expire_oldest_entry () * #GNUNET_SYSERR if the request was successfully combined */ static int -try_combine_recent (void *cls, - const struct GNUNET_HashCode *key, - void *value) +try_combine_recent(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct RecentRequest *in = cls; struct RecentRequest *rr = value; - if ( (0 != GNUNET_memcmp (&in->peer, - &rr->peer)) || - (in->type != rr->type) || - (in->xquery_size != rr->xquery_size) || - (0 != memcmp (in->xquery, - rr->xquery, - in->xquery_size)) ) + if ((0 != GNUNET_memcmp(&in->peer, + &rr->peer)) || + (in->type != rr->type) || + (in->xquery_size != rr->xquery_size) || + (0 != memcmp(in->xquery, + rr->xquery, + in->xquery_size))) return GNUNET_OK; - GNUNET_break (GNUNET_SYSERR != - GNUNET_BLOCK_group_merge (in->bg, - rr->bg)); + GNUNET_break(GNUNET_SYSERR != + GNUNET_BLOCK_group_merge(in->bg, + rr->bg)); rr->bg = in->bg; - GNUNET_free (in); + GNUNET_free(in); return GNUNET_SYSERR; } @@ -398,53 +400,53 @@ try_combine_recent (void *cls, * @param reply_bf_mutator mutator for @a reply_bf */ void -GDS_ROUTING_add (const struct GNUNET_PeerIdentity *sender, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *bg, - enum GNUNET_DHT_RouteOption options, - const struct GNUNET_HashCode *key, - const void *xquery, - size_t xquery_size) +GDS_ROUTING_add(const struct GNUNET_PeerIdentity *sender, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *bg, + enum GNUNET_DHT_RouteOption options, + const struct GNUNET_HashCode *key, + const void *xquery, + size_t xquery_size) { struct RecentRequest *recent_req; - while (GNUNET_CONTAINER_heap_get_size (recent_heap) >= DHT_MAX_RECENT) - expire_oldest_entry (); - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop ("# Entries added to routing table"), - 1, - GNUNET_NO); - recent_req = GNUNET_malloc (sizeof (struct RecentRequest) + xquery_size); + while (GNUNET_CONTAINER_heap_get_size(recent_heap) >= DHT_MAX_RECENT) + expire_oldest_entry(); + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop("# Entries added to routing table"), + 1, + GNUNET_NO); + recent_req = GNUNET_malloc(sizeof(struct RecentRequest) + xquery_size); recent_req->peer = *sender; recent_req->key = *key; recent_req->bg = bg; recent_req->type = type; recent_req->options = options; recent_req->xquery = &recent_req[1]; - GNUNET_memcpy (&recent_req[1], - xquery, - xquery_size); + GNUNET_memcpy(&recent_req[1], + xquery, + xquery_size); recent_req->xquery_size = xquery_size; if (GNUNET_SYSERR == - GNUNET_CONTAINER_multihashmap_get_multiple (recent_map, - key, - &try_combine_recent, - recent_req)) - { - GNUNET_STATISTICS_update (GDS_stats, - gettext_noop - ("# DHT requests combined"), - 1, GNUNET_NO); - return; - } + GNUNET_CONTAINER_multihashmap_get_multiple(recent_map, + key, + &try_combine_recent, + recent_req)) + { + GNUNET_STATISTICS_update(GDS_stats, + gettext_noop + ("# DHT requests combined"), + 1, GNUNET_NO); + return; + } recent_req->heap_node - = GNUNET_CONTAINER_heap_insert (recent_heap, + = GNUNET_CONTAINER_heap_insert(recent_heap, + recent_req, + GNUNET_TIME_absolute_get().abs_value_us); + GNUNET_CONTAINER_multihashmap_put(recent_map, + key, recent_req, - GNUNET_TIME_absolute_get ().abs_value_us); - GNUNET_CONTAINER_multihashmap_put (recent_map, - key, - recent_req, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); } @@ -452,10 +454,10 @@ GDS_ROUTING_add (const struct GNUNET_PeerIdentity *sender, * Initialize routing subsystem. */ void -GDS_ROUTING_init () +GDS_ROUTING_init() { - recent_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); - recent_map = GNUNET_CONTAINER_multihashmap_create (DHT_MAX_RECENT * 4 / 3, GNUNET_NO); + recent_heap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN); + recent_map = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT * 4 / 3, GNUNET_NO); } @@ -463,15 +465,15 @@ GDS_ROUTING_init () * Shutdown routing subsystem. */ void -GDS_ROUTING_done () +GDS_ROUTING_done() { - while (GNUNET_CONTAINER_heap_get_size (recent_heap) > 0) - expire_oldest_entry (); - GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (recent_heap)); - GNUNET_CONTAINER_heap_destroy (recent_heap); + while (GNUNET_CONTAINER_heap_get_size(recent_heap) > 0) + expire_oldest_entry(); + GNUNET_assert(0 == GNUNET_CONTAINER_heap_get_size(recent_heap)); + GNUNET_CONTAINER_heap_destroy(recent_heap); recent_heap = NULL; - GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (recent_map)); - GNUNET_CONTAINER_multihashmap_destroy (recent_map); + GNUNET_assert(0 == GNUNET_CONTAINER_multihashmap_size(recent_map)); + GNUNET_CONTAINER_multihashmap_destroy(recent_map); recent_map = NULL; } diff --git a/src/dht/gnunet-service-dht_routing.h b/src/dht/gnunet-service-dht_routing.h index e7f707296..ace6b9c0c 100644 --- a/src/dht/gnunet-service-dht_routing.h +++ b/src/dht/gnunet-service-dht_routing.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet-service-dht_routing.h @@ -49,15 +49,15 @@ * @param data_size number of bytes in @a data */ void -GDS_ROUTING_process (enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute expiration_time, - const struct GNUNET_HashCode *key, - unsigned int put_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *get_path, - const void *data, - size_t data_size); +GDS_ROUTING_process(enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute expiration_time, + const struct GNUNET_HashCode *key, + unsigned int put_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *get_path, + const void *data, + size_t data_size); /** @@ -72,26 +72,26 @@ GDS_ROUTING_process (enum GNUNET_BLOCK_Type type, * @param xquery_size number of bytes in @a xquery */ void -GDS_ROUTING_add (const struct GNUNET_PeerIdentity *sender, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *bg, - enum GNUNET_DHT_RouteOption options, - const struct GNUNET_HashCode * key, - const void *xquery, - size_t xquery_size); +GDS_ROUTING_add(const struct GNUNET_PeerIdentity *sender, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *bg, + enum GNUNET_DHT_RouteOption options, + const struct GNUNET_HashCode * key, + const void *xquery, + size_t xquery_size); /** * Initialize routing subsystem. */ void -GDS_ROUTING_init (void); +GDS_ROUTING_init(void); /** * Shutdown routing subsystem. */ void -GDS_ROUTING_done (void); +GDS_ROUTING_done(void); #endif diff --git a/src/dht/gnunet_dht_profiler.c b/src/dht/gnunet_dht_profiler.c index a8f5a3aca..179f84a11 100644 --- a/src/dht/gnunet_dht_profiler.c +++ b/src/dht/gnunet_dht_profiler.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/gnunet_dht_profiler.c @@ -32,10 +32,10 @@ #define MESSAGE(...) \ - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, __VA_ARGS__) + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, __VA_ARGS__) #define DEBUG(...) \ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__) /** * Number of peers which should perform a PUT out of 100 peers @@ -60,8 +60,7 @@ struct ActiveContext; /** * Context to hold data of peer */ -struct Context -{ +struct Context { /** * The testbed peer this context belongs to */ @@ -76,15 +75,13 @@ struct Context * Active context; NULL if this peer is not an active peer */ struct ActiveContext *ac; - }; /** * Context for a peer which actively does DHT PUT/GET */ -struct ActiveContext -{ +struct ActiveContext { /** * The linked peer context */ @@ -261,8 +258,7 @@ static int peers_started = 0; /** * Should we do a PUT (mode = 0) or GET (mode = 1); */ -static enum -{ +static enum { MODE_PUT = 0, MODE_GET = 1 @@ -279,7 +275,7 @@ static int in_shutdown = 0; * Connect to DHT services of active peers */ static void -start_profiling (void); +start_profiling(void); /** @@ -288,43 +284,43 @@ start_profiling (void); * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { struct ActiveContext *ac; in_shutdown = GNUNET_YES; if (NULL != a_ctx) - { - for (unsigned int cnt=0; cnt < num_peers; cnt++) { - /* Cleanup active context if this peer is an active peer */ - ac = a_ctx[cnt].ac; - if (NULL != ac) - { - if (NULL != ac->delay_task) - GNUNET_SCHEDULER_cancel (ac->delay_task); - if (NULL != ac->hash) - free (ac->hash); - if (NULL != ac->dht_put) - GNUNET_DHT_put_cancel (ac->dht_put); - if (NULL != ac->dht_get) - GNUNET_DHT_get_stop (ac->dht_get); - } - /* Cleanup testbed operation handle at the last as this operation may - contain service connection to DHT */ - if (NULL != a_ctx[cnt].op) - GNUNET_TESTBED_operation_done (a_ctx[cnt].op); + for (unsigned int cnt = 0; cnt < num_peers; cnt++) + { + /* Cleanup active context if this peer is an active peer */ + ac = a_ctx[cnt].ac; + if (NULL != ac) + { + if (NULL != ac->delay_task) + GNUNET_SCHEDULER_cancel(ac->delay_task); + if (NULL != ac->hash) + free(ac->hash); + if (NULL != ac->dht_put) + GNUNET_DHT_put_cancel(ac->dht_put); + if (NULL != ac->dht_get) + GNUNET_DHT_get_stop(ac->dht_get); + } + /* Cleanup testbed operation handle at the last as this operation may + contain service connection to DHT */ + if (NULL != a_ctx[cnt].op) + GNUNET_TESTBED_operation_done(a_ctx[cnt].op); + } + GNUNET_free(a_ctx); + a_ctx = NULL; } - GNUNET_free (a_ctx); - a_ctx = NULL; - } //FIXME: Should we collect stats only for put/get not for other messages. if (NULL != bandwidth_stats_op) - { - GNUNET_TESTBED_operation_done (bandwidth_stats_op); - bandwidth_stats_op = NULL; - } - GNUNET_free_non_null (a_ac); + { + GNUNET_TESTBED_operation_done(bandwidth_stats_op); + bandwidth_stats_op = NULL; + } + GNUNET_free_non_null(a_ac); } @@ -338,18 +334,18 @@ do_shutdown (void *cls) * operation has executed successfully. */ static void -bandwidth_stats_cont (void *cls, - struct GNUNET_TESTBED_Operation *op, - const char *emsg) +bandwidth_stats_cont(void *cls, + struct GNUNET_TESTBED_Operation *op, + const char *emsg) { - MESSAGE ("# Outgoing (core) bandwidth: %llu bytes\n", - (unsigned long long) outgoing_bandwidth); - MESSAGE ("# Incoming (core) bandwidth: %llu bytes\n", - (unsigned long long) incoming_bandwidth); - fprintf (stderr, - "Benchmark done. Collect data via gnunet-statistics, then press ENTER to exit.\n"); - (void) getchar (); - GNUNET_SCHEDULER_shutdown (); + MESSAGE("# Outgoing (core) bandwidth: %llu bytes\n", + (unsigned long long)outgoing_bandwidth); + MESSAGE("# Incoming (core) bandwidth: %llu bytes\n", + (unsigned long long)incoming_bandwidth); + fprintf(stderr, + "Benchmark done. Collect data via gnunet-statistics, then press ENTER to exit.\n"); + (void)getchar(); + GNUNET_SCHEDULER_shutdown(); } @@ -365,55 +361,55 @@ bandwidth_stats_cont (void *cls, * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration */ static int -bandwidth_stats_iterator (void *cls, - const struct GNUNET_TESTBED_Peer *peer, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +bandwidth_stats_iterator(void *cls, + const struct GNUNET_TESTBED_Peer *peer, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { static const char *s_sent = "# bytes encrypted"; static const char *s_recv = "# bytes decrypted"; - if (0 == strncmp (s_sent, name, strlen (s_sent))) + if (0 == strncmp(s_sent, name, strlen(s_sent))) outgoing_bandwidth = outgoing_bandwidth + value; - else if (0 == strncmp(s_recv, name, strlen (s_recv))) + else if (0 == strncmp(s_recv, name, strlen(s_recv))) incoming_bandwidth = incoming_bandwidth + value; return GNUNET_OK; } static void -summarize () +summarize() { - MESSAGE ("# PUTS started: %llu\n", - n_puts); - MESSAGE ("# PUTS succeeded: %llu\n", - n_puts_ok); - MESSAGE ("# GETS made: %u\n", - n_gets); - MESSAGE ("# GETS succeeded: %u\n", - n_gets_ok); - MESSAGE ("# GETS failed: %u\n", - n_gets_fail); - MESSAGE ("# average_put_path_length: %f\n", - average_put_path_length); - MESSAGE ("# average_get_path_length: %f\n", - average_get_path_length); + MESSAGE("# PUTS started: %llu\n", + n_puts); + MESSAGE("# PUTS succeeded: %llu\n", + n_puts_ok); + MESSAGE("# GETS made: %u\n", + n_gets); + MESSAGE("# GETS succeeded: %u\n", + n_gets_ok); + MESSAGE("# GETS failed: %u\n", + n_gets_fail); + MESSAGE("# average_put_path_length: %f\n", + average_put_path_length); + MESSAGE("# average_get_path_length: %f\n", + average_get_path_length); if (NULL == testbed_handles) - { - MESSAGE ("No peers found\n"); - return; - } + { + MESSAGE("No peers found\n"); + return; + } /* Collect Stats*/ - bandwidth_stats_op = GNUNET_TESTBED_get_statistics (n_active, - testbed_handles, - "core", - NULL, - &bandwidth_stats_iterator, - &bandwidth_stats_cont, - NULL); + bandwidth_stats_op = GNUNET_TESTBED_get_statistics(n_active, + testbed_handles, + "core", + NULL, + &bandwidth_stats_iterator, + &bandwidth_stats_cont, + NULL); } @@ -423,27 +419,27 @@ summarize () * @param cls NULL */ static void -cancel_get (void *cls) +cancel_get(void *cls) { struct ActiveContext *ac = cls; struct Context *ctx = ac->ctx; ac->delay_task = NULL; - GNUNET_assert (NULL != ac->dht_get); - GNUNET_DHT_get_stop (ac->dht_get); + GNUNET_assert(NULL != ac->dht_get); + GNUNET_DHT_get_stop(ac->dht_get); ac->dht_get = NULL; n_gets_fail++; - GNUNET_assert (NULL != ctx->op); - GNUNET_TESTBED_operation_done (ctx->op); + GNUNET_assert(NULL != ctx->op); + GNUNET_TESTBED_operation_done(ctx->op); ctx->op = NULL; /* If profiling is complete, summarize */ if (n_active == n_gets_fail + n_gets_ok) - { - average_put_path_length = (double)total_put_path_length/(double)n_active; - average_get_path_length = (double)total_get_path_length/(double )n_gets_ok; - summarize (); - } + { + average_put_path_length = (double)total_put_path_length / (double)n_active; + average_get_path_length = (double)total_get_path_length / (double )n_gets_ok; + summarize(); + } } @@ -465,45 +461,45 @@ cancel_get (void *cls) * @param data pointer to the result data */ static void -get_iter (void *cls, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - enum GNUNET_BLOCK_Type type, - size_t size, const void *data) +get_iter(void *cls, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + enum GNUNET_BLOCK_Type type, + size_t size, const void *data) { struct ActiveContext *ac = cls; struct ActiveContext *get_ac = ac->get_ac; struct Context *ctx = ac->ctx; /* we found the data we are looking for */ - DEBUG ("We found a GET request; %u remaining\n", - n_gets - (n_gets_fail + n_gets_ok)); //FIXME: It always prints 1. + DEBUG("We found a GET request; %u remaining\n", + n_gets - (n_gets_fail + n_gets_ok)); //FIXME: It always prints 1. n_gets_ok++; get_ac->nrefs--; - GNUNET_DHT_get_stop (ac->dht_get); + GNUNET_DHT_get_stop(ac->dht_get); ac->dht_get = NULL; if (ac->delay_task != NULL) - GNUNET_SCHEDULER_cancel (ac->delay_task); + GNUNET_SCHEDULER_cancel(ac->delay_task); ac->delay_task = NULL; - GNUNET_assert (NULL != ctx->op); - GNUNET_TESTBED_operation_done (ctx->op); + GNUNET_assert(NULL != ctx->op); + GNUNET_TESTBED_operation_done(ctx->op); ctx->op = NULL; total_put_path_length = total_put_path_length + (double)put_path_length; total_get_path_length = total_get_path_length + (double)get_path_length; - DEBUG ("total_put_path_length = %u,put_path \n", - total_put_path_length); + DEBUG("total_put_path_length = %u,put_path \n", + total_put_path_length); /* Summarize if profiling is complete */ if (n_active == n_gets_fail + n_gets_ok) - { - average_put_path_length = (double)total_put_path_length/(double)n_active; - average_get_path_length = (double)total_get_path_length/(double )n_gets_ok; - summarize (); - } + { + average_put_path_length = (double)total_put_path_length / (double)n_active; + average_get_path_length = (double)total_get_path_length / (double )n_gets_ok; + summarize(); + } } @@ -513,7 +509,7 @@ get_iter (void *cls, * @param cls the active context */ static void -delayed_get (void *cls) +delayed_get(void *cls) { struct ActiveContext *ac = cls; struct ActiveContext *get_ac; @@ -522,34 +518,34 @@ delayed_get (void *cls) ac->delay_task = NULL; get_ac = NULL; while (1) - { - r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - n_active); - get_ac = &a_ac[r]; - if (NULL != get_ac->hash) - break; - } + { + r = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + n_active); + get_ac = &a_ac[r]; + if (NULL != get_ac->hash) + break; + } get_ac->nrefs++; ac->get_ac = get_ac; - r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - num_puts_per_peer); - DEBUG ("GET_REQUEST_START key %s \n", - GNUNET_h2s(&get_ac->hash[r])); - ac->dht_get = GNUNET_DHT_get_start (ac->dht, - GNUNET_BLOCK_TYPE_TEST, - &get_ac->hash[r], - 1, /* replication level */ - GNUNET_DHT_RO_NONE, - NULL, - 0, /* extended query and size */ - &get_iter, - ac); /* GET iterator and closure */ + r = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + num_puts_per_peer); + DEBUG("GET_REQUEST_START key %s \n", + GNUNET_h2s(&get_ac->hash[r])); + ac->dht_get = GNUNET_DHT_get_start(ac->dht, + GNUNET_BLOCK_TYPE_TEST, + &get_ac->hash[r], + 1, /* replication level */ + GNUNET_DHT_RO_NONE, + NULL, + 0, /* extended query and size */ + &get_iter, + ac); /* GET iterator and closure */ n_gets++; /* schedule the timeout task for GET */ - ac->delay_task = GNUNET_SCHEDULER_add_delayed (timeout, - &cancel_get, - ac); + ac->delay_task = GNUNET_SCHEDULER_add_delayed(timeout, + &cancel_get, + ac); } @@ -561,7 +557,7 @@ delayed_get (void *cls) * @param cls the active context */ static void -delayed_put (void *cls); +delayed_put(void *cls); /** @@ -571,14 +567,14 @@ delayed_put (void *cls); * @param cls the active context */ static void -put_cont (void *cls) +put_cont(void *cls) { struct ActiveContext *ac = cls; ac->dht_put = NULL; n_puts_ok++; - ac->delay_task = GNUNET_SCHEDULER_add_now (&delayed_put, - ac); + ac->delay_task = GNUNET_SCHEDULER_add_now(&delayed_put, + ac); } @@ -590,7 +586,7 @@ put_cont (void *cls) * @param cls the active context */ static void -delayed_put (void *cls) +delayed_put(void *cls) { struct ActiveContext *ac = cls; char block[65536]; @@ -598,42 +594,42 @@ delayed_put (void *cls) ac->delay_task = NULL; if (0 == ac->put_count) - { - struct Context *ctx = ac->ctx; - struct GNUNET_TESTBED_Operation *op; - - GNUNET_assert (NULL != ctx); - op = ctx->op; - ctx->op = NULL; - GNUNET_TESTBED_operation_done (op); - return; - } + { + struct Context *ctx = ac->ctx; + struct GNUNET_TESTBED_Operation *op; + + GNUNET_assert(NULL != ctx); + op = ctx->op; + ctx->op = NULL; + GNUNET_TESTBED_operation_done(op); + return; + } /* Generate and DHT PUT some random data */ block_size = 16; /* minimum */ /* make random payload, reserve 512 - 16 bytes for DHT headers */ - block_size += GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE - 512); - GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, - block, - block_size); + block_size += GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE - 512); + GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_WEAK, + block, + block_size); ac->put_count--; - GNUNET_CRYPTO_hash (block, - block_size, - &ac->hash[ac->put_count]); - DEBUG ("PUT_REQUEST_START key %s\n", - GNUNET_h2s (&ac->hash[ac->put_count])); - ac->dht_put = GNUNET_DHT_put (ac->dht, - &ac->hash[ac->put_count], - replication, - GNUNET_DHT_RO_RECORD_ROUTE, - GNUNET_BLOCK_TYPE_TEST, - block_size, - block, - GNUNET_TIME_UNIT_FOREVER_ABS, /* expiration time */ - &put_cont, - ac); /* continuation and its closure */ + GNUNET_CRYPTO_hash(block, + block_size, + &ac->hash[ac->put_count]); + DEBUG("PUT_REQUEST_START key %s\n", + GNUNET_h2s(&ac->hash[ac->put_count])); + ac->dht_put = GNUNET_DHT_put(ac->dht, + &ac->hash[ac->put_count], + replication, + GNUNET_DHT_RO_RECORD_ROUTE, + GNUNET_BLOCK_TYPE_TEST, + block_size, + block, + GNUNET_TIME_UNIT_FOREVER_ABS, /* expiration time */ + &put_cont, + ac); /* continuation and its closure */ n_puts++; } @@ -648,65 +644,66 @@ delayed_put (void *cls) * operation has executed successfully. */ static void -dht_connected (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg) +dht_connected(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg) { struct ActiveContext *ac = cls; struct Context *ctx = ac->ctx; - GNUNET_assert (NULL != ctx); //FIXME: Fails - GNUNET_assert (NULL != ctx->op); - GNUNET_assert (ctx->op == op); - ac->dht = (struct GNUNET_DHT_Handle *) ca_result; + GNUNET_assert(NULL != ctx); //FIXME: Fails + GNUNET_assert(NULL != ctx->op); + GNUNET_assert(ctx->op == op); + ac->dht = (struct GNUNET_DHT_Handle *)ca_result; if (NULL != emsg) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Connection to DHT service failed: %s\n", - emsg); - GNUNET_TESTBED_operation_done (ctx->op); /* Calls dht_disconnect() */ - ctx->op = NULL; - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Connection to DHT service failed: %s\n", + emsg); + GNUNET_TESTBED_operation_done(ctx->op); /* Calls dht_disconnect() */ + ctx->op = NULL; + return; + } switch (mode) - { - case MODE_PUT: + { + case MODE_PUT: { struct GNUNET_TIME_Relative peer_delay_put; peer_delay_put.rel_value_us = - GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, - delay_put.rel_value_us); + GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, + delay_put.rel_value_us); ac->put_count = num_puts_per_peer; - ac->hash = calloc (ac->put_count, - sizeof (struct GNUNET_HashCode)); + ac->hash = calloc(ac->put_count, + sizeof(struct GNUNET_HashCode)); if (NULL == ac->hash) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "calloc"); - GNUNET_SCHEDULER_shutdown (); - return; - } - ac->delay_task = GNUNET_SCHEDULER_add_delayed (peer_delay_put, - &delayed_put, - ac); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "calloc"); + GNUNET_SCHEDULER_shutdown(); + return; + } + ac->delay_task = GNUNET_SCHEDULER_add_delayed(peer_delay_put, + &delayed_put, + ac); break; } - case MODE_GET: + + case MODE_GET: { struct GNUNET_TIME_Relative peer_delay_get; peer_delay_get.rel_value_us = delay_get.rel_value_us + - GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, - delay_get.rel_value_us); - ac->delay_task = GNUNET_SCHEDULER_add_delayed (peer_delay_get, - &delayed_get, - ac); + GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, + delay_get.rel_value_us); + ac->delay_task = GNUNET_SCHEDULER_add_delayed(peer_delay_get, + &delayed_get, + ac); break; } - } + } } @@ -720,12 +717,12 @@ dht_connected (void *cls, * @return service handle to return in 'op_result', NULL on error */ static void * -dht_connect (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +dht_connect(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { n_dht++; - return GNUNET_DHT_connect (cfg, - 10); + return GNUNET_DHT_connect(cfg, + 10); } @@ -737,14 +734,14 @@ dht_connect (void *cls, * @param op_result service handle returned from the connect adapter */ static void -dht_disconnect (void *cls, - void *op_result) +dht_disconnect(void *cls, + void *op_result) { struct ActiveContext *ac = cls; - GNUNET_assert (NULL != ac->dht); - GNUNET_assert (ac->dht == op_result); - GNUNET_DHT_disconnect (ac->dht); + GNUNET_assert(NULL != ac->dht); + GNUNET_assert(ac->dht == op_result); + GNUNET_DHT_disconnect(ac->dht); ac->dht = NULL; n_dht--; if (0 != n_dht) @@ -752,19 +749,20 @@ dht_disconnect (void *cls, if (GNUNET_YES == in_shutdown) return; switch (mode) - { - case MODE_PUT: - if (n_puts_ok != ((unsigned long long) n_active) * num_puts_per_peer) - return; - /* Start GETs if all PUTs have been made */ - mode = MODE_GET; - start_profiling (); - return; - case MODE_GET: - if ((n_gets_ok + n_gets_fail) != n_active) + { + case MODE_PUT: + if (n_puts_ok != ((unsigned long long)n_active) * num_puts_per_peer) + return; + /* Start GETs if all PUTs have been made */ + mode = MODE_GET; + start_profiling(); return; - break; - } + + case MODE_GET: + if ((n_gets_ok + n_gets_fail) != n_active) + return; + break; + } } @@ -776,21 +774,21 @@ start_profiling() { struct Context *ctx; - DEBUG ("GNUNET_TESTBED_service_connect\n"); - GNUNET_break (GNUNET_YES != in_shutdown); + DEBUG("GNUNET_TESTBED_service_connect\n"); + GNUNET_break(GNUNET_YES != in_shutdown); for (unsigned int i = 0; i < n_active; i++) - { - struct ActiveContext *ac = &a_ac[i]; - GNUNET_assert (NULL != (ctx = ac->ctx)); - GNUNET_assert (NULL == ctx->op); - ctx->op = GNUNET_TESTBED_service_connect (ctx, - ctx->peer, - "dht", - &dht_connected, ac, - &dht_connect, - &dht_disconnect, - ac); - } + { + struct ActiveContext *ac = &a_ac[i]; + GNUNET_assert(NULL != (ctx = ac->ctx)); + GNUNET_assert(NULL == ctx->op); + ctx->op = GNUNET_TESTBED_service_connect(ctx, + ctx->peer, + "dht", + &dht_connected, ac, + &dht_connect, + &dht_disconnect, + ac); + } } @@ -803,22 +801,22 @@ start_profiling() * operation has executed successfully. */ static void -service_started (void *cls, - struct GNUNET_TESTBED_Operation *op, - const char *emsg) +service_started(void *cls, + struct GNUNET_TESTBED_Operation *op, + const char *emsg) { struct Context *ctx = cls; - GNUNET_assert (NULL != ctx); - GNUNET_assert (NULL != ctx->op); - GNUNET_TESTBED_operation_done (ctx->op); + GNUNET_assert(NULL != ctx); + GNUNET_assert(NULL != ctx->op); + GNUNET_TESTBED_operation_done(ctx->op); ctx->op = NULL; peers_started++; - DEBUG ("Peers Started = %d; num_peers = %d \n", - peers_started, - num_peers); + DEBUG("Peers Started = %d; num_peers = %d \n", + peers_started, + num_peers); if (peers_started == num_peers) - start_profiling (); + start_profiling(); } @@ -834,63 +832,63 @@ service_started (void *cls, * @param links_failed the number of overlay link */ static void -test_run (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - unsigned int links_succeeded, - unsigned int links_failed) +test_run(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + unsigned int links_succeeded, + unsigned int links_failed) { unsigned int ac_cnt; testbed_handles = peers; if (NULL == peers) - { - /* exit */ - GNUNET_assert (0); - } - MESSAGE ("%u peers started, %u/%u links up\n", - num_peers, - links_succeeded, - links_succeeded + links_failed); - a_ctx = GNUNET_new_array (num_peers, - struct Context); + { + /* exit */ + GNUNET_assert(0); + } + MESSAGE("%u peers started, %u/%u links up\n", + num_peers, + links_succeeded, + links_succeeded + links_failed); + a_ctx = GNUNET_new_array(num_peers, + struct Context); /* select the peers which actively participate in profiling */ n_active = num_peers * put_probability / 100; if (0 == n_active) - { - GNUNET_SCHEDULER_shutdown (); - GNUNET_free (a_ctx); - a_ctx = NULL; - return; - } + { + GNUNET_SCHEDULER_shutdown(); + GNUNET_free(a_ctx); + a_ctx = NULL; + return; + } - a_ac = GNUNET_new_array (n_active, - struct ActiveContext); + a_ac = GNUNET_new_array(n_active, + struct ActiveContext); ac_cnt = 0; for (unsigned int cnt = 0; cnt < num_peers && ac_cnt < n_active; cnt++) - { - if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - 100) >= put_probability) - continue; - - a_ctx[cnt].ac = &a_ac[ac_cnt]; - a_ac[ac_cnt].ctx = &a_ctx[cnt]; - ac_cnt++; - } + { + if (GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + 100) >= put_probability) + continue; + + a_ctx[cnt].ac = &a_ac[ac_cnt]; + a_ac[ac_cnt].ctx = &a_ctx[cnt]; + ac_cnt++; + } n_active = ac_cnt; /* start DHT service on all peers */ for (unsigned int cnt = 0; cnt < num_peers; cnt++) - { - a_ctx[cnt].peer = peers[cnt]; - a_ctx[cnt].op = GNUNET_TESTBED_peer_manage_service (&a_ctx[cnt], - peers[cnt], - "dht", - &service_started, - &a_ctx[cnt], - 1); - } + { + a_ctx[cnt].peer = peers[cnt]; + a_ctx[cnt].op = GNUNET_TESTBED_peer_manage_service(&a_ctx[cnt], + peers[cnt], + "dht", + &service_started, + &a_ctx[cnt], + 1); + } } @@ -903,32 +901,32 @@ test_run (void *cls, * @param config configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *config) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *config) { uint64_t event_mask; if (0 == num_peers) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Exiting as the number of peers is %u\n"), - num_peers); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Exiting as the number of peers is %u\n"), + num_peers); + return; + } cfg = config; event_mask = 0; - GNUNET_TESTBED_run (hosts_file, - cfg, - num_peers, - event_mask, - NULL, - NULL, - &test_run, - NULL); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); + GNUNET_TESTBED_run(hosts_file, + cfg, + num_peers, + event_mask, + NULL, + NULL, + &test_run, + NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); } @@ -938,78 +936,78 @@ run (void *cls, * @return 0 on success */ int -main (int argc, - char *const *argv) +main(int argc, + char *const *argv) { int rc; struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_option_uint ('n', - "peers", - "COUNT", - gettext_noop ("number of peers to start"), - &num_peers), - GNUNET_GETOPT_option_uint ('p', - "peer-put-count", - "COUNT", - gettext_noop ("number of PUTs to perform per peer"), - &num_puts_per_peer), - GNUNET_GETOPT_option_string ('H', - "hosts", - "FILENAME", - gettext_noop ("name of the file with the login information for the testbed"), - &hosts_file), - GNUNET_GETOPT_option_relative_time ('D', - "delay", - "DELAY", - gettext_noop ("delay between rounds for collecting statistics (default: 30 sec)"), - &delay_stats), - GNUNET_GETOPT_option_relative_time ('P', - "PUT-delay", - "DELAY", - gettext_noop ("delay to start doing PUTs (default: 1 sec)"), - &delay_put), - GNUNET_GETOPT_option_relative_time ('G', - "GET-delay", - "DELAY", - gettext_noop ("delay to start doing GETs (default: 5 min)"), - &delay_get), - GNUNET_GETOPT_option_uint ('r', - "replication", - "DEGREE", - gettext_noop ("replication degree for DHT PUTs"), - &replication), - GNUNET_GETOPT_option_uint ('R', - "random-chance", - "PROBABILITY", - gettext_noop ("chance that a peer is selected at random for PUTs"), - &put_probability), - GNUNET_GETOPT_option_relative_time ('t', - "timeout", - "TIMEOUT", - gettext_noop ("timeout for DHT PUT and GET requests (default: 1 min)"), - &timeout), + GNUNET_GETOPT_option_uint('n', + "peers", + "COUNT", + gettext_noop("number of peers to start"), + &num_peers), + GNUNET_GETOPT_option_uint('p', + "peer-put-count", + "COUNT", + gettext_noop("number of PUTs to perform per peer"), + &num_puts_per_peer), + GNUNET_GETOPT_option_string('H', + "hosts", + "FILENAME", + gettext_noop("name of the file with the login information for the testbed"), + &hosts_file), + GNUNET_GETOPT_option_relative_time('D', + "delay", + "DELAY", + gettext_noop("delay between rounds for collecting statistics (default: 30 sec)"), + &delay_stats), + GNUNET_GETOPT_option_relative_time('P', + "PUT-delay", + "DELAY", + gettext_noop("delay to start doing PUTs (default: 1 sec)"), + &delay_put), + GNUNET_GETOPT_option_relative_time('G', + "GET-delay", + "DELAY", + gettext_noop("delay to start doing GETs (default: 5 min)"), + &delay_get), + GNUNET_GETOPT_option_uint('r', + "replication", + "DEGREE", + gettext_noop("replication degree for DHT PUTs"), + &replication), + GNUNET_GETOPT_option_uint('R', + "random-chance", + "PROBABILITY", + gettext_noop("chance that a peer is selected at random for PUTs"), + &put_probability), + GNUNET_GETOPT_option_relative_time('t', + "timeout", + "TIMEOUT", + gettext_noop("timeout for DHT PUT and GET requests (default: 1 min)"), + &timeout), GNUNET_GETOPT_OPTION_END }; if (GNUNET_OK != - GNUNET_STRINGS_get_utf8_args (argc, argv, - &argc, &argv)) + GNUNET_STRINGS_get_utf8_args(argc, argv, + &argc, &argv)) return 2; /* set default delays */ - delay_stats = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10); - delay_put = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10); - delay_get = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10); - timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10); + delay_stats = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10); + delay_put = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10); + delay_get = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10); + timeout = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10); replication = 1; /* default replication */ rc = 0; if (GNUNET_OK != - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-dht-profiler", - gettext_noop ("Measure quality and performance of the DHT service."), - options, - &run, - NULL)) + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-dht-profiler", + gettext_noop("Measure quality and performance of the DHT service."), + options, + &run, + NULL)) rc = 1; return rc; } diff --git a/src/dht/plugin_block_dht.c b/src/dht/plugin_block_dht.c index 44f4b9226..918a18eb6 100644 --- a/src/dht/plugin_block_dht.c +++ b/src/dht/plugin_block_dht.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/plugin_block_dht.c @@ -53,38 +53,38 @@ * by this @a type of block (this is not an error) */ static struct GNUNET_BLOCK_Group * -block_plugin_dht_create_group (void *cls, - enum GNUNET_BLOCK_Type type, - uint32_t nonce, - const void *raw_data, - size_t raw_data_size, - va_list va) +block_plugin_dht_create_group(void *cls, + enum GNUNET_BLOCK_Type type, + uint32_t nonce, + const void *raw_data, + size_t raw_data_size, + va_list va) { unsigned int bf_size; const char *guard; - guard = va_arg (va, const char *); - if (0 == strcmp (guard, - "seen-set-size")) - bf_size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size (va_arg (va, - unsigned int), - BLOOMFILTER_K); - else if (0 == strcmp (guard, - "filter-size")) - bf_size = va_arg (va, unsigned int); + guard = va_arg(va, const char *); + if (0 == strcmp(guard, + "seen-set-size")) + bf_size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size(va_arg(va, + unsigned int), + BLOOMFILTER_K); + else if (0 == strcmp(guard, + "filter-size")) + bf_size = va_arg(va, unsigned int); else - { - GNUNET_break (0); - bf_size = 8; - } - GNUNET_break (NULL == va_arg (va, const char *)); - return GNUNET_BLOCK_GROUP_bf_create (cls, - bf_size, - BLOOMFILTER_K, - type, - nonce, - raw_data, - raw_data_size); + { + GNUNET_break(0); + bf_size = 8; + } + GNUNET_break(NULL == va_arg(va, const char *)); + return GNUNET_BLOCK_GROUP_bf_create(cls, + bf_size, + BLOOMFILTER_K, + type, + nonce, + raw_data, + raw_data_size); } @@ -105,16 +105,16 @@ block_plugin_dht_create_group (void *cls, * @return characterization of result */ static enum GNUNET_BLOCK_EvaluationResult -block_plugin_dht_evaluate (void *cls, - struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *group, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode *query, - const void *xquery, - size_t xquery_size, - const void *reply_block, - size_t reply_block_size) +block_plugin_dht_evaluate(void *cls, + struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *group, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode *query, + const void *xquery, + size_t xquery_size, + const void *reply_block, + size_t reply_block_size) { const struct GNUNET_HELLO_Message *hello; struct GNUNET_PeerIdentity pid; @@ -124,35 +124,35 @@ block_plugin_dht_evaluate (void *cls, if (type != GNUNET_BLOCK_TYPE_DHT_HELLO) return GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED; if (0 != xquery_size) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; - } + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; + } if (NULL == reply_block) return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; - if (reply_block_size < sizeof (struct GNUNET_MessageHeader)) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; - } + if (reply_block_size < sizeof(struct GNUNET_MessageHeader)) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } msg = reply_block; - if (reply_block_size != ntohs (msg->size)) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; - } + if (reply_block_size != ntohs(msg->size)) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } hello = reply_block; - if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid)) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; - } - GNUNET_CRYPTO_hash (&pid, - sizeof (pid), - &phash); + if (GNUNET_OK != GNUNET_HELLO_get_id(hello, &pid)) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } + GNUNET_CRYPTO_hash(&pid, + sizeof(pid), + &phash); if (GNUNET_YES == - GNUNET_BLOCK_GROUP_bf_test_and_set (group, - &phash)) + GNUNET_BLOCK_GROUP_bf_test_and_set(group, + &phash)) return GNUNET_BLOCK_EVALUATION_OK_DUPLICATE; return GNUNET_BLOCK_EVALUATION_OK_MORE; } @@ -170,11 +170,11 @@ block_plugin_dht_evaluate (void *cls, * (or if extracting a key from a block of this type does not work) */ static int -block_plugin_dht_get_key (void *cls, - enum GNUNET_BLOCK_Type type, - const void *block, - size_t block_size, - struct GNUNET_HashCode *key) +block_plugin_dht_get_key(void *cls, + enum GNUNET_BLOCK_Type type, + const void *block, + size_t block_size, + struct GNUNET_HashCode *key) { const struct GNUNET_MessageHeader *msg; const struct GNUNET_HELLO_Message *hello; @@ -182,34 +182,34 @@ block_plugin_dht_get_key (void *cls, if (type != GNUNET_BLOCK_TYPE_DHT_HELLO) return GNUNET_SYSERR; - if (block_size < sizeof (struct GNUNET_MessageHeader)) - { - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "block-dht", - _("Block not of type %u\n"), - GNUNET_BLOCK_TYPE_DHT_HELLO); - return GNUNET_NO; - } + if (block_size < sizeof(struct GNUNET_MessageHeader)) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "block-dht", + _("Block not of type %u\n"), + GNUNET_BLOCK_TYPE_DHT_HELLO); + return GNUNET_NO; + } msg = block; - if (block_size != ntohs (msg->size)) - { - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "block-dht", - _("Size mismatch for block\n"), - GNUNET_BLOCK_TYPE_DHT_HELLO); - return GNUNET_NO; - } + if (block_size != ntohs(msg->size)) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "block-dht", + _("Size mismatch for block\n"), + GNUNET_BLOCK_TYPE_DHT_HELLO); + return GNUNET_NO; + } hello = block; - memset (key, 0, sizeof (*key)); - pid = (struct GNUNET_PeerIdentity *) key; - if (GNUNET_OK != GNUNET_HELLO_get_id (hello, pid)) - { - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "block-dht", - _("Block of type %u is malformed\n"), - GNUNET_BLOCK_TYPE_DHT_HELLO); - return GNUNET_NO; - } + memset(key, 0, sizeof(*key)); + pid = (struct GNUNET_PeerIdentity *)key; + if (GNUNET_OK != GNUNET_HELLO_get_id(hello, pid)) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "block-dht", + _("Block of type %u is malformed\n"), + GNUNET_BLOCK_TYPE_DHT_HELLO); + return GNUNET_NO; + } return GNUNET_OK; } @@ -218,7 +218,7 @@ block_plugin_dht_get_key (void *cls, * Entry point for the plugin. */ void * -libgnunet_plugin_block_dht_init (void *cls) +libgnunet_plugin_block_dht_init(void *cls) { static enum GNUNET_BLOCK_Type types[] = { @@ -227,7 +227,7 @@ libgnunet_plugin_block_dht_init (void *cls) }; struct GNUNET_BLOCK_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_BLOCK_PluginFunctions); + api = GNUNET_new(struct GNUNET_BLOCK_PluginFunctions); api->evaluate = &block_plugin_dht_evaluate; api->get_key = &block_plugin_dht_get_key; api->create_group = &block_plugin_dht_create_group; @@ -240,11 +240,11 @@ libgnunet_plugin_block_dht_init (void *cls) * Exit point from the plugin. */ void * -libgnunet_plugin_block_dht_done (void *cls) +libgnunet_plugin_block_dht_done(void *cls) { struct GNUNET_BLOCK_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/dht/test_dht_api.c b/src/dht/test_dht_api.c index 7ec6758b7..f4a337ea8 100644 --- a/src/dht/test_dht_api.c +++ b/src/dht/test_dht_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/test_dht_api.c * @brief base test case for dht api @@ -34,7 +34,7 @@ /** * How long until we really give up on a particular testcase portion? */ -#define TOTAL_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define TOTAL_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) static struct GNUNET_DHT_Handle *dht_handle; @@ -48,55 +48,55 @@ static struct GNUNET_SCHEDULER_Task *die_task; static void -do_shutdown (void *cls) +do_shutdown(void *cls) { if (NULL != die_task) - { - GNUNET_SCHEDULER_cancel (die_task); - die_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(die_task); + die_task = NULL; + } if (NULL != put_handle) - { - GNUNET_DHT_put_cancel (put_handle); - put_handle = NULL; - } + { + GNUNET_DHT_put_cancel(put_handle); + put_handle = NULL; + } if (NULL != get_handle) - { - GNUNET_DHT_get_stop (get_handle); - get_handle = NULL; - } - GNUNET_DHT_disconnect (dht_handle); + { + GNUNET_DHT_get_stop(get_handle); + get_handle = NULL; + } + GNUNET_DHT_disconnect(dht_handle); dht_handle = NULL; } static void -end_badly (void *cls) +end_badly(void *cls) { die_task = NULL; - fprintf (stderr, - "%s", - "Ending on an unhappy note.\n"); - GNUNET_SCHEDULER_shutdown (); + fprintf(stderr, + "%s", + "Ending on an unhappy note.\n"); + GNUNET_SCHEDULER_shutdown(); ok = 1; } static void -test_get_iterator (void *cls, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - enum GNUNET_BLOCK_Type type, - size_t size, - const void *data) +test_get_iterator(void *cls, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + enum GNUNET_BLOCK_Type type, + size_t size, + const void *data) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "test_get_iterator called (we got a result), stopping get request!\n"); - GNUNET_SCHEDULER_shutdown (); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "test_get_iterator called (we got a result), stopping get request!\n"); + GNUNET_SCHEDULER_shutdown(); ok = 0; } @@ -107,83 +107,83 @@ test_get_iterator (void *cls, * @param cls closure */ static void -test_get (void *cls) +test_get(void *cls) { struct GNUNET_HashCode hash; put_handle = NULL; - memset (&hash, - 42, - sizeof (struct GNUNET_HashCode)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Called test_get!\n"); - GNUNET_assert (dht_handle != NULL); - get_handle = GNUNET_DHT_get_start (dht_handle, - GNUNET_BLOCK_TYPE_TEST, - &hash, - 1, - GNUNET_DHT_RO_NONE, - NULL, - 0, - &test_get_iterator, - NULL); + memset(&hash, + 42, + sizeof(struct GNUNET_HashCode)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Called test_get!\n"); + GNUNET_assert(dht_handle != NULL); + get_handle = GNUNET_DHT_get_start(dht_handle, + GNUNET_BLOCK_TYPE_TEST, + &hash, + 1, + GNUNET_DHT_RO_NONE, + NULL, + 0, + &test_get_iterator, + NULL); if (NULL == get_handle) - { - GNUNET_break (0); - ok = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_break(0); + ok = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct GNUNET_HashCode hash; char *data; size_t data_size = 42; - GNUNET_assert (ok == 1); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - die_task = GNUNET_SCHEDULER_add_delayed (TOTAL_TIMEOUT, - &end_badly, - NULL); - memset (&hash, - 42, - sizeof (struct GNUNET_HashCode)); - data = GNUNET_malloc (data_size); - memset (data, 43, data_size); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Called test_put!\n"); - dht_handle = GNUNET_DHT_connect (cfg, - 100); - GNUNET_assert (NULL != dht_handle); - put_handle = GNUNET_DHT_put (dht_handle, - &hash, - 1, - GNUNET_DHT_RO_NONE, - GNUNET_BLOCK_TYPE_TEST, - data_size, - data, - GNUNET_TIME_relative_to_absolute (TOTAL_TIMEOUT), - &test_get, - NULL); - GNUNET_free (data); + GNUNET_assert(ok == 1); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); + die_task = GNUNET_SCHEDULER_add_delayed(TOTAL_TIMEOUT, + &end_badly, + NULL); + memset(&hash, + 42, + sizeof(struct GNUNET_HashCode)); + data = GNUNET_malloc(data_size); + memset(data, 43, data_size); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Called test_put!\n"); + dht_handle = GNUNET_DHT_connect(cfg, + 100); + GNUNET_assert(NULL != dht_handle); + put_handle = GNUNET_DHT_put(dht_handle, + &hash, + 1, + GNUNET_DHT_RO_NONE, + GNUNET_BLOCK_TYPE_TEST, + data_size, + data, + GNUNET_TIME_relative_to_absolute(TOTAL_TIMEOUT), + &test_get, + NULL); + GNUNET_free(data); } int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-dht-api", - "test_dht_api_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-dht-api", + "test_dht_api_data.conf", + &run, NULL)) return 1; return ok; } diff --git a/src/dht/test_dht_monitor.c b/src/dht/test_dht_monitor.c index 9d0462c87..f5586e9bc 100644 --- a/src/dht/test_dht_monitor.c +++ b/src/dht/test_dht_monitor.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/test_dht_monitor.c * @brief Test for the dht monitoring API; checks that we receive "some" monitor events @@ -31,19 +31,18 @@ /** * How long do we run the test at most? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 300) /** * How often do we run the PUTs? */ -#define PUT_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) +#define PUT_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) /** * Information we keep for each GET operation. */ -struct GetOperation -{ +struct GetOperation { /** * DLL. */ @@ -58,7 +57,6 @@ struct GetOperation * Handle for the operation. */ struct GNUNET_DHT_GetHandle *get; - }; @@ -110,34 +108,34 @@ static unsigned int monitor_counter; * @param cls the `struct GNUNET_DHT_TEST_Context` */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { struct GNUNET_DHT_TEST_Context *ctx = cls; unsigned int i; struct GetOperation *get_op; ok = (monitor_counter > NUM_PEERS) ? 0 : 2; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Received %u monitor events\n", - monitor_counter); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Received %u monitor events\n", + monitor_counter); while (NULL != (get_op = get_tail)) - { - GNUNET_DHT_get_stop (get_op->get); - GNUNET_CONTAINER_DLL_remove (get_head, - get_tail, - get_op); - GNUNET_free (get_op); - } - for (i=0;iget); + GNUNET_CONTAINER_DLL_remove(get_head, + get_tail, + get_op); + GNUNET_free(get_op); + } + for (i = 0; i < NUM_PEERS; i++) + GNUNET_DHT_monitor_stop(monitors[i]); + GNUNET_free(monitors); + GNUNET_SCHEDULER_cancel(put_task); + GNUNET_DHT_TEST_cleanup(ctx); if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } } @@ -149,10 +147,10 @@ shutdown_task (void *cls) * @param cls NULL */ static void -timeout_task_cb (void *cls) +timeout_task_cb(void *cls) { timeout_task = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -172,41 +170,41 @@ timeout_task_cb (void *cls) * @param data pointer to the result data */ static void -dht_get_handler (void *cls, struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode * key, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - enum GNUNET_BLOCK_Type type, - size_t size, const void *data) +dht_get_handler(void *cls, struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode * key, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + enum GNUNET_BLOCK_Type type, + size_t size, const void *data) { struct GetOperation *get_op = cls; struct GNUNET_HashCode want; - if (sizeof (struct GNUNET_HashCode) != size) - { - GNUNET_break (0); - return; - } - GNUNET_CRYPTO_hash (key, sizeof (*key), &want); - if (0 != memcmp (&want, data, sizeof (want))) - { - GNUNET_break (0); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Get successful\n"); - GNUNET_DHT_get_stop (get_op->get); - GNUNET_CONTAINER_DLL_remove (get_head, - get_tail, - get_op); - GNUNET_free (get_op); + if (sizeof(struct GNUNET_HashCode) != size) + { + GNUNET_break(0); + return; + } + GNUNET_CRYPTO_hash(key, sizeof(*key), &want); + if (0 != memcmp(&want, data, sizeof(want))) + { + GNUNET_break(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Get successful\n"); + GNUNET_DHT_get_stop(get_op->get); + GNUNET_CONTAINER_DLL_remove(get_head, + get_tail, + get_op); + GNUNET_free(get_op); if (NULL != get_head) return; /* all DHT GET operations successful; terminate! */ ok = 0; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -216,28 +214,28 @@ dht_get_handler (void *cls, struct GNUNET_TIME_Absolute exp, * @param cls array with NUM_PEERS DHT handles */ static void -do_puts (void *cls) +do_puts(void *cls) { struct GNUNET_DHT_Handle **hs = cls; struct GNUNET_HashCode key; struct GNUNET_HashCode value; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Putting values into DHT\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Putting values into DHT\n"); for (unsigned int i = 0; i < NUM_PEERS; i++) - { - GNUNET_CRYPTO_hash (&i, sizeof (i), &key); - GNUNET_CRYPTO_hash (&key, sizeof (key), &value); - GNUNET_DHT_put (hs[i], &key, 10U, - GNUNET_DHT_RO_RECORD_ROUTE | - GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, - GNUNET_BLOCK_TYPE_TEST, - sizeof (value), &value, - GNUNET_TIME_UNIT_FOREVER_ABS, - NULL, NULL); - } - put_task = GNUNET_SCHEDULER_add_delayed (PUT_FREQUENCY, - &do_puts, hs); + { + GNUNET_CRYPTO_hash(&i, sizeof(i), &key); + GNUNET_CRYPTO_hash(&key, sizeof(key), &value); + GNUNET_DHT_put(hs[i], &key, 10U, + GNUNET_DHT_RO_RECORD_ROUTE | + GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, + GNUNET_BLOCK_TYPE_TEST, + sizeof(value), &value, + GNUNET_TIME_UNIT_FOREVER_ABS, + NULL, NULL); + } + put_task = GNUNET_SCHEDULER_add_delayed(PUT_FREQUENCY, + &do_puts, hs); } @@ -255,22 +253,22 @@ do_puts (void *cls) * @param key Key of the requested data. */ static void -monitor_get_cb (void *cls, - enum GNUNET_DHT_RouteOption options, - enum GNUNET_BLOCK_Type type, - uint32_t hop_count, - uint32_t desired_replication_level, - unsigned int path_length, - const struct GNUNET_PeerIdentity *path, - const struct GNUNET_HashCode * key) +monitor_get_cb(void *cls, + enum GNUNET_DHT_RouteOption options, + enum GNUNET_BLOCK_Type type, + uint32_t hop_count, + uint32_t desired_replication_level, + unsigned int path_length, + const struct GNUNET_PeerIdentity *path, + const struct GNUNET_HashCode * key) { unsigned int i; - i = (unsigned int) (long) cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "%u got a GET message for key %s\n", - i, - GNUNET_h2s (key)); + i = (unsigned int)(long)cls; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "%u got a GET message for key %s\n", + i, + GNUNET_h2s(key)); monitor_counter++; } @@ -292,26 +290,26 @@ monitor_get_cb (void *cls, * @param size Number of bytes in data. */ static void -monitor_put_cb (void *cls, - enum GNUNET_DHT_RouteOption options, - enum GNUNET_BLOCK_Type type, - uint32_t hop_count, - uint32_t desired_replication_level, - unsigned int path_length, - const struct GNUNET_PeerIdentity *path, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode * key, - const void *data, - size_t size) +monitor_put_cb(void *cls, + enum GNUNET_DHT_RouteOption options, + enum GNUNET_BLOCK_Type type, + uint32_t hop_count, + uint32_t desired_replication_level, + unsigned int path_length, + const struct GNUNET_PeerIdentity *path, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode * key, + const void *data, + size_t size) { unsigned int i; - i = (unsigned int) (long) cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "%u got a PUT message for key %s with %u bytes\n", - i, - GNUNET_h2s (key), - (unsigned int) size); + i = (unsigned int)(long)cls; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "%u got a PUT message for key %s with %u bytes\n", + i, + GNUNET_h2s(key), + (unsigned int)size); monitor_counter++; } @@ -332,25 +330,25 @@ monitor_put_cb (void *cls, * @param size Number of bytes in data. */ static void -monitor_res_cb (void *cls, - enum GNUNET_BLOCK_Type type, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode * key, - const void *data, - size_t size) +monitor_res_cb(void *cls, + enum GNUNET_BLOCK_Type type, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode * key, + const void *data, + size_t size) { unsigned int i; - i = (unsigned int) (long) cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "%u got a REPLY message for key %s with %u bytes\n", - i, - GNUNET_h2s (key), - (unsigned int) size); + i = (unsigned int)(long)cls; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "%u got a REPLY message for key %s with %u bytes\n", + i, + GNUNET_h2s(key), + (unsigned int)size); monitor_counter++; } @@ -365,56 +363,56 @@ monitor_res_cb (void *cls, * @param dhts handle to each of the DHTs of the peers */ static void -run (void *cls, - struct GNUNET_DHT_TEST_Context *ctx, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - struct GNUNET_DHT_Handle **dhts) +run(void *cls, + struct GNUNET_DHT_TEST_Context *ctx, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + struct GNUNET_DHT_Handle **dhts) { unsigned int i; unsigned int j; struct GNUNET_HashCode key; struct GetOperation *get_op; - GNUNET_assert (NUM_PEERS == num_peers); + GNUNET_assert(NUM_PEERS == num_peers); my_peers = peers; - monitors = GNUNET_new_array (num_peers, - struct GNUNET_DHT_MonitorHandle *); + monitors = GNUNET_new_array(num_peers, + struct GNUNET_DHT_MonitorHandle *); + for (i = 0; i < num_peers; i++) + monitors[i] = GNUNET_DHT_monitor_start(dhts[i], + GNUNET_BLOCK_TYPE_ANY, + NULL, + &monitor_get_cb, + &monitor_res_cb, + &monitor_put_cb, + (void *)(long)i); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Peers setup, starting test\n"); + put_task = GNUNET_SCHEDULER_add_now(&do_puts, dhts); for (i = 0; i < num_peers; i++) - monitors[i] = GNUNET_DHT_monitor_start (dhts[i], - GNUNET_BLOCK_TYPE_ANY, - NULL, - &monitor_get_cb, - &monitor_res_cb, - &monitor_put_cb, - (void *)(long)i); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Peers setup, starting test\n"); - put_task = GNUNET_SCHEDULER_add_now (&do_puts, dhts); - for (i=0;iget = GNUNET_DHT_get_start (dhts[j], - GNUNET_BLOCK_TYPE_TEST, /* type */ - &key, /*key to search */ - 4U, /* replication level */ - GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, - NULL, /* xquery */ - 0, /* xquery bits */ - &dht_get_handler, get_op); + GNUNET_CRYPTO_hash(&i, sizeof(i), &key); + for (j = 0; j < num_peers; j++) + { + get_op = GNUNET_new(struct GetOperation); + GNUNET_CONTAINER_DLL_insert(get_head, + get_tail, + get_op); + get_op->get = GNUNET_DHT_get_start(dhts[j], + GNUNET_BLOCK_TYPE_TEST, /* type */ + &key, /*key to search */ + 4U, /* replication level */ + GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, + NULL, /* xquery */ + 0, /* xquery bits */ + &dht_get_handler, get_op); + } } - } - timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &timeout_task_cb, - NULL); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - ctx); + timeout_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &timeout_task_cb, + NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + ctx); } @@ -422,12 +420,12 @@ run (void *cls, * Main: start test */ int -main (int xargc, char *xargv[]) +main(int xargc, char *xargv[]) { - GNUNET_DHT_TEST_run ("test-dht-monitor", - "test_dht_monitor.conf", - NUM_PEERS, - &run, NULL); + GNUNET_DHT_TEST_run("test-dht-monitor", + "test_dht_monitor.conf", + NUM_PEERS, + &run, NULL); return ok; } diff --git a/src/dht/test_dht_topo.c b/src/dht/test_dht_topo.c index a0d80e52c..32d99152d 100644 --- a/src/dht/test_dht_topo.c +++ b/src/dht/test_dht_topo.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dht/test_dht_topo.c * @author Christian Grothoff @@ -32,19 +32,18 @@ /** * How long until we give up on fetching the data? */ -#define GET_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 120) +#define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 120) /** * How frequently do we execute the PUTs? */ -#define PUT_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define PUT_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) /** * Information we keep for each GET operation. */ -struct GetOperation -{ +struct GetOperation { /** * DLL. */ @@ -59,7 +58,6 @@ struct GetOperation * Handle for the operation. */ struct GNUNET_DHT_GetHandle *get; - }; @@ -107,80 +105,79 @@ static unsigned int NUM_PEERS; /** * Statistics we print out. */ -static struct -{ +static struct { const char *subsystem; const char *name; unsigned long long total; } stats[] = { - {"core", "# bytes decrypted", 0}, - {"core", "# bytes encrypted", 0}, - {"core", "# type maps received", 0}, - {"core", "# session keys confirmed via PONG", 0}, - {"core", "# peers connected", 0}, - {"core", "# key exchanges initiated", 0}, - {"core", "# send requests dropped (disconnected)", 0}, - {"core", "# transmissions delayed due to corking", 0}, - {"core", "# messages discarded (expired prior to transmission)", 0}, - {"core", "# messages discarded (disconnected)", 0}, - {"core", "# discarded CORE_SEND requests", 0}, - {"core", "# discarded lower priority CORE_SEND requests", 0}, - {"transport", "# bytes received via TCP", 0}, - {"transport", "# bytes transmitted via TCP", 0}, - {"dht", "# PUT messages queued for transmission", 0}, - {"dht", "# P2P PUT requests received", 0}, - {"dht", "# GET messages queued for transmission", 0}, - {"dht", "# P2P GET requests received", 0}, - {"dht", "# RESULT messages queued for transmission", 0}, - {"dht", "# P2P RESULTS received", 0}, - {"dht", "# Queued messages discarded (peer disconnected)", 0}, - {"dht", "# Peers excluded from routing due to Bloomfilter", 0}, - {"dht", "# Peer selection failed", 0}, - {"dht", "# FIND PEER requests ignored due to Bloomfilter", 0}, - {"dht", "# FIND PEER requests ignored due to lack of HELLO", 0}, - {"dht", "# P2P FIND PEER requests processed", 0}, - {"dht", "# P2P GET requests ONLY routed", 0}, - {"dht", "# Preference updates given to core", 0}, - {"dht", "# REPLIES ignored for CLIENTS (no match)", 0}, - {"dht", "# GET requests from clients injected", 0}, - {"dht", "# GET requests received from clients", 0}, - {"dht", "# GET STOP requests received from clients", 0}, - {"dht", "# ITEMS stored in datacache", 0}, - {"dht", "# Good RESULTS found in datacache", 0}, - {"dht", "# GET requests given to datacache", 0}, - {NULL, NULL, 0} + { "core", "# bytes decrypted", 0 }, + { "core", "# bytes encrypted", 0 }, + { "core", "# type maps received", 0 }, + { "core", "# session keys confirmed via PONG", 0 }, + { "core", "# peers connected", 0 }, + { "core", "# key exchanges initiated", 0 }, + { "core", "# send requests dropped (disconnected)", 0 }, + { "core", "# transmissions delayed due to corking", 0 }, + { "core", "# messages discarded (expired prior to transmission)", 0 }, + { "core", "# messages discarded (disconnected)", 0 }, + { "core", "# discarded CORE_SEND requests", 0 }, + { "core", "# discarded lower priority CORE_SEND requests", 0 }, + { "transport", "# bytes received via TCP", 0 }, + { "transport", "# bytes transmitted via TCP", 0 }, + { "dht", "# PUT messages queued for transmission", 0 }, + { "dht", "# P2P PUT requests received", 0 }, + { "dht", "# GET messages queued for transmission", 0 }, + { "dht", "# P2P GET requests received", 0 }, + { "dht", "# RESULT messages queued for transmission", 0 }, + { "dht", "# P2P RESULTS received", 0 }, + { "dht", "# Queued messages discarded (peer disconnected)", 0 }, + { "dht", "# Peers excluded from routing due to Bloomfilter", 0 }, + { "dht", "# Peer selection failed", 0 }, + { "dht", "# FIND PEER requests ignored due to Bloomfilter", 0 }, + { "dht", "# FIND PEER requests ignored due to lack of HELLO", 0 }, + { "dht", "# P2P FIND PEER requests processed", 0 }, + { "dht", "# P2P GET requests ONLY routed", 0 }, + { "dht", "# Preference updates given to core", 0 }, + { "dht", "# REPLIES ignored for CLIENTS (no match)", 0 }, + { "dht", "# GET requests from clients injected", 0 }, + { "dht", "# GET requests received from clients", 0 }, + { "dht", "# GET STOP requests received from clients", 0 }, + { "dht", "# ITEMS stored in datacache", 0 }, + { "dht", "# Good RESULTS found in datacache", 0 }, + { "dht", "# GET requests given to datacache", 0 }, + { NULL, NULL, 0 } }; static struct GNUNET_DHT_TEST_Context * -stop_ops () +stop_ops() { struct GetOperation *get_op; struct GNUNET_DHT_TEST_Context *ctx = NULL; if (NULL != timeout_task) - { - ctx = GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + ctx = GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } if (NULL != put_task) - { - GNUNET_SCHEDULER_cancel (put_task); - put_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(put_task); + put_task = NULL; + } if (NULL != get_task) - { - GNUNET_SCHEDULER_cancel (get_task); - get_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(get_task); + get_task = NULL; + } while (NULL != (get_op = get_tail)) - { - GNUNET_DHT_get_stop (get_op->get); - GNUNET_CONTAINER_DLL_remove (get_head, - get_tail, - get_op); - GNUNET_free (get_op); - } + { + GNUNET_DHT_get_stop(get_op->get); + GNUNET_CONTAINER_DLL_remove(get_head, + get_tail, + get_op); + GNUNET_free(get_op); + } return ctx; } @@ -193,32 +190,32 @@ stop_ops () * @param emsg error message on failure */ static void -stats_finished (void *cls, - struct GNUNET_TESTBED_Operation *op, - const char *emsg) +stats_finished(void *cls, + struct GNUNET_TESTBED_Operation *op, + const char *emsg) { struct GNUNET_DHT_TEST_Context *ctx = cls; unsigned int i; if (NULL != op) - GNUNET_TESTBED_operation_done (op); + GNUNET_TESTBED_operation_done(op); if (NULL != emsg) - { - fprintf (stderr, - _("Gathering statistics failed: %s\n"), - emsg); - GNUNET_SCHEDULER_cancel (put_task); - GNUNET_DHT_TEST_cleanup (ctx); - return; - } + { + fprintf(stderr, + _("Gathering statistics failed: %s\n"), + emsg); + GNUNET_SCHEDULER_cancel(put_task); + GNUNET_DHT_TEST_cleanup(ctx); + return; + } for (i = 0; NULL != stats[i].name; i++) - fprintf (stderr, - "%6s/%60s = %12llu\n", - stats[i].subsystem, - stats[i].name, - stats[i].total); - GNUNET_DHT_TEST_cleanup (ctx); - GNUNET_SCHEDULER_shutdown (); + fprintf(stderr, + "%6s/%60s = %12llu\n", + stats[i].subsystem, + stats[i].name, + stats[i].total); + GNUNET_DHT_TEST_cleanup(ctx); + GNUNET_SCHEDULER_shutdown(); } @@ -234,20 +231,20 @@ stats_finished (void *cls, * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration */ static int -handle_stats (void *cls, - const struct GNUNET_TESTBED_Peer *peer, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +handle_stats(void *cls, + const struct GNUNET_TESTBED_Peer *peer, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { unsigned int i; for (i = 0; NULL != stats[i].name; i++) - if ( (0 == strcasecmp (subsystem, - stats[i].subsystem)) && - (0 == strcasecmp (name, - stats[i].name)) ) + if ((0 == strcasecmp(subsystem, + stats[i].subsystem)) && + (0 == strcasecmp(name, + stats[i].name))) stats[i].total += value; return GNUNET_OK; } @@ -260,9 +257,9 @@ handle_stats (void *cls, * @param cls the 'struct GNUNET_DHT_TestContext' */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - (void) stop_ops (); + (void)stop_ops(); } @@ -273,12 +270,12 @@ shutdown_task (void *cls) * @param cls the `struct GNUNET_DHT_TestContext` */ static void -timeout_cb (void *cls) +timeout_cb(void *cls) { timeout_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Timeout\n"); - GNUNET_SCHEDULER_shutdown (); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Timeout\n"); + GNUNET_SCHEDULER_shutdown(); } @@ -298,75 +295,75 @@ timeout_cb (void *cls) * @param data pointer to the result data */ static void -dht_get_handler (void *cls, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - enum GNUNET_BLOCK_Type type, - size_t size, - const void *data) +dht_get_handler(void *cls, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + enum GNUNET_BLOCK_Type type, + size_t size, + const void *data) { struct GetOperation *get_op = cls; struct GNUNET_HashCode want; struct GNUNET_DHT_TEST_Context *ctx; - if (sizeof (struct GNUNET_HashCode) != size) - { - GNUNET_break (0); - return; - } - GNUNET_CRYPTO_hash (key, - sizeof (*key), - &want); - if (0 != memcmp (&want, - data, - sizeof (want))) - { - GNUNET_break (0); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Get successful\n"); + if (sizeof(struct GNUNET_HashCode) != size) + { + GNUNET_break(0); + return; + } + GNUNET_CRYPTO_hash(key, + sizeof(*key), + &want); + if (0 != memcmp(&want, + data, + sizeof(want))) + { + GNUNET_break(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Get successful\n"); #if 0 { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "PATH: (get %u, put %u)\n", - get_path_length, - put_path_length); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - " LOCAL\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "PATH: (get %u, put %u)\n", + get_path_length, + put_path_length); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + " LOCAL\n"); for (int i = get_path_length - 1; i >= 0; i--) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - " %s\n", - GNUNET_i2s (&get_path[i])); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + " %s\n", + GNUNET_i2s(&get_path[i])); for (int i = put_path_length - 1; i >= 0; i--) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - " %s\n", - GNUNET_i2s (&put_path[i])); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + " %s\n", + GNUNET_i2s(&put_path[i])); } #endif - GNUNET_DHT_get_stop (get_op->get); - GNUNET_CONTAINER_DLL_remove (get_head, - get_tail, - get_op); - GNUNET_free (get_op); + GNUNET_DHT_get_stop(get_op->get); + GNUNET_CONTAINER_DLL_remove(get_head, + get_tail, + get_op); + GNUNET_free(get_op); if (NULL != get_head) return; /* all DHT GET operations successful; get stats! */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "All DHT operations successful. Obtaining stats!\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "All DHT operations successful. Obtaining stats!\n"); ok = 0; - ctx = stop_ops (); - GNUNET_assert (NULL != ctx); - (void) GNUNET_TESTBED_get_statistics (NUM_PEERS, - my_peers, - NULL, NULL, - &handle_stats, - &stats_finished, - ctx); + ctx = stop_ops(); + GNUNET_assert(NULL != ctx); + (void)GNUNET_TESTBED_get_statistics(NUM_PEERS, + my_peers, + NULL, NULL, + &handle_stats, + &stats_finished, + ctx); } @@ -377,38 +374,38 @@ dht_get_handler (void *cls, * @param tc Task context */ static void -do_puts (void *cls) +do_puts(void *cls) { struct GNUNET_DHT_Handle **hs = cls; struct GNUNET_HashCode key; struct GNUNET_HashCode value; put_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Putting values into DHT\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Putting values into DHT\n"); for (unsigned int i = 0; i < NUM_PEERS; i++) - { - GNUNET_CRYPTO_hash (&i, - sizeof (i), - &key); - GNUNET_CRYPTO_hash (&key, - sizeof (key), - &value); - GNUNET_DHT_put (hs[i], - &key, - 10U, - GNUNET_DHT_RO_RECORD_ROUTE | - GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, - GNUNET_BLOCK_TYPE_TEST, - sizeof (value), - &value, - GNUNET_TIME_UNIT_FOREVER_ABS, - NULL, - NULL); - } - put_task = GNUNET_SCHEDULER_add_delayed (PUT_FREQUENCY, - &do_puts, - hs); + { + GNUNET_CRYPTO_hash(&i, + sizeof(i), + &key); + GNUNET_CRYPTO_hash(&key, + sizeof(key), + &value); + GNUNET_DHT_put(hs[i], + &key, + 10U, + GNUNET_DHT_RO_RECORD_ROUTE | + GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, + GNUNET_BLOCK_TYPE_TEST, + sizeof(value), + &value, + GNUNET_TIME_UNIT_FOREVER_ABS, + NULL, + NULL); + } + put_task = GNUNET_SCHEDULER_add_delayed(PUT_FREQUENCY, + &do_puts, + hs); } @@ -416,7 +413,7 @@ do_puts (void *cls) * Start GET operations. */ static void -start_get (void *cls) +start_get(void *cls) { struct GNUNET_DHT_Handle **dhts = cls; unsigned int i; @@ -425,26 +422,26 @@ start_get (void *cls) struct GetOperation *get_op; get_task = NULL; - for (i=0;iget = GNUNET_DHT_get_start (dhts[j], - GNUNET_BLOCK_TYPE_TEST, /* type */ - &key, /*key to search */ - 4U, /* replication level */ - GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, - NULL, /* xquery */ - 0, /* xquery bits */ - &dht_get_handler, - get_op); + GNUNET_CRYPTO_hash(&i, sizeof(i), &key); + for (j = 0; j < NUM_PEERS; j++) + { + get_op = GNUNET_new(struct GetOperation); + GNUNET_CONTAINER_DLL_insert(get_head, + get_tail, + get_op); + get_op->get = GNUNET_DHT_get_start(dhts[j], + GNUNET_BLOCK_TYPE_TEST, /* type */ + &key, /*key to search */ + 4U, /* replication level */ + GNUNET_DHT_RO_RECORD_ROUTE | GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, + NULL, /* xquery */ + 0, /* xquery bits */ + &dht_get_handler, + get_op); + } } - } } @@ -458,26 +455,26 @@ start_get (void *cls) * @param dhts handle to each of the DHTs of the peers */ static void -run (void *cls, - struct GNUNET_DHT_TEST_Context *ctx, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - struct GNUNET_DHT_Handle **dhts) +run(void *cls, + struct GNUNET_DHT_TEST_Context *ctx, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + struct GNUNET_DHT_Handle **dhts) { - GNUNET_assert (NUM_PEERS == num_peers); + GNUNET_assert(NUM_PEERS == num_peers); my_peers = peers; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Peers setup, starting test\n"); - put_task = GNUNET_SCHEDULER_add_now (&do_puts, - dhts); - get_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &start_get, - dhts); - timeout_task = GNUNET_SCHEDULER_add_delayed (GET_TIMEOUT, - &timeout_cb, - ctx); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - ctx); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Peers setup, starting test\n"); + put_task = GNUNET_SCHEDULER_add_now(&do_puts, + dhts); + get_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &start_get, + dhts); + timeout_task = GNUNET_SCHEDULER_add_delayed(GET_TIMEOUT, + &timeout_cb, + ctx); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + ctx); } @@ -485,44 +482,44 @@ run (void *cls, * Main: start test */ int -main (int xargc, char *xargv[]) +main(int xargc, char *xargv[]) { const char *cfg_filename; const char *test_name; - if (NULL != strstr (xargv[0], "test_dht_2dtorus")) - { - cfg_filename = "test_dht_2dtorus.conf"; - test_name = "test-dht-2dtorus"; - NUM_PEERS = 16; - } - else if (NULL != strstr (xargv[0], "test_dht_line")) - { - cfg_filename = "test_dht_line.conf"; - test_name = "test-dht-line"; - NUM_PEERS = 5; - } - else if (NULL != strstr (xargv[0], "test_dht_twopeer")) - { - cfg_filename = "test_dht_line.conf"; - test_name = "test-dht-twopeer"; - NUM_PEERS = 2; - } - else if (NULL != strstr (xargv[0], "test_dht_multipeer")) - { - cfg_filename = "test_dht_multipeer.conf"; - test_name = "test-dht-multipeer"; - NUM_PEERS = 10; - } + if (NULL != strstr(xargv[0], "test_dht_2dtorus")) + { + cfg_filename = "test_dht_2dtorus.conf"; + test_name = "test-dht-2dtorus"; + NUM_PEERS = 16; + } + else if (NULL != strstr(xargv[0], "test_dht_line")) + { + cfg_filename = "test_dht_line.conf"; + test_name = "test-dht-line"; + NUM_PEERS = 5; + } + else if (NULL != strstr(xargv[0], "test_dht_twopeer")) + { + cfg_filename = "test_dht_line.conf"; + test_name = "test-dht-twopeer"; + NUM_PEERS = 2; + } + else if (NULL != strstr(xargv[0], "test_dht_multipeer")) + { + cfg_filename = "test_dht_multipeer.conf"; + test_name = "test-dht-multipeer"; + NUM_PEERS = 10; + } else - { - GNUNET_break (0); - return 1; - } - GNUNET_DHT_TEST_run (test_name, - cfg_filename, - NUM_PEERS, - &run, NULL); + { + GNUNET_break(0); + return 1; + } + GNUNET_DHT_TEST_run(test_name, + cfg_filename, + NUM_PEERS, + &run, NULL); return ok; } diff --git a/src/dns/dns.h b/src/dns/dns.h index af86bbaed..12d8f6025 100644 --- a/src/dns/dns.h +++ b/src/dns/dns.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -32,10 +32,9 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Message from client to DNS service to register itself. */ -struct GNUNET_DNS_Register -{ +struct GNUNET_DNS_Register { /** - * Header of type #GNUNET_MESSAGE_TYPE_DNS_CLIENT_INIT + * Header of type #GNUNET_MESSAGE_TYPE_DNS_CLIENT_INIT */ struct GNUNET_MessageHeader header; @@ -49,10 +48,9 @@ struct GNUNET_DNS_Register /** * Message from DNS service to client: please handle a request. */ -struct GNUNET_DNS_Request -{ +struct GNUNET_DNS_Request { /** - * Header of type #GNUNET_MESSAGE_TYPE_DNS_CLIENT_REQUEST + * Header of type #GNUNET_MESSAGE_TYPE_DNS_CLIENT_REQUEST */ struct GNUNET_MessageHeader header; @@ -67,15 +65,13 @@ struct GNUNET_DNS_Request uint64_t request_id GNUNET_PACKED; /* followed by original DNS request (without UDP header) */ - }; /** * Message from client to DNS service: here is my reply. */ -struct GNUNET_DNS_Response -{ +struct GNUNET_DNS_Response { /** * Header of type #GNUNET_MESSAGE_TYPE_DNS_CLIENT_RESPONSE */ @@ -92,7 +88,6 @@ struct GNUNET_DNS_Response uint64_t request_id GNUNET_PACKED; /* followed by original DNS request (without UDP header) */ - }; diff --git a/src/dns/dns_api.c b/src/dns/dns_api.c index e34f02ef0..4dc8e00dd 100644 --- a/src/dns/dns_api.c +++ b/src/dns/dns_api.c @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -31,9 +31,7 @@ /** * Handle to identify an individual DNS request. */ -struct GNUNET_DNS_RequestHandle -{ - +struct GNUNET_DNS_RequestHandle { /** * Handle to DNS API. */ @@ -48,16 +46,13 @@ struct GNUNET_DNS_RequestHandle * Re-connect counter, to make sure we did not reconnect in the meantime. */ uint32_t generation; - }; /** * DNS handle */ -struct GNUNET_DNS_Handle -{ - +struct GNUNET_DNS_Handle { /** * Connection to DNS service, or NULL. */ @@ -108,7 +103,7 @@ struct GNUNET_DNS_Handle * @param tc scheduler context (unused) */ static void -reconnect (void *cls); +reconnect(void *cls); /** @@ -117,17 +112,17 @@ reconnect (void *cls); * @param dh handle with the connection */ static void -force_reconnect (struct GNUNET_DNS_Handle *dh) +force_reconnect(struct GNUNET_DNS_Handle *dh) { if (NULL != dh->mq) - { - GNUNET_MQ_destroy (dh->mq); - dh->mq = NULL; - } + { + GNUNET_MQ_destroy(dh->mq); + dh->mq = NULL; + } dh->reconnect_task = - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &reconnect, - dh); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &reconnect, + dh); } @@ -140,12 +135,12 @@ force_reconnect (struct GNUNET_DNS_Handle *dh) * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_DNS_Handle *dh = cls; - force_reconnect (dh); + force_reconnect(dh); } @@ -158,14 +153,14 @@ mq_error_handler (void *cls, * @param req message from the service (request) */ static int -check_request (void *cls, - const struct GNUNET_DNS_Request *req) +check_request(void *cls, + const struct GNUNET_DNS_Request *req) { - if (0 != ntohl (req->reserved)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + if (0 != ntohl(req->reserved)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -178,22 +173,22 @@ check_request (void *cls, * @param msg message from the service (request) */ static void -handle_request (void *cls, - const struct GNUNET_DNS_Request *req) +handle_request(void *cls, + const struct GNUNET_DNS_Request *req) { struct GNUNET_DNS_Handle *dh = cls; - size_t payload_length = ntohs (req->header.size) - sizeof (*req); + size_t payload_length = ntohs(req->header.size) - sizeof(*req); struct GNUNET_DNS_RequestHandle *rh; - rh = GNUNET_new (struct GNUNET_DNS_RequestHandle); - rh->dh =dh; + rh = GNUNET_new(struct GNUNET_DNS_RequestHandle); + rh->dh = dh; rh->request_id = req->request_id; rh->generation = dh->generation; dh->pending_requests++; - dh->rh (dh->rh_cls, - rh, - payload_length, - (const char*) &req[1]); + dh->rh(dh->rh_cls, + rh, + payload_length, + (const char*)&req[1]); } @@ -203,33 +198,33 @@ handle_request (void *cls, * @param cls handle with the connection to connect */ static void -reconnect (void *cls) +reconnect(void *cls) { struct GNUNET_DNS_Handle *dh = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (request, - GNUNET_MESSAGE_TYPE_DNS_CLIENT_REQUEST, - struct GNUNET_DNS_Request, - dh), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(request, + GNUNET_MESSAGE_TYPE_DNS_CLIENT_REQUEST, + struct GNUNET_DNS_Request, + dh), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *env; struct GNUNET_DNS_Register *msg; dh->reconnect_task = NULL; - dh->mq = GNUNET_CLIENT_connect (dh->cfg, - "dns", - handlers, - &mq_error_handler, - dh); + dh->mq = GNUNET_CLIENT_connect(dh->cfg, + "dns", + handlers, + &mq_error_handler, + dh); if (NULL == dh->mq) return; dh->generation++; - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_DNS_CLIENT_INIT); - msg->flags = htonl (dh->flags); - GNUNET_MQ_send (dh->mq, - env); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_DNS_CLIENT_INIT); + msg->flags = htonl(dh->flags); + GNUNET_MQ_send(dh->mq, + env); } @@ -244,24 +239,24 @@ reconnect (void *cls) * @param rh request that should now be forwarded */ void -GNUNET_DNS_request_forward (struct GNUNET_DNS_RequestHandle *rh) +GNUNET_DNS_request_forward(struct GNUNET_DNS_RequestHandle *rh) { struct GNUNET_MQ_Envelope *env; struct GNUNET_DNS_Response *resp; - GNUNET_assert (0 < rh->dh->pending_requests--); + GNUNET_assert(0 < rh->dh->pending_requests--); if (rh->generation != rh->dh->generation) - { - GNUNET_free (rh); - return; - } - env = GNUNET_MQ_msg (resp, - GNUNET_MESSAGE_TYPE_DNS_CLIENT_RESPONSE); - resp->drop_flag = htonl (1); + { + GNUNET_free(rh); + return; + } + env = GNUNET_MQ_msg(resp, + GNUNET_MESSAGE_TYPE_DNS_CLIENT_RESPONSE); + resp->drop_flag = htonl(1); resp->request_id = rh->request_id; - GNUNET_MQ_send (rh->dh->mq, - env); - GNUNET_free (rh); + GNUNET_MQ_send(rh->dh->mq, + env); + GNUNET_free(rh); } @@ -272,24 +267,24 @@ GNUNET_DNS_request_forward (struct GNUNET_DNS_RequestHandle *rh) * @param rh request that should now be dropped */ void -GNUNET_DNS_request_drop (struct GNUNET_DNS_RequestHandle *rh) +GNUNET_DNS_request_drop(struct GNUNET_DNS_RequestHandle *rh) { struct GNUNET_MQ_Envelope *env; struct GNUNET_DNS_Response *resp; - GNUNET_assert (0 < rh->dh->pending_requests--); + GNUNET_assert(0 < rh->dh->pending_requests--); if (rh->generation != rh->dh->generation) - { - GNUNET_free (rh); + { + GNUNET_free(rh); return; - } - env = GNUNET_MQ_msg (resp, - GNUNET_MESSAGE_TYPE_DNS_CLIENT_RESPONSE); + } + env = GNUNET_MQ_msg(resp, + GNUNET_MESSAGE_TYPE_DNS_CLIENT_RESPONSE); resp->request_id = rh->request_id; - resp->drop_flag = htonl (0); - GNUNET_MQ_send (rh->dh->mq, - env); - GNUNET_free (rh); + resp->drop_flag = htonl(0); + GNUNET_MQ_send(rh->dh->mq, + env); + GNUNET_free(rh); } @@ -303,37 +298,37 @@ GNUNET_DNS_request_drop (struct GNUNET_DNS_RequestHandle *rh) * @param reply reply data */ void -GNUNET_DNS_request_answer (struct GNUNET_DNS_RequestHandle *rh, - uint16_t reply_length, - const char *reply) +GNUNET_DNS_request_answer(struct GNUNET_DNS_RequestHandle *rh, + uint16_t reply_length, + const char *reply) { struct GNUNET_MQ_Envelope *env; struct GNUNET_DNS_Response *resp; - GNUNET_assert (0 < rh->dh->pending_requests--); + GNUNET_assert(0 < rh->dh->pending_requests--); if (rh->generation != rh->dh->generation) - { - GNUNET_free (rh); + { + GNUNET_free(rh); return; - } - if (reply_length + sizeof (struct GNUNET_DNS_Response) + } + if (reply_length + sizeof(struct GNUNET_DNS_Response) >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - GNUNET_free (rh); - return; - } - env = GNUNET_MQ_msg_extra (resp, - reply_length, - GNUNET_MESSAGE_TYPE_DNS_CLIENT_RESPONSE); - resp->drop_flag = htonl (2); + { + GNUNET_break(0); + GNUNET_free(rh); + return; + } + env = GNUNET_MQ_msg_extra(resp, + reply_length, + GNUNET_MESSAGE_TYPE_DNS_CLIENT_RESPONSE); + resp->drop_flag = htonl(2); resp->request_id = rh->request_id; - GNUNET_memcpy (&resp[1], - reply, - reply_length); - GNUNET_MQ_send (rh->dh->mq, - env); - GNUNET_free (rh); + GNUNET_memcpy(&resp[1], + reply, + reply_length); + GNUNET_MQ_send(rh->dh->mq, + env); + GNUNET_free(rh); } @@ -347,19 +342,19 @@ GNUNET_DNS_request_answer (struct GNUNET_DNS_RequestHandle *rh, * @return DNS handle */ struct GNUNET_DNS_Handle * -GNUNET_DNS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - enum GNUNET_DNS_Flags flags, - GNUNET_DNS_RequestHandler rh, - void *rh_cls) +GNUNET_DNS_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + enum GNUNET_DNS_Flags flags, + GNUNET_DNS_RequestHandler rh, + void *rh_cls) { struct GNUNET_DNS_Handle *dh; - dh = GNUNET_new (struct GNUNET_DNS_Handle); + dh = GNUNET_new(struct GNUNET_DNS_Handle); dh->cfg = cfg; dh->flags = flags; dh->rh = rh; dh->rh_cls = rh_cls; - dh->reconnect_task = GNUNET_SCHEDULER_add_now (&reconnect, dh); + dh->reconnect_task = GNUNET_SCHEDULER_add_now(&reconnect, dh); return dh; } @@ -370,21 +365,21 @@ GNUNET_DNS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param dh DNS handle */ void -GNUNET_DNS_disconnect (struct GNUNET_DNS_Handle *dh) +GNUNET_DNS_disconnect(struct GNUNET_DNS_Handle *dh) { if (NULL != dh->mq) - { - GNUNET_MQ_destroy (dh->mq); - dh->mq = NULL; - } + { + GNUNET_MQ_destroy(dh->mq); + dh->mq = NULL; + } if (NULL != dh->reconnect_task) - { - GNUNET_SCHEDULER_cancel (dh->reconnect_task); - dh->reconnect_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(dh->reconnect_task); + dh->reconnect_task = NULL; + } /* make sure client has no pending requests left over! */ - GNUNET_break (0 == dh->pending_requests); - GNUNET_free (dh); + GNUNET_break(0 == dh->pending_requests); + GNUNET_free(dh); } /* end of dns_api.c */ diff --git a/src/dns/gnunet-dns-monitor.c b/src/dns/gnunet-dns-monitor.c index e822b3211..819cb025d 100644 --- a/src/dns/gnunet-dns-monitor.c +++ b/src/dns/gnunet-dns-monitor.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/dns/gnunet-dns-monitor.c @@ -62,22 +62,31 @@ static unsigned int verbosity; * @return type as string, only valid until the next call to this function */ static const char * -get_type (uint16_t type) +get_type(uint16_t type) { static char buf[6]; + switch (type) - { - case GNUNET_DNSPARSER_TYPE_A: return "A"; - case GNUNET_DNSPARSER_TYPE_NS: return "NS"; - case GNUNET_DNSPARSER_TYPE_CNAME: return "CNAME"; - case GNUNET_DNSPARSER_TYPE_SOA: return "SOA"; - case GNUNET_DNSPARSER_TYPE_PTR: return "PTR"; - case GNUNET_DNSPARSER_TYPE_MX: return "MX"; - case GNUNET_DNSPARSER_TYPE_TXT: return "TXT"; - case GNUNET_DNSPARSER_TYPE_AAAA: return "AAAA"; - case GNUNET_DNSPARSER_TYPE_SRV: return "SRV"; - } - GNUNET_snprintf (buf, sizeof (buf), "%u", (unsigned int) type); + { + case GNUNET_DNSPARSER_TYPE_A: return "A"; + + case GNUNET_DNSPARSER_TYPE_NS: return "NS"; + + case GNUNET_DNSPARSER_TYPE_CNAME: return "CNAME"; + + case GNUNET_DNSPARSER_TYPE_SOA: return "SOA"; + + case GNUNET_DNSPARSER_TYPE_PTR: return "PTR"; + + case GNUNET_DNSPARSER_TYPE_MX: return "MX"; + + case GNUNET_DNSPARSER_TYPE_TXT: return "TXT"; + + case GNUNET_DNSPARSER_TYPE_AAAA: return "AAAA"; + + case GNUNET_DNSPARSER_TYPE_SRV: return "SRV"; + } + GNUNET_snprintf(buf, sizeof(buf), "%u", (unsigned int)type); return buf; } @@ -89,16 +98,19 @@ get_type (uint16_t type) * @return class as string, only valid until the next call to this function */ static const char * -get_class (uint16_t class) +get_class(uint16_t class) { static char buf[6]; + switch (class) - { - case GNUNET_TUN_DNS_CLASS_INTERNET: return "IN"; - case GNUNET_TUN_DNS_CLASS_CHAOS: return "CHAOS"; - case GNUNET_TUN_DNS_CLASS_HESIOD: return "HESIOD"; - } - GNUNET_snprintf (buf, sizeof (buf), "%u", (unsigned int) class); + { + case GNUNET_TUN_DNS_CLASS_INTERNET: return "IN"; + + case GNUNET_TUN_DNS_CLASS_CHAOS: return "CHAOS"; + + case GNUNET_TUN_DNS_CLASS_HESIOD: return "HESIOD"; + } + GNUNET_snprintf(buf, sizeof(buf), "%u", (unsigned int)class); return buf; } @@ -109,13 +121,13 @@ get_class (uint16_t class) * @param query query to display. */ static void -display_query (const struct GNUNET_DNSPARSER_Query *query) +display_query(const struct GNUNET_DNSPARSER_Query *query) { - fprintf (stdout, - "\t\t%s %s: %s\n", - get_class (query->dns_traffic_class), - get_type (query->type), - query->name); + fprintf(stdout, + "\t\t%s %s: %s\n", + get_class(query->dns_traffic_class), + get_type(query->type), + query->name); } @@ -125,7 +137,7 @@ display_query (const struct GNUNET_DNSPARSER_Query *query) * @param record record to display. */ static void -display_record (const struct GNUNET_DNSPARSER_Record *record) +display_record(const struct GNUNET_DNSPARSER_Record *record) { const char *format; char buf[INET6_ADDRSTRLEN]; @@ -133,86 +145,93 @@ display_record (const struct GNUNET_DNSPARSER_Record *record) tmp = NULL; switch (record->type) - { - case GNUNET_DNSPARSER_TYPE_A: - if (record->data.raw.data_len != sizeof (struct in_addr)) - format = ""; - else - format = inet_ntop (AF_INET, record->data.raw.data, buf, sizeof (buf)); - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - if (record->data.raw.data_len != sizeof (struct in6_addr)) - format = ""; - else - format = inet_ntop (AF_INET6, record->data.raw.data, buf, sizeof (buf)); - break; - case GNUNET_DNSPARSER_TYPE_NS: - case GNUNET_DNSPARSER_TYPE_CNAME: - case GNUNET_DNSPARSER_TYPE_PTR: - format = record->data.hostname; - break; - case GNUNET_DNSPARSER_TYPE_SOA: - if (NULL == record->data.soa) - format = ""; - else { - GNUNET_asprintf (&tmp, - "origin: %s, mail: %s, serial = %u, refresh = %u s, retry = %u s, expire = %u s, minimum = %u s", - record->data.soa->mname, - record->data.soa->rname, - (unsigned int) record->data.soa->serial, - (unsigned int) record->data.soa->refresh, - (unsigned int) record->data.soa->retry, - (unsigned int) record->data.soa->expire, - (unsigned int) record->data.soa->minimum_ttl); - format = tmp; - } - break; - case GNUNET_DNSPARSER_TYPE_MX: - if (record->data.mx == NULL) - format = ""; - else - { - GNUNET_asprintf (&tmp, - "%u: %s", - record->data.mx->preference, - record->data.mx->mxhost); - format = tmp; - } - break; - case GNUNET_DNSPARSER_TYPE_SRV: - if (NULL == record->data.srv) - format = ""; - else - { - GNUNET_asprintf (&tmp, - "priority %u, weight = %s, port = %u, target = %s", - (unsigned int) record->data.srv->priority, - (unsigned int) record->data.srv->weight, - (unsigned int) record->data.srv->port, - record->data.srv->target); + case GNUNET_DNSPARSER_TYPE_A: + if (record->data.raw.data_len != sizeof(struct in_addr)) + format = ""; + else + format = inet_ntop(AF_INET, record->data.raw.data, buf, sizeof(buf)); + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + if (record->data.raw.data_len != sizeof(struct in6_addr)) + format = ""; + else + format = inet_ntop(AF_INET6, record->data.raw.data, buf, sizeof(buf)); + break; + + case GNUNET_DNSPARSER_TYPE_NS: + case GNUNET_DNSPARSER_TYPE_CNAME: + case GNUNET_DNSPARSER_TYPE_PTR: + format = record->data.hostname; + break; + + case GNUNET_DNSPARSER_TYPE_SOA: + if (NULL == record->data.soa) + format = ""; + else + { + GNUNET_asprintf(&tmp, + "origin: %s, mail: %s, serial = %u, refresh = %u s, retry = %u s, expire = %u s, minimum = %u s", + record->data.soa->mname, + record->data.soa->rname, + (unsigned int)record->data.soa->serial, + (unsigned int)record->data.soa->refresh, + (unsigned int)record->data.soa->retry, + (unsigned int)record->data.soa->expire, + (unsigned int)record->data.soa->minimum_ttl); + format = tmp; + } + break; + + case GNUNET_DNSPARSER_TYPE_MX: + if (record->data.mx == NULL) + format = ""; + else + { + GNUNET_asprintf(&tmp, + "%u: %s", + record->data.mx->preference, + record->data.mx->mxhost); + format = tmp; + } + break; + + case GNUNET_DNSPARSER_TYPE_SRV: + if (NULL == record->data.srv) + format = ""; + else + { + GNUNET_asprintf(&tmp, + "priority %u, weight = %s, port = %u, target = %s", + (unsigned int)record->data.srv->priority, + (unsigned int)record->data.srv->weight, + (unsigned int)record->data.srv->port, + record->data.srv->target); + format = tmp; + } + break; + + case GNUNET_DNSPARSER_TYPE_TXT: + GNUNET_asprintf(&tmp, + "%.*s", + (unsigned int)record->data.raw.data_len, + record->data.raw.data); format = tmp; + break; + + default: + format = ""; + break; } - break; - case GNUNET_DNSPARSER_TYPE_TXT: - GNUNET_asprintf (&tmp, - "%.*s", - (unsigned int) record->data.raw.data_len, - record->data.raw.data); - format = tmp; - break; - default: - format = ""; - break; - } - fprintf (stdout, - "\t\t%s %s: %s = %s (%u s)\n", - get_class (record->dns_traffic_class), - get_type (record->type), - record->name, - format, - (unsigned int) (GNUNET_TIME_absolute_get_remaining (record->expiration_time).rel_value_us / 1000LL / 1000LL)); - GNUNET_free_non_null (tmp); + fprintf(stdout, + "\t\t%s %s: %s = %s (%u s)\n", + get_class(record->dns_traffic_class), + get_type(record->type), + record->name, + format, + (unsigned int)(GNUNET_TIME_absolute_get_remaining(record->expiration_time).rel_value_us / 1000LL / 1000LL)); + GNUNET_free_non_null(tmp); } @@ -240,62 +259,62 @@ display_record (const struct GNUNET_DNSPARSER_Record *record) * @param request udp payload of the DNS request */ static void -display_request (void *cls, - struct GNUNET_DNS_RequestHandle *rh, - size_t request_length, - const char *request) +display_request(void *cls, + struct GNUNET_DNS_RequestHandle *rh, + size_t request_length, + const char *request) { static const char *return_codes[] = - { - "No error", "Format error", "Server failure", "Name error", - "Not implemented", "Refused", "YXDomain", "YXRRset", - "NXRRset", "NOT AUTH", "NOT ZONE", "", - "", "", "", "" - }; + { + "No error", "Format error", "Server failure", "Name error", + "Not implemented", "Refused", "YXDomain", "YXRRset", + "NXRRset", "NOT AUTH", "NOT ZONE", "", + "", "", "", "" + }; static const char *op_codes[] = - { - "Query", "Inverse query", "Status", "", - "", "", "", "", - "", "", "", "", - "", "", "", "" - }; + { + "Query", "Inverse query", "Status", "", + "", "", "", "", + "", "", "", "", + "", "", "", "" + }; struct GNUNET_DNSPARSER_Packet *p; unsigned int i; - p = GNUNET_DNSPARSER_parse (request, request_length); + p = GNUNET_DNSPARSER_parse(request, request_length); if (NULL == p) - { - fprintf (stderr, "Received malformed DNS packet!\n"); - // FIXME: drop instead? - GNUNET_DNS_request_forward (rh); - return; - } - fprintf (stdout, - "%s with ID: %5u Flags: %s%s%s%s%s%s, Return Code: %s, Opcode: %s\n", - p->flags.query_or_response ? "Response" : "Query", - p->id, - p->flags.recursion_desired ? "RD " : "", - p->flags.message_truncated ? "MT " : "", - p->flags.authoritative_answer ? "AA " : "", - p->flags.checking_disabled ? "CD " : "", - p->flags.authenticated_data ? "AD " : "", - p->flags.recursion_available ? "RA " : "", - return_codes[p->flags.return_code & 15], - op_codes[p->flags.opcode & 15]); + { + fprintf(stderr, "Received malformed DNS packet!\n"); + // FIXME: drop instead? + GNUNET_DNS_request_forward(rh); + return; + } + fprintf(stdout, + "%s with ID: %5u Flags: %s%s%s%s%s%s, Return Code: %s, Opcode: %s\n", + p->flags.query_or_response ? "Response" : "Query", + p->id, + p->flags.recursion_desired ? "RD " : "", + p->flags.message_truncated ? "MT " : "", + p->flags.authoritative_answer ? "AA " : "", + p->flags.checking_disabled ? "CD " : "", + p->flags.authenticated_data ? "AD " : "", + p->flags.recursion_available ? "RA " : "", + return_codes[p->flags.return_code & 15], + op_codes[p->flags.opcode & 15]); if (p->num_queries > 0) - fprintf (stdout, - "\tQueries:\n"); - for (i=0;inum_queries;i++) - display_query (&p->queries[i]); + fprintf(stdout, + "\tQueries:\n"); + for (i = 0; i < p->num_queries; i++) + display_query(&p->queries[i]); if (p->num_answers > 0) - fprintf (stdout, - "\tAnswers:\n"); - for (i=0;inum_answers;i++) - display_record (&p->answers[i]); - fprintf (stdout, "\n"); - GNUNET_DNSPARSER_free_packet (p); - GNUNET_DNS_request_forward (rh); + fprintf(stdout, + "\tAnswers:\n"); + for (i = 0; i < p->num_answers; i++) + display_record(&p->answers[i]); + fprintf(stdout, "\n"); + GNUNET_DNSPARSER_free_packet(p); + GNUNET_DNS_request_forward(rh); } @@ -303,13 +322,13 @@ display_request (void *cls, * Shutdown. */ static void -do_disconnect (void *cls) +do_disconnect(void *cls) { if (NULL != handle) - { - GNUNET_DNS_disconnect (handle); - handle = NULL; - } + { + GNUNET_DNS_disconnect(handle); + handle = NULL; + } } @@ -322,8 +341,8 @@ do_disconnect (void *cls) * @param cfg configuration */ static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { enum GNUNET_DNS_Flags flags; @@ -335,41 +354,40 @@ run (void *cls, char *const *args, const char *cfgfile, if (outbound_only) flags |= GNUNET_DNS_FLAG_RESPONSE_MONITOR; handle = - GNUNET_DNS_connect (cfg, - flags, - &display_request, - NULL); - GNUNET_SCHEDULER_add_shutdown (&do_disconnect, NULL); + GNUNET_DNS_connect(cfg, + flags, + &display_request, + NULL); + GNUNET_SCHEDULER_add_shutdown(&do_disconnect, NULL); } int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { + GNUNET_GETOPT_option_flag('i', + "inbound-only", + gettext_noop("only monitor DNS queries"), + &inbound_only), - GNUNET_GETOPT_option_flag ('i', - "inbound-only", - gettext_noop ("only monitor DNS queries"), - &inbound_only), - - GNUNET_GETOPT_option_flag ('o', - "outbound-only", - gettext_noop ("only monitor DNS queries"), - &outbound_only), + GNUNET_GETOPT_option_flag('o', + "outbound-only", + gettext_noop("only monitor DNS queries"), + &outbound_only), - GNUNET_GETOPT_option_verbose (&verbosity), + GNUNET_GETOPT_option_verbose(&verbosity), GNUNET_GETOPT_OPTION_END }; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, "gnunet-dns-monitor", - gettext_noop - ("Monitor DNS queries."), options, - &run, NULL)) ? ret : 1; - GNUNET_free ((void*) argv); + GNUNET_PROGRAM_run(argc, argv, "gnunet-dns-monitor", + gettext_noop + ("Monitor DNS queries."), options, + &run, NULL)) ? ret : 1; + GNUNET_free((void*)argv); return ret; } diff --git a/src/dns/gnunet-dns-redirector.c b/src/dns/gnunet-dns-redirector.c index 608540e12..f1978ce92 100644 --- a/src/dns/gnunet-dns-redirector.c +++ b/src/dns/gnunet-dns-redirector.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/dns/gnunet-dns-redirector.c @@ -61,48 +61,51 @@ static unsigned int verbosity; * @param record record to modify */ static void -modify_record (const struct GNUNET_DNSPARSER_Record *record) +modify_record(const struct GNUNET_DNSPARSER_Record *record) { char buf[INET6_ADDRSTRLEN]; switch (record->type) - { - case GNUNET_DNSPARSER_TYPE_A: - if (record->data.raw.data_len != sizeof (struct in_addr)) - return; - if (NULL != n4) { - if (verbosity > 1) - fprintf (stderr, - "Changing A record from `%s' to `%s'\n", - inet_ntop (AF_INET, record->data.raw.data, buf, sizeof (buf)), - n4); - GNUNET_assert (1 == inet_pton (AF_INET, n4, record->data.raw.data)); - } - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - if (record->data.raw.data_len != sizeof (struct in6_addr)) - return; - if (NULL != n6) - { - if (verbosity > 1) - fprintf (stderr, - "Changing AAAA record from `%s' to `%s'\n", - inet_ntop (AF_INET6, record->data.raw.data, buf, sizeof (buf)), - n6); - GNUNET_assert (1 == inet_pton (AF_INET6, n6, record->data.raw.data)); + case GNUNET_DNSPARSER_TYPE_A: + if (record->data.raw.data_len != sizeof(struct in_addr)) + return; + if (NULL != n4) + { + if (verbosity > 1) + fprintf(stderr, + "Changing A record from `%s' to `%s'\n", + inet_ntop(AF_INET, record->data.raw.data, buf, sizeof(buf)), + n4); + GNUNET_assert(1 == inet_pton(AF_INET, n4, record->data.raw.data)); + } + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + if (record->data.raw.data_len != sizeof(struct in6_addr)) + return; + if (NULL != n6) + { + if (verbosity > 1) + fprintf(stderr, + "Changing AAAA record from `%s' to `%s'\n", + inet_ntop(AF_INET6, record->data.raw.data, buf, sizeof(buf)), + n6); + GNUNET_assert(1 == inet_pton(AF_INET6, n6, record->data.raw.data)); + } + break; + + case GNUNET_DNSPARSER_TYPE_NS: + case GNUNET_DNSPARSER_TYPE_CNAME: + case GNUNET_DNSPARSER_TYPE_PTR: + case GNUNET_DNSPARSER_TYPE_SOA: + case GNUNET_DNSPARSER_TYPE_MX: + case GNUNET_DNSPARSER_TYPE_TXT: + break; + + default: + break; } - break; - case GNUNET_DNSPARSER_TYPE_NS: - case GNUNET_DNSPARSER_TYPE_CNAME: - case GNUNET_DNSPARSER_TYPE_PTR: - case GNUNET_DNSPARSER_TYPE_SOA: - case GNUNET_DNSPARSER_TYPE_MX: - case GNUNET_DNSPARSER_TYPE_TXT: - break; - default: - break; - } } @@ -130,10 +133,10 @@ modify_record (const struct GNUNET_DNSPARSER_Record *record) * @param request udp payload of the DNS request */ static void -modify_request (void *cls, - struct GNUNET_DNS_RequestHandle *rh, - size_t request_length, - const char *request) +modify_request(void *cls, + struct GNUNET_DNS_RequestHandle *rh, + size_t request_length, + const char *request) { struct GNUNET_DNSPARSER_Packet *p; unsigned int i; @@ -141,35 +144,35 @@ modify_request (void *cls, size_t len; int ret; - p = GNUNET_DNSPARSER_parse (request, request_length); + p = GNUNET_DNSPARSER_parse(request, request_length); if (NULL == p) - { - fprintf (stderr, "Received malformed DNS packet, leaving it untouched\n"); - GNUNET_DNS_request_forward (rh); - return; - } - for (i=0;inum_answers;i++) - modify_record (&p->answers[i]); + { + fprintf(stderr, "Received malformed DNS packet, leaving it untouched\n"); + GNUNET_DNS_request_forward(rh); + return; + } + for (i = 0; i < p->num_answers; i++) + modify_record(&p->answers[i]); buf = NULL; - ret = GNUNET_DNSPARSER_pack (p, 1024, &buf, &len); - GNUNET_DNSPARSER_free_packet (p); + ret = GNUNET_DNSPARSER_pack(p, 1024, &buf, &len); + GNUNET_DNSPARSER_free_packet(p); if (GNUNET_OK != ret) - { - if (GNUNET_NO == ret) - fprintf (stderr, - "Modified DNS response did not fit, keeping old response\n"); - else - GNUNET_break (0); /* our modifications should have been sane! */ - GNUNET_DNS_request_forward (rh); - } + { + if (GNUNET_NO == ret) + fprintf(stderr, + "Modified DNS response did not fit, keeping old response\n"); + else + GNUNET_break(0); /* our modifications should have been sane! */ + GNUNET_DNS_request_forward(rh); + } else - { - if (verbosity > 0) - fprintf (stdout, - "Injecting modified DNS response\n"); - GNUNET_DNS_request_answer (rh, len, buf); - } - GNUNET_free_non_null (buf); + { + if (verbosity > 0) + fprintf(stdout, + "Injecting modified DNS response\n"); + GNUNET_DNS_request_answer(rh, len, buf); + } + GNUNET_free_non_null(buf); } @@ -177,13 +180,13 @@ modify_request (void *cls, * Shutdown. */ static void -do_disconnect (void *cls) +do_disconnect(void *cls) { if (NULL != handle) - { - GNUNET_DNS_disconnect (handle); - handle = NULL; - } + { + GNUNET_DNS_disconnect(handle); + handle = NULL; + } } @@ -196,66 +199,67 @@ do_disconnect (void *cls) * @param cfg configuration */ static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct in_addr i4; struct in6_addr i6; - if ( (n4 != NULL) && - (1 != inet_pton (AF_INET, n4, &i4)) ) - { - fprintf (stderr, - "`%s' is nto a valid IPv4 address!\n", - n4); - return; - } - if ( (n6 != NULL) && - (1 != inet_pton (AF_INET6, n6, &i6)) ) - { - fprintf (stderr, - "`%s' is nto a valid IPv6 address!\n", - n6); - return; - } + + if ((n4 != NULL) && + (1 != inet_pton(AF_INET, n4, &i4))) + { + fprintf(stderr, + "`%s' is nto a valid IPv4 address!\n", + n4); + return; + } + if ((n6 != NULL) && + (1 != inet_pton(AF_INET6, n6, &i6))) + { + fprintf(stderr, + "`%s' is nto a valid IPv6 address!\n", + n6); + return; + } handle = - GNUNET_DNS_connect (cfg, - GNUNET_DNS_FLAG_POST_RESOLUTION, - &modify_request, - NULL); - GNUNET_SCHEDULER_add_shutdown (&do_disconnect, NULL); + GNUNET_DNS_connect(cfg, + GNUNET_DNS_FLAG_POST_RESOLUTION, + &modify_request, + NULL); + GNUNET_SCHEDULER_add_shutdown(&do_disconnect, NULL); } int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_option_string ('4', - "ipv4", - "IPV4", - gettext_noop ("set A records"), - &n4), - - GNUNET_GETOPT_option_string ('6', - "ipv4", - "IPV6", - gettext_noop ("set AAAA records"), - &n6), - - GNUNET_GETOPT_option_verbose (&verbosity), + GNUNET_GETOPT_option_string('4', + "ipv4", + "IPV4", + gettext_noop("set A records"), + &n4), + + GNUNET_GETOPT_option_string('6', + "ipv4", + "IPV6", + gettext_noop("set AAAA records"), + &n6), + + GNUNET_GETOPT_option_verbose(&verbosity), GNUNET_GETOPT_OPTION_END }; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, "gnunet-dns-redirector", - gettext_noop - ("Change DNS replies to point elsewhere."), options, - &run, NULL)) ? ret : 1; - GNUNET_free ((void*) argv); + GNUNET_PROGRAM_run(argc, argv, "gnunet-dns-redirector", + gettext_noop + ("Change DNS replies to point elsewhere."), options, + &run, NULL)) ? ret : 1; + GNUNET_free((void*)argv); return ret; } diff --git a/src/dns/gnunet-helper-dns.c b/src/dns/gnunet-helper-dns.c index 554727094..85c72579d 100644 --- a/src/dns/gnunet-helper-dns.c +++ b/src/dns/gnunet-helper-dns.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dns/gnunet-helper-dns.c @@ -87,8 +87,7 @@ /** * This is in linux/include/net/ipv6.h, but not always exported... */ -struct in6_ifreq -{ +struct in6_ifreq { struct in6_addr ifr6_addr; uint32_t ifr6_prefixlen; unsigned int ifr6_ifindex; @@ -152,11 +151,11 @@ static int cpipe[2]; * @param signal signal number of the signal (not used) */ static void -signal_handler (int signal) +signal_handler(int signal) { /* ignore return value, as the signal handler could theoretically be called many times before the shutdown can actually happen */ - (void) write (cpipe[1], "K", 1); + (void)write(cpipe[1], "K", 1); } @@ -168,22 +167,22 @@ signal_handler (int signal) * @param flags open flags (O_RDONLY, O_WRONLY) */ static void -open_dev_null (int target_fd, - int flags) +open_dev_null(int target_fd, + int flags) { int fd; - fd = open ("/dev/null", flags); + fd = open("/dev/null", flags); if (-1 == fd) - abort (); + abort(); if (fd == target_fd) return; - if (-1 == dup2 (fd, target_fd)) - { - (void) close (fd); - abort (); - } - (void) close (fd); + if (-1 == dup2(fd, target_fd)) + { + (void)close(fd); + abort(); + } + (void)close(fd); } @@ -195,49 +194,50 @@ open_dev_null (int target_fd, * @return 0 on success, 1 on any error */ static int -fork_and_exec (const char *file, - char *const cmd[]) +fork_and_exec(const char *file, + char *const cmd[]) { int status; pid_t pid; pid_t ret; - pid = fork (); + pid = fork(); if (-1 == pid) - { - fprintf (stderr, - "fork failed: %s\n", - strerror (errno)); - return 1; - } + { + fprintf(stderr, + "fork failed: %s\n", + strerror(errno)); + return 1; + } if (0 == pid) - { - /* we are the child process */ - /* close stdin/stdout to not cause interference - with the helper's main protocol! */ - (void) close (0); - open_dev_null (0, O_RDONLY); - (void) close (1); - open_dev_null (1, O_WRONLY); - (void) execv (file, cmd); - /* can only get here on error */ - fprintf (stderr, - "exec `%s' failed: %s\n", - file, - strerror (errno)); - _exit (1); - } + { + /* we are the child process */ + /* close stdin/stdout to not cause interference + with the helper's main protocol! */ + (void)close(0); + open_dev_null(0, O_RDONLY); + (void)close(1); + open_dev_null(1, O_WRONLY); + (void)execv(file, cmd); + /* can only get here on error */ + fprintf(stderr, + "exec `%s' failed: %s\n", + file, + strerror(errno)); + _exit(1); + } /* keep running waitpid as long as the only error we get is 'EINTR' */ - while ( (-1 == (ret = waitpid (pid, &status, 0))) && - (errno == EINTR) ); + while ((-1 == (ret = waitpid(pid, &status, 0))) && + (errno == EINTR)) + ; if (-1 == ret) - { - fprintf (stderr, - "waitpid failed: %s\n", - strerror (errno)); - return 1; - } - if (! (WIFEXITED (status) && (0 == WEXITSTATUS (status)))) + { + fprintf(stderr, + "waitpid failed: %s\n", + strerror(errno)); + return 1; + } + if (!(WIFEXITED(status) && (0 == WEXITSTATUS(status)))) return 1; /* child process completed and returned success, we're happy */ return 0; @@ -252,45 +252,45 @@ fork_and_exec (const char *file, * @return the fd to the tun or -1 on error */ static int -init_tun (char *dev) +init_tun(char *dev) { struct ifreq ifr; int fd; if (NULL == dev) - { - errno = EINVAL; - return -1; - } + { + errno = EINVAL; + return -1; + } - if (-1 == (fd = open ("/dev/net/tun", O_RDWR))) - { - fprintf (stderr, "Error opening `%s': %s\n", "/dev/net/tun", - strerror (errno)); - return -1; - } + if (-1 == (fd = open("/dev/net/tun", O_RDWR))) + { + fprintf(stderr, "Error opening `%s': %s\n", "/dev/net/tun", + strerror(errno)); + return -1; + } if (fd >= FD_SETSIZE) - { - fprintf (stderr, "File descriptor to large: %d", fd); - (void) close (fd); - return -1; - } + { + fprintf(stderr, "File descriptor to large: %d", fd); + (void)close(fd); + return -1; + } - memset (&ifr, 0, sizeof (ifr)); + memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TUN; if ('\0' != *dev) - strncpy (ifr.ifr_name, dev, IFNAMSIZ); + strncpy(ifr.ifr_name, dev, IFNAMSIZ); - if (-1 == ioctl (fd, TUNSETIFF, (void *) &ifr)) - { - fprintf (stderr, "Error with ioctl on `%s': %s\n", "/dev/net/tun", - strerror (errno)); - (void) close (fd); - return -1; - } - strcpy (dev, ifr.ifr_name); + if (-1 == ioctl(fd, TUNSETIFF, (void *)&ifr)) + { + fprintf(stderr, "Error with ioctl on `%s': %s\n", "/dev/net/tun", + strerror(errno)); + (void)close(fd); + return -1; + } + strcpy(dev, ifr.ifr_name); return fd; } @@ -303,7 +303,7 @@ init_tun (char *dev) * @param prefix_len the length of the network-prefix */ static void -set_address6 (const char *dev, const char *address, unsigned long prefix_len) +set_address6(const char *dev, const char *address, unsigned long prefix_len) { struct ifreq ifr; struct in6_ifreq ifr6; @@ -313,39 +313,39 @@ set_address6 (const char *dev, const char *address, unsigned long prefix_len) /* * parse the new address */ - memset (&sa6, 0, sizeof (struct sockaddr_in6)); + memset(&sa6, 0, sizeof(struct sockaddr_in6)); sa6.sin6_family = AF_INET6; - if (1 != inet_pton (AF_INET6, address, sa6.sin6_addr.s6_addr)) - { - fprintf (stderr, - "Failed to parse IPv6 address `%s': %s\n", - address, - strerror (errno)); - exit (1); - } + if (1 != inet_pton(AF_INET6, address, sa6.sin6_addr.s6_addr)) + { + fprintf(stderr, + "Failed to parse IPv6 address `%s': %s\n", + address, + strerror(errno)); + exit(1); + } - if (-1 == (fd = socket (PF_INET6, SOCK_DGRAM, 0))) - { - fprintf (stderr, - "Error creating IPv6 socket: %s (ignored)\n", - strerror (errno)); - /* ignore error, maybe only IPv4 works on this system! */ - return; - } + if (-1 == (fd = socket(PF_INET6, SOCK_DGRAM, 0))) + { + fprintf(stderr, + "Error creating IPv6 socket: %s (ignored)\n", + strerror(errno)); + /* ignore error, maybe only IPv4 works on this system! */ + return; + } - memset (&ifr, 0, sizeof (struct ifreq)); + memset(&ifr, 0, sizeof(struct ifreq)); /* * Get the index of the if */ - strncpy (ifr.ifr_name, dev, IFNAMSIZ); - if (-1 == ioctl (fd, SIOGIFINDEX, &ifr)) - { - fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno)); - (void) close (fd); - exit (1); - } + strncpy(ifr.ifr_name, dev, IFNAMSIZ); + if (-1 == ioctl(fd, SIOGIFINDEX, &ifr)) + { + fprintf(stderr, "ioctl failed at %d: %s\n", __LINE__, strerror(errno)); + (void)close(fd); + exit(1); + } - memset (&ifr6, 0, sizeof (struct in6_ifreq)); + memset(&ifr6, 0, sizeof(struct in6_ifreq)); ifr6.ifr6_addr = sa6.sin6_addr; ifr6.ifr6_ifindex = ifr.ifr_ifindex; ifr6.ifr6_prefixlen = prefix_len; @@ -353,42 +353,42 @@ set_address6 (const char *dev, const char *address, unsigned long prefix_len) /* * Set the address */ - if (-1 == ioctl (fd, SIOCSIFADDR, &ifr6)) - { - fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__, - strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCSIFADDR, &ifr6)) + { + fprintf(stderr, "ioctl failed at line %d: %s\n", __LINE__, + strerror(errno)); + (void)close(fd); + exit(1); + } /* * Get the flags */ - if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr)) - { - fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__, - strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCGIFFLAGS, &ifr)) + { + fprintf(stderr, "ioctl failed at line %d: %s\n", __LINE__, + strerror(errno)); + (void)close(fd); + exit(1); + } /* * Add the UP and RUNNING flags */ ifr.ifr_flags |= IFF_UP | IFF_RUNNING; - if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr)) - { - fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__, - strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCSIFFLAGS, &ifr)) + { + fprintf(stderr, "ioctl failed at line %d: %s\n", __LINE__, + strerror(errno)); + (void)close(fd); + exit(1); + } - if (0 != close (fd)) - { - fprintf (stderr, "close failed: %s\n", strerror (errno)); - exit (1); - } + if (0 != close(fd)) + { + fprintf(stderr, "close failed: %s\n", strerror(errno)); + exit(1); + } } @@ -400,100 +400,100 @@ set_address6 (const char *dev, const char *address, unsigned long prefix_len) * @param mask the netmask */ static void -set_address4 (const char *dev, const char *address, const char *mask) +set_address4(const char *dev, const char *address, const char *mask) { int fd; struct sockaddr_in *addr; struct ifreq ifr; - memset (&ifr, 0, sizeof (struct ifreq)); - addr = (struct sockaddr_in *) &(ifr.ifr_addr); + memset(&ifr, 0, sizeof(struct ifreq)); + addr = (struct sockaddr_in *)&(ifr.ifr_addr); addr->sin_family = AF_INET; /* * Parse the address */ - if (1 != inet_pton (AF_INET, address, &addr->sin_addr.s_addr)) - { - fprintf (stderr, - "Failed to parse IPv4 address `%s': %s\n", - address, - strerror (errno)); - exit (1); - } + if (1 != inet_pton(AF_INET, address, &addr->sin_addr.s_addr)) + { + fprintf(stderr, + "Failed to parse IPv4 address `%s': %s\n", + address, + strerror(errno)); + exit(1); + } - if (-1 == (fd = socket (PF_INET, SOCK_DGRAM, 0))) - { - fprintf (stderr, - "Error creating IPv4 socket: %s\n", - strerror (errno)); - exit (1); - } + if (-1 == (fd = socket(PF_INET, SOCK_DGRAM, 0))) + { + fprintf(stderr, + "Error creating IPv4 socket: %s\n", + strerror(errno)); + exit(1); + } - strncpy (ifr.ifr_name, dev, IFNAMSIZ); + strncpy(ifr.ifr_name, dev, IFNAMSIZ); /* * Set the address */ - if (-1 == ioctl (fd, SIOCSIFADDR, &ifr)) - { - fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCSIFADDR, &ifr)) + { + fprintf(stderr, "ioctl failed at %d: %s\n", __LINE__, strerror(errno)); + (void)close(fd); + exit(1); + } /* * Parse the netmask */ - addr = (struct sockaddr_in *) &(ifr.ifr_netmask); - if (1 != inet_pton (AF_INET, mask, &addr->sin_addr.s_addr)) - { - fprintf (stderr, "Failed to parse address `%s': %s\n", mask, - strerror (errno)); - (void) close (fd); - exit (1); - } + addr = (struct sockaddr_in *)&(ifr.ifr_netmask); + if (1 != inet_pton(AF_INET, mask, &addr->sin_addr.s_addr)) + { + fprintf(stderr, "Failed to parse address `%s': %s\n", mask, + strerror(errno)); + (void)close(fd); + exit(1); + } /* * Set the netmask */ - if (-1 == ioctl (fd, SIOCSIFNETMASK, &ifr)) - { - fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__, - strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCSIFNETMASK, &ifr)) + { + fprintf(stderr, "ioctl failed at line %d: %s\n", __LINE__, + strerror(errno)); + (void)close(fd); + exit(1); + } /* * Get the flags */ - if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr)) - { - fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__, - strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCGIFFLAGS, &ifr)) + { + fprintf(stderr, "ioctl failed at line %d: %s\n", __LINE__, + strerror(errno)); + (void)close(fd); + exit(1); + } /* * Add the UP and RUNNING flags */ ifr.ifr_flags |= IFF_UP | IFF_RUNNING; - if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr)) - { - fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__, - strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCSIFFLAGS, &ifr)) + { + fprintf(stderr, "ioctl failed at line %d: %s\n", __LINE__, + strerror(errno)); + (void)close(fd); + exit(1); + } - if (0 != close (fd)) - { - fprintf (stderr, "close failed: %s\n", strerror (errno)); - (void) close (fd); - exit (1); - } + if (0 != close(fd)) + { + fprintf(stderr, "close failed: %s\n", strerror(errno)); + (void)close(fd); + exit(1); + } } @@ -505,7 +505,7 @@ set_address4 (const char *dev, const char *address, const char *mask) * @param fd_tun tunnel FD */ static void -run (int fd_tun) +run(int fd_tun) { /* * The buffer filled by reading from fd_tun @@ -526,176 +526,176 @@ run (int fd_tun) int max; while (1) - { - FD_ZERO (&fds_w); - FD_ZERO (&fds_r); - - /* - * We are supposed to read and the buffer is empty - * -> select on read from tun - */ - if (0 == buftun_size) - FD_SET (fd_tun, &fds_r); - - /* - * We are supposed to read and the buffer is not empty - * -> select on write to stdout - */ - if (0 < buftun_size) - FD_SET (1, &fds_w); - - /* - * We are supposed to write and the buffer is empty - * -> select on read from stdin - */ - if (NULL == bufin_read) - FD_SET (0, &fds_r); - - /* - * We are supposed to write and the buffer is not empty - * -> select on write to tun - */ - if (NULL != bufin_read) - FD_SET (fd_tun, &fds_w); - - FD_SET (cpipe[0], &fds_r); - max = (fd_tun > cpipe[0]) ? fd_tun : cpipe[0]; - - int r = select (max + 1, &fds_r, &fds_w, NULL, NULL); - - if (-1 == r) - { - if (EINTR == errno) - continue; - fprintf (stderr, "select failed: %s\n", strerror (errno)); - return; - } - - if (r > 0) { - if (FD_ISSET (cpipe[0], &fds_r)) - return; /* aborted by signal */ - - if (FD_ISSET (fd_tun, &fds_r)) - { - buftun_size = - read (fd_tun, buftun + sizeof (struct GNUNET_MessageHeader), - MAX_SIZE - sizeof (struct GNUNET_MessageHeader)); - if (-1 == buftun_size) + FD_ZERO(&fds_w); + FD_ZERO(&fds_r); + + /* + * We are supposed to read and the buffer is empty + * -> select on read from tun + */ + if (0 == buftun_size) + FD_SET(fd_tun, &fds_r); + + /* + * We are supposed to read and the buffer is not empty + * -> select on write to stdout + */ + if (0 < buftun_size) + FD_SET(1, &fds_w); + + /* + * We are supposed to write and the buffer is empty + * -> select on read from stdin + */ + if (NULL == bufin_read) + FD_SET(0, &fds_r); + + /* + * We are supposed to write and the buffer is not empty + * -> select on write to tun + */ + if (NULL != bufin_read) + FD_SET(fd_tun, &fds_w); + + FD_SET(cpipe[0], &fds_r); + max = (fd_tun > cpipe[0]) ? fd_tun : cpipe[0]; + + int r = select(max + 1, &fds_r, &fds_w, NULL, NULL); + + if (-1 == r) { - if ( (errno == EINTR) || - (errno == EAGAIN) ) - { - buftun_size = 0; - continue; - } - fprintf (stderr, "read-error: %s\n", strerror (errno)); - return; - } - if (0 == buftun_size) - { - fprintf (stderr, "EOF on tun\n"); - return; - } - buftun_read = buftun; - { - struct GNUNET_MessageHeader *hdr = - (struct GNUNET_MessageHeader *) buftun; - buftun_size += sizeof (struct GNUNET_MessageHeader); - hdr->type = htons (GNUNET_MESSAGE_TYPE_DNS_HELPER); - hdr->size = htons (buftun_size); - } - } - else if (FD_ISSET (1, &fds_w)) - { - ssize_t written = write (1, buftun_read, buftun_size); - - if (-1 == written) - { - if ( (errno == EINTR) || - (errno == EAGAIN) ) - continue; - fprintf (stderr, "write-error to stdout: %s\n", strerror (errno)); - return; - } - if (0 == written) - { - fprintf (stderr, "write returned 0\n"); + if (EINTR == errno) + continue; + fprintf(stderr, "select failed: %s\n", strerror(errno)); return; } - buftun_size -= written; - buftun_read += written; - } - if (FD_ISSET (0, &fds_r)) - { - bufin_size = read (0, bufin + bufin_rpos, MAX_SIZE - bufin_rpos); - if (-1 == bufin_size) + if (r > 0) { - bufin_read = NULL; - if ( (errno == EINTR) || - (errno == EAGAIN) ) - continue; - fprintf (stderr, "read-error: %s\n", strerror (errno)); - return; - } - if (0 == bufin_size) - { - bufin_read = NULL; - fprintf (stderr, "EOF on stdin\n"); - return; - } - { - struct GNUNET_MessageHeader *hdr; + if (FD_ISSET(cpipe[0], &fds_r)) + return; /* aborted by signal */ + + if (FD_ISSET(fd_tun, &fds_r)) + { + buftun_size = + read(fd_tun, buftun + sizeof(struct GNUNET_MessageHeader), + MAX_SIZE - sizeof(struct GNUNET_MessageHeader)); + if (-1 == buftun_size) + { + if ((errno == EINTR) || + (errno == EAGAIN)) + { + buftun_size = 0; + continue; + } + fprintf(stderr, "read-error: %s\n", strerror(errno)); + return; + } + if (0 == buftun_size) + { + fprintf(stderr, "EOF on tun\n"); + return; + } + buftun_read = buftun; + { + struct GNUNET_MessageHeader *hdr = + (struct GNUNET_MessageHeader *)buftun; + buftun_size += sizeof(struct GNUNET_MessageHeader); + hdr->type = htons(GNUNET_MESSAGE_TYPE_DNS_HELPER); + hdr->size = htons(buftun_size); + } + } + else if (FD_ISSET(1, &fds_w)) + { + ssize_t written = write(1, buftun_read, buftun_size); + + if (-1 == written) + { + if ((errno == EINTR) || + (errno == EAGAIN)) + continue; + fprintf(stderr, "write-error to stdout: %s\n", strerror(errno)); + return; + } + if (0 == written) + { + fprintf(stderr, "write returned 0\n"); + return; + } + buftun_size -= written; + buftun_read += written; + } + + if (FD_ISSET(0, &fds_r)) + { + bufin_size = read(0, bufin + bufin_rpos, MAX_SIZE - bufin_rpos); + if (-1 == bufin_size) + { + bufin_read = NULL; + if ((errno == EINTR) || + (errno == EAGAIN)) + continue; + fprintf(stderr, "read-error: %s\n", strerror(errno)); + return; + } + if (0 == bufin_size) + { + bufin_read = NULL; + fprintf(stderr, "EOF on stdin\n"); + return; + } + { + struct GNUNET_MessageHeader *hdr; PROCESS_BUFFER: - bufin_rpos += bufin_size; - if (bufin_rpos < sizeof (struct GNUNET_MessageHeader)) - continue; - hdr = (struct GNUNET_MessageHeader *) bufin; - if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_DNS_HELPER) - { - fprintf (stderr, "protocol violation!\n"); - return; - } - if (ntohs (hdr->size) > bufin_rpos) - continue; - bufin_read = bufin + sizeof (struct GNUNET_MessageHeader); - bufin_size = ntohs (hdr->size) - sizeof (struct GNUNET_MessageHeader); - bufin_rpos -= bufin_size + sizeof (struct GNUNET_MessageHeader); - } - } - else if (FD_ISSET (fd_tun, &fds_w)) - { - ssize_t written = write (fd_tun, bufin_read, bufin_size); - - if (-1 == written) - { - if ( (errno == EINTR) || - (errno == EAGAIN) ) - continue; - fprintf (stderr, "write-error to tun: %s\n", strerror (errno)); - return; - } - if (0 == written) - { - fprintf (stderr, "write returned 0\n"); - return; + bufin_rpos += bufin_size; + if (bufin_rpos < sizeof(struct GNUNET_MessageHeader)) + continue; + hdr = (struct GNUNET_MessageHeader *)bufin; + if (ntohs(hdr->type) != GNUNET_MESSAGE_TYPE_DNS_HELPER) + { + fprintf(stderr, "protocol violation!\n"); + return; + } + if (ntohs(hdr->size) > bufin_rpos) + continue; + bufin_read = bufin + sizeof(struct GNUNET_MessageHeader); + bufin_size = ntohs(hdr->size) - sizeof(struct GNUNET_MessageHeader); + bufin_rpos -= bufin_size + sizeof(struct GNUNET_MessageHeader); + } + } + else if (FD_ISSET(fd_tun, &fds_w)) + { + ssize_t written = write(fd_tun, bufin_read, bufin_size); + + if (-1 == written) + { + if ((errno == EINTR) || + (errno == EAGAIN)) + continue; + fprintf(stderr, "write-error to tun: %s\n", strerror(errno)); + return; + } + if (0 == written) + { + fprintf(stderr, "write returned 0\n"); + return; + } + { + bufin_size -= written; + bufin_read += written; + if (0 == bufin_size) + { + memmove(bufin, bufin_read, bufin_rpos); + bufin_read = NULL; /* start reading again */ + bufin_size = 0; + goto PROCESS_BUFFER; + } + } + } } - { - bufin_size -= written; - bufin_read += written; - if (0 == bufin_size) - { - memmove (bufin, bufin_read, bufin_rpos); - bufin_read = NULL; /* start reading again */ - bufin_size = 0; - goto PROCESS_BUFFER; - } - } - } } - } } @@ -732,7 +732,7 @@ PROCESS_BUFFER: * 255 failed to handle kill signal properly */ int -main (int argc, char *const*argv) +main(int argc, char *const*argv) { int r; char dev[IFNAMSIZ]; @@ -742,224 +742,224 @@ main (int argc, char *const*argv) int nortsetup = 0; if (7 != argc) - { - fprintf (stderr, "Fatal: must supply 6 arguments!\n"); - return 1; - } + { + fprintf(stderr, "Fatal: must supply 6 arguments!\n"); + return 1; + } /* assert privs so we can modify the firewall rules! */ - uid = getuid (); + uid = getuid(); #ifdef HAVE_SETRESUID - if (0 != setresuid (uid, 0, 0)) - { - fprintf (stderr, "Failed to setresuid to root: %s\n", strerror (errno)); - return 254; - } + if (0 != setresuid(uid, 0, 0)) + { + fprintf(stderr, "Failed to setresuid to root: %s\n", strerror(errno)); + return 254; + } #else - if (0 != seteuid (0)) - { - fprintf (stderr, "Failed to seteuid back to root: %s\n", strerror (errno)); - return 254; - } + if (0 != seteuid(0)) + { + fprintf(stderr, "Failed to seteuid back to root: %s\n", strerror(errno)); + return 254; + } #endif - if (0 == strncmp (argv[6], "1", 2)) + if (0 == strncmp(argv[6], "1", 2)) nortsetup = 1; if (0 == nortsetup) - { - /* verify that the binaries we care about are executable */ + { + /* verify that the binaries we care about are executable */ #ifdef IPTABLES - if (0 == access (IPTABLES, X_OK)) - sbin_iptables = IPTABLES; - else + if (0 == access(IPTABLES, X_OK)) + sbin_iptables = IPTABLES; + else #endif - if (0 == access ("/sbin/iptables", X_OK)) - sbin_iptables = "/sbin/iptables"; - else if (0 == access ("/usr/sbin/iptables", X_OK)) - sbin_iptables = "/usr/sbin/iptables"; - else - { - fprintf (stderr, - "Fatal: executable iptables not found in approved directories: %s\n", - strerror (errno)); - return 3; - } + if (0 == access("/sbin/iptables", X_OK)) + sbin_iptables = "/sbin/iptables"; + else if (0 == access("/usr/sbin/iptables", X_OK)) + sbin_iptables = "/usr/sbin/iptables"; + else + { + fprintf(stderr, + "Fatal: executable iptables not found in approved directories: %s\n", + strerror(errno)); + return 3; + } #ifdef IP6TABLES - if (0 == access (IP6TABLES, X_OK)) - sbin_ip6tables = IP6TABLES; - else + if (0 == access(IP6TABLES, X_OK)) + sbin_ip6tables = IP6TABLES; + else #endif - if (0 == access ("/sbin/ip6tables", X_OK)) - sbin_ip6tables = "/sbin/ip6tables"; - else if (0 == access ("/usr/sbin/ip6tables", X_OK)) - sbin_ip6tables = "/usr/sbin/ip6tables"; - else - { - fprintf (stderr, - "Fatal: executable ip6tables not found in approved directories: %s\n", - strerror (errno)); - return 3; - } + if (0 == access("/sbin/ip6tables", X_OK)) + sbin_ip6tables = "/sbin/ip6tables"; + else if (0 == access("/usr/sbin/ip6tables", X_OK)) + sbin_ip6tables = "/usr/sbin/ip6tables"; + else + { + fprintf(stderr, + "Fatal: executable ip6tables not found in approved directories: %s\n", + strerror(errno)); + return 3; + } #ifdef PATH_TO_IP - if (0 == access (PATH_TO_IP, X_OK)) - sbin_ip = PATH_TO_IP; - else + if (0 == access(PATH_TO_IP, X_OK)) + sbin_ip = PATH_TO_IP; + else #endif - if (0 == access ("/sbin/ip", X_OK)) - sbin_ip = "/sbin/ip"; - else if (0 == access ("/usr/sbin/ip", X_OK)) - sbin_ip = "/usr/sbin/ip"; - else if (0 == access ("/bin/ip", X_OK)) /* gentoo has it there */ - sbin_ip = "/bin/ip"; - else - { - fprintf (stderr, - "Fatal: executable ip not found in approved directories: %s\n", - strerror (errno)); - return 4; - } + if (0 == access("/sbin/ip", X_OK)) + sbin_ip = "/sbin/ip"; + else if (0 == access("/usr/sbin/ip", X_OK)) + sbin_ip = "/usr/sbin/ip"; + else if (0 == access("/bin/ip", X_OK)) /* gentoo has it there */ + sbin_ip = "/bin/ip"; + else + { + fprintf(stderr, + "Fatal: executable ip not found in approved directories: %s\n", + strerror(errno)); + return 4; + } #ifdef SYSCTL - if (0 == access (SYSCTL, X_OK)) - sbin_sysctl = SYSCTL; - else + if (0 == access(SYSCTL, X_OK)) + sbin_sysctl = SYSCTL; + else #endif - if (0 == access ("/sbin/sysctl", X_OK)) - sbin_sysctl = "/sbin/sysctl"; - else if (0 == access ("/usr/sbin/sysctl", X_OK)) - sbin_sysctl = "/usr/sbin/sysctl"; - else - { - fprintf (stderr, - "Fatal: executable sysctl not found in approved directories: %s\n", - strerror (errno)); - return 5; + if (0 == access("/sbin/sysctl", X_OK)) + sbin_sysctl = "/sbin/sysctl"; + else if (0 == access("/usr/sbin/sysctl", X_OK)) + sbin_sysctl = "/usr/sbin/sysctl"; + else + { + fprintf(stderr, + "Fatal: executable sysctl not found in approved directories: %s\n", + strerror(errno)); + return 5; + } } - } /* setup 'mygid' string */ - snprintf (mygid, sizeof (mygid), "%d", (int) getegid()); + snprintf(mygid, sizeof(mygid), "%d", (int)getegid()); /* do not die on SIGPIPE */ - if (SIG_ERR == signal (SIGPIPE, SIG_IGN)) - { - fprintf (stderr, "Failed to protect against SIGPIPE: %s\n", - strerror (errno)); - return 7; - } + if (SIG_ERR == signal(SIGPIPE, SIG_IGN)) + { + fprintf(stderr, "Failed to protect against SIGPIPE: %s\n", + strerror(errno)); + return 7; + } /* setup pipe to shutdown nicely on SIGINT */ - if (0 != pipe (cpipe)) - { - fprintf (stderr, - "Fatal: could not setup control pipe: %s\n", - strerror (errno)); - return 6; - } - if (cpipe[0] >= FD_SETSIZE) - { - fprintf (stderr, "Pipe file descriptor to large: %d", cpipe[0]); - (void) close (cpipe[0]); - (void) close (cpipe[1]); - return 6; - } - { - /* make pipe non-blocking, as we theoretically could otherwise block - in the signal handler */ - int flags = fcntl (cpipe[1], F_GETFL); - if (-1 == flags) + if (0 != pipe(cpipe)) { - fprintf (stderr, "Failed to read flags for pipe: %s", strerror (errno)); - (void) close (cpipe[0]); - (void) close (cpipe[1]); + fprintf(stderr, + "Fatal: could not setup control pipe: %s\n", + strerror(errno)); return 6; } - flags |= O_NONBLOCK; - if (0 != fcntl (cpipe[1], F_SETFL, flags)) + if (cpipe[0] >= FD_SETSIZE) { - fprintf (stderr, "Failed to make pipe non-blocking: %s", strerror (errno)); - (void) close (cpipe[0]); - (void) close (cpipe[1]); + fprintf(stderr, "Pipe file descriptor to large: %d", cpipe[0]); + (void)close(cpipe[0]); + (void)close(cpipe[1]); return 6; } + { + /* make pipe non-blocking, as we theoretically could otherwise block + in the signal handler */ + int flags = fcntl(cpipe[1], F_GETFL); + if (-1 == flags) + { + fprintf(stderr, "Failed to read flags for pipe: %s", strerror(errno)); + (void)close(cpipe[0]); + (void)close(cpipe[1]); + return 6; + } + flags |= O_NONBLOCK; + if (0 != fcntl(cpipe[1], F_SETFL, flags)) + { + fprintf(stderr, "Failed to make pipe non-blocking: %s", strerror(errno)); + (void)close(cpipe[0]); + (void)close(cpipe[1]); + return 6; + } } - if ( (SIG_ERR == signal (SIGTERM, &signal_handler)) || + if ((SIG_ERR == signal(SIGTERM, &signal_handler)) || #if (SIGTERM != GNUNET_TERM_SIG) - (SIG_ERR == signal (GNUNET_TERM_SIG, &signal_handler)) || + (SIG_ERR == signal(GNUNET_TERM_SIG, &signal_handler)) || #endif - (SIG_ERR == signal (SIGINT, &signal_handler)) || - (SIG_ERR == signal (SIGHUP, &signal_handler)) ) - { - fprintf (stderr, - "Fatal: could not initialize signal handler: %s\n", - strerror (errno)); - (void) close (cpipe[0]); - (void) close (cpipe[1]); - return 7; - } + (SIG_ERR == signal(SIGINT, &signal_handler)) || + (SIG_ERR == signal(SIGHUP, &signal_handler))) + { + fprintf(stderr, + "Fatal: could not initialize signal handler: %s\n", + strerror(errno)); + (void)close(cpipe[0]); + (void)close(cpipe[1]); + return 7; + } /* get interface name */ - strncpy (dev, argv[1], IFNAMSIZ); + strncpy(dev, argv[1], IFNAMSIZ); dev[IFNAMSIZ - 1] = '\0'; /* Disable rp filtering */ if (0 == nortsetup) - { - char *const sysctl_args[] = {"sysctl", "-w", - "net.ipv4.conf.all.rp_filter=0", NULL}; - char *const sysctl_args2[] = {"sysctl", "-w", - "net.ipv4.conf.default.rp_filter=0", NULL}; - if ((0 != fork_and_exec (sbin_sysctl, sysctl_args)) || - (0 != fork_and_exec (sbin_sysctl, sysctl_args2))) { - fprintf (stderr, - "Failed to disable rp filtering.\n"); - return 5; + char *const sysctl_args[] = { "sysctl", "-w", + "net.ipv4.conf.all.rp_filter=0", NULL }; + char *const sysctl_args2[] = { "sysctl", "-w", + "net.ipv4.conf.default.rp_filter=0", NULL }; + if ((0 != fork_and_exec(sbin_sysctl, sysctl_args)) || + (0 != fork_and_exec(sbin_sysctl, sysctl_args2))) + { + fprintf(stderr, + "Failed to disable rp filtering.\n"); + return 5; + } } - } /* now open virtual interface (first part that requires root) */ - if (-1 == (fd_tun = init_tun (dev))) - { - fprintf (stderr, "Fatal: could not initialize tun-interface\n"); - (void) signal (SIGTERM, SIG_IGN); + if (-1 == (fd_tun = init_tun(dev))) + { + fprintf(stderr, "Fatal: could not initialize tun-interface\n"); + (void)signal(SIGTERM, SIG_IGN); #if (SIGTERM != GNUNET_TERM_SIG) - (void) signal (GNUNET_TERM_SIG, SIG_IGN); + (void)signal(GNUNET_TERM_SIG, SIG_IGN); #endif - (void) signal (SIGINT, SIG_IGN); - (void) signal (SIGHUP, SIG_IGN); - (void) close (cpipe[0]); - (void) close (cpipe[1]); - return 5; - } + (void)signal(SIGINT, SIG_IGN); + (void)signal(SIGHUP, SIG_IGN); + (void)close(cpipe[0]); + (void)close(cpipe[1]); + return 5; + } /* now set interface addresses */ { const char *address = argv[2]; - long prefix_len = atol (argv[3]); + long prefix_len = atol(argv[3]); if ((prefix_len < 1) || (prefix_len > 127)) - { - fprintf (stderr, "Fatal: prefix_len out of range\n"); - (void) signal (SIGTERM, SIG_IGN); + { + fprintf(stderr, "Fatal: prefix_len out of range\n"); + (void)signal(SIGTERM, SIG_IGN); #if (SIGTERM != GNUNET_TERM_SIG) - (void) signal (GNUNET_TERM_SIG, SIG_IGN); + (void)signal(GNUNET_TERM_SIG, SIG_IGN); #endif - (void) signal (SIGINT, SIG_IGN); - (void) signal (SIGHUP, SIG_IGN); - (void) close (cpipe[0]); - (void) close (cpipe[1]); - return 2; - } - set_address6 (dev, address, prefix_len); + (void)signal(SIGINT, SIG_IGN); + (void)signal(SIGHUP, SIG_IGN); + (void)close(cpipe[0]); + (void)close(cpipe[1]); + return 2; + } + set_address6(dev, address, prefix_len); } { const char *address = argv[4]; const char *mask = argv[5]; - set_address4 (dev, address, mask); + set_address4(dev, address, mask); } @@ -968,237 +968,237 @@ main (int argc, char *const*argv) by the 'gnunet-service-dns') and with destination to port 53 on UDP, without hijacking */ if (0 == nortsetup) - { - r = 8; /* failed to fully setup routing table */ { - char *const mangle_args[] = + r = 8; /* failed to fully setup routing table */ + { + char *const mangle_args[] = { - "iptables", "-m", "owner", "-t", "mangle", "-I", "OUTPUT", "1", "-p", - "udp", "--gid-owner", mygid, "--dport", DNS_PORT, "-j", - "ACCEPT", NULL + "iptables", "-m", "owner", "-t", "mangle", "-I", "OUTPUT", "1", "-p", + "udp", "--gid-owner", mygid, "--dport", DNS_PORT, "-j", + "ACCEPT", NULL }; - if (0 != fork_and_exec (sbin_iptables, mangle_args)) - goto cleanup_rest; - } - { - char *const mangle_args[] = + if (0 != fork_and_exec(sbin_iptables, mangle_args)) + goto cleanup_rest; + } + { + char *const mangle_args[] = { - "ip6tables", "-m", "owner", "-t", "mangle", "-I", "OUTPUT", "1", "-p", - "udp", "--gid-owner", mygid, "--dport", DNS_PORT, "-j", - "ACCEPT", NULL + "ip6tables", "-m", "owner", "-t", "mangle", "-I", "OUTPUT", "1", "-p", + "udp", "--gid-owner", mygid, "--dport", DNS_PORT, "-j", + "ACCEPT", NULL }; - if (0 != fork_and_exec (sbin_ip6tables, mangle_args)) - goto cleanup_mangle_1b; - } - /* Mark all of the other DNS traffic using our mark DNS_MARK, - unless it is on a link-local IPv6 address, which we cannot support. */ - { - char *const mark_args[] = + if (0 != fork_and_exec(sbin_ip6tables, mangle_args)) + goto cleanup_mangle_1b; + } + /* Mark all of the other DNS traffic using our mark DNS_MARK, + unless it is on a link-local IPv6 address, which we cannot support. */ + { + char *const mark_args[] = { - "iptables", "-t", "mangle", "-I", "OUTPUT", "2", "-p", - "udp", "--dport", DNS_PORT, - "-j", "MARK", "--set-mark", DNS_MARK, - NULL + "iptables", "-t", "mangle", "-I", "OUTPUT", "2", "-p", + "udp", "--dport", DNS_PORT, + "-j", "MARK", "--set-mark", DNS_MARK, + NULL }; - if (0 != fork_and_exec (sbin_iptables, mark_args)) - goto cleanup_mangle_1; - } - { - char *const mark_args[] = + if (0 != fork_and_exec(sbin_iptables, mark_args)) + goto cleanup_mangle_1; + } + { + char *const mark_args[] = { - "ip6tables", "-t", "mangle", "-I", "OUTPUT", "2", "-p", - "udp", "--dport", DNS_PORT, - "!", "-s", "fe80::/10", /* this line excludes link-local traffic */ - "-j", "MARK", "--set-mark", DNS_MARK, - NULL + "ip6tables", "-t", "mangle", "-I", "OUTPUT", "2", "-p", + "udp", "--dport", DNS_PORT, + "!", "-s", "fe80::/10", /* this line excludes link-local traffic */ + "-j", "MARK", "--set-mark", DNS_MARK, + NULL }; - if (0 != fork_and_exec (sbin_ip6tables, mark_args)) - goto cleanup_mark_2b; - } - /* Forward all marked DNS traffic to our DNS_TABLE */ - { - char *const forward_args[] = + if (0 != fork_and_exec(sbin_ip6tables, mark_args)) + goto cleanup_mark_2b; + } + /* Forward all marked DNS traffic to our DNS_TABLE */ + { + char *const forward_args[] = { - "ip", "rule", "add", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL + "ip", "rule", "add", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL }; - if (0 != fork_and_exec (sbin_ip, forward_args)) - goto cleanup_mark_2; - } - { - char *const forward_args[] = + if (0 != fork_and_exec(sbin_ip, forward_args)) + goto cleanup_mark_2; + } + { + char *const forward_args[] = { "ip", "-6", "rule", "add", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL }; - if (0 != fork_and_exec (sbin_ip, forward_args)) - goto cleanup_forward_3b; - } - /* Finally, add rule in our forwarding table to pass to our virtual interface */ - { - char *const route_args[] = + if (0 != fork_and_exec(sbin_ip, forward_args)) + goto cleanup_forward_3b; + } + /* Finally, add rule in our forwarding table to pass to our virtual interface */ + { + char *const route_args[] = { - "ip", "route", "add", "default", "dev", dev, - "table", DNS_TABLE, NULL + "ip", "route", "add", "default", "dev", dev, + "table", DNS_TABLE, NULL }; - if (0 != fork_and_exec (sbin_ip, route_args)) - goto cleanup_forward_3; - } - { - char *const route_args[] = + if (0 != fork_and_exec(sbin_ip, route_args)) + goto cleanup_forward_3; + } + { + char *const route_args[] = { "ip", "-6", "route", "add", "default", "dev", dev, "table", DNS_TABLE, NULL }; - if (0 != fork_and_exec (sbin_ip, route_args)) - goto cleanup_route_4b; + if (0 != fork_and_exec(sbin_ip, route_args)) + goto cleanup_route_4b; + } } - } /* drop privs *except* for the saved UID; this is not perfect, but better than doing nothing */ #ifdef HAVE_SETRESUID - if (0 != setresuid (uid, uid, 0)) - { - fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno)); - r = 24; - goto cleanup_route_4; - } + if (0 != setresuid(uid, uid, 0)) + { + fprintf(stderr, "Failed to setresuid: %s\n", strerror(errno)); + r = 24; + goto cleanup_route_4; + } #else /* Note: no 'setuid' here as we must keep our saved UID as root */ - if (0 != seteuid (uid)) - { - fprintf (stderr, "Failed to seteuid: %s\n", strerror (errno)); - r = 24; - goto cleanup_route_4; - } + if (0 != seteuid(uid)) + { + fprintf(stderr, "Failed to seteuid: %s\n", strerror(errno)); + r = 24; + goto cleanup_route_4; + } #endif r = 0; /* did fully setup routing table (if nothing else happens, we were successful!) */ /* now forward until we hit a problem */ - run (fd_tun); + run(fd_tun); /* now need to regain privs so we can remove the firewall rules we added! */ #ifdef HAVE_SETRESUID - if (0 != setresuid (uid, 0, 0)) - { - fprintf (stderr, "Failed to setresuid back to root: %s\n", strerror (errno)); - r = 40; - goto cleanup_route_4; - } + if (0 != setresuid(uid, 0, 0)) + { + fprintf(stderr, "Failed to setresuid back to root: %s\n", strerror(errno)); + r = 40; + goto cleanup_route_4; + } #else - if (0 != seteuid (0)) - { - fprintf (stderr, "Failed to seteuid back to root: %s\n", strerror (errno)); - r = 40; - goto cleanup_route_4; - } + if (0 != seteuid(0)) + { + fprintf(stderr, "Failed to seteuid back to root: %s\n", strerror(errno)); + r = 40; + goto cleanup_route_4; + } #endif /* update routing tables again -- this is why we could not fully drop privs */ /* now undo updating of routing tables; normal exit or clean-up-on-error case */ - cleanup_route_4: +cleanup_route_4: if (0 == nortsetup) - { - char *const route_clean_args[] = + { + char *const route_clean_args[] = { - "ip", "-6", "route", "del", "default", "dev", dev, - "table", DNS_TABLE, NULL + "ip", "-6", "route", "del", "default", "dev", dev, + "table", DNS_TABLE, NULL }; - if (0 != fork_and_exec (sbin_ip, route_clean_args)) - r += 1; - } - cleanup_route_4b: + if (0 != fork_and_exec(sbin_ip, route_clean_args)) + r += 1; + } +cleanup_route_4b: if (0 == nortsetup) - { - char *const route_clean_args[] = + { + char *const route_clean_args[] = { - "ip", "route", "del", "default", "dev", dev, - "table", DNS_TABLE, NULL + "ip", "route", "del", "default", "dev", dev, + "table", DNS_TABLE, NULL }; - if (0 != fork_and_exec (sbin_ip, route_clean_args)) - r += 1; - } - cleanup_forward_3: + if (0 != fork_and_exec(sbin_ip, route_clean_args)) + r += 1; + } +cleanup_forward_3: if (0 == nortsetup) - { - char *const forward_clean_args[] = + { + char *const forward_clean_args[] = { - "ip", "-6", "rule", "del", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL + "ip", "-6", "rule", "del", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL }; - if (0 != fork_and_exec (sbin_ip, forward_clean_args)) - r += 2; - } - cleanup_forward_3b: + if (0 != fork_and_exec(sbin_ip, forward_clean_args)) + r += 2; + } +cleanup_forward_3b: if (0 == nortsetup) - { - char *const forward_clean_args[] = + { + char *const forward_clean_args[] = { - "ip", "rule", "del", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL + "ip", "rule", "del", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL }; - if (0 != fork_and_exec (sbin_ip, forward_clean_args)) - r += 2; - } - cleanup_mark_2: + if (0 != fork_and_exec(sbin_ip, forward_clean_args)) + r += 2; + } +cleanup_mark_2: if (0 == nortsetup) - { - char *const mark_clean_args[] = + { + char *const mark_clean_args[] = { - "ip6tables", "-t", "mangle", "-D", "OUTPUT", "-p", "udp", - "--dport", DNS_PORT, + "ip6tables", "-t", "mangle", "-D", "OUTPUT", "-p", "udp", + "--dport", DNS_PORT, "!", "-s", "fe80::/10", /* this line excludes link-local traffic */ "-j", "MARK", "--set-mark", DNS_MARK, NULL }; - if (0 != fork_and_exec (sbin_ip6tables, mark_clean_args)) - r += 4; - } - cleanup_mark_2b: + if (0 != fork_and_exec(sbin_ip6tables, mark_clean_args)) + r += 4; + } +cleanup_mark_2b: if (0 == nortsetup) - { - char *const mark_clean_args[] = + { + char *const mark_clean_args[] = { - "iptables", "-t", "mangle", "-D", "OUTPUT", "-p", "udp", - "--dport", DNS_PORT, "-j", "MARK", "--set-mark", DNS_MARK, NULL + "iptables", "-t", "mangle", "-D", "OUTPUT", "-p", "udp", + "--dport", DNS_PORT, "-j", "MARK", "--set-mark", DNS_MARK, NULL }; - if (0 != fork_and_exec (sbin_iptables, mark_clean_args)) - r += 4; - } - cleanup_mangle_1: + if (0 != fork_and_exec(sbin_iptables, mark_clean_args)) + r += 4; + } +cleanup_mangle_1: if (0 == nortsetup) - { - char *const mangle_clean_args[] = + { + char *const mangle_clean_args[] = { - "ip6tables", "-m", "owner", "-t", "mangle", "-D", "OUTPUT", "-p", "udp", - "--gid-owner", mygid, "--dport", DNS_PORT, "-j", "ACCEPT", - NULL + "ip6tables", "-m", "owner", "-t", "mangle", "-D", "OUTPUT", "-p", "udp", + "--gid-owner", mygid, "--dport", DNS_PORT, "-j", "ACCEPT", + NULL }; - if (0 != fork_and_exec (sbin_ip6tables, mangle_clean_args)) - r += 8; - } - cleanup_mangle_1b: + if (0 != fork_and_exec(sbin_ip6tables, mangle_clean_args)) + r += 8; + } +cleanup_mangle_1b: if (0 == nortsetup) - { - char *const mangle_clean_args[] = + { + char *const mangle_clean_args[] = { - "iptables", "-m", "owner", "-t", "mangle", "-D", "OUTPUT", "-p", "udp", - "--gid-owner", mygid, "--dport", DNS_PORT, "-j", "ACCEPT", - NULL + "iptables", "-m", "owner", "-t", "mangle", "-D", "OUTPUT", "-p", "udp", + "--gid-owner", mygid, "--dport", DNS_PORT, "-j", "ACCEPT", + NULL }; - if (0 != fork_and_exec (sbin_iptables, mangle_clean_args)) - r += 8; - } + if (0 != fork_and_exec(sbin_iptables, mangle_clean_args)) + r += 8; + } - cleanup_rest: +cleanup_rest: /* close virtual interface */ - (void) close (fd_tun); + (void)close(fd_tun); /* remove signal handler so we can close the pipes */ - (void) signal (SIGTERM, SIG_IGN); + (void)signal(SIGTERM, SIG_IGN); #if (SIGTERM != GNUNET_TERM_SIG) - (void) signal (GNUNET_TERM_SIG, SIG_IGN); + (void)signal(GNUNET_TERM_SIG, SIG_IGN); #endif - (void) signal (SIGINT, SIG_IGN); - (void) signal (SIGHUP, SIG_IGN); - (void) close (cpipe[0]); - (void) close (cpipe[1]); + (void)signal(SIGINT, SIG_IGN); + (void)signal(SIGHUP, SIG_IGN); + (void)close(cpipe[0]); + (void)close(cpipe[1]); return r; } diff --git a/src/dns/gnunet-service-dns.c b/src/dns/gnunet-service-dns.c index 9c4f1f490..9a2293b2d 100644 --- a/src/dns/gnunet-service-dns.c +++ b/src/dns/gnunet-service-dns.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dns/gnunet-service-dns.c @@ -59,14 +59,13 @@ * Generic logging shorthand */ #define LOG(kind, ...) \ - GNUNET_log_from (kind, "dns", __VA_ARGS__); + GNUNET_log_from(kind, "dns", __VA_ARGS__); /** * Phases each request goes through. */ -enum RequestPhase -{ +enum RequestPhase { /** * Request has just been received. */ @@ -112,16 +111,15 @@ enum RequestPhase /** * Entry we keep for each client. */ -struct ClientRecord -{ +struct ClientRecord { /** * Kept in doubly-linked list. */ struct ClientRecord *next; - /** + /** * Kept in doubly-linked list. - */ + */ struct ClientRecord *prev; /** @@ -138,16 +136,13 @@ struct ClientRecord * Flags for the client. */ enum GNUNET_DNS_Flags flags; - }; /** * Entry we keep for each active request. */ -struct RequestRecord -{ - +struct RequestRecord { /** * List of clients that still need to see this request (each entry * is set to NULL when the client is done). @@ -197,7 +192,6 @@ struct RequestRecord * In which phase this this request? */ enum RequestPhase phase; - }; @@ -258,14 +252,14 @@ static struct GNUNET_DNSSTUB_Context *dnsstub; * @param rr request to clean up */ static void -cleanup_rr (struct RequestRecord *rr) +cleanup_rr(struct RequestRecord *rr) { - GNUNET_free_non_null (rr->payload); + GNUNET_free_non_null(rr->payload); rr->payload = NULL; rr->payload_length = 0; - GNUNET_array_grow (rr->client_wait_list, - rr->client_wait_list_length, - 0); + GNUNET_array_grow(rr->client_wait_list, + rr->client_wait_list_length, + 0); } @@ -275,28 +269,28 @@ cleanup_rr (struct RequestRecord *rr) * @param cls unused */ static void -cleanup_task (void *cls GNUNET_UNUSED) +cleanup_task(void *cls GNUNET_UNUSED) { if (NULL != hijacker) - { - GNUNET_HELPER_stop (hijacker, GNUNET_NO); - hijacker = NULL; - } - for (unsigned int i=0;i<8;i++) - GNUNET_free_non_null (helper_argv[i]); - for (unsigned int i=0;i<=UINT16_MAX;i++) - cleanup_rr (&requests[i]); + { + GNUNET_HELPER_stop(hijacker, GNUNET_NO); + hijacker = NULL; + } + for (unsigned int i = 0; i < 8; i++) + GNUNET_free_non_null(helper_argv[i]); + for (unsigned int i = 0; i <= UINT16_MAX; i++) + cleanup_rr(&requests[i]); if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, - GNUNET_NO); - stats = NULL; - } + { + GNUNET_STATISTICS_destroy(stats, + GNUNET_NO); + stats = NULL; + } if (NULL != dnsstub) - { - GNUNET_DNSSTUB_stop (dnsstub); - dnsstub = NULL; - } + { + GNUNET_DNSSTUB_stop(dnsstub); + dnsstub = NULL; + } } @@ -306,54 +300,56 @@ cleanup_task (void *cls GNUNET_UNUSED) * @param rr request send to the network or just clean up. */ static void -request_done (struct RequestRecord *rr) +request_done(struct RequestRecord *rr) { struct GNUNET_MessageHeader *hdr; size_t reply_len; uint16_t source_port; uint16_t destination_port; - GNUNET_array_grow (rr->client_wait_list, - rr->client_wait_list_length, - 0); + GNUNET_array_grow(rr->client_wait_list, + rr->client_wait_list_length, + 0); if (RP_RESPONSE_MONITOR != rr->phase) - { - /* no response, drop */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got no response for request %llu, dropping\n", - (unsigned long long) rr->request_id); - cleanup_rr (rr); - return; - } + { + /* no response, drop */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got no response for request %llu, dropping\n", + (unsigned long long)rr->request_id); + cleanup_rr(rr); + return; + } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Transmitting response for request %llu\n", - (unsigned long long) rr->request_id); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Transmitting response for request %llu\n", + (unsigned long long)rr->request_id); /* send response via hijacker */ - reply_len = sizeof (struct GNUNET_MessageHeader); - reply_len += sizeof (struct GNUNET_TUN_Layer2PacketHeader); + reply_len = sizeof(struct GNUNET_MessageHeader); + reply_len += sizeof(struct GNUNET_TUN_Layer2PacketHeader); switch (rr->src_addr.ss_family) - { - case AF_INET: - reply_len += sizeof (struct GNUNET_TUN_IPv4Header); - break; - case AF_INET6: - reply_len += sizeof (struct GNUNET_TUN_IPv6Header); - break; - default: - GNUNET_break (0); - cleanup_rr (rr); - return; - } - reply_len += sizeof (struct GNUNET_TUN_UdpHeader); + { + case AF_INET: + reply_len += sizeof(struct GNUNET_TUN_IPv4Header); + break; + + case AF_INET6: + reply_len += sizeof(struct GNUNET_TUN_IPv6Header); + break; + + default: + GNUNET_break(0); + cleanup_rr(rr); + return; + } + reply_len += sizeof(struct GNUNET_TUN_UdpHeader); reply_len += rr->payload_length; if (reply_len >= GNUNET_MAX_MESSAGE_SIZE) - { - /* response too big, drop */ - GNUNET_break (0); /* how can this be? */ - cleanup_rr(rr); - return; - } + { + /* response too big, drop */ + GNUNET_break(0); /* how can this be? */ + cleanup_rr(rr); + return; + } { char buf[reply_len] GNUNET_ALIGN; size_t off; @@ -361,68 +357,70 @@ request_done (struct RequestRecord *rr) struct GNUNET_TUN_IPv6Header ip6; /* first, GNUnet message header */ - hdr = (struct GNUNET_MessageHeader*) buf; - hdr->type = htons (GNUNET_MESSAGE_TYPE_DNS_HELPER); - hdr->size = htons ((uint16_t) reply_len); - off = sizeof (struct GNUNET_MessageHeader); + hdr = (struct GNUNET_MessageHeader*)buf; + hdr->type = htons(GNUNET_MESSAGE_TYPE_DNS_HELPER); + hdr->size = htons((uint16_t)reply_len); + off = sizeof(struct GNUNET_MessageHeader); /* first, TUN header */ { struct GNUNET_TUN_Layer2PacketHeader tun; - tun.flags = htons (0); + tun.flags = htons(0); if (rr->src_addr.ss_family == AF_INET) - tun.proto = htons (ETH_P_IPV4); + tun.proto = htons(ETH_P_IPV4); else - tun.proto = htons (ETH_P_IPV6); - GNUNET_memcpy (&buf[off], - &tun, - sizeof (struct GNUNET_TUN_Layer2PacketHeader)); - off += sizeof (struct GNUNET_TUN_Layer2PacketHeader); + tun.proto = htons(ETH_P_IPV6); + GNUNET_memcpy(&buf[off], + &tun, + sizeof(struct GNUNET_TUN_Layer2PacketHeader)); + off += sizeof(struct GNUNET_TUN_Layer2PacketHeader); } /* now IP header */ switch (rr->src_addr.ss_family) - { - case AF_INET: { - struct sockaddr_in *src = (struct sockaddr_in *) &rr->src_addr; - struct sockaddr_in *dst = (struct sockaddr_in *) &rr->dst_addr; - - source_port = dst->sin_port; - destination_port = src->sin_port; - GNUNET_TUN_initialize_ipv4_header (&ip4, - IPPROTO_UDP, - reply_len - off - sizeof (struct GNUNET_TUN_IPv4Header), - &dst->sin_addr, - &src->sin_addr); - GNUNET_memcpy (&buf[off], - &ip4, - sizeof (ip4)); - off += sizeof (ip4); + case AF_INET: + { + struct sockaddr_in *src = (struct sockaddr_in *)&rr->src_addr; + struct sockaddr_in *dst = (struct sockaddr_in *)&rr->dst_addr; + + source_port = dst->sin_port; + destination_port = src->sin_port; + GNUNET_TUN_initialize_ipv4_header(&ip4, + IPPROTO_UDP, + reply_len - off - sizeof(struct GNUNET_TUN_IPv4Header), + &dst->sin_addr, + &src->sin_addr); + GNUNET_memcpy(&buf[off], + &ip4, + sizeof(ip4)); + off += sizeof(ip4); } break; - case AF_INET6: + + case AF_INET6: { - struct sockaddr_in6 *src = (struct sockaddr_in6 *) &rr->src_addr; - struct sockaddr_in6 *dst = (struct sockaddr_in6 *) &rr->dst_addr; - - source_port = dst->sin6_port; - destination_port = src->sin6_port; - GNUNET_TUN_initialize_ipv6_header (&ip6, - IPPROTO_UDP, - reply_len - off - sizeof (struct GNUNET_TUN_IPv6Header), - &dst->sin6_addr, - &src->sin6_addr); - GNUNET_memcpy (&buf[off], - &ip6, - sizeof (ip6)); - off += sizeof (ip6); + struct sockaddr_in6 *src = (struct sockaddr_in6 *)&rr->src_addr; + struct sockaddr_in6 *dst = (struct sockaddr_in6 *)&rr->dst_addr; + + source_port = dst->sin6_port; + destination_port = src->sin6_port; + GNUNET_TUN_initialize_ipv6_header(&ip6, + IPPROTO_UDP, + reply_len - off - sizeof(struct GNUNET_TUN_IPv6Header), + &dst->sin6_addr, + &src->sin6_addr); + GNUNET_memcpy(&buf[off], + &ip6, + sizeof(ip6)); + off += sizeof(ip6); } break; - default: - GNUNET_assert (0); - } + + default: + GNUNET_assert(0); + } /* now UDP header */ { @@ -430,40 +428,40 @@ request_done (struct RequestRecord *rr) udp.source_port = source_port; udp.destination_port = destination_port; - udp.len = htons (reply_len - off); + udp.len = htons(reply_len - off); if (AF_INET == rr->src_addr.ss_family) - GNUNET_TUN_calculate_udp4_checksum (&ip4, - &udp, - rr->payload, - rr->payload_length); + GNUNET_TUN_calculate_udp4_checksum(&ip4, + &udp, + rr->payload, + rr->payload_length); else - GNUNET_TUN_calculate_udp6_checksum (&ip6, - &udp, - rr->payload, - rr->payload_length); - GNUNET_memcpy (&buf[off], - &udp, - sizeof (udp)); - off += sizeof (udp); + GNUNET_TUN_calculate_udp6_checksum(&ip6, + &udp, + rr->payload, + rr->payload_length); + GNUNET_memcpy(&buf[off], + &udp, + sizeof(udp)); + off += sizeof(udp); } /* now DNS payload */ { - GNUNET_memcpy (&buf[off], rr->payload, rr->payload_length); + GNUNET_memcpy(&buf[off], rr->payload, rr->payload_length); off += rr->payload_length; } /* final checks & sending */ - GNUNET_assert (off == reply_len); - (void) GNUNET_HELPER_send (hijacker, - hdr, - GNUNET_YES, - NULL, NULL); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# DNS requests answered via TUN interface"), - 1, GNUNET_NO); + GNUNET_assert(off == reply_len); + (void)GNUNET_HELPER_send(hijacker, + hdr, + GNUNET_YES, + NULL, NULL); + GNUNET_STATISTICS_update(stats, + gettext_noop("# DNS requests answered via TUN interface"), + 1, GNUNET_NO); } /* clean up, we're done */ - cleanup_rr (rr); + cleanup_rr(rr); } @@ -475,31 +473,31 @@ request_done (struct RequestRecord *rr) * @param cr client to send the response to */ static void -send_request_to_client (struct RequestRecord *rr, - struct ClientRecord *cr) +send_request_to_client(struct RequestRecord *rr, + struct ClientRecord *cr) { struct GNUNET_MQ_Envelope *env; struct GNUNET_DNS_Request *req; - if (sizeof (struct GNUNET_DNS_Request) + rr->payload_length >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - cleanup_rr (rr); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending information about request %llu to local client\n", - (unsigned long long) rr->request_id); - env = GNUNET_MQ_msg_extra (req, - rr->payload_length, - GNUNET_MESSAGE_TYPE_DNS_CLIENT_REQUEST); - req->reserved = htonl (0); + if (sizeof(struct GNUNET_DNS_Request) + rr->payload_length >= GNUNET_MAX_MESSAGE_SIZE) + { + GNUNET_break(0); + cleanup_rr(rr); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending information about request %llu to local client\n", + (unsigned long long)rr->request_id); + env = GNUNET_MQ_msg_extra(req, + rr->payload_length, + GNUNET_MESSAGE_TYPE_DNS_CLIENT_REQUEST); + req->reserved = htonl(0); req->request_id = rr->request_id; - GNUNET_memcpy (&req[1], - rr->payload, - rr->payload_length); - GNUNET_MQ_send (cr->mq, - env); + GNUNET_memcpy(&req[1], + rr->payload, + rr->payload_length); + GNUNET_MQ_send(cr->mq, + env); } @@ -512,9 +510,9 @@ send_request_to_client (struct RequestRecord *rr, * @param r number of bytes in dns */ static void -process_dns_result (void *cls, - const struct GNUNET_TUN_DnsHeader *dns, - size_t r); +process_dns_result(void *cls, + const struct GNUNET_TUN_DnsHeader *dns, + size_t r); /** @@ -524,129 +522,138 @@ process_dns_result (void *cls, * @param rr request to process further */ static void -next_phase (struct RequestRecord *rr) +next_phase(struct RequestRecord *rr) { struct ClientRecord *cr; int nz; if (rr->phase == RP_DROP) - { - cleanup_rr (rr); - return; - } + { + cleanup_rr(rr); + return; + } nz = -1; - for (unsigned int j=0;jclient_wait_list_length;j++) - { - if (NULL != rr->client_wait_list[j]) + for (unsigned int j = 0; j < rr->client_wait_list_length; j++) { - nz = (int) j; - break; + if (NULL != rr->client_wait_list[j]) + { + nz = (int)j; + break; + } } - } if (-1 != nz) - { - send_request_to_client (rr, - rr->client_wait_list[nz]); - return; - } - /* done with current phase, advance! */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Request %llu now in phase %d\n", - rr->request_id, - rr->phase); - switch (rr->phase) - { - case RP_INIT: - rr->phase = RP_REQUEST_MONITOR; - for (cr = clients_head; NULL != cr; cr = cr->next) { - if (0 != (cr->flags & GNUNET_DNS_FLAG_REQUEST_MONITOR)) - GNUNET_array_append (rr->client_wait_list, - rr->client_wait_list_length, - cr); + send_request_to_client(rr, + rr->client_wait_list[nz]); + return; } - next_phase (rr); - return; - case RP_REQUEST_MONITOR: - rr->phase = RP_QUERY; - for (cr = clients_head; NULL != cr; cr = cr->next) + /* done with current phase, advance! */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Request %llu now in phase %d\n", + rr->request_id, + rr->phase); + switch (rr->phase) { - if (0 != (cr->flags & GNUNET_DNS_FLAG_PRE_RESOLUTION)) - GNUNET_array_append (rr->client_wait_list, - rr->client_wait_list_length, - cr); - } - next_phase (rr); - return; - case RP_QUERY: + case RP_INIT: + rr->phase = RP_REQUEST_MONITOR; + for (cr = clients_head; NULL != cr; cr = cr->next) + { + if (0 != (cr->flags & GNUNET_DNS_FLAG_REQUEST_MONITOR)) + GNUNET_array_append(rr->client_wait_list, + rr->client_wait_list_length, + cr); + } + next_phase(rr); + return; + + case RP_REQUEST_MONITOR: + rr->phase = RP_QUERY; + for (cr = clients_head; NULL != cr; cr = cr->next) + { + if (0 != (cr->flags & GNUNET_DNS_FLAG_PRE_RESOLUTION)) + GNUNET_array_append(rr->client_wait_list, + rr->client_wait_list_length, + cr); + } + next_phase(rr); + return; + + case RP_QUERY: #if 0 - /* TODO: optionally, use this to forward DNS requests to the - *original* DNS server instead of the one we have configured... - (but then we need to create a fresh dnsstub for each request - *and* manage the timeout) */ - switch (rr->dst_addr.ss_family) - { - case AF_INET: - salen = sizeof (struct sockaddr_in); - sa = (const struct sockaddr *) &rr->dst_addr; + /* TODO: optionally, use this to forward DNS requests to the + * original* DNS server instead of the one we have configured... + (but then we need to create a fresh dnsstub for each request + * and* manage the timeout) */ + switch (rr->dst_addr.ss_family) + { + case AF_INET: + salen = sizeof(struct sockaddr_in); + sa = (const struct sockaddr *)&rr->dst_addr; + break; + + case AF_INET6: + salen = sizeof(struct sockaddr_in6); + sa = (const struct sockaddr *)&rr->dst_addr; + break; + + default: + GNUNET_assert(0); + } +#endif + rr->phase = RP_INTERNET_DNS; + rr->rs = GNUNET_DNSSTUB_resolve(dnsstub, + rr->payload, + rr->payload_length, + &process_dns_result, + NULL); + if (NULL == rr->rs) + { + GNUNET_STATISTICS_update(stats, + gettext_noop("# DNS exit failed (failed to open socket)"), + 1, + GNUNET_NO); + cleanup_rr(rr); + return; + } + return; + + case RP_INTERNET_DNS: + rr->phase = RP_MODIFY; + for (cr = clients_head; NULL != cr; cr = cr->next) + { + if (0 != (cr->flags & GNUNET_DNS_FLAG_POST_RESOLUTION)) + GNUNET_array_append(rr->client_wait_list, + rr->client_wait_list_length, + cr); + } + next_phase(rr); + return; + + case RP_MODIFY: + rr->phase = RP_RESPONSE_MONITOR; + for (cr = clients_head; NULL != cr; cr = cr->next) + { + if (0 != (cr->flags & GNUNET_DNS_FLAG_RESPONSE_MONITOR)) + GNUNET_array_append(rr->client_wait_list, + rr->client_wait_list_length, + cr); + } + next_phase(rr); + return; + + case RP_RESPONSE_MONITOR: + request_done(rr); break; - case AF_INET6: - salen = sizeof (struct sockaddr_in6); - sa = (const struct sockaddr *) &rr->dst_addr; + + case RP_DROP: + cleanup_rr(rr); break; + default: - GNUNET_assert (0); - } -#endif - rr->phase = RP_INTERNET_DNS; - rr->rs = GNUNET_DNSSTUB_resolve (dnsstub, - rr->payload, - rr->payload_length, - &process_dns_result, - NULL); - if (NULL == rr->rs) - { - GNUNET_STATISTICS_update (stats, - gettext_noop ("# DNS exit failed (failed to open socket)"), - 1, - GNUNET_NO); - cleanup_rr (rr); - return; - } - return; - case RP_INTERNET_DNS: - rr->phase = RP_MODIFY; - for (cr = clients_head; NULL != cr; cr = cr->next) - { - if (0 != (cr->flags & GNUNET_DNS_FLAG_POST_RESOLUTION)) - GNUNET_array_append (rr->client_wait_list, - rr->client_wait_list_length, - cr); - } - next_phase (rr); - return; - case RP_MODIFY: - rr->phase = RP_RESPONSE_MONITOR; - for (cr = clients_head; NULL != cr; cr = cr->next) - { - if (0 != (cr->flags & GNUNET_DNS_FLAG_RESPONSE_MONITOR)) - GNUNET_array_append (rr->client_wait_list, - rr->client_wait_list_length, - cr); + GNUNET_break(0); + cleanup_rr(rr); + break; } - next_phase (rr); - return; - case RP_RESPONSE_MONITOR: - request_done (rr); - break; - case RP_DROP: - cleanup_rr (rr); - break; - default: - GNUNET_break (0); - cleanup_rr (rr); - break; - } } @@ -659,18 +666,18 @@ next_phase (struct RequestRecord *rr) * @return our `struct ClientRecord` */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { struct ClientRecord *cr = cls; - cr = GNUNET_new (struct ClientRecord); + cr = GNUNET_new(struct ClientRecord); cr->client = client; cr->mq = mq; - GNUNET_CONTAINER_DLL_insert (clients_head, - clients_tail, - cr); + GNUNET_CONTAINER_DLL_insert(clients_head, + clients_tail, + cr); return cr; } @@ -683,31 +690,31 @@ client_connect_cb (void *cls, * @param app_ctx our `struct ClientRecord` */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { struct ClientRecord *cr = app_ctx; struct RequestRecord *rr; - GNUNET_CONTAINER_DLL_remove (clients_head, - clients_tail, - cr); - for (unsigned int i=0;iclient_wait_list_length) - continue; /* not in use */ - for (unsigned int j=0;jclient_wait_list_length;j++) + GNUNET_CONTAINER_DLL_remove(clients_head, + clients_tail, + cr); + for (unsigned int i = 0; i < UINT16_MAX; i++) { - if (rr->client_wait_list[j] == cr) - { - rr->client_wait_list[j] = NULL; - next_phase (rr); - } + rr = &requests[i]; + if (0 == rr->client_wait_list_length) + continue; /* not in use */ + for (unsigned int j = 0; j < rr->client_wait_list_length; j++) + { + if (rr->client_wait_list[j] == cr) + { + rr->client_wait_list[j] = NULL; + next_phase(rr); + } + } } - } - GNUNET_free (cr); + GNUNET_free(cr); } @@ -720,39 +727,39 @@ client_disconnect_cb (void *cls, * @param r number of bytes in dns */ static void -process_dns_result (void *cls, - const struct GNUNET_TUN_DnsHeader *dns, - size_t r) +process_dns_result(void *cls, + const struct GNUNET_TUN_DnsHeader *dns, + size_t r) { struct RequestRecord *rr; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Processing DNS result from stub resolver\n"); - GNUNET_assert (NULL == cls); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Processing DNS result from stub resolver\n"); + GNUNET_assert(NULL == cls); if (NULL == dns) return; /* ignore */ rr = &requests[dns->id]; if (rr->phase != RP_INTERNET_DNS) - { - /* unexpected / bogus reply */ - GNUNET_STATISTICS_update (stats, - gettext_noop ("# External DNS response discarded (no matching request)"), - 1, GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received DNS reply that does not match any pending request. Dropping.\n"); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got a response from the stub resolver for DNS request %llu intercepted locally!\n", - (unsigned long long) rr->request_id); - GNUNET_free_non_null (rr->payload); - rr->payload = GNUNET_malloc (r); - GNUNET_memcpy (rr->payload, - dns, - r); + { + /* unexpected / bogus reply */ + GNUNET_STATISTICS_update(stats, + gettext_noop("# External DNS response discarded (no matching request)"), + 1, GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received DNS reply that does not match any pending request. Dropping.\n"); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got a response from the stub resolver for DNS request %llu intercepted locally!\n", + (unsigned long long)rr->request_id); + GNUNET_free_non_null(rr->payload); + rr->payload = GNUNET_malloc(r); + GNUNET_memcpy(rr->payload, + dns, + r); rr->payload_length = r; - next_phase (rr); + next_phase(rr); } @@ -763,13 +770,13 @@ process_dns_result (void *cls, * @param reg the init message */ static void -handle_client_init (void *cls, - const struct GNUNET_DNS_Register *reg) +handle_client_init(void *cls, + const struct GNUNET_DNS_Register *reg) { struct ClientRecord *cr = cls; - cr->flags = (enum GNUNET_DNS_Flags) ntohl (reg->flags); - GNUNET_SERVICE_client_continue (cr->client); + cr->flags = (enum GNUNET_DNS_Flags)ntohl(reg->flags); + GNUNET_SERVICE_client_continue(cr->client); } @@ -781,8 +788,8 @@ handle_client_init (void *cls, * @return #GNUNET_OK (always fine) */ static int -check_client_response (void *cls, - const struct GNUNET_DNS_Response *resp) +check_client_response(void *cls, + const struct GNUNET_DNS_Response *resp) { return GNUNET_OK; /* any payload is acceptable */ } @@ -795,87 +802,89 @@ check_client_response (void *cls, * @param resp the response */ static void -handle_client_response (void *cls, - const struct GNUNET_DNS_Response *resp) +handle_client_response(void *cls, + const struct GNUNET_DNS_Response *resp) { struct ClientRecord *cr = cls; struct RequestRecord *rr; uint16_t msize; uint16_t off; - msize = ntohs (resp->header.size); - off = (uint16_t) resp->request_id; + msize = ntohs(resp->header.size); + off = (uint16_t)resp->request_id; rr = &requests[off]; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received DNS response with ID %llu from local client!\n", - (unsigned long long) resp->request_id); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received DNS response with ID %llu from local client!\n", + (unsigned long long)resp->request_id); if (rr->request_id != resp->request_id) - { - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Client response discarded (no matching request)"), - 1, - GNUNET_NO); - GNUNET_SERVICE_client_continue (cr->client); - return; - } - for (unsigned int i=0;iclient_wait_list_length;i++) - { - if (NULL == rr->client_wait_list[i]) - continue; - if (rr->client_wait_list[i] != cr) - continue; - rr->client_wait_list[i] = NULL; - switch (ntohl (resp->drop_flag)) { - case 0: /* drop */ - rr->phase = RP_DROP; - break; - case 1: /* no change */ - break; - case 2: /* update */ - msize -= sizeof (struct GNUNET_DNS_Response); - if ( (sizeof (struct GNUNET_TUN_DnsHeader) > msize) || - (RP_REQUEST_MONITOR == rr->phase) || - (RP_RESPONSE_MONITOR == rr->phase) ) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (cr->client); - next_phase (rr); - return; - } - GNUNET_free_non_null (rr->payload); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Changing DNS reply according to client specifications\n"); - rr->payload = GNUNET_malloc (msize); - rr->payload_length = msize; - GNUNET_memcpy (rr->payload, &resp[1], msize); - if (rr->phase == RP_QUERY) - { - /* clear wait list, we're moving to MODIFY phase next */ - GNUNET_array_grow (rr->client_wait_list, - rr->client_wait_list_length, - 0); - } - /* if query changed to answer, move past DNS resolution phase... */ - if ( (RP_QUERY == rr->phase) && - (rr->payload_length > sizeof (struct GNUNET_TUN_DnsHeader)) && - ((struct GNUNET_TUN_DnsFlags*)&(((struct GNUNET_TUN_DnsHeader*) rr->payload)->flags))->query_or_response == 1) - { - rr->phase = RP_INTERNET_DNS; - GNUNET_array_grow (rr->client_wait_list, - rr->client_wait_list_length, - 0); - } - break; + GNUNET_STATISTICS_update(stats, + gettext_noop("# Client response discarded (no matching request)"), + 1, + GNUNET_NO); + GNUNET_SERVICE_client_continue(cr->client); + return; + } + for (unsigned int i = 0; i < rr->client_wait_list_length; i++) + { + if (NULL == rr->client_wait_list[i]) + continue; + if (rr->client_wait_list[i] != cr) + continue; + rr->client_wait_list[i] = NULL; + switch (ntohl(resp->drop_flag)) + { + case 0: /* drop */ + rr->phase = RP_DROP; + break; + + case 1: /* no change */ + break; + + case 2: /* update */ + msize -= sizeof(struct GNUNET_DNS_Response); + if ((sizeof(struct GNUNET_TUN_DnsHeader) > msize) || + (RP_REQUEST_MONITOR == rr->phase) || + (RP_RESPONSE_MONITOR == rr->phase)) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(cr->client); + next_phase(rr); + return; + } + GNUNET_free_non_null(rr->payload); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Changing DNS reply according to client specifications\n"); + rr->payload = GNUNET_malloc(msize); + rr->payload_length = msize; + GNUNET_memcpy(rr->payload, &resp[1], msize); + if (rr->phase == RP_QUERY) + { + /* clear wait list, we're moving to MODIFY phase next */ + GNUNET_array_grow(rr->client_wait_list, + rr->client_wait_list_length, + 0); + } + /* if query changed to answer, move past DNS resolution phase... */ + if ((RP_QUERY == rr->phase) && + (rr->payload_length > sizeof(struct GNUNET_TUN_DnsHeader)) && + ((struct GNUNET_TUN_DnsFlags*)&(((struct GNUNET_TUN_DnsHeader*)rr->payload)->flags))->query_or_response == 1) + { + rr->phase = RP_INTERNET_DNS; + GNUNET_array_grow(rr->client_wait_list, + rr->client_wait_list_length, + 0); + } + break; + } + next_phase(rr); + GNUNET_SERVICE_client_continue(cr->client); + return; } - next_phase (rr); - GNUNET_SERVICE_client_continue (cr->client); - return; - } /* odd, client was not on our list for the request, that ought to be an error */ - GNUNET_break (0); - GNUNET_SERVICE_client_drop (cr->client); + GNUNET_break(0); + GNUNET_SERVICE_client_drop(cr->client); } @@ -887,8 +896,8 @@ handle_client_response (void *cls, * @param message the actual message, a DNS request we should handle */ static int -process_helper_messages (void *cls, - const struct GNUNET_MessageHeader *message) +process_helper_messages(void *cls, + const struct GNUNET_MessageHeader *message) { uint16_t msize; const struct GNUNET_TUN_Layer2PacketHeader *tun; @@ -902,93 +911,95 @@ process_helper_messages (void *cls, struct sockaddr_in *dsta4; struct sockaddr_in6 *dsta6; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Intercepted message via DNS hijacker\n"); - msize = ntohs (message->size); - if (msize < sizeof (struct GNUNET_MessageHeader) + sizeof (struct GNUNET_TUN_Layer2PacketHeader) + sizeof (struct GNUNET_TUN_IPv4Header)) - { - /* non-IP packet received on TUN!? */ - GNUNET_break (0); - return GNUNET_OK; - } - msize -= sizeof (struct GNUNET_MessageHeader); - tun = (const struct GNUNET_TUN_Layer2PacketHeader *) &message[1]; - msize -= sizeof (struct GNUNET_TUN_Layer2PacketHeader); - switch (ntohs (tun->proto)) - { - case ETH_P_IPV4: - ip4 = (const struct GNUNET_TUN_IPv4Header *) &tun[1]; - ip6 = NULL; /* make compiler happy */ - if ( (msize < sizeof (struct GNUNET_TUN_IPv4Header)) || - (ip4->version != 4) || - (ip4->header_length != sizeof (struct GNUNET_TUN_IPv4Header) / 4) || - (ntohs(ip4->total_length) != msize) || - (ip4->protocol != IPPROTO_UDP) ) + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Intercepted message via DNS hijacker\n"); + msize = ntohs(message->size); + if (msize < sizeof(struct GNUNET_MessageHeader) + sizeof(struct GNUNET_TUN_Layer2PacketHeader) + sizeof(struct GNUNET_TUN_IPv4Header)) { - /* non-IP/UDP packet received on TUN (or with options) */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Received malformed IPv4-UDP packet on TUN interface.\n")); + /* non-IP packet received on TUN!? */ + GNUNET_break(0); return GNUNET_OK; } - udp = (const struct GNUNET_TUN_UdpHeader*) &ip4[1]; - msize -= sizeof (struct GNUNET_TUN_IPv4Header); - break; - case ETH_P_IPV6: - ip4 = NULL; /* make compiler happy */ - ip6 = (const struct GNUNET_TUN_IPv6Header *) &tun[1]; - if ( (msize < sizeof (struct GNUNET_TUN_IPv6Header)) || - (ip6->version != 6) || - (ntohs (ip6->payload_length) != msize - sizeof (struct GNUNET_TUN_IPv6Header)) || - (ip6->next_header != IPPROTO_UDP) ) + msize -= sizeof(struct GNUNET_MessageHeader); + tun = (const struct GNUNET_TUN_Layer2PacketHeader *)&message[1]; + msize -= sizeof(struct GNUNET_TUN_Layer2PacketHeader); + switch (ntohs(tun->proto)) { - /* non-IP/UDP packet received on TUN (or with extensions) */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Received malformed IPv6-UDP packet on TUN interface.\n")); + case ETH_P_IPV4: + ip4 = (const struct GNUNET_TUN_IPv4Header *)&tun[1]; + ip6 = NULL; /* make compiler happy */ + if ((msize < sizeof(struct GNUNET_TUN_IPv4Header)) || + (ip4->version != 4) || + (ip4->header_length != sizeof(struct GNUNET_TUN_IPv4Header) / 4) || + (ntohs(ip4->total_length) != msize) || + (ip4->protocol != IPPROTO_UDP)) + { + /* non-IP/UDP packet received on TUN (or with options) */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Received malformed IPv4-UDP packet on TUN interface.\n")); + return GNUNET_OK; + } + udp = (const struct GNUNET_TUN_UdpHeader*)&ip4[1]; + msize -= sizeof(struct GNUNET_TUN_IPv4Header); + break; + + case ETH_P_IPV6: + ip4 = NULL; /* make compiler happy */ + ip6 = (const struct GNUNET_TUN_IPv6Header *)&tun[1]; + if ((msize < sizeof(struct GNUNET_TUN_IPv6Header)) || + (ip6->version != 6) || + (ntohs(ip6->payload_length) != msize - sizeof(struct GNUNET_TUN_IPv6Header)) || + (ip6->next_header != IPPROTO_UDP)) + { + /* non-IP/UDP packet received on TUN (or with extensions) */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Received malformed IPv6-UDP packet on TUN interface.\n")); + return GNUNET_OK; + } + udp = (const struct GNUNET_TUN_UdpHeader *)&ip6[1]; + msize -= sizeof(struct GNUNET_TUN_IPv6Header); + break; + + default: + /* non-IP packet received on TUN!? */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Got non-IP packet with %u bytes and protocol %u from TUN\n"), + (unsigned int)msize, + ntohs(tun->proto)); return GNUNET_OK; } - udp = (const struct GNUNET_TUN_UdpHeader *) &ip6[1]; - msize -= sizeof (struct GNUNET_TUN_IPv6Header); - break; - default: - /* non-IP packet received on TUN!? */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Got non-IP packet with %u bytes and protocol %u from TUN\n"), - (unsigned int) msize, - ntohs (tun->proto)); - return GNUNET_OK; - } - if ( (msize <= sizeof (struct GNUNET_TUN_UdpHeader) + sizeof (struct GNUNET_TUN_DnsHeader)) || - (DNS_PORT != ntohs (udp->destination_port)) ) - { - /* non-DNS packet received on TUN, ignore */ - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("DNS interceptor got non-DNS packet (dropped)\n")); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Non-DNS UDP packet received via TUN interface"), - 1, GNUNET_NO); - return GNUNET_OK; - } - msize -= sizeof (struct GNUNET_TUN_UdpHeader); - dns = (const struct GNUNET_TUN_DnsHeader*) &udp[1]; + if ((msize <= sizeof(struct GNUNET_TUN_UdpHeader) + sizeof(struct GNUNET_TUN_DnsHeader)) || + (DNS_PORT != ntohs(udp->destination_port))) + { + /* non-DNS packet received on TUN, ignore */ + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("DNS interceptor got non-DNS packet (dropped)\n")); + GNUNET_STATISTICS_update(stats, + gettext_noop("# Non-DNS UDP packet received via TUN interface"), + 1, GNUNET_NO); + return GNUNET_OK; + } + msize -= sizeof(struct GNUNET_TUN_UdpHeader); + dns = (const struct GNUNET_TUN_DnsHeader*)&udp[1]; rr = &requests[dns->id]; /* clean up from previous request */ - GNUNET_free_non_null (rr->payload); + GNUNET_free_non_null(rr->payload); rr->payload = NULL; - GNUNET_array_grow (rr->client_wait_list, - rr->client_wait_list_length, - 0); + GNUNET_array_grow(rr->client_wait_list, + rr->client_wait_list_length, + 0); /* setup new request */ rr->phase = RP_INIT; - switch (ntohs (tun->proto)) - { - case ETH_P_IPV4: + switch (ntohs(tun->proto)) { - srca4 = (struct sockaddr_in*) &rr->src_addr; - dsta4 = (struct sockaddr_in*) &rr->dst_addr; - memset (srca4, 0, sizeof (struct sockaddr_in)); - memset (dsta4, 0, sizeof (struct sockaddr_in)); + case ETH_P_IPV4: + { + srca4 = (struct sockaddr_in*)&rr->src_addr; + dsta4 = (struct sockaddr_in*)&rr->dst_addr; + memset(srca4, 0, sizeof(struct sockaddr_in)); + memset(dsta4, 0, sizeof(struct sockaddr_in)); srca4->sin_family = AF_INET; dsta4->sin_family = AF_INET; srca4->sin_addr = ip4->source_address; @@ -996,17 +1007,18 @@ process_helper_messages (void *cls, srca4->sin_port = udp->source_port; dsta4->sin_port = udp->destination_port; #if HAVE_SOCKADDR_IN_SIN_LEN - srca4->sin_len = sizeof (struct sockaddr_in); - dsta4->sin_len = sizeof (struct sockaddr_in); + srca4->sin_len = sizeof(struct sockaddr_in); + dsta4->sin_len = sizeof(struct sockaddr_in); #endif } break; - case ETH_P_IPV6: + + case ETH_P_IPV6: { - srca6 = (struct sockaddr_in6*) &rr->src_addr; - dsta6 = (struct sockaddr_in6*) &rr->dst_addr; - memset (srca6, 0, sizeof (struct sockaddr_in6)); - memset (dsta6, 0, sizeof (struct sockaddr_in6)); + srca6 = (struct sockaddr_in6*)&rr->src_addr; + dsta6 = (struct sockaddr_in6*)&rr->dst_addr; + memset(srca6, 0, sizeof(struct sockaddr_in6)); + memset(dsta6, 0, sizeof(struct sockaddr_in6)); srca6->sin6_family = AF_INET6; dsta6->sin6_family = AF_INET6; srca6->sin6_addr = ip6->source_address; @@ -1014,27 +1026,28 @@ process_helper_messages (void *cls, srca6->sin6_port = udp->source_port; dsta6->sin6_port = udp->destination_port; #if HAVE_SOCKADDR_IN_SIN_LEN - srca6->sin6_len = sizeof (struct sockaddr_in6); - dsta6->sin6_len = sizeof (struct sockaddr_in6); + srca6->sin6_len = sizeof(struct sockaddr_in6); + dsta6->sin6_len = sizeof(struct sockaddr_in6); #endif } - break; - default: - GNUNET_assert (0); - } - rr->payload = GNUNET_malloc (msize); + break; + + default: + GNUNET_assert(0); + } + rr->payload = GNUNET_malloc(msize); rr->payload_length = msize; - GNUNET_memcpy (rr->payload, dns, msize); + GNUNET_memcpy(rr->payload, dns, msize); rr->request_id = dns->id | (request_id_gen << 16); request_id_gen++; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Creating new DNS request %llu\n", - (unsigned long long) rr->request_id); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# DNS requests received via TUN interface"), - 1, GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Creating new DNS request %llu\n", + (unsigned long long)rr->request_id); + GNUNET_STATISTICS_update(stats, + gettext_noop("# DNS requests received via TUN interface"), + 1, GNUNET_NO); /* start request processing state machine */ - next_phase (rr); + next_phase(rr); return GNUNET_OK; } @@ -1045,9 +1058,9 @@ process_helper_messages (void *cls, * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg_, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg_, + struct GNUNET_SERVICE_Handle *service) { char *ifc_name; char *ipv4addr; @@ -1059,126 +1072,126 @@ run (void *cls, int nortsetup; cfg = cfg_; - stats = GNUNET_STATISTICS_create ("dns", cfg); - GNUNET_SCHEDULER_add_shutdown (&cleanup_task, - cls); - dnsstub = GNUNET_DNSSTUB_start (128); + stats = GNUNET_STATISTICS_create("dns", cfg); + GNUNET_SCHEDULER_add_shutdown(&cleanup_task, + cls); + dnsstub = GNUNET_DNSSTUB_start(128); /* TODO: support multiple DNS_EXIT servers being configured */ /* TODO: see above TODO on using DNS server from original packet. Not sure which is best... */ dns_exit = NULL; - if ( (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "dns", - "DNS_EXIT", - &dns_exit)) || - (GNUNET_OK != - GNUNET_DNSSTUB_add_dns_ip (dnsstub, - dns_exit)) ) - { - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, - "dns", - "DNS_EXIT", - _("need a valid IPv4 or IPv6 address\n")); - GNUNET_free_non_null (dns_exit); - } - binary = GNUNET_OS_get_suid_binary_path (cfg, "gnunet-helper-dns"); + if ((GNUNET_OK != + GNUNET_CONFIGURATION_get_value_string(cfg, + "dns", + "DNS_EXIT", + &dns_exit)) || + (GNUNET_OK != + GNUNET_DNSSTUB_add_dns_ip(dnsstub, + dns_exit))) + { + GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_ERROR, + "dns", + "DNS_EXIT", + _("need a valid IPv4 or IPv6 address\n")); + GNUNET_free_non_null(dns_exit); + } + binary = GNUNET_OS_get_suid_binary_path(cfg, "gnunet-helper-dns"); if (GNUNET_YES != - GNUNET_OS_check_helper_binary (binary, - GNUNET_YES, - NULL)) // TODO: once we have a windows-testcase, add test parameters here - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("`%s' is not SUID or the path is invalid, " - "will not run DNS interceptor\n"), - binary); - global_ret = 1; - GNUNET_free (binary); - return; - } - GNUNET_free (binary); + GNUNET_OS_check_helper_binary(binary, + GNUNET_YES, + NULL)) // TODO: once we have a windows-testcase, add test parameters here + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("`%s' is not SUID or the path is invalid, " + "will not run DNS interceptor\n"), + binary); + global_ret = 1; + GNUNET_free(binary); + return; + } + GNUNET_free(binary); - helper_argv[0] = GNUNET_strdup ("gnunet-dns"); + helper_argv[0] = GNUNET_strdup("gnunet-dns"); if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, - "dns", - "IFNAME", - &ifc_name)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "No entry 'IFNAME' in configuration!\n"); - GNUNET_free (binary); - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_CONFIGURATION_get_value_string(cfg, + "dns", + "IFNAME", + &ifc_name)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "No entry 'IFNAME' in configuration!\n"); + GNUNET_free(binary); + GNUNET_SCHEDULER_shutdown(); + return; + } helper_argv[1] = ifc_name; - if ( (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, - "dns", - "IPV6ADDR", - &ipv6addr)) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "No entry 'IPV6ADDR' in configuration!\n"); - GNUNET_free (binary); - GNUNET_SCHEDULER_shutdown (); - return; - } + if ((GNUNET_SYSERR == + GNUNET_CONFIGURATION_get_value_string(cfg, + "dns", + "IPV6ADDR", + &ipv6addr))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "No entry 'IPV6ADDR' in configuration!\n"); + GNUNET_free(binary); + GNUNET_SCHEDULER_shutdown(); + return; + } helper_argv[2] = ipv6addr; if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, - "dns", - "IPV6PREFIX", - &ipv6prefix)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "No entry 'IPV6PREFIX' in configuration!\n"); - GNUNET_free (binary); - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_CONFIGURATION_get_value_string(cfg, + "dns", + "IPV6PREFIX", + &ipv6prefix)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "No entry 'IPV6PREFIX' in configuration!\n"); + GNUNET_free(binary); + GNUNET_SCHEDULER_shutdown(); + return; + } helper_argv[3] = ipv6prefix; if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, - "dns", - "IPV4ADDR", - &ipv4addr)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "No entry 'IPV4ADDR' in configuration!\n"); - GNUNET_free (binary); - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_CONFIGURATION_get_value_string(cfg, + "dns", + "IPV4ADDR", + &ipv4addr)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "No entry 'IPV4ADDR' in configuration!\n"); + GNUNET_free(binary); + GNUNET_SCHEDULER_shutdown(); + return; + } helper_argv[4] = ipv4addr; if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, "dns", "IPV4MASK", - &ipv4mask)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "No entry 'IPV4MASK' in configuration!\n"); - GNUNET_free (binary); - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_CONFIGURATION_get_value_string(cfg, "dns", "IPV4MASK", + &ipv4mask)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "No entry 'IPV4MASK' in configuration!\n"); + GNUNET_free(binary); + GNUNET_SCHEDULER_shutdown(); + return; + } helper_argv[5] = ipv4mask; - nortsetup = GNUNET_CONFIGURATION_get_value_yesno (cfg, "dns", - "SKIP_ROUTING_SETUP"); + nortsetup = GNUNET_CONFIGURATION_get_value_yesno(cfg, "dns", + "SKIP_ROUTING_SETUP"); if (GNUNET_YES == nortsetup) helper_argv[6] = GNUNET_strdup("1"); else helper_argv[6] = GNUNET_strdup("0"); helper_argv[7] = NULL; - hijacker = GNUNET_HELPER_start (GNUNET_NO, - binary, - helper_argv, - &process_helper_messages, - NULL, NULL); - GNUNET_free (binary); + hijacker = GNUNET_HELPER_start(GNUNET_NO, + binary, + helper_argv, + &process_helper_messages, + NULL, NULL); + GNUNET_free(binary); } @@ -1186,21 +1199,21 @@ run (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("dns", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_fixed_size (client_init, - GNUNET_MESSAGE_TYPE_DNS_CLIENT_INIT, - struct GNUNET_DNS_Register, - NULL), - GNUNET_MQ_hd_var_size (client_response, + ("dns", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_fixed_size(client_init, + GNUNET_MESSAGE_TYPE_DNS_CLIENT_INIT, + struct GNUNET_DNS_Register, + NULL), + GNUNET_MQ_hd_var_size(client_response, GNUNET_MESSAGE_TYPE_DNS_CLIENT_RESPONSE, struct GNUNET_DNS_Response, NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_handler_end()); /* FIXME: this might need a port on systems without 'getresgid' */ @@ -1209,28 +1222,28 @@ GNUNET_SERVICE_MAIN * Enable use of SGID capabilities on POSIX */ void __attribute__ ((constructor)) -GNUNET_DNS_init () +GNUNET_DNS_init() { gid_t rgid; gid_t egid; gid_t sgid; - if (-1 == getresgid (&rgid, - &egid, - &sgid)) - { - fprintf (stderr, - "getresgid failed: %s\n", - strerror (errno)); - } + if (-1 == getresgid(&rgid, + &egid, + &sgid)) + { + fprintf(stderr, + "getresgid failed: %s\n", + strerror(errno)); + } else if (sgid != rgid) - { - if (-1 == setregid (sgid, - sgid)) - fprintf (stderr, - "setregid failed: %s\n", - strerror (errno)); - } + { + if (-1 == setregid(sgid, + sgid)) + fprintf(stderr, + "setregid failed: %s\n", + strerror(errno)); + } } #endif diff --git a/src/dns/gnunet-zonewalk.c b/src/dns/gnunet-zonewalk.c index 19fc5b78d..2968d0209 100644 --- a/src/dns/gnunet-zonewalk.c +++ b/src/dns/gnunet-zonewalk.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/dns/gnunet-zoneimport.c @@ -31,8 +31,7 @@ /** * Request we should make. */ -struct Request -{ +struct Request { /** * Requests are kept in a DLL. */ @@ -144,145 +143,155 @@ static struct GNUNET_SCHEDULER_Task *t; * @param rec response */ static void -process_record (struct Request *req, - struct GNUNET_DNSPARSER_Record *rec) +process_record(struct Request *req, + struct GNUNET_DNSPARSER_Record *rec) { char buf[INET6_ADDRSTRLEN]; records++; switch (rec->type) - { - case GNUNET_DNSPARSER_TYPE_A: - fprintf (stdout, - "%s A %s\n", - req->hostname, - inet_ntop (AF_INET, + { + case GNUNET_DNSPARSER_TYPE_A: + fprintf(stdout, + "%s A %s\n", + req->hostname, + inet_ntop(AF_INET, rec->data.raw.data, buf, - sizeof (buf))); - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - fprintf (stdout, - "%s AAAA %s\n", - req->hostname, - inet_ntop (AF_INET6, + sizeof(buf))); + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + fprintf(stdout, + "%s AAAA %s\n", + req->hostname, + inet_ntop(AF_INET6, rec->data.raw.data, buf, - sizeof (buf))); - break; - case GNUNET_DNSPARSER_TYPE_NS: - fprintf (stdout, - "%s NS %s\n", - req->hostname, - rec->data.hostname); - break; - case GNUNET_DNSPARSER_TYPE_CNAME: - fprintf (stdout, - "%s CNAME %s\n", - req->hostname, - rec->data.hostname); - break; - case GNUNET_DNSPARSER_TYPE_MX: - fprintf (stdout, - "%s MX %u %s\n", - req->hostname, - (unsigned int) rec->data.mx->preference, - rec->data.mx->mxhost); - break; - case GNUNET_DNSPARSER_TYPE_SOA: - fprintf (stdout, - "%s SOA %s %s %u %u %u %u %u\n", - req->hostname, - rec->data.soa->mname, - rec->data.soa->rname, - (unsigned int) rec->data.soa->serial, - (unsigned int) rec->data.soa->refresh, - (unsigned int) rec->data.soa->retry, - (unsigned int) rec->data.soa->expire, - (unsigned int) rec->data.soa->minimum_ttl); - break; - case GNUNET_DNSPARSER_TYPE_SRV: - fprintf (stdout, - "%s SRV %s %u %u %u\n", - req->hostname, - rec->data.srv->target, - rec->data.srv->priority, - rec->data.srv->weight, - rec->data.srv->port); - break; - case GNUNET_DNSPARSER_TYPE_PTR: - fprintf (stdout, - "%s PTR %s\n", - req->hostname, - rec->data.hostname); - break; - case GNUNET_DNSPARSER_TYPE_TXT: - fprintf (stdout, - "%s TXT %.*s\n", - req->hostname, - (int) rec->data.raw.data_len, - (char *) rec->data.raw.data); - break; - case GNUNET_DNSPARSER_TYPE_DNAME: - fprintf (stdout, - "%s DNAME %s\n", - req->hostname, - rec->data.hostname); - break; + sizeof(buf))); + break; + + case GNUNET_DNSPARSER_TYPE_NS: + fprintf(stdout, + "%s NS %s\n", + req->hostname, + rec->data.hostname); + break; + + case GNUNET_DNSPARSER_TYPE_CNAME: + fprintf(stdout, + "%s CNAME %s\n", + req->hostname, + rec->data.hostname); + break; + + case GNUNET_DNSPARSER_TYPE_MX: + fprintf(stdout, + "%s MX %u %s\n", + req->hostname, + (unsigned int)rec->data.mx->preference, + rec->data.mx->mxhost); + break; + + case GNUNET_DNSPARSER_TYPE_SOA: + fprintf(stdout, + "%s SOA %s %s %u %u %u %u %u\n", + req->hostname, + rec->data.soa->mname, + rec->data.soa->rname, + (unsigned int)rec->data.soa->serial, + (unsigned int)rec->data.soa->refresh, + (unsigned int)rec->data.soa->retry, + (unsigned int)rec->data.soa->expire, + (unsigned int)rec->data.soa->minimum_ttl); + break; + + case GNUNET_DNSPARSER_TYPE_SRV: + fprintf(stdout, + "%s SRV %s %u %u %u\n", + req->hostname, + rec->data.srv->target, + rec->data.srv->priority, + rec->data.srv->weight, + rec->data.srv->port); + break; + + case GNUNET_DNSPARSER_TYPE_PTR: + fprintf(stdout, + "%s PTR %s\n", + req->hostname, + rec->data.hostname); + break; + + case GNUNET_DNSPARSER_TYPE_TXT: + fprintf(stdout, + "%s TXT %.*s\n", + req->hostname, + (int)rec->data.raw.data_len, + (char *)rec->data.raw.data); + break; + + case GNUNET_DNSPARSER_TYPE_DNAME: + fprintf(stdout, + "%s DNAME %s\n", + req->hostname, + rec->data.hostname); + break; /* obscure records */ - case GNUNET_DNSPARSER_TYPE_AFSDB: - case GNUNET_DNSPARSER_TYPE_NAPTR: - case GNUNET_DNSPARSER_TYPE_APL: - case GNUNET_DNSPARSER_TYPE_DHCID: - case GNUNET_DNSPARSER_TYPE_HIP: - case GNUNET_DNSPARSER_TYPE_LOC: - case GNUNET_DNSPARSER_TYPE_RP: - case GNUNET_DNSPARSER_TYPE_TKEY: - case GNUNET_DNSPARSER_TYPE_TSIG: - case GNUNET_DNSPARSER_TYPE_URI: - case GNUNET_DNSPARSER_TYPE_TA: + case GNUNET_DNSPARSER_TYPE_AFSDB: + case GNUNET_DNSPARSER_TYPE_NAPTR: + case GNUNET_DNSPARSER_TYPE_APL: + case GNUNET_DNSPARSER_TYPE_DHCID: + case GNUNET_DNSPARSER_TYPE_HIP: + case GNUNET_DNSPARSER_TYPE_LOC: + case GNUNET_DNSPARSER_TYPE_RP: + case GNUNET_DNSPARSER_TYPE_TKEY: + case GNUNET_DNSPARSER_TYPE_TSIG: + case GNUNET_DNSPARSER_TYPE_URI: + case GNUNET_DNSPARSER_TYPE_TA: /* DNSSEC */ - case GNUNET_DNSPARSER_TYPE_DS: - case GNUNET_DNSPARSER_TYPE_RRSIG: - case GNUNET_DNSPARSER_TYPE_NSEC: - case GNUNET_DNSPARSER_TYPE_DNSKEY: - case GNUNET_DNSPARSER_TYPE_NSEC3: - case GNUNET_DNSPARSER_TYPE_NSEC3PARAM: - case GNUNET_DNSPARSER_TYPE_CDS: - case GNUNET_DNSPARSER_TYPE_CDNSKEY: + case GNUNET_DNSPARSER_TYPE_DS: + case GNUNET_DNSPARSER_TYPE_RRSIG: + case GNUNET_DNSPARSER_TYPE_NSEC: + case GNUNET_DNSPARSER_TYPE_DNSKEY: + case GNUNET_DNSPARSER_TYPE_NSEC3: + case GNUNET_DNSPARSER_TYPE_NSEC3PARAM: + case GNUNET_DNSPARSER_TYPE_CDS: + case GNUNET_DNSPARSER_TYPE_CDNSKEY: /* DNSSEC payload */ - case GNUNET_DNSPARSER_TYPE_CERT: - case GNUNET_DNSPARSER_TYPE_SSHFP: - case GNUNET_DNSPARSER_TYPE_IPSECKEY: - case GNUNET_DNSPARSER_TYPE_TLSA: - case GNUNET_DNSPARSER_TYPE_OPENPGPKEY: + case GNUNET_DNSPARSER_TYPE_CERT: + case GNUNET_DNSPARSER_TYPE_SSHFP: + case GNUNET_DNSPARSER_TYPE_IPSECKEY: + case GNUNET_DNSPARSER_TYPE_TLSA: + case GNUNET_DNSPARSER_TYPE_OPENPGPKEY: /* obsolete records */ - case GNUNET_DNSPARSER_TYPE_SIG: - case GNUNET_DNSPARSER_TYPE_KEY: - case GNUNET_DNSPARSER_TYPE_KX: + case GNUNET_DNSPARSER_TYPE_SIG: + case GNUNET_DNSPARSER_TYPE_KEY: + case GNUNET_DNSPARSER_TYPE_KX: { char *base32; - base32 = GNUNET_STRINGS_data_to_string_alloc (rec->data.raw.data, - rec->data.raw.data_len); - fprintf (stdout, - "%s (%u) %s\n", - req->hostname, - rec->type, - base32); - GNUNET_free (base32); + base32 = GNUNET_STRINGS_data_to_string_alloc(rec->data.raw.data, + rec->data.raw.data_len); + fprintf(stdout, + "%s (%u) %s\n", + req->hostname, + rec->type, + base32); + GNUNET_free(base32); } break; - default: - fprintf (stderr, - "Unsupported type %u\n", - (unsigned int) rec->type); - break; - } + + default: + fprintf(stderr, + "Unsupported type %u\n", + (unsigned int)rec->type); + break; + } } @@ -294,90 +303,90 @@ process_record (struct Request *req, * @param dns_len number of bytes in @a dns */ static void -process_result (void *cls, - const struct GNUNET_TUN_DnsHeader *dns, - size_t dns_len) +process_result(void *cls, + const struct GNUNET_TUN_DnsHeader *dns, + size_t dns_len) { struct Request *req = cls; struct GNUNET_DNSPARSER_Packet *p; if (NULL == dns) - { - /* stub gave up */ - pending--; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Stub gave up on DNS reply for `%s'\n", - req->hostname); - GNUNET_CONTAINER_DLL_remove (req_head, - req_tail, - req); - if (req->issue_num > MAX_RETRIES) { - failures++; - GNUNET_free (req->hostname); - GNUNET_free (req->raw); - GNUNET_free (req); + /* stub gave up */ + pending--; + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Stub gave up on DNS reply for `%s'\n", + req->hostname); + GNUNET_CONTAINER_DLL_remove(req_head, + req_tail, + req); + if (req->issue_num > MAX_RETRIES) + { + failures++; + GNUNET_free(req->hostname); + GNUNET_free(req->raw); + GNUNET_free(req); + return; + } + GNUNET_CONTAINER_DLL_insert_tail(req_head, + req_tail, + req); + req->rs = NULL; return; } - GNUNET_CONTAINER_DLL_insert_tail (req_head, - req_tail, - req); - req->rs = NULL; - return; - } if (req->id != dns->id) return; pending--; - GNUNET_DNSSTUB_resolve_cancel (req->rs); + GNUNET_DNSSTUB_resolve_cancel(req->rs); req->rs = NULL; - GNUNET_CONTAINER_DLL_remove (req_head, - req_tail, - req); - p = GNUNET_DNSPARSER_parse ((const char *) dns, - dns_len); + GNUNET_CONTAINER_DLL_remove(req_head, + req_tail, + req); + p = GNUNET_DNSPARSER_parse((const char *)dns, + dns_len); if (NULL == p) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to parse DNS reply for `%s'\n", - req->hostname); - if (req->issue_num > MAX_RETRIES) { - failures++; - GNUNET_free (req->hostname); - GNUNET_free (req->raw); - GNUNET_free (req); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to parse DNS reply for `%s'\n", + req->hostname); + if (req->issue_num > MAX_RETRIES) + { + failures++; + GNUNET_free(req->hostname); + GNUNET_free(req->raw); + GNUNET_free(req); + return; + } + GNUNET_CONTAINER_DLL_insert_tail(req_head, + req_tail, + req); return; } - GNUNET_CONTAINER_DLL_insert_tail (req_head, - req_tail, - req); - return; - } - for (unsigned int i=0;inum_answers;i++) - { - struct GNUNET_DNSPARSER_Record *rs = &p->answers[i]; - - process_record (req, - rs); - } - for (unsigned int i=0;inum_authority_records;i++) - { - struct GNUNET_DNSPARSER_Record *rs = &p->authority_records[i]; - - process_record (req, - rs); - } - for (unsigned int i=0;inum_additional_records;i++) - { - struct GNUNET_DNSPARSER_Record *rs = &p->additional_records[i]; - - process_record (req, - rs); - } - GNUNET_DNSPARSER_free_packet (p); - GNUNET_free (req->hostname); - GNUNET_free (req->raw); - GNUNET_free (req); + for (unsigned int i = 0; i < p->num_answers; i++) + { + struct GNUNET_DNSPARSER_Record *rs = &p->answers[i]; + + process_record(req, + rs); + } + for (unsigned int i = 0; i < p->num_authority_records; i++) + { + struct GNUNET_DNSPARSER_Record *rs = &p->authority_records[i]; + + process_record(req, + rs); + } + for (unsigned int i = 0; i < p->num_additional_records; i++) + { + struct GNUNET_DNSPARSER_Record *rs = &p->additional_records[i]; + + process_record(req, + rs); + } + GNUNET_DNSPARSER_free_packet(p); + GNUNET_free(req->hostname); + GNUNET_free(req->raw); + GNUNET_free(req); } @@ -391,31 +400,31 @@ process_result (void *cls, * #GNUNET_SYSERR if we are at the rate limit */ static int -submit_req (struct Request *req) +submit_req(struct Request *req) { static struct timeval last_request; struct timeval now; if (NULL != req->rs) return GNUNET_NO; /* already submitted */ - gettimeofday (&now, - NULL); - if ( ( ( (now.tv_sec - last_request.tv_sec) == 0) && - ( (now.tv_usec - last_request.tv_usec) < TIME_THRESH) ) || - (pending >= THRESH) ) + gettimeofday(&now, + NULL); + if ((((now.tv_sec - last_request.tv_sec) == 0) && + ((now.tv_usec - last_request.tv_usec) < TIME_THRESH)) || + (pending >= THRESH)) return GNUNET_SYSERR; - GNUNET_assert (NULL == req->rs); - req->rs = GNUNET_DNSSTUB_resolve (ctx, - req->raw, - req->raw_len, - &process_result, - req); - GNUNET_assert (NULL != req->rs); + GNUNET_assert(NULL == req->rs); + req->rs = GNUNET_DNSSTUB_resolve(ctx, + req->raw, + req->raw_len, + &process_result, + req); + GNUNET_assert(NULL != req->rs); req->issue_num++; last_request = now; lookups++; pending++; - req->time = time (NULL); + req->time = time(NULL); return GNUNET_OK; } @@ -428,21 +437,21 @@ submit_req (struct Request *req) static void process_queue(void *cls) { - (void) cls; + (void)cls; t = NULL; for (struct Request *req = req_head; NULL != req; req = req->next) - { - if (GNUNET_SYSERR == submit_req (req)) - break; - } + { + if (GNUNET_SYSERR == submit_req(req)) + break; + } if (NULL != req_head) - t = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MILLISECONDS, - &process_queue, - NULL); + t = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MILLISECONDS, + &process_queue, + NULL); else - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -452,15 +461,15 @@ process_queue(void *cls) * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - (void) cls; + (void)cls; if (NULL != t) - { - GNUNET_SCHEDULER_cancel (t); - t = NULL; - } - GNUNET_DNSSTUB_stop (ctx); + { + GNUNET_SCHEDULER_cancel(t); + t = NULL; + } + GNUNET_DNSSTUB_stop(ctx); ctx = NULL; } @@ -472,14 +481,14 @@ do_shutdown (void *cls) * @param cls NULL */ static void -run (void *cls) +run(void *cls) { - (void) cls; + (void)cls; - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - t = GNUNET_SCHEDULER_add_now (&process_queue, + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); + t = GNUNET_SCHEDULER_add_now(&process_queue, + NULL); } @@ -489,7 +498,7 @@ run (void *cls) * @param hostname name to resolve */ static void -queue (const char *hostname) +queue(const char *hostname) { struct GNUNET_DNSPARSER_Packet p; struct GNUNET_DNSPARSER_Query q; @@ -499,46 +508,46 @@ queue (const char *hostname) int ret; if (GNUNET_OK != - GNUNET_DNSPARSER_check_name (hostname)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Refusing invalid hostname `%s'\n", - hostname); - return; - } - q.name = (char *) hostname; + GNUNET_DNSPARSER_check_name(hostname)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Refusing invalid hostname `%s'\n", + hostname); + return; + } + q.name = (char *)hostname; q.type = GNUNET_DNSPARSER_TYPE_NS; q.dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; - memset (&p, - 0, - sizeof (p)); + memset(&p, + 0, + sizeof(p)); p.num_queries = 1; p.queries = &q; - p.id = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, - UINT16_MAX); - ret = GNUNET_DNSPARSER_pack (&p, - UINT16_MAX, - &raw, - &raw_size); + p.id = (uint16_t)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, + UINT16_MAX); + ret = GNUNET_DNSPARSER_pack(&p, + UINT16_MAX, + &raw, + &raw_size); if (GNUNET_OK != ret) - { - if (GNUNET_NO == ret) - GNUNET_free (raw); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to pack query for hostname `%s'\n", - hostname); - return; - } + { + if (GNUNET_NO == ret) + GNUNET_free(raw); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to pack query for hostname `%s'\n", + hostname); + return; + } - req = GNUNET_new (struct Request); - req->hostname = strdup (hostname); + req = GNUNET_new(struct Request); + req->hostname = strdup(hostname); req->raw = raw; req->raw_len = raw_size; req->id = p.id; - GNUNET_CONTAINER_DLL_insert_tail (req_head, - req_tail, - req); + GNUNET_CONTAINER_DLL_insert_tail(req_head, + req_tail, + req); } @@ -550,50 +559,50 @@ queue (const char *hostname) * @return 0 on success */ int -main (int argc, - char **argv) +main(int argc, + char **argv) { char hn[256]; if (2 != argc) - { - fprintf (stderr, - "Missing required configuration argument\n"); - return -1; - } - ctx = GNUNET_DNSSTUB_start (256); + { + fprintf(stderr, + "Missing required configuration argument\n"); + return -1; + } + ctx = GNUNET_DNSSTUB_start(256); if (NULL == ctx) - { - fprintf (stderr, - "Failed to initialize GNUnet DNS STUB\n"); - return 1; - } + { + fprintf(stderr, + "Failed to initialize GNUnet DNS STUB\n"); + return 1; + } if (GNUNET_OK != - GNUNET_DNSSTUB_add_dns_ip (ctx, - argv[1])) - { - fprintf (stderr, - "Failed to use `%s' for DNS resolver\n", - argv[1]); - return 1; - } + GNUNET_DNSSTUB_add_dns_ip(ctx, + argv[1])) + { + fprintf(stderr, + "Failed to use `%s' for DNS resolver\n", + argv[1]); + return 1; + } while (NULL != - fgets (hn, - sizeof (hn), - stdin)) - { - if (strlen(hn) > 0) - hn[strlen(hn)-1] = '\0'; /* eat newline */ - queue (hn); - } - GNUNET_SCHEDULER_run (&run, - NULL); - fprintf (stderr, - "Did %u lookups, found %u records, %u lookups failed, %u pending on shutdown\n", - lookups, - records, - failures, - pending); + fgets(hn, + sizeof(hn), + stdin)) + { + if (strlen(hn) > 0) + hn[strlen(hn) - 1] = '\0'; /* eat newline */ + queue(hn); + } + GNUNET_SCHEDULER_run(&run, + NULL); + fprintf(stderr, + "Did %u lookups, found %u records, %u lookups failed, %u pending on shutdown\n", + lookups, + records, + failures, + pending); return 0; } diff --git a/src/dns/plugin_block_dns.c b/src/dns/plugin_block_dns.c index ed75ce2f3..fd4d844c5 100644 --- a/src/dns/plugin_block_dns.c +++ b/src/dns/plugin_block_dns.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file dns/plugin_block_dns.c @@ -54,37 +54,37 @@ * by this @a type of block (this is not an error) */ static struct GNUNET_BLOCK_Group * -block_plugin_dns_create_group (void *cls, - enum GNUNET_BLOCK_Type type, - uint32_t nonce, - const void *raw_data, - size_t raw_data_size, - va_list va) +block_plugin_dns_create_group(void *cls, + enum GNUNET_BLOCK_Type type, + uint32_t nonce, + const void *raw_data, + size_t raw_data_size, + va_list va) { unsigned int bf_size; const char *guard; - guard = va_arg (va, const char *); - if (0 == strcmp (guard, - "seen-set-size")) - bf_size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size (va_arg (va, unsigned int), - BLOOMFILTER_K); - else if (0 == strcmp (guard, - "filter-size")) - bf_size = va_arg (va, unsigned int); + guard = va_arg(va, const char *); + if (0 == strcmp(guard, + "seen-set-size")) + bf_size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size(va_arg(va, unsigned int), + BLOOMFILTER_K); + else if (0 == strcmp(guard, + "filter-size")) + bf_size = va_arg(va, unsigned int); else - { - GNUNET_break (0); - bf_size = 8; - } - GNUNET_break (NULL == va_arg (va, const char *)); - return GNUNET_BLOCK_GROUP_bf_create (cls, - bf_size, - BLOOMFILTER_K, - type, - nonce, - raw_data, - raw_data_size); + { + GNUNET_break(0); + bf_size = 8; + } + GNUNET_break(NULL == va_arg(va, const char *)); + return GNUNET_BLOCK_GROUP_bf_create(cls, + bf_size, + BLOOMFILTER_K, + type, + nonce, + raw_data, + raw_data_size); } @@ -105,71 +105,72 @@ block_plugin_dns_create_group (void *cls, * @return characterization of result */ static enum GNUNET_BLOCK_EvaluationResult -block_plugin_dns_evaluate (void *cls, - struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *bg, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode * query, - const void *xquery, - size_t xquery_size, - const void *reply_block, - size_t reply_block_size) +block_plugin_dns_evaluate(void *cls, + struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *bg, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode * query, + const void *xquery, + size_t xquery_size, + const void *reply_block, + size_t reply_block_size) { const struct GNUNET_DNS_Advertisement *ad; struct GNUNET_HashCode phash; switch (type) - { - case GNUNET_BLOCK_TYPE_DNS: - if (0 != xquery_size) - return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; - - if (NULL == reply_block) - return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; - - if (sizeof (struct GNUNET_DNS_Advertisement) != reply_block_size) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; - } - ad = reply_block; - - if (ntohl (ad->purpose.size) != - sizeof (struct GNUNET_DNS_Advertisement) - - sizeof (struct GNUNET_CRYPTO_EddsaSignature)) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; - } - if (0 == - GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh - (ad->expiration_time)).rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "DNS advertisement has expired\n"); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; - } - if (GNUNET_OK != - GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_DNS_RECORD, - &ad->purpose, - &ad->signature, - &ad->peer.public_key)) { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + case GNUNET_BLOCK_TYPE_DNS: + if (0 != xquery_size) + return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; + + if (NULL == reply_block) + return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; + + if (sizeof(struct GNUNET_DNS_Advertisement) != reply_block_size) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } + ad = reply_block; + + if (ntohl(ad->purpose.size) != + sizeof(struct GNUNET_DNS_Advertisement) - + sizeof(struct GNUNET_CRYPTO_EddsaSignature)) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } + if (0 == + GNUNET_TIME_absolute_get_remaining(GNUNET_TIME_absolute_ntoh + (ad->expiration_time)).rel_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "DNS advertisement has expired\n"); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } + if (GNUNET_OK != + GNUNET_CRYPTO_eddsa_verify(GNUNET_SIGNATURE_PURPOSE_DNS_RECORD, + &ad->purpose, + &ad->signature, + &ad->peer.public_key)) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } + GNUNET_CRYPTO_hash(reply_block, + reply_block_size, + &phash); + if (GNUNET_YES == + GNUNET_BLOCK_GROUP_bf_test_and_set(bg, + &phash)) + return GNUNET_BLOCK_EVALUATION_OK_DUPLICATE; + return GNUNET_BLOCK_EVALUATION_OK_MORE; + + default: + return GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED; } - GNUNET_CRYPTO_hash (reply_block, - reply_block_size, - &phash); - if (GNUNET_YES == - GNUNET_BLOCK_GROUP_bf_test_and_set (bg, - &phash)) - return GNUNET_BLOCK_EVALUATION_OK_DUPLICATE; - return GNUNET_BLOCK_EVALUATION_OK_MORE; - default: - return GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED; - } } @@ -185,11 +186,11 @@ block_plugin_dns_evaluate (void *cls, * (or if extracting a key from a block of this type does not work) */ static int -block_plugin_dns_get_key (void *cls, - enum GNUNET_BLOCK_Type type, - const void *block, - size_t block_size, - struct GNUNET_HashCode *key) +block_plugin_dns_get_key(void *cls, + enum GNUNET_BLOCK_Type type, + const void *block, + size_t block_size, + struct GNUNET_HashCode *key) { /* we cannot extract a key from a block of this type */ return GNUNET_SYSERR; @@ -200,7 +201,7 @@ block_plugin_dns_get_key (void *cls, * Entry point for the plugin. */ void * -libgnunet_plugin_block_dns_init (void *cls) +libgnunet_plugin_block_dns_init(void *cls) { static enum GNUNET_BLOCK_Type types[] = { @@ -209,7 +210,7 @@ libgnunet_plugin_block_dns_init (void *cls) }; struct GNUNET_BLOCK_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_BLOCK_PluginFunctions); + api = GNUNET_new(struct GNUNET_BLOCK_PluginFunctions); api->evaluate = &block_plugin_dns_evaluate; api->get_key = &block_plugin_dns_get_key; api->create_group = &block_plugin_dns_create_group; @@ -222,11 +223,11 @@ libgnunet_plugin_block_dns_init (void *cls) * Exit point from the plugin. */ void * -libgnunet_plugin_block_dns_done (void *cls) +libgnunet_plugin_block_dns_done(void *cls) { struct GNUNET_BLOCK_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/exit/exit.h b/src/exit/exit.h index 6214c230a..be4f042b6 100644 --- a/src/exit/exit.h +++ b/src/exit/exit.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file exit/exit.h @@ -34,8 +34,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * Message send via cadet to an exit daemon to initiate forwarding of * TCP data to a local service. */ -struct GNUNET_EXIT_TcpServiceStartMessage -{ +struct GNUNET_EXIT_TcpServiceStartMessage { /** * Type is #GNUNET_MESSAGE_TYPE_VPN_TCP_TO_SERVICE_START */ @@ -60,8 +59,7 @@ struct GNUNET_EXIT_TcpServiceStartMessage * Message send via cadet to an exit daemon to initiate forwarding of * TCP data to the Internet. */ -struct GNUNET_EXIT_TcpInternetStartMessage -{ +struct GNUNET_EXIT_TcpInternetStartMessage { /** * Type is #GNUNET_MESSAGE_TYPE_VPN_TCP_TO_INTERNET_START */ @@ -91,8 +89,7 @@ struct GNUNET_EXIT_TcpInternetStartMessage * format is used for both Internet-exits and service-exits and * in both directions (VPN to exit and exit to VPN). */ -struct GNUNET_EXIT_TcpDataMessage -{ +struct GNUNET_EXIT_TcpDataMessage { /** * Type is #GNUNET_MESSAGE_TYPE_VPN_TCP_DATA */ @@ -117,8 +114,7 @@ struct GNUNET_EXIT_TcpDataMessage * Message send via cadet to an exit daemon to send * UDP data to a local service. */ -struct GNUNET_EXIT_UdpServiceMessage -{ +struct GNUNET_EXIT_UdpServiceMessage { /** * Type is #GNUNET_MESSAGE_TYPE_VPN_UDP_TO_SERVICE */ @@ -142,8 +138,7 @@ struct GNUNET_EXIT_UdpServiceMessage * Message send via cadet to an exit daemon to forward * UDP data to the Internet. */ -struct GNUNET_EXIT_UdpInternetMessage -{ +struct GNUNET_EXIT_UdpInternetMessage { /** * Type is #GNUNET_MESSAGE_TYPE_VPN_UDP_TO_INTERNET */ @@ -175,8 +170,7 @@ struct GNUNET_EXIT_UdpInternetMessage * Message send from exit daemon back to the UDP entry point * (used for both Internet and Service exit replies). */ -struct GNUNET_EXIT_UdpReplyMessage -{ +struct GNUNET_EXIT_UdpReplyMessage { /** * Type is #GNUNET_MESSAGE_TYPE_VPN_UDP_REPLY */ @@ -202,8 +196,7 @@ struct GNUNET_EXIT_UdpReplyMessage * Message send via cadet to an exit daemon to send * ICMP data to a local service. */ -struct GNUNET_EXIT_IcmpServiceMessage -{ +struct GNUNET_EXIT_IcmpServiceMessage { /** * Type is #GNUNET_MESSAGE_TYPE_VPN_ICMP_TO_SERVICE */ @@ -233,8 +226,7 @@ struct GNUNET_EXIT_IcmpServiceMessage * Message send via cadet to an exit daemon to forward * ICMP data to the Internet. */ -struct GNUNET_EXIT_IcmpInternetMessage -{ +struct GNUNET_EXIT_IcmpInternetMessage { /** * Type is #GNUNET_MESSAGE_TYPE_VPN_ICMP_TO_INTERNET */ @@ -268,8 +260,7 @@ struct GNUNET_EXIT_IcmpInternetMessage * Message send via cadet to the vpn service to send * ICMP data to the VPN's TUN interface. */ -struct GNUNET_EXIT_IcmpToVPNMessage -{ +struct GNUNET_EXIT_IcmpToVPNMessage { /** * Type is #GNUNET_MESSAGE_TYPE_VPN_ICMP_TO_VPN */ diff --git a/src/exit/gnunet-daemon-exit.c b/src/exit/gnunet-daemon-exit.c index 716a1ead0..f7cadbace 100644 --- a/src/exit/gnunet-daemon-exit.c +++ b/src/exit/gnunet-daemon-exit.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file exit/gnunet-daemon-exit.c @@ -66,31 +66,30 @@ /** * How frequently do we re-announce the regex for the exit? */ -#define REGEX_REFRESH_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 30) +#define REGEX_REFRESH_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 30) /** * How frequently do we re-announce the DNS exit in the DHT? */ -#define DHT_PUT_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define DHT_PUT_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) /** * How long do we typically sign the DNS exit advertisement for? */ -#define DNS_ADVERTISEMENT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 3) +#define DNS_ADVERTISEMENT_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_HOURS, 3) /** * Generic logging shorthand */ #define LOG(kind, ...) \ - GNUNET_log_from (kind, "exit", __VA_ARGS__); + GNUNET_log_from(kind, "exit", __VA_ARGS__); /** * Information about an address. */ -struct SocketAddress -{ +struct SocketAddress { /** * AF_INET or AF_INET6. */ @@ -99,8 +98,7 @@ struct SocketAddress /** * Remote address information. */ - union - { + union { /** * Address, if af is AF_INET. */ @@ -121,7 +119,6 @@ struct SocketAddress * Remote port, in host byte order! */ uint16_t port; - }; @@ -130,9 +127,7 @@ struct SocketAddress * a service this peer is specifically offering an exit for * (for a specific domain name). */ -struct LocalService -{ - +struct LocalService { /** * Remote address to use for the service. */ @@ -157,7 +152,6 @@ struct LocalService * #GNUNET_YES if this is a UDP service, otherwise TCP. */ int16_t is_udp; - }; @@ -166,9 +160,7 @@ struct LocalService * IP-version, protocol, source-IP, destination-IP, source-port and * destinatin-port. */ -struct RedirectInformation -{ - +struct RedirectInformation { /** * Address information for the other party (equivalent of the * arguments one would give to "connect"). @@ -190,7 +182,7 @@ struct RedirectInformation Note 2: we might also sometimes not match on all components of the tuple, to support protocols where things do not always fully map. - */ + */ }; @@ -200,8 +192,7 @@ struct RedirectInformation * with the channel's closure so we can find it again for the next * message from the channel. */ -struct ChannelState -{ +struct ChannelState { /** * Cadet channel that is used for this connection. */ @@ -220,11 +211,8 @@ struct ChannelState */ int is_dns; - union - { - struct - { - + union { + struct { /** * Heap node for this state in the connections_heap. */ @@ -246,9 +234,7 @@ struct ChannelState struct RedirectInformation ri; } tcp_udp; - struct - { - + struct { /** * Socket we are using to transmit this request (must match if we receive * a response). @@ -264,11 +250,8 @@ struct ChannelState * DNS request ID that we used for forwarding. */ uint16_t my_id; - } dns; - } specifics; - }; @@ -435,8 +418,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Message with a DNS response. */ -struct DnsResponseMessage -{ +struct DnsResponseMessage { /** * GNUnet header, of type #GNUNET_MESSAGE_TYPE_VPN_DNS_FROM_INTERNET */ @@ -462,35 +444,35 @@ GNUNET_NETWORK_STRUCT_END * @param r number of bytes in @a dns */ static void -process_dns_result (void *cls, - const struct GNUNET_TUN_DnsHeader *dns, - size_t r) +process_dns_result(void *cls, + const struct GNUNET_TUN_DnsHeader *dns, + size_t r) { struct ChannelState *ts; struct GNUNET_MQ_Envelope *env; struct DnsResponseMessage *resp; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Processing DNS result from stub resolver\n"); - GNUNET_assert (NULL == cls); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Processing DNS result from stub resolver\n"); + GNUNET_assert(NULL == cls); if (NULL == dns) return; /* Handle case that this is a reply to a request from a CADET DNS channel */ ts = channels[dns->id]; if (NULL == ts) return; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got a response from the stub resolver for DNS request received via CADET!\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got a response from the stub resolver for DNS request received via CADET!\n"); channels[dns->id] = NULL; - env = GNUNET_MQ_msg_extra (resp, - r - sizeof (struct GNUNET_TUN_DnsHeader), - GNUNET_MESSAGE_TYPE_VPN_DNS_FROM_INTERNET); - GNUNET_memcpy (&resp->dns, - dns, - r); + env = GNUNET_MQ_msg_extra(resp, + r - sizeof(struct GNUNET_TUN_DnsHeader), + GNUNET_MESSAGE_TYPE_VPN_DNS_FROM_INTERNET); + GNUNET_memcpy(&resp->dns, + dns, + r); resp->dns.id = ts->specifics.dns.original_id; - GNUNET_MQ_send (GNUNET_CADET_get_mq (ts->channel), - env); + GNUNET_MQ_send(GNUNET_CADET_get_mq(ts->channel), + env); } @@ -503,21 +485,21 @@ process_dns_result (void *cls, * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_dns_request (void *cls, - const struct DnsResponseMessage *msg) +check_dns_request(void *cls, + const struct DnsResponseMessage *msg) { struct ChannelState *ts = cls; if (NULL == dnsstub) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } if (GNUNET_NO == ts->is_dns) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -529,42 +511,42 @@ check_dns_request (void *cls, * @param msg the actual message */ static void -handle_dns_request (void *cls, - const struct DnsResponseMessage *msg) +handle_dns_request(void *cls, + const struct DnsResponseMessage *msg) { struct ChannelState *ts = cls; - size_t mlen = ntohs (msg->header.size); - size_t dlen = mlen - sizeof (struct GNUNET_MessageHeader); + size_t mlen = ntohs(msg->header.size); + size_t dlen = mlen - sizeof(struct GNUNET_MessageHeader); char buf[dlen] GNUNET_ALIGN; struct GNUNET_TUN_DnsHeader *dout; if (GNUNET_SYSERR == ts->is_dns) - { - /* channel is DNS from now on */ - ts->is_dns = GNUNET_YES; - } + { + /* channel is DNS from now on */ + ts->is_dns = GNUNET_YES; + } ts->specifics.dns.original_id = msg->dns.id; if (channels[ts->specifics.dns.my_id] == ts) channels[ts->specifics.dns.my_id] = NULL; - ts->specifics.dns.my_id = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT16_MAX + 1); + ts->specifics.dns.my_id = (uint16_t)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + UINT16_MAX + 1); channels[ts->specifics.dns.my_id] = ts; - GNUNET_memcpy (buf, - &msg->dns, - dlen); - dout = (struct GNUNET_TUN_DnsHeader *) buf; + GNUNET_memcpy(buf, + &msg->dns, + dlen); + dout = (struct GNUNET_TUN_DnsHeader *)buf; dout->id = ts->specifics.dns.my_id; - ts->specifics.dns.rs = GNUNET_DNSSTUB_resolve (dnsstub, - buf, - dlen, - &process_dns_result, - NULL); + ts->specifics.dns.rs = GNUNET_DNSSTUB_resolve(dnsstub, + buf, + dlen, + &process_dns_result, + NULL); if (NULL == ts->specifics.dns.rs) - { - GNUNET_break_op (0); - return; - } - GNUNET_CADET_receive_done (ts->channel); + { + GNUNET_break_op(0); + return; + } + GNUNET_CADET_receive_done(ts->channel); } @@ -576,62 +558,66 @@ handle_dns_request (void *cls, * @param ri information about the connection */ static void -hash_redirect_info (struct GNUNET_HashCode *hash, - const struct RedirectInformation *ri) +hash_redirect_info(struct GNUNET_HashCode *hash, + const struct RedirectInformation *ri) { char *off; - memset (hash, - 0, - sizeof (struct GNUNET_HashCode)); + memset(hash, + 0, + sizeof(struct GNUNET_HashCode)); /* the GNUnet hashmap only uses the first sizeof(unsigned int) of the hash, so we put the IP address in there (and hope for few collisions) */ - off = (char*) hash; + off = (char*)hash; switch (ri->remote_address.af) - { - case AF_INET: - GNUNET_memcpy (off, - &ri->remote_address.address.ipv4, - sizeof (struct in_addr)); - off += sizeof (struct in_addr); - break; - case AF_INET6: - GNUNET_memcpy (off, - &ri->remote_address.address.ipv6, - sizeof (struct in6_addr)); - off += sizeof (struct in_addr); - break; - default: - GNUNET_assert (0); - } - GNUNET_memcpy (off, - &ri->remote_address.port, - sizeof (uint16_t)); - off += sizeof (uint16_t); + { + case AF_INET: + GNUNET_memcpy(off, + &ri->remote_address.address.ipv4, + sizeof(struct in_addr)); + off += sizeof(struct in_addr); + break; + + case AF_INET6: + GNUNET_memcpy(off, + &ri->remote_address.address.ipv6, + sizeof(struct in6_addr)); + off += sizeof(struct in_addr); + break; + + default: + GNUNET_assert(0); + } + GNUNET_memcpy(off, + &ri->remote_address.port, + sizeof(uint16_t)); + off += sizeof(uint16_t); switch (ri->local_address.af) - { - case AF_INET: - GNUNET_memcpy (off, - &ri->local_address.address.ipv4, - sizeof (struct in_addr)); - off += sizeof (struct in_addr); - break; - case AF_INET6: - GNUNET_memcpy (off, - &ri->local_address.address.ipv6, - sizeof (struct in6_addr)); - off += sizeof (struct in_addr); - break; - default: - GNUNET_assert (0); - } - GNUNET_memcpy (off, - &ri->local_address.port, - sizeof (uint16_t)); - off += sizeof (uint16_t); - GNUNET_memcpy (off, - &ri->remote_address.proto, - sizeof (uint8_t)); + { + case AF_INET: + GNUNET_memcpy(off, + &ri->local_address.address.ipv4, + sizeof(struct in_addr)); + off += sizeof(struct in_addr); + break; + + case AF_INET6: + GNUNET_memcpy(off, + &ri->local_address.address.ipv6, + sizeof(struct in6_addr)); + off += sizeof(struct in_addr); + break; + + default: + GNUNET_assert(0); + } + GNUNET_memcpy(off, + &ri->local_address.port, + sizeof(uint16_t)); + off += sizeof(uint16_t); + GNUNET_memcpy(off, + &ri->remote_address.proto, + sizeof(uint8_t)); /* off += sizeof (uint8_t); */ } @@ -650,51 +636,51 @@ hash_redirect_info (struct GNUNET_HashCode *hash, * @return NULL if we have no tracking information for this tuple */ static struct ChannelState * -get_redirect_state (int af, - int protocol, - const void *destination_ip, - uint16_t destination_port, - const void *local_ip, - uint16_t local_port, - struct GNUNET_HashCode *state_key) +get_redirect_state(int af, + int protocol, + const void *destination_ip, + uint16_t destination_port, + const void *local_ip, + uint16_t local_port, + struct GNUNET_HashCode *state_key) { struct RedirectInformation ri; struct GNUNET_HashCode key; struct ChannelState *state; - if ( ( (af == AF_INET) && (protocol == IPPROTO_ICMP) ) || - ( (af == AF_INET6) && (protocol == IPPROTO_ICMPV6) ) ) - { - /* ignore ports */ - destination_port = 0; - local_port = 0; - } + if (((af == AF_INET) && (protocol == IPPROTO_ICMP)) || + ((af == AF_INET6) && (protocol == IPPROTO_ICMPV6))) + { + /* ignore ports */ + destination_port = 0; + local_port = 0; + } ri.remote_address.af = af; if (af == AF_INET) - ri.remote_address.address.ipv4 = *((struct in_addr*) destination_ip); + ri.remote_address.address.ipv4 = *((struct in_addr*)destination_ip); else - ri.remote_address.address.ipv6 = * ((struct in6_addr*) destination_ip); + ri.remote_address.address.ipv6 = *((struct in6_addr*)destination_ip); ri.remote_address.port = destination_port; ri.remote_address.proto = protocol; ri.local_address.af = af; if (af == AF_INET) - ri.local_address.address.ipv4 = *((struct in_addr*) local_ip); + ri.local_address.address.ipv4 = *((struct in_addr*)local_ip); else - ri.local_address.address.ipv6 = * ((struct in6_addr*) local_ip); + ri.local_address.address.ipv6 = *((struct in6_addr*)local_ip); ri.local_address.port = local_port; ri.local_address.proto = protocol; - hash_redirect_info (&key, - &ri); + hash_redirect_info(&key, + &ri); if (NULL != state_key) *state_key = key; - state = GNUNET_CONTAINER_multihashmap_get (connections_map, - &key); + state = GNUNET_CONTAINER_multihashmap_get(connections_map, + &key); if (NULL == state) return NULL; /* Mark this connection as freshly used */ if (NULL == state_key) - GNUNET_CONTAINER_heap_update_cost (state->specifics.tcp_udp.heap_node, - GNUNET_TIME_absolute_get ().abs_value_us); + GNUNET_CONTAINER_heap_update_cost(state->specifics.tcp_udp.heap_node, + GNUNET_TIME_absolute_get().abs_value_us); return state; } @@ -710,36 +696,36 @@ get_redirect_state (int af, * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_tcp_service (void *cls, - const struct GNUNET_EXIT_TcpServiceStartMessage *start) +check_tcp_service(void *cls, + const struct GNUNET_EXIT_TcpServiceStartMessage *start) { struct ChannelState *state = cls; if (NULL == state) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } if (GNUNET_YES == state->is_dns) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } if (NULL == state->specifics.tcp_udp.serv) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } if (NULL != state->specifics.tcp_udp.heap_node) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if (start->tcp_header.off * 4 < sizeof (struct GNUNET_TUN_TcpHeader)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if (start->tcp_header.off * 4 < sizeof(struct GNUNET_TUN_TcpHeader)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -763,82 +749,86 @@ check_tcp_service (void *cls, * AND the payload */ static void -prepare_ipv4_packet (const void *payload, - size_t payload_length, - int protocol, - const struct GNUNET_TUN_TcpHeader *tcp_header, - const struct SocketAddress *src_address, - const struct SocketAddress *dst_address, - struct GNUNET_TUN_IPv4Header *pkt4) +prepare_ipv4_packet(const void *payload, + size_t payload_length, + int protocol, + const struct GNUNET_TUN_TcpHeader *tcp_header, + const struct SocketAddress *src_address, + const struct SocketAddress *dst_address, + struct GNUNET_TUN_IPv4Header *pkt4) { size_t len; len = payload_length; switch (protocol) - { - case IPPROTO_UDP: - len += sizeof (struct GNUNET_TUN_UdpHeader); - break; - case IPPROTO_TCP: - len += sizeof (struct GNUNET_TUN_TcpHeader); - GNUNET_assert (NULL != tcp_header); - break; - default: - GNUNET_break (0); - return; - } - if (len + sizeof (struct GNUNET_TUN_IPv4Header) > UINT16_MAX) - { - GNUNET_break (0); - return; - } + { + case IPPROTO_UDP: + len += sizeof(struct GNUNET_TUN_UdpHeader); + break; - GNUNET_TUN_initialize_ipv4_header (pkt4, - protocol, - len, - &src_address->address.ipv4, - &dst_address->address.ipv4); - switch (protocol) - { - case IPPROTO_UDP: + case IPPROTO_TCP: + len += sizeof(struct GNUNET_TUN_TcpHeader); + GNUNET_assert(NULL != tcp_header); + break; + + default: + GNUNET_break(0); + return; + } + if (len + sizeof(struct GNUNET_TUN_IPv4Header) > UINT16_MAX) { - struct GNUNET_TUN_UdpHeader *pkt4_udp = (struct GNUNET_TUN_UdpHeader *) &pkt4[1]; + GNUNET_break(0); + return; + } - pkt4_udp->source_port = htons (src_address->port); - pkt4_udp->destination_port = htons (dst_address->port); - pkt4_udp->len = htons ((uint16_t) payload_length); - GNUNET_TUN_calculate_udp4_checksum (pkt4, - pkt4_udp, - payload, - payload_length); - GNUNET_memcpy (&pkt4_udp[1], - payload, - payload_length); + GNUNET_TUN_initialize_ipv4_header(pkt4, + protocol, + len, + &src_address->address.ipv4, + &dst_address->address.ipv4); + switch (protocol) + { + case IPPROTO_UDP: + { + struct GNUNET_TUN_UdpHeader *pkt4_udp = (struct GNUNET_TUN_UdpHeader *)&pkt4[1]; + + pkt4_udp->source_port = htons(src_address->port); + pkt4_udp->destination_port = htons(dst_address->port); + pkt4_udp->len = htons((uint16_t)payload_length); + GNUNET_TUN_calculate_udp4_checksum(pkt4, + pkt4_udp, + payload, + payload_length); + GNUNET_memcpy(&pkt4_udp[1], + payload, + payload_length); } break; - case IPPROTO_TCP: + + case IPPROTO_TCP: { - struct GNUNET_TUN_TcpHeader *pkt4_tcp = (struct GNUNET_TUN_TcpHeader *) &pkt4[1]; + struct GNUNET_TUN_TcpHeader *pkt4_tcp = (struct GNUNET_TUN_TcpHeader *)&pkt4[1]; *pkt4_tcp = *tcp_header; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending TCP packet from port %u to port %u\n", - src_address->port, - dst_address->port); - pkt4_tcp->source_port = htons (src_address->port); - pkt4_tcp->destination_port = htons (dst_address->port); - GNUNET_TUN_calculate_tcp4_checksum (pkt4, - pkt4_tcp, - payload, - payload_length); - GNUNET_memcpy (&pkt4_tcp[1], - payload, - payload_length); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending TCP packet from port %u to port %u\n", + src_address->port, + dst_address->port); + pkt4_tcp->source_port = htons(src_address->port); + pkt4_tcp->destination_port = htons(dst_address->port); + GNUNET_TUN_calculate_tcp4_checksum(pkt4, + pkt4_tcp, + payload, + payload_length); + GNUNET_memcpy(&pkt4_tcp[1], + payload, + payload_length); } break; - default: - GNUNET_assert (0); - } + + default: + GNUNET_assert(0); + } } @@ -861,80 +851,84 @@ prepare_ipv4_packet (const void *payload, * AND the payload */ static void -prepare_ipv6_packet (const void *payload, - size_t payload_length, - int protocol, - const struct GNUNET_TUN_TcpHeader *tcp_header, - const struct SocketAddress *src_address, - const struct SocketAddress *dst_address, - struct GNUNET_TUN_IPv6Header *pkt6) +prepare_ipv6_packet(const void *payload, + size_t payload_length, + int protocol, + const struct GNUNET_TUN_TcpHeader *tcp_header, + const struct SocketAddress *src_address, + const struct SocketAddress *dst_address, + struct GNUNET_TUN_IPv6Header *pkt6) { size_t len; len = payload_length; switch (protocol) - { - case IPPROTO_UDP: - len += sizeof (struct GNUNET_TUN_UdpHeader); - break; - case IPPROTO_TCP: - len += sizeof (struct GNUNET_TUN_TcpHeader); - break; - default: - GNUNET_break (0); - return; - } + { + case IPPROTO_UDP: + len += sizeof(struct GNUNET_TUN_UdpHeader); + break; + + case IPPROTO_TCP: + len += sizeof(struct GNUNET_TUN_TcpHeader); + break; + + default: + GNUNET_break(0); + return; + } if (len > UINT16_MAX) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } - GNUNET_TUN_initialize_ipv6_header (pkt6, - protocol, - len, - &src_address->address.ipv6, - &dst_address->address.ipv6); + GNUNET_TUN_initialize_ipv6_header(pkt6, + protocol, + len, + &src_address->address.ipv6, + &dst_address->address.ipv6); switch (protocol) - { - case IPPROTO_UDP: { - struct GNUNET_TUN_UdpHeader *pkt6_udp = (struct GNUNET_TUN_UdpHeader *) &pkt6[1]; - - pkt6_udp->source_port = htons (src_address->port); - pkt6_udp->destination_port = htons (dst_address->port); - pkt6_udp->len = htons ((uint16_t) payload_length); - GNUNET_TUN_calculate_udp6_checksum (pkt6, - pkt6_udp, - payload, - payload_length); - GNUNET_memcpy (&pkt6_udp[1], - payload, - payload_length); + case IPPROTO_UDP: + { + struct GNUNET_TUN_UdpHeader *pkt6_udp = (struct GNUNET_TUN_UdpHeader *)&pkt6[1]; + + pkt6_udp->source_port = htons(src_address->port); + pkt6_udp->destination_port = htons(dst_address->port); + pkt6_udp->len = htons((uint16_t)payload_length); + GNUNET_TUN_calculate_udp6_checksum(pkt6, + pkt6_udp, + payload, + payload_length); + GNUNET_memcpy(&pkt6_udp[1], + payload, + payload_length); } break; - case IPPROTO_TCP: + + case IPPROTO_TCP: { - struct GNUNET_TUN_TcpHeader *pkt6_tcp = (struct GNUNET_TUN_TcpHeader *) &pkt6[1]; + struct GNUNET_TUN_TcpHeader *pkt6_tcp = (struct GNUNET_TUN_TcpHeader *)&pkt6[1]; /* GNUNET_memcpy first here as some TCP header fields are initialized this way! */ *pkt6_tcp = *tcp_header; - pkt6_tcp->source_port = htons (src_address->port); - pkt6_tcp->destination_port = htons (dst_address->port); - GNUNET_TUN_calculate_tcp6_checksum (pkt6, - pkt6_tcp, - payload, - payload_length); - GNUNET_memcpy (&pkt6_tcp[1], - payload, - payload_length); + pkt6_tcp->source_port = htons(src_address->port); + pkt6_tcp->destination_port = htons(dst_address->port); + GNUNET_TUN_calculate_tcp6_checksum(pkt6, + pkt6_tcp, + payload, + payload_length); + GNUNET_memcpy(&pkt6_tcp[1], + payload, + payload_length); } break; - default: - GNUNET_assert (0); - break; - } + + default: + GNUNET_assert(0); + break; + } } @@ -948,93 +942,97 @@ prepare_ipv6_packet (const void *payload, * @param payload_length number of bytes in @a payload */ static void -send_tcp_packet_via_tun (const struct SocketAddress *destination_address, - const struct SocketAddress *source_address, - const struct GNUNET_TUN_TcpHeader *tcp_header, - const void *payload, - size_t payload_length) +send_tcp_packet_via_tun(const struct SocketAddress *destination_address, + const struct SocketAddress *source_address, + const struct GNUNET_TUN_TcpHeader *tcp_header, + const void *payload, + size_t payload_length) { size_t len; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# TCP packets sent via TUN"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending packet with %u bytes TCP payload via TUN\n", - (unsigned int) payload_length); - len = sizeof (struct GNUNET_MessageHeader) + sizeof (struct GNUNET_TUN_Layer2PacketHeader); + GNUNET_STATISTICS_update(stats, + gettext_noop("# TCP packets sent via TUN"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending packet with %u bytes TCP payload via TUN\n", + (unsigned int)payload_length); + len = sizeof(struct GNUNET_MessageHeader) + sizeof(struct GNUNET_TUN_Layer2PacketHeader); switch (source_address->af) - { - case AF_INET: - len += sizeof (struct GNUNET_TUN_IPv4Header); - break; - case AF_INET6: - len += sizeof (struct GNUNET_TUN_IPv6Header); - break; - default: - GNUNET_break (0); - return; - } - len += sizeof (struct GNUNET_TUN_TcpHeader); + { + case AF_INET: + len += sizeof(struct GNUNET_TUN_IPv4Header); + break; + + case AF_INET6: + len += sizeof(struct GNUNET_TUN_IPv6Header); + break; + + default: + GNUNET_break(0); + return; + } + len += sizeof(struct GNUNET_TUN_TcpHeader); len += payload_length; if (len >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } { char buf[len] GNUNET_ALIGN; struct GNUNET_MessageHeader *hdr; struct GNUNET_TUN_Layer2PacketHeader *tun; - hdr = (struct GNUNET_MessageHeader *) buf; - hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER); - hdr->size = htons (len); - tun = (struct GNUNET_TUN_Layer2PacketHeader*) &hdr[1]; - tun->flags = htons (0); + hdr = (struct GNUNET_MessageHeader *)buf; + hdr->type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER); + hdr->size = htons(len); + tun = (struct GNUNET_TUN_Layer2PacketHeader*)&hdr[1]; + tun->flags = htons(0); switch (source_address->af) - { - case AF_INET: { - struct GNUNET_TUN_IPv4Header *ipv4 - = (struct GNUNET_TUN_IPv4Header*) &tun[1]; - - tun->proto = htons (ETH_P_IPV4); - prepare_ipv4_packet (payload, - payload_length, - IPPROTO_TCP, - tcp_header, - source_address, - destination_address, - ipv4); + case AF_INET: + { + struct GNUNET_TUN_IPv4Header *ipv4 + = (struct GNUNET_TUN_IPv4Header*)&tun[1]; + + tun->proto = htons(ETH_P_IPV4); + prepare_ipv4_packet(payload, + payload_length, + IPPROTO_TCP, + tcp_header, + source_address, + destination_address, + ipv4); } break; - case AF_INET6: + + case AF_INET6: { - struct GNUNET_TUN_IPv6Header *ipv6 - = (struct GNUNET_TUN_IPv6Header*) &tun[1]; - - tun->proto = htons (ETH_P_IPV6); - prepare_ipv6_packet (payload, - payload_length, - IPPROTO_TCP, - tcp_header, - source_address, - destination_address, - ipv6); + struct GNUNET_TUN_IPv6Header *ipv6 + = (struct GNUNET_TUN_IPv6Header*)&tun[1]; + + tun->proto = htons(ETH_P_IPV6); + prepare_ipv6_packet(payload, + payload_length, + IPPROTO_TCP, + tcp_header, + source_address, + destination_address, + ipv6); } break; - default: - GNUNET_assert (0); - break; - } + + default: + GNUNET_assert(0); + break; + } if (NULL != helper_handle) - (void) GNUNET_HELPER_send (helper_handle, - (const struct GNUNET_MessageHeader*) buf, - GNUNET_YES, - NULL, - NULL); + (void)GNUNET_HELPER_send(helper_handle, + (const struct GNUNET_MessageHeader*)buf, + GNUNET_YES, + NULL, + NULL); } } @@ -1049,94 +1047,98 @@ send_tcp_packet_via_tun (const struct SocketAddress *destination_address, * @param payload_length number of bytes of data in @a payload */ static void -send_icmp_packet_via_tun (const struct SocketAddress *destination_address, - const struct SocketAddress *source_address, - const struct GNUNET_TUN_IcmpHeader *icmp_header, - const void *payload, size_t payload_length) +send_icmp_packet_via_tun(const struct SocketAddress *destination_address, + const struct SocketAddress *source_address, + const struct GNUNET_TUN_IcmpHeader *icmp_header, + const void *payload, size_t payload_length) { size_t len; struct GNUNET_TUN_IcmpHeader *icmp; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# ICMP packets sent via TUN"), - 1, GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending packet with %u bytes ICMP payload via TUN\n", - (unsigned int) payload_length); - len = sizeof (struct GNUNET_MessageHeader) + sizeof (struct GNUNET_TUN_Layer2PacketHeader); + GNUNET_STATISTICS_update(stats, + gettext_noop("# ICMP packets sent via TUN"), + 1, GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending packet with %u bytes ICMP payload via TUN\n", + (unsigned int)payload_length); + len = sizeof(struct GNUNET_MessageHeader) + sizeof(struct GNUNET_TUN_Layer2PacketHeader); switch (destination_address->af) - { - case AF_INET: - len += sizeof (struct GNUNET_TUN_IPv4Header); - break; - case AF_INET6: - len += sizeof (struct GNUNET_TUN_IPv6Header); - break; - default: - GNUNET_break (0); - return; - } - len += sizeof (struct GNUNET_TUN_IcmpHeader); + { + case AF_INET: + len += sizeof(struct GNUNET_TUN_IPv4Header); + break; + + case AF_INET6: + len += sizeof(struct GNUNET_TUN_IPv6Header); + break; + + default: + GNUNET_break(0); + return; + } + len += sizeof(struct GNUNET_TUN_IcmpHeader); len += payload_length; if (len >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } { char buf[len] GNUNET_ALIGN; struct GNUNET_MessageHeader *hdr; struct GNUNET_TUN_Layer2PacketHeader *tun; - hdr= (struct GNUNET_MessageHeader *) buf; - hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER); - hdr->size = htons (len); - tun = (struct GNUNET_TUN_Layer2PacketHeader*) &hdr[1]; - tun->flags = htons (0); + hdr = (struct GNUNET_MessageHeader *)buf; + hdr->type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER); + hdr->size = htons(len); + tun = (struct GNUNET_TUN_Layer2PacketHeader*)&hdr[1]; + tun->flags = htons(0); switch (source_address->af) - { - case AF_INET: { - struct GNUNET_TUN_IPv4Header * ipv4 = (struct GNUNET_TUN_IPv4Header*) &tun[1]; - - tun->proto = htons (ETH_P_IPV4); - GNUNET_TUN_initialize_ipv4_header (ipv4, - IPPROTO_ICMP, - sizeof (struct GNUNET_TUN_IcmpHeader) + payload_length, - &source_address->address.ipv4, - &destination_address->address.ipv4); - icmp = (struct GNUNET_TUN_IcmpHeader*) &ipv4[1]; + case AF_INET: + { + struct GNUNET_TUN_IPv4Header * ipv4 = (struct GNUNET_TUN_IPv4Header*)&tun[1]; + + tun->proto = htons(ETH_P_IPV4); + GNUNET_TUN_initialize_ipv4_header(ipv4, + IPPROTO_ICMP, + sizeof(struct GNUNET_TUN_IcmpHeader) + payload_length, + &source_address->address.ipv4, + &destination_address->address.ipv4); + icmp = (struct GNUNET_TUN_IcmpHeader*)&ipv4[1]; } break; - case AF_INET6: + + case AF_INET6: { - struct GNUNET_TUN_IPv6Header * ipv6 = (struct GNUNET_TUN_IPv6Header*) &tun[1]; - - tun->proto = htons (ETH_P_IPV6); - GNUNET_TUN_initialize_ipv6_header (ipv6, - IPPROTO_ICMPV6, - sizeof (struct GNUNET_TUN_IcmpHeader) + payload_length, - &source_address->address.ipv6, - &destination_address->address.ipv6); - icmp = (struct GNUNET_TUN_IcmpHeader*) &ipv6[1]; + struct GNUNET_TUN_IPv6Header * ipv6 = (struct GNUNET_TUN_IPv6Header*)&tun[1]; + + tun->proto = htons(ETH_P_IPV6); + GNUNET_TUN_initialize_ipv6_header(ipv6, + IPPROTO_ICMPV6, + sizeof(struct GNUNET_TUN_IcmpHeader) + payload_length, + &source_address->address.ipv6, + &destination_address->address.ipv6); + icmp = (struct GNUNET_TUN_IcmpHeader*)&ipv6[1]; } break; - default: - GNUNET_assert (0); - break; - } + + default: + GNUNET_assert(0); + break; + } *icmp = *icmp_header; - GNUNET_memcpy (&icmp[1], - payload, - payload_length); - GNUNET_TUN_calculate_icmp_checksum (icmp, - payload, - payload_length); + GNUNET_memcpy(&icmp[1], + payload, + payload_length); + GNUNET_TUN_calculate_icmp_checksum(icmp, + payload, + payload_length); if (NULL != helper_handle) - (void) GNUNET_HELPER_send (helper_handle, - (const struct GNUNET_MessageHeader*) buf, - GNUNET_YES, - NULL, NULL); + (void)GNUNET_HELPER_send(helper_handle, + (const struct GNUNET_MessageHeader*)buf, + GNUNET_YES, + NULL, NULL); } } @@ -1150,24 +1152,24 @@ send_icmp_packet_via_tun (const struct SocketAddress *destination_address, * @param local_address address to initialize */ static void -setup_fresh_address (int af, - uint8_t proto, - struct SocketAddress *local_address) +setup_fresh_address(int af, + uint8_t proto, + struct SocketAddress *local_address) { local_address->af = af; - local_address->proto = (uint8_t) proto; + local_address->proto = (uint8_t)proto; /* default "local" port range is often 32768--61000, so we pick a random value in that range */ - if ( ( (af == AF_INET) && (proto == IPPROTO_ICMP) ) || - ( (af == AF_INET6) && (proto == IPPROTO_ICMPV6) ) ) + if (((af == AF_INET) && (proto == IPPROTO_ICMP)) || + ((af == AF_INET6) && (proto == IPPROTO_ICMPV6))) local_address->port = 0; else local_address->port - = (uint16_t) 32768 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - 28232); + = (uint16_t)32768 + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + 28232); switch (af) - { - case AF_INET: + { + case AF_INET: { struct in_addr addr; struct in_addr mask; @@ -1176,26 +1178,27 @@ setup_fresh_address (int af, addr = exit_ipv4addr; mask = exit_ipv4mask; if (0 == ~mask.s_addr) - { - /* only one valid IP anyway */ - local_address->address.ipv4 = addr; - return; - } + { + /* only one valid IP anyway */ + local_address->address.ipv4 = addr; + return; + } /* Given 192.168.0.1/255.255.0.0, we want a mask - of '192.168.255.255', thus: */ + of '192.168.255.255', thus: */ mask.s_addr = addr.s_addr | ~mask.s_addr; /* Pick random IPv4 address within the subnet, except 'addr' or 'mask' itself */ do - { - rnd.s_addr = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT32_MAX); - local_address->address.ipv4.s_addr = (addr.s_addr | rnd.s_addr) & mask.s_addr; - } - while ( (local_address->address.ipv4.s_addr == addr.s_addr) || - (local_address->address.ipv4.s_addr == mask.s_addr) ); + { + rnd.s_addr = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + UINT32_MAX); + local_address->address.ipv4.s_addr = (addr.s_addr | rnd.s_addr) & mask.s_addr; + } + while ((local_address->address.ipv4.s_addr == addr.s_addr) || + (local_address->address.ipv4.s_addr == mask.s_addr)); } break; - case AF_INET6: + + case AF_INET6: { struct in6_addr addr; struct in6_addr mask; @@ -1203,39 +1206,40 @@ setup_fresh_address (int af, int i; addr = exit_ipv6addr; - GNUNET_assert (ipv6prefix < 128); + GNUNET_assert(ipv6prefix < 128); if (ipv6prefix == 127) - { - /* only one valid IP anyway */ - local_address->address.ipv6 = addr; - return; - } + { + /* only one valid IP anyway */ + local_address->address.ipv6 = addr; + return; + } /* Given ABCD::/96, we want a mask of 'ABCD::FFFF:FFFF, - thus: */ + thus: */ mask = addr; - for (i=127;i>=ipv6prefix;i--) - mask.s6_addr[i / 8] |= (1 << (i % 8)); + for (i = 127; i >= ipv6prefix; i--) + mask.s6_addr[i / 8] |= (1 << (i % 8)); /* Pick random IPv6 address within the subnet, except 'addr' or 'mask' itself */ do - { - for (i=0;i<16;i++) - { - rnd.s6_addr[i] = (unsigned char) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - 256); - local_address->address.ipv6.s6_addr[i] - = (addr.s6_addr[i] | rnd.s6_addr[i]) & mask.s6_addr[i]; - } - } - while ( (0 == GNUNET_memcmp (&local_address->address.ipv6, - &addr)) || - (0 == GNUNET_memcmp (&local_address->address.ipv6, - &mask)) ); + { + for (i = 0; i < 16; i++) + { + rnd.s6_addr[i] = (unsigned char)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + 256); + local_address->address.ipv6.s6_addr[i] + = (addr.s6_addr[i] | rnd.s6_addr[i]) & mask.s6_addr[i]; + } + } + while ((0 == GNUNET_memcmp(&local_address->address.ipv6, + &addr)) || + (0 == GNUNET_memcmp(&local_address->address.ipv6, + &mask))); } break; - default: - GNUNET_assert (0); - } + + default: + GNUNET_assert(0); + } } @@ -1261,61 +1265,62 @@ setup_fresh_address (int af, * used to test if a state has been fully setup). */ static void -setup_state_record (struct ChannelState *state) +setup_state_record(struct ChannelState *state) { struct GNUNET_HashCode key; struct ChannelState *s; /* generate fresh, unique address */ do - { - if (NULL == state->specifics.tcp_udp.serv) - setup_fresh_address (state->specifics.tcp_udp.ri.remote_address.af, - state->specifics.tcp_udp.ri.remote_address.proto, - &state->specifics.tcp_udp.ri.local_address); - else - setup_fresh_address (state->specifics.tcp_udp.serv->address.af, - state->specifics.tcp_udp.serv->address.proto, - &state->specifics.tcp_udp.ri.local_address); - } while (NULL != - get_redirect_state (state->specifics.tcp_udp.ri.remote_address.af, - state->specifics.tcp_udp.ri.remote_address.proto, - &state->specifics.tcp_udp.ri.remote_address.address, - state->specifics.tcp_udp.ri.remote_address.port, - &state->specifics.tcp_udp.ri.local_address.address, - state->specifics.tcp_udp.ri.local_address.port, - &key)); + { + if (NULL == state->specifics.tcp_udp.serv) + setup_fresh_address(state->specifics.tcp_udp.ri.remote_address.af, + state->specifics.tcp_udp.ri.remote_address.proto, + &state->specifics.tcp_udp.ri.local_address); + else + setup_fresh_address(state->specifics.tcp_udp.serv->address.af, + state->specifics.tcp_udp.serv->address.proto, + &state->specifics.tcp_udp.ri.local_address); + } + while (NULL != + get_redirect_state(state->specifics.tcp_udp.ri.remote_address.af, + state->specifics.tcp_udp.ri.remote_address.proto, + &state->specifics.tcp_udp.ri.remote_address.address, + state->specifics.tcp_udp.ri.remote_address.port, + &state->specifics.tcp_udp.ri.local_address.address, + state->specifics.tcp_udp.ri.local_address.port, + &key)); { char buf[INET6_ADDRSTRLEN]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Picked local address %s:%u for new connection\n", - inet_ntop (state->specifics.tcp_udp.ri.local_address.af, - &state->specifics.tcp_udp.ri.local_address.address, - buf, - sizeof (buf)), - (unsigned int) state->specifics.tcp_udp.ri.local_address.port); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Picked local address %s:%u for new connection\n", + inet_ntop(state->specifics.tcp_udp.ri.local_address.af, + &state->specifics.tcp_udp.ri.local_address.address, + buf, + sizeof(buf)), + (unsigned int)state->specifics.tcp_udp.ri.local_address.port); } state->specifics.tcp_udp.state_key = key; - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (connections_map, - &key, state, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(connections_map, + &key, state, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); state->specifics.tcp_udp.heap_node - = GNUNET_CONTAINER_heap_insert (connections_heap, - state, - GNUNET_TIME_absolute_get ().abs_value_us); - while (GNUNET_CONTAINER_heap_get_size (connections_heap) > max_connections) - { - s = GNUNET_CONTAINER_heap_remove_root (connections_heap); - GNUNET_assert (state != s); - s->specifics.tcp_udp.heap_node = NULL; - GNUNET_CADET_channel_destroy (s->channel); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_remove (connections_map, - &s->specifics.tcp_udp.state_key, - s)); - GNUNET_free (s); - } + = GNUNET_CONTAINER_heap_insert(connections_heap, + state, + GNUNET_TIME_absolute_get().abs_value_us); + while (GNUNET_CONTAINER_heap_get_size(connections_heap) > max_connections) + { + s = GNUNET_CONTAINER_heap_remove_root(connections_heap); + GNUNET_assert(state != s); + s->specifics.tcp_udp.heap_node = NULL; + GNUNET_CADET_channel_destroy(s->channel); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_remove(connections_map, + &s->specifics.tcp_udp.state_key, + s)); + GNUNET_free(s); + } } @@ -1328,87 +1333,91 @@ setup_state_record (struct ChannelState *state) * @param payload_length number of bytes of data in @a payload */ static void -send_udp_packet_via_tun (const struct SocketAddress *destination_address, - const struct SocketAddress *source_address, - const void *payload, size_t payload_length) +send_udp_packet_via_tun(const struct SocketAddress *destination_address, + const struct SocketAddress *source_address, + const void *payload, size_t payload_length) { size_t len; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# UDP packets sent via TUN"), - 1, GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending packet with %u bytes UDP payload via TUN\n", - (unsigned int) payload_length); - len = sizeof (struct GNUNET_MessageHeader) + sizeof (struct GNUNET_TUN_Layer2PacketHeader); + GNUNET_STATISTICS_update(stats, + gettext_noop("# UDP packets sent via TUN"), + 1, GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending packet with %u bytes UDP payload via TUN\n", + (unsigned int)payload_length); + len = sizeof(struct GNUNET_MessageHeader) + sizeof(struct GNUNET_TUN_Layer2PacketHeader); switch (source_address->af) - { - case AF_INET: - len += sizeof (struct GNUNET_TUN_IPv4Header); - break; - case AF_INET6: - len += sizeof (struct GNUNET_TUN_IPv6Header); - break; - default: - GNUNET_break (0); - return; - } - len += sizeof (struct GNUNET_TUN_UdpHeader); - len += payload_length; - if (len >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return; - } - { + { + case AF_INET: + len += sizeof(struct GNUNET_TUN_IPv4Header); + break; + + case AF_INET6: + len += sizeof(struct GNUNET_TUN_IPv6Header); + break; + + default: + GNUNET_break(0); + return; + } + len += sizeof(struct GNUNET_TUN_UdpHeader); + len += payload_length; + if (len >= GNUNET_MAX_MESSAGE_SIZE) + { + GNUNET_break(0); + return; + } + { char buf[len] GNUNET_ALIGN; struct GNUNET_MessageHeader *hdr; struct GNUNET_TUN_Layer2PacketHeader *tun; - hdr= (struct GNUNET_MessageHeader *) buf; - hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER); - hdr->size = htons (len); - tun = (struct GNUNET_TUN_Layer2PacketHeader*) &hdr[1]; - tun->flags = htons (0); + hdr = (struct GNUNET_MessageHeader *)buf; + hdr->type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER); + hdr->size = htons(len); + tun = (struct GNUNET_TUN_Layer2PacketHeader*)&hdr[1]; + tun->flags = htons(0); switch (source_address->af) - { - case AF_INET: { - struct GNUNET_TUN_IPv4Header * ipv4 = (struct GNUNET_TUN_IPv4Header*) &tun[1]; - - tun->proto = htons (ETH_P_IPV4); - prepare_ipv4_packet (payload, - payload_length, - IPPROTO_UDP, - NULL, - source_address, - destination_address, - ipv4); + case AF_INET: + { + struct GNUNET_TUN_IPv4Header * ipv4 = (struct GNUNET_TUN_IPv4Header*)&tun[1]; + + tun->proto = htons(ETH_P_IPV4); + prepare_ipv4_packet(payload, + payload_length, + IPPROTO_UDP, + NULL, + source_address, + destination_address, + ipv4); } break; - case AF_INET6: + + case AF_INET6: { - struct GNUNET_TUN_IPv6Header * ipv6 = (struct GNUNET_TUN_IPv6Header*) &tun[1]; - - tun->proto = htons (ETH_P_IPV6); - prepare_ipv6_packet (payload, - payload_length, - IPPROTO_UDP, - NULL, - source_address, - destination_address, - ipv6); + struct GNUNET_TUN_IPv6Header * ipv6 = (struct GNUNET_TUN_IPv6Header*)&tun[1]; + + tun->proto = htons(ETH_P_IPV6); + prepare_ipv6_packet(payload, + payload_length, + IPPROTO_UDP, + NULL, + source_address, + destination_address, + ipv6); } break; - default: - GNUNET_assert (0); - break; - } + + default: + GNUNET_assert(0); + break; + } if (NULL != helper_handle) - (void) GNUNET_HELPER_send (helper_handle, - (const struct GNUNET_MessageHeader*) buf, - GNUNET_YES, - NULL, NULL); + (void)GNUNET_HELPER_send(helper_handle, + (const struct GNUNET_MessageHeader*)buf, + GNUNET_YES, + NULL, NULL); } } @@ -1422,16 +1431,16 @@ send_udp_packet_via_tun (const struct SocketAddress *destination_address, * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_udp_remote (void *cls, - const struct GNUNET_EXIT_UdpInternetMessage *msg) +check_udp_remote(void *cls, + const struct GNUNET_EXIT_UdpInternetMessage *msg) { struct ChannelState *state = cls; if (GNUNET_YES == state->is_dns) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1443,88 +1452,90 @@ check_udp_remote (void *cls, * @param msg the actual message */ static void -handle_udp_remote (void *cls, - const struct GNUNET_EXIT_UdpInternetMessage *msg) +handle_udp_remote(void *cls, + const struct GNUNET_EXIT_UdpInternetMessage *msg) { struct ChannelState *state = cls; - uint16_t pkt_len = ntohs (msg->header.size) - sizeof (struct GNUNET_EXIT_UdpInternetMessage); + uint16_t pkt_len = ntohs(msg->header.size) - sizeof(struct GNUNET_EXIT_UdpInternetMessage); const struct in_addr *v4; const struct in6_addr *v6; const void *payload; int af; if (GNUNET_SYSERR == state->is_dns) - { - /* channel is UDP/TCP from now on */ - state->is_dns = GNUNET_NO; - } - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Bytes received from CADET"), - pkt_len, GNUNET_NO); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# UDP IP-exit requests received via cadet"), - 1, GNUNET_NO); - af = (int) ntohl (msg->af); - state->specifics.tcp_udp.ri.remote_address.af = af; - switch (af) - { - case AF_INET: - if (pkt_len < sizeof (struct in_addr)) - { - GNUNET_break_op (0); - return; - } - if (! ipv4_exit) - { - GNUNET_break_op (0); - return; - } - v4 = (const struct in_addr*) &msg[1]; - payload = &v4[1]; - pkt_len -= sizeof (struct in_addr); - state->specifics.tcp_udp.ri.remote_address.address.ipv4 = *v4; - break; - case AF_INET6: - if (pkt_len < sizeof (struct in6_addr)) { - GNUNET_break_op (0); - return; + /* channel is UDP/TCP from now on */ + state->is_dns = GNUNET_NO; } - if (! ipv6_exit) + GNUNET_STATISTICS_update(stats, + gettext_noop("# Bytes received from CADET"), + pkt_len, GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# UDP IP-exit requests received via cadet"), + 1, GNUNET_NO); + af = (int)ntohl(msg->af); + state->specifics.tcp_udp.ri.remote_address.af = af; + switch (af) { - GNUNET_break_op (0); + case AF_INET: + if (pkt_len < sizeof(struct in_addr)) + { + GNUNET_break_op(0); + return; + } + if (!ipv4_exit) + { + GNUNET_break_op(0); + return; + } + v4 = (const struct in_addr*)&msg[1]; + payload = &v4[1]; + pkt_len -= sizeof(struct in_addr); + state->specifics.tcp_udp.ri.remote_address.address.ipv4 = *v4; + break; + + case AF_INET6: + if (pkt_len < sizeof(struct in6_addr)) + { + GNUNET_break_op(0); + return; + } + if (!ipv6_exit) + { + GNUNET_break_op(0); + return; + } + v6 = (const struct in6_addr*)&msg[1]; + payload = &v6[1]; + pkt_len -= sizeof(struct in6_addr); + state->specifics.tcp_udp.ri.remote_address.address.ipv6 = *v6; + break; + + default: + GNUNET_break_op(0); return; } - v6 = (const struct in6_addr*) &msg[1]; - payload = &v6[1]; - pkt_len -= sizeof (struct in6_addr); - state->specifics.tcp_udp.ri.remote_address.address.ipv6 = *v6; - break; - default: - GNUNET_break_op (0); - return; - } { char buf[INET6_ADDRSTRLEN]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received data from %s for forwarding to UDP %s:%u\n", - GNUNET_i2s (&state->peer), - inet_ntop (af, - &state->specifics.tcp_udp.ri.remote_address.address, - buf, sizeof (buf)), - (unsigned int) ntohs (msg->destination_port)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received data from %s for forwarding to UDP %s:%u\n", + GNUNET_i2s(&state->peer), + inet_ntop(af, + &state->specifics.tcp_udp.ri.remote_address.address, + buf, sizeof(buf)), + (unsigned int)ntohs(msg->destination_port)); } state->specifics.tcp_udp.ri.remote_address.proto = IPPROTO_UDP; state->specifics.tcp_udp.ri.remote_address.port = msg->destination_port; if (NULL == state->specifics.tcp_udp.heap_node) - setup_state_record (state); - if (0 != ntohs (msg->source_port)) + setup_state_record(state); + if (0 != ntohs(msg->source_port)) state->specifics.tcp_udp.ri.local_address.port = msg->source_port; - send_udp_packet_via_tun (&state->specifics.tcp_udp.ri.remote_address, - &state->specifics.tcp_udp.ri.local_address, - payload, - pkt_len); - GNUNET_CADET_receive_done (state->channel); + send_udp_packet_via_tun(&state->specifics.tcp_udp.ri.remote_address, + &state->specifics.tcp_udp.ri.local_address, + payload, + pkt_len); + GNUNET_CADET_receive_done(state->channel); } @@ -1538,16 +1549,16 @@ handle_udp_remote (void *cls, * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_udp_service (void *cls, - const struct GNUNET_EXIT_UdpServiceMessage *msg) +check_udp_service(void *cls, + const struct GNUNET_EXIT_UdpServiceMessage *msg) { struct ChannelState *state = cls; if (NULL == state->specifics.tcp_udp.serv) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1560,31 +1571,31 @@ check_udp_service (void *cls, * @param msg the actual message */ static void -handle_udp_service (void *cls, - const struct GNUNET_EXIT_UdpServiceMessage *msg) +handle_udp_service(void *cls, + const struct GNUNET_EXIT_UdpServiceMessage *msg) { struct ChannelState *state = cls; - uint16_t pkt_len = ntohs (msg->header.size) - sizeof (struct GNUNET_EXIT_UdpServiceMessage); - - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Bytes received from CADET"), - pkt_len, GNUNET_NO); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# UDP service requests received via cadet"), - 1, GNUNET_NO); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received data from %s for forwarding to UDP service %s on port %u\n", - GNUNET_i2s (&state->peer), - GNUNET_h2s (&state->specifics.tcp_udp.serv->descriptor), - (unsigned int) ntohs (msg->destination_port)); - setup_state_record (state); - if (0 != ntohs (msg->source_port)) + uint16_t pkt_len = ntohs(msg->header.size) - sizeof(struct GNUNET_EXIT_UdpServiceMessage); + + GNUNET_STATISTICS_update(stats, + gettext_noop("# Bytes received from CADET"), + pkt_len, GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# UDP service requests received via cadet"), + 1, GNUNET_NO); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received data from %s for forwarding to UDP service %s on port %u\n", + GNUNET_i2s(&state->peer), + GNUNET_h2s(&state->specifics.tcp_udp.serv->descriptor), + (unsigned int)ntohs(msg->destination_port)); + setup_state_record(state); + if (0 != ntohs(msg->source_port)) state->specifics.tcp_udp.ri.local_address.port = msg->source_port; - send_udp_packet_via_tun (&state->specifics.tcp_udp.ri.remote_address, - &state->specifics.tcp_udp.ri.local_address, - &msg[1], - pkt_len); - GNUNET_CADET_receive_done (state->channel); + send_udp_packet_via_tun(&state->specifics.tcp_udp.ri.remote_address, + &state->specifics.tcp_udp.ri.local_address, + &msg[1], + pkt_len); + GNUNET_CADET_receive_done(state->channel); } @@ -1598,39 +1609,39 @@ handle_udp_service (void *cls, * #GNUNET_SYSERR to close it (signal serious error) */ static void -handle_tcp_service (void *cls, - const struct GNUNET_EXIT_TcpServiceStartMessage *start) +handle_tcp_service(void *cls, + const struct GNUNET_EXIT_TcpServiceStartMessage *start) { struct ChannelState *state = cls; - uint16_t pkt_len = ntohs (start->header.size) - sizeof (struct GNUNET_EXIT_TcpServiceStartMessage); + uint16_t pkt_len = ntohs(start->header.size) - sizeof(struct GNUNET_EXIT_TcpServiceStartMessage); if (GNUNET_SYSERR == state->is_dns) - { - /* channel is UDP/TCP from now on */ - state->is_dns = GNUNET_NO; - } - GNUNET_STATISTICS_update (stats, - gettext_noop ("# TCP service creation requests received via cadet"), - 1, - GNUNET_NO); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Bytes received from CADET"), - pkt_len, - GNUNET_NO); - GNUNET_break_op (ntohl (start->reserved) == 0); + { + /* channel is UDP/TCP from now on */ + state->is_dns = GNUNET_NO; + } + GNUNET_STATISTICS_update(stats, + gettext_noop("# TCP service creation requests received via cadet"), + 1, + GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# Bytes received from CADET"), + pkt_len, + GNUNET_NO); + GNUNET_break_op(ntohl(start->reserved) == 0); /* setup fresh connection */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received data from %s for forwarding to TCP service %s on port %u\n", - GNUNET_i2s (&state->peer), - GNUNET_h2s (&state->specifics.tcp_udp.serv->descriptor), - (unsigned int) ntohs (start->tcp_header.destination_port)); - setup_state_record (state); - send_tcp_packet_via_tun (&state->specifics.tcp_udp.ri.remote_address, - &state->specifics.tcp_udp.ri.local_address, - &start->tcp_header, - &start[1], - pkt_len); - GNUNET_CADET_receive_done (state->channel); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received data from %s for forwarding to TCP service %s on port %u\n", + GNUNET_i2s(&state->peer), + GNUNET_h2s(&state->specifics.tcp_udp.serv->descriptor), + (unsigned int)ntohs(start->tcp_header.destination_port)); + setup_state_record(state); + send_tcp_packet_via_tun(&state->specifics.tcp_udp.ri.remote_address, + &state->specifics.tcp_udp.ri.local_address, + &start->tcp_header, + &start[1], + pkt_len); + GNUNET_CADET_receive_done(state->channel); } @@ -1643,32 +1654,32 @@ handle_tcp_service (void *cls, * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_tcp_remote (void *cls, - const struct GNUNET_EXIT_TcpInternetStartMessage *start) +check_tcp_remote(void *cls, + const struct GNUNET_EXIT_TcpInternetStartMessage *start) { struct ChannelState *state = cls; if (NULL == state) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } if (GNUNET_YES == state->is_dns) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if ( (NULL != state->specifics.tcp_udp.serv) || - (NULL != state->specifics.tcp_udp.heap_node) ) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if (start->tcp_header.off * 4 < sizeof (struct GNUNET_TUN_TcpHeader)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if ((NULL != state->specifics.tcp_udp.serv) || + (NULL != state->specifics.tcp_udp.heap_node)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if (start->tcp_header.off * 4 < sizeof(struct GNUNET_TUN_TcpHeader)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1680,86 +1691,88 @@ check_tcp_remote (void *cls, * @param start the actual message */ static void -handle_tcp_remote (void *cls, - const struct GNUNET_EXIT_TcpInternetStartMessage *start) +handle_tcp_remote(void *cls, + const struct GNUNET_EXIT_TcpInternetStartMessage *start) { struct ChannelState *state = cls; - uint16_t pkt_len = ntohs (start->header.size) - sizeof (struct GNUNET_EXIT_TcpInternetStartMessage); + uint16_t pkt_len = ntohs(start->header.size) - sizeof(struct GNUNET_EXIT_TcpInternetStartMessage); const struct in_addr *v4; const struct in6_addr *v6; const void *payload; int af; if (GNUNET_SYSERR == state->is_dns) - { - /* channel is UDP/TCP from now on */ - state->is_dns = GNUNET_NO; - } - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Bytes received from CADET"), - pkt_len, GNUNET_NO); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# TCP IP-exit creation requests received via cadet"), - 1, GNUNET_NO); - af = (int) ntohl (start->af); - state->specifics.tcp_udp.ri.remote_address.af = af; - switch (af) - { - case AF_INET: - if (pkt_len < sizeof (struct in_addr)) - { - GNUNET_break_op (0); - return; - } - if (! ipv4_exit) { - GNUNET_break_op (0); - return; - } - v4 = (const struct in_addr*) &start[1]; - payload = &v4[1]; - pkt_len -= sizeof (struct in_addr); - state->specifics.tcp_udp.ri.remote_address.address.ipv4 = *v4; - break; - case AF_INET6: - if (pkt_len < sizeof (struct in6_addr)) - { - GNUNET_break_op (0); - return; + /* channel is UDP/TCP from now on */ + state->is_dns = GNUNET_NO; } - if (! ipv6_exit) + GNUNET_STATISTICS_update(stats, + gettext_noop("# Bytes received from CADET"), + pkt_len, GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# TCP IP-exit creation requests received via cadet"), + 1, GNUNET_NO); + af = (int)ntohl(start->af); + state->specifics.tcp_udp.ri.remote_address.af = af; + switch (af) { - GNUNET_break_op (0); + case AF_INET: + if (pkt_len < sizeof(struct in_addr)) + { + GNUNET_break_op(0); + return; + } + if (!ipv4_exit) + { + GNUNET_break_op(0); + return; + } + v4 = (const struct in_addr*)&start[1]; + payload = &v4[1]; + pkt_len -= sizeof(struct in_addr); + state->specifics.tcp_udp.ri.remote_address.address.ipv4 = *v4; + break; + + case AF_INET6: + if (pkt_len < sizeof(struct in6_addr)) + { + GNUNET_break_op(0); + return; + } + if (!ipv6_exit) + { + GNUNET_break_op(0); + return; + } + v6 = (const struct in6_addr*)&start[1]; + payload = &v6[1]; + pkt_len -= sizeof(struct in6_addr); + state->specifics.tcp_udp.ri.remote_address.address.ipv6 = *v6; + break; + + default: + GNUNET_break_op(0); return; } - v6 = (const struct in6_addr*) &start[1]; - payload = &v6[1]; - pkt_len -= sizeof (struct in6_addr); - state->specifics.tcp_udp.ri.remote_address.address.ipv6 = *v6; - break; - default: - GNUNET_break_op (0); - return; - } { char buf[INET6_ADDRSTRLEN]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received payload from %s for existing TCP stream to %s:%u\n", - GNUNET_i2s (&state->peer), - inet_ntop (af, - &state->specifics.tcp_udp.ri.remote_address.address, - buf, sizeof (buf)), - (unsigned int) ntohs (start->tcp_header.destination_port)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received payload from %s for existing TCP stream to %s:%u\n", + GNUNET_i2s(&state->peer), + inet_ntop(af, + &state->specifics.tcp_udp.ri.remote_address.address, + buf, sizeof(buf)), + (unsigned int)ntohs(start->tcp_header.destination_port)); } state->specifics.tcp_udp.ri.remote_address.proto = IPPROTO_TCP; - state->specifics.tcp_udp.ri.remote_address.port = ntohs (start->tcp_header.destination_port); - setup_state_record (state); - send_tcp_packet_via_tun (&state->specifics.tcp_udp.ri.remote_address, - &state->specifics.tcp_udp.ri.local_address, - &start->tcp_header, - payload, - pkt_len); - GNUNET_CADET_receive_done (state->channel); + state->specifics.tcp_udp.ri.remote_address.port = ntohs(start->tcp_header.destination_port); + setup_state_record(state); + send_tcp_packet_via_tun(&state->specifics.tcp_udp.ri.remote_address, + &state->specifics.tcp_udp.ri.local_address, + &start->tcp_header, + payload, + pkt_len); + GNUNET_CADET_receive_done(state->channel); } @@ -1773,31 +1786,31 @@ handle_tcp_remote (void *cls, * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_tcp_data (void *cls, - const struct GNUNET_EXIT_TcpDataMessage *data) +check_tcp_data(void *cls, + const struct GNUNET_EXIT_TcpDataMessage *data) { struct ChannelState *state = cls; - if ( (NULL == state) || - (NULL == state->specifics.tcp_udp.heap_node) ) - { - /* connection should have been up! */ - GNUNET_STATISTICS_update (stats, - gettext_noop ("# TCP DATA requests dropped (no session)"), - 1, GNUNET_NO); - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if (data->tcp_header.off * 4 < sizeof (struct GNUNET_TUN_TcpHeader)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + if ((NULL == state) || + (NULL == state->specifics.tcp_udp.heap_node)) + { + /* connection should have been up! */ + GNUNET_STATISTICS_update(stats, + gettext_noop("# TCP DATA requests dropped (no session)"), + 1, GNUNET_NO); + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if (data->tcp_header.off * 4 < sizeof(struct GNUNET_TUN_TcpHeader)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } if (GNUNET_YES == state->is_dns) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1810,42 +1823,42 @@ check_tcp_data (void *cls, * @param message the actual message */ static void -handle_tcp_data (void *cls, - const struct GNUNET_EXIT_TcpDataMessage *data) +handle_tcp_data(void *cls, + const struct GNUNET_EXIT_TcpDataMessage *data) { struct ChannelState *state = cls; - uint16_t pkt_len = ntohs (data->header.size) - sizeof (struct GNUNET_EXIT_TcpDataMessage); - - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Bytes received from CADET"), - pkt_len, GNUNET_NO); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# TCP data requests received via cadet"), - 1, GNUNET_NO); + uint16_t pkt_len = ntohs(data->header.size) - sizeof(struct GNUNET_EXIT_TcpDataMessage); + + GNUNET_STATISTICS_update(stats, + gettext_noop("# Bytes received from CADET"), + pkt_len, GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# TCP data requests received via cadet"), + 1, GNUNET_NO); if (GNUNET_SYSERR == state->is_dns) - { - /* channel is UDP/TCP from now on */ - state->is_dns = GNUNET_NO; - } + { + /* channel is UDP/TCP from now on */ + state->is_dns = GNUNET_NO; + } - GNUNET_break_op (ntohl (data->reserved) == 0); + GNUNET_break_op(ntohl(data->reserved) == 0); { char buf[INET6_ADDRSTRLEN]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received additional %u bytes of data from %s for TCP stream to %s:%u\n", - pkt_len, - GNUNET_i2s (&state->peer), - inet_ntop (state->specifics.tcp_udp.ri.remote_address.af, - &state->specifics.tcp_udp.ri.remote_address.address, - buf, sizeof (buf)), - (unsigned int) state->specifics.tcp_udp.ri.remote_address.port); - } - - send_tcp_packet_via_tun (&state->specifics.tcp_udp.ri.remote_address, - &state->specifics.tcp_udp.ri.local_address, - &data->tcp_header, - &data[1], pkt_len); - GNUNET_CADET_receive_done (state->channel); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received additional %u bytes of data from %s for TCP stream to %s:%u\n", + pkt_len, + GNUNET_i2s(&state->peer), + inet_ntop(state->specifics.tcp_udp.ri.remote_address.af, + &state->specifics.tcp_udp.ri.remote_address.address, + buf, sizeof(buf)), + (unsigned int)state->specifics.tcp_udp.ri.remote_address.port); + } + + send_tcp_packet_via_tun(&state->specifics.tcp_udp.ri.remote_address, + &state->specifics.tcp_udp.ri.local_address, + &data->tcp_header, + &data[1], pkt_len); + GNUNET_CADET_receive_done(state->channel); } @@ -1859,19 +1872,19 @@ handle_tcp_data (void *cls, * also be the first 8 bytes of the TCP header */ static void -make_up_icmpv4_payload (struct ChannelState *state, - struct GNUNET_TUN_IPv4Header *ipp, - struct GNUNET_TUN_UdpHeader *udp) +make_up_icmpv4_payload(struct ChannelState *state, + struct GNUNET_TUN_IPv4Header *ipp, + struct GNUNET_TUN_UdpHeader *udp) { - GNUNET_TUN_initialize_ipv4_header (ipp, - state->specifics.tcp_udp.ri.remote_address.proto, - sizeof (struct GNUNET_TUN_TcpHeader), - &state->specifics.tcp_udp.ri.remote_address.address.ipv4, - &state->specifics.tcp_udp.ri.local_address.address.ipv4); - udp->source_port = htons (state->specifics.tcp_udp.ri.remote_address.port); - udp->destination_port = htons (state->specifics.tcp_udp.ri.local_address.port); - udp->len = htons (0); - udp->crc = htons (0); + GNUNET_TUN_initialize_ipv4_header(ipp, + state->specifics.tcp_udp.ri.remote_address.proto, + sizeof(struct GNUNET_TUN_TcpHeader), + &state->specifics.tcp_udp.ri.remote_address.address.ipv4, + &state->specifics.tcp_udp.ri.local_address.address.ipv4); + udp->source_port = htons(state->specifics.tcp_udp.ri.remote_address.port); + udp->destination_port = htons(state->specifics.tcp_udp.ri.local_address.port); + udp->len = htons(0); + udp->crc = htons(0); } @@ -1885,19 +1898,19 @@ make_up_icmpv4_payload (struct ChannelState *state, * also be the first 8 bytes of the TCP header */ static void -make_up_icmpv6_payload (struct ChannelState *state, - struct GNUNET_TUN_IPv6Header *ipp, - struct GNUNET_TUN_UdpHeader *udp) +make_up_icmpv6_payload(struct ChannelState *state, + struct GNUNET_TUN_IPv6Header *ipp, + struct GNUNET_TUN_UdpHeader *udp) { - GNUNET_TUN_initialize_ipv6_header (ipp, - state->specifics.tcp_udp.ri.remote_address.proto, - sizeof (struct GNUNET_TUN_TcpHeader), - &state->specifics.tcp_udp.ri.remote_address.address.ipv6, - &state->specifics.tcp_udp.ri.local_address.address.ipv6); - udp->source_port = htons (state->specifics.tcp_udp.ri.remote_address.port); - udp->destination_port = htons (state->specifics.tcp_udp.ri.local_address.port); - udp->len = htons (0); - udp->crc = htons (0); + GNUNET_TUN_initialize_ipv6_header(ipp, + state->specifics.tcp_udp.ri.remote_address.proto, + sizeof(struct GNUNET_TUN_TcpHeader), + &state->specifics.tcp_udp.ri.remote_address.address.ipv6, + &state->specifics.tcp_udp.ri.local_address.address.ipv6); + udp->source_port = htons(state->specifics.tcp_udp.ri.remote_address.port); + udp->destination_port = htons(state->specifics.tcp_udp.ri.local_address.port); + udp->len = htons(0); + udp->crc = htons(0); } @@ -1910,16 +1923,16 @@ make_up_icmpv6_payload (struct ChannelState *state, * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_icmp_remote (void *cls, - const struct GNUNET_EXIT_IcmpInternetMessage *msg) +check_icmp_remote(void *cls, + const struct GNUNET_EXIT_IcmpInternetMessage *msg) { struct ChannelState *state = cls; if (GNUNET_YES == state->is_dns) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1931,177 +1944,183 @@ check_icmp_remote (void *cls, * @param msg the actual message */ static void -handle_icmp_remote (void *cls, - const struct GNUNET_EXIT_IcmpInternetMessage *msg) +handle_icmp_remote(void *cls, + const struct GNUNET_EXIT_IcmpInternetMessage *msg) { struct ChannelState *state = cls; - uint16_t pkt_len = ntohs (msg->header.size) - sizeof (struct GNUNET_EXIT_IcmpInternetMessage); + uint16_t pkt_len = ntohs(msg->header.size) - sizeof(struct GNUNET_EXIT_IcmpInternetMessage); const struct in_addr *v4; const struct in6_addr *v6; const void *payload; - char buf[sizeof (struct GNUNET_TUN_IPv6Header) + 8] GNUNET_ALIGN; + char buf[sizeof(struct GNUNET_TUN_IPv6Header) + 8] GNUNET_ALIGN; int af; if (GNUNET_SYSERR == state->is_dns) - { - /* channel is UDP/TCP from now on */ - state->is_dns = GNUNET_NO; - } - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Bytes received from CADET"), - pkt_len, GNUNET_NO); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# ICMP IP-exit requests received via cadet"), - 1, GNUNET_NO); - - af = (int) ntohl (msg->af); - if ( (NULL != state->specifics.tcp_udp.heap_node) && - (af != state->specifics.tcp_udp.ri.remote_address.af) ) - { - /* other peer switched AF on this channel; not allowed */ - GNUNET_break_op (0); - return; - } - - switch (af) - { - case AF_INET: - if (pkt_len < sizeof (struct in_addr)) { - GNUNET_break_op (0); - return; - } - if (! ipv4_exit) - { - GNUNET_break_op (0); - return; - } - v4 = (const struct in_addr*) &msg[1]; - payload = &v4[1]; - pkt_len -= sizeof (struct in_addr); - state->specifics.tcp_udp.ri.remote_address.address.ipv4 = *v4; - if (NULL == state->specifics.tcp_udp.heap_node) - { - state->specifics.tcp_udp.ri.remote_address.af = af; - state->specifics.tcp_udp.ri.remote_address.proto = IPPROTO_ICMP; - setup_state_record (state); - } - /* check that ICMP type is something we want to support - and possibly make up payload! */ - switch (msg->icmp_header.type) - { - case GNUNET_TUN_ICMPTYPE_ECHO_REPLY: - case GNUNET_TUN_ICMPTYPE_ECHO_REQUEST: - break; - case GNUNET_TUN_ICMPTYPE_DESTINATION_UNREACHABLE: - case GNUNET_TUN_ICMPTYPE_SOURCE_QUENCH: - case GNUNET_TUN_ICMPTYPE_TIME_EXCEEDED: - if (0 != pkt_len) - { - GNUNET_break_op (0); - return; - } - /* make up payload */ - { - struct GNUNET_TUN_IPv4Header *ipp = (struct GNUNET_TUN_IPv4Header *) buf; - struct GNUNET_TUN_UdpHeader *udp = (struct GNUNET_TUN_UdpHeader *) &ipp[1]; - - GNUNET_assert (8 == sizeof (struct GNUNET_TUN_UdpHeader)); - pkt_len = sizeof (struct GNUNET_TUN_IPv4Header) + 8; - make_up_icmpv4_payload (state, - ipp, - udp); - payload = ipp; - } - break; - default: - GNUNET_break_op (0); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# ICMPv4 packets dropped (type not allowed)"), - 1, GNUNET_NO); - return; + /* channel is UDP/TCP from now on */ + state->is_dns = GNUNET_NO; } - /* end AF_INET */ - break; - case AF_INET6: - if (pkt_len < sizeof (struct in6_addr)) - { - GNUNET_break_op (0); - return; - } - if (! ipv6_exit) + GNUNET_STATISTICS_update(stats, + gettext_noop("# Bytes received from CADET"), + pkt_len, GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# ICMP IP-exit requests received via cadet"), + 1, GNUNET_NO); + + af = (int)ntohl(msg->af); + if ((NULL != state->specifics.tcp_udp.heap_node) && + (af != state->specifics.tcp_udp.ri.remote_address.af)) { - GNUNET_break_op (0); + /* other peer switched AF on this channel; not allowed */ + GNUNET_break_op(0); return; } - v6 = (const struct in6_addr*) &msg[1]; - payload = &v6[1]; - pkt_len -= sizeof (struct in6_addr); - state->specifics.tcp_udp.ri.remote_address.address.ipv6 = *v6; - if (NULL == state->specifics.tcp_udp.heap_node) - { - state->specifics.tcp_udp.ri.remote_address.af = af; - state->specifics.tcp_udp.ri.remote_address.proto = IPPROTO_ICMPV6; - setup_state_record (state); - } - /* check that ICMP type is something we want to support - and possibly make up payload! */ - switch (msg->icmp_header.type) + + switch (af) { - case GNUNET_TUN_ICMPTYPE6_ECHO_REPLY: - case GNUNET_TUN_ICMPTYPE6_ECHO_REQUEST: + case AF_INET: + if (pkt_len < sizeof(struct in_addr)) + { + GNUNET_break_op(0); + return; + } + if (!ipv4_exit) + { + GNUNET_break_op(0); + return; + } + v4 = (const struct in_addr*)&msg[1]; + payload = &v4[1]; + pkt_len -= sizeof(struct in_addr); + state->specifics.tcp_udp.ri.remote_address.address.ipv4 = *v4; + if (NULL == state->specifics.tcp_udp.heap_node) + { + state->specifics.tcp_udp.ri.remote_address.af = af; + state->specifics.tcp_udp.ri.remote_address.proto = IPPROTO_ICMP; + setup_state_record(state); + } + /* check that ICMP type is something we want to support + and possibly make up payload! */ + switch (msg->icmp_header.type) + { + case GNUNET_TUN_ICMPTYPE_ECHO_REPLY: + case GNUNET_TUN_ICMPTYPE_ECHO_REQUEST: + break; + + case GNUNET_TUN_ICMPTYPE_DESTINATION_UNREACHABLE: + case GNUNET_TUN_ICMPTYPE_SOURCE_QUENCH: + case GNUNET_TUN_ICMPTYPE_TIME_EXCEEDED: + if (0 != pkt_len) + { + GNUNET_break_op(0); + return; + } + /* make up payload */ + { + struct GNUNET_TUN_IPv4Header *ipp = (struct GNUNET_TUN_IPv4Header *)buf; + struct GNUNET_TUN_UdpHeader *udp = (struct GNUNET_TUN_UdpHeader *)&ipp[1]; + + GNUNET_assert(8 == sizeof(struct GNUNET_TUN_UdpHeader)); + pkt_len = sizeof(struct GNUNET_TUN_IPv4Header) + 8; + make_up_icmpv4_payload(state, + ipp, + udp); + payload = ipp; + } + break; + + default: + GNUNET_break_op(0); + GNUNET_STATISTICS_update(stats, + gettext_noop("# ICMPv4 packets dropped (type not allowed)"), + 1, GNUNET_NO); + return; + } + /* end AF_INET */ break; - case GNUNET_TUN_ICMPTYPE6_DESTINATION_UNREACHABLE: - case GNUNET_TUN_ICMPTYPE6_PACKET_TOO_BIG: - case GNUNET_TUN_ICMPTYPE6_TIME_EXCEEDED: - case GNUNET_TUN_ICMPTYPE6_PARAMETER_PROBLEM: - if (0 != pkt_len) - { - GNUNET_break_op (0); - return; - } - /* make up payload */ - { - struct GNUNET_TUN_IPv6Header *ipp = (struct GNUNET_TUN_IPv6Header *) buf; - struct GNUNET_TUN_UdpHeader *udp = (struct GNUNET_TUN_UdpHeader *) &ipp[1]; - - GNUNET_assert (8 == sizeof (struct GNUNET_TUN_UdpHeader)); - pkt_len = sizeof (struct GNUNET_TUN_IPv6Header) + 8; - make_up_icmpv6_payload (state, - ipp, - udp); - payload = ipp; - } + + case AF_INET6: + if (pkt_len < sizeof(struct in6_addr)) + { + GNUNET_break_op(0); + return; + } + if (!ipv6_exit) + { + GNUNET_break_op(0); + return; + } + v6 = (const struct in6_addr*)&msg[1]; + payload = &v6[1]; + pkt_len -= sizeof(struct in6_addr); + state->specifics.tcp_udp.ri.remote_address.address.ipv6 = *v6; + if (NULL == state->specifics.tcp_udp.heap_node) + { + state->specifics.tcp_udp.ri.remote_address.af = af; + state->specifics.tcp_udp.ri.remote_address.proto = IPPROTO_ICMPV6; + setup_state_record(state); + } + /* check that ICMP type is something we want to support + and possibly make up payload! */ + switch (msg->icmp_header.type) + { + case GNUNET_TUN_ICMPTYPE6_ECHO_REPLY: + case GNUNET_TUN_ICMPTYPE6_ECHO_REQUEST: + break; + + case GNUNET_TUN_ICMPTYPE6_DESTINATION_UNREACHABLE: + case GNUNET_TUN_ICMPTYPE6_PACKET_TOO_BIG: + case GNUNET_TUN_ICMPTYPE6_TIME_EXCEEDED: + case GNUNET_TUN_ICMPTYPE6_PARAMETER_PROBLEM: + if (0 != pkt_len) + { + GNUNET_break_op(0); + return; + } + /* make up payload */ + { + struct GNUNET_TUN_IPv6Header *ipp = (struct GNUNET_TUN_IPv6Header *)buf; + struct GNUNET_TUN_UdpHeader *udp = (struct GNUNET_TUN_UdpHeader *)&ipp[1]; + + GNUNET_assert(8 == sizeof(struct GNUNET_TUN_UdpHeader)); + pkt_len = sizeof(struct GNUNET_TUN_IPv6Header) + 8; + make_up_icmpv6_payload(state, + ipp, + udp); + payload = ipp; + } + break; + + default: + GNUNET_break_op(0); + GNUNET_STATISTICS_update(stats, + gettext_noop("# ICMPv6 packets dropped (type not allowed)"), + 1, GNUNET_NO); + return; + } + /* end AF_INET6 */ break; + default: - GNUNET_break_op (0); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# ICMPv6 packets dropped (type not allowed)"), - 1, GNUNET_NO); + /* bad AF */ + GNUNET_break_op(0); return; } - /* end AF_INET6 */ - break; - default: - /* bad AF */ - GNUNET_break_op (0); - return; - } { char buf[INET6_ADDRSTRLEN]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ICMP data from %s for forwarding to %s\n", - GNUNET_i2s (&state->peer), - inet_ntop (af, - &state->specifics.tcp_udp.ri.remote_address.address, - buf, sizeof (buf))); - } - send_icmp_packet_via_tun (&state->specifics.tcp_udp.ri.remote_address, - &state->specifics.tcp_udp.ri.local_address, - &msg->icmp_header, - payload, pkt_len); - GNUNET_CADET_receive_done (state->channel); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ICMP data from %s for forwarding to %s\n", + GNUNET_i2s(&state->peer), + inet_ntop(af, + &state->specifics.tcp_udp.ri.remote_address.address, + buf, sizeof(buf))); + } + send_icmp_packet_via_tun(&state->specifics.tcp_udp.ri.remote_address, + &state->specifics.tcp_udp.ri.local_address, + &msg->icmp_header, + payload, pkt_len); + GNUNET_CADET_receive_done(state->channel); } @@ -2115,42 +2134,44 @@ handle_icmp_remote (void *cls, * @return number of bytes of payload we created in buf */ static uint16_t -make_up_icmp_service_payload (struct ChannelState *state, - char *buf) +make_up_icmp_service_payload(struct ChannelState *state, + char *buf) { switch (state->specifics.tcp_udp.serv->address.af) - { - case AF_INET: + { + case AF_INET: { struct GNUNET_TUN_IPv4Header *ipv4; struct GNUNET_TUN_UdpHeader *udp; ipv4 = (struct GNUNET_TUN_IPv4Header *)buf; - udp = (struct GNUNET_TUN_UdpHeader *) &ipv4[1]; - make_up_icmpv4_payload (state, - ipv4, - udp); - GNUNET_assert (8 == sizeof (struct GNUNET_TUN_UdpHeader)); - return sizeof (struct GNUNET_TUN_IPv4Header) + 8; + udp = (struct GNUNET_TUN_UdpHeader *)&ipv4[1]; + make_up_icmpv4_payload(state, + ipv4, + udp); + GNUNET_assert(8 == sizeof(struct GNUNET_TUN_UdpHeader)); + return sizeof(struct GNUNET_TUN_IPv4Header) + 8; } break; - case AF_INET6: + + case AF_INET6: { struct GNUNET_TUN_IPv6Header *ipv6; struct GNUNET_TUN_UdpHeader *udp; ipv6 = (struct GNUNET_TUN_IPv6Header *)buf; - udp = (struct GNUNET_TUN_UdpHeader *) &ipv6[1]; - make_up_icmpv6_payload (state, - ipv6, - udp); - GNUNET_assert (8 == sizeof (struct GNUNET_TUN_UdpHeader)); - return sizeof (struct GNUNET_TUN_IPv6Header) + 8; + udp = (struct GNUNET_TUN_UdpHeader *)&ipv6[1]; + make_up_icmpv6_payload(state, + ipv6, + udp); + GNUNET_assert(8 == sizeof(struct GNUNET_TUN_UdpHeader)); + return sizeof(struct GNUNET_TUN_IPv6Header) + 8; } break; - default: - GNUNET_break (0); - } + + default: + GNUNET_break(0); + } return 0; } @@ -2165,21 +2186,21 @@ make_up_icmp_service_payload (struct ChannelState *state, * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_icmp_service (void *cls, - const struct GNUNET_EXIT_IcmpServiceMessage *msg) +check_icmp_service(void *cls, + const struct GNUNET_EXIT_IcmpServiceMessage *msg) { struct ChannelState *state = cls; if (GNUNET_YES == state->is_dns) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } if (NULL == state->specifics.tcp_udp.serv) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -2192,164 +2213,176 @@ check_icmp_service (void *cls, * @param msg the actual message */ static void -handle_icmp_service (void *cls, - const struct GNUNET_EXIT_IcmpServiceMessage *msg) +handle_icmp_service(void *cls, + const struct GNUNET_EXIT_IcmpServiceMessage *msg) { struct ChannelState *state = cls; - uint16_t pkt_len = ntohs (msg->header.size) - sizeof (struct GNUNET_EXIT_IcmpServiceMessage); + uint16_t pkt_len = ntohs(msg->header.size) - sizeof(struct GNUNET_EXIT_IcmpServiceMessage); struct GNUNET_TUN_IcmpHeader icmp; - char buf[sizeof (struct GNUNET_TUN_IPv6Header) + 8] GNUNET_ALIGN; + char buf[sizeof(struct GNUNET_TUN_IPv6Header) + 8] GNUNET_ALIGN; const void *payload; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Bytes received from CADET"), - pkt_len, GNUNET_NO); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# ICMP service requests received via cadet"), - 1, GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# Bytes received from CADET"), + pkt_len, GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# ICMP service requests received via cadet"), + 1, GNUNET_NO); /* check that we got at least a valid header */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received data from %s for forwarding to ICMP service %s\n", - GNUNET_i2s (&state->peer), - GNUNET_h2s (&state->specifics.tcp_udp.serv->descriptor)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received data from %s for forwarding to ICMP service %s\n", + GNUNET_i2s(&state->peer), + GNUNET_h2s(&state->specifics.tcp_udp.serv->descriptor)); icmp = msg->icmp_header; payload = &msg[1]; state->specifics.tcp_udp.ri.remote_address = state->specifics.tcp_udp.serv->address; - setup_state_record (state); + setup_state_record(state); /* check that ICMP type is something we want to support, perform ICMP PT if needed ans possibly make up payload */ switch (msg->af) - { - case AF_INET: - switch (msg->icmp_header.type) - { - case GNUNET_TUN_ICMPTYPE_ECHO_REPLY: - if (state->specifics.tcp_udp.serv->address.af == AF_INET6) - icmp.type = GNUNET_TUN_ICMPTYPE6_ECHO_REPLY; - break; - case GNUNET_TUN_ICMPTYPE_ECHO_REQUEST: - if (state->specifics.tcp_udp.serv->address.af == AF_INET6) - icmp.type = GNUNET_TUN_ICMPTYPE6_ECHO_REQUEST; - break; - case GNUNET_TUN_ICMPTYPE_DESTINATION_UNREACHABLE: - if (state->specifics.tcp_udp.serv->address.af == AF_INET6) - icmp.type = GNUNET_TUN_ICMPTYPE6_DESTINATION_UNREACHABLE; - if (0 != pkt_len) - { - GNUNET_break_op (0); - return; - } - payload = buf; - pkt_len = make_up_icmp_service_payload (state, buf); - break; - case GNUNET_TUN_ICMPTYPE_TIME_EXCEEDED: - if (state->specifics.tcp_udp.serv->address.af == AF_INET6) - icmp.type = GNUNET_TUN_ICMPTYPE6_TIME_EXCEEDED; - if (0 != pkt_len) - { - GNUNET_break_op (0); - return; - } - payload = buf; - pkt_len = make_up_icmp_service_payload (state, buf); - break; - case GNUNET_TUN_ICMPTYPE_SOURCE_QUENCH: - if (state->specifics.tcp_udp.serv->address.af == AF_INET6) - { - GNUNET_STATISTICS_update (stats, - gettext_noop ("# ICMPv4 packets dropped (impossible PT to v6)"), - 1, GNUNET_NO); - return; - } - if (0 != pkt_len) - { - GNUNET_break_op (0); - return; - } - payload = buf; - pkt_len = make_up_icmp_service_payload (state, buf); - break; - default: - GNUNET_break_op (0); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# ICMPv4 packets dropped (type not allowed)"), - 1, GNUNET_NO); - return; - } - /* end of AF_INET */ - break; - case AF_INET6: - switch (msg->icmp_header.type) { - case GNUNET_TUN_ICMPTYPE6_ECHO_REPLY: - if (state->specifics.tcp_udp.serv->address.af == AF_INET) - icmp.type = GNUNET_TUN_ICMPTYPE_ECHO_REPLY; - break; - case GNUNET_TUN_ICMPTYPE6_ECHO_REQUEST: - if (state->specifics.tcp_udp.serv->address.af == AF_INET) - icmp.type = GNUNET_TUN_ICMPTYPE_ECHO_REQUEST; - break; - case GNUNET_TUN_ICMPTYPE6_DESTINATION_UNREACHABLE: - if (state->specifics.tcp_udp.serv->address.af == AF_INET) - icmp.type = GNUNET_TUN_ICMPTYPE_DESTINATION_UNREACHABLE; - if (0 != pkt_len) - { - GNUNET_break_op (0); - return; - } - payload = buf; - pkt_len = make_up_icmp_service_payload (state, buf); - break; - case GNUNET_TUN_ICMPTYPE6_TIME_EXCEEDED: - if (state->specifics.tcp_udp.serv->address.af == AF_INET) - icmp.type = GNUNET_TUN_ICMPTYPE_TIME_EXCEEDED; - if (0 != pkt_len) - { - GNUNET_break_op (0); - return; - } - payload = buf; - pkt_len = make_up_icmp_service_payload (state, buf); + case AF_INET: + switch (msg->icmp_header.type) + { + case GNUNET_TUN_ICMPTYPE_ECHO_REPLY: + if (state->specifics.tcp_udp.serv->address.af == AF_INET6) + icmp.type = GNUNET_TUN_ICMPTYPE6_ECHO_REPLY; + break; + + case GNUNET_TUN_ICMPTYPE_ECHO_REQUEST: + if (state->specifics.tcp_udp.serv->address.af == AF_INET6) + icmp.type = GNUNET_TUN_ICMPTYPE6_ECHO_REQUEST; + break; + + case GNUNET_TUN_ICMPTYPE_DESTINATION_UNREACHABLE: + if (state->specifics.tcp_udp.serv->address.af == AF_INET6) + icmp.type = GNUNET_TUN_ICMPTYPE6_DESTINATION_UNREACHABLE; + if (0 != pkt_len) + { + GNUNET_break_op(0); + return; + } + payload = buf; + pkt_len = make_up_icmp_service_payload(state, buf); + break; + + case GNUNET_TUN_ICMPTYPE_TIME_EXCEEDED: + if (state->specifics.tcp_udp.serv->address.af == AF_INET6) + icmp.type = GNUNET_TUN_ICMPTYPE6_TIME_EXCEEDED; + if (0 != pkt_len) + { + GNUNET_break_op(0); + return; + } + payload = buf; + pkt_len = make_up_icmp_service_payload(state, buf); + break; + + case GNUNET_TUN_ICMPTYPE_SOURCE_QUENCH: + if (state->specifics.tcp_udp.serv->address.af == AF_INET6) + { + GNUNET_STATISTICS_update(stats, + gettext_noop("# ICMPv4 packets dropped (impossible PT to v6)"), + 1, GNUNET_NO); + return; + } + if (0 != pkt_len) + { + GNUNET_break_op(0); + return; + } + payload = buf; + pkt_len = make_up_icmp_service_payload(state, buf); + break; + + default: + GNUNET_break_op(0); + GNUNET_STATISTICS_update(stats, + gettext_noop("# ICMPv4 packets dropped (type not allowed)"), + 1, GNUNET_NO); + return; + } + /* end of AF_INET */ break; - case GNUNET_TUN_ICMPTYPE6_PACKET_TOO_BIG: - case GNUNET_TUN_ICMPTYPE6_PARAMETER_PROBLEM: - if (state->specifics.tcp_udp.serv->address.af == AF_INET) - { - GNUNET_STATISTICS_update (stats, - gettext_noop ("# ICMPv6 packets dropped (impossible PT to v4)"), - 1, GNUNET_NO); - return; - } - if (0 != pkt_len) - { - GNUNET_break_op (0); - return; - } - payload = buf; - pkt_len = make_up_icmp_service_payload (state, buf); + + case AF_INET6: + switch (msg->icmp_header.type) + { + case GNUNET_TUN_ICMPTYPE6_ECHO_REPLY: + if (state->specifics.tcp_udp.serv->address.af == AF_INET) + icmp.type = GNUNET_TUN_ICMPTYPE_ECHO_REPLY; + break; + + case GNUNET_TUN_ICMPTYPE6_ECHO_REQUEST: + if (state->specifics.tcp_udp.serv->address.af == AF_INET) + icmp.type = GNUNET_TUN_ICMPTYPE_ECHO_REQUEST; + break; + + case GNUNET_TUN_ICMPTYPE6_DESTINATION_UNREACHABLE: + if (state->specifics.tcp_udp.serv->address.af == AF_INET) + icmp.type = GNUNET_TUN_ICMPTYPE_DESTINATION_UNREACHABLE; + if (0 != pkt_len) + { + GNUNET_break_op(0); + return; + } + payload = buf; + pkt_len = make_up_icmp_service_payload(state, buf); + break; + + case GNUNET_TUN_ICMPTYPE6_TIME_EXCEEDED: + if (state->specifics.tcp_udp.serv->address.af == AF_INET) + icmp.type = GNUNET_TUN_ICMPTYPE_TIME_EXCEEDED; + if (0 != pkt_len) + { + GNUNET_break_op(0); + return; + } + payload = buf; + pkt_len = make_up_icmp_service_payload(state, buf); + break; + + case GNUNET_TUN_ICMPTYPE6_PACKET_TOO_BIG: + case GNUNET_TUN_ICMPTYPE6_PARAMETER_PROBLEM: + if (state->specifics.tcp_udp.serv->address.af == AF_INET) + { + GNUNET_STATISTICS_update(stats, + gettext_noop("# ICMPv6 packets dropped (impossible PT to v4)"), + 1, GNUNET_NO); + return; + } + if (0 != pkt_len) + { + GNUNET_break_op(0); + return; + } + payload = buf; + pkt_len = make_up_icmp_service_payload(state, buf); + break; + + default: + GNUNET_break_op(0); + GNUNET_STATISTICS_update(stats, + gettext_noop("# ICMPv6 packets dropped (type not allowed)"), + 1, GNUNET_NO); + return; + } + /* end of AF_INET6 */ break; + default: - GNUNET_break_op (0); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# ICMPv6 packets dropped (type not allowed)"), - 1, GNUNET_NO); + GNUNET_break_op(0); return; } - /* end of AF_INET6 */ - break; - default: - GNUNET_break_op (0); - return; - } - send_icmp_packet_via_tun (&state->specifics.tcp_udp.ri.remote_address, - &state->specifics.tcp_udp.ri.local_address, - &icmp, - payload, - pkt_len); - GNUNET_CADET_receive_done (state->channel); + send_icmp_packet_via_tun(&state->specifics.tcp_udp.ri.remote_address, + &state->specifics.tcp_udp.ri.local_address, + &icmp, + payload, + pkt_len); + GNUNET_CADET_receive_done(state->channel); } @@ -2362,19 +2395,19 @@ handle_icmp_service (void *cls, * @return #GNUNET_OK */ static int -free_service_record (void *cls, - const struct GNUNET_HashCode *key, - void *value) +free_service_record(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct LocalService *service = value; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (services, - key, - service)); - GNUNET_CADET_close_port (service->port); - GNUNET_free_non_null (service->name); - GNUNET_free (service); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(services, + key, + service)); + GNUNET_CADET_close_port(service->port); + GNUNET_free_non_null(service->name); + GNUNET_free(service); return GNUNET_OK; } @@ -2388,21 +2421,21 @@ free_service_record (void *cls, * @return initial channel context for the channel */ static void * -new_service_channel (void *cls, - struct GNUNET_CADET_Channel *channel, - const struct GNUNET_PeerIdentity *initiator) +new_service_channel(void *cls, + struct GNUNET_CADET_Channel *channel, + const struct GNUNET_PeerIdentity *initiator) { struct LocalService *ls = cls; - struct ChannelState *s = GNUNET_new (struct ChannelState); + struct ChannelState *s = GNUNET_new(struct ChannelState); s->peer = *initiator; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Inbound CADET channels created"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received inbound channel from `%s'\n", - GNUNET_i2s (initiator)); + GNUNET_STATISTICS_update(stats, + gettext_noop("# Inbound CADET channels created"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received inbound channel from `%s'\n", + GNUNET_i2s(initiator)); s->channel = channel; s->specifics.tcp_udp.serv = ls; s->specifics.tcp_udp.ri.remote_address = ls->address; @@ -2418,36 +2451,36 @@ new_service_channel (void *cls, * @param channel connection to the other end (henceforth invalid) */ static void -clean_channel (void *cls, - const struct GNUNET_CADET_Channel *channel) +clean_channel(void *cls, + const struct GNUNET_CADET_Channel *channel) { struct ChannelState *s = cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Channel destroyed\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Channel destroyed\n"); if (GNUNET_SYSERR == s->is_dns) - { - GNUNET_free (s); - return; - } + { + GNUNET_free(s); + return; + } if (GNUNET_YES == s->is_dns) - { - if (channels[s->specifics.dns.my_id] == s) - channels[s->specifics.dns.my_id] = NULL; - } + { + if (channels[s->specifics.dns.my_id] == s) + channels[s->specifics.dns.my_id] = NULL; + } else - { - if (NULL != s->specifics.tcp_udp.heap_node) { - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (connections_map, - &s->specifics.tcp_udp.state_key, - s)); - GNUNET_CONTAINER_heap_remove_node (s->specifics.tcp_udp.heap_node); - s->specifics.tcp_udp.heap_node = NULL; + if (NULL != s->specifics.tcp_udp.heap_node) + { + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(connections_map, + &s->specifics.tcp_udp.state_key, + s)); + GNUNET_CONTAINER_heap_remove_node(s->specifics.tcp_udp.heap_node); + s->specifics.tcp_udp.heap_node = NULL; + } } - } - GNUNET_free (s); + GNUNET_free(s); } @@ -2461,66 +2494,66 @@ clean_channel (void *cls, * @param service service information record to store (service->name will be set). */ static void -store_service (int proto, - const char *name, - uint16_t destination_port, - struct LocalService *service) +store_service(int proto, + const char *name, + uint16_t destination_port, + struct LocalService *service) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (icmp_service, - GNUNET_MESSAGE_TYPE_VPN_ICMP_TO_SERVICE, - struct GNUNET_EXIT_IcmpServiceMessage, - service), - GNUNET_MQ_hd_var_size (udp_service, - GNUNET_MESSAGE_TYPE_VPN_UDP_TO_SERVICE, - struct GNUNET_EXIT_UdpServiceMessage, - service), - GNUNET_MQ_hd_var_size (tcp_service, - GNUNET_MESSAGE_TYPE_VPN_TCP_TO_SERVICE_START, - struct GNUNET_EXIT_TcpServiceStartMessage, - service), - GNUNET_MQ_hd_var_size (tcp_data, - GNUNET_MESSAGE_TYPE_VPN_TCP_DATA_TO_EXIT, - struct GNUNET_EXIT_TcpDataMessage, - service), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(icmp_service, + GNUNET_MESSAGE_TYPE_VPN_ICMP_TO_SERVICE, + struct GNUNET_EXIT_IcmpServiceMessage, + service), + GNUNET_MQ_hd_var_size(udp_service, + GNUNET_MESSAGE_TYPE_VPN_UDP_TO_SERVICE, + struct GNUNET_EXIT_UdpServiceMessage, + service), + GNUNET_MQ_hd_var_size(tcp_service, + GNUNET_MESSAGE_TYPE_VPN_TCP_TO_SERVICE_START, + struct GNUNET_EXIT_TcpServiceStartMessage, + service), + GNUNET_MQ_hd_var_size(tcp_data, + GNUNET_MESSAGE_TYPE_VPN_TCP_DATA_TO_EXIT, + struct GNUNET_EXIT_TcpDataMessage, + service), + GNUNET_MQ_handler_end() }; struct GNUNET_HashCode cadet_port; - service->name = GNUNET_strdup (name); - GNUNET_TUN_service_name_to_hash (name, - &service->descriptor); - GNUNET_TUN_compute_service_cadet_port (&service->descriptor, - destination_port, - &cadet_port); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Opening CADET port %s for SERVICE exit %s on port %u\n", - GNUNET_h2s (&cadet_port), - name, - (unsigned int) destination_port); - service->port = GNUNET_CADET_open_port (cadet_handle, - &cadet_port, - &new_service_channel, - service, - NULL, - &clean_channel, - handlers); + service->name = GNUNET_strdup(name); + GNUNET_TUN_service_name_to_hash(name, + &service->descriptor); + GNUNET_TUN_compute_service_cadet_port(&service->descriptor, + destination_port, + &cadet_port); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Opening CADET port %s for SERVICE exit %s on port %u\n", + GNUNET_h2s(&cadet_port), + name, + (unsigned int)destination_port); + service->port = GNUNET_CADET_open_port(cadet_handle, + &cadet_port, + &new_service_channel, + service, + NULL, + &clean_channel, + handlers); service->is_udp = (IPPROTO_UDP == proto); if (GNUNET_OK != - GNUNET_CONTAINER_multihashmap_put (services, - &cadet_port, - service, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - GNUNET_CADET_close_port (service->port); - GNUNET_free_non_null (service->name); - GNUNET_free (service); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Got duplicate service records for `%s:%u'\n"), - name, - (unsigned int) destination_port); - } + GNUNET_CONTAINER_multihashmap_put(services, + &cadet_port, + service, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_CADET_close_port(service->port); + GNUNET_free_non_null(service->name); + GNUNET_free(service); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Got duplicate service records for `%s:%u'\n"), + name, + (unsigned int)destination_port); + } } @@ -2531,16 +2564,16 @@ store_service (int proto, * @param env message to queue */ static void -send_packet_to_cadet_channel (struct ChannelState *s, - struct GNUNET_MQ_Envelope *env) +send_packet_to_cadet_channel(struct ChannelState *s, + struct GNUNET_MQ_Envelope *env) { - GNUNET_assert (NULL != s); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Messages transmitted via cadet channels"), - 1, - GNUNET_NO); - GNUNET_MQ_send (GNUNET_CADET_get_mq (s->channel), - env); + GNUNET_assert(NULL != s); + GNUNET_STATISTICS_update(stats, + gettext_noop("# Messages transmitted via cadet channels"), + 1, + GNUNET_NO); + GNUNET_MQ_send(GNUNET_CADET_get_mq(s->channel), + env); } @@ -2556,11 +2589,11 @@ send_packet_to_cadet_channel (struct ChannelState *s, * be the original destination address) */ static void -icmp_from_helper (const struct GNUNET_TUN_IcmpHeader *icmp, - size_t pktlen, - int af, - const void *destination_ip, - const void *source_ip) +icmp_from_helper(const struct GNUNET_TUN_IcmpHeader *icmp, + size_t pktlen, + int af, + const void *destination_ip, + const void *source_ip) { struct ChannelState *state; struct GNUNET_MQ_Envelope *env; @@ -2575,165 +2608,176 @@ icmp_from_helper (const struct GNUNET_TUN_IcmpHeader *icmp, { char sbuf[INET6_ADDRSTRLEN]; char dbuf[INET6_ADDRSTRLEN]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ICMP packet going from %s to %s\n", - inet_ntop (af, - source_ip, - sbuf, sizeof (sbuf)), - inet_ntop (af, - destination_ip, - dbuf, sizeof (dbuf))); - } - if (pktlen < sizeof (struct GNUNET_TUN_IcmpHeader)) - { - /* blame kernel */ - GNUNET_break (0); - return; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ICMP packet going from %s to %s\n", + inet_ntop(af, + source_ip, + sbuf, sizeof(sbuf)), + inet_ntop(af, + destination_ip, + dbuf, sizeof(dbuf))); } + if (pktlen < sizeof(struct GNUNET_TUN_IcmpHeader)) + { + /* blame kernel */ + GNUNET_break(0); + return; + } + /* Find out if this is an ICMP packet in response to an existing TCP/UDP packet and if so, figure out ports / protocol of the existing session from the IP data in the ICMP payload */ source_port = 0; destination_port = 0; switch (af) - { - case AF_INET: - protocol = IPPROTO_ICMP; - switch (icmp->type) - { - case GNUNET_TUN_ICMPTYPE_ECHO_REPLY: - case GNUNET_TUN_ICMPTYPE_ECHO_REQUEST: - break; - case GNUNET_TUN_ICMPTYPE_DESTINATION_UNREACHABLE: - case GNUNET_TUN_ICMPTYPE_SOURCE_QUENCH: - case GNUNET_TUN_ICMPTYPE_TIME_EXCEEDED: - if (pktlen < - sizeof (struct GNUNET_TUN_IcmpHeader) + - sizeof (struct GNUNET_TUN_IPv4Header) + 8) - { - /* blame kernel */ - GNUNET_break (0); - return; - } - ipv4 = (const struct GNUNET_TUN_IPv4Header *) &icmp[1]; - protocol = ipv4->protocol; - /* could be TCP or UDP, but both have the ports in the right - place, so that doesn't matter here */ - udp = (const struct GNUNET_TUN_UdpHeader *) &ipv4[1]; - /* swap ports, as they are from the original message */ - destination_port = ntohs (udp->source_port); - source_port = ntohs (udp->destination_port); - /* throw away ICMP payload, won't be useful for the other side anyway */ - pktlen = sizeof (struct GNUNET_TUN_IcmpHeader); - break; - default: - GNUNET_STATISTICS_update (stats, - gettext_noop ("# ICMPv4 packets dropped (type not allowed)"), - 1, GNUNET_NO); - return; - } - break; - case AF_INET6: - protocol = IPPROTO_ICMPV6; - switch (icmp->type) - { - case GNUNET_TUN_ICMPTYPE6_DESTINATION_UNREACHABLE: - case GNUNET_TUN_ICMPTYPE6_PACKET_TOO_BIG: - case GNUNET_TUN_ICMPTYPE6_TIME_EXCEEDED: - case GNUNET_TUN_ICMPTYPE6_PARAMETER_PROBLEM: - if (pktlen < - sizeof (struct GNUNET_TUN_IcmpHeader) + - sizeof (struct GNUNET_TUN_IPv6Header) + 8) - { - /* blame kernel */ - GNUNET_break (0); - return; - } - ipv6 = (const struct GNUNET_TUN_IPv6Header *) &icmp[1]; - protocol = ipv6->next_header; - /* could be TCP or UDP, but both have the ports in the right - place, so that doesn't matter here */ - udp = (const struct GNUNET_TUN_UdpHeader *) &ipv6[1]; - /* swap ports, as they are from the original message */ - destination_port = ntohs (udp->source_port); - source_port = ntohs (udp->destination_port); - /* throw away ICMP payload, won't be useful for the other side anyway */ - pktlen = sizeof (struct GNUNET_TUN_IcmpHeader); - break; - case GNUNET_TUN_ICMPTYPE6_ECHO_REQUEST: - case GNUNET_TUN_ICMPTYPE6_ECHO_REPLY: - break; - default: - GNUNET_STATISTICS_update (stats, - gettext_noop ("# ICMPv6 packets dropped (type not allowed)"), - 1, GNUNET_NO); - return; - } - break; - default: - GNUNET_assert (0); - } + { + case AF_INET: + protocol = IPPROTO_ICMP; + switch (icmp->type) + { + case GNUNET_TUN_ICMPTYPE_ECHO_REPLY: + case GNUNET_TUN_ICMPTYPE_ECHO_REQUEST: + break; + + case GNUNET_TUN_ICMPTYPE_DESTINATION_UNREACHABLE: + case GNUNET_TUN_ICMPTYPE_SOURCE_QUENCH: + case GNUNET_TUN_ICMPTYPE_TIME_EXCEEDED: + if (pktlen < + sizeof(struct GNUNET_TUN_IcmpHeader) + + sizeof(struct GNUNET_TUN_IPv4Header) + 8) + { + /* blame kernel */ + GNUNET_break(0); + return; + } + ipv4 = (const struct GNUNET_TUN_IPv4Header *)&icmp[1]; + protocol = ipv4->protocol; + /* could be TCP or UDP, but both have the ports in the right + place, so that doesn't matter here */ + udp = (const struct GNUNET_TUN_UdpHeader *)&ipv4[1]; + /* swap ports, as they are from the original message */ + destination_port = ntohs(udp->source_port); + source_port = ntohs(udp->destination_port); + /* throw away ICMP payload, won't be useful for the other side anyway */ + pktlen = sizeof(struct GNUNET_TUN_IcmpHeader); + break; + + default: + GNUNET_STATISTICS_update(stats, + gettext_noop("# ICMPv4 packets dropped (type not allowed)"), + 1, GNUNET_NO); + return; + } + break; + + case AF_INET6: + protocol = IPPROTO_ICMPV6; + switch (icmp->type) + { + case GNUNET_TUN_ICMPTYPE6_DESTINATION_UNREACHABLE: + case GNUNET_TUN_ICMPTYPE6_PACKET_TOO_BIG: + case GNUNET_TUN_ICMPTYPE6_TIME_EXCEEDED: + case GNUNET_TUN_ICMPTYPE6_PARAMETER_PROBLEM: + if (pktlen < + sizeof(struct GNUNET_TUN_IcmpHeader) + + sizeof(struct GNUNET_TUN_IPv6Header) + 8) + { + /* blame kernel */ + GNUNET_break(0); + return; + } + ipv6 = (const struct GNUNET_TUN_IPv6Header *)&icmp[1]; + protocol = ipv6->next_header; + /* could be TCP or UDP, but both have the ports in the right + place, so that doesn't matter here */ + udp = (const struct GNUNET_TUN_UdpHeader *)&ipv6[1]; + /* swap ports, as they are from the original message */ + destination_port = ntohs(udp->source_port); + source_port = ntohs(udp->destination_port); + /* throw away ICMP payload, won't be useful for the other side anyway */ + pktlen = sizeof(struct GNUNET_TUN_IcmpHeader); + break; + + case GNUNET_TUN_ICMPTYPE6_ECHO_REQUEST: + case GNUNET_TUN_ICMPTYPE6_ECHO_REPLY: + break; + + default: + GNUNET_STATISTICS_update(stats, + gettext_noop("# ICMPv6 packets dropped (type not allowed)"), + 1, GNUNET_NO); + return; + } + break; + + default: + GNUNET_assert(0); + } switch (protocol) - { - case IPPROTO_ICMP: - state = get_redirect_state (af, - IPPROTO_ICMP, - source_ip, - 0, - destination_ip, - 0, - NULL); - break; - case IPPROTO_ICMPV6: - state = get_redirect_state (af, - IPPROTO_ICMPV6, - source_ip, - 0, - destination_ip, - 0, - NULL); - break; - case IPPROTO_UDP: - state = get_redirect_state (af, - IPPROTO_UDP, - source_ip, - source_port, - destination_ip, - destination_port, - NULL); - break; - case IPPROTO_TCP: - state = get_redirect_state (af, - IPPROTO_TCP, - source_ip, - source_port, - destination_ip, - destination_port, - NULL); - break; - default: - GNUNET_STATISTICS_update (stats, - gettext_noop ("# ICMP packets dropped (not allowed)"), - 1, - GNUNET_NO); - return; - } + { + case IPPROTO_ICMP: + state = get_redirect_state(af, + IPPROTO_ICMP, + source_ip, + 0, + destination_ip, + 0, + NULL); + break; + + case IPPROTO_ICMPV6: + state = get_redirect_state(af, + IPPROTO_ICMPV6, + source_ip, + 0, + destination_ip, + 0, + NULL); + break; + + case IPPROTO_UDP: + state = get_redirect_state(af, + IPPROTO_UDP, + source_ip, + source_port, + destination_ip, + destination_port, + NULL); + break; + + case IPPROTO_TCP: + state = get_redirect_state(af, + IPPROTO_TCP, + source_ip, + source_port, + destination_ip, + destination_port, + NULL); + break; + + default: + GNUNET_STATISTICS_update(stats, + gettext_noop("# ICMP packets dropped (not allowed)"), + 1, + GNUNET_NO); + return; + } if (NULL == state) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("ICMP Packet dropped, have no matching connection information\n")); - return; - } - env = GNUNET_MQ_msg_extra (i2v, - pktlen - sizeof (struct GNUNET_TUN_IcmpHeader), - GNUNET_MESSAGE_TYPE_VPN_ICMP_TO_VPN); - i2v->af = htonl (af); - GNUNET_memcpy (&i2v->icmp_header, - icmp, - pktlen); - send_packet_to_cadet_channel (state, - env); + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("ICMP Packet dropped, have no matching connection information\n")); + return; + } + env = GNUNET_MQ_msg_extra(i2v, + pktlen - sizeof(struct GNUNET_TUN_IcmpHeader), + GNUNET_MESSAGE_TYPE_VPN_ICMP_TO_VPN); + i2v->af = htonl(af); + GNUNET_memcpy(&i2v->icmp_header, + icmp, + pktlen); + send_packet_to_cadet_channel(state, + env); } @@ -2749,11 +2793,11 @@ icmp_from_helper (const struct GNUNET_TUN_IcmpHeader *icmp, * be the original destination address) */ static void -udp_from_helper (const struct GNUNET_TUN_UdpHeader *udp, - size_t pktlen, - int af, - const void *destination_ip, - const void *source_ip) +udp_from_helper(const struct GNUNET_TUN_UdpHeader *udp, + size_t pktlen, + int af, + const void *destination_ip, + const void *source_ip) { struct ChannelState *state; struct GNUNET_MQ_Envelope *env; @@ -2763,52 +2807,53 @@ udp_from_helper (const struct GNUNET_TUN_UdpHeader *udp, char sbuf[INET6_ADDRSTRLEN]; char dbuf[INET6_ADDRSTRLEN]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received UDP packet going from %s:%u to %s:%u\n", - inet_ntop (af, - source_ip, - sbuf, sizeof (sbuf)), - (unsigned int) ntohs (udp->source_port), - inet_ntop (af, - destination_ip, - dbuf, sizeof (dbuf)), - (unsigned int) ntohs (udp->destination_port)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received UDP packet going from %s:%u to %s:%u\n", + inet_ntop(af, + source_ip, + sbuf, sizeof(sbuf)), + (unsigned int)ntohs(udp->source_port), + inet_ntop(af, + destination_ip, + dbuf, sizeof(dbuf)), + (unsigned int)ntohs(udp->destination_port)); } - if (pktlen < sizeof (struct GNUNET_TUN_UdpHeader)) - { - /* blame kernel */ - GNUNET_break (0); - return; - } - if (pktlen != ntohs (udp->len)) - { - /* blame kernel */ - GNUNET_break (0); - return; - } - state = get_redirect_state (af, - IPPROTO_UDP, - source_ip, - ntohs (udp->source_port), - destination_ip, - ntohs (udp->destination_port), - NULL); + + if (pktlen < sizeof(struct GNUNET_TUN_UdpHeader)) + { + /* blame kernel */ + GNUNET_break(0); + return; + } + if (pktlen != ntohs(udp->len)) + { + /* blame kernel */ + GNUNET_break(0); + return; + } + state = get_redirect_state(af, + IPPROTO_UDP, + source_ip, + ntohs(udp->source_port), + destination_ip, + ntohs(udp->destination_port), + NULL); if (NULL == state) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("UDP Packet dropped, have no matching connection information\n")); - return; - } - env = GNUNET_MQ_msg_extra (urm, - pktlen - sizeof (struct GNUNET_TUN_UdpHeader), - GNUNET_MESSAGE_TYPE_VPN_UDP_REPLY); - urm->source_port = htons (0); - urm->destination_port = htons (0); - GNUNET_memcpy (&urm[1], - &udp[1], - pktlen - sizeof (struct GNUNET_TUN_UdpHeader)); - send_packet_to_cadet_channel (state, - env); + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("UDP Packet dropped, have no matching connection information\n")); + return; + } + env = GNUNET_MQ_msg_extra(urm, + pktlen - sizeof(struct GNUNET_TUN_UdpHeader), + GNUNET_MESSAGE_TYPE_VPN_UDP_REPLY); + urm->source_port = htons(0); + urm->destination_port = htons(0); + GNUNET_memcpy(&urm[1], + &udp[1], + pktlen - sizeof(struct GNUNET_TUN_UdpHeader)); + send_packet_to_cadet_channel(state, + env); } @@ -2824,11 +2869,11 @@ udp_from_helper (const struct GNUNET_TUN_UdpHeader *udp, * be the original destination address) */ static void -tcp_from_helper (const struct GNUNET_TUN_TcpHeader *tcp, - size_t pktlen, - int af, - const void *destination_ip, - const void *source_ip) +tcp_from_helper(const struct GNUNET_TUN_TcpHeader *tcp, + size_t pktlen, + int af, + const void *destination_ip, + const void *source_ip) { struct ChannelState *state; char buf[pktlen] GNUNET_ALIGN; @@ -2840,61 +2885,62 @@ tcp_from_helper (const struct GNUNET_TUN_TcpHeader *tcp, { char sbuf[INET6_ADDRSTRLEN]; char dbuf[INET6_ADDRSTRLEN]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received TCP packet with %u bytes going from %s:%u to %s:%u\n", - (unsigned int) (pktlen - sizeof (struct GNUNET_TUN_TcpHeader)), - inet_ntop (af, - source_ip, - sbuf, sizeof (sbuf)), - (unsigned int) ntohs (tcp->source_port), - inet_ntop (af, - destination_ip, - dbuf, sizeof (dbuf)), - (unsigned int) ntohs (tcp->destination_port)); - } - if (pktlen < sizeof (struct GNUNET_TUN_TcpHeader)) - { - /* blame kernel */ - GNUNET_break (0); - return; - } - state = get_redirect_state (af, - IPPROTO_TCP, - source_ip, - ntohs (tcp->source_port), - destination_ip, - ntohs (tcp->destination_port), - NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received TCP packet with %u bytes going from %s:%u to %s:%u\n", + (unsigned int)(pktlen - sizeof(struct GNUNET_TUN_TcpHeader)), + inet_ntop(af, + source_ip, + sbuf, sizeof(sbuf)), + (unsigned int)ntohs(tcp->source_port), + inet_ntop(af, + destination_ip, + dbuf, sizeof(dbuf)), + (unsigned int)ntohs(tcp->destination_port)); + } + + if (pktlen < sizeof(struct GNUNET_TUN_TcpHeader)) + { + /* blame kernel */ + GNUNET_break(0); + return; + } + state = get_redirect_state(af, + IPPROTO_TCP, + source_ip, + ntohs(tcp->source_port), + destination_ip, + ntohs(tcp->destination_port), + NULL); if (NULL == state) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("TCP Packet dropped, have no matching connection information\n")); + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("TCP Packet dropped, have no matching connection information\n")); - return; - } + return; + } /* mug port numbers and crc to avoid information leakage; sender will need to lookup the correct values anyway */ - GNUNET_memcpy (buf, tcp, pktlen); - mtcp = (struct GNUNET_TUN_TcpHeader *) buf; + GNUNET_memcpy(buf, tcp, pktlen); + mtcp = (struct GNUNET_TUN_TcpHeader *)buf; mtcp->source_port = 0; mtcp->destination_port = 0; mtcp->crc = 0; - mlen = sizeof (struct GNUNET_EXIT_TcpDataMessage) + (pktlen - sizeof (struct GNUNET_TUN_TcpHeader)); + mlen = sizeof(struct GNUNET_EXIT_TcpDataMessage) + (pktlen - sizeof(struct GNUNET_TUN_TcpHeader)); if (mlen >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return; - } - env = GNUNET_MQ_msg_extra (tdm, - pktlen - sizeof (struct GNUNET_TUN_TcpHeader), - GNUNET_MESSAGE_TYPE_VPN_TCP_DATA_TO_VPN); - tdm->reserved = htonl (0); - GNUNET_memcpy (&tdm->tcp_header, - buf, - pktlen); - send_packet_to_cadet_channel (state, - env); + { + GNUNET_break(0); + return; + } + env = GNUNET_MQ_msg_extra(tdm, + pktlen - sizeof(struct GNUNET_TUN_TcpHeader), + GNUNET_MESSAGE_TYPE_VPN_TCP_DATA_TO_VPN); + tdm->reserved = htonl(0); + GNUNET_memcpy(&tdm->tcp_header, + buf, + pktlen); + send_packet_to_cadet_channel(state, + env); } @@ -2905,142 +2951,150 @@ tcp_from_helper (const struct GNUNET_TUN_TcpHeader *tcp, * @param message message received from helper */ static int -message_token (void *cls GNUNET_UNUSED, - const struct GNUNET_MessageHeader *message) +message_token(void *cls GNUNET_UNUSED, + const struct GNUNET_MessageHeader *message) { const struct GNUNET_TUN_Layer2PacketHeader *pkt_tun; size_t size; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got %u-byte message of type %u from gnunet-helper-exit\n", - ntohs (message->size), - ntohs (message->type)); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Packets received from TUN"), - 1, GNUNET_NO); - if (ntohs (message->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) - { - GNUNET_break (0); - return GNUNET_OK; - } - size = ntohs (message->size); - if (size < sizeof (struct GNUNET_TUN_Layer2PacketHeader) + sizeof (struct GNUNET_MessageHeader)) - { - GNUNET_break (0); - return GNUNET_OK; - } - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Bytes received from TUN"), - size, GNUNET_NO); - pkt_tun = (const struct GNUNET_TUN_Layer2PacketHeader *) &message[1]; - size -= sizeof (struct GNUNET_TUN_Layer2PacketHeader) + sizeof (struct GNUNET_MessageHeader); - switch (ntohs (pkt_tun->proto)) - { - case ETH_P_IPV4: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got %u-byte message of type %u from gnunet-helper-exit\n", + ntohs(message->size), + ntohs(message->type)); + GNUNET_STATISTICS_update(stats, + gettext_noop("# Packets received from TUN"), + 1, GNUNET_NO); + if (ntohs(message->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) + { + GNUNET_break(0); + return GNUNET_OK; + } + size = ntohs(message->size); + if (size < sizeof(struct GNUNET_TUN_Layer2PacketHeader) + sizeof(struct GNUNET_MessageHeader)) + { + GNUNET_break(0); + return GNUNET_OK; + } + GNUNET_STATISTICS_update(stats, + gettext_noop("# Bytes received from TUN"), + size, GNUNET_NO); + pkt_tun = (const struct GNUNET_TUN_Layer2PacketHeader *)&message[1]; + size -= sizeof(struct GNUNET_TUN_Layer2PacketHeader) + sizeof(struct GNUNET_MessageHeader); + switch (ntohs(pkt_tun->proto)) + { + case ETH_P_IPV4: { const struct GNUNET_TUN_IPv4Header *pkt4; - if (size < sizeof (struct GNUNET_TUN_IPv4Header)) - { - /* Kernel to blame? */ - GNUNET_break (0); - return GNUNET_OK; - } - pkt4 = (const struct GNUNET_TUN_IPv4Header *) &pkt_tun[1]; - if (size != ntohs (pkt4->total_length)) - { - /* Kernel to blame? */ - GNUNET_break (0); - return GNUNET_OK; - } - if (pkt4->header_length * 4 != sizeof (struct GNUNET_TUN_IPv4Header)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("IPv4 packet options received. Ignored.\n")); - return GNUNET_OK; - } - - size -= sizeof (struct GNUNET_TUN_IPv4Header); + if (size < sizeof(struct GNUNET_TUN_IPv4Header)) + { + /* Kernel to blame? */ + GNUNET_break(0); + return GNUNET_OK; + } + pkt4 = (const struct GNUNET_TUN_IPv4Header *)&pkt_tun[1]; + if (size != ntohs(pkt4->total_length)) + { + /* Kernel to blame? */ + GNUNET_break(0); + return GNUNET_OK; + } + if (pkt4->header_length * 4 != sizeof(struct GNUNET_TUN_IPv4Header)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("IPv4 packet options received. Ignored.\n")); + return GNUNET_OK; + } + + size -= sizeof(struct GNUNET_TUN_IPv4Header); switch (pkt4->protocol) - { - case IPPROTO_UDP: - udp_from_helper ((const struct GNUNET_TUN_UdpHeader *) &pkt4[1], size, - AF_INET, - &pkt4->destination_address, - &pkt4->source_address); - break; - case IPPROTO_TCP: - tcp_from_helper ((const struct GNUNET_TUN_TcpHeader *) &pkt4[1], size, - AF_INET, - &pkt4->destination_address, - &pkt4->source_address); - break; - case IPPROTO_ICMP: - icmp_from_helper ((const struct GNUNET_TUN_IcmpHeader *) &pkt4[1], size, - AF_INET, - &pkt4->destination_address, - &pkt4->source_address); - break; - default: - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("IPv4 packet with unsupported next header %u received. Ignored.\n"), - (int) pkt4->protocol); - return GNUNET_OK; - } + { + case IPPROTO_UDP: + udp_from_helper((const struct GNUNET_TUN_UdpHeader *)&pkt4[1], size, + AF_INET, + &pkt4->destination_address, + &pkt4->source_address); + break; + + case IPPROTO_TCP: + tcp_from_helper((const struct GNUNET_TUN_TcpHeader *)&pkt4[1], size, + AF_INET, + &pkt4->destination_address, + &pkt4->source_address); + break; + + case IPPROTO_ICMP: + icmp_from_helper((const struct GNUNET_TUN_IcmpHeader *)&pkt4[1], size, + AF_INET, + &pkt4->destination_address, + &pkt4->source_address); + break; + + default: + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("IPv4 packet with unsupported next header %u received. Ignored.\n"), + (int)pkt4->protocol); + return GNUNET_OK; + } } break; - case ETH_P_IPV6: + + case ETH_P_IPV6: { const struct GNUNET_TUN_IPv6Header *pkt6; - if (size < sizeof (struct GNUNET_TUN_IPv6Header)) - { - /* Kernel to blame? */ - GNUNET_break (0); - return GNUNET_OK; - } - pkt6 = (struct GNUNET_TUN_IPv6Header *) &pkt_tun[1]; - if (size != ntohs (pkt6->payload_length) + sizeof (struct GNUNET_TUN_IPv6Header)) - { - /* Kernel to blame? */ - GNUNET_break (0); - return GNUNET_OK; - } - size -= sizeof (struct GNUNET_TUN_IPv6Header); + if (size < sizeof(struct GNUNET_TUN_IPv6Header)) + { + /* Kernel to blame? */ + GNUNET_break(0); + return GNUNET_OK; + } + pkt6 = (struct GNUNET_TUN_IPv6Header *)&pkt_tun[1]; + if (size != ntohs(pkt6->payload_length) + sizeof(struct GNUNET_TUN_IPv6Header)) + { + /* Kernel to blame? */ + GNUNET_break(0); + return GNUNET_OK; + } + size -= sizeof(struct GNUNET_TUN_IPv6Header); switch (pkt6->next_header) - { - case IPPROTO_UDP: - udp_from_helper ((const struct GNUNET_TUN_UdpHeader *) &pkt6[1], size, - AF_INET6, - &pkt6->destination_address, - &pkt6->source_address); - break; - case IPPROTO_TCP: - tcp_from_helper ((const struct GNUNET_TUN_TcpHeader *) &pkt6[1], size, - AF_INET6, - &pkt6->destination_address, - &pkt6->source_address); - break; - case IPPROTO_ICMPV6: - icmp_from_helper ((const struct GNUNET_TUN_IcmpHeader *) &pkt6[1], size, - AF_INET6, - &pkt6->destination_address, - &pkt6->source_address); - break; - default: - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("IPv6 packet with unsupported next header %d received. Ignored.\n"), - pkt6->next_header); - return GNUNET_OK; - } + { + case IPPROTO_UDP: + udp_from_helper((const struct GNUNET_TUN_UdpHeader *)&pkt6[1], size, + AF_INET6, + &pkt6->destination_address, + &pkt6->source_address); + break; + + case IPPROTO_TCP: + tcp_from_helper((const struct GNUNET_TUN_TcpHeader *)&pkt6[1], size, + AF_INET6, + &pkt6->destination_address, + &pkt6->source_address); + break; + + case IPPROTO_ICMPV6: + icmp_from_helper((const struct GNUNET_TUN_IcmpHeader *)&pkt6[1], size, + AF_INET6, + &pkt6->destination_address, + &pkt6->source_address); + break; + + default: + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("IPv6 packet with unsupported next header %d received. Ignored.\n"), + pkt6->next_header); + return GNUNET_OK; + } } break; - default: - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Packet from unknown protocol %u received. Ignored.\n"), - ntohs (pkt_tun->proto)); - break; - } + + default: + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Packet from unknown protocol %u received. Ignored.\n"), + ntohs(pkt_tun->proto)); + break; + } return GNUNET_OK; } @@ -3054,21 +3108,21 @@ message_token (void *cls GNUNET_UNUSED, * @return initial channel context for the channel */ static void * -new_channel (void *cls, - struct GNUNET_CADET_Channel *channel, - const struct GNUNET_PeerIdentity *initiator) +new_channel(void *cls, + struct GNUNET_CADET_Channel *channel, + const struct GNUNET_PeerIdentity *initiator) { - struct ChannelState *s = GNUNET_new (struct ChannelState); + struct ChannelState *s = GNUNET_new(struct ChannelState); s->is_dns = GNUNET_SYSERR; s->peer = *initiator; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# Inbound CADET channels created"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received inbound channel from `%s'\n", - GNUNET_i2s (initiator)); + GNUNET_STATISTICS_update(stats, + gettext_noop("# Inbound CADET channels created"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received inbound channel from `%s'\n", + GNUNET_i2s(initiator)); s->channel = channel; return s; } @@ -3082,11 +3136,11 @@ new_channel (void *cls, * @param value value to free */ static int -free_iterate (void *cls, - const struct GNUNET_HashCode * hash, - void *value) +free_iterate(void *cls, + const struct GNUNET_HashCode * hash, + void *value) { - GNUNET_free (value); + GNUNET_free(value); return GNUNET_YES; } @@ -3101,7 +3155,7 @@ free_iterate (void *cls, * @param tc scheduler context */ static void -dummy_task (void *cls) +dummy_task(void *cls) { /* just terminate */ } @@ -3113,101 +3167,101 @@ dummy_task (void *cls) * @param cls NULL */ static void -cleanup (void *cls) +cleanup(void *cls) { unsigned int i; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Exit service is shutting down now\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Exit service is shutting down now\n"); if (NULL != helper_handle) - { - GNUNET_HELPER_stop (helper_handle, GNUNET_NO); - helper_handle = NULL; - } + { + GNUNET_HELPER_stop(helper_handle, GNUNET_NO); + helper_handle = NULL; + } if (NULL != regex4) - { - GNUNET_REGEX_announce_cancel (regex4); - regex4 = NULL; - } + { + GNUNET_REGEX_announce_cancel(regex4); + regex4 = NULL; + } if (NULL != regex6) - { - GNUNET_REGEX_announce_cancel (regex6); - regex6 = NULL; - } + { + GNUNET_REGEX_announce_cancel(regex6); + regex6 = NULL; + } if (NULL != services) - { - GNUNET_CONTAINER_multihashmap_iterate (services, - &free_service_record, - NULL); - GNUNET_CONTAINER_multihashmap_destroy (services); - } + { + GNUNET_CONTAINER_multihashmap_iterate(services, + &free_service_record, + NULL); + GNUNET_CONTAINER_multihashmap_destroy(services); + } if (NULL != dns_port) - { - GNUNET_CADET_close_port (dns_port); - dns_port = NULL; - } + { + GNUNET_CADET_close_port(dns_port); + dns_port = NULL; + } if (NULL != cadet_port4) - { - GNUNET_CADET_close_port (cadet_port4); - cadet_port4 = NULL; - } + { + GNUNET_CADET_close_port(cadet_port4); + cadet_port4 = NULL; + } if (NULL != cadet_port6) - { - GNUNET_CADET_close_port (cadet_port6); - cadet_port6 = NULL; - } + { + GNUNET_CADET_close_port(cadet_port6); + cadet_port6 = NULL; + } if (NULL != cadet_handle) - { - GNUNET_CADET_disconnect (cadet_handle); - cadet_handle = NULL; - } + { + GNUNET_CADET_disconnect(cadet_handle); + cadet_handle = NULL; + } if (NULL != connections_map) - { - GNUNET_CONTAINER_multihashmap_iterate (connections_map, - &free_iterate, - NULL); - GNUNET_CONTAINER_multihashmap_destroy (connections_map); - connections_map = NULL; - } + { + GNUNET_CONTAINER_multihashmap_iterate(connections_map, + &free_iterate, + NULL); + GNUNET_CONTAINER_multihashmap_destroy(connections_map); + connections_map = NULL; + } if (NULL != connections_heap) - { - GNUNET_CONTAINER_heap_destroy (connections_heap); - connections_heap = NULL; - } + { + GNUNET_CONTAINER_heap_destroy(connections_heap); + connections_heap = NULL; + } if (NULL != dnsstub) - { - GNUNET_DNSSTUB_stop (dnsstub); - dnsstub = NULL; - } + { + GNUNET_DNSSTUB_stop(dnsstub); + dnsstub = NULL; + } if (NULL != peer_key) - { - GNUNET_free (peer_key); - peer_key = NULL; - } + { + GNUNET_free(peer_key); + peer_key = NULL; + } if (NULL != dht_task) - { - GNUNET_SCHEDULER_cancel (dht_task); - dht_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(dht_task); + dht_task = NULL; + } if (NULL != dht_put) - { - GNUNET_DHT_put_cancel (dht_put); - dht_put = NULL; - } + { + GNUNET_DHT_put_cancel(dht_put); + dht_put = NULL; + } if (NULL != dht) - { - GNUNET_DHT_disconnect (dht); - dht = NULL; - } + { + GNUNET_DHT_disconnect(dht); + dht = NULL; + } if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, - GNUNET_NO); - stats = NULL; - } - for (i=0;i<8;i++) - GNUNET_free_non_null (exit_argv[i]); + { + GNUNET_STATISTICS_destroy(stats, + GNUNET_NO); + stats = NULL; + } + for (i = 0; i < 8; i++) + GNUNET_free_non_null(exit_argv[i]); } @@ -3219,9 +3273,9 @@ cleanup (void *cls) * @param name DNS name of the service */ static void -add_services (int proto, - char *cpy, - const char *name) +add_services(int proto, + char *cpy, + const char *name) { char *redirect; char *hostname; @@ -3230,142 +3284,144 @@ add_services (int proto, char *n; size_t slen; - slen = strlen (name); - GNUNET_assert (slen >= 8); - n = GNUNET_strndup (name, slen - 8 /* remove .gnunet. */); + slen = strlen(name); + GNUNET_assert(slen >= 8); + n = GNUNET_strndup(name, slen - 8 /* remove .gnunet. */); - for (redirect = strtok (cpy, " ;"); redirect != NULL; - redirect = strtok (NULL, " ;")) - { - if (NULL == (hostname = strstr (redirect, ":"))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Option `%s' for domain `%s' is not formatted correctly!\n"), - redirect, - name); - continue; - } - hostname[0] = '\0'; - hostname++; - if (NULL == (hostport = strstr (hostname, ":"))) + for (redirect = strtok(cpy, " ;"); redirect != NULL; + redirect = strtok(NULL, " ;")) { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Option `%s' for domain `%s' is not formatted correctly!\n"), - redirect, - name); - continue; + if (NULL == (hostname = strstr(redirect, ":"))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Option `%s' for domain `%s' is not formatted correctly!\n"), + redirect, + name); + continue; + } + hostname[0] = '\0'; + hostname++; + if (NULL == (hostport = strstr(hostname, ":"))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Option `%s' for domain `%s' is not formatted correctly!\n"), + redirect, + name); + continue; + } + hostport[0] = '\0'; + hostport++; + + int local_port = atoi(redirect); + int remote_port = atoi(hostport); + + if (!((local_port > 0) && (local_port < 65536))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("`%s' is not a valid port number (for domain `%s')!"), + redirect, + name); + continue; + } + if (!((remote_port > 0) && (remote_port < 65536))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("`%s' is not a valid port number (for domain `%s')!"), + hostport, + name); + continue; + } + + serv = GNUNET_new(struct LocalService); + serv->address.proto = proto; + serv->address.port = remote_port; + if (0 == strcmp("localhost4", + hostname)) + { + const char *ip4addr = exit_argv[5]; + + serv->address.af = AF_INET; + GNUNET_assert(1 == inet_pton(AF_INET, + ip4addr, + &serv->address.address.ipv4)); + } + else if (0 == strcmp("localhost6", + hostname)) + { + const char *ip6addr = exit_argv[3]; + + serv->address.af = AF_INET6; + GNUNET_assert(1 == inet_pton(AF_INET6, + ip6addr, + &serv->address.address.ipv6)); + } + else + { + struct addrinfo *res; + int ret; + + ret = getaddrinfo(hostname, + NULL, + NULL, + &res); + if ((0 != ret) || (NULL == res)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("No addresses found for hostname `%s' of service `%s'!\n"), + hostname, + n); + GNUNET_free(serv); + continue; + } + + serv->address.af = res->ai_family; + switch (res->ai_family) + { + case AF_INET: + if (!ipv4_enabled) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Service `%s' configured for IPv4, but IPv4 is disabled!\n"), + n); + freeaddrinfo(res); + GNUNET_free(serv); + continue; + } + serv->address.address.ipv4 + = ((struct sockaddr_in *)res->ai_addr)->sin_addr; + break; + + case AF_INET6: + if (!ipv6_enabled) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Service `%s' configured for IPv4, but IPv4 is disabled!\n"), + n); + freeaddrinfo(res); + GNUNET_free(serv); + continue; + } + serv->address.address.ipv6 + = ((struct sockaddr_in6 *)res->ai_addr)->sin6_addr; + break; + + default: + freeaddrinfo(res); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("No IP addresses found for hostname `%s' of service `%s'!\n"), + hostname, + n); + GNUNET_free(serv); + continue; + } + freeaddrinfo(res); + } + store_service(proto, + n, + local_port, + serv); } - hostport[0] = '\0'; - hostport++; - - int local_port = atoi (redirect); - int remote_port = atoi (hostport); - - if (! ((local_port > 0) && (local_port < 65536))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("`%s' is not a valid port number (for domain `%s')!"), - redirect, - name); - continue; - } - if (! ((remote_port > 0) && (remote_port < 65536))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("`%s' is not a valid port number (for domain `%s')!"), - hostport, - name); - continue; - } - - serv = GNUNET_new (struct LocalService); - serv->address.proto = proto; - serv->address.port = remote_port; - if (0 == strcmp ("localhost4", - hostname)) - { - const char *ip4addr = exit_argv[5]; - - serv->address.af = AF_INET; - GNUNET_assert (1 == inet_pton (AF_INET, - ip4addr, - &serv->address.address.ipv4)); - } - else if (0 == strcmp ("localhost6", - hostname)) - { - const char *ip6addr = exit_argv[3]; - - serv->address.af = AF_INET6; - GNUNET_assert (1 == inet_pton (AF_INET6, - ip6addr, - &serv->address.address.ipv6)); - } - else - { - struct addrinfo *res; - int ret; - - ret = getaddrinfo (hostname, - NULL, - NULL, - &res); - if ( (0 != ret) || (NULL == res) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("No addresses found for hostname `%s' of service `%s'!\n"), - hostname, - n); - GNUNET_free (serv); - continue; - } - - serv->address.af = res->ai_family; - switch (res->ai_family) - { - case AF_INET: - if (! ipv4_enabled) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Service `%s' configured for IPv4, but IPv4 is disabled!\n"), - n); - freeaddrinfo (res); - GNUNET_free (serv); - continue; - } - serv->address.address.ipv4 - = ((struct sockaddr_in *) res->ai_addr)->sin_addr; - break; - case AF_INET6: - if (! ipv6_enabled) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Service `%s' configured for IPv4, but IPv4 is disabled!\n"), - n); - freeaddrinfo (res); - GNUNET_free (serv); - continue; - } - serv->address.address.ipv6 - = ((struct sockaddr_in6 *) res->ai_addr)->sin6_addr; - break; - default: - freeaddrinfo (res); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("No IP addresses found for hostname `%s' of service `%s'!\n"), - hostname, - n); - GNUNET_free (serv); - continue; - } - freeaddrinfo (res); - } - store_service (proto, - n, - local_port, - serv); - } - GNUNET_free (n); + GNUNET_free(n); } @@ -3376,36 +3432,36 @@ add_services (int proto, * @param section name of section in config */ static void -read_service_conf (void *cls, - const char *section) +read_service_conf(void *cls, + const char *section) { char *cpy; - if ((strlen (section) < 8) || - (0 != strcmp (".gnunet.", section + (strlen (section) - 8)))) + if ((strlen(section) < 8) || + (0 != strcmp(".gnunet.", section + (strlen(section) - 8)))) return; if (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (cfg, - section, - "UDP_REDIRECTS", - &cpy)) - { - add_services (IPPROTO_UDP, - cpy, - section); - GNUNET_free (cpy); - } + GNUNET_CONFIGURATION_get_value_string(cfg, + section, + "UDP_REDIRECTS", + &cpy)) + { + add_services(IPPROTO_UDP, + cpy, + section); + GNUNET_free(cpy); + } if (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (cfg, - section, - "TCP_REDIRECTS", - &cpy)) - { - add_services (IPPROTO_TCP, - cpy, - section); - GNUNET_free (cpy); - } + GNUNET_CONFIGURATION_get_value_string(cfg, + section, + "TCP_REDIRECTS", + &cpy)) + { + add_services(IPPROTO_TCP, + cpy, + section); + GNUNET_free(cpy); + } } @@ -3416,7 +3472,7 @@ read_service_conf (void *cls, * @param cls closure */ static void -do_dht_put (void *cls); +do_dht_put(void *cls); /** @@ -3426,7 +3482,7 @@ do_dht_put (void *cls); * @param cls closure, NULL */ static void -dht_put_cont (void *cls) +dht_put_cont(void *cls) { dht_put = NULL; } @@ -3439,37 +3495,37 @@ dht_put_cont (void *cls) * @param cls closure */ static void -do_dht_put (void *cls) +do_dht_put(void *cls) { struct GNUNET_TIME_Absolute expiration; - dht_task = GNUNET_SCHEDULER_add_delayed (DHT_PUT_FREQUENCY, - &do_dht_put, - NULL); - expiration = GNUNET_TIME_absolute_ntoh (dns_advertisement.expiration_time); - if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value_us < + dht_task = GNUNET_SCHEDULER_add_delayed(DHT_PUT_FREQUENCY, + &do_dht_put, + NULL); + expiration = GNUNET_TIME_absolute_ntoh(dns_advertisement.expiration_time); + if (GNUNET_TIME_absolute_get_remaining(expiration).rel_value_us < GNUNET_TIME_UNIT_HOURS.rel_value_us) - { - /* refresh advertisement */ - expiration = GNUNET_TIME_relative_to_absolute (DNS_ADVERTISEMENT_TIMEOUT); - dns_advertisement.expiration_time = GNUNET_TIME_absolute_hton (expiration); - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_eddsa_sign (peer_key, - &dns_advertisement.purpose, - &dns_advertisement.signature)); - } + { + /* refresh advertisement */ + expiration = GNUNET_TIME_relative_to_absolute(DNS_ADVERTISEMENT_TIMEOUT); + dns_advertisement.expiration_time = GNUNET_TIME_absolute_hton(expiration); + GNUNET_assert(GNUNET_OK == + GNUNET_CRYPTO_eddsa_sign(peer_key, + &dns_advertisement.purpose, + &dns_advertisement.signature)); + } if (NULL != dht_put) - GNUNET_DHT_put_cancel (dht_put); - dht_put = GNUNET_DHT_put (dht, - &dht_put_key, - 1 /* replication */, - GNUNET_DHT_RO_NONE, - GNUNET_BLOCK_TYPE_DNS, - sizeof (struct GNUNET_DNS_Advertisement), - &dns_advertisement, - expiration, - &dht_put_cont, - NULL); + GNUNET_DHT_put_cancel(dht_put); + dht_put = GNUNET_DHT_put(dht, + &dht_put_key, + 1 /* replication */, + GNUNET_DHT_RO_NONE, + GNUNET_BLOCK_TYPE_DNS, + sizeof(struct GNUNET_DNS_Advertisement), + &dns_advertisement, + expiration, + &dht_put_cont, + NULL); } @@ -3478,48 +3534,48 @@ do_dht_put (void *cls) * are supported by the OS) according to our configuration. */ static void -parse_ip_options () +parse_ip_options() { - ipv4_exit = GNUNET_CONFIGURATION_get_value_yesno (cfg, - "exit", - "EXIT_IPV4"); - ipv6_exit = GNUNET_CONFIGURATION_get_value_yesno (cfg, - "exit", - "EXIT_IPV6"); - ipv4_enabled = GNUNET_CONFIGURATION_get_value_yesno (cfg, - "exit", - "ENABLE_IPV4"); - ipv6_enabled = GNUNET_CONFIGURATION_get_value_yesno (cfg, - "exit", - "ENABLE_IPV6"); - if ( (ipv4_exit || ipv4_enabled) && - GNUNET_OK != GNUNET_NETWORK_test_pf (PF_INET)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("This system does not support IPv4, will disable IPv4 functions despite them being enabled in the configuration\n")); - ipv4_exit = GNUNET_NO; - ipv4_enabled = GNUNET_NO; - } - if ( (ipv6_exit || ipv6_enabled) && - GNUNET_OK != GNUNET_NETWORK_test_pf (PF_INET6)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("This system does not support IPv6, will disable IPv6 functions despite them being enabled in the configuration\n")); - ipv6_exit = GNUNET_NO; - ipv6_enabled = GNUNET_NO; - } - if (ipv4_exit && (! ipv4_enabled)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Cannot enable IPv4 exit but disable IPv4 on TUN interface, will use ENABLE_IPv4=YES\n")); - ipv4_enabled = GNUNET_YES; - } - if (ipv6_exit && (! ipv6_enabled)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Cannot enable IPv6 exit but disable IPv6 on TUN interface, will use ENABLE_IPv6=YES\n")); - ipv6_enabled = GNUNET_YES; - } + ipv4_exit = GNUNET_CONFIGURATION_get_value_yesno(cfg, + "exit", + "EXIT_IPV4"); + ipv6_exit = GNUNET_CONFIGURATION_get_value_yesno(cfg, + "exit", + "EXIT_IPV6"); + ipv4_enabled = GNUNET_CONFIGURATION_get_value_yesno(cfg, + "exit", + "ENABLE_IPV4"); + ipv6_enabled = GNUNET_CONFIGURATION_get_value_yesno(cfg, + "exit", + "ENABLE_IPV6"); + if ((ipv4_exit || ipv4_enabled) && + GNUNET_OK != GNUNET_NETWORK_test_pf(PF_INET)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("This system does not support IPv4, will disable IPv4 functions despite them being enabled in the configuration\n")); + ipv4_exit = GNUNET_NO; + ipv4_enabled = GNUNET_NO; + } + if ((ipv6_exit || ipv6_enabled) && + GNUNET_OK != GNUNET_NETWORK_test_pf(PF_INET6)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("This system does not support IPv6, will disable IPv6 functions despite them being enabled in the configuration\n")); + ipv6_exit = GNUNET_NO; + ipv6_enabled = GNUNET_NO; + } + if (ipv4_exit && (!ipv4_enabled)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Cannot enable IPv4 exit but disable IPv4 on TUN interface, will use ENABLE_IPv4=YES\n")); + ipv4_enabled = GNUNET_YES; + } + if (ipv6_exit && (!ipv6_enabled)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Cannot enable IPv6 exit but disable IPv6 on TUN interface, will use ENABLE_IPv6=YES\n")); + ipv6_enabled = GNUNET_YES; + } } @@ -3528,71 +3584,71 @@ parse_ip_options () * advertise the DNS exit (if applicable). */ static void -advertise_dns_exit () +advertise_dns_exit() { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (dns_request, - GNUNET_MESSAGE_TYPE_VPN_DNS_TO_INTERNET, - struct DnsResponseMessage, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(dns_request, + GNUNET_MESSAGE_TYPE_VPN_DNS_TO_INTERNET, + struct DnsResponseMessage, + NULL), + GNUNET_MQ_handler_end() }; char *dns_exit; struct GNUNET_HashCode port; if (GNUNET_YES != - GNUNET_CONFIGURATION_get_value_yesno (cfg, - "exit", - "EXIT_DNS")) + GNUNET_CONFIGURATION_get_value_yesno(cfg, + "exit", + "EXIT_DNS")) return; - GNUNET_assert (NULL != (dnsstub = GNUNET_DNSSTUB_start (128))); + GNUNET_assert(NULL != (dnsstub = GNUNET_DNSSTUB_start(128))); dns_exit = NULL; /* TODO: support using multiple DNS resolvers */ - if ( (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "exit", - "DNS_RESOLVER", - &dns_exit)) || - (GNUNET_OK != - GNUNET_DNSSTUB_add_dns_ip (dnsstub, - dns_exit)) ) - { - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, - "dns", - "DNS_RESOLVER", - _("need a valid IPv4 or IPv6 address\n")); - GNUNET_free_non_null (dns_exit); - return; - } + if ((GNUNET_OK != + GNUNET_CONFIGURATION_get_value_string(cfg, + "exit", + "DNS_RESOLVER", + &dns_exit)) || + (GNUNET_OK != + GNUNET_DNSSTUB_add_dns_ip(dnsstub, + dns_exit))) + { + GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_ERROR, + "dns", + "DNS_RESOLVER", + _("need a valid IPv4 or IPv6 address\n")); + GNUNET_free_non_null(dns_exit); + return; + } /* open port */ - GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_INTERNET_RESOLVER, - strlen (GNUNET_APPLICATION_PORT_INTERNET_RESOLVER), - &port); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Opening CADET port %s for DNS exit service\n", - GNUNET_h2s (&port)); - dns_port = GNUNET_CADET_open_port (cadet_handle, - &port, - &new_channel, - NULL, - NULL, - &clean_channel, - handlers); + GNUNET_CRYPTO_hash(GNUNET_APPLICATION_PORT_INTERNET_RESOLVER, + strlen(GNUNET_APPLICATION_PORT_INTERNET_RESOLVER), + &port); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Opening CADET port %s for DNS exit service\n", + GNUNET_h2s(&port)); + dns_port = GNUNET_CADET_open_port(cadet_handle, + &port, + &new_channel, + NULL, + NULL, + &clean_channel, + handlers); /* advertise exit */ - dht = GNUNET_DHT_connect (cfg, - 1); - peer_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg); - GNUNET_CRYPTO_eddsa_key_get_public (peer_key, - &dns_advertisement.peer.public_key); - dns_advertisement.purpose.size = htonl (sizeof (struct GNUNET_DNS_Advertisement) - - sizeof (struct GNUNET_CRYPTO_EddsaSignature)); - dns_advertisement.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_DNS_RECORD); - GNUNET_CRYPTO_hash ("dns", - strlen ("dns"), - &dht_put_key); - dht_task = GNUNET_SCHEDULER_add_now (&do_dht_put, - NULL); - GNUNET_free (dns_exit); + dht = GNUNET_DHT_connect(cfg, + 1); + peer_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration(cfg); + GNUNET_CRYPTO_eddsa_key_get_public(peer_key, + &dns_advertisement.peer.public_key); + dns_advertisement.purpose.size = htonl(sizeof(struct GNUNET_DNS_Advertisement) - + sizeof(struct GNUNET_CRYPTO_EddsaSignature)); + dns_advertisement.purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_DNS_RECORD); + GNUNET_CRYPTO_hash("dns", + strlen("dns"), + &dht_put_key); + dht_task = GNUNET_SCHEDULER_add_now(&do_dht_put, + NULL); + GNUNET_free(dns_exit); } @@ -3602,7 +3658,7 @@ advertise_dns_exit () * @return #GNUNET_OK on success, #GNUNET_SYSERR if we should shutdown */ static int -setup_exit_helper_args () +setup_exit_helper_args() { char *exit_ifname; char *tun_ifname; @@ -3611,133 +3667,133 @@ setup_exit_helper_args () char *ipv4addr; char *ipv4mask; - exit_argv[0] = GNUNET_strdup ("exit-gnunet"); + exit_argv[0] = GNUNET_strdup("exit-gnunet"); if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, - "exit", - "TUN_IFNAME", - &tun_ifname)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "EXIT", - "TUN_IFNAME"); - return GNUNET_SYSERR; - } + GNUNET_CONFIGURATION_get_value_string(cfg, + "exit", + "TUN_IFNAME", + &tun_ifname)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "EXIT", + "TUN_IFNAME"); + return GNUNET_SYSERR; + } exit_argv[1] = tun_ifname; if (ipv4_enabled) - { - if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, - "exit", - "EXIT_IFNAME", - &exit_ifname)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "EXIT", - "EXIT_IFNAME"); - return GNUNET_SYSERR; + { + if (GNUNET_SYSERR == + GNUNET_CONFIGURATION_get_value_string(cfg, + "exit", + "EXIT_IFNAME", + &exit_ifname)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "EXIT", + "EXIT_IFNAME"); + return GNUNET_SYSERR; + } + exit_argv[2] = exit_ifname; } - exit_argv[2] = exit_ifname; - } else - { - exit_argv[2] = GNUNET_strdup ("-"); - } + { + exit_argv[2] = GNUNET_strdup("-"); + } if (GNUNET_YES == ipv6_enabled) - { - ipv6addr = NULL; - if ( (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, + { + ipv6addr = NULL; + if ((GNUNET_SYSERR == + GNUNET_CONFIGURATION_get_value_string(cfg, "exit", "IPV6ADDR", - &ipv6addr) || - (1 != inet_pton (AF_INET6, + &ipv6addr) || + (1 != inet_pton(AF_INET6, ipv6addr, - &exit_ipv6addr))) ) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "EXIT", - "IPV6ADDR"); - GNUNET_free_non_null (ipv6addr); - return GNUNET_SYSERR; - } - exit_argv[3] = ipv6addr; - if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, - "exit", - "IPV6PREFIX", - &ipv6prefix_s)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "EXIT", - "IPV6PREFIX"); - return GNUNET_SYSERR; - } - exit_argv[4] = ipv6prefix_s; - if ( (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (cfg, + &exit_ipv6addr)))) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "EXIT", + "IPV6ADDR"); + GNUNET_free_non_null(ipv6addr); + return GNUNET_SYSERR; + } + exit_argv[3] = ipv6addr; + if (GNUNET_SYSERR == + GNUNET_CONFIGURATION_get_value_string(cfg, + "exit", + "IPV6PREFIX", + &ipv6prefix_s)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "EXIT", + "IPV6PREFIX"); + return GNUNET_SYSERR; + } + exit_argv[4] = ipv6prefix_s; + if ((GNUNET_OK != + GNUNET_CONFIGURATION_get_value_number(cfg, "exit", - "IPV6PREFIX", - &ipv6prefix)) || - (ipv6prefix >= 127) ) - { - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, - "EXIT", - "IPV6PREFIX", - _("Must be a number")); - return GNUNET_SYSERR; + "IPV6PREFIX", + &ipv6prefix)) || + (ipv6prefix >= 127)) + { + GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_ERROR, + "EXIT", + "IPV6PREFIX", + _("Must be a number")); + return GNUNET_SYSERR; + } } - } else - { - /* IPv6 explicitly disabled */ - exit_argv[3] = GNUNET_strdup ("-"); - exit_argv[4] = GNUNET_strdup ("-"); - } + { + /* IPv6 explicitly disabled */ + exit_argv[3] = GNUNET_strdup("-"); + exit_argv[4] = GNUNET_strdup("-"); + } if (GNUNET_YES == ipv4_enabled) - { - ipv4addr = NULL; - if ( (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, + { + ipv4addr = NULL; + if ((GNUNET_SYSERR == + GNUNET_CONFIGURATION_get_value_string(cfg, "exit", "IPV4ADDR", - &ipv4addr) || - (1 != inet_pton (AF_INET, + &ipv4addr) || + (1 != inet_pton(AF_INET, ipv4addr, - &exit_ipv4addr))) ) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "EXIT", - "IPV4ADDR"); - GNUNET_free_non_null (ipv4addr); - return GNUNET_SYSERR; - } - exit_argv[5] = ipv4addr; - ipv4mask = NULL; - if ( (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, + &exit_ipv4addr)))) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "EXIT", + "IPV4ADDR"); + GNUNET_free_non_null(ipv4addr); + return GNUNET_SYSERR; + } + exit_argv[5] = ipv4addr; + ipv4mask = NULL; + if ((GNUNET_SYSERR == + GNUNET_CONFIGURATION_get_value_string(cfg, "exit", "IPV4MASK", - &ipv4mask) || - (1 != inet_pton (AF_INET, + &ipv4mask) || + (1 != inet_pton(AF_INET, ipv4mask, - &exit_ipv4mask))) ) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "EXIT", - "IPV4MASK"); - GNUNET_free_non_null (ipv4mask); - return GNUNET_SYSERR; + &exit_ipv4mask)))) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "EXIT", + "IPV4MASK"); + GNUNET_free_non_null(ipv4mask); + return GNUNET_SYSERR; + } + exit_argv[6] = ipv4mask; } - exit_argv[6] = ipv4mask; - } else - { - /* IPv4 explicitly disabled */ - exit_argv[5] = GNUNET_strdup ("-"); - exit_argv[6] = GNUNET_strdup ("-"); - } + { + /* IPv4 explicitly disabled */ + exit_argv[5] = GNUNET_strdup("-"); + exit_argv[6] = GNUNET_strdup("-"); + } exit_argv[7] = NULL; return GNUNET_OK; } @@ -3752,29 +3808,29 @@ setup_exit_helper_args () * @param cfg_ configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg_) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg_) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (icmp_remote, - GNUNET_MESSAGE_TYPE_VPN_ICMP_TO_INTERNET, - struct GNUNET_EXIT_IcmpInternetMessage, - NULL), - GNUNET_MQ_hd_var_size (udp_remote, - GNUNET_MESSAGE_TYPE_VPN_UDP_TO_INTERNET, - struct GNUNET_EXIT_UdpInternetMessage, - NULL), - GNUNET_MQ_hd_var_size (tcp_remote, - GNUNET_MESSAGE_TYPE_VPN_TCP_TO_INTERNET_START, - struct GNUNET_EXIT_TcpInternetStartMessage, - NULL), - GNUNET_MQ_hd_var_size (tcp_data, - GNUNET_MESSAGE_TYPE_VPN_TCP_DATA_TO_EXIT, - struct GNUNET_EXIT_TcpDataMessage, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(icmp_remote, + GNUNET_MESSAGE_TYPE_VPN_ICMP_TO_INTERNET, + struct GNUNET_EXIT_IcmpInternetMessage, + NULL), + GNUNET_MQ_hd_var_size(udp_remote, + GNUNET_MESSAGE_TYPE_VPN_UDP_TO_INTERNET, + struct GNUNET_EXIT_UdpInternetMessage, + NULL), + GNUNET_MQ_hd_var_size(tcp_remote, + GNUNET_MESSAGE_TYPE_VPN_TCP_TO_INTERNET_START, + struct GNUNET_EXIT_TcpInternetStartMessage, + NULL), + GNUNET_MQ_hd_var_size(tcp_data, + GNUNET_MESSAGE_TYPE_VPN_TCP_DATA_TO_EXIT, + struct GNUNET_EXIT_TcpDataMessage, + NULL), + GNUNET_MQ_handler_end() }; struct GNUNET_HashCode port; char *policy; @@ -3784,157 +3840,157 @@ run (void *cls, cfg = cfg_; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (cfg, - "exit", - "MAX_CONNECTIONS", - &max_connections)) + GNUNET_CONFIGURATION_get_value_number(cfg, + "exit", + "MAX_CONNECTIONS", + &max_connections)) max_connections = 1024; - parse_ip_options (); - binary = GNUNET_OS_get_suid_binary_path (cfg, "gnunet-helper-exit"); - if ( (ipv4_exit) || (ipv6_exit) ) - { - if (GNUNET_YES != - GNUNET_OS_check_helper_binary (binary, - GNUNET_YES, - "gnunet-vpn - - - 169.1.3.7 255.255.255.0")) //no nat, ipv4 only - { - GNUNET_free (binary); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("`%s' is not SUID or the path is invalid, EXIT will not work\n"), - "gnunet-helper-exit"); - GNUNET_SCHEDULER_add_shutdown (&dummy_task, - NULL); - global_ret = 1; + parse_ip_options(); + binary = GNUNET_OS_get_suid_binary_path(cfg, "gnunet-helper-exit"); + if ((ipv4_exit) || (ipv6_exit)) + { + if (GNUNET_YES != + GNUNET_OS_check_helper_binary(binary, + GNUNET_YES, + "gnunet-vpn - - - 169.1.3.7 255.255.255.0")) //no nat, ipv4 only + { + GNUNET_free(binary); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("`%s' is not SUID or the path is invalid, EXIT will not work\n"), + "gnunet-helper-exit"); + GNUNET_SCHEDULER_add_shutdown(&dummy_task, + NULL); + global_ret = 1; + return; + } + } + if (!(ipv4_enabled || ipv6_enabled)) + { + GNUNET_free(binary); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No useful service enabled. Exiting.\n")); + GNUNET_SCHEDULER_shutdown(); return; } - } - if (! (ipv4_enabled || ipv6_enabled)) - { - GNUNET_free (binary); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No useful service enabled. Exiting.\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_SCHEDULER_add_shutdown (&cleanup, - NULL); - stats = GNUNET_STATISTICS_create ("exit", - cfg); - cadet_handle = GNUNET_CADET_connect (cfg); + GNUNET_SCHEDULER_add_shutdown(&cleanup, + NULL); + stats = GNUNET_STATISTICS_create("exit", + cfg); + cadet_handle = GNUNET_CADET_connect(cfg); if (NULL == cadet_handle) - { - GNUNET_free (binary); - GNUNET_SCHEDULER_shutdown (); - return; - } - advertise_dns_exit (); + { + GNUNET_free(binary); + GNUNET_SCHEDULER_shutdown(); + return; + } + advertise_dns_exit(); if (GNUNET_OK != - setup_exit_helper_args ()) - { - GNUNET_free (binary); - GNUNET_SCHEDULER_shutdown (); - return; - } + setup_exit_helper_args()) + { + GNUNET_free(binary); + GNUNET_SCHEDULER_shutdown(); + return; + } - services = GNUNET_CONTAINER_multihashmap_create (65536, - GNUNET_NO); - connections_map = GNUNET_CONTAINER_multihashmap_create (65536, - GNUNET_NO); - connections_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); - GNUNET_CONFIGURATION_iterate_sections (cfg, - &read_service_conf, - NULL); + services = GNUNET_CONTAINER_multihashmap_create(65536, + GNUNET_NO); + connections_map = GNUNET_CONTAINER_multihashmap_create(65536, + GNUNET_NO); + connections_heap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN); + GNUNET_CONFIGURATION_iterate_sections(cfg, + &read_service_conf, + NULL); /* Cadet handle acquired, now open ports and announce regular expressions matching our exit */ - if ( (GNUNET_YES == ipv4_enabled) && - (GNUNET_YES == ipv4_exit) ) - { - GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_IPV4_GATEWAY, - strlen (GNUNET_APPLICATION_PORT_IPV4_GATEWAY), - &port); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Opening CADET port %s for IPv4 gateway service\n", - GNUNET_h2s (&port)); - cadet_port4 = GNUNET_CADET_open_port (cadet_handle, - &port, - &new_channel, - NULL, - NULL, - &clean_channel, - handlers); - policy = NULL; - if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "exit", - "EXIT_RANGE_IPV4_POLICY", - &policy)) - regex = NULL; - else - regex = GNUNET_TUN_ipv4policy2regex (policy); - GNUNET_free_non_null (policy); - if (NULL != regex) - { - (void) GNUNET_asprintf (&prefixed_regex, - "%s%s", - GNUNET_APPLICATION_TYPE_EXIT_REGEX_PREFIX, - regex); - regex4 = GNUNET_REGEX_announce (cfg, - prefixed_regex, - REGEX_REFRESH_FREQUENCY, - REGEX_MAX_PATH_LEN_IPV4); - GNUNET_free (regex); - GNUNET_free (prefixed_regex); + if ((GNUNET_YES == ipv4_enabled) && + (GNUNET_YES == ipv4_exit)) + { + GNUNET_CRYPTO_hash(GNUNET_APPLICATION_PORT_IPV4_GATEWAY, + strlen(GNUNET_APPLICATION_PORT_IPV4_GATEWAY), + &port); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Opening CADET port %s for IPv4 gateway service\n", + GNUNET_h2s(&port)); + cadet_port4 = GNUNET_CADET_open_port(cadet_handle, + &port, + &new_channel, + NULL, + NULL, + &clean_channel, + handlers); + policy = NULL; + if (GNUNET_OK != + GNUNET_CONFIGURATION_get_value_string(cfg, + "exit", + "EXIT_RANGE_IPV4_POLICY", + &policy)) + regex = NULL; + else + regex = GNUNET_TUN_ipv4policy2regex(policy); + GNUNET_free_non_null(policy); + if (NULL != regex) + { + (void)GNUNET_asprintf(&prefixed_regex, + "%s%s", + GNUNET_APPLICATION_TYPE_EXIT_REGEX_PREFIX, + regex); + regex4 = GNUNET_REGEX_announce(cfg, + prefixed_regex, + REGEX_REFRESH_FREQUENCY, + REGEX_MAX_PATH_LEN_IPV4); + GNUNET_free(regex); + GNUNET_free(prefixed_regex); + } } - } - if ( (GNUNET_YES == ipv6_enabled) && (GNUNET_YES == ipv6_exit) ) - { - GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_IPV6_GATEWAY, - strlen (GNUNET_APPLICATION_PORT_IPV6_GATEWAY), - &port); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Opening CADET port %s for IPv6 gateway service\n", - GNUNET_h2s (&port)); - cadet_port6 = GNUNET_CADET_open_port (cadet_handle, - &port, - &new_channel, - NULL, - NULL, - &clean_channel, - handlers); - policy = NULL; - if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "exit", - "EXIT_RANGE_IPV6_POLICY", - &policy)) - regex = NULL; - else - regex = GNUNET_TUN_ipv6policy2regex (policy); - GNUNET_free_non_null (policy); - if (NULL != regex) - { - (void) GNUNET_asprintf (&prefixed_regex, - "%s%s", - GNUNET_APPLICATION_TYPE_EXIT_REGEX_PREFIX, - regex); - regex6 = GNUNET_REGEX_announce (cfg, - prefixed_regex, - REGEX_REFRESH_FREQUENCY, - REGEX_MAX_PATH_LEN_IPV6); - GNUNET_free (regex); - GNUNET_free (prefixed_regex); + if ((GNUNET_YES == ipv6_enabled) && (GNUNET_YES == ipv6_exit)) + { + GNUNET_CRYPTO_hash(GNUNET_APPLICATION_PORT_IPV6_GATEWAY, + strlen(GNUNET_APPLICATION_PORT_IPV6_GATEWAY), + &port); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Opening CADET port %s for IPv6 gateway service\n", + GNUNET_h2s(&port)); + cadet_port6 = GNUNET_CADET_open_port(cadet_handle, + &port, + &new_channel, + NULL, + NULL, + &clean_channel, + handlers); + policy = NULL; + if (GNUNET_OK != + GNUNET_CONFIGURATION_get_value_string(cfg, + "exit", + "EXIT_RANGE_IPV6_POLICY", + &policy)) + regex = NULL; + else + regex = GNUNET_TUN_ipv6policy2regex(policy); + GNUNET_free_non_null(policy); + if (NULL != regex) + { + (void)GNUNET_asprintf(&prefixed_regex, + "%s%s", + GNUNET_APPLICATION_TYPE_EXIT_REGEX_PREFIX, + regex); + regex6 = GNUNET_REGEX_announce(cfg, + prefixed_regex, + REGEX_REFRESH_FREQUENCY, + REGEX_MAX_PATH_LEN_IPV6); + GNUNET_free(regex); + GNUNET_free(prefixed_regex); + } } - } - helper_handle = GNUNET_HELPER_start (GNUNET_NO, - binary, - exit_argv, - &message_token, - NULL, - NULL); - GNUNET_free (binary); + helper_handle = GNUNET_HELPER_start(GNUNET_NO, + binary, + exit_argv, + &message_token, + NULL, + NULL); + GNUNET_free(binary); } @@ -3946,28 +4002,28 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, - char *const *argv) +main(int argc, + char *const *argv) { static const struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; if (GNUNET_OK != - GNUNET_STRINGS_get_utf8_args (argc, - argv, - &argc, - &argv)) + GNUNET_STRINGS_get_utf8_args(argc, + argv, + &argc, + &argv)) return 2; return (GNUNET_OK == - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-daemon-exit", - gettext_noop ("Daemon to run to provide an IP exit node for the VPN"), - options, - &run, - NULL)) ? global_ret : 1; + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-daemon-exit", + gettext_noop("Daemon to run to provide an IP exit node for the VPN"), + options, + &run, + NULL)) ? global_ret : 1; } diff --git a/src/exit/gnunet-helper-exit-windows.c b/src/exit/gnunet-helper-exit-windows.c index 8bae7ca86..0ffd28148 100644 --- a/src/exit/gnunet-helper-exit-windows.c +++ b/src/exit/gnunet-helper-exit-windows.c @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -66,7 +66,7 @@ #if DEBUG /* FIXME: define with varargs... */ -#define LOG_DEBUG(msg) fprintf (stderr, "%s", msg); +#define LOG_DEBUG(msg) fprintf(stderr, "%s", msg); #else #define LOG_DEBUG(msg) do {} while (0) #endif @@ -162,9 +162,7 @@ static char device_guid[256]; /** * Possible states of an IO facility. */ -enum IO_State -{ - +enum IO_State { /** * overlapped I/O is ready for work */ @@ -190,15 +188,13 @@ enum IO_State * overlapped I/O has failed, stop processing */ IOSTATE_FAILED - }; /** * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling */ -struct io_facility -{ +struct io_facility { /** * The mode the state machine associated with this object is in. */ @@ -243,12 +239,12 @@ struct io_facility /** * ReOpenFile is only available as of XP SP2 and 2003 SP1 */ -WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD); +WINBASEAPI HANDLE WINAPI ReOpenFile(HANDLE, DWORD, DWORD, DWORD); /** * IsWow64Process definition for our is_win64, as this is a kernel function */ -typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); +typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL); /** @@ -261,7 +257,7 @@ typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); * @param n the length of the string to copy, including its terminating null * byte * @return the length of the string that was copied, excluding the terminating - * null byte + * null byte */ size_t GNUNET_strlcpy(char *dst, const char *src, size_t n) @@ -269,9 +265,9 @@ GNUNET_strlcpy(char *dst, const char *src, size_t n) size_t ret; size_t slen; - GNUNET_assert (0 != n); - slen = strnlen (src, n - 1); - memcpy (dst, src, slen); + GNUNET_assert(0 != n); + slen = strnlen(src, n - 1); + memcpy(dst, src, slen); dst[slen] = '\0'; return slen; } @@ -283,7 +279,7 @@ GNUNET_strlcpy(char *dst, const char *src, size_t n) * @return true if */ BOOL -is_win64 () +is_win64() { #if defined(_WIN64) //this is a win64 binary, @@ -292,10 +288,10 @@ is_win64 () //this is a 32bit binary, and we need to check if we are running in WOW64 BOOL success = FALSE; BOOL on_wow64 = FALSE; - LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process"); + LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process"); if (NULL != IsWow64Process) - success = IsWow64Process (GetCurrentProcess (), &on_wow64); + success = IsWow64Process(GetCurrentProcess(), &on_wow64); return success && on_wow64; #endif @@ -309,22 +305,22 @@ is_win64 () * * EPIPE (could not read STDOUT) */ static int -execute_shellcommand (const char *command) +execute_shellcommand(const char *command) { FILE *pipe; - if ( (NULL == command) || - (NULL == (pipe = _popen (command, "rt"))) ) + if ((NULL == command) || + (NULL == (pipe = _popen(command, "rt")))) return EINVAL; #if DEBUG - fprintf (stderr, "DEBUG: Command output: \n"); + fprintf(stderr, "DEBUG: Command output: \n"); char output[LINE_LEN]; - while (NULL != fgets (output, sizeof (output), pipe)) - fprintf (stderr, "%s", output); + while (NULL != fgets(output, sizeof(output), pipe)) + fprintf(stderr, "%s", output); #endif - return _pclose (pipe); + return _pclose(pipe); } @@ -335,7 +331,7 @@ execute_shellcommand (const char *command) * @param prefix_len the length of the network-prefix */ static int -set_address6 (const char *address, unsigned long prefix_len) +set_address6(const char *address, unsigned long prefix_len) { int ret = EINVAL; char command[LINE_LEN]; @@ -344,29 +340,29 @@ set_address6 (const char *address, unsigned long prefix_len) /* * parse the new address */ - memset (&sa6, 0, sizeof (struct sockaddr_in6)); + memset(&sa6, 0, sizeof(struct sockaddr_in6)); sa6.sin6_family = AF_INET6; - if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr)) + if (1 != inet_pton(AF_INET6, address, &sa6.sin6_addr.s6_addr)) { - fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address, - strerror (errno)); + fprintf(stderr, "ERROR: Failed to parse address `%s': %s\n", address, + strerror(errno)); return -1; } /* * prepare the command */ - snprintf (command, LINE_LEN, - "netsh interface ipv6 add address \"%s\" %s/%d store=active", - device_visible_name, address, prefix_len); + snprintf(command, LINE_LEN, + "netsh interface ipv6 add address \"%s\" %s/%d store=active", + device_visible_name, address, prefix_len); /* * Set the address */ - ret = execute_shellcommand (command); + ret = execute_shellcommand(command); /* Did it work?*/ if (0 != ret) - fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret)); + fprintf(stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror(ret)); return ret; } @@ -377,7 +373,7 @@ set_address6 (const char *address, unsigned long prefix_len) * @param address the IPv4-Address */ static void -remove_address6 (const char *address) +remove_address6(const char *address) { char command[LINE_LEN]; int ret = EINVAL; @@ -386,17 +382,17 @@ remove_address6 (const char *address) /* * prepare the command */ - snprintf (command, LINE_LEN, - "netsh interface ipv6 delete address \"%s\" store=persistent", - device_visible_name); + snprintf(command, LINE_LEN, + "netsh interface ipv6 delete address \"%s\" store=persistent", + device_visible_name); /* * Set the address */ - ret = execute_shellcommand (command); + ret = execute_shellcommand(command); /* Did it work?*/ if (0 != ret) - fprintf (stderr, "FATAL: removing IPv6 address failed: %s\n", strerror (ret)); + fprintf(stderr, "FATAL: removing IPv6 address failed: %s\n", strerror(ret)); } @@ -407,21 +403,22 @@ remove_address6 (const char *address) * @param mask the netmask */ static int -set_address4 (const char *address, const char *mask) +set_address4(const char *address, const char *mask) { int ret = EINVAL; char command[LINE_LEN]; struct sockaddr_in addr; + addr.sin_family = AF_INET; /* * Parse the address */ - if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr)) + if (1 != inet_pton(AF_INET, address, &addr.sin_addr.s_addr)) { - fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address, - strerror (errno)); + fprintf(stderr, "ERROR: Failed to parse address `%s': %s\n", address, + strerror(errno)); return -1; } // Set Device to Subnet-Mode? @@ -430,17 +427,17 @@ set_address4 (const char *address, const char *mask) /* * prepare the command */ - snprintf (command, LINE_LEN, - "netsh interface ipv4 add address \"%s\" %s %s store=active", - device_visible_name, address, mask); + snprintf(command, LINE_LEN, + "netsh interface ipv4 add address \"%s\" %s %s store=active", + device_visible_name, address, mask); /* * Set the address */ - ret = execute_shellcommand (command); + ret = execute_shellcommand(command); /* Did it work?*/ if (0 != ret) - fprintf (stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror (ret)); + fprintf(stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror(ret)); return ret; } @@ -451,7 +448,7 @@ set_address4 (const char *address, const char *mask) * @param address the IPv4-Address */ static void -remove_address4 (const char *address) +remove_address4(const char *address) { char command[LINE_LEN]; int ret = EINVAL; @@ -461,17 +458,17 @@ remove_address4 (const char *address) /* * prepare the command */ - snprintf (command, LINE_LEN, - "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent", - device_visible_name); + snprintf(command, LINE_LEN, + "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent", + device_visible_name); /* * Set the address */ - ret = execute_shellcommand (command); + ret = execute_shellcommand(command); /* Did it work?*/ if (0 != ret) - fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret)); + fprintf(stderr, "FATAL: removing IPv4 address failed: %s\n", strerror(ret)); } @@ -481,7 +478,7 @@ remove_address4 (const char *address) * @return: TRUE if setup was successful, else FALSE */ static BOOL -setup_interface () +setup_interface() { /* * where to find our inf-file. (+ the "full" path, after windows found") @@ -500,20 +497,20 @@ setup_interface () * Set the device's hardware ID and add it to a list. * This information will later on identify this device in registry. */ - str_length = GNUNET_strlcpy (hwidlist, - HARDWARE_ID, - sizeof (hwidlist)) + 1; + str_length = GNUNET_strlcpy(hwidlist, + HARDWARE_ID, + sizeof(hwidlist)) + 1; /** * this is kind of over-complicated, but allows keeps things independent of * how the openvpn-hwid is actually stored. * * A HWID list is double-\0 terminated and \0 separated */ - str_length = strlen (hwidlist) + 1; - str_length += GNUNET_strlcpy (&hwidlist[str_length], - secondary_hwid, - sizeof (hwidlist) - str_length) + 1; - GNUNET_assert (str_length < sizeof (hwidlist)); + str_length = strlen(hwidlist) + 1; + str_length += GNUNET_strlcpy(&hwidlist[str_length], + secondary_hwid, + sizeof(hwidlist) - str_length) + 1; + GNUNET_assert(str_length < sizeof(hwidlist)); hwidlist[str_length] = '\0'; ++str_length; @@ -522,62 +519,62 @@ setup_interface () * find it. We need to pick the correct driver for win32/win64. */ if (is_win64()) - GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename); + GetFullPathNameA(INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename); else - GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename); + GetFullPathNameA(INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename); - fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path); + fprintf(stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path); /** * Bootstrap our device info using the drivers inf-file */ - if ( ! SetupDiGetINFClassA (inf_file_path, - &class_guid, - class_name, sizeof (class_name) / sizeof (char), - NULL)) + if (!SetupDiGetINFClassA(inf_file_path, + &class_guid, + class_name, sizeof(class_name) / sizeof(char), + NULL)) return FALSE; /** * Collect all the other needed information... * let the system fill our this form */ - DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL); + DeviceInfo = SetupDiCreateDeviceInfoList(&class_guid, NULL); if (DeviceInfo == INVALID_HANDLE_VALUE) return FALSE; - DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA); - if ( ! SetupDiCreateDeviceInfoA (DeviceInfo, - class_name, - &class_guid, - NULL, - 0, - DICD_GENERATE_ID, - &DeviceNode)) + DeviceNode.cbSize = sizeof(SP_DEVINFO_DATA); + if (!SetupDiCreateDeviceInfoA(DeviceInfo, + class_name, + &class_guid, + NULL, + 0, + DICD_GENERATE_ID, + &DeviceNode)) return FALSE; /* Deploy all the information collected into the registry */ - if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo, - &DeviceNode, - SPDRP_HARDWAREID, - (LPBYTE) hwidlist, - str_length * sizeof (char))) + if (!SetupDiSetDeviceRegistryPropertyA(DeviceInfo, + &DeviceNode, + SPDRP_HARDWAREID, + (LPBYTE)hwidlist, + str_length * sizeof(char))) return FALSE; /* Install our new class(=device) into the system */ - if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE, - DeviceInfo, - &DeviceNode)) + if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE, + DeviceInfo, + &DeviceNode)) return FALSE; /* This system call tends to take a while (several seconds!) on "modern" Windoze systems */ - if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL, - secondary_hwid, - inf_file_path, - INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE, - NULL)) //reboot required? NEVER! + if (!UpdateDriverForPlugAndPlayDevicesA(NULL, + secondary_hwid, + inf_file_path, + INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE, + NULL)) //reboot required? NEVER! return FALSE; - fprintf (stderr, "DEBUG: successfully created a network device\n"); + fprintf(stderr, "DEBUG: successfully created a network device\n"); return TRUE; } @@ -589,14 +586,14 @@ setup_interface () * @return: TRUE if destruction was successful, else FALSE */ static BOOL -remove_interface () +remove_interface() { SP_REMOVEDEVICE_PARAMS remove; if (INVALID_HANDLE_VALUE == DeviceInfo) return FALSE; - remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER); + remove.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER); remove.HwProfile = 0; remove.Scope = DI_REMOVEDEVICE_GLOBAL; remove.ClassInstallHeader.InstallFunction = DIF_REMOVE; @@ -604,22 +601,22 @@ remove_interface () * 1. Prepare our existing device information set, and place the * uninstall related information into the structure */ - if ( ! SetupDiSetClassInstallParamsA (DeviceInfo, - (PSP_DEVINFO_DATA) & DeviceNode, - &remove.ClassInstallHeader, - sizeof (remove))) + if (!SetupDiSetClassInstallParamsA(DeviceInfo, + (PSP_DEVINFO_DATA)&DeviceNode, + &remove.ClassInstallHeader, + sizeof(remove))) return FALSE; /* * 2. Uninstall the virtual interface using the class installer */ - if ( ! SetupDiCallClassInstaller (DIF_REMOVE, - DeviceInfo, - (PSP_DEVINFO_DATA) & DeviceNode)) + if (!SetupDiCallClassInstaller(DIF_REMOVE, + DeviceInfo, + (PSP_DEVINFO_DATA)&DeviceNode)) return FALSE; - SetupDiDestroyDeviceInfoList (DeviceInfo); + SetupDiDestroyDeviceInfoList(DeviceInfo); - fprintf (stderr, "DEBUG: removed interface successfully\n"); + fprintf(stderr, "DEBUG: removed interface successfully\n"); return TRUE; } @@ -632,7 +629,7 @@ remove_interface () * @return: TRUE if we were able to lookup the interface's name, else FALSE */ static BOOL -resolve_interface_name () +resolve_interface_name() { SP_DEVINFO_LIST_DETAIL_DATA device_details; char pnp_instance_id [MAX_DEVICE_ID_LEN]; @@ -645,29 +642,29 @@ resolve_interface_name () char adapter[] = INTERFACE_REGISTRY_LOCATION; /* We can obtain the PNP instance ID from our setupapi handle */ - device_details.cbSize = sizeof (device_details); - if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst, - (PCHAR) pnp_instance_id, - MAX_DEVICE_ID_LEN, - 0, //must be 0 - NULL)) //hMachine, we are local + device_details.cbSize = sizeof(device_details); + if (CR_SUCCESS != CM_Get_Device_ID_ExA(DeviceNode.DevInst, + (PCHAR)pnp_instance_id, + MAX_DEVICE_ID_LEN, + 0, //must be 0 + NULL)) //hMachine, we are local return FALSE; - fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id); + fprintf(stderr, "DEBUG: Resolving interface name for network device %s\n", pnp_instance_id); /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */ for (retrys = 0; retrys < 120 && !retval; retrys++) { /* sleep for 250ms*/ - Sleep (250); + Sleep(250); /* Now we can use this ID to locate the correct networks interface in registry */ - if (ERROR_SUCCESS != RegOpenKeyExA ( - HKEY_LOCAL_MACHINE, - adapter, - 0, - KEY_READ, - &adapter_key_handle)) + if (ERROR_SUCCESS != RegOpenKeyExA( + HKEY_LOCAL_MACHINE, + adapter, + 0, + KEY_READ, + &adapter_key_handle)) return FALSE; /* Of course there is a multitude of entries here, with arbitrary names, @@ -683,17 +680,17 @@ resolve_interface_name () char adaptername_name[] = "Name"; DWORD data_type; - len = 256 * sizeof (char); + len = 256 * sizeof(char); /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */ - status = RegEnumKeyExA ( - adapter_key_handle, - i, - instance_key, - &len, - NULL, - NULL, - NULL, - NULL); + status = RegEnumKeyExA( + adapter_key_handle, + i, + instance_key, + &len, + NULL, + NULL, + NULL, + NULL); /* this may fail due to one of two reasons: * we are at the end of the list*/ @@ -704,44 +701,44 @@ resolve_interface_name () goto cleanup; /* prepare our new query string: */ - snprintf (query_key, 256, "%s\\%s\\Connection", - adapter, - instance_key); + snprintf(query_key, 256, "%s\\%s\\Connection", + adapter, + instance_key); /* look inside instance_key\\Connection */ - if (ERROR_SUCCESS != RegOpenKeyExA ( - HKEY_LOCAL_MACHINE, - query_key, - 0, - KEY_READ, - &instance_key_handle)) + if (ERROR_SUCCESS != RegOpenKeyExA( + HKEY_LOCAL_MACHINE, + query_key, + 0, + KEY_READ, + &instance_key_handle)) goto cleanup; /* now, read our PnpInstanceID */ - len = sizeof (pnpinstanceid_value); - status = RegQueryValueExA (instance_key_handle, - pnpinstanceid_name, - NULL, //reserved, always NULL according to MSDN - &data_type, - (LPBYTE) pnpinstanceid_value, - &len); + len = sizeof(pnpinstanceid_value); + status = RegQueryValueExA(instance_key_handle, + pnpinstanceid_name, + NULL, //reserved, always NULL according to MSDN + &data_type, + (LPBYTE)pnpinstanceid_value, + &len); if (status != ERROR_SUCCESS || data_type != REG_SZ) goto cleanup; /* compare the value we got to our devices PNPInstanceID*/ - if (0 != strncmp (pnpinstanceid_value, pnp_instance_id, - sizeof (pnpinstanceid_value) / sizeof (char))) + if (0 != strncmp(pnpinstanceid_value, pnp_instance_id, + sizeof(pnpinstanceid_value) / sizeof(char))) goto cleanup; - len = sizeof (device_visible_name); - status = RegQueryValueExA ( - instance_key_handle, - adaptername_name, - NULL, //reserved, always NULL according to MSDN - &data_type, - (LPBYTE) device_visible_name, - &len); + len = sizeof(device_visible_name); + status = RegQueryValueExA( + instance_key_handle, + adaptername_name, + NULL, //reserved, always NULL according to MSDN + &data_type, + (LPBYTE)device_visible_name, + &len); if (status != ERROR_SUCCESS || data_type != REG_SZ) goto cleanup; @@ -750,17 +747,17 @@ resolve_interface_name () * we have successfully found OUR instance, * save the device GUID before exiting */ - GNUNET_strlcpy (device_guid, instance_key, sizeof (device_guid)); + GNUNET_strlcpy(device_guid, instance_key, sizeof(device_guid)); retval = TRUE; - fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid); + fprintf(stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid); cleanup: - RegCloseKey (instance_key_handle); + RegCloseKey(instance_key_handle); ++i; } - RegCloseKey (adapter_key_handle); + RegCloseKey(adapter_key_handle); } return retval; } @@ -773,25 +770,27 @@ cleanup: * @return TRUE if the version is sufficient, else FALSE */ static BOOL -check_tapw32_version (HANDLE handle) +check_tapw32_version(HANDLE handle) { ULONG version[3]; DWORD len; - memset (&(version), 0, sizeof (version)); - if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION, - &version, sizeof (version), - &version, sizeof (version), &len, NULL)) - fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n", - (int) version[0], - (int) version[1], - (version[2] ? "(DEBUG)" : "")); + memset(&(version), 0, sizeof(version)); + + if (DeviceIoControl(handle, TAP_WIN_IOCTL_GET_VERSION, + &version, sizeof(version), + &version, sizeof(version), &len, NULL)) + fprintf(stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n", + (int)version[0], + (int)version[1], + (version[2] ? "(DEBUG)" : "")); if ((version[0] != TAP_WIN_MIN_MAJOR) || - (version[1] < TAP_WIN_MIN_MINOR )){ - fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n", - TAP_WIN_MIN_MAJOR, - TAP_WIN_MIN_MINOR); + (version[1] < TAP_WIN_MIN_MINOR)) + { + fprintf(stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n", + TAP_WIN_MIN_MAJOR, + TAP_WIN_MIN_MINOR); return FALSE; } @@ -805,55 +804,55 @@ check_tapw32_version (HANDLE handle) * @return the fd to the tun or -1 on error */ static HANDLE -init_tun () +init_tun() { char device_path[256]; HANDLE handle; - if (! setup_interface ()) + if (!setup_interface()) { errno = ENODEV; return INVALID_HANDLE_VALUE; } - if (! resolve_interface_name ()) + if (!resolve_interface_name()) { errno = ENODEV; return INVALID_HANDLE_VALUE; } /* Open Windows TAP-Windows adapter */ - snprintf (device_path, sizeof (device_path), "%s%s%s", - USERMODEDEVICEDIR, - device_guid, - TAP_WIN_SUFFIX); - - handle = CreateFile ( - device_path, - GENERIC_READ | GENERIC_WRITE, - 0, /* was: FILE_SHARE_READ */ - 0, - OPEN_EXISTING, - FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, - 0 - ); + snprintf(device_path, sizeof(device_path), "%s%s%s", + USERMODEDEVICEDIR, + device_guid, + TAP_WIN_SUFFIX); + + handle = CreateFile( + device_path, + GENERIC_READ | GENERIC_WRITE, + 0, /* was: FILE_SHARE_READ */ + 0, + OPEN_EXISTING, + FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, + 0 + ); if (INVALID_HANDLE_VALUE == handle) { - fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path); + fprintf(stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path); return handle; } /* get driver version info */ - if (! check_tapw32_version (handle)) + if (!check_tapw32_version(handle)) { - CloseHandle (handle); + CloseHandle(handle); return INVALID_HANDLE_VALUE; } /* TODO (opt?): get MTU-Size */ - fprintf (stderr, "DEBUG: successfully opened TAP device\n"); + fprintf(stderr, "DEBUG: successfully opened TAP device\n"); return handle; } @@ -865,21 +864,22 @@ init_tun () * @return True if the operation succeeded, else false */ static BOOL -tun_up (HANDLE handle) +tun_up(HANDLE handle) { ULONG status = TRUE; DWORD len; - if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS, - &status, sizeof (status), - &status, sizeof (status), &len, NULL)) + + if (!DeviceIoControl(handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS, + &status, sizeof(status), + &status, sizeof(status), &len, NULL)) { - fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n"); + fprintf(stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n"); return FALSE; } /* Wait for the device to go UP, might take some time. */ - Sleep (TAP32_POSTUP_WAITTIME * 1000); - fprintf (stderr, "DEBUG: successfully set TAP device to UP\n"); + Sleep(TAP32_POSTUP_WAITTIME * 1000); + fprintf(stderr, "DEBUG: successfully set TAP device to UP\n"); return TRUE; } @@ -911,8 +911,8 @@ tun_up (HANDLE handle) * @return false if an event reset was impossible (OS error), else true */ static BOOL -attempt_read_tap (struct io_facility * input_facility, - struct io_facility * output_facility) +attempt_read_tap(struct io_facility * input_facility, + struct io_facility * output_facility) { struct GNUNET_MessageHeader * hdr; unsigned short size; @@ -920,137 +920,139 @@ attempt_read_tap (struct io_facility * input_facility, switch (input_facility->facility_state) { case IOSTATE_READY: - { - if (! ResetEvent (input_facility->overlapped.hEvent)) - { + { + if (!ResetEvent(input_facility->overlapped.hEvent)) + { + return FALSE; + } + + input_facility->buffer_size = 0; + + /* Check how the task is handled */ + if (ReadFile(input_facility->handle, + input_facility->buffer, + sizeof(input_facility->buffer) - sizeof(struct GNUNET_MessageHeader), + &input_facility->buffer_size, + &input_facility->overlapped)) + { /* async event processed immediately*/ + /* reset event manually*/ + if (!SetEvent(input_facility->overlapped.hEvent)) return FALSE; - } - - input_facility->buffer_size = 0; - - /* Check how the task is handled */ - if (ReadFile (input_facility->handle, - input_facility->buffer, - sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader), - &input_facility->buffer_size, - &input_facility->overlapped)) - {/* async event processed immediately*/ - - /* reset event manually*/ - if (! SetEvent (input_facility->overlapped.hEvent)) - return FALSE; - - fprintf (stderr, "DEBUG: tap read succeeded immediately\n"); - - /* we successfully read something from the TAP and now need to - * send it our via STDOUT. Is that possible at the moment? */ - if ((IOSTATE_READY == output_facility->facility_state || - IOSTATE_WAITING == output_facility->facility_state) - && (0 < input_facility->buffer_size)) - { /* hand over this buffers content and apply message header for gnunet */ - hdr = (struct GNUNET_MessageHeader *) output_facility->buffer; - size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader); - - GNUNET_memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader), - input_facility->buffer, - input_facility->buffer_size); - - output_facility->buffer_size = size; - hdr->size = htons (size); - hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER); - output_facility->facility_state = IOSTATE_READY; - } - else if (0 < input_facility->buffer_size) - /* If we have have read our buffer, wait for our write-partner*/ - input_facility->facility_state = IOSTATE_WAITING; - } - else /* operation was either queued or failed*/ - { - int err = GetLastError (); - if (ERROR_IO_PENDING == err) - { /* operation queued */ - input_facility->facility_state = IOSTATE_QUEUED; - } - else - { /* error occurred, let the rest of the elements finish */ - input_facility->path_open = FALSE; - input_facility->facility_state = IOSTATE_FAILED; - if (IOSTATE_WAITING == output_facility->facility_state) - output_facility->path_open = FALSE; - - fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n"); - } - } - } + + fprintf(stderr, "DEBUG: tap read succeeded immediately\n"); + + /* we successfully read something from the TAP and now need to + * send it our via STDOUT. Is that possible at the moment? */ + if ((IOSTATE_READY == output_facility->facility_state || + IOSTATE_WAITING == output_facility->facility_state) + && (0 < input_facility->buffer_size)) + { /* hand over this buffers content and apply message header for gnunet */ + hdr = (struct GNUNET_MessageHeader *)output_facility->buffer; + size = input_facility->buffer_size + sizeof(struct GNUNET_MessageHeader); + + GNUNET_memcpy(output_facility->buffer + sizeof(struct GNUNET_MessageHeader), + input_facility->buffer, + input_facility->buffer_size); + + output_facility->buffer_size = size; + hdr->size = htons(size); + hdr->type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER); + output_facility->facility_state = IOSTATE_READY; + } + else if (0 < input_facility->buffer_size) + /* If we have have read our buffer, wait for our write-partner*/ + input_facility->facility_state = IOSTATE_WAITING; + } + else /* operation was either queued or failed*/ + { + int err = GetLastError(); + if (ERROR_IO_PENDING == err) + { /* operation queued */ + input_facility->facility_state = IOSTATE_QUEUED; + } + else + { /* error occurred, let the rest of the elements finish */ + input_facility->path_open = FALSE; + input_facility->facility_state = IOSTATE_FAILED; + if (IOSTATE_WAITING == output_facility->facility_state) + output_facility->path_open = FALSE; + + fprintf(stderr, "FATAL: Read from handle failed, allowing write to finish\n"); + } + } + } return TRUE; - // We are queued and should check if the read has finished + + // We are queued and should check if the read has finished case IOSTATE_QUEUED: - { - // there was an operation going on already, check if that has completed now. - - if (GetOverlappedResult (input_facility->handle, - &input_facility->overlapped, - &input_facility->buffer_size, - FALSE)) - {/* successful return for a queued operation */ - if (! ResetEvent (input_facility->overlapped.hEvent)) - return FALSE; - - fprintf (stderr, "DEBUG: tap read succeeded delayed\n"); - - /* we successfully read something from the TAP and now need to - * send it our via STDOUT. Is that possible at the moment? */ - if ((IOSTATE_READY == output_facility->facility_state || - IOSTATE_WAITING == output_facility->facility_state) - && 0 < input_facility->buffer_size) - { /* hand over this buffers content and apply message header for gnunet */ - hdr = (struct GNUNET_MessageHeader *) output_facility->buffer; - size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader); - - GNUNET_memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader), - input_facility->buffer, - input_facility->buffer_size); - - output_facility->buffer_size = size; - hdr->size = htons(size); - hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER); - output_facility->facility_state = IOSTATE_READY; - input_facility->facility_state = IOSTATE_READY; - } - else if (0 < input_facility->buffer_size) - { /* If we have have read our buffer, wait for our write-partner*/ - input_facility->facility_state = IOSTATE_WAITING; - // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish? - } - } - else - { /* operation still pending/queued or failed? */ - int err = GetLastError (); - if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err)) - { /* error occurred, let the rest of the elements finish */ - input_facility->path_open = FALSE; - input_facility->facility_state = IOSTATE_FAILED; - if (IOSTATE_WAITING == output_facility->facility_state) - output_facility->path_open = FALSE; - fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n"); - } - } - } + { + // there was an operation going on already, check if that has completed now. + + if (GetOverlappedResult(input_facility->handle, + &input_facility->overlapped, + &input_facility->buffer_size, + FALSE)) + { /* successful return for a queued operation */ + if (!ResetEvent(input_facility->overlapped.hEvent)) + return FALSE; + + fprintf(stderr, "DEBUG: tap read succeeded delayed\n"); + + /* we successfully read something from the TAP and now need to + * send it our via STDOUT. Is that possible at the moment? */ + if ((IOSTATE_READY == output_facility->facility_state || + IOSTATE_WAITING == output_facility->facility_state) + && 0 < input_facility->buffer_size) + { /* hand over this buffers content and apply message header for gnunet */ + hdr = (struct GNUNET_MessageHeader *)output_facility->buffer; + size = input_facility->buffer_size + sizeof(struct GNUNET_MessageHeader); + + GNUNET_memcpy(output_facility->buffer + sizeof(struct GNUNET_MessageHeader), + input_facility->buffer, + input_facility->buffer_size); + + output_facility->buffer_size = size; + hdr->size = htons(size); + hdr->type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER); + output_facility->facility_state = IOSTATE_READY; + input_facility->facility_state = IOSTATE_READY; + } + else if (0 < input_facility->buffer_size) + { /* If we have have read our buffer, wait for our write-partner*/ + input_facility->facility_state = IOSTATE_WAITING; + // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish? + } + } + else + { /* operation still pending/queued or failed? */ + int err = GetLastError(); + if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err)) + { /* error occurred, let the rest of the elements finish */ + input_facility->path_open = FALSE; + input_facility->facility_state = IOSTATE_FAILED; + if (IOSTATE_WAITING == output_facility->facility_state) + output_facility->path_open = FALSE; + fprintf(stderr, "FATAL: Read from handle failed, allowing write to finish\n"); + } + } + } return TRUE; + case IOSTATE_RESUME: - hdr = (struct GNUNET_MessageHeader *) output_facility->buffer; - size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader); + hdr = (struct GNUNET_MessageHeader *)output_facility->buffer; + size = input_facility->buffer_size + sizeof(struct GNUNET_MessageHeader); - GNUNET_memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader), - input_facility->buffer, - input_facility->buffer_size); + GNUNET_memcpy(output_facility->buffer + sizeof(struct GNUNET_MessageHeader), + input_facility->buffer, + input_facility->buffer_size); output_facility->buffer_size = size; - hdr->size = htons (size); - hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER); + hdr->size = htons(size); + hdr->type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER); output_facility->facility_state = IOSTATE_READY; input_facility->facility_state = IOSTATE_READY; return TRUE; + default: return TRUE; } @@ -1084,154 +1086,157 @@ attempt_read_tap (struct io_facility * input_facility, * @return false if an event reset was impossible (OS error), else true */ static BOOL -attempt_read_stdin (struct io_facility * input_facility, - struct io_facility * output_facility) +attempt_read_stdin(struct io_facility * input_facility, + struct io_facility * output_facility) { struct GNUNET_MessageHeader * hdr; switch (input_facility->facility_state) { case IOSTATE_READY: - { - input_facility->buffer_size = 0; + { + input_facility->buffer_size = 0; partial_read_iostate_ready: - if (! ResetEvent (input_facility->overlapped.hEvent)) - return FALSE; + if (!ResetEvent(input_facility->overlapped.hEvent)) + return FALSE; - /* Check how the task is handled */ - if (ReadFile (input_facility->handle, - input_facility->buffer + input_facility->buffer_size, - sizeof (input_facility->buffer) - input_facility->buffer_size, - &input_facility->buffer_size_processed, - &input_facility->overlapped)) - {/* async event processed immediately*/ - hdr = (struct GNUNET_MessageHeader *) input_facility->buffer; - - /* reset event manually*/ - if (!SetEvent (input_facility->overlapped.hEvent)) - return FALSE; - - fprintf (stderr, "DEBUG: stdin read succeeded immediately\n"); - input_facility->buffer_size += input_facility->buffer_size_processed; - - if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER || - ntohs (hdr->size) > sizeof (input_facility->buffer)) - { - fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size)); - input_facility->facility_state = IOSTATE_READY; - return TRUE; - } - /* we got the a part of a packet */ - if (ntohs (hdr->size) > input_facility->buffer_size) - goto partial_read_iostate_ready; - - /* have we read more than 0 bytes of payload? (sizeread > header)*/ - if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) && - ((IOSTATE_READY == output_facility->facility_state) || - (IOSTATE_WAITING == output_facility->facility_state))) - {/* we successfully read something from the TAP and now need to - * send it our via STDOUT. Is that possible at the moment? */ - - /* hand over this buffers content and strip gnunet message header */ - GNUNET_memcpy (output_facility->buffer, - input_facility->buffer + sizeof (struct GNUNET_MessageHeader), - input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader)); - output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader); - output_facility->facility_state = IOSTATE_READY; - input_facility->facility_state = IOSTATE_READY; - } - else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader)) - /* If we have have read our buffer, wait for our write-partner*/ - input_facility->facility_state = IOSTATE_WAITING; - else /* we read nothing */ + /* Check how the task is handled */ + if (ReadFile(input_facility->handle, + input_facility->buffer + input_facility->buffer_size, + sizeof(input_facility->buffer) - input_facility->buffer_size, + &input_facility->buffer_size_processed, + &input_facility->overlapped)) + { /* async event processed immediately*/ + hdr = (struct GNUNET_MessageHeader *)input_facility->buffer; + + /* reset event manually*/ + if (!SetEvent(input_facility->overlapped.hEvent)) + return FALSE; + + fprintf(stderr, "DEBUG: stdin read succeeded immediately\n"); + input_facility->buffer_size += input_facility->buffer_size_processed; + + if (ntohs(hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER || + ntohs(hdr->size) > sizeof(input_facility->buffer)) + { + fprintf(stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs(hdr->type), ntohs(hdr->size)); + input_facility->facility_state = IOSTATE_READY; + return TRUE; + } + /* we got the a part of a packet */ + if (ntohs(hdr->size) > input_facility->buffer_size) + goto partial_read_iostate_ready; + + /* have we read more than 0 bytes of payload? (sizeread > header)*/ + if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader) && + ((IOSTATE_READY == output_facility->facility_state) || + (IOSTATE_WAITING == output_facility->facility_state))) + { /* we successfully read something from the TAP and now need to + * send it our via STDOUT. Is that possible at the moment? */ + /* hand over this buffers content and strip gnunet message header */ + GNUNET_memcpy(output_facility->buffer, + input_facility->buffer + sizeof(struct GNUNET_MessageHeader), + input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader)); + output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader); + output_facility->facility_state = IOSTATE_READY; input_facility->facility_state = IOSTATE_READY; - } - else /* operation was either queued or failed*/ - { - int err = GetLastError (); - if (ERROR_IO_PENDING == err) /* operation queued */ - input_facility->facility_state = IOSTATE_QUEUED; - else - { /* error occurred, let the rest of the elements finish */ - input_facility->path_open = FALSE; - input_facility->facility_state = IOSTATE_FAILED; - if (IOSTATE_WAITING == output_facility->facility_state) - output_facility->path_open = FALSE; - - fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n"); - } - } - } + } + else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader)) + /* If we have have read our buffer, wait for our write-partner*/ + input_facility->facility_state = IOSTATE_WAITING; + else /* we read nothing */ + input_facility->facility_state = IOSTATE_READY; + } + else /* operation was either queued or failed*/ + { + int err = GetLastError(); + if (ERROR_IO_PENDING == err) /* operation queued */ + input_facility->facility_state = IOSTATE_QUEUED; + else + { /* error occurred, let the rest of the elements finish */ + input_facility->path_open = FALSE; + input_facility->facility_state = IOSTATE_FAILED; + if (IOSTATE_WAITING == output_facility->facility_state) + output_facility->path_open = FALSE; + + fprintf(stderr, "FATAL: Read from handle failed, allowing write to finish\n"); + } + } + } return TRUE; - // We are queued and should check if the read has finished + + // We are queued and should check if the read has finished case IOSTATE_QUEUED: - { - // there was an operation going on already, check if that has completed now. - if (GetOverlappedResult (input_facility->handle, - &input_facility->overlapped, - &input_facility->buffer_size_processed, - FALSE)) - {/* successful return for a queued operation */ - hdr = (struct GNUNET_MessageHeader *) input_facility->buffer; - - if (! ResetEvent (input_facility->overlapped.hEvent)) - return FALSE; - - fprintf (stderr, "DEBUG: stdin read succeeded delayed\n"); - input_facility->buffer_size += input_facility->buffer_size_processed; - - if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) || - (ntohs (hdr->size) > sizeof (input_facility->buffer))) - { - fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size)); - input_facility->facility_state = IOSTATE_READY; - return TRUE; - } - /* we got the a part of a packet */ - if (ntohs (hdr->size) > input_facility->buffer_size ); - goto partial_read_iostate_ready; - - /* we successfully read something from the TAP and now need to - * send it our via STDOUT. Is that possible at the moment? */ - if ((IOSTATE_READY == output_facility->facility_state || - IOSTATE_WAITING == output_facility->facility_state) - && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader)) - { /* hand over this buffers content and strip gnunet message header */ - GNUNET_memcpy (output_facility->buffer, - input_facility->buffer + sizeof(struct GNUNET_MessageHeader), - input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader)); - output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader); - output_facility->facility_state = IOSTATE_READY; - input_facility->facility_state = IOSTATE_READY; - } - else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader)) - input_facility->facility_state = IOSTATE_WAITING; - else + { + // there was an operation going on already, check if that has completed now. + if (GetOverlappedResult(input_facility->handle, + &input_facility->overlapped, + &input_facility->buffer_size_processed, + FALSE)) + { /* successful return for a queued operation */ + hdr = (struct GNUNET_MessageHeader *)input_facility->buffer; + + if (!ResetEvent(input_facility->overlapped.hEvent)) + return FALSE; + + fprintf(stderr, "DEBUG: stdin read succeeded delayed\n"); + input_facility->buffer_size += input_facility->buffer_size_processed; + + if ((ntohs(hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) || + (ntohs(hdr->size) > sizeof(input_facility->buffer))) + { + fprintf(stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs(hdr->type), ntohs(hdr->size)); input_facility->facility_state = IOSTATE_READY; - } - else - { /* operation still pending/queued or failed? */ - int err = GetLastError (); - if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err)) - { /* error occurred, let the rest of the elements finish */ - input_facility->path_open = FALSE; - input_facility->facility_state = IOSTATE_FAILED; - if (IOSTATE_WAITING == output_facility->facility_state) - output_facility->path_open = FALSE; - fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n"); - } - } - } + return TRUE; + } + /* we got the a part of a packet */ + if (ntohs(hdr->size) > input_facility->buffer_size) + ; + goto partial_read_iostate_ready; + + /* we successfully read something from the TAP and now need to + * send it our via STDOUT. Is that possible at the moment? */ + if ((IOSTATE_READY == output_facility->facility_state || + IOSTATE_WAITING == output_facility->facility_state) + && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader)) + { /* hand over this buffers content and strip gnunet message header */ + GNUNET_memcpy(output_facility->buffer, + input_facility->buffer + sizeof(struct GNUNET_MessageHeader), + input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader)); + output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader); + output_facility->facility_state = IOSTATE_READY; + input_facility->facility_state = IOSTATE_READY; + } + else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader)) + input_facility->facility_state = IOSTATE_WAITING; + else + input_facility->facility_state = IOSTATE_READY; + } + else + { /* operation still pending/queued or failed? */ + int err = GetLastError(); + if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err)) + { /* error occurred, let the rest of the elements finish */ + input_facility->path_open = FALSE; + input_facility->facility_state = IOSTATE_FAILED; + if (IOSTATE_WAITING == output_facility->facility_state) + output_facility->path_open = FALSE; + fprintf(stderr, "FATAL: Read from handle failed, allowing write to finish\n"); + } + } + } return TRUE; + case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */ - GNUNET_memcpy (output_facility->buffer, - input_facility->buffer + sizeof (struct GNUNET_MessageHeader), - input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader)); - output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader); + GNUNET_memcpy(output_facility->buffer, + input_facility->buffer + sizeof(struct GNUNET_MessageHeader), + input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader)); + output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader); output_facility->facility_state = IOSTATE_READY; input_facility->facility_state = IOSTATE_READY; return TRUE; + default: return TRUE; } @@ -1248,8 +1253,8 @@ partial_read_iostate_ready: * @return false if an event reset was impossible (OS error), else true */ static BOOL -attempt_write (struct io_facility * output_facility, - struct io_facility * input_facility) +attempt_write(struct io_facility * output_facility, + struct io_facility * input_facility) { switch (output_facility->facility_state) { @@ -1257,22 +1262,21 @@ attempt_write (struct io_facility * output_facility, output_facility->buffer_size_written = 0; continue_partial_write: - if (! ResetEvent (output_facility->overlapped.hEvent)) + if (!ResetEvent(output_facility->overlapped.hEvent)) return FALSE; /* Check how the task was handled */ - if (WriteFile (output_facility->handle, - output_facility->buffer + output_facility->buffer_size_written, - output_facility->buffer_size - output_facility->buffer_size_written, - &output_facility->buffer_size_processed, - &output_facility->overlapped)) + if (WriteFile(output_facility->handle, + output_facility->buffer + output_facility->buffer_size_written, + output_facility->buffer_size - output_facility->buffer_size_written, + &output_facility->buffer_size_processed, + &output_facility->overlapped)) {/* async event processed immediately*/ - - fprintf (stderr, "DEBUG: write succeeded immediately\n"); + fprintf(stderr, "DEBUG: write succeeded immediately\n"); output_facility->buffer_size_written += output_facility->buffer_size_processed; /* reset event manually*/ - if (! SetEvent (output_facility->overlapped.hEvent)) + if (!SetEvent(output_facility->overlapped.hEvent)) return FALSE; /* partial write */ @@ -1290,7 +1294,7 @@ continue_partial_write: } else /* operation was either queued or failed*/ { - int err = GetLastError (); + int err = GetLastError(); if (ERROR_IO_PENDING == err) { /* operation queued */ output_facility->facility_state = IOSTATE_QUEUED; @@ -1299,22 +1303,23 @@ continue_partial_write: { /* error occurred, close this path */ output_facility->path_open = FALSE; output_facility->facility_state = IOSTATE_FAILED; - fprintf (stderr, "FATAL: Write to handle failed, exiting\n"); + fprintf(stderr, "FATAL: Write to handle failed, exiting\n"); } } return TRUE; + case IOSTATE_QUEUED: // there was an operation going on already, check if that has completed now. - if (GetOverlappedResult (output_facility->handle, - &output_facility->overlapped, - &output_facility->buffer_size_processed, - FALSE)) + if (GetOverlappedResult(output_facility->handle, + &output_facility->overlapped, + &output_facility->buffer_size_processed, + FALSE)) {/* successful return for a queued operation */ - if (! ResetEvent (output_facility->overlapped.hEvent)) + if (!ResetEvent(output_facility->overlapped.hEvent)) return FALSE; - fprintf (stderr, "DEBUG: write succeeded delayed\n"); + fprintf(stderr, "DEBUG: write succeeded delayed\n"); output_facility->buffer_size_written += output_facility->buffer_size_processed; /* partial write */ @@ -1332,14 +1337,15 @@ continue_partial_write: } else { /* operation still pending/queued or failed? */ - int err = GetLastError (); + int err = GetLastError(); if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err)) { /* error occurred, close this path */ output_facility->path_open = FALSE; output_facility->facility_state = IOSTATE_FAILED; - fprintf (stderr, "FATAL: Write to handle failed, exiting\n"); + fprintf(stderr, "FATAL: Write to handle failed, exiting\n"); } } + default: return TRUE; } @@ -1355,15 +1361,15 @@ continue_partial_write: * @return true on success, else false */ static BOOL -initialize_io_facility (struct io_facility * elem, - int initial_state, - BOOL signaled) +initialize_io_facility(struct io_facility * elem, + int initial_state, + BOOL signaled) { elem->path_open = TRUE; elem->handle = INVALID_HANDLE_VALUE; elem->facility_state = initial_state; elem->buffer_size = 0; - elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL); + elem->overlapped.hEvent = CreateEvent(NULL, TRUE, signaled, NULL); if (NULL == elem->overlapped.hEvent) return FALSE; @@ -1377,7 +1383,7 @@ initialize_io_facility (struct io_facility * elem, * @param tap_handle device handle for interacting with the Virtual interface */ static void -run (HANDLE tap_handle) +run(HANDLE tap_handle) { /* IO-Facility for reading from our virtual interface */ struct io_facility tap_read; @@ -1388,8 +1394,8 @@ run (HANDLE tap_handle) /* IO-Facility for writing to stdout */ struct io_facility std_out; - HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE); - HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE); + HANDLE parent_std_in_handle = GetStdHandle(STD_INPUT_HANDLE); + HANDLE parent_std_out_handle = GetStdHandle(STD_OUTPUT_HANDLE); /* tun up: */ /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn @@ -1398,14 +1404,14 @@ run (HANDLE tap_handle) * DHCP and such are all features we will never use in gnunet afaik. * But for openvpn those are essential. */ - if ((privilege_testing) || (! tun_up (tap_handle) )) + if ((privilege_testing) || (!tun_up(tap_handle))) goto teardown_final; /* Initialize our overlapped IO structures*/ - if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE) - && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE) - && initialize_io_facility (&std_in, IOSTATE_READY, FALSE) - && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE))) + if (!(initialize_io_facility(&tap_read, IOSTATE_READY, FALSE) + && initialize_io_facility(&tap_write, IOSTATE_WAITING, TRUE) + && initialize_io_facility(&std_in, IOSTATE_READY, FALSE) + && initialize_io_facility(&std_out, IOSTATE_WAITING, TRUE))) goto teardown_final; /* Handles for STDIN and STDOUT */ @@ -1416,75 +1422,74 @@ run (HANDLE tap_handle) /* Debug output to console STDIN/STDOUT*/ std_in.handle = parent_std_in_handle; std_out.handle = parent_std_out_handle; - #else - fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n"); + fprintf(stderr, "DEBUG: reopening stdin/out for overlapped IO\n"); /* * Find out the types of our handles. * This part is a problem, because in windows we need to handle files, * pipes and the console differently. */ - if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) || - (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle))) + if ((FILE_TYPE_PIPE != GetFileType(parent_std_in_handle)) || + (FILE_TYPE_PIPE != GetFileType(parent_std_out_handle))) { - fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n"); + fprintf(stderr, "ERROR: stdin/stdout must be named pipes\n"); goto teardown; } - std_in.handle = ReOpenFile (parent_std_in_handle, - GENERIC_READ, - FILE_SHARE_WRITE | FILE_SHARE_READ, - FILE_FLAG_OVERLAPPED); + std_in.handle = ReOpenFile(parent_std_in_handle, + GENERIC_READ, + FILE_SHARE_WRITE | FILE_SHARE_READ, + FILE_FLAG_OVERLAPPED); if (INVALID_HANDLE_VALUE == std_in.handle) { - fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n"); + fprintf(stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n"); goto teardown; } - std_out.handle = ReOpenFile (parent_std_out_handle, - GENERIC_WRITE, - FILE_SHARE_READ, - FILE_FLAG_OVERLAPPED); + std_out.handle = ReOpenFile(parent_std_out_handle, + GENERIC_WRITE, + FILE_SHARE_READ, + FILE_FLAG_OVERLAPPED); if (INVALID_HANDLE_VALUE == std_out.handle) { - fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n"); + fprintf(stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n"); goto teardown; } #endif - fprintf (stderr, "DEBUG: mainloop has begun\n"); + fprintf(stderr, "DEBUG: mainloop has begun\n"); while (std_out.path_open || tap_write.path_open) { /* perform READ from stdin if possible */ - if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write))) + if (std_in.path_open && (!attempt_read_stdin(&std_in, &tap_write))) break; /* perform READ from tap if possible */ - if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out))) + if (tap_read.path_open && (!attempt_read_tap(&tap_read, &std_out))) break; /* perform WRITE to tap if possible */ - if (tap_write.path_open && (! attempt_write (&tap_write, &std_in))) + if (tap_write.path_open && (!attempt_write(&tap_write, &std_in))) break; /* perform WRITE to STDOUT if possible */ - if (std_out.path_open && (! attempt_write (&std_out, &tap_read))) + if (std_out.path_open && (!attempt_write(&std_out, &tap_read))) break; } - fprintf (stderr, "DEBUG: teardown initiated\n"); + fprintf(stderr, "DEBUG: teardown initiated\n"); teardown: - CancelIo (tap_handle); - CancelIo (std_in.handle); - CancelIo (std_out.handle); + CancelIo(tap_handle); + CancelIo(std_in.handle); + CancelIo(std_out.handle); teardown_final: - CloseHandle (tap_handle); + CloseHandle(tap_handle); } @@ -1501,7 +1506,7 @@ teardown_final: * 6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"] */ int -main (int argc, char **argv) +main(int argc, char **argv) { char hwid[LINE_LEN]; HANDLE handle; @@ -1511,99 +1516,100 @@ main (int argc, char **argv) BOOL have_ip6 = FALSE; BOOL have_nat44 = FALSE; - if ( (1 < argc) && (0 != strcmp (argv[1], "-d"))){ + if ((1 < argc) && (0 != strcmp(argv[1], "-d"))) + { privilege_testing = TRUE; - fprintf (stderr, - "%s", - "DEBUG: Running binary in privilege testing mode."); + fprintf(stderr, + "%s", + "DEBUG: Running binary in privilege testing mode."); argv++; argc--; } if (6 != argc) { - fprintf (stderr, - "%s", - "FATAL: must supply 6 arguments\nUsage:\ngnunet-helper-exit [-d] \n"); + fprintf(stderr, + "%s", + "FATAL: must supply 6 arguments\nUsage:\ngnunet-helper-exit [-d] \n"); return 1; } - GNUNET_strlcpy (hwid, argv[1], sizeof (hwid)); + GNUNET_strlcpy(hwid, argv[1], sizeof(hwid)); /* * We use our PID for finding/resolving the control-panel name of our virtual * device. PIDs are (of course) unique at runtime, thus we can safely use it * as additional hardware-id for our device. */ - snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d", - hwid, - _getpid ()); + snprintf(secondary_hwid, LINE_LEN / 2, "%s-%d", + hwid, + _getpid()); - if (INVALID_HANDLE_VALUE == (handle = init_tun ())) + if (INVALID_HANDLE_VALUE == (handle = init_tun())) { - fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n", - hwid, - argv[3], - argv[4], - argv[5], - argv[6]); + fprintf(stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n", + hwid, + argv[3], + argv[4], + argv[5], + argv[6]); global_ret = -1; goto cleanup; } - fprintf (stderr, "DEBUG: Setting IPs, if needed\n"); - if (0 != strcmp (argv[3], "-")) + fprintf(stderr, "DEBUG: Setting IPs, if needed\n"); + if (0 != strcmp(argv[3], "-")) { char command[LINE_LEN]; const char *address = argv[3]; - long prefix_len = atol (argv[4]); + long prefix_len = atol(argv[4]); if ((prefix_len < 1) || (prefix_len > 127)) { - fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n"); + fprintf(stderr, "FATAL: ipv6 prefix_len out of range\n"); global_ret = -1; goto cleanup; } - fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n", address, prefix_len); - if (0 != (global_ret = set_address6 (address, prefix_len))) + fprintf(stderr, "DEBUG: Setting IP6 address: %s/%d\n", address, prefix_len); + if (0 != (global_ret = set_address6(address, prefix_len))) goto cleanup; have_ip6 = TRUE; /* install our the windows NAT module*/ - fprintf (stderr, "DEBUG: Setting IPv6 Forwarding for internal and external interface.\n"); + fprintf(stderr, "DEBUG: Setting IPv6 Forwarding for internal and external interface.\n"); /* outside interface (maybe that's already set) */ - snprintf (command, LINE_LEN, - "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled store=active", - argv[2]); - local_ret = execute_shellcommand (command); + snprintf(command, LINE_LEN, + "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled store=active", + argv[2]); + local_ret = execute_shellcommand(command); if (0 != local_ret) { - fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret)); + fprintf(stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror(local_ret)); goto cleanup; } /* internal interface */ - snprintf (command, LINE_LEN, - "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled advertise=enabled store=active", - device_visible_name); - local_ret = execute_shellcommand (command); + snprintf(command, LINE_LEN, + "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled advertise=enabled store=active", + device_visible_name); + local_ret = execute_shellcommand(command); if (0 != local_ret) { - fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret)); + fprintf(stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror(local_ret)); goto cleanup; } /* we can keep IPv6 forwarding around, as all interfaces have * their forwarding mode reset to false at bootup. */ } - if (0 != strcmp (argv[5], "-")) + if (0 != strcmp(argv[5], "-")) { const char *address = argv[5]; const char *mask = argv[6]; - fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n", address, mask); - if (0 != (global_ret = set_address4 (address, mask))) + fprintf(stderr, "DEBUG: Setting IP4 address: %s/%s\n", address, mask); + if (0 != (global_ret = set_address4(address, mask))) goto cleanup; // setup NAPT, if possible @@ -1620,36 +1626,36 @@ main (int argc, char **argv) * ... */ have_ip4 = TRUE; - if (0 != strcmp (argv[2], "-")) + if (0 != strcmp(argv[2], "-")) { char command[LINE_LEN]; /* install our the windows NAT module*/ - fprintf (stderr, "DEBUG: Adding NAPT/Masquerading between external IF %s and mine.\n", argv[2]); - local_ret = execute_shellcommand ("netsh routing ip nat install"); + fprintf(stderr, "DEBUG: Adding NAPT/Masquerading between external IF %s and mine.\n", argv[2]); + local_ret = execute_shellcommand("netsh routing ip nat install"); if (0 != local_ret) { - fprintf (stderr, "FATAL: Could not install NAPT support via Netsh: %s\n", strerror (local_ret)); + fprintf(stderr, "FATAL: Could not install NAPT support via Netsh: %s\n", strerror(local_ret)); goto cleanup; } /* external IF */ - snprintf (command, LINE_LEN, - "netsh routing ip nat add interface \"%s\" full", /*full = NAPT (addr+port)*/ - argv[2]); - local_ret = execute_shellcommand (command); + snprintf(command, LINE_LEN, + "netsh routing ip nat add interface \"%s\" full", /*full = NAPT (addr+port)*/ + argv[2]); + local_ret = execute_shellcommand(command); if (0 != local_ret) { - fprintf (stderr, "FATAL: IPv4-NAPT on external interface failed: %s\n", strerror (local_ret)); + fprintf(stderr, "FATAL: IPv4-NAPT on external interface failed: %s\n", strerror(local_ret)); goto cleanup; } /* private/internal/virtual IF */ - snprintf (command, LINE_LEN, - "netsh routing ip nat add interface \"%s\" private", - device_visible_name); - local_ret = execute_shellcommand (command); + snprintf(command, LINE_LEN, + "netsh routing ip nat add interface \"%s\" private", + device_visible_name); + local_ret = execute_shellcommand(command); if (0 != local_ret) { - fprintf (stderr, "FATAL: IPv4-NAPT on internal interface failed: %s\n", strerror (local_ret)); + fprintf(stderr, "FATAL: IPv4-NAPT on internal interface failed: %s\n", strerror(local_ret)); goto cleanup; have_nat44 = TRUE; @@ -1657,12 +1663,14 @@ main (int argc, char **argv) } } - run (handle); + run(handle); cleanup: - if (have_ip4) { + if (have_ip4) + { const char *address = argv[5]; - if (have_nat44) { + if (have_nat44) + { char command[LINE_LEN]; fprintf(stderr, "DEBUG: removing IP4 NAPT from virtual interface \n"); snprintf(command, LINE_LEN, @@ -1670,22 +1678,22 @@ cleanup: device_visible_name); local_ret = execute_shellcommand(command); if (0 != local_ret) - fprintf(stderr, "WARNING: Could not remove IPv4-NAPT from internal interface, hopefully this will have no effect in future runs: %s\n", strerror(local_ret)); - } + fprintf(stderr, "WARNING: Could not remove IPv4-NAPT from internal interface, hopefully this will have no effect in future runs: %s\n", strerror(local_ret)); + } fprintf(stderr, "DEBUG: Removing IP4 address\n"); - remove_address4 (address); - } + remove_address4(address); + } if (have_ip6) { const char *address = argv[3]; - fprintf (stderr, "DEBUG: Removing IP6 address\n"); - remove_address6 (address); + fprintf(stderr, "DEBUG: Removing IP6 address\n"); + remove_address6(address); } - fprintf (stderr, "DEBUG: removing interface\n"); - remove_interface (); - fprintf (stderr, "DEBUG: graceful exit completed\n"); + fprintf(stderr, "DEBUG: removing interface\n"); + remove_interface(); + fprintf(stderr, "DEBUG: graceful exit completed\n"); return global_ret; } diff --git a/src/exit/gnunet-helper-exit.c b/src/exit/gnunet-helper-exit.c index cda38710f..297a17813 100644 --- a/src/exit/gnunet-helper-exit.c +++ b/src/exit/gnunet-helper-exit.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file exit/gnunet-helper-exit.c @@ -81,8 +81,7 @@ static const char *sbin_iptables; /** * This is in linux/include/net/ipv6.h, but not always exported... */ -struct in6_ifreq -{ +struct in6_ifreq { struct in6_addr ifr6_addr; uint32_t ifr6_prefixlen; /* __u32 in the original */ int ifr6_ifindex; @@ -98,22 +97,22 @@ struct in6_ifreq * @param flags open flags (O_RDONLY, O_WRONLY) */ static void -open_dev_null (int target_fd, - int flags) +open_dev_null(int target_fd, + int flags) { int fd; - fd = open ("/dev/null", flags); + fd = open("/dev/null", flags); if (-1 == fd) - abort (); + abort(); if (fd == target_fd) return; - if (-1 == dup2 (fd, target_fd)) - { - (void) close (fd); - abort (); - } - (void) close (fd); + if (-1 == dup2(fd, target_fd)) + { + (void)close(fd); + abort(); + } + (void)close(fd); } @@ -125,49 +124,50 @@ open_dev_null (int target_fd, * @return 0 on success, 1 on any error */ static int -fork_and_exec (const char *file, - char *const cmd[]) +fork_and_exec(const char *file, + char *const cmd[]) { int status; pid_t pid; pid_t ret; - pid = fork (); + pid = fork(); if (-1 == pid) - { - fprintf (stderr, - "fork failed: %s\n", - strerror (errno)); - return 1; - } + { + fprintf(stderr, + "fork failed: %s\n", + strerror(errno)); + return 1; + } if (0 == pid) - { - /* we are the child process */ - /* close stdin/stdout to not cause interference - with the helper's main protocol! */ - (void) close (0); - open_dev_null (0, O_RDONLY); - (void) close (1); - open_dev_null (1, O_WRONLY); - (void) execv (file, cmd); - /* can only get here on error */ - fprintf (stderr, - "exec `%s' failed: %s\n", - file, - strerror (errno)); - _exit (1); - } + { + /* we are the child process */ + /* close stdin/stdout to not cause interference + with the helper's main protocol! */ + (void)close(0); + open_dev_null(0, O_RDONLY); + (void)close(1); + open_dev_null(1, O_WRONLY); + (void)execv(file, cmd); + /* can only get here on error */ + fprintf(stderr, + "exec `%s' failed: %s\n", + file, + strerror(errno)); + _exit(1); + } /* keep running waitpid as long as the only error we get is 'EINTR' */ - while ( (-1 == (ret = waitpid (pid, &status, 0))) && - (errno == EINTR) ); + while ((-1 == (ret = waitpid(pid, &status, 0))) && + (errno == EINTR)) + ; if (-1 == ret) - { - fprintf (stderr, - "waitpid failed: %s\n", - strerror (errno)); - return 1; - } - if (! (WIFEXITED (status) && (0 == WEXITSTATUS (status)))) + { + fprintf(stderr, + "waitpid failed: %s\n", + strerror(errno)); + return 1; + } + if (!(WIFEXITED(status) && (0 == WEXITSTATUS(status)))) return 1; /* child process completed and returned success, we're happy */ return 0; @@ -182,46 +182,46 @@ fork_and_exec (const char *file, * @return the fd to the tun or -1 on error */ static int -init_tun (char *dev) +init_tun(char *dev) { struct ifreq ifr; int fd; if (NULL == dev) - { - errno = EINVAL; - return -1; - } - - if (-1 == (fd = open ("/dev/net/tun", O_RDWR))) - { - fprintf (stderr, "Error opening `%s': %s\n", "/dev/net/tun", - strerror (errno)); - return -1; - } + { + errno = EINVAL; + return -1; + } + + if (-1 == (fd = open("/dev/net/tun", O_RDWR))) + { + fprintf(stderr, "Error opening `%s': %s\n", "/dev/net/tun", + strerror(errno)); + return -1; + } if (fd >= FD_SETSIZE) - { - fprintf (stderr, "File descriptor to large: %d", fd); - (void) close (fd); - return -1; - } + { + fprintf(stderr, "File descriptor to large: %d", fd); + (void)close(fd); + return -1; + } - memset (&ifr, 0, sizeof (ifr)); + memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TUN; if ('\0' != *dev) - strncpy (ifr.ifr_name, dev, IFNAMSIZ); - - if (-1 == ioctl (fd, TUNSETIFF, (void *) &ifr)) - { - fprintf (stderr, - "Error with ioctl on `%s': %s\n", "/dev/net/tun", - strerror (errno)); - (void) close (fd); - return -1; - } - strcpy (dev, ifr.ifr_name); + strncpy(ifr.ifr_name, dev, IFNAMSIZ); + + if (-1 == ioctl(fd, TUNSETIFF, (void *)&ifr)) + { + fprintf(stderr, + "Error with ioctl on `%s': %s\n", "/dev/net/tun", + strerror(errno)); + (void)close(fd); + return -1; + } + strcpy(dev, ifr.ifr_name); return fd; } @@ -234,7 +234,7 @@ init_tun (char *dev) * @param prefix_len the length of the network-prefix */ static void -set_address6 (const char *dev, const char *address, unsigned long prefix_len) +set_address6(const char *dev, const char *address, unsigned long prefix_len) { struct ifreq ifr; struct sockaddr_in6 sa6; @@ -244,34 +244,34 @@ set_address6 (const char *dev, const char *address, unsigned long prefix_len) /* * parse the new address */ - memset (&sa6, 0, sizeof (struct sockaddr_in6)); + memset(&sa6, 0, sizeof(struct sockaddr_in6)); sa6.sin6_family = AF_INET6; - if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr)) - { - fprintf (stderr, "Failed to parse address `%s': %s\n", address, - strerror (errno)); - exit (1); - } - - if (-1 == (fd = socket (PF_INET6, SOCK_DGRAM, 0))) - { - fprintf (stderr, "Error creating socket: %s\n", strerror (errno)); - exit (1); - } - - memset (&ifr, 0, sizeof (struct ifreq)); + if (1 != inet_pton(AF_INET6, address, &sa6.sin6_addr)) + { + fprintf(stderr, "Failed to parse address `%s': %s\n", address, + strerror(errno)); + exit(1); + } + + if (-1 == (fd = socket(PF_INET6, SOCK_DGRAM, 0))) + { + fprintf(stderr, "Error creating socket: %s\n", strerror(errno)); + exit(1); + } + + memset(&ifr, 0, sizeof(struct ifreq)); /* * Get the index of the if */ - strncpy (ifr.ifr_name, dev, IFNAMSIZ); - if (-1 == ioctl (fd, SIOGIFINDEX, &ifr)) - { - fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno)); - (void) close (fd); - exit (1); - } - - memset (&ifr6, 0, sizeof (struct in6_ifreq)); + strncpy(ifr.ifr_name, dev, IFNAMSIZ); + if (-1 == ioctl(fd, SIOGIFINDEX, &ifr)) + { + fprintf(stderr, "ioctl failed at %d: %s\n", __LINE__, strerror(errno)); + (void)close(fd); + exit(1); + } + + memset(&ifr6, 0, sizeof(struct in6_ifreq)); ifr6.ifr6_addr = sa6.sin6_addr; ifr6.ifr6_ifindex = ifr.ifr_ifindex; ifr6.ifr6_prefixlen = prefix_len; @@ -279,42 +279,42 @@ set_address6 (const char *dev, const char *address, unsigned long prefix_len) /* * Set the address */ - if (-1 == ioctl (fd, SIOCSIFADDR, &ifr6)) - { - fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__, - strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCSIFADDR, &ifr6)) + { + fprintf(stderr, "ioctl failed at line %d: %s\n", __LINE__, + strerror(errno)); + (void)close(fd); + exit(1); + } /* * Get the flags */ - if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr)) - { - fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__, - strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCGIFFLAGS, &ifr)) + { + fprintf(stderr, "ioctl failed at line %d: %s\n", __LINE__, + strerror(errno)); + (void)close(fd); + exit(1); + } /* * Add the UP and RUNNING flags */ ifr.ifr_flags |= IFF_UP | IFF_RUNNING; - if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr)) - { - fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__, - strerror (errno)); - (void) close (fd); - exit (1); - } - - if (0 != close (fd)) - { - fprintf (stderr, "close failed: %s\n", strerror (errno)); - exit (1); - } + if (-1 == ioctl(fd, SIOCSIFFLAGS, &ifr)) + { + fprintf(stderr, "ioctl failed at line %d: %s\n", __LINE__, + strerror(errno)); + (void)close(fd); + exit(1); + } + + if (0 != close(fd)) + { + fprintf(stderr, "close failed: %s\n", strerror(errno)); + exit(1); + } } @@ -326,96 +326,96 @@ set_address6 (const char *dev, const char *address, unsigned long prefix_len) * @param mask the netmask */ static void -set_address4 (const char *dev, const char *address, const char *mask) +set_address4(const char *dev, const char *address, const char *mask) { int fd; struct sockaddr_in *addr; struct ifreq ifr; - memset (&ifr, 0, sizeof (struct ifreq)); - addr = (struct sockaddr_in *) &(ifr.ifr_addr); + memset(&ifr, 0, sizeof(struct ifreq)); + addr = (struct sockaddr_in *)&(ifr.ifr_addr); addr->sin_family = AF_INET; /* * Parse the address */ - if (1 != inet_pton (AF_INET, address, &addr->sin_addr.s_addr)) - { - fprintf (stderr, "Failed to parse address `%s': %s\n", address, - strerror (errno)); - exit (1); - } + if (1 != inet_pton(AF_INET, address, &addr->sin_addr.s_addr)) + { + fprintf(stderr, "Failed to parse address `%s': %s\n", address, + strerror(errno)); + exit(1); + } - if (-1 == (fd = socket (PF_INET, SOCK_DGRAM, 0))) - { - fprintf (stderr, "Error creating socket: %s\n", strerror (errno)); - exit (1); - } + if (-1 == (fd = socket(PF_INET, SOCK_DGRAM, 0))) + { + fprintf(stderr, "Error creating socket: %s\n", strerror(errno)); + exit(1); + } - strncpy (ifr.ifr_name, dev, IFNAMSIZ); + strncpy(ifr.ifr_name, dev, IFNAMSIZ); /* * Set the address */ - if (-1 == ioctl (fd, SIOCSIFADDR, &ifr)) - { - fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCSIFADDR, &ifr)) + { + fprintf(stderr, "ioctl failed at %d: %s\n", __LINE__, strerror(errno)); + (void)close(fd); + exit(1); + } /* * Parse the netmask */ - addr = (struct sockaddr_in *) &(ifr.ifr_netmask); - if (1 != inet_pton (AF_INET, mask, &addr->sin_addr.s_addr)) - { - fprintf (stderr, "Failed to parse address `%s': %s\n", mask, - strerror (errno)); - (void) close (fd); - exit (1); - } + addr = (struct sockaddr_in *)&(ifr.ifr_netmask); + if (1 != inet_pton(AF_INET, mask, &addr->sin_addr.s_addr)) + { + fprintf(stderr, "Failed to parse address `%s': %s\n", mask, + strerror(errno)); + (void)close(fd); + exit(1); + } /* * Set the netmask */ - if (-1 == ioctl (fd, SIOCSIFNETMASK, &ifr)) - { - fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__, - strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCSIFNETMASK, &ifr)) + { + fprintf(stderr, "ioctl failed at line %d: %s\n", __LINE__, + strerror(errno)); + (void)close(fd); + exit(1); + } /* * Get the flags */ - if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr)) - { - fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__, - strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCGIFFLAGS, &ifr)) + { + fprintf(stderr, "ioctl failed at line %d: %s\n", __LINE__, + strerror(errno)); + (void)close(fd); + exit(1); + } /* * Add the UP and RUNNING flags */ ifr.ifr_flags |= IFF_UP | IFF_RUNNING; - if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr)) - { - fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__, - strerror (errno)); - (void) close (fd); - exit (1); - } - - if (0 != close (fd)) - { - fprintf (stderr, "close failed: %s\n", strerror (errno)); - (void) close (fd); - exit (1); - } + if (-1 == ioctl(fd, SIOCSIFFLAGS, &ifr)) + { + fprintf(stderr, "ioctl failed at line %d: %s\n", __LINE__, + strerror(errno)); + (void)close(fd); + exit(1); + } + + if (0 != close(fd)) + { + fprintf(stderr, "close failed: %s\n", strerror(errno)); + (void)close(fd); + exit(1); + } } @@ -425,7 +425,7 @@ set_address4 (const char *dev, const char *address, const char *mask) * @param fd_tun tunnel FD */ static void -run (int fd_tun) +run(int fd_tun) { /* * The buffer filled by reading from fd_tun @@ -452,188 +452,188 @@ run (int fd_tun) int write_open = 1; while ((1 == read_open) && (1 == write_open)) - { - FD_ZERO (&fds_w); - FD_ZERO (&fds_r); - - /* - * We are supposed to read and the buffer is empty - * -> select on read from tun - */ - if (read_open && (0 == buftun_size)) - FD_SET (fd_tun, &fds_r); - - /* - * We are supposed to read and the buffer is not empty - * -> select on write to stdout - */ - if (read_open && (0 != buftun_size)) - FD_SET (1, &fds_w); - - /* - * We are supposed to write and the buffer is empty - * -> select on read from stdin - */ - if (write_open && (NULL == bufin_read)) - FD_SET (0, &fds_r); - - /* - * We are supposed to write and the buffer is not empty - * -> select on write to tun - */ - if (write_open && (NULL != bufin_read)) - FD_SET (fd_tun, &fds_w); - - int r = select (fd_tun + 1, &fds_r, &fds_w, NULL, NULL); - - if (-1 == r) - { - if (EINTR == errno) - continue; - fprintf (stderr, "select failed: %s\n", strerror (errno)); - exit (1); - } - - if (r > 0) - { - if (FD_ISSET (fd_tun, &fds_r)) - { - buftun_size = - read (fd_tun, buftun + sizeof (struct GNUNET_MessageHeader), - MAX_SIZE - sizeof (struct GNUNET_MessageHeader)); - if (-1 == buftun_size) + { + FD_ZERO(&fds_w); + FD_ZERO(&fds_r); + + /* + * We are supposed to read and the buffer is empty + * -> select on read from tun + */ + if (read_open && (0 == buftun_size)) + FD_SET(fd_tun, &fds_r); + + /* + * We are supposed to read and the buffer is not empty + * -> select on write to stdout + */ + if (read_open && (0 != buftun_size)) + FD_SET(1, &fds_w); + + /* + * We are supposed to write and the buffer is empty + * -> select on read from stdin + */ + if (write_open && (NULL == bufin_read)) + FD_SET(0, &fds_r); + + /* + * We are supposed to write and the buffer is not empty + * -> select on write to tun + */ + if (write_open && (NULL != bufin_read)) + FD_SET(fd_tun, &fds_w); + + int r = select(fd_tun + 1, &fds_r, &fds_w, NULL, NULL); + + if (-1 == r) { - fprintf (stderr, - "read-error: %s\n", - strerror (errno)); - shutdown (fd_tun, SHUT_RD); - shutdown (1, SHUT_WR); - read_open = 0; - buftun_size = 0; + if (EINTR == errno) + continue; + fprintf(stderr, "select failed: %s\n", strerror(errno)); + exit(1); } - else if (0 == buftun_size) + + if (r > 0) { + if (FD_ISSET(fd_tun, &fds_r)) + { + buftun_size = + read(fd_tun, buftun + sizeof(struct GNUNET_MessageHeader), + MAX_SIZE - sizeof(struct GNUNET_MessageHeader)); + if (-1 == buftun_size) + { + fprintf(stderr, + "read-error: %s\n", + strerror(errno)); + shutdown(fd_tun, SHUT_RD); + shutdown(1, SHUT_WR); + read_open = 0; + buftun_size = 0; + } + else if (0 == buftun_size) + { #if DEBUG - fprintf (stderr, "EOF on tun\n"); + fprintf(stderr, "EOF on tun\n"); #endif - shutdown (fd_tun, SHUT_RD); - shutdown (1, SHUT_WR); - read_open = 0; - buftun_size = 0; - } - else - { - buftun_read = buftun; - struct GNUNET_MessageHeader *hdr = - (struct GNUNET_MessageHeader *) buftun; - buftun_size += sizeof (struct GNUNET_MessageHeader); - hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER); - hdr->size = htons (buftun_size); - } - } - else if (FD_ISSET (1, &fds_w)) - { - ssize_t written = write (1, buftun_read, buftun_size); - - if (-1 == written) - { + shutdown(fd_tun, SHUT_RD); + shutdown(1, SHUT_WR); + read_open = 0; + buftun_size = 0; + } + else + { + buftun_read = buftun; + struct GNUNET_MessageHeader *hdr = + (struct GNUNET_MessageHeader *)buftun; + buftun_size += sizeof(struct GNUNET_MessageHeader); + hdr->type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER); + hdr->size = htons(buftun_size); + } + } + else if (FD_ISSET(1, &fds_w)) + { + ssize_t written = write(1, buftun_read, buftun_size); + + if (-1 == written) + { #if !DEBUG - if (errno != EPIPE) + if (errno != EPIPE) #endif - fprintf (stderr, - "write-error to stdout: %s\n", - strerror (errno)); - shutdown (fd_tun, SHUT_RD); - shutdown (1, SHUT_WR); - read_open = 0; - buftun_size = 0; - } - else if (0 == written) - { - fprintf (stderr, "write returned 0!?\n"); - exit (1); - } - else - { - buftun_size -= written; - buftun_read += written; - } - } - - if (FD_ISSET (0, &fds_r)) - { - bufin_size = read (0, bufin + bufin_rpos, MAX_SIZE - bufin_rpos); - if (-1 == bufin_size) - { - fprintf (stderr, "read-error: %s\n", strerror (errno)); - shutdown (0, SHUT_RD); - shutdown (fd_tun, SHUT_WR); - write_open = 0; - bufin_size = 0; - } - else if (0 == bufin_size) - { + fprintf(stderr, + "write-error to stdout: %s\n", + strerror(errno)); + shutdown(fd_tun, SHUT_RD); + shutdown(1, SHUT_WR); + read_open = 0; + buftun_size = 0; + } + else if (0 == written) + { + fprintf(stderr, "write returned 0!?\n"); + exit(1); + } + else + { + buftun_size -= written; + buftun_read += written; + } + } + + if (FD_ISSET(0, &fds_r)) + { + bufin_size = read(0, bufin + bufin_rpos, MAX_SIZE - bufin_rpos); + if (-1 == bufin_size) + { + fprintf(stderr, "read-error: %s\n", strerror(errno)); + shutdown(0, SHUT_RD); + shutdown(fd_tun, SHUT_WR); + write_open = 0; + bufin_size = 0; + } + else if (0 == bufin_size) + { #if DEBUG - fprintf (stderr, "EOF on stdin\n"); + fprintf(stderr, "EOF on stdin\n"); #endif - shutdown (0, SHUT_RD); - shutdown (fd_tun, SHUT_WR); - write_open = 0; - bufin_size = 0; - } - else - { - struct GNUNET_MessageHeader *hdr; + shutdown(0, SHUT_RD); + shutdown(fd_tun, SHUT_WR); + write_open = 0; + bufin_size = 0; + } + else + { + struct GNUNET_MessageHeader *hdr; PROCESS_BUFFER: - bufin_rpos += bufin_size; - if (bufin_rpos < sizeof (struct GNUNET_MessageHeader)) - continue; - hdr = (struct GNUNET_MessageHeader *) bufin; - if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) - { - fprintf (stderr, "protocol violation!\n"); - exit (1); - } - if (ntohs (hdr->size) > bufin_rpos) - continue; - bufin_read = bufin + sizeof (struct GNUNET_MessageHeader); - bufin_size = ntohs (hdr->size) - sizeof (struct GNUNET_MessageHeader); - bufin_rpos -= bufin_size + sizeof (struct GNUNET_MessageHeader); - } - } - else if (FD_ISSET (fd_tun, &fds_w)) - { - ssize_t written = write (fd_tun, bufin_read, bufin_size); - - if (-1 == written) - { - fprintf (stderr, "write-error to tun: %s\n", strerror (errno)); - shutdown (0, SHUT_RD); - shutdown (fd_tun, SHUT_WR); - write_open = 0; - bufin_size = 0; + bufin_rpos += bufin_size; + if (bufin_rpos < sizeof(struct GNUNET_MessageHeader)) + continue; + hdr = (struct GNUNET_MessageHeader *)bufin; + if (ntohs(hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) + { + fprintf(stderr, "protocol violation!\n"); + exit(1); + } + if (ntohs(hdr->size) > bufin_rpos) + continue; + bufin_read = bufin + sizeof(struct GNUNET_MessageHeader); + bufin_size = ntohs(hdr->size) - sizeof(struct GNUNET_MessageHeader); + bufin_rpos -= bufin_size + sizeof(struct GNUNET_MessageHeader); + } + } + else if (FD_ISSET(fd_tun, &fds_w)) + { + ssize_t written = write(fd_tun, bufin_read, bufin_size); + + if (-1 == written) + { + fprintf(stderr, "write-error to tun: %s\n", strerror(errno)); + shutdown(0, SHUT_RD); + shutdown(fd_tun, SHUT_WR); + write_open = 0; + bufin_size = 0; + } + else if (0 == written) + { + fprintf(stderr, "write returned 0!?\n"); + exit(1); + } + else + { + bufin_size -= written; + bufin_read += written; + if (0 == bufin_size) + { + memmove(bufin, bufin_read, bufin_rpos); + bufin_read = NULL; /* start reading again */ + bufin_size = 0; + goto PROCESS_BUFFER; + } + } + } } - else if (0 == written) - { - fprintf (stderr, "write returned 0!?\n"); - exit (1); - } - else - { - bufin_size -= written; - bufin_read += written; - if (0 == bufin_size) - { - memmove (bufin, bufin_read, bufin_rpos); - bufin_read = NULL; /* start reading again */ - bufin_size = 0; - goto PROCESS_BUFFER; - } - } - } } - } } @@ -651,166 +651,166 @@ PROCESS_BUFFER: * 6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"] */ int -main (int argc, char **argv) +main(int argc, char **argv) { char dev[IFNAMSIZ]; int fd_tun; int global_ret; if (7 != argc) - { - fprintf (stderr, "Fatal: must supply 6 arguments!\n"); - return 1; - } - if ( (0 == strcmp (argv[3], "-")) && - (0 == strcmp (argv[5], "-")) ) - { - fprintf (stderr, "Fatal: disabling both IPv4 and IPv6 makes no sense.\n"); - return 1; - } - if (0 != strcmp (argv[2], "-")) - { -#ifdef IPTABLES - if (0 == access (IPTABLES, X_OK)) - sbin_iptables = IPTABLES; - else -#endif - if (0 == access ("/sbin/iptables", X_OK)) - sbin_iptables = "/sbin/iptables"; - else if (0 == access ("/usr/sbin/iptables", X_OK)) - sbin_iptables = "/usr/sbin/iptables"; - else - { - fprintf (stderr, - "Fatal: executable iptables not found in approved directories: %s\n", - strerror (errno)); + { + fprintf(stderr, "Fatal: must supply 6 arguments!\n"); return 1; } + if ((0 == strcmp(argv[3], "-")) && + (0 == strcmp(argv[5], "-"))) + { + fprintf(stderr, "Fatal: disabling both IPv4 and IPv6 makes no sense.\n"); + return 1; + } + if (0 != strcmp(argv[2], "-")) + { +#ifdef IPTABLES + if (0 == access(IPTABLES, X_OK)) + sbin_iptables = IPTABLES; + else +#endif + if (0 == access("/sbin/iptables", X_OK)) + sbin_iptables = "/sbin/iptables"; + else if (0 == access("/usr/sbin/iptables", X_OK)) + sbin_iptables = "/usr/sbin/iptables"; + else + { + fprintf(stderr, + "Fatal: executable iptables not found in approved directories: %s\n", + strerror(errno)); + return 1; + } #ifdef SYSCTL - if (0 == access (SYSCTL, X_OK)) - sbin_sysctl = SYSCTL; - else + if (0 == access(SYSCTL, X_OK)) + sbin_sysctl = SYSCTL; + else #endif - if (0 == access ("/sbin/sysctl", X_OK)) - sbin_sysctl = "/sbin/sysctl"; - else if (0 == access ("/usr/sbin/sysctl", X_OK)) - sbin_sysctl = "/usr/sbin/sysctl"; - else - { - fprintf (stderr, - "Fatal: executable sysctl not found in approved directories: %s\n", - strerror (errno)); - return 1; + if (0 == access("/sbin/sysctl", X_OK)) + sbin_sysctl = "/sbin/sysctl"; + else if (0 == access("/usr/sbin/sysctl", X_OK)) + sbin_sysctl = "/usr/sbin/sysctl"; + else + { + fprintf(stderr, + "Fatal: executable sysctl not found in approved directories: %s\n", + strerror(errno)); + return 1; + } } - } - strncpy (dev, argv[1], IFNAMSIZ); + strncpy(dev, argv[1], IFNAMSIZ); dev[IFNAMSIZ - 1] = '\0'; - if (-1 == (fd_tun = init_tun (dev))) - { - fprintf (stderr, - "Fatal: could not initialize tun-interface `%s' with IPv6 %s/%s and IPv4 %s/%s\n", - dev, - argv[3], - argv[4], - argv[5], - argv[6]); - return 1; - } - - if (0 != strcmp (argv[3], "-")) - { + if (-1 == (fd_tun = init_tun(dev))) { - const char *address = argv[3]; - long prefix_len = atol (argv[4]); - - if ((prefix_len < 1) || (prefix_len > 127)) - { - fprintf (stderr, "Fatal: prefix_len out of range\n"); - return 1; - } - set_address6 (dev, address, prefix_len); + fprintf(stderr, + "Fatal: could not initialize tun-interface `%s' with IPv6 %s/%s and IPv4 %s/%s\n", + dev, + argv[3], + argv[4], + argv[5], + argv[6]); + return 1; } - if (0 != strcmp (argv[2], "-")) + + if (0 != strcmp(argv[3], "-")) { - char *const sysctl_args[] = - { - "sysctl", "-w", "net.ipv6.conf.all.forwarding=1", NULL - }; - if (0 != fork_and_exec (sbin_sysctl, - sysctl_args)) { - fprintf (stderr, - "Failed to enable IPv6 forwarding. Will continue anyway.\n"); + const char *address = argv[3]; + long prefix_len = atol(argv[4]); + + if ((prefix_len < 1) || (prefix_len > 127)) + { + fprintf(stderr, "Fatal: prefix_len out of range\n"); + return 1; + } + set_address6(dev, address, prefix_len); } + if (0 != strcmp(argv[2], "-")) + { + char *const sysctl_args[] = + { + "sysctl", "-w", "net.ipv6.conf.all.forwarding=1", NULL + }; + if (0 != fork_and_exec(sbin_sysctl, + sysctl_args)) + { + fprintf(stderr, + "Failed to enable IPv6 forwarding. Will continue anyway.\n"); + } + } } - } - if (0 != strcmp (argv[5], "-")) - { - { - const char *address = argv[5]; - const char *mask = argv[6]; - - set_address4 (dev, address, mask); - } - if (0 != strcmp (argv[2], "-")) + if (0 != strcmp(argv[5], "-")) { { - char *const sysctl_args[] = - { - "sysctl", "-w", "net.ipv4.ip_forward=1", NULL - }; - if (0 != fork_and_exec (sbin_sysctl, - sysctl_args)) - { - fprintf (stderr, - "Failed to enable IPv4 forwarding. Will continue anyway.\n"); - } + const char *address = argv[5]; + const char *mask = argv[6]; + + set_address4(dev, address, mask); } - { - char *const iptables_args[] = - { - "iptables", "-t", "nat", "-A", "POSTROUTING", "-o", argv[2], "-j", "MASQUERADE", NULL - }; - if (0 != fork_and_exec (sbin_iptables, - iptables_args)) + if (0 != strcmp(argv[2], "-")) { - fprintf (stderr, - "Failed to enable IPv4 masquerading (NAT). Will continue anyway.\n"); + { + char *const sysctl_args[] = + { + "sysctl", "-w", "net.ipv4.ip_forward=1", NULL + }; + if (0 != fork_and_exec(sbin_sysctl, + sysctl_args)) + { + fprintf(stderr, + "Failed to enable IPv4 forwarding. Will continue anyway.\n"); + } + } + { + char *const iptables_args[] = + { + "iptables", "-t", "nat", "-A", "POSTROUTING", "-o", argv[2], "-j", "MASQUERADE", NULL + }; + if (0 != fork_and_exec(sbin_iptables, + iptables_args)) + { + fprintf(stderr, + "Failed to enable IPv4 masquerading (NAT). Will continue anyway.\n"); + } + } } - } } - } - uid_t uid = getuid (); + uid_t uid = getuid(); #ifdef HAVE_SETRESUID - if (0 != setresuid (uid, uid, uid)) - { - fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno)); - global_ret = 2; - goto cleanup; - } + if (0 != setresuid(uid, uid, uid)) + { + fprintf(stderr, "Failed to setresuid: %s\n", strerror(errno)); + global_ret = 2; + goto cleanup; + } #else - if (0 != (setuid (uid) | seteuid (uid))) - { - fprintf (stderr, "Failed to setuid: %s\n", strerror (errno)); - global_ret = 2; - goto cleanup; - } + if (0 != (setuid(uid) | seteuid(uid))) + { + fprintf(stderr, "Failed to setuid: %s\n", strerror(errno)); + global_ret = 2; + goto cleanup; + } #endif - if (SIG_ERR == signal (SIGPIPE, SIG_IGN)) - { - fprintf (stderr, "Failed to protect against SIGPIPE: %s\n", - strerror (errno)); - /* no exit, we might as well die with SIGPIPE should it ever happen */ - } - run (fd_tun); + if (SIG_ERR == signal(SIGPIPE, SIG_IGN)) + { + fprintf(stderr, "Failed to protect against SIGPIPE: %s\n", + strerror(errno)); + /* no exit, we might as well die with SIGPIPE should it ever happen */ + } + run(fd_tun); global_ret = 0; - cleanup: - (void) close (fd_tun); +cleanup: + (void)close(fd_tun); return global_ret; } diff --git a/src/fragmentation/defragmentation.c b/src/fragmentation/defragmentation.c index bbe6f3741..d68a98c52 100644 --- a/src/fragmentation/defragmentation.c +++ b/src/fragmentation/defragmentation.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/fragmentation/defragmentation.c * @brief library to help defragment messages @@ -29,8 +29,7 @@ /** * Timestamps for fragments. */ -struct FragTimes -{ +struct FragTimes { /** * The time the fragment was received. */ @@ -49,8 +48,7 @@ struct FragTimes * handle 'stray' messages that are received 'late'. A message * context is ONLY discarded when the queue gets too big. */ -struct MessageContext -{ +struct MessageContext { /** * This is a DLL. */ @@ -128,16 +126,13 @@ struct MessageContext * Was the last fragment we got a duplicate? */ int16_t last_duplicate; - }; /** * Defragmentation context (one per connection). */ -struct GNUNET_DEFRAGMENT_Context -{ - +struct GNUNET_DEFRAGMENT_Context { /** * For statistics. */ @@ -190,7 +185,6 @@ struct GNUNET_DEFRAGMENT_Context * Maximum message size for each fragment. */ uint16_t mtu; - }; @@ -208,15 +202,15 @@ struct GNUNET_DEFRAGMENT_Context * @return the defragmentation context */ struct GNUNET_DEFRAGMENT_Context * -GNUNET_DEFRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats, - uint16_t mtu, unsigned int num_msgs, - void *cls, - GNUNET_FRAGMENT_MessageProcessor proc, - GNUNET_DEFRAGMENT_AckProcessor ackp) +GNUNET_DEFRAGMENT_context_create(struct GNUNET_STATISTICS_Handle *stats, + uint16_t mtu, unsigned int num_msgs, + void *cls, + GNUNET_FRAGMENT_MessageProcessor proc, + GNUNET_DEFRAGMENT_AckProcessor ackp) { struct GNUNET_DEFRAGMENT_Context *dc; - dc = GNUNET_new (struct GNUNET_DEFRAGMENT_Context); + dc = GNUNET_new(struct GNUNET_DEFRAGMENT_Context); dc->stats = stats; dc->cls = cls; dc->proc = proc; @@ -234,23 +228,23 @@ GNUNET_DEFRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats, * @param dc defragmentation context */ void -GNUNET_DEFRAGMENT_context_destroy (struct GNUNET_DEFRAGMENT_Context *dc) +GNUNET_DEFRAGMENT_context_destroy(struct GNUNET_DEFRAGMENT_Context *dc) { struct MessageContext *mc; while (NULL != (mc = dc->head)) - { - GNUNET_CONTAINER_DLL_remove (dc->head, dc->tail, mc); - dc->list_size--; - if (NULL != mc->ack_task) { - GNUNET_SCHEDULER_cancel (mc->ack_task); - mc->ack_task = NULL; + GNUNET_CONTAINER_DLL_remove(dc->head, dc->tail, mc); + dc->list_size--; + if (NULL != mc->ack_task) + { + GNUNET_SCHEDULER_cancel(mc->ack_task); + mc->ack_task = NULL; + } + GNUNET_free(mc); } - GNUNET_free (mc); - } - GNUNET_assert (0 == dc->list_size); - GNUNET_free (dc); + GNUNET_assert(0 == dc->list_size); + GNUNET_free(dc); } @@ -260,25 +254,25 @@ GNUNET_DEFRAGMENT_context_destroy (struct GNUNET_DEFRAGMENT_Context *dc) * @param cls the message context */ static void -send_ack (void *cls) +send_ack(void *cls) { struct MessageContext *mc = cls; struct GNUNET_DEFRAGMENT_Context *dc = mc->dc; struct FragmentAcknowledgement fa; mc->ack_task = NULL; - fa.header.size = htons (sizeof (struct FragmentAcknowledgement)); - fa.header.type = htons (GNUNET_MESSAGE_TYPE_FRAGMENT_ACK); - fa.fragment_id = htonl (mc->fragment_id); - fa.bits = GNUNET_htonll (mc->bits); - GNUNET_STATISTICS_update (mc->dc->stats, - _("# acknowledgements sent for fragment"), - 1, - GNUNET_NO); + fa.header.size = htons(sizeof(struct FragmentAcknowledgement)); + fa.header.type = htons(GNUNET_MESSAGE_TYPE_FRAGMENT_ACK); + fa.fragment_id = htonl(mc->fragment_id); + fa.bits = GNUNET_htonll(mc->bits); + GNUNET_STATISTICS_update(mc->dc->stats, + _("# acknowledgements sent for fragment"), + 1, + GNUNET_NO); mc->last_duplicate = GNUNET_NO; /* clear flag */ - dc->ackp (dc->cls, - mc->fragment_id, - &fa.header); + dc->ackp(dc->cls, + mc->fragment_id, + &fa.header); } @@ -287,28 +281,28 @@ send_ack (void *cls) * Copyright (C) 2000 Brian Gough */ static void -gsl_fit_mul (const double *x, const size_t xstride, const double *y, - const size_t ystride, const size_t n, double *c1, double *cov_11, - double *sumsq) +gsl_fit_mul(const double *x, const size_t xstride, const double *y, + const size_t ystride, const size_t n, double *c1, double *cov_11, + double *sumsq) { double m_x = 0, m_y = 0, m_dx2 = 0, m_dxdy = 0; size_t i; for (i = 0; i < n; i++) - { - m_x += (x[i * xstride] - m_x) / (i + 1.0); - m_y += (y[i * ystride] - m_y) / (i + 1.0); - } + { + m_x += (x[i * xstride] - m_x) / (i + 1.0); + m_y += (y[i * ystride] - m_y) / (i + 1.0); + } for (i = 0; i < n; i++) - { - const double dx = x[i * xstride] - m_x; - const double dy = y[i * ystride] - m_y; + { + const double dx = x[i * xstride] - m_x; + const double dy = y[i * ystride] - m_y; - m_dx2 += (dx * dx - m_dx2) / (i + 1.0); - m_dxdy += (dx * dy - m_dxdy) / (i + 1.0); - } + m_dx2 += (dx * dx - m_dx2) / (i + 1.0); + m_dxdy += (dx * dy - m_dxdy) / (i + 1.0); + } /* In terms of y = b x */ @@ -321,13 +315,13 @@ gsl_fit_mul (const double *x, const size_t xstride, const double *y, /* Compute chi^2 = \sum (y_i - b * x_i)^2 */ for (i = 0; i < n; i++) - { - const double dx = x[i * xstride] - m_x; - const double dy = y[i * ystride] - m_y; - const double d = (m_y - b * m_x) + dy - b * dx; + { + const double dx = x[i * xstride] - m_x; + const double dy = y[i * ystride] - m_y; + const double d = (m_y - b * m_x) + dy - b * dx; - d2 += d * d; - } + d2 += d * d; + } s2 = d2 / (n - 1.0); /* chisq per degree of freedom */ @@ -346,7 +340,7 @@ gsl_fit_mul (const double *x, const size_t xstride, const double *y, * @return average delay between time stamps (based on least-squares fit) */ static struct GNUNET_TIME_Relative -estimate_latency (struct MessageContext *mc) +estimate_latency(struct MessageContext *mc) { struct FragTimes *first; size_t total = mc->frag_times_write_offset - mc->frag_times_start_offset; @@ -359,15 +353,15 @@ estimate_latency (struct MessageContext *mc) struct GNUNET_TIME_Relative ret; first = &mc->frag_times[mc->frag_times_start_offset]; - GNUNET_assert (total > 1); + GNUNET_assert(total > 1); for (i = 0; i < total; i++) - { - x[i] = (double) i; - y[i] = (double) (first[i].time.abs_value_us - first[0].time.abs_value_us); - } - gsl_fit_mul (x, 1, y, 1, total, &c1, &cov11, &sumsq); - c1 += sqrt (sumsq); /* add 1 std dev */ - ret.rel_value_us = (uint64_t) c1; + { + x[i] = (double)i; + y[i] = (double)(first[i].time.abs_value_us - first[0].time.abs_value_us); + } + gsl_fit_mul(x, 1, y, 1, total, &c1, &cov11, &sumsq); + c1 += sqrt(sumsq); /* add 1 std dev */ + ret.rel_value_us = (uint64_t)c1; if (0 == ret.rel_value_us) ret = GNUNET_TIME_UNIT_MICROSECONDS; /* always at least 1 */ return ret; @@ -380,7 +374,7 @@ estimate_latency (struct MessageContext *mc) * @param dc defragmentation context */ static void -discard_oldest_mc (struct GNUNET_DEFRAGMENT_Context *dc) +discard_oldest_mc(struct GNUNET_DEFRAGMENT_Context *dc) { struct MessageContext *old; struct MessageContext *pos; @@ -388,21 +382,21 @@ discard_oldest_mc (struct GNUNET_DEFRAGMENT_Context *dc) old = NULL; pos = dc->head; while (NULL != pos) - { - if ((old == NULL) || - (old->last_update.abs_value_us > pos->last_update.abs_value_us)) - old = pos; - pos = pos->next; - } - GNUNET_assert (NULL != old); - GNUNET_CONTAINER_DLL_remove (dc->head, dc->tail, old); + { + if ((old == NULL) || + (old->last_update.abs_value_us > pos->last_update.abs_value_us)) + old = pos; + pos = pos->next; + } + GNUNET_assert(NULL != old); + GNUNET_CONTAINER_DLL_remove(dc->head, dc->tail, old); dc->list_size--; if (NULL != old->ack_task) - { - GNUNET_SCHEDULER_cancel (old->ack_task); - old->ack_task = NULL; - } - GNUNET_free (old); + { + GNUNET_SCHEDULER_cancel(old->ack_task); + old->ack_task = NULL; + } + GNUNET_free(old); } @@ -416,8 +410,8 @@ discard_oldest_mc (struct GNUNET_DEFRAGMENT_Context *dc) * #GNUNET_SYSERR on error */ int -GNUNET_DEFRAGMENT_process_fragment (struct GNUNET_DEFRAGMENT_Context *dc, - const struct GNUNET_MessageHeader *msg) +GNUNET_DEFRAGMENT_process_fragment(struct GNUNET_DEFRAGMENT_Context *dc, + const struct GNUNET_MessageHeader *msg) { struct MessageContext *mc; const struct FragmentHeader *fh; @@ -435,40 +429,40 @@ GNUNET_DEFRAGMENT_process_fragment (struct GNUNET_DEFRAGMENT_Context *dc, int duplicate; int last; - if (ntohs (msg->size) < sizeof (struct FragmentHeader)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if (ntohs (msg->size) > dc->mtu) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - fh = (const struct FragmentHeader *) msg; - msize = ntohs (fh->total_size); - if (msize < sizeof (struct GNUNET_MessageHeader)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - fid = ntohl (fh->fragment_id); - foff = ntohs (fh->offset); + if (ntohs(msg->size) < sizeof(struct FragmentHeader)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if (ntohs(msg->size) > dc->mtu) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + fh = (const struct FragmentHeader *)msg; + msize = ntohs(fh->total_size); + if (msize < sizeof(struct GNUNET_MessageHeader)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + fid = ntohl(fh->fragment_id); + foff = ntohs(fh->offset); if (foff >= msize) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if (0 != (foff % (dc->mtu - sizeof (struct FragmentHeader)))) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - GNUNET_STATISTICS_update (dc->stats, - _("# fragments received"), - 1, - GNUNET_NO); - num_fragments = (ntohs (msg->size) + dc->mtu - sizeof (struct FragmentHeader)-1) / (dc->mtu - sizeof (struct FragmentHeader)); + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if (0 != (foff % (dc->mtu - sizeof(struct FragmentHeader)))) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + GNUNET_STATISTICS_update(dc->stats, + _("# fragments received"), + 1, + GNUNET_NO); + num_fragments = (ntohs(msg->size) + dc->mtu - sizeof(struct FragmentHeader) - 1) / (dc->mtu - sizeof(struct FragmentHeader)); last = 0; for (mc = dc->head; NULL != mc; mc = mc->next) if (mc->fragment_id > fid) @@ -477,68 +471,68 @@ GNUNET_DEFRAGMENT_process_fragment (struct GNUNET_DEFRAGMENT_Context *dc, mc = dc->head; while ((NULL != mc) && (fid != mc->fragment_id)) mc = mc->next; - bit = foff / (dc->mtu - sizeof (struct FragmentHeader)); - if (bit * (dc->mtu - sizeof (struct FragmentHeader)) + ntohs (msg->size) - - sizeof (struct FragmentHeader) > msize) - { - /* payload extends past total message size */ - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + bit = foff / (dc->mtu - sizeof(struct FragmentHeader)); + if (bit * (dc->mtu - sizeof(struct FragmentHeader)) + ntohs(msg->size) - + sizeof(struct FragmentHeader) > msize) + { + /* payload extends past total message size */ + GNUNET_break_op(0); + return GNUNET_SYSERR; + } if ((NULL != mc) && (msize != mc->total_size)) - { - /* inconsistent message size */ - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - now = GNUNET_TIME_absolute_get (); + { + /* inconsistent message size */ + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + now = GNUNET_TIME_absolute_get(); if (NULL == mc) - { - mc = GNUNET_malloc (sizeof (struct MessageContext) + msize); - mc->msg = (const struct GNUNET_MessageHeader *) &mc[1]; - mc->dc = dc; - mc->total_size = msize; - mc->fragment_id = fid; - mc->last_update = now; - n = (msize + dc->mtu - sizeof (struct FragmentHeader) - 1) / (dc->mtu - - sizeof (struct + { + mc = GNUNET_malloc(sizeof(struct MessageContext) + msize); + mc->msg = (const struct GNUNET_MessageHeader *)&mc[1]; + mc->dc = dc; + mc->total_size = msize; + mc->fragment_id = fid; + mc->last_update = now; + n = (msize + dc->mtu - sizeof(struct FragmentHeader) - 1) / (dc->mtu - + sizeof(struct FragmentHeader)); - if (n == 64) - mc->bits = UINT64_MAX; /* set all 64 bit */ - else - mc->bits = (1LLU << n) - 1; /* set lowest 'bits' bit */ - if (dc->list_size >= dc->num_msgs) - discard_oldest_mc (dc); - GNUNET_CONTAINER_DLL_insert (dc->head, - dc->tail, - mc); - dc->list_size++; - } + if (n == 64) + mc->bits = UINT64_MAX; /* set all 64 bit */ + else + mc->bits = (1LLU << n) - 1; /* set lowest 'bits' bit */ + if (dc->list_size >= dc->num_msgs) + discard_oldest_mc(dc); + GNUNET_CONTAINER_DLL_insert(dc->head, + dc->tail, + mc); + dc->list_size++; + } /* copy data to 'mc' */ if (0 != (mc->bits & (1LLU << bit))) - { - mc->bits -= 1LLU << bit; - mbuf = (char *) &mc[1]; - GNUNET_memcpy (&mbuf[bit * (dc->mtu - sizeof (struct FragmentHeader))], &fh[1], - ntohs (msg->size) - sizeof (struct FragmentHeader)); - mc->last_update = now; - if (bit < mc->last_bit) - mc->frag_times_start_offset = mc->frag_times_write_offset; - mc->last_bit = bit; - mc->frag_times[mc->frag_times_write_offset].time = now; - mc->frag_times[mc->frag_times_write_offset].bit = bit; - mc->frag_times_write_offset++; - duplicate = GNUNET_NO; - } + { + mc->bits -= 1LLU << bit; + mbuf = (char *)&mc[1]; + GNUNET_memcpy(&mbuf[bit * (dc->mtu - sizeof(struct FragmentHeader))], &fh[1], + ntohs(msg->size) - sizeof(struct FragmentHeader)); + mc->last_update = now; + if (bit < mc->last_bit) + mc->frag_times_start_offset = mc->frag_times_write_offset; + mc->last_bit = bit; + mc->frag_times[mc->frag_times_write_offset].time = now; + mc->frag_times[mc->frag_times_write_offset].bit = bit; + mc->frag_times_write_offset++; + duplicate = GNUNET_NO; + } else - { - duplicate = GNUNET_YES; - GNUNET_STATISTICS_update (dc->stats, - _("# duplicate fragments received"), - 1, - GNUNET_NO); - } + { + duplicate = GNUNET_YES; + GNUNET_STATISTICS_update(dc->stats, + _("# duplicate fragments received"), + 1, + GNUNET_NO); + } /* count number of missing fragments after the current one */ bc = 0; @@ -549,41 +543,41 @@ GNUNET_DEFRAGMENT_process_fragment (struct GNUNET_DEFRAGMENT_Context *dc, bc = 0; /* notify about complete message */ - if ( (GNUNET_NO == duplicate) && - (0 == mc->bits) ) - { - GNUNET_STATISTICS_update (dc->stats, - _("# messages defragmented"), - 1, - GNUNET_NO); - /* message complete, notify! */ - dc->proc (dc->cls, mc->msg); - } + if ((GNUNET_NO == duplicate) && + (0 == mc->bits)) + { + GNUNET_STATISTICS_update(dc->stats, + _("# messages defragmented"), + 1, + GNUNET_NO); + /* message complete, notify! */ + dc->proc(dc->cls, mc->msg); + } /* send ACK */ if (mc->frag_times_write_offset - mc->frag_times_start_offset > 1) - { - dc->latency = estimate_latency (mc); - } - delay = GNUNET_TIME_relative_saturating_multiply (dc->latency, - bc + 1); - if ( (last + fid == num_fragments) || - (0 == mc->bits) || - (GNUNET_YES == duplicate) ) - { - /* message complete or duplicate or last missing fragment in - linear sequence; ACK now! */ - delay = GNUNET_TIME_UNIT_ZERO; - } + { + dc->latency = estimate_latency(mc); + } + delay = GNUNET_TIME_relative_saturating_multiply(dc->latency, + bc + 1); + if ((last + fid == num_fragments) || + (0 == mc->bits) || + (GNUNET_YES == duplicate)) + { + /* message complete or duplicate or last missing fragment in + linear sequence; ACK now! */ + delay = GNUNET_TIME_UNIT_ZERO; + } if (NULL != mc->ack_task) - GNUNET_SCHEDULER_cancel (mc->ack_task); - mc->ack_task = GNUNET_SCHEDULER_add_delayed (delay, - &send_ack, - mc); + GNUNET_SCHEDULER_cancel(mc->ack_task); + mc->ack_task = GNUNET_SCHEDULER_add_delayed(delay, + &send_ack, + mc); if (GNUNET_YES == duplicate) - { - mc->last_duplicate = GNUNET_YES; - return GNUNET_NO; - } + { + mc->last_duplicate = GNUNET_YES; + return GNUNET_NO; + } return GNUNET_YES; } diff --git a/src/fragmentation/fragmentation.c b/src/fragmentation/fragmentation.c index 9fca6eef0..5f31f9094 100644 --- a/src/fragmentation/fragmentation.c +++ b/src/fragmentation/fragmentation.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/fragmentation/fragmentation.c * @brief library to help fragment messages @@ -31,14 +31,13 @@ /** * Absolute minimum delay we impose between sending and expecting ACK to arrive. */ -#define MIN_ACK_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 1) +#define MIN_ACK_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 1) /** * Fragmentation context. */ -struct GNUNET_FRAGMENT_Context -{ +struct GNUNET_FRAGMENT_Context { /** * Statistics to use. */ @@ -134,7 +133,6 @@ struct GNUNET_FRAGMENT_Context * Target fragment size. */ uint16_t mtu; - }; @@ -145,20 +143,20 @@ struct GNUNET_FRAGMENT_Context * @return ack in human-readable format */ const char * -GNUNET_FRAGMENT_print_ack (const struct GNUNET_MessageHeader *ack) +GNUNET_FRAGMENT_print_ack(const struct GNUNET_MessageHeader *ack) { static char buf[128]; const struct FragmentAcknowledgement *fa; - if (sizeof (struct FragmentAcknowledgement) != - htons (ack->size)) + if (sizeof(struct FragmentAcknowledgement) != + htons(ack->size)) return ""; - fa = (const struct FragmentAcknowledgement *) ack; - GNUNET_snprintf (buf, - sizeof (buf), - "%u-%llX", - ntohl (fa->fragment_id), - GNUNET_ntohll (fa->bits)); + fa = (const struct FragmentAcknowledgement *)ack; + GNUNET_snprintf(buf, + sizeof(buf), + "%u-%llX", + ntohl(fa->fragment_id), + GNUNET_ntohll(fa->bits)); return buf; } @@ -169,7 +167,7 @@ GNUNET_FRAGMENT_print_ack (const struct GNUNET_MessageHeader *ack) * @param cls the `struct GNUNET_FRAGMENT_Context` */ static void -transmit_next (void *cls) +transmit_next(void *cls) { struct GNUNET_FRAGMENT_Context *fc = cls; char msg[fc->mtu]; @@ -182,108 +180,108 @@ transmit_next (void *cls) int wrap; fc->task = NULL; - GNUNET_assert (GNUNET_NO == fc->proc_busy); + GNUNET_assert(GNUNET_NO == fc->proc_busy); if (0 == fc->acks) return; /* all done */ /* calculate delay */ wrap = 0; while (0 == (fc->acks & (1LLU << fc->next_transmission))) - { - fc->next_transmission = (fc->next_transmission + 1) % 64; - wrap |= (0 == fc->next_transmission); - } + { + fc->next_transmission = (fc->next_transmission + 1) % 64; + wrap |= (0 == fc->next_transmission); + } bit = fc->next_transmission; - size = ntohs (fc->msg->size); - if (bit == size / (fc->mtu - sizeof (struct FragmentHeader))) + size = ntohs(fc->msg->size); + if (bit == size / (fc->mtu - sizeof(struct FragmentHeader))) fsize = - (size % (fc->mtu - sizeof (struct FragmentHeader))) + - sizeof (struct FragmentHeader); + (size % (fc->mtu - sizeof(struct FragmentHeader))) + + sizeof(struct FragmentHeader); else fsize = fc->mtu; if (NULL != fc->tracker) - delay = GNUNET_BANDWIDTH_tracker_get_delay (fc->tracker, - fsize); + delay = GNUNET_BANDWIDTH_tracker_get_delay(fc->tracker, + fsize); else delay = GNUNET_TIME_UNIT_ZERO; if (delay.rel_value_us > 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Fragmentation logic delays transmission of next fragment by %s\n", - GNUNET_STRINGS_relative_time_to_string (delay, + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Fragmentation logic delays transmission of next fragment by %s\n", + GNUNET_STRINGS_relative_time_to_string(delay, GNUNET_YES)); - fc->task = GNUNET_SCHEDULER_add_delayed (delay, - &transmit_next, - fc); - return; - } + fc->task = GNUNET_SCHEDULER_add_delayed(delay, + &transmit_next, + fc); + return; + } fc->next_transmission = (fc->next_transmission + 1) % 64; wrap |= (0 == fc->next_transmission); while (0 == (fc->acks & (1LLU << fc->next_transmission))) - { - fc->next_transmission = (fc->next_transmission + 1) % 64; - wrap |= (0 == fc->next_transmission); - } + { + fc->next_transmission = (fc->next_transmission + 1) % 64; + wrap |= (0 == fc->next_transmission); + } /* assemble fragmentation message */ - mbuf = (const char *) &fc[1]; - fh = (struct FragmentHeader *) msg; - fh->header.size = htons (fsize); - fh->header.type = htons (GNUNET_MESSAGE_TYPE_FRAGMENT); - fh->fragment_id = htonl (fc->fragment_id); + mbuf = (const char *)&fc[1]; + fh = (struct FragmentHeader *)msg; + fh->header.size = htons(fsize); + fh->header.type = htons(GNUNET_MESSAGE_TYPE_FRAGMENT); + fh->fragment_id = htonl(fc->fragment_id); fh->total_size = fc->msg->size; /* already in big-endian */ - fh->offset = htons ((fc->mtu - sizeof (struct FragmentHeader)) * bit); - GNUNET_memcpy (&fh[1], &mbuf[bit * (fc->mtu - sizeof (struct FragmentHeader))], - fsize - sizeof (struct FragmentHeader)); + fh->offset = htons((fc->mtu - sizeof(struct FragmentHeader)) * bit); + GNUNET_memcpy(&fh[1], &mbuf[bit * (fc->mtu - sizeof(struct FragmentHeader))], + fsize - sizeof(struct FragmentHeader)); if (NULL != fc->tracker) - GNUNET_BANDWIDTH_tracker_consume (fc->tracker, fsize); - GNUNET_STATISTICS_update (fc->stats, - _("# fragments transmitted"), - 1, - GNUNET_NO); + GNUNET_BANDWIDTH_tracker_consume(fc->tracker, fsize); + GNUNET_STATISTICS_update(fc->stats, + _("# fragments transmitted"), + 1, + GNUNET_NO); if (0 != fc->last_round.abs_value_us) - GNUNET_STATISTICS_update (fc->stats, - _("# fragments retransmitted"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(fc->stats, + _("# fragments retransmitted"), + 1, + GNUNET_NO); /* select next message to calculate delay */ bit = fc->next_transmission; - size = ntohs (fc->msg->size); - if (bit == size / (fc->mtu - sizeof (struct FragmentHeader))) - fsize = size % (fc->mtu - sizeof (struct FragmentHeader)); + size = ntohs(fc->msg->size); + if (bit == size / (fc->mtu - sizeof(struct FragmentHeader))) + fsize = size % (fc->mtu - sizeof(struct FragmentHeader)); else fsize = fc->mtu; if (NULL != fc->tracker) - delay = GNUNET_BANDWIDTH_tracker_get_delay (fc->tracker, - fsize); + delay = GNUNET_BANDWIDTH_tracker_get_delay(fc->tracker, + fsize); else delay = GNUNET_TIME_UNIT_ZERO; if (fc->num_rounds < 64) - delay = GNUNET_TIME_relative_max (delay, - GNUNET_TIME_relative_saturating_multiply - (fc->msg_delay, + delay = GNUNET_TIME_relative_max(delay, + GNUNET_TIME_relative_saturating_multiply + (fc->msg_delay, (1ULL << fc->num_rounds))); else delay = GNUNET_TIME_UNIT_FOREVER_REL; if (wrap) - { - /* full round transmitted wait 2x delay for ACK before going again */ - fc->num_rounds++; - delay = GNUNET_TIME_relative_saturating_multiply (fc->ack_delay, 2); - /* never use zero, need some time for ACK always */ - delay = GNUNET_TIME_relative_max (MIN_ACK_DELAY, delay); - fc->wack = GNUNET_YES; - fc->last_round = GNUNET_TIME_absolute_get (); - GNUNET_STATISTICS_update (fc->stats, - _("# fragments wrap arounds"), - 1, - GNUNET_NO); - } + { + /* full round transmitted wait 2x delay for ACK before going again */ + fc->num_rounds++; + delay = GNUNET_TIME_relative_saturating_multiply(fc->ack_delay, 2); + /* never use zero, need some time for ACK always */ + delay = GNUNET_TIME_relative_max(MIN_ACK_DELAY, delay); + fc->wack = GNUNET_YES; + fc->last_round = GNUNET_TIME_absolute_get(); + GNUNET_STATISTICS_update(fc->stats, + _("# fragments wrap arounds"), + 1, + GNUNET_NO); + } fc->proc_busy = GNUNET_YES; - fc->delay_until = GNUNET_TIME_relative_to_absolute (delay); + fc->delay_until = GNUNET_TIME_relative_to_absolute(delay); fc->num_transmissions++; - fc->proc (fc->proc_cls, - &fh->header); + fc->proc(fc->proc_cls, + &fh->header); } @@ -308,53 +306,53 @@ transmit_next (void *cls) * @return the fragmentation context */ struct GNUNET_FRAGMENT_Context * -GNUNET_FRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats, - uint16_t mtu, - struct GNUNET_BANDWIDTH_Tracker *tracker, - struct GNUNET_TIME_Relative msg_delay, - struct GNUNET_TIME_Relative ack_delay, - const struct GNUNET_MessageHeader *msg, - GNUNET_FRAGMENT_MessageProcessor proc, - void *proc_cls) +GNUNET_FRAGMENT_context_create(struct GNUNET_STATISTICS_Handle *stats, + uint16_t mtu, + struct GNUNET_BANDWIDTH_Tracker *tracker, + struct GNUNET_TIME_Relative msg_delay, + struct GNUNET_TIME_Relative ack_delay, + const struct GNUNET_MessageHeader *msg, + GNUNET_FRAGMENT_MessageProcessor proc, + void *proc_cls) { struct GNUNET_FRAGMENT_Context *fc; size_t size; uint64_t bits; - GNUNET_STATISTICS_update (stats, - _("# messages fragmented"), - 1, - GNUNET_NO); - GNUNET_assert (mtu >= 1024 + sizeof (struct FragmentHeader)); - size = ntohs (msg->size); - GNUNET_STATISTICS_update (stats, - _("# total size of fragmented messages"), - size, GNUNET_NO); - GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader)); - fc = GNUNET_malloc (sizeof (struct GNUNET_FRAGMENT_Context) + size); + GNUNET_STATISTICS_update(stats, + _("# messages fragmented"), + 1, + GNUNET_NO); + GNUNET_assert(mtu >= 1024 + sizeof(struct FragmentHeader)); + size = ntohs(msg->size); + GNUNET_STATISTICS_update(stats, + _("# total size of fragmented messages"), + size, GNUNET_NO); + GNUNET_assert(size >= sizeof(struct GNUNET_MessageHeader)); + fc = GNUNET_malloc(sizeof(struct GNUNET_FRAGMENT_Context) + size); fc->stats = stats; fc->mtu = mtu; fc->tracker = tracker; fc->ack_delay = ack_delay; fc->msg_delay = msg_delay; - fc->msg = (const struct GNUNET_MessageHeader *) &fc[1]; + fc->msg = (const struct GNUNET_MessageHeader *)&fc[1]; fc->proc = proc; fc->proc_cls = proc_cls; fc->fragment_id = - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT32_MAX); - GNUNET_memcpy (&fc[1], msg, size); + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + UINT32_MAX); + GNUNET_memcpy(&fc[1], msg, size); bits = - (size + mtu - sizeof (struct FragmentHeader) - 1) / (mtu - - sizeof (struct - FragmentHeader)); - GNUNET_assert (bits <= 64); + (size + mtu - sizeof(struct FragmentHeader) - 1) / (mtu - + sizeof(struct + FragmentHeader)); + GNUNET_assert(bits <= 64); if (bits == 64) fc->acks_mask = UINT64_MAX; /* set all 64 bit */ else fc->acks_mask = (1LLU << bits) - 1; /* set lowest 'bits' bit */ fc->acks = fc->acks_mask; - fc->task = GNUNET_SCHEDULER_add_now (&transmit_next, fc); + fc->task = GNUNET_SCHEDULER_add_now(&transmit_next, fc); return fc; } @@ -367,15 +365,15 @@ GNUNET_FRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats, * @param fc fragmentation context */ void -GNUNET_FRAGMENT_context_transmission_done (struct GNUNET_FRAGMENT_Context *fc) +GNUNET_FRAGMENT_context_transmission_done(struct GNUNET_FRAGMENT_Context *fc) { - GNUNET_assert (fc->proc_busy == GNUNET_YES); + GNUNET_assert(fc->proc_busy == GNUNET_YES); fc->proc_busy = GNUNET_NO; - GNUNET_assert (fc->task == NULL); + GNUNET_assert(fc->task == NULL); fc->task = - GNUNET_SCHEDULER_add_at (fc->delay_until, - &transmit_next, - fc); + GNUNET_SCHEDULER_add_at(fc->delay_until, + &transmit_next, + fc); } @@ -391,8 +389,8 @@ GNUNET_FRAGMENT_context_transmission_done (struct GNUNET_FRAGMENT_Context *fc) * #GNUNET_SYSERR if this ack is not valid for this fc */ int -GNUNET_FRAGMENT_process_ack (struct GNUNET_FRAGMENT_Context *fc, - const struct GNUNET_MessageHeader *msg) +GNUNET_FRAGMENT_process_ack(struct GNUNET_FRAGMENT_Context *fc, + const struct GNUNET_MessageHeader *msg) { const struct FragmentAcknowledgement *fa; uint64_t abits; @@ -401,97 +399,97 @@ GNUNET_FRAGMENT_process_ack (struct GNUNET_FRAGMENT_Context *fc, unsigned int snd_cnt; unsigned int i; - if (sizeof (struct FragmentAcknowledgement) != ntohs (msg->size)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - fa = (const struct FragmentAcknowledgement *) msg; - if (ntohl (fa->fragment_id) != fc->fragment_id) - return GNUNET_SYSERR; /* not our ACK */ - abits = GNUNET_ntohll (fa->bits); - if ( (GNUNET_YES == fc->wack) && - (0 != fc->num_transmissions) ) - { - /* normal ACK, can update running average of delay... */ - fc->wack = GNUNET_NO; - ndelay = GNUNET_TIME_absolute_get_duration (fc->last_round); - fc->ack_delay.rel_value_us = - (ndelay.rel_value_us / fc->num_transmissions + 3 * fc->ack_delay.rel_value_us) / 4; - /* calculate ratio msg sent vs. msg acked */ - ack_cnt = 0; - snd_cnt = 0; - for (i=0;i<64;i++) - { - if (1 == (fc->acks_mask & (1ULL << i))) - { - snd_cnt++; - if (0 == (abits & (1ULL << i))) - ack_cnt++; - } - } - if (0 == ack_cnt) + if (sizeof(struct FragmentAcknowledgement) != ntohs(msg->size)) { - /* complete loss */ - fc->msg_delay = GNUNET_TIME_relative_saturating_multiply (fc->msg_delay, - snd_cnt); + GNUNET_break_op(0); + return GNUNET_SYSERR; } - else if (snd_cnt > ack_cnt) + fa = (const struct FragmentAcknowledgement *)msg; + if (ntohl(fa->fragment_id) != fc->fragment_id) + return GNUNET_SYSERR; /* not our ACK */ + abits = GNUNET_ntohll(fa->bits); + if ((GNUNET_YES == fc->wack) && + (0 != fc->num_transmissions)) { - /* some loss, slow down proportionally */ - fc->msg_delay.rel_value_us = ((fc->msg_delay.rel_value_us * ack_cnt) / snd_cnt); + /* normal ACK, can update running average of delay... */ + fc->wack = GNUNET_NO; + ndelay = GNUNET_TIME_absolute_get_duration(fc->last_round); + fc->ack_delay.rel_value_us = + (ndelay.rel_value_us / fc->num_transmissions + 3 * fc->ack_delay.rel_value_us) / 4; + /* calculate ratio msg sent vs. msg acked */ + ack_cnt = 0; + snd_cnt = 0; + for (i = 0; i < 64; i++) + { + if (1 == (fc->acks_mask & (1ULL << i))) + { + snd_cnt++; + if (0 == (abits & (1ULL << i))) + ack_cnt++; + } + } + if (0 == ack_cnt) + { + /* complete loss */ + fc->msg_delay = GNUNET_TIME_relative_saturating_multiply(fc->msg_delay, + snd_cnt); + } + else if (snd_cnt > ack_cnt) + { + /* some loss, slow down proportionally */ + fc->msg_delay.rel_value_us = ((fc->msg_delay.rel_value_us * ack_cnt) / snd_cnt); + } + else if (snd_cnt == ack_cnt) + { + fc->msg_delay.rel_value_us = + (ndelay.rel_value_us / fc->num_transmissions + 3 * fc->msg_delay.rel_value_us) / 5; + } + fc->num_transmissions = 0; + fc->msg_delay = GNUNET_TIME_relative_min(fc->msg_delay, + GNUNET_TIME_UNIT_SECONDS); + fc->ack_delay = GNUNET_TIME_relative_min(fc->ack_delay, + GNUNET_TIME_UNIT_SECONDS); } - else if (snd_cnt == ack_cnt) + GNUNET_STATISTICS_update(fc->stats, + _("# fragment acknowledgements received"), + 1, + GNUNET_NO); + if (abits != (fc->acks & abits)) { - fc->msg_delay.rel_value_us = - (ndelay.rel_value_us / fc->num_transmissions + 3 * fc->msg_delay.rel_value_us) / 5; + /* ID collission or message reordering, count! This should be rare! */ + GNUNET_STATISTICS_update(fc->stats, + _("# bits removed from fragmentation ACKs"), 1, + GNUNET_NO); } - fc->num_transmissions = 0; - fc->msg_delay = GNUNET_TIME_relative_min (fc->msg_delay, - GNUNET_TIME_UNIT_SECONDS); - fc->ack_delay = GNUNET_TIME_relative_min (fc->ack_delay, - GNUNET_TIME_UNIT_SECONDS); - } - GNUNET_STATISTICS_update (fc->stats, - _("# fragment acknowledgements received"), - 1, - GNUNET_NO); - if (abits != (fc->acks & abits)) - { - /* ID collission or message reordering, count! This should be rare! */ - GNUNET_STATISTICS_update (fc->stats, - _("# bits removed from fragmentation ACKs"), 1, - GNUNET_NO); - } fc->acks = abits & fc->acks_mask; if (0 != fc->acks) - { - /* more to transmit, do so right now (if tracker permits...) */ - if (fc->task != NULL) - { - /* schedule next transmission now, no point in waiting... */ - GNUNET_SCHEDULER_cancel (fc->task); - fc->task = GNUNET_SCHEDULER_add_now (&transmit_next, fc); - } - else { - /* only case where there is no task should be if we're waiting - * for the right to transmit again (proc_busy set to YES) */ - GNUNET_assert (GNUNET_YES == fc->proc_busy); + /* more to transmit, do so right now (if tracker permits...) */ + if (fc->task != NULL) + { + /* schedule next transmission now, no point in waiting... */ + GNUNET_SCHEDULER_cancel(fc->task); + fc->task = GNUNET_SCHEDULER_add_now(&transmit_next, fc); + } + else + { + /* only case where there is no task should be if we're waiting + * for the right to transmit again (proc_busy set to YES) */ + GNUNET_assert(GNUNET_YES == fc->proc_busy); + } + return GNUNET_NO; } - return GNUNET_NO; - } /* all done */ - GNUNET_STATISTICS_update (fc->stats, - _("# fragmentation transmissions completed"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(fc->stats, + _("# fragmentation transmissions completed"), + 1, + GNUNET_NO); if (NULL != fc->task) - { - GNUNET_SCHEDULER_cancel (fc->task); - fc->task = NULL; - } + { + GNUNET_SCHEDULER_cancel(fc->task); + fc->task = NULL; + } return GNUNET_OK; } @@ -507,18 +505,18 @@ GNUNET_FRAGMENT_process_ack (struct GNUNET_FRAGMENT_Context *fc, * last message, set to FOREVER if the message was not fully transmitted (OUT only) */ void -GNUNET_FRAGMENT_context_destroy (struct GNUNET_FRAGMENT_Context *fc, - struct GNUNET_TIME_Relative *msg_delay, - struct GNUNET_TIME_Relative *ack_delay) +GNUNET_FRAGMENT_context_destroy(struct GNUNET_FRAGMENT_Context *fc, + struct GNUNET_TIME_Relative *msg_delay, + struct GNUNET_TIME_Relative *ack_delay) { if (fc->task != NULL) - GNUNET_SCHEDULER_cancel (fc->task); + GNUNET_SCHEDULER_cancel(fc->task); if (NULL != ack_delay) *ack_delay = fc->ack_delay; if (NULL != msg_delay) - *msg_delay = GNUNET_TIME_relative_saturating_multiply (fc->msg_delay, - fc->num_rounds); - GNUNET_free (fc); + *msg_delay = GNUNET_TIME_relative_saturating_multiply(fc->msg_delay, + fc->num_rounds); + GNUNET_free(fc); } diff --git a/src/fragmentation/fragmentation.h b/src/fragmentation/fragmentation.h index 9816e2116..3578cadca 100644 --- a/src/fragmentation/fragmentation.h +++ b/src/fragmentation/fragmentation.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/fragmentation/fragmentation.h * @brief library to help fragment messages @@ -33,9 +33,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * Header for a message fragment. Followed by the * original message. */ -struct FragmentHeader -{ - +struct FragmentHeader { /** * Message header. */ @@ -56,16 +54,13 @@ struct FragmentHeader * message. Will be a multiple of the MTU. */ uint16_t offset GNUNET_PACKED; - }; /** * Message fragment acknowledgement. */ -struct FragmentAcknowledgement -{ - +struct FragmentAcknowledgement { /** * Message header. */ @@ -82,7 +77,6 @@ struct FragmentAcknowledgement * have not yet been received). */ uint64_t bits GNUNET_PACKED; - }; GNUNET_NETWORK_STRUCT_END diff --git a/src/fragmentation/test_fragmentation.c b/src/fragmentation/test_fragmentation.c index a49f6d71a..51ae2bb60 100644 --- a/src/fragmentation/test_fragmentation.c +++ b/src/fragmentation/test_fragmentation.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fragmentation/test_fragmentation.c * @brief test for fragmentation.c @@ -68,52 +68,52 @@ static struct GNUNET_TIME_Relative ack_delay; static void -do_shutdown (void *cls) +do_shutdown(void *cls) { ret = 0; shutdown_task = NULL; - GNUNET_DEFRAGMENT_context_destroy (defrag); + GNUNET_DEFRAGMENT_context_destroy(defrag); defrag = NULL; if (NULL != frag) - { - GNUNET_FRAGMENT_context_destroy (frag, &msg_delay, &ack_delay); - frag = NULL; - } - fprintf (stderr, - "\nFinal message-delay: %s\n", - GNUNET_STRINGS_relative_time_to_string (msg_delay, - GNUNET_YES)); - fprintf (stderr, - "Final ack-delay: %s\n", - GNUNET_STRINGS_relative_time_to_string (ack_delay, - GNUNET_YES)); + { + GNUNET_FRAGMENT_context_destroy(frag, &msg_delay, &ack_delay); + frag = NULL; + } + fprintf(stderr, + "\nFinal message-delay: %s\n", + GNUNET_STRINGS_relative_time_to_string(msg_delay, + GNUNET_YES)); + fprintf(stderr, + "Final ack-delay: %s\n", + GNUNET_STRINGS_relative_time_to_string(ack_delay, + GNUNET_YES)); } static void -proc_msgs (void *cls, const struct GNUNET_MessageHeader *hdr) +proc_msgs(void *cls, const struct GNUNET_MessageHeader *hdr) { static unsigned int total; unsigned int i; const char *buf; #if DETAILS - fprintf (stderr, "%s", "M! "); /* message complete, good! */ + fprintf(stderr, "%s", "M! "); /* message complete, good! */ #endif - buf = (const char *) hdr; - for (i = sizeof (struct GNUNET_MessageHeader); i < ntohs (hdr->size); i++) - GNUNET_assert (buf[i] == (char) i); + buf = (const char *)hdr; + for (i = sizeof(struct GNUNET_MessageHeader); i < ntohs(hdr->size); i++) + GNUNET_assert(buf[i] == (char)i); total++; -#if ! DETAILS +#if !DETAILS if (0 == (total % (NUM_MSGS / 100))) - fprintf (stderr, "%s", "."); + fprintf(stderr, "%s", "."); #endif /* tolerate 10% loss, i.e. due to duplicate fragment IDs */ if ((total >= NUM_MSGS - (NUM_MSGS / 10)) && (ret != 0)) - { - if (NULL == shutdown_task) - shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL); - } + { + if (NULL == shutdown_task) + shutdown_task = GNUNET_SCHEDULER_add_now(&do_shutdown, NULL); + } } @@ -121,45 +121,45 @@ proc_msgs (void *cls, const struct GNUNET_MessageHeader *hdr) * Process fragment (by passing to defrag). */ static void -proc_frac (void *cls, const struct GNUNET_MessageHeader *hdr) +proc_frac(void *cls, const struct GNUNET_MessageHeader *hdr) { struct GNUNET_FRAGMENT_Context **fc = cls; int ret; - GNUNET_FRAGMENT_context_transmission_done (*fc); - if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, DROPRATE)) - { - frag_drops++; + GNUNET_FRAGMENT_context_transmission_done(*fc); + if (0 == GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, DROPRATE)) + { + frag_drops++; #if DETAILS - fprintf (stderr, "%s", "DF "); /* dropped Frag */ + fprintf(stderr, "%s", "DF "); /* dropped Frag */ #endif - return; /* random drop */ - } + return; /* random drop */ + } if (NULL == defrag) - { - fprintf (stderr, "%s", "?E "); /* Error: frag after shutdown!? */ - return; - } - ret = GNUNET_DEFRAGMENT_process_fragment (defrag, hdr); + { + fprintf(stderr, "%s", "?E "); /* Error: frag after shutdown!? */ + return; + } + ret = GNUNET_DEFRAGMENT_process_fragment(defrag, hdr); if (ret == GNUNET_NO) - { + { #if DETAILS - fprintf (stderr, "%s", "FF "); /* duplicate fragment */ + fprintf(stderr, "%s", "FF "); /* duplicate fragment */ #endif - dups++; - } + dups++; + } else if (ret == GNUNET_OK) - { + { #if DETAILS - fprintf (stderr, "%s", "F! "); /* good fragment */ + fprintf(stderr, "%s", "F! "); /* good fragment */ #endif - fragc++; - } + fragc++; + } } static void -next_transmission () +next_transmission() { static unsigned int i; struct GNUNET_MessageHeader *msg; @@ -167,32 +167,32 @@ next_transmission () unsigned int j; if (0 == i) - { - for (j = 0; j < sizeof (buf); j++) - buf[j] = (char) j; - } + { + for (j = 0; j < sizeof(buf); j++) + buf[j] = (char)j; + } else - { - GNUNET_FRAGMENT_context_destroy (frag, - &msg_delay, - &ack_delay); - frag = NULL; - } + { + GNUNET_FRAGMENT_context_destroy(frag, + &msg_delay, + &ack_delay); + frag = NULL; + } if (i == NUM_MSGS) return; #if DETAILS - fprintf (stderr, "%s", "T! "); /* sending message */ + fprintf(stderr, "%s", "T! "); /* sending message */ #endif - msg = (struct GNUNET_MessageHeader *) buf; - msg->type = htons ((uint16_t) i); + msg = (struct GNUNET_MessageHeader *)buf; + msg->type = htons((uint16_t)i); msg->size = - htons (sizeof (struct GNUNET_MessageHeader) + (17 * i) % (32 * 1024)); - frag = GNUNET_FRAGMENT_context_create (NULL /* no stats */ , - MTU, &trackers[i], - msg_delay, - ack_delay, - msg, - &proc_frac, &frag); + htons(sizeof(struct GNUNET_MessageHeader) + (17 * i) % (32 * 1024)); + frag = GNUNET_FRAGMENT_context_create(NULL /* no stats */, + MTU, &trackers[i], + msg_delay, + ack_delay, + msg, + &proc_frac, &frag); i++; } @@ -201,46 +201,46 @@ next_transmission () * Process ACK (by passing to fragmenter) */ static void -proc_acks (void *cls, - uint32_t msg_id, - const struct GNUNET_MessageHeader *hdr) +proc_acks(void *cls, + uint32_t msg_id, + const struct GNUNET_MessageHeader *hdr) { unsigned int i; int ret; - if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, DROPRATE)) - { - ack_drops++; + if (0 == GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, DROPRATE)) + { + ack_drops++; #if DETAILS - fprintf (stderr, "%s", "DA "); /* dropped ACK */ + fprintf(stderr, "%s", "DA "); /* dropped ACK */ #endif - return; /* random drop */ - } + return; /* random drop */ + } for (i = 0; i < NUM_MSGS; i++) - { - if (NULL == frag) - continue; - ret = GNUNET_FRAGMENT_process_ack (frag, hdr); - if (ret == GNUNET_OK) { + if (NULL == frag) + continue; + ret = GNUNET_FRAGMENT_process_ack(frag, hdr); + if (ret == GNUNET_OK) + { #if DETAILS - fprintf (stderr, "%s", "GA "); /* good ACK */ + fprintf(stderr, "%s", "GA "); /* good ACK */ #endif - next_transmission (); - acks++; - return; - } - if (ret == GNUNET_NO) - { + next_transmission(); + acks++; + return; + } + if (ret == GNUNET_NO) + { #if DETAILS - fprintf (stderr, "%s", "AA "); /* duplciate ACK */ + fprintf(stderr, "%s", "AA "); /* duplciate ACK */ #endif - acks++; - return; + acks++; + return; + } } - } #if DETAILS - fprintf (stderr, "%s", "?A "); /* BAD: ack that nobody feels responsible for... */ + fprintf(stderr, "%s", "?A "); /* BAD: ack that nobody feels responsible for... */ #endif } @@ -249,22 +249,22 @@ proc_acks (void *cls, * Main function run with scheduler. */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - defrag = GNUNET_DEFRAGMENT_context_create (NULL, MTU, - 3, - NULL, - &proc_msgs, - &proc_acks); - next_transmission (); + defrag = GNUNET_DEFRAGMENT_context_create(NULL, MTU, + 3, + NULL, + &proc_msgs, + &proc_acks); + next_transmission(); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END @@ -281,23 +281,23 @@ main (int argc, char *argv[]) msg_delay = GNUNET_TIME_UNIT_MILLISECONDS; ack_delay = GNUNET_TIME_UNIT_SECONDS; - GNUNET_log_setup ("test-fragmentation", - "WARNING", - NULL); + GNUNET_log_setup("test-fragmentation", + "WARNING", + NULL); for (i = 0; i < NUM_MSGS; i++) - GNUNET_BANDWIDTH_tracker_init (&trackers[i], NULL, NULL, - GNUNET_BANDWIDTH_value_init ((i + 1) * 1024), - 100); - GNUNET_PROGRAM_run (5, - argv_prog, - "test-fragmentation", "nohelp", - options, - &run, NULL); - fprintf (stderr, - "\nHad %u good fragments, %u duplicate fragments, %u acks and %u simulated drops of acks\n", - fragc, - dups, - acks, - ack_drops); + GNUNET_BANDWIDTH_tracker_init(&trackers[i], NULL, NULL, + GNUNET_BANDWIDTH_value_init((i + 1) * 1024), + 100); + GNUNET_PROGRAM_run(5, + argv_prog, + "test-fragmentation", "nohelp", + options, + &run, NULL); + fprintf(stderr, + "\nHad %u good fragments, %u duplicate fragments, %u acks and %u simulated drops of acks\n", + fragc, + dups, + acks, + ack_drops); return ret; } diff --git a/src/fragmentation/test_fragmentation_parallel.c b/src/fragmentation/test_fragmentation_parallel.c index d8e598484..6db9c55a9 100644 --- a/src/fragmentation/test_fragmentation_parallel.c +++ b/src/fragmentation/test_fragmentation_parallel.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fragmentation/test_fragmentation.c * @brief test for fragmentation.c @@ -64,48 +64,48 @@ static struct GNUNET_SCHEDULER_Task *shutdown_task; static void -do_shutdown (void *cls) +do_shutdown(void *cls) { unsigned int i; ret = 0; shutdown_task = NULL; - GNUNET_DEFRAGMENT_context_destroy (defrag); + GNUNET_DEFRAGMENT_context_destroy(defrag); defrag = NULL; for (i = 0; i < NUM_MSGS; i++) - { - if (frags[i] == NULL) - continue; - GNUNET_FRAGMENT_context_destroy (frags[i], NULL, NULL); - frags[i] = NULL; - } + { + if (frags[i] == NULL) + continue; + GNUNET_FRAGMENT_context_destroy(frags[i], NULL, NULL); + frags[i] = NULL; + } } static void -proc_msgs (void *cls, const struct GNUNET_MessageHeader *hdr) +proc_msgs(void *cls, const struct GNUNET_MessageHeader *hdr) { static unsigned int total; unsigned int i; const char *buf; #if DETAILS - fprintf (stderr, "%s", "!"); /* message complete, good! */ + fprintf(stderr, "%s", "!"); /* message complete, good! */ #endif - buf = (const char *) hdr; - for (i = sizeof (struct GNUNET_MessageHeader); i < ntohs (hdr->size); i++) - GNUNET_assert (buf[i] == (char) i); + buf = (const char *)hdr; + for (i = sizeof(struct GNUNET_MessageHeader); i < ntohs(hdr->size); i++) + GNUNET_assert(buf[i] == (char)i); total++; -#if ! DETAILS +#if !DETAILS if (0 == (total % (NUM_MSGS / 100))) - fprintf (stderr, "%s", "."); + fprintf(stderr, "%s", "."); #endif /* tolerate 10% loss, i.e. due to duplicate fragment IDs */ if ((total >= NUM_MSGS - (NUM_MSGS / 10)) && (ret != 0)) - { - if (NULL == shutdown_task) - shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL); - } + { + if (NULL == shutdown_task) + shutdown_task = GNUNET_SCHEDULER_add_now(&do_shutdown, NULL); + } } @@ -113,42 +113,42 @@ proc_msgs (void *cls, const struct GNUNET_MessageHeader *hdr) * Process ACK (by passing to fragmenter) */ static void -proc_acks (void *cls, uint32_t msg_id, const struct GNUNET_MessageHeader *hdr) +proc_acks(void *cls, uint32_t msg_id, const struct GNUNET_MessageHeader *hdr) { unsigned int i; int ret; - if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, DROPRATE)) - { - ack_drops++; - return; /* random drop */ - } + if (0 == GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, DROPRATE)) + { + ack_drops++; + return; /* random drop */ + } for (i = 0; i < NUM_MSGS; i++) - { - if (frags[i] == NULL) - continue; - ret = GNUNET_FRAGMENT_process_ack (frags[i], hdr); - if (ret == GNUNET_OK) { + if (frags[i] == NULL) + continue; + ret = GNUNET_FRAGMENT_process_ack(frags[i], hdr); + if (ret == GNUNET_OK) + { #if DETAILS - fprintf (stderr, "%s", "@"); /* good ACK */ + fprintf(stderr, "%s", "@"); /* good ACK */ #endif - GNUNET_FRAGMENT_context_destroy (frags[i], NULL, NULL); - frags[i] = NULL; - acks++; - return; - } - if (ret == GNUNET_NO) - { + GNUNET_FRAGMENT_context_destroy(frags[i], NULL, NULL); + frags[i] = NULL; + acks++; + return; + } + if (ret == GNUNET_NO) + { #if DETAILS - fprintf (stderr, "%s", "@"); /* good ACK */ + fprintf(stderr, "%s", "@"); /* good ACK */ #endif - acks++; - return; + acks++; + return; + } } - } #if DETAILS - fprintf (stderr, "%s", "_"); /* BAD: ack that nobody feels responsible for... */ + fprintf(stderr, "%s", "_"); /* BAD: ack that nobody feels responsible for... */ #endif } @@ -157,37 +157,37 @@ proc_acks (void *cls, uint32_t msg_id, const struct GNUNET_MessageHeader *hdr) * Process fragment (by passing to defrag). */ static void -proc_frac (void *cls, const struct GNUNET_MessageHeader *hdr) +proc_frac(void *cls, const struct GNUNET_MessageHeader *hdr) { struct GNUNET_FRAGMENT_Context **fc = cls; int ret; - GNUNET_FRAGMENT_context_transmission_done (*fc); - if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, DROPRATE)) - { - frag_drops++; - return; /* random drop */ - } + GNUNET_FRAGMENT_context_transmission_done(*fc); + if (0 == GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, DROPRATE)) + { + frag_drops++; + return; /* random drop */ + } if (NULL == defrag) - { - fprintf (stderr, "%s", "E"); /* Error: frag after shutdown!? */ - return; - } - ret = GNUNET_DEFRAGMENT_process_fragment (defrag, hdr); + { + fprintf(stderr, "%s", "E"); /* Error: frag after shutdown!? */ + return; + } + ret = GNUNET_DEFRAGMENT_process_fragment(defrag, hdr); if (ret == GNUNET_NO) - { + { #if DETAILS - fprintf (stderr, "%s", "?"); /* duplicate fragment */ + fprintf(stderr, "%s", "?"); /* duplicate fragment */ #endif - dups++; - } + dups++; + } else if (ret == GNUNET_OK) - { + { #if DETAILS - fprintf (stderr, "%s", "."); /* good fragment */ + fprintf(stderr, "%s", "."); /* good fragment */ #endif - fragc++; - } + fragc++; + } } @@ -195,35 +195,35 @@ proc_frac (void *cls, const struct GNUNET_MessageHeader *hdr) * Main function run with scheduler. */ static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { unsigned int i; struct GNUNET_MessageHeader *msg; char buf[MTU + 32 * 1024]; - defrag = GNUNET_DEFRAGMENT_context_create (NULL, MTU, NUM_MSGS /* enough space for all */ - , NULL, &proc_msgs, &proc_acks); - for (i = 0; i < sizeof (buf); i++) - buf[i] = (char) i; - msg = (struct GNUNET_MessageHeader *) buf; + defrag = GNUNET_DEFRAGMENT_context_create(NULL, MTU, NUM_MSGS /* enough space for all */ + , NULL, &proc_msgs, &proc_acks); + for (i = 0; i < sizeof(buf); i++) + buf[i] = (char)i; + msg = (struct GNUNET_MessageHeader *)buf; for (i = 0; i < NUM_MSGS; i++) - { - msg->type = htons ((uint16_t) i); - msg->size = - htons (sizeof (struct GNUNET_MessageHeader) + (17 * i) % (32 * 1024)); - frags[i] = GNUNET_FRAGMENT_context_create (NULL /* no stats */ , - MTU, &trackers[i], - GNUNET_TIME_UNIT_MILLISECONDS, - GNUNET_TIME_UNIT_SECONDS, - msg, - &proc_frac, &frags[i]); - } + { + msg->type = htons((uint16_t)i); + msg->size = + htons(sizeof(struct GNUNET_MessageHeader) + (17 * i) % (32 * 1024)); + frags[i] = GNUNET_FRAGMENT_context_create(NULL /* no stats */, + MTU, &trackers[i], + GNUNET_TIME_UNIT_MILLISECONDS, + GNUNET_TIME_UNIT_SECONDS, + msg, + &proc_frac, &frags[i]); + } } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END @@ -238,17 +238,17 @@ main (int argc, char *argv[]) }; unsigned int i; - GNUNET_log_setup ("test-fragmentation", - "WARNING", - NULL); + GNUNET_log_setup("test-fragmentation", + "WARNING", + NULL); for (i = 0; i < NUM_MSGS; i++) - GNUNET_BANDWIDTH_tracker_init (&trackers[i], NULL, NULL, - GNUNET_BANDWIDTH_value_init ((i + 1) * 1024), - 100); - GNUNET_PROGRAM_run (5, argv_prog, "test-fragmentation", "nohelp", options, - &run, NULL); - fprintf (stderr, - "\nHad %u good fragments, %u duplicate fragments, %u acks and %u simulated drops of acks\n", - fragc, dups, acks, ack_drops); + GNUNET_BANDWIDTH_tracker_init(&trackers[i], NULL, NULL, + GNUNET_BANDWIDTH_value_init((i + 1) * 1024), + 100); + GNUNET_PROGRAM_run(5, argv_prog, "test-fragmentation", "nohelp", options, + &run, NULL); + fprintf(stderr, + "\nHad %u good fragments, %u duplicate fragments, %u acks and %u simulated drops of acks\n", + fragc, dups, acks, ack_drops); return ret; } diff --git a/src/fs/fs.h b/src/fs/fs.h index 25bc95e62..294a433fc 100644 --- a/src/fs/fs.h +++ b/src/fs/fs.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs.h @@ -50,8 +50,7 @@ /** * @brief content hash key */ -struct ContentHashKey -{ +struct ContentHashKey { /** * Hash of the original content, used for encryption. */ @@ -71,9 +70,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * Message sent from a GNUnet (fs) publishing activity to sign * a LOC URI. */ -struct RequestLocSignatureMessage -{ - +struct RequestLocSignatureMessage { /** * Message type will be #GNUNET_MESSAGE_TYPE_FS_REQUEST_LOC_SIGN. */ @@ -105,9 +102,7 @@ struct RequestLocSignatureMessage /** * Message sent from the service with the signed LOC URI. */ -struct ResponseLocSignatureMessage -{ - +struct ResponseLocSignatureMessage { /** * Message type will be * #GNUNET_MESSAGE_TYPE_FS_REQUEST_LOC_SIGNATURE. @@ -150,9 +145,7 @@ struct ResponseLocSignatureMessage * computing it; this is an optimization that should be safe given * that the client is not our adversary). */ -struct IndexStartMessage -{ - +struct IndexStartMessage { /** * Message type will be #GNUNET_MESSAGE_TYPE_FS_INDEX_START. */ @@ -188,7 +181,6 @@ struct IndexStartMessage /* this is followed by a 0-terminated * filename of a file with the hash * "file_id" as seen by the client */ - }; @@ -196,8 +188,7 @@ struct IndexStartMessage * Message send by FS service in response to a request * asking for a list of all indexed files. */ -struct IndexInfoMessage -{ +struct IndexInfoMessage { /** * Message type will be * #GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY. @@ -217,7 +208,6 @@ struct IndexInfoMessage /* this is followed by a 0-terminated * filename of a file with the hash * "file_id" as seen by the client */ - }; @@ -228,9 +218,7 @@ struct IndexInfoMessage * files and response with a confirmation message (even if the file * was already not on the list). */ -struct UnindexMessage -{ - +struct UnindexMessage { /** * Message type will be #GNUNET_MESSAGE_TYPE_FS_UNINDEX. */ @@ -245,7 +233,6 @@ struct UnindexMessage * Hash of the file that we will unindex. */ struct GNUNET_HashCode file_id; - }; @@ -272,9 +259,7 @@ struct UnindexMessage * Message sent from a GNUnet (fs) search activity to the * gnunet-service-fs to start a search. */ -struct SearchMessage -{ - +struct SearchMessage { /** * Message type will be #GNUNET_MESSAGE_TYPE_FS_START_SEARCH. */ @@ -333,9 +318,7 @@ struct SearchMessage * single response are considered done. This message is transmitted * between peers. */ -struct PutMessage -{ - +struct PutMessage { /** * Message type will be #GNUNET_MESSAGE_TYPE_FS_PUT. */ @@ -352,7 +335,6 @@ struct PutMessage struct GNUNET_TIME_AbsoluteNBO expiration; /* this is followed by the actual encrypted content */ - }; /** @@ -361,9 +343,7 @@ struct PutMessage * single response are considered done. This message is transmitted * between the service and a client. */ -struct ClientPutMessage -{ - +struct ClientPutMessage { /** * Message type will be #GNUNET_MESSAGE_TYPE_FS_PUT. */ @@ -398,7 +378,6 @@ struct ClientPutMessage uint32_t respect_offered; /* this is followed by the actual encrypted content */ - }; GNUNET_NETWORK_STRUCT_END diff --git a/src/fs/fs_api.c b/src/fs/fs_api.c index f7b64a5c9..45051ddcb 100644 --- a/src/fs/fs_api.c +++ b/src/fs/fs_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_api.c @@ -47,23 +47,23 @@ * @param qe job to start */ static void -start_job (struct GNUNET_FS_QueueEntry *qe) +start_job(struct GNUNET_FS_QueueEntry *qe) { qe->active = GNUNET_YES; - qe->start (qe->cls); + qe->start(qe->cls); qe->start_times++; qe->h->active_blocks += qe->blocks; qe->h->active_downloads++; - qe->start_time = GNUNET_TIME_absolute_get (); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting job %p (%u active)\n", - qe, - qe->h->active_downloads); - GNUNET_CONTAINER_DLL_remove (qe->h->pending_head, qe->h->pending_tail, qe); - GNUNET_CONTAINER_DLL_insert_after (qe->h->running_head, - qe->h->running_tail, - qe->h->running_tail, - qe); + qe->start_time = GNUNET_TIME_absolute_get(); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting job %p (%u active)\n", + qe, + qe->h->active_downloads); + GNUNET_CONTAINER_DLL_remove(qe->h->pending_head, qe->h->pending_tail, qe); + GNUNET_CONTAINER_DLL_insert_after(qe->h->running_head, + qe->h->running_tail, + qe->h->running_tail, + qe); } @@ -74,25 +74,25 @@ start_job (struct GNUNET_FS_QueueEntry *qe) * @param qe job to stop */ static void -stop_job (struct GNUNET_FS_QueueEntry *qe) +stop_job(struct GNUNET_FS_QueueEntry *qe) { qe->active = GNUNET_NO; - qe->stop (qe->cls); - GNUNET_assert (0 < qe->h->active_downloads); + qe->stop(qe->cls); + GNUNET_assert(0 < qe->h->active_downloads); qe->h->active_downloads--; qe->h->active_blocks -= qe->blocks; - qe->run_time = GNUNET_TIME_relative_add (qe->run_time, - GNUNET_TIME_absolute_get_duration ( - qe->start_time)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Stopping job %p (%u active)\n", - qe, - qe->h->active_downloads); - GNUNET_CONTAINER_DLL_remove (qe->h->running_head, qe->h->running_tail, qe); - GNUNET_CONTAINER_DLL_insert_after (qe->h->pending_head, - qe->h->pending_tail, - qe->h->pending_tail, - qe); + qe->run_time = GNUNET_TIME_relative_add(qe->run_time, + GNUNET_TIME_absolute_get_duration( + qe->start_time)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Stopping job %p (%u active)\n", + qe, + qe->h->active_downloads); + GNUNET_CONTAINER_DLL_remove(qe->h->running_head, qe->h->running_tail, qe); + GNUNET_CONTAINER_DLL_insert_after(qe->h->pending_head, + qe->h->pending_tail, + qe->h->pending_tail, + qe); } @@ -103,7 +103,7 @@ stop_job (struct GNUNET_FS_QueueEntry *qe) * @param cls the `struct GNUNET_FS_Handle *` */ static void -process_job_queue (void *cls) +process_job_queue(void *cls) { struct GNUNET_FS_Handle *h = cls; struct GNUNET_FS_QueueEntry *qe; @@ -131,20 +131,22 @@ process_job_queue (void *cls) num_probes_waiting = 0; num_downloads_waiting = 0; for (qe = h->pending_head; NULL != qe; qe = qe->next) - { - switch (qe->priority) { - case GNUNET_FS_QUEUE_PRIORITY_PROBE: - num_probes_waiting++; - break; - case GNUNET_FS_QUEUE_PRIORITY_NORMAL: - num_downloads_waiting++; - break; - default: - GNUNET_break (0); - break; + switch (qe->priority) + { + case GNUNET_FS_QUEUE_PRIORITY_PROBE: + num_probes_waiting++; + break; + + case GNUNET_FS_QUEUE_PRIORITY_NORMAL: + num_downloads_waiting++; + break; + + default: + GNUNET_break(0); + break; + } } - } /* now, calculate some basic statistics on running jobs */ num_probes_active = 0; num_probes_expired = 0; @@ -152,161 +154,165 @@ process_job_queue (void *cls) num_downloads_expired = 0; next = h->running_head; while (NULL != (qe = next)) - { - next = qe->next; - switch (qe->priority) - { - case GNUNET_FS_QUEUE_PRIORITY_PROBE: - run_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2); - end_time = GNUNET_TIME_absolute_add (qe->start_time, run_time); - rst = GNUNET_TIME_absolute_get_remaining (end_time); - if (0 == rst.rel_value_us) - { - num_probes_expired++; - stop_job (qe); - } - else - { - num_probes_active++; - restart_at = GNUNET_TIME_relative_min (rst, restart_at); - } - break; - case GNUNET_FS_QUEUE_PRIORITY_NORMAL: - run_time = - GNUNET_TIME_relative_saturating_multiply (h->avg_block_latency, - qe->blocks * qe->start_times); - end_time = GNUNET_TIME_absolute_add (qe->start_time, run_time); - rst = GNUNET_TIME_absolute_get_remaining (end_time); - if (0 == rst.rel_value_us) - { - num_downloads_expired++; - stop_job (qe); - } - else - { - num_downloads_active++; - restart_at = GNUNET_TIME_relative_min (rst, restart_at); - } - break; - default: - GNUNET_break (0); - break; + { + next = qe->next; + switch (qe->priority) + { + case GNUNET_FS_QUEUE_PRIORITY_PROBE: + run_time = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2); + end_time = GNUNET_TIME_absolute_add(qe->start_time, run_time); + rst = GNUNET_TIME_absolute_get_remaining(end_time); + if (0 == rst.rel_value_us) + { + num_probes_expired++; + stop_job(qe); + } + else + { + num_probes_active++; + restart_at = GNUNET_TIME_relative_min(rst, restart_at); + } + break; + + case GNUNET_FS_QUEUE_PRIORITY_NORMAL: + run_time = + GNUNET_TIME_relative_saturating_multiply(h->avg_block_latency, + qe->blocks * qe->start_times); + end_time = GNUNET_TIME_absolute_add(qe->start_time, run_time); + rst = GNUNET_TIME_absolute_get_remaining(end_time); + if (0 == rst.rel_value_us) + { + num_downloads_expired++; + stop_job(qe); + } + else + { + num_downloads_active++; + restart_at = GNUNET_TIME_relative_min(rst, restart_at); + } + break; + + default: + GNUNET_break(0); + break; + } } - } - GNUNET_break (h->active_downloads == - num_downloads_active + num_probes_active); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "PA: %u, PE: %u, PW: %u; DA: %u, DE: %u, DW: %u\n", - num_probes_active, - num_probes_expired, - num_probes_waiting, - num_downloads_active, - num_downloads_expired, - num_downloads_waiting); - GNUNET_break (h->active_downloads + num_probes_active <= - h->max_parallel_downloads); + GNUNET_break(h->active_downloads == + num_downloads_active + num_probes_active); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "PA: %u, PE: %u, PW: %u; DA: %u, DE: %u, DW: %u\n", + num_probes_active, + num_probes_expired, + num_probes_waiting, + num_downloads_active, + num_downloads_expired, + num_downloads_waiting); + GNUNET_break(h->active_downloads + num_probes_active <= + h->max_parallel_downloads); /* calculate start/stop decisions */ if (h->active_downloads + num_downloads_waiting > h->max_parallel_downloads) - { - /* stop as many probes as there are downloads and probes */ - num_probes_change = -GNUNET_MIN (num_probes_active, num_downloads_waiting); - /* start as many downloads as there are free slots, including those - we just opened up */ - num_downloads_change = - h->max_parallel_downloads - h->active_downloads - num_probes_change; - } + { + /* stop as many probes as there are downloads and probes */ + num_probes_change = -GNUNET_MIN(num_probes_active, num_downloads_waiting); + /* start as many downloads as there are free slots, including those + we just opened up */ + num_downloads_change = + h->max_parallel_downloads - h->active_downloads - num_probes_change; + } else - { - /* start all downloads (we can) */ - num_downloads_change = num_downloads_waiting; - /* also start probes if there is room, but use a lower cap of (mpd/4) + 1 */ - if (1 + h->max_parallel_downloads / 4 >= - (h->active_downloads + num_downloads_change)) - num_probes_change = - GNUNET_MIN (num_probes_waiting, - (1 + h->max_parallel_downloads / 4) - - (h->active_downloads + num_downloads_change)); - else - num_probes_change = 0; - } - GNUNET_break (num_downloads_change <= num_downloads_waiting); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Changing %d probes and %d/%u/%u downloads\n", - num_probes_change, - num_downloads_change, - (unsigned int) h->active_downloads, - (unsigned int) h->max_parallel_downloads); + { + /* start all downloads (we can) */ + num_downloads_change = num_downloads_waiting; + /* also start probes if there is room, but use a lower cap of (mpd/4) + 1 */ + if (1 + h->max_parallel_downloads / 4 >= + (h->active_downloads + num_downloads_change)) + num_probes_change = + GNUNET_MIN(num_probes_waiting, + (1 + h->max_parallel_downloads / 4) - + (h->active_downloads + num_downloads_change)); + else + num_probes_change = 0; + } + GNUNET_break(num_downloads_change <= num_downloads_waiting); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Changing %d probes and %d/%u/%u downloads\n", + num_probes_change, + num_downloads_change, + (unsigned int)h->active_downloads, + (unsigned int)h->max_parallel_downloads); /* actually stop probes */ next = h->running_head; while (NULL != (qe = next)) - { - next = qe->next; - if (GNUNET_FS_QUEUE_PRIORITY_PROBE != qe->priority) - continue; - if (num_probes_change < 0) { - stop_job (qe); - num_probes_change++; - if (0 == num_probes_change) - break; + next = qe->next; + if (GNUNET_FS_QUEUE_PRIORITY_PROBE != qe->priority) + continue; + if (num_probes_change < 0) + { + stop_job(qe); + num_probes_change++; + if (0 == num_probes_change) + break; + } } - } - GNUNET_break (0 <= num_probes_change); + GNUNET_break(0 <= num_probes_change); /* start some more tasks if we now have empty slots */ block_limit_hit = GNUNET_NO; next = h->pending_head; while ((NULL != (qe = next)) && ((num_probes_change > 0) || (num_downloads_change > 0))) - { - next = qe->next; - switch (qe->priority) - { - case GNUNET_FS_QUEUE_PRIORITY_PROBE: - if (num_probes_change > 0) - { - start_job (qe); - num_probes_change--; - run_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2); - restart_at = GNUNET_TIME_relative_min (run_time, restart_at); - } - break; - case GNUNET_FS_QUEUE_PRIORITY_NORMAL: - if ((num_downloads_change > 0) && - ((qe->blocks + h->active_blocks <= h->max_parallel_requests) || - ((qe->blocks > h->max_parallel_requests) && - (0 == h->active_downloads)))) - { - start_job (qe); - num_downloads_change--; - } - else if (num_downloads_change > 0) - block_limit_hit = GNUNET_YES; - break; - default: - GNUNET_break (0); - break; + { + next = qe->next; + switch (qe->priority) + { + case GNUNET_FS_QUEUE_PRIORITY_PROBE: + if (num_probes_change > 0) + { + start_job(qe); + num_probes_change--; + run_time = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2); + restart_at = GNUNET_TIME_relative_min(run_time, restart_at); + } + break; + + case GNUNET_FS_QUEUE_PRIORITY_NORMAL: + if ((num_downloads_change > 0) && + ((qe->blocks + h->active_blocks <= h->max_parallel_requests) || + ((qe->blocks > h->max_parallel_requests) && + (0 == h->active_downloads)))) + { + start_job(qe); + num_downloads_change--; + } + else if (num_downloads_change > 0) + block_limit_hit = GNUNET_YES; + break; + + default: + GNUNET_break(0); + break; + } } - } - GNUNET_break ((0 == num_downloads_change) || (GNUNET_YES == block_limit_hit)); - GNUNET_break (0 == num_probes_change); + GNUNET_break((0 == num_downloads_change) || (GNUNET_YES == block_limit_hit)); + GNUNET_break(0 == num_probes_change); - GNUNET_log ( + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "AD: %u, MP: %u; %d probes and %d downloads to start, will run again in %s\n", h->active_downloads, h->max_parallel_requests, num_probes_change, num_downloads_change, - GNUNET_STRINGS_relative_time_to_string (restart_at, GNUNET_YES)); + GNUNET_STRINGS_relative_time_to_string(restart_at, GNUNET_YES)); /* make sure we run again, callbacks might have already re-scheduled the job, so cancel such an operation (if it exists) */ if (NULL != h->queue_job) - GNUNET_SCHEDULER_cancel (h->queue_job); + GNUNET_SCHEDULER_cancel(h->queue_job); h->queue_job = - GNUNET_SCHEDULER_add_delayed (restart_at, &process_job_queue, h); + GNUNET_SCHEDULER_add_delayed(restart_at, &process_job_queue, h); } @@ -322,31 +328,31 @@ process_job_queue (void *cls) * @return queue handle */ struct GNUNET_FS_QueueEntry * -GNUNET_FS_queue_ (struct GNUNET_FS_Handle *h, - GNUNET_SCHEDULER_TaskCallback start, - GNUNET_SCHEDULER_TaskCallback stop, - void *cls, - unsigned int blocks, - enum GNUNET_FS_QueuePriority priority) +GNUNET_FS_queue_(struct GNUNET_FS_Handle *h, + GNUNET_SCHEDULER_TaskCallback start, + GNUNET_SCHEDULER_TaskCallback stop, + void *cls, + unsigned int blocks, + enum GNUNET_FS_QueuePriority priority) { struct GNUNET_FS_QueueEntry *qe; - qe = GNUNET_new (struct GNUNET_FS_QueueEntry); + qe = GNUNET_new(struct GNUNET_FS_QueueEntry); qe->h = h; qe->start = start; qe->stop = stop; qe->cls = cls; - qe->queue_time = GNUNET_TIME_absolute_get (); + qe->queue_time = GNUNET_TIME_absolute_get(); qe->blocks = blocks; qe->priority = priority; - GNUNET_CONTAINER_DLL_insert_after (h->pending_head, - h->pending_tail, - h->pending_tail, - qe); + GNUNET_CONTAINER_DLL_insert_after(h->pending_head, + h->pending_tail, + h->pending_tail, + qe); if (NULL != h->queue_job) - GNUNET_SCHEDULER_cancel (h->queue_job); - h->queue_job = GNUNET_SCHEDULER_add_now (&process_job_queue, h); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Queueing job %p\n", qe); + GNUNET_SCHEDULER_cancel(h->queue_job); + h->queue_job = GNUNET_SCHEDULER_add_now(&process_job_queue, h); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Queueing job %p\n", qe); return qe; } @@ -357,19 +363,19 @@ GNUNET_FS_queue_ (struct GNUNET_FS_Handle *h, * @param qe handle for the job */ void -GNUNET_FS_dequeue_ (struct GNUNET_FS_QueueEntry *qe) +GNUNET_FS_dequeue_(struct GNUNET_FS_QueueEntry *qe) { struct GNUNET_FS_Handle *h; h = qe->h; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Dequeueing job %p\n", qe); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Dequeueing job %p\n", qe); if (GNUNET_YES == qe->active) - stop_job (qe); - GNUNET_CONTAINER_DLL_remove (h->pending_head, h->pending_tail, qe); - GNUNET_free (qe); + stop_job(qe); + GNUNET_CONTAINER_DLL_remove(h->pending_head, h->pending_tail, qe); + GNUNET_free(qe); if (NULL != h->queue_job) - GNUNET_SCHEDULER_cancel (h->queue_job); - h->queue_job = GNUNET_SCHEDULER_add_now (&process_job_queue, h); + GNUNET_SCHEDULER_cancel(h->queue_job); + h->queue_job = GNUNET_SCHEDULER_add_now(&process_job_queue, h); } @@ -382,16 +388,16 @@ GNUNET_FS_dequeue_ (struct GNUNET_FS_QueueEntry *qe) * @return fresh top-level activity handle */ struct TopLevelActivity * -GNUNET_FS_make_top (struct GNUNET_FS_Handle *h, - SuspendSignalFunction ssf, - void *ssf_cls) +GNUNET_FS_make_top(struct GNUNET_FS_Handle *h, + SuspendSignalFunction ssf, + void *ssf_cls) { struct TopLevelActivity *ret; - ret = GNUNET_new (struct TopLevelActivity); + ret = GNUNET_new(struct TopLevelActivity); ret->ssf = ssf; ret->ssf_cls = ssf_cls; - GNUNET_CONTAINER_DLL_insert (h->top_head, h->top_tail, ret); + GNUNET_CONTAINER_DLL_insert(h->top_head, h->top_tail, ret); return ret; } @@ -403,18 +409,17 @@ GNUNET_FS_make_top (struct GNUNET_FS_Handle *h, * @param top top level activity entry */ void -GNUNET_FS_end_top (struct GNUNET_FS_Handle *h, struct TopLevelActivity *top) +GNUNET_FS_end_top(struct GNUNET_FS_Handle *h, struct TopLevelActivity *top) { - GNUNET_CONTAINER_DLL_remove (h->top_head, h->top_tail, top); - GNUNET_free (top); + GNUNET_CONTAINER_DLL_remove(h->top_head, h->top_tail, top); + GNUNET_free(top); } /** * Closure for #GNUNET_FS_data_reader_file_(). */ -struct FileInfo -{ +struct FileInfo { /** * Name of the file to read. */ @@ -448,63 +453,63 @@ struct FileInfo * @return number of bytes written, usually @a max, 0 on error */ size_t -GNUNET_FS_data_reader_file_ (void *cls, - uint64_t offset, - size_t max, - void *buf, - char **emsg) +GNUNET_FS_data_reader_file_(void *cls, + uint64_t offset, + size_t max, + void *buf, + char **emsg) { struct FileInfo *fi = cls; ssize_t ret; if (UINT64_MAX == offset) - { - if (NULL != fi->fd) { - GNUNET_DISK_file_close (fi->fd); - fi->fd = NULL; + if (NULL != fi->fd) + { + GNUNET_DISK_file_close(fi->fd); + fi->fd = NULL; + } + return 0; } - return 0; - } if (0 == max) - { - if (NULL != fi->fd) - GNUNET_DISK_file_close (fi->fd); - GNUNET_free (fi->filename); - GNUNET_free (fi); - return 0; - } - if (NULL == fi->fd) - { - fi->fd = GNUNET_DISK_file_open (fi->filename, - GNUNET_DISK_OPEN_READ, - GNUNET_DISK_PERM_NONE); - if (NULL == fi->fd) - { - GNUNET_asprintf (emsg, - _ ("Could not open file `%s': %s"), - fi->filename, - strerror (errno)); + { + if (NULL != fi->fd) + GNUNET_DISK_file_close(fi->fd); + GNUNET_free(fi->filename); + GNUNET_free(fi); return 0; } - } + if (NULL == fi->fd) + { + fi->fd = GNUNET_DISK_file_open(fi->filename, + GNUNET_DISK_OPEN_READ, + GNUNET_DISK_PERM_NONE); + if (NULL == fi->fd) + { + GNUNET_asprintf(emsg, + _("Could not open file `%s': %s"), + fi->filename, + strerror(errno)); + return 0; + } + } if ((GNUNET_SYSERR == - GNUNET_DISK_file_seek (fi->fd, offset, GNUNET_DISK_SEEK_SET)) || - (-1 == (ret = GNUNET_DISK_file_read (fi->fd, buf, max)))) - { - GNUNET_asprintf (emsg, - _ ("Could not read file `%s': %s"), - fi->filename, - strerror (errno)); - return 0; - } + GNUNET_DISK_file_seek(fi->fd, offset, GNUNET_DISK_SEEK_SET)) || + (-1 == (ret = GNUNET_DISK_file_read(fi->fd, buf, max)))) + { + GNUNET_asprintf(emsg, + _("Could not read file `%s': %s"), + fi->filename, + strerror(errno)); + return 0; + } if (ret != max) - { - GNUNET_asprintf (emsg, - _ ("Short read reading from file `%s'!"), - fi->filename); - return 0; - } + { + GNUNET_asprintf(emsg, + _("Short read reading from file `%s'!"), + fi->filename); + return 0; + } return max; } @@ -516,17 +521,17 @@ GNUNET_FS_data_reader_file_ (void *cls, * @return closure to use, NULL on error */ void * -GNUNET_FS_make_file_reader_context_ (const char *filename) +GNUNET_FS_make_file_reader_context_(const char *filename) { struct FileInfo *fi; - fi = GNUNET_new (struct FileInfo); - fi->filename = GNUNET_STRINGS_filename_expand (filename); + fi = GNUNET_new(struct FileInfo); + fi->filename = GNUNET_STRINGS_filename_expand(filename); if (NULL == fi->filename) - { - GNUNET_free (fi); - return NULL; - } + { + GNUNET_free(fi); + return NULL; + } return fi; } @@ -552,22 +557,22 @@ GNUNET_FS_make_file_reader_context_ (const char *filename) * @return number of bytes written, usually @a max, 0 on error */ size_t -GNUNET_FS_data_reader_copy_ (void *cls, - uint64_t offset, - size_t max, - void *buf, - char **emsg) +GNUNET_FS_data_reader_copy_(void *cls, + uint64_t offset, + size_t max, + void *buf, + char **emsg) { char *data = cls; if (UINT64_MAX == offset) return 0; if (0 == max) - { - GNUNET_free_non_null (data); - return 0; - } - GNUNET_memcpy (buf, &data[offset], max); + { + GNUNET_free_non_null(data); + return 0; + } + GNUNET_memcpy(buf, &data[offset], max); return max; } @@ -582,30 +587,30 @@ GNUNET_FS_data_reader_copy_ (void *cls, * @return NULL on error */ static char * -get_serialization_file_name (struct GNUNET_FS_Handle *h, - const char *ext, - const char *ent) +get_serialization_file_name(struct GNUNET_FS_Handle *h, + const char *ext, + const char *ent) { char *basename; char *ret; if (0 == (h->flags & GNUNET_FS_FLAGS_PERSISTENCE)) return NULL; /* persistence not requested */ - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (h->cfg, - "fs", - "STATE_DIR", - &basename)) + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(h->cfg, + "fs", + "STATE_DIR", + &basename)) return NULL; - GNUNET_asprintf (&ret, - "%s%s%s%s%s%s%s", - basename, - DIR_SEPARATOR_STR, - h->client_name, - DIR_SEPARATOR_STR, - ext, - DIR_SEPARATOR_STR, - ent); - GNUNET_free (basename); + GNUNET_asprintf(&ret, + "%s%s%s%s%s%s%s", + basename, + DIR_SEPARATOR_STR, + h->client_name, + DIR_SEPARATOR_STR, + ext, + DIR_SEPARATOR_STR, + ent); + GNUNET_free(basename); return ret; } @@ -622,33 +627,33 @@ get_serialization_file_name (struct GNUNET_FS_Handle *h, * @return NULL on error */ static char * -get_serialization_file_name_in_dir (struct GNUNET_FS_Handle *h, - const char *ext, - const char *uni, - const char *ent) +get_serialization_file_name_in_dir(struct GNUNET_FS_Handle *h, + const char *ext, + const char *uni, + const char *ent) { char *basename; char *ret; if (0 == (h->flags & GNUNET_FS_FLAGS_PERSISTENCE)) return NULL; /* persistence not requested */ - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (h->cfg, - "fs", - "STATE_DIR", - &basename)) + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(h->cfg, + "fs", + "STATE_DIR", + &basename)) return NULL; - GNUNET_asprintf (&ret, - "%s%s%s%s%s%s%s.dir%s%s", - basename, - DIR_SEPARATOR_STR, - h->client_name, - DIR_SEPARATOR_STR, - ext, - DIR_SEPARATOR_STR, - uni, - DIR_SEPARATOR_STR, - ent); - GNUNET_free (basename); + GNUNET_asprintf(&ret, + "%s%s%s%s%s%s%s.dir%s%s", + basename, + DIR_SEPARATOR_STR, + h->client_name, + DIR_SEPARATOR_STR, + ext, + DIR_SEPARATOR_STR, + uni, + DIR_SEPARATOR_STR, + ent); + GNUNET_free(basename); return ret; } @@ -662,16 +667,16 @@ get_serialization_file_name_in_dir (struct GNUNET_FS_Handle *h, * @return NULL on error */ static struct GNUNET_BIO_ReadHandle * -get_read_handle (struct GNUNET_FS_Handle *h, const char *ext, const char *ent) +get_read_handle(struct GNUNET_FS_Handle *h, const char *ext, const char *ent) { char *fn; struct GNUNET_BIO_ReadHandle *ret; - fn = get_serialization_file_name (h, ext, ent); + fn = get_serialization_file_name(h, ext, ent); if (NULL == fn) return NULL; - ret = GNUNET_BIO_read_open (fn); - GNUNET_free (fn); + ret = GNUNET_BIO_read_open(fn); + GNUNET_free(fn); return ret; } @@ -685,17 +690,17 @@ get_read_handle (struct GNUNET_FS_Handle *h, const char *ext, const char *ent) * @return NULL on error */ static struct GNUNET_BIO_WriteHandle * -get_write_handle (struct GNUNET_FS_Handle *h, const char *ext, const char *ent) +get_write_handle(struct GNUNET_FS_Handle *h, const char *ext, const char *ent) { char *fn; struct GNUNET_BIO_WriteHandle *ret; - fn = get_serialization_file_name (h, ext, ent); + fn = get_serialization_file_name(h, ext, ent); if (NULL == fn) return NULL; - ret = GNUNET_BIO_write_open (fn); - GNUNET_break (NULL != ret); - GNUNET_free (fn); + ret = GNUNET_BIO_write_open(fn); + GNUNET_break(NULL != ret); + GNUNET_free(fn); return ret; } @@ -710,19 +715,19 @@ get_write_handle (struct GNUNET_FS_Handle *h, const char *ext, const char *ent) * @return NULL on error */ static struct GNUNET_BIO_WriteHandle * -get_write_handle_in_dir (struct GNUNET_FS_Handle *h, - const char *ext, - const char *uni, - const char *ent) +get_write_handle_in_dir(struct GNUNET_FS_Handle *h, + const char *ext, + const char *uni, + const char *ent) { char *fn; struct GNUNET_BIO_WriteHandle *ret; - fn = get_serialization_file_name_in_dir (h, ext, uni, ent); + fn = get_serialization_file_name_in_dir(h, ext, uni, ent); if (NULL == fn) return NULL; - ret = GNUNET_BIO_write_open (fn); - GNUNET_free (fn); + ret = GNUNET_BIO_write_open(fn); + GNUNET_free(fn); return ret; } @@ -735,24 +740,24 @@ get_write_handle_in_dir (struct GNUNET_FS_Handle *h, * @param ent entity identifier */ void -GNUNET_FS_remove_sync_file_ (struct GNUNET_FS_Handle *h, - const char *ext, - const char *ent) +GNUNET_FS_remove_sync_file_(struct GNUNET_FS_Handle *h, + const char *ext, + const char *ent) { char *filename; - if ((NULL == ent) || (0 == strlen (ent))) - { - GNUNET_break (0); - return; - } - filename = get_serialization_file_name (h, ext, ent); + if ((NULL == ent) || (0 == strlen(ent))) + { + GNUNET_break(0); + return; + } + filename = get_serialization_file_name(h, ext, ent); if (NULL != filename) - { - if ((0 != unlink (filename)) && (ENOENT != errno)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", filename); - GNUNET_free (filename); - } + { + if ((0 != unlink(filename)) && (ENOENT != errno)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", filename); + GNUNET_free(filename); + } } @@ -765,24 +770,24 @@ GNUNET_FS_remove_sync_file_ (struct GNUNET_FS_Handle *h, * @param ent entity identifier */ static void -remove_sync_file_in_dir (struct GNUNET_FS_Handle *h, - const char *ext, - const char *uni, - const char *ent) +remove_sync_file_in_dir(struct GNUNET_FS_Handle *h, + const char *ext, + const char *uni, + const char *ent) { char *filename; - if ((NULL == ent) || (0 == strlen (ent))) - { - GNUNET_break (0); - return; - } - filename = get_serialization_file_name_in_dir (h, ext, uni, ent); + if ((NULL == ent) || (0 == strlen(ent))) + { + GNUNET_break(0); + return; + } + filename = get_serialization_file_name_in_dir(h, ext, uni, ent); if (NULL == filename) return; - if (0 != unlink (filename)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", filename); - GNUNET_free (filename); + if (0 != unlink(filename)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", filename); + GNUNET_free(filename); } @@ -794,21 +799,21 @@ remove_sync_file_in_dir (struct GNUNET_FS_Handle *h, * @param uni unique name of parent */ void -GNUNET_FS_remove_sync_dir_ (struct GNUNET_FS_Handle *h, - const char *ext, - const char *uni) +GNUNET_FS_remove_sync_dir_(struct GNUNET_FS_Handle *h, + const char *ext, + const char *uni) { char *dn; if (NULL == uni) return; - dn = get_serialization_file_name_in_dir (h, ext, uni, ""); + dn = get_serialization_file_name_in_dir(h, ext, uni, ""); if (NULL == dn) return; - if ((GNUNET_YES == GNUNET_DISK_directory_test (dn, GNUNET_YES)) && - (GNUNET_OK != GNUNET_DISK_directory_remove (dn))) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rmdir", dn); - GNUNET_free (dn); + if ((GNUNET_YES == GNUNET_DISK_directory_test(dn, GNUNET_YES)) && + (GNUNET_OK != GNUNET_DISK_directory_remove(dn))) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "rmdir", dn); + GNUNET_free(dn); } @@ -827,13 +832,13 @@ GNUNET_FS_remove_sync_dir_ (struct GNUNET_FS_Handle *h, * @return #GNUNET_OK on success */ static int -write_start_time (struct GNUNET_BIO_WriteHandle *wh, - struct GNUNET_TIME_Absolute timestamp) +write_start_time(struct GNUNET_BIO_WriteHandle *wh, + struct GNUNET_TIME_Absolute timestamp) { struct GNUNET_TIME_Relative dur; - dur = GNUNET_TIME_absolute_get_duration (timestamp); - return GNUNET_BIO_write_int64 (wh, dur.rel_value_us); + dur = GNUNET_TIME_absolute_get_duration(timestamp); + return GNUNET_BIO_write_int64(wh, dur.rel_value_us); } @@ -852,14 +857,14 @@ write_start_time (struct GNUNET_BIO_WriteHandle *wh, * @return #GNUNET_OK on success */ static int -read_start_time (struct GNUNET_BIO_ReadHandle *rh, - struct GNUNET_TIME_Absolute *timestamp) +read_start_time(struct GNUNET_BIO_ReadHandle *rh, + struct GNUNET_TIME_Absolute *timestamp) { struct GNUNET_TIME_Relative dur; - if (GNUNET_OK != GNUNET_BIO_read_int64 (rh, &dur.rel_value_us)) + if (GNUNET_OK != GNUNET_BIO_read_int64(rh, &dur.rel_value_us)) return GNUNET_SYSERR; - *timestamp = GNUNET_TIME_absolute_subtract (GNUNET_TIME_absolute_get (), dur); + *timestamp = GNUNET_TIME_absolute_subtract(GNUNET_TIME_absolute_get(), dur); return GNUNET_OK; } @@ -874,7 +879,7 @@ read_start_time (struct GNUNET_BIO_ReadHandle *rh, * @return NULL on error */ static struct GNUNET_FS_FileInformation * -deserialize_file_information (struct GNUNET_FS_Handle *h, const char *filename); +deserialize_file_information(struct GNUNET_FS_Handle *h, const char *filename); /** @@ -888,9 +893,9 @@ deserialize_file_information (struct GNUNET_FS_Handle *h, const char *filename); * @return NULL on error */ static struct GNUNET_FS_FileInformation * -deserialize_fi_node (struct GNUNET_FS_Handle *h, - const char *fn, - struct GNUNET_BIO_ReadHandle *rh) +deserialize_fi_node(struct GNUNET_FS_Handle *h, + const char *fn, + struct GNUNET_BIO_ReadHandle *rh) { struct GNUNET_FS_FileInformation *ret; struct GNUNET_FS_FileInformation *nxt; @@ -901,204 +906,209 @@ deserialize_fi_node (struct GNUNET_FS_Handle *h, char *filename; uint32_t dsize; - if (GNUNET_OK != GNUNET_BIO_read (rh, "status flag", &b, sizeof (b))) - { - GNUNET_break (0); - return NULL; - } - ret = GNUNET_new (struct GNUNET_FS_FileInformation); + if (GNUNET_OK != GNUNET_BIO_read(rh, "status flag", &b, sizeof(b))) + { + GNUNET_break(0); + return NULL; + } + ret = GNUNET_new(struct GNUNET_FS_FileInformation); ret->h = h; ksks = NULL; chks = NULL; skss = NULL; filename = NULL; - if ((GNUNET_OK != GNUNET_BIO_read_meta_data (rh, "metadata", &ret->meta)) || - (GNUNET_OK != GNUNET_BIO_read_string (rh, "ksk-uri", &ksks, 32 * 1024)) || + if ((GNUNET_OK != GNUNET_BIO_read_meta_data(rh, "metadata", &ret->meta)) || + (GNUNET_OK != GNUNET_BIO_read_string(rh, "ksk-uri", &ksks, 32 * 1024)) || ((NULL != ksks) && - ((NULL == (ret->keywords = GNUNET_FS_uri_parse (ksks, NULL))) || - (GNUNET_YES != GNUNET_FS_uri_test_ksk (ret->keywords)))) || - (GNUNET_OK != GNUNET_BIO_read_string (rh, "chk-uri", &chks, 1024)) || + ((NULL == (ret->keywords = GNUNET_FS_uri_parse(ksks, NULL))) || + (GNUNET_YES != GNUNET_FS_uri_test_ksk(ret->keywords)))) || + (GNUNET_OK != GNUNET_BIO_read_string(rh, "chk-uri", &chks, 1024)) || ((NULL != chks) && - ((NULL == (ret->chk_uri = GNUNET_FS_uri_parse (chks, NULL))) || - (GNUNET_YES != GNUNET_FS_uri_test_chk (ret->chk_uri)))) || - (GNUNET_OK != GNUNET_BIO_read_string (rh, "sks-uri", &skss, 1024)) || + ((NULL == (ret->chk_uri = GNUNET_FS_uri_parse(chks, NULL))) || + (GNUNET_YES != GNUNET_FS_uri_test_chk(ret->chk_uri)))) || + (GNUNET_OK != GNUNET_BIO_read_string(rh, "sks-uri", &skss, 1024)) || ((NULL != skss) && - ((NULL == (ret->sks_uri = GNUNET_FS_uri_parse (skss, NULL))) || - (GNUNET_YES != GNUNET_FS_uri_test_sks (ret->sks_uri)))) || - (GNUNET_OK != read_start_time (rh, &ret->start_time)) || + ((NULL == (ret->sks_uri = GNUNET_FS_uri_parse(skss, NULL))) || + (GNUNET_YES != GNUNET_FS_uri_test_sks(ret->sks_uri)))) || + (GNUNET_OK != read_start_time(rh, &ret->start_time)) || (GNUNET_OK != - GNUNET_BIO_read_string (rh, "emsg", &ret->emsg, 16 * 1024)) || + GNUNET_BIO_read_string(rh, "emsg", &ret->emsg, 16 * 1024)) || (GNUNET_OK != - GNUNET_BIO_read_string (rh, "fn", &ret->filename, 16 * 1024)) || + GNUNET_BIO_read_string(rh, "fn", &ret->filename, 16 * 1024)) || (GNUNET_OK != - GNUNET_BIO_read_int64 (rh, &ret->bo.expiration_time.abs_value_us)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &ret->bo.anonymity_level)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &ret->bo.content_priority)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &ret->bo.replication_level))) - { - GNUNET_break (0); - goto cleanup; - } - switch (b) - { - case 0: /* file-insert */ - if (GNUNET_OK != GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size)) + GNUNET_BIO_read_int64(rh, &ret->bo.expiration_time.abs_value_us)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &ret->bo.anonymity_level)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &ret->bo.content_priority)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &ret->bo.replication_level))) { - GNUNET_break (0); + GNUNET_break(0); goto cleanup; } - ret->is_directory = GNUNET_NO; - ret->data.file.do_index = GNUNET_NO; - ret->data.file.have_hash = GNUNET_NO; - ret->data.file.index_start_confirmed = GNUNET_NO; - if (GNUNET_NO == ret->is_published) + switch (b) { + case 0: /* file-insert */ + if (GNUNET_OK != GNUNET_BIO_read_int64(rh, &ret->data.file.file_size)) + { + GNUNET_break(0); + goto cleanup; + } + ret->is_directory = GNUNET_NO; + ret->data.file.do_index = GNUNET_NO; + ret->data.file.have_hash = GNUNET_NO; + ret->data.file.index_start_confirmed = GNUNET_NO; + if (GNUNET_NO == ret->is_published) + { + if (NULL == ret->filename) + { + ret->data.file.reader = &GNUNET_FS_data_reader_copy_; + ret->data.file.reader_cls = + GNUNET_malloc_large(ret->data.file.file_size); + if (ret->data.file.reader_cls == NULL) + goto cleanup; + if (GNUNET_OK != GNUNET_BIO_read(rh, + "file-data", + ret->data.file.reader_cls, + ret->data.file.file_size)) + { + GNUNET_break(0); + goto cleanup; + } + } + else + { + ret->data.file.reader = &GNUNET_FS_data_reader_file_; + ret->data.file.reader_cls = + GNUNET_FS_make_file_reader_context_(ret->filename); + } + } + break; + + case 1: /* file-index, no hash */ + if (NULL == ret->filename) + { + GNUNET_break(0); + goto cleanup; + } + if (GNUNET_OK != GNUNET_BIO_read_int64(rh, &ret->data.file.file_size)) + { + GNUNET_break(0); + goto cleanup; + } + ret->is_directory = GNUNET_NO; + ret->data.file.do_index = GNUNET_YES; + ret->data.file.have_hash = GNUNET_NO; + ret->data.file.index_start_confirmed = GNUNET_NO; + ret->data.file.reader = &GNUNET_FS_data_reader_file_; + ret->data.file.reader_cls = + GNUNET_FS_make_file_reader_context_(ret->filename); + break; + + case 2: /* file-index-with-hash */ if (NULL == ret->filename) - { - ret->data.file.reader = &GNUNET_FS_data_reader_copy_; - ret->data.file.reader_cls = - GNUNET_malloc_large (ret->data.file.file_size); - if (ret->data.file.reader_cls == NULL) + { + GNUNET_break(0); goto cleanup; - if (GNUNET_OK != GNUNET_BIO_read (rh, - "file-data", - ret->data.file.reader_cls, - ret->data.file.file_size)) + } + if ((GNUNET_OK != GNUNET_BIO_read_int64(rh, &ret->data.file.file_size)) || + (GNUNET_OK != GNUNET_BIO_read(rh, + "fileid", + &ret->data.file.file_id, + sizeof(struct GNUNET_HashCode)))) { - GNUNET_break (0); + GNUNET_break(0); goto cleanup; } - } - else - { - ret->data.file.reader = &GNUNET_FS_data_reader_file_; - ret->data.file.reader_cls = - GNUNET_FS_make_file_reader_context_ (ret->filename); - } - } - break; - case 1: /* file-index, no hash */ - if (NULL == ret->filename) - { - GNUNET_break (0); - goto cleanup; - } - if (GNUNET_OK != GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size)) - { - GNUNET_break (0); - goto cleanup; - } - ret->is_directory = GNUNET_NO; - ret->data.file.do_index = GNUNET_YES; - ret->data.file.have_hash = GNUNET_NO; - ret->data.file.index_start_confirmed = GNUNET_NO; - ret->data.file.reader = &GNUNET_FS_data_reader_file_; - ret->data.file.reader_cls = - GNUNET_FS_make_file_reader_context_ (ret->filename); - break; - case 2: /* file-index-with-hash */ - if (NULL == ret->filename) - { - GNUNET_break (0); - goto cleanup; - } - if ((GNUNET_OK != GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size)) || - (GNUNET_OK != GNUNET_BIO_read (rh, - "fileid", - &ret->data.file.file_id, - sizeof (struct GNUNET_HashCode)))) - { - GNUNET_break (0); - goto cleanup; - } - ret->is_directory = GNUNET_NO; - ret->data.file.do_index = GNUNET_YES; - ret->data.file.have_hash = GNUNET_YES; - ret->data.file.index_start_confirmed = GNUNET_NO; - ret->data.file.reader = &GNUNET_FS_data_reader_file_; - ret->data.file.reader_cls = - GNUNET_FS_make_file_reader_context_ (ret->filename); - break; - case 3: /* file-index-with-hash-confirmed */ - if (NULL == ret->filename) - { - GNUNET_break (0); + ret->is_directory = GNUNET_NO; + ret->data.file.do_index = GNUNET_YES; + ret->data.file.have_hash = GNUNET_YES; + ret->data.file.index_start_confirmed = GNUNET_NO; + ret->data.file.reader = &GNUNET_FS_data_reader_file_; + ret->data.file.reader_cls = + GNUNET_FS_make_file_reader_context_(ret->filename); + break; + + case 3: /* file-index-with-hash-confirmed */ + if (NULL == ret->filename) + { + GNUNET_break(0); + goto cleanup; + } + if ((GNUNET_OK != GNUNET_BIO_read_int64(rh, &ret->data.file.file_size)) || + (GNUNET_OK != GNUNET_BIO_read(rh, + "fileid", + &ret->data.file.file_id, + sizeof(struct GNUNET_HashCode)))) + { + GNUNET_break(0); + goto cleanup; + } + ret->is_directory = GNUNET_NO; + ret->data.file.do_index = GNUNET_YES; + ret->data.file.have_hash = GNUNET_YES; + ret->data.file.index_start_confirmed = GNUNET_YES; + ret->data.file.reader = &GNUNET_FS_data_reader_file_; + ret->data.file.reader_cls = + GNUNET_FS_make_file_reader_context_(ret->filename); + break; + + case 4: /* directory */ + ret->is_directory = GNUNET_YES; + if ((GNUNET_OK != GNUNET_BIO_read_int32(rh, &dsize)) || + (GNUNET_OK != + GNUNET_BIO_read_int64(rh, &ret->data.dir.contents_completed)) || + (GNUNET_OK != + GNUNET_BIO_read_int64(rh, &ret->data.dir.contents_size)) || + (NULL == (ret->data.dir.dir_data = GNUNET_malloc_large(dsize))) || + (GNUNET_OK != + GNUNET_BIO_read(rh, "dir-data", ret->data.dir.dir_data, dsize)) || + (GNUNET_OK != + GNUNET_BIO_read_string(rh, "ent-filename", &filename, 16 * 1024))) + { + GNUNET_break(0); + goto cleanup; + } + ret->data.dir.dir_size = (uint32_t)dsize; + if (NULL != filename) + { + ret->data.dir.entries = deserialize_file_information(h, filename); + GNUNET_free(filename); + filename = NULL; + nxt = ret->data.dir.entries; + while (NULL != nxt) + { + nxt->dir = ret; + nxt = nxt->next; + } + } + break; + + default: + GNUNET_break(0); goto cleanup; } - if ((GNUNET_OK != GNUNET_BIO_read_int64 (rh, &ret->data.file.file_size)) || - (GNUNET_OK != GNUNET_BIO_read (rh, - "fileid", - &ret->data.file.file_id, - sizeof (struct GNUNET_HashCode)))) + ret->serialization = GNUNET_strdup(fn); + if (GNUNET_OK != + GNUNET_BIO_read_string(rh, "nxt-filename", &filename, 16 * 1024)) { - GNUNET_break (0); + GNUNET_break(0); goto cleanup; } - ret->is_directory = GNUNET_NO; - ret->data.file.do_index = GNUNET_YES; - ret->data.file.have_hash = GNUNET_YES; - ret->data.file.index_start_confirmed = GNUNET_YES; - ret->data.file.reader = &GNUNET_FS_data_reader_file_; - ret->data.file.reader_cls = - GNUNET_FS_make_file_reader_context_ (ret->filename); - break; - case 4: /* directory */ - ret->is_directory = GNUNET_YES; - if ((GNUNET_OK != GNUNET_BIO_read_int32 (rh, &dsize)) || - (GNUNET_OK != - GNUNET_BIO_read_int64 (rh, &ret->data.dir.contents_completed)) || - (GNUNET_OK != - GNUNET_BIO_read_int64 (rh, &ret->data.dir.contents_size)) || - (NULL == (ret->data.dir.dir_data = GNUNET_malloc_large (dsize))) || - (GNUNET_OK != - GNUNET_BIO_read (rh, "dir-data", ret->data.dir.dir_data, dsize)) || - (GNUNET_OK != - GNUNET_BIO_read_string (rh, "ent-filename", &filename, 16 * 1024))) - { - GNUNET_break (0); - goto cleanup; - } - ret->data.dir.dir_size = (uint32_t) dsize; - if (NULL != filename) + if (NULL != filename) { - ret->data.dir.entries = deserialize_file_information (h, filename); - GNUNET_free (filename); + ret->next = deserialize_file_information(h, filename); + GNUNET_free(filename); filename = NULL; - nxt = ret->data.dir.entries; - while (NULL != nxt) - { - nxt->dir = ret; - nxt = nxt->next; - } - } - break; - default: - GNUNET_break (0); - goto cleanup; - } - ret->serialization = GNUNET_strdup (fn); - if (GNUNET_OK != - GNUNET_BIO_read_string (rh, "nxt-filename", &filename, 16 * 1024)) - { - GNUNET_break (0); - goto cleanup; - } - if (NULL != filename) - { - ret->next = deserialize_file_information (h, filename); - GNUNET_free (filename); - filename = NULL; - } - GNUNET_free_non_null (ksks); - GNUNET_free_non_null (skss); - GNUNET_free_non_null (chks); + } + GNUNET_free_non_null(ksks); + GNUNET_free_non_null(skss); + GNUNET_free_non_null(chks); return ret; cleanup: - GNUNET_free_non_null (ksks); - GNUNET_free_non_null (chks); - GNUNET_free_non_null (skss); - GNUNET_free_non_null (filename); - GNUNET_FS_file_information_destroy (ret, NULL, NULL); + GNUNET_free_non_null(ksks); + GNUNET_free_non_null(chks); + GNUNET_free_non_null(skss); + GNUNET_free_non_null(filename); + GNUNET_FS_file_information_destroy(ret, NULL, NULL); return NULL; } @@ -1113,36 +1123,36 @@ cleanup: * @return NULL on error */ static struct GNUNET_FS_FileInformation * -deserialize_file_information (struct GNUNET_FS_Handle *h, const char *filename) +deserialize_file_information(struct GNUNET_FS_Handle *h, const char *filename) { struct GNUNET_FS_FileInformation *ret; struct GNUNET_BIO_ReadHandle *rh; char *emsg; char *fn; - rh = get_read_handle (h, GNUNET_FS_SYNC_PATH_FILE_INFO, filename); + rh = get_read_handle(h, GNUNET_FS_SYNC_PATH_FILE_INFO, filename); if (NULL == rh) return NULL; - ret = deserialize_fi_node (h, filename, rh); - if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to resume publishing information `%s': %s\n"), - filename, - emsg); - GNUNET_free (emsg); - } + ret = deserialize_fi_node(h, filename, rh); + if (GNUNET_OK != GNUNET_BIO_read_close(rh, &emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to resume publishing information `%s': %s\n"), + filename, + emsg); + GNUNET_free(emsg); + } if (NULL == ret) - { - fn = - get_serialization_file_name (h, GNUNET_FS_SYNC_PATH_FILE_INFO, filename); - if (NULL != fn) { - if (0 != unlink (fn)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn); - GNUNET_free (fn); + fn = + get_serialization_file_name(h, GNUNET_FS_SYNC_PATH_FILE_INFO, filename); + if (NULL != fn) + { + if (0 != unlink(fn)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", fn); + GNUNET_free(fn); + } } - } return ret; } @@ -1156,7 +1166,7 @@ deserialize_file_information (struct GNUNET_FS_Handle *h, const char *filename) * @return copy of the basename, NULL on error */ static char * -get_serialization_short_name (const char *fullname) +get_serialization_short_name(const char *fullname) { const char *end; const char *nxt; @@ -1166,18 +1176,18 @@ get_serialization_short_name (const char *fullname) /* FIXME: we could do this faster since we know * the length of 'end'... */ while ('\0' != *nxt) - { - if (DIR_SEPARATOR == *nxt) - end = nxt + 1; - nxt++; - } - if ((NULL == end) || (0 == strlen (end))) - { - GNUNET_break (0); - return NULL; - } - GNUNET_break (6 == strlen (end)); - return GNUNET_strdup (end); + { + if (DIR_SEPARATOR == *nxt) + end = nxt + 1; + nxt++; + } + if ((NULL == end) || (0 == strlen(end))) + { + GNUNET_break(0); + return NULL; + } + GNUNET_break(6 == strlen(end)); + return GNUNET_strdup(end); } @@ -1190,7 +1200,7 @@ get_serialization_short_name (const char *fullname) * @return NULL on errror */ static char * -make_serialization_file_name (struct GNUNET_FS_Handle *h, const char *ext) +make_serialization_file_name(struct GNUNET_FS_Handle *h, const char *ext) { char *fn; char *dn; @@ -1198,20 +1208,20 @@ make_serialization_file_name (struct GNUNET_FS_Handle *h, const char *ext) if (0 == (h->flags & GNUNET_FS_FLAGS_PERSISTENCE)) return NULL; /* persistence not requested */ - dn = get_serialization_file_name (h, ext, ""); + dn = get_serialization_file_name(h, ext, ""); if (NULL == dn) return NULL; - if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (dn)) - { - GNUNET_free (dn); - return NULL; - } - fn = GNUNET_DISK_mktemp (dn); - GNUNET_free (dn); + if (GNUNET_OK != GNUNET_DISK_directory_create_for_file(dn)) + { + GNUNET_free(dn); + return NULL; + } + fn = GNUNET_DISK_mktemp(dn); + GNUNET_free(dn); if (NULL == fn) return NULL; /* epic fail */ - ret = get_serialization_short_name (fn); - GNUNET_free (fn); + ret = get_serialization_short_name(fn); + GNUNET_free(fn); return ret; } @@ -1226,9 +1236,9 @@ make_serialization_file_name (struct GNUNET_FS_Handle *h, const char *ext) * @return NULL on errror */ static char * -make_serialization_file_name_in_dir (struct GNUNET_FS_Handle *h, - const char *ext, - const char *uni) +make_serialization_file_name_in_dir(struct GNUNET_FS_Handle *h, + const char *ext, + const char *uni) { char *fn; char *dn; @@ -1236,20 +1246,20 @@ make_serialization_file_name_in_dir (struct GNUNET_FS_Handle *h, if (0 == (h->flags & GNUNET_FS_FLAGS_PERSISTENCE)) return NULL; /* persistence not requested */ - dn = get_serialization_file_name_in_dir (h, ext, uni, ""); + dn = get_serialization_file_name_in_dir(h, ext, uni, ""); if (NULL == dn) return NULL; - if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (dn)) - { - GNUNET_free (dn); - return NULL; - } - fn = GNUNET_DISK_mktemp (dn); - GNUNET_free (dn); + if (GNUNET_OK != GNUNET_DISK_directory_create_for_file(dn)) + { + GNUNET_free(dn); + return NULL; + } + fn = GNUNET_DISK_mktemp(dn); + GNUNET_free(dn); if (NULL == fn) return NULL; /* epic fail */ - ret = get_serialization_short_name (fn); - GNUNET_free (fn); + ret = get_serialization_short_name(fn); + GNUNET_free(fn); return ret; } @@ -1262,8 +1272,8 @@ make_serialization_file_name_in_dir (struct GNUNET_FS_Handle *h, * @return #GNUNET_OK on success */ static int -copy_from_reader (struct GNUNET_BIO_WriteHandle *wh, - struct GNUNET_FS_FileInformation *fi) +copy_from_reader(struct GNUNET_BIO_WriteHandle *wh, + struct GNUNET_FS_FileInformation *fi) { char buf[32 * 1024]; uint64_t off; @@ -1274,19 +1284,19 @@ copy_from_reader (struct GNUNET_BIO_WriteHandle *wh, emsg = NULL; off = 0; while (off < fi->data.file.file_size) - { - left = GNUNET_MIN (sizeof (buf), fi->data.file.file_size - off); - ret = - fi->data.file.reader (fi->data.file.reader_cls, off, left, buf, &emsg); - if (0 == ret) - { - GNUNET_free (emsg); - return GNUNET_SYSERR; - } - if (GNUNET_OK != GNUNET_BIO_write (wh, buf, ret)) - return GNUNET_SYSERR; - off += ret; - } + { + left = GNUNET_MIN(sizeof(buf), fi->data.file.file_size - off); + ret = + fi->data.file.reader(fi->data.file.reader_cls, off, left, buf, &emsg); + if (0 == ret) + { + GNUNET_free(emsg); + return GNUNET_SYSERR; + } + if (GNUNET_OK != GNUNET_BIO_write(wh, buf, ret)) + return GNUNET_SYSERR; + off += ret; + } return GNUNET_OK; } @@ -1298,7 +1308,7 @@ copy_from_reader (struct GNUNET_BIO_WriteHandle *wh, * @param fi file information to sync with disk */ void -GNUNET_FS_file_information_sync_ (struct GNUNET_FS_FileInformation *fi) +GNUNET_FS_file_information_sync_(struct GNUNET_FS_FileInformation *fi) { char *fn; struct GNUNET_BIO_WriteHandle *wh; @@ -1309,17 +1319,17 @@ GNUNET_FS_file_information_sync_ (struct GNUNET_FS_FileInformation *fi) if (NULL == fi->serialization) fi->serialization = - make_serialization_file_name (fi->h, GNUNET_FS_SYNC_PATH_FILE_INFO); + make_serialization_file_name(fi->h, GNUNET_FS_SYNC_PATH_FILE_INFO); if (NULL == fi->serialization) return; wh = - get_write_handle (fi->h, GNUNET_FS_SYNC_PATH_FILE_INFO, fi->serialization); + get_write_handle(fi->h, GNUNET_FS_SYNC_PATH_FILE_INFO, fi->serialization); if (NULL == wh) - { - GNUNET_free (fi->serialization); - fi->serialization = NULL; - return; - } + { + GNUNET_free(fi->serialization); + fi->serialization = NULL; + return; + } if (GNUNET_YES == fi->is_directory) b = 4; else if (GNUNET_YES == fi->data.file.index_start_confirmed) @@ -1331,143 +1341,147 @@ GNUNET_FS_file_information_sync_ (struct GNUNET_FS_FileInformation *fi) else b = 0; if (NULL != fi->keywords) - ksks = GNUNET_FS_uri_to_string (fi->keywords); + ksks = GNUNET_FS_uri_to_string(fi->keywords); else ksks = NULL; if (NULL != fi->chk_uri) - chks = GNUNET_FS_uri_to_string (fi->chk_uri); + chks = GNUNET_FS_uri_to_string(fi->chk_uri); else chks = NULL; if (NULL != fi->sks_uri) - skss = GNUNET_FS_uri_to_string (fi->sks_uri); + skss = GNUNET_FS_uri_to_string(fi->sks_uri); else skss = NULL; - if ((GNUNET_OK != GNUNET_BIO_write (wh, &b, sizeof (b))) || - (GNUNET_OK != GNUNET_BIO_write_meta_data (wh, fi->meta)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, ksks)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, chks)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, skss)) || - (GNUNET_OK != write_start_time (wh, fi->start_time)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, fi->emsg)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, fi->filename)) || + if ((GNUNET_OK != GNUNET_BIO_write(wh, &b, sizeof(b))) || + (GNUNET_OK != GNUNET_BIO_write_meta_data(wh, fi->meta)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, ksks)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, chks)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, skss)) || + (GNUNET_OK != write_start_time(wh, fi->start_time)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, fi->emsg)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, fi->filename)) || (GNUNET_OK != - GNUNET_BIO_write_int64 (wh, fi->bo.expiration_time.abs_value_us)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, fi->bo.anonymity_level)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, fi->bo.content_priority)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, fi->bo.replication_level))) - { - GNUNET_break (0); - goto cleanup; - } - GNUNET_free_non_null (chks); + GNUNET_BIO_write_int64(wh, fi->bo.expiration_time.abs_value_us)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, fi->bo.anonymity_level)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, fi->bo.content_priority)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, fi->bo.replication_level))) + { + GNUNET_break(0); + goto cleanup; + } + GNUNET_free_non_null(chks); chks = NULL; - GNUNET_free_non_null (ksks); + GNUNET_free_non_null(ksks); ksks = NULL; - GNUNET_free_non_null (skss); + GNUNET_free_non_null(skss); skss = NULL; switch (b) - { - case 0: /* file-insert */ - if (GNUNET_OK != GNUNET_BIO_write_int64 (wh, fi->data.file.file_size)) - { - GNUNET_break (0); - goto cleanup; - } - if ((GNUNET_NO == fi->is_published) && (NULL == fi->filename)) - if (GNUNET_OK != copy_from_reader (wh, fi)) - { - GNUNET_break (0); - goto cleanup; - } - break; - case 1: /* file-index, no hash */ - if (NULL == fi->filename) { - GNUNET_break (0); - goto cleanup; - } - if (GNUNET_OK != GNUNET_BIO_write_int64 (wh, fi->data.file.file_size)) - { - GNUNET_break (0); + case 0: /* file-insert */ + if (GNUNET_OK != GNUNET_BIO_write_int64(wh, fi->data.file.file_size)) + { + GNUNET_break(0); + goto cleanup; + } + if ((GNUNET_NO == fi->is_published) && (NULL == fi->filename)) + if (GNUNET_OK != copy_from_reader(wh, fi)) + { + GNUNET_break(0); + goto cleanup; + } + break; + + case 1: /* file-index, no hash */ + if (NULL == fi->filename) + { + GNUNET_break(0); + goto cleanup; + } + if (GNUNET_OK != GNUNET_BIO_write_int64(wh, fi->data.file.file_size)) + { + GNUNET_break(0); + goto cleanup; + } + break; + + case 2: /* file-index-with-hash */ + case 3: /* file-index-with-hash-confirmed */ + if (NULL == fi->filename) + { + GNUNET_break(0); + goto cleanup; + } + if ((GNUNET_OK != GNUNET_BIO_write_int64(wh, fi->data.file.file_size)) || + (GNUNET_OK != GNUNET_BIO_write(wh, + &fi->data.file.file_id, + sizeof(struct GNUNET_HashCode)))) + { + GNUNET_break(0); + goto cleanup; + } + break; + + case 4: /* directory */ + if ((NULL != fi->data.dir.entries) && + (NULL == fi->data.dir.entries->serialization)) + GNUNET_FS_file_information_sync_(fi->data.dir.entries); + if ((GNUNET_OK != GNUNET_BIO_write_int32(wh, fi->data.dir.dir_size)) || + (GNUNET_OK != + GNUNET_BIO_write_int64(wh, fi->data.dir.contents_completed)) || + (GNUNET_OK != + GNUNET_BIO_write_int64(wh, fi->data.dir.contents_size)) || + (GNUNET_OK != GNUNET_BIO_write(wh, + fi->data.dir.dir_data, + (uint32_t)fi->data.dir.dir_size)) || + (GNUNET_OK != + GNUNET_BIO_write_string(wh, + (fi->data.dir.entries == NULL) + ? NULL + : fi->data.dir.entries->serialization))) + { + GNUNET_break(0); + goto cleanup; + } + break; + + default: + GNUNET_assert(0); goto cleanup; } - break; - case 2: /* file-index-with-hash */ - case 3: /* file-index-with-hash-confirmed */ - if (NULL == fi->filename) + if ((NULL != fi->next) && (NULL == fi->next->serialization)) + GNUNET_FS_file_information_sync_(fi->next); + if (GNUNET_OK != GNUNET_BIO_write_string(wh, + (fi->next != NULL) + ? fi->next->serialization + : NULL)) { - GNUNET_break (0); + GNUNET_break(0); goto cleanup; } - if ((GNUNET_OK != GNUNET_BIO_write_int64 (wh, fi->data.file.file_size)) || - (GNUNET_OK != GNUNET_BIO_write (wh, - &fi->data.file.file_id, - sizeof (struct GNUNET_HashCode)))) + if (GNUNET_OK != GNUNET_BIO_write_close(wh)) { - GNUNET_break (0); + wh = NULL; + GNUNET_break(0); goto cleanup; } - break; - case 4: /* directory */ - if ((NULL != fi->data.dir.entries) && - (NULL == fi->data.dir.entries->serialization)) - GNUNET_FS_file_information_sync_ (fi->data.dir.entries); - if ((GNUNET_OK != GNUNET_BIO_write_int32 (wh, fi->data.dir.dir_size)) || - (GNUNET_OK != - GNUNET_BIO_write_int64 (wh, fi->data.dir.contents_completed)) || - (GNUNET_OK != - GNUNET_BIO_write_int64 (wh, fi->data.dir.contents_size)) || - (GNUNET_OK != GNUNET_BIO_write (wh, - fi->data.dir.dir_data, - (uint32_t) fi->data.dir.dir_size)) || - (GNUNET_OK != - GNUNET_BIO_write_string (wh, - (fi->data.dir.entries == NULL) - ? NULL - : fi->data.dir.entries->serialization))) - { - GNUNET_break (0); - goto cleanup; - } - break; - default: - GNUNET_assert (0); - goto cleanup; - } - if ((NULL != fi->next) && (NULL == fi->next->serialization)) - GNUNET_FS_file_information_sync_ (fi->next); - if (GNUNET_OK != GNUNET_BIO_write_string (wh, - (fi->next != NULL) - ? fi->next->serialization - : NULL)) - { - GNUNET_break (0); - goto cleanup; - } - if (GNUNET_OK != GNUNET_BIO_write_close (wh)) - { - wh = NULL; - GNUNET_break (0); - goto cleanup; - } return; /* done! */ cleanup: if (NULL != wh) - (void) GNUNET_BIO_write_close (wh); - GNUNET_free_non_null (chks); - GNUNET_free_non_null (ksks); - GNUNET_free_non_null (skss); - fn = get_serialization_file_name (fi->h, - GNUNET_FS_SYNC_PATH_FILE_INFO, - fi->serialization); + (void)GNUNET_BIO_write_close(wh); + GNUNET_free_non_null(chks); + GNUNET_free_non_null(ksks); + GNUNET_free_non_null(skss); + fn = get_serialization_file_name(fi->h, + GNUNET_FS_SYNC_PATH_FILE_INFO, + fi->serialization); if (NULL != fn) - { - if (0 != unlink (fn)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn); - GNUNET_free (fn); - } - GNUNET_free (fi->serialization); + { + if (0 != unlink(fn)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", fn); + GNUNET_free(fn); + } + GNUNET_free(fi->serialization); fi->serialization = NULL; } @@ -1481,19 +1495,19 @@ cleanup: * @return NULL if srch was not found in this subtree */ static struct GNUNET_FS_FileInformation * -find_file_position (struct GNUNET_FS_FileInformation *pos, const char *srch) +find_file_position(struct GNUNET_FS_FileInformation *pos, const char *srch) { struct GNUNET_FS_FileInformation *r; while (NULL != pos) - { - if (0 == strcmp (srch, pos->serialization)) - return pos; - if ((GNUNET_YES == pos->is_directory) && - (NULL != (r = find_file_position (pos->data.dir.entries, srch)))) - return r; - pos = pos->next; - } + { + if (0 == strcmp(srch, pos->serialization)) + return pos; + if ((GNUNET_YES == pos->is_directory) && + (NULL != (r = find_file_position(pos->data.dir.entries, srch)))) + return r; + pos = pos->next; + } return NULL; } @@ -1513,33 +1527,33 @@ find_file_position (struct GNUNET_FS_FileInformation *pos, const char *srch) * @return #GNUNET_OK to continue (always) */ static int -fip_signal_resume (void *cls, - struct GNUNET_FS_FileInformation *fi, - uint64_t length, - struct GNUNET_CONTAINER_MetaData *meta, - struct GNUNET_FS_Uri **uri, - struct GNUNET_FS_BlockOptions *bo, - int *do_index, - void **client_info) +fip_signal_resume(void *cls, + struct GNUNET_FS_FileInformation *fi, + uint64_t length, + struct GNUNET_CONTAINER_MetaData *meta, + struct GNUNET_FS_Uri **uri, + struct GNUNET_FS_BlockOptions *bo, + int *do_index, + void **client_info) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_ProgressInfo pi; if (GNUNET_YES == pc->skip_next_fi_callback) - { - pc->skip_next_fi_callback = GNUNET_NO; - return GNUNET_OK; - } + { + pc->skip_next_fi_callback = GNUNET_NO; + return GNUNET_OK; + } pi.status = GNUNET_FS_STATUS_PUBLISH_RESUME; pi.value.publish.specifics.resume.message = fi->emsg; pi.value.publish.specifics.resume.chk_uri = fi->chk_uri; - *client_info = GNUNET_FS_publish_make_status_ (&pi, pc, fi, 0); - if (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) - { - /* process entries in directory */ - pc->skip_next_fi_callback = GNUNET_YES; - GNUNET_FS_file_information_inspect (fi, &fip_signal_resume, pc); - } + *client_info = GNUNET_FS_publish_make_status_(&pi, pc, fi, 0); + if (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory(meta)) + { + /* process entries in directory */ + pc->skip_next_fi_callback = GNUNET_YES; + GNUNET_FS_file_information_inspect(fi, &fip_signal_resume, pc); + } return GNUNET_OK; } @@ -1553,7 +1567,7 @@ fip_signal_resume (void *cls, * @return #GNUNET_OK (continue to iterate) */ static int -deserialize_publish_file (void *cls, const char *filename) +deserialize_publish_file(void *cls, const char *filename) { struct GNUNET_FS_Handle *h = cls; struct GNUNET_BIO_ReadHandle *rh; @@ -1566,115 +1580,115 @@ deserialize_publish_file (void *cls, const char *filename) char *fi_pos; char *emsg; - pc = GNUNET_new (struct GNUNET_FS_PublishContext); + pc = GNUNET_new(struct GNUNET_FS_PublishContext); pc->h = h; - pc->serialization = get_serialization_short_name (filename); + pc->serialization = get_serialization_short_name(filename); fi_root = NULL; fi_pos = NULL; - rh = GNUNET_BIO_read_open (filename); + rh = GNUNET_BIO_read_open(filename); if (NULL == rh) - { - GNUNET_break (0); - goto cleanup; - } + { + GNUNET_break(0); + goto cleanup; + } if ((GNUNET_OK != - GNUNET_BIO_read_string (rh, "publish-nid", &pc->nid, 1024)) || + GNUNET_BIO_read_string(rh, "publish-nid", &pc->nid, 1024)) || (GNUNET_OK != - GNUNET_BIO_read_string (rh, "publish-nuid", &pc->nuid, 1024)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &options)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &all_done)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &have_ns)) || + GNUNET_BIO_read_string(rh, "publish-nuid", &pc->nuid, 1024)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &options)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &all_done)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &have_ns)) || (GNUNET_OK != - GNUNET_BIO_read_string (rh, "publish-firoot", &fi_root, 128)) || + GNUNET_BIO_read_string(rh, "publish-firoot", &fi_root, 128)) || (GNUNET_OK != - GNUNET_BIO_read_string (rh, "publish-fipos", &fi_pos, 128)) || + GNUNET_BIO_read_string(rh, "publish-fipos", &fi_pos, 128)) || ((GNUNET_YES == have_ns) && - (GNUNET_OK != GNUNET_BIO_read (rh, "publish-ns", &ns, sizeof (ns))))) - { - GNUNET_break (0); - goto cleanup; - } + (GNUNET_OK != GNUNET_BIO_read(rh, "publish-ns", &ns, sizeof(ns))))) + { + GNUNET_break(0); + goto cleanup; + } pc->options = options; pc->all_done = all_done; if (NULL == fi_root) - { - GNUNET_break (0); - goto cleanup; - } - pc->fi = deserialize_file_information (h, fi_root); + { + GNUNET_break(0); + goto cleanup; + } + pc->fi = deserialize_file_information(h, fi_root); if (NULL == pc->fi) - { - GNUNET_break (0); - goto cleanup; - } + { + GNUNET_break(0); + goto cleanup; + } if (GNUNET_YES == have_ns) - { - pc->ns = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPrivateKey); - *pc->ns = ns; - } + { + pc->ns = GNUNET_new(struct GNUNET_CRYPTO_EcdsaPrivateKey); + *pc->ns = ns; + } if ((0 == (pc->options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY)) && (GNUNET_YES != pc->all_done)) - { - pc->dsh = GNUNET_DATASTORE_connect (h->cfg); - if (NULL == pc->dsh) - goto cleanup; - } + { + pc->dsh = GNUNET_DATASTORE_connect(h->cfg); + if (NULL == pc->dsh) + goto cleanup; + } if (NULL != fi_pos) - { - pc->fi_pos = find_file_position (pc->fi, fi_pos); - GNUNET_free (fi_pos); - fi_pos = NULL; - if (NULL == pc->fi_pos) - { - /* failed to find position for resuming, outch! Will start from root! */ - GNUNET_break (0); - if (GNUNET_YES != pc->all_done) - pc->fi_pos = pc->fi; - } - } - GNUNET_free (fi_root); + { + pc->fi_pos = find_file_position(pc->fi, fi_pos); + GNUNET_free(fi_pos); + fi_pos = NULL; + if (NULL == pc->fi_pos) + { + /* failed to find position for resuming, outch! Will start from root! */ + GNUNET_break(0); + if (GNUNET_YES != pc->all_done) + pc->fi_pos = pc->fi; + } + } + GNUNET_free(fi_root); fi_root = NULL; /* generate RESUME event(s) */ - GNUNET_FS_file_information_inspect (pc->fi, &fip_signal_resume, pc); + GNUNET_FS_file_information_inspect(pc->fi, &fip_signal_resume, pc); /* re-start publishing (if needed)... */ if (GNUNET_YES != pc->all_done) - { - GNUNET_assert (NULL == pc->upload_task); - pc->upload_task = - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, - &GNUNET_FS_publish_main_, - pc); - } - if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failure while resuming publishing operation `%s': %s\n"), - filename, - emsg); - GNUNET_free (emsg); - } - pc->top = GNUNET_FS_make_top (h, &GNUNET_FS_publish_signal_suspend_, pc); + { + GNUNET_assert(NULL == pc->upload_task); + pc->upload_task = + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_BACKGROUND, + &GNUNET_FS_publish_main_, + pc); + } + if (GNUNET_OK != GNUNET_BIO_read_close(rh, &emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failure while resuming publishing operation `%s': %s\n"), + filename, + emsg); + GNUNET_free(emsg); + } + pc->top = GNUNET_FS_make_top(h, &GNUNET_FS_publish_signal_suspend_, pc); return GNUNET_OK; cleanup: - GNUNET_free_non_null (pc->nid); - GNUNET_free_non_null (pc->nuid); - GNUNET_free_non_null (fi_root); - GNUNET_free_non_null (fi_pos); - if ((NULL != rh) && (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to resume publishing operation `%s': %s\n"), - filename, - emsg); - GNUNET_free (emsg); - } + GNUNET_free_non_null(pc->nid); + GNUNET_free_non_null(pc->nuid); + GNUNET_free_non_null(fi_root); + GNUNET_free_non_null(fi_pos); + if ((NULL != rh) && (GNUNET_OK != GNUNET_BIO_read_close(rh, &emsg))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to resume publishing operation `%s': %s\n"), + filename, + emsg); + GNUNET_free(emsg); + } if (NULL != pc->fi) - GNUNET_FS_file_information_destroy (pc->fi, NULL, NULL); - if (0 != unlink (filename)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", filename); - GNUNET_free (pc->serialization); - GNUNET_free (pc); + GNUNET_FS_file_information_destroy(pc->fi, NULL, NULL); + if (0 != unlink(filename)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", filename); + GNUNET_free(pc->serialization); + GNUNET_free(pc); return GNUNET_OK; } @@ -1688,65 +1702,65 @@ cleanup: * @param pc the struct to sync */ void -GNUNET_FS_publish_sync_ (struct GNUNET_FS_PublishContext *pc) +GNUNET_FS_publish_sync_(struct GNUNET_FS_PublishContext *pc) { struct GNUNET_BIO_WriteHandle *wh; int32_t have_ns; if (NULL == pc->serialization) pc->serialization = - make_serialization_file_name (pc->h, GNUNET_FS_SYNC_PATH_MASTER_PUBLISH); + make_serialization_file_name(pc->h, GNUNET_FS_SYNC_PATH_MASTER_PUBLISH); if (NULL == pc->serialization) return; if (NULL == pc->fi) return; if (NULL == pc->fi->serialization) - { - GNUNET_break (0); - return; - } - wh = get_write_handle (pc->h, - GNUNET_FS_SYNC_PATH_MASTER_PUBLISH, - pc->serialization); + { + GNUNET_break(0); + return; + } + wh = get_write_handle(pc->h, + GNUNET_FS_SYNC_PATH_MASTER_PUBLISH, + pc->serialization); if (NULL == wh) - { - GNUNET_break (0); - goto cleanup; - } + { + GNUNET_break(0); + goto cleanup; + } have_ns = (NULL != pc->ns) ? GNUNET_YES : GNUNET_NO; - if ((GNUNET_OK != GNUNET_BIO_write_string (wh, pc->nid)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, pc->nuid)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, pc->options)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, pc->all_done)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, have_ns)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, pc->fi->serialization)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, - (NULL == pc->fi_pos) - ? NULL - : pc->fi_pos->serialization)) || + if ((GNUNET_OK != GNUNET_BIO_write_string(wh, pc->nid)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, pc->nuid)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, pc->options)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, pc->all_done)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, have_ns)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, pc->fi->serialization)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, + (NULL == pc->fi_pos) + ? NULL + : pc->fi_pos->serialization)) || ((NULL != pc->ns) && (GNUNET_OK != - GNUNET_BIO_write (wh, - pc->ns, - sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))))) - { - GNUNET_break (0); - goto cleanup; - } - if (GNUNET_OK != GNUNET_BIO_write_close (wh)) - { - wh = NULL; - GNUNET_break (0); - goto cleanup; - } + GNUNET_BIO_write(wh, + pc->ns, + sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey))))) + { + GNUNET_break(0); + goto cleanup; + } + if (GNUNET_OK != GNUNET_BIO_write_close(wh)) + { + wh = NULL; + GNUNET_break(0); + goto cleanup; + } return; cleanup: if (NULL != wh) - (void) GNUNET_BIO_write_close (wh); - GNUNET_FS_remove_sync_file_ (pc->h, - GNUNET_FS_SYNC_PATH_MASTER_PUBLISH, - pc->serialization); - GNUNET_free (pc->serialization); + (void)GNUNET_BIO_write_close(wh); + GNUNET_FS_remove_sync_file_(pc->h, + GNUNET_FS_SYNC_PATH_MASTER_PUBLISH, + pc->serialization); + GNUNET_free(pc->serialization); pc->serialization = NULL; } @@ -1760,60 +1774,60 @@ cleanup: * @param uc the struct to sync */ void -GNUNET_FS_unindex_sync_ (struct GNUNET_FS_UnindexContext *uc) +GNUNET_FS_unindex_sync_(struct GNUNET_FS_UnindexContext *uc) { struct GNUNET_BIO_WriteHandle *wh; char *uris; if (NULL == uc->serialization) uc->serialization = - make_serialization_file_name (uc->h, GNUNET_FS_SYNC_PATH_MASTER_UNINDEX); + make_serialization_file_name(uc->h, GNUNET_FS_SYNC_PATH_MASTER_UNINDEX); if (NULL == uc->serialization) return; - wh = get_write_handle (uc->h, - GNUNET_FS_SYNC_PATH_MASTER_UNINDEX, - uc->serialization); + wh = get_write_handle(uc->h, + GNUNET_FS_SYNC_PATH_MASTER_UNINDEX, + uc->serialization); if (NULL == wh) - { - GNUNET_break (0); - goto cleanup; - } + { + GNUNET_break(0); + goto cleanup; + } if (NULL != uc->ksk_uri) - uris = GNUNET_FS_uri_to_string (uc->ksk_uri); + uris = GNUNET_FS_uri_to_string(uc->ksk_uri); else uris = NULL; - if ((GNUNET_OK != GNUNET_BIO_write_string (wh, uc->filename)) || - (GNUNET_OK != GNUNET_BIO_write_int64 (wh, uc->file_size)) || - (GNUNET_OK != write_start_time (wh, uc->start_time)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, (uint32_t) uc->state)) || + if ((GNUNET_OK != GNUNET_BIO_write_string(wh, uc->filename)) || + (GNUNET_OK != GNUNET_BIO_write_int64(wh, uc->file_size)) || + (GNUNET_OK != write_start_time(wh, uc->start_time)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, (uint32_t)uc->state)) || (GNUNET_OK != - GNUNET_BIO_write (wh, &uc->chk, sizeof (struct ContentHashKey))) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, uris)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, (uint32_t) uc->ksk_offset)) || + GNUNET_BIO_write(wh, &uc->chk, sizeof(struct ContentHashKey))) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, uris)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, (uint32_t)uc->ksk_offset)) || ((uc->state == UNINDEX_STATE_FS_NOTIFY) && - (GNUNET_OK != GNUNET_BIO_write (wh, - &uc->file_id, - sizeof (struct GNUNET_HashCode)))) || + (GNUNET_OK != GNUNET_BIO_write(wh, + &uc->file_id, + sizeof(struct GNUNET_HashCode)))) || ((uc->state == UNINDEX_STATE_ERROR) && - (GNUNET_OK != GNUNET_BIO_write_string (wh, uc->emsg)))) - { - GNUNET_break (0); - goto cleanup; - } - if (GNUNET_OK != GNUNET_BIO_write_close (wh)) - { - wh = NULL; - GNUNET_break (0); - goto cleanup; - } + (GNUNET_OK != GNUNET_BIO_write_string(wh, uc->emsg)))) + { + GNUNET_break(0); + goto cleanup; + } + if (GNUNET_OK != GNUNET_BIO_write_close(wh)) + { + wh = NULL; + GNUNET_break(0); + goto cleanup; + } return; cleanup: if (NULL != wh) - (void) GNUNET_BIO_write_close (wh); - GNUNET_FS_remove_sync_file_ (uc->h, - GNUNET_FS_SYNC_PATH_MASTER_UNINDEX, - uc->serialization); - GNUNET_free (uc->serialization); + (void)GNUNET_BIO_write_close(wh); + GNUNET_FS_remove_sync_file_(uc->h, + GNUNET_FS_SYNC_PATH_MASTER_UNINDEX, + uc->serialization); + GNUNET_free(uc->serialization); uc->serialization = NULL; } @@ -1826,22 +1840,22 @@ cleanup: * @return #GNUNET_YES on success, #GNUNET_NO on error */ static int -write_download_request (struct GNUNET_BIO_WriteHandle *wh, - struct DownloadRequest *dr) +write_download_request(struct GNUNET_BIO_WriteHandle *wh, + struct DownloadRequest *dr) { unsigned int i; - if ((GNUNET_OK != GNUNET_BIO_write_int32 (wh, dr->state)) || - (GNUNET_OK != GNUNET_BIO_write_int64 (wh, dr->offset)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, dr->num_children)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, dr->depth))) + if ((GNUNET_OK != GNUNET_BIO_write_int32(wh, dr->state)) || + (GNUNET_OK != GNUNET_BIO_write_int64(wh, dr->offset)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, dr->num_children)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, dr->depth))) return GNUNET_NO; if ((BRS_CHK_SET == dr->state) && (GNUNET_OK != - GNUNET_BIO_write (wh, &dr->chk, sizeof (struct ContentHashKey)))) + GNUNET_BIO_write(wh, &dr->chk, sizeof(struct ContentHashKey)))) return GNUNET_NO; for (i = 0; i < dr->num_children; i++) - if (GNUNET_NO == write_download_request (wh, dr->children[i])) + if (GNUNET_NO == write_download_request(wh, dr->children[i])) return GNUNET_NO; return GNUNET_YES; } @@ -1854,56 +1868,59 @@ write_download_request (struct GNUNET_BIO_WriteHandle *wh, * @return value the download request read from disk, NULL on error */ static struct DownloadRequest * -read_download_request (struct GNUNET_BIO_ReadHandle *rh) +read_download_request(struct GNUNET_BIO_ReadHandle *rh) { struct DownloadRequest *dr; unsigned int i; - dr = GNUNET_new (struct DownloadRequest); - if ((GNUNET_OK != GNUNET_BIO_read_int32 (rh, &dr->state)) || - (GNUNET_OK != GNUNET_BIO_read_int64 (rh, &dr->offset)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &dr->num_children)) || + dr = GNUNET_new(struct DownloadRequest); + if ((GNUNET_OK != GNUNET_BIO_read_int32(rh, &dr->state)) || + (GNUNET_OK != GNUNET_BIO_read_int64(rh, &dr->offset)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &dr->num_children)) || (dr->num_children > CHK_PER_INODE) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &dr->depth)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &dr->depth)) || ((0 == dr->depth) && (dr->num_children > 0)) || ((dr->depth > 0) && (0 == dr->num_children))) - { - GNUNET_break (0); - dr->num_children = 0; - goto cleanup; - } + { + GNUNET_break(0); + dr->num_children = 0; + goto cleanup; + } if (dr->num_children > 0) dr->children = - GNUNET_malloc (dr->num_children * sizeof (struct DownloadRequest *)); + GNUNET_malloc(dr->num_children * sizeof(struct DownloadRequest *)); switch (dr->state) - { - case BRS_INIT: - case BRS_RECONSTRUCT_DOWN: - case BRS_RECONSTRUCT_META_UP: - case BRS_RECONSTRUCT_UP: - break; - case BRS_CHK_SET: - if (GNUNET_OK != - GNUNET_BIO_read (rh, "chk", &dr->chk, sizeof (struct ContentHashKey))) + { + case BRS_INIT: + case BRS_RECONSTRUCT_DOWN: + case BRS_RECONSTRUCT_META_UP: + case BRS_RECONSTRUCT_UP: + break; + + case BRS_CHK_SET: + if (GNUNET_OK != + GNUNET_BIO_read(rh, "chk", &dr->chk, sizeof(struct ContentHashKey))) + goto cleanup; + break; + + case BRS_DOWNLOAD_DOWN: + case BRS_DOWNLOAD_UP: + case BRS_ERROR: + break; + + default: + GNUNET_break(0); goto cleanup; - break; - case BRS_DOWNLOAD_DOWN: - case BRS_DOWNLOAD_UP: - case BRS_ERROR: - break; - default: - GNUNET_break (0); - goto cleanup; - } + } for (i = 0; i < dr->num_children; i++) - { - if (NULL == (dr->children[i] = read_download_request (rh))) - goto cleanup; - dr->children[i]->parent = dr; - } + { + if (NULL == (dr->children[i] = read_download_request(rh))) + goto cleanup; + dr->children[i]->parent = dr; + } return dr; cleanup: - GNUNET_FS_free_download_request_ (dr); + GNUNET_FS_free_download_request_(dr); return NULL; } @@ -1918,26 +1935,26 @@ cleanup: * @return the expanded file name, NULL for none */ static char * -get_download_sync_filename (struct GNUNET_FS_DownloadContext *dc, - const char *uni, - const char *ext) +get_download_sync_filename(struct GNUNET_FS_DownloadContext *dc, + const char *uni, + const char *ext) { char *par; char *epar; if (dc->parent == NULL) - return get_serialization_file_name (dc->h, - (dc->search != NULL) - ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD - : GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD, - uni); + return get_serialization_file_name(dc->h, + (dc->search != NULL) + ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD + : GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD, + uni); if (NULL == dc->parent->serialization) return NULL; - par = get_download_sync_filename (dc->parent, dc->parent->serialization, ""); + par = get_download_sync_filename(dc->parent, dc->parent->serialization, ""); if (NULL == par) return NULL; - GNUNET_asprintf (&epar, "%s.dir%s%s%s", par, DIR_SEPARATOR_STR, uni, ext); - GNUNET_free (par); + GNUNET_asprintf(&epar, "%s.dir%s%s%s", par, DIR_SEPARATOR_STR, uni, ext); + GNUNET_free(par); return epar; } @@ -1951,7 +1968,7 @@ get_download_sync_filename (struct GNUNET_FS_DownloadContext *dc, * @param dc the struct to sync */ void -GNUNET_FS_download_sync_ (struct GNUNET_FS_DownloadContext *dc) +GNUNET_FS_download_sync_(struct GNUNET_FS_DownloadContext *dc) { struct GNUNET_BIO_WriteHandle *wh; char *uris; @@ -1961,87 +1978,87 @@ GNUNET_FS_download_sync_ (struct GNUNET_FS_DownloadContext *dc) if (0 != (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE)) return; /* we don't sync probes */ if (NULL == dc->serialization) - { - dir = get_download_sync_filename (dc, "", ""); - if (NULL == dir) - return; - if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (dir)) { - GNUNET_free (dir); - return; + dir = get_download_sync_filename(dc, "", ""); + if (NULL == dir) + return; + if (GNUNET_OK != GNUNET_DISK_directory_create_for_file(dir)) + { + GNUNET_free(dir); + return; + } + fn = GNUNET_DISK_mktemp(dir); + GNUNET_free(dir); + if (NULL == fn) + return; + dc->serialization = get_serialization_short_name(fn); } - fn = GNUNET_DISK_mktemp (dir); - GNUNET_free (dir); - if (NULL == fn) - return; - dc->serialization = get_serialization_short_name (fn); - } else - { - fn = get_download_sync_filename (dc, dc->serialization, ""); - if (NULL == fn) { - GNUNET_free (dc->serialization); + fn = get_download_sync_filename(dc, dc->serialization, ""); + if (NULL == fn) + { + GNUNET_free(dc->serialization); + dc->serialization = NULL; + GNUNET_free(fn); + return; + } + } + wh = GNUNET_BIO_write_open(fn); + if (NULL == wh) + { + GNUNET_free(dc->serialization); dc->serialization = NULL; - GNUNET_free (fn); + GNUNET_free(fn); return; } - } - wh = GNUNET_BIO_write_open (fn); - if (NULL == wh) - { - GNUNET_free (dc->serialization); - dc->serialization = NULL; - GNUNET_free (fn); - return; - } - GNUNET_assert ((GNUNET_YES == GNUNET_FS_uri_test_chk (dc->uri)) || - (GNUNET_YES == GNUNET_FS_uri_test_loc (dc->uri))); - uris = GNUNET_FS_uri_to_string (dc->uri); - if ((GNUNET_OK != GNUNET_BIO_write_string (wh, uris)) || - (GNUNET_OK != GNUNET_BIO_write_meta_data (wh, dc->meta)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, dc->emsg)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, dc->filename)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, dc->temp_filename)) || - (GNUNET_OK != GNUNET_BIO_write_int64 (wh, dc->old_file_size)) || - (GNUNET_OK != GNUNET_BIO_write_int64 (wh, dc->offset)) || - (GNUNET_OK != GNUNET_BIO_write_int64 (wh, dc->length)) || - (GNUNET_OK != GNUNET_BIO_write_int64 (wh, dc->completed)) || - (GNUNET_OK != write_start_time (wh, dc->start_time)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, dc->anonymity)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, (uint32_t) dc->options)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, (uint32_t) dc->has_finished))) - { - GNUNET_break (0); - goto cleanup; - } - if (NULL == dc->emsg) - { - GNUNET_assert (dc->top_request != NULL); - if (GNUNET_YES != write_download_request (wh, dc->top_request)) + GNUNET_assert((GNUNET_YES == GNUNET_FS_uri_test_chk(dc->uri)) || + (GNUNET_YES == GNUNET_FS_uri_test_loc(dc->uri))); + uris = GNUNET_FS_uri_to_string(dc->uri); + if ((GNUNET_OK != GNUNET_BIO_write_string(wh, uris)) || + (GNUNET_OK != GNUNET_BIO_write_meta_data(wh, dc->meta)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, dc->emsg)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, dc->filename)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, dc->temp_filename)) || + (GNUNET_OK != GNUNET_BIO_write_int64(wh, dc->old_file_size)) || + (GNUNET_OK != GNUNET_BIO_write_int64(wh, dc->offset)) || + (GNUNET_OK != GNUNET_BIO_write_int64(wh, dc->length)) || + (GNUNET_OK != GNUNET_BIO_write_int64(wh, dc->completed)) || + (GNUNET_OK != write_start_time(wh, dc->start_time)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, dc->anonymity)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, (uint32_t)dc->options)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, (uint32_t)dc->has_finished))) { - GNUNET_break (0); + GNUNET_break(0); goto cleanup; } - } - GNUNET_free_non_null (uris); + if (NULL == dc->emsg) + { + GNUNET_assert(dc->top_request != NULL); + if (GNUNET_YES != write_download_request(wh, dc->top_request)) + { + GNUNET_break(0); + goto cleanup; + } + } + GNUNET_free_non_null(uris); uris = NULL; - if (GNUNET_OK != GNUNET_BIO_write_close (wh)) - { - wh = NULL; - GNUNET_break (0); - goto cleanup; - } - GNUNET_free (fn); + if (GNUNET_OK != GNUNET_BIO_write_close(wh)) + { + wh = NULL; + GNUNET_break(0); + goto cleanup; + } + GNUNET_free(fn); return; cleanup: if (NULL != wh) - (void) GNUNET_BIO_write_close (wh); - GNUNET_free_non_null (uris); - if (0 != unlink (fn)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn); - GNUNET_free (fn); - GNUNET_free (dc->serialization); + (void)GNUNET_BIO_write_close(wh); + GNUNET_free_non_null(uris); + if (0 != unlink(fn)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", fn); + GNUNET_free(fn); + GNUNET_free(dc->serialization); dc->serialization = NULL; } @@ -2055,7 +2072,7 @@ cleanup: * @param sr the struct to sync */ void -GNUNET_FS_search_result_sync_ (struct GNUNET_FS_SearchResult *sr) +GNUNET_FS_search_result_sync_(struct GNUNET_FS_SearchResult *sr) { struct GNUNET_BIO_WriteHandle *wh; char *uris; @@ -2065,74 +2082,74 @@ GNUNET_FS_search_result_sync_ (struct GNUNET_FS_SearchResult *sr) uris = NULL; if (NULL == sr->serialization) sr->serialization = - make_serialization_file_name_in_dir (sr->h, - (sr->sc->psearch_result == NULL) - ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH - : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, - sr->sc->serialization); + make_serialization_file_name_in_dir(sr->h, + (sr->sc->psearch_result == NULL) + ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH + : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, + sr->sc->serialization); if (NULL == sr->serialization) return; - wh = get_write_handle_in_dir (sr->h, - (sr->sc->psearch_result == NULL) - ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH - : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, - sr->sc->serialization, - sr->serialization); + wh = get_write_handle_in_dir(sr->h, + (sr->sc->psearch_result == NULL) + ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH + : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, + sr->sc->serialization, + sr->serialization); if (NULL == wh) - { - GNUNET_break (0); - goto cleanup; - } - uris = GNUNET_FS_uri_to_string (sr->uri); - if ((GNUNET_OK != GNUNET_BIO_write_string (wh, uris)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, - sr->download != NULL - ? sr->download->serialization - : NULL)) || + { + GNUNET_break(0); + goto cleanup; + } + uris = GNUNET_FS_uri_to_string(sr->uri); + if ((GNUNET_OK != GNUNET_BIO_write_string(wh, uris)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, + sr->download != NULL + ? sr->download->serialization + : NULL)) || (GNUNET_OK != - GNUNET_BIO_write_string (wh, - sr->update_search != NULL - ? sr->update_search->serialization - : NULL)) || - (GNUNET_OK != GNUNET_BIO_write_meta_data (wh, sr->meta)) || + GNUNET_BIO_write_string(wh, + sr->update_search != NULL + ? sr->update_search->serialization + : NULL)) || + (GNUNET_OK != GNUNET_BIO_write_meta_data(wh, sr->meta)) || (GNUNET_OK != - GNUNET_BIO_write (wh, &sr->key, sizeof (struct GNUNET_HashCode))) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, sr->mandatory_missing)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, sr->optional_support)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, sr->availability_success)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, sr->availability_trials))) - { - GNUNET_break (0); - goto cleanup; - } + GNUNET_BIO_write(wh, &sr->key, sizeof(struct GNUNET_HashCode))) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, sr->mandatory_missing)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, sr->optional_support)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, sr->availability_success)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, sr->availability_trials))) + { + GNUNET_break(0); + goto cleanup; + } if ((NULL != sr->uri) && (GNUNET_FS_URI_KSK == sr->sc->uri->type) && (GNUNET_OK != - GNUNET_BIO_write (wh, - sr->keyword_bitmap, - (sr->sc->uri->data.ksk.keywordCount + 7) / 8))) - { - GNUNET_break (0); - goto cleanup; - } - if (GNUNET_OK != GNUNET_BIO_write_close (wh)) - { - wh = NULL; - GNUNET_break (0); - goto cleanup; - } - GNUNET_free_non_null (uris); + GNUNET_BIO_write(wh, + sr->keyword_bitmap, + (sr->sc->uri->data.ksk.keywordCount + 7) / 8))) + { + GNUNET_break(0); + goto cleanup; + } + if (GNUNET_OK != GNUNET_BIO_write_close(wh)) + { + wh = NULL; + GNUNET_break(0); + goto cleanup; + } + GNUNET_free_non_null(uris); return; cleanup: - GNUNET_free_non_null (uris); + GNUNET_free_non_null(uris); if (NULL != wh) - (void) GNUNET_BIO_write_close (wh); - remove_sync_file_in_dir (sr->h, - (NULL == sr->sc->psearch_result) - ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH - : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, - sr->sc->serialization, - sr->serialization); - GNUNET_free (sr->serialization); + (void)GNUNET_BIO_write_close(wh); + remove_sync_file_in_dir(sr->h, + (NULL == sr->sc->psearch_result) + ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH + : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, + sr->sc->serialization, + sr->serialization); + GNUNET_free(sr->serialization); sr->serialization = NULL; } @@ -2146,7 +2163,7 @@ cleanup: * @param sc the struct to sync */ void -GNUNET_FS_search_sync_ (struct GNUNET_FS_SearchContext *sc) +GNUNET_FS_search_sync_(struct GNUNET_FS_SearchContext *sc) { struct GNUNET_BIO_WriteHandle *wh; char *uris; @@ -2154,47 +2171,47 @@ GNUNET_FS_search_sync_ (struct GNUNET_FS_SearchContext *sc) const char *category; category = (NULL == sc->psearch_result) ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH - : GNUNET_FS_SYNC_PATH_CHILD_SEARCH; + : GNUNET_FS_SYNC_PATH_CHILD_SEARCH; if (NULL == sc->serialization) - sc->serialization = make_serialization_file_name (sc->h, category); + sc->serialization = make_serialization_file_name(sc->h, category); if (NULL == sc->serialization) return; uris = NULL; - wh = get_write_handle (sc->h, category, sc->serialization); + wh = get_write_handle(sc->h, category, sc->serialization); if (NULL == wh) - { - GNUNET_break (0); - goto cleanup; - } - GNUNET_assert ((GNUNET_YES == GNUNET_FS_uri_test_ksk (sc->uri)) || - (GNUNET_YES == GNUNET_FS_uri_test_sks (sc->uri))); - uris = GNUNET_FS_uri_to_string (sc->uri); + { + GNUNET_break(0); + goto cleanup; + } + GNUNET_assert((GNUNET_YES == GNUNET_FS_uri_test_ksk(sc->uri)) || + (GNUNET_YES == GNUNET_FS_uri_test_sks(sc->uri))); + uris = GNUNET_FS_uri_to_string(sc->uri); in_pause = (sc->task != NULL) ? 'r' : '\0'; - if ((GNUNET_OK != GNUNET_BIO_write_string (wh, uris)) || - (GNUNET_OK != write_start_time (wh, sc->start_time)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, sc->emsg)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, (uint32_t) sc->options)) || - (GNUNET_OK != GNUNET_BIO_write (wh, &in_pause, sizeof (in_pause))) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, sc->anonymity))) - { - GNUNET_break (0); - goto cleanup; - } - GNUNET_free (uris); + if ((GNUNET_OK != GNUNET_BIO_write_string(wh, uris)) || + (GNUNET_OK != write_start_time(wh, sc->start_time)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, sc->emsg)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, (uint32_t)sc->options)) || + (GNUNET_OK != GNUNET_BIO_write(wh, &in_pause, sizeof(in_pause))) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, sc->anonymity))) + { + GNUNET_break(0); + goto cleanup; + } + GNUNET_free(uris); uris = NULL; - if (GNUNET_OK != GNUNET_BIO_write_close (wh)) - { - wh = NULL; - GNUNET_break (0); - goto cleanup; - } + if (GNUNET_OK != GNUNET_BIO_write_close(wh)) + { + wh = NULL; + GNUNET_break(0); + goto cleanup; + } return; cleanup: if (NULL != wh) - (void) GNUNET_BIO_write_close (wh); - GNUNET_free_non_null (uris); - GNUNET_FS_remove_sync_file_ (sc->h, category, sc->serialization); - GNUNET_free (sc->serialization); + (void)GNUNET_BIO_write_close(wh); + GNUNET_free_non_null(uris); + GNUNET_FS_remove_sync_file_(sc->h, category, sc->serialization); + GNUNET_free(sc->serialization); sc->serialization = NULL; } @@ -2208,7 +2225,7 @@ cleanup: * @return #GNUNET_OK (continue to iterate) */ static int -deserialize_unindex_file (void *cls, const char *filename) +deserialize_unindex_file(void *cls, const char *filename) { struct GNUNET_FS_Handle *h = cls; struct GNUNET_BIO_ReadHandle *rh; @@ -2218,144 +2235,155 @@ deserialize_unindex_file (void *cls, const char *filename) char *uris; uint32_t state; - uc = GNUNET_new (struct GNUNET_FS_UnindexContext); + uc = GNUNET_new(struct GNUNET_FS_UnindexContext); uc->h = h; - uc->serialization = get_serialization_short_name (filename); - rh = GNUNET_BIO_read_open (filename); + uc->serialization = get_serialization_short_name(filename); + rh = GNUNET_BIO_read_open(filename); if (NULL == rh) - { - GNUNET_break (0); - goto cleanup; - } + { + GNUNET_break(0); + goto cleanup; + } uris = NULL; if ((GNUNET_OK != - GNUNET_BIO_read_string (rh, "unindex-fn", &uc->filename, 10 * 1024)) || - (GNUNET_OK != GNUNET_BIO_read_int64 (rh, &uc->file_size)) || - (GNUNET_OK != read_start_time (rh, &uc->start_time)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &state)) || + GNUNET_BIO_read_string(rh, "unindex-fn", &uc->filename, 10 * 1024)) || + (GNUNET_OK != GNUNET_BIO_read_int64(rh, &uc->file_size)) || + (GNUNET_OK != read_start_time(rh, &uc->start_time)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &state)) || (GNUNET_OK != - GNUNET_BIO_read (rh, "uri", &uc->chk, sizeof (struct ContentHashKey))) || + GNUNET_BIO_read(rh, "uri", &uc->chk, sizeof(struct ContentHashKey))) || (GNUNET_OK != - GNUNET_BIO_read_string (rh, "unindex-kskuri", &uris, 10 * 1024)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &uc->ksk_offset))) - { - GNUNET_free_non_null (uris); - GNUNET_break (0); - goto cleanup; - } - if (NULL != uris) - { - uc->ksk_uri = GNUNET_FS_uri_parse (uris, &emsg); - GNUNET_free (uris); - if (NULL == uc->ksk_uri) + GNUNET_BIO_read_string(rh, "unindex-kskuri", &uris, 10 * 1024)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &uc->ksk_offset))) { - GNUNET_break (0); - GNUNET_free_non_null (emsg); + GNUNET_free_non_null(uris); + GNUNET_break(0); goto cleanup; } - } + if (NULL != uris) + { + uc->ksk_uri = GNUNET_FS_uri_parse(uris, &emsg); + GNUNET_free(uris); + if (NULL == uc->ksk_uri) + { + GNUNET_break(0); + GNUNET_free_non_null(emsg); + goto cleanup; + } + } if ((uc->ksk_offset > 0) && ((NULL == uc->ksk_uri) || (uc->ksk_offset > uc->ksk_uri->data.ksk.keywordCount))) - { - GNUNET_break (0); - goto cleanup; - } - uc->state = (enum UnindexState) state; - switch (state) - { - case UNINDEX_STATE_HASHING: - break; - case UNINDEX_STATE_FS_NOTIFY: - if (GNUNET_OK != GNUNET_BIO_read (rh, - "unindex-hash", - &uc->file_id, - sizeof (struct GNUNET_HashCode))) { - GNUNET_break (0); + GNUNET_break(0); goto cleanup; } - break; - case UNINDEX_STATE_DS_REMOVE: - case UNINDEX_STATE_EXTRACT_KEYWORDS: - case UNINDEX_STATE_DS_REMOVE_KBLOCKS: - break; - case UNINDEX_STATE_COMPLETE: - break; - case UNINDEX_STATE_ERROR: - if (GNUNET_OK != - GNUNET_BIO_read_string (rh, "unindex-emsg", &uc->emsg, 10 * 1024)) - { - GNUNET_break (0); + uc->state = (enum UnindexState)state; + switch (state) + { + case UNINDEX_STATE_HASHING: + break; + + case UNINDEX_STATE_FS_NOTIFY: + if (GNUNET_OK != GNUNET_BIO_read(rh, + "unindex-hash", + &uc->file_id, + sizeof(struct GNUNET_HashCode))) + { + GNUNET_break(0); + goto cleanup; + } + break; + + case UNINDEX_STATE_DS_REMOVE: + case UNINDEX_STATE_EXTRACT_KEYWORDS: + case UNINDEX_STATE_DS_REMOVE_KBLOCKS: + break; + + case UNINDEX_STATE_COMPLETE: + break; + + case UNINDEX_STATE_ERROR: + if (GNUNET_OK != + GNUNET_BIO_read_string(rh, "unindex-emsg", &uc->emsg, 10 * 1024)) + { + GNUNET_break(0); + goto cleanup; + } + break; + + default: + GNUNET_break(0); goto cleanup; } - break; - default: - GNUNET_break (0); - goto cleanup; - } - uc->top = GNUNET_FS_make_top (h, &GNUNET_FS_unindex_signal_suspend_, uc); + uc->top = GNUNET_FS_make_top(h, &GNUNET_FS_unindex_signal_suspend_, uc); pi.status = GNUNET_FS_STATUS_UNINDEX_RESUME; pi.value.unindex.specifics.resume.message = uc->emsg; - GNUNET_FS_unindex_make_status_ (&pi, - uc, - (uc->state == UNINDEX_STATE_COMPLETE) - ? uc->file_size - : 0); + GNUNET_FS_unindex_make_status_(&pi, + uc, + (uc->state == UNINDEX_STATE_COMPLETE) + ? uc->file_size + : 0); switch (uc->state) - { - case UNINDEX_STATE_HASHING: - uc->fhc = GNUNET_CRYPTO_hash_file (GNUNET_SCHEDULER_PRIORITY_IDLE, - uc->filename, - HASHING_BLOCKSIZE, - &GNUNET_FS_unindex_process_hash_, - uc); - break; - case UNINDEX_STATE_FS_NOTIFY: - uc->state = UNINDEX_STATE_HASHING; - GNUNET_FS_unindex_process_hash_ (uc, &uc->file_id); - break; - case UNINDEX_STATE_DS_REMOVE: - GNUNET_FS_unindex_do_remove_ (uc); - break; - case UNINDEX_STATE_EXTRACT_KEYWORDS: - GNUNET_FS_unindex_do_extract_keywords_ (uc); - break; - case UNINDEX_STATE_DS_REMOVE_KBLOCKS: - GNUNET_FS_unindex_do_remove_kblocks_ (uc); - break; - case UNINDEX_STATE_COMPLETE: - case UNINDEX_STATE_ERROR: - /* no need to resume any operation, we were done */ - break; - default: - break; - } - if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failure while resuming unindexing operation `%s': %s\n"), - filename, - emsg); - GNUNET_free (emsg); - } + { + case UNINDEX_STATE_HASHING: + uc->fhc = GNUNET_CRYPTO_hash_file(GNUNET_SCHEDULER_PRIORITY_IDLE, + uc->filename, + HASHING_BLOCKSIZE, + &GNUNET_FS_unindex_process_hash_, + uc); + break; + + case UNINDEX_STATE_FS_NOTIFY: + uc->state = UNINDEX_STATE_HASHING; + GNUNET_FS_unindex_process_hash_(uc, &uc->file_id); + break; + + case UNINDEX_STATE_DS_REMOVE: + GNUNET_FS_unindex_do_remove_(uc); + break; + + case UNINDEX_STATE_EXTRACT_KEYWORDS: + GNUNET_FS_unindex_do_extract_keywords_(uc); + break; + + case UNINDEX_STATE_DS_REMOVE_KBLOCKS: + GNUNET_FS_unindex_do_remove_kblocks_(uc); + break; + + case UNINDEX_STATE_COMPLETE: + case UNINDEX_STATE_ERROR: + /* no need to resume any operation, we were done */ + break; + + default: + break; + } + if (GNUNET_OK != GNUNET_BIO_read_close(rh, &emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failure while resuming unindexing operation `%s': %s\n"), + filename, + emsg); + GNUNET_free(emsg); + } return GNUNET_OK; cleanup: - GNUNET_free_non_null (uc->filename); - if ((NULL != rh) && (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to resume unindexing operation `%s': %s\n"), - filename, - emsg); - GNUNET_free (emsg); - } + GNUNET_free_non_null(uc->filename); + if ((NULL != rh) && (GNUNET_OK != GNUNET_BIO_read_close(rh, &emsg))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to resume unindexing operation `%s': %s\n"), + filename, + emsg); + GNUNET_free(emsg); + } if (NULL != uc->serialization) - GNUNET_FS_remove_sync_file_ (h, - GNUNET_FS_SYNC_PATH_MASTER_UNINDEX, - uc->serialization); - GNUNET_free_non_null (uc->serialization); - GNUNET_free (uc); + GNUNET_FS_remove_sync_file_(h, + GNUNET_FS_SYNC_PATH_MASTER_UNINDEX, + uc->serialization); + GNUNET_free_non_null(uc->serialization); + GNUNET_free(uc); return GNUNET_OK; } @@ -2370,11 +2398,11 @@ cleanup: * @param serialization name under which the search was serialized */ static void -deserialize_download (struct GNUNET_FS_Handle *h, - struct GNUNET_BIO_ReadHandle *rh, - struct GNUNET_FS_DownloadContext *parent, - struct GNUNET_FS_SearchResult *search, - const char *serialization); +deserialize_download(struct GNUNET_FS_Handle *h, + struct GNUNET_BIO_ReadHandle *rh, + struct GNUNET_FS_DownloadContext *parent, + struct GNUNET_FS_SearchResult *search, + const char *serialization); /** @@ -2386,10 +2414,10 @@ deserialize_download (struct GNUNET_FS_Handle *h, * @param serialization name under which the search was serialized */ static struct GNUNET_FS_SearchContext * -deserialize_search (struct GNUNET_FS_Handle *h, - struct GNUNET_BIO_ReadHandle *rh, - struct GNUNET_FS_SearchResult *psearch_result, - const char *serialization); +deserialize_search(struct GNUNET_FS_Handle *h, + struct GNUNET_BIO_ReadHandle *rh, + struct GNUNET_FS_SearchResult *psearch_result, + const char *serialization); /** @@ -2401,7 +2429,7 @@ deserialize_search (struct GNUNET_FS_Handle *h, * @return #GNUNET_OK (continue to iterate) */ static int -deserialize_search_result (void *cls, const char *filename) +deserialize_search_result(void *cls, const char *filename) { struct GNUNET_FS_SearchContext *sc = cls; char *ser; @@ -2413,133 +2441,133 @@ deserialize_search_result (void *cls, const char *filename) struct GNUNET_BIO_ReadHandle *drh; struct GNUNET_FS_SearchResult *sr; - ser = get_serialization_short_name (filename); - rh = GNUNET_BIO_read_open (filename); + ser = get_serialization_short_name(filename); + rh = GNUNET_BIO_read_open(filename); if (NULL == rh) - { - if (NULL != ser) { - remove_sync_file_in_dir (sc->h, - (NULL == sc->psearch_result) - ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH - : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, - sc->serialization, - ser); - GNUNET_free (ser); + if (NULL != ser) + { + remove_sync_file_in_dir(sc->h, + (NULL == sc->psearch_result) + ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH + : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, + sc->serialization, + ser); + GNUNET_free(ser); + } + return GNUNET_OK; } - return GNUNET_OK; - } emsg = NULL; uris = NULL; download = NULL; update_srch = NULL; - sr = GNUNET_new (struct GNUNET_FS_SearchResult); + sr = GNUNET_new(struct GNUNET_FS_SearchResult); sr->h = sc->h; sr->sc = sc; sr->serialization = ser; if ((GNUNET_OK != - GNUNET_BIO_read_string (rh, "result-uri", &uris, 10 * 1024)) || - (NULL == (sr->uri = GNUNET_FS_uri_parse (uris, &emsg))) || + GNUNET_BIO_read_string(rh, "result-uri", &uris, 10 * 1024)) || + (NULL == (sr->uri = GNUNET_FS_uri_parse(uris, &emsg))) || (GNUNET_OK != - GNUNET_BIO_read_string (rh, "download-lnk", &download, 16)) || + GNUNET_BIO_read_string(rh, "download-lnk", &download, 16)) || (GNUNET_OK != - GNUNET_BIO_read_string (rh, "search-lnk", &update_srch, 16)) || - (GNUNET_OK != GNUNET_BIO_read_meta_data (rh, "result-meta", &sr->meta)) || - (GNUNET_OK != GNUNET_BIO_read (rh, - "result-key", - &sr->key, - sizeof (struct GNUNET_HashCode))) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &sr->mandatory_missing)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &sr->optional_support)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &sr->availability_success)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &sr->availability_trials))) - { - GNUNET_break (0); - goto cleanup; - } - if (GNUNET_FS_URI_KSK == sr->sc->uri->type) - { - sr->keyword_bitmap = GNUNET_malloc ( - (sr->sc->uri->data.ksk.keywordCount + 7) / 8); /* round up, count bits */ - if (GNUNET_OK != - GNUNET_BIO_read (rh, - "keyword-bitmap", - sr->keyword_bitmap, - (sr->sc->uri->data.ksk.keywordCount + 7) / 8)) - { - GNUNET_break (0); + GNUNET_BIO_read_string(rh, "search-lnk", &update_srch, 16)) || + (GNUNET_OK != GNUNET_BIO_read_meta_data(rh, "result-meta", &sr->meta)) || + (GNUNET_OK != GNUNET_BIO_read(rh, + "result-key", + &sr->key, + sizeof(struct GNUNET_HashCode))) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &sr->mandatory_missing)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &sr->optional_support)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &sr->availability_success)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &sr->availability_trials))) + { + GNUNET_break(0); goto cleanup; } - } - GNUNET_free (uris); + if (GNUNET_FS_URI_KSK == sr->sc->uri->type) + { + sr->keyword_bitmap = GNUNET_malloc( + (sr->sc->uri->data.ksk.keywordCount + 7) / 8); /* round up, count bits */ + if (GNUNET_OK != + GNUNET_BIO_read(rh, + "keyword-bitmap", + sr->keyword_bitmap, + (sr->sc->uri->data.ksk.keywordCount + 7) / 8)) + { + GNUNET_break(0); + goto cleanup; + } + } + GNUNET_free(uris); if (NULL != download) - { - drh = get_read_handle (sc->h, GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD, download); - if (NULL != drh) - { - deserialize_download (sc->h, drh, NULL, sr, download); - if (GNUNET_OK != GNUNET_BIO_read_close (drh, &emsg)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to resume sub-download `%s': %s\n"), - download, - emsg); - GNUNET_free (emsg); - } - } - GNUNET_free (download); - } + { + drh = get_read_handle(sc->h, GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD, download); + if (NULL != drh) + { + deserialize_download(sc->h, drh, NULL, sr, download); + if (GNUNET_OK != GNUNET_BIO_read_close(drh, &emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to resume sub-download `%s': %s\n"), + download, + emsg); + GNUNET_free(emsg); + } + } + GNUNET_free(download); + } if (NULL != update_srch) - { - drh = - get_read_handle (sc->h, GNUNET_FS_SYNC_PATH_CHILD_SEARCH, update_srch); - if (NULL != drh) - { - deserialize_search (sc->h, drh, sr, update_srch); - if (GNUNET_OK != GNUNET_BIO_read_close (drh, &emsg)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to resume sub-search `%s': %s\n"), - update_srch, - emsg); - GNUNET_free (emsg); - } - } - GNUNET_free (update_srch); - } - GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_multihashmap_put ( - sc->master_result_map, - &sr->key, - sr, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); - if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failure while resuming search operation `%s': %s\n"), - filename, - emsg); - GNUNET_free (emsg); - } + { + drh = + get_read_handle(sc->h, GNUNET_FS_SYNC_PATH_CHILD_SEARCH, update_srch); + if (NULL != drh) + { + deserialize_search(sc->h, drh, sr, update_srch); + if (GNUNET_OK != GNUNET_BIO_read_close(drh, &emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to resume sub-search `%s': %s\n"), + update_srch, + emsg); + GNUNET_free(emsg); + } + } + GNUNET_free(update_srch); + } + GNUNET_break(GNUNET_YES == GNUNET_CONTAINER_multihashmap_put( + sc->master_result_map, + &sr->key, + sr, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); + if (GNUNET_OK != GNUNET_BIO_read_close(rh, &emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failure while resuming search operation `%s': %s\n"), + filename, + emsg); + GNUNET_free(emsg); + } return GNUNET_OK; cleanup: - GNUNET_free_non_null (download); - GNUNET_free_non_null (emsg); - GNUNET_free_non_null (uris); - GNUNET_free_non_null (update_srch); + GNUNET_free_non_null(download); + GNUNET_free_non_null(emsg); + GNUNET_free_non_null(uris); + GNUNET_free_non_null(update_srch); if (NULL != sr->uri) - GNUNET_FS_uri_destroy (sr->uri); + GNUNET_FS_uri_destroy(sr->uri); if (NULL != sr->meta) - GNUNET_CONTAINER_meta_data_destroy (sr->meta); - GNUNET_free (sr->serialization); - GNUNET_free (sr); - if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failure while resuming search operation `%s': %s\n"), - filename, - emsg); - GNUNET_free (emsg); - } + GNUNET_CONTAINER_meta_data_destroy(sr->meta); + GNUNET_free(sr->serialization); + GNUNET_free(sr); + if (GNUNET_OK != GNUNET_BIO_read_close(rh, &emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failure while resuming search operation `%s': %s\n"), + filename, + emsg); + GNUNET_free(emsg); + } return GNUNET_OK; } @@ -2553,7 +2581,7 @@ cleanup: * @param dc download to resume */ static void -signal_download_resume (struct GNUNET_FS_DownloadContext *dc) +signal_download_resume(struct GNUNET_FS_DownloadContext *dc) { struct GNUNET_FS_DownloadContext *dcc; struct GNUNET_FS_ProgressInfo pi; @@ -2561,13 +2589,13 @@ signal_download_resume (struct GNUNET_FS_DownloadContext *dc) pi.status = GNUNET_FS_STATUS_DOWNLOAD_RESUME; pi.value.download.specifics.resume.meta = dc->meta; pi.value.download.specifics.resume.message = dc->emsg; - GNUNET_FS_download_make_status_ (&pi, dc); + GNUNET_FS_download_make_status_(&pi, dc); dcc = dc->child_head; while (NULL != dcc) - { - signal_download_resume (dcc); - dcc = dcc->next; - } + { + signal_download_resume(dcc); + dcc = dcc->next; + } } @@ -2578,7 +2606,7 @@ signal_download_resume (struct GNUNET_FS_DownloadContext *dc) * @param sc search being resumed */ static void -signal_search_resume (struct GNUNET_FS_SearchContext *sc); +signal_search_resume(struct GNUNET_FS_SearchContext *sc); /** @@ -2591,36 +2619,36 @@ signal_search_resume (struct GNUNET_FS_SearchContext *sc); * @return #GNUNET_YES (we should continue to iterate) */ static int -signal_result_resume (void *cls, const struct GNUNET_HashCode *key, void *value) +signal_result_resume(void *cls, const struct GNUNET_HashCode *key, void *value) { struct GNUNET_FS_SearchContext *sc = cls; struct GNUNET_FS_ProgressInfo pi; struct GNUNET_FS_SearchResult *sr = value; if (0 == sr->mandatory_missing) - { - pi.status = GNUNET_FS_STATUS_SEARCH_RESUME_RESULT; - pi.value.search.specifics.resume_result.meta = sr->meta; - pi.value.search.specifics.resume_result.uri = sr->uri; - pi.value.search.specifics.resume_result.result = sr; - pi.value.search.specifics.resume_result.availability_rank = - 2 * sr->availability_success - sr->availability_trials; - pi.value.search.specifics.resume_result.availability_certainty = - sr->availability_trials; - pi.value.search.specifics.resume_result.applicability_rank = - sr->optional_support; - sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc); - } + { + pi.status = GNUNET_FS_STATUS_SEARCH_RESUME_RESULT; + pi.value.search.specifics.resume_result.meta = sr->meta; + pi.value.search.specifics.resume_result.uri = sr->uri; + pi.value.search.specifics.resume_result.result = sr; + pi.value.search.specifics.resume_result.availability_rank = + 2 * sr->availability_success - sr->availability_trials; + pi.value.search.specifics.resume_result.availability_certainty = + sr->availability_trials; + pi.value.search.specifics.resume_result.applicability_rank = + sr->optional_support; + sr->client_info = GNUNET_FS_search_make_status_(&pi, sc->h, sc); + } if (NULL != sr->download) - { - signal_download_resume (sr->download); - } + { + signal_download_resume(sr->download); + } else - { - GNUNET_FS_search_start_probe_ (sr); - } + { + GNUNET_FS_search_start_probe_(sr); + } if (NULL != sr->update_search) - signal_search_resume (sr->update_search); + signal_search_resume(sr->update_search); return GNUNET_YES; } @@ -2631,7 +2659,7 @@ signal_result_resume (void *cls, const struct GNUNET_HashCode *key, void *value) * @param sc search context to free */ static void -free_search_context (struct GNUNET_FS_SearchContext *sc); +free_search_context(struct GNUNET_FS_SearchContext *sc); /** @@ -2643,18 +2671,18 @@ free_search_context (struct GNUNET_FS_SearchContext *sc); * @return #GNUNET_YES (we should continue to iterate) */ static int -free_result (void *cls, const struct GNUNET_HashCode *key, void *value) +free_result(void *cls, const struct GNUNET_HashCode *key, void *value) { struct GNUNET_FS_SearchResult *sr = value; if (NULL != sr->update_search) - { - free_search_context (sr->update_search); - GNUNET_assert (NULL == sr->update_search); - } - GNUNET_CONTAINER_meta_data_destroy (sr->meta); - GNUNET_FS_uri_destroy (sr->uri); - GNUNET_free (sr); + { + free_search_context(sr->update_search); + GNUNET_assert(NULL == sr->update_search); + } + GNUNET_CONTAINER_meta_data_destroy(sr->meta); + GNUNET_FS_uri_destroy(sr->uri); + GNUNET_free(sr); return GNUNET_YES; } @@ -2665,33 +2693,33 @@ free_result (void *cls, const struct GNUNET_HashCode *key, void *value) * @param sc search context to free */ static void -free_search_context (struct GNUNET_FS_SearchContext *sc) +free_search_context(struct GNUNET_FS_SearchContext *sc) { if (NULL != sc->serialization) - { - GNUNET_FS_remove_sync_file_ (sc->h, - (sc->psearch_result == NULL) - ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH - : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, - sc->serialization); - GNUNET_FS_remove_sync_dir_ (sc->h, - (sc->psearch_result == NULL) + { + GNUNET_FS_remove_sync_file_(sc->h, + (sc->psearch_result == NULL) ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, - sc->serialization); - } - GNUNET_free_non_null (sc->serialization); - GNUNET_free_non_null (sc->emsg); + sc->serialization); + GNUNET_FS_remove_sync_dir_(sc->h, + (sc->psearch_result == NULL) + ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH + : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, + sc->serialization); + } + GNUNET_free_non_null(sc->serialization); + GNUNET_free_non_null(sc->emsg); if (NULL != sc->uri) - GNUNET_FS_uri_destroy (sc->uri); + GNUNET_FS_uri_destroy(sc->uri); if (NULL != sc->master_result_map) - { - GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map, - &free_result, - sc); - GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map); - } - GNUNET_free (sc); + { + GNUNET_CONTAINER_multihashmap_iterate(sc->master_result_map, + &free_result, + sc); + GNUNET_CONTAINER_multihashmap_destroy(sc->master_result_map); + } + GNUNET_free(sc); } @@ -2704,35 +2732,35 @@ free_search_context (struct GNUNET_FS_SearchContext *sc) * @return #GNUNET_OK (continue to iterate) */ static int -deserialize_subdownload (void *cls, const char *filename) +deserialize_subdownload(void *cls, const char *filename) { struct GNUNET_FS_DownloadContext *parent = cls; char *ser; char *emsg; struct GNUNET_BIO_ReadHandle *rh; - ser = get_serialization_short_name (filename); - rh = GNUNET_BIO_read_open (filename); + ser = get_serialization_short_name(filename); + rh = GNUNET_BIO_read_open(filename); if (NULL == rh) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ( - "Failed to resume sub-download `%s': could not open file `%s'\n"), - ser, - filename); - GNUNET_free (ser); - return GNUNET_OK; - } - deserialize_download (parent->h, rh, parent, NULL, ser); - if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to resume sub-download `%s': %s\n"), - ser, - emsg); - GNUNET_free (emsg); - } - GNUNET_free (ser); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _( + "Failed to resume sub-download `%s': could not open file `%s'\n"), + ser, + filename); + GNUNET_free(ser); + return GNUNET_OK; + } + deserialize_download(parent->h, rh, parent, NULL, ser); + if (GNUNET_OK != GNUNET_BIO_read_close(rh, &emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to resume sub-download `%s': %s\n"), + ser, + emsg); + GNUNET_free(emsg); + } + GNUNET_free(ser); return GNUNET_OK; } @@ -2745,27 +2773,27 @@ deserialize_subdownload (void *cls, const char *filename) * @param dc context to free */ static void -free_download_context (struct GNUNET_FS_DownloadContext *dc) +free_download_context(struct GNUNET_FS_DownloadContext *dc) { struct GNUNET_FS_DownloadContext *dcc; if (NULL != dc->meta) - GNUNET_CONTAINER_meta_data_destroy (dc->meta); + GNUNET_CONTAINER_meta_data_destroy(dc->meta); if (NULL != dc->uri) - GNUNET_FS_uri_destroy (dc->uri); - GNUNET_free_non_null (dc->temp_filename); - GNUNET_free_non_null (dc->emsg); - GNUNET_free_non_null (dc->filename); - GNUNET_free_non_null (dc->serialization); + GNUNET_FS_uri_destroy(dc->uri); + GNUNET_free_non_null(dc->temp_filename); + GNUNET_free_non_null(dc->emsg); + GNUNET_free_non_null(dc->filename); + GNUNET_free_non_null(dc->serialization); while (NULL != (dcc = dc->child_head)) - { - GNUNET_CONTAINER_DLL_remove (dc->child_head, dc->child_tail, dcc); - free_download_context (dcc); - } - GNUNET_FS_free_download_request_ (dc->top_request); + { + GNUNET_CONTAINER_DLL_remove(dc->child_head, dc->child_tail, dcc); + free_download_context(dcc); + } + GNUNET_FS_free_download_request_(dc->top_request); if (NULL != dc->active) - GNUNET_CONTAINER_multihashmap_destroy (dc->active); - GNUNET_free (dc); + GNUNET_CONTAINER_multihashmap_destroy(dc->active); + GNUNET_free(dc); } @@ -2779,11 +2807,11 @@ free_download_context (struct GNUNET_FS_DownloadContext *dc) * @param serialization name under which the search was serialized */ static void -deserialize_download (struct GNUNET_FS_Handle *h, - struct GNUNET_BIO_ReadHandle *rh, - struct GNUNET_FS_DownloadContext *parent, - struct GNUNET_FS_SearchResult *search, - const char *serialization) +deserialize_download(struct GNUNET_FS_Handle *h, + struct GNUNET_BIO_ReadHandle *rh, + struct GNUNET_FS_DownloadContext *parent, + struct GNUNET_FS_SearchResult *search, + const char *serialization) { struct GNUNET_FS_DownloadContext *dc; char *emsg; @@ -2794,86 +2822,86 @@ deserialize_download (struct GNUNET_FS_Handle *h, uris = NULL; emsg = NULL; - dc = GNUNET_new (struct GNUNET_FS_DownloadContext); + dc = GNUNET_new(struct GNUNET_FS_DownloadContext); dc->parent = parent; dc->h = h; - dc->serialization = GNUNET_strdup (serialization); + dc->serialization = GNUNET_strdup(serialization); if ((GNUNET_OK != - GNUNET_BIO_read_string (rh, "download-uri", &uris, 10 * 1024)) || - (NULL == (dc->uri = GNUNET_FS_uri_parse (uris, &emsg))) || - ((GNUNET_YES != GNUNET_FS_uri_test_chk (dc->uri)) && - (GNUNET_YES != GNUNET_FS_uri_test_loc (dc->uri))) || + GNUNET_BIO_read_string(rh, "download-uri", &uris, 10 * 1024)) || + (NULL == (dc->uri = GNUNET_FS_uri_parse(uris, &emsg))) || + ((GNUNET_YES != GNUNET_FS_uri_test_chk(dc->uri)) && + (GNUNET_YES != GNUNET_FS_uri_test_loc(dc->uri))) || (GNUNET_OK != - GNUNET_BIO_read_meta_data (rh, "download-meta", &dc->meta)) || + GNUNET_BIO_read_meta_data(rh, "download-meta", &dc->meta)) || (GNUNET_OK != - GNUNET_BIO_read_string (rh, "download-emsg", &dc->emsg, 10 * 1024)) || + GNUNET_BIO_read_string(rh, "download-emsg", &dc->emsg, 10 * 1024)) || (GNUNET_OK != - GNUNET_BIO_read_string (rh, "download-fn", &dc->filename, 10 * 1024)) || - (GNUNET_OK != GNUNET_BIO_read_string (rh, - "download-tfn", - &dc->temp_filename, - 10 * 1024)) || - (GNUNET_OK != GNUNET_BIO_read_int64 (rh, &dc->old_file_size)) || - (GNUNET_OK != GNUNET_BIO_read_int64 (rh, &dc->offset)) || - (GNUNET_OK != GNUNET_BIO_read_int64 (rh, &dc->length)) || - (GNUNET_OK != GNUNET_BIO_read_int64 (rh, &dc->completed)) || - (GNUNET_OK != read_start_time (rh, &dc->start_time)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &dc->anonymity)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &options)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &status))) - { - GNUNET_break (0); - goto cleanup; - } - dc->options = (enum GNUNET_FS_DownloadOptions) options; + GNUNET_BIO_read_string(rh, "download-fn", &dc->filename, 10 * 1024)) || + (GNUNET_OK != GNUNET_BIO_read_string(rh, + "download-tfn", + &dc->temp_filename, + 10 * 1024)) || + (GNUNET_OK != GNUNET_BIO_read_int64(rh, &dc->old_file_size)) || + (GNUNET_OK != GNUNET_BIO_read_int64(rh, &dc->offset)) || + (GNUNET_OK != GNUNET_BIO_read_int64(rh, &dc->length)) || + (GNUNET_OK != GNUNET_BIO_read_int64(rh, &dc->completed)) || + (GNUNET_OK != read_start_time(rh, &dc->start_time)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &dc->anonymity)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &options)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &status))) + { + GNUNET_break(0); + goto cleanup; + } + dc->options = (enum GNUNET_FS_DownloadOptions)options; dc->active = - GNUNET_CONTAINER_multihashmap_create (1 + 2 * (dc->length / DBLOCK_SIZE), - GNUNET_NO); - dc->has_finished = (int) status; + GNUNET_CONTAINER_multihashmap_create(1 + 2 * (dc->length / DBLOCK_SIZE), + GNUNET_NO); + dc->has_finished = (int)status; dc->treedepth = - GNUNET_FS_compute_depth (GNUNET_FS_uri_chk_get_file_size (dc->uri)); - if (GNUNET_FS_uri_test_loc (dc->uri)) - GNUNET_assert (GNUNET_OK == - GNUNET_FS_uri_loc_get_peer_identity (dc->uri, &dc->target)); + GNUNET_FS_compute_depth(GNUNET_FS_uri_chk_get_file_size(dc->uri)); + if (GNUNET_FS_uri_test_loc(dc->uri)) + GNUNET_assert(GNUNET_OK == + GNUNET_FS_uri_loc_get_peer_identity(dc->uri, &dc->target)); if (NULL == dc->emsg) - { - dc->top_request = read_download_request (rh); - if (NULL == dc->top_request) { - GNUNET_break (0); - goto cleanup; + dc->top_request = read_download_request(rh); + if (NULL == dc->top_request) + { + GNUNET_break(0); + goto cleanup; + } } - } - dn = get_download_sync_filename (dc, dc->serialization, ".dir"); + dn = get_download_sync_filename(dc, dc->serialization, ".dir"); if (NULL != dn) - { - if (GNUNET_YES == GNUNET_DISK_directory_test (dn, GNUNET_YES)) - GNUNET_DISK_directory_scan (dn, &deserialize_subdownload, dc); - GNUNET_free (dn); - } + { + if (GNUNET_YES == GNUNET_DISK_directory_test(dn, GNUNET_YES)) + GNUNET_DISK_directory_scan(dn, &deserialize_subdownload, dc); + GNUNET_free(dn); + } if (NULL != parent) - { - GNUNET_CONTAINER_DLL_insert (parent->child_head, parent->child_tail, dc); - } + { + GNUNET_CONTAINER_DLL_insert(parent->child_head, parent->child_tail, dc); + } if (NULL != search) - { - dc->search = search; - search->download = dc; - } + { + dc->search = search; + search->download = dc; + } if ((NULL == parent) && (NULL == search)) - { - dc->top = - GNUNET_FS_make_top (dc->h, &GNUNET_FS_download_signal_suspend_, dc); - signal_download_resume (dc); - } - GNUNET_free (uris); - GNUNET_assert (NULL == dc->job_queue); - dc->task = GNUNET_SCHEDULER_add_now (&GNUNET_FS_download_start_task_, dc); + { + dc->top = + GNUNET_FS_make_top(dc->h, &GNUNET_FS_download_signal_suspend_, dc); + signal_download_resume(dc); + } + GNUNET_free(uris); + GNUNET_assert(NULL == dc->job_queue); + dc->task = GNUNET_SCHEDULER_add_now(&GNUNET_FS_download_start_task_, dc); return; cleanup: - GNUNET_free_non_null (uris); - GNUNET_free_non_null (emsg); - free_download_context (dc); + GNUNET_free_non_null(uris); + GNUNET_free_non_null(emsg); + free_download_context(dc); } @@ -2884,7 +2912,7 @@ cleanup: * @param sc search being resumed */ static void -signal_search_resume (struct GNUNET_FS_SearchContext *sc) +signal_search_resume(struct GNUNET_FS_SearchContext *sc) { struct GNUNET_FS_ProgressInfo pi; @@ -2892,10 +2920,10 @@ signal_search_resume (struct GNUNET_FS_SearchContext *sc) pi.value.search.specifics.resume.message = sc->emsg; pi.value.search.specifics.resume.is_paused = (NULL == sc->mq) ? GNUNET_YES : GNUNET_NO; - sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc); - GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map, - &signal_result_resume, - sc); + sc->client_info = GNUNET_FS_search_make_status_(&pi, sc->h, sc); + GNUNET_CONTAINER_multihashmap_iterate(sc->master_result_map, + &signal_result_resume, + sc); } @@ -2908,10 +2936,10 @@ signal_search_resume (struct GNUNET_FS_SearchContext *sc) * @param serialization name under which the search was serialized */ static struct GNUNET_FS_SearchContext * -deserialize_search (struct GNUNET_FS_Handle *h, - struct GNUNET_BIO_ReadHandle *rh, - struct GNUNET_FS_SearchResult *psearch_result, - const char *serialization) +deserialize_search(struct GNUNET_FS_Handle *h, + struct GNUNET_BIO_ReadHandle *rh, + struct GNUNET_FS_SearchResult *psearch_result, + const char *serialization) { struct GNUNET_FS_SearchContext *sc; char *emsg; @@ -2921,64 +2949,64 @@ deserialize_search (struct GNUNET_FS_Handle *h, char in_pause; if ((NULL != psearch_result) && (NULL != psearch_result->update_search)) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } uris = NULL; emsg = NULL; - sc = GNUNET_new (struct GNUNET_FS_SearchContext); + sc = GNUNET_new(struct GNUNET_FS_SearchContext); if (NULL != psearch_result) - { - sc->psearch_result = psearch_result; - psearch_result->update_search = sc; - } + { + sc->psearch_result = psearch_result; + psearch_result->update_search = sc; + } sc->h = h; - sc->serialization = GNUNET_strdup (serialization); + sc->serialization = GNUNET_strdup(serialization); if ((GNUNET_OK != - GNUNET_BIO_read_string (rh, "search-uri", &uris, 10 * 1024)) || - (NULL == (sc->uri = GNUNET_FS_uri_parse (uris, &emsg))) || - ((GNUNET_YES != GNUNET_FS_uri_test_ksk (sc->uri)) && - (GNUNET_YES != GNUNET_FS_uri_test_sks (sc->uri))) || - (GNUNET_OK != read_start_time (rh, &sc->start_time)) || + GNUNET_BIO_read_string(rh, "search-uri", &uris, 10 * 1024)) || + (NULL == (sc->uri = GNUNET_FS_uri_parse(uris, &emsg))) || + ((GNUNET_YES != GNUNET_FS_uri_test_ksk(sc->uri)) && + (GNUNET_YES != GNUNET_FS_uri_test_sks(sc->uri))) || + (GNUNET_OK != read_start_time(rh, &sc->start_time)) || (GNUNET_OK != - GNUNET_BIO_read_string (rh, "search-emsg", &sc->emsg, 10 * 1024)) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &options)) || + GNUNET_BIO_read_string(rh, "search-emsg", &sc->emsg, 10 * 1024)) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &options)) || (GNUNET_OK != - GNUNET_BIO_read (rh, "search-pause", &in_pause, sizeof (in_pause))) || - (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &sc->anonymity))) - { - GNUNET_break (0); - goto cleanup; - } - sc->options = (enum GNUNET_FS_SearchOptions) options; - sc->master_result_map = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_NO); - dn = get_serialization_file_name_in_dir (h, - (NULL == sc->psearch_result) - ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH - : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, - sc->serialization, - ""); + GNUNET_BIO_read(rh, "search-pause", &in_pause, sizeof(in_pause))) || + (GNUNET_OK != GNUNET_BIO_read_int32(rh, &sc->anonymity))) + { + GNUNET_break(0); + goto cleanup; + } + sc->options = (enum GNUNET_FS_SearchOptions)options; + sc->master_result_map = GNUNET_CONTAINER_multihashmap_create(16, GNUNET_NO); + dn = get_serialization_file_name_in_dir(h, + (NULL == sc->psearch_result) + ? GNUNET_FS_SYNC_PATH_MASTER_SEARCH + : GNUNET_FS_SYNC_PATH_CHILD_SEARCH, + sc->serialization, + ""); if (NULL != dn) - { - if (GNUNET_YES == GNUNET_DISK_directory_test (dn, GNUNET_YES)) - GNUNET_DISK_directory_scan (dn, &deserialize_search_result, sc); - GNUNET_free (dn); - } + { + if (GNUNET_YES == GNUNET_DISK_directory_test(dn, GNUNET_YES)) + GNUNET_DISK_directory_scan(dn, &deserialize_search_result, sc); + GNUNET_free(dn); + } if (('\0' == in_pause) && - (GNUNET_OK != GNUNET_FS_search_start_searching_ (sc))) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_WARNING, - _ ("Could not resume running search, will resume as paused search\n")); - } - signal_search_resume (sc); - GNUNET_free (uris); + (GNUNET_OK != GNUNET_FS_search_start_searching_(sc))) + { + GNUNET_log( + GNUNET_ERROR_TYPE_WARNING, + _("Could not resume running search, will resume as paused search\n")); + } + signal_search_resume(sc); + GNUNET_free(uris); return sc; cleanup: - GNUNET_free_non_null (emsg); - free_search_context (sc); - GNUNET_free_non_null (uris); + GNUNET_free_non_null(emsg); + free_search_context(sc); + GNUNET_free_non_null(uris); return NULL; } @@ -2992,7 +3020,7 @@ cleanup: * @return #GNUNET_OK (continue to iterate) */ static int -deserialize_search_file (void *cls, const char *filename) +deserialize_search_file(void *cls, const char *filename) { struct GNUNET_FS_Handle *h = cls; char *ser; @@ -3001,36 +3029,36 @@ deserialize_search_file (void *cls, const char *filename) struct GNUNET_FS_SearchContext *sc; struct stat buf; - if (0 != stat (filename, &buf)) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", filename); - return GNUNET_OK; - } - if (S_ISDIR (buf.st_mode)) + if (0 != stat(filename, &buf)) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "stat", filename); + return GNUNET_OK; + } + if (S_ISDIR(buf.st_mode)) return GNUNET_OK; /* skip directories */ - ser = get_serialization_short_name (filename); - rh = GNUNET_BIO_read_open (filename); + ser = get_serialization_short_name(filename); + rh = GNUNET_BIO_read_open(filename); if (NULL == rh) - { - if (NULL != ser) { - GNUNET_FS_remove_sync_file_ (h, GNUNET_FS_SYNC_PATH_MASTER_SEARCH, ser); - GNUNET_free (ser); + if (NULL != ser) + { + GNUNET_FS_remove_sync_file_(h, GNUNET_FS_SYNC_PATH_MASTER_SEARCH, ser); + GNUNET_free(ser); + } + return GNUNET_OK; } - return GNUNET_OK; - } - sc = deserialize_search (h, rh, NULL, ser); + sc = deserialize_search(h, rh, NULL, ser); if (NULL != sc) - sc->top = GNUNET_FS_make_top (h, &GNUNET_FS_search_signal_suspend_, sc); - GNUNET_free (ser); - if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failure while resuming search operation `%s': %s\n"), - filename, - emsg); - GNUNET_free (emsg); - } + sc->top = GNUNET_FS_make_top(h, &GNUNET_FS_search_signal_suspend_, sc); + GNUNET_free(ser); + if (GNUNET_OK != GNUNET_BIO_read_close(rh, &emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failure while resuming search operation `%s': %s\n"), + filename, + emsg); + GNUNET_free(emsg); + } return GNUNET_OK; } @@ -3044,32 +3072,32 @@ deserialize_search_file (void *cls, const char *filename) * @return #GNUNET_OK (continue to iterate) */ static int -deserialize_download_file (void *cls, const char *filename) +deserialize_download_file(void *cls, const char *filename) { struct GNUNET_FS_Handle *h = cls; char *ser; char *emsg; struct GNUNET_BIO_ReadHandle *rh; - ser = get_serialization_short_name (filename); - rh = GNUNET_BIO_read_open (filename); + ser = get_serialization_short_name(filename); + rh = GNUNET_BIO_read_open(filename); if (NULL == rh) - { - if (0 != unlink (filename)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", filename); - GNUNET_free (ser); - return GNUNET_OK; - } - deserialize_download (h, rh, NULL, NULL, ser); - GNUNET_free (ser); - if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failure while resuming download operation `%s': %s\n"), - filename, - emsg); - GNUNET_free (emsg); - } + { + if (0 != unlink(filename)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", filename); + GNUNET_free(ser); + return GNUNET_OK; + } + deserialize_download(h, rh, NULL, NULL, ser); + GNUNET_free(ser); + if (GNUNET_OK != GNUNET_BIO_read_close(rh, &emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failure while resuming download operation `%s': %s\n"), + filename, + emsg); + GNUNET_free(emsg); + } return GNUNET_OK; } @@ -3082,18 +3110,18 @@ deserialize_download_file (void *cls, const char *filename) * @param h the `struct GNUNET_FS_Handle *` */ static void -deserialization_master (const char *master_path, - GNUNET_FileNameCallback proc, - struct GNUNET_FS_Handle *h) +deserialization_master(const char *master_path, + GNUNET_FileNameCallback proc, + struct GNUNET_FS_Handle *h) { char *dn; - dn = get_serialization_file_name (h, master_path, ""); + dn = get_serialization_file_name(h, master_path, ""); if (NULL == dn) return; - if (GNUNET_YES == GNUNET_DISK_directory_test (dn, GNUNET_YES)) - GNUNET_DISK_directory_scan (dn, proc, h); - GNUNET_free (dn); + if (GNUNET_YES == GNUNET_DISK_directory_test(dn, GNUNET_YES)) + GNUNET_DISK_directory_scan(dn, proc, h); + GNUNET_free(dn); } @@ -3109,20 +3137,20 @@ deserialization_master (const char *master_path, * @return NULL on error */ struct GNUNET_FS_Handle * -GNUNET_FS_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *client_name, - GNUNET_FS_ProgressCallback upcb, - void *upcb_cls, - enum GNUNET_FS_Flags flags, - ...) +GNUNET_FS_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *client_name, + GNUNET_FS_ProgressCallback upcb, + void *upcb_cls, + enum GNUNET_FS_Flags flags, + ...) { struct GNUNET_FS_Handle *ret; enum GNUNET_FS_OPTIONS opt; va_list ap; - ret = GNUNET_new (struct GNUNET_FS_Handle); + ret = GNUNET_new(struct GNUNET_FS_Handle); ret->cfg = cfg; - ret->client_name = GNUNET_strdup (client_name); + ret->client_name = GNUNET_strdup(client_name); ret->upcb = upcb; ret->upcb_cls = upcb_cls; ret->flags = flags; @@ -3130,44 +3158,46 @@ GNUNET_FS_start (const struct GNUNET_CONFIGURATION_Handle *cfg, ret->max_parallel_requests = DEFAULT_MAX_PARALLEL_REQUESTS; ret->avg_block_latency = GNUNET_TIME_UNIT_MINUTES; /* conservative starting point */ - va_start (ap, flags); + va_start(ap, flags); while (GNUNET_FS_OPTIONS_END != - (opt = GNUNET_VA_ARG_ENUM (ap, GNUNET_FS_OPTIONS))) - { - switch (opt) + (opt = GNUNET_VA_ARG_ENUM(ap, GNUNET_FS_OPTIONS))) { - case GNUNET_FS_OPTIONS_DOWNLOAD_PARALLELISM: - ret->max_parallel_downloads = va_arg (ap, unsigned int); + switch (opt) + { + case GNUNET_FS_OPTIONS_DOWNLOAD_PARALLELISM: + ret->max_parallel_downloads = va_arg(ap, unsigned int); - break; - case GNUNET_FS_OPTIONS_REQUEST_PARALLELISM: - ret->max_parallel_requests = va_arg (ap, unsigned int); + break; - break; - default: - GNUNET_break (0); - GNUNET_free (ret->client_name); - GNUNET_free (ret); - va_end (ap); - return NULL; + case GNUNET_FS_OPTIONS_REQUEST_PARALLELISM: + ret->max_parallel_requests = va_arg(ap, unsigned int); + + break; + + default: + GNUNET_break(0); + GNUNET_free(ret->client_name); + GNUNET_free(ret); + va_end(ap); + return NULL; + } } - } - va_end (ap); + va_end(ap); if (0 != (GNUNET_FS_FLAGS_PERSISTENCE & flags)) - { - deserialization_master (GNUNET_FS_SYNC_PATH_MASTER_PUBLISH, - &deserialize_publish_file, - ret); - deserialization_master (GNUNET_FS_SYNC_PATH_MASTER_SEARCH, - &deserialize_search_file, - ret); - deserialization_master (GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD, - &deserialize_download_file, - ret); - deserialization_master (GNUNET_FS_SYNC_PATH_MASTER_UNINDEX, - &deserialize_unindex_file, - ret); - } + { + deserialization_master(GNUNET_FS_SYNC_PATH_MASTER_PUBLISH, + &deserialize_publish_file, + ret); + deserialization_master(GNUNET_FS_SYNC_PATH_MASTER_SEARCH, + &deserialize_search_file, + ret); + deserialization_master(GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD, + &deserialize_download_file, + ret); + deserialization_master(GNUNET_FS_SYNC_PATH_MASTER_UNINDEX, + &deserialize_unindex_file, + ret); + } return ret; } @@ -3182,14 +3212,14 @@ GNUNET_FS_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param h handle that was returned from #GNUNET_FS_start() */ void -GNUNET_FS_stop (struct GNUNET_FS_Handle *h) +GNUNET_FS_stop(struct GNUNET_FS_Handle *h) { while (NULL != h->top_head) - h->top_head->ssf (h->top_head->ssf_cls); + h->top_head->ssf(h->top_head->ssf_cls); if (NULL != h->queue_job) - GNUNET_SCHEDULER_cancel (h->queue_job); - GNUNET_free (h->client_name); - GNUNET_free (h); + GNUNET_SCHEDULER_cancel(h->queue_job); + GNUNET_free(h->client_name); + GNUNET_free(h); } diff --git a/src/fs/fs_api.h b/src/fs/fs_api.h index ad054ef06..dcc487eb1 100644 --- a/src/fs/fs_api.h +++ b/src/fs/fs_api.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_api.h @@ -90,9 +90,7 @@ * @brief complete information needed * to download a file. */ -struct FileIdentifier -{ - +struct FileIdentifier { /** * Total size of the file in bytes. (network byte order (!)) */ @@ -102,7 +100,6 @@ struct FileIdentifier * Query and key of the top GNUNET_EC_IBlock. */ struct ContentHashKey chk; - }; @@ -110,8 +107,7 @@ struct FileIdentifier * Information about a file and its location * (peer claiming to share the file). */ -struct Location -{ +struct Location { /** * Information about the shared file. */ @@ -132,14 +128,12 @@ struct Location * peer identity and expiration time. */ struct GNUNET_CRYPTO_EddsaSignature contentSignature; - }; /** * Types of URIs. */ -enum GNUNET_FS_UriType -{ +enum GNUNET_FS_UriType { /** * Content-hash-key (simple file). */ @@ -165,17 +159,14 @@ enum GNUNET_FS_UriType /** * A Universal Resource Identifier (URI), opaque. */ -struct GNUNET_FS_Uri -{ +struct GNUNET_FS_Uri { /** * Type of the URI. */ enum GNUNET_FS_UriType type; - union - { - struct - { + union { + struct { /** * Keywords start with a '+' if they are mandatory (in which * case the '+' is NOT part of the keyword) and with a simple @@ -193,8 +184,7 @@ struct GNUNET_FS_Uri unsigned int keywordCount; } ksk; - struct - { + struct { /** * Identifier of the namespace. */ @@ -205,7 +195,6 @@ struct GNUNET_FS_Uri * namespace. */ char *identifier; - } sks; /** @@ -220,7 +209,6 @@ struct GNUNET_FS_Uri */ struct Location loc; } data; - }; @@ -228,9 +216,7 @@ struct GNUNET_FS_Uri * Information for a file or directory that is * about to be published. */ -struct GNUNET_FS_FileInformation -{ - +struct GNUNET_FS_FileInformation { /** * Files in a directory are kept as a linked list. */ @@ -309,15 +295,11 @@ struct GNUNET_FS_FileInformation /** * Data describing either the file or the directory. */ - union - { - + union { /** * Data for a file. */ - struct - { - + struct { /** * Function that can be used to read the data for the file. */ @@ -356,15 +338,12 @@ struct GNUNET_FS_FileInformation * #GNUNET_YES if this step has been completed. */ int index_start_confirmed; - } file; /** * Data for a directory. */ - struct - { - + struct { /** * Linked list of entries in the directory. */ @@ -391,9 +370,7 @@ struct GNUNET_FS_FileInformation * Sum of all of the sizes of all of the files in the directory. */ uint64_t contents_size; - } dir; - } data; /** @@ -405,15 +382,13 @@ struct GNUNET_FS_FileInformation * Are we done publishing this file? */ int is_published; - }; /** * Priorities for the queue. */ -enum GNUNET_FS_QueuePriority -{ +enum GNUNET_FS_QueuePriority { /** * This is a probe (low priority). */ @@ -429,8 +404,7 @@ enum GNUNET_FS_QueuePriority /** * Entry in the job queue. */ -struct GNUNET_FS_QueueEntry -{ +struct GNUNET_FS_QueueEntry { /** * This is a linked list. */ @@ -501,16 +475,13 @@ struct GNUNET_FS_QueueEntry * #GNUNET_YES if the job is active now. */ int active; - }; /** * Information we store for each search result. */ -struct GNUNET_FS_SearchResult -{ - +struct GNUNET_FS_SearchResult { /** * File-sharing context this result belongs to. */ @@ -625,7 +596,6 @@ struct GNUNET_FS_SearchResult * search result. */ uint32_t availability_trials; - }; @@ -641,12 +611,12 @@ struct GNUNET_FS_SearchResult * @return queue handle */ struct GNUNET_FS_QueueEntry * -GNUNET_FS_queue_ (struct GNUNET_FS_Handle *h, - GNUNET_SCHEDULER_TaskCallback start, - GNUNET_SCHEDULER_TaskCallback stop, - void *cls, - unsigned int blocks, - enum GNUNET_FS_QueuePriority priority); +GNUNET_FS_queue_(struct GNUNET_FS_Handle *h, + GNUNET_SCHEDULER_TaskCallback start, + GNUNET_SCHEDULER_TaskCallback stop, + void *cls, + unsigned int blocks, + enum GNUNET_FS_QueuePriority priority); /** @@ -655,7 +625,7 @@ GNUNET_FS_queue_ (struct GNUNET_FS_Handle *h, * @param qe handle for the job */ void -GNUNET_FS_dequeue_ (struct GNUNET_FS_QueueEntry *qe); +GNUNET_FS_dequeue_(struct GNUNET_FS_QueueEntry *qe); /** @@ -675,11 +645,11 @@ GNUNET_FS_dequeue_ (struct GNUNET_FS_QueueEntry *qe); * @return number of bytes written, usually "max", 0 on error */ size_t -GNUNET_FS_data_reader_file_ (void *cls, - uint64_t offset, - size_t max, - void *buf, - char **emsg); +GNUNET_FS_data_reader_file_(void *cls, + uint64_t offset, + size_t max, + void *buf, + char **emsg); /** @@ -689,7 +659,7 @@ GNUNET_FS_data_reader_file_ (void *cls, * @return closure to use */ void * -GNUNET_FS_make_file_reader_context_ (const char *filename); +GNUNET_FS_make_file_reader_context_(const char *filename); @@ -710,11 +680,11 @@ GNUNET_FS_make_file_reader_context_ (const char *filename); * @return number of bytes written, usually @a max, 0 on error */ size_t -GNUNET_FS_data_reader_copy_ (void *cls, - uint64_t offset, - size_t max, - void *buf, - char **emsg); +GNUNET_FS_data_reader_copy_(void *cls, + uint64_t offset, + size_t max, + void *buf, + char **emsg); /** @@ -733,8 +703,8 @@ GNUNET_FS_data_reader_copy_ (void *cls, * field in the `struct GNUNET_FS_ProgressInfo`. */ void * -GNUNET_FS_search_probe_progress_ (void *cls, - const struct GNUNET_FS_ProgressInfo *info); +GNUNET_FS_search_probe_progress_(void *cls, + const struct GNUNET_FS_ProgressInfo *info); /** @@ -743,7 +713,7 @@ GNUNET_FS_search_probe_progress_ (void *cls, * @param cls `struct GNUNET_FS_PublishContext` identifies the upload */ void -GNUNET_FS_publish_main_ (void *cls); +GNUNET_FS_publish_main_(void *cls); /** @@ -754,8 +724,8 @@ GNUNET_FS_publish_main_ (void *cls); * @param file_id computed hash, NULL on error */ void -GNUNET_FS_unindex_process_hash_ (void *cls, - const struct GNUNET_HashCode *file_id); +GNUNET_FS_unindex_process_hash_(void *cls, + const struct GNUNET_HashCode *file_id); /** @@ -764,7 +734,7 @@ GNUNET_FS_unindex_process_hash_ (void *cls, * @param uc context for the unindex operation. */ void -GNUNET_FS_unindex_do_extract_keywords_ (struct GNUNET_FS_UnindexContext *uc); +GNUNET_FS_unindex_do_extract_keywords_(struct GNUNET_FS_UnindexContext *uc); /** @@ -773,7 +743,7 @@ GNUNET_FS_unindex_do_extract_keywords_ (struct GNUNET_FS_UnindexContext *uc); * @param uc context for the unindex operation. */ void -GNUNET_FS_unindex_do_remove_kblocks_ (struct GNUNET_FS_UnindexContext *uc); +GNUNET_FS_unindex_do_remove_kblocks_(struct GNUNET_FS_UnindexContext *uc); /** @@ -787,10 +757,10 @@ GNUNET_FS_unindex_do_remove_kblocks_ (struct GNUNET_FS_UnindexContext *uc); * @return value returned from callback */ void * -GNUNET_FS_publish_make_status_ (struct GNUNET_FS_ProgressInfo *pi, - struct GNUNET_FS_PublishContext *pc, - const struct GNUNET_FS_FileInformation *p, - uint64_t offset); +GNUNET_FS_publish_make_status_(struct GNUNET_FS_ProgressInfo *pi, + struct GNUNET_FS_PublishContext *pc, + const struct GNUNET_FS_FileInformation *p, + uint64_t offset); /** @@ -801,8 +771,8 @@ GNUNET_FS_publish_make_status_ (struct GNUNET_FS_ProgressInfo *pi, * @param dc overall download context */ void -GNUNET_FS_download_make_status_ (struct GNUNET_FS_ProgressInfo *pi, - struct GNUNET_FS_DownloadContext *dc); +GNUNET_FS_download_make_status_(struct GNUNET_FS_ProgressInfo *pi, + struct GNUNET_FS_DownloadContext *dc); /** @@ -812,7 +782,7 @@ GNUNET_FS_download_make_status_ (struct GNUNET_FS_ProgressInfo *pi, * @param cls the 'struct GNUNET_FS_DownloadContext' */ void -GNUNET_FS_download_start_task_ (void *cls); +GNUNET_FS_download_start_task_(void *cls); @@ -825,9 +795,9 @@ GNUNET_FS_download_start_task_ (void *cls); * @param offset where we are in the file (for progress) */ void -GNUNET_FS_unindex_make_status_ (struct GNUNET_FS_ProgressInfo *pi, - struct GNUNET_FS_UnindexContext *uc, - uint64_t offset); +GNUNET_FS_unindex_make_status_(struct GNUNET_FS_ProgressInfo *pi, + struct GNUNET_FS_UnindexContext *uc, + uint64_t offset); /** * Fill in all of the generic fields for a search event and @@ -839,9 +809,9 @@ GNUNET_FS_unindex_make_status_ (struct GNUNET_FS_ProgressInfo *pi, * @return value returned by the callback */ void * -GNUNET_FS_search_make_status_ (struct GNUNET_FS_ProgressInfo *pi, - struct GNUNET_FS_Handle *h, - struct GNUNET_FS_SearchContext *sc); +GNUNET_FS_search_make_status_(struct GNUNET_FS_ProgressInfo *pi, + struct GNUNET_FS_Handle *h, + struct GNUNET_FS_SearchContext *sc); /** @@ -850,7 +820,7 @@ GNUNET_FS_search_make_status_ (struct GNUNET_FS_ProgressInfo *pi, * @param uc context for the unindex operation. */ void -GNUNET_FS_unindex_do_remove_ (struct GNUNET_FS_UnindexContext *uc); +GNUNET_FS_unindex_do_remove_(struct GNUNET_FS_UnindexContext *uc); /** * Build the request and actually initiate the search using the @@ -860,7 +830,7 @@ GNUNET_FS_unindex_do_remove_ (struct GNUNET_FS_UnindexContext *uc); * @return GNUNET_OK on success, GNUNET_SYSERR on error */ int -GNUNET_FS_search_start_searching_ (struct GNUNET_FS_SearchContext *sc); +GNUNET_FS_search_start_searching_(struct GNUNET_FS_SearchContext *sc); /** * Start the downloading process (by entering the queue). @@ -868,7 +838,7 @@ GNUNET_FS_search_start_searching_ (struct GNUNET_FS_SearchContext *sc); * @param dc our download context */ void -GNUNET_FS_download_start_downloading_ (struct GNUNET_FS_DownloadContext *dc); +GNUNET_FS_download_start_downloading_(struct GNUNET_FS_DownloadContext *dc); /** @@ -877,7 +847,7 @@ GNUNET_FS_download_start_downloading_ (struct GNUNET_FS_DownloadContext *dc); * @param sr the search result */ void -GNUNET_FS_search_start_probe_ (struct GNUNET_FS_SearchResult *sr); +GNUNET_FS_search_start_probe_(struct GNUNET_FS_SearchResult *sr); /** @@ -888,9 +858,9 @@ GNUNET_FS_search_start_probe_ (struct GNUNET_FS_SearchResult *sr); * @param ent entity identifier */ void -GNUNET_FS_remove_sync_file_ (struct GNUNET_FS_Handle *h, - const char *ext, - const char *ent); +GNUNET_FS_remove_sync_file_(struct GNUNET_FS_Handle *h, + const char *ext, + const char *ent); /** @@ -901,9 +871,9 @@ GNUNET_FS_remove_sync_file_ (struct GNUNET_FS_Handle *h, * @param uni unique name of parent */ void -GNUNET_FS_remove_sync_dir_ (struct GNUNET_FS_Handle *h, - const char *ext, - const char *uni); +GNUNET_FS_remove_sync_dir_(struct GNUNET_FS_Handle *h, + const char *ext, + const char *uni); /** @@ -915,7 +885,7 @@ GNUNET_FS_remove_sync_dir_ (struct GNUNET_FS_Handle *h, * @param fi the struct to sync */ void -GNUNET_FS_file_information_sync_ (struct GNUNET_FS_FileInformation *f); +GNUNET_FS_file_information_sync_(struct GNUNET_FS_FileInformation *f); /** @@ -927,7 +897,7 @@ GNUNET_FS_file_information_sync_ (struct GNUNET_FS_FileInformation *f); * @param pc the struct to sync */ void -GNUNET_FS_publish_sync_ (struct GNUNET_FS_PublishContext *pc); +GNUNET_FS_publish_sync_(struct GNUNET_FS_PublishContext *pc); /** @@ -939,7 +909,7 @@ GNUNET_FS_publish_sync_ (struct GNUNET_FS_PublishContext *pc); * @param uc the struct to sync */ void -GNUNET_FS_unindex_sync_ (struct GNUNET_FS_UnindexContext *uc); +GNUNET_FS_unindex_sync_(struct GNUNET_FS_UnindexContext *uc); /** @@ -951,7 +921,7 @@ GNUNET_FS_unindex_sync_ (struct GNUNET_FS_UnindexContext *uc); * @param sc the struct to sync */ void -GNUNET_FS_search_sync_ (struct GNUNET_FS_SearchContext *sc); +GNUNET_FS_search_sync_(struct GNUNET_FS_SearchContext *sc); /** @@ -963,7 +933,7 @@ GNUNET_FS_search_sync_ (struct GNUNET_FS_SearchContext *sc); * @param sr the struct to sync */ void -GNUNET_FS_search_result_sync_ (struct GNUNET_FS_SearchResult *sr); +GNUNET_FS_search_result_sync_(struct GNUNET_FS_SearchResult *sr); /** @@ -975,7 +945,7 @@ GNUNET_FS_search_result_sync_ (struct GNUNET_FS_SearchResult *sr); * @param dc the struct to sync */ void -GNUNET_FS_download_sync_ (struct GNUNET_FS_DownloadContext *dc); +GNUNET_FS_download_sync_(struct GNUNET_FS_DownloadContext *dc); /** @@ -985,7 +955,7 @@ GNUNET_FS_download_sync_ (struct GNUNET_FS_DownloadContext *dc); * @param cls the `struct GNUNET_FS_PublishContext` to signal for */ void -GNUNET_FS_publish_signal_suspend_ (void *cls); +GNUNET_FS_publish_signal_suspend_(void *cls); /** @@ -995,7 +965,7 @@ GNUNET_FS_publish_signal_suspend_ (void *cls); * @param cls the 'struct GNUNET_FS_SearchContext' to signal for */ void -GNUNET_FS_search_signal_suspend_ (void *cls); +GNUNET_FS_search_signal_suspend_(void *cls); /** @@ -1005,7 +975,7 @@ GNUNET_FS_search_signal_suspend_ (void *cls); * @param cls the `struct GNUNET_FS_DownloadContext` to signal for */ void -GNUNET_FS_download_signal_suspend_ (void *cls); +GNUNET_FS_download_signal_suspend_(void *cls); /** @@ -1015,7 +985,7 @@ GNUNET_FS_download_signal_suspend_ (void *cls); * @param cls the `struct GNUNET_FS_UnindexContext` to signal for */ void -GNUNET_FS_unindex_signal_suspend_ (void *cls); +GNUNET_FS_unindex_signal_suspend_(void *cls); /** @@ -1031,8 +1001,7 @@ typedef void (*SuspendSignalFunction) (void *cls); * We track all of the top-level activities of FS * so that we can signal 'suspend' on shutdown. */ -struct TopLevelActivity -{ +struct TopLevelActivity { /** * This is a doubly-linked list. */ @@ -1064,9 +1033,9 @@ struct TopLevelActivity * @return fresh top-level activity handle */ struct TopLevelActivity * -GNUNET_FS_make_top (struct GNUNET_FS_Handle *h, - SuspendSignalFunction ssf, - void *ssf_cls); +GNUNET_FS_make_top(struct GNUNET_FS_Handle *h, + SuspendSignalFunction ssf, + void *ssf_cls); /** @@ -1076,16 +1045,15 @@ GNUNET_FS_make_top (struct GNUNET_FS_Handle *h, * @param top top level activity entry */ void -GNUNET_FS_end_top (struct GNUNET_FS_Handle *h, - struct TopLevelActivity *top); +GNUNET_FS_end_top(struct GNUNET_FS_Handle *h, + struct TopLevelActivity *top); /** * Master context for most FS operations. */ -struct GNUNET_FS_Handle -{ +struct GNUNET_FS_Handle { /** * Configuration to use. */ @@ -1188,15 +1156,13 @@ struct GNUNET_FS_Handle * Maximum number of parallel requests. */ unsigned int max_parallel_requests; - }; /** * Handle for controlling a publication process. */ -struct GNUNET_FS_PublishContext -{ +struct GNUNET_FS_PublishContext { /** * Handle to the global fs context. */ @@ -1322,8 +1288,7 @@ struct GNUNET_FS_PublishContext /** * Phases of unindex processing (state machine). */ -enum UnindexState -{ +enum UnindexState { /** * We're currently hashing the file. */ @@ -1366,9 +1331,7 @@ enum UnindexState /** * Handle for controlling an unindexing operation. */ -struct GNUNET_FS_UnindexContext -{ - +struct GNUNET_FS_UnindexContext { /** * The content hash key of the last block we processed, will in the * end be set to the CHK from the URI. Used to remove the KBlocks. @@ -1482,16 +1445,13 @@ struct GNUNET_FS_UnindexContext * Current operatinonal phase. */ enum UnindexState state; - }; /** * Information we keep for each keyword in a keyword search. */ -struct SearchRequestEntry -{ - +struct SearchRequestEntry { /** * Hash of the public key, also known as the query. */ @@ -1523,15 +1483,13 @@ struct SearchRequestEntry * (started with '+')? */ int mandatory; - }; /** * Handle for controlling a search. */ -struct GNUNET_FS_SearchContext -{ +struct GNUNET_FS_SearchContext { /** * Handle to the global FS context. */ @@ -1627,8 +1585,7 @@ struct GNUNET_FS_SearchContext * order of progression is linear through the states, alternatives * are documented in the comments. */ -enum BlockRequestState -{ +enum BlockRequestState { /** * Initial state, block has only been allocated (since it is * relevant to the overall download request). @@ -1695,9 +1652,7 @@ enum BlockRequestState /** * Information about an active download request. */ -struct DownloadRequest -{ - +struct DownloadRequest { /** * Parent in the CHK-tree. */ @@ -1740,7 +1695,6 @@ struct DownloadRequest * State in the FSM. */ enum BlockRequestState state; - }; @@ -1750,7 +1704,7 @@ struct DownloadRequest * @param dr request to free */ void -GNUNET_FS_free_download_request_ (struct DownloadRequest *dr); +GNUNET_FS_free_download_request_(struct DownloadRequest *dr); /** @@ -1759,15 +1713,13 @@ GNUNET_FS_free_download_request_ (struct DownloadRequest *dr); * @param sr result to start pinging for. */ void -GNUNET_FS_stop_probe_ping_task_ (struct GNUNET_FS_SearchResult *sr); +GNUNET_FS_stop_probe_ping_task_(struct GNUNET_FS_SearchResult *sr); /** * Context for controlling a download. */ -struct GNUNET_FS_DownloadContext -{ - +struct GNUNET_FS_DownloadContext { /** * Global FS context. */ @@ -1959,7 +1911,6 @@ struct GNUNET_FS_DownloadContext * Are we ready to issue requests (reconstructions are finished)? */ int issue_requests; - }; diff --git a/src/fs/fs_directory.c b/src/fs/fs_directory.c index 2dadc4835..ae7727cf0 100644 --- a/src/fs/fs_directory.c +++ b/src/fs/fs_directory.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_directory.c @@ -51,18 +51,18 @@ * we have no mime-type information (treat as #GNUNET_NO) */ int -GNUNET_FS_meta_data_test_for_directory (const struct GNUNET_CONTAINER_MetaData *md) +GNUNET_FS_meta_data_test_for_directory(const struct GNUNET_CONTAINER_MetaData *md) { char *mime; int ret; if (NULL == md) return GNUNET_SYSERR; - mime = GNUNET_CONTAINER_meta_data_get_by_type (md, EXTRACTOR_METATYPE_MIMETYPE); + mime = GNUNET_CONTAINER_meta_data_get_by_type(md, EXTRACTOR_METATYPE_MIMETYPE); if (NULL == mime) return GNUNET_SYSERR; - ret = (0 == strcasecmp (mime, GNUNET_FS_DIRECTORY_MIME)) ? GNUNET_YES : GNUNET_NO; - GNUNET_free (mime); + ret = (0 == strcasecmp(mime, GNUNET_FS_DIRECTORY_MIME)) ? GNUNET_YES : GNUNET_NO; + GNUNET_free(mime); return ret; } @@ -74,32 +74,30 @@ GNUNET_FS_meta_data_test_for_directory (const struct GNUNET_CONTAINER_MetaData * * @param md metadata to add mimetype to */ void -GNUNET_FS_meta_data_make_directory (struct GNUNET_CONTAINER_MetaData *md) +GNUNET_FS_meta_data_make_directory(struct GNUNET_CONTAINER_MetaData *md) { char *mime; mime = - GNUNET_CONTAINER_meta_data_get_by_type (md, EXTRACTOR_METATYPE_MIMETYPE); + GNUNET_CONTAINER_meta_data_get_by_type(md, EXTRACTOR_METATYPE_MIMETYPE); if (mime != NULL) - { - GNUNET_break (0 == strcmp (mime, GNUNET_FS_DIRECTORY_MIME)); - GNUNET_free (mime); - return; - } - GNUNET_CONTAINER_meta_data_insert (md, "", - EXTRACTOR_METATYPE_MIMETYPE, - EXTRACTOR_METAFORMAT_UTF8, "text/plain", - GNUNET_FS_DIRECTORY_MIME, - strlen (GNUNET_FS_DIRECTORY_MIME) + 1); + { + GNUNET_break(0 == strcmp(mime, GNUNET_FS_DIRECTORY_MIME)); + GNUNET_free(mime); + return; + } + GNUNET_CONTAINER_meta_data_insert(md, "", + EXTRACTOR_METATYPE_MIMETYPE, + EXTRACTOR_METAFORMAT_UTF8, "text/plain", + GNUNET_FS_DIRECTORY_MIME, + strlen(GNUNET_FS_DIRECTORY_MIME) + 1); } /** * Closure for 'find_full_data'. */ -struct GetFullDataClosure -{ - +struct GetFullDataClosure { /** * Extracted binary meta data. */ @@ -130,22 +128,22 @@ struct GetFullDataClosure * @return 0 to continue extracting, 1 to abort */ static int -find_full_data (void *cls, const char *plugin_name, - enum EXTRACTOR_MetaType type, enum EXTRACTOR_MetaFormat format, - const char *data_mime_type, const char *data, size_t data_len) +find_full_data(void *cls, const char *plugin_name, + enum EXTRACTOR_MetaType type, enum EXTRACTOR_MetaFormat format, + const char *data_mime_type, const char *data, size_t data_len) { struct GetFullDataClosure *gfdc = cls; if (type == EXTRACTOR_METATYPE_GNUNET_FULL_DATA) - { - gfdc->size = data_len; - if (data_len > 0) { - gfdc->data = GNUNET_malloc (data_len); - GNUNET_memcpy (gfdc->data, data, data_len); + gfdc->size = data_len; + if (data_len > 0) + { + gfdc->data = GNUNET_malloc(data_len); + GNUNET_memcpy(gfdc->data, data, data_len); + } + return 1; } - return 1; - } return 0; } @@ -176,11 +174,11 @@ find_full_data (void *cls, const char *plugin_name, * #GNUNET_SYSERR if @a data does not represent a directory */ int -GNUNET_FS_directory_list_contents (size_t size, - const void *data, - uint64_t offset, - GNUNET_FS_DirectoryEntryProcessor dep, - void *dep_cls) +GNUNET_FS_directory_list_contents(size_t size, + const void *data, + uint64_t offset, + GNUNET_FS_DirectoryEntryProcessor dep, + void *dep_cls) { struct GetFullDataClosure full_data; const char *cdata = data; @@ -194,132 +192,131 @@ GNUNET_FS_directory_list_contents (size_t size, char *filename; if ((offset == 0) && - ((size < 8 + sizeof (uint32_t)) || - (0 != memcmp (cdata, - GNUNET_FS_DIRECTORY_MAGIC, - 8)))) + ((size < 8 + sizeof(uint32_t)) || + (0 != memcmp(cdata, + GNUNET_FS_DIRECTORY_MAGIC, + 8)))) return GNUNET_SYSERR; pos = offset; if (offset == 0) - { - GNUNET_memcpy (&mdSize, - &cdata[8], - sizeof (uint32_t)); - mdSize = ntohl (mdSize); - if (mdSize > size - 8 - sizeof (uint32_t)) { - /* invalid size */ - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("MAGIC mismatch. This is not a GNUnet directory.\n")); - return GNUNET_SYSERR; - } - md = GNUNET_CONTAINER_meta_data_deserialize (&cdata[8 + sizeof (uint32_t)], - mdSize); - if (md == NULL) - { - GNUNET_break (0); - return GNUNET_SYSERR; /* malformed ! */ + GNUNET_memcpy(&mdSize, + &cdata[8], + sizeof(uint32_t)); + mdSize = ntohl(mdSize); + if (mdSize > size - 8 - sizeof(uint32_t)) + { + /* invalid size */ + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("MAGIC mismatch. This is not a GNUnet directory.\n")); + return GNUNET_SYSERR; + } + md = GNUNET_CONTAINER_meta_data_deserialize(&cdata[8 + sizeof(uint32_t)], + mdSize); + if (md == NULL) + { + GNUNET_break(0); + return GNUNET_SYSERR; /* malformed ! */ + } + dep(dep_cls, + NULL, + NULL, + md, + 0, + NULL); + GNUNET_CONTAINER_meta_data_destroy(md); + pos = 8 + sizeof(uint32_t) + mdSize; } - dep (dep_cls, - NULL, - NULL, - md, - 0, - NULL); - GNUNET_CONTAINER_meta_data_destroy (md); - pos = 8 + sizeof (uint32_t) + mdSize; - } while (pos < size) - { - /* find end of URI */ - if (cdata[pos] == '\0') - { - /* URI is never empty, must be end of block, - * skip to next alignment */ - align = ((pos / DBLOCK_SIZE) + 1) * DBLOCK_SIZE; - if (align == pos) - { - /* if we were already aligned, still skip a block! */ - align += DBLOCK_SIZE; - } - pos = align; - if (pos >= size) - { - /* malformed - or partial download... */ - break; - } - } - epos = pos; - while ((epos < size) && (cdata[epos] != '\0')) - epos++; - if (epos >= size) - return GNUNET_NO; /* malformed - or partial download */ - - uri = GNUNET_FS_uri_parse (&cdata[pos], &emsg); - pos = epos + 1; - if (NULL == uri) - { - GNUNET_free (emsg); - pos--; /* go back to '\0' to force going to next alignment */ - continue; - } - if (GNUNET_FS_uri_test_ksk (uri)) { - GNUNET_FS_uri_destroy (uri); - GNUNET_break (0); - return GNUNET_NO; /* illegal in directory! */ - } + /* find end of URI */ + if (cdata[pos] == '\0') + { + /* URI is never empty, must be end of block, + * skip to next alignment */ + align = ((pos / DBLOCK_SIZE) + 1) * DBLOCK_SIZE; + if (align == pos) + { + /* if we were already aligned, still skip a block! */ + align += DBLOCK_SIZE; + } + pos = align; + if (pos >= size) + { + /* malformed - or partial download... */ + break; + } + } + epos = pos; + while ((epos < size) && (cdata[epos] != '\0')) + epos++; + if (epos >= size) + return GNUNET_NO; /* malformed - or partial download */ + + uri = GNUNET_FS_uri_parse(&cdata[pos], &emsg); + pos = epos + 1; + if (NULL == uri) + { + GNUNET_free(emsg); + pos--; /* go back to '\0' to force going to next alignment */ + continue; + } + if (GNUNET_FS_uri_test_ksk(uri)) + { + GNUNET_FS_uri_destroy(uri); + GNUNET_break(0); + return GNUNET_NO; /* illegal in directory! */ + } - GNUNET_memcpy (&mdSize, - &cdata[pos], - sizeof (uint32_t)); - mdSize = ntohl (mdSize); - pos += sizeof (uint32_t); - if (pos + mdSize > size) - { - GNUNET_FS_uri_destroy (uri); - return GNUNET_NO; /* malformed - or partial download */ - } + GNUNET_memcpy(&mdSize, + &cdata[pos], + sizeof(uint32_t)); + mdSize = ntohl(mdSize); + pos += sizeof(uint32_t); + if (pos + mdSize > size) + { + GNUNET_FS_uri_destroy(uri); + return GNUNET_NO; /* malformed - or partial download */ + } - md = GNUNET_CONTAINER_meta_data_deserialize (&cdata[pos], - mdSize); - if (NULL == md) - { - GNUNET_FS_uri_destroy (uri); - GNUNET_break (0); - return GNUNET_NO; /* malformed ! */ - } - pos += mdSize; - filename = - GNUNET_CONTAINER_meta_data_get_by_type (md, - EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME); - full_data.size = 0; - full_data.data = NULL; - GNUNET_CONTAINER_meta_data_iterate (md, - &find_full_data, - &full_data); - if (NULL != dep) - { - dep (dep_cls, - filename, - uri, - md, - full_data.size, - full_data.data); + md = GNUNET_CONTAINER_meta_data_deserialize(&cdata[pos], + mdSize); + if (NULL == md) + { + GNUNET_FS_uri_destroy(uri); + GNUNET_break(0); + return GNUNET_NO; /* malformed ! */ + } + pos += mdSize; + filename = + GNUNET_CONTAINER_meta_data_get_by_type(md, + EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME); + full_data.size = 0; + full_data.data = NULL; + GNUNET_CONTAINER_meta_data_iterate(md, + &find_full_data, + &full_data); + if (NULL != dep) + { + dep(dep_cls, + filename, + uri, + md, + full_data.size, + full_data.data); + } + GNUNET_free_non_null(full_data.data); + GNUNET_free_non_null(filename); + GNUNET_CONTAINER_meta_data_destroy(md); + GNUNET_FS_uri_destroy(uri); } - GNUNET_free_non_null (full_data.data); - GNUNET_free_non_null (filename); - GNUNET_CONTAINER_meta_data_destroy (md); - GNUNET_FS_uri_destroy (uri); - } return GNUNET_OK; } /** * Entries in the directory (builder). */ -struct BuilderEntry -{ +struct BuilderEntry { /** * This is a linked list. */ @@ -334,8 +331,7 @@ struct BuilderEntry /** * Internal state of a directory builder. */ -struct GNUNET_FS_DirectoryBuilder -{ +struct GNUNET_FS_DirectoryBuilder { /** * Meta-data for the directory itself. */ @@ -359,17 +355,17 @@ struct GNUNET_FS_DirectoryBuilder * @param mdir metadata for the directory */ struct GNUNET_FS_DirectoryBuilder * -GNUNET_FS_directory_builder_create (const struct GNUNET_CONTAINER_MetaData - *mdir) +GNUNET_FS_directory_builder_create(const struct GNUNET_CONTAINER_MetaData + *mdir) { struct GNUNET_FS_DirectoryBuilder *ret; - ret = GNUNET_new (struct GNUNET_FS_DirectoryBuilder); + ret = GNUNET_new(struct GNUNET_FS_DirectoryBuilder); if (mdir != NULL) - ret->meta = GNUNET_CONTAINER_meta_data_duplicate (mdir); + ret->meta = GNUNET_CONTAINER_meta_data_duplicate(mdir); else - ret->meta = GNUNET_CONTAINER_meta_data_create (); - GNUNET_FS_meta_data_make_directory (ret->meta); + ret->meta = GNUNET_CONTAINER_meta_data_create(); + GNUNET_FS_meta_data_make_directory(ret->meta); return ret; } @@ -385,10 +381,10 @@ GNUNET_FS_directory_builder_create (const struct GNUNET_CONTAINER_MetaData * by the uri which must be of type LOC or CHK */ void -GNUNET_FS_directory_builder_add (struct GNUNET_FS_DirectoryBuilder *bld, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *md, - const void *data) +GNUNET_FS_directory_builder_add(struct GNUNET_FS_DirectoryBuilder *bld, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *md, + const void *data) { struct GNUNET_FS_Uri *curi; struct BuilderEntry *e; @@ -404,71 +400,71 @@ GNUNET_FS_directory_builder_add (struct GNUNET_FS_DirectoryBuilder *bld, struct GNUNET_CONTAINER_MetaData *meta; const struct GNUNET_CONTAINER_MetaData *meta_use; - GNUNET_assert (!GNUNET_FS_uri_test_ksk (uri)); + GNUNET_assert(!GNUNET_FS_uri_test_ksk(uri)); if (NULL != data) - { - GNUNET_assert (!GNUNET_FS_uri_test_sks (uri)); - if (GNUNET_FS_uri_test_chk (uri)) { - fsize = GNUNET_FS_uri_chk_get_file_size (uri); + GNUNET_assert(!GNUNET_FS_uri_test_sks(uri)); + if (GNUNET_FS_uri_test_chk(uri)) + { + fsize = GNUNET_FS_uri_chk_get_file_size(uri); + } + else + { + curi = GNUNET_FS_uri_loc_get_uri(uri); + GNUNET_assert(NULL != curi); + fsize = GNUNET_FS_uri_chk_get_file_size(curi); + GNUNET_FS_uri_destroy(curi); + } } - else + else { - curi = GNUNET_FS_uri_loc_get_uri (uri); - GNUNET_assert (NULL != curi); - fsize = GNUNET_FS_uri_chk_get_file_size (curi); - GNUNET_FS_uri_destroy (curi); + fsize = 0; /* not given */ } - } - else - { - fsize = 0; /* not given */ - } if (fsize > MAX_INLINE_SIZE) fsize = 0; /* too large */ - uris = GNUNET_FS_uri_to_string (uri); - slen = strlen (uris) + 1; - mds = GNUNET_CONTAINER_meta_data_get_serialized_size (md); + uris = GNUNET_FS_uri_to_string(uri); + slen = strlen(uris) + 1; + mds = GNUNET_CONTAINER_meta_data_get_serialized_size(md); meta_use = md; meta = NULL; if (fsize > 0) - { - meta = GNUNET_CONTAINER_meta_data_duplicate (md); - GNUNET_CONTAINER_meta_data_insert (meta, "", - EXTRACTOR_METATYPE_GNUNET_FULL_DATA, - EXTRACTOR_METAFORMAT_BINARY, NULL, data, - fsize); - mdxs = GNUNET_CONTAINER_meta_data_get_serialized_size (meta); - if ((slen + sizeof (uint32_t) + mdxs - 1) / DBLOCK_SIZE == - (slen + sizeof (uint32_t) + mds - 1) / DBLOCK_SIZE) { - /* adding full data would not cause us to cross - * additional blocks, so add it! */ - meta_use = meta; - mds = mdxs; + meta = GNUNET_CONTAINER_meta_data_duplicate(md); + GNUNET_CONTAINER_meta_data_insert(meta, "", + EXTRACTOR_METATYPE_GNUNET_FULL_DATA, + EXTRACTOR_METAFORMAT_BINARY, NULL, data, + fsize); + mdxs = GNUNET_CONTAINER_meta_data_get_serialized_size(meta); + if ((slen + sizeof(uint32_t) + mdxs - 1) / DBLOCK_SIZE == + (slen + sizeof(uint32_t) + mds - 1) / DBLOCK_SIZE) + { + /* adding full data would not cause us to cross + * additional blocks, so add it! */ + meta_use = meta; + mds = mdxs; + } } - } if (mds > GNUNET_MAX_MALLOC_CHECKED / 2) mds = GNUNET_MAX_MALLOC_CHECKED / 2; - e = GNUNET_malloc (sizeof (struct BuilderEntry) + slen + mds + - sizeof (uint32_t)); - ser = (char *) &e[1]; - GNUNET_memcpy (ser, uris, slen); - GNUNET_free (uris); - sptr = &ser[slen + sizeof (uint32_t)]; + e = GNUNET_malloc(sizeof(struct BuilderEntry) + slen + mds + + sizeof(uint32_t)); + ser = (char *)&e[1]; + GNUNET_memcpy(ser, uris, slen); + GNUNET_free(uris); + sptr = &ser[slen + sizeof(uint32_t)]; ret = - GNUNET_CONTAINER_meta_data_serialize (meta_use, &sptr, mds, - GNUNET_CONTAINER_META_DATA_SERIALIZE_PART); + GNUNET_CONTAINER_meta_data_serialize(meta_use, &sptr, mds, + GNUNET_CONTAINER_META_DATA_SERIALIZE_PART); if (NULL != meta) - GNUNET_CONTAINER_meta_data_destroy (meta); + GNUNET_CONTAINER_meta_data_destroy(meta); if (ret == -1) mds = 0; else mds = ret; - big = htonl (mds); - GNUNET_memcpy (&ser[slen], &big, sizeof (uint32_t)); - e->len = slen + sizeof (uint32_t) + mds; + big = htonl(mds); + GNUNET_memcpy(&ser[slen], &big, sizeof(uint32_t)); + e->len = slen + sizeof(uint32_t) + mds; e->next = bld->head; bld->head = e; bld->count++; @@ -481,7 +477,7 @@ GNUNET_FS_directory_builder_add (struct GNUNET_FS_DirectoryBuilder *bld, * after alignment to the DBLOCK_SIZE. */ static size_t -do_align (size_t start_position, size_t end_position) +do_align(size_t start_position, size_t end_position) { size_t align; @@ -502,8 +498,8 @@ do_align (size_t start_position, size_t end_position) * @param perm the permutation of the blocks (updated) */ static void -block_align (size_t start, unsigned int count, const size_t * sizes, - unsigned int *perm) +block_align(size_t start, unsigned int count, const size_t * sizes, + unsigned int *perm) { unsigned int i; unsigned int j; @@ -517,46 +513,46 @@ block_align (size_t start, unsigned int count, const size_t * sizes, cpos = start; for (i = 0; i < count; i++) - { - start = cpos; - badness = 0x7FFFFFFF; - best = -1; - for (j = i; j < count; j++) { - cval = perm[j]; - cend = cpos + sizes[cval]; - if (cpos % DBLOCK_SIZE == 0) - { - /* prefer placing the largest blocks first */ - cbad = -(cend % DBLOCK_SIZE); - } - else - { - if (cpos / DBLOCK_SIZE == cend / DBLOCK_SIZE) - { - /* Data fits into the same block! Prefer small left-overs! */ - cbad = DBLOCK_SIZE - cend % DBLOCK_SIZE; - } - else + start = cpos; + badness = 0x7FFFFFFF; + best = -1; + for (j = i; j < count; j++) { - /* Would have to waste space to re-align, add big factor, this - * case is a real loss (proportional to space wasted)! */ - cbad = DBLOCK_SIZE * (DBLOCK_SIZE - cpos % DBLOCK_SIZE); + cval = perm[j]; + cend = cpos + sizes[cval]; + if (cpos % DBLOCK_SIZE == 0) + { + /* prefer placing the largest blocks first */ + cbad = -(cend % DBLOCK_SIZE); + } + else + { + if (cpos / DBLOCK_SIZE == cend / DBLOCK_SIZE) + { + /* Data fits into the same block! Prefer small left-overs! */ + cbad = DBLOCK_SIZE - cend % DBLOCK_SIZE; + } + else + { + /* Would have to waste space to re-align, add big factor, this + * case is a real loss (proportional to space wasted)! */ + cbad = DBLOCK_SIZE * (DBLOCK_SIZE - cpos % DBLOCK_SIZE); + } + } + if (cbad < badness) + { + best = j; + badness = cbad; + } } - } - if (cbad < badness) - { - best = j; - badness = cbad; - } + GNUNET_assert(best != -1); + tmp = perm[i]; + perm[i] = perm[best]; + perm[best] = tmp; + cpos += sizes[perm[i]]; + cpos = do_align(start, cpos); } - GNUNET_assert (best != -1); - tmp = perm[i]; - perm[i] = perm[best]; - perm[best] = tmp; - cpos += sizes[perm[i]]; - cpos = do_align (start, cpos); - } } @@ -571,9 +567,9 @@ block_align (size_t start, unsigned int count, const size_t * sizes, * @return #GNUNET_OK on success */ int -GNUNET_FS_directory_builder_finish (struct GNUNET_FS_DirectoryBuilder *bld, - size_t * rsize, - void **rdata) +GNUNET_FS_directory_builder_finish(struct GNUNET_FS_DirectoryBuilder *bld, + size_t * rsize, + void **rdata) { char *data; char *sptr; @@ -589,82 +585,82 @@ GNUNET_FS_directory_builder_finish (struct GNUNET_FS_DirectoryBuilder *bld, ssize_t ret; uint32_t big; - size = strlen (GNUNET_DIRECTORY_MAGIC) + sizeof (uint32_t); - size += GNUNET_CONTAINER_meta_data_get_serialized_size (bld->meta); + size = strlen(GNUNET_DIRECTORY_MAGIC) + sizeof(uint32_t); + size += GNUNET_CONTAINER_meta_data_get_serialized_size(bld->meta); sizes = NULL; perm = NULL; bes = NULL; if (0 < bld->count) - { - sizes = GNUNET_new_array (bld->count, - size_t); - perm = GNUNET_new_array (bld->count, - unsigned int); - bes = GNUNET_new_array (bld->count, - struct BuilderEntry *); - pos = bld->head; - for (i = 0; i < bld->count; i++) - { - perm[i] = i; - bes[i] = pos; - sizes[i] = pos->len; - pos = pos->next; - } - block_align (size, bld->count, sizes, perm); - /* compute final size with alignment */ - for (i = 0; i < bld->count; i++) { - psize = size; - size += sizes[perm[i]]; - size = do_align (psize, size); + sizes = GNUNET_new_array(bld->count, + size_t); + perm = GNUNET_new_array(bld->count, + unsigned int); + bes = GNUNET_new_array(bld->count, + struct BuilderEntry *); + pos = bld->head; + for (i = 0; i < bld->count; i++) + { + perm[i] = i; + bes[i] = pos; + sizes[i] = pos->len; + pos = pos->next; + } + block_align(size, bld->count, sizes, perm); + /* compute final size with alignment */ + for (i = 0; i < bld->count; i++) + { + psize = size; + size += sizes[perm[i]]; + size = do_align(psize, size); + } } - } *rsize = size; - data = GNUNET_malloc_large (size); + data = GNUNET_malloc_large(size); if (data == NULL) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "malloc"); - *rsize = 0; - *rdata = NULL; - GNUNET_free_non_null (sizes); - GNUNET_free_non_null (perm); - GNUNET_free_non_null (bes); - return GNUNET_SYSERR; - } + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "malloc"); + *rsize = 0; + *rdata = NULL; + GNUNET_free_non_null(sizes); + GNUNET_free_non_null(perm); + GNUNET_free_non_null(bes); + return GNUNET_SYSERR; + } *rdata = data; - GNUNET_memcpy (data, - GNUNET_DIRECTORY_MAGIC, - strlen (GNUNET_DIRECTORY_MAGIC)); - off = strlen (GNUNET_DIRECTORY_MAGIC); + GNUNET_memcpy(data, + GNUNET_DIRECTORY_MAGIC, + strlen(GNUNET_DIRECTORY_MAGIC)); + off = strlen(GNUNET_DIRECTORY_MAGIC); - sptr = &data[off + sizeof (uint32_t)]; + sptr = &data[off + sizeof(uint32_t)]; ret = - GNUNET_CONTAINER_meta_data_serialize (bld->meta, - &sptr, - size - off - sizeof (uint32_t), - GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL); - GNUNET_assert (ret != -1); - big = htonl (ret); - GNUNET_memcpy (&data[off], - &big, - sizeof (uint32_t)); - off += sizeof (uint32_t) + ret; + GNUNET_CONTAINER_meta_data_serialize(bld->meta, + &sptr, + size - off - sizeof(uint32_t), + GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL); + GNUNET_assert(ret != -1); + big = htonl(ret); + GNUNET_memcpy(&data[off], + &big, + sizeof(uint32_t)); + off += sizeof(uint32_t) + ret; for (j = 0; j < bld->count; j++) - { - i = perm[j]; - psize = off; - off += sizes[i]; - off = do_align (psize, off); - GNUNET_memcpy (&data[off - sizes[i]], &(bes[i])[1], sizes[i]); - GNUNET_free (bes[i]); - } - GNUNET_free_non_null (sizes); - GNUNET_free_non_null (perm); - GNUNET_free_non_null (bes); - GNUNET_assert (off == size); - GNUNET_CONTAINER_meta_data_destroy (bld->meta); - GNUNET_free (bld); + { + i = perm[j]; + psize = off; + off += sizes[i]; + off = do_align(psize, off); + GNUNET_memcpy(&data[off - sizes[i]], &(bes[i])[1], sizes[i]); + GNUNET_free(bes[i]); + } + GNUNET_free_non_null(sizes); + GNUNET_free_non_null(perm); + GNUNET_free_non_null(bes); + GNUNET_assert(off == size); + GNUNET_CONTAINER_meta_data_destroy(bld->meta); + GNUNET_free(bld); return GNUNET_OK; } diff --git a/src/fs/fs_dirmetascan.c b/src/fs/fs_dirmetascan.c index dd207e2c9..9202de5ab 100644 --- a/src/fs/fs_dirmetascan.c +++ b/src/fs/fs_dirmetascan.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_dirmetascan.c @@ -35,9 +35,7 @@ * An opaque structure a pointer to which is returned to the * caller to be used to control the scanner. */ -struct GNUNET_FS_DirScanner -{ - +struct GNUNET_FS_DirScanner { /** * Helper process. */ @@ -96,20 +94,20 @@ struct GNUNET_FS_DirScanner * @param ds directory scanner structure */ void -GNUNET_FS_directory_scan_abort (struct GNUNET_FS_DirScanner *ds) +GNUNET_FS_directory_scan_abort(struct GNUNET_FS_DirScanner *ds) { /* terminate helper */ if (NULL != ds->helper) - GNUNET_HELPER_stop (ds->helper, GNUNET_NO); + GNUNET_HELPER_stop(ds->helper, GNUNET_NO); /* free resources */ if (NULL != ds->toplevel) - GNUNET_FS_share_tree_free (ds->toplevel); + GNUNET_FS_share_tree_free(ds->toplevel); if (NULL != ds->stop_task) - GNUNET_SCHEDULER_cancel (ds->stop_task); - GNUNET_free_non_null (ds->ex_arg); - GNUNET_free (ds->filename_expanded); - GNUNET_free (ds); + GNUNET_SCHEDULER_cancel(ds->stop_task); + GNUNET_free_non_null(ds->ex_arg); + GNUNET_free(ds->filename_expanded); + GNUNET_free(ds); } @@ -122,16 +120,16 @@ GNUNET_FS_directory_scan_abort (struct GNUNET_FS_DirScanner *ds) * @return the results of the scan (a directory tree) */ struct GNUNET_FS_ShareTreeItem * -GNUNET_FS_directory_scan_get_result (struct GNUNET_FS_DirScanner *ds) +GNUNET_FS_directory_scan_get_result(struct GNUNET_FS_DirScanner *ds) { struct GNUNET_FS_ShareTreeItem *result; /* check that we're actually done */ - GNUNET_assert (NULL == ds->helper); + GNUNET_assert(NULL == ds->helper); /* preserve result */ result = ds->toplevel; ds->toplevel = NULL; - GNUNET_FS_directory_scan_abort (ds); + GNUNET_FS_directory_scan_abort(ds); return result; } @@ -144,35 +142,35 @@ GNUNET_FS_directory_scan_get_result (struct GNUNET_FS_DirScanner *ds) * @return next file, NULL for none */ static struct GNUNET_FS_ShareTreeItem * -advance (struct GNUNET_FS_ShareTreeItem *pos) +advance(struct GNUNET_FS_ShareTreeItem *pos) { int moved; - GNUNET_assert (NULL != pos); + GNUNET_assert(NULL != pos); moved = 0; /* must not terminate, even on file, otherwise "normal" */ while ((pos->is_directory == GNUNET_YES) || (0 == moved)) - { - if ((moved != -1) && (NULL != pos->children_head)) - { - pos = pos->children_head; - moved = 1; /* can terminate if file */ - continue; - } - if (NULL != pos->next) - { - pos = pos->next; - moved = 1; /* can terminate if file */ - continue; - } - if (NULL != pos->parent) { - pos = pos->parent; - moved = -1; /* force move to 'next' or 'parent' */ - continue; + if ((moved != -1) && (NULL != pos->children_head)) + { + pos = pos->children_head; + moved = 1; /* can terminate if file */ + continue; + } + if (NULL != pos->next) + { + pos = pos->next; + moved = 1; /* can terminate if file */ + continue; + } + if (NULL != pos->parent) + { + pos = pos->parent; + moved = -1; /* force move to 'next' or 'parent' */ + continue; + } + /* no more options, end of traversal */ + return NULL; } - /* no more options, end of traversal */ - return NULL; - } return pos; } @@ -186,30 +184,30 @@ advance (struct GNUNET_FS_ShareTreeItem *pos) * @return new entry that was just created */ static struct GNUNET_FS_ShareTreeItem * -expand_tree (struct GNUNET_FS_ShareTreeItem *parent, - const char *filename, - int is_directory) +expand_tree(struct GNUNET_FS_ShareTreeItem *parent, + const char *filename, + int is_directory) { struct GNUNET_FS_ShareTreeItem *chld; size_t slen; - chld = GNUNET_new (struct GNUNET_FS_ShareTreeItem); + chld = GNUNET_new(struct GNUNET_FS_ShareTreeItem); chld->parent = parent; - chld->filename = GNUNET_strdup (filename); - GNUNET_asprintf (&chld->short_filename, - "%s%s", - GNUNET_STRINGS_get_short_name (filename), - is_directory == GNUNET_YES ? "/" : ""); + chld->filename = GNUNET_strdup(filename); + GNUNET_asprintf(&chld->short_filename, + "%s%s", + GNUNET_STRINGS_get_short_name(filename), + is_directory == GNUNET_YES ? "/" : ""); /* make sure we do not end with '//' */ - slen = strlen (chld->short_filename); + slen = strlen(chld->short_filename); if ((slen >= 2) && (chld->short_filename[slen - 1] == '/') && (chld->short_filename[slen - 2] == '/')) chld->short_filename[slen - 1] = '\0'; chld->is_directory = is_directory; if (NULL != parent) - GNUNET_CONTAINER_DLL_insert (parent->children_head, - parent->children_tail, - chld); + GNUNET_CONTAINER_DLL_insert(parent->children_head, + parent->children_tail, + chld); return chld; } @@ -220,20 +218,20 @@ expand_tree (struct GNUNET_FS_ShareTreeItem *parent, * @param cls the 'struct GNUNET_FS_DirScanner' */ static void -finish_scan (void *cls) +finish_scan(void *cls) { struct GNUNET_FS_DirScanner *ds = cls; ds->stop_task = NULL; if (NULL != ds->helper) - { - GNUNET_HELPER_stop (ds->helper, GNUNET_NO); - ds->helper = NULL; - } - ds->progress_callback (ds->progress_callback_cls, - NULL, - GNUNET_SYSERR, - GNUNET_FS_DIRSCANNER_FINISHED); + { + GNUNET_HELPER_stop(ds->helper, GNUNET_NO); + ds->helper = NULL; + } + ds->progress_callback(ds->progress_callback_cls, + NULL, + GNUNET_SYSERR, + GNUNET_FS_DIRSCANNER_FINISHED); } @@ -248,168 +246,175 @@ finish_scan (void *cls) * #GNUNET_SYSERR to stop further processing with error */ static int -process_helper_msgs (void *cls, const struct GNUNET_MessageHeader *msg) +process_helper_msgs(void *cls, const struct GNUNET_MessageHeader *msg) { struct GNUNET_FS_DirScanner *ds = cls; const char *filename; size_t left; #if 0 - fprintf (stderr, - "DMS parses %u-byte message of type %u\n", - (unsigned int) ntohs (msg->size), - (unsigned int) ntohs (msg->type)); + fprintf(stderr, + "DMS parses %u-byte message of type %u\n", + (unsigned int)ntohs(msg->size), + (unsigned int)ntohs(msg->type)); #endif - left = ntohs (msg->size) - sizeof (struct GNUNET_MessageHeader); - filename = (const char *) &msg[1]; - switch (ntohs (msg->type)) - { - case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_FILE: - if (filename[left - 1] != '\0') - { - GNUNET_break (0); - break; - } - ds->progress_callback (ds->progress_callback_cls, - filename, - GNUNET_NO, - GNUNET_FS_DIRSCANNER_FILE_START); - if (NULL == ds->toplevel) - { - ds->toplevel = expand_tree (ds->pos, filename, GNUNET_NO); - } - else + left = ntohs(msg->size) - sizeof(struct GNUNET_MessageHeader); + filename = (const char *)&msg[1]; + switch (ntohs(msg->type)) { - GNUNET_assert (NULL != ds->pos); - (void) expand_tree (ds->pos, filename, GNUNET_NO); - } - return GNUNET_OK; - case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_DIRECTORY: - if (filename[left - 1] != '\0') - { - GNUNET_break (0); + case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_FILE: + if (filename[left - 1] != '\0') + { + GNUNET_break(0); + break; + } + ds->progress_callback(ds->progress_callback_cls, + filename, + GNUNET_NO, + GNUNET_FS_DIRSCANNER_FILE_START); + if (NULL == ds->toplevel) + { + ds->toplevel = expand_tree(ds->pos, filename, GNUNET_NO); + } + else + { + GNUNET_assert(NULL != ds->pos); + (void)expand_tree(ds->pos, filename, GNUNET_NO); + } + return GNUNET_OK; + + case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_DIRECTORY: + if (filename[left - 1] != '\0') + { + GNUNET_break(0); + break; + } + if (0 == strcmp("..", filename)) + { + if (NULL == ds->pos) + { + GNUNET_break(0); + break; + } + ds->pos = ds->pos->parent; + return GNUNET_OK; + } + ds->progress_callback(ds->progress_callback_cls, + filename, + GNUNET_YES, + GNUNET_FS_DIRSCANNER_FILE_START); + ds->pos = expand_tree(ds->pos, filename, GNUNET_YES); + if (NULL == ds->toplevel) + ds->toplevel = ds->pos; + return GNUNET_OK; + + case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR: break; - } - if (0 == strcmp ("..", filename)) - { - if (NULL == ds->pos) - { - GNUNET_break (0); + + case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_SKIP_FILE: + if ('\0' != filename[left - 1]) break; - } - ds->pos = ds->pos->parent; + ds->progress_callback(ds->progress_callback_cls, + filename, + GNUNET_SYSERR, + GNUNET_FS_DIRSCANNER_FILE_IGNORED); return GNUNET_OK; - } - ds->progress_callback (ds->progress_callback_cls, - filename, - GNUNET_YES, - GNUNET_FS_DIRSCANNER_FILE_START); - ds->pos = expand_tree (ds->pos, filename, GNUNET_YES); - if (NULL == ds->toplevel) - ds->toplevel = ds->pos; - return GNUNET_OK; - case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR: - break; - case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_SKIP_FILE: - if ('\0' != filename[left - 1]) - break; - ds->progress_callback (ds->progress_callback_cls, - filename, - GNUNET_SYSERR, - GNUNET_FS_DIRSCANNER_FILE_IGNORED); - return GNUNET_OK; - case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_COUNTING_DONE: - if (0 != left) - { - GNUNET_break (0); - break; - } - if (NULL == ds->toplevel) - break; - ds->progress_callback (ds->progress_callback_cls, - NULL, - GNUNET_SYSERR, - GNUNET_FS_DIRSCANNER_ALL_COUNTED); - ds->pos = ds->toplevel; - if (GNUNET_YES == ds->pos->is_directory) - ds->pos = advance (ds->pos); - return GNUNET_OK; - case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_META_DATA: { - size_t nlen; - const char *end; - - if (NULL == ds->pos) - { - GNUNET_break (0); - break; - } - end = memchr (filename, 0, left); - if (NULL == end) - { - GNUNET_break (0); - break; - } - end++; - nlen = end - filename; - left -= nlen; - if (0 != strcmp (filename, ds->pos->filename)) - { - GNUNET_break (0); - break; - } - ds->progress_callback (ds->progress_callback_cls, - filename, - GNUNET_YES, - GNUNET_FS_DIRSCANNER_EXTRACT_FINISHED); - if (0 < left) - { - ds->pos->meta = GNUNET_CONTAINER_meta_data_deserialize (end, left); - if (NULL == ds->pos->meta) - { - GNUNET_break (0); + + case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_COUNTING_DONE: + if (0 != left) + { + GNUNET_break(0); + break; + } + if (NULL == ds->toplevel) break; - } - /* having full filenames is too dangerous; always make sure we clean them up */ - GNUNET_CONTAINER_meta_data_delete (ds->pos->meta, - EXTRACTOR_METATYPE_FILENAME, - NULL, - 0); - /* instead, put in our 'safer' original filename */ - GNUNET_CONTAINER_meta_data_insert (ds->pos->meta, - "", - EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME, - EXTRACTOR_METAFORMAT_UTF8, - "text/plain", - ds->pos->short_filename, - strlen (ds->pos->short_filename) + 1); - } - ds->pos->ksk_uri = GNUNET_FS_uri_ksk_create_from_meta_data (ds->pos->meta); - ds->pos = advance (ds->pos); - return GNUNET_OK; - } - case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_FINISHED: - if (NULL != ds->pos) - { - GNUNET_break (0); - break; + ds->progress_callback(ds->progress_callback_cls, + NULL, + GNUNET_SYSERR, + GNUNET_FS_DIRSCANNER_ALL_COUNTED); + ds->pos = ds->toplevel; + if (GNUNET_YES == ds->pos->is_directory) + ds->pos = advance(ds->pos); + return GNUNET_OK; + + case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_META_DATA: { + size_t nlen; + const char *end; + + if (NULL == ds->pos) + { + GNUNET_break(0); + break; + } + end = memchr(filename, 0, left); + if (NULL == end) + { + GNUNET_break(0); + break; + } + end++; + nlen = end - filename; + left -= nlen; + if (0 != strcmp(filename, ds->pos->filename)) + { + GNUNET_break(0); + break; + } + ds->progress_callback(ds->progress_callback_cls, + filename, + GNUNET_YES, + GNUNET_FS_DIRSCANNER_EXTRACT_FINISHED); + if (0 < left) + { + ds->pos->meta = GNUNET_CONTAINER_meta_data_deserialize(end, left); + if (NULL == ds->pos->meta) + { + GNUNET_break(0); + break; + } + /* having full filenames is too dangerous; always make sure we clean them up */ + GNUNET_CONTAINER_meta_data_delete(ds->pos->meta, + EXTRACTOR_METATYPE_FILENAME, + NULL, + 0); + /* instead, put in our 'safer' original filename */ + GNUNET_CONTAINER_meta_data_insert(ds->pos->meta, + "", + EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME, + EXTRACTOR_METAFORMAT_UTF8, + "text/plain", + ds->pos->short_filename, + strlen(ds->pos->short_filename) + 1); + } + ds->pos->ksk_uri = GNUNET_FS_uri_ksk_create_from_meta_data(ds->pos->meta); + ds->pos = advance(ds->pos); + return GNUNET_OK; } - if (0 != left) - { - GNUNET_break (0); + + case GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_FINISHED: + if (NULL != ds->pos) + { + GNUNET_break(0); + break; + } + if (0 != left) + { + GNUNET_break(0); + break; + } + if (NULL == ds->toplevel) + break; + ds->stop_task = GNUNET_SCHEDULER_add_now(&finish_scan, ds); + return GNUNET_OK; + + default: + GNUNET_break(0); break; } - if (NULL == ds->toplevel) - break; - ds->stop_task = GNUNET_SCHEDULER_add_now (&finish_scan, ds); - return GNUNET_OK; - default: - GNUNET_break (0); - break; - } - ds->progress_callback (ds->progress_callback_cls, - NULL, - GNUNET_SYSERR, - GNUNET_FS_DIRSCANNER_INTERNAL_ERROR); + ds->progress_callback(ds->progress_callback_cls, + NULL, + GNUNET_SYSERR, + GNUNET_FS_DIRSCANNER_INTERNAL_ERROR); return GNUNET_OK; } @@ -420,17 +425,17 @@ process_helper_msgs (void *cls, const struct GNUNET_MessageHeader *msg) * @param cls the 'struct GNUNET_FS_DirScanner' callback. */ static void -helper_died_cb (void *cls) +helper_died_cb(void *cls) { struct GNUNET_FS_DirScanner *ds = cls; ds->helper = NULL; if (NULL != ds->stop_task) return; /* normal death, was finished */ - ds->progress_callback (ds->progress_callback_cls, - NULL, - GNUNET_SYSERR, - GNUNET_FS_DIRSCANNER_INTERNAL_ERROR); + ds->progress_callback(ds->progress_callback_cls, + NULL, + GNUNET_SYSERR, + GNUNET_FS_DIRSCANNER_INTERNAL_ERROR); } @@ -446,48 +451,48 @@ helper_died_cb (void *cls) * @return directory scanner object to be used for controlling the scanner */ struct GNUNET_FS_DirScanner * -GNUNET_FS_directory_scan_start (const char *filename, - int disable_extractor, - const char *ex, - GNUNET_FS_DirScannerProgressCallback cb, - void *cb_cls) +GNUNET_FS_directory_scan_start(const char *filename, + int disable_extractor, + const char *ex, + GNUNET_FS_DirScannerProgressCallback cb, + void *cb_cls) { struct stat sbuf; char *filename_expanded; struct GNUNET_FS_DirScanner *ds; - if (0 != stat (filename, &sbuf)) + if (0 != stat(filename, &sbuf)) return NULL; - filename_expanded = GNUNET_STRINGS_filename_expand (filename); + filename_expanded = GNUNET_STRINGS_filename_expand(filename); if (NULL == filename_expanded) return NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting to scan directory `%s'\n", - filename_expanded); - ds = GNUNET_new (struct GNUNET_FS_DirScanner); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting to scan directory `%s'\n", + filename_expanded); + ds = GNUNET_new(struct GNUNET_FS_DirScanner); ds->progress_callback = cb; ds->progress_callback_cls = cb_cls; ds->filename_expanded = filename_expanded; if (disable_extractor) - ds->ex_arg = GNUNET_strdup ("-"); + ds->ex_arg = GNUNET_strdup("-"); else - ds->ex_arg = (NULL != ex) ? GNUNET_strdup (ex) : NULL; + ds->ex_arg = (NULL != ex) ? GNUNET_strdup(ex) : NULL; ds->args[0] = "gnunet-helper-fs-publish"; ds->args[1] = ds->filename_expanded; ds->args[2] = ds->ex_arg; ds->args[3] = NULL; - ds->helper = GNUNET_HELPER_start (GNUNET_NO, - "gnunet-helper-fs-publish", - ds->args, - &process_helper_msgs, - &helper_died_cb, - ds); + ds->helper = GNUNET_HELPER_start(GNUNET_NO, + "gnunet-helper-fs-publish", + ds->args, + &process_helper_msgs, + &helper_died_cb, + ds); if (NULL == ds->helper) - { - GNUNET_free (filename_expanded); - GNUNET_free (ds); - return NULL; - } + { + GNUNET_free(filename_expanded); + GNUNET_free(ds); + return NULL; + } return ds; } diff --git a/src/fs/fs_download.c b/src/fs/fs_download.c index 59821f8a5..de70c53a8 100644 --- a/src/fs/fs_download.c +++ b/src/fs/fs_download.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_download.c * @brief download methods @@ -34,16 +34,16 @@ * use to try to do a recursive download. */ static int -is_recursive_download (struct GNUNET_FS_DownloadContext *dc) +is_recursive_download(struct GNUNET_FS_DownloadContext *dc) { return (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE)) && - ((GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (dc->meta)) || + ((GNUNET_YES == GNUNET_FS_meta_data_test_for_directory(dc->meta)) || ((NULL == dc->meta) && ((NULL == dc->filename) || - ((strlen (dc->filename) >= strlen (GNUNET_FS_DIRECTORY_EXT)) && - (NULL != strstr (dc->filename + strlen (dc->filename) - - strlen (GNUNET_FS_DIRECTORY_EXT), - GNUNET_FS_DIRECTORY_EXT)))))); + ((strlen(dc->filename) >= strlen(GNUNET_FS_DIRECTORY_EXT)) && + (NULL != strstr(dc->filename + strlen(dc->filename) - + strlen(GNUNET_FS_DIRECTORY_EXT), + GNUNET_FS_DIRECTORY_EXT)))))); } @@ -64,7 +64,7 @@ is_recursive_download (struct GNUNET_FS_DownloadContext *dc) * with the range for any other block */ static uint64_t -compute_disk_offset (uint64_t fsize, uint64_t off, unsigned int depth) +compute_disk_offset(uint64_t fsize, uint64_t off, unsigned int depth) { unsigned int i; uint64_t lsize; /* what is the size of all IBlocks for depth "i"? */ @@ -77,18 +77,18 @@ compute_disk_offset (uint64_t fsize, uint64_t off, unsigned int depth) * to full DBLOCK_SIZE */ loff = ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * DBLOCK_SIZE; lsize = - ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * sizeof (struct ContentHashKey); - GNUNET_assert (0 == (off % DBLOCK_SIZE)); + ((fsize + DBLOCK_SIZE - 1) / DBLOCK_SIZE) * sizeof(struct ContentHashKey); + GNUNET_assert(0 == (off % DBLOCK_SIZE)); ioff = (off / DBLOCK_SIZE); for (i = 1; i < depth; i++) - { - loff += lsize; - lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE; - GNUNET_assert (lsize > 0); - GNUNET_assert (0 == (ioff % CHK_PER_INODE)); - ioff /= CHK_PER_INODE; - } - return loff + ioff * sizeof (struct ContentHashKey); + { + loff += lsize; + lsize = (lsize + CHK_PER_INODE - 1) / CHK_PER_INODE; + GNUNET_assert(lsize > 0); + GNUNET_assert(0 == (ioff % CHK_PER_INODE)); + ioff /= CHK_PER_INODE; + } + return loff + ioff * sizeof(struct ContentHashKey); } @@ -100,8 +100,8 @@ compute_disk_offset (uint64_t fsize, uint64_t off, unsigned int depth) * @param dc overall download context */ void -GNUNET_FS_download_make_status_ (struct GNUNET_FS_ProgressInfo *pi, - struct GNUNET_FS_DownloadContext *dc) +GNUNET_FS_download_make_status_(struct GNUNET_FS_ProgressInfo *pi, + struct GNUNET_FS_DownloadContext *dc) { pi->value.download.dc = dc; pi->value.download.cctx = dc->client_info; @@ -114,26 +114,24 @@ GNUNET_FS_download_make_status_ (struct GNUNET_FS_ProgressInfo *pi, pi->value.download.size = dc->length; /* FIXME: Fix duration calculation to account for pauses */ pi->value.download.duration = - GNUNET_TIME_absolute_get_duration (dc->start_time); + GNUNET_TIME_absolute_get_duration(dc->start_time); pi->value.download.completed = dc->completed; pi->value.download.anonymity = dc->anonymity; pi->value.download.eta = - GNUNET_TIME_calculate_eta (dc->start_time, dc->completed, dc->length); + GNUNET_TIME_calculate_eta(dc->start_time, dc->completed, dc->length); pi->value.download.is_active = (NULL == dc->mq) ? GNUNET_NO : GNUNET_YES; pi->fsh = dc->h; if (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE)) - dc->client_info = dc->h->upcb (dc->h->upcb_cls, pi); + dc->client_info = dc->h->upcb(dc->h->upcb_cls, pi); else - dc->client_info = GNUNET_FS_search_probe_progress_ (NULL, pi); + dc->client_info = GNUNET_FS_search_probe_progress_(NULL, pi); } /** * Closure for iterator processing results. */ -struct ProcessResultClosure -{ - +struct ProcessResultClosure { /** * Hash of data. */ @@ -191,9 +189,9 @@ struct ProcessResultClosure * @return #GNUNET_YES (we should continue to iterate); unless serious error */ static int -process_result_with_request (void *cls, - const struct GNUNET_HashCode *key, - void *value); +process_result_with_request(void *cls, + const struct GNUNET_HashCode *key, + void *value); /** @@ -210,12 +208,12 @@ process_result_with_request (void *cls, * @return GNUNET_OK on success */ static int -encrypt_existing_match (struct GNUNET_FS_DownloadContext *dc, - const struct ContentHashKey *chk, - struct DownloadRequest *dr, - const char *block, - size_t len, - int do_store) +encrypt_existing_match(struct GNUNET_FS_DownloadContext *dc, + const struct ContentHashKey *chk, + struct DownloadRequest *dr, + const char *block, + size_t len, + int do_store) { struct ProcessResultClosure prc; char enc[len]; @@ -223,34 +221,34 @@ encrypt_existing_match (struct GNUNET_FS_DownloadContext *dc, struct GNUNET_CRYPTO_SymmetricInitializationVector iv; struct GNUNET_HashCode query; - GNUNET_CRYPTO_hash_to_aes_key (&chk->key, &sk, &iv); - if (-1 == GNUNET_CRYPTO_symmetric_encrypt (block, len, &sk, &iv, enc)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - GNUNET_CRYPTO_hash (enc, len, &query); - if (0 != memcmp (&query, &chk->query, sizeof (struct GNUNET_HashCode))) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - GNUNET_log ( + GNUNET_CRYPTO_hash_to_aes_key(&chk->key, &sk, &iv); + if (-1 == GNUNET_CRYPTO_symmetric_encrypt(block, len, &sk, &iv, enc)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + GNUNET_CRYPTO_hash(enc, len, &query); + if (0 != memcmp(&query, &chk->query, sizeof(struct GNUNET_HashCode))) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "Matching %u byte block for `%s' at offset %llu already present, no need for download!\n", - (unsigned int) len, + (unsigned int)len, dc->filename, - (unsigned long long) dr->offset); + (unsigned long long)dr->offset); /* already got it! */ prc.dc = dc; prc.data = enc; prc.size = len; prc.type = (0 == dr->depth) ? GNUNET_BLOCK_TYPE_FS_DBLOCK - : GNUNET_BLOCK_TYPE_FS_IBLOCK; + : GNUNET_BLOCK_TYPE_FS_IBLOCK; prc.query = chk->query; prc.do_store = do_store; prc.last_transmission = GNUNET_TIME_UNIT_FOREVER_ABS; - process_result_with_request (&prc, &chk->key, dr); + process_result_with_request(&prc, &chk->key, dr); return GNUNET_OK; } @@ -263,7 +261,7 @@ encrypt_existing_match (struct GNUNET_FS_DownloadContext *dc, * @param dc download context that is having trouble */ static void -try_reconnect (struct GNUNET_FS_DownloadContext *dc); +try_reconnect(struct GNUNET_FS_DownloadContext *dc); /** @@ -278,12 +276,12 @@ try_reconnect (struct GNUNET_FS_DownloadContext *dc); * @param data contents of the file (or NULL if they were not inlined) */ static void -trigger_recursive_download (void *cls, - const char *filename, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *meta, - size_t length, - const void *data); +trigger_recursive_download(void *cls, + const char *filename, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *meta, + size_t length, + const void *data); /** @@ -293,7 +291,7 @@ trigger_recursive_download (void *cls, * @param dc context of download that just completed */ static void -full_recursive_download (struct GNUNET_FS_DownloadContext *dc) +full_recursive_download(struct GNUNET_FS_DownloadContext *dc) { size_t size; uint64_t size64; @@ -301,64 +299,64 @@ full_recursive_download (struct GNUNET_FS_DownloadContext *dc) struct GNUNET_DISK_FileHandle *h; struct GNUNET_DISK_MapHandle *m; - size64 = GNUNET_FS_uri_chk_get_file_size (dc->uri); - size = (size_t) size64; - if (size64 != (uint64_t) size) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_ERROR, - _ ( - "Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n")); - return; - } + size64 = GNUNET_FS_uri_chk_get_file_size(dc->uri); + size = (size_t)size64; + if (size64 != (uint64_t)size) + { + GNUNET_log( + GNUNET_ERROR_TYPE_ERROR, + _( + "Recursive downloads of directories larger than 4 GB are not supported on 32-bit systems\n")); + return; + } if (NULL != dc->filename) - { - h = GNUNET_DISK_file_open (dc->filename, - GNUNET_DISK_OPEN_READ, - GNUNET_DISK_PERM_NONE); - } + { + h = GNUNET_DISK_file_open(dc->filename, + GNUNET_DISK_OPEN_READ, + GNUNET_DISK_PERM_NONE); + } else - { - GNUNET_assert (NULL != dc->temp_filename); - h = GNUNET_DISK_file_open (dc->temp_filename, - GNUNET_DISK_OPEN_READ, - GNUNET_DISK_PERM_NONE); - } + { + GNUNET_assert(NULL != dc->temp_filename); + h = GNUNET_DISK_file_open(dc->temp_filename, + GNUNET_DISK_OPEN_READ, + GNUNET_DISK_PERM_NONE); + } if (NULL == h) return; /* oops */ - data = GNUNET_DISK_file_map (h, &m, GNUNET_DISK_MAP_TYPE_READ, size); + data = GNUNET_DISK_file_map(h, &m, GNUNET_DISK_MAP_TYPE_READ, size); if (NULL == data) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Directory too large for system address space\n")); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Directory too large for system address space\n")); + } else - { - if (GNUNET_OK != - GNUNET_FS_directory_list_contents (size, - data, - 0, - &trigger_recursive_download, - dc)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_WARNING, - _ ( - "Failed to access full directroy contents of `%s' for recursive download\n"), - dc->filename); - } - GNUNET_DISK_file_unmap (m); - } - GNUNET_DISK_file_close (h); + { + if (GNUNET_OK != + GNUNET_FS_directory_list_contents(size, + data, + 0, + &trigger_recursive_download, + dc)) + { + GNUNET_log( + GNUNET_ERROR_TYPE_WARNING, + _( + "Failed to access full directroy contents of `%s' for recursive download\n"), + dc->filename); + } + GNUNET_DISK_file_unmap(m); + } + GNUNET_DISK_file_close(h); if (NULL == dc->filename) - { - if (0 != unlink (dc->temp_filename)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, - "unlink", - dc->temp_filename); - GNUNET_free (dc->temp_filename); - dc->temp_filename = NULL; - } + { + if (0 != unlink(dc->temp_filename)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, + "unlink", + dc->temp_filename); + GNUNET_free(dc->temp_filename); + dc->temp_filename = NULL; + } } @@ -373,48 +371,48 @@ full_recursive_download (struct GNUNET_FS_DownloadContext *dc) * @param dc download to check for completion of children */ static void -check_completed (struct GNUNET_FS_DownloadContext *dc) +check_completed(struct GNUNET_FS_DownloadContext *dc) { struct GNUNET_FS_ProgressInfo pi; struct GNUNET_FS_DownloadContext *pos; /* first, check if we need to download children */ - if (is_recursive_download (dc)) - full_recursive_download (dc); + if (is_recursive_download(dc)) + full_recursive_download(dc); /* then, check if children are done already */ for (pos = dc->child_head; NULL != pos; pos = pos->next) - { - if ((NULL == pos->emsg) && (pos->completed < pos->length)) - return; /* not done yet */ - if ((NULL != pos->child_head) && (pos->has_finished != GNUNET_YES)) - return; /* not transitively done yet */ - } + { + if ((NULL == pos->emsg) && (pos->completed < pos->length)) + return; /* not done yet */ + if ((NULL != pos->child_head) && (pos->has_finished != GNUNET_YES)) + return; /* not transitively done yet */ + } /* All of our children are done, so mark this download done */ dc->has_finished = GNUNET_YES; if (NULL != dc->job_queue) - { - GNUNET_FS_dequeue_ (dc->job_queue); - dc->job_queue = NULL; - } + { + GNUNET_FS_dequeue_(dc->job_queue); + dc->job_queue = NULL; + } if (NULL != dc->task) - { - GNUNET_SCHEDULER_cancel (dc->task); - dc->task = NULL; - } + { + GNUNET_SCHEDULER_cancel(dc->task); + dc->task = NULL; + } if (NULL != dc->rfh) - { - GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (dc->rfh)); - dc->rfh = NULL; - } - GNUNET_FS_download_sync_ (dc); + { + GNUNET_break(GNUNET_OK == GNUNET_DISK_file_close(dc->rfh)); + dc->rfh = NULL; + } + GNUNET_FS_download_sync_(dc); /* signal completion */ pi.status = GNUNET_FS_STATUS_DOWNLOAD_COMPLETED; - GNUNET_FS_download_make_status_ (&pi, dc); + GNUNET_FS_download_make_status_(&pi, dc); /* let parent know */ if (NULL != dc->parent) - check_completed (dc->parent); + check_completed(dc->parent); } @@ -429,10 +427,10 @@ check_completed (struct GNUNET_FS_DownloadContext *dc) * @param data_len number of bytes in data */ static void -try_match_block (struct GNUNET_FS_DownloadContext *dc, - struct DownloadRequest *dr, - const char *data, - size_t data_len) +try_match_block(struct GNUNET_FS_DownloadContext *dc, + struct DownloadRequest *dr, + const char *data, + size_t data_len) { struct GNUNET_FS_ProgressInfo pi; unsigned int i; @@ -454,128 +452,130 @@ try_match_block (struct GNUNET_FS_DownloadContext *dc, if (BRS_DOWNLOAD_UP == dr->state) return; if (dr->depth > 0) - { - if ((dc->offset > 0) || - (dc->length < GNUNET_ntohll (dc->uri->data.chk.file_length))) - { - /* NOTE: this test is not tight, but should suffice; the issue - here is that 'dr->num_children' may inherently only specify a - smaller range than what is in the original file; - thus, reconstruction of (some) inner blocks will fail. - FIXME: we might eventually want to write a tighter test to - maximize the circumstances under which we do succeed with - IBlock reconstruction. (need good tests though). */ - return; - } - complete = GNUNET_YES; - for (i = 0; i < dr->num_children; i++) { - drc = dr->children[i]; - try_match_block (dc, drc, data, data_len); - if (drc->state != BRS_RECONSTRUCT_META_UP) - complete = GNUNET_NO; - else - chks[i] = drc->chk; + if ((dc->offset > 0) || + (dc->length < GNUNET_ntohll(dc->uri->data.chk.file_length))) + { + /* NOTE: this test is not tight, but should suffice; the issue + here is that 'dr->num_children' may inherently only specify a + smaller range than what is in the original file; + thus, reconstruction of (some) inner blocks will fail. + FIXME: we might eventually want to write a tighter test to + maximize the circumstances under which we do succeed with + IBlock reconstruction. (need good tests though). */ + return; + } + complete = GNUNET_YES; + for (i = 0; i < dr->num_children; i++) + { + drc = dr->children[i]; + try_match_block(dc, drc, data, data_len); + if (drc->state != BRS_RECONSTRUCT_META_UP) + complete = GNUNET_NO; + else + chks[i] = drc->chk; + } + if (GNUNET_YES != complete) + return; + data = (const char *)chks; + dlen = dr->num_children * sizeof(struct ContentHashKey); } - if (GNUNET_YES != complete) - return; - data = (const char *) chks; - dlen = dr->num_children * sizeof (struct ContentHashKey); - } else - { - if (dr->offset > data_len) - return; /* oops */ - dlen = GNUNET_MIN (data_len - dr->offset, DBLOCK_SIZE); - } - GNUNET_CRYPTO_hash (&data[dr->offset], dlen, &in_chk.key); - GNUNET_CRYPTO_hash_to_aes_key (&in_chk.key, &sk, &iv); + { + if (dr->offset > data_len) + return; /* oops */ + dlen = GNUNET_MIN(data_len - dr->offset, DBLOCK_SIZE); + } + GNUNET_CRYPTO_hash(&data[dr->offset], dlen, &in_chk.key); + GNUNET_CRYPTO_hash_to_aes_key(&in_chk.key, &sk, &iv); if (-1 == - GNUNET_CRYPTO_symmetric_encrypt (&data[dr->offset], dlen, &sk, &iv, enc)) - { - GNUNET_break (0); - return; - } - GNUNET_CRYPTO_hash (enc, dlen, &in_chk.query); + GNUNET_CRYPTO_symmetric_encrypt(&data[dr->offset], dlen, &sk, &iv, enc)) + { + GNUNET_break(0); + return; + } + GNUNET_CRYPTO_hash(enc, dlen, &in_chk.query); switch (dr->state) - { - case BRS_INIT: - dr->chk = in_chk; - dr->state = BRS_RECONSTRUCT_META_UP; - break; - case BRS_CHK_SET: - if (0 != memcmp (&in_chk, &dr->chk, sizeof (struct ContentHashKey))) - { - /* other peer provided bogus meta data */ - GNUNET_break_op (0); + { + case BRS_INIT: + dr->chk = in_chk; + dr->state = BRS_RECONSTRUCT_META_UP; + break; + + case BRS_CHK_SET: + if (0 != memcmp(&in_chk, &dr->chk, sizeof(struct ContentHashKey))) + { + /* other peer provided bogus meta data */ + GNUNET_break_op(0); + break; + } + /* write block to disk */ + fn = (NULL != dc->filename) ? dc->filename : dc->temp_filename; + if (NULL != fn) + { + fh = GNUNET_DISK_file_open(fn, + GNUNET_DISK_OPEN_READWRITE | + GNUNET_DISK_OPEN_CREATE | + GNUNET_DISK_OPEN_TRUNCATE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_GROUP_READ | + GNUNET_DISK_PERM_OTHER_READ); + if (NULL == fh) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "open", fn); + GNUNET_asprintf(&dc->emsg, + _("Failed to open file `%s' for writing"), + fn); + GNUNET_DISK_file_close(fh); + dr->state = BRS_ERROR; + pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR; + pi.value.download.specifics.error.message = dc->emsg; + GNUNET_FS_download_make_status_(&pi, dc); + return; + } + if (data_len != GNUNET_DISK_file_write(fh, odata, odata_len)) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "write", fn); + GNUNET_asprintf(&dc->emsg, + _("Failed to open file `%s' for writing"), + fn); + GNUNET_DISK_file_close(fh); + dr->state = BRS_ERROR; + pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR; + pi.value.download.specifics.error.message = dc->emsg; + GNUNET_FS_download_make_status_(&pi, dc); + return; + } + GNUNET_DISK_file_close(fh); + } + /* signal success */ + dr->state = BRS_DOWNLOAD_UP; + dc->completed = dc->length; + GNUNET_FS_download_sync_(dc); + pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS; + pi.value.download.specifics.progress.data = data; + pi.value.download.specifics.progress.offset = 0; + pi.value.download.specifics.progress.data_len = dlen; + pi.value.download.specifics.progress.depth = 0; + pi.value.download.specifics.progress.respect_offered = 0; + pi.value.download.specifics.progress.block_download_duration = + GNUNET_TIME_UNIT_ZERO; + GNUNET_FS_download_make_status_(&pi, dc); + if ((NULL != dc->filename) && + (0 != truncate(dc->filename, + GNUNET_ntohll(dc->uri->data.chk.file_length)))) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, + "truncate", + dc->filename); + check_completed(dc); + break; + + default: + /* how did we get here? */ + GNUNET_break(0); break; } - /* write block to disk */ - fn = (NULL != dc->filename) ? dc->filename : dc->temp_filename; - if (NULL != fn) - { - fh = GNUNET_DISK_file_open (fn, - GNUNET_DISK_OPEN_READWRITE | - GNUNET_DISK_OPEN_CREATE | - GNUNET_DISK_OPEN_TRUNCATE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_GROUP_READ | - GNUNET_DISK_PERM_OTHER_READ); - if (NULL == fh) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn); - GNUNET_asprintf (&dc->emsg, - _ ("Failed to open file `%s' for writing"), - fn); - GNUNET_DISK_file_close (fh); - dr->state = BRS_ERROR; - pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR; - pi.value.download.specifics.error.message = dc->emsg; - GNUNET_FS_download_make_status_ (&pi, dc); - return; - } - if (data_len != GNUNET_DISK_file_write (fh, odata, odata_len)) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "write", fn); - GNUNET_asprintf (&dc->emsg, - _ ("Failed to open file `%s' for writing"), - fn); - GNUNET_DISK_file_close (fh); - dr->state = BRS_ERROR; - pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR; - pi.value.download.specifics.error.message = dc->emsg; - GNUNET_FS_download_make_status_ (&pi, dc); - return; - } - GNUNET_DISK_file_close (fh); - } - /* signal success */ - dr->state = BRS_DOWNLOAD_UP; - dc->completed = dc->length; - GNUNET_FS_download_sync_ (dc); - pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS; - pi.value.download.specifics.progress.data = data; - pi.value.download.specifics.progress.offset = 0; - pi.value.download.specifics.progress.data_len = dlen; - pi.value.download.specifics.progress.depth = 0; - pi.value.download.specifics.progress.respect_offered = 0; - pi.value.download.specifics.progress.block_download_duration = - GNUNET_TIME_UNIT_ZERO; - GNUNET_FS_download_make_status_ (&pi, dc); - if ((NULL != dc->filename) && - (0 != truncate (dc->filename, - GNUNET_ntohll (dc->uri->data.chk.file_length)))) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, - "truncate", - dc->filename); - check_completed (dc); - break; - default: - /* how did we get here? */ - GNUNET_break (0); - break; - } } @@ -598,27 +598,27 @@ try_match_block (struct GNUNET_FS_DownloadContext *dc, * @return 0 to continue extracting, 1 to abort */ static int -match_full_data (void *cls, - const char *plugin_name, - enum EXTRACTOR_MetaType type, - enum EXTRACTOR_MetaFormat format, - const char *data_mime_type, - const char *data, - size_t data_len) +match_full_data(void *cls, + const char *plugin_name, + enum EXTRACTOR_MetaType type, + enum EXTRACTOR_MetaFormat format, + const char *data_mime_type, + const char *data, + size_t data_len) { struct GNUNET_FS_DownloadContext *dc = cls; if (EXTRACTOR_METATYPE_GNUNET_FULL_DATA != type) return 0; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found %u bytes of FD!\n", - (unsigned int) data_len); - if (GNUNET_FS_uri_chk_get_file_size (dc->uri) != data_len) - { - GNUNET_break_op (0); - return 1; /* bogus meta data */ - } - try_match_block (dc, dc->top_request, data, data_len); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found %u bytes of FD!\n", + (unsigned int)data_len); + if (GNUNET_FS_uri_chk_get_file_size(dc->uri) != data_len) + { + GNUNET_break_op(0); + return 1; /* bogus meta data */ + } + try_match_block(dc, dc->top_request, data, data_len); return 1; } @@ -630,20 +630,21 @@ match_full_data (void *cls, * @param dr download request that is done */ static void -propagate_up (struct DownloadRequest *dr) +propagate_up(struct DownloadRequest *dr) { unsigned int i; do - { - dr->state = BRS_DOWNLOAD_UP; - dr = dr->parent; - if (NULL == dr) - break; - for (i = 0; i < dr->num_children; i++) - if (dr->children[i]->state != BRS_DOWNLOAD_UP) + { + dr->state = BRS_DOWNLOAD_UP; + dr = dr->parent; + if (NULL == dr) break; - } while (i == dr->num_children); + for (i = 0; i < dr->num_children; i++) + if (dr->children[i]->state != BRS_DOWNLOAD_UP) + break; + } + while (i == dr->num_children); } @@ -658,8 +659,8 @@ propagate_up (struct DownloadRequest *dr) * @param dr block to reconstruct */ static void -try_top_down_reconstruction (struct GNUNET_FS_DownloadContext *dc, - struct DownloadRequest *dr) +try_top_down_reconstruction(struct GNUNET_FS_DownloadContext *dc, + struct DownloadRequest *dr) { uint64_t off; char block[DBLOCK_SIZE]; @@ -672,64 +673,64 @@ try_top_down_reconstruction (struct GNUNET_FS_DownloadContext *dc, const struct ContentHashKey *chks; int up_done; - GNUNET_assert (NULL != dc->rfh); - GNUNET_assert (BRS_CHK_SET == dr->state); - total = GNUNET_FS_uri_chk_get_file_size (dc->uri); - GNUNET_assert (dr->depth < dc->treedepth); - len = GNUNET_FS_tree_calculate_block_size (total, dr->offset, dr->depth); - GNUNET_assert (len <= DBLOCK_SIZE); - off = compute_disk_offset (total, dr->offset, dr->depth); + GNUNET_assert(NULL != dc->rfh); + GNUNET_assert(BRS_CHK_SET == dr->state); + total = GNUNET_FS_uri_chk_get_file_size(dc->uri); + GNUNET_assert(dr->depth < dc->treedepth); + len = GNUNET_FS_tree_calculate_block_size(total, dr->offset, dr->depth); + GNUNET_assert(len <= DBLOCK_SIZE); + off = compute_disk_offset(total, dr->offset, dr->depth); if (dc->old_file_size < off + len) return; /* failure */ - if (off != GNUNET_DISK_file_seek (dc->rfh, off, GNUNET_DISK_SEEK_SET)) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "seek", dc->filename); - return; /* failure */ - } - if (len != GNUNET_DISK_file_read (dc->rfh, block, len)) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "read", dc->filename); - return; /* failure */ - } - GNUNET_CRYPTO_hash (block, len, &key); - if (0 != memcmp (&key, &dr->chk.key, sizeof (struct GNUNET_HashCode))) + if (off != GNUNET_DISK_file_seek(dc->rfh, off, GNUNET_DISK_SEEK_SET)) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "seek", dc->filename); + return; /* failure */ + } + if (len != GNUNET_DISK_file_read(dc->rfh, block, len)) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "read", dc->filename); + return; /* failure */ + } + GNUNET_CRYPTO_hash(block, len, &key); + if (0 != memcmp(&key, &dr->chk.key, sizeof(struct GNUNET_HashCode))) return; /* mismatch */ if (GNUNET_OK != - encrypt_existing_match (dc, &dr->chk, dr, block, len, GNUNET_NO)) - { - /* hash matches but encrypted block does not, really bad */ - dr->state = BRS_ERROR; - /* propagate up */ - while (NULL != dr->parent) + encrypt_existing_match(dc, &dr->chk, dr, block, len, GNUNET_NO)) { - dr = dr->parent; + /* hash matches but encrypted block does not, really bad */ dr->state = BRS_ERROR; + /* propagate up */ + while (NULL != dr->parent) + { + dr = dr->parent; + dr->state = BRS_ERROR; + } + return; } - return; - } /* block matches */ dr->state = BRS_DOWNLOAD_DOWN; /* set CHKs for children */ up_done = GNUNET_YES; - chks = (const struct ContentHashKey *) block; + chks = (const struct ContentHashKey *)block; for (i = 0; i < dr->num_children; i++) - { - drc = dr->children[i]; - GNUNET_assert (drc->offset >= dr->offset); - child_block_size = GNUNET_FS_tree_compute_tree_size (drc->depth); - GNUNET_assert (0 == (drc->offset - dr->offset) % child_block_size); - if (BRS_INIT == drc->state) - { - drc->state = BRS_CHK_SET; - drc->chk = chks[drc->chk_idx]; - try_top_down_reconstruction (dc, drc); - } - if (BRS_DOWNLOAD_UP != drc->state) - up_done = GNUNET_NO; /* children not all done */ - } + { + drc = dr->children[i]; + GNUNET_assert(drc->offset >= dr->offset); + child_block_size = GNUNET_FS_tree_compute_tree_size(drc->depth); + GNUNET_assert(0 == (drc->offset - dr->offset) % child_block_size); + if (BRS_INIT == drc->state) + { + drc->state = BRS_CHK_SET; + drc->chk = chks[drc->chk_idx]; + try_top_down_reconstruction(dc, drc); + } + if (BRS_DOWNLOAD_UP != drc->state) + up_done = GNUNET_NO; /* children not all done */ + } if (GNUNET_YES == up_done) - propagate_up (dr); /* children all done (or no children...) */ + propagate_up(dr); /* children all done (or no children...) */ } @@ -742,26 +743,26 @@ try_top_down_reconstruction (struct GNUNET_FS_DownloadContext *dc, * @return #GNUNET_OK */ static int -retry_entry (void *cls, const struct GNUNET_HashCode *key, void *entry) +retry_entry(void *cls, const struct GNUNET_HashCode *key, void *entry) { struct GNUNET_FS_DownloadContext *dc = cls; struct DownloadRequest *dr = entry; struct SearchMessage *sm; struct GNUNET_MQ_Envelope *env; - env = GNUNET_MQ_msg (sm, GNUNET_MESSAGE_TYPE_FS_START_SEARCH); + env = GNUNET_MQ_msg(sm, GNUNET_MESSAGE_TYPE_FS_START_SEARCH); if (0 != (dc->options & GNUNET_FS_DOWNLOAD_OPTION_LOOPBACK_ONLY)) - sm->options = htonl (GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY); + sm->options = htonl(GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY); else - sm->options = htonl (GNUNET_FS_SEARCH_OPTION_NONE); + sm->options = htonl(GNUNET_FS_SEARCH_OPTION_NONE); if (0 == dr->depth) - sm->type = htonl (GNUNET_BLOCK_TYPE_FS_DBLOCK); + sm->type = htonl(GNUNET_BLOCK_TYPE_FS_DBLOCK); else - sm->type = htonl (GNUNET_BLOCK_TYPE_FS_IBLOCK); - sm->anonymity_level = htonl (dc->anonymity); + sm->type = htonl(GNUNET_BLOCK_TYPE_FS_IBLOCK); + sm->anonymity_level = htonl(dc->anonymity); sm->target = dc->target; sm->query = dr->chk.query; - GNUNET_MQ_send (dc->mq, env); + GNUNET_MQ_send(dc->mq, env); return GNUNET_OK; } @@ -773,55 +774,62 @@ retry_entry (void *cls, const struct GNUNET_HashCode *key, void *entry) * @param dr request to schedule */ static void -schedule_block_download (struct GNUNET_FS_DownloadContext *dc, - struct DownloadRequest *dr) +schedule_block_download(struct GNUNET_FS_DownloadContext *dc, + struct DownloadRequest *dr) { unsigned int i; switch (dr->state) - { - case BRS_INIT: - GNUNET_assert (0); - break; - case BRS_RECONSTRUCT_DOWN: - GNUNET_assert (0); - break; - case BRS_RECONSTRUCT_META_UP: - GNUNET_assert (0); - break; - case BRS_RECONSTRUCT_UP: - GNUNET_assert (0); - break; - case BRS_CHK_SET: - /* normal case, start download */ - break; - case BRS_DOWNLOAD_DOWN: - for (i = 0; i < dr->num_children; i++) - schedule_block_download (dc, dr->children[i]); - return; - case BRS_DOWNLOAD_UP: - /* We're done! */ - return; - case BRS_ERROR: - GNUNET_break (0); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Scheduling download at offset %llu and depth %u for `%s'\n", - (unsigned long long) dr->offset, - dr->depth, - GNUNET_h2s (&dr->chk.query)); - if (GNUNET_NO != GNUNET_CONTAINER_multihashmap_contains_value (dc->active, - &dr->chk.query, - dr)) + { + case BRS_INIT: + GNUNET_assert(0); + break; + + case BRS_RECONSTRUCT_DOWN: + GNUNET_assert(0); + break; + + case BRS_RECONSTRUCT_META_UP: + GNUNET_assert(0); + break; + + case BRS_RECONSTRUCT_UP: + GNUNET_assert(0); + break; + + case BRS_CHK_SET: + /* normal case, start download */ + break; + + case BRS_DOWNLOAD_DOWN: + for (i = 0; i < dr->num_children; i++) + schedule_block_download(dc, dr->children[i]); + return; + + case BRS_DOWNLOAD_UP: + /* We're done! */ + return; + + case BRS_ERROR: + GNUNET_break(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Scheduling download at offset %llu and depth %u for `%s'\n", + (unsigned long long)dr->offset, + dr->depth, + GNUNET_h2s(&dr->chk.query)); + if (GNUNET_NO != GNUNET_CONTAINER_multihashmap_contains_value(dc->active, + &dr->chk.query, + dr)) return; /* already active */ - GNUNET_CONTAINER_multihashmap_put (dc->active, - &dr->chk.query, - dr, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + GNUNET_CONTAINER_multihashmap_put(dc->active, + &dr->chk.query, + dr, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); if (NULL == dc->mq) return; /* download not active */ - retry_entry (dc, &dr->chk.query, dr); + retry_entry(dc, &dr->chk.query, dr); } @@ -839,12 +847,12 @@ schedule_block_download (struct GNUNET_FS_DownloadContext *dc, * @param data contents of the file (or NULL if they were not inlined) */ static void -trigger_recursive_download (void *cls, - const char *filename, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *meta, - size_t length, - const void *data) +trigger_recursive_download(void *cls, + const char *filename, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *meta, + size_t length, + const void *data) { struct GNUNET_FS_DownloadContext *dc = cls; struct GNUNET_FS_DownloadContext *cpos; @@ -861,121 +869,121 @@ trigger_recursive_download (void *cls, return; /* entry for the directory itself */ cpos = dc->child_head; while (NULL != cpos) - { - if ((GNUNET_FS_uri_test_equal (uri, cpos->uri)) || - ((NULL != filename) && (0 == strcmp (cpos->filename, filename)))) - break; - cpos = cpos->next; - } + { + if ((GNUNET_FS_uri_test_equal(uri, cpos->uri)) || + ((NULL != filename) && (0 == strcmp(cpos->filename, filename)))) + break; + cpos = cpos->next; + } if (NULL != cpos) return; /* already exists */ fn = NULL; if (NULL == filename) - { - fn = GNUNET_FS_meta_data_suggest_filename (meta); - if (NULL == fn) - { - us = GNUNET_FS_uri_to_string (uri); - fn = GNUNET_strdup (&us[strlen (GNUNET_FS_URI_CHK_PREFIX)]); - GNUNET_free (us); - } - else if ('.' == fn[0]) - { - ext = fn; - us = GNUNET_FS_uri_to_string (uri); - GNUNET_asprintf (&fn, - "%s%s", - &us[strlen (GNUNET_FS_URI_CHK_PREFIX)], - ext); - GNUNET_free (ext); - GNUNET_free (us); - } - /* change '\' to '/' (this should have happened - * during insertion, but malicious peers may - * not have done this) */ - while (NULL != (pos = strstr (fn, "\\"))) - *pos = '/'; - /* remove '../' everywhere (again, well-behaved - * peers don't do this, but don't trust that - * we did not get something nasty) */ - while (NULL != (pos = strstr (fn, "../"))) - { - pos[0] = '_'; - pos[1] = '_'; - pos[2] = '_'; - } - filename = fn; - } + { + fn = GNUNET_FS_meta_data_suggest_filename(meta); + if (NULL == fn) + { + us = GNUNET_FS_uri_to_string(uri); + fn = GNUNET_strdup(&us[strlen(GNUNET_FS_URI_CHK_PREFIX)]); + GNUNET_free(us); + } + else if ('.' == fn[0]) + { + ext = fn; + us = GNUNET_FS_uri_to_string(uri); + GNUNET_asprintf(&fn, + "%s%s", + &us[strlen(GNUNET_FS_URI_CHK_PREFIX)], + ext); + GNUNET_free(ext); + GNUNET_free(us); + } + /* change '\' to '/' (this should have happened + * during insertion, but malicious peers may + * not have done this) */ + while (NULL != (pos = strstr(fn, "\\"))) + *pos = '/'; + /* remove '../' everywhere (again, well-behaved + * peers don't do this, but don't trust that + * we did not get something nasty) */ + while (NULL != (pos = strstr(fn, "../"))) + { + pos[0] = '_'; + pos[1] = '_'; + pos[2] = '_'; + } + filename = fn; + } if (NULL == dc->filename) - { - full_name = NULL; - } + { + full_name = NULL; + } else - { - dn = GNUNET_strdup (dc->filename); - GNUNET_break ( - (strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) && - (NULL != strstr (dn + strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT), - GNUNET_FS_DIRECTORY_EXT))); - sfn = GNUNET_strdup (filename); - while ((strlen (sfn) > 0) && ('/' == filename[strlen (sfn) - 1])) - sfn[strlen (sfn) - 1] = '\0'; - if ((strlen (dn) >= strlen (GNUNET_FS_DIRECTORY_EXT)) && - (NULL != strstr (dn + strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT), - GNUNET_FS_DIRECTORY_EXT))) - dn[strlen (dn) - strlen (GNUNET_FS_DIRECTORY_EXT)] = '\0'; - if ((GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) && - ((strlen (filename) < strlen (GNUNET_FS_DIRECTORY_EXT)) || - (NULL == strstr (filename + strlen (filename) - - strlen (GNUNET_FS_DIRECTORY_EXT), - GNUNET_FS_DIRECTORY_EXT)))) - { - GNUNET_asprintf (&full_name, - "%s%s%s%s", - dn, - DIR_SEPARATOR_STR, - sfn, - GNUNET_FS_DIRECTORY_EXT); - } - else - { - GNUNET_asprintf (&full_name, "%s%s%s", dn, DIR_SEPARATOR_STR, sfn); - } - GNUNET_free (sfn); - GNUNET_free (dn); - } + { + dn = GNUNET_strdup(dc->filename); + GNUNET_break( + (strlen(dn) >= strlen(GNUNET_FS_DIRECTORY_EXT)) && + (NULL != strstr(dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT), + GNUNET_FS_DIRECTORY_EXT))); + sfn = GNUNET_strdup(filename); + while ((strlen(sfn) > 0) && ('/' == filename[strlen(sfn) - 1])) + sfn[strlen(sfn) - 1] = '\0'; + if ((strlen(dn) >= strlen(GNUNET_FS_DIRECTORY_EXT)) && + (NULL != strstr(dn + strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT), + GNUNET_FS_DIRECTORY_EXT))) + dn[strlen(dn) - strlen(GNUNET_FS_DIRECTORY_EXT)] = '\0'; + if ((GNUNET_YES == GNUNET_FS_meta_data_test_for_directory(meta)) && + ((strlen(filename) < strlen(GNUNET_FS_DIRECTORY_EXT)) || + (NULL == strstr(filename + strlen(filename) - + strlen(GNUNET_FS_DIRECTORY_EXT), + GNUNET_FS_DIRECTORY_EXT)))) + { + GNUNET_asprintf(&full_name, + "%s%s%s%s", + dn, + DIR_SEPARATOR_STR, + sfn, + GNUNET_FS_DIRECTORY_EXT); + } + else + { + GNUNET_asprintf(&full_name, "%s%s%s", dn, DIR_SEPARATOR_STR, sfn); + } + GNUNET_free(sfn); + GNUNET_free(dn); + } if ((NULL != full_name) && - (GNUNET_OK != GNUNET_DISK_directory_create_for_file (full_name))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ( - "Failed to create directory for recursive download of `%s'\n"), - full_name); - GNUNET_free (full_name); - GNUNET_free_non_null (fn); - return; - } + (GNUNET_OK != GNUNET_DISK_directory_create_for_file(full_name))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _( + "Failed to create directory for recursive download of `%s'\n"), + full_name); + GNUNET_free(full_name); + GNUNET_free_non_null(fn); + return; + } temp_name = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Triggering recursive download of size %llu with %u bytes MD\n", - (unsigned long long) GNUNET_FS_uri_chk_get_file_size (uri), - (unsigned int) GNUNET_CONTAINER_meta_data_get_serialized_size ( - meta)); - GNUNET_FS_download_start (dc->h, - uri, - meta, - full_name, - temp_name, - 0, - GNUNET_FS_uri_chk_get_file_size (uri), - dc->anonymity, - dc->options, - NULL, - dc); - GNUNET_free_non_null (full_name); - GNUNET_free_non_null (temp_name); - GNUNET_free_non_null (fn); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Triggering recursive download of size %llu with %u bytes MD\n", + (unsigned long long)GNUNET_FS_uri_chk_get_file_size(uri), + (unsigned int)GNUNET_CONTAINER_meta_data_get_serialized_size( + meta)); + GNUNET_FS_download_start(dc->h, + uri, + meta, + full_name, + temp_name, + 0, + GNUNET_FS_uri_chk_get_file_size(uri), + dc->anonymity, + dc->options, + NULL, + dc); + GNUNET_free_non_null(full_name); + GNUNET_free_non_null(temp_name); + GNUNET_free_non_null(fn); } @@ -985,14 +993,14 @@ trigger_recursive_download (void *cls, * @param dr request to free */ void -GNUNET_FS_free_download_request_ (struct DownloadRequest *dr) +GNUNET_FS_free_download_request_(struct DownloadRequest *dr) { if (NULL == dr) return; for (unsigned int i = 0; i < dr->num_children; i++) - GNUNET_FS_free_download_request_ (dr->children[i]); - GNUNET_free_non_null (dr->children); - GNUNET_free (dr); + GNUNET_FS_free_download_request_(dr->children[i]); + GNUNET_free_non_null(dr->children); + GNUNET_free(dr); } @@ -1006,9 +1014,9 @@ GNUNET_FS_free_download_request_ (struct DownloadRequest *dr) * @return #GNUNET_YES (we should continue to iterate); unless serious error */ static int -process_result_with_request (void *cls, - const struct GNUNET_HashCode *key, - void *value) +process_result_with_request(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct ProcessResultClosure *prc = cls; struct DownloadRequest *dr = value; @@ -1025,132 +1033,132 @@ process_result_with_request (void *cls, int i; struct ContentHashKey *chkarr; - GNUNET_log ( + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "Received %u byte block `%s' matching pending request at depth %u and offset %llu/%llu\n", - (unsigned int) prc->size, - GNUNET_h2s (key), + (unsigned int)prc->size, + GNUNET_h2s(key), dr->depth, - (unsigned long long) dr->offset, - (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length)); - bs = GNUNET_FS_tree_calculate_block_size (GNUNET_ntohll ( - dc->uri->data.chk.file_length), - dr->offset, - dr->depth); + (unsigned long long)dr->offset, + (unsigned long long)GNUNET_ntohll(dc->uri->data.chk.file_length)); + bs = GNUNET_FS_tree_calculate_block_size(GNUNET_ntohll( + dc->uri->data.chk.file_length), + dr->offset, + dr->depth); if (prc->size != bs) - { - GNUNET_asprintf ( - &dc->emsg, - _ ( - "Internal error or bogus download URI (expected %u bytes at depth %u and offset %llu/%llu, got %u bytes)"), - bs, - dr->depth, - (unsigned long long) dr->offset, - (unsigned long long) GNUNET_ntohll (dc->uri->data.chk.file_length), - prc->size); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s\n", dc->emsg); - while (NULL != dr->parent) { + GNUNET_asprintf( + &dc->emsg, + _( + "Internal error or bogus download URI (expected %u bytes at depth %u and offset %llu/%llu, got %u bytes)"), + bs, + dr->depth, + (unsigned long long)dr->offset, + (unsigned long long)GNUNET_ntohll(dc->uri->data.chk.file_length), + prc->size); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s\n", dc->emsg); + while (NULL != dr->parent) + { + dr->state = BRS_ERROR; + dr = dr->parent; + } dr->state = BRS_ERROR; - dr = dr->parent; + goto signal_error; } - dr->state = BRS_ERROR; - goto signal_error; - } - (void) GNUNET_CONTAINER_multihashmap_remove (dc->active, &prc->query, dr); - GNUNET_CRYPTO_hash_to_aes_key (&dr->chk.key, &skey, &iv); + (void)GNUNET_CONTAINER_multihashmap_remove(dc->active, &prc->query, dr); + GNUNET_CRYPTO_hash_to_aes_key(&dr->chk.key, &skey, &iv); if (-1 == - GNUNET_CRYPTO_symmetric_decrypt (prc->data, prc->size, &skey, &iv, pt)) - { - GNUNET_break (0); - dc->emsg = GNUNET_strdup (_ ("internal error decrypting content")); - goto signal_error; - } - off = compute_disk_offset (GNUNET_ntohll (dc->uri->data.chk.file_length), - dr->offset, - dr->depth); + GNUNET_CRYPTO_symmetric_decrypt(prc->data, prc->size, &skey, &iv, pt)) + { + GNUNET_break(0); + dc->emsg = GNUNET_strdup(_("internal error decrypting content")); + goto signal_error; + } + off = compute_disk_offset(GNUNET_ntohll(dc->uri->data.chk.file_length), + dr->offset, + dr->depth); /* save to disk */ if ((GNUNET_YES == prc->do_store) && - ((NULL != dc->filename) || (is_recursive_download (dc))) && + ((NULL != dc->filename) || (is_recursive_download(dc))) && ((dr->depth == dc->treedepth) || (0 == (dc->options & GNUNET_FS_DOWNLOAD_NO_TEMPORARIES)))) - { - fh = GNUNET_DISK_file_open (NULL != dc->filename ? dc->filename - : dc->temp_filename, - GNUNET_DISK_OPEN_READWRITE | - GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_GROUP_READ | - GNUNET_DISK_PERM_OTHER_READ); - if (NULL == fh) - { - GNUNET_asprintf (&dc->emsg, - _ ("Download failed: could not open file `%s': %s"), - dc->filename, - strerror (errno)); - goto signal_error; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Saving decrypted block to disk at offset %llu\n", - (unsigned long long) off); - if ((off != GNUNET_DISK_file_seek (fh, off, GNUNET_DISK_SEEK_SET))) - { - GNUNET_asprintf (&dc->emsg, - _ ("Failed to seek to offset %llu in file `%s': %s"), - (unsigned long long) off, - dc->filename, - strerror (errno)); - goto signal_error; - } - if (prc->size != GNUNET_DISK_file_write (fh, pt, prc->size)) { - GNUNET_asprintf ( - &dc->emsg, - _ ("Failed to write block of %u bytes at offset %llu in file `%s': %s"), - (unsigned int) prc->size, - (unsigned long long) off, - dc->filename, - strerror (errno)); - goto signal_error; + fh = GNUNET_DISK_file_open(NULL != dc->filename ? dc->filename + : dc->temp_filename, + GNUNET_DISK_OPEN_READWRITE | + GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_GROUP_READ | + GNUNET_DISK_PERM_OTHER_READ); + if (NULL == fh) + { + GNUNET_asprintf(&dc->emsg, + _("Download failed: could not open file `%s': %s"), + dc->filename, + strerror(errno)); + goto signal_error; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Saving decrypted block to disk at offset %llu\n", + (unsigned long long)off); + if ((off != GNUNET_DISK_file_seek(fh, off, GNUNET_DISK_SEEK_SET))) + { + GNUNET_asprintf(&dc->emsg, + _("Failed to seek to offset %llu in file `%s': %s"), + (unsigned long long)off, + dc->filename, + strerror(errno)); + goto signal_error; + } + if (prc->size != GNUNET_DISK_file_write(fh, pt, prc->size)) + { + GNUNET_asprintf( + &dc->emsg, + _("Failed to write block of %u bytes at offset %llu in file `%s': %s"), + (unsigned int)prc->size, + (unsigned long long)off, + dc->filename, + strerror(errno)); + goto signal_error; + } + GNUNET_break(GNUNET_OK == GNUNET_DISK_file_close(fh)); + fh = NULL; } - GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fh)); - fh = NULL; - } if (0 == dr->depth) - { - /* DBLOCK, update progress and try recursion if applicable */ - app = prc->size; - if (dr->offset < dc->offset) - { - /* starting offset begins in the middle of pt, - * do not count first bytes as progress */ - GNUNET_assert (app > (dc->offset - dr->offset)); - app -= (dc->offset - dr->offset); - } - if (dr->offset + prc->size > dc->offset + dc->length) - { - /* end of block is after relevant range, - * do not count last bytes as progress */ - GNUNET_assert (app > - (dr->offset + prc->size) - (dc->offset + dc->length)); - app -= (dr->offset + prc->size) - (dc->offset + dc->length); - } - dc->completed += app; - - /* do recursive download if option is set and either meta data - * says it is a directory or if no meta data is given AND filename - * ends in '.gnd' (top-level case) */ - if (is_recursive_download (dc)) - GNUNET_FS_directory_list_contents (prc->size, - pt, - off, - &trigger_recursive_download, - dc); - } - GNUNET_assert (dc->completed <= dc->length); + { + /* DBLOCK, update progress and try recursion if applicable */ + app = prc->size; + if (dr->offset < dc->offset) + { + /* starting offset begins in the middle of pt, + * do not count first bytes as progress */ + GNUNET_assert(app > (dc->offset - dr->offset)); + app -= (dc->offset - dr->offset); + } + if (dr->offset + prc->size > dc->offset + dc->length) + { + /* end of block is after relevant range, + * do not count last bytes as progress */ + GNUNET_assert(app > + (dr->offset + prc->size) - (dc->offset + dc->length)); + app -= (dr->offset + prc->size) - (dc->offset + dc->length); + } + dc->completed += app; + + /* do recursive download if option is set and either meta data + * says it is a directory or if no meta data is given AND filename + * ends in '.gnd' (top-level case) */ + if (is_recursive_download(dc)) + GNUNET_FS_directory_list_contents(prc->size, + pt, + off, + &trigger_recursive_download, + dc); + } + GNUNET_assert(dc->completed <= dc->length); dr->state = BRS_DOWNLOAD_DOWN; pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS; pi.value.download.specifics.progress.data = pt; @@ -1163,112 +1171,120 @@ process_result_with_request (void *cls, if (prc->last_transmission.abs_value_us != GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us) pi.value.download.specifics.progress.block_download_duration = - GNUNET_TIME_absolute_get_duration (prc->last_transmission); + GNUNET_TIME_absolute_get_duration(prc->last_transmission); else pi.value.download.specifics.progress.block_download_duration = GNUNET_TIME_UNIT_ZERO; /* found locally */ - GNUNET_FS_download_make_status_ (&pi, dc); + GNUNET_FS_download_make_status_(&pi, dc); if (0 == dr->depth) - propagate_up (dr); + propagate_up(dr); if (dc->completed == dc->length) - { - /* download completed, signal */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Download completed, truncating file to desired length %llu\n", - (unsigned long long) GNUNET_ntohll ( - dc->uri->data.chk.file_length)); - /* truncate file to size (since we store IBlocks at the end) */ - if (NULL != dc->filename) - { - if (0 != truncate (dc->filename, - GNUNET_ntohll (dc->uri->data.chk.file_length))) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, - "truncate", - dc->filename); - } - GNUNET_assert (0 == dr->depth); - check_completed (dc); - } + { + /* download completed, signal */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Download completed, truncating file to desired length %llu\n", + (unsigned long long)GNUNET_ntohll( + dc->uri->data.chk.file_length)); + /* truncate file to size (since we store IBlocks at the end) */ + if (NULL != dc->filename) + { + if (0 != truncate(dc->filename, + GNUNET_ntohll(dc->uri->data.chk.file_length))) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, + "truncate", + dc->filename); + } + GNUNET_assert(0 == dr->depth); + check_completed(dc); + } if (0 == dr->depth) - { - /* bottom of the tree, no child downloads possible, just sync */ - GNUNET_FS_download_sync_ (dc); - return GNUNET_YES; - } + { + /* bottom of the tree, no child downloads possible, just sync */ + GNUNET_FS_download_sync_(dc); + return GNUNET_YES; + } - GNUNET_log ( + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "Triggering downloads of children (this block was at depth %u and offset %llu)\n", dr->depth, - (unsigned long long) dr->offset); - GNUNET_assert (0 == (prc->size % sizeof (struct ContentHashKey))); - chkarr = (struct ContentHashKey *) pt; + (unsigned long long)dr->offset); + GNUNET_assert(0 == (prc->size % sizeof(struct ContentHashKey))); + chkarr = (struct ContentHashKey *)pt; for (i = dr->num_children - 1; i >= 0; i--) - { - drc = dr->children[i]; - switch (drc->state) { - case BRS_INIT: - if ((drc->chk_idx + 1) * sizeof (struct ContentHashKey) > prc->size) - { - /* 'chkarr' does not have enough space for this chk_idx; - internal error! */ - GNUNET_break (0); - GNUNET_assert (0); - dc->emsg = GNUNET_strdup (_ ("internal error decoding tree")); - goto signal_error; - } - drc->chk = chkarr[drc->chk_idx]; - drc->state = BRS_CHK_SET; - if (GNUNET_YES == dc->issue_requests) - schedule_block_download (dc, drc); - break; - case BRS_RECONSTRUCT_DOWN: - GNUNET_assert (0); - break; - case BRS_RECONSTRUCT_META_UP: - GNUNET_assert (0); - break; - case BRS_RECONSTRUCT_UP: - GNUNET_assert (0); - break; - case BRS_CHK_SET: - GNUNET_assert (0); - break; - case BRS_DOWNLOAD_DOWN: - GNUNET_assert (0); - break; - case BRS_DOWNLOAD_UP: - GNUNET_assert (0); - break; - case BRS_ERROR: - GNUNET_assert (0); - break; - default: - GNUNET_assert (0); - break; + drc = dr->children[i]; + switch (drc->state) + { + case BRS_INIT: + if ((drc->chk_idx + 1) * sizeof(struct ContentHashKey) > prc->size) + { + /* 'chkarr' does not have enough space for this chk_idx; + internal error! */ + GNUNET_break(0); + GNUNET_assert(0); + dc->emsg = GNUNET_strdup(_("internal error decoding tree")); + goto signal_error; + } + drc->chk = chkarr[drc->chk_idx]; + drc->state = BRS_CHK_SET; + if (GNUNET_YES == dc->issue_requests) + schedule_block_download(dc, drc); + break; + + case BRS_RECONSTRUCT_DOWN: + GNUNET_assert(0); + break; + + case BRS_RECONSTRUCT_META_UP: + GNUNET_assert(0); + break; + + case BRS_RECONSTRUCT_UP: + GNUNET_assert(0); + break; + + case BRS_CHK_SET: + GNUNET_assert(0); + break; + + case BRS_DOWNLOAD_DOWN: + GNUNET_assert(0); + break; + + case BRS_DOWNLOAD_UP: + GNUNET_assert(0); + break; + + case BRS_ERROR: + GNUNET_assert(0); + break; + + default: + GNUNET_assert(0); + break; + } } - } - GNUNET_FS_download_sync_ (dc); + GNUNET_FS_download_sync_(dc); return GNUNET_YES; signal_error: if (NULL != fh) - GNUNET_DISK_file_close (fh); + GNUNET_DISK_file_close(fh); pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR; pi.value.download.specifics.error.message = dc->emsg; - GNUNET_FS_download_make_status_ (&pi, dc); - GNUNET_MQ_destroy (dc->mq); + GNUNET_FS_download_make_status_(&pi, dc); + GNUNET_MQ_destroy(dc->mq); dc->mq = NULL; - GNUNET_FS_free_download_request_ (dc->top_request); + GNUNET_FS_free_download_request_(dc->top_request); dc->top_request = NULL; if (NULL != dc->job_queue) - { - GNUNET_FS_dequeue_ (dc->job_queue); - dc->job_queue = NULL; - } - GNUNET_FS_download_sync_ (dc); + { + GNUNET_FS_dequeue_(dc->job_queue); + dc->job_queue = NULL; + } + GNUNET_FS_download_sync_(dc); return GNUNET_NO; } @@ -1281,7 +1297,7 @@ signal_error: * @param msg message received */ static int -check_put (void *cls, const struct ClientPutMessage *cm) +check_put(void *cls, const struct ClientPutMessage *cm) { /* any varsize length is OK */ return GNUNET_OK; @@ -1296,28 +1312,28 @@ check_put (void *cls, const struct ClientPutMessage *cm) * @param msg message received */ static void -handle_put (void *cls, const struct ClientPutMessage *cm) +handle_put(void *cls, const struct ClientPutMessage *cm) { struct GNUNET_FS_DownloadContext *dc = cls; - uint16_t msize = ntohs (cm->header.size) - sizeof (*cm); + uint16_t msize = ntohs(cm->header.size) - sizeof(*cm); struct ProcessResultClosure prc; prc.dc = dc; prc.data = &cm[1]; - prc.last_transmission = GNUNET_TIME_absolute_ntoh (cm->last_transmission); + prc.last_transmission = GNUNET_TIME_absolute_ntoh(cm->last_transmission); prc.size = msize; - prc.type = ntohl (cm->type); + prc.type = ntohl(cm->type); prc.do_store = GNUNET_YES; - prc.respect_offered = ntohl (cm->respect_offered); - prc.num_transmissions = ntohl (cm->num_transmissions); - GNUNET_CRYPTO_hash (prc.data, msize, &prc.query); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received result for query `%s' from FS service\n", - GNUNET_h2s (&prc.query)); - GNUNET_CONTAINER_multihashmap_get_multiple (dc->active, - &prc.query, - &process_result_with_request, - &prc); + prc.respect_offered = ntohl(cm->respect_offered); + prc.num_transmissions = ntohl(cm->num_transmissions); + GNUNET_CRYPTO_hash(prc.data, msize, &prc.query); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received result for query `%s' from FS service\n", + GNUNET_h2s(&prc.query)); + GNUNET_CONTAINER_multihashmap_get_multiple(dc->active, + &prc.query, + &process_result_with_request, + &prc); } @@ -1330,18 +1346,18 @@ handle_put (void *cls, const struct ClientPutMessage *cm) * @param error error code */ static void -download_mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +download_mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_FS_DownloadContext *dc = cls; if (NULL != dc->mq) - { - GNUNET_MQ_destroy (dc->mq); - dc->mq = NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Transmitting download request failed, trying to reconnect\n"); - try_reconnect (dc); + { + GNUNET_MQ_destroy(dc->mq); + dc->mq = NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Transmitting download request failed, trying to reconnect\n"); + try_reconnect(dc); } @@ -1351,31 +1367,31 @@ download_mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @param cls our download context */ static void -do_reconnect (void *cls) +do_reconnect(void *cls) { struct GNUNET_FS_DownloadContext *dc = cls; struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_var_size (put, - GNUNET_MESSAGE_TYPE_FS_PUT, - struct ClientPutMessage, - dc), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_var_size(put, + GNUNET_MESSAGE_TYPE_FS_PUT, + struct ClientPutMessage, + dc), + GNUNET_MQ_handler_end() }; dc->task = NULL; - dc->mq = GNUNET_CLIENT_connect (dc->h->cfg, - "fs", - handlers, - &download_mq_error_handler, - dc); + dc->mq = GNUNET_CLIENT_connect(dc->h->cfg, + "fs", + handlers, + &download_mq_error_handler, + dc); if (NULL == dc->mq) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Connecting to `%s'-service failed, will try again.\n", - "FS"); - try_reconnect (dc); - return; - } - GNUNET_CONTAINER_multihashmap_iterate (dc->active, &retry_entry, dc); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Connecting to `%s'-service failed, will try again.\n", + "FS"); + try_reconnect(dc); + return; + } + GNUNET_CONTAINER_multihashmap_iterate(dc->active, &retry_entry, dc); } @@ -1387,27 +1403,27 @@ do_reconnect (void *cls) * @param dc download context that is having trouble */ static void -try_reconnect (struct GNUNET_FS_DownloadContext *dc) +try_reconnect(struct GNUNET_FS_DownloadContext *dc) { if (NULL != dc->mq) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Moving all requests back to pending list\n"); - GNUNET_MQ_destroy (dc->mq); - dc->mq = NULL; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Moving all requests back to pending list\n"); + GNUNET_MQ_destroy(dc->mq); + dc->mq = NULL; + } if (0 == dc->reconnect_backoff.rel_value_us) dc->reconnect_backoff = GNUNET_TIME_UNIT_MILLISECONDS; else - dc->reconnect_backoff = GNUNET_TIME_STD_BACKOFF (dc->reconnect_backoff); + dc->reconnect_backoff = GNUNET_TIME_STD_BACKOFF(dc->reconnect_backoff); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Will try to reconnect in %s\n", - GNUNET_STRINGS_relative_time_to_string (dc->reconnect_backoff, - GNUNET_YES)); - GNUNET_break (NULL != dc->job_queue); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Will try to reconnect in %s\n", + GNUNET_STRINGS_relative_time_to_string(dc->reconnect_backoff, + GNUNET_YES)); + GNUNET_break(NULL != dc->job_queue); dc->task = - GNUNET_SCHEDULER_add_delayed (dc->reconnect_backoff, &do_reconnect, dc); + GNUNET_SCHEDULER_add_delayed(dc->reconnect_backoff, &do_reconnect, dc); } @@ -1418,18 +1434,18 @@ try_reconnect (struct GNUNET_FS_DownloadContext *dc) * @param mq handle to use for communcation with FS (we must destroy it!) */ static void -activate_fs_download (void *cls) +activate_fs_download(void *cls) { struct GNUNET_FS_DownloadContext *dc = cls; struct GNUNET_FS_ProgressInfo pi; - GNUNET_assert (NULL == dc->mq); - GNUNET_assert (NULL != dc->active); - do_reconnect (dc); + GNUNET_assert(NULL == dc->mq); + GNUNET_assert(NULL != dc->active); + do_reconnect(dc); if (NULL != dc->mq) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download activated\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Download activated\n"); pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE; - GNUNET_FS_download_make_status_ (&pi, dc); + GNUNET_FS_download_make_status_(&pi, dc); } @@ -1439,19 +1455,19 @@ activate_fs_download (void *cls) * @param cls the `struct GNUNET_FS_DownloadContext` */ static void -deactivate_fs_download (void *cls) +deactivate_fs_download(void *cls) { struct GNUNET_FS_DownloadContext *dc = cls; struct GNUNET_FS_ProgressInfo pi; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download deactivated\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Download deactivated\n"); if (NULL != dc->mq) - { - GNUNET_MQ_destroy (dc->mq); - dc->mq = NULL; - } + { + GNUNET_MQ_destroy(dc->mq); + dc->mq = NULL; + } pi.status = GNUNET_FS_STATUS_DOWNLOAD_INACTIVE; - GNUNET_FS_download_make_status_ (&pi, dc); + GNUNET_FS_download_make_status_(&pi, dc); } @@ -1475,38 +1491,38 @@ deactivate_fs_download (void *cls) * the specified depth */ static struct DownloadRequest * -create_download_request (struct DownloadRequest *parent, - unsigned int chk_idx, - unsigned int depth, - uint64_t dr_offset, - uint64_t file_start_offset, - uint64_t desired_length) +create_download_request(struct DownloadRequest *parent, + unsigned int chk_idx, + unsigned int depth, + uint64_t dr_offset, + uint64_t file_start_offset, + uint64_t desired_length) { struct DownloadRequest *dr; unsigned int i; unsigned int head_skip; uint64_t child_block_size; - dr = GNUNET_new (struct DownloadRequest); + dr = GNUNET_new(struct DownloadRequest); dr->parent = parent; dr->depth = depth; dr->offset = dr_offset; dr->chk_idx = chk_idx; if (0 == depth) return dr; - child_block_size = GNUNET_FS_tree_compute_tree_size (depth - 1); + child_block_size = GNUNET_FS_tree_compute_tree_size(depth - 1); /* calculate how many blocks at this level are not interesting * from the start (rounded down), either because of the requested * file offset or because this IBlock is further along */ if (dr_offset < file_start_offset) - { - head_skip = (file_start_offset - dr_offset) / child_block_size; - } + { + head_skip = (file_start_offset - dr_offset) / child_block_size; + } else - { - head_skip = 0; - } + { + head_skip = 0; + } /* calculate index of last block at this level that is interesting (rounded up) */ dr->num_children = @@ -1514,32 +1530,32 @@ create_download_request (struct DownloadRequest *parent, if (dr->num_children * child_block_size < file_start_offset + desired_length - dr_offset) dr->num_children++; /* round up */ - GNUNET_assert (dr->num_children > head_skip); + GNUNET_assert(dr->num_children > head_skip); dr->num_children -= head_skip; if (dr->num_children > CHK_PER_INODE) dr->num_children = CHK_PER_INODE; /* cap at max */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Block at offset %llu and depth %u has %u children\n", - (unsigned long long) dr_offset, - depth, - dr->num_children); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Block at offset %llu and depth %u has %u children\n", + (unsigned long long)dr_offset, + depth, + dr->num_children); /* now we can get the total number of *interesting* children for this block */ /* why else would we have gotten here to begin with? (that'd be a bad logic error) */ - GNUNET_assert (dr->num_children > 0); + GNUNET_assert(dr->num_children > 0); - dr->children = GNUNET_new_array (dr->num_children, struct DownloadRequest *); + dr->children = GNUNET_new_array(dr->num_children, struct DownloadRequest *); for (i = 0; i < dr->num_children; i++) - { - dr->children[i] = - create_download_request (dr, - i + head_skip, - depth - 1, - dr_offset + (i + head_skip) * child_block_size, - file_start_offset, - desired_length); - } + { + dr->children[i] = + create_download_request(dr, + i + head_skip, + depth - 1, + dr_offset + (i + head_skip) * child_block_size, + file_start_offset, + desired_length); + } return dr; } @@ -1551,25 +1567,25 @@ create_download_request (struct DownloadRequest *parent, * @param cls the 'struct ReconstructContext' */ static void -reconstruct_cont (void *cls) +reconstruct_cont(void *cls) { struct GNUNET_FS_DownloadContext *dc = cls; /* clean up state from tree encoder */ if (NULL != dc->task) - { - GNUNET_SCHEDULER_cancel (dc->task); - dc->task = NULL; - } + { + GNUNET_SCHEDULER_cancel(dc->task); + dc->task = NULL; + } if (NULL != dc->rfh) - { - GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (dc->rfh)); - dc->rfh = NULL; - } + { + GNUNET_break(GNUNET_OK == GNUNET_DISK_file_close(dc->rfh)); + dc->rfh = NULL; + } /* start "normal" download */ dc->issue_requests = GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting normal download\n"); - schedule_block_download (dc, dc->top_request); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Starting normal download\n"); + schedule_block_download(dc, dc->top_request); } @@ -1579,12 +1595,12 @@ reconstruct_cont (void *cls) * @param cls the 'struct GNUJNET_FS_DownloadContext' we're processing */ static void -get_next_block (void *cls) +get_next_block(void *cls) { struct GNUNET_FS_DownloadContext *dc = cls; dc->task = NULL; - GNUNET_FS_tree_encoder_next (dc->te); + GNUNET_FS_tree_encoder_next(dc->te); } @@ -1606,13 +1622,13 @@ get_next_block (void *cls) * @param block_size size of block (in bytes) */ static void -reconstruct_cb (void *cls, - const struct ContentHashKey *chk, - uint64_t offset, - unsigned int depth, - enum GNUNET_BLOCK_Type type, - const void *block, - uint16_t block_size) +reconstruct_cb(void *cls, + const struct ContentHashKey *chk, + uint64_t offset, + unsigned int depth, + enum GNUNET_BLOCK_Type type, + const void *block, + uint16_t block_size) { struct GNUNET_FS_DownloadContext *dc = cls; struct GNUNET_FS_ProgressInfo pi; @@ -1623,117 +1639,125 @@ reconstruct_cb (void *cls, /* find corresponding request entry */ dr = dc->top_request; while (dr->depth > depth) - { - GNUNET_assert (dr->num_children > 0); - blen = GNUNET_FS_tree_compute_tree_size (dr->depth - 1); - chld = (offset - dr->offset) / blen; - if (chld < dr->children[0]->chk_idx) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Block %u < %u irrelevant for our range\n", - chld, - dr->children[0]->chk_idx); - dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc); - return; /* irrelevant block */ - } - if (chld > dr->children[dr->num_children - 1]->chk_idx) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Block %u > %u irrelevant for our range\n", - chld, - dr->children[dr->num_children - 1]->chk_idx); - dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc); - return; /* irrelevant block */ - } - dr = dr->children[chld - dr->children[0]->chk_idx]; - } - GNUNET_log ( + { + GNUNET_assert(dr->num_children > 0); + blen = GNUNET_FS_tree_compute_tree_size(dr->depth - 1); + chld = (offset - dr->offset) / blen; + if (chld < dr->children[0]->chk_idx) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Block %u < %u irrelevant for our range\n", + chld, + dr->children[0]->chk_idx); + dc->task = GNUNET_SCHEDULER_add_now(&get_next_block, dc); + return; /* irrelevant block */ + } + if (chld > dr->children[dr->num_children - 1]->chk_idx) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Block %u > %u irrelevant for our range\n", + chld, + dr->children[dr->num_children - 1]->chk_idx); + dc->task = GNUNET_SCHEDULER_add_now(&get_next_block, dc); + return; /* irrelevant block */ + } + dr = dr->children[chld - dr->children[0]->chk_idx]; + } + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "Matched TE block with request at offset %llu and depth %u in state %d\n", - (unsigned long long) dr->offset, + (unsigned long long)dr->offset, dr->depth, dr->state); /* FIXME: this code needs more testing and might need to handle more states... */ switch (dr->state) - { - case BRS_INIT: - break; - case BRS_RECONSTRUCT_DOWN: - break; - case BRS_RECONSTRUCT_META_UP: - break; - case BRS_RECONSTRUCT_UP: - break; - case BRS_CHK_SET: - if (0 == memcmp (chk, &dr->chk, sizeof (struct ContentHashKey))) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Reconstruction succeeded, can use block at offset %llu, depth %u\n", - (unsigned long long) offset, - depth); - /* block matches, hence tree below matches; - * this request is done! */ - dr->state = BRS_DOWNLOAD_UP; - (void) GNUNET_CONTAINER_multihashmap_remove (dc->active, - &dr->chk.query, - dr); - /* calculate how many bytes of payload this block - * corresponds to */ - blen = GNUNET_FS_tree_compute_tree_size (dr->depth); - /* how many of those bytes are in the requested range? */ - blen = GNUNET_MIN (blen, dc->length + dc->offset - dr->offset); - /* signal progress */ - dc->completed += blen; - pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS; - pi.value.download.specifics.progress.data = NULL; - pi.value.download.specifics.progress.offset = offset; - pi.value.download.specifics.progress.data_len = 0; - pi.value.download.specifics.progress.depth = 0; - pi.value.download.specifics.progress.respect_offered = 0; - pi.value.download.specifics.progress.block_download_duration = - GNUNET_TIME_UNIT_ZERO; - GNUNET_FS_download_make_status_ (&pi, dc); - /* FIXME: duplicated code from 'process_result_with_request - refactor */ - if (dc->completed == dc->length) - { - /* download completed, signal */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Download completed, truncating file to desired length %llu\n", - (unsigned long long) GNUNET_ntohll ( - dc->uri->data.chk.file_length)); - /* truncate file to size (since we store IBlocks at the end) */ - if (NULL != dc->filename) + { + case BRS_INIT: + break; + + case BRS_RECONSTRUCT_DOWN: + break; + + case BRS_RECONSTRUCT_META_UP: + break; + + case BRS_RECONSTRUCT_UP: + break; + + case BRS_CHK_SET: + if (0 == memcmp(chk, &dr->chk, sizeof(struct ContentHashKey))) { - if (0 != truncate (dc->filename, - GNUNET_ntohll (dc->uri->data.chk.file_length))) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, - "truncate", - dc->filename); + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Reconstruction succeeded, can use block at offset %llu, depth %u\n", + (unsigned long long)offset, + depth); + /* block matches, hence tree below matches; + * this request is done! */ + dr->state = BRS_DOWNLOAD_UP; + (void)GNUNET_CONTAINER_multihashmap_remove(dc->active, + &dr->chk.query, + dr); + /* calculate how many bytes of payload this block + * corresponds to */ + blen = GNUNET_FS_tree_compute_tree_size(dr->depth); + /* how many of those bytes are in the requested range? */ + blen = GNUNET_MIN(blen, dc->length + dc->offset - dr->offset); + /* signal progress */ + dc->completed += blen; + pi.status = GNUNET_FS_STATUS_DOWNLOAD_PROGRESS; + pi.value.download.specifics.progress.data = NULL; + pi.value.download.specifics.progress.offset = offset; + pi.value.download.specifics.progress.data_len = 0; + pi.value.download.specifics.progress.depth = 0; + pi.value.download.specifics.progress.respect_offered = 0; + pi.value.download.specifics.progress.block_download_duration = + GNUNET_TIME_UNIT_ZERO; + GNUNET_FS_download_make_status_(&pi, dc); + /* FIXME: duplicated code from 'process_result_with_request - refactor */ + if (dc->completed == dc->length) + { + /* download completed, signal */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Download completed, truncating file to desired length %llu\n", + (unsigned long long)GNUNET_ntohll( + dc->uri->data.chk.file_length)); + /* truncate file to size (since we store IBlocks at the end) */ + if (NULL != dc->filename) + { + if (0 != truncate(dc->filename, + GNUNET_ntohll(dc->uri->data.chk.file_length))) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, + "truncate", + dc->filename); + } + } } - } + else + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Reconstruction failed, need to download block at offset %llu, depth %u\n", + (unsigned long long)offset, + depth); + break; + + case BRS_DOWNLOAD_DOWN: + break; + + case BRS_DOWNLOAD_UP: + break; + + case BRS_ERROR: + break; + + default: + GNUNET_assert(0); + break; } - else - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Reconstruction failed, need to download block at offset %llu, depth %u\n", - (unsigned long long) offset, - depth); - break; - case BRS_DOWNLOAD_DOWN: - break; - case BRS_DOWNLOAD_UP: - break; - case BRS_ERROR: - break; - default: - GNUNET_assert (0); - break; - } - dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc); + dc->task = GNUNET_SCHEDULER_add_now(&get_next_block, dc); if ((dr == dc->top_request) && (dr->state == BRS_DOWNLOAD_UP)) - check_completed (dc); + check_completed(dc); } @@ -1750,7 +1774,7 @@ reconstruct_cb (void *cls, * @return number of bytes copied to buf, 0 on error */ static size_t -fh_reader (void *cls, uint64_t offset, size_t max, void *buf, char **emsg) +fh_reader(void *cls, uint64_t offset, size_t max, void *buf, char **emsg) { struct GNUNET_FS_DownloadContext *dc = cls; struct GNUNET_DISK_FileHandle *fh = dc->rfh; @@ -1758,19 +1782,19 @@ fh_reader (void *cls, uint64_t offset, size_t max, void *buf, char **emsg) if (NULL != emsg) *emsg = NULL; - if (offset != GNUNET_DISK_file_seek (fh, offset, GNUNET_DISK_SEEK_SET)) - { - if (NULL != emsg) - *emsg = GNUNET_strdup (strerror (errno)); - return 0; - } - ret = GNUNET_DISK_file_read (fh, buf, max); + if (offset != GNUNET_DISK_file_seek(fh, offset, GNUNET_DISK_SEEK_SET)) + { + if (NULL != emsg) + *emsg = GNUNET_strdup(strerror(errno)); + return 0; + } + ret = GNUNET_DISK_file_read(fh, buf, max); if (ret < 0) - { - if (NULL != emsg) - *emsg = GNUNET_strdup (strerror (errno)); - return 0; - } + { + if (NULL != emsg) + *emsg = GNUNET_strdup(strerror(errno)); + return 0; + } return ret; } @@ -1782,151 +1806,155 @@ fh_reader (void *cls, uint64_t offset, size_t max, void *buf, char **emsg) * @param cls the 'struct GNUNET_FS_DownloadContext' */ void -GNUNET_FS_download_start_task_ (void *cls) +GNUNET_FS_download_start_task_(void *cls) { struct GNUNET_FS_DownloadContext *dc = cls; struct GNUNET_FS_ProgressInfo pi; struct GNUNET_DISK_FileHandle *fh; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Start task running...\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Start task running...\n"); dc->task = NULL; if (0 == dc->length) - { - /* no bytes required! */ - if (NULL != dc->filename) - { - fh = GNUNET_DISK_file_open (dc->filename, - GNUNET_DISK_OPEN_READWRITE | - GNUNET_DISK_OPEN_CREATE | - ((0 == - GNUNET_FS_uri_chk_get_file_size (dc->uri)) - ? GNUNET_DISK_OPEN_TRUNCATE - : 0), - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_GROUP_READ | - GNUNET_DISK_PERM_OTHER_READ); - GNUNET_DISK_file_close (fh); - } - GNUNET_FS_download_sync_ (dc); - pi.status = GNUNET_FS_STATUS_DOWNLOAD_START; - pi.value.download.specifics.start.meta = dc->meta; - GNUNET_FS_download_make_status_ (&pi, dc); - check_completed (dc); - return; - } + { + /* no bytes required! */ + if (NULL != dc->filename) + { + fh = GNUNET_DISK_file_open(dc->filename, + GNUNET_DISK_OPEN_READWRITE | + GNUNET_DISK_OPEN_CREATE | + ((0 == + GNUNET_FS_uri_chk_get_file_size(dc->uri)) + ? GNUNET_DISK_OPEN_TRUNCATE + : 0), + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_GROUP_READ | + GNUNET_DISK_PERM_OTHER_READ); + GNUNET_DISK_file_close(fh); + } + GNUNET_FS_download_sync_(dc); + pi.status = GNUNET_FS_STATUS_DOWNLOAD_START; + pi.value.download.specifics.start.meta = dc->meta; + GNUNET_FS_download_make_status_(&pi, dc); + check_completed(dc); + return; + } if (NULL != dc->emsg) return; if (NULL == dc->top_request) - { - dc->top_request = create_download_request (NULL, - 0, - dc->treedepth - 1, - 0, - dc->offset, - dc->length); - dc->top_request->state = BRS_CHK_SET; - dc->top_request->chk = (dc->uri->type == GNUNET_FS_URI_CHK) + { + dc->top_request = create_download_request(NULL, + 0, + dc->treedepth - 1, + 0, + dc->offset, + dc->length); + dc->top_request->state = BRS_CHK_SET; + dc->top_request->chk = (dc->uri->type == GNUNET_FS_URI_CHK) ? dc->uri->data.chk.chk : dc->uri->data.loc.fi.chk; - /* signal start */ - GNUNET_FS_download_sync_ (dc); - if (NULL != dc->search) - GNUNET_FS_search_result_sync_ (dc->search); - pi.status = GNUNET_FS_STATUS_DOWNLOAD_START; - pi.value.download.specifics.start.meta = dc->meta; - GNUNET_FS_download_make_status_ (&pi, dc); - } - GNUNET_FS_download_start_downloading_ (dc); + /* signal start */ + GNUNET_FS_download_sync_(dc); + if (NULL != dc->search) + GNUNET_FS_search_result_sync_(dc->search); + pi.status = GNUNET_FS_STATUS_DOWNLOAD_START; + pi.value.download.specifics.start.meta = dc->meta; + GNUNET_FS_download_make_status_(&pi, dc); + } + GNUNET_FS_download_start_downloading_(dc); /* attempt reconstruction from disk */ - if (GNUNET_YES == GNUNET_DISK_file_test (dc->filename)) - dc->rfh = GNUNET_DISK_file_open (dc->filename, - GNUNET_DISK_OPEN_READ, - GNUNET_DISK_PERM_NONE); + if (GNUNET_YES == GNUNET_DISK_file_test(dc->filename)) + dc->rfh = GNUNET_DISK_file_open(dc->filename, + GNUNET_DISK_OPEN_READ, + GNUNET_DISK_PERM_NONE); if (dc->top_request->state == BRS_CHK_SET) - { - if (NULL != dc->rfh) - { - /* first, try top-down */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Trying top-down reconstruction for `%s'\n", - dc->filename); - try_top_down_reconstruction (dc, dc->top_request); - switch (dc->top_request->state) - { - case BRS_CHK_SET: - break; /* normal */ - case BRS_DOWNLOAD_DOWN: - break; /* normal, some blocks already down */ - case BRS_DOWNLOAD_UP: - /* already done entirely, party! */ - if (NULL != dc->rfh) + { + if (NULL != dc->rfh) { - /* avoid hanging on to file handle longer than - * necessary */ - GNUNET_DISK_file_close (dc->rfh); - dc->rfh = NULL; + /* first, try top-down */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Trying top-down reconstruction for `%s'\n", + dc->filename); + try_top_down_reconstruction(dc, dc->top_request); + switch (dc->top_request->state) + { + case BRS_CHK_SET: + break; /* normal */ + + case BRS_DOWNLOAD_DOWN: + break; /* normal, some blocks already down */ + + case BRS_DOWNLOAD_UP: + /* already done entirely, party! */ + if (NULL != dc->rfh) + { + /* avoid hanging on to file handle longer than + * necessary */ + GNUNET_DISK_file_close(dc->rfh); + dc->rfh = NULL; + } + return; + + case BRS_ERROR: + GNUNET_asprintf(&dc->emsg, _("Invalid URI")); + GNUNET_FS_download_sync_(dc); + pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR; + pi.value.download.specifics.error.message = dc->emsg; + GNUNET_FS_download_make_status_(&pi, dc); + return; + + default: + GNUNET_assert(0); + break; + } } - return; - case BRS_ERROR: - GNUNET_asprintf (&dc->emsg, _ ("Invalid URI")); - GNUNET_FS_download_sync_ (dc); - pi.status = GNUNET_FS_STATUS_DOWNLOAD_ERROR; - pi.value.download.specifics.error.message = dc->emsg; - GNUNET_FS_download_make_status_ (&pi, dc); - return; - default: - GNUNET_assert (0); - break; - } } - } /* attempt reconstruction from meta data */ - if ((GNUNET_FS_uri_chk_get_file_size (dc->uri) <= MAX_INLINE_SIZE) && + if ((GNUNET_FS_uri_chk_get_file_size(dc->uri) <= MAX_INLINE_SIZE) && (NULL != dc->meta)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Trying to find embedded meta data for download of size %llu with %u bytes MD\n", - (unsigned long long) GNUNET_FS_uri_chk_get_file_size (dc->uri), - (unsigned int) GNUNET_CONTAINER_meta_data_get_serialized_size (dc->meta)); - GNUNET_CONTAINER_meta_data_iterate (dc->meta, &match_full_data, dc); - if (BRS_DOWNLOAD_UP == dc->top_request->state) { - if (NULL != dc->rfh) - { - /* avoid hanging on to file handle longer than - * necessary */ - GNUNET_DISK_file_close (dc->rfh); - dc->rfh = NULL; - } - return; /* finished, status update was already done for us */ - } - } + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Trying to find embedded meta data for download of size %llu with %u bytes MD\n", + (unsigned long long)GNUNET_FS_uri_chk_get_file_size(dc->uri), + (unsigned int)GNUNET_CONTAINER_meta_data_get_serialized_size(dc->meta)); + GNUNET_CONTAINER_meta_data_iterate(dc->meta, &match_full_data, dc); + if (BRS_DOWNLOAD_UP == dc->top_request->state) + { + if (NULL != dc->rfh) + { + /* avoid hanging on to file handle longer than + * necessary */ + GNUNET_DISK_file_close(dc->rfh); + dc->rfh = NULL; + } + return; /* finished, status update was already done for us */ + } + } if (NULL != dc->rfh) - { - /* finally, actually run bottom-up */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Trying bottom-up reconstruction of file `%s'\n", - dc->filename); - dc->te = - GNUNET_FS_tree_encoder_create (dc->h, - GNUNET_FS_uri_chk_get_file_size (dc->uri), - dc, - &fh_reader, - &reconstruct_cb, - NULL, - &reconstruct_cont); - dc->task = GNUNET_SCHEDULER_add_now (&get_next_block, dc); - } + { + /* finally, actually run bottom-up */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Trying bottom-up reconstruction of file `%s'\n", + dc->filename); + dc->te = + GNUNET_FS_tree_encoder_create(dc->h, + GNUNET_FS_uri_chk_get_file_size(dc->uri), + dc, + &fh_reader, + &reconstruct_cb, + NULL, + &reconstruct_cont); + dc->task = GNUNET_SCHEDULER_add_now(&get_next_block, dc); + } else - { - /* simple, top-level download */ - dc->issue_requests = GNUNET_YES; - schedule_block_download (dc, dc->top_request); - } + { + /* simple, top-level download */ + dc->issue_requests = GNUNET_YES; + schedule_block_download(dc, dc->top_request); + } if (BRS_DOWNLOAD_UP == dc->top_request->state) - check_completed (dc); + check_completed(dc); } @@ -1937,59 +1965,59 @@ GNUNET_FS_download_start_task_ (void *cls) * @param cls the 'struct GNUNET_FS_DownloadContext' to signal for */ void -GNUNET_FS_download_signal_suspend_ (void *cls) +GNUNET_FS_download_signal_suspend_(void *cls) { struct GNUNET_FS_DownloadContext *dc = cls; struct GNUNET_FS_ProgressInfo pi; if (NULL != dc->top) - GNUNET_FS_end_top (dc->h, dc->top); + GNUNET_FS_end_top(dc->h, dc->top); while (NULL != dc->child_head) - GNUNET_FS_download_signal_suspend_ (dc->child_head); + GNUNET_FS_download_signal_suspend_(dc->child_head); if (NULL != dc->search) - { - dc->search->download = NULL; - dc->search = NULL; - } + { + dc->search->download = NULL; + dc->search = NULL; + } if (NULL != dc->job_queue) - { - GNUNET_FS_dequeue_ (dc->job_queue); - dc->job_queue = NULL; - } + { + GNUNET_FS_dequeue_(dc->job_queue); + dc->job_queue = NULL; + } if (NULL != dc->parent) - GNUNET_CONTAINER_DLL_remove (dc->parent->child_head, - dc->parent->child_tail, - dc); + GNUNET_CONTAINER_DLL_remove(dc->parent->child_head, + dc->parent->child_tail, + dc); if (NULL != dc->task) - { - GNUNET_SCHEDULER_cancel (dc->task); - dc->task = NULL; - } + { + GNUNET_SCHEDULER_cancel(dc->task); + dc->task = NULL; + } pi.status = GNUNET_FS_STATUS_DOWNLOAD_SUSPEND; - GNUNET_FS_download_make_status_ (&pi, dc); + GNUNET_FS_download_make_status_(&pi, dc); if (NULL != dc->te) - { - GNUNET_FS_tree_encoder_finish (dc->te, NULL); - dc->te = NULL; - } + { + GNUNET_FS_tree_encoder_finish(dc->te, NULL); + dc->te = NULL; + } if (NULL != dc->rfh) - { - GNUNET_DISK_file_close (dc->rfh); - dc->rfh = NULL; - } - GNUNET_FS_free_download_request_ (dc->top_request); + { + GNUNET_DISK_file_close(dc->rfh); + dc->rfh = NULL; + } + GNUNET_FS_free_download_request_(dc->top_request); if (NULL != dc->active) - { - GNUNET_CONTAINER_multihashmap_destroy (dc->active); - dc->active = NULL; - } - GNUNET_free_non_null (dc->filename); - GNUNET_CONTAINER_meta_data_destroy (dc->meta); - GNUNET_FS_uri_destroy (dc->uri); - GNUNET_free_non_null (dc->temp_filename); - GNUNET_free_non_null (dc->serialization); - GNUNET_assert (NULL == dc->job_queue); - GNUNET_free (dc); + { + GNUNET_CONTAINER_multihashmap_destroy(dc->active); + dc->active = NULL; + } + GNUNET_free_non_null(dc->filename); + GNUNET_CONTAINER_meta_data_destroy(dc->meta); + GNUNET_FS_uri_destroy(dc->uri); + GNUNET_free_non_null(dc->temp_filename); + GNUNET_free_non_null(dc->serialization); + GNUNET_assert(NULL == dc->job_queue); + GNUNET_free(dc); } @@ -2013,72 +2041,72 @@ GNUNET_FS_download_signal_suspend_ (void *cls) * @return context that can be used to control this download */ struct GNUNET_FS_DownloadContext * -create_download_context (struct GNUNET_FS_Handle *h, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *meta, - const char *filename, - const char *tempname, - uint64_t offset, - uint64_t length, - uint32_t anonymity, - enum GNUNET_FS_DownloadOptions options, - void *cctx) +create_download_context(struct GNUNET_FS_Handle *h, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *meta, + const char *filename, + const char *tempname, + uint64_t offset, + uint64_t length, + uint32_t anonymity, + enum GNUNET_FS_DownloadOptions options, + void *cctx) { struct GNUNET_FS_DownloadContext *dc; - GNUNET_assert (GNUNET_FS_uri_test_chk (uri) || GNUNET_FS_uri_test_loc (uri)); + GNUNET_assert(GNUNET_FS_uri_test_chk(uri) || GNUNET_FS_uri_test_loc(uri)); if ((offset + length < offset) || - (offset + length > GNUNET_FS_uri_chk_get_file_size (uri))) - { - GNUNET_break (0); - return NULL; - } - dc = GNUNET_new (struct GNUNET_FS_DownloadContext); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting download %p, %u bytes at offset %llu\n", - dc, - (unsigned int) length, - (unsigned long long) offset); + (offset + length > GNUNET_FS_uri_chk_get_file_size(uri))) + { + GNUNET_break(0); + return NULL; + } + dc = GNUNET_new(struct GNUNET_FS_DownloadContext); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting download %p, %u bytes at offset %llu\n", + dc, + (unsigned int)length, + (unsigned long long)offset); dc->h = h; - dc->uri = GNUNET_FS_uri_dup (uri); - dc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta); + dc->uri = GNUNET_FS_uri_dup(uri); + dc->meta = GNUNET_CONTAINER_meta_data_duplicate(meta); dc->client_info = cctx; - dc->start_time = GNUNET_TIME_absolute_get (); + dc->start_time = GNUNET_TIME_absolute_get(); if (NULL != filename) - { - dc->filename = GNUNET_strdup (filename); - if (GNUNET_YES == GNUNET_DISK_file_test (filename)) - GNUNET_break (GNUNET_OK == GNUNET_DISK_file_size (filename, + { + dc->filename = GNUNET_strdup(filename); + if (GNUNET_YES == GNUNET_DISK_file_test(filename)) + GNUNET_break(GNUNET_OK == GNUNET_DISK_file_size(filename, &dc->old_file_size, GNUNET_YES, GNUNET_YES)); - } - if (GNUNET_FS_uri_test_loc (dc->uri)) - GNUNET_assert (GNUNET_OK == - GNUNET_FS_uri_loc_get_peer_identity (dc->uri, &dc->target)); + } + if (GNUNET_FS_uri_test_loc(dc->uri)) + GNUNET_assert(GNUNET_OK == + GNUNET_FS_uri_loc_get_peer_identity(dc->uri, &dc->target)); dc->offset = offset; dc->length = length; dc->anonymity = anonymity; dc->options = options; dc->active = - GNUNET_CONTAINER_multihashmap_create (1 + 2 * (length / DBLOCK_SIZE), - GNUNET_NO); + GNUNET_CONTAINER_multihashmap_create(1 + 2 * (length / DBLOCK_SIZE), + GNUNET_NO); dc->treedepth = - GNUNET_FS_compute_depth (GNUNET_FS_uri_chk_get_file_size (dc->uri)); - if ((NULL == filename) && (is_recursive_download (dc))) - { - if (NULL != tempname) - dc->temp_filename = GNUNET_strdup (tempname); - else - dc->temp_filename = GNUNET_DISK_mktemp ("gnunet-directory-download-tmp"); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting download `%s' of %llu bytes with tree depth %u\n", - filename, - (unsigned long long) length, - dc->treedepth); - GNUNET_assert (NULL == dc->job_queue); - dc->task = GNUNET_SCHEDULER_add_now (&GNUNET_FS_download_start_task_, dc); + GNUNET_FS_compute_depth(GNUNET_FS_uri_chk_get_file_size(dc->uri)); + if ((NULL == filename) && (is_recursive_download(dc))) + { + if (NULL != tempname) + dc->temp_filename = GNUNET_strdup(tempname); + else + dc->temp_filename = GNUNET_DISK_mktemp("gnunet-directory-download-tmp"); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting download `%s' of %llu bytes with tree depth %u\n", + filename, + (unsigned long long)length, + dc->treedepth); + GNUNET_assert(NULL == dc->job_queue); + dc->task = GNUNET_SCHEDULER_add_now(&GNUNET_FS_download_start_task_, dc); return dc; } @@ -2114,38 +2142,38 @@ create_download_context (struct GNUNET_FS_Handle *h, * @return context that can be used to control this download */ struct GNUNET_FS_DownloadContext * -GNUNET_FS_download_start (struct GNUNET_FS_Handle *h, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *meta, - const char *filename, - const char *tempname, - uint64_t offset, - uint64_t length, - uint32_t anonymity, - enum GNUNET_FS_DownloadOptions options, - void *cctx, - struct GNUNET_FS_DownloadContext *parent) +GNUNET_FS_download_start(struct GNUNET_FS_Handle *h, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *meta, + const char *filename, + const char *tempname, + uint64_t offset, + uint64_t length, + uint32_t anonymity, + enum GNUNET_FS_DownloadOptions options, + void *cctx, + struct GNUNET_FS_DownloadContext *parent) { struct GNUNET_FS_DownloadContext *dc; - dc = create_download_context (h, - uri, - meta, - filename, - tempname, - offset, - length, - anonymity, - options, - cctx); + dc = create_download_context(h, + uri, + meta, + filename, + tempname, + offset, + length, + anonymity, + options, + cctx); if (NULL == dc) return NULL; dc->parent = parent; if (NULL != parent) - GNUNET_CONTAINER_DLL_insert (parent->child_head, parent->child_tail, dc); + GNUNET_CONTAINER_DLL_insert(parent->child_head, parent->child_tail, dc); else if (0 == (GNUNET_FS_DOWNLOAD_IS_PROBE & options)) dc->top = - GNUNET_FS_make_top (dc->h, &GNUNET_FS_download_signal_suspend_, dc); + GNUNET_FS_make_top(dc->h, &GNUNET_FS_download_signal_suspend_, dc); return dc; } @@ -2185,43 +2213,43 @@ GNUNET_FS_download_start (struct GNUNET_FS_Handle *h, * @return context that can be used to control this download */ struct GNUNET_FS_DownloadContext * -GNUNET_FS_download_start_from_search (struct GNUNET_FS_Handle *h, - struct GNUNET_FS_SearchResult *sr, - const char *filename, - const char *tempname, - uint64_t offset, - uint64_t length, - uint32_t anonymity, - enum GNUNET_FS_DownloadOptions options, - void *cctx) +GNUNET_FS_download_start_from_search(struct GNUNET_FS_Handle *h, + struct GNUNET_FS_SearchResult *sr, + const char *filename, + const char *tempname, + uint64_t offset, + uint64_t length, + uint32_t anonymity, + enum GNUNET_FS_DownloadOptions options, + void *cctx) { struct GNUNET_FS_DownloadContext *dc; if ((NULL == sr) || (NULL != sr->download)) - { - GNUNET_break (0); - return NULL; - } - dc = create_download_context (h, - sr->uri, - sr->meta, - filename, - tempname, - offset, - length, - anonymity, - options, - cctx); + { + GNUNET_break(0); + return NULL; + } + dc = create_download_context(h, + sr->uri, + sr->meta, + filename, + tempname, + offset, + length, + anonymity, + options, + cctx); if (NULL == dc) return NULL; dc->search = sr; sr->download = dc; if (NULL != sr->probe_ctx) - { - GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES); - sr->probe_ctx = NULL; - GNUNET_FS_stop_probe_ping_task_ (sr); - } + { + GNUNET_FS_download_stop(sr->probe_ctx, GNUNET_YES); + sr->probe_ctx = NULL; + GNUNET_FS_stop_probe_ping_task_(sr); + } return dc; } @@ -2232,28 +2260,28 @@ GNUNET_FS_download_start_from_search (struct GNUNET_FS_Handle *h, * @param dc our download context */ void -GNUNET_FS_download_start_downloading_ (struct GNUNET_FS_DownloadContext *dc) +GNUNET_FS_download_start_downloading_(struct GNUNET_FS_DownloadContext *dc) { if (dc->completed == dc->length) return; if (NULL != dc->mq) return; /* already running */ - GNUNET_assert (NULL == dc->job_queue); - GNUNET_assert (NULL == dc->task); - GNUNET_assert (NULL != dc->active); + GNUNET_assert(NULL == dc->job_queue); + GNUNET_assert(NULL == dc->task); + GNUNET_assert(NULL != dc->active); dc->job_queue = - GNUNET_FS_queue_ (dc->h, - &activate_fs_download, - &deactivate_fs_download, - dc, - (dc->length + DBLOCK_SIZE - 1) / DBLOCK_SIZE, - (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE)) - ? GNUNET_FS_QUEUE_PRIORITY_NORMAL - : GNUNET_FS_QUEUE_PRIORITY_PROBE); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Download %p put into queue as job %p\n", - dc, - dc->job_queue); + GNUNET_FS_queue_(dc->h, + &activate_fs_download, + &deactivate_fs_download, + dc, + (dc->length + DBLOCK_SIZE - 1) / DBLOCK_SIZE, + (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE)) + ? GNUNET_FS_QUEUE_PRIORITY_NORMAL + : GNUNET_FS_QUEUE_PRIORITY_PROBE); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Download %p put into queue as job %p\n", + dc, + dc->job_queue); } /** @@ -2262,9 +2290,9 @@ GNUNET_FS_download_start_downloading_ (struct GNUNET_FS_DownloadContext *dc) * @param dc handle for the download */ void -GNUNET_FS_download_suspend (struct GNUNET_FS_DownloadContext *dc) +GNUNET_FS_download_suspend(struct GNUNET_FS_DownloadContext *dc) { - deactivate_fs_download (dc); + deactivate_fs_download(dc); } @@ -2274,23 +2302,23 @@ GNUNET_FS_download_suspend (struct GNUNET_FS_DownloadContext *dc) * @param dc handle for the download */ void -GNUNET_FS_download_resume (struct GNUNET_FS_DownloadContext *dc) +GNUNET_FS_download_resume(struct GNUNET_FS_DownloadContext *dc) { struct GNUNET_FS_ProgressInfo pi; pi.status = GNUNET_FS_STATUS_DOWNLOAD_ACTIVE; - GNUNET_FS_download_make_status_ (&pi, dc); + GNUNET_FS_download_make_status_(&pi, dc); - GNUNET_assert (NULL == dc->task); + GNUNET_assert(NULL == dc->task); dc->job_queue = - GNUNET_FS_queue_ (dc->h, - &activate_fs_download, - &deactivate_fs_download, - dc, - (dc->length + DBLOCK_SIZE - 1) / DBLOCK_SIZE, - (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE)) - ? GNUNET_FS_QUEUE_PRIORITY_NORMAL - : GNUNET_FS_QUEUE_PRIORITY_PROBE); + GNUNET_FS_queue_(dc->h, + &activate_fs_download, + &deactivate_fs_download, + dc, + (dc->length + DBLOCK_SIZE - 1) / DBLOCK_SIZE, + (0 == (dc->options & GNUNET_FS_DOWNLOAD_IS_PROBE)) + ? GNUNET_FS_QUEUE_PRIORITY_NORMAL + : GNUNET_FS_QUEUE_PRIORITY_PROBE); } @@ -2301,88 +2329,88 @@ GNUNET_FS_download_resume (struct GNUNET_FS_DownloadContext *dc) * @param do_delete delete files of incomplete downloads */ void -GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc, int do_delete) +GNUNET_FS_download_stop(struct GNUNET_FS_DownloadContext *dc, int do_delete) { struct GNUNET_FS_ProgressInfo pi; int have_children; int search_was_null; if (NULL != dc->top) - GNUNET_FS_end_top (dc->h, dc->top); + GNUNET_FS_end_top(dc->h, dc->top); if (NULL != dc->task) - { - GNUNET_SCHEDULER_cancel (dc->task); - dc->task = NULL; - } + { + GNUNET_SCHEDULER_cancel(dc->task); + dc->task = NULL; + } search_was_null = (NULL == dc->search); if (NULL != dc->search) - { - dc->search->download = NULL; - GNUNET_FS_search_result_sync_ (dc->search); - dc->search = NULL; - } + { + dc->search->download = NULL; + GNUNET_FS_search_result_sync_(dc->search); + dc->search = NULL; + } if (NULL != dc->job_queue) - { - GNUNET_FS_dequeue_ (dc->job_queue); - dc->job_queue = NULL; - } + { + GNUNET_FS_dequeue_(dc->job_queue); + dc->job_queue = NULL; + } if (NULL != dc->te) - { - GNUNET_FS_tree_encoder_finish (dc->te, NULL); - dc->te = NULL; - } + { + GNUNET_FS_tree_encoder_finish(dc->te, NULL); + dc->te = NULL; + } have_children = (NULL != dc->child_head) ? GNUNET_YES : GNUNET_NO; while (NULL != dc->child_head) - GNUNET_FS_download_stop (dc->child_head, do_delete); + GNUNET_FS_download_stop(dc->child_head, do_delete); if (NULL != dc->parent) - GNUNET_CONTAINER_DLL_remove (dc->parent->child_head, - dc->parent->child_tail, - dc); + GNUNET_CONTAINER_DLL_remove(dc->parent->child_head, + dc->parent->child_tail, + dc); if (NULL != dc->serialization) - GNUNET_FS_remove_sync_file_ (dc->h, - ((NULL != dc->parent) || (! search_was_null)) - ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD - : GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD, - dc->serialization); - if ((GNUNET_YES == have_children) && (NULL == dc->parent)) - GNUNET_FS_remove_sync_dir_ (dc->h, - (! search_was_null) - ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD - : GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD, + GNUNET_FS_remove_sync_file_(dc->h, + ((NULL != dc->parent) || (!search_was_null)) + ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD + : GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD, dc->serialization); + if ((GNUNET_YES == have_children) && (NULL == dc->parent)) + GNUNET_FS_remove_sync_dir_(dc->h, + (!search_was_null) + ? GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD + : GNUNET_FS_SYNC_PATH_MASTER_DOWNLOAD, + dc->serialization); pi.status = GNUNET_FS_STATUS_DOWNLOAD_STOPPED; - GNUNET_FS_download_make_status_ (&pi, dc); - GNUNET_FS_free_download_request_ (dc->top_request); + GNUNET_FS_download_make_status_(&pi, dc); + GNUNET_FS_free_download_request_(dc->top_request); dc->top_request = NULL; if (NULL != dc->active) - { - GNUNET_CONTAINER_multihashmap_destroy (dc->active); - dc->active = NULL; - } + { + GNUNET_CONTAINER_multihashmap_destroy(dc->active); + dc->active = NULL; + } if (NULL != dc->filename) - { - if ((dc->completed != dc->length) && (GNUNET_YES == do_delete)) - { - if ((0 != unlink (dc->filename)) && (ENOENT != errno)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, - "unlink", - dc->filename); - } - GNUNET_free (dc->filename); - } - GNUNET_CONTAINER_meta_data_destroy (dc->meta); - GNUNET_FS_uri_destroy (dc->uri); + { + if ((dc->completed != dc->length) && (GNUNET_YES == do_delete)) + { + if ((0 != unlink(dc->filename)) && (ENOENT != errno)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, + "unlink", + dc->filename); + } + GNUNET_free(dc->filename); + } + GNUNET_CONTAINER_meta_data_destroy(dc->meta); + GNUNET_FS_uri_destroy(dc->uri); if (NULL != dc->temp_filename) - { - if (0 != unlink (dc->temp_filename)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, - "unlink", - dc->temp_filename); - GNUNET_free (dc->temp_filename); - } - GNUNET_free_non_null (dc->serialization); - GNUNET_assert (NULL == dc->job_queue); - GNUNET_free (dc); + { + if (0 != unlink(dc->temp_filename)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, + "unlink", + dc->temp_filename); + GNUNET_free(dc->temp_filename); + } + GNUNET_free_non_null(dc->serialization); + GNUNET_assert(NULL == dc->job_queue); + GNUNET_free(dc); } /* end of fs_download.c */ diff --git a/src/fs/fs_file_information.c b/src/fs/fs_file_information.c index fbf3181ef..ccba1a8b4 100644 --- a/src/fs/fs_file_information.c +++ b/src/fs/fs_file_information.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_file_information.c @@ -42,7 +42,7 @@ * can be used to read this fi-struct from disk. */ const char * -GNUNET_FS_file_information_get_id (struct GNUNET_FS_FileInformation *s) +GNUNET_FS_file_information_get_id(struct GNUNET_FS_FileInformation *s) { if (NULL != s->dir) return NULL; @@ -56,7 +56,7 @@ GNUNET_FS_file_information_get_id (struct GNUNET_FS_FileInformation *s) * @return "filename" field of the structure (can be NULL) */ const char * -GNUNET_FS_file_information_get_filename (struct GNUNET_FS_FileInformation *s) +GNUNET_FS_file_information_get_filename(struct GNUNET_FS_FileInformation *s) { return s->filename; } @@ -71,12 +71,12 @@ GNUNET_FS_file_information_get_filename (struct GNUNET_FS_FileInformation *s) * @param filename filename to set */ void -GNUNET_FS_file_information_set_filename (struct GNUNET_FS_FileInformation *s, - const char *filename) +GNUNET_FS_file_information_set_filename(struct GNUNET_FS_FileInformation *s, + const char *filename) { - GNUNET_free_non_null (s->filename); + GNUNET_free_non_null(s->filename); if (filename) - s->filename = GNUNET_strdup (filename); + s->filename = GNUNET_strdup(filename); else s->filename = NULL; } @@ -97,7 +97,7 @@ GNUNET_FS_file_information_set_filename (struct GNUNET_FS_FileInformation *s, * @return publish structure entry for the file */ struct GNUNET_FS_FileInformation * -GNUNET_FS_file_information_create_from_file ( +GNUNET_FS_file_information_create_from_file( struct GNUNET_FS_Handle *h, void *client_info, const char *filename, @@ -118,58 +118,58 @@ GNUNET_FS_file_information_create_from_file ( /* FIXME: should include_symbolic_links be GNUNET_NO or GNUNET_YES here? */ if (GNUNET_OK != - GNUNET_DISK_file_size (filename, &fsize, GNUNET_NO, GNUNET_YES)) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", filename); - return NULL; - } - fi = GNUNET_FS_make_file_reader_context_ (filename); + GNUNET_DISK_file_size(filename, &fsize, GNUNET_NO, GNUNET_YES)) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "stat", filename); + return NULL; + } + fi = GNUNET_FS_make_file_reader_context_(filename); if (NULL == fi) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } ret = - GNUNET_FS_file_information_create_from_reader (h, - client_info, - fsize, - &GNUNET_FS_data_reader_file_, - fi, - keywords, - meta, - do_index, - bo); + GNUNET_FS_file_information_create_from_reader(h, + client_info, + fsize, + &GNUNET_FS_data_reader_file_, + fi, + keywords, + meta, + do_index, + bo); if (ret == NULL) return NULL; ret->h = h; - ret->filename = GNUNET_strdup (filename); -#if ! WINDOWS + ret->filename = GNUNET_strdup(filename); +#if !WINDOWS fn = filename; #else - plibc_conv_to_win_path (filename, fn_conv); + plibc_conv_to_win_path(filename, fn_conv); fn = fn_conv; #endif - while (NULL != (ss = strstr (fn, DIR_SEPARATOR_STR))) + while (NULL != (ss = strstr(fn, DIR_SEPARATOR_STR))) fn = ss + 1; /* FIXME: If we assume that on other platforms CRT is UTF-8-aware, then * this should be changed to EXTRACTOR_METAFORMAT_UTF8 */ -#if ! WINDOWS - GNUNET_CONTAINER_meta_data_insert (ret->meta, - "", - EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME, - EXTRACTOR_METAFORMAT_C_STRING, - "text/plain", - fn, - strlen (fn) + 1); +#if !WINDOWS + GNUNET_CONTAINER_meta_data_insert(ret->meta, + "", + EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME, + EXTRACTOR_METAFORMAT_C_STRING, + "text/plain", + fn, + strlen(fn) + 1); #else - GNUNET_CONTAINER_meta_data_insert (ret->meta, - "", - EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME, - EXTRACTOR_METAFORMAT_UTF8, - "text/plain", - fn, - strlen (fn) + 1); + GNUNET_CONTAINER_meta_data_insert(ret->meta, + "", + EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME, + EXTRACTOR_METAFORMAT_UTF8, + "text/plain", + fn, + strlen(fn) + 1); #endif return ret; } @@ -192,7 +192,7 @@ GNUNET_FS_file_information_create_from_file ( * @return publish structure entry for the file */ struct GNUNET_FS_FileInformation * -GNUNET_FS_file_information_create_from_data ( +GNUNET_FS_file_information_create_from_data( struct GNUNET_FS_Handle *h, void *client_info, uint64_t length, @@ -203,19 +203,19 @@ GNUNET_FS_file_information_create_from_data ( const struct GNUNET_FS_BlockOptions *bo) { if (GNUNET_YES == do_index) - { - GNUNET_break (0); - return NULL; - } - return GNUNET_FS_file_information_create_from_reader (h, - client_info, - length, - &GNUNET_FS_data_reader_copy_, - data, - keywords, - meta, - do_index, - bo); + { + GNUNET_break(0); + return NULL; + } + return GNUNET_FS_file_information_create_from_reader(h, + client_info, + length, + &GNUNET_FS_data_reader_copy_, + data, + keywords, + meta, + do_index, + bo); } @@ -236,7 +236,7 @@ GNUNET_FS_file_information_create_from_data ( * @return publish structure entry for the file */ struct GNUNET_FS_FileInformation * -GNUNET_FS_file_information_create_from_reader ( +GNUNET_FS_file_information_create_from_reader( struct GNUNET_FS_Handle *h, void *client_info, uint64_t length, @@ -250,17 +250,17 @@ GNUNET_FS_file_information_create_from_reader ( struct GNUNET_FS_FileInformation *ret; if ((GNUNET_YES == do_index) && (reader != &GNUNET_FS_data_reader_file_)) - { - GNUNET_break (0); - return NULL; - } - ret = GNUNET_new (struct GNUNET_FS_FileInformation); + { + GNUNET_break(0); + return NULL; + } + ret = GNUNET_new(struct GNUNET_FS_FileInformation); ret->h = h; ret->client_info = client_info; - ret->meta = GNUNET_CONTAINER_meta_data_duplicate (meta); + ret->meta = GNUNET_CONTAINER_meta_data_duplicate(meta); if (ret->meta == NULL) - ret->meta = GNUNET_CONTAINER_meta_data_create (); - ret->keywords = (keywords == NULL) ? NULL : GNUNET_FS_uri_dup (keywords); + ret->meta = GNUNET_CONTAINER_meta_data_create(); + ret->keywords = (keywords == NULL) ? NULL : GNUNET_FS_uri_dup(keywords); ret->data.file.reader = reader; ret->data.file.reader_cls = reader_cls; ret->data.file.do_index = do_index; @@ -277,7 +277,7 @@ GNUNET_FS_file_information_create_from_reader ( * @return #GNUNET_YES if so, #GNUNET_NO if not */ int -GNUNET_FS_file_information_is_directory ( +GNUNET_FS_file_information_is_directory( const struct GNUNET_FS_FileInformation *ent) { return ent->is_directory; @@ -297,7 +297,7 @@ GNUNET_FS_file_information_is_directory ( * @return publish structure entry for the directory , NULL on error */ struct GNUNET_FS_FileInformation * -GNUNET_FS_file_information_create_empty_directory ( +GNUNET_FS_file_information_create_empty_directory( struct GNUNET_FS_Handle *h, void *client_info, const struct GNUNET_FS_Uri *keywords, @@ -307,15 +307,15 @@ GNUNET_FS_file_information_create_empty_directory ( { struct GNUNET_FS_FileInformation *ret; - ret = GNUNET_new (struct GNUNET_FS_FileInformation); + ret = GNUNET_new(struct GNUNET_FS_FileInformation); ret->h = h; ret->client_info = client_info; - ret->meta = GNUNET_CONTAINER_meta_data_duplicate (meta); - ret->keywords = GNUNET_FS_uri_dup (keywords); + ret->meta = GNUNET_CONTAINER_meta_data_duplicate(meta); + ret->keywords = GNUNET_FS_uri_dup(keywords); ret->bo = *bo; ret->is_directory = GNUNET_YES; if (filename != NULL) - ret->filename = GNUNET_strdup (filename); + ret->filename = GNUNET_strdup(filename); return ret; } @@ -332,15 +332,15 @@ GNUNET_FS_file_information_create_empty_directory ( * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_FS_file_information_add (struct GNUNET_FS_FileInformation *dir, - struct GNUNET_FS_FileInformation *ent) +GNUNET_FS_file_information_add(struct GNUNET_FS_FileInformation *dir, + struct GNUNET_FS_FileInformation *ent) { if ((ent->dir != NULL) || (ent->next != NULL) || (dir->is_directory != GNUNET_YES)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } ent->dir = dir; ent->next = dir->data.dir.entries; dir->data.dir.entries = ent; @@ -364,45 +364,45 @@ GNUNET_FS_file_information_add (struct GNUNET_FS_FileInformation *dir, * @param proc_cls closure for @a proc */ void -GNUNET_FS_file_information_inspect (struct GNUNET_FS_FileInformation *dir, - GNUNET_FS_FileInformationProcessor proc, - void *proc_cls) +GNUNET_FS_file_information_inspect(struct GNUNET_FS_FileInformation *dir, + GNUNET_FS_FileInformationProcessor proc, + void *proc_cls) { struct GNUNET_FS_FileInformation *pos; int no; no = GNUNET_NO; if (GNUNET_OK != - proc (proc_cls, - dir, - (dir->is_directory == GNUNET_YES) ? dir->data.dir.dir_size - : dir->data.file.file_size, - dir->meta, - &dir->keywords, - &dir->bo, - (dir->is_directory == GNUNET_YES) ? &no : &dir->data.file.do_index, - &dir->client_info)) + proc(proc_cls, + dir, + (dir->is_directory == GNUNET_YES) ? dir->data.dir.dir_size + : dir->data.file.file_size, + dir->meta, + &dir->keywords, + &dir->bo, + (dir->is_directory == GNUNET_YES) ? &no : &dir->data.file.do_index, + &dir->client_info)) return; if (dir->is_directory != GNUNET_YES) return; pos = dir->data.dir.entries; while (pos != NULL) - { - no = GNUNET_NO; - if (GNUNET_OK != - proc (proc_cls, - pos, - (pos->is_directory == GNUNET_YES) ? pos->data.dir.dir_size - : pos->data.file.file_size, - pos->meta, - &pos->keywords, - &pos->bo, - (pos->is_directory == GNUNET_YES) ? &no - : &pos->data.file.do_index, - &pos->client_info)) - break; - pos = pos->next; - } + { + no = GNUNET_NO; + if (GNUNET_OK != + proc(proc_cls, + pos, + (pos->is_directory == GNUNET_YES) ? pos->data.dir.dir_size + : pos->data.file.file_size, + pos->meta, + &pos->keywords, + &pos->bo, + (pos->is_directory == GNUNET_YES) ? &no + : &pos->data.file.do_index, + &pos->client_info)) + break; + pos = pos->next; + } } @@ -417,75 +417,75 @@ GNUNET_FS_file_information_inspect (struct GNUNET_FS_FileInformation *dir, * @param cleaner_cls closure for @a cleaner */ void -GNUNET_FS_file_information_destroy (struct GNUNET_FS_FileInformation *fi, - GNUNET_FS_FileInformationProcessor cleaner, - void *cleaner_cls) +GNUNET_FS_file_information_destroy(struct GNUNET_FS_FileInformation *fi, + GNUNET_FS_FileInformationProcessor cleaner, + void *cleaner_cls) { struct GNUNET_FS_FileInformation *pos; int no; no = GNUNET_NO; if (GNUNET_YES == fi->is_directory) - { - /* clean up directory */ - while (NULL != (pos = fi->data.dir.entries)) { - fi->data.dir.entries = pos->next; - GNUNET_FS_file_information_destroy (pos, cleaner, cleaner_cls); + /* clean up directory */ + while (NULL != (pos = fi->data.dir.entries)) + { + fi->data.dir.entries = pos->next; + GNUNET_FS_file_information_destroy(pos, cleaner, cleaner_cls); + } + /* clean up client-info */ + if (NULL != cleaner) + cleaner(cleaner_cls, + fi, + fi->data.dir.dir_size, + fi->meta, + &fi->keywords, + &fi->bo, + &no, + &fi->client_info); + GNUNET_free_non_null(fi->data.dir.dir_data); } - /* clean up client-info */ - if (NULL != cleaner) - cleaner (cleaner_cls, - fi, - fi->data.dir.dir_size, - fi->meta, - &fi->keywords, - &fi->bo, - &no, - &fi->client_info); - GNUNET_free_non_null (fi->data.dir.dir_data); - } else - { - /* call clean-up function of the reader */ - if (NULL != fi->data.file.reader) { - (void) fi->data.file.reader (fi->data.file.reader_cls, 0, 0, NULL, NULL); - fi->data.file.reader = NULL; + /* call clean-up function of the reader */ + if (NULL != fi->data.file.reader) + { + (void)fi->data.file.reader(fi->data.file.reader_cls, 0, 0, NULL, NULL); + fi->data.file.reader = NULL; + } + /* clean up client-info */ + if (NULL != cleaner) + cleaner(cleaner_cls, + fi, + fi->data.file.file_size, + fi->meta, + &fi->keywords, + &fi->bo, + &fi->data.file.do_index, + &fi->client_info); } - /* clean up client-info */ - if (NULL != cleaner) - cleaner (cleaner_cls, - fi, - fi->data.file.file_size, - fi->meta, - &fi->keywords, - &fi->bo, - &fi->data.file.do_index, - &fi->client_info); - } - GNUNET_free_non_null (fi->filename); - GNUNET_free_non_null (fi->emsg); + GNUNET_free_non_null(fi->filename); + GNUNET_free_non_null(fi->emsg); if (NULL != fi->sks_uri) - GNUNET_FS_uri_destroy (fi->sks_uri); + GNUNET_FS_uri_destroy(fi->sks_uri); if (NULL != fi->chk_uri) - GNUNET_FS_uri_destroy (fi->chk_uri); + GNUNET_FS_uri_destroy(fi->chk_uri); /* clean up serialization */ - if ((NULL != fi->serialization) && (0 != unlink (fi->serialization))) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, - "unlink", - fi->serialization); + if ((NULL != fi->serialization) && (0 != unlink(fi->serialization))) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, + "unlink", + fi->serialization); if (NULL != fi->keywords) - GNUNET_FS_uri_destroy (fi->keywords); + GNUNET_FS_uri_destroy(fi->keywords); if (NULL != fi->meta) - GNUNET_CONTAINER_meta_data_destroy (fi->meta); - GNUNET_free_non_null (fi->serialization); + GNUNET_CONTAINER_meta_data_destroy(fi->meta); + GNUNET_free_non_null(fi->serialization); if (NULL != fi->te) - { - GNUNET_FS_tree_encoder_finish (fi->te, NULL); - fi->te = NULL; - } - GNUNET_free (fi); + { + GNUNET_FS_tree_encoder_finish(fi->te, NULL); + fi->te = NULL; + } + GNUNET_free(fi); } diff --git a/src/fs/fs_getopt.c b/src/fs/fs_getopt.c index 0d5907a40..4f53f64a5 100644 --- a/src/fs/fs_getopt.c +++ b/src/fs/fs_getopt.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_getopt.c @@ -43,10 +43,10 @@ * @return #GNUNET_OK on success */ static int -getopt_set_keywords (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, - void *scls, - const char *option, - const char *value) +getopt_set_keywords(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, + void *scls, + const char *option, + const char *value) { struct GNUNET_FS_Uri **uri = scls; struct GNUNET_FS_Uri *u = *uri; @@ -54,64 +54,64 @@ getopt_set_keywords (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, size_t slen; if (NULL == u) - { - u = GNUNET_new (struct GNUNET_FS_Uri); - *uri = u; - u->type = GNUNET_FS_URI_KSK; - u->data.ksk.keywordCount = 0; - u->data.ksk.keywords = NULL; - } + { + u = GNUNET_new(struct GNUNET_FS_Uri); + *uri = u; + u->type = GNUNET_FS_URI_KSK; + u->data.ksk.keywordCount = 0; + u->data.ksk.keywords = NULL; + } else - { - GNUNET_assert (GNUNET_FS_URI_KSK == u->type); - } - slen = strlen (value); + { + GNUNET_assert(GNUNET_FS_URI_KSK == u->type); + } + slen = strlen(value); if (0 == slen) return GNUNET_SYSERR; /* cannot be empty */ if (value[0] == '+') - { - /* simply preserve the "mandatory" flag */ - if (slen < 2) - return GNUNET_SYSERR; /* empty keywords not allowed */ - if ((value[1] == '"') && (slen > 3) && (value[slen - 1] == '"')) - { - /* remove the quotes, keep the '+' */ - val = GNUNET_malloc (slen - 1); - val[0] = '+'; - GNUNET_memcpy (&val[1], - &value[2], - slen - 3); - val[slen - 2] = '\0'; - } - else { - /* no quotes, just keep the '+' */ - val = GNUNET_strdup (value); + /* simply preserve the "mandatory" flag */ + if (slen < 2) + return GNUNET_SYSERR; /* empty keywords not allowed */ + if ((value[1] == '"') && (slen > 3) && (value[slen - 1] == '"')) + { + /* remove the quotes, keep the '+' */ + val = GNUNET_malloc(slen - 1); + val[0] = '+'; + GNUNET_memcpy(&val[1], + &value[2], + slen - 3); + val[slen - 2] = '\0'; + } + else + { + /* no quotes, just keep the '+' */ + val = GNUNET_strdup(value); + } } - } else - { - if ((value[0] == '"') && (slen > 2) && (value[slen - 1] == '"')) { - /* remove the quotes, add a space */ - val = GNUNET_malloc (slen); - val[0] = ' '; - GNUNET_memcpy (&val[1], - &value[1], - slen - 2); - val[slen - 1] = '\0'; + if ((value[0] == '"') && (slen > 2) && (value[slen - 1] == '"')) + { + /* remove the quotes, add a space */ + val = GNUNET_malloc(slen); + val[0] = ' '; + GNUNET_memcpy(&val[1], + &value[1], + slen - 2); + val[slen - 1] = '\0'; + } + else + { + /* add a space to indicate "not mandatory" */ + val = GNUNET_malloc(slen + 2); + strcpy(val, " "); + strcat(val, value); + } } - else - { - /* add a space to indicate "not mandatory" */ - val = GNUNET_malloc (slen + 2); - strcpy (val, " "); - strcat (val, value); - } - } - GNUNET_array_append (u->data.ksk.keywords, - u->data.ksk.keywordCount, - val); + GNUNET_array_append(u->data.ksk.keywords, + u->data.ksk.keywordCount, + val); return GNUNET_OK; } @@ -126,11 +126,11 @@ getopt_set_keywords (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, * @param[out] topKeywords set to the desired value */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_FS_GETOPT_KEYWORDS (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - struct GNUNET_FS_Uri **topKeywords) +GNUNET_FS_GETOPT_KEYWORDS(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + struct GNUNET_FS_Uri **topKeywords) { struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName, @@ -139,7 +139,7 @@ GNUNET_FS_GETOPT_KEYWORDS (char shortName, .description = description, .require_argument = 1, .processor = &getopt_set_keywords, - .scls = (void *) topKeywords + .scls = (void *)topKeywords }; return clo; @@ -159,12 +159,13 @@ GNUNET_FS_GETOPT_KEYWORDS (char shortName, * @return #GNUNET_OK on success */ static int -getopt_set_metadata (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, - void *scls, - const char *option, - const char *value) +getopt_set_metadata(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, + void *scls, + const char *option, + const char *value) { struct GNUNET_CONTAINER_MetaData **mm = scls; + #if HAVE_EXTRACTOR_H && HAVE_LIBEXTRACTOR enum EXTRACTOR_MetaType type; const char *typename; @@ -175,66 +176,66 @@ getopt_set_metadata (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, meta = *mm; if (meta == NULL) - { - meta = GNUNET_CONTAINER_meta_data_create (); - *mm = meta; - } + { + meta = GNUNET_CONTAINER_meta_data_create(); + *mm = meta; + } /* Use GNUNET_STRINGS_get_utf8_args() in main() to acquire utf-8-encoded * commandline arguments, so that the following line is not needed. */ /*tmp = GNUNET_STRINGS_to_utf8 (value, strlen (value), locale_charset ());*/ - tmp = GNUNET_strdup (value); + tmp = GNUNET_strdup(value); #if HAVE_EXTRACTOR_H && HAVE_LIBEXTRACTOR - type = EXTRACTOR_metatype_get_max (); + type = EXTRACTOR_metatype_get_max(); while (type > 0) - { - type--; - typename = EXTRACTOR_metatype_to_string (type); - typename_i18n = dgettext (LIBEXTRACTOR_GETTEXT_DOMAIN, typename); - if ((strlen (tmp) >= strlen (typename) + 1) && - (tmp[strlen (typename)] == ':') && - (0 == strncmp (typename, tmp, strlen (typename)))) { - GNUNET_CONTAINER_meta_data_insert (meta, "", type, - EXTRACTOR_METAFORMAT_UTF8, - "text/plain", - &tmp[strlen (typename) + 1], - strlen (&tmp[strlen (typename) + 1]) + - 1); - GNUNET_free (tmp); - tmp = NULL; - break; + type--; + typename = EXTRACTOR_metatype_to_string(type); + typename_i18n = dgettext(LIBEXTRACTOR_GETTEXT_DOMAIN, typename); + if ((strlen(tmp) >= strlen(typename) + 1) && + (tmp[strlen(typename)] == ':') && + (0 == strncmp(typename, tmp, strlen(typename)))) + { + GNUNET_CONTAINER_meta_data_insert(meta, "", type, + EXTRACTOR_METAFORMAT_UTF8, + "text/plain", + &tmp[strlen(typename) + 1], + strlen(&tmp[strlen(typename) + 1]) + + 1); + GNUNET_free(tmp); + tmp = NULL; + break; + } + if ((strlen(tmp) >= strlen(typename_i18n) + 1) && + (tmp[strlen(typename_i18n)] == ':') && + (0 == strncmp(typename_i18n, tmp, strlen(typename_i18n)))) + { + GNUNET_CONTAINER_meta_data_insert(meta, "", type, + EXTRACTOR_METAFORMAT_UTF8, + "text/plain", + &tmp[strlen(typename_i18n) + 1], + strlen(&tmp + [strlen(typename_i18n) + 1]) + + 1); + GNUNET_free(tmp); + tmp = NULL; + break; + } } - if ((strlen (tmp) >= strlen (typename_i18n) + 1) && - (tmp[strlen (typename_i18n)] == ':') && - (0 == strncmp (typename_i18n, tmp, strlen (typename_i18n)))) - { - GNUNET_CONTAINER_meta_data_insert (meta, "", type, - EXTRACTOR_METAFORMAT_UTF8, - "text/plain", - &tmp[strlen (typename_i18n) + 1], - strlen (&tmp - [strlen (typename_i18n) + 1]) + - 1); - GNUNET_free (tmp); - tmp = NULL; - break; - } - } #endif if (NULL != tmp) - { - GNUNET_CONTAINER_meta_data_insert (meta, "", - EXTRACTOR_METATYPE_UNKNOWN, - EXTRACTOR_METAFORMAT_UTF8, "text/plain", - tmp, strlen (tmp) + 1); - GNUNET_free (tmp); - printf (_ - ("Unknown metadata type in metadata option `%s'. Using metadata type `unknown' instead.\n"), - value); - } + { + GNUNET_CONTAINER_meta_data_insert(meta, "", + EXTRACTOR_METATYPE_UNKNOWN, + EXTRACTOR_METAFORMAT_UTF8, "text/plain", + tmp, strlen(tmp) + 1); + GNUNET_free(tmp); + printf(_ + ("Unknown metadata type in metadata option `%s'. Using metadata type `unknown' instead.\n"), + value); + } return GNUNET_OK; } @@ -248,11 +249,11 @@ getopt_set_metadata (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, * @param[out] metadata set to the desired value */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_FS_GETOPT_METADATA (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - struct GNUNET_CONTAINER_MetaData **meta) +GNUNET_FS_GETOPT_METADATA(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + struct GNUNET_CONTAINER_MetaData **meta) { struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName, @@ -261,7 +262,7 @@ GNUNET_FS_GETOPT_METADATA (char shortName, .description = description, .require_argument = 1, .processor = &getopt_set_metadata, - .scls = (void *) meta + .scls = (void *)meta }; return clo; diff --git a/src/fs/fs_list_indexed.c b/src/fs/fs_list_indexed.c index 08a7be48e..c023d0ac6 100644 --- a/src/fs/fs_list_indexed.c +++ b/src/fs/fs_list_indexed.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_list_indexed.c @@ -34,9 +34,7 @@ /** * Context for #GNUNET_FS_get_indexed_files(). */ -struct GNUNET_FS_GetIndexedContext -{ - +struct GNUNET_FS_GetIndexedContext { /** * Connection to the FS service. */ @@ -72,15 +70,15 @@ struct GNUNET_FS_GetIndexedContext * @param msg message with indexing information */ static void -handle_index_info_end (void *cls, - const struct GNUNET_MessageHeader *msg) +handle_index_info_end(void *cls, + const struct GNUNET_MessageHeader *msg) { struct GNUNET_FS_GetIndexedContext *gic = cls; - (void) gic->iterator (gic->iterator_cls, - NULL, - NULL); - GNUNET_FS_get_indexed_files_cancel (gic); + (void)gic->iterator(gic->iterator_cls, + NULL, + NULL); + GNUNET_FS_get_indexed_files_cancel(gic); } @@ -92,18 +90,18 @@ handle_index_info_end (void *cls, * @param iim message with indexing information */ static int -check_index_info (void *cls, - const struct IndexInfoMessage *iim) +check_index_info(void *cls, + const struct IndexInfoMessage *iim) { - uint16_t msize = ntohs (iim->header.size) - sizeof (*iim); + uint16_t msize = ntohs(iim->header.size) - sizeof(*iim); const char *filename; - filename = (const char *) &iim[1]; + filename = (const char *)&iim[1]; if (filename[msize - 1] != '\0') - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -116,21 +114,21 @@ check_index_info (void *cls, * @param iim message with indexing information */ static void -handle_index_info (void *cls, - const struct IndexInfoMessage *iim) +handle_index_info(void *cls, + const struct IndexInfoMessage *iim) { struct GNUNET_FS_GetIndexedContext *gic = cls; const char *filename; - filename = (const char *) &iim[1]; + filename = (const char *)&iim[1]; if (GNUNET_OK != - gic->iterator (gic->iterator_cls, - filename, - &iim->file_id)) - { - GNUNET_FS_get_indexed_files_cancel (gic); - return; - } + gic->iterator(gic->iterator_cls, + filename, + &iim->file_id)) + { + GNUNET_FS_get_indexed_files_cancel(gic); + return; + } } @@ -143,16 +141,16 @@ handle_index_info (void *cls, * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_FS_GetIndexedContext *gic = cls; - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed to receive response from `%s' service.\n"), - "fs"); - (void) gic->iterator (gic->iterator_cls, NULL, NULL); - GNUNET_FS_get_indexed_files_cancel (gic); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to receive response from `%s' service.\n"), + "fs"); + (void)gic->iterator(gic->iterator_cls, NULL, NULL); + GNUNET_FS_get_indexed_files_cancel(gic); } @@ -165,45 +163,45 @@ mq_error_handler (void *cls, * @return NULL on error ('iter' is not called) */ struct GNUNET_FS_GetIndexedContext * -GNUNET_FS_get_indexed_files (struct GNUNET_FS_Handle *h, - GNUNET_FS_IndexedFileProcessor iterator, - void *iterator_cls) +GNUNET_FS_get_indexed_files(struct GNUNET_FS_Handle *h, + GNUNET_FS_IndexedFileProcessor iterator, + void *iterator_cls) { struct GNUNET_FS_GetIndexedContext *gic - = GNUNET_new (struct GNUNET_FS_GetIndexedContext); + = GNUNET_new(struct GNUNET_FS_GetIndexedContext); struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (index_info_end, - GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END, - struct GNUNET_MessageHeader, - gic), - GNUNET_MQ_hd_var_size (index_info, - GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY, - struct IndexInfoMessage, - gic), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(index_info_end, + GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END, + struct GNUNET_MessageHeader, + gic), + GNUNET_MQ_hd_var_size(index_info, + GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY, + struct IndexInfoMessage, + gic), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; - gic->mq = GNUNET_CLIENT_connect (h->cfg, - "fs", - handlers, - &mq_error_handler, - h); + gic->mq = GNUNET_CLIENT_connect(h->cfg, + "fs", + handlers, + &mq_error_handler, + h); if (NULL == gic->mq) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed to not connect to `%s' service.\n"), - "fs"); - GNUNET_free (gic); - return NULL; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to not connect to `%s' service.\n"), + "fs"); + GNUNET_free(gic); + return NULL; + } gic->iterator = iterator; gic->iterator_cls = iterator_cls; - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET); - GNUNET_MQ_send (gic->mq, - env); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET); + GNUNET_MQ_send(gic->mq, + env); return gic; } @@ -214,10 +212,10 @@ GNUNET_FS_get_indexed_files (struct GNUNET_FS_Handle *h, * @param gic operation to cancel */ void -GNUNET_FS_get_indexed_files_cancel (struct GNUNET_FS_GetIndexedContext *gic) +GNUNET_FS_get_indexed_files_cancel(struct GNUNET_FS_GetIndexedContext *gic) { - GNUNET_MQ_destroy (gic->mq); - GNUNET_free (gic); + GNUNET_MQ_destroy(gic->mq); + GNUNET_free(gic); } diff --git a/src/fs/fs_misc.c b/src/fs/fs_misc.c index 918c637a0..79f082626 100644 --- a/src/fs/fs_misc.c +++ b/src/fs/fs_misc.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_misc.c * @brief misc. functions related to file-sharing in general @@ -35,74 +35,74 @@ * @return NULL if meta data is useless for suggesting a filename */ char * -GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData - *md) +GNUNET_FS_meta_data_suggest_filename(const struct GNUNET_CONTAINER_MetaData + *md) { static const char *mimeMap[][2] = { - {"application/bz2", ".bz2"}, - {"application/gnunet-directory", ".gnd"}, - {"application/java", ".class"}, - {"application/msword", ".doc"}, - {"application/nar", ".nar"}, - {"application/narinfo", ".narinfo"}, - {"application/ogg", ".ogg"}, - {"application/pdf", ".pdf"}, - {"application/pgp-keys", ".key"}, - {"application/pgp-signature", ".pgp"}, - {"application/postscript", ".ps"}, - {"application/rar", ".rar"}, - {"application/rtf", ".rtf"}, - {"application/xml", ".xml"}, - {"application/x-debian-package", ".deb"}, - {"application/x-dvi", ".dvi"}, - {"application/x-flac", ".flac"}, - {"application/x-gzip", ".gz"}, - {"application/x-java-archive", ".jar"}, - {"application/x-java-vm", ".class"}, - {"application/x-python-code", ".pyc"}, - {"application/x-redhat-package-manager", ".rpm"}, - {"application/x-rpm", ".rpm"}, - {"application/x-tar", ".tar"}, - {"application/x-tex-pk", ".pk"}, - {"application/x-texinfo", ".texinfo"}, - {"application/x-xcf", ".xcf"}, - {"application/x-xfig", ".xfig"}, - {"application/zip", ".zip"}, + { "application/bz2", ".bz2" }, + { "application/gnunet-directory", ".gnd" }, + { "application/java", ".class" }, + { "application/msword", ".doc" }, + { "application/nar", ".nar" }, + { "application/narinfo", ".narinfo" }, + { "application/ogg", ".ogg" }, + { "application/pdf", ".pdf" }, + { "application/pgp-keys", ".key" }, + { "application/pgp-signature", ".pgp" }, + { "application/postscript", ".ps" }, + { "application/rar", ".rar" }, + { "application/rtf", ".rtf" }, + { "application/xml", ".xml" }, + { "application/x-debian-package", ".deb" }, + { "application/x-dvi", ".dvi" }, + { "application/x-flac", ".flac" }, + { "application/x-gzip", ".gz" }, + { "application/x-java-archive", ".jar" }, + { "application/x-java-vm", ".class" }, + { "application/x-python-code", ".pyc" }, + { "application/x-redhat-package-manager", ".rpm" }, + { "application/x-rpm", ".rpm" }, + { "application/x-tar", ".tar" }, + { "application/x-tex-pk", ".pk" }, + { "application/x-texinfo", ".texinfo" }, + { "application/x-xcf", ".xcf" }, + { "application/x-xfig", ".xfig" }, + { "application/zip", ".zip" }, - {"audio/midi", ".midi"}, - {"audio/mpeg", ".mp3"}, - {"audio/real", ".rm"}, - {"audio/x-wav", ".wav"}, + { "audio/midi", ".midi" }, + { "audio/mpeg", ".mp3" }, + { "audio/real", ".rm" }, + { "audio/x-wav", ".wav" }, - {"image/gif", ".gif"}, - {"image/jpeg", ".jpg"}, - {"image/pcx", ".pcx"}, - {"image/png", ".png"}, - {"image/tiff", ".tiff"}, - {"image/x-ms-bmp", ".bmp"}, - {"image/x-xpixmap", ".xpm"}, + { "image/gif", ".gif" }, + { "image/jpeg", ".jpg" }, + { "image/pcx", ".pcx" }, + { "image/png", ".png" }, + { "image/tiff", ".tiff" }, + { "image/x-ms-bmp", ".bmp" }, + { "image/x-xpixmap", ".xpm" }, - {"text/css", ".css"}, - {"text/html", ".html"}, - {"text/plain", ".txt"}, - {"text/rtf", ".rtf"}, - {"text/x-c++hdr", ".h++"}, - {"text/x-c++src", ".c++"}, - {"text/x-chdr", ".h"}, - {"text/x-csrc", ".c"}, - {"text/x-java", ".java"}, - {"text/x-moc", ".moc"}, - {"text/x-pascal", ".pas"}, - {"text/x-perl", ".pl"}, - {"text/x-python", ".py"}, - {"text/x-tex", ".tex"}, + { "text/css", ".css" }, + { "text/html", ".html" }, + { "text/plain", ".txt" }, + { "text/rtf", ".rtf" }, + { "text/x-c++hdr", ".h++" }, + { "text/x-c++src", ".c++" }, + { "text/x-chdr", ".h" }, + { "text/x-csrc", ".c" }, + { "text/x-java", ".java" }, + { "text/x-moc", ".moc" }, + { "text/x-pascal", ".pas" }, + { "text/x-perl", ".pl" }, + { "text/x-python", ".py" }, + { "text/x-tex", ".tex" }, - {"video/avi", ".avi"}, - {"video/mpeg", ".mpeg"}, - {"video/quicktime", ".qt"}, - {"video/real", ".rm"}, - {"video/x-msvideo", ".avi"}, - {NULL, NULL}, + { "video/avi", ".avi" }, + { "video/mpeg", ".mpeg" }, + { "video/quicktime", ".qt" }, + { "video/real", ".rm" }, + { "video/x-msvideo", ".avi" }, + { NULL, NULL }, }; char *ret; unsigned int i; @@ -111,52 +111,52 @@ GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData const char *ext; ret = - GNUNET_CONTAINER_meta_data_get_by_type (md, - EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME); + GNUNET_CONTAINER_meta_data_get_by_type(md, + EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME); if (ret != NULL) return ret; ext = NULL; mime = - GNUNET_CONTAINER_meta_data_get_by_type (md, EXTRACTOR_METATYPE_MIMETYPE); + GNUNET_CONTAINER_meta_data_get_by_type(md, EXTRACTOR_METATYPE_MIMETYPE); if (mime != NULL) - { - i = 0; - while ((mimeMap[i][0] != NULL) && (0 != strcmp (mime, mimeMap[i][0]))) - i++; - if (mimeMap[i][1] == NULL) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, - _("Did not find mime type `%s' in extension list.\n"), mime); - else - ext = mimeMap[i][1]; - GNUNET_free (mime); - } + { + i = 0; + while ((mimeMap[i][0] != NULL) && (0 != strcmp(mime, mimeMap[i][0]))) + i++; + if (mimeMap[i][1] == NULL) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, + _("Did not find mime type `%s' in extension list.\n"), mime); + else + ext = mimeMap[i][1]; + GNUNET_free(mime); + } base = - GNUNET_CONTAINER_meta_data_get_first_by_types (md, - EXTRACTOR_METATYPE_TITLE, - EXTRACTOR_METATYPE_BOOK_TITLE, - EXTRACTOR_METATYPE_ORIGINAL_TITLE, - EXTRACTOR_METATYPE_PACKAGE_NAME, - EXTRACTOR_METATYPE_URL, - EXTRACTOR_METATYPE_URI, - EXTRACTOR_METATYPE_DESCRIPTION, - EXTRACTOR_METATYPE_ISRC, - EXTRACTOR_METATYPE_JOURNAL_NAME, - EXTRACTOR_METATYPE_AUTHOR_NAME, - EXTRACTOR_METATYPE_SUBJECT, - EXTRACTOR_METATYPE_ALBUM, - EXTRACTOR_METATYPE_ARTIST, - EXTRACTOR_METATYPE_KEYWORDS, - EXTRACTOR_METATYPE_COMMENT, - EXTRACTOR_METATYPE_UNKNOWN, - -1); + GNUNET_CONTAINER_meta_data_get_first_by_types(md, + EXTRACTOR_METATYPE_TITLE, + EXTRACTOR_METATYPE_BOOK_TITLE, + EXTRACTOR_METATYPE_ORIGINAL_TITLE, + EXTRACTOR_METATYPE_PACKAGE_NAME, + EXTRACTOR_METATYPE_URL, + EXTRACTOR_METATYPE_URI, + EXTRACTOR_METATYPE_DESCRIPTION, + EXTRACTOR_METATYPE_ISRC, + EXTRACTOR_METATYPE_JOURNAL_NAME, + EXTRACTOR_METATYPE_AUTHOR_NAME, + EXTRACTOR_METATYPE_SUBJECT, + EXTRACTOR_METATYPE_ALBUM, + EXTRACTOR_METATYPE_ARTIST, + EXTRACTOR_METATYPE_KEYWORDS, + EXTRACTOR_METATYPE_COMMENT, + EXTRACTOR_METATYPE_UNKNOWN, + -1); if ((base == NULL) && (ext == NULL)) return NULL; if (base == NULL) - return GNUNET_strdup (ext); + return GNUNET_strdup(ext); if (ext == NULL) return base; - GNUNET_asprintf (&ret, "%s%s", base, ext); - GNUNET_free (base); + GNUNET_asprintf(&ret, "%s%s", base, ext); + GNUNET_free(base); return ret; } diff --git a/src/fs/fs_namespace.c b/src/fs/fs_namespace.c index 11a137a09..b740eb2ba 100644 --- a/src/fs/fs_namespace.c +++ b/src/fs/fs_namespace.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_namespace.c @@ -37,8 +37,7 @@ * Information about an (updateable) node in the * namespace. */ -struct NamespaceUpdateNode -{ +struct NamespaceUpdateNode { /** * Identifier for this node. */ @@ -75,9 +74,7 @@ struct NamespaceUpdateNode /** * Handle to update information for a namespace. */ -struct GNUNET_FS_UpdateInformationGraph -{ - +struct GNUNET_FS_UpdateInformationGraph { /** * Handle to the FS service context. */ @@ -125,7 +122,7 @@ struct GNUNET_FS_UpdateInformationGraph * @return NULL on error, otherwise the name of the directory */ static char * -get_update_information_directory ( +get_update_information_directory( struct GNUNET_FS_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns) { @@ -136,20 +133,20 @@ get_update_information_directory ( struct GNUNET_CRYPTO_HashAsciiEncoded enc; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (h->cfg, "FS", "UPDATE_DIR", &dn)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "fs", "UPDATE_DIR"); - return NULL; - } - GNUNET_CRYPTO_ecdsa_key_get_public (ns, &pub); - GNUNET_CRYPTO_hash (&pub, sizeof (pub), &hc); - GNUNET_CRYPTO_hash_to_enc (&hc, &enc); - GNUNET_asprintf (&ret, - "%s%s%s", - dn, - DIR_SEPARATOR_STR, - (const char *) enc.encoding); - GNUNET_free (dn); + GNUNET_CONFIGURATION_get_value_filename(h->cfg, "FS", "UPDATE_DIR", &dn)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "fs", "UPDATE_DIR"); + return NULL; + } + GNUNET_CRYPTO_ecdsa_key_get_public(ns, &pub); + GNUNET_CRYPTO_hash(&pub, sizeof(pub), &hc); + GNUNET_CRYPTO_hash_to_enc(&hc, &enc); + GNUNET_asprintf(&ret, + "%s%s%s", + dn, + DIR_SEPARATOR_STR, + (const char *)enc.encoding); + GNUNET_free(dn); return ret; } @@ -160,24 +157,24 @@ get_update_information_directory ( * @param uig data structure to free */ static void -free_update_information_graph (struct GNUNET_FS_UpdateInformationGraph *uig) +free_update_information_graph(struct GNUNET_FS_UpdateInformationGraph *uig) { unsigned int i; struct NamespaceUpdateNode *nsn; for (i = 0; i < uig->update_node_count; i++) - { - nsn = uig->update_nodes[i]; - GNUNET_CONTAINER_meta_data_destroy (nsn->md); - GNUNET_FS_uri_destroy (nsn->uri); - GNUNET_free (nsn->id); - GNUNET_free (nsn->update); - GNUNET_free (nsn); - } - GNUNET_array_grow (uig->update_nodes, uig->update_node_count, 0); + { + nsn = uig->update_nodes[i]; + GNUNET_CONTAINER_meta_data_destroy(nsn->md); + GNUNET_FS_uri_destroy(nsn->uri); + GNUNET_free(nsn->id); + GNUNET_free(nsn->update); + GNUNET_free(nsn); + } + GNUNET_array_grow(uig->update_nodes, uig->update_node_count, 0); if (NULL != uig->update_map) - GNUNET_CONTAINER_multihashmap_destroy (uig->update_map); - GNUNET_free (uig); + GNUNET_CONTAINER_multihashmap_destroy(uig->update_map); + GNUNET_free(uig); } @@ -187,7 +184,7 @@ free_update_information_graph (struct GNUNET_FS_UpdateInformationGraph *uig) * @param uig update information graph to dump */ static void -write_update_information_graph (struct GNUNET_FS_UpdateInformationGraph *uig) +write_update_information_graph(struct GNUNET_FS_UpdateInformationGraph *uig) { char *fn; struct GNUNET_BIO_WriteHandle *wh; @@ -195,40 +192,40 @@ write_update_information_graph (struct GNUNET_FS_UpdateInformationGraph *uig) struct NamespaceUpdateNode *n; char *uris; - fn = get_update_information_directory (uig->h, &uig->ns); - wh = GNUNET_BIO_write_open (fn); + fn = get_update_information_directory(uig->h, &uig->ns); + wh = GNUNET_BIO_write_open(fn); if (NULL == wh) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to open `%s' for writing: %s\n"), - fn, - strerror (errno)); - GNUNET_free (fn); - return; - } - if (GNUNET_OK != GNUNET_BIO_write_int32 (wh, uig->update_node_count)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to open `%s' for writing: %s\n"), + fn, + strerror(errno)); + GNUNET_free(fn); + return; + } + if (GNUNET_OK != GNUNET_BIO_write_int32(wh, uig->update_node_count)) goto END; for (i = 0; i < uig->update_node_count; i++) - { - n = uig->update_nodes[i]; - uris = GNUNET_FS_uri_to_string (n->uri); - if ((GNUNET_OK != GNUNET_BIO_write_string (wh, n->id)) || - (GNUNET_OK != GNUNET_BIO_write_meta_data (wh, n->md)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, n->update)) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, uris))) { - GNUNET_free (uris); - break; + n = uig->update_nodes[i]; + uris = GNUNET_FS_uri_to_string(n->uri); + if ((GNUNET_OK != GNUNET_BIO_write_string(wh, n->id)) || + (GNUNET_OK != GNUNET_BIO_write_meta_data(wh, n->md)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, n->update)) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, uris))) + { + GNUNET_free(uris); + break; + } + GNUNET_free(uris); } - GNUNET_free (uris); - } END: - if (GNUNET_OK != GNUNET_BIO_write_close (wh)) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to write `%s': %s\n"), - fn, - strerror (errno)); - GNUNET_free (fn); + if (GNUNET_OK != GNUNET_BIO_write_close(wh)) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to write `%s': %s\n"), + fn, + strerror(errno)); + GNUNET_free(fn); } @@ -240,8 +237,8 @@ END: * @return update graph, never NULL */ static struct GNUNET_FS_UpdateInformationGraph * -read_update_information_graph (struct GNUNET_FS_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns) +read_update_information_graph(struct GNUNET_FS_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns) { struct GNUNET_FS_UpdateInformationGraph *uig; char *fn; @@ -252,79 +249,79 @@ read_update_information_graph (struct GNUNET_FS_Handle *h, uint32_t count; char *emsg; - uig = GNUNET_new (struct GNUNET_FS_UpdateInformationGraph); + uig = GNUNET_new(struct GNUNET_FS_UpdateInformationGraph); uig->h = h; uig->ns = *ns; - fn = get_update_information_directory (h, ns); - if (GNUNET_YES != GNUNET_DISK_file_test (fn)) - { - GNUNET_free (fn); - return uig; - } - rh = GNUNET_BIO_read_open (fn); + fn = get_update_information_directory(h, ns); + if (GNUNET_YES != GNUNET_DISK_file_test(fn)) + { + GNUNET_free(fn); + return uig; + } + rh = GNUNET_BIO_read_open(fn); if (NULL == rh) - { - GNUNET_free (fn); - return uig; - } - if (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &count)) - { - GNUNET_break (0); - goto END; - } + { + GNUNET_free(fn); + return uig; + } + if (GNUNET_OK != GNUNET_BIO_read_int32(rh, &count)) + { + GNUNET_break(0); + goto END; + } if (count > 1024 * 1024) - { - GNUNET_break (0); - goto END; - } + { + GNUNET_break(0); + goto END; + } if (0 == count) goto END; uig->update_nodes = - GNUNET_malloc (count * sizeof (struct NamespaceUpdateNode *)); + GNUNET_malloc(count * sizeof(struct NamespaceUpdateNode *)); for (i = 0; i < count; i++) - { - n = GNUNET_new (struct NamespaceUpdateNode); - if ((GNUNET_OK != - GNUNET_BIO_read_string (rh, "identifier", &n->id, 1024)) || - (GNUNET_OK != GNUNET_BIO_read_meta_data (rh, "meta", &n->md)) || - (GNUNET_OK != - GNUNET_BIO_read_string (rh, "update-id", &n->update, 1024)) || - (GNUNET_OK != GNUNET_BIO_read_string (rh, "uri", &uris, 1024 * 2))) { - GNUNET_break (0); - GNUNET_free_non_null (n->id); - GNUNET_free_non_null (n->update); - if (n->md != NULL) - GNUNET_CONTAINER_meta_data_destroy (n->md); - GNUNET_free (n); - break; - } - n->uri = GNUNET_FS_uri_parse (uris, &emsg); - GNUNET_free (uris); - if (n->uri == NULL) - { - GNUNET_break (0); - GNUNET_free (emsg); - GNUNET_free (n->id); - GNUNET_free_non_null (n->update); - GNUNET_CONTAINER_meta_data_destroy (n->md); - GNUNET_free (n); - break; + n = GNUNET_new(struct NamespaceUpdateNode); + if ((GNUNET_OK != + GNUNET_BIO_read_string(rh, "identifier", &n->id, 1024)) || + (GNUNET_OK != GNUNET_BIO_read_meta_data(rh, "meta", &n->md)) || + (GNUNET_OK != + GNUNET_BIO_read_string(rh, "update-id", &n->update, 1024)) || + (GNUNET_OK != GNUNET_BIO_read_string(rh, "uri", &uris, 1024 * 2))) + { + GNUNET_break(0); + GNUNET_free_non_null(n->id); + GNUNET_free_non_null(n->update); + if (n->md != NULL) + GNUNET_CONTAINER_meta_data_destroy(n->md); + GNUNET_free(n); + break; + } + n->uri = GNUNET_FS_uri_parse(uris, &emsg); + GNUNET_free(uris); + if (n->uri == NULL) + { + GNUNET_break(0); + GNUNET_free(emsg); + GNUNET_free(n->id); + GNUNET_free_non_null(n->update); + GNUNET_CONTAINER_meta_data_destroy(n->md); + GNUNET_free(n); + break; + } + uig->update_nodes[i] = n; } - uig->update_nodes[i] = n; - } uig->update_node_count = i; END: - if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to read `%s': %s\n"), - fn, - emsg); - GNUNET_free (emsg); - } - GNUNET_free (fn); + if (GNUNET_OK != GNUNET_BIO_read_close(rh, &emsg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to read `%s': %s\n"), + fn, + emsg); + GNUNET_free(emsg); + } + GNUNET_free(fn); return uig; } @@ -332,9 +329,7 @@ END: /** * Context for the SKS publication. */ -struct GNUNET_FS_PublishSksContext -{ - +struct GNUNET_FS_PublishSksContext { /** * URI of the new entry in the namespace. */ @@ -386,33 +381,33 @@ struct GNUNET_FS_PublishSksContext * @param msg error message (or NULL) */ static void -sks_publish_cont (void *cls, const char *msg) +sks_publish_cont(void *cls, const char *msg) { struct GNUNET_FS_PublishSksContext *psc = cls; struct GNUNET_FS_UpdateInformationGraph *uig; psc->uc = NULL; if (NULL != msg) - { - if (NULL != psc->cont) - psc->cont (psc->cont_cls, NULL, msg); - GNUNET_FS_publish_sks_cancel (psc); - return; - } + { + if (NULL != psc->cont) + psc->cont(psc->cont_cls, NULL, msg); + GNUNET_FS_publish_sks_cancel(psc); + return; + } if (NULL != psc->nsn) - { - /* FIXME: this can be done much more - * efficiently by simply appending to the - * file and overwriting the 4-byte header */ - uig = read_update_information_graph (psc->h, &psc->ns); - GNUNET_array_append (uig->update_nodes, uig->update_node_count, psc->nsn); - psc->nsn = NULL; - write_update_information_graph (uig); - free_update_information_graph (uig); - } + { + /* FIXME: this can be done much more + * efficiently by simply appending to the + * file and overwriting the 4-byte header */ + uig = read_update_information_graph(psc->h, &psc->ns); + GNUNET_array_append(uig->update_nodes, uig->update_node_count, psc->nsn); + psc->nsn = NULL; + write_update_information_graph(uig); + free_update_information_graph(uig); + } if (NULL != psc->cont) - psc->cont (psc->cont_cls, psc->uri, NULL); - GNUNET_FS_publish_sks_cancel (psc); + psc->cont(psc->cont_cls, psc->uri, NULL); + GNUNET_FS_publish_sks_cancel(psc); } @@ -432,59 +427,59 @@ sks_publish_cont (void *cls, const char *msg) * @return NULL on error ('cont' will still be called) */ struct GNUNET_FS_PublishSksContext * -GNUNET_FS_publish_sks (struct GNUNET_FS_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, - const char *identifier, - const char *update, - const struct GNUNET_CONTAINER_MetaData *meta, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_FS_BlockOptions *bo, - enum GNUNET_FS_PublishOptions options, - GNUNET_FS_PublishContinuation cont, - void *cont_cls) +GNUNET_FS_publish_sks(struct GNUNET_FS_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, + const char *identifier, + const char *update, + const struct GNUNET_CONTAINER_MetaData *meta, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_FS_BlockOptions *bo, + enum GNUNET_FS_PublishOptions options, + GNUNET_FS_PublishContinuation cont, + void *cont_cls) { struct GNUNET_FS_PublishSksContext *psc; struct GNUNET_FS_Uri *sks_uri; - sks_uri = GNUNET_new (struct GNUNET_FS_Uri); + sks_uri = GNUNET_new(struct GNUNET_FS_Uri); sks_uri->type = GNUNET_FS_URI_SKS; - sks_uri->data.sks.identifier = GNUNET_strdup (identifier); - GNUNET_CRYPTO_ecdsa_key_get_public (ns, &sks_uri->data.sks.ns); + sks_uri->data.sks.identifier = GNUNET_strdup(identifier); + GNUNET_CRYPTO_ecdsa_key_get_public(ns, &sks_uri->data.sks.ns); - psc = GNUNET_new (struct GNUNET_FS_PublishSksContext); + psc = GNUNET_new(struct GNUNET_FS_PublishSksContext); psc->h = h; psc->uri = sks_uri; psc->cont = cont; psc->cont_cls = cont_cls; psc->ns = *ns; if (0 == (options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY)) - { - psc->dsh = GNUNET_DATASTORE_connect (h->cfg); - if (NULL == psc->dsh) { - sks_publish_cont (psc, _ ("Failed to connect to datastore.")); - return NULL; + psc->dsh = GNUNET_DATASTORE_connect(h->cfg); + if (NULL == psc->dsh) + { + sks_publish_cont(psc, _("Failed to connect to datastore.")); + return NULL; + } } - } if (NULL != update) - { - psc->nsn = GNUNET_new (struct NamespaceUpdateNode); - psc->nsn->id = GNUNET_strdup (identifier); - psc->nsn->update = GNUNET_strdup (update); - psc->nsn->md = GNUNET_CONTAINER_meta_data_duplicate (meta); - psc->nsn->uri = GNUNET_FS_uri_dup (uri); - } - psc->uc = GNUNET_FS_publish_ublock_ (h, - psc->dsh, - identifier, - update, - ns, - meta, - uri, - bo, - options, - &sks_publish_cont, - psc); + { + psc->nsn = GNUNET_new(struct NamespaceUpdateNode); + psc->nsn->id = GNUNET_strdup(identifier); + psc->nsn->update = GNUNET_strdup(update); + psc->nsn->md = GNUNET_CONTAINER_meta_data_duplicate(meta); + psc->nsn->uri = GNUNET_FS_uri_dup(uri); + } + psc->uc = GNUNET_FS_publish_ublock_(h, + psc->dsh, + identifier, + update, + ns, + meta, + uri, + bo, + options, + &sks_publish_cont, + psc); return psc; } @@ -495,36 +490,35 @@ GNUNET_FS_publish_sks (struct GNUNET_FS_Handle *h, * @param psc context of the operation to abort. */ void -GNUNET_FS_publish_sks_cancel (struct GNUNET_FS_PublishSksContext *psc) +GNUNET_FS_publish_sks_cancel(struct GNUNET_FS_PublishSksContext *psc) { if (NULL != psc->uc) - { - GNUNET_FS_publish_ublock_cancel_ (psc->uc); - psc->uc = NULL; - } + { + GNUNET_FS_publish_ublock_cancel_(psc->uc); + psc->uc = NULL; + } if (NULL != psc->dsh) - { - GNUNET_DATASTORE_disconnect (psc->dsh, GNUNET_NO); - psc->dsh = NULL; - } - GNUNET_FS_uri_destroy (psc->uri); + { + GNUNET_DATASTORE_disconnect(psc->dsh, GNUNET_NO); + psc->dsh = NULL; + } + GNUNET_FS_uri_destroy(psc->uri); if (NULL != psc->nsn) - { - GNUNET_CONTAINER_meta_data_destroy (psc->nsn->md); - GNUNET_FS_uri_destroy (psc->nsn->uri); - GNUNET_free (psc->nsn->id); - GNUNET_free (psc->nsn->update); - GNUNET_free (psc->nsn); - } - GNUNET_free (psc); + { + GNUNET_CONTAINER_meta_data_destroy(psc->nsn->md); + GNUNET_FS_uri_destroy(psc->nsn->uri); + GNUNET_free(psc->nsn->id); + GNUNET_free(psc->nsn->update); + GNUNET_free(psc->nsn); + } + GNUNET_free(psc); } /** * Closure for 'process_update_node'. */ -struct ProcessUpdateClosure -{ +struct ProcessUpdateClosure { /** * Function to call for each node. */ @@ -548,12 +542,12 @@ struct ProcessUpdateClosure * GNUNET_NO if not. */ static int -process_update_node (void *cls, const struct GNUNET_HashCode *key, void *value) +process_update_node(void *cls, const struct GNUNET_HashCode *key, void *value) { struct ProcessUpdateClosure *pc = cls; struct NamespaceUpdateNode *nsn = value; - pc->ip (pc->ip_cls, nsn->id, nsn->uri, nsn->md, nsn->update); + pc->ip(pc->ip_cls, nsn->id, nsn->uri, nsn->md, nsn->update); return GNUNET_YES; } @@ -561,8 +555,7 @@ process_update_node (void *cls, const struct GNUNET_HashCode *key, void *value) /** * Closure for 'find_trees'. */ -struct FindTreeClosure -{ +struct FindTreeClosure { /** * UIG we are operating on. */ @@ -611,38 +604,38 @@ struct FindTreeClosure * GNUNET_NO if not. */ static int -find_trees (void *cls, const struct GNUNET_HashCode *key, void *value) +find_trees(void *cls, const struct GNUNET_HashCode *key, void *value) { struct FindTreeClosure *fc = cls; struct NamespaceUpdateNode *nsn = value; struct GNUNET_HashCode hc; if (nsn->nug == fc->nug) - { - if (UINT_MAX == nsn->tree_id) - return GNUNET_YES; /* circular */ - GNUNET_assert (nsn->tree_id < fc->tree_array_size); - if (fc->tree_array[nsn->tree_id] != nsn) - return GNUNET_YES; /* part of "another" (directed) TREE, - * and not root of it, end trace */ - if (nsn->tree_id == fc->id) - return GNUNET_YES; /* that's our own root (can this be?) */ - /* merge existing TREE, we have a root for both */ - fc->tree_array[nsn->tree_id] = NULL; - if (UINT_MAX == fc->id) - fc->id = nsn->tree_id; /* take over ID */ - } + { + if (UINT_MAX == nsn->tree_id) + return GNUNET_YES; /* circular */ + GNUNET_assert(nsn->tree_id < fc->tree_array_size); + if (fc->tree_array[nsn->tree_id] != nsn) + return GNUNET_YES; /* part of "another" (directed) TREE, + * and not root of it, end trace */ + if (nsn->tree_id == fc->id) + return GNUNET_YES; /* that's our own root (can this be?) */ + /* merge existing TREE, we have a root for both */ + fc->tree_array[nsn->tree_id] = NULL; + if (UINT_MAX == fc->id) + fc->id = nsn->tree_id; /* take over ID */ + } else - { - nsn->nug = fc->nug; - nsn->tree_id = UINT_MAX; /* mark as undef */ - /* trace */ - GNUNET_CRYPTO_hash (nsn->update, strlen (nsn->update), &hc); - GNUNET_CONTAINER_multihashmap_get_multiple (fc->uig->update_map, - &hc, - &find_trees, - fc); - } + { + nsn->nug = fc->nug; + nsn->tree_id = UINT_MAX; /* mark as undef */ + /* trace */ + GNUNET_CRYPTO_hash(nsn->update, strlen(nsn->update), &hc); + GNUNET_CONTAINER_multihashmap_get_multiple(fc->uig->update_map, + &hc, + &find_trees, + fc); + } return GNUNET_YES; } @@ -671,7 +664,7 @@ find_trees (void *cls, const struct GNUNET_HashCode *key, void *value) * @param ip_cls closure for ip */ void -GNUNET_FS_namespace_list_updateable ( +GNUNET_FS_namespace_list_updateable( struct GNUNET_FS_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, const char *next_id, @@ -686,125 +679,125 @@ GNUNET_FS_namespace_list_updateable ( struct FindTreeClosure fc; struct GNUNET_FS_UpdateInformationGraph *uig; - uig = read_update_information_graph (h, ns); + uig = read_update_information_graph(h, ns); if (NULL == uig->update_nodes) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "No updateable nodes found for ID `%s'\n", - next_id); - free_update_information_graph (uig); - return; /* no nodes */ - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "No updateable nodes found for ID `%s'\n", + next_id); + free_update_information_graph(uig); + return; /* no nodes */ + } uig->update_map = - GNUNET_CONTAINER_multihashmap_create (2 + 3 * uig->update_node_count / 4, - GNUNET_NO); + GNUNET_CONTAINER_multihashmap_create(2 + 3 * uig->update_node_count / 4, + GNUNET_NO); for (i = 0; i < uig->update_node_count; i++) - { - nsn = uig->update_nodes[i]; - GNUNET_CRYPTO_hash (nsn->id, strlen (nsn->id), &hc); - GNUNET_CONTAINER_multihashmap_put ( - uig->update_map, - &hc, - nsn, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - } + { + nsn = uig->update_nodes[i]; + GNUNET_CRYPTO_hash(nsn->id, strlen(nsn->id), &hc); + GNUNET_CONTAINER_multihashmap_put( + uig->update_map, + &hc, + nsn, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + } if (NULL != next_id) - { - GNUNET_CRYPTO_hash (next_id, strlen (next_id), &hc); - pc.ip = ip; - pc.ip_cls = ip_cls; - GNUNET_CONTAINER_multihashmap_get_multiple (uig->update_map, - &hc, - &process_update_node, - &pc); - free_update_information_graph (uig); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Calculating TREEs to find roots of update trees\n"); + { + GNUNET_CRYPTO_hash(next_id, strlen(next_id), &hc); + pc.ip = ip; + pc.ip_cls = ip_cls; + GNUNET_CONTAINER_multihashmap_get_multiple(uig->update_map, + &hc, + &process_update_node, + &pc); + free_update_information_graph(uig); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Calculating TREEs to find roots of update trees\n"); /* Find heads of TREEs in update graph */ nug = ++uig->nug_gen; fc.tree_array = NULL; fc.tree_array_size = 0; for (i = 0; i < uig->update_node_count; i++) - { - nsn = uig->update_nodes[i]; - if (nsn->nug == nug) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "TREE of node `%s' is %u\n", - nsn->id, - nsn->nug); - continue; /* already placed in TREE */ - } - GNUNET_CRYPTO_hash (nsn->update, strlen (nsn->update), &hc); - nsn->nug = nug; - nsn->tree_id = UINT_MAX; - fc.id = UINT_MAX; - fc.nug = nug; - fc.uig = uig; - GNUNET_CONTAINER_multihashmap_get_multiple (uig->update_map, - &hc, - &find_trees, - &fc); - if (UINT_MAX == fc.id) { - /* start new TREE */ - for (fc.id = 0; fc.id < fc.tree_array_size; fc.id++) - { - if (NULL == fc.tree_array[fc.id]) + nsn = uig->update_nodes[i]; + if (nsn->nug == nug) { - fc.tree_array[fc.id] = nsn; - nsn->tree_id = fc.id; - break; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "TREE of node `%s' is %u\n", + nsn->id, + nsn->nug); + continue; /* already placed in TREE */ } - } - if (fc.id == fc.tree_array_size) - { - GNUNET_array_append (fc.tree_array, fc.tree_array_size, nsn); - nsn->tree_id = fc.id; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting new TREE %u with node `%s'\n", - nsn->tree_id, - nsn->id); - /* put all nodes with same identifier into this TREE */ - GNUNET_CRYPTO_hash (nsn->id, strlen (nsn->id), &hc); - fc.id = nsn->tree_id; + GNUNET_CRYPTO_hash(nsn->update, strlen(nsn->update), &hc); + nsn->nug = nug; + nsn->tree_id = UINT_MAX; + fc.id = UINT_MAX; fc.nug = nug; fc.uig = uig; - GNUNET_CONTAINER_multihashmap_get_multiple (uig->update_map, - &hc, - &find_trees, - &fc); - } - else - { - /* make head of TREE "id" */ - fc.tree_array[fc.id] = nsn; - nsn->tree_id = fc.id; + GNUNET_CONTAINER_multihashmap_get_multiple(uig->update_map, + &hc, + &find_trees, + &fc); + if (UINT_MAX == fc.id) + { + /* start new TREE */ + for (fc.id = 0; fc.id < fc.tree_array_size; fc.id++) + { + if (NULL == fc.tree_array[fc.id]) + { + fc.tree_array[fc.id] = nsn; + nsn->tree_id = fc.id; + break; + } + } + if (fc.id == fc.tree_array_size) + { + GNUNET_array_append(fc.tree_array, fc.tree_array_size, nsn); + nsn->tree_id = fc.id; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting new TREE %u with node `%s'\n", + nsn->tree_id, + nsn->id); + /* put all nodes with same identifier into this TREE */ + GNUNET_CRYPTO_hash(nsn->id, strlen(nsn->id), &hc); + fc.id = nsn->tree_id; + fc.nug = nug; + fc.uig = uig; + GNUNET_CONTAINER_multihashmap_get_multiple(uig->update_map, + &hc, + &find_trees, + &fc); + } + else + { + /* make head of TREE "id" */ + fc.tree_array[fc.id] = nsn; + nsn->tree_id = fc.id; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "TREE of node `%s' is %u\n", + nsn->id, + fc.id); } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "TREE of node `%s' is %u\n", - nsn->id, - fc.id); - } for (i = 0; i < fc.tree_array_size; i++) - { - nsn = fc.tree_array[i]; - if (NULL != nsn) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Root of TREE %u is node `%s'\n", - i, - nsn->id); - ip (ip_cls, nsn->id, nsn->uri, nsn->md, nsn->update); + nsn = fc.tree_array[i]; + if (NULL != nsn) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Root of TREE %u is node `%s'\n", + i, + nsn->id); + ip(ip_cls, nsn->id, nsn->uri, nsn->md, nsn->update); + } } - } - GNUNET_array_grow (fc.tree_array, fc.tree_array_size, 0); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Done processing TREEs\n"); - free_update_information_graph (uig); + GNUNET_array_grow(fc.tree_array, fc.tree_array_size, 0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Done processing TREEs\n"); + free_update_information_graph(uig); } diff --git a/src/fs/fs_publish.c b/src/fs/fs_publish.c index 71ab1122c..b599bb06e 100644 --- a/src/fs/fs_publish.c +++ b/src/fs/fs_publish.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_publish.c * @brief publish a file or directory in GNUnet @@ -44,10 +44,10 @@ * @return value returned from callback */ void * -GNUNET_FS_publish_make_status_ (struct GNUNET_FS_ProgressInfo *pi, - struct GNUNET_FS_PublishContext *pc, - const struct GNUNET_FS_FileInformation *p, - uint64_t offset) +GNUNET_FS_publish_make_status_(struct GNUNET_FS_ProgressInfo *pi, + struct GNUNET_FS_PublishContext *pc, + const struct GNUNET_FS_FileInformation *p, + uint64_t offset) { pi->value.publish.pc = pc; pi->value.publish.fi = p; @@ -55,16 +55,16 @@ GNUNET_FS_publish_make_status_ (struct GNUNET_FS_ProgressInfo *pi, pi->value.publish.pctx = (NULL == p->dir) ? NULL : p->dir->client_info; pi->value.publish.filename = p->filename; pi->value.publish.size = - (GNUNET_YES == p->is_directory) ? p->data.dir.dir_size : p->data.file.file_size; + (GNUNET_YES == p->is_directory) ? p->data.dir.dir_size : p->data.file.file_size; pi->value.publish.eta = - GNUNET_TIME_calculate_eta (p->start_time, offset, - pi->value.publish.size); + GNUNET_TIME_calculate_eta(p->start_time, offset, + pi->value.publish.size); pi->value.publish.completed = offset; pi->value.publish.duration = - GNUNET_TIME_absolute_get_duration (p->start_time); + GNUNET_TIME_absolute_get_duration(p->start_time); pi->value.publish.anonymity = p->bo.anonymity_level; pi->fsh = pc->h; - return pc->h->upcb (pc->h->upcb_cls, pi); + return pc->h->upcb(pc->h->upcb_cls, pi); } @@ -74,31 +74,31 @@ GNUNET_FS_publish_make_status_ (struct GNUNET_FS_ProgressInfo *pi, * @param pc struct to clean up */ static void -publish_cleanup (struct GNUNET_FS_PublishContext *pc) +publish_cleanup(struct GNUNET_FS_PublishContext *pc) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Cleaning up publish context (done!)\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Cleaning up publish context (done!)\n"); if (NULL != pc->fhc) - { - GNUNET_CRYPTO_hash_file_cancel (pc->fhc); - pc->fhc = NULL; - } - GNUNET_FS_file_information_destroy (pc->fi, NULL, NULL); - GNUNET_free_non_null (pc->nid); - GNUNET_free_non_null (pc->nuid); - GNUNET_free_non_null (pc->serialization); + { + GNUNET_CRYPTO_hash_file_cancel(pc->fhc); + pc->fhc = NULL; + } + GNUNET_FS_file_information_destroy(pc->fi, NULL, NULL); + GNUNET_free_non_null(pc->nid); + GNUNET_free_non_null(pc->nuid); + GNUNET_free_non_null(pc->serialization); if (NULL != pc->dsh) - { - GNUNET_DATASTORE_disconnect (pc->dsh, GNUNET_NO); - pc->dsh = NULL; - } + { + GNUNET_DATASTORE_disconnect(pc->dsh, GNUNET_NO); + pc->dsh = NULL; + } if (NULL != pc->mq) - { - GNUNET_MQ_destroy (pc->mq); - pc->mq = NULL; - } - GNUNET_assert (NULL == pc->upload_task); - GNUNET_free (pc); + { + GNUNET_MQ_destroy(pc->mq); + pc->mq = NULL; + } + GNUNET_assert(NULL == pc->upload_task); + GNUNET_free(pc); } @@ -112,42 +112,42 @@ publish_cleanup (struct GNUNET_FS_PublishContext *pc) * @param msg error message (or NULL) */ static void -ds_put_cont (void *cls, - int success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +ds_put_cont(void *cls, + int success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_ProgressInfo pi; pc->qre = NULL; if (GNUNET_SYSERR == success) - { - GNUNET_asprintf (&pc->fi_pos->emsg, - _("Publishing failed: %s"), - msg); - pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR; - pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL; - pi.value.publish.specifics.error.message = pc->fi_pos->emsg; - pc->fi_pos->client_info = - GNUNET_FS_publish_make_status_ (&pi, pc, pc->fi_pos, 0); - if ((GNUNET_YES != pc->fi_pos->is_directory) && - (NULL != pc->fi_pos->filename) && - (GNUNET_YES == pc->any_done) && - (GNUNET_YES == pc->fi_pos->data.file.do_index)) { - /* run unindex to clean up */ - GNUNET_FS_unindex_start (pc->h, - pc->fi_pos->filename, - NULL); + GNUNET_asprintf(&pc->fi_pos->emsg, + _("Publishing failed: %s"), + msg); + pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR; + pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL; + pi.value.publish.specifics.error.message = pc->fi_pos->emsg; + pc->fi_pos->client_info = + GNUNET_FS_publish_make_status_(&pi, pc, pc->fi_pos, 0); + if ((GNUNET_YES != pc->fi_pos->is_directory) && + (NULL != pc->fi_pos->filename) && + (GNUNET_YES == pc->any_done) && + (GNUNET_YES == pc->fi_pos->data.file.do_index)) + { + /* run unindex to clean up */ + GNUNET_FS_unindex_start(pc->h, + pc->fi_pos->filename, + NULL); + } + return; } - return; - } pc->any_done = GNUNET_YES; - GNUNET_assert (NULL == pc->upload_task); + GNUNET_assert(NULL == pc->upload_task); pc->upload_task = - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, - &GNUNET_FS_publish_main_, pc); + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_BACKGROUND, + &GNUNET_FS_publish_main_, pc); } @@ -160,8 +160,8 @@ ds_put_cont (void *cls, * @param pc context of the publication */ static void -signal_publish_completion (struct GNUNET_FS_FileInformation *p, - struct GNUNET_FS_PublishContext *pc) +signal_publish_completion(struct GNUNET_FS_FileInformation *p, + struct GNUNET_FS_PublishContext *pc) { struct GNUNET_FS_ProgressInfo pi; @@ -170,8 +170,8 @@ signal_publish_completion (struct GNUNET_FS_FileInformation *p, pi.value.publish.specifics.completed.chk_uri = p->chk_uri; pi.value.publish.specifics.completed.sks_uri = p->sks_uri; p->client_info = - GNUNET_FS_publish_make_status_ (&pi, pc, p, - p->data.file.file_size); + GNUNET_FS_publish_make_status_(&pi, pc, p, + p->data.file.file_size); } @@ -185,28 +185,27 @@ signal_publish_completion (struct GNUNET_FS_FileInformation *p, * @param emsg error message */ static void -signal_publish_error (struct GNUNET_FS_FileInformation *p, - struct GNUNET_FS_PublishContext *pc, - const char *emsg) +signal_publish_error(struct GNUNET_FS_FileInformation *p, + struct GNUNET_FS_PublishContext *pc, + const char *emsg) { struct GNUNET_FS_ProgressInfo pi; - p->emsg = GNUNET_strdup (emsg); + p->emsg = GNUNET_strdup(emsg); pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR; pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL; pi.value.publish.specifics.error.message = emsg; - p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, 0); + p->client_info = GNUNET_FS_publish_make_status_(&pi, pc, p, 0); if ((p->is_directory != GNUNET_YES) && (NULL != p->filename) && (GNUNET_YES == pc->any_done) && (p->data.file.do_index == GNUNET_YES)) - { - /* run unindex to clean up */ - GNUNET_FS_unindex_start (pc->h, - p->filename, - NULL); - } - + { + /* run unindex to clean up */ + GNUNET_FS_unindex_start(pc->h, + p->filename, + NULL); + } } @@ -219,18 +218,18 @@ signal_publish_error (struct GNUNET_FS_FileInformation *p, * @param msg error message (typically NULL, not used) */ static void -finish_release_reserve (void *cls, int success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +finish_release_reserve(void *cls, int success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct GNUNET_FS_PublishContext *pc = cls; pc->qre = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Releasing reserve done!\n"); - signal_publish_completion (pc->fi, pc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Releasing reserve done!\n"); + signal_publish_completion(pc->fi, pc); pc->all_done = GNUNET_YES; - GNUNET_FS_publish_sync_ (pc); + GNUNET_FS_publish_sync_(pc); } @@ -243,35 +242,35 @@ finish_release_reserve (void *cls, int success, * @param emsg NULL on success, otherwise error message */ static void -publish_sblocks_cont (void *cls, - const struct GNUNET_FS_Uri *uri, - const char *emsg) +publish_sblocks_cont(void *cls, + const struct GNUNET_FS_Uri *uri, + const char *emsg) { struct GNUNET_FS_PublishContext *pc = cls; pc->sks_pc = NULL; if (NULL != emsg) - { - signal_publish_error (pc->fi, pc, emsg); - GNUNET_FS_publish_sync_ (pc); - return; - } + { + signal_publish_error(pc->fi, pc, emsg); + GNUNET_FS_publish_sync_(pc); + return; + } if (NULL != uri) - { - /* sks publication, remember namespace URI */ - pc->fi->sks_uri = GNUNET_FS_uri_dup (uri); - } - GNUNET_assert (pc->qre == NULL); + { + /* sks publication, remember namespace URI */ + pc->fi->sks_uri = GNUNET_FS_uri_dup(uri); + } + GNUNET_assert(pc->qre == NULL); if ((pc->dsh != NULL) && (pc->rid != 0)) - { - pc->qre = - GNUNET_DATASTORE_release_reserve (pc->dsh, pc->rid, UINT_MAX, UINT_MAX, - &finish_release_reserve, pc); - } + { + pc->qre = + GNUNET_DATASTORE_release_reserve(pc->dsh, pc->rid, UINT_MAX, UINT_MAX, + &finish_release_reserve, pc); + } else - { - finish_release_reserve (pc, GNUNET_OK, GNUNET_TIME_UNIT_ZERO_ABS, NULL); - } + { + finish_release_reserve(pc, GNUNET_OK, GNUNET_TIME_UNIT_ZERO_ABS, NULL); + } } @@ -282,20 +281,20 @@ publish_sblocks_cont (void *cls, * @param pc overall upload data */ static void -publish_sblock (struct GNUNET_FS_PublishContext *pc) +publish_sblock(struct GNUNET_FS_PublishContext *pc) { if (NULL != pc->ns) - pc->sks_pc = GNUNET_FS_publish_sks (pc->h, - pc->ns, - pc->nid, - pc->nuid, - pc->fi->meta, - pc->fi->chk_uri, - &pc->fi->bo, - pc->options, - &publish_sblocks_cont, pc); + pc->sks_pc = GNUNET_FS_publish_sks(pc->h, + pc->ns, + pc->nid, + pc->nuid, + pc->fi->meta, + pc->fi->chk_uri, + &pc->fi->bo, + pc->options, + &publish_sblocks_cont, pc); else - publish_sblocks_cont (pc, NULL, NULL); + publish_sblocks_cont(pc, NULL, NULL); } @@ -309,44 +308,44 @@ publish_sblock (struct GNUNET_FS_PublishContext *pc) * @param emsg NULL on success, otherwise error message */ static void -publish_kblocks_cont (void *cls, - const struct GNUNET_FS_Uri *uri, - const char *emsg) +publish_kblocks_cont(void *cls, + const struct GNUNET_FS_Uri *uri, + const char *emsg) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_FileInformation *p = pc->fi_pos; pc->ksk_pc = NULL; if (NULL != emsg) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Error uploading KSK blocks: %s\n", - emsg); - signal_publish_error (p, pc, emsg); - GNUNET_FS_file_information_sync_ (p); - GNUNET_FS_publish_sync_ (pc); - GNUNET_assert (NULL == pc->upload_task); - pc->upload_task = - GNUNET_SCHEDULER_add_with_priority - (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, - &GNUNET_FS_publish_main_, - pc); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "KSK blocks published, moving on to next file\n"); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Error uploading KSK blocks: %s\n", + emsg); + signal_publish_error(p, pc, emsg); + GNUNET_FS_file_information_sync_(p); + GNUNET_FS_publish_sync_(pc); + GNUNET_assert(NULL == pc->upload_task); + pc->upload_task = + GNUNET_SCHEDULER_add_with_priority + (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, + &GNUNET_FS_publish_main_, + pc); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "KSK blocks published, moving on to next file\n"); if (NULL != p->dir) - signal_publish_completion (p, pc); + signal_publish_completion(p, pc); /* move on to next file */ if (NULL != p->next) pc->fi_pos = p->next; else pc->fi_pos = p->dir; - GNUNET_FS_publish_sync_ (pc); - GNUNET_assert (NULL == pc->upload_task); + GNUNET_FS_publish_sync_(pc); + GNUNET_assert(NULL == pc->upload_task); pc->upload_task = - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, - &GNUNET_FS_publish_main_, pc); + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_BACKGROUND, + &GNUNET_FS_publish_main_, pc); } @@ -364,11 +363,11 @@ publish_kblocks_cont (void *cls, * @return number of bytes copied to buf, 0 on error */ static size_t -block_reader (void *cls, - uint64_t offset, - size_t max, - void *buf, - char **emsg) +block_reader(void *cls, + uint64_t offset, + size_t max, + void *buf, + char **emsg) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_FileInformation *p; @@ -377,31 +376,31 @@ block_reader (void *cls, p = pc->fi_pos; if (GNUNET_YES == p->is_directory) - { - pt_size = GNUNET_MIN (max, p->data.dir.dir_size - offset); - dd = p->data.dir.dir_data; - GNUNET_memcpy (buf, &dd[offset], pt_size); - } + { + pt_size = GNUNET_MIN(max, p->data.dir.dir_size - offset); + dd = p->data.dir.dir_data; + GNUNET_memcpy(buf, &dd[offset], pt_size); + } else - { - if (UINT64_MAX == offset) - { - if (&GNUNET_FS_data_reader_file_ == p->data.file.reader) - { - /* force closing the file to avoid keeping too many files open */ - p->data.file.reader (p->data.file.reader_cls, offset, 0, NULL, NULL); - } - return 0; - } - pt_size = GNUNET_MIN (max, p->data.file.file_size - offset); - if (0 == pt_size) - return 0; /* calling reader with pt_size==0 + { + if (UINT64_MAX == offset) + { + if (&GNUNET_FS_data_reader_file_ == p->data.file.reader) + { + /* force closing the file to avoid keeping too many files open */ + p->data.file.reader(p->data.file.reader_cls, offset, 0, NULL, NULL); + } + return 0; + } + pt_size = GNUNET_MIN(max, p->data.file.file_size - offset); + if (0 == pt_size) + return 0; /* calling reader with pt_size==0 * might free buf, so don't! */ - if (pt_size != - p->data.file.reader (p->data.file.reader_cls, offset, pt_size, buf, - emsg)) - return 0; - } + if (pt_size != + p->data.file.reader(p->data.file.reader_cls, offset, pt_size, buf, + emsg)) + return 0; + } return pt_size; } @@ -414,7 +413,7 @@ block_reader (void *cls, * @param cls our publishing context */ static void -encode_cont (void *cls) +encode_cont(void *cls) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_FileInformation *p; @@ -422,44 +421,44 @@ encode_cont (void *cls) char *emsg; uint64_t flen; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished with tree encoder\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished with tree encoder\n"); p = pc->fi_pos; - p->chk_uri = GNUNET_FS_tree_encoder_get_uri (p->te); - GNUNET_FS_file_information_sync_ (p); - GNUNET_FS_tree_encoder_finish (p->te, &emsg); + p->chk_uri = GNUNET_FS_tree_encoder_get_uri(p->te); + GNUNET_FS_file_information_sync_(p); + GNUNET_FS_tree_encoder_finish(p->te, &emsg); p->te = NULL; if (NULL != emsg) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Error during tree walk: %s\n", - emsg); - GNUNET_asprintf (&p->emsg, - _("Publishing failed: %s"), - emsg); - GNUNET_free (emsg); - pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR; - pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL; - pi.value.publish.specifics.error.message = p->emsg; - p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, 0); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Error during tree walk: %s\n", + emsg); + GNUNET_asprintf(&p->emsg, + _("Publishing failed: %s"), + emsg); + GNUNET_free(emsg); + pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR; + pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL; + pi.value.publish.specifics.error.message = p->emsg; + p->client_info = GNUNET_FS_publish_make_status_(&pi, pc, p, 0); + } else - { - /* final progress event */ - GNUNET_assert (NULL != p->chk_uri); - flen = GNUNET_FS_uri_chk_get_file_size (p->chk_uri); - pi.status = GNUNET_FS_STATUS_PUBLISH_PROGRESS; - pi.value.publish.specifics.progress.data = NULL; - pi.value.publish.specifics.progress.offset = flen; - pi.value.publish.specifics.progress.data_len = 0; - pi.value.publish.specifics.progress.depth = GNUNET_FS_compute_depth (flen); - p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, flen); - } + { + /* final progress event */ + GNUNET_assert(NULL != p->chk_uri); + flen = GNUNET_FS_uri_chk_get_file_size(p->chk_uri); + pi.status = GNUNET_FS_STATUS_PUBLISH_PROGRESS; + pi.value.publish.specifics.progress.data = NULL; + pi.value.publish.specifics.progress.offset = flen; + pi.value.publish.specifics.progress.data_len = 0; + pi.value.publish.specifics.progress.depth = GNUNET_FS_compute_depth(flen); + p->client_info = GNUNET_FS_publish_make_status_(&pi, pc, p, flen); + } /* continue with main */ /* continue with main */ - GNUNET_assert (NULL == pc->upload_task); + GNUNET_assert(NULL == pc->upload_task); pc->upload_task = - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, - &GNUNET_FS_publish_main_, pc); + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_BACKGROUND, + &GNUNET_FS_publish_main_, pc); } @@ -478,13 +477,13 @@ encode_cont (void *cls) * @param block_size size of @a block (in bytes) */ static void -block_proc (void *cls, - const struct ContentHashKey *chk, - uint64_t offset, - unsigned int depth, - enum GNUNET_BLOCK_Type type, - const void *block, - uint16_t block_size) +block_proc(void *cls, + const struct ContentHashKey *chk, + uint64_t offset, + unsigned int depth, + enum GNUNET_BLOCK_Type type, + const void *block, + uint16_t block_size) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_FileInformation *p; @@ -492,62 +491,62 @@ block_proc (void *cls, p = pc->fi_pos; if (NULL == pc->dsh) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Waiting for datastore connection\n"); - GNUNET_assert (NULL == pc->upload_task); - pc->upload_task = + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Waiting for datastore connection\n"); + GNUNET_assert(NULL == pc->upload_task); + pc->upload_task = GNUNET_SCHEDULER_add_with_priority - (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, &GNUNET_FS_publish_main_, pc); - return; - } - - if ( (GNUNET_YES != p->is_directory) && - (GNUNET_YES == p->data.file.do_index) && - (GNUNET_BLOCK_TYPE_FS_DBLOCK == type) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Indexing block `%s' for offset %llu with index size %u\n", - GNUNET_h2s (&chk->query), - (unsigned long long) offset, - (unsigned int) sizeof (struct OnDemandBlock)); - odb.offset = GNUNET_htonll (offset); - odb.file_id = p->data.file.file_id; - GNUNET_assert (pc->qre == NULL); - pc->qre = - GNUNET_DATASTORE_put (pc->dsh, - (p->is_directory == GNUNET_YES) ? 0 : pc->rid, - &chk->query, - sizeof (struct OnDemandBlock), - &odb, - GNUNET_BLOCK_TYPE_FS_ONDEMAND, - p->bo.content_priority, - p->bo.anonymity_level, - p->bo.replication_level, - p->bo.expiration_time, - -2, 1, - &ds_put_cont, pc); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publishing block `%s' for offset %llu with size %u\n", - GNUNET_h2s (&chk->query), - (unsigned long long) offset, - (unsigned int) block_size); - GNUNET_assert (pc->qre == NULL); + (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, &GNUNET_FS_publish_main_, pc); + return; + } + + if ((GNUNET_YES != p->is_directory) && + (GNUNET_YES == p->data.file.do_index) && + (GNUNET_BLOCK_TYPE_FS_DBLOCK == type)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Indexing block `%s' for offset %llu with index size %u\n", + GNUNET_h2s(&chk->query), + (unsigned long long)offset, + (unsigned int)sizeof(struct OnDemandBlock)); + odb.offset = GNUNET_htonll(offset); + odb.file_id = p->data.file.file_id; + GNUNET_assert(pc->qre == NULL); + pc->qre = + GNUNET_DATASTORE_put(pc->dsh, + (p->is_directory == GNUNET_YES) ? 0 : pc->rid, + &chk->query, + sizeof(struct OnDemandBlock), + &odb, + GNUNET_BLOCK_TYPE_FS_ONDEMAND, + p->bo.content_priority, + p->bo.anonymity_level, + p->bo.replication_level, + p->bo.expiration_time, + -2, 1, + &ds_put_cont, pc); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publishing block `%s' for offset %llu with size %u\n", + GNUNET_h2s(&chk->query), + (unsigned long long)offset, + (unsigned int)block_size); + GNUNET_assert(pc->qre == NULL); pc->qre = - GNUNET_DATASTORE_put (pc->dsh, (p->is_directory == GNUNET_YES) ? 0 : pc->rid, - &chk->query, - block_size, - block, - type, - p->bo.content_priority, - p->bo.anonymity_level, - p->bo.replication_level, - p->bo.expiration_time, - -2, 1, - &ds_put_cont, - pc); + GNUNET_DATASTORE_put(pc->dsh, (p->is_directory == GNUNET_YES) ? 0 : pc->rid, + &chk->query, + block_size, + block, + type, + p->bo.content_priority, + p->bo.anonymity_level, + p->bo.replication_level, + p->bo.expiration_time, + -2, 1, + &ds_put_cont, + pc); } @@ -562,10 +561,10 @@ block_proc (void *cls, * @param depth depth of the block in the tree, 0 for DBLOCK */ static void -progress_proc (void *cls, uint64_t offset, - const void *pt_block, - size_t pt_size, - unsigned int depth) +progress_proc(void *cls, uint64_t offset, + const void *pt_block, + size_t pt_size, + unsigned int depth) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_FileInformation *p; @@ -578,24 +577,23 @@ progress_proc (void *cls, uint64_t offset, pi.value.publish.specifics.progress.offset = offset; pi.value.publish.specifics.progress.data_len = pt_size; pi.value.publish.specifics.progress.depth = depth; - p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, offset); - if ( (0 != depth) || - (GNUNET_YES == p->is_directory) ) + p->client_info = GNUNET_FS_publish_make_status_(&pi, pc, p, offset); + if ((0 != depth) || + (GNUNET_YES == p->is_directory)) return; while (NULL != (par = p->dir)) - { - p = par; - GNUNET_assert (GNUNET_YES == par->is_directory); - p->data.dir.contents_completed += pt_size; - pi.status = GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY; - pi.value.publish.specifics.progress_directory.completed = p->data.dir.contents_completed; - pi.value.publish.specifics.progress_directory.total = p->data.dir.contents_size; - pi.value.publish.specifics.progress_directory.eta = GNUNET_TIME_calculate_eta (p->start_time, - p->data.dir.contents_completed, - p->data.dir.contents_size); - p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, 0); - - } + { + p = par; + GNUNET_assert(GNUNET_YES == par->is_directory); + p->data.dir.contents_completed += pt_size; + pi.status = GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY; + pi.value.publish.specifics.progress_directory.completed = p->data.dir.contents_completed; + pi.value.publish.specifics.progress_directory.total = p->data.dir.contents_size; + pi.value.publish.specifics.progress_directory.eta = GNUNET_TIME_calculate_eta(p->start_time, + p->data.dir.contents_completed, + p->data.dir.contents_size); + p->client_info = GNUNET_FS_publish_make_status_(&pi, pc, p, 0); + } } @@ -607,7 +605,7 @@ progress_proc (void *cls, uint64_t offset, * @param pc overall upload data */ static void -publish_content (struct GNUNET_FS_PublishContext *pc) +publish_content(struct GNUNET_FS_PublishContext *pc) { struct GNUNET_FS_FileInformation *p; char *emsg; @@ -617,65 +615,64 @@ publish_content (struct GNUNET_FS_PublishContext *pc) uint64_t size; p = pc->fi_pos; - GNUNET_assert (NULL != p); + GNUNET_assert(NULL != p); if (NULL == p->te) - { - if (GNUNET_YES == p->is_directory) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating directory\n"); - db = GNUNET_FS_directory_builder_create (p->meta); - dirpos = p->data.dir.entries; - while (NULL != dirpos) - { - if (GNUNET_YES == dirpos->is_directory) - { - raw_data = dirpos->data.dir.dir_data; - dirpos->data.dir.dir_data = NULL; - } - else + { + if (GNUNET_YES == p->is_directory) { - raw_data = NULL; - if ((dirpos->data.file.file_size < MAX_INLINE_SIZE) && - (dirpos->data.file.file_size > 0)) - { - raw_data = GNUNET_malloc (dirpos->data.file.file_size); - emsg = NULL; - if (dirpos->data.file.file_size != - dirpos->data.file.reader (dirpos->data.file.reader_cls, 0, - dirpos->data.file.file_size, raw_data, - &emsg)) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Creating directory\n"); + db = GNUNET_FS_directory_builder_create(p->meta); + dirpos = p->data.dir.entries; + while (NULL != dirpos) { - GNUNET_free_non_null (emsg); - GNUNET_free (raw_data); - raw_data = NULL; + if (GNUNET_YES == dirpos->is_directory) + { + raw_data = dirpos->data.dir.dir_data; + dirpos->data.dir.dir_data = NULL; + } + else + { + raw_data = NULL; + if ((dirpos->data.file.file_size < MAX_INLINE_SIZE) && + (dirpos->data.file.file_size > 0)) + { + raw_data = GNUNET_malloc(dirpos->data.file.file_size); + emsg = NULL; + if (dirpos->data.file.file_size != + dirpos->data.file.reader(dirpos->data.file.reader_cls, 0, + dirpos->data.file.file_size, raw_data, + &emsg)) + { + GNUNET_free_non_null(emsg); + GNUNET_free(raw_data); + raw_data = NULL; + } + dirpos->data.file.reader(dirpos->data.file.reader_cls, UINT64_MAX, 0, 0, NULL); + } + } + GNUNET_FS_directory_builder_add(db, dirpos->chk_uri, dirpos->meta, + raw_data); + GNUNET_free_non_null(raw_data); + dirpos = dirpos->next; } - dirpos->data.file.reader (dirpos->data.file.reader_cls, UINT64_MAX, 0, 0, NULL); - } + GNUNET_free_non_null(p->data.dir.dir_data); + p->data.dir.dir_data = NULL; + p->data.dir.dir_size = 0; + GNUNET_FS_directory_builder_finish(db, &p->data.dir.dir_size, + &p->data.dir.dir_data); + GNUNET_FS_file_information_sync_(p); } - GNUNET_FS_directory_builder_add (db, dirpos->chk_uri, dirpos->meta, - raw_data); - GNUNET_free_non_null (raw_data); - dirpos = dirpos->next; - } - GNUNET_free_non_null (p->data.dir.dir_data); - p->data.dir.dir_data = NULL; - p->data.dir.dir_size = 0; - GNUNET_FS_directory_builder_finish (db, &p->data.dir.dir_size, - &p->data.dir.dir_data); - GNUNET_FS_file_information_sync_ (p); - } - size = (GNUNET_YES == p->is_directory) ? p->data.dir.dir_size : p->data.file.file_size; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Creating tree encoder\n"); - p->te = - GNUNET_FS_tree_encoder_create (pc->h, size, pc, &block_reader, - &block_proc, &progress_proc, - &encode_cont); - - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Processing next block from tree\n"); - GNUNET_FS_tree_encoder_next (p->te); + size = (GNUNET_YES == p->is_directory) ? p->data.dir.dir_size : p->data.file.file_size; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Creating tree encoder\n"); + p->te = + GNUNET_FS_tree_encoder_create(pc->h, size, pc, &block_reader, + &block_proc, &progress_proc, + &encode_cont); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Processing next block from tree\n"); + GNUNET_FS_tree_encoder_next(p->te); } @@ -687,17 +684,17 @@ publish_content (struct GNUNET_FS_PublishContext *pc) * @param msg the response we got */ static int -check_index_start_failed (void *cls, - const struct GNUNET_MessageHeader *msg) +check_index_start_failed(void *cls, + const struct GNUNET_MessageHeader *msg) { - size_t msize = ntohs (msg->size) - sizeof (*msg); - const char *emsg = (const char *) &msg[1]; - - if (emsg[msize - sizeof (struct GNUNET_MessageHeader) - 1] != '\0') - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + size_t msize = ntohs(msg->size) - sizeof(*msg); + const char *emsg = (const char *)&msg[1]; + + if (emsg[msize - sizeof(struct GNUNET_MessageHeader) - 1] != '\0') + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -710,27 +707,27 @@ check_index_start_failed (void *cls, * @param msg the response we got */ static void -handle_index_start_failed (void *cls, - const struct GNUNET_MessageHeader *msg) +handle_index_start_failed(void *cls, + const struct GNUNET_MessageHeader *msg) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_FileInformation *p; - const char *emsg = (const char *) &msg[1]; + const char *emsg = (const char *)&msg[1]; char *msgtxt; - GNUNET_MQ_destroy (pc->mq); + GNUNET_MQ_destroy(pc->mq); pc->mq = NULL; p = pc->fi_pos; - GNUNET_asprintf (&msgtxt, - _("Can not index file `%s': %s.\n"), - p->filename, - gettext (emsg)); - signal_publish_error (p, - pc, - msgtxt); - GNUNET_free (msgtxt); - GNUNET_FS_file_information_sync_ (p); - GNUNET_FS_publish_sync_ (pc); + GNUNET_asprintf(&msgtxt, + _("Can not index file `%s': %s.\n"), + p->filename, + gettext(emsg)); + signal_publish_error(p, + pc, + msgtxt); + GNUNET_free(msgtxt); + GNUNET_FS_file_information_sync_(p); + GNUNET_FS_publish_sync_(pc); } @@ -742,18 +739,18 @@ handle_index_start_failed (void *cls, * @param msg the response we got */ static void -handle_index_start_ok (void *cls, - const struct GNUNET_MessageHeader *msg) +handle_index_start_ok(void *cls, + const struct GNUNET_MessageHeader *msg) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_FileInformation *p; - GNUNET_MQ_destroy (pc->mq); + GNUNET_MQ_destroy(pc->mq); pc->mq = NULL; p = pc->fi_pos; p->data.file.index_start_confirmed = GNUNET_YES; - GNUNET_FS_file_information_sync_ (p); - publish_content (pc); + GNUNET_FS_file_information_sync_(p); + publish_content(pc); } @@ -766,25 +763,25 @@ handle_index_start_ok (void *cls, * @param error error code */ static void -index_mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +index_mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_FileInformation *p; if (NULL != pc->mq) - { - GNUNET_MQ_destroy (pc->mq); - pc->mq = NULL; - } + { + GNUNET_MQ_destroy(pc->mq); + pc->mq = NULL; + } p = pc->fi_pos; - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Can not index file `%s': %s. Will try to insert instead.\n"), - p->filename, - _("error on index-start request to `fs' service")); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Can not index file `%s': %s. Will try to insert instead.\n"), + p->filename, + _("error on index-start request to `fs' service")); p->data.file.do_index = GNUNET_NO; - GNUNET_FS_file_information_sync_ (p); - publish_content (pc); + GNUNET_FS_file_information_sync_(p); + publish_content(pc); } @@ -796,20 +793,20 @@ index_mq_error_handler (void *cls, * @param res resulting hash, NULL on error */ static void -hash_for_index_cb (void *cls, - const struct GNUNET_HashCode *res) +hash_for_index_cb(void *cls, + const struct GNUNET_HashCode *res) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (index_start_ok, - GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK, - struct GNUNET_MessageHeader, - pc), - GNUNET_MQ_hd_var_size (index_start_failed, - GNUNET_MESSAGE_TYPE_FS_INDEX_START_FAILED, - struct GNUNET_MessageHeader, - pc), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(index_start_ok, + GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK, + struct GNUNET_MessageHeader, + pc), + GNUNET_MQ_hd_var_size(index_start_failed, + GNUNET_MESSAGE_TYPE_FS_INDEX_START_FAILED, + struct GNUNET_MessageHeader, + pc), + GNUNET_MQ_handler_end() }; struct GNUNET_FS_FileInformation *p; struct GNUNET_MQ_Envelope *env; @@ -822,97 +819,97 @@ hash_for_index_cb (void *cls, pc->fhc = NULL; p = pc->fi_pos; if (NULL == res) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Can not index file `%s': %s. Will try to insert instead.\n"), - p->filename, - _("failed to compute hash")); - p->data.file.do_index = GNUNET_NO; - GNUNET_FS_file_information_sync_ (p); - publish_content (pc); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Can not index file `%s': %s. Will try to insert instead.\n"), + p->filename, + _("failed to compute hash")); + p->data.file.do_index = GNUNET_NO; + GNUNET_FS_file_information_sync_(p); + publish_content(pc); + return; + } if (GNUNET_YES == p->data.file.index_start_confirmed) - { - publish_content (pc); - return; - } - fn = GNUNET_STRINGS_filename_expand (p->filename); - GNUNET_assert (fn != NULL); - slen = strlen (fn) + 1; + { + publish_content(pc); + return; + } + fn = GNUNET_STRINGS_filename_expand(p->filename); + GNUNET_assert(fn != NULL); + slen = strlen(fn) + 1; if (slen >= - GNUNET_MAX_MESSAGE_SIZE - sizeof (struct IndexStartMessage)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ - ("Can not index file `%s': %s. Will try to insert instead.\n"), - fn, _("filename too long")); - GNUNET_free (fn); - p->data.file.do_index = GNUNET_NO; - GNUNET_FS_file_information_sync_ (p); - publish_content (pc); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Hash of indexed file `%s' is `%s'\n", - p->filename, - GNUNET_h2s (res)); + GNUNET_MAX_MESSAGE_SIZE - sizeof(struct IndexStartMessage)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _ + ("Can not index file `%s': %s. Will try to insert instead.\n"), + fn, _("filename too long")); + GNUNET_free(fn); + p->data.file.do_index = GNUNET_NO; + GNUNET_FS_file_information_sync_(p); + publish_content(pc); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Hash of indexed file `%s' is `%s'\n", + p->filename, + GNUNET_h2s(res)); if (0 != (pc->options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY)) - { - p->data.file.file_id = *res; - p->data.file.have_hash = GNUNET_YES; - p->data.file.index_start_confirmed = GNUNET_YES; - GNUNET_FS_file_information_sync_ (p); - publish_content (pc); - GNUNET_free (fn); - return; - } - pc->mq = GNUNET_CLIENT_connect (pc->h->cfg, - "fs", - handlers, - &index_mq_error_handler, - pc); + { + p->data.file.file_id = *res; + p->data.file.have_hash = GNUNET_YES; + p->data.file.index_start_confirmed = GNUNET_YES; + GNUNET_FS_file_information_sync_(p); + publish_content(pc); + GNUNET_free(fn); + return; + } + pc->mq = GNUNET_CLIENT_connect(pc->h->cfg, + "fs", + handlers, + &index_mq_error_handler, + pc); if (NULL == pc->mq) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Can not index file `%s': %s. Will try to insert instead.\n"), - p->filename, - _("could not connect to `fs' service")); - p->data.file.do_index = GNUNET_NO; - publish_content (pc); - GNUNET_free (fn); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Can not index file `%s': %s. Will try to insert instead.\n"), + p->filename, + _("could not connect to `fs' service")); + p->data.file.do_index = GNUNET_NO; + publish_content(pc); + GNUNET_free(fn); + return; + } if (p->data.file.have_hash != GNUNET_YES) - { - p->data.file.file_id = *res; - p->data.file.have_hash = GNUNET_YES; - GNUNET_FS_file_information_sync_ (p); - } - env = GNUNET_MQ_msg_extra (ism, - slen, - GNUNET_MESSAGE_TYPE_FS_INDEX_START); + { + p->data.file.file_id = *res; + p->data.file.have_hash = GNUNET_YES; + GNUNET_FS_file_information_sync_(p); + } + env = GNUNET_MQ_msg_extra(ism, + slen, + GNUNET_MESSAGE_TYPE_FS_INDEX_START); if (GNUNET_OK == - GNUNET_DISK_file_get_identifiers (p->filename, - &dev, - &ino)) - { - ism->device = GNUNET_htonll (dev); - ism->inode = GNUNET_htonll (ino); - } + GNUNET_DISK_file_get_identifiers(p->filename, + &dev, + &ino)) + { + ism->device = GNUNET_htonll(dev); + ism->inode = GNUNET_htonll(ino); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - _("Failed to get file identifiers for `%s'\n"), - p->filename); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + _("Failed to get file identifiers for `%s'\n"), + p->filename); + } ism->file_id = *res; - GNUNET_memcpy (&ism[1], - fn, - slen); - GNUNET_free (fn); - GNUNET_MQ_send (pc->mq, - env); + GNUNET_memcpy(&ism[1], + fn, + slen); + GNUNET_free(fn); + GNUNET_MQ_send(pc->mq, + env); } @@ -922,27 +919,27 @@ hash_for_index_cb (void *cls, * @param pc publishing context to do this for */ static void -publish_kblocks (struct GNUNET_FS_PublishContext *pc) +publish_kblocks(struct GNUNET_FS_PublishContext *pc) { struct GNUNET_FS_FileInformation *p; p = pc->fi_pos; /* upload of "p" complete, publish KBlocks! */ if (NULL != p->keywords) - { - pc->ksk_pc = GNUNET_FS_publish_ksk (pc->h, - p->keywords, - p->meta, - p->chk_uri, - &p->bo, - pc->options, - &publish_kblocks_cont, - pc); - } + { + pc->ksk_pc = GNUNET_FS_publish_ksk(pc->h, + p->keywords, + p->meta, + p->chk_uri, + &p->bo, + pc->options, + &publish_kblocks_cont, + pc); + } else - { - publish_kblocks_cont (pc, p->chk_uri, NULL); - } + { + publish_kblocks_cont(pc, p->chk_uri, NULL); + } } @@ -953,8 +950,8 @@ publish_kblocks (struct GNUNET_FS_PublishContext *pc) * @param sig the response we got */ static void -handle_signature_response (void *cls, - const struct ResponseLocSignatureMessage *sig) +handle_signature_response(void *cls, + const struct ResponseLocSignatureMessage *sig) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_FileInformation *p; @@ -964,11 +961,11 @@ handle_signature_response (void *cls, /* p->data.loc.fi kept from CHK before */ p->chk_uri->data.loc.peer = sig->peer; p->chk_uri->data.loc.expirationTime - = GNUNET_TIME_absolute_ntoh (sig->expiration_time); + = GNUNET_TIME_absolute_ntoh(sig->expiration_time); p->chk_uri->data.loc.contentSignature = sig->signature; - GNUNET_FS_file_information_sync_ (p); - GNUNET_FS_publish_sync_ (pc); - publish_kblocks (pc); + GNUNET_FS_file_information_sync_(p); + GNUNET_FS_publish_sync_(pc); + publish_kblocks(pc); } @@ -981,19 +978,19 @@ handle_signature_response (void *cls, * @param error error code */ static void -loc_mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +loc_mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_FS_PublishContext *pc = cls; if (NULL != pc->mq) - { - GNUNET_MQ_destroy (pc->mq); - pc->mq = NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Can not create LOC URI. Will continue with CHK instead.\n")); - publish_kblocks (pc); + { + GNUNET_MQ_destroy(pc->mq); + pc->mq = NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Can not create LOC URI. Will continue with CHK instead.\n")); + publish_kblocks(pc); } @@ -1005,42 +1002,42 @@ loc_mq_error_handler (void *cls, * @param pc the publishing context do to this for */ static void -create_loc_uri (struct GNUNET_FS_PublishContext *pc) +create_loc_uri(struct GNUNET_FS_PublishContext *pc) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (signature_response, - GNUNET_MESSAGE_TYPE_FS_REQUEST_LOC_SIGNATURE, - struct ResponseLocSignatureMessage, - pc), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(signature_response, + GNUNET_MESSAGE_TYPE_FS_REQUEST_LOC_SIGNATURE, + struct ResponseLocSignatureMessage, + pc), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *env; struct RequestLocSignatureMessage *req; struct GNUNET_FS_FileInformation *p; if (NULL != pc->mq) - GNUNET_MQ_destroy (pc->mq); - pc->mq = GNUNET_CLIENT_connect (pc->h->cfg, - "fs", - handlers, - &loc_mq_error_handler, - pc); + GNUNET_MQ_destroy(pc->mq); + pc->mq = GNUNET_CLIENT_connect(pc->h->cfg, + "fs", + handlers, + &loc_mq_error_handler, + pc); if (NULL == pc->mq) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Can not create LOC URI. Will continue with CHK instead.\n")); - publish_kblocks (pc); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Can not create LOC URI. Will continue with CHK instead.\n")); + publish_kblocks(pc); + return; + } p = pc->fi_pos; - env = GNUNET_MQ_msg (req, - GNUNET_MESSAGE_TYPE_FS_REQUEST_LOC_SIGN); - req->purpose = htonl (GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT); - req->expiration_time = GNUNET_TIME_absolute_hton (p->bo.expiration_time); + env = GNUNET_MQ_msg(req, + GNUNET_MESSAGE_TYPE_FS_REQUEST_LOC_SIGN); + req->purpose = htonl(GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT); + req->expiration_time = GNUNET_TIME_absolute_hton(p->bo.expiration_time); req->chk = p->chk_uri->data.chk.chk; - req->file_length = GNUNET_htonll (p->chk_uri->data.chk.file_length); - GNUNET_MQ_send (pc->mq, - env); + req->file_length = GNUNET_htonll(p->chk_uri->data.chk.file_length); + GNUNET_MQ_send(pc->mq, + env); } @@ -1050,7 +1047,7 @@ create_loc_uri (struct GNUNET_FS_PublishContext *pc) * @param cls `struct GNUNET_FS_PublishContext *` identifies the upload */ void -GNUNET_FS_publish_main_ (void *cls) +GNUNET_FS_publish_main_(void *cls) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_ProgressInfo pi; @@ -1060,108 +1057,108 @@ GNUNET_FS_publish_main_ (void *cls) pc->upload_task = NULL; p = pc->fi_pos; if (NULL == p) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publishing complete, now publishing SKS and KSK blocks.\n"); - /* upload of entire hierarchy complete, - * publish namespace entries */ - GNUNET_FS_publish_sync_ (pc); - publish_sblock (pc); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publishing complete, now publishing SKS and KSK blocks.\n"); + /* upload of entire hierarchy complete, + * publish namespace entries */ + GNUNET_FS_publish_sync_(pc); + publish_sblock(pc); + return; + } /* find starting position */ - while ( (GNUNET_YES == p->is_directory) && - (NULL != p->data.dir.entries) && - (NULL == p->emsg) && - (NULL == p->data.dir.entries->chk_uri) ) - { - p = p->data.dir.entries; - pc->fi_pos = p; - GNUNET_FS_publish_sync_ (pc); - } + while ((GNUNET_YES == p->is_directory) && + (NULL != p->data.dir.entries) && + (NULL == p->emsg) && + (NULL == p->data.dir.entries->chk_uri)) + { + p = p->data.dir.entries; + pc->fi_pos = p; + GNUNET_FS_publish_sync_(pc); + } /* abort on error */ if (NULL != p->emsg) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Error uploading: %s\n", - p->emsg); - /* error with current file, abort all - * related files as well! */ - while (NULL != p->dir) - { - fn = GNUNET_CONTAINER_meta_data_get_by_type (p->meta, - EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME); - p = p->dir; - if (fn != NULL) - { - GNUNET_asprintf (&p->emsg, - _("Recursive upload failed at `%s': %s"), - fn, - p->emsg); - GNUNET_free (fn); - } - else - { - GNUNET_asprintf (&p->emsg, - _("Recursive upload failed: %s"), - p->emsg); - } - pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR; - pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL; - pi.value.publish.specifics.error.message = p->emsg; - p->client_info = GNUNET_FS_publish_make_status_ (&pi, pc, p, 0); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Error uploading: %s\n", + p->emsg); + /* error with current file, abort all + * related files as well! */ + while (NULL != p->dir) + { + fn = GNUNET_CONTAINER_meta_data_get_by_type(p->meta, + EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME); + p = p->dir; + if (fn != NULL) + { + GNUNET_asprintf(&p->emsg, + _("Recursive upload failed at `%s': %s"), + fn, + p->emsg); + GNUNET_free(fn); + } + else + { + GNUNET_asprintf(&p->emsg, + _("Recursive upload failed: %s"), + p->emsg); + } + pi.status = GNUNET_FS_STATUS_PUBLISH_ERROR; + pi.value.publish.eta = GNUNET_TIME_UNIT_FOREVER_REL; + pi.value.publish.specifics.error.message = p->emsg; + p->client_info = GNUNET_FS_publish_make_status_(&pi, pc, p, 0); + } + pc->all_done = GNUNET_YES; + GNUNET_FS_publish_sync_(pc); + return; } - pc->all_done = GNUNET_YES; - GNUNET_FS_publish_sync_ (pc); - return; - } /* handle completion */ if (NULL != p->chk_uri) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "File upload complete, now publishing KSK blocks.\n"); - GNUNET_FS_publish_sync_ (pc); - - if ( (0 == p->bo.anonymity_level) && - (GNUNET_YES != - GNUNET_FS_uri_test_loc (p->chk_uri)) ) - { - /* zero anonymity, box CHK URI in LOC URI */ - create_loc_uri (pc); - } - else { - publish_kblocks (pc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "File upload complete, now publishing KSK blocks.\n"); + GNUNET_FS_publish_sync_(pc); + + if ((0 == p->bo.anonymity_level) && + (GNUNET_YES != + GNUNET_FS_uri_test_loc(p->chk_uri))) + { + /* zero anonymity, box CHK URI in LOC URI */ + create_loc_uri(pc); + } + else + { + publish_kblocks(pc); + } + return; } - return; - } if ((GNUNET_YES != p->is_directory) && (p->data.file.do_index)) - { - if (NULL == p->filename) { - p->data.file.do_index = GNUNET_NO; - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Can not index file `%s': %s. Will try to insert instead.\n"), - "", - _("needs to be an actual file")); - GNUNET_FS_file_information_sync_ (p); - publish_content (pc); + if (NULL == p->filename) + { + p->data.file.do_index = GNUNET_NO; + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Can not index file `%s': %s. Will try to insert instead.\n"), + "", + _("needs to be an actual file")); + GNUNET_FS_file_information_sync_(p); + publish_content(pc); + return; + } + if (p->data.file.have_hash) + { + hash_for_index_cb(pc, &p->data.file.file_id); + } + else + { + p->start_time = GNUNET_TIME_absolute_get(); + pc->fhc = + GNUNET_CRYPTO_hash_file(GNUNET_SCHEDULER_PRIORITY_IDLE, p->filename, + HASHING_BLOCKSIZE, &hash_for_index_cb, pc); + } return; } - if (p->data.file.have_hash) - { - hash_for_index_cb (pc, &p->data.file.file_id); - } - else - { - p->start_time = GNUNET_TIME_absolute_get (); - pc->fhc = - GNUNET_CRYPTO_hash_file (GNUNET_SCHEDULER_PRIORITY_IDLE, p->filename, - HASHING_BLOCKSIZE, &hash_for_index_cb, pc); - } - return; - } - publish_content (pc); + publish_content(pc); } @@ -1180,14 +1177,14 @@ GNUNET_FS_publish_main_ (void *cls) * @return #GNUNET_OK to continue (always) */ static int -fip_signal_start (void *cls, - struct GNUNET_FS_FileInformation *fi, - uint64_t length, - struct GNUNET_CONTAINER_MetaData *meta, - struct GNUNET_FS_Uri **uri, - struct GNUNET_FS_BlockOptions *bo, - int *do_index, - void **client_info) +fip_signal_start(void *cls, + struct GNUNET_FS_FileInformation *fi, + uint64_t length, + struct GNUNET_CONTAINER_MetaData *meta, + struct GNUNET_FS_Uri **uri, + struct GNUNET_FS_BlockOptions *bo, + int *do_index, + void **client_info) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_ProgressInfo pi; @@ -1195,52 +1192,52 @@ fip_signal_start (void *cls, uint64_t left; if (GNUNET_YES == pc->skip_next_fi_callback) - { - pc->skip_next_fi_callback = GNUNET_NO; - return GNUNET_OK; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting publish operation\n"); + { + pc->skip_next_fi_callback = GNUNET_NO; + return GNUNET_OK; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting publish operation\n"); if (*do_index) - { - /* space for on-demand blocks */ - pc->reserve_space += + { + /* space for on-demand blocks */ + pc->reserve_space += ((length + DBLOCK_SIZE - - 1) / DBLOCK_SIZE) * sizeof (struct OnDemandBlock); - } + 1) / DBLOCK_SIZE) * sizeof(struct OnDemandBlock); + } else - { - /* space for DBlocks */ - pc->reserve_space += length; - } + { + /* space for DBlocks */ + pc->reserve_space += length; + } /* entries for IBlocks and DBlocks, space for IBlocks */ left = length; while (1) - { - left = (left + DBLOCK_SIZE - 1) / DBLOCK_SIZE; - pc->reserve_entries += left; - if (left <= 1) - break; - left = left * sizeof (struct ContentHashKey); - pc->reserve_space += left; - } + { + left = (left + DBLOCK_SIZE - 1) / DBLOCK_SIZE; + pc->reserve_entries += left; + if (left <= 1) + break; + left = left * sizeof(struct ContentHashKey); + pc->reserve_space += left; + } pc->reserve_entries++; /* entries and space for keywords */ if (NULL != *uri) - { - kc = GNUNET_FS_uri_ksk_get_keyword_count (*uri); - pc->reserve_entries += kc; - pc->reserve_space += GNUNET_MAX_MESSAGE_SIZE * kc; - } + { + kc = GNUNET_FS_uri_ksk_get_keyword_count(*uri); + pc->reserve_entries += kc; + pc->reserve_space += GNUNET_MAX_MESSAGE_SIZE * kc; + } pi.status = GNUNET_FS_STATUS_PUBLISH_START; - *client_info = GNUNET_FS_publish_make_status_ (&pi, pc, fi, 0); - GNUNET_FS_file_information_sync_ (fi); + *client_info = GNUNET_FS_publish_make_status_(&pi, pc, fi, 0); + GNUNET_FS_file_information_sync_(fi); if ((fi->is_directory) && (fi->dir != NULL)) - { - /* We are a directory, and we are not top-level; process entries in directory */ - pc->skip_next_fi_callback = GNUNET_YES; - GNUNET_FS_file_information_inspect (fi, &fip_signal_start, pc); - } + { + /* We are a directory, and we are not top-level; process entries in directory */ + pc->skip_next_fi_callback = GNUNET_YES; + GNUNET_FS_file_information_inspect(fi, &fip_signal_start, pc); + } return GNUNET_OK; } @@ -1253,39 +1250,39 @@ fip_signal_start (void *cls, * @param pc the publish context of which a file is being suspended */ static void -suspend_operation (struct GNUNET_FS_FileInformation *fi, - struct GNUNET_FS_PublishContext *pc) +suspend_operation(struct GNUNET_FS_FileInformation *fi, + struct GNUNET_FS_PublishContext *pc) { struct GNUNET_FS_ProgressInfo pi; uint64_t off; if (NULL != pc->ksk_pc) - { - GNUNET_FS_publish_ksk_cancel (pc->ksk_pc); - pc->ksk_pc = NULL; - } + { + GNUNET_FS_publish_ksk_cancel(pc->ksk_pc); + pc->ksk_pc = NULL; + } if (NULL != pc->sks_pc) - { - GNUNET_FS_publish_sks_cancel (pc->sks_pc); - pc->sks_pc = NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Suspending publish operation\n"); - GNUNET_free_non_null (fi->serialization); + { + GNUNET_FS_publish_sks_cancel(pc->sks_pc); + pc->sks_pc = NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Suspending publish operation\n"); + GNUNET_free_non_null(fi->serialization); fi->serialization = NULL; off = (NULL == fi->chk_uri) ? 0 : (GNUNET_YES == fi->is_directory) ? fi->data.dir.dir_size : fi->data.file.file_size; pi.status = GNUNET_FS_STATUS_PUBLISH_SUSPEND; - GNUNET_break (NULL == GNUNET_FS_publish_make_status_ (&pi, pc, fi, off)); + GNUNET_break(NULL == GNUNET_FS_publish_make_status_(&pi, pc, fi, off)); if (NULL != pc->qre) - { - GNUNET_DATASTORE_cancel (pc->qre); - pc->qre = NULL; - } + { + GNUNET_DATASTORE_cancel(pc->qre); + pc->qre = NULL; + } if (NULL != pc->dsh) - { - GNUNET_DATASTORE_disconnect (pc->dsh, GNUNET_NO); - pc->dsh = NULL; - } + { + GNUNET_DATASTORE_disconnect(pc->dsh, GNUNET_NO); + pc->dsh = NULL; + } pc->rid = 0; } @@ -1305,29 +1302,29 @@ suspend_operation (struct GNUNET_FS_FileInformation *fi, * @return #GNUNET_OK to continue (always) */ static int -fip_signal_suspend (void *cls, - struct GNUNET_FS_FileInformation *fi, - uint64_t length, - struct GNUNET_CONTAINER_MetaData *meta, - struct GNUNET_FS_Uri **uri, - struct GNUNET_FS_BlockOptions *bo, - int *do_index, - void **client_info) +fip_signal_suspend(void *cls, + struct GNUNET_FS_FileInformation *fi, + uint64_t length, + struct GNUNET_CONTAINER_MetaData *meta, + struct GNUNET_FS_Uri **uri, + struct GNUNET_FS_BlockOptions *bo, + int *do_index, + void **client_info) { struct GNUNET_FS_PublishContext *pc = cls; if (GNUNET_YES == pc->skip_next_fi_callback) - { - pc->skip_next_fi_callback = GNUNET_NO; - return GNUNET_OK; - } - if (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) - { - /* process entries in directory */ - pc->skip_next_fi_callback = GNUNET_YES; - GNUNET_FS_file_information_inspect (fi, &fip_signal_suspend, pc); - } - suspend_operation (fi, pc); + { + pc->skip_next_fi_callback = GNUNET_NO; + return GNUNET_OK; + } + if (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory(meta)) + { + /* process entries in directory */ + pc->skip_next_fi_callback = GNUNET_YES; + GNUNET_FS_file_information_inspect(fi, &fip_signal_suspend, pc); + } + suspend_operation(fi, pc); *client_info = NULL; return GNUNET_OK; } @@ -1340,21 +1337,21 @@ fip_signal_suspend (void *cls, * @param cls the `struct GNUNET_FS_PublishContext` to signal for */ void -GNUNET_FS_publish_signal_suspend_ (void *cls) +GNUNET_FS_publish_signal_suspend_(void *cls) { struct GNUNET_FS_PublishContext *pc = cls; if (NULL != pc->upload_task) - { - GNUNET_SCHEDULER_cancel (pc->upload_task); - pc->upload_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(pc->upload_task); + pc->upload_task = NULL; + } pc->skip_next_fi_callback = GNUNET_YES; - GNUNET_FS_file_information_inspect (pc->fi, &fip_signal_suspend, pc); - suspend_operation (pc->fi, pc); - GNUNET_FS_end_top (pc->h, pc->top); + GNUNET_FS_file_information_inspect(pc->fi, &fip_signal_suspend, pc); + suspend_operation(pc->fi, pc); + GNUNET_FS_end_top(pc->h, pc->top); pc->top = NULL; - publish_cleanup (pc); + publish_cleanup(pc); } @@ -1368,30 +1365,30 @@ GNUNET_FS_publish_signal_suspend_ (void *cls) * @param msg error message on error, otherwise NULL */ static void -finish_reserve (void *cls, - int success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +finish_reserve(void *cls, + int success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct GNUNET_FS_PublishContext *pc = cls; pc->qre = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Reservation complete (%d)!\n", - success); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Reservation complete (%d)!\n", + success); if ((msg != NULL) || (success <= 0)) - { - GNUNET_asprintf (&pc->fi->emsg, - _("Datastore failure: %s"), - msg); - signal_publish_error (pc->fi, pc, pc->fi->emsg); - return; - } + { + GNUNET_asprintf(&pc->fi->emsg, + _("Datastore failure: %s"), + msg); + signal_publish_error(pc->fi, pc, pc->fi->emsg); + return; + } pc->rid = success; - GNUNET_assert (NULL == pc->upload_task); + GNUNET_assert(NULL == pc->upload_task); pc->upload_task = - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, - &GNUNET_FS_publish_main_, pc); + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_BACKGROUND, + &GNUNET_FS_publish_main_, pc); } @@ -1401,7 +1398,7 @@ finish_reserve (void *cls, * @param fi file structure to traverse */ static uint64_t -compute_contents_size (struct GNUNET_FS_FileInformation *fi) +compute_contents_size(struct GNUNET_FS_FileInformation *fi) { struct GNUNET_FS_FileInformation *ent; @@ -1409,7 +1406,7 @@ compute_contents_size (struct GNUNET_FS_FileInformation *fi) return fi->data.file.file_size; fi->data.dir.contents_size = 0; for (ent = fi->data.dir.entries; NULL != ent; ent = ent->next) - fi->data.dir.contents_size += compute_contents_size (ent); + fi->data.dir.contents_size += compute_contents_size(ent); return fi->data.dir.contents_size; } @@ -1428,67 +1425,67 @@ compute_contents_size (struct GNUNET_FS_FileInformation *fi) * @return context that can be used to control the publish operation */ struct GNUNET_FS_PublishContext * -GNUNET_FS_publish_start (struct GNUNET_FS_Handle *h, - struct GNUNET_FS_FileInformation *fi, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, - const char *nid, - const char *nuid, - enum GNUNET_FS_PublishOptions options) +GNUNET_FS_publish_start(struct GNUNET_FS_Handle *h, + struct GNUNET_FS_FileInformation *fi, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, + const char *nid, + const char *nuid, + enum GNUNET_FS_PublishOptions options) { struct GNUNET_FS_PublishContext *ret; struct GNUNET_DATASTORE_Handle *dsh; - GNUNET_assert (NULL != h); - compute_contents_size (fi); + GNUNET_assert(NULL != h); + compute_contents_size(fi); if (0 == (options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY)) - { - dsh = GNUNET_DATASTORE_connect (h->cfg); - if (NULL == dsh) - return NULL; - } + { + dsh = GNUNET_DATASTORE_connect(h->cfg); + if (NULL == dsh) + return NULL; + } else - { - dsh = NULL; - } - ret = GNUNET_new (struct GNUNET_FS_PublishContext); + { + dsh = NULL; + } + ret = GNUNET_new(struct GNUNET_FS_PublishContext); ret->dsh = dsh; ret->h = h; ret->fi = fi; if (NULL != ns) - { - ret->ns = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPrivateKey); - *ret->ns = *ns; - GNUNET_assert (NULL != nid); - ret->nid = GNUNET_strdup (nid); - if (NULL != nuid) - ret->nuid = GNUNET_strdup (nuid); - } + { + ret->ns = GNUNET_new(struct GNUNET_CRYPTO_EcdsaPrivateKey); + *ret->ns = *ns; + GNUNET_assert(NULL != nid); + ret->nid = GNUNET_strdup(nid); + if (NULL != nuid) + ret->nuid = GNUNET_strdup(nuid); + } ret->options = options; /* signal start */ - GNUNET_FS_file_information_inspect (ret->fi, &fip_signal_start, ret); + GNUNET_FS_file_information_inspect(ret->fi, &fip_signal_start, ret); ret->fi_pos = ret->fi; - ret->top = GNUNET_FS_make_top (h, &GNUNET_FS_publish_signal_suspend_, ret); - GNUNET_FS_publish_sync_ (ret); + ret->top = GNUNET_FS_make_top(h, &GNUNET_FS_publish_signal_suspend_, ret); + GNUNET_FS_publish_sync_(ret); if (NULL != ret->dsh) - { - GNUNET_assert (NULL == ret->qre); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Reserving space for %u entries and %llu bytes for publication\n"), - (unsigned int) ret->reserve_entries, - (unsigned long long) ret->reserve_space); - ret->qre = - GNUNET_DATASTORE_reserve (ret->dsh, ret->reserve_space, - ret->reserve_entries, - &finish_reserve, - ret); - } + { + GNUNET_assert(NULL == ret->qre); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Reserving space for %u entries and %llu bytes for publication\n"), + (unsigned int)ret->reserve_entries, + (unsigned long long)ret->reserve_space); + ret->qre = + GNUNET_DATASTORE_reserve(ret->dsh, ret->reserve_space, + ret->reserve_entries, + &finish_reserve, + ret); + } else - { - GNUNET_assert (NULL == ret->upload_task); - ret->upload_task = + { + GNUNET_assert(NULL == ret->upload_task); + ret->upload_task = GNUNET_SCHEDULER_add_with_priority - (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, &GNUNET_FS_publish_main_, ret); - } + (GNUNET_SCHEDULER_PRIORITY_BACKGROUND, &GNUNET_FS_publish_main_, ret); + } return ret; } @@ -1508,39 +1505,39 @@ GNUNET_FS_publish_start (struct GNUNET_FS_Handle *h, * @return #GNUNET_OK to continue (always) */ static int -fip_signal_stop (void *cls, - struct GNUNET_FS_FileInformation *fi, - uint64_t length, - struct GNUNET_CONTAINER_MetaData *meta, - struct GNUNET_FS_Uri **uri, - struct GNUNET_FS_BlockOptions *bo, - int *do_index, void **client_info) +fip_signal_stop(void *cls, + struct GNUNET_FS_FileInformation *fi, + uint64_t length, + struct GNUNET_CONTAINER_MetaData *meta, + struct GNUNET_FS_Uri **uri, + struct GNUNET_FS_BlockOptions *bo, + int *do_index, void **client_info) { struct GNUNET_FS_PublishContext *pc = cls; struct GNUNET_FS_ProgressInfo pi; uint64_t off; if (GNUNET_YES == pc->skip_next_fi_callback) - { - pc->skip_next_fi_callback = GNUNET_NO; - return GNUNET_OK; - } - if (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (meta)) - { - /* process entries in directory first */ - pc->skip_next_fi_callback = GNUNET_YES; - GNUNET_FS_file_information_inspect (fi, &fip_signal_stop, pc); - } + { + pc->skip_next_fi_callback = GNUNET_NO; + return GNUNET_OK; + } + if (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory(meta)) + { + /* process entries in directory first */ + pc->skip_next_fi_callback = GNUNET_YES; + GNUNET_FS_file_information_inspect(fi, &fip_signal_stop, pc); + } if (NULL != fi->serialization) - { - GNUNET_FS_remove_sync_file_ (pc->h, GNUNET_FS_SYNC_PATH_FILE_INFO, - fi->serialization); - GNUNET_free (fi->serialization); - fi->serialization = NULL; - } + { + GNUNET_FS_remove_sync_file_(pc->h, GNUNET_FS_SYNC_PATH_FILE_INFO, + fi->serialization); + GNUNET_free(fi->serialization); + fi->serialization = NULL; + } off = (fi->chk_uri == NULL) ? 0 : length; pi.status = GNUNET_FS_STATUS_PUBLISH_STOPPED; - GNUNET_break (NULL == GNUNET_FS_publish_make_status_ (&pi, pc, fi, off)); + GNUNET_break(NULL == GNUNET_FS_publish_make_status_(&pi, pc, fi, off)); *client_info = NULL; return GNUNET_OK; } @@ -1555,56 +1552,56 @@ fip_signal_stop (void *cls, * @param pc context for the upload to stop */ void -GNUNET_FS_publish_stop (struct GNUNET_FS_PublishContext *pc) +GNUNET_FS_publish_stop(struct GNUNET_FS_PublishContext *pc) { struct GNUNET_FS_ProgressInfo pi; uint64_t off; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publish stop called\n"); - GNUNET_FS_end_top (pc->h, pc->top); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publish stop called\n"); + GNUNET_FS_end_top(pc->h, pc->top); if (NULL != pc->ksk_pc) - { - GNUNET_FS_publish_ksk_cancel (pc->ksk_pc); - pc->ksk_pc = NULL; - } + { + GNUNET_FS_publish_ksk_cancel(pc->ksk_pc); + pc->ksk_pc = NULL; + } if (NULL != pc->sks_pc) - { - GNUNET_FS_publish_sks_cancel (pc->sks_pc); - pc->sks_pc = NULL; - } + { + GNUNET_FS_publish_sks_cancel(pc->sks_pc); + pc->sks_pc = NULL; + } if (NULL != pc->upload_task) - { - GNUNET_SCHEDULER_cancel (pc->upload_task); - pc->upload_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(pc->upload_task); + pc->upload_task = NULL; + } pc->skip_next_fi_callback = GNUNET_YES; - GNUNET_FS_file_information_inspect (pc->fi, &fip_signal_stop, pc); + GNUNET_FS_file_information_inspect(pc->fi, &fip_signal_stop, pc); if (NULL != pc->fi->serialization) - { - GNUNET_FS_remove_sync_file_ (pc->h, GNUNET_FS_SYNC_PATH_FILE_INFO, - pc->fi->serialization); - GNUNET_free (pc->fi->serialization); - pc->fi->serialization = NULL; - } - off = (NULL == pc->fi->chk_uri) ? 0 : GNUNET_ntohll (pc->fi->chk_uri->data.chk.file_length); + { + GNUNET_FS_remove_sync_file_(pc->h, GNUNET_FS_SYNC_PATH_FILE_INFO, + pc->fi->serialization); + GNUNET_free(pc->fi->serialization); + pc->fi->serialization = NULL; + } + off = (NULL == pc->fi->chk_uri) ? 0 : GNUNET_ntohll(pc->fi->chk_uri->data.chk.file_length); if (NULL != pc->serialization) - { - GNUNET_FS_remove_sync_file_ (pc->h, GNUNET_FS_SYNC_PATH_MASTER_PUBLISH, - pc->serialization); - GNUNET_free (pc->serialization); - pc->serialization = NULL; - } + { + GNUNET_FS_remove_sync_file_(pc->h, GNUNET_FS_SYNC_PATH_MASTER_PUBLISH, + pc->serialization); + GNUNET_free(pc->serialization); + pc->serialization = NULL; + } if (NULL != pc->qre) - { - GNUNET_DATASTORE_cancel (pc->qre); - pc->qre = NULL; - } + { + GNUNET_DATASTORE_cancel(pc->qre); + pc->qre = NULL; + } pi.status = GNUNET_FS_STATUS_PUBLISH_STOPPED; - GNUNET_break (NULL == GNUNET_FS_publish_make_status_ (&pi, pc, pc->fi, off)); - publish_cleanup (pc); + GNUNET_break(NULL == GNUNET_FS_publish_make_status_(&pi, pc, pc->fi, off)); + publish_cleanup(pc); } diff --git a/src/fs/fs_publish_ksk.c b/src/fs/fs_publish_ksk.c index e7f6408fd..151b8256c 100644 --- a/src/fs/fs_publish_ksk.c +++ b/src/fs/fs_publish_ksk.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_publish_ksk.c @@ -38,9 +38,7 @@ /** * Context for the KSK publication. */ -struct GNUNET_FS_PublishKskContext -{ - +struct GNUNET_FS_PublishKskContext { /** * Keywords to use. */ @@ -100,7 +98,6 @@ struct GNUNET_FS_PublishKskContext * Keyword that we are currently processing. */ unsigned int i; - }; @@ -112,7 +109,7 @@ struct GNUNET_FS_PublishKskContext * @param cls closure of type `struct PublishKskContext *` */ static void -publish_ksk_cont (void *cls); +publish_ksk_cont(void *cls); /** @@ -123,21 +120,21 @@ publish_ksk_cont (void *cls); * @param msg error message (or NULL) */ static void -kb_put_cont (void *cls, - const char *msg) +kb_put_cont(void *cls, + const char *msg) { struct GNUNET_FS_PublishKskContext *pkc = cls; pkc->uc = NULL; if (NULL != msg) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "KBlock PUT operation failed: %s\n", msg); - pkc->cont (pkc->cont_cls, NULL, msg); - GNUNET_FS_publish_ksk_cancel (pkc); - return; - } - pkc->ksk_task = GNUNET_SCHEDULER_add_now (&publish_ksk_cont, pkc); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "KBlock PUT operation failed: %s\n", msg); + pkc->cont(pkc->cont_cls, NULL, msg); + GNUNET_FS_publish_ksk_cancel(pkc); + return; + } + pkc->ksk_task = GNUNET_SCHEDULER_add_now(&publish_ksk_cont, pkc); } @@ -148,33 +145,33 @@ kb_put_cont (void *cls, * @param cls closure of type `struct GNUNET_FS_PublishKskContext *` */ static void -publish_ksk_cont (void *cls) +publish_ksk_cont(void *cls) { struct GNUNET_FS_PublishKskContext *pkc = cls; const char *keyword; pkc->ksk_task = NULL; - if ( (pkc->i == pkc->ksk_uri->data.ksk.keywordCount) || - (NULL == pkc->dsh) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "KSK PUT operation complete\n"); - pkc->cont (pkc->cont_cls, pkc->ksk_uri, - NULL); - GNUNET_FS_publish_ksk_cancel (pkc); - return; - } + if ((pkc->i == pkc->ksk_uri->data.ksk.keywordCount) || + (NULL == pkc->dsh)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "KSK PUT operation complete\n"); + pkc->cont(pkc->cont_cls, pkc->ksk_uri, + NULL); + GNUNET_FS_publish_ksk_cancel(pkc); + return; + } keyword = pkc->ksk_uri->data.ksk.keywords[pkc->i++]; - pkc->uc = GNUNET_FS_publish_ublock_ (pkc->h, - pkc->dsh, - keyword + 1 /* skip '+' */, - NULL, - GNUNET_CRYPTO_ecdsa_key_get_anonymous (), - pkc->meta, - pkc->uri, - &pkc->bo, - pkc->options, - &kb_put_cont, pkc); + pkc->uc = GNUNET_FS_publish_ublock_(pkc->h, + pkc->dsh, + keyword + 1 /* skip '+' */, + NULL, + GNUNET_CRYPTO_ecdsa_key_get_anonymous(), + pkc->meta, + pkc->uri, + &pkc->bo, + pkc->options, + &kb_put_cont, pkc); } @@ -192,39 +189,39 @@ publish_ksk_cont (void *cls) * @return NULL on error ('cont' will still be called) */ struct GNUNET_FS_PublishKskContext * -GNUNET_FS_publish_ksk (struct GNUNET_FS_Handle *h, - const struct GNUNET_FS_Uri *ksk_uri, - const struct GNUNET_CONTAINER_MetaData *meta, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_FS_BlockOptions *bo, - enum GNUNET_FS_PublishOptions options, - GNUNET_FS_PublishContinuation cont, void *cont_cls) +GNUNET_FS_publish_ksk(struct GNUNET_FS_Handle *h, + const struct GNUNET_FS_Uri *ksk_uri, + const struct GNUNET_CONTAINER_MetaData *meta, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_FS_BlockOptions *bo, + enum GNUNET_FS_PublishOptions options, + GNUNET_FS_PublishContinuation cont, void *cont_cls) { struct GNUNET_FS_PublishKskContext *pkc; - GNUNET_assert (NULL != uri); - pkc = GNUNET_new (struct GNUNET_FS_PublishKskContext); + GNUNET_assert(NULL != uri); + pkc = GNUNET_new(struct GNUNET_FS_PublishKskContext); pkc->h = h; pkc->bo = *bo; pkc->options = options; pkc->cont = cont; pkc->cont_cls = cont_cls; - pkc->meta = GNUNET_CONTAINER_meta_data_duplicate (meta); + pkc->meta = GNUNET_CONTAINER_meta_data_duplicate(meta); if (0 == (options & GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY)) - { - pkc->dsh = GNUNET_DATASTORE_connect (h->cfg); - if (NULL == pkc->dsh) { - cont (cont_cls, - NULL, - _("Could not connect to datastore.")); - GNUNET_free (pkc); - return NULL; + pkc->dsh = GNUNET_DATASTORE_connect(h->cfg); + if (NULL == pkc->dsh) + { + cont(cont_cls, + NULL, + _("Could not connect to datastore.")); + GNUNET_free(pkc); + return NULL; + } } - } - pkc->uri = GNUNET_FS_uri_dup (uri); - pkc->ksk_uri = GNUNET_FS_uri_dup (ksk_uri); - pkc->ksk_task = GNUNET_SCHEDULER_add_now (&publish_ksk_cont, pkc); + pkc->uri = GNUNET_FS_uri_dup(uri); + pkc->ksk_uri = GNUNET_FS_uri_dup(ksk_uri); + pkc->ksk_task = GNUNET_SCHEDULER_add_now(&publish_ksk_cont, pkc); return pkc; } @@ -235,27 +232,27 @@ GNUNET_FS_publish_ksk (struct GNUNET_FS_Handle *h, * @param pkc context of the operation to abort. */ void -GNUNET_FS_publish_ksk_cancel (struct GNUNET_FS_PublishKskContext *pkc) +GNUNET_FS_publish_ksk_cancel(struct GNUNET_FS_PublishKskContext *pkc) { if (NULL != pkc->ksk_task) - { - GNUNET_SCHEDULER_cancel (pkc->ksk_task); - pkc->ksk_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(pkc->ksk_task); + pkc->ksk_task = NULL; + } if (NULL != pkc->uc) - { - GNUNET_FS_publish_ublock_cancel_ (pkc->uc); - pkc->uc = NULL; - } + { + GNUNET_FS_publish_ublock_cancel_(pkc->uc); + pkc->uc = NULL; + } if (NULL != pkc->dsh) - { - GNUNET_DATASTORE_disconnect (pkc->dsh, GNUNET_NO); - pkc->dsh = NULL; - } - GNUNET_CONTAINER_meta_data_destroy (pkc->meta); - GNUNET_FS_uri_destroy (pkc->ksk_uri); - GNUNET_FS_uri_destroy (pkc->uri); - GNUNET_free (pkc); + { + GNUNET_DATASTORE_disconnect(pkc->dsh, GNUNET_NO); + pkc->dsh = NULL; + } + GNUNET_CONTAINER_meta_data_destroy(pkc->meta); + GNUNET_FS_uri_destroy(pkc->ksk_uri); + GNUNET_FS_uri_destroy(pkc->uri); + GNUNET_free(pkc); } diff --git a/src/fs/fs_publish_ublock.c b/src/fs/fs_publish_ublock.c index 368a4aff4..4dfb4a585 100644 --- a/src/fs/fs_publish_ublock.c +++ b/src/fs/fs_publish_ublock.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_publish_ublock.c @@ -43,21 +43,21 @@ * @param pub public key to use for key derivation */ static void -derive_ublock_encryption_key (struct GNUNET_CRYPTO_SymmetricSessionKey *skey, - struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, - const char *label, - const struct GNUNET_CRYPTO_EcdsaPublicKey *pub) +derive_ublock_encryption_key(struct GNUNET_CRYPTO_SymmetricSessionKey *skey, + struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, + const char *label, + const struct GNUNET_CRYPTO_EcdsaPublicKey *pub) { struct GNUNET_HashCode key; /* derive key from 'label' and public key of the namespace */ - GNUNET_assert (GNUNET_YES == - GNUNET_CRYPTO_kdf (&key, sizeof (key), - "UBLOCK-ENC", strlen ("UBLOCK-ENC"), - label, strlen (label), - pub, sizeof (*pub), - NULL, 0)); - GNUNET_CRYPTO_hash_to_aes_key (&key, skey, iv); + GNUNET_assert(GNUNET_YES == + GNUNET_CRYPTO_kdf(&key, sizeof(key), + "UBLOCK-ENC", strlen("UBLOCK-ENC"), + label, strlen(label), + pub, sizeof(*pub), + NULL, 0)); + GNUNET_CRYPTO_hash_to_aes_key(&key, skey, iv); } @@ -71,29 +71,27 @@ derive_ublock_encryption_key (struct GNUNET_CRYPTO_SymmetricSessionKey *skey, * @param output where to write the result, has input_len bytes */ void -GNUNET_FS_ublock_decrypt_ (const void *input, - size_t input_len, - const struct GNUNET_CRYPTO_EcdsaPublicKey *ns, - const char *label, - void *output) +GNUNET_FS_ublock_decrypt_(const void *input, + size_t input_len, + const struct GNUNET_CRYPTO_EcdsaPublicKey *ns, + const char *label, + void *output) { struct GNUNET_CRYPTO_SymmetricInitializationVector iv; struct GNUNET_CRYPTO_SymmetricSessionKey skey; - derive_ublock_encryption_key (&skey, &iv, - label, ns); - GNUNET_CRYPTO_symmetric_decrypt (input, input_len, - &skey, &iv, - output); + derive_ublock_encryption_key(&skey, &iv, + label, ns); + GNUNET_CRYPTO_symmetric_decrypt(input, input_len, + &skey, &iv, + output); } /** * Context for 'ublock_put_cont'. */ -struct GNUNET_FS_PublishUblockContext -{ - +struct GNUNET_FS_PublishUblockContext { /** * Function to call when done. */ @@ -113,7 +111,6 @@ struct GNUNET_FS_PublishUblockContext * Task to run continuation asynchronously. */ struct GNUNET_SCHEDULER_Task * task; - }; @@ -130,16 +127,16 @@ struct GNUNET_FS_PublishUblockContext * @param msg NULL on success, otherwise an error message */ static void -ublock_put_cont (void *cls, - int32_t success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +ublock_put_cont(void *cls, + int32_t success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct GNUNET_FS_PublishUblockContext *uc = cls; uc->qre = NULL; - uc->cont (uc->cont_cls, msg); - GNUNET_free (uc); + uc->cont(uc->cont_cls, msg); + GNUNET_free(uc); } @@ -149,13 +146,13 @@ ublock_put_cont (void *cls, * @param cls the `struct GNUNET_FS_PublishUblockContext *` */ static void -run_cont (void *cls) +run_cont(void *cls) { struct GNUNET_FS_PublishUblockContext *uc = cls; uc->task = NULL; - uc->cont (uc->cont_cls, NULL); - GNUNET_free (uc); + uc->cont(uc->cont_cls, NULL); + GNUNET_free(uc); } @@ -176,16 +173,16 @@ run_cont (void *cls) * @return NULL on error (@a cont will still be called) */ struct GNUNET_FS_PublishUblockContext * -GNUNET_FS_publish_ublock_ (struct GNUNET_FS_Handle *h, - struct GNUNET_DATASTORE_Handle *dsh, - const char *label, - const char *ulabel, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, - const struct GNUNET_CONTAINER_MetaData *meta, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_FS_BlockOptions *bo, - enum GNUNET_FS_PublishOptions options, - GNUNET_FS_UBlockContinuation cont, void *cont_cls) +GNUNET_FS_publish_ublock_(struct GNUNET_FS_Handle *h, + struct GNUNET_DATASTORE_Handle *dsh, + const char *label, + const char *ulabel, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, + const struct GNUNET_CONTAINER_MetaData *meta, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_FS_BlockOptions *bo, + enum GNUNET_FS_PublishOptions options, + GNUNET_FS_UBlockContinuation cont, void *cont_cls) { struct GNUNET_FS_PublishUblockContext *uc; struct GNUNET_HashCode query; @@ -207,101 +204,101 @@ GNUNET_FS_publish_ublock_ (struct GNUNET_FS_Handle *h, if (NULL == meta) mdsize = 0; else - mdsize = GNUNET_CONTAINER_meta_data_get_serialized_size (meta); - GNUNET_assert (mdsize >= 0); - uris = GNUNET_FS_uri_to_string (uri); - slen = strlen (uris) + 1; + mdsize = GNUNET_CONTAINER_meta_data_get_serialized_size(meta); + GNUNET_assert(mdsize >= 0); + uris = GNUNET_FS_uri_to_string(uri); + slen = strlen(uris) + 1; if (NULL == ulabel) ulen = 1; else - ulen = strlen (ulabel) + 1; - size = mdsize + sizeof (struct UBlock) + slen + ulen; + ulen = strlen(ulabel) + 1; + size = mdsize + sizeof(struct UBlock) + slen + ulen; if (size > MAX_UBLOCK_SIZE) - { - size = MAX_UBLOCK_SIZE; - mdsize = size - sizeof (struct UBlock) - (slen + ulen); - } - ub_plain = GNUNET_malloc (size); - kbe = (char *) &ub_plain[1]; + { + size = MAX_UBLOCK_SIZE; + mdsize = size - sizeof(struct UBlock) - (slen + ulen); + } + ub_plain = GNUNET_malloc(size); + kbe = (char *)&ub_plain[1]; if (NULL != ulabel) - GNUNET_memcpy (kbe, ulabel, ulen); + GNUNET_memcpy(kbe, ulabel, ulen); kbe += ulen; - GNUNET_memcpy (kbe, uris, slen); + GNUNET_memcpy(kbe, uris, slen); kbe += slen; - GNUNET_free (uris); + GNUNET_free(uris); sptr = kbe; if (NULL != meta) mdsize = - GNUNET_CONTAINER_meta_data_serialize (meta, &sptr, mdsize, - GNUNET_CONTAINER_META_DATA_SERIALIZE_PART); + GNUNET_CONTAINER_meta_data_serialize(meta, &sptr, mdsize, + GNUNET_CONTAINER_META_DATA_SERIALIZE_PART); if (-1 == mdsize) - { - GNUNET_break (0); - GNUNET_free (ub_plain); - cont (cont_cls, _("Internal error.")); - return NULL; - } - size = sizeof (struct UBlock) + slen + mdsize + ulen; - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publishing under identifier `%s'\n", - label); + { + GNUNET_break(0); + GNUNET_free(ub_plain); + cont(cont_cls, _("Internal error.")); + return NULL; + } + size = sizeof(struct UBlock) + slen + mdsize + ulen; + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publishing under identifier `%s'\n", + label); /* get public key of the namespace */ - GNUNET_CRYPTO_ecdsa_key_get_public (ns, - &pub); - derive_ublock_encryption_key (&skey, &iv, - label, &pub); + GNUNET_CRYPTO_ecdsa_key_get_public(ns, + &pub); + derive_ublock_encryption_key(&skey, &iv, + label, &pub); /* encrypt ublock */ - ub_enc = GNUNET_malloc (size); - GNUNET_CRYPTO_symmetric_encrypt (&ub_plain[1], - ulen + slen + mdsize, - &skey, &iv, - &ub_enc[1]); - GNUNET_free (ub_plain); - ub_enc->purpose.size = htonl (ulen + slen + mdsize + - sizeof (struct UBlock) - - sizeof (struct GNUNET_CRYPTO_EcdsaSignature)); - ub_enc->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_FS_UBLOCK); + ub_enc = GNUNET_malloc(size); + GNUNET_CRYPTO_symmetric_encrypt(&ub_plain[1], + ulen + slen + mdsize, + &skey, &iv, + &ub_enc[1]); + GNUNET_free(ub_plain); + ub_enc->purpose.size = htonl(ulen + slen + mdsize + + sizeof(struct UBlock) + - sizeof(struct GNUNET_CRYPTO_EcdsaSignature)); + ub_enc->purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_FS_UBLOCK); /* derive signing-key from 'label' and public key of the namespace */ - nsd = GNUNET_CRYPTO_ecdsa_private_key_derive (ns, label, "fs-ublock"); - GNUNET_CRYPTO_ecdsa_key_get_public (nsd, - &ub_enc->verification_key); - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_ecdsa_sign (nsd, - &ub_enc->purpose, - &ub_enc->signature)); - GNUNET_CRYPTO_hash (&ub_enc->verification_key, - sizeof (ub_enc->verification_key), - &query); - GNUNET_free (nsd); - - uc = GNUNET_new (struct GNUNET_FS_PublishUblockContext); + nsd = GNUNET_CRYPTO_ecdsa_private_key_derive(ns, label, "fs-ublock"); + GNUNET_CRYPTO_ecdsa_key_get_public(nsd, + &ub_enc->verification_key); + GNUNET_assert(GNUNET_OK == + GNUNET_CRYPTO_ecdsa_sign(nsd, + &ub_enc->purpose, + &ub_enc->signature)); + GNUNET_CRYPTO_hash(&ub_enc->verification_key, + sizeof(ub_enc->verification_key), + &query); + GNUNET_free(nsd); + + uc = GNUNET_new(struct GNUNET_FS_PublishUblockContext); uc->cont = cont; uc->cont_cls = cont_cls; if (NULL != dsh) - { - uc->qre = - GNUNET_DATASTORE_put (dsh, - 0, - &query, - ulen + slen + mdsize + sizeof (struct UBlock), - ub_enc, - GNUNET_BLOCK_TYPE_FS_UBLOCK, - bo->content_priority, - bo->anonymity_level, - bo->replication_level, - bo->expiration_time, - -2, 1, - &ublock_put_cont, uc); - } + { + uc->qre = + GNUNET_DATASTORE_put(dsh, + 0, + &query, + ulen + slen + mdsize + sizeof(struct UBlock), + ub_enc, + GNUNET_BLOCK_TYPE_FS_UBLOCK, + bo->content_priority, + bo->anonymity_level, + bo->replication_level, + bo->expiration_time, + -2, 1, + &ublock_put_cont, uc); + } else - { - uc->task = GNUNET_SCHEDULER_add_now (&run_cont, - uc); - } - GNUNET_free (ub_enc); + { + uc->task = GNUNET_SCHEDULER_add_now(&run_cont, + uc); + } + GNUNET_free(ub_enc); return uc; } @@ -312,13 +309,13 @@ GNUNET_FS_publish_ublock_ (struct GNUNET_FS_Handle *h, * @param uc operation to abort. */ void -GNUNET_FS_publish_ublock_cancel_ (struct GNUNET_FS_PublishUblockContext *uc) +GNUNET_FS_publish_ublock_cancel_(struct GNUNET_FS_PublishUblockContext *uc) { if (NULL != uc->qre) - GNUNET_DATASTORE_cancel (uc->qre); + GNUNET_DATASTORE_cancel(uc->qre); if (NULL != uc->task) - GNUNET_SCHEDULER_cancel (uc->task); - GNUNET_free (uc); + GNUNET_SCHEDULER_cancel(uc->task); + GNUNET_free(uc); } /* end of fs_publish_ublock.c */ diff --git a/src/fs/fs_publish_ublock.h b/src/fs/fs_publish_ublock.h index ad07e5f6f..9d0a518c6 100644 --- a/src/fs/fs_publish_ublock.h +++ b/src/fs/fs_publish_ublock.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_publish_ublock.h @@ -44,11 +44,11 @@ * @param output where to write the result, has input_len bytes */ void -GNUNET_FS_ublock_decrypt_ (const void *input, - size_t input_len, - const struct GNUNET_CRYPTO_EcdsaPublicKey *ns, - const char *label, - void *output); +GNUNET_FS_ublock_decrypt_(const void *input, + size_t input_len, + const struct GNUNET_CRYPTO_EcdsaPublicKey *ns, + const char *label, + void *output); /** @@ -65,7 +65,7 @@ struct GNUNET_FS_PublishUblockContext; * @param emsg error message, NULL on success */ typedef void (*GNUNET_FS_UBlockContinuation) (void *cls, - const char *emsg); + const char *emsg); /** @@ -85,16 +85,16 @@ typedef void (*GNUNET_FS_UBlockContinuation) (void *cls, * @return NULL on error ('cont' will still be called) */ struct GNUNET_FS_PublishUblockContext * -GNUNET_FS_publish_ublock_ (struct GNUNET_FS_Handle *h, - struct GNUNET_DATASTORE_Handle *dsh, - const char *label, - const char *ulabel, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, - const struct GNUNET_CONTAINER_MetaData *meta, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_FS_BlockOptions *bo, - enum GNUNET_FS_PublishOptions options, - GNUNET_FS_UBlockContinuation cont, void *cont_cls); +GNUNET_FS_publish_ublock_(struct GNUNET_FS_Handle *h, + struct GNUNET_DATASTORE_Handle *dsh, + const char *label, + const char *ulabel, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, + const struct GNUNET_CONTAINER_MetaData *meta, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_FS_BlockOptions *bo, + enum GNUNET_FS_PublishOptions options, + GNUNET_FS_UBlockContinuation cont, void *cont_cls); /** @@ -103,6 +103,6 @@ GNUNET_FS_publish_ublock_ (struct GNUNET_FS_Handle *h, * @param uc operation to abort. */ void -GNUNET_FS_publish_ublock_cancel_ (struct GNUNET_FS_PublishUblockContext *uc); +GNUNET_FS_publish_ublock_cancel_(struct GNUNET_FS_PublishUblockContext *uc); #endif diff --git a/src/fs/fs_search.c b/src/fs/fs_search.c index e808d3eaa..662bc1619 100644 --- a/src/fs/fs_search.c +++ b/src/fs/fs_search.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_search.c * @brief Helper functions for searching. @@ -45,9 +45,9 @@ * @return value returned by the callback */ void * -GNUNET_FS_search_make_status_ (struct GNUNET_FS_ProgressInfo *pi, - struct GNUNET_FS_Handle *h, - struct GNUNET_FS_SearchContext *sc) +GNUNET_FS_search_make_status_(struct GNUNET_FS_ProgressInfo *pi, + struct GNUNET_FS_Handle *h, + struct GNUNET_FS_SearchContext *sc) { void *ret; @@ -59,11 +59,11 @@ GNUNET_FS_search_make_status_ (struct GNUNET_FS_ProgressInfo *pi, : sc->psearch_result->client_info; pi->value.search.query = (NULL != sc) ? sc->uri : NULL; pi->value.search.duration = (NULL != sc) - ? GNUNET_TIME_absolute_get_duration (sc->start_time) - : GNUNET_TIME_UNIT_ZERO; + ? GNUNET_TIME_absolute_get_duration(sc->start_time) + : GNUNET_TIME_UNIT_ZERO; pi->value.search.anonymity = (NULL != sc) ? sc->anonymity : 0; pi->fsh = h; - ret = h->upcb (h->upcb_cls, pi); + ret = h->upcb(h->upcb_cls, pi); return ret; } @@ -79,14 +79,14 @@ GNUNET_FS_search_make_status_ (struct GNUNET_FS_ProgressInfo *pi, * #GNUNET_OK otherwise */ static int -test_result_present (void *cls, - const struct GNUNET_HashCode * key, - void *value) +test_result_present(void *cls, + const struct GNUNET_HashCode * key, + void *value) { const struct GNUNET_FS_Uri *uri = cls; struct GNUNET_FS_SearchResult *sr = value; - if (GNUNET_FS_uri_test_equal (uri, sr->uri)) + if (GNUNET_FS_uri_test_equal(uri, sr->uri)) return GNUNET_SYSERR; return GNUNET_OK; } @@ -100,8 +100,8 @@ test_result_present (void *cls, * @param sr the specific result */ static void -notify_client_chk_result (struct GNUNET_FS_SearchContext *sc, - struct GNUNET_FS_SearchResult *sr) +notify_client_chk_result(struct GNUNET_FS_SearchContext *sc, + struct GNUNET_FS_SearchResult *sr) { struct GNUNET_FS_ProgressInfo pi; @@ -110,7 +110,7 @@ notify_client_chk_result (struct GNUNET_FS_SearchContext *sc, pi.value.search.specifics.result.uri = sr->uri; pi.value.search.specifics.result.result = sr; pi.value.search.specifics.result.applicability_rank = sr->optional_support; - sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc); + sr->client_info = GNUNET_FS_search_make_status_(&pi, sc->h, sc); } @@ -122,8 +122,8 @@ notify_client_chk_result (struct GNUNET_FS_SearchContext *sc, * @param sr the specific result */ static void -notify_client_chk_update (struct GNUNET_FS_SearchContext *sc, - struct GNUNET_FS_SearchResult *sr) +notify_client_chk_update(struct GNUNET_FS_SearchContext *sc, + struct GNUNET_FS_SearchResult *sr) { struct GNUNET_FS_ProgressInfo pi; @@ -132,21 +132,20 @@ notify_client_chk_update (struct GNUNET_FS_SearchContext *sc, pi.value.search.specifics.update.meta = sr->meta; pi.value.search.specifics.update.uri = sr->uri; pi.value.search.specifics.update.availability_rank = - 2 * sr->availability_success - sr->availability_trials; + 2 * sr->availability_success - sr->availability_trials; pi.value.search.specifics.update.availability_certainty = - sr->availability_trials; + sr->availability_trials; pi.value.search.specifics.update.applicability_rank = sr->optional_support; pi.value.search.specifics.update.current_probe_time - = GNUNET_TIME_absolute_get_duration (sr->probe_active_time); - sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc); + = GNUNET_TIME_absolute_get_duration(sr->probe_active_time); + sr->client_info = GNUNET_FS_search_make_status_(&pi, sc->h, sc); } /** * Context for "get_result_present". */ -struct GetResultContext -{ +struct GetResultContext { /** * The URI we're looking for. */ @@ -171,14 +170,14 @@ struct GetResultContext * @return #GNUNET_OK */ static int -get_result_present (void *cls, - const struct GNUNET_HashCode *key, - void *value) +get_result_present(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GetResultContext *grc = cls; struct GNUNET_FS_SearchResult *sr = value; - if (GNUNET_FS_uri_test_equal (grc->uri, sr->uri)) + if (GNUNET_FS_uri_test_equal(grc->uri, sr->uri)) grc->sr = sr; return GNUNET_OK; } @@ -191,7 +190,7 @@ get_result_present (void *cls, * @param sr search result to signal for */ static void -signal_probe_result (struct GNUNET_FS_SearchResult *sr) +signal_probe_result(struct GNUNET_FS_SearchResult *sr) { struct GNUNET_FS_ProgressInfo pi; @@ -205,9 +204,9 @@ signal_probe_result (struct GNUNET_FS_SearchResult *sr) = sr->availability_trials; pi.value.search.specifics.update.applicability_rank = sr->optional_support; pi.value.search.specifics.update.current_probe_time - = GNUNET_TIME_absolute_get_duration (sr->probe_active_time); - sr->client_info = GNUNET_FS_search_make_status_ (&pi, sr->h, sr->sc); - GNUNET_FS_search_start_probe_ (sr); + = GNUNET_TIME_absolute_get_duration(sr->probe_active_time); + sr->client_info = GNUNET_FS_search_make_status_(&pi, sr->h, sr->sc); + GNUNET_FS_search_start_probe_(sr); } @@ -217,21 +216,21 @@ signal_probe_result (struct GNUNET_FS_SearchResult *sr) * @param cls our `struct GNUNET_FS_SearchResult *` */ static void -probe_failure_handler (void *cls) +probe_failure_handler(void *cls) { struct GNUNET_FS_SearchResult *sr = cls; sr->probe_cancel_task = NULL; sr->availability_trials++; - GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES); + GNUNET_FS_download_stop(sr->probe_ctx, GNUNET_YES); sr->probe_ctx = NULL; - GNUNET_FS_stop_probe_ping_task_ (sr); - GNUNET_FS_search_result_sync_ (sr); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Probe #%u for search result %p failed\n", - sr->availability_trials, - sr); - signal_probe_result (sr); + GNUNET_FS_stop_probe_ping_task_(sr); + GNUNET_FS_search_result_sync_(sr); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Probe #%u for search result %p failed\n", + sr->availability_trials, + sr); + signal_probe_result(sr); } @@ -241,22 +240,22 @@ probe_failure_handler (void *cls) * @param cls our `struct GNUNET_FS_SearchResult *` */ static void -probe_success_handler (void *cls) +probe_success_handler(void *cls) { struct GNUNET_FS_SearchResult *sr = cls; sr->probe_cancel_task = NULL; sr->availability_trials++; sr->availability_success++; - GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES); + GNUNET_FS_download_stop(sr->probe_ctx, GNUNET_YES); sr->probe_ctx = NULL; - GNUNET_FS_stop_probe_ping_task_ (sr); - GNUNET_FS_search_result_sync_ (sr); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Probe #%u for search result %p succeeded\n", - sr->availability_trials, - sr); - signal_probe_result (sr); + GNUNET_FS_stop_probe_ping_task_(sr); + GNUNET_FS_search_result_sync_(sr); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Probe #%u for search result %p succeeded\n", + sr->availability_trials, + sr); + signal_probe_result(sr); } @@ -276,82 +275,91 @@ probe_success_handler (void *cls) * field in the `struct GNUNET_FS_ProgressInfo`. */ void * -GNUNET_FS_search_probe_progress_ (void *cls, - const struct GNUNET_FS_ProgressInfo *info) +GNUNET_FS_search_probe_progress_(void *cls, + const struct GNUNET_FS_ProgressInfo *info) { struct GNUNET_FS_SearchResult *sr = info->value.download.cctx; struct GNUNET_TIME_Relative dur; switch (info->status) - { - case GNUNET_FS_STATUS_DOWNLOAD_START: - /* ignore */ - break; - case GNUNET_FS_STATUS_DOWNLOAD_RESUME: - /* probes should never be resumed */ - GNUNET_assert (0); - break; - case GNUNET_FS_STATUS_DOWNLOAD_SUSPEND: - /* probes should never be suspended */ - GNUNET_break (0); - break; - case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: - /* ignore */ - break; - case GNUNET_FS_STATUS_DOWNLOAD_ERROR: - if (NULL != sr->probe_cancel_task) - { - GNUNET_SCHEDULER_cancel (sr->probe_cancel_task); - sr->probe_cancel_task = NULL; - } - sr->probe_cancel_task = - GNUNET_SCHEDULER_add_delayed (sr->remaining_probe_time, - &probe_failure_handler, sr); - break; - case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED: - if (NULL != sr->probe_cancel_task) - { - GNUNET_SCHEDULER_cancel (sr->probe_cancel_task); - sr->probe_cancel_task = NULL; - } - sr->probe_cancel_task = - GNUNET_SCHEDULER_add_now (&probe_success_handler, sr); - break; - case GNUNET_FS_STATUS_DOWNLOAD_STOPPED: - if (NULL != sr->probe_cancel_task) - { - GNUNET_SCHEDULER_cancel (sr->probe_cancel_task); - sr->probe_cancel_task = NULL; - } - sr = NULL; - break; - case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE: - if (NULL == sr->probe_cancel_task) { - sr->probe_active_time = GNUNET_TIME_absolute_get (); + case GNUNET_FS_STATUS_DOWNLOAD_START: + /* ignore */ + break; + + case GNUNET_FS_STATUS_DOWNLOAD_RESUME: + /* probes should never be resumed */ + GNUNET_assert(0); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_SUSPEND: + /* probes should never be suspended */ + GNUNET_break(0); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: + /* ignore */ + break; + + case GNUNET_FS_STATUS_DOWNLOAD_ERROR: + if (NULL != sr->probe_cancel_task) + { + GNUNET_SCHEDULER_cancel(sr->probe_cancel_task); + sr->probe_cancel_task = NULL; + } sr->probe_cancel_task = - GNUNET_SCHEDULER_add_delayed (sr->remaining_probe_time, - &probe_failure_handler, sr); - } - break; - case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE: - if (NULL != sr->probe_cancel_task) - { - GNUNET_SCHEDULER_cancel (sr->probe_cancel_task); - sr->probe_cancel_task = NULL; - } - dur = GNUNET_TIME_absolute_get_duration (sr->probe_active_time); - sr->remaining_probe_time = - GNUNET_TIME_relative_subtract (sr->remaining_probe_time, dur); - if (0 == sr->remaining_probe_time.rel_value_us) + GNUNET_SCHEDULER_add_delayed(sr->remaining_probe_time, + &probe_failure_handler, sr); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED: + if (NULL != sr->probe_cancel_task) + { + GNUNET_SCHEDULER_cancel(sr->probe_cancel_task); + sr->probe_cancel_task = NULL; + } sr->probe_cancel_task = - GNUNET_SCHEDULER_add_now (&probe_failure_handler, sr); - GNUNET_FS_search_result_sync_ (sr); - break; - default: - GNUNET_break (0); - return NULL; - } + GNUNET_SCHEDULER_add_now(&probe_success_handler, sr); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_STOPPED: + if (NULL != sr->probe_cancel_task) + { + GNUNET_SCHEDULER_cancel(sr->probe_cancel_task); + sr->probe_cancel_task = NULL; + } + sr = NULL; + break; + + case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE: + if (NULL == sr->probe_cancel_task) + { + sr->probe_active_time = GNUNET_TIME_absolute_get(); + sr->probe_cancel_task = + GNUNET_SCHEDULER_add_delayed(sr->remaining_probe_time, + &probe_failure_handler, sr); + } + break; + + case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE: + if (NULL != sr->probe_cancel_task) + { + GNUNET_SCHEDULER_cancel(sr->probe_cancel_task); + sr->probe_cancel_task = NULL; + } + dur = GNUNET_TIME_absolute_get_duration(sr->probe_active_time); + sr->remaining_probe_time = + GNUNET_TIME_relative_subtract(sr->remaining_probe_time, dur); + if (0 == sr->remaining_probe_time.rel_value_us) + sr->probe_cancel_task = + GNUNET_SCHEDULER_add_now(&probe_failure_handler, sr); + GNUNET_FS_search_result_sync_(sr); + break; + + default: + GNUNET_break(0); + return NULL; + } return sr; } @@ -362,18 +370,18 @@ GNUNET_FS_search_probe_progress_ (void *cls, * @param cls the `struct GNUNET_FS_SearchResult` that we are probing for */ static void -probe_ping_task_cb (void *cls) +probe_ping_task_cb(void *cls) { struct GNUNET_FS_Handle *h = cls; struct GNUNET_FS_SearchResult *sr; for (sr = h->probes_head; NULL != sr; sr = sr->next) if (NULL != sr->probe_ctx->mq) - signal_probe_result (sr); + signal_probe_result(sr); h->probe_ping_task - = GNUNET_SCHEDULER_add_delayed (GNUNET_FS_PROBE_UPDATE_FREQUENCY, - &probe_ping_task_cb, - h); + = GNUNET_SCHEDULER_add_delayed(GNUNET_FS_PROBE_UPDATE_FREQUENCY, + &probe_ping_task_cb, + h); } @@ -383,17 +391,17 @@ probe_ping_task_cb (void *cls) * @param sr result to start pinging for. */ static void -start_probe_ping_task (struct GNUNET_FS_SearchResult *sr) +start_probe_ping_task(struct GNUNET_FS_SearchResult *sr) { struct GNUNET_FS_Handle *h = sr->h; - GNUNET_CONTAINER_DLL_insert (h->probes_head, - h->probes_tail, - sr); + GNUNET_CONTAINER_DLL_insert(h->probes_head, + h->probes_tail, + sr); if (NULL == h->probe_ping_task) h->probe_ping_task - = GNUNET_SCHEDULER_add_now (&probe_ping_task_cb, - h); + = GNUNET_SCHEDULER_add_now(&probe_ping_task_cb, + h); } @@ -403,18 +411,18 @@ start_probe_ping_task (struct GNUNET_FS_SearchResult *sr) * @param sr result to start pinging for. */ void -GNUNET_FS_stop_probe_ping_task_ (struct GNUNET_FS_SearchResult *sr) +GNUNET_FS_stop_probe_ping_task_(struct GNUNET_FS_SearchResult *sr) { struct GNUNET_FS_Handle *h = sr->h; - GNUNET_CONTAINER_DLL_remove (h->probes_head, - h->probes_tail, - sr); + GNUNET_CONTAINER_DLL_remove(h->probes_head, + h->probes_tail, + sr); if (NULL == h->probes_head) - { - GNUNET_SCHEDULER_cancel (h->probe_ping_task); - h->probe_ping_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(h->probe_ping_task); + h->probe_ping_task = NULL; + } } @@ -424,7 +432,7 @@ GNUNET_FS_stop_probe_ping_task_ (struct GNUNET_FS_SearchResult *sr) * @param sr the search result */ void -GNUNET_FS_search_start_probe_ (struct GNUNET_FS_SearchResult *sr) +GNUNET_FS_search_start_probe_(struct GNUNET_FS_SearchResult *sr) { uint64_t off; uint64_t len; @@ -437,35 +445,35 @@ GNUNET_FS_search_start_probe_ (struct GNUNET_FS_SearchResult *sr) return; if (sr->availability_trials > AVAILABILITY_TRIALS_MAX) return; - if ( (GNUNET_FS_URI_CHK != sr->uri->type) && (GNUNET_FS_URI_LOC != sr->uri->type)) + if ((GNUNET_FS_URI_CHK != sr->uri->type) && (GNUNET_FS_URI_LOC != sr->uri->type)) return; - len = GNUNET_FS_uri_chk_get_file_size (sr->uri); + len = GNUNET_FS_uri_chk_get_file_size(sr->uri); if (0 == len) return; if ((len <= DBLOCK_SIZE) && (sr->availability_success > 0)) return; off = len / DBLOCK_SIZE; if (off > 0) - off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, off); + off = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, off); off *= DBLOCK_SIZE; if (len - off < DBLOCK_SIZE) len = len - off; else len = DBLOCK_SIZE; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting probe #%u (at offset %llu) for search result %p\n", - sr->availability_trials + 1, - (unsigned long long) off, - sr); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting probe #%u (at offset %llu) for search result %p\n", + sr->availability_trials + 1, + (unsigned long long)off, + sr); sr->remaining_probe_time = - GNUNET_TIME_relative_saturating_multiply (sr->h->avg_block_latency, - 2 * (1 + sr->availability_trials)); + GNUNET_TIME_relative_saturating_multiply(sr->h->avg_block_latency, + 2 * (1 + sr->availability_trials)); sr->probe_ctx = - GNUNET_FS_download_start (sr->h, sr->uri, sr->meta, NULL, NULL, off, - len, sr->anonymity, - GNUNET_FS_DOWNLOAD_NO_TEMPORARIES | - GNUNET_FS_DOWNLOAD_IS_PROBE, sr, NULL); - start_probe_ping_task (sr); + GNUNET_FS_download_start(sr->h, sr->uri, sr->meta, NULL, NULL, off, + len, sr->anonymity, + GNUNET_FS_DOWNLOAD_NO_TEMPORARIES | + GNUNET_FS_DOWNLOAD_IS_PROBE, sr, NULL); + start_probe_ping_task(sr); } @@ -480,23 +488,23 @@ GNUNET_FS_search_start_probe_ (struct GNUNET_FS_SearchResult *sr) * @return the search result handle to access the probe activity */ struct GNUNET_FS_SearchResult * -GNUNET_FS_probe (struct GNUNET_FS_Handle *h, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *meta, - void *client_info, - uint32_t anonymity) +GNUNET_FS_probe(struct GNUNET_FS_Handle *h, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *meta, + void *client_info, + uint32_t anonymity) { struct GNUNET_FS_SearchResult *sr; - GNUNET_assert (NULL != h); - GNUNET_assert (NULL != uri); - sr = GNUNET_new (struct GNUNET_FS_SearchResult); + GNUNET_assert(NULL != h); + GNUNET_assert(NULL != uri); + sr = GNUNET_new(struct GNUNET_FS_SearchResult); sr->h = h; - sr->uri = GNUNET_FS_uri_dup (uri); - sr->meta = GNUNET_CONTAINER_meta_data_duplicate (meta); + sr->uri = GNUNET_FS_uri_dup(uri); + sr->meta = GNUNET_CONTAINER_meta_data_duplicate(meta); sr->client_info = client_info; sr->anonymity = anonymity; - GNUNET_FS_search_start_probe_ (sr); + GNUNET_FS_search_start_probe_(sr); return sr; } @@ -507,19 +515,19 @@ GNUNET_FS_probe (struct GNUNET_FS_Handle *h, * @param sr search result */ static void -GNUNET_FS_search_stop_probe_ (struct GNUNET_FS_SearchResult *sr) +GNUNET_FS_search_stop_probe_(struct GNUNET_FS_SearchResult *sr) { if (NULL != sr->probe_ctx) - { - GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES); - sr->probe_ctx = NULL; - GNUNET_FS_stop_probe_ping_task_ (sr); - } + { + GNUNET_FS_download_stop(sr->probe_ctx, GNUNET_YES); + sr->probe_ctx = NULL; + GNUNET_FS_stop_probe_ping_task_(sr); + } if (NULL != sr->probe_cancel_task) - { - GNUNET_SCHEDULER_cancel (sr->probe_cancel_task); - sr->probe_cancel_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(sr->probe_cancel_task); + sr->probe_cancel_task = NULL; + } } @@ -531,16 +539,16 @@ GNUNET_FS_search_stop_probe_ (struct GNUNET_FS_SearchResult *sr) * @return the value of the 'client_info' pointer */ void * -GNUNET_FS_probe_stop (struct GNUNET_FS_SearchResult *sr) +GNUNET_FS_probe_stop(struct GNUNET_FS_SearchResult *sr) { void *client_info; - GNUNET_assert (NULL == sr->sc); - GNUNET_FS_search_stop_probe_ (sr); - GNUNET_FS_uri_destroy (sr->uri); - GNUNET_CONTAINER_meta_data_destroy (sr->meta); + GNUNET_assert(NULL == sr->sc); + GNUNET_FS_search_stop_probe_(sr); + GNUNET_FS_uri_destroy(sr->uri); + GNUNET_CONTAINER_meta_data_destroy(sr->meta); client_info = sr->client_info; - GNUNET_free (sr); + GNUNET_free(sr); return client_info; } @@ -556,10 +564,10 @@ GNUNET_FS_probe_stop (struct GNUNET_FS_SearchResult *sr) * under the @a ent keyword */ static void -process_ksk_result (struct GNUNET_FS_SearchContext *sc, - struct SearchRequestEntry *ent, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *meta) +process_ksk_result(struct GNUNET_FS_SearchContext *sc, + struct SearchRequestEntry *ent, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *meta) { struct GNUNET_HashCode key; struct GNUNET_FS_SearchResult *sr; @@ -568,80 +576,80 @@ process_ksk_result (struct GNUNET_FS_SearchContext *sc, unsigned int koff; /* check if new */ - GNUNET_assert (NULL != sc); + GNUNET_assert(NULL != sc); if (GNUNET_OK != - GNUNET_FS_uri_to_key (uri, - &key)) - { - GNUNET_break_op (0); - return; - } + GNUNET_FS_uri_to_key(uri, + &key)) + { + GNUNET_break_op(0); + return; + } if (GNUNET_SYSERR == - GNUNET_CONTAINER_multihashmap_get_multiple (ent->results, - &key, - &test_result_present, - (void *) uri)) + GNUNET_CONTAINER_multihashmap_get_multiple(ent->results, + &key, + &test_result_present, + (void *)uri)) return; /* duplicate result */ /* try to find search result in master map */ grc.sr = NULL; grc.uri = uri; - GNUNET_CONTAINER_multihashmap_get_multiple (sc->master_result_map, - &key, - &get_result_present, &grc); + GNUNET_CONTAINER_multihashmap_get_multiple(sc->master_result_map, + &key, + &get_result_present, &grc); sr = grc.sr; is_new = (NULL == sr) || (sr->mandatory_missing > 0); if (NULL == sr) - { - sr = GNUNET_new (struct GNUNET_FS_SearchResult); - sr->h = sc->h; - sr->sc = sc; - sr->anonymity = sc->anonymity; - sr->uri = GNUNET_FS_uri_dup (uri); - sr->meta = GNUNET_CONTAINER_meta_data_duplicate (meta); - sr->mandatory_missing = sc->mandatory_count; - sr->key = key; - sr->keyword_bitmap = GNUNET_malloc ((sc->uri->data.ksk.keywordCount + 7) / 8); /* round up, count bits */ - GNUNET_CONTAINER_multihashmap_put (sc->master_result_map, &key, sr, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - } + { + sr = GNUNET_new(struct GNUNET_FS_SearchResult); + sr->h = sc->h; + sr->sc = sc; + sr->anonymity = sc->anonymity; + sr->uri = GNUNET_FS_uri_dup(uri); + sr->meta = GNUNET_CONTAINER_meta_data_duplicate(meta); + sr->mandatory_missing = sc->mandatory_count; + sr->key = key; + sr->keyword_bitmap = GNUNET_malloc((sc->uri->data.ksk.keywordCount + 7) / 8); /* round up, count bits */ + GNUNET_CONTAINER_multihashmap_put(sc->master_result_map, &key, sr, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + } else - { - GNUNET_CONTAINER_meta_data_merge (sr->meta, meta); - } - GNUNET_break (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (ent->results, - &sr->key, - sr, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + { + GNUNET_CONTAINER_meta_data_merge(sr->meta, meta); + } + GNUNET_break(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(ent->results, + &sr->key, + sr, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); koff = ent - sc->requests; - GNUNET_assert ( (ent >= sc->requests) && - (koff < sc->uri->data.ksk.keywordCount)); + GNUNET_assert((ent >= sc->requests) && + (koff < sc->uri->data.ksk.keywordCount)); sr->keyword_bitmap[koff / 8] |= (1 << (koff % 8)); /* check if mandatory satisfied */ - if (1 <= GNUNET_CONTAINER_multihashmap_size (ent->results)) - { - if (ent->mandatory) + if (1 <= GNUNET_CONTAINER_multihashmap_size(ent->results)) { - GNUNET_break (sr->mandatory_missing > 0); - sr->mandatory_missing--; + if (ent->mandatory) + { + GNUNET_break(sr->mandatory_missing > 0); + sr->mandatory_missing--; + } + else + { + sr->optional_support++; + } } - else + if (0 != sr->mandatory_missing) { - sr->optional_support++; + GNUNET_break(NULL == sr->client_info); + return; } - } - if (0 != sr->mandatory_missing) - { - GNUNET_break (NULL == sr->client_info); - return; - } if (is_new) - notify_client_chk_result (sc, sr); + notify_client_chk_result(sc, sr); else - notify_client_chk_update (sc, sr); - GNUNET_FS_search_result_sync_ (sr); - GNUNET_FS_search_start_probe_ (sr); + notify_client_chk_update(sc, sr); + GNUNET_FS_search_result_sync_(sr); + GNUNET_FS_search_start_probe_(sr); } @@ -658,12 +666,12 @@ process_ksk_result (struct GNUNET_FS_SearchContext *sc, * @return context that can be used to control the search */ static struct GNUNET_FS_SearchContext * -search_start (struct GNUNET_FS_Handle *h, - const struct GNUNET_FS_Uri *uri, - uint32_t anonymity, - enum GNUNET_FS_SearchOptions options, - void *cctx, - struct GNUNET_FS_SearchResult *psearch); +search_start(struct GNUNET_FS_Handle *h, + const struct GNUNET_FS_Uri *uri, + uint32_t anonymity, + enum GNUNET_FS_SearchOptions options, + void *cctx, + struct GNUNET_FS_SearchResult *psearch); /** @@ -674,58 +682,58 @@ search_start (struct GNUNET_FS_Handle *h, * @param id_update identifier for updates, NULL for none * @param uri the URI that was found * @param meta metadata associated with the URI - */ + */ static void -process_sks_result (struct GNUNET_FS_SearchContext *sc, - const char *id_update, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *meta) +process_sks_result(struct GNUNET_FS_SearchContext *sc, + const char *id_update, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *meta) { struct GNUNET_FS_Uri uu; struct GNUNET_HashCode key; struct GNUNET_FS_SearchResult *sr; /* check if new */ - GNUNET_assert (NULL != sc); + GNUNET_assert(NULL != sc); if (GNUNET_OK != - GNUNET_FS_uri_to_key (uri, - &key)) - { - GNUNET_break (0); - return; - } - GNUNET_CRYPTO_hash_xor (&uri->data.chk.chk.key, - &uri->data.chk.chk.query, - &key); + GNUNET_FS_uri_to_key(uri, + &key)) + { + GNUNET_break(0); + return; + } + GNUNET_CRYPTO_hash_xor(&uri->data.chk.chk.key, + &uri->data.chk.chk.query, + &key); if (GNUNET_SYSERR == - GNUNET_CONTAINER_multihashmap_get_multiple (sc->master_result_map, &key, - &test_result_present, - (void *) uri)) + GNUNET_CONTAINER_multihashmap_get_multiple(sc->master_result_map, &key, + &test_result_present, + (void *)uri)) return; /* duplicate result */ - sr = GNUNET_new (struct GNUNET_FS_SearchResult); + sr = GNUNET_new(struct GNUNET_FS_SearchResult); sr->h = sc->h; sr->sc = sc; sr->anonymity = sc->anonymity; - sr->uri = GNUNET_FS_uri_dup (uri); - sr->meta = GNUNET_CONTAINER_meta_data_duplicate (meta); + sr->uri = GNUNET_FS_uri_dup(uri); + sr->meta = GNUNET_CONTAINER_meta_data_duplicate(meta); sr->key = key; - GNUNET_CONTAINER_multihashmap_put (sc->master_result_map, &key, sr, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - GNUNET_FS_search_result_sync_ (sr); - GNUNET_FS_search_start_probe_ (sr); + GNUNET_CONTAINER_multihashmap_put(sc->master_result_map, &key, sr, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + GNUNET_FS_search_result_sync_(sr); + GNUNET_FS_search_start_probe_(sr); /* notify client */ if (0 == sr->mandatory_missing) - notify_client_chk_result (sc, sr); + notify_client_chk_result(sc, sr); else - GNUNET_break (NULL == sr->client_info); + GNUNET_break(NULL == sr->client_info); /* search for updates */ - if (0 == strlen (id_update)) + if (0 == strlen(id_update)) return; /* no updates */ uu.type = GNUNET_FS_URI_SKS; uu.data.sks.ns = sc->uri->data.sks.ns; - uu.data.sks.identifier = GNUNET_strdup (id_update); - (void) search_start (sc->h, &uu, sc->anonymity, sc->options, NULL, sr); - GNUNET_free (uu.data.sks.identifier); + uu.data.sks.identifier = GNUNET_strdup(id_update); + (void)search_start(sc->h, &uu, sc->anonymity, sc->options, NULL, sr); + GNUNET_free(uu.data.sks.identifier); } @@ -744,11 +752,11 @@ process_sks_result (struct GNUNET_FS_SearchContext *sc, * keyword, internal error) */ static int -decrypt_block_with_keyword (const struct GNUNET_FS_SearchContext *sc, - const struct GNUNET_CRYPTO_EcdsaPublicKey *dpub, - const void *edata, - size_t edata_size, - char *data) +decrypt_block_with_keyword(const struct GNUNET_FS_SearchContext *sc, + const struct GNUNET_CRYPTO_EcdsaPublicKey *dpub, + const void *edata, + size_t edata_size, + char *data) { const struct GNUNET_CRYPTO_EcdsaPrivateKey *anon; struct GNUNET_CRYPTO_EcdsaPublicKey anon_pub; @@ -756,23 +764,23 @@ decrypt_block_with_keyword (const struct GNUNET_FS_SearchContext *sc, /* find key */ for (i = 0; i < sc->uri->data.ksk.keywordCount; i++) - if (0 == memcmp (dpub, - &sc->requests[i].dpub, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey))) + if (0 == memcmp(dpub, + &sc->requests[i].dpub, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey))) break; if (i == sc->uri->data.ksk.keywordCount) - { - /* oops, does not match any of our keywords!? */ - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + /* oops, does not match any of our keywords!? */ + GNUNET_break(0); + return GNUNET_SYSERR; + } /* decrypt */ - anon = GNUNET_CRYPTO_ecdsa_key_get_anonymous (); - GNUNET_CRYPTO_ecdsa_key_get_public (anon, &anon_pub); - GNUNET_FS_ublock_decrypt_ (edata, edata_size, - &anon_pub, - sc->requests[i].keyword, - data); + anon = GNUNET_CRYPTO_ecdsa_key_get_anonymous(); + GNUNET_CRYPTO_ecdsa_key_get_public(anon, &anon_pub); + GNUNET_FS_ublock_decrypt_(edata, edata_size, + &anon_pub, + sc->requests[i].keyword, + data); return i; } @@ -787,65 +795,65 @@ decrypt_block_with_keyword (const struct GNUNET_FS_SearchContext *sc, * @param size size of @a ub */ static void -process_kblock (struct GNUNET_FS_SearchContext *sc, - const struct UBlock *ub, - size_t size) +process_kblock(struct GNUNET_FS_SearchContext *sc, + const struct UBlock *ub, + size_t size) { size_t j; - char pt[size - sizeof (struct UBlock)]; + char pt[size - sizeof(struct UBlock)]; const char *eos; struct GNUNET_CONTAINER_MetaData *meta; struct GNUNET_FS_Uri *uri; char *emsg; int i; - if (-1 == (i = decrypt_block_with_keyword (sc, - &ub->verification_key, - &ub[1], - size - sizeof (struct UBlock), - pt))) + if (-1 == (i = decrypt_block_with_keyword(sc, + &ub->verification_key, + &ub[1], + size - sizeof(struct UBlock), + pt))) return; /* parse; pt[0] is just '\0', so we skip over that */ - eos = memchr (&pt[1], '\0', sizeof (pt) - 1); + eos = memchr(&pt[1], '\0', sizeof(pt) - 1); if (NULL == eos) - { - GNUNET_break_op (0); - return; - } - if (NULL == (uri = GNUNET_FS_uri_parse (&pt[1], &emsg))) - { - if (GNUNET_FS_VERSION > 0x00090400) { - /* we broke this in 0x00090300, so don't bitch - too loudly just one version up... */ - GNUNET_break_op (0); /* ublock malformed */ - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to parse URI `%s': %s\n"), - &pt[1], - emsg); + GNUNET_break_op(0); + return; + } + if (NULL == (uri = GNUNET_FS_uri_parse(&pt[1], &emsg))) + { + if (GNUNET_FS_VERSION > 0x00090400) + { + /* we broke this in 0x00090300, so don't bitch + too loudly just one version up... */ + GNUNET_break_op(0); /* ublock malformed */ + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to parse URI `%s': %s\n"), + &pt[1], + emsg); + } + GNUNET_free_non_null(emsg); + return; } - GNUNET_free_non_null (emsg); - return; - } j = eos - pt + 1; - if (sizeof (pt) == j) - meta = GNUNET_CONTAINER_meta_data_create (); + if (sizeof(pt) == j) + meta = GNUNET_CONTAINER_meta_data_create(); else - meta = GNUNET_CONTAINER_meta_data_deserialize (&pt[j], sizeof (pt) - j); + meta = GNUNET_CONTAINER_meta_data_deserialize(&pt[j], sizeof(pt) - j); if (NULL == meta) - { - GNUNET_break_op (0); /* ublock malformed */ - GNUNET_FS_uri_destroy (uri); - return; - } - process_ksk_result (sc, - &sc->requests[i], - uri, - meta); + { + GNUNET_break_op(0); /* ublock malformed */ + GNUNET_FS_uri_destroy(uri); + return; + } + process_ksk_result(sc, + &sc->requests[i], + uri, + meta); /* clean up */ - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_FS_uri_destroy (uri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_FS_uri_destroy(uri); } @@ -859,11 +867,11 @@ process_kblock (struct GNUNET_FS_SearchContext *sc, * @param size size of @a ub */ static void -process_sblock (struct GNUNET_FS_SearchContext *sc, - const struct UBlock *ub, - size_t size) +process_sblock(struct GNUNET_FS_SearchContext *sc, + const struct UBlock *ub, + size_t size) { - size_t len = size - sizeof (struct UBlock); + size_t len = size - sizeof(struct UBlock); char pt[len]; struct GNUNET_FS_Uri *uri; struct GNUNET_CONTAINER_MetaData *meta; @@ -872,36 +880,36 @@ process_sblock (struct GNUNET_FS_SearchContext *sc, size_t off; char *emsg; - GNUNET_FS_ublock_decrypt_ (&ub[1], len, - &sc->uri->data.sks.ns, - sc->uri->data.sks.identifier, - pt); + GNUNET_FS_ublock_decrypt_(&ub[1], len, + &sc->uri->data.sks.ns, + sc->uri->data.sks.identifier, + pt); /* parse */ - if (0 == (off = GNUNET_STRINGS_buffer_tokenize (pt, len, 2, &id, &uris))) - { - GNUNET_break_op (0); /* ublock malformed */ - return; - } - if (NULL == (meta = GNUNET_CONTAINER_meta_data_deserialize (&pt[off], len - off))) - { - GNUNET_break_op (0); /* ublock malformed */ - return; - } - if (NULL == (uri = GNUNET_FS_uri_parse (uris, &emsg))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to parse URI `%s': %s\n"), - uris, emsg); - GNUNET_break_op (0); /* ublock malformed */ - GNUNET_free_non_null (emsg); - GNUNET_CONTAINER_meta_data_destroy (meta); - return; - } + if (0 == (off = GNUNET_STRINGS_buffer_tokenize(pt, len, 2, &id, &uris))) + { + GNUNET_break_op(0); /* ublock malformed */ + return; + } + if (NULL == (meta = GNUNET_CONTAINER_meta_data_deserialize(&pt[off], len - off))) + { + GNUNET_break_op(0); /* ublock malformed */ + return; + } + if (NULL == (uri = GNUNET_FS_uri_parse(uris, &emsg))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to parse URI `%s': %s\n"), + uris, emsg); + GNUNET_break_op(0); /* ublock malformed */ + GNUNET_free_non_null(emsg); + GNUNET_CONTAINER_meta_data_destroy(meta); + return; + } /* process */ - process_sks_result (sc, id, uri, meta); + process_sks_result(sc, id, uri, meta); /* clean up */ - GNUNET_FS_uri_destroy (uri); - GNUNET_CONTAINER_meta_data_destroy (meta); + GNUNET_FS_uri_destroy(uri); + GNUNET_CONTAINER_meta_data_destroy(meta); } @@ -913,7 +921,7 @@ process_sblock (struct GNUNET_FS_SearchContext *sc, * @param sc the search to reconnec */ static void -try_reconnect (struct GNUNET_FS_SearchContext *sc); +try_reconnect(struct GNUNET_FS_SearchContext *sc); /** @@ -923,8 +931,8 @@ try_reconnect (struct GNUNET_FS_SearchContext *sc); * @param msg result message received */ static int -check_result (void *cls, - const struct ClientPutMessage *cm) +check_result(void *cls, + const struct ClientPutMessage *cm) { /* payload of any variable size is OK */ return GNUNET_OK; @@ -938,49 +946,54 @@ check_result (void *cls, * @param msg result message received */ static void -handle_result (void *cls, - const struct ClientPutMessage *cm) +handle_result(void *cls, + const struct ClientPutMessage *cm) { struct GNUNET_FS_SearchContext *sc = cls; - uint16_t msize = ntohs (cm->header.size) - sizeof (*cm); - enum GNUNET_BLOCK_Type type = ntohl (cm->type); - - if (GNUNET_TIME_absolute_get_duration (GNUNET_TIME_absolute_ntoh (cm->expiration)).rel_value_us > 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Result received has already expired.\n"); - return; /* result expired */ - } + uint16_t msize = ntohs(cm->header.size) - sizeof(*cm); + enum GNUNET_BLOCK_Type type = ntohl(cm->type); + + if (GNUNET_TIME_absolute_get_duration(GNUNET_TIME_absolute_ntoh(cm->expiration)).rel_value_us > 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Result received has already expired.\n"); + return; /* result expired */ + } switch (type) - { - case GNUNET_BLOCK_TYPE_FS_UBLOCK: - if (GNUNET_FS_URI_SKS == sc->uri->type) - process_sblock (sc, - (const struct UBlock *) &cm[1], - msize); - else - process_kblock (sc, - (const struct UBlock *) &cm[1], - msize); - break; - case GNUNET_BLOCK_TYPE_ANY: - GNUNET_break (0); - break; - case GNUNET_BLOCK_TYPE_FS_DBLOCK: - GNUNET_break (0); - break; - case GNUNET_BLOCK_TYPE_FS_ONDEMAND: - GNUNET_break (0); - break; - case GNUNET_BLOCK_TYPE_FS_IBLOCK: - GNUNET_break (0); - break; - default: - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Got result with unknown block type `%d', ignoring"), - type); - break; - } + { + case GNUNET_BLOCK_TYPE_FS_UBLOCK: + if (GNUNET_FS_URI_SKS == sc->uri->type) + process_sblock(sc, + (const struct UBlock *)&cm[1], + msize); + else + process_kblock(sc, + (const struct UBlock *)&cm[1], + msize); + break; + + case GNUNET_BLOCK_TYPE_ANY: + GNUNET_break(0); + break; + + case GNUNET_BLOCK_TYPE_FS_DBLOCK: + GNUNET_break(0); + break; + + case GNUNET_BLOCK_TYPE_FS_ONDEMAND: + GNUNET_break(0); + break; + + case GNUNET_BLOCK_TYPE_FS_IBLOCK: + GNUNET_break(0); + break; + + default: + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Got result with unknown block type `%d', ignoring"), + type); + break; + } } @@ -991,14 +1004,13 @@ handle_result (void *cls, * @param sc context for the search */ static void -schedule_transmit_search_request (struct GNUNET_FS_SearchContext *sc); +schedule_transmit_search_request(struct GNUNET_FS_SearchContext *sc); /** * Closure for #build_result_set(). */ -struct MessageBuilderContext -{ +struct MessageBuilderContext { /** * How many entries can we store to xoff. */ @@ -1036,21 +1048,21 @@ struct MessageBuilderContext * @return #GNUNET_OK to continue iterating */ static int -build_result_set (void *cls, - const struct GNUNET_HashCode *key, - void *value) +build_result_set(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct MessageBuilderContext *mbc = cls; struct GNUNET_FS_SearchResult *sr = value; - if ( (NULL != sr->keyword_bitmap) && - (0 == (sr->keyword_bitmap[mbc->keyword_offset / 8] & (1 << (mbc->keyword_offset % 8)))) ) + if ((NULL != sr->keyword_bitmap) && + (0 == (sr->keyword_bitmap[mbc->keyword_offset / 8] & (1 << (mbc->keyword_offset % 8))))) return GNUNET_OK; /* have no match for this keyword yet */ if (mbc->skip_cnt > 0) - { - mbc->skip_cnt--; - return GNUNET_OK; - } + { + mbc->skip_cnt--; + return GNUNET_OK; + } if (0 == mbc->put_cnt) return GNUNET_SYSERR; mbc->xoff[--mbc->put_cnt] = *key; @@ -1069,15 +1081,15 @@ build_result_set (void *cls, * @return #GNUNET_OK to continue iterating */ static int -find_result_set (void *cls, - const struct GNUNET_HashCode *key, - void *value) +find_result_set(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct MessageBuilderContext *mbc = cls; struct GNUNET_FS_SearchResult *sr = value; - if ( (NULL != sr->keyword_bitmap) && - (0 == (sr->keyword_bitmap[mbc->keyword_offset / 8] & (1 << (mbc->keyword_offset % 8)))) ) + if ((NULL != sr->keyword_bitmap) && + (0 == (sr->keyword_bitmap[mbc->keyword_offset / 8] & (1 << (mbc->keyword_offset % 8))))) return GNUNET_OK; /* have no match for this keyword yet */ mbc->put_cnt++; return GNUNET_OK; @@ -1091,7 +1103,7 @@ find_result_set (void *cls, * @param sc context for the search */ static void -schedule_transmit_search_request (struct GNUNET_FS_SearchContext *sc) +schedule_transmit_search_request(struct GNUNET_FS_SearchContext *sc) { struct MessageBuilderContext mbc; struct GNUNET_MQ_Envelope *env; @@ -1106,115 +1118,115 @@ schedule_transmit_search_request (struct GNUNET_FS_SearchContext *sc) unsigned int keyword_offset; int first_call; - memset (&mbc, 0, sizeof (mbc)); + memset(&mbc, 0, sizeof(mbc)); mbc.sc = sc; - if (GNUNET_FS_uri_test_ksk (sc->uri)) - { - /* This will calculate the result set size ONLY for - "keyword_offset == 0", so we will have to recalculate - it for the other keywords later! */ - GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map, - &find_result_set, - &mbc); - total_seen_results = mbc.put_cnt; - } + if (GNUNET_FS_uri_test_ksk(sc->uri)) + { + /* This will calculate the result set size ONLY for + "keyword_offset == 0", so we will have to recalculate + it for the other keywords later! */ + GNUNET_CONTAINER_multihashmap_iterate(sc->master_result_map, + &find_result_set, + &mbc); + total_seen_results = mbc.put_cnt; + } else - { - total_seen_results - = GNUNET_CONTAINER_multihashmap_size (sc->master_result_map); - } + { + total_seen_results + = GNUNET_CONTAINER_multihashmap_size(sc->master_result_map); + } search_request_map_offset = 0; keyword_offset = 0; first_call = GNUNET_YES; - while ( (0 != (left = - (total_seen_results - search_request_map_offset))) || - (GNUNET_YES == first_call) ) - { - first_call = GNUNET_NO; - options = SEARCH_MESSAGE_OPTION_NONE; - if (0 != (sc->options & GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY)) - options |= SEARCH_MESSAGE_OPTION_LOOPBACK_ONLY; - - fit = (GNUNET_MAX_MESSAGE_SIZE - 1 - sizeof (*sm)) / sizeof (struct GNUNET_HashCode); - todo = GNUNET_MIN (fit, - left); - env = GNUNET_MQ_msg_extra (sm, - sizeof (struct GNUNET_HashCode) * todo, - GNUNET_MESSAGE_TYPE_FS_START_SEARCH); - mbc.skip_cnt = search_request_map_offset; - mbc.xoff = (struct GNUNET_HashCode *) &sm[1]; - sm->type = htonl (GNUNET_BLOCK_TYPE_FS_UBLOCK); - sm->anonymity_level = htonl (sc->anonymity); - memset (&sm->target, - 0, - sizeof (struct GNUNET_PeerIdentity)); - - if (GNUNET_FS_uri_test_ksk (sc->uri)) + while ((0 != (left = + (total_seen_results - search_request_map_offset))) || + (GNUNET_YES == first_call)) { - mbc.keyword_offset = keyword_offset; - /* calculate how many results we can send in this message */ - mbc.put_cnt = todo; - /* now build message */ - sm->query = sc->requests[keyword_offset].uquery; - GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map, - &build_result_set, - &mbc); - search_request_map_offset += todo; - GNUNET_assert (0 == mbc.put_cnt); - GNUNET_assert (total_seen_results >= search_request_map_offset); - if (total_seen_results != search_request_map_offset) - { - /* more requesting to be done... */ - sm->options = htonl (options | SEARCH_MESSAGE_OPTION_CONTINUED); - } - else - { - sm->options = htonl (options); - keyword_offset++; - if (sc->uri->data.ksk.keywordCount != keyword_offset) + first_call = GNUNET_NO; + options = SEARCH_MESSAGE_OPTION_NONE; + if (0 != (sc->options & GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY)) + options |= SEARCH_MESSAGE_OPTION_LOOPBACK_ONLY; + + fit = (GNUNET_MAX_MESSAGE_SIZE - 1 - sizeof(*sm)) / sizeof(struct GNUNET_HashCode); + todo = GNUNET_MIN(fit, + left); + env = GNUNET_MQ_msg_extra(sm, + sizeof(struct GNUNET_HashCode) * todo, + GNUNET_MESSAGE_TYPE_FS_START_SEARCH); + mbc.skip_cnt = search_request_map_offset; + mbc.xoff = (struct GNUNET_HashCode *)&sm[1]; + sm->type = htonl(GNUNET_BLOCK_TYPE_FS_UBLOCK); + sm->anonymity_level = htonl(sc->anonymity); + memset(&sm->target, + 0, + sizeof(struct GNUNET_PeerIdentity)); + + if (GNUNET_FS_uri_test_ksk(sc->uri)) { - /* more keywords => more requesting to be done... */ - first_call = GNUNET_YES; - search_request_map_offset = 0; - mbc.put_cnt = 0; mbc.keyword_offset = keyword_offset; - GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map, - &find_result_set, - &mbc); - total_seen_results = mbc.put_cnt; + /* calculate how many results we can send in this message */ + mbc.put_cnt = todo; + /* now build message */ + sm->query = sc->requests[keyword_offset].uquery; + GNUNET_CONTAINER_multihashmap_iterate(sc->master_result_map, + &build_result_set, + &mbc); + search_request_map_offset += todo; + GNUNET_assert(0 == mbc.put_cnt); + GNUNET_assert(total_seen_results >= search_request_map_offset); + if (total_seen_results != search_request_map_offset) + { + /* more requesting to be done... */ + sm->options = htonl(options | SEARCH_MESSAGE_OPTION_CONTINUED); + } + else + { + sm->options = htonl(options); + keyword_offset++; + if (sc->uri->data.ksk.keywordCount != keyword_offset) + { + /* more keywords => more requesting to be done... */ + first_call = GNUNET_YES; + search_request_map_offset = 0; + mbc.put_cnt = 0; + mbc.keyword_offset = keyword_offset; + GNUNET_CONTAINER_multihashmap_iterate(sc->master_result_map, + &find_result_set, + &mbc); + total_seen_results = mbc.put_cnt; + } + } } - } - } - else - { - GNUNET_assert (GNUNET_FS_uri_test_sks (sc->uri)); - - GNUNET_CRYPTO_ecdsa_public_key_derive (&sc->uri->data.sks.ns, - sc->uri->data.sks.identifier, - "fs-ublock", - &dpub); - GNUNET_CRYPTO_hash (&dpub, - sizeof (dpub), - &sm->query); - mbc.put_cnt = todo; - mbc.keyword_offset = 0; - GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map, - &build_result_set, - &mbc); - GNUNET_assert (total_seen_results >= search_request_map_offset); - if (total_seen_results != search_request_map_offset) - { - /* more requesting to be done... */ - sm->options = htonl (options | SEARCH_MESSAGE_OPTION_CONTINUED); - } else - { - sm->options = htonl (options); - } + { + GNUNET_assert(GNUNET_FS_uri_test_sks(sc->uri)); + + GNUNET_CRYPTO_ecdsa_public_key_derive(&sc->uri->data.sks.ns, + sc->uri->data.sks.identifier, + "fs-ublock", + &dpub); + GNUNET_CRYPTO_hash(&dpub, + sizeof(dpub), + &sm->query); + mbc.put_cnt = todo; + mbc.keyword_offset = 0; + GNUNET_CONTAINER_multihashmap_iterate(sc->master_result_map, + &build_result_set, + &mbc); + GNUNET_assert(total_seen_results >= search_request_map_offset); + if (total_seen_results != search_request_map_offset) + { + /* more requesting to be done... */ + sm->options = htonl(options | SEARCH_MESSAGE_OPTION_CONTINUED); + } + else + { + sm->options = htonl(options); + } + } + GNUNET_MQ_send(sc->mq, + env); } - GNUNET_MQ_send (sc->mq, - env); - } } @@ -1227,17 +1239,17 @@ schedule_transmit_search_request (struct GNUNET_FS_SearchContext *sc) * @param error error code */ static void -search_mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +search_mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_FS_SearchContext *sc = cls; if (NULL != sc->mq) - { - GNUNET_MQ_destroy (sc->mq); - sc->mq = NULL; - } - try_reconnect (sc); + { + GNUNET_MQ_destroy(sc->mq); + sc->mq = NULL; + } + try_reconnect(sc); } @@ -1248,29 +1260,29 @@ search_mq_error_handler (void *cls, * @param cls our search context */ static void -do_reconnect (void *cls) +do_reconnect(void *cls) { struct GNUNET_FS_SearchContext *sc = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (result, - GNUNET_MESSAGE_TYPE_FS_PUT, - struct ClientPutMessage, - sc), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(result, + GNUNET_MESSAGE_TYPE_FS_PUT, + struct ClientPutMessage, + sc), + GNUNET_MQ_handler_end() }; sc->task = NULL; - sc->mq = GNUNET_CLIENT_connect (sc->h->cfg, - "fs", - handlers, - &search_mq_error_handler, - sc); + sc->mq = GNUNET_CLIENT_connect(sc->h->cfg, + "fs", + handlers, + &search_mq_error_handler, + sc); if (NULL == sc->mq) - { - try_reconnect (sc); - return; - } - schedule_transmit_search_request (sc); + { + try_reconnect(sc); + return; + } + schedule_transmit_search_request(sc); } @@ -1282,18 +1294,18 @@ do_reconnect (void *cls) * @param sc the search to reconnec */ static void -try_reconnect (struct GNUNET_FS_SearchContext *sc) +try_reconnect(struct GNUNET_FS_SearchContext *sc) { if (NULL != sc->mq) - { - GNUNET_MQ_destroy (sc->mq); - sc->mq = NULL; - } - sc->reconnect_backoff = GNUNET_TIME_STD_BACKOFF (sc->reconnect_backoff); + { + GNUNET_MQ_destroy(sc->mq); + sc->mq = NULL; + } + sc->reconnect_backoff = GNUNET_TIME_STD_BACKOFF(sc->reconnect_backoff); sc->task = - GNUNET_SCHEDULER_add_delayed (sc->reconnect_backoff, - &do_reconnect, - sc); + GNUNET_SCHEDULER_add_delayed(sc->reconnect_backoff, + &do_reconnect, + sc); } @@ -1310,39 +1322,39 @@ try_reconnect (struct GNUNET_FS_SearchContext *sc) * @return context that can be used to control the search */ static struct GNUNET_FS_SearchContext * -search_start (struct GNUNET_FS_Handle *h, - const struct GNUNET_FS_Uri *uri, - uint32_t anonymity, - enum GNUNET_FS_SearchOptions options, - void *cctx, - struct GNUNET_FS_SearchResult *psearch) +search_start(struct GNUNET_FS_Handle *h, + const struct GNUNET_FS_Uri *uri, + uint32_t anonymity, + enum GNUNET_FS_SearchOptions options, + void *cctx, + struct GNUNET_FS_SearchResult *psearch) { struct GNUNET_FS_SearchContext *sc; struct GNUNET_FS_ProgressInfo pi; - sc = GNUNET_new (struct GNUNET_FS_SearchContext); + sc = GNUNET_new(struct GNUNET_FS_SearchContext); sc->h = h; sc->options = options; - sc->uri = GNUNET_FS_uri_dup (uri); + sc->uri = GNUNET_FS_uri_dup(uri); sc->anonymity = anonymity; - sc->start_time = GNUNET_TIME_absolute_get (); + sc->start_time = GNUNET_TIME_absolute_get(); if (NULL != psearch) - { - sc->psearch_result = psearch; - psearch->update_search = sc; - } - sc->master_result_map = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_NO); + { + sc->psearch_result = psearch; + psearch->update_search = sc; + } + sc->master_result_map = GNUNET_CONTAINER_multihashmap_create(16, GNUNET_NO); sc->client_info = cctx; - if (GNUNET_OK != GNUNET_FS_search_start_searching_ (sc)) - { - GNUNET_FS_uri_destroy (sc->uri); - GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map); - GNUNET_free (sc); - return NULL; - } - GNUNET_FS_search_sync_ (sc); + if (GNUNET_OK != GNUNET_FS_search_start_searching_(sc)) + { + GNUNET_FS_uri_destroy(sc->uri); + GNUNET_CONTAINER_multihashmap_destroy(sc->master_result_map); + GNUNET_free(sc); + return NULL; + } + GNUNET_FS_search_sync_(sc); pi.status = GNUNET_FS_STATUS_SEARCH_START; - sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc); + sc->client_info = GNUNET_FS_search_make_status_(&pi, sc->h, sc); return sc; } @@ -1357,9 +1369,9 @@ search_start (struct GNUNET_FS_Handle *h, * @return #GNUNET_YES (we should continue to iterate) */ static int -update_sre_result_maps (void *cls, - const struct GNUNET_HashCode *key, - void *value) +update_sre_result_maps(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GNUNET_FS_SearchContext *sc = cls; struct GNUNET_FS_SearchResult *sr = value; @@ -1367,11 +1379,11 @@ update_sre_result_maps (void *cls, for (i = 0; i < sc->uri->data.ksk.keywordCount; i++) if (0 != (sr->keyword_bitmap[i / 8] & (1 << (i % 8)))) - GNUNET_break (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (sc->requests[i].results, - &sr->key, - sr, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_break(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(sc->requests[i].results, + &sr->key, + sr, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); return GNUNET_YES; } @@ -1385,7 +1397,7 @@ update_sre_result_maps (void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_FS_search_start_searching_ (struct GNUNET_FS_SearchContext *sc) +GNUNET_FS_search_start_searching_(struct GNUNET_FS_SearchContext *sc) { unsigned int i; const char *keyword; @@ -1393,45 +1405,45 @@ GNUNET_FS_search_start_searching_ (struct GNUNET_FS_SearchContext *sc) struct GNUNET_CRYPTO_EcdsaPublicKey anon_pub; struct SearchRequestEntry *sre; - GNUNET_assert (NULL == sc->mq); - if (GNUNET_FS_uri_test_ksk (sc->uri)) - { - GNUNET_assert (0 != sc->uri->data.ksk.keywordCount); - anon = GNUNET_CRYPTO_ecdsa_key_get_anonymous (); - GNUNET_CRYPTO_ecdsa_key_get_public (anon, &anon_pub); - sc->requests - = GNUNET_new_array (sc->uri->data.ksk.keywordCount, - struct SearchRequestEntry); - - for (i = 0; i < sc->uri->data.ksk.keywordCount; i++) + GNUNET_assert(NULL == sc->mq); + if (GNUNET_FS_uri_test_ksk(sc->uri)) { - keyword = &sc->uri->data.ksk.keywords[i][1]; - sre = &sc->requests[i]; - sre->keyword = GNUNET_strdup (keyword); - GNUNET_CRYPTO_ecdsa_public_key_derive (&anon_pub, - keyword, - "fs-ublock", - &sre->dpub); - GNUNET_CRYPTO_hash (&sre->dpub, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey), - &sre->uquery); - sre->mandatory = (sc->uri->data.ksk.keywords[i][0] == '+'); - if (sre->mandatory) - sc->mandatory_count++; - sre->results = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_NO); + GNUNET_assert(0 != sc->uri->data.ksk.keywordCount); + anon = GNUNET_CRYPTO_ecdsa_key_get_anonymous(); + GNUNET_CRYPTO_ecdsa_key_get_public(anon, &anon_pub); + sc->requests + = GNUNET_new_array(sc->uri->data.ksk.keywordCount, + struct SearchRequestEntry); + + for (i = 0; i < sc->uri->data.ksk.keywordCount; i++) + { + keyword = &sc->uri->data.ksk.keywords[i][1]; + sre = &sc->requests[i]; + sre->keyword = GNUNET_strdup(keyword); + GNUNET_CRYPTO_ecdsa_public_key_derive(&anon_pub, + keyword, + "fs-ublock", + &sre->dpub); + GNUNET_CRYPTO_hash(&sre->dpub, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey), + &sre->uquery); + sre->mandatory = (sc->uri->data.ksk.keywords[i][0] == '+'); + if (sre->mandatory) + sc->mandatory_count++; + sre->results = GNUNET_CONTAINER_multihashmap_create(4, GNUNET_NO); + } + GNUNET_CONTAINER_multihashmap_iterate(sc->master_result_map, + &update_sre_result_maps, + sc); } - GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map, - &update_sre_result_maps, - sc); - } - GNUNET_assert (NULL == sc->task); - do_reconnect (sc); + GNUNET_assert(NULL == sc->task); + do_reconnect(sc); if (NULL == sc->mq) - { - GNUNET_SCHEDULER_cancel (sc->task); - sc->task = NULL; - return GNUNET_SYSERR; - } + { + GNUNET_SCHEDULER_cancel(sc->task); + sc->task = NULL; + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1445,25 +1457,25 @@ GNUNET_FS_search_start_searching_ (struct GNUNET_FS_SearchContext *sc) * @return #GNUNET_OK */ static int -search_result_freeze_probes (void *cls, - const struct GNUNET_HashCode *key, - void *value) +search_result_freeze_probes(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GNUNET_FS_SearchResult *sr = value; if (NULL != sr->probe_ctx) - { - GNUNET_FS_download_stop (sr->probe_ctx, GNUNET_YES); - sr->probe_ctx = NULL; - GNUNET_FS_stop_probe_ping_task_ (sr); - } + { + GNUNET_FS_download_stop(sr->probe_ctx, GNUNET_YES); + sr->probe_ctx = NULL; + GNUNET_FS_stop_probe_ping_task_(sr); + } if (NULL != sr->probe_cancel_task) - { - GNUNET_SCHEDULER_cancel (sr->probe_cancel_task); - sr->probe_cancel_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(sr->probe_cancel_task); + sr->probe_cancel_task = NULL; + } if (NULL != sr->update_search) - GNUNET_FS_search_pause (sr->update_search); + GNUNET_FS_search_pause(sr->update_search); return GNUNET_OK; } @@ -1477,15 +1489,15 @@ search_result_freeze_probes (void *cls, * @return #GNUNET_OK */ static int -search_result_resume_probes (void *cls, - const struct GNUNET_HashCode * key, - void *value) +search_result_resume_probes(void *cls, + const struct GNUNET_HashCode * key, + void *value) { struct GNUNET_FS_SearchResult *sr = value; - GNUNET_FS_search_start_probe_ (sr); + GNUNET_FS_search_start_probe_(sr); if (NULL != sr->update_search) - GNUNET_FS_search_continue (sr->update_search); + GNUNET_FS_search_continue(sr->update_search); return GNUNET_OK; } @@ -1499,40 +1511,40 @@ search_result_resume_probes (void *cls, * @return #GNUNET_OK */ static int -search_result_suspend (void *cls, - const struct GNUNET_HashCode *key, - void *value) +search_result_suspend(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GNUNET_FS_SearchContext *sc = cls; struct GNUNET_FS_SearchResult *sr = value; struct GNUNET_FS_ProgressInfo pi; if (NULL != sr->download) - { - GNUNET_FS_download_signal_suspend_ (sr->download); - sr->download = NULL; - } + { + GNUNET_FS_download_signal_suspend_(sr->download); + sr->download = NULL; + } if (NULL != sr->update_search) - { - GNUNET_FS_search_signal_suspend_ (sr->update_search); - sr->update_search = NULL; - } - GNUNET_FS_search_stop_probe_ (sr); + { + GNUNET_FS_search_signal_suspend_(sr->update_search); + sr->update_search = NULL; + } + GNUNET_FS_search_stop_probe_(sr); if (0 == sr->mandatory_missing) - { - /* client is aware of search result, notify about suspension event */ - pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_SUSPEND; - pi.value.search.specifics.result_suspend.cctx = sr->client_info; - pi.value.search.specifics.result_suspend.meta = sr->meta; - pi.value.search.specifics.result_suspend.uri = sr->uri; - sr->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc); - } - GNUNET_break (NULL == sr->client_info); - GNUNET_free_non_null (sr->serialization); - GNUNET_FS_uri_destroy (sr->uri); - GNUNET_CONTAINER_meta_data_destroy (sr->meta); - GNUNET_free_non_null (sr->keyword_bitmap); - GNUNET_free (sr); + { + /* client is aware of search result, notify about suspension event */ + pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_SUSPEND; + pi.value.search.specifics.result_suspend.cctx = sr->client_info; + pi.value.search.specifics.result_suspend.meta = sr->meta; + pi.value.search.specifics.result_suspend.uri = sr->uri; + sr->client_info = GNUNET_FS_search_make_status_(&pi, sc->h, sc); + } + GNUNET_break(NULL == sr->client_info); + GNUNET_free_non_null(sr->serialization); + GNUNET_FS_uri_destroy(sr->uri); + GNUNET_CONTAINER_meta_data_destroy(sr->meta); + GNUNET_free_non_null(sr->keyword_bitmap); + GNUNET_free(sr); return GNUNET_OK; } @@ -1544,43 +1556,43 @@ search_result_suspend (void *cls, * @param cls the `struct GNUNET_FS_SearchContext` to signal for */ void -GNUNET_FS_search_signal_suspend_ (void *cls) +GNUNET_FS_search_signal_suspend_(void *cls) { struct GNUNET_FS_SearchContext *sc = cls; struct GNUNET_FS_ProgressInfo pi; unsigned int i; - GNUNET_FS_end_top (sc->h, sc->top); - GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map, - &search_result_suspend, sc); + GNUNET_FS_end_top(sc->h, sc->top); + GNUNET_CONTAINER_multihashmap_iterate(sc->master_result_map, + &search_result_suspend, sc); pi.status = GNUNET_FS_STATUS_SEARCH_SUSPEND; - sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc); - GNUNET_break (NULL == sc->client_info); + sc->client_info = GNUNET_FS_search_make_status_(&pi, sc->h, sc); + GNUNET_break(NULL == sc->client_info); if (sc->task != NULL) - { - GNUNET_SCHEDULER_cancel (sc->task); - sc->task = NULL; - } + { + GNUNET_SCHEDULER_cancel(sc->task); + sc->task = NULL; + } if (NULL != sc->mq) - { - GNUNET_MQ_destroy (sc->mq); - sc->mq = NULL; - } - GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map); + { + GNUNET_MQ_destroy(sc->mq); + sc->mq = NULL; + } + GNUNET_CONTAINER_multihashmap_destroy(sc->master_result_map); if (NULL != sc->requests) - { - GNUNET_assert (GNUNET_FS_uri_test_ksk (sc->uri)); - for (i = 0; i < sc->uri->data.ksk.keywordCount; i++) { - GNUNET_CONTAINER_multihashmap_destroy (sc->requests[i].results); - GNUNET_free (sc->requests[i].keyword); + GNUNET_assert(GNUNET_FS_uri_test_ksk(sc->uri)); + for (i = 0; i < sc->uri->data.ksk.keywordCount; i++) + { + GNUNET_CONTAINER_multihashmap_destroy(sc->requests[i].results); + GNUNET_free(sc->requests[i].keyword); + } } - } - GNUNET_free_non_null (sc->requests); - GNUNET_free_non_null (sc->emsg); - GNUNET_FS_uri_destroy (sc->uri); - GNUNET_free_non_null (sc->serialization); - GNUNET_free (sc); + GNUNET_free_non_null(sc->requests); + GNUNET_free_non_null(sc->emsg); + GNUNET_FS_uri_destroy(sc->uri); + GNUNET_free_non_null(sc->serialization); + GNUNET_free(sc); } @@ -1596,16 +1608,16 @@ GNUNET_FS_search_signal_suspend_ (void *cls) * @return context that can be used to control the search */ struct GNUNET_FS_SearchContext * -GNUNET_FS_search_start (struct GNUNET_FS_Handle *h, - const struct GNUNET_FS_Uri *uri, uint32_t anonymity, - enum GNUNET_FS_SearchOptions options, void *cctx) +GNUNET_FS_search_start(struct GNUNET_FS_Handle *h, + const struct GNUNET_FS_Uri *uri, uint32_t anonymity, + enum GNUNET_FS_SearchOptions options, void *cctx) { struct GNUNET_FS_SearchContext *ret; - ret = search_start (h, uri, anonymity, options, cctx, NULL); + ret = search_start(h, uri, anonymity, options, cctx, NULL); if (NULL == ret) return NULL; - ret->top = GNUNET_FS_make_top (h, &GNUNET_FS_search_signal_suspend_, ret); + ret->top = GNUNET_FS_make_top(h, &GNUNET_FS_search_signal_suspend_, ret); return ret; } @@ -1616,28 +1628,28 @@ GNUNET_FS_search_start (struct GNUNET_FS_Handle *h, * @param sc context for the search that should be paused */ void -GNUNET_FS_search_pause (struct GNUNET_FS_SearchContext *sc) +GNUNET_FS_search_pause(struct GNUNET_FS_SearchContext *sc) { struct GNUNET_FS_ProgressInfo pi; if (NULL != sc->task) - { - GNUNET_SCHEDULER_cancel (sc->task); - sc->task = NULL; - } + { + GNUNET_SCHEDULER_cancel(sc->task); + sc->task = NULL; + } if (NULL != sc->mq) - { - GNUNET_MQ_destroy (sc->mq); - sc->mq = NULL; - } - GNUNET_FS_search_sync_ (sc); - GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map, - &search_result_freeze_probes, - sc); + { + GNUNET_MQ_destroy(sc->mq); + sc->mq = NULL; + } + GNUNET_FS_search_sync_(sc); + GNUNET_CONTAINER_multihashmap_iterate(sc->master_result_map, + &search_result_freeze_probes, + sc); pi.status = GNUNET_FS_STATUS_SEARCH_PAUSED; - sc->client_info = GNUNET_FS_search_make_status_ (&pi, - sc->h, - sc); + sc->client_info = GNUNET_FS_search_make_status_(&pi, + sc->h, + sc); } @@ -1647,18 +1659,18 @@ GNUNET_FS_search_pause (struct GNUNET_FS_SearchContext *sc) * @param sc context for the search that should be resumed */ void -GNUNET_FS_search_continue (struct GNUNET_FS_SearchContext *sc) +GNUNET_FS_search_continue(struct GNUNET_FS_SearchContext *sc) { struct GNUNET_FS_ProgressInfo pi; - GNUNET_assert (NULL == sc->mq); - GNUNET_assert (NULL == sc->task); - do_reconnect (sc); - GNUNET_FS_search_sync_ (sc); + GNUNET_assert(NULL == sc->mq); + GNUNET_assert(NULL == sc->task); + do_reconnect(sc); + GNUNET_FS_search_sync_(sc); pi.status = GNUNET_FS_STATUS_SEARCH_CONTINUED; - sc->client_info = GNUNET_FS_search_make_status_ (&pi, sc->h, sc); - GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map, - &search_result_resume_probes, sc); + sc->client_info = GNUNET_FS_search_make_status_(&pi, sc->h, sc); + GNUNET_CONTAINER_multihashmap_iterate(sc->master_result_map, + &search_result_resume_probes, sc); } @@ -1671,48 +1683,48 @@ GNUNET_FS_search_continue (struct GNUNET_FS_SearchContext *sc) * @return #GNUNET_OK */ static int -search_result_stop (void *cls, - const struct GNUNET_HashCode *key, - void *value) +search_result_stop(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GNUNET_FS_SearchContext *sc = cls; struct GNUNET_FS_SearchResult *sr = value; struct GNUNET_FS_ProgressInfo pi; - GNUNET_FS_search_stop_probe_ (sr); + GNUNET_FS_search_stop_probe_(sr); if (NULL != sr->download) - { - sr->download->search = NULL; - sr->download->top - = GNUNET_FS_make_top (sr->download->h, - &GNUNET_FS_download_signal_suspend_, - sr->download); - if (NULL != sr->download->serialization) { - GNUNET_FS_remove_sync_file_ (sc->h, - GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD, - sr->download->serialization); - GNUNET_free (sr->download->serialization); - sr->download->serialization = NULL; + sr->download->search = NULL; + sr->download->top + = GNUNET_FS_make_top(sr->download->h, + &GNUNET_FS_download_signal_suspend_, + sr->download); + if (NULL != sr->download->serialization) + { + GNUNET_FS_remove_sync_file_(sc->h, + GNUNET_FS_SYNC_PATH_CHILD_DOWNLOAD, + sr->download->serialization); + GNUNET_free(sr->download->serialization); + sr->download->serialization = NULL; + } + pi.status = GNUNET_FS_STATUS_DOWNLOAD_LOST_PARENT; + GNUNET_FS_download_make_status_(&pi, + sr->download); + GNUNET_FS_download_sync_(sr->download); + sr->download = NULL; } - pi.status = GNUNET_FS_STATUS_DOWNLOAD_LOST_PARENT; - GNUNET_FS_download_make_status_ (&pi, - sr->download); - GNUNET_FS_download_sync_ (sr->download); - sr->download = NULL; - } if (0 != sr->mandatory_missing) - { - /* client is unaware of search result as - it does not match required keywords */ - GNUNET_break (NULL == sr->client_info); - return GNUNET_OK; - } + { + /* client is unaware of search result as + it does not match required keywords */ + GNUNET_break(NULL == sr->client_info); + return GNUNET_OK; + } pi.status = GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED; pi.value.search.specifics.result_stopped.cctx = sr->client_info; pi.value.search.specifics.result_stopped.meta = sr->meta; pi.value.search.specifics.result_stopped.uri = sr->uri; - sr->client_info = GNUNET_FS_search_make_status_ (&pi, sr->h, sc); + sr->client_info = GNUNET_FS_search_make_status_(&pi, sr->h, sc); return GNUNET_OK; } @@ -1726,25 +1738,25 @@ search_result_stop (void *cls, * @return #GNUNET_OK */ static int -search_result_free (void *cls, - const struct GNUNET_HashCode *key, - void *value) +search_result_free(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GNUNET_FS_SearchResult *sr = value; if (NULL != sr->update_search) - { - GNUNET_FS_search_stop (sr->update_search); - GNUNET_assert (NULL == sr->update_search); - } - GNUNET_break (NULL == sr->probe_ctx); - GNUNET_break (NULL == sr->probe_cancel_task); - GNUNET_break (NULL == sr->client_info); - GNUNET_free_non_null (sr->serialization); - GNUNET_FS_uri_destroy (sr->uri); - GNUNET_CONTAINER_meta_data_destroy (sr->meta); - GNUNET_free_non_null (sr->keyword_bitmap); - GNUNET_free (sr); + { + GNUNET_FS_search_stop(sr->update_search); + GNUNET_assert(NULL == sr->update_search); + } + GNUNET_break(NULL == sr->probe_ctx); + GNUNET_break(NULL == sr->probe_cancel_task); + GNUNET_break(NULL == sr->client_info); + GNUNET_free_non_null(sr->serialization); + GNUNET_FS_uri_destroy(sr->uri); + GNUNET_CONTAINER_meta_data_destroy(sr->meta); + GNUNET_free_non_null(sr->keyword_bitmap); + GNUNET_free(sr); return GNUNET_OK; } @@ -1755,60 +1767,60 @@ search_result_free (void *cls, * @param sc context for the search that should be stopped */ void -GNUNET_FS_search_stop (struct GNUNET_FS_SearchContext *sc) +GNUNET_FS_search_stop(struct GNUNET_FS_SearchContext *sc) { struct GNUNET_FS_ProgressInfo pi; unsigned int i; if (NULL != sc->top) - GNUNET_FS_end_top (sc->h, sc->top); - GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map, - &search_result_stop, - sc); + GNUNET_FS_end_top(sc->h, sc->top); + GNUNET_CONTAINER_multihashmap_iterate(sc->master_result_map, + &search_result_stop, + sc); if (NULL != sc->psearch_result) sc->psearch_result->update_search = NULL; if (NULL != sc->serialization) - { - GNUNET_FS_remove_sync_file_ (sc->h, + { + GNUNET_FS_remove_sync_file_(sc->h, + (NULL != sc->psearch_result) + ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH + : GNUNET_FS_SYNC_PATH_MASTER_SEARCH, + sc->serialization); + GNUNET_FS_remove_sync_dir_(sc->h, (NULL != sc->psearch_result) ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH : GNUNET_FS_SYNC_PATH_MASTER_SEARCH, sc->serialization); - GNUNET_FS_remove_sync_dir_ (sc->h, - (NULL != sc->psearch_result) - ? GNUNET_FS_SYNC_PATH_CHILD_SEARCH - : GNUNET_FS_SYNC_PATH_MASTER_SEARCH, - sc->serialization); - GNUNET_free (sc->serialization); - } + GNUNET_free(sc->serialization); + } pi.status = GNUNET_FS_STATUS_SEARCH_STOPPED; - sc->client_info = GNUNET_FS_search_make_status_ (&pi, - sc->h, - sc); - GNUNET_break (NULL == sc->client_info); + sc->client_info = GNUNET_FS_search_make_status_(&pi, + sc->h, + sc); + GNUNET_break(NULL == sc->client_info); if (NULL != sc->task) - { - GNUNET_SCHEDULER_cancel (sc->task); - sc->task = NULL; - } + { + GNUNET_SCHEDULER_cancel(sc->task); + sc->task = NULL; + } if (NULL != sc->mq) - { - GNUNET_MQ_destroy (sc->mq); - sc->mq = NULL; - } - GNUNET_CONTAINER_multihashmap_iterate (sc->master_result_map, - &search_result_free, sc); - GNUNET_CONTAINER_multihashmap_destroy (sc->master_result_map); + { + GNUNET_MQ_destroy(sc->mq); + sc->mq = NULL; + } + GNUNET_CONTAINER_multihashmap_iterate(sc->master_result_map, + &search_result_free, sc); + GNUNET_CONTAINER_multihashmap_destroy(sc->master_result_map); if (NULL != sc->requests) - { - GNUNET_assert (GNUNET_FS_uri_test_ksk (sc->uri)); - for (i = 0; i < sc->uri->data.ksk.keywordCount; i++) - GNUNET_CONTAINER_multihashmap_destroy (sc->requests[i].results); - } - GNUNET_free_non_null (sc->requests); - GNUNET_free_non_null (sc->emsg); - GNUNET_FS_uri_destroy (sc->uri); - GNUNET_free (sc); + { + GNUNET_assert(GNUNET_FS_uri_test_ksk(sc->uri)); + for (i = 0; i < sc->uri->data.ksk.keywordCount; i++) + GNUNET_CONTAINER_multihashmap_destroy(sc->requests[i].results); + } + GNUNET_free_non_null(sc->requests); + GNUNET_free_non_null(sc->emsg); + GNUNET_FS_uri_destroy(sc->uri); + GNUNET_free(sc); } /* end of fs_search.c */ diff --git a/src/fs/fs_sharetree.c b/src/fs/fs_sharetree.c index 282d7796a..a2cc37170 100644 --- a/src/fs/fs_sharetree.c +++ b/src/fs/fs_sharetree.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_sharetree.c @@ -34,9 +34,7 @@ * Entry for each unique keyword to track how often * it occured. Contains the keyword and the counter. */ -struct KeywordCounter -{ - +struct KeywordCounter { /** * This is a doubly-linked list */ @@ -56,16 +54,13 @@ struct KeywordCounter * How many files have this keyword? */ unsigned int count; - }; /** * Aggregate information we keep for meta data in each directory. */ -struct MetaCounter -{ - +struct MetaCounter { /** * This is a doubly-linked list */ @@ -111,7 +106,6 @@ struct MetaCounter * (type and format do not have to match). */ unsigned int count; - }; @@ -119,9 +113,7 @@ struct MetaCounter * A structure that forms a singly-linked list that serves as a stack * for metadata-processing function. */ -struct TrimContext -{ - +struct TrimContext { /** * Map from the hash over the keyword to an 'struct KeywordCounter *' * counter that says how often this keyword was @@ -145,7 +137,6 @@ struct TrimContext * Number of times an item has to be found to be moved to the parent. */ unsigned int move_threshold; - }; @@ -158,26 +149,26 @@ struct TrimContext * @return always GNUNET_OK */ static int -add_to_keyword_counter (void *cls, const char *keyword, int is_mandatory) +add_to_keyword_counter(void *cls, const char *keyword, int is_mandatory) { struct GNUNET_CONTAINER_MultiHashMap *mcm = cls; struct KeywordCounter *cnt; struct GNUNET_HashCode hc; size_t klen; - klen = strlen (keyword) + 1; - GNUNET_CRYPTO_hash (keyword, klen - 1, &hc); - cnt = GNUNET_CONTAINER_multihashmap_get (mcm, &hc); + klen = strlen(keyword) + 1; + GNUNET_CRYPTO_hash(keyword, klen - 1, &hc); + cnt = GNUNET_CONTAINER_multihashmap_get(mcm, &hc); if (cnt == NULL) - { - cnt = GNUNET_malloc (sizeof (struct KeywordCounter) + klen); - cnt->value = (const char *) &cnt[1]; - GNUNET_memcpy (&cnt[1], keyword, klen); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (mcm, - &hc, cnt, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - } + { + cnt = GNUNET_malloc(sizeof(struct KeywordCounter) + klen); + cnt->value = (const char *)&cnt[1]; + GNUNET_memcpy(&cnt[1], keyword, klen); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(mcm, + &hc, cnt, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + } cnt->count++; return GNUNET_OK; } @@ -201,30 +192,30 @@ add_to_keyword_counter (void *cls, const char *keyword, int is_mandatory) * @return 0 to continue extracting / iterating */ static int -add_to_meta_counter (void *cls, const char *plugin_name, - enum EXTRACTOR_MetaType type, enum EXTRACTOR_MetaFormat format, - const char *data_mime_type, const char *data, size_t data_len) +add_to_meta_counter(void *cls, const char *plugin_name, + enum EXTRACTOR_MetaType type, enum EXTRACTOR_MetaFormat format, + const char *data_mime_type, const char *data, size_t data_len) { struct GNUNET_CONTAINER_MultiHashMap *map = cls; struct GNUNET_HashCode key; struct MetaCounter *cnt; - GNUNET_CRYPTO_hash (data, data_len, &key); - cnt = GNUNET_CONTAINER_multihashmap_get (map, &key); + GNUNET_CRYPTO_hash(data, data_len, &key); + cnt = GNUNET_CONTAINER_multihashmap_get(map, &key); if (NULL == cnt) - { - cnt = GNUNET_new (struct MetaCounter); - cnt->data = data; - cnt->data_size = data_len; - cnt->plugin_name = plugin_name; - cnt->type = type; - cnt->format = format; - cnt->data_mime_type = data_mime_type; - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (map, - &key, cnt, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - } + { + cnt = GNUNET_new(struct MetaCounter); + cnt->data = data; + cnt->data_size = data_len; + cnt->plugin_name = plugin_name; + cnt->type = type; + cnt->format = format; + cnt->data_mime_type = data_mime_type; + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(map, + &key, cnt, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + } cnt->count++; return 0; } @@ -239,21 +230,21 @@ add_to_meta_counter (void *cls, const char *plugin_name, * @return always GNUNET_OK */ static int -remove_high_frequency_keywords (void *cls, const char *keyword, int is_mandatory) +remove_high_frequency_keywords(void *cls, const char *keyword, int is_mandatory) { struct TrimContext *tc = cls; struct KeywordCounter *counter; struct GNUNET_HashCode hc; size_t klen; - klen = strlen (keyword) + 1; - GNUNET_CRYPTO_hash (keyword, klen - 1, &hc); - counter = GNUNET_CONTAINER_multihashmap_get (tc->keywordcounter, &hc); - GNUNET_assert (NULL != counter); + klen = strlen(keyword) + 1; + GNUNET_CRYPTO_hash(keyword, klen - 1, &hc); + counter = GNUNET_CONTAINER_multihashmap_get(tc->keywordcounter, &hc); + GNUNET_assert(NULL != counter); if (counter->count < tc->move_threshold) return GNUNET_OK; - GNUNET_FS_uri_ksk_remove_keyword (tc->pos->ksk_uri, - counter->value); + GNUNET_FS_uri_ksk_remove_keyword(tc->pos->ksk_uri, + counter->value); return GNUNET_OK; } @@ -268,23 +259,23 @@ remove_high_frequency_keywords (void *cls, const char *keyword, int is_mandatory * @return GNUNET_YES (always) */ static int -migrate_and_drop_keywords (void *cls, const struct GNUNET_HashCode * key, void *value) +migrate_and_drop_keywords(void *cls, const struct GNUNET_HashCode * key, void *value) { struct TrimContext *tc = cls; struct KeywordCounter *counter = value; if (counter->count >= tc->move_threshold) - { - if (NULL == tc->pos->ksk_uri) - tc->pos->ksk_uri = GNUNET_FS_uri_ksk_create_from_args (1, &counter->value); - else - GNUNET_FS_uri_ksk_add_keyword (tc->pos->ksk_uri, counter->value, GNUNET_NO); - } - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (tc->keywordcounter, - key, - counter)); - GNUNET_free (counter); + { + if (NULL == tc->pos->ksk_uri) + tc->pos->ksk_uri = GNUNET_FS_uri_ksk_create_from_args(1, &counter->value); + else + GNUNET_FS_uri_ksk_add_keyword(tc->pos->ksk_uri, counter->value, GNUNET_NO); + } + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(tc->keywordcounter, + key, + counter)); + GNUNET_free(counter); return GNUNET_YES; } @@ -299,27 +290,27 @@ migrate_and_drop_keywords (void *cls, const struct GNUNET_HashCode * key, void * * @return GNUNET_YES (always) */ static int -migrate_and_drop_metadata (void *cls, const struct GNUNET_HashCode * key, void *value) +migrate_and_drop_metadata(void *cls, const struct GNUNET_HashCode * key, void *value) { struct TrimContext *tc = cls; struct MetaCounter *counter = value; if (counter->count >= tc->move_threshold) - { - if (NULL == tc->pos->meta) - tc->pos->meta = GNUNET_CONTAINER_meta_data_create (); - GNUNET_CONTAINER_meta_data_insert (tc->pos->meta, - counter->plugin_name, - counter->type, - counter->format, - counter->data_mime_type, counter->data, - counter->data_size); - } - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (tc->metacounter, - key, - counter)); - GNUNET_free (counter); + { + if (NULL == tc->pos->meta) + tc->pos->meta = GNUNET_CONTAINER_meta_data_create(); + GNUNET_CONTAINER_meta_data_insert(tc->pos->meta, + counter->plugin_name, + counter->type, + counter->format, + counter->data_mime_type, counter->data, + counter->data_size); + } + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(tc->metacounter, + key, + counter)); + GNUNET_free(counter); return GNUNET_YES; } @@ -332,8 +323,8 @@ migrate_and_drop_metadata (void *cls, const struct GNUNET_HashCode * key, void * * @param tree tree to trim */ static void -share_tree_trim (struct TrimContext *tc, - struct GNUNET_FS_ShareTreeItem *tree) +share_tree_trim(struct TrimContext *tc, + struct GNUNET_FS_ShareTreeItem *tree) { struct GNUNET_FS_ShareTreeItem *pos; unsigned int num_children; @@ -341,64 +332,64 @@ share_tree_trim (struct TrimContext *tc, /* first, trim all children */ num_children = 0; for (pos = tree->children_head; NULL != pos; pos = pos->next) - { - share_tree_trim (tc, pos); - num_children++; - } + { + share_tree_trim(tc, pos); + num_children++; + } /* consider adding filename to directory meta data */ if (tree->is_directory == GNUNET_YES) - { - const char *user = getenv ("USER"); - if ( (user == NULL) || - (0 != strncasecmp (user, tree->short_filename, strlen(user)))) { - /* only use filename if it doesn't match $USER */ - if (NULL == tree->meta) - tree->meta = GNUNET_CONTAINER_meta_data_create (); - GNUNET_CONTAINER_meta_data_insert (tree->meta, "", - EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME, - EXTRACTOR_METAFORMAT_UTF8, - "text/plain", tree->short_filename, - strlen (tree->short_filename) + 1); + const char *user = getenv("USER"); + if ((user == NULL) || + (0 != strncasecmp(user, tree->short_filename, strlen(user)))) + { + /* only use filename if it doesn't match $USER */ + if (NULL == tree->meta) + tree->meta = GNUNET_CONTAINER_meta_data_create(); + GNUNET_CONTAINER_meta_data_insert(tree->meta, "", + EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME, + EXTRACTOR_METAFORMAT_UTF8, + "text/plain", tree->short_filename, + strlen(tree->short_filename) + 1); + } } - } if (1 >= num_children) return; /* nothing to trim */ /* now, count keywords and meta data in children */ for (pos = tree->children_head; NULL != pos; pos = pos->next) - { - if (NULL != pos->meta) - GNUNET_CONTAINER_meta_data_iterate (pos->meta, &add_to_meta_counter, tc->metacounter); - if (NULL != pos->ksk_uri) - GNUNET_FS_uri_ksk_get_keywords (pos->ksk_uri, &add_to_keyword_counter, tc->keywordcounter); - } + { + if (NULL != pos->meta) + GNUNET_CONTAINER_meta_data_iterate(pos->meta, &add_to_meta_counter, tc->metacounter); + if (NULL != pos->ksk_uri) + GNUNET_FS_uri_ksk_get_keywords(pos->ksk_uri, &add_to_keyword_counter, tc->keywordcounter); + } /* calculate threshold for moving keywords / meta data */ tc->move_threshold = 1 + (num_children / 2); /* remove high-frequency keywords from children */ for (pos = tree->children_head; NULL != pos; pos = pos->next) - { - tc->pos = pos; - if (NULL != pos->ksk_uri) { - struct GNUNET_FS_Uri *ksk_uri_copy = GNUNET_FS_uri_dup (pos->ksk_uri); - GNUNET_FS_uri_ksk_get_keywords (ksk_uri_copy, &remove_high_frequency_keywords, tc); - GNUNET_FS_uri_destroy (ksk_uri_copy); + tc->pos = pos; + if (NULL != pos->ksk_uri) + { + struct GNUNET_FS_Uri *ksk_uri_copy = GNUNET_FS_uri_dup(pos->ksk_uri); + GNUNET_FS_uri_ksk_get_keywords(ksk_uri_copy, &remove_high_frequency_keywords, tc); + GNUNET_FS_uri_destroy(ksk_uri_copy); + } } - } /* add high-frequency meta data and keywords to parent */ tc->pos = tree; - GNUNET_CONTAINER_multihashmap_iterate (tc->keywordcounter, - &migrate_and_drop_keywords, - tc); - GNUNET_CONTAINER_multihashmap_iterate (tc->metacounter, - &migrate_and_drop_metadata, - tc); + GNUNET_CONTAINER_multihashmap_iterate(tc->keywordcounter, + &migrate_and_drop_keywords, + tc); + GNUNET_CONTAINER_multihashmap_iterate(tc->metacounter, + &migrate_and_drop_metadata, + tc); } @@ -409,17 +400,17 @@ share_tree_trim (struct TrimContext *tc, * @param toplevel toplevel directory in the tree, returned by the scanner */ void -GNUNET_FS_share_tree_trim (struct GNUNET_FS_ShareTreeItem *toplevel) +GNUNET_FS_share_tree_trim(struct GNUNET_FS_ShareTreeItem *toplevel) { struct TrimContext tc; if (toplevel == NULL) return; - tc.keywordcounter = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_NO); - tc.metacounter = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_NO); - share_tree_trim (&tc, toplevel); - GNUNET_CONTAINER_multihashmap_destroy (tc.keywordcounter); - GNUNET_CONTAINER_multihashmap_destroy (tc.metacounter); + tc.keywordcounter = GNUNET_CONTAINER_multihashmap_create(1024, GNUNET_NO); + tc.metacounter = GNUNET_CONTAINER_multihashmap_create(1024, GNUNET_NO); + share_tree_trim(&tc, toplevel); + GNUNET_CONTAINER_multihashmap_destroy(tc.keywordcounter); + GNUNET_CONTAINER_multihashmap_destroy(tc.metacounter); } @@ -429,23 +420,23 @@ GNUNET_FS_share_tree_trim (struct GNUNET_FS_ShareTreeItem *toplevel) * @param toplevel toplevel of the tree to be freed */ void -GNUNET_FS_share_tree_free (struct GNUNET_FS_ShareTreeItem *toplevel) +GNUNET_FS_share_tree_free(struct GNUNET_FS_ShareTreeItem *toplevel) { struct GNUNET_FS_ShareTreeItem *pos; while (NULL != (pos = toplevel->children_head)) - GNUNET_FS_share_tree_free (pos); + GNUNET_FS_share_tree_free(pos); if (NULL != toplevel->parent) - GNUNET_CONTAINER_DLL_remove (toplevel->parent->children_head, - toplevel->parent->children_tail, - toplevel); + GNUNET_CONTAINER_DLL_remove(toplevel->parent->children_head, + toplevel->parent->children_tail, + toplevel); if (NULL != toplevel->meta) - GNUNET_CONTAINER_meta_data_destroy (toplevel->meta); + GNUNET_CONTAINER_meta_data_destroy(toplevel->meta); if (NULL != toplevel->ksk_uri) - GNUNET_FS_uri_destroy (toplevel->ksk_uri); - GNUNET_free_non_null (toplevel->filename); - GNUNET_free_non_null (toplevel->short_filename); - GNUNET_free (toplevel); + GNUNET_FS_uri_destroy(toplevel->ksk_uri); + GNUNET_free_non_null(toplevel->filename); + GNUNET_free_non_null(toplevel->short_filename); + GNUNET_free(toplevel); } /* end fs_sharetree.c */ diff --git a/src/fs/fs_test_lib.c b/src/fs/fs_test_lib.c index abbda1ece..e3ab0ec88 100644 --- a/src/fs/fs_test_lib.c +++ b/src/fs/fs_test_lib.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_test_lib.c @@ -37,9 +37,7 @@ /** * Handle for a publishing operation started for testing FS. */ -struct TestPublishOperation -{ - +struct TestPublishOperation { /** * Handle for the operation to connect to the peer's 'fs' service. */ @@ -110,9 +108,7 @@ struct TestPublishOperation /** * Handle for a download operation started for testing FS. */ -struct TestDownloadOperation -{ - +struct TestDownloadOperation { /** * Handle for the operation to connect to the peer's 'fs' service. */ @@ -172,7 +168,6 @@ struct TestDownloadOperation * Verbosity level of the current operation. */ unsigned int verbose; - }; @@ -183,23 +178,23 @@ struct TestDownloadOperation * @param tc scheduler context (unused) */ static void -report_uri (void *cls) +report_uri(void *cls) { struct TestPublishOperation *po = cls; - GNUNET_FS_publish_stop (po->publish_context); - GNUNET_TESTBED_operation_done (po->fs_op); - po->publish_cont (po->publish_cont_cls, - po->publish_uri, - (GNUNET_YES == po->do_index) - ? po->publish_tmp_file - : NULL); - GNUNET_FS_uri_destroy (po->publish_uri); - if ( (GNUNET_YES != po->do_index) && - (NULL != po->publish_tmp_file) ) - (void) GNUNET_DISK_directory_remove (po->publish_tmp_file); - GNUNET_free_non_null (po->publish_tmp_file); - GNUNET_free (po); + GNUNET_FS_publish_stop(po->publish_context); + GNUNET_TESTBED_operation_done(po->fs_op); + po->publish_cont(po->publish_cont_cls, + po->publish_uri, + (GNUNET_YES == po->do_index) + ? po->publish_tmp_file + : NULL); + GNUNET_FS_uri_destroy(po->publish_uri); + if ((GNUNET_YES != po->do_index) && + (NULL != po->publish_tmp_file)) + (void)GNUNET_DISK_directory_remove(po->publish_tmp_file); + GNUNET_free_non_null(po->publish_tmp_file); + GNUNET_free(po); } @@ -209,19 +204,19 @@ report_uri (void *cls) * @param cls the publish operation context */ static void -publish_timeout (void *cls) +publish_timeout(void *cls) { struct TestPublishOperation *po = cls; po->publish_timeout_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Timeout while trying to publish data\n"); - GNUNET_TESTBED_operation_done (po->fs_op); - GNUNET_FS_publish_stop (po->publish_context); - po->publish_cont (po->publish_cont_cls, NULL, NULL); - (void) GNUNET_DISK_directory_remove (po->publish_tmp_file); - GNUNET_free_non_null (po->publish_tmp_file); - GNUNET_free (po); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Timeout while trying to publish data\n"); + GNUNET_TESTBED_operation_done(po->fs_op); + GNUNET_FS_publish_stop(po->publish_context); + po->publish_cont(po->publish_cont_cls, NULL, NULL); + (void)GNUNET_DISK_directory_remove(po->publish_tmp_file); + GNUNET_free_non_null(po->publish_tmp_file); + GNUNET_free(po); } @@ -232,37 +227,41 @@ publish_timeout (void *cls) * @param info information about the event */ static void * -publish_progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *info) +publish_progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *info) { struct TestPublishOperation *po = cls; switch (info->status) - { - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - GNUNET_SCHEDULER_cancel (po->publish_timeout_task); - po->publish_timeout_task = NULL; - po->publish_uri = - GNUNET_FS_uri_dup (info->value.publish.specifics.completed.chk_uri); - GNUNET_SCHEDULER_add_now (&report_uri, - po); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - if (po->verbose) - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Publishing at %llu/%llu bytes\n", - (unsigned long long) info->value.publish.completed, - (unsigned long long) info->value.publish.size); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - break; - case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: - if (po->verbose) - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Download at %llu/%llu bytes\n", - (unsigned long long) info->value.download.completed, - (unsigned long long) info->value.download.size); - break; - default: - break; - } + { + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + GNUNET_SCHEDULER_cancel(po->publish_timeout_task); + po->publish_timeout_task = NULL; + po->publish_uri = + GNUNET_FS_uri_dup(info->value.publish.specifics.completed.chk_uri); + GNUNET_SCHEDULER_add_now(&report_uri, + po); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + if (po->verbose) + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Publishing at %llu/%llu bytes\n", + (unsigned long long)info->value.publish.completed, + (unsigned long long)info->value.publish.size); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + break; + + case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: + if (po->verbose) + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Download at %llu/%llu bytes\n", + (unsigned long long)info->value.download.completed, + (unsigned long long)info->value.download.size); + break; + + default: + break; + } return NULL; } @@ -278,11 +277,11 @@ publish_progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *info) * @return number of bytes written to buf */ static size_t -file_generator (void *cls, - uint64_t offset, - size_t max, - void *buf, - char **emsg) +file_generator(void *cls, + uint64_t offset, + size_t max, + void *buf, + char **emsg) { uint32_t *publish_seed = cls; uint64_t pos; @@ -294,14 +293,14 @@ file_generator (void *cls, if (buf == NULL) return 0; for (pos = 0; pos < 8; pos++) - cbuf[pos] = (uint8_t) (offset >> pos * 8); + cbuf[pos] = (uint8_t)(offset >> pos * 8); for (pos = 8; pos < max; pos++) - { - mod = (255 - (offset / 1024 / 32)); - if (mod == 0) - mod = 1; - cbuf[pos] = (uint8_t) ((offset * (*publish_seed)) % mod); - } + { + mod = (255 - (offset / 1024 / 32)); + if (mod == 0) + mod = 1; + cbuf[pos] = (uint8_t)((offset * (*publish_seed)) % mod); + } return max; } @@ -316,16 +315,16 @@ file_generator (void *cls, * @return service handle to return in 'op_result', NULL on error */ static void * -publish_connect_adapter (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +publish_connect_adapter(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct TestPublishOperation *po = cls; - return GNUNET_FS_start (cfg, - "fs-test-publish", - &publish_progress_cb, po, - GNUNET_FS_FLAGS_NONE, - GNUNET_FS_OPTIONS_END); + return GNUNET_FS_start(cfg, + "fs-test-publish", + &publish_progress_cb, po, + GNUNET_FS_FLAGS_NONE, + GNUNET_FS_OPTIONS_END); } @@ -336,12 +335,12 @@ publish_connect_adapter (void *cls, * @param op_result unused (different for publish/download!) */ static void -fs_disconnect_adapter (void *cls, - void *op_result) +fs_disconnect_adapter(void *cls, + void *op_result) { struct GNUNET_FS_Handle *fs = op_result; - GNUNET_FS_stop (fs); + GNUNET_FS_stop(fs); } @@ -355,10 +354,10 @@ fs_disconnect_adapter (void *cls, * operation has executed successfully. */ static void -publish_fs_connect_complete_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg) +publish_fs_connect_complete_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg) { struct TestPublishOperation *po = cls; struct GNUNET_FS_FileInformation *fi; @@ -371,58 +370,58 @@ publish_fs_connect_complete_cb (void *cls, if (NULL == ca_result) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to connect to FS for publishing: %s\n", emsg); - po->publish_cont (po->publish_cont_cls, - NULL, NULL); - GNUNET_TESTBED_operation_done (po->fs_op); - GNUNET_free (po); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Failed to connect to FS for publishing: %s\n", emsg); + po->publish_cont(po->publish_cont_cls, + NULL, NULL); + GNUNET_TESTBED_operation_done(po->fs_op); + GNUNET_free(po); return; } po->fs = ca_result; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (CONTENT_LIFETIME); + bo.expiration_time = GNUNET_TIME_relative_to_absolute(CONTENT_LIFETIME); bo.anonymity_level = po->anonymity; bo.content_priority = 42; bo.replication_level = 1; if (GNUNET_YES == po->do_index) - { - po->publish_tmp_file = GNUNET_DISK_mktemp ("fs-test-publish-index"); - GNUNET_assert (po->publish_tmp_file != NULL); - fh = GNUNET_DISK_file_open (po->publish_tmp_file, - GNUNET_DISK_OPEN_WRITE | - GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE); - GNUNET_assert (NULL != fh); - off = 0; - while (off < po->size) { - bsize = GNUNET_MIN (sizeof (buf), po->size - off); - emsg = NULL; - GNUNET_assert (bsize == file_generator (&po->publish_seed, off, bsize, buf, &em)); - GNUNET_assert (em == NULL); - GNUNET_assert (bsize == GNUNET_DISK_file_write (fh, buf, bsize)); - off += bsize; + po->publish_tmp_file = GNUNET_DISK_mktemp("fs-test-publish-index"); + GNUNET_assert(po->publish_tmp_file != NULL); + fh = GNUNET_DISK_file_open(po->publish_tmp_file, + GNUNET_DISK_OPEN_WRITE | + GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE); + GNUNET_assert(NULL != fh); + off = 0; + while (off < po->size) + { + bsize = GNUNET_MIN(sizeof(buf), po->size - off); + emsg = NULL; + GNUNET_assert(bsize == file_generator(&po->publish_seed, off, bsize, buf, &em)); + GNUNET_assert(em == NULL); + GNUNET_assert(bsize == GNUNET_DISK_file_write(fh, buf, bsize)); + off += bsize; + } + GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fh)); + fi = GNUNET_FS_file_information_create_from_file(po->fs, po, + po->publish_tmp_file, + NULL, NULL, po->do_index, + &bo); + GNUNET_assert(NULL != fi); } - GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh)); - fi = GNUNET_FS_file_information_create_from_file (po->fs, po, - po->publish_tmp_file, - NULL, NULL, po->do_index, - &bo); - GNUNET_assert (NULL != fi); - } else - { - fi = GNUNET_FS_file_information_create_from_reader (po->fs, po, - po->size, - &file_generator, &po->publish_seed, - NULL, NULL, - po->do_index, &bo); - GNUNET_assert (NULL != fi); - } + { + fi = GNUNET_FS_file_information_create_from_reader(po->fs, po, + po->size, + &file_generator, &po->publish_seed, + NULL, NULL, + po->do_index, &bo); + GNUNET_assert(NULL != fi); + } po->publish_context = - GNUNET_FS_publish_start (po->fs, fi, NULL, NULL, NULL, - GNUNET_FS_PUBLISH_OPTION_NONE); + GNUNET_FS_publish_start(po->fs, fi, NULL, NULL, NULL, + GNUNET_FS_PUBLISH_OPTION_NONE); } @@ -442,15 +441,15 @@ publish_fs_connect_complete_cb (void *cls, * @param cont_cls closure for cont */ void -GNUNET_FS_TEST_publish (struct GNUNET_TESTBED_Peer *peer, - struct GNUNET_TIME_Relative timeout, uint32_t anonymity, - int do_index, uint64_t size, uint32_t seed, - unsigned int verbose, - GNUNET_FS_TEST_UriContinuation cont, void *cont_cls) +GNUNET_FS_TEST_publish(struct GNUNET_TESTBED_Peer *peer, + struct GNUNET_TIME_Relative timeout, uint32_t anonymity, + int do_index, uint64_t size, uint32_t seed, + unsigned int verbose, + GNUNET_FS_TEST_UriContinuation cont, void *cont_cls) { struct TestPublishOperation *po; - po = GNUNET_new (struct TestPublishOperation); + po = GNUNET_new(struct TestPublishOperation); po->publish_cont = cont; po->publish_cont_cls = cont_cls; po->publish_seed = seed; @@ -458,16 +457,16 @@ GNUNET_FS_TEST_publish (struct GNUNET_TESTBED_Peer *peer, po->size = size; po->verbose = verbose; po->do_index = do_index; - po->fs_op = GNUNET_TESTBED_service_connect (po, - peer, - "fs", - &publish_fs_connect_complete_cb, - po, - &publish_connect_adapter, - &fs_disconnect_adapter, - po); + po->fs_op = GNUNET_TESTBED_service_connect(po, + peer, + "fs", + &publish_fs_connect_complete_cb, + po, + &publish_connect_adapter, + &fs_disconnect_adapter, + po); po->publish_timeout_task = - GNUNET_SCHEDULER_add_delayed (timeout, &publish_timeout, po); + GNUNET_SCHEDULER_add_delayed(timeout, &publish_timeout, po); } @@ -480,20 +479,20 @@ GNUNET_FS_TEST_publish (struct GNUNET_TESTBED_Peer *peer, * @param cls the download operation context */ static void -download_timeout (void *cls) +download_timeout(void *cls) { struct TestDownloadOperation *dop = cls; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Timeout while trying to download file\n"); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Timeout while trying to download file\n"); dop->download_timeout_task = NULL; - GNUNET_FS_download_stop (dop->download_context, - GNUNET_YES); - GNUNET_SCHEDULER_add_now (dop->download_cont, - dop->download_cont_cls); - GNUNET_TESTBED_operation_done (dop->fs_op); - GNUNET_FS_uri_destroy (dop->uri); - GNUNET_free (dop); + GNUNET_FS_download_stop(dop->download_context, + GNUNET_YES); + GNUNET_SCHEDULER_add_now(dop->download_cont, + dop->download_cont_cls); + GNUNET_TESTBED_operation_done(dop->fs_op); + GNUNET_FS_uri_destroy(dop->uri); + GNUNET_free(dop); } @@ -503,17 +502,17 @@ download_timeout (void *cls) * @param cls the download operation context */ static void -report_success (void *cls) +report_success(void *cls) { struct TestDownloadOperation *dop = cls; - GNUNET_FS_download_stop (dop->download_context, - GNUNET_YES); - GNUNET_SCHEDULER_add_now (dop->download_cont, - dop->download_cont_cls); - GNUNET_TESTBED_operation_done (dop->fs_op); - GNUNET_FS_uri_destroy (dop->uri); - GNUNET_free (dop); + GNUNET_FS_download_stop(dop->download_context, + GNUNET_YES); + GNUNET_SCHEDULER_add_now(dop->download_cont, + dop->download_cont_cls); + GNUNET_TESTBED_operation_done(dop->fs_op); + GNUNET_FS_uri_destroy(dop->uri); + GNUNET_free(dop); } @@ -524,34 +523,37 @@ report_success (void *cls) * @param info information about the event */ static void * -download_progress_cb (void *cls, - const struct GNUNET_FS_ProgressInfo *info) +download_progress_cb(void *cls, + const struct GNUNET_FS_ProgressInfo *info) { struct TestDownloadOperation *dop = cls; switch (info->status) - { - case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: - if (dop->verbose) - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Download at %llu/%llu bytes\n", - (unsigned long long) info->value.download.completed, - (unsigned long long) info->value.download.size); - break; - case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED: - GNUNET_SCHEDULER_cancel (dop->download_timeout_task); - dop->download_timeout_task = NULL; - GNUNET_SCHEDULER_add_now (&report_success, dop); - break; - case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE: - case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE: - break; + { + case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: + if (dop->verbose) + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Download at %llu/%llu bytes\n", + (unsigned long long)info->value.download.completed, + (unsigned long long)info->value.download.size); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED: + GNUNET_SCHEDULER_cancel(dop->download_timeout_task); + dop->download_timeout_task = NULL; + GNUNET_SCHEDULER_add_now(&report_success, dop); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE: + case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE: + break; + /* FIXME: monitor data correctness during download progress */ /* FIXME: do performance reports given sufficient verbosity */ /* FIXME: advance timeout task to "immediate" on error */ - default: - break; - } + default: + break; + } return NULL; } @@ -566,16 +568,16 @@ download_progress_cb (void *cls, * @return service handle to return in 'op_result', NULL on error */ static void * -download_connect_adapter (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +download_connect_adapter(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct TestPublishOperation *po = cls; - return GNUNET_FS_start (cfg, - "fs-test-download", - &download_progress_cb, po, - GNUNET_FS_FLAGS_NONE, - GNUNET_FS_OPTIONS_END); + return GNUNET_FS_start(cfg, + "fs-test-download", + &download_progress_cb, po, + GNUNET_FS_FLAGS_NONE, + GNUNET_FS_OPTIONS_END); } @@ -589,19 +591,19 @@ download_connect_adapter (void *cls, * operation has executed successfully. */ static void -download_fs_connect_complete_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg) +download_fs_connect_complete_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg) { struct TestDownloadOperation *dop = cls; dop->fs = ca_result; - GNUNET_assert (NULL != dop->fs); + GNUNET_assert(NULL != dop->fs); dop->download_context = - GNUNET_FS_download_start (dop->fs, dop->uri, NULL, NULL, NULL, 0, dop->size, - dop->anonymity, GNUNET_FS_DOWNLOAD_OPTION_NONE, - NULL, NULL); + GNUNET_FS_download_start(dop->fs, dop->uri, NULL, NULL, NULL, 0, dop->size, + dop->anonymity, GNUNET_FS_DOWNLOAD_OPTION_NONE, + NULL, NULL); } @@ -619,33 +621,33 @@ download_fs_connect_complete_cb (void *cls, * @param cont_cls closure for cont */ void -GNUNET_FS_TEST_download (struct GNUNET_TESTBED_Peer *peer, - struct GNUNET_TIME_Relative timeout, - uint32_t anonymity, uint32_t seed, - const struct GNUNET_FS_Uri *uri, unsigned int verbose, - GNUNET_SCHEDULER_TaskCallback cont, void *cont_cls) +GNUNET_FS_TEST_download(struct GNUNET_TESTBED_Peer *peer, + struct GNUNET_TIME_Relative timeout, + uint32_t anonymity, uint32_t seed, + const struct GNUNET_FS_Uri *uri, unsigned int verbose, + GNUNET_SCHEDULER_TaskCallback cont, void *cont_cls) { struct TestDownloadOperation *dop; - dop = GNUNET_new (struct TestDownloadOperation); - dop->uri = GNUNET_FS_uri_dup (uri); - dop->size = GNUNET_FS_uri_chk_get_file_size (uri); + dop = GNUNET_new(struct TestDownloadOperation); + dop->uri = GNUNET_FS_uri_dup(uri); + dop->size = GNUNET_FS_uri_chk_get_file_size(uri); dop->verbose = verbose; dop->anonymity = anonymity; dop->download_cont = cont; dop->download_cont_cls = cont_cls; dop->download_seed = seed; - dop->fs_op = GNUNET_TESTBED_service_connect (dop, - peer, - "fs", - &download_fs_connect_complete_cb, - dop, - &download_connect_adapter, - &fs_disconnect_adapter, - dop); + dop->fs_op = GNUNET_TESTBED_service_connect(dop, + peer, + "fs", + &download_fs_connect_complete_cb, + dop, + &download_connect_adapter, + &fs_disconnect_adapter, + dop); dop->download_timeout_task = - GNUNET_SCHEDULER_add_delayed (timeout, &download_timeout, dop); + GNUNET_SCHEDULER_add_delayed(timeout, &download_timeout, dop); } diff --git a/src/fs/fs_test_lib.h b/src/fs/fs_test_lib.h index 4bf0c7caa..e1c43bea7 100644 --- a/src/fs/fs_test_lib.h +++ b/src/fs/fs_test_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_test_lib.h @@ -64,15 +64,15 @@ typedef void * @param cont_cls closure for @a cont */ void -GNUNET_FS_TEST_publish (struct GNUNET_TESTBED_Peer *peer, - struct GNUNET_TIME_Relative timeout, - uint32_t anonymity, - int do_index, - uint64_t size, - uint32_t seed, - unsigned int verbose, - GNUNET_FS_TEST_UriContinuation cont, - void *cont_cls); +GNUNET_FS_TEST_publish(struct GNUNET_TESTBED_Peer *peer, + struct GNUNET_TIME_Relative timeout, + uint32_t anonymity, + int do_index, + uint64_t size, + uint32_t seed, + unsigned int verbose, + GNUNET_FS_TEST_UriContinuation cont, + void *cont_cls); /** @@ -89,14 +89,14 @@ GNUNET_FS_TEST_publish (struct GNUNET_TESTBED_Peer *peer, * @param cont_cls closure for @a cont */ void -GNUNET_FS_TEST_download (struct GNUNET_TESTBED_Peer *peer, - struct GNUNET_TIME_Relative timeout, - uint32_t anonymity, - uint32_t seed, - const struct GNUNET_FS_Uri *uri, - unsigned int verbose, - GNUNET_SCHEDULER_TaskCallback cont, - void *cont_cls); +GNUNET_FS_TEST_download(struct GNUNET_TESTBED_Peer *peer, + struct GNUNET_TIME_Relative timeout, + uint32_t anonymity, + uint32_t seed, + const struct GNUNET_FS_Uri *uri, + unsigned int verbose, + GNUNET_SCHEDULER_TaskCallback cont, + void *cont_cls); diff --git a/src/fs/fs_tree.c b/src/fs/fs_tree.c index 203de3c7e..5d486a8c9 100644 --- a/src/fs/fs_tree.c +++ b/src/fs/fs_tree.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_tree.c * @brief Merkle-tree-ish-CHK file encoding for GNUnet @@ -32,9 +32,7 @@ * Context for an ECRS-based file encoder that computes * the Merkle-ish-CHK tree. */ -struct GNUNET_FS_TreeEncoder -{ - +struct GNUNET_FS_TreeEncoder { /** * Global FS context. */ @@ -123,7 +121,7 @@ struct GNUNET_FS_TreeEncoder * @return depth of the tree, always > 0. A depth of 1 means only a DBLOCK. */ unsigned int -GNUNET_FS_compute_depth (uint64_t flen) +GNUNET_FS_compute_depth(uint64_t flen) { unsigned int treeDepth; uint64_t fl; @@ -131,15 +129,15 @@ GNUNET_FS_compute_depth (uint64_t flen) treeDepth = 1; fl = DBLOCK_SIZE; while (fl < flen) - { - treeDepth++; - if (fl * CHK_PER_INODE < fl) { - /* integer overflow, this is a HUGE file... */ - return treeDepth; + treeDepth++; + if (fl * CHK_PER_INODE < fl) + { + /* integer overflow, this is a HUGE file... */ + return treeDepth; + } + fl = fl * CHK_PER_INODE; } - fl = fl * CHK_PER_INODE; - } return treeDepth; } @@ -154,7 +152,7 @@ GNUNET_FS_compute_depth (uint64_t flen) * @return number of bytes of payload a subtree of this depth may correspond to */ uint64_t -GNUNET_FS_tree_compute_tree_size (unsigned int depth) +GNUNET_FS_tree_compute_tree_size(unsigned int depth) { uint64_t rsize; unsigned int i; @@ -181,30 +179,30 @@ GNUNET_FS_tree_compute_tree_size (unsigned int depth) * @return size of the corresponding IBlock */ static uint16_t -GNUNET_FS_tree_compute_iblock_size (unsigned int depth, uint64_t end_offset) +GNUNET_FS_tree_compute_iblock_size(unsigned int depth, uint64_t end_offset) { unsigned int ret; uint64_t mod; uint64_t bds; - GNUNET_assert (depth > 0); - GNUNET_assert (end_offset > 0); - bds = GNUNET_FS_tree_compute_tree_size (depth); + GNUNET_assert(depth > 0); + GNUNET_assert(end_offset > 0); + bds = GNUNET_FS_tree_compute_tree_size(depth); mod = end_offset % bds; if (0 == mod) - { - /* we were triggered at the end of a full block */ - ret = CHK_PER_INODE; - } + { + /* we were triggered at the end of a full block */ + ret = CHK_PER_INODE; + } else - { - /* we were triggered at the end of the file */ - bds /= CHK_PER_INODE; - ret = mod / bds; - if (0 != mod % bds) - ret++; - } - return (uint16_t) (ret * sizeof (struct ContentHashKey)); + { + /* we were triggered at the end of the file */ + bds /= CHK_PER_INODE; + ret = mod / bds; + if (0 != mod % bds) + ret++; + } + return (uint16_t)(ret * sizeof(struct ContentHashKey)); } @@ -220,32 +218,32 @@ GNUNET_FS_tree_compute_iblock_size (unsigned int depth, uint64_t end_offset) * @return number of bytes stored in this node */ size_t -GNUNET_FS_tree_calculate_block_size (uint64_t fsize, uint64_t offset, - unsigned int depth) +GNUNET_FS_tree_calculate_block_size(uint64_t fsize, uint64_t offset, + unsigned int depth) { size_t ret; uint64_t rsize; uint64_t epos; unsigned int chks; - GNUNET_assert (fsize > 0); - GNUNET_assert (offset <= fsize); + GNUNET_assert(fsize > 0); + GNUNET_assert(offset <= fsize); if (depth == 0) - { - ret = DBLOCK_SIZE; - if ((offset + ret > fsize) || (offset + ret < offset)) - ret = (size_t) (fsize - offset); - return ret; - } - - rsize = GNUNET_FS_tree_compute_tree_size (depth - 1); + { + ret = DBLOCK_SIZE; + if ((offset + ret > fsize) || (offset + ret < offset)) + ret = (size_t)(fsize - offset); + return ret; + } + + rsize = GNUNET_FS_tree_compute_tree_size(depth - 1); epos = offset + rsize * CHK_PER_INODE; if ((epos < offset) || (epos > fsize)) epos = fsize; /* round up when computing #CHKs in our IBlock */ chks = (epos - offset + rsize - 1) / rsize; - GNUNET_assert (chks <= CHK_PER_INODE); - return chks * sizeof (struct ContentHashKey); + GNUNET_assert(chks <= CHK_PER_INODE); + return chks * sizeof(struct ContentHashKey); } @@ -267,16 +265,16 @@ GNUNET_FS_tree_calculate_block_size (uint64_t fsize, uint64_t offset, * @param cont function to call when done */ struct GNUNET_FS_TreeEncoder * -GNUNET_FS_tree_encoder_create (struct GNUNET_FS_Handle *h, uint64_t size, - void *cls, - GNUNET_FS_DataReader reader, - GNUNET_FS_TreeBlockProcessor proc, - GNUNET_FS_TreeProgressCallback progress, - GNUNET_SCHEDULER_TaskCallback cont) +GNUNET_FS_tree_encoder_create(struct GNUNET_FS_Handle *h, uint64_t size, + void *cls, + GNUNET_FS_DataReader reader, + GNUNET_FS_TreeBlockProcessor proc, + GNUNET_FS_TreeProgressCallback progress, + GNUNET_SCHEDULER_TaskCallback cont) { struct GNUNET_FS_TreeEncoder *te; - te = GNUNET_new (struct GNUNET_FS_TreeEncoder); + te = GNUNET_new(struct GNUNET_FS_TreeEncoder); te->h = h; te->size = size; te->cls = cls; @@ -284,14 +282,14 @@ GNUNET_FS_tree_encoder_create (struct GNUNET_FS_Handle *h, uint64_t size, te->proc = proc; te->progress = progress; te->cont = cont; - te->chk_tree_depth = GNUNET_FS_compute_depth (size); + te->chk_tree_depth = GNUNET_FS_compute_depth(size); te->chk_tree - = GNUNET_new_array (te->chk_tree_depth * CHK_PER_INODE, - struct ContentHashKey); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created tree encoder for file with %llu bytes and depth %u\n", - (unsigned long long) size, - te->chk_tree_depth); + = GNUNET_new_array(te->chk_tree_depth * CHK_PER_INODE, + struct ContentHashKey); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created tree encoder for file with %llu bytes and depth %u\n", + (unsigned long long)size, + te->chk_tree_depth); return te; } @@ -308,12 +306,12 @@ GNUNET_FS_tree_encoder_create (struct GNUNET_FS_Handle *h, uint64_t size, * @return (array of CHKs') offset in the above IBlock */ static unsigned int -compute_chk_offset (unsigned int depth, uint64_t end_offset) +compute_chk_offset(unsigned int depth, uint64_t end_offset) { uint64_t bds; unsigned int ret; - bds = GNUNET_FS_tree_compute_tree_size (depth); + bds = GNUNET_FS_tree_compute_tree_size(depth); if (depth > 0) end_offset--; /* round down since for depth > 0 offset is at the END of the block */ ret = end_offset / bds; @@ -329,7 +327,7 @@ compute_chk_offset (unsigned int depth, uint64_t end_offset) * @param te tree encoder to use */ void -GNUNET_FS_tree_encoder_next (struct GNUNET_FS_TreeEncoder *te) +GNUNET_FS_tree_encoder_next(struct GNUNET_FS_TreeEncoder *te) { struct ContentHashKey *mychk; const void *pt_block; @@ -340,77 +338,77 @@ GNUNET_FS_tree_encoder_next (struct GNUNET_FS_TreeEncoder *te) struct GNUNET_CRYPTO_SymmetricInitializationVector iv; unsigned int off; - GNUNET_assert (GNUNET_NO == te->in_next); + GNUNET_assert(GNUNET_NO == te->in_next); te->in_next = GNUNET_YES; if (te->chk_tree_depth == te->current_depth) - { - off = CHK_PER_INODE * (te->chk_tree_depth - 1); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "TE done, reading CHK `%s' from %u\n", - GNUNET_h2s (&te->chk_tree[off].query), off); - te->uri = GNUNET_new (struct GNUNET_FS_Uri); - te->uri->type = GNUNET_FS_URI_CHK; - te->uri->data.chk.chk = te->chk_tree[off]; - te->uri->data.chk.file_length = GNUNET_htonll (te->size); - te->in_next = GNUNET_NO; - te->cont (te->cls); - return; - } - if (0 == te->current_depth) - { - /* read DBLOCK */ - pt_size = GNUNET_MIN (DBLOCK_SIZE, te->size - te->publish_offset); - if (pt_size != - te->reader (te->cls, te->publish_offset, pt_size, iob, &te->emsg)) { + off = CHK_PER_INODE * (te->chk_tree_depth - 1); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "TE done, reading CHK `%s' from %u\n", + GNUNET_h2s(&te->chk_tree[off].query), off); + te->uri = GNUNET_new(struct GNUNET_FS_Uri); + te->uri->type = GNUNET_FS_URI_CHK; + te->uri->data.chk.chk = te->chk_tree[off]; + te->uri->data.chk.file_length = GNUNET_htonll(te->size); te->in_next = GNUNET_NO; - te->cont (te->cls); + te->cont(te->cls); return; } - pt_block = iob; - } + if (0 == te->current_depth) + { + /* read DBLOCK */ + pt_size = GNUNET_MIN(DBLOCK_SIZE, te->size - te->publish_offset); + if (pt_size != + te->reader(te->cls, te->publish_offset, pt_size, iob, &te->emsg)) + { + te->in_next = GNUNET_NO; + te->cont(te->cls); + return; + } + pt_block = iob; + } else - { - pt_size = - GNUNET_FS_tree_compute_iblock_size (te->current_depth, - te->publish_offset); - pt_block = &te->chk_tree[(te->current_depth - 1) * CHK_PER_INODE]; - } - off = compute_chk_offset (te->current_depth, te->publish_offset); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "TE is at offset %llu and depth %u with block size %u and target-CHK-offset %u\n", - (unsigned long long) te->publish_offset, te->current_depth, - (unsigned int) pt_size, (unsigned int) off); + { + pt_size = + GNUNET_FS_tree_compute_iblock_size(te->current_depth, + te->publish_offset); + pt_block = &te->chk_tree[(te->current_depth - 1) * CHK_PER_INODE]; + } + off = compute_chk_offset(te->current_depth, te->publish_offset); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "TE is at offset %llu and depth %u with block size %u and target-CHK-offset %u\n", + (unsigned long long)te->publish_offset, te->current_depth, + (unsigned int)pt_size, (unsigned int)off); mychk = &te->chk_tree[te->current_depth * CHK_PER_INODE + off]; - GNUNET_CRYPTO_hash (pt_block, pt_size, &mychk->key); - GNUNET_CRYPTO_hash_to_aes_key (&mychk->key, &sk, &iv); - GNUNET_CRYPTO_symmetric_encrypt (pt_block, pt_size, &sk, &iv, enc); - GNUNET_CRYPTO_hash (enc, pt_size, &mychk->query); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "TE calculates query to be `%s', stored at %u\n", - GNUNET_h2s (&mychk->query), - te->current_depth * CHK_PER_INODE + off); + GNUNET_CRYPTO_hash(pt_block, pt_size, &mychk->key); + GNUNET_CRYPTO_hash_to_aes_key(&mychk->key, &sk, &iv); + GNUNET_CRYPTO_symmetric_encrypt(pt_block, pt_size, &sk, &iv, enc); + GNUNET_CRYPTO_hash(enc, pt_size, &mychk->query); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "TE calculates query to be `%s', stored at %u\n", + GNUNET_h2s(&mychk->query), + te->current_depth * CHK_PER_INODE + off); if (NULL != te->proc) - te->proc (te->cls, mychk, te->publish_offset, te->current_depth, - (0 == - te->current_depth) ? GNUNET_BLOCK_TYPE_FS_DBLOCK : - GNUNET_BLOCK_TYPE_FS_IBLOCK, enc, pt_size); + te->proc(te->cls, mychk, te->publish_offset, te->current_depth, + (0 == + te->current_depth) ? GNUNET_BLOCK_TYPE_FS_DBLOCK : + GNUNET_BLOCK_TYPE_FS_IBLOCK, enc, pt_size); if (NULL != te->progress) - te->progress (te->cls, te->publish_offset, pt_block, pt_size, - te->current_depth); + te->progress(te->cls, te->publish_offset, pt_block, pt_size, + te->current_depth); if (0 == te->current_depth) - { - te->publish_offset += pt_size; - if ((te->publish_offset == te->size) || - (0 == te->publish_offset % (CHK_PER_INODE * DBLOCK_SIZE))) - te->current_depth++; - } + { + te->publish_offset += pt_size; + if ((te->publish_offset == te->size) || + (0 == te->publish_offset % (CHK_PER_INODE * DBLOCK_SIZE))) + te->current_depth++; + } else - { - if ((off == CHK_PER_INODE) || (te->publish_offset == te->size)) - te->current_depth++; - else - te->current_depth = 0; - } + { + if ((off == CHK_PER_INODE) || (te->publish_offset == te->size)) + te->current_depth++; + else + te->current_depth = 0; + } te->in_next = GNUNET_NO; } @@ -422,10 +420,10 @@ GNUNET_FS_tree_encoder_next (struct GNUNET_FS_TreeEncoder *te) * @return uri set to the resulting URI (if encoding finished), NULL otherwise */ struct GNUNET_FS_Uri * -GNUNET_FS_tree_encoder_get_uri (struct GNUNET_FS_TreeEncoder *te) +GNUNET_FS_tree_encoder_get_uri(struct GNUNET_FS_TreeEncoder *te) { if (NULL != te->uri) - return GNUNET_FS_uri_dup (te->uri); + return GNUNET_FS_uri_dup(te->uri); return NULL; } @@ -441,23 +439,23 @@ GNUNET_FS_tree_encoder_get_uri (struct GNUNET_FS_TreeEncoder *te) * both "*emsg" will be set to NULL). */ void -GNUNET_FS_tree_encoder_finish (struct GNUNET_FS_TreeEncoder *te, - char **emsg) +GNUNET_FS_tree_encoder_finish(struct GNUNET_FS_TreeEncoder *te, + char **emsg) { if (NULL != te->reader) - { - (void) te->reader (te->cls, UINT64_MAX, 0, 0, NULL); - te->reader = NULL; - } - GNUNET_assert (GNUNET_NO == te->in_next); + { + (void)te->reader(te->cls, UINT64_MAX, 0, 0, NULL); + te->reader = NULL; + } + GNUNET_assert(GNUNET_NO == te->in_next); if (NULL != te->uri) - GNUNET_FS_uri_destroy (te->uri); + GNUNET_FS_uri_destroy(te->uri); if (emsg != NULL) *emsg = te->emsg; else - GNUNET_free_non_null (te->emsg); - GNUNET_free (te->chk_tree); - GNUNET_free (te); + GNUNET_free_non_null(te->emsg); + GNUNET_free(te->chk_tree); + GNUNET_free(te); } /* end of fs_tree.c */ diff --git a/src/fs/fs_tree.h b/src/fs/fs_tree.h index 13a8603c5..7ce7e461b 100644 --- a/src/fs/fs_tree.h +++ b/src/fs/fs_tree.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_tree.h @@ -41,7 +41,7 @@ * @return depth of the tree, always > 0. A depth of 1 means only a DBLOCK. */ unsigned int -GNUNET_FS_compute_depth (uint64_t flen); +GNUNET_FS_compute_depth(uint64_t flen); /** @@ -54,7 +54,7 @@ GNUNET_FS_compute_depth (uint64_t flen); * @return number of bytes of payload a subtree of this depth may correspond to */ uint64_t -GNUNET_FS_tree_compute_tree_size (unsigned int depth); +GNUNET_FS_tree_compute_tree_size(unsigned int depth); /** @@ -69,8 +69,8 @@ GNUNET_FS_tree_compute_tree_size (unsigned int depth); * @return number of bytes stored in this node */ size_t -GNUNET_FS_tree_calculate_block_size (uint64_t fsize, uint64_t offset, - unsigned int depth); +GNUNET_FS_tree_calculate_block_size(uint64_t fsize, uint64_t offset, + unsigned int depth); /** @@ -138,11 +138,11 @@ typedef void (*GNUNET_FS_TreeProgressCallback) (void *cls, uint64_t offset, * @return tree encoder context */ struct GNUNET_FS_TreeEncoder * -GNUNET_FS_tree_encoder_create (struct GNUNET_FS_Handle *h, uint64_t size, - void *cls, GNUNET_FS_DataReader reader, - GNUNET_FS_TreeBlockProcessor proc, - GNUNET_FS_TreeProgressCallback progress, - GNUNET_SCHEDULER_TaskCallback cont); +GNUNET_FS_tree_encoder_create(struct GNUNET_FS_Handle *h, uint64_t size, + void *cls, GNUNET_FS_DataReader reader, + GNUNET_FS_TreeBlockProcessor proc, + GNUNET_FS_TreeProgressCallback progress, + GNUNET_SCHEDULER_TaskCallback cont); /** @@ -154,7 +154,7 @@ GNUNET_FS_tree_encoder_create (struct GNUNET_FS_Handle *h, uint64_t size, * @param te tree encoder to use */ void -GNUNET_FS_tree_encoder_next (struct GNUNET_FS_TreeEncoder *te); +GNUNET_FS_tree_encoder_next(struct GNUNET_FS_TreeEncoder *te); /** @@ -164,7 +164,7 @@ GNUNET_FS_tree_encoder_next (struct GNUNET_FS_TreeEncoder *te); * @return uri set to the resulting URI (if encoding finished), NULL otherwise */ struct GNUNET_FS_Uri * -GNUNET_FS_tree_encoder_get_uri (struct GNUNET_FS_TreeEncoder *te); +GNUNET_FS_tree_encoder_get_uri(struct GNUNET_FS_TreeEncoder *te); /** @@ -178,8 +178,8 @@ GNUNET_FS_tree_encoder_get_uri (struct GNUNET_FS_TreeEncoder *te); * both "*emsg" will be set to NULL). */ void -GNUNET_FS_tree_encoder_finish (struct GNUNET_FS_TreeEncoder *te, - char **emsg); +GNUNET_FS_tree_encoder_finish(struct GNUNET_FS_TreeEncoder *te, + char **emsg); #if 0 @@ -194,8 +194,8 @@ GNUNET_FS_tree_encoder_finish (struct GNUNET_FS_TreeEncoder *te, * @param size set to the size of the resume data */ void -GNUNET_FS_tree_encoder_resume_get_data (const struct GNUNET_FS_TreeEncoder *te, - void **data, size_t * size); +GNUNET_FS_tree_encoder_resume_get_data(const struct GNUNET_FS_TreeEncoder *te, + void **data, size_t * size); /** @@ -207,8 +207,8 @@ GNUNET_FS_tree_encoder_resume_get_data (const struct GNUNET_FS_TreeEncoder *te, * @param size the size of the resume data */ void -GNUNET_FS_tree_encoder_resume (struct GNUNET_FS_TreeEncoder *te, - const void *data, size_t size); +GNUNET_FS_tree_encoder_resume(struct GNUNET_FS_TreeEncoder *te, + const void *data, size_t size); #endif diff --git a/src/fs/fs_unindex.c b/src/fs/fs_unindex.c index b013902c9..be2dbbddd 100644 --- a/src/fs/fs_unindex.c +++ b/src/fs/fs_unindex.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_unindex.c @@ -48,26 +48,26 @@ * @return number of bytes copied to buf, 0 on error */ static size_t -unindex_reader (void *cls, - uint64_t offset, - size_t max, - void *buf, - char **emsg) +unindex_reader(void *cls, + uint64_t offset, + size_t max, + void *buf, + char **emsg) { struct GNUNET_FS_UnindexContext *uc = cls; size_t pt_size; - pt_size = GNUNET_MIN (max, uc->file_size - offset); - if (offset != GNUNET_DISK_file_seek (uc->fh, offset, GNUNET_DISK_SEEK_SET)) - { - *emsg = GNUNET_strdup (_("Failed to find given position in file")); - return 0; - } - if (pt_size != GNUNET_DISK_file_read (uc->fh, buf, pt_size)) - { - *emsg = GNUNET_strdup (_("Failed to read file")); - return 0; - } + pt_size = GNUNET_MIN(max, uc->file_size - offset); + if (offset != GNUNET_DISK_file_seek(uc->fh, offset, GNUNET_DISK_SEEK_SET)) + { + *emsg = GNUNET_strdup(_("Failed to find given position in file")); + return 0; + } + if (pt_size != GNUNET_DISK_file_read(uc->fh, buf, pt_size)) + { + *emsg = GNUNET_strdup(_("Failed to read file")); + return 0; + } return pt_size; } @@ -81,21 +81,21 @@ unindex_reader (void *cls, * @param offset where we are in the file (for progress) */ void -GNUNET_FS_unindex_make_status_ (struct GNUNET_FS_ProgressInfo *pi, - struct GNUNET_FS_UnindexContext *uc, - uint64_t offset) +GNUNET_FS_unindex_make_status_(struct GNUNET_FS_ProgressInfo *pi, + struct GNUNET_FS_UnindexContext *uc, + uint64_t offset) { pi->value.unindex.uc = uc; pi->value.unindex.cctx = uc->client_info; pi->value.unindex.filename = uc->filename; pi->value.unindex.size = uc->file_size; pi->value.unindex.eta = - GNUNET_TIME_calculate_eta (uc->start_time, offset, uc->file_size); + GNUNET_TIME_calculate_eta(uc->start_time, offset, uc->file_size); pi->value.unindex.duration = - GNUNET_TIME_absolute_get_duration (uc->start_time); + GNUNET_TIME_absolute_get_duration(uc->start_time); pi->value.unindex.completed = offset; pi->fsh = uc->h; - uc->client_info = uc->h->upcb (uc->h->upcb_cls, pi); + uc->client_info = uc->h->upcb(uc->h->upcb_cls, pi); } @@ -110,11 +110,11 @@ GNUNET_FS_unindex_make_status_ (struct GNUNET_FS_ProgressInfo *pi, * @param depth depth of the block in the tree, 0 for DBLOCK */ static void -unindex_progress (void *cls, - uint64_t offset, - const void *pt_block, - size_t pt_size, - unsigned int depth) +unindex_progress(void *cls, + uint64_t offset, + const void *pt_block, + size_t pt_size, + unsigned int depth) { struct GNUNET_FS_UnindexContext *uc = cls; struct GNUNET_FS_ProgressInfo pi; @@ -124,7 +124,7 @@ unindex_progress (void *cls, pi.value.unindex.specifics.progress.offset = offset; pi.value.unindex.specifics.progress.data_len = pt_size; pi.value.unindex.specifics.progress.depth = depth; - GNUNET_FS_unindex_make_status_ (&pi, uc, offset); + GNUNET_FS_unindex_make_status_(&pi, uc, offset); } @@ -135,14 +135,14 @@ unindex_progress (void *cls, * @param uc context for the failed unindexing operation */ static void -signal_unindex_error (struct GNUNET_FS_UnindexContext *uc) +signal_unindex_error(struct GNUNET_FS_UnindexContext *uc) { struct GNUNET_FS_ProgressInfo pi; pi.status = GNUNET_FS_STATUS_UNINDEX_ERROR; pi.value.unindex.eta = GNUNET_TIME_UNIT_FOREVER_REL; pi.value.unindex.specifics.error.message = uc->emsg; - GNUNET_FS_unindex_make_status_ (&pi, uc, 0); + GNUNET_FS_unindex_make_status_(&pi, uc, 0); } @@ -156,22 +156,22 @@ signal_unindex_error (struct GNUNET_FS_UnindexContext *uc) * @param msg NULL on success, otherwise an error message */ static void -process_cont (void *cls, - int success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +process_cont(void *cls, + int success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct GNUNET_FS_UnindexContext *uc = cls; if (success == GNUNET_SYSERR) - { - uc->emsg = GNUNET_strdup (msg); - signal_unindex_error (uc); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Datastore REMOVE operation succeeded\n"); - GNUNET_FS_tree_encoder_next (uc->tc); + { + uc->emsg = GNUNET_strdup(msg); + signal_unindex_error(uc); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Datastore REMOVE operation succeeded\n"); + GNUNET_FS_tree_encoder_next(uc->tc); } @@ -190,13 +190,13 @@ process_cont (void *cls, * @param block_size size of block (in bytes) */ static void -unindex_process (void *cls, - const struct ContentHashKey *chk, - uint64_t offset, - unsigned int depth, - enum GNUNET_BLOCK_Type type, - const void *block, - uint16_t block_size) +unindex_process(void *cls, + const struct ContentHashKey *chk, + uint64_t offset, + unsigned int depth, + enum GNUNET_BLOCK_Type type, + const void *block, + uint16_t block_size) { struct GNUNET_FS_UnindexContext *uc = cls; uint32_t size; @@ -204,21 +204,21 @@ unindex_process (void *cls, struct OnDemandBlock odb; if (type != GNUNET_BLOCK_TYPE_FS_DBLOCK) - { - size = block_size; - data = block; - } + { + size = block_size; + data = block; + } else /* on-demand encoded DBLOCK */ - { - size = sizeof (struct OnDemandBlock); - odb.offset = GNUNET_htonll (offset); - odb.file_id = uc->file_id; - data = &odb; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending REMOVE request to DATASTORE service\n"); - GNUNET_DATASTORE_remove (uc->dsh, &chk->query, size, data, -2, 1, - &process_cont, uc); + { + size = sizeof(struct OnDemandBlock); + odb.offset = GNUNET_htonll(offset); + odb.file_id = uc->file_id; + data = &odb; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending REMOVE request to DATASTORE service\n"); + GNUNET_DATASTORE_remove(uc->dsh, &chk->query, size, data, -2, 1, + &process_cont, uc); uc->chk = *chk; } @@ -231,24 +231,24 @@ unindex_process (void *cls, * @param msg the response */ static void -handle_unindex_response (void *cls, - const struct GNUNET_MessageHeader *msg) +handle_unindex_response(void *cls, + const struct GNUNET_MessageHeader *msg) { struct GNUNET_FS_UnindexContext *uc = cls; struct GNUNET_FS_ProgressInfo pi; if (NULL != uc->mq) - { - GNUNET_MQ_destroy (uc->mq); - uc->mq = NULL; - } + { + GNUNET_MQ_destroy(uc->mq); + uc->mq = NULL; + } uc->state = UNINDEX_STATE_COMPLETE; pi.status = GNUNET_FS_STATUS_UNINDEX_COMPLETED; pi.value.unindex.eta = GNUNET_TIME_UNIT_ZERO; - GNUNET_FS_unindex_sync_ (uc); - GNUNET_FS_unindex_make_status_ (&pi, - uc, - uc->file_size); + GNUNET_FS_unindex_sync_(uc); + GNUNET_FS_unindex_make_status_(&pi, + uc, + uc->file_size); } @@ -261,20 +261,20 @@ handle_unindex_response (void *cls, * @param error error code */ static void -unindex_mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +unindex_mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_FS_UnindexContext *uc = cls; if (NULL != uc->mq) - { - GNUNET_MQ_destroy (uc->mq); - uc->mq = NULL; - } + { + GNUNET_MQ_destroy(uc->mq); + uc->mq = NULL; + } uc->state = UNINDEX_STATE_ERROR; - uc->emsg = GNUNET_strdup (_("Error communicating with `fs' service.")); - GNUNET_FS_unindex_sync_ (uc); - signal_unindex_error (uc); + uc->emsg = GNUNET_strdup(_("Error communicating with `fs' service.")); + GNUNET_FS_unindex_sync_(uc); + signal_unindex_error(uc); } @@ -286,56 +286,56 @@ unindex_mq_error_handler (void *cls, * @param uc our unindexing context */ static void -unindex_finish (struct GNUNET_FS_UnindexContext *uc) +unindex_finish(struct GNUNET_FS_UnindexContext *uc) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (unindex_response, - GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK, - struct GNUNET_MessageHeader, - uc), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(unindex_response, + GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK, + struct GNUNET_MessageHeader, + uc), + GNUNET_MQ_handler_end() }; char *emsg; struct GNUNET_MQ_Envelope *env; struct UnindexMessage *req; /* generate final progress message */ - unindex_progress (uc, - uc->file_size, - NULL, - 0, - 0); - GNUNET_FS_tree_encoder_finish (uc->tc, - &emsg); + unindex_progress(uc, + uc->file_size, + NULL, + 0, + 0); + GNUNET_FS_tree_encoder_finish(uc->tc, + &emsg); uc->tc = NULL; - GNUNET_DISK_file_close (uc->fh); + GNUNET_DISK_file_close(uc->fh); uc->fh = NULL; - GNUNET_DATASTORE_disconnect (uc->dsh, GNUNET_NO); + GNUNET_DATASTORE_disconnect(uc->dsh, GNUNET_NO); uc->dsh = NULL; uc->state = UNINDEX_STATE_FS_NOTIFY; - GNUNET_FS_unindex_sync_ (uc); - uc->mq = GNUNET_CLIENT_connect (uc->h->cfg, - "fs", - handlers, - &unindex_mq_error_handler, - uc); + GNUNET_FS_unindex_sync_(uc); + uc->mq = GNUNET_CLIENT_connect(uc->h->cfg, + "fs", + handlers, + &unindex_mq_error_handler, + uc); if (NULL == uc->mq) - { - uc->state = UNINDEX_STATE_ERROR; - uc->emsg = - GNUNET_strdup (_("Failed to connect to FS service for unindexing.")); - GNUNET_FS_unindex_sync_ (uc); - signal_unindex_error (uc); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending UNINDEX message to FS service\n"); - env = GNUNET_MQ_msg (req, - GNUNET_MESSAGE_TYPE_FS_UNINDEX); + { + uc->state = UNINDEX_STATE_ERROR; + uc->emsg = + GNUNET_strdup(_("Failed to connect to FS service for unindexing.")); + GNUNET_FS_unindex_sync_(uc); + signal_unindex_error(uc); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending UNINDEX message to FS service\n"); + env = GNUNET_MQ_msg(req, + GNUNET_MESSAGE_TYPE_FS_UNINDEX); req->reserved = 0; req->file_id = uc->file_id; - GNUNET_MQ_send (uc->mq, - env); + GNUNET_MQ_send(uc->mq, + env); } @@ -351,47 +351,49 @@ unindex_finish (struct GNUNET_FS_UnindexContext *uc) * @param reason kind of progress we are making */ static void -unindex_directory_scan_cb (void *cls, - const char *filename, - int is_directory, - enum GNUNET_FS_DirScannerProgressUpdateReason reason) +unindex_directory_scan_cb(void *cls, + const char *filename, + int is_directory, + enum GNUNET_FS_DirScannerProgressUpdateReason reason) { struct GNUNET_FS_UnindexContext *uc = cls; static struct GNUNET_FS_ShareTreeItem * directory_scan_result; switch (reason) - { - case GNUNET_FS_DIRSCANNER_FINISHED: - directory_scan_result = GNUNET_FS_directory_scan_get_result (uc->dscan); - uc->dscan = NULL; - if (NULL != directory_scan_result->ksk_uri) - { - uc->ksk_uri = GNUNET_FS_uri_dup (directory_scan_result->ksk_uri); - uc->state = UNINDEX_STATE_DS_REMOVE_KBLOCKS; - GNUNET_FS_unindex_sync_ (uc); - GNUNET_FS_unindex_do_remove_kblocks_ (uc); - } - else - { - uc->emsg = GNUNET_strdup (_("Failed to get KSKs from directory scan.")); - GNUNET_FS_unindex_sync_ (uc); - unindex_finish (uc); - } - GNUNET_FS_share_tree_free (directory_scan_result); - break; - case GNUNET_FS_DIRSCANNER_INTERNAL_ERROR: - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Internal error scanning `%s'.\n"), - uc->filename); - GNUNET_FS_directory_scan_abort (uc->dscan); - uc->dscan = NULL; - uc->emsg = GNUNET_strdup (_("Failed to get KSKs from directory scan.")); - GNUNET_FS_unindex_sync_ (uc); - unindex_finish (uc); - break; - default: - break; - } + { + case GNUNET_FS_DIRSCANNER_FINISHED: + directory_scan_result = GNUNET_FS_directory_scan_get_result(uc->dscan); + uc->dscan = NULL; + if (NULL != directory_scan_result->ksk_uri) + { + uc->ksk_uri = GNUNET_FS_uri_dup(directory_scan_result->ksk_uri); + uc->state = UNINDEX_STATE_DS_REMOVE_KBLOCKS; + GNUNET_FS_unindex_sync_(uc); + GNUNET_FS_unindex_do_remove_kblocks_(uc); + } + else + { + uc->emsg = GNUNET_strdup(_("Failed to get KSKs from directory scan.")); + GNUNET_FS_unindex_sync_(uc); + unindex_finish(uc); + } + GNUNET_FS_share_tree_free(directory_scan_result); + break; + + case GNUNET_FS_DIRSCANNER_INTERNAL_ERROR: + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Internal error scanning `%s'.\n"), + uc->filename); + GNUNET_FS_directory_scan_abort(uc->dscan); + uc->dscan = NULL; + uc->emsg = GNUNET_strdup(_("Failed to get KSKs from directory scan.")); + GNUNET_FS_unindex_sync_(uc); + unindex_finish(uc); + break; + + default: + break; + } } @@ -401,18 +403,18 @@ unindex_directory_scan_cb (void *cls, * @param uc context for the unindex operation. */ void -GNUNET_FS_unindex_do_extract_keywords_ (struct GNUNET_FS_UnindexContext *uc) +GNUNET_FS_unindex_do_extract_keywords_(struct GNUNET_FS_UnindexContext *uc) { char *ex; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (uc->h->cfg, "FS", "EXTRACTORS", &ex)) + GNUNET_CONFIGURATION_get_value_string(uc->h->cfg, "FS", "EXTRACTORS", &ex)) ex = NULL; - uc->dscan = GNUNET_FS_directory_scan_start (uc->filename, - GNUNET_NO, ex, - &unindex_directory_scan_cb, - uc); - GNUNET_free_non_null (ex); + uc->dscan = GNUNET_FS_directory_scan_start(uc->filename, + GNUNET_NO, ex, + &unindex_directory_scan_cb, + uc); + GNUNET_free_non_null(ex); } @@ -430,20 +432,20 @@ GNUNET_FS_unindex_do_extract_keywords_ (struct GNUNET_FS_UnindexContext *uc) * @param msg NULL on success, otherwise an error message */ static void -continue_after_remove (void *cls, - int32_t success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +continue_after_remove(void *cls, + int32_t success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct GNUNET_FS_UnindexContext *uc = cls; uc->dqe = NULL; if (success != GNUNET_YES) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed to remove UBlock: %s\n"), - msg); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to remove UBlock: %s\n"), + msg); uc->ksk_offset++; - GNUNET_FS_unindex_do_remove_kblocks_ (uc); + GNUNET_FS_unindex_do_remove_kblocks_(uc); } @@ -470,16 +472,16 @@ continue_after_remove (void *cls, * maybe 0 if no unique identifier is available */ static void -process_kblock_for_unindex (void *cls, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +process_kblock_for_unindex(void *cls, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct GNUNET_FS_UnindexContext *uc = cls; const struct UBlock *ub; @@ -488,82 +490,82 @@ process_kblock_for_unindex (void *cls, uc->dqe = NULL; if (NULL == data) - { - /* no result */ - uc->ksk_offset++; - GNUNET_FS_unindex_do_remove_kblocks_ (uc); - return; - } - GNUNET_assert (GNUNET_BLOCK_TYPE_FS_UBLOCK == type); - if (size < sizeof (struct UBlock)) - { - GNUNET_break (0); - goto get_next; - } + { + /* no result */ + uc->ksk_offset++; + GNUNET_FS_unindex_do_remove_kblocks_(uc); + return; + } + GNUNET_assert(GNUNET_BLOCK_TYPE_FS_UBLOCK == type); + if (size < sizeof(struct UBlock)) + { + GNUNET_break(0); + goto get_next; + } ub = data; - GNUNET_CRYPTO_hash (&ub->verification_key, - sizeof (ub->verification_key), - &query); - if (0 != memcmp (&query, - key, - sizeof (struct GNUNET_HashCode))) - { - /* result does not match our keyword, skip */ - goto get_next; - } + GNUNET_CRYPTO_hash(&ub->verification_key, + sizeof(ub->verification_key), + &query); + if (0 != memcmp(&query, + key, + sizeof(struct GNUNET_HashCode))) + { + /* result does not match our keyword, skip */ + goto get_next; + } { - char pt[size - sizeof (struct UBlock)]; + char pt[size - sizeof(struct UBlock)]; struct GNUNET_CRYPTO_EcdsaPublicKey anon_pub; const char *keyword; - GNUNET_CRYPTO_ecdsa_key_get_public (GNUNET_CRYPTO_ecdsa_key_get_anonymous (), - &anon_pub); + GNUNET_CRYPTO_ecdsa_key_get_public(GNUNET_CRYPTO_ecdsa_key_get_anonymous(), + &anon_pub); keyword = &uc->ksk_uri->data.ksk.keywords[uc->ksk_offset][1]; - GNUNET_FS_ublock_decrypt_ (&ub[1], size - sizeof (struct UBlock), - &anon_pub, - keyword, - pt); - if (NULL == memchr (&pt[1], 0, sizeof (pt) - 1)) - { - GNUNET_break_op (0); /* malformed UBlock */ - goto get_next; - } - chk_uri = GNUNET_FS_uri_parse (&pt[1], NULL); + GNUNET_FS_ublock_decrypt_(&ub[1], size - sizeof(struct UBlock), + &anon_pub, + keyword, + pt); + if (NULL == memchr(&pt[1], 0, sizeof(pt) - 1)) + { + GNUNET_break_op(0); /* malformed UBlock */ + goto get_next; + } + chk_uri = GNUNET_FS_uri_parse(&pt[1], NULL); if (NULL == chk_uri) + { + GNUNET_break_op(0); /* malformed UBlock */ + goto get_next; + } + } + if (0 != memcmp(&uc->chk, + &chk_uri->data.chk.chk, + sizeof(struct ContentHashKey))) { - GNUNET_break_op (0); /* malformed UBlock */ + /* different CHK, ignore */ + GNUNET_FS_uri_destroy(chk_uri); goto get_next; } - } - if (0 != memcmp (&uc->chk, - &chk_uri->data.chk.chk, - sizeof (struct ContentHashKey))) - { - /* different CHK, ignore */ - GNUNET_FS_uri_destroy (chk_uri); - goto get_next; - } - GNUNET_FS_uri_destroy (chk_uri); + GNUNET_FS_uri_destroy(chk_uri); /* matches! */ - uc->dqe = GNUNET_DATASTORE_remove (uc->dsh, - key, - size, - data, + uc->dqe = GNUNET_DATASTORE_remove(uc->dsh, + key, + size, + data, + 0 /* priority */, + 1 /* queue size */, + &continue_after_remove, + uc); + return; +get_next: + uc->dqe = GNUNET_DATASTORE_get_key(uc->dsh, + uid + 1 /* next_uid */, + false /* random */, + &uc->uquery, + GNUNET_BLOCK_TYPE_FS_UBLOCK, 0 /* priority */, 1 /* queue size */, - &continue_after_remove, + &process_kblock_for_unindex, uc); - return; - get_next: - uc->dqe = GNUNET_DATASTORE_get_key (uc->dsh, - uid + 1 /* next_uid */, - false /* random */, - &uc->uquery, - GNUNET_BLOCK_TYPE_FS_UBLOCK, - 0 /* priority */, - 1 /* queue size */, - &process_kblock_for_unindex, - uc); } @@ -573,7 +575,7 @@ process_kblock_for_unindex (void *cls, * @param uc context for the unindex operation. */ void -GNUNET_FS_unindex_do_remove_kblocks_ (struct GNUNET_FS_UnindexContext *uc) +GNUNET_FS_unindex_do_remove_kblocks_(struct GNUNET_FS_UnindexContext *uc) { const char *keyword; const struct GNUNET_CRYPTO_EcdsaPrivateKey *anon; @@ -581,41 +583,41 @@ GNUNET_FS_unindex_do_remove_kblocks_ (struct GNUNET_FS_UnindexContext *uc) struct GNUNET_CRYPTO_EcdsaPublicKey dpub; if (NULL == uc->dsh) - uc->dsh = GNUNET_DATASTORE_connect (uc->h->cfg); + uc->dsh = GNUNET_DATASTORE_connect(uc->h->cfg); if (NULL == uc->dsh) - { - uc->state = UNINDEX_STATE_ERROR; - uc->emsg = GNUNET_strdup (_("Failed to connect to `datastore' service.")); - GNUNET_FS_unindex_sync_ (uc); - signal_unindex_error (uc); - return; - } - if ( (NULL == uc->ksk_uri) || - (uc->ksk_offset >= uc->ksk_uri->data.ksk.keywordCount) ) - { - unindex_finish (uc); - return; - } - anon = GNUNET_CRYPTO_ecdsa_key_get_anonymous (); - GNUNET_CRYPTO_ecdsa_key_get_public (anon, - &anon_pub); + { + uc->state = UNINDEX_STATE_ERROR; + uc->emsg = GNUNET_strdup(_("Failed to connect to `datastore' service.")); + GNUNET_FS_unindex_sync_(uc); + signal_unindex_error(uc); + return; + } + if ((NULL == uc->ksk_uri) || + (uc->ksk_offset >= uc->ksk_uri->data.ksk.keywordCount)) + { + unindex_finish(uc); + return; + } + anon = GNUNET_CRYPTO_ecdsa_key_get_anonymous(); + GNUNET_CRYPTO_ecdsa_key_get_public(anon, + &anon_pub); keyword = &uc->ksk_uri->data.ksk.keywords[uc->ksk_offset][1]; - GNUNET_CRYPTO_ecdsa_public_key_derive (&anon_pub, - keyword, - "fs-ublock", - &dpub); - GNUNET_CRYPTO_hash (&dpub, - sizeof (dpub), - &uc->uquery); - uc->dqe = GNUNET_DATASTORE_get_key (uc->dsh, - 0 /* next_uid */, - false /* random */, - &uc->uquery, - GNUNET_BLOCK_TYPE_FS_UBLOCK, - 0 /* priority */, - 1 /* queue size */, - &process_kblock_for_unindex, - uc); + GNUNET_CRYPTO_ecdsa_public_key_derive(&anon_pub, + keyword, + "fs-ublock", + &dpub); + GNUNET_CRYPTO_hash(&dpub, + sizeof(dpub), + &uc->uquery); + uc->dqe = GNUNET_DATASTORE_get_key(uc->dsh, + 0 /* next_uid */, + false /* random */, + &uc->uquery, + GNUNET_BLOCK_TYPE_FS_UBLOCK, + 0 /* priority */, + 1 /* queue size */, + &process_kblock_for_unindex, + uc); } @@ -626,13 +628,13 @@ GNUNET_FS_unindex_do_remove_kblocks_ (struct GNUNET_FS_UnindexContext *uc) * @param cls our unindexing context */ static void -unindex_extract_keywords (void *cls) +unindex_extract_keywords(void *cls) { struct GNUNET_FS_UnindexContext *uc = cls; uc->state = UNINDEX_STATE_EXTRACT_KEYWORDS; - GNUNET_FS_unindex_sync_ (uc); - GNUNET_FS_unindex_do_extract_keywords_ (uc); + GNUNET_FS_unindex_sync_(uc); + GNUNET_FS_unindex_do_extract_keywords_(uc); } @@ -642,40 +644,40 @@ unindex_extract_keywords (void *cls) * @param uc context for the unindex operation. */ void -GNUNET_FS_unindex_do_remove_ (struct GNUNET_FS_UnindexContext *uc) +GNUNET_FS_unindex_do_remove_(struct GNUNET_FS_UnindexContext *uc) { if (NULL == uc->dsh) - uc->dsh = GNUNET_DATASTORE_connect (uc->h->cfg); + uc->dsh = GNUNET_DATASTORE_connect(uc->h->cfg); if (NULL == uc->dsh) - { - uc->state = UNINDEX_STATE_ERROR; - uc->emsg = GNUNET_strdup (_("Failed to connect to `datastore' service.")); - GNUNET_FS_unindex_sync_ (uc); - signal_unindex_error (uc); - return; - } + { + uc->state = UNINDEX_STATE_ERROR; + uc->emsg = GNUNET_strdup(_("Failed to connect to `datastore' service.")); + GNUNET_FS_unindex_sync_(uc); + signal_unindex_error(uc); + return; + } uc->fh = - GNUNET_DISK_file_open (uc->filename, GNUNET_DISK_OPEN_READ, - GNUNET_DISK_PERM_NONE); + GNUNET_DISK_file_open(uc->filename, GNUNET_DISK_OPEN_READ, + GNUNET_DISK_PERM_NONE); if (NULL == uc->fh) - { - GNUNET_DATASTORE_disconnect (uc->dsh, GNUNET_NO); - uc->dsh = NULL; - uc->state = UNINDEX_STATE_ERROR; - uc->emsg = GNUNET_strdup (_("Failed to open file for unindexing.")); - GNUNET_FS_unindex_sync_ (uc); - signal_unindex_error (uc); - return; - } + { + GNUNET_DATASTORE_disconnect(uc->dsh, GNUNET_NO); + uc->dsh = NULL; + uc->state = UNINDEX_STATE_ERROR; + uc->emsg = GNUNET_strdup(_("Failed to open file for unindexing.")); + GNUNET_FS_unindex_sync_(uc); + signal_unindex_error(uc); + return; + } uc->tc = - GNUNET_FS_tree_encoder_create (uc->h, - uc->file_size, - uc, - &unindex_reader, - &unindex_process, - &unindex_progress, - &unindex_extract_keywords); - GNUNET_FS_tree_encoder_next (uc->tc); + GNUNET_FS_tree_encoder_create(uc->h, + uc->file_size, + uc, + &unindex_reader, + &unindex_process, + &unindex_progress, + &unindex_extract_keywords); + GNUNET_FS_tree_encoder_next(uc->tc); } @@ -687,29 +689,29 @@ GNUNET_FS_unindex_do_remove_ (struct GNUNET_FS_UnindexContext *uc) * @param file_id computed hash, NULL on error */ void -GNUNET_FS_unindex_process_hash_ (void *cls, - const struct GNUNET_HashCode *file_id) +GNUNET_FS_unindex_process_hash_(void *cls, + const struct GNUNET_HashCode *file_id) { struct GNUNET_FS_UnindexContext *uc = cls; uc->fhc = NULL; if (uc->state != UNINDEX_STATE_HASHING) - { - GNUNET_FS_unindex_stop (uc); - return; - } + { + GNUNET_FS_unindex_stop(uc); + return; + } if (file_id == NULL) - { - uc->state = UNINDEX_STATE_ERROR; - uc->emsg = GNUNET_strdup (_("Failed to compute hash of file.")); - GNUNET_FS_unindex_sync_ (uc); - signal_unindex_error (uc); - return; - } + { + uc->state = UNINDEX_STATE_ERROR; + uc->emsg = GNUNET_strdup(_("Failed to compute hash of file.")); + GNUNET_FS_unindex_sync_(uc); + signal_unindex_error(uc); + return; + } uc->file_id = *file_id; uc->state = UNINDEX_STATE_DS_REMOVE; - GNUNET_FS_unindex_sync_ (uc); - GNUNET_FS_unindex_do_remove_ (uc); + GNUNET_FS_unindex_sync_(uc); + GNUNET_FS_unindex_do_remove_(uc); } @@ -720,62 +722,62 @@ GNUNET_FS_unindex_process_hash_ (void *cls, * @param cls the `struct GNUNET_FS_UnindexContext` to signal for */ void -GNUNET_FS_unindex_signal_suspend_ (void *cls) +GNUNET_FS_unindex_signal_suspend_(void *cls) { struct GNUNET_FS_UnindexContext *uc = cls; struct GNUNET_FS_ProgressInfo pi; /* FIXME: lots of duplication with unindex_stop here! */ if (uc->dscan != NULL) - { - GNUNET_FS_directory_scan_abort (uc->dscan); - uc->dscan = NULL; - } + { + GNUNET_FS_directory_scan_abort(uc->dscan); + uc->dscan = NULL; + } if (NULL != uc->dqe) - { - GNUNET_DATASTORE_cancel (uc->dqe); - uc->dqe = NULL; - } + { + GNUNET_DATASTORE_cancel(uc->dqe); + uc->dqe = NULL; + } if (uc->fhc != NULL) - { - GNUNET_CRYPTO_hash_file_cancel (uc->fhc); - uc->fhc = NULL; - } + { + GNUNET_CRYPTO_hash_file_cancel(uc->fhc); + uc->fhc = NULL; + } if (NULL != uc->ksk_uri) - { - GNUNET_FS_uri_destroy (uc->ksk_uri); - uc->ksk_uri = NULL; - } + { + GNUNET_FS_uri_destroy(uc->ksk_uri); + uc->ksk_uri = NULL; + } if (NULL != uc->mq) - { - GNUNET_MQ_destroy (uc->mq); - uc->mq = NULL; - } + { + GNUNET_MQ_destroy(uc->mq); + uc->mq = NULL; + } if (NULL != uc->dsh) - { - GNUNET_DATASTORE_disconnect (uc->dsh, GNUNET_NO); - uc->dsh = NULL; - } + { + GNUNET_DATASTORE_disconnect(uc->dsh, GNUNET_NO); + uc->dsh = NULL; + } if (NULL != uc->tc) - { - GNUNET_FS_tree_encoder_finish (uc->tc, NULL); - uc->tc = NULL; - } + { + GNUNET_FS_tree_encoder_finish(uc->tc, NULL); + uc->tc = NULL; + } if (uc->fh != NULL) - { - GNUNET_DISK_file_close (uc->fh); - uc->fh = NULL; - } - GNUNET_FS_end_top (uc->h, uc->top); + { + GNUNET_DISK_file_close(uc->fh); + uc->fh = NULL; + } + GNUNET_FS_end_top(uc->h, uc->top); pi.status = GNUNET_FS_STATUS_UNINDEX_SUSPEND; - GNUNET_FS_unindex_make_status_ (&pi, uc, - (uc->state == - UNINDEX_STATE_COMPLETE) ? uc->file_size : 0); - GNUNET_break (NULL == uc->client_info); - GNUNET_free (uc->filename); - GNUNET_free_non_null (uc->serialization); - GNUNET_free_non_null (uc->emsg); - GNUNET_free (uc); + GNUNET_FS_unindex_make_status_(&pi, uc, + (uc->state == + UNINDEX_STATE_COMPLETE) ? uc->file_size : 0); + GNUNET_break(NULL == uc->client_info); + GNUNET_free(uc->filename); + GNUNET_free_non_null(uc->serialization); + GNUNET_free_non_null(uc->emsg); + GNUNET_free(uc); } @@ -788,38 +790,38 @@ GNUNET_FS_unindex_signal_suspend_ (void *cls) * @return NULL on error, otherwise handle */ struct GNUNET_FS_UnindexContext * -GNUNET_FS_unindex_start (struct GNUNET_FS_Handle *h, - const char *filename, - void *cctx) +GNUNET_FS_unindex_start(struct GNUNET_FS_Handle *h, + const char *filename, + void *cctx) { struct GNUNET_FS_UnindexContext *uc; struct GNUNET_FS_ProgressInfo pi; uint64_t size; if (GNUNET_OK != - GNUNET_DISK_file_size (filename, - &size, - GNUNET_YES, - GNUNET_YES)) + GNUNET_DISK_file_size(filename, + &size, + GNUNET_YES, + GNUNET_YES)) return NULL; - uc = GNUNET_new (struct GNUNET_FS_UnindexContext); + uc = GNUNET_new(struct GNUNET_FS_UnindexContext); uc->h = h; - uc->filename = GNUNET_strdup (filename); - uc->start_time = GNUNET_TIME_absolute_get (); + uc->filename = GNUNET_strdup(filename); + uc->start_time = GNUNET_TIME_absolute_get(); uc->file_size = size; uc->client_info = cctx; - GNUNET_FS_unindex_sync_ (uc); + GNUNET_FS_unindex_sync_(uc); pi.status = GNUNET_FS_STATUS_UNINDEX_START; pi.value.unindex.eta = GNUNET_TIME_UNIT_FOREVER_REL; - GNUNET_FS_unindex_make_status_ (&pi, uc, 0); + GNUNET_FS_unindex_make_status_(&pi, uc, 0); uc->fhc = - GNUNET_CRYPTO_hash_file (GNUNET_SCHEDULER_PRIORITY_IDLE, - filename, - HASHING_BLOCKSIZE, - &GNUNET_FS_unindex_process_hash_, uc); - uc->top = GNUNET_FS_make_top (h, - &GNUNET_FS_unindex_signal_suspend_, - uc); + GNUNET_CRYPTO_hash_file(GNUNET_SCHEDULER_PRIORITY_IDLE, + filename, + HASHING_BLOCKSIZE, + &GNUNET_FS_unindex_process_hash_, uc); + uc->top = GNUNET_FS_make_top(h, + &GNUNET_FS_unindex_signal_suspend_, + uc); return uc; } @@ -830,67 +832,67 @@ GNUNET_FS_unindex_start (struct GNUNET_FS_Handle *h, * @param uc handle */ void -GNUNET_FS_unindex_stop (struct GNUNET_FS_UnindexContext *uc) +GNUNET_FS_unindex_stop(struct GNUNET_FS_UnindexContext *uc) { struct GNUNET_FS_ProgressInfo pi; if (NULL != uc->dscan) - { - GNUNET_FS_directory_scan_abort (uc->dscan); - uc->dscan = NULL; - } + { + GNUNET_FS_directory_scan_abort(uc->dscan); + uc->dscan = NULL; + } if (NULL != uc->dqe) - { - GNUNET_DATASTORE_cancel (uc->dqe); - uc->dqe = NULL; - } + { + GNUNET_DATASTORE_cancel(uc->dqe); + uc->dqe = NULL; + } if (NULL != uc->fhc) - { - GNUNET_CRYPTO_hash_file_cancel (uc->fhc); - uc->fhc = NULL; - } + { + GNUNET_CRYPTO_hash_file_cancel(uc->fhc); + uc->fhc = NULL; + } if (NULL != uc->mq) - { - GNUNET_MQ_destroy (uc->mq); - uc->mq = NULL; - } + { + GNUNET_MQ_destroy(uc->mq); + uc->mq = NULL; + } if (NULL != uc->dsh) - { - GNUNET_DATASTORE_disconnect (uc->dsh, GNUNET_NO); - uc->dsh = NULL; - } + { + GNUNET_DATASTORE_disconnect(uc->dsh, GNUNET_NO); + uc->dsh = NULL; + } if (NULL != uc->ksk_uri) - { - GNUNET_FS_uri_destroy (uc->ksk_uri); - uc->ksk_uri = NULL; - } + { + GNUNET_FS_uri_destroy(uc->ksk_uri); + uc->ksk_uri = NULL; + } if (NULL != uc->tc) - { - GNUNET_FS_tree_encoder_finish (uc->tc, NULL); - uc->tc = NULL; - } + { + GNUNET_FS_tree_encoder_finish(uc->tc, NULL); + uc->tc = NULL; + } if (uc->fh != NULL) - { - GNUNET_DISK_file_close (uc->fh); - uc->fh = NULL; - } - GNUNET_FS_end_top (uc->h, uc->top); + { + GNUNET_DISK_file_close(uc->fh); + uc->fh = NULL; + } + GNUNET_FS_end_top(uc->h, uc->top); if (uc->serialization != NULL) - { - GNUNET_FS_remove_sync_file_ (uc->h, GNUNET_FS_SYNC_PATH_MASTER_UNINDEX, - uc->serialization); - GNUNET_free (uc->serialization); - uc->serialization = NULL; - } + { + GNUNET_FS_remove_sync_file_(uc->h, GNUNET_FS_SYNC_PATH_MASTER_UNINDEX, + uc->serialization); + GNUNET_free(uc->serialization); + uc->serialization = NULL; + } pi.status = GNUNET_FS_STATUS_UNINDEX_STOPPED; pi.value.unindex.eta = GNUNET_TIME_UNIT_ZERO; - GNUNET_FS_unindex_make_status_ (&pi, uc, - (uc->state == - UNINDEX_STATE_COMPLETE) ? uc->file_size : 0); - GNUNET_break (NULL == uc->client_info); - GNUNET_free_non_null (uc->emsg); - GNUNET_free (uc->filename); - GNUNET_free (uc); + GNUNET_FS_unindex_make_status_(&pi, uc, + (uc->state == + UNINDEX_STATE_COMPLETE) ? uc->file_size : 0); + GNUNET_break(NULL == uc->client_info); + GNUNET_free_non_null(uc->emsg); + GNUNET_free(uc->filename); + GNUNET_free(uc); } /* end of fs_unindex.c */ diff --git a/src/fs/fs_uri.c b/src/fs/fs_uri.c index 5a67afbc0..c9ce19114 100644 --- a/src/fs/fs_uri.c +++ b/src/fs/fs_uri.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/fs_uri.c @@ -100,43 +100,47 @@ * @return #GNUNET_OK on success */ int -GNUNET_FS_uri_to_key (const struct GNUNET_FS_Uri *uri, - struct GNUNET_HashCode *key) +GNUNET_FS_uri_to_key(const struct GNUNET_FS_Uri *uri, + struct GNUNET_HashCode *key) { switch (uri->type) - { - case GNUNET_FS_URI_CHK: - *key = uri->data.chk.chk.query; - return GNUNET_OK; - case GNUNET_FS_URI_SKS: - GNUNET_CRYPTO_hash (uri->data.sks.identifier, - strlen (uri->data.sks.identifier), - key); - return GNUNET_OK; - case GNUNET_FS_URI_KSK: - if (uri->data.ksk.keywordCount > 0) { - GNUNET_CRYPTO_hash (uri->data.ksk.keywords[0], - strlen (uri->data.ksk.keywords[0]), - key); + case GNUNET_FS_URI_CHK: + *key = uri->data.chk.chk.query; return GNUNET_OK; - } - else - { - memset (key, 0, sizeof (struct GNUNET_HashCode)); + + case GNUNET_FS_URI_SKS: + GNUNET_CRYPTO_hash(uri->data.sks.identifier, + strlen(uri->data.sks.identifier), + key); + return GNUNET_OK; + + case GNUNET_FS_URI_KSK: + if (uri->data.ksk.keywordCount > 0) + { + GNUNET_CRYPTO_hash(uri->data.ksk.keywords[0], + strlen(uri->data.ksk.keywords[0]), + key); + return GNUNET_OK; + } + else + { + memset(key, 0, sizeof(struct GNUNET_HashCode)); + return GNUNET_SYSERR; + } + break; + + case GNUNET_FS_URI_LOC: + GNUNET_CRYPTO_hash(&uri->data.loc.fi, + sizeof(struct FileIdentifier) + + sizeof(struct GNUNET_PeerIdentity), + key); + return GNUNET_OK; + + default: + memset(key, 0, sizeof(struct GNUNET_HashCode)); return GNUNET_SYSERR; } - break; - case GNUNET_FS_URI_LOC: - GNUNET_CRYPTO_hash (&uri->data.loc.fi, - sizeof (struct FileIdentifier) + - sizeof (struct GNUNET_PeerIdentity), - key); - return GNUNET_OK; - default: - memset (key, 0, sizeof (struct GNUNET_HashCode)); - return GNUNET_SYSERR; - } } @@ -148,7 +152,7 @@ GNUNET_FS_uri_to_key (const struct GNUNET_FS_Uri *uri, * @return string with the keywords */ char * -GNUNET_FS_uri_ksk_to_string_fancy (const struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_ksk_to_string_fancy(const struct GNUNET_FS_Uri *uri) { size_t n; char *ret; @@ -158,45 +162,45 @@ GNUNET_FS_uri_ksk_to_string_fancy (const struct GNUNET_FS_Uri *uri) unsigned int keywordCount; if ((NULL == uri) || (GNUNET_FS_URI_KSK != uri->type)) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } keywords = uri->data.ksk.keywords; keywordCount = uri->data.ksk.keywordCount; n = keywordCount + 1; for (i = 0; i < keywordCount; i++) - { - keyword = keywords[i]; - n += strlen (keyword) - 1; - if (NULL != strstr (&keyword[1], " ")) - n += 2; - if (keyword[0] == '+') - n++; - } - ret = GNUNET_malloc (n); - strcpy (ret, ""); - for (i = 0; i < keywordCount; i++) - { - keyword = keywords[i]; - if (NULL != strstr (&keyword[1], " ")) { - strcat (ret, "\""); + keyword = keywords[i]; + n += strlen(keyword) - 1; + if (NULL != strstr(&keyword[1], " ")) + n += 2; if (keyword[0] == '+') - strcat (ret, keyword); - else - strcat (ret, &keyword[1]); - strcat (ret, "\""); + n++; } - else + ret = GNUNET_malloc(n); + strcpy(ret, ""); + for (i = 0; i < keywordCount; i++) { - if (keyword[0] == '+') - strcat (ret, keyword); + keyword = keywords[i]; + if (NULL != strstr(&keyword[1], " ")) + { + strcat(ret, "\""); + if (keyword[0] == '+') + strcat(ret, keyword); + else + strcat(ret, &keyword[1]); + strcat(ret, "\""); + } else - strcat (ret, &keyword[1]); + { + if (keyword[0] == '+') + strcat(ret, keyword); + else + strcat(ret, &keyword[1]); + } + strcat(ret, " "); } - strcat (ret, " "); - } return ret; } @@ -212,7 +216,7 @@ GNUNET_FS_uri_ksk_to_string_fancy (const struct GNUNET_FS_Uri *uri) * @return decodded string with leading space (or preserved plus) */ static char * -percent_decode_keyword (const char *in, char **emsg) +percent_decode_keyword(const char *in, char **emsg) { char *out; char *ret; @@ -220,44 +224,44 @@ percent_decode_keyword (const char *in, char **emsg) unsigned int wpos; unsigned int hx; - out = GNUNET_strdup (in); + out = GNUNET_strdup(in); rpos = 0; wpos = 0; while (out[rpos] != '\0') - { - if (out[rpos] == '%') - { - if (1 != sscanf (&out[rpos + 1], "%2X", &hx)) - { - GNUNET_free (out); - *emsg = GNUNET_strdup ( - _ (/* xgettext:no-c-format */ - "Malformed KSK URI (`%' must be followed by HEX number)")); - return NULL; - } - rpos += 3; - if (hx == '"') - continue; /* skip double quote */ - out[wpos++] = (char) hx; - } - else { - out[wpos++] = out[rpos++]; + if (out[rpos] == '%') + { + if (1 != sscanf(&out[rpos + 1], "%2X", &hx)) + { + GNUNET_free(out); + *emsg = GNUNET_strdup( + _(/* xgettext:no-c-format */ + "Malformed KSK URI (`%' must be followed by HEX number)")); + return NULL; + } + rpos += 3; + if (hx == '"') + continue; /* skip double quote */ + out[wpos++] = (char)hx; + } + else + { + out[wpos++] = out[rpos++]; + } } - } out[wpos] = '\0'; if (out[0] == '+') - { - ret = GNUNET_strdup (out); - } + { + ret = GNUNET_strdup(out); + } else - { - /* need to prefix with space */ - ret = GNUNET_malloc (strlen (out) + 2); - strcpy (ret, " "); - strcat (ret, out); - } - GNUNET_free (out); + { + /* need to prefix with space */ + ret = GNUNET_malloc(strlen(out) + 2); + strcpy(ret, " "); + strcat(ret, out); + } + GNUNET_free(out); return ret; } @@ -271,7 +275,7 @@ percent_decode_keyword (const char *in, char **emsg) * @return NULL on error, otherwise the KSK URI */ static struct GNUNET_FS_Uri * -uri_ksk_parse (const char *s, char **emsg) +uri_ksk_parse(const char *s, char **emsg) { struct GNUNET_FS_Uri *ret; char **keywords; @@ -283,74 +287,74 @@ uri_ksk_parse (const char *s, char **emsg) char *dup; int saw_quote; - slen = strlen (s); - pos = strlen (GNUNET_FS_URI_KSK_PREFIX); - if ((slen <= pos) || (0 != strncmp (s, GNUNET_FS_URI_KSK_PREFIX, pos))) + slen = strlen(s); + pos = strlen(GNUNET_FS_URI_KSK_PREFIX); + if ((slen <= pos) || (0 != strncmp(s, GNUNET_FS_URI_KSK_PREFIX, pos))) return NULL; /* not KSK URI */ if ((s[slen - 1] == '+') || (s[pos] == '+')) - { - *emsg = - GNUNET_strdup (_ ("Malformed KSK URI (must not begin or end with `+')")); - return NULL; - } + { + *emsg = + GNUNET_strdup(_("Malformed KSK URI (must not begin or end with `+')")); + return NULL; + } max = 1; saw_quote = 0; for (i = pos; i < slen; i++) - { - if ((s[i] == '%') && (&s[i] == strstr (&s[i], "%22"))) - { - saw_quote = (saw_quote + 1) % 2; - i += 3; - continue; - } - if ((s[i] == '+') && (saw_quote == 0)) { - max++; - if (s[i - 1] == '+') - { - *emsg = GNUNET_strdup (_ ("Malformed KSK URI (`++' not allowed)")); - return NULL; - } + if ((s[i] == '%') && (&s[i] == strstr(&s[i], "%22"))) + { + saw_quote = (saw_quote + 1) % 2; + i += 3; + continue; + } + if ((s[i] == '+') && (saw_quote == 0)) + { + max++; + if (s[i - 1] == '+') + { + *emsg = GNUNET_strdup(_("Malformed KSK URI (`++' not allowed)")); + return NULL; + } + } } - } if (saw_quote == 1) - { - *emsg = GNUNET_strdup (_ ("Malformed KSK URI (quotes not balanced)")); - return NULL; - } - iret = max; - dup = GNUNET_strdup (s); - keywords = GNUNET_new_array (max, char *); - for (i = slen - 1; i >= (int) pos; i--) - { - if ((s[i] == '%') && (&s[i] == strstr (&s[i], "%22"))) { - saw_quote = (saw_quote + 1) % 2; - continue; + *emsg = GNUNET_strdup(_("Malformed KSK URI (quotes not balanced)")); + return NULL; } - if ((dup[i] == '+') && (saw_quote == 0)) + iret = max; + dup = GNUNET_strdup(s); + keywords = GNUNET_new_array(max, char *); + for (i = slen - 1; i >= (int)pos; i--) { - keywords[--max] = percent_decode_keyword (&dup[i + 1], emsg); - if (NULL == keywords[max]) - goto CLEANUP; - dup[i] = '\0'; + if ((s[i] == '%') && (&s[i] == strstr(&s[i], "%22"))) + { + saw_quote = (saw_quote + 1) % 2; + continue; + } + if ((dup[i] == '+') && (saw_quote == 0)) + { + keywords[--max] = percent_decode_keyword(&dup[i + 1], emsg); + if (NULL == keywords[max]) + goto CLEANUP; + dup[i] = '\0'; + } } - } - keywords[--max] = percent_decode_keyword (&dup[pos], emsg); + keywords[--max] = percent_decode_keyword(&dup[pos], emsg); if (NULL == keywords[max]) goto CLEANUP; - GNUNET_assert (0 == max); - GNUNET_free (dup); - ret = GNUNET_new (struct GNUNET_FS_Uri); + GNUNET_assert(0 == max); + GNUNET_free(dup); + ret = GNUNET_new(struct GNUNET_FS_Uri); ret->type = GNUNET_FS_URI_KSK; ret->data.ksk.keywordCount = iret; ret->data.ksk.keywords = keywords; return ret; CLEANUP: for (i = 0; i < max; i++) - GNUNET_free_non_null (keywords[i]); - GNUNET_free (keywords); - GNUNET_free (dup); + GNUNET_free_non_null(keywords[i]); + GNUNET_free(keywords); + GNUNET_free(dup); return NULL; } @@ -365,31 +369,31 @@ CLEANUP: * @return NULL on error, SKS URI otherwise */ static struct GNUNET_FS_Uri * -uri_sks_parse (const char *s, char **emsg) +uri_sks_parse(const char *s, char **emsg) { struct GNUNET_FS_Uri *ret; struct GNUNET_CRYPTO_EcdsaPublicKey ns; size_t pos; char *end; - pos = strlen (GNUNET_FS_URI_SKS_PREFIX); - if ((strlen (s) <= pos) || (0 != strncmp (s, GNUNET_FS_URI_SKS_PREFIX, pos))) + pos = strlen(GNUNET_FS_URI_SKS_PREFIX); + if ((strlen(s) <= pos) || (0 != strncmp(s, GNUNET_FS_URI_SKS_PREFIX, pos))) return NULL; /* not an SKS URI */ - end = strchr (&s[pos], '/'); + end = strchr(&s[pos], '/'); if ((NULL == end) || - (GNUNET_OK != GNUNET_STRINGS_string_to_data (&s[pos], - end - &s[pos], - &ns, - sizeof (ns)))) - { - *emsg = GNUNET_strdup (_ ("Malformed SKS URI (wrong syntax)")); - return NULL; /* malformed */ - } + (GNUNET_OK != GNUNET_STRINGS_string_to_data(&s[pos], + end - &s[pos], + &ns, + sizeof(ns)))) + { + *emsg = GNUNET_strdup(_("Malformed SKS URI (wrong syntax)")); + return NULL; /* malformed */ + } end++; /* skip over '/' */ - ret = GNUNET_new (struct GNUNET_FS_Uri); + ret = GNUNET_new(struct GNUNET_FS_Uri); ret->type = GNUNET_FS_URI_SKS; ret->data.sks.ns = ns; - ret->data.sks.identifier = GNUNET_strdup (end); + ret->data.sks.identifier = GNUNET_strdup(end); return ret; } @@ -404,46 +408,46 @@ uri_sks_parse (const char *s, char **emsg) * @return NULL on error, CHK URI otherwise */ static struct GNUNET_FS_Uri * -uri_chk_parse (const char *s, char **emsg) +uri_chk_parse(const char *s, char **emsg) { struct GNUNET_FS_Uri *ret; struct FileIdentifier fi; unsigned int pos; unsigned long long flen; size_t slen; - char h1[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)]; - char h2[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)]; + char h1[sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)]; + char h2[sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)]; - slen = strlen (s); - pos = strlen (GNUNET_FS_URI_CHK_PREFIX); - if ((slen < pos + 2 * sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) + 1) || - (0 != strncmp (s, GNUNET_FS_URI_CHK_PREFIX, pos))) + slen = strlen(s); + pos = strlen(GNUNET_FS_URI_CHK_PREFIX); + if ((slen < pos + 2 * sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) + 1) || + (0 != strncmp(s, GNUNET_FS_URI_CHK_PREFIX, pos))) return NULL; /* not a CHK URI */ - if ((s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] != '.') || - (s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2 - 1] != '.')) - { - *emsg = GNUNET_strdup (_ ("Malformed CHK URI (wrong syntax)")); - return NULL; - } - GNUNET_memcpy (h1, &s[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)); - h1[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0'; - GNUNET_memcpy (h2, - &s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)], - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)); - h2[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0'; - - if ((GNUNET_OK != GNUNET_CRYPTO_hash_from_string (h1, &fi.chk.key)) || - (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (h2, &fi.chk.query)) || + if ((s[pos + sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] != '.') || + (s[pos + sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) * 2 - 1] != '.')) + { + *emsg = GNUNET_strdup(_("Malformed CHK URI (wrong syntax)")); + return NULL; + } + GNUNET_memcpy(h1, &s[pos], sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)); + h1[sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0'; + GNUNET_memcpy(h2, + &s[pos + sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)], + sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)); + h2[sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0'; + + if ((GNUNET_OK != GNUNET_CRYPTO_hash_from_string(h1, &fi.chk.key)) || + (GNUNET_OK != GNUNET_CRYPTO_hash_from_string(h2, &fi.chk.query)) || (1 != - sscanf (&s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2], - "%llu", - &flen))) - { - *emsg = GNUNET_strdup (_ ("Malformed CHK URI (failed to decode CHK)")); - return NULL; - } - fi.file_length = GNUNET_htonll (flen); - ret = GNUNET_new (struct GNUNET_FS_Uri); + sscanf(&s[pos + sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) * 2], + "%llu", + &flen))) + { + *emsg = GNUNET_strdup(_("Malformed CHK URI (failed to decode CHK)")); + return NULL; + } + fi.file_length = GNUNET_htonll(flen); + ret = GNUNET_new(struct GNUNET_FS_Uri); ret->type = GNUNET_FS_URI_CHK; ret->data.chk = fi; return ret; @@ -456,8 +460,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * assembled in memory to create or verify the signature of a location * URI. */ -struct LocUriAssembly -{ +struct LocUriAssembly { /** * What is being signed (rest of this struct). */ @@ -494,11 +497,11 @@ GNUNET_NETWORK_STRUCT_END * @return NULL on error, valid LOC URI otherwise */ static struct GNUNET_FS_Uri * -uri_loc_parse (const char *s, char **emsg) +uri_loc_parse(const char *s, char **emsg) { struct GNUNET_FS_Uri *uri; - char h1[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)]; - char h2[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)]; + char h1[sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)]; + char h2[sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)]; unsigned int pos; unsigned int npos; unsigned long long exptime; @@ -508,113 +511,113 @@ uri_loc_parse (const char *s, char **emsg) struct LocUriAssembly ass; size_t slen; - slen = strlen (s); - pos = strlen (GNUNET_FS_URI_LOC_PREFIX); - if ((slen < pos + 2 * sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) + 1) || - (0 != strncmp (s, GNUNET_FS_URI_LOC_PREFIX, pos))) + slen = strlen(s); + pos = strlen(GNUNET_FS_URI_LOC_PREFIX); + if ((slen < pos + 2 * sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) + 1) || + (0 != strncmp(s, GNUNET_FS_URI_LOC_PREFIX, pos))) return NULL; /* not a LOC URI */ - if ((s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] != '.') || - (s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2 - 1] != '.')) - { - *emsg = GNUNET_strdup (_ ("LOC URI malformed (wrong syntax)")); - return NULL; - } - GNUNET_memcpy (h1, &s[pos], sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)); - h1[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0'; - GNUNET_memcpy (h2, - &s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)], - sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded)); - h2[sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0'; - - if ((GNUNET_OK != GNUNET_CRYPTO_hash_from_string (h1, &ass.fi.chk.key)) || - (GNUNET_OK != GNUNET_CRYPTO_hash_from_string (h2, &ass.fi.chk.query)) || + if ((s[pos + sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] != '.') || + (s[pos + sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) * 2 - 1] != '.')) + { + *emsg = GNUNET_strdup(_("LOC URI malformed (wrong syntax)")); + return NULL; + } + GNUNET_memcpy(h1, &s[pos], sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)); + h1[sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0'; + GNUNET_memcpy(h2, + &s[pos + sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)], + sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded)); + h2[sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) - 1] = '\0'; + + if ((GNUNET_OK != GNUNET_CRYPTO_hash_from_string(h1, &ass.fi.chk.key)) || + (GNUNET_OK != GNUNET_CRYPTO_hash_from_string(h2, &ass.fi.chk.query)) || (1 != - sscanf (&s[pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2], - "%llu", - &flen))) - { - *emsg = GNUNET_strdup (_ ("LOC URI malformed (no CHK)")); - return NULL; - } - ass.fi.file_length = GNUNET_htonll (flen); + sscanf(&s[pos + sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) * 2], + "%llu", + &flen))) + { + *emsg = GNUNET_strdup(_("LOC URI malformed (no CHK)")); + return NULL; + } + ass.fi.file_length = GNUNET_htonll(flen); - npos = pos + sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) * 2; + npos = pos + sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) * 2; while ((s[npos] != '\0') && (s[npos] != '.')) npos++; if (s[npos] == '\0') - { - *emsg = GNUNET_strdup (_ ("LOC URI malformed (missing LOC)")); - goto ERR; - } + { + *emsg = GNUNET_strdup(_("LOC URI malformed (missing LOC)")); + goto ERR; + } npos++; - if ((strlen (&s[npos]) <= GNUNET_CRYPTO_PKEY_ASCII_LENGTH + 1) || + if ((strlen(&s[npos]) <= GNUNET_CRYPTO_PKEY_ASCII_LENGTH + 1) || ('.' != s[npos + GNUNET_CRYPTO_PKEY_ASCII_LENGTH])) - { - *emsg = - GNUNET_strdup (_ ("LOC URI malformed (wrong syntax for public key)")); - } + { + *emsg = + GNUNET_strdup(_("LOC URI malformed (wrong syntax for public key)")); + } if ( GNUNET_OK != - GNUNET_CRYPTO_eddsa_public_key_from_string (&s[npos], - GNUNET_CRYPTO_PKEY_ASCII_LENGTH, - &ass.peer.public_key)) - { - *emsg = - GNUNET_strdup (_ ("LOC URI malformed (could not decode public key)")); - goto ERR; - } + GNUNET_CRYPTO_eddsa_public_key_from_string(&s[npos], + GNUNET_CRYPTO_PKEY_ASCII_LENGTH, + &ass.peer.public_key)) + { + *emsg = + GNUNET_strdup(_("LOC URI malformed (could not decode public key)")); + goto ERR; + } npos += GNUNET_CRYPTO_PKEY_ASCII_LENGTH; if (s[npos++] != '.') - { - *emsg = GNUNET_strdup (_ ("LOC URI malformed (could not find signature)")); - goto ERR; - } - if ((strlen (&s[npos]) <= SIGNATURE_ASCII_LENGTH + 1) || + { + *emsg = GNUNET_strdup(_("LOC URI malformed (could not find signature)")); + goto ERR; + } + if ((strlen(&s[npos]) <= SIGNATURE_ASCII_LENGTH + 1) || ('.' != s[npos + SIGNATURE_ASCII_LENGTH])) - { - *emsg = - GNUNET_strdup (_ ("LOC URI malformed (wrong syntax for signature)")); - goto ERR; - } + { + *emsg = + GNUNET_strdup(_("LOC URI malformed (wrong syntax for signature)")); + goto ERR; + } if (GNUNET_OK != - GNUNET_STRINGS_string_to_data (&s[npos], - SIGNATURE_ASCII_LENGTH, - &sig, - sizeof ( - struct GNUNET_CRYPTO_EddsaSignature))) - { - *emsg = - GNUNET_strdup (_ ("LOC URI malformed (could not decode signature)")); - goto ERR; - } + GNUNET_STRINGS_string_to_data(&s[npos], + SIGNATURE_ASCII_LENGTH, + &sig, + sizeof( + struct GNUNET_CRYPTO_EddsaSignature))) + { + *emsg = + GNUNET_strdup(_("LOC URI malformed (could not decode signature)")); + goto ERR; + } npos += SIGNATURE_ASCII_LENGTH; if (s[npos++] != '.') - { - *emsg = GNUNET_strdup ( - _ ("LOC URI malformed (wrong syntax for expiration time)")); - goto ERR; - } - if (1 != sscanf (&s[npos], "%llu", &exptime)) - { - *emsg = - GNUNET_strdup (_ ("LOC URI malformed (could not parse expiration time)")); - goto ERR; - } - ass.purpose.size = htonl (sizeof (struct LocUriAssembly)); - ass.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT); + { + *emsg = GNUNET_strdup( + _("LOC URI malformed (wrong syntax for expiration time)")); + goto ERR; + } + if (1 != sscanf(&s[npos], "%llu", &exptime)) + { + *emsg = + GNUNET_strdup(_("LOC URI malformed (could not parse expiration time)")); + goto ERR; + } + ass.purpose.size = htonl(sizeof(struct LocUriAssembly)); + ass.purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT); et.abs_value_us = exptime * 1000LL * 1000LL; - ass.exptime = GNUNET_TIME_absolute_hton (et); + ass.exptime = GNUNET_TIME_absolute_hton(et); if (GNUNET_OK != - GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT, - &ass.purpose, - &sig, - &ass.peer.public_key)) - { - *emsg = - GNUNET_strdup (_ ("LOC URI malformed (signature failed validation)")); - goto ERR; - } - uri = GNUNET_new (struct GNUNET_FS_Uri); + GNUNET_CRYPTO_eddsa_verify(GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT, + &ass.purpose, + &sig, + &ass.peer.public_key)) + { + *emsg = + GNUNET_strdup(_("LOC URI malformed (signature failed validation)")); + goto ERR; + } + uri = GNUNET_new(struct GNUNET_FS_Uri); uri->type = GNUNET_FS_URI_LOC; uri->data.loc.fi = ass.fi; uri->data.loc.peer = ass.peer; @@ -635,30 +638,30 @@ ERR: * @return NULL on error */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_parse (const char *uri, char **emsg) +GNUNET_FS_uri_parse(const char *uri, char **emsg) { struct GNUNET_FS_Uri *ret; char *msg; if (NULL == uri) - { - GNUNET_break (0); - if (NULL != emsg) - *emsg = GNUNET_strdup (_ ("invalid argument")); - return NULL; - } + { + GNUNET_break(0); + if (NULL != emsg) + *emsg = GNUNET_strdup(_("invalid argument")); + return NULL; + } if (NULL == emsg) emsg = &msg; *emsg = NULL; - if ((NULL != (ret = uri_chk_parse (uri, emsg))) || - (NULL != (ret = uri_ksk_parse (uri, emsg))) || - (NULL != (ret = uri_sks_parse (uri, emsg))) || - (NULL != (ret = uri_loc_parse (uri, emsg)))) + if ((NULL != (ret = uri_chk_parse(uri, emsg))) || + (NULL != (ret = uri_ksk_parse(uri, emsg))) || + (NULL != (ret = uri_sks_parse(uri, emsg))) || + (NULL != (ret = uri_loc_parse(uri, emsg)))) return ret; if (NULL == *emsg) - *emsg = GNUNET_strdup (_ ("Unrecognized URI type")); + *emsg = GNUNET_strdup(_("Unrecognized URI type")); if (emsg == &msg) - GNUNET_free (msg); + GNUNET_free(msg); return NULL; } @@ -669,27 +672,30 @@ GNUNET_FS_uri_parse (const char *uri, char **emsg) * @param uri uri to free */ void -GNUNET_FS_uri_destroy (struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_destroy(struct GNUNET_FS_Uri *uri) { unsigned int i; switch (uri->type) - { - case GNUNET_FS_URI_KSK: - for (i = 0; i < uri->data.ksk.keywordCount; i++) - GNUNET_free (uri->data.ksk.keywords[i]); - GNUNET_array_grow (uri->data.ksk.keywords, uri->data.ksk.keywordCount, 0); - break; - case GNUNET_FS_URI_SKS: - GNUNET_free (uri->data.sks.identifier); - break; - case GNUNET_FS_URI_LOC: - break; - default: - /* do nothing */ - break; - } - GNUNET_free (uri); + { + case GNUNET_FS_URI_KSK: + for (i = 0; i < uri->data.ksk.keywordCount; i++) + GNUNET_free(uri->data.ksk.keywords[i]); + GNUNET_array_grow(uri->data.ksk.keywords, uri->data.ksk.keywordCount, 0); + break; + + case GNUNET_FS_URI_SKS: + GNUNET_free(uri->data.sks.identifier); + break; + + case GNUNET_FS_URI_LOC: + break; + + default: + /* do nothing */ + break; + } + GNUNET_free(uri); } @@ -700,7 +706,7 @@ GNUNET_FS_uri_destroy (struct GNUNET_FS_Uri *uri) * @return 0 if this is not a keyword URI */ unsigned int -GNUNET_FS_uri_ksk_get_keyword_count (const struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_ksk_get_keyword_count(const struct GNUNET_FS_Uri *uri) { if (uri->type != GNUNET_FS_URI_KSK) return 0; @@ -718,9 +724,9 @@ GNUNET_FS_uri_ksk_get_keyword_count (const struct GNUNET_FS_Uri *uri) * keywords iterated over until iterator aborted */ int -GNUNET_FS_uri_ksk_get_keywords (const struct GNUNET_FS_Uri *uri, - GNUNET_FS_KeywordIterator iterator, - void *iterator_cls) +GNUNET_FS_uri_ksk_get_keywords(const struct GNUNET_FS_Uri *uri, + GNUNET_FS_KeywordIterator iterator, + void *iterator_cls) { unsigned int i; char *keyword; @@ -730,13 +736,13 @@ GNUNET_FS_uri_ksk_get_keywords (const struct GNUNET_FS_Uri *uri, if (NULL == iterator) return uri->data.ksk.keywordCount; for (i = 0; i < uri->data.ksk.keywordCount; i++) - { - keyword = uri->data.ksk.keywords[i]; - /* first character of keyword indicates - * if it is mandatory or not */ - if (GNUNET_OK != iterator (iterator_cls, &keyword[1], keyword[0] == '+')) - return i; - } + { + keyword = uri->data.ksk.keywords[i]; + /* first character of keyword indicates + * if it is mandatory or not */ + if (GNUNET_OK != iterator(iterator_cls, &keyword[1], keyword[0] == '+')) + return i; + } return i; } @@ -750,23 +756,23 @@ GNUNET_FS_uri_ksk_get_keywords (const struct GNUNET_FS_Uri *uri, * @param is_mandatory is this keyword mandatory? */ void -GNUNET_FS_uri_ksk_add_keyword (struct GNUNET_FS_Uri *uri, - const char *keyword, - int is_mandatory) +GNUNET_FS_uri_ksk_add_keyword(struct GNUNET_FS_Uri *uri, + const char *keyword, + int is_mandatory) { unsigned int i; const char *old; char *n; - GNUNET_assert (uri->type == GNUNET_FS_URI_KSK); + GNUNET_assert(uri->type == GNUNET_FS_URI_KSK); for (i = 0; i < uri->data.ksk.keywordCount; i++) - { - old = uri->data.ksk.keywords[i]; - if (0 == strcmp (&old[1], keyword)) - return; - } - GNUNET_asprintf (&n, is_mandatory ? "+%s" : " %s", keyword); - GNUNET_array_append (uri->data.ksk.keywords, uri->data.ksk.keywordCount, n); + { + old = uri->data.ksk.keywords[i]; + if (0 == strcmp(&old[1], keyword)) + return; + } + GNUNET_asprintf(&n, is_mandatory ? "+%s" : " %s", keyword); + GNUNET_array_append(uri->data.ksk.keywords, uri->data.ksk.keywordCount, n); } @@ -778,27 +784,27 @@ GNUNET_FS_uri_ksk_add_keyword (struct GNUNET_FS_Uri *uri, * @param keyword keyword to add */ void -GNUNET_FS_uri_ksk_remove_keyword (struct GNUNET_FS_Uri *uri, - const char *keyword) +GNUNET_FS_uri_ksk_remove_keyword(struct GNUNET_FS_Uri *uri, + const char *keyword) { unsigned int i; char *old; - GNUNET_assert (uri->type == GNUNET_FS_URI_KSK); + GNUNET_assert(uri->type == GNUNET_FS_URI_KSK); for (i = 0; i < uri->data.ksk.keywordCount; i++) - { - old = uri->data.ksk.keywords[i]; - if (0 == strcmp (&old[1], keyword)) { - uri->data.ksk.keywords[i] = - uri->data.ksk.keywords[uri->data.ksk.keywordCount - 1]; - GNUNET_array_grow (uri->data.ksk.keywords, - uri->data.ksk.keywordCount, - uri->data.ksk.keywordCount - 1); - GNUNET_free (old); - return; + old = uri->data.ksk.keywords[i]; + if (0 == strcmp(&old[1], keyword)) + { + uri->data.ksk.keywords[i] = + uri->data.ksk.keywords[uri->data.ksk.keywordCount - 1]; + GNUNET_array_grow(uri->data.ksk.keywords, + uri->data.ksk.keywordCount, + uri->data.ksk.keywordCount - 1); + GNUNET_free(old); + return; + } } - } } @@ -810,8 +816,8 @@ GNUNET_FS_uri_ksk_remove_keyword (struct GNUNET_FS_Uri *uri, * @return #GNUNET_SYSERR if this is not a location URI, otherwise #GNUNET_OK */ int -GNUNET_FS_uri_loc_get_peer_identity (const struct GNUNET_FS_Uri *uri, - struct GNUNET_PeerIdentity *peer) +GNUNET_FS_uri_loc_get_peer_identity(const struct GNUNET_FS_Uri *uri, + struct GNUNET_PeerIdentity *peer) { if (uri->type != GNUNET_FS_URI_LOC) return GNUNET_SYSERR; @@ -827,9 +833,9 @@ GNUNET_FS_uri_loc_get_peer_identity (const struct GNUNET_FS_Uri *uri, * @return expiration time of the URI */ struct GNUNET_TIME_Absolute -GNUNET_FS_uri_loc_get_expiration (const struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_loc_get_expiration(const struct GNUNET_FS_Uri *uri) { - GNUNET_assert (uri->type == GNUNET_FS_URI_LOC); + GNUNET_assert(uri->type == GNUNET_FS_URI_LOC); return uri->data.loc.expirationTime; } @@ -841,13 +847,13 @@ GNUNET_FS_uri_loc_get_expiration (const struct GNUNET_FS_Uri *uri) * @return NULL if argument is not a location URI */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_loc_get_uri (const struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_loc_get_uri(const struct GNUNET_FS_Uri *uri) { struct GNUNET_FS_Uri *ret; if (uri->type != GNUNET_FS_URI_LOC) return NULL; - ret = GNUNET_new (struct GNUNET_FS_Uri); + ret = GNUNET_new(struct GNUNET_FS_Uri); ret->type = GNUNET_FS_URI_CHK; ret->data.chk = uri->data.loc.fi; return ret; @@ -867,9 +873,9 @@ GNUNET_FS_uri_loc_get_uri (const struct GNUNET_FS_Uri *uri) * @return the location URI, NULL on error */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_loc_create (const struct GNUNET_FS_Uri *base_uri, - const struct GNUNET_CRYPTO_EddsaPrivateKey *sign_key, - struct GNUNET_TIME_Absolute expiration_time) +GNUNET_FS_uri_loc_create(const struct GNUNET_FS_Uri *base_uri, + const struct GNUNET_CRYPTO_EddsaPrivateKey *sign_key, + struct GNUNET_TIME_Absolute expiration_time) { struct GNUNET_FS_Uri *uri; struct GNUNET_CRYPTO_EddsaPublicKey my_public_key; @@ -880,21 +886,21 @@ GNUNET_FS_uri_loc_create (const struct GNUNET_FS_Uri *base_uri, return NULL; /* we round expiration time to full seconds for SKS URIs */ et.abs_value_us = (expiration_time.abs_value_us / 1000000LL) * 1000000LL; - GNUNET_CRYPTO_eddsa_key_get_public (sign_key, &my_public_key); - ass.purpose.size = htonl (sizeof (struct LocUriAssembly)); - ass.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT); - ass.exptime = GNUNET_TIME_absolute_hton (et); + GNUNET_CRYPTO_eddsa_key_get_public(sign_key, &my_public_key); + ass.purpose.size = htonl(sizeof(struct LocUriAssembly)); + ass.purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT); + ass.exptime = GNUNET_TIME_absolute_hton(et); ass.fi = base_uri->data.chk; ass.peer.public_key = my_public_key; - uri = GNUNET_new (struct GNUNET_FS_Uri); + uri = GNUNET_new(struct GNUNET_FS_Uri); uri->type = GNUNET_FS_URI_LOC; uri->data.loc.fi = base_uri->data.chk; uri->data.loc.expirationTime = et; uri->data.loc.peer.public_key = my_public_key; - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_eddsa_sign (sign_key, - &ass.purpose, - &uri->data.loc.contentSignature)); + GNUNET_assert(GNUNET_OK == + GNUNET_CRYPTO_eddsa_sign(sign_key, + &ass.purpose, + &uri->data.loc.contentSignature)); return uri; } @@ -907,15 +913,15 @@ GNUNET_FS_uri_loc_create (const struct GNUNET_FS_Uri *base_uri, * @return an FS URI for the given namespace and identifier */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_sks_create (const struct GNUNET_CRYPTO_EcdsaPublicKey *ns, - const char *id) +GNUNET_FS_uri_sks_create(const struct GNUNET_CRYPTO_EcdsaPublicKey *ns, + const char *id) { struct GNUNET_FS_Uri *ns_uri; - ns_uri = GNUNET_new (struct GNUNET_FS_Uri); + ns_uri = GNUNET_new(struct GNUNET_FS_Uri); ns_uri->type = GNUNET_FS_URI_SKS; ns_uri->data.sks.ns = *ns; - ns_uri->data.sks.identifier = GNUNET_strdup (id); + ns_uri->data.sks.identifier = GNUNET_strdup(id); return ns_uri; } @@ -930,8 +936,8 @@ GNUNET_FS_uri_sks_create (const struct GNUNET_CRYPTO_EcdsaPublicKey *ns, * @return merged URI, NULL on error */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_ksk_merge (const struct GNUNET_FS_Uri *u1, - const struct GNUNET_FS_Uri *u2) +GNUNET_FS_uri_ksk_merge(const struct GNUNET_FS_Uri *u1, + const struct GNUNET_FS_Uri *u2) { struct GNUNET_FS_Uri *ret; unsigned int kc; @@ -944,34 +950,34 @@ GNUNET_FS_uri_ksk_merge (const struct GNUNET_FS_Uri *u1, if ((u1 == NULL) && (u2 == NULL)) return NULL; if (u1 == NULL) - return GNUNET_FS_uri_dup (u2); + return GNUNET_FS_uri_dup(u2); if (u2 == NULL) - return GNUNET_FS_uri_dup (u1); + return GNUNET_FS_uri_dup(u1); if ((u1->type != GNUNET_FS_URI_KSK) || (u2->type != GNUNET_FS_URI_KSK)) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } kc = u1->data.ksk.keywordCount; - kl = GNUNET_new_array (kc + u2->data.ksk.keywordCount, char *); + kl = GNUNET_new_array(kc + u2->data.ksk.keywordCount, char *); for (i = 0; i < u1->data.ksk.keywordCount; i++) - kl[i] = GNUNET_strdup (u1->data.ksk.keywords[i]); + kl[i] = GNUNET_strdup(u1->data.ksk.keywords[i]); for (i = 0; i < u2->data.ksk.keywordCount; i++) - { - kp = u2->data.ksk.keywords[i]; - found = 0; - for (j = 0; j < u1->data.ksk.keywordCount; j++) - if (0 == strcmp (kp + 1, kl[j] + 1)) - { - found = 1; - if (kp[0] == '+') - kl[j][0] = '+'; - break; - } - if (0 == found) - kl[kc++] = GNUNET_strdup (kp); - } - ret = GNUNET_new (struct GNUNET_FS_Uri); + { + kp = u2->data.ksk.keywords[i]; + found = 0; + for (j = 0; j < u1->data.ksk.keywordCount; j++) + if (0 == strcmp(kp + 1, kl[j] + 1)) + { + found = 1; + if (kp[0] == '+') + kl[j][0] = '+'; + break; + } + if (0 == found) + kl[kc++] = GNUNET_strdup(kp); + } + ret = GNUNET_new(struct GNUNET_FS_Uri); ret->type = GNUNET_FS_URI_KSK; ret->data.ksk.keywordCount = kc; ret->data.ksk.keywords = kl; @@ -986,43 +992,46 @@ GNUNET_FS_uri_ksk_merge (const struct GNUNET_FS_Uri *u1, * @return copy of the URI */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_dup (const struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_dup(const struct GNUNET_FS_Uri *uri) { struct GNUNET_FS_Uri *ret; unsigned int i; if (uri == NULL) return NULL; - ret = GNUNET_new (struct GNUNET_FS_Uri); - GNUNET_memcpy (ret, uri, sizeof (struct GNUNET_FS_Uri)); + ret = GNUNET_new(struct GNUNET_FS_Uri); + GNUNET_memcpy(ret, uri, sizeof(struct GNUNET_FS_Uri)); switch (ret->type) - { - case GNUNET_FS_URI_KSK: - if (ret->data.ksk.keywordCount >= - GNUNET_MAX_MALLOC_CHECKED / sizeof (char *)) { - GNUNET_break (0); - GNUNET_free (ret); - return NULL; - } - if (ret->data.ksk.keywordCount > 0) - { - ret->data.ksk.keywords = - GNUNET_new_array (ret->data.ksk.keywordCount, char *); - for (i = 0; i < ret->data.ksk.keywordCount; i++) - ret->data.ksk.keywords[i] = GNUNET_strdup (uri->data.ksk.keywords[i]); + case GNUNET_FS_URI_KSK: + if (ret->data.ksk.keywordCount >= + GNUNET_MAX_MALLOC_CHECKED / sizeof(char *)) + { + GNUNET_break(0); + GNUNET_free(ret); + return NULL; + } + if (ret->data.ksk.keywordCount > 0) + { + ret->data.ksk.keywords = + GNUNET_new_array(ret->data.ksk.keywordCount, char *); + for (i = 0; i < ret->data.ksk.keywordCount; i++) + ret->data.ksk.keywords[i] = GNUNET_strdup(uri->data.ksk.keywords[i]); + } + else + ret->data.ksk.keywords = NULL; /* just to be sure */ + break; + + case GNUNET_FS_URI_SKS: + ret->data.sks.identifier = GNUNET_strdup(uri->data.sks.identifier); + break; + + case GNUNET_FS_URI_LOC: + break; + + default: + break; } - else - ret->data.ksk.keywords = NULL; /* just to be sure */ - break; - case GNUNET_FS_URI_SKS: - ret->data.sks.identifier = GNUNET_strdup (uri->data.sks.identifier); - break; - case GNUNET_FS_URI_LOC: - break; - default: - break; - } return ret; } @@ -1045,7 +1054,7 @@ GNUNET_FS_uri_dup (const struct GNUNET_FS_Uri *uri) * if keywords is not legal (i.e. empty). */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_ksk_create (const char *keywords, char **emsg) +GNUNET_FS_uri_ksk_create(const char *keywords, char **emsg) { char **keywordarr; unsigned int num_Words; @@ -1056,68 +1065,68 @@ GNUNET_FS_uri_ksk_create (const char *keywords, char **emsg) int saw_quote; if (keywords == NULL) - { - *emsg = GNUNET_strdup (_ ("No keywords specified!\n")); - GNUNET_break (0); - return NULL; - } - searchString = GNUNET_strdup (keywords); + { + *emsg = GNUNET_strdup(_("No keywords specified!\n")); + GNUNET_break(0); + return NULL; + } + searchString = GNUNET_strdup(keywords); num_Words = 0; inWord = 0; saw_quote = 0; pos = searchString; while ('\0' != *pos) - { - if ((saw_quote == 0) && (isspace ((unsigned char) *pos))) { - inWord = 0; + if ((saw_quote == 0) && (isspace((unsigned char)*pos))) + { + inWord = 0; + } + else if (0 == inWord) + { + inWord = 1; + ++num_Words; + } + if ('"' == *pos) + saw_quote = (saw_quote + 1) % 2; + pos++; } - else if (0 == inWord) + if (num_Words == 0) { - inWord = 1; - ++num_Words; + GNUNET_free(searchString); + *emsg = GNUNET_strdup(_("No keywords specified!\n")); + return NULL; } - if ('"' == *pos) - saw_quote = (saw_quote + 1) % 2; - pos++; - } - if (num_Words == 0) - { - GNUNET_free (searchString); - *emsg = GNUNET_strdup (_ ("No keywords specified!\n")); - return NULL; - } if (saw_quote != 0) - { - GNUNET_free (searchString); - *emsg = GNUNET_strdup (_ ("Number of double-quotes not balanced!\n")); - return NULL; - } - keywordarr = GNUNET_new_array (num_Words, char *); + { + GNUNET_free(searchString); + *emsg = GNUNET_strdup(_("Number of double-quotes not balanced!\n")); + return NULL; + } + keywordarr = GNUNET_new_array(num_Words, char *); num_Words = 0; inWord = 0; pos = searchString; while ('\0' != *pos) - { - if ((saw_quote == 0) && (isspace ((unsigned char) *pos))) - { - inWord = 0; - *pos = '\0'; - } - else if (0 == inWord) { - keywordarr[num_Words] = pos; - inWord = 1; - ++num_Words; + if ((saw_quote == 0) && (isspace((unsigned char)*pos))) + { + inWord = 0; + *pos = '\0'; + } + else if (0 == inWord) + { + keywordarr[num_Words] = pos; + inWord = 1; + ++num_Words; + } + if ('"' == *pos) + saw_quote = (saw_quote + 1) % 2; + pos++; } - if ('"' == *pos) - saw_quote = (saw_quote + 1) % 2; - pos++; - } uri = - GNUNET_FS_uri_ksk_create_from_args (num_Words, (const char **) keywordarr); - GNUNET_free (keywordarr); - GNUNET_free (searchString); + GNUNET_FS_uri_ksk_create_from_args(num_Words, (const char **)keywordarr); + GNUNET_free(keywordarr); + GNUNET_free(searchString); return uri; } @@ -1140,7 +1149,7 @@ GNUNET_FS_uri_ksk_create (const char *keywords, char **emsg) * if keywords is not legal (i.e. empty). */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_ksk_create_from_args (unsigned int argc, const char **argv) +GNUNET_FS_uri_ksk_create_from_args(unsigned int argc, const char **argv) { unsigned int i; struct GNUNET_FS_Uri *uri; @@ -1155,36 +1164,36 @@ GNUNET_FS_uri_ksk_create_from_args (unsigned int argc, const char **argv) /* allow URI to be given as one and only keyword and * handle accordingly */ emsg = NULL; - if ((argc == 1) && (strlen (argv[0]) > strlen (GNUNET_FS_URI_PREFIX)) && - (0 == strncmp (argv[0], - GNUNET_FS_URI_PREFIX, - strlen (GNUNET_FS_URI_PREFIX))) && - (NULL != (uri = GNUNET_FS_uri_parse (argv[0], &emsg)))) + if ((argc == 1) && (strlen(argv[0]) > strlen(GNUNET_FS_URI_PREFIX)) && + (0 == strncmp(argv[0], + GNUNET_FS_URI_PREFIX, + strlen(GNUNET_FS_URI_PREFIX))) && + (NULL != (uri = GNUNET_FS_uri_parse(argv[0], &emsg)))) return uri; - GNUNET_free_non_null (emsg); - uri = GNUNET_new (struct GNUNET_FS_Uri); + GNUNET_free_non_null(emsg); + uri = GNUNET_new(struct GNUNET_FS_Uri); uri->type = GNUNET_FS_URI_KSK; uri->data.ksk.keywordCount = argc; - uri->data.ksk.keywords = GNUNET_new_array (argc, char *); + uri->data.ksk.keywords = GNUNET_new_array(argc, char *); for (i = 0; i < argc; i++) - { - keyword = argv[i]; - if (keyword[0] == '+') - val = GNUNET_strdup (keyword); - else - GNUNET_asprintf (&val, " %s", keyword); - r = val; - w = val; - while ('\0' != *r) { - if ('"' == *r) - r++; + keyword = argv[i]; + if (keyword[0] == '+') + val = GNUNET_strdup(keyword); else - *(w++) = *(r++); + GNUNET_asprintf(&val, " %s", keyword); + r = val; + w = val; + while ('\0' != *r) + { + if ('"' == *r) + r++; + else + *(w++) = *(r++); + } + *w = '\0'; + uri->data.ksk.keywords[i] = val; } - *w = '\0'; - uri->data.ksk.keywords[i] = val; - } return uri; } @@ -1197,62 +1206,66 @@ GNUNET_FS_uri_ksk_create_from_args (unsigned int argc, const char **argv) * @return #GNUNET_YES if the URIs are equal */ int -GNUNET_FS_uri_test_equal (const struct GNUNET_FS_Uri *u1, - const struct GNUNET_FS_Uri *u2) +GNUNET_FS_uri_test_equal(const struct GNUNET_FS_Uri *u1, + const struct GNUNET_FS_Uri *u2) { int ret; unsigned int i; unsigned int j; - GNUNET_assert (u1 != NULL); - GNUNET_assert (u2 != NULL); + GNUNET_assert(u1 != NULL); + GNUNET_assert(u2 != NULL); if (u1->type != u2->type) return GNUNET_NO; switch (u1->type) - { - case GNUNET_FS_URI_CHK: - if (0 == - memcmp (&u1->data.chk, &u2->data.chk, sizeof (struct FileIdentifier))) - return GNUNET_YES; - return GNUNET_NO; - case GNUNET_FS_URI_SKS: - if ((0 == memcmp (&u1->data.sks.ns, - &u2->data.sks.ns, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey))) && - (0 == strcmp (u1->data.sks.identifier, u2->data.sks.identifier))) + { + case GNUNET_FS_URI_CHK: + if (0 == + memcmp(&u1->data.chk, &u2->data.chk, sizeof(struct FileIdentifier))) + return GNUNET_YES; + return GNUNET_NO; - return GNUNET_YES; - return GNUNET_NO; - case GNUNET_FS_URI_KSK: - if (u1->data.ksk.keywordCount != u2->data.ksk.keywordCount) + case GNUNET_FS_URI_SKS: + if ((0 == memcmp(&u1->data.sks.ns, + &u2->data.sks.ns, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey))) && + (0 == strcmp(u1->data.sks.identifier, u2->data.sks.identifier))) + + return GNUNET_YES; return GNUNET_NO; - for (i = 0; i < u1->data.ksk.keywordCount; i++) - { - ret = GNUNET_NO; - for (j = 0; j < u2->data.ksk.keywordCount; j++) - { - if (0 == strcmp (u1->data.ksk.keywords[i], u2->data.ksk.keywords[j])) + + case GNUNET_FS_URI_KSK: + if (u1->data.ksk.keywordCount != u2->data.ksk.keywordCount) + return GNUNET_NO; + for (i = 0; i < u1->data.ksk.keywordCount; i++) { - ret = GNUNET_YES; - break; + ret = GNUNET_NO; + for (j = 0; j < u2->data.ksk.keywordCount; j++) + { + if (0 == strcmp(u1->data.ksk.keywords[i], u2->data.ksk.keywords[j])) + { + ret = GNUNET_YES; + break; + } + } + if (ret == GNUNET_NO) + return GNUNET_NO; } - } - if (ret == GNUNET_NO) + return GNUNET_YES; + + case GNUNET_FS_URI_LOC: + if (memcmp(&u1->data.loc, + &u2->data.loc, + sizeof(struct FileIdentifier) + + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) + + sizeof(struct GNUNET_TIME_Absolute) + + sizeof(unsigned short) + sizeof(unsigned short)) != 0) return GNUNET_NO; - } - return GNUNET_YES; - case GNUNET_FS_URI_LOC: - if (memcmp (&u1->data.loc, - &u2->data.loc, - sizeof (struct FileIdentifier) + - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) + - sizeof (struct GNUNET_TIME_Absolute) + - sizeof (unsigned short) + sizeof (unsigned short)) != 0) + return GNUNET_YES; + + default: return GNUNET_NO; - return GNUNET_YES; - default: - return GNUNET_NO; - } + } } @@ -1263,7 +1276,7 @@ GNUNET_FS_uri_test_equal (const struct GNUNET_FS_Uri *u1, * @return #GNUNET_YES if this is an SKS uri */ int -GNUNET_FS_uri_test_sks (const struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_test_sks(const struct GNUNET_FS_Uri *uri) { return uri->type == GNUNET_FS_URI_SKS; } @@ -1278,14 +1291,14 @@ GNUNET_FS_uri_test_sks (const struct GNUNET_FS_Uri *uri) * @return #GNUNET_OK on success */ int -GNUNET_FS_uri_sks_get_namespace (const struct GNUNET_FS_Uri *uri, - struct GNUNET_CRYPTO_EcdsaPublicKey *pseudonym) +GNUNET_FS_uri_sks_get_namespace(const struct GNUNET_FS_Uri *uri, + struct GNUNET_CRYPTO_EcdsaPublicKey *pseudonym) { - if (! GNUNET_FS_uri_test_sks (uri)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + if (!GNUNET_FS_uri_test_sks(uri)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } *pseudonym = uri->data.sks.ns; return GNUNET_OK; } @@ -1298,14 +1311,14 @@ GNUNET_FS_uri_sks_get_namespace (const struct GNUNET_FS_Uri *uri, * @return NULL on error (not a valid SKS URI) */ char * -GNUNET_FS_uri_sks_get_content_id (const struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_sks_get_content_id(const struct GNUNET_FS_Uri *uri) { - if (! GNUNET_FS_uri_test_sks (uri)) - { - GNUNET_break (0); - return NULL; - } - return GNUNET_strdup (uri->data.sks.identifier); + if (!GNUNET_FS_uri_test_sks(uri)) + { + GNUNET_break(0); + return NULL; + } + return GNUNET_strdup(uri->data.sks.identifier); } @@ -1316,16 +1329,16 @@ GNUNET_FS_uri_sks_get_content_id (const struct GNUNET_FS_Uri *uri) * @return #GNUNET_YES if this is a KSK uri */ int -GNUNET_FS_uri_test_ksk (const struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_test_ksk(const struct GNUNET_FS_Uri *uri) { #if EXTRA_CHECKS unsigned int i; if (uri->type == GNUNET_FS_URI_KSK) - { - for (i = 0; i < uri->data.ksk.keywordCount; i++) - GNUNET_assert (uri->data.ksk.keywords[i] != NULL); - } + { + for (i = 0; i < uri->data.ksk.keywordCount; i++) + GNUNET_assert(uri->data.ksk.keywords[i] != NULL); + } #endif return uri->type == GNUNET_FS_URI_KSK; } @@ -1338,7 +1351,7 @@ GNUNET_FS_uri_test_ksk (const struct GNUNET_FS_Uri *uri) * @return #GNUNET_YES if this is a CHK uri */ int -GNUNET_FS_uri_test_chk (const struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_test_chk(const struct GNUNET_FS_Uri *uri) { return uri->type == GNUNET_FS_URI_CHK; } @@ -1352,17 +1365,19 @@ GNUNET_FS_uri_test_chk (const struct GNUNET_FS_Uri *uri) * @return size of the file as specified in the CHK URI */ uint64_t -GNUNET_FS_uri_chk_get_file_size (const struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_chk_get_file_size(const struct GNUNET_FS_Uri *uri) { switch (uri->type) - { - case GNUNET_FS_URI_CHK: - return GNUNET_ntohll (uri->data.chk.file_length); - case GNUNET_FS_URI_LOC: - return GNUNET_ntohll (uri->data.loc.fi.file_length); - default: - GNUNET_assert (0); - } + { + case GNUNET_FS_URI_CHK: + return GNUNET_ntohll(uri->data.chk.file_length); + + case GNUNET_FS_URI_LOC: + return GNUNET_ntohll(uri->data.loc.fi.file_length); + + default: + GNUNET_assert(0); + } return 0; /* unreachable */ } @@ -1374,7 +1389,7 @@ GNUNET_FS_uri_chk_get_file_size (const struct GNUNET_FS_Uri *uri) * @return #GNUNET_YES if this is a LOC uri */ int -GNUNET_FS_uri_test_loc (const struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_test_loc(const struct GNUNET_FS_Uri *uri) { return uri->type == GNUNET_FS_URI_LOC; } @@ -1390,13 +1405,13 @@ GNUNET_FS_uri_test_loc (const struct GNUNET_FS_Uri *uri) * @param index offset where to add the keyword */ static void -insert_non_mandatory_keyword (const char *s, char **array, int index) +insert_non_mandatory_keyword(const char *s, char **array, int index) { char *nkword; - GNUNET_asprintf (&nkword, - " %s", /* space to mark as 'non mandatory' */ - s); + GNUNET_asprintf(&nkword, + " %s", /* space to mark as 'non mandatory' */ + s); array[index] = nkword; } @@ -1411,12 +1426,12 @@ insert_non_mandatory_keyword (const char *s, char **array, int index) * @return #GNUNET_YES if the keyword exists, #GNUNET_NO if not */ static int -find_duplicate (const char *s, const char **array, int array_length) +find_duplicate(const char *s, const char **array, int array_length) { int j; for (j = array_length - 1; j >= 0; j--) - if (0 == strcmp (&array[j][1], s)) + if (0 == strcmp(&array[j][1], s)) return GNUNET_YES; return GNUNET_NO; } @@ -1426,53 +1441,54 @@ find_duplicate (const char *s, const char **array, int array_length) * FIXME: comment */ static char * -normalize_metadata (enum EXTRACTOR_MetaFormat format, - const char *data, - size_t data_len) +normalize_metadata(enum EXTRACTOR_MetaFormat format, + const char *data, + size_t data_len) { uint8_t *free_str = NULL; - uint8_t *str_to_normalize = (uint8_t *) data; + uint8_t *str_to_normalize = (uint8_t *)data; uint8_t *normalized; size_t r_len; + if (str_to_normalize == NULL) return NULL; /* Don't trust libextractor */ if (format == EXTRACTOR_METAFORMAT_UTF8) - { - free_str = (uint8_t *) u8_check ((const uint8_t *) data, data_len); - if (free_str == NULL) - free_str = NULL; - else - format = EXTRACTOR_METAFORMAT_C_STRING; - } + { + free_str = (uint8_t *)u8_check((const uint8_t *)data, data_len); + if (free_str == NULL) + free_str = NULL; + else + format = EXTRACTOR_METAFORMAT_C_STRING; + } if (format == EXTRACTOR_METAFORMAT_C_STRING) - { - free_str = u8_strconv_from_encoding (data, - locale_charset (), - iconveh_escape_sequence); - if (free_str == NULL) - return NULL; - } - - normalized = u8_tolower (str_to_normalize, - strlen ((char *) str_to_normalize), - NULL, - UNINORM_NFD, - NULL, - &r_len); + { + free_str = u8_strconv_from_encoding(data, + locale_charset(), + iconveh_escape_sequence); + if (free_str == NULL) + return NULL; + } + + normalized = u8_tolower(str_to_normalize, + strlen((char *)str_to_normalize), + NULL, + UNINORM_NFD, + NULL, + &r_len); /* free_str is allocated by libunistring internally, use free() */ if (free_str != NULL) - free (free_str); + free(free_str); if (normalized != NULL) - { - /* u8_tolower allocates a non-NULL-terminated string! */ - free_str = GNUNET_malloc (r_len + 1); - GNUNET_memcpy (free_str, normalized, r_len); - free_str[r_len] = '\0'; - free (normalized); - normalized = free_str; - } - return (char *) normalized; + { + /* u8_tolower allocates a non-NULL-terminated string! */ + free_str = GNUNET_malloc(r_len + 1); + GNUNET_memcpy(free_str, normalized, r_len); + free_str[r_len] = '\0'; + free(normalized); + normalized = free_str; + } + return (char *)normalized; } @@ -1481,15 +1497,16 @@ normalize_metadata (enum EXTRACTOR_MetaFormat format, * returns that count. */ static size_t -u8_strcount (const uint8_t *s) +u8_strcount(const uint8_t *s) { size_t count; ucs4_t c; - GNUNET_assert (s != NULL); + + GNUNET_assert(s != NULL); if (s[0] == 0) return 0; for (count = 0; s != NULL; count++) - s = u8_next (&c, s); + s = u8_next(&c, s); return count - 1; } @@ -1511,7 +1528,7 @@ u8_strcount (const uint8_t *s) * were duplicates (when extracting). */ static int -get_keywords_from_parens (const char *s, char **array, int index) +get_keywords_from_parens(const char *s, char **array, int index) { int count = 0; char *open_paren; @@ -1521,77 +1538,80 @@ get_keywords_from_parens (const char *s, char **array, int index) if (NULL == s) return 0; - ss = GNUNET_strdup (s); + ss = GNUNET_strdup(s); open_paren = ss - 1; - while (NULL != (open_paren = strpbrk (open_paren + 1, "[{("))) - { - int match = 0; - - close_paren = strpbrk (open_paren + 1, "]})"); - if (NULL == close_paren) - continue; - switch (open_paren[0]) - { - case '[': - if (']' == close_paren[0]) - match = 1; - break; - case '{': - if ('}' == close_paren[0]) - match = 1; - break; - case '(': - if (')' == close_paren[0]) - match = 1; - break; - default: - break; - } - if (match && (close_paren - open_paren > 1)) + while (NULL != (open_paren = strpbrk(open_paren + 1, "[{("))) { - tmp = close_paren[0]; - close_paren[0] = '\0'; - /* Keywords must be at least 3 characters long */ - if (u8_strcount ((const uint8_t *) &open_paren[1]) <= 2) - { - close_paren[0] = tmp; + int match = 0; + + close_paren = strpbrk(open_paren + 1, "]})"); + if (NULL == close_paren) continue; - } - if (NULL != array) - { - char *normalized; - if (GNUNET_NO == find_duplicate ((const char *) &open_paren[1], - (const char **) array, - index + count)) + switch (open_paren[0]) { - insert_non_mandatory_keyword ((const char *) &open_paren[1], - array, - index + count); - count++; + case '[': + if (']' == close_paren[0]) + match = 1; + break; + + case '{': + if ('}' == close_paren[0]) + match = 1; + break; + + case '(': + if (')' == close_paren[0]) + match = 1; + break; + + default: + break; } - normalized = normalize_metadata (EXTRACTOR_METAFORMAT_UTF8, - &open_paren[1], - close_paren - &open_paren[1]); - if (normalized != NULL) + if (match && (close_paren - open_paren > 1)) { - if (GNUNET_NO == find_duplicate ((const char *) normalized, - (const char **) array, - index + count)) - { - insert_non_mandatory_keyword ((const char *) normalized, - array, - index + count); + tmp = close_paren[0]; + close_paren[0] = '\0'; + /* Keywords must be at least 3 characters long */ + if (u8_strcount((const uint8_t *)&open_paren[1]) <= 2) + { + close_paren[0] = tmp; + continue; + } + if (NULL != array) + { + char *normalized; + if (GNUNET_NO == find_duplicate((const char *)&open_paren[1], + (const char **)array, + index + count)) + { + insert_non_mandatory_keyword((const char *)&open_paren[1], + array, + index + count); + count++; + } + normalized = normalize_metadata(EXTRACTOR_METAFORMAT_UTF8, + &open_paren[1], + close_paren - &open_paren[1]); + if (normalized != NULL) + { + if (GNUNET_NO == find_duplicate((const char *)normalized, + (const char **)array, + index + count)) + { + insert_non_mandatory_keyword((const char *)normalized, + array, + index + count); + count++; + } + GNUNET_free(normalized); + } + } + else count++; - } - GNUNET_free (normalized); + close_paren[0] = tmp; } - } - else - count++; - close_paren[0] = tmp; } - } - GNUNET_free (ss); + GNUNET_free(ss); return count; } @@ -1616,46 +1636,46 @@ get_keywords_from_parens (const char *s, char **array, int index) * duplicates (when extracting). */ static int -get_keywords_from_tokens (const char *s, char **array, int index) +get_keywords_from_tokens(const char *s, char **array, int index) { char *p; char *ss; int seps = 0; - ss = GNUNET_strdup (s); - for (p = strtok (ss, TOKENS); p != NULL; p = strtok (NULL, TOKENS)) - { - /* Keywords must be at least 3 characters long */ - if (u8_strcount ((const uint8_t *) p) <= 2) - continue; - if (NULL != array) + ss = GNUNET_strdup(s); + for (p = strtok(ss, TOKENS); p != NULL; p = strtok(NULL, TOKENS)) { - char *normalized; - if (GNUNET_NO == find_duplicate (p, (const char **) array, index + seps)) - { - insert_non_mandatory_keyword (p, array, index + seps); - seps++; - } - normalized = - normalize_metadata (EXTRACTOR_METAFORMAT_UTF8, p, strlen (p)); - if (normalized != NULL) - { - if (GNUNET_NO == find_duplicate ((const char *) normalized, - (const char **) array, - index + seps)) + /* Keywords must be at least 3 characters long */ + if (u8_strcount((const uint8_t *)p) <= 2) + continue; + if (NULL != array) { - insert_non_mandatory_keyword ((const char *) normalized, - array, - index + seps); - seps++; + char *normalized; + if (GNUNET_NO == find_duplicate(p, (const char **)array, index + seps)) + { + insert_non_mandatory_keyword(p, array, index + seps); + seps++; + } + normalized = + normalize_metadata(EXTRACTOR_METAFORMAT_UTF8, p, strlen(p)); + if (normalized != NULL) + { + if (GNUNET_NO == find_duplicate((const char *)normalized, + (const char **)array, + index + seps)) + { + insert_non_mandatory_keyword((const char *)normalized, + array, + index + seps); + seps++; + } + GNUNET_free(normalized); + } } - GNUNET_free (normalized); - } + else + seps++; } - else - seps++; - } - GNUNET_free (ss); + GNUNET_free(ss); return seps; } #undef TOKENS @@ -1679,13 +1699,13 @@ get_keywords_from_tokens (const char *s, char **array, int index) * @return 0 (always) */ static int -gather_uri_data (void *cls, - const char *plugin_name, - enum EXTRACTOR_MetaType type, - enum EXTRACTOR_MetaFormat format, - const char *data_mime_type, - const char *data, - size_t data_len) +gather_uri_data(void *cls, + const char *plugin_name, + enum EXTRACTOR_MetaType type, + enum EXTRACTOR_MetaFormat format, + const char *data_mime_type, + const char *data, + size_t data_len) { struct GNUNET_FS_Uri *uri = cls; char *normalized_data; @@ -1699,49 +1719,49 @@ gather_uri_data (void *cls, * and will return the length of its valid part, skipping the keyword. * If it does - fix the extractor, not this check! */ - if (u8_strcount ((const uint8_t *) data) <= 2) + if (u8_strcount((const uint8_t *)data) <= 2) return 0; if ((EXTRACTOR_METATYPE_MIMETYPE == type) && - (NULL != (sep = memchr (data, '/', data_len))) && (sep != data)) - { - char *xtra; + (NULL != (sep = memchr(data, '/', data_len))) && (sep != data)) + { + char *xtra; - GNUNET_asprintf (&xtra, "mimetype:%.*s", (int) (sep - data), data); - if (! find_duplicate (xtra, - (const char **) uri->data.ksk.keywords, + GNUNET_asprintf(&xtra, "mimetype:%.*s", (int)(sep - data), data); + if (!find_duplicate(xtra, + (const char **)uri->data.ksk.keywords, uri->data.ksk.keywordCount)) + { + insert_non_mandatory_keyword(xtra, + uri->data.ksk.keywords, + uri->data.ksk.keywordCount); + uri->data.ksk.keywordCount++; + } + GNUNET_free(xtra); + } + + normalized_data = normalize_metadata(format, data, data_len); + if (!find_duplicate(data, + (const char **)uri->data.ksk.keywords, + uri->data.ksk.keywordCount)) { - insert_non_mandatory_keyword (xtra, - uri->data.ksk.keywords, - uri->data.ksk.keywordCount); + insert_non_mandatory_keyword(data, + uri->data.ksk.keywords, + uri->data.ksk.keywordCount); uri->data.ksk.keywordCount++; } - GNUNET_free (xtra); - } - - normalized_data = normalize_metadata (format, data, data_len); - if (! find_duplicate (data, - (const char **) uri->data.ksk.keywords, - uri->data.ksk.keywordCount)) - { - insert_non_mandatory_keyword (data, - uri->data.ksk.keywords, - uri->data.ksk.keywordCount); - uri->data.ksk.keywordCount++; - } if (NULL != normalized_data) - { - if (! find_duplicate (normalized_data, - (const char **) uri->data.ksk.keywords, - uri->data.ksk.keywordCount)) { - insert_non_mandatory_keyword (normalized_data, - uri->data.ksk.keywords, - uri->data.ksk.keywordCount); - uri->data.ksk.keywordCount++; + if (!find_duplicate(normalized_data, + (const char **)uri->data.ksk.keywords, + uri->data.ksk.keywordCount)) + { + insert_non_mandatory_keyword(normalized_data, + uri->data.ksk.keywords, + uri->data.ksk.keywordCount); + uri->data.ksk.keywordCount++; + } + GNUNET_free(normalized_data); } - GNUNET_free (normalized_data); - } return 0; } @@ -1755,7 +1775,7 @@ gather_uri_data (void *cls, * @return NULL on error, otherwise a KSK URI */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_ksk_create_from_meta_data ( +GNUNET_FS_uri_ksk_create_from_meta_data( const struct GNUNET_CONTAINER_MetaData *md) { struct GNUNET_FS_Uri *ret; @@ -1768,41 +1788,41 @@ GNUNET_FS_uri_ksk_create_from_meta_data ( if (NULL == md) return NULL; - ret = GNUNET_new (struct GNUNET_FS_Uri); + ret = GNUNET_new(struct GNUNET_FS_Uri); ret->type = GNUNET_FS_URI_KSK; - ent = GNUNET_CONTAINER_meta_data_iterate (md, NULL, NULL); + ent = GNUNET_CONTAINER_meta_data_iterate(md, NULL, NULL); if (ent > 0) - { - full_name = GNUNET_CONTAINER_meta_data_get_first_by_types ( - md, - EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME, - -1); - if (NULL != full_name) { - filename = full_name; - while (NULL != (ss = strstr (filename, DIR_SEPARATOR_STR))) - filename = ss + 1; - tok_keywords = get_keywords_from_tokens (filename, NULL, 0); - paren_keywords = get_keywords_from_parens (filename, NULL, 0); + full_name = GNUNET_CONTAINER_meta_data_get_first_by_types( + md, + EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME, + -1); + if (NULL != full_name) + { + filename = full_name; + while (NULL != (ss = strstr(filename, DIR_SEPARATOR_STR))) + filename = ss + 1; + tok_keywords = get_keywords_from_tokens(filename, NULL, 0); + paren_keywords = get_keywords_from_parens(filename, NULL, 0); + } + /* x3 because there might be a normalized variant of every keyword, + plus theoretically one more for mime... */ + ret->data.ksk.keywords = + GNUNET_new_array((ent + tok_keywords + paren_keywords) * 3, char *); + GNUNET_CONTAINER_meta_data_iterate(md, &gather_uri_data, ret); } - /* x3 because there might be a normalized variant of every keyword, - plus theoretically one more for mime... */ - ret->data.ksk.keywords = - GNUNET_new_array ((ent + tok_keywords + paren_keywords) * 3, char *); - GNUNET_CONTAINER_meta_data_iterate (md, &gather_uri_data, ret); - } if (tok_keywords > 0) ret->data.ksk.keywordCount += - get_keywords_from_tokens (filename, - ret->data.ksk.keywords, - ret->data.ksk.keywordCount); + get_keywords_from_tokens(filename, + ret->data.ksk.keywords, + ret->data.ksk.keywordCount); if (paren_keywords > 0) ret->data.ksk.keywordCount += - get_keywords_from_parens (filename, - ret->data.ksk.keywords, - ret->data.ksk.keywordCount); + get_keywords_from_parens(filename, + ret->data.ksk.keywords, + ret->data.ksk.keywordCount); if (ent > 0) - GNUNET_free_non_null (full_name); + GNUNET_free_non_null(full_name); return ret; } @@ -1812,10 +1832,10 @@ GNUNET_FS_uri_ksk_create_from_meta_data ( * need to be encoded using %-encoding? */ static int -needs_percent (char c) +needs_percent(char c) { - return (! ((isalnum ((unsigned char) c)) || (c == '-') || (c == '_') || - (c == '.') || (c == '~'))); + return(!((isalnum((unsigned char)c)) || (c == '-') || (c == '_') || + (c == '.') || (c == '~'))); } @@ -1826,7 +1846,7 @@ needs_percent (char c) * @return NULL on error (i.e. keywordCount == 0) */ static char * -uri_ksk_to_string (const struct GNUNET_FS_Uri *uri) +uri_ksk_to_string(const struct GNUNET_FS_Uri *uri) { char **keywords; unsigned int keywordCount; @@ -1842,49 +1862,49 @@ uri_ksk_to_string (const struct GNUNET_FS_Uri *uri) return NULL; keywords = uri->data.ksk.keywords; keywordCount = uri->data.ksk.keywordCount; - n = keywordCount + strlen (GNUNET_FS_URI_PREFIX) + - strlen (GNUNET_FS_URI_KSK_INFIX) + 1; + n = keywordCount + strlen(GNUNET_FS_URI_PREFIX) + + strlen(GNUNET_FS_URI_KSK_INFIX) + 1; for (i = 0; i < keywordCount; i++) - { - keyword = keywords[i]; - slen = strlen (keyword); - n += slen; - for (j = 0; j < slen; j++) { - if ((j == 0) && (keyword[j] == ' ')) - { - n--; - continue; /* skip leading space */ - } - if (needs_percent (keyword[j])) - n += 2; /* will use %-encoding */ + keyword = keywords[i]; + slen = strlen(keyword); + n += slen; + for (j = 0; j < slen; j++) + { + if ((j == 0) && (keyword[j] == ' ')) + { + n--; + continue; /* skip leading space */ + } + if (needs_percent(keyword[j])) + n += 2; /* will use %-encoding */ + } } - } - ret = GNUNET_malloc (n); - strcpy (ret, GNUNET_FS_URI_PREFIX); - strcat (ret, GNUNET_FS_URI_KSK_INFIX); - wpos = strlen (ret); + ret = GNUNET_malloc(n); + strcpy(ret, GNUNET_FS_URI_PREFIX); + strcat(ret, GNUNET_FS_URI_KSK_INFIX); + wpos = strlen(ret); for (i = 0; i < keywordCount; i++) - { - keyword = keywords[i]; - slen = strlen (keyword); - for (j = 0; j < slen; j++) { - if ((j == 0) && (keyword[j] == ' ')) - continue; /* skip leading space */ - if (needs_percent (keyword[j])) - { - sprintf (&ret[wpos], "%%%02X", (unsigned char) keyword[j]); - wpos += 3; - } - else - { - ret[wpos++] = keyword[j]; - } + keyword = keywords[i]; + slen = strlen(keyword); + for (j = 0; j < slen; j++) + { + if ((j == 0) && (keyword[j] == ' ')) + continue; /* skip leading space */ + if (needs_percent(keyword[j])) + { + sprintf(&ret[wpos], "%%%02X", (unsigned char)keyword[j]); + wpos += 3; + } + else + { + ret[wpos++] = keyword[j]; + } + } + if (i != keywordCount - 1) + ret[wpos++] = '+'; } - if (i != keywordCount - 1) - ret[wpos++] = '+'; - } return ret; } @@ -1896,7 +1916,7 @@ uri_ksk_to_string (const struct GNUNET_FS_Uri *uri) * @return NULL on error */ static char * -uri_sks_to_string (const struct GNUNET_FS_Uri *uri) +uri_sks_to_string(const struct GNUNET_FS_Uri *uri) { char *ret; char buf[1024]; @@ -1904,18 +1924,18 @@ uri_sks_to_string (const struct GNUNET_FS_Uri *uri) if (GNUNET_FS_URI_SKS != uri->type) return NULL; ret = - GNUNET_STRINGS_data_to_string (&uri->data.sks.ns, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey), - buf, - sizeof (buf)); - GNUNET_assert (NULL != ret); + GNUNET_STRINGS_data_to_string(&uri->data.sks.ns, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey), + buf, + sizeof(buf)); + GNUNET_assert(NULL != ret); ret[0] = '\0'; - GNUNET_asprintf (&ret, - "%s%s%s/%s", - GNUNET_FS_URI_PREFIX, - GNUNET_FS_URI_SKS_INFIX, - buf, - uri->data.sks.identifier); + GNUNET_asprintf(&ret, + "%s%s%s/%s", + GNUNET_FS_URI_PREFIX, + GNUNET_FS_URI_SKS_INFIX, + buf, + uri->data.sks.identifier); return ret; } @@ -1927,7 +1947,7 @@ uri_sks_to_string (const struct GNUNET_FS_Uri *uri) * @return NULL on error */ static char * -uri_chk_to_string (const struct GNUNET_FS_Uri *uri) +uri_chk_to_string(const struct GNUNET_FS_Uri *uri) { const struct FileIdentifier *fi; char *ret; @@ -1937,16 +1957,16 @@ uri_chk_to_string (const struct GNUNET_FS_Uri *uri) if (uri->type != GNUNET_FS_URI_CHK) return NULL; fi = &uri->data.chk; - GNUNET_CRYPTO_hash_to_enc (&fi->chk.key, &keyhash); - GNUNET_CRYPTO_hash_to_enc (&fi->chk.query, &queryhash); - - GNUNET_asprintf (&ret, - "%s%s%s.%s.%llu", - GNUNET_FS_URI_PREFIX, - GNUNET_FS_URI_CHK_INFIX, - (const char *) &keyhash, - (const char *) &queryhash, - GNUNET_ntohll (fi->file_length)); + GNUNET_CRYPTO_hash_to_enc(&fi->chk.key, &keyhash); + GNUNET_CRYPTO_hash_to_enc(&fi->chk.query, &queryhash); + + GNUNET_asprintf(&ret, + "%s%s%s.%s.%llu", + GNUNET_FS_URI_PREFIX, + GNUNET_FS_URI_CHK_INFIX, + (const char *)&keyhash, + (const char *)&queryhash, + GNUNET_ntohll(fi->file_length)); return ret; } @@ -1958,7 +1978,7 @@ uri_chk_to_string (const struct GNUNET_FS_Uri *uri) * @return NULL on error */ static char * -uri_loc_to_string (const struct GNUNET_FS_Uri *uri) +uri_loc_to_string(const struct GNUNET_FS_Uri *uri) { char *ret; struct GNUNET_CRYPTO_HashAsciiEncoded keyhash; @@ -1966,30 +1986,30 @@ uri_loc_to_string (const struct GNUNET_FS_Uri *uri) char *peer_id; char peer_sig[SIGNATURE_ASCII_LENGTH + 1]; - GNUNET_CRYPTO_hash_to_enc (&uri->data.loc.fi.chk.key, &keyhash); - GNUNET_CRYPTO_hash_to_enc (&uri->data.loc.fi.chk.query, &queryhash); + GNUNET_CRYPTO_hash_to_enc(&uri->data.loc.fi.chk.key, &keyhash); + GNUNET_CRYPTO_hash_to_enc(&uri->data.loc.fi.chk.query, &queryhash); peer_id = - GNUNET_CRYPTO_eddsa_public_key_to_string (&uri->data.loc.peer.public_key); - GNUNET_assert ( + GNUNET_CRYPTO_eddsa_public_key_to_string(&uri->data.loc.peer.public_key); + GNUNET_assert( NULL != - GNUNET_STRINGS_data_to_string (&uri->data.loc.contentSignature, - sizeof (struct GNUNET_CRYPTO_EddsaSignature), - peer_sig, - sizeof (peer_sig))); - GNUNET_asprintf (&ret, - "%s%s%s.%s.%llu.%s.%s.%llu", - GNUNET_FS_URI_PREFIX, - GNUNET_FS_URI_LOC_INFIX, - (const char *) &keyhash, - (const char *) &queryhash, - (unsigned long long) GNUNET_ntohll ( - uri->data.loc.fi.file_length), - peer_id, - peer_sig, - (unsigned long long) - uri->data.loc.expirationTime.abs_value_us / - 1000000LL); - GNUNET_free (peer_id); + GNUNET_STRINGS_data_to_string(&uri->data.loc.contentSignature, + sizeof(struct GNUNET_CRYPTO_EddsaSignature), + peer_sig, + sizeof(peer_sig))); + GNUNET_asprintf(&ret, + "%s%s%s.%s.%llu.%s.%s.%llu", + GNUNET_FS_URI_PREFIX, + GNUNET_FS_URI_LOC_INFIX, + (const char *)&keyhash, + (const char *)&queryhash, + (unsigned long long)GNUNET_ntohll( + uri->data.loc.fi.file_length), + peer_id, + peer_sig, + (unsigned long long) + uri->data.loc.expirationTime.abs_value_us / + 1000000LL); + GNUNET_free(peer_id); return ret; } @@ -2001,27 +2021,31 @@ uri_loc_to_string (const struct GNUNET_FS_Uri *uri) * @return the UTF-8 string */ char * -GNUNET_FS_uri_to_string (const struct GNUNET_FS_Uri *uri) +GNUNET_FS_uri_to_string(const struct GNUNET_FS_Uri *uri) { if (uri == NULL) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } switch (uri->type) - { - case GNUNET_FS_URI_KSK: - return uri_ksk_to_string (uri); - case GNUNET_FS_URI_SKS: - return uri_sks_to_string (uri); - case GNUNET_FS_URI_CHK: - return uri_chk_to_string (uri); - case GNUNET_FS_URI_LOC: - return uri_loc_to_string (uri); - default: - GNUNET_break (0); - return NULL; - } + { + case GNUNET_FS_URI_KSK: + return uri_ksk_to_string(uri); + + case GNUNET_FS_URI_SKS: + return uri_sks_to_string(uri); + + case GNUNET_FS_URI_CHK: + return uri_chk_to_string(uri); + + case GNUNET_FS_URI_LOC: + return uri_loc_to_string(uri); + + default: + GNUNET_break(0); + return NULL; + } } /* end of fs_uri.c */ diff --git a/src/fs/gnunet-auto-share.c b/src/fs/gnunet-auto-share.c index 8b04e474d..6fc71ebe5 100644 --- a/src/fs/gnunet-auto-share.c +++ b/src/fs/gnunet-auto-share.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-auto-share.c * @brief automatically publish files on GNUnet @@ -29,7 +29,7 @@ #include "platform.h" #include "gnunet_util_lib.h" -#define MAX_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 4) +#define MAX_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_HOURS, 4) #define MIN_DELAY GNUNET_TIME_UNIT_MINUTES @@ -38,9 +38,7 @@ * Item in our work queue (or in the set of files/directories * we have successfully published). */ -struct WorkItem -{ - +struct WorkItem { /** * PENDING Work is kept in a linked list. */ @@ -162,16 +160,16 @@ static struct GNUNET_OS_Process *publish_proc; * Compute the name of the state database file we will use. */ static char * -get_state_file () +get_state_file() { char *ret; - GNUNET_asprintf (&ret, - "%s%s.auto-share", - dir_name, - (DIR_SEPARATOR == dir_name[strlen (dir_name) - 1]) - ? "" - : DIR_SEPARATOR_STR); + GNUNET_asprintf(&ret, + "%s%s.auto-share", + dir_name, + (DIR_SEPARATOR == dir_name[strlen(dir_name) - 1]) + ? "" + : DIR_SEPARATOR_STR); return ret; } @@ -180,7 +178,7 @@ get_state_file () * Load the set of #work_finished items from disk. */ static void -load_state () +load_state() { char *fn; struct GNUNET_BIO_ReadHandle *rh; @@ -190,47 +188,47 @@ load_state () char *emsg; emsg = NULL; - fn = get_state_file (); - rh = GNUNET_BIO_read_open (fn); - GNUNET_free (fn); + fn = get_state_file(); + rh = GNUNET_BIO_read_open(fn); + GNUNET_free(fn); if (NULL == rh) return; fn = NULL; - if (GNUNET_OK != GNUNET_BIO_read_int32 (rh, &n)) + if (GNUNET_OK != GNUNET_BIO_read_int32(rh, &n)) goto error; while (n-- > 0) - { - if ((GNUNET_OK != GNUNET_BIO_read_string (rh, "filename", &fn, 1024)) || - (GNUNET_OK != - GNUNET_BIO_read (rh, "id", &id, sizeof (struct GNUNET_HashCode)))) - goto error; - wi = GNUNET_new (struct WorkItem); - wi->id = id; - wi->filename = fn; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Loaded serialization ID for `%s' is `%s'\n", - wi->filename, - GNUNET_h2s (&id)); - fn = NULL; - GNUNET_CRYPTO_hash (wi->filename, strlen (wi->filename), &id); - GNUNET_break (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put ( - work_finished, - &id, - wi, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - } - if (GNUNET_OK == GNUNET_BIO_read_close (rh, &emsg)) + { + if ((GNUNET_OK != GNUNET_BIO_read_string(rh, "filename", &fn, 1024)) || + (GNUNET_OK != + GNUNET_BIO_read(rh, "id", &id, sizeof(struct GNUNET_HashCode)))) + goto error; + wi = GNUNET_new(struct WorkItem); + wi->id = id; + wi->filename = fn; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Loaded serialization ID for `%s' is `%s'\n", + wi->filename, + GNUNET_h2s(&id)); + fn = NULL; + GNUNET_CRYPTO_hash(wi->filename, strlen(wi->filename), &id); + GNUNET_break(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put( + work_finished, + &id, + wi, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + } + if (GNUNET_OK == GNUNET_BIO_read_close(rh, &emsg)) return; rh = NULL; error: - GNUNET_free_non_null (fn); + GNUNET_free_non_null(fn); if (NULL != rh) - (void) GNUNET_BIO_read_close (rh, &emsg); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to load state: %s\n"), - emsg); - GNUNET_free_non_null (emsg); + (void)GNUNET_BIO_read_close(rh, &emsg); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to load state: %s\n"), + emsg); + GNUNET_free_non_null(emsg); } @@ -243,18 +241,18 @@ error: * @return #GNUNET_OK to continue to iterate (if write worked) */ static int -write_item (void *cls, const struct GNUNET_HashCode *key, void *value) +write_item(void *cls, const struct GNUNET_HashCode *key, void *value) { struct GNUNET_BIO_WriteHandle *wh = cls; struct WorkItem *wi = value; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Saving serialization ID of file `%s' with value `%s'\n", - wi->filename, - GNUNET_h2s (&wi->id)); - if ((GNUNET_OK != GNUNET_BIO_write_string (wh, wi->filename)) || + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Saving serialization ID of file `%s' with value `%s'\n", + wi->filename, + GNUNET_h2s(&wi->id)); + if ((GNUNET_OK != GNUNET_BIO_write_string(wh, wi->filename)) || (GNUNET_OK != - GNUNET_BIO_write (wh, &wi->id, sizeof (struct GNUNET_HashCode)))) + GNUNET_BIO_write(wh, &wi->id, sizeof(struct GNUNET_HashCode)))) return GNUNET_SYSERR; /* write error, abort iteration */ return GNUNET_OK; } @@ -264,38 +262,38 @@ write_item (void *cls, const struct GNUNET_HashCode *key, void *value) * Save the set of #work_finished items on disk. */ static void -save_state () +save_state() { uint32_t n; struct GNUNET_BIO_WriteHandle *wh; char *fn; - n = GNUNET_CONTAINER_multihashmap_size (work_finished); - fn = get_state_file (); - wh = GNUNET_BIO_write_open (fn); + n = GNUNET_CONTAINER_multihashmap_size(work_finished); + fn = get_state_file(); + wh = GNUNET_BIO_write_open(fn); if (NULL == wh) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to save state to file %s\n"), - fn); - GNUNET_free (fn); - return; - } - if (GNUNET_OK != GNUNET_BIO_write_int32 (wh, n)) - { - (void) GNUNET_BIO_write_close (wh); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to save state to file %s\n"), - fn); - GNUNET_free (fn); - return; - } - (void) GNUNET_CONTAINER_multihashmap_iterate (work_finished, &write_item, wh); - if (GNUNET_OK != GNUNET_BIO_write_close (wh)) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to save state to file %s\n"), - fn); - GNUNET_free (fn); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to save state to file %s\n"), + fn); + GNUNET_free(fn); + return; + } + if (GNUNET_OK != GNUNET_BIO_write_int32(wh, n)) + { + (void)GNUNET_BIO_write_close(wh); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to save state to file %s\n"), + fn); + GNUNET_free(fn); + return; + } + (void)GNUNET_CONTAINER_multihashmap_iterate(work_finished, &write_item, wh); + if (GNUNET_OK != GNUNET_BIO_write_close(wh)) + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to save state to file %s\n"), + fn); + GNUNET_free(fn); } @@ -305,19 +303,19 @@ save_state () * @param cls closure, unused */ static void -do_stop_task (void *cls) +do_stop_task(void *cls) { do_shutdown = GNUNET_YES; if (NULL != publish_proc) - { - GNUNET_OS_process_kill (publish_proc, SIGKILL); - return; - } + { + GNUNET_OS_process_kill(publish_proc, SIGKILL); + return; + } if (NULL != run_task) - { - GNUNET_SCHEDULER_cancel (run_task); - run_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(run_task); + run_task = NULL; + } } @@ -325,7 +323,7 @@ do_stop_task (void *cls) * Decide what the next task is (working or scanning) and schedule it. */ static void -schedule_next_task (void); +schedule_next_task(void); /** @@ -335,7 +333,7 @@ schedule_next_task (void); * @param cls the `struct WorkItem` we were working on */ static void -maint_child_death (void *cls) +maint_child_death(void *cls) { struct WorkItem *wi = cls; struct GNUNET_HashCode key; @@ -347,65 +345,65 @@ maint_child_death (void *cls) const struct GNUNET_SCHEDULER_TaskContext *tc; run_task = NULL; - pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ); - tc = GNUNET_SCHEDULER_get_task_context (); + pr = GNUNET_DISK_pipe_handle(sigpipe, GNUNET_DISK_PIPE_END_READ); + tc = GNUNET_SCHEDULER_get_task_context(); if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) - { - /* shutdown scheduled us, someone else will kill child, - we should just try again */ - run_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, - pr, - &maint_child_death, - wi); - return; - } + { + /* shutdown scheduled us, someone else will kill child, + we should just try again */ + run_task = GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL, + pr, + &maint_child_death, + wi); + return; + } /* consume the signal */ - GNUNET_break (0 < GNUNET_DISK_file_read (pr, &c, sizeof (c))); + GNUNET_break(0 < GNUNET_DISK_file_read(pr, &c, sizeof(c))); - ret = GNUNET_OS_process_status (publish_proc, &type, &code); - GNUNET_assert (GNUNET_SYSERR != ret); + ret = GNUNET_OS_process_status(publish_proc, &type, &code); + GNUNET_assert(GNUNET_SYSERR != ret); if (GNUNET_NO == ret) - { - /* process still running? Then where did the SIGCHLD come from? - Well, let's declare it spurious (kernel bug?) and keep rolling. - */ - GNUNET_break (0); - run_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, - pr, - &maint_child_death, - wi); - return; - } - GNUNET_assert (GNUNET_OK == ret); - - GNUNET_OS_process_destroy (publish_proc); + { + /* process still running? Then where did the SIGCHLD come from? + Well, let's declare it spurious (kernel bug?) and keep rolling. + */ + GNUNET_break(0); + run_task = GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL, + pr, + &maint_child_death, + wi); + return; + } + GNUNET_assert(GNUNET_OK == ret); + + GNUNET_OS_process_destroy(publish_proc); publish_proc = NULL; if (GNUNET_YES == do_shutdown) - { - GNUNET_free (wi->filename); - GNUNET_free (wi); - return; - } + { + GNUNET_free(wi->filename); + GNUNET_free(wi); + return; + } if ((GNUNET_OS_PROCESS_EXITED == type) && (0 == code)) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Publication of `%s' done\n"), - wi->filename); - GNUNET_CRYPTO_hash (wi->filename, strlen (wi->filename), &key); - GNUNET_break (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put ( - work_finished, - &key, - wi, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Publication of `%s' done\n"), + wi->filename); + GNUNET_CRYPTO_hash(wi->filename, strlen(wi->filename), &key); + GNUNET_break(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put( + work_finished, + &key, + wi, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + } else - { - GNUNET_CONTAINER_DLL_insert_tail (work_head, work_tail, wi); - } - save_state (); - schedule_next_task (); + { + GNUNET_CONTAINER_DLL_insert_tail(work_head, work_tail, wi); + } + save_state(); + schedule_next_task(); } @@ -414,17 +412,17 @@ maint_child_death (void *cls) * respective handler by writing to the trigger pipe. */ static void -sighandler_child_death () +sighandler_child_death() { static char c; int old_errno = errno; /* back-up errno */ - GNUNET_break ( + GNUNET_break( 1 == - GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle (sigpipe, - GNUNET_DISK_PIPE_END_WRITE), - &c, - sizeof (c))); + GNUNET_DISK_file_write(GNUNET_DISK_pipe_handle(sigpipe, + GNUNET_DISK_PIPE_END_WRITE), + &c, + sizeof(c))); errno = old_errno; /* restore errno */ } @@ -435,7 +433,7 @@ sighandler_child_death () * @param cls closure, NULL */ static void -work (void *cls) +work(void *cls) { static char *argv[14]; static char anon_level[20]; @@ -447,7 +445,7 @@ work (void *cls) run_task = NULL; wi = work_head; - GNUNET_CONTAINER_DLL_remove (work_head, work_tail, wi); + GNUNET_CONTAINER_DLL_remove(work_head, work_tail, wi); argc = 0; argv[argc++] = "gnunet-publish"; if (verbose) @@ -458,41 +456,41 @@ work (void *cls) argv[argc++] = "-d"; argv[argc++] = "-c"; argv[argc++] = cfg_filename; - GNUNET_snprintf (anon_level, sizeof (anon_level), "%u", anonymity_level); + GNUNET_snprintf(anon_level, sizeof(anon_level), "%u", anonymity_level); argv[argc++] = "-a"; argv[argc++] = anon_level; - GNUNET_snprintf (content_prio, sizeof (content_prio), "%u", content_priority); + GNUNET_snprintf(content_prio, sizeof(content_prio), "%u", content_priority); argv[argc++] = "-p"; argv[argc++] = content_prio; - GNUNET_snprintf (repl_level, sizeof (repl_level), "%u", replication_level); + GNUNET_snprintf(repl_level, sizeof(repl_level), "%u", replication_level); argv[argc++] = "-r"; argv[argc++] = repl_level; argv[argc++] = wi->filename; argv[argc] = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Publishing `%s'\n"), wi->filename); - GNUNET_assert (NULL == publish_proc); - publish_proc = GNUNET_OS_start_process_vap (GNUNET_YES, - 0, - NULL, - NULL, - NULL, - "gnunet-publish", - argv); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Publishing `%s'\n"), wi->filename); + GNUNET_assert(NULL == publish_proc); + publish_proc = GNUNET_OS_start_process_vap(GNUNET_YES, + 0, + NULL, + NULL, + NULL, + "gnunet-publish", + argv); if (NULL == publish_proc) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to run `%s'\n"), - "gnunet-publish"); - GNUNET_CONTAINER_DLL_insert (work_head, work_tail, wi); - run_task = - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &work, NULL); - return; - } - pr = GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ); - run_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, - pr, - &maint_child_death, - wi); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to run `%s'\n"), + "gnunet-publish"); + GNUNET_CONTAINER_DLL_insert(work_head, work_tail, wi); + run_task = + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES, &work, NULL); + return; + } + pr = GNUNET_DISK_pipe_handle(sigpipe, GNUNET_DISK_PIPE_END_READ); + run_task = GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL, + pr, + &maint_child_death, + wi); } @@ -505,39 +503,39 @@ work (void *cls) * @return #GNUNET_OK (always) */ static int -determine_id (void *cls, const char *filename) +determine_id(void *cls, const char *filename) { struct GNUNET_HashCode *id = cls; struct stat sbuf; struct GNUNET_HashCode fx[2]; struct GNUNET_HashCode ft; - if (0 != stat (filename, &sbuf)) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "stat", filename); - return GNUNET_OK; - } - GNUNET_CRYPTO_hash (filename, strlen (filename), &fx[0]); - if (! S_ISDIR (sbuf.st_mode)) - { - uint64_t fattr[2]; - - fattr[0] = GNUNET_htonll (sbuf.st_size); - fattr[0] = GNUNET_htonll (sbuf.st_mtime); - - GNUNET_CRYPTO_hash (fattr, sizeof (fattr), &fx[1]); - } + if (0 != stat(filename, &sbuf)) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "stat", filename); + return GNUNET_OK; + } + GNUNET_CRYPTO_hash(filename, strlen(filename), &fx[0]); + if (!S_ISDIR(sbuf.st_mode)) + { + uint64_t fattr[2]; + + fattr[0] = GNUNET_htonll(sbuf.st_size); + fattr[0] = GNUNET_htonll(sbuf.st_mtime); + + GNUNET_CRYPTO_hash(fattr, sizeof(fattr), &fx[1]); + } else - { - memset (&fx[1], 1, sizeof (struct GNUNET_HashCode)); - GNUNET_DISK_directory_scan (filename, &determine_id, &fx[1]); - } + { + memset(&fx[1], 1, sizeof(struct GNUNET_HashCode)); + GNUNET_DISK_directory_scan(filename, &determine_id, &fx[1]); + } /* use hash here to make hierarchical structure distinct from all files on the same level */ - GNUNET_CRYPTO_hash (fx, sizeof (fx), &ft); + GNUNET_CRYPTO_hash(fx, sizeof(fx), &ft); /* use XOR here so that order of the files in the directory does not matter! */ - GNUNET_CRYPTO_hash_xor (&ft, id, id); + GNUNET_CRYPTO_hash_xor(&ft, id, id); return GNUNET_OK; } @@ -552,7 +550,7 @@ determine_id (void *cls, const char *filename) * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR during shutdown */ static int -add_file (void *cls, const char *filename) +add_file(void *cls, const char *filename) { struct WorkItem *wi; struct GNUNET_HashCode key; @@ -560,29 +558,29 @@ add_file (void *cls, const char *filename) if (GNUNET_YES == do_shutdown) return GNUNET_SYSERR; - if ((NULL != strstr (filename, "/.auto-share")) || - (NULL != strstr (filename, "\\.auto-share"))) + if ((NULL != strstr(filename, "/.auto-share")) || + (NULL != strstr(filename, "\\.auto-share"))) return GNUNET_OK; /* skip internal file */ - GNUNET_CRYPTO_hash (filename, strlen (filename), &key); - wi = GNUNET_CONTAINER_multihashmap_get (work_finished, &key); - memset (&id, 0, sizeof (struct GNUNET_HashCode)); - determine_id (&id, filename); + GNUNET_CRYPTO_hash(filename, strlen(filename), &key); + wi = GNUNET_CONTAINER_multihashmap_get(work_finished, &key); + memset(&id, 0, sizeof(struct GNUNET_HashCode)); + determine_id(&id, filename); if (NULL != wi) - { - if (0 == memcmp (&id, &wi->id, sizeof (struct GNUNET_HashCode))) - return GNUNET_OK; /* skip: we did this one already */ - /* contents changed, need to re-do the directory... */ - GNUNET_assert ( - GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (work_finished, &key, wi)); - } + { + if (0 == memcmp(&id, &wi->id, sizeof(struct GNUNET_HashCode))) + return GNUNET_OK; /* skip: we did this one already */ + /* contents changed, need to re-do the directory... */ + GNUNET_assert( + GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(work_finished, &key, wi)); + } else - { - wi = GNUNET_new (struct WorkItem); - wi->filename = GNUNET_strdup (filename); - } + { + wi = GNUNET_new(struct WorkItem); + wi->filename = GNUNET_strdup(filename); + } wi->id = id; - GNUNET_CONTAINER_DLL_insert (work_head, work_tail, wi); + GNUNET_CONTAINER_DLL_insert(work_head, work_tail, wi); if (GNUNET_YES == do_shutdown) return GNUNET_SYSERR; return GNUNET_OK; @@ -595,12 +593,12 @@ add_file (void *cls, const char *filename) * @param cls NULL */ static void -scan (void *cls) +scan(void *cls) { run_task = NULL; - start_time = GNUNET_TIME_absolute_get (); - (void) GNUNET_DISK_directory_scan (dir_name, &add_file, NULL); - schedule_next_task (); + start_time = GNUNET_TIME_absolute_get(); + (void)GNUNET_DISK_directory_scan(dir_name, &add_file, NULL); + schedule_next_task(); } @@ -608,27 +606,27 @@ scan (void *cls) * Decide what the next task is (working or scanning) and schedule it. */ static void -schedule_next_task () +schedule_next_task() { struct GNUNET_TIME_Relative delay; if (GNUNET_YES == do_shutdown) return; - GNUNET_assert (NULL == run_task); + GNUNET_assert(NULL == run_task); if (NULL == work_head) - { - /* delay by at most 4h, at least 1s, and otherwise in between depending - on how long it took to scan */ - delay = GNUNET_TIME_absolute_get_duration (start_time); - delay = GNUNET_TIME_relative_saturating_multiply (delay, 100); - delay = GNUNET_TIME_relative_min (delay, MAX_DELAY); - delay = GNUNET_TIME_relative_max (delay, MIN_DELAY); - run_task = GNUNET_SCHEDULER_add_delayed (delay, &scan, NULL); - } + { + /* delay by at most 4h, at least 1s, and otherwise in between depending + on how long it took to scan */ + delay = GNUNET_TIME_absolute_get_duration(start_time); + delay = GNUNET_TIME_relative_saturating_multiply(delay, 100); + delay = GNUNET_TIME_relative_min(delay, MAX_DELAY); + delay = GNUNET_TIME_relative_max(delay, MIN_DELAY); + run_task = GNUNET_SCHEDULER_add_delayed(delay, &scan, NULL); + } else - { - run_task = GNUNET_SCHEDULER_add_now (&work, NULL); - } + { + run_task = GNUNET_SCHEDULER_add_now(&work, NULL); + } } @@ -641,29 +639,29 @@ schedule_next_task () * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { /* check arguments */ if ((NULL == args[0]) || (NULL != args[1]) || - (GNUNET_YES != GNUNET_DISK_directory_test (args[0], GNUNET_YES))) - { - printf (_ ( - "You must specify one and only one directory name for automatic publication.\n")); - ret = -1; - return; - } - cfg_filename = GNUNET_strdup (cfgfile); + (GNUNET_YES != GNUNET_DISK_directory_test(args[0], GNUNET_YES))) + { + printf(_( + "You must specify one and only one directory name for automatic publication.\n")); + ret = -1; + return; + } + cfg_filename = GNUNET_strdup(cfgfile); cfg = c; dir_name = args[0]; - work_finished = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_NO); - load_state (); - run_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE, - &scan, - NULL); - GNUNET_SCHEDULER_add_shutdown (&do_stop_task, NULL); + work_finished = GNUNET_CONTAINER_multihashmap_create(1024, GNUNET_NO); + load_state(); + run_task = GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_IDLE, + &scan, + NULL); + GNUNET_SCHEDULER_add_shutdown(&do_stop_task, NULL); } @@ -676,12 +674,12 @@ run (void *cls, * @return #GNUNET_OK to continue to iterate */ static int -free_item (void *cls, const struct GNUNET_HashCode *key, void *value) +free_item(void *cls, const struct GNUNET_HashCode *key, void *value) { struct WorkItem *wi = value; - GNUNET_free (wi->filename); - GNUNET_free (wi); + GNUNET_free(wi->filename); + GNUNET_free(wi); return GNUNET_OK; } @@ -694,89 +692,89 @@ free_item (void *cls, const struct GNUNET_HashCode *key, void *value) * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { - - GNUNET_GETOPT_option_uint ('a', - "anonymity", - "LEVEL", - gettext_noop ( - "set the desired LEVEL of sender-anonymity"), - &anonymity_level), - - GNUNET_GETOPT_option_flag ( + GNUNET_GETOPT_option_uint('a', + "anonymity", + "LEVEL", + gettext_noop( + "set the desired LEVEL of sender-anonymity"), + &anonymity_level), + + GNUNET_GETOPT_option_flag( 'd', "disable-creation-time", - gettext_noop ( + gettext_noop( "disable adding the creation time to the metadata of the uploaded file"), &do_disable_creation_time), - GNUNET_GETOPT_option_flag ( + GNUNET_GETOPT_option_flag( 'D', "disable-extractor", - gettext_noop ("do not use libextractor to add keywords or metadata"), + gettext_noop("do not use libextractor to add keywords or metadata"), &disable_extractor), - GNUNET_GETOPT_option_uint ('p', - "priority", - "PRIORITY", - gettext_noop ( - "specify the priority of the content"), - &content_priority), + GNUNET_GETOPT_option_uint('p', + "priority", + "PRIORITY", + gettext_noop( + "specify the priority of the content"), + &content_priority), - GNUNET_GETOPT_option_uint ('r', - "replication", - "LEVEL", - gettext_noop ( - "set the desired replication LEVEL"), - &replication_level), + GNUNET_GETOPT_option_uint('r', + "replication", + "LEVEL", + gettext_noop( + "set the desired replication LEVEL"), + &replication_level), - GNUNET_GETOPT_option_verbose (&verbose), + GNUNET_GETOPT_option_verbose(&verbose), - GNUNET_GETOPT_OPTION_END}; + GNUNET_GETOPT_OPTION_END + }; struct WorkItem *wi; int ok; struct GNUNET_SIGNAL_Context *shc_chld; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; - sigpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO); - GNUNET_assert (NULL != sigpipe); + sigpipe = GNUNET_DISK_pipe(GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO); + GNUNET_assert(NULL != sigpipe); shc_chld = - GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death); + GNUNET_SIGNAL_handler_install(GNUNET_SIGCHLD, &sighandler_child_death); ok = (GNUNET_OK == - GNUNET_PROGRAM_run ( + GNUNET_PROGRAM_run( argc, argv, "gnunet-auto-share [OPTIONS] FILENAME", - gettext_noop ("Automatically publish files from a directory on GNUnet"), + gettext_noop("Automatically publish files from a directory on GNUnet"), options, &run, NULL)) - ? ret - : 1; + ? ret + : 1; if (NULL != work_finished) - { - (void) GNUNET_CONTAINER_multihashmap_iterate (work_finished, + { + (void)GNUNET_CONTAINER_multihashmap_iterate(work_finished, &free_item, NULL); - GNUNET_CONTAINER_multihashmap_destroy (work_finished); - } + GNUNET_CONTAINER_multihashmap_destroy(work_finished); + } while (NULL != (wi = work_head)) - { - GNUNET_CONTAINER_DLL_remove (work_head, work_tail, wi); - GNUNET_free (wi->filename); - GNUNET_free (wi); - } - GNUNET_SIGNAL_handler_uninstall (shc_chld); + { + GNUNET_CONTAINER_DLL_remove(work_head, work_tail, wi); + GNUNET_free(wi->filename); + GNUNET_free(wi); + } + GNUNET_SIGNAL_handler_uninstall(shc_chld); shc_chld = NULL; - GNUNET_DISK_pipe_close (sigpipe); + GNUNET_DISK_pipe_close(sigpipe); sigpipe = NULL; - GNUNET_free_non_null (cfg_filename); + GNUNET_free_non_null(cfg_filename); cfg_filename = NULL; - GNUNET_free ((void *) argv); + GNUNET_free((void *)argv); return ok; } diff --git a/src/fs/gnunet-daemon-fsprofiler.c b/src/fs/gnunet-daemon-fsprofiler.c index 0202dde9c..524475c40 100644 --- a/src/fs/gnunet-daemon-fsprofiler.c +++ b/src/fs/gnunet-daemon-fsprofiler.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-daemon-fsprofiler.c @@ -34,8 +34,7 @@ * We use 'patterns' of the form (x,y,t) to specify desired download/publish * activities of a peer. They are stored in a DLL. */ -struct Pattern -{ +struct Pattern { /** * Kept in a DLL. */ @@ -173,29 +172,29 @@ static struct Pattern *download_tail; * @return GNUNET_OK on success */ static int -parse_pattern (struct Pattern **head, - struct Pattern **tail, - const char *pattern) +parse_pattern(struct Pattern **head, + struct Pattern **tail, + const char *pattern) { struct Pattern *p; unsigned long long x; unsigned long long y; unsigned long long t; - while (3 == sscanf (pattern, - "(%llu,%llu,%llu)", - &x, &y, &t)) - { - p = GNUNET_new (struct Pattern); - p->x = x; - p->y = y; - p->delay.rel_value_us = (uint64_t) t; - GNUNET_CONTAINER_DLL_insert (*head, *tail, p); - pattern = strstr (pattern, ")"); - GNUNET_assert (NULL != pattern); - pattern++; - } - return (0 == strlen (pattern)) ? GNUNET_OK : GNUNET_SYSERR; + while (3 == sscanf(pattern, + "(%llu,%llu,%llu)", + &x, &y, &t)) + { + p = GNUNET_new(struct Pattern); + p->x = x; + p->y = y; + p->delay.rel_value_us = (uint64_t)t; + GNUNET_CONTAINER_DLL_insert(*head, *tail, p); + pattern = strstr(pattern, ")"); + GNUNET_assert(NULL != pattern); + pattern++; + } + return (0 == strlen(pattern)) ? GNUNET_OK : GNUNET_SYSERR; } @@ -206,13 +205,13 @@ parse_pattern (struct Pattern **head, * @return corresponding KSK URI */ static struct GNUNET_FS_Uri * -make_keywords (uint64_t kval) +make_keywords(uint64_t kval) { char kw[128]; - GNUNET_snprintf (kw, sizeof (kw), - "%llu", (unsigned long long) kval); - return GNUNET_FS_uri_ksk_create (kw, NULL); + GNUNET_snprintf(kw, sizeof(kw), + "%llu", (unsigned long long)kval); + return GNUNET_FS_uri_ksk_create(kw, NULL); } @@ -226,9 +225,9 @@ make_keywords (uint64_t kval) * @return file information handle for the file */ static struct GNUNET_FS_FileInformation * -make_file (uint64_t length, - uint64_t kval, - void *ctx) +make_file(uint64_t length, + uint64_t kval, + void *ctx) { struct GNUNET_FS_FileInformation *fi; struct GNUNET_FS_BlockOptions bo; @@ -238,27 +237,27 @@ make_file (uint64_t length, uint64_t xor; data = NULL; /* to make compilers happy */ - if ( (0 != length) && - (NULL == (data = GNUNET_malloc_large ((size_t) length))) ) - return NULL; + if ((0 != length) && + (NULL == (data = GNUNET_malloc_large((size_t)length)))) + return NULL; /* initialize data with 'unique' data only depending on 'kval' and 'size', making sure that blocks do not repeat */ - for (i=0;itask) - GNUNET_SCHEDULER_cancel (p->task); - if (NULL != p->ctx) - GNUNET_FS_publish_stop (p->ctx); - GNUNET_CONTAINER_DLL_remove (publish_head, publish_tail, p); - GNUNET_free (p); - } + { + if (NULL != p->task) + GNUNET_SCHEDULER_cancel(p->task); + if (NULL != p->ctx) + GNUNET_FS_publish_stop(p->ctx); + GNUNET_CONTAINER_DLL_remove(publish_head, publish_tail, p); + GNUNET_free(p); + } while (NULL != (p = download_head)) - { - if (NULL != p->task) - GNUNET_SCHEDULER_cancel (p->task); - if (NULL != p->stask) - GNUNET_SCHEDULER_cancel (p->stask); - if (NULL != p->ctx) - GNUNET_FS_download_stop (p->ctx, GNUNET_YES); - if (NULL != p->sctx) - GNUNET_FS_search_stop (p->sctx); - GNUNET_CONTAINER_DLL_remove (download_head, download_tail, p); - GNUNET_free (p); - } + { + if (NULL != p->task) + GNUNET_SCHEDULER_cancel(p->task); + if (NULL != p->stask) + GNUNET_SCHEDULER_cancel(p->stask); + if (NULL != p->ctx) + GNUNET_FS_download_stop(p->ctx, GNUNET_YES); + if (NULL != p->sctx) + GNUNET_FS_search_stop(p->sctx); + GNUNET_CONTAINER_DLL_remove(download_head, download_tail, p); + GNUNET_free(p); + } if (NULL != fs_handle) - { - GNUNET_FS_stop (fs_handle); - fs_handle = NULL; - } + { + GNUNET_FS_stop(fs_handle); + fs_handle = NULL; + } if (NULL != stats_handle) - { - GNUNET_STATISTICS_destroy (stats_handle, GNUNET_YES); - stats_handle = NULL; - } + { + GNUNET_STATISTICS_destroy(stats_handle, GNUNET_YES); + stats_handle = NULL; + } } @@ -314,12 +313,12 @@ shutdown_task (void *cls) * @param cls the 'struct Pattern' of the publish operation to stop */ static void -publish_stop_task (void *cls) +publish_stop_task(void *cls) { struct Pattern *p = cls; p->task = NULL; - GNUNET_FS_publish_stop (p->ctx); + GNUNET_FS_publish_stop(p->ctx); } @@ -329,12 +328,12 @@ publish_stop_task (void *cls) * @param cls the 'struct Pattern' of the download operation to stop */ static void -download_stop_task (void *cls) +download_stop_task(void *cls) { struct Pattern *p = cls; p->task = NULL; - GNUNET_FS_download_stop (p->ctx, GNUNET_YES); + GNUNET_FS_download_stop(p->ctx, GNUNET_YES); } @@ -344,12 +343,12 @@ download_stop_task (void *cls) * @param cls the 'struct Pattern' of the download operation to stop */ static void -search_stop_task (void *cls) +search_stop_task(void *cls) { struct Pattern *p = cls; p->stask = NULL; - GNUNET_FS_search_stop (p->sctx); + GNUNET_FS_search_stop(p->sctx); } @@ -369,124 +368,138 @@ search_stop_task (void *cls) * field in the GNUNET_FS_ProgressInfo struct. */ static void * -progress_cb (void *cls, - const struct GNUNET_FS_ProgressInfo *info) +progress_cb(void *cls, + const struct GNUNET_FS_ProgressInfo *info) { struct Pattern *p; const struct GNUNET_FS_Uri *uri; switch (info->status) - { - case GNUNET_FS_STATUS_PUBLISH_START: - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - p = info->value.publish.cctx; - return p; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - p = info->value.publish.cctx; - return p; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Publishing failed\n"); - GNUNET_STATISTICS_update (stats_handle, - "# failed publish operations", 1, GNUNET_NO); - p = info->value.publish.cctx; - p->task = GNUNET_SCHEDULER_add_now (&publish_stop_task, p); - return p; - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - p = info->value.publish.cctx; - GNUNET_STATISTICS_update (stats_handle, - "# publishing time (ms)", - (long long) GNUNET_TIME_absolute_get_duration (p->start_time).rel_value_us / 1000LL, - GNUNET_NO); - p->task = GNUNET_SCHEDULER_add_now (&publish_stop_task, p); - return p; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - p = info->value.publish.cctx; - p->ctx = NULL; - GNUNET_CONTAINER_DLL_remove (publish_head, publish_tail, p); - GNUNET_free (p); - return NULL; - case GNUNET_FS_STATUS_DOWNLOAD_START: - case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: - case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE: - case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE: - p = info->value.download.cctx; - return p; - case GNUNET_FS_STATUS_DOWNLOAD_ERROR: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Download failed\n"); - GNUNET_STATISTICS_update (stats_handle, - "# failed downloads", 1, GNUNET_NO); - p = info->value.download.cctx; - p->task = GNUNET_SCHEDULER_add_now (&download_stop_task, p); - return p; - case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED: - p = info->value.download.cctx; - GNUNET_STATISTICS_update (stats_handle, - "# download time (ms)", - (long long) GNUNET_TIME_absolute_get_duration (p->start_time).rel_value_us / 1000LL, - GNUNET_NO); - p->task = GNUNET_SCHEDULER_add_now (&download_stop_task, p); - return p; - case GNUNET_FS_STATUS_DOWNLOAD_STOPPED: - p = info->value.download.cctx; - p->ctx = NULL; - if (NULL == p->sctx) - { - GNUNET_CONTAINER_DLL_remove (download_head, download_tail, p); - GNUNET_free (p); - } - return NULL; - case GNUNET_FS_STATUS_SEARCH_START: - case GNUNET_FS_STATUS_SEARCH_RESULT_NAMESPACE: - p = info->value.search.cctx; - return p; - case GNUNET_FS_STATUS_SEARCH_RESULT: - p = info->value.search.cctx; - uri = info->value.search.specifics.result.uri; - if (GNUNET_YES != GNUNET_FS_uri_test_chk (uri)) - return NULL; /* not what we want */ - if (p->y != GNUNET_FS_uri_chk_get_file_size (uri)) - return NULL; /* not what we want */ - GNUNET_STATISTICS_update (stats_handle, - "# search time (ms)", - (long long) GNUNET_TIME_absolute_get_duration (p->start_time).rel_value_us / 1000LL, - GNUNET_NO); - p->start_time = GNUNET_TIME_absolute_get (); - p->ctx = GNUNET_FS_download_start (fs_handle, uri, - NULL, NULL, NULL, - 0, GNUNET_FS_uri_chk_get_file_size (uri), - anonymity_level, - GNUNET_FS_DOWNLOAD_NO_TEMPORARIES, - p, - NULL); - p->stask = GNUNET_SCHEDULER_add_now (&search_stop_task, p); - return NULL; - case GNUNET_FS_STATUS_SEARCH_UPDATE: - case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: - return NULL; /* don't care */ - case GNUNET_FS_STATUS_SEARCH_ERROR: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Search failed\n"); - GNUNET_STATISTICS_update (stats_handle, - "# failed searches", 1, GNUNET_NO); - p = info->value.search.cctx; - p->stask = GNUNET_SCHEDULER_add_now (&search_stop_task, p); - return p; - case GNUNET_FS_STATUS_SEARCH_STOPPED: - p = info->value.search.cctx; - p->sctx = NULL; - if (NULL == p->ctx) { - GNUNET_CONTAINER_DLL_remove (download_head, download_tail, p); - GNUNET_free (p); + case GNUNET_FS_STATUS_PUBLISH_START: + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + p = info->value.publish.cctx; + return p; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + p = info->value.publish.cctx; + return p; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Publishing failed\n"); + GNUNET_STATISTICS_update(stats_handle, + "# failed publish operations", 1, GNUNET_NO); + p = info->value.publish.cctx; + p->task = GNUNET_SCHEDULER_add_now(&publish_stop_task, p); + return p; + + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + p = info->value.publish.cctx; + GNUNET_STATISTICS_update(stats_handle, + "# publishing time (ms)", + (long long)GNUNET_TIME_absolute_get_duration(p->start_time).rel_value_us / 1000LL, + GNUNET_NO); + p->task = GNUNET_SCHEDULER_add_now(&publish_stop_task, p); + return p; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + p = info->value.publish.cctx; + p->ctx = NULL; + GNUNET_CONTAINER_DLL_remove(publish_head, publish_tail, p); + GNUNET_free(p); + return NULL; + + case GNUNET_FS_STATUS_DOWNLOAD_START: + case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: + case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE: + case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE: + p = info->value.download.cctx; + return p; + + case GNUNET_FS_STATUS_DOWNLOAD_ERROR: + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Download failed\n"); + GNUNET_STATISTICS_update(stats_handle, + "# failed downloads", 1, GNUNET_NO); + p = info->value.download.cctx; + p->task = GNUNET_SCHEDULER_add_now(&download_stop_task, p); + return p; + + case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED: + p = info->value.download.cctx; + GNUNET_STATISTICS_update(stats_handle, + "# download time (ms)", + (long long)GNUNET_TIME_absolute_get_duration(p->start_time).rel_value_us / 1000LL, + GNUNET_NO); + p->task = GNUNET_SCHEDULER_add_now(&download_stop_task, p); + return p; + + case GNUNET_FS_STATUS_DOWNLOAD_STOPPED: + p = info->value.download.cctx; + p->ctx = NULL; + if (NULL == p->sctx) + { + GNUNET_CONTAINER_DLL_remove(download_head, download_tail, p); + GNUNET_free(p); + } + return NULL; + + case GNUNET_FS_STATUS_SEARCH_START: + case GNUNET_FS_STATUS_SEARCH_RESULT_NAMESPACE: + p = info->value.search.cctx; + return p; + + case GNUNET_FS_STATUS_SEARCH_RESULT: + p = info->value.search.cctx; + uri = info->value.search.specifics.result.uri; + if (GNUNET_YES != GNUNET_FS_uri_test_chk(uri)) + return NULL; /* not what we want */ + if (p->y != GNUNET_FS_uri_chk_get_file_size(uri)) + return NULL; /* not what we want */ + GNUNET_STATISTICS_update(stats_handle, + "# search time (ms)", + (long long)GNUNET_TIME_absolute_get_duration(p->start_time).rel_value_us / 1000LL, + GNUNET_NO); + p->start_time = GNUNET_TIME_absolute_get(); + p->ctx = GNUNET_FS_download_start(fs_handle, uri, + NULL, NULL, NULL, + 0, GNUNET_FS_uri_chk_get_file_size(uri), + anonymity_level, + GNUNET_FS_DOWNLOAD_NO_TEMPORARIES, + p, + NULL); + p->stask = GNUNET_SCHEDULER_add_now(&search_stop_task, p); + return NULL; + + case GNUNET_FS_STATUS_SEARCH_UPDATE: + case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: + return NULL; /* don't care */ + + case GNUNET_FS_STATUS_SEARCH_ERROR: + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Search failed\n"); + GNUNET_STATISTICS_update(stats_handle, + "# failed searches", 1, GNUNET_NO); + p = info->value.search.cctx; + p->stask = GNUNET_SCHEDULER_add_now(&search_stop_task, p); + return p; + + case GNUNET_FS_STATUS_SEARCH_STOPPED: + p = info->value.search.cctx; + p->sctx = NULL; + if (NULL == p->ctx) + { + GNUNET_CONTAINER_DLL_remove(download_head, download_tail, p); + GNUNET_free(p); + } + return NULL; + + default: + /* unexpected event during profiling */ + GNUNET_break(0); + return NULL; } - return NULL; - default: - /* unexpected event during profiling */ - GNUNET_break (0); - return NULL; - } } @@ -496,18 +509,18 @@ progress_cb (void *cls, * @param cls the 'struct Pattern' specifying the operation to perform */ static void -start_publish (void *cls) +start_publish(void *cls) { struct Pattern *p = cls; struct GNUNET_FS_FileInformation *fi; p->task = NULL; - fi = make_file (p->x, p->y, p); - p->start_time = GNUNET_TIME_absolute_get (); - p->ctx = GNUNET_FS_publish_start (fs_handle, - fi, - NULL, NULL, NULL, - GNUNET_FS_PUBLISH_OPTION_NONE); + fi = make_file(p->x, p->y, p); + p->start_time = GNUNET_TIME_absolute_get(); + p->ctx = GNUNET_FS_publish_start(fs_handle, + fi, + NULL, NULL, NULL, + GNUNET_FS_PUBLISH_OPTION_NONE); } @@ -517,18 +530,18 @@ start_publish (void *cls) * @param cls the 'struct Pattern' specifying the operation to perform */ static void -start_download (void *cls) +start_download(void *cls) { struct Pattern *p = cls; struct GNUNET_FS_Uri *keywords; p->task = NULL; - keywords = make_keywords (p->x); - p->start_time = GNUNET_TIME_absolute_get (); - p->sctx = GNUNET_FS_search_start (fs_handle, keywords, - anonymity_level, - GNUNET_FS_SEARCH_OPTION_NONE, - p); + keywords = make_keywords(p->x); + p->start_time = GNUNET_TIME_absolute_get(); + p->sctx = GNUNET_FS_search_start(fs_handle, keywords, + anonymity_level, + GNUNET_FS_SEARCH_OPTION_NONE, + p); } @@ -541,88 +554,88 @@ start_download (void *cls) * @param cfg_ configuration */ static void -run (void *cls, char *const *args GNUNET_UNUSED, - const char *cfgfile GNUNET_UNUSED, - const struct GNUNET_CONFIGURATION_Handle *cfg_) +run(void *cls, char *const *args GNUNET_UNUSED, + const char *cfgfile GNUNET_UNUSED, + const struct GNUNET_CONFIGURATION_Handle *cfg_) { char myoptname[128]; struct Pattern *p; cfg = cfg_; /* Scheduled the task to clean up when shutdown is called */ - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (cfg, - "TESTBED", "PEERID", - &my_peerid)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "TESTBED", "PEERID"); - global_ret = GNUNET_SYSERR; - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_CONFIGURATION_get_value_number(cfg, + "TESTBED", "PEERID", + &my_peerid)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "TESTBED", "PEERID"); + global_ret = GNUNET_SYSERR; + GNUNET_SCHEDULER_shutdown(); + return; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (cfg, - "FSPROFILER", "ANONYMITY_LEVEL", - &anonymity_level)) + GNUNET_CONFIGURATION_get_value_number(cfg, + "FSPROFILER", "ANONYMITY_LEVEL", + &anonymity_level)) anonymity_level = 1; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (cfg, - "FSPROFILER", "REPLICATION_LEVEL", - &replication_level)) + GNUNET_CONFIGURATION_get_value_number(cfg, + "FSPROFILER", "REPLICATION_LEVEL", + &replication_level)) replication_level = 1; - GNUNET_snprintf (myoptname, sizeof (myoptname), - "DOWNLOAD-PATTERN-%u", my_peerid); + GNUNET_snprintf(myoptname, sizeof(myoptname), + "DOWNLOAD-PATTERN-%u", my_peerid); if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "FSPROFILER", myoptname, - &download_pattern)) - download_pattern = GNUNET_strdup (""); - GNUNET_snprintf (myoptname, sizeof (myoptname), - "PUBLISH-PATTERN-%u", my_peerid); + GNUNET_CONFIGURATION_get_value_string(cfg, + "FSPROFILER", myoptname, + &download_pattern)) + download_pattern = GNUNET_strdup(""); + GNUNET_snprintf(myoptname, sizeof(myoptname), + "PUBLISH-PATTERN-%u", my_peerid); if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "FSPROFILER", myoptname, - &publish_pattern)) - publish_pattern = GNUNET_strdup (""); - if ( (GNUNET_OK != - parse_pattern (&download_head, - &download_tail, - download_pattern)) || - (GNUNET_OK != - parse_pattern (&publish_head, - &publish_tail, - publish_pattern)) ) - { - GNUNET_SCHEDULER_shutdown (); - return; - } - - stats_handle = GNUNET_STATISTICS_create ("fsprofiler", cfg); + GNUNET_CONFIGURATION_get_value_string(cfg, + "FSPROFILER", myoptname, + &publish_pattern)) + publish_pattern = GNUNET_strdup(""); + if ((GNUNET_OK != + parse_pattern(&download_head, + &download_tail, + download_pattern)) || + (GNUNET_OK != + parse_pattern(&publish_head, + &publish_tail, + publish_pattern))) + { + GNUNET_SCHEDULER_shutdown(); + return; + } + + stats_handle = GNUNET_STATISTICS_create("fsprofiler", cfg); fs_handle = - GNUNET_FS_start (cfg, - "fsprofiler", - &progress_cb, NULL, - GNUNET_FS_FLAGS_NONE, - GNUNET_FS_OPTIONS_DOWNLOAD_PARALLELISM, 1, - GNUNET_FS_OPTIONS_REQUEST_PARALLELISM, 1, - GNUNET_FS_OPTIONS_END); + GNUNET_FS_start(cfg, + "fsprofiler", + &progress_cb, NULL, + GNUNET_FS_FLAGS_NONE, + GNUNET_FS_OPTIONS_DOWNLOAD_PARALLELISM, 1, + GNUNET_FS_OPTIONS_REQUEST_PARALLELISM, 1, + GNUNET_FS_OPTIONS_END); if (NULL == fs_handle) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not acquire FS handle. Exiting.\n"); - global_ret = GNUNET_SYSERR; - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not acquire FS handle. Exiting.\n"); + global_ret = GNUNET_SYSERR; + GNUNET_SCHEDULER_shutdown(); + return; + } for (p = publish_head; NULL != p; p = p->next) - p->task = GNUNET_SCHEDULER_add_delayed (p->delay, - &start_publish, p); + p->task = GNUNET_SCHEDULER_add_delayed(p->delay, + &start_publish, p); for (p = download_head; NULL != p; p = p->next) - p->task = GNUNET_SCHEDULER_add_delayed (p->delay, - &start_download, p); + p->task = GNUNET_SCHEDULER_add_delayed(p->delay, + &start_download, p); } @@ -634,19 +647,19 @@ run (void *cls, char *const *args GNUNET_UNUSED, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { static const struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; return (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, "gnunet-daemon-fsprofiler", - gettext_noop - ("Daemon to use file-sharing to measure its performance."), - options, &run, NULL)) ? global_ret : 1; + GNUNET_PROGRAM_run(argc, argv, "gnunet-daemon-fsprofiler", + gettext_noop + ("Daemon to use file-sharing to measure its performance."), + options, &run, NULL)) ? global_ret : 1; } /* end of gnunet-daemon-fsprofiler.c */ diff --git a/src/fs/gnunet-directory.c b/src/fs/gnunet-directory.c index 4cce69d72..f33db109f 100644 --- a/src/fs/gnunet-directory.c +++ b/src/fs/gnunet-directory.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-directory.c * @brief display content of GNUnet directories @@ -40,32 +40,32 @@ static int ret; * @return always 0 (to continue iterating) */ static int -item_printer (void *cls, - const char *plugin_name, - enum EXTRACTOR_MetaType type, - enum EXTRACTOR_MetaFormat format, - const char *data_mime_type, - const char *data, - size_t data_size) +item_printer(void *cls, + const char *plugin_name, + enum EXTRACTOR_MetaType type, + enum EXTRACTOR_MetaFormat format, + const char *data_mime_type, + const char *data, + size_t data_size) { if (type == EXTRACTOR_METATYPE_GNUNET_FULL_DATA) - { - printf (_ ("\t\n"), - (unsigned int) data_size); - return 0; - } + { + printf(_("\t\n"), + (unsigned int)data_size); + return 0; + } if ((format != EXTRACTOR_METAFORMAT_UTF8) && (format != EXTRACTOR_METAFORMAT_C_STRING)) return 0; if (type == EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME) return 0; #if HAVE_LIBEXTRACTOR - printf ("\t%20s: %s\n", - dgettext (LIBEXTRACTOR_GETTEXT_DOMAIN, - EXTRACTOR_metatype_to_string (type)), - data); + printf("\t%20s: %s\n", + dgettext(LIBEXTRACTOR_GETTEXT_DOMAIN, + EXTRACTOR_metatype_to_string(type)), + data); #else - printf ("\t%20d: %s\n", type, data); + printf("\t%20d: %s\n", type, data); #endif return 0; } @@ -87,34 +87,34 @@ item_printer (void *cls, * @param data data available for the file (length bytes) */ static void -print_entry (void *cls, - const char *filename, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *meta, - size_t length, - const void *data) +print_entry(void *cls, + const char *filename, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *meta, + size_t length, + const void *data) { char *string; char *name; - name = GNUNET_CONTAINER_meta_data_get_by_type ( + name = GNUNET_CONTAINER_meta_data_get_by_type( meta, EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME); if (uri == NULL) - { - printf (_ ("Directory `%s' meta data:\n"), name ? name : ""); - GNUNET_CONTAINER_meta_data_iterate (meta, &item_printer, NULL); - printf ("\n"); - printf (_ ("Directory `%s' contents:\n"), name ? name : ""); - GNUNET_free_non_null (name); - return; - } - string = GNUNET_FS_uri_to_string (uri); - printf ("%s (%s):\n", name ? name : "", string); - GNUNET_free (string); - GNUNET_CONTAINER_meta_data_iterate (meta, &item_printer, NULL); - printf ("\n"); - GNUNET_free_non_null (name); + { + printf(_("Directory `%s' meta data:\n"), name ? name : ""); + GNUNET_CONTAINER_meta_data_iterate(meta, &item_printer, NULL); + printf("\n"); + printf(_("Directory `%s' contents:\n"), name ? name : ""); + GNUNET_free_non_null(name); + return; + } + string = GNUNET_FS_uri_to_string(uri); + printf("%s (%s):\n", name ? name : "", string); + GNUNET_free(string); + GNUNET_CONTAINER_meta_data_iterate(meta, &item_printer, NULL); + printf("\n"); + GNUNET_free_non_null(name); } @@ -127,10 +127,10 @@ print_entry (void *cls, * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_DISK_MapHandle *map; struct GNUNET_DISK_FileHandle *h; @@ -141,37 +141,37 @@ run (void *cls, int i; if (NULL == args[0]) - { - fprintf (stderr, "%s", _ ("You must specify a filename to inspect.\n")); - ret = 1; - return; - } + { + fprintf(stderr, "%s", _("You must specify a filename to inspect.\n")); + ret = 1; + return; + } i = 0; while (NULL != (filename = args[i++])) - { - if ((GNUNET_OK != - GNUNET_DISK_file_size (filename, &size, GNUNET_YES, GNUNET_YES)) || - (NULL == (h = GNUNET_DISK_file_open (filename, - GNUNET_DISK_OPEN_READ, - GNUNET_DISK_PERM_NONE)))) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to read directory `%s'\n"), - filename); - ret = 1; - continue; + if ((GNUNET_OK != + GNUNET_DISK_file_size(filename, &size, GNUNET_YES, GNUNET_YES)) || + (NULL == (h = GNUNET_DISK_file_open(filename, + GNUNET_DISK_OPEN_READ, + GNUNET_DISK_PERM_NONE)))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to read directory `%s'\n"), + filename); + ret = 1; + continue; + } + len = (size_t)size; + data = GNUNET_DISK_file_map(h, &map, GNUNET_DISK_MAP_TYPE_READ, len); + GNUNET_assert(NULL != data); + if (GNUNET_OK != + GNUNET_FS_directory_list_contents(len, data, 0, &print_entry, NULL)) + fprintf(stdout, _("`%s' is not a GNUnet directory\n"), filename); + else + printf("\n"); + GNUNET_DISK_file_unmap(map); + GNUNET_DISK_file_close(h); } - len = (size_t) size; - data = GNUNET_DISK_file_map (h, &map, GNUNET_DISK_MAP_TYPE_READ, len); - GNUNET_assert (NULL != data); - if (GNUNET_OK != - GNUNET_FS_directory_list_contents (len, data, 0, &print_entry, NULL)) - fprintf (stdout, _ ("`%s' is not a GNUnet directory\n"), filename); - else - printf ("\n"); - GNUNET_DISK_file_unmap (map); - GNUNET_DISK_file_close (h); - } } /** @@ -182,26 +182,27 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { static struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_OPTION_END}; + GNUNET_GETOPT_OPTION_END + }; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-directory [OPTIONS] FILENAME", - gettext_noop ( - "Display contents of a GNUnet directory"), - options, - &run, - NULL)) - ? ret - : 1; - GNUNET_free ((void *) argv); + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-directory [OPTIONS] FILENAME", + gettext_noop( + "Display contents of a GNUnet directory"), + options, + &run, + NULL)) + ? ret + : 1; + GNUNET_free((void *)argv); return ret; } diff --git a/src/fs/gnunet-download.c b/src/fs/gnunet-download.c index 00e8336a2..eda6765ab 100644 --- a/src/fs/gnunet-download.c +++ b/src/fs/gnunet-download.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-download.c * @brief downloading for files on GNUnet @@ -54,21 +54,21 @@ static int local_only; static void -cleanup_task (void *cls) +cleanup_task(void *cls) { - GNUNET_FS_stop (ctx); + GNUNET_FS_stop(ctx); ctx = NULL; } static void -shutdown_task (void *cls) +shutdown_task(void *cls) { if (NULL != dc) - { - GNUNET_FS_download_stop (dc, delete_incomplete); - dc = NULL; - } + { + GNUNET_FS_download_stop(dc, delete_incomplete); + dc = NULL; + } } @@ -80,30 +80,30 @@ shutdown_task (void *cls) * @param w desired number of steps in the progress bar */ static void -display_bar (unsigned long long x, unsigned long long n, unsigned int w) +display_bar(unsigned long long x, unsigned long long n, unsigned int w) { char buf[w + 20]; unsigned int p; unsigned int endeq; float ratio_complete; -#if ! WINDOWS - if (0 == isatty (1)) +#if !WINDOWS + if (0 == isatty(1)) return; #else - if (FILE_TYPE_CHAR != GetFileType (GetStdHandle (STD_OUTPUT_HANDLE))) + if (FILE_TYPE_CHAR != GetFileType(GetStdHandle(STD_OUTPUT_HANDLE))) return; #endif - ratio_complete = x / (float) n; + ratio_complete = x / (float)n; endeq = ratio_complete * w; - GNUNET_snprintf (buf, sizeof (buf), "%3d%% [", (int) (ratio_complete * 100)); + GNUNET_snprintf(buf, sizeof(buf), "%3d%% [", (int)(ratio_complete * 100)); for (p = 0; p < endeq; p++) - strcat (buf, "="); + strcat(buf, "="); for (p = endeq; p < w; p++) - strcat (buf, " "); - strcat (buf, "]\r"); - printf ("%s", buf); - fflush (stdout); + strcat(buf, " "); + strcat(buf, "]\r"); + printf("%s", buf); + fflush(stdout); } @@ -121,100 +121,106 @@ display_bar (unsigned long long x, unsigned long long n, unsigned int w) * field in the `struct GNUNET_FS_ProgressInfo` */ static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *info) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *info) { char *s; const char *s2; char *t; switch (info->status) - { - case GNUNET_FS_STATUS_DOWNLOAD_START: - if (verbose > 1) - fprintf (stderr, - _ ("Starting download `%s'.\n"), - info->value.download.filename); - break; - case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: - if (verbose) { - s = GNUNET_strdup ( - GNUNET_STRINGS_relative_time_to_string (info->value.download.eta, - GNUNET_YES)); - if (info->value.download.specifics.progress.block_download_duration - .rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) - s2 = _ (""); + case GNUNET_FS_STATUS_DOWNLOAD_START: + if (verbose > 1) + fprintf(stderr, + _("Starting download `%s'.\n"), + info->value.download.filename); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: + if (verbose) + { + s = GNUNET_strdup( + GNUNET_STRINGS_relative_time_to_string(info->value.download.eta, + GNUNET_YES)); + if (info->value.download.specifics.progress.block_download_duration + .rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) + s2 = _(""); + else + s2 = GNUNET_STRINGS_relative_time_to_string(info->value.download + .specifics.progress + .block_download_duration, + GNUNET_YES); + t = GNUNET_STRINGS_byte_size_fancy( + info->value.download.completed * 1000LL / + (info->value.download.duration.rel_value_us + 1)); + fprintf( + stdout, + _( + "Downloading `%s' at %llu/%llu (%s remaining, %s/s). Block took %s to download\n"), + info->value.download.filename, + (unsigned long long)info->value.download.completed, + (unsigned long long)info->value.download.size, + s, + t, + s2); + GNUNET_free(s); + GNUNET_free(t); + } else - s2 = GNUNET_STRINGS_relative_time_to_string (info->value.download - .specifics.progress - .block_download_duration, - GNUNET_YES); - t = GNUNET_STRINGS_byte_size_fancy ( - info->value.download.completed * 1000LL / - (info->value.download.duration.rel_value_us + 1)); - fprintf ( - stdout, - _ ( - "Downloading `%s' at %llu/%llu (%s remaining, %s/s). Block took %s to download\n"), - info->value.download.filename, - (unsigned long long) info->value.download.completed, - (unsigned long long) info->value.download.size, - s, - t, - s2); - GNUNET_free (s); - GNUNET_free (t); - } - else - { - display_bar (info->value.download.completed, - info->value.download.size, - 60); - } - break; - case GNUNET_FS_STATUS_DOWNLOAD_ERROR: -#if ! WINDOWS - if (0 != isatty (1)) - fprintf (stdout, "\n"); + { + display_bar(info->value.download.completed, + info->value.download.size, + 60); + } + break; + + case GNUNET_FS_STATUS_DOWNLOAD_ERROR: +#if !WINDOWS + if (0 != isatty(1)) + fprintf(stdout, "\n"); #else - if (FILE_TYPE_CHAR == GetFileType (GetStdHandle (STD_OUTPUT_HANDLE))) - fprintf (stdout, "\n"); + if (FILE_TYPE_CHAR == GetFileType(GetStdHandle(STD_OUTPUT_HANDLE))) + fprintf(stdout, "\n"); #endif - fprintf (stderr, - _ ("Error downloading: %s.\n"), - info->value.download.specifics.error.message); - GNUNET_SCHEDULER_shutdown (); - break; - case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED: - s = GNUNET_STRINGS_byte_size_fancy ( - info->value.download.completed * 1000 / - (info->value.download.duration.rel_value_us + 1)); -#if ! WINDOWS - if (0 != isatty (1)) - fprintf (stdout, "\n"); + fprintf(stderr, + _("Error downloading: %s.\n"), + info->value.download.specifics.error.message); + GNUNET_SCHEDULER_shutdown(); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED: + s = GNUNET_STRINGS_byte_size_fancy( + info->value.download.completed * 1000 / + (info->value.download.duration.rel_value_us + 1)); +#if !WINDOWS + if (0 != isatty(1)) + fprintf(stdout, "\n"); #else - if (FILE_TYPE_CHAR == GetFileType (GetStdHandle (STD_OUTPUT_HANDLE))) - fprintf (stdout, "\n"); + if (FILE_TYPE_CHAR == GetFileType(GetStdHandle(STD_OUTPUT_HANDLE))) + fprintf(stdout, "\n"); #endif - fprintf (stdout, - _ ("Downloading `%s' done (%s/s).\n"), - info->value.download.filename, - s); - GNUNET_free (s); - if (info->value.download.dc == dc) - GNUNET_SCHEDULER_shutdown (); - break; - case GNUNET_FS_STATUS_DOWNLOAD_STOPPED: - if (info->value.download.dc == dc) - GNUNET_SCHEDULER_add_now (&cleanup_task, NULL); - break; - case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE: - case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE: - break; - default: - fprintf (stderr, _ ("Unexpected status: %d\n"), info->status); - break; - } + fprintf(stdout, + _("Downloading `%s' done (%s/s).\n"), + info->value.download.filename, + s); + GNUNET_free(s); + if (info->value.download.dc == dc) + GNUNET_SCHEDULER_shutdown(); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_STOPPED: + if (info->value.download.dc == dc) + GNUNET_SCHEDULER_add_now(&cleanup_task, NULL); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE: + case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE: + break; + + default: + fprintf(stderr, _("Unexpected status: %d\n"), info->status); + break; + } return NULL; } @@ -228,84 +234,84 @@ progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *info) * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { struct GNUNET_FS_Uri *uri; char *emsg; enum GNUNET_FS_DownloadOptions options; if (NULL == args[0]) - { - fprintf (stderr, "%s", _ ("You need to specify a URI argument.\n")); - return; - } - uri = GNUNET_FS_uri_parse (args[0], &emsg); + { + fprintf(stderr, "%s", _("You need to specify a URI argument.\n")); + return; + } + uri = GNUNET_FS_uri_parse(args[0], &emsg); if (NULL == uri) - { - fprintf (stderr, _ ("Failed to parse URI: %s\n"), emsg); - GNUNET_free (emsg); - ret = 1; - return; - } - if ((! GNUNET_FS_uri_test_chk (uri)) && (! GNUNET_FS_uri_test_loc (uri))) - { - fprintf (stderr, "%s", _ ("Only CHK or LOC URIs supported.\n")); - ret = 1; - GNUNET_FS_uri_destroy (uri); - return; - } + { + fprintf(stderr, _("Failed to parse URI: %s\n"), emsg); + GNUNET_free(emsg); + ret = 1; + return; + } + if ((!GNUNET_FS_uri_test_chk(uri)) && (!GNUNET_FS_uri_test_loc(uri))) + { + fprintf(stderr, "%s", _("Only CHK or LOC URIs supported.\n")); + ret = 1; + GNUNET_FS_uri_destroy(uri); + return; + } if (NULL == filename) - { - fprintf (stderr, "%s", _ ("Target filename must be specified.\n")); - ret = 1; - GNUNET_FS_uri_destroy (uri); - return; - } + { + fprintf(stderr, "%s", _("Target filename must be specified.\n")); + ret = 1; + GNUNET_FS_uri_destroy(uri); + return; + } cfg = c; - ctx = GNUNET_FS_start (cfg, - "gnunet-download", - &progress_cb, - NULL, - GNUNET_FS_FLAGS_NONE, - GNUNET_FS_OPTIONS_DOWNLOAD_PARALLELISM, - parallelism, - GNUNET_FS_OPTIONS_REQUEST_PARALLELISM, - request_parallelism, - GNUNET_FS_OPTIONS_END); + ctx = GNUNET_FS_start(cfg, + "gnunet-download", + &progress_cb, + NULL, + GNUNET_FS_FLAGS_NONE, + GNUNET_FS_OPTIONS_DOWNLOAD_PARALLELISM, + parallelism, + GNUNET_FS_OPTIONS_REQUEST_PARALLELISM, + request_parallelism, + GNUNET_FS_OPTIONS_END); if (NULL == ctx) - { - fprintf (stderr, _ ("Could not initialize `%s' subsystem.\n"), "FS"); - GNUNET_FS_uri_destroy (uri); - ret = 1; - return; - } + { + fprintf(stderr, _("Could not initialize `%s' subsystem.\n"), "FS"); + GNUNET_FS_uri_destroy(uri); + ret = 1; + return; + } options = GNUNET_FS_DOWNLOAD_OPTION_NONE; if (do_recursive) options |= GNUNET_FS_DOWNLOAD_OPTION_RECURSIVE; if (local_only) options |= GNUNET_FS_DOWNLOAD_OPTION_LOOPBACK_ONLY; - dc = GNUNET_FS_download_start (ctx, - uri, - NULL, - filename, - NULL, - 0, - GNUNET_FS_uri_chk_get_file_size (uri), - anonymity, - options, - NULL, - NULL); - GNUNET_FS_uri_destroy (uri); + dc = GNUNET_FS_download_start(ctx, + uri, + NULL, + filename, + NULL, + 0, + GNUNET_FS_uri_chk_get_file_size(uri), + anonymity, + options, + NULL, + NULL); + GNUNET_FS_uri_destroy(uri); if (dc == NULL) - { - GNUNET_FS_stop (ctx); - ctx = NULL; - return; - } - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + { + GNUNET_FS_stop(ctx); + ctx = NULL; + return; + } + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); } @@ -317,75 +323,75 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_uint ('a', - "anonymity", - "LEVEL", - gettext_noop ( - "set the desired LEVEL of receiver-anonymity"), - &anonymity), - - GNUNET_GETOPT_option_flag ( - 'D', - "delete-incomplete", - gettext_noop ("delete incomplete downloads (when aborted with CTRL-C)"), - &delete_incomplete), - - GNUNET_GETOPT_option_flag ( - 'n', - "no-network", - gettext_noop ("only search the local peer (no P2P network search)"), - &local_only), - GNUNET_GETOPT_option_string ('o', - "output", - "FILENAME", - gettext_noop ("write the file to FILENAME"), - &filename), - GNUNET_GETOPT_option_uint ( - 'p', - "parallelism", - "DOWNLOADS", - gettext_noop ( - "set the maximum number of parallel downloads that is allowed"), - ¶llelism), - GNUNET_GETOPT_option_uint ( - 'r', - "request-parallelism", - "REQUESTS", - gettext_noop ( - "set the maximum number of parallel requests for blocks that is allowed"), - &request_parallelism), - GNUNET_GETOPT_option_flag ('R', - "recursive", - gettext_noop ( - "download a GNUnet directory recursively"), - &do_recursive), - GNUNET_GETOPT_option_increment_uint ( - 'V', - "verbose", - gettext_noop ("be verbose (print progress information)"), - &verbose), - GNUNET_GETOPT_OPTION_END}; - - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + { GNUNET_GETOPT_option_uint('a', + "anonymity", + "LEVEL", + gettext_noop( + "set the desired LEVEL of receiver-anonymity"), + &anonymity), + + GNUNET_GETOPT_option_flag( + 'D', + "delete-incomplete", + gettext_noop("delete incomplete downloads (when aborted with CTRL-C)"), + &delete_incomplete), + + GNUNET_GETOPT_option_flag( + 'n', + "no-network", + gettext_noop("only search the local peer (no P2P network search)"), + &local_only), + GNUNET_GETOPT_option_string('o', + "output", + "FILENAME", + gettext_noop("write the file to FILENAME"), + &filename), + GNUNET_GETOPT_option_uint( + 'p', + "parallelism", + "DOWNLOADS", + gettext_noop( + "set the maximum number of parallel downloads that is allowed"), + ¶llelism), + GNUNET_GETOPT_option_uint( + 'r', + "request-parallelism", + "REQUESTS", + gettext_noop( + "set the maximum number of parallel requests for blocks that is allowed"), + &request_parallelism), + GNUNET_GETOPT_option_flag('R', + "recursive", + gettext_noop( + "download a GNUnet directory recursively"), + &do_recursive), + GNUNET_GETOPT_option_increment_uint( + 'V', + "verbose", + gettext_noop("be verbose (print progress information)"), + &verbose), + GNUNET_GETOPT_OPTION_END }; + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run ( + GNUNET_PROGRAM_run( argc, argv, "gnunet-download [OPTIONS] URI", - gettext_noop ( + gettext_noop( "Download files from GNUnet using a GNUnet CHK or LOC URI (gnunet://fs/chk/...)"), options, &run, NULL)) - ? ret - : 1; - GNUNET_free ((void *) argv); + ? ret + : 1; + GNUNET_free((void *)argv); return ret; } diff --git a/src/fs/gnunet-fs-profiler.c b/src/fs/gnunet-fs-profiler.c index 8a71c5a59..d47ca8b29 100644 --- a/src/fs/gnunet-fs-profiler.c +++ b/src/fs/gnunet-fs-profiler.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-fs-profiler.c @@ -62,15 +62,15 @@ static struct GNUNET_SCHEDULER_Task * terminate_taskid; * operation has executed successfully. */ static void -shutdown_task (void *cls, - struct GNUNET_TESTBED_Operation *op, - const char *emsg) +shutdown_task(void *cls, + struct GNUNET_TESTBED_Operation *op, + const char *emsg) { if (NULL != emsg) - fprintf (stderr, - "Error collecting statistics: %s\n", - emsg); - GNUNET_SCHEDULER_shutdown (); + fprintf(stderr, + "Error collecting statistics: %s\n", + emsg); + GNUNET_SCHEDULER_shutdown(); } @@ -87,19 +87,19 @@ shutdown_task (void *cls, * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration */ static int -process_stats (void *cls, - const struct GNUNET_TESTBED_Peer *peer, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +process_stats(void *cls, + const struct GNUNET_TESTBED_Peer *peer, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { - fprintf (stdout, - "%p-%s: %s = %llu\n", - peer, - subsystem, - name, - (unsigned long long) value); + fprintf(stdout, + "%p-%s: %s = %llu\n", + peer, + subsystem, + name, + (unsigned long long)value); return GNUNET_OK; } @@ -111,18 +111,18 @@ process_stats (void *cls, * @param cls NULL */ static void -terminate_task (void *cls) +terminate_task(void *cls) { if (NULL != terminate_taskid) - { - GNUNET_SCHEDULER_cancel (terminate_taskid); - terminate_taskid = NULL; - } - GNUNET_TESTBED_get_statistics (0, NULL, - NULL, NULL, - &process_stats, - &shutdown_task, - NULL); + { + GNUNET_SCHEDULER_cancel(terminate_taskid); + terminate_taskid = NULL; + } + GNUNET_TESTBED_get_statistics(0, NULL, + NULL, NULL, + &process_stats, + &shutdown_task, + NULL); } @@ -133,10 +133,10 @@ terminate_task (void *cls) * @param cls NULL */ static void -timeout_task (void *cls) +timeout_task(void *cls) { terminate_taskid = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -153,23 +153,23 @@ timeout_task (void *cls) * failed */ static void -test_master (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - unsigned int links_succeeded, - unsigned int links_failed) +test_master(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + unsigned int links_succeeded, + unsigned int links_failed) { // const struct GNUNET_CONFIGURATION_Handle *cfg = cls; // FIXME: enable clients to signal 'completion' before timeout; // in that case, run the 'terminate_task' "immediately" if (0 != timeout.rel_value_us) - terminate_taskid = GNUNET_SCHEDULER_add_delayed (timeout, - &timeout_task, - NULL); - GNUNET_SCHEDULER_add_shutdown (&terminate_task, - NULL); + terminate_taskid = GNUNET_SCHEDULER_add_delayed(timeout, + &timeout_task, + NULL); + GNUNET_SCHEDULER_add_shutdown(&terminate_task, + NULL); } @@ -182,14 +182,14 @@ test_master (void *cls, * @param cfg configuration */ static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - GNUNET_TESTBED_run (host_filename, - cfg, - num_peers, - 0, NULL, NULL, - &test_master, (void *) cfg); + GNUNET_TESTBED_run(host_filename, + cfg, + num_peers, + 0, NULL, NULL, + &test_master, (void *)cfg); } @@ -201,38 +201,38 @@ run (void *cls, char *const *args, const char *cfgfile, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { - - GNUNET_GETOPT_option_uint ('n', - "num-peers", - "COUNT", - gettext_noop ("run the experiment with COUNT peers"), - &num_peers), - - GNUNET_GETOPT_option_string ('H', - "hosts", - "HOSTFILE", - gettext_noop ("specifies name of a file with the HOSTS the testbed should use"), - &host_filename), - - GNUNET_GETOPT_option_relative_time ('t', - "timeout", - "DELAY", - gettext_noop ("automatically terminate experiment after DELAY"), - &timeout), + GNUNET_GETOPT_option_uint('n', + "num-peers", + "COUNT", + gettext_noop("run the experiment with COUNT peers"), + &num_peers), + + GNUNET_GETOPT_option_string('H', + "hosts", + "HOSTFILE", + gettext_noop("specifies name of a file with the HOSTS the testbed should use"), + &host_filename), + + GNUNET_GETOPT_option_relative_time('t', + "timeout", + "DELAY", + gettext_noop("automatically terminate experiment after DELAY"), + &timeout), GNUNET_GETOPT_OPTION_END }; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, "gnunet-fs-profiler", - gettext_noop ("run a testbed to measure file-sharing performance"), options, &run, - NULL)) ? ret : 1; - GNUNET_free ((void*) argv); + GNUNET_PROGRAM_run(argc, argv, "gnunet-fs-profiler", + gettext_noop("run a testbed to measure file-sharing performance"), options, &run, + NULL)) ? ret : 1; + GNUNET_free((void*)argv); return ret; } diff --git a/src/fs/gnunet-fs.c b/src/fs/gnunet-fs.c index ad2a8d6c5..3fa65d6cb 100644 --- a/src/fs/gnunet-fs.c +++ b/src/fs/gnunet-fs.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-fs.c * @brief special file-sharing functions @@ -55,20 +55,20 @@ static unsigned int verbose; * @return GNUNET_OK to continue iteration */ static int -print_indexed (void *cls, - const char *filename, - const struct GNUNET_HashCode *file_id) +print_indexed(void *cls, + const char *filename, + const struct GNUNET_HashCode *file_id) { if (NULL == filename) - { - GNUNET_FS_stop (fs); - fs = NULL; - return GNUNET_OK; - } + { + GNUNET_FS_stop(fs); + fs = NULL; + return GNUNET_OK; + } if (verbose) - fprintf (stdout, "%s: %s\n", GNUNET_h2s (file_id), filename); + fprintf(stdout, "%s: %s\n", GNUNET_h2s(file_id), filename); else - fprintf (stdout, "%s\n", filename); + fprintf(stdout, "%s\n", filename); return GNUNET_OK; } @@ -82,32 +82,32 @@ print_indexed (void *cls, * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { if (list_indexed_files) - { - fs = GNUNET_FS_start (cfg, - "gnunet-fs", - NULL, - NULL, - GNUNET_FS_FLAGS_NONE, - GNUNET_FS_OPTIONS_END); - if (NULL == fs) { - ret = 1; - return; + fs = GNUNET_FS_start(cfg, + "gnunet-fs", + NULL, + NULL, + GNUNET_FS_FLAGS_NONE, + GNUNET_FS_OPTIONS_END); + if (NULL == fs) + { + ret = 1; + return; + } + if (NULL == GNUNET_FS_get_indexed_files(fs, &print_indexed, NULL)) + { + ret = 2; + GNUNET_FS_stop(fs); + fs = NULL; + return; + } } - if (NULL == GNUNET_FS_get_indexed_files (fs, &print_indexed, NULL)) - { - ret = 2; - GNUNET_FS_stop (fs); - fs = NULL; - return; - } - } } /** @@ -118,32 +118,32 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { + GNUNET_GETOPT_option_flag('i', + "list-indexed", + gettext_noop( + "print a list of all indexed files"), + &list_indexed_files), - GNUNET_GETOPT_option_flag ('i', - "list-indexed", - gettext_noop ( - "print a list of all indexed files"), - &list_indexed_files), - - GNUNET_GETOPT_option_verbose (&verbose), - GNUNET_GETOPT_OPTION_END}; + GNUNET_GETOPT_option_verbose(&verbose), + GNUNET_GETOPT_OPTION_END + }; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-fs [OPTIONS]", - gettext_noop ("Special file-sharing operations"), - options, - &run, - NULL)) - ? ret - : 1; - GNUNET_free ((void *) argv); + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-fs [OPTIONS]", + gettext_noop("Special file-sharing operations"), + options, + &run, + NULL)) + ? ret + : 1; + GNUNET_free((void *)argv); return ret; } diff --git a/src/fs/gnunet-helper-fs-publish.c b/src/fs/gnunet-helper-fs-publish.c index dcb4b47cd..db74e65aa 100644 --- a/src/fs/gnunet-helper-fs-publish.c +++ b/src/fs/gnunet-helper-fs-publish.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/fs/gnunet-helper-fs-publish.c @@ -33,9 +33,7 @@ /** * A node of a directory tree. */ -struct ScanTreeNode -{ - +struct ScanTreeNode { /** * This is a doubly-linked list */ @@ -113,41 +111,41 @@ static int output_stream; * @return always 0 to continue extracting */ static int -add_to_md (void *cls, - const char *plugin_name, - enum EXTRACTOR_MetaType type, - enum EXTRACTOR_MetaFormat format, - const char *data_mime_type, - const char *data, - size_t data_len) +add_to_md(void *cls, + const char *plugin_name, + enum EXTRACTOR_MetaType type, + enum EXTRACTOR_MetaFormat format, + const char *data_mime_type, + const char *data, + size_t data_len) { struct GNUNET_CONTAINER_MetaData *md = cls; if (((EXTRACTOR_METAFORMAT_UTF8 == format) || (EXTRACTOR_METAFORMAT_C_STRING == format)) && ('\0' != data[data_len - 1])) - { - char zdata[data_len + 1]; - GNUNET_memcpy (zdata, data, data_len); - zdata[data_len] = '\0'; - (void) GNUNET_CONTAINER_meta_data_insert (md, + { + char zdata[data_len + 1]; + GNUNET_memcpy(zdata, data, data_len); + zdata[data_len] = '\0'; + (void)GNUNET_CONTAINER_meta_data_insert(md, plugin_name, type, format, data_mime_type, zdata, data_len + 1); - } + } else - { - (void) GNUNET_CONTAINER_meta_data_insert (md, + { + (void)GNUNET_CONTAINER_meta_data_insert(md, plugin_name, type, format, data_mime_type, data, data_len); - } + } return 0; } #endif @@ -159,18 +157,18 @@ add_to_md (void *cls, * @param tree tree to free */ static void -free_tree (struct ScanTreeNode *tree) +free_tree(struct ScanTreeNode *tree) { struct ScanTreeNode *pos; while (NULL != (pos = tree->children_head)) - free_tree (pos); + free_tree(pos); if (NULL != tree->parent) - GNUNET_CONTAINER_DLL_remove (tree->parent->children_head, - tree->parent->children_tail, - tree); - GNUNET_free (tree->filename); - GNUNET_free (tree); + GNUNET_CONTAINER_DLL_remove(tree->parent->children_head, + tree->parent->children_tail, + tree); + GNUNET_free(tree->filename); + GNUNET_free(tree); } @@ -182,7 +180,7 @@ free_tree (struct ScanTreeNode *tree) * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -write_all (const void *buf, size_t size) +write_all(const void *buf, size_t size) { const char *cbuf = buf; size_t total; @@ -190,15 +188,16 @@ write_all (const void *buf, size_t size) total = 0; do - { - wr = write (output_stream, &cbuf[total], size - total); - if (wr > 0) - total += wr; - } while ((wr > 0) && (total < size)); + { + wr = write(output_stream, &cbuf[total], size - total); + if (wr > 0) + total += wr; + } + while ((wr > 0) && (total < size)); if (wr <= 0) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Failed to write to stdout: %s\n", - strerror (errno)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Failed to write to stdout: %s\n", + strerror(errno)); return (total == size) ? GNUNET_OK : GNUNET_SYSERR; } @@ -212,20 +211,20 @@ write_all (const void *buf, size_t size) * @return #GNUNET_SYSERR to stop scanning (the pipe was broken somehow) */ static int -write_message (uint16_t message_type, const char *data, size_t data_length) +write_message(uint16_t message_type, const char *data, size_t data_length) { struct GNUNET_MessageHeader hdr; #if 0 - fprintf (stderr, - "Helper sends %u-byte message of type %u\n", - (unsigned int) (sizeof (struct GNUNET_MessageHeader) + data_length), - (unsigned int) message_type); + fprintf(stderr, + "Helper sends %u-byte message of type %u\n", + (unsigned int)(sizeof(struct GNUNET_MessageHeader) + data_length), + (unsigned int)message_type); #endif - hdr.type = htons (message_type); - hdr.size = htons (sizeof (struct GNUNET_MessageHeader) + data_length); - if ((GNUNET_OK != write_all (&hdr, sizeof (hdr))) || - (GNUNET_OK != write_all (data, data_length))) + hdr.type = htons(message_type); + hdr.size = htons(sizeof(struct GNUNET_MessageHeader) + data_length); + if ((GNUNET_OK != write_all(&hdr, sizeof(hdr))) || + (GNUNET_OK != write_all(data, data_length))) return GNUNET_SYSERR; return GNUNET_OK; } @@ -242,14 +241,13 @@ write_message (uint16_t message_type, const char *data, size_t data_length) * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -preprocess_file (const char *filename, struct ScanTreeNode **dst); +preprocess_file(const char *filename, struct ScanTreeNode **dst); /** * Closure for the 'scan_callback' */ -struct RecursionContext -{ +struct RecursionContext { /** * Parent to add the files to. */ @@ -272,22 +270,22 @@ struct RecursionContext * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -scan_callback (void *cls, const char *filename) +scan_callback(void *cls, const char *filename) { struct RecursionContext *rc = cls; struct ScanTreeNode *chld; - if (GNUNET_OK != preprocess_file (filename, &chld)) - { - rc->stop = GNUNET_YES; - return GNUNET_SYSERR; - } + if (GNUNET_OK != preprocess_file(filename, &chld)) + { + rc->stop = GNUNET_YES; + return GNUNET_SYSERR; + } if (NULL == chld) return GNUNET_OK; chld->parent = rc->parent; - GNUNET_CONTAINER_DLL_insert (rc->parent->children_head, - rc->parent->children_tail, - chld); + GNUNET_CONTAINER_DLL_insert(rc->parent->children_head, + rc->parent->children_tail, + chld); return GNUNET_OK; } @@ -303,60 +301,60 @@ scan_callback (void *cls, const char *filename) * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -preprocess_file (const char *filename, struct ScanTreeNode **dst) +preprocess_file(const char *filename, struct ScanTreeNode **dst) { struct ScanTreeNode *item; struct stat sbuf; uint64_t fsize = 0; - if ((0 != stat (filename, &sbuf)) || - ((! S_ISDIR (sbuf.st_mode)) && + if ((0 != stat(filename, &sbuf)) || + ((!S_ISDIR(sbuf.st_mode)) && (GNUNET_OK != - GNUNET_DISK_file_size (filename, &fsize, GNUNET_NO, GNUNET_YES)))) - { - /* If the file doesn't exist (or is not stat-able for any other reason) - skip it (but report it), but do continue. */ - if (GNUNET_OK != - write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_SKIP_FILE, - filename, - strlen (filename) + 1)) - return GNUNET_SYSERR; - /* recoverable error, store 'NULL' in *dst */ - *dst = NULL; - return GNUNET_OK; - } + GNUNET_DISK_file_size(filename, &fsize, GNUNET_NO, GNUNET_YES)))) + { + /* If the file doesn't exist (or is not stat-able for any other reason) + skip it (but report it), but do continue. */ + if (GNUNET_OK != + write_message(GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_SKIP_FILE, + filename, + strlen(filename) + 1)) + return GNUNET_SYSERR; + /* recoverable error, store 'NULL' in *dst */ + *dst = NULL; + return GNUNET_OK; + } /* Report the progress */ if ( GNUNET_OK != - write_message (S_ISDIR (sbuf.st_mode) - ? GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_DIRECTORY - : GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_FILE, - filename, - strlen (filename) + 1)) + write_message(S_ISDIR(sbuf.st_mode) + ? GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_DIRECTORY + : GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_FILE, + filename, + strlen(filename) + 1)) return GNUNET_SYSERR; - item = GNUNET_new (struct ScanTreeNode); - item->filename = GNUNET_strdup (filename); - item->is_directory = (S_ISDIR (sbuf.st_mode)) ? GNUNET_YES : GNUNET_NO; + item = GNUNET_new(struct ScanTreeNode); + item->filename = GNUNET_strdup(filename); + item->is_directory = (S_ISDIR(sbuf.st_mode)) ? GNUNET_YES : GNUNET_NO; item->file_size = fsize; if (GNUNET_YES == item->is_directory) - { - struct RecursionContext rc; - - rc.parent = item; - rc.stop = GNUNET_NO; - GNUNET_DISK_directory_scan (filename, &scan_callback, &rc); - if ( - (GNUNET_YES == rc.stop) || - (GNUNET_OK != - write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_DIRECTORY, - "..", - 3))) { - free_tree (item); - return GNUNET_SYSERR; + struct RecursionContext rc; + + rc.parent = item; + rc.stop = GNUNET_NO; + GNUNET_DISK_directory_scan(filename, &scan_callback, &rc); + if ( + (GNUNET_YES == rc.stop) || + (GNUNET_OK != + write_message(GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_PROGRESS_DIRECTORY, + "..", + 3))) + { + free_tree(item); + return GNUNET_SYSERR; + } } - } *dst = item; return GNUNET_OK; } @@ -369,67 +367,67 @@ preprocess_file (const char *filename, struct ScanTreeNode **dst) * @return #GNUNET_OK on success, #GNUNET_SYSERR on fatal errors */ static int -extract_files (struct ScanTreeNode *item) +extract_files(struct ScanTreeNode *item) { struct GNUNET_CONTAINER_MetaData *meta; ssize_t size; size_t slen; if (GNUNET_YES == item->is_directory) - { - /* for directories, we simply only descent, no extraction, no - progress reporting */ - struct ScanTreeNode *pos; - - for (pos = item->children_head; NULL != pos; pos = pos->next) - if (GNUNET_OK != extract_files (pos)) - return GNUNET_SYSERR; - return GNUNET_OK; - } + { + /* for directories, we simply only descent, no extraction, no + progress reporting */ + struct ScanTreeNode *pos; + + for (pos = item->children_head; NULL != pos; pos = pos->next) + if (GNUNET_OK != extract_files(pos)) + return GNUNET_SYSERR; + return GNUNET_OK; + } /* this is the expensive operation, *afterwards* we'll check for aborts */ - meta = GNUNET_CONTAINER_meta_data_create (); + meta = GNUNET_CONTAINER_meta_data_create(); #if HAVE_LIBEXTRACTOR - EXTRACTOR_extract (plugins, item->filename, NULL, 0, &add_to_md, meta); + EXTRACTOR_extract(plugins, item->filename, NULL, 0, &add_to_md, meta); #endif - slen = strlen (item->filename) + 1; - size = GNUNET_CONTAINER_meta_data_get_serialized_size (meta); + slen = strlen(item->filename) + 1; + size = GNUNET_CONTAINER_meta_data_get_serialized_size(meta); if (-1 == size) - { - /* no meta data */ - GNUNET_CONTAINER_meta_data_destroy (meta); - if (GNUNET_OK != - write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_META_DATA, - item->filename, - slen)) - return GNUNET_SYSERR; - return GNUNET_OK; - } - else if (size > (UINT16_MAX - sizeof (struct GNUNET_MessageHeader) - slen)) - { - /* We can't transfer more than 64k bytes in one message. */ - size = UINT16_MAX - sizeof (struct GNUNET_MessageHeader) - slen; - } + { + /* no meta data */ + GNUNET_CONTAINER_meta_data_destroy(meta); + if (GNUNET_OK != + write_message(GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_META_DATA, + item->filename, + slen)) + return GNUNET_SYSERR; + return GNUNET_OK; + } + else if (size > (UINT16_MAX - sizeof(struct GNUNET_MessageHeader) - slen)) + { + /* We can't transfer more than 64k bytes in one message. */ + size = UINT16_MAX - sizeof(struct GNUNET_MessageHeader) - slen; + } { char buf[size + slen]; char *dst = &buf[slen]; - GNUNET_memcpy (buf, item->filename, slen); - size = GNUNET_CONTAINER_meta_data_serialize ( + GNUNET_memcpy(buf, item->filename, slen); + size = GNUNET_CONTAINER_meta_data_serialize( meta, &dst, size, GNUNET_CONTAINER_META_DATA_SERIALIZE_PART); if (size < 0) - { - GNUNET_break (0); - size = 0; - } - GNUNET_CONTAINER_meta_data_destroy (meta); + { + GNUNET_break(0); + size = 0; + } + GNUNET_CONTAINER_meta_data_destroy(meta); if (GNUNET_OK != - write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_META_DATA, - buf, - slen + size)) + write_message(GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_META_DATA, + buf, + slen + size)) return GNUNET_SYSERR; } return GNUNET_OK; @@ -441,23 +439,23 @@ extract_files (struct ScanTreeNode *item) * Install a signal handler to ignore SIGPIPE. */ static void -ignore_sigpipe () +ignore_sigpipe() { struct sigaction oldsig; struct sigaction sig; - memset (&sig, 0, sizeof (struct sigaction)); + memset(&sig, 0, sizeof(struct sigaction)); sig.sa_handler = SIG_IGN; - sigemptyset (&sig.sa_mask); + sigemptyset(&sig.sa_mask); #ifdef SA_INTERRUPT sig.sa_flags = SA_INTERRUPT; /* SunOS */ #else sig.sa_flags = SA_RESTART; #endif - if (0 != sigaction (SIGPIPE, &sig, &oldsig)) - fprintf (stderr, - "Failed to install SIGPIPE handler: %s\n", - strerror (errno)); + if (0 != sigaction(SIGPIPE, &sig, &oldsig)) + fprintf(stderr, + "Failed to install SIGPIPE handler: %s\n", + strerror(errno)); } @@ -468,17 +466,17 @@ ignore_sigpipe () * @param flags flags to use (O_RDONLY or O_WRONLY) */ static void -make_dev_zero (int fd, int flags) +make_dev_zero(int fd, int flags) { int z; - GNUNET_assert (0 == close (fd)); - z = open ("/dev/null", flags); - GNUNET_assert (-1 != z); + GNUNET_assert(0 == close(fd)); + z = open("/dev/null", flags); + GNUNET_assert(-1 != z); if (z == fd) return; - GNUNET_break (fd == dup2 (z, fd)); - GNUNET_assert (0 == close (z)); + GNUNET_break(fd == dup2(z, fd)); + GNUNET_assert(0 == close(z)); } #endif @@ -495,7 +493,7 @@ make_dev_zero (int fd, int flags) * @return 0 on success */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { const char *filename_expanded; const char *ex; @@ -505,98 +503,98 @@ main (int argc, char *const *argv) /* We're using stdout to communicate binary data back to the parent; use * binary mode. */ - _setmode (1, _O_BINARY); + _setmode(1, _O_BINARY); /* Get utf-8-encoded arguments */ - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 5; output_stream = 1; /* stdout */ #else - ignore_sigpipe (); + ignore_sigpipe(); /* move stdout to some other FD for IPC, bind stdout/stderr to /dev/null */ - output_stream = dup (1); - make_dev_zero (1, O_WRONLY); - make_dev_zero (2, O_WRONLY); + output_stream = dup(1); + make_dev_zero(1, O_WRONLY); + make_dev_zero(2, O_WRONLY); #endif /* parse command line */ if ((3 != argc) && (2 != argc)) - { - fprintf (stderr, - "%s", - "gnunet-helper-fs-publish needs exactly one or two arguments\n"); + { + fprintf(stderr, + "%s", + "gnunet-helper-fs-publish needs exactly one or two arguments\n"); #if WINDOWS - GNUNET_free ((void *) argv); + GNUNET_free((void *)argv); #endif - return 1; - } + return 1; + } filename_expanded = argv[1]; ex = argv[2]; - if ((NULL == ex) || (0 != strcmp (ex, "-"))) - { + if ((NULL == ex) || (0 != strcmp(ex, "-"))) + { #if HAVE_LIBEXTRACTOR - plugins = EXTRACTOR_plugin_add_defaults (EXTRACTOR_OPTION_DEFAULT_POLICY); - if (NULL != ex) - plugins = EXTRACTOR_plugin_add_config (plugins, - ex, - EXTRACTOR_OPTION_DEFAULT_POLICY); + plugins = EXTRACTOR_plugin_add_defaults(EXTRACTOR_OPTION_DEFAULT_POLICY); + if (NULL != ex) + plugins = EXTRACTOR_plugin_add_config(plugins, + ex, + EXTRACTOR_OPTION_DEFAULT_POLICY); #endif - } + } /* scan tree to find out how much work there is to be done */ - if (GNUNET_OK != preprocess_file (filename_expanded, &root)) - { - (void) write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR, NULL, 0); + if (GNUNET_OK != preprocess_file(filename_expanded, &root)) + { + (void)write_message(GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR, NULL, 0); #if HAVE_LIBEXTRACTOR - EXTRACTOR_plugin_remove_all (plugins); + EXTRACTOR_plugin_remove_all(plugins); #endif #if WINDOWS - GNUNET_free ((void *) argv); + GNUNET_free((void *)argv); #endif - return 2; - } + return 2; + } /* signal that we're done counting files, so that a percentage of progress can now be calculated */ if (GNUNET_OK != - write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_COUNTING_DONE, - NULL, - 0)) - { + write_message(GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_COUNTING_DONE, + NULL, + 0)) + { #if HAVE_LIBEXTRACTOR - EXTRACTOR_plugin_remove_all (plugins); + EXTRACTOR_plugin_remove_all(plugins); #endif #if WINDOWS - GNUNET_free ((void *) argv); + GNUNET_free((void *)argv); #endif - return 3; - } + return 3; + } if (NULL != root) - { - if (GNUNET_OK != extract_files (root)) { - (void) write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR, - NULL, - 0); - free_tree (root); + if (GNUNET_OK != extract_files(root)) + { + (void)write_message(GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_ERROR, + NULL, + 0); + free_tree(root); #if HAVE_LIBEXTRACTOR - EXTRACTOR_plugin_remove_all (plugins); + EXTRACTOR_plugin_remove_all(plugins); #endif #if WINDOWS - GNUNET_free ((void *) argv); + GNUNET_free((void *)argv); #endif - return 4; + return 4; + } + free_tree(root); } - free_tree (root); - } /* enable "clean" shutdown by telling parent that we are done */ - (void) write_message (GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_FINISHED, - NULL, - 0); + (void)write_message(GNUNET_MESSAGE_TYPE_FS_PUBLISH_HELPER_FINISHED, + NULL, + 0); #if HAVE_LIBEXTRACTOR - EXTRACTOR_plugin_remove_all (plugins); + EXTRACTOR_plugin_remove_all(plugins); #endif #if WINDOWS - GNUNET_free ((void *) argv); + GNUNET_free((void *)argv); #endif return 0; } diff --git a/src/fs/gnunet-publish.c b/src/fs/gnunet-publish.c index 84cbf0aac..24baa4d38 100644 --- a/src/fs/gnunet-publish.c +++ b/src/fs/gnunet-publish.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-publish.c * @brief publishing files on GNUnet @@ -67,7 +67,7 @@ static struct GNUNET_FS_Uri *topKeywords; /** * Options we set for published blocks. */ -static struct GNUNET_FS_BlockOptions bo = {{0LL}, 1, 365, 1}; +static struct GNUNET_FS_BlockOptions bo = { { 0LL }, 1, 365, 1 }; /** * Value of URI provided on command-line (when not publishing @@ -148,41 +148,41 @@ static struct GNUNET_IDENTITY_Handle *identity; * @param cls NULL */ static void -do_stop_task (void *cls) +do_stop_task(void *cls) { struct GNUNET_FS_PublishContext *p; if (NULL != ds) - { - GNUNET_FS_directory_scan_abort (ds); - ds = NULL; - } + { + GNUNET_FS_directory_scan_abort(ds); + ds = NULL; + } if (NULL != identity) - { - GNUNET_IDENTITY_disconnect (identity); - identity = NULL; - } + { + GNUNET_IDENTITY_disconnect(identity); + identity = NULL; + } if (NULL != pc) - { - p = pc; - pc = NULL; - GNUNET_FS_publish_stop (p); - } + { + p = pc; + pc = NULL; + GNUNET_FS_publish_stop(p); + } if (NULL != ctx) - { - GNUNET_FS_stop (ctx); - ctx = NULL; - } + { + GNUNET_FS_stop(ctx); + ctx = NULL; + } if (NULL != meta) - { - GNUNET_CONTAINER_meta_data_destroy (meta); - meta = NULL; - } + { + GNUNET_CONTAINER_meta_data_destroy(meta); + meta = NULL; + } if (NULL != uri) - { - GNUNET_FS_uri_destroy (uri); - uri = NULL; - } + { + GNUNET_FS_uri_destroy(uri); + uri = NULL; + } } @@ -200,94 +200,105 @@ do_stop_task (void *cls) * field in the GNUNET_FS_ProgressInfo struct. */ static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *info) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *info) { const char *s; char *suri; switch (info->status) - { - case GNUNET_FS_STATUS_PUBLISH_START: - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - if (verbose) { - s = GNUNET_STRINGS_relative_time_to_string (info->value.publish.eta, - GNUNET_YES); - fprintf (stdout, - _ ("Publishing `%s' at %llu/%llu (%s remaining)\n"), - info->value.publish.filename, - (unsigned long long) info->value.publish.completed, - (unsigned long long) info->value.publish.size, - s); - } - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - if (verbose) - { - s = GNUNET_STRINGS_relative_time_to_string (info->value.publish.specifics - .progress_directory.eta, - GNUNET_YES); - fprintf (stdout, - _ ("Publishing `%s' at %llu/%llu (%s remaining)\n"), - info->value.publish.filename, - (unsigned long long) - info->value.publish.specifics.progress_directory.completed, - (unsigned long long) - info->value.publish.specifics.progress_directory.total, - s); - } - break; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - fprintf (stderr, - _ ("Error publishing: %s.\n"), - info->value.publish.specifics.error.message); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - break; - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - fprintf (stdout, - _ ("Publishing `%s' done.\n"), - info->value.publish.filename); - suri = - GNUNET_FS_uri_to_string (info->value.publish.specifics.completed.chk_uri); - fprintf (stdout, _ ("URI is `%s'.\n"), suri); - GNUNET_free (suri); - if (NULL != info->value.publish.specifics.completed.sks_uri) - { - suri = GNUNET_FS_uri_to_string ( - info->value.publish.specifics.completed.sks_uri); - fprintf (stdout, _ ("Namespace URI is `%s'.\n"), suri); - GNUNET_free (suri); - } - if (NULL == info->value.publish.pctx) - { - ret = 0; - GNUNET_SCHEDULER_shutdown (); + case GNUNET_FS_STATUS_PUBLISH_START: + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + if (verbose) + { + s = GNUNET_STRINGS_relative_time_to_string(info->value.publish.eta, + GNUNET_YES); + fprintf(stdout, + _("Publishing `%s' at %llu/%llu (%s remaining)\n"), + info->value.publish.filename, + (unsigned long long)info->value.publish.completed, + (unsigned long long)info->value.publish.size, + s); + } + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + if (verbose) + { + s = GNUNET_STRINGS_relative_time_to_string(info->value.publish.specifics + .progress_directory.eta, + GNUNET_YES); + fprintf(stdout, + _("Publishing `%s' at %llu/%llu (%s remaining)\n"), + info->value.publish.filename, + (unsigned long long) + info->value.publish.specifics.progress_directory.completed, + (unsigned long long) + info->value.publish.specifics.progress_directory.total, + s); + } + break; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + fprintf(stderr, + _("Error publishing: %s.\n"), + info->value.publish.specifics.error.message); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + break; + + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + fprintf(stdout, + _("Publishing `%s' done.\n"), + info->value.publish.filename); + suri = + GNUNET_FS_uri_to_string(info->value.publish.specifics.completed.chk_uri); + fprintf(stdout, _("URI is `%s'.\n"), suri); + GNUNET_free(suri); + if (NULL != info->value.publish.specifics.completed.sks_uri) + { + suri = GNUNET_FS_uri_to_string( + info->value.publish.specifics.completed.sks_uri); + fprintf(stdout, _("Namespace URI is `%s'.\n"), suri); + GNUNET_free(suri); + } + if (NULL == info->value.publish.pctx) + { + ret = 0; + GNUNET_SCHEDULER_shutdown(); + } + break; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + GNUNET_break(NULL == pc); + return NULL; + + case GNUNET_FS_STATUS_UNINDEX_START: + fprintf(stderr, "%s", _("Starting cleanup after abort\n")); + return NULL; + + case GNUNET_FS_STATUS_UNINDEX_PROGRESS: + return NULL; + + case GNUNET_FS_STATUS_UNINDEX_COMPLETED: + fprintf(stderr, "%s", _("Cleanup after abort completed.\n")); + GNUNET_FS_unindex_stop(info->value.unindex.uc); + return NULL; + + case GNUNET_FS_STATUS_UNINDEX_ERROR: + fprintf(stderr, "%s", _("Cleanup after abort failed.\n")); + GNUNET_FS_unindex_stop(info->value.unindex.uc); + return NULL; + + case GNUNET_FS_STATUS_UNINDEX_STOPPED: + return NULL; + + default: + fprintf(stderr, _("Unexpected status: %d\n"), info->status); + return NULL; } - break; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - GNUNET_break (NULL == pc); - return NULL; - case GNUNET_FS_STATUS_UNINDEX_START: - fprintf (stderr, "%s", _ ("Starting cleanup after abort\n")); - return NULL; - case GNUNET_FS_STATUS_UNINDEX_PROGRESS: - return NULL; - case GNUNET_FS_STATUS_UNINDEX_COMPLETED: - fprintf (stderr, "%s", _ ("Cleanup after abort completed.\n")); - GNUNET_FS_unindex_stop (info->value.unindex.uc); - return NULL; - case GNUNET_FS_STATUS_UNINDEX_ERROR: - fprintf (stderr, "%s", _ ("Cleanup after abort failed.\n")); - GNUNET_FS_unindex_stop (info->value.unindex.uc); - return NULL; - case GNUNET_FS_STATUS_UNINDEX_STOPPED: - return NULL; - default: - fprintf (stderr, _ ("Unexpected status: %d\n"), info->status); - return NULL; - } return ""; /* non-null */ } @@ -306,13 +317,13 @@ progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *info) * @return always 0 */ static int -meta_printer (void *cls, - const char *plugin_name, - enum EXTRACTOR_MetaType type, - enum EXTRACTOR_MetaFormat format, - const char *data_mime_type, - const char *data, - size_t data_size) +meta_printer(void *cls, + const char *plugin_name, + enum EXTRACTOR_MetaType type, + enum EXTRACTOR_MetaFormat format, + const char *data_mime_type, + const char *data, + size_t data_size) { if ((EXTRACTOR_METAFORMAT_UTF8 != format) && (EXTRACTOR_METAFORMAT_C_STRING != format)) @@ -320,9 +331,9 @@ meta_printer (void *cls, if (EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME == type) return 0; #if HAVE_LIBEXTRACTOR - fprintf (stdout, "\t%s - %s\n", EXTRACTOR_metatype_to_string (type), data); + fprintf(stdout, "\t%s - %s\n", EXTRACTOR_metatype_to_string(type), data); #else - fprintf (stdout, "\t%d - %s\n", type, data); + fprintf(stdout, "\t%d - %s\n", type, data); #endif return 0; } @@ -337,9 +348,9 @@ meta_printer (void *cls, * @return #GNUNET_OK to continue to iterate, #GNUNET_SYSERR to abort */ static int -keyword_printer (void *cls, const char *keyword, int is_mandatory) +keyword_printer(void *cls, const char *keyword, int is_mandatory) { - fprintf (stdout, "\t%s\n", keyword); + fprintf(stdout, "\t%s\n", keyword); return GNUNET_OK; } @@ -362,14 +373,14 @@ keyword_printer (void *cls, const char *keyword, int is_mandatory) * to abort the iteration */ static int -publish_inspector (void *cls, - struct GNUNET_FS_FileInformation *fi, - uint64_t length, - struct GNUNET_CONTAINER_MetaData *m, - struct GNUNET_FS_Uri **uri, - struct GNUNET_FS_BlockOptions *bo, - int *do_index, - void **client_info) +publish_inspector(void *cls, + struct GNUNET_FS_FileInformation *fi, + uint64_t length, + struct GNUNET_CONTAINER_MetaData *m, + struct GNUNET_FS_Uri **uri, + struct GNUNET_FS_BlockOptions *bo, + int *do_index, + void **client_info) { char *fn; char *fs; @@ -378,50 +389,50 @@ publish_inspector (void *cls, if (cls == fi) return GNUNET_OK; if ((disable_extractor) && (NULL != *uri)) - { - GNUNET_FS_uri_destroy (*uri); - *uri = NULL; - } - if (NULL != topKeywords) - { - if (NULL != *uri) { - new_uri = GNUNET_FS_uri_ksk_merge (topKeywords, *uri); - GNUNET_FS_uri_destroy (*uri); - *uri = new_uri; - GNUNET_FS_uri_destroy (topKeywords); + GNUNET_FS_uri_destroy(*uri); + *uri = NULL; } - else + if (NULL != topKeywords) { - *uri = topKeywords; + if (NULL != *uri) + { + new_uri = GNUNET_FS_uri_ksk_merge(topKeywords, *uri); + GNUNET_FS_uri_destroy(*uri); + *uri = new_uri; + GNUNET_FS_uri_destroy(topKeywords); + } + else + { + *uri = topKeywords; + } + topKeywords = NULL; } - topKeywords = NULL; - } if (NULL != meta) - { - GNUNET_CONTAINER_meta_data_merge (m, meta); - GNUNET_CONTAINER_meta_data_destroy (meta); - meta = NULL; - } + { + GNUNET_CONTAINER_meta_data_merge(m, meta); + GNUNET_CONTAINER_meta_data_destroy(meta); + meta = NULL; + } if (enable_creation_time) - GNUNET_CONTAINER_meta_data_add_publication_date (m); + GNUNET_CONTAINER_meta_data_add_publication_date(m); if (extract_only) - { - fn = GNUNET_CONTAINER_meta_data_get_by_type ( - m, - EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME); - fs = GNUNET_STRINGS_byte_size_fancy (length); - fprintf (stdout, _ ("Meta data for file `%s' (%s)\n"), fn, fs); - GNUNET_CONTAINER_meta_data_iterate (m, &meta_printer, NULL); - fprintf (stdout, _ ("Keywords for file `%s' (%s)\n"), fn, fs); - GNUNET_free (fn); - GNUNET_free (fs); - if (NULL != *uri) - GNUNET_FS_uri_ksk_get_keywords (*uri, &keyword_printer, NULL); - fprintf (stdout, "%s", "\n"); - } - if (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory (m)) - GNUNET_FS_file_information_inspect (fi, &publish_inspector, fi); + { + fn = GNUNET_CONTAINER_meta_data_get_by_type( + m, + EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME); + fs = GNUNET_STRINGS_byte_size_fancy(length); + fprintf(stdout, _("Meta data for file `%s' (%s)\n"), fn, fs); + GNUNET_CONTAINER_meta_data_iterate(m, &meta_printer, NULL); + fprintf(stdout, _("Keywords for file `%s' (%s)\n"), fn, fs); + GNUNET_free(fn); + GNUNET_free(fs); + if (NULL != *uri) + GNUNET_FS_uri_ksk_get_keywords(*uri, &keyword_printer, NULL); + fprintf(stdout, "%s", "\n"); + } + if (GNUNET_YES == GNUNET_FS_meta_data_test_for_directory(m)) + GNUNET_FS_file_information_inspect(fi, &publish_inspector, fi); return GNUNET_OK; } @@ -436,16 +447,16 @@ publish_inspector (void *cls, * @param emsg error message, NULL on success */ static void -uri_sks_continuation (void *cls, - const struct GNUNET_FS_Uri *sks_uri, - const char *emsg) +uri_sks_continuation(void *cls, + const struct GNUNET_FS_Uri *sks_uri, + const char *emsg) { if (NULL != emsg) - { - fprintf (stderr, "%s\n", emsg); - ret = 1; - } - GNUNET_SCHEDULER_shutdown (); + { + fprintf(stderr, "%s\n", emsg); + ret = 1; + } + GNUNET_SCHEDULER_shutdown(); } @@ -459,33 +470,33 @@ uri_sks_continuation (void *cls, * @param emsg error message, NULL on success */ static void -uri_ksk_continuation (void *cls, - const struct GNUNET_FS_Uri *ksk_uri, - const char *emsg) +uri_ksk_continuation(void *cls, + const struct GNUNET_FS_Uri *ksk_uri, + const char *emsg) { const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv; if (NULL != emsg) - { - fprintf (stderr, "%s\n", emsg); - ret = 1; - } + { + fprintf(stderr, "%s\n", emsg); + ret = 1; + } if (NULL == namespace) - { - GNUNET_SCHEDULER_shutdown (); - return; - } - priv = GNUNET_IDENTITY_ego_get_private_key (namespace); - GNUNET_FS_publish_sks (ctx, - priv, - this_id, - next_id, - meta, - uri, - &bo, - GNUNET_FS_PUBLISH_OPTION_NONE, - &uri_sks_continuation, - NULL); + { + GNUNET_SCHEDULER_shutdown(); + return; + } + priv = GNUNET_IDENTITY_ego_get_private_key(namespace); + GNUNET_FS_publish_sks(ctx, + priv, + this_id, + next_id, + meta, + uri, + &bo, + GNUNET_FS_PUBLISH_OPTION_NONE, + &uri_sks_continuation, + NULL); } @@ -497,52 +508,52 @@ uri_ksk_continuation (void *cls, * @return handle with the information for the publishing operation */ static struct GNUNET_FS_FileInformation * -get_file_information (struct GNUNET_FS_ShareTreeItem *item) +get_file_information(struct GNUNET_FS_ShareTreeItem *item) { struct GNUNET_FS_FileInformation *fi; struct GNUNET_FS_FileInformation *fic; struct GNUNET_FS_ShareTreeItem *child; if (GNUNET_YES == item->is_directory) - { - if (NULL == item->meta) - item->meta = GNUNET_CONTAINER_meta_data_create (); - GNUNET_CONTAINER_meta_data_delete (item->meta, - EXTRACTOR_METATYPE_MIMETYPE, - NULL, - 0); - GNUNET_FS_meta_data_make_directory (item->meta); - if (NULL == item->ksk_uri) { - const char *mime = GNUNET_FS_DIRECTORY_MIME; - item->ksk_uri = GNUNET_FS_uri_ksk_create_from_args (1, &mime); + if (NULL == item->meta) + item->meta = GNUNET_CONTAINER_meta_data_create(); + GNUNET_CONTAINER_meta_data_delete(item->meta, + EXTRACTOR_METATYPE_MIMETYPE, + NULL, + 0); + GNUNET_FS_meta_data_make_directory(item->meta); + if (NULL == item->ksk_uri) + { + const char *mime = GNUNET_FS_DIRECTORY_MIME; + item->ksk_uri = GNUNET_FS_uri_ksk_create_from_args(1, &mime); + } + else + GNUNET_FS_uri_ksk_add_keyword(item->ksk_uri, + GNUNET_FS_DIRECTORY_MIME, + GNUNET_NO); + fi = GNUNET_FS_file_information_create_empty_directory(ctx, + NULL, + item->ksk_uri, + item->meta, + &bo, + item->filename); + for (child = item->children_head; child; child = child->next) + { + fic = get_file_information(child); + GNUNET_break(GNUNET_OK == GNUNET_FS_file_information_add(fi, fic)); + } } - else - GNUNET_FS_uri_ksk_add_keyword (item->ksk_uri, - GNUNET_FS_DIRECTORY_MIME, - GNUNET_NO); - fi = GNUNET_FS_file_information_create_empty_directory (ctx, - NULL, - item->ksk_uri, - item->meta, - &bo, - item->filename); - for (child = item->children_head; child; child = child->next) + else { - fic = get_file_information (child); - GNUNET_break (GNUNET_OK == GNUNET_FS_file_information_add (fi, fic)); + fi = GNUNET_FS_file_information_create_from_file(ctx, + NULL, + item->filename, + item->ksk_uri, + item->meta, + !do_insert, + &bo); } - } - else - { - fi = GNUNET_FS_file_information_create_from_file (ctx, - NULL, - item->filename, - item->ksk_uri, - item->meta, - ! do_insert, - &bo); - } return fi; } @@ -554,46 +565,46 @@ get_file_information (struct GNUNET_FS_ShareTreeItem *item) * @param directory_scan_result result from the directory scan, freed in this function */ static void -directory_trim_complete (struct GNUNET_FS_ShareTreeItem *directory_scan_result) +directory_trim_complete(struct GNUNET_FS_ShareTreeItem *directory_scan_result) { struct GNUNET_FS_FileInformation *fi; const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv; - fi = get_file_information (directory_scan_result); - GNUNET_FS_share_tree_free (directory_scan_result); + fi = get_file_information(directory_scan_result); + GNUNET_FS_share_tree_free(directory_scan_result); if (NULL == fi) - { - fprintf (stderr, "%s", _ ("Could not publish\n")); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_FS_file_information_inspect (fi, &publish_inspector, NULL); + { + fprintf(stderr, "%s", _("Could not publish\n")); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_FS_file_information_inspect(fi, &publish_inspector, NULL); if (extract_only) - { - GNUNET_FS_file_information_destroy (fi, NULL, NULL); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_FS_file_information_destroy(fi, NULL, NULL); + GNUNET_SCHEDULER_shutdown(); + return; + } if (NULL == namespace) priv = NULL; else - priv = GNUNET_IDENTITY_ego_get_private_key (namespace); - pc = GNUNET_FS_publish_start (ctx, - fi, - priv, - this_id, - next_id, - (do_simulate) - ? GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY - : GNUNET_FS_PUBLISH_OPTION_NONE); + priv = GNUNET_IDENTITY_ego_get_private_key(namespace); + pc = GNUNET_FS_publish_start(ctx, + fi, + priv, + this_id, + next_id, + (do_simulate) + ? GNUNET_FS_PUBLISH_OPTION_SIMULATE_ONLY + : GNUNET_FS_PUBLISH_OPTION_NONE); if (NULL == pc) - { - fprintf (stderr, "%s", _ ("Could not start publishing.\n")); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } + { + fprintf(stderr, "%s", _("Could not start publishing.\n")); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } } @@ -609,57 +620,63 @@ directory_trim_complete (struct GNUNET_FS_ShareTreeItem *directory_scan_result) * @param reason kind of progress we are making */ static void -directory_scan_cb (void *cls, - const char *filename, - int is_directory, - enum GNUNET_FS_DirScannerProgressUpdateReason reason) +directory_scan_cb(void *cls, + const char *filename, + int is_directory, + enum GNUNET_FS_DirScannerProgressUpdateReason reason) { struct GNUNET_FS_ShareTreeItem *directory_scan_result; switch (reason) - { - case GNUNET_FS_DIRSCANNER_FILE_START: - if (verbose > 1) { - if (is_directory == GNUNET_YES) - fprintf (stdout, _ ("Scanning directory `%s'.\n"), filename); - else - fprintf (stdout, _ ("Scanning file `%s'.\n"), filename); + case GNUNET_FS_DIRSCANNER_FILE_START: + if (verbose > 1) + { + if (is_directory == GNUNET_YES) + fprintf(stdout, _("Scanning directory `%s'.\n"), filename); + else + fprintf(stdout, _("Scanning file `%s'.\n"), filename); + } + break; + + case GNUNET_FS_DIRSCANNER_FILE_IGNORED: + fprintf(stderr, + _("There was trouble processing file `%s', skipping it.\n"), + filename); + break; + + case GNUNET_FS_DIRSCANNER_ALL_COUNTED: + if (verbose) + fprintf(stdout, "%s", _("Preprocessing complete.\n")); + break; + + case GNUNET_FS_DIRSCANNER_EXTRACT_FINISHED: + if (verbose > 2) + fprintf(stdout, + _("Extracting meta data from file `%s' complete.\n"), + filename); + break; + + case GNUNET_FS_DIRSCANNER_FINISHED: + if (verbose > 1) + fprintf(stdout, "%s", _("Meta data extraction has finished.\n")); + directory_scan_result = GNUNET_FS_directory_scan_get_result(ds); + ds = NULL; + GNUNET_FS_share_tree_trim(directory_scan_result); + directory_trim_complete(directory_scan_result); + break; + + case GNUNET_FS_DIRSCANNER_INTERNAL_ERROR: + fprintf(stdout, "%s", _("Error scanning directory.\n")); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + break; + + default: + GNUNET_assert(0); + break; } - break; - case GNUNET_FS_DIRSCANNER_FILE_IGNORED: - fprintf (stderr, - _ ("There was trouble processing file `%s', skipping it.\n"), - filename); - break; - case GNUNET_FS_DIRSCANNER_ALL_COUNTED: - if (verbose) - fprintf (stdout, "%s", _ ("Preprocessing complete.\n")); - break; - case GNUNET_FS_DIRSCANNER_EXTRACT_FINISHED: - if (verbose > 2) - fprintf (stdout, - _ ("Extracting meta data from file `%s' complete.\n"), - filename); - break; - case GNUNET_FS_DIRSCANNER_FINISHED: - if (verbose > 1) - fprintf (stdout, "%s", _ ("Meta data extraction has finished.\n")); - directory_scan_result = GNUNET_FS_directory_scan_get_result (ds); - ds = NULL; - GNUNET_FS_share_tree_trim (directory_scan_result); - directory_trim_complete (directory_scan_result); - break; - case GNUNET_FS_DIRSCANNER_INTERNAL_ERROR: - fprintf (stdout, "%s", _ ("Error scanning directory.\n")); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - break; - default: - GNUNET_assert (0); - break; - } - fflush (stdout); + fflush(stdout); } @@ -670,67 +687,67 @@ directory_scan_cb (void *cls, * @param args0 filename to publish */ static void -identity_continuation (const char *args0) +identity_continuation(const char *args0) { char *ex; char *emsg; if ((NULL != pseudonym) && (NULL == namespace)) - { - fprintf (stderr, _ ("Selected pseudonym `%s' unknown\n"), pseudonym); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } - if (NULL != uri_string) - { - emsg = NULL; - if (NULL == (uri = GNUNET_FS_uri_parse (uri_string, &emsg))) { - fprintf (stderr, _ ("Failed to parse URI: %s\n"), emsg); - GNUNET_free (emsg); + fprintf(stderr, _("Selected pseudonym `%s' unknown\n"), pseudonym); ret = 1; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); + return; + } + if (NULL != uri_string) + { + emsg = NULL; + if (NULL == (uri = GNUNET_FS_uri_parse(uri_string, &emsg))) + { + fprintf(stderr, _("Failed to parse URI: %s\n"), emsg); + GNUNET_free(emsg); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_FS_publish_ksk(ctx, + topKeywords, + meta, + uri, + &bo, + GNUNET_FS_PUBLISH_OPTION_NONE, + &uri_ksk_continuation, + NULL); return; } - GNUNET_FS_publish_ksk (ctx, - topKeywords, - meta, - uri, - &bo, - GNUNET_FS_PUBLISH_OPTION_NONE, - &uri_ksk_continuation, - NULL); - return; - } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, "FS", "EXTRACTORS", &ex)) + GNUNET_CONFIGURATION_get_value_string(cfg, "FS", "EXTRACTORS", &ex)) ex = NULL; - if (0 != access (args0, R_OK)) - { - fprintf (stderr, - _ ("Failed to access `%s': %s\n"), - args0, - strerror (errno)); - GNUNET_free_non_null (ex); - return; - } - ds = GNUNET_FS_directory_scan_start (args0, - disable_extractor, - ex, - &directory_scan_cb, - NULL); + if (0 != access(args0, R_OK)) + { + fprintf(stderr, + _("Failed to access `%s': %s\n"), + args0, + strerror(errno)); + GNUNET_free_non_null(ex); + return; + } + ds = GNUNET_FS_directory_scan_start(args0, + disable_extractor, + ex, + &directory_scan_cb, + NULL); if (NULL == ds) - { - fprintf ( - stderr, - "%s", - _ ( - "Failed to start meta directory scanner. Is gnunet-helper-publish-fs installed?\n")); - GNUNET_free_non_null (ex); - return; - } - GNUNET_free_non_null (ex); + { + fprintf( + stderr, + "%s", + _( + "Failed to start meta directory scanner. Is gnunet-helper-publish-fs installed?\n")); + GNUNET_free_non_null(ex); + return; + } + GNUNET_free_non_null(ex); } @@ -746,22 +763,22 @@ identity_continuation (const char *args0) * must thus no longer be used */ static void -identity_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +identity_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { const char *args0 = cls; if (NULL == ego) - { - identity_continuation (args0); - return; - } + { + identity_continuation(args0); + return; + } if (NULL == name) return; - if (0 == strcmp (name, pseudonym)) - namespace = ego; + if (0 == strcmp(name, pseudonym)) + namespace = ego; } @@ -774,82 +791,82 @@ identity_cb (void *cls, * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { /* check arguments */ if ((NULL != uri_string) && (extract_only)) - { - printf (_ ("Cannot extract metadata from a URI!\n")); - ret = -1; - return; - } - if (((NULL == uri_string) || (extract_only)) && - ((NULL == args[0]) || (NULL != args[1]))) - { - printf (_ ("You must specify one and only one filename for insertion.\n")); - ret = -1; - return; - } - if ((NULL != uri_string) && (NULL != args[0])) - { - printf (_ ("You must NOT specify an URI and a filename.\n")); - ret = -1; - return; - } - if (NULL != pseudonym) - { - if (NULL == this_id) { - fprintf (stderr, - _ ("Option `%s' is required when using option `%s'.\n"), - "-t", - "-P"); + printf(_("Cannot extract metadata from a URI!\n")); ret = -1; return; } - } - else - { /* ordinary insertion checks */ - if (NULL != next_id) + if (((NULL == uri_string) || (extract_only)) && + ((NULL == args[0]) || (NULL != args[1]))) { - fprintf (stderr, - _ ("Option `%s' makes no sense without option `%s'.\n"), - "-N", - "-P"); + printf(_("You must specify one and only one filename for insertion.\n")); ret = -1; return; } - if (NULL != this_id) + if ((NULL != uri_string) && (NULL != args[0])) { - fprintf (stderr, - _ ("Option `%s' makes no sense without option `%s'.\n"), - "-t", - "-P"); + printf(_("You must NOT specify an URI and a filename.\n")); ret = -1; return; } - } + if (NULL != pseudonym) + { + if (NULL == this_id) + { + fprintf(stderr, + _("Option `%s' is required when using option `%s'.\n"), + "-t", + "-P"); + ret = -1; + return; + } + } + else + { /* ordinary insertion checks */ + if (NULL != next_id) + { + fprintf(stderr, + _("Option `%s' makes no sense without option `%s'.\n"), + "-N", + "-P"); + ret = -1; + return; + } + if (NULL != this_id) + { + fprintf(stderr, + _("Option `%s' makes no sense without option `%s'.\n"), + "-t", + "-P"); + ret = -1; + return; + } + } cfg = c; - ctx = GNUNET_FS_start (cfg, - "gnunet-publish", - &progress_cb, - NULL, - GNUNET_FS_FLAGS_NONE, - GNUNET_FS_OPTIONS_END); + ctx = GNUNET_FS_start(cfg, + "gnunet-publish", + &progress_cb, + NULL, + GNUNET_FS_FLAGS_NONE, + GNUNET_FS_OPTIONS_END); if (NULL == ctx) - { - fprintf (stderr, _ ("Could not initialize `%s' subsystem.\n"), "FS"); - ret = 1; - return; - } - GNUNET_SCHEDULER_add_shutdown (&do_stop_task, NULL); + { + fprintf(stderr, _("Could not initialize `%s' subsystem.\n"), "FS"); + ret = 1; + return; + } + GNUNET_SCHEDULER_add_shutdown(&do_stop_task, NULL); if (NULL != pseudonym) - identity = GNUNET_IDENTITY_connect (cfg, &identity_cb, args[0]); + identity = GNUNET_IDENTITY_connect(cfg, &identity_cb, args[0]); else - identity_continuation (args[0]); + identity_continuation(args[0]); } @@ -861,120 +878,121 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_uint ('a', - "anonymity", - "LEVEL", - gettext_noop ( - "set the desired LEVEL of sender-anonymity"), - &bo.anonymity_level), - GNUNET_GETOPT_option_flag ( - 'D', - "disable-extractor", - gettext_noop ("do not use libextractor to add keywords or metadata"), - &disable_extractor), - GNUNET_GETOPT_option_flag ('E', - "enable-creation-time", - gettext_noop ( - "enable adding the creation time to the " - "metadata of the uploaded file"), - &enable_creation_time), - GNUNET_GETOPT_option_flag ('e', - "extract", - gettext_noop ( - "print list of extracted keywords that would " - "be used, but do not perform upload"), - &extract_only), - GNUNET_FS_GETOPT_KEYWORDS ( - 'k', - "key", - "KEYWORD", - gettext_noop ( - "add an additional keyword for the top-level " - "file or directory (this option can be specified multiple times)"), - &topKeywords), - GNUNET_FS_GETOPT_METADATA ( - 'm', - "meta", - "TYPE:VALUE", - gettext_noop ("set the meta-data for the given TYPE to the given VALUE"), - &meta), - GNUNET_GETOPT_option_flag ( - 'n', - "noindex", - gettext_noop ("do not index, perform full insertion (stores " - "entire file in encrypted form in GNUnet database)"), - &do_insert), - GNUNET_GETOPT_option_string ( - 'N', - "next", - "ID", - gettext_noop ("specify ID of an updated version to be " - "published in the future (for namespace insertions only)"), - &next_id), - GNUNET_GETOPT_option_uint ('p', - "priority", - "PRIORITY", - gettext_noop ( - "specify the priority of the content"), - &bo.content_priority), - GNUNET_GETOPT_option_string ('P', - "pseudonym", - "NAME", - gettext_noop ( - "publish the files under the pseudonym " - "NAME (place file into namespace)"), - &pseudonym), - GNUNET_GETOPT_option_uint ('r', - "replication", - "LEVEL", - gettext_noop ( - "set the desired replication LEVEL"), - &bo.replication_level), - GNUNET_GETOPT_option_flag ('s', - "simulate-only", - gettext_noop ( - "only simulate the process but do not do " - "any actual publishing (useful to compute URIs)"), - &do_simulate), - GNUNET_GETOPT_option_string ('t', - "this", - "ID", - gettext_noop ( - "set the ID of this version of the publication " - "(for namespace insertions only)"), - &this_id), - GNUNET_GETOPT_option_string ( - 'u', - "uri", - "URI", - gettext_noop ( - "URI to be published (can be used instead of passing a " - "file to add keywords to the file with the respective URI)"), - &uri_string), - - GNUNET_GETOPT_option_verbose (&verbose), - - GNUNET_GETOPT_OPTION_END}; + { GNUNET_GETOPT_option_uint('a', + "anonymity", + "LEVEL", + gettext_noop( + "set the desired LEVEL of sender-anonymity"), + &bo.anonymity_level), + GNUNET_GETOPT_option_flag( + 'D', + "disable-extractor", + gettext_noop("do not use libextractor to add keywords or metadata"), + &disable_extractor), + GNUNET_GETOPT_option_flag('E', + "enable-creation-time", + gettext_noop( + "enable adding the creation time to the " + "metadata of the uploaded file"), + &enable_creation_time), + GNUNET_GETOPT_option_flag('e', + "extract", + gettext_noop( + "print list of extracted keywords that would " + "be used, but do not perform upload"), + &extract_only), + GNUNET_FS_GETOPT_KEYWORDS( + 'k', + "key", + "KEYWORD", + gettext_noop( + "add an additional keyword for the top-level " + "file or directory (this option can be specified multiple times)"), + &topKeywords), + GNUNET_FS_GETOPT_METADATA( + 'm', + "meta", + "TYPE:VALUE", + gettext_noop("set the meta-data for the given TYPE to the given VALUE"), + &meta), + GNUNET_GETOPT_option_flag( + 'n', + "noindex", + gettext_noop("do not index, perform full insertion (stores " + "entire file in encrypted form in GNUnet database)"), + &do_insert), + GNUNET_GETOPT_option_string( + 'N', + "next", + "ID", + gettext_noop("specify ID of an updated version to be " + "published in the future (for namespace insertions only)"), + &next_id), + GNUNET_GETOPT_option_uint('p', + "priority", + "PRIORITY", + gettext_noop( + "specify the priority of the content"), + &bo.content_priority), + GNUNET_GETOPT_option_string('P', + "pseudonym", + "NAME", + gettext_noop( + "publish the files under the pseudonym " + "NAME (place file into namespace)"), + &pseudonym), + GNUNET_GETOPT_option_uint('r', + "replication", + "LEVEL", + gettext_noop( + "set the desired replication LEVEL"), + &bo.replication_level), + GNUNET_GETOPT_option_flag('s', + "simulate-only", + gettext_noop( + "only simulate the process but do not do " + "any actual publishing (useful to compute URIs)"), + &do_simulate), + GNUNET_GETOPT_option_string('t', + "this", + "ID", + gettext_noop( + "set the ID of this version of the publication " + "(for namespace insertions only)"), + &this_id), + GNUNET_GETOPT_option_string( + 'u', + "uri", + "URI", + gettext_noop( + "URI to be published (can be used instead of passing a " + "file to add keywords to the file with the respective URI)"), + &uri_string), + + GNUNET_GETOPT_option_verbose(&verbose), + + GNUNET_GETOPT_OPTION_END }; + bo.expiration_time = - GNUNET_TIME_year_to_time (GNUNET_TIME_get_current_year () + 2); + GNUNET_TIME_year_to_time(GNUNET_TIME_get_current_year() + 2); - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-publish [OPTIONS] FILENAME", - gettext_noop ("Publish a file or directory on GNUnet"), - options, - &run, - NULL)) - ? ret - : 1; - GNUNET_free ((void *) argv); + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-publish [OPTIONS] FILENAME", + gettext_noop("Publish a file or directory on GNUnet"), + options, + &run, + NULL)) + ? ret + : 1; + GNUNET_free((void *)argv); return ret; } diff --git a/src/fs/gnunet-search.c b/src/fs/gnunet-search.c index 7d6ff4c6b..ac31387e2 100644 --- a/src/fs/gnunet-search.c +++ b/src/fs/gnunet-search.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-search.c * @brief searching for files on GNUnet @@ -76,13 +76,13 @@ static struct GNUNET_SCHEDULER_Task *tt; * @return 0 to continue extracting, 1 to abort */ static int -item_printer (void *cls, - const char *plugin_name, - enum EXTRACTOR_MetaType type, - enum EXTRACTOR_MetaFormat format, - const char *data_mime_type, - const char *data, - size_t data_size) +item_printer(void *cls, + const char *plugin_name, + enum EXTRACTOR_MetaType type, + enum EXTRACTOR_MetaFormat format, + const char *data_mime_type, + const char *data, + size_t data_size) { if ((format != EXTRACTOR_METAFORMAT_UTF8) && (format != EXTRACTOR_METAFORMAT_C_STRING)) @@ -90,45 +90,45 @@ item_printer (void *cls, if (type == EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME) return 0; #if HAVE_LIBEXTRACTOR - printf ("\t%20s: %s\n", - dgettext (LIBEXTRACTOR_GETTEXT_DOMAIN, - EXTRACTOR_metatype_to_string (type)), - data); + printf("\t%20s: %s\n", + dgettext(LIBEXTRACTOR_GETTEXT_DOMAIN, + EXTRACTOR_metatype_to_string(type)), + data); #else - printf ("\t%20d: %s\n", type, data); + printf("\t%20d: %s\n", type, data); #endif return 0; } static void -clean_task (void *cls) +clean_task(void *cls) { size_t dsize; void *ddata; - GNUNET_FS_stop (ctx); + GNUNET_FS_stop(ctx); ctx = NULL; if (output_filename == NULL) return; - if (GNUNET_OK != GNUNET_FS_directory_builder_finish (db, &dsize, &ddata)) - { - GNUNET_break (0); - GNUNET_free (output_filename); - return; - } - if (dsize != GNUNET_DISK_fn_write (output_filename, - ddata, - dsize, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)) - { - fprintf (stderr, - _ ("Failed to write directory with search results to `%s'\n"), - output_filename); - } - GNUNET_free_non_null (ddata); - GNUNET_free (output_filename); + if (GNUNET_OK != GNUNET_FS_directory_builder_finish(db, &dsize, &ddata)) + { + GNUNET_break(0); + GNUNET_free(output_filename); + return; + } + if (dsize != GNUNET_DISK_fn_write(output_filename, + ddata, + dsize, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)) + { + fprintf(stderr, + _("Failed to write directory with search results to `%s'\n"), + output_filename); + } + GNUNET_free_non_null(ddata); + GNUNET_free(output_filename); } @@ -146,7 +146,7 @@ clean_task (void *cls) * field in the GNUNET_FS_ProgressInfo struct. */ static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *info) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *info) { static unsigned int cnt; int is_directory; @@ -154,92 +154,98 @@ progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *info) char *filename; switch (info->status) - { - case GNUNET_FS_STATUS_SEARCH_START: - break; - case GNUNET_FS_STATUS_SEARCH_RESULT: - if (db != NULL) - GNUNET_FS_directory_builder_add (db, - info->value.search.specifics.result.uri, - info->value.search.specifics.result.meta, - NULL); - uri = GNUNET_FS_uri_to_string (info->value.search.specifics.result.uri); - printf ("#%u:\n", ++cnt); - filename = GNUNET_CONTAINER_meta_data_get_by_type ( - info->value.search.specifics.result.meta, - EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME); - is_directory = GNUNET_FS_meta_data_test_for_directory ( - info->value.search.specifics.result.meta); - if (NULL != filename) { - while ((filename[0] != '\0') && ('/' == filename[strlen (filename) - 1])) - filename[strlen (filename) - 1] = '\0'; - GNUNET_DISK_filename_canonicalize (filename); - if (GNUNET_YES == is_directory) - printf ("gnunet-download -o \"%s%s\" -R %s\n", - filename, - GNUNET_FS_DIRECTORY_EXT, - uri); + case GNUNET_FS_STATUS_SEARCH_START: + break; + + case GNUNET_FS_STATUS_SEARCH_RESULT: + if (db != NULL) + GNUNET_FS_directory_builder_add(db, + info->value.search.specifics.result.uri, + info->value.search.specifics.result.meta, + NULL); + uri = GNUNET_FS_uri_to_string(info->value.search.specifics.result.uri); + printf("#%u:\n", ++cnt); + filename = GNUNET_CONTAINER_meta_data_get_by_type( + info->value.search.specifics.result.meta, + EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME); + is_directory = GNUNET_FS_meta_data_test_for_directory( + info->value.search.specifics.result.meta); + if (NULL != filename) + { + while ((filename[0] != '\0') && ('/' == filename[strlen(filename) - 1])) + filename[strlen(filename) - 1] = '\0'; + GNUNET_DISK_filename_canonicalize(filename); + if (GNUNET_YES == is_directory) + printf("gnunet-download -o \"%s%s\" -R %s\n", + filename, + GNUNET_FS_DIRECTORY_EXT, + uri); + else + printf("gnunet-download -o \"%s\" %s\n", filename, uri); + } + else if (GNUNET_YES == is_directory) + printf("gnunet-download -o \"collection%s\" -R %s\n", + GNUNET_FS_DIRECTORY_EXT, + uri); else - printf ("gnunet-download -o \"%s\" %s\n", filename, uri); + printf("gnunet-download %s\n", uri); + if (verbose) + GNUNET_CONTAINER_meta_data_iterate(info->value.search.specifics.result + .meta, + &item_printer, + NULL); + printf("\n"); + fflush(stdout); + GNUNET_free_non_null(filename); + GNUNET_free(uri); + results++; + if ((results_limit > 0) && (results >= results_limit)) + GNUNET_SCHEDULER_shutdown(); + break; + + case GNUNET_FS_STATUS_SEARCH_UPDATE: + break; + + case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: + /* ignore */ + break; + + case GNUNET_FS_STATUS_SEARCH_ERROR: + fprintf(stderr, + _("Error searching: %s.\n"), + info->value.search.specifics.error.message); + GNUNET_SCHEDULER_shutdown(); + break; + + case GNUNET_FS_STATUS_SEARCH_STOPPED: + GNUNET_SCHEDULER_add_now(&clean_task, NULL); + break; + + default: + fprintf(stderr, _("Unexpected status: %d\n"), info->status); + break; } - else if (GNUNET_YES == is_directory) - printf ("gnunet-download -o \"collection%s\" -R %s\n", - GNUNET_FS_DIRECTORY_EXT, - uri); - else - printf ("gnunet-download %s\n", uri); - if (verbose) - GNUNET_CONTAINER_meta_data_iterate (info->value.search.specifics.result - .meta, - &item_printer, - NULL); - printf ("\n"); - fflush (stdout); - GNUNET_free_non_null (filename); - GNUNET_free (uri); - results++; - if ((results_limit > 0) && (results >= results_limit)) - GNUNET_SCHEDULER_shutdown (); - break; - case GNUNET_FS_STATUS_SEARCH_UPDATE: - break; - case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: - /* ignore */ - break; - case GNUNET_FS_STATUS_SEARCH_ERROR: - fprintf (stderr, - _ ("Error searching: %s.\n"), - info->value.search.specifics.error.message); - GNUNET_SCHEDULER_shutdown (); - break; - case GNUNET_FS_STATUS_SEARCH_STOPPED: - GNUNET_SCHEDULER_add_now (&clean_task, NULL); - break; - default: - fprintf (stderr, _ ("Unexpected status: %d\n"), info->status); - break; - } return NULL; } static void -shutdown_task (void *cls) +shutdown_task(void *cls) { if (sc != NULL) - { - GNUNET_FS_search_stop (sc); - sc = NULL; - } + { + GNUNET_FS_search_stop(sc); + sc = NULL; + } } static void -timeout_task (void *cls) +timeout_task(void *cls) { tt = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -252,10 +258,10 @@ timeout_task (void *cls) * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { struct GNUNET_FS_Uri *uri; unsigned int argc; @@ -264,46 +270,46 @@ run (void *cls, argc = 0; while (NULL != args[argc]) argc++; - uri = GNUNET_FS_uri_ksk_create_from_args (argc, (const char **) args); + uri = GNUNET_FS_uri_ksk_create_from_args(argc, (const char **)args); if (NULL == uri) - { - fprintf (stderr, - "%s", - _ ("Could not create keyword URI from arguments.\n")); - ret = 1; - return; - } + { + fprintf(stderr, + "%s", + _("Could not create keyword URI from arguments.\n")); + ret = 1; + return; + } cfg = c; - ctx = GNUNET_FS_start (cfg, - "gnunet-search", - &progress_cb, - NULL, - GNUNET_FS_FLAGS_NONE, - GNUNET_FS_OPTIONS_END); + ctx = GNUNET_FS_start(cfg, + "gnunet-search", + &progress_cb, + NULL, + GNUNET_FS_FLAGS_NONE, + GNUNET_FS_OPTIONS_END); if (NULL == ctx) - { - fprintf (stderr, _ ("Could not initialize `%s' subsystem.\n"), "FS"); - GNUNET_FS_uri_destroy (uri); - ret = 1; - return; - } + { + fprintf(stderr, _("Could not initialize `%s' subsystem.\n"), "FS"); + GNUNET_FS_uri_destroy(uri); + ret = 1; + return; + } if (output_filename != NULL) - db = GNUNET_FS_directory_builder_create (NULL); + db = GNUNET_FS_directory_builder_create(NULL); options = GNUNET_FS_SEARCH_OPTION_NONE; if (local_only) options |= GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY; - sc = GNUNET_FS_search_start (ctx, uri, anonymity, options, NULL); - GNUNET_FS_uri_destroy (uri); + sc = GNUNET_FS_search_start(ctx, uri, anonymity, options, NULL); + GNUNET_FS_uri_destroy(uri); if (NULL == sc) - { - fprintf (stderr, "%s", _ ("Could not start searching.\n")); - GNUNET_FS_stop (ctx); - ret = 1; - return; - } + { + fprintf(stderr, "%s", _("Could not start searching.\n")); + GNUNET_FS_stop(ctx); + ret = 1; + return; + } if (0 != timeout.rel_value_us) - tt = GNUNET_SCHEDULER_add_delayed (timeout, &timeout_task, NULL); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + tt = GNUNET_SCHEDULER_add_delayed(timeout, &timeout_task, NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); } @@ -315,57 +321,57 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_uint ('a', - "anonymity", - "LEVEL", - gettext_noop ( - "set the desired LEVEL of receiver-anonymity"), - &anonymity), - GNUNET_GETOPT_option_flag ( - 'n', - "no-network", - gettext_noop ("only search the local peer (no P2P network search)"), - &local_only), - GNUNET_GETOPT_option_string ( - 'o', - "output", - "PREFIX", - gettext_noop ("write search results to file starting with PREFIX"), - &output_filename), - GNUNET_GETOPT_option_relative_time ( - 't', - "timeout", - "DELAY", - gettext_noop ("automatically terminate search after DELAY"), - &timeout), - GNUNET_GETOPT_option_verbose (&verbose), - GNUNET_GETOPT_option_uint ('N', - "results", - "VALUE", - gettext_noop ("automatically terminate search " - "after VALUE results are found"), - &results_limit), - GNUNET_GETOPT_OPTION_END}; - - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + { GNUNET_GETOPT_option_uint('a', + "anonymity", + "LEVEL", + gettext_noop( + "set the desired LEVEL of receiver-anonymity"), + &anonymity), + GNUNET_GETOPT_option_flag( + 'n', + "no-network", + gettext_noop("only search the local peer (no P2P network search)"), + &local_only), + GNUNET_GETOPT_option_string( + 'o', + "output", + "PREFIX", + gettext_noop("write search results to file starting with PREFIX"), + &output_filename), + GNUNET_GETOPT_option_relative_time( + 't', + "timeout", + "DELAY", + gettext_noop("automatically terminate search after DELAY"), + &timeout), + GNUNET_GETOPT_option_verbose(&verbose), + GNUNET_GETOPT_option_uint('N', + "results", + "VALUE", + gettext_noop("automatically terminate search " + "after VALUE results are found"), + &results_limit), + GNUNET_GETOPT_OPTION_END }; + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-search [OPTIONS] KEYWORD", - gettext_noop ( - "Search GNUnet for files that were published on GNUnet"), - options, - &run, - NULL)) - ? ret - : 1; - GNUNET_free ((void *) argv); + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-search [OPTIONS] KEYWORD", + gettext_noop( + "Search GNUnet for files that were published on GNUnet"), + options, + &run, + NULL)) + ? ret + : 1; + GNUNET_free((void *)argv); return ret; } diff --git a/src/fs/gnunet-service-fs.c b/src/fs/gnunet-service-fs.c index 691242ce3..70aff8a75 100644 --- a/src/fs/gnunet-service-fs.c +++ b/src/fs/gnunet-service-fs.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs.c @@ -59,7 +59,7 @@ * time interval, remaining cover traffic counters are * decremented by 1/16th. */ -#define COVER_AGE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define COVER_AGE_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) /** * Collect an instane number of statistics? May cause excessive IPC. @@ -72,9 +72,7 @@ * Doubly-linked list of requests we are performing * on behalf of the same client. */ -struct ClientRequest -{ - +struct ClientRequest { /** * This is a doubly-linked list. */ @@ -99,7 +97,6 @@ struct ClientRequest * Task scheduled to destroy the request. */ struct GNUNET_SCHEDULER_Task * kill_task; - }; @@ -107,8 +104,7 @@ struct ClientRequest * Replies to be transmitted to the client. The actual * response message is allocated after this struct. */ -struct ClientResponse -{ +struct ClientResponse { /** * This is a doubly-linked list. */ @@ -135,9 +131,7 @@ struct ClientResponse * Information we track while handling an index * start request from a client. */ -struct IndexStartContext -{ - +struct IndexStartContext { /** * This is a doubly linked list. */ @@ -167,16 +161,13 @@ struct IndexStartContext * Hash of the contents of the file. */ struct GNUNET_HashCode file_id; - }; /** * A local client. */ -struct GSF_LocalClient -{ - +struct GSF_LocalClient { /** * ID of the client. */ @@ -218,7 +209,6 @@ struct GSF_LocalClient * Tail of linked list of responses. */ struct ClientResponse *res_tail; - }; @@ -343,13 +333,13 @@ static struct GNUNET_LOAD_Value *datastore_get_load; * @return handle to local client entry */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { struct GSF_LocalClient *pos; - pos = GNUNET_new (struct GSF_LocalClient); + pos = GNUNET_new(struct GSF_LocalClient); pos->client = client; pos->mq = mq; return pos; @@ -362,22 +352,22 @@ client_connect_cb (void *cls, * @param cls the client request to free */ static void -client_request_destroy (void *cls) +client_request_destroy(void *cls) { struct ClientRequest *cr = cls; struct GSF_LocalClient *lc = cr->lc; cr->kill_task = NULL; - GNUNET_CONTAINER_DLL_remove (lc->cr_head, - lc->cr_tail, - cr); - GSF_pending_request_cancel_ (cr->pr, - GNUNET_YES); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# client searches active"), - -1, - GNUNET_NO); - GNUNET_free (cr); + GNUNET_CONTAINER_DLL_remove(lc->cr_head, + lc->cr_tail, + cr); + GSF_pending_request_cancel_(cr->pr, + GNUNET_YES); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# client searches active"), + -1, + GNUNET_NO); + GNUNET_free(cr); } @@ -400,15 +390,15 @@ client_request_destroy (void *cls) * @param data_len number of bytes in @a data */ static void -client_response_handler (void *cls, - enum GNUNET_BLOCK_EvaluationResult eval, - struct GSF_PendingRequest *pr, - uint32_t reply_anonymity_level, - struct GNUNET_TIME_Absolute expiration, - struct GNUNET_TIME_Absolute last_transmission, - enum GNUNET_BLOCK_Type type, - const void *data, - size_t data_len) +client_response_handler(void *cls, + enum GNUNET_BLOCK_EvaluationResult eval, + struct GSF_PendingRequest *pr, + uint32_t reply_anonymity_level, + struct GNUNET_TIME_Absolute expiration, + struct GNUNET_TIME_Absolute last_transmission, + enum GNUNET_BLOCK_Type type, + const void *data, + size_t data_len) { struct ClientRequest *cr = cls; struct GSF_LocalClient *lc; @@ -417,52 +407,52 @@ client_response_handler (void *cls, const struct GSF_PendingRequestData *prd; if (NULL == data) - { - /* local-only request, with no result, clean up. */ - if (NULL == cr->kill_task) - cr->kill_task = GNUNET_SCHEDULER_add_now (&client_request_destroy, - cr); - return; - } - prd = GSF_pending_request_get_data_ (pr); - GNUNET_break (type != GNUNET_BLOCK_TYPE_ANY); + { + /* local-only request, with no result, clean up. */ + if (NULL == cr->kill_task) + cr->kill_task = GNUNET_SCHEDULER_add_now(&client_request_destroy, + cr); + return; + } + prd = GSF_pending_request_get_data_(pr); + GNUNET_break(type != GNUNET_BLOCK_TYPE_ANY); if ((prd->type != type) && (prd->type != GNUNET_BLOCK_TYPE_ANY)) - { - GNUNET_break (0); - return; - } - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop - ("# replies received for local clients"), 1, - GNUNET_NO); - GNUNET_assert (pr == cr->pr); + { + GNUNET_break(0); + return; + } + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop + ("# replies received for local clients"), 1, + GNUNET_NO); + GNUNET_assert(pr == cr->pr); lc = cr->lc; - env = GNUNET_MQ_msg_extra (pm, - data_len, - GNUNET_MESSAGE_TYPE_FS_PUT); - pm->type = htonl (type); - pm->expiration = GNUNET_TIME_absolute_hton (expiration); - pm->last_transmission = GNUNET_TIME_absolute_hton (last_transmission); - pm->num_transmissions = htonl (prd->num_transmissions); - pm->respect_offered = htonl (prd->respect_offered); - GNUNET_memcpy (&pm[1], - data, - data_len); - GNUNET_MQ_send (lc->mq, - env); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Queued reply to query `%s' for local client\n", - GNUNET_h2s (&prd->query)); + env = GNUNET_MQ_msg_extra(pm, + data_len, + GNUNET_MESSAGE_TYPE_FS_PUT); + pm->type = htonl(type); + pm->expiration = GNUNET_TIME_absolute_hton(expiration); + pm->last_transmission = GNUNET_TIME_absolute_hton(last_transmission); + pm->num_transmissions = htonl(prd->num_transmissions); + pm->respect_offered = htonl(prd->respect_offered); + GNUNET_memcpy(&pm[1], + data, + data_len); + GNUNET_MQ_send(lc->mq, + env); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Queued reply to query `%s' for local client\n", + GNUNET_h2s(&prd->query)); if (GNUNET_BLOCK_EVALUATION_OK_LAST != eval) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Evaluation %d - keeping query alive\n", - (int) eval); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Evaluation %d - keeping query alive\n", + (int)eval); + return; + } if (NULL == cr->kill_task) - cr->kill_task = GNUNET_SCHEDULER_add_now (&client_request_destroy, - cr); + cr->kill_task = GNUNET_SCHEDULER_add_now(&client_request_destroy, + cr); } @@ -475,9 +465,9 @@ client_response_handler (void *cls, * @param app_ctx the `struct GSF_LocalClient` */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { struct GSF_LocalClient *lc = app_ctx; struct IndexStartContext *isc; @@ -485,27 +475,27 @@ client_disconnect_cb (void *cls, struct ClientResponse *res; while (NULL != (cr = lc->cr_head)) - { - if (NULL != cr->kill_task) - GNUNET_SCHEDULER_cancel (cr->kill_task); - client_request_destroy (cr); - } + { + if (NULL != cr->kill_task) + GNUNET_SCHEDULER_cancel(cr->kill_task); + client_request_destroy(cr); + } while (NULL != (res = lc->res_head)) - { - GNUNET_CONTAINER_DLL_remove (lc->res_head, - lc->res_tail, - res); - GNUNET_free (res); - } + { + GNUNET_CONTAINER_DLL_remove(lc->res_head, + lc->res_tail, + res); + GNUNET_free(res); + } while (NULL != (isc = lc->isc_head)) - { - GNUNET_CONTAINER_DLL_remove (lc->isc_head, - lc->isc_tail, - isc); - GNUNET_CRYPTO_hash_file_cancel (isc->fhc); - GNUNET_free (isc); - } - GNUNET_free (lc); + { + GNUNET_CONTAINER_DLL_remove(lc->isc_head, + lc->isc_tail, + isc); + GNUNET_CRYPTO_hash_file_cancel(isc->fhc); + GNUNET_free(isc); + } + GNUNET_free(lc); } @@ -518,14 +508,14 @@ client_disconnect_cb (void *cls, * @param cls unused closure */ static void -age_cover_counters (void *cls) +age_cover_counters(void *cls) { GSF_cover_content_count = (GSF_cover_content_count * 15) / 16; GSF_cover_query_count = (GSF_cover_query_count * 15) / 16; cover_age_task = - GNUNET_SCHEDULER_add_delayed (COVER_AGE_FREQUENCY, - &age_cover_counters, - NULL); + GNUNET_SCHEDULER_add_delayed(COVER_AGE_FREQUENCY, + &age_cover_counters, + NULL); } @@ -536,12 +526,12 @@ age_cover_counters (void *cls) * @param start time when the datastore request was issued */ void -GSF_update_datastore_delay_ (struct GNUNET_TIME_Absolute start) +GSF_update_datastore_delay_(struct GNUNET_TIME_Absolute start) { struct GNUNET_TIME_Relative delay; - delay = GNUNET_TIME_absolute_get_duration (start); - GNUNET_LOAD_update (datastore_get_load, delay.rel_value_us); + delay = GNUNET_TIME_absolute_get_duration(start); + GNUNET_LOAD_update(datastore_get_load, delay.rel_value_us); } @@ -556,11 +546,11 @@ GSF_update_datastore_delay_ (struct GNUNET_TIME_Absolute start) * #GNUNET_SYSERR to process for free (load low) */ int -GSF_test_get_load_too_high_ (uint32_t priority) +GSF_test_get_load_too_high_(uint32_t priority) { double ld; - ld = GNUNET_LOAD_get_load (datastore_get_load); + ld = GNUNET_LOAD_get_load(datastore_get_load); if (ld < 1) return GNUNET_SYSERR; if (ld <= priority) @@ -581,30 +571,30 @@ GSF_test_get_load_too_high_ (uint32_t priority) * @param prop performance data for the address (as far as known) */ static void -update_latencies (void *cls, - const struct GNUNET_HELLO_Address *address, - int active, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, - struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, - const struct GNUNET_ATS_Properties *prop) +update_latencies(void *cls, + const struct GNUNET_HELLO_Address *address, + int active, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out, + struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in, + const struct GNUNET_ATS_Properties *prop) { if (NULL == address) - { - /* ATS service temporarily disconnected */ - return; - } + { + /* ATS service temporarily disconnected */ + return; + } if (GNUNET_YES != active) return; - GSF_update_peer_latency_ (&address->peer, - prop->delay); + GSF_update_peer_latency_(&address->peer, + prop->delay); GSF_avg_latency.rel_value_us = (GSF_avg_latency.rel_value_us * 31 + - GNUNET_MIN (5000, prop->delay.rel_value_us)) / 32; - GNUNET_STATISTICS_set (GSF_stats, - gettext_noop ("# running average P2P latency (ms)"), - GSF_avg_latency.rel_value_us / 1000LL, - GNUNET_NO); + GNUNET_MIN(5000, prop->delay.rel_value_us)) / 32; + GNUNET_STATISTICS_set(GSF_stats, + gettext_noop("# running average P2P latency (ms)"), + GSF_avg_latency.rel_value_us / 1000LL, + GNUNET_NO); } @@ -617,17 +607,17 @@ update_latencies (void *cls, * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_p2p_put (void *cls, - const struct PutMessage *put) +check_p2p_put(void *cls, + const struct PutMessage *put) { enum GNUNET_BLOCK_Type type; - type = ntohl (put->type); + type = ntohl(put->type); if (GNUNET_BLOCK_TYPE_FS_ONDEMAND == type) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -642,25 +632,25 @@ check_p2p_put (void *cls, * @param ppd peer performance data */ static void -consider_request_for_forwarding (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GSF_ConnectedPeer *cp, - const struct GSF_PeerPerformanceData *ppd) +consider_request_for_forwarding(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GSF_ConnectedPeer *cp, + const struct GSF_PeerPerformanceData *ppd) { struct GSF_PendingRequest *pr = cls; if (GNUNET_YES != - GSF_pending_request_test_target_ (pr, peer)) - { + GSF_pending_request_test_target_(pr, peer)) + { #if INSANE_STATISTICS - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# Loopback routes suppressed"), 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# Loopback routes suppressed"), 1, + GNUNET_NO); #endif - return; - } - GSF_plan_add_ (cp, - pr); + return; + } + GSF_plan_add_(cp, + pr); } @@ -675,17 +665,17 @@ consider_request_for_forwarding (void *cls, * @param result final datastore lookup result */ void -GSF_consider_forwarding (void *cls, - struct GSF_PendingRequest *pr, - enum GNUNET_BLOCK_EvaluationResult result) +GSF_consider_forwarding(void *cls, + struct GSF_PendingRequest *pr, + enum GNUNET_BLOCK_EvaluationResult result) { if (GNUNET_BLOCK_EVALUATION_OK_LAST == result) return; /* we're done... */ if (GNUNET_YES != - GSF_pending_request_test_active_ (pr)) + GSF_pending_request_test_active_(pr)) return; /* request is not actually active, skip! */ - GSF_iterate_connected_peers_ (&consider_request_for_forwarding, - pr); + GSF_iterate_connected_peers_(&consider_request_for_forwarding, + pr); } @@ -698,35 +688,35 @@ GSF_consider_forwarding (void *cls, * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_p2p_get (void *cls, - const struct GetMessage *gm) +check_p2p_get(void *cls, + const struct GetMessage *gm) { size_t msize; unsigned int bm; unsigned int bits; size_t bfsize; - msize = ntohs (gm->header.size); - bm = ntohl (gm->hash_bitmap); + msize = ntohs(gm->header.size); + bm = ntohl(gm->hash_bitmap); bits = 0; while (bm > 0) - { - if (1 == (bm & 1)) - bits++; - bm >>= 1; - } - if (msize < sizeof (struct GetMessage) + bits * sizeof (struct GNUNET_PeerIdentity)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (struct GNUNET_PeerIdentity); + { + if (1 == (bm & 1)) + bits++; + bm >>= 1; + } + if (msize < sizeof(struct GetMessage) + bits * sizeof(struct GNUNET_PeerIdentity)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + bfsize = msize - sizeof(struct GetMessage) - bits * sizeof(struct GNUNET_PeerIdentity); /* bfsize must be power of 2, check! */ if (0 != ((bfsize - 1) & bfsize)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -742,46 +732,48 @@ check_p2p_get (void *cls, * @param result final datastore lookup result */ static void -start_p2p_processing (void *cls, - struct GSF_PendingRequest *pr, - enum GNUNET_BLOCK_EvaluationResult result) +start_p2p_processing(void *cls, + struct GSF_PendingRequest *pr, + enum GNUNET_BLOCK_EvaluationResult result) { struct GSF_LocalClient *lc = cls; struct GSF_PendingRequestData *prd; - GNUNET_SERVICE_client_continue (lc->client); + GNUNET_SERVICE_client_continue(lc->client); if (GNUNET_BLOCK_EVALUATION_OK_LAST == result) return; /* we're done, 'pr' was already destroyed... */ - prd = GSF_pending_request_get_data_ (pr); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished database lookup for local request `%s' with result %d\n", - GNUNET_h2s (&prd->query), - result); + prd = GSF_pending_request_get_data_(pr); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished database lookup for local request `%s' with result %d\n", + GNUNET_h2s(&prd->query), + result); if (0 == prd->anonymity_level) - { - switch (prd->type) { - case GNUNET_BLOCK_TYPE_FS_DBLOCK: - case GNUNET_BLOCK_TYPE_FS_IBLOCK: - /* the above block types MAY be available via 'cadet' */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Considering cadet-based download for block\n"); - GSF_cadet_lookup_ (pr); - break; - case GNUNET_BLOCK_TYPE_FS_UBLOCK: - /* the above block types are in the DHT */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Considering DHT-based search for block\n"); - GSF_dht_lookup_ (pr); - break; - default: - GNUNET_break (0); - break; + switch (prd->type) + { + case GNUNET_BLOCK_TYPE_FS_DBLOCK: + case GNUNET_BLOCK_TYPE_FS_IBLOCK: + /* the above block types MAY be available via 'cadet' */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Considering cadet-based download for block\n"); + GSF_cadet_lookup_(pr); + break; + + case GNUNET_BLOCK_TYPE_FS_UBLOCK: + /* the above block types are in the DHT */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Considering DHT-based search for block\n"); + GSF_dht_lookup_(pr); + break; + + default: + GNUNET_break(0); + break; + } } - } - GSF_consider_forwarding (NULL, - pr, - result); + GSF_consider_forwarding(NULL, + pr, + result); } @@ -794,17 +786,17 @@ start_p2p_processing (void *cls, * @return #GNUNET_OK if @a sm is well-formed */ static int -check_client_start_search (void *cls, - const struct SearchMessage *sm) +check_client_start_search(void *cls, + const struct SearchMessage *sm) { uint16_t msize; - msize = ntohs (sm->header.size) - sizeof (struct SearchMessage); - if (0 != msize % sizeof (struct GNUNET_HashCode)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + msize = ntohs(sm->header.size) - sizeof(struct SearchMessage); + if (0 != msize % sizeof(struct GNUNET_HashCode)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -820,8 +812,8 @@ check_client_start_search (void *cls, * @param sm the actual message */ static void -handle_client_start_search (void *cls, - const struct SearchMessage *sm) +handle_client_start_search(void *cls, + const struct SearchMessage *sm) { static struct GNUNET_PeerIdentity all_zeros; struct GSF_LocalClient *lc = cls; @@ -832,90 +824,90 @@ handle_client_start_search (void *cls, enum GNUNET_BLOCK_Type type; enum GSF_PendingRequestOptions options; - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# client searches received"), - 1, - GNUNET_NO); - msize = ntohs (sm->header.size) - sizeof (struct SearchMessage); - sc = msize / sizeof (struct GNUNET_HashCode); - type = ntohl (sm->type); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received request for `%s' of type %u from local client\n", - GNUNET_h2s (&sm->query), - (unsigned int) type); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# client searches received"), + 1, + GNUNET_NO); + msize = ntohs(sm->header.size) - sizeof(struct SearchMessage); + sc = msize / sizeof(struct GNUNET_HashCode); + type = ntohl(sm->type); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received request for `%s' of type %u from local client\n", + GNUNET_h2s(&sm->query), + (unsigned int)type); cr = NULL; /* detect duplicate UBLOCK requests */ if ((type == GNUNET_BLOCK_TYPE_FS_UBLOCK) || (type == GNUNET_BLOCK_TYPE_ANY)) - { - cr = lc->cr_head; - while (NULL != cr) { - prd = GSF_pending_request_get_data_ (cr->pr); - /* only unify with queries that hae not yet started local processing - (SEARCH_MESSAGE_OPTION_CONTINUED was always set) and that have a - matching query and type */ - if ((GNUNET_YES != prd->has_started) && - (0 != memcmp (&prd->query, - &sm->query, - sizeof (struct GNUNET_HashCode))) && - (prd->type == type)) - break; - cr = cr->next; + cr = lc->cr_head; + while (NULL != cr) + { + prd = GSF_pending_request_get_data_(cr->pr); + /* only unify with queries that hae not yet started local processing + (SEARCH_MESSAGE_OPTION_CONTINUED was always set) and that have a + matching query and type */ + if ((GNUNET_YES != prd->has_started) && + (0 != memcmp(&prd->query, + &sm->query, + sizeof(struct GNUNET_HashCode))) && + (prd->type == type)) + break; + cr = cr->next; + } } - } if (NULL != cr) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Have existing request, merging content-seen lists.\n"); - GSF_pending_request_update_ (cr->pr, - (const struct GNUNET_HashCode *) &sm[1], - sc); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# client searches updated (merged content seen list)"), - 1, - GNUNET_NO); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Have existing request, merging content-seen lists.\n"); + GSF_pending_request_update_(cr->pr, + (const struct GNUNET_HashCode *)&sm[1], + sc); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# client searches updated (merged content seen list)"), + 1, + GNUNET_NO); + } else - { - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# client searches active"), - 1, - GNUNET_NO); - cr = GNUNET_new (struct ClientRequest); - cr->lc = lc; - GNUNET_CONTAINER_DLL_insert (lc->cr_head, - lc->cr_tail, - cr); - options = GSF_PRO_LOCAL_REQUEST; - if (0 != (SEARCH_MESSAGE_OPTION_LOOPBACK_ONLY & ntohl (sm->options))) - options |= GSF_PRO_LOCAL_ONLY; - cr->pr = GSF_pending_request_create_ (options, type, - &sm->query, - (0 != - memcmp (&sm->target, + { + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# client searches active"), + 1, + GNUNET_NO); + cr = GNUNET_new(struct ClientRequest); + cr->lc = lc; + GNUNET_CONTAINER_DLL_insert(lc->cr_head, + lc->cr_tail, + cr); + options = GSF_PRO_LOCAL_REQUEST; + if (0 != (SEARCH_MESSAGE_OPTION_LOOPBACK_ONLY & ntohl(sm->options))) + options |= GSF_PRO_LOCAL_ONLY; + cr->pr = GSF_pending_request_create_(options, type, + &sm->query, + (0 != + memcmp(&sm->target, &all_zeros, - sizeof (struct GNUNET_PeerIdentity))) - ? &sm->target : NULL, NULL, 0, - 0 /* bf */ , - ntohl (sm->anonymity_level), - 0 /* priority */ , - 0 /* ttl */ , - 0 /* sender PID */ , - 0 /* origin PID */ , - (const struct GNUNET_HashCode *) &sm[1], sc, - &client_response_handler, - cr); - } - if (0 != (SEARCH_MESSAGE_OPTION_CONTINUED & ntohl (sm->options))) - { - GNUNET_SERVICE_client_continue (lc->client); - return; - } - GSF_pending_request_get_data_ (cr->pr)->has_started = GNUNET_YES; - GSF_local_lookup_ (cr->pr, - &start_p2p_processing, - lc); + sizeof(struct GNUNET_PeerIdentity))) + ? &sm->target : NULL, NULL, 0, + 0 /* bf */, + ntohl(sm->anonymity_level), + 0 /* priority */, + 0 /* ttl */, + 0 /* sender PID */, + 0 /* origin PID */, + (const struct GNUNET_HashCode *)&sm[1], sc, + &client_response_handler, + cr); + } + if (0 != (SEARCH_MESSAGE_OPTION_CONTINUED & ntohl(sm->options))) + { + GNUNET_SERVICE_client_continue(lc->client); + return; + } + GSF_pending_request_get_data_(cr->pr)->has_started = GNUNET_YES; + GSF_local_lookup_(cr->pr, + &start_p2p_processing, + lc); } @@ -926,8 +918,8 @@ handle_client_start_search (void *cls, * @param msg the actual message */ static void -handle_client_loc_sign (void *cls, - const struct RequestLocSignatureMessage *msg) +handle_client_loc_sign(void *cls, + const struct RequestLocSignatureMessage *msg) { struct GSF_LocalClient *lc = cls; struct GNUNET_FS_Uri base; @@ -935,24 +927,24 @@ handle_client_loc_sign (void *cls, struct GNUNET_MQ_Envelope *env; struct ResponseLocSignatureMessage *resp; - GNUNET_break (GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT == - ntohl (msg->purpose)); + GNUNET_break(GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT == + ntohl(msg->purpose)); base.type = GNUNET_FS_URI_CHK; base.data.chk.chk = msg->chk; - base.data.chk.file_length = GNUNET_ntohll (msg->file_length); - loc = GNUNET_FS_uri_loc_create (&base, - pk, - GNUNET_TIME_absolute_ntoh (msg->expiration_time)); - env = GNUNET_MQ_msg (resp, - GNUNET_MESSAGE_TYPE_FS_REQUEST_LOC_SIGNATURE); - resp->purpose = htonl (GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT); - resp->expiration_time = GNUNET_TIME_absolute_hton (loc->data.loc.expirationTime); + base.data.chk.file_length = GNUNET_ntohll(msg->file_length); + loc = GNUNET_FS_uri_loc_create(&base, + pk, + GNUNET_TIME_absolute_ntoh(msg->expiration_time)); + env = GNUNET_MQ_msg(resp, + GNUNET_MESSAGE_TYPE_FS_REQUEST_LOC_SIGNATURE); + resp->purpose = htonl(GNUNET_SIGNATURE_PURPOSE_PEER_PLACEMENT); + resp->expiration_time = GNUNET_TIME_absolute_hton(loc->data.loc.expirationTime); resp->signature = loc->data.loc.contentSignature; resp->peer = loc->data.loc.peer; - GNUNET_FS_uri_destroy (loc); - GNUNET_MQ_send (lc->mq, - env); - GNUNET_SERVICE_client_continue (lc->client); + GNUNET_FS_uri_destroy(loc); + GNUNET_MQ_send(lc->mq, + env); + GNUNET_SERVICE_client_continue(lc->client); } @@ -964,24 +956,24 @@ handle_client_loc_sign (void *cls, * @return #GNUNET_OK if @a ism is well-formed */ static int -check_client_index_start (void *cls, - const struct IndexStartMessage *ism) +check_client_index_start(void *cls, + const struct IndexStartMessage *ism) { char *fn; - GNUNET_MQ_check_zero_termination (ism); + GNUNET_MQ_check_zero_termination(ism); if (0 != ism->reserved) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - fn = GNUNET_STRINGS_filename_expand ((const char *) &ism[1]); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + fn = GNUNET_STRINGS_filename_expand((const char *)&ism[1]); if (NULL == fn) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - GNUNET_free (fn); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + GNUNET_free(fn); return GNUNET_OK; } @@ -993,21 +985,21 @@ check_client_index_start (void *cls, * @param isc the data about the index info entry for the request */ static void -signal_index_ok (struct IndexStartContext *isc) +signal_index_ok(struct IndexStartContext *isc) { struct GSF_LocalClient *lc = isc->lc; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; - GNUNET_FS_add_to_index (isc->filename, - &isc->file_id); - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK); - GNUNET_MQ_send (lc->mq, - env); - GNUNET_free (isc->filename); - GNUNET_free (isc); - GNUNET_SERVICE_client_continue (lc->client); + GNUNET_FS_add_to_index(isc->filename, + &isc->file_id); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK); + GNUNET_MQ_send(lc->mq, + env); + GNUNET_free(isc->filename); + GNUNET_free(isc); + GNUNET_SERVICE_client_continue(lc->client); } @@ -1019,36 +1011,36 @@ signal_index_ok (struct IndexStartContext *isc) * @param res resulting hash, NULL on error */ static void -hash_for_index_val (void *cls, - const struct GNUNET_HashCode *res) +hash_for_index_val(void *cls, + const struct GNUNET_HashCode *res) { struct IndexStartContext *isc = cls; struct GSF_LocalClient *lc = isc->lc; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; - GNUNET_CONTAINER_DLL_remove (lc->isc_head, - lc->isc_tail, - isc); + GNUNET_CONTAINER_DLL_remove(lc->isc_head, + lc->isc_tail, + isc); isc->fhc = NULL; - if ( (NULL == res) || - (0 != memcmp (res, - &isc->file_id, - sizeof (struct GNUNET_HashCode)))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Hash mismatch trying to index file `%s' which does not have hash `%s'\n"), - isc->filename, - GNUNET_h2s (&isc->file_id)); - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_FS_INDEX_START_FAILED); - GNUNET_MQ_send (lc->mq, - env); - GNUNET_SERVICE_client_continue (lc->client); - GNUNET_free (isc); - return; - } - signal_index_ok (isc); + if ((NULL == res) || + (0 != memcmp(res, + &isc->file_id, + sizeof(struct GNUNET_HashCode)))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Hash mismatch trying to index file `%s' which does not have hash `%s'\n"), + isc->filename, + GNUNET_h2s(&isc->file_id)); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_FS_INDEX_START_FAILED); + GNUNET_MQ_send(lc->mq, + env); + GNUNET_SERVICE_client_continue(lc->client); + GNUNET_free(isc); + return; + } + signal_index_ok(isc); } @@ -1059,8 +1051,8 @@ hash_for_index_val (void *cls, * @param message the actual message */ static void -handle_client_index_start (void *cls, - const struct IndexStartMessage *ism) +handle_client_index_start(void *cls, + const struct IndexStartMessage *ism) { struct GSF_LocalClient *lc = cls; struct IndexStartContext *isc; @@ -1070,49 +1062,49 @@ handle_client_index_start (void *cls, uint64_t mydev; uint64_t myino; - fn = GNUNET_STRINGS_filename_expand ((const char *) &ism[1]); - GNUNET_assert (NULL != fn); - dev = GNUNET_ntohll (ism->device); - ino = GNUNET_ntohll (ism->inode); - isc = GNUNET_new (struct IndexStartContext); + fn = GNUNET_STRINGS_filename_expand((const char *)&ism[1]); + GNUNET_assert(NULL != fn); + dev = GNUNET_ntohll(ism->device); + ino = GNUNET_ntohll(ism->inode); + isc = GNUNET_new(struct IndexStartContext); isc->filename = fn; isc->file_id = ism->file_id; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received START_INDEX message for file `%s'\n", - isc->filename); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received START_INDEX message for file `%s'\n", + isc->filename); isc->lc = lc; mydev = 0; myino = 0; - if ( ( (dev != 0) || - (ino != 0) ) && - (GNUNET_OK == GNUNET_DISK_file_get_identifiers (fn, - &mydev, - &myino)) && - (dev == mydev) && - (ino == myino) ) - { - /* fast validation OK! */ - signal_index_ok (isc); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Mismatch in file identifiers (%llu != %llu or %u != %u), need to hash.\n", - (unsigned long long) ino, - (unsigned long long) myino, - (unsigned int) dev, - (unsigned int) mydev); + if (((dev != 0) || + (ino != 0)) && + (GNUNET_OK == GNUNET_DISK_file_get_identifiers(fn, + &mydev, + &myino)) && + (dev == mydev) && + (ino == myino)) + { + /* fast validation OK! */ + signal_index_ok(isc); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Mismatch in file identifiers (%llu != %llu or %u != %u), need to hash.\n", + (unsigned long long)ino, + (unsigned long long)myino, + (unsigned int)dev, + (unsigned int)mydev); /* slow validation, need to hash full file (again) */ - GNUNET_CONTAINER_DLL_insert (lc->isc_head, - lc->isc_tail, - isc); - isc->fhc = GNUNET_CRYPTO_hash_file (GNUNET_SCHEDULER_PRIORITY_IDLE, - isc->filename, - HASHING_BLOCKSIZE, - &hash_for_index_val, - isc); + GNUNET_CONTAINER_DLL_insert(lc->isc_head, + lc->isc_tail, + isc); + isc->fhc = GNUNET_CRYPTO_hash_file(GNUNET_SCHEDULER_PRIORITY_IDLE, + isc->filename, + HASHING_BLOCKSIZE, + &hash_for_index_val, + isc); if (NULL == isc->fhc) - hash_for_index_val (isc, - NULL); + hash_for_index_val(isc, + NULL); } @@ -1123,13 +1115,13 @@ handle_client_index_start (void *cls, * @param message the actual message */ static void -handle_client_index_list_get (void *cls, - const struct GNUNET_MessageHeader *message) +handle_client_index_list_get(void *cls, + const struct GNUNET_MessageHeader *message) { struct GSF_LocalClient *lc = cls; - GNUNET_FS_indexing_send_list (lc->mq); - GNUNET_SERVICE_client_continue (lc->client); + GNUNET_FS_indexing_send_list(lc->mq); + GNUNET_SERVICE_client_continue(lc->client); } @@ -1140,25 +1132,25 @@ handle_client_index_list_get (void *cls, * @param message the actual message */ static void -handle_client_unindex (void *cls, - const struct UnindexMessage *um) +handle_client_unindex(void *cls, + const struct UnindexMessage *um) { struct GSF_LocalClient *lc = cls; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; int found; - GNUNET_break (0 == um->reserved); - found = GNUNET_FS_indexing_do_unindex (&um->file_id); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Client requested unindexing of file `%s': %s\n", - GNUNET_h2s (&um->file_id), - found ? "found" : "not found"); - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK); - GNUNET_MQ_send (lc->mq, - env); - GNUNET_SERVICE_client_continue (lc->client); + GNUNET_break(0 == um->reserved); + found = GNUNET_FS_indexing_do_unindex(&um->file_id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Client requested unindexing of file `%s': %s\n", + GNUNET_h2s(&um->file_id), + found ? "found" : "not found"); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK); + GNUNET_MQ_send(lc->mq, + env); + GNUNET_SERVICE_client_continue(lc->client); } @@ -1168,44 +1160,44 @@ handle_client_unindex (void *cls, * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - GSF_cadet_stop_server (); + GSF_cadet_stop_server(); if (NULL != GSF_core) - { - GNUNET_CORE_disconnect (GSF_core); - GSF_core = NULL; - } + { + GNUNET_CORE_disconnect(GSF_core); + GSF_core = NULL; + } if (NULL != GSF_ats) - { - GNUNET_ATS_performance_done (GSF_ats); - GSF_ats = NULL; - } - GSF_put_done_ (); - GSF_push_done_ (); - GSF_pending_request_done_ (); - GSF_plan_done (); - GSF_connected_peer_done_ (); - GNUNET_DATASTORE_disconnect (GSF_dsh, - GNUNET_NO); + { + GNUNET_ATS_performance_done(GSF_ats); + GSF_ats = NULL; + } + GSF_put_done_(); + GSF_push_done_(); + GSF_pending_request_done_(); + GSF_plan_done(); + GSF_connected_peer_done_(); + GNUNET_DATASTORE_disconnect(GSF_dsh, + GNUNET_NO); GSF_dsh = NULL; - GNUNET_DHT_disconnect (GSF_dht); + GNUNET_DHT_disconnect(GSF_dht); GSF_dht = NULL; - GNUNET_BLOCK_context_destroy (GSF_block_ctx); + GNUNET_BLOCK_context_destroy(GSF_block_ctx); GSF_block_ctx = NULL; - GNUNET_CONFIGURATION_destroy (block_cfg); + GNUNET_CONFIGURATION_destroy(block_cfg); block_cfg = NULL; - GNUNET_STATISTICS_destroy (GSF_stats, GNUNET_NO); + GNUNET_STATISTICS_destroy(GSF_stats, GNUNET_NO); GSF_stats = NULL; if (NULL != cover_age_task) - { - GNUNET_SCHEDULER_cancel (cover_age_task); - cover_age_task = NULL; - } - GNUNET_FS_indexing_done (); - GNUNET_LOAD_value_free (datastore_get_load); + { + GNUNET_SCHEDULER_cancel(cover_age_task); + cover_age_task = NULL; + } + GNUNET_FS_indexing_done(); + GNUNET_LOAD_value_free(datastore_get_load); datastore_get_load = NULL; - GNUNET_LOAD_value_free (GSF_rt_entry_lifetime); + GNUNET_LOAD_value_free(GSF_rt_entry_lifetime); GSF_rt_entry_lifetime = NULL; } @@ -1221,16 +1213,16 @@ shutdown_task (void *cls) * @param my_identity ID of this peer, NULL if we failed */ static void -peer_init_handler (void *cls, - const struct GNUNET_PeerIdentity *my_identity) +peer_init_handler(void *cls, + const struct GNUNET_PeerIdentity *my_identity) { - if (0 != GNUNET_memcmp (&GSF_my_id, - my_identity)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Peer identity mismatch, refusing to start!\n"); - GNUNET_SCHEDULER_shutdown (); - } + if (0 != GNUNET_memcmp(&GSF_my_id, + my_identity)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Peer identity mismatch, refusing to start!\n"); + GNUNET_SCHEDULER_shutdown(); + } } @@ -1240,25 +1232,25 @@ peer_init_handler (void *cls, * @param c configuration to use */ static int -main_init (const struct GNUNET_CONFIGURATION_Handle *c) +main_init(const struct GNUNET_CONFIGURATION_Handle *c) { struct GNUNET_MQ_MessageHandler no_p2p_handlers[] = { - GNUNET_MQ_handler_end () + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_MessageHandler p2p_handlers[] = { - GNUNET_MQ_hd_var_size (p2p_get, - GNUNET_MESSAGE_TYPE_FS_GET, - struct GetMessage, - NULL), - GNUNET_MQ_hd_var_size (p2p_put, - GNUNET_MESSAGE_TYPE_FS_PUT, - struct PutMessage, - NULL), - GNUNET_MQ_hd_fixed_size (p2p_migration_stop, - GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP, - struct MigrationStopMessage, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(p2p_get, + GNUNET_MESSAGE_TYPE_FS_GET, + struct GetMessage, + NULL), + GNUNET_MQ_hd_var_size(p2p_put, + GNUNET_MESSAGE_TYPE_FS_PUT, + struct PutMessage, + NULL), + GNUNET_MQ_hd_fixed_size(p2p_migration_stop, + GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP, + struct MigrationStopMessage, + NULL), + GNUNET_MQ_handler_end() }; int anon_p2p_off; char *keyfile; @@ -1266,54 +1258,54 @@ main_init (const struct GNUNET_CONFIGURATION_Handle *c) /* this option is really only for testcases that need to disable _anonymous_ file-sharing for some reason */ anon_p2p_off = (GNUNET_YES == - GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, - "fs", - "DISABLE_ANON_TRANSFER")); + GNUNET_CONFIGURATION_get_value_yesno(GSF_cfg, + "fs", + "DISABLE_ANON_TRANSFER")); if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (GSF_cfg, - "PEER", - "PRIVATE_KEY", - &keyfile)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("FS service is lacking HOSTKEY configuration setting. Exiting.\n")); - GNUNET_SCHEDULER_shutdown (); - return GNUNET_SYSERR; - } - pk = GNUNET_CRYPTO_eddsa_key_create_from_file (keyfile); - GNUNET_free (keyfile); - GNUNET_assert (NULL != pk); - GNUNET_CRYPTO_eddsa_key_get_public (pk, - &GSF_my_id.public_key); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "I am peer %s\n", - GNUNET_i2s (&GSF_my_id)); + GNUNET_CONFIGURATION_get_value_filename(GSF_cfg, + "PEER", + "PRIVATE_KEY", + &keyfile)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("FS service is lacking HOSTKEY configuration setting. Exiting.\n")); + GNUNET_SCHEDULER_shutdown(); + return GNUNET_SYSERR; + } + pk = GNUNET_CRYPTO_eddsa_key_create_from_file(keyfile); + GNUNET_free(keyfile); + GNUNET_assert(NULL != pk); + GNUNET_CRYPTO_eddsa_key_get_public(pk, + &GSF_my_id.public_key); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "I am peer %s\n", + GNUNET_i2s(&GSF_my_id)); GSF_core - = GNUNET_CORE_connect (GSF_cfg, - NULL, - &peer_init_handler, - &GSF_peer_connect_handler, - &GSF_peer_disconnect_handler, - (GNUNET_YES == anon_p2p_off) - ? no_p2p_handlers - : p2p_handlers); + = GNUNET_CORE_connect(GSF_cfg, + NULL, + &peer_init_handler, + &GSF_peer_connect_handler, + &GSF_peer_disconnect_handler, + (GNUNET_YES == anon_p2p_off) + ? no_p2p_handlers + : p2p_handlers); if (NULL == GSF_core) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect to `%s' service.\n"), - "core"); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to `%s' service.\n"), + "core"); + return GNUNET_SYSERR; + } cover_age_task = - GNUNET_SCHEDULER_add_delayed (COVER_AGE_FREQUENCY, - &age_cover_counters, - NULL); - datastore_get_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE); - GSF_cadet_start_server (); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); + GNUNET_SCHEDULER_add_delayed(COVER_AGE_FREQUENCY, + &age_cover_counters, + NULL); + datastore_get_load = GNUNET_LOAD_value_init(DATASTORE_LOAD_AUTODECLINE); + GSF_cadet_start_server(); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); return GNUNET_OK; } @@ -1326,55 +1318,55 @@ main_init (const struct GNUNET_CONFIGURATION_Handle *c) * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_SERVICE_Handle *service) { unsigned long long dqs; GSF_cfg = cfg; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_size (GSF_cfg, - "fs", - "DATASTORE_QUEUE_SIZE", - &dqs)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO, - "fs", - "DATASTORE_QUEUE_SIZE"); - dqs = 32; - } - GSF_datastore_queue_size = (unsigned int) dqs; + GNUNET_CONFIGURATION_get_value_size(GSF_cfg, + "fs", + "DATASTORE_QUEUE_SIZE", + &dqs)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_INFO, + "fs", + "DATASTORE_QUEUE_SIZE"); + dqs = 32; + } + GSF_datastore_queue_size = (unsigned int)dqs; GSF_enable_randomized_delays = - GNUNET_CONFIGURATION_get_value_yesno (cfg, "fs", "DELAY"); - GSF_dsh = GNUNET_DATASTORE_connect (cfg); + GNUNET_CONFIGURATION_get_value_yesno(cfg, "fs", "DELAY"); + GSF_dsh = GNUNET_DATASTORE_connect(cfg); if (NULL == GSF_dsh) - { - GNUNET_SCHEDULER_shutdown (); - return; - } - GSF_rt_entry_lifetime = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_FOREVER_REL); - GSF_stats = GNUNET_STATISTICS_create ("fs", cfg); - block_cfg = GNUNET_CONFIGURATION_create (); - GSF_block_ctx = GNUNET_BLOCK_context_create (block_cfg); - GNUNET_assert (NULL != GSF_block_ctx); - GSF_dht = GNUNET_DHT_connect (cfg, FS_DHT_HT_SIZE); - GSF_plan_init (); - GSF_pending_request_init_ (); - GSF_connected_peer_init_ (); - GSF_ats = GNUNET_ATS_performance_init (GSF_cfg, - &update_latencies, - NULL); - GSF_push_init_ (); - GSF_put_init_ (); - if ( (GNUNET_OK != GNUNET_FS_indexing_init (cfg, - GSF_dsh)) || - (GNUNET_OK != main_init (cfg)) ) - { - GNUNET_SCHEDULER_shutdown (); - shutdown_task (NULL); - return; - } + { + GNUNET_SCHEDULER_shutdown(); + return; + } + GSF_rt_entry_lifetime = GNUNET_LOAD_value_init(GNUNET_TIME_UNIT_FOREVER_REL); + GSF_stats = GNUNET_STATISTICS_create("fs", cfg); + block_cfg = GNUNET_CONFIGURATION_create(); + GSF_block_ctx = GNUNET_BLOCK_context_create(block_cfg); + GNUNET_assert(NULL != GSF_block_ctx); + GSF_dht = GNUNET_DHT_connect(cfg, FS_DHT_HT_SIZE); + GSF_plan_init(); + GSF_pending_request_init_(); + GSF_connected_peer_init_(); + GSF_ats = GNUNET_ATS_performance_init(GSF_cfg, + &update_latencies, + NULL); + GSF_push_init_(); + GSF_put_init_(); + if ((GNUNET_OK != GNUNET_FS_indexing_init(cfg, + GSF_dsh)) || + (GNUNET_OK != main_init(cfg))) + { + GNUNET_SCHEDULER_shutdown(); + shutdown_task(NULL); + return; + } } @@ -1382,33 +1374,33 @@ run (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("fs", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_var_size (client_index_start, + ("fs", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_var_size(client_index_start, GNUNET_MESSAGE_TYPE_FS_INDEX_START, struct IndexStartMessage, NULL), - GNUNET_MQ_hd_fixed_size (client_index_list_get, - GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_hd_fixed_size (client_unindex, - GNUNET_MESSAGE_TYPE_FS_UNINDEX, - struct UnindexMessage, - NULL), - GNUNET_MQ_hd_var_size (client_start_search, + GNUNET_MQ_hd_fixed_size(client_index_list_get, + GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_hd_fixed_size(client_unindex, + GNUNET_MESSAGE_TYPE_FS_UNINDEX, + struct UnindexMessage, + NULL), + GNUNET_MQ_hd_var_size(client_start_search, GNUNET_MESSAGE_TYPE_FS_START_SEARCH, struct SearchMessage, NULL), - GNUNET_MQ_hd_fixed_size (client_loc_sign, - GNUNET_MESSAGE_TYPE_FS_REQUEST_LOC_SIGN, - struct RequestLocSignatureMessage, - NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_hd_fixed_size(client_loc_sign, + GNUNET_MESSAGE_TYPE_FS_REQUEST_LOC_SIGN, + struct RequestLocSignatureMessage, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-fs.c */ diff --git a/src/fs/gnunet-service-fs.h b/src/fs/gnunet-service-fs.h index 661126f08..21a822c6d 100644 --- a/src/fs/gnunet-service-fs.h +++ b/src/fs/gnunet-service-fs.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs.h @@ -48,7 +48,7 @@ * automatically (since if we don't use it, clearly the * load must be going down). */ -#define DATASTORE_LOAD_AUTODECLINE GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250) +#define DATASTORE_LOAD_AUTODECLINE GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250) /** * Only the (mandatory) query is included. @@ -79,9 +79,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Message sent between peers asking for FS-content. */ -struct GetMessage -{ - +struct GetMessage { /** * Message type will be #GNUNET_MESSAGE_TYPE_FS_GET. */ @@ -136,8 +134,7 @@ struct GetMessage * Message send by a peer that wants to be excluded * from migration for a while. */ -struct MigrationStopMessage -{ +struct MigrationStopMessage { /** * Message type will be * GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP. @@ -153,7 +150,6 @@ struct MigrationStopMessage * How long should the block last? */ struct GNUNET_TIME_RelativeNBO duration; - }; GNUNET_NETWORK_STRUCT_END @@ -279,9 +275,9 @@ extern unsigned int GSF_datastore_queue_size; * @param result final datastore lookup result */ void -GSF_consider_forwarding (void *cls, - struct GSF_PendingRequest *pr, - enum GNUNET_BLOCK_EvaluationResult result); +GSF_consider_forwarding(void *cls, + struct GSF_PendingRequest *pr, + enum GNUNET_BLOCK_EvaluationResult result); /** @@ -294,7 +290,7 @@ GSF_consider_forwarding (void *cls, * #GNUNET_SYSERR to process for free (load low) */ int -GSF_test_get_load_too_high_ (uint32_t priority); +GSF_test_get_load_too_high_(uint32_t priority); /** @@ -304,7 +300,7 @@ GSF_test_get_load_too_high_ (uint32_t priority); * @param start time when the datastore request was issued */ void -GSF_update_datastore_delay_ (struct GNUNET_TIME_Absolute start); +GSF_update_datastore_delay_(struct GNUNET_TIME_Absolute start); #endif diff --git a/src/fs/gnunet-service-fs_cadet.h b/src/fs/gnunet-service-fs_cadet.h index 728faaf27..61bd8b314 100644 --- a/src/fs/gnunet-service-fs_cadet.h +++ b/src/fs/gnunet-service-fs_cadet.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_cadet.h @@ -60,11 +60,11 @@ typedef void * @return handle to cancel the operation */ struct GSF_CadetRequest * -GSF_cadet_query (const struct GNUNET_PeerIdentity *target, - const struct GNUNET_HashCode *query, - enum GNUNET_BLOCK_Type type, - GSF_CadetReplyProcessor proc, - void *proc_cls); +GSF_cadet_query(const struct GNUNET_PeerIdentity *target, + const struct GNUNET_HashCode *query, + enum GNUNET_BLOCK_Type type, + GSF_CadetReplyProcessor proc, + void *proc_cls); /** * Function called on each active cadets to shut them down. @@ -75,9 +75,9 @@ GSF_cadet_query (const struct GNUNET_PeerIdentity *target, * @return #GNUNET_YES (continue to iterate) */ int -GSF_cadet_release_clients (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value); +GSF_cadet_release_clients(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value); /** @@ -87,21 +87,21 @@ GSF_cadet_release_clients (void *cls, * @param sr request to cancel */ void -GSF_cadet_query_cancel (struct GSF_CadetRequest *sr); +GSF_cadet_query_cancel(struct GSF_CadetRequest *sr); /** * Initialize subsystem for non-anonymous file-sharing. */ void -GSF_cadet_start_server (void); +GSF_cadet_start_server(void); /** * Shutdown subsystem for non-anonymous file-sharing. */ void -GSF_cadet_stop_server (void); +GSF_cadet_stop_server(void); /** * Cadet channel for creating outbound channels. @@ -120,9 +120,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Query from one peer, asking the other for CHK-data. */ -struct CadetQueryMessage -{ - +struct CadetQueryMessage { /** * Type is GNUNET_MESSAGE_TYPE_FS_CADET_QUERY. */ @@ -137,16 +135,13 @@ struct CadetQueryMessage * Query hash from CHK (hash of encrypted block). */ struct GNUNET_HashCode query; - }; /** * Reply to a CadetQueryMessage. */ -struct CadetReplyMessage -{ - +struct CadetReplyMessage { /** * Type is GNUNET_MESSAGE_TYPE_FS_CADET_REPLY. */ @@ -163,7 +158,6 @@ struct CadetReplyMessage struct GNUNET_TIME_AbsoluteNBO expiration; /* followed by the encrypted block */ - }; GNUNET_NETWORK_STRUCT_END diff --git a/src/fs/gnunet-service-fs_cadet_client.c b/src/fs/gnunet-service-fs_cadet_client.c index 81afe0411..a494ba751 100644 --- a/src/fs/gnunet-service-fs_cadet_client.c +++ b/src/fs/gnunet-service-fs_cadet_client.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_cadet_client.c @@ -42,7 +42,7 @@ * After how long do we reset connections without replies? */ #define CLIENT_RETRY_TIMEOUT \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30) /** @@ -54,9 +54,7 @@ struct CadetHandle; /** * Handle for a request that is going out via cadet API. */ -struct GSF_CadetRequest -{ - +struct GSF_CadetRequest { /** * DLL. */ @@ -103,8 +101,7 @@ struct GSF_CadetRequest /** * Handle for a cadet to another peer. */ -struct CadetHandle -{ +struct CadetHandle { /** * Head of DLL of pending requests on this cadet. */ @@ -168,7 +165,7 @@ struct GNUNET_CONTAINER_MultiPeerMap *cadet_map; * @param cls `struct CadetHandle` to process */ static void -transmit_pending (void *cls); +transmit_pending(void *cls); /** @@ -181,15 +178,15 @@ transmit_pending (void *cls); * @return #GNUNET_YES (continue to iterate) */ static int -move_to_pending (void *cls, const struct GNUNET_HashCode *key, void *value) +move_to_pending(void *cls, const struct GNUNET_HashCode *key, void *value) { struct CadetHandle *mh = cls; struct GSF_CadetRequest *sr = value; - GNUNET_assert ( + GNUNET_assert( GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (mh->waiting_map, key, value)); - GNUNET_CONTAINER_DLL_insert (mh->pending_head, mh->pending_tail, sr); + GNUNET_CONTAINER_multihashmap_remove(mh->waiting_map, key, value)); + GNUNET_CONTAINER_DLL_insert(mh->pending_head, mh->pending_tail, sr); sr->was_transmitted = GNUNET_NO; return GNUNET_YES; } @@ -204,7 +201,7 @@ move_to_pending (void *cls, const struct GNUNET_HashCode *key, void *value) * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing */ static int -check_reply (void *cls, const struct CadetReplyMessage *srm) +check_reply(void *cls, const struct CadetReplyMessage *srm) { /* We check later... */ return GNUNET_OK; @@ -217,7 +214,7 @@ check_reply (void *cls, const struct CadetReplyMessage *srm) * @param cls the `struct CadetHandle` to tear down */ static void -reset_cadet_task (void *cls); +reset_cadet_task(void *cls); /** @@ -227,20 +224,18 @@ reset_cadet_task (void *cls); * @param mh cadet to reset */ static void -reset_cadet_async (struct CadetHandle *mh) +reset_cadet_async(struct CadetHandle *mh) { if (NULL != mh->reset_task) - GNUNET_SCHEDULER_cancel (mh->reset_task); - mh->reset_task = GNUNET_SCHEDULER_add_now (&reset_cadet_task, mh); + GNUNET_SCHEDULER_cancel(mh->reset_task); + mh->reset_task = GNUNET_SCHEDULER_add_now(&reset_cadet_task, mh); } /** * Closure for handle_reply(). */ -struct HandleReplyClosure -{ - +struct HandleReplyClosure { /** * Reply payload. */ @@ -278,18 +273,18 @@ struct HandleReplyClosure * @return #GNUNET_YES (continue to iterate) */ static int -process_reply (void *cls, const struct GNUNET_HashCode *key, void *value) +process_reply(void *cls, const struct GNUNET_HashCode *key, void *value) { struct HandleReplyClosure *hrc = cls; struct GSF_CadetRequest *sr = value; - sr->proc (sr->proc_cls, - hrc->type, - hrc->expiration, - hrc->data_size, - hrc->data); + sr->proc(sr->proc_cls, + hrc->type, + hrc->expiration, + hrc->data_size, + hrc->data); sr->proc = NULL; - GSF_cadet_query_cancel (sr); + GSF_cadet_query_cancel(sr); hrc->found = GNUNET_YES; return GNUNET_YES; } @@ -306,11 +301,11 @@ process_reply (void *cls, const struct GNUNET_HashCode *key, void *value) * @return #GNUNET_YES (continue to iterate) */ static int -free_waiting_entry (void *cls, const struct GNUNET_HashCode *key, void *value) +free_waiting_entry(void *cls, const struct GNUNET_HashCode *key, void *value) { struct GSF_CadetRequest *sr = value; - GSF_cadet_query_cancel (sr); + GSF_cadet_query_cancel(sr); return GNUNET_YES; } @@ -323,7 +318,7 @@ free_waiting_entry (void *cls, const struct GNUNET_HashCode *key, void *value) * @param srm the actual message */ static void -handle_reply (void *cls, const struct CadetReplyMessage *srm) +handle_reply(void *cls, const struct CadetReplyMessage *srm) { struct CadetHandle *mh = cls; struct HandleReplyClosure hrc; @@ -331,47 +326,47 @@ handle_reply (void *cls, const struct CadetReplyMessage *srm) enum GNUNET_BLOCK_Type type; struct GNUNET_HashCode query; - msize = ntohs (srm->header.size) - sizeof (struct CadetReplyMessage); - type = (enum GNUNET_BLOCK_Type) ntohl (srm->type); + msize = ntohs(srm->header.size) - sizeof(struct CadetReplyMessage); + type = (enum GNUNET_BLOCK_Type)ntohl(srm->type); if (GNUNET_YES != - GNUNET_BLOCK_get_key (GSF_block_ctx, type, &srm[1], msize, &query)) - { - GNUNET_break_op (0); - GNUNET_log ( - GNUNET_ERROR_TYPE_WARNING, - "Received bogus reply of type %u with %u bytes via cadet from peer %s\n", - type, - msize, - GNUNET_i2s (&mh->target)); - reset_cadet_async (mh); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received reply `%s' via cadet from peer %s\n", - GNUNET_h2s (&query), - GNUNET_i2s (&mh->target)); - GNUNET_CADET_receive_done (mh->channel); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# replies received via cadet"), - 1, - GNUNET_NO); + GNUNET_BLOCK_get_key(GSF_block_ctx, type, &srm[1], msize, &query)) + { + GNUNET_break_op(0); + GNUNET_log( + GNUNET_ERROR_TYPE_WARNING, + "Received bogus reply of type %u with %u bytes via cadet from peer %s\n", + type, + msize, + GNUNET_i2s(&mh->target)); + reset_cadet_async(mh); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received reply `%s' via cadet from peer %s\n", + GNUNET_h2s(&query), + GNUNET_i2s(&mh->target)); + GNUNET_CADET_receive_done(mh->channel); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# replies received via cadet"), + 1, + GNUNET_NO); hrc.data = &srm[1]; hrc.data_size = msize; - hrc.expiration = GNUNET_TIME_absolute_ntoh (srm->expiration); + hrc.expiration = GNUNET_TIME_absolute_ntoh(srm->expiration); hrc.type = type; hrc.found = GNUNET_NO; - GNUNET_CONTAINER_multihashmap_get_multiple (mh->waiting_map, - &query, - &process_reply, - &hrc); + GNUNET_CONTAINER_multihashmap_get_multiple(mh->waiting_map, + &query, + &process_reply, + &hrc); if (GNUNET_NO == hrc.found) - { - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ( - "# replies received via cadet dropped"), - 1, - GNUNET_NO); - } + { + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop( + "# replies received via cadet dropped"), + 1, + GNUNET_NO); + } } @@ -383,34 +378,34 @@ handle_reply (void *cls, const struct CadetReplyMessage *srm) * @param channel channel of the disconnecting client */ static void -disconnect_cb (void *cls, const struct GNUNET_CADET_Channel *channel) +disconnect_cb(void *cls, const struct GNUNET_CADET_Channel *channel) { struct CadetHandle *mh = cls; struct GSF_CadetRequest *sr; if (NULL == mh->channel) return; /* being destroyed elsewhere */ - GNUNET_assert (channel == mh->channel); + GNUNET_assert(channel == mh->channel); mh->channel = NULL; while (NULL != (sr = mh->pending_head)) - GSF_cadet_query_cancel (sr); + GSF_cadet_query_cancel(sr); /* first remove `mh` from the `cadet_map`, so that if the callback from `free_waiting_entry()` happens to re-issue the request, we don't immediately have it back in the `waiting_map`. */ - GNUNET_assert (GNUNET_OK == GNUNET_CONTAINER_multipeermap_remove (cadet_map, - &mh->target, - mh)); - GNUNET_CONTAINER_multihashmap_iterate (mh->waiting_map, - &free_waiting_entry, - mh); + GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multipeermap_remove(cadet_map, + &mh->target, + mh)); + GNUNET_CONTAINER_multihashmap_iterate(mh->waiting_map, + &free_waiting_entry, + mh); if (NULL != mh->timeout_task) - GNUNET_SCHEDULER_cancel (mh->timeout_task); + GNUNET_SCHEDULER_cancel(mh->timeout_task); if (NULL != mh->reset_task) - GNUNET_SCHEDULER_cancel (mh->reset_task); - GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (mh->waiting_map)); - GNUNET_CONTAINER_multihashmap_destroy (mh->waiting_map); - GNUNET_free (mh); + GNUNET_SCHEDULER_cancel(mh->reset_task); + GNUNET_assert(0 == GNUNET_CONTAINER_multihashmap_size(mh->waiting_map)); + GNUNET_CONTAINER_multihashmap_destroy(mh->waiting_map); + GNUNET_free(mh); } @@ -429,16 +424,16 @@ disconnect_cb (void *cls, const struct GNUNET_CADET_Channel *channel) * this value will be negative.. */ static void -window_change_cb (void *cls, - const struct GNUNET_CADET_Channel *channel, - int window_size) +window_change_cb(void *cls, + const struct GNUNET_CADET_Channel *channel, + int window_size) { /* FIXME: for flow control, implement? */ #if 0 /* Something like this instead of the GNUNET_MQ_notify_sent() in transmit_pending() might be good (once the window change CB works...) */ if (0 < window_size) /* test needed? */ - transmit_pending (mh); + transmit_pending(mh); #endif } @@ -449,38 +444,38 @@ window_change_cb (void *cls, * @param mh cadet to reset */ static void -reset_cadet (struct CadetHandle *mh) +reset_cadet(struct CadetHandle *mh) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Resetting cadet channel to %s\n", - GNUNET_i2s (&mh->target)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Resetting cadet channel to %s\n", + GNUNET_i2s(&mh->target)); if (NULL != mh->channel) - { - GNUNET_CADET_channel_destroy (mh->channel); - mh->channel = NULL; - } - GNUNET_CONTAINER_multihashmap_iterate (mh->waiting_map, &move_to_pending, mh); + { + GNUNET_CADET_channel_destroy(mh->channel); + mh->channel = NULL; + } + GNUNET_CONTAINER_multihashmap_iterate(mh->waiting_map, &move_to_pending, mh); { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_var_size (reply, - GNUNET_MESSAGE_TYPE_FS_CADET_REPLY, - struct CadetReplyMessage, - mh), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_var_size(reply, + GNUNET_MESSAGE_TYPE_FS_CADET_REPLY, + struct CadetReplyMessage, + mh), + GNUNET_MQ_handler_end() }; struct GNUNET_HashCode port; - GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER, - strlen (GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER), - &port); - mh->channel = GNUNET_CADET_channel_create (cadet_handle, - mh, - &mh->target, - &port, - &window_change_cb, - &disconnect_cb, - handlers); + GNUNET_CRYPTO_hash(GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER, + strlen(GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER), + &port); + mh->channel = GNUNET_CADET_channel_create(cadet_handle, + mh, + &mh->target, + &port, + &window_change_cb, + &disconnect_cb, + handlers); } - transmit_pending (mh); + transmit_pending(mh); } @@ -490,19 +485,19 @@ reset_cadet (struct CadetHandle *mh) * @param cls the `struct CadetHandle` to tear down */ static void -cadet_timeout (void *cls) +cadet_timeout(void *cls) { struct CadetHandle *mh = cls; struct GNUNET_CADET_Channel *tun; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Timeout on cadet channel to %s\n", - GNUNET_i2s (&mh->target)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Timeout on cadet channel to %s\n", + GNUNET_i2s(&mh->target)); mh->timeout_task = NULL; tun = mh->channel; mh->channel = NULL; if (NULL != tun) - GNUNET_CADET_channel_destroy (tun); + GNUNET_CADET_channel_destroy(tun); } @@ -512,12 +507,12 @@ cadet_timeout (void *cls) * @param cls the `struct CadetHandle` to tear down */ static void -reset_cadet_task (void *cls) +reset_cadet_task(void *cls) { struct CadetHandle *mh = cls; mh->reset_task = NULL; - reset_cadet (mh); + reset_cadet(mh); } @@ -527,36 +522,36 @@ reset_cadet_task (void *cls) * @param cls `struct CadetHandle` to process */ static void -transmit_pending (void *cls) +transmit_pending(void *cls) { struct CadetHandle *mh = cls; - struct GNUNET_MQ_Handle *mq = GNUNET_CADET_get_mq (mh->channel); + struct GNUNET_MQ_Handle *mq = GNUNET_CADET_get_mq(mh->channel); struct GSF_CadetRequest *sr; struct GNUNET_MQ_Envelope *env; struct CadetQueryMessage *sqm; - if ((0 != GNUNET_MQ_get_length (mq)) || (NULL == (sr = mh->pending_head))) + if ((0 != GNUNET_MQ_get_length(mq)) || (NULL == (sr = mh->pending_head))) return; - GNUNET_CONTAINER_DLL_remove (mh->pending_head, mh->pending_tail, sr); - GNUNET_assert (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put ( - mh->waiting_map, - &sr->query, - sr, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); + GNUNET_CONTAINER_DLL_remove(mh->pending_head, mh->pending_tail, sr); + GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put( + mh->waiting_map, + &sr->query, + sr, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); sr->was_transmitted = GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending query for %s via cadet to %s\n", - GNUNET_h2s (&sr->query), - GNUNET_i2s (&mh->target)); - env = GNUNET_MQ_msg (sqm, GNUNET_MESSAGE_TYPE_FS_CADET_QUERY); - GNUNET_MQ_env_set_options (env, - GNUNET_MQ_PREF_GOODPUT | - GNUNET_MQ_PREF_CORK_ALLOWED | - GNUNET_MQ_PREF_OUT_OF_ORDER); - sqm->type = htonl (sr->type); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending query for %s via cadet to %s\n", + GNUNET_h2s(&sr->query), + GNUNET_i2s(&mh->target)); + env = GNUNET_MQ_msg(sqm, GNUNET_MESSAGE_TYPE_FS_CADET_QUERY); + GNUNET_MQ_env_set_options(env, + GNUNET_MQ_PREF_GOODPUT | + GNUNET_MQ_PREF_CORK_ALLOWED | + GNUNET_MQ_PREF_OUT_OF_ORDER); + sqm->type = htonl(sr->type); sqm->query = sr->query; - GNUNET_MQ_notify_sent (env, &transmit_pending, mh); - GNUNET_MQ_send (mq, env); + GNUNET_MQ_notify_sent(env, &transmit_pending, mh); + GNUNET_MQ_send(mq, env); } @@ -566,53 +561,53 @@ transmit_pending (void *cls) * @param target peer we want to communicate with */ static struct CadetHandle * -get_cadet (const struct GNUNET_PeerIdentity *target) +get_cadet(const struct GNUNET_PeerIdentity *target) { struct CadetHandle *mh; - mh = GNUNET_CONTAINER_multipeermap_get (cadet_map, target); + mh = GNUNET_CONTAINER_multipeermap_get(cadet_map, target); if (NULL != mh) - { - if (NULL != mh->timeout_task) { - GNUNET_SCHEDULER_cancel (mh->timeout_task); - mh->timeout_task = NULL; + if (NULL != mh->timeout_task) + { + GNUNET_SCHEDULER_cancel(mh->timeout_task); + mh->timeout_task = NULL; + } + return mh; } - return mh; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Creating cadet channel to %s\n", - GNUNET_i2s (target)); - mh = GNUNET_new (struct CadetHandle); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Creating cadet channel to %s\n", + GNUNET_i2s(target)); + mh = GNUNET_new(struct CadetHandle); mh->reset_task = - GNUNET_SCHEDULER_add_delayed (CLIENT_RETRY_TIMEOUT, &reset_cadet_task, mh); - mh->waiting_map = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_YES); + GNUNET_SCHEDULER_add_delayed(CLIENT_RETRY_TIMEOUT, &reset_cadet_task, mh); + mh->waiting_map = GNUNET_CONTAINER_multihashmap_create(16, GNUNET_YES); mh->target = *target; - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put ( - cadet_map, - &mh->target, - mh, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_put( + cadet_map, + &mh->target, + mh, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_var_size (reply, - GNUNET_MESSAGE_TYPE_FS_CADET_REPLY, - struct CadetReplyMessage, - mh), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_var_size(reply, + GNUNET_MESSAGE_TYPE_FS_CADET_REPLY, + struct CadetReplyMessage, + mh), + GNUNET_MQ_handler_end() }; struct GNUNET_HashCode port; - GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER, - strlen (GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER), - &port); - mh->channel = GNUNET_CADET_channel_create (cadet_handle, - mh, - &mh->target, - &port, - &window_change_cb, - &disconnect_cb, - handlers); + GNUNET_CRYPTO_hash(GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER, + strlen(GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER), + &port); + mh->channel = GNUNET_CADET_channel_create(cadet_handle, + mh, + &mh->target, + &port, + &window_change_cb, + &disconnect_cb, + handlers); } return mh; } @@ -629,28 +624,28 @@ get_cadet (const struct GNUNET_PeerIdentity *target) * @return handle to cancel the operation */ struct GSF_CadetRequest * -GSF_cadet_query (const struct GNUNET_PeerIdentity *target, - const struct GNUNET_HashCode *query, - enum GNUNET_BLOCK_Type type, - GSF_CadetReplyProcessor proc, - void *proc_cls) +GSF_cadet_query(const struct GNUNET_PeerIdentity *target, + const struct GNUNET_HashCode *query, + enum GNUNET_BLOCK_Type type, + GSF_CadetReplyProcessor proc, + void *proc_cls) { struct CadetHandle *mh; struct GSF_CadetRequest *sr; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Preparing to send query for %s via cadet to %s\n", - GNUNET_h2s (query), - GNUNET_i2s (target)); - mh = get_cadet (target); - sr = GNUNET_new (struct GSF_CadetRequest); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Preparing to send query for %s via cadet to %s\n", + GNUNET_h2s(query), + GNUNET_i2s(target)); + mh = get_cadet(target); + sr = GNUNET_new(struct GSF_CadetRequest); sr->mh = mh; sr->proc = proc; sr->proc_cls = proc_cls; sr->type = type; sr->query = *query; - GNUNET_CONTAINER_DLL_insert (mh->pending_head, mh->pending_tail, sr); - transmit_pending (mh); + GNUNET_CONTAINER_DLL_insert(mh->pending_head, mh->pending_tail, sr); + transmit_pending(mh); return sr; } @@ -662,7 +657,7 @@ GSF_cadet_query (const struct GNUNET_PeerIdentity *target, * @param sr request to cancel */ void -GSF_cadet_query_cancel (struct GSF_CadetRequest *sr) +GSF_cadet_query_cancel(struct GSF_CadetRequest *sr) { struct CadetHandle *mh = sr->mh; GSF_CadetReplyProcessor p; @@ -670,26 +665,26 @@ GSF_cadet_query_cancel (struct GSF_CadetRequest *sr) p = sr->proc; sr->proc = NULL; if (NULL != p) - { - /* signal failure / cancellation to callback */ - p (sr->proc_cls, GNUNET_BLOCK_TYPE_ANY, GNUNET_TIME_UNIT_ZERO_ABS, 0, NULL); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Cancelled query for %s via cadet to %s\n", - GNUNET_h2s (&sr->query), - GNUNET_i2s (&sr->mh->target)); + { + /* signal failure / cancellation to callback */ + p(sr->proc_cls, GNUNET_BLOCK_TYPE_ANY, GNUNET_TIME_UNIT_ZERO_ABS, 0, NULL); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Cancelled query for %s via cadet to %s\n", + GNUNET_h2s(&sr->query), + GNUNET_i2s(&sr->mh->target)); if (GNUNET_YES == sr->was_transmitted) - GNUNET_assert ( + GNUNET_assert( GNUNET_OK == - GNUNET_CONTAINER_multihashmap_remove (mh->waiting_map, &sr->query, sr)); + GNUNET_CONTAINER_multihashmap_remove(mh->waiting_map, &sr->query, sr)); else - GNUNET_CONTAINER_DLL_remove (mh->pending_head, mh->pending_tail, sr); - GNUNET_free (sr); - if ((0 == GNUNET_CONTAINER_multihashmap_size (mh->waiting_map)) && + GNUNET_CONTAINER_DLL_remove(mh->pending_head, mh->pending_tail, sr); + GNUNET_free(sr); + if ((0 == GNUNET_CONTAINER_multihashmap_size(mh->waiting_map)) && (NULL == mh->pending_head)) - mh->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &cadet_timeout, - mh); + mh->timeout_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &cadet_timeout, + mh); } @@ -702,27 +697,27 @@ GSF_cadet_query_cancel (struct GSF_CadetRequest *sr) * @return #GNUNET_YES (continue to iterate) */ int -GSF_cadet_release_clients (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +GSF_cadet_release_clients(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct CadetHandle *mh = value; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Timeout on cadet channel to %s\n", - GNUNET_i2s (&mh->target)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Timeout on cadet channel to %s\n", + GNUNET_i2s(&mh->target)); if (NULL != mh->channel) - { - struct GNUNET_CADET_Channel *channel = mh->channel; + { + struct GNUNET_CADET_Channel *channel = mh->channel; - mh->channel = NULL; - GNUNET_CADET_channel_destroy (channel); - } + mh->channel = NULL; + GNUNET_CADET_channel_destroy(channel); + } if (NULL != mh->reset_task) - { - GNUNET_SCHEDULER_cancel (mh->reset_task); - mh->reset_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(mh->reset_task); + mh->reset_task = NULL; + } return GNUNET_YES; } diff --git a/src/fs/gnunet-service-fs_cadet_server.c b/src/fs/gnunet-service-fs_cadet_server.c index bb320806a..68e87f092 100644 --- a/src/fs/gnunet-service-fs_cadet_server.c +++ b/src/fs/gnunet-service-fs_cadet_server.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_cadet_server.c @@ -40,14 +40,13 @@ /** * After how long do we termiante idle connections? */ -#define IDLE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2) +#define IDLE_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2) /** * A message in the queue to be written to the cadet. */ -struct WriteQueueItem -{ +struct WriteQueueItem { /** * Kept in a DLL. */ @@ -68,8 +67,7 @@ struct WriteQueueItem /** * Information we keep around for each active cadeting client. */ -struct CadetClient -{ +struct CadetClient { /** * DLL */ @@ -114,7 +112,6 @@ struct CadetClient * Size of the last write that was initiated. */ size_t reply_size; - }; @@ -151,7 +148,7 @@ static unsigned long long sc_count_max; * @param cls the 'struct CadetClient' */ static void -timeout_cadet_task (void *cls) +timeout_cadet_task(void *cls) { struct CadetClient *sc = cls; struct GNUNET_CADET_Channel *tun; @@ -159,10 +156,10 @@ timeout_cadet_task (void *cls) sc->timeout_task = NULL; tun = sc->channel; sc->channel = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Timeout for inactive cadet client %p\n", - sc); - GNUNET_CADET_channel_destroy (tun); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Timeout for inactive cadet client %p\n", + sc); + GNUNET_CADET_channel_destroy(tun); } @@ -172,13 +169,13 @@ timeout_cadet_task (void *cls) * @param sc client handle to reset timeout for */ static void -refresh_timeout_task (struct CadetClient *sc) +refresh_timeout_task(struct CadetClient *sc) { if (NULL != sc->timeout_task) - GNUNET_SCHEDULER_cancel (sc->timeout_task); - sc->timeout_task = GNUNET_SCHEDULER_add_delayed (IDLE_TIMEOUT, - &timeout_cadet_task, - sc); + GNUNET_SCHEDULER_cancel(sc->timeout_task); + sc->timeout_task = GNUNET_SCHEDULER_add_delayed(IDLE_TIMEOUT, + &timeout_cadet_task, + sc); } @@ -189,23 +186,23 @@ refresh_timeout_task (struct CadetClient *sc) * @param cls where to process the write queue */ static void -continue_writing (void *cls) +continue_writing(void *cls) { struct CadetClient *sc = cls; struct GNUNET_MQ_Handle *mq; - mq = GNUNET_CADET_get_mq (sc->channel); - if (0 != GNUNET_MQ_get_length (mq)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Write pending, waiting for it to complete\n"); - return; - } - refresh_timeout_task (sc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished processing cadet request from client %p, ready to receive the next one\n", - sc); - GNUNET_CADET_receive_done (sc->channel); + mq = GNUNET_CADET_get_mq(sc->channel); + if (0 != GNUNET_MQ_get_length(mq)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Write pending, waiting for it to complete\n"); + return; + } + refresh_timeout_task(sc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished processing cadet request from client %p, ready to receive the next one\n", + sc); + GNUNET_CADET_receive_done(sc->channel); } @@ -225,103 +222,103 @@ continue_writing (void *cls) * maybe 0 if no unique identifier is available */ static void -handle_datastore_reply (void *cls, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +handle_datastore_reply(void *cls, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct CadetClient *sc = cls; - size_t msize = size + sizeof (struct CadetReplyMessage); + size_t msize = size + sizeof(struct CadetReplyMessage); struct GNUNET_MQ_Envelope *env; struct CadetReplyMessage *srm; sc->qe = NULL; if (NULL == data) - { - /* no result, this should not really happen, as for - non-anonymous routing only peers that HAVE the - answers should be queried; OTOH, this is not a - hard error as we might have had the answer in the - past and the user might have unindexed it. Hence - we log at level "INFO" for now. */ - if (NULL == key) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Have no answer and the query was NULL\n"); - } - else { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Have no answer for query `%s'\n", - GNUNET_h2s (key)); + /* no result, this should not really happen, as for + non-anonymous routing only peers that HAVE the + answers should be queried; OTOH, this is not a + hard error as we might have had the answer in the + past and the user might have unindexed it. Hence + we log at level "INFO" for now. */ + if (NULL == key) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Have no answer and the query was NULL\n"); + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Have no answer for query `%s'\n", + GNUNET_h2s(key)); + } + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# queries received via CADET not answered"), + 1, + GNUNET_NO); + continue_writing(sc); + return; } - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# queries received via CADET not answered"), - 1, - GNUNET_NO); - continue_writing (sc); - return; - } if (GNUNET_BLOCK_TYPE_FS_ONDEMAND == type) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Performing on-demand encoding for query %s\n", - GNUNET_h2s (key)); - if (GNUNET_OK != - GNUNET_FS_handle_on_demand_block (key, - size, - data, - type, - priority, - anonymity, - replication, - expiration, - uid, - &handle_datastore_reply, - sc)) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "On-demand encoding request failed\n"); - continue_writing (sc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Performing on-demand encoding for query %s\n", + GNUNET_h2s(key)); + if (GNUNET_OK != + GNUNET_FS_handle_on_demand_block(key, + size, + data, + type, + priority, + anonymity, + replication, + expiration, + uid, + &handle_datastore_reply, + sc)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "On-demand encoding request failed\n"); + continue_writing(sc); + } + return; } - return; - } if (msize > GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - continue_writing (sc); - return; - } - GNUNET_break (GNUNET_BLOCK_TYPE_ANY != type); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting transmission of %u byte reply of type %d for query `%s' via cadet to %p\n", - (unsigned int) size, - (unsigned int) type, - GNUNET_h2s (key), - sc); - env = GNUNET_MQ_msg_extra (srm, - size, - GNUNET_MESSAGE_TYPE_FS_CADET_REPLY); - srm->type = htonl (type); - srm->expiration = GNUNET_TIME_absolute_hton (expiration); - GNUNET_memcpy (&srm[1], - data, - size); - GNUNET_MQ_notify_sent (env, - &continue_writing, - sc); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# Blocks transferred via cadet"), - 1, - GNUNET_NO); - GNUNET_MQ_send (GNUNET_CADET_get_mq (sc->channel), - env); + { + GNUNET_break(0); + continue_writing(sc); + return; + } + GNUNET_break(GNUNET_BLOCK_TYPE_ANY != type); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting transmission of %u byte reply of type %d for query `%s' via cadet to %p\n", + (unsigned int)size, + (unsigned int)type, + GNUNET_h2s(key), + sc); + env = GNUNET_MQ_msg_extra(srm, + size, + GNUNET_MESSAGE_TYPE_FS_CADET_REPLY); + srm->type = htonl(type); + srm->expiration = GNUNET_TIME_absolute_hton(expiration); + GNUNET_memcpy(&srm[1], + data, + size); + GNUNET_MQ_notify_sent(env, + &continue_writing, + sc); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# Blocks transferred via cadet"), + 1, + GNUNET_NO); + GNUNET_MQ_send(GNUNET_CADET_get_mq(sc->channel), + env); } @@ -333,35 +330,35 @@ handle_datastore_reply (void *cls, * @param sqm the actual message */ static void -handle_request (void *cls, - const struct CadetQueryMessage *sqm) +handle_request(void *cls, + const struct CadetQueryMessage *sqm) { struct CadetClient *sc = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received query for `%s' via cadet from client %p\n", - GNUNET_h2s (&sqm->query), - sc); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# queries received via cadet"), - 1, - GNUNET_NO); - refresh_timeout_task (sc); - sc->qe = GNUNET_DATASTORE_get_key (GSF_dsh, - 0 /* next_uid */, - false /* random */, - &sqm->query, - ntohl (sqm->type), - 0 /* priority */, - GSF_datastore_queue_size, - &handle_datastore_reply, - sc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received query for `%s' via cadet from client %p\n", + GNUNET_h2s(&sqm->query), + sc); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# queries received via cadet"), + 1, + GNUNET_NO); + refresh_timeout_task(sc); + sc->qe = GNUNET_DATASTORE_get_key(GSF_dsh, + 0 /* next_uid */, + false /* random */, + &sqm->query, + ntohl(sqm->type), + 0 /* priority */, + GSF_datastore_queue_size, + &handle_datastore_reply, + sc); if (NULL == sc->qe) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Queueing request with datastore failed (queue full?)\n"); - continue_writing (sc); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Queueing request with datastore failed (queue full?)\n"); + continue_writing(sc); + } } @@ -375,37 +372,37 @@ handle_request (void *cls, * @return initial channel context (our `struct CadetClient`) */ static void * -connect_cb (void *cls, - struct GNUNET_CADET_Channel *channel, - const struct GNUNET_PeerIdentity *initiator) +connect_cb(void *cls, + struct GNUNET_CADET_Channel *channel, + const struct GNUNET_PeerIdentity *initiator) { struct CadetClient *sc; - GNUNET_assert (NULL != channel); + GNUNET_assert(NULL != channel); if (sc_count >= sc_count_max) - { - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# cadet client connections rejected"), - 1, - GNUNET_NO); - GNUNET_CADET_channel_destroy (channel); - return NULL; - } - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# cadet connections active"), - 1, - GNUNET_NO); - sc = GNUNET_new (struct CadetClient); + { + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# cadet client connections rejected"), + 1, + GNUNET_NO); + GNUNET_CADET_channel_destroy(channel); + return NULL; + } + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# cadet connections active"), + 1, + GNUNET_NO); + sc = GNUNET_new(struct CadetClient); sc->channel = channel; - GNUNET_CONTAINER_DLL_insert (sc_head, - sc_tail, - sc); + GNUNET_CONTAINER_DLL_insert(sc_head, + sc_tail, + sc); sc_count++; - refresh_timeout_task (sc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Accepting inbound cadet connection from `%s' as client %p\n", - GNUNET_i2s (initiator), - sc); + refresh_timeout_task(sc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Accepting inbound cadet connection from `%s' as client %p\n", + GNUNET_i2s(initiator), + sc); return sc; } @@ -419,8 +416,8 @@ connect_cb (void *cls, * @param channel_ctx */ static void -disconnect_cb (void *cls, - const struct GNUNET_CADET_Channel *channel) +disconnect_cb(void *cls, + const struct GNUNET_CADET_Channel *channel) { struct CadetClient *sc = cls; struct WriteQueueItem *wqi; @@ -428,30 +425,30 @@ disconnect_cb (void *cls, if (NULL == sc) return; sc->channel = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Terminating cadet connection with client %p\n", - sc); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# cadet connections active"), -1, - GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Terminating cadet connection with client %p\n", + sc); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# cadet connections active"), -1, + GNUNET_NO); if (NULL != sc->terminate_task) - GNUNET_SCHEDULER_cancel (sc->terminate_task); + GNUNET_SCHEDULER_cancel(sc->terminate_task); if (NULL != sc->timeout_task) - GNUNET_SCHEDULER_cancel (sc->timeout_task); + GNUNET_SCHEDULER_cancel(sc->timeout_task); if (NULL != sc->qe) - GNUNET_DATASTORE_cancel (sc->qe); + GNUNET_DATASTORE_cancel(sc->qe); while (NULL != (wqi = sc->wqi_head)) - { - GNUNET_CONTAINER_DLL_remove (sc->wqi_head, - sc->wqi_tail, - wqi); - GNUNET_free (wqi); - } - GNUNET_CONTAINER_DLL_remove (sc_head, - sc_tail, - sc); + { + GNUNET_CONTAINER_DLL_remove(sc->wqi_head, + sc->wqi_tail, + wqi); + GNUNET_free(wqi); + } + GNUNET_CONTAINER_DLL_remove(sc_head, + sc_tail, + sc); sc_count--; - GNUNET_free (sc); + GNUNET_free(sc); } @@ -470,9 +467,9 @@ disconnect_cb (void *cls, * this value will be negative.. */ static void -window_change_cb (void *cls, - const struct GNUNET_CADET_Channel *channel, - int window_size) +window_change_cb(void *cls, + const struct GNUNET_CADET_Channel *channel, + int window_size) { /* FIXME: could do flow control here... */ } @@ -482,39 +479,39 @@ window_change_cb (void *cls, * Initialize subsystem for non-anonymous file-sharing. */ void -GSF_cadet_start_server () +GSF_cadet_start_server() { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_fixed_size (request, - GNUNET_MESSAGE_TYPE_FS_CADET_QUERY, - struct CadetQueryMessage, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_fixed_size(request, + GNUNET_MESSAGE_TYPE_FS_CADET_QUERY, + struct CadetQueryMessage, + NULL), + GNUNET_MQ_handler_end() }; struct GNUNET_HashCode port; if (GNUNET_YES != - GNUNET_CONFIGURATION_get_value_number (GSF_cfg, - "fs", - "MAX_CADET_CLIENTS", - &sc_count_max)) + GNUNET_CONFIGURATION_get_value_number(GSF_cfg, + "fs", + "MAX_CADET_CLIENTS", + &sc_count_max)) return; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Initializing cadet FS server with a limit of %llu connections\n", - sc_count_max); - cadet_map = GNUNET_CONTAINER_multipeermap_create (16, GNUNET_YES); - cadet_handle = GNUNET_CADET_connect (GSF_cfg); - GNUNET_assert (NULL != cadet_handle); - GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER, - strlen (GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER), - &port); - cadet_port = GNUNET_CADET_open_port (cadet_handle, - &port, - &connect_cb, - NULL, - &window_change_cb, - &disconnect_cb, - handlers); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Initializing cadet FS server with a limit of %llu connections\n", + sc_count_max); + cadet_map = GNUNET_CONTAINER_multipeermap_create(16, GNUNET_YES); + cadet_handle = GNUNET_CADET_connect(GSF_cfg); + GNUNET_assert(NULL != cadet_handle); + GNUNET_CRYPTO_hash(GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER, + strlen(GNUNET_APPLICATION_PORT_FS_BLOCK_TRANSFER), + &port); + cadet_port = GNUNET_CADET_open_port(cadet_handle, + &port, + &connect_cb, + NULL, + &window_change_cb, + &disconnect_cb, + handlers); } @@ -522,25 +519,25 @@ GSF_cadet_start_server () * Shutdown subsystem for non-anonymous file-sharing. */ void -GSF_cadet_stop_server () +GSF_cadet_stop_server() { - GNUNET_CONTAINER_multipeermap_iterate (cadet_map, - &GSF_cadet_release_clients, - NULL); - GNUNET_CONTAINER_multipeermap_destroy (cadet_map); + GNUNET_CONTAINER_multipeermap_iterate(cadet_map, + &GSF_cadet_release_clients, + NULL); + GNUNET_CONTAINER_multipeermap_destroy(cadet_map); cadet_map = NULL; if (NULL != cadet_port) - { - GNUNET_CADET_close_port (cadet_port); - cadet_port = NULL; - } + { + GNUNET_CADET_close_port(cadet_port); + cadet_port = NULL; + } if (NULL != cadet_handle) - { - GNUNET_CADET_disconnect (cadet_handle); - cadet_handle = NULL; - } - GNUNET_assert (NULL == sc_head); - GNUNET_assert (0 == sc_count); + { + GNUNET_CADET_disconnect(cadet_handle); + cadet_handle = NULL; + } + GNUNET_assert(NULL == sc_head); + GNUNET_assert(0 == sc_count); } /* end of gnunet-service-fs_cadet.c */ diff --git a/src/fs/gnunet-service-fs_cp.c b/src/fs/gnunet-service-fs_cp.c index a3a521221..6dab37869 100644 --- a/src/fs/gnunet-service-fs_cp.c +++ b/src/fs/gnunet-service-fs_cp.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_cp.c * @brief API to handle 'connected peers' @@ -43,12 +43,12 @@ /** * How often do we flush respect values to disk? */ -#define RESPECT_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5) +#define RESPECT_FLUSH_FREQ GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5) /** * After how long do we discard a reply? */ -#define REPLY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2) +#define REPLY_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2) /** * Collect an instane number of statistics? May cause excessive IPC. @@ -59,9 +59,7 @@ /** * Handle to cancel a transmission request. */ -struct GSF_PeerTransmitHandle -{ - +struct GSF_PeerTransmitHandle { /** * Kept in a doubly-linked list. */ @@ -101,16 +99,13 @@ struct GSF_PeerTransmitHandle * Priority of this request. */ uint32_t priority; - }; /** * Handle for an entry in our delay list. */ -struct GSF_DelayedHandle -{ - +struct GSF_DelayedHandle { /** * Kept in a doubly-linked list. */ @@ -140,16 +135,13 @@ struct GSF_DelayedHandle * Size of the message. */ size_t msize; - }; /** * Information per peer and request. */ -struct PeerRequest -{ - +struct PeerRequest { /** * Handle to generic request (generic: from peer or local client). */ @@ -164,16 +156,13 @@ struct PeerRequest * Task for asynchronous stopping of this request. */ struct GNUNET_SCHEDULER_Task *kill_task; - }; /** * A connected peer. */ -struct GSF_ConnectedPeer -{ - +struct GSF_ConnectedPeer { /** * Performance data for this peer. */ @@ -278,7 +267,6 @@ struct GSF_ConnectedPeer * Handle to the PEERSTORE iterate request for peer respect value */ struct GNUNET_PEERSTORE_IterateContext *respect_iterate_req; - }; @@ -305,16 +293,16 @@ static struct GNUNET_SCHEDULER_Task *fr_task; * @param latency current latency value */ void -GSF_update_peer_latency_ (const struct GNUNET_PeerIdentity *id, - struct GNUNET_TIME_Relative latency) +GSF_update_peer_latency_(const struct GNUNET_PeerIdentity *id, + struct GNUNET_TIME_Relative latency) { struct GSF_ConnectedPeer *cp; - cp = GSF_peer_get_ (id); + cp = GSF_peer_get_(id); if (NULL == cp) return; /* we're not yet connected at the core level, ignore */ - GNUNET_LOAD_value_set_decline (cp->ppd.transmission_delay, - latency); + GNUNET_LOAD_value_set_decline(cp->ppd.transmission_delay, + latency); } @@ -325,7 +313,7 @@ GSF_update_peer_latency_ (const struct GNUNET_PeerIdentity *id, * @return performance data record for the peer */ struct GSF_PeerPerformanceData * -GSF_get_peer_performance_data_ (struct GSF_ConnectedPeer *cp) +GSF_get_peer_performance_data_(struct GSF_ConnectedPeer *cp) { return &cp->ppd; } @@ -337,7 +325,7 @@ GSF_get_peer_performance_data_ (struct GSF_ConnectedPeer *cp) * @param cp which peer to send a message to */ static void -peer_transmit (struct GSF_ConnectedPeer *cp); +peer_transmit(struct GSF_ConnectedPeer *cp); /** @@ -351,10 +339,10 @@ peer_transmit (struct GSF_ConnectedPeer *cp); * long should the client wait until re-trying? */ static void -ats_reserve_callback (void *cls, - const struct GNUNET_PeerIdentity *peer, - int32_t amount, - struct GNUNET_TIME_Relative res_delay); +ats_reserve_callback(void *cls, + const struct GNUNET_PeerIdentity *peer, + int32_t amount, + struct GNUNET_TIME_Relative res_delay); /** @@ -364,42 +352,42 @@ ats_reserve_callback (void *cls, * @param pth transmission handle to schedule */ static void -schedule_transmission (struct GSF_PeerTransmitHandle *pth) +schedule_transmission(struct GSF_PeerTransmitHandle *pth) { struct GSF_ConnectedPeer *cp; struct GNUNET_PeerIdentity target; cp = pth->cp; - GNUNET_assert (0 != cp->ppd.pid); - GNUNET_PEER_resolve (cp->ppd.pid, &target); + GNUNET_assert(0 != cp->ppd.pid); + GNUNET_PEER_resolve(cp->ppd.pid, &target); if (0 != cp->inc_preference) - { - GNUNET_ATS_performance_change_preference (GSF_ats, - &target, - GNUNET_ATS_PREFERENCE_BANDWIDTH, - (double) cp->inc_preference, - GNUNET_ATS_PREFERENCE_END); - cp->inc_preference = 0; - } - - if ( (GNUNET_YES == pth->is_query) && - (GNUNET_YES != pth->was_reserved) ) - { - /* query, need reservation */ - if (GNUNET_YES != cp->did_reserve) - return; /* not ready */ - cp->did_reserve = GNUNET_NO; - /* reservation already done! */ - pth->was_reserved = GNUNET_YES; - cp->rc = GNUNET_ATS_reserve_bandwidth (GSF_ats, - &target, - DBLOCK_SIZE, - &ats_reserve_callback, - cp); - return; - } - peer_transmit (cp); + { + GNUNET_ATS_performance_change_preference(GSF_ats, + &target, + GNUNET_ATS_PREFERENCE_BANDWIDTH, + (double)cp->inc_preference, + GNUNET_ATS_PREFERENCE_END); + cp->inc_preference = 0; + } + + if ((GNUNET_YES == pth->is_query) && + (GNUNET_YES != pth->was_reserved)) + { + /* query, need reservation */ + if (GNUNET_YES != cp->did_reserve) + return; /* not ready */ + cp->did_reserve = GNUNET_NO; + /* reservation already done! */ + pth->was_reserved = GNUNET_YES; + cp->rc = GNUNET_ATS_reserve_bandwidth(GSF_ats, + &target, + DBLOCK_SIZE, + &ats_reserve_callback, + cp); + return; + } + peer_transmit(cp); } @@ -409,38 +397,38 @@ schedule_transmission (struct GSF_PeerTransmitHandle *pth) * @param cp which peer to send a message to */ static void -peer_transmit (struct GSF_ConnectedPeer *cp) +peer_transmit(struct GSF_ConnectedPeer *cp) { struct GSF_PeerTransmitHandle *pth = cp->pth_head; struct GSF_PeerTransmitHandle *pos; if (NULL == pth) return; - GNUNET_CONTAINER_DLL_remove (cp->pth_head, - cp->pth_tail, - pth); + GNUNET_CONTAINER_DLL_remove(cp->pth_head, + cp->pth_tail, + pth); if (GNUNET_YES == pth->is_query) - { - cp->ppd.last_request_times[(cp->last_request_times_off++) % - MAX_QUEUE_PER_PEER] = - GNUNET_TIME_absolute_get (); - GNUNET_assert (0 < cp->ppd.pending_queries--); - } + { + cp->ppd.last_request_times[(cp->last_request_times_off++) % + MAX_QUEUE_PER_PEER] = + GNUNET_TIME_absolute_get(); + GNUNET_assert(0 < cp->ppd.pending_queries--); + } else if (GNUNET_NO == pth->is_query) - { - GNUNET_assert (0 < cp->ppd.pending_replies--); - } - GNUNET_LOAD_update (cp->ppd.transmission_delay, - GNUNET_TIME_absolute_get_duration - (pth->transmission_request_start_time).rel_value_us); - GNUNET_MQ_send (cp->mq, - pth->env); - GNUNET_free (pth); + { + GNUNET_assert(0 < cp->ppd.pending_replies--); + } + GNUNET_LOAD_update(cp->ppd.transmission_delay, + GNUNET_TIME_absolute_get_duration + (pth->transmission_request_start_time).rel_value_us); + GNUNET_MQ_send(cp->mq, + pth->env); + GNUNET_free(pth); if (NULL != (pos = cp->pth_head)) - { - GNUNET_assert (pos != pth); - schedule_transmission (pos); - } + { + GNUNET_assert(pos != pth); + schedule_transmission(pos); + } } @@ -450,18 +438,18 @@ peer_transmit (struct GSF_ConnectedPeer *cp) * @param cls the `struct GSF_ConnectedPeer` to reserve from */ static void -retry_reservation (void *cls) +retry_reservation(void *cls) { struct GSF_ConnectedPeer *cp = cls; struct GNUNET_PeerIdentity target; - GNUNET_PEER_resolve (cp->ppd.pid, &target); + GNUNET_PEER_resolve(cp->ppd.pid, &target); cp->rc_delay_task = NULL; cp->rc = - GNUNET_ATS_reserve_bandwidth (GSF_ats, - &target, - DBLOCK_SIZE, - &ats_reserve_callback, cp); + GNUNET_ATS_reserve_bandwidth(GSF_ats, + &target, + DBLOCK_SIZE, + &ats_reserve_callback, cp); } @@ -476,34 +464,34 @@ retry_reservation (void *cls) * long should the client wait until re-trying? */ static void -ats_reserve_callback (void *cls, - const struct GNUNET_PeerIdentity *peer, - int32_t amount, - struct GNUNET_TIME_Relative res_delay) +ats_reserve_callback(void *cls, + const struct GNUNET_PeerIdentity *peer, + int32_t amount, + struct GNUNET_TIME_Relative res_delay) { struct GSF_ConnectedPeer *cp = cls; struct GSF_PeerTransmitHandle *pth; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Reserved %d bytes / need to wait %s for reservation\n", - (int) amount, - GNUNET_STRINGS_relative_time_to_string (res_delay, GNUNET_YES)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Reserved %d bytes / need to wait %s for reservation\n", + (int)amount, + GNUNET_STRINGS_relative_time_to_string(res_delay, GNUNET_YES)); cp->rc = NULL; if (0 == amount) - { - cp->rc_delay_task = - GNUNET_SCHEDULER_add_delayed (res_delay, - &retry_reservation, - cp); - return; - } + { + cp->rc_delay_task = + GNUNET_SCHEDULER_add_delayed(res_delay, + &retry_reservation, + cp); + return; + } cp->did_reserve = GNUNET_YES; pth = cp->pth_head; if (NULL != pth) - { - /* reservation success, try transmission now! */ - peer_transmit (cp); - } + { + /* reservation success, try transmission now! */ + peer_transmit(cp); + } } @@ -515,22 +503,22 @@ ats_reserve_callback (void *cls, * @param emsg error message, or NULL if no errors */ static void -peer_respect_cb (void *cls, - const struct GNUNET_PEERSTORE_Record *record, - const char *emsg) +peer_respect_cb(void *cls, + const struct GNUNET_PEERSTORE_Record *record, + const char *emsg) { struct GSF_ConnectedPeer *cp = cls; - GNUNET_assert (NULL != cp->respect_iterate_req); - if ( (NULL != record) && - (sizeof (cp->disk_respect) == record->value_size)) - { - cp->disk_respect = *((uint32_t *)record->value); - cp->ppd.respect += *((uint32_t *)record->value); - } - GSF_push_start_ (cp); + GNUNET_assert(NULL != cp->respect_iterate_req); + if ((NULL != record) && + (sizeof(cp->disk_respect) == record->value_size)) + { + cp->disk_respect = *((uint32_t *)record->value); + cp->ppd.respect += *((uint32_t *)record->value); + } + GSF_push_start_(cp); if (NULL != record) - GNUNET_PEERSTORE_iterate_cancel (cp->respect_iterate_req); + GNUNET_PEERSTORE_iterate_cancel(cp->respect_iterate_req); cp->respect_iterate_req = NULL; } @@ -546,27 +534,27 @@ peer_respect_cb (void *cls, * @return #GNUNET_YES to continue to iterate */ static int -consider_peer_for_forwarding (void *cls, - const struct GNUNET_HashCode *key, - struct GSF_PendingRequest *pr) +consider_peer_for_forwarding(void *cls, + const struct GNUNET_HashCode *key, + struct GSF_PendingRequest *pr) { struct GSF_ConnectedPeer *cp = cls; struct GNUNET_PeerIdentity pid; if (GNUNET_YES != - GSF_pending_request_test_active_ (pr)) + GSF_pending_request_test_active_(pr)) return GNUNET_YES; /* request is not actually active, skip! */ - GSF_connected_peer_get_identity_ (cp, &pid); + GSF_connected_peer_get_identity_(cp, &pid); if (GNUNET_YES != - GSF_pending_request_test_target_ (pr, &pid)) - { - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# Loopback routes suppressed"), - 1, - GNUNET_NO); - return GNUNET_YES; - } - GSF_plan_add_ (cp, pr); + GSF_pending_request_test_target_(pr, &pid)) + { + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# Loopback routes suppressed"), + 1, + GNUNET_NO); + return GNUNET_YES; + } + GSF_plan_add_(cp, pr); return GNUNET_YES; } @@ -581,49 +569,49 @@ consider_peer_for_forwarding (void *cls, * @return our internal handle for the peer */ void * -GSF_peer_connect_handler (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +GSF_peer_connect_handler(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { struct GSF_ConnectedPeer *cp; if (0 == - GNUNET_memcmp (&GSF_my_id, - peer)) + GNUNET_memcmp(&GSF_my_id, + peer)) return NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connected to peer %s\n", - GNUNET_i2s (peer)); - cp = GNUNET_new (struct GSF_ConnectedPeer); - cp->ppd.pid = GNUNET_PEER_intern (peer); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connected to peer %s\n", + GNUNET_i2s(peer)); + cp = GNUNET_new(struct GSF_ConnectedPeer); + cp->ppd.pid = GNUNET_PEER_intern(peer); cp->ppd.peer = peer; cp->mq = mq; - cp->ppd.transmission_delay = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_ZERO); + cp->ppd.transmission_delay = GNUNET_LOAD_value_init(GNUNET_TIME_UNIT_ZERO); cp->rc = - GNUNET_ATS_reserve_bandwidth (GSF_ats, - peer, - DBLOCK_SIZE, - &ats_reserve_callback, cp); - cp->request_map = GNUNET_CONTAINER_multihashmap_create (128, - GNUNET_YES); - GNUNET_break (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put (cp_map, - GSF_connected_peer_get_identity2_ (cp), - cp, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - GNUNET_STATISTICS_set (GSF_stats, - gettext_noop ("# peers connected"), - GNUNET_CONTAINER_multipeermap_size (cp_map), - GNUNET_NO); - cp->respect_iterate_req - = GNUNET_PEERSTORE_iterate (peerstore, - "fs", - peer, - "respect", - &peer_respect_cb, + GNUNET_ATS_reserve_bandwidth(GSF_ats, + peer, + DBLOCK_SIZE, + &ats_reserve_callback, cp); + cp->request_map = GNUNET_CONTAINER_multihashmap_create(128, + GNUNET_YES); + GNUNET_break(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_put(cp_map, + GSF_connected_peer_get_identity2_(cp), + cp, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_STATISTICS_set(GSF_stats, + gettext_noop("# peers connected"), + GNUNET_CONTAINER_multipeermap_size(cp_map), + GNUNET_NO); + cp->respect_iterate_req + = GNUNET_PEERSTORE_iterate(peerstore, + "fs", + peer, + "respect", + &peer_respect_cb, + cp); + GSF_iterate_pending_requests_(&consider_peer_for_forwarding, cp); - GSF_iterate_pending_requests_ (&consider_peer_for_forwarding, - cp); return cp; } @@ -635,21 +623,21 @@ GSF_peer_connect_handler (void *cls, * @param cls the `struct GSF_ConnectedPeer` */ static void -revive_migration (void *cls) +revive_migration(void *cls) { struct GSF_ConnectedPeer *cp = cls; struct GNUNET_TIME_Relative bt; cp->mig_revive_task = NULL; - bt = GNUNET_TIME_absolute_get_remaining (cp->ppd.migration_blocked_until); + bt = GNUNET_TIME_absolute_get_remaining(cp->ppd.migration_blocked_until); if (0 != bt.rel_value_us) - { - /* still time left... */ - cp->mig_revive_task = - GNUNET_SCHEDULER_add_delayed (bt, &revive_migration, cp); - return; - } - GSF_push_start_ (cp); + { + /* still time left... */ + cp->mig_revive_task = + GNUNET_SCHEDULER_add_delayed(bt, &revive_migration, cp); + return; + } + GSF_push_start_(cp); } @@ -660,44 +648,44 @@ revive_migration (void *cls) * @return NULL if the peer is not currently connected */ struct GSF_ConnectedPeer * -GSF_peer_get_ (const struct GNUNET_PeerIdentity *peer) +GSF_peer_get_(const struct GNUNET_PeerIdentity *peer) { if (NULL == cp_map) return NULL; - return GNUNET_CONTAINER_multipeermap_get (cp_map, peer); + return GNUNET_CONTAINER_multipeermap_get(cp_map, peer); } /** - * Handle P2P #GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP message. + * Handle P2P #GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP message. * * @param cls closure, the `struct GSF_ConnectedPeer` * @param msm the actual message */ void -handle_p2p_migration_stop (void *cls, - const struct MigrationStopMessage *msm) +handle_p2p_migration_stop(void *cls, + const struct MigrationStopMessage *msm) { struct GSF_ConnectedPeer *cp = cls; struct GNUNET_TIME_Relative bt; - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# migration stop messages received"), - 1, GNUNET_NO); - bt = GNUNET_TIME_relative_ntoh (msm->duration); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Migration of content to peer `%s' blocked for %s\n"), - GNUNET_i2s (cp->ppd.peer), - GNUNET_STRINGS_relative_time_to_string (bt, GNUNET_YES)); - cp->ppd.migration_blocked_until = GNUNET_TIME_relative_to_absolute (bt); - if ( (NULL == cp->mig_revive_task) && - (NULL == cp->respect_iterate_req) ) - { - GSF_push_stop_ (cp); - cp->mig_revive_task = - GNUNET_SCHEDULER_add_delayed (bt, - &revive_migration, cp); - } + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# migration stop messages received"), + 1, GNUNET_NO); + bt = GNUNET_TIME_relative_ntoh(msm->duration); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Migration of content to peer `%s' blocked for %s\n"), + GNUNET_i2s(cp->ppd.peer), + GNUNET_STRINGS_relative_time_to_string(bt, GNUNET_YES)); + cp->ppd.migration_blocked_until = GNUNET_TIME_relative_to_absolute(bt); + if ((NULL == cp->mig_revive_task) && + (NULL == cp->respect_iterate_req)) + { + GSF_push_stop_(cp); + cp->mig_revive_task = + GNUNET_SCHEDULER_add_delayed(bt, + &revive_migration, cp); + } } @@ -707,26 +695,26 @@ handle_p2p_migration_stop (void *cls, * @param peerreq request to free */ static void -free_pending_request (struct PeerRequest *peerreq) +free_pending_request(struct PeerRequest *peerreq) { struct GSF_ConnectedPeer *cp = peerreq->cp; struct GSF_PendingRequestData *prd; - prd = GSF_pending_request_get_data_ (peerreq->pr); + prd = GSF_pending_request_get_data_(peerreq->pr); if (NULL != peerreq->kill_task) - { - GNUNET_SCHEDULER_cancel (peerreq->kill_task); - peerreq->kill_task = NULL; - } - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# P2P searches active"), - -1, - GNUNET_NO); - GNUNET_break (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (cp->request_map, - &prd->query, - peerreq)); - GNUNET_free (peerreq); + { + GNUNET_SCHEDULER_cancel(peerreq->kill_task); + peerreq->kill_task = NULL; + } + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# P2P searches active"), + -1, + GNUNET_NO); + GNUNET_break(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(cp->request_map, + &prd->query, + peerreq)); + GNUNET_free(peerreq); } @@ -739,16 +727,16 @@ free_pending_request (struct PeerRequest *peerreq) * @return #GNUNET_YES (continue to iterate) */ static int -cancel_pending_request (void *cls, - const struct GNUNET_HashCode *query, - void *value) +cancel_pending_request(void *cls, + const struct GNUNET_HashCode *query, + void *value) { struct PeerRequest *peerreq = value; struct GSF_PendingRequest *pr = peerreq->pr; - free_pending_request (peerreq); - GSF_pending_request_cancel_ (pr, - GNUNET_NO); + free_pending_request(peerreq); + GSF_pending_request_cancel_(pr, + GNUNET_NO); return GNUNET_OK; } @@ -759,17 +747,17 @@ cancel_pending_request (void *cls, * @param cls the request to free */ static void -peer_request_destroy (void *cls) +peer_request_destroy(void *cls) { struct PeerRequest *peerreq = cls; struct GSF_PendingRequest *pr = peerreq->pr; struct GSF_PendingRequestData *prd; peerreq->kill_task = NULL; - prd = GSF_pending_request_get_data_ (pr); - cancel_pending_request (NULL, - &prd->query, - peerreq); + prd = GSF_pending_request_get_data_(pr); + cancel_pending_request(NULL, + &prd->query, + peerreq); } @@ -779,20 +767,20 @@ peer_request_destroy (void *cls) * @param cls the `struct GSF_DelayedHandle` with the message */ static void -transmit_delayed_now (void *cls) +transmit_delayed_now(void *cls) { struct GSF_DelayedHandle *dh = cls; struct GSF_ConnectedPeer *cp = dh->cp; - GNUNET_CONTAINER_DLL_remove (cp->delayed_head, - cp->delayed_tail, - dh); + GNUNET_CONTAINER_DLL_remove(cp->delayed_head, + cp->delayed_tail, + dh); cp->delay_queue_size--; - GSF_peer_transmit_ (cp, - GNUNET_NO, - UINT32_MAX, - dh->env); - GNUNET_free (dh); + GSF_peer_transmit_(cp, + GNUNET_NO, + UINT32_MAX, + dh->env); + GNUNET_free(dh); } @@ -802,20 +790,20 @@ transmit_delayed_now (void *cls) * @return desired delay */ static struct GNUNET_TIME_Relative -get_randomized_delay () +get_randomized_delay() { struct GNUNET_TIME_Relative ret; ret = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, - GNUNET_CRYPTO_random_u32 - (GNUNET_CRYPTO_QUALITY_WEAK, - 2 * GSF_avg_latency.rel_value_us + 1)); + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, + GNUNET_CRYPTO_random_u32 + (GNUNET_CRYPTO_QUALITY_WEAK, + 2 * GSF_avg_latency.rel_value_us + 1)); #if INSANE_STATISTICS - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop - ("# artificial delays introduced (ms)"), - ret.rel_value_us / 1000LL, GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop + ("# artificial delays introduced (ms)"), + ret.rel_value_us / 1000LL, GNUNET_NO); #endif return ret; } @@ -840,15 +828,15 @@ get_randomized_delay () * @param data_len number of bytes in @a data */ static void -handle_p2p_reply (void *cls, - enum GNUNET_BLOCK_EvaluationResult eval, - struct GSF_PendingRequest *pr, - uint32_t reply_anonymity_level, - struct GNUNET_TIME_Absolute expiration, - struct GNUNET_TIME_Absolute last_transmission, - enum GNUNET_BLOCK_Type type, - const void *data, - size_t data_len) +handle_p2p_reply(void *cls, + enum GNUNET_BLOCK_EvaluationResult eval, + struct GSF_PendingRequest *pr, + uint32_t reply_anonymity_level, + struct GNUNET_TIME_Absolute expiration, + struct GNUNET_TIME_Absolute last_transmission, + enum GNUNET_BLOCK_Type type, + const void *data, + size_t data_len) { struct PeerRequest *peerreq = cls; struct GSF_ConnectedPeer *cp = peerreq->cp; @@ -857,96 +845,96 @@ handle_p2p_reply (void *cls, struct PutMessage *pm; size_t msize; - GNUNET_assert (data_len + sizeof (struct PutMessage) < - GNUNET_MAX_MESSAGE_SIZE); - GNUNET_assert (peerreq->pr == pr); - prd = GSF_pending_request_get_data_ (pr); + GNUNET_assert(data_len + sizeof(struct PutMessage) < + GNUNET_MAX_MESSAGE_SIZE); + GNUNET_assert(peerreq->pr == pr); + prd = GSF_pending_request_get_data_(pr); if (NULL == data) - { - free_pending_request (peerreq); - return; - } - GNUNET_break (GNUNET_BLOCK_TYPE_ANY != type); + { + free_pending_request(peerreq); + return; + } + GNUNET_break(GNUNET_BLOCK_TYPE_ANY != type); if ((prd->type != type) && (GNUNET_BLOCK_TYPE_ANY != prd->type)) - { - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop - ("# replies dropped due to type mismatch"), - 1, GNUNET_NO); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Transmitting result for query `%s' to peer\n", - GNUNET_h2s (&prd->query)); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# replies received for other peers"), - 1, GNUNET_NO); - msize = sizeof (struct PutMessage) + data_len; + { + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop + ("# replies dropped due to type mismatch"), + 1, GNUNET_NO); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Transmitting result for query `%s' to peer\n", + GNUNET_h2s(&prd->query)); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# replies received for other peers"), + 1, GNUNET_NO); + msize = sizeof(struct PutMessage) + data_len; if (msize >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return; - } - if ((UINT32_MAX != reply_anonymity_level) && (reply_anonymity_level > 1)) - { - if (reply_anonymity_level - 1 > GSF_cover_content_count) { - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop - ("# replies dropped due to insufficient cover traffic"), - 1, GNUNET_NO); + GNUNET_break(0); return; } - GSF_cover_content_count -= (reply_anonymity_level - 1); - } - - env = GNUNET_MQ_msg_extra (pm, - data_len, - GNUNET_MESSAGE_TYPE_FS_PUT); - pm->type = htonl (type); - pm->expiration = GNUNET_TIME_absolute_hton (expiration); - GNUNET_memcpy (&pm[1], - data, - data_len); - if ( (UINT32_MAX != reply_anonymity_level) && - (0 != reply_anonymity_level) && - (GNUNET_YES == GSF_enable_randomized_delays) ) - { - struct GSF_DelayedHandle *dh; - - dh = GNUNET_new (struct GSF_DelayedHandle); - dh->cp = cp; - dh->env = env; - dh->msize = msize; - GNUNET_CONTAINER_DLL_insert (cp->delayed_head, - cp->delayed_tail, - dh); - cp->delay_queue_size++; - dh->delay_task = - GNUNET_SCHEDULER_add_delayed (get_randomized_delay (), - &transmit_delayed_now, - dh); - } + if ((UINT32_MAX != reply_anonymity_level) && (reply_anonymity_level > 1)) + { + if (reply_anonymity_level - 1 > GSF_cover_content_count) + { + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop + ("# replies dropped due to insufficient cover traffic"), + 1, GNUNET_NO); + return; + } + GSF_cover_content_count -= (reply_anonymity_level - 1); + } + + env = GNUNET_MQ_msg_extra(pm, + data_len, + GNUNET_MESSAGE_TYPE_FS_PUT); + pm->type = htonl(type); + pm->expiration = GNUNET_TIME_absolute_hton(expiration); + GNUNET_memcpy(&pm[1], + data, + data_len); + if ((UINT32_MAX != reply_anonymity_level) && + (0 != reply_anonymity_level) && + (GNUNET_YES == GSF_enable_randomized_delays)) + { + struct GSF_DelayedHandle *dh; + + dh = GNUNET_new(struct GSF_DelayedHandle); + dh->cp = cp; + dh->env = env; + dh->msize = msize; + GNUNET_CONTAINER_DLL_insert(cp->delayed_head, + cp->delayed_tail, + dh); + cp->delay_queue_size++; + dh->delay_task = + GNUNET_SCHEDULER_add_delayed(get_randomized_delay(), + &transmit_delayed_now, + dh); + } else - { - GSF_peer_transmit_ (cp, - GNUNET_NO, - UINT32_MAX, - env); - } + { + GSF_peer_transmit_(cp, + GNUNET_NO, + UINT32_MAX, + env); + } if (GNUNET_BLOCK_EVALUATION_OK_LAST != eval) return; if (NULL == peerreq->kill_task) - { - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop - ("# P2P searches destroyed due to ultimate reply"), - 1, - GNUNET_NO); - peerreq->kill_task = - GNUNET_SCHEDULER_add_now (&peer_request_destroy, - peerreq); - } + { + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop + ("# P2P searches destroyed due to ultimate reply"), + 1, + GNUNET_NO); + peerreq->kill_task = + GNUNET_SCHEDULER_add_now(&peer_request_destroy, + peerreq); + } } @@ -959,31 +947,31 @@ handle_p2p_reply (void *cls, * @returns the actual change in respect (positive or negative) */ static int -change_peer_respect (struct GSF_ConnectedPeer *cp, int value) +change_peer_respect(struct GSF_ConnectedPeer *cp, int value) { if (0 == value) return 0; - GNUNET_assert (NULL != cp); + GNUNET_assert(NULL != cp); if (value > 0) - { - if (cp->ppd.respect + value < cp->ppd.respect) { - value = UINT32_MAX - cp->ppd.respect; - cp->ppd.respect = UINT32_MAX; + if (cp->ppd.respect + value < cp->ppd.respect) + { + value = UINT32_MAX - cp->ppd.respect; + cp->ppd.respect = UINT32_MAX; + } + else + cp->ppd.respect += value; } - else - cp->ppd.respect += value; - } else - { - if (cp->ppd.respect < -value) { - value = -cp->ppd.respect; - cp->ppd.respect = 0; + if (cp->ppd.respect < -value) + { + value = -cp->ppd.respect; + cp->ppd.respect = 0; + } + else + cp->ppd.respect += value; } - else - cp->ppd.respect += value; - } return value; } @@ -997,58 +985,58 @@ change_peer_respect (struct GSF_ConnectedPeer *cp, int value) * @return effective priority */ static int32_t -bound_priority (uint32_t prio_in, - struct GSF_ConnectedPeer *cp) +bound_priority(uint32_t prio_in, + struct GSF_ConnectedPeer *cp) { #define N ((double)128.0) uint32_t ret; double rret; int ld; - ld = GSF_test_get_load_too_high_ (0); + ld = GSF_test_get_load_too_high_(0); if (GNUNET_SYSERR == ld) - { + { #if INSANE_STATISTICS - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop - ("# requests done for free (low load)"), 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop + ("# requests done for free (low load)"), 1, + GNUNET_NO); #endif - return 0; /* excess resources */ - } + return 0; /* excess resources */ + } if (prio_in > INT32_MAX) prio_in = INT32_MAX; - ret = -change_peer_respect (cp, -(int) prio_in); + ret = -change_peer_respect(cp, -(int)prio_in); if (ret > 0) - { - if (ret > GSF_current_priorities + N) - rret = GSF_current_priorities + N; - else - rret = ret; - GSF_current_priorities = (GSF_current_priorities * (N - 1) + rret) / N; - } + { + if (ret > GSF_current_priorities + N) + rret = GSF_current_priorities + N; + else + rret = ret; + GSF_current_priorities = (GSF_current_priorities * (N - 1) + rret) / N; + } if ((GNUNET_YES == ld) && (ret > 0)) - { - /* try with charging */ - ld = GSF_test_get_load_too_high_ (ret); - } + { + /* try with charging */ + ld = GSF_test_get_load_too_high_(ret); + } if (GNUNET_YES == ld) - { - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop - ("# request dropped, priority insufficient"), 1, - GNUNET_NO); - /* undo charge */ - change_peer_respect (cp, (int) ret); - return -1; /* not enough resources */ - } + { + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop + ("# request dropped, priority insufficient"), 1, + GNUNET_NO); + /* undo charge */ + change_peer_respect(cp, (int)ret); + return -1; /* not enough resources */ + } else - { - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop - ("# requests done for a price (normal load)"), 1, - GNUNET_NO); - } + { + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop + ("# requests done for a price (normal load)"), 1, + GNUNET_NO); + } #undef N return ret; } @@ -1064,20 +1052,20 @@ bound_priority (uint32_t prio_in, * otherwise the ttl-limit for the given @a prio */ static int32_t -bound_ttl (int32_t ttl_in, - uint32_t prio) +bound_ttl(int32_t ttl_in, + uint32_t prio) { unsigned long long allowed; if (ttl_in <= 0) return ttl_in; - allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000; + allowed = ((unsigned long long)prio) * TTL_DECREMENT / 1000; if (ttl_in > allowed) - { - if (allowed >= (1 << 30)) - return 1 << 30; - return allowed; - } + { + if (allowed >= (1 << 30)) + return 1 << 30; + return allowed; + } return ttl_in; } @@ -1085,9 +1073,7 @@ bound_ttl (int32_t ttl_in, /** * Closure for #test_exist_cb(). */ -struct TestExistClosure -{ - +struct TestExistClosure { /** * Priority of the incoming request. */ @@ -1107,7 +1093,6 @@ struct TestExistClosure * Set to #GNUNET_YES if we are done handling the query. */ int finished; - }; @@ -1122,9 +1107,9 @@ struct TestExistClosure * #GNUNET_NO if we successfully merged */ static int -test_exist_cb (void *cls, - const struct GNUNET_HashCode *hc, - void *value) +test_exist_cb(void *cls, + const struct GNUNET_HashCode *hc, + void *value) { struct TestExistClosure *tec = cls; struct PeerRequest *peerreq = value; @@ -1132,28 +1117,28 @@ test_exist_cb (void *cls, struct GSF_PendingRequestData *prd; pr = peerreq->pr; - prd = GSF_pending_request_get_data_ (pr); + prd = GSF_pending_request_get_data_(pr); if (prd->type != tec->type) return GNUNET_YES; if (prd->ttl.abs_value_us >= - GNUNET_TIME_absolute_get ().abs_value_us + tec->ttl * 1000LL) - { - /* existing request has higher TTL, drop new one! */ - prd->priority += tec->priority; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Have existing request with higher TTL, dropping new request.\n"); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop - ("# requests dropped due to higher-TTL request"), - 1, GNUNET_NO); - tec->finished = GNUNET_YES; - return GNUNET_NO; - } + GNUNET_TIME_absolute_get().abs_value_us + tec->ttl * 1000LL) + { + /* existing request has higher TTL, drop new one! */ + prd->priority += tec->priority; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Have existing request with higher TTL, dropping new request.\n"); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop + ("# requests dropped due to higher-TTL request"), + 1, GNUNET_NO); + tec->finished = GNUNET_YES; + return GNUNET_NO; + } /* existing request has lower TTL, drop old one! */ tec->priority += prd->priority; - free_pending_request (peerreq); - GSF_pending_request_cancel_ (pr, - GNUNET_YES); + free_pending_request(peerreq); + GSF_pending_request_cancel_(pr, + GNUNET_YES); return GNUNET_NO; } @@ -1168,8 +1153,8 @@ test_exist_cb (void *cls, * @param gm the GET message */ void -handle_p2p_get (void *cls, - const struct GetMessage *gm) +handle_p2p_get(void *cls, + const struct GetMessage *gm) { struct GSF_ConnectedPeer *cps = cls; struct PeerRequest *peerreq; @@ -1187,167 +1172,167 @@ handle_p2p_get (void *cls, GNUNET_PEER_Id spid; const struct GSF_PendingRequestData *prd; - msize = ntohs (gm->header.size); - tec.type = ntohl (gm->type); - bm = ntohl (gm->hash_bitmap); + msize = ntohs(gm->header.size); + tec.type = ntohl(gm->type); + bm = ntohl(gm->hash_bitmap); bits = 0; while (bm > 0) - { - if (1 == (bm & 1)) - bits++; - bm >>= 1; - } - opt = (const struct GNUNET_PeerIdentity *) &gm[1]; - bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (struct GNUNET_PeerIdentity); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop - ("# GET requests received (from other peers)"), - 1, - GNUNET_NO); + { + if (1 == (bm & 1)) + bits++; + bm >>= 1; + } + opt = (const struct GNUNET_PeerIdentity *)&gm[1]; + bfsize = msize - sizeof(struct GetMessage) - bits * sizeof(struct GNUNET_PeerIdentity); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop + ("# GET requests received (from other peers)"), + 1, + GNUNET_NO); GSF_cover_query_count++; - bm = ntohl (gm->hash_bitmap); + bm = ntohl(gm->hash_bitmap); bits = 0; if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO)) - cp = GSF_peer_get_ (&opt[bits++]); + cp = GSF_peer_get_(&opt[bits++]); else cp = cps; if (NULL == cp) - { - if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO)) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Failed to find RETURN-TO peer `%s' in connection set. Dropping query.\n", - GNUNET_i2s (&opt[bits - 1])); - - else - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Failed to find peer `%s' in connection set. Dropping query.\n", - GNUNET_i2s (cps->ppd.peer)); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop - ("# requests dropped due to missing reverse route"), - 1, - GNUNET_NO); - return; - } - unsigned int queue_size = GNUNET_MQ_get_length (cp->mq); + { + if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO)) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Failed to find RETURN-TO peer `%s' in connection set. Dropping query.\n", + GNUNET_i2s(&opt[bits - 1])); + + else + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Failed to find peer `%s' in connection set. Dropping query.\n", + GNUNET_i2s(cps->ppd.peer)); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop + ("# requests dropped due to missing reverse route"), + 1, + GNUNET_NO); + return; + } + unsigned int queue_size = GNUNET_MQ_get_length(cp->mq); queue_size += cp->ppd.pending_replies + cp->delay_queue_size; if (queue_size > MAX_QUEUE_PER_PEER) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Peer `%s' has too many replies queued already. Dropping query.\n", - GNUNET_i2s (cps->ppd.peer)); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# requests dropped due to full reply queue"), - 1, - GNUNET_NO); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Peer `%s' has too many replies queued already. Dropping query.\n", + GNUNET_i2s(cps->ppd.peer)); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# requests dropped due to full reply queue"), + 1, + GNUNET_NO); + return; + } /* note that we can really only check load here since otherwise * peers could find out that we are overloaded by not being * disconnected after sending us a malformed query... */ - tec.priority = bound_priority (ntohl (gm->priority), - cps); + tec.priority = bound_priority(ntohl(gm->priority), + cps); if (tec.priority < 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Dropping query from `%s', this peer is too busy.\n", - GNUNET_i2s (cps->ppd.peer)); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received request for `%s' of type %u from peer `%s' with flags %u\n", - GNUNET_h2s (&gm->query), - (unsigned int) tec.type, - GNUNET_i2s (cps->ppd.peer), - (unsigned int) bm); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Dropping query from `%s', this peer is too busy.\n", + GNUNET_i2s(cps->ppd.peer)); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received request for `%s' of type %u from peer `%s' with flags %u\n", + GNUNET_h2s(&gm->query), + (unsigned int)tec.type, + GNUNET_i2s(cps->ppd.peer), + (unsigned int)bm); target = - (0 != - (bm & GET_MESSAGE_BIT_TRANSMIT_TO)) ? (&opt[bits++]) : NULL; + (0 != + (bm & GET_MESSAGE_BIT_TRANSMIT_TO)) ? (&opt[bits++]) : NULL; options = GSF_PRO_DEFAULTS; spid = 0; - if ((GNUNET_LOAD_get_load (cp->ppd.transmission_delay) > 3 * (1 + tec.priority)) - || (GNUNET_LOAD_get_average (cp->ppd.transmission_delay) > + if ((GNUNET_LOAD_get_load(cp->ppd.transmission_delay) > 3 * (1 + tec.priority)) + || (GNUNET_LOAD_get_average(cp->ppd.transmission_delay) > GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value_us * 2 + - GNUNET_LOAD_get_average (GSF_rt_entry_lifetime))) - { - /* don't have BW to send to peer, or would likely take longer than we have for it, - * so at best indirect the query */ - tec.priority = 0; - options |= GSF_PRO_FORWARD_ONLY; - spid = GNUNET_PEER_intern (cps->ppd.peer); - GNUNET_assert (0 != spid); - } - tec.ttl = bound_ttl (ntohl (gm->ttl), - tec.priority); + GNUNET_LOAD_get_average(GSF_rt_entry_lifetime))) + { + /* don't have BW to send to peer, or would likely take longer than we have for it, + * so at best indirect the query */ + tec.priority = 0; + options |= GSF_PRO_FORWARD_ONLY; + spid = GNUNET_PEER_intern(cps->ppd.peer); + GNUNET_assert(0 != spid); + } + tec.ttl = bound_ttl(ntohl(gm->ttl), + tec.priority); /* decrement ttl (always) */ ttl_decrement = - 2 * TTL_DECREMENT + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - TTL_DECREMENT); - if ( (tec.ttl < 0) && - (((int32_t) (tec.ttl - ttl_decrement)) > 0) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Dropping query from `%s' due to TTL underflow (%d - %u).\n", - GNUNET_i2s (cps->ppd.peer), - tec.ttl, - ttl_decrement); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop - ("# requests dropped due TTL underflow"), 1, - GNUNET_NO); - /* integer underflow => drop (should be very rare)! */ - return; - } + 2 * TTL_DECREMENT + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + TTL_DECREMENT); + if ((tec.ttl < 0) && + (((int32_t)(tec.ttl - ttl_decrement)) > 0)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Dropping query from `%s' due to TTL underflow (%d - %u).\n", + GNUNET_i2s(cps->ppd.peer), + tec.ttl, + ttl_decrement); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop + ("# requests dropped due TTL underflow"), 1, + GNUNET_NO); + /* integer underflow => drop (should be very rare)! */ + return; + } tec.ttl -= ttl_decrement; /* test if the request already exists */ tec.finished = GNUNET_NO; - GNUNET_CONTAINER_multihashmap_get_multiple (cp->request_map, - &gm->query, - &test_exist_cb, - &tec); + GNUNET_CONTAINER_multihashmap_get_multiple(cp->request_map, + &gm->query, + &test_exist_cb, + &tec); if (GNUNET_YES == tec.finished) return; /* merged into existing request, we're done */ - peerreq = GNUNET_new (struct PeerRequest); + peerreq = GNUNET_new(struct PeerRequest); peerreq->cp = cp; - pr = GSF_pending_request_create_ (options, - tec.type, - &gm->query, - target, - (bfsize > 0) - ? (const char *) &opt[bits] - : NULL, - bfsize, - ntohl (gm->filter_mutator), - 1 /* anonymity */, - (uint32_t) tec.priority, - tec.ttl, - spid, - GNUNET_PEER_intern (cps->ppd.peer), - NULL, 0, /* replies_seen */ - &handle_p2p_reply, - peerreq); - GNUNET_assert (NULL != pr); - prd = GSF_pending_request_get_data_ (pr); + pr = GSF_pending_request_create_(options, + tec.type, + &gm->query, + target, + (bfsize > 0) + ? (const char *)&opt[bits] + : NULL, + bfsize, + ntohl(gm->filter_mutator), + 1 /* anonymity */, + (uint32_t)tec.priority, + tec.ttl, + spid, + GNUNET_PEER_intern(cps->ppd.peer), + NULL, 0, /* replies_seen */ + &handle_p2p_reply, + peerreq); + GNUNET_assert(NULL != pr); + prd = GSF_pending_request_get_data_(pr); peerreq->pr = pr; - GNUNET_break (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (cp->request_map, - &prd->query, - peerreq, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# P2P query messages received and processed"), - 1, - GNUNET_NO); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# P2P searches active"), - 1, - GNUNET_NO); - GSF_pending_request_get_data_ (pr)->has_started = GNUNET_YES; - GSF_local_lookup_ (pr, - &GSF_consider_forwarding, - NULL); + GNUNET_break(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(cp->request_map, + &prd->query, + peerreq, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# P2P query messages received and processed"), + 1, + GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# P2P searches active"), + 1, + GNUNET_NO); + GSF_pending_request_get_data_(pr)->has_started = GNUNET_YES; + GSF_local_lookup_(pr, + &GSF_consider_forwarding, + NULL); } @@ -1359,22 +1344,22 @@ handle_p2p_get (void *cls, * @param cp target peer * @param is_query is this a query (#GNUNET_YES) or content (#GNUNET_NO) or neither (#GNUNET_SYSERR) * @param priority how important is this request? - * @param timeout when does this request timeout + * @param timeout when does this request timeout * @param size number of bytes we would like to send to the peer * @param env message to send */ void -GSF_peer_transmit_ (struct GSF_ConnectedPeer *cp, - int is_query, - uint32_t priority, - struct GNUNET_MQ_Envelope *env) +GSF_peer_transmit_(struct GSF_ConnectedPeer *cp, + int is_query, + uint32_t priority, + struct GNUNET_MQ_Envelope *env) { struct GSF_PeerTransmitHandle *pth; struct GSF_PeerTransmitHandle *pos; struct GSF_PeerTransmitHandle *prev; - pth = GNUNET_new (struct GSF_PeerTransmitHandle); - pth->transmission_request_start_time = GNUNET_TIME_absolute_get (); + pth = GNUNET_new(struct GSF_PeerTransmitHandle); + pth->transmission_request_start_time = GNUNET_TIME_absolute_get(); pth->env = env; pth->is_query = is_query; pth->priority = priority; @@ -1383,19 +1368,19 @@ GSF_peer_transmit_ (struct GSF_ConnectedPeer *cp, prev = NULL; pos = cp->pth_head; while ((NULL != pos) && (pos->priority > priority)) - { - prev = pos; - pos = pos->next; - } - GNUNET_CONTAINER_DLL_insert_after (cp->pth_head, - cp->pth_tail, - prev, - pth); + { + prev = pos; + pos = pos->next; + } + GNUNET_CONTAINER_DLL_insert_after(cp->pth_head, + cp->pth_tail, + prev, + pth); if (GNUNET_YES == is_query) cp->ppd.pending_queries++; else if (GNUNET_NO == is_query) cp->ppd.pending_replies++; - schedule_transmission (pth); + schedule_transmission(pth); } @@ -1407,19 +1392,19 @@ GSF_peer_transmit_ (struct GSF_ConnectedPeer *cp, * @param request_priority priority of the original request */ void -GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp, - struct GNUNET_TIME_Absolute request_time, - uint32_t request_priority) +GSF_peer_update_performance_(struct GSF_ConnectedPeer *cp, + struct GNUNET_TIME_Absolute request_time, + uint32_t request_priority) { struct GNUNET_TIME_Relative delay; - delay = GNUNET_TIME_absolute_get_duration (request_time); + delay = GNUNET_TIME_absolute_get_duration(request_time); cp->ppd.avg_reply_delay.rel_value_us = - (cp->ppd.avg_reply_delay.rel_value_us * (RUNAVG_DELAY_N - 1) + - delay.rel_value_us) / RUNAVG_DELAY_N; + (cp->ppd.avg_reply_delay.rel_value_us * (RUNAVG_DELAY_N - 1) + + delay.rel_value_us) / RUNAVG_DELAY_N; cp->ppd.avg_priority = - (cp->ppd.avg_priority * (RUNAVG_DELAY_N - 1) + - request_priority) / RUNAVG_DELAY_N; + (cp->ppd.avg_priority * (RUNAVG_DELAY_N - 1) + + request_priority) / RUNAVG_DELAY_N; } @@ -1431,8 +1416,8 @@ GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp, * @param initiator_client local client on responsible for query */ void -GSF_peer_update_responder_client_ (struct GSF_ConnectedPeer *cp, - struct GSF_LocalClient *initiator_client) +GSF_peer_update_responder_client_(struct GSF_ConnectedPeer *cp, + struct GSF_LocalClient *initiator_client) { cp->ppd.last_client_replies[cp->last_client_replies_woff++ % CS2P_SUCCESS_LIST_SIZE] = initiator_client; @@ -1447,15 +1432,15 @@ GSF_peer_update_responder_client_ (struct GSF_ConnectedPeer *cp, * @param initiator_peer other peer responsible for query */ void -GSF_peer_update_responder_peer_ (struct GSF_ConnectedPeer *cp, - const struct GSF_ConnectedPeer *initiator_peer) +GSF_peer_update_responder_peer_(struct GSF_ConnectedPeer *cp, + const struct GSF_ConnectedPeer *initiator_peer) { unsigned int woff; woff = cp->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE; - GNUNET_PEER_change_rc (cp->ppd.last_p2p_replies[woff], -1); + GNUNET_PEER_change_rc(cp->ppd.last_p2p_replies[woff], -1); cp->ppd.last_p2p_replies[woff] = initiator_peer->ppd.pid; - GNUNET_PEER_change_rc (initiator_peer->ppd.pid, 1); + GNUNET_PEER_change_rc(initiator_peer->ppd.pid, 1); cp->last_p2p_replies_woff = (woff + 1) % P2P_SUCCESS_LIST_SIZE; } @@ -1469,23 +1454,23 @@ GSF_peer_update_responder_peer_ (struct GSF_ConnectedPeer *cp, * @return #GNUNET_OK to continue iteration */ static int -flush_respect (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +flush_respect(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct GSF_ConnectedPeer *cp = value; struct GNUNET_PeerIdentity pid; if (cp->ppd.respect == cp->disk_respect) return GNUNET_OK; /* unchanged */ - GNUNET_assert (0 != cp->ppd.pid); - GNUNET_PEER_resolve (cp->ppd.pid, &pid); - GNUNET_PEERSTORE_store (peerstore, "fs", &pid, "respect", &cp->ppd.respect, - sizeof (cp->ppd.respect), - GNUNET_TIME_UNIT_FOREVER_ABS, - GNUNET_PEERSTORE_STOREOPTION_REPLACE, - NULL, - NULL); + GNUNET_assert(0 != cp->ppd.pid); + GNUNET_PEER_resolve(cp->ppd.pid, &pid); + GNUNET_PEERSTORE_store(peerstore, "fs", &pid, "respect", &cp->ppd.respect, + sizeof(cp->ppd.respect), + GNUNET_TIME_UNIT_FOREVER_ABS, + GNUNET_PEERSTORE_STOREOPTION_REPLACE, + NULL, + NULL); return GNUNET_OK; } @@ -1499,9 +1484,9 @@ flush_respect (void *cls, * @param internal_cls the corresponding `struct GSF_ConnectedPeer` */ void -GSF_peer_disconnect_handler (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *internal_cls) +GSF_peer_disconnect_handler(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *internal_cls) { struct GSF_ConnectedPeer *cp = internal_cls; struct GSF_PeerTransmitHandle *pth; @@ -1509,84 +1494,83 @@ GSF_peer_disconnect_handler (void *cls, if (NULL == cp) return; /* must have been disconnect from core with - * 'peer' == my_id, ignore */ - flush_respect (NULL, - peer, - cp); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (cp_map, - peer, - cp)); - GNUNET_STATISTICS_set (GSF_stats, - gettext_noop ("# peers connected"), - GNUNET_CONTAINER_multipeermap_size (cp_map), - GNUNET_NO); + * 'peer' == my_id, ignore */ + flush_respect(NULL, + peer, + cp); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(cp_map, + peer, + cp)); + GNUNET_STATISTICS_set(GSF_stats, + gettext_noop("# peers connected"), + GNUNET_CONTAINER_multipeermap_size(cp_map), + GNUNET_NO); if (NULL != cp->respect_iterate_req) - { - GNUNET_PEERSTORE_iterate_cancel (cp->respect_iterate_req); - cp->respect_iterate_req = NULL; - } + { + GNUNET_PEERSTORE_iterate_cancel(cp->respect_iterate_req); + cp->respect_iterate_req = NULL; + } if (NULL != cp->rc) - { - GNUNET_ATS_reserve_bandwidth_cancel (cp->rc); - cp->rc = NULL; - } + { + GNUNET_ATS_reserve_bandwidth_cancel(cp->rc); + cp->rc = NULL; + } if (NULL != cp->rc_delay_task) - { - GNUNET_SCHEDULER_cancel (cp->rc_delay_task); - cp->rc_delay_task = NULL; - } - GNUNET_CONTAINER_multihashmap_iterate (cp->request_map, - &cancel_pending_request, - cp); - GNUNET_CONTAINER_multihashmap_destroy (cp->request_map); + { + GNUNET_SCHEDULER_cancel(cp->rc_delay_task); + cp->rc_delay_task = NULL; + } + GNUNET_CONTAINER_multihashmap_iterate(cp->request_map, + &cancel_pending_request, + cp); + GNUNET_CONTAINER_multihashmap_destroy(cp->request_map); cp->request_map = NULL; - GSF_plan_notify_peer_disconnect_ (cp); - GNUNET_LOAD_value_free (cp->ppd.transmission_delay); - GNUNET_PEER_decrement_rcs (cp->ppd.last_p2p_replies, - P2P_SUCCESS_LIST_SIZE); - memset (cp->ppd.last_p2p_replies, - 0, - sizeof (cp->ppd.last_p2p_replies)); - GSF_push_stop_ (cp); + GSF_plan_notify_peer_disconnect_(cp); + GNUNET_LOAD_value_free(cp->ppd.transmission_delay); + GNUNET_PEER_decrement_rcs(cp->ppd.last_p2p_replies, + P2P_SUCCESS_LIST_SIZE); + memset(cp->ppd.last_p2p_replies, + 0, + sizeof(cp->ppd.last_p2p_replies)); + GSF_push_stop_(cp); while (NULL != (pth = cp->pth_head)) - { - GNUNET_CONTAINER_DLL_remove (cp->pth_head, - cp->pth_tail, - pth); - if (GNUNET_YES == pth->is_query) - GNUNET_assert (0 < cp->ppd.pending_queries--); - else if (GNUNET_NO == pth->is_query) - GNUNET_assert (0 < cp->ppd.pending_replies--); - GNUNET_free (pth); - } + { + GNUNET_CONTAINER_DLL_remove(cp->pth_head, + cp->pth_tail, + pth); + if (GNUNET_YES == pth->is_query) + GNUNET_assert(0 < cp->ppd.pending_queries--); + else if (GNUNET_NO == pth->is_query) + GNUNET_assert(0 < cp->ppd.pending_replies--); + GNUNET_free(pth); + } while (NULL != (dh = cp->delayed_head)) - { - GNUNET_CONTAINER_DLL_remove (cp->delayed_head, - cp->delayed_tail, - dh); - GNUNET_MQ_discard (dh->env); - cp->delay_queue_size--; - GNUNET_SCHEDULER_cancel (dh->delay_task); - GNUNET_free (dh); - } - GNUNET_PEER_change_rc (cp->ppd.pid, -1); + { + GNUNET_CONTAINER_DLL_remove(cp->delayed_head, + cp->delayed_tail, + dh); + GNUNET_MQ_discard(dh->env); + cp->delay_queue_size--; + GNUNET_SCHEDULER_cancel(dh->delay_task); + GNUNET_free(dh); + } + GNUNET_PEER_change_rc(cp->ppd.pid, -1); if (NULL != cp->mig_revive_task) - { - GNUNET_SCHEDULER_cancel (cp->mig_revive_task); - cp->mig_revive_task = NULL; - } - GNUNET_break (0 == cp->ppd.pending_queries); - GNUNET_break (0 == cp->ppd.pending_replies); - GNUNET_free (cp); + { + GNUNET_SCHEDULER_cancel(cp->mig_revive_task); + cp->mig_revive_task = NULL; + } + GNUNET_break(0 == cp->ppd.pending_queries); + GNUNET_break(0 == cp->ppd.pending_replies); + GNUNET_free(cp); } /** * Closure for #call_iterator(). */ -struct IterationContext -{ +struct IterationContext { /** * Function to call on each entry. */ @@ -1608,16 +1592,16 @@ struct IterationContext * @return #GNUNET_YES to continue iteration */ static int -call_iterator (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +call_iterator(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct IterationContext *ic = cls; struct GSF_ConnectedPeer *cp = value; - ic->it (ic->it_cls, - key, cp, - &cp->ppd); + ic->it(ic->it_cls, + key, cp, + &cp->ppd); return GNUNET_YES; } @@ -1629,16 +1613,16 @@ call_iterator (void *cls, * @param it_cls closure for @a it */ void -GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it, - void *it_cls) +GSF_iterate_connected_peers_(GSF_ConnectedPeerIterator it, + void *it_cls) { struct IterationContext ic; ic.it = it; ic.it_cls = it_cls; - GNUNET_CONTAINER_multipeermap_iterate (cp_map, - &call_iterator, - &ic); + GNUNET_CONTAINER_multipeermap_iterate(cp_map, + &call_iterator, + &ic); } @@ -1649,11 +1633,11 @@ GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it, * @param id identity to set (written to) */ void -GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp, - struct GNUNET_PeerIdentity *id) +GSF_connected_peer_get_identity_(const struct GSF_ConnectedPeer *cp, + struct GNUNET_PeerIdentity *id) { - GNUNET_assert (0 != cp->ppd.pid); - GNUNET_PEER_resolve (cp->ppd.pid, id); + GNUNET_assert(0 != cp->ppd.pid); + GNUNET_PEER_resolve(cp->ppd.pid, id); } @@ -1664,10 +1648,10 @@ GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp, * @return reference to peer identity, valid until peer disconnects (!) */ const struct GNUNET_PeerIdentity * -GSF_connected_peer_get_identity2_ (const struct GSF_ConnectedPeer *cp) +GSF_connected_peer_get_identity2_(const struct GSF_ConnectedPeer *cp) { - GNUNET_assert (0 != cp->ppd.pid); - return GNUNET_PEER_resolve2 (cp->ppd.pid); + GNUNET_assert(0 != cp->ppd.pid); + return GNUNET_PEER_resolve2(cp->ppd.pid); } @@ -1679,38 +1663,38 @@ GSF_connected_peer_get_identity2_ (const struct GSF_ConnectedPeer *cp) * @param block_time until when to block */ void -GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp, - struct GNUNET_TIME_Absolute block_time) +GSF_block_peer_migration_(struct GSF_ConnectedPeer *cp, + struct GNUNET_TIME_Absolute block_time) { struct GNUNET_MQ_Envelope *env; struct MigrationStopMessage *msm; - + if (cp->last_migration_block.abs_value_us > block_time.abs_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Migration already blocked for another %s\n", - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining - (cp->last_migration_block), GNUNET_YES)); - return; /* already blocked */ - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Asking to stop migration for %s\n", - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (block_time), - GNUNET_YES)); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Migration already blocked for another %s\n", + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_remaining + (cp->last_migration_block), GNUNET_YES)); + return; /* already blocked */ + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Asking to stop migration for %s\n", + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_remaining(block_time), + GNUNET_YES)); cp->last_migration_block = block_time; - env = GNUNET_MQ_msg (msm, - GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP); - msm->reserved = htonl (0); + env = GNUNET_MQ_msg(msm, + GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP); + msm->reserved = htonl(0); msm->duration - = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining - (cp->last_migration_block)); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# migration stop messages sent"), - 1, - GNUNET_NO); - GSF_peer_transmit_ (cp, - GNUNET_SYSERR, - UINT32_MAX, - env); + = GNUNET_TIME_relative_hton(GNUNET_TIME_absolute_get_remaining + (cp->last_migration_block)); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# migration stop messages sent"), + 1, + GNUNET_NO); + GSF_peer_transmit_(cp, + GNUNET_SYSERR, + UINT32_MAX, + env); } @@ -1724,8 +1708,8 @@ GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp, * @param pref preference change */ void -GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp, - uint64_t pref) +GSF_connected_peer_change_preference_(struct GSF_ConnectedPeer *cp, + uint64_t pref) { cp->inc_preference += pref; } @@ -1737,15 +1721,15 @@ GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp, * @param cls closure, not used */ static void -cron_flush_respect (void *cls) +cron_flush_respect(void *cls) { fr_task = NULL; - GNUNET_CONTAINER_multipeermap_iterate (cp_map, - &flush_respect, - NULL); - fr_task = GNUNET_SCHEDULER_add_delayed_with_priority (RESPECT_FLUSH_FREQ, - GNUNET_SCHEDULER_PRIORITY_HIGH, - &cron_flush_respect, NULL); + GNUNET_CONTAINER_multipeermap_iterate(cp_map, + &flush_respect, + NULL); + fr_task = GNUNET_SCHEDULER_add_delayed_with_priority(RESPECT_FLUSH_FREQ, + GNUNET_SCHEDULER_PRIORITY_HIGH, + &cron_flush_respect, NULL); } @@ -1753,12 +1737,12 @@ cron_flush_respect (void *cls) * Initialize peer management subsystem. */ void -GSF_connected_peer_init_ () +GSF_connected_peer_init_() { - cp_map = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES); - peerstore = GNUNET_PEERSTORE_connect (GSF_cfg); - fr_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH, - &cron_flush_respect, NULL); + cp_map = GNUNET_CONTAINER_multipeermap_create(128, GNUNET_YES); + peerstore = GNUNET_PEERSTORE_connect(GSF_cfg); + fr_task = GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_HIGH, + &cron_flush_respect, NULL); } @@ -1766,18 +1750,17 @@ GSF_connected_peer_init_ () * Shutdown peer management subsystem. */ void -GSF_connected_peer_done_ () +GSF_connected_peer_done_() { - GNUNET_CONTAINER_multipeermap_iterate (cp_map, - &flush_respect, - NULL); - GNUNET_SCHEDULER_cancel (fr_task); + GNUNET_CONTAINER_multipeermap_iterate(cp_map, + &flush_respect, + NULL); + GNUNET_SCHEDULER_cancel(fr_task); fr_task = NULL; - GNUNET_CONTAINER_multipeermap_destroy (cp_map); + GNUNET_CONTAINER_multipeermap_destroy(cp_map); cp_map = NULL; - GNUNET_PEERSTORE_disconnect (peerstore, - GNUNET_YES); - + GNUNET_PEERSTORE_disconnect(peerstore, + GNUNET_YES); } @@ -1790,9 +1773,9 @@ GSF_connected_peer_done_ () * @return #GNUNET_YES (we should continue to iterate) */ static int -clean_local_client (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +clean_local_client(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { const struct GSF_LocalClient *lc = cls; struct GSF_ConnectedPeer *cp = value; @@ -1812,13 +1795,13 @@ clean_local_client (void *cls, * @param lc handle to the local client (henceforth invalid) */ void -GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc) +GSF_handle_local_client_disconnect_(const struct GSF_LocalClient *lc) { if (NULL == cp_map) return; /* already cleaned up */ - GNUNET_CONTAINER_multipeermap_iterate (cp_map, - &clean_local_client, - (void *) lc); + GNUNET_CONTAINER_multipeermap_iterate(cp_map, + &clean_local_client, + (void *)lc); } diff --git a/src/fs/gnunet-service-fs_cp.h b/src/fs/gnunet-service-fs_cp.h index 486b696ba..9eab3d9de 100644 --- a/src/fs/gnunet-service-fs_cp.h +++ b/src/fs/gnunet-service-fs_cp.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_cp.h @@ -60,9 +60,7 @@ /** * Performance data kept for a peer. */ -struct GSF_PeerPerformanceData -{ - +struct GSF_PeerPerformanceData { /** * List of the last clients for which this peer successfully * answered a query. @@ -128,7 +126,7 @@ struct GSF_PeerPerformanceData * The peer's identity (pointer). */ const struct GNUNET_PeerIdentity *peer; - + /** * Respect rating for this peer */ @@ -143,7 +141,6 @@ struct GSF_PeerPerformanceData * Number of pending replies (queries are not counted) */ unsigned int pending_replies; - }; @@ -205,9 +202,9 @@ struct GSF_PeerTransmitHandle; * @return internal handle for the peer */ void * -GSF_peer_connect_handler (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq); +GSF_peer_connect_handler(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq); /** @@ -217,7 +214,7 @@ GSF_peer_connect_handler (void *cls, * @return NULL if this peer is not currently connected */ struct GSF_ConnectedPeer * -GSF_peer_get_ (const struct GNUNET_PeerIdentity *peer); +GSF_peer_get_(const struct GNUNET_PeerIdentity *peer); /** @@ -227,8 +224,8 @@ GSF_peer_get_ (const struct GNUNET_PeerIdentity *peer); * @param latency current latency value */ void -GSF_update_peer_latency_ (const struct GNUNET_PeerIdentity *id, - struct GNUNET_TIME_Relative latency); +GSF_update_peer_latency_(const struct GNUNET_PeerIdentity *id, + struct GNUNET_TIME_Relative latency); /** @@ -242,10 +239,10 @@ GSF_update_peer_latency_ (const struct GNUNET_PeerIdentity *id, * @param env envelope of message to send */ void -GSF_peer_transmit_ (struct GSF_ConnectedPeer *cp, - int is_query, - uint32_t priority, - struct GNUNET_MQ_Envelope *env); +GSF_peer_transmit_(struct GSF_ConnectedPeer *cp, + int is_query, + uint32_t priority, + struct GNUNET_MQ_Envelope *env); /** @@ -256,9 +253,9 @@ GSF_peer_transmit_ (struct GSF_ConnectedPeer *cp, * @param request_priority priority of the original request */ void -GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp, - struct GNUNET_TIME_Absolute request_time, - uint32_t request_priority); +GSF_peer_update_performance_(struct GSF_ConnectedPeer *cp, + struct GNUNET_TIME_Absolute request_time, + uint32_t request_priority); /** @@ -269,8 +266,8 @@ GSF_peer_update_performance_ (struct GSF_ConnectedPeer *cp, * @param initiator_client local client on responsible for query */ void -GSF_peer_update_responder_client_ (struct GSF_ConnectedPeer *cp, - struct GSF_LocalClient *initiator_client); +GSF_peer_update_responder_client_(struct GSF_ConnectedPeer *cp, + struct GSF_LocalClient *initiator_client); /** @@ -281,9 +278,9 @@ GSF_peer_update_responder_client_ (struct GSF_ConnectedPeer *cp, * @param initiator_peer other peer responsible for query */ void -GSF_peer_update_responder_peer_ (struct GSF_ConnectedPeer *cp, - const struct GSF_ConnectedPeer - *initiator_peer); +GSF_peer_update_responder_peer_(struct GSF_ConnectedPeer *cp, + const struct GSF_ConnectedPeer + *initiator_peer); /** @@ -293,8 +290,8 @@ GSF_peer_update_responder_peer_ (struct GSF_ConnectedPeer *cp, * @param msm the actual message */ void -handle_p2p_migration_stop (void *cls, - const struct MigrationStopMessage *message); +handle_p2p_migration_stop(void *cls, + const struct MigrationStopMessage *message); /** @@ -304,8 +301,8 @@ handle_p2p_migration_stop (void *cls, * @param gm the actual message */ void -handle_p2p_get (void *cls, - const struct GetMessage *gm); +handle_p2p_get(void *cls, + const struct GetMessage *gm); /** @@ -315,7 +312,7 @@ handle_p2p_get (void *cls, * @return performance data record for the peer */ struct GSF_PeerPerformanceData * -GSF_get_peer_performance_data_ (struct GSF_ConnectedPeer *cp); +GSF_get_peer_performance_data_(struct GSF_ConnectedPeer *cp); /** @@ -326,8 +323,8 @@ GSF_get_peer_performance_data_ (struct GSF_ConnectedPeer *cp); * @param block_time until when to block */ void -GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp, - struct GNUNET_TIME_Absolute block_time); +GSF_block_peer_migration_(struct GSF_ConnectedPeer *cp, + struct GNUNET_TIME_Absolute block_time); /** @@ -339,9 +336,9 @@ GSF_block_peer_migration_ (struct GSF_ConnectedPeer *cp, * @param internal_cls our `struct GSF_ConnectedPeer` for @a peer */ void -GSF_peer_disconnect_handler (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *internal_cls); +GSF_peer_disconnect_handler(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *internal_cls); /** @@ -351,7 +348,7 @@ GSF_peer_disconnect_handler (void *cls, * @param lc handle to the local client (henceforth invalid) */ void -GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc); +GSF_handle_local_client_disconnect_(const struct GSF_LocalClient *lc); /** @@ -364,8 +361,8 @@ GSF_handle_local_client_disconnect_ (const struct GSF_LocalClient *lc); * @param pref preference change */ void -GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp, - uint64_t pref); +GSF_connected_peer_change_preference_(struct GSF_ConnectedPeer *cp, + uint64_t pref); /** @@ -375,8 +372,8 @@ GSF_connected_peer_change_preference_ (struct GSF_ConnectedPeer *cp, * @param id identity to set (written to) */ void -GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp, - struct GNUNET_PeerIdentity *id); +GSF_connected_peer_get_identity_(const struct GSF_ConnectedPeer *cp, + struct GNUNET_PeerIdentity *id); /** @@ -386,7 +383,7 @@ GSF_connected_peer_get_identity_ (const struct GSF_ConnectedPeer *cp, * @return reference to peer identity, valid until peer disconnects (!) */ const struct GNUNET_PeerIdentity * -GSF_connected_peer_get_identity2_ (const struct GSF_ConnectedPeer *cp); +GSF_connected_peer_get_identity2_(const struct GSF_ConnectedPeer *cp); @@ -397,21 +394,21 @@ GSF_connected_peer_get_identity2_ (const struct GSF_ConnectedPeer *cp); * @param it_cls closure for it */ void -GSF_iterate_connected_peers_ (GSF_ConnectedPeerIterator it, void *it_cls); +GSF_iterate_connected_peers_(GSF_ConnectedPeerIterator it, void *it_cls); /** * Initialize peer management subsystem. */ void -GSF_connected_peer_init_ (void); +GSF_connected_peer_init_(void); /** * Shutdown peer management subsystem. */ void -GSF_connected_peer_done_ (void); +GSF_connected_peer_done_(void); #endif diff --git a/src/fs/gnunet-service-fs_indexing.c b/src/fs/gnunet-service-fs_indexing.c index df5f70b3d..e21b2ca57 100644 --- a/src/fs/gnunet-service-fs_indexing.c +++ b/src/fs/gnunet-service-fs_indexing.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_indexing.c @@ -39,9 +39,7 @@ * In-memory information about indexed files (also available * on-disk). */ -struct IndexInfo -{ - +struct IndexInfo { /** * This is a doubly linked list. */ @@ -110,44 +108,44 @@ static struct GNUNET_DATASTORE_Handle *dsh; * Write the current index information list to disk. */ static void -write_index_list () +write_index_list() { struct GNUNET_BIO_WriteHandle *wh; char *fn; struct IndexInfo *pos; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (cfg, "FS", "INDEXDB", &fn)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "fs", - "INDEXDB"); - return; - } - wh = GNUNET_BIO_write_open (fn); + GNUNET_CONFIGURATION_get_value_filename(cfg, "FS", "INDEXDB", &fn)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "fs", + "INDEXDB"); + return; + } + wh = GNUNET_BIO_write_open(fn); if (NULL == wh) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - _ ("Could not open `%s'.\n"), - fn); - GNUNET_free (fn); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + _("Could not open `%s'.\n"), + fn); + GNUNET_free(fn); + return; + } for (pos = indexed_files_head; NULL != pos; pos = pos->next) - if ((GNUNET_OK != GNUNET_BIO_write (wh, - &pos->file_id, - sizeof (struct GNUNET_HashCode))) || - (GNUNET_OK != GNUNET_BIO_write_string (wh, pos->filename))) + if ((GNUNET_OK != GNUNET_BIO_write(wh, + &pos->file_id, + sizeof(struct GNUNET_HashCode))) || + (GNUNET_OK != GNUNET_BIO_write_string(wh, pos->filename))) break; - if (GNUNET_OK != GNUNET_BIO_write_close (wh)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - _ ("Error writing `%s'.\n"), - fn); - GNUNET_free (fn); - return; - } - GNUNET_free (fn); + if (GNUNET_OK != GNUNET_BIO_write_close(wh)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + _("Error writing `%s'.\n"), + fn); + GNUNET_free(fn); + return; + } + GNUNET_free(fn); } @@ -155,7 +153,7 @@ write_index_list () * Read index information from disk. */ static void -read_index_list () +read_index_list() { struct GNUNET_BIO_ReadHandle *rh; char *fn; @@ -166,59 +164,59 @@ read_index_list () char *emsg; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (cfg, "FS", "INDEXDB", &fn)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "fs", - "INDEXDB"); - return; - } - if (GNUNET_NO == GNUNET_DISK_file_test (fn)) - { - /* no index info yet */ - GNUNET_free (fn); - return; - } - rh = GNUNET_BIO_read_open (fn); + GNUNET_CONFIGURATION_get_value_filename(cfg, "FS", "INDEXDB", &fn)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "fs", + "INDEXDB"); + return; + } + if (GNUNET_NO == GNUNET_DISK_file_test(fn)) + { + /* no index info yet */ + GNUNET_free(fn); + return; + } + rh = GNUNET_BIO_read_open(fn); if (NULL == rh) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - _ ("Could not open `%s'.\n"), - fn); - GNUNET_free (fn); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + _("Could not open `%s'.\n"), + fn); + GNUNET_free(fn); + return; + } while ( - (GNUNET_OK == GNUNET_BIO_read (rh, - "Hash of indexed file", - &hc, - sizeof (struct GNUNET_HashCode))) && + (GNUNET_OK == GNUNET_BIO_read(rh, + "Hash of indexed file", + &hc, + sizeof(struct GNUNET_HashCode))) && (GNUNET_OK == - GNUNET_BIO_read_string (rh, "Name of indexed file", &fname, 1024 * 16)) && + GNUNET_BIO_read_string(rh, "Name of indexed file", &fname, 1024 * 16)) && (fname != NULL)) - { - slen = strlen (fname) + 1; - pos = GNUNET_malloc (sizeof (struct IndexInfo) + slen); - pos->file_id = hc; - pos->filename = (const char *) &pos[1]; - GNUNET_memcpy (&pos[1], fname, slen); - if (GNUNET_SYSERR == GNUNET_CONTAINER_multihashmap_put ( - ifm, - &pos->file_id, - pos, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - GNUNET_free (pos); - } - else { - GNUNET_CONTAINER_DLL_insert (indexed_files_head, indexed_files_tail, pos); + slen = strlen(fname) + 1; + pos = GNUNET_malloc(sizeof(struct IndexInfo) + slen); + pos->file_id = hc; + pos->filename = (const char *)&pos[1]; + GNUNET_memcpy(&pos[1], fname, slen); + if (GNUNET_SYSERR == GNUNET_CONTAINER_multihashmap_put( + ifm, + &pos->file_id, + pos, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_free(pos); + } + else + { + GNUNET_CONTAINER_DLL_insert(indexed_files_head, indexed_files_tail, pos); + } + GNUNET_free(fname); } - GNUNET_free (fname); - } - if (GNUNET_OK != GNUNET_BIO_read_close (rh, &emsg)) - GNUNET_free (emsg); - GNUNET_free (fn); + if (GNUNET_OK != GNUNET_BIO_read_close(rh, &emsg)) + GNUNET_free(emsg); + GNUNET_free(fn); } @@ -232,15 +230,15 @@ read_index_list () * @param msg error message */ static void -remove_cont (void *cls, - int success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +remove_cont(void *cls, + int success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { if (GNUNET_OK != success) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to delete bogus block: %s\n"), - msg); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to delete bogus block: %s\n"), + msg); } @@ -265,17 +263,17 @@ remove_cont (void *cls, * @return GNUNET_OK on success */ int -GNUNET_FS_handle_on_demand_block (const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid, - GNUNET_DATASTORE_DatumProcessor cont, - void *cont_cls) +GNUNET_FS_handle_on_demand_block(const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid, + GNUNET_DATASTORE_DatumProcessor cont, + void *cont_cls) { const struct OnDemandBlock *odb; struct GNUNET_HashCode nkey; @@ -290,79 +288,79 @@ GNUNET_FS_handle_on_demand_block (const struct GNUNET_HashCode *key, uint64_t off; struct IndexInfo *ii; - if (size != sizeof (struct OnDemandBlock)) - { - GNUNET_break (0); - GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1, &remove_cont, NULL); - return GNUNET_SYSERR; - } - odb = (const struct OnDemandBlock *) data; - off = GNUNET_ntohll (odb->offset); - ii = GNUNET_CONTAINER_multihashmap_get (ifm, &odb->file_id); + if (size != sizeof(struct OnDemandBlock)) + { + GNUNET_break(0); + GNUNET_DATASTORE_remove(dsh, key, size, data, -1, -1, &remove_cont, NULL); + return GNUNET_SYSERR; + } + odb = (const struct OnDemandBlock *)data; + off = GNUNET_ntohll(odb->offset); + ii = GNUNET_CONTAINER_multihashmap_get(ifm, &odb->file_id); if (NULL == ii) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to find index %s\n", - GNUNET_h2s (&odb->file_id)); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to find index %s\n", + GNUNET_h2s(&odb->file_id)); + return GNUNET_SYSERR; + } fn = ii->filename; - if ((NULL == fn) || (0 != access (fn, R_OK))) - { - GNUNET_STATISTICS_update ( - GSF_stats, - gettext_noop ("# index blocks removed: original file inaccessible"), - 1, - GNUNET_YES); - GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1, &remove_cont, NULL); - return GNUNET_SYSERR; - } - if ((NULL == (fh = GNUNET_DISK_file_open (fn, - GNUNET_DISK_OPEN_READ, - GNUNET_DISK_PERM_NONE))) || - (off != GNUNET_DISK_file_seek (fh, off, GNUNET_DISK_SEEK_SET)) || - (-1 == (nsize = GNUNET_DISK_file_read (fh, ndata, sizeof (ndata))))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ( - "Could not access indexed file `%s' (%s) at offset %llu: %s\n"), - GNUNET_h2s (&odb->file_id), - fn, - (unsigned long long) off, - (fn == NULL) ? _ ("not indexed") : strerror (errno)); - if (fh != NULL) - GNUNET_DISK_file_close (fh); - GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1, &remove_cont, NULL); - return GNUNET_SYSERR; - } - GNUNET_DISK_file_close (fh); - GNUNET_CRYPTO_hash (ndata, nsize, &nkey); - GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv); - GNUNET_CRYPTO_symmetric_encrypt (ndata, nsize, &skey, &iv, edata); - GNUNET_CRYPTO_hash (edata, nsize, &query); - if (0 != memcmp (&query, key, sizeof (struct GNUNET_HashCode))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Indexed file `%s' changed at offset %llu\n"), - fn, - (unsigned long long) off); - GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1, &remove_cont, NULL); - return GNUNET_SYSERR; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "On-demand encoded block for query `%s'\n", - GNUNET_h2s (key)); - cont (cont_cls, - key, - nsize, - edata, - GNUNET_BLOCK_TYPE_FS_DBLOCK, - priority, - anonymity, - replication, - expiration, - uid); + if ((NULL == fn) || (0 != access(fn, R_OK))) + { + GNUNET_STATISTICS_update( + GSF_stats, + gettext_noop("# index blocks removed: original file inaccessible"), + 1, + GNUNET_YES); + GNUNET_DATASTORE_remove(dsh, key, size, data, -1, -1, &remove_cont, NULL); + return GNUNET_SYSERR; + } + if ((NULL == (fh = GNUNET_DISK_file_open(fn, + GNUNET_DISK_OPEN_READ, + GNUNET_DISK_PERM_NONE))) || + (off != GNUNET_DISK_file_seek(fh, off, GNUNET_DISK_SEEK_SET)) || + (-1 == (nsize = GNUNET_DISK_file_read(fh, ndata, sizeof(ndata))))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _( + "Could not access indexed file `%s' (%s) at offset %llu: %s\n"), + GNUNET_h2s(&odb->file_id), + fn, + (unsigned long long)off, + (fn == NULL) ? _("not indexed") : strerror(errno)); + if (fh != NULL) + GNUNET_DISK_file_close(fh); + GNUNET_DATASTORE_remove(dsh, key, size, data, -1, -1, &remove_cont, NULL); + return GNUNET_SYSERR; + } + GNUNET_DISK_file_close(fh); + GNUNET_CRYPTO_hash(ndata, nsize, &nkey); + GNUNET_CRYPTO_hash_to_aes_key(&nkey, &skey, &iv); + GNUNET_CRYPTO_symmetric_encrypt(ndata, nsize, &skey, &iv, edata); + GNUNET_CRYPTO_hash(edata, nsize, &query); + if (0 != memcmp(&query, key, sizeof(struct GNUNET_HashCode))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Indexed file `%s' changed at offset %llu\n"), + fn, + (unsigned long long)off); + GNUNET_DATASTORE_remove(dsh, key, size, data, -1, -1, &remove_cont, NULL); + return GNUNET_SYSERR; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "On-demand encoded block for query `%s'\n", + GNUNET_h2s(key)); + cont(cont_cls, + key, + nsize, + edata, + GNUNET_BLOCK_TYPE_FS_DBLOCK, + priority, + anonymity, + replication, + expiration, + uid); return GNUNET_OK; } @@ -373,7 +371,7 @@ GNUNET_FS_handle_on_demand_block (const struct GNUNET_HashCode *key, * @param mq message queue to send information to */ void -GNUNET_FS_indexing_send_list (struct GNUNET_MQ_Handle *mq) +GNUNET_FS_indexing_send_list(struct GNUNET_MQ_Handle *mq) { struct GNUNET_MQ_Envelope *env; struct IndexInfoMessage *iim; @@ -383,23 +381,23 @@ GNUNET_FS_indexing_send_list (struct GNUNET_MQ_Handle *mq) struct IndexInfo *pos; for (pos = indexed_files_head; NULL != pos; pos = pos->next) - { - fn = pos->filename; - slen = strlen (fn) + 1; - if (slen + sizeof (struct IndexInfoMessage) >= GNUNET_MAX_MESSAGE_SIZE) { - GNUNET_break (0); - break; + fn = pos->filename; + slen = strlen(fn) + 1; + if (slen + sizeof(struct IndexInfoMessage) >= GNUNET_MAX_MESSAGE_SIZE) + { + GNUNET_break(0); + break; + } + env = + GNUNET_MQ_msg_extra(iim, slen, GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY); + iim->reserved = 0; + iim->file_id = pos->file_id; + GNUNET_memcpy(&iim[1], fn, slen); + GNUNET_MQ_send(mq, env); } - env = - GNUNET_MQ_msg_extra (iim, slen, GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY); - iim->reserved = 0; - iim->file_id = pos->file_id; - GNUNET_memcpy (&iim[1], fn, slen); - GNUNET_MQ_send (mq, env); - } - env = GNUNET_MQ_msg (iem, GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END); - GNUNET_MQ_send (mq, env); + env = GNUNET_MQ_msg(iem, GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END); + GNUNET_MQ_send(mq, env); } @@ -410,23 +408,23 @@ GNUNET_FS_indexing_send_list (struct GNUNET_MQ_Handle *mq) * @return #GNUNET_YES if the @a fid was found */ int -GNUNET_FS_indexing_do_unindex (const struct GNUNET_HashCode *fid) +GNUNET_FS_indexing_do_unindex(const struct GNUNET_HashCode *fid) { struct IndexInfo *pos; for (pos = indexed_files_head; NULL != pos; pos = pos->next) - { - if (0 == memcmp (&pos->file_id, fid, sizeof (struct GNUNET_HashCode))) { - GNUNET_CONTAINER_DLL_remove (indexed_files_head, indexed_files_tail, pos); - GNUNET_break ( - GNUNET_OK == - GNUNET_CONTAINER_multihashmap_remove (ifm, &pos->file_id, pos)); - GNUNET_free (pos); - write_index_list (); - return GNUNET_YES; + if (0 == memcmp(&pos->file_id, fid, sizeof(struct GNUNET_HashCode))) + { + GNUNET_CONTAINER_DLL_remove(indexed_files_head, indexed_files_tail, pos); + GNUNET_break( + GNUNET_OK == + GNUNET_CONTAINER_multihashmap_remove(ifm, &pos->file_id, pos)); + GNUNET_free(pos); + write_index_list(); + return GNUNET_YES; + } } - } return GNUNET_NO; } @@ -438,40 +436,40 @@ GNUNET_FS_indexing_do_unindex (const struct GNUNET_HashCode *fid) * @param file_id hash identifier for @a filename */ void -GNUNET_FS_add_to_index (const char *filename, - const struct GNUNET_HashCode *file_id) +GNUNET_FS_add_to_index(const char *filename, + const struct GNUNET_HashCode *file_id) { struct IndexInfo *ii; size_t slen; - ii = GNUNET_CONTAINER_multihashmap_get (ifm, file_id); + ii = GNUNET_CONTAINER_multihashmap_get(ifm, file_id); if (NULL != ii) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_INFO, - _ ( - "Index request received for file `%s' is already indexed as `%s'. Permitting anyway.\n"), - filename, - ii->filename); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding file %s to index as %s\n", - filename, - GNUNET_h2s (file_id)); - slen = strlen (filename) + 1; - ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen); + { + GNUNET_log( + GNUNET_ERROR_TYPE_INFO, + _( + "Index request received for file `%s' is already indexed as `%s'. Permitting anyway.\n"), + filename, + ii->filename); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding file %s to index as %s\n", + filename, + GNUNET_h2s(file_id)); + slen = strlen(filename) + 1; + ii = GNUNET_malloc(sizeof(struct IndexInfo) + slen); ii->file_id = *file_id; - ii->filename = (const char *) &ii[1]; - GNUNET_memcpy (&ii[1], filename, slen); - GNUNET_CONTAINER_DLL_insert (indexed_files_head, indexed_files_tail, ii); - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put ( - ifm, - &ii->file_id, - ii, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - write_index_list (); + ii->filename = (const char *)&ii[1]; + GNUNET_memcpy(&ii[1], filename, slen); + GNUNET_CONTAINER_DLL_insert(indexed_files_head, indexed_files_tail, ii); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put( + ifm, + &ii->file_id, + ii, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + write_index_list(); } @@ -479,21 +477,21 @@ GNUNET_FS_add_to_index (const char *filename, * Shutdown the module. */ void -GNUNET_FS_indexing_done () +GNUNET_FS_indexing_done() { struct IndexInfo *pos; while (NULL != (pos = indexed_files_head)) - { - GNUNET_CONTAINER_DLL_remove (indexed_files_head, indexed_files_tail, pos); - if (pos->fhc != NULL) - GNUNET_CRYPTO_hash_file_cancel (pos->fhc); - GNUNET_break ( - GNUNET_OK == - GNUNET_CONTAINER_multihashmap_remove (ifm, &pos->file_id, pos)); - GNUNET_free (pos); - } - GNUNET_CONTAINER_multihashmap_destroy (ifm); + { + GNUNET_CONTAINER_DLL_remove(indexed_files_head, indexed_files_tail, pos); + if (pos->fhc != NULL) + GNUNET_CRYPTO_hash_file_cancel(pos->fhc); + GNUNET_break( + GNUNET_OK == + GNUNET_CONTAINER_multihashmap_remove(ifm, &pos->file_id, pos)); + GNUNET_free(pos); + } + GNUNET_CONTAINER_multihashmap_destroy(ifm); ifm = NULL; cfg = NULL; } @@ -506,13 +504,13 @@ GNUNET_FS_indexing_done () * @param d datastore to use */ int -GNUNET_FS_indexing_init (const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_DATASTORE_Handle *d) +GNUNET_FS_indexing_init(const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_DATASTORE_Handle *d) { cfg = c; dsh = d; - ifm = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_YES); - read_index_list (); + ifm = GNUNET_CONTAINER_multihashmap_create(128, GNUNET_YES); + read_index_list(); return GNUNET_OK; } diff --git a/src/fs/gnunet-service-fs_indexing.h b/src/fs/gnunet-service-fs_indexing.h index d6166f0a9..4c137d7a6 100644 --- a/src/fs/gnunet-service-fs_indexing.h +++ b/src/fs/gnunet-service-fs_indexing.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_indexing.h @@ -56,17 +56,17 @@ * @return #GNUNET_OK on success */ int -GNUNET_FS_handle_on_demand_block (const struct GNUNET_HashCode *key, - uint32_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid, - GNUNET_DATASTORE_DatumProcessor cont, - void *cont_cls); +GNUNET_FS_handle_on_demand_block(const struct GNUNET_HashCode *key, + uint32_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid, + GNUNET_DATASTORE_DatumProcessor cont, + void *cont_cls); /** @@ -75,7 +75,7 @@ GNUNET_FS_handle_on_demand_block (const struct GNUNET_HashCode *key, * @param mq message queue to send information to */ void -GNUNET_FS_indexing_send_list (struct GNUNET_MQ_Handle *mq); +GNUNET_FS_indexing_send_list(struct GNUNET_MQ_Handle *mq); /** @@ -85,7 +85,7 @@ GNUNET_FS_indexing_send_list (struct GNUNET_MQ_Handle *mq); * @return #GNUNET_YES if the @a fid was found */ int -GNUNET_FS_indexing_do_unindex (const struct GNUNET_HashCode *fid); +GNUNET_FS_indexing_do_unindex(const struct GNUNET_HashCode *fid); /** @@ -95,8 +95,8 @@ GNUNET_FS_indexing_do_unindex (const struct GNUNET_HashCode *fid); * @param file_id hash identifier for @a filename */ void -GNUNET_FS_add_to_index (const char *filename, - const struct GNUNET_HashCode *file_id); +GNUNET_FS_add_to_index(const char *filename, + const struct GNUNET_HashCode *file_id); /** @@ -107,15 +107,15 @@ GNUNET_FS_add_to_index (const char *filename, * @return GNUNET_OK on success */ int -GNUNET_FS_indexing_init (const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_DATASTORE_Handle *d); +GNUNET_FS_indexing_init(const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_DATASTORE_Handle *d); /** * Shutdown the module. */ void -GNUNET_FS_indexing_done (void); +GNUNET_FS_indexing_done(void); #endif diff --git a/src/fs/gnunet-service-fs_pe.c b/src/fs/gnunet-service-fs_pe.c index 5e85bfdb7..3c1112333 100644 --- a/src/fs/gnunet-service-fs_pe.c +++ b/src/fs/gnunet-service-fs_pe.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_pe.c @@ -63,9 +63,7 @@ struct PeerPlan; * to be able to lookup all plan entries corresponding * to a given pending request.) */ -struct GSF_PendingRequestPlanBijection -{ - +struct GSF_PendingRequestPlanBijection { /** * This is a doubly-linked list. */ @@ -97,7 +95,6 @@ struct GSF_PendingRequestPlanBijection * and one of the origins of the request). */ struct GSF_PendingRequest *pr; - }; @@ -107,9 +104,7 @@ struct GSF_PendingRequestPlanBijection * with one entry in each heap of each `struct PeerPlan`. Each * entry tracks information relevant for this request and this peer. */ -struct GSF_RequestPlan -{ - +struct GSF_RequestPlan { /** * This is a doubly-linked list. */ @@ -161,15 +156,13 @@ struct GSF_RequestPlan * How often did we transmit this request to this peer? */ unsigned int transmission_counter; - }; /** * Transmission plan for a peer. */ -struct PeerPlan -{ +struct PeerPlan { /** * Heap with pending queries (`struct GSF_RequestPlan`), higher weights mean higher priority. */ @@ -202,7 +195,6 @@ struct PeerPlan * Current message under transmission for the plan. */ struct GNUNET_MQ_Envelope *env; - }; @@ -235,9 +227,9 @@ static unsigned long long plan_count; * @return the associated query */ static const struct GNUNET_HashCode * -get_rp_key (struct GSF_RequestPlan *rp) +get_rp_key(struct GSF_RequestPlan *rp) { - return &GSF_pending_request_get_data_ (rp->pe_head->pr)->query; + return &GSF_pending_request_get_data_(rp->pe_head->pr)->query; } @@ -248,8 +240,8 @@ get_rp_key (struct GSF_RequestPlan *rp) * @param rp request to plan */ static void -plan (struct PeerPlan *pp, - struct GSF_RequestPlan *rp) +plan(struct PeerPlan *pp, + struct GSF_RequestPlan *rp) { #define N ((double)128.0) /** @@ -260,28 +252,28 @@ plan (struct PeerPlan *pp, struct GSF_PendingRequestData *prd; struct GNUNET_TIME_Relative delay; - GNUNET_assert (rp->pp == pp); - GNUNET_STATISTICS_set (GSF_stats, - gettext_noop ("# average retransmission delay (ms)"), - total_delay * 1000LL / plan_count, GNUNET_NO); - prd = GSF_pending_request_get_data_ (rp->pe_head->pr); + GNUNET_assert(rp->pp == pp); + GNUNET_STATISTICS_set(GSF_stats, + gettext_noop("# average retransmission delay (ms)"), + total_delay * 1000LL / plan_count, GNUNET_NO); + prd = GSF_pending_request_get_data_(rp->pe_head->pr); if (rp->transmission_counter < 8) delay = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, - rp->transmission_counter); + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, + rp->transmission_counter); else if (rp->transmission_counter < 32) delay = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, - 8 + - (1LL << (rp->transmission_counter - 8))); + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, + 8 + + (1LL << (rp->transmission_counter - 8))); else delay = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, - 8 + (1LL << 24)); + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, + 8 + (1LL << 24)); delay.rel_value_us = - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - delay.rel_value_us + 1); + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + delay.rel_value_us + 1); /* Add 0.01 to avg_delay to avoid division-by-zero later */ avg_delay = (((avg_delay * (N - 1.0)) + delay.rel_value_us) / N) + 0.01; @@ -307,36 +299,36 @@ plan (struct PeerPlan *pp, * Note: M_PI_4 = PI/4 = arctan(1) */ rp->priority = - round ((GSF_current_priorities + - 1.0) * atan (delay.rel_value_us / avg_delay)) / M_PI_4; + round((GSF_current_priorities + + 1.0) * atan(delay.rel_value_us / avg_delay)) / M_PI_4; /* Note: usage of 'round' and 'atan' requires -lm */ if (rp->transmission_counter != 0) delay.rel_value_us += TTL_DECREMENT * 1000; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Considering (re)transmission number %u in %s\n", - (unsigned int) rp->transmission_counter, - GNUNET_STRINGS_relative_time_to_string (delay, - GNUNET_YES)); - rp->earliest_transmission = GNUNET_TIME_relative_to_absolute (delay); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Earliest (re)transmission for `%s' in %us\n", - GNUNET_h2s (&prd->query), - rp->transmission_counter); - GNUNET_assert (rp->hn == NULL); - if (0 == GNUNET_TIME_absolute_get_remaining (rp->earliest_transmission).rel_value_us) - rp->hn = GNUNET_CONTAINER_heap_insert (pp->priority_heap, - rp, - rp->priority); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Considering (re)transmission number %u in %s\n", + (unsigned int)rp->transmission_counter, + GNUNET_STRINGS_relative_time_to_string(delay, + GNUNET_YES)); + rp->earliest_transmission = GNUNET_TIME_relative_to_absolute(delay); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Earliest (re)transmission for `%s' in %us\n", + GNUNET_h2s(&prd->query), + rp->transmission_counter); + GNUNET_assert(rp->hn == NULL); + if (0 == GNUNET_TIME_absolute_get_remaining(rp->earliest_transmission).rel_value_us) + rp->hn = GNUNET_CONTAINER_heap_insert(pp->priority_heap, + rp, + rp->priority); else rp->hn = - GNUNET_CONTAINER_heap_insert (pp->delay_heap, - rp, - rp->earliest_transmission.abs_value_us); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_contains_value (pp->plan_map, - get_rp_key (rp), - rp)); + GNUNET_CONTAINER_heap_insert(pp->delay_heap, + rp, + rp->earliest_transmission.abs_value_us); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_contains_value(pp->plan_map, + get_rp_key(rp), + rp)); #undef N } @@ -348,7 +340,7 @@ plan (struct PeerPlan *pp, * @return pending request with highest TTL */ struct GSF_PendingRequest * -get_latest (const struct GSF_RequestPlan *rp) +get_latest(const struct GSF_RequestPlan *rp) { struct GSF_PendingRequest *ret; struct GSF_PendingRequestPlanBijection *bi; @@ -359,18 +351,18 @@ get_latest (const struct GSF_RequestPlan *rp) if (NULL == bi) return NULL; /* should never happen */ ret = bi->pr; - rprd = GSF_pending_request_get_data_ (ret); + rprd = GSF_pending_request_get_data_(ret); for (bi = bi->next_PE; NULL != bi; bi = bi->next_PE) - { - GNUNET_break (GNUNET_YES == - GSF_pending_request_test_active_ (bi->pr)); - prd = GSF_pending_request_get_data_ (bi->pr); - if (prd->ttl.abs_value_us > rprd->ttl.abs_value_us) { - ret = bi->pr; - rprd = prd; + GNUNET_break(GNUNET_YES == + GSF_pending_request_test_active_(bi->pr)); + prd = GSF_pending_request_get_data_(bi->pr); + if (prd->ttl.abs_value_us > rprd->ttl.abs_value_us) + { + ret = bi->pr; + rprd = prd; + } } - } return ret; } @@ -381,102 +373,100 @@ get_latest (const struct GSF_RequestPlan *rp) * @param cls the `struct PeerPlan` */ static void -schedule_peer_transmission (void *cls) +schedule_peer_transmission(void *cls) { struct PeerPlan *pp = cls; struct GSF_RequestPlan *rp; struct GNUNET_TIME_Relative delay; if (NULL != pp->task) - { - pp->task = NULL; - } + { + pp->task = NULL; + } else - { - GNUNET_assert (NULL != pp->env); - pp->env = NULL; - } + { + GNUNET_assert(NULL != pp->env); + pp->env = NULL; + } /* move ready requests to priority queue */ - while ((NULL != (rp = GNUNET_CONTAINER_heap_peek (pp->delay_heap))) && + while ((NULL != (rp = GNUNET_CONTAINER_heap_peek(pp->delay_heap))) && (0 == GNUNET_TIME_absolute_get_remaining - (rp->earliest_transmission).rel_value_us)) - { - GNUNET_assert (rp == GNUNET_CONTAINER_heap_remove_root (pp->delay_heap)); - rp->hn = GNUNET_CONTAINER_heap_insert (pp->priority_heap, - rp, - rp->priority); - } - if (0 == GNUNET_CONTAINER_heap_get_size (pp->priority_heap)) - { - /* priority heap (still) empty, check for delay... */ - rp = GNUNET_CONTAINER_heap_peek (pp->delay_heap); - if (NULL == rp) + (rp->earliest_transmission).rel_value_us)) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "No active requests for plan %p.\n", - pp); - return; /* both queues empty */ + GNUNET_assert(rp == GNUNET_CONTAINER_heap_remove_root(pp->delay_heap)); + rp->hn = GNUNET_CONTAINER_heap_insert(pp->priority_heap, + rp, + rp->priority); + } + if (0 == GNUNET_CONTAINER_heap_get_size(pp->priority_heap)) + { + /* priority heap (still) empty, check for delay... */ + rp = GNUNET_CONTAINER_heap_peek(pp->delay_heap); + if (NULL == rp) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "No active requests for plan %p.\n", + pp); + return; /* both queues empty */ + } + delay = GNUNET_TIME_absolute_get_remaining(rp->earliest_transmission); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sleeping for %s before retrying requests on plan %p.\n", + GNUNET_STRINGS_relative_time_to_string(delay, + GNUNET_YES), + pp); + GNUNET_STATISTICS_set(GSF_stats, + gettext_noop("# delay heap timeout (ms)"), + delay.rel_value_us / 1000LL, GNUNET_NO); + + pp->task + = GNUNET_SCHEDULER_add_at(rp->earliest_transmission, + &schedule_peer_transmission, + pp); + return; } - delay = GNUNET_TIME_absolute_get_remaining (rp->earliest_transmission); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sleeping for %s before retrying requests on plan %p.\n", - GNUNET_STRINGS_relative_time_to_string (delay, - GNUNET_YES), - pp); - GNUNET_STATISTICS_set (GSF_stats, - gettext_noop ("# delay heap timeout (ms)"), - delay.rel_value_us / 1000LL, GNUNET_NO); - - pp->task - = GNUNET_SCHEDULER_add_at (rp->earliest_transmission, - &schedule_peer_transmission, - pp); - return; - } #if INSANE_STATISTICS - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# query plans executed"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# query plans executed"), + 1, + GNUNET_NO); #endif /* process from priority heap */ - rp = GNUNET_CONTAINER_heap_remove_root (pp->priority_heap); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Executing query plan %p\n", - rp); - GNUNET_assert (NULL != rp); + rp = GNUNET_CONTAINER_heap_remove_root(pp->priority_heap); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Executing query plan %p\n", + rp); + GNUNET_assert(NULL != rp); rp->hn = NULL; - rp->last_transmission = GNUNET_TIME_absolute_get (); + rp->last_transmission = GNUNET_TIME_absolute_get(); rp->transmission_counter++; total_delay++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Executing plan %p executed %u times, planning retransmission\n", - rp, - rp->transmission_counter); - GNUNET_assert (NULL == pp->env); - pp->env = GSF_pending_request_get_message_ (get_latest (rp)); - GNUNET_MQ_notify_sent (pp->env, - &schedule_peer_transmission, - pp); - GSF_peer_transmit_ (pp->cp, - GNUNET_YES, - rp->priority, - pp->env); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# query messages sent to other peers"), - 1, - GNUNET_NO); - plan (pp, - rp); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Executing plan %p executed %u times, planning retransmission\n", + rp, + rp->transmission_counter); + GNUNET_assert(NULL == pp->env); + pp->env = GSF_pending_request_get_message_(get_latest(rp)); + GNUNET_MQ_notify_sent(pp->env, + &schedule_peer_transmission, + pp); + GSF_peer_transmit_(pp->cp, + GNUNET_YES, + rp->priority, + pp->env); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# query messages sent to other peers"), + 1, + GNUNET_NO); + plan(pp, + rp); } /** * Closure for merge_pr(). */ -struct MergeContext -{ - +struct MergeContext { /** * Request we are trying to merge. */ @@ -486,7 +476,6 @@ struct MergeContext * Set to #GNUNET_YES if we succeeded to merge. */ int merged; - }; @@ -501,9 +490,9 @@ struct MergeContext * #GNUNET_NO if not (merge success) */ static int -merge_pr (void *cls, - const struct GNUNET_HashCode *query, - void *element) +merge_pr(void *cls, + const struct GNUNET_HashCode *query, + void *element) { struct MergeContext *mpr = cls; struct GSF_RequestPlan *rp = element; @@ -511,44 +500,44 @@ merge_pr (void *cls, struct GSF_PendingRequestPlanBijection *bi; struct GSF_PendingRequest *latest; - GNUNET_break (GNUNET_YES == - GSF_pending_request_test_active_ (mpr->pr)); + GNUNET_break(GNUNET_YES == + GSF_pending_request_test_active_(mpr->pr)); if (GNUNET_OK != - GSF_pending_request_is_compatible_ (mpr->pr, - rp->pe_head->pr)) + GSF_pending_request_is_compatible_(mpr->pr, + rp->pe_head->pr)) return GNUNET_YES; /* merge new request with existing request plan */ - bi = GNUNET_new (struct GSF_PendingRequestPlanBijection); + bi = GNUNET_new(struct GSF_PendingRequestPlanBijection); bi->rp = rp; bi->pr = mpr->pr; - prd = GSF_pending_request_get_data_ (mpr->pr); - GNUNET_CONTAINER_MDLL_insert (PR, - prd->pr_head, - prd->pr_tail, - bi); - GNUNET_CONTAINER_MDLL_insert (PE, - rp->pe_head, - rp->pe_tail, - bi); + prd = GSF_pending_request_get_data_(mpr->pr); + GNUNET_CONTAINER_MDLL_insert(PR, + prd->pr_head, + prd->pr_tail, + bi); + GNUNET_CONTAINER_MDLL_insert(PE, + rp->pe_head, + rp->pe_tail, + bi); mpr->merged = GNUNET_YES; #if INSANE_STATISTICS - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# requests merged"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# requests merged"), + 1, + GNUNET_NO); #endif - latest = get_latest (rp); - if (GSF_pending_request_get_data_ (latest)->ttl.abs_value_us < + latest = get_latest(rp); + if (GSF_pending_request_get_data_(latest)->ttl.abs_value_us < prd->ttl.abs_value_us) - { + { #if INSANE_STATISTICS - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# requests refreshed"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# requests refreshed"), + 1, + GNUNET_NO); #endif - rp->transmission_counter = 0; /* reset */ - } + rp->transmission_counter = 0; /* reset */ + } return GNUNET_NO; } @@ -560,8 +549,8 @@ merge_pr (void *cls, * @param pr request with the entry */ void -GSF_plan_add_ (struct GSF_ConnectedPeer *cp, - struct GSF_PendingRequest *pr) +GSF_plan_add_(struct GSF_ConnectedPeer *cp, + struct GSF_PendingRequest *pr) { const struct GNUNET_PeerIdentity *id; struct PeerPlan *pp; @@ -570,66 +559,66 @@ GSF_plan_add_ (struct GSF_ConnectedPeer *cp, struct GSF_PendingRequestPlanBijection *bi; struct MergeContext mpc; - GNUNET_assert (GNUNET_YES == - GSF_pending_request_test_active_ (pr)); - GNUNET_assert (NULL != cp); - id = GSF_connected_peer_get_identity2_ (cp); - pp = GNUNET_CONTAINER_multipeermap_get (plans, id); + GNUNET_assert(GNUNET_YES == + GSF_pending_request_test_active_(pr)); + GNUNET_assert(NULL != cp); + id = GSF_connected_peer_get_identity2_(cp); + pp = GNUNET_CONTAINER_multipeermap_get(plans, id); if (NULL == pp) - { - pp = GNUNET_new (struct PeerPlan); - pp->plan_map = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO); - pp->priority_heap = - GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MAX); - pp->delay_heap = - GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); - pp->cp = cp; - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put (plans, + { + pp = GNUNET_new(struct PeerPlan); + pp->plan_map = GNUNET_CONTAINER_multihashmap_create(128, GNUNET_NO); + pp->priority_heap = + GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MAX); + pp->delay_heap = + GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN); + pp->cp = cp; + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_put(plans, id, pp, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - pp->task = GNUNET_SCHEDULER_add_now (&schedule_peer_transmission, - pp); - } + pp->task = GNUNET_SCHEDULER_add_now(&schedule_peer_transmission, + pp); + } mpc.merged = GNUNET_NO; mpc.pr = pr; - prd = GSF_pending_request_get_data_ (pr); - GNUNET_CONTAINER_multihashmap_get_multiple (pp->plan_map, - &prd->query, - &merge_pr, - &mpc); + prd = GSF_pending_request_get_data_(pr); + GNUNET_CONTAINER_multihashmap_get_multiple(pp->plan_map, + &prd->query, + &merge_pr, + &mpc); if (GNUNET_NO != mpc.merged) return; plan_count++; - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# query plan entries"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Planning transmission of query `%s' to peer `%s'\n", - GNUNET_h2s (&prd->query), - GNUNET_i2s (id)); - rp = GNUNET_new (struct GSF_RequestPlan); - bi = GNUNET_new (struct GSF_PendingRequestPlanBijection); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# query plan entries"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Planning transmission of query `%s' to peer `%s'\n", + GNUNET_h2s(&prd->query), + GNUNET_i2s(id)); + rp = GNUNET_new(struct GSF_RequestPlan); + bi = GNUNET_new(struct GSF_PendingRequestPlanBijection); bi->rp = rp; bi->pr = pr; - GNUNET_CONTAINER_MDLL_insert (PR, - prd->pr_head, - prd->pr_tail, - bi); - GNUNET_CONTAINER_MDLL_insert (PE, - rp->pe_head, - rp->pe_tail, - bi); + GNUNET_CONTAINER_MDLL_insert(PR, + prd->pr_head, + prd->pr_tail, + bi); + GNUNET_CONTAINER_MDLL_insert(PE, + rp->pe_head, + rp->pe_tail, + bi); rp->pp = pp; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_put (pp->plan_map, - get_rp_key (rp), - rp, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); - plan (pp, - rp); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_put(pp->plan_map, + get_rp_key(rp), + rp, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); + plan(pp, + rp); } @@ -640,7 +629,7 @@ GSF_plan_add_ (struct GSF_ConnectedPeer *cp, * @param cp connected peer */ void -GSF_plan_notify_peer_disconnect_ (const struct GSF_ConnectedPeer *cp) +GSF_plan_notify_peer_disconnect_(const struct GSF_ConnectedPeer *cp) { const struct GNUNET_PeerIdentity *id; struct PeerPlan *pp; @@ -648,70 +637,70 @@ GSF_plan_notify_peer_disconnect_ (const struct GSF_ConnectedPeer *cp) struct GSF_PendingRequestData *prd; struct GSF_PendingRequestPlanBijection *bi; - id = GSF_connected_peer_get_identity2_ (cp); - pp = GNUNET_CONTAINER_multipeermap_get (plans, id); + id = GSF_connected_peer_get_identity2_(cp); + pp = GNUNET_CONTAINER_multipeermap_get(plans, id); if (NULL == pp) return; /* nothing was ever planned for this peer */ - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (plans, id, - pp)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(plans, id, + pp)); if (NULL != pp->task) - { - GNUNET_SCHEDULER_cancel (pp->task); - pp->task = NULL; - } - while (NULL != (rp = GNUNET_CONTAINER_heap_remove_root (pp->priority_heap))) - { - GNUNET_break (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (pp->plan_map, - get_rp_key (rp), - rp)); - while (NULL != (bi = rp->pe_head)) { - GNUNET_CONTAINER_MDLL_remove (PE, - rp->pe_head, - rp->pe_tail, - bi); - prd = GSF_pending_request_get_data_ (bi->pr); - GNUNET_CONTAINER_MDLL_remove (PR, - prd->pr_head, - prd->pr_tail, - bi); - GNUNET_free (bi); + GNUNET_SCHEDULER_cancel(pp->task); + pp->task = NULL; } - plan_count--; - GNUNET_free (rp); - } - GNUNET_CONTAINER_heap_destroy (pp->priority_heap); - while (NULL != (rp = GNUNET_CONTAINER_heap_remove_root (pp->delay_heap))) - { - GNUNET_break (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (pp->plan_map, - get_rp_key (rp), + while (NULL != (rp = GNUNET_CONTAINER_heap_remove_root(pp->priority_heap))) + { + GNUNET_break(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(pp->plan_map, + get_rp_key(rp), rp)); - while (NULL != (bi = rp->pe_head)) + while (NULL != (bi = rp->pe_head)) + { + GNUNET_CONTAINER_MDLL_remove(PE, + rp->pe_head, + rp->pe_tail, + bi); + prd = GSF_pending_request_get_data_(bi->pr); + GNUNET_CONTAINER_MDLL_remove(PR, + prd->pr_head, + prd->pr_tail, + bi); + GNUNET_free(bi); + } + plan_count--; + GNUNET_free(rp); + } + GNUNET_CONTAINER_heap_destroy(pp->priority_heap); + while (NULL != (rp = GNUNET_CONTAINER_heap_remove_root(pp->delay_heap))) { - prd = GSF_pending_request_get_data_ (bi->pr); - GNUNET_CONTAINER_MDLL_remove (PE, - rp->pe_head, - rp->pe_tail, - bi); - GNUNET_CONTAINER_MDLL_remove (PR, - prd->pr_head, - prd->pr_tail, - bi); - GNUNET_free (bi); + GNUNET_break(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(pp->plan_map, + get_rp_key(rp), + rp)); + while (NULL != (bi = rp->pe_head)) + { + prd = GSF_pending_request_get_data_(bi->pr); + GNUNET_CONTAINER_MDLL_remove(PE, + rp->pe_head, + rp->pe_tail, + bi); + GNUNET_CONTAINER_MDLL_remove(PR, + prd->pr_head, + prd->pr_tail, + bi); + GNUNET_free(bi); + } + plan_count--; + GNUNET_free(rp); } - plan_count--; - GNUNET_free (rp); - } - GNUNET_STATISTICS_set (GSF_stats, - gettext_noop ("# query plan entries"), - plan_count, - GNUNET_NO); - GNUNET_CONTAINER_heap_destroy (pp->delay_heap); - GNUNET_CONTAINER_multihashmap_destroy (pp->plan_map); - GNUNET_free (pp); + GNUNET_STATISTICS_set(GSF_stats, + gettext_noop("# query plan entries"), + plan_count, + GNUNET_NO); + GNUNET_CONTAINER_heap_destroy(pp->delay_heap); + GNUNET_CONTAINER_multihashmap_destroy(pp->plan_map); + GNUNET_free(pp); } @@ -725,23 +714,23 @@ GSF_plan_notify_peer_disconnect_ (const struct GSF_ConnectedPeer *cp) * @return #GNUNET_YES if @a result was changed, #GNUNET_NO otherwise. */ int -GSF_request_plan_reference_get_last_transmission_ (struct GSF_PendingRequestPlanBijection *pr_head, - struct GSF_ConnectedPeer *sender, - struct GNUNET_TIME_Absolute *result) +GSF_request_plan_reference_get_last_transmission_(struct GSF_PendingRequestPlanBijection *pr_head, + struct GSF_ConnectedPeer *sender, + struct GNUNET_TIME_Absolute *result) { struct GSF_PendingRequestPlanBijection *bi; for (bi = pr_head; NULL != bi; bi = bi->next_PR) - { - if (bi->rp->pp->cp == sender) { - if (0 == bi->rp->last_transmission.abs_value_us) - *result = GNUNET_TIME_UNIT_FOREVER_ABS; - else - *result = bi->rp->last_transmission; - return GNUNET_YES; + if (bi->rp->pp->cp == sender) + { + if (0 == bi->rp->last_transmission.abs_value_us) + *result = GNUNET_TIME_UNIT_FOREVER_ABS; + else + *result = bi->rp->last_transmission; + return GNUNET_YES; + } } - } return GNUNET_NO; } @@ -753,41 +742,41 @@ GSF_request_plan_reference_get_last_transmission_ (struct GSF_PendingRequestPlan * @param pr request that is done */ void -GSF_plan_notify_request_done_ (struct GSF_PendingRequest *pr) +GSF_plan_notify_request_done_(struct GSF_PendingRequest *pr) { struct GSF_RequestPlan *rp; struct GSF_PendingRequestData *prd; struct GSF_PendingRequestPlanBijection *bi; - prd = GSF_pending_request_get_data_ (pr); + prd = GSF_pending_request_get_data_(pr); while (NULL != (bi = prd->pr_head)) - { - rp = bi->rp; - GNUNET_CONTAINER_MDLL_remove (PR, - prd->pr_head, - prd->pr_tail, - bi); - GNUNET_CONTAINER_MDLL_remove (PE, - rp->pe_head, - rp->pe_tail, - bi); - GNUNET_assert (bi->pr == pr); - if (NULL == rp->pe_head) { - GNUNET_CONTAINER_heap_remove_node (rp->hn); - plan_count--; - GNUNET_break (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (rp->pp->plan_map, - &prd->query, - rp)); - GNUNET_free (rp); + rp = bi->rp; + GNUNET_CONTAINER_MDLL_remove(PR, + prd->pr_head, + prd->pr_tail, + bi); + GNUNET_CONTAINER_MDLL_remove(PE, + rp->pe_head, + rp->pe_tail, + bi); + GNUNET_assert(bi->pr == pr); + if (NULL == rp->pe_head) + { + GNUNET_CONTAINER_heap_remove_node(rp->hn); + plan_count--; + GNUNET_break(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(rp->pp->plan_map, + &prd->query, + rp)); + GNUNET_free(rp); + } + GNUNET_free(bi); } - GNUNET_free (bi); - } - GNUNET_STATISTICS_set (GSF_stats, - gettext_noop ("# query plan entries"), - plan_count, - GNUNET_NO); + GNUNET_STATISTICS_set(GSF_stats, + gettext_noop("# query plan entries"), + plan_count, + GNUNET_NO); } @@ -795,10 +784,10 @@ GSF_plan_notify_request_done_ (struct GSF_PendingRequest *pr) * Initialize plan subsystem. */ void -GSF_plan_init () +GSF_plan_init() { - plans = GNUNET_CONTAINER_multipeermap_create (256, - GNUNET_YES); + plans = GNUNET_CONTAINER_multipeermap_create(256, + GNUNET_YES); } @@ -806,10 +795,10 @@ GSF_plan_init () * Shutdown plan subsystem. */ void -GSF_plan_done () +GSF_plan_done() { - GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (plans)); - GNUNET_CONTAINER_multipeermap_destroy (plans); + GNUNET_assert(0 == GNUNET_CONTAINER_multipeermap_size(plans)); + GNUNET_CONTAINER_multipeermap_destroy(plans); } diff --git a/src/fs/gnunet-service-fs_pe.h b/src/fs/gnunet-service-fs_pe.h index 10f7daea5..dfad71be9 100644 --- a/src/fs/gnunet-service-fs_pe.h +++ b/src/fs/gnunet-service-fs_pe.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_pe.h @@ -36,8 +36,8 @@ * @param pr request with the entry */ void -GSF_plan_add_ (struct GSF_ConnectedPeer *cp, - struct GSF_PendingRequest *pr); +GSF_plan_add_(struct GSF_ConnectedPeer *cp, + struct GSF_PendingRequest *pr); /** @@ -47,7 +47,7 @@ GSF_plan_add_ (struct GSF_ConnectedPeer *cp, * @param cp connected peer */ void -GSF_plan_notify_peer_disconnect_ (const struct GSF_ConnectedPeer *cp); +GSF_plan_notify_peer_disconnect_(const struct GSF_ConnectedPeer *cp); /** @@ -57,7 +57,7 @@ GSF_plan_notify_peer_disconnect_ (const struct GSF_ConnectedPeer *cp); * @param pr request that is done */ void -GSF_plan_notify_request_done_ (struct GSF_PendingRequest *pr); +GSF_plan_notify_request_done_(struct GSF_PendingRequest *pr); /** * Get the last transmission attempt time for the request plan list @@ -69,22 +69,22 @@ GSF_plan_notify_request_done_ (struct GSF_PendingRequest *pr); * @return GNUNET_YES if 'result' was changed, GNUNET_NO otherwise. */ int -GSF_request_plan_reference_get_last_transmission_ (struct GSF_PendingRequestPlanBijection *pr_head, - struct GSF_ConnectedPeer *sender, - struct GNUNET_TIME_Absolute *result); +GSF_request_plan_reference_get_last_transmission_(struct GSF_PendingRequestPlanBijection *pr_head, + struct GSF_ConnectedPeer *sender, + struct GNUNET_TIME_Absolute *result); /** * Initialize plan subsystem. */ void -GSF_plan_init (void); +GSF_plan_init(void); /** * Shutdown plan subsystem. */ void -GSF_plan_done (void); +GSF_plan_done(void); #endif diff --git a/src/fs/gnunet-service-fs_pr.c b/src/fs/gnunet-service-fs_pr.c index f9702486a..90587cfa0 100644 --- a/src/fs/gnunet-service-fs_pr.c +++ b/src/fs/gnunet-service-fs_pr.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_pr.c @@ -74,8 +74,7 @@ /** * An active request. */ -struct GSF_PendingRequest -{ +struct GSF_PendingRequest { /** * Public data for the request. */ @@ -247,31 +246,31 @@ static unsigned long long max_pending_requests = (32 * 1024); * @param pr request for which the BF is to be recomputed */ static void -refresh_bloomfilter (enum GNUNET_BLOCK_Type type, struct GSF_PendingRequest *pr) +refresh_bloomfilter(enum GNUNET_BLOCK_Type type, struct GSF_PendingRequest *pr) { if (NULL != pr->bg) - { - GNUNET_BLOCK_group_destroy (pr->bg); - pr->bg = NULL; - } + { + GNUNET_BLOCK_group_destroy(pr->bg); + pr->bg = NULL; + } if (GNUNET_BLOCK_TYPE_FS_UBLOCK != type) return; /* no need */ pr->bg = - GNUNET_BLOCK_group_create (GSF_block_ctx, - type, - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT32_MAX), - NULL, - 0, - "seen-set-size", - pr->replies_seen_count, - NULL); + GNUNET_BLOCK_group_create(GSF_block_ctx, + type, + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + UINT32_MAX), + NULL, + 0, + "seen-set-size", + pr->replies_seen_count, + NULL); if (NULL == pr->bg) return; - GNUNET_break (GNUNET_OK == - GNUNET_BLOCK_group_set_seen (pr->bg, - pr->replies_seen, - pr->replies_seen_count)); + GNUNET_break(GNUNET_OK == + GNUNET_BLOCK_group_set_seen(pr->bg, + pr->replies_seen, + pr->replies_seen_count)); } @@ -297,129 +296,129 @@ refresh_bloomfilter (enum GNUNET_BLOCK_Type type, struct GSF_PendingRequest *pr) * @return handle for the new pending request */ struct GSF_PendingRequest * -GSF_pending_request_create_ (enum GSF_PendingRequestOptions options, - enum GNUNET_BLOCK_Type type, - const struct GNUNET_HashCode *query, - const struct GNUNET_PeerIdentity *target, - const char *bf_data, - size_t bf_size, - uint32_t mingle, - uint32_t anonymity_level, - uint32_t priority, - int32_t ttl, - GNUNET_PEER_Id sender_pid, - GNUNET_PEER_Id origin_pid, - const struct GNUNET_HashCode *replies_seen, - unsigned int replies_seen_count, - GSF_PendingRequestReplyHandler rh, - void *rh_cls) +GSF_pending_request_create_(enum GSF_PendingRequestOptions options, + enum GNUNET_BLOCK_Type type, + const struct GNUNET_HashCode *query, + const struct GNUNET_PeerIdentity *target, + const char *bf_data, + size_t bf_size, + uint32_t mingle, + uint32_t anonymity_level, + uint32_t priority, + int32_t ttl, + GNUNET_PEER_Id sender_pid, + GNUNET_PEER_Id origin_pid, + const struct GNUNET_HashCode *replies_seen, + unsigned int replies_seen_count, + GSF_PendingRequestReplyHandler rh, + void *rh_cls) { struct GSF_PendingRequest *pr; struct GSF_PendingRequest *dpr; size_t extra; struct GNUNET_HashCode *eptr; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Creating request handle for `%s' of type %d\n", - GNUNET_h2s (query), - type); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Creating request handle for `%s' of type %d\n", + GNUNET_h2s(query), + type); #if INSANE_STATISTICS - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# Pending requests created"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# Pending requests created"), + 1, + GNUNET_NO); #endif extra = 0; if (NULL != target) - extra += sizeof (struct GNUNET_PeerIdentity); - pr = GNUNET_malloc (sizeof (struct GSF_PendingRequest) + extra); + extra += sizeof(struct GNUNET_PeerIdentity); + pr = GNUNET_malloc(sizeof(struct GSF_PendingRequest) + extra); pr->public_data.query = *query; - eptr = (struct GNUNET_HashCode *) &pr[1]; + eptr = (struct GNUNET_HashCode *)&pr[1]; if (NULL != target) - { - pr->public_data.target = (struct GNUNET_PeerIdentity *) eptr; - GNUNET_memcpy (eptr, target, sizeof (struct GNUNET_PeerIdentity)); - } + { + pr->public_data.target = (struct GNUNET_PeerIdentity *)eptr; + GNUNET_memcpy(eptr, target, sizeof(struct GNUNET_PeerIdentity)); + } pr->public_data.anonymity_level = anonymity_level; pr->public_data.priority = priority; pr->public_data.original_priority = priority; pr->public_data.options = options; pr->public_data.type = type; - pr->public_data.start_time = GNUNET_TIME_absolute_get (); + pr->public_data.start_time = GNUNET_TIME_absolute_get(); pr->sender_pid = sender_pid; pr->origin_pid = origin_pid; pr->rh = rh; pr->rh_cls = rh_cls; - GNUNET_assert ((sender_pid != 0) || (0 == (options & GSF_PRO_FORWARD_ONLY))); + GNUNET_assert((sender_pid != 0) || (0 == (options & GSF_PRO_FORWARD_ONLY))); if (ttl >= 0) - pr->public_data.ttl = GNUNET_TIME_relative_to_absolute ( - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, (uint32_t) ttl)); + pr->public_data.ttl = GNUNET_TIME_relative_to_absolute( + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, (uint32_t)ttl)); else - pr->public_data.ttl = GNUNET_TIME_absolute_subtract ( + pr->public_data.ttl = GNUNET_TIME_absolute_subtract( pr->public_data.start_time, - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, - (uint32_t) (-ttl))); + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, + (uint32_t)(-ttl))); if (replies_seen_count > 0) - { - pr->replies_seen_size = replies_seen_count; - pr->replies_seen = - GNUNET_new_array (pr->replies_seen_size, struct GNUNET_HashCode); - GNUNET_memcpy (pr->replies_seen, - replies_seen, - replies_seen_count * sizeof (struct GNUNET_HashCode)); - pr->replies_seen_count = replies_seen_count; - } + { + pr->replies_seen_size = replies_seen_count; + pr->replies_seen = + GNUNET_new_array(pr->replies_seen_size, struct GNUNET_HashCode); + GNUNET_memcpy(pr->replies_seen, + replies_seen, + replies_seen_count * sizeof(struct GNUNET_HashCode)); + pr->replies_seen_count = replies_seen_count; + } if ((NULL != bf_data) && (GNUNET_BLOCK_TYPE_FS_UBLOCK == pr->public_data.type)) - { - pr->bg = GNUNET_BLOCK_group_create (GSF_block_ctx, - pr->public_data.type, - mingle, - bf_data, - bf_size, - "seen-set-size", - 0, - NULL); - } + { + pr->bg = GNUNET_BLOCK_group_create(GSF_block_ctx, + pr->public_data.type, + mingle, + bf_data, + bf_size, + "seen-set-size", + 0, + NULL); + } else if ((replies_seen_count > 0) && (0 != (options & GSF_PRO_BLOOMFILTER_FULL_REFRESH))) - { - refresh_bloomfilter (pr->public_data.type, pr); - } - GNUNET_CONTAINER_multihashmap_put (pr_map, - &pr->public_data.query, - pr, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + { + refresh_bloomfilter(pr->public_data.type, pr); + } + GNUNET_CONTAINER_multihashmap_put(pr_map, + &pr->public_data.query, + pr, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); if (0 == (options & GSF_PRO_REQUEST_NEVER_EXPIRES)) - { - pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap, - pr, - pr->public_data.ttl.abs_value_us); - /* make sure we don't track too many requests */ - while (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > - max_pending_requests) { - dpr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap); - GNUNET_assert (NULL != dpr); - if (pr == dpr) - break; /* let the request live briefly... */ - if (NULL != dpr->rh) - dpr->rh (dpr->rh_cls, - GNUNET_BLOCK_EVALUATION_REQUEST_VALID, - dpr, - UINT32_MAX, - GNUNET_TIME_UNIT_FOREVER_ABS, - GNUNET_TIME_UNIT_FOREVER_ABS, - GNUNET_BLOCK_TYPE_ANY, - NULL, - 0); - GSF_pending_request_cancel_ (dpr, GNUNET_YES); + pr->hnode = GNUNET_CONTAINER_heap_insert(requests_by_expiration_heap, + pr, + pr->public_data.ttl.abs_value_us); + /* make sure we don't track too many requests */ + while (GNUNET_CONTAINER_heap_get_size(requests_by_expiration_heap) > + max_pending_requests) + { + dpr = GNUNET_CONTAINER_heap_peek(requests_by_expiration_heap); + GNUNET_assert(NULL != dpr); + if (pr == dpr) + break; /* let the request live briefly... */ + if (NULL != dpr->rh) + dpr->rh(dpr->rh_cls, + GNUNET_BLOCK_EVALUATION_REQUEST_VALID, + dpr, + UINT32_MAX, + GNUNET_TIME_UNIT_FOREVER_ABS, + GNUNET_TIME_UNIT_FOREVER_ABS, + GNUNET_BLOCK_TYPE_ANY, + NULL, + 0); + GSF_pending_request_cancel_(dpr, GNUNET_YES); + } } - } - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# Pending requests active"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# Pending requests active"), + 1, + GNUNET_NO); return pr; } @@ -430,7 +429,7 @@ GSF_pending_request_create_ (enum GSF_PendingRequestOptions options, * @return associated public data */ struct GSF_PendingRequestData * -GSF_pending_request_get_data_ (struct GSF_PendingRequest *pr) +GSF_pending_request_get_data_(struct GSF_PendingRequest *pr) { return &pr->public_data; } @@ -446,13 +445,13 @@ GSF_pending_request_get_data_ (struct GSF_PendingRequest *pr) * @return #GNUNET_OK if the requests are compatible */ int -GSF_pending_request_is_compatible_ (struct GSF_PendingRequest *pra, - struct GSF_PendingRequest *prb) +GSF_pending_request_is_compatible_(struct GSF_PendingRequest *pra, + struct GSF_PendingRequest *prb) { if ((pra->public_data.type != prb->public_data.type) || - (0 != memcmp (&pra->public_data.query, - &prb->public_data.query, - sizeof (struct GNUNET_HashCode)))) + (0 != memcmp(&pra->public_data.query, + &prb->public_data.query, + sizeof(struct GNUNET_HashCode)))) return GNUNET_NO; return GNUNET_OK; } @@ -467,45 +466,45 @@ GSF_pending_request_is_compatible_ (struct GSF_PendingRequest *pra, * @param replies_seen_count size of the replies_seen array */ void -GSF_pending_request_update_ (struct GSF_PendingRequest *pr, - const struct GNUNET_HashCode *replies_seen, - unsigned int replies_seen_count) +GSF_pending_request_update_(struct GSF_PendingRequest *pr, + const struct GNUNET_HashCode *replies_seen, + unsigned int replies_seen_count) { if (replies_seen_count + pr->replies_seen_count < pr->replies_seen_count) return; /* integer overflow */ if (0 != (pr->public_data.options & GSF_PRO_BLOOMFILTER_FULL_REFRESH)) - { - /* we're responsible for the BF, full refresh */ - if (replies_seen_count + pr->replies_seen_count > pr->replies_seen_size) - GNUNET_array_grow (pr->replies_seen, - pr->replies_seen_size, - replies_seen_count + pr->replies_seen_count); - GNUNET_memcpy (&pr->replies_seen[pr->replies_seen_count], - replies_seen, - sizeof (struct GNUNET_HashCode) * replies_seen_count); - pr->replies_seen_count += replies_seen_count; - refresh_bloomfilter (pr->public_data.type, pr); - } - else - { - if (NULL == pr->bg) { - /* we're not the initiator, but the initiator did not give us - * any bloom-filter, so we need to create one on-the-fly */ - refresh_bloomfilter (pr->public_data.type, pr); + /* we're responsible for the BF, full refresh */ + if (replies_seen_count + pr->replies_seen_count > pr->replies_seen_size) + GNUNET_array_grow(pr->replies_seen, + pr->replies_seen_size, + replies_seen_count + pr->replies_seen_count); + GNUNET_memcpy(&pr->replies_seen[pr->replies_seen_count], + replies_seen, + sizeof(struct GNUNET_HashCode) * replies_seen_count); + pr->replies_seen_count += replies_seen_count; + refresh_bloomfilter(pr->public_data.type, pr); } - else + else { - GNUNET_break (GNUNET_OK == - GNUNET_BLOCK_group_set_seen (pr->bg, - replies_seen, - pr->replies_seen_count)); + if (NULL == pr->bg) + { + /* we're not the initiator, but the initiator did not give us + * any bloom-filter, so we need to create one on-the-fly */ + refresh_bloomfilter(pr->public_data.type, pr); + } + else + { + GNUNET_break(GNUNET_OK == + GNUNET_BLOCK_group_set_seen(pr->bg, + replies_seen, + pr->replies_seen_count)); + } } - } if (NULL != pr->gh) - GNUNET_DHT_get_filter_known_results (pr->gh, - replies_seen_count, - replies_seen); + GNUNET_DHT_get_filter_known_results(pr->gh, + replies_seen_count, + replies_seen); } @@ -517,7 +516,7 @@ GSF_pending_request_update_ (struct GSF_PendingRequest *pr, * @return envelope with the request message */ struct GNUNET_MQ_Envelope * -GSF_pending_request_get_message_ (struct GSF_PendingRequest *pr) +GSF_pending_request_get_message_(struct GSF_PendingRequest *pr) { struct GNUNET_MQ_Envelope *env; struct GetMessage *gm; @@ -532,61 +531,61 @@ GSF_pending_request_get_message_ (struct GSF_PendingRequest *pr) void *bf_data; uint32_t bf_nonce; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Building request message for `%s' of type %d\n", - GNUNET_h2s (&pr->public_data.query), - pr->public_data.type); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Building request message for `%s' of type %d\n", + GNUNET_h2s(&pr->public_data.query), + pr->public_data.type); k = 0; bm = 0; do_route = (0 == (pr->public_data.options & GSF_PRO_FORWARD_ONLY)); - if ((! do_route) && (pr->sender_pid == 0)) - { - GNUNET_break (0); - do_route = GNUNET_YES; - } - if (! do_route) - { - bm |= GET_MESSAGE_BIT_RETURN_TO; - k++; - } + if ((!do_route) && (pr->sender_pid == 0)) + { + GNUNET_break(0); + do_route = GNUNET_YES; + } + if (!do_route) + { + bm |= GET_MESSAGE_BIT_RETURN_TO; + k++; + } if (NULL != pr->public_data.target) - { - bm |= GET_MESSAGE_BIT_TRANSMIT_TO; - k++; - } + { + bm |= GET_MESSAGE_BIT_TRANSMIT_TO; + k++; + } if (GNUNET_OK != - GNUNET_BLOCK_group_serialize (pr->bg, &bf_nonce, &bf_data, &bf_size)) - { - bf_size = 0; - bf_data = NULL; - } - env = GNUNET_MQ_msg_extra (gm, - bf_size + k * sizeof (struct GNUNET_PeerIdentity), - GNUNET_MESSAGE_TYPE_FS_GET); - gm->type = htonl (pr->public_data.type); + GNUNET_BLOCK_group_serialize(pr->bg, &bf_nonce, &bf_data, &bf_size)) + { + bf_size = 0; + bf_data = NULL; + } + env = GNUNET_MQ_msg_extra(gm, + bf_size + k * sizeof(struct GNUNET_PeerIdentity), + GNUNET_MESSAGE_TYPE_FS_GET); + gm->type = htonl(pr->public_data.type); if (do_route) - prio = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - pr->public_data.priority + 1); + prio = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + pr->public_data.priority + 1); else prio = 0; pr->public_data.priority -= prio; pr->public_data.num_transmissions++; pr->public_data.respect_offered += prio; - gm->priority = htonl (prio); - now = GNUNET_TIME_absolute_get (); - ttl = (int64_t) (pr->public_data.ttl.abs_value_us - now.abs_value_us); - gm->ttl = htonl (ttl / 1000LL / 1000LL); - gm->filter_mutator = htonl (bf_nonce); - gm->hash_bitmap = htonl (bm); + gm->priority = htonl(prio); + now = GNUNET_TIME_absolute_get(); + ttl = (int64_t)(pr->public_data.ttl.abs_value_us - now.abs_value_us); + gm->ttl = htonl(ttl / 1000LL / 1000LL); + gm->filter_mutator = htonl(bf_nonce); + gm->hash_bitmap = htonl(bm); gm->query = pr->public_data.query; - ext = (struct GNUNET_PeerIdentity *) &gm[1]; + ext = (struct GNUNET_PeerIdentity *)&gm[1]; k = 0; - if (! do_route) - GNUNET_PEER_resolve (pr->sender_pid, &ext[k++]); + if (!do_route) + GNUNET_PEER_resolve(pr->sender_pid, &ext[k++]); if (NULL != pr->public_data.target) ext[k++] = *pr->public_data.target; - GNUNET_memcpy (&ext[k], bf_data, bf_size); - GNUNET_free_non_null (bf_data); + GNUNET_memcpy(&ext[k], bf_data, bf_size); + GNUNET_free_non_null(bf_data); return env; } @@ -600,61 +599,61 @@ GSF_pending_request_get_message_ (struct GSF_PendingRequest *pr) * @return #GNUNET_YES (we should continue to iterate) */ static int -clean_request (void *cls, const struct GNUNET_HashCode *key, void *value) +clean_request(void *cls, const struct GNUNET_HashCode *key, void *value) { struct GSF_PendingRequest *pr = value; GSF_LocalLookupContinuation cont; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Cleaning up pending request for `%s'.\n", - GNUNET_h2s (key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Cleaning up pending request for `%s'.\n", + GNUNET_h2s(key)); if (NULL != pr->cadet_request) - { - pr->cadet_retry_count = CADET_RETRY_MAX; - GSF_cadet_query_cancel (pr->cadet_request); - pr->cadet_request = NULL; - } + { + pr->cadet_retry_count = CADET_RETRY_MAX; + GSF_cadet_query_cancel(pr->cadet_request); + pr->cadet_request = NULL; + } if (NULL != (cont = pr->llc_cont)) - { - pr->llc_cont = NULL; - cont (pr->llc_cont_cls, pr, pr->local_result); - } - GSF_plan_notify_request_done_ (pr); - GNUNET_free_non_null (pr->replies_seen); - GNUNET_BLOCK_group_destroy (pr->bg); + { + pr->llc_cont = NULL; + cont(pr->llc_cont_cls, pr, pr->local_result); + } + GSF_plan_notify_request_done_(pr); + GNUNET_free_non_null(pr->replies_seen); + GNUNET_BLOCK_group_destroy(pr->bg); pr->bg = NULL; - GNUNET_PEER_change_rc (pr->sender_pid, -1); + GNUNET_PEER_change_rc(pr->sender_pid, -1); pr->sender_pid = 0; - GNUNET_PEER_change_rc (pr->origin_pid, -1); + GNUNET_PEER_change_rc(pr->origin_pid, -1); pr->origin_pid = 0; if (NULL != pr->hnode) - { - GNUNET_CONTAINER_heap_remove_node (pr->hnode); - pr->hnode = NULL; - } + { + GNUNET_CONTAINER_heap_remove_node(pr->hnode); + pr->hnode = NULL; + } if (NULL != pr->qe) - { - GNUNET_DATASTORE_cancel (pr->qe); - pr->qe = NULL; - } + { + GNUNET_DATASTORE_cancel(pr->qe); + pr->qe = NULL; + } if (NULL != pr->gh) - { - GNUNET_DHT_get_stop (pr->gh); - pr->gh = NULL; - } + { + GNUNET_DHT_get_stop(pr->gh); + pr->gh = NULL; + } if (NULL != pr->warn_task) - { - GNUNET_SCHEDULER_cancel (pr->warn_task); - pr->warn_task = NULL; - } - GNUNET_assert ( + { + GNUNET_SCHEDULER_cancel(pr->warn_task); + pr->warn_task = NULL; + } + GNUNET_assert( GNUNET_OK == - GNUNET_CONTAINER_multihashmap_remove (pr_map, &pr->public_data.query, pr)); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# Pending requests active"), - -1, - GNUNET_NO); - GNUNET_free (pr); + GNUNET_CONTAINER_multihashmap_remove(pr_map, &pr->public_data.query, pr)); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# Pending requests active"), + -1, + GNUNET_NO); + GNUNET_free(pr); return GNUNET_YES; } @@ -666,49 +665,49 @@ clean_request (void *cls, const struct GNUNET_HashCode *key, void *value) * @param full_cleanup fully purge the request */ void -GSF_pending_request_cancel_ (struct GSF_PendingRequest *pr, int full_cleanup) +GSF_pending_request_cancel_(struct GSF_PendingRequest *pr, int full_cleanup) { GSF_LocalLookupContinuation cont; if (NULL == pr_map) return; /* already cleaned up! */ if (GNUNET_NO == full_cleanup) - { - /* make request inactive (we're no longer interested in more results), - * but do NOT remove from our data-structures, we still need it there - * to prevent the request from looping */ - pr->rh = NULL; - if (NULL != pr->cadet_request) { - pr->cadet_retry_count = CADET_RETRY_MAX; - GSF_cadet_query_cancel (pr->cadet_request); - pr->cadet_request = NULL; + /* make request inactive (we're no longer interested in more results), + * but do NOT remove from our data-structures, we still need it there + * to prevent the request from looping */ + pr->rh = NULL; + if (NULL != pr->cadet_request) + { + pr->cadet_retry_count = CADET_RETRY_MAX; + GSF_cadet_query_cancel(pr->cadet_request); + pr->cadet_request = NULL; + } + if (NULL != (cont = pr->llc_cont)) + { + pr->llc_cont = NULL; + cont(pr->llc_cont_cls, pr, pr->local_result); + } + GSF_plan_notify_request_done_(pr); + if (NULL != pr->qe) + { + GNUNET_DATASTORE_cancel(pr->qe); + pr->qe = NULL; + } + if (NULL != pr->gh) + { + GNUNET_DHT_get_stop(pr->gh); + pr->gh = NULL; + } + if (NULL != pr->warn_task) + { + GNUNET_SCHEDULER_cancel(pr->warn_task); + pr->warn_task = NULL; + } + return; } - if (NULL != (cont = pr->llc_cont)) - { - pr->llc_cont = NULL; - cont (pr->llc_cont_cls, pr, pr->local_result); - } - GSF_plan_notify_request_done_ (pr); - if (NULL != pr->qe) - { - GNUNET_DATASTORE_cancel (pr->qe); - pr->qe = NULL; - } - if (NULL != pr->gh) - { - GNUNET_DHT_get_stop (pr->gh); - pr->gh = NULL; - } - if (NULL != pr->warn_task) - { - GNUNET_SCHEDULER_cancel (pr->warn_task); - pr->warn_task = NULL; - } - return; - } - GNUNET_assert (GNUNET_YES == - clean_request (NULL, &pr->public_data.query, pr)); + GNUNET_assert(GNUNET_YES == + clean_request(NULL, &pr->public_data.query, pr)); } @@ -719,11 +718,11 @@ GSF_pending_request_cancel_ (struct GSF_PendingRequest *pr, int full_cleanup) * @param cls closure for @a it */ void -GSF_iterate_pending_requests_ (GSF_PendingRequestIterator it, void *cls) +GSF_iterate_pending_requests_(GSF_PendingRequestIterator it, void *cls) { - GNUNET_CONTAINER_multihashmap_iterate ( + GNUNET_CONTAINER_multihashmap_iterate( pr_map, - (GNUNET_CONTAINER_MulitHashMapIteratorCallback) it, + (GNUNET_CONTAINER_MulitHashMapIteratorCallback)it, cls); } @@ -731,8 +730,7 @@ GSF_iterate_pending_requests_ (GSF_PendingRequestIterator it, void *cls) /** * Closure for process_reply() function. */ -struct ProcessReplyClosure -{ +struct ProcessReplyClosure { /** * The data for the reply. */ @@ -793,14 +791,14 @@ struct ProcessReplyClosure * @param pr request that was satisfied */ static void -update_request_performance_data (struct ProcessReplyClosure *prq, - struct GSF_PendingRequest *pr) +update_request_performance_data(struct ProcessReplyClosure *prq, + struct GSF_PendingRequest *pr) { if (prq->sender == NULL) return; - GSF_peer_update_performance_ (prq->sender, - pr->public_data.start_time, - prq->priority); + GSF_peer_update_performance_(prq->sender, + pr->public_data.start_time, + prq->priority); } @@ -813,7 +811,7 @@ update_request_performance_data (struct ProcessReplyClosure *prq, * @return #GNUNET_YES (we should continue to iterate) */ static int -process_reply (void *cls, const struct GNUNET_HashCode *key, void *value) +process_reply(void *cls, const struct GNUNET_HashCode *key, void *value) { struct ProcessReplyClosure *prq = cls; struct GSF_PendingRequest *pr = value; @@ -822,121 +820,128 @@ process_reply (void *cls, const struct GNUNET_HashCode *key, void *value) if (NULL == pr->rh) return GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Matched result (type %u) for query `%s' with pending request\n", - (unsigned int) prq->type, - GNUNET_h2s (key)); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# replies received and matched"), - 1, - GNUNET_NO); - prq->eval = GNUNET_BLOCK_evaluate (GSF_block_ctx, - prq->type, - pr->bg, - prq->eo, - key, - NULL, - 0, - prq->data, - prq->size); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Matched result (type %u) for query `%s' with pending request\n", + (unsigned int)prq->type, + GNUNET_h2s(key)); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# replies received and matched"), + 1, + GNUNET_NO); + prq->eval = GNUNET_BLOCK_evaluate(GSF_block_ctx, + prq->type, + pr->bg, + prq->eo, + key, + NULL, + 0, + prq->data, + prq->size); switch (prq->eval) - { - case GNUNET_BLOCK_EVALUATION_OK_MORE: - update_request_performance_data (prq, pr); - break; - case GNUNET_BLOCK_EVALUATION_OK_LAST: - /* short cut: stop processing early, no BF-update, etc. */ - update_request_performance_data (prq, pr); - GNUNET_LOAD_update (GSF_rt_entry_lifetime, - GNUNET_TIME_absolute_get_duration ( - pr->public_data.start_time) - .rel_value_us); - if (GNUNET_YES != - GSF_request_plan_reference_get_last_transmission_ (pr->public_data - .pr_head, - prq->sender, - &last_transmission)) - last_transmission.abs_value_us = - GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us; - /* pass on to other peers / local clients */ - pr->rh (pr->rh_cls, - prq->eval, - pr, - prq->anonymity_level, - prq->expiration, - last_transmission, - prq->type, - prq->data, - prq->size); - return GNUNET_YES; - case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE: + { + case GNUNET_BLOCK_EVALUATION_OK_MORE: + update_request_performance_data(prq, pr); + break; + + case GNUNET_BLOCK_EVALUATION_OK_LAST: + /* short cut: stop processing early, no BF-update, etc. */ + update_request_performance_data(prq, pr); + GNUNET_LOAD_update(GSF_rt_entry_lifetime, + GNUNET_TIME_absolute_get_duration( + pr->public_data.start_time) + .rel_value_us); + if (GNUNET_YES != + GSF_request_plan_reference_get_last_transmission_(pr->public_data + .pr_head, + prq->sender, + &last_transmission)) + last_transmission.abs_value_us = + GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us; + /* pass on to other peers / local clients */ + pr->rh(pr->rh_cls, + prq->eval, + pr, + prq->anonymity_level, + prq->expiration, + last_transmission, + prq->type, + prq->data, + prq->size); + return GNUNET_YES; + + case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE: #if INSANE_STATISTICS - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ( - "# duplicate replies discarded (bloomfilter)"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop( + "# duplicate replies discarded (bloomfilter)"), + 1, + GNUNET_NO); #endif - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Duplicate response, discarding.\n"); - return GNUNET_YES; /* duplicate */ - case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT: - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# irrelevant replies discarded"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Irrelevant response, ignoring.\n"); - return GNUNET_YES; - case GNUNET_BLOCK_EVALUATION_RESULT_INVALID: - return GNUNET_YES; /* wrong namespace */ - case GNUNET_BLOCK_EVALUATION_REQUEST_VALID: - GNUNET_break (0); - return GNUNET_YES; - case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID: - GNUNET_break (0); - return GNUNET_YES; - case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unsupported block type %u\n"), - prq->type); - return GNUNET_NO; - } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Duplicate response, discarding.\n"); + return GNUNET_YES; /* duplicate */ + + case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT: + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# irrelevant replies discarded"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Irrelevant response, ignoring.\n"); + return GNUNET_YES; + + case GNUNET_BLOCK_EVALUATION_RESULT_INVALID: + return GNUNET_YES; /* wrong namespace */ + + case GNUNET_BLOCK_EVALUATION_REQUEST_VALID: + GNUNET_break(0); + return GNUNET_YES; + + case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID: + GNUNET_break(0); + return GNUNET_YES; + + case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED: + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unsupported block type %u\n"), + prq->type); + return GNUNET_NO; + } /* update bloomfilter */ - GNUNET_CRYPTO_hash (prq->data, prq->size, &chash); - GSF_pending_request_update_ (pr, &chash, 1); + GNUNET_CRYPTO_hash(prq->data, prq->size, &chash); + GSF_pending_request_update_(pr, &chash, 1); if (NULL == prq->sender) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found result for query `%s' in local datastore\n", - GNUNET_h2s (key)); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# results found locally"), - 1, - GNUNET_NO); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found result for query `%s' in local datastore\n", + GNUNET_h2s(key)); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# results found locally"), + 1, + GNUNET_NO); + } else - { - GSF_dht_lookup_ (pr); - } + { + GSF_dht_lookup_(pr); + } prq->priority += pr->public_data.original_priority; pr->public_data.priority = 0; pr->public_data.original_priority = 0; pr->public_data.results_found++; prq->request_found = GNUNET_YES; /* finally, pass on to other peer / local client */ - if (! GSF_request_plan_reference_get_last_transmission_ (pr->public_data - .pr_head, - prq->sender, - &last_transmission)) + if (!GSF_request_plan_reference_get_last_transmission_(pr->public_data + .pr_head, + prq->sender, + &last_transmission)) last_transmission.abs_value_us = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us; - pr->rh (pr->rh_cls, - prq->eval, - pr, - prq->anonymity_level, - prq->expiration, - last_transmission, - prq->type, - prq->data, - prq->size); + pr->rh(pr->rh_cls, + prq->eval, + pr, + prq->anonymity_level, + prq->expiration, + last_transmission, + prq->type, + prq->data, + prq->size); return GNUNET_YES; } @@ -944,9 +949,7 @@ process_reply (void *cls, const struct GNUNET_HashCode *key, void *value) /** * Context for put_migration_continuation(). */ -struct PutMigrationContext -{ - +struct PutMigrationContext { /** * Start time for the operation. */ @@ -975,10 +978,10 @@ struct PutMigrationContext * @param msg NULL on success, otherwise an error message */ static void -put_migration_continuation (void *cls, - int success, - struct GNUNET_TIME_Absolute min_expiration, - const char *msg) +put_migration_continuation(void *cls, + int success, + struct GNUNET_TIME_Absolute min_expiration, + const char *msg) { struct PutMigrationContext *pmc = cls; struct GSF_ConnectedPeer *cp; @@ -986,67 +989,67 @@ put_migration_continuation (void *cls, struct GSF_PeerPerformanceData *ppd; if (NULL != datastore_put_load) - { - if (GNUNET_SYSERR != success) { - GNUNET_LOAD_update (datastore_put_load, - GNUNET_TIME_absolute_get_duration (pmc->start) - .rel_value_us); + if (GNUNET_SYSERR != success) + { + GNUNET_LOAD_update(datastore_put_load, + GNUNET_TIME_absolute_get_duration(pmc->start) + .rel_value_us); + } + else + { + /* on queue failure / timeout, increase the put load dramatically */ + GNUNET_LOAD_update(datastore_put_load, + GNUNET_TIME_UNIT_MINUTES.rel_value_us); + } } - else - { - /* on queue failure / timeout, increase the put load dramatically */ - GNUNET_LOAD_update (datastore_put_load, - GNUNET_TIME_UNIT_MINUTES.rel_value_us); - } - } - cp = GSF_peer_get_ (&pmc->origin); + cp = GSF_peer_get_(&pmc->origin); if (GNUNET_OK == success) - { - if (NULL != cp) { - ppd = GSF_get_peer_performance_data_ (cp); - ppd->migration_delay.rel_value_us /= 2; + if (NULL != cp) + { + ppd = GSF_get_peer_performance_data_(cp); + ppd->migration_delay.rel_value_us /= 2; + } + GNUNET_free(pmc); + return; } - GNUNET_free (pmc); - return; - } if ((GNUNET_NO == success) && (GNUNET_NO == pmc->requested) && (NULL != cp)) - { - ppd = GSF_get_peer_performance_data_ (cp); - if (min_expiration.abs_value_us > 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Asking to stop migration for %s because datastore is full\n", - GNUNET_STRINGS_relative_time_to_string ( - GNUNET_TIME_absolute_get_remaining (min_expiration), - GNUNET_YES)); - GSF_block_peer_migration_ (cp, min_expiration); - } - else { - ppd->migration_delay = GNUNET_TIME_relative_max (GNUNET_TIME_UNIT_SECONDS, - ppd->migration_delay); - ppd->migration_delay = - GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_HOURS, ppd->migration_delay); - mig_pause.rel_value_us = - GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, - ppd->migration_delay.rel_value_us); - ppd->migration_delay = - GNUNET_TIME_relative_saturating_multiply (ppd->migration_delay, 2); - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Replicated content already exists locally, asking to stop migration for %s\n", - GNUNET_STRINGS_relative_time_to_string (mig_pause, GNUNET_YES)); - GSF_block_peer_migration_ (cp, - GNUNET_TIME_relative_to_absolute (mig_pause)); + ppd = GSF_get_peer_performance_data_(cp); + if (min_expiration.abs_value_us > 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Asking to stop migration for %s because datastore is full\n", + GNUNET_STRINGS_relative_time_to_string( + GNUNET_TIME_absolute_get_remaining(min_expiration), + GNUNET_YES)); + GSF_block_peer_migration_(cp, min_expiration); + } + else + { + ppd->migration_delay = GNUNET_TIME_relative_max(GNUNET_TIME_UNIT_SECONDS, + ppd->migration_delay); + ppd->migration_delay = + GNUNET_TIME_relative_min(GNUNET_TIME_UNIT_HOURS, ppd->migration_delay); + mig_pause.rel_value_us = + GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, + ppd->migration_delay.rel_value_us); + ppd->migration_delay = + GNUNET_TIME_relative_saturating_multiply(ppd->migration_delay, 2); + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Replicated content already exists locally, asking to stop migration for %s\n", + GNUNET_STRINGS_relative_time_to_string(mig_pause, GNUNET_YES)); + GSF_block_peer_migration_(cp, + GNUNET_TIME_relative_to_absolute(mig_pause)); + } } - } - GNUNET_free (pmc); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# Datastore `PUT' failures"), - 1, - GNUNET_NO); + GNUNET_free(pmc); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# Datastore `PUT' failures"), + 1, + GNUNET_NO); } @@ -1060,22 +1063,22 @@ put_migration_continuation (void *cls, * #GNUNET_NO to process normally (load normal or low) */ static int -test_put_load_too_high (uint32_t priority) +test_put_load_too_high(uint32_t priority) { double ld; if (NULL == datastore_put_load) return GNUNET_NO; - if (GNUNET_LOAD_get_average (datastore_put_load) < 50) + if (GNUNET_LOAD_get_average(datastore_put_load) < 50) return GNUNET_NO; /* very fast */ - ld = GNUNET_LOAD_get_load (datastore_put_load); + ld = GNUNET_LOAD_get_load(datastore_put_load); if (ld < 2.0 * (1 + priority)) return GNUNET_NO; - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ( - "# storage requests dropped due to high load"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop( + "# storage requests dropped due to high load"), + 1, + GNUNET_NO); return GNUNET_YES; } @@ -1096,67 +1099,67 @@ test_put_load_too_high (uint32_t priority) * @param data pointer to the result data */ static void -handle_dht_reply (void *cls, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - enum GNUNET_BLOCK_Type type, - size_t size, - const void *data) +handle_dht_reply(void *cls, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + enum GNUNET_BLOCK_Type type, + size_t size, + const void *data) { struct GSF_PendingRequest *pr = cls; struct ProcessReplyClosure prq; struct PutMigrationContext *pmc; - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# Replies received from DHT"), - 1, - GNUNET_NO); - memset (&prq, 0, sizeof (prq)); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# Replies received from DHT"), + 1, + GNUNET_NO); + memset(&prq, 0, sizeof(prq)); prq.data = data; prq.expiration = exp; /* do not allow migrated content to live longer than 1 year */ - prq.expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute ( - GNUNET_TIME_UNIT_YEARS), - prq.expiration); + prq.expiration = GNUNET_TIME_absolute_min(GNUNET_TIME_relative_to_absolute( + GNUNET_TIME_UNIT_YEARS), + prq.expiration); prq.size = size; prq.type = type; prq.eo = GNUNET_BLOCK_EO_NONE; - process_reply (&prq, key, pr); + process_reply(&prq, key, pr); if ((GNUNET_YES == active_to_migration) && - (GNUNET_NO == test_put_load_too_high (prq.priority))) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Replicating result for query `%s' with priority %u\n", - GNUNET_h2s (key), - prq.priority); - pmc = GNUNET_new (struct PutMigrationContext); - pmc->start = GNUNET_TIME_absolute_get (); - pmc->requested = GNUNET_YES; - if (NULL == GNUNET_DATASTORE_put (GSF_dsh, - 0, - key, - size, - data, - type, - prq.priority, - 1 /* anonymity */, - 0 /* replication */, - exp, - 1 + prq.priority, - MAX_DATASTORE_QUEUE, - &put_migration_continuation, - pmc)) + (GNUNET_NO == test_put_load_too_high(prq.priority))) { - put_migration_continuation (pmc, - GNUNET_SYSERR, - GNUNET_TIME_UNIT_ZERO_ABS, - NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Replicating result for query `%s' with priority %u\n", + GNUNET_h2s(key), + prq.priority); + pmc = GNUNET_new(struct PutMigrationContext); + pmc->start = GNUNET_TIME_absolute_get(); + pmc->requested = GNUNET_YES; + if (NULL == GNUNET_DATASTORE_put(GSF_dsh, + 0, + key, + size, + data, + type, + prq.priority, + 1 /* anonymity */, + 0 /* replication */, + exp, + 1 + prq.priority, + MAX_DATASTORE_QUEUE, + &put_migration_continuation, + pmc)) + { + put_migration_continuation(pmc, + GNUNET_SYSERR, + GNUNET_TIME_UNIT_ZERO_ABS, + NULL); + } } - } } @@ -1166,42 +1169,42 @@ handle_dht_reply (void *cls, * @param pr the pending request to process */ void -GSF_dht_lookup_ (struct GSF_PendingRequest *pr) +GSF_dht_lookup_(struct GSF_PendingRequest *pr) { const void *xquery; size_t xquery_size; struct GNUNET_PeerIdentity pi; - char buf[sizeof (struct GNUNET_HashCode) * 2] GNUNET_ALIGN; + char buf[sizeof(struct GNUNET_HashCode) * 2] GNUNET_ALIGN; if (0 != pr->public_data.anonymity_level) return; if (NULL != pr->gh) - { - GNUNET_DHT_get_stop (pr->gh); - pr->gh = NULL; - } + { + GNUNET_DHT_get_stop(pr->gh); + pr->gh = NULL; + } xquery = NULL; xquery_size = 0; if (0 != (pr->public_data.options & GSF_PRO_FORWARD_ONLY)) - { - GNUNET_assert (0 != pr->sender_pid); - GNUNET_PEER_resolve (pr->sender_pid, &pi); - GNUNET_memcpy (&buf[xquery_size], &pi, sizeof (struct GNUNET_PeerIdentity)); - xquery_size += sizeof (struct GNUNET_PeerIdentity); - } - pr->gh = GNUNET_DHT_get_start (GSF_dht, - pr->public_data.type, - &pr->public_data.query, - DHT_GET_REPLICATION, - GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, - xquery, - xquery_size, - &handle_dht_reply, - pr); + { + GNUNET_assert(0 != pr->sender_pid); + GNUNET_PEER_resolve(pr->sender_pid, &pi); + GNUNET_memcpy(&buf[xquery_size], &pi, sizeof(struct GNUNET_PeerIdentity)); + xquery_size += sizeof(struct GNUNET_PeerIdentity); + } + pr->gh = GNUNET_DHT_get_start(GSF_dht, + pr->public_data.type, + &pr->public_data.query, + DHT_GET_REPLICATION, + GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, + xquery, + xquery_size, + &handle_dht_reply, + pr); if ((NULL != pr->gh) && (0 != pr->replies_seen_count)) - GNUNET_DHT_get_filter_known_results (pr->gh, - pr->replies_seen_count, - pr->replies_seen); + GNUNET_DHT_get_filter_known_results(pr->gh, + pr->replies_seen_count, + pr->replies_seen); } @@ -1215,11 +1218,11 @@ GSF_dht_lookup_ (struct GSF_PendingRequest *pr) * @param data reply block data, NULL on error */ static void -cadet_reply_proc (void *cls, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute expiration, - size_t data_size, - const void *data) +cadet_reply_proc(void *cls, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute expiration, + size_t data_size, + const void *data) { struct GSF_PendingRequest *pr = cls; struct ProcessReplyClosure prq; @@ -1227,46 +1230,46 @@ cadet_reply_proc (void *cls, pr->cadet_request = NULL; if (GNUNET_BLOCK_TYPE_ANY == type) - { - GNUNET_break (NULL == data); - GNUNET_break (0 == data_size); - pr->cadet_retry_count++; - if (pr->cadet_retry_count >= CADET_RETRY_MAX) - return; /* give up on cadet */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Error retrieiving block via cadet\n"); - /* retry -- without delay, as this is non-anonymous - and cadet/cadet connect will take some time anyway */ - pr->cadet_request = GSF_cadet_query (pr->public_data.target, - &pr->public_data.query, - pr->public_data.type, - &cadet_reply_proc, - pr); - return; - } + { + GNUNET_break(NULL == data); + GNUNET_break(0 == data_size); + pr->cadet_retry_count++; + if (pr->cadet_retry_count >= CADET_RETRY_MAX) + return; /* give up on cadet */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Error retrieiving block via cadet\n"); + /* retry -- without delay, as this is non-anonymous + and cadet/cadet connect will take some time anyway */ + pr->cadet_request = GSF_cadet_query(pr->public_data.target, + &pr->public_data.query, + pr->public_data.type, + &cadet_reply_proc, + pr); + return; + } if (GNUNET_YES != - GNUNET_BLOCK_get_key (GSF_block_ctx, type, data, data_size, &query)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Failed to derive key for block of type %d\n", - (int) type); - GNUNET_break_op (0); - return; - } - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# Replies received from CADET"), - 1, - GNUNET_NO); - memset (&prq, 0, sizeof (prq)); + GNUNET_BLOCK_get_key(GSF_block_ctx, type, data, data_size, &query)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Failed to derive key for block of type %d\n", + (int)type); + GNUNET_break_op(0); + return; + } + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# Replies received from CADET"), + 1, + GNUNET_NO); + memset(&prq, 0, sizeof(prq)); prq.data = data; prq.expiration = expiration; /* do not allow migrated content to live longer than 1 year */ - prq.expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute ( - GNUNET_TIME_UNIT_YEARS), - prq.expiration); + prq.expiration = GNUNET_TIME_absolute_min(GNUNET_TIME_relative_to_absolute( + GNUNET_TIME_UNIT_YEARS), + prq.expiration); prq.size = data_size; prq.type = type; prq.eo = GNUNET_BLOCK_EO_NONE; - process_reply (&prq, &query, pr); + process_reply(&prq, &query, pr); } @@ -1276,23 +1279,23 @@ cadet_reply_proc (void *cls, * @param pr the pending request to process */ void -GSF_cadet_lookup_ (struct GSF_PendingRequest *pr) +GSF_cadet_lookup_(struct GSF_PendingRequest *pr) { if (0 != pr->public_data.anonymity_level) return; if (0 == pr->public_data.target) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Cannot do cadet-based download, target peer not known\n"); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Cannot do cadet-based download, target peer not known\n"); + return; + } if (NULL != pr->cadet_request) return; - pr->cadet_request = GSF_cadet_query (pr->public_data.target, - &pr->public_data.query, - pr->public_data.type, - &cadet_reply_proc, - pr); + pr->cadet_request = GSF_cadet_query(pr->public_data.target, + &pr->public_data.query, + pr->public_data.type, + &cadet_reply_proc, + pr); } @@ -1302,18 +1305,18 @@ GSF_cadet_lookup_ (struct GSF_PendingRequest *pr) * @param cls the `struct GSF_PendingRequest` */ static void -warn_delay_task (void *cls) +warn_delay_task(void *cls) { struct GSF_PendingRequest *pr = cls; - GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, - _ ("Datastore lookup already took %s!\n"), - GNUNET_STRINGS_relative_time_to_string ( - GNUNET_TIME_absolute_get_duration (pr->qe_start), - GNUNET_YES)); - pr->warn_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, - &warn_delay_task, - pr); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, + _("Datastore lookup already took %s!\n"), + GNUNET_STRINGS_relative_time_to_string( + GNUNET_TIME_absolute_get_duration(pr->qe_start), + GNUNET_YES)); + pr->warn_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES, + &warn_delay_task, + pr); } @@ -1323,140 +1326,140 @@ warn_delay_task (void *cls) * @param cls the `struct GSF_PendingRequest` */ static void -odc_warn_delay_task (void *cls) +odc_warn_delay_task(void *cls) { struct GSF_PendingRequest *pr = cls; - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("On-demand lookup already took %s!\n"), - GNUNET_STRINGS_relative_time_to_string ( - GNUNET_TIME_absolute_get_duration (pr->qe_start), - GNUNET_YES)); - pr->warn_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, - &odc_warn_delay_task, - pr); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("On-demand lookup already took %s!\n"), + GNUNET_STRINGS_relative_time_to_string( + GNUNET_TIME_absolute_get_duration(pr->qe_start), + GNUNET_YES)); + pr->warn_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES, + &odc_warn_delay_task, + pr); } /* Call our continuation (if we have any) */ static void -call_continuation (struct GSF_PendingRequest *pr) +call_continuation(struct GSF_PendingRequest *pr) { GSF_LocalLookupContinuation cont = pr->llc_cont; - GNUNET_assert (NULL == pr->qe); + GNUNET_assert(NULL == pr->qe); if (NULL != pr->warn_task) - { - GNUNET_SCHEDULER_cancel (pr->warn_task); - pr->warn_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(pr->warn_task); + pr->warn_task = NULL; + } if (NULL == cont) return; /* no continuation */ pr->llc_cont = NULL; if (0 != (GSF_PRO_LOCAL_ONLY & pr->public_data.options)) - { - if (GNUNET_BLOCK_EVALUATION_OK_LAST != pr->local_result) { - /* Signal that we are done and that there won't be any - additional results to allow client to clean up state. */ - pr->rh (pr->rh_cls, - GNUNET_BLOCK_EVALUATION_OK_LAST, - pr, - UINT32_MAX, - GNUNET_TIME_UNIT_ZERO_ABS, - GNUNET_TIME_UNIT_FOREVER_ABS, - GNUNET_BLOCK_TYPE_ANY, - NULL, - 0); + if (GNUNET_BLOCK_EVALUATION_OK_LAST != pr->local_result) + { + /* Signal that we are done and that there won't be any + additional results to allow client to clean up state. */ + pr->rh(pr->rh_cls, + GNUNET_BLOCK_EVALUATION_OK_LAST, + pr, + UINT32_MAX, + GNUNET_TIME_UNIT_ZERO_ABS, + GNUNET_TIME_UNIT_FOREVER_ABS, + GNUNET_BLOCK_TYPE_ANY, + NULL, + 0); + } + /* Finally, call our continuation to signal that we are + done with local processing of this request; i.e. to + start reading again from the client. */ + cont(pr->llc_cont_cls, NULL, GNUNET_BLOCK_EVALUATION_OK_LAST); + return; } - /* Finally, call our continuation to signal that we are - done with local processing of this request; i.e. to - start reading again from the client. */ - cont (pr->llc_cont_cls, NULL, GNUNET_BLOCK_EVALUATION_OK_LAST); - return; - } - cont (pr->llc_cont_cls, pr, pr->local_result); + cont(pr->llc_cont_cls, pr, pr->local_result); } /* Update stats and call continuation */ static void -no_more_local_results (struct GSF_PendingRequest *pr) +no_more_local_results(struct GSF_PendingRequest *pr) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, - "No further local responses available.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, + "No further local responses available.\n"); #if INSANE_STATISTICS if ((GNUNET_BLOCK_TYPE_FS_DBLOCK == pr->public_data.type) || (GNUNET_BLOCK_TYPE_FS_IBLOCK == pr->public_data.type)) - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ( - "# requested DBLOCK or IBLOCK not found"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop( + "# requested DBLOCK or IBLOCK not found"), + 1, + GNUNET_NO); #endif - call_continuation (pr); + call_continuation(pr); } /* forward declaration */ static void -process_local_reply (void *cls, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid); +process_local_reply(void *cls, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid); /* Start a local query */ static void -start_local_query (struct GSF_PendingRequest *pr, - uint64_t next_uid, - bool random) +start_local_query(struct GSF_PendingRequest *pr, + uint64_t next_uid, + bool random) { - pr->qe_start = GNUNET_TIME_absolute_get (); - pr->warn_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, - &warn_delay_task, - pr); - pr->qe = GNUNET_DATASTORE_get_key (GSF_dsh, - next_uid, - random, - &pr->public_data.query, - pr->public_data.type == - GNUNET_BLOCK_TYPE_FS_DBLOCK - ? GNUNET_BLOCK_TYPE_ANY - : pr->public_data.type, - (0 != (GSF_PRO_PRIORITY_UNLIMITED & - pr->public_data.options)) - ? UINT_MAX - : 1 - /* queue priority */, - (0 != (GSF_PRO_PRIORITY_UNLIMITED & - pr->public_data.options)) - ? UINT_MAX - : GSF_datastore_queue_size - /* max queue size */, - &process_local_reply, - pr); + pr->qe_start = GNUNET_TIME_absolute_get(); + pr->warn_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES, + &warn_delay_task, + pr); + pr->qe = GNUNET_DATASTORE_get_key(GSF_dsh, + next_uid, + random, + &pr->public_data.query, + pr->public_data.type == + GNUNET_BLOCK_TYPE_FS_DBLOCK + ? GNUNET_BLOCK_TYPE_ANY + : pr->public_data.type, + (0 != (GSF_PRO_PRIORITY_UNLIMITED & + pr->public_data.options)) + ? UINT_MAX + : 1 + /* queue priority */, + (0 != (GSF_PRO_PRIORITY_UNLIMITED & + pr->public_data.options)) + ? UINT_MAX + : GSF_datastore_queue_size + /* max queue size */, + &process_local_reply, + pr); if (NULL != pr->qe) return; - GNUNET_log ( + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "ERROR Requesting `%s' of type %d with next_uid %llu from datastore.\n", - GNUNET_h2s (&pr->public_data.query), + GNUNET_h2s(&pr->public_data.query), pr->public_data.type, - (unsigned long long) next_uid); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ( - "# Datastore lookups concluded (error queueing)"), - 1, - GNUNET_NO); - call_continuation (pr); + (unsigned long long)next_uid); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop( + "# Datastore lookups concluded (error queueing)"), + 1, + GNUNET_NO); + call_continuation(pr); } @@ -1479,178 +1482,178 @@ start_local_query (struct GSF_PendingRequest *pr, * maybe 0 if no unique identifier is available */ static void -process_local_reply (void *cls, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +process_local_reply(void *cls, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct GSF_PendingRequest *pr = cls; struct ProcessReplyClosure prq; struct GNUNET_HashCode query; unsigned int old_rf; - GNUNET_SCHEDULER_cancel (pr->warn_task); + GNUNET_SCHEDULER_cancel(pr->warn_task); pr->warn_task = NULL; if (NULL == pr->qe) goto called_from_on_demand; pr->qe = NULL; if ( (NULL == key) && pr->seen_null && - ! pr->have_first_uid) /* We have hit the end for the 2nd time with no results */ - { - /* No results */ + !pr->have_first_uid) /* We have hit the end for the 2nd time with no results */ + { + /* No results */ #if INSANE_STATISTICS - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ( - "# Datastore lookups concluded (no results)"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop( + "# Datastore lookups concluded (no results)"), + 1, + GNUNET_NO); #endif - no_more_local_results (pr); - return; - } + no_more_local_results(pr); + return; + } if (((NULL == key) && pr->seen_null) || /* We have hit the end for the 2nd time OR */ (pr->seen_null && pr->have_first_uid && (uid >= pr->first_uid))) /* We have hit the end and past first UID */ - { - /* Seen all results */ - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ( - "# Datastore lookups concluded (seen all)"), - 1, - GNUNET_NO); - no_more_local_results (pr); - return; - } + { + /* Seen all results */ + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop( + "# Datastore lookups concluded (seen all)"), + 1, + GNUNET_NO); + no_more_local_results(pr); + return; + } if (NULL == key) - { - GNUNET_assert (! pr->seen_null); - pr->seen_null = true; - start_local_query (pr, 0 /* next_uid */, false /* random */); - return; - } - if (! pr->have_first_uid) - { - pr->first_uid = uid; - pr->have_first_uid = true; - } + { + GNUNET_assert(!pr->seen_null); + pr->seen_null = true; + start_local_query(pr, 0 /* next_uid */, false /* random */); + return; + } + if (!pr->have_first_uid) + { + pr->first_uid = uid; + pr->have_first_uid = true; + } pr->result_count++; if (pr->result_count > MAX_RESULTS) - { - GNUNET_STATISTICS_update ( - GSF_stats, - gettext_noop ("# Datastore lookups aborted (more than MAX_RESULTS)"), - 1, - GNUNET_NO); - no_more_local_results (pr); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received reply for `%s' of type %d with UID %llu from datastore.\n", - GNUNET_h2s (key), - type, - (unsigned long long) uid); + { + GNUNET_STATISTICS_update( + GSF_stats, + gettext_noop("# Datastore lookups aborted (more than MAX_RESULTS)"), + 1, + GNUNET_NO); + no_more_local_results(pr); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received reply for `%s' of type %d with UID %llu from datastore.\n", + GNUNET_h2s(key), + type, + (unsigned long long)uid); if (GNUNET_BLOCK_TYPE_FS_ONDEMAND == type) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found ONDEMAND block, performing on-demand encoding\n"); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ( - "# on-demand blocks matched requests"), - 1, - GNUNET_NO); - pr->qe_start = GNUNET_TIME_absolute_get (); - pr->warn_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, - &odc_warn_delay_task, - pr); - if (GNUNET_OK == GNUNET_FS_handle_on_demand_block (key, - size, - data, - type, - priority, - anonymity, - replication, - expiration, - uid, - &process_local_reply, - pr)) { - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ( - "# on-demand lookups performed successfully"), - 1, - GNUNET_NO); - return; /* we're done */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found ONDEMAND block, performing on-demand encoding\n"); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop( + "# on-demand blocks matched requests"), + 1, + GNUNET_NO); + pr->qe_start = GNUNET_TIME_absolute_get(); + pr->warn_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES, + &odc_warn_delay_task, + pr); + if (GNUNET_OK == GNUNET_FS_handle_on_demand_block(key, + size, + data, + type, + priority, + anonymity, + replication, + expiration, + uid, + &process_local_reply, + pr)) + { + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop( + "# on-demand lookups performed successfully"), + 1, + GNUNET_NO); + return; /* we're done */ + } + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# on-demand lookups failed"), + 1, + GNUNET_NO); + GNUNET_SCHEDULER_cancel(pr->warn_task); + start_local_query(pr, uid + 1 /* next_uid */, false /* random */); + return; } - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# on-demand lookups failed"), - 1, - GNUNET_NO); - GNUNET_SCHEDULER_cancel (pr->warn_task); - start_local_query (pr, uid + 1 /* next_uid */, false /* random */); - return; - } called_from_on_demand: old_rf = pr->public_data.results_found; - memset (&prq, 0, sizeof (prq)); + memset(&prq, 0, sizeof(prq)); prq.data = data; prq.expiration = expiration; prq.size = size; if (GNUNET_OK != - GNUNET_BLOCK_get_key (GSF_block_ctx, type, data, size, &query)) - { - GNUNET_break (0); - GNUNET_DATASTORE_remove (GSF_dsh, - key, - size, - data, - UINT_MAX, - UINT_MAX, - NULL, - NULL); - start_local_query (pr, uid + 1 /* next_uid */, false /* random */); - return; - } + GNUNET_BLOCK_get_key(GSF_block_ctx, type, data, size, &query)) + { + GNUNET_break(0); + GNUNET_DATASTORE_remove(GSF_dsh, + key, + size, + data, + UINT_MAX, + UINT_MAX, + NULL, + NULL); + start_local_query(pr, uid + 1 /* next_uid */, false /* random */); + return; + } prq.type = type; prq.priority = priority; prq.request_found = GNUNET_NO; prq.anonymity_level = anonymity; if ((0 == old_rf) && (0 == pr->public_data.results_found)) - GSF_update_datastore_delay_ (pr->public_data.start_time); + GSF_update_datastore_delay_(pr->public_data.start_time); prq.eo = GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO; - process_reply (&prq, key, pr); + process_reply(&prq, key, pr); pr->local_result = prq.eval; if (GNUNET_BLOCK_EVALUATION_OK_LAST == prq.eval) - { - GNUNET_STATISTICS_update ( - GSF_stats, - gettext_noop ("# Datastore lookups concluded (found last result)"), - 1, - GNUNET_NO); - call_continuation (pr); - return; - } + { + GNUNET_STATISTICS_update( + GSF_stats, + gettext_noop("# Datastore lookups concluded (found last result)"), + 1, + GNUNET_NO); + call_continuation(pr); + return; + } if ((0 == (GSF_PRO_PRIORITY_UNLIMITED & pr->public_data.options)) && - ((GNUNET_YES == GSF_test_get_load_too_high_ (0)) || + ((GNUNET_YES == GSF_test_get_load_too_high_(0)) || (pr->public_data.results_found > 5 + 2 * pr->public_data.priority))) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Load too high, done with request\n"); - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ( - "# Datastore lookups concluded (load too high)"), - 1, - GNUNET_NO); - call_continuation (pr); - return; - } - start_local_query (pr, uid + 1 /* next_uid */, false /* random */); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Load too high, done with request\n"); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop( + "# Datastore lookups concluded (load too high)"), + 1, + GNUNET_NO); + call_continuation(pr); + return; + } + start_local_query(pr, uid + 1 /* next_uid */, false /* random */); } @@ -1662,17 +1665,17 @@ called_from_on_demand: * @return #GNUNET_YES if this request could be forwarded to the given peer */ int -GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr, - const struct GNUNET_PeerIdentity *target) +GSF_pending_request_test_target_(struct GSF_PendingRequest *pr, + const struct GNUNET_PeerIdentity *target) { struct GNUNET_PeerIdentity pi; if (0 == pr->origin_pid) return GNUNET_YES; - GNUNET_PEER_resolve (pr->origin_pid, &pi); - return (0 == memcmp (&pi, target, sizeof (struct GNUNET_PeerIdentity))) - ? GNUNET_NO - : GNUNET_YES; + GNUNET_PEER_resolve(pr->origin_pid, &pi); + return (0 == memcmp(&pi, target, sizeof(struct GNUNET_PeerIdentity))) + ? GNUNET_NO + : GNUNET_YES; } @@ -1684,22 +1687,22 @@ GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr, * @param cont_cls closure for @a cont */ void -GSF_local_lookup_ (struct GSF_PendingRequest *pr, - GSF_LocalLookupContinuation cont, - void *cont_cls) +GSF_local_lookup_(struct GSF_PendingRequest *pr, + GSF_LocalLookupContinuation cont, + void *cont_cls) { - GNUNET_assert (NULL == pr->gh); - GNUNET_assert (NULL == pr->cadet_request); - GNUNET_assert (NULL == pr->llc_cont); + GNUNET_assert(NULL == pr->gh); + GNUNET_assert(NULL == pr->cadet_request); + GNUNET_assert(NULL == pr->llc_cont); pr->llc_cont = cont; pr->llc_cont_cls = cont_cls; #if INSANE_STATISTICS - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# Datastore lookups initiated"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# Datastore lookups initiated"), + 1, + GNUNET_NO); #endif - start_local_query (pr, 0 /* next_uid */, true /* random */); + start_local_query(pr, 0 /* next_uid */, true /* random */); } @@ -1713,7 +1716,7 @@ GSF_local_lookup_ (struct GSF_PendingRequest *pr, * @param put the actual message */ void -handle_p2p_put (void *cls, const struct PutMessage *put) +handle_p2p_put(void *cls, const struct PutMessage *put) { struct GSF_ConnectedPeer *cp = cls; uint16_t msize; @@ -1726,30 +1729,30 @@ handle_p2p_put (void *cls, const struct PutMessage *put) double putl; struct PutMigrationContext *pmc; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received P2P PUT from %s\n", - GNUNET_i2s (GSF_get_peer_performance_data_ (cp)->peer)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received P2P PUT from %s\n", + GNUNET_i2s(GSF_get_peer_performance_data_(cp)->peer)); GSF_cover_content_count++; - msize = ntohs (put->header.size); - dsize = msize - sizeof (struct PutMessage); - type = ntohl (put->type); - expiration = GNUNET_TIME_absolute_ntoh (put->expiration); + msize = ntohs(put->header.size); + dsize = msize - sizeof(struct PutMessage); + type = ntohl(put->type); + expiration = GNUNET_TIME_absolute_ntoh(put->expiration); /* do not allow migrated content to live longer than 1 year */ - expiration = GNUNET_TIME_absolute_min (GNUNET_TIME_relative_to_absolute ( - GNUNET_TIME_UNIT_YEARS), - expiration); + expiration = GNUNET_TIME_absolute_min(GNUNET_TIME_relative_to_absolute( + GNUNET_TIME_UNIT_YEARS), + expiration); if (GNUNET_OK != - GNUNET_BLOCK_get_key (GSF_block_ctx, type, &put[1], dsize, &query)) - { - GNUNET_break_op (0); - return; - } - GNUNET_STATISTICS_update (GSF_stats, - gettext_noop ("# GAP PUT messages received"), - 1, - GNUNET_NO); + GNUNET_BLOCK_get_key(GSF_block_ctx, type, &put[1], dsize, &query)) + { + GNUNET_break_op(0); + return; + } + GNUNET_STATISTICS_update(GSF_stats, + gettext_noop("# GAP PUT messages received"), + 1, + GNUNET_NO); /* now, lookup 'query' */ - prq.data = (const void *) &put[1]; + prq.data = (const void *)&put[1]; prq.sender = cp; prq.size = dsize; prq.type = type; @@ -1758,80 +1761,80 @@ handle_p2p_put (void *cls, const struct PutMessage *put) prq.anonymity_level = UINT32_MAX; prq.request_found = GNUNET_NO; prq.eo = GNUNET_BLOCK_EO_NONE; - GNUNET_CONTAINER_multihashmap_get_multiple (pr_map, - &query, - &process_reply, - &prq); + GNUNET_CONTAINER_multihashmap_get_multiple(pr_map, + &query, + &process_reply, + &prq); if (NULL != cp) - { - GSF_connected_peer_change_preference_ (cp, - CONTENT_BANDWIDTH_VALUE + - 1000 * prq.priority); - GSF_get_peer_performance_data_ (cp)->respect += prq.priority; - } + { + GSF_connected_peer_change_preference_(cp, + CONTENT_BANDWIDTH_VALUE + + 1000 * prq.priority); + GSF_get_peer_performance_data_(cp)->respect += prq.priority; + } if ((GNUNET_YES == active_to_migration) && (NULL != cp) && - (GNUNET_NO == test_put_load_too_high (prq.priority))) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Replicating result for query `%s' with priority %u\n", - GNUNET_h2s (&query), - prq.priority); - pmc = GNUNET_new (struct PutMigrationContext); - pmc->start = GNUNET_TIME_absolute_get (); - pmc->requested = prq.request_found; - GNUNET_assert (0 != GSF_get_peer_performance_data_ (cp)->pid); - GNUNET_PEER_resolve (GSF_get_peer_performance_data_ (cp)->pid, - &pmc->origin); - if (NULL == GNUNET_DATASTORE_put (GSF_dsh, - 0, - &query, - dsize, - &put[1], - type, - prq.priority, - 1 /* anonymity */, - 0 /* replication */, - expiration, - 1 + prq.priority, - MAX_DATASTORE_QUEUE, - &put_migration_continuation, - pmc)) + (GNUNET_NO == test_put_load_too_high(prq.priority))) { - put_migration_continuation (pmc, - GNUNET_SYSERR, - GNUNET_TIME_UNIT_ZERO_ABS, - NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Replicating result for query `%s' with priority %u\n", + GNUNET_h2s(&query), + prq.priority); + pmc = GNUNET_new(struct PutMigrationContext); + pmc->start = GNUNET_TIME_absolute_get(); + pmc->requested = prq.request_found; + GNUNET_assert(0 != GSF_get_peer_performance_data_(cp)->pid); + GNUNET_PEER_resolve(GSF_get_peer_performance_data_(cp)->pid, + &pmc->origin); + if (NULL == GNUNET_DATASTORE_put(GSF_dsh, + 0, + &query, + dsize, + &put[1], + type, + prq.priority, + 1 /* anonymity */, + 0 /* replication */, + expiration, + 1 + prq.priority, + MAX_DATASTORE_QUEUE, + &put_migration_continuation, + pmc)) + { + put_migration_continuation(pmc, + GNUNET_SYSERR, + GNUNET_TIME_UNIT_ZERO_ABS, + NULL); + } } - } else if (NULL != cp) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Choosing not to keep content `%s' (%d/%d)\n", - GNUNET_h2s (&query), - active_to_migration, - test_put_load_too_high (prq.priority)); - } - putl = GNUNET_LOAD_get_load (datastore_put_load); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Choosing not to keep content `%s' (%d/%d)\n", + GNUNET_h2s(&query), + active_to_migration, + test_put_load_too_high(prq.priority)); + } + putl = GNUNET_LOAD_get_load(datastore_put_load); if ((NULL != cp) && (GNUNET_NO == prq.request_found) && ((GNUNET_YES != active_to_migration) || (putl > 2.5 * (1 + prq.priority)))) - { - if (GNUNET_YES != active_to_migration) - putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5); - block_time = GNUNET_TIME_relative_multiply ( - GNUNET_TIME_UNIT_MILLISECONDS, - 5000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - (unsigned int) (60000 * putl * putl))); - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Asking to stop migration for %s because of load %f and events %d/%d\n", - GNUNET_STRINGS_relative_time_to_string (block_time, GNUNET_YES), - putl, - active_to_migration, - (GNUNET_NO == prq.request_found)); - GSF_block_peer_migration_ (cp, - GNUNET_TIME_relative_to_absolute (block_time)); - } + { + if (GNUNET_YES != active_to_migration) + putl = 1.0 + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 5); + block_time = GNUNET_TIME_relative_multiply( + GNUNET_TIME_UNIT_MILLISECONDS, + 5000 + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + (unsigned int)(60000 * putl * putl))); + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Asking to stop migration for %s because of load %f and events %d/%d\n", + GNUNET_STRINGS_relative_time_to_string(block_time, GNUNET_YES), + putl, + active_to_migration, + (GNUNET_NO == prq.request_found)); + GSF_block_peer_migration_(cp, + GNUNET_TIME_relative_to_absolute(block_time)); + } } @@ -1842,7 +1845,7 @@ handle_p2p_put (void *cls, const struct PutMessage *put) * @return #GNUNET_YES if the request is still active */ int -GSF_pending_request_test_active_ (struct GSF_PendingRequest *pr) +GSF_pending_request_test_active_(struct GSF_PendingRequest *pr) { return (NULL != pr->rh) ? GNUNET_YES : GNUNET_NO; } @@ -1852,24 +1855,24 @@ GSF_pending_request_test_active_ (struct GSF_PendingRequest *pr) * Setup the subsystem. */ void -GSF_pending_request_init_ () +GSF_pending_request_init_() { if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (GSF_cfg, - "fs", - "MAX_PENDING_REQUESTS", - &max_pending_requests)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_INFO, - "fs", - "MAX_PENDING_REQUESTS"); - } + GNUNET_CONFIGURATION_get_value_number(GSF_cfg, + "fs", + "MAX_PENDING_REQUESTS", + &max_pending_requests)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_INFO, + "fs", + "MAX_PENDING_REQUESTS"); + } active_to_migration = - GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, "FS", "CONTENT_CACHING"); - datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE); - pr_map = GNUNET_CONTAINER_multihashmap_create (32 * 1024, GNUNET_YES); + GNUNET_CONFIGURATION_get_value_yesno(GSF_cfg, "FS", "CONTENT_CACHING"); + datastore_put_load = GNUNET_LOAD_value_init(DATASTORE_LOAD_AUTODECLINE); + pr_map = GNUNET_CONTAINER_multihashmap_create(32 * 1024, GNUNET_YES); requests_by_expiration_heap = - GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); + GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN); } @@ -1877,14 +1880,14 @@ GSF_pending_request_init_ () * Shutdown the subsystem. */ void -GSF_pending_request_done_ () +GSF_pending_request_done_() { - GNUNET_CONTAINER_multihashmap_iterate (pr_map, &clean_request, NULL); - GNUNET_CONTAINER_multihashmap_destroy (pr_map); + GNUNET_CONTAINER_multihashmap_iterate(pr_map, &clean_request, NULL); + GNUNET_CONTAINER_multihashmap_destroy(pr_map); pr_map = NULL; - GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap); + GNUNET_CONTAINER_heap_destroy(requests_by_expiration_heap); requests_by_expiration_heap = NULL; - GNUNET_LOAD_value_free (datastore_put_load); + GNUNET_LOAD_value_free(datastore_put_load); datastore_put_load = NULL; } diff --git a/src/fs/gnunet-service-fs_pr.h b/src/fs/gnunet-service-fs_pr.h index abdb0c9f6..39e471c4d 100644 --- a/src/fs/gnunet-service-fs_pr.h +++ b/src/fs/gnunet-service-fs_pr.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_pr.h @@ -32,9 +32,7 @@ /** * Options for pending requests (bits to be ORed). */ -enum GSF_PendingRequestOptions -{ - +enum GSF_PendingRequestOptions { /** * No special options (P2P-default). */ @@ -69,7 +67,7 @@ enum GSF_PendingRequestOptions * Option mask for typical local requests. */ GSF_PRO_LOCAL_REQUEST = - (GSF_PRO_BLOOMFILTER_FULL_REFRESH | GSF_PRO_PRIORITY_UNLIMITED | GSF_PRO_REQUEST_NEVER_EXPIRES) + (GSF_PRO_BLOOMFILTER_FULL_REFRESH | GSF_PRO_PRIORITY_UNLIMITED | GSF_PRO_REQUEST_NEVER_EXPIRES) }; @@ -78,9 +76,7 @@ enum GSF_PendingRequestOptions * 'gnunet-service-fs_pr', not in the sense of network-wide * known) associated with each pending request. */ -struct GSF_PendingRequestData -{ - +struct GSF_PendingRequestData { /** * Primary query hash for this request. */ @@ -163,7 +159,6 @@ struct GSF_PendingRequestData * we still constructing it? */ int has_started; - }; @@ -220,22 +215,22 @@ typedef void * @return handle for the new pending request */ struct GSF_PendingRequest * -GSF_pending_request_create_ (enum GSF_PendingRequestOptions options, - enum GNUNET_BLOCK_Type type, - const struct GNUNET_HashCode *query, - const struct GNUNET_PeerIdentity *target, - const char *bf_data, - size_t bf_size, - uint32_t mingle, - uint32_t anonymity_level, - uint32_t priority, - int32_t ttl, - GNUNET_PEER_Id sender_pid, - GNUNET_PEER_Id origin_pid, - const struct GNUNET_HashCode *replies_seen, - unsigned int replies_seen_count, - GSF_PendingRequestReplyHandler rh, - void *rh_cls); +GSF_pending_request_create_(enum GSF_PendingRequestOptions options, + enum GNUNET_BLOCK_Type type, + const struct GNUNET_HashCode *query, + const struct GNUNET_PeerIdentity *target, + const char *bf_data, + size_t bf_size, + uint32_t mingle, + uint32_t anonymity_level, + uint32_t priority, + int32_t ttl, + GNUNET_PEER_Id sender_pid, + GNUNET_PEER_Id origin_pid, + const struct GNUNET_HashCode *replies_seen, + unsigned int replies_seen_count, + GSF_PendingRequestReplyHandler rh, + void *rh_cls); /** @@ -247,9 +242,9 @@ GSF_pending_request_create_ (enum GSF_PendingRequestOptions options, * @param replies_seen_count size of the @a replies_seen array */ void -GSF_pending_request_update_ (struct GSF_PendingRequest *pr, - const struct GNUNET_HashCode *replies_seen, - unsigned int replies_seen_count); +GSF_pending_request_update_(struct GSF_PendingRequest *pr, + const struct GNUNET_HashCode *replies_seen, + unsigned int replies_seen_count); /** @@ -259,7 +254,7 @@ GSF_pending_request_update_ (struct GSF_PendingRequest *pr, * @return associated public data */ struct GSF_PendingRequestData * -GSF_pending_request_get_data_ (struct GSF_PendingRequest *pr); +GSF_pending_request_get_data_(struct GSF_PendingRequest *pr); /** @@ -269,7 +264,7 @@ GSF_pending_request_get_data_ (struct GSF_PendingRequest *pr); * @return #GNUNET_YES if the request is still active */ int -GSF_pending_request_test_active_ (struct GSF_PendingRequest *pr); +GSF_pending_request_test_active_(struct GSF_PendingRequest *pr); /** @@ -282,8 +277,8 @@ GSF_pending_request_test_active_ (struct GSF_PendingRequest *pr); * @return #GNUNET_OK if the requests are compatible */ int -GSF_pending_request_is_compatible_ (struct GSF_PendingRequest *pra, - struct GSF_PendingRequest *prb); +GSF_pending_request_is_compatible_(struct GSF_PendingRequest *pra, + struct GSF_PendingRequest *prb); /** @@ -294,7 +289,7 @@ GSF_pending_request_is_compatible_ (struct GSF_PendingRequest *pra, * @return envelope with the request message */ struct GNUNET_MQ_Envelope * -GSF_pending_request_get_message_ (struct GSF_PendingRequest *pr); +GSF_pending_request_get_message_(struct GSF_PendingRequest *pr); /** @@ -304,8 +299,8 @@ GSF_pending_request_get_message_ (struct GSF_PendingRequest *pr); * @param full_cleanup fully purge the request */ void -GSF_pending_request_cancel_ (struct GSF_PendingRequest *pr, - int full_cleanup); +GSF_pending_request_cancel_(struct GSF_PendingRequest *pr, + int full_cleanup); /** @@ -330,8 +325,8 @@ typedef int * @param cls closure for it */ void -GSF_iterate_pending_requests_ (GSF_PendingRequestIterator it, - void *cls); +GSF_iterate_pending_requests_(GSF_PendingRequestIterator it, + void *cls); /** @@ -344,8 +339,8 @@ GSF_iterate_pending_requests_ (GSF_PendingRequestIterator it, * @param put the actual message */ void -handle_p2p_put (void *cls, - const struct PutMessage *put); +handle_p2p_put(void *cls, + const struct PutMessage *put); /** @@ -354,7 +349,7 @@ handle_p2p_put (void *cls, * @param pr the pending request to process */ void -GSF_dht_lookup_ (struct GSF_PendingRequest *pr); +GSF_dht_lookup_(struct GSF_PendingRequest *pr); /** @@ -363,7 +358,7 @@ GSF_dht_lookup_ (struct GSF_PendingRequest *pr); * @param pr the pending request to process */ void -GSF_cadet_lookup_ (struct GSF_PendingRequest *pr); +GSF_cadet_lookup_(struct GSF_PendingRequest *pr); /** @@ -388,9 +383,9 @@ typedef void * @param cont_cls closure for @a cont */ void -GSF_local_lookup_ (struct GSF_PendingRequest *pr, - GSF_LocalLookupContinuation cont, - void *cont_cls); +GSF_local_lookup_(struct GSF_PendingRequest *pr, + GSF_LocalLookupContinuation cont, + void *cont_cls); /** @@ -401,8 +396,8 @@ GSF_local_lookup_ (struct GSF_PendingRequest *pr, * @return #GNUNET_YES if this request could be forwarded to the given peer */ int -GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr, - const struct GNUNET_PeerIdentity *target); +GSF_pending_request_test_target_(struct GSF_PendingRequest *pr, + const struct GNUNET_PeerIdentity *target); @@ -410,14 +405,14 @@ GSF_pending_request_test_target_ (struct GSF_PendingRequest *pr, * Setup the subsystem. */ void -GSF_pending_request_init_ (void); +GSF_pending_request_init_(void); /** * Shutdown the subsystem. */ void -GSF_pending_request_done_ (void); +GSF_pending_request_done_(void); #endif diff --git a/src/fs/gnunet-service-fs_push.c b/src/fs/gnunet-service-fs_push.c index a75f17f82..162dcc0b5 100644 --- a/src/fs/gnunet-service-fs_push.c +++ b/src/fs/gnunet-service-fs_push.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_push.c @@ -49,15 +49,13 @@ * that if this value is increased, the migration testcase may need to be * adjusted as well (especially the CONTENT_LIFETIME in fs_test_lib.c). */ -#define MIN_MIGRATION_CONTENT_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 30) +#define MIN_MIGRATION_CONTENT_LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 30) /** * Block that is ready for migration to other peers. Actual data is at the end of the block. */ -struct MigrationReadyBlock -{ - +struct MigrationReadyBlock { /** * This is a doubly-linked list. */ @@ -104,8 +102,7 @@ struct MigrationReadyBlock /** * Information about a peer waiting for migratable data. */ -struct MigrationReadyPeer -{ +struct MigrationReadyPeer { /** * This is a doubly-linked list. */ @@ -186,15 +183,15 @@ static int value_found; * @param mb block to delete */ static void -delete_migration_block (struct MigrationReadyBlock *mb) +delete_migration_block(struct MigrationReadyBlock *mb) { - GNUNET_CONTAINER_DLL_remove (mig_head, - mig_tail, - mb); - GNUNET_PEER_decrement_rcs (mb->target_list, - MIGRATION_LIST_SIZE); + GNUNET_CONTAINER_DLL_remove(mig_head, + mig_tail, + mb); + GNUNET_PEER_decrement_rcs(mb->target_list, + MIGRATION_LIST_SIZE); mig_size--; - GNUNET_free (mb); + GNUNET_free(mb); } @@ -204,7 +201,7 @@ delete_migration_block (struct MigrationReadyBlock *mb) * @param cls a `struct MigrationReadyPeer *` */ static void -find_content (void *cls); +find_content(void *cls); /** @@ -215,50 +212,50 @@ find_content (void *cls); * @return #GNUNET_YES if the block was deleted (!) */ static int -transmit_content (struct MigrationReadyPeer *mrp, - struct MigrationReadyBlock *block) +transmit_content(struct MigrationReadyPeer *mrp, + struct MigrationReadyBlock *block) { struct PutMessage *msg; unsigned int i; struct GSF_PeerPerformanceData *ppd; int ret; - ppd = GSF_get_peer_performance_data_ (mrp->peer); - GNUNET_assert (NULL == mrp->env); - mrp->env = GNUNET_MQ_msg_extra (msg, - block->size, - GNUNET_MESSAGE_TYPE_FS_PUT); - msg->type = htonl (block->type); - msg->expiration = GNUNET_TIME_absolute_hton (block->expiration); - GNUNET_memcpy (&msg[1], - &block[1], - block->size); + ppd = GSF_get_peer_performance_data_(mrp->peer); + GNUNET_assert(NULL == mrp->env); + mrp->env = GNUNET_MQ_msg_extra(msg, + block->size, + GNUNET_MESSAGE_TYPE_FS_PUT); + msg->type = htonl(block->type); + msg->expiration = GNUNET_TIME_absolute_hton(block->expiration); + GNUNET_memcpy(&msg[1], + &block[1], + block->size); for (i = 0; i < MIGRATION_LIST_SIZE; i++) - { - if (block->target_list[i] == 0) { - block->target_list[i] = ppd->pid; - GNUNET_PEER_change_rc (block->target_list[i], - 1); - break; + if (block->target_list[i] == 0) + { + block->target_list[i] = ppd->pid; + GNUNET_PEER_change_rc(block->target_list[i], + 1); + break; + } } - } if (MIGRATION_LIST_SIZE == i) - { - delete_migration_block (block); - ret = GNUNET_YES; - } + { + delete_migration_block(block); + ret = GNUNET_YES; + } else - { - ret = GNUNET_NO; - } - GNUNET_MQ_notify_sent (mrp->env, - &find_content, - mrp); - GSF_peer_transmit_ (mrp->peer, - GNUNET_NO, - 0 /* priority */ , - mrp->env); + { + ret = GNUNET_NO; + } + GNUNET_MQ_notify_sent(mrp->env, + &find_content, + mrp); + GSF_peer_transmit_(mrp->peer, + GNUNET_NO, + 0 /* priority */, + mrp->env); return ret; } @@ -271,7 +268,7 @@ transmit_content (struct MigrationReadyPeer *mrp, * @return number of times block was forwarded */ static unsigned int -count_targets (struct MigrationReadyBlock *block) +count_targets(struct MigrationReadyBlock *block) { unsigned int i; @@ -291,8 +288,8 @@ count_targets (struct MigrationReadyBlock *block) * @return score (>= 0: feasible, negative: infeasible) */ static long -score_content (struct MigrationReadyPeer *mrp, - struct MigrationReadyBlock *block) +score_content(struct MigrationReadyPeer *mrp, + struct MigrationReadyBlock *block) { unsigned int i; struct GSF_PeerPerformanceData *ppd; @@ -300,18 +297,18 @@ score_content (struct MigrationReadyPeer *mrp, struct GNUNET_HashCode hc; uint32_t dist; - ppd = GSF_get_peer_performance_data_ (mrp->peer); + ppd = GSF_get_peer_performance_data_(mrp->peer); for (i = 0; i < MIGRATION_LIST_SIZE; i++) if (block->target_list[i] == ppd->pid) return -1; - GNUNET_assert (0 != ppd->pid); - GNUNET_PEER_resolve (ppd->pid, - &id); - GNUNET_CRYPTO_hash (&id, - sizeof (struct GNUNET_PeerIdentity), - &hc); - dist = GNUNET_CRYPTO_hash_distance_u32 (&block->query, - &hc); + GNUNET_assert(0 != ppd->pid); + GNUNET_PEER_resolve(ppd->pid, + &id); + GNUNET_CRYPTO_hash(&id, + sizeof(struct GNUNET_PeerIdentity), + &hc); + dist = GNUNET_CRYPTO_hash_distance_u32(&block->query, + &hc); /* closer distance, higher score: */ return UINT32_MAX - dist; } @@ -322,7 +319,7 @@ score_content (struct MigrationReadyPeer *mrp, * (re)scheduling it with the appropriate delay. */ static void -consider_gathering (void); +consider_gathering(void); /** @@ -331,7 +328,7 @@ consider_gathering (void); * @param cls peer to find content for */ static void -find_content (void *cls) +find_content(void *cls) { struct MigrationReadyPeer *mrp = cls; struct MigrationReadyBlock *pos; @@ -344,48 +341,48 @@ find_content (void *cls) best_score = -1; pos = mig_head; while (NULL != pos) - { - score = score_content (mrp, pos); - if (score > best_score) { - best_score = score; - best = pos; + score = score_content(mrp, pos); + if (score > best_score) + { + best_score = score; + best = pos; + } + pos = pos->next; } - pos = pos->next; - } if (NULL == best) - { - if (mig_size < MAX_MIGRATION_QUEUE) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "No content found for pushing, waiting for queue to fill\n"); - return; /* will fill up eventually... */ - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "No suitable content found, purging content from full queue\n"); - /* failed to find migration target AND - * queue is full, purge most-forwarded - * block from queue to make room for more */ - pos = mig_head; - while (NULL != pos) - { - score = count_targets (pos); - if (score >= best_score) - { - best_score = score; - best = pos; - } - pos = pos->next; + if (mig_size < MAX_MIGRATION_QUEUE) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "No content found for pushing, waiting for queue to fill\n"); + return; /* will fill up eventually... */ + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "No suitable content found, purging content from full queue\n"); + /* failed to find migration target AND + * queue is full, purge most-forwarded + * block from queue to make room for more */ + pos = mig_head; + while (NULL != pos) + { + score = count_targets(pos); + if (score >= best_score) + { + best_score = score; + best = pos; + } + pos = pos->next; + } + GNUNET_assert(NULL != best); + delete_migration_block(best); + consider_gathering(); + return; } - GNUNET_assert (NULL != best); - delete_migration_block (best); - consider_gathering (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Preparing to push best content to peer\n"); - transmit_content (mrp, - best); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Preparing to push best content to peer\n"); + transmit_content(mrp, + best); } @@ -396,7 +393,7 @@ find_content (void *cls) * @param cls unused */ static void -gather_migration_blocks (void *cls); +gather_migration_blocks(void *cls); /** @@ -404,7 +401,7 @@ gather_migration_blocks (void *cls); * (re)scheduling it with the appropriate delay. */ static void -consider_gathering () +consider_gathering() { struct GNUNET_TIME_Relative delay; @@ -416,25 +413,25 @@ consider_gathering () return; if (mig_size >= MAX_MIGRATION_QUEUE) return; - delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, - mig_size); - delay = GNUNET_TIME_relative_divide (delay, - MAX_MIGRATION_QUEUE); - delay = GNUNET_TIME_relative_max (delay, - min_migration_delay); + delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, + mig_size); + delay = GNUNET_TIME_relative_divide(delay, + MAX_MIGRATION_QUEUE); + delay = GNUNET_TIME_relative_max(delay, + min_migration_delay); if (GNUNET_NO == value_found) - { - /* wait at least 5s if the datastore is empty */ - delay = GNUNET_TIME_relative_max (delay, - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, + { + /* wait at least 5s if the datastore is empty */ + delay = GNUNET_TIME_relative_max(delay, + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Scheduling gathering task (queue size: %u)\n", - mig_size); - mig_task = GNUNET_SCHEDULER_add_delayed (delay, - &gather_migration_blocks, - NULL); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Scheduling gathering task (queue size: %u)\n", + mig_size); + mig_task = GNUNET_SCHEDULER_add_delayed(delay, + &gather_migration_blocks, + NULL); } @@ -454,81 +451,82 @@ consider_gathering () * maybe 0 if no unique identifier is available */ static void -process_migration_content (void *cls, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +process_migration_content(void *cls, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct MigrationReadyBlock *mb; struct MigrationReadyPeer *pos; mig_qe = NULL; if (NULL == key) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "No content found for migration...\n"); - consider_gathering (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "No content found for migration...\n"); + consider_gathering(); + return; + } value_found = GNUNET_YES; - if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value_us < + if (GNUNET_TIME_absolute_get_remaining(expiration).rel_value_us < MIN_MIGRATION_CONTENT_LIFETIME.rel_value_us) - { - /* content will expire soon, don't bother */ - consider_gathering (); - return; - } + { + /* content will expire soon, don't bother */ + consider_gathering(); + return; + } if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND) - { - if (GNUNET_OK != - GNUNET_FS_handle_on_demand_block (key, - size, - data, - type, - priority, - anonymity, - replication, - expiration, - uid, - &process_migration_content, - NULL)) - consider_gathering (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Retrieved block `%s' of type %u for migration (queue size: %u/%u)\n", - GNUNET_h2s (key), - type, mig_size + 1, - MAX_MIGRATION_QUEUE); - mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size); + { + if (GNUNET_OK != + GNUNET_FS_handle_on_demand_block(key, + size, + data, + type, + priority, + anonymity, + replication, + expiration, + uid, + &process_migration_content, + NULL)) + consider_gathering(); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Retrieved block `%s' of type %u for migration (queue size: %u/%u)\n", + GNUNET_h2s(key), + type, mig_size + 1, + MAX_MIGRATION_QUEUE); + mb = GNUNET_malloc(sizeof(struct MigrationReadyBlock) + size); mb->query = *key; mb->expiration = expiration; mb->size = size; mb->type = type; - GNUNET_memcpy (&mb[1], data, size); - GNUNET_CONTAINER_DLL_insert_after (mig_head, - mig_tail, - mig_tail, - mb); + GNUNET_memcpy(&mb[1], data, size); + GNUNET_CONTAINER_DLL_insert_after(mig_head, + mig_tail, + mig_tail, + mb); mig_size++; for (pos = peer_head; NULL != pos; pos = pos->next) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Preparing to push best content to peer %s\n", - GNUNET_i2s (GSF_connected_peer_get_identity2_(pos->peer))); - if ( (NULL == pos->env) && - (GNUNET_YES == transmit_content (pos, - mb)) ) { - break; /* 'mb' was freed! */ + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Preparing to push best content to peer %s\n", + GNUNET_i2s(GSF_connected_peer_get_identity2_(pos->peer))); + if ((NULL == pos->env) && + (GNUNET_YES == transmit_content(pos, + mb))) + { + break; /* 'mb' was freed! */ + } } - } - consider_gathering (); + consider_gathering(); } @@ -539,24 +537,24 @@ process_migration_content (void *cls, * @param cls unused */ static void -gather_migration_blocks (void *cls) +gather_migration_blocks(void *cls) { mig_task = NULL; if (mig_size >= MAX_MIGRATION_QUEUE) return; if (NULL == GSF_dsh) return; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Asking datastore for content for replication (queue size: %u)\n", - mig_size); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Asking datastore for content for replication (queue size: %u)\n", + mig_size); value_found = GNUNET_NO; - mig_qe = GNUNET_DATASTORE_get_for_replication (GSF_dsh, - 0, - UINT_MAX, - &process_migration_content, - NULL); + mig_qe = GNUNET_DATASTORE_get_for_replication(GSF_dsh, + 0, + UINT_MAX, + &process_migration_content, + NULL); if (NULL == mig_qe) - consider_gathering (); + consider_gathering(); } @@ -567,7 +565,7 @@ gather_migration_blocks (void *cls) * @param peer handle for the peer that connected */ void -GSF_push_start_ (struct GSF_ConnectedPeer *peer) +GSF_push_start_(struct GSF_ConnectedPeer *peer) { struct MigrationReadyPeer *mrp; @@ -577,22 +575,22 @@ GSF_push_start_ (struct GSF_ConnectedPeer *peer) if (mrp->peer == peer) break; if (NULL != mrp) - { - /* same peer added twice, must not happen */ - GNUNET_break (0); - return; - } + { + /* same peer added twice, must not happen */ + GNUNET_break(0); + return; + } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding peer %s to list for pushing\n", - GNUNET_i2s (GSF_connected_peer_get_identity2_(peer))); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding peer %s to list for pushing\n", + GNUNET_i2s(GSF_connected_peer_get_identity2_(peer))); - mrp = GNUNET_new (struct MigrationReadyPeer); + mrp = GNUNET_new(struct MigrationReadyPeer); mrp->peer = peer; - find_content (mrp); - GNUNET_CONTAINER_DLL_insert (peer_head, - peer_tail, - mrp); + find_content(mrp); + GNUNET_CONTAINER_DLL_insert(peer_head, + peer_tail, + mrp); } @@ -603,7 +601,7 @@ GSF_push_start_ (struct GSF_ConnectedPeer *peer) * @param peer handle for the peer that disconnected */ void -GSF_push_stop_ (struct GSF_ConnectedPeer *peer) +GSF_push_stop_(struct GSF_ConnectedPeer *peer) { struct MigrationReadyPeer *pos; @@ -613,11 +611,11 @@ GSF_push_stop_ (struct GSF_ConnectedPeer *peer) if (NULL == pos) return; if (NULL != pos->env) - GNUNET_MQ_send_cancel (pos->env); - GNUNET_CONTAINER_DLL_remove (peer_head, - peer_tail, - pos); - GNUNET_free (pos); + GNUNET_MQ_send_cancel(pos->env); + GNUNET_CONTAINER_DLL_remove(peer_head, + peer_tail, + pos); + GNUNET_free(pos); } @@ -625,28 +623,28 @@ GSF_push_stop_ (struct GSF_ConnectedPeer *peer) * Setup the module. */ void -GSF_push_init_ () +GSF_push_init_() { enabled = - GNUNET_CONFIGURATION_get_value_yesno (GSF_cfg, - "FS", - "CONTENT_PUSHING"); + GNUNET_CONFIGURATION_get_value_yesno(GSF_cfg, + "FS", + "CONTENT_PUSHING"); if (GNUNET_YES != enabled) return; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_time (GSF_cfg, - "fs", - "MIN_MIGRATION_DELAY", - &min_migration_delay)) - { - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING, - "fs", - "MIN_MIGRATION_DELAY", - _("time required, content pushing disabled")); - return; - } - consider_gathering (); + GNUNET_CONFIGURATION_get_value_time(GSF_cfg, + "fs", + "MIN_MIGRATION_DELAY", + &min_migration_delay)) + { + GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_WARNING, + "fs", + "MIN_MIGRATION_DELAY", + _("time required, content pushing disabled")); + return; + } + consider_gathering(); } @@ -654,21 +652,21 @@ GSF_push_init_ () * Shutdown the module. */ void -GSF_push_done_ () +GSF_push_done_() { if (NULL != mig_task) - { - GNUNET_SCHEDULER_cancel (mig_task); - mig_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(mig_task); + mig_task = NULL; + } if (NULL != mig_qe) - { - GNUNET_DATASTORE_cancel (mig_qe); - mig_qe = NULL; - } + { + GNUNET_DATASTORE_cancel(mig_qe); + mig_qe = NULL; + } while (NULL != mig_head) - delete_migration_block (mig_head); - GNUNET_assert (0 == mig_size); + delete_migration_block(mig_head); + GNUNET_assert(0 == mig_size); } /* end of gnunet-service-fs_push.c */ diff --git a/src/fs/gnunet-service-fs_push.h b/src/fs/gnunet-service-fs_push.h index ab2d2204a..0917364e2 100644 --- a/src/fs/gnunet-service-fs_push.h +++ b/src/fs/gnunet-service-fs_push.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_push.h @@ -33,14 +33,14 @@ * Setup the module. */ void -GSF_push_init_ (void); +GSF_push_init_(void); /** * Shutdown the module. */ void -GSF_push_done_ (void); +GSF_push_done_(void); /** @@ -50,7 +50,7 @@ GSF_push_done_ (void); * @param peer handle for the peer that connected */ void -GSF_push_start_ (struct GSF_ConnectedPeer *peer); +GSF_push_start_(struct GSF_ConnectedPeer *peer); /** @@ -60,7 +60,7 @@ GSF_push_start_ (struct GSF_ConnectedPeer *peer); * @param peer handle for the peer that disconnected */ void -GSF_push_stop_ (struct GSF_ConnectedPeer *peer); +GSF_push_stop_(struct GSF_ConnectedPeer *peer); #endif diff --git a/src/fs/gnunet-service-fs_put.c b/src/fs/gnunet-service-fs_put.c index 78a4b98df..deba91a0c 100644 --- a/src/fs/gnunet-service-fs_put.c +++ b/src/fs/gnunet-service-fs_put.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_put.c @@ -31,7 +31,7 @@ /** * How often do we at most PUT content into the DHT? */ -#define MAX_DHT_PUT_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define MAX_DHT_PUT_FREQ GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) /** * How many replicas do we try to create per PUT? @@ -42,9 +42,7 @@ /** * Context for each zero-anonymity iterator. */ -struct PutOperator -{ - +struct PutOperator { /** * Request to datastore for DHT PUTs (or NULL). */ @@ -88,8 +86,8 @@ struct PutOperator * of block that we're putting into the DHT). */ static struct PutOperator operators[] = { - {NULL, GNUNET_BLOCK_TYPE_FS_UBLOCK, 0, 0, 0}, - {NULL, GNUNET_BLOCK_TYPE_ANY, 0, 0, 0} + { NULL, GNUNET_BLOCK_TYPE_FS_UBLOCK, 0, 0, 0 }, + { NULL, GNUNET_BLOCK_TYPE_ANY, 0, 0, 0 } }; @@ -100,7 +98,7 @@ static struct PutOperator operators[] = { * @param tc scheduler context (unused) */ static void -gather_dht_put_blocks (void *cls); +gather_dht_put_blocks(void *cls); /** @@ -109,25 +107,25 @@ gather_dht_put_blocks (void *cls); * @param po put operator to schedule */ static void -schedule_next_put (struct PutOperator *po) +schedule_next_put(struct PutOperator *po) { struct GNUNET_TIME_Relative delay; if (po->zero_anonymity_count_estimate > 0) - { - delay = - GNUNET_TIME_relative_divide (GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY, - po->zero_anonymity_count_estimate); - delay = GNUNET_TIME_relative_min (delay, MAX_DHT_PUT_FREQ); - } + { + delay = + GNUNET_TIME_relative_divide(GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY, + po->zero_anonymity_count_estimate); + delay = GNUNET_TIME_relative_min(delay, MAX_DHT_PUT_FREQ); + } else - { - /* if we have NO zero-anonymity content yet, wait 5 minutes for some to - * (hopefully) appear */ - delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5); - } + { + /* if we have NO zero-anonymity content yet, wait 5 minutes for some to + * (hopefully) appear */ + delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5); + } po->dht_task = - GNUNET_SCHEDULER_add_delayed (delay, &gather_dht_put_blocks, po); + GNUNET_SCHEDULER_add_delayed(delay, &gather_dht_put_blocks, po); } @@ -137,12 +135,12 @@ schedule_next_put (struct PutOperator *po) * @param cls type of blocks to gather */ static void -delay_dht_put_blocks (void *cls) +delay_dht_put_blocks(void *cls) { struct PutOperator *po = cls; po->dht_put = NULL; - schedule_next_put (po); + schedule_next_put(po); } @@ -152,12 +150,12 @@ delay_dht_put_blocks (void *cls) * @param cls type of blocks to gather */ static void -delay_dht_put_task (void *cls) +delay_dht_put_task(void *cls) { struct PutOperator *po = cls; po->dht_task = NULL; - schedule_next_put (po); + schedule_next_put(po); } @@ -177,45 +175,45 @@ delay_dht_put_task (void *cls) * maybe 0 if no unique identifier is available */ static void -process_dht_put_content (void *cls, - const struct GNUNET_HashCode * key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - uint64_t uid) +process_dht_put_content(void *cls, + const struct GNUNET_HashCode * key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + uint64_t uid) { struct PutOperator *po = cls; po->dht_qe = NULL; if (key == NULL) - { - po->zero_anonymity_count_estimate = po->result_count; - po->result_count = 0; - po->next_uid = 0; - po->dht_task = GNUNET_SCHEDULER_add_now (&delay_dht_put_task, po); - return; - } + { + po->zero_anonymity_count_estimate = po->result_count; + po->result_count = 0; + po->next_uid = 0; + po->dht_task = GNUNET_SCHEDULER_add_now(&delay_dht_put_task, po); + return; + } po->result_count++; po->next_uid = uid + 1; po->zero_anonymity_count_estimate = - GNUNET_MAX (po->result_count, po->zero_anonymity_count_estimate); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Retrieved block `%s' of type %u for DHT PUT\n", GNUNET_h2s (key), - type); - po->dht_put = GNUNET_DHT_put (GSF_dht, - key, - DEFAULT_PUT_REPLICATION, - GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, - type, - size, - data, - expiration, - &delay_dht_put_blocks, - po); + GNUNET_MAX(po->result_count, po->zero_anonymity_count_estimate); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Retrieved block `%s' of type %u for DHT PUT\n", GNUNET_h2s(key), + type); + po->dht_put = GNUNET_DHT_put(GSF_dht, + key, + DEFAULT_PUT_REPLICATION, + GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, + type, + size, + data, + expiration, + &delay_dht_put_blocks, + po); } @@ -225,21 +223,21 @@ process_dht_put_content (void *cls, * @param cls type of blocks to gather */ static void -gather_dht_put_blocks (void *cls) +gather_dht_put_blocks(void *cls) { struct PutOperator *po = cls; po->dht_task = NULL; po->dht_qe = - GNUNET_DATASTORE_get_zero_anonymity (GSF_dsh, - po->next_uid, - 0, - UINT_MAX, - po->dht_put_type, - &process_dht_put_content, - po); + GNUNET_DATASTORE_get_zero_anonymity(GSF_dsh, + po->next_uid, + 0, + UINT_MAX, + po->dht_put_type, + &process_dht_put_content, + po); if (NULL == po->dht_qe) - po->dht_task = GNUNET_SCHEDULER_add_now (&delay_dht_put_task, po); + po->dht_task = GNUNET_SCHEDULER_add_now(&delay_dht_put_task, po); } @@ -247,17 +245,17 @@ gather_dht_put_blocks (void *cls) * Setup the module. */ void -GSF_put_init_ () +GSF_put_init_() { unsigned int i; i = 0; while (operators[i].dht_put_type != GNUNET_BLOCK_TYPE_ANY) - { - operators[i].dht_task = - GNUNET_SCHEDULER_add_now (&gather_dht_put_blocks, &operators[i]); - i++; - } + { + operators[i].dht_task = + GNUNET_SCHEDULER_add_now(&gather_dht_put_blocks, &operators[i]); + i++; + } } @@ -265,31 +263,31 @@ GSF_put_init_ () * Shutdown the module. */ void -GSF_put_done_ () +GSF_put_done_() { struct PutOperator *po; unsigned int i; i = 0; while ((po = &operators[i])->dht_put_type != GNUNET_BLOCK_TYPE_ANY) - { - if (NULL != po->dht_task) - { - GNUNET_SCHEDULER_cancel (po->dht_task); - po->dht_task = NULL; - } - if (NULL != po->dht_put) - { - GNUNET_DHT_put_cancel (po->dht_put); - po->dht_put = NULL; - } - if (NULL != po->dht_qe) { - GNUNET_DATASTORE_cancel (po->dht_qe); - po->dht_qe = NULL; + if (NULL != po->dht_task) + { + GNUNET_SCHEDULER_cancel(po->dht_task); + po->dht_task = NULL; + } + if (NULL != po->dht_put) + { + GNUNET_DHT_put_cancel(po->dht_put); + po->dht_put = NULL; + } + if (NULL != po->dht_qe) + { + GNUNET_DATASTORE_cancel(po->dht_qe); + po->dht_qe = NULL; + } + i++; } - i++; - } } /* end of gnunet-service-fs_put.c */ diff --git a/src/fs/gnunet-service-fs_put.h b/src/fs/gnunet-service-fs_put.h index de9751842..2d85d9831 100644 --- a/src/fs/gnunet-service-fs_put.h +++ b/src/fs/gnunet-service-fs_put.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-service-fs_put.h @@ -33,14 +33,14 @@ * Setup the module. */ void -GSF_put_init_ (void); +GSF_put_init_(void); /** * Shutdown the module. */ void -GSF_put_done_ (void); +GSF_put_done_(void); #endif diff --git a/src/fs/gnunet-unindex.c b/src/fs/gnunet-unindex.c index 4d13e7ef3..873dfa5eb 100644 --- a/src/fs/gnunet-unindex.c +++ b/src/fs/gnunet-unindex.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/gnunet-unindex.c * @brief unindex files published on GNUnet @@ -40,24 +40,24 @@ static struct GNUNET_FS_UnindexContext *uc; static void -cleanup_task (void *cls) +cleanup_task(void *cls) { - GNUNET_FS_stop (ctx); + GNUNET_FS_stop(ctx); ctx = NULL; } static void -shutdown_task (void *cls) +shutdown_task(void *cls) { struct GNUNET_FS_UnindexContext *u; if (uc != NULL) - { - u = uc; - uc = NULL; - GNUNET_FS_unindex_stop (u); - } + { + u = uc; + uc = NULL; + GNUNET_FS_unindex_stop(u); + } } /** @@ -74,43 +74,48 @@ shutdown_task (void *cls) * field in the GNUNET_FS_ProgressInfo struct. */ static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *info) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *info) { const char *s; switch (info->status) - { - case GNUNET_FS_STATUS_UNINDEX_START: - break; - case GNUNET_FS_STATUS_UNINDEX_PROGRESS: - if (verbose) { - s = GNUNET_STRINGS_relative_time_to_string (info->value.unindex.eta, - GNUNET_YES); - fprintf (stdout, - _ ("Unindexing at %llu/%llu (%s remaining)\n"), - (unsigned long long) info->value.unindex.completed, - (unsigned long long) info->value.unindex.size, - s); + case GNUNET_FS_STATUS_UNINDEX_START: + break; + + case GNUNET_FS_STATUS_UNINDEX_PROGRESS: + if (verbose) + { + s = GNUNET_STRINGS_relative_time_to_string(info->value.unindex.eta, + GNUNET_YES); + fprintf(stdout, + _("Unindexing at %llu/%llu (%s remaining)\n"), + (unsigned long long)info->value.unindex.completed, + (unsigned long long)info->value.unindex.size, + s); + } + break; + + case GNUNET_FS_STATUS_UNINDEX_ERROR: + fprintf(stderr, + _("Error unindexing: %s.\n"), + info->value.unindex.specifics.error.message); + GNUNET_SCHEDULER_shutdown(); + break; + + case GNUNET_FS_STATUS_UNINDEX_COMPLETED: + fprintf(stdout, "%s", _("Unindexing done.\n")); + GNUNET_SCHEDULER_shutdown(); + break; + + case GNUNET_FS_STATUS_UNINDEX_STOPPED: + GNUNET_SCHEDULER_add_now(&cleanup_task, NULL); + break; + + default: + fprintf(stderr, _("Unexpected status: %d\n"), info->status); + break; } - break; - case GNUNET_FS_STATUS_UNINDEX_ERROR: - fprintf (stderr, - _ ("Error unindexing: %s.\n"), - info->value.unindex.specifics.error.message); - GNUNET_SCHEDULER_shutdown (); - break; - case GNUNET_FS_STATUS_UNINDEX_COMPLETED: - fprintf (stdout, "%s", _ ("Unindexing done.\n")); - GNUNET_SCHEDULER_shutdown (); - break; - case GNUNET_FS_STATUS_UNINDEX_STOPPED: - GNUNET_SCHEDULER_add_now (&cleanup_task, NULL); - break; - default: - fprintf (stderr, _ ("Unexpected status: %d\n"), info->status); - break; - } return NULL; } @@ -124,39 +129,39 @@ progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *info) * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { /* check arguments */ if ((args[0] == NULL) || (args[1] != NULL)) - { - printf (_ ("You must specify one and only one filename for unindexing.\n")); - ret = -1; - return; - } + { + printf(_("You must specify one and only one filename for unindexing.\n")); + ret = -1; + return; + } cfg = c; - ctx = GNUNET_FS_start (cfg, - "gnunet-unindex", - &progress_cb, - NULL, - GNUNET_FS_FLAGS_NONE, - GNUNET_FS_OPTIONS_END); + ctx = GNUNET_FS_start(cfg, + "gnunet-unindex", + &progress_cb, + NULL, + GNUNET_FS_FLAGS_NONE, + GNUNET_FS_OPTIONS_END); if (NULL == ctx) - { - fprintf (stderr, _ ("Could not initialize `%s' subsystem.\n"), "FS"); - ret = 1; - return; - } - uc = GNUNET_FS_unindex_start (ctx, args[0], NULL); + { + fprintf(stderr, _("Could not initialize `%s' subsystem.\n"), "FS"); + ret = 1; + return; + } + uc = GNUNET_FS_unindex_start(ctx, args[0], NULL); if (NULL == uc) - { - fprintf (stderr, "%s", _ ("Could not start unindex operation.\n")); - GNUNET_FS_stop (ctx); - return; - } - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + { + fprintf(stderr, "%s", _("Could not start unindex operation.\n")); + GNUNET_FS_stop(ctx); + return; + } + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); } @@ -168,30 +173,30 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { + GNUNET_GETOPT_option_verbose(&verbose), - GNUNET_GETOPT_option_verbose (&verbose), - - GNUNET_GETOPT_OPTION_END}; + GNUNET_GETOPT_OPTION_END + }; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run ( + GNUNET_PROGRAM_run( argc, argv, "gnunet-unindex [OPTIONS] FILENAME", - gettext_noop ( + gettext_noop( "Unindex a file that was previously indexed with gnunet-publish."), options, &run, NULL)) - ? ret - : 1; - GNUNET_free ((void *) argv); + ? ret + : 1; + GNUNET_free((void *)argv); return ret; } diff --git a/src/fs/perf_gnunet_service_fs_p2p.c b/src/fs/perf_gnunet_service_fs_p2p.c index 0d76dfc3d..515144eb1 100644 --- a/src/fs/perf_gnunet_service_fs_p2p.c +++ b/src/fs/perf_gnunet_service_fs_p2p.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/perf_gnunet_service_fs_p2p.c @@ -37,7 +37,7 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 30) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 30) #define NUM_DAEMONS 2 @@ -57,16 +57,14 @@ static struct GNUNET_TIME_Absolute start_time; /** * Master context for 'stat_run'. */ -struct StatMaster -{ +struct StatMaster { struct GNUNET_STATISTICS_Handle *stat; struct GNUNET_TESTBED_Operation *op; unsigned int daemon; unsigned int value; }; -struct StatValues -{ +struct StatValues { const char *subsystem; const char *name; }; @@ -75,28 +73,28 @@ struct StatValues * Statistics we print out. */ static struct StatValues stats[] = { - {"fs", "# queries forwarded"}, - {"fs", "# replies received and matched"}, - {"fs", "# results found locally"}, - {"fs", "# requests forwarded due to high load"}, - {"fs", "# requests done for free (low load)"}, - {"fs", "# requests dropped, priority insufficient"}, - {"fs", "# requests done for a price (normal load)"}, - {"fs", "# requests dropped by datastore (queue length limit)"}, - {"fs", "# P2P searches received"}, - {"fs", "# P2P searches discarded (queue length bound)"}, - {"fs", "# replies received for local clients"}, - {"fs", "# queries retransmitted to same target"}, - {"core", "# bytes decrypted"}, - {"core", "# bytes encrypted"}, - {"core", "# discarded CORE_SEND requests"}, - {"core", "# discarded CORE_SEND request bytes"}, - {"core", "# discarded lower priority CORE_SEND requests"}, - {"core", "# discarded lower priority CORE_SEND request bytes"}, - {"transport", "# bytes received via TCP"}, - {"transport", "# bytes transmitted via TCP"}, - {"datacache", "# bytes stored"}, - {NULL, NULL} + { "fs", "# queries forwarded" }, + { "fs", "# replies received and matched" }, + { "fs", "# results found locally" }, + { "fs", "# requests forwarded due to high load" }, + { "fs", "# requests done for free (low load)" }, + { "fs", "# requests dropped, priority insufficient" }, + { "fs", "# requests done for a price (normal load)" }, + { "fs", "# requests dropped by datastore (queue length limit)" }, + { "fs", "# P2P searches received" }, + { "fs", "# P2P searches discarded (queue length bound)" }, + { "fs", "# replies received for local clients" }, + { "fs", "# queries retransmitted to same target" }, + { "core", "# bytes decrypted" }, + { "core", "# bytes encrypted" }, + { "core", "# discarded CORE_SEND requests" }, + { "core", "# discarded CORE_SEND request bytes" }, + { "core", "# discarded lower priority CORE_SEND requests" }, + { "core", "# discarded lower priority CORE_SEND request bytes" }, + { "transport", "# bytes received via TCP" }, + { "transport", "# bytes transmitted via TCP" }, + { "datacache", "# bytes stored" }, + { NULL, NULL } }; @@ -111,17 +109,17 @@ static struct StatValues stats[] = { * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration */ static int -print_stat (void *cls, const char *subsystem, const char *name, uint64_t value, - int is_persistent) +print_stat(void *cls, const char *subsystem, const char *name, uint64_t value, + int is_persistent) { struct StatMaster *sm = cls; - fprintf (stderr, - "Peer %2u: %12s/%50s = %12llu\n", - sm->daemon, - subsystem, - name, - (unsigned long long) value); + fprintf(stderr, + "Peer %2u: %12s/%50s = %12llu\n", + sm->daemon, + subsystem, + name, + (unsigned long long)value); return GNUNET_OK; } @@ -130,23 +128,23 @@ print_stat (void *cls, const char *subsystem, const char *name, uint64_t value, * Function that gathers stats from all daemons. */ static void -stat_run (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg); +stat_run(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg); /** * Function called when GET operation on stats is done. */ static void -get_done (void *cls, int success) +get_done(void *cls, int success) { struct StatMaster *sm = cls; - GNUNET_break (GNUNET_OK == success); + GNUNET_break(GNUNET_OK == success); sm->value++; - stat_run (sm, sm->op, sm->stat, NULL); + stat_run(sm, sm->op, sm->stat, NULL); } @@ -161,11 +159,11 @@ get_done (void *cls, int success) * @return service handle to return in 'op_result', NULL on error */ static void * -statistics_connect_adapter (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +statistics_connect_adapter(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - return GNUNET_STATISTICS_create ("", - cfg); + return GNUNET_STATISTICS_create("", + cfg); } @@ -177,10 +175,10 @@ statistics_connect_adapter (void *cls, * @param op_result service handle returned from the connect adapter */ static void -statistics_disconnect_adapter (void *cls, - void *op_result) +statistics_disconnect_adapter(void *cls, + void *op_result) { - GNUNET_STATISTICS_destroy (op_result, GNUNET_NO); + GNUNET_STATISTICS_destroy(op_result, GNUNET_NO); } @@ -188,57 +186,57 @@ statistics_disconnect_adapter (void *cls, * Function that gathers stats from all daemons. */ static void -stat_run (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg) +stat_run(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg) { struct StatMaster *sm = cls; if (NULL != emsg) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to statistics service: %s\n", - emsg); - GNUNET_SCHEDULER_shutdown (); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to statistics service: %s\n", + emsg); + GNUNET_SCHEDULER_shutdown(); return; } sm->stat = ca_result; if (stats[sm->value].name != NULL) - { - GNUNET_STATISTICS_get (sm->stat, + { + GNUNET_STATISTICS_get(sm->stat, #if 0 - NULL, NULL, + NULL, NULL, #else - stats[sm->value].subsystem, stats[sm->value].name, + stats[sm->value].subsystem, stats[sm->value].name, #endif - &get_done, &print_stat, - sm); - return; - } - GNUNET_TESTBED_operation_done (sm->op); + &get_done, &print_stat, + sm); + return; + } + GNUNET_TESTBED_operation_done(sm->op); sm->value = 0; sm->daemon++; if (NUM_DAEMONS == sm->daemon) - { - GNUNET_free (sm); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_free(sm); + GNUNET_SCHEDULER_shutdown(); + return; + } sm->op = - GNUNET_TESTBED_service_connect (NULL, - daemons[sm->daemon], - "statistics", - &stat_run, sm, - &statistics_connect_adapter, - &statistics_disconnect_adapter, - NULL); + GNUNET_TESTBED_service_connect(NULL, + daemons[sm->daemon], + "statistics", + &stat_run, sm, + &statistics_connect_adapter, + &statistics_disconnect_adapter, + NULL); } static void -do_report (void *cls) +do_report(void *cls) { char *fn = cls; struct GNUNET_TIME_Relative del; @@ -246,120 +244,120 @@ do_report (void *cls) struct StatMaster *sm; if (NULL != fn) - { - GNUNET_DISK_directory_remove (fn); - GNUNET_free (fn); - } + { + GNUNET_DISK_directory_remove(fn); + GNUNET_free(fn); + } if (0 == - GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (start_time, - TIMEOUT)).rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Timeout during download, shutting down with error\n"); - ok = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } - - del = GNUNET_TIME_absolute_get_duration (start_time); + GNUNET_TIME_absolute_get_remaining(GNUNET_TIME_absolute_add(start_time, + TIMEOUT)).rel_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Timeout during download, shutting down with error\n"); + ok = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } + + del = GNUNET_TIME_absolute_get_duration(start_time); if (del.rel_value_us == 0) del.rel_value_us = 1; fancy = - GNUNET_STRINGS_byte_size_fancy (((unsigned long long) FILESIZE) * - 1000000LL / del.rel_value_us); - fprintf (stdout, - "Download speed was %s/s\n", - fancy); - GNUNET_free (fancy); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished download, shutting down\n"); - sm = GNUNET_new (struct StatMaster); + GNUNET_STRINGS_byte_size_fancy(((unsigned long long)FILESIZE) * + 1000000LL / del.rel_value_us); + fprintf(stdout, + "Download speed was %s/s\n", + fancy); + GNUNET_free(fancy); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished download, shutting down\n"); + sm = GNUNET_new(struct StatMaster); sm->op = - GNUNET_TESTBED_service_connect (NULL, - daemons[sm->daemon], - "statistics", - &stat_run, sm, - &statistics_connect_adapter, - &statistics_disconnect_adapter, - NULL); + GNUNET_TESTBED_service_connect(NULL, + daemons[sm->daemon], + "statistics", + &stat_run, sm, + &statistics_connect_adapter, + &statistics_disconnect_adapter, + NULL); } static void -do_download (void *cls, - const struct GNUNET_FS_Uri *uri, - const char *fn) +do_download(void *cls, + const struct GNUNET_FS_Uri *uri, + const char *fn) { int anonymity; if (NULL == uri) - { - GNUNET_SCHEDULER_shutdown (); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Timeout during upload attempt, shutting down with error\n"); - ok = 1; - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Downloading %llu bytes\n", - (unsigned long long) FILESIZE); - start_time = GNUNET_TIME_absolute_get (); - if (NULL != strstr (progname, "dht")) + { + GNUNET_SCHEDULER_shutdown(); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Timeout during upload attempt, shutting down with error\n"); + ok = 1; + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Downloading %llu bytes\n", + (unsigned long long)FILESIZE); + start_time = GNUNET_TIME_absolute_get(); + if (NULL != strstr(progname, "dht")) anonymity = 0; else anonymity = 1; - start_time = GNUNET_TIME_absolute_get (); - GNUNET_FS_TEST_download (daemons[0], - TIMEOUT, - anonymity, - SEED, - uri, - VERBOSE, - &do_report, - (NULL == fn) ? NULL : GNUNET_strdup (fn)); + start_time = GNUNET_TIME_absolute_get(); + GNUNET_FS_TEST_download(daemons[0], + TIMEOUT, + anonymity, + SEED, + uri, + VERBOSE, + &do_report, + (NULL == fn) ? NULL : GNUNET_strdup(fn)); } static void -do_publish (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - unsigned int links_succeeded, - unsigned int links_failed) +do_publish(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + unsigned int links_succeeded, + unsigned int links_failed) { unsigned int i; int do_index; int anonymity; - GNUNET_assert (NUM_DAEMONS == num_peers); - for (i=0;i. SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/perf_gnunet_service_fs_p2p_respect.c @@ -57,7 +57,7 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 30) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 30) /** * Number of daemons in clique, must be at least 3 (!). @@ -93,16 +93,14 @@ static char *fn2; /** * Master context for 'stat_run'. */ -struct StatMaster -{ +struct StatMaster { struct GNUNET_STATISTICS_Handle *stat; struct GNUNET_TESTBED_Operation *op; unsigned int daemon; unsigned int value; }; -struct StatValues -{ +struct StatValues { const char *subsystem; const char *name; }; @@ -111,44 +109,44 @@ struct StatValues * Statistics we print out. */ static struct StatValues stats[] = { - {"fs", "# artificial delays introduced (ms)"}, - {"fs", "# queries forwarded"}, - {"fs", "# replies received and matched"}, - {"fs", "# results found locally"}, - {"fs", "# requests forwarded due to high load"}, - {"fs", "# requests done for free (low load)"}, - {"fs", "# requests dropped, priority insufficient"}, - {"fs", "# requests done for a price (normal load)"}, - {"fs", "# requests dropped by datastore (queue length limit)"}, - {"fs", "# P2P searches received"}, - {"fs", "# P2P searches discarded (queue length bound)"}, - {"fs", "# replies received for local clients"}, - {"fs", "# queries retransmitted to same target"}, - {"core", "# bytes decrypted"}, - {"core", "# bytes encrypted"}, - {"core", "# discarded CORE_SEND requests"}, - {"core", "# discarded lower priority CORE_SEND requests"}, - {"transport", "# bytes received via TCP"}, - {"transport", "# bytes transmitted via TCP"}, - {"datacache", "# bytes stored"}, - {NULL, NULL} + { "fs", "# artificial delays introduced (ms)" }, + { "fs", "# queries forwarded" }, + { "fs", "# replies received and matched" }, + { "fs", "# results found locally" }, + { "fs", "# requests forwarded due to high load" }, + { "fs", "# requests done for free (low load)" }, + { "fs", "# requests dropped, priority insufficient" }, + { "fs", "# requests done for a price (normal load)" }, + { "fs", "# requests dropped by datastore (queue length limit)" }, + { "fs", "# P2P searches received" }, + { "fs", "# P2P searches discarded (queue length bound)" }, + { "fs", "# replies received for local clients" }, + { "fs", "# queries retransmitted to same target" }, + { "core", "# bytes decrypted" }, + { "core", "# bytes encrypted" }, + { "core", "# discarded CORE_SEND requests" }, + { "core", "# discarded lower priority CORE_SEND requests" }, + { "transport", "# bytes received via TCP" }, + { "transport", "# bytes transmitted via TCP" }, + { "datacache", "# bytes stored" }, + { NULL, NULL } }; static void -cleanup () +cleanup() { - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); if (NULL != fn1) - { - GNUNET_DISK_directory_remove (fn1); - GNUNET_free (fn1); - } + { + GNUNET_DISK_directory_remove(fn1); + GNUNET_free(fn1); + } if (NULL != fn2) - { - GNUNET_DISK_directory_remove (fn2); - GNUNET_free (fn2); - } + { + GNUNET_DISK_directory_remove(fn2); + GNUNET_free(fn2); + } } @@ -163,13 +161,13 @@ cleanup () * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration */ static int -print_stat (void *cls, const char *subsystem, const char *name, uint64_t value, - int is_persistent) +print_stat(void *cls, const char *subsystem, const char *name, uint64_t value, + int is_persistent) { struct StatMaster *sm = cls; - fprintf (stderr, "Peer %2u: %12s/%50s = %12llu\n", sm->daemon, subsystem, - name, (unsigned long long) value); + fprintf(stderr, "Peer %2u: %12s/%50s = %12llu\n", sm->daemon, subsystem, + name, (unsigned long long)value); return GNUNET_OK; } @@ -178,23 +176,23 @@ print_stat (void *cls, const char *subsystem, const char *name, uint64_t value, * Function that gathers stats from all daemons. */ static void -stat_run (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg); +stat_run(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg); /** * Function called when GET operation on stats is done. */ static void -get_done (void *cls, int success) +get_done(void *cls, int success) { struct StatMaster *sm = cls; - GNUNET_break (GNUNET_OK == success); + GNUNET_break(GNUNET_OK == success); sm->value++; - stat_run (sm, sm->op, sm->stat, NULL); + stat_run(sm, sm->op, sm->stat, NULL); } @@ -210,11 +208,11 @@ get_done (void *cls, int success) * @return service handle to return in 'op_result', NULL on error */ static void * -statistics_connect_adapter (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +statistics_connect_adapter(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - return GNUNET_STATISTICS_create ("", - cfg); + return GNUNET_STATISTICS_create("", + cfg); } @@ -226,10 +224,10 @@ statistics_connect_adapter (void *cls, * @param op_result service handle returned from the connect adapter */ static void -statistics_disconnect_adapter (void *cls, - void *op_result) +statistics_disconnect_adapter(void *cls, + void *op_result) { - GNUNET_STATISTICS_destroy (op_result, GNUNET_NO); + GNUNET_STATISTICS_destroy(op_result, GNUNET_NO); } @@ -237,49 +235,49 @@ statistics_disconnect_adapter (void *cls, * Function that gathers stats from all daemons. */ static void -stat_run (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg) +stat_run(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg) { struct StatMaster *sm = cls; sm->stat = ca_result; - GNUNET_assert (NULL != sm->stat); + GNUNET_assert(NULL != sm->stat); if (NULL != stats[sm->value].name) - { - GNUNET_STATISTICS_get (sm->stat, + { + GNUNET_STATISTICS_get(sm->stat, #if 0 - NULL, NULL, + NULL, NULL, #else - stats[sm->value].subsystem, stats[sm->value].name, + stats[sm->value].subsystem, stats[sm->value].name, #endif - &get_done, &print_stat, - sm); - return; - } - GNUNET_TESTBED_operation_done (sm->op); + &get_done, &print_stat, + sm); + return; + } + GNUNET_TESTBED_operation_done(sm->op); sm->value = 0; sm->daemon++; if (NUM_DAEMONS == sm->daemon) - { - GNUNET_free (sm); - cleanup (); - return; - } + { + GNUNET_free(sm); + cleanup(); + return; + } sm->op = - GNUNET_TESTBED_service_connect (NULL, - daemons[sm->daemon], - "statistics", - &stat_run, sm, - &statistics_connect_adapter, - &statistics_disconnect_adapter, - NULL); + GNUNET_TESTBED_service_connect(NULL, + daemons[sm->daemon], + "statistics", + &stat_run, sm, + &statistics_connect_adapter, + &statistics_disconnect_adapter, + NULL); } static void -do_report (void *cls) +do_report(void *cls) { static int download_counter; const char *type = cls; @@ -288,62 +286,62 @@ do_report (void *cls) struct StatMaster *sm; if (0 == - GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (start_time, - TIMEOUT)).rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Timeout during download for type `%s', shutting down with error\n", - type); - ok = 1; - cleanup (); - return; - } - del = GNUNET_TIME_absolute_get_duration (start_time); + GNUNET_TIME_absolute_get_remaining(GNUNET_TIME_absolute_add(start_time, + TIMEOUT)).rel_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Timeout during download for type `%s', shutting down with error\n", + type); + ok = 1; + cleanup(); + return; + } + del = GNUNET_TIME_absolute_get_duration(start_time); if (del.rel_value_us == 0) del.rel_value_us = 1; fancy = - GNUNET_STRINGS_byte_size_fancy (((unsigned long long) FILESIZE) * - 1000000LL / del.rel_value_us); - fprintf (stderr, "Download speed of type `%s' was %s/s\n", type, fancy); - GNUNET_free (fancy); + GNUNET_STRINGS_byte_size_fancy(((unsigned long long)FILESIZE) * + 1000000LL / del.rel_value_us); + fprintf(stderr, "Download speed of type `%s' was %s/s\n", type, fancy); + GNUNET_free(fancy); if (NUM_DAEMONS != ++download_counter) return; /* more downloads to come */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished all downloads, getting statistics\n"); - sm = GNUNET_new (struct StatMaster); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished all downloads, getting statistics\n"); + sm = GNUNET_new(struct StatMaster); sm->op = - GNUNET_TESTBED_service_connect (NULL, - daemons[sm->daemon], - "statistics", - &stat_run, sm, - &statistics_connect_adapter, - &statistics_disconnect_adapter, - NULL); + GNUNET_TESTBED_service_connect(NULL, + daemons[sm->daemon], + "statistics", + &stat_run, sm, + &statistics_connect_adapter, + &statistics_disconnect_adapter, + NULL); } static void -do_downloads (void *cls, const struct GNUNET_FS_Uri *u2, - const char *fn) +do_downloads(void *cls, const struct GNUNET_FS_Uri *u2, + const char *fn) { int anonymity; unsigned int i; if (NULL == u2) - { - cleanup (); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Timeout during upload attempt, shutting down with error\n"); - ok = 1; - return; - } + { + cleanup(); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Timeout during upload attempt, shutting down with error\n"); + ok = 1; + return; + } if (NULL != fn) - fn2 = GNUNET_strdup (fn); - uri2 = GNUNET_FS_uri_dup (u2); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Downloading %llu bytes\n", - (unsigned long long) FILESIZE); - start_time = GNUNET_TIME_absolute_get (); - if (NULL != strstr (progname, "dht")) + fn2 = GNUNET_strdup(fn); + uri2 = GNUNET_FS_uri_dup(u2); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Downloading %llu bytes\n", + (unsigned long long)FILESIZE); + start_time = GNUNET_TIME_absolute_get(); + if (NULL != strstr(progname, "dht")) anonymity = 0; else anonymity = 1; @@ -351,127 +349,127 @@ do_downloads (void *cls, const struct GNUNET_FS_Uri *u2, * these peers do participate in sharing, they just * don't have to offer anything *initially*. */ for (i = 0; i < NUM_DAEMONS - 2; i++) - GNUNET_FS_TEST_download (daemons[i], TIMEOUT, anonymity, - 0 == (i % 2) ? SEED1 : SEED2, - 0 == (i % 2) ? uri1 : uri2, VERBOSE, &do_report, - "leach"); + GNUNET_FS_TEST_download(daemons[i], TIMEOUT, anonymity, + 0 == (i % 2) ? SEED1 : SEED2, + 0 == (i % 2) ? uri1 : uri2, VERBOSE, &do_report, + "leach"); /* mutual downloads of (primary) sharing peers */ - GNUNET_FS_TEST_download (daemons[NUM_DAEMONS - 2], TIMEOUT, anonymity, SEED1, - uri1, VERBOSE, &do_report, "seeder 2"); - GNUNET_FS_TEST_download (daemons[NUM_DAEMONS - 1], TIMEOUT, anonymity, SEED2, - uri2, VERBOSE, &do_report, "seeder 1"); + GNUNET_FS_TEST_download(daemons[NUM_DAEMONS - 2], TIMEOUT, anonymity, SEED1, + uri1, VERBOSE, &do_report, "seeder 2"); + GNUNET_FS_TEST_download(daemons[NUM_DAEMONS - 1], TIMEOUT, anonymity, SEED2, + uri2, VERBOSE, &do_report, "seeder 1"); } static void -do_publish2 (void *cls, - const struct GNUNET_FS_Uri *u1, - const char *fn) +do_publish2(void *cls, + const struct GNUNET_FS_Uri *u1, + const char *fn) { int do_index; int anonymity; if (NULL == u1) - { - cleanup (); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Timeout during upload attempt, shutting down with error\n"); - ok = 1; - return; - } + { + cleanup(); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Timeout during upload attempt, shutting down with error\n"); + ok = 1; + return; + } if (NULL != fn) - fn1 = GNUNET_strdup (fn); - uri1 = GNUNET_FS_uri_dup (u1); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Publishing %llu bytes\n", - (unsigned long long) FILESIZE); - if (NULL != strstr (progname, "index")) + fn1 = GNUNET_strdup(fn); + uri1 = GNUNET_FS_uri_dup(u1); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Publishing %llu bytes\n", + (unsigned long long)FILESIZE); + if (NULL != strstr(progname, "index")) do_index = GNUNET_YES; else do_index = GNUNET_NO; - if (NULL != strstr (progname, "dht")) + if (NULL != strstr(progname, "dht")) anonymity = 0; else anonymity = 1; - GNUNET_FS_TEST_publish (daemons[NUM_DAEMONS - 2], TIMEOUT, anonymity, - do_index, FILESIZE, SEED2, VERBOSE, &do_downloads, - NULL); + GNUNET_FS_TEST_publish(daemons[NUM_DAEMONS - 2], TIMEOUT, anonymity, + do_index, FILESIZE, SEED2, VERBOSE, &do_downloads, + NULL); } static void -do_publish1 (void *cls, - struct GNUNET_TESTBED_Operation *op, - const char *emsg) +do_publish1(void *cls, + struct GNUNET_TESTBED_Operation *op, + const char *emsg) { unsigned int *coco = cls; int do_index; int anonymity; - GNUNET_TESTBED_operation_done (op); + GNUNET_TESTBED_operation_done(op); if (NULL != emsg) - { - cleanup (); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error trying to connect: %s\n", emsg); - ok = 1; - return; - } + { + cleanup(); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error trying to connect: %s\n", emsg); + ok = 1; + return; + } if (0 != (--(*coco))) return; /* more connections to be created */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Publishing %llu bytes\n", - (unsigned long long) FILESIZE); - if (NULL != strstr (progname, "index")) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Publishing %llu bytes\n", + (unsigned long long)FILESIZE); + if (NULL != strstr(progname, "index")) do_index = GNUNET_YES; else do_index = GNUNET_NO; - if (NULL != strstr (progname, "dht")) + if (NULL != strstr(progname, "dht")) anonymity = 0; else anonymity = 1; - GNUNET_FS_TEST_publish (daemons[NUM_DAEMONS - 1], TIMEOUT, anonymity, - do_index, FILESIZE, SEED1, VERBOSE, &do_publish2, - NULL); + GNUNET_FS_TEST_publish(daemons[NUM_DAEMONS - 1], TIMEOUT, anonymity, + do_index, FILESIZE, SEED1, VERBOSE, &do_publish2, + NULL); } static void -do_connect (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - unsigned int links_succeeded, - unsigned int links_failed) +do_connect(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + unsigned int links_succeeded, + unsigned int links_failed) { static unsigned int coco; unsigned int i; unsigned int j; - GNUNET_assert (NUM_DAEMONS == num_peers); - for (i=0;i. SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/plugin_block_fs.c @@ -51,58 +51,61 @@ * by this @a type of block (this is not an error) */ static struct GNUNET_BLOCK_Group * -block_plugin_fs_create_group (void *cls, - enum GNUNET_BLOCK_Type type, - uint32_t nonce, - const void *raw_data, - size_t raw_data_size, - va_list va) +block_plugin_fs_create_group(void *cls, + enum GNUNET_BLOCK_Type type, + uint32_t nonce, + const void *raw_data, + size_t raw_data_size, + va_list va) { unsigned int size; const char *guard; switch (type) - { - case GNUNET_BLOCK_TYPE_FS_DBLOCK: - GNUNET_break (NULL == va_arg (va, const char *)); - return NULL; - case GNUNET_BLOCK_TYPE_FS_IBLOCK: - GNUNET_break (NULL == va_arg (va, const char *)); - return NULL; - case GNUNET_BLOCK_TYPE_FS_UBLOCK: - guard = va_arg (va, const char *); - if (0 == strcmp (guard, - "seen-set-size")) - { - size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size (va_arg (va, unsigned int), - BLOOMFILTER_K); - } - else if (0 == strcmp (guard, - "filter-size")) - { - size = va_arg (va, unsigned int); - } - else { - /* va-args invalid! bad bug, complain! */ - GNUNET_break (0); - size = 8; + case GNUNET_BLOCK_TYPE_FS_DBLOCK: + GNUNET_break(NULL == va_arg(va, const char *)); + return NULL; + + case GNUNET_BLOCK_TYPE_FS_IBLOCK: + GNUNET_break(NULL == va_arg(va, const char *)); + return NULL; + + case GNUNET_BLOCK_TYPE_FS_UBLOCK: + guard = va_arg(va, const char *); + if (0 == strcmp(guard, + "seen-set-size")) + { + size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size(va_arg(va, unsigned int), + BLOOMFILTER_K); + } + else if (0 == strcmp(guard, + "filter-size")) + { + size = va_arg(va, unsigned int); + } + else + { + /* va-args invalid! bad bug, complain! */ + GNUNET_break(0); + size = 8; + } + if (0 == size) + size = raw_data_size; /* not for us to determine, use what we got! */ + GNUNET_break(NULL == va_arg(va, const char *)); + return GNUNET_BLOCK_GROUP_bf_create(cls, + size, + BLOOMFILTER_K, + type, + nonce, + raw_data, + raw_data_size); + + default: + GNUNET_break(NULL == va_arg(va, const char *)); + GNUNET_break(0); + return NULL; } - if (0 == size) - size = raw_data_size; /* not for us to determine, use what we got! */ - GNUNET_break (NULL == va_arg (va, const char *)); - return GNUNET_BLOCK_GROUP_bf_create (cls, - size, - BLOOMFILTER_K, - type, - nonce, - raw_data, - raw_data_size); - default: - GNUNET_break (NULL == va_arg (va, const char *)); - GNUNET_break (0); - return NULL; - } } @@ -126,84 +129,86 @@ block_plugin_fs_create_group (void *cls, * @return characterization of result */ static enum GNUNET_BLOCK_EvaluationResult -block_plugin_fs_evaluate (void *cls, - struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *bg, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode *query, - const void *xquery, - size_t xquery_size, - const void *reply_block, - size_t reply_block_size) +block_plugin_fs_evaluate(void *cls, + struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *bg, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode *query, + const void *xquery, + size_t xquery_size, + const void *reply_block, + size_t reply_block_size) { const struct UBlock *ub; struct GNUNET_HashCode hc; struct GNUNET_HashCode chash; switch (type) - { - case GNUNET_BLOCK_TYPE_FS_DBLOCK: - case GNUNET_BLOCK_TYPE_FS_IBLOCK: - if (0 != xquery_size) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; - } - if (NULL == reply_block) - return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; - return GNUNET_BLOCK_EVALUATION_OK_LAST; - case GNUNET_BLOCK_TYPE_FS_UBLOCK: - if (0 != xquery_size) { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; - } - if (NULL == reply_block) - return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; + case GNUNET_BLOCK_TYPE_FS_DBLOCK: + case GNUNET_BLOCK_TYPE_FS_IBLOCK: + if (0 != xquery_size) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; + } + if (NULL == reply_block) + return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; + return GNUNET_BLOCK_EVALUATION_OK_LAST; - if (reply_block_size < sizeof (struct UBlock)) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; - } - ub = reply_block; - GNUNET_CRYPTO_hash (&ub->verification_key, - sizeof (ub->verification_key), - &hc); - if (0 != memcmp (&hc, - query, - sizeof (struct GNUNET_HashCode))) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; - } - if (reply_block_size != ntohl (ub->purpose.size) + sizeof (struct GNUNET_CRYPTO_EcdsaSignature)) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; - } - if ( (0 == (eo & GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO)) && - (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_UBLOCK, + case GNUNET_BLOCK_TYPE_FS_UBLOCK: + if (0 != xquery_size) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; + } + if (NULL == reply_block) + return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; + + if (reply_block_size < sizeof(struct UBlock)) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } + ub = reply_block; + GNUNET_CRYPTO_hash(&ub->verification_key, + sizeof(ub->verification_key), + &hc); + if (0 != memcmp(&hc, + query, + sizeof(struct GNUNET_HashCode))) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } + if (reply_block_size != ntohl(ub->purpose.size) + sizeof(struct GNUNET_CRYPTO_EcdsaSignature)) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } + if ((0 == (eo & GNUNET_BLOCK_EO_LOCAL_SKIP_CRYPTO)) && + (GNUNET_OK != + GNUNET_CRYPTO_ecdsa_verify(GNUNET_SIGNATURE_PURPOSE_FS_UBLOCK, &ub->purpose, &ub->signature, - &ub->verification_key)) ) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + &ub->verification_key))) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } + GNUNET_CRYPTO_hash(reply_block, + reply_block_size, + &chash); + if (GNUNET_YES == + GNUNET_BLOCK_GROUP_bf_test_and_set(bg, + &chash)) + return GNUNET_BLOCK_EVALUATION_OK_DUPLICATE; + return GNUNET_BLOCK_EVALUATION_OK_MORE; + + default: + return GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED; } - GNUNET_CRYPTO_hash (reply_block, - reply_block_size, - &chash); - if (GNUNET_YES == - GNUNET_BLOCK_GROUP_bf_test_and_set (bg, - &chash)) - return GNUNET_BLOCK_EVALUATION_OK_DUPLICATE; - return GNUNET_BLOCK_EVALUATION_OK_MORE; - default: - return GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED; - } } @@ -219,35 +224,37 @@ block_plugin_fs_evaluate (void *cls, * (or if extracting a key from a block of this type does not work) */ static int -block_plugin_fs_get_key (void *cls, - enum GNUNET_BLOCK_Type type, - const void *block, - size_t block_size, - struct GNUNET_HashCode *key) +block_plugin_fs_get_key(void *cls, + enum GNUNET_BLOCK_Type type, + const void *block, + size_t block_size, + struct GNUNET_HashCode *key) { const struct UBlock *ub; switch (type) - { - case GNUNET_BLOCK_TYPE_FS_DBLOCK: - case GNUNET_BLOCK_TYPE_FS_IBLOCK: - GNUNET_CRYPTO_hash (block, block_size, key); - return GNUNET_OK; - case GNUNET_BLOCK_TYPE_FS_UBLOCK: - if (block_size < sizeof (struct UBlock)) { - GNUNET_break (0); + case GNUNET_BLOCK_TYPE_FS_DBLOCK: + case GNUNET_BLOCK_TYPE_FS_IBLOCK: + GNUNET_CRYPTO_hash(block, block_size, key); + return GNUNET_OK; + + case GNUNET_BLOCK_TYPE_FS_UBLOCK: + if (block_size < sizeof(struct UBlock)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + ub = block; + GNUNET_CRYPTO_hash(&ub->verification_key, + sizeof(ub->verification_key), + key); + return GNUNET_OK; + + default: + GNUNET_break(0); return GNUNET_SYSERR; } - ub = block; - GNUNET_CRYPTO_hash (&ub->verification_key, - sizeof (ub->verification_key), - key); - return GNUNET_OK; - default: - GNUNET_break (0); - return GNUNET_SYSERR; - } } @@ -255,7 +262,7 @@ block_plugin_fs_get_key (void *cls, * Entry point for the plugin. */ void * -libgnunet_plugin_block_fs_init (void *cls) +libgnunet_plugin_block_fs_init(void *cls) { static enum GNUNET_BLOCK_Type types[] = { @@ -266,7 +273,7 @@ libgnunet_plugin_block_fs_init (void *cls) }; struct GNUNET_BLOCK_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_BLOCK_PluginFunctions); + api = GNUNET_new(struct GNUNET_BLOCK_PluginFunctions); api->evaluate = &block_plugin_fs_evaluate; api->get_key = &block_plugin_fs_get_key; api->create_group = &block_plugin_fs_create_group; @@ -279,11 +286,11 @@ libgnunet_plugin_block_fs_init (void *cls) * Exit point from the plugin. */ void * -libgnunet_plugin_block_fs_done (void *cls) +libgnunet_plugin_block_fs_done(void *cls) { struct GNUNET_BLOCK_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/fs/test_fs.c b/src/fs/test_fs.c index e88c74464..e88bacf59 100644 --- a/src/fs/test_fs.c +++ b/src/fs/test_fs.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs.c @@ -33,16 +33,16 @@ #define CHECK(a) if (!(a)) { ok = GNUNET_NO; GNUNET_GE_BREAK(NULL, 0); goto FAILURE; } static char * -makeName (unsigned int i) +makeName(unsigned int i) { char *fn; - fn = GNUNET_malloc (strlen ("/tmp/gnunet-basic_fsui_test/BASIC_FSUI_TEST") + - 14); - GNUNET_snprintf (fn, - strlen ("/tmp/gnunet-basic_fsui_test/BASIC_FSUI_TEST") + 14, - "/tmp/gnunet-basic_fsui_test/BASIC_FSUI_TEST%u", i); - GNUNET_disk_directory_create_for_file (NULL, fn); + fn = GNUNET_malloc(strlen("/tmp/gnunet-basic_fsui_test/BASIC_FSUI_TEST") + + 14); + GNUNET_snprintf(fn, + strlen("/tmp/gnunet-basic_fsui_test/BASIC_FSUI_TEST") + 14, + "/tmp/gnunet-basic_fsui_test/BASIC_FSUI_TEST%u", i); + GNUNET_disk_directory_create_for_file(NULL, fn); return fn; } @@ -55,42 +55,47 @@ static struct GNUNET_ECRS_URI *search_uri; static struct GNUNET_FSUI_Context *ctx; static void * -eventCallback (void *cls, const GNUNET_FSUI_Event * event) +eventCallback(void *cls, const GNUNET_FSUI_Event * event) { static char unused; switch (event->type) - { - case GNUNET_FSUI_search_resumed: - case GNUNET_FSUI_download_resumed: - case GNUNET_FSUI_upload_resumed: - case GNUNET_FSUI_unindex_resumed: - return &unused; - case GNUNET_FSUI_search_result: + { + case GNUNET_FSUI_search_resumed: + case GNUNET_FSUI_download_resumed: + case GNUNET_FSUI_upload_resumed: + case GNUNET_FSUI_unindex_resumed: + return &unused; + + case GNUNET_FSUI_search_result: #if DEBUG_VERBOSE - printf ("Received search result\n"); + printf("Received search result\n"); #endif - search_uri = GNUNET_ECRS_uri_duplicate (event->data.SearchResult.fi.uri); - search_meta = GNUNET_meta_data_duplicate (event->data.SearchResult.fi.meta); - break; - case GNUNET_FSUI_upload_completed: + search_uri = GNUNET_ECRS_uri_duplicate(event->data.SearchResult.fi.uri); + search_meta = GNUNET_meta_data_duplicate(event->data.SearchResult.fi.meta); + break; + + case GNUNET_FSUI_upload_completed: #if DEBUG_VERBOSE - printf ("Upload complete.\n"); + printf("Upload complete.\n"); #endif - break; - case GNUNET_FSUI_download_completed: + break; + + case GNUNET_FSUI_download_completed: #if DEBUG_VERBOSE - printf ("Download complete.\n"); + printf("Download complete.\n"); #endif - break; - case GNUNET_FSUI_unindex_completed: + break; + + case GNUNET_FSUI_unindex_completed: #if DEBUG_VERBOSE - printf ("Unindex complete.\n"); + printf("Unindex complete.\n"); #endif - break; - default: - break; - } + break; + + default: + break; + } lastEvent = event->type; return NULL; } @@ -98,7 +103,7 @@ eventCallback (void *cls, const GNUNET_FSUI_Event * event) #define START_DAEMON 1 int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { #if START_DAEMON struct GNUNET_OS_Process *daemon; @@ -122,128 +127,128 @@ main (int argc, char *argv[]) struct GNUNET_FSUI_UnindexList *unindex = NULL; struct GNUNET_FSUI_DownloadList *download = NULL; - cfg = GNUNET_GC_create (); - if (-1 == GNUNET_GC_parse_configuration (cfg, "check.conf")) - { - GNUNET_GC_free (cfg); - return -1; - } + cfg = GNUNET_GC_create(); + if (-1 == GNUNET_GC_parse_configuration(cfg, "check.conf")) + { + GNUNET_GC_free(cfg); + return -1; + } #if START_DAEMON - daemon = GNUNET_daemon_start (NULL, cfg, "peer.conf", GNUNET_NO); - GNUNET_GE_ASSERT (NULL, daemon != NULL); - CHECK (GNUNET_OK == - GNUNET_wait_for_daemon_running (NULL, cfg, 60 * GNUNET_CRON_SECONDS)); + daemon = GNUNET_daemon_start(NULL, cfg, "peer.conf", GNUNET_NO); + GNUNET_GE_ASSERT(NULL, daemon != NULL); + CHECK(GNUNET_OK == + GNUNET_wait_for_daemon_running(NULL, cfg, 60 * GNUNET_CRON_SECONDS)); #endif - GNUNET_thread_sleep (5 * GNUNET_CRON_SECONDS); /* give apps time to start */ + GNUNET_thread_sleep(5 * GNUNET_CRON_SECONDS); /* give apps time to start */ ok = GNUNET_YES; /* ACTUAL TEST CODE */ - ctx = GNUNET_FSUI_start (NULL, cfg, "basic_fsui_test", 32, /* thread pool size */ - GNUNET_NO, /* no resume */ - &eventCallback, NULL); - CHECK (ctx != NULL); - filename = makeName (42); - GNUNET_disk_file_write (NULL, filename, "foo bar test!", - strlen ("foo bar test!"), "600"); - meta = GNUNET_meta_data_create (); + ctx = GNUNET_FSUI_start(NULL, cfg, "basic_fsui_test", 32, /* thread pool size */ + GNUNET_NO, /* no resume */ + &eventCallback, NULL); + CHECK(ctx != NULL); + filename = makeName(42); + GNUNET_disk_file_write(NULL, filename, "foo bar test!", + strlen("foo bar test!"), "600"); + meta = GNUNET_meta_data_create(); kuri = - GNUNET_ECRS_keyword_command_line_to_uri (NULL, 2, - (const char **) keywords); + GNUNET_ECRS_keyword_command_line_to_uri(NULL, 2, + (const char **)keywords); /* upload */ - upload = GNUNET_FSUI_upload_start (ctx, filename, (GNUNET_FSUI_DirectoryScanCallback) & GNUNET_disk_directory_scan, NULL, 0, /* anonymity */ - 0, /* priority */ - GNUNET_YES, GNUNET_NO, GNUNET_NO, - GNUNET_get_time () + 5 * GNUNET_CRON_HOURS, - meta, kuri, kuri); - CHECK (upload != NULL); - GNUNET_ECRS_uri_destroy (kuri); - GNUNET_meta_data_destroy (meta); + upload = GNUNET_FSUI_upload_start(ctx, filename, (GNUNET_FSUI_DirectoryScanCallback) & GNUNET_disk_directory_scan, NULL, 0, /* anonymity */ + 0, /* priority */ + GNUNET_YES, GNUNET_NO, GNUNET_NO, + GNUNET_get_time() + 5 * GNUNET_CRON_HOURS, + meta, kuri, kuri); + CHECK(upload != NULL); + GNUNET_ECRS_uri_destroy(kuri); + GNUNET_meta_data_destroy(meta); prog = 0; while (lastEvent != GNUNET_FSUI_upload_completed) - { - prog++; - CHECK (prog < 10000) GNUNET_thread_sleep (50 * GNUNET_CRON_MILLISECONDS); - if (GNUNET_shutdown_test () == GNUNET_YES) - break; - } + { + prog++; + CHECK(prog < 10000) GNUNET_thread_sleep(50 * GNUNET_CRON_MILLISECONDS); + if (GNUNET_shutdown_test() == GNUNET_YES) + break; + } /* search */ - GNUNET_snprintf (keyword, 40, "+%s +%s", keywords[0], keywords[1]); - uri = GNUNET_ECRS_keyword_string_to_uri (NULL, keyword); - search = GNUNET_FSUI_search_start (ctx, 0, uri); - GNUNET_ECRS_uri_destroy (uri); - CHECK (search != NULL); + GNUNET_snprintf(keyword, 40, "+%s +%s", keywords[0], keywords[1]); + uri = GNUNET_ECRS_keyword_string_to_uri(NULL, keyword); + search = GNUNET_FSUI_search_start(ctx, 0, uri); + GNUNET_ECRS_uri_destroy(uri); + CHECK(search != NULL); prog = 0; while (lastEvent != GNUNET_FSUI_search_result) - { - prog++; - CHECK (prog < 10000); - GNUNET_thread_sleep (50 * GNUNET_CRON_MILLISECONDS); - if (GNUNET_shutdown_test () == GNUNET_YES) - break; - } - GNUNET_FSUI_search_abort (search); - GNUNET_FSUI_search_stop (search); + { + prog++; + CHECK(prog < 10000); + GNUNET_thread_sleep(50 * GNUNET_CRON_MILLISECONDS); + if (GNUNET_shutdown_test() == GNUNET_YES) + break; + } + GNUNET_FSUI_search_abort(search); + GNUNET_FSUI_search_stop(search); /* download */ - fn = makeName (43); + fn = makeName(43); download = - GNUNET_FSUI_download_start (ctx, 0, GNUNET_NO, search_uri, search_meta, - fn, NULL, NULL); - GNUNET_free (fn); + GNUNET_FSUI_download_start(ctx, 0, GNUNET_NO, search_uri, search_meta, + fn, NULL, NULL); + GNUNET_free(fn); prog = 0; while (lastEvent != GNUNET_FSUI_download_completed) - { - prog++; - CHECK (prog < 10000); - GNUNET_thread_sleep (50 * GNUNET_CRON_MILLISECONDS); - if (GNUNET_shutdown_test () == GNUNET_YES) - break; - } - GNUNET_FSUI_download_stop (download); + { + prog++; + CHECK(prog < 10000); + GNUNET_thread_sleep(50 * GNUNET_CRON_MILLISECONDS); + if (GNUNET_shutdown_test() == GNUNET_YES) + break; + } + GNUNET_FSUI_download_stop(download); download = NULL; - GNUNET_ECRS_uri_destroy (search_uri); - GNUNET_meta_data_destroy (search_meta); + GNUNET_ECRS_uri_destroy(search_uri); + GNUNET_meta_data_destroy(search_meta); /* unindex */ - unindex = GNUNET_FSUI_unindex_start (ctx, filename); + unindex = GNUNET_FSUI_unindex_start(ctx, filename); prog = 0; while (lastEvent != GNUNET_FSUI_unindex_completed) - { - prog++; - CHECK (prog < 10000); - GNUNET_thread_sleep (50 * GNUNET_CRON_MILLISECONDS); - if (GNUNET_shutdown_test () == GNUNET_YES) - break; - } + { + prog++; + CHECK(prog < 10000); + GNUNET_thread_sleep(50 * GNUNET_CRON_MILLISECONDS); + if (GNUNET_shutdown_test() == GNUNET_YES) + break; + } if (lastEvent != GNUNET_FSUI_unindex_completed) - GNUNET_FSUI_unindex_abort (unindex); - GNUNET_FSUI_unindex_stop (unindex); + GNUNET_FSUI_unindex_abort(unindex); + GNUNET_FSUI_unindex_stop(unindex); /* END OF TEST CODE */ FAILURE: if (ctx != NULL) - GNUNET_FSUI_stop (ctx); + GNUNET_FSUI_stop(ctx); if (filename != NULL) - { - unlink (filename); - GNUNET_free (filename); - } + { + unlink(filename); + GNUNET_free(filename); + } if (download != NULL) - { - GNUNET_FSUI_download_abort (download); - GNUNET_FSUI_download_stop (download); - } - filename = makeName (43); + { + GNUNET_FSUI_download_abort(download); + GNUNET_FSUI_download_stop(download); + } + filename = makeName(43); /* TODO: verify file 'filename(42)' == file 'filename(43)' */ - unlink (filename); - GNUNET_free (filename); + unlink(filename); + GNUNET_free(filename); #if START_DAEMON - GNUNET_GE_ASSERT (NULL, GNUNET_OK == GNUNET_daemon_stop (NULL, daemon)); - GNUNET_OS_process_destroy (daemon); + GNUNET_GE_ASSERT(NULL, GNUNET_OK == GNUNET_daemon_stop(NULL, daemon)); + GNUNET_OS_process_destroy(daemon); #endif - GNUNET_GC_free (cfg); + GNUNET_GC_free(cfg); return (ok == GNUNET_YES) ? 0 : 1; } diff --git a/src/fs/test_fs_directory.c b/src/fs/test_fs_directory.c index 5cdbd9d07..936c3bed4 100644 --- a/src/fs/test_fs_directory.c +++ b/src/fs/test_fs_directory.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_directory.c * @brief Test for fs_directory.c @@ -32,8 +32,7 @@ #define ABORT() { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); return 1; } -struct PCLS -{ +struct PCLS { struct GNUNET_FS_Uri **uri; struct GNUNET_CONTAINER_MetaData **md; unsigned int pos; @@ -41,9 +40,9 @@ struct PCLS }; static void -processor (void *cls, const char *filename, const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *md, size_t length, - const void *data) +processor(void *cls, const char *filename, const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *md, size_t length, + const void *data) { struct PCLS *p = cls; int i; @@ -51,19 +50,19 @@ processor (void *cls, const char *filename, const struct GNUNET_FS_Uri *uri, if (NULL == uri) return; /* ignore directory's meta data */ for (i = 0; i < p->max; i++) - { - if (GNUNET_CONTAINER_meta_data_test_equal (p->md[i], md) && - GNUNET_FS_uri_test_equal (p->uri[i], uri)) { - p->pos++; - return; + if (GNUNET_CONTAINER_meta_data_test_equal(p->md[i], md) && + GNUNET_FS_uri_test_equal(p->uri[i], uri)) + { + p->pos++; + return; + } } - } - fprintf (stderr, "Error at %s:%d\n", __FILE__, __LINE__); + fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); } static int -testDirectory (unsigned int i) +testDirectory(unsigned int i) { struct GNUNET_FS_DirectoryBuilder *db; char *data; @@ -82,99 +81,99 @@ testDirectory (unsigned int i) const char *s; cls.max = i; - uris = GNUNET_malloc (sizeof (struct GNUNET_FS_Uri *) * i); - mds = GNUNET_malloc (sizeof (struct GNUNET_CONTAINER_MetaData *) * i); - meta = GNUNET_CONTAINER_meta_data_create (); - GNUNET_CONTAINER_meta_data_insert (meta, "", EXTRACTOR_METATYPE_TITLE, - EXTRACTOR_METAFORMAT_UTF8, "text/plain", - "A title", strlen ("A title") + 1); - GNUNET_CONTAINER_meta_data_insert (meta, "", - EXTRACTOR_METATYPE_AUTHOR_NAME, - EXTRACTOR_METAFORMAT_UTF8, "text/plain", - "An author", strlen ("An author") + 1); + uris = GNUNET_malloc(sizeof(struct GNUNET_FS_Uri *) * i); + mds = GNUNET_malloc(sizeof(struct GNUNET_CONTAINER_MetaData *) * i); + meta = GNUNET_CONTAINER_meta_data_create(); + GNUNET_CONTAINER_meta_data_insert(meta, "", EXTRACTOR_METATYPE_TITLE, + EXTRACTOR_METAFORMAT_UTF8, "text/plain", + "A title", strlen("A title") + 1); + GNUNET_CONTAINER_meta_data_insert(meta, "", + EXTRACTOR_METATYPE_AUTHOR_NAME, + EXTRACTOR_METAFORMAT_UTF8, "text/plain", + "An author", strlen("An author") + 1); for (p = 0; p < i; p++) - { - mds[p] = GNUNET_CONTAINER_meta_data_create (); - for (q = 0; q <= p; q++) { - GNUNET_snprintf (txt, sizeof (txt), "%u -- %u\n", p, q); - GNUNET_CONTAINER_meta_data_insert (mds[p], "", + mds[p] = GNUNET_CONTAINER_meta_data_create(); + for (q = 0; q <= p; q++) + { + GNUNET_snprintf(txt, sizeof(txt), "%u -- %u\n", p, q); + GNUNET_CONTAINER_meta_data_insert(mds[p], "", #if HAVE_EXTRACTOR_H && HAVE_LIBEXTRACTOR - q % EXTRACTOR_metatype_get_max (), + q % EXTRACTOR_metatype_get_max(), #else - q % 128, + q % 128, #endif - EXTRACTOR_METAFORMAT_UTF8, - "text/plain", txt, strlen (txt) + 1); - } - GNUNET_snprintf (uri, sizeof (uri), - "gnunet://fs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.%u", - p); - emsg = NULL; - uris[p] = GNUNET_FS_uri_parse (uri, &emsg); - if (uris[p] == NULL) - { - GNUNET_CONTAINER_meta_data_destroy (mds[p]); - while (--p > 0) - { - GNUNET_CONTAINER_meta_data_destroy (mds[p]); - GNUNET_FS_uri_destroy (uris[p]); - } - GNUNET_free (mds); - GNUNET_free (uris); - GNUNET_free (emsg); - GNUNET_CONTAINER_meta_data_destroy (meta); - ABORT (); /* error in testcase */ + EXTRACTOR_METAFORMAT_UTF8, + "text/plain", txt, strlen(txt) + 1); + } + GNUNET_snprintf(uri, sizeof(uri), + "gnunet://fs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.%u", + p); + emsg = NULL; + uris[p] = GNUNET_FS_uri_parse(uri, &emsg); + if (uris[p] == NULL) + { + GNUNET_CONTAINER_meta_data_destroy(mds[p]); + while (--p > 0) + { + GNUNET_CONTAINER_meta_data_destroy(mds[p]); + GNUNET_FS_uri_destroy(uris[p]); + } + GNUNET_free(mds); + GNUNET_free(uris); + GNUNET_free(emsg); + GNUNET_CONTAINER_meta_data_destroy(meta); + ABORT(); /* error in testcase */ + } + GNUNET_assert(emsg == NULL); } - GNUNET_assert (emsg == NULL); - } - start = GNUNET_TIME_absolute_get (); - db = GNUNET_FS_directory_builder_create (meta); + start = GNUNET_TIME_absolute_get(); + db = GNUNET_FS_directory_builder_create(meta); for (p = 0; p < i; p++) - GNUNET_FS_directory_builder_add (db, uris[p], mds[p], NULL); - GNUNET_FS_directory_builder_finish (db, &dlen, (void **) &data); - s = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration - (start), - GNUNET_YES); - fprintf (stdout, - "Creating directory with %u entires and total size %llu took %s\n", - i, (unsigned long long) dlen, s); + GNUNET_FS_directory_builder_add(db, uris[p], mds[p], NULL); + GNUNET_FS_directory_builder_finish(db, &dlen, (void **)&data); + s = GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration + (start), + GNUNET_YES); + fprintf(stdout, + "Creating directory with %u entires and total size %llu took %s\n", + i, (unsigned long long)dlen, s); if (i < 100) - { - cls.pos = 0; - cls.uri = uris; - cls.md = mds; - GNUNET_FS_directory_list_contents (dlen, data, 0, &processor, &cls); - GNUNET_assert (cls.pos == i); - } - GNUNET_free (data); - GNUNET_CONTAINER_meta_data_destroy (meta); + { + cls.pos = 0; + cls.uri = uris; + cls.md = mds; + GNUNET_FS_directory_list_contents(dlen, data, 0, &processor, &cls); + GNUNET_assert(cls.pos == i); + } + GNUNET_free(data); + GNUNET_CONTAINER_meta_data_destroy(meta); for (p = 0; p < i; p++) - { - GNUNET_CONTAINER_meta_data_destroy (mds[p]); - GNUNET_FS_uri_destroy (uris[p]); - } - GNUNET_free (uris); - GNUNET_free (mds); + { + GNUNET_CONTAINER_meta_data_destroy(mds[p]); + GNUNET_FS_uri_destroy(uris[p]); + } + GNUNET_free(uris); + GNUNET_free(mds); return ret; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { int failureCount = 0; int i; - GNUNET_log_setup ("test_fs_directory", + GNUNET_log_setup("test_fs_directory", #if VERBOSE - "DEBUG", + "DEBUG", #else - "WARNING", + "WARNING", #endif - NULL); + NULL); for (i = 17; i < 1000; i *= 2) - failureCount += testDirectory (i); + failureCount += testDirectory(i); if (failureCount != 0) return 1; return 0; diff --git a/src/fs/test_fs_download.c b/src/fs/test_fs_download.c index 242e6f1aa..f7c35a680 100644 --- a/src/fs/test_fs_download.c +++ b/src/fs/test_fs_download.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_download.c @@ -38,12 +38,12 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 120) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 120) /** * How long should our test-content live? */ -#define LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) static unsigned int anonymity_level; @@ -67,187 +67,198 @@ static int err; static void -timeout_kill_task (void *cls) +timeout_kill_task(void *cls) { if (NULL != download) - { - GNUNET_FS_download_stop (download, GNUNET_YES); - download = NULL; - } + { + GNUNET_FS_download_stop(download, GNUNET_YES); + download = NULL; + } else if (NULL != publish) - { - GNUNET_FS_publish_stop (publish); - publish = NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Timeout downloading file\n"); + { + GNUNET_FS_publish_stop(publish); + publish = NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Timeout downloading file\n"); timeout_kill = NULL; err = 1; } static void -abort_publish_task (void *cls) +abort_publish_task(void *cls) { if (NULL != publish) - { - GNUNET_FS_publish_stop (publish); - publish = NULL; - } + { + GNUNET_FS_publish_stop(publish); + publish = NULL; + } } static void -stop_fs_task (void *cls) +stop_fs_task(void *cls) { - GNUNET_FS_stop (fs); + GNUNET_FS_stop(fs); fs = NULL; } static void -abort_download_task (void *cls) +abort_download_task(void *cls) { uint64_t size; if (NULL != download) - { - GNUNET_FS_download_stop (download, GNUNET_YES); - download = NULL; - } - GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_size (fn, &size, GNUNET_YES, GNUNET_NO)); - GNUNET_assert (size == FILESIZE); - GNUNET_DISK_directory_remove (fn); - GNUNET_free (fn); + { + GNUNET_FS_download_stop(download, GNUNET_YES); + download = NULL; + } + GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_size(fn, &size, GNUNET_YES, GNUNET_NO)); + GNUNET_assert(size == FILESIZE); + GNUNET_DISK_directory_remove(fn); + GNUNET_free(fn); fn = NULL; - GNUNET_SCHEDULER_cancel (timeout_kill); + GNUNET_SCHEDULER_cancel(timeout_kill); timeout_kill = NULL; } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { - switch (event->status) - { - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publish is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.publish.completed, - (unsigned long long) event->value.publish.size, - event->value.publish.specifics.progress.depth, - (unsigned long long) event->value.publish.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - break; - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - fprintf (stdout, - "Publishing complete, %llu kb/s.\n", - (unsigned long long) (FILESIZE * 1000000LL / - (1 + - GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024LL)); - GAUGER ("FS", - (GNUNET_YES == indexed) - ? "Publishing speed (indexing)" - : "Publishing speed (insertion)", - (unsigned long long) (FILESIZE * 1000000LL / - (1 + - GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024LL), "kb/s"); - fn = GNUNET_DISK_mktemp ("gnunet-download-test-dst"); - start = GNUNET_TIME_absolute_get (); - download = - GNUNET_FS_download_start (fs, - event->value.publish.specifics. - completed.chk_uri, NULL, fn, NULL, 0, - FILESIZE, anonymity_level, - GNUNET_FS_DOWNLOAD_OPTION_NONE, - "download", NULL); - GNUNET_assert (download != NULL); - break; - case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED: - fprintf (stdout, - "Download complete, %llu kb/s.\n", - (unsigned long long) (FILESIZE * 1000000LL / - (1 + - GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024LL)); - GAUGER ("FS", - (GNUNET_YES == indexed) - ? "Local download speed (indexed)" - : "Local download speed (inserted)", - (unsigned long long) (FILESIZE * 1000000LL / + { + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publish is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.publish.completed, + (unsigned long long)event->value.publish.size, + event->value.publish.specifics.progress.depth, + (unsigned long long)event->value.publish.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + break; + + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + fprintf(stdout, + "Publishing complete, %llu kb/s.\n", + (unsigned long long)(FILESIZE * 1000000LL / + (1 + + GNUNET_TIME_absolute_get_duration + (start).rel_value_us) / 1024LL)); + GAUGER("FS", + (GNUNET_YES == indexed) + ? "Publishing speed (indexing)" + : "Publishing speed (insertion)", + (unsigned long long)(FILESIZE * 1000000LL / + (1 + + GNUNET_TIME_absolute_get_duration + (start).rel_value_us) / 1024LL), "kb/s"); + fn = GNUNET_DISK_mktemp("gnunet-download-test-dst"); + start = GNUNET_TIME_absolute_get(); + download = + GNUNET_FS_download_start(fs, + event->value.publish.specifics. + completed.chk_uri, NULL, fn, NULL, 0, + FILESIZE, anonymity_level, + GNUNET_FS_DOWNLOAD_OPTION_NONE, + "download", NULL); + GNUNET_assert(download != NULL); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED: + fprintf(stdout, + "Download complete, %llu kb/s.\n", + (unsigned long long)(FILESIZE * 1000000LL / + (1 + + GNUNET_TIME_absolute_get_duration + (start).rel_value_us) / 1024LL)); + GAUGER("FS", + (GNUNET_YES == indexed) + ? "Local download speed (indexed)" + : "Local download speed (inserted)", + (unsigned long long)(FILESIZE * 1000000LL / (1 + GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024LL), "kb/s"); - GNUNET_SCHEDULER_add_now (&abort_download_task, NULL); - break; - case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: - GNUNET_assert (download == event->value.download.dc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Download is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.download.completed, - (unsigned long long) event->value.download.size, - event->value.download.specifics.progress.depth, - (unsigned long long) event->value.download.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - fprintf (stderr, "Error publishing file: %s\n", - event->value.publish.specifics.error.message); - GNUNET_break (0); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - GNUNET_SCHEDULER_shutdown (); - break; - case GNUNET_FS_STATUS_DOWNLOAD_ERROR: - fprintf (stderr, "Error downloading file: %s\n", - event->value.download.specifics.error.message); - GNUNET_SCHEDULER_add_now (&abort_download_task, NULL); - GNUNET_SCHEDULER_shutdown (); - break; - case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE: - case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE: - break; - case GNUNET_FS_STATUS_PUBLISH_START: - GNUNET_assert (0 == strcmp ("publish-context", event->value.publish.cctx)); - GNUNET_assert (NULL == event->value.publish.pctx); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (1 == event->value.publish.anonymity); - break; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - GNUNET_assert (publish == event->value.publish.pc); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (1 == event->value.publish.anonymity); - GNUNET_SCHEDULER_add_now (&stop_fs_task, NULL); - break; - case GNUNET_FS_STATUS_DOWNLOAD_START: - GNUNET_assert (0 == strcmp ("download", event->value.download.cctx)); - GNUNET_assert (NULL == event->value.download.pctx); - GNUNET_assert (NULL != event->value.download.uri); - GNUNET_assert (0 == strcmp (fn, event->value.download.filename)); - GNUNET_assert (FILESIZE == event->value.download.size); - GNUNET_assert (0 == event->value.download.completed); - GNUNET_assert (1 == event->value.download.anonymity); - break; - case GNUNET_FS_STATUS_DOWNLOAD_STOPPED: - GNUNET_assert (download == event->value.download.dc); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - default: - printf ("Unexpected event: %d\n", event->status); - break; - } + (start).rel_value_us) / 1024LL), "kb/s"); + GNUNET_SCHEDULER_add_now(&abort_download_task, NULL); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: + GNUNET_assert(download == event->value.download.dc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Download is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.download.completed, + (unsigned long long)event->value.download.size, + event->value.download.specifics.progress.depth, + (unsigned long long)event->value.download.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + fprintf(stderr, "Error publishing file: %s\n", + event->value.publish.specifics.error.message); + GNUNET_break(0); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + GNUNET_SCHEDULER_shutdown(); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_ERROR: + fprintf(stderr, "Error downloading file: %s\n", + event->value.download.specifics.error.message); + GNUNET_SCHEDULER_add_now(&abort_download_task, NULL); + GNUNET_SCHEDULER_shutdown(); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE: + case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE: + break; + + case GNUNET_FS_STATUS_PUBLISH_START: + GNUNET_assert(0 == strcmp("publish-context", event->value.publish.cctx)); + GNUNET_assert(NULL == event->value.publish.pctx); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(1 == event->value.publish.anonymity); + break; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + GNUNET_assert(publish == event->value.publish.pc); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(1 == event->value.publish.anonymity); + GNUNET_SCHEDULER_add_now(&stop_fs_task, NULL); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_START: + GNUNET_assert(0 == strcmp("download", event->value.download.cctx)); + GNUNET_assert(NULL == event->value.download.pctx); + GNUNET_assert(NULL != event->value.download.uri); + GNUNET_assert(0 == strcmp(fn, event->value.download.filename)); + GNUNET_assert(FILESIZE == event->value.download.size); + GNUNET_assert(0 == event->value.download.completed); + GNUNET_assert(1 == event->value.download.anonymity); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_STOPPED: + GNUNET_assert(download == event->value.download.dc); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + default: + printf("Unexpected event: %d\n", event->status); + break; + } return NULL; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { const char *binary_name = cls; const char *keywords[] = { @@ -262,89 +273,89 @@ run (void *cls, struct GNUNET_FS_BlockOptions bo; if (GNUNET_YES == - GNUNET_CONFIGURATION_get_value_yesno (cfg, - "download-test", - "USE_STREAM")) + GNUNET_CONFIGURATION_get_value_yesno(cfg, + "download-test", + "USE_STREAM")) anonymity_level = 0; else anonymity_level = 1; - fs = GNUNET_FS_start (cfg, binary_name, &progress_cb, NULL, - GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); - GNUNET_assert (NULL != fs); - buf = GNUNET_malloc (FILESIZE); + fs = GNUNET_FS_start(cfg, binary_name, &progress_cb, NULL, + GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); + GNUNET_assert(NULL != fs); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - meta = GNUNET_CONTAINER_meta_data_create (); - kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + meta = GNUNET_CONTAINER_meta_data_create(); + kuri = GNUNET_FS_uri_ksk_create_from_args(2, keywords); bo.content_priority = 42; bo.anonymity_level = anonymity_level; bo.replication_level = 0; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME); + bo.expiration_time = GNUNET_TIME_relative_to_absolute(LIFETIME); if (GNUNET_YES == - GNUNET_CONFIGURATION_get_value_yesno (cfg, - "download-test", - "USE_INDEX")) - { - fn1 = GNUNET_DISK_mktemp ("gnunet-download-indexed-test"); - GNUNET_assert (FILESIZE == - GNUNET_DISK_fn_write (fn1, buf, FILESIZE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)); - GNUNET_free (buf); - fi = GNUNET_FS_file_information_create_from_file (fs, "publish-context", fn1, - kuri, meta, GNUNET_YES, - &bo); - indexed = GNUNET_YES; - } + GNUNET_CONFIGURATION_get_value_yesno(cfg, + "download-test", + "USE_INDEX")) + { + fn1 = GNUNET_DISK_mktemp("gnunet-download-indexed-test"); + GNUNET_assert(FILESIZE == + GNUNET_DISK_fn_write(fn1, buf, FILESIZE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)); + GNUNET_free(buf); + fi = GNUNET_FS_file_information_create_from_file(fs, "publish-context", fn1, + kuri, meta, GNUNET_YES, + &bo); + indexed = GNUNET_YES; + } else - { - fi = GNUNET_FS_file_information_create_from_data (fs, "publish-context", - FILESIZE, buf, kuri, meta, - GNUNET_NO, &bo); - /* note: buf will be free'd as part of 'fi' now */ - indexed = GNUNET_NO; - } - GNUNET_FS_uri_destroy (kuri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_assert (NULL != fi); + { + fi = GNUNET_FS_file_information_create_from_data(fs, "publish-context", + FILESIZE, buf, kuri, meta, + GNUNET_NO, &bo); + /* note: buf will be free'd as part of 'fi' now */ + indexed = GNUNET_NO; + } + GNUNET_FS_uri_destroy(kuri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_assert(NULL != fi); timeout_kill = - GNUNET_SCHEDULER_add_delayed (TIMEOUT, &timeout_kill_task, NULL); - start = GNUNET_TIME_absolute_get (); + GNUNET_SCHEDULER_add_delayed(TIMEOUT, &timeout_kill_task, NULL); + start = GNUNET_TIME_absolute_get(); publish = - GNUNET_FS_publish_start (fs, fi, NULL, NULL, NULL, - GNUNET_FS_PUBLISH_OPTION_NONE); - GNUNET_assert (publish != NULL); + GNUNET_FS_publish_start(fs, fi, NULL, NULL, NULL, + GNUNET_FS_PUBLISH_OPTION_NONE); + GNUNET_assert(publish != NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *binary_name; const char *config_name; binary_name = "test-fs-download"; config_name = "test_fs_download_data.conf"; - if (NULL != strstr (argv[0], "indexed")) - { - binary_name = "test-fs-download-indexed"; - config_name = "test_fs_download_indexed.conf"; - } - if (NULL != strstr (argv[0], "cadet")) - { - binary_name = "test-fs-download-cadet"; - config_name = "test_fs_download_cadet.conf"; - } - if (0 != GNUNET_TESTING_peer_run (binary_name, - config_name, - &run, (void *) binary_name)) + if (NULL != strstr(argv[0], "indexed")) + { + binary_name = "test-fs-download-indexed"; + config_name = "test_fs_download_indexed.conf"; + } + if (NULL != strstr(argv[0], "cadet")) + { + binary_name = "test-fs-download-cadet"; + config_name = "test_fs_download_cadet.conf"; + } + if (0 != GNUNET_TESTING_peer_run(binary_name, + config_name, + &run, (void *)binary_name)) return 1; if (NULL != fn1) - { - unlink (fn1); - GNUNET_free (fn1); - } + { + unlink(fn1); + GNUNET_free(fn1); + } return err; } diff --git a/src/fs/test_fs_download_persistence.c b/src/fs/test_fs_download_persistence.c index 97c2a338c..78dbe821e 100644 --- a/src/fs/test_fs_download_persistence.c +++ b/src/fs/test_fs_download_persistence.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_download_persistence.c @@ -36,12 +36,12 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** * How long should our test-content live? */ -#define LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) static struct GNUNET_TIME_Absolute start; @@ -62,66 +62,66 @@ static int err; static void -timeout_kill_task (void *cls) +timeout_kill_task(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Timeout downloading file\n"); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Timeout downloading file\n"); if (download != NULL) - { - GNUNET_FS_download_stop (download, GNUNET_YES); - download = NULL; - } + { + GNUNET_FS_download_stop(download, GNUNET_YES); + download = NULL; + } else if (publish != NULL) - { - GNUNET_FS_publish_stop (publish); - publish = NULL; - } + { + GNUNET_FS_publish_stop(publish); + publish = NULL; + } timeout_kill = NULL; err = 1; } static void -abort_publish_task (void *cls) +abort_publish_task(void *cls) { if (publish != NULL) - { - GNUNET_FS_publish_stop (publish); - publish = NULL; - } + { + GNUNET_FS_publish_stop(publish); + publish = NULL; + } } static void -abort_download_task (void *cls) +abort_download_task(void *cls) { uint64_t size; if (download != NULL) - { - GNUNET_FS_download_stop (download, GNUNET_YES); - download = NULL; - } - GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_size (fn, &size, GNUNET_YES, GNUNET_NO)); - GNUNET_assert (size == FILESIZE); - GNUNET_DISK_directory_remove (fn); - GNUNET_free (fn); + { + GNUNET_FS_download_stop(download, GNUNET_YES); + download = NULL; + } + GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_size(fn, &size, GNUNET_YES, GNUNET_NO)); + GNUNET_assert(size == FILESIZE); + GNUNET_DISK_directory_remove(fn); + GNUNET_free(fn); fn = NULL; - GNUNET_SCHEDULER_cancel (timeout_kill); + GNUNET_SCHEDULER_cancel(timeout_kill); timeout_kill = NULL; } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event); +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event); static void -restart_fs_task (void *cls) +restart_fs_task(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Restarting FS.\n"); - GNUNET_FS_stop (fs); - fs = GNUNET_FS_start (cfg, "test-fs-download-persistence", &progress_cb, NULL, - GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Restarting FS.\n"); + GNUNET_FS_stop(fs); + fs = GNUNET_FS_start(cfg, "test-fs-download-persistence", &progress_cb, NULL, + GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); } @@ -133,7 +133,7 @@ restart_fs_task (void *cls) * @param ev type of the event to consider */ static void -consider_restart (int ev) +consider_restart(int ev) { static int prev[32]; static int off; @@ -143,141 +143,158 @@ consider_restart (int ev) if (prev[i] == ev) return; prev[off++] = ev; - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_URGENT, - &restart_fs_task, NULL); + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_URGENT, + &restart_fs_task, NULL); } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { switch (event->status) - { - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publish is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.publish.completed, - (unsigned long long) event->value.publish.size, - event->value.publish.specifics.progress.depth, - (unsigned long long) event->value.publish.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - break; - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - printf ("Publishing complete, %llu kbps.\n", - (unsigned long long) (FILESIZE * 1000000LL / + { + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publish is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.publish.completed, + (unsigned long long)event->value.publish.size, + event->value.publish.specifics.progress.depth, + (unsigned long long)event->value.publish.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + break; + + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + printf("Publishing complete, %llu kbps.\n", + (unsigned long long)(FILESIZE * 1000000LL / (1 + GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024LL)); - fn = GNUNET_DISK_mktemp ("gnunet-download-test-dst"); - start = GNUNET_TIME_absolute_get (); - GNUNET_assert (download == NULL); - GNUNET_FS_download_start (fs, - event->value.publish.specifics.completed.chk_uri, - NULL, fn, NULL, 0, FILESIZE, 1, - GNUNET_FS_DOWNLOAD_OPTION_NONE, "download", NULL); - break; - case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED: - printf ("Download complete, %llu kbps.\n", - (unsigned long long) (FILESIZE * 1000000LL / + (start).rel_value_us) / 1024LL)); + fn = GNUNET_DISK_mktemp("gnunet-download-test-dst"); + start = GNUNET_TIME_absolute_get(); + GNUNET_assert(download == NULL); + GNUNET_FS_download_start(fs, + event->value.publish.specifics.completed.chk_uri, + NULL, fn, NULL, 0, FILESIZE, 1, + GNUNET_FS_DOWNLOAD_OPTION_NONE, "download", NULL); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_COMPLETED: + printf("Download complete, %llu kbps.\n", + (unsigned long long)(FILESIZE * 1000000LL / (1 + GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024LL)); - GNUNET_SCHEDULER_add_now (&abort_download_task, NULL); - break; - case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: - consider_restart (event->status); - GNUNET_assert (download == event->value.download.dc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Download is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.download.completed, - (unsigned long long) event->value.download.size, - event->value.download.specifics.progress.depth, - (unsigned long long) event->value.download.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - fprintf (stderr, "Error publishing file: %s\n", - event->value.publish.specifics.error.message); - GNUNET_break (0); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - case GNUNET_FS_STATUS_DOWNLOAD_ERROR: - fprintf (stderr, "Error downloading file: %s\n", - event->value.download.specifics.error.message); - GNUNET_SCHEDULER_add_now (&abort_download_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_SUSPEND: - GNUNET_assert (event->value.publish.pc == publish); - publish = NULL; - break; - case GNUNET_FS_STATUS_PUBLISH_RESUME: - GNUNET_assert (NULL == publish); - publish = event->value.publish.pc; - break; - case GNUNET_FS_STATUS_DOWNLOAD_SUSPEND: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download suspended.\n"); - GNUNET_assert (event->value.download.dc == download); - download = NULL; - break; - case GNUNET_FS_STATUS_DOWNLOAD_RESUME: - GNUNET_assert (NULL == download); - download = event->value.download.dc; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download resumed.\n"); - break; - case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE: - consider_restart (event->status); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download active.\n"); - break; - case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE: - consider_restart (event->status); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download inactive.\n"); - break; - case GNUNET_FS_STATUS_PUBLISH_START: - GNUNET_assert (0 == strcmp ("publish-context", event->value.publish.cctx)); - GNUNET_assert (NULL == event->value.publish.pctx); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (1 == event->value.publish.anonymity); - break; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - GNUNET_assert (publish == event->value.publish.pc); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (1 == event->value.publish.anonymity); - GNUNET_FS_stop (fs); - fs = NULL; - break; - case GNUNET_FS_STATUS_DOWNLOAD_START: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download started.\n"); - consider_restart (event->status); - GNUNET_assert (download == NULL); - download = event->value.download.dc; - GNUNET_assert (0 == strcmp ("download", event->value.download.cctx)); - GNUNET_assert (NULL == event->value.download.pctx); - GNUNET_assert (NULL != event->value.download.uri); - GNUNET_assert (0 == strcmp (fn, event->value.download.filename)); - GNUNET_assert (FILESIZE == event->value.download.size); - GNUNET_assert (0 == event->value.download.completed); - GNUNET_assert (1 == event->value.download.anonymity); - break; - case GNUNET_FS_STATUS_DOWNLOAD_STOPPED: - GNUNET_assert (download == event->value.download.dc); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - download = NULL; - break; - default: - printf ("Unexpected event: %d\n", event->status); - break; - } + (start).rel_value_us) / 1024LL)); + GNUNET_SCHEDULER_add_now(&abort_download_task, NULL); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_PROGRESS: + consider_restart(event->status); + GNUNET_assert(download == event->value.download.dc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Download is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.download.completed, + (unsigned long long)event->value.download.size, + event->value.download.specifics.progress.depth, + (unsigned long long)event->value.download.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + fprintf(stderr, "Error publishing file: %s\n", + event->value.publish.specifics.error.message); + GNUNET_break(0); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_ERROR: + fprintf(stderr, "Error downloading file: %s\n", + event->value.download.specifics.error.message); + GNUNET_SCHEDULER_add_now(&abort_download_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_SUSPEND: + GNUNET_assert(event->value.publish.pc == publish); + publish = NULL; + break; + + case GNUNET_FS_STATUS_PUBLISH_RESUME: + GNUNET_assert(NULL == publish); + publish = event->value.publish.pc; + break; + + case GNUNET_FS_STATUS_DOWNLOAD_SUSPEND: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Download suspended.\n"); + GNUNET_assert(event->value.download.dc == download); + download = NULL; + break; + + case GNUNET_FS_STATUS_DOWNLOAD_RESUME: + GNUNET_assert(NULL == download); + download = event->value.download.dc; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Download resumed.\n"); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_ACTIVE: + consider_restart(event->status); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Download active.\n"); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_INACTIVE: + consider_restart(event->status); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Download inactive.\n"); + break; + + case GNUNET_FS_STATUS_PUBLISH_START: + GNUNET_assert(0 == strcmp("publish-context", event->value.publish.cctx)); + GNUNET_assert(NULL == event->value.publish.pctx); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(1 == event->value.publish.anonymity); + break; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + GNUNET_assert(publish == event->value.publish.pc); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(1 == event->value.publish.anonymity); + GNUNET_FS_stop(fs); + fs = NULL; + break; + + case GNUNET_FS_STATUS_DOWNLOAD_START: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Download started.\n"); + consider_restart(event->status); + GNUNET_assert(download == NULL); + download = event->value.download.dc; + GNUNET_assert(0 == strcmp("download", event->value.download.cctx)); + GNUNET_assert(NULL == event->value.download.pctx); + GNUNET_assert(NULL != event->value.download.uri); + GNUNET_assert(0 == strcmp(fn, event->value.download.filename)); + GNUNET_assert(FILESIZE == event->value.download.size); + GNUNET_assert(0 == event->value.download.completed); + GNUNET_assert(1 == event->value.download.anonymity); + break; + + case GNUNET_FS_STATUS_DOWNLOAD_STOPPED: + GNUNET_assert(download == event->value.download.dc); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + download = NULL; + break; + + default: + printf("Unexpected event: %d\n", event->status); + break; + } return NULL; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_TESTING_Peer *peer) { const char *keywords[] = { "down_foo", @@ -291,40 +308,40 @@ run (void *cls, struct GNUNET_FS_BlockOptions bo; cfg = c; - fs = GNUNET_FS_start (cfg, "test-fs-download-persistence", &progress_cb, NULL, - GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); - GNUNET_assert (NULL != fs); - buf = GNUNET_malloc (FILESIZE); + fs = GNUNET_FS_start(cfg, "test-fs-download-persistence", &progress_cb, NULL, + GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); + GNUNET_assert(NULL != fs); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - meta = GNUNET_CONTAINER_meta_data_create (); - kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + meta = GNUNET_CONTAINER_meta_data_create(); + kuri = GNUNET_FS_uri_ksk_create_from_args(2, keywords); bo.content_priority = 42; bo.anonymity_level = 1; bo.replication_level = 0; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME); - fi = GNUNET_FS_file_information_create_from_data (fs, "publish-context", - FILESIZE, buf, kuri, meta, - GNUNET_NO, &bo); - GNUNET_FS_uri_destroy (kuri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_assert (NULL != fi); + bo.expiration_time = GNUNET_TIME_relative_to_absolute(LIFETIME); + fi = GNUNET_FS_file_information_create_from_data(fs, "publish-context", + FILESIZE, buf, kuri, meta, + GNUNET_NO, &bo); + GNUNET_FS_uri_destroy(kuri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_assert(NULL != fi); timeout_kill = - GNUNET_SCHEDULER_add_delayed (TIMEOUT, &timeout_kill_task, NULL); - start = GNUNET_TIME_absolute_get (); + GNUNET_SCHEDULER_add_delayed(TIMEOUT, &timeout_kill_task, NULL); + start = GNUNET_TIME_absolute_get(); publish = - GNUNET_FS_publish_start (fs, fi, NULL, NULL, NULL, - GNUNET_FS_PUBLISH_OPTION_NONE); - GNUNET_assert (publish != NULL); + GNUNET_FS_publish_start(fs, fi, NULL, NULL, NULL, + GNUNET_FS_PUBLISH_OPTION_NONE); + GNUNET_assert(publish != NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-download-persistence", - "test_fs_download_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-download-persistence", + "test_fs_download_data.conf", + &run, NULL)) return 1; return err; } diff --git a/src/fs/test_fs_file_information.c b/src/fs/test_fs_file_information.c index 06682043a..1f008997f 100644 --- a/src/fs/test_fs_file_information.c +++ b/src/fs/test_fs_file_information.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_file_information.c @@ -44,21 +44,21 @@ /** * How long should our test-content live? */ -#define LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) static int -mycleaner (void *cls, struct GNUNET_FS_FileInformation *fi, uint64_t length, - struct GNUNET_CONTAINER_MetaData *meta, struct GNUNET_FS_Uri **uri, - struct GNUNET_FS_BlockOptions *bo, int *do_index, void **client_info) +mycleaner(void *cls, struct GNUNET_FS_FileInformation *fi, uint64_t length, + struct GNUNET_CONTAINER_MetaData *meta, struct GNUNET_FS_Uri **uri, + struct GNUNET_FS_BlockOptions *bo, int *do_index, void **client_info) { return GNUNET_OK; } static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { const char *keywords[] = { "down_foo", @@ -76,67 +76,67 @@ run (void *cls, char *const *args, const char *cfgfile, size_t i; struct GNUNET_FS_BlockOptions bo; - fs = GNUNET_FS_start (cfg, "test-fs-file-information", NULL, NULL, - GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); - fn1 = GNUNET_DISK_mktemp ("gnunet-file_information-test-dst"); - buf = GNUNET_malloc (FILESIZE); + fs = GNUNET_FS_start(cfg, "test-fs-file-information", NULL, NULL, + GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); + fn1 = GNUNET_DISK_mktemp("gnunet-file_information-test-dst"); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - GNUNET_assert (FILESIZE == - GNUNET_DISK_fn_write (fn1, buf, FILESIZE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)); - GNUNET_free (buf); - - fn2 = GNUNET_DISK_mktemp ("gnunet-file_information-test-dst"); - buf = GNUNET_malloc (FILESIZE); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + GNUNET_assert(FILESIZE == + GNUNET_DISK_fn_write(fn1, buf, FILESIZE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)); + GNUNET_free(buf); + + fn2 = GNUNET_DISK_mktemp("gnunet-file_information-test-dst"); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - GNUNET_assert (FILESIZE == - GNUNET_DISK_fn_write (fn2, buf, FILESIZE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)); - GNUNET_free (buf); - - meta = GNUNET_CONTAINER_meta_data_create (); - kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + GNUNET_assert(FILESIZE == + GNUNET_DISK_fn_write(fn2, buf, FILESIZE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)); + GNUNET_free(buf); + + meta = GNUNET_CONTAINER_meta_data_create(); + kuri = GNUNET_FS_uri_ksk_create_from_args(2, keywords); bo.content_priority = 42; bo.anonymity_level = 1; bo.replication_level = 0; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME); + bo.expiration_time = GNUNET_TIME_relative_to_absolute(LIFETIME); fi1 = - GNUNET_FS_file_information_create_from_file (fs, - "file_information-context1", - fn1, kuri, meta, GNUNET_YES, - &bo); - GNUNET_assert (fi1 != NULL); + GNUNET_FS_file_information_create_from_file(fs, + "file_information-context1", + fn1, kuri, meta, GNUNET_YES, + &bo); + GNUNET_assert(fi1 != NULL); fi2 = - GNUNET_FS_file_information_create_from_file (fs, - "file_information-context2", - fn2, kuri, meta, GNUNET_YES, - &bo); - GNUNET_assert (fi2 != NULL); + GNUNET_FS_file_information_create_from_file(fs, + "file_information-context2", + fn2, kuri, meta, GNUNET_YES, + &bo); + GNUNET_assert(fi2 != NULL); fidir = - GNUNET_FS_file_information_create_empty_directory (fs, - "file_information-context-dir", - kuri, meta, &bo, NULL); - GNUNET_assert (GNUNET_OK == GNUNET_FS_file_information_add (fidir, fi1)); - GNUNET_assert (GNUNET_OK == GNUNET_FS_file_information_add (fidir, fi2)); - GNUNET_FS_uri_destroy (kuri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_assert (NULL != fidir); + GNUNET_FS_file_information_create_empty_directory(fs, + "file_information-context-dir", + kuri, meta, &bo, NULL); + GNUNET_assert(GNUNET_OK == GNUNET_FS_file_information_add(fidir, fi1)); + GNUNET_assert(GNUNET_OK == GNUNET_FS_file_information_add(fidir, fi2)); + GNUNET_FS_uri_destroy(kuri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_assert(NULL != fidir); /* FIXME: test more of API! */ - GNUNET_FS_file_information_destroy (fidir, &mycleaner, NULL); - GNUNET_DISK_directory_remove (fn1); - GNUNET_DISK_directory_remove (fn2); - GNUNET_free_non_null (fn1); - GNUNET_free_non_null (fn2); - GNUNET_FS_stop (fs); + GNUNET_FS_file_information_destroy(fidir, &mycleaner, NULL); + GNUNET_DISK_directory_remove(fn1); + GNUNET_DISK_directory_remove(fn2); + GNUNET_free_non_null(fn1); + GNUNET_free_non_null(fn2); + GNUNET_FS_stop(fs); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { char *const argvx[] = { "test-fs-file_information", @@ -148,12 +148,12 @@ main (int argc, char *argv[]) GNUNET_GETOPT_OPTION_END }; - GNUNET_log_setup ("test_fs_file_information", - "WARNING", - NULL); - GNUNET_PROGRAM_run ((sizeof (argvx) / sizeof (char *)) - 1, argvx, - "test-fs-file_information", "nohelp", options, &run, - NULL); + GNUNET_log_setup("test_fs_file_information", + "WARNING", + NULL); + GNUNET_PROGRAM_run((sizeof(argvx) / sizeof(char *)) - 1, argvx, + "test-fs-file_information", "nohelp", options, &run, + NULL); return 0; } diff --git a/src/fs/test_fs_getopt.c b/src/fs/test_fs_getopt.c index 3562069e1..48777b0e0 100644 --- a/src/fs/test_fs_getopt.c +++ b/src/fs/test_fs_getopt.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_getopt.c * @brief test for fs_getopt.c @@ -27,11 +27,11 @@ int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - GNUNET_log_setup ("test_fs_getopt", - "WARNING", - NULL); - fprintf (stderr, "%s", "WARNING: testcase not yet written.\n"); + GNUNET_log_setup("test_fs_getopt", + "WARNING", + NULL); + fprintf(stderr, "%s", "WARNING: testcase not yet written.\n"); return 0; /* testcase passed */ } diff --git a/src/fs/test_fs_list_indexed.c b/src/fs/test_fs_list_indexed.c index a4e7eb53f..b5e5982d0 100644 --- a/src/fs/test_fs_list_indexed.c +++ b/src/fs/test_fs_list_indexed.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_list_indexed.c @@ -40,12 +40,12 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** * How long should our test-content live? */ -#define LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) static struct GNUNET_TIME_Absolute start; @@ -62,115 +62,121 @@ static int err; static void -abort_publish_task (void *cls) +abort_publish_task(void *cls) { - GNUNET_FS_publish_stop (publish); + GNUNET_FS_publish_stop(publish); publish = NULL; - GNUNET_DISK_directory_remove (fn1); - GNUNET_free (fn1); + GNUNET_DISK_directory_remove(fn1); + GNUNET_free(fn1); fn1 = NULL; - GNUNET_DISK_directory_remove (fn2); - GNUNET_free (fn2); + GNUNET_DISK_directory_remove(fn2); + GNUNET_free(fn2); fn2 = NULL; } static void -list_indexed_task (void *cls) +list_indexed_task(void *cls) { - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { void *ret; ret = NULL; switch (event->status) - { - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - ret = event->value.publish.cctx; - printf ("Publish complete, %llu kbps.\n", - (unsigned long long) (FILESIZE * 1000000LL / + { + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + ret = event->value.publish.cctx; + printf("Publish complete, %llu kbps.\n", + (unsigned long long)(FILESIZE * 1000000LL / (1 + GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024)); - if (0 == strcmp ("list_indexed-context-dir", event->value.publish.cctx)) - GNUNET_SCHEDULER_add_now (&list_indexed_task, NULL); - - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - ret = event->value.publish.cctx; - GNUNET_assert (publish == event->value.publish.pc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publish is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.publish.completed, - (unsigned long long) event->value.publish.size, - event->value.publish.specifics.progress.depth, - (unsigned long long) event->value.publish.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - ret = event->value.publish.cctx; - break; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - ret = event->value.publish.cctx; - fprintf (stderr, "Error publishing file: %s\n", - event->value.publish.specifics.error.message); - err = 1; - if (0 == strcmp ("list_indexed-context-dir", event->value.publish.cctx)) - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_START: - ret = event->value.publish.cctx; - if (0 == strcmp ("list_indexed-context1", event->value.publish.cctx)) - { - GNUNET_assert (0 == - strcmp ("list_indexed-context-dir", - event->value.publish.pctx)); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (1 == event->value.publish.anonymity); - } - else if (0 == strcmp ("list_indexed-context2", event->value.publish.cctx)) - { - GNUNET_assert (0 == - strcmp ("list_indexed-context-dir", - event->value.publish.pctx)); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (2 == event->value.publish.anonymity); - } - else if (0 == - strcmp ("list_indexed-context-dir", event->value.publish.cctx)) - { - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (3 == event->value.publish.anonymity); - } - else - GNUNET_assert (0); - break; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - if (0 == strcmp ("list_indexed-context-dir", event->value.publish.cctx)) - { - GNUNET_assert (publish == event->value.publish.pc); - publish = NULL; + (start).rel_value_us) / 1024)); + if (0 == strcmp("list_indexed-context-dir", event->value.publish.cctx)) + GNUNET_SCHEDULER_add_now(&list_indexed_task, NULL); + + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + ret = event->value.publish.cctx; + GNUNET_assert(publish == event->value.publish.pc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publish is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.publish.completed, + (unsigned long long)event->value.publish.size, + event->value.publish.specifics.progress.depth, + (unsigned long long)event->value.publish.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + ret = event->value.publish.cctx; + break; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + ret = event->value.publish.cctx; + fprintf(stderr, "Error publishing file: %s\n", + event->value.publish.specifics.error.message); + err = 1; + if (0 == strcmp("list_indexed-context-dir", event->value.publish.cctx)) + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_START: + ret = event->value.publish.cctx; + if (0 == strcmp("list_indexed-context1", event->value.publish.cctx)) + { + GNUNET_assert(0 == + strcmp("list_indexed-context-dir", + event->value.publish.pctx)); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(1 == event->value.publish.anonymity); + } + else if (0 == strcmp("list_indexed-context2", event->value.publish.cctx)) + { + GNUNET_assert(0 == + strcmp("list_indexed-context-dir", + event->value.publish.pctx)); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(2 == event->value.publish.anonymity); + } + else if (0 == + strcmp("list_indexed-context-dir", event->value.publish.cctx)) + { + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(3 == event->value.publish.anonymity); + } + else + GNUNET_assert(0); + break; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + if (0 == strcmp("list_indexed-context-dir", event->value.publish.cctx)) + { + GNUNET_assert(publish == event->value.publish.pc); + publish = NULL; + } + break; + + default: + printf("Unexpected event: %d\n", event->status); + break; } - break; - default: - printf ("Unexpected event: %d\n", event->status); - break; - } return ret; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { const char *keywords[] = { "down_foo", @@ -185,70 +191,70 @@ run (void *cls, size_t i; struct GNUNET_FS_BlockOptions bo; - fs = GNUNET_FS_start (cfg, "test-fs-list_indexed", &progress_cb, NULL, - GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); - GNUNET_assert (NULL != fs); - fn1 = GNUNET_DISK_mktemp ("gnunet-list_indexed-test-dst"); - buf = GNUNET_malloc (FILESIZE); + fs = GNUNET_FS_start(cfg, "test-fs-list_indexed", &progress_cb, NULL, + GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); + GNUNET_assert(NULL != fs); + fn1 = GNUNET_DISK_mktemp("gnunet-list_indexed-test-dst"); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - GNUNET_assert (FILESIZE == - GNUNET_DISK_fn_write (fn1, buf, FILESIZE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)); - GNUNET_free (buf); - - fn2 = GNUNET_DISK_mktemp ("gnunet-list_indexed-test-dst"); - buf = GNUNET_malloc (FILESIZE); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + GNUNET_assert(FILESIZE == + GNUNET_DISK_fn_write(fn1, buf, FILESIZE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)); + GNUNET_free(buf); + + fn2 = GNUNET_DISK_mktemp("gnunet-list_indexed-test-dst"); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - GNUNET_assert (FILESIZE == - GNUNET_DISK_fn_write (fn2, buf, FILESIZE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)); - GNUNET_free (buf); - - meta = GNUNET_CONTAINER_meta_data_create (); - kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + GNUNET_assert(FILESIZE == + GNUNET_DISK_fn_write(fn2, buf, FILESIZE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)); + GNUNET_free(buf); + + meta = GNUNET_CONTAINER_meta_data_create(); + kuri = GNUNET_FS_uri_ksk_create_from_args(2, keywords); bo.content_priority = 42; bo.anonymity_level = 1; bo.replication_level = 0; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME); + bo.expiration_time = GNUNET_TIME_relative_to_absolute(LIFETIME); fi1 = - GNUNET_FS_file_information_create_from_file (fs, "list_indexed-context1", - fn1, kuri, meta, GNUNET_YES, - &bo); - GNUNET_assert (NULL != fi1); + GNUNET_FS_file_information_create_from_file(fs, "list_indexed-context1", + fn1, kuri, meta, GNUNET_YES, + &bo); + GNUNET_assert(NULL != fi1); bo.anonymity_level = 2; fi2 = - GNUNET_FS_file_information_create_from_file (fs, "list_indexed-context2", - fn2, kuri, meta, GNUNET_YES, - &bo); - GNUNET_assert (NULL != fi2); + GNUNET_FS_file_information_create_from_file(fs, "list_indexed-context2", + fn2, kuri, meta, GNUNET_YES, + &bo); + GNUNET_assert(NULL != fi2); bo.anonymity_level = 3; fidir = - GNUNET_FS_file_information_create_empty_directory (fs, - "list_indexed-context-dir", - kuri, meta, &bo, NULL); - GNUNET_assert (GNUNET_OK == GNUNET_FS_file_information_add (fidir, fi1)); - GNUNET_assert (GNUNET_OK == GNUNET_FS_file_information_add (fidir, fi2)); - GNUNET_FS_uri_destroy (kuri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_assert (NULL != fidir); - start = GNUNET_TIME_absolute_get (); + GNUNET_FS_file_information_create_empty_directory(fs, + "list_indexed-context-dir", + kuri, meta, &bo, NULL); + GNUNET_assert(GNUNET_OK == GNUNET_FS_file_information_add(fidir, fi1)); + GNUNET_assert(GNUNET_OK == GNUNET_FS_file_information_add(fidir, fi2)); + GNUNET_FS_uri_destroy(kuri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_assert(NULL != fidir); + start = GNUNET_TIME_absolute_get(); publish = - GNUNET_FS_publish_start (fs, fidir, NULL, NULL, NULL, - GNUNET_FS_PUBLISH_OPTION_NONE); - GNUNET_assert (publish != NULL); + GNUNET_FS_publish_start(fs, fidir, NULL, NULL, NULL, + GNUNET_FS_PUBLISH_OPTION_NONE); + GNUNET_assert(publish != NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-list-indexed", - "test_fs_list_indexed_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-list-indexed", + "test_fs_list_indexed_data.conf", + &run, NULL)) return 1; return 0; } diff --git a/src/fs/test_fs_namespace.c b/src/fs/test_fs_namespace.c index 43c899b72..3abbd5063 100644 --- a/src/fs/test_fs_namespace.c +++ b/src/fs/test_fs_namespace.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_namespace.c @@ -49,118 +49,123 @@ static int err; static void -abort_ksk_search_task (void *cls) +abort_ksk_search_task(void *cls) { if (ksk_search != NULL) - { - GNUNET_FS_search_stop (ksk_search); - ksk_search = NULL; - if (sks_search == NULL) { - GNUNET_FS_stop (fs); - if (NULL != kill_task) - GNUNET_SCHEDULER_cancel (kill_task); + GNUNET_FS_search_stop(ksk_search); + ksk_search = NULL; + if (sks_search == NULL) + { + GNUNET_FS_stop(fs); + if (NULL != kill_task) + GNUNET_SCHEDULER_cancel(kill_task); + } } - } } static void -abort_sks_search_task (void *cls) +abort_sks_search_task(void *cls) { if (sks_search == NULL) return; - GNUNET_FS_search_stop (sks_search); + GNUNET_FS_search_stop(sks_search); sks_search = NULL; if (ksk_search == NULL) - { - GNUNET_FS_stop (fs); - if (NULL != kill_task) - GNUNET_SCHEDULER_cancel (kill_task); - } + { + GNUNET_FS_stop(fs); + if (NULL != kill_task) + GNUNET_SCHEDULER_cancel(kill_task); + } } static void -do_timeout (void *cls) +do_timeout(void *cls) { err = 1; - fprintf (stderr, "%s", "Operation timed out\n"); + fprintf(stderr, "%s", "Operation timed out\n"); kill_task = NULL; - abort_sks_search_task (NULL); - abort_ksk_search_task (NULL); + abort_sks_search_task(NULL); + abort_ksk_search_task(NULL); } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { switch (event->status) - { - case GNUNET_FS_STATUS_SEARCH_RESULT: - if (sks_search == event->value.search.sc) - { - if (!GNUNET_FS_uri_test_equal - (sks_expect_uri, event->value.search.specifics.result.uri)) - { - fprintf (stderr, "%s", "Wrong result for sks search!\n"); - err = 1; - } - /* give system 1ms to initiate update search! */ - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MILLISECONDS, - &abort_sks_search_task, NULL); - } - else if (ksk_search == event->value.search.sc) - { - if (!GNUNET_FS_uri_test_equal - (ksk_expect_uri, event->value.search.specifics.result.uri)) - { - fprintf (stderr, "%s", "Wrong result for ksk search!\n"); - err = 1; - } - GNUNET_SCHEDULER_add_now (&abort_ksk_search_task, NULL); - } - else - { - fprintf (stderr, "%s", "Unexpected search result received!\n"); - GNUNET_break (0); - } - break; - case GNUNET_FS_STATUS_SEARCH_ERROR: - fprintf (stderr, "Error searching file: %s\n", - event->value.search.specifics.error.message); - if (sks_search == event->value.search.sc) - GNUNET_SCHEDULER_add_now (&abort_sks_search_task, NULL); - else if (ksk_search == event->value.search.sc) - GNUNET_SCHEDULER_add_now (&abort_ksk_search_task, NULL); - else - GNUNET_break (0); - break; - case GNUNET_FS_STATUS_SEARCH_START: - GNUNET_assert ((NULL == event->value.search.cctx) || - (0 == strcmp ("sks_search", event->value.search.cctx)) || - (0 == strcmp ("ksk_search", event->value.search.cctx))); - if (NULL == event->value.search.cctx) { - GNUNET_assert (0 == strcmp ("sks_search", event->value.search.pctx)); - update_started = GNUNET_YES; + case GNUNET_FS_STATUS_SEARCH_RESULT: + if (sks_search == event->value.search.sc) + { + if (!GNUNET_FS_uri_test_equal + (sks_expect_uri, event->value.search.specifics.result.uri)) + { + fprintf(stderr, "%s", "Wrong result for sks search!\n"); + err = 1; + } + /* give system 1ms to initiate update search! */ + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MILLISECONDS, + &abort_sks_search_task, NULL); + } + else if (ksk_search == event->value.search.sc) + { + if (!GNUNET_FS_uri_test_equal + (ksk_expect_uri, event->value.search.specifics.result.uri)) + { + fprintf(stderr, "%s", "Wrong result for ksk search!\n"); + err = 1; + } + GNUNET_SCHEDULER_add_now(&abort_ksk_search_task, NULL); + } + else + { + fprintf(stderr, "%s", "Unexpected search result received!\n"); + GNUNET_break(0); + } + break; + + case GNUNET_FS_STATUS_SEARCH_ERROR: + fprintf(stderr, "Error searching file: %s\n", + event->value.search.specifics.error.message); + if (sks_search == event->value.search.sc) + GNUNET_SCHEDULER_add_now(&abort_sks_search_task, NULL); + else if (ksk_search == event->value.search.sc) + GNUNET_SCHEDULER_add_now(&abort_ksk_search_task, NULL); + else + GNUNET_break(0); + break; + + case GNUNET_FS_STATUS_SEARCH_START: + GNUNET_assert((NULL == event->value.search.cctx) || + (0 == strcmp("sks_search", event->value.search.cctx)) || + (0 == strcmp("ksk_search", event->value.search.cctx))); + if (NULL == event->value.search.cctx) + { + GNUNET_assert(0 == strcmp("sks_search", event->value.search.pctx)); + update_started = GNUNET_YES; + } + GNUNET_assert(1 == event->value.search.anonymity); + break; + + case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: + return NULL; + + case GNUNET_FS_STATUS_SEARCH_STOPPED: + return NULL; + + default: + fprintf(stderr, "Unexpected event: %d\n", event->status); + break; } - GNUNET_assert (1 == event->value.search.anonymity); - break; - case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: - return NULL; - case GNUNET_FS_STATUS_SEARCH_STOPPED: - return NULL; - default: - fprintf (stderr, "Unexpected event: %d\n", event->status); - break; - } return event->value.search.cctx; } static void -publish_cont (void *cls, const struct GNUNET_FS_Uri *ksk_uri, const char *emsg) +publish_cont(void *cls, const struct GNUNET_FS_Uri *ksk_uri, const char *emsg) { char *msg; struct GNUNET_FS_Uri *sks_uri; @@ -169,37 +174,37 @@ publish_cont (void *cls, const struct GNUNET_FS_Uri *ksk_uri, const char *emsg) char *ret; if (NULL != emsg) - { - fprintf (stderr, "Error publishing: %s\n", emsg); - err = 1; - GNUNET_FS_stop (fs); - return; - } - ret = GNUNET_STRINGS_data_to_string (&nsid, sizeof (nsid), buf, sizeof (buf)); - GNUNET_assert (NULL != ret); + { + fprintf(stderr, "Error publishing: %s\n", emsg); + err = 1; + GNUNET_FS_stop(fs); + return; + } + ret = GNUNET_STRINGS_data_to_string(&nsid, sizeof(nsid), buf, sizeof(buf)); + GNUNET_assert(NULL != ret); ret[0] = '\0'; - GNUNET_snprintf (sbuf, sizeof (sbuf), "gnunet://fs/sks/%s/this", buf); - sks_uri = GNUNET_FS_uri_parse (sbuf, &msg); + GNUNET_snprintf(sbuf, sizeof(sbuf), "gnunet://fs/sks/%s/this", buf); + sks_uri = GNUNET_FS_uri_parse(sbuf, &msg); if (NULL == sks_uri) - { - fprintf (stderr, "failed to parse URI `%s': %s\n", sbuf, msg); - err = 1; - GNUNET_FS_stop (fs); - GNUNET_free_non_null (msg); - return; - } + { + fprintf(stderr, "failed to parse URI `%s': %s\n", sbuf, msg); + err = 1; + GNUNET_FS_stop(fs); + GNUNET_free_non_null(msg); + return; + } ksk_search = - GNUNET_FS_search_start (fs, ksk_uri, 1, GNUNET_FS_SEARCH_OPTION_NONE, - "ksk_search"); + GNUNET_FS_search_start(fs, ksk_uri, 1, GNUNET_FS_SEARCH_OPTION_NONE, + "ksk_search"); sks_search = - GNUNET_FS_search_start (fs, sks_uri, 1, GNUNET_FS_SEARCH_OPTION_NONE, - "sks_search"); - GNUNET_FS_uri_destroy (sks_uri); + GNUNET_FS_search_start(fs, sks_uri, 1, GNUNET_FS_SEARCH_OPTION_NONE, + "sks_search"); + GNUNET_FS_uri_destroy(sks_uri); } static void -sks_cont (void *cls, const struct GNUNET_FS_Uri *uri, const char *emsg) +sks_cont(void *cls, const struct GNUNET_FS_Uri *uri, const char *emsg) { struct GNUNET_CONTAINER_MetaData *meta; struct GNUNET_FS_Uri *ksk_uri; @@ -207,61 +212,61 @@ sks_cont (void *cls, const struct GNUNET_FS_Uri *uri, const char *emsg) struct GNUNET_FS_BlockOptions bo; if (NULL == uri) - { - fprintf (stderr, "Error publishing: %s\n", emsg); - err = 1; - GNUNET_FS_stop (fs); - return; - } - meta = GNUNET_CONTAINER_meta_data_create (); + { + fprintf(stderr, "Error publishing: %s\n", emsg); + err = 1; + GNUNET_FS_stop(fs); + return; + } + meta = GNUNET_CONTAINER_meta_data_create(); msg = NULL; - ksk_uri = GNUNET_FS_uri_parse ("gnunet://fs/ksk/ns-search", &msg); - GNUNET_assert (NULL == msg); - ksk_expect_uri = GNUNET_FS_uri_dup (uri); + ksk_uri = GNUNET_FS_uri_parse("gnunet://fs/ksk/ns-search", &msg); + GNUNET_assert(NULL == msg); + ksk_expect_uri = GNUNET_FS_uri_dup(uri); bo.content_priority = 1; bo.anonymity_level = 1; bo.replication_level = 0; bo.expiration_time = - GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES); - GNUNET_FS_publish_ksk (fs, ksk_uri, meta, uri, &bo, - GNUNET_FS_PUBLISH_OPTION_NONE, &publish_cont, NULL); - GNUNET_FS_uri_destroy (ksk_uri); - GNUNET_CONTAINER_meta_data_destroy (meta); + GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_MINUTES); + GNUNET_FS_publish_ksk(fs, ksk_uri, meta, uri, &bo, + GNUNET_FS_PUBLISH_OPTION_NONE, &publish_cont, NULL); + GNUNET_FS_uri_destroy(ksk_uri); + GNUNET_CONTAINER_meta_data_destroy(meta); } static void -adv_cont (void *cls, const struct GNUNET_FS_Uri *uri, const char *emsg) +adv_cont(void *cls, const struct GNUNET_FS_Uri *uri, const char *emsg) { struct GNUNET_CONTAINER_MetaData *meta; struct GNUNET_CRYPTO_EcdsaPrivateKey *ns; struct GNUNET_FS_BlockOptions bo; if (NULL != emsg) - { - fprintf (stderr, "Error publishing: %s\n", emsg); - err = 1; - GNUNET_FS_stop (fs); - return; - } - ns = GNUNET_CRYPTO_ecdsa_key_create (); - meta = GNUNET_CONTAINER_meta_data_create (); - sks_expect_uri = GNUNET_FS_uri_dup (uri); + { + fprintf(stderr, "Error publishing: %s\n", emsg); + err = 1; + GNUNET_FS_stop(fs); + return; + } + ns = GNUNET_CRYPTO_ecdsa_key_create(); + meta = GNUNET_CONTAINER_meta_data_create(); + sks_expect_uri = GNUNET_FS_uri_dup(uri); bo.content_priority = 1; bo.anonymity_level = 1; bo.replication_level = 0; bo.expiration_time = - GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES); - GNUNET_CRYPTO_ecdsa_key_get_public (ns, &nsid); - GNUNET_FS_publish_sks (fs, ns, "this", "next", meta, uri, - &bo, GNUNET_FS_PUBLISH_OPTION_NONE, &sks_cont, NULL); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_free (ns); + GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_MINUTES); + GNUNET_CRYPTO_ecdsa_key_get_public(ns, &nsid); + GNUNET_FS_publish_sks(fs, ns, "this", "next", meta, uri, + &bo, GNUNET_FS_PUBLISH_OPTION_NONE, &sks_cont, NULL); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_free(ns); } static void -testNamespace () +testNamespace() { struct GNUNET_CRYPTO_EcdsaPrivateKey *ns; struct GNUNET_FS_BlockOptions bo; @@ -269,46 +274,46 @@ testNamespace () struct GNUNET_FS_Uri *ksk_uri; struct GNUNET_FS_Uri *sks_uri; - ns = GNUNET_CRYPTO_ecdsa_key_create (); - meta = GNUNET_CONTAINER_meta_data_create (); - ksk_uri = GNUNET_FS_uri_parse ("gnunet://fs/ksk/testnsa", NULL); + ns = GNUNET_CRYPTO_ecdsa_key_create(); + meta = GNUNET_CONTAINER_meta_data_create(); + ksk_uri = GNUNET_FS_uri_parse("gnunet://fs/ksk/testnsa", NULL); bo.content_priority = 1; bo.anonymity_level = 1; bo.replication_level = 0; bo.expiration_time = - GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES); - sks_uri = GNUNET_FS_uri_sks_create (&nsid, "root"); - GNUNET_FS_publish_ksk (fs, - ksk_uri, meta, sks_uri, - &bo, GNUNET_FS_PUBLISH_OPTION_NONE, - &adv_cont, NULL); - GNUNET_FS_uri_destroy (sks_uri); + GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_MINUTES); + sks_uri = GNUNET_FS_uri_sks_create(&nsid, "root"); + GNUNET_FS_publish_ksk(fs, + ksk_uri, meta, sks_uri, + &bo, GNUNET_FS_PUBLISH_OPTION_NONE, + &adv_cont, NULL); + GNUNET_FS_uri_destroy(sks_uri); kill_task = - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, &do_timeout, - NULL); - GNUNET_FS_uri_destroy (ksk_uri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_free (ns); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES, &do_timeout, + NULL); + GNUNET_FS_uri_destroy(ksk_uri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_free(ns); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - fs = GNUNET_FS_start (cfg, "test-fs-namespace", &progress_cb, NULL, - GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); - testNamespace (); + fs = GNUNET_FS_start(cfg, "test-fs-namespace", &progress_cb, NULL, + GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); + testNamespace(); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-namespace", - "test_fs_namespace_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-namespace", + "test_fs_namespace_data.conf", + &run, NULL)) return 1; return err; } diff --git a/src/fs/test_fs_namespace_list_updateable.c b/src/fs/test_fs_namespace_list_updateable.c index 99c0967b8..9a28fcb1b 100644 --- a/src/fs/test_fs_namespace_list_updateable.c +++ b/src/fs/test_fs_namespace_list_updateable.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_namespace_list_updateable.c @@ -45,129 +45,128 @@ static struct GNUNET_FS_BlockOptions bo; static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { return NULL; } static void -do_shutdown () +do_shutdown() { if (uri_this != NULL) - GNUNET_FS_uri_destroy (uri_this); + GNUNET_FS_uri_destroy(uri_this); if (uri_next != NULL) - GNUNET_FS_uri_destroy (uri_next); + GNUNET_FS_uri_destroy(uri_next); if (ns != NULL) - GNUNET_free (ns); + GNUNET_free(ns); if (meta != NULL) - GNUNET_CONTAINER_meta_data_destroy (meta); + GNUNET_CONTAINER_meta_data_destroy(meta); } static void -check_next (void *cls, const char *last_id, - const struct GNUNET_FS_Uri *last_uri, - const struct GNUNET_CONTAINER_MetaData *last_meta, - const char *next_id) +check_next(void *cls, const char *last_id, + const struct GNUNET_FS_Uri *last_uri, + const struct GNUNET_CONTAINER_MetaData *last_meta, + const char *next_id) { - GNUNET_break (0 == strcmp (last_id, "next")); - GNUNET_break (0 == strcmp (next_id, "future")); + GNUNET_break(0 == strcmp(last_id, "next")); + GNUNET_break(0 == strcmp(next_id, "future")); err -= 4; } static void -check_this_next (void *cls, const char *last_id, - const struct GNUNET_FS_Uri *last_uri, - const struct GNUNET_CONTAINER_MetaData *last_meta, - const char *next_id) +check_this_next(void *cls, const char *last_id, + const struct GNUNET_FS_Uri *last_uri, + const struct GNUNET_CONTAINER_MetaData *last_meta, + const char *next_id) { - GNUNET_break (0 == strcmp (last_id, "this")); - GNUNET_break (0 == strcmp (next_id, "next")); + GNUNET_break(0 == strcmp(last_id, "this")); + GNUNET_break(0 == strcmp(next_id, "next")); err -= 2; err += 4; - GNUNET_FS_namespace_list_updateable (fs, ns, next_id, &check_next, NULL); + GNUNET_FS_namespace_list_updateable(fs, ns, next_id, &check_next, NULL); } static void -sks_cont_next (void *cls, const struct GNUNET_FS_Uri *uri, const char *emsg) +sks_cont_next(void *cls, const struct GNUNET_FS_Uri *uri, const char *emsg) { - GNUNET_assert (NULL == emsg); + GNUNET_assert(NULL == emsg); err += 2; - GNUNET_FS_namespace_list_updateable (fs, ns, NULL, &check_this_next, NULL); + GNUNET_FS_namespace_list_updateable(fs, ns, NULL, &check_this_next, NULL); } static void -check_this (void *cls, const char *last_id, - const struct GNUNET_FS_Uri *last_uri, - const struct GNUNET_CONTAINER_MetaData *last_meta, - const char *next_id) +check_this(void *cls, const char *last_id, + const struct GNUNET_FS_Uri *last_uri, + const struct GNUNET_CONTAINER_MetaData *last_meta, + const char *next_id) { - GNUNET_break (0 == strcmp (last_id, "this")); - GNUNET_break (0 == strcmp (next_id, "next")); + GNUNET_break(0 == strcmp(last_id, "this")); + GNUNET_break(0 == strcmp(next_id, "next")); err -= 1; } static void -sks_cont_this (void *cls, const struct GNUNET_FS_Uri *uri, const char *emsg) +sks_cont_this(void *cls, const struct GNUNET_FS_Uri *uri, const char *emsg) { - GNUNET_assert (NULL == emsg); + GNUNET_assert(NULL == emsg); err = 1; - GNUNET_FS_namespace_list_updateable (fs, ns, NULL, &check_this, NULL); - GNUNET_FS_publish_sks (fs, ns, "next", "future", meta, uri_next, &bo, - GNUNET_FS_PUBLISH_OPTION_NONE, &sks_cont_next, NULL); - + GNUNET_FS_namespace_list_updateable(fs, ns, NULL, &check_this, NULL); + GNUNET_FS_publish_sks(fs, ns, "next", "future", meta, uri_next, &bo, + GNUNET_FS_PUBLISH_OPTION_NONE, &sks_cont_next, NULL); } static void -testNamespace () +testNamespace() { - ns = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (NULL != ns); + ns = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(NULL != ns); bo.content_priority = 1; bo.anonymity_level = 1; bo.replication_level = 0; bo.expiration_time = - GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES); - meta = GNUNET_CONTAINER_meta_data_create (); + GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_MINUTES); + meta = GNUNET_CONTAINER_meta_data_create(); uri_this = - GNUNET_FS_uri_parse + GNUNET_FS_uri_parse ("gnunet://fs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.42", - NULL); + NULL); uri_next = - GNUNET_FS_uri_parse + GNUNET_FS_uri_parse ("gnunet://fs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.43", - NULL); - GNUNET_FS_publish_sks (fs, ns, "this", "next", meta, uri_this, &bo, - GNUNET_FS_PUBLISH_OPTION_NONE, &sks_cont_this, NULL); + NULL); + GNUNET_FS_publish_sks(fs, ns, "this", "next", meta, uri_this, &bo, + GNUNET_FS_PUBLISH_OPTION_NONE, &sks_cont_this, NULL); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - fs = GNUNET_FS_start (cfg, "test-fs-namespace", &progress_cb, NULL, - GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); - testNamespace (); + fs = GNUNET_FS_start(cfg, "test-fs-namespace", &progress_cb, NULL, + GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); + testNamespace(); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-namespace-list-updateable", - "test_fs_namespace_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-namespace-list-updateable", + "test_fs_namespace_data.conf", + &run, NULL)) return 1; - do_shutdown (); + do_shutdown(); return err; } diff --git a/src/fs/test_fs_publish.c b/src/fs/test_fs_publish.c index fe54bb552..02c1587d2 100644 --- a/src/fs/test_fs_publish.c +++ b/src/fs/test_fs_publish.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_publish.c * @brief simple testcase for publish operation (indexing, listing @@ -36,12 +36,12 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** * How long should our test-content live? */ -#define LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) static struct GNUNET_TIME_Absolute start; @@ -58,105 +58,111 @@ static int err; static void -abort_publish_task (void *cls) +abort_publish_task(void *cls) { - GNUNET_FS_publish_stop (publish); + GNUNET_FS_publish_stop(publish); publish = NULL; - GNUNET_DISK_directory_remove (fn1); - GNUNET_free (fn1); + GNUNET_DISK_directory_remove(fn1); + GNUNET_free(fn1); fn1 = NULL; - GNUNET_DISK_directory_remove (fn2); - GNUNET_free (fn2); + GNUNET_DISK_directory_remove(fn2); + GNUNET_free(fn2); fn2 = NULL; } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { void *ret; ret = NULL; switch (event->status) - { - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - ret = event->value.publish.cctx; - printf ("Publish complete, %llu kbps.\n", - (unsigned long long) (FILESIZE * 1000000LL / + { + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + ret = event->value.publish.cctx; + printf("Publish complete, %llu kbps.\n", + (unsigned long long)(FILESIZE * 1000000LL / (1 + GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024)); - if (0 == strcmp ("publish-context-dir", event->value.publish.cctx)) - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - ret = event->value.publish.cctx; - GNUNET_assert (publish == event->value.publish.pc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publish is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.publish.completed, - (unsigned long long) event->value.publish.size, - event->value.publish.specifics.progress.depth, - (unsigned long long) event->value.publish.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - ret = event->value.publish.cctx; - break; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - ret = event->value.publish.cctx; - fprintf (stderr, "Error publishing file: %s\n", - event->value.publish.specifics.error.message); - err = 1; - if (0 == strcmp ("publish-context-dir", event->value.publish.cctx)) - { - fprintf (stderr, "Scheduling abort task for error on `%s'\n", - (const char *) event->value.publish.cctx); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - } - break; - case GNUNET_FS_STATUS_PUBLISH_START: - ret = event->value.publish.cctx; - if (0 == strcmp ("publish-context1", event->value.publish.cctx)) - { - GNUNET_assert (0 == - strcmp ("publish-context-dir", event->value.publish.pctx)); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (1 == event->value.publish.anonymity); - } - else if (0 == strcmp ("publish-context2", event->value.publish.cctx)) - { - GNUNET_assert (0 == - strcmp ("publish-context-dir", event->value.publish.pctx)); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (2 == event->value.publish.anonymity); - } - else if (0 == strcmp ("publish-context-dir", event->value.publish.cctx)) - { - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (3 == event->value.publish.anonymity); + (start).rel_value_us) / 1024)); + if (0 == strcmp("publish-context-dir", event->value.publish.cctx)) + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + ret = event->value.publish.cctx; + GNUNET_assert(publish == event->value.publish.pc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publish is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.publish.completed, + (unsigned long long)event->value.publish.size, + event->value.publish.specifics.progress.depth, + (unsigned long long)event->value.publish.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + ret = event->value.publish.cctx; + break; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + ret = event->value.publish.cctx; + fprintf(stderr, "Error publishing file: %s\n", + event->value.publish.specifics.error.message); + err = 1; + if (0 == strcmp("publish-context-dir", event->value.publish.cctx)) + { + fprintf(stderr, "Scheduling abort task for error on `%s'\n", + (const char *)event->value.publish.cctx); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + } + break; + + case GNUNET_FS_STATUS_PUBLISH_START: + ret = event->value.publish.cctx; + if (0 == strcmp("publish-context1", event->value.publish.cctx)) + { + GNUNET_assert(0 == + strcmp("publish-context-dir", event->value.publish.pctx)); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(1 == event->value.publish.anonymity); + } + else if (0 == strcmp("publish-context2", event->value.publish.cctx)) + { + GNUNET_assert(0 == + strcmp("publish-context-dir", event->value.publish.pctx)); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(2 == event->value.publish.anonymity); + } + else if (0 == strcmp("publish-context-dir", event->value.publish.cctx)) + { + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(3 == event->value.publish.anonymity); + } + else + GNUNET_assert(0); + break; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + if (0 == strcmp("publish-context-dir", event->value.publish.cctx)) + GNUNET_assert(publish == event->value.publish.pc); + break; + + default: + printf("Unexpected event: %d\n", event->status); + break; } - else - GNUNET_assert (0); - break; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - if (0 == strcmp ("publish-context-dir", event->value.publish.cctx)) - GNUNET_assert (publish == event->value.publish.pc); - break; - default: - printf ("Unexpected event: %d\n", event->status); - break; - } return ret; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { const char *keywords[] = { "down_foo", @@ -171,70 +177,70 @@ run (void *cls, size_t i; struct GNUNET_FS_BlockOptions bo; - fs = GNUNET_FS_start (cfg, "test-fs-publish", &progress_cb, NULL, - GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); - GNUNET_assert (NULL != fs); - fn1 = GNUNET_DISK_mktemp ("gnunet-publish-test-dst"); - buf = GNUNET_malloc (FILESIZE); + fs = GNUNET_FS_start(cfg, "test-fs-publish", &progress_cb, NULL, + GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); + GNUNET_assert(NULL != fs); + fn1 = GNUNET_DISK_mktemp("gnunet-publish-test-dst"); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - GNUNET_assert (FILESIZE == - GNUNET_DISK_fn_write (fn1, buf, FILESIZE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)); - GNUNET_free (buf); - - fn2 = GNUNET_DISK_mktemp ("gnunet-publish-test-dst"); - buf = GNUNET_malloc (FILESIZE); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + GNUNET_assert(FILESIZE == + GNUNET_DISK_fn_write(fn1, buf, FILESIZE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)); + GNUNET_free(buf); + + fn2 = GNUNET_DISK_mktemp("gnunet-publish-test-dst"); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - GNUNET_assert (FILESIZE == - GNUNET_DISK_fn_write (fn2, buf, FILESIZE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)); - GNUNET_free (buf); - - meta = GNUNET_CONTAINER_meta_data_create (); - kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + GNUNET_assert(FILESIZE == + GNUNET_DISK_fn_write(fn2, buf, FILESIZE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)); + GNUNET_free(buf); + + meta = GNUNET_CONTAINER_meta_data_create(); + kuri = GNUNET_FS_uri_ksk_create_from_args(2, keywords); bo.content_priority = 42; bo.anonymity_level = 1; bo.replication_level = 0; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME); + bo.expiration_time = GNUNET_TIME_relative_to_absolute(LIFETIME); fi1 = - GNUNET_FS_file_information_create_from_file (fs, "publish-context1", fn1, - kuri, meta, GNUNET_YES, &bo); + GNUNET_FS_file_information_create_from_file(fs, "publish-context1", fn1, + kuri, meta, GNUNET_YES, &bo); - GNUNET_assert (NULL != fi1); + GNUNET_assert(NULL != fi1); bo.anonymity_level = 2; fi2 = - GNUNET_FS_file_information_create_from_file (fs, "publish-context2", fn2, - kuri, meta, GNUNET_YES, &bo); - GNUNET_assert (NULL != fi2); + GNUNET_FS_file_information_create_from_file(fs, "publish-context2", fn2, + kuri, meta, GNUNET_YES, &bo); + GNUNET_assert(NULL != fi2); bo.anonymity_level = 3; fidir = - GNUNET_FS_file_information_create_empty_directory (fs, - "publish-context-dir", - kuri, meta, &bo, NULL); - GNUNET_assert (GNUNET_OK == GNUNET_FS_file_information_add (fidir, fi1)); - GNUNET_assert (GNUNET_OK == GNUNET_FS_file_information_add (fidir, fi2)); - GNUNET_FS_uri_destroy (kuri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_assert (NULL != fidir); - start = GNUNET_TIME_absolute_get (); + GNUNET_FS_file_information_create_empty_directory(fs, + "publish-context-dir", + kuri, meta, &bo, NULL); + GNUNET_assert(GNUNET_OK == GNUNET_FS_file_information_add(fidir, fi1)); + GNUNET_assert(GNUNET_OK == GNUNET_FS_file_information_add(fidir, fi2)); + GNUNET_FS_uri_destroy(kuri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_assert(NULL != fidir); + start = GNUNET_TIME_absolute_get(); publish = - GNUNET_FS_publish_start (fs, fidir, NULL, NULL, NULL, - GNUNET_FS_PUBLISH_OPTION_NONE); - GNUNET_assert (publish != NULL); + GNUNET_FS_publish_start(fs, fidir, NULL, NULL, NULL, + GNUNET_FS_PUBLISH_OPTION_NONE); + GNUNET_assert(publish != NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-publish", - "test_fs_publish_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-publish", + "test_fs_publish_data.conf", + &run, NULL)) return 1; return err; } diff --git a/src/fs/test_fs_publish_persistence.c b/src/fs/test_fs_publish_persistence.c index 6242e66f8..7cba55179 100644 --- a/src/fs/test_fs_publish_persistence.c +++ b/src/fs/test_fs_publish_persistence.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_publish_persistence.c * @brief simple testcase for persistence of simple publish operation @@ -36,12 +36,12 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** * How long should our test-content live? */ -#define LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) static struct GNUNET_TIME_Absolute start; @@ -64,39 +64,39 @@ static struct GNUNET_SCHEDULER_Task *rtask; static void -abort_publish_task (void *cls) +abort_publish_task(void *cls) { - GNUNET_FS_publish_stop (publish); + GNUNET_FS_publish_stop(publish); publish = NULL; - GNUNET_DISK_directory_remove (fn1); - GNUNET_free (fn1); + GNUNET_DISK_directory_remove(fn1); + GNUNET_free(fn1); fn1 = NULL; - GNUNET_DISK_directory_remove (fn2); - GNUNET_free (fn2); + GNUNET_DISK_directory_remove(fn2); + GNUNET_free(fn2); fn2 = NULL; - GNUNET_FS_stop (fs); + GNUNET_FS_stop(fs); fs = NULL; if (NULL != rtask) - { - GNUNET_SCHEDULER_cancel (rtask); - rtask = NULL; - } + { + GNUNET_SCHEDULER_cancel(rtask); + rtask = NULL; + } } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event); +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event); static void -restart_fs_task (void *cls) +restart_fs_task(void *cls) { rtask = NULL; - GNUNET_FS_stop (fs); - fs = GNUNET_FS_start (cfg, "test-fs-publish-persistence", - &progress_cb, NULL, - GNUNET_FS_FLAGS_PERSISTENCE, - GNUNET_FS_OPTIONS_END); + GNUNET_FS_stop(fs); + fs = GNUNET_FS_start(cfg, "test-fs-publish-persistence", + &progress_cb, NULL, + GNUNET_FS_FLAGS_PERSISTENCE, + GNUNET_FS_OPTIONS_END); } @@ -108,7 +108,7 @@ restart_fs_task (void *cls) * @param ev type of the event to consider */ static void -consider_restart (int ev) +consider_restart(int ev) { static int prev[32]; static int off; @@ -119,115 +119,123 @@ consider_restart (int ev) return; prev[off++] = ev; rtask = - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_URGENT, - &restart_fs_task, NULL); + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_URGENT, + &restart_fs_task, NULL); } static void * -progress_cb (void *cls, - const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, + const struct GNUNET_FS_ProgressInfo *event) { void *ret; ret = NULL; switch (event->status) - { - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - ret = event->value.publish.cctx; - printf ("Publish complete, %llu kbps.\n", - (unsigned long long) (FILESIZE * 1000000LL / + { + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + ret = event->value.publish.cctx; + printf("Publish complete, %llu kbps.\n", + (unsigned long long)(FILESIZE * 1000000LL / (1 + GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024)); - if ( (NULL != event->value.publish.cctx) && - (0 == strcmp ("publish-context-dir", event->value.publish.cctx)) ) - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - ret = event->value.publish.cctx; - return ret; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - consider_restart (event->status); - ret = event->value.publish.cctx; - GNUNET_assert (publish == event->value.publish.pc); + (start).rel_value_us) / 1024)); + if ((NULL != event->value.publish.cctx) && + (0 == strcmp("publish-context-dir", event->value.publish.cctx))) + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + ret = event->value.publish.cctx; + return ret; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + consider_restart(event->status); + ret = event->value.publish.cctx; + GNUNET_assert(publish == event->value.publish.pc); #if VERBOSE - printf ("Publish is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.publish.completed, - (unsigned long long) event->value.publish.size, - event->value.publish.specifics.progress.depth, - (unsigned long long) event->value.publish.specifics. - progress.offset); + printf("Publish is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.publish.completed, + (unsigned long long)event->value.publish.size, + event->value.publish.specifics.progress.depth, + (unsigned long long)event->value.publish.specifics. + progress.offset); #endif - break; - case GNUNET_FS_STATUS_PUBLISH_SUSPEND: - if (event->value.publish.pc == publish) - publish = NULL; - break; - case GNUNET_FS_STATUS_PUBLISH_RESUME: - if (NULL == publish) - { - GNUNET_assert (GNUNET_YES == - GNUNET_FS_file_information_is_directory (event-> - value.publish. - fi)); + break; + + case GNUNET_FS_STATUS_PUBLISH_SUSPEND: + if (event->value.publish.pc == publish) + publish = NULL; + break; + + case GNUNET_FS_STATUS_PUBLISH_RESUME: + if (NULL == publish) + { + GNUNET_assert(GNUNET_YES == + GNUNET_FS_file_information_is_directory(event-> + value.publish. + fi)); + publish = event->value.publish.pc; + return "publish-context-dir"; + } + break; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + ret = event->value.publish.cctx; + fprintf(stderr, "Error publishing file: %s\n", + event->value.publish.specifics.error.message); + err = 1; + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_START: + consider_restart(event->status); publish = event->value.publish.pc; - return "publish-context-dir"; - } - break; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - ret = event->value.publish.cctx; - fprintf (stderr, "Error publishing file: %s\n", - event->value.publish.specifics.error.message); - err = 1; - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_START: - consider_restart (event->status); - publish = event->value.publish.pc; - ret = event->value.publish.cctx; - if (0 == strcmp ("publish-context1", event->value.publish.cctx)) - { - GNUNET_assert (0 == - strcmp ("publish-context-dir", event->value.publish.pctx)); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (1 == event->value.publish.anonymity); - } - else if (0 == strcmp ("publish-context2", event->value.publish.cctx)) - { - GNUNET_assert (0 == - strcmp ("publish-context-dir", event->value.publish.pctx)); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (2 == event->value.publish.anonymity); - } - else if (0 == strcmp ("publish-context-dir", event->value.publish.cctx)) - { - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (3 == event->value.publish.anonymity); + ret = event->value.publish.cctx; + if (0 == strcmp("publish-context1", event->value.publish.cctx)) + { + GNUNET_assert(0 == + strcmp("publish-context-dir", event->value.publish.pctx)); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(1 == event->value.publish.anonymity); + } + else if (0 == strcmp("publish-context2", event->value.publish.cctx)) + { + GNUNET_assert(0 == + strcmp("publish-context-dir", event->value.publish.pctx)); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(2 == event->value.publish.anonymity); + } + else if (0 == strcmp("publish-context-dir", event->value.publish.cctx)) + { + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(3 == event->value.publish.anonymity); + } + else + GNUNET_assert(0); + break; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + consider_restart(event->status); + if ((NULL != event->value.publish.cctx) && + (0 == strcmp("publish-context-dir", event->value.publish.cctx))) + GNUNET_assert(publish == event->value.publish.pc); + break; + + default: + printf("Unexpected event: %d\n", event->status); + break; } - else - GNUNET_assert (0); - break; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - consider_restart (event->status); - if ( (NULL != event->value.publish.cctx) && - (0 == strcmp ("publish-context-dir", event->value.publish.cctx)) ) - GNUNET_assert (publish == event->value.publish.pc); - break; - default: - printf ("Unexpected event: %d\n", event->status); - break; - } return ret; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_TESTING_Peer *peer) { const char *keywords[] = { "down_foo", @@ -243,67 +251,67 @@ run (void *cls, struct GNUNET_FS_BlockOptions bo; cfg = c; - fs = GNUNET_FS_start (cfg, "test-fs-publish-persistence", &progress_cb, NULL, - GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); - GNUNET_assert (NULL != fs); - fn1 = GNUNET_DISK_mktemp ("gnunet-publish-test-dst"); - buf = GNUNET_malloc (FILESIZE); + fs = GNUNET_FS_start(cfg, "test-fs-publish-persistence", &progress_cb, NULL, + GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); + GNUNET_assert(NULL != fs); + fn1 = GNUNET_DISK_mktemp("gnunet-publish-test-dst"); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - GNUNET_assert (FILESIZE == - GNUNET_DISK_fn_write (fn1, buf, FILESIZE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)); - GNUNET_free (buf); - - fn2 = GNUNET_DISK_mktemp ("gnunet-publish-test-dst"); - buf = GNUNET_malloc (FILESIZE); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + GNUNET_assert(FILESIZE == + GNUNET_DISK_fn_write(fn1, buf, FILESIZE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)); + GNUNET_free(buf); + + fn2 = GNUNET_DISK_mktemp("gnunet-publish-test-dst"); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - GNUNET_assert (FILESIZE == - GNUNET_DISK_fn_write (fn2, buf, FILESIZE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)); - GNUNET_free (buf); - - meta = GNUNET_CONTAINER_meta_data_create (); - kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + GNUNET_assert(FILESIZE == + GNUNET_DISK_fn_write(fn2, buf, FILESIZE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)); + GNUNET_free(buf); + + meta = GNUNET_CONTAINER_meta_data_create(); + kuri = GNUNET_FS_uri_ksk_create_from_args(2, keywords); bo.content_priority = 42; bo.anonymity_level = 1; bo.replication_level = 0; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME); + bo.expiration_time = GNUNET_TIME_relative_to_absolute(LIFETIME); fi1 = - GNUNET_FS_file_information_create_from_file (fs, "publish-context1", fn1, - kuri, meta, GNUNET_YES, &bo); - GNUNET_assert (NULL != fi1); + GNUNET_FS_file_information_create_from_file(fs, "publish-context1", fn1, + kuri, meta, GNUNET_YES, &bo); + GNUNET_assert(NULL != fi1); bo.anonymity_level = 2; fi2 = - GNUNET_FS_file_information_create_from_file (fs, "publish-context2", fn2, - kuri, meta, GNUNET_YES, &bo); - GNUNET_assert (NULL != fi2); + GNUNET_FS_file_information_create_from_file(fs, "publish-context2", fn2, + kuri, meta, GNUNET_YES, &bo); + GNUNET_assert(NULL != fi2); bo.anonymity_level = 3; fidir = - GNUNET_FS_file_information_create_empty_directory (fs, - "publish-context-dir", - kuri, meta, &bo, NULL); - GNUNET_assert (GNUNET_OK == GNUNET_FS_file_information_add (fidir, fi1)); - GNUNET_assert (GNUNET_OK == GNUNET_FS_file_information_add (fidir, fi2)); - GNUNET_FS_uri_destroy (kuri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_assert (NULL != fidir); - start = GNUNET_TIME_absolute_get (); - GNUNET_FS_publish_start (fs, fidir, NULL, NULL, NULL, - GNUNET_FS_PUBLISH_OPTION_NONE); - GNUNET_assert (publish != NULL); + GNUNET_FS_file_information_create_empty_directory(fs, + "publish-context-dir", + kuri, meta, &bo, NULL); + GNUNET_assert(GNUNET_OK == GNUNET_FS_file_information_add(fidir, fi1)); + GNUNET_assert(GNUNET_OK == GNUNET_FS_file_information_add(fidir, fi2)); + GNUNET_FS_uri_destroy(kuri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_assert(NULL != fidir); + start = GNUNET_TIME_absolute_get(); + GNUNET_FS_publish_start(fs, fidir, NULL, NULL, NULL, + GNUNET_FS_PUBLISH_OPTION_NONE); + GNUNET_assert(publish != NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-publish-persistence", - "test_fs_publish_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-publish-persistence", + "test_fs_publish_data.conf", + &run, NULL)) return 1; return err; } diff --git a/src/fs/test_fs_search.c b/src/fs/test_fs_search.c index 2a7f4b1dd..7906a4163 100644 --- a/src/fs/test_fs_search.c +++ b/src/fs/test_fs_search.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_search.c * @brief simple testcase for simple publish + search operation @@ -36,12 +36,12 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** * How long should our test-content live? */ -#define LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) static struct GNUNET_TIME_Absolute start; @@ -58,54 +58,54 @@ static int err; static void -abort_publish_task (void *cls) +abort_publish_task(void *cls) { if (NULL != publish) - { - GNUNET_FS_publish_stop (publish); - publish = NULL; - } + { + GNUNET_FS_publish_stop(publish); + publish = NULL; + } if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } } static void -abort_error (void *cls) +abort_error(void *cls) { - fprintf (stderr, - "Timeout\n"); + fprintf(stderr, + "Timeout\n"); timeout_task = NULL; if (NULL != search) - { - GNUNET_FS_search_stop (search); - search = NULL; - } + { + GNUNET_FS_search_stop(search); + search = NULL; + } if (NULL != publish) - { - GNUNET_FS_publish_stop (publish); - publish = NULL; - } + { + GNUNET_FS_publish_stop(publish); + publish = NULL; + } err = 1; } static void -abort_search_task (void *cls) +abort_search_task(void *cls) { if (NULL != search) - { - GNUNET_FS_search_stop (search); - search = NULL; - } + { + GNUNET_FS_search_stop(search); + search = NULL; + } } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { const char *keywords[] = { "down_foo" @@ -113,80 +113,91 @@ progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) struct GNUNET_FS_Uri *kuri; switch (event->status) - { - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publish is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.publish.completed, - (unsigned long long) event->value.publish.size, - event->value.publish.specifics.progress.depth, - (unsigned long long) event->value.publish.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - break; - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - kuri = GNUNET_FS_uri_ksk_create_from_args (1, keywords); - start = GNUNET_TIME_absolute_get (); - search = - GNUNET_FS_search_start (fs, kuri, 1, GNUNET_FS_SEARCH_OPTION_NONE, - "search"); - GNUNET_FS_uri_destroy (kuri); - GNUNET_assert (search != NULL); - break; - case GNUNET_FS_STATUS_SEARCH_RESULT: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Search complete.\n"); - GNUNET_SCHEDULER_add_now (&abort_search_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - fprintf (stderr, "Error publishing file: %s\n", - event->value.publish.specifics.error.message); - GNUNET_break (0); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - case GNUNET_FS_STATUS_SEARCH_ERROR: - fprintf (stderr, "Error searching file: %s\n", - event->value.search.specifics.error.message); - GNUNET_SCHEDULER_add_now (&abort_search_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_START: - GNUNET_assert (0 == strcmp ("publish-context", event->value.publish.cctx)); - GNUNET_assert (NULL == event->value.publish.pctx); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (1 == event->value.publish.anonymity); - break; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - GNUNET_assert (publish == event->value.publish.pc); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (1 == event->value.publish.anonymity); - GNUNET_FS_stop (fs); - fs = NULL; - break; - case GNUNET_FS_STATUS_SEARCH_START: - GNUNET_assert (search == NULL); - GNUNET_assert (0 == strcmp ("search", event->value.search.cctx)); - GNUNET_assert (1 == event->value.search.anonymity); - break; - case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: - break; - case GNUNET_FS_STATUS_SEARCH_STOPPED: - GNUNET_assert (search == event->value.search.sc); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - default: - fprintf (stderr, "Unexpected event: %d\n", event->status); - break; - } + { + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publish is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.publish.completed, + (unsigned long long)event->value.publish.size, + event->value.publish.specifics.progress.depth, + (unsigned long long)event->value.publish.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + break; + + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + kuri = GNUNET_FS_uri_ksk_create_from_args(1, keywords); + start = GNUNET_TIME_absolute_get(); + search = + GNUNET_FS_search_start(fs, kuri, 1, GNUNET_FS_SEARCH_OPTION_NONE, + "search"); + GNUNET_FS_uri_destroy(kuri); + GNUNET_assert(search != NULL); + break; + + case GNUNET_FS_STATUS_SEARCH_RESULT: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Search complete.\n"); + GNUNET_SCHEDULER_add_now(&abort_search_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + fprintf(stderr, "Error publishing file: %s\n", + event->value.publish.specifics.error.message); + GNUNET_break(0); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + case GNUNET_FS_STATUS_SEARCH_ERROR: + fprintf(stderr, "Error searching file: %s\n", + event->value.search.specifics.error.message); + GNUNET_SCHEDULER_add_now(&abort_search_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_START: + GNUNET_assert(0 == strcmp("publish-context", event->value.publish.cctx)); + GNUNET_assert(NULL == event->value.publish.pctx); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(1 == event->value.publish.anonymity); + break; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + GNUNET_assert(publish == event->value.publish.pc); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(1 == event->value.publish.anonymity); + GNUNET_FS_stop(fs); + fs = NULL; + break; + + case GNUNET_FS_STATUS_SEARCH_START: + GNUNET_assert(search == NULL); + GNUNET_assert(0 == strcmp("search", event->value.search.cctx)); + GNUNET_assert(1 == event->value.search.anonymity); + break; + + case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: + break; + + case GNUNET_FS_STATUS_SEARCH_STOPPED: + GNUNET_assert(search == event->value.search.sc); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + default: + fprintf(stderr, "Unexpected event: %d\n", event->status); + break; + } return NULL; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { const char *keywords[] = { "down_foo", @@ -199,40 +210,40 @@ run (void *cls, struct GNUNET_FS_FileInformation *fi; size_t i; - fs = GNUNET_FS_start (cfg, "test-fs-search", &progress_cb, NULL, - GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); - GNUNET_assert (NULL != fs); - buf = GNUNET_malloc (FILESIZE); + fs = GNUNET_FS_start(cfg, "test-fs-search", &progress_cb, NULL, + GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); + GNUNET_assert(NULL != fs); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - meta = GNUNET_CONTAINER_meta_data_create (); - kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + meta = GNUNET_CONTAINER_meta_data_create(); + kuri = GNUNET_FS_uri_ksk_create_from_args(2, keywords); bo.content_priority = 42; bo.anonymity_level = 1; bo.replication_level = 0; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME); - fi = GNUNET_FS_file_information_create_from_data (fs, "publish-context", - FILESIZE, buf, kuri, meta, - GNUNET_NO, &bo); - GNUNET_FS_uri_destroy (kuri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_assert (NULL != fi); - start = GNUNET_TIME_absolute_get (); + bo.expiration_time = GNUNET_TIME_relative_to_absolute(LIFETIME); + fi = GNUNET_FS_file_information_create_from_data(fs, "publish-context", + FILESIZE, buf, kuri, meta, + GNUNET_NO, &bo); + GNUNET_FS_uri_destroy(kuri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_assert(NULL != fi); + start = GNUNET_TIME_absolute_get(); publish = - GNUNET_FS_publish_start (fs, fi, NULL, NULL, NULL, - GNUNET_FS_PUBLISH_OPTION_NONE); - GNUNET_assert (publish != NULL); - timeout_task = GNUNET_SCHEDULER_add_delayed (LIFETIME, - &abort_error, NULL); + GNUNET_FS_publish_start(fs, fi, NULL, NULL, NULL, + GNUNET_FS_PUBLISH_OPTION_NONE); + GNUNET_assert(publish != NULL); + timeout_task = GNUNET_SCHEDULER_add_delayed(LIFETIME, + &abort_error, NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-search", - "test_fs_search_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-search", + "test_fs_search_data.conf", + &run, NULL)) return 1; return err; } diff --git a/src/fs/test_fs_search_persistence.c b/src/fs/test_fs_search_persistence.c index 68e3a4a62..b01abe75f 100644 --- a/src/fs/test_fs_search_persistence.c +++ b/src/fs/test_fs_search_persistence.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_search_persistence.c * @brief simple testcase for persistence of search operation @@ -36,12 +36,12 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** * How long should our test-content live? */ -#define LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) static struct GNUNET_TIME_Absolute start; @@ -60,62 +60,62 @@ static int err; static void -abort_error (void *cls) +abort_error(void *cls) { timeout_task = NULL; - fprintf (stderr, - "Timeout\n"); + fprintf(stderr, + "Timeout\n"); if (NULL != search) - { - GNUNET_FS_search_stop (search); - search = NULL; - } + { + GNUNET_FS_search_stop(search); + search = NULL; + } if (NULL != publish) - { - GNUNET_FS_publish_stop (publish); - publish = NULL; - } + { + GNUNET_FS_publish_stop(publish); + publish = NULL; + } err = 1; } static void -abort_publish_task (void *cls) +abort_publish_task(void *cls) { if (NULL != publish) - { - GNUNET_FS_publish_stop (publish); - publish = NULL; - } + { + GNUNET_FS_publish_stop(publish); + publish = NULL; + } if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } } static void -abort_search_task (void *cls) +abort_search_task(void *cls) { if (NULL != search) - { - GNUNET_FS_search_stop (search); - search = NULL; - } + { + GNUNET_FS_search_stop(search); + search = NULL; + } } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event); +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event); static void -restart_fs_task (void *cls) +restart_fs_task(void *cls) { - GNUNET_FS_stop (fs); - fs = GNUNET_FS_start (cfg, "test-fs-search-persistence", &progress_cb, NULL, - GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); + GNUNET_FS_stop(fs); + fs = GNUNET_FS_start(cfg, "test-fs-search-persistence", &progress_cb, NULL, + GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); } @@ -127,7 +127,7 @@ restart_fs_task (void *cls) * @param ev type of the event to consider */ static void -consider_restart (int ev) +consider_restart(int ev) { static int prev[32]; static int off; @@ -137,13 +137,13 @@ consider_restart (int ev) if (prev[i] == ev) return; prev[off++] = ev; - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_URGENT, - &restart_fs_task, NULL); + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_URGENT, + &restart_fs_task, NULL); } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { const char *keywords[] = { "down_foo" @@ -151,103 +151,118 @@ progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) struct GNUNET_FS_Uri *kuri; switch (event->status) - { - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publish is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.publish.completed, - (unsigned long long) event->value.publish.size, - event->value.publish.specifics.progress.depth, - (unsigned long long) event->value.publish.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - break; - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - kuri = GNUNET_FS_uri_ksk_create_from_args (1, keywords); - start = GNUNET_TIME_absolute_get (); - GNUNET_FS_search_start (fs, kuri, 1, GNUNET_FS_SEARCH_OPTION_NONE, - "search"); - GNUNET_FS_uri_destroy (kuri); - GNUNET_assert (search != NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_SUSPEND: - if (event->value.publish.pc == publish) - publish = NULL; - break; - case GNUNET_FS_STATUS_PUBLISH_RESUME: - if (NULL == publish) - publish = event->value.publish.pc; - break; - case GNUNET_FS_STATUS_SEARCH_RESULT: - /* FIXME: consider_restart (event->status); cannot be tested with - * search result since we exit here after the first one... */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Search complete.\n"); - GNUNET_SCHEDULER_add_now (&abort_search_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - fprintf (stderr, "Error publishing file: %s\n", - event->value.publish.specifics.error.message); - GNUNET_break (0); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - case GNUNET_FS_STATUS_SEARCH_ERROR: - fprintf (stderr, "Error searching file: %s\n", - event->value.search.specifics.error.message); - GNUNET_SCHEDULER_add_now (&abort_search_task, NULL); - break; - case GNUNET_FS_STATUS_SEARCH_SUSPEND: - if (event->value.search.sc == search) - search = NULL; - break; - case GNUNET_FS_STATUS_SEARCH_RESUME: - if (NULL == search) { + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publish is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.publish.completed, + (unsigned long long)event->value.publish.size, + event->value.publish.specifics.progress.depth, + (unsigned long long)event->value.publish.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + break; + + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + kuri = GNUNET_FS_uri_ksk_create_from_args(1, keywords); + start = GNUNET_TIME_absolute_get(); + GNUNET_FS_search_start(fs, kuri, 1, GNUNET_FS_SEARCH_OPTION_NONE, + "search"); + GNUNET_FS_uri_destroy(kuri); + GNUNET_assert(search != NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_SUSPEND: + if (event->value.publish.pc == publish) + publish = NULL; + break; + + case GNUNET_FS_STATUS_PUBLISH_RESUME: + if (NULL == publish) + publish = event->value.publish.pc; + break; + + case GNUNET_FS_STATUS_SEARCH_RESULT: + /* FIXME: consider_restart (event->status); cannot be tested with + * search result since we exit here after the first one... */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Search complete.\n"); + GNUNET_SCHEDULER_add_now(&abort_search_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + fprintf(stderr, "Error publishing file: %s\n", + event->value.publish.specifics.error.message); + GNUNET_break(0); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + case GNUNET_FS_STATUS_SEARCH_ERROR: + fprintf(stderr, "Error searching file: %s\n", + event->value.search.specifics.error.message); + GNUNET_SCHEDULER_add_now(&abort_search_task, NULL); + break; + + case GNUNET_FS_STATUS_SEARCH_SUSPEND: + if (event->value.search.sc == search) + search = NULL; + break; + + case GNUNET_FS_STATUS_SEARCH_RESUME: + if (NULL == search) + { + search = event->value.search.sc; + return "search"; + } + break; + + case GNUNET_FS_STATUS_PUBLISH_START: + GNUNET_assert(0 == strcmp("publish-context", event->value.publish.cctx)); + GNUNET_assert(NULL == event->value.publish.pctx); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(1 == event->value.publish.anonymity); + break; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + GNUNET_assert(publish == event->value.publish.pc); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(1 == event->value.publish.anonymity); + GNUNET_FS_stop(fs); + fs = NULL; + break; + + case GNUNET_FS_STATUS_SEARCH_START: + consider_restart(event->status); + GNUNET_assert(search == NULL); search = event->value.search.sc; - return "search"; + GNUNET_assert(0 == strcmp("search", event->value.search.cctx)); + GNUNET_assert(1 == event->value.search.anonymity); + break; + + case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: + break; + + case GNUNET_FS_STATUS_SEARCH_STOPPED: + GNUNET_assert(search == event->value.search.sc); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + search = NULL; + break; + + default: + fprintf(stderr, "Unexpected event: %d\n", event->status); + break; } - break; - case GNUNET_FS_STATUS_PUBLISH_START: - GNUNET_assert (0 == strcmp ("publish-context", event->value.publish.cctx)); - GNUNET_assert (NULL == event->value.publish.pctx); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (1 == event->value.publish.anonymity); - break; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - GNUNET_assert (publish == event->value.publish.pc); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (1 == event->value.publish.anonymity); - GNUNET_FS_stop (fs); - fs = NULL; - break; - case GNUNET_FS_STATUS_SEARCH_START: - consider_restart (event->status); - GNUNET_assert (search == NULL); - search = event->value.search.sc; - GNUNET_assert (0 == strcmp ("search", event->value.search.cctx)); - GNUNET_assert (1 == event->value.search.anonymity); - break; - case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: - break; - case GNUNET_FS_STATUS_SEARCH_STOPPED: - GNUNET_assert (search == event->value.search.sc); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - search = NULL; - break; - default: - fprintf (stderr, "Unexpected event: %d\n", event->status); - break; - } return NULL; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_TESTING_Peer *peer) { const char *keywords[] = { "down_foo", @@ -261,40 +276,40 @@ run (void *cls, struct GNUNET_FS_BlockOptions bo; cfg = c; - fs = GNUNET_FS_start (cfg, "test-fs-search-persistence", &progress_cb, NULL, - GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); - GNUNET_assert (NULL != fs); - buf = GNUNET_malloc (FILESIZE); + fs = GNUNET_FS_start(cfg, "test-fs-search-persistence", &progress_cb, NULL, + GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); + GNUNET_assert(NULL != fs); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - meta = GNUNET_CONTAINER_meta_data_create (); - kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + meta = GNUNET_CONTAINER_meta_data_create(); + kuri = GNUNET_FS_uri_ksk_create_from_args(2, keywords); bo.content_priority = 42; bo.anonymity_level = 1; bo.replication_level = 0; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME); - fi = GNUNET_FS_file_information_create_from_data (fs, "publish-context", - FILESIZE, buf, kuri, meta, - GNUNET_NO, &bo); - GNUNET_FS_uri_destroy (kuri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_assert (NULL != fi); - start = GNUNET_TIME_absolute_get (); + bo.expiration_time = GNUNET_TIME_relative_to_absolute(LIFETIME); + fi = GNUNET_FS_file_information_create_from_data(fs, "publish-context", + FILESIZE, buf, kuri, meta, + GNUNET_NO, &bo); + GNUNET_FS_uri_destroy(kuri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_assert(NULL != fi); + start = GNUNET_TIME_absolute_get(); publish = - GNUNET_FS_publish_start (fs, fi, NULL, NULL, NULL, - GNUNET_FS_PUBLISH_OPTION_NONE); - GNUNET_assert (publish != NULL); - timeout_task = GNUNET_SCHEDULER_add_delayed (LIFETIME, - &abort_error, NULL); + GNUNET_FS_publish_start(fs, fi, NULL, NULL, NULL, + GNUNET_FS_PUBLISH_OPTION_NONE); + GNUNET_assert(publish != NULL); + timeout_task = GNUNET_SCHEDULER_add_delayed(LIFETIME, + &abort_error, NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-search-persistence", - "test_fs_search_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-search-persistence", + "test_fs_search_data.conf", + &run, NULL)) return 1; return err; } diff --git a/src/fs/test_fs_search_probes.c b/src/fs/test_fs_search_probes.c index c65649108..5584efca7 100644 --- a/src/fs/test_fs_search_probes.c +++ b/src/fs/test_fs_search_probes.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_search_probes.c @@ -37,12 +37,12 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** * How long should our test-content live? */ -#define LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) static struct GNUNET_TIME_Absolute start; @@ -59,52 +59,52 @@ static int err; static void -abort_error (void *cls) +abort_error(void *cls) { timeout_task = NULL; - fprintf (stderr, - "Timeout\n"); + fprintf(stderr, + "Timeout\n"); if (NULL != search) - { - GNUNET_FS_search_stop (search); - search = NULL; - } + { + GNUNET_FS_search_stop(search); + search = NULL; + } if (NULL != publish) - { - GNUNET_FS_publish_stop (publish); - publish = NULL; - } + { + GNUNET_FS_publish_stop(publish); + publish = NULL; + } err = 1; } static void -abort_publish_task (void *cls) +abort_publish_task(void *cls) { if (NULL != publish) - { - GNUNET_FS_publish_stop (publish); - publish = NULL; - } + { + GNUNET_FS_publish_stop(publish); + publish = NULL; + } if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } } static void -abort_search_task (void *cls) +abort_search_task(void *cls) { if (search != NULL) - GNUNET_FS_search_stop (search); + GNUNET_FS_search_stop(search); search = NULL; } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { const char *keywords[] = { "down_foo" @@ -112,85 +112,97 @@ progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) struct GNUNET_FS_Uri *kuri; switch (event->status) - { - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publish is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.publish.completed, - (unsigned long long) event->value.publish.size, - event->value.publish.specifics.progress.depth, - (unsigned long long) event->value.publish.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - break; - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - kuri = GNUNET_FS_uri_ksk_create_from_args (1, keywords); - start = GNUNET_TIME_absolute_get (); - search = - GNUNET_FS_search_start (fs, kuri, 1, GNUNET_FS_SEARCH_OPTION_NONE, - "search"); - GNUNET_FS_uri_destroy (kuri); - GNUNET_assert (search != NULL); - break; - case GNUNET_FS_STATUS_SEARCH_RESULT: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Search complete.\n"); - break; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - fprintf (stderr, "Error publishing file: %s\n", - event->value.publish.specifics.error.message); - GNUNET_break (0); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - case GNUNET_FS_STATUS_SEARCH_ERROR: - fprintf (stderr, "Error searching file: %s\n", - event->value.search.specifics.error.message); - GNUNET_SCHEDULER_add_now (&abort_search_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_START: - GNUNET_assert (0 == strcmp ("publish-context", event->value.publish.cctx)); - GNUNET_assert (NULL == event->value.publish.pctx); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (1 == event->value.publish.anonymity); - break; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - GNUNET_assert (publish == event->value.publish.pc); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (1 == event->value.publish.anonymity); - GNUNET_FS_stop (fs); - fs = NULL; - break; - case GNUNET_FS_STATUS_SEARCH_UPDATE: - if ( (0 < event->value.search.specifics.update.availability_rank) && - (0 < event->value.search.specifics.update.availability_certainty) ) - GNUNET_SCHEDULER_add_now (&abort_search_task, NULL); - break; - case GNUNET_FS_STATUS_SEARCH_START: - GNUNET_assert (search == NULL); - GNUNET_assert (0 == strcmp ("search", event->value.search.cctx)); - GNUNET_assert (1 == event->value.search.anonymity); - break; - case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: - break; - case GNUNET_FS_STATUS_SEARCH_STOPPED: - GNUNET_assert (search == event->value.search.sc); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - default: - fprintf (stderr, - "Unexpected event: %d\n", - event->status); - break; - } + { + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publish is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.publish.completed, + (unsigned long long)event->value.publish.size, + event->value.publish.specifics.progress.depth, + (unsigned long long)event->value.publish.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + break; + + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + kuri = GNUNET_FS_uri_ksk_create_from_args(1, keywords); + start = GNUNET_TIME_absolute_get(); + search = + GNUNET_FS_search_start(fs, kuri, 1, GNUNET_FS_SEARCH_OPTION_NONE, + "search"); + GNUNET_FS_uri_destroy(kuri); + GNUNET_assert(search != NULL); + break; + + case GNUNET_FS_STATUS_SEARCH_RESULT: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Search complete.\n"); + break; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + fprintf(stderr, "Error publishing file: %s\n", + event->value.publish.specifics.error.message); + GNUNET_break(0); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + case GNUNET_FS_STATUS_SEARCH_ERROR: + fprintf(stderr, "Error searching file: %s\n", + event->value.search.specifics.error.message); + GNUNET_SCHEDULER_add_now(&abort_search_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_START: + GNUNET_assert(0 == strcmp("publish-context", event->value.publish.cctx)); + GNUNET_assert(NULL == event->value.publish.pctx); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(1 == event->value.publish.anonymity); + break; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + GNUNET_assert(publish == event->value.publish.pc); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(1 == event->value.publish.anonymity); + GNUNET_FS_stop(fs); + fs = NULL; + break; + + case GNUNET_FS_STATUS_SEARCH_UPDATE: + if ((0 < event->value.search.specifics.update.availability_rank) && + (0 < event->value.search.specifics.update.availability_certainty)) + GNUNET_SCHEDULER_add_now(&abort_search_task, NULL); + break; + + case GNUNET_FS_STATUS_SEARCH_START: + GNUNET_assert(search == NULL); + GNUNET_assert(0 == strcmp("search", event->value.search.cctx)); + GNUNET_assert(1 == event->value.search.anonymity); + break; + + case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: + break; + + case GNUNET_FS_STATUS_SEARCH_STOPPED: + GNUNET_assert(search == event->value.search.sc); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + default: + fprintf(stderr, + "Unexpected event: %d\n", + event->status); + break; + } return NULL; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { const char *keywords[] = { "down_foo", @@ -203,41 +215,41 @@ run (void *cls, struct GNUNET_FS_FileInformation *fi; size_t i; - fs = GNUNET_FS_start (cfg, "test-fs-search", &progress_cb, NULL, - GNUNET_FS_FLAGS_DO_PROBES, - GNUNET_FS_OPTIONS_END); - GNUNET_assert (NULL != fs); - buf = GNUNET_malloc (FILESIZE); + fs = GNUNET_FS_start(cfg, "test-fs-search", &progress_cb, NULL, + GNUNET_FS_FLAGS_DO_PROBES, + GNUNET_FS_OPTIONS_END); + GNUNET_assert(NULL != fs); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - meta = GNUNET_CONTAINER_meta_data_create (); - kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + meta = GNUNET_CONTAINER_meta_data_create(); + kuri = GNUNET_FS_uri_ksk_create_from_args(2, keywords); bo.content_priority = 42; bo.anonymity_level = 1; bo.replication_level = 0; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME); - fi = GNUNET_FS_file_information_create_from_data (fs, "publish-context", - FILESIZE, buf, kuri, meta, - GNUNET_NO, &bo); - GNUNET_FS_uri_destroy (kuri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_assert (NULL != fi); - start = GNUNET_TIME_absolute_get (); + bo.expiration_time = GNUNET_TIME_relative_to_absolute(LIFETIME); + fi = GNUNET_FS_file_information_create_from_data(fs, "publish-context", + FILESIZE, buf, kuri, meta, + GNUNET_NO, &bo); + GNUNET_FS_uri_destroy(kuri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_assert(NULL != fi); + start = GNUNET_TIME_absolute_get(); publish = - GNUNET_FS_publish_start (fs, fi, NULL, NULL, NULL, - GNUNET_FS_PUBLISH_OPTION_NONE); - GNUNET_assert (publish != NULL); - timeout_task = GNUNET_SCHEDULER_add_delayed (LIFETIME, - &abort_error, NULL); + GNUNET_FS_publish_start(fs, fi, NULL, NULL, NULL, + GNUNET_FS_PUBLISH_OPTION_NONE); + GNUNET_assert(publish != NULL); + timeout_task = GNUNET_SCHEDULER_add_delayed(LIFETIME, + &abort_error, NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-search-probes", - "test_fs_search_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-search-probes", + "test_fs_search_data.conf", + &run, NULL)) return 1; return err; } diff --git a/src/fs/test_fs_search_with_and.c b/src/fs/test_fs_search_with_and.c index f1072a4a1..e43b8e25a 100644 --- a/src/fs/test_fs_search_with_and.c +++ b/src/fs/test_fs_search_with_and.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_search_with_and.c * @brief testcase for publishing multiple files and search with a and operator @@ -42,12 +42,12 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** * How long should our test-content live? */ -#define LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) static struct GNUNET_TIME_Absolute start; @@ -66,140 +66,150 @@ static int processed_files; static void -abort_publish_task (void *cls) +abort_publish_task(void *cls) { if (NULL != publish) - { - GNUNET_FS_publish_stop (publish); - publish = NULL; - } + { + GNUNET_FS_publish_stop(publish); + publish = NULL; + } if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } } static void -abort_error (void *cls) +abort_error(void *cls) { - fprintf (stderr, - "Timeout\n"); + fprintf(stderr, + "Timeout\n"); timeout_task = NULL; if (NULL != search) - { - GNUNET_FS_search_stop (search); - search = NULL; - } + { + GNUNET_FS_search_stop(search); + search = NULL; + } if (NULL != publish) - { - GNUNET_FS_publish_stop (publish); - publish = NULL; - } + { + GNUNET_FS_publish_stop(publish); + publish = NULL; + } err = 1; } static void -abort_search_task (void *cls) +abort_search_task(void *cls) { if (NULL != search) - { - GNUNET_FS_search_stop (search); - search = NULL; - } + { + GNUNET_FS_search_stop(search); + search = NULL; + } } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { - struct GNUNET_FS_Uri *kuri; switch (event->status) - { - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publish is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.publish.completed, - (unsigned long long) event->value.publish.size, - event->value.publish.specifics.progress.depth, - (unsigned long long) event->value.publish.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - break; - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - processed_files++; - if(processed_files == NUM_FILES) - { - char *emsg = NULL; - kuri = GNUNET_FS_uri_ksk_create ("+down_foo +down_bar", &emsg); - GNUNET_assert (kuri != NULL); - - start = GNUNET_TIME_absolute_get (); - search = - GNUNET_FS_search_start (fs, kuri, 1, GNUNET_FS_SEARCH_OPTION_NONE, - "search"); - GNUNET_FS_uri_destroy (kuri); - GNUNET_assert (search != NULL); - } - break; - case GNUNET_FS_STATUS_SEARCH_RESULT: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Search complete.\n"); - GNUNET_SCHEDULER_add_now (&abort_search_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - fprintf (stderr, "Error publishing file: %s\n", - event->value.publish.specifics.error.message); - GNUNET_break (0); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - case GNUNET_FS_STATUS_SEARCH_ERROR: - fprintf (stderr, "Error searching file: %s\n", - event->value.search.specifics.error.message); - GNUNET_SCHEDULER_add_now (&abort_search_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_START: - GNUNET_assert (0 == strcmp ("publish-context", event->value.publish.cctx)); - GNUNET_assert (NULL == event->value.publish.pctx); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (1 == event->value.publish.anonymity); - break; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - GNUNET_assert (publish == event->value.publish.pc); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (1 == event->value.publish.anonymity); - GNUNET_FS_stop (fs); - fs = NULL; - break; - case GNUNET_FS_STATUS_SEARCH_START: - GNUNET_assert (search == NULL); - GNUNET_assert (0 == strcmp ("search", event->value.search.cctx)); - GNUNET_assert (1 == event->value.search.anonymity); - break; - case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: - break; - case GNUNET_FS_STATUS_SEARCH_STOPPED: - GNUNET_assert (search == event->value.search.sc); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - default: - fprintf (stderr, "Unexpected event: %d\n", event->status); - break; - } + { + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publish is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.publish.completed, + (unsigned long long)event->value.publish.size, + event->value.publish.specifics.progress.depth, + (unsigned long long)event->value.publish.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + break; + + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + processed_files++; + if (processed_files == NUM_FILES) + { + char *emsg = NULL; + kuri = GNUNET_FS_uri_ksk_create("+down_foo +down_bar", &emsg); + GNUNET_assert(kuri != NULL); + + start = GNUNET_TIME_absolute_get(); + search = + GNUNET_FS_search_start(fs, kuri, 1, GNUNET_FS_SEARCH_OPTION_NONE, + "search"); + GNUNET_FS_uri_destroy(kuri); + GNUNET_assert(search != NULL); + } + break; + + case GNUNET_FS_STATUS_SEARCH_RESULT: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Search complete.\n"); + GNUNET_SCHEDULER_add_now(&abort_search_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + fprintf(stderr, "Error publishing file: %s\n", + event->value.publish.specifics.error.message); + GNUNET_break(0); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + case GNUNET_FS_STATUS_SEARCH_ERROR: + fprintf(stderr, "Error searching file: %s\n", + event->value.search.specifics.error.message); + GNUNET_SCHEDULER_add_now(&abort_search_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_START: + GNUNET_assert(0 == strcmp("publish-context", event->value.publish.cctx)); + GNUNET_assert(NULL == event->value.publish.pctx); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(1 == event->value.publish.anonymity); + break; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + GNUNET_assert(publish == event->value.publish.pc); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(1 == event->value.publish.anonymity); + GNUNET_FS_stop(fs); + fs = NULL; + break; + + case GNUNET_FS_STATUS_SEARCH_START: + GNUNET_assert(search == NULL); + GNUNET_assert(0 == strcmp("search", event->value.search.cctx)); + GNUNET_assert(1 == event->value.search.anonymity); + break; + + case GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED: + break; + + case GNUNET_FS_STATUS_SEARCH_STOPPED: + GNUNET_assert(search == event->value.search.sc); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + default: + fprintf(stderr, "Unexpected event: %d\n", event->status); + break; + } return NULL; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { const char *keywords[] = { "down_foo", @@ -213,46 +223,47 @@ run (void *cls, size_t i; size_t j; - fs = GNUNET_FS_start (cfg, "test-fs-search", &progress_cb, NULL, - GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); - GNUNET_assert (NULL != fs); + fs = GNUNET_FS_start(cfg, "test-fs-search", &progress_cb, NULL, + GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); + GNUNET_assert(NULL != fs); processed_files = 0; - for(j = 0; j < NUM_FILES; j++){ - buf = GNUNET_malloc (FILESIZE); - for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - meta = GNUNET_CONTAINER_meta_data_create (); - kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords); - bo.content_priority = 42; - bo.anonymity_level = 1; - bo.replication_level = 0; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME); - fi = GNUNET_FS_file_information_create_from_data (fs, "publish-context", - FILESIZE, buf, kuri, meta, - GNUNET_NO, &bo); - GNUNET_FS_uri_destroy (kuri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_assert (NULL != fi); - start = GNUNET_TIME_absolute_get (); - publish = - GNUNET_FS_publish_start (fs, fi, NULL, NULL, NULL, + for (j = 0; j < NUM_FILES; j++) + { + buf = GNUNET_malloc(FILESIZE); + for (i = 0; i < FILESIZE; i++) + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + meta = GNUNET_CONTAINER_meta_data_create(); + kuri = GNUNET_FS_uri_ksk_create_from_args(2, keywords); + bo.content_priority = 42; + bo.anonymity_level = 1; + bo.replication_level = 0; + bo.expiration_time = GNUNET_TIME_relative_to_absolute(LIFETIME); + fi = GNUNET_FS_file_information_create_from_data(fs, "publish-context", + FILESIZE, buf, kuri, meta, + GNUNET_NO, &bo); + GNUNET_FS_uri_destroy(kuri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_assert(NULL != fi); + start = GNUNET_TIME_absolute_get(); + publish = + GNUNET_FS_publish_start(fs, fi, NULL, NULL, NULL, GNUNET_FS_PUBLISH_OPTION_NONE); - GNUNET_assert (publish != NULL); - } + GNUNET_assert(publish != NULL); + } - timeout_task = GNUNET_SCHEDULER_add_delayed (LIFETIME, - &abort_error, NULL); + timeout_task = GNUNET_SCHEDULER_add_delayed(LIFETIME, + &abort_error, NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-search-with-and", - "test_fs_search_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-search-with-and", + "test_fs_search_data.conf", + &run, NULL)) return 1; return err; } diff --git a/src/fs/test_fs_start_stop.c b/src/fs/test_fs_start_stop.c index e20e00996..4e3c17db0 100644 --- a/src/fs/test_fs_start_stop.c +++ b/src/fs/test_fs_start_stop.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_start_stop.c * @brief testcase for fs.c (start-stop only) @@ -30,32 +30,32 @@ static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { return NULL; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct GNUNET_FS_Handle *fs; - fs = GNUNET_FS_start (cfg, "test-fs-start-stop", &progress_cb, NULL, - GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); - GNUNET_assert (NULL != fs); - GNUNET_FS_stop (fs); + fs = GNUNET_FS_start(cfg, "test-fs-start-stop", &progress_cb, NULL, + GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); + GNUNET_assert(NULL != fs); + GNUNET_FS_stop(fs); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-start-stop", - "test_fs_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-start-stop", + "test_fs_data.conf", + &run, NULL)) return 1; return 0; } diff --git a/src/fs/test_fs_test_lib.c b/src/fs/test_fs_test_lib.c index 52b0bf2c0..7e27469cc 100644 --- a/src/fs/test_fs_test_lib.c +++ b/src/fs/test_fs_test_lib.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_test_lib.c @@ -36,7 +36,7 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 300) #define NUM_DAEMONS 2 @@ -50,75 +50,74 @@ static int ret; static void -do_stop (void *cls) +do_stop(void *cls) { char *fn = cls; if (0 == - GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (start_time, - TIMEOUT)).rel_value_us) - { - GNUNET_break (0); - ret = 1; - } + GNUNET_TIME_absolute_get_remaining(GNUNET_TIME_absolute_add(start_time, + TIMEOUT)).rel_value_us) + { + GNUNET_break(0); + ret = 1; + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished download, shutting down\n"); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished download, shutting down\n"); + } if (NULL != fn) - { - GNUNET_DISK_directory_remove (fn); - GNUNET_free (fn); - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_DISK_directory_remove(fn); + GNUNET_free(fn); + } + GNUNET_SCHEDULER_shutdown(); } static void -do_download (void *cls, - const struct GNUNET_FS_Uri *uri, - const char *fn) +do_download(void *cls, + const struct GNUNET_FS_Uri *uri, + const char *fn) { if (NULL == uri) - { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - ret = 1; - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Downloading %llu bytes\n", - (unsigned long long) FILESIZE); - start_time = GNUNET_TIME_absolute_get (); - GNUNET_FS_TEST_download (the_peers[0], - TIMEOUT, 1, SEED, - uri, - VERBOSE, - &do_stop, - (NULL == fn) ? NULL : GNUNET_strdup (fn)); + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + ret = 1; + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Downloading %llu bytes\n", + (unsigned long long)FILESIZE); + start_time = GNUNET_TIME_absolute_get(); + GNUNET_FS_TEST_download(the_peers[0], + TIMEOUT, 1, SEED, + uri, + VERBOSE, + &do_stop, + (NULL == fn) ? NULL : GNUNET_strdup(fn)); } static void -do_publish (void *cls, - struct GNUNET_TESTBED_Operation *op, - const char *emsg) +do_publish(void *cls, + struct GNUNET_TESTBED_Operation *op, + const char *emsg) { - GNUNET_TESTBED_operation_done (op); + GNUNET_TESTBED_operation_done(op); if (NULL != emsg) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to connect peers: %s\n", emsg); - GNUNET_break (0); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Publishing %llu bytes\n", - (unsigned long long) FILESIZE); - GNUNET_FS_TEST_publish (the_peers[0], TIMEOUT, 1, GNUNET_NO, FILESIZE, SEED, - VERBOSE, &do_download, NULL); - + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Failed to connect peers: %s\n", emsg); + GNUNET_break(0); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Publishing %llu bytes\n", + (unsigned long long)FILESIZE); + GNUNET_FS_TEST_publish(the_peers[0], TIMEOUT, 1, GNUNET_NO, FILESIZE, SEED, + VERBOSE, &do_download, NULL); } @@ -135,23 +134,23 @@ do_publish (void *cls, * failed */ static void -run (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - unsigned int links_succeeded, - unsigned int links_failed) +run(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + unsigned int links_succeeded, + unsigned int links_failed) { unsigned int i; - GNUNET_assert (NUM_DAEMONS == num_peers); - for (i=0;i. SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_unindex.c @@ -37,12 +37,12 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** * How long should our test-content live? */ -#define LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) static struct GNUNET_TIME_Absolute start; @@ -57,117 +57,127 @@ static char *fn; static void -abort_publish_task (void *cls) +abort_publish_task(void *cls) { - GNUNET_FS_publish_stop (publish); + GNUNET_FS_publish_stop(publish); publish = NULL; } static void -abort_unindex_task (void *cls) +abort_unindex_task(void *cls) { - GNUNET_FS_unindex_stop (unindex); + GNUNET_FS_unindex_stop(unindex); unindex = NULL; - GNUNET_DISK_directory_remove (fn); - GNUNET_free (fn); + GNUNET_DISK_directory_remove(fn); + GNUNET_free(fn); fn = NULL; } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { - switch (event->status) - { - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publish is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.publish.completed, - (unsigned long long) event->value.publish.size, - event->value.publish.specifics.progress.depth, - (unsigned long long) event->value.publish.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - break; - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - printf ("Publishing complete, %llu kbps.\n", - (unsigned long long) (FILESIZE * 1000000LL / + { + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publish is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.publish.completed, + (unsigned long long)event->value.publish.size, + event->value.publish.specifics.progress.depth, + (unsigned long long)event->value.publish.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + break; + + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + printf("Publishing complete, %llu kbps.\n", + (unsigned long long)(FILESIZE * 1000000LL / (1 + GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024)); - start = GNUNET_TIME_absolute_get (); - unindex = GNUNET_FS_unindex_start (fs, fn, "unindex"); - GNUNET_assert (unindex != NULL); - break; - case GNUNET_FS_STATUS_UNINDEX_COMPLETED: - printf ("Unindex complete, %llu kbps.\n", - (unsigned long long) (FILESIZE * 1000000LL / + (start).rel_value_us) / 1024)); + start = GNUNET_TIME_absolute_get(); + unindex = GNUNET_FS_unindex_start(fs, fn, "unindex"); + GNUNET_assert(unindex != NULL); + break; + + case GNUNET_FS_STATUS_UNINDEX_COMPLETED: + printf("Unindex complete, %llu kbps.\n", + (unsigned long long)(FILESIZE * 1000000LL / (1 + GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024)); - GNUNET_SCHEDULER_add_now (&abort_unindex_task, NULL); - break; - case GNUNET_FS_STATUS_UNINDEX_PROGRESS: - GNUNET_assert (unindex == event->value.unindex.uc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Unindex is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.unindex.completed, - (unsigned long long) event->value.unindex.size, - event->value.unindex.specifics.progress.depth, - (unsigned long long) event->value.unindex.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - fprintf (stderr, "Error publishing file: %s\n", - event->value.publish.specifics.error.message); - GNUNET_break (0); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - case GNUNET_FS_STATUS_UNINDEX_ERROR: - fprintf (stderr, "Error unindexing file: %s\n", - event->value.unindex.specifics.error.message); - GNUNET_SCHEDULER_add_now (&abort_unindex_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_START: - GNUNET_assert (0 == strcmp ("publish-context", event->value.publish.cctx)); - GNUNET_assert (NULL == event->value.publish.pctx); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (1 == event->value.publish.anonymity); - break; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - GNUNET_assert (publish == event->value.publish.pc); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (1 == event->value.publish.anonymity); - GNUNET_FS_stop (fs); - fs = NULL; - break; - case GNUNET_FS_STATUS_UNINDEX_START: - GNUNET_assert (unindex == NULL); - GNUNET_assert (0 == strcmp ("unindex", event->value.unindex.cctx)); - GNUNET_assert (0 == strcmp (fn, event->value.unindex.filename)); - GNUNET_assert (FILESIZE == event->value.unindex.size); - GNUNET_assert (0 == event->value.unindex.completed); - break; - case GNUNET_FS_STATUS_UNINDEX_STOPPED: - GNUNET_assert (unindex == event->value.unindex.uc); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - default: - printf ("Unexpected event: %d\n", event->status); - break; - } + (start).rel_value_us) / 1024)); + GNUNET_SCHEDULER_add_now(&abort_unindex_task, NULL); + break; + + case GNUNET_FS_STATUS_UNINDEX_PROGRESS: + GNUNET_assert(unindex == event->value.unindex.uc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Unindex is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.unindex.completed, + (unsigned long long)event->value.unindex.size, + event->value.unindex.specifics.progress.depth, + (unsigned long long)event->value.unindex.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + fprintf(stderr, "Error publishing file: %s\n", + event->value.publish.specifics.error.message); + GNUNET_break(0); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + case GNUNET_FS_STATUS_UNINDEX_ERROR: + fprintf(stderr, "Error unindexing file: %s\n", + event->value.unindex.specifics.error.message); + GNUNET_SCHEDULER_add_now(&abort_unindex_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_START: + GNUNET_assert(0 == strcmp("publish-context", event->value.publish.cctx)); + GNUNET_assert(NULL == event->value.publish.pctx); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(1 == event->value.publish.anonymity); + break; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + GNUNET_assert(publish == event->value.publish.pc); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(1 == event->value.publish.anonymity); + GNUNET_FS_stop(fs); + fs = NULL; + break; + + case GNUNET_FS_STATUS_UNINDEX_START: + GNUNET_assert(unindex == NULL); + GNUNET_assert(0 == strcmp("unindex", event->value.unindex.cctx)); + GNUNET_assert(0 == strcmp(fn, event->value.unindex.filename)); + GNUNET_assert(FILESIZE == event->value.unindex.size); + GNUNET_assert(0 == event->value.unindex.completed); + break; + + case GNUNET_FS_STATUS_UNINDEX_STOPPED: + GNUNET_assert(unindex == event->value.unindex.uc); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + default: + printf("Unexpected event: %d\n", event->status); + break; + } return NULL; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { const char *keywords[] = { "down_foo", @@ -180,44 +190,44 @@ run (void *cls, size_t i; struct GNUNET_FS_BlockOptions bo; - fn = GNUNET_DISK_mktemp ("gnunet-unindex-test-dst"); - fs = GNUNET_FS_start (cfg, "test-fs-unindex", &progress_cb, NULL, - GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); - GNUNET_assert (NULL != fs); - buf = GNUNET_malloc (FILESIZE); + fn = GNUNET_DISK_mktemp("gnunet-unindex-test-dst"); + fs = GNUNET_FS_start(cfg, "test-fs-unindex", &progress_cb, NULL, + GNUNET_FS_FLAGS_NONE, GNUNET_FS_OPTIONS_END); + GNUNET_assert(NULL != fs); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - GNUNET_assert (FILESIZE == - GNUNET_DISK_fn_write (fn, buf, FILESIZE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)); - GNUNET_free (buf); - meta = GNUNET_CONTAINER_meta_data_create (); - kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + GNUNET_assert(FILESIZE == + GNUNET_DISK_fn_write(fn, buf, FILESIZE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)); + GNUNET_free(buf); + meta = GNUNET_CONTAINER_meta_data_create(); + kuri = GNUNET_FS_uri_ksk_create_from_args(2, keywords); bo.content_priority = 42; bo.anonymity_level = 1; bo.replication_level = 0; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME); - fi = GNUNET_FS_file_information_create_from_file (fs, "publish-context", fn, - kuri, meta, GNUNET_YES, - &bo); - GNUNET_FS_uri_destroy (kuri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_assert (NULL != fi); - start = GNUNET_TIME_absolute_get (); + bo.expiration_time = GNUNET_TIME_relative_to_absolute(LIFETIME); + fi = GNUNET_FS_file_information_create_from_file(fs, "publish-context", fn, + kuri, meta, GNUNET_YES, + &bo); + GNUNET_FS_uri_destroy(kuri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_assert(NULL != fi); + start = GNUNET_TIME_absolute_get(); publish = - GNUNET_FS_publish_start (fs, fi, NULL, NULL, NULL, - GNUNET_FS_PUBLISH_OPTION_NONE); - GNUNET_assert (publish != NULL); + GNUNET_FS_publish_start(fs, fi, NULL, NULL, NULL, + GNUNET_FS_PUBLISH_OPTION_NONE); + GNUNET_assert(publish != NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-unindex", - "test_fs_unindex_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-unindex", + "test_fs_unindex_data.conf", + &run, NULL)) return 1; return 0; } diff --git a/src/fs/test_fs_unindex_persistence.c b/src/fs/test_fs_unindex_persistence.c index 50d45708a..7deebb95b 100644 --- a/src/fs/test_fs_unindex_persistence.c +++ b/src/fs/test_fs_unindex_persistence.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_unindex_persistence.c @@ -36,12 +36,12 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** * How long should our test-content live? */ -#define LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define LIFETIME GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) static struct GNUNET_TIME_Absolute start; @@ -58,40 +58,40 @@ static const struct GNUNET_CONFIGURATION_Handle *cfg; static void -abort_publish_task (void *cls) +abort_publish_task(void *cls) { - GNUNET_FS_publish_stop (publish); + GNUNET_FS_publish_stop(publish); publish = NULL; } static void -abort_unindex_task (void *cls) +abort_unindex_task(void *cls) { if (unindex != NULL) - { - GNUNET_FS_unindex_stop (unindex); - unindex = NULL; - } + { + GNUNET_FS_unindex_stop(unindex); + unindex = NULL; + } if (fn != NULL) - { - GNUNET_DISK_directory_remove (fn); - GNUNET_free (fn); - fn = NULL; - } + { + GNUNET_DISK_directory_remove(fn); + GNUNET_free(fn); + fn = NULL; + } } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event); +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event); static void -restart_fs_task (void *cls) +restart_fs_task(void *cls) { - GNUNET_FS_stop (fs); - fs = GNUNET_FS_start (cfg, "test-fs-unindex-persistence", &progress_cb, NULL, - GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); + GNUNET_FS_stop(fs); + fs = GNUNET_FS_start(cfg, "test-fs-unindex-persistence", &progress_cb, NULL, + GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); } @@ -103,7 +103,7 @@ restart_fs_task (void *cls) * @param ev type of the event to consider */ static void -consider_restart (int ev) +consider_restart(int ev) { static int prev[32]; static int off; @@ -113,125 +113,140 @@ consider_restart (int ev) if (prev[i] == ev) return; prev[off++] = ev; - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_URGENT, - &restart_fs_task, NULL); + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_URGENT, + &restart_fs_task, NULL); } static void * -progress_cb (void *cls, const struct GNUNET_FS_ProgressInfo *event) +progress_cb(void *cls, const struct GNUNET_FS_ProgressInfo *event) { switch (event->status) - { - case GNUNET_FS_STATUS_PUBLISH_PROGRESS: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Publish is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.publish.completed, - (unsigned long long) event->value.publish.size, - event->value.publish.specifics.progress.depth, - (unsigned long long) event->value.publish.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: - break; - case GNUNET_FS_STATUS_PUBLISH_COMPLETED: - printf ("Publishing complete, %llu kbps.\n", - (unsigned long long) (FILESIZE * 1000000LL / + { + case GNUNET_FS_STATUS_PUBLISH_PROGRESS: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Publish is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.publish.completed, + (unsigned long long)event->value.publish.size, + event->value.publish.specifics.progress.depth, + (unsigned long long)event->value.publish.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY: + break; + + case GNUNET_FS_STATUS_PUBLISH_COMPLETED: + printf("Publishing complete, %llu kbps.\n", + (unsigned long long)(FILESIZE * 1000000LL / (1 + GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024)); - start = GNUNET_TIME_absolute_get (); - unindex = GNUNET_FS_unindex_start (fs, fn, "unindex"); - GNUNET_assert (unindex != NULL); - break; - case GNUNET_FS_STATUS_UNINDEX_COMPLETED: - printf ("Unindex complete, %llu kbps.\n", - (unsigned long long) (FILESIZE * 1000000LL / + (start).rel_value_us) / 1024)); + start = GNUNET_TIME_absolute_get(); + unindex = GNUNET_FS_unindex_start(fs, fn, "unindex"); + GNUNET_assert(unindex != NULL); + break; + + case GNUNET_FS_STATUS_UNINDEX_COMPLETED: + printf("Unindex complete, %llu kbps.\n", + (unsigned long long)(FILESIZE * 1000000LL / (1 + GNUNET_TIME_absolute_get_duration - (start).rel_value_us) / 1024)); - GNUNET_SCHEDULER_add_now (&abort_unindex_task, NULL); - break; - case GNUNET_FS_STATUS_UNINDEX_PROGRESS: - consider_restart (event->status); - GNUNET_assert (unindex == event->value.unindex.uc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Unindex is progressing (%llu/%llu at level %u off %llu)...\n", - (unsigned long long) event->value.unindex.completed, - (unsigned long long) event->value.unindex.size, - event->value.unindex.specifics.progress.depth, - (unsigned long long) event->value.unindex.specifics. - progress.offset); - break; - case GNUNET_FS_STATUS_PUBLISH_SUSPEND: - if (event->value.publish.pc == publish) - publish = NULL; - break; - case GNUNET_FS_STATUS_PUBLISH_RESUME: - if (NULL == publish) - { - publish = event->value.publish.pc; - return "publish-context"; + (start).rel_value_us) / 1024)); + GNUNET_SCHEDULER_add_now(&abort_unindex_task, NULL); + break; + + case GNUNET_FS_STATUS_UNINDEX_PROGRESS: + consider_restart(event->status); + GNUNET_assert(unindex == event->value.unindex.uc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Unindex is progressing (%llu/%llu at level %u off %llu)...\n", + (unsigned long long)event->value.unindex.completed, + (unsigned long long)event->value.unindex.size, + event->value.unindex.specifics.progress.depth, + (unsigned long long)event->value.unindex.specifics. + progress.offset); + break; + + case GNUNET_FS_STATUS_PUBLISH_SUSPEND: + if (event->value.publish.pc == publish) + publish = NULL; + break; + + case GNUNET_FS_STATUS_PUBLISH_RESUME: + if (NULL == publish) + { + publish = event->value.publish.pc; + return "publish-context"; + } + break; + + case GNUNET_FS_STATUS_UNINDEX_SUSPEND: + GNUNET_assert(event->value.unindex.uc == unindex); + unindex = NULL; + break; + + case GNUNET_FS_STATUS_UNINDEX_RESUME: + GNUNET_assert(NULL == unindex); + unindex = event->value.unindex.uc; + return "unindex"; + + case GNUNET_FS_STATUS_PUBLISH_ERROR: + fprintf(stderr, "Error publishing file: %s\n", + event->value.publish.specifics.error.message); + GNUNET_break(0); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + case GNUNET_FS_STATUS_UNINDEX_ERROR: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Error unindexing file: %s\n", + event->value.unindex.specifics.error.message); + GNUNET_SCHEDULER_add_now(&abort_unindex_task, NULL); + break; + + case GNUNET_FS_STATUS_PUBLISH_START: + GNUNET_assert(0 == strcmp("publish-context", event->value.publish.cctx)); + GNUNET_assert(NULL == event->value.publish.pctx); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(0 == event->value.publish.completed); + GNUNET_assert(1 == event->value.publish.anonymity); + break; + + case GNUNET_FS_STATUS_PUBLISH_STOPPED: + GNUNET_assert(publish == event->value.publish.pc); + GNUNET_assert(FILESIZE == event->value.publish.size); + GNUNET_assert(1 == event->value.publish.anonymity); + GNUNET_FS_stop(fs); + fs = NULL; + break; + + case GNUNET_FS_STATUS_UNINDEX_START: + consider_restart(event->status); + GNUNET_assert(unindex == NULL); + GNUNET_assert(0 == strcmp("unindex", event->value.unindex.cctx)); + GNUNET_assert(0 == strcmp(fn, event->value.unindex.filename)); + GNUNET_assert(FILESIZE == event->value.unindex.size); + GNUNET_assert(0 == event->value.unindex.completed); + break; + + case GNUNET_FS_STATUS_UNINDEX_STOPPED: + GNUNET_assert(unindex == event->value.unindex.uc); + GNUNET_SCHEDULER_add_now(&abort_publish_task, NULL); + break; + + default: + printf("Unexpected event: %d\n", event->status); + break; } - break; - case GNUNET_FS_STATUS_UNINDEX_SUSPEND: - GNUNET_assert (event->value.unindex.uc == unindex); - unindex = NULL; - break; - case GNUNET_FS_STATUS_UNINDEX_RESUME: - GNUNET_assert (NULL == unindex); - unindex = event->value.unindex.uc; - return "unindex"; - case GNUNET_FS_STATUS_PUBLISH_ERROR: - fprintf (stderr, "Error publishing file: %s\n", - event->value.publish.specifics.error.message); - GNUNET_break (0); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - case GNUNET_FS_STATUS_UNINDEX_ERROR: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Error unindexing file: %s\n", - event->value.unindex.specifics.error.message); - GNUNET_SCHEDULER_add_now (&abort_unindex_task, NULL); - break; - case GNUNET_FS_STATUS_PUBLISH_START: - GNUNET_assert (0 == strcmp ("publish-context", event->value.publish.cctx)); - GNUNET_assert (NULL == event->value.publish.pctx); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (0 == event->value.publish.completed); - GNUNET_assert (1 == event->value.publish.anonymity); - break; - case GNUNET_FS_STATUS_PUBLISH_STOPPED: - GNUNET_assert (publish == event->value.publish.pc); - GNUNET_assert (FILESIZE == event->value.publish.size); - GNUNET_assert (1 == event->value.publish.anonymity); - GNUNET_FS_stop (fs); - fs = NULL; - break; - case GNUNET_FS_STATUS_UNINDEX_START: - consider_restart (event->status); - GNUNET_assert (unindex == NULL); - GNUNET_assert (0 == strcmp ("unindex", event->value.unindex.cctx)); - GNUNET_assert (0 == strcmp (fn, event->value.unindex.filename)); - GNUNET_assert (FILESIZE == event->value.unindex.size); - GNUNET_assert (0 == event->value.unindex.completed); - break; - case GNUNET_FS_STATUS_UNINDEX_STOPPED: - GNUNET_assert (unindex == event->value.unindex.uc); - GNUNET_SCHEDULER_add_now (&abort_publish_task, NULL); - break; - default: - printf ("Unexpected event: %d\n", event->status); - break; - } return NULL; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_TESTING_Peer *peer) { const char *keywords[] = { "down_foo", @@ -245,44 +260,44 @@ run (void *cls, struct GNUNET_FS_BlockOptions bo; cfg = c; - fn = GNUNET_DISK_mktemp ("gnunet-unindex-test-dst"); - fs = GNUNET_FS_start (cfg, "test-fs-unindex-persistence", &progress_cb, NULL, - GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); - GNUNET_assert (NULL != fs); - buf = GNUNET_malloc (FILESIZE); + fn = GNUNET_DISK_mktemp("gnunet-unindex-test-dst"); + fs = GNUNET_FS_start(cfg, "test-fs-unindex-persistence", &progress_cb, NULL, + GNUNET_FS_FLAGS_PERSISTENCE, GNUNET_FS_OPTIONS_END); + GNUNET_assert(NULL != fs); + buf = GNUNET_malloc(FILESIZE); for (i = 0; i < FILESIZE; i++) - buf[i] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 256); - GNUNET_assert (FILESIZE == - GNUNET_DISK_fn_write (fn, buf, FILESIZE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)); - GNUNET_free (buf); - meta = GNUNET_CONTAINER_meta_data_create (); - kuri = GNUNET_FS_uri_ksk_create_from_args (2, keywords); + buf[i] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256); + GNUNET_assert(FILESIZE == + GNUNET_DISK_fn_write(fn, buf, FILESIZE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)); + GNUNET_free(buf); + meta = GNUNET_CONTAINER_meta_data_create(); + kuri = GNUNET_FS_uri_ksk_create_from_args(2, keywords); bo.content_priority = 42; bo.anonymity_level = 1; bo.replication_level = 0; - bo.expiration_time = GNUNET_TIME_relative_to_absolute (LIFETIME); - fi = GNUNET_FS_file_information_create_from_file (fs, "publish-context", fn, - kuri, meta, GNUNET_YES, - &bo); - GNUNET_FS_uri_destroy (kuri); - GNUNET_CONTAINER_meta_data_destroy (meta); - GNUNET_assert (NULL != fi); - start = GNUNET_TIME_absolute_get (); + bo.expiration_time = GNUNET_TIME_relative_to_absolute(LIFETIME); + fi = GNUNET_FS_file_information_create_from_file(fs, "publish-context", fn, + kuri, meta, GNUNET_YES, + &bo); + GNUNET_FS_uri_destroy(kuri); + GNUNET_CONTAINER_meta_data_destroy(meta); + GNUNET_assert(NULL != fi); + start = GNUNET_TIME_absolute_get(); publish = - GNUNET_FS_publish_start (fs, fi, NULL, NULL, NULL, - GNUNET_FS_PUBLISH_OPTION_NONE); - GNUNET_assert (publish != NULL); + GNUNET_FS_publish_start(fs, fi, NULL, NULL, NULL, + GNUNET_FS_PUBLISH_OPTION_NONE); + GNUNET_assert(publish != NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-fs-unindex-persistence", - "test_fs_unindex_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-fs-unindex-persistence", + "test_fs_unindex_data.conf", + &run, NULL)) return 1; return 0; } diff --git a/src/fs/test_fs_uri.c b/src/fs/test_fs_uri.c index e0a2ecea7..3cbbc27d3 100644 --- a/src/fs/test_fs_uri.c +++ b/src/fs/test_fs_uri.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_fs_uri.c * @brief Test for fs_uri.c @@ -29,52 +29,52 @@ static int -testKeyword () +testKeyword() { char *uri; struct GNUNET_FS_Uri *ret; char *emsg; - if (NULL != (ret = GNUNET_FS_uri_parse ("gnunet://fs/ksk/++", &emsg))) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } - GNUNET_free (emsg); - ret = GNUNET_FS_uri_parse ("gnunet://fs/ksk/foo+bar", &emsg); + if (NULL != (ret = GNUNET_FS_uri_parse("gnunet://fs/ksk/++", &emsg))) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } + GNUNET_free(emsg); + ret = GNUNET_FS_uri_parse("gnunet://fs/ksk/foo+bar", &emsg); if (NULL == ret) - { - GNUNET_free (emsg); - GNUNET_assert (0); - } - if (! GNUNET_FS_uri_test_ksk (ret)) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } + { + GNUNET_free(emsg); + GNUNET_assert(0); + } + if (!GNUNET_FS_uri_test_ksk(ret)) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } if ((2 != ret->data.ksk.keywordCount) || - (0 != strcmp (" foo", ret->data.ksk.keywords[0])) || - (0 != strcmp (" bar", ret->data.ksk.keywords[1]))) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } + (0 != strcmp(" foo", ret->data.ksk.keywords[0])) || + (0 != strcmp(" bar", ret->data.ksk.keywords[1]))) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } - uri = GNUNET_FS_uri_to_string (ret); - if (0 != strcmp (uri, "gnunet://fs/ksk/foo+bar")) - { - GNUNET_free (uri); - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } - GNUNET_free (uri); - GNUNET_FS_uri_destroy (ret); + uri = GNUNET_FS_uri_to_string(ret); + if (0 != strcmp(uri, "gnunet://fs/ksk/foo+bar")) + { + GNUNET_free(uri); + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } + GNUNET_free(uri); + GNUNET_FS_uri_destroy(ret); return 0; } static int -testLocation () +testLocation() { struct GNUNET_FS_Uri *uri; char *uric; @@ -84,71 +84,71 @@ testLocation () struct GNUNET_CRYPTO_EddsaPrivateKey *pk; baseURI = - GNUNET_FS_uri_parse + GNUNET_FS_uri_parse ("gnunet://fs/chk/4QZP479A9SKGFNMQ2ZBCYE71YV2QMTVGWTVPB6A10ASVCKXDHB05DKPSC7ZF6E9P9W1VE47394EQY7NXA47Q6R35M7P1MJPGP59D1Z8.D54QD1K5XCG5878T6YZ19AM60MQ6FC0YNVK7QY08KK0KM0FJJ3KQWYG112FN5T07KN7J0X35DF6WVBT9B8ZMZ3X2BXJ22X3KFQ6MV2G.15999", - &emsg); - GNUNET_assert (baseURI != NULL); - GNUNET_assert (emsg == NULL); - pk = GNUNET_CRYPTO_eddsa_key_create (); - uri = GNUNET_FS_uri_loc_create (baseURI, - pk, - GNUNET_TIME_absolute_get ()); - GNUNET_free (pk); + &emsg); + GNUNET_assert(baseURI != NULL); + GNUNET_assert(emsg == NULL); + pk = GNUNET_CRYPTO_eddsa_key_create(); + uri = GNUNET_FS_uri_loc_create(baseURI, + pk, + GNUNET_TIME_absolute_get()); + GNUNET_free(pk); if (NULL == uri) - { - GNUNET_break (0); - GNUNET_FS_uri_destroy (baseURI); - return 1; - } - if (! GNUNET_FS_uri_test_loc (uri)) - { - GNUNET_break (0); - GNUNET_FS_uri_destroy (uri); - GNUNET_FS_uri_destroy (baseURI); - return 1; - } - uri2 = GNUNET_FS_uri_loc_get_uri (uri); - if (! GNUNET_FS_uri_test_equal (baseURI, uri2)) - { - GNUNET_break (0); - GNUNET_FS_uri_destroy (uri); - GNUNET_FS_uri_destroy (uri2); - GNUNET_FS_uri_destroy (baseURI); - return 1; - } - GNUNET_FS_uri_destroy (uri2); - GNUNET_FS_uri_destroy (baseURI); - uric = GNUNET_FS_uri_to_string (uri); + { + GNUNET_break(0); + GNUNET_FS_uri_destroy(baseURI); + return 1; + } + if (!GNUNET_FS_uri_test_loc(uri)) + { + GNUNET_break(0); + GNUNET_FS_uri_destroy(uri); + GNUNET_FS_uri_destroy(baseURI); + return 1; + } + uri2 = GNUNET_FS_uri_loc_get_uri(uri); + if (!GNUNET_FS_uri_test_equal(baseURI, uri2)) + { + GNUNET_break(0); + GNUNET_FS_uri_destroy(uri); + GNUNET_FS_uri_destroy(uri2); + GNUNET_FS_uri_destroy(baseURI); + return 1; + } + GNUNET_FS_uri_destroy(uri2); + GNUNET_FS_uri_destroy(baseURI); + uric = GNUNET_FS_uri_to_string(uri); #if 0 /* not for the faint of heart: */ - printf ("URI: `%s'\n", uric); + printf("URI: `%s'\n", uric); #endif - uri2 = GNUNET_FS_uri_parse (uric, &emsg); - GNUNET_free (uric); + uri2 = GNUNET_FS_uri_parse(uric, &emsg); + GNUNET_free(uric); if (uri2 == NULL) - { - fprintf (stderr, "URI parsing failed: %s\n", emsg); - GNUNET_break (0); - GNUNET_FS_uri_destroy (uri); - GNUNET_free (emsg); - return 1; - } - GNUNET_assert (NULL == emsg); - if (GNUNET_YES != GNUNET_FS_uri_test_equal (uri, uri2)) - { - GNUNET_break (0); - GNUNET_FS_uri_destroy (uri); - GNUNET_FS_uri_destroy (uri2); - return 1; - } - GNUNET_FS_uri_destroy (uri2); - GNUNET_FS_uri_destroy (uri); + { + fprintf(stderr, "URI parsing failed: %s\n", emsg); + GNUNET_break(0); + GNUNET_FS_uri_destroy(uri); + GNUNET_free(emsg); + return 1; + } + GNUNET_assert(NULL == emsg); + if (GNUNET_YES != GNUNET_FS_uri_test_equal(uri, uri2)) + { + GNUNET_break(0); + GNUNET_FS_uri_destroy(uri); + GNUNET_FS_uri_destroy(uri2); + return 1; + } + GNUNET_FS_uri_destroy(uri2); + GNUNET_FS_uri_destroy(uri); return 0; } static int -testNamespace (int i) +testNamespace(int i) { char *uri; struct GNUNET_FS_Uri *ret; @@ -161,71 +161,71 @@ testNamespace (int i) if (NULL != (ret = - GNUNET_FS_uri_parse ("gnunet://fs/sks/D1KJS9H2A82Q65VKQ0ML3RFU6U1D3VUK", - &emsg))) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } - GNUNET_free (emsg); + GNUNET_FS_uri_parse("gnunet://fs/sks/D1KJS9H2A82Q65VKQ0ML3RFU6U1D3VUK", + &emsg))) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } + GNUNET_free(emsg); if (NULL != (ret = - GNUNET_FS_uri_parse - ("gnunet://fs/sks/XQHH4R288W26EBV369F6RCE0PJVJTX2Y74Q2FJPMPGA31HJX2JG/this", &emsg))) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } - GNUNET_free (emsg); - if (NULL != (ret = GNUNET_FS_uri_parse ("gnunet://fs/sks/test", &emsg))) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } - GNUNET_free (emsg); - ph = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_CRYPTO_ecdsa_key_get_public (ph, &id); - sret = GNUNET_STRINGS_data_to_string (&id, sizeof (id), - ubuf, sizeof (ubuf) - 1); - GNUNET_assert (NULL != sret); + GNUNET_FS_uri_parse + ("gnunet://fs/sks/XQHH4R288W26EBV369F6RCE0PJVJTX2Y74Q2FJPMPGA31HJX2JG/this", &emsg))) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } + GNUNET_free(emsg); + if (NULL != (ret = GNUNET_FS_uri_parse("gnunet://fs/sks/test", &emsg))) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } + GNUNET_free(emsg); + ph = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_CRYPTO_ecdsa_key_get_public(ph, &id); + sret = GNUNET_STRINGS_data_to_string(&id, sizeof(id), + ubuf, sizeof(ubuf) - 1); + GNUNET_assert(NULL != sret); sret[0] = '\0'; - GNUNET_snprintf (buf, sizeof (buf), - "gnunet://fs/sks/%s/test", - ubuf); - ret = GNUNET_FS_uri_parse (buf, &emsg); + GNUNET_snprintf(buf, sizeof(buf), + "gnunet://fs/sks/%s/test", + ubuf); + ret = GNUNET_FS_uri_parse(buf, &emsg); if (NULL == ret) - { - GNUNET_free (emsg); - GNUNET_assert (0); - } - if (GNUNET_FS_uri_test_ksk (ret)) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } - if (!GNUNET_FS_uri_test_sks (ret)) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } + { + GNUNET_free(emsg); + GNUNET_assert(0); + } + if (GNUNET_FS_uri_test_ksk(ret)) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } + if (!GNUNET_FS_uri_test_sks(ret)) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } - uri = GNUNET_FS_uri_to_string (ret); + uri = GNUNET_FS_uri_to_string(ret); if (0 != - strcmp (uri, - buf)) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_free (uri); - GNUNET_assert (0); - } - GNUNET_free (uri); - GNUNET_FS_uri_destroy (ret); + strcmp(uri, + buf)) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_free(uri); + GNUNET_assert(0); + } + GNUNET_free(uri); + GNUNET_FS_uri_destroy(ret); return 0; } static int -testFile (int i) +testFile(int i) { char *uri; struct GNUNET_FS_Uri *ret; @@ -233,93 +233,93 @@ testFile (int i) if (NULL != (ret = - GNUNET_FS_uri_parse - ("gnunet://fs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H00000440000.42", - &emsg))) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } - GNUNET_free (emsg); + GNUNET_FS_uri_parse + ("gnunet://fs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H00000440000.42", + &emsg))) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } + GNUNET_free(emsg); if (NULL != (ret = - GNUNET_FS_uri_parse - ("gnunet://fs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000", - &emsg))) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } - GNUNET_free (emsg); + GNUNET_FS_uri_parse + ("gnunet://fs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000", + &emsg))) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } + GNUNET_free(emsg); if (NULL != (ret = - GNUNET_FS_uri_parse - ("gnunet://fs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.FGH", - &emsg))) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } - GNUNET_free (emsg); + GNUNET_FS_uri_parse + ("gnunet://fs/chk/C282GG70GKK41O4551011DO413KFBVTVMQG1OG30I0K4045N0G41HAPB82G680A02JRVVFO8URVRU2F159011DO41000000022RG820.RNVVVVOOLCLK065B5D04HTNVNSIB2AI022RG8200HSLK1CO1000ATQ98824DMA2032LIMG50CG0K057NVUVG200000H000004400000.FGH", + &emsg))) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } + GNUNET_free(emsg); ret = - GNUNET_FS_uri_parse + GNUNET_FS_uri_parse ("gnunet://fs/chk/4QZP479A9SKGFNMQ2ZBCYE71YV2QMTVGWTVPB6A10ASVCKXDHB05DKPSC7ZF6E9P9W1VE47394EQY7NXA47Q6R35M7P1MJPGP59D1Z8.D54QD1K5XCG5878T6YZ19AM60MQ6FC0YNVK7QY08KK0KM0FJJ3KQWYG112FN5T07KN7J0X35DF6WVBT9B8ZMZ3X2BXJ22X3KFQ6MV2G.42", - &emsg); + &emsg); if (ret == NULL) - { - GNUNET_free (emsg); - GNUNET_assert (0); - } - if (GNUNET_FS_uri_test_ksk (ret)) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } - if (GNUNET_FS_uri_test_sks (ret)) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } - if (GNUNET_ntohll (ret->data.chk.file_length) != 42) - { - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } + { + GNUNET_free(emsg); + GNUNET_assert(0); + } + if (GNUNET_FS_uri_test_ksk(ret)) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } + if (GNUNET_FS_uri_test_sks(ret)) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } + if (GNUNET_ntohll(ret->data.chk.file_length) != 42) + { + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } - uri = GNUNET_FS_uri_to_string (ret); + uri = GNUNET_FS_uri_to_string(ret); if (0 != - strcmp (uri, - "gnunet://fs/chk/4QZP479A9SKGFNMQ2ZBCYE71YV2QMTVGWTVPB6A10ASVCKXDHB05DKPSC7ZF6E9P9W1VE47394EQY7NXA47Q6R35M7P1MJPGP59D1Z8.D54QD1K5XCG5878T6YZ19AM60MQ6FC0YNVK7QY08KK0KM0FJJ3KQWYG112FN5T07KN7J0X35DF6WVBT9B8ZMZ3X2BXJ22X3KFQ6MV2G.42")) - { - GNUNET_free (uri); - GNUNET_FS_uri_destroy (ret); - GNUNET_assert (0); - } - GNUNET_free (uri); - GNUNET_FS_uri_destroy (ret); + strcmp(uri, + "gnunet://fs/chk/4QZP479A9SKGFNMQ2ZBCYE71YV2QMTVGWTVPB6A10ASVCKXDHB05DKPSC7ZF6E9P9W1VE47394EQY7NXA47Q6R35M7P1MJPGP59D1Z8.D54QD1K5XCG5878T6YZ19AM60MQ6FC0YNVK7QY08KK0KM0FJJ3KQWYG112FN5T07KN7J0X35DF6WVBT9B8ZMZ3X2BXJ22X3KFQ6MV2G.42")) + { + GNUNET_free(uri); + GNUNET_FS_uri_destroy(ret); + GNUNET_assert(0); + } + GNUNET_free(uri); + GNUNET_FS_uri_destroy(ret); return 0; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { int failureCount = 0; int i; - GNUNET_log_setup ("test_fs_uri", - "WARNING", - NULL); - failureCount += testKeyword (); - failureCount += testLocation (); + GNUNET_log_setup("test_fs_uri", + "WARNING", + NULL); + failureCount += testKeyword(); + failureCount += testLocation(); for (i = 0; i < 255; i++) - { - /* fprintf (stderr, "%s", "."); */ - failureCount += testNamespace (i); - failureCount += testFile (i); - } + { + /* fprintf (stderr, "%s", "."); */ + failureCount += testNamespace(i); + failureCount += testFile(i); + } /* fprintf (stderr, "%s", "\n"); */ - GNUNET_DISK_directory_remove ("/tmp/gnunet-test-fs-uri"); + GNUNET_DISK_directory_remove("/tmp/gnunet-test-fs-uri"); if (failureCount != 0) return 1; return 0; diff --git a/src/fs/test_gnunet_service_fs_migration.c b/src/fs/test_gnunet_service_fs_migration.c index f7daf6b1a..c56e89e11 100644 --- a/src/fs/test_gnunet_service_fs_migration.c +++ b/src/fs/test_gnunet_service_fs_migration.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_gnunet_service_fs_migration.c @@ -37,12 +37,12 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 120) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 120) /** * How long do we give the peers for content migration? */ -#define MIGRATION_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 90) +#define MIGRATION_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90) #define SEED 42 @@ -55,8 +55,7 @@ static struct GNUNET_TIME_Absolute start_time; static struct GNUNET_TESTBED_Operation *op; -struct DownloadContext -{ +struct DownloadContext { char *fn; struct GNUNET_FS_Uri *uri; @@ -64,154 +63,154 @@ struct DownloadContext static void -do_stop (void *cls) +do_stop(void *cls) { struct GNUNET_TIME_Relative del; char *fancy; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); if (0 == - GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (start_time, - TIMEOUT)).rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Timeout during download, shutting down with error\n"); - ok = 1; - } + GNUNET_TIME_absolute_get_remaining(GNUNET_TIME_absolute_add(start_time, + TIMEOUT)).rel_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Timeout during download, shutting down with error\n"); + ok = 1; + } else - { - del = GNUNET_TIME_absolute_get_duration (start_time); - if (del.rel_value_us == 0) - del.rel_value_us = 1; - fancy = - GNUNET_STRINGS_byte_size_fancy (((unsigned long long) FILESIZE) * - 1000000LL / del.rel_value_us); - fprintf (stdout, - "Download speed was %s/s\n", - fancy); - GNUNET_free (fancy); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished download, shutting down\n"); - } + { + del = GNUNET_TIME_absolute_get_duration(start_time); + if (del.rel_value_us == 0) + del.rel_value_us = 1; + fancy = + GNUNET_STRINGS_byte_size_fancy(((unsigned long long)FILESIZE) * + 1000000LL / del.rel_value_us); + fprintf(stdout, + "Download speed was %s/s\n", + fancy); + GNUNET_free(fancy); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished download, shutting down\n"); + } } static void -do_download (void *cls, - const char *emsg) +do_download(void *cls, + const char *emsg) { struct DownloadContext *dc = cls; struct GNUNET_FS_Uri *uri = dc->uri; - GNUNET_TESTBED_operation_done (op); + GNUNET_TESTBED_operation_done(op); op = NULL; if (NULL != dc->fn) - { - GNUNET_DISK_directory_remove (dc->fn); - GNUNET_free (dc->fn); - } - GNUNET_free (dc); + { + GNUNET_DISK_directory_remove(dc->fn); + GNUNET_free(dc->fn); + } + GNUNET_free(dc); if (NULL != emsg) - { - GNUNET_SCHEDULER_shutdown (); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Failed to stop source daemon: %s\n", - emsg); - GNUNET_FS_uri_destroy (uri); - ok = 1; - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Downloading %llu bytes\n", - (unsigned long long) FILESIZE); - start_time = GNUNET_TIME_absolute_get (); - GNUNET_FS_TEST_download (daemons[0], - TIMEOUT, - 1, - SEED, - uri, - VERBOSE, - &do_stop, - NULL); - GNUNET_FS_uri_destroy (uri); + { + GNUNET_SCHEDULER_shutdown(); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Failed to stop source daemon: %s\n", + emsg); + GNUNET_FS_uri_destroy(uri); + ok = 1; + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Downloading %llu bytes\n", + (unsigned long long)FILESIZE); + start_time = GNUNET_TIME_absolute_get(); + GNUNET_FS_TEST_download(daemons[0], + TIMEOUT, + 1, + SEED, + uri, + VERBOSE, + &do_stop, + NULL); + GNUNET_FS_uri_destroy(uri); } static void -stop_source_peer (void *cls) +stop_source_peer(void *cls) { struct DownloadContext *dc = cls; /* FIXME: We should not interact with testbed when shutting down */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Stopping source peer\n"); - op = GNUNET_TESTBED_peer_stop (NULL, - daemons[1], - &do_download, dc); - GNUNET_assert (NULL != op); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Stopping source peer\n"); + op = GNUNET_TESTBED_peer_stop(NULL, + daemons[1], + &do_download, dc); + GNUNET_assert(NULL != op); } static void -do_wait (void *cls, - const struct GNUNET_FS_Uri *uri, - const char *fn) +do_wait(void *cls, + const struct GNUNET_FS_Uri *uri, + const char *fn) { struct DownloadContext *dc; if (NULL == uri) - { - GNUNET_SCHEDULER_shutdown (); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Timeout during upload attempt, shutting down with error\n"); - ok = 1; - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Waiting to allow content to migrate\n"); - dc = GNUNET_new (struct DownloadContext); - dc->uri = GNUNET_FS_uri_dup (uri); + { + GNUNET_SCHEDULER_shutdown(); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Timeout during upload attempt, shutting down with error\n"); + ok = 1; + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Waiting to allow content to migrate\n"); + dc = GNUNET_new(struct DownloadContext); + dc->uri = GNUNET_FS_uri_dup(uri); if (NULL != fn) - dc->fn = GNUNET_strdup (fn); - (void) GNUNET_SCHEDULER_add_delayed (MIGRATION_DELAY, - &stop_source_peer, - dc); + dc->fn = GNUNET_strdup(fn); + (void)GNUNET_SCHEDULER_add_delayed(MIGRATION_DELAY, + &stop_source_peer, + dc); } static void -do_publish (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - unsigned int links_succeeded, - unsigned int links_failed) +do_publish(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + unsigned int links_succeeded, + unsigned int links_failed) { unsigned int i; - GNUNET_assert (2 == num_peers); - for (i=0;i. SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_gnunet_service_fs_p2p.c @@ -36,7 +36,7 @@ /** * How long until we give up on the download? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 300) #define NUM_DAEMONS 2 @@ -54,110 +54,110 @@ static struct GNUNET_TIME_Absolute start_time; static void -do_stop (void *cls) +do_stop(void *cls) { char *fn = cls; struct GNUNET_TIME_Relative del; char *fancy; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); if (0 == - GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_add (start_time, - TIMEOUT)).rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Timeout during download, shutting down with error\n"); - ok = 1; - } + GNUNET_TIME_absolute_get_remaining(GNUNET_TIME_absolute_add(start_time, + TIMEOUT)).rel_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Timeout during download, shutting down with error\n"); + ok = 1; + } else - { - del = GNUNET_TIME_absolute_get_duration (start_time); - if (0 == del.rel_value_us) - del.rel_value_us = 1; - fancy = - GNUNET_STRINGS_byte_size_fancy (((unsigned long long) FILESIZE) * - 1000000LL / del.rel_value_us); - fprintf (stdout, - "Download speed was %s/s\n", - fancy); - GNUNET_free (fancy); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished download, shutting down\n"); - } + { + del = GNUNET_TIME_absolute_get_duration(start_time); + if (0 == del.rel_value_us) + del.rel_value_us = 1; + fancy = + GNUNET_STRINGS_byte_size_fancy(((unsigned long long)FILESIZE) * + 1000000LL / del.rel_value_us); + fprintf(stdout, + "Download speed was %s/s\n", + fancy); + GNUNET_free(fancy); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished download, shutting down\n"); + } if (NULL != fn) - { - GNUNET_DISK_directory_remove (fn); - GNUNET_free (fn); - } + { + GNUNET_DISK_directory_remove(fn); + GNUNET_free(fn); + } } static void -do_download (void *cls, const struct GNUNET_FS_Uri *uri, - const char *fn) +do_download(void *cls, const struct GNUNET_FS_Uri *uri, + const char *fn) { if (NULL == uri) - { - GNUNET_SCHEDULER_shutdown (); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Timeout during upload attempt, shutting down with error\n"); - ok = 1; - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Downloading %llu bytes\n", - (unsigned long long) FILESIZE); - start_time = GNUNET_TIME_absolute_get (); - GNUNET_FS_TEST_download (daemons[0], TIMEOUT, - anonymity_level, SEED, uri, - VERBOSE, &do_stop, - (NULL == fn) - ? NULL - : GNUNET_strdup (fn)); + { + GNUNET_SCHEDULER_shutdown(); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Timeout during upload attempt, shutting down with error\n"); + ok = 1; + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Downloading %llu bytes\n", + (unsigned long long)FILESIZE); + start_time = GNUNET_TIME_absolute_get(); + GNUNET_FS_TEST_download(daemons[0], TIMEOUT, + anonymity_level, SEED, uri, + VERBOSE, &do_stop, + (NULL == fn) + ? NULL + : GNUNET_strdup(fn)); } static void -do_publish (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - unsigned int links_succeeded, - unsigned int links_failed) +do_publish(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + unsigned int links_succeeded, + unsigned int links_failed) { unsigned int i; - if (NULL != strstr (progname, "cadet")) + if (NULL != strstr(progname, "cadet")) anonymity_level = 0; else anonymity_level = 1; - GNUNET_assert (NUM_DAEMONS == num_peers); - for (i=0;i. SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file fs/test_plugin_block_fs.c * @brief test for plugin_block_fs.c @@ -27,64 +27,64 @@ static int -test_fs (struct GNUNET_BLOCK_Context *ctx) +test_fs(struct GNUNET_BLOCK_Context *ctx) { struct GNUNET_HashCode key; char block[4]; - memset (block, 1, sizeof (block)); + memset(block, 1, sizeof(block)); if (GNUNET_OK != - GNUNET_BLOCK_get_key (ctx, GNUNET_BLOCK_TYPE_FS_DBLOCK, block, - sizeof (block), &key)) + GNUNET_BLOCK_get_key(ctx, GNUNET_BLOCK_TYPE_FS_DBLOCK, block, + sizeof(block), &key)) return 1; if (GNUNET_BLOCK_EVALUATION_OK_LAST != - GNUNET_BLOCK_evaluate (ctx, - GNUNET_BLOCK_TYPE_FS_DBLOCK, - NULL, - GNUNET_BLOCK_EO_NONE, - &key, - NULL, 0, - block, sizeof (block))) + GNUNET_BLOCK_evaluate(ctx, + GNUNET_BLOCK_TYPE_FS_DBLOCK, + NULL, + GNUNET_BLOCK_EO_NONE, + &key, + NULL, 0, + block, sizeof(block))) return 2; if (GNUNET_BLOCK_EVALUATION_REQUEST_VALID != - GNUNET_BLOCK_evaluate (ctx, - GNUNET_BLOCK_TYPE_FS_DBLOCK, - NULL, - GNUNET_BLOCK_EO_NONE, - &key, - NULL, 0, - NULL, 0)) + GNUNET_BLOCK_evaluate(ctx, + GNUNET_BLOCK_TYPE_FS_DBLOCK, + NULL, + GNUNET_BLOCK_EO_NONE, + &key, + NULL, 0, + NULL, 0)) return 4; - GNUNET_log_skip (1, GNUNET_NO); + GNUNET_log_skip(1, GNUNET_NO); if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID != - GNUNET_BLOCK_evaluate (ctx, - GNUNET_BLOCK_TYPE_FS_DBLOCK, - NULL, - GNUNET_BLOCK_EO_NONE, - &key, - "bogus", 5, - NULL, 0)) + GNUNET_BLOCK_evaluate(ctx, + GNUNET_BLOCK_TYPE_FS_DBLOCK, + NULL, + GNUNET_BLOCK_EO_NONE, + &key, + "bogus", 5, + NULL, 0)) return 8; - GNUNET_log_skip (0, GNUNET_YES); + GNUNET_log_skip(0, GNUNET_YES); return 0; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { int ret; struct GNUNET_BLOCK_Context *ctx; struct GNUNET_CONFIGURATION_Handle *cfg; - GNUNET_log_setup ("test-block", "WARNING", NULL); - cfg = GNUNET_CONFIGURATION_create (); - ctx = GNUNET_BLOCK_context_create (cfg); - ret = test_fs (ctx); - GNUNET_BLOCK_context_destroy (ctx); - GNUNET_CONFIGURATION_destroy (cfg); + GNUNET_log_setup("test-block", "WARNING", NULL); + cfg = GNUNET_CONFIGURATION_create(); + ctx = GNUNET_BLOCK_context_create(cfg); + ret = test_fs(ctx); + GNUNET_BLOCK_context_destroy(ctx); + GNUNET_CONFIGURATION_destroy(cfg); if (ret != 0) - fprintf (stderr, "Tests failed: %d\n", ret); + fprintf(stderr, "Tests failed: %d\n", ret); return ret; } diff --git a/src/gns/gns.h b/src/gns/gns.h index 3b41de83c..8465f49f9 100644 --- a/src/gns/gns.h +++ b/src/gns/gns.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -33,8 +33,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Message from client to GNS service to lookup records. */ -struct LookupMessage -{ +struct LookupMessage { /** * Header of type #GNUNET_MESSAGE_TYPE_GNS_LOOKUP */ @@ -73,10 +72,9 @@ struct LookupMessage /** * Message from GNS service to client: new results. */ -struct LookupResultMessage -{ +struct LookupResultMessage { /** - * Header of type #GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT + * Header of type #GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT */ struct GNUNET_MessageHeader header; @@ -91,7 +89,6 @@ struct LookupResultMessage uint32_t rd_count GNUNET_PACKED; /* followed by rd_count GNUNET_GNSRECORD_Data structs*/ - }; diff --git a/src/gns/gns_api.c b/src/gns/gns_api.c index ba83b73cd..62f250959 100644 --- a/src/gns/gns_api.c +++ b/src/gns/gns_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/gns_api.c * @brief library to access the GNS service @@ -34,14 +34,12 @@ #include "gns_api.h" -#define LOG(kind,...) GNUNET_log_from (kind, "gns-api",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "gns-api", __VA_ARGS__) /** * Handle to a lookup request */ -struct GNUNET_GNS_LookupRequest -{ - +struct GNUNET_GNS_LookupRequest { /** * DLL */ @@ -76,7 +74,6 @@ struct GNUNET_GNS_LookupRequest * request id */ uint32_t r_id; - }; @@ -86,7 +83,7 @@ struct GNUNET_GNS_LookupRequest * @param handle the handle to the GNS service */ static void -reconnect (struct GNUNET_GNS_Handle *handle); +reconnect(struct GNUNET_GNS_Handle *handle); /** @@ -95,12 +92,12 @@ reconnect (struct GNUNET_GNS_Handle *handle); * @param cls the handle */ static void -reconnect_task (void *cls) +reconnect_task(void *cls) { struct GNUNET_GNS_Handle *handle = cls; handle->reconnect_task = NULL; - reconnect (handle); + reconnect(handle); } @@ -110,16 +107,16 @@ reconnect_task (void *cls) * @param handle our handle */ static void -force_reconnect (struct GNUNET_GNS_Handle *handle) +force_reconnect(struct GNUNET_GNS_Handle *handle) { - GNUNET_MQ_destroy (handle->mq); + GNUNET_MQ_destroy(handle->mq); handle->mq = NULL; handle->reconnect_backoff - = GNUNET_TIME_STD_BACKOFF (handle->reconnect_backoff); + = GNUNET_TIME_STD_BACKOFF(handle->reconnect_backoff); handle->reconnect_task - = GNUNET_SCHEDULER_add_delayed (handle->reconnect_backoff, - &reconnect_task, - handle); + = GNUNET_SCHEDULER_add_delayed(handle->reconnect_backoff, + &reconnect_task, + handle); } @@ -132,15 +129,15 @@ force_reconnect (struct GNUNET_GNS_Handle *handle) * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_GNS_Handle *handle = cls; - LOG (GNUNET_ERROR_TYPE_WARNING, - "Problem with message queue. error: %i\n", - error); - force_reconnect (handle); + LOG(GNUNET_ERROR_TYPE_WARNING, + "Problem with message queue. error: %i\n", + error); + force_reconnect(handle); } @@ -151,23 +148,23 @@ mq_error_handler (void *cls, * @param loookup_msg the incoming message */ static int -check_result (void *cls, - const struct LookupResultMessage *lookup_msg) +check_result(void *cls, + const struct LookupResultMessage *lookup_msg) { - size_t mlen = ntohs (lookup_msg->header.size) - sizeof (*lookup_msg); - uint32_t rd_count = ntohl (lookup_msg->rd_count); + size_t mlen = ntohs(lookup_msg->header.size) - sizeof(*lookup_msg); + uint32_t rd_count = ntohl(lookup_msg->rd_count); struct GNUNET_GNSRECORD_Data rd[rd_count]; - (void) cls; + (void)cls; if (GNUNET_SYSERR == - GNUNET_GNSRECORD_records_deserialize (mlen, - (const char*) &lookup_msg[1], - rd_count, - rd)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + GNUNET_GNSRECORD_records_deserialize(mlen, + (const char*)&lookup_msg[1], + rd_count, + rd)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -179,21 +176,21 @@ check_result (void *cls, * @param loookup_msg the incoming message */ static void -handle_result (void *cls, - const struct LookupResultMessage *lookup_msg) +handle_result(void *cls, + const struct LookupResultMessage *lookup_msg) { struct GNUNET_GNS_Handle *handle = cls; - size_t mlen = ntohs (lookup_msg->header.size) - sizeof (*lookup_msg); - uint32_t rd_count = ntohl (lookup_msg->rd_count); + size_t mlen = ntohs(lookup_msg->header.size) - sizeof(*lookup_msg); + uint32_t rd_count = ntohl(lookup_msg->rd_count); struct GNUNET_GNSRECORD_Data rd[rd_count]; - uint32_t r_id = ntohl (lookup_msg->id); + uint32_t r_id = ntohl(lookup_msg->id); struct GNUNET_GNS_LookupRequest *lr; GNUNET_GNS_LookupResultProcessor proc; void *proc_cls; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received lookup reply from GNS service (%u records)\n", - (unsigned int) rd_count); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received lookup reply from GNS service (%u records)\n", + (unsigned int)rd_count); for (lr = handle->lookup_head; NULL != lr; lr = lr->next) if (lr->r_id == r_id) break; @@ -202,20 +199,20 @@ handle_result (void *cls, proc = lr->lookup_proc; proc_cls = lr->proc_cls; - GNUNET_assert (GNUNET_OK == - GNUNET_GNSRECORD_records_deserialize (mlen, - (const char*) &lookup_msg[1], - rd_count, - rd)); - proc (proc_cls, - rd_count, - rd); - GNUNET_CONTAINER_DLL_remove (handle->lookup_head, - handle->lookup_tail, - lr); + GNUNET_assert(GNUNET_OK == + GNUNET_GNSRECORD_records_deserialize(mlen, + (const char*)&lookup_msg[1], + rd_count, + rd)); + proc(proc_cls, + rd_count, + rd); + GNUNET_CONTAINER_DLL_remove(handle->lookup_head, + handle->lookup_tail, + lr); if (NULL != lr->env) - GNUNET_MQ_discard (lr->env); - GNUNET_free (lr); + GNUNET_MQ_discard(lr->env); + GNUNET_free(lr); } @@ -225,31 +222,31 @@ handle_result (void *cls, * @param handle the handle to the GNS service */ static void -reconnect (struct GNUNET_GNS_Handle *handle) +reconnect(struct GNUNET_GNS_Handle *handle) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (result, - GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT, - struct LookupResultMessage, - handle), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(result, + GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT, + struct LookupResultMessage, + handle), + GNUNET_MQ_handler_end() }; - GNUNET_assert (NULL == handle->mq); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Trying to connect to GNS\n"); - handle->mq = GNUNET_CLIENT_connect (handle->cfg, - "gns", - handlers, - &mq_error_handler, - handle); + GNUNET_assert(NULL == handle->mq); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Trying to connect to GNS\n"); + handle->mq = GNUNET_CLIENT_connect(handle->cfg, + "gns", + handlers, + &mq_error_handler, + handle); if (NULL == handle->mq) return; for (struct GNUNET_GNS_LookupRequest *lh = handle->lookup_head; NULL != lh; lh = lh->next) - GNUNET_MQ_send_copy (handle->mq, - lh->env); + GNUNET_MQ_send_copy(handle->mq, + lh->env); } @@ -260,18 +257,18 @@ reconnect (struct GNUNET_GNS_Handle *handle) * @return handle to the GNS service, or NULL on error */ struct GNUNET_GNS_Handle * -GNUNET_GNS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_GNS_connect(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_GNS_Handle *handle; - handle = GNUNET_new (struct GNUNET_GNS_Handle); + handle = GNUNET_new(struct GNUNET_GNS_Handle); handle->cfg = cfg; - reconnect (handle); + reconnect(handle); if (NULL == handle->mq) - { - GNUNET_free (handle); - return NULL; - } + { + GNUNET_free(handle); + return NULL; + } return handle; } @@ -282,20 +279,20 @@ GNUNET_GNS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) * @param handle handle of the GNS connection to stop */ void -GNUNET_GNS_disconnect (struct GNUNET_GNS_Handle *handle) +GNUNET_GNS_disconnect(struct GNUNET_GNS_Handle *handle) { if (NULL != handle->mq) - { - GNUNET_MQ_destroy (handle->mq); - handle->mq = NULL; - } + { + GNUNET_MQ_destroy(handle->mq); + handle->mq = NULL; + } if (NULL != handle->reconnect_task) - { - GNUNET_SCHEDULER_cancel (handle->reconnect_task); - handle->reconnect_task = NULL; - } - GNUNET_assert (NULL == handle->lookup_head); - GNUNET_free (handle); + { + GNUNET_SCHEDULER_cancel(handle->reconnect_task); + handle->reconnect_task = NULL; + } + GNUNET_assert(NULL == handle->lookup_head); + GNUNET_free(handle); } @@ -306,17 +303,17 @@ GNUNET_GNS_disconnect (struct GNUNET_GNS_Handle *handle) * @return closure from the lookup result processor */ void * -GNUNET_GNS_lookup_cancel (struct GNUNET_GNS_LookupRequest *lr) +GNUNET_GNS_lookup_cancel(struct GNUNET_GNS_LookupRequest *lr) { struct GNUNET_GNS_Handle *handle = lr->gns_handle; void *ret; - GNUNET_CONTAINER_DLL_remove (handle->lookup_head, - handle->lookup_tail, - lr); - GNUNET_MQ_discard (lr->env); + GNUNET_CONTAINER_DLL_remove(handle->lookup_head, + handle->lookup_tail, + lr); + GNUNET_MQ_discard(lr->env); ret = lr->proc_cls; - GNUNET_free (lr); + GNUNET_free(lr); return ret; } @@ -334,13 +331,13 @@ GNUNET_GNS_lookup_cancel (struct GNUNET_GNS_LookupRequest *lr) * @return handle to the get request */ struct GNUNET_GNS_LookupRequest* -GNUNET_GNS_lookup (struct GNUNET_GNS_Handle *handle, - const char *name, - const struct GNUNET_CRYPTO_EcdsaPublicKey *zone, - uint32_t type, - enum GNUNET_GNS_LocalOptions options, - GNUNET_GNS_LookupResultProcessor proc, - void *proc_cls) +GNUNET_GNS_lookup(struct GNUNET_GNS_Handle *handle, + const char *name, + const struct GNUNET_CRYPTO_EcdsaPublicKey *zone, + uint32_t type, + enum GNUNET_GNS_LocalOptions options, + GNUNET_GNS_LookupResultProcessor proc, + void *proc_cls) { /* IPC to shorten gns names, return shorten_handle */ struct LookupMessage *lookup_msg; @@ -348,40 +345,40 @@ GNUNET_GNS_lookup (struct GNUNET_GNS_Handle *handle, size_t nlen; if (NULL == name) - { - GNUNET_break (0); - return NULL; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Trying to lookup `%s' in GNS\n", - name); - nlen = strlen (name) + 1; - if (nlen >= GNUNET_MAX_MESSAGE_SIZE - sizeof (*lr)) - { - GNUNET_break (0); - return NULL; - } - lr = GNUNET_new (struct GNUNET_GNS_LookupRequest); + { + GNUNET_break(0); + return NULL; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Trying to lookup `%s' in GNS\n", + name); + nlen = strlen(name) + 1; + if (nlen >= GNUNET_MAX_MESSAGE_SIZE - sizeof(*lr)) + { + GNUNET_break(0); + return NULL; + } + lr = GNUNET_new(struct GNUNET_GNS_LookupRequest); lr->gns_handle = handle; lr->lookup_proc = proc; lr->proc_cls = proc_cls; lr->r_id = handle->r_id_gen++; - lr->env = GNUNET_MQ_msg_extra (lookup_msg, - nlen, - GNUNET_MESSAGE_TYPE_GNS_LOOKUP); - lookup_msg->id = htonl (lr->r_id); - lookup_msg->options = htons ((uint16_t) options); + lr->env = GNUNET_MQ_msg_extra(lookup_msg, + nlen, + GNUNET_MESSAGE_TYPE_GNS_LOOKUP); + lookup_msg->id = htonl(lr->r_id); + lookup_msg->options = htons((uint16_t)options); lookup_msg->zone = *zone; - lookup_msg->type = htonl (type); - GNUNET_memcpy (&lookup_msg[1], - name, - nlen); - GNUNET_CONTAINER_DLL_insert (handle->lookup_head, - handle->lookup_tail, - lr); + lookup_msg->type = htonl(type); + GNUNET_memcpy(&lookup_msg[1], + name, + nlen); + GNUNET_CONTAINER_DLL_insert(handle->lookup_head, + handle->lookup_tail, + lr); if (NULL != handle->mq) - GNUNET_MQ_send_copy (handle->mq, - lr->env); + GNUNET_MQ_send_copy(handle->mq, + lr->env); return lr; } diff --git a/src/gns/gns_api.h b/src/gns/gns_api.h index 40fdbfacd..7e07f909f 100644 --- a/src/gns/gns_api.h +++ b/src/gns/gns_api.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/gns_api.h * @brief shared data structures of libgnunetgns @@ -32,9 +32,7 @@ /** * Connection to the GNS service. */ -struct GNUNET_GNS_Handle -{ - +struct GNUNET_GNS_Handle { /** * Configuration to use. */ @@ -69,7 +67,6 @@ struct GNUNET_GNS_Handle * Request Id generator. Incremented by one for each request. */ uint32_t r_id_gen; - }; diff --git a/src/gns/gns_tld_api.c b/src/gns/gns_tld_api.c index f36b31acf..0692199e3 100644 --- a/src/gns/gns_tld_api.c +++ b/src/gns/gns_tld_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/gns_tld_api.c * @brief library to access the GNS service, including TLD lookup @@ -35,15 +35,13 @@ #include "gns_api.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "gns-tld-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "gns-tld-api", __VA_ARGS__) /** * Handle to a lookup request */ -struct GNUNET_GNS_LookupWithTldRequest -{ - +struct GNUNET_GNS_LookupWithTldRequest { /** * handle to gns */ @@ -105,11 +103,11 @@ struct GNUNET_GNS_LookupWithTldRequest * or @a name if @a name does not contain a "." */ static const char * -get_tld (const char *name) +get_tld(const char *name) { const char *tld; - tld = strrchr (name, (unsigned char) '.'); + tld = strrchr(name, (unsigned char)'.'); if (NULL == tld) tld = name; else @@ -125,18 +123,18 @@ get_tld (const char *name) * @param tld what to eat (can be more than just the tld) */ static void -eat_tld (char *name, const char *tld) +eat_tld(char *name, const char *tld) { - GNUNET_assert (0 < strlen (name)); - if ((NULL == tld) || (strlen (name) == strlen (tld))) - { - strcpy (name, GNUNET_GNS_EMPTY_LABEL_AT); - } + GNUNET_assert(0 < strlen(name)); + if ((NULL == tld) || (strlen(name) == strlen(tld))) + { + strcpy(name, GNUNET_GNS_EMPTY_LABEL_AT); + } else - { - GNUNET_assert (strlen (tld) < strlen (name)); - name[strlen (name) - strlen (tld) - 1] = '\0'; - } + { + GNUNET_assert(strlen(tld) < strlen(name)); + name[strlen(name) - strlen(tld) - 1] = '\0'; + } } @@ -148,15 +146,15 @@ eat_tld (char *name, const char *tld) * @param rd array of @a rd_count records with the results */ static void -process_lookup_result (void *cls, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +process_lookup_result(void *cls, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_GNS_LookupWithTldRequest *ltr = cls; ltr->lr = NULL; - ltr->lookup_proc (ltr->lookup_proc_cls, GNUNET_YES, rd_count, rd); - GNUNET_GNS_lookup_with_tld_cancel (ltr); + ltr->lookup_proc(ltr->lookup_proc_cls, GNUNET_YES, rd_count, rd); + GNUNET_GNS_lookup_with_tld_cancel(ltr); } @@ -167,16 +165,16 @@ process_lookup_result (void *cls, * @param pkey public key to use for the zone, can be NULL */ static void -lookup_with_public_key (struct GNUNET_GNS_LookupWithTldRequest *ltr, - const struct GNUNET_CRYPTO_EcdsaPublicKey *pkey) +lookup_with_public_key(struct GNUNET_GNS_LookupWithTldRequest *ltr, + const struct GNUNET_CRYPTO_EcdsaPublicKey *pkey) { - ltr->lr = GNUNET_GNS_lookup (ltr->gns_handle, - ltr->name, - pkey, - ltr->type, - ltr->options, - &process_lookup_result, - ltr); + ltr->lr = GNUNET_GNS_lookup(ltr->gns_handle, + ltr->name, + pkey, + ltr->type, + ltr->options, + &process_lookup_result, + ltr); } @@ -190,38 +188,38 @@ lookup_with_public_key (struct GNUNET_GNS_LookupWithTldRequest *ltr, * @param name name of the ego */ static void -identity_zone_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv, - const char *ego_name) +identity_zone_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv, + const char *ego_name) { struct GNUNET_GNS_LookupWithTldRequest *ltr = cls; struct GNUNET_CRYPTO_EcdsaPublicKey pkey; ltr->id_co = NULL; if (NULL == priv) - { - /* no matching ego found */ - ltr->lookup_proc (ltr->lookup_proc_cls, GNUNET_NO, 0, NULL); - return; - } + { + /* no matching ego found */ + ltr->lookup_proc(ltr->lookup_proc_cls, GNUNET_NO, 0, NULL); + return; + } /* Final case: TLD matches one of our egos */ - if (0 == strcmp (ltr->name, ego_name)) - { - /* name matches ego name perfectly, only "@" remains */ - strcpy (ltr->name, GNUNET_GNS_EMPTY_LABEL_AT); - } + if (0 == strcmp(ltr->name, ego_name)) + { + /* name matches ego name perfectly, only "@" remains */ + strcpy(ltr->name, GNUNET_GNS_EMPTY_LABEL_AT); + } else - { - GNUNET_assert (strlen (ego_name) < strlen (ltr->name)); - ltr->name[strlen (ltr->name) - strlen (ego_name) - 1] = '\0'; - } + { + GNUNET_assert(strlen(ego_name) < strlen(ltr->name)); + ltr->name[strlen(ltr->name) - strlen(ego_name) - 1] = '\0'; + } /* if the name is of the form 'label' (and not 'label.SUBDOMAIN'), never go to the DHT */ - if (NULL == strchr (ltr->name, (unsigned char) '.')) + if (NULL == strchr(ltr->name, (unsigned char)'.')) ltr->options = GNUNET_GNS_LO_NO_DHT; else ltr->options = GNUNET_GNS_LO_LOCAL_MASTER; - GNUNET_CRYPTO_ecdsa_key_get_public (priv, &pkey); - lookup_with_public_key (ltr, &pkey); + GNUNET_CRYPTO_ecdsa_key_get_public(priv, &pkey); + lookup_with_public_key(ltr, &pkey); } @@ -239,12 +237,12 @@ identity_zone_cb (void *cls, * @return handle to the get request, NULL on error (i.e. bad configuration) */ struct GNUNET_GNS_LookupWithTldRequest * -GNUNET_GNS_lookup_with_tld (struct GNUNET_GNS_Handle *handle, - const char *name, - uint32_t type, - enum GNUNET_GNS_LocalOptions options, - GNUNET_GNS_LookupResultProcessor2 proc, - void *proc_cls) +GNUNET_GNS_lookup_with_tld(struct GNUNET_GNS_Handle *handle, + const char *name, + uint32_t type, + enum GNUNET_GNS_LocalOptions options, + GNUNET_GNS_LookupResultProcessor2 proc, + void *proc_cls) { struct GNUNET_GNS_LookupWithTldRequest *ltr; const char *tld; @@ -252,70 +250,70 @@ GNUNET_GNS_lookup_with_tld (struct GNUNET_GNS_Handle *handle, char *zonestr; struct GNUNET_CRYPTO_EcdsaPublicKey pkey; - ltr = GNUNET_new (struct GNUNET_GNS_LookupWithTldRequest); + ltr = GNUNET_new(struct GNUNET_GNS_LookupWithTldRequest); ltr->gns_handle = handle; - ltr->name = GNUNET_strdup (name); + ltr->name = GNUNET_strdup(name); ltr->type = type; ltr->options = options; ltr->lookup_proc = proc; ltr->lookup_proc_cls = proc_cls; /* start with trivial case: TLD is zkey */ - tld = get_tld (ltr->name); + tld = get_tld(ltr->name); if (GNUNET_OK == - GNUNET_CRYPTO_ecdsa_public_key_from_string (tld, strlen (tld), &pkey)) - { - eat_tld (ltr->name, tld); - lookup_with_public_key (ltr, &pkey); - return ltr; - } + GNUNET_CRYPTO_ecdsa_public_key_from_string(tld, strlen(tld), &pkey)) + { + eat_tld(ltr->name, tld); + lookup_with_public_key(ltr, &pkey); + return ltr; + } /* second case: domain is mapped in our configuration file */ for (const char *domain = name; NULL != domain; - domain = strchr (domain, (unsigned char) '.')) - { - if ('.' == domain[0]) - domain++; - GNUNET_asprintf (&dot_tld, ".%s", domain); - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (handle->cfg, - "gns", - dot_tld, - &zonestr)) + domain = strchr(domain, (unsigned char)'.')) { - if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (zonestr, - strlen (zonestr), - &pkey)) - { - GNUNET_log_config_invalid ( - GNUNET_ERROR_TYPE_ERROR, - "gns", - dot_tld, - _ ("Expected a base32-encoded public zone key\n")); - GNUNET_free (zonestr); - GNUNET_free (dot_tld); - GNUNET_free (ltr->name); - GNUNET_free (ltr); - return NULL; - } - eat_tld (ltr->name, &dot_tld[1]); - GNUNET_free (zonestr); - GNUNET_free (dot_tld); - lookup_with_public_key (ltr, &pkey); - return ltr; + if ('.' == domain[0]) + domain++; + GNUNET_asprintf(&dot_tld, ".%s", domain); + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(handle->cfg, + "gns", + dot_tld, + &zonestr)) + { + if (GNUNET_OK != + GNUNET_CRYPTO_ecdsa_public_key_from_string(zonestr, + strlen(zonestr), + &pkey)) + { + GNUNET_log_config_invalid( + GNUNET_ERROR_TYPE_ERROR, + "gns", + dot_tld, + _("Expected a base32-encoded public zone key\n")); + GNUNET_free(zonestr); + GNUNET_free(dot_tld); + GNUNET_free(ltr->name); + GNUNET_free(ltr); + return NULL; + } + eat_tld(ltr->name, &dot_tld[1]); + GNUNET_free(zonestr); + GNUNET_free(dot_tld); + lookup_with_public_key(ltr, &pkey); + return ltr; + } + GNUNET_free(dot_tld); } - GNUNET_free (dot_tld); - } ltr->id_co = - GNUNET_IDENTITY_ego_lookup_by_suffix (ltr->gns_handle->cfg, - ltr->name, - &identity_zone_cb, - ltr); + GNUNET_IDENTITY_ego_lookup_by_suffix(ltr->gns_handle->cfg, + ltr->name, + &identity_zone_cb, + ltr); if (NULL == ltr->id_co) - { - GNUNET_free (ltr->name); - GNUNET_free (ltr); - return NULL; - } + { + GNUNET_free(ltr->name); + GNUNET_free(ltr); + return NULL; + } return ltr; } @@ -327,23 +325,23 @@ GNUNET_GNS_lookup_with_tld (struct GNUNET_GNS_Handle *handle, * @return closure from the lookup result processor */ void * -GNUNET_GNS_lookup_with_tld_cancel (struct GNUNET_GNS_LookupWithTldRequest *ltr) +GNUNET_GNS_lookup_with_tld_cancel(struct GNUNET_GNS_LookupWithTldRequest *ltr) { void *ret = ltr->lookup_proc_cls; if (NULL != ltr->id_co) - { - GNUNET_IDENTITY_ego_lookup_by_suffix_cancel (ltr->id_co); - ltr->id_co = NULL; - } + { + GNUNET_IDENTITY_ego_lookup_by_suffix_cancel(ltr->id_co); + ltr->id_co = NULL; + } if (NULL != ltr->lr) - { - GNUNET_GNS_lookup_cancel (ltr->lr); - ltr->lr = NULL; - } - GNUNET_free_non_null (ltr->longest_match); - GNUNET_free (ltr->name); - GNUNET_free (ltr); + { + GNUNET_GNS_lookup_cancel(ltr->lr); + ltr->lr = NULL; + } + GNUNET_free_non_null(ltr->longest_match); + GNUNET_free(ltr->name); + GNUNET_free(ltr); return ret; } diff --git a/src/gns/gnunet-bcd.c b/src/gns/gnunet-bcd.c index 368afbbf5..181c30d8d 100644 --- a/src/gns/gnunet-bcd.c +++ b/src/gns/gnunet-bcd.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/gnunet-bcd.c @@ -81,8 +81,7 @@ static char *resfile; static uint16_t port = 8888; -struct Entry -{ +struct Entry { const char *formname; const char *texname; }; @@ -92,175 +91,175 @@ struct Entry * Main request handler. */ static int -access_handler_callback (void *cls, - struct MHD_Connection *connection, - const char *url, - const char *method, - const char *version, - const char *upload_data, - size_t *upload_data_size, - void **con_cls) +access_handler_callback(void *cls, + struct MHD_Connection *connection, + const char *url, + const char *method, + const char *version, + const char *upload_data, + size_t *upload_data_size, + void **con_cls) { static int dummy; - static const struct Entry map[] = {{"prefix", "prefix"}, - {"name", "name"}, - {"suffix", "suffix"}, - {"street", "street"}, - {"city", "city"}, - {"phone", "phone"}, - {"fax", "fax"}, - {"email", "email"}, - {"homepage", "homepage"}, - {"orga", "orga"}, - {"departmenti18n", "departmentde"}, - {"departmenten", "departmenten"}, - {"subdepartmenti18n", "subdepartmentde"}, - {"subdepartmenten", "subdepartmenten"}, - {"jobtitlei18n", "jobtitlegerman"}, - {"jobtitleen", "jobtitleenglish"}, - {"subdepartmenten", "subdepartmenten"}, - {NULL, NULL}}; - - (void) cls; - (void) version; - (void) upload_data; - (void) upload_data_size; - if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Refusing `%s' request to HTTP server\n"), - method); - return MHD_NO; - } - if (NULL == *con_cls) - { - (*con_cls) = &dummy; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending 100 CONTINUE reply\n"); - return MHD_YES; /* send 100 continue */ - } - if (0 == strcasecmp (url, "/")) - return MHD_queue_response (connection, MHD_HTTP_OK, main_response); - if (0 == strcasecmp (url, "/submit.pdf")) - { - unsigned int i; - char *p; - char *tmp; - char *deffile; - struct GNUNET_CRYPTO_EcdsaPublicKey pub; - size_t slen; - FILE *f; - struct stat st; - struct MHD_Response *response; - int fd; - int ret; - - const char *gpg_fp = MHD_lookup_connection_value (connection, - MHD_GET_ARGUMENT_KIND, - "gpgfingerprint"); - const char *gns_nick = MHD_lookup_connection_value (connection, - MHD_GET_ARGUMENT_KIND, - "gnsnick"); - const char *gnskey = - MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "gnskey"); - if ((NULL == gnskey) || - (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (gnskey, - strlen (gnskey), - &pub))) - { - return MHD_queue_response (connection, - MHD_HTTP_OK, - invalid_gnskey_response); - } - tmp = GNUNET_DISK_mkdtemp (gnskey); - if (NULL == tmp) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mktemp", gnskey); - return MHD_NO; - } - GNUNET_asprintf (&deffile, "%s%s%s", tmp, DIR_SEPARATOR_STR, "def.tex"); - f = fopen (deffile, "w"); - if (NULL == f) + static const struct Entry map[] = { { "prefix", "prefix" }, + { "name", "name" }, + { "suffix", "suffix" }, + { "street", "street" }, + { "city", "city" }, + { "phone", "phone" }, + { "fax", "fax" }, + { "email", "email" }, + { "homepage", "homepage" }, + { "orga", "orga" }, + { "departmenti18n", "departmentde" }, + { "departmenten", "departmenten" }, + { "subdepartmenti18n", "subdepartmentde" }, + { "subdepartmenten", "subdepartmenten" }, + { "jobtitlei18n", "jobtitlegerman" }, + { "jobtitleen", "jobtitleenglish" }, + { "subdepartmenten", "subdepartmenten" }, + { NULL, NULL } }; + + (void)cls; + (void)version; + (void)upload_data; + (void)upload_data_size; + if (0 != strcmp(method, MHD_HTTP_METHOD_GET)) { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", deffile); - GNUNET_free (deffile); - GNUNET_DISK_directory_remove (tmp); - GNUNET_free (tmp); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Refusing `%s' request to HTTP server\n"), + method); return MHD_NO; } - for (i = 0; NULL != map[i].formname; i++) - { - const char *val = MHD_lookup_connection_value (connection, - MHD_GET_ARGUMENT_KIND, - map[i].formname); - if (NULL != val) - fprintf (f, "\\def\\%s{%s}\n", map[i].texname, val); - else - fprintf (f, "\\def\\%s{}\n", map[i].texname); - } - if (NULL != gpg_fp) - { - char *gpg1; - char *gpg2; - - slen = strlen (gpg_fp); - gpg1 = GNUNET_strndup (gpg_fp, slen / 2); - gpg2 = GNUNET_strdup (&gpg_fp[slen / 2]); - fprintf (f, "\\def\\gpglineone{%s}\n\\def\\gpglinetwo{%s}\n", gpg1, gpg2); - GNUNET_free (gpg2); - GNUNET_free (gpg1); - } - fprintf (f, - "\\def\\gns{%s/%s}\n", - gnskey, - (NULL == gns_nick) ? "" : gns_nick); - fclose (f); - GNUNET_asprintf ( - &p, - "cd %s; cp %s gns-bcd.tex | pdflatex --enable-write18 gns-bcd.tex > /dev/null 2> /dev/null", - tmp, - resfile); - GNUNET_free (deffile); - ret = system (p); - if (WIFSIGNALED (ret) || (0 != WEXITSTATUS (ret))) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "system", p); - GNUNET_asprintf (&deffile, "%s%s%s", tmp, DIR_SEPARATOR_STR, "gns-bcd.pdf"); - fd = open (deffile, O_RDONLY); - if (-1 == fd) + if (NULL == *con_cls) { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", deffile); - GNUNET_free (deffile); - GNUNET_free (p); - GNUNET_DISK_directory_remove (tmp); - GNUNET_free (tmp); - return MHD_NO; + (*con_cls) = &dummy; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending 100 CONTINUE reply\n"); + return MHD_YES; /* send 100 continue */ } - GNUNET_break (0 == STAT (deffile, &st)); - if (NULL == - (response = MHD_create_response_from_fd ((size_t) st.st_size, fd))) + if (0 == strcasecmp(url, "/")) + return MHD_queue_response(connection, MHD_HTTP_OK, main_response); + if (0 == strcasecmp(url, "/submit.pdf")) { - GNUNET_break (0); - GNUNET_break (0 == CLOSE (fd)); - GNUNET_free (deffile); - GNUNET_free (p); - GNUNET_DISK_directory_remove (tmp); - GNUNET_free (tmp); - return MHD_NO; - } - (void) MHD_add_response_header (response, + unsigned int i; + char *p; + char *tmp; + char *deffile; + struct GNUNET_CRYPTO_EcdsaPublicKey pub; + size_t slen; + FILE *f; + struct stat st; + struct MHD_Response *response; + int fd; + int ret; + + const char *gpg_fp = MHD_lookup_connection_value(connection, + MHD_GET_ARGUMENT_KIND, + "gpgfingerprint"); + const char *gns_nick = MHD_lookup_connection_value(connection, + MHD_GET_ARGUMENT_KIND, + "gnsnick"); + const char *gnskey = + MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "gnskey"); + if ((NULL == gnskey) || + (GNUNET_OK != + GNUNET_CRYPTO_ecdsa_public_key_from_string(gnskey, + strlen(gnskey), + &pub))) + { + return MHD_queue_response(connection, + MHD_HTTP_OK, + invalid_gnskey_response); + } + tmp = GNUNET_DISK_mkdtemp(gnskey); + if (NULL == tmp) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "mktemp", gnskey); + return MHD_NO; + } + GNUNET_asprintf(&deffile, "%s%s%s", tmp, DIR_SEPARATOR_STR, "def.tex"); + f = fopen(deffile, "w"); + if (NULL == f) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "open", deffile); + GNUNET_free(deffile); + GNUNET_DISK_directory_remove(tmp); + GNUNET_free(tmp); + return MHD_NO; + } + for (i = 0; NULL != map[i].formname; i++) + { + const char *val = MHD_lookup_connection_value(connection, + MHD_GET_ARGUMENT_KIND, + map[i].formname); + if (NULL != val) + fprintf(f, "\\def\\%s{%s}\n", map[i].texname, val); + else + fprintf(f, "\\def\\%s{}\n", map[i].texname); + } + if (NULL != gpg_fp) + { + char *gpg1; + char *gpg2; + + slen = strlen(gpg_fp); + gpg1 = GNUNET_strndup(gpg_fp, slen / 2); + gpg2 = GNUNET_strdup(&gpg_fp[slen / 2]); + fprintf(f, "\\def\\gpglineone{%s}\n\\def\\gpglinetwo{%s}\n", gpg1, gpg2); + GNUNET_free(gpg2); + GNUNET_free(gpg1); + } + fprintf(f, + "\\def\\gns{%s/%s}\n", + gnskey, + (NULL == gns_nick) ? "" : gns_nick); + fclose(f); + GNUNET_asprintf( + &p, + "cd %s; cp %s gns-bcd.tex | pdflatex --enable-write18 gns-bcd.tex > /dev/null 2> /dev/null", + tmp, + resfile); + GNUNET_free(deffile); + ret = system(p); + if (WIFSIGNALED(ret) || (0 != WEXITSTATUS(ret))) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "system", p); + GNUNET_asprintf(&deffile, "%s%s%s", tmp, DIR_SEPARATOR_STR, "gns-bcd.pdf"); + fd = open(deffile, O_RDONLY); + if (-1 == fd) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "open", deffile); + GNUNET_free(deffile); + GNUNET_free(p); + GNUNET_DISK_directory_remove(tmp); + GNUNET_free(tmp); + return MHD_NO; + } + GNUNET_break(0 == STAT(deffile, &st)); + if (NULL == + (response = MHD_create_response_from_fd((size_t)st.st_size, fd))) + { + GNUNET_break(0); + GNUNET_break(0 == CLOSE(fd)); + GNUNET_free(deffile); + GNUNET_free(p); + GNUNET_DISK_directory_remove(tmp); + GNUNET_free(tmp); + return MHD_NO; + } + (void)MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, "application/pdf"); - ret = MHD_queue_response (connection, MHD_HTTP_OK, response); - MHD_destroy_response (response); - GNUNET_free (deffile); - GNUNET_free (p); - GNUNET_DISK_directory_remove (tmp); - GNUNET_free (tmp); - return ret; - } - return MHD_queue_response (connection, - MHD_HTTP_NOT_FOUND, - not_found_response); + ret = MHD_queue_response(connection, MHD_HTTP_OK, response); + MHD_destroy_response(response); + GNUNET_free(deffile); + GNUNET_free(p); + GNUNET_DISK_directory_remove(tmp); + GNUNET_free(tmp); + return ret; + } + return MHD_queue_response(connection, + MHD_HTTP_NOT_FOUND, + not_found_response); } @@ -269,7 +268,7 @@ access_handler_callback (void *cls, * starts the task waiting for them. */ static struct GNUNET_SCHEDULER_Task * -prepare_daemon (struct MHD_Daemon *daemon_handle); +prepare_daemon(struct MHD_Daemon *daemon_handle); /** @@ -277,13 +276,13 @@ prepare_daemon (struct MHD_Daemon *daemon_handle); * and schedule the next run. */ static void -run_daemon (void *cls) +run_daemon(void *cls) { struct MHD_Daemon *daemon_handle = cls; http_task = NULL; - GNUNET_assert (MHD_YES == MHD_run (daemon_handle)); - http_task = prepare_daemon (daemon_handle); + GNUNET_assert(MHD_YES == MHD_run(daemon_handle)); + http_task = prepare_daemon(daemon_handle); } @@ -292,7 +291,7 @@ run_daemon (void *cls) * starts the task waiting for them. */ static struct GNUNET_SCHEDULER_Task * -prepare_daemon (struct MHD_Daemon *daemon_handle) +prepare_daemon(struct MHD_Daemon *daemon_handle) { struct GNUNET_SCHEDULER_Task *ret; fd_set rs; @@ -305,28 +304,28 @@ prepare_daemon (struct MHD_Daemon *daemon_handle) int haveto; struct GNUNET_TIME_Relative tv; - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); - wrs = GNUNET_NETWORK_fdset_create (); - wws = GNUNET_NETWORK_fdset_create (); + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); + wrs = GNUNET_NETWORK_fdset_create(); + wws = GNUNET_NETWORK_fdset_create(); max = -1; - GNUNET_assert (MHD_YES == MHD_get_fdset (daemon_handle, &rs, &ws, &es, &max)); - haveto = MHD_get_timeout (daemon_handle, &timeout); + GNUNET_assert(MHD_YES == MHD_get_fdset(daemon_handle, &rs, &ws, &es, &max)); + haveto = MHD_get_timeout(daemon_handle, &timeout); if (haveto == MHD_YES) - tv.rel_value_us = (uint64_t) timeout * 1000LL; + tv.rel_value_us = (uint64_t)timeout * 1000LL; else tv = GNUNET_TIME_UNIT_FOREVER_REL; - GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1); - GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1); - ret = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH, - tv, - wrs, - wws, - &run_daemon, - daemon_handle); - GNUNET_NETWORK_fdset_destroy (wrs); - GNUNET_NETWORK_fdset_destroy (wws); + GNUNET_NETWORK_fdset_copy_native(wrs, &rs, max + 1); + GNUNET_NETWORK_fdset_copy_native(wws, &ws, max + 1); + ret = GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_HIGH, + tv, + wrs, + wws, + &run_daemon, + daemon_handle); + GNUNET_NETWORK_fdset_destroy(wrs); + GNUNET_NETWORK_fdset_destroy(wws); return ret; } @@ -337,41 +336,41 @@ prepare_daemon (struct MHD_Daemon *daemon_handle) * @return #GNUNET_OK on success */ static int -server_start () +server_start() { if (0 == port) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Invalid port number %u. Exiting.\n"), - port); - return GNUNET_SYSERR; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Businesscard HTTP server starts on %u\n"), - port); - daemon_handle = MHD_start_daemon (MHD_USE_DUAL_STACK | MHD_USE_DEBUG, - port, - NULL /* accept_policy_callback */, - NULL, - &access_handler_callback, - NULL, - MHD_OPTION_CONNECTION_LIMIT, - (unsigned int) 512, - MHD_OPTION_PER_IP_CONNECTION_LIMIT, - (unsigned int) 2, - MHD_OPTION_CONNECTION_TIMEOUT, - (unsigned int) 60, - MHD_OPTION_CONNECTION_MEMORY_LIMIT, - (size_t) (16 * 1024), - MHD_OPTION_END); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Invalid port number %u. Exiting.\n"), + port); + return GNUNET_SYSERR; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Businesscard HTTP server starts on %u\n"), + port); + daemon_handle = MHD_start_daemon(MHD_USE_DUAL_STACK | MHD_USE_DEBUG, + port, + NULL /* accept_policy_callback */, + NULL, + &access_handler_callback, + NULL, + MHD_OPTION_CONNECTION_LIMIT, + (unsigned int)512, + MHD_OPTION_PER_IP_CONNECTION_LIMIT, + (unsigned int)2, + MHD_OPTION_CONNECTION_TIMEOUT, + (unsigned int)60, + MHD_OPTION_CONNECTION_MEMORY_LIMIT, + (size_t)(16 * 1024), + MHD_OPTION_END); if (NULL == daemon_handle) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Could not start businesscard HTTP server on port %u\n"), - (unsigned int) port); - return GNUNET_SYSERR; - } - http_task = prepare_daemon (daemon_handle); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Could not start businesscard HTTP server on port %u\n"), + (unsigned int)port); + return GNUNET_SYSERR; + } + http_task = prepare_daemon(daemon_handle); return GNUNET_OK; } @@ -380,40 +379,40 @@ server_start () * Stop HTTP server. */ static void -server_stop (void *cls) +server_stop(void *cls) { - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "HTTP server shutdown\n"); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "HTTP server shutdown\n"); if (NULL != http_task) - { - GNUNET_SCHEDULER_cancel (http_task); - http_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(http_task); + http_task = NULL; + } if (NULL != daemon_handle) - { - MHD_stop_daemon (daemon_handle); - daemon_handle = NULL; - } + { + MHD_stop_daemon(daemon_handle); + daemon_handle = NULL; + } if (NULL != main_response) - { - MHD_destroy_response (main_response); - main_response = NULL; - } + { + MHD_destroy_response(main_response); + main_response = NULL; + } if (NULL != invalid_gnskey_response) - { - MHD_destroy_response (invalid_gnskey_response); - invalid_gnskey_response = NULL; - } + { + MHD_destroy_response(invalid_gnskey_response); + invalid_gnskey_response = NULL; + } if (NULL != not_found_response) - { - MHD_destroy_response (not_found_response); - not_found_response = NULL; - } + { + MHD_destroy_response(not_found_response); + not_found_response = NULL; + } if (NULL != resfile) - { - GNUNET_free (resfile); - resfile = NULL; - } + { + GNUNET_free(resfile); + resfile = NULL; + } } @@ -426,66 +425,66 @@ server_stop (void *cls) * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { struct stat st; char *dir; char *fn; int fd; - (void) cls; - (void) args; - (void) cfgfile; + (void)cls; + (void)args; + (void)cfgfile; cfg = c; - dir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR); - GNUNET_assert (NULL != dir); - GNUNET_asprintf (&fn, "%s%s%s", dir, DIR_SEPARATOR_STR, "gns-bcd.html"); - GNUNET_asprintf (&resfile, "%s%s%s", dir, DIR_SEPARATOR_STR, "gns-bcd.tex"); - GNUNET_free (dir); - fd = open (fn, O_RDONLY); + dir = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_DATADIR); + GNUNET_assert(NULL != dir); + GNUNET_asprintf(&fn, "%s%s%s", dir, DIR_SEPARATOR_STR, "gns-bcd.html"); + GNUNET_asprintf(&resfile, "%s%s%s", dir, DIR_SEPARATOR_STR, "gns-bcd.tex"); + GNUNET_free(dir); + fd = open(fn, O_RDONLY); if (-1 == fd) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn); - GNUNET_free (fn); - return; - } - if (0 != STAT (fn, &st)) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn); - GNUNET_free (fn); - GNUNET_break (0 == CLOSE (fd)); - return; - } - GNUNET_free (fn); + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "open", fn); + GNUNET_free(fn); + return; + } + if (0 != STAT(fn, &st)) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "open", fn); + GNUNET_free(fn); + GNUNET_break(0 == CLOSE(fd)); + return; + } + GNUNET_free(fn); if (NULL == - (main_response = MHD_create_response_from_fd ((size_t) st.st_size, fd))) - { - GNUNET_break (0); - GNUNET_break (0 == CLOSE (fd)); - return; - } - (void) MHD_add_response_header (main_response, - MHD_HTTP_HEADER_CONTENT_TYPE, - "text/html"); + (main_response = MHD_create_response_from_fd((size_t)st.st_size, fd))) + { + GNUNET_break(0); + GNUNET_break(0 == CLOSE(fd)); + return; + } + (void)MHD_add_response_header(main_response, + MHD_HTTP_HEADER_CONTENT_TYPE, + "text/html"); invalid_gnskey_response = - MHD_create_response_from_buffer (strlen (INVALID_GNSKEY), - INVALID_GNSKEY, - MHD_RESPMEM_PERSISTENT); - (void) MHD_add_response_header (invalid_gnskey_response, - MHD_HTTP_HEADER_CONTENT_TYPE, - "text/html"); - not_found_response = MHD_create_response_from_buffer (strlen (NOT_FOUND), - NOT_FOUND, - MHD_RESPMEM_PERSISTENT); - (void) MHD_add_response_header (not_found_response, - MHD_HTTP_HEADER_CONTENT_TYPE, - "text/html"); - if (GNUNET_OK != server_start ()) + MHD_create_response_from_buffer(strlen(INVALID_GNSKEY), + INVALID_GNSKEY, + MHD_RESPMEM_PERSISTENT); + (void)MHD_add_response_header(invalid_gnskey_response, + MHD_HTTP_HEADER_CONTENT_TYPE, + "text/html"); + not_found_response = MHD_create_response_from_buffer(strlen(NOT_FOUND), + NOT_FOUND, + MHD_RESPMEM_PERSISTENT); + (void)MHD_add_response_header(not_found_response, + MHD_HTTP_HEADER_CONTENT_TYPE, + "text/html"); + if (GNUNET_OK != server_start()) return; - GNUNET_SCHEDULER_add_shutdown (&server_stop, NULL); + GNUNET_SCHEDULER_add_shutdown(&server_stop, NULL); } @@ -497,33 +496,33 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { - - GNUNET_GETOPT_option_uint16 ('p', - "port", - "PORT", - gettext_noop ( - "Run HTTP serve on port PORT (default is 8888)"), - &port), - GNUNET_GETOPT_OPTION_END}; + GNUNET_GETOPT_option_uint16('p', + "port", + "PORT", + gettext_noop( + "Run HTTP serve on port PORT (default is 8888)"), + &port), + GNUNET_GETOPT_OPTION_END + }; int ret; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; - GNUNET_log_setup ("gnunet-bcd", "WARNING", NULL); + GNUNET_log_setup("gnunet-bcd", "WARNING", NULL); ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-bcd", - _ ("GNUnet HTTP server to create business cards"), - options, - &run, - NULL)) - ? 0 - : 1; - GNUNET_free ((void *) argv); + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-bcd", + _("GNUnet HTTP server to create business cards"), + options, + &run, + NULL)) + ? 0 + : 1; + GNUNET_free((void *)argv); return ret; } diff --git a/src/gns/gnunet-dns2gns.c b/src/gns/gnunet-dns2gns.c index d2eabf02c..4058aba99 100644 --- a/src/gns/gnunet-dns2gns.c +++ b/src/gns/gnunet-dns2gns.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnunet-dns2gns.c * @brief DNS server that translates DNS requests to GNS @@ -37,8 +37,7 @@ /** * Data kept per request. */ -struct Request -{ +struct Request { /** * Socket to use for sending the reply. */ @@ -156,39 +155,39 @@ static const struct GNUNET_CONFIGURATION_Handle *cfg; * @param cls unused */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - (void) cls; + (void)cls; if (NULL != t4) - { - GNUNET_SCHEDULER_cancel (t4); - t4 = NULL; - } + { + GNUNET_SCHEDULER_cancel(t4); + t4 = NULL; + } if (NULL != t6) - { - GNUNET_SCHEDULER_cancel (t6); - t6 = NULL; - } + { + GNUNET_SCHEDULER_cancel(t6); + t6 = NULL; + } if (NULL != listen_socket4) - { - GNUNET_NETWORK_socket_close (listen_socket4); - listen_socket4 = NULL; - } + { + GNUNET_NETWORK_socket_close(listen_socket4); + listen_socket4 = NULL; + } if (NULL != listen_socket6) - { - GNUNET_NETWORK_socket_close (listen_socket6); - listen_socket6 = NULL; - } + { + GNUNET_NETWORK_socket_close(listen_socket6); + listen_socket6 = NULL; + } if (NULL != gns) - { - GNUNET_GNS_disconnect (gns); - gns = NULL; - } + { + GNUNET_GNS_disconnect(gns); + gns = NULL; + } if (NULL != dns_stub) - { - GNUNET_DNSSTUB_stop (dns_stub); - dns_stub = NULL; - } + { + GNUNET_DNSSTUB_stop(dns_stub); + dns_stub = NULL; + } } @@ -198,38 +197,38 @@ do_shutdown (void *cls) * @param request context for the request. */ static void -send_response (struct Request *request) +send_response(struct Request *request) { char *buf; size_t size; ssize_t sret; if (GNUNET_SYSERR == - GNUNET_DNSPARSER_pack (request->packet, - UINT16_MAX /* is this not too much? */, - &buf, - &size)) + GNUNET_DNSPARSER_pack(request->packet, + UINT16_MAX /* is this not too much? */, + &buf, + &size)) { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed to pack DNS response into UDP packet!\n")); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to pack DNS response into UDP packet!\n")); } else { - sret = GNUNET_NETWORK_socket_sendto (request->lsock, - buf, - size, - request->addr, - request->addr_len); - if ( (sret < 0) || - (size != (size_t) sret) ) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "sendto"); - GNUNET_free (buf); + sret = GNUNET_NETWORK_socket_sendto(request->lsock, + buf, + size, + request->addr, + request->addr_len); + if ((sret < 0) || + (size != (size_t)sret)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "sendto"); + GNUNET_free(buf); } - GNUNET_SCHEDULER_cancel (request->timeout_task); - GNUNET_DNSPARSER_free_packet (request->packet); - GNUNET_free (request->udp_msg); - GNUNET_free (request); + GNUNET_SCHEDULER_cancel(request->timeout_task); + GNUNET_DNSPARSER_free_packet(request->packet); + GNUNET_free(request->udp_msg); + GNUNET_free(request); } @@ -239,18 +238,18 @@ send_response (struct Request *request) * @param cls `struct Request *` of the request to clean up */ static void -do_timeout (void *cls) +do_timeout(void *cls) { struct Request *request = cls; if (NULL != request->packet) - GNUNET_DNSPARSER_free_packet (request->packet); + GNUNET_DNSPARSER_free_packet(request->packet); if (NULL != request->lookup) - GNUNET_GNS_lookup_with_tld_cancel (request->lookup); + GNUNET_GNS_lookup_with_tld_cancel(request->lookup); if (NULL != request->dns_lookup) - GNUNET_DNSSTUB_resolve_cancel (request->dns_lookup); - GNUNET_free (request->udp_msg); - GNUNET_free (request); + GNUNET_DNSSTUB_resolve_cancel(request->dns_lookup); + GNUNET_free(request->udp_msg); + GNUNET_free(request); } @@ -262,28 +261,28 @@ do_timeout (void *cls) * @param r size of the DNS payload */ static void -dns_result_processor (void *cls, - const struct GNUNET_TUN_DnsHeader *dns, - size_t r) +dns_result_processor(void *cls, + const struct GNUNET_TUN_DnsHeader *dns, + size_t r) { struct Request *request = cls; if (NULL == dns) - { - /* DNSSTUB gave up, so we trigger timeout early */ - GNUNET_SCHEDULER_cancel (request->timeout_task); - do_timeout (request); - return; - } + { + /* DNSSTUB gave up, so we trigger timeout early */ + GNUNET_SCHEDULER_cancel(request->timeout_task); + do_timeout(request); + return; + } if (request->original_request_id != dns->id) - { - /* for a another query, ignore */ - return; - } - request->packet = GNUNET_DNSPARSER_parse ((char*)dns, - r); - GNUNET_DNSSTUB_resolve_cancel (request->dns_lookup); - send_response (request); + { + /* for a another query, ignore */ + return; + } + request->packet = GNUNET_DNSPARSER_parse((char*)dns, + r); + GNUNET_DNSSTUB_resolve_cancel(request->dns_lookup); + send_response(request); } @@ -296,10 +295,10 @@ dns_result_processor (void *cls, * @param rd the records in reply */ static void -result_processor (void *cls, - int was_gns, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +result_processor(void *cls, + int was_gns, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct Request *request = cls; struct GNUNET_DNSPARSER_Packet *packet; @@ -307,22 +306,22 @@ result_processor (void *cls, request->lookup = NULL; if (GNUNET_NO == was_gns) - { - /* TLD not configured for GNS, fall back to DNS */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Using DNS resolver IP `%s' to resolve `%s'\n", - dns_ip, - request->packet->queries[0].name); - request->original_request_id = request->packet->id; - GNUNET_DNSPARSER_free_packet (request->packet); - request->packet = NULL; - request->dns_lookup = GNUNET_DNSSTUB_resolve (dns_stub, - request->udp_msg, - request->udp_msg_size, - &dns_result_processor, - request); - return; - } + { + /* TLD not configured for GNS, fall back to DNS */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Using DNS resolver IP `%s' to resolve `%s'\n", + dns_ip, + request->packet->queries[0].name); + request->original_request_id = request->packet->id; + GNUNET_DNSPARSER_free_packet(request->packet); + request->packet = NULL; + request->dns_lookup = GNUNET_DNSSTUB_resolve(dns_stub, + request->udp_msg, + request->udp_msg_size, + &dns_result_processor, + request); + return; + } packet = request->packet; packet->flags.query_or_response = 1; packet->flags.return_code = GNUNET_TUN_DNS_RETURN_CODE_NO_ERROR; @@ -333,59 +332,62 @@ result_processor (void *cls, packet->flags.message_truncated = 0; packet->flags.authoritative_answer = 0; //packet->flags.opcode = GNUNET_TUN_DNS_OPCODE_STATUS; // ??? - for (uint32_t i=0;iqueries[0].name); - rec.dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; - rec.type = GNUNET_DNSPARSER_TYPE_A; - rec.data.raw.data = GNUNET_new (struct in_addr); - GNUNET_memcpy (rec.data.raw.data, - rd[i].data, - rd[i].data_size); - rec.data.raw.data_len = sizeof (struct in_addr); - GNUNET_array_append (packet->answers, - packet->num_answers, - rec); - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - GNUNET_assert (sizeof (struct in6_addr) == rd[i].data_size); - rec.name = GNUNET_strdup (packet->queries[0].name); - rec.data.raw.data = GNUNET_new (struct in6_addr); - rec.dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; - rec.type = GNUNET_DNSPARSER_TYPE_AAAA; - GNUNET_memcpy (rec.data.raw.data, - rd[i].data, - rd[i].data_size); - rec.data.raw.data_len = sizeof (struct in6_addr); - GNUNET_array_append (packet->answers, - packet->num_answers, - rec); - break; - case GNUNET_DNSPARSER_TYPE_CNAME: - rec.name = GNUNET_strdup (packet->queries[0].name); - rec.data.hostname = GNUNET_strdup (rd[i].data); - rec.dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; - rec.type = GNUNET_DNSPARSER_TYPE_CNAME; - GNUNET_memcpy (rec.data.hostname, - rd[i].data, - rd[i].data_size); - GNUNET_array_append (packet->answers, - packet->num_answers, - rec); - break; - default: - /* skip */ - break; - } + { + case GNUNET_DNSPARSER_TYPE_A: + GNUNET_assert(sizeof(struct in_addr) == rd[i].data_size); + rec.name = GNUNET_strdup(packet->queries[0].name); + rec.dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; + rec.type = GNUNET_DNSPARSER_TYPE_A; + rec.data.raw.data = GNUNET_new(struct in_addr); + GNUNET_memcpy(rec.data.raw.data, + rd[i].data, + rd[i].data_size); + rec.data.raw.data_len = sizeof(struct in_addr); + GNUNET_array_append(packet->answers, + packet->num_answers, + rec); + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + GNUNET_assert(sizeof(struct in6_addr) == rd[i].data_size); + rec.name = GNUNET_strdup(packet->queries[0].name); + rec.data.raw.data = GNUNET_new(struct in6_addr); + rec.dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; + rec.type = GNUNET_DNSPARSER_TYPE_AAAA; + GNUNET_memcpy(rec.data.raw.data, + rd[i].data, + rd[i].data_size); + rec.data.raw.data_len = sizeof(struct in6_addr); + GNUNET_array_append(packet->answers, + packet->num_answers, + rec); + break; + + case GNUNET_DNSPARSER_TYPE_CNAME: + rec.name = GNUNET_strdup(packet->queries[0].name); + rec.data.hostname = GNUNET_strdup(rd[i].data); + rec.dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; + rec.type = GNUNET_DNSPARSER_TYPE_CNAME; + GNUNET_memcpy(rec.data.hostname, + rd[i].data, + rd[i].data_size); + GNUNET_array_append(packet->answers, + packet->num_answers, + rec); + break; + + default: + /* skip */ + break; + } } - send_response (request); + send_response(request); } @@ -399,73 +401,73 @@ result_processor (void *cls, * @param udp_msg_size number of bytes in @a udp_msg */ static void -handle_request (struct GNUNET_NETWORK_Handle *lsock, - const void *addr, - size_t addr_len, - const char *udp_msg, - size_t udp_msg_size) +handle_request(struct GNUNET_NETWORK_Handle *lsock, + const void *addr, + size_t addr_len, + const char *udp_msg, + size_t udp_msg_size) { struct Request *request; struct GNUNET_DNSPARSER_Packet *packet; - packet = GNUNET_DNSPARSER_parse (udp_msg, - udp_msg_size); + packet = GNUNET_DNSPARSER_parse(udp_msg, + udp_msg_size); if (NULL == packet) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Cannot parse DNS request from %s\n"), - GNUNET_a2s (addr, addr_len)); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received request for `%s' with flags %u, #answers %d, #auth %d, #additional %d\n", - packet->queries[0].name, - (unsigned int) packet->flags.query_or_response, - (int) packet->num_answers, - (int) packet->num_authority_records, - (int) packet->num_additional_records); - if ( (0 != packet->flags.query_or_response) || - (0 != packet->num_answers) || - (0 != packet->num_authority_records)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Received malformed DNS request from %s\n"), - GNUNET_a2s (addr, addr_len)); - GNUNET_DNSPARSER_free_packet (packet); - return; - } - if ( (1 != packet->num_queries) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Received unsupported DNS request from %s\n"), - GNUNET_a2s (addr, - addr_len)); - GNUNET_DNSPARSER_free_packet (packet); - return; - } - request = GNUNET_malloc (sizeof (struct Request) + addr_len); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Cannot parse DNS request from %s\n"), + GNUNET_a2s(addr, addr_len)); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received request for `%s' with flags %u, #answers %d, #auth %d, #additional %d\n", + packet->queries[0].name, + (unsigned int)packet->flags.query_or_response, + (int)packet->num_answers, + (int)packet->num_authority_records, + (int)packet->num_additional_records); + if ((0 != packet->flags.query_or_response) || + (0 != packet->num_answers) || + (0 != packet->num_authority_records)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Received malformed DNS request from %s\n"), + GNUNET_a2s(addr, addr_len)); + GNUNET_DNSPARSER_free_packet(packet); + return; + } + if ((1 != packet->num_queries)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Received unsupported DNS request from %s\n"), + GNUNET_a2s(addr, + addr_len)); + GNUNET_DNSPARSER_free_packet(packet); + return; + } + request = GNUNET_malloc(sizeof(struct Request) + addr_len); request->lsock = lsock; request->packet = packet; request->addr = &request[1]; request->addr_len = addr_len; - GNUNET_memcpy (&request[1], - addr, - addr_len); + GNUNET_memcpy(&request[1], + addr, + addr_len); request->udp_msg_size = udp_msg_size; - request->udp_msg = GNUNET_memdup (udp_msg, - udp_msg_size); - request->timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &do_timeout, - request); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Calling GNS on `%s'\n", - packet->queries[0].name); - request->lookup = GNUNET_GNS_lookup_with_tld (gns, - packet->queries[0].name, - packet->queries[0].type, - GNUNET_NO, - &result_processor, - request); + request->udp_msg = GNUNET_memdup(udp_msg, + udp_msg_size); + request->timeout_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &do_timeout, + request); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Calling GNS on `%s'\n", + packet->queries[0].name); + request->lookup = GNUNET_GNS_lookup_with_tld(gns, + packet->queries[0].name, + packet->queries[0].type, + GNUNET_NO, + &result_processor, + request); } @@ -475,49 +477,49 @@ handle_request (struct GNUNET_NETWORK_Handle *lsock, * @param cls the 'listen_socket4' */ static void -read_dns4 (void *cls) +read_dns4(void *cls) { struct sockaddr_in v4; socklen_t addrlen; ssize_t size; const struct GNUNET_SCHEDULER_TaskContext *tc; - GNUNET_assert (listen_socket4 == cls); - t4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - listen_socket4, - &read_dns4, - listen_socket4); - tc = GNUNET_SCHEDULER_get_task_context (); + GNUNET_assert(listen_socket4 == cls); + t4 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + listen_socket4, + &read_dns4, + listen_socket4); + tc = GNUNET_SCHEDULER_get_task_context(); if (0 == (GNUNET_SCHEDULER_REASON_READ_READY & tc->reason)) return; /* shutdown? */ - size = GNUNET_NETWORK_socket_recvfrom_amount (listen_socket4); + size = GNUNET_NETWORK_socket_recvfrom_amount(listen_socket4); if (0 > size) { - GNUNET_break (0); + GNUNET_break(0); return; /* read error!? */ } { char buf[size + 1]; ssize_t sret; - addrlen = sizeof (v4); - sret = GNUNET_NETWORK_socket_recvfrom (listen_socket4, - buf, - size + 1, - (struct sockaddr *) &v4, - &addrlen); + addrlen = sizeof(v4); + sret = GNUNET_NETWORK_socket_recvfrom(listen_socket4, + buf, + size + 1, + (struct sockaddr *)&v4, + &addrlen); if (0 > sret) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "recvfrom"); - return; - } - GNUNET_break (size == sret); - handle_request (listen_socket4, - &v4, - addrlen, - buf, - size); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "recvfrom"); + return; + } + GNUNET_break(size == sret); + handle_request(listen_socket4, + &v4, + addrlen, + buf, + size); } } @@ -528,49 +530,49 @@ read_dns4 (void *cls) * @param cls the 'listen_socket6' */ static void -read_dns6 (void *cls) +read_dns6(void *cls) { struct sockaddr_in6 v6; socklen_t addrlen; ssize_t size; const struct GNUNET_SCHEDULER_TaskContext *tc; - GNUNET_assert (listen_socket6 == cls); - t6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - listen_socket6, - &read_dns6, - listen_socket6); - tc = GNUNET_SCHEDULER_get_task_context (); + GNUNET_assert(listen_socket6 == cls); + t6 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + listen_socket6, + &read_dns6, + listen_socket6); + tc = GNUNET_SCHEDULER_get_task_context(); if (0 == (GNUNET_SCHEDULER_REASON_READ_READY & tc->reason)) return; /* shutdown? */ - size = GNUNET_NETWORK_socket_recvfrom_amount (listen_socket6); + size = GNUNET_NETWORK_socket_recvfrom_amount(listen_socket6); if (0 > size) { - GNUNET_break (0); + GNUNET_break(0); return; /* read error!? */ } { char buf[size]; ssize_t sret; - addrlen = sizeof (v6); - sret = GNUNET_NETWORK_socket_recvfrom (listen_socket6, - buf, - size, - (struct sockaddr *) &v6, - &addrlen); + addrlen = sizeof(v6); + sret = GNUNET_NETWORK_socket_recvfrom(listen_socket6, + buf, + size, + (struct sockaddr *)&v6, + &addrlen); if (0 > sret) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "recvfrom"); - return; - } - GNUNET_break (size == sret); - handle_request (listen_socket6, - &v6, - addrlen, - buf, - size); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "recvfrom"); + return; + } + GNUNET_break(size == sret); + handle_request(listen_socket6, + &v6, + addrlen, + buf, + size); } } @@ -584,149 +586,150 @@ read_dns6 (void *cls) * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { char *addr_str; - (void) cls; - (void) args; - (void) cfgfile; + + (void)cls; + (void)args; + (void)cfgfile; cfg = c; if (NULL == dns_ip) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No DNS server specified!\n")); - return; - } - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - if (NULL == (gns = GNUNET_GNS_connect (cfg))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No DNS server specified!\n")); + return; + } + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); + if (NULL == (gns = GNUNET_GNS_connect(cfg))) return; - GNUNET_assert (NULL != (dns_stub = GNUNET_DNSSTUB_start (128))); + GNUNET_assert(NULL != (dns_stub = GNUNET_DNSSTUB_start(128))); if (GNUNET_OK != - GNUNET_DNSSTUB_add_dns_ip (dns_stub, - dns_ip)) - { - GNUNET_DNSSTUB_stop (dns_stub); - GNUNET_GNS_disconnect (gns); - gns = NULL; - return; - } + GNUNET_DNSSTUB_add_dns_ip(dns_stub, + dns_ip)) + { + GNUNET_DNSSTUB_stop(dns_stub); + GNUNET_GNS_disconnect(gns); + gns = NULL; + return; + } /* Get address to bind to */ - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (c, "dns2gns", - "BIND_TO", - &addr_str)) - { - //No address specified - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Don't know what to bind to...\n"); - GNUNET_free (addr_str); - GNUNET_SCHEDULER_shutdown (); - return; - } - if (1 != inet_pton (AF_INET, addr_str, &address)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse address %s\n", - addr_str); - GNUNET_free (addr_str); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_free (addr_str); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(c, "dns2gns", + "BIND_TO", + &addr_str)) + { + //No address specified + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Don't know what to bind to...\n"); + GNUNET_free(addr_str); + GNUNET_SCHEDULER_shutdown(); + return; + } + if (1 != inet_pton(AF_INET, addr_str, &address)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse address %s\n", + addr_str); + GNUNET_free(addr_str); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_free(addr_str); /* Get address to bind to */ - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (c, "dns2gns", - "BIND_TO6", - &addr_str)) - { - //No address specified - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Don't know what to bind6 to...\n"); - GNUNET_free (addr_str); - GNUNET_SCHEDULER_shutdown (); - return; - } - if (1 != inet_pton (AF_INET6, addr_str, &address6)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse IPv6 address %s\n", - addr_str); - GNUNET_free (addr_str); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_free (addr_str); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(c, "dns2gns", + "BIND_TO6", + &addr_str)) + { + //No address specified + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Don't know what to bind6 to...\n"); + GNUNET_free(addr_str); + GNUNET_SCHEDULER_shutdown(); + return; + } + if (1 != inet_pton(AF_INET6, addr_str, &address6)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse IPv6 address %s\n", + addr_str); + GNUNET_free(addr_str); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_free(addr_str); - listen_socket4 = GNUNET_NETWORK_socket_create (PF_INET, - SOCK_DGRAM, - IPPROTO_UDP); + listen_socket4 = GNUNET_NETWORK_socket_create(PF_INET, + SOCK_DGRAM, + IPPROTO_UDP); if (NULL != listen_socket4) - { - struct sockaddr_in v4; + { + struct sockaddr_in v4; - memset (&v4, 0, sizeof (v4)); - v4.sin_family = AF_INET; - v4.sin_addr.s_addr = address; + memset(&v4, 0, sizeof(v4)); + v4.sin_family = AF_INET; + v4.sin_addr.s_addr = address; #if HAVE_SOCKADDR_IN_SIN_LEN - v4.sin_len = sizeof (v4); + v4.sin_len = sizeof(v4); #endif - v4.sin_port = htons (listen_port); - if (GNUNET_OK != - GNUNET_NETWORK_socket_bind (listen_socket4, - (struct sockaddr *) &v4, - sizeof (v4))) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind"); - GNUNET_NETWORK_socket_close (listen_socket4); - listen_socket4 = NULL; + v4.sin_port = htons(listen_port); + if (GNUNET_OK != + GNUNET_NETWORK_socket_bind(listen_socket4, + (struct sockaddr *)&v4, + sizeof(v4))) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "bind"); + GNUNET_NETWORK_socket_close(listen_socket4); + listen_socket4 = NULL; + } } - } - listen_socket6 = GNUNET_NETWORK_socket_create (PF_INET6, - SOCK_DGRAM, - IPPROTO_UDP); + listen_socket6 = GNUNET_NETWORK_socket_create(PF_INET6, + SOCK_DGRAM, + IPPROTO_UDP); if (NULL != listen_socket6) - { - struct sockaddr_in6 v6; + { + struct sockaddr_in6 v6; - memset (&v6, 0, sizeof (v6)); - v6.sin6_family = AF_INET6; - v6.sin6_addr = address6; + memset(&v6, 0, sizeof(v6)); + v6.sin6_family = AF_INET6; + v6.sin6_addr = address6; #if HAVE_SOCKADDR_IN_SIN_LEN - v6.sin6_len = sizeof (v6); + v6.sin6_len = sizeof(v6); #endif - v6.sin6_port = htons (listen_port); - if (GNUNET_OK != - GNUNET_NETWORK_socket_bind (listen_socket6, - (struct sockaddr *) &v6, - sizeof (v6))) + v6.sin6_port = htons(listen_port); + if (GNUNET_OK != + GNUNET_NETWORK_socket_bind(listen_socket6, + (struct sockaddr *)&v6, + sizeof(v6))) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "bind"); + GNUNET_NETWORK_socket_close(listen_socket6); + listen_socket6 = NULL; + } + } + if ((NULL == listen_socket4) && + (NULL == listen_socket6)) { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind"); - GNUNET_NETWORK_socket_close (listen_socket6); - listen_socket6 = NULL; + GNUNET_GNS_disconnect(gns); + gns = NULL; + GNUNET_DNSSTUB_stop(dns_stub); + dns_stub = NULL; + return; } - } - if ( (NULL == listen_socket4) && - (NULL == listen_socket6) ) - { - GNUNET_GNS_disconnect (gns); - gns = NULL; - GNUNET_DNSSTUB_stop (dns_stub); - dns_stub = NULL; - return; - } if (NULL != listen_socket4) - t4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - listen_socket4, - &read_dns4, - listen_socket4); + t4 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + listen_socket4, + &read_dns4, + listen_socket4); if (NULL != listen_socket6) - t6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - listen_socket6, - &read_dns6, - listen_socket6); + t6 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + listen_socket6, + &read_dns6, + listen_socket6); } @@ -738,39 +741,39 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, - char *const *argv) +main(int argc, + char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_option_string ('d', - "dns", - "IP", - gettext_noop ("IP of recursive DNS resolver to use (required)"), - &dns_ip), - GNUNET_GETOPT_option_uint ('p', - "port", - "UDPPORT", - gettext_noop ("UDP port to listen on for inbound DNS requests; default: 2853"), - &listen_port), + GNUNET_GETOPT_option_string('d', + "dns", + "IP", + gettext_noop("IP of recursive DNS resolver to use (required)"), + &dns_ip), + GNUNET_GETOPT_option_uint('p', + "port", + "UDPPORT", + gettext_noop("UDP port to listen on for inbound DNS requests; default: 2853"), + &listen_port), GNUNET_GETOPT_OPTION_END }; int ret; if (GNUNET_OK != - GNUNET_STRINGS_get_utf8_args (argc, argv, - &argc, &argv)) + GNUNET_STRINGS_get_utf8_args(argc, argv, + &argc, &argv)) return 2; - GNUNET_log_setup ("gnunet-dns2gns", - "WARNING", - NULL); + GNUNET_log_setup("gnunet-dns2gns", + "WARNING", + NULL); ret = - (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, - "gnunet-dns2gns", - _("GNUnet DNS-to-GNS proxy (a DNS server)"), - options, - &run, NULL)) ? 0 : 1; - GNUNET_free ((void*) argv); + (GNUNET_OK == + GNUNET_PROGRAM_run(argc, argv, + "gnunet-dns2gns", + _("GNUnet DNS-to-GNS proxy (a DNS server)"), + options, + &run, NULL)) ? 0 : 1; + GNUNET_free((void*)argv); return ret; } diff --git a/src/gns/gnunet-gns-benchmark.c b/src/gns/gnunet-gns-benchmark.c index 77066fd3f..b64201f10 100644 --- a/src/gns/gnunet-gns-benchmark.c +++ b/src/gns/gnunet-gns-benchmark.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/gns/gnunet-gns-benchmark.c * @brief issue many queries to GNS and compute performance statistics @@ -31,12 +31,12 @@ /** * How long do we wait at least between requests by default? */ -#define DEF_REQUEST_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 1) +#define DEF_REQUEST_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 1) /** * How long do we wait until we consider a request failed by default? */ -#define DEF_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1) +#define DEF_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1) /** @@ -45,8 +45,7 @@ * However, this process does not change how it acts * based on the category. */ -enum RequestCategory -{ +enum RequestCategory { RC_SHARED = 0, RC_PRIVATE = 1, /** @@ -61,9 +60,7 @@ enum RequestCategory * thus optimizing it is crucial for the overall memory consumption of * the zone importer. */ -struct Request -{ - +struct Request { /** * Active requests are kept in a DLL. */ @@ -101,7 +98,6 @@ struct Request * Category of the request. */ enum RequestCategory cat; - }; @@ -192,11 +188,11 @@ static int g2d; * @param req request to free */ static void -free_request (struct Request *req) +free_request(struct Request *req) { if (NULL != req->lr) - GNUNET_GNS_lookup_with_tld_cancel (req->lr); - GNUNET_free (req); + GNUNET_GNS_lookup_with_tld_cancel(req->lr); + GNUNET_free(req); } @@ -209,32 +205,32 @@ free_request (struct Request *req) * @param rd the records in reply */ static void -process_result (void *cls, - int gns_tld, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +process_result(void *cls, + int gns_tld, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct Request *req = cls; - (void) gns_tld; - (void) rd_count; - (void) rd; + (void)gns_tld; + (void)rd_count; + (void)rd; active_cnt--; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got response for request `%s'\n", - req->hostname); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got response for request `%s'\n", + req->hostname); req->lr = NULL; - req->latency = GNUNET_TIME_absolute_get_duration (req->op_start_time); - GNUNET_CONTAINER_DLL_remove (act_head, - act_tail, - req); - GNUNET_CONTAINER_DLL_insert (succ_head, - succ_tail, - req); + req->latency = GNUNET_TIME_absolute_get_duration(req->op_start_time); + GNUNET_CONTAINER_DLL_remove(act_head, + act_tail, + req); + GNUNET_CONTAINER_DLL_insert(succ_head, + succ_tail, + req); replies[req->cat]++; latency_sum[req->cat] - = GNUNET_TIME_relative_add (latency_sum[req->cat], - req->latency); + = GNUNET_TIME_relative_add(latency_sum[req->cat], + req->latency); } @@ -244,69 +240,69 @@ process_result (void *cls, * @param cls NULL */ static void -process_queue (void *cls) +process_queue(void *cls) { struct Request *req; struct GNUNET_TIME_Relative duration; - (void) cls; + (void)cls; t = NULL; /* check for expired requests */ while (NULL != (req = act_head)) - { - duration = GNUNET_TIME_absolute_get_duration (req->op_start_time); - if (duration.rel_value_us < timeout.rel_value_us) - break; - GNUNET_CONTAINER_DLL_remove (act_head, - act_tail, - req); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Failing request `%s' due to timeout\n", - req->hostname); - failures[req->cat]++; - active_cnt--; - free_request (req); - } + { + duration = GNUNET_TIME_absolute_get_duration(req->op_start_time); + if (duration.rel_value_us < timeout.rel_value_us) + break; + GNUNET_CONTAINER_DLL_remove(act_head, + act_tail, + req); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Failing request `%s' due to timeout\n", + req->hostname); + failures[req->cat]++; + active_cnt--; + free_request(req); + } if (NULL == (req = todo_head)) - { - struct GNUNET_TIME_Absolute at; - - if (NULL == (req = act_head)) { - GNUNET_SCHEDULER_shutdown (); + struct GNUNET_TIME_Absolute at; + + if (NULL == (req = act_head)) + { + GNUNET_SCHEDULER_shutdown(); + return; + } + at = GNUNET_TIME_absolute_add(req->op_start_time, + timeout); + t = GNUNET_SCHEDULER_add_at(at, + &process_queue, + NULL); return; } - at = GNUNET_TIME_absolute_add (req->op_start_time, - timeout); - t = GNUNET_SCHEDULER_add_at (at, - &process_queue, - NULL); - return; - } - GNUNET_CONTAINER_DLL_remove (todo_head, - todo_tail, - req); - GNUNET_CONTAINER_DLL_insert_tail (act_head, - act_tail, - req); + GNUNET_CONTAINER_DLL_remove(todo_head, + todo_tail, + req); + GNUNET_CONTAINER_DLL_insert_tail(act_head, + act_tail, + req); lookups[req->cat]++; active_cnt++; - req->op_start_time = GNUNET_TIME_absolute_get (); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting request `%s' (%u in parallel)\n", - req->hostname, - active_cnt); - req->lr = GNUNET_GNS_lookup_with_tld (gns, - req->hostname, - g2d - ? GNUNET_GNSRECORD_TYPE_GNS2DNS - : GNUNET_GNSRECORD_TYPE_ANY, - GNUNET_GNS_LO_DEFAULT, - &process_result, - req); - t = GNUNET_SCHEDULER_add_delayed (request_delay, - &process_queue, - NULL); + req->op_start_time = GNUNET_TIME_absolute_get(); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting request `%s' (%u in parallel)\n", + req->hostname, + active_cnt); + req->lr = GNUNET_GNS_lookup_with_tld(gns, + req->hostname, + g2d + ? GNUNET_GNSRECORD_TYPE_GNS2DNS + : GNUNET_GNSRECORD_TYPE_ANY, + GNUNET_GNS_LO_DEFAULT, + &process_result, + req); + t = GNUNET_SCHEDULER_add_delayed(request_delay, + &process_queue, + NULL); } @@ -318,11 +314,11 @@ process_queue (void *cls) * @return -1 if c1c2, 0 if c1==c2. */ static int -compare_req (const void *c1, - const void *c2) +compare_req(const void *c1, + const void *c2) { - const struct Request *r1 = *(void **) c1; - const struct Request *r2 = *(void **) c2; + const struct Request *r1 = *(void **)c1; + const struct Request *r2 = *(void **)c2; if (r1->latency.rel_value_us < r2->latency.rel_value_us) return -1; @@ -338,101 +334,101 @@ compare_req (const void *c1, * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { struct Request *req; struct Request **ra[RC_MAX]; unsigned int rp[RC_MAX]; - (void) cls; - for (enum RequestCategory rc = 0;rc < RC_MAX;rc++) - { - ra[rc] = GNUNET_new_array (replies[rc], - struct Request *); - rp[rc] = 0; - } - for (req = succ_head;NULL != req; req = req->next) - { - GNUNET_assert (rp[req->cat] < replies[req->cat]); - ra[req->cat][rp[req->cat]++] = req; - } - for (enum RequestCategory rc = 0;rc < RC_MAX;rc++) - { - unsigned int off; - - fprintf (stdout, - "Category %u\n", - rc); - fprintf (stdout, - "\tlookups: %u replies: %u failures: %u\n", - lookups[rc], - replies[rc], - failures[rc]); - if (0 == rp[rc]) - continue; - qsort (ra[rc], - rp[rc], - sizeof (struct Request *), - &compare_req); - latency_sum[rc] = GNUNET_TIME_relative_divide (latency_sum[rc], - replies[rc]); - fprintf (stdout, - "\taverage: %s\n", - GNUNET_STRINGS_relative_time_to_string (latency_sum[rc], - GNUNET_YES)); - off = rp[rc] * 50 / 100; - fprintf (stdout, - "\tmedian(50): %s\n", - GNUNET_STRINGS_relative_time_to_string (ra[rc][off]->latency, - GNUNET_YES)); - off = rp[rc] * 75 / 100; - fprintf (stdout, - "\tquantile(75): %s\n", - GNUNET_STRINGS_relative_time_to_string (ra[rc][off]->latency, - GNUNET_YES)); - off = rp[rc] * 90 / 100; - fprintf (stdout, - "\tquantile(90): %s\n", - GNUNET_STRINGS_relative_time_to_string (ra[rc][off]->latency, - GNUNET_YES)); - off = rp[rc] * 99 / 100; - fprintf (stdout, - "\tquantile(99): %s\n", - GNUNET_STRINGS_relative_time_to_string (ra[rc][off]->latency, - GNUNET_YES)); - GNUNET_free (ra[rc]); - } + (void)cls; + for (enum RequestCategory rc = 0; rc < RC_MAX; rc++) + { + ra[rc] = GNUNET_new_array(replies[rc], + struct Request *); + rp[rc] = 0; + } + for (req = succ_head; NULL != req; req = req->next) + { + GNUNET_assert(rp[req->cat] < replies[req->cat]); + ra[req->cat][rp[req->cat]++] = req; + } + for (enum RequestCategory rc = 0; rc < RC_MAX; rc++) + { + unsigned int off; + + fprintf(stdout, + "Category %u\n", + rc); + fprintf(stdout, + "\tlookups: %u replies: %u failures: %u\n", + lookups[rc], + replies[rc], + failures[rc]); + if (0 == rp[rc]) + continue; + qsort(ra[rc], + rp[rc], + sizeof(struct Request *), + &compare_req); + latency_sum[rc] = GNUNET_TIME_relative_divide(latency_sum[rc], + replies[rc]); + fprintf(stdout, + "\taverage: %s\n", + GNUNET_STRINGS_relative_time_to_string(latency_sum[rc], + GNUNET_YES)); + off = rp[rc] * 50 / 100; + fprintf(stdout, + "\tmedian(50): %s\n", + GNUNET_STRINGS_relative_time_to_string(ra[rc][off]->latency, + GNUNET_YES)); + off = rp[rc] * 75 / 100; + fprintf(stdout, + "\tquantile(75): %s\n", + GNUNET_STRINGS_relative_time_to_string(ra[rc][off]->latency, + GNUNET_YES)); + off = rp[rc] * 90 / 100; + fprintf(stdout, + "\tquantile(90): %s\n", + GNUNET_STRINGS_relative_time_to_string(ra[rc][off]->latency, + GNUNET_YES)); + off = rp[rc] * 99 / 100; + fprintf(stdout, + "\tquantile(99): %s\n", + GNUNET_STRINGS_relative_time_to_string(ra[rc][off]->latency, + GNUNET_YES)); + GNUNET_free(ra[rc]); + } if (NULL != t) - { - GNUNET_SCHEDULER_cancel (t); - t = NULL; - } + { + GNUNET_SCHEDULER_cancel(t); + t = NULL; + } while (NULL != (req = act_head)) - { - GNUNET_CONTAINER_DLL_remove (act_head, - act_tail, - req); - free_request (req); - } + { + GNUNET_CONTAINER_DLL_remove(act_head, + act_tail, + req); + free_request(req); + } while (NULL != (req = succ_head)) - { - GNUNET_CONTAINER_DLL_remove (succ_head, - succ_tail, - req); - free_request (req); - } + { + GNUNET_CONTAINER_DLL_remove(succ_head, + succ_tail, + req); + free_request(req); + } while (NULL != (req = todo_head)) - { - GNUNET_CONTAINER_DLL_remove (todo_head, - todo_tail, - req); - free_request (req); - } + { + GNUNET_CONTAINER_DLL_remove(todo_head, + todo_tail, + req); + free_request(req); + } if (NULL != gns) - { - GNUNET_GNS_disconnect (gns); - gns = NULL; - } + { + GNUNET_GNS_disconnect(gns); + gns = NULL; + } } @@ -443,32 +439,32 @@ do_shutdown (void *cls) * @param cat category of the @a hostname */ static void -queue (const char *hostname, - enum RequestCategory cat) +queue(const char *hostname, + enum RequestCategory cat) { struct Request *req; const char *dot; size_t hlen; - dot = strchr (hostname, - (unsigned char) '.'); + dot = strchr(hostname, + (unsigned char)'.'); if (NULL == dot) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Refusing invalid hostname `%s' (lacks '.')\n", - hostname); - return; - } - hlen = strlen (hostname) + 1; - req = GNUNET_malloc (sizeof (struct Request) + hlen); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Refusing invalid hostname `%s' (lacks '.')\n", + hostname); + return; + } + hlen = strlen(hostname) + 1; + req = GNUNET_malloc(sizeof(struct Request) + hlen); req->cat = cat; - req->hostname = (char *) &req[1]; - GNUNET_memcpy (&req[1], - hostname, - hlen); - GNUNET_CONTAINER_DLL_insert (todo_head, - todo_tail, - req); + req->hostname = (char *)&req[1]; + GNUNET_memcpy(&req[1], + hostname, + hlen); + GNUNET_CONTAINER_DLL_insert(todo_head, + todo_tail, + req); } @@ -478,7 +474,7 @@ queue (const char *hostname, * @param cls NULL */ static void -process_stdin (void *cls) +process_stdin(void *cls) { static struct GNUNET_TIME_Absolute last; static uint64_t idot; @@ -486,48 +482,48 @@ process_stdin (void *cls) char hn[256]; char in[270]; - (void) cls; + (void)cls; t = NULL; while (NULL != - fgets (in, - sizeof (in), - stdin)) - { - if (strlen(in) > 0) - hn[strlen(in)-1] = '\0'; /* eat newline */ - if ( (2 != sscanf (in, - "%u %255s", - &cat, - hn)) || - (cat >= RC_MAX) ) - { - fprintf (stderr, - "Malformed input line `%s', skipping\n", - in); - continue; - } - if (0 == idot) - last = GNUNET_TIME_absolute_get (); - idot++; - if (0 == idot % 100000) + fgets(in, + sizeof(in), + stdin)) { - struct GNUNET_TIME_Relative delta; - - delta = GNUNET_TIME_absolute_get_duration (last); - last = GNUNET_TIME_absolute_get (); - fprintf (stderr, - "Read 100000 domain names in %s\n", - GNUNET_STRINGS_relative_time_to_string (delta, - GNUNET_YES)); + if (strlen(in) > 0) + hn[strlen(in) - 1] = '\0'; /* eat newline */ + if ((2 != sscanf(in, + "%u %255s", + &cat, + hn)) || + (cat >= RC_MAX)) + { + fprintf(stderr, + "Malformed input line `%s', skipping\n", + in); + continue; + } + if (0 == idot) + last = GNUNET_TIME_absolute_get(); + idot++; + if (0 == idot % 100000) + { + struct GNUNET_TIME_Relative delta; + + delta = GNUNET_TIME_absolute_get_duration(last); + last = GNUNET_TIME_absolute_get(); + fprintf(stderr, + "Read 100000 domain names in %s\n", + GNUNET_STRINGS_relative_time_to_string(delta, + GNUNET_YES)); + } + queue(hn, + (enum RequestCategory)cat); } - queue (hn, - (enum RequestCategory) cat); - } - fprintf (stderr, - "Done reading %llu domain names\n", - (unsigned long long) idot); - t = GNUNET_SCHEDULER_add_now (&process_queue, - NULL); + fprintf(stderr, + "Done reading %llu domain names\n", + (unsigned long long)idot); + t = GNUNET_SCHEDULER_add_now(&process_queue, + NULL); } @@ -541,25 +537,25 @@ process_stdin (void *cls) * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - (void) cls; - (void) args; - (void) cfgfile; - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - gns = GNUNET_GNS_connect (cfg); + (void)cls; + (void)args; + (void)cfgfile; + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); + gns = GNUNET_GNS_connect(cfg); if (NULL == gns) - { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } - t = GNUNET_SCHEDULER_add_now (&process_stdin, - NULL); + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + t = GNUNET_SCHEDULER_add_now(&process_stdin, + NULL); } @@ -571,44 +567,44 @@ run (void *cls, * @return 0 on success */ int -main (int argc, - char *const*argv) +main(int argc, + char *const*argv) { int ret = 0; struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_option_relative_time ('d', - "delay", - "RELATIVETIME", - gettext_noop ("how long to wait between queries"), - &request_delay), - GNUNET_GETOPT_option_relative_time ('t', - "timeout", - "RELATIVETIME", - gettext_noop ("how long to wait for an answer"), - &timeout), - GNUNET_GETOPT_option_flag ('2', - "g2d", - gettext_noop ("look for GNS2DNS records instead of ANY"), - &g2d), + GNUNET_GETOPT_option_relative_time('d', + "delay", + "RELATIVETIME", + gettext_noop("how long to wait between queries"), + &request_delay), + GNUNET_GETOPT_option_relative_time('t', + "timeout", + "RELATIVETIME", + gettext_noop("how long to wait for an answer"), + &timeout), + GNUNET_GETOPT_option_flag('2', + "g2d", + gettext_noop("look for GNS2DNS records instead of ANY"), + &g2d), GNUNET_GETOPT_OPTION_END }; if (GNUNET_OK != - GNUNET_STRINGS_get_utf8_args (argc, argv, - &argc, &argv)) + GNUNET_STRINGS_get_utf8_args(argc, argv, + &argc, &argv)) return 2; timeout = DEF_TIMEOUT; request_delay = DEF_REQUEST_DELAY; if (GNUNET_OK != - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-gns-benchmark", - "resolve GNS names and measure performance", - options, - &run, - NULL)) + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-gns-benchmark", + "resolve GNS names and measure performance", + options, + &run, + NULL)) ret = 1; - GNUNET_free ((void*) argv); + GNUNET_free((void*)argv); return ret; } diff --git a/src/gns/gnunet-gns-helper-service-w32.c b/src/gns/gnunet-gns-helper-service-w32.c index 4eb965e24..4c4803556 100644 --- a/src/gns/gnunet-gns-helper-service-w32.c +++ b/src/gns/gnunet-gns-helper-service-w32.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnunet-gns-helper-service-w32.c * @brief an intermediary service to access distributed GNS @@ -35,7 +35,7 @@ #include #include -#define DEFINE_DNS_GUID(a,x) DEFINE_GUID(a, 0x00090035, 0x0000, x, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46) +#define DEFINE_DNS_GUID(a, x) DEFINE_GUID(a, 0x00090035, 0x0000, x, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46) DEFINE_DNS_GUID(SVCID_DNS_TYPE_A, 0x0001); DEFINE_DNS_GUID(SVCID_DNS_TYPE_NS, 0x0002); DEFINE_DNS_GUID(SVCID_DNS_TYPE_CNAME, 0x0005); @@ -49,8 +49,7 @@ DEFINE_GUID(SVCID_HOSTNAME, 0x0002a800, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, DEFINE_GUID(SVCID_INET_HOSTADDRBYNAME, 0x0002a803, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); -struct request -{ +struct request { /** * We keep these in a doubly-linked list (for cleanup). */ @@ -120,83 +119,83 @@ static int got_egos; * @param cls unused */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { struct request *rq; if (NULL != id_op) - { - GNUNET_IDENTITY_cancel (id_op); - id_op = NULL; - } + { + GNUNET_IDENTITY_cancel(id_op); + id_op = NULL; + } if (NULL != identity) - { - GNUNET_IDENTITY_disconnect (identity); - identity = NULL; - } + { + GNUNET_IDENTITY_disconnect(identity); + identity = NULL; + } while (NULL != (rq = rq_head)) - { - if (NULL != rq->lookup_request) - GNUNET_GNS_lookup_cancel (rq->lookup_request); - GNUNET_CONTAINER_DLL_remove (rq_head, - rq_tail, - rq); - GNUNET_free_non_null (rq->name); - if (rq->u8name) - free (rq->u8name); - GNUNET_free (rq); - } + { + if (NULL != rq->lookup_request) + GNUNET_GNS_lookup_cancel(rq->lookup_request); + GNUNET_CONTAINER_DLL_remove(rq_head, + rq_tail, + rq); + GNUNET_free_non_null(rq->name); + if (rq->u8name) + free(rq->u8name); + GNUNET_free(rq); + } if (NULL != gns) - { - GNUNET_GNS_disconnect (gns); - gns = NULL; - } + { + GNUNET_GNS_disconnect(gns); + gns = NULL; + } } #define MarshallPtr(ptr, base, type) \ if (ptr) \ - ptr = (type *) ((char *) ptr - (char *) base) + ptr = (type *) ((char *)ptr - (char *)base) void -MarshallWSAQUERYSETW (WSAQUERYSETW *qs, GUID *sc) +MarshallWSAQUERYSETW(WSAQUERYSETW *qs, GUID *sc) { - MarshallPtr (qs->lpszServiceInstanceName, qs, wchar_t); - MarshallPtr (qs->lpServiceClassId, qs, GUID); - MarshallPtr (qs->lpVersion, qs, WSAVERSION); - MarshallPtr (qs->lpNSProviderId, qs, GUID); - MarshallPtr (qs->lpszContext, qs, wchar_t); - MarshallPtr (qs->lpafpProtocols, qs, AFPROTOCOLS); - MarshallPtr (qs->lpszQueryString, qs, wchar_t); + MarshallPtr(qs->lpszServiceInstanceName, qs, wchar_t); + MarshallPtr(qs->lpServiceClassId, qs, GUID); + MarshallPtr(qs->lpVersion, qs, WSAVERSION); + MarshallPtr(qs->lpNSProviderId, qs, GUID); + MarshallPtr(qs->lpszContext, qs, wchar_t); + MarshallPtr(qs->lpafpProtocols, qs, AFPROTOCOLS); + MarshallPtr(qs->lpszQueryString, qs, wchar_t); for (int i = 0; i < qs->dwNumberOfCsAddrs; i++) - { - MarshallPtr (qs->lpcsaBuffer[i].LocalAddr.lpSockaddr, qs, SOCKADDR); - MarshallPtr (qs->lpcsaBuffer[i].RemoteAddr.lpSockaddr, qs, SOCKADDR); - } - MarshallPtr (qs->lpcsaBuffer, qs, CSADDR_INFO); - if (IsEqualGUID (&SVCID_INET_HOSTADDRBYNAME, sc) && qs->lpBlob != NULL && qs->lpBlob->pBlobData != NULL) - { - struct hostent *he; - - he = (struct hostent *) qs->lpBlob->pBlobData; - for (int i = 0; he->h_aliases[i] != NULL; i++) - MarshallPtr (he->h_aliases[i], he, char); - MarshallPtr (he->h_aliases, he, char *); - MarshallPtr (he->h_name, he, char); - for (int i = 0; he->h_addr_list[i] != NULL; i++) - MarshallPtr (he->h_addr_list[i], he, void); - MarshallPtr (he->h_addr_list, he, char *); - MarshallPtr (qs->lpBlob->pBlobData, qs, void); - } - MarshallPtr (qs->lpBlob, qs, BLOB); + { + MarshallPtr(qs->lpcsaBuffer[i].LocalAddr.lpSockaddr, qs, SOCKADDR); + MarshallPtr(qs->lpcsaBuffer[i].RemoteAddr.lpSockaddr, qs, SOCKADDR); + } + MarshallPtr(qs->lpcsaBuffer, qs, CSADDR_INFO); + if (IsEqualGUID(&SVCID_INET_HOSTADDRBYNAME, sc) && qs->lpBlob != NULL && qs->lpBlob->pBlobData != NULL) + { + struct hostent *he; + + he = (struct hostent *)qs->lpBlob->pBlobData; + for (int i = 0; he->h_aliases[i] != NULL; i++) + MarshallPtr(he->h_aliases[i], he, char); + MarshallPtr(he->h_aliases, he, char *); + MarshallPtr(he->h_name, he, char); + for (int i = 0; he->h_addr_list[i] != NULL; i++) + MarshallPtr(he->h_addr_list[i], he, void); + MarshallPtr(he->h_addr_list, he, char *); + MarshallPtr(qs->lpBlob->pBlobData, qs, void); + } + MarshallPtr(qs->lpBlob, qs, BLOB); } static void -process_lookup_result (void *cls, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +process_lookup_result(void *cls, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct request *rq = cls; int i, j, csanum; @@ -211,269 +210,272 @@ process_lookup_result (void *cls, size_t blobsize = 0; size_t blobaddrcount = 0; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got lookup result with count %u for rq %p with client %p\n", - rd_count, - rq, - rq->client); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got lookup result with count %u for rq %p with client %p\n", + rd_count, + rq, + rq->client); rq->lookup_request = NULL; if (0 == rd_count) - { - msgend_env = GNUNET_MQ_msg (msgend, GNUNET_MESSAGE_TYPE_W32RESOLVER_RESPONSE); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (rq->client), - msgend_env); - GNUNET_CONTAINER_DLL_remove (rq_head, - rq_tail, - rq); - GNUNET_free_non_null (rq->name); - if (rq->u8name) - free (rq->u8name); - GNUNET_free (rq); - return; - } - - size = sizeof (struct GNUNET_W32RESOLVER_GetMessage) + sizeof (WSAQUERYSETW); - size += (wcslen (rq->name) + 1) * sizeof (wchar_t); - size += sizeof (GUID); + { + msgend_env = GNUNET_MQ_msg(msgend, GNUNET_MESSAGE_TYPE_W32RESOLVER_RESPONSE); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(rq->client), + msgend_env); + GNUNET_CONTAINER_DLL_remove(rq_head, + rq_tail, + rq); + GNUNET_free_non_null(rq->name); + if (rq->u8name) + free(rq->u8name); + GNUNET_free(rq); + return; + } + + size = sizeof(struct GNUNET_W32RESOLVER_GetMessage) + sizeof(WSAQUERYSETW); + size += (wcslen(rq->name) + 1) * sizeof(wchar_t); + size += sizeof(GUID); /* lpszComment ? a TXT record? */ - size += sizeof (GUID); + size += sizeof(GUID); /* lpszContext ? Not sure what it is */ csanum = 0; for (i = 0; i < rd_count; i++) - { - switch (rd[i].record_type) { - case GNUNET_DNSPARSER_TYPE_A: - if (rd[i].data_size != sizeof (struct in_addr)) - continue; - size += sizeof (CSADDR_INFO) + sizeof (struct sockaddr_in) * 2; - csanum++; - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - if (rd[i].data_size != sizeof (struct in6_addr)) - continue; - size += sizeof (CSADDR_INFO) + sizeof (struct sockaddr_in6) * 2; - csanum++; - break; + switch (rd[i].record_type) + { + case GNUNET_DNSPARSER_TYPE_A: + if (rd[i].data_size != sizeof(struct in_addr)) + continue; + size += sizeof(CSADDR_INFO) + sizeof(struct sockaddr_in) * 2; + csanum++; + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + if (rd[i].data_size != sizeof(struct in6_addr)) + continue; + size += sizeof(CSADDR_INFO) + sizeof(struct sockaddr_in6) * 2; + csanum++; + break; + } } - } - if (IsEqualGUID (&SVCID_INET_HOSTADDRBYNAME, &rq->sc)) - { - size += sizeof (BLOB); - blobsize += sizeof (struct hostent); - blobsize += strlen (rq->u8name) + 1; - blobsize += sizeof (void *); /* For aliases */ - blobsize += sizeof (void *); /* For addresses */ - for (i = 0; i < rd_count; i++) + if (IsEqualGUID(&SVCID_INET_HOSTADDRBYNAME, &rq->sc)) { - if ((rq->af == AF_INET || rq->af == AF_UNSPEC) && rd[i].record_type == GNUNET_DNSPARSER_TYPE_A) - { - blobsize += sizeof (void *); - blobsize += sizeof (struct in_addr); - blobaddrcount++; - } - else if (rq->af == AF_INET6 && rd[i].record_type == GNUNET_DNSPARSER_TYPE_AAAA) - { - blobsize += sizeof (void *); - blobsize += sizeof (struct in6_addr); - blobaddrcount++; - } + size += sizeof(BLOB); + blobsize += sizeof(struct hostent); + blobsize += strlen(rq->u8name) + 1; + blobsize += sizeof(void *); /* For aliases */ + blobsize += sizeof(void *); /* For addresses */ + for (i = 0; i < rd_count; i++) + { + if ((rq->af == AF_INET || rq->af == AF_UNSPEC) && rd[i].record_type == GNUNET_DNSPARSER_TYPE_A) + { + blobsize += sizeof(void *); + blobsize += sizeof(struct in_addr); + blobaddrcount++; + } + else if (rq->af == AF_INET6 && rd[i].record_type == GNUNET_DNSPARSER_TYPE_AAAA) + { + blobsize += sizeof(void *); + blobsize += sizeof(struct in6_addr); + blobaddrcount++; + } + } + size += blobsize; } - size += blobsize; - } - size_recalc = sizeof (struct GNUNET_W32RESOLVER_GetMessage) + sizeof (WSAQUERYSETW); - msg_env = GNUNET_MQ_msg_extra (msg, - size - sizeof (struct GNUNET_MessageHeader), - GNUNET_MESSAGE_TYPE_W32RESOLVER_RESPONSE); - msg->af = htonl (rq->af); - msg->sc_data1 = htonl (rq->sc.Data1); - msg->sc_data2 = htons (rq->sc.Data2); - msg->sc_data3 = htons (rq->sc.Data3); + size_recalc = sizeof(struct GNUNET_W32RESOLVER_GetMessage) + sizeof(WSAQUERYSETW); + msg_env = GNUNET_MQ_msg_extra(msg, + size - sizeof(struct GNUNET_MessageHeader), + GNUNET_MESSAGE_TYPE_W32RESOLVER_RESPONSE); + msg->af = htonl(rq->af); + msg->sc_data1 = htonl(rq->sc.Data1); + msg->sc_data2 = htons(rq->sc.Data2); + msg->sc_data3 = htons(rq->sc.Data3); for (i = 0; i < 8; i++) msg->sc_data4[i] = rq->sc.Data4[i]; - qs = (WSAQUERYSETW *) &msg[1]; - ptr = (char *) &qs[1]; - GNUNET_break (size_recalc == (size_t) ((char *) ptr - (char *) msg)); - qs->dwSize = sizeof (WSAQUERYSETW); - qs->lpszServiceInstanceName = (wchar_t *) ptr; - ptr += (wcslen (rq->name) + 1) * sizeof (wchar_t); - size_recalc += (wcslen (rq->name) + 1) * sizeof (wchar_t); - GNUNET_break (size_recalc == (size_t) ((char *) ptr - (char *) msg)); - wcscpy (qs->lpszServiceInstanceName, rq->name); - qs->lpServiceClassId = (GUID *) ptr; - ptr += sizeof (GUID); - size_recalc += sizeof (GUID); - GNUNET_break (size_recalc == (size_t) ((char *) ptr - (char *) msg)); - GNUNET_memcpy (qs->lpServiceClassId, &rq->sc, sizeof (GUID)); + qs = (WSAQUERYSETW *)&msg[1]; + ptr = (char *)&qs[1]; + GNUNET_break(size_recalc == (size_t)((char *)ptr - (char *)msg)); + qs->dwSize = sizeof(WSAQUERYSETW); + qs->lpszServiceInstanceName = (wchar_t *)ptr; + ptr += (wcslen(rq->name) + 1) * sizeof(wchar_t); + size_recalc += (wcslen(rq->name) + 1) * sizeof(wchar_t); + GNUNET_break(size_recalc == (size_t)((char *)ptr - (char *)msg)); + wcscpy(qs->lpszServiceInstanceName, rq->name); + qs->lpServiceClassId = (GUID *)ptr; + ptr += sizeof(GUID); + size_recalc += sizeof(GUID); + GNUNET_break(size_recalc == (size_t)((char *)ptr - (char *)msg)); + GNUNET_memcpy(qs->lpServiceClassId, &rq->sc, sizeof(GUID)); qs->lpVersion = NULL; qs->dwNameSpace = NS_DNS; - qs->lpNSProviderId = (GUID *) ptr; - ptr += sizeof (GUID); - size_recalc += sizeof (GUID); - GNUNET_break (size_recalc == (size_t) ((char *) ptr - (char *) msg)); - GNUNET_memcpy (qs->lpNSProviderId, &GNUNET_NAMESPACE_PROVIDER_DNS, sizeof (GUID)); + qs->lpNSProviderId = (GUID *)ptr; + ptr += sizeof(GUID); + size_recalc += sizeof(GUID); + GNUNET_break(size_recalc == (size_t)((char *)ptr - (char *)msg)); + GNUNET_memcpy(qs->lpNSProviderId, &GNUNET_NAMESPACE_PROVIDER_DNS, sizeof(GUID)); qs->lpszContext = NULL; qs->dwNumberOfProtocols = 0; qs->lpafpProtocols = NULL; /* Don't bother with this... */ qs->lpszQueryString = NULL; qs->dwNumberOfCsAddrs = rd_count; - qs->lpcsaBuffer = (CSADDR_INFO *) ptr; - ptr += sizeof (CSADDR_INFO) * csanum; + qs->lpcsaBuffer = (CSADDR_INFO *)ptr; + ptr += sizeof(CSADDR_INFO) * csanum; j = 0; for (i = 0; i < rd_count; i++) - { - switch (rd[i].record_type) { - case GNUNET_DNSPARSER_TYPE_A: - if (rd[i].data_size != sizeof (struct in_addr)) - continue; - qs->lpcsaBuffer[j].iSocketType = SOCK_STREAM; - qs->lpcsaBuffer[j].iProtocol = IPPROTO_TCP; - - qs->lpcsaBuffer[j].LocalAddr.iSockaddrLength = sizeof (struct sockaddr_in); - qs->lpcsaBuffer[j].LocalAddr.lpSockaddr = (SOCKADDR *) ptr; - ptr += qs->lpcsaBuffer[j].LocalAddr.iSockaddrLength; - memset (qs->lpcsaBuffer[j].LocalAddr.lpSockaddr, 0, qs->lpcsaBuffer[j].LocalAddr.iSockaddrLength); - ((struct sockaddr_in *)qs->lpcsaBuffer[j].LocalAddr.lpSockaddr)->sin_family = AF_INET; - - qs->lpcsaBuffer[j].RemoteAddr.iSockaddrLength = sizeof (struct sockaddr_in); - qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr = (SOCKADDR *) ptr; - ptr += qs->lpcsaBuffer[j].RemoteAddr.iSockaddrLength; - memset (qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr, 0, qs->lpcsaBuffer[j].RemoteAddr.iSockaddrLength); - ((struct sockaddr_in *)qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr)->sin_family = AF_INET; - ((struct sockaddr_in *)qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr)->sin_port = htonl (53); /* Don't ask why it's 53 */ - ((struct sockaddr_in *)qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr)->sin_addr = *(struct in_addr *) rd[i].data; - size_recalc += sizeof (CSADDR_INFO) + sizeof (struct sockaddr_in) * 2; - j++; - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - if (rd[i].data_size != sizeof (struct in6_addr)) - continue; - qs->lpcsaBuffer[j].iSocketType = SOCK_STREAM; - qs->lpcsaBuffer[j].iProtocol = IPPROTO_TCP; - - qs->lpcsaBuffer[j].LocalAddr.iSockaddrLength = sizeof (struct sockaddr_in6); - qs->lpcsaBuffer[j].LocalAddr.lpSockaddr = (SOCKADDR *) ptr; - ptr += qs->lpcsaBuffer[j].LocalAddr.iSockaddrLength; - memset (qs->lpcsaBuffer[j].LocalAddr.lpSockaddr, 0, qs->lpcsaBuffer[j].LocalAddr.iSockaddrLength); - ((struct sockaddr_in6 *)qs->lpcsaBuffer[j].LocalAddr.lpSockaddr)->sin6_family = AF_INET6; - - qs->lpcsaBuffer[j].RemoteAddr.iSockaddrLength = sizeof (struct sockaddr_in6); - qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr = (SOCKADDR *) ptr; - ptr += qs->lpcsaBuffer[j].RemoteAddr.iSockaddrLength; - memset (qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr, 0, qs->lpcsaBuffer[j].RemoteAddr.iSockaddrLength); - ((struct sockaddr_in6 *)qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr)->sin6_family = AF_INET6; - ((struct sockaddr_in6 *)qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr)->sin6_port = htonl (53); /* Don't ask why it's 53 */ - ((struct sockaddr_in6 *)qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr)->sin6_addr = *(struct in6_addr *) rd[i].data; - size_recalc += sizeof (CSADDR_INFO) + sizeof (struct sockaddr_in6) * 2; - j++; - break; - default: - break; + switch (rd[i].record_type) + { + case GNUNET_DNSPARSER_TYPE_A: + if (rd[i].data_size != sizeof(struct in_addr)) + continue; + qs->lpcsaBuffer[j].iSocketType = SOCK_STREAM; + qs->lpcsaBuffer[j].iProtocol = IPPROTO_TCP; + + qs->lpcsaBuffer[j].LocalAddr.iSockaddrLength = sizeof(struct sockaddr_in); + qs->lpcsaBuffer[j].LocalAddr.lpSockaddr = (SOCKADDR *)ptr; + ptr += qs->lpcsaBuffer[j].LocalAddr.iSockaddrLength; + memset(qs->lpcsaBuffer[j].LocalAddr.lpSockaddr, 0, qs->lpcsaBuffer[j].LocalAddr.iSockaddrLength); + ((struct sockaddr_in *)qs->lpcsaBuffer[j].LocalAddr.lpSockaddr)->sin_family = AF_INET; + + qs->lpcsaBuffer[j].RemoteAddr.iSockaddrLength = sizeof(struct sockaddr_in); + qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr = (SOCKADDR *)ptr; + ptr += qs->lpcsaBuffer[j].RemoteAddr.iSockaddrLength; + memset(qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr, 0, qs->lpcsaBuffer[j].RemoteAddr.iSockaddrLength); + ((struct sockaddr_in *)qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr)->sin_family = AF_INET; + ((struct sockaddr_in *)qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr)->sin_port = htonl(53); /* Don't ask why it's 53 */ + ((struct sockaddr_in *)qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr)->sin_addr = *(struct in_addr *)rd[i].data; + size_recalc += sizeof(CSADDR_INFO) + sizeof(struct sockaddr_in) * 2; + j++; + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + if (rd[i].data_size != sizeof(struct in6_addr)) + continue; + qs->lpcsaBuffer[j].iSocketType = SOCK_STREAM; + qs->lpcsaBuffer[j].iProtocol = IPPROTO_TCP; + + qs->lpcsaBuffer[j].LocalAddr.iSockaddrLength = sizeof(struct sockaddr_in6); + qs->lpcsaBuffer[j].LocalAddr.lpSockaddr = (SOCKADDR *)ptr; + ptr += qs->lpcsaBuffer[j].LocalAddr.iSockaddrLength; + memset(qs->lpcsaBuffer[j].LocalAddr.lpSockaddr, 0, qs->lpcsaBuffer[j].LocalAddr.iSockaddrLength); + ((struct sockaddr_in6 *)qs->lpcsaBuffer[j].LocalAddr.lpSockaddr)->sin6_family = AF_INET6; + + qs->lpcsaBuffer[j].RemoteAddr.iSockaddrLength = sizeof(struct sockaddr_in6); + qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr = (SOCKADDR *)ptr; + ptr += qs->lpcsaBuffer[j].RemoteAddr.iSockaddrLength; + memset(qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr, 0, qs->lpcsaBuffer[j].RemoteAddr.iSockaddrLength); + ((struct sockaddr_in6 *)qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr)->sin6_family = AF_INET6; + ((struct sockaddr_in6 *)qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr)->sin6_port = htonl(53); /* Don't ask why it's 53 */ + ((struct sockaddr_in6 *)qs->lpcsaBuffer[j].RemoteAddr.lpSockaddr)->sin6_addr = *(struct in6_addr *)rd[i].data; + size_recalc += sizeof(CSADDR_INFO) + sizeof(struct sockaddr_in6) * 2; + j++; + break; + + default: + break; + } } - } - GNUNET_break (size_recalc == (size_t) ((char *) ptr - (char *) msg)); + GNUNET_break(size_recalc == (size_t)((char *)ptr - (char *)msg)); qs->dwOutputFlags = 0; - if (IsEqualGUID (&SVCID_INET_HOSTADDRBYNAME, &rq->sc)) - { - struct hostent *he; - qs->lpBlob = (BLOB *) ptr; - ptr += sizeof (BLOB); - - size_recalc += sizeof (BLOB); - GNUNET_break (size_recalc == (size_t) ((char *) ptr - (char *) msg)); - - qs->lpBlob->cbSize = blobsize; - qs->lpBlob->pBlobData = (BYTE *) ptr; - ptr += sizeof (struct hostent); - - size_recalc += sizeof (struct hostent); - GNUNET_break (size_recalc == (size_t) ((char *) ptr - (char *) msg)); - - he = (struct hostent *) qs->lpBlob->pBlobData; - he->h_name = (char *) ptr; - ptr += strlen (rq->u8name) + 1; - - size_recalc += strlen (rq->u8name) + 1; - GNUNET_break (size_recalc == (size_t) ((char *) ptr - (char *) msg)); - - strcpy (he->h_name, rq->u8name); - he->h_aliases = (char **) ptr; - ptr += sizeof (void *); - - size_recalc += sizeof (void *); /* For aliases */ - GNUNET_break (size_recalc == (size_t) ((char *) ptr - (char *) msg)); - - he->h_aliases[0] = NULL; - he->h_addrtype = rq->af; - he->h_length = rq->af == AF_INET || rq->af == AF_UNSPEC ? sizeof (struct in_addr) : sizeof (struct in6_addr); - he->h_addr_list = (char **) ptr; - ptr += sizeof (void *) * (blobaddrcount + 1); - - size_recalc += sizeof (void *) * (blobaddrcount + 1); /* For addresses */ - GNUNET_break (size_recalc == (size_t) ((char *) ptr - (char *) msg)); + if (IsEqualGUID(&SVCID_INET_HOSTADDRBYNAME, &rq->sc)) + { + struct hostent *he; + qs->lpBlob = (BLOB *)ptr; + ptr += sizeof(BLOB); + + size_recalc += sizeof(BLOB); + GNUNET_break(size_recalc == (size_t)((char *)ptr - (char *)msg)); + + qs->lpBlob->cbSize = blobsize; + qs->lpBlob->pBlobData = (BYTE *)ptr; + ptr += sizeof(struct hostent); + + size_recalc += sizeof(struct hostent); + GNUNET_break(size_recalc == (size_t)((char *)ptr - (char *)msg)); + + he = (struct hostent *)qs->lpBlob->pBlobData; + he->h_name = (char *)ptr; + ptr += strlen(rq->u8name) + 1; + + size_recalc += strlen(rq->u8name) + 1; + GNUNET_break(size_recalc == (size_t)((char *)ptr - (char *)msg)); + + strcpy(he->h_name, rq->u8name); + he->h_aliases = (char **)ptr; + ptr += sizeof(void *); + + size_recalc += sizeof(void *); /* For aliases */ + GNUNET_break(size_recalc == (size_t)((char *)ptr - (char *)msg)); + + he->h_aliases[0] = NULL; + he->h_addrtype = rq->af; + he->h_length = rq->af == AF_INET || rq->af == AF_UNSPEC ? sizeof(struct in_addr) : sizeof(struct in6_addr); + he->h_addr_list = (char **)ptr; + ptr += sizeof(void *) * (blobaddrcount + 1); + + size_recalc += sizeof(void *) * (blobaddrcount + 1); /* For addresses */ + GNUNET_break(size_recalc == (size_t)((char *)ptr - (char *)msg)); + + j = 0; + for (i = 0; i < rd_count; i++) + { + if ((rq->af == AF_INET || rq->af == AF_UNSPEC) && + rd[i].record_type == GNUNET_DNSPARSER_TYPE_A) + { + he->h_addr_list[j] = (char *)ptr; + ptr += sizeof(struct in_addr); + + size_recalc += sizeof(struct in_addr); + GNUNET_break(size_recalc == (size_t)((char *)ptr - (char *)msg)); + + GNUNET_memcpy(he->h_addr_list[j], rd[i].data, sizeof(struct in_addr)); + j++; + } + else if (rq->af == AF_INET6 && rd[i].record_type == GNUNET_DNSPARSER_TYPE_AAAA) + { + he->h_addr_list[j] = (char *)ptr; + ptr += sizeof(struct in6_addr); + + size_recalc += sizeof(struct in6_addr); + GNUNET_break(size_recalc == (size_t)((char *)ptr - (char *)msg)); + + GNUNET_memcpy(he->h_addr_list[j], rd[i].data, sizeof(struct in6_addr)); + j++; + } + } + he->h_addr_list[j] = NULL; + } + msgend_env = GNUNET_MQ_msg(msgend, GNUNET_MESSAGE_TYPE_W32RESOLVER_RESPONSE); - j = 0; - for (i = 0; i < rd_count; i++) + if ((char *)ptr - (char *)msg != size || size_recalc != size || size_recalc != ((char *)ptr - (char *)msg)) { - if ((rq->af == AF_INET || rq->af == AF_UNSPEC) && - rd[i].record_type == GNUNET_DNSPARSER_TYPE_A) - { - he->h_addr_list[j] = (char *) ptr; - ptr += sizeof (struct in_addr); - - size_recalc += sizeof (struct in_addr); - GNUNET_break (size_recalc == (size_t) ((char *) ptr - (char *) msg)); - - GNUNET_memcpy (he->h_addr_list[j], rd[i].data, sizeof (struct in_addr)); - j++; - } - else if (rq->af == AF_INET6 && rd[i].record_type == GNUNET_DNSPARSER_TYPE_AAAA) - { - he->h_addr_list[j] = (char *) ptr; - ptr += sizeof (struct in6_addr); - - size_recalc += sizeof (struct in6_addr); - GNUNET_break (size_recalc == (size_t) ((char *) ptr - (char *) msg)); - - GNUNET_memcpy (he->h_addr_list[j], rd[i].data, sizeof (struct in6_addr)); - j++; - } + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error in WSAQUERYSETW size calc: expected %u, got %lu (recalc %u)\n", + size, + (unsigned long)((char *)ptr - (char *)msg), + size_recalc); } - he->h_addr_list[j] = NULL; - } - msgend_env = GNUNET_MQ_msg (msgend, GNUNET_MESSAGE_TYPE_W32RESOLVER_RESPONSE); - - if ((char *) ptr - (char *) msg != size || size_recalc != size || size_recalc != ((char *) ptr - (char *) msg)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error in WSAQUERYSETW size calc: expected %u, got %lu (recalc %u)\n", - size, - (unsigned long) ((char *) ptr - (char *) msg), - size_recalc); - } - MarshallWSAQUERYSETW (qs, &rq->sc); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (rq->client), - msg_env); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (rq->client), - msgend_env); - GNUNET_CONTAINER_DLL_remove (rq_head, - rq_tail, - rq); - GNUNET_free_non_null (rq->name); + MarshallWSAQUERYSETW(qs, &rq->sc); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(rq->client), + msg_env); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(rq->client), + msgend_env); + GNUNET_CONTAINER_DLL_remove(rq_head, + rq_tail, + rq); + GNUNET_free_non_null(rq->name); if (rq->u8name) - free (rq->u8name); - GNUNET_free (rq); + free(rq->u8name); + GNUNET_free(rq); } static void -get_ip_from_hostname (struct GNUNET_SERVICE_Client *client, - const wchar_t *name, - int af, - GUID sc) +get_ip_from_hostname(struct GNUNET_SERVICE_Client *client, + const wchar_t *name, + int af, + GUID sc) { struct request *rq; char *hostname; @@ -481,104 +483,104 @@ get_ip_from_hostname (struct GNUNET_SERVICE_Client *client, size_t namelen; uint32_t rtype; - if (IsEqualGUID (&SVCID_DNS_TYPE_A, &sc)) + if (IsEqualGUID(&SVCID_DNS_TYPE_A, &sc)) rtype = GNUNET_DNSPARSER_TYPE_A; - else if (IsEqualGUID (&SVCID_DNS_TYPE_NS, &sc)) + else if (IsEqualGUID(&SVCID_DNS_TYPE_NS, &sc)) rtype = GNUNET_DNSPARSER_TYPE_NS; - else if (IsEqualGUID (&SVCID_DNS_TYPE_CNAME, &sc)) + else if (IsEqualGUID(&SVCID_DNS_TYPE_CNAME, &sc)) rtype = GNUNET_DNSPARSER_TYPE_CNAME; - else if (IsEqualGUID (&SVCID_DNS_TYPE_SOA, &sc)) + else if (IsEqualGUID(&SVCID_DNS_TYPE_SOA, &sc)) rtype = GNUNET_DNSPARSER_TYPE_SOA; - else if (IsEqualGUID (&SVCID_DNS_TYPE_PTR, &sc)) + else if (IsEqualGUID(&SVCID_DNS_TYPE_PTR, &sc)) rtype = GNUNET_DNSPARSER_TYPE_PTR; - else if (IsEqualGUID (&SVCID_DNS_TYPE_MX, &sc)) + else if (IsEqualGUID(&SVCID_DNS_TYPE_MX, &sc)) rtype = GNUNET_DNSPARSER_TYPE_MX; - else if (IsEqualGUID (&SVCID_DNS_TYPE_TEXT, &sc)) + else if (IsEqualGUID(&SVCID_DNS_TYPE_TEXT, &sc)) rtype = GNUNET_DNSPARSER_TYPE_TXT; - else if (IsEqualGUID (&SVCID_DNS_TYPE_AAAA, &sc)) + else if (IsEqualGUID(&SVCID_DNS_TYPE_AAAA, &sc)) rtype = GNUNET_DNSPARSER_TYPE_AAAA; - else if (IsEqualGUID (&SVCID_DNS_TYPE_SRV, &sc)) + else if (IsEqualGUID(&SVCID_DNS_TYPE_SRV, &sc)) rtype = GNUNET_DNSPARSER_TYPE_SRV; - else if (IsEqualGUID (&SVCID_INET_HOSTADDRBYNAME, &sc)) + else if (IsEqualGUID(&SVCID_INET_HOSTADDRBYNAME, &sc)) rtype = GNUNET_DNSPARSER_TYPE_A; else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Unknown GUID: %08lX-%04X-%04X-%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X\n", - sc.Data1, - sc.Data2, - sc.Data3, - sc.Data4[0], - sc.Data4[1], - sc.Data4[2], - sc.Data4[3], - sc.Data4[4], - sc.Data4[5], - sc.Data4[6], - sc.Data4[7]); - GNUNET_SERVICE_client_drop (client); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Unknown GUID: %08lX-%04X-%04X-%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X\n", + sc.Data1, + sc.Data2, + sc.Data3, + sc.Data4[0], + sc.Data4[1], + sc.Data4[2], + sc.Data4[3], + sc.Data4[4], + sc.Data4[5], + sc.Data4[6], + sc.Data4[7]); + GNUNET_SERVICE_client_drop(client); + return; + } if (name) - namelen = wcslen (name); + namelen = wcslen(name); else namelen = 0; if (namelen > 0) - hostname = (char *) u16_to_u8 (name, namelen + 1, NULL, &strl); + hostname = (char *)u16_to_u8(name, namelen + 1, NULL, &strl); else hostname = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "W32 DNS resolver asked to look up %s for `%s'.\n", - af == AF_INET ? "IPv4" : af == AF_INET6 ? "IPv6" : "anything", - hostname); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "W32 DNS resolver asked to look up %s for `%s'.\n", + af == AF_INET ? "IPv4" : af == AF_INET6 ? "IPv6" : "anything", + hostname); - rq = GNUNET_new (struct request); + rq = GNUNET_new(struct request); rq->sc = sc; rq->client = client; rq->af = af; if (rq->af != AF_INET && rq->af != AF_INET6) rq->af = AF_INET; if (namelen) - { - rq->name = GNUNET_malloc ((namelen + 1) * sizeof (wchar_t)); - GNUNET_memcpy (rq->name, - name, - (namelen + 1) * sizeof (wchar_t)); - rq->u8name = hostname; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Launching a lookup for client %p with rq %p\n", - client, - rq); - rq->lookup_request = GNUNET_GNS_lookup (gns, - hostname, - &gns_master_pubkey, - rtype, - GNUNET_NO /* Use DHT */, - &process_lookup_result, - rq); + { + rq->name = GNUNET_malloc((namelen + 1) * sizeof(wchar_t)); + GNUNET_memcpy(rq->name, + name, + (namelen + 1) * sizeof(wchar_t)); + rq->u8name = hostname; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Launching a lookup for client %p with rq %p\n", + client, + rq); + rq->lookup_request = GNUNET_GNS_lookup(gns, + hostname, + &gns_master_pubkey, + rtype, + GNUNET_NO /* Use DHT */, + &process_lookup_result, + rq); if (NULL != rq->lookup_request) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Lookup launched, waiting for a reply\n"); - GNUNET_SERVICE_client_continue (client); - GNUNET_CONTAINER_DLL_insert (rq_head, - rq_tail, - rq); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Lookup launched, waiting for a reply\n"); + GNUNET_SERVICE_client_continue(client); + GNUNET_CONTAINER_DLL_insert(rq_head, + rq_tail, + rq); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Lookup was not launched, disconnecting the client\n"); - GNUNET_free_non_null (rq->name); - if (rq->u8name) - free (rq->u8name); - GNUNET_free (rq); - GNUNET_SERVICE_client_drop (client); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Lookup was not launched, disconnecting the client\n"); + GNUNET_free_non_null(rq->name); + if (rq->u8name) + free(rq->u8name); + GNUNET_free(rq); + GNUNET_SERVICE_client_drop(client); + } } @@ -590,25 +592,25 @@ get_ip_from_hostname (struct GNUNET_SERVICE_Client *client, * @return #GNUNET_OK if @a msg is well-formed */ static int -check_get (void *cls, - const struct GNUNET_W32RESOLVER_GetMessage *msg) +check_get(void *cls, + const struct GNUNET_W32RESOLVER_GetMessage *msg) { uint16_t size; const wchar_t *hostname; - if (! got_egos) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Not ready to process requests, lacking ego data\n")); - return GNUNET_SYSERR; - } - size = ntohs (msg->header.size) - sizeof (struct GNUNET_W32RESOLVER_GetMessage); - hostname = (const wchar_t *) &msg[1]; + if (!got_egos) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Not ready to process requests, lacking ego data\n")); + return GNUNET_SYSERR; + } + size = ntohs(msg->header.size) - sizeof(struct GNUNET_W32RESOLVER_GetMessage); + hostname = (const wchar_t *)&msg[1]; if (hostname[size / 2 - 1] != L'\0') - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -620,8 +622,8 @@ check_get (void *cls, * @param msg the actual message */ static void -handle_get (void *cls, - const struct GNUNET_W32RESOLVER_GetMessage *msg) +handle_get(void *cls, + const struct GNUNET_W32RESOLVER_GetMessage *msg) { struct GNUNET_SERVICE_Client *client = cls; GUID sc; @@ -629,50 +631,50 @@ handle_get (void *cls, const wchar_t *hostname; int af; - size = ntohs (msg->header.size) - sizeof (struct GNUNET_W32RESOLVER_GetMessage); - af = ntohl (msg->af); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got NBO GUID: %08X-%04X-%04X-%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X\n", - msg->sc_data1, - msg->sc_data2, - msg->sc_data3, - msg->sc_data4[0], - msg->sc_data4[1], - msg->sc_data4[2], - msg->sc_data4[3], - msg->sc_data4[4], - msg->sc_data4[5], - msg->sc_data4[6], - msg->sc_data4[7]); - sc.Data1 = ntohl (msg->sc_data1); - sc.Data2 = ntohs (msg->sc_data2); - sc.Data3 = ntohs (msg->sc_data3); + size = ntohs(msg->header.size) - sizeof(struct GNUNET_W32RESOLVER_GetMessage); + af = ntohl(msg->af); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got NBO GUID: %08X-%04X-%04X-%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X\n", + msg->sc_data1, + msg->sc_data2, + msg->sc_data3, + msg->sc_data4[0], + msg->sc_data4[1], + msg->sc_data4[2], + msg->sc_data4[3], + msg->sc_data4[4], + msg->sc_data4[5], + msg->sc_data4[6], + msg->sc_data4[7]); + sc.Data1 = ntohl(msg->sc_data1); + sc.Data2 = ntohs(msg->sc_data2); + sc.Data3 = ntohs(msg->sc_data3); for (int i = 0; i < 8; i++) sc.Data4[i] = msg->sc_data4[i]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got GUID: %08lX-%04X-%04X-%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X\n", - sc.Data1, - sc.Data2, - sc.Data3, - sc.Data4[0], - sc.Data4[1], - sc.Data4[2], - sc.Data4[3], - sc.Data4[4], - sc.Data4[5], - sc.Data4[6], - sc.Data4[7]); - hostname = (const wchar_t *) &msg[1]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name of %u bytes (last word is 0x%0X): %*S\n", - size, - hostname[size / 2 - 2], - size / 2, - hostname); - get_ip_from_hostname (client, - hostname, - af, - sc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got GUID: %08lX-%04X-%04X-%02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X\n", + sc.Data1, + sc.Data2, + sc.Data3, + sc.Data4[0], + sc.Data4[1], + sc.Data4[2], + sc.Data4[3], + sc.Data4[4], + sc.Data4[5], + sc.Data4[6], + sc.Data4[7]); + hostname = (const wchar_t *)&msg[1]; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name of %u bytes (last word is 0x%0X): %*S\n", + size, + hostname[size / 2 - 2], + size / 2, + hostname); + get_ip_from_hostname(client, + hostname, + af, + sc); } @@ -689,21 +691,21 @@ handle_get (void *cls, * must thus no longer be used */ static void -identity_master_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +identity_master_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { id_op = NULL; if (NULL == ego) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Ego for `gns-master' not found, cannot perform lookup. Did you run gnunet-gns-import.sh?\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_IDENTITY_ego_get_public_key (ego, - &gns_master_pubkey); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Ego for `gns-master' not found, cannot perform lookup. Did you run gnunet-gns-import.sh?\n")); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_IDENTITY_ego_get_public_key(ego, + &gns_master_pubkey); got_egos = 1; } @@ -716,35 +718,35 @@ identity_master_cb (void *cls, * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_SERVICE_Handle *service) { - gns = GNUNET_GNS_connect (cfg); + gns = GNUNET_GNS_connect(cfg); if (NULL == gns) - { - fprintf (stderr, - _("Failed to connect to GNS\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - identity = GNUNET_IDENTITY_connect (cfg, - NULL, - NULL); + { + fprintf(stderr, + _("Failed to connect to GNS\n")); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); + identity = GNUNET_IDENTITY_connect(cfg, + NULL, + NULL); if (NULL == identity) - { - fprintf (stderr, - _("Failed to connect to identity service\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } - id_op = GNUNET_IDENTITY_get (identity, - "gns-master", - &identity_master_cb, - NULL); - GNUNET_assert (NULL != id_op); + { + fprintf(stderr, + _("Failed to connect to identity service\n")); + GNUNET_SCHEDULER_shutdown(); + return; + } + id_op = GNUNET_IDENTITY_get(identity, + "gns-master", + &identity_master_cb, + NULL); + GNUNET_assert(NULL != id_op); } @@ -757,9 +759,9 @@ run (void *cls, * @return @a client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { return client; } @@ -773,11 +775,11 @@ client_connect_cb (void *cls, * @param internal_cls should be equal to @a c */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *internal_cls) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *internal_cls) { - GNUNET_assert (internal_cls == client); + GNUNET_assert(internal_cls == client); } @@ -785,17 +787,17 @@ client_disconnect_cb (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("gns-helper-service-w32", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_var_size (get, + ("gns-helper-service-w32", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_var_size(get, GNUNET_MESSAGE_TYPE_W32RESOLVER_REQUEST, struct GNUNET_W32RESOLVER_GetMessage, NULL), - GNUNET_MQ_handler_end()); + GNUNET_MQ_handler_end()); /* end of gnunet-gns-helper-service-w32.c */ diff --git a/src/gns/gnunet-gns-import.c b/src/gns/gnunet-gns-import.c index 5e3560313..82710b803 100644 --- a/src/gns/gnunet-gns-import.c +++ b/src/gns/gnunet-gns-import.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnunet-gns.c * @brief binary version of gnunet-gns-import.sh @@ -86,13 +86,13 @@ static int ret; static int -run_process_and_wait (int pipe_control, - enum GNUNET_OS_InheritStdioFlags std_inheritance, - struct GNUNET_DISK_PipeHandle *pipe_stdin, - struct GNUNET_DISK_PipeHandle *pipe_stdout, - enum GNUNET_OS_ProcessStatusType *st, - unsigned long *code, - const char *filename, ...) +run_process_and_wait(int pipe_control, + enum GNUNET_OS_InheritStdioFlags std_inheritance, + struct GNUNET_DISK_PipeHandle *pipe_stdin, + struct GNUNET_DISK_PipeHandle *pipe_stdout, + enum GNUNET_OS_ProcessStatusType *st, + unsigned long *code, + const char *filename, ...) { static struct GNUNET_OS_Process *p; int arglen; @@ -101,93 +101,96 @@ run_process_and_wait (int pipe_control, char *argp; va_list ap, apc1, apc2; - va_start (ap, filename); - va_copy (apc1, ap); - va_copy (apc2, ap); + va_start(ap, filename); + va_copy(apc1, ap); + va_copy(apc2, ap); arglen = 0; - while (NULL != (arg = va_arg (apc1, char *))) - arglen += strlen (arg) + 1; - va_end (apc1); - args = argp = GNUNET_malloc (arglen); - while (NULL != (arg = va_arg (apc2, char *))) - { - strcpy (argp, arg); - argp += strlen (arg); - *argp = ' '; - argp += 1; - } - va_end (apc2); + while (NULL != (arg = va_arg(apc1, char *))) + arglen += strlen(arg) + 1; + va_end(apc1); + args = argp = GNUNET_malloc(arglen); + while (NULL != (arg = va_arg(apc2, char *))) + { + strcpy(argp, arg); + argp += strlen(arg); + *argp = ' '; + argp += 1; + } + va_end(apc2); if (arglen > 0) argp[-1] = '\0'; - p = GNUNET_OS_start_process_va (pipe_control, std_inheritance, - pipe_stdin, - pipe_stdout, - NULL, - filename, ap); - va_end (ap); + p = GNUNET_OS_start_process_va(pipe_control, std_inheritance, + pipe_stdin, + pipe_stdout, + NULL, + filename, ap); + va_end(ap); if (NULL == p) - { - ret = 3; - fprintf (stderr, "Failed to run `%s'\n", args); - GNUNET_free (args); - return 1; - } - - if (GNUNET_OK != GNUNET_OS_process_wait (p)) - { - ret = 4; - fprintf (stderr, "Failed to wait for `%s'\n", args); - GNUNET_free (args); - return 1; - } - - switch (GNUNET_OS_process_status (p, st, code)) - { + { + ret = 3; + fprintf(stderr, "Failed to run `%s'\n", args); + GNUNET_free(args); + return 1; + } + + if (GNUNET_OK != GNUNET_OS_process_wait(p)) + { + ret = 4; + fprintf(stderr, "Failed to wait for `%s'\n", args); + GNUNET_free(args); + return 1; + } + + switch (GNUNET_OS_process_status(p, st, code)) + { case GNUNET_OK: break; + case GNUNET_NO: ret = 5; - fprintf (stderr, "`%s' is still running\n", args); - GNUNET_free (args); + fprintf(stderr, "`%s' is still running\n", args); + GNUNET_free(args); return 1; + default: case GNUNET_SYSERR: ret = 6; - fprintf (stderr, "Failed to check the status of `%s'\n", args); - GNUNET_free (args); + fprintf(stderr, "Failed to check the status of `%s'\n", args); + GNUNET_free(args); return 1; - } + } #ifdef WINDOWS if (GNUNET_OS_PROCESS_EXITED != *st || 0 != *code) - { - ret = 7; - fprintf (stderr, "`%s' did not end correctly (%d, %d)\n", args, *st, *code); - return 1; - } + { + ret = 7; + fprintf(stderr, "`%s' did not end correctly (%d, %d)\n", args, *st, *code); + return 1; + } #endif return 0; } static void -check_pkey (unsigned int rd_len, const struct GNUNET_GNSRECORD_Data *rd, - char *pk, int *found_rec) +check_pkey(unsigned int rd_len, const struct GNUNET_GNSRECORD_Data *rd, + char *pk, int *found_rec) { int i; + for (i = 0; i < rd_len; i++) - { - char *s; - if (GNUNET_GNSRECORD_TYPE_PKEY != rd[i].record_type || - rd[i].data_size != sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)) - continue; - s = GNUNET_GNSRECORD_value_to_string (rd[i].record_type, - rd[i].data, - rd[i].data_size); - if (NULL == s) - continue; - if (0 == strcmp (s, pk)) - *found_rec = GNUNET_YES; - GNUNET_free (s); - } + { + char *s; + if (GNUNET_GNSRECORD_TYPE_PKEY != rd[i].record_type || + rd[i].data_size != sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey)) + continue; + s = GNUNET_GNSRECORD_value_to_string(rd[i].record_type, + rd[i].data, + rd[i].data_size); + if (NULL == s) + continue; + if (0 == strcmp(s, pk)) + *found_rec = GNUNET_YES; + GNUNET_free(s); + } } /** @@ -200,53 +203,54 @@ check_pkey (unsigned int rd_len, const struct GNUNET_GNSRECORD_Data *rd, * @param rd array of records with data to store */ static void -zone_iterator (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *rname, unsigned int rd_len, - const struct GNUNET_GNSRECORD_Data *rd) +zone_iterator(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *rname, unsigned int rd_len, + const struct GNUNET_GNSRECORD_Data *rd) { if (NULL != rname) - { - if (0 == strcmp (rname, "private")) - check_pkey (rd_len, rd, private_zone_pkey, &found_private_rec); - else if (0 == strcmp (rname, "pin")) - check_pkey (rd_len, rd, pin_zone_pkey, &found_pin_rec); - } - GNUNET_NAMESTORE_zone_iterator_next (list_it); + { + if (0 == strcmp(rname, "private")) + check_pkey(rd_len, rd, private_zone_pkey, &found_private_rec); + else if (0 == strcmp(rname, "pin")) + check_pkey(rd_len, rd, pin_zone_pkey, &found_pin_rec); + } + GNUNET_NAMESTORE_zone_iterator_next(list_it); } static void -zone_iteration_error (void *cls) +zone_iteration_error(void *cls) { enum GNUNET_OS_ProcessStatusType st; unsigned long code; + if (!found_private_rec) - { - if (0 != run_process_and_wait (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, - "gnunet-namestore", - "gnunet-namestore", "-z", "master-zone", "-a", "-e", "never", "-n", "private", "-p", "-t", "PKEY", "-V", private_zone_pkey, NULL)) { - ret = 8; - return; + if (0 != run_process_and_wait(GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, + "gnunet-namestore", + "gnunet-namestore", "-z", "master-zone", "-a", "-e", "never", "-n", "private", "-p", "-t", "PKEY", "-V", private_zone_pkey, NULL)) + { + ret = 8; + return; + } } - } if (!found_pin_rec) - { - if (0 != run_process_and_wait (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, - "gnunet-namestore", - "gnunet-namestore", "-z", "master-zone", "-a", "-e", "never", "-n", "pin", "-p", "-t", "PKEY", "-V", pin_zone_pkey, NULL)) { - ret = 10; - return; + if (0 != run_process_and_wait(GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, + "gnunet-namestore", + "gnunet-namestore", "-z", "master-zone", "-a", "-e", "never", "-n", "pin", "-p", "-t", "PKEY", "-V", pin_zone_pkey, NULL)) + { + ret = 10; + return; + } } - } list_it = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } static void -zone_iteration_finished (void *cls) +zone_iteration_finished(void *cls) { } @@ -283,43 +287,44 @@ zone_iteration_finished (void *cls) * @param identifier identifier assigned by the user for this ego, * NULL if the user just deleted the ego and it * must thus no longer be used -*/ + */ static void -get_ego (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *identifier) +get_ego(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *identifier) { static struct GNUNET_CRYPTO_EcdsaPublicKey pk; + if (NULL == ego) - { - if (NULL == master_zone_pkey || - NULL == private_zone_pkey) { - ret = 11; - GNUNET_SCHEDULER_shutdown (); + if (NULL == master_zone_pkey || + NULL == private_zone_pkey) + { + ret = 11; + GNUNET_SCHEDULER_shutdown(); + return; + } + list_it = GNUNET_NAMESTORE_zone_iteration_start(ns, + &master_pk, &zone_iteration_error, NULL, &zone_iterator, NULL, &zone_iteration_finished, NULL); + if (NULL == list_it) + { + ret = 12; + GNUNET_SCHEDULER_shutdown(); + } return; } - list_it = GNUNET_NAMESTORE_zone_iteration_start (ns, - &master_pk, &zone_iteration_error, NULL, &zone_iterator, NULL, &zone_iteration_finished, NULL); - if (NULL == list_it) - { - ret = 12; - GNUNET_SCHEDULER_shutdown (); - } - return; - } - GNUNET_IDENTITY_ego_get_public_key (ego, &pk); + GNUNET_IDENTITY_ego_get_public_key(ego, &pk); if (NULL != identifier) - { - if (NULL == master_zone_pkey && 0 == strcmp ("master-zone", identifier)) { - master_zone_pkey = GNUNET_CRYPTO_ecdsa_public_key_to_string (&pk); - master_pk = *GNUNET_IDENTITY_ego_get_private_key (ego); + if (NULL == master_zone_pkey && 0 == strcmp("master-zone", identifier)) + { + master_zone_pkey = GNUNET_CRYPTO_ecdsa_public_key_to_string(&pk); + master_pk = *GNUNET_IDENTITY_ego_get_private_key(ego); + } + else if (NULL == private_zone_pkey && 0 == strcmp("private-zone", identifier)) + private_zone_pkey = GNUNET_CRYPTO_ecdsa_public_key_to_string(&pk); } - else if (NULL == private_zone_pkey && 0 == strcmp ("private-zone", identifier)) - private_zone_pkey = GNUNET_CRYPTO_ecdsa_public_key_to_string (&pk); - } } /** @@ -328,27 +333,27 @@ get_ego (void *cls, * @param cls NULL */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - GNUNET_free_non_null (master_zone_pkey); + GNUNET_free_non_null(master_zone_pkey); master_zone_pkey = NULL; - GNUNET_free_non_null (private_zone_pkey); + GNUNET_free_non_null(private_zone_pkey); private_zone_pkey = NULL; if (NULL != list_it) - { - GNUNET_NAMESTORE_zone_iteration_stop (list_it); - list_it = NULL; - } + { + GNUNET_NAMESTORE_zone_iteration_stop(list_it); + list_it = NULL; + } if (NULL != ns) - { - GNUNET_NAMESTORE_disconnect (ns); - ns = NULL; - } + { + GNUNET_NAMESTORE_disconnect(ns); + ns = NULL; + } if (NULL != sh) - { - GNUNET_IDENTITY_disconnect (sh); - sh = NULL; - } + { + GNUNET_IDENTITY_disconnect(sh); + sh = NULL; + } } /** @@ -360,71 +365,71 @@ shutdown_task (void *cls) * @param c configuration */ static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { enum GNUNET_OS_ProcessStatusType st; unsigned long code; cfg = c; - if (0 != run_process_and_wait (GNUNET_NO, 0, NULL, NULL, &st, &code, - "gnunet-arm", - "gnunet-arm", "-I", NULL)) - { - if (7 == ret) - fprintf (stderr, "GNUnet is not running, please start GNUnet before running import\n"); - return; - } + if (0 != run_process_and_wait(GNUNET_NO, 0, NULL, NULL, &st, &code, + "gnunet-arm", + "gnunet-arm", "-I", NULL)) + { + if (7 == ret) + fprintf(stderr, "GNUnet is not running, please start GNUnet before running import\n"); + return; + } - if (0 != run_process_and_wait (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, - "gnunet-identity", - "gnunet-identity", "-C", "master-zone", NULL)) + if (0 != run_process_and_wait(GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, + "gnunet-identity", + "gnunet-identity", "-C", "master-zone", NULL)) return; - if (0 != run_process_and_wait (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, - "gnunet-identity", - "gnunet-identity", "-C", "private-zone", NULL)) + if (0 != run_process_and_wait(GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, + "gnunet-identity", + "gnunet-identity", "-C", "private-zone", NULL)) return; - if (0 != run_process_and_wait (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, - "gnunet-identity", - "gnunet-identity", "-C", "sks-zone", NULL)) + if (0 != run_process_and_wait(GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, + "gnunet-identity", + "gnunet-identity", "-C", "sks-zone", NULL)) return; - if (0 != run_process_and_wait (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, - "gnunet-identity", - "gnunet-identity", "-e", "master-zone", "-s", "gns-master", NULL)) + if (0 != run_process_and_wait(GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, + "gnunet-identity", + "gnunet-identity", "-e", "master-zone", "-s", "gns-master", NULL)) return; - if (0 != run_process_and_wait (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, - "gnunet-identity", - "gnunet-identity", "-e", "master-zone", "-s", "namestore", NULL)) + if (0 != run_process_and_wait(GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, + "gnunet-identity", + "gnunet-identity", "-e", "master-zone", "-s", "namestore", NULL)) return; - if (0 != run_process_and_wait (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, - "gnunet-identity", - "gnunet-identity", "-e", "master-zone", "-s", "gns-proxy", NULL)) + if (0 != run_process_and_wait(GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, + "gnunet-identity", + "gnunet-identity", "-e", "master-zone", "-s", "gns-proxy", NULL)) return; - if (0 != run_process_and_wait (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, - "gnunet-identity", - "gnunet-identity", "-e", "master-zone", "-s", "gns-intercept", NULL)) + if (0 != run_process_and_wait(GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, + "gnunet-identity", + "gnunet-identity", "-e", "master-zone", "-s", "gns-intercept", NULL)) return; - if (0 != run_process_and_wait (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, - "gnunet-identity", - "gnunet-identity", "-e", "private-zone", "-s", "gns-private", NULL)) + if (0 != run_process_and_wait(GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, + "gnunet-identity", + "gnunet-identity", "-e", "private-zone", "-s", "gns-private", NULL)) return; - if (0 != run_process_and_wait (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, - "gnunet-identity", - "gnunet-identity", "-e", "sks-zone", "-s", "fs-sks", NULL)) + if (0 != run_process_and_wait(GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, NULL, NULL, &st, &code, + "gnunet-identity", + "gnunet-identity", "-e", "sks-zone", "-s", "fs-sks", NULL)) return; - ns = GNUNET_NAMESTORE_connect (cfg); - sh = GNUNET_IDENTITY_connect (cfg, &get_ego, NULL); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + ns = GNUNET_NAMESTORE_connect(cfg); + sh = GNUNET_IDENTITY_connect(cfg, &get_ego, NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); } @@ -436,23 +441,23 @@ run (void *cls, char *const *args, const char *cfgfile, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { static const struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; int r; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; - GNUNET_log_setup ("gnunet-gns-import", "WARNING", NULL); + GNUNET_log_setup("gnunet-gns-import", "WARNING", NULL); ret = 0; - r = GNUNET_PROGRAM_run (argc, argv, "gnunet-gns-import", - _("This program will import some GNS authorities into your GNS namestore."), - options, - &run, NULL); - GNUNET_free ((void*) argv); + r = GNUNET_PROGRAM_run(argc, argv, "gnunet-gns-import", + _("This program will import some GNS authorities into your GNS namestore."), + options, + &run, NULL); + GNUNET_free((void*)argv); return GNUNET_OK == r ? ret : 1; } diff --git a/src/gns/gnunet-gns-proxy.c b/src/gns/gnunet-gns-proxy.c index eb8115026..6285a8fcd 100644 --- a/src/gns/gnunet-gns-proxy.c +++ b/src/gns/gnunet-gns-proxy.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Martin Schanzenbach * @author Christian Grothoff @@ -94,13 +94,13 @@ /** * After how long do we clean up unused MHD TLS instances? */ -#define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5) +#define MHD_CACHE_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5) /** * After how long do we clean up Socks5 handles that failed to show any activity * with their respective MHD instance? */ -#define HTTP_HANDSHAKE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15) +#define HTTP_HANDSHAKE_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15) /** @@ -110,13 +110,13 @@ * @param fun name of curl_easy-function that gave the error * @param rc return code from curl */ -#define LOG_CURL_EASY(level,fun,rc) \ - GNUNET_log (level, \ - _("%s failed at %s:%d: `%s'\n"), \ - fun, \ - __FILE__, \ - __LINE__, \ - curl_easy_strerror (rc)) +#define LOG_CURL_EASY(level, fun, rc) \ + GNUNET_log(level, \ + _("%s failed at %s:%d: `%s'\n"), \ + fun, \ + __FILE__, \ + __LINE__, \ + curl_easy_strerror(rc)) /* *************** Socks protocol definitions (move to TUN?) ****************** */ @@ -135,8 +135,7 @@ /** * Commands in Socks5. */ -enum Socks5Commands -{ +enum Socks5Commands { /** * Establish TCP/IP stream. */ @@ -157,8 +156,7 @@ enum Socks5Commands /** * Address types in Socks5. */ -enum Socks5AddressType -{ +enum Socks5AddressType { /** * IPv4 address. */ @@ -173,15 +171,13 @@ enum Socks5AddressType * IPv6 address. */ SOCKS5_AT_IPV6 = 4 - }; /** * Status codes in Socks5 response. */ -enum Socks5StatusCode -{ +enum Socks5StatusCode { SOCKS5_STATUS_REQUEST_GRANTED = 0, SOCKS5_STATUS_GENERAL_FAILURE = 1, SOCKS5_STATUS_CONNECTION_NOT_ALLOWED_BY_RULE = 2, @@ -197,8 +193,7 @@ enum Socks5StatusCode /** * Client hello in Socks5 protocol. */ -struct Socks5ClientHelloMessage -{ +struct Socks5ClientHelloMessage { /** * Should be #SOCKS_VERSION_5. */ @@ -210,15 +205,13 @@ struct Socks5ClientHelloMessage uint8_t num_auth_methods; /* followed by supported authentication methods, 1 byte per method */ - }; /** * Server hello in Socks5 protocol. */ -struct Socks5ServerHelloMessage -{ +struct Socks5ServerHelloMessage { /** * Should be #SOCKS_VERSION_5. */ @@ -235,8 +228,7 @@ struct Socks5ServerHelloMessage /** * Client socks request in Socks5 protocol. */ -struct Socks5ClientRequestMessage -{ +struct Socks5ClientRequestMessage { /** * Should be #SOCKS_VERSION_5. */ @@ -268,8 +260,7 @@ struct Socks5ClientRequestMessage /** * Server response to client requests in Socks5 protocol. */ -struct Socks5ServerResponseMessage -{ +struct Socks5ServerResponseMessage { /** * Should be #SOCKS_VERSION_5. */ @@ -295,7 +286,6 @@ struct Socks5ServerResponseMessage * length field (uint8_t) in front (depending on @e addr_type). * followed by port number in network byte order (uint16_t). */ - }; @@ -305,8 +295,7 @@ struct Socks5ServerResponseMessage /** * A structure for CA cert/key */ -struct ProxyCA -{ +struct ProxyCA { /** * The certificate */ @@ -322,8 +311,7 @@ struct ProxyCA /** * Structure for GNS certificates */ -struct ProxyGNSCertificate -{ +struct ProxyGNSCertificate { /** * The certificate as PEM */ @@ -340,8 +328,7 @@ struct ProxyGNSCertificate /** * A structure for all running Httpds */ -struct MhdHttpList -{ +struct MhdHttpList { /** * DLL for httpds */ @@ -376,7 +363,6 @@ struct MhdHttpList * is this an ssl daemon? */ int is_ssl; - }; @@ -386,8 +372,7 @@ struct MhdHttpList /** * The socks phases. */ -enum SocksPhase -{ +enum SocksPhase { /** * We're waiting to get the client hello. */ @@ -443,8 +428,7 @@ enum SocksPhase /** * A header list */ -struct HttpResponseHeader -{ +struct HttpResponseHeader { /** * DLL */ @@ -469,9 +453,7 @@ struct HttpResponseHeader /** * A structure for socks requests */ -struct Socks5Request -{ - +struct Socks5Request { /** * DLL. */ @@ -769,7 +751,7 @@ static const struct GNUNET_CONFIGURATION_Handle *cfg; * @param hd the daemon to run now. */ static void -run_mhd_now (struct MhdHttpList *hd); +run_mhd_now(struct MhdHttpList *hd); /** @@ -778,79 +760,79 @@ run_mhd_now (struct MhdHttpList *hd); * @param s5r the handle to destroy */ static void -cleanup_s5r (struct Socks5Request *s5r) +cleanup_s5r(struct Socks5Request *s5r) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Cleaning up socks request\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Cleaning up socks request\n"); if (NULL != s5r->curl) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Cleaning up cURL handle\n"); - curl_multi_remove_handle (curl_multi, - s5r->curl); - curl_easy_cleanup (s5r->curl); - s5r->curl = NULL; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Cleaning up cURL handle\n"); + curl_multi_remove_handle(curl_multi, + s5r->curl); + curl_easy_cleanup(s5r->curl); + s5r->curl = NULL; + } if (s5r->suspended) - { - s5r->suspended = GNUNET_NO; - MHD_resume_connection (s5r->con); - } - curl_slist_free_all (s5r->headers); + { + s5r->suspended = GNUNET_NO; + MHD_resume_connection(s5r->con); + } + curl_slist_free_all(s5r->headers); if (NULL != s5r->hosts) - { - curl_slist_free_all (s5r->hosts); - } - if ( (NULL != s5r->response) && - (curl_failure_response != s5r->response) ) - { - MHD_destroy_response (s5r->response); - s5r->response = NULL; - } + { + curl_slist_free_all(s5r->hosts); + } + if ((NULL != s5r->response) && + (curl_failure_response != s5r->response)) + { + MHD_destroy_response(s5r->response); + s5r->response = NULL; + } if (NULL != s5r->rtask) - { - GNUNET_SCHEDULER_cancel (s5r->rtask); - s5r->rtask = NULL; - } + { + GNUNET_SCHEDULER_cancel(s5r->rtask); + s5r->rtask = NULL; + } if (NULL != s5r->timeout_task) - { - GNUNET_SCHEDULER_cancel (s5r->timeout_task); - s5r->timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(s5r->timeout_task); + s5r->timeout_task = NULL; + } if (NULL != s5r->wtask) - { - GNUNET_SCHEDULER_cancel (s5r->wtask); - s5r->wtask = NULL; - } + { + GNUNET_SCHEDULER_cancel(s5r->wtask); + s5r->wtask = NULL; + } if (NULL != s5r->gns_lookup) - { - GNUNET_GNS_lookup_with_tld_cancel (s5r->gns_lookup); - s5r->gns_lookup = NULL; - } + { + GNUNET_GNS_lookup_with_tld_cancel(s5r->gns_lookup); + s5r->gns_lookup = NULL; + } if (NULL != s5r->sock) - { - if (SOCKS5_SOCKET_WITH_MHD <= s5r->state) - GNUNET_NETWORK_socket_free_memory_only_ (s5r->sock); - else - GNUNET_NETWORK_socket_close (s5r->sock); - s5r->sock = NULL; - } - GNUNET_CONTAINER_DLL_remove (s5r_head, - s5r_tail, - s5r); - GNUNET_free_non_null (s5r->domain); - GNUNET_free_non_null (s5r->leho); - GNUNET_free_non_null (s5r->url); - for (unsigned int i=0;inum_danes;i++) - GNUNET_free (s5r->dane_data[i]); - GNUNET_free (s5r); + { + if (SOCKS5_SOCKET_WITH_MHD <= s5r->state) + GNUNET_NETWORK_socket_free_memory_only_(s5r->sock); + else + GNUNET_NETWORK_socket_close(s5r->sock); + s5r->sock = NULL; + } + GNUNET_CONTAINER_DLL_remove(s5r_head, + s5r_tail, + s5r); + GNUNET_free_non_null(s5r->domain); + GNUNET_free_non_null(s5r->leho); + GNUNET_free_non_null(s5r->url); + for (unsigned int i = 0; i < s5r->num_danes; i++) + GNUNET_free(s5r->dane_data[i]); + GNUNET_free(s5r); } /* ************************* HTTP handling with cURL *********************** */ static void -curl_download_prepare (); +curl_download_prepare(); /** @@ -865,89 +847,89 @@ curl_download_prepare (); * @return number of bytes written to @a buf */ static ssize_t -mhd_content_cb (void *cls, - uint64_t pos, - char* buf, - size_t max) +mhd_content_cb(void *cls, + uint64_t pos, + char* buf, + size_t max) { struct Socks5Request *s5r = cls; size_t bytes_to_copy; - if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) || - (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) ) - { - /* we're still not done with the upload, do not yet - start the download, the IO buffer is still full - with upload data. */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Pausing MHD download %s%s, not yet ready for download\n", - s5r->domain, - s5r->url); - return 0; /* not yet ready for data download */ - } - bytes_to_copy = GNUNET_MIN (max, - s5r->io_len); - if ( (0 == bytes_to_copy) && - (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Pausing MHD download %s%s, no data available\n", - s5r->domain, - s5r->url); - if (NULL != s5r->curl) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Continuing CURL interaction for %s%s\n", - s5r->domain, - s5r->url); - if (GNUNET_YES == s5r->curl_paused) - { - s5r->curl_paused = GNUNET_NO; - curl_easy_pause (s5r->curl, - CURLPAUSE_CONT); - } - curl_download_prepare (); + if ((SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) || + (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state)) + { + /* we're still not done with the upload, do not yet + start the download, the IO buffer is still full + with upload data. */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Pausing MHD download %s%s, not yet ready for download\n", + s5r->domain, + s5r->url); + return 0; /* not yet ready for data download */ } - if (GNUNET_NO == s5r->suspended) + bytes_to_copy = GNUNET_MIN(max, + s5r->io_len); + if ((0 == bytes_to_copy) && + (SOCKS5_SOCKET_DOWNLOAD_DONE != s5r->state)) { - MHD_suspend_connection (s5r->con); - s5r->suspended = GNUNET_YES; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Pausing MHD download %s%s, no data available\n", + s5r->domain, + s5r->url); + if (NULL != s5r->curl) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Continuing CURL interaction for %s%s\n", + s5r->domain, + s5r->url); + if (GNUNET_YES == s5r->curl_paused) + { + s5r->curl_paused = GNUNET_NO; + curl_easy_pause(s5r->curl, + CURLPAUSE_CONT); + } + curl_download_prepare(); + } + if (GNUNET_NO == s5r->suspended) + { + MHD_suspend_connection(s5r->con); + s5r->suspended = GNUNET_YES; + } + return 0; /* more data later */ } - return 0; /* more data later */ - } - if ( (0 == bytes_to_copy) && - (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Completed MHD download %s%s\n", - s5r->domain, - s5r->url); - return MHD_CONTENT_READER_END_OF_STREAM; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Writing %llu/%llu bytes to %s%s\n", - (unsigned long long) bytes_to_copy, - (unsigned long long) s5r->io_len, - s5r->domain, - s5r->url); - GNUNET_memcpy (buf, - s5r->io_buf, - bytes_to_copy); - memmove (s5r->io_buf, - &s5r->io_buf[bytes_to_copy], - s5r->io_len - bytes_to_copy); + if ((0 == bytes_to_copy) && + (SOCKS5_SOCKET_DOWNLOAD_DONE == s5r->state)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Completed MHD download %s%s\n", + s5r->domain, + s5r->url); + return MHD_CONTENT_READER_END_OF_STREAM; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Writing %llu/%llu bytes to %s%s\n", + (unsigned long long)bytes_to_copy, + (unsigned long long)s5r->io_len, + s5r->domain, + s5r->url); + GNUNET_memcpy(buf, + s5r->io_buf, + bytes_to_copy); + memmove(s5r->io_buf, + &s5r->io_buf[bytes_to_copy], + s5r->io_len - bytes_to_copy); s5r->io_len -= bytes_to_copy; - if ( (NULL != s5r->curl) && - (GNUNET_YES == s5r->curl_paused) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Continuing CURL interaction for %s%s\n", - s5r->domain, - s5r->url); - s5r->curl_paused = GNUNET_NO; - curl_easy_pause (s5r->curl, - CURLPAUSE_CONT); - } + if ((NULL != s5r->curl) && + (GNUNET_YES == s5r->curl_paused)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Continuing CURL interaction for %s%s\n", + s5r->domain, + s5r->url); + s5r->curl_paused = GNUNET_NO; + curl_easy_pause(s5r->curl, + CURLPAUSE_CONT); + } return bytes_to_copy; } @@ -961,7 +943,7 @@ mhd_content_cb (void *cls, * @return #GNUNET_OK if the certificate is valid */ static int -check_ssl_certificate (struct Socks5Request *s5r) +check_ssl_certificate(struct Socks5Request *s5r) { unsigned int cert_list_size; const gnutls_datum_t *chainp; @@ -973,113 +955,113 @@ check_ssl_certificate (struct Socks5Request *s5r) const char *name; s5r->ssl_checked = GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Checking X.509 certificate\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Checking X.509 certificate\n"); if (CURLE_OK != - curl_easy_getinfo (s5r->curl, - CURLINFO_TLS_SESSION, - &tlsinfo)) + curl_easy_getinfo(s5r->curl, + CURLINFO_TLS_SESSION, + &tlsinfo)) return GNUNET_SYSERR; if (CURLSSLBACKEND_GNUTLS != tlsinfo->backend) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unsupported CURL TLS backend %d\n"), - tlsinfo->backend); - return GNUNET_SYSERR; - } - chainp = gnutls_certificate_get_peers (tlsinfo->internals, - &cert_list_size); - if ( (! chainp) || - (0 == cert_list_size) ) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unsupported CURL TLS backend %d\n"), + tlsinfo->backend); + return GNUNET_SYSERR; + } + chainp = gnutls_certificate_get_peers(tlsinfo->internals, + &cert_list_size); + if ((!chainp) || + (0 == cert_list_size)) return GNUNET_SYSERR; - size = sizeof (certdn); + size = sizeof(certdn); /* initialize an X.509 certificate structure. */ - gnutls_x509_crt_init (&x509_cert); - gnutls_x509_crt_import (x509_cert, - chainp, - GNUTLS_X509_FMT_DER); - - if (0 != (rc = gnutls_x509_crt_get_dn_by_oid (x509_cert, - GNUTLS_OID_X520_COMMON_NAME, - 0, /* the first and only one */ - 0 /* no DER encoding */, - certdn, - &size))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed to fetch CN from cert: %s\n"), - gnutls_strerror(rc)); - gnutls_x509_crt_deinit (x509_cert); - return GNUNET_SYSERR; - } + gnutls_x509_crt_init(&x509_cert); + gnutls_x509_crt_import(x509_cert, + chainp, + GNUTLS_X509_FMT_DER); + + if (0 != (rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, + GNUTLS_OID_X520_COMMON_NAME, + 0, /* the first and only one */ + 0 /* no DER encoding */, + certdn, + &size))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to fetch CN from cert: %s\n"), + gnutls_strerror(rc)); + gnutls_x509_crt_deinit(x509_cert); + return GNUNET_SYSERR; + } /* check for TLSA/DANE records */ #if HAVE_GNUTLS_DANE if (0 != s5r->num_danes) - { - dane_state_t dane_state; - dane_query_t dane_query; - unsigned int verify; + { + dane_state_t dane_state; + dane_query_t dane_query; + unsigned int verify; - /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */ - if (0 != (rc = dane_state_init (&dane_state, + /* FIXME: add flags to gnutls to NOT read UNBOUND_ROOT_KEY_FILE here! */ + if (0 != (rc = dane_state_init(&dane_state, #ifdef DANE_F_IGNORE_DNSSEC - DANE_F_IGNORE_DNSSEC | + DANE_F_IGNORE_DNSSEC | #endif - DANE_F_IGNORE_LOCAL_RESOLVER))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed to initialize DANE: %s\n"), - dane_strerror(rc)); - gnutls_x509_crt_deinit (x509_cert); - return GNUNET_SYSERR; - } - s5r->dane_data[s5r->num_danes] = NULL; - s5r->dane_data_len[s5r->num_danes] = 0; - if (0 != (rc = dane_raw_tlsa (dane_state, - &dane_query, - s5r->dane_data, - s5r->dane_data_len, - GNUNET_YES, - GNUNET_NO))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed to parse DANE record: %s\n"), - dane_strerror(rc)); - dane_state_deinit (dane_state); - gnutls_x509_crt_deinit (x509_cert); - return GNUNET_SYSERR; - } - if (0 != (rc = dane_verify_crt_raw (dane_state, - chainp, - cert_list_size, - gnutls_certificate_type_get (tlsinfo->internals), - dane_query, - 0, 0, - &verify))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed to verify TLS connection using DANE: %s\n"), - dane_strerror(rc)); - dane_query_deinit (dane_query); - dane_state_deinit (dane_state); - gnutls_x509_crt_deinit (x509_cert); - return GNUNET_SYSERR; - } - if (0 != verify) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed DANE verification failed with GnuTLS verify status code: %u\n"), - verify); - dane_query_deinit (dane_query); - dane_state_deinit (dane_state); - gnutls_x509_crt_deinit (x509_cert); - return GNUNET_SYSERR; + DANE_F_IGNORE_LOCAL_RESOLVER))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to initialize DANE: %s\n"), + dane_strerror(rc)); + gnutls_x509_crt_deinit(x509_cert); + return GNUNET_SYSERR; + } + s5r->dane_data[s5r->num_danes] = NULL; + s5r->dane_data_len[s5r->num_danes] = 0; + if (0 != (rc = dane_raw_tlsa(dane_state, + &dane_query, + s5r->dane_data, + s5r->dane_data_len, + GNUNET_YES, + GNUNET_NO))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to parse DANE record: %s\n"), + dane_strerror(rc)); + dane_state_deinit(dane_state); + gnutls_x509_crt_deinit(x509_cert); + return GNUNET_SYSERR; + } + if (0 != (rc = dane_verify_crt_raw(dane_state, + chainp, + cert_list_size, + gnutls_certificate_type_get(tlsinfo->internals), + dane_query, + 0, 0, + &verify))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to verify TLS connection using DANE: %s\n"), + dane_strerror(rc)); + dane_query_deinit(dane_query); + dane_state_deinit(dane_state); + gnutls_x509_crt_deinit(x509_cert); + return GNUNET_SYSERR; + } + if (0 != verify) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed DANE verification failed with GnuTLS verify status code: %u\n"), + verify); + dane_query_deinit(dane_query); + dane_state_deinit(dane_state); + gnutls_x509_crt_deinit(x509_cert); + return GNUNET_SYSERR; + } + dane_query_deinit(dane_query); + dane_state_deinit(dane_state); + /* success! */ } - dane_query_deinit (dane_query); - dane_state_deinit (dane_state); - /* success! */ - } else #endif { @@ -1088,27 +1070,27 @@ check_ssl_certificate (struct Socks5Request *s5r) if (NULL != s5r->leho) name = s5r->leho; if (NULL != name) - { - if (0 == (rc = gnutls_x509_crt_check_hostname (x509_cert, - name))) { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("TLS certificate subject name (%s) does not match `%s': %d\n"), - certdn, - name, - rc); - gnutls_x509_crt_deinit (x509_cert); - return GNUNET_SYSERR; + if (0 == (rc = gnutls_x509_crt_check_hostname(x509_cert, + name))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("TLS certificate subject name (%s) does not match `%s': %d\n"), + certdn, + name, + rc); + gnutls_x509_crt_deinit(x509_cert); + return GNUNET_SYSERR; + } } - } else - { - /* we did not even have the domain name!? */ - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + /* we did not even have the domain name!? */ + GNUNET_break(0); + return GNUNET_SYSERR; + } } - gnutls_x509_crt_deinit (x509_cert); + gnutls_x509_crt_deinit(x509_cert); return GNUNET_OK; } @@ -1126,10 +1108,10 @@ check_ssl_certificate (struct Socks5Request *s5r) * @return size of processed bytes */ static size_t -curl_check_hdr (void *buffer, - size_t size, - size_t nmemb, - void *cls) +curl_check_hdr(void *buffer, + size_t size, + size_t nmemb, + void *cls) { struct Socks5Request *s5r = cls; struct HttpResponseHeader *header; @@ -1145,178 +1127,178 @@ curl_check_hdr (void *buffer, int domain_matched; char *tok; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Receiving HTTP response header from CURL\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Receiving HTTP response header from CURL\n"); /* first, check TLS certificate */ - if ( (GNUNET_YES != s5r->ssl_checked) && - (GNUNET_YES == s5r->is_tls)) - //(HTTPS_PORT == s5r->port)) - { - if (GNUNET_OK != check_ssl_certificate (s5r)) - return 0; - } - ndup = GNUNET_strndup (buffer, - bytes); - hdr_type = strtok (ndup, - ":"); + if ((GNUNET_YES != s5r->ssl_checked) && + (GNUNET_YES == s5r->is_tls)) + //(HTTPS_PORT == s5r->port)) + { + if (GNUNET_OK != check_ssl_certificate(s5r)) + return 0; + } + ndup = GNUNET_strndup(buffer, + bytes); + hdr_type = strtok(ndup, + ":"); if (NULL == hdr_type) - { - GNUNET_free (ndup); - return bytes; - } - hdr_val = strtok (NULL, - ""); + { + GNUNET_free(ndup); + return bytes; + } + hdr_val = strtok(NULL, + ""); if (NULL == hdr_val) - { - GNUNET_free (ndup); - return bytes; - } + { + GNUNET_free(ndup); + return bytes; + } if (' ' == *hdr_val) hdr_val++; /* custom logic for certain header types */ new_cookie_hdr = NULL; - if ( (NULL != s5r->leho) && - (0 == strcasecmp (hdr_type, - MHD_HTTP_HEADER_SET_COOKIE)) ) + if ((NULL != s5r->leho) && + (0 == strcasecmp(hdr_type, + MHD_HTTP_HEADER_SET_COOKIE))) - { - new_cookie_hdr = GNUNET_malloc (strlen (hdr_val) + - strlen (s5r->domain) + 1); - offset = 0; - domain_matched = GNUNET_NO; /* make sure we match domain at most once */ - for (tok = strtok (hdr_val, ";"); NULL != tok; tok = strtok (NULL, ";")) - { - if ( (0 == strncasecmp (tok, - " domain", - strlen (" domain"))) && - (GNUNET_NO == domain_matched) ) - { - domain_matched = GNUNET_YES; - cookie_domain = tok + strlen (" domain") + 1; - if (strlen (cookie_domain) < strlen (s5r->leho)) + { + new_cookie_hdr = GNUNET_malloc(strlen(hdr_val) + + strlen(s5r->domain) + 1); + offset = 0; + domain_matched = GNUNET_NO; /* make sure we match domain at most once */ + for (tok = strtok(hdr_val, ";"); NULL != tok; tok = strtok(NULL, ";")) { - delta_cdomain = strlen (s5r->leho) - strlen (cookie_domain); - if (0 == strcasecmp (cookie_domain, - s5r->leho + delta_cdomain)) - { - offset += sprintf (new_cookie_hdr + offset, - " domain=%s;", - s5r->domain); - continue; - } + if ((0 == strncasecmp(tok, + " domain", + strlen(" domain"))) && + (GNUNET_NO == domain_matched)) + { + domain_matched = GNUNET_YES; + cookie_domain = tok + strlen(" domain") + 1; + if (strlen(cookie_domain) < strlen(s5r->leho)) + { + delta_cdomain = strlen(s5r->leho) - strlen(cookie_domain); + if (0 == strcasecmp(cookie_domain, + s5r->leho + delta_cdomain)) + { + offset += sprintf(new_cookie_hdr + offset, + " domain=%s;", + s5r->domain); + continue; + } + } + else if (0 == strcmp(cookie_domain, + s5r->leho)) + { + offset += sprintf(new_cookie_hdr + offset, + " domain=%s;", + s5r->domain); + continue; + } + else if (('.' == cookie_domain[0]) && + (0 == strcmp(&cookie_domain[1], + s5r->leho))) + { + offset += sprintf(new_cookie_hdr + offset, + " domain=.%s;", + s5r->domain); + continue; + } + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Cookie domain `%s' supplied by server is invalid\n"), + tok); + } + GNUNET_memcpy(new_cookie_hdr + offset, + tok, + strlen(tok)); + offset += strlen(tok); + new_cookie_hdr[offset++] = ';'; } - else if (0 == strcmp (cookie_domain, - s5r->leho)) + hdr_val = new_cookie_hdr; + } + + new_location = NULL; + if (0 == strcasecmp(MHD_HTTP_HEADER_TRANSFER_ENCODING, + hdr_type)) + { + /* Ignore transfer encoding, set automatically by MHD if required */ + goto cleanup; + } + if ((0 == strcasecmp(MHD_HTTP_HEADER_LOCATION, + hdr_type))) + { + char *leho_host; + + GNUNET_asprintf(&leho_host, + (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port) + ? "http://%s" + : "https://%s", + s5r->leho); + if (0 == strncmp(leho_host, + hdr_val, + strlen(leho_host))) { - offset += sprintf (new_cookie_hdr + offset, - " domain=%s;", - s5r->domain); - continue; + GNUNET_asprintf(&new_location, + "%s%s%s", + (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port) + ? "http://" + : "https://", + s5r->domain, + hdr_val + strlen(leho_host)); + hdr_val = new_location; } - else if ( ('.' == cookie_domain[0]) && - (0 == strcmp (&cookie_domain[1], - s5r->leho)) ) + GNUNET_free(leho_host); + } + if (0 == strcasecmp(MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, + hdr_type)) + { + char *leho_host; + + GNUNET_asprintf(&leho_host, + (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port) + ? "http://%s" + : "https://%s", + s5r->leho); + if (0 == strncmp(leho_host, + hdr_val, + strlen(leho_host))) { - offset += sprintf (new_cookie_hdr + offset, - " domain=.%s;", - s5r->domain); - continue; + GNUNET_asprintf(&new_location, + "%s%s", + (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port) + ? "http://" + : "https://", + s5r->domain); + hdr_val = new_location; } - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Cookie domain `%s' supplied by server is invalid\n"), - tok); - } - GNUNET_memcpy (new_cookie_hdr + offset, - tok, - strlen (tok)); - offset += strlen (tok); - new_cookie_hdr[offset++] = ';'; + GNUNET_free(leho_host); } - hdr_val = new_cookie_hdr; - } - - new_location = NULL; - if (0 == strcasecmp (MHD_HTTP_HEADER_TRANSFER_ENCODING, - hdr_type)) - { - /* Ignore transfer encoding, set automatically by MHD if required */ - goto cleanup; - } - if ((0 == strcasecmp (MHD_HTTP_HEADER_LOCATION, - hdr_type))) - { - char *leho_host; - - GNUNET_asprintf (&leho_host, - (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port) - ? "http://%s" - : "https://%s", - s5r->leho); - if (0 == strncmp (leho_host, - hdr_val, - strlen (leho_host))) - { - GNUNET_asprintf (&new_location, - "%s%s%s", - (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port) - ? "http://" - : "https://", - s5r->domain, - hdr_val + strlen (leho_host)); - hdr_val = new_location; - } - GNUNET_free (leho_host); - } - if (0 == strcasecmp (MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, - hdr_type)) - { - char *leho_host; - - GNUNET_asprintf (&leho_host, - (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port) - ? "http://%s" - : "https://%s", - s5r->leho); - if (0 == strncmp (leho_host, - hdr_val, - strlen (leho_host))) - { - GNUNET_asprintf (&new_location, - "%s%s", - (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port) - ? "http://" - : "https://", - s5r->domain); - hdr_val = new_location; - } - GNUNET_free (leho_host); - } /* MHD does not allow certain characters in values, remove those */ - if (NULL != (tok = strchr (hdr_val, '\n'))) + if (NULL != (tok = strchr(hdr_val, '\n'))) *tok = '\0'; - if (NULL != (tok = strchr (hdr_val, '\r'))) + if (NULL != (tok = strchr(hdr_val, '\r'))) *tok = '\0'; - if (NULL != (tok = strchr (hdr_val, '\t'))) + if (NULL != (tok = strchr(hdr_val, '\t'))) *tok = '\0'; - if (0 != strlen (hdr_val)) /* Rely in MHD to set those */ - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding header %s: %s to MHD response\n", - hdr_type, - hdr_val); - header = GNUNET_new (struct HttpResponseHeader); - header->type = GNUNET_strdup (hdr_type); - header->value = GNUNET_strdup (hdr_val); - GNUNET_CONTAINER_DLL_insert (s5r->header_head, - s5r->header_tail, - header); - } - cleanup: - GNUNET_free (ndup); - GNUNET_free_non_null (new_cookie_hdr); - GNUNET_free_non_null (new_location); + if (0 != strlen(hdr_val)) /* Rely in MHD to set those */ + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding header %s: %s to MHD response\n", + hdr_type, + hdr_val); + header = GNUNET_new(struct HttpResponseHeader); + header->type = GNUNET_strdup(hdr_type); + header->value = GNUNET_strdup(hdr_val); + GNUNET_CONTAINER_DLL_insert(s5r->header_head, + s5r->header_tail, + header); + } +cleanup: + GNUNET_free(ndup); + GNUNET_free_non_null(new_cookie_hdr); + GNUNET_free_non_null(new_location); return bytes; } @@ -1330,73 +1312,73 @@ curl_check_hdr (void *buffer, * already initialized before */ static int -create_mhd_response_from_s5r (struct Socks5Request *s5r) +create_mhd_response_from_s5r(struct Socks5Request *s5r) { long resp_code; double content_length; if (NULL != s5r->response) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Response already set!\n"); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Response already set!\n"); + return GNUNET_SYSERR; + } - GNUNET_break (CURLE_OK == - curl_easy_getinfo (s5r->curl, - CURLINFO_RESPONSE_CODE, - &resp_code)); - GNUNET_break (CURLE_OK == - curl_easy_getinfo (s5r->curl, - CURLINFO_CONTENT_LENGTH_DOWNLOAD, - &content_length)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Creating MHD response with code %d and size %d for %s%s\n", - (int) resp_code, - (int) content_length, - s5r->domain, - s5r->url); + GNUNET_break(CURLE_OK == + curl_easy_getinfo(s5r->curl, + CURLINFO_RESPONSE_CODE, + &resp_code)); + GNUNET_break(CURLE_OK == + curl_easy_getinfo(s5r->curl, + CURLINFO_CONTENT_LENGTH_DOWNLOAD, + &content_length)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Creating MHD response with code %d and size %d for %s%s\n", + (int)resp_code, + (int)content_length, + s5r->domain, + s5r->url); s5r->response_code = resp_code; - s5r->response = MHD_create_response_from_callback ((-1 == content_length) - ? MHD_SIZE_UNKNOWN - : content_length, - IO_BUFFERSIZE, - &mhd_content_cb, - s5r, - NULL); + s5r->response = MHD_create_response_from_callback((-1 == content_length) + ? MHD_SIZE_UNKNOWN + : content_length, + IO_BUFFERSIZE, + &mhd_content_cb, + s5r, + NULL); for (struct HttpResponseHeader *header = s5r->header_head; NULL != header; header = header->next) - { - if (0 == strcasecmp (header->type, - MHD_HTTP_HEADER_CONTENT_LENGTH)) - continue; /* MHD won't let us mess with those, for good reason */ - if ( (0 == strcasecmp (header->type, + { + if (0 == strcasecmp(header->type, + MHD_HTTP_HEADER_CONTENT_LENGTH)) + continue; /* MHD won't let us mess with those, for good reason */ + if ((0 == strcasecmp(header->type, MHD_HTTP_HEADER_TRANSFER_ENCODING)) && - ( (0 == strcasecmp (header->value, - "identity")) || - (0 == strcasecmp (header->value, - "chunked")) ) ) - continue; /* MHD won't let us mess with those, for good reason */ - if (MHD_YES != - MHD_add_response_header (s5r->response, - header->type, - header->value)) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Failed to add header `%s:%s'\n", - header->type, - header->value); + ((0 == strcasecmp(header->value, + "identity")) || + (0 == strcasecmp(header->value, + "chunked")))) + continue; /* MHD won't let us mess with those, for good reason */ + if (MHD_YES != + MHD_add_response_header(s5r->response, + header->type, + header->value)) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Failed to add header `%s:%s'\n", + header->type, + header->value); + } } - } /* force connection to be closed after each request, as we do not support HTTP pipelining (yet, FIXME!) */ /*GNUNET_break (MHD_YES == - MHD_add_response_header (s5r->response, - MHD_HTTP_HEADER_CONNECTION, - "close"));*/ - MHD_resume_connection (s5r->con); + MHD_add_response_header (s5r->response, + MHD_HTTP_HEADER_CONNECTION, + "close"));*/ + MHD_resume_connection(s5r->con); s5r->suspended = GNUNET_NO; return GNUNET_OK; } @@ -1413,70 +1395,70 @@ create_mhd_response_from_s5r (struct Socks5Request *s5r) * @return number of bytes handled */ static size_t -curl_download_cb (void *ptr, - size_t size, - size_t nmemb, - void* ctx) +curl_download_cb(void *ptr, + size_t size, + size_t nmemb, + void* ctx) { struct Socks5Request *s5r = ctx; size_t total = size * nmemb; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Receiving %ux%u bytes for `%s%s' from cURL to download\n", - (unsigned int) size, - (unsigned int) nmemb, - s5r->domain, - s5r->url); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Receiving %ux%u bytes for `%s%s' from cURL to download\n", + (unsigned int)size, + (unsigned int)nmemb, + s5r->domain, + s5r->url); if (NULL == s5r->response) - GNUNET_assert (GNUNET_OK == - create_mhd_response_from_s5r (s5r)); - if ( (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) && - (0 == s5r->io_len)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Previous upload finished... starting DOWNLOAD.\n"); - s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED; - } - if ( (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) || - (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) ) - { - /* we're still not done with the upload, do not yet - start the download, the IO buffer is still full - with upload data. */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Pausing CURL download `%s%s', waiting for UPLOAD to finish\n", - s5r->domain, - s5r->url); - s5r->curl_paused = GNUNET_YES; - return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */ - } - if (sizeof (s5r->io_buf) - s5r->io_len < total) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Pausing CURL `%s%s' download, not enough space %llu %llu %llu\n", - s5r->domain, - s5r->url, - (unsigned long long) sizeof (s5r->io_buf), - (unsigned long long) s5r->io_len, - (unsigned long long) total); - s5r->curl_paused = GNUNET_YES; - return CURL_WRITEFUNC_PAUSE; /* not enough space */ - } - GNUNET_memcpy (&s5r->io_buf[s5r->io_len], - ptr, - total); + GNUNET_assert(GNUNET_OK == + create_mhd_response_from_s5r(s5r)); + if ((SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) && + (0 == s5r->io_len)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Previous upload finished... starting DOWNLOAD.\n"); + s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED; + } + if ((SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) || + (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state)) + { + /* we're still not done with the upload, do not yet + start the download, the IO buffer is still full + with upload data. */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Pausing CURL download `%s%s', waiting for UPLOAD to finish\n", + s5r->domain, + s5r->url); + s5r->curl_paused = GNUNET_YES; + return CURL_WRITEFUNC_PAUSE; /* not yet ready for data download */ + } + if (sizeof(s5r->io_buf) - s5r->io_len < total) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Pausing CURL `%s%s' download, not enough space %llu %llu %llu\n", + s5r->domain, + s5r->url, + (unsigned long long)sizeof(s5r->io_buf), + (unsigned long long)s5r->io_len, + (unsigned long long)total); + s5r->curl_paused = GNUNET_YES; + return CURL_WRITEFUNC_PAUSE; /* not enough space */ + } + GNUNET_memcpy(&s5r->io_buf[s5r->io_len], + ptr, + total); s5r->io_len += total; if (GNUNET_YES == s5r->suspended) - { - MHD_resume_connection (s5r->con); - s5r->suspended = GNUNET_NO; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received %llu bytes of payload via cURL from %s\n", - (unsigned long long) total, - s5r->domain); + { + MHD_resume_connection(s5r->con); + s5r->suspended = GNUNET_NO; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received %llu bytes of payload via cURL from %s\n", + (unsigned long long)total, + s5r->domain); if (s5r->io_len == total) - run_mhd_now (s5r->hd); + run_mhd_now(s5r->hd); return total; } @@ -1492,64 +1474,64 @@ curl_download_cb (void *ptr, * @return number of bytes copied to @a buf */ static size_t -curl_upload_cb (void *buf, - size_t size, - size_t nmemb, - void *cls) +curl_upload_cb(void *buf, + size_t size, + size_t nmemb, + void *cls) { struct Socks5Request *s5r = cls; size_t len = size * nmemb; size_t to_copy; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Receiving %ux%u bytes for `%s%s' from cURL to upload\n", - (unsigned int) size, - (unsigned int) nmemb, - s5r->domain, - s5r->url); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Receiving %ux%u bytes for `%s%s' from cURL to upload\n", + (unsigned int)size, + (unsigned int)nmemb, + s5r->domain, + s5r->url); - if ( (0 == s5r->io_len) && - (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Pausing CURL UPLOAD %s%s, need more data\n", - s5r->domain, - s5r->url); - return CURL_READFUNC_PAUSE; - } - if ( (0 == s5r->io_len) && - (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state) ) - { - s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED; - if (GNUNET_YES == s5r->curl_paused) + if ((0 == s5r->io_len) && + (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state)) { - s5r->curl_paused = GNUNET_NO; - curl_easy_pause (s5r->curl, - CURLPAUSE_CONT); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Completed CURL UPLOAD %s%s\n", - s5r->domain, - s5r->url); - return 0; /* upload finished, can now download */ - } - if ( (SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) && - (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state) ) - { - GNUNET_break (0); - return CURL_READFUNC_ABORT; - } - to_copy = GNUNET_MIN (s5r->io_len, - len); - GNUNET_memcpy (buf, - s5r->io_buf, - to_copy); - memmove (s5r->io_buf, - &s5r->io_buf[to_copy], - s5r->io_len - to_copy); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Pausing CURL UPLOAD %s%s, need more data\n", + s5r->domain, + s5r->url); + return CURL_READFUNC_PAUSE; + } + if ((0 == s5r->io_len) && + (SOCKS5_SOCKET_UPLOAD_DONE == s5r->state)) + { + s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED; + if (GNUNET_YES == s5r->curl_paused) + { + s5r->curl_paused = GNUNET_NO; + curl_easy_pause(s5r->curl, + CURLPAUSE_CONT); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Completed CURL UPLOAD %s%s\n", + s5r->domain, + s5r->url); + return 0; /* upload finished, can now download */ + } + if ((SOCKS5_SOCKET_UPLOAD_STARTED != s5r->state) && + (SOCKS5_SOCKET_UPLOAD_DONE != s5r->state)) + { + GNUNET_break(0); + return CURL_READFUNC_ABORT; + } + to_copy = GNUNET_MIN(s5r->io_len, + len); + GNUNET_memcpy(buf, + s5r->io_buf, + to_copy); + memmove(s5r->io_buf, + &s5r->io_buf[to_copy], + s5r->io_len - to_copy); s5r->io_len -= to_copy; - if (s5r->io_len + to_copy == sizeof (s5r->io_buf)) - run_mhd_now (s5r->hd); /* got more space for upload now */ + if (s5r->io_len + to_copy == sizeof(s5r->io_buf)) + run_mhd_now(s5r->hd); /* got more space for upload now */ return to_copy; } @@ -1564,14 +1546,14 @@ curl_upload_cb (void *buf, * @param cls closure */ static void -curl_task_download (void *cls); +curl_task_download(void *cls); /** * Ask cURL for the select() sets and schedule cURL operations. */ static void -curl_download_prepare () +curl_download_prepare() { CURLMcode mret; fd_set rs; @@ -1583,63 +1565,63 @@ curl_download_prepare () long to; struct GNUNET_TIME_Relative rtime; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Scheduling CURL interaction\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Scheduling CURL interaction\n"); if (NULL != curl_download_task) - { - GNUNET_SCHEDULER_cancel (curl_download_task); - curl_download_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(curl_download_task); + curl_download_task = NULL; + } max = -1; - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); - if (CURLM_OK != (mret = curl_multi_fdset (curl_multi, - &rs, - &ws, - &es, - &max))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "%s failed at %s:%d: `%s'\n", - "curl_multi_fdset", __FILE__, __LINE__, - curl_multi_strerror (mret)); - return; - } + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); + if (CURLM_OK != (mret = curl_multi_fdset(curl_multi, + &rs, + &ws, + &es, + &max))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "%s failed at %s:%d: `%s'\n", + "curl_multi_fdset", __FILE__, __LINE__, + curl_multi_strerror(mret)); + return; + } to = -1; - GNUNET_break (CURLM_OK == - curl_multi_timeout (curl_multi, - &to)); + GNUNET_break(CURLM_OK == + curl_multi_timeout(curl_multi, + &to)); if (-1 == to) rtime = GNUNET_TIME_UNIT_FOREVER_REL; else - rtime = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, - to); + rtime = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, + to); if (-1 != max) - { - grs = GNUNET_NETWORK_fdset_create (); - gws = GNUNET_NETWORK_fdset_create (); - GNUNET_NETWORK_fdset_copy_native (grs, - &rs, - max + 1); - GNUNET_NETWORK_fdset_copy_native (gws, - &ws, - max + 1); - curl_download_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, - rtime, - grs, - gws, - &curl_task_download, - curl_multi); - GNUNET_NETWORK_fdset_destroy (gws); - GNUNET_NETWORK_fdset_destroy (grs); - } - else - { - curl_download_task = GNUNET_SCHEDULER_add_delayed (rtime, + { + grs = GNUNET_NETWORK_fdset_create(); + gws = GNUNET_NETWORK_fdset_create(); + GNUNET_NETWORK_fdset_copy_native(grs, + &rs, + max + 1); + GNUNET_NETWORK_fdset_copy_native(gws, + &ws, + max + 1); + curl_download_task = GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT, + rtime, + grs, + gws, &curl_task_download, curl_multi); - } + GNUNET_NETWORK_fdset_destroy(gws); + GNUNET_NETWORK_fdset_destroy(grs); + } + else + { + curl_download_task = GNUNET_SCHEDULER_add_delayed(rtime, + &curl_task_download, + curl_multi); + } } @@ -1649,7 +1631,7 @@ curl_download_prepare () * @param cls closure, NULL */ static void -curl_task_download (void *cls) +curl_task_download(void *cls) { int running; int msgnum; @@ -1658,103 +1640,109 @@ curl_task_download (void *cls) struct Socks5Request *s5r; curl_download_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Running CURL interaction\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Running CURL interaction\n"); do - { - running = 0; - mret = curl_multi_perform (curl_multi, - &running); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Checking CURL multi status: %d\n", - mret); - while (NULL != (msg = curl_multi_info_read (curl_multi, - &msgnum))) - { - GNUNET_break (CURLE_OK == - curl_easy_getinfo (msg->easy_handle, - CURLINFO_PRIVATE, - (char **) &s5r )); - if (NULL == s5r) - { - GNUNET_break (0); - continue; - } - switch (msg->msg) - { - case CURLMSG_NONE: - /* documentation says this is not used */ - GNUNET_break (0); - break; - case CURLMSG_DONE: - switch (msg->data.result) - { - case CURLE_OK: - case CURLE_GOT_NOTHING: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "CURL download %s%s completed.\n", - s5r->domain, - s5r->url); + { + running = 0; + mret = curl_multi_perform(curl_multi, + &running); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Checking CURL multi status: %d\n", + mret); + while (NULL != (msg = curl_multi_info_read(curl_multi, + &msgnum))) + { + GNUNET_break(CURLE_OK == + curl_easy_getinfo(msg->easy_handle, + CURLINFO_PRIVATE, + (char **)&s5r)); + if (NULL == s5r) + { + GNUNET_break(0); + continue; + } + switch (msg->msg) + { + case CURLMSG_NONE: + /* documentation says this is not used */ + GNUNET_break(0); + break; + + case CURLMSG_DONE: + switch (msg->data.result) + { + case CURLE_OK: + case CURLE_GOT_NOTHING: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "CURL download %s%s completed.\n", + s5r->domain, + s5r->url); + if (NULL == s5r->response) + { + GNUNET_assert(GNUNET_OK == + create_mhd_response_from_s5r(s5r)); + } + s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE; + if (GNUNET_YES == s5r->suspended) + { + MHD_resume_connection(s5r->con); + s5r->suspended = GNUNET_NO; + } + run_mhd_now(s5r->hd); + break; + + default: + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Download curl %s%s failed: %s\n", + s5r->domain, + s5r->url, + curl_easy_strerror(msg->data.result)); + /* FIXME: indicate error somehow? close MHD connection badly as well? */ + s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE; + if (GNUNET_YES == s5r->suspended) + { + MHD_resume_connection(s5r->con); + s5r->suspended = GNUNET_NO; + } + run_mhd_now(s5r->hd); + break; + } if (NULL == s5r->response) - { - GNUNET_assert (GNUNET_OK == - create_mhd_response_from_s5r (s5r)); - } - s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE; - if (GNUNET_YES == s5r->suspended) - { - MHD_resume_connection (s5r->con); - s5r->suspended = GNUNET_NO; - } - run_mhd_now (s5r->hd); + s5r->response = curl_failure_response; + break; + + case CURLMSG_LAST: + /* documentation says this is not used */ + GNUNET_break(0); break; + default: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Download curl %s%s failed: %s\n", - s5r->domain, - s5r->url, - curl_easy_strerror (msg->data.result)); - /* FIXME: indicate error somehow? close MHD connection badly as well? */ - s5r->state = SOCKS5_SOCKET_DOWNLOAD_DONE; - if (GNUNET_YES == s5r->suspended) - { - MHD_resume_connection (s5r->con); - s5r->suspended = GNUNET_NO; - } - run_mhd_now (s5r->hd); + /* unexpected status code */ + GNUNET_break(0); break; - } - if (NULL == s5r->response) - s5r->response = curl_failure_response; - break; - case CURLMSG_LAST: - /* documentation says this is not used */ - GNUNET_break (0); - break; - default: - /* unexpected status code */ - GNUNET_break (0); - break; - } - }; - } while (mret == CURLM_CALL_MULTI_PERFORM); + } + } + ; + } + while (mret == CURLM_CALL_MULTI_PERFORM); if (CURLM_OK != mret) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "%s failed at %s:%d: `%s'\n", - "curl_multi_perform", __FILE__, __LINE__, - curl_multi_strerror (mret)); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "%s failed at %s:%d: `%s'\n", + "curl_multi_perform", __FILE__, __LINE__, + curl_multi_strerror(mret)); if (0 == running) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Suspending cURL multi loop, no more events pending\n"); - if (NULL != curl_download_task) { - GNUNET_SCHEDULER_cancel (curl_download_task); - curl_download_task = NULL; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Suspending cURL multi loop, no more events pending\n"); + if (NULL != curl_download_task) + { + GNUNET_SCHEDULER_cancel(curl_download_task); + curl_download_task = NULL; + } + return; /* nothing more in progress */ } - return; /* nothing more in progress */ - } - curl_download_prepare (); + curl_download_prepare(); } @@ -1775,28 +1763,28 @@ curl_task_download (void *cls) * @return #MHD_YES to continue to iterate */ static int -con_val_iter (void *cls, - enum MHD_ValueKind kind, - const char *key, - const char *value) +con_val_iter(void *cls, + enum MHD_ValueKind kind, + const char *key, + const char *value) { struct Socks5Request *s5r = cls; char *hdr; - if ( (0 == strcasecmp (MHD_HTTP_HEADER_HOST, - key)) && - (NULL != s5r->leho) ) + if ((0 == strcasecmp(MHD_HTTP_HEADER_HOST, + key)) && + (NULL != s5r->leho)) value = s5r->leho; - GNUNET_asprintf (&hdr, - "%s: %s", - key, - value); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding HEADER `%s' to HTTP request\n", - hdr); - s5r->headers = curl_slist_append (s5r->headers, - hdr); - GNUNET_free (hdr); + GNUNET_asprintf(&hdr, + "%s: %s", + key, + value); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding HEADER `%s' to HTTP request\n", + hdr); + s5r->headers = curl_slist_append(s5r->headers, + hdr); + GNUNET_free(hdr); return MHD_YES; } @@ -1825,14 +1813,14 @@ con_val_iter (void *cls, * error while handling the request */ static int -create_response (void *cls, - struct MHD_Connection *con, - const char *url, - const char *meth, - const char *ver, - const char *upload_data, - size_t *upload_data_size, - void **con_cls) +create_response(void *cls, + struct MHD_Connection *con, + const char *url, + const char *meth, + const char *ver, + const char *upload_data, + size_t *upload_data_size, + void **con_cls) { struct Socks5Request *s5r = *con_cls; char *curlurl; @@ -1845,412 +1833,415 @@ create_response (void *cls, size_t left; if (NULL == s5r) - { - GNUNET_break (0); - return MHD_NO; - } + { + GNUNET_break(0); + return MHD_NO; + } s5r->con = con; /* Fresh connection. */ if (SOCKS5_SOCKET_WITH_MHD == s5r->state) - { - /* first time here, initialize curl handle */ - if (s5r->is_gns) { - sa = (const struct sockaddr *) &s5r->destination_address; - switch (sa->sa_family) - { - case AF_INET: - s4 = (const struct sockaddr_in *) &s5r->destination_address; - if (NULL == inet_ntop (AF_INET, - &s4->sin_addr, - ipstring, - sizeof (ipstring))) + /* first time here, initialize curl handle */ + if (s5r->is_gns) { - GNUNET_break (0); - return MHD_NO; + sa = (const struct sockaddr *)&s5r->destination_address; + switch (sa->sa_family) + { + case AF_INET: + s4 = (const struct sockaddr_in *)&s5r->destination_address; + if (NULL == inet_ntop(AF_INET, + &s4->sin_addr, + ipstring, + sizeof(ipstring))) + { + GNUNET_break(0); + return MHD_NO; + } + GNUNET_snprintf(ipaddr, + sizeof(ipaddr), + "%s", + ipstring); + port = ntohs(s4->sin_port); + break; + + case AF_INET6: + s6 = (const struct sockaddr_in6 *)&s5r->destination_address; + if (NULL == inet_ntop(AF_INET6, + &s6->sin6_addr, + ipstring, + sizeof(ipstring))) + { + GNUNET_break(0); + return MHD_NO; + } + GNUNET_snprintf(ipaddr, + sizeof(ipaddr), + "%s", + ipstring); + port = ntohs(s6->sin6_port); + break; + + default: + GNUNET_break(0); + return MHD_NO; + } } - GNUNET_snprintf (ipaddr, - sizeof (ipaddr), - "%s", - ipstring); - port = ntohs (s4->sin_port); - break; - case AF_INET6: - s6 = (const struct sockaddr_in6 *) &s5r->destination_address; - if (NULL == inet_ntop (AF_INET6, - &s6->sin6_addr, - ipstring, - sizeof (ipstring))) + else { - GNUNET_break (0); - return MHD_NO; + port = s5r->port; } - GNUNET_snprintf (ipaddr, - sizeof (ipaddr), - "%s", - ipstring); - port = ntohs (s6->sin6_port); - break; - default: - GNUNET_break (0); - return MHD_NO; - } - } - else - { - port = s5r->port; - } - if (NULL == s5r->curl) - s5r->curl = curl_easy_init (); - if (NULL == s5r->curl) - return MHD_queue_response (con, - MHD_HTTP_INTERNAL_SERVER_ERROR, - curl_failure_response); - curl_easy_setopt (s5r->curl, - CURLOPT_HEADERFUNCTION, - &curl_check_hdr); - curl_easy_setopt (s5r->curl, - CURLOPT_HEADERDATA, - s5r); - curl_easy_setopt (s5r->curl, - CURLOPT_FOLLOWLOCATION, - 0); - if (s5r->is_gns) - curl_easy_setopt (s5r->curl, - CURLOPT_IPRESOLVE, - CURL_IPRESOLVE_V4); - curl_easy_setopt (s5r->curl, - CURLOPT_CONNECTTIMEOUT, - 600L); - curl_easy_setopt (s5r->curl, - CURLOPT_TIMEOUT, - 600L); - curl_easy_setopt (s5r->curl, - CURLOPT_NOSIGNAL, - 1L); - curl_easy_setopt (s5r->curl, - CURLOPT_HTTP_CONTENT_DECODING, - 0); - curl_easy_setopt (s5r->curl, - CURLOPT_NOSIGNAL, - 1L); - curl_easy_setopt (s5r->curl, - CURLOPT_PRIVATE, - s5r); - curl_easy_setopt (s5r->curl, - CURLOPT_VERBOSE, - 0L); - /** - * Pre-populate cache to resolve Hostname. - * This is necessary as the DNS name in the CURLOPT_URL is used - * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication - */ - if (NULL != s5r->leho) - { - char *curl_hosts; - - GNUNET_asprintf (&curl_hosts, - "%s:%d:%s", - s5r->leho, - port, - ipaddr); - s5r->hosts = curl_slist_append (NULL, - curl_hosts); - curl_easy_setopt (s5r->curl, - CURLOPT_RESOLVE, - s5r->hosts); - GNUNET_free (curl_hosts); - } - if (s5r->is_gns) - { - GNUNET_asprintf (&curlurl, - (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port) - ? "http://%s:%d%s" - : "https://%s:%d%s", - (NULL != s5r->leho) - ? s5r->leho - : ipaddr, - port, - s5r->url); - } - else - { - GNUNET_asprintf (&curlurl, - (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port) - ? "http://%s:%d%s" - : "https://%s:%d%s", - s5r->domain, - port, - s5r->url); - } - curl_easy_setopt (s5r->curl, - CURLOPT_URL, - curlurl); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Launching %s CURL interaction, fetching `%s'\n", - (s5r->is_gns) ? "GNS" : "DNS", - curlurl); - GNUNET_free (curlurl); - if (0 == strcasecmp (meth, - MHD_HTTP_METHOD_PUT)) - { - s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED; - curl_easy_setopt (s5r->curl, - CURLOPT_UPLOAD, - 1L); - curl_easy_setopt (s5r->curl, - CURLOPT_WRITEFUNCTION, - &curl_download_cb); - curl_easy_setopt (s5r->curl, - CURLOPT_WRITEDATA, - s5r); - GNUNET_assert (CURLE_OK == - curl_easy_setopt (s5r->curl, - CURLOPT_READFUNCTION, - &curl_upload_cb)); - curl_easy_setopt (s5r->curl, - CURLOPT_READDATA, - s5r); - { - const char *us; - long upload_size = 0; - - us = MHD_lookup_connection_value (con, - MHD_HEADER_KIND, - MHD_HTTP_HEADER_CONTENT_LENGTH); - if ( (1 == sscanf (us, - "%ld", - &upload_size)) && - (upload_size >= 0) ) + if (NULL == s5r->curl) + s5r->curl = curl_easy_init(); + if (NULL == s5r->curl) + return MHD_queue_response(con, + MHD_HTTP_INTERNAL_SERVER_ERROR, + curl_failure_response); + curl_easy_setopt(s5r->curl, + CURLOPT_HEADERFUNCTION, + &curl_check_hdr); + curl_easy_setopt(s5r->curl, + CURLOPT_HEADERDATA, + s5r); + curl_easy_setopt(s5r->curl, + CURLOPT_FOLLOWLOCATION, + 0); + if (s5r->is_gns) + curl_easy_setopt(s5r->curl, + CURLOPT_IPRESOLVE, + CURL_IPRESOLVE_V4); + curl_easy_setopt(s5r->curl, + CURLOPT_CONNECTTIMEOUT, + 600L); + curl_easy_setopt(s5r->curl, + CURLOPT_TIMEOUT, + 600L); + curl_easy_setopt(s5r->curl, + CURLOPT_NOSIGNAL, + 1L); + curl_easy_setopt(s5r->curl, + CURLOPT_HTTP_CONTENT_DECODING, + 0); + curl_easy_setopt(s5r->curl, + CURLOPT_NOSIGNAL, + 1L); + curl_easy_setopt(s5r->curl, + CURLOPT_PRIVATE, + s5r); + curl_easy_setopt(s5r->curl, + CURLOPT_VERBOSE, + 0L); + /** + * Pre-populate cache to resolve Hostname. + * This is necessary as the DNS name in the CURLOPT_URL is used + * for SNI http://de.wikipedia.org/wiki/Server_Name_Indication + */ + if (NULL != s5r->leho) { - curl_easy_setopt (s5r->curl, - CURLOPT_INFILESIZE, - upload_size); + char *curl_hosts; + + GNUNET_asprintf(&curl_hosts, + "%s:%d:%s", + s5r->leho, + port, + ipaddr); + s5r->hosts = curl_slist_append(NULL, + curl_hosts); + curl_easy_setopt(s5r->curl, + CURLOPT_RESOLVE, + s5r->hosts); + GNUNET_free(curl_hosts); } - } - } - else if (0 == strcasecmp (meth, MHD_HTTP_METHOD_POST)) - { - s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED; - curl_easy_setopt (s5r->curl, - CURLOPT_POST, - 1L); - curl_easy_setopt (s5r->curl, - CURLOPT_WRITEFUNCTION, - &curl_download_cb); - curl_easy_setopt (s5r->curl, - CURLOPT_WRITEDATA, - s5r); - curl_easy_setopt (s5r->curl, - CURLOPT_READFUNCTION, - &curl_upload_cb); - curl_easy_setopt (s5r->curl, - CURLOPT_READDATA, - s5r); - { - const char *us; - long upload_size; - - upload_size = 0; - us = MHD_lookup_connection_value (con, - MHD_HEADER_KIND, - MHD_HTTP_HEADER_CONTENT_LENGTH); - if ( (NULL != us) && - (1 == sscanf (us, - "%ld", - &upload_size)) && - (upload_size >= 0) ) + if (s5r->is_gns) { - curl_easy_setopt (s5r->curl, - CURLOPT_INFILESIZE, - upload_size); - } else { - curl_easy_setopt (s5r->curl, - CURLOPT_INFILESIZE, - upload_size); + GNUNET_asprintf(&curlurl, + (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port) + ? "http://%s:%d%s" + : "https://%s:%d%s", + (NULL != s5r->leho) + ? s5r->leho + : ipaddr, + port, + s5r->url); + } + else + { + GNUNET_asprintf(&curlurl, + (GNUNET_YES != s5r->is_tls) //(HTTPS_PORT != s5r->port) + ? "http://%s:%d%s" + : "https://%s:%d%s", + s5r->domain, + port, + s5r->url); + } + curl_easy_setopt(s5r->curl, + CURLOPT_URL, + curlurl); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Launching %s CURL interaction, fetching `%s'\n", + (s5r->is_gns) ? "GNS" : "DNS", + curlurl); + GNUNET_free(curlurl); + if (0 == strcasecmp(meth, + MHD_HTTP_METHOD_PUT)) + { + s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED; + curl_easy_setopt(s5r->curl, + CURLOPT_UPLOAD, + 1L); + curl_easy_setopt(s5r->curl, + CURLOPT_WRITEFUNCTION, + &curl_download_cb); + curl_easy_setopt(s5r->curl, + CURLOPT_WRITEDATA, + s5r); + GNUNET_assert(CURLE_OK == + curl_easy_setopt(s5r->curl, + CURLOPT_READFUNCTION, + &curl_upload_cb)); + curl_easy_setopt(s5r->curl, + CURLOPT_READDATA, + s5r); + { + const char *us; + long upload_size = 0; + + us = MHD_lookup_connection_value(con, + MHD_HEADER_KIND, + MHD_HTTP_HEADER_CONTENT_LENGTH); + if ((1 == sscanf(us, + "%ld", + &upload_size)) && + (upload_size >= 0)) + { + curl_easy_setopt(s5r->curl, + CURLOPT_INFILESIZE, + upload_size); + } + } + } + else if (0 == strcasecmp(meth, MHD_HTTP_METHOD_POST)) + { + s5r->state = SOCKS5_SOCKET_UPLOAD_STARTED; + curl_easy_setopt(s5r->curl, + CURLOPT_POST, + 1L); + curl_easy_setopt(s5r->curl, + CURLOPT_WRITEFUNCTION, + &curl_download_cb); + curl_easy_setopt(s5r->curl, + CURLOPT_WRITEDATA, + s5r); + curl_easy_setopt(s5r->curl, + CURLOPT_READFUNCTION, + &curl_upload_cb); + curl_easy_setopt(s5r->curl, + CURLOPT_READDATA, + s5r); + { + const char *us; + long upload_size; + + upload_size = 0; + us = MHD_lookup_connection_value(con, + MHD_HEADER_KIND, + MHD_HTTP_HEADER_CONTENT_LENGTH); + if ((NULL != us) && + (1 == sscanf(us, + "%ld", + &upload_size)) && + (upload_size >= 0)) + { + curl_easy_setopt(s5r->curl, + CURLOPT_INFILESIZE, + upload_size); + } + else + { + curl_easy_setopt(s5r->curl, + CURLOPT_INFILESIZE, + upload_size); + } + } + } + else if (0 == strcasecmp(meth, + MHD_HTTP_METHOD_HEAD)) + { + s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED; + curl_easy_setopt(s5r->curl, + CURLOPT_NOBODY, + 1L); + } + else if (0 == strcasecmp(meth, + MHD_HTTP_METHOD_OPTIONS)) + { + s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED; + curl_easy_setopt(s5r->curl, + CURLOPT_CUSTOMREQUEST, + "OPTIONS"); + curl_easy_setopt(s5r->curl, + CURLOPT_WRITEFUNCTION, + &curl_download_cb); + curl_easy_setopt(s5r->curl, + CURLOPT_WRITEDATA, + s5r); + } + else if (0 == strcasecmp(meth, + MHD_HTTP_METHOD_GET)) + { + s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED; + curl_easy_setopt(s5r->curl, + CURLOPT_HTTPGET, + 1L); + curl_easy_setopt(s5r->curl, + CURLOPT_WRITEFUNCTION, + &curl_download_cb); + curl_easy_setopt(s5r->curl, + CURLOPT_WRITEDATA, + s5r); + } + else if (0 == strcasecmp(meth, + MHD_HTTP_METHOD_DELETE)) + { + s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED; + curl_easy_setopt(s5r->curl, + CURLOPT_CUSTOMREQUEST, + "DELETE"); + curl_easy_setopt(s5r->curl, + CURLOPT_WRITEFUNCTION, + &curl_download_cb); + curl_easy_setopt(s5r->curl, + CURLOPT_WRITEDATA, + s5r); + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Unsupported HTTP method `%s'\n"), + meth); + curl_easy_cleanup(s5r->curl); + s5r->curl = NULL; + return MHD_NO; } - } - } - else if (0 == strcasecmp (meth, - MHD_HTTP_METHOD_HEAD)) - { - s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED; - curl_easy_setopt (s5r->curl, - CURLOPT_NOBODY, - 1L); - } - else if (0 == strcasecmp (meth, - MHD_HTTP_METHOD_OPTIONS)) - { - s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED; - curl_easy_setopt (s5r->curl, - CURLOPT_CUSTOMREQUEST, - "OPTIONS"); - curl_easy_setopt (s5r->curl, - CURLOPT_WRITEFUNCTION, - &curl_download_cb); - curl_easy_setopt (s5r->curl, - CURLOPT_WRITEDATA, - s5r); - - } - else if (0 == strcasecmp (meth, - MHD_HTTP_METHOD_GET)) - { - s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED; - curl_easy_setopt (s5r->curl, - CURLOPT_HTTPGET, - 1L); - curl_easy_setopt (s5r->curl, - CURLOPT_WRITEFUNCTION, - &curl_download_cb); - curl_easy_setopt (s5r->curl, - CURLOPT_WRITEDATA, - s5r); - } - else if (0 == strcasecmp (meth, - MHD_HTTP_METHOD_DELETE)) - { - s5r->state = SOCKS5_SOCKET_DOWNLOAD_STARTED; - curl_easy_setopt (s5r->curl, - CURLOPT_CUSTOMREQUEST, - "DELETE"); - curl_easy_setopt (s5r->curl, - CURLOPT_WRITEFUNCTION, - &curl_download_cb); - curl_easy_setopt (s5r->curl, - CURLOPT_WRITEDATA, - s5r); - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Unsupported HTTP method `%s'\n"), - meth); - curl_easy_cleanup (s5r->curl); - s5r->curl = NULL; - return MHD_NO; - } - if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_0)) - { - curl_easy_setopt (s5r->curl, - CURLOPT_HTTP_VERSION, - CURL_HTTP_VERSION_1_0); - } - else if (0 == strcasecmp (ver, MHD_HTTP_VERSION_1_1)) - { - curl_easy_setopt (s5r->curl, - CURLOPT_HTTP_VERSION, - CURL_HTTP_VERSION_1_1); - } - else - { - curl_easy_setopt (s5r->curl, - CURLOPT_HTTP_VERSION, - CURL_HTTP_VERSION_NONE); - } + if (0 == strcasecmp(ver, MHD_HTTP_VERSION_1_0)) + { + curl_easy_setopt(s5r->curl, + CURLOPT_HTTP_VERSION, + CURL_HTTP_VERSION_1_0); + } + else if (0 == strcasecmp(ver, MHD_HTTP_VERSION_1_1)) + { + curl_easy_setopt(s5r->curl, + CURLOPT_HTTP_VERSION, + CURL_HTTP_VERSION_1_1); + } + else + { + curl_easy_setopt(s5r->curl, + CURLOPT_HTTP_VERSION, + CURL_HTTP_VERSION_NONE); + } - if (GNUNET_YES == s5r->is_tls) //(HTTPS_PORT == s5r->port) - { - curl_easy_setopt (s5r->curl, - CURLOPT_USE_SSL, - CURLUSESSL_ALL); - if (0 < s5r->num_danes) - curl_easy_setopt (s5r->curl, - CURLOPT_SSL_VERIFYPEER, - 0L); + if (GNUNET_YES == s5r->is_tls) //(HTTPS_PORT == s5r->port) + { + curl_easy_setopt(s5r->curl, + CURLOPT_USE_SSL, + CURLUSESSL_ALL); + if (0 < s5r->num_danes) + curl_easy_setopt(s5r->curl, + CURLOPT_SSL_VERIFYPEER, + 0L); + else + curl_easy_setopt(s5r->curl, + CURLOPT_SSL_VERIFYPEER, + 1L); + /* Disable cURL checking the hostname, as we will check ourselves + as only we have the domain name or the LEHO or the DANE record */ + curl_easy_setopt(s5r->curl, + CURLOPT_SSL_VERIFYHOST, + 0L); + } else - curl_easy_setopt (s5r->curl, - CURLOPT_SSL_VERIFYPEER, - 1L); - /* Disable cURL checking the hostname, as we will check ourselves - as only we have the domain name or the LEHO or the DANE record */ - curl_easy_setopt (s5r->curl, - CURLOPT_SSL_VERIFYHOST, - 0L); - } - else - { - curl_easy_setopt (s5r->curl, - CURLOPT_USE_SSL, - CURLUSESSL_NONE); - } + { + curl_easy_setopt(s5r->curl, + CURLOPT_USE_SSL, + CURLUSESSL_NONE); + } - if (CURLM_OK != - curl_multi_add_handle (curl_multi, - s5r->curl)) - { - GNUNET_break (0); - curl_easy_cleanup (s5r->curl); - s5r->curl = NULL; - return MHD_NO; + if (CURLM_OK != + curl_multi_add_handle(curl_multi, + s5r->curl)) + { + GNUNET_break(0); + curl_easy_cleanup(s5r->curl); + s5r->curl = NULL; + return MHD_NO; + } + MHD_get_connection_values(con, + MHD_HEADER_KIND, + (MHD_KeyValueIterator) & con_val_iter, + s5r); + curl_easy_setopt(s5r->curl, + CURLOPT_HTTPHEADER, + s5r->headers); + curl_download_prepare(); + return MHD_YES; } - MHD_get_connection_values (con, - MHD_HEADER_KIND, - (MHD_KeyValueIterator) &con_val_iter, - s5r); - curl_easy_setopt (s5r->curl, - CURLOPT_HTTPHEADER, - s5r->headers); - curl_download_prepare (); - return MHD_YES; - } /* continuing to process request */ if (0 != *upload_data_size) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Processing %u bytes UPLOAD\n", - (unsigned int) *upload_data_size); - - /* FIXME: This must be set or a header with Transfer-Encoding: chunked. Else - * upload callback is not called! - */ - curl_easy_setopt (s5r->curl, - CURLOPT_POSTFIELDSIZE, - *upload_data_size); - - left = GNUNET_MIN (*upload_data_size, - sizeof (s5r->io_buf) - s5r->io_len); - GNUNET_memcpy (&s5r->io_buf[s5r->io_len], - upload_data, - left); - s5r->io_len += left; - *upload_data_size -= left; - GNUNET_assert (NULL != s5r->curl); - if (GNUNET_YES == s5r->curl_paused) { - s5r->curl_paused = GNUNET_NO; - curl_easy_pause (s5r->curl, - CURLPAUSE_CONT); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Processing %u bytes UPLOAD\n", + (unsigned int)*upload_data_size); + + /* FIXME: This must be set or a header with Transfer-Encoding: chunked. Else + * upload callback is not called! + */ + curl_easy_setopt(s5r->curl, + CURLOPT_POSTFIELDSIZE, + *upload_data_size); + + left = GNUNET_MIN(*upload_data_size, + sizeof(s5r->io_buf) - s5r->io_len); + GNUNET_memcpy(&s5r->io_buf[s5r->io_len], + upload_data, + left); + s5r->io_len += left; + *upload_data_size -= left; + GNUNET_assert(NULL != s5r->curl); + if (GNUNET_YES == s5r->curl_paused) + { + s5r->curl_paused = GNUNET_NO; + curl_easy_pause(s5r->curl, + CURLPAUSE_CONT); + } + return MHD_YES; } - return MHD_YES; - } if (SOCKS5_SOCKET_UPLOAD_STARTED == s5r->state) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished processing UPLOAD\n"); - s5r->state = SOCKS5_SOCKET_UPLOAD_DONE; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished processing UPLOAD\n"); + s5r->state = SOCKS5_SOCKET_UPLOAD_DONE; + } if (NULL == s5r->response) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Waiting for HTTP response for %s%s...\n", - s5r->domain, - s5r->url); - MHD_suspend_connection (con); - s5r->suspended = GNUNET_YES; - return MHD_YES; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Queueing response for %s%s with MHD\n", - s5r->domain, - s5r->url); - run_mhd_now (s5r->hd); - return MHD_queue_response (con, - s5r->response_code, - s5r->response); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Waiting for HTTP response for %s%s...\n", + s5r->domain, + s5r->url); + MHD_suspend_connection(con); + s5r->suspended = GNUNET_YES; + return MHD_YES; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Queueing response for %s%s with MHD\n", + s5r->domain, + s5r->url); + run_mhd_now(s5r->hd); + return MHD_queue_response(con, + s5r->response_code, + s5r->response); } @@ -2267,51 +2258,51 @@ create_response (void *cls, * @param toe reason for request termination (ignored) */ static void -mhd_completed_cb (void *cls, - struct MHD_Connection *connection, - void **con_cls, - enum MHD_RequestTerminationCode toe) +mhd_completed_cb(void *cls, + struct MHD_Connection *connection, + void **con_cls, + enum MHD_RequestTerminationCode toe) { struct Socks5Request *s5r = *con_cls; if (NULL == s5r) return; if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe) - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "MHD encountered error handling request: %d\n", - toe); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "MHD encountered error handling request: %d\n", + toe); if (NULL != s5r->curl) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Removing cURL handle (MHD interaction complete)\n"); - curl_multi_remove_handle (curl_multi, - s5r->curl); - curl_slist_free_all (s5r->headers); - s5r->headers = NULL; - curl_easy_reset (s5r->curl); - s5r->rbuf_len = 0; - s5r->wbuf_len = 0; - s5r->io_len = 0; - curl_download_prepare (); - } - if ( (NULL != s5r->response) && - (curl_failure_response != s5r->response) ) - MHD_destroy_response (s5r->response); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Removing cURL handle (MHD interaction complete)\n"); + curl_multi_remove_handle(curl_multi, + s5r->curl); + curl_slist_free_all(s5r->headers); + s5r->headers = NULL; + curl_easy_reset(s5r->curl); + s5r->rbuf_len = 0; + s5r->wbuf_len = 0; + s5r->io_len = 0; + curl_download_prepare(); + } + if ((NULL != s5r->response) && + (curl_failure_response != s5r->response)) + MHD_destroy_response(s5r->response); for (struct HttpResponseHeader *header = s5r->header_head; NULL != header; header = s5r->header_head) - { - GNUNET_CONTAINER_DLL_remove (s5r->header_head, - s5r->header_tail, - header); - GNUNET_free (header->type); - GNUNET_free (header->value); - GNUNET_free (header); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished request for %s\n", - s5r->url); - GNUNET_free (s5r->url); + { + GNUNET_CONTAINER_DLL_remove(s5r->header_head, + s5r->header_tail, + header); + GNUNET_free(header->type); + GNUNET_free(header->value); + GNUNET_free(header); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished request for %s\n", + s5r->url); + GNUNET_free(s5r->url); s5r->state = SOCKS5_SOCKET_WITH_MHD; s5r->url = NULL; s5r->response = NULL; @@ -2329,56 +2320,58 @@ mhd_completed_cb (void *cls, * @param toe connection notification type */ static void -mhd_connection_cb (void *cls, - struct MHD_Connection *connection, - void **con_cls, - enum MHD_ConnectionNotificationCode cnc) +mhd_connection_cb(void *cls, + struct MHD_Connection *connection, + void **con_cls, + enum MHD_ConnectionNotificationCode cnc) { struct Socks5Request *s5r; const union MHD_ConnectionInfo *ci; int sock; switch (cnc) - { + { case MHD_CONNECTION_NOTIFY_STARTED: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection started...\n"); - ci = MHD_get_connection_info (connection, - MHD_CONNECTION_INFO_CONNECTION_FD); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connection started...\n"); + ci = MHD_get_connection_info(connection, + MHD_CONNECTION_INFO_CONNECTION_FD); if (NULL == ci) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } sock = ci->connect_fd; for (s5r = s5r_head; NULL != s5r; s5r = s5r->next) - { - if (GNUNET_NETWORK_get_fd (s5r->sock) == sock) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Context set...\n"); - s5r->ssl_checked = GNUNET_NO; - *con_cls = s5r; - break; + if (GNUNET_NETWORK_get_fd(s5r->sock) == sock) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Context set...\n"); + s5r->ssl_checked = GNUNET_NO; + *con_cls = s5r; + break; + } } - } break; + case MHD_CONNECTION_NOTIFY_CLOSED: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Connection closed... cleaning up\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Connection closed... cleaning up\n"); s5r = *con_cls; if (NULL == s5r) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Connection stale!\n"); - return; - } - cleanup_s5r (s5r); - curl_download_prepare (); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Connection stale!\n"); + return; + } + cleanup_s5r(s5r); + curl_download_prepare(); *con_cls = NULL; break; + default: - GNUNET_break (0); - } + GNUNET_break(0); + } } /** @@ -2395,34 +2388,34 @@ mhd_connection_cb (void *cls, * @return the `struct Socks5Request` that this @a connection is for */ static void * -mhd_log_callback (void *cls, - const char *url, - struct MHD_Connection *connection) +mhd_log_callback(void *cls, + const char *url, + struct MHD_Connection *connection) { struct Socks5Request *s5r; const union MHD_ConnectionInfo *ci; - ci = MHD_get_connection_info (connection, - MHD_CONNECTION_INFO_SOCKET_CONTEXT); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing %s\n", url); + ci = MHD_get_connection_info(connection, + MHD_CONNECTION_INFO_SOCKET_CONTEXT); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Processing %s\n", url); if (NULL == ci) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } s5r = ci->socket_context; if (NULL != s5r->url) - { - GNUNET_break (0); - return NULL; - } - s5r->url = GNUNET_strdup (url); + { + GNUNET_break(0); + return NULL; + } + s5r->url = GNUNET_strdup(url); if (NULL != s5r->timeout_task) - { - GNUNET_SCHEDULER_cancel (s5r->timeout_task); - s5r->timeout_task = NULL; - } - GNUNET_assert (s5r->state == SOCKS5_SOCKET_WITH_MHD); + { + GNUNET_SCHEDULER_cancel(s5r->timeout_task); + s5r->timeout_task = NULL; + } + GNUNET_assert(s5r->state == SOCKS5_SOCKET_WITH_MHD); return s5r; } @@ -2433,22 +2426,22 @@ mhd_log_callback (void *cls, * @param hd daemon to stop */ static void -kill_httpd (struct MhdHttpList *hd) +kill_httpd(struct MhdHttpList *hd) { - GNUNET_CONTAINER_DLL_remove (mhd_httpd_head, - mhd_httpd_tail, - hd); - GNUNET_free_non_null (hd->domain); - MHD_stop_daemon (hd->daemon); + GNUNET_CONTAINER_DLL_remove(mhd_httpd_head, + mhd_httpd_tail, + hd); + GNUNET_free_non_null(hd->domain); + MHD_stop_daemon(hd->daemon); if (NULL != hd->httpd_task) - { - GNUNET_SCHEDULER_cancel (hd->httpd_task); - hd->httpd_task = NULL; - } - GNUNET_free_non_null (hd->proxy_cert); + { + GNUNET_SCHEDULER_cancel(hd->httpd_task); + hd->httpd_task = NULL; + } + GNUNET_free_non_null(hd->proxy_cert); if (hd == httpd) httpd = NULL; - GNUNET_free (hd); + GNUNET_free(hd); } @@ -2458,12 +2451,12 @@ kill_httpd (struct MhdHttpList *hd) * @param cls the `struct MhdHttpList *` */ static void -kill_httpd_task (void *cls) +kill_httpd_task(void *cls) { struct MhdHttpList *hd = cls; hd->httpd_task = NULL; - kill_httpd (hd); + kill_httpd(hd); } @@ -2473,7 +2466,7 @@ kill_httpd_task (void *cls) * @param cls the `struct MhdHttpList *` of the daemon that is being run */ static void -do_httpd (void *cls); +do_httpd(void *cls); /** @@ -2484,7 +2477,7 @@ do_httpd (void *cls); * @param hd the daemon to schedule */ static void -schedule_httpd (struct MhdHttpList *hd) +schedule_httpd(struct MhdHttpList *hd) { fd_set rs; fd_set ws; @@ -2496,63 +2489,63 @@ schedule_httpd (struct MhdHttpList *hd) MHD_UNSIGNED_LONG_LONG timeout; struct GNUNET_TIME_Relative tv; - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); max = -1; if (MHD_YES != - MHD_get_fdset (hd->daemon, - &rs, - &ws, - &es, - &max)) - { - kill_httpd (hd); - return; - } - haveto = MHD_get_timeout (hd->daemon, - &timeout); + MHD_get_fdset(hd->daemon, + &rs, + &ws, + &es, + &max)) + { + kill_httpd(hd); + return; + } + haveto = MHD_get_timeout(hd->daemon, + &timeout); if (MHD_YES == haveto) - tv.rel_value_us = (uint64_t) timeout * 1000LL; + tv.rel_value_us = (uint64_t)timeout * 1000LL; else tv = GNUNET_TIME_UNIT_FOREVER_REL; if (-1 != max) - { - wrs = GNUNET_NETWORK_fdset_create (); - wws = GNUNET_NETWORK_fdset_create (); - GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1); - GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1); - } + { + wrs = GNUNET_NETWORK_fdset_create(); + wws = GNUNET_NETWORK_fdset_create(); + GNUNET_NETWORK_fdset_copy_native(wrs, &rs, max + 1); + GNUNET_NETWORK_fdset_copy_native(wws, &ws, max + 1); + } else - { - wrs = NULL; - wws = NULL; - } + { + wrs = NULL; + wws = NULL; + } if (NULL != hd->httpd_task) - { - GNUNET_SCHEDULER_cancel (hd->httpd_task); - hd->httpd_task = NULL; - } - if ( (MHD_YES != haveto) && - (-1 == max) && - (hd != httpd) ) - { - /* daemon is idle, kill after timeout */ - hd->httpd_task = GNUNET_SCHEDULER_add_delayed (MHD_CACHE_TIMEOUT, - &kill_httpd_task, - hd); - } + { + GNUNET_SCHEDULER_cancel(hd->httpd_task); + hd->httpd_task = NULL; + } + if ((MHD_YES != haveto) && + (-1 == max) && + (hd != httpd)) + { + /* daemon is idle, kill after timeout */ + hd->httpd_task = GNUNET_SCHEDULER_add_delayed(MHD_CACHE_TIMEOUT, + &kill_httpd_task, + hd); + } else - { - hd->httpd_task = - GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, - tv, wrs, wws, - &do_httpd, hd); - } + { + hd->httpd_task = + GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT, + tv, wrs, wws, + &do_httpd, hd); + } if (NULL != wrs) - GNUNET_NETWORK_fdset_destroy (wrs); + GNUNET_NETWORK_fdset_destroy(wrs); if (NULL != wws) - GNUNET_NETWORK_fdset_destroy (wws); + GNUNET_NETWORK_fdset_destroy(wws); } @@ -2562,13 +2555,13 @@ schedule_httpd (struct MhdHttpList *hd) * @param cls the `struct MhdHttpList` of the daemon that is being run */ static void -do_httpd (void *cls) +do_httpd(void *cls) { struct MhdHttpList *hd = cls; hd->httpd_task = NULL; - MHD_run (hd->daemon); - schedule_httpd (hd); + MHD_run(hd->daemon); + schedule_httpd(hd); } @@ -2578,12 +2571,12 @@ do_httpd (void *cls) * @param hd the daemon to run now. */ static void -run_mhd_now (struct MhdHttpList *hd) +run_mhd_now(struct MhdHttpList *hd) { if (NULL != hd->httpd_task) - GNUNET_SCHEDULER_cancel (hd->httpd_task); - hd->httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd, - hd); + GNUNET_SCHEDULER_cancel(hd->httpd_task); + hd->httpd_task = GNUNET_SCHEDULER_add_now(&do_httpd, + hd); } @@ -2595,30 +2588,30 @@ run_mhd_now (struct MhdHttpList *hd) * @return NULL on error */ static void* -load_file (const char* filename, - unsigned int* size) +load_file(const char* filename, + unsigned int* size) { void *buffer; uint64_t fsize; if (GNUNET_OK != - GNUNET_DISK_file_size (filename, - &fsize, - GNUNET_YES, - GNUNET_YES)) + GNUNET_DISK_file_size(filename, + &fsize, + GNUNET_YES, + GNUNET_YES)) return NULL; if (fsize > MAX_PEM_SIZE) return NULL; - *size = (unsigned int) fsize; - buffer = GNUNET_malloc (*size); + *size = (unsigned int)fsize; + buffer = GNUNET_malloc(*size); if (fsize != - GNUNET_DISK_fn_read (filename, - buffer, - (size_t) fsize)) - { - GNUNET_free (buffer); - return NULL; - } + GNUNET_DISK_fn_read(filename, + buffer, + (size_t)fsize)) + { + GNUNET_free(buffer); + return NULL; + } return buffer; } @@ -2631,25 +2624,25 @@ load_file (const char* filename, * @return #GNUNET_OK on success */ static int -load_key_from_file (gnutls_x509_privkey_t key, - const char* keyfile) +load_key_from_file(gnutls_x509_privkey_t key, + const char* keyfile) { gnutls_datum_t key_data; int ret; - key_data.data = load_file (keyfile, - &key_data.size); + key_data.data = load_file(keyfile, + &key_data.size); if (NULL == key_data.data) return GNUNET_SYSERR; - ret = gnutls_x509_privkey_import (key, &key_data, - GNUTLS_X509_FMT_PEM); + ret = gnutls_x509_privkey_import(key, &key_data, + GNUTLS_X509_FMT_PEM); if (GNUTLS_E_SUCCESS != ret) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to import private key from file `%s'\n"), - keyfile); - } - GNUNET_free_non_null (key_data.data); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to import private key from file `%s'\n"), + keyfile); + } + GNUNET_free_non_null(key_data.data); return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK; } @@ -2662,26 +2655,26 @@ load_key_from_file (gnutls_x509_privkey_t key, * @return #GNUNET_OK on success */ static int -load_cert_from_file (gnutls_x509_crt_t crt, - const char* certfile) +load_cert_from_file(gnutls_x509_crt_t crt, + const char* certfile) { gnutls_datum_t cert_data; int ret; - cert_data.data = load_file (certfile, - &cert_data.size); + cert_data.data = load_file(certfile, + &cert_data.size); if (NULL == cert_data.data) return GNUNET_SYSERR; - ret = gnutls_x509_crt_import (crt, - &cert_data, - GNUTLS_X509_FMT_PEM); + ret = gnutls_x509_crt_import(crt, + &cert_data, + GNUTLS_X509_FMT_PEM); if (GNUTLS_E_SUCCESS != ret) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to import certificate from `%s'\n"), - certfile); - } - GNUNET_free_non_null (cert_data.data); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to import certificate from `%s'\n"), + certfile); + } + GNUNET_free_non_null(cert_data.data); return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK; } @@ -2693,7 +2686,7 @@ load_cert_from_file (gnutls_x509_crt_t crt, * @return a struct holding the PEM data, NULL on error */ static struct ProxyGNSCertificate * -generate_gns_certificate (const char *name) +generate_gns_certificate(const char *name) { unsigned int serial; size_t key_buf_size; @@ -2703,65 +2696,65 @@ generate_gns_certificate (const char *name) struct tm *tm_data; struct ProxyGNSCertificate *pgc; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Generating x.509 certificate for `%s'\n", - name); - GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_init (&request)); - GNUNET_break (GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key (request, proxy_ca.key)); - pgc = GNUNET_new (struct ProxyGNSCertificate); - gnutls_x509_crt_set_dn_by_oid (request, - GNUTLS_OID_X520_COUNTRY_NAME, - 0, - "ZZ", - strlen ("ZZ")); - gnutls_x509_crt_set_dn_by_oid (request, - GNUTLS_OID_X520_ORGANIZATION_NAME, - 0, - "GNU Name System", - strlen ("GNU Name System")); - gnutls_x509_crt_set_dn_by_oid (request, - GNUTLS_OID_X520_COMMON_NAME, - 0, - name, - strlen (name)); - gnutls_x509_crt_set_subject_alternative_name (request, - GNUTLS_SAN_DNSNAME, - name); - GNUNET_break (GNUTLS_E_SUCCESS == - gnutls_x509_crt_set_version (request, - 3)); - gnutls_rnd (GNUTLS_RND_NONCE, - &serial, - sizeof (serial)); - gnutls_x509_crt_set_serial (request, - &serial, - sizeof (serial)); - etime = time (NULL); - tm_data = localtime (&etime); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Generating x.509 certificate for `%s'\n", + name); + GNUNET_break(GNUTLS_E_SUCCESS == gnutls_x509_crt_init(&request)); + GNUNET_break(GNUTLS_E_SUCCESS == gnutls_x509_crt_set_key(request, proxy_ca.key)); + pgc = GNUNET_new(struct ProxyGNSCertificate); + gnutls_x509_crt_set_dn_by_oid(request, + GNUTLS_OID_X520_COUNTRY_NAME, + 0, + "ZZ", + strlen("ZZ")); + gnutls_x509_crt_set_dn_by_oid(request, + GNUTLS_OID_X520_ORGANIZATION_NAME, + 0, + "GNU Name System", + strlen("GNU Name System")); + gnutls_x509_crt_set_dn_by_oid(request, + GNUTLS_OID_X520_COMMON_NAME, + 0, + name, + strlen(name)); + gnutls_x509_crt_set_subject_alternative_name(request, + GNUTLS_SAN_DNSNAME, + name); + GNUNET_break(GNUTLS_E_SUCCESS == + gnutls_x509_crt_set_version(request, + 3)); + gnutls_rnd(GNUTLS_RND_NONCE, + &serial, + sizeof(serial)); + gnutls_x509_crt_set_serial(request, + &serial, + sizeof(serial)); + etime = time(NULL); + tm_data = localtime(&etime); tm_data->tm_hour--; etime = mktime(tm_data); - gnutls_x509_crt_set_activation_time (request, - etime); + gnutls_x509_crt_set_activation_time(request, + etime); tm_data->tm_year++; - etime = mktime (tm_data); - gnutls_x509_crt_set_expiration_time (request, - etime); - gnutls_x509_crt_sign2 (request, - proxy_ca.cert, - proxy_ca.key, - GNUTLS_DIG_SHA512, - 0); - key_buf_size = sizeof (pgc->key); - cert_buf_size = sizeof (pgc->cert); - gnutls_x509_crt_export (request, - GNUTLS_X509_FMT_PEM, - pgc->cert, - &cert_buf_size); - gnutls_x509_privkey_export (proxy_ca.key, - GNUTLS_X509_FMT_PEM, - pgc->key, - &key_buf_size); - gnutls_x509_crt_deinit (request); + etime = mktime(tm_data); + gnutls_x509_crt_set_expiration_time(request, + etime); + gnutls_x509_crt_sign2(request, + proxy_ca.cert, + proxy_ca.key, + GNUTLS_DIG_SHA512, + 0); + key_buf_size = sizeof(pgc->key); + cert_buf_size = sizeof(pgc->cert); + gnutls_x509_crt_export(request, + GNUTLS_X509_FMT_PEM, + pgc->cert, + &cert_buf_size); + gnutls_x509_privkey_export(proxy_ca.key, + GNUTLS_X509_FMT_PEM, + pgc->key, + &key_buf_size); + gnutls_x509_crt_deinit(request); return pgc; } @@ -2774,9 +2767,9 @@ generate_gns_certificate (const char *name) * @param ap arguments to @a fm */ static void -mhd_error_log_callback (void *cls, - const char *fm, - va_list ap) +mhd_error_log_callback(void *cls, + const char *fm, + va_list ap) { /* do nothing */ } @@ -2789,49 +2782,49 @@ mhd_error_log_callback (void *cls, * @return NULL on error */ static struct MhdHttpList * -lookup_ssl_httpd (const char* domain) +lookup_ssl_httpd(const char* domain) { struct MhdHttpList *hd; struct ProxyGNSCertificate *pgc; if (NULL == domain) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } for (hd = mhd_httpd_head; NULL != hd; hd = hd->next) - if ( (NULL != hd->domain) && - (0 == strcmp (hd->domain, domain)) ) + if ((NULL != hd->domain) && + (0 == strcmp(hd->domain, domain))) return hd; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting fresh MHD HTTPS instance for domain `%s'\n", - domain); - pgc = generate_gns_certificate (domain); - hd = GNUNET_new (struct MhdHttpList); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting fresh MHD HTTPS instance for domain `%s'\n", + domain); + pgc = generate_gns_certificate(domain); + hd = GNUNET_new(struct MhdHttpList); hd->is_ssl = GNUNET_YES; - hd->domain = GNUNET_strdup (domain); + hd->domain = GNUNET_strdup(domain); hd->proxy_cert = pgc; - hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME, - 0, - NULL, NULL, - &create_response, hd, - MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16, - MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL, - MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL, - MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL, - MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL, - MHD_OPTION_HTTPS_MEM_KEY, pgc->key, - MHD_OPTION_HTTPS_MEM_CERT, pgc->cert, - MHD_OPTION_END); + hd->daemon = MHD_start_daemon(MHD_USE_DEBUG | MHD_USE_SSL | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME, + 0, + NULL, NULL, + &create_response, hd, + MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)16, + MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL, + MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL, + MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL, + MHD_OPTION_EXTERNAL_LOGGER, &mhd_error_log_callback, NULL, + MHD_OPTION_HTTPS_MEM_KEY, pgc->key, + MHD_OPTION_HTTPS_MEM_CERT, pgc->cert, + MHD_OPTION_END); if (NULL == hd->daemon) - { - GNUNET_free (pgc); - GNUNET_free (hd); - return NULL; - } - GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, - mhd_httpd_tail, - hd); + { + GNUNET_free(pgc); + GNUNET_free(hd); + return NULL; + } + GNUNET_CONTAINER_DLL_insert(mhd_httpd_head, + mhd_httpd_tail, + hd); return hd; } @@ -2844,12 +2837,12 @@ lookup_ssl_httpd (const char* domain) * @param cls the `struct Socks5Request *` */ static void -timeout_s5r_handshake (void *cls) +timeout_s5r_handshake(void *cls) { struct Socks5Request *s5r = cls; s5r->timeout_task = NULL; - cleanup_s5r (s5r); + cleanup_s5r(s5r); } @@ -2862,7 +2855,7 @@ timeout_s5r_handshake (void *cls) * @param s5r socks request that has reached the final stage */ static void -setup_data_transfer (struct Socks5Request *s5r) +setup_data_transfer(struct Socks5Request *s5r) { struct MhdHttpList *hd; int fd; @@ -2871,47 +2864,49 @@ setup_data_transfer (struct Socks5Request *s5r) char *domain; if (GNUNET_YES == s5r->is_tls) - { - GNUNET_asprintf (&domain, - "%s", + { + GNUNET_asprintf(&domain, + "%s", + s5r->domain); + hd = lookup_ssl_httpd(domain); + if (NULL == hd) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to start HTTPS server for `%s'\n"), s5r->domain); - hd = lookup_ssl_httpd (domain); - if (NULL == hd) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to start HTTPS server for `%s'\n"), - s5r->domain); - cleanup_s5r (s5r); - GNUNET_free (domain); - return; + cleanup_s5r(s5r); + GNUNET_free(domain); + return; + } } - } else { + else + { domain = NULL; - GNUNET_assert (NULL != httpd); + GNUNET_assert(NULL != httpd); hd = httpd; - } - fd = GNUNET_NETWORK_get_fd (s5r->sock); - addr = GNUNET_NETWORK_get_addr (s5r->sock); - len = GNUNET_NETWORK_get_addrlen (s5r->sock); + } + fd = GNUNET_NETWORK_get_fd(s5r->sock); + addr = GNUNET_NETWORK_get_addr(s5r->sock); + len = GNUNET_NETWORK_get_addrlen(s5r->sock); s5r->state = SOCKS5_SOCKET_WITH_MHD; if (MHD_YES != - MHD_add_connection (hd->daemon, - fd, - addr, - len)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed to pass client to MHD\n")); - cleanup_s5r (s5r); - GNUNET_free_non_null (domain); - return; - } + MHD_add_connection(hd->daemon, + fd, + addr, + len)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to pass client to MHD\n")); + cleanup_s5r(s5r); + GNUNET_free_non_null(domain); + return; + } s5r->hd = hd; - schedule_httpd (hd); - s5r->timeout_task = GNUNET_SCHEDULER_add_delayed (HTTP_HANDSHAKE_TIMEOUT, - &timeout_s5r_handshake, - s5r); - GNUNET_free_non_null (domain); + schedule_httpd(hd); + s5r->timeout_task = GNUNET_SCHEDULER_add_delayed(HTTP_HANDSHAKE_TIMEOUT, + &timeout_s5r_handshake, + s5r); + GNUNET_free_non_null(domain); } @@ -2924,57 +2919,61 @@ setup_data_transfer (struct Socks5Request *s5r) * @param cls the closure with the `struct Socks5Request` */ static void -do_write (void *cls) +do_write(void *cls) { struct Socks5Request *s5r = cls; ssize_t len; s5r->wtask = NULL; - len = GNUNET_NETWORK_socket_send (s5r->sock, - s5r->wbuf, - s5r->wbuf_len); + len = GNUNET_NETWORK_socket_send(s5r->sock, + s5r->wbuf, + s5r->wbuf_len); if (len <= 0) - { - /* write error: connection closed, shutdown, etc.; just clean up */ - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Write Error\n"); - cleanup_s5r (s5r); - return; - } - memmove (s5r->wbuf, - &s5r->wbuf[len], - s5r->wbuf_len - len); + { + /* write error: connection closed, shutdown, etc.; just clean up */ + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Write Error\n"); + cleanup_s5r(s5r); + return; + } + memmove(s5r->wbuf, + &s5r->wbuf[len], + s5r->wbuf_len - len); s5r->wbuf_len -= len; if (s5r->wbuf_len > 0) - { - /* not done writing */ - s5r->wtask = - GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL, - s5r->sock, - &do_write, s5r); - return; - } + { + /* not done writing */ + s5r->wtask = + GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL, + s5r->sock, + &do_write, s5r); + return; + } /* we're done writing, continue with state machine! */ switch (s5r->state) - { + { case SOCKS5_INIT: - GNUNET_assert (0); + GNUNET_assert(0); break; + case SOCKS5_REQUEST: - GNUNET_assert (NULL != s5r->rtask); + GNUNET_assert(NULL != s5r->rtask); break; + case SOCKS5_DATA_TRANSFER: - setup_data_transfer (s5r); + setup_data_transfer(s5r); return; + case SOCKS5_WRITE_THEN_CLEANUP: - cleanup_s5r (s5r); + cleanup_s5r(s5r); return; + default: - GNUNET_break (0); + GNUNET_break(0); break; - } + } } @@ -2985,21 +2984,21 @@ do_write (void *cls) * @param sc status code to return */ static void -signal_socks_failure (struct Socks5Request *s5r, - enum Socks5StatusCode sc) +signal_socks_failure(struct Socks5Request *s5r, + enum Socks5StatusCode sc) { struct Socks5ServerResponseMessage *s_resp; - s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len]; - memset (s_resp, 0, sizeof (struct Socks5ServerResponseMessage)); + s_resp = (struct Socks5ServerResponseMessage *)&s5r->wbuf[s5r->wbuf_len]; + memset(s_resp, 0, sizeof(struct Socks5ServerResponseMessage)); s_resp->version = SOCKS_VERSION_5; s_resp->reply = sc; s5r->state = SOCKS5_WRITE_THEN_CLEANUP; if (NULL != s5r->wtask) s5r->wtask = - GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL, - s5r->sock, - &do_write, s5r); + GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL, + s5r->sock, + &do_write, s5r); } @@ -3009,26 +3008,26 @@ signal_socks_failure (struct Socks5Request *s5r, * @param s5r request to return success status message for */ static void -signal_socks_success (struct Socks5Request *s5r) +signal_socks_success(struct Socks5Request *s5r) { struct Socks5ServerResponseMessage *s_resp; - s_resp = (struct Socks5ServerResponseMessage *) &s5r->wbuf[s5r->wbuf_len]; + s_resp = (struct Socks5ServerResponseMessage *)&s5r->wbuf[s5r->wbuf_len]; s_resp->version = SOCKS_VERSION_5; s_resp->reply = SOCKS5_STATUS_REQUEST_GRANTED; s_resp->reserved = 0; s_resp->addr_type = SOCKS5_AT_IPV4; /* zero out IPv4 address and port */ - memset (&s_resp[1], - 0, - sizeof (struct in_addr) + sizeof (uint16_t)); - s5r->wbuf_len += sizeof (struct Socks5ServerResponseMessage) + - sizeof (struct in_addr) + sizeof (uint16_t); + memset(&s_resp[1], + 0, + sizeof(struct in_addr) + sizeof(uint16_t)); + s5r->wbuf_len += sizeof(struct Socks5ServerResponseMessage) + + sizeof(struct in_addr) + sizeof(uint16_t); if (NULL == s5r->wtask) s5r->wtask = - GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL, - s5r->sock, - &do_write, s5r); + GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL, + s5r->sock, + &do_write, s5r); } @@ -3041,10 +3040,10 @@ signal_socks_success (struct Socks5Request *s5r) * @param rd record data */ static void -handle_gns_result (void *cls, - int tld, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +handle_gns_result(void *cls, + int tld, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct Socks5Request *s5r = cls; const struct GNUNET_GNSRECORD_Data *r; @@ -3053,118 +3052,123 @@ handle_gns_result (void *cls, s5r->gns_lookup = NULL; s5r->is_gns = tld; got_ip = GNUNET_NO; - for (uint32_t i=0;irecord_type) + for (uint32_t i = 0; i < rd_count; i++) { - case GNUNET_DNSPARSER_TYPE_A: + r = &rd[i]; + switch (r->record_type) + { + case GNUNET_DNSPARSER_TYPE_A: { struct sockaddr_in *in; - if (sizeof (struct in_addr) != r->data_size) - { - GNUNET_break_op (0); - break; - } + if (sizeof(struct in_addr) != r->data_size) + { + GNUNET_break_op(0); + break; + } if (GNUNET_YES == got_ip) break; if (GNUNET_OK != - GNUNET_NETWORK_test_pf (PF_INET)) + GNUNET_NETWORK_test_pf(PF_INET)) break; got_ip = GNUNET_YES; - in = (struct sockaddr_in *) &s5r->destination_address; + in = (struct sockaddr_in *)&s5r->destination_address; in->sin_family = AF_INET; - GNUNET_memcpy (&in->sin_addr, - r->data, - r->data_size); - in->sin_port = htons (s5r->port); + GNUNET_memcpy(&in->sin_addr, + r->data, + r->data_size); + in->sin_port = htons(s5r->port); #if HAVE_SOCKADDR_IN_SIN_LEN - in->sin_len = sizeof (*in); + in->sin_len = sizeof(*in); #endif } break; - case GNUNET_DNSPARSER_TYPE_AAAA: + + case GNUNET_DNSPARSER_TYPE_AAAA: { struct sockaddr_in6 *in; - if (sizeof (struct in6_addr) != r->data_size) - { - GNUNET_break_op (0); - break; - } + if (sizeof(struct in6_addr) != r->data_size) + { + GNUNET_break_op(0); + break; + } if (GNUNET_YES == got_ip) break; if (GNUNET_YES == disable_v6) break; if (GNUNET_OK != - GNUNET_NETWORK_test_pf (PF_INET6)) + GNUNET_NETWORK_test_pf(PF_INET6)) break; /* FIXME: allow user to disable IPv6 per configuration option... */ got_ip = GNUNET_YES; - in = (struct sockaddr_in6 *) &s5r->destination_address; + in = (struct sockaddr_in6 *)&s5r->destination_address; in->sin6_family = AF_INET6; - GNUNET_memcpy (&in->sin6_addr, - r->data, - r->data_size); - in->sin6_port = htons (s5r->port); + GNUNET_memcpy(&in->sin6_addr, + r->data, + r->data_size); + in->sin6_port = htons(s5r->port); #if HAVE_SOCKADDR_IN_SIN_LEN - in->sin6_len = sizeof (*in); + in->sin6_len = sizeof(*in); #endif } break; - case GNUNET_GNSRECORD_TYPE_VPN: - GNUNET_break (0); /* should have been translated within GNS */ - break; - case GNUNET_GNSRECORD_TYPE_LEHO: - GNUNET_free_non_null (s5r->leho); - s5r->leho = GNUNET_strndup (r->data, - r->data_size); - break; - case GNUNET_GNSRECORD_TYPE_BOX: + + case GNUNET_GNSRECORD_TYPE_VPN: + GNUNET_break(0); /* should have been translated within GNS */ + break; + + case GNUNET_GNSRECORD_TYPE_LEHO: + GNUNET_free_non_null(s5r->leho); + s5r->leho = GNUNET_strndup(r->data, + r->data_size); + break; + + case GNUNET_GNSRECORD_TYPE_BOX: { const struct GNUNET_GNSRECORD_BoxRecord *box; - if (r->data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord)) - { - GNUNET_break_op (0); - break; - } + if (r->data_size < sizeof(struct GNUNET_GNSRECORD_BoxRecord)) + { + GNUNET_break_op(0); + break; + } box = r->data; - if ( (ntohl (box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) || - (ntohs (box->protocol) != IPPROTO_TCP) || - (ntohs (box->service) != s5r->port) ) + if ((ntohl(box->record_type) != GNUNET_DNSPARSER_TYPE_TLSA) || + (ntohs(box->protocol) != IPPROTO_TCP) || + (ntohs(box->service) != s5r->port)) break; /* BOX record does not apply */ - if (s5r->num_danes >= MAX_DANES) - { - GNUNET_break (0); /* MAX_DANES too small */ - break; - } + if (s5r->num_danes >= MAX_DANES) + { + GNUNET_break(0); /* MAX_DANES too small */ + break; + } s5r->is_tls = GNUNET_YES; /* This should be TLS */ s5r->dane_data_len[s5r->num_danes] - = r->data_size - sizeof (struct GNUNET_GNSRECORD_BoxRecord); + = r->data_size - sizeof(struct GNUNET_GNSRECORD_BoxRecord); s5r->dane_data[s5r->num_danes] - = GNUNET_memdup (&box[1], - s5r->dane_data_len[s5r->num_danes]); - s5r->num_danes++; + = GNUNET_memdup(&box[1], + s5r->dane_data_len[s5r->num_danes]); + s5r->num_danes++; + break; + } + + default: + /* don't care */ break; } - default: - /* don't care */ - break; } - } - if ( (GNUNET_YES != got_ip) && - (GNUNET_YES == tld) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name resolution failed to yield useful IP address.\n"); - signal_socks_failure (s5r, - SOCKS5_STATUS_GENERAL_FAILURE); - return; - } + if ((GNUNET_YES != got_ip) && + (GNUNET_YES == tld)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name resolution failed to yield useful IP address.\n"); + signal_socks_failure(s5r, + SOCKS5_STATUS_GENERAL_FAILURE); + return; + } s5r->state = SOCKS5_DATA_TRANSFER; - signal_socks_success (s5r); + signal_socks_success(s5r); } @@ -3175,13 +3179,13 @@ handle_gns_result (void *cls, * @param len number of bytes in read buffer to advance */ static void -clear_from_s5r_rbuf (struct Socks5Request *s5r, - size_t len) +clear_from_s5r_rbuf(struct Socks5Request *s5r, + size_t len) { - GNUNET_assert (len <= s5r->rbuf_len); - memmove (s5r->rbuf, - &s5r->rbuf[len], - s5r->rbuf_len - len); + GNUNET_assert(len <= s5r->rbuf_len); + memmove(s5r->rbuf, + &s5r->rbuf[len], + s5r->rbuf_len - len); s5r->rbuf_len -= len; } @@ -3192,7 +3196,7 @@ clear_from_s5r_rbuf (struct Socks5Request *s5r, * @param cls the closure with the `struct Socks5Request` */ static void -do_s5r_read (void *cls) +do_s5r_read(void *cls) { struct Socks5Request *s5r = cls; const struct Socks5ClientHelloMessage *c_hello; @@ -3203,188 +3207,196 @@ do_s5r_read (void *cls) const struct GNUNET_SCHEDULER_TaskContext *tc; s5r->rtask = NULL; - tc = GNUNET_SCHEDULER_get_task_context (); - if ( (NULL != tc->read_ready) && - (GNUNET_NETWORK_fdset_isset (tc->read_ready, - s5r->sock)) ) - { - rlen = GNUNET_NETWORK_socket_recv (s5r->sock, - &s5r->rbuf[s5r->rbuf_len], - sizeof (s5r->rbuf) - s5r->rbuf_len); - if (rlen <= 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "socks5 client disconnected.\n"); - cleanup_s5r (s5r); - return; + tc = GNUNET_SCHEDULER_get_task_context(); + if ((NULL != tc->read_ready) && + (GNUNET_NETWORK_fdset_isset(tc->read_ready, + s5r->sock))) + { + rlen = GNUNET_NETWORK_socket_recv(s5r->sock, + &s5r->rbuf[s5r->rbuf_len], + sizeof(s5r->rbuf) - s5r->rbuf_len); + if (rlen <= 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "socks5 client disconnected.\n"); + cleanup_s5r(s5r); + return; + } + s5r->rbuf_len += rlen; } - s5r->rbuf_len += rlen; - } - s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - s5r->sock, - &do_s5r_read, s5r); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Processing %zu bytes of socks data in state %d\n", - s5r->rbuf_len, - s5r->state); + s5r->rtask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + s5r->sock, + &do_s5r_read, s5r); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Processing %zu bytes of socks data in state %d\n", + s5r->rbuf_len, + s5r->state); switch (s5r->state) - { + { case SOCKS5_INIT: - c_hello = (const struct Socks5ClientHelloMessage*) &s5r->rbuf; - if ( (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage)) || - (s5r->rbuf_len < sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods) ) + c_hello = (const struct Socks5ClientHelloMessage*)&s5r->rbuf; + if ((s5r->rbuf_len < sizeof(struct Socks5ClientHelloMessage)) || + (s5r->rbuf_len < sizeof(struct Socks5ClientHelloMessage) + c_hello->num_auth_methods)) return; /* need more data */ if (SOCKS_VERSION_5 != c_hello->version) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unsupported socks version %d\n"), - (int) c_hello->version); - cleanup_s5r (s5r); - return; - } - clear_from_s5r_rbuf (s5r, - sizeof (struct Socks5ClientHelloMessage) + c_hello->num_auth_methods); - GNUNET_assert (0 == s5r->wbuf_len); - s_hello = (struct Socks5ServerHelloMessage *) &s5r->wbuf; - s5r->wbuf_len = sizeof (struct Socks5ServerHelloMessage); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unsupported socks version %d\n"), + (int)c_hello->version); + cleanup_s5r(s5r); + return; + } + clear_from_s5r_rbuf(s5r, + sizeof(struct Socks5ClientHelloMessage) + c_hello->num_auth_methods); + GNUNET_assert(0 == s5r->wbuf_len); + s_hello = (struct Socks5ServerHelloMessage *)&s5r->wbuf; + s5r->wbuf_len = sizeof(struct Socks5ServerHelloMessage); s_hello->version = SOCKS_VERSION_5; s_hello->auth_method = SOCKS_AUTH_NONE; - GNUNET_assert (NULL == s5r->wtask); - s5r->wtask = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL, - s5r->sock, - &do_write, s5r); + GNUNET_assert(NULL == s5r->wtask); + s5r->wtask = GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL, + s5r->sock, + &do_write, s5r); s5r->state = SOCKS5_REQUEST; return; + case SOCKS5_REQUEST: - c_req = (const struct Socks5ClientRequestMessage *) &s5r->rbuf; - if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage)) + c_req = (const struct Socks5ClientRequestMessage *)&s5r->rbuf; + if (s5r->rbuf_len < sizeof(struct Socks5ClientRequestMessage)) return; switch (c_req->command) - { + { case SOCKS5_CMD_TCP_STREAM: /* handled below */ break; + default: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unsupported socks command %d\n"), - (int) c_req->command); - signal_socks_failure (s5r, - SOCKS5_STATUS_COMMAND_NOT_SUPPORTED); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unsupported socks command %d\n"), + (int)c_req->command); + signal_socks_failure(s5r, + SOCKS5_STATUS_COMMAND_NOT_SUPPORTED); return; - } + } switch (c_req->addr_type) - { + { case SOCKS5_AT_IPV4: - { - const struct in_addr *v4 = (const struct in_addr *) &c_req[1]; - const uint16_t *port = (const uint16_t *) &v4[1]; - struct sockaddr_in *in; - - s5r->port = ntohs (*port); - alen = sizeof (struct in_addr); - if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) + - alen + sizeof (uint16_t)) - return; /* need more data */ - in = (struct sockaddr_in *) &s5r->destination_address; - in->sin_family = AF_INET; - in->sin_addr = *v4; - in->sin_port = *port; + { + const struct in_addr *v4 = (const struct in_addr *)&c_req[1]; + const uint16_t *port = (const uint16_t *)&v4[1]; + struct sockaddr_in *in; + + s5r->port = ntohs(*port); + alen = sizeof(struct in_addr); + if (s5r->rbuf_len < sizeof(struct Socks5ClientRequestMessage) + + alen + sizeof(uint16_t)) + return; /* need more data */ + in = (struct sockaddr_in *)&s5r->destination_address; + in->sin_family = AF_INET; + in->sin_addr = *v4; + in->sin_port = *port; #if HAVE_SOCKADDR_IN_SIN_LEN - in->sin_len = sizeof (*in); + in->sin_len = sizeof(*in); #endif - s5r->state = SOCKS5_DATA_TRANSFER; - } - break; + s5r->state = SOCKS5_DATA_TRANSFER; + } + break; + case SOCKS5_AT_IPV6: - { - const struct in6_addr *v6 = (const struct in6_addr *) &c_req[1]; - const uint16_t *port = (const uint16_t *) &v6[1]; - struct sockaddr_in6 *in; - - s5r->port = ntohs (*port); - alen = sizeof (struct in6_addr); - if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) + - alen + sizeof (uint16_t)) - return; /* need more data */ - in = (struct sockaddr_in6 *) &s5r->destination_address; - in->sin6_family = AF_INET6; - in->sin6_addr = *v6; - in->sin6_port = *port; + { + const struct in6_addr *v6 = (const struct in6_addr *)&c_req[1]; + const uint16_t *port = (const uint16_t *)&v6[1]; + struct sockaddr_in6 *in; + + s5r->port = ntohs(*port); + alen = sizeof(struct in6_addr); + if (s5r->rbuf_len < sizeof(struct Socks5ClientRequestMessage) + + alen + sizeof(uint16_t)) + return; /* need more data */ + in = (struct sockaddr_in6 *)&s5r->destination_address; + in->sin6_family = AF_INET6; + in->sin6_addr = *v6; + in->sin6_port = *port; #if HAVE_SOCKADDR_IN_SIN_LEN - in->sin6_len = sizeof (*in); + in->sin6_len = sizeof(*in); #endif - s5r->state = SOCKS5_DATA_TRANSFER; - } - break; + s5r->state = SOCKS5_DATA_TRANSFER; + } + break; + case SOCKS5_AT_DOMAINNAME: - { - const uint8_t *dom_len; - const char *dom_name; - const uint16_t *port; - - dom_len = (const uint8_t *) &c_req[1]; - alen = *dom_len + 1; - if (s5r->rbuf_len < sizeof (struct Socks5ClientRequestMessage) + - alen + sizeof (uint16_t)) - return; /* need more data */ - dom_name = (const char *) &dom_len[1]; - port = (const uint16_t*) &dom_name[*dom_len]; - s5r->domain = GNUNET_strndup (dom_name, - *dom_len); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Requested connection is to %s:%d\n", - //(HTTPS_PORT == s5r->port) ? "s" : "", - s5r->domain, - ntohs (*port)); - s5r->state = SOCKS5_RESOLVING; - s5r->port = ntohs (*port); - s5r->is_tls = (HTTPS_PORT == s5r->port) ? GNUNET_YES : GNUNET_NO; - s5r->gns_lookup = GNUNET_GNS_lookup_with_tld (gns_handle, - s5r->domain, - GNUNET_DNSPARSER_TYPE_A, - GNUNET_NO /* only cached */, - &handle_gns_result, - s5r); - break; - } + { + const uint8_t *dom_len; + const char *dom_name; + const uint16_t *port; + + dom_len = (const uint8_t *)&c_req[1]; + alen = *dom_len + 1; + if (s5r->rbuf_len < sizeof(struct Socks5ClientRequestMessage) + + alen + sizeof(uint16_t)) + return; /* need more data */ + dom_name = (const char *)&dom_len[1]; + port = (const uint16_t*)&dom_name[*dom_len]; + s5r->domain = GNUNET_strndup(dom_name, + *dom_len); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Requested connection is to %s:%d\n", + //(HTTPS_PORT == s5r->port) ? "s" : "", + s5r->domain, + ntohs(*port)); + s5r->state = SOCKS5_RESOLVING; + s5r->port = ntohs(*port); + s5r->is_tls = (HTTPS_PORT == s5r->port) ? GNUNET_YES : GNUNET_NO; + s5r->gns_lookup = GNUNET_GNS_lookup_with_tld(gns_handle, + s5r->domain, + GNUNET_DNSPARSER_TYPE_A, + GNUNET_NO /* only cached */, + &handle_gns_result, + s5r); + break; + } + default: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unsupported socks address type %d\n"), - (int) c_req->addr_type); - signal_socks_failure (s5r, - SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unsupported socks address type %d\n"), + (int)c_req->addr_type); + signal_socks_failure(s5r, + SOCKS5_STATUS_ADDRESS_TYPE_NOT_SUPPORTED); return; - } - clear_from_s5r_rbuf (s5r, - sizeof (struct Socks5ClientRequestMessage) + - alen + sizeof (uint16_t)); + } + clear_from_s5r_rbuf(s5r, + sizeof(struct Socks5ClientRequestMessage) + + alen + sizeof(uint16_t)); if (0 != s5r->rbuf_len) - { - /* read more bytes than healthy, why did the client send more!? */ - GNUNET_break_op (0); - signal_socks_failure (s5r, - SOCKS5_STATUS_GENERAL_FAILURE); - return; - } + { + /* read more bytes than healthy, why did the client send more!? */ + GNUNET_break_op(0); + signal_socks_failure(s5r, + SOCKS5_STATUS_GENERAL_FAILURE); + return; + } if (SOCKS5_DATA_TRANSFER == s5r->state) - { - /* if we are not waiting for GNS resolution, signal success */ - signal_socks_success (s5r); - } + { + /* if we are not waiting for GNS resolution, signal success */ + signal_socks_success(s5r); + } /* We are done reading right now */ - GNUNET_SCHEDULER_cancel (s5r->rtask); + GNUNET_SCHEDULER_cancel(s5r->rtask); s5r->rtask = NULL; return; + case SOCKS5_RESOLVING: - GNUNET_assert (0); + GNUNET_assert(0); return; + case SOCKS5_DATA_TRANSFER: - GNUNET_assert (0); + GNUNET_assert(0); return; + default: - GNUNET_assert (0); + GNUNET_assert(0); return; - } + } } @@ -3395,46 +3407,46 @@ do_s5r_read (void *cls) * @param tc the scheduler context */ static void -do_accept (void *cls) +do_accept(void *cls) { struct GNUNET_NETWORK_Handle *lsock = cls; struct GNUNET_NETWORK_Handle *s; struct Socks5Request *s5r; - GNUNET_assert (NULL != lsock); + GNUNET_assert(NULL != lsock); if (lsock == lsock4) - ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - lsock, - &do_accept, - lsock); + ltask4 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + lsock, + &do_accept, + lsock); else if (lsock == lsock6) - ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - lsock, - &do_accept, - lsock); + ltask6 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + lsock, + &do_accept, + lsock); else - GNUNET_assert (0); - s = GNUNET_NETWORK_socket_accept (lsock, - NULL, - NULL); + GNUNET_assert(0); + s = GNUNET_NETWORK_socket_accept(lsock, + NULL, + NULL); if (NULL == s) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "accept"); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got an inbound connection, waiting for data\n"); - s5r = GNUNET_new (struct Socks5Request); - GNUNET_CONTAINER_DLL_insert (s5r_head, - s5r_tail, - s5r); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "accept"); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got an inbound connection, waiting for data\n"); + s5r = GNUNET_new(struct Socks5Request); + GNUNET_CONTAINER_DLL_insert(s5r_head, + s5r_tail, + s5r); s5r->sock = s; s5r->state = SOCKS5_INIT; - s5r->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - s5r->sock, - &do_s5r_read, - s5r); + s5r->rtask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + s5r->sock, + &do_s5r_read, + s5r); } @@ -3447,63 +3459,63 @@ do_accept (void *cls) * @param cls closure */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Shutting down...\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Shutting down...\n"); /* MHD requires resuming before destroying the daemons */ for (struct Socks5Request *s5r = s5r_head; NULL != s5r; s5r = s5r->next) - { - if (s5r->suspended) { - s5r->suspended = GNUNET_NO; - MHD_resume_connection (s5r->con); + if (s5r->suspended) + { + s5r->suspended = GNUNET_NO; + MHD_resume_connection(s5r->con); + } } - } while (NULL != mhd_httpd_head) - kill_httpd (mhd_httpd_head); + kill_httpd(mhd_httpd_head); while (NULL != s5r_head) - cleanup_s5r (s5r_head); + cleanup_s5r(s5r_head); if (NULL != lsock4) - { - GNUNET_NETWORK_socket_close (lsock4); - lsock4 = NULL; - } + { + GNUNET_NETWORK_socket_close(lsock4); + lsock4 = NULL; + } if (NULL != lsock6) - { - GNUNET_NETWORK_socket_close (lsock6); - lsock6 = NULL; - } + { + GNUNET_NETWORK_socket_close(lsock6); + lsock6 = NULL; + } if (NULL != curl_multi) - { - curl_multi_cleanup (curl_multi); - curl_multi = NULL; - } + { + curl_multi_cleanup(curl_multi); + curl_multi = NULL; + } if (NULL != gns_handle) - { - GNUNET_GNS_disconnect (gns_handle); - gns_handle = NULL; - } + { + GNUNET_GNS_disconnect(gns_handle); + gns_handle = NULL; + } if (NULL != curl_download_task) - { - GNUNET_SCHEDULER_cancel (curl_download_task); - curl_download_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(curl_download_task); + curl_download_task = NULL; + } if (NULL != ltask4) - { - GNUNET_SCHEDULER_cancel (ltask4); - ltask4 = NULL; - } + { + GNUNET_SCHEDULER_cancel(ltask4); + ltask4 = NULL; + } if (NULL != ltask6) - { - GNUNET_SCHEDULER_cancel (ltask6); - ltask6 = NULL; - } - gnutls_x509_crt_deinit (proxy_ca.cert); - gnutls_x509_privkey_deinit (proxy_ca.key); - gnutls_global_deinit (); + { + GNUNET_SCHEDULER_cancel(ltask6); + ltask6 = NULL; + } + gnutls_x509_crt_deinit(proxy_ca.cert); + gnutls_x509_privkey_deinit(proxy_ca.key); + gnutls_global_deinit(); } @@ -3513,34 +3525,34 @@ do_shutdown (void *cls) * @return NULL on error */ static struct GNUNET_NETWORK_Handle * -bind_v4 () +bind_v4() { struct GNUNET_NETWORK_Handle *ls; struct sockaddr_in sa4; int eno; - memset (&sa4, 0, sizeof (sa4)); + memset(&sa4, 0, sizeof(sa4)); sa4.sin_family = AF_INET; - sa4.sin_port = htons (port); + sa4.sin_port = htons(port); sa4.sin_addr.s_addr = address; #if HAVE_SOCKADDR_IN_SIN_LEN - sa4.sin_len = sizeof (sa4); + sa4.sin_len = sizeof(sa4); #endif - ls = GNUNET_NETWORK_socket_create (AF_INET, - SOCK_STREAM, - 0); + ls = GNUNET_NETWORK_socket_create(AF_INET, + SOCK_STREAM, + 0); if (NULL == ls) return NULL; if (GNUNET_OK != - GNUNET_NETWORK_socket_bind (ls, - (const struct sockaddr *) &sa4, - sizeof (sa4))) - { - eno = errno; - GNUNET_NETWORK_socket_close (ls); - errno = eno; - return NULL; - } + GNUNET_NETWORK_socket_bind(ls, + (const struct sockaddr *)&sa4, + sizeof(sa4))) + { + eno = errno; + GNUNET_NETWORK_socket_close(ls); + errno = eno; + return NULL; + } return ls; } @@ -3551,34 +3563,34 @@ bind_v4 () * @return NULL on error */ static struct GNUNET_NETWORK_Handle * -bind_v6 () +bind_v6() { struct GNUNET_NETWORK_Handle *ls; struct sockaddr_in6 sa6; int eno; - memset (&sa6, 0, sizeof (sa6)); + memset(&sa6, 0, sizeof(sa6)); sa6.sin6_family = AF_INET6; - sa6.sin6_port = htons (port); + sa6.sin6_port = htons(port); sa6.sin6_addr = address6; #if HAVE_SOCKADDR_IN_SIN_LEN - sa6.sin6_len = sizeof (sa6); + sa6.sin6_len = sizeof(sa6); #endif - ls = GNUNET_NETWORK_socket_create (AF_INET6, - SOCK_STREAM, - 0); + ls = GNUNET_NETWORK_socket_create(AF_INET6, + SOCK_STREAM, + 0); if (NULL == ls) return NULL; if (GNUNET_OK != - GNUNET_NETWORK_socket_bind (ls, - (const struct sockaddr *) &sa6, - sizeof (sa6))) - { - eno = errno; - GNUNET_NETWORK_socket_close (ls); - errno = eno; - return NULL; - } + GNUNET_NETWORK_socket_bind(ls, + (const struct sockaddr *)&sa6, + sizeof(sa6))) + { + eno = errno; + GNUNET_NETWORK_socket_close(ls); + errno = eno; + return NULL; + } return ls; } @@ -3592,10 +3604,10 @@ bind_v6 () * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { char* cafile_cfg = NULL; char* cafile; @@ -3605,198 +3617,198 @@ run (void *cls, cfg = c; /* Get address to bind to */ - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "gns-proxy", - "BIND_TO", - &addr_str)) - { - //No address specified - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Don't know what to bind to...\n"); - GNUNET_free (addr_str); - GNUNET_SCHEDULER_shutdown (); - return; - } - if (1 != inet_pton (AF_INET, addr_str, &address)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse address %s\n", - addr_str); - GNUNET_free (addr_str); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_free (addr_str); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, "gns-proxy", + "BIND_TO", + &addr_str)) + { + //No address specified + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Don't know what to bind to...\n"); + GNUNET_free(addr_str); + GNUNET_SCHEDULER_shutdown(); + return; + } + if (1 != inet_pton(AF_INET, addr_str, &address)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse address %s\n", + addr_str); + GNUNET_free(addr_str); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_free(addr_str); /* Get address to bind to */ - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "gns-proxy", - "BIND_TO6", - &addr_str)) - { - //No address specified - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Don't know what to bind6 to...\n"); - GNUNET_free (addr_str); - GNUNET_SCHEDULER_shutdown (); - return; - } - if (1 != inet_pton (AF_INET6, addr_str, &address6)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse IPv6 address %s\n", - addr_str); - GNUNET_free (addr_str); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_free (addr_str); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, "gns-proxy", + "BIND_TO6", + &addr_str)) + { + //No address specified + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Don't know what to bind6 to...\n"); + GNUNET_free(addr_str); + GNUNET_SCHEDULER_shutdown(); + return; + } + if (1 != inet_pton(AF_INET6, addr_str, &address6)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse IPv6 address %s\n", + addr_str); + GNUNET_free(addr_str); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_free(addr_str); - if (NULL == (curl_multi = curl_multi_init ())) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create cURL multi handle!\n"); - return; - } + if (NULL == (curl_multi = curl_multi_init())) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create cURL multi handle!\n"); + return; + } cafile = cafile_opt; if (NULL == cafile) - { - if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (cfg, - "gns-proxy", - "PROXY_CACERT", - &cafile_cfg)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "gns-proxy", - "PROXY_CACERT"); + { + if (GNUNET_OK != + GNUNET_CONFIGURATION_get_value_filename(cfg, + "gns-proxy", + "PROXY_CACERT", + &cafile_cfg)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "gns-proxy", + "PROXY_CACERT"); + return; + } + cafile = cafile_cfg; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Using `%s' as CA\n", + cafile); + + gnutls_global_init(); + gnutls_x509_crt_init(&proxy_ca.cert); + gnutls_x509_privkey_init(&proxy_ca.key); + + if ((GNUNET_OK != + load_cert_from_file(proxy_ca.cert, + cafile)) || + (GNUNET_OK != + load_key_from_file(proxy_ca.key, + cafile))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to load X.509 key and certificate from `%s'\n"), + cafile); + gnutls_x509_crt_deinit(proxy_ca.cert); + gnutls_x509_privkey_deinit(proxy_ca.key); + gnutls_global_deinit(); + GNUNET_free_non_null(cafile_cfg); return; } - cafile = cafile_cfg; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Using `%s' as CA\n", - cafile); - - gnutls_global_init (); - gnutls_x509_crt_init (&proxy_ca.cert); - gnutls_x509_privkey_init (&proxy_ca.key); - - if ( (GNUNET_OK != - load_cert_from_file (proxy_ca.cert, - cafile)) || - (GNUNET_OK != - load_key_from_file (proxy_ca.key, - cafile)) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to load X.509 key and certificate from `%s'\n"), - cafile); - gnutls_x509_crt_deinit (proxy_ca.cert); - gnutls_x509_privkey_deinit (proxy_ca.key); - gnutls_global_deinit (); - GNUNET_free_non_null (cafile_cfg); - return; - } - GNUNET_free_non_null (cafile_cfg); - if (NULL == (gns_handle = GNUNET_GNS_connect (cfg))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to connect to GNS!\n"); - gnutls_x509_crt_deinit (proxy_ca.cert); - gnutls_x509_privkey_deinit (proxy_ca.key); - gnutls_global_deinit (); - return; - } - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); + GNUNET_free_non_null(cafile_cfg); + if (NULL == (gns_handle = GNUNET_GNS_connect(cfg))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to connect to GNS!\n"); + gnutls_x509_crt_deinit(proxy_ca.cert); + gnutls_x509_privkey_deinit(proxy_ca.key); + gnutls_global_deinit(); + return; + } + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); /* Open listen socket for socks proxy */ - lsock6 = bind_v6 (); + lsock6 = bind_v6(); if (NULL == lsock6) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "bind"); - } - else - { - if (GNUNET_OK != - GNUNET_NETWORK_socket_listen (lsock6, - 5)) { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "listen"); - GNUNET_NETWORK_socket_close (lsock6); - lsock6 = NULL; + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "bind"); } - else + else { - ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - lsock6, - &do_accept, - lsock6); + if (GNUNET_OK != + GNUNET_NETWORK_socket_listen(lsock6, + 5)) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "listen"); + GNUNET_NETWORK_socket_close(lsock6); + lsock6 = NULL; + } + else + { + ltask6 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + lsock6, + &do_accept, + lsock6); + } } - } - lsock4 = bind_v4 (); + lsock4 = bind_v4(); if (NULL == lsock4) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "bind"); - } + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "bind"); + } else - { - if (GNUNET_OK != - GNUNET_NETWORK_socket_listen (lsock4, - 5)) { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "listen"); - GNUNET_NETWORK_socket_close (lsock4); - lsock4 = NULL; + if (GNUNET_OK != + GNUNET_NETWORK_socket_listen(lsock4, + 5)) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "listen"); + GNUNET_NETWORK_socket_close(lsock4); + lsock4 = NULL; + } + else + { + ltask4 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + lsock4, + &do_accept, + lsock4); + } } - else + if ((NULL == lsock4) && + (NULL == lsock6)) + { + GNUNET_SCHEDULER_shutdown(); + return; + } + if (0 != curl_global_init(CURL_GLOBAL_WIN32)) { - ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - lsock4, - &do_accept, - lsock4); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "cURL global init failed!\n"); + GNUNET_SCHEDULER_shutdown(); + return; } - } - if ( (NULL == lsock4) && - (NULL == lsock6) ) - { - GNUNET_SCHEDULER_shutdown (); - return; - } - if (0 != curl_global_init (CURL_GLOBAL_WIN32)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "cURL global init failed!\n"); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Proxy listens on port %u\n", - (unsigned int) port); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Proxy listens on port %u\n", + (unsigned int)port); /* start MHD daemon for HTTP */ - hd = GNUNET_new (struct MhdHttpList); - hd->daemon = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME, - 0, - NULL, NULL, - &create_response, hd, - MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16, - MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL, - MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL, - MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL, - MHD_OPTION_END); + hd = GNUNET_new(struct MhdHttpList); + hd->daemon = MHD_start_daemon(MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET | MHD_ALLOW_SUSPEND_RESUME, + 0, + NULL, NULL, + &create_response, hd, + MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)16, + MHD_OPTION_NOTIFY_COMPLETED, &mhd_completed_cb, NULL, + MHD_OPTION_NOTIFY_CONNECTION, &mhd_connection_cb, NULL, + MHD_OPTION_URI_LOG_CALLBACK, &mhd_log_callback, NULL, + MHD_OPTION_END); if (NULL == hd->daemon) - { - GNUNET_free (hd); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_free(hd); + GNUNET_SCHEDULER_shutdown(); + return; + } httpd = hd; - GNUNET_CONTAINER_DLL_insert (mhd_httpd_head, - mhd_httpd_tail, - hd); + GNUNET_CONTAINER_DLL_insert(mhd_httpd_head, + mhd_httpd_tail, + hd); } @@ -3808,24 +3820,24 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, - char *const *argv) +main(int argc, + char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_option_uint16 ('p', - "port", - NULL, - gettext_noop ("listen on specified port (default: 7777)"), - &port), - GNUNET_GETOPT_option_string ('a', - "authority", - NULL, - gettext_noop ("pem file to use as CA"), - &cafile_opt), - GNUNET_GETOPT_option_flag ('6', - "disable-ivp6", - gettext_noop ("disable use of IPv6"), - &disable_v6), + GNUNET_GETOPT_option_uint16('p', + "port", + NULL, + gettext_noop("listen on specified port (default: 7777)"), + &port), + GNUNET_GETOPT_option_string('a', + "authority", + NULL, + gettext_noop("pem file to use as CA"), + &cafile_opt), + GNUNET_GETOPT_option_flag('6', + "disable-ivp6", + gettext_noop("disable use of IPv6"), + &disable_v6), GNUNET_GETOPT_OPTION_END }; @@ -3835,26 +3847,26 @@ main (int argc, int ret; if (GNUNET_OK != - GNUNET_STRINGS_get_utf8_args (argc, argv, - &argc, &argv)) + GNUNET_STRINGS_get_utf8_args(argc, argv, + &argc, &argv)) return 2; - GNUNET_log_setup ("gnunet-gns-proxy", - "WARNING", - NULL); + GNUNET_log_setup("gnunet-gns-proxy", + "WARNING", + NULL); curl_failure_response - = MHD_create_response_from_buffer (strlen (page), - (void *) page, - MHD_RESPMEM_PERSISTENT); + = MHD_create_response_from_buffer(strlen(page), + (void *)page, + MHD_RESPMEM_PERSISTENT); ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, - "gnunet-gns-proxy", - _("GNUnet GNS proxy"), - options, - &run, NULL)) ? 0 : 1; - MHD_destroy_response (curl_failure_response); - GNUNET_free_non_null ((char *) argv); + GNUNET_PROGRAM_run(argc, argv, + "gnunet-gns-proxy", + _("GNUnet GNS proxy"), + options, + &run, NULL)) ? 0 : 1; + MHD_destroy_response(curl_failure_response); + GNUNET_free_non_null((char *)argv); return ret; } diff --git a/src/gns/gnunet-gns.c b/src/gns/gnunet-gns.c index d795f89fc..352ccce04 100644 --- a/src/gns/gnunet-gns.c +++ b/src/gns/gnunet-gns.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnunet-gns.c * @brief command line tool to access distributed GNS @@ -90,24 +90,24 @@ static int global_ret; * @param cls unused */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - (void) cls; + (void)cls; if (NULL != to_task) - { - GNUNET_SCHEDULER_cancel (to_task); - to_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(to_task); + to_task = NULL; + } if (NULL != lr) - { - GNUNET_GNS_lookup_with_tld_cancel (lr); - lr = NULL; - } + { + GNUNET_GNS_lookup_with_tld_cancel(lr); + lr = NULL; + } if (NULL != gns) - { - GNUNET_GNS_disconnect (gns); - gns = NULL; - } + { + GNUNET_GNS_disconnect(gns); + gns = NULL; + } } /** @@ -116,11 +116,11 @@ do_shutdown (void *cls) * @param cls unused */ static void -do_timeout (void* cls) +do_timeout(void* cls) { to_task = NULL; global_ret = 3; //Timeout - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } /** @@ -132,10 +132,10 @@ do_timeout (void* cls) * @param rd array of @a rd_count records with the results */ static void -process_lookup_result (void *cls, - int was_gns, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +process_lookup_result(void *cls, + int was_gns, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { const char *name = cls; const char *typename; @@ -143,41 +143,41 @@ process_lookup_result (void *cls, lr = NULL; if (GNUNET_NO == was_gns) - { - global_ret = 4; /* not for GNS */ - GNUNET_SCHEDULER_shutdown (); - return; - } - if (! raw) - { - if (0 == rd_count) - printf ("No results.\n"); - else - printf ("%s:\n", name); - } + { + global_ret = 4; /* not for GNS */ + GNUNET_SCHEDULER_shutdown(); + return; + } + if (!raw) + { + if (0 == rd_count) + printf("No results.\n"); + else + printf("%s:\n", name); + } for (uint32_t i = 0; i < rd_count; i++) - { - if ((rd[i].record_type != rtype) && (GNUNET_GNSRECORD_TYPE_ANY != rtype)) - continue; - typename = GNUNET_GNSRECORD_number_to_typename (rd[i].record_type); - string_val = GNUNET_GNSRECORD_value_to_string (rd[i].record_type, - rd[i].data, - rd[i].data_size); - if (NULL == string_val) { - fprintf (stderr, - "Record %u of type %d malformed, skipping\n", - (unsigned int) i, - (int) rd[i].record_type); - continue; + if ((rd[i].record_type != rtype) && (GNUNET_GNSRECORD_TYPE_ANY != rtype)) + continue; + typename = GNUNET_GNSRECORD_number_to_typename(rd[i].record_type); + string_val = GNUNET_GNSRECORD_value_to_string(rd[i].record_type, + rd[i].data, + rd[i].data_size); + if (NULL == string_val) + { + fprintf(stderr, + "Record %u of type %d malformed, skipping\n", + (unsigned int)i, + (int)rd[i].record_type); + continue; + } + if (raw) + printf("%s\n", string_val); + else + printf("Got `%s' record: %s\n", typename, string_val); + GNUNET_free(string_val); } - if (raw) - printf ("%s\n", string_val); - else - printf ("Got `%s' record: %s\n", typename, string_val); - GNUNET_free (string_val); - } - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -190,53 +190,53 @@ process_lookup_result (void *cls, * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { - (void) cls; - (void) args; - (void) cfgfile; + (void)cls; + (void)args; + (void)cfgfile; cfg = c; to_task = NULL; - if (GNUNET_OK != GNUNET_DNSPARSER_check_name (lookup_name)) - { - fprintf (stderr, _ ("`%s' is not a valid domain name\n"), lookup_name); - global_ret = 3; - return; - } - to_task = GNUNET_SCHEDULER_add_delayed (timeout, &do_timeout, NULL); - gns = GNUNET_GNS_connect (cfg); + if (GNUNET_OK != GNUNET_DNSPARSER_check_name(lookup_name)) + { + fprintf(stderr, _("`%s' is not a valid domain name\n"), lookup_name); + global_ret = 3; + return; + } + to_task = GNUNET_SCHEDULER_add_delayed(timeout, &do_timeout, NULL); + gns = GNUNET_GNS_connect(cfg); if (NULL == gns) - { - fprintf (stderr, _ ("Failed to connect to GNS\n")); - global_ret = 2; - return; - } - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL); + { + fprintf(stderr, _("Failed to connect to GNS\n")); + global_ret = 2; + return; + } + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); if (NULL != lookup_type) - rtype = GNUNET_GNSRECORD_typename_to_number (lookup_type); + rtype = GNUNET_GNSRECORD_typename_to_number(lookup_type); else rtype = GNUNET_DNSPARSER_TYPE_A; if (UINT32_MAX == rtype) - { - fprintf (stderr, _ ("Invalid typename specified, assuming `ANY'\n")); - rtype = GNUNET_GNSRECORD_TYPE_ANY; - } - lr = GNUNET_GNS_lookup_with_tld (gns, - lookup_name, - rtype, - GNUNET_GNS_LO_DEFAULT, - &process_lookup_result, - lookup_name); + { + fprintf(stderr, _("Invalid typename specified, assuming `ANY'\n")); + rtype = GNUNET_GNSRECORD_TYPE_ANY; + } + lr = GNUNET_GNS_lookup_with_tld(gns, + lookup_name, + rtype, + GNUNET_GNS_LO_DEFAULT, + &process_lookup_result, + lookup_name); if (NULL == lr) - { - global_ret = 2; - GNUNET_SCHEDULER_shutdown (); - return; - } + { + global_ret = 2; + GNUNET_SCHEDULER_shutdown(); + return; + } } @@ -248,48 +248,48 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { timeout = GNUNET_TIME_UNIT_FOREVER_REL; struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_mandatory ( - GNUNET_GETOPT_option_string ('u', - "lookup", - "NAME", - gettext_noop ( - "Lookup a record for the given name"), - &lookup_name)), - GNUNET_GETOPT_option_string ('t', - "type", - "TYPE", - gettext_noop ( - "Specify the type of the record to lookup"), - &lookup_type), - GNUNET_GETOPT_option_relative_time ('T', - "timeout", - "TIMEOUT", - gettext_noop ( - "Specify a timeout for the lookup"), - &timeout), - GNUNET_GETOPT_option_flag ('r', - "raw", - gettext_noop ("No unneeded output"), - &raw), - GNUNET_GETOPT_OPTION_END}; + { GNUNET_GETOPT_option_mandatory( + GNUNET_GETOPT_option_string('u', + "lookup", + "NAME", + gettext_noop( + "Lookup a record for the given name"), + &lookup_name)), + GNUNET_GETOPT_option_string('t', + "type", + "TYPE", + gettext_noop( + "Specify the type of the record to lookup"), + &lookup_type), + GNUNET_GETOPT_option_relative_time('T', + "timeout", + "TIMEOUT", + gettext_noop( + "Specify a timeout for the lookup"), + &timeout), + GNUNET_GETOPT_option_flag('r', + "raw", + gettext_noop("No unneeded output"), + &raw), + GNUNET_GETOPT_OPTION_END }; int ret; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; - GNUNET_log_setup ("gnunet-gns", "WARNING", NULL); - ret = GNUNET_PROGRAM_run (argc, - argv, - "gnunet-gns", - _ ("GNUnet GNS resolver tool"), - options, - &run, - NULL); - GNUNET_free ((void *) argv); + GNUNET_log_setup("gnunet-gns", "WARNING", NULL); + ret = GNUNET_PROGRAM_run(argc, + argv, + "gnunet-gns", + _("GNUnet GNS resolver tool"), + options, + &run, + NULL); + GNUNET_free((void *)argv); if (GNUNET_OK != ret) return 1; return global_ret; diff --git a/src/gns/gnunet-service-gns.c b/src/gns/gnunet-service-gns.c index 65c232f93..5bfaf4859 100644 --- a/src/gns/gnunet-service-gns.c +++ b/src/gns/gnunet-service-gns.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/gnunet-service-gns.c * @brief GNU Name System (main service) @@ -46,9 +46,7 @@ struct GnsClient; /** * Handle to a lookup operation from client via API. */ -struct ClientLookupHandle -{ - +struct ClientLookupHandle { /** * We keep these in a DLL. */ @@ -73,15 +71,13 @@ struct ClientLookupHandle * request id */ uint32_t request_id; - }; /** * Information we track per connected client. */ -struct GnsClient -{ +struct GnsClient { /** * The client */ @@ -108,9 +104,7 @@ struct GnsClient * Representation of a TLD, mapping the respective TLD string * (i.e. ".gnu") to the respective public key of the zone. */ -struct GNS_TopLevelDomain -{ - +struct GNS_TopLevelDomain { /** * Kept in a DLL, as there are unlikely enough of these to * warrant a hash map. @@ -132,7 +126,6 @@ struct GNS_TopLevelDomain * Top-level domain as a string, including leading ".". */ char *tld; - }; @@ -180,25 +173,25 @@ static struct GNS_TopLevelDomain *tld_tail; * @return #GNUNET_YES if @a tld was found #GNUNET_NO if not */ int -GNS_find_tld (const char *tld_str, - struct GNUNET_CRYPTO_EcdsaPublicKey *pkey) +GNS_find_tld(const char *tld_str, + struct GNUNET_CRYPTO_EcdsaPublicKey *pkey) { if ('\0' == *tld_str) return GNUNET_NO; for (struct GNS_TopLevelDomain *tld = tld_head; NULL != tld; tld = tld->next) - { - if (0 == strcasecmp (tld_str, - tld->tld)) { - *pkey = tld->pkey; - return GNUNET_YES; + if (0 == strcasecmp(tld_str, + tld->tld)) + { + *pkey = tld->pkey; + return GNUNET_YES; + } } - } if (GNUNET_OK == - GNUNET_GNSRECORD_zkey_to_pkey (tld_str + 1, - pkey)) + GNUNET_GNSRECORD_zkey_to_pkey(tld_str + 1, + pkey)) return GNUNET_YES; /* TLD string *was* the public key */ return GNUNET_NO; } @@ -212,12 +205,12 @@ GNS_find_tld (const char *tld_str, * or @a name if @a name does not contain a "." */ const char * -GNS_get_tld (const char *name) +GNS_get_tld(const char *name) { const char *tld; - tld = strrchr (name, - (unsigned char) '.'); + tld = strrchr(name, + (unsigned char)'.'); if (NULL == tld) tld = name; else @@ -232,39 +225,39 @@ GNS_get_tld (const char *name) * @param cls unused, NULL */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { struct GNS_TopLevelDomain *tld; - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Shutting down!\n"); - GNS_interceptor_done (); - GNS_resolver_done (); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Shutting down!\n"); + GNS_interceptor_done(); + GNS_resolver_done(); if (NULL != statistics) - { - GNUNET_STATISTICS_destroy (statistics, - GNUNET_NO); - statistics = NULL; - } + { + GNUNET_STATISTICS_destroy(statistics, + GNUNET_NO); + statistics = NULL; + } if (NULL != namecache_handle) - { - GNUNET_NAMECACHE_disconnect (namecache_handle); - namecache_handle = NULL; - } + { + GNUNET_NAMECACHE_disconnect(namecache_handle); + namecache_handle = NULL; + } if (NULL != dht_handle) - { - GNUNET_DHT_disconnect (dht_handle); - dht_handle = NULL; - } + { + GNUNET_DHT_disconnect(dht_handle); + dht_handle = NULL; + } while (NULL != (tld = tld_head)) - { - GNUNET_CONTAINER_DLL_remove (tld_head, - tld_tail, - tld); - GNUNET_free (tld->tld); - GNUNET_free (tld); - } + { + GNUNET_CONTAINER_DLL_remove(tld_head, + tld_tail, + tld); + GNUNET_free(tld->tld); + GNUNET_free(tld); + } } @@ -276,27 +269,27 @@ shutdown_task (void *cls) * @param app_ctx @a client */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { struct ClientLookupHandle *clh; struct GnsClient *gc = app_ctx; - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Client %p disconnected\n", - client); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Client %p disconnected\n", + client); while (NULL != (clh = gc->clh_head)) - { - if (NULL != clh->lookup) - GNS_resolver_lookup_cancel (clh->lookup); - GNUNET_CONTAINER_DLL_remove (gc->clh_head, - gc->clh_tail, - clh); - GNUNET_free (clh); - } - GNUNET_free (gc); + { + if (NULL != clh->lookup) + GNS_resolver_lookup_cancel(clh->lookup); + GNUNET_CONTAINER_DLL_remove(gc->clh_head, + gc->clh_tail, + clh); + GNUNET_free(clh); + } + GNUNET_free(gc); } @@ -309,17 +302,17 @@ client_disconnect_cb (void *cls, * @return internal namestore client structure for this client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { struct GnsClient *gc; - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Client %p connected\n", - client); - gc = GNUNET_new (struct GnsClient); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Client %p connected\n", + client); + gc = GNUNET_new(struct GnsClient); gc->client = client; gc->mq = mq; return gc; @@ -334,9 +327,9 @@ client_connect_cb (void *cls, * @param rd the record data */ static void -send_lookup_response (void *cls, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +send_lookup_response(void *cls, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct ClientLookupHandle *clh = cls; struct GnsClient *gc = clh->gc; @@ -344,46 +337,46 @@ send_lookup_response (void *cls, struct LookupResultMessage *rmsg; ssize_t len; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending LOOKUP_RESULT message with %u results\n", - (unsigned int) rd_count); - len = GNUNET_GNSRECORD_records_get_size (rd_count, - rd); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending LOOKUP_RESULT message with %u results\n", + (unsigned int)rd_count); + len = GNUNET_GNSRECORD_records_get_size(rd_count, + rd); if (len < 0) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (gc->client); - return; - } - if (len > UINT16_MAX - sizeof (*rmsg)) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (gc->client); - return; - } - env = GNUNET_MQ_msg_extra (rmsg, - len, - GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(gc->client); + return; + } + if (len > UINT16_MAX - sizeof(*rmsg)) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(gc->client); + return; + } + env = GNUNET_MQ_msg_extra(rmsg, + len, + GNUNET_MESSAGE_TYPE_GNS_LOOKUP_RESULT); rmsg->id = clh->request_id; - rmsg->rd_count = htonl (rd_count); - GNUNET_assert (len == - GNUNET_GNSRECORD_records_serialize (rd_count, - rd, - len, - (char*) &rmsg[1])); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (gc->client), - env); - GNUNET_CONTAINER_DLL_remove (gc->clh_head, - gc->clh_tail, - clh); - GNUNET_free (clh); - GNUNET_STATISTICS_update (statistics, - "Completed lookups", 1, - GNUNET_NO); - GNUNET_STATISTICS_update (statistics, - "Records resolved", - rd_count, - GNUNET_NO); + rmsg->rd_count = htonl(rd_count); + GNUNET_assert(len == + GNUNET_GNSRECORD_records_serialize(rd_count, + rd, + len, + (char*)&rmsg[1])); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(gc->client), + env); + GNUNET_CONTAINER_DLL_remove(gc->clh_head, + gc->clh_tail, + clh); + GNUNET_free(clh); + GNUNET_STATISTICS_update(statistics, + "Completed lookups", 1, + GNUNET_NO); + GNUNET_STATISTICS_update(statistics, + "Records resolved", + rd_count, + GNUNET_NO); } @@ -395,19 +388,19 @@ send_lookup_response (void *cls, * @return #GNUNET_OK if @a l_msg is well-formed */ static int -check_lookup (void *cls, - const struct LookupMessage *l_msg) +check_lookup(void *cls, + const struct LookupMessage *l_msg) { size_t nlen; - (void) cls; - GNUNET_MQ_check_zero_termination (l_msg); - nlen = ntohs (l_msg->header.size) - sizeof (struct LookupMessage); + (void)cls; + GNUNET_MQ_check_zero_termination(l_msg); + nlen = ntohs(l_msg->header.size) - sizeof(struct LookupMessage); if (nlen > GNUNET_DNSPARSER_MAX_NAME_LENGTH) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -420,8 +413,8 @@ check_lookup (void *cls, * @param message the message */ static void -handle_lookup (void *cls, - const struct LookupMessage *sh_msg) +handle_lookup(void *cls, + const struct LookupMessage *sh_msg) { struct GnsClient *gc = cls; char name[GNUNET_DNSPARSER_MAX_NAME_LENGTH + 1]; @@ -429,47 +422,47 @@ handle_lookup (void *cls, char *nameptr = name; const char *utf_in; - GNUNET_SERVICE_client_continue (gc->client); - utf_in = (const char *) &sh_msg[1]; - GNUNET_STRINGS_utf8_tolower (utf_in, - nameptr); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received LOOKUP `%s' message\n", - name); - clh = GNUNET_new (struct ClientLookupHandle); - GNUNET_CONTAINER_DLL_insert (gc->clh_head, - gc->clh_tail, - clh); + GNUNET_SERVICE_client_continue(gc->client); + utf_in = (const char *)&sh_msg[1]; + GNUNET_STRINGS_utf8_tolower(utf_in, + nameptr); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received LOOKUP `%s' message\n", + name); + clh = GNUNET_new(struct ClientLookupHandle); + GNUNET_CONTAINER_DLL_insert(gc->clh_head, + gc->clh_tail, + clh); clh->gc = gc; clh->request_id = sh_msg->id; - if ( (GNUNET_DNSPARSER_TYPE_A == ntohl (sh_msg->type)) && - (GNUNET_OK != v4_enabled) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "LOOKUP: Query for A record but AF_INET not supported!"); - send_lookup_response (clh, - 0, - NULL); - return; - } - if ( (GNUNET_DNSPARSER_TYPE_AAAA == ntohl (sh_msg->type)) && - (GNUNET_OK != v6_enabled) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "LOOKUP: Query for AAAA record but AF_INET6 not supported!"); - send_lookup_response (clh, - 0, - NULL); - return; - } - clh->lookup = GNS_resolver_lookup (&sh_msg->zone, - ntohl (sh_msg->type), - name, - (enum GNUNET_GNS_LocalOptions) ntohs (sh_msg->options), - &send_lookup_response, clh); - GNUNET_STATISTICS_update (statistics, - "Lookup attempts", - 1, GNUNET_NO); + if ((GNUNET_DNSPARSER_TYPE_A == ntohl(sh_msg->type)) && + (GNUNET_OK != v4_enabled)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "LOOKUP: Query for A record but AF_INET not supported!"); + send_lookup_response(clh, + 0, + NULL); + return; + } + if ((GNUNET_DNSPARSER_TYPE_AAAA == ntohl(sh_msg->type)) && + (GNUNET_OK != v6_enabled)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "LOOKUP: Query for AAAA record but AF_INET6 not supported!"); + send_lookup_response(clh, + 0, + NULL); + return; + } + clh->lookup = GNS_resolver_lookup(&sh_msg->zone, + ntohl(sh_msg->type), + name, + (enum GNUNET_GNS_LocalOptions)ntohs(sh_msg->options), + &send_lookup_response, clh); + GNUNET_STATISTICS_update(statistics, + "Lookup attempts", + 1, GNUNET_NO); } @@ -482,36 +475,36 @@ handle_lookup (void *cls, * @param value value for the option, public key for TLDs */ static void -read_service_conf (void *cls, - const char *section, - const char *option, - const char *value) +read_service_conf(void *cls, + const char *section, + const char *option, + const char *value) { struct GNUNET_CRYPTO_EcdsaPublicKey pk; struct GNS_TopLevelDomain *tld; - (void) cls; - (void) section; + (void)cls; + (void)section; if (option[0] != '.') return; if (GNUNET_OK != - GNUNET_STRINGS_string_to_data (value, - strlen (value), - &pk, - sizeof (pk))) - { - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, - section, - option, - _("Properly base32-encoded public key required")); - return; - } - tld = GNUNET_new (struct GNS_TopLevelDomain); - tld->tld = GNUNET_strdup (&option[1]); + GNUNET_STRINGS_string_to_data(value, + strlen(value), + &pk, + sizeof(pk))) + { + GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_ERROR, + section, + option, + _("Properly base32-encoded public key required")); + return; + } + tld = GNUNET_new(struct GNS_TopLevelDomain); + tld->tld = GNUNET_strdup(&option[1]); tld->pkey = pk; - GNUNET_CONTAINER_DLL_insert (tld_head, - tld_tail, - tld); + GNUNET_CONTAINER_DLL_insert(tld_head, + tld_tail, + tld); } @@ -523,66 +516,66 @@ read_service_conf (void *cls, * @param c configuration to use */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *service) { unsigned long long max_parallel_bg_queries = 16; - GNUNET_CONFIGURATION_iterate_section_values (c, - "gns", - &read_service_conf, - NULL); - v6_enabled = GNUNET_NETWORK_test_pf (PF_INET6); - v4_enabled = GNUNET_NETWORK_test_pf (PF_INET); - namecache_handle = GNUNET_NAMECACHE_connect (c); + GNUNET_CONFIGURATION_iterate_section_values(c, + "gns", + &read_service_conf, + NULL); + v6_enabled = GNUNET_NETWORK_test_pf(PF_INET6); + v4_enabled = GNUNET_NETWORK_test_pf(PF_INET); + namecache_handle = GNUNET_NAMECACHE_connect(c); if (NULL == namecache_handle) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect to the namecache!\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to the namecache!\n")); + GNUNET_SCHEDULER_shutdown(); + return; + } if (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_number (c, - "gns", - "MAX_PARALLEL_BACKGROUND_QUERIES", - &max_parallel_bg_queries)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Number of allowed parallel background queries: %llu\n", - max_parallel_bg_queries); - } - dht_handle = GNUNET_DHT_connect (c, - (unsigned int) max_parallel_bg_queries); + GNUNET_CONFIGURATION_get_value_number(c, + "gns", + "MAX_PARALLEL_BACKGROUND_QUERIES", + &max_parallel_bg_queries)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Number of allowed parallel background queries: %llu\n", + max_parallel_bg_queries); + } + dht_handle = GNUNET_DHT_connect(c, + (unsigned int)max_parallel_bg_queries); if (NULL == dht_handle) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Could not connect to DHT!\n")); - GNUNET_SCHEDULER_add_now (&shutdown_task, - NULL); - return; - } - GNS_resolver_init (namecache_handle, - dht_handle, - c, - max_parallel_bg_queries); - if ( (GNUNET_YES == - GNUNET_CONFIGURATION_get_value_yesno (c, - "gns", - "INTERCEPT_DNS")) && - (GNUNET_SYSERR == - GNS_interceptor_init (c)) ) - { - GNUNET_break (0); - GNUNET_SCHEDULER_add_now (&shutdown_task, - NULL); - return; - } - statistics = GNUNET_STATISTICS_create ("gns", - c); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Could not connect to DHT!\n")); + GNUNET_SCHEDULER_add_now(&shutdown_task, + NULL); + return; + } + GNS_resolver_init(namecache_handle, + dht_handle, + c, + max_parallel_bg_queries); + if ((GNUNET_YES == + GNUNET_CONFIGURATION_get_value_yesno(c, + "gns", + "INTERCEPT_DNS")) && + (GNUNET_SYSERR == + GNS_interceptor_init(c))) + { + GNUNET_break(0); + GNUNET_SCHEDULER_add_now(&shutdown_task, + NULL); + return; + } + statistics = GNUNET_STATISTICS_create("gns", + c); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); } @@ -590,17 +583,17 @@ run (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("gns", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_var_size (lookup, + ("gns", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_var_size(lookup, GNUNET_MESSAGE_TYPE_GNS_LOOKUP, struct LookupMessage, NULL), - GNUNET_MQ_handler_end()); + GNUNET_MQ_handler_end()); /* end of gnunet-service-gns.c */ diff --git a/src/gns/gnunet-service-gns.h b/src/gns/gnunet-service-gns.h index d9309e985..2c17ca72a 100644 --- a/src/gns/gnunet-service-gns.h +++ b/src/gns/gnunet-service-gns.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/gnunet-service-gns.h * @brief GNU Name System (main service) @@ -35,8 +35,8 @@ * @return #GNUNET_YES if @a tld was found #GNUNET_NO if not */ int -GNS_find_tld (const char *tld_str, - struct GNUNET_CRYPTO_EcdsaPublicKey *pkey); +GNS_find_tld(const char *tld_str, + struct GNUNET_CRYPTO_EcdsaPublicKey *pkey); /** @@ -47,7 +47,7 @@ GNS_find_tld (const char *tld_str, * or @a name if @a name does not contain a "." */ const char * -GNS_get_tld (const char *name); +GNS_get_tld(const char *name); #endif diff --git a/src/gns/gnunet-service-gns_interceptor.c b/src/gns/gnunet-service-gns_interceptor.c index d5a84f6a0..e56aaef47 100644 --- a/src/gns/gnunet-service-gns_interceptor.c +++ b/src/gns/gnunet-service-gns_interceptor.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/gnunet-service-gns_interceptor.c * @brief GNUnet GNS interceptor logic @@ -37,9 +37,7 @@ * Handle to a DNS intercepted * reslution request */ -struct InterceptLookupHandle -{ - +struct InterceptLookupHandle { /** * We keep these in a DLL. */ @@ -64,7 +62,6 @@ struct InterceptLookupHandle * Handle for the lookup operation. */ struct GNS_ResolverHandle *lookup; - }; @@ -92,8 +89,8 @@ static struct InterceptLookupHandle *ilh_tail; * @param rd the record data */ static void -reply_to_dns (void *cls, uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +reply_to_dns(void *cls, uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct InterceptLookupHandle *ilh = cls; struct GNUNET_DNSPARSER_Packet *packet = ilh->packet; @@ -109,7 +106,7 @@ reply_to_dns (void *cls, uint32_t rd_count, /* Put records in the DNS packet */ num_answers = 0; - for (i=0; i < rd_count; i++) + for (i = 0; i < rd_count; i++) if (rd[i].record_type == query->type) num_answers++; skip_answers = 0; @@ -124,123 +121,131 @@ reply_to_dns (void *cls, uint32_t rd_count, /* FIXME: need to handle #GNUNET_GNSRECORD_RF_SHADOW_RECORD option (by ignoring records where this flag is set if there is any other record of that type in the result set) */ - for (i=0; i < rd_count; i++) - { - if (rd[i].record_type == query->type) + for (i = 0; i < rd_count; i++) { - answer_records[i - skip_answers].name = query->name; - answer_records[i - skip_answers].type = rd[i].record_type; - switch(rd[i].record_type) - { - case GNUNET_DNSPARSER_TYPE_NS: - case GNUNET_DNSPARSER_TYPE_CNAME: - case GNUNET_DNSPARSER_TYPE_PTR: - answer_records[i - skip_answers].data.hostname - = GNUNET_DNSPARSER_parse_name (rd[i].data, - rd[i].data_size, - &off); - if ( (off != rd[i].data_size) || - (NULL == answer_records[i].data.hostname) ) - { - GNUNET_break_op (0); - skip_answers++; - } - break; - case GNUNET_DNSPARSER_TYPE_SOA: - answer_records[i - skip_answers].data.soa - = GNUNET_DNSPARSER_parse_soa (rd[i].data, - rd[i].data_size, - &off); - if ( (off != rd[i].data_size) || - (NULL == answer_records[i].data.soa) ) - { - GNUNET_break_op (0); - skip_answers++; - } - break; - case GNUNET_DNSPARSER_TYPE_SRV: - /* FIXME: SRV is not yet supported */ - skip_answers++; - break; - case GNUNET_DNSPARSER_TYPE_MX: - answer_records[i - skip_answers].data.mx - = GNUNET_DNSPARSER_parse_mx (rd[i].data, - rd[i].data_size, - &off); - if ( (off != rd[i].data_size) || - (NULL == answer_records[i].data.hostname) ) - { - GNUNET_break_op (0); - skip_answers++; - } - break; - default: - answer_records[i - skip_answers].data.raw.data_len = rd[i].data_size; - answer_records[i - skip_answers].data.raw.data = (char*)rd[i].data; - break; - } - GNUNET_break (0 == (rd[i - skip_answers].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)); - answer_records[i - skip_answers].expiration_time.abs_value_us = rd[i].expiration_time; - answer_records[i - skip_answers].dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; - } - else - { - additional_records[i - skip_additional].name = query->name; - additional_records[i - skip_additional].type = rd[i].record_type; - switch(rd[i].record_type) - { - case GNUNET_DNSPARSER_TYPE_NS: - case GNUNET_DNSPARSER_TYPE_CNAME: - case GNUNET_DNSPARSER_TYPE_PTR: - additional_records[i - skip_additional].data.hostname - = GNUNET_DNSPARSER_parse_name (rd[i].data, - rd[i].data_size, - &off); - if ( (off != rd[i].data_size) || - (NULL == additional_records[i].data.hostname) ) - { - GNUNET_break_op (0); - skip_additional++; - } - break; - case GNUNET_DNSPARSER_TYPE_SOA: - additional_records[i - skip_additional].data.soa - = GNUNET_DNSPARSER_parse_soa (rd[i].data, - rd[i].data_size, - &off); - if ( (off != rd[i].data_size) || - (NULL == additional_records[i].data.hostname) ) - { - GNUNET_break_op (0); - skip_additional++; - } - break; - case GNUNET_DNSPARSER_TYPE_MX: - additional_records[i - skip_additional].data.mx - = GNUNET_DNSPARSER_parse_mx (rd[i].data, - rd[i].data_size, - &off); - if ( (off != rd[i].data_size) || - (NULL == additional_records[i].data.hostname) ) - { - GNUNET_break_op (0); - skip_additional++; - } - break; - case GNUNET_DNSPARSER_TYPE_SRV: - /* FIXME: SRV is not yet supported */ - skip_answers++; - break; - default: - additional_records[i - skip_additional].data.raw.data_len = rd[i].data_size; - additional_records[i - skip_additional].data.raw.data = (char*)rd[i].data; - break; - } - GNUNET_break (0 == (rd[i - skip_additional].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)); - additional_records[i - skip_additional].expiration_time.abs_value_us = rd[i].expiration_time; - additional_records[i - skip_additional].dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; + if (rd[i].record_type == query->type) + { + answer_records[i - skip_answers].name = query->name; + answer_records[i - skip_answers].type = rd[i].record_type; + switch (rd[i].record_type) + { + case GNUNET_DNSPARSER_TYPE_NS: + case GNUNET_DNSPARSER_TYPE_CNAME: + case GNUNET_DNSPARSER_TYPE_PTR: + answer_records[i - skip_answers].data.hostname + = GNUNET_DNSPARSER_parse_name(rd[i].data, + rd[i].data_size, + &off); + if ((off != rd[i].data_size) || + (NULL == answer_records[i].data.hostname)) + { + GNUNET_break_op(0); + skip_answers++; + } + break; + + case GNUNET_DNSPARSER_TYPE_SOA: + answer_records[i - skip_answers].data.soa + = GNUNET_DNSPARSER_parse_soa(rd[i].data, + rd[i].data_size, + &off); + if ((off != rd[i].data_size) || + (NULL == answer_records[i].data.soa)) + { + GNUNET_break_op(0); + skip_answers++; + } + break; + + case GNUNET_DNSPARSER_TYPE_SRV: + /* FIXME: SRV is not yet supported */ + skip_answers++; + break; + + case GNUNET_DNSPARSER_TYPE_MX: + answer_records[i - skip_answers].data.mx + = GNUNET_DNSPARSER_parse_mx(rd[i].data, + rd[i].data_size, + &off); + if ((off != rd[i].data_size) || + (NULL == answer_records[i].data.hostname)) + { + GNUNET_break_op(0); + skip_answers++; + } + break; + + default: + answer_records[i - skip_answers].data.raw.data_len = rd[i].data_size; + answer_records[i - skip_answers].data.raw.data = (char*)rd[i].data; + break; + } + GNUNET_break(0 == (rd[i - skip_answers].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)); + answer_records[i - skip_answers].expiration_time.abs_value_us = rd[i].expiration_time; + answer_records[i - skip_answers].dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; + } + else + { + additional_records[i - skip_additional].name = query->name; + additional_records[i - skip_additional].type = rd[i].record_type; + switch (rd[i].record_type) + { + case GNUNET_DNSPARSER_TYPE_NS: + case GNUNET_DNSPARSER_TYPE_CNAME: + case GNUNET_DNSPARSER_TYPE_PTR: + additional_records[i - skip_additional].data.hostname + = GNUNET_DNSPARSER_parse_name(rd[i].data, + rd[i].data_size, + &off); + if ((off != rd[i].data_size) || + (NULL == additional_records[i].data.hostname)) + { + GNUNET_break_op(0); + skip_additional++; + } + break; + + case GNUNET_DNSPARSER_TYPE_SOA: + additional_records[i - skip_additional].data.soa + = GNUNET_DNSPARSER_parse_soa(rd[i].data, + rd[i].data_size, + &off); + if ((off != rd[i].data_size) || + (NULL == additional_records[i].data.hostname)) + { + GNUNET_break_op(0); + skip_additional++; + } + break; + + case GNUNET_DNSPARSER_TYPE_MX: + additional_records[i - skip_additional].data.mx + = GNUNET_DNSPARSER_parse_mx(rd[i].data, + rd[i].data_size, + &off); + if ((off != rd[i].data_size) || + (NULL == additional_records[i].data.hostname)) + { + GNUNET_break_op(0); + skip_additional++; + } + break; + + case GNUNET_DNSPARSER_TYPE_SRV: + /* FIXME: SRV is not yet supported */ + skip_answers++; + break; + + default: + additional_records[i - skip_additional].data.raw.data_len = rd[i].data_size; + additional_records[i - skip_additional].data.raw.data = (char*)rd[i].data; + break; + } + GNUNET_break(0 == (rd[i - skip_additional].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)); + additional_records[i - skip_additional].expiration_time.abs_value_us = rd[i].expiration_time; + additional_records[i - skip_additional].dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; + } } - } packet->num_answers = num_answers - skip_answers; packet->num_additional_records = rd_count - num_answers - skip_additional; packet->flags.authoritative_answer = 1; @@ -249,32 +254,32 @@ reply_to_dns (void *cls, uint32_t rd_count, else packet->flags.return_code = GNUNET_TUN_DNS_RETURN_CODE_NO_ERROR; packet->flags.query_or_response = 1; - ret = GNUNET_DNSPARSER_pack (packet, - 1024, /* maximum allowed size for DNS reply */ - &buf, - &len); + ret = GNUNET_DNSPARSER_pack(packet, + 1024, /* maximum allowed size for DNS reply */ + &buf, + &len); if (GNUNET_OK != ret) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Error converting GNS response to DNS response!\n")); - if (GNUNET_NO == ret) - GNUNET_free (buf); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Error converting GNS response to DNS response!\n")); + if (GNUNET_NO == ret) + GNUNET_free(buf); + } else - { - GNUNET_DNS_request_answer (ilh->request_handle, - len, - buf); - GNUNET_free (buf); - } + { + GNUNET_DNS_request_answer(ilh->request_handle, + len, + buf); + GNUNET_free(buf); + } packet->num_answers = 0; packet->answers = NULL; packet->num_additional_records = 0; packet->additional_records = NULL; - GNUNET_DNSPARSER_free_packet (packet); + GNUNET_DNSPARSER_free_packet(packet); } - GNUNET_CONTAINER_DLL_remove (ilh_head, ilh_tail, ilh); - GNUNET_free (ilh); + GNUNET_CONTAINER_DLL_remove(ilh_head, ilh_tail, ilh); + GNUNET_free(ilh); } @@ -287,61 +292,61 @@ reply_to_dns (void *cls, uint32_t rd_count, * @param request UDP payload of the DNS request */ static void -handle_dns_request (void *cls, - struct GNUNET_DNS_RequestHandle *rh, - size_t request_length, - const char *request) +handle_dns_request(void *cls, + struct GNUNET_DNS_RequestHandle *rh, + size_t request_length, + const char *request) { struct GNUNET_DNSPARSER_Packet *p; struct InterceptLookupHandle *ilh; struct GNUNET_CRYPTO_EcdsaPublicKey zone; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Hijacked a DNS request. Processing.\n"); - if (NULL == (p = GNUNET_DNSPARSER_parse (request, request_length))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Received malformed DNS packet, leaving it untouched.\n"); - GNUNET_DNS_request_forward (rh); - GNUNET_DNSPARSER_free_packet (p); - return; - } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Hijacked a DNS request. Processing.\n"); + if (NULL == (p = GNUNET_DNSPARSER_parse(request, request_length))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Received malformed DNS packet, leaving it untouched.\n"); + GNUNET_DNS_request_forward(rh); + GNUNET_DNSPARSER_free_packet(p); + return; + } /* Check TLD and decide if we or legacy dns is responsible */ if (1 != p->num_queries) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Not exactly one query in DNS packet. Forwarding untouched.\n"); - GNUNET_DNS_request_forward (rh); - GNUNET_DNSPARSER_free_packet(p); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Not exactly one query in DNS packet. Forwarding untouched.\n"); + GNUNET_DNS_request_forward(rh); + GNUNET_DNSPARSER_free_packet(p); + return; + } /* Check for GNS TLDs. */ if (GNUNET_YES == - GNS_find_tld (GNS_get_tld (p->queries[0].name), - &zone)) - { - /* Start resolution in GNS */ - ilh = GNUNET_new (struct InterceptLookupHandle); - GNUNET_CONTAINER_DLL_insert (ilh_head, - ilh_tail, - ilh); - ilh->packet = p; - ilh->request_handle = rh; - ilh->lookup = GNS_resolver_lookup (&zone, - p->queries[0].type, - p->queries[0].name, - GNUNET_NO, - &reply_to_dns, ilh); - return; - } + GNS_find_tld(GNS_get_tld(p->queries[0].name), + &zone)) + { + /* Start resolution in GNS */ + ilh = GNUNET_new(struct InterceptLookupHandle); + GNUNET_CONTAINER_DLL_insert(ilh_head, + ilh_tail, + ilh); + ilh->packet = p; + ilh->request_handle = rh; + ilh->lookup = GNS_resolver_lookup(&zone, + p->queries[0].type, + p->queries[0].name, + GNUNET_NO, + &reply_to_dns, ilh); + return; + } /* This request does not concern us. Forward to real DNS. */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Request for `%s' is forwarded to DNS untouched.\n", - p->queries[0].name); - GNUNET_DNS_request_forward (rh); - GNUNET_DNSPARSER_free_packet (p); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Request for `%s' is forwarded to DNS untouched.\n", + p->queries[0].name); + GNUNET_DNS_request_forward(rh); + GNUNET_DNSPARSER_free_packet(p); } @@ -352,20 +357,20 @@ handle_dns_request (void *cls, * @return #GNUNET_OK on success */ int -GNS_interceptor_init (const struct GNUNET_CONFIGURATION_Handle *c) +GNS_interceptor_init(const struct GNUNET_CONFIGURATION_Handle *c) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "DNS hijacking enabled. Connecting to DNS service.\n"); - dns_handle = GNUNET_DNS_connect (c, - GNUNET_DNS_FLAG_PRE_RESOLUTION, - &handle_dns_request, - NULL); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "DNS hijacking enabled. Connecting to DNS service.\n"); + dns_handle = GNUNET_DNS_connect(c, + GNUNET_DNS_FLAG_PRE_RESOLUTION, + &handle_dns_request, + NULL); if (NULL == dns_handle) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect to the DNS service!\n")); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to the DNS service!\n")); + return GNUNET_SYSERR; + } return GNUNET_YES; } @@ -374,25 +379,25 @@ GNS_interceptor_init (const struct GNUNET_CONFIGURATION_Handle *c) * Disconnect from interceptor */ void -GNS_interceptor_done () +GNS_interceptor_done() { struct InterceptLookupHandle *ilh; while (NULL != (ilh = ilh_head)) - { - GNUNET_CONTAINER_DLL_remove (ilh_head, - ilh_tail, - ilh); - GNS_resolver_lookup_cancel (ilh->lookup); - GNUNET_DNS_request_drop (ilh->request_handle); - GNUNET_DNSPARSER_free_packet (ilh->packet); - GNUNET_free (ilh); - } + { + GNUNET_CONTAINER_DLL_remove(ilh_head, + ilh_tail, + ilh); + GNS_resolver_lookup_cancel(ilh->lookup); + GNUNET_DNS_request_drop(ilh->request_handle); + GNUNET_DNSPARSER_free_packet(ilh->packet); + GNUNET_free(ilh); + } if (NULL != dns_handle) - { - GNUNET_DNS_disconnect (dns_handle); - dns_handle = NULL; - } + { + GNUNET_DNS_disconnect(dns_handle); + dns_handle = NULL; + } } /* end of gnunet-service-gns_interceptor.c */ diff --git a/src/gns/gnunet-service-gns_interceptor.h b/src/gns/gnunet-service-gns_interceptor.h index 095448db2..10e1acab6 100644 --- a/src/gns/gnunet-service-gns_interceptor.h +++ b/src/gns/gnunet-service-gns_interceptor.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/gnunet-service-gns_interceptor.h * @brief GNUnet GNS service @@ -35,12 +35,12 @@ * @return #GNUNET_YES on success #GNUNET_SYSERR on error */ int -GNS_interceptor_init (const struct GNUNET_CONFIGURATION_Handle *c); +GNS_interceptor_init(const struct GNUNET_CONFIGURATION_Handle *c); /** * Stops the interceptor */ void -GNS_interceptor_done (void); +GNS_interceptor_done(void); #endif diff --git a/src/gns/gnunet-service-gns_resolver.c b/src/gns/gnunet-service-gns_resolver.c index 703a0f652..da54f3dd5 100644 --- a/src/gns/gnunet-service-gns_resolver.c +++ b/src/gns/gnunet-service-gns_resolver.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/gnunet-service-gns_resolver.c @@ -45,17 +45,17 @@ /** * Default DHT timeout for lookups. */ -#define DHT_LOOKUP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60) +#define DHT_LOOKUP_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60) /** * Default timeout for DNS lookups. */ -#define DNS_LOOKUP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15) +#define DNS_LOOKUP_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15) /** * Default timeout for VPN redirections. */ -#define VPN_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 30) +#define VPN_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 30) /** * DHT replication level @@ -80,9 +80,7 @@ struct AuthorityChain; * responsible DNS server hostname in a GNS2DNS recursive * resolution. */ -struct Gns2DnsPending -{ - +struct Gns2DnsPending { /** * Kept in a DLL. */ @@ -128,8 +126,7 @@ struct GNS_ResolverHandle; * DLL to hold the authority chain we had to pass in the resolution * process. */ -struct AuthorityChain -{ +struct AuthorityChain { /** * This is a DLL. */ @@ -159,16 +156,13 @@ struct AuthorityChain /** * Information about the resolver authority for this label. */ - union - { - + union { /** * The zone of the GNS authority */ struct GNUNET_CRYPTO_EcdsaPublicKey gns_authority; - struct - { + struct { /** * Domain of the DNS resolver that is the authority. * (appended to construct the DNS name to resolve; @@ -203,20 +197,15 @@ struct AuthorityChain * Did we start the recursive resolution via DNS? */ int launched; - } dns_authority; - } authority_info; - }; /** * A result we got from DNS. */ -struct DnsResult -{ - +struct DnsResult { /** * Kept in DLL. */ @@ -247,16 +236,13 @@ struct DnsResult * Type of the GNS/DNS record. */ uint32_t record_type; - }; /** * Closure for #vpn_allocation_cb. */ -struct VpnContext -{ - +struct VpnContext { /** * Which resolution process are we processing. */ @@ -288,9 +274,7 @@ struct VpnContext * Handle to a currenty pending resolution. On result (positive or * negative) the #GNS_ResultProcessor is called. */ -struct GNS_ResolverHandle -{ - +struct GNS_ResolverHandle { /** * DLL */ @@ -426,16 +410,13 @@ struct GNS_ResolverHandle * 16 bit random ID we used in the @e dns_request. */ uint16_t original_dns_id; - }; /** * Active namestore caching operations. */ -struct CacheOps -{ - +struct CacheOps { /** * Organized in a DLL. */ @@ -450,7 +431,6 @@ struct CacheOps * Pending Namestore caching task. */ struct GNUNET_NAMECACHE_QueueEntry *namecache_qe_cache; - }; @@ -526,19 +506,19 @@ static const struct GNUNET_CONFIGURATION_Handle *cfg; * @return #GNUNET_YES if canonical */ /* dead, but keep for now */ int -is_canonical (const char *name) +is_canonical(const char *name) { const char *pos; const char *dot; - if (NULL == strchr (name, - (unsigned char) '.')) + if (NULL == strchr(name, + (unsigned char)'.')) return GNUNET_YES; if ('_' != name[0]) return GNUNET_NO; pos = &name[1]; - while (NULL != (dot = strchr (pos, - (unsigned char) '.'))) + while (NULL != (dot = strchr(pos, + (unsigned char)'.'))) if ('_' != dot[1]) return GNUNET_NO; else @@ -556,22 +536,22 @@ is_canonical (const char *name) * @return updated name */ static char * -translate_dot_plus (struct GNS_ResolverHandle *rh, - char *name) +translate_dot_plus(struct GNS_ResolverHandle *rh, + char *name) { char *ret; - size_t s_len = strlen (name); + size_t s_len = strlen(name); - if (0 != strcmp (&name[s_len - 2], - ".+")) + if (0 != strcmp(&name[s_len - 2], + ".+")) return name; /* did not end in ".+" */ - GNUNET_assert (GNUNET_YES == rh->ac_tail->gns_authority); - GNUNET_asprintf (&ret, - "%.*s.%s", - (int) (s_len - 2), - name, - GNUNET_GNSRECORD_pkey_to_zkey (&rh->ac_tail->authority_info.gns_authority)); - GNUNET_free (name); + GNUNET_assert(GNUNET_YES == rh->ac_tail->gns_authority); + GNUNET_asprintf(&ret, + "%.*s.%s", + (int)(s_len - 2), + name, + GNUNET_GNSRECORD_pkey_to_zkey(&rh->ac_tail->authority_info.gns_authority)); + GNUNET_free(name); return ret; } @@ -583,12 +563,12 @@ translate_dot_plus (struct GNS_ResolverHandle *rh, * @param cls the `struct GNS_ResolverHandle` */ static void -GNS_resolver_lookup_cancel_ (void *cls) +GNS_resolver_lookup_cancel_(void *cls) { struct GNS_ResolverHandle *rh = cls; rh->task_id = NULL; - GNS_resolver_lookup_cancel (rh); + GNS_resolver_lookup_cancel(rh); } @@ -598,14 +578,14 @@ GNS_resolver_lookup_cancel_ (void *cls) * @param rh the resolution to fail */ static void -fail_resolution (struct GNS_ResolverHandle *rh) +fail_resolution(struct GNS_ResolverHandle *rh) { - rh->proc (rh->proc_cls, - 0, - NULL); - GNUNET_assert (NULL == rh->task_id); - rh->task_id = GNUNET_SCHEDULER_add_now (&GNS_resolver_lookup_cancel_, - rh); + rh->proc(rh->proc_cls, + 0, + NULL); + GNUNET_assert(NULL == rh->task_id); + rh->task_id = GNUNET_SCHEDULER_add_now(&GNS_resolver_lookup_cancel_, + rh); } @@ -615,12 +595,12 @@ fail_resolution (struct GNS_ResolverHandle *rh) * @param cls the `struct GNS_ResolverHandle` */ static void -timeout_resolution (void *cls) +timeout_resolution(void *cls) { struct GNS_ResolverHandle *rh = cls; rh->task_id = NULL; - fail_resolution (rh); + fail_resolution(rh); } @@ -642,7 +622,7 @@ timeout_resolution (void *cls) * @return NULL if there are no more labels */ static char * -resolver_lookup_get_next_label (struct GNS_ResolverHandle *rh) +resolver_lookup_get_next_label(struct GNS_ResolverHandle *rh) { const char *rp; const char *dot; @@ -655,71 +635,71 @@ resolver_lookup_get_next_label (struct GNS_ResolverHandle *rh) if (0 == rh->name_resolution_pos) return NULL; - dot = memrchr (rh->name, - (int) '.', - rh->name_resolution_pos); + dot = memrchr(rh->name, + (int)'.', + rh->name_resolution_pos); if (NULL == dot) - { - /* done, this was the last one */ - len = rh->name_resolution_pos; - rp = rh->name; - rh->name_resolution_pos = 0; - } + { + /* done, this was the last one */ + len = rh->name_resolution_pos; + rp = rh->name; + rh->name_resolution_pos = 0; + } else - { - /* advance by one label */ - len = rh->name_resolution_pos - (dot - rh->name) - 1; - rp = dot + 1; - rh->name_resolution_pos = dot - rh->name; - } + { + /* advance by one label */ + len = rh->name_resolution_pos - (dot - rh->name) - 1; + rp = dot + 1; + rh->name_resolution_pos = dot - rh->name; + } rh->protocol = 0; rh->service = 0; - ret = GNUNET_strndup (rp, len); + ret = GNUNET_strndup(rp, len); /* If we have labels starting with underscore with label on * the right (SRV/DANE/BOX case), determine port/protocol; * The format of `rh->name` must be "_PORT._PROTOCOL". */ - if ( ('_' == rh->name[0]) && - (NULL != (dot = memrchr (rh->name, - (int) '.', - rh->name_resolution_pos))) && - ('_' == dot[1]) && - (NULL == memrchr (rh->name, - (int) '.', - dot - rh->name)) ) - { - srv_name = GNUNET_strndup (&rh->name[1], - (dot - rh->name) - 1); - proto_name = GNUNET_strndup (&dot[2], - rh->name_resolution_pos - (dot - rh->name) - 1); - rh->name_resolution_pos = 0; - pe = getprotobyname (proto_name); - if (NULL == pe) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Protocol `%s' unknown, skipping labels.\n"), - proto_name); - GNUNET_free (proto_name); - GNUNET_free (srv_name); - return ret; - } - se = getservbyname (srv_name, - proto_name); - if (NULL == se) + if (('_' == rh->name[0]) && + (NULL != (dot = memrchr(rh->name, + (int)'.', + rh->name_resolution_pos))) && + ('_' == dot[1]) && + (NULL == memrchr(rh->name, + (int)'.', + dot - rh->name))) { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Service `%s' unknown for protocol `%s', skipping labels.\n"), - srv_name, - proto_name); - GNUNET_free (proto_name); - GNUNET_free (srv_name); - return ret; + srv_name = GNUNET_strndup(&rh->name[1], + (dot - rh->name) - 1); + proto_name = GNUNET_strndup(&dot[2], + rh->name_resolution_pos - (dot - rh->name) - 1); + rh->name_resolution_pos = 0; + pe = getprotobyname(proto_name); + if (NULL == pe) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Protocol `%s' unknown, skipping labels.\n"), + proto_name); + GNUNET_free(proto_name); + GNUNET_free(srv_name); + return ret; + } + se = getservbyname(srv_name, + proto_name); + if (NULL == se) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Service `%s' unknown for protocol `%s', skipping labels.\n"), + srv_name, + proto_name); + GNUNET_free(proto_name); + GNUNET_free(srv_name); + return ret; + } + rh->protocol = pe->p_proto; + rh->service = se->s_port; + GNUNET_free(proto_name); + GNUNET_free(srv_name); } - rh->protocol = pe->p_proto; - rh->service = se->s_port; - GNUNET_free (proto_name); - GNUNET_free (srv_name); - } return ret; } @@ -730,7 +710,7 @@ resolver_lookup_get_next_label (struct GNS_ResolverHandle *rh) * @param rh resolution process that has culminated in a result */ static void -transmit_lookup_dns_result (struct GNS_ResolverHandle *rh) +transmit_lookup_dns_result(struct GNS_ResolverHandle *rh) { struct DnsResult *pos; unsigned int n; @@ -744,31 +724,31 @@ transmit_lookup_dns_result (struct GNS_ResolverHandle *rh) i = 0; for (pos = rh->dns_result_head; NULL != pos; pos = pos->next) - { - rd[i].data = pos->data; - rd[i].data_size = pos->data_size; - rd[i].record_type = pos->record_type; - if (0 == pos->expiration_time) - { - rd[i].flags = GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION; - rd[i].expiration_time = 0; - } - else { - rd[i].flags = GNUNET_GNSRECORD_RF_NONE; - rd[i].expiration_time = pos->expiration_time; + rd[i].data = pos->data; + rd[i].data_size = pos->data_size; + rd[i].record_type = pos->record_type; + if (0 == pos->expiration_time) + { + rd[i].flags = GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION; + rd[i].expiration_time = 0; + } + else + { + rd[i].flags = GNUNET_GNSRECORD_RF_NONE; + rd[i].expiration_time = pos->expiration_time; + } + i++; } - i++; - } - GNUNET_assert (i == n); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Transmitting standard DNS result with %u records\n", - n); - rh->proc (rh->proc_cls, - n, - rd); + GNUNET_assert(i == n); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Transmitting standard DNS result with %u records\n", + n); + rh->proc(rh->proc_cls, + n, + rd); } - GNS_resolver_lookup_cancel (rh); + GNS_resolver_lookup_cancel(rh); } @@ -782,25 +762,25 @@ transmit_lookup_dns_result (struct GNS_ResolverHandle *rh) * @param data binary data to return in DNS record */ static void -add_dns_result (struct GNS_ResolverHandle *rh, - uint64_t expiration_time, - uint32_t record_type, - size_t data_size, - const void *data) +add_dns_result(struct GNS_ResolverHandle *rh, + uint64_t expiration_time, + uint32_t record_type, + size_t data_size, + const void *data) { struct DnsResult *res; - res = GNUNET_malloc (sizeof (struct DnsResult) + data_size); + res = GNUNET_malloc(sizeof(struct DnsResult) + data_size); res->expiration_time = expiration_time; res->data_size = data_size; res->record_type = record_type; res->data = &res[1]; - GNUNET_memcpy (&res[1], - data, - data_size); - GNUNET_CONTAINER_DLL_insert (rh->dns_result_head, - rh->dns_result_tail, - res); + GNUNET_memcpy(&res[1], + data, + data_size); + GNUNET_CONTAINER_DLL_insert(rh->dns_result_head, + rh->dns_result_tail, + res); } @@ -813,45 +793,47 @@ add_dns_result (struct GNS_ResolverHandle *rh, * @param addrlen length of the address */ static void -handle_dns_result (void *cls, - const struct sockaddr *addr, - socklen_t addrlen) +handle_dns_result(void *cls, + const struct sockaddr *addr, + socklen_t addrlen) { struct GNS_ResolverHandle *rh = cls; const struct sockaddr_in *sa4; const struct sockaddr_in6 *sa6; if (NULL == addr) - { - rh->std_resolve = NULL; - transmit_lookup_dns_result (rh); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received %u bytes of DNS IP data\n", - addrlen); + { + rh->std_resolve = NULL; + transmit_lookup_dns_result(rh); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received %u bytes of DNS IP data\n", + addrlen); switch (addr->sa_family) - { - case AF_INET: - sa4 = (const struct sockaddr_in *) addr; - add_dns_result (rh, - 0 /* expiration time is unknown */, - GNUNET_DNSPARSER_TYPE_A, - sizeof (struct in_addr), - &sa4->sin_addr); - break; - case AF_INET6: - sa6 = (const struct sockaddr_in6 *) addr; - add_dns_result (rh, - 0 /* expiration time is unknown */, - GNUNET_DNSPARSER_TYPE_AAAA, - sizeof (struct in6_addr), - &sa6->sin6_addr); - break; - default: - GNUNET_break (0); - break; - } + { + case AF_INET: + sa4 = (const struct sockaddr_in *)addr; + add_dns_result(rh, + 0 /* expiration time is unknown */, + GNUNET_DNSPARSER_TYPE_A, + sizeof(struct in_addr), + &sa4->sin_addr); + break; + + case AF_INET6: + sa6 = (const struct sockaddr_in6 *)addr; + add_dns_result(rh, + 0 /* expiration time is unknown */, + GNUNET_DNSPARSER_TYPE_AAAA, + sizeof(struct in6_addr), + &sa6->sin6_addr); + break; + + default: + GNUNET_break(0); + break; + } } @@ -862,7 +844,7 @@ handle_dns_result (void *cls, * @param tc task context */ static void -recursive_resolution (void *cls); +recursive_resolution(void *cls); /** @@ -872,7 +854,7 @@ recursive_resolution (void *cls); * @param cls closure with `struct GNS_ResolverHandle *rh` */ static void -start_resolver_lookup (void *cls); +start_resolver_lookup(void *cls); /** @@ -884,9 +866,9 @@ start_resolver_lookup (void *cls); * @param dns_len number of bytes in @a dns */ static void -dns_result_parser (void *cls, - const struct GNUNET_TUN_DnsHeader *dns, - size_t dns_len) +dns_result_parser(void *cls, + const struct GNUNET_TUN_DnsHeader *dns, + size_t dns_len) { struct GNS_ResolverHandle *rh = cls; struct GNUNET_DNSPARSER_Packet *p; @@ -894,80 +876,82 @@ dns_result_parser (void *cls, unsigned int rd_count; if (NULL == dns) - { - rh->dns_request = NULL; - GNUNET_SCHEDULER_cancel (rh->task_id); - rh->task_id = NULL; - fail_resolution (rh); - return; - } + { + rh->dns_request = NULL; + GNUNET_SCHEDULER_cancel(rh->task_id); + rh->task_id = NULL; + fail_resolution(rh); + return; + } if (rh->original_dns_id != dns->id) - { - /* DNS answer, but for another query */ - return; - } - p = GNUNET_DNSPARSER_parse ((const char *) dns, - dns_len); + { + /* DNS answer, but for another query */ + return; + } + p = GNUNET_DNSPARSER_parse((const char *)dns, + dns_len); if (NULL == p) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed to parse DNS response\n")); - return; - } - - /* We got a result from DNS */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received DNS response for `%s' with %u answers\n", - rh->ac_tail->label, - (unsigned int) p->num_answers); - if ( (p->num_answers > 0) && - (GNUNET_DNSPARSER_TYPE_CNAME == p->answers[0].type) && - (GNUNET_DNSPARSER_TYPE_CNAME != rh->record_type) ) - { - int af; - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Got CNAME `%s' from DNS for `%s'\n", - p->answers[0].data.hostname, - rh->name); - if (NULL != rh->std_resolve) { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Multiple CNAME results from DNS resolving `%s'! Not really allowed...\n", - rh->name); - GNUNET_RESOLVER_request_cancel (rh->std_resolve); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to parse DNS response\n")); + return; } - GNUNET_free (rh->name); - rh->name = GNUNET_strdup (p->answers[0].data.hostname); - rh->name_resolution_pos = strlen (rh->name); - switch (rh->record_type) + + /* We got a result from DNS */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received DNS response for `%s' with %u answers\n", + rh->ac_tail->label, + (unsigned int)p->num_answers); + if ((p->num_answers > 0) && + (GNUNET_DNSPARSER_TYPE_CNAME == p->answers[0].type) && + (GNUNET_DNSPARSER_TYPE_CNAME != rh->record_type)) { - case GNUNET_DNSPARSER_TYPE_A: - af = AF_INET; - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - af = AF_INET6; - break; - default: - af = AF_UNSPEC; - break; + int af; + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Got CNAME `%s' from DNS for `%s'\n", + p->answers[0].data.hostname, + rh->name); + if (NULL != rh->std_resolve) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Multiple CNAME results from DNS resolving `%s'! Not really allowed...\n", + rh->name); + GNUNET_RESOLVER_request_cancel(rh->std_resolve); + } + GNUNET_free(rh->name); + rh->name = GNUNET_strdup(p->answers[0].data.hostname); + rh->name_resolution_pos = strlen(rh->name); + switch (rh->record_type) + { + case GNUNET_DNSPARSER_TYPE_A: + af = AF_INET; + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + af = AF_INET6; + break; + + default: + af = AF_UNSPEC; + break; + } + if (NULL != rh->leho) + add_dns_result(rh, + GNUNET_TIME_UNIT_HOURS.rel_value_us, + GNUNET_GNSRECORD_TYPE_LEHO, + strlen(rh->leho), + rh->leho); + rh->std_resolve = GNUNET_RESOLVER_ip_get(rh->name, + af, + DNS_LOOKUP_TIMEOUT, + &handle_dns_result, + rh); + GNUNET_DNSPARSER_free_packet(p); + GNUNET_DNSSTUB_resolve_cancel(rh->dns_request); + rh->dns_request = NULL; + return; } - if (NULL != rh->leho) - add_dns_result (rh, - GNUNET_TIME_UNIT_HOURS.rel_value_us, - GNUNET_GNSRECORD_TYPE_LEHO, - strlen (rh->leho), - rh->leho); - rh->std_resolve = GNUNET_RESOLVER_ip_get (rh->name, - af, - DNS_LOOKUP_TIMEOUT, - &handle_dns_result, - rh); - GNUNET_DNSPARSER_free_packet (p); - GNUNET_DNSSTUB_resolve_cancel (rh->dns_request); - rh->dns_request = NULL; - return; - } /* convert from (parsed) DNS to (binary) GNS format! */ rd_count = p->num_answers + p->num_authority_records + p->num_additional_records; @@ -980,151 +964,157 @@ dns_result_parser (void *cls, buf_off = 0; skip = 0; - memset (rd, - 0, - sizeof (rd)); - for (unsigned int i=0;inum_answers) - rec = &p->answers[i]; - else if (i < p->num_answers + p->num_authority_records) - rec = &p->authority_records[i - p->num_answers]; - else - rec = &p->additional_records[i - p->num_answers - p->num_authority_records]; - /* As we copied the full DNS name to 'rh->ac_tail->label', this - should be the correct check to see if this record is actually - a record for our label... */ - if (0 != strcmp (rec->name, - rh->ac_tail->label)) + memset(rd, + 0, + sizeof(rd)); + for (unsigned int i = 0; i < rd_count; i++) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Dropping record `%s', does not match desired name `%s'\n", - rec->name, - rh->ac_tail->label); - skip++; - continue; - } - rd[i - skip].record_type = rec->type; - rd[i - skip].expiration_time = rec->expiration_time.abs_value_us; - switch (rec->type) + if (i < p->num_answers) + rec = &p->answers[i]; + else if (i < p->num_answers + p->num_authority_records) + rec = &p->authority_records[i - p->num_answers]; + else + rec = &p->additional_records[i - p->num_answers - p->num_authority_records]; + /* As we copied the full DNS name to 'rh->ac_tail->label', this + should be the correct check to see if this record is actually + a record for our label... */ + if (0 != strcmp(rec->name, + rh->ac_tail->label)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Dropping record `%s', does not match desired name `%s'\n", + rec->name, + rh->ac_tail->label); + skip++; + continue; + } + rd[i - skip].record_type = rec->type; + rd[i - skip].expiration_time = rec->expiration_time.abs_value_us; + switch (rec->type) + { + case GNUNET_DNSPARSER_TYPE_A: + if (rec->data.raw.data_len != sizeof(struct in_addr)) + { + GNUNET_break_op(0); + skip++; + continue; + } + rd[i - skip].data_size = rec->data.raw.data_len; + rd[i - skip].data = rec->data.raw.data; + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + if (rec->data.raw.data_len != sizeof(struct in6_addr)) + { + GNUNET_break_op(0); + skip++; + continue; + } + rd[i - skip].data_size = rec->data.raw.data_len; + rd[i - skip].data = rec->data.raw.data; + break; + + case GNUNET_DNSPARSER_TYPE_CNAME: + case GNUNET_DNSPARSER_TYPE_PTR: + case GNUNET_DNSPARSER_TYPE_NS: + buf_start = buf_off; + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_name(buf, + sizeof(buf), + &buf_off, + rec->data.hostname)) + { + GNUNET_break(0); + skip++; + continue; + } + rd[i - skip].data_size = buf_off - buf_start; + rd[i - skip].data = &buf[buf_start]; + break; + + case GNUNET_DNSPARSER_TYPE_SOA: + buf_start = buf_off; + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_soa(buf, + sizeof(buf), + &buf_off, + rec->data.soa)) + { + GNUNET_break(0); + skip++; + continue; + } + rd[i - skip].data_size = buf_off - buf_start; + rd[i - skip].data = &buf[buf_start]; + break; + + case GNUNET_DNSPARSER_TYPE_MX: + buf_start = buf_off; + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_mx(buf, + sizeof(buf), + &buf_off, + rec->data.mx)) + { + GNUNET_break(0); + skip++; + continue; + } + rd[i - skip].data_size = buf_off - buf_start; + rd[i - skip].data = &buf[buf_start]; + break; + + case GNUNET_DNSPARSER_TYPE_SRV: + buf_start = buf_off; + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_srv(buf, + sizeof(buf), + &buf_off, + rec->data.srv)) + { + GNUNET_break(0); + skip++; + continue; + } + rd[i - skip].data_size = buf_off - buf_start; + rd[i - skip].data = &buf[buf_start]; + break; + + default: + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Skipping record of unsupported type %d\n"), + rec->type); + skip++; + continue; + } + } /* end of for all records in answer */ + if (NULL != rh->leho) { - case GNUNET_DNSPARSER_TYPE_A: - if (rec->data.raw.data_len != sizeof (struct in_addr)) - { - GNUNET_break_op (0); - skip++; - continue; - } - rd[i - skip].data_size = rec->data.raw.data_len; - rd[i - skip].data = rec->data.raw.data; - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - if (rec->data.raw.data_len != sizeof (struct in6_addr)) - { - GNUNET_break_op (0); - skip++; - continue; - } - rd[i - skip].data_size = rec->data.raw.data_len; - rd[i - skip].data = rec->data.raw.data; - break; - case GNUNET_DNSPARSER_TYPE_CNAME: - case GNUNET_DNSPARSER_TYPE_PTR: - case GNUNET_DNSPARSER_TYPE_NS: - buf_start = buf_off; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_name (buf, - sizeof (buf), - &buf_off, - rec->data.hostname)) - { - GNUNET_break (0); - skip++; - continue; - } - rd[i - skip].data_size = buf_off - buf_start; - rd[i - skip].data = &buf[buf_start]; - break; - case GNUNET_DNSPARSER_TYPE_SOA: - buf_start = buf_off; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_soa (buf, - sizeof (buf), - &buf_off, - rec->data.soa)) - { - GNUNET_break (0); - skip++; - continue; - } - rd[i - skip].data_size = buf_off - buf_start; - rd[i - skip].data = &buf[buf_start]; - break; - case GNUNET_DNSPARSER_TYPE_MX: - buf_start = buf_off; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_mx (buf, - sizeof (buf), - &buf_off, - rec->data.mx)) - { - GNUNET_break (0); - skip++; - continue; - } - rd[i - skip].data_size = buf_off - buf_start; - rd[i - skip].data = &buf[buf_start]; - break; - case GNUNET_DNSPARSER_TYPE_SRV: - buf_start = buf_off; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_srv (buf, - sizeof (buf), - &buf_off, - rec->data.srv)) - { - GNUNET_break (0); - skip++; - continue; - } - rd[i - skip].data_size = buf_off - buf_start; - rd[i - skip].data = &buf[buf_start]; - break; - default: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Skipping record of unsupported type %d\n"), - rec->type); - skip++; - continue; + rd[rd_count - skip].record_type = GNUNET_GNSRECORD_TYPE_LEHO; + rd[rd_count - skip].flags = GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION; + rd[rd_count - skip].expiration_time = GNUNET_TIME_UNIT_HOURS.rel_value_us; + rd[rd_count - skip].data = rh->leho; + rd[rd_count - skip].data_size = strlen(rh->leho); + skip--; /* skip one LESS */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding LEHO %s\n", + rh->leho); } - } /* end of for all records in answer */ - if (NULL != rh->leho) - { - rd[rd_count - skip].record_type = GNUNET_GNSRECORD_TYPE_LEHO; - rd[rd_count - skip].flags = GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION; - rd[rd_count - skip].expiration_time = GNUNET_TIME_UNIT_HOURS.rel_value_us; - rd[rd_count - skip].data = rh->leho; - rd[rd_count - skip].data_size = strlen (rh->leho); - skip--; /* skip one LESS */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding LEHO %s\n", - rh->leho); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Returning DNS response for `%s' with %u answers\n", - rh->ac_tail->label, - (unsigned int) (rd_count - skip)); - rh->proc (rh->proc_cls, - rd_count - skip, - rd); - GNUNET_DNSSTUB_resolve_cancel (rh->dns_request); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Returning DNS response for `%s' with %u answers\n", + rh->ac_tail->label, + (unsigned int)(rd_count - skip)); + rh->proc(rh->proc_cls, + rd_count - skip, + rd); + GNUNET_DNSSTUB_resolve_cancel(rh->dns_request); rh->dns_request = NULL; } - GNUNET_DNSPARSER_free_packet (p); + GNUNET_DNSPARSER_free_packet(p); if (NULL != rh->task_id) - GNUNET_SCHEDULER_cancel (rh->task_id); /* should be timeout task */ - rh->task_id = GNUNET_SCHEDULER_add_now (&GNS_resolver_lookup_cancel_, - rh); + GNUNET_SCHEDULER_cancel(rh->task_id); /* should be timeout task */ + rh->task_id = GNUNET_SCHEDULER_add_now(&GNS_resolver_lookup_cancel_, + rh); } @@ -1137,7 +1127,7 @@ dns_result_parser (void *cls, * @param rh resolution information */ static void -recursive_dns_resolution (struct GNS_ResolverHandle *rh) +recursive_dns_resolution(struct GNS_ResolverHandle *rh) { struct AuthorityChain *ac; struct GNUNET_DNSPARSER_Query *query; @@ -1147,54 +1137,54 @@ recursive_dns_resolution (struct GNS_ResolverHandle *rh) int ret; ac = rh->ac_tail; - GNUNET_assert (NULL != ac); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting DNS lookup for `%s'\n", - ac->label); - GNUNET_assert (GNUNET_NO == ac->gns_authority); - query = GNUNET_new (struct GNUNET_DNSPARSER_Query); - query->name = GNUNET_strdup (ac->label); + GNUNET_assert(NULL != ac); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting DNS lookup for `%s'\n", + ac->label); + GNUNET_assert(GNUNET_NO == ac->gns_authority); + query = GNUNET_new(struct GNUNET_DNSPARSER_Query); + query->name = GNUNET_strdup(ac->label); query->type = rh->record_type; query->dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; - p = GNUNET_new (struct GNUNET_DNSPARSER_Packet); + p = GNUNET_new(struct GNUNET_DNSPARSER_Packet); p->queries = query; p->num_queries = 1; - p->id = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, - UINT16_MAX); + p->id = (uint16_t)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, + UINT16_MAX); p->flags.opcode = GNUNET_TUN_DNS_OPCODE_QUERY; p->flags.recursion_desired = 1; - ret = GNUNET_DNSPARSER_pack (p, - 1024, - &dns_request, - &dns_request_length); + ret = GNUNET_DNSPARSER_pack(p, + 1024, + &dns_request, + &dns_request_length); if (GNUNET_OK != ret) - { - GNUNET_break (0); - rh->proc (rh->proc_cls, - 0, - NULL); - GNUNET_assert (NULL == rh->task_id); - rh->task_id = GNUNET_SCHEDULER_add_now (&GNS_resolver_lookup_cancel_, - rh); - } + { + GNUNET_break(0); + rh->proc(rh->proc_cls, + 0, + NULL); + GNUNET_assert(NULL == rh->task_id); + rh->task_id = GNUNET_SCHEDULER_add_now(&GNS_resolver_lookup_cancel_, + rh); + } else - { - rh->original_dns_id = p->id; - GNUNET_assert (NULL != ac->authority_info.dns_authority.dns_handle); - GNUNET_assert (NULL == rh->dns_request); - rh->leho = GNUNET_strdup (ac->label); - rh->dns_request = GNUNET_DNSSTUB_resolve (ac->authority_info.dns_authority.dns_handle, - dns_request, - dns_request_length, - &dns_result_parser, - rh); - rh->task_id = GNUNET_SCHEDULER_add_delayed (DNS_LOOKUP_TIMEOUT, - &timeout_resolution, - rh); - } + { + rh->original_dns_id = p->id; + GNUNET_assert(NULL != ac->authority_info.dns_authority.dns_handle); + GNUNET_assert(NULL == rh->dns_request); + rh->leho = GNUNET_strdup(ac->label); + rh->dns_request = GNUNET_DNSSTUB_resolve(ac->authority_info.dns_authority.dns_handle, + dns_request, + dns_request_length, + &dns_result_parser, + rh); + rh->task_id = GNUNET_SCHEDULER_add_delayed(DNS_LOOKUP_TIMEOUT, + &timeout_resolution, + rh); + } if (GNUNET_SYSERR != ret) - GNUNET_free (dns_request); - GNUNET_DNSPARSER_free_packet (p); + GNUNET_free(dns_request); + GNUNET_DNSPARSER_free_packet(p); } @@ -1207,85 +1197,87 @@ recursive_dns_resolution (struct GNS_ResolverHandle *rh) * authority chain tail */ static void -handle_gns_cname_result (struct GNS_ResolverHandle *rh, - const char *cname) +handle_gns_cname_result(struct GNS_ResolverHandle *rh, + const char *cname) { size_t nlen; char *res; struct AuthorityChain *ac; int af; - nlen = strlen (cname); - if ( (nlen > 2) && - (0 == strcmp (".+", - &cname[nlen - 2])) ) - { - /* CNAME resolution continues relative to current domain */ - if (0 == rh->name_resolution_pos) + nlen = strlen(cname); + if ((nlen > 2) && + (0 == strcmp(".+", + &cname[nlen - 2]))) { - res = GNUNET_strndup (cname, nlen - 2); - rh->name_resolution_pos = nlen - 2; + /* CNAME resolution continues relative to current domain */ + if (0 == rh->name_resolution_pos) + { + res = GNUNET_strndup(cname, nlen - 2); + rh->name_resolution_pos = nlen - 2; + } + else + { + GNUNET_asprintf(&res, + "%.*s.%.*s", + (int)rh->name_resolution_pos, + rh->name, + (int)(nlen - 2), + cname); + rh->name_resolution_pos = strlen(res); + } + GNUNET_free(rh->name); + rh->name = res; + ac = GNUNET_new(struct AuthorityChain); + ac->rh = rh; + ac->gns_authority = GNUNET_YES; + ac->authority_info.gns_authority = rh->ac_tail->authority_info.gns_authority; + ac->label = resolver_lookup_get_next_label(rh); + /* add AC to tail */ + GNUNET_CONTAINER_DLL_insert_tail(rh->ac_head, + rh->ac_tail, + ac); + rh->task_id = GNUNET_SCHEDULER_add_now(&recursive_resolution, + rh); + return; } - else + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Got CNAME `%s' from GNS for `%s'\n", + cname, + rh->name); + if (NULL != rh->std_resolve) { - GNUNET_asprintf (&res, - "%.*s.%.*s", - (int) rh->name_resolution_pos, - rh->name, - (int) (nlen - 2), - cname); - rh->name_resolution_pos = strlen (res); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Multiple CNAME results from GNS resolving `%s'! Not really allowed...\n", + rh->name); + GNUNET_RESOLVER_request_cancel(rh->std_resolve); } - GNUNET_free (rh->name); - rh->name = res; - ac = GNUNET_new (struct AuthorityChain); - ac->rh = rh; - ac->gns_authority = GNUNET_YES; - ac->authority_info.gns_authority = rh->ac_tail->authority_info.gns_authority; - ac->label = resolver_lookup_get_next_label (rh); - /* add AC to tail */ - GNUNET_CONTAINER_DLL_insert_tail (rh->ac_head, - rh->ac_tail, - ac); - rh->task_id = GNUNET_SCHEDULER_add_now (&recursive_resolution, - rh); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Got CNAME `%s' from GNS for `%s'\n", - cname, - rh->name); - if (NULL != rh->std_resolve) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Multiple CNAME results from GNS resolving `%s'! Not really allowed...\n", - rh->name); - GNUNET_RESOLVER_request_cancel (rh->std_resolve); - } /* name is absolute, go to DNS */ - GNUNET_free (rh->name); - rh->name = GNUNET_strdup (cname); - rh->name_resolution_pos = strlen (rh->name); + GNUNET_free(rh->name); + rh->name = GNUNET_strdup(cname); + rh->name_resolution_pos = strlen(rh->name); switch (rh->record_type) - { - case GNUNET_DNSPARSER_TYPE_A: - af = AF_INET; - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - af = AF_INET6; - break; - default: - af = AF_UNSPEC; - break; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Doing standard DNS lookup for `%s'\n", - rh->name); - rh->std_resolve = GNUNET_RESOLVER_ip_get (rh->name, - af, - DNS_LOOKUP_TIMEOUT, - &handle_dns_result, - rh); + { + case GNUNET_DNSPARSER_TYPE_A: + af = AF_INET; + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + af = AF_INET6; + break; + + default: + af = AF_UNSPEC; + break; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Doing standard DNS lookup for `%s'\n", + rh->name); + rh->std_resolve = GNUNET_RESOLVER_ip_get(rh->name, + af, + DNS_LOOKUP_TIMEOUT, + &handle_dns_result, + rh); } @@ -1297,9 +1289,9 @@ handle_gns_cname_result (struct GNS_ResolverHandle *rh, * @param rd array of records with data to store */ static void -handle_gns_resolution_result (void *cls, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd); +handle_gns_resolution_result(void *cls, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd); /** @@ -1317,9 +1309,9 @@ handle_gns_resolution_result (void *cls, * specified target peer; NULL on error */ static void -vpn_allocation_cb (void *cls, - int af, - const void *address) +vpn_allocation_cb(void *cls, + int af, + const void *address) { struct VpnContext *vpn_ctx = cls; struct GNS_ResolverHandle *rh = vpn_ctx->rh; @@ -1328,47 +1320,49 @@ vpn_allocation_cb (void *cls, vpn_ctx->vpn_request = NULL; rh->vpn_ctx = NULL; - GNUNET_assert (GNUNET_OK == - GNUNET_GNSRECORD_records_deserialize ((size_t) vpn_ctx->rd_data_size, - vpn_ctx->rd_data, - vpn_ctx->rd_count, - rd)); - for (i=0;ird_count;i++) - { - if (GNUNET_GNSRECORD_TYPE_VPN == rd[i].record_type) + GNUNET_assert(GNUNET_OK == + GNUNET_GNSRECORD_records_deserialize((size_t)vpn_ctx->rd_data_size, + vpn_ctx->rd_data, + vpn_ctx->rd_count, + rd)); + for (i = 0; i < vpn_ctx->rd_count; i++) { - switch (af) - { - case AF_INET: - rd[i].record_type = GNUNET_DNSPARSER_TYPE_A; - rd[i].data_size = sizeof (struct in_addr); - rd[i].expiration_time = GNUNET_TIME_relative_to_absolute (VPN_TIMEOUT).abs_value_us; - rd[i].flags = 0; - rd[i].data = address; - break; - case AF_INET6: - rd[i].record_type = GNUNET_DNSPARSER_TYPE_AAAA; - rd[i].expiration_time = GNUNET_TIME_relative_to_absolute (VPN_TIMEOUT).abs_value_us; - rd[i].flags = 0; - rd[i].data = address; - rd[i].data_size = sizeof (struct in6_addr); - break; - default: - GNUNET_assert (0); - } - break; + if (GNUNET_GNSRECORD_TYPE_VPN == rd[i].record_type) + { + switch (af) + { + case AF_INET: + rd[i].record_type = GNUNET_DNSPARSER_TYPE_A; + rd[i].data_size = sizeof(struct in_addr); + rd[i].expiration_time = GNUNET_TIME_relative_to_absolute(VPN_TIMEOUT).abs_value_us; + rd[i].flags = 0; + rd[i].data = address; + break; + + case AF_INET6: + rd[i].record_type = GNUNET_DNSPARSER_TYPE_AAAA; + rd[i].expiration_time = GNUNET_TIME_relative_to_absolute(VPN_TIMEOUT).abs_value_us; + rd[i].flags = 0; + rd[i].data = address; + rd[i].data_size = sizeof(struct in6_addr); + break; + + default: + GNUNET_assert(0); + } + break; + } } - } - GNUNET_assert (i < vpn_ctx->rd_count); + GNUNET_assert(i < vpn_ctx->rd_count); if (0 == vpn_ctx->rd_count) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("VPN returned empty result for `%s'\n"), - rh->name); - handle_gns_resolution_result (rh, - vpn_ctx->rd_count, - rd); - GNUNET_free (vpn_ctx->rd_data); - GNUNET_free (vpn_ctx); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("VPN returned empty result for `%s'\n"), + rh->name); + handle_gns_resolution_result(rh, + vpn_ctx->rd_count, + rd); + GNUNET_free(vpn_ctx->rd_data); + GNUNET_free(vpn_ctx); } @@ -1380,32 +1374,31 @@ vpn_allocation_cb (void *cls, * @param ac context for GNS2DNS resolution */ static void -continue_with_gns2dns (struct AuthorityChain *ac) +continue_with_gns2dns(struct AuthorityChain *ac) { struct GNS_ResolverHandle *rh = ac->rh; - if ( (NULL != ac->authority_info.dns_authority.gp_head) && - (GNUNET_NO == ac->authority_info.dns_authority.found) ) + if ((NULL != ac->authority_info.dns_authority.gp_head) && + (GNUNET_NO == ac->authority_info.dns_authority.found)) return; /* more pending and none found yet */ if (GNUNET_NO == ac->authority_info.dns_authority.found) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Failed to resolve DNS server for `%s' in GNS2DNS resolution\n", - ac->authority_info.dns_authority.name); - fail_resolution (rh); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Failed to resolve DNS server for `%s' in GNS2DNS resolution\n", + ac->authority_info.dns_authority.name); + fail_resolution(rh); + return; + } if (GNUNET_NO != ac->authority_info.dns_authority.launched) return; /* already running, do not launch again! */ /* recurse */ ac->authority_info.dns_authority.launched = GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Will continue resolution using DNS to resolve `%s'\n", - ac->label); - GNUNET_assert (NULL == rh->task_id); - rh->task_id = GNUNET_SCHEDULER_add_now (&recursive_resolution, - rh); - + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Will continue resolution using DNS to resolve `%s'\n", + ac->label); + GNUNET_assert(NULL == rh->task_id); + rh->task_id = GNUNET_SCHEDULER_add_now(&recursive_resolution, + rh); } @@ -1418,93 +1411,95 @@ continue_with_gns2dns (struct AuthorityChain *ac) * @param rd addresses for the DNS resolver (presumably) */ static void -handle_gns2dns_result (void *cls, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +handle_gns2dns_result(void *cls, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct Gns2DnsPending *gp = cls; struct AuthorityChain *ac = gp->ac; - GNUNET_CONTAINER_DLL_remove (ac->authority_info.dns_authority.gp_head, - ac->authority_info.dns_authority.gp_tail, - gp); + GNUNET_CONTAINER_DLL_remove(ac->authority_info.dns_authority.gp_head, + ac->authority_info.dns_authority.gp_tail, + gp); /* enable cleanup of 'rh' handle that automatically comes after we return, and which expects 'rh' to be in the #rlh_head DLL. */ if (NULL != gp->rh) - { - GNUNET_CONTAINER_DLL_insert (rlh_head, - rlh_tail, - gp->rh); - gp->rh = NULL; - } - GNUNET_free (gp); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received %u results for IP address of DNS server for GNS2DNS transition\n", - rd_count); + { + GNUNET_CONTAINER_DLL_insert(rlh_head, + rlh_tail, + gp->rh); + gp->rh = NULL; + } + GNUNET_free(gp); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received %u results for IP address of DNS server for GNS2DNS transition\n", + rd_count); /* find suitable A/AAAA record */ - for (unsigned int j=0;jauthority_info.dns_authority.dns_handle, - (const struct sockaddr *) &v4)) - ac->authority_info.dns_authority.found = GNUNET_YES; - break; - } - case GNUNET_DNSPARSER_TYPE_AAAA: - { - struct sockaddr_in6 v6; + GNUNET_memcpy(&v4.sin_addr, + rd[j].data, + sizeof(struct in_addr)); + if (GNUNET_OK == + GNUNET_DNSSTUB_add_dns_sa(ac->authority_info.dns_authority.dns_handle, + (const struct sockaddr *)&v4)) + ac->authority_info.dns_authority.found = GNUNET_YES; + break; + } - if (sizeof (struct in6_addr) != rd[j].data_size) + case GNUNET_DNSPARSER_TYPE_AAAA: { - GNUNET_break_op (0); - continue; - } - /* FIXME: might want to check if we support IPv6 here, - and otherwise skip this one and hope we find another */ - memset (&v6, - 0, - sizeof (v6)); - v6.sin6_family = AF_INET6; - v6.sin6_port = htons (53); + struct sockaddr_in6 v6; + + if (sizeof(struct in6_addr) != rd[j].data_size) + { + GNUNET_break_op(0); + continue; + } + /* FIXME: might want to check if we support IPv6 here, + and otherwise skip this one and hope we find another */ + memset(&v6, + 0, + sizeof(v6)); + v6.sin6_family = AF_INET6; + v6.sin6_port = htons(53); #if HAVE_SOCKADDR_IN_SIN_LEN - v6.sin6_len = (u_char) sizeof (v6); + v6.sin6_len = (u_char)sizeof(v6); #endif - GNUNET_memcpy (&v6.sin6_addr, - rd[j].data, - sizeof (struct in6_addr)); - if (GNUNET_OK == - GNUNET_DNSSTUB_add_dns_sa (ac->authority_info.dns_authority.dns_handle, - (const struct sockaddr *) &v6)) - ac->authority_info.dns_authority.found = GNUNET_YES; - break; - } - default: - break; + GNUNET_memcpy(&v6.sin6_addr, + rd[j].data, + sizeof(struct in6_addr)); + if (GNUNET_OK == + GNUNET_DNSSTUB_add_dns_sa(ac->authority_info.dns_authority.dns_handle, + (const struct sockaddr *)&v6)) + ac->authority_info.dns_authority.found = GNUNET_YES; + break; + } + + default: + break; + } } - } - continue_with_gns2dns (ac); + continue_with_gns2dns(ac); } @@ -1516,9 +1511,9 @@ handle_gns2dns_result (void *cls, * @param addrlen length of @a addr */ static void -handle_gns2dns_ip (void *cls, - const struct sockaddr *addr, - socklen_t addrlen) +handle_gns2dns_ip(void *cls, + const struct sockaddr *addr, + socklen_t addrlen) { struct Gns2DnsPending *gp = cls; struct AuthorityChain *ac = gp->ac; @@ -1527,42 +1522,44 @@ handle_gns2dns_ip (void *cls, struct sockaddr_in6 *v6; if (NULL == addr) - { - /* DNS resolution finished */ - if (0 == gp->num_results) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Failed to use DNS to resolve name of DNS resolver\n"); - GNUNET_CONTAINER_DLL_remove (ac->authority_info.dns_authority.gp_head, - ac->authority_info.dns_authority.gp_tail, - gp); - GNUNET_free (gp); - continue_with_gns2dns (ac); - return; - } - GNUNET_memcpy (&ss, - addr, - addrlen); + { + /* DNS resolution finished */ + if (0 == gp->num_results) + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Failed to use DNS to resolve name of DNS resolver\n"); + GNUNET_CONTAINER_DLL_remove(ac->authority_info.dns_authority.gp_head, + ac->authority_info.dns_authority.gp_tail, + gp); + GNUNET_free(gp); + continue_with_gns2dns(ac); + return; + } + GNUNET_memcpy(&ss, + addr, + addrlen); switch (ss.ss_family) - { - case AF_INET: - v4 = (struct sockaddr_in *) &ss; - v4->sin_port = htons (53); - gp->num_results++; - break; - case AF_INET6: - v6 = (struct sockaddr_in6 *) &ss; - v6->sin6_port = htons (53); - gp->num_results++; - break; - default: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unsupported AF %d\n", - ss.ss_family); - return; - } + { + case AF_INET: + v4 = (struct sockaddr_in *)&ss; + v4->sin_port = htons(53); + gp->num_results++; + break; + + case AF_INET6: + v6 = (struct sockaddr_in6 *)&ss; + v6->sin6_port = htons(53); + gp->num_results++; + break; + + default: + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unsupported AF %d\n", + ss.ss_family); + return; + } if (GNUNET_OK == - GNUNET_DNSSTUB_add_dns_sa (ac->authority_info.dns_authority.dns_handle, - (struct sockaddr *) &ss)) + GNUNET_DNSSTUB_add_dns_sa(ac->authority_info.dns_authority.dns_handle, + (struct sockaddr *)&ss)) ac->authority_info.dns_authority.found = GNUNET_YES; } @@ -1574,27 +1571,27 @@ handle_gns2dns_ip (void *cls, * @param rd record with CNAME to resolve recursively */ static void -recursive_cname_resolution (struct GNS_ResolverHandle *rh, - const struct GNUNET_GNSRECORD_Data *rd) +recursive_cname_resolution(struct GNS_ResolverHandle *rh, + const struct GNUNET_GNSRECORD_Data *rd) { char *cname; size_t off; off = 0; - cname = GNUNET_DNSPARSER_parse_name (rd->data, - rd->data_size, - &off); - if ( (NULL == cname) || - (off != rd->data_size) ) - { - GNUNET_break_op (0); /* record not well-formed */ - GNUNET_free_non_null (cname); - fail_resolution (rh); - return; - } - handle_gns_cname_result (rh, - cname); - GNUNET_free (cname); + cname = GNUNET_DNSPARSER_parse_name(rd->data, + rd->data_size, + &off); + if ((NULL == cname) || + (off != rd->data_size)) + { + GNUNET_break_op(0); /* record not well-formed */ + GNUNET_free_non_null(cname); + fail_resolution(rh); + return; + } + handle_gns_cname_result(rh, + cname); + GNUNET_free(cname); } @@ -1605,34 +1602,34 @@ recursive_cname_resolution (struct GNS_ResolverHandle *rh, * @param rd record with PKEY to resolve recursively */ static void -recursive_pkey_resolution (struct GNS_ResolverHandle *rh, - const struct GNUNET_GNSRECORD_Data *rd) +recursive_pkey_resolution(struct GNS_ResolverHandle *rh, + const struct GNUNET_GNSRECORD_Data *rd) { struct AuthorityChain *ac; /* delegation to another zone */ - if (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) != + if (sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) != rd->data_size) - { - GNUNET_break_op (0); - fail_resolution (rh); - return; - } + { + GNUNET_break_op(0); + fail_resolution(rh); + return; + } /* expand authority chain */ - ac = GNUNET_new (struct AuthorityChain); + ac = GNUNET_new(struct AuthorityChain); ac->rh = rh; ac->gns_authority = GNUNET_YES; - GNUNET_memcpy (&ac->authority_info.gns_authority, - rd->data, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)); - ac->label = resolver_lookup_get_next_label (rh); + GNUNET_memcpy(&ac->authority_info.gns_authority, + rd->data, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey)); + ac->label = resolver_lookup_get_next_label(rh); /* add AC to tail */ - GNUNET_CONTAINER_DLL_insert_tail (rh->ac_head, - rh->ac_tail, - ac); + GNUNET_CONTAINER_DLL_insert_tail(rh->ac_head, + rh->ac_tail, + ac); /* recurse */ - rh->task_id = GNUNET_SCHEDULER_add_now (&recursive_resolution, - rh); + rh->task_id = GNUNET_SCHEDULER_add_now(&recursive_resolution, + rh); } @@ -1647,9 +1644,9 @@ recursive_pkey_resolution (struct GNS_ResolverHandle *rh, * @return #GNUNET_OK if this worked, #GNUNET_SYSERR if no GNS2DNS records were in @a rd */ static int -recursive_gns2dns_resolution (struct GNS_ResolverHandle *rh, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +recursive_gns2dns_resolution(struct GNS_ResolverHandle *rh, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct AuthorityChain *ac; const char *tld; @@ -1657,157 +1654,157 @@ recursive_gns2dns_resolution (struct GNS_ResolverHandle *rh, ns = NULL; /* expand authority chain */ - ac = GNUNET_new (struct AuthorityChain); + ac = GNUNET_new(struct AuthorityChain); ac->rh = rh; - ac->authority_info.dns_authority.dns_handle = GNUNET_DNSSTUB_start (4); + ac->authority_info.dns_authority.dns_handle = GNUNET_DNSSTUB_start(4); - for (unsigned int i=0;iauthority_info.dns_authority.dns_handle, - ip)); - ac->authority_info.dns_authority.found = GNUNET_YES; - GNUNET_free (ip); - continue; - } - tld = GNS_get_tld (ip); - if (0 != strcmp (tld, - "+")) - { - /* 'ip' is a DNS name */ - gp = GNUNET_new (struct Gns2DnsPending); + &v6))) + { + GNUNET_break(GNUNET_OK == + GNUNET_DNSSTUB_add_dns_ip(ac->authority_info.dns_authority.dns_handle, + ip)); + ac->authority_info.dns_authority.found = GNUNET_YES; + GNUNET_free(ip); + continue; + } + tld = GNS_get_tld(ip); + if (0 != strcmp(tld, + "+")) + { + /* 'ip' is a DNS name */ + gp = GNUNET_new(struct Gns2DnsPending); + gp->ac = ac; + GNUNET_CONTAINER_DLL_insert(ac->authority_info.dns_authority.gp_head, + ac->authority_info.dns_authority.gp_tail, + gp); + gp->dns_rh = GNUNET_RESOLVER_ip_get(ip, + AF_UNSPEC, + GNUNET_TIME_UNIT_FOREVER_REL, + &handle_gns2dns_ip, + gp); + GNUNET_free(ip); + continue; + } + /* 'ip' should be a GNS name */ + gp = GNUNET_new(struct Gns2DnsPending); gp->ac = ac; - GNUNET_CONTAINER_DLL_insert (ac->authority_info.dns_authority.gp_head, - ac->authority_info.dns_authority.gp_tail, - gp); - gp->dns_rh = GNUNET_RESOLVER_ip_get (ip, - AF_UNSPEC, - GNUNET_TIME_UNIT_FOREVER_REL, - &handle_gns2dns_ip, - gp); - GNUNET_free (ip); - continue; - } - /* 'ip' should be a GNS name */ - gp = GNUNET_new (struct Gns2DnsPending); - gp->ac = ac; - GNUNET_CONTAINER_DLL_insert (ac->authority_info.dns_authority.gp_head, - ac->authority_info.dns_authority.gp_tail, - gp); - gp->rh = GNUNET_new (struct GNS_ResolverHandle); - ip = translate_dot_plus (rh, - ip); - tld = GNS_get_tld (ip); - if (GNUNET_OK != - GNUNET_GNSRECORD_zkey_to_pkey (tld, - &zone)) - { - GNUNET_break_op (0); - GNUNET_free (ip); - continue; - } - gp->rh->authority_zone = zone; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Resolving `%s' to determine IP address of DNS server for GNS2DNS transition for `%s'\n", - ip, - ns); - gp->rh->name = ip; - gp->rh->name_resolution_pos = strlen (ip) - strlen (tld) - 1; - gp->rh->proc = &handle_gns2dns_result; - gp->rh->proc_cls = gp; - gp->rh->record_type = GNUNET_GNSRECORD_TYPE_ANY; - gp->rh->options = GNUNET_GNS_LO_DEFAULT; - gp->rh->loop_limiter = rh->loop_limiter + 1; - gp->rh->task_id - = GNUNET_SCHEDULER_add_now (&start_resolver_lookup, - gp->rh); - } /* end 'for all records' */ + GNUNET_CONTAINER_DLL_insert(ac->authority_info.dns_authority.gp_head, + ac->authority_info.dns_authority.gp_tail, + gp); + gp->rh = GNUNET_new(struct GNS_ResolverHandle); + ip = translate_dot_plus(rh, + ip); + tld = GNS_get_tld(ip); + if (GNUNET_OK != + GNUNET_GNSRECORD_zkey_to_pkey(tld, + &zone)) + { + GNUNET_break_op(0); + GNUNET_free(ip); + continue; + } + gp->rh->authority_zone = zone; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Resolving `%s' to determine IP address of DNS server for GNS2DNS transition for `%s'\n", + ip, + ns); + gp->rh->name = ip; + gp->rh->name_resolution_pos = strlen(ip) - strlen(tld) - 1; + gp->rh->proc = &handle_gns2dns_result; + gp->rh->proc_cls = gp; + gp->rh->record_type = GNUNET_GNSRECORD_TYPE_ANY; + gp->rh->options = GNUNET_GNS_LO_DEFAULT; + gp->rh->loop_limiter = rh->loop_limiter + 1; + gp->rh->task_id + = GNUNET_SCHEDULER_add_now(&start_resolver_lookup, + gp->rh); + } /* end 'for all records' */ if (NULL == ns) - { - /* not a single GNS2DNS record found */ - GNUNET_free (ac); - return GNUNET_SYSERR; - } - GNUNET_assert (strlen (ns) <= GNUNET_DNSPARSER_MAX_NAME_LENGTH); - strcpy (ac->authority_info.dns_authority.name, - ns); + { + /* not a single GNS2DNS record found */ + GNUNET_free(ac); + return GNUNET_SYSERR; + } + GNUNET_assert(strlen(ns) <= GNUNET_DNSPARSER_MAX_NAME_LENGTH); + strcpy(ac->authority_info.dns_authority.name, + ns); /* for DNS recursion, the label is the full DNS name, created from the remainder of the GNS name and the name in the NS record */ - GNUNET_asprintf (&ac->label, - "%.*s%s%s", - (int) rh->name_resolution_pos, - rh->name, - (0 != rh->name_resolution_pos) ? "." : "", - ns); - GNUNET_free (ns); - GNUNET_CONTAINER_DLL_insert_tail (rh->ac_head, - rh->ac_tail, - ac); - if (strlen (ac->label) > GNUNET_DNSPARSER_MAX_NAME_LENGTH) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("GNS lookup resulted in DNS name that is too long (`%s')\n"), - ac->label); - return GNUNET_SYSERR; - } - continue_with_gns2dns (ac); + GNUNET_asprintf(&ac->label, + "%.*s%s%s", + (int)rh->name_resolution_pos, + rh->name, + (0 != rh->name_resolution_pos) ? "." : "", + ns); + GNUNET_free(ns); + GNUNET_CONTAINER_DLL_insert_tail(rh->ac_head, + rh->ac_tail, + ac); + if (strlen(ac->label) > GNUNET_DNSPARSER_MAX_NAME_LENGTH) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("GNS lookup resulted in DNS name that is too long (`%s')\n"), + ac->label); + return GNUNET_SYSERR; + } + continue_with_gns2dns(ac); return GNUNET_OK; } @@ -1820,9 +1817,9 @@ recursive_gns2dns_resolution (struct GNS_ResolverHandle *rh, * @param rd array of records with data to store */ static void -handle_gns_resolution_result (void *cls, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +handle_gns_resolution_result(void *cls, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNS_ResolverHandle *rh = cls; char *cname; @@ -1838,431 +1835,442 @@ handle_gns_resolution_result (void *cls, struct GNUNET_GNSRECORD_Data rd_new[rd_count]; unsigned int rd_off; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Resolution succeeded for `%s' in zone %s, got %u records\n", - rh->ac_tail->label, - GNUNET_GNSRECORD_z2s (&rh->ac_tail->authority_info.gns_authority), - rd_count); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Resolution succeeded for `%s' in zone %s, got %u records\n", + rh->ac_tail->label, + GNUNET_GNSRECORD_z2s(&rh->ac_tail->authority_info.gns_authority), + rd_count); if (0 == rd_count) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("GNS lookup failed (zero records found for `%s')\n"), - rh->name); - fail_resolution (rh); - return; - } - - if (0 == rh->name_resolution_pos) - { - /* top-level match, are we done yet? */ - if ( (rd_count > 0) && - (GNUNET_DNSPARSER_TYPE_CNAME == rd[0].record_type) && - (GNUNET_DNSPARSER_TYPE_CNAME != rh->record_type) ) { - off = 0; - cname = GNUNET_DNSPARSER_parse_name (rd[0].data, - rd[0].data_size, - &off); - if ( (NULL == cname) || - (off != rd[0].data_size) ) - { - GNUNET_break_op (0); - GNUNET_free_non_null (cname); - fail_resolution (rh); - return; - } - handle_gns_cname_result (rh, - cname); - GNUNET_free (cname); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("GNS lookup failed (zero records found for `%s')\n"), + rh->name); + fail_resolution(rh); return; } - /* If A/AAAA was requested, but we got a VPN - record, we convert it to A/AAAA using GNUnet VPN */ - if ( (GNUNET_DNSPARSER_TYPE_A == rh->record_type) || - (GNUNET_DNSPARSER_TYPE_AAAA == rh->record_type) ) + + if (0 == rh->name_resolution_pos) { - for (unsigned int i=0;irecord_type) ? AF_INET : AF_INET6; - if (sizeof (struct GNUNET_TUN_GnsVpnRecord) > - rd[i].data_size) - { - GNUNET_break_op (0); - fail_resolution (rh); - return; - } - vpn = (const struct GNUNET_TUN_GnsVpnRecord *) rd[i].data; - vname = (const char *) &vpn[1]; - if ('\0' != vname[rd[i].data_size - 1 - sizeof (struct GNUNET_TUN_GnsVpnRecord)]) - { - GNUNET_break_op (0); - fail_resolution (rh); - return; - } - GNUNET_TUN_service_name_to_hash (vname, - &vhash); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Attempting VPN allocation for %s-%s (AF: %d, proto %d)\n", - GNUNET_i2s (&vpn->peer), - vname, - (int) af, - (int) ntohs (vpn->proto)); - vpn_ctx = GNUNET_new (struct VpnContext); - rh->vpn_ctx = vpn_ctx; - vpn_ctx->rh = rh; - vpn_ctx->rd_data_size = GNUNET_GNSRECORD_records_get_size (rd_count, - rd); - if (vpn_ctx->rd_data_size < 0) + /* top-level match, are we done yet? */ + if ((rd_count > 0) && + (GNUNET_DNSPARSER_TYPE_CNAME == rd[0].record_type) && + (GNUNET_DNSPARSER_TYPE_CNAME != rh->record_type)) + { + off = 0; + cname = GNUNET_DNSPARSER_parse_name(rd[0].data, + rd[0].data_size, + &off); + if ((NULL == cname) || + (off != rd[0].data_size)) { - GNUNET_break_op (0); - GNUNET_free (vpn_ctx); - fail_resolution (rh); - return; - } - vpn_ctx->rd_data = GNUNET_malloc ((size_t) vpn_ctx->rd_data_size); - vpn_ctx->rd_count = rd_count; - GNUNET_assert (vpn_ctx->rd_data_size == - GNUNET_GNSRECORD_records_serialize (rd_count, - rd, - (size_t) vpn_ctx->rd_data_size, - vpn_ctx->rd_data)); - vpn_ctx->vpn_request = GNUNET_VPN_redirect_to_peer (vpn_handle, - af, - ntohs (vpn->proto), - &vpn->peer, - &vhash, - GNUNET_TIME_relative_to_absolute (VPN_TIMEOUT), - &vpn_allocation_cb, - vpn_ctx); - return; - } - case GNUNET_GNSRECORD_TYPE_GNS2DNS: - { - /* delegation to DNS */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found GNS2DNS record, delegating to DNS!\n"); - if (GNUNET_OK == - recursive_gns2dns_resolution (rh, - rd_count, - rd)) + GNUNET_break_op(0); + GNUNET_free_non_null(cname); + fail_resolution(rh); return; - else - goto fail; - } - default: - break; - } /* end: switch */ - } /* end: for rd */ - } /* end: name_resolution_pos */ - /* convert relative names in record values to absolute names, - using 'scratch' array for memory allocations */ - scratch_off = 0; - rd_off = 0; - for (unsigned int i=0;iprotocol) && - (0 != rh->service) && - (GNUNET_GNSRECORD_TYPE_BOX != rd[i].record_type) ) - continue; /* we _only_ care about boxed records */ - - GNUNET_assert (rd_off < rd_count); - rd_new[rd_off] = rd[i]; - /* Check if the embedded name(s) end in "+", and if so, - replace the "+" with the zone at "ac_tail", changing the name - to a ".ZONEKEY". The name is allocated on the 'scratch' array, - so we can free it afterwards. */ - switch (rd[i].record_type) - { - case GNUNET_DNSPARSER_TYPE_CNAME: - { - char *cname; - - off = 0; - cname = GNUNET_DNSPARSER_parse_name (rd[i].data, - rd[i].data_size, - &off); - if ( (NULL == cname) || - (off != rd[i].data_size) ) - { - GNUNET_break_op (0); /* record not well-formed */ - } - else - { - cname = translate_dot_plus (rh, cname); - GNUNET_break (NULL != cname); - scratch_start = scratch_off; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_name (scratch, - sizeof (scratch), - &scratch_off, - cname)) - { - GNUNET_break (0); - } - else - { - GNUNET_assert (rd_off < rd_count); - rd_new[rd_off].data = &scratch[scratch_start]; - rd_new[rd_off].data_size = scratch_off - scratch_start; - rd_off++; - } - } - GNUNET_free_non_null (cname); - } - break; - case GNUNET_DNSPARSER_TYPE_SOA: - { - struct GNUNET_DNSPARSER_SoaRecord *soa; - - off = 0; - soa = GNUNET_DNSPARSER_parse_soa (rd[i].data, - rd[i].data_size, - &off); - if ( (NULL == soa) || - (off != rd[i].data_size) ) - { - GNUNET_break_op (0); /* record not well-formed */ - } - else - { - soa->mname = translate_dot_plus (rh, soa->mname); - soa->rname = translate_dot_plus (rh, soa->rname); - scratch_start = scratch_off; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_soa (scratch, - sizeof (scratch), - &scratch_off, - soa)) - { - GNUNET_break (0); - } - else - { - GNUNET_assert (rd_off < rd_count); - rd_new[rd_off].data = &scratch[scratch_start]; - rd_new[rd_off].data_size = scratch_off - scratch_start; - rd_off++; - } - } - if (NULL != soa) - GNUNET_DNSPARSER_free_soa (soa); - } - break; - case GNUNET_DNSPARSER_TYPE_MX: - { - struct GNUNET_DNSPARSER_MxRecord *mx; - - off = 0; - mx = GNUNET_DNSPARSER_parse_mx (rd[i].data, - rd[i].data_size, - &off); - if ( (NULL == mx) || - (off != rd[i].data_size) ) - { - GNUNET_break_op (0); /* record not well-formed */ - } - else - { - mx->mxhost = translate_dot_plus (rh, mx->mxhost); - scratch_start = scratch_off; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_mx (scratch, - sizeof (scratch), - &scratch_off, - mx)) - { - GNUNET_break (0); - } - else - { - GNUNET_assert (rd_off < rd_count); - rd_new[rd_off].data = &scratch[scratch_start]; - rd_new[rd_off].data_size = scratch_off - scratch_start; - rd_off++; - } - } - if (NULL != mx) - GNUNET_DNSPARSER_free_mx (mx); - } - break; - case GNUNET_DNSPARSER_TYPE_SRV: - { - struct GNUNET_DNSPARSER_SrvRecord *srv; - - off = 0; - srv = GNUNET_DNSPARSER_parse_srv (rd[i].data, - rd[i].data_size, - &off); - if ( (NULL == srv) || - (off != rd[i].data_size) ) - { - GNUNET_break_op (0); /* record not well-formed */ - } - else - { - srv->target = translate_dot_plus (rh, srv->target); - scratch_start = scratch_off; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_srv (scratch, - sizeof (scratch), - &scratch_off, - srv)) - { - GNUNET_break (0); - } - else - { - GNUNET_assert (rd_off < rd_count); - rd_new[rd_off].data = &scratch[scratch_start]; - rd_new[rd_off].data_size = scratch_off - scratch_start; - rd_off++; - } - } - if (NULL != srv) - GNUNET_DNSPARSER_free_srv (srv); - } - break; - - case GNUNET_GNSRECORD_TYPE_NICK: - { - const char *nick; - - nick = rd[i].data; - if ((rd[i].data_size > 0) && - (nick[rd[i].data_size -1] != '\0')) - { - GNUNET_break_op (0); - break; - } - break; - } - case GNUNET_GNSRECORD_TYPE_PKEY: - { - struct GNUNET_CRYPTO_EcdsaPublicKey pub; - - if (rd[i].data_size != sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)) - { - GNUNET_break_op (0); - break; - } - GNUNET_memcpy (&pub, - rd[i].data, - rd[i].data_size); - rd_off++; - if (GNUNET_GNSRECORD_TYPE_PKEY != rh->record_type) - { - /* try to resolve "@" */ - struct AuthorityChain *ac; - - ac = GNUNET_new (struct AuthorityChain); - ac->rh = rh; - ac->gns_authority = GNUNET_YES; - ac->authority_info.gns_authority = pub; - ac->label = GNUNET_strdup (GNUNET_GNS_EMPTY_LABEL_AT); - GNUNET_CONTAINER_DLL_insert_tail (rh->ac_head, - rh->ac_tail, - ac); - rh->task_id = GNUNET_SCHEDULER_add_now (&recursive_resolution, - rh); - return; - } + } + handle_gns_cname_result(rh, + cname); + GNUNET_free(cname); + return; } - break; - case GNUNET_GNSRECORD_TYPE_GNS2DNS: + /* If A/AAAA was requested, but we got a VPN + record, we convert it to A/AAAA using GNUnet VPN */ + if ((GNUNET_DNSPARSER_TYPE_A == rh->record_type) || + (GNUNET_DNSPARSER_TYPE_AAAA == rh->record_type)) { - /* delegation to DNS */ - if (GNUNET_GNSRECORD_TYPE_GNS2DNS == rh->record_type) - { - rd_off++; - break; /* do not follow to DNS, we wanted the GNS2DNS record! */ - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found GNS2DNS record, delegating to DNS!\n"); - if (GNUNET_OK == - recursive_gns2dns_resolution (rh, - rd_count, - rd)) - return; - else - goto fail; - } - case GNUNET_GNSRECORD_TYPE_BOX: + for (unsigned int i = 0; i < rd_count; i++) + { + switch (rd[i].record_type) + { + case GNUNET_GNSRECORD_TYPE_VPN: + { + af = (GNUNET_DNSPARSER_TYPE_A == rh->record_type) ? AF_INET : AF_INET6; + if (sizeof(struct GNUNET_TUN_GnsVpnRecord) > + rd[i].data_size) + { + GNUNET_break_op(0); + fail_resolution(rh); + return; + } + vpn = (const struct GNUNET_TUN_GnsVpnRecord *)rd[i].data; + vname = (const char *)&vpn[1]; + if ('\0' != vname[rd[i].data_size - 1 - sizeof(struct GNUNET_TUN_GnsVpnRecord)]) + { + GNUNET_break_op(0); + fail_resolution(rh); + return; + } + GNUNET_TUN_service_name_to_hash(vname, + &vhash); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Attempting VPN allocation for %s-%s (AF: %d, proto %d)\n", + GNUNET_i2s(&vpn->peer), + vname, + (int)af, + (int)ntohs(vpn->proto)); + vpn_ctx = GNUNET_new(struct VpnContext); + rh->vpn_ctx = vpn_ctx; + vpn_ctx->rh = rh; + vpn_ctx->rd_data_size = GNUNET_GNSRECORD_records_get_size(rd_count, + rd); + if (vpn_ctx->rd_data_size < 0) + { + GNUNET_break_op(0); + GNUNET_free(vpn_ctx); + fail_resolution(rh); + return; + } + vpn_ctx->rd_data = GNUNET_malloc((size_t)vpn_ctx->rd_data_size); + vpn_ctx->rd_count = rd_count; + GNUNET_assert(vpn_ctx->rd_data_size == + GNUNET_GNSRECORD_records_serialize(rd_count, + rd, + (size_t)vpn_ctx->rd_data_size, + vpn_ctx->rd_data)); + vpn_ctx->vpn_request = GNUNET_VPN_redirect_to_peer(vpn_handle, + af, + ntohs(vpn->proto), + &vpn->peer, + &vhash, + GNUNET_TIME_relative_to_absolute(VPN_TIMEOUT), + &vpn_allocation_cb, + vpn_ctx); + return; + } + + case GNUNET_GNSRECORD_TYPE_GNS2DNS: + { + /* delegation to DNS */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found GNS2DNS record, delegating to DNS!\n"); + if (GNUNET_OK == + recursive_gns2dns_resolution(rh, + rd_count, + rd)) + return; + else + goto fail; + } + + default: + break; + } /* end: switch */ + } /* end: for rd */ + } /* end: name_resolution_pos */ + /* convert relative names in record values to absolute names, + using 'scratch' array for memory allocations */ + scratch_off = 0; + rd_off = 0; + for (unsigned int i = 0; i < rd_count; i++) { - /* unbox SRV/TLSA records if a specific one was requested */ - if ( (0 != rh->protocol) && - (0 != rh->service) && - (rd[i].data_size >= sizeof (struct GNUNET_GNSRECORD_BoxRecord)) ) - { - const struct GNUNET_GNSRECORD_BoxRecord *box; + GNUNET_assert(rd_off <= i); + if ((0 != rh->protocol) && + (0 != rh->service) && + (GNUNET_GNSRECORD_TYPE_BOX != rd[i].record_type)) + continue; /* we _only_ care about boxed records */ + + GNUNET_assert(rd_off < rd_count); + rd_new[rd_off] = rd[i]; + /* Check if the embedded name(s) end in "+", and if so, + replace the "+" with the zone at "ac_tail", changing the name + to a ".ZONEKEY". The name is allocated on the 'scratch' array, + so we can free it afterwards. */ + switch (rd[i].record_type) + { + case GNUNET_DNSPARSER_TYPE_CNAME: + { + char *cname; + + off = 0; + cname = GNUNET_DNSPARSER_parse_name(rd[i].data, + rd[i].data_size, + &off); + if ((NULL == cname) || + (off != rd[i].data_size)) + { + GNUNET_break_op(0); /* record not well-formed */ + } + else + { + cname = translate_dot_plus(rh, cname); + GNUNET_break(NULL != cname); + scratch_start = scratch_off; + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_name(scratch, + sizeof(scratch), + &scratch_off, + cname)) + { + GNUNET_break(0); + } + else + { + GNUNET_assert(rd_off < rd_count); + rd_new[rd_off].data = &scratch[scratch_start]; + rd_new[rd_off].data_size = scratch_off - scratch_start; + rd_off++; + } + } + GNUNET_free_non_null(cname); + } + break; - box = rd[i].data; - if ( (ntohs (box->protocol) == rh->protocol) && - (ntohs (box->service) == rh->service) ) + case GNUNET_DNSPARSER_TYPE_SOA: { - /* Box matches, unbox! */ - GNUNET_assert (rd_off < rd_count); - rd_new[rd_off].record_type = ntohl (box->record_type); - rd_new[rd_off].data_size -= sizeof (struct GNUNET_GNSRECORD_BoxRecord); - rd_new[rd_off].data = &box[1]; + struct GNUNET_DNSPARSER_SoaRecord *soa; + + off = 0; + soa = GNUNET_DNSPARSER_parse_soa(rd[i].data, + rd[i].data_size, + &off); + if ((NULL == soa) || + (off != rd[i].data_size)) + { + GNUNET_break_op(0); /* record not well-formed */ + } + else + { + soa->mname = translate_dot_plus(rh, soa->mname); + soa->rname = translate_dot_plus(rh, soa->rname); + scratch_start = scratch_off; + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_soa(scratch, + sizeof(scratch), + &scratch_off, + soa)) + { + GNUNET_break(0); + } + else + { + GNUNET_assert(rd_off < rd_count); + rd_new[rd_off].data = &scratch[scratch_start]; + rd_new[rd_off].data_size = scratch_off - scratch_start; + rd_off++; + } + } + if (NULL != soa) + GNUNET_DNSPARSER_free_soa(soa); + } + break; + + case GNUNET_DNSPARSER_TYPE_MX: + { + struct GNUNET_DNSPARSER_MxRecord *mx; + + off = 0; + mx = GNUNET_DNSPARSER_parse_mx(rd[i].data, + rd[i].data_size, + &off); + if ((NULL == mx) || + (off != rd[i].data_size)) + { + GNUNET_break_op(0); /* record not well-formed */ + } + else + { + mx->mxhost = translate_dot_plus(rh, mx->mxhost); + scratch_start = scratch_off; + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_mx(scratch, + sizeof(scratch), + &scratch_off, + mx)) + { + GNUNET_break(0); + } + else + { + GNUNET_assert(rd_off < rd_count); + rd_new[rd_off].data = &scratch[scratch_start]; + rd_new[rd_off].data_size = scratch_off - scratch_start; + rd_off++; + } + } + if (NULL != mx) + GNUNET_DNSPARSER_free_mx(mx); + } + break; + + case GNUNET_DNSPARSER_TYPE_SRV: + { + struct GNUNET_DNSPARSER_SrvRecord *srv; + + off = 0; + srv = GNUNET_DNSPARSER_parse_srv(rd[i].data, + rd[i].data_size, + &off); + if ((NULL == srv) || + (off != rd[i].data_size)) + { + GNUNET_break_op(0); /* record not well-formed */ + } + else + { + srv->target = translate_dot_plus(rh, srv->target); + scratch_start = scratch_off; + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_srv(scratch, + sizeof(scratch), + &scratch_off, + srv)) + { + GNUNET_break(0); + } + else + { + GNUNET_assert(rd_off < rd_count); + rd_new[rd_off].data = &scratch[scratch_start]; + rd_new[rd_off].data_size = scratch_off - scratch_start; + rd_off++; + } + } + if (NULL != srv) + GNUNET_DNSPARSER_free_srv(srv); + } + break; + + case GNUNET_GNSRECORD_TYPE_NICK: + { + const char *nick; + + nick = rd[i].data; + if ((rd[i].data_size > 0) && + (nick[rd[i].data_size - 1] != '\0')) + { + GNUNET_break_op(0); + break; + } + break; + } + + case GNUNET_GNSRECORD_TYPE_PKEY: + { + struct GNUNET_CRYPTO_EcdsaPublicKey pub; + + if (rd[i].data_size != sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey)) + { + GNUNET_break_op(0); + break; + } + GNUNET_memcpy(&pub, + rd[i].data, + rd[i].data_size); rd_off++; + if (GNUNET_GNSRECORD_TYPE_PKEY != rh->record_type) + { + /* try to resolve "@" */ + struct AuthorityChain *ac; + + ac = GNUNET_new(struct AuthorityChain); + ac->rh = rh; + ac->gns_authority = GNUNET_YES; + ac->authority_info.gns_authority = pub; + ac->label = GNUNET_strdup(GNUNET_GNS_EMPTY_LABEL_AT); + GNUNET_CONTAINER_DLL_insert_tail(rh->ac_head, + rh->ac_tail, + ac); + rh->task_id = GNUNET_SCHEDULER_add_now(&recursive_resolution, + rh); + return; + } + } + break; + + case GNUNET_GNSRECORD_TYPE_GNS2DNS: + { + /* delegation to DNS */ + if (GNUNET_GNSRECORD_TYPE_GNS2DNS == rh->record_type) + { + rd_off++; + break; /* do not follow to DNS, we wanted the GNS2DNS record! */ + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found GNS2DNS record, delegating to DNS!\n"); + if (GNUNET_OK == + recursive_gns2dns_resolution(rh, + rd_count, + rd)) + return; + else + goto fail; } - } - else - { - /* no specific protocol/service specified, preserve all BOX - records (for modern, GNS-enabled applications) */ - rd_off++; - } - break; - } - default: - rd_off++; - break; - } /* end: switch */ - } /* end: for rd_count */ - - /* yes, we are done, return result */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Returning GNS response for `%s' with %u answers\n", - rh->ac_tail->label, - rd_off); - rh->proc (rh->proc_cls, - rd_off, - rd_new); - rh->task_id = GNUNET_SCHEDULER_add_now (&GNS_resolver_lookup_cancel_, - rh); - return; - } + + case GNUNET_GNSRECORD_TYPE_BOX: + { + /* unbox SRV/TLSA records if a specific one was requested */ + if ((0 != rh->protocol) && + (0 != rh->service) && + (rd[i].data_size >= sizeof(struct GNUNET_GNSRECORD_BoxRecord))) + { + const struct GNUNET_GNSRECORD_BoxRecord *box; + + box = rd[i].data; + if ((ntohs(box->protocol) == rh->protocol) && + (ntohs(box->service) == rh->service)) + { + /* Box matches, unbox! */ + GNUNET_assert(rd_off < rd_count); + rd_new[rd_off].record_type = ntohl(box->record_type); + rd_new[rd_off].data_size -= sizeof(struct GNUNET_GNSRECORD_BoxRecord); + rd_new[rd_off].data = &box[1]; + rd_off++; + } + } + else + { + /* no specific protocol/service specified, preserve all BOX + records (for modern, GNS-enabled applications) */ + rd_off++; + } + break; + } + + default: + rd_off++; + break; + } /* end: switch */ + } /* end: for rd_count */ + + /* yes, we are done, return result */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Returning GNS response for `%s' with %u answers\n", + rh->ac_tail->label, + rd_off); + rh->proc(rh->proc_cls, + rd_off, + rd_new); + rh->task_id = GNUNET_SCHEDULER_add_now(&GNS_resolver_lookup_cancel_, + rh); + return; + } switch (rd[0].record_type) - { - case GNUNET_DNSPARSER_TYPE_CNAME: - GNUNET_break_op (1 == rd_count); /* CNAME should be unique */ - recursive_cname_resolution (rh, + { + case GNUNET_DNSPARSER_TYPE_CNAME: + GNUNET_break_op(1 == rd_count); /* CNAME should be unique */ + recursive_cname_resolution(rh, + &rd[0]); + return; + + case GNUNET_GNSRECORD_TYPE_PKEY: + GNUNET_break_op(1 == rd_count); /* PKEY should be unique */ + recursive_pkey_resolution(rh, &rd[0]); - return; - case GNUNET_GNSRECORD_TYPE_PKEY: - GNUNET_break_op (1 == rd_count); /* PKEY should be unique */ - recursive_pkey_resolution (rh, - &rd[0]); - return; - default: - if (GNUNET_OK == - recursive_gns2dns_resolution (rh, - rd_count, - rd)) return; - break; - } - fail: - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("GNS lookup recursion failed (no delegation record found)\n")); - fail_resolution (rh); + + default: + if (GNUNET_OK == + recursive_gns2dns_resolution(rh, + rd_count, + rd)) + return; + break; + } +fail: + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("GNS lookup recursion failed (no delegation record found)\n")); + fail_resolution(rh); } @@ -2275,21 +2283,21 @@ handle_gns_resolution_result (void *cls, * @param emsg error message */ static void -namecache_cache_continuation (void *cls, - int32_t success, - const char *emsg) +namecache_cache_continuation(void *cls, + int32_t success, + const char *emsg) { struct CacheOps *co = cls; co->namecache_qe_cache = NULL; if (GNUNET_OK != success) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed to cache GNS resolution: %s\n"), - emsg); - GNUNET_CONTAINER_DLL_remove (co_head, - co_tail, - co); - GNUNET_free (co); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to cache GNS resolution: %s\n"), + emsg); + GNUNET_CONTAINER_DLL_remove(co_head, + co_tail, + co); + GNUNET_free(co); } @@ -2311,88 +2319,88 @@ namecache_cache_continuation (void *cls, * @param data pointer to the result data */ static void -handle_dht_response (void *cls, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - enum GNUNET_BLOCK_Type type, - size_t size, - const void *data) +handle_dht_response(void *cls, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + enum GNUNET_BLOCK_Type type, + size_t size, + const void *data) { struct GNS_ResolverHandle *rh = cls; struct AuthorityChain *ac = rh->ac_tail; const struct GNUNET_GNSRECORD_Block *block; struct CacheOps *co; - (void) exp; - (void) key; - (void) get_path; - (void) get_path_length; - (void) put_path; - (void) put_path_length; - (void) type; - GNUNET_DHT_get_stop (rh->get_handle); + (void)exp; + (void)key; + (void)get_path; + (void)get_path_length; + (void)put_path; + (void)put_path_length; + (void)type; + GNUNET_DHT_get_stop(rh->get_handle); rh->get_handle = NULL; - GNUNET_CONTAINER_heap_remove_node (rh->dht_heap_node); + GNUNET_CONTAINER_heap_remove_node(rh->dht_heap_node); rh->dht_heap_node = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Handling response from the DHT\n"); - if (size < sizeof (struct GNUNET_GNSRECORD_Block)) - { - /* how did this pass DHT block validation!? */ - GNUNET_break (0); - fail_resolution (rh); - return; - } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Handling response from the DHT\n"); + if (size < sizeof(struct GNUNET_GNSRECORD_Block)) + { + /* how did this pass DHT block validation!? */ + GNUNET_break(0); + fail_resolution(rh); + return; + } block = data; if (size != - ntohl (block->purpose.size) + - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) + - sizeof (struct GNUNET_CRYPTO_EcdsaSignature)) - { - /* how did this pass DHT block validation!? */ - GNUNET_break (0); - fail_resolution (rh); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Decrypting DHT block of size %u for `%s', expires %s\n", - ntohl (block->purpose.size), - rh->name, - GNUNET_STRINGS_absolute_time_to_string (exp)); + ntohl(block->purpose.size) + + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) + + sizeof(struct GNUNET_CRYPTO_EcdsaSignature)) + { + /* how did this pass DHT block validation!? */ + GNUNET_break(0); + fail_resolution(rh); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Decrypting DHT block of size %u for `%s', expires %s\n", + ntohl(block->purpose.size), + rh->name, + GNUNET_STRINGS_absolute_time_to_string(exp)); if (GNUNET_OK != - GNUNET_GNSRECORD_block_decrypt (block, - &ac->authority_info.gns_authority, - ac->label, - &handle_gns_resolution_result, - rh)) - { - GNUNET_break_op (0); /* block was ill-formed */ - fail_resolution (rh); - return; - } - if (0 == GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (block->expiration_time)).rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received expired block from the DHT, will not cache it.\n"); - return; - } + GNUNET_GNSRECORD_block_decrypt(block, + &ac->authority_info.gns_authority, + ac->label, + &handle_gns_resolution_result, + rh)) + { + GNUNET_break_op(0); /* block was ill-formed */ + fail_resolution(rh); + return; + } + if (0 == GNUNET_TIME_absolute_get_remaining(GNUNET_TIME_absolute_ntoh(block->expiration_time)).rel_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received expired block from the DHT, will not cache it.\n"); + return; + } if (GNUNET_YES == disable_cache) return; /* Cache well-formed blocks */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Caching response from the DHT in namecache\n"); - co = GNUNET_new (struct CacheOps); - co->namecache_qe_cache = GNUNET_NAMECACHE_block_cache (namecache_handle, - block, - &namecache_cache_continuation, - co); - GNUNET_CONTAINER_DLL_insert (co_head, - co_tail, - co); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Caching response from the DHT in namecache\n"); + co = GNUNET_new(struct CacheOps); + co->namecache_qe_cache = GNUNET_NAMECACHE_block_cache(namecache_handle, + block, + &namecache_cache_continuation, + co); + GNUNET_CONTAINER_DLL_insert(co_head, + co_tail, + co); } @@ -2403,30 +2411,30 @@ handle_dht_response (void *cls, * @param query key to use in the DHT lookup */ static void -start_dht_request (struct GNS_ResolverHandle *rh, - const struct GNUNET_HashCode *query) +start_dht_request(struct GNS_ResolverHandle *rh, + const struct GNUNET_HashCode *query) { struct GNS_ResolverHandle *rx; - GNUNET_assert (NULL == rh->get_handle); - rh->get_handle = GNUNET_DHT_get_start (dht_handle, - GNUNET_BLOCK_TYPE_GNS_NAMERECORD, - query, - DHT_GNS_REPLICATION_LEVEL, - GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, - NULL, 0, - &handle_dht_response, rh); - rh->dht_heap_node = GNUNET_CONTAINER_heap_insert (dht_lookup_heap, - rh, - GNUNET_TIME_absolute_get ().abs_value_us); - if (GNUNET_CONTAINER_heap_get_size (dht_lookup_heap) > max_allowed_background_queries) - { - /* fail longest-standing DHT request */ - rx = GNUNET_CONTAINER_heap_remove_root (dht_lookup_heap); - rx->dht_heap_node = NULL; - GNUNET_assert (NULL != rx); - fail_resolution (rx); - } + GNUNET_assert(NULL == rh->get_handle); + rh->get_handle = GNUNET_DHT_get_start(dht_handle, + GNUNET_BLOCK_TYPE_GNS_NAMERECORD, + query, + DHT_GNS_REPLICATION_LEVEL, + GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, + NULL, 0, + &handle_dht_response, rh); + rh->dht_heap_node = GNUNET_CONTAINER_heap_insert(dht_lookup_heap, + rh, + GNUNET_TIME_absolute_get().abs_value_us); + if (GNUNET_CONTAINER_heap_get_size(dht_lookup_heap) > max_allowed_background_queries) + { + /* fail longest-standing DHT request */ + rx = GNUNET_CONTAINER_heap_remove_root(dht_lookup_heap); + rx->dht_heap_node = NULL; + GNUNET_assert(NULL != rx); + fail_resolution(rx); + } } @@ -2439,19 +2447,19 @@ start_dht_request (struct GNS_ResolverHandle *rh, * @param rd array of records with data to store */ static void -handle_gns_namecache_resolution_result (void *cls, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +handle_gns_namecache_resolution_result(void *cls, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNS_ResolverHandle *rh = cls; if (0 == rd_count) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("GNS namecache returned empty result for `%s'\n"), - rh->name); - handle_gns_resolution_result (rh, - rd_count, - rd); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("GNS namecache returned empty result for `%s'\n"), + rh->name); + handle_gns_resolution_result(rh, + rd_count, + rd); } @@ -2462,8 +2470,8 @@ handle_gns_namecache_resolution_result (void *cls, * @param block block that was stored in the namecache */ static void -handle_namecache_block_response (void *cls, - const struct GNUNET_GNSRECORD_Block *block) +handle_namecache_block_response(void *cls, + const struct GNUNET_GNSRECORD_Block *block) { struct GNS_ResolverHandle *rh = cls; struct AuthorityChain *ac = rh->ac_tail; @@ -2471,62 +2479,62 @@ handle_namecache_block_response (void *cls, const struct GNUNET_CRYPTO_EcdsaPublicKey *auth = &ac->authority_info.gns_authority; struct GNUNET_HashCode query; - GNUNET_assert (NULL != rh->namecache_qe); + GNUNET_assert(NULL != rh->namecache_qe); rh->namecache_qe = NULL; - if ( ( (GNUNET_GNS_LO_DEFAULT == rh->options) || - ( (GNUNET_GNS_LO_LOCAL_MASTER == rh->options) && - (ac != rh->ac_head) ) ) && - ( (NULL == block) || - (0 == GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (block->expiration_time)).rel_value_us) ) ) - { - /* namecache knows nothing; try DHT lookup */ - GNUNET_GNSRECORD_query_from_public_key (auth, - label, - &query); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting DHT lookup for `%s' in zone `%s' under key `%s'\n", - ac->label, - GNUNET_GNSRECORD_z2s (&ac->authority_info.gns_authority), - GNUNET_h2s (&query)); - start_dht_request (rh, &query); - return; - } + if (((GNUNET_GNS_LO_DEFAULT == rh->options) || + ((GNUNET_GNS_LO_LOCAL_MASTER == rh->options) && + (ac != rh->ac_head))) && + ((NULL == block) || + (0 == GNUNET_TIME_absolute_get_remaining(GNUNET_TIME_absolute_ntoh(block->expiration_time)).rel_value_us))) + { + /* namecache knows nothing; try DHT lookup */ + GNUNET_GNSRECORD_query_from_public_key(auth, + label, + &query); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting DHT lookup for `%s' in zone `%s' under key `%s'\n", + ac->label, + GNUNET_GNSRECORD_z2s(&ac->authority_info.gns_authority), + GNUNET_h2s(&query)); + start_dht_request(rh, &query); + return; + } - if ( (NULL == block) || - (0 == GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (block->expiration_time)).rel_value_us) ) - { - /* DHT not permitted and no local result, fail */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Resolution failed for `%s' in zone %s (DHT lookup not permitted by configuration)\n", - ac->label, - GNUNET_GNSRECORD_z2s (&ac->authority_info.gns_authority)); - fail_resolution (rh); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received result from namecache for label `%s'\n", - ac->label); + if ((NULL == block) || + (0 == GNUNET_TIME_absolute_get_remaining(GNUNET_TIME_absolute_ntoh(block->expiration_time)).rel_value_us)) + { + /* DHT not permitted and no local result, fail */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Resolution failed for `%s' in zone %s (DHT lookup not permitted by configuration)\n", + ac->label, + GNUNET_GNSRECORD_z2s(&ac->authority_info.gns_authority)); + fail_resolution(rh); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received result from namecache for label `%s'\n", + ac->label); if (GNUNET_OK != - GNUNET_GNSRECORD_block_decrypt (block, - auth, - label, - &handle_gns_namecache_resolution_result, - rh)) - { - GNUNET_break_op (0); /* block was ill-formed */ - /* try DHT instead */ - GNUNET_GNSRECORD_query_from_public_key (auth, - label, - &query); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting DHT lookup for `%s' in zone `%s' under key `%s'\n", - ac->label, - GNUNET_GNSRECORD_z2s (&ac->authority_info.gns_authority), - GNUNET_h2s (&query)); - start_dht_request (rh, &query); - return; - } + GNUNET_GNSRECORD_block_decrypt(block, + auth, + label, + &handle_gns_namecache_resolution_result, + rh)) + { + GNUNET_break_op(0); /* block was ill-formed */ + /* try DHT instead */ + GNUNET_GNSRECORD_query_from_public_key(auth, + label, + &query); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting DHT lookup for `%s' in zone `%s' under key `%s'\n", + ac->label, + GNUNET_GNSRECORD_z2s(&ac->authority_info.gns_authority), + GNUNET_h2s(&query)); + start_dht_request(rh, &query); + return; + } } @@ -2536,32 +2544,32 @@ handle_namecache_block_response (void *cls, * @param rh query we are processing */ static void -recursive_gns_resolution_namecache (struct GNS_ResolverHandle *rh) +recursive_gns_resolution_namecache(struct GNS_ResolverHandle *rh) { struct AuthorityChain *ac = rh->ac_tail; struct GNUNET_HashCode query; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting GNS resolution for `%s' in zone %s\n", - ac->label, - GNUNET_GNSRECORD_z2s (&ac->authority_info.gns_authority)); - GNUNET_GNSRECORD_query_from_public_key (&ac->authority_info.gns_authority, - ac->label, - &query); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting GNS resolution for `%s' in zone %s\n", + ac->label, + GNUNET_GNSRECORD_z2s(&ac->authority_info.gns_authority)); + GNUNET_GNSRECORD_query_from_public_key(&ac->authority_info.gns_authority, + ac->label, + &query); if (GNUNET_YES != disable_cache) - { - rh->namecache_qe - = GNUNET_NAMECACHE_lookup_block (namecache_handle, - &query, - &handle_namecache_block_response, - rh); - GNUNET_assert (NULL != rh->namecache_qe); - } + { + rh->namecache_qe + = GNUNET_NAMECACHE_lookup_block(namecache_handle, + &query, + &handle_namecache_block_response, + rh); + GNUNET_assert(NULL != rh->namecache_qe); + } else - { - start_dht_request (rh, - &query); - } + { + start_dht_request(rh, + &query); + } } @@ -2572,22 +2580,22 @@ recursive_gns_resolution_namecache (struct GNS_ResolverHandle *rh) * @param is_valid #GNUNET_YES if the zone was not yet revoked */ static void -handle_revocation_result (void *cls, - int is_valid) +handle_revocation_result(void *cls, + int is_valid) { struct GNS_ResolverHandle *rh = cls; struct AuthorityChain *ac = rh->ac_tail; rh->rev_check = NULL; if (GNUNET_YES != is_valid) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Zone %s was revoked, resolution fails\n"), - GNUNET_GNSRECORD_z2s (&ac->authority_info.gns_authority)); - fail_resolution (rh); - return; - } - recursive_gns_resolution_namecache (rh); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Zone %s was revoked, resolution fails\n"), + GNUNET_GNSRECORD_z2s(&ac->authority_info.gns_authority)); + fail_resolution(rh); + return; + } + recursive_gns_resolution_namecache(rh); } @@ -2597,18 +2605,18 @@ handle_revocation_result (void *cls, * @param rh query we are processing */ static void -recursive_gns_resolution_revocation (struct GNS_ResolverHandle *rh) +recursive_gns_resolution_revocation(struct GNS_ResolverHandle *rh) { struct AuthorityChain *ac = rh->ac_tail; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting revocation check for zone %s\n", - GNUNET_GNSRECORD_z2s (&ac->authority_info.gns_authority)); - rh->rev_check = GNUNET_REVOCATION_query (cfg, - &ac->authority_info.gns_authority, - &handle_revocation_result, - rh); - GNUNET_assert (NULL != rh->rev_check); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting revocation check for zone %s\n", + GNUNET_GNSRECORD_z2s(&ac->authority_info.gns_authority)); + rh->rev_check = GNUNET_REVOCATION_query(cfg, + &ac->authority_info.gns_authority, + &handle_revocation_result, + rh); + GNUNET_assert(NULL != rh->rev_check); } @@ -2618,23 +2626,23 @@ recursive_gns_resolution_revocation (struct GNS_ResolverHandle *rh) * @param cls the `struct GNS_ResolverHandle` of the resolution */ static void -recursive_resolution (void *cls) +recursive_resolution(void *cls) { struct GNS_ResolverHandle *rh = cls; rh->task_id = NULL; if (MAX_RECURSION < rh->loop_limiter++) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Encountered unbounded recursion resolving `%s'\n", - rh->name); - fail_resolution (rh); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Encountered unbounded recursion resolving `%s'\n", + rh->name); + fail_resolution(rh); + return; + } if (GNUNET_YES == rh->ac_tail->gns_authority) - recursive_gns_resolution_revocation (rh); + recursive_gns_resolution_revocation(rh); else - recursive_dns_resolution (rh); + recursive_dns_resolution(rh); } @@ -2645,7 +2653,7 @@ recursive_resolution (void *cls) * @param cls the `struct GNS_ResolverHandle` */ static void -start_resolver_lookup (void *cls) +start_resolver_lookup(void *cls) { struct GNS_ResolverHandle *rh = cls; struct AuthorityChain *ac; @@ -2653,61 +2661,61 @@ start_resolver_lookup (void *cls) struct in6_addr v6; rh->task_id = NULL; - if (1 == inet_pton (AF_INET, - rh->name, - &v4)) - { - /* name is IPv4 address, pretend it's an A record */ - struct GNUNET_GNSRECORD_Data rd; - - rd.data = &v4; - rd.data_size = sizeof (v4); - rd.expiration_time = UINT64_MAX; - rd.record_type = GNUNET_DNSPARSER_TYPE_A; - rd.flags = 0; - rh->proc (rh->proc_cls, - 1, - &rd); - GNUNET_assert (NULL == rh->task_id); - rh->task_id = GNUNET_SCHEDULER_add_now (&GNS_resolver_lookup_cancel_, - rh); - return; - } - if (1 == inet_pton (AF_INET6, - rh->name, - &v6)) - { - /* name is IPv6 address, pretend it's an AAAA record */ - struct GNUNET_GNSRECORD_Data rd; - - rd.data = &v6; - rd.data_size = sizeof (v6); - rd.expiration_time = UINT64_MAX; - rd.record_type = GNUNET_DNSPARSER_TYPE_AAAA; - rd.flags = 0; - rh->proc (rh->proc_cls, - 1, - &rd); - GNUNET_assert (NULL == rh->task_id); - rh->task_id = GNUNET_SCHEDULER_add_now (&GNS_resolver_lookup_cancel_, - rh); - return; - } + if (1 == inet_pton(AF_INET, + rh->name, + &v4)) + { + /* name is IPv4 address, pretend it's an A record */ + struct GNUNET_GNSRECORD_Data rd; + + rd.data = &v4; + rd.data_size = sizeof(v4); + rd.expiration_time = UINT64_MAX; + rd.record_type = GNUNET_DNSPARSER_TYPE_A; + rd.flags = 0; + rh->proc(rh->proc_cls, + 1, + &rd); + GNUNET_assert(NULL == rh->task_id); + rh->task_id = GNUNET_SCHEDULER_add_now(&GNS_resolver_lookup_cancel_, + rh); + return; + } + if (1 == inet_pton(AF_INET6, + rh->name, + &v6)) + { + /* name is IPv6 address, pretend it's an AAAA record */ + struct GNUNET_GNSRECORD_Data rd; + + rd.data = &v6; + rd.data_size = sizeof(v6); + rd.expiration_time = UINT64_MAX; + rd.record_type = GNUNET_DNSPARSER_TYPE_AAAA; + rd.flags = 0; + rh->proc(rh->proc_cls, + 1, + &rd); + GNUNET_assert(NULL == rh->task_id); + rh->task_id = GNUNET_SCHEDULER_add_now(&GNS_resolver_lookup_cancel_, + rh); + return; + } - ac = GNUNET_new (struct AuthorityChain); + ac = GNUNET_new(struct AuthorityChain); ac->rh = rh; - ac->label = resolver_lookup_get_next_label (rh); + ac->label = resolver_lookup_get_next_label(rh); if (NULL == ac->label) /* name was just the "TLD", so we default to label - #GNUNET_GNS_EMPTY_LABEL_AT */ - ac->label = GNUNET_strdup (GNUNET_GNS_EMPTY_LABEL_AT); + #GNUNET_GNS_EMPTY_LABEL_AT */ + ac->label = GNUNET_strdup(GNUNET_GNS_EMPTY_LABEL_AT); ac->gns_authority = GNUNET_YES; ac->authority_info.gns_authority = rh->authority_zone; - GNUNET_CONTAINER_DLL_insert_tail (rh->ac_head, - rh->ac_tail, - ac); - rh->task_id = GNUNET_SCHEDULER_add_now (&recursive_resolution, - rh); + GNUNET_CONTAINER_DLL_insert_tail(rh->ac_head, + rh->ac_tail, + ac); + rh->task_id = GNUNET_SCHEDULER_add_now(&recursive_resolution, + rh); } @@ -2724,31 +2732,31 @@ start_resolver_lookup (void *cls) * @return handle to cancel operation */ struct GNS_ResolverHandle * -GNS_resolver_lookup (const struct GNUNET_CRYPTO_EcdsaPublicKey *zone, - uint32_t record_type, - const char *name, - enum GNUNET_GNS_LocalOptions options, - GNS_ResultProcessor proc, - void *proc_cls) +GNS_resolver_lookup(const struct GNUNET_CRYPTO_EcdsaPublicKey *zone, + uint32_t record_type, + const char *name, + enum GNUNET_GNS_LocalOptions options, + GNS_ResultProcessor proc, + void *proc_cls) { struct GNS_ResolverHandle *rh; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting lookup for `%s'\n", - name); - rh = GNUNET_new (struct GNS_ResolverHandle); - GNUNET_CONTAINER_DLL_insert (rlh_head, - rlh_tail, - rh); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting lookup for `%s'\n", + name); + rh = GNUNET_new(struct GNS_ResolverHandle); + GNUNET_CONTAINER_DLL_insert(rlh_head, + rlh_tail, + rh); rh->authority_zone = *zone; rh->proc = proc; rh->proc_cls = proc_cls; rh->options = options; rh->record_type = record_type; - rh->name = GNUNET_strdup (name); - rh->name_resolution_pos = strlen (name); - rh->task_id = GNUNET_SCHEDULER_add_now (&start_resolver_lookup, - rh); + rh->name = GNUNET_strdup(name); + rh->name_resolution_pos = strlen(name); + rh->task_id = GNUNET_SCHEDULER_add_now(&start_resolver_lookup, + rh); return rh; } @@ -2759,107 +2767,107 @@ GNS_resolver_lookup (const struct GNUNET_CRYPTO_EcdsaPublicKey *zone, * @param rh resolution to abort */ void -GNS_resolver_lookup_cancel (struct GNS_ResolverHandle *rh) +GNS_resolver_lookup_cancel(struct GNS_ResolverHandle *rh) { struct DnsResult *dr; struct AuthorityChain *ac; struct VpnContext *vpn_ctx; - GNUNET_CONTAINER_DLL_remove (rlh_head, - rlh_tail, - rh); + GNUNET_CONTAINER_DLL_remove(rlh_head, + rlh_tail, + rh); if (NULL != rh->dns_request) - { - GNUNET_DNSSTUB_resolve_cancel (rh->dns_request); - rh->dns_request = NULL; - } + { + GNUNET_DNSSTUB_resolve_cancel(rh->dns_request); + rh->dns_request = NULL; + } while (NULL != (ac = rh->ac_head)) - { - GNUNET_CONTAINER_DLL_remove (rh->ac_head, - rh->ac_tail, - ac); - if (GNUNET_NO == ac->gns_authority) { - struct Gns2DnsPending *gp; - - while (NULL != (gp = ac->authority_info.dns_authority.gp_head)) - { - GNUNET_CONTAINER_DLL_remove (ac->authority_info.dns_authority.gp_head, - ac->authority_info.dns_authority.gp_tail, - gp); - if (NULL != gp->rh) + GNUNET_CONTAINER_DLL_remove(rh->ac_head, + rh->ac_tail, + ac); + if (GNUNET_NO == ac->gns_authority) { - /* rh->g2dc->rh is NOT in the DLL yet, so to enable us - using GNS_resolver_lookup_cancel here, we need to - add it first... */ - GNUNET_CONTAINER_DLL_insert (rlh_head, - rlh_tail, - gp->rh); - GNUNET_assert (NULL == gp->rh->task_id); - gp->rh->task_id = GNUNET_SCHEDULER_add_now (&GNS_resolver_lookup_cancel_, - gp->rh); - gp->rh = NULL; - } - if (NULL != gp->dns_rh) - { - GNUNET_RESOLVER_request_cancel (gp->dns_rh); - gp->dns_rh = NULL; + struct Gns2DnsPending *gp; + + while (NULL != (gp = ac->authority_info.dns_authority.gp_head)) + { + GNUNET_CONTAINER_DLL_remove(ac->authority_info.dns_authority.gp_head, + ac->authority_info.dns_authority.gp_tail, + gp); + if (NULL != gp->rh) + { + /* rh->g2dc->rh is NOT in the DLL yet, so to enable us + using GNS_resolver_lookup_cancel here, we need to + add it first... */ + GNUNET_CONTAINER_DLL_insert(rlh_head, + rlh_tail, + gp->rh); + GNUNET_assert(NULL == gp->rh->task_id); + gp->rh->task_id = GNUNET_SCHEDULER_add_now(&GNS_resolver_lookup_cancel_, + gp->rh); + gp->rh = NULL; + } + if (NULL != gp->dns_rh) + { + GNUNET_RESOLVER_request_cancel(gp->dns_rh); + gp->dns_rh = NULL; + } + GNUNET_free(gp); + } + GNUNET_DNSSTUB_stop(ac->authority_info.dns_authority.dns_handle); } - GNUNET_free (gp); - } - GNUNET_DNSSTUB_stop (ac->authority_info.dns_authority.dns_handle); + GNUNET_free(ac->label); + GNUNET_free(ac); } - GNUNET_free (ac->label); - GNUNET_free (ac); - } if (NULL != rh->task_id) - { - GNUNET_SCHEDULER_cancel (rh->task_id); - rh->task_id = NULL; - } + { + GNUNET_SCHEDULER_cancel(rh->task_id); + rh->task_id = NULL; + } if (NULL != rh->get_handle) - { - GNUNET_DHT_get_stop (rh->get_handle); - rh->get_handle = NULL; - } + { + GNUNET_DHT_get_stop(rh->get_handle); + rh->get_handle = NULL; + } if (NULL != rh->dht_heap_node) - { - GNUNET_CONTAINER_heap_remove_node (rh->dht_heap_node); - rh->dht_heap_node = NULL; - } + { + GNUNET_CONTAINER_heap_remove_node(rh->dht_heap_node); + rh->dht_heap_node = NULL; + } if (NULL != (vpn_ctx = rh->vpn_ctx)) - { - GNUNET_VPN_cancel_request (vpn_ctx->vpn_request); - GNUNET_free (vpn_ctx->rd_data); - GNUNET_free (vpn_ctx); - } + { + GNUNET_VPN_cancel_request(vpn_ctx->vpn_request); + GNUNET_free(vpn_ctx->rd_data); + GNUNET_free(vpn_ctx); + } if (NULL != rh->namecache_qe) - { - GNUNET_NAMECACHE_cancel (rh->namecache_qe); - rh->namecache_qe = NULL; - } + { + GNUNET_NAMECACHE_cancel(rh->namecache_qe); + rh->namecache_qe = NULL; + } if (NULL != rh->rev_check) - { - GNUNET_REVOCATION_query_cancel (rh->rev_check); - rh->rev_check = NULL; - } + { + GNUNET_REVOCATION_query_cancel(rh->rev_check); + rh->rev_check = NULL; + } if (NULL != rh->std_resolve) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Canceling standard DNS resolution\n"); - GNUNET_RESOLVER_request_cancel (rh->std_resolve); - rh->std_resolve = NULL; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Canceling standard DNS resolution\n"); + GNUNET_RESOLVER_request_cancel(rh->std_resolve); + rh->std_resolve = NULL; + } while (NULL != (dr = rh->dns_result_head)) - { - GNUNET_CONTAINER_DLL_remove (rh->dns_result_head, - rh->dns_result_tail, - dr); - GNUNET_free (dr); - } - GNUNET_free_non_null (rh->leho); - GNUNET_free (rh->name); - GNUNET_free (rh); + { + GNUNET_CONTAINER_DLL_remove(rh->dns_result_head, + rh->dns_result_tail, + dr); + GNUNET_free(dr); + } + GNUNET_free_non_null(rh->leho); + GNUNET_free(rh->name); + GNUNET_free(rh); } @@ -2875,24 +2883,24 @@ GNS_resolver_lookup_cancel (struct GNS_ResolverHandle *rh) * @param max_bg_queries maximum number of parallel background queries in dht */ void -GNS_resolver_init (struct GNUNET_NAMECACHE_Handle *nc, - struct GNUNET_DHT_Handle *dht, - const struct GNUNET_CONFIGURATION_Handle *c, - unsigned long long max_bg_queries) +GNS_resolver_init(struct GNUNET_NAMECACHE_Handle *nc, + struct GNUNET_DHT_Handle *dht, + const struct GNUNET_CONFIGURATION_Handle *c, + unsigned long long max_bg_queries) { cfg = c; namecache_handle = nc; dht_handle = dht; dht_lookup_heap = - GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); + GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN); max_allowed_background_queries = max_bg_queries; - disable_cache = GNUNET_CONFIGURATION_get_value_yesno (cfg, - "namecache", - "DISABLE"); + disable_cache = GNUNET_CONFIGURATION_get_value_yesno(cfg, + "namecache", + "DISABLE"); if (GNUNET_YES == disable_cache) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Namecache disabled\n"); - vpn_handle = GNUNET_VPN_connect (cfg); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Namecache disabled\n"); + vpn_handle = GNUNET_VPN_connect(cfg); } @@ -2900,30 +2908,30 @@ GNS_resolver_init (struct GNUNET_NAMECACHE_Handle *nc, * Shutdown resolver */ void -GNS_resolver_done () +GNS_resolver_done() { struct GNS_ResolverHandle *rh; struct CacheOps *co; /* abort active resolutions */ while (NULL != (rh = rlh_head)) - { - rh->proc (rh->proc_cls, - 0, - NULL); - GNS_resolver_lookup_cancel (rh); - } + { + rh->proc(rh->proc_cls, + 0, + NULL); + GNS_resolver_lookup_cancel(rh); + } while (NULL != (co = co_head)) - { - GNUNET_CONTAINER_DLL_remove (co_head, - co_tail, - co); - GNUNET_NAMECACHE_cancel (co->namecache_qe_cache); - GNUNET_free (co); - } - GNUNET_CONTAINER_heap_destroy (dht_lookup_heap); + { + GNUNET_CONTAINER_DLL_remove(co_head, + co_tail, + co); + GNUNET_NAMECACHE_cancel(co->namecache_qe_cache); + GNUNET_free(co); + } + GNUNET_CONTAINER_heap_destroy(dht_lookup_heap); dht_lookup_heap = NULL; - GNUNET_VPN_disconnect (vpn_handle); + GNUNET_VPN_disconnect(vpn_handle); vpn_handle = NULL; dht_handle = NULL; namecache_handle = NULL; diff --git a/src/gns/gnunet-service-gns_resolver.h b/src/gns/gnunet-service-gns_resolver.h index 240747931..8865f3c95 100644 --- a/src/gns/gnunet-service-gns_resolver.h +++ b/src/gns/gnunet-service-gns_resolver.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/gnunet-service-gns_resolver.h * @brief GNUnet GNS service @@ -39,17 +39,17 @@ * @param max_bg_queries maximum amount of background queries */ void -GNS_resolver_init (struct GNUNET_NAMECACHE_Handle *nc, - struct GNUNET_DHT_Handle *dht, - const struct GNUNET_CONFIGURATION_Handle *c, - unsigned long long max_bg_queries); +GNS_resolver_init(struct GNUNET_NAMECACHE_Handle *nc, + struct GNUNET_DHT_Handle *dht, + const struct GNUNET_CONFIGURATION_Handle *c, + unsigned long long max_bg_queries); /** * Cleanup resolver: Terminate pending lookups */ void -GNS_resolver_done (void); +GNS_resolver_done(void); /** @@ -84,12 +84,12 @@ typedef void * @return handle to cancel operation */ struct GNS_ResolverHandle * -GNS_resolver_lookup (const struct GNUNET_CRYPTO_EcdsaPublicKey *zone, - uint32_t record_type, - const char *name, - enum GNUNET_GNS_LocalOptions options, - GNS_ResultProcessor proc, - void *proc_cls); +GNS_resolver_lookup(const struct GNUNET_CRYPTO_EcdsaPublicKey *zone, + uint32_t record_type, + const char *name, + enum GNUNET_GNS_LocalOptions options, + GNS_ResultProcessor proc, + void *proc_cls); /** @@ -98,6 +98,6 @@ GNS_resolver_lookup (const struct GNUNET_CRYPTO_EcdsaPublicKey *zone, * @param rh resolution to abort */ void -GNS_resolver_lookup_cancel (struct GNS_ResolverHandle *rh); +GNS_resolver_lookup_cancel(struct GNS_ResolverHandle *rh); #endif diff --git a/src/gns/gnunet_w32nsp_lib.h b/src/gns/gnunet_w32nsp_lib.h index 1c17efefe..0316245ff 100644 --- a/src/gns/gnunet_w32nsp_lib.h +++ b/src/gns/gnunet_w32nsp_lib.h @@ -4,6 +4,6 @@ #include /* E0D24085-622C-4A93-9A0018-034469DE28DA */ -DEFINE_GUID (GNUNET_NAMESPACE_PROVIDER_DNS, 0xE0D24085L, 0x622C, 0x4A93, 0x9A, 0x18, 0x03, 0x44, 0x69, 0xDE, 0x28, 0xDA); +DEFINE_GUID(GNUNET_NAMESPACE_PROVIDER_DNS, 0xE0D24085L, 0x622C, 0x4A93, 0x9A, 0x18, 0x03, 0x44, 0x69, 0xDE, 0x28, 0xDA); #endif /* GNUNET_W32NSP_LIB_H */ diff --git a/src/gns/nss/nss_gns.c b/src/gns/nss/nss_gns.c index d76eac845..43fc030b9 100644 --- a/src/gns/nss/nss_gns.c +++ b/src/gns/nss/nss_gns.c @@ -17,7 +17,7 @@ along with nss-mdns; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -***/ + ***/ #include #include @@ -37,9 +37,9 @@ /** macro to align idx to 32bit boundary */ #define ALIGN(idx) do { \ - if (idx % sizeof(void*)) \ - idx += (sizeof(void*) - idx % sizeof(void*)); /* Align on 32 bit boundary */ \ -} while(0) + if (idx % sizeof(void*)) \ + idx += (sizeof(void*) - idx % sizeof(void*)); /* Align on 32 bit boundary */ \ + } while (0) /** @@ -75,7 +75,7 @@ _nss_gns_gethostbyname2_r(const char *name, #ifdef NSS_IPV6_ONLY af = AF_INET6; #else - af = AF_INET; + af = AF_INET; #endif #ifdef NSS_IPV4_ONLY @@ -83,70 +83,70 @@ _nss_gns_gethostbyname2_r(const char *name, #elif NSS_IPV6_ONLY if (af != AF_INET6) #else - if ( (af != AF_INET) && - (af != AF_INET6) ) + if ((af != AF_INET) && + (af != AF_INET6)) #endif - { - *errnop = EINVAL; - *h_errnop = NO_RECOVERY; + { + *errnop = EINVAL; + *h_errnop = NO_RECOVERY; - goto finish; - } + goto finish; + } address_length = (af == AF_INET) ? sizeof(ipv4_address_t) : sizeof(ipv6_address_t); if (buflen < sizeof(char*) + /* alias names */ - strlen (name) + 1) - { /* official name */ - *errnop = ERANGE; - *h_errnop = NO_RECOVERY; - status = NSS_STATUS_TRYAGAIN; - - goto finish; - } + strlen(name) + 1) + { /* official name */ + *errnop = ERANGE; + *h_errnop = NO_RECOVERY; + status = NSS_STATUS_TRYAGAIN; + + goto finish; + } u.count = 0; u.data_len = 0; - i = gns_resolve_name (af, - name, - &u); + i = gns_resolve_name(af, + name, + &u); if (-1 == i) - { - *errnop = errno; - status = NSS_STATUS_UNAVAIL; - *h_errnop = NO_RECOVERY; - goto finish; - } + { + *errnop = errno; + status = NSS_STATUS_UNAVAIL; + *h_errnop = NO_RECOVERY; + goto finish; + } if (-2 == i) - { - *errnop = ENOENT; - *h_errnop = NO_RECOVERY; - status = NSS_STATUS_UNAVAIL; - goto finish; - } + { + *errnop = ENOENT; + *h_errnop = NO_RECOVERY; + status = NSS_STATUS_UNAVAIL; + goto finish; + } if (-3 == i) - { - *errnop = ETIMEDOUT; - *h_errnop = HOST_NOT_FOUND; - status = NSS_STATUS_NOTFOUND; - goto finish; - } - if (0 == u.count) - { - *errnop = 0; /* success */ - *h_errnop = NO_DATA; /* success */ - status = NSS_STATUS_NOTFOUND; - goto finish; - } + { + *errnop = ETIMEDOUT; + *h_errnop = HOST_NOT_FOUND; + status = NSS_STATUS_NOTFOUND; + goto finish; + } + if (0 == u.count) + { + *errnop = 0; /* success */ + *h_errnop = NO_DATA; /* success */ + status = NSS_STATUS_NOTFOUND; + goto finish; + } /* Alias names */ - *((char**) buffer) = NULL; - result->h_aliases = (char**) buffer; + *((char**)buffer) = NULL; + result->h_aliases = (char**)buffer; idx = sizeof(char*); /* Official name */ - strcpy (buffer+idx, - name); - result->h_name = buffer+idx; - idx += strlen (name)+1; + strcpy(buffer + idx, + name); + result->h_name = buffer + idx; + idx += strlen(name) + 1; ALIGN(idx); @@ -154,29 +154,29 @@ _nss_gns_gethostbyname2_r(const char *name, result->h_length = address_length; /* Check if there's enough space for the addresses */ - if (buflen < idx+u.data_len+sizeof(char*)*(u.count+1)) - { - *errnop = ERANGE; - *h_errnop = NO_RECOVERY; - status = NSS_STATUS_TRYAGAIN; - goto finish; - } - /* Addresses */ + if (buflen < idx + u.data_len + sizeof(char*) * (u.count + 1)) + { + *errnop = ERANGE; + *h_errnop = NO_RECOVERY; + status = NSS_STATUS_TRYAGAIN; + goto finish; + } + /* Addresses */ astart = idx; - l = u.count*address_length; + l = u.count * address_length; if (0 != l) - memcpy (buffer+astart, - &u.data, - l); + memcpy(buffer + astart, + &u.data, + l); /* address_length is a multiple of 32bits, so idx is still aligned * correctly */ idx += l; /* Address array address_length is always a multiple of 32bits */ for (i = 0; i < u.count; i++) - ((char**) (buffer+idx))[i] = buffer+astart+address_length*i; - ((char**) (buffer+idx))[i] = NULL; - result->h_addr_list = (char**) (buffer+idx); + ((char**)(buffer + idx))[i] = buffer + astart + address_length * i; + ((char**)(buffer + idx))[i] = NULL; + result->h_addr_list = (char**)(buffer + idx); status = NSS_STATUS_SUCCESS; @@ -197,20 +197,20 @@ finish: * @return a nss_status code */ enum nss_status -_nss_gns_gethostbyname_r (const char *name, - struct hostent *result, - char *buffer, - size_t buflen, - int *errnop, - int *h_errnop) +_nss_gns_gethostbyname_r(const char *name, + struct hostent *result, + char *buffer, + size_t buflen, + int *errnop, + int *h_errnop) { - return _nss_gns_gethostbyname2_r (name, - AF_UNSPEC, - result, - buffer, - buflen, - errnop, - h_errnop); + return _nss_gns_gethostbyname2_r(name, + AF_UNSPEC, + result, + buffer, + buflen, + errnop, + h_errnop); } @@ -229,21 +229,21 @@ _nss_gns_gethostbyname_r (const char *name, * @return NSS_STATUS_UNAVAIL */ enum nss_status -_nss_gns_gethostbyaddr_r (const void* addr, - int len, - int af, - struct hostent *result, - char *buffer, - size_t buflen, - int *errnop, - int *h_errnop) +_nss_gns_gethostbyaddr_r(const void* addr, + int len, + int af, + struct hostent *result, + char *buffer, + size_t buflen, + int *errnop, + int *h_errnop) { - (void) addr; - (void) len; - (void) af; - (void) result; - (void) buffer; - (void) buflen; + (void)addr; + (void)len; + (void)af; + (void)result; + (void)buffer; + (void)buflen; *errnop = EINVAL; *h_errnop = NO_RECOVERY; /* NOTE we allow to leak this into DNS so no NOTFOUND */ diff --git a/src/gns/nss/nss_gns_query.c b/src/gns/nss/nss_gns_query.c index 253bb0f02..8af618618 100644 --- a/src/gns/nss/nss_gns_query.c +++ b/src/gns/nss/nss_gns_query.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ #include #include #include @@ -33,12 +33,12 @@ #define TIMEOUT "5s" static void -kwait (pid_t chld) +kwait(pid_t chld) { int ret; - kill (chld, SIGKILL); - waitpid (chld, &ret, 0); + kill(chld, SIGKILL); + waitpid(chld, &ret, 0); } @@ -55,7 +55,7 @@ kwait (pid_t chld) * else 0 */ int -gns_resolve_name (int af, const char *name, struct userdata *u) +gns_resolve_name(int af, const char *name, struct userdata *u) { FILE *p; char line[128]; @@ -63,85 +63,85 @@ gns_resolve_name (int af, const char *name, struct userdata *u) int out[2]; pid_t pid; - if (0 != pipe (out)) + if (0 != pipe(out)) return -1; - pid = fork (); + pid = fork(); if (-1 == pid) return -1; if (0 == pid) - { - char *argv[] = {"gnunet-gns", - "-r", - "-t", - (AF_INET6 == af) ? "AAAA" : "A", - "-u", - (char *) name, - "-T", - TIMEOUT, - NULL}; + { + char *argv[] = { "gnunet-gns", + "-r", + "-t", + (AF_INET6 == af) ? "AAAA" : "A", + "-u", + (char *)name, + "-T", + TIMEOUT, + NULL }; - (void) close (STDOUT_FILENO); - if ((0 != close (out[0])) || - (STDOUT_FILENO != dup2 (out[1], STDOUT_FILENO))) - _exit (1); - (void) execvp ("gnunet-gns", argv); - _exit (1); - } - (void) close (out[1]); - p = fdopen (out[0], "r"); + (void)close(STDOUT_FILENO); + if ((0 != close(out[0])) || + (STDOUT_FILENO != dup2(out[1], STDOUT_FILENO))) + _exit(1); + (void)execvp("gnunet-gns", argv); + _exit(1); + } + (void)close(out[1]); + p = fdopen(out[0], "r"); if (NULL == p) - { - kwait (pid); - return -1; - } - while (NULL != fgets (line, sizeof (line), p)) - { - if (u->count >= MAX_ENTRIES) - break; - if (line[strlen (line) - 1] == '\n') { - line[strlen (line) - 1] = '\0'; - if (AF_INET == af) - { - if (inet_pton (af, line, &u->data.ipv4[u->count])) - { - u->count++; - u->data_len += sizeof (ipv4_address_t); - } - else - { - (void) fclose (p); - kwait (pid); - errno = EINVAL; - return -1; - } - } - else if (AF_INET6 == af) - { - if (inet_pton (af, line, &u->data.ipv6[u->count])) - { - u->count++; - u->data_len += sizeof (ipv6_address_t); - } - else + kwait(pid); + return -1; + } + while (NULL != fgets(line, sizeof(line), p)) + { + if (u->count >= MAX_ENTRIES) + break; + if (line[strlen(line) - 1] == '\n') { - (void) fclose (p); - kwait (pid); - errno = EINVAL; - return -1; + line[strlen(line) - 1] = '\0'; + if (AF_INET == af) + { + if (inet_pton(af, line, &u->data.ipv4[u->count])) + { + u->count++; + u->data_len += sizeof(ipv4_address_t); + } + else + { + (void)fclose(p); + kwait(pid); + errno = EINVAL; + return -1; + } + } + else if (AF_INET6 == af) + { + if (inet_pton(af, line, &u->data.ipv6[u->count])) + { + u->count++; + u->data_len += sizeof(ipv6_address_t); + } + else + { + (void)fclose(p); + kwait(pid); + errno = EINVAL; + return -1; + } + } } - } } - } - (void) fclose (p); - waitpid (pid, &ret, 0); - if (! WIFEXITED (ret)) + (void)fclose(p); + waitpid(pid, &ret, 0); + if (!WIFEXITED(ret)) return -1; - if (4 == WEXITSTATUS (ret)) + if (4 == WEXITSTATUS(ret)) return -2; /* not for GNS */ if (3 == ret) return -3; /* timeout -> not found */ - if ((2 == WEXITSTATUS (ret)) || (1 == WEXITSTATUS (ret))) + if ((2 == WEXITSTATUS(ret)) || (1 == WEXITSTATUS(ret))) return -2; /* launch failure -> service unavailable */ return 0; } diff --git a/src/gns/nss/nss_gns_query.h b/src/gns/nss/nss_gns_query.h index 30ba76fd9..1901dd6c4 100644 --- a/src/gns/nss/nss_gns_query.h +++ b/src/gns/nss/nss_gns_query.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ #ifndef NSS_GNS_QUERY_H #define NSS_GNS_QUERY_H @@ -28,20 +28,17 @@ /* Maximum number of entries to return */ #define MAX_ENTRIES 16 -typedef struct -{ +typedef struct { uint32_t address; } ipv4_address_t; -typedef struct -{ +typedef struct { uint8_t address[16]; } ipv6_address_t; -struct userdata -{ +struct userdata { int count; int data_len; /* only valid when doing reverse lookup */ union { diff --git a/src/gns/plugin_block_gns.c b/src/gns/plugin_block_gns.c index 86d45b9fe..71cd78a8e 100644 --- a/src/gns/plugin_block_gns.c +++ b/src/gns/plugin_block_gns.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/plugin_block_gns.c @@ -56,37 +56,37 @@ * by this @a type of block (this is not an error) */ static struct GNUNET_BLOCK_Group * -block_plugin_gns_create_group (void *cls, - enum GNUNET_BLOCK_Type type, - uint32_t nonce, - const void *raw_data, - size_t raw_data_size, - va_list va) +block_plugin_gns_create_group(void *cls, + enum GNUNET_BLOCK_Type type, + uint32_t nonce, + const void *raw_data, + size_t raw_data_size, + va_list va) { unsigned int bf_size; const char *guard; - guard = va_arg (va, const char *); - if (0 == strcmp (guard, - "seen-set-size")) - bf_size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size (va_arg (va, unsigned int), - BLOOMFILTER_K); - else if (0 == strcmp (guard, - "filter-size")) - bf_size = va_arg (va, unsigned int); + guard = va_arg(va, const char *); + if (0 == strcmp(guard, + "seen-set-size")) + bf_size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size(va_arg(va, unsigned int), + BLOOMFILTER_K); + else if (0 == strcmp(guard, + "filter-size")) + bf_size = va_arg(va, unsigned int); else - { - GNUNET_break (0); - bf_size = GNS_BF_SIZE; - } - GNUNET_break (NULL == va_arg (va, const char *)); - return GNUNET_BLOCK_GROUP_bf_create (cls, - bf_size, - BLOOMFILTER_K, - type, - nonce, - raw_data, - raw_data_size); + { + GNUNET_break(0); + bf_size = GNS_BF_SIZE; + } + GNUNET_break(NULL == va_arg(va, const char *)); + return GNUNET_BLOCK_GROUP_bf_create(cls, + bf_size, + BLOOMFILTER_K, + type, + nonce, + raw_data, + raw_data_size); } @@ -110,16 +110,16 @@ block_plugin_gns_create_group (void *cls, * @return characterization of result */ static enum GNUNET_BLOCK_EvaluationResult -block_plugin_gns_evaluate (void *cls, - struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *bg, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode *query, - const void *xquery, - size_t xquery_size, - const void *reply_block, - size_t reply_block_size) +block_plugin_gns_evaluate(void *cls, + struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *bg, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode *query, + const void *xquery, + size_t xquery_size, + const void *reply_block, + size_t reply_block_size) { const struct GNUNET_GNSRECORD_Block *block; struct GNUNET_HashCode h; @@ -128,48 +128,48 @@ block_plugin_gns_evaluate (void *cls, if (type != GNUNET_BLOCK_TYPE_GNS_NAMERECORD) return GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED; if (NULL == reply_block) - { - if (0 != xquery_size) { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; + if (0 != xquery_size) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; + } + return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; } - return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; - } /* this is a reply */ - if (reply_block_size < sizeof (struct GNUNET_GNSRECORD_Block)) + if (reply_block_size < sizeof(struct GNUNET_GNSRECORD_Block)) { - GNUNET_break_op (0); + GNUNET_break_op(0); return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; } block = reply_block; - if (ntohl (block->purpose.size) + sizeof (struct GNUNET_CRYPTO_EcdsaSignature) + sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) != + if (ntohl(block->purpose.size) + sizeof(struct GNUNET_CRYPTO_EcdsaSignature) + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) != reply_block_size) { - GNUNET_break_op (0); + GNUNET_break_op(0); return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; } - GNUNET_CRYPTO_hash (&block->derived_key, - sizeof (block->derived_key), - &h); - if (0 != GNUNET_memcmp (&h, query)) + GNUNET_CRYPTO_hash(&block->derived_key, + sizeof(block->derived_key), + &h); + if (0 != GNUNET_memcmp(&h, query)) { - GNUNET_break_op (0); + GNUNET_break_op(0); return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; } if (GNUNET_OK != - GNUNET_GNSRECORD_block_verify (block)) + GNUNET_GNSRECORD_block_verify(block)) { - GNUNET_break_op (0); + GNUNET_break_op(0); return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; } - GNUNET_CRYPTO_hash (reply_block, - reply_block_size, - &chash); + GNUNET_CRYPTO_hash(reply_block, + reply_block_size, + &chash); if (GNUNET_YES == - GNUNET_BLOCK_GROUP_bf_test_and_set (bg, - &chash)) + GNUNET_BLOCK_GROUP_bf_test_and_set(bg, + &chash)) return GNUNET_BLOCK_EVALUATION_OK_DUPLICATE; return GNUNET_BLOCK_EVALUATION_OK_MORE; } @@ -187,25 +187,25 @@ block_plugin_gns_evaluate (void *cls, * (or if extracting a key from a block of this type does not work) */ static int -block_plugin_gns_get_key (void *cls, - enum GNUNET_BLOCK_Type type, - const void *reply_block, - size_t reply_block_size, - struct GNUNET_HashCode *key) +block_plugin_gns_get_key(void *cls, + enum GNUNET_BLOCK_Type type, + const void *reply_block, + size_t reply_block_size, + struct GNUNET_HashCode *key) { const struct GNUNET_GNSRECORD_Block *block; if (type != GNUNET_BLOCK_TYPE_GNS_NAMERECORD) return GNUNET_SYSERR; - if (reply_block_size < sizeof (struct GNUNET_GNSRECORD_Block)) + if (reply_block_size < sizeof(struct GNUNET_GNSRECORD_Block)) { - GNUNET_break_op (0); + GNUNET_break_op(0); return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; } block = reply_block; - GNUNET_CRYPTO_hash (&block->derived_key, - sizeof (block->derived_key), - key); + GNUNET_CRYPTO_hash(&block->derived_key, + sizeof(block->derived_key), + key); return GNUNET_OK; } @@ -214,7 +214,7 @@ block_plugin_gns_get_key (void *cls, * Entry point for the plugin. */ void * -libgnunet_plugin_block_gns_init (void *cls) +libgnunet_plugin_block_gns_init(void *cls) { static enum GNUNET_BLOCK_Type types[] = { @@ -223,7 +223,7 @@ libgnunet_plugin_block_gns_init (void *cls) }; struct GNUNET_BLOCK_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_BLOCK_PluginFunctions); + api = GNUNET_new(struct GNUNET_BLOCK_PluginFunctions); api->evaluate = &block_plugin_gns_evaluate; api->get_key = &block_plugin_gns_get_key; api->create_group = &block_plugin_gns_create_group; @@ -236,11 +236,11 @@ libgnunet_plugin_block_gns_init (void *cls) * Exit point from the plugin. */ void * -libgnunet_plugin_block_gns_done (void *cls) +libgnunet_plugin_block_gns_done(void *cls) { struct GNUNET_BLOCK_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/gns/plugin_gnsrecord_gns.c b/src/gns/plugin_gnsrecord_gns.c index 8cb76cffe..094307ea3 100644 --- a/src/gns/plugin_gnsrecord_gns.c +++ b/src/gns/plugin_gnsrecord_gns.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/plugin_gnsrecord_gns.c @@ -44,88 +44,94 @@ * @return NULL on error, otherwise human-readable representation of the value */ static char * -gns_value_to_string (void *cls, - uint32_t type, - const void *data, - size_t data_size) +gns_value_to_string(void *cls, + uint32_t type, + const void *data, + size_t data_size) { const char *cdata; switch (type) - { - case GNUNET_GNSRECORD_TYPE_PKEY: - if (data_size != sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)) - return NULL; - return GNUNET_CRYPTO_ecdsa_public_key_to_string (data); - case GNUNET_GNSRECORD_TYPE_NICK: - return GNUNET_strndup (data, data_size); - case GNUNET_GNSRECORD_TYPE_LEHO: - return GNUNET_strndup (data, data_size); - case GNUNET_GNSRECORD_TYPE_GNS2DNS: { - char *ns; - char *ip; - size_t off; - char *nstr; - - off = 0; - ns = GNUNET_DNSPARSER_parse_name (data, data_size, &off); - ip = GNUNET_DNSPARSER_parse_name (data, data_size, &off); - if ((NULL == ns) || (NULL == ip) || (off != data_size)) { - GNUNET_break_op (0); - GNUNET_free_non_null (ns); - GNUNET_free_non_null (ip); + case GNUNET_GNSRECORD_TYPE_PKEY: + if (data_size != sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey)) + return NULL; + return GNUNET_CRYPTO_ecdsa_public_key_to_string(data); + + case GNUNET_GNSRECORD_TYPE_NICK: + return GNUNET_strndup(data, data_size); + + case GNUNET_GNSRECORD_TYPE_LEHO: + return GNUNET_strndup(data, data_size); + + case GNUNET_GNSRECORD_TYPE_GNS2DNS: { + char *ns; + char *ip; + size_t off; + char *nstr; + + off = 0; + ns = GNUNET_DNSPARSER_parse_name(data, data_size, &off); + ip = GNUNET_DNSPARSER_parse_name(data, data_size, &off); + if ((NULL == ns) || (NULL == ip) || (off != data_size)) + { + GNUNET_break_op(0); + GNUNET_free_non_null(ns); + GNUNET_free_non_null(ip); + return NULL; + } + GNUNET_asprintf(&nstr, "%s@%s", ns, ip); + GNUNET_free_non_null(ns); + GNUNET_free_non_null(ip); + return nstr; + } + + case GNUNET_GNSRECORD_TYPE_VPN: { + struct GNUNET_TUN_GnsVpnRecord vpn; + char *vpn_str; + + cdata = data; + if ((data_size <= sizeof(vpn)) || ('\0' != cdata[data_size - 1])) + return NULL; /* malformed */ + /* need to memcpy for alignment */ + GNUNET_memcpy(&vpn, data, sizeof(vpn)); + GNUNET_asprintf(&vpn_str, + "%u %s %s", + (unsigned int)ntohs(vpn.proto), + (const char *)GNUNET_i2s_full(&vpn.peer), + (const char *)&cdata[sizeof(vpn)]); + return vpn_str; + } + + case GNUNET_GNSRECORD_TYPE_BOX: { + struct GNUNET_GNSRECORD_BoxRecord box; + uint32_t rt; + char *box_str; + char *ival; + + cdata = data; + if (data_size < sizeof(struct GNUNET_GNSRECORD_BoxRecord)) + return NULL; /* malformed */ + GNUNET_memcpy(&box, data, sizeof(box)); + rt = ntohl(box.record_type); + ival = GNUNET_GNSRECORD_value_to_string(rt, + &cdata[sizeof(box)], + data_size - sizeof(box)); + if (NULL == ival) + return NULL; /* malformed */ + GNUNET_asprintf(&box_str, + "%u %u %u %s", + (unsigned int)ntohs(box.protocol), + (unsigned int)ntohs(box.service), + (unsigned int)rt, + ival); + GNUNET_free(ival); + return box_str; + } + + default: return NULL; } - GNUNET_asprintf (&nstr, "%s@%s", ns, ip); - GNUNET_free_non_null (ns); - GNUNET_free_non_null (ip); - return nstr; - } - case GNUNET_GNSRECORD_TYPE_VPN: { - struct GNUNET_TUN_GnsVpnRecord vpn; - char *vpn_str; - - cdata = data; - if ((data_size <= sizeof (vpn)) || ('\0' != cdata[data_size - 1])) - return NULL; /* malformed */ - /* need to memcpy for alignment */ - GNUNET_memcpy (&vpn, data, sizeof (vpn)); - GNUNET_asprintf (&vpn_str, - "%u %s %s", - (unsigned int) ntohs (vpn.proto), - (const char *) GNUNET_i2s_full (&vpn.peer), - (const char *) &cdata[sizeof (vpn)]); - return vpn_str; - } - case GNUNET_GNSRECORD_TYPE_BOX: { - struct GNUNET_GNSRECORD_BoxRecord box; - uint32_t rt; - char *box_str; - char *ival; - - cdata = data; - if (data_size < sizeof (struct GNUNET_GNSRECORD_BoxRecord)) - return NULL; /* malformed */ - GNUNET_memcpy (&box, data, sizeof (box)); - rt = ntohl (box.record_type); - ival = GNUNET_GNSRECORD_value_to_string (rt, - &cdata[sizeof (box)], - data_size - sizeof (box)); - if (NULL == ival) - return NULL; /* malformed */ - GNUNET_asprintf (&box_str, - "%u %u %u %s", - (unsigned int) ntohs (box.protocol), - (unsigned int) ntohs (box.service), - (unsigned int) rt, - ival); - GNUNET_free (ival); - return box_str; - } - default: - return NULL; - } } @@ -141,142 +147,146 @@ gns_value_to_string (void *cls, * @return #GNUNET_OK on success */ static int -gns_string_to_value (void *cls, - uint32_t type, - const char *s, - void **data, - size_t *data_size) +gns_string_to_value(void *cls, + uint32_t type, + const char *s, + void **data, + size_t *data_size) { struct GNUNET_CRYPTO_EcdsaPublicKey pkey; if (NULL == s) return GNUNET_SYSERR; switch (type) - { - - case GNUNET_GNSRECORD_TYPE_PKEY: - if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (s, strlen (s), &pkey)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse PKEY record `%s'\n"), - s); - return GNUNET_SYSERR; - } - *data = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPublicKey); - GNUNET_memcpy (*data, &pkey, sizeof (pkey)); - *data_size = sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey); - return GNUNET_OK; - - case GNUNET_GNSRECORD_TYPE_NICK: - *data = GNUNET_strdup (s); - *data_size = strlen (s); - return GNUNET_OK; - case GNUNET_GNSRECORD_TYPE_LEHO: - *data = GNUNET_strdup (s); - *data_size = strlen (s); - return GNUNET_OK; - case GNUNET_GNSRECORD_TYPE_GNS2DNS: { - char nsbuf[514]; - char *cpy; - char *at; - size_t off; - - cpy = GNUNET_strdup (s); - at = strchr (cpy, '@'); - if (NULL == at) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse GNS2DNS record `%s'\n"), - s); - GNUNET_free (cpy); - return GNUNET_SYSERR; - } - *at = '\0'; - at++; - - off = 0; - if ((GNUNET_OK != GNUNET_DNSPARSER_builder_add_name (nsbuf, - sizeof (nsbuf), - &off, - cpy)) || - (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_name (nsbuf, sizeof (nsbuf), &off, at))) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to serialize GNS2DNS record with value `%s'\n"), - s); - GNUNET_free (cpy); - return GNUNET_SYSERR; + case GNUNET_GNSRECORD_TYPE_PKEY: + if (GNUNET_OK != + GNUNET_CRYPTO_ecdsa_public_key_from_string(s, strlen(s), &pkey)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse PKEY record `%s'\n"), + s); + return GNUNET_SYSERR; + } + *data = GNUNET_new(struct GNUNET_CRYPTO_EcdsaPublicKey); + GNUNET_memcpy(*data, &pkey, sizeof(pkey)); + *data_size = sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey); + return GNUNET_OK; + + case GNUNET_GNSRECORD_TYPE_NICK: + *data = GNUNET_strdup(s); + *data_size = strlen(s); + return GNUNET_OK; + + case GNUNET_GNSRECORD_TYPE_LEHO: + *data = GNUNET_strdup(s); + *data_size = strlen(s); + return GNUNET_OK; + + case GNUNET_GNSRECORD_TYPE_GNS2DNS: { + char nsbuf[514]; + char *cpy; + char *at; + size_t off; + + cpy = GNUNET_strdup(s); + at = strchr(cpy, '@'); + if (NULL == at) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse GNS2DNS record `%s'\n"), + s); + GNUNET_free(cpy); + return GNUNET_SYSERR; + } + *at = '\0'; + at++; + + off = 0; + if ((GNUNET_OK != GNUNET_DNSPARSER_builder_add_name(nsbuf, + sizeof(nsbuf), + &off, + cpy)) || + (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_name(nsbuf, sizeof(nsbuf), &off, at))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to serialize GNS2DNS record with value `%s'\n"), + s); + GNUNET_free(cpy); + return GNUNET_SYSERR; + } + GNUNET_free(cpy); + *data_size = off; + *data = GNUNET_malloc(off); + GNUNET_memcpy(*data, nsbuf, off); + return GNUNET_OK; } - GNUNET_free (cpy); - *data_size = off; - *data = GNUNET_malloc (off); - GNUNET_memcpy (*data, nsbuf, off); - return GNUNET_OK; - } - case GNUNET_GNSRECORD_TYPE_VPN: { - struct GNUNET_TUN_GnsVpnRecord *vpn; - char s_peer[103 + 1]; - char s_serv[253 + 1]; - unsigned int proto; - - if (3 != sscanf (s, "%u %103s %253s", &proto, s_peer, s_serv)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse VPN record string `%s'\n"), - s); - return GNUNET_SYSERR; + + case GNUNET_GNSRECORD_TYPE_VPN: { + struct GNUNET_TUN_GnsVpnRecord *vpn; + char s_peer[103 + 1]; + char s_serv[253 + 1]; + unsigned int proto; + + if (3 != sscanf(s, "%u %103s %253s", &proto, s_peer, s_serv)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse VPN record string `%s'\n"), + s); + return GNUNET_SYSERR; + } + *data_size = sizeof(struct GNUNET_TUN_GnsVpnRecord) + strlen(s_serv) + 1; + *data = vpn = GNUNET_malloc(*data_size); + if (GNUNET_OK != + GNUNET_CRYPTO_eddsa_public_key_from_string((char *)s_peer, + strlen(s_peer), + &vpn->peer.public_key)) + { + GNUNET_free(vpn); + *data_size = 0; + return GNUNET_SYSERR; + } + vpn->proto = htons((uint16_t)proto); + strcpy((char *)&vpn[1], s_serv); + return GNUNET_OK; } - *data_size = sizeof (struct GNUNET_TUN_GnsVpnRecord) + strlen (s_serv) + 1; - *data = vpn = GNUNET_malloc (*data_size); - if (GNUNET_OK != - GNUNET_CRYPTO_eddsa_public_key_from_string ((char *) s_peer, - strlen (s_peer), - &vpn->peer.public_key)) - { - GNUNET_free (vpn); - *data_size = 0; - return GNUNET_SYSERR; + + case GNUNET_GNSRECORD_TYPE_BOX: { + struct GNUNET_GNSRECORD_BoxRecord *box; + size_t rest; + unsigned int protocol; + unsigned int service; + unsigned int record_type; + void *bval; + size_t bval_size; + + if (3 != sscanf(s, "%u %u %u ", &protocol, &service, &record_type)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse BOX record string `%s'\n"), + s); + return GNUNET_SYSERR; + } + rest = snprintf(NULL, 0, "%u %u %u ", protocol, service, record_type); + if (GNUNET_OK != GNUNET_GNSRECORD_string_to_value(record_type, + &s[rest], + &bval, + &bval_size)) + return GNUNET_SYSERR; + *data_size = sizeof(struct GNUNET_GNSRECORD_BoxRecord) + bval_size; + *data = box = GNUNET_malloc(*data_size); + box->protocol = htons(protocol); + box->service = htons(service); + box->record_type = htonl(record_type); + GNUNET_memcpy(&box[1], bval, bval_size); + GNUNET_free(bval); + return GNUNET_OK; } - vpn->proto = htons ((uint16_t) proto); - strcpy ((char *) &vpn[1], s_serv); - return GNUNET_OK; - } - case GNUNET_GNSRECORD_TYPE_BOX: { - struct GNUNET_GNSRECORD_BoxRecord *box; - size_t rest; - unsigned int protocol; - unsigned int service; - unsigned int record_type; - void *bval; - size_t bval_size; - - if (3 != sscanf (s, "%u %u %u ", &protocol, &service, &record_type)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse BOX record string `%s'\n"), - s); + + default: return GNUNET_SYSERR; } - rest = snprintf (NULL, 0, "%u %u %u ", protocol, service, record_type); - if (GNUNET_OK != GNUNET_GNSRECORD_string_to_value (record_type, - &s[rest], - &bval, - &bval_size)) - return GNUNET_SYSERR; - *data_size = sizeof (struct GNUNET_GNSRECORD_BoxRecord) + bval_size; - *data = box = GNUNET_malloc (*data_size); - box->protocol = htons (protocol); - box->service = htons (service); - box->record_type = htonl (record_type); - GNUNET_memcpy (&box[1], bval, bval_size); - GNUNET_free (bval); - return GNUNET_OK; - } - default: - return GNUNET_SYSERR; - } } @@ -284,17 +294,16 @@ gns_string_to_value (void *cls, * Mapping of record type numbers to human-readable * record type names. */ -static struct -{ +static struct { const char *name; uint32_t number; -} gns_name_map[] = {{"PKEY", GNUNET_GNSRECORD_TYPE_PKEY}, - {"NICK", GNUNET_GNSRECORD_TYPE_NICK}, - {"LEHO", GNUNET_GNSRECORD_TYPE_LEHO}, - {"VPN", GNUNET_GNSRECORD_TYPE_VPN}, - {"GNS2DNS", GNUNET_GNSRECORD_TYPE_GNS2DNS}, - {"BOX", GNUNET_GNSRECORD_TYPE_BOX}, - {NULL, UINT32_MAX}}; +} gns_name_map[] = { { "PKEY", GNUNET_GNSRECORD_TYPE_PKEY }, + { "NICK", GNUNET_GNSRECORD_TYPE_NICK }, + { "LEHO", GNUNET_GNSRECORD_TYPE_LEHO }, + { "VPN", GNUNET_GNSRECORD_TYPE_VPN }, + { "GNS2DNS", GNUNET_GNSRECORD_TYPE_GNS2DNS }, + { "BOX", GNUNET_GNSRECORD_TYPE_BOX }, + { NULL, UINT32_MAX } }; /** @@ -305,13 +314,13 @@ static struct * @return corresponding number, UINT32_MAX on error */ static uint32_t -gns_typename_to_number (void *cls, const char *gns_typename) +gns_typename_to_number(void *cls, const char *gns_typename) { unsigned int i; i = 0; while ((NULL != gns_name_map[i].name) && - (0 != strcasecmp (gns_typename, gns_name_map[i].name))) + (0 != strcasecmp(gns_typename, gns_name_map[i].name))) i++; return gns_name_map[i].number; } @@ -325,7 +334,7 @@ gns_typename_to_number (void *cls, const char *gns_typename) * @return corresponding typestring, NULL on error */ static const char * -gns_number_to_typename (void *cls, uint32_t type) +gns_number_to_typename(void *cls, uint32_t type) { unsigned int i; @@ -343,11 +352,11 @@ gns_number_to_typename (void *cls, uint32_t type) * @return the exported block API */ void * -libgnunet_plugin_gnsrecord_gns_init (void *cls) +libgnunet_plugin_gnsrecord_gns_init(void *cls) { struct GNUNET_GNSRECORD_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_GNSRECORD_PluginFunctions); + api = GNUNET_new(struct GNUNET_GNSRECORD_PluginFunctions); api->value_to_string = &gns_value_to_string; api->string_to_value = &gns_string_to_value; api->typename_to_number = &gns_typename_to_number; @@ -363,11 +372,11 @@ libgnunet_plugin_gnsrecord_gns_init (void *cls) * @return NULL */ void * -libgnunet_plugin_gnsrecord_gns_done (void *cls) +libgnunet_plugin_gnsrecord_gns_done(void *cls) { struct GNUNET_GNSRECORD_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/gns/plugin_rest_gns.c b/src/gns/plugin_rest_gns.c index 1ecde12f0..2fc103ef6 100644 --- a/src/gns/plugin_rest_gns.c +++ b/src/gns/plugin_rest_gns.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Philippe Buschmann * @file gns/plugin_rest_gns.c @@ -65,17 +65,14 @@ static char *allow_methods; /** * @brief struct returned by the initialization function of the plugin */ -struct Plugin -{ +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; }; /** * The request handle */ -struct RequestHandle -{ - +struct RequestHandle { /** * Connection to GNS */ @@ -143,35 +140,36 @@ struct RequestHandle * @param handle Handle to clean up */ static void -cleanup_handle (void *cls) +cleanup_handle(void *cls) { struct RequestHandle *handle = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); if (NULL != handle->gns_lookup) - { - GNUNET_GNS_lookup_with_tld_cancel (handle->gns_lookup); - handle->gns_lookup = NULL; - } + { + GNUNET_GNS_lookup_with_tld_cancel(handle->gns_lookup); + handle->gns_lookup = NULL; + } if (NULL != handle->gns) - { - GNUNET_GNS_disconnect (handle->gns); - handle->gns = NULL; - } + { + GNUNET_GNS_disconnect(handle->gns); + handle->gns = NULL; + } if (NULL != handle->timeout_task) - { - GNUNET_SCHEDULER_cancel (handle->timeout_task); - handle->timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(handle->timeout_task); + handle->timeout_task = NULL; + } if (NULL != handle->url) - GNUNET_free (handle->url); + GNUNET_free(handle->url); if (NULL != handle->name) - GNUNET_free (handle->name); + GNUNET_free(handle->name); if (NULL != handle->emsg) - GNUNET_free (handle->emsg); + GNUNET_free(handle->emsg); - GNUNET_free (handle); + GNUNET_free(handle); } @@ -181,39 +179,40 @@ cleanup_handle (void *cls) * @param cls the `struct RequestHandle` */ static void -do_error (void *cls) +do_error(void *cls) { struct RequestHandle *handle = cls; struct MHD_Response *resp; - json_t *json_error = json_object (); + json_t *json_error = json_object(); char *response; if (NULL != handle->timeout_task) - GNUNET_SCHEDULER_cancel (handle->timeout_task); + GNUNET_SCHEDULER_cancel(handle->timeout_task); handle->timeout_task = NULL; if (NULL == handle->emsg) - handle->emsg = GNUNET_strdup (GNUNET_REST_GNS_ERROR_UNKNOWN); + handle->emsg = GNUNET_strdup(GNUNET_REST_GNS_ERROR_UNKNOWN); - json_object_set_new (json_error, "error", json_string (handle->emsg)); + json_object_set_new(json_error, "error", json_string(handle->emsg)); if (0 == handle->response_code) handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; - response = json_dumps (json_error, 0); - resp = GNUNET_REST_create_response (response); - handle->proc (handle->proc_cls, resp, handle->response_code); - json_decref (json_error); - GNUNET_free (response); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + response = json_dumps(json_error, 0); + resp = GNUNET_REST_create_response(response); + handle->proc(handle->proc_cls, resp, handle->response_code); + json_decref(json_error); + GNUNET_free(response); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } static void -do_timeout (void *cls) +do_timeout(void *cls) { struct RequestHandle *handle = cls; + handle->timeout_task = NULL; handle->response_code = MHD_HTTP_REQUEST_TIMEOUT; - do_error (handle); + do_error(handle); } @@ -226,10 +225,10 @@ do_timeout (void *cls) * @param rd the records in reply */ static void -handle_gns_response (void *cls, - int was_gns, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +handle_gns_response(void *cls, + int was_gns, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct RequestHandle *handle = cls; struct MHD_Response *resp; @@ -239,22 +238,22 @@ handle_gns_response (void *cls, handle->gns_lookup = NULL; if (GNUNET_NO == was_gns) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_GNS_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - - result_obj = GNUNET_JSON_from_gnsrecord (handle->name, rd, rd_count); - - result = json_dumps (result_obj, 0); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result); - resp = GNUNET_REST_create_response (result); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_free (result); - json_decref (result_obj); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_GNS_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + + result_obj = GNUNET_JSON_from_gnsrecord(handle->name, rd, rd_count); + + result = json_dumps(result_obj, 0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result); + resp = GNUNET_REST_create_response(result); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_free(result); + json_decref(result_obj); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } @@ -266,9 +265,9 @@ handle_gns_response (void *cls, * @param cls the RequestHandle */ void -get_gns_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +get_gns_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct GNUNET_HashCode key; @@ -277,50 +276,50 @@ get_gns_cont (struct GNUNET_REST_RequestHandle *con_handle, name = NULL; handle->name = NULL; - if (strlen (GNUNET_REST_API_NS_GNS) < strlen (handle->url)) - { - name = &handle->url[strlen (GNUNET_REST_API_NS_GNS) + 1]; - } + if (strlen(GNUNET_REST_API_NS_GNS) < strlen(handle->url)) + { + name = &handle->url[strlen(GNUNET_REST_API_NS_GNS) + 1]; + } if (NULL == name) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_GNS_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - if (0 >= strlen (name)) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_GNS_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - handle->name = GNUNET_strdup (name); + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_GNS_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + if (0 >= strlen(name)) + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_GNS_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + handle->name = GNUNET_strdup(name); handle->record_type = UINT32_MAX; - GNUNET_CRYPTO_hash (GNUNET_REST_GNS_PARAM_RECORD_TYPE, - strlen (GNUNET_REST_GNS_PARAM_RECORD_TYPE), - &key); + GNUNET_CRYPTO_hash(GNUNET_REST_GNS_PARAM_RECORD_TYPE, + strlen(GNUNET_REST_GNS_PARAM_RECORD_TYPE), + &key); if (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_contains (con_handle->url_param_map, &key)) - { - record_type = - GNUNET_CONTAINER_multihashmap_get (con_handle->url_param_map, &key); - handle->record_type = GNUNET_GNSRECORD_typename_to_number (record_type); - } + GNUNET_CONTAINER_multihashmap_contains(con_handle->url_param_map, &key)) + { + record_type = + GNUNET_CONTAINER_multihashmap_get(con_handle->url_param_map, &key); + handle->record_type = GNUNET_GNSRECORD_typename_to_number(record_type); + } if (UINT32_MAX == handle->record_type) - { - handle->record_type = GNUNET_GNSRECORD_TYPE_ANY; - } - - handle->gns_lookup = GNUNET_GNS_lookup_with_tld (handle->gns, - handle->name, - handle->record_type, - GNUNET_NO, - &handle_gns_response, - handle); + { + handle->record_type = GNUNET_GNSRECORD_TYPE_ANY; + } + + handle->gns_lookup = GNUNET_GNS_lookup_with_tld(handle->gns, + handle->name, + handle->record_type, + GNUNET_NO, + &handle_gns_response, + handle); } @@ -332,18 +331,18 @@ get_gns_cont (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ static void -options_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +options_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct MHD_Response *resp; struct RequestHandle *handle = cls; //independent of path return all options - resp = GNUNET_REST_create_response (NULL); - MHD_add_response_header (resp, "Access-Control-Allow-Methods", allow_methods); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + resp = GNUNET_REST_create_response(NULL); + MHD_add_response_header(resp, "Access-Control-Allow-Methods", allow_methods); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); return; } @@ -354,20 +353,20 @@ options_cont (struct GNUNET_REST_RequestHandle *con_handle, * @param handle the request handle */ static void -init_cont (struct RequestHandle *handle) +init_cont(struct RequestHandle *handle) { struct GNUNET_REST_RequestHandlerError err; static const struct GNUNET_REST_RequestHandler handlers[] = - {{MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_GNS, &get_gns_cont}, - {MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_GNS, &options_cont}, - GNUNET_REST_HANDLER_END}; + { { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_GNS, &get_gns_cont }, + { MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_GNS, &options_cont }, + GNUNET_REST_HANDLER_END }; if (GNUNET_NO == - GNUNET_REST_handle_request (handle->rest_handle, handlers, &err, handle)) - { - handle->response_code = err.error_code; - GNUNET_SCHEDULER_add_now (&do_error, handle); - } + GNUNET_REST_handle_request(handle->rest_handle, handlers, &err, handle)) + { + handle->response_code = err.error_code; + GNUNET_SCHEDULER_add_now(&do_error, handle); + } } @@ -383,30 +382,30 @@ init_cont (struct RequestHandle *handle) * @return GNUNET_OK if request accepted */ static void -rest_process_request (struct GNUNET_REST_RequestHandle *rest_handle, - GNUNET_REST_ResultProcessor proc, - void *proc_cls) +rest_process_request(struct GNUNET_REST_RequestHandle *rest_handle, + GNUNET_REST_ResultProcessor proc, + void *proc_cls) { - struct RequestHandle *handle = GNUNET_new (struct RequestHandle); + struct RequestHandle *handle = GNUNET_new(struct RequestHandle); handle->response_code = 0; handle->timeout = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60); + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60); handle->proc_cls = proc_cls; handle->proc = proc; handle->rest_handle = rest_handle; - handle->url = GNUNET_strdup (rest_handle->url); - if (handle->url[strlen (handle->url) - 1] == '/') - handle->url[strlen (handle->url) - 1] = '\0'; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n"); - handle->gns = GNUNET_GNS_connect (cfg); - init_cont (handle); + handle->url = GNUNET_strdup(rest_handle->url); + if (handle->url[strlen(handle->url) - 1] == '/') + handle->url[strlen(handle->url) - 1] = '\0'; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n"); + handle->gns = GNUNET_GNS_connect(cfg); + init_cont(handle); handle->timeout_task = - GNUNET_SCHEDULER_add_delayed (handle->timeout, &do_timeout, handle); + GNUNET_SCHEDULER_add_delayed(handle->timeout, &do_timeout, handle); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connected\n"); } @@ -417,7 +416,7 @@ rest_process_request (struct GNUNET_REST_RequestHandle *rest_handle, * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_rest_gns_init (void *cls) +libgnunet_plugin_rest_gns_init(void *cls) { static struct Plugin plugin; struct GNUNET_REST_Plugin *api; @@ -425,21 +424,21 @@ libgnunet_plugin_rest_gns_init (void *cls) cfg = cls; if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.cfg = cfg; - api = GNUNET_new (struct GNUNET_REST_Plugin); + api = GNUNET_new(struct GNUNET_REST_Plugin); api->cls = &plugin; api->name = GNUNET_REST_API_NS_GNS; api->process_request = &rest_process_request; - GNUNET_asprintf (&allow_methods, - "%s, %s, %s, %s, %s", - MHD_HTTP_METHOD_GET, - MHD_HTTP_METHOD_POST, - MHD_HTTP_METHOD_PUT, - MHD_HTTP_METHOD_DELETE, - MHD_HTTP_METHOD_OPTIONS); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Gns REST API initialized\n")); + GNUNET_asprintf(&allow_methods, + "%s, %s, %s, %s, %s", + MHD_HTTP_METHOD_GET, + MHD_HTTP_METHOD_POST, + MHD_HTTP_METHOD_PUT, + MHD_HTTP_METHOD_DELETE, + MHD_HTTP_METHOD_OPTIONS); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, _("Gns REST API initialized\n")); return api; } @@ -451,15 +450,16 @@ libgnunet_plugin_rest_gns_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_rest_gns_done (void *cls) +libgnunet_plugin_rest_gns_done(void *cls) { struct GNUNET_REST_Plugin *api = cls; struct Plugin *plugin = api->cls; + plugin->cfg = NULL; - GNUNET_free_non_null (allow_methods); - GNUNET_free (api); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Gns REST plugin is finished\n"); + GNUNET_free_non_null(allow_methods); + GNUNET_free(api); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Gns REST plugin is finished\n"); return NULL; } diff --git a/src/gns/test_gns_proxy.c b/src/gns/test_gns_proxy.c index 053f5f898..2df422731 100644 --- a/src/gns/test_gns_proxy.c +++ b/src/gns/test_gns_proxy.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file test_gns_proxy.c @@ -37,7 +37,7 @@ #define TEST_DOMAIN "www.test" -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 300) /** * Return value for 'main'. @@ -69,8 +69,7 @@ static gnutls_x509_crt_t proxy_cert; static gnutls_x509_privkey_t proxy_key; -struct CBC -{ +struct CBC { char buf[1024]; size_t pos; }; @@ -85,30 +84,30 @@ static struct CBC cbc; * @return NULL on error */ static void* -load_file (const char* filename, - unsigned int* size) +load_file(const char* filename, + unsigned int* size) { void *buffer; uint64_t fsize; if (GNUNET_OK != - GNUNET_DISK_file_size (filename, - &fsize, - GNUNET_YES, - GNUNET_YES)) + GNUNET_DISK_file_size(filename, + &fsize, + GNUNET_YES, + GNUNET_YES)) return NULL; if (fsize > MAX_PEM_SIZE) return NULL; - *size = (unsigned int) fsize; - buffer = GNUNET_malloc (*size); + *size = (unsigned int)fsize; + buffer = GNUNET_malloc(*size); if (fsize != - GNUNET_DISK_fn_read (filename, - buffer, - (size_t) fsize)) - { - GNUNET_free (buffer); - return NULL; - } + GNUNET_DISK_fn_read(filename, + buffer, + (size_t)fsize)) + { + GNUNET_free(buffer); + return NULL; + } return buffer; } @@ -120,25 +119,25 @@ load_file (const char* filename, * @return #GNUNET_OK on success */ static int -load_key_from_file (gnutls_x509_privkey_t key, - const char* keyfile) +load_key_from_file(gnutls_x509_privkey_t key, + const char* keyfile) { gnutls_datum_t key_data; int ret; - key_data.data = load_file (keyfile, - &key_data.size); + key_data.data = load_file(keyfile, + &key_data.size); if (NULL == key_data.data) return GNUNET_SYSERR; - ret = gnutls_x509_privkey_import (key, &key_data, - GNUTLS_X509_FMT_PEM); + ret = gnutls_x509_privkey_import(key, &key_data, + GNUTLS_X509_FMT_PEM); if (GNUTLS_E_SUCCESS != ret) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to import private key from file `%s'\n"), - keyfile); - } - GNUNET_free_non_null (key_data.data); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to import private key from file `%s'\n"), + keyfile); + } + GNUNET_free_non_null(key_data.data); return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK; } @@ -150,107 +149,108 @@ load_key_from_file (gnutls_x509_privkey_t key, * @return #GNUNET_OK on success */ static int -load_cert_from_file (gnutls_x509_crt_t crt, - const char* certfile) +load_cert_from_file(gnutls_x509_crt_t crt, + const char* certfile) { gnutls_datum_t cert_data; int ret; - cert_data.data = load_file (certfile, - &cert_data.size); + cert_data.data = load_file(certfile, + &cert_data.size); if (NULL == cert_data.data) return GNUNET_SYSERR; - ret = gnutls_x509_crt_import (crt, - &cert_data, - GNUTLS_X509_FMT_PEM); + ret = gnutls_x509_crt_import(crt, + &cert_data, + GNUTLS_X509_FMT_PEM); if (GNUTLS_E_SUCCESS != ret) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to import certificate from `%s'\n"), - certfile); - } - GNUNET_free_non_null (cert_data.data); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to import certificate from `%s'\n"), + certfile); + } + GNUNET_free_non_null(cert_data.data); return (GNUTLS_E_SUCCESS != ret) ? GNUNET_SYSERR : GNUNET_OK; } static size_t -copy_buffer (void *ptr, size_t size, size_t nmemb, void *ctx) +copy_buffer(void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > sizeof(cbc->buf)) return 0; /* overflow */ - GNUNET_memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); + GNUNET_memcpy(&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static int -mhd_ahc (void *cls, - struct MHD_Connection *connection, - const char *url, - const char *method, - const char *version, - const char *upload_data, size_t *upload_data_size, - void **unused) +mhd_ahc(void *cls, + struct MHD_Connection *connection, + const char *url, + const char *method, + const char *version, + const char *upload_data, size_t *upload_data_size, + void **unused) { static int ptr; struct MHD_Response *response; int ret; - if (0 != strcmp ("GET", method)) + if (0 != strcmp("GET", method)) return MHD_NO; /* unexpected method */ if (&ptr != *unused) - { - *unused = &ptr; - return MHD_YES; - } + { + *unused = &ptr; + return MHD_YES; + } *unused = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MHD sends respose for request to URL `%s'\n", url); - response = MHD_create_response_from_buffer (strlen (url), - (void *) url, - MHD_RESPMEM_MUST_COPY); - ret = MHD_queue_response (connection, MHD_HTTP_OK, response); - MHD_destroy_response (response); - if (ret == MHD_NO) { - global_ret = 1; - abort (); - } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MHD sends respose for request to URL `%s'\n", url); + response = MHD_create_response_from_buffer(strlen(url), + (void *)url, + MHD_RESPMEM_MUST_COPY); + ret = MHD_queue_response(connection, MHD_HTTP_OK, response); + MHD_destroy_response(response); + if (ret == MHD_NO) + { + global_ret = 1; + abort(); + } global_ret = 0; return ret; } static void -do_shutdown () +do_shutdown() { if (mhd_task_id != NULL) - { - GNUNET_SCHEDULER_cancel (mhd_task_id); - mhd_task_id = NULL; - } + { + GNUNET_SCHEDULER_cancel(mhd_task_id); + mhd_task_id = NULL; + } if (curl_task_id != NULL) - { - GNUNET_SCHEDULER_cancel (curl_task_id); - curl_task_id = NULL; - } + { + GNUNET_SCHEDULER_cancel(curl_task_id); + curl_task_id = NULL; + } if (NULL != mhd) - { - MHD_stop_daemon (mhd); - mhd = NULL; - } - GNUNET_free_non_null (url); + { + MHD_stop_daemon(mhd); + mhd = NULL; + } + GNUNET_free_non_null(url); if (NULL != proxy_proc) { - (void) GNUNET_OS_process_kill (proxy_proc, SIGKILL); - GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (proxy_proc)); - GNUNET_OS_process_destroy (proxy_proc); + (void)GNUNET_OS_process_kill(proxy_proc, SIGKILL); + GNUNET_assert(GNUNET_OK == GNUNET_OS_process_wait(proxy_proc)); + GNUNET_OS_process_destroy(proxy_proc); proxy_proc = NULL; } url = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -258,19 +258,19 @@ do_shutdown () * Function to run the HTTP client. */ static void -curl_main (void); +curl_main(void); static void -curl_task (void *cls) +curl_task(void *cls) { curl_task_id = NULL; - curl_main (); + curl_main(); } static void -curl_main () +curl_main() { fd_set rs; fd_set ws; @@ -284,93 +284,93 @@ curl_main () struct CURLMsg *msg; max = 0; - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); - curl_multi_perform (multi, &running); + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); + curl_multi_perform(multi, &running); if (running == 0) - { - GNUNET_assert (NULL != (msg = curl_multi_info_read (multi, &running))); - if (msg->msg == CURLMSG_DONE) { - if (msg->data.result != CURLE_OK) - { - fprintf (stderr, - "%s failed at %s:%d: `%s'\n", - "curl_multi_perform", - __FILE__, - __LINE__, curl_easy_strerror (msg->data.result)); - global_ret = 1; - } + GNUNET_assert(NULL != (msg = curl_multi_info_read(multi, &running))); + if (msg->msg == CURLMSG_DONE) + { + if (msg->data.result != CURLE_OK) + { + fprintf(stderr, + "%s failed at %s:%d: `%s'\n", + "curl_multi_perform", + __FILE__, + __LINE__, curl_easy_strerror(msg->data.result)); + global_ret = 1; + } + } + curl_multi_remove_handle(multi, curl); + curl_multi_cleanup(multi); + curl_easy_cleanup(curl); + curl = NULL; + multi = NULL; + if (cbc.pos != strlen("/hello_world")) + { + GNUNET_break(0); + global_ret = 2; + } + if (0 != strncmp("/hello_world", cbc.buf, strlen("/hello_world"))) + { + GNUNET_break(0); + global_ret = 3; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Download complete, shutting down!\n"); + do_shutdown(); + return; } - curl_multi_remove_handle (multi, curl); - curl_multi_cleanup (multi); - curl_easy_cleanup (curl); - curl = NULL; - multi = NULL; - if (cbc.pos != strlen ("/hello_world")) - { - GNUNET_break (0); - global_ret = 2; - } - if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) - { - GNUNET_break (0); - global_ret = 3; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download complete, shutting down!\n"); - do_shutdown (); - return; - } - GNUNET_assert (CURLM_OK == curl_multi_fdset (multi, &rs, &ws, &es, &max)); - if ( (CURLM_OK != curl_multi_timeout (multi, &timeout)) || - (-1 == timeout) ) + GNUNET_assert(CURLM_OK == curl_multi_fdset(multi, &rs, &ws, &es, &max)); + if ((CURLM_OK != curl_multi_timeout(multi, &timeout)) || + (-1 == timeout)) delay = GNUNET_TIME_UNIT_SECONDS; else - delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, (unsigned int) timeout); - GNUNET_NETWORK_fdset_copy_native (&nrs, - &rs, - max + 1); - GNUNET_NETWORK_fdset_copy_native (&nws, - &ws, - max + 1); - curl_task_id = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, - delay, - &nrs, - &nws, - &curl_task, - NULL); + delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, (unsigned int)timeout); + GNUNET_NETWORK_fdset_copy_native(&nrs, + &rs, + max + 1); + GNUNET_NETWORK_fdset_copy_native(&nws, + &ws, + max + 1); + curl_task_id = GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT, + delay, + &nrs, + &nws, + &curl_task, + NULL); } static void -start_curl (void *cls) +start_curl(void *cls) { curl_task_id = NULL; - GNUNET_asprintf (&url, - "https://%s:%d/hello_world", - TEST_DOMAIN, port); - curl = curl_easy_init (); - curl_easy_setopt (curl, CURLOPT_URL, url); + GNUNET_asprintf(&url, + "https://%s:%d/hello_world", + TEST_DOMAIN, port); + curl = curl_easy_init(); + curl_easy_setopt(curl, CURLOPT_URL, url); //curl_easy_setopt (curl, CURLOPT_URL, "https://127.0.0.1:8443/hello_world"); - curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, ©_buffer); - curl_easy_setopt (curl, CURLOPT_WRITEDATA, &cbc); - curl_easy_setopt (curl, CURLOPT_FAILONERROR, 1); - curl_easy_setopt (curl, CURLOPT_TIMEOUT, 150L); - curl_easy_setopt (curl, CURLOPT_CONNECTTIMEOUT, 15L); - curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1); - curl_easy_setopt (curl, CURLOPT_CAINFO, cafile_opt); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ©_buffer); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &cbc); + curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); + curl_easy_setopt(curl, CURLOPT_TIMEOUT, 150L); + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15L); + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); + curl_easy_setopt(curl, CURLOPT_CAINFO, cafile_opt); //curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 0L); //curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0L); - curl_easy_setopt (curl, CURLOPT_PROXY, "socks5h://127.0.0.1:7777"); - - multi = curl_multi_init (); - GNUNET_assert (multi != NULL); - GNUNET_assert (CURLM_OK == curl_multi_add_handle (multi, curl)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Beginning HTTP download from `%s'\n", - url); - curl_main (); + curl_easy_setopt(curl, CURLOPT_PROXY, "socks5h://127.0.0.1:7777"); + + multi = curl_multi_init(); + GNUNET_assert(multi != NULL); + GNUNET_assert(CURLM_OK == curl_multi_add_handle(multi, curl)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Beginning HTTP download from `%s'\n", + url); + curl_main(); } @@ -387,12 +387,12 @@ start_curl (void *cls) * specified target peer; NULL on error */ static void -commence_testing (void *cls) +commence_testing(void *cls) { curl_task_id = - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &start_curl, - NULL); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &start_curl, + NULL); } @@ -400,20 +400,20 @@ commence_testing (void *cls) * Function to keep the HTTP server running. */ static void -mhd_main (void); +mhd_main(void); static void -mhd_task (void *cls) +mhd_task(void *cls) { mhd_task_id = NULL; - MHD_run (mhd); - mhd_main (); + MHD_run(mhd); + mhd_main(); } static void -mhd_main () +mhd_main() { struct GNUNET_NETWORK_FDSet nrs; struct GNUNET_NETWORK_FDSet nws; @@ -424,30 +424,30 @@ mhd_main () unsigned MHD_LONG_LONG timeout; struct GNUNET_TIME_Relative delay; - GNUNET_assert (NULL == mhd_task_id); - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); + GNUNET_assert(NULL == mhd_task_id); + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); max_fd = -1; - GNUNET_assert (MHD_YES == - MHD_get_fdset (mhd, &rs, &ws, &es, &max_fd)); - if (MHD_YES == MHD_get_timeout (mhd, &timeout)) - delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, - (unsigned int) timeout); + GNUNET_assert(MHD_YES == + MHD_get_fdset(mhd, &rs, &ws, &es, &max_fd)); + if (MHD_YES == MHD_get_timeout(mhd, &timeout)) + delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, + (unsigned int)timeout); else delay = GNUNET_TIME_UNIT_FOREVER_REL; - GNUNET_NETWORK_fdset_copy_native (&nrs, - &rs, - max_fd + 1); - GNUNET_NETWORK_fdset_copy_native (&nws, - &ws, - max_fd + 1); - mhd_task_id = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, - delay, - &nrs, - &nws, - &mhd_task, - NULL); + GNUNET_NETWORK_fdset_copy_native(&nrs, + &rs, + max_fd + 1); + GNUNET_NETWORK_fdset_copy_native(&nws, + &ws, + max_fd + 1); + mhd_task_id = GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT, + delay, + &nrs, + &nws, + &mhd_task, + NULL); } @@ -460,105 +460,105 @@ mhd_main () * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Using `%s' as CA\n", - cafile_srv); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Using `%s' as CA\n", + cafile_srv); char cert[MAX_PEM_SIZE]; char key[MAX_PEM_SIZE]; size_t key_buf_size; size_t cert_buf_size; - gnutls_global_init (); - gnutls_x509_crt_init (&proxy_cert); - gnutls_x509_privkey_init (&proxy_key); - - if ( (GNUNET_OK != - load_cert_from_file (proxy_cert, - cafile_srv)) || - (GNUNET_OK != - load_key_from_file (proxy_key, - cafile_srv)) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to load X.509 key and certificate from `%s'\n"), - cafile_srv); - gnutls_x509_crt_deinit (proxy_cert); - gnutls_x509_privkey_deinit (proxy_key); - gnutls_global_deinit (); - return; - } - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - key_buf_size = sizeof (key); - cert_buf_size = sizeof (cert); - gnutls_x509_crt_export (proxy_cert, - GNUTLS_X509_FMT_PEM, - cert, - &cert_buf_size); - gnutls_x509_privkey_export (proxy_key, - GNUTLS_X509_FMT_PEM, - key, - &key_buf_size); - mhd = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_SSL | MHD_ALLOW_SUSPEND_RESUME, port, - NULL, NULL, - &mhd_ahc, NULL, - MHD_OPTION_HTTPS_MEM_KEY, key, - MHD_OPTION_HTTPS_MEM_CERT, cert, - MHD_OPTION_END); - GNUNET_assert (NULL != mhd); - mhd_main (); - - GNUNET_SCHEDULER_add_now (&commence_testing, - NULL); + gnutls_global_init(); + gnutls_x509_crt_init(&proxy_cert); + gnutls_x509_privkey_init(&proxy_key); + + if ((GNUNET_OK != + load_cert_from_file(proxy_cert, + cafile_srv)) || + (GNUNET_OK != + load_key_from_file(proxy_key, + cafile_srv))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to load X.509 key and certificate from `%s'\n"), + cafile_srv); + gnutls_x509_crt_deinit(proxy_cert); + gnutls_x509_privkey_deinit(proxy_key); + gnutls_global_deinit(); + return; + } + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); + key_buf_size = sizeof(key); + cert_buf_size = sizeof(cert); + gnutls_x509_crt_export(proxy_cert, + GNUTLS_X509_FMT_PEM, + cert, + &cert_buf_size); + gnutls_x509_privkey_export(proxy_key, + GNUTLS_X509_FMT_PEM, + key, + &key_buf_size); + mhd = MHD_start_daemon(MHD_USE_DEBUG | MHD_USE_SSL | MHD_ALLOW_SUSPEND_RESUME, port, + NULL, NULL, + &mhd_ahc, NULL, + MHD_OPTION_HTTPS_MEM_KEY, key, + MHD_OPTION_HTTPS_MEM_CERT, cert, + MHD_OPTION_END); + GNUNET_assert(NULL != mhd); + mhd_main(); + + GNUNET_SCHEDULER_add_now(&commence_testing, + NULL); } int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_option_uint16 ('p', - "port", - NULL, - gettext_noop ("listen on specified port (default: 7777)"), - &port), - GNUNET_GETOPT_option_string ('A', - "curlcert", - NULL, - gettext_noop ("pem file to use as CA"), - &cafile_opt), - GNUNET_GETOPT_option_string ('S', - "servercert", - NULL, - gettext_noop ("pem file to use for the server"), - &cafile_srv), + GNUNET_GETOPT_option_uint16('p', + "port", + NULL, + gettext_noop("listen on specified port (default: 7777)"), + &port), + GNUNET_GETOPT_option_string('A', + "curlcert", + NULL, + gettext_noop("pem file to use as CA"), + &cafile_opt), + GNUNET_GETOPT_option_string('S', + "servercert", + NULL, + gettext_noop("pem file to use for the server"), + &cafile_srv), GNUNET_GETOPT_OPTION_END }; - if (0 != curl_global_init (CURL_GLOBAL_WIN32)) - { - fprintf (stderr, "failed to initialize curl\n"); - return 2; - } + if (0 != curl_global_init(CURL_GLOBAL_WIN32)) + { + fprintf(stderr, "failed to initialize curl\n"); + return 2; + } if (GNUNET_OK != - GNUNET_STRINGS_get_utf8_args (argc, argv, - &argc, &argv)) + GNUNET_STRINGS_get_utf8_args(argc, argv, + &argc, &argv)) return 2; - GNUNET_log_setup ("gnunet-gns-proxy-test", - "WARNING", - NULL); - if (GNUNET_OK != GNUNET_PROGRAM_run (argc, argv, - "gnunet-gns-proxy-test", - _("GNUnet GNS proxy test"), - options, - &run, NULL)) + GNUNET_log_setup("gnunet-gns-proxy-test", + "WARNING", + NULL); + if (GNUNET_OK != GNUNET_PROGRAM_run(argc, argv, + "gnunet-gns-proxy-test", + _("GNUnet GNS proxy test"), + options, + &run, NULL)) return 1; - GNUNET_free_non_null ((char *) argv); + GNUNET_free_non_null((char *)argv); return global_ret; } diff --git a/src/gns/w32nsp-install.c b/src/gns/w32nsp-install.c index 6c9c44409..2674359fb 100644 --- a/src/gns/w32nsp-install.c +++ b/src/gns/w32nsp-install.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/w32nsp-install.c * @brief W32 integration installer for GNS @@ -31,7 +31,7 @@ #include int -main (int argc, char **argv) +main(int argc, char **argv) { int ret; int r = 1; @@ -47,97 +47,97 @@ main (int argc, char **argv) int p_count; int i; - if (WSAStartup (MAKEWORD (2,2), &wsd) != 0) - { - fprintf (stderr, "WSAStartup () failed: %lu\n", GetLastError ()); - return 5; - } + if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) + { + fprintf(stderr, "WSAStartup () failed: %lu\n", GetLastError()); + return 5; + } dwBufferLen = dwInitialBufferLen; - pi = malloc (dwBufferLen); + pi = malloc(dwBufferLen); if (NULL == pi) - { - fprintf (stderr, "malloc (%lu) failed: %d\n", dwBufferLen, errno); - WSACleanup (); - return 6; - } - p_count = WSAEnumNameSpaceProviders (&dwBufferLen, pi); + { + fprintf(stderr, "malloc (%lu) failed: %d\n", dwBufferLen, errno); + WSACleanup(); + return 6; + } + p_count = WSAEnumNameSpaceProviders(&dwBufferLen, pi); if (SOCKET_ERROR == p_count) - { - DWORD err = GetLastError (); - if (WSAEFAULT == err && dwBufferLen != dwInitialBufferLen) { - free (pi); + DWORD err = GetLastError(); + if (WSAEFAULT == err && dwBufferLen != dwInitialBufferLen) + { + free(pi); - pi = malloc (dwBufferLen); - if (pi == NULL) - { - fprintf (stderr, "malloc (%lu) failed: %d\n", dwBufferLen, errno); - WSACleanup (); - return 6; - } + pi = malloc(dwBufferLen); + if (pi == NULL) + { + fprintf(stderr, "malloc (%lu) failed: %d\n", dwBufferLen, errno); + WSACleanup(); + return 6; + } - p_count = WSAEnumNameSpaceProviders (&dwBufferLen, pi); - if (SOCKET_ERROR == p_count) - { - fprintf (stderr, "WSAEnumNameSpaceProviders (&%lu, %p) failed: %lu\n", dwBufferLen, pi, GetLastError ()); - free (pi); - WSACleanup (); - return 7; - } - } - else - { - fprintf (stderr, "WSAEnumNameSpaceProviders (&%lu, %p) failed: %lu\n", dwBufferLen, pi, GetLastError ()); - free (pi); - WSACleanup (); - return 8; + p_count = WSAEnumNameSpaceProviders(&dwBufferLen, pi); + if (SOCKET_ERROR == p_count) + { + fprintf(stderr, "WSAEnumNameSpaceProviders (&%lu, %p) failed: %lu\n", dwBufferLen, pi, GetLastError()); + free(pi); + WSACleanup(); + return 7; + } + } + else + { + fprintf(stderr, "WSAEnumNameSpaceProviders (&%lu, %p) failed: %lu\n", dwBufferLen, pi, GetLastError()); + free(pi); + WSACleanup(); + return 8; + } } - } - for (i= 0; i < p_count; i++) - { - if (IsEqualGUID (&pi[i].NSProviderId, &id)) + for (i = 0; i < p_count; i++) { - fprintf (stderr, "GNUnet DNS provider is already installed\n"); - free (pi); - WSACleanup (); - return 0; + if (IsEqualGUID(&pi[i].NSProviderId, &id)) + { + fprintf(stderr, "GNUnet DNS provider is already installed\n"); + free(pi); + WSACleanup(); + return 0; + } } - } - free (pi); + free(pi); - cmdl = GetCommandLineW (); + cmdl = GetCommandLineW(); if (cmdl == NULL) - { - WSACleanup (); - return 2; - } - wargv = CommandLineToArgvW (cmdl, &wargc); + { + WSACleanup(); + return 2; + } + wargv = CommandLineToArgvW(cmdl, &wargc); if (wargv == NULL) - { - WSACleanup (); - return 3; - } + { + WSACleanup(); + return 3; + } r = 4; if (wargc == 2) - { - ret = WSCInstallNameSpace (L"GNUnet DNS provider", wargv[1], NS_DNS, 0, &id); - if (ret == NO_ERROR) - { - fprintf (stderr, "Installed GNUnet DNS provider\n"); - r = 0; - } - else { - r = 1; - fprintf (stderr, - "WSCInstallNameSpace (L\"GNUnet DNS provider\", \"%S\", %d, 0, %p) failed: %lu\n", - wargv[1], NS_DNS, &id, GetLastError ()); + ret = WSCInstallNameSpace(L"GNUnet DNS provider", wargv[1], NS_DNS, 0, &id); + if (ret == NO_ERROR) + { + fprintf(stderr, "Installed GNUnet DNS provider\n"); + r = 0; + } + else + { + r = 1; + fprintf(stderr, + "WSCInstallNameSpace (L\"GNUnet DNS provider\", \"%S\", %d, 0, %p) failed: %lu\n", + wargv[1], NS_DNS, &id, GetLastError()); + } } - } else - fprintf (stderr, "Usage: %S \n", wargv[0]); - WSACleanup (); + fprintf(stderr, "Usage: %S \n", wargv[0]); + WSACleanup(); return r; } diff --git a/src/gns/w32nsp-resolve.c b/src/gns/w32nsp-resolve.c index 841f5b9e6..ad0fd3586 100644 --- a/src/gns/w32nsp-resolve.c +++ b/src/gns/w32nsp-resolve.c @@ -11,19 +11,19 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/w32nsp-resolve.c * @brief W32 integration for GNS * @author LRN */ /* Instead of including gnunet_common.h */ -#define GNUNET_memcpy(dst,src,n) do { if (0 != n) { (void) memcpy (dst,src,n); } } while (0) +#define GNUNET_memcpy(dst, src, n) do { if (0 != n) { (void)memcpy(dst, src, n); } } while (0) #include #include @@ -34,15 +34,15 @@ #include "gnunet_w32nsp_lib.h" #include -typedef int (WSPAPI *LPNSPSTARTUP) (LPGUID lpProviderId, LPNSP_ROUTINE lpnspRoutines); +typedef int (WSPAPI *LPNSPSTARTUP)(LPGUID lpProviderId, LPNSP_ROUTINE lpnspRoutines); -GUID host = {0x0002a800,0,0,{ 0xC0,0,0,0,0,0,0,0x46 }}; -GUID ip4 = {0x00090035,0,1,{ 0xc0,0,0,0,0,0,0,0x046}}; -GUID ip6 = {0x00090035,0,0x001c, { 0xc0,0,0,0,0,0,0,0x046}}; +GUID host = { 0x0002a800, 0, 0, { 0xC0, 0, 0, 0, 0, 0, 0, 0x46 } }; +GUID ip4 = { 0x00090035, 0, 1, { 0xc0, 0, 0, 0, 0, 0, 0, 0x046 } }; +GUID ip6 = { 0x00090035, 0, 0x001c, { 0xc0, 0, 0, 0, 0, 0, 0, 0x046 } }; DEFINE_GUID(W32_DNS, 0x22059D40, 0x7E9E, 0x11CF, 0xAE, 0x5A, 0x00, 0xAA, 0x00, 0xA7, 0x11, 0x2B); -#define DEFINE_DNS_GUID(a,x) DEFINE_GUID(a, 0x00090035, 0x0000, x, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46) +#define DEFINE_DNS_GUID(a, x) DEFINE_GUID(a, 0x00090035, 0x0000, x, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46) DEFINE_DNS_GUID(SVCID_DNS_TYPE_A, 0x0001); DEFINE_DNS_GUID(SVCID_DNS_TYPE_NS, 0x0002); DEFINE_DNS_GUID(SVCID_DNS_TYPE_CNAME, 0x0005); @@ -63,15 +63,15 @@ DEFINE_GUID(SVCID_INET_HOSTADDRBYNAME, 0x0002a803, 0x0000, 0x0000, 0xc0, 0x00, 0 VOID FixList(PCHAR ** List, PCHAR Base) { - if(*List) + if (*List) { - PCHAR * Addr; + PCHAR * Addr; - Addr = *List = (PCHAR *)( ((DWORD)*List + Base) ); - while(*Addr) + Addr = *List = (PCHAR *)(((DWORD)*List + Base)); + while (*Addr) { - *Addr = (PCHAR)(((DWORD)*Addr + Base)); - Addr++; + *Addr = (PCHAR)(((DWORD)*Addr + Base)); + Addr++; } } } @@ -84,82 +84,92 @@ FixList(PCHAR ** List, PCHAR Base) VOID UnpackHostEnt(struct hostent * hostent) { - PCHAR pch; + PCHAR pch; - pch = (PCHAR)hostent; + pch = (PCHAR)hostent; - if(hostent->h_name) - { - hostent->h_name = (PCHAR)((DWORD)hostent->h_name + pch); - } - FixList(&hostent->h_aliases, pch); - FixList(&hostent->h_addr_list, pch); + if (hostent->h_name) + { + hostent->h_name = (PCHAR)((DWORD)hostent->h_name + pch); + } + FixList(&hostent->h_aliases, pch); + FixList(&hostent->h_addr_list, pch); } static void -print_hostent (struct hostent *he) +print_hostent(struct hostent *he) { int i; char **pAlias; printf("\tOfficial name: %s\n", he->h_name); - for (i=0, pAlias = he->h_aliases; *pAlias != 0; pAlias++) { + for (i = 0, pAlias = he->h_aliases; *pAlias != 0; pAlias++) + { printf("\tAlternate name #%d: %s\n", ++i, *pAlias); - } + } printf("\tAddress type: "); - switch (he->h_addrtype) { - case AF_INET: + switch (he->h_addrtype) + { + case AF_INET: printf("AF_INET\n"); break; - case AF_INET6: + + case AF_INET6: printf("AF_INET6\n"); break; - case AF_NETBIOS: + + case AF_NETBIOS: printf("AF_NETBIOS\n"); break; - default: + + default: printf(" %d\n", he->h_addrtype); break; - } + } printf("\tAddress length: %d\n", he->h_length); - if (he->h_addrtype == AF_INET) { - struct sockaddr_in addr; - memset (&addr, 0, sizeof (addr)); - addr.sin_family = AF_INET; - addr.sin_port = 0; - i = 0; - while (he->h_addr_list[i] != 0) { - char buf[1024]; - DWORD buflen = 1024; - addr.sin_addr = *(struct in_addr *) he->h_addr_list[i++]; - if (NO_ERROR == WSAAddressToStringA ((LPSOCKADDR) &addr, sizeof (addr), NULL, buf, &buflen)) - printf("\tIPv4 Address #%d: %s\n", i, buf); - else - printf("\tIPv4 Address #%d: Can't convert: %lu\n", i, GetLastError ()); + if (he->h_addrtype == AF_INET) + { + struct sockaddr_in addr; + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_port = 0; + i = 0; + while (he->h_addr_list[i] != 0) + { + char buf[1024]; + DWORD buflen = 1024; + addr.sin_addr = *(struct in_addr *)he->h_addr_list[i++]; + if (NO_ERROR == WSAAddressToStringA((LPSOCKADDR)&addr, sizeof(addr), NULL, buf, &buflen)) + printf("\tIPv4 Address #%d: %s\n", i, buf); + else + printf("\tIPv4 Address #%d: Can't convert: %lu\n", i, GetLastError()); + } } - } else if (he->h_addrtype == AF_INET6) { - struct sockaddr_in6 addr; - memset (&addr, 0, sizeof (addr)); - addr.sin6_family = AF_INET6; - addr.sin6_port = 0; - i = 0; - while (he->h_addr_list[i] != 0) { - char buf[1024]; - DWORD buflen = 1024; - addr.sin6_addr = *(struct in6_addr *) he->h_addr_list[i++]; - if (NO_ERROR == WSAAddressToStringA ((LPSOCKADDR) &addr, sizeof (addr), NULL, buf, &buflen)) - printf("\tIPv6 Address #%d: %s\n", i, buf); - else - printf("\tIPv6 Address #%d: Can't convert: %lu\n", i, GetLastError ()); + else if (he->h_addrtype == AF_INET6) + { + struct sockaddr_in6 addr; + memset(&addr, 0, sizeof(addr)); + addr.sin6_family = AF_INET6; + addr.sin6_port = 0; + i = 0; + while (he->h_addr_list[i] != 0) + { + char buf[1024]; + DWORD buflen = 1024; + addr.sin6_addr = *(struct in6_addr *)he->h_addr_list[i++]; + if (NO_ERROR == WSAAddressToStringA((LPSOCKADDR)&addr, sizeof(addr), NULL, buf, &buflen)) + printf("\tIPv6 Address #%d: %s\n", i, buf); + else + printf("\tIPv6 Address #%d: Can't convert: %lu\n", i, GetLastError()); + } } - } } int -main (int argc, char **argv) +main(int argc, char **argv) { int ret; int r = 1; @@ -170,277 +180,285 @@ main (int argc, char **argv) int wargc; wchar_t **wargv; - if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) - { - fprintf (stderr, "WSAStartup() failed: %lu\n", GetLastError()); - return 5; - } + if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) + { + fprintf(stderr, "WSAStartup() failed: %lu\n", GetLastError()); + return 5; + } - cmdl = GetCommandLineW (); + cmdl = GetCommandLineW(); if (cmdl == NULL) - { - WSACleanup(); - return 2; - } - wargv = CommandLineToArgvW (cmdl, &wargc); + { + WSACleanup(); + return 2; + } + wargv = CommandLineToArgvW(cmdl, &wargc); if (wargv == NULL) - { - WSACleanup(); - return 3; - } + { + WSACleanup(); + return 3; + } r = 4; if (wargc == 5) - { - if (wcscmp (wargv[1], L"A") == 0) - sc = SVCID_DNS_TYPE_A; - else if (wcscmp (wargv[1], L"AAAA") == 0) - sc = SVCID_DNS_TYPE_AAAA; - else if (wcscmp (wargv[1], L"name") == 0) - sc = SVCID_HOSTNAME; - else if (wcscmp (wargv[1], L"addr") == 0) - sc = SVCID_INET_HOSTADDRBYNAME; - else - wargc -= 1; - if (wcscmp (wargv[4], L"mswdns") == 0) - prov = W32_DNS; - else if (wcscmp (wargv[4], L"gnunetdns") == 0) - prov = GNUNET_NAMESPACE_PROVIDER_DNS; - else - wargc -= 1; - } + { + if (wcscmp(wargv[1], L"A") == 0) + sc = SVCID_DNS_TYPE_A; + else if (wcscmp(wargv[1], L"AAAA") == 0) + sc = SVCID_DNS_TYPE_AAAA; + else if (wcscmp(wargv[1], L"name") == 0) + sc = SVCID_HOSTNAME; + else if (wcscmp(wargv[1], L"addr") == 0) + sc = SVCID_INET_HOSTADDRBYNAME; + else + wargc -= 1; + if (wcscmp(wargv[4], L"mswdns") == 0) + prov = W32_DNS; + else if (wcscmp(wargv[4], L"gnunetdns") == 0) + prov = GNUNET_NAMESPACE_PROVIDER_DNS; + else + wargc -= 1; + } else if (wargc == 3) - { - } + { + } else - { - fprintf (stderr, "Usage: %S \n" - "record type - one of the following: A | AAAA | name | addr\n" - "service name - a string to resolve; \" \" (a space) means 'blank'\n" - "NSP library path - path to libw32nsp\n" - "NSP id - one of the following: mswdns | gnunetdns\n", - wargv[0]); - } - - if (wargc == 5) - { - HMODULE nsp; - - nsp = LoadLibraryW (wargv[3]); - if (nsp == NULL) { - fprintf (stderr, "Failed to load library `%S'\n", wargv[3]); + fprintf(stderr, "Usage: %S \n" + "record type - one of the following: A | AAAA | name | addr\n" + "service name - a string to resolve; \" \" (a space) means 'blank'\n" + "NSP library path - path to libw32nsp\n" + "NSP id - one of the following: mswdns | gnunetdns\n", + wargv[0]); } - else + + if (wargc == 5) { - LPNSPSTARTUP startup = (LPNSPSTARTUP) GetProcAddress (nsp, "NSPStartup"); - if (startup == NULL) - startup = (LPNSPSTARTUP) GetProcAddress (nsp, "NSPStartup@8"); - if (startup != NULL) - { - NSP_ROUTINE api; - api.cbSize = sizeof (api); - ret = startup (&prov, &api); - if (NO_ERROR != ret) - fprintf (stderr, "startup failed: %lu\n", GetLastError ()); - else + HMODULE nsp; + + nsp = LoadLibraryW(wargv[3]); + if (nsp == NULL) { - HANDLE lookup; - WSAQUERYSETW search; - char buf[4096]; - WSAQUERYSETW *result = (WSAQUERYSETW *) buf; - DWORD resultsize; - DWORD err; - memset (&search, 0, sizeof (search)); - search.dwSize = sizeof (search); - search.lpszServiceInstanceName = (wcscmp (wargv[2], L" ") == 0) ? NULL : wargv[2]; - search.lpServiceClassId = ≻ - search.lpNSProviderId = &prov; - search.dwNameSpace = NS_ALL; - ret = api.NSPLookupServiceBegin (&prov, &search, NULL, LUP_RETURN_ALL, &lookup); - if (ret != NO_ERROR) - { - fprintf (stderr, "lookup start failed\n"); - } - else - { - resultsize = 4096; - ret = api.NSPLookupServiceNext (lookup, LUP_RETURN_ALL, &resultsize, result); - err = GetLastError (); - if (ret != NO_ERROR) - { - fprintf (stderr, "lookup next failed: %lu\n", err); - } - else + fprintf(stderr, "Failed to load library `%S'\n", wargv[3]); + } + else + { + LPNSPSTARTUP startup = (LPNSPSTARTUP)GetProcAddress(nsp, "NSPStartup"); + if (startup == NULL) + startup = (LPNSPSTARTUP)GetProcAddress(nsp, "NSPStartup@8"); + if (startup != NULL) { - int i; - printf ("Got result:\n"); - printf (" lpszServiceInstanceName: %S\n", result->lpszServiceInstanceName ? result->lpszServiceInstanceName : L"NULL"); - if (result->lpServiceClassId) - printf (" lpServiceClassId: { 0x%08lX,0x%04X,0x%04X, { 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X } }\n", - result->lpServiceClassId->Data1, result->lpServiceClassId->Data2, result->lpServiceClassId->Data3, result->lpServiceClassId->Data4[0], - result->lpServiceClassId->Data4[1], result->lpServiceClassId->Data4[2], result->lpServiceClassId->Data4[3], result->lpServiceClassId->Data4[4], - result->lpServiceClassId->Data4[5], result->lpServiceClassId->Data4[6], result->lpServiceClassId->Data4[7]); - else - printf (" lpServiceClassId: NULL\n"); - if (result->lpVersion) - printf (" lpVersion: 0x%08lX, %d\n", result->lpVersion->dwVersion, result->lpVersion->ecHow); + NSP_ROUTINE api; + api.cbSize = sizeof(api); + ret = startup(&prov, &api); + if (NO_ERROR != ret) + fprintf(stderr, "startup failed: %lu\n", GetLastError()); else - printf (" lpVersion: NULL\n"); - printf (" lpszComment: %S\n", result->lpszComment ? result->lpszComment : L"NULL"); - printf (" dwNameSpace: %lu\n", result->dwNameSpace); - if (result->lpNSProviderId) - printf (" lpNSProviderId: { 0x%08lX,0x%04X,0x%04X, { 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X } }\n", - result->lpNSProviderId->Data1, result->lpNSProviderId->Data2, result->lpNSProviderId->Data3, result->lpNSProviderId->Data4[0], - result->lpNSProviderId->Data4[1], result->lpNSProviderId->Data4[2], result->lpNSProviderId->Data4[3], result->lpNSProviderId->Data4[4], - result->lpNSProviderId->Data4[5], result->lpNSProviderId->Data4[6], result->lpNSProviderId->Data4[7]); - else - printf (" lpNSProviderId: NULL\n"); - printf (" lpszContext: %S\n", result->lpszContext ? result->lpszContext : L"NULL"); - printf (" dwNumberOfProtocols: %lu\n", result->dwNumberOfProtocols); - printf (" lpszQueryString: %S\n", result->lpszQueryString ? result->lpszQueryString : L"NULL"); - printf (" dwNumberOfCsAddrs: %lu\n", result->dwNumberOfCsAddrs); - for (i = 0; i < result->dwNumberOfCsAddrs; i++) - { - switch (result->lpcsaBuffer[i].iSocketType) { - case SOCK_STREAM: - printf (" %d: iSocketType = SOCK_STREAM\n", i); - break; - case SOCK_DGRAM: - printf (" %d: iSocketType = SOCK_DGRAM\n", i); - break; - default: - printf (" %d: iSocketType = %d\n", i, result->lpcsaBuffer[i].iSocketType); - } - switch (result->lpcsaBuffer[i].iProtocol) - { - case IPPROTO_TCP: - printf (" %d: iProtocol = IPPROTO_TCP\n", i); - break; - case IPPROTO_UDP: - printf (" %d: iProtocol = IPPROTO_UDP\n", i); - break; - default: - printf (" %d: iProtocol = %d\n", i, result->lpcsaBuffer[i].iProtocol); - } - switch (result->lpcsaBuffer[i].LocalAddr.lpSockaddr->sa_family) - { - case AF_INET: - printf (" %d: loc family = AF_INET\n", i); - break; - case AF_INET6: - printf (" %d: loc family = AF_INET6\n", i); - break; - default: - printf (" %d: loc family = %hu\n", i, result->lpcsaBuffer[i].LocalAddr.lpSockaddr->sa_family); - } - switch (result->lpcsaBuffer[i].RemoteAddr.lpSockaddr->sa_family) - { - case AF_INET: - printf (" %d: rem family = AF_INET\n", i); - break; - case AF_INET6: - printf (" %d: rem family = AF_INET6\n", i); - break; - default: - printf (" %d: rem family = %hu\n", i, result->lpcsaBuffer[i].RemoteAddr.lpSockaddr->sa_family); - } - char buf[1024]; - DWORD buflen = 1024; - if (NO_ERROR == WSAAddressToStringA (result->lpcsaBuffer[i].LocalAddr.lpSockaddr, result->lpcsaBuffer[i].LocalAddr.iSockaddrLength, NULL, buf, &buflen)) - printf("\tLocal Address #%d: %s\n", i, buf); - else - printf("\tLocal Address #%d: Can't convert: %lu\n", i, GetLastError ()); - buflen = 1024; - if (NO_ERROR == WSAAddressToStringA (result->lpcsaBuffer[i].RemoteAddr.lpSockaddr, result->lpcsaBuffer[i].RemoteAddr.iSockaddrLength, NULL, buf, &buflen)) - printf("\tRemote Address #%d: %s\n", i, buf); - else - printf("\tRemote Address #%d: Can't convert: %lu\n", i, GetLastError ()); - } - printf (" dwOutputFlags: 0x%08lX\n", result->dwOutputFlags); - printf (" lpBlob: 0x%p\n", result->lpBlob); - if (result->lpBlob) - { - struct hostent *he = malloc (result->lpBlob->cbSize); - if (he != NULL) - { - GNUNET_memcpy (he, result->lpBlob->pBlobData, result->lpBlob->cbSize); - UnpackHostEnt (he); - print_hostent (he); - free (he); + HANDLE lookup; + WSAQUERYSETW search; + char buf[4096]; + WSAQUERYSETW *result = (WSAQUERYSETW *)buf; + DWORD resultsize; + DWORD err; + memset(&search, 0, sizeof(search)); + search.dwSize = sizeof(search); + search.lpszServiceInstanceName = (wcscmp(wargv[2], L" ") == 0) ? NULL : wargv[2]; + search.lpServiceClassId = ≻ + search.lpNSProviderId = &prov; + search.dwNameSpace = NS_ALL; + ret = api.NSPLookupServiceBegin(&prov, &search, NULL, LUP_RETURN_ALL, &lookup); + if (ret != NO_ERROR) + { + fprintf(stderr, "lookup start failed\n"); + } + else + { + resultsize = 4096; + ret = api.NSPLookupServiceNext(lookup, LUP_RETURN_ALL, &resultsize, result); + err = GetLastError(); + if (ret != NO_ERROR) + { + fprintf(stderr, "lookup next failed: %lu\n", err); + } + else + { + int i; + printf("Got result:\n"); + printf(" lpszServiceInstanceName: %S\n", result->lpszServiceInstanceName ? result->lpszServiceInstanceName : L"NULL"); + if (result->lpServiceClassId) + printf(" lpServiceClassId: { 0x%08lX,0x%04X,0x%04X, { 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X } }\n", + result->lpServiceClassId->Data1, result->lpServiceClassId->Data2, result->lpServiceClassId->Data3, result->lpServiceClassId->Data4[0], + result->lpServiceClassId->Data4[1], result->lpServiceClassId->Data4[2], result->lpServiceClassId->Data4[3], result->lpServiceClassId->Data4[4], + result->lpServiceClassId->Data4[5], result->lpServiceClassId->Data4[6], result->lpServiceClassId->Data4[7]); + else + printf(" lpServiceClassId: NULL\n"); + if (result->lpVersion) + printf(" lpVersion: 0x%08lX, %d\n", result->lpVersion->dwVersion, result->lpVersion->ecHow); + else + printf(" lpVersion: NULL\n"); + printf(" lpszComment: %S\n", result->lpszComment ? result->lpszComment : L"NULL"); + printf(" dwNameSpace: %lu\n", result->dwNameSpace); + if (result->lpNSProviderId) + printf(" lpNSProviderId: { 0x%08lX,0x%04X,0x%04X, { 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X } }\n", + result->lpNSProviderId->Data1, result->lpNSProviderId->Data2, result->lpNSProviderId->Data3, result->lpNSProviderId->Data4[0], + result->lpNSProviderId->Data4[1], result->lpNSProviderId->Data4[2], result->lpNSProviderId->Data4[3], result->lpNSProviderId->Data4[4], + result->lpNSProviderId->Data4[5], result->lpNSProviderId->Data4[6], result->lpNSProviderId->Data4[7]); + else + printf(" lpNSProviderId: NULL\n"); + printf(" lpszContext: %S\n", result->lpszContext ? result->lpszContext : L"NULL"); + printf(" dwNumberOfProtocols: %lu\n", result->dwNumberOfProtocols); + printf(" lpszQueryString: %S\n", result->lpszQueryString ? result->lpszQueryString : L"NULL"); + printf(" dwNumberOfCsAddrs: %lu\n", result->dwNumberOfCsAddrs); + for (i = 0; i < result->dwNumberOfCsAddrs; i++) + { + switch (result->lpcsaBuffer[i].iSocketType) + { + case SOCK_STREAM: + printf(" %d: iSocketType = SOCK_STREAM\n", i); + break; + + case SOCK_DGRAM: + printf(" %d: iSocketType = SOCK_DGRAM\n", i); + break; + + default: + printf(" %d: iSocketType = %d\n", i, result->lpcsaBuffer[i].iSocketType); + } + switch (result->lpcsaBuffer[i].iProtocol) + { + case IPPROTO_TCP: + printf(" %d: iProtocol = IPPROTO_TCP\n", i); + break; + + case IPPROTO_UDP: + printf(" %d: iProtocol = IPPROTO_UDP\n", i); + break; + + default: + printf(" %d: iProtocol = %d\n", i, result->lpcsaBuffer[i].iProtocol); + } + switch (result->lpcsaBuffer[i].LocalAddr.lpSockaddr->sa_family) + { + case AF_INET: + printf(" %d: loc family = AF_INET\n", i); + break; + + case AF_INET6: + printf(" %d: loc family = AF_INET6\n", i); + break; + + default: + printf(" %d: loc family = %hu\n", i, result->lpcsaBuffer[i].LocalAddr.lpSockaddr->sa_family); + } + switch (result->lpcsaBuffer[i].RemoteAddr.lpSockaddr->sa_family) + { + case AF_INET: + printf(" %d: rem family = AF_INET\n", i); + break; + + case AF_INET6: + printf(" %d: rem family = AF_INET6\n", i); + break; + + default: + printf(" %d: rem family = %hu\n", i, result->lpcsaBuffer[i].RemoteAddr.lpSockaddr->sa_family); + } + char buf[1024]; + DWORD buflen = 1024; + if (NO_ERROR == WSAAddressToStringA(result->lpcsaBuffer[i].LocalAddr.lpSockaddr, result->lpcsaBuffer[i].LocalAddr.iSockaddrLength, NULL, buf, &buflen)) + printf("\tLocal Address #%d: %s\n", i, buf); + else + printf("\tLocal Address #%d: Can't convert: %lu\n", i, GetLastError()); + buflen = 1024; + if (NO_ERROR == WSAAddressToStringA(result->lpcsaBuffer[i].RemoteAddr.lpSockaddr, result->lpcsaBuffer[i].RemoteAddr.iSockaddrLength, NULL, buf, &buflen)) + printf("\tRemote Address #%d: %s\n", i, buf); + else + printf("\tRemote Address #%d: Can't convert: %lu\n", i, GetLastError()); + } + printf(" dwOutputFlags: 0x%08lX\n", result->dwOutputFlags); + printf(" lpBlob: 0x%p\n", result->lpBlob); + if (result->lpBlob) + { + struct hostent *he = malloc(result->lpBlob->cbSize); + if (he != NULL) + { + GNUNET_memcpy(he, result->lpBlob->pBlobData, result->lpBlob->cbSize); + UnpackHostEnt(he); + print_hostent(he); + free(he); + } + } + } + ret = api.NSPLookupServiceEnd(lookup); + if (ret != NO_ERROR) + printf("NSPLookupServiceEnd() failed: %lu\n", GetLastError()); + } + api.NSPCleanup(&prov); } - } } - ret = api.NSPLookupServiceEnd (lookup); - if (ret != NO_ERROR) - printf ("NSPLookupServiceEnd() failed: %lu\n", GetLastError ()); - } - api.NSPCleanup (&prov); + FreeLibrary(nsp); } - } - FreeLibrary (nsp); } - } else if (wargc == 3) - { - int s; - ADDRINFOW hints; - ADDRINFOW *result; - ADDRINFOW *pos; + { + int s; + ADDRINFOW hints; + ADDRINFOW *result; + ADDRINFOW *pos; - memset (&hints, 0, sizeof (struct addrinfo)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; - if (0 != (s = GetAddrInfoW (wargv[2], NULL, &hints, &result))) - { - fprintf (stderr, "Cound not resolve `%S' using GetAddrInfoW: %lu\n", - wargv[2], GetLastError ()); - } - else - { - for (pos = result; pos != NULL; pos = pos->ai_next) - { - wchar_t tmpbuf[1024]; - DWORD buflen = 1024; - if (0 == WSAAddressToStringW (pos->ai_addr, pos->ai_addrlen, NULL, tmpbuf, &buflen)) - fprintf (stderr, "Result:\n" - " flags: 0x%X\n" - " family: 0x%X\n" - " socktype: 0x%X\n" - " protocol: 0x%X\n" - " addrlen: %u\n" - " addr: %S\n" - " canonname: %S\n", - pos->ai_flags, - pos->ai_family, - pos->ai_socktype, - pos->ai_protocol, - pos->ai_addrlen, - tmpbuf, - pos->ai_canonname); - else - fprintf (stderr, "Result:\n" - " flags: 0x%X\n" - " family: 0x%X\n" - " socktype: 0x%X\n" - " protocol: 0x%X\n" - " addrlen: %u\n" - " addr: %S\n" - " canonname: %S\n", - pos->ai_flags, - pos->ai_family, - pos->ai_socktype, - pos->ai_protocol, - pos->ai_addrlen, - L"", - pos->ai_canonname); - } - if (NULL != result) - FreeAddrInfoW (result); + if (0 != (s = GetAddrInfoW(wargv[2], NULL, &hints, &result))) + { + fprintf(stderr, "Cound not resolve `%S' using GetAddrInfoW: %lu\n", + wargv[2], GetLastError()); + } + else + { + for (pos = result; pos != NULL; pos = pos->ai_next) + { + wchar_t tmpbuf[1024]; + DWORD buflen = 1024; + if (0 == WSAAddressToStringW(pos->ai_addr, pos->ai_addrlen, NULL, tmpbuf, &buflen)) + fprintf(stderr, "Result:\n" + " flags: 0x%X\n" + " family: 0x%X\n" + " socktype: 0x%X\n" + " protocol: 0x%X\n" + " addrlen: %u\n" + " addr: %S\n" + " canonname: %S\n", + pos->ai_flags, + pos->ai_family, + pos->ai_socktype, + pos->ai_protocol, + pos->ai_addrlen, + tmpbuf, + pos->ai_canonname); + else + fprintf(stderr, "Result:\n" + " flags: 0x%X\n" + " family: 0x%X\n" + " socktype: 0x%X\n" + " protocol: 0x%X\n" + " addrlen: %u\n" + " addr: %S\n" + " canonname: %S\n", + pos->ai_flags, + pos->ai_family, + pos->ai_socktype, + pos->ai_protocol, + pos->ai_addrlen, + L"", + pos->ai_canonname); + } + if (NULL != result) + FreeAddrInfoW(result); + } } - } WSACleanup(); return r; } diff --git a/src/gns/w32nsp-uninstall.c b/src/gns/w32nsp-uninstall.c index b2a9b083e..f5031f341 100644 --- a/src/gns/w32nsp-uninstall.c +++ b/src/gns/w32nsp-uninstall.c @@ -6,26 +6,26 @@ #include int -main (int argc, char **argv) +main(int argc, char **argv) { int ret; GUID id = GNUNET_NAMESPACE_PROVIDER_DNS; WSADATA wsd; - if (WSAStartup (MAKEWORD (2,2), &wsd) != 0) - { - fprintf (stderr, "WSAStartup () failed: %lu\n", GetLastError ()); - return 5; - } + if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) + { + fprintf(stderr, "WSAStartup () failed: %lu\n", GetLastError()); + return 5; + } - ret = WSCUnInstallNameSpace (&id); + ret = WSCUnInstallNameSpace(&id); if (ret == NO_ERROR) - { - fprintf (stderr, "Uninstalled GNUnet DNS provider\n"); - WSACleanup (); - return 0; - } - fprintf (stderr, "WSCUnInstallNameSpace () failed: %lu\n", GetLastError ()); - WSACleanup (); + { + fprintf(stderr, "Uninstalled GNUnet DNS provider\n"); + WSACleanup(); + return 0; + } + fprintf(stderr, "WSCUnInstallNameSpace () failed: %lu\n", GetLastError()); + WSACleanup(); return 1; } \ No newline at end of file diff --git a/src/gns/w32nsp.c b/src/gns/w32nsp.c index 56d07a50c..5178cb822 100644 --- a/src/gns/w32nsp.c +++ b/src/gns/w32nsp.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gns/w32nsp.c * @brief W32 integration for GNS @@ -32,7 +32,7 @@ #endif #if VERBOSE # define __printf__ printf -# define DEBUGLOG(s, ...) printf (s, ##__VA_ARGS__) +# define DEBUGLOG(s, ...) printf(s, ## __VA_ARGS__) #endif #include @@ -80,8 +80,7 @@ static CRITICAL_SECTION records_cs; -struct record -{ +struct record { SOCKET s; DWORD flags; uint8_t state; @@ -94,58 +93,60 @@ static size_t records_len = 0; static size_t records_size = 0; static int -resize_records () +resize_records() { size_t new_size = records_len > 0 ? records_len * 2 : 5; - struct record *new_records = malloc (new_size * sizeof (struct record)); + struct record *new_records = malloc(new_size * sizeof(struct record)); + if (new_records == NULL) - { - SetLastError (WSA_NOT_ENOUGH_MEMORY); - return 0; - } - GNUNET_memcpy (new_records, records, records_len * sizeof (struct record)); - memset (&new_records[records_len], 0, sizeof (struct record) * (new_size - records_len)); + { + SetLastError(WSA_NOT_ENOUGH_MEMORY); + return 0; + } + GNUNET_memcpy(new_records, records, records_len * sizeof(struct record)); + memset(&new_records[records_len], 0, sizeof(struct record) * (new_size - records_len)); records_size = new_size; - free (records); + free(records); records = new_records; return 1; } static int -add_record (SOCKET s, const wchar_t *name, DWORD flags) +add_record(SOCKET s, const wchar_t *name, DWORD flags) { int res = 1; int i; int empty = -1; + //EnterCriticalSection (&records_cs); for (i = 0; i < records_len; i++) if (records[i].state == 0) break; empty = i; if (i == records_len) - { - res = resize_records (); - if (res) - empty = records_len++; - } + { + res = resize_records(); + if (res) + empty = records_len++; + } if (res) - { - struct record r; - r.s = s; - r.flags = flags; - r.name = (wchar_t *) name; - r.state = 1; - r.buf = NULL; - if (name) - r.name = wcsdup (name); - records[empty] = r; - } + { + struct record r; + r.s = s; + r.flags = flags; + r.name = (wchar_t *)name; + r.state = 1; + r.buf = NULL; + if (name) + r.name = wcsdup(name); + records[empty] = r; + } //LeaveCriticalSection (&records_cs); return res; } /* These are not defined by mingw.org headers at the moment*/ -typedef INT (WSPAPI *LPNSPIOCTL) (HANDLE,DWORD,LPVOID,DWORD,LPVOID,DWORD,LPDWORD,LPWSACOMPLETION,LPWSATHREADID); +typedef INT (WSPAPI *LPNSPIOCTL)(HANDLE, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPWSACOMPLETION, LPWSATHREADID); typedef struct _NSP_ROUTINE_XP { DWORD cbSize; DWORD dwMajorVersion; @@ -162,39 +163,39 @@ typedef struct _NSP_ROUTINE_XP { } NSP_ROUTINE_XP; static SOCKET -connect_to_dns_resolver () +connect_to_dns_resolver() { struct sockaddr_in addr; SOCKET r; int ret; - r = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); + r = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == r) - { - SetLastError (16004); - return r; - } + { + SetLastError(16004); + return r; + } addr.sin_family = AF_INET; - addr.sin_port = htons (5353); /* TCP 5353 is not registered; UDP 5353 is */ - addr.sin_addr.s_addr = inet_addr ("127.0.0.1"); + addr.sin_port = htons(5353); /* TCP 5353 is not registered; UDP 5353 is */ + addr.sin_addr.s_addr = inet_addr("127.0.0.1"); - ret = connect (r, (struct sockaddr *) &addr, sizeof (addr)); + ret = connect(r, (struct sockaddr *)&addr, sizeof(addr)); if (SOCKET_ERROR == ret) - { - DWORD err = GetLastError (); - closesocket (r); - SetLastError (err); - SetLastError (16005); - r = INVALID_SOCKET; - } + { + DWORD err = GetLastError(); + closesocket(r); + SetLastError(err); + SetLastError(16005); + r = INVALID_SOCKET; + } return r; } static int -send_name_to_ip_request (LPWSAQUERYSETW lpqsRestrictions, - LPWSASERVICECLASSINFOW lpServiceClassInfo, DWORD dwControlFlags, - SOCKET *resolver) +send_name_to_ip_request(LPWSAQUERYSETW lpqsRestrictions, + LPWSASERVICECLASSINFOW lpServiceClassInfo, DWORD dwControlFlags, + SOCKET *resolver) { struct GNUNET_W32RESOLVER_GetMessage *msg; int af4 = 0; @@ -202,91 +203,95 @@ send_name_to_ip_request (LPWSAQUERYSETW lpqsRestrictions, char *buf; int ret = 1; int i; - size_t size = sizeof (struct GNUNET_W32RESOLVER_GetMessage); + size_t size = sizeof(struct GNUNET_W32RESOLVER_GetMessage); size_t namelen = 0; + if (lpqsRestrictions->lpszServiceInstanceName) - namelen = sizeof (wchar_t) * (wcslen (lpqsRestrictions->lpszServiceInstanceName) + 1); + namelen = sizeof(wchar_t) * (wcslen(lpqsRestrictions->lpszServiceInstanceName) + 1); size += namelen; - buf = malloc (size); - msg = (struct GNUNET_W32RESOLVER_GetMessage *) buf; - msg->header.size = htons (size); - msg->header.type = htons (GNUNET_MESSAGE_TYPE_W32RESOLVER_REQUEST); + buf = malloc(size); + msg = (struct GNUNET_W32RESOLVER_GetMessage *)buf; + msg->header.size = htons(size); + msg->header.type = htons(GNUNET_MESSAGE_TYPE_W32RESOLVER_REQUEST); if (lpqsRestrictions->dwNumberOfProtocols > 0) - { - int i; - for (i = 0; i < lpqsRestrictions->dwNumberOfProtocols; i++) { - if (lpqsRestrictions->lpafpProtocols[0].iAddressFamily == AF_INET) - af4 = 1; - if (lpqsRestrictions->lpafpProtocols[0].iAddressFamily == AF_INET6) - af6 = 1; + int i; + for (i = 0; i < lpqsRestrictions->dwNumberOfProtocols; i++) + { + if (lpqsRestrictions->lpafpProtocols[0].iAddressFamily == AF_INET) + af4 = 1; + if (lpqsRestrictions->lpafpProtocols[0].iAddressFamily == AF_INET6) + af6 = 1; + } } - } if (af4 && !af6) - msg->af = htonl (AF_INET); + msg->af = htonl(AF_INET); else if (af6 && !af4) - msg->af = htonl (AF_INET6); + msg->af = htonl(AF_INET6); else - msg->af = htonl (AF_UNSPEC); + msg->af = htonl(AF_UNSPEC); if (lpqsRestrictions->lpszServiceInstanceName) - GNUNET_memcpy (&msg[1], lpqsRestrictions->lpszServiceInstanceName, namelen); - msg->sc_data1 = htonl (lpqsRestrictions->lpServiceClassId->Data1); - msg->sc_data2 = htons (lpqsRestrictions->lpServiceClassId->Data2); - msg->sc_data3 = htons (lpqsRestrictions->lpServiceClassId->Data3); + GNUNET_memcpy(&msg[1], lpqsRestrictions->lpszServiceInstanceName, namelen); + msg->sc_data1 = htonl(lpqsRestrictions->lpServiceClassId->Data1); + msg->sc_data2 = htons(lpqsRestrictions->lpServiceClassId->Data2); + msg->sc_data3 = htons(lpqsRestrictions->lpServiceClassId->Data3); for (i = 0; i < 8; i++) msg->sc_data4[i] = lpqsRestrictions->lpServiceClassId->Data4[i]; - *resolver = connect_to_dns_resolver (); + *resolver = connect_to_dns_resolver(); if (*resolver != INVALID_SOCKET) - { - if (size != send (*resolver, buf, size, 0)) { + if (size != send(*resolver, buf, size, 0)) + { #if VERBOSE - DWORD err = GetLastError (); + DWORD err = GetLastError(); #endif - closesocket (*resolver); - *resolver = INVALID_SOCKET; - DEBUGLOG ("GNUNET_W32NSP_LookupServiceBegin: failed to send request: %lu\n", err); - SetLastError (WSATRY_AGAIN); - ret = 0; + closesocket(*resolver); + *resolver = INVALID_SOCKET; + DEBUGLOG("GNUNET_W32NSP_LookupServiceBegin: failed to send request: %lu\n", err); + SetLastError(WSATRY_AGAIN); + ret = 0; + } } - } else ret = 0; - free (buf); + free(buf); return ret; } static int WSPAPI -NSPCleanup (LPGUID lpProviderId) +NSPCleanup(LPGUID lpProviderId) { - DEBUGLOG ("NSPCleanup\n"); - if (IsEqualGUID (lpProviderId, &GNUNET_NAMESPACE_PROVIDER_DNS)) - { - return NO_ERROR; - } - SetLastError (WSAEINVALIDPROVIDER); + DEBUGLOG("NSPCleanup\n"); + if (IsEqualGUID(lpProviderId, &GNUNET_NAMESPACE_PROVIDER_DNS)) + { + return NO_ERROR; + } + SetLastError(WSAEINVALIDPROVIDER); return SOCKET_ERROR; } BOOL WINAPI -DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) +DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) - { + { case DLL_PROCESS_ATTACH: - if (!InitializeCriticalSectionAndSpinCount (&records_cs, 0x00000400)) - { - return FALSE; - } + if (!InitializeCriticalSectionAndSpinCount(&records_cs, 0x00000400)) + { + return FALSE; + } break; + case DLL_THREAD_ATTACH: break; + case DLL_THREAD_DETACH: break; + case DLL_PROCESS_DETACH: - DeleteCriticalSection (&records_cs); + DeleteCriticalSection(&records_cs); break; - } + } return TRUE; } @@ -294,374 +299,375 @@ DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) static int WSPAPI -GNUNET_W32NSP_LookupServiceBegin (LPGUID lpProviderId, LPWSAQUERYSETW lpqsRestrictions, - LPWSASERVICECLASSINFOW lpServiceClassInfo, DWORD dwControlFlags, - LPHANDLE lphLookup) +GNUNET_W32NSP_LookupServiceBegin(LPGUID lpProviderId, LPWSAQUERYSETW lpqsRestrictions, + LPWSASERVICECLASSINFOW lpServiceClassInfo, DWORD dwControlFlags, + LPHANDLE lphLookup) { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceBegin\n"); - if (IsEqualGUID (lpProviderId, &GNUNET_NAMESPACE_PROVIDER_DNS)) - { - SOCKET s; - if (lpqsRestrictions->dwNameSpace != NS_DNS && lpqsRestrictions->dwNameSpace != NS_ALL) + DEBUGLOG("GNUNET_W32NSP_LookupServiceBegin\n"); + if (IsEqualGUID(lpProviderId, &GNUNET_NAMESPACE_PROVIDER_DNS)) { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceBegin: wrong namespace\n"); - SetLastError (WSAEINVAL); + SOCKET s; + if (lpqsRestrictions->dwNameSpace != NS_DNS && lpqsRestrictions->dwNameSpace != NS_ALL) + { + DEBUGLOG("GNUNET_W32NSP_LookupServiceBegin: wrong namespace\n"); + SetLastError(WSAEINVAL); + return SOCKET_ERROR; + } + if (lpqsRestrictions->lpszServiceInstanceName != NULL) + { + wchar_t *s = lpqsRestrictions->lpszServiceInstanceName; + size_t len = wcslen(s); + if (len >= 5 && wcscmp(&s[len - 5], L".zkey") == 0) + { + } + else if (len >= 4 && wcscmp(&s[len - 4], L".gnu") == 0) + { + } + else + { + DEBUGLOG("GNUNET_W32NSP_LookupServiceBegin: unsupported TLD\n"); + SetLastError(WSAEINVAL); + return SOCKET_ERROR; + } + } + + if (send_name_to_ip_request(lpqsRestrictions, + lpServiceClassInfo, dwControlFlags, &s)) + { + if (!(add_record(s, lpqsRestrictions->lpszServiceInstanceName, dwControlFlags))) + { + DWORD err = GetLastError(); + DEBUGLOG("GNUNET_W32NSP_LookupServiceBegin: failed to add a record\n"); + closesocket(s); + SetLastError(err); + return SOCKET_ERROR; + } + *lphLookup = (HANDLE)s; + DEBUGLOG("GNUNET_W32NSP_LookupServiceBegin: OK (%lu)\n", GetLastError()); + return NO_ERROR; + } return SOCKET_ERROR; } - if (lpqsRestrictions->lpszServiceInstanceName != NULL) - { - wchar_t *s = lpqsRestrictions->lpszServiceInstanceName; - size_t len = wcslen (s); - if (len >= 5 && wcscmp (&s[len - 5], L".zkey") == 0) - { - } - else if (len >= 4 && wcscmp (&s[len - 4], L".gnu") == 0) - { - } - else - { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceBegin: unsupported TLD\n"); - SetLastError (WSAEINVAL); - return SOCKET_ERROR; - } - } - - if (send_name_to_ip_request (lpqsRestrictions, - lpServiceClassInfo, dwControlFlags, &s)) - { - if (!(add_record (s, lpqsRestrictions->lpszServiceInstanceName, dwControlFlags))) - { - DWORD err = GetLastError (); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceBegin: failed to add a record\n"); - closesocket (s); - SetLastError (err); - return SOCKET_ERROR; - } - *lphLookup = (HANDLE) s; - DEBUGLOG ("GNUNET_W32NSP_LookupServiceBegin: OK (%lu)\n", GetLastError ()); - return NO_ERROR; - } - return SOCKET_ERROR; - } - DEBUGLOG ("GNUNET_W32NSP_LookupServiceBegin: wrong provider\n"); - SetLastError (WSAEINVALIDPROVIDER); + DEBUGLOG("GNUNET_W32NSP_LookupServiceBegin: wrong provider\n"); + SetLastError(WSAEINVALIDPROVIDER); return SOCKET_ERROR; } #define UnmarshallPtr(ptr, ptrtype, base) \ if (ptr) \ - ptr = (ptrtype *) (base + (uintptr_t) ptr) + ptr = (ptrtype *) (base + (uintptr_t)ptr) static void -UnmarshallWSAQUERYSETW (LPWSAQUERYSETW req) +UnmarshallWSAQUERYSETW(LPWSAQUERYSETW req) { int i; - char *base = (char *) req; - UnmarshallPtr (req->lpszServiceInstanceName, wchar_t, base); - UnmarshallPtr (req->lpServiceClassId, GUID, base); - UnmarshallPtr (req->lpVersion, WSAVERSION, base); - UnmarshallPtr (req->lpszComment, wchar_t, base); - UnmarshallPtr (req->lpNSProviderId, GUID, base); - UnmarshallPtr (req->lpszContext, wchar_t, base); - UnmarshallPtr (req->lpafpProtocols, AFPROTOCOLS, base); - UnmarshallPtr (req->lpszQueryString, wchar_t, base); - UnmarshallPtr (req->lpcsaBuffer, CSADDR_INFO, base); + char *base = (char *)req; + + UnmarshallPtr(req->lpszServiceInstanceName, wchar_t, base); + UnmarshallPtr(req->lpServiceClassId, GUID, base); + UnmarshallPtr(req->lpVersion, WSAVERSION, base); + UnmarshallPtr(req->lpszComment, wchar_t, base); + UnmarshallPtr(req->lpNSProviderId, GUID, base); + UnmarshallPtr(req->lpszContext, wchar_t, base); + UnmarshallPtr(req->lpafpProtocols, AFPROTOCOLS, base); + UnmarshallPtr(req->lpszQueryString, wchar_t, base); + UnmarshallPtr(req->lpcsaBuffer, CSADDR_INFO, base); for (i = 0; i < req->dwNumberOfCsAddrs; i++) - { - UnmarshallPtr (req->lpcsaBuffer[i].LocalAddr.lpSockaddr, SOCKADDR, base); - UnmarshallPtr (req->lpcsaBuffer[i].RemoteAddr.lpSockaddr, SOCKADDR, base); - } - UnmarshallPtr (req->lpBlob, BLOB, base); + { + UnmarshallPtr(req->lpcsaBuffer[i].LocalAddr.lpSockaddr, SOCKADDR, base); + UnmarshallPtr(req->lpcsaBuffer[i].RemoteAddr.lpSockaddr, SOCKADDR, base); + } + UnmarshallPtr(req->lpBlob, BLOB, base); if (req->lpBlob) - UnmarshallPtr (req->lpBlob->pBlobData, BYTE, base); + UnmarshallPtr(req->lpBlob->pBlobData, BYTE, base); } static int WSAAPI -GNUNET_W32NSP_LookupServiceNext (HANDLE hLookup, DWORD dwControlFlags, - LPDWORD lpdwBufferLength, LPWSAQUERYSETW lpqsResults) +GNUNET_W32NSP_LookupServiceNext(HANDLE hLookup, DWORD dwControlFlags, + LPDWORD lpdwBufferLength, LPWSAQUERYSETW lpqsResults) { /*DWORD effective_flags;*/ int i; - struct GNUNET_MessageHeader header = {0, 0}; + struct GNUNET_MessageHeader header = { 0, 0 }; int rec = -1; int rc; int to_receive; int t; char *buf; - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext\n"); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext\n"); //EnterCriticalSection (&records_cs); for (i = 0; i < records_len; i++) - { - if (records[i].s == (SOCKET) hLookup) { - rec = i; - break; + if (records[i].s == (SOCKET)hLookup) + { + rec = i; + break; + } } - } if (rec == -1) - { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: invalid handle\n"); - SetLastError (WSA_INVALID_HANDLE); - //LeaveCriticalSection (&records_cs); - return SOCKET_ERROR; - } + { + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: invalid handle\n"); + SetLastError(WSA_INVALID_HANDLE); + //LeaveCriticalSection (&records_cs); + return SOCKET_ERROR; + } if (records[rec].state & 4) - { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: session is closed\n"); - SetLastError (WSA_E_NO_MORE); - //LeaveCriticalSection (&records_cs); - return SOCKET_ERROR; - } + { + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: session is closed\n"); + SetLastError(WSA_E_NO_MORE); + //LeaveCriticalSection (&records_cs); + return SOCKET_ERROR; + } /*effective_flags = dwControlFlags & records[rec].flags;*/ if (records[rec].buf) - { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: checking buffer\n"); - header = *((struct GNUNET_MessageHeader *) records[rec].buf); - if (*lpdwBufferLength < header.size - sizeof (struct GNUNET_W32RESOLVER_GetMessage)) { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: client buffer is too small\n"); - SetLastError (WSAEFAULT); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: checking buffer\n"); + header = *((struct GNUNET_MessageHeader *)records[rec].buf); + if (*lpdwBufferLength < header.size - sizeof(struct GNUNET_W32RESOLVER_GetMessage)) + { + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: client buffer is too small\n"); + SetLastError(WSAEFAULT); + //LeaveCriticalSection (&records_cs); + return SOCKET_ERROR; + } + GNUNET_memcpy(lpqsResults, &((struct GNUNET_W32RESOLVER_GetMessage *)records[rec].buf)[1], header.size - sizeof(struct GNUNET_W32RESOLVER_GetMessage)); + free(records[rec].buf); + records[rec].buf = NULL; //LeaveCriticalSection (&records_cs); - return SOCKET_ERROR; + UnmarshallWSAQUERYSETW((LPWSAQUERYSETW)lpqsResults); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: OK (from buffer)\n"); + return NO_ERROR; } - GNUNET_memcpy (lpqsResults, &((struct GNUNET_W32RESOLVER_GetMessage *)records[rec].buf)[1], header.size - sizeof (struct GNUNET_W32RESOLVER_GetMessage)); - free (records[rec].buf); - records[rec].buf = NULL; - //LeaveCriticalSection (&records_cs); - UnmarshallWSAQUERYSETW ((LPWSAQUERYSETW) lpqsResults); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: OK (from buffer)\n"); - return NO_ERROR; - } records[rec].state |= 8; //LeaveCriticalSection (&records_cs); - to_receive = sizeof (header); + to_receive = sizeof(header); rc = 0; #if VERBOSE { unsigned long have; - int ior = ioctlsocket ((SOCKET) hLookup, FIONREAD, &have); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: reading %d bytes as a header from %p, %lu bytes available\n", to_receive, hLookup, have); + int ior = ioctlsocket((SOCKET)hLookup, FIONREAD, &have); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: reading %d bytes as a header from %p, %lu bytes available\n", to_receive, hLookup, have); } #endif while (to_receive > 0) - { - t = recv ((SOCKET) hLookup, &((char *) &header)[rc], to_receive, 0); - if (t > 0) { - rc += t; - to_receive -= t; + t = recv((SOCKET)hLookup, &((char *)&header)[rc], to_receive, 0); + if (t > 0) + { + rc += t; + to_receive -= t; + } + else + break; } - else - break; - } #if VERBOSE { unsigned long have; - int ior = ioctlsocket ((SOCKET) hLookup, FIONREAD, &have); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: read %d bytes as a header from %p, %lu bytes available\n", rc, hLookup, have); + int ior = ioctlsocket((SOCKET)hLookup, FIONREAD, &have); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: read %d bytes as a header from %p, %lu bytes available\n", rc, hLookup, have); } #endif //EnterCriticalSection (&records_cs); records[rec].state &= ~8; - if (rc != sizeof (header)) - { - if (records[rec].state & 2) - { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: call cancelled\n"); - SetLastError (WSA_E_CANCELLED); - } - else + if (rc != sizeof(header)) { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: failed to receive enough data for a header (rc %d != %u, state is 0x%0X)\n", rc, sizeof (header), records[rec].state); - SetLastError (WSA_E_NO_MORE); + if (records[rec].state & 2) + { + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: call cancelled\n"); + SetLastError(WSA_E_CANCELLED); + } + else + { + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: failed to receive enough data for a header (rc %d != %u, state is 0x%0X)\n", rc, sizeof(header), records[rec].state); + SetLastError(WSA_E_NO_MORE); + } + records[rec].state |= 4; + //LeaveCriticalSection (&records_cs); + return SOCKET_ERROR; } - records[rec].state |= 4; - //LeaveCriticalSection (&records_cs); - return SOCKET_ERROR; - } records[rec].state &= ~8; - header.type = ntohs (header.type); - header.size = ntohs (header.size); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: header type %d, header size %u\n", header.type, header.size); + header.type = ntohs(header.type); + header.size = ntohs(header.size); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: header type %d, header size %u\n", header.type, header.size); if (header.type != GNUNET_MESSAGE_TYPE_W32RESOLVER_RESPONSE || (header.type == GNUNET_MESSAGE_TYPE_W32RESOLVER_RESPONSE && - header.size == sizeof (header))) - { - records[rec].state |= 4; - if (header.type != GNUNET_MESSAGE_TYPE_W32RESOLVER_RESPONSE) - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: header type is wrong\n"); - else - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: empty header - no data\n"); - //LeaveCriticalSection (&records_cs); - SetLastError (WSA_E_NO_MORE); - return SOCKET_ERROR; - } - buf = malloc (header.size); + header.size == sizeof(header))) + { + records[rec].state |= 4; + if (header.type != GNUNET_MESSAGE_TYPE_W32RESOLVER_RESPONSE) + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: header type is wrong\n"); + else + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: empty header - no data\n"); + //LeaveCriticalSection (&records_cs); + SetLastError(WSA_E_NO_MORE); + return SOCKET_ERROR; + } + buf = malloc(header.size); if (buf == NULL) - { - records[rec].state |= 4; - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: malloc() failed\n"); - //LeaveCriticalSection (&records_cs); - SetLastError (WSA_E_NO_MORE); - return SOCKET_ERROR; - } + { + records[rec].state |= 4; + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: malloc() failed\n"); + //LeaveCriticalSection (&records_cs); + SetLastError(WSA_E_NO_MORE); + return SOCKET_ERROR; + } records[rec].state |= 8; //LeaveCriticalSection (&records_cs); - GNUNET_memcpy (buf, &header, sizeof (header)); - to_receive = header.size - sizeof (header); + GNUNET_memcpy(buf, &header, sizeof(header)); + to_receive = header.size - sizeof(header); rc = 0; #if VERBOSE { unsigned long have; - int ior = ioctlsocket ((SOCKET) hLookup, FIONREAD, &have); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: reading %d bytes as a body from %p, %lu bytes available\n", to_receive, hLookup, have); + int ior = ioctlsocket((SOCKET)hLookup, FIONREAD, &have); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: reading %d bytes as a body from %p, %lu bytes available\n", to_receive, hLookup, have); } #endif while (to_receive > 0) - { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: recv (%d)\n", to_receive); - t = recv ((SOCKET) hLookup, &((char *) &((struct GNUNET_MessageHeader *) buf)[1])[rc], to_receive, 0); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: recv returned %d\n", t); - if (t > 0) { - rc += t; - to_receive -= t; + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: recv (%d)\n", to_receive); + t = recv((SOCKET)hLookup, &((char *)&((struct GNUNET_MessageHeader *)buf)[1])[rc], to_receive, 0); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: recv returned %d\n", t); + if (t > 0) + { + rc += t; + to_receive -= t; + } + else + break; } - else - break; - } #if VERBOSE { unsigned long have; - int ior = ioctlsocket ((SOCKET) hLookup, FIONREAD, &have); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: read %d bytes as a body from %p, %lu bytes available\n", rc, hLookup, have); + int ior = ioctlsocket((SOCKET)hLookup, FIONREAD, &have); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: read %d bytes as a body from %p, %lu bytes available\n", rc, hLookup, have); } #endif //EnterCriticalSection (&records_cs); records[rec].state &= ~8; - if (rc != header.size - sizeof (header)) - { - free (buf); - if (records[rec].state & 2) + if (rc != header.size - sizeof(header)) { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: call cancelled\n"); - SetLastError (WSA_E_CANCELLED); + free(buf); + if (records[rec].state & 2) + { + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: call cancelled\n"); + SetLastError(WSA_E_CANCELLED); + } + else + { + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: failed to receive enough data for the rest (rc %d != %d, state is 0x%0X)\n", rc, header.size - sizeof(header), records[rec].state); + SetLastError(WSA_E_NO_MORE); + } + records[rec].state |= 4; + //LeaveCriticalSection (&records_cs); + return SOCKET_ERROR; } - else + if (*lpdwBufferLength < header.size - sizeof(struct GNUNET_W32RESOLVER_GetMessage)) { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: failed to receive enough data for the rest (rc %d != %d, state is 0x%0X)\n", rc, header.size - sizeof (header), records[rec].state); - SetLastError (WSA_E_NO_MORE); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: client buffer is too small\n"); + SetLastError(WSAEFAULT); + records[rec].buf = buf; + //LeaveCriticalSection (&records_cs); + return SOCKET_ERROR; } - records[rec].state |= 4; - //LeaveCriticalSection (&records_cs); - return SOCKET_ERROR; - } - if (*lpdwBufferLength < header.size - sizeof (struct GNUNET_W32RESOLVER_GetMessage)) - { - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: client buffer is too small\n"); - SetLastError (WSAEFAULT); - records[rec].buf = buf; - //LeaveCriticalSection (&records_cs); - return SOCKET_ERROR; - } //LeaveCriticalSection (&records_cs); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: writing %d bytes into result buffer\n", header.size - sizeof (struct GNUNET_W32RESOLVER_GetMessage)); - GNUNET_memcpy (lpqsResults, &((struct GNUNET_W32RESOLVER_GetMessage *)buf)[1], header.size - sizeof (struct GNUNET_W32RESOLVER_GetMessage)); - free (buf); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: OK\n"); - UnmarshallWSAQUERYSETW ((LPWSAQUERYSETW) lpqsResults); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceNext: returning (%lu)\n", GetLastError ()); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: writing %d bytes into result buffer\n", header.size - sizeof(struct GNUNET_W32RESOLVER_GetMessage)); + GNUNET_memcpy(lpqsResults, &((struct GNUNET_W32RESOLVER_GetMessage *)buf)[1], header.size - sizeof(struct GNUNET_W32RESOLVER_GetMessage)); + free(buf); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: OK\n"); + UnmarshallWSAQUERYSETW((LPWSAQUERYSETW)lpqsResults); + DEBUGLOG("GNUNET_W32NSP_LookupServiceNext: returning (%lu)\n", GetLastError()); return NO_ERROR; } static int WSPAPI -GNUNET_W32NSP_LookupServiceEnd (HANDLE hLookup) +GNUNET_W32NSP_LookupServiceEnd(HANDLE hLookup) { int i; int rec = -1; - DEBUGLOG ("GNUNET_W32NSP_LookupServiceEnd\n"); + DEBUGLOG("GNUNET_W32NSP_LookupServiceEnd\n"); //EnterCriticalSection (&records_cs); for (i = 0; i < records_len; i++) - { - if (records[i].s == (SOCKET) hLookup) { - rec = i; - break; + if (records[i].s == (SOCKET)hLookup) + { + rec = i; + break; + } } - } if (rec == -1) - { - SetLastError (WSA_INVALID_HANDLE); - //LeaveCriticalSection (&records_cs); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceEnd: invalid handle\n"); - return SOCKET_ERROR; - } + { + SetLastError(WSA_INVALID_HANDLE); + //LeaveCriticalSection (&records_cs); + DEBUGLOG("GNUNET_W32NSP_LookupServiceEnd: invalid handle\n"); + return SOCKET_ERROR; + } records[rec].state |= 2; - closesocket (records[rec].s); + closesocket(records[rec].s); while (records[rec].state & 8) - { - //LeaveCriticalSection (&records_cs); - Sleep (10); - //EnterCriticalSection (&records_cs); - } + { + //LeaveCriticalSection (&records_cs); + Sleep(10); + //EnterCriticalSection (&records_cs); + } if (records[rec].buf) - free (records[rec].buf); + free(records[rec].buf); records[rec].buf = NULL; records[rec].state = 0; if (records[rec].name) - free (records[rec].name); + free(records[rec].name); //LeaveCriticalSection (&records_cs); - DEBUGLOG ("GNUNET_W32NSP_LookupServiceEnd: OK\n"); + DEBUGLOG("GNUNET_W32NSP_LookupServiceEnd: OK\n"); return NO_ERROR; } static int WSAAPI -GNUNET_W32NSP_SetService (LPGUID lpProviderId, - LPWSASERVICECLASSINFOW lpServiceClassInfo, LPWSAQUERYSETW lpqsRegInfo, - WSAESETSERVICEOP essOperation, DWORD dwControlFlags) +GNUNET_W32NSP_SetService(LPGUID lpProviderId, + LPWSASERVICECLASSINFOW lpServiceClassInfo, LPWSAQUERYSETW lpqsRegInfo, + WSAESETSERVICEOP essOperation, DWORD dwControlFlags) { - DEBUGLOG ("GNUNET_W32NSP_SetService\n"); - SetLastError (WSAEOPNOTSUPP); + DEBUGLOG("GNUNET_W32NSP_SetService\n"); + SetLastError(WSAEOPNOTSUPP); return SOCKET_ERROR; } static int WSAAPI -GNUNET_W32NSP_InstallServiceClass (LPGUID lpProviderId, - LPWSASERVICECLASSINFOW lpServiceClassInfo) +GNUNET_W32NSP_InstallServiceClass(LPGUID lpProviderId, + LPWSASERVICECLASSINFOW lpServiceClassInfo) { - DEBUGLOG ("GNUNET_W32NSP_InstallServiceClass\n"); - SetLastError (WSAEOPNOTSUPP); + DEBUGLOG("GNUNET_W32NSP_InstallServiceClass\n"); + SetLastError(WSAEOPNOTSUPP); return SOCKET_ERROR; } static int WSAAPI -GNUNET_W32NSP_RemoveServiceClass (LPGUID lpProviderId, LPGUID lpServiceClassId) +GNUNET_W32NSP_RemoveServiceClass(LPGUID lpProviderId, LPGUID lpServiceClassId) { - DEBUGLOG ("GNUNET_W32NSP_RemoveServiceClass\n"); - SetLastError (WSAEOPNOTSUPP); + DEBUGLOG("GNUNET_W32NSP_RemoveServiceClass\n"); + SetLastError(WSAEOPNOTSUPP); return SOCKET_ERROR; } static int WSAAPI -GNUNET_W32NSP_GetServiceClassInfo (LPGUID lpProviderId, LPDWORD lpdwBufSize, - LPWSASERVICECLASSINFOW lpServiceClassInfo) +GNUNET_W32NSP_GetServiceClassInfo(LPGUID lpProviderId, LPDWORD lpdwBufSize, + LPWSASERVICECLASSINFOW lpServiceClassInfo) { - DEBUGLOG ("GNUNET_W32NSP_GetServiceClassInfo\n"); - SetLastError (WSAEOPNOTSUPP); + DEBUGLOG("GNUNET_W32NSP_GetServiceClassInfo\n"); + SetLastError(WSAEOPNOTSUPP); return SOCKET_ERROR; } static int WSAAPI -GNUNET_W32NSP_Ioctl (HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer, - DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer, - LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion, - LPWSATHREADID lpThreadId) +GNUNET_W32NSP_Ioctl(HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer, + DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer, + LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion, + LPWSATHREADID lpThreadId) { - DEBUGLOG ("GNUNET_W32NSP_Ioctl\n"); - SetLastError (WSAEOPNOTSUPP); + DEBUGLOG("GNUNET_W32NSP_Ioctl\n"); + SetLastError(WSAEOPNOTSUPP); return SOCKET_ERROR; } @@ -671,35 +677,35 @@ GNUNET_W32NSP_Ioctl (HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer, * provider. All other routines are passed as pointers in lpnspRoutines. */ int WSAAPI -GNUNET_W32NSP_NSPStartup (LPGUID lpProviderId, LPNSP_ROUTINE lpnspRoutines) +GNUNET_W32NSP_NSPStartup(LPGUID lpProviderId, LPNSP_ROUTINE lpnspRoutines) { - if (IsEqualGUID (lpProviderId, &GNUNET_NAMESPACE_PROVIDER_DNS)) - { - if (!connect_to_dns_resolver ()) + if (IsEqualGUID(lpProviderId, &GNUNET_NAMESPACE_PROVIDER_DNS)) { - return SOCKET_ERROR; + if (!connect_to_dns_resolver()) + { + return SOCKET_ERROR; + } + /* This assumes that NSP_ROUTINE struct doesn't have a NSPIoctl member. + * If it does, you need to use FIELD_OFFSET() macro to get offset of NSPIoctl + * and use that offset as cbSize. + */ + lpnspRoutines->cbSize = sizeof(NSP_ROUTINE); + + lpnspRoutines->dwMajorVersion = NSPAPI_VERSION_MAJOR; + lpnspRoutines->dwMinorVersion = NSPAPI_VERSION_MINOR; + lpnspRoutines->NSPCleanup = NSPCleanup; + lpnspRoutines->NSPLookupServiceBegin = GNUNET_W32NSP_LookupServiceBegin; + lpnspRoutines->NSPLookupServiceNext = GNUNET_W32NSP_LookupServiceNext; + lpnspRoutines->NSPLookupServiceEnd = GNUNET_W32NSP_LookupServiceEnd; + lpnspRoutines->NSPSetService = GNUNET_W32NSP_SetService; + lpnspRoutines->NSPInstallServiceClass = GNUNET_W32NSP_InstallServiceClass; + lpnspRoutines->NSPRemoveServiceClass = GNUNET_W32NSP_RemoveServiceClass; + lpnspRoutines->NSPGetServiceClassInfo = GNUNET_W32NSP_GetServiceClassInfo; + /*((NSP_ROUTINE_XP *) lpnspRoutines)->NSPIoctl = GNUNET_W32NSP_Ioctl;*/ + lpnspRoutines->NSPIoctl = GNUNET_W32NSP_Ioctl; + return NO_ERROR; } - /* This assumes that NSP_ROUTINE struct doesn't have a NSPIoctl member. - * If it does, you need to use FIELD_OFFSET() macro to get offset of NSPIoctl - * and use that offset as cbSize. - */ - lpnspRoutines->cbSize = sizeof(NSP_ROUTINE); - - lpnspRoutines->dwMajorVersion = NSPAPI_VERSION_MAJOR; - lpnspRoutines->dwMinorVersion = NSPAPI_VERSION_MINOR; - lpnspRoutines->NSPCleanup = NSPCleanup; - lpnspRoutines->NSPLookupServiceBegin = GNUNET_W32NSP_LookupServiceBegin; - lpnspRoutines->NSPLookupServiceNext = GNUNET_W32NSP_LookupServiceNext; - lpnspRoutines->NSPLookupServiceEnd = GNUNET_W32NSP_LookupServiceEnd; - lpnspRoutines->NSPSetService = GNUNET_W32NSP_SetService; - lpnspRoutines->NSPInstallServiceClass = GNUNET_W32NSP_InstallServiceClass; - lpnspRoutines->NSPRemoveServiceClass = GNUNET_W32NSP_RemoveServiceClass; - lpnspRoutines->NSPGetServiceClassInfo = GNUNET_W32NSP_GetServiceClassInfo; - /*((NSP_ROUTINE_XP *) lpnspRoutines)->NSPIoctl = GNUNET_W32NSP_Ioctl;*/ - lpnspRoutines->NSPIoctl = GNUNET_W32NSP_Ioctl; - return NO_ERROR; - } - SetLastError (WSAEINVALIDPROVIDER); + SetLastError(WSAEINVALIDPROVIDER); return SOCKET_ERROR; } diff --git a/src/gns/w32resolver.h b/src/gns/w32resolver.h index c73559cf0..17521ba50 100644 --- a/src/gns/w32resolver.h +++ b/src/gns/w32resolver.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -50,8 +50,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * The last W32RESOLVER_RESPONSE will just be a header without any data * (used to indicate the end of the list). */ -struct GNUNET_W32RESOLVER_GetMessage -{ +struct GNUNET_W32RESOLVER_GetMessage { /** * Type: GNUNET_MESSAGE_TYPE_W32RESOLVER_REQUEST */ diff --git a/src/gnsrecord/gnsrecord.c b/src/gnsrecord/gnsrecord.c index a4e8624e8..7672a7b00 100644 --- a/src/gnsrecord/gnsrecord.c +++ b/src/gnsrecord/gnsrecord.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnsrecord/gnsrecord.c @@ -32,14 +32,13 @@ #include "gnunet_gnsrecord_plugin.h" #include "gnunet_tun_lib.h" -#define LOG(kind,...) GNUNET_log_from (kind, "gnsrecord",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "gnsrecord", __VA_ARGS__) /** * Handle for a plugin. */ -struct Plugin -{ +struct Plugin { /** * Name of the shared library. */ @@ -76,20 +75,20 @@ static int once; * @param lib_ret the plugin API */ static void -add_plugin (void *cls, - const char *library_name, - void *lib_ret) +add_plugin(void *cls, + const char *library_name, + void *lib_ret) { struct GNUNET_GNSRECORD_PluginFunctions *api = lib_ret; struct Plugin *plugin; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Loading block plugin `%s'\n", - library_name); - plugin = GNUNET_new (struct Plugin); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Loading block plugin `%s'\n", + library_name); + plugin = GNUNET_new(struct Plugin); plugin->api = api; - plugin->library_name = GNUNET_strdup (library_name); - GNUNET_array_append (gns_plugins, num_plugins, plugin); + plugin->library_name = GNUNET_strdup(library_name); + GNUNET_array_append(gns_plugins, num_plugins, plugin); } @@ -97,13 +96,13 @@ add_plugin (void *cls, * Loads all plugins (lazy initialization). */ static void -init () +init() { if (1 == once) return; once = 1; - GNUNET_PLUGIN_load_all ("libgnunet_plugin_gnsrecord_", NULL, - &add_plugin, NULL); + GNUNET_PLUGIN_load_all("libgnunet_plugin_gnsrecord_", NULL, + &add_plugin, NULL); } @@ -111,20 +110,20 @@ init () * Dual function to #init(). */ void __attribute__ ((destructor)) -GNSRECORD_fini () +GNSRECORD_fini() { struct Plugin *plugin; for (unsigned int i = 0; i < num_plugins; i++) - { - plugin = gns_plugins[i]; - GNUNET_break (NULL == - GNUNET_PLUGIN_unload (plugin->library_name, + { + plugin = gns_plugins[i]; + GNUNET_break(NULL == + GNUNET_PLUGIN_unload(plugin->library_name, plugin->api)); - GNUNET_free (plugin->library_name); - GNUNET_free (plugin); - } - GNUNET_free_non_null (gns_plugins); + GNUNET_free(plugin->library_name); + GNUNET_free(plugin); + } + GNUNET_free_non_null(gns_plugins); gns_plugins = NULL; once = 0; num_plugins = 0; @@ -140,23 +139,23 @@ GNSRECORD_fini () * @return NULL on error, otherwise human-readable representation of the value */ char * -GNUNET_GNSRECORD_value_to_string (uint32_t type, - const void *data, - size_t data_size) +GNUNET_GNSRECORD_value_to_string(uint32_t type, + const void *data, + size_t data_size) { struct Plugin *plugin; char *ret; - init (); + init(); for (unsigned int i = 0; i < num_plugins; i++) - { - plugin = gns_plugins[i]; - if (NULL != (ret = plugin->api->value_to_string (plugin->api->cls, - type, - data, - data_size))) - return ret; - } + { + plugin = gns_plugins[i]; + if (NULL != (ret = plugin->api->value_to_string(plugin->api->cls, + type, + data, + data_size))) + return ret; + } return NULL; } @@ -172,24 +171,24 @@ GNUNET_GNSRECORD_value_to_string (uint32_t type, * @return #GNUNET_OK on success */ int -GNUNET_GNSRECORD_string_to_value (uint32_t type, - const char *s, - void **data, - size_t *data_size) +GNUNET_GNSRECORD_string_to_value(uint32_t type, + const char *s, + void **data, + size_t *data_size) { struct Plugin *plugin; - init (); + init(); for (unsigned int i = 0; i < num_plugins; i++) - { - plugin = gns_plugins[i]; - if (GNUNET_OK == plugin->api->string_to_value (plugin->api->cls, - type, - s, - data, - data_size)) - return GNUNET_OK; - } + { + plugin = gns_plugins[i]; + if (GNUNET_OK == plugin->api->string_to_value(plugin->api->cls, + type, + s, + data, + data_size)) + return GNUNET_OK; + } return GNUNET_SYSERR; } @@ -201,22 +200,22 @@ GNUNET_GNSRECORD_string_to_value (uint32_t type, * @return corresponding number, UINT32_MAX on error */ uint32_t -GNUNET_GNSRECORD_typename_to_number (const char *dns_typename) +GNUNET_GNSRECORD_typename_to_number(const char *dns_typename) { struct Plugin *plugin; uint32_t ret; - if (0 == strcasecmp (dns_typename, - "ANY")) + if (0 == strcasecmp(dns_typename, + "ANY")) return GNUNET_GNSRECORD_TYPE_ANY; - init (); + init(); for (unsigned int i = 0; i < num_plugins; i++) - { - plugin = gns_plugins[i]; - if (UINT32_MAX != (ret = plugin->api->typename_to_number (plugin->api->cls, - dns_typename))) - return ret; - } + { + plugin = gns_plugins[i]; + if (UINT32_MAX != (ret = plugin->api->typename_to_number(plugin->api->cls, + dns_typename))) + return ret; + } return UINT32_MAX; } @@ -228,21 +227,21 @@ GNUNET_GNSRECORD_typename_to_number (const char *dns_typename) * @return corresponding typestring, NULL on error */ const char * -GNUNET_GNSRECORD_number_to_typename (uint32_t type) +GNUNET_GNSRECORD_number_to_typename(uint32_t type) { struct Plugin *plugin; const char * ret; if (GNUNET_GNSRECORD_TYPE_ANY == type) return "ANY"; - init (); + init(); for (unsigned int i = 0; i < num_plugins; i++) - { - plugin = gns_plugins[i]; - if (NULL != (ret = plugin->api->number_to_typename (plugin->api->cls, - type))) - return ret; - } + { + plugin = gns_plugins[i]; + if (NULL != (ret = plugin->api->number_to_typename(plugin->api->cls, + type))) + return ret; + } return NULL; } diff --git a/src/gnsrecord/gnsrecord_crypto.c b/src/gnsrecord/gnsrecord_crypto.c index 2785a4a59..6eda1e962 100644 --- a/src/gnsrecord/gnsrecord_crypto.c +++ b/src/gnsrecord/gnsrecord_crypto.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnsrecord/gnsrecord_crypto.c @@ -35,7 +35,7 @@ #include "gnunet_tun_lib.h" -#define LOG(kind,...) GNUNET_log_from (kind, "gnsrecord",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "gnsrecord", __VA_ARGS__) /** @@ -47,24 +47,24 @@ * @param pub public key to use for KDF */ static void -derive_block_aes_key (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, - struct GNUNET_CRYPTO_SymmetricSessionKey *skey, - const char *label, - const struct GNUNET_CRYPTO_EcdsaPublicKey *pub) +derive_block_aes_key(struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, + struct GNUNET_CRYPTO_SymmetricSessionKey *skey, + const char *label, + const struct GNUNET_CRYPTO_EcdsaPublicKey *pub) { static const char ctx_key[] = "gns-aes-ctx-key"; static const char ctx_iv[] = "gns-aes-ctx-iv"; - GNUNET_CRYPTO_kdf (skey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey), - pub, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey), - label, strlen (label), - ctx_key, strlen (ctx_key), - NULL, 0); - GNUNET_CRYPTO_kdf (iv, sizeof (struct GNUNET_CRYPTO_SymmetricInitializationVector), - pub, sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey), - label, strlen (label), - ctx_iv, strlen (ctx_iv), - NULL, 0); + GNUNET_CRYPTO_kdf(skey, sizeof(struct GNUNET_CRYPTO_SymmetricSessionKey), + pub, sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey), + label, strlen(label), + ctx_key, strlen(ctx_key), + NULL, 0); + GNUNET_CRYPTO_kdf(iv, sizeof(struct GNUNET_CRYPTO_SymmetricInitializationVector), + pub, sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey), + label, strlen(label), + ctx_iv, strlen(ctx_iv), + NULL, 0); } @@ -80,15 +80,15 @@ derive_block_aes_key (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, * @return NULL on error (block too large) */ struct GNUNET_GNSRECORD_Block * -block_create (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, - const struct GNUNET_CRYPTO_EcdsaPublicKey *pkey, - struct GNUNET_TIME_Absolute expire, - const char *label, - const struct GNUNET_GNSRECORD_Data *rd, - unsigned int rd_count) +block_create(const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, + const struct GNUNET_CRYPTO_EcdsaPublicKey *pkey, + struct GNUNET_TIME_Absolute expire, + const char *label, + const struct GNUNET_GNSRECORD_Data *rd, + unsigned int rd_count) { - ssize_t payload_len = GNUNET_GNSRECORD_records_get_size (rd_count, - rd); + ssize_t payload_len = GNUNET_GNSRECORD_records_get_size(rd_count, + rd); struct GNUNET_GNSRECORD_Block *block; struct GNUNET_CRYPTO_EcdsaPrivateKey *dkey; struct GNUNET_CRYPTO_SymmetricInitializationVector iv; @@ -98,80 +98,80 @@ block_create (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, struct GNUNET_TIME_Absolute now; if (payload_len < 0) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } if (payload_len > GNUNET_GNSRECORD_MAX_BLOCK_SIZE) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } /* convert relative to absolute times */ - now = GNUNET_TIME_absolute_get (); - for (unsigned int i=0;ipurpose.size = htonl (sizeof (uint32_t) + - payload_len + - sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) + - sizeof (struct GNUNET_TIME_AbsoluteNBO)); - block->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN); - block->expiration_time = GNUNET_TIME_absolute_hton (expire); + char payload[sizeof(uint32_t) + payload_len]; + + GNUNET_memcpy(payload, + &rd_count_nbo, + sizeof(uint32_t)); + GNUNET_assert(payload_len == + GNUNET_GNSRECORD_records_serialize(rd_count, + rdc, + payload_len, + &payload[sizeof(uint32_t)])); + block = GNUNET_malloc(sizeof(struct GNUNET_GNSRECORD_Block) + + sizeof(uint32_t) + + payload_len); + block->purpose.size = htonl(sizeof(uint32_t) + + payload_len + + sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose) + + sizeof(struct GNUNET_TIME_AbsoluteNBO)); + block->purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN); + block->expiration_time = GNUNET_TIME_absolute_hton(expire); /* encrypt and sign */ - dkey = GNUNET_CRYPTO_ecdsa_private_key_derive (key, - label, - "gns"); - GNUNET_CRYPTO_ecdsa_key_get_public (dkey, - &block->derived_key); - derive_block_aes_key (&iv, - &skey, - label, - pkey); - GNUNET_break (payload_len + sizeof (uint32_t) == - GNUNET_CRYPTO_symmetric_encrypt (payload, - payload_len + sizeof (uint32_t), - &skey, - &iv, - &block[1])); + dkey = GNUNET_CRYPTO_ecdsa_private_key_derive(key, + label, + "gns"); + GNUNET_CRYPTO_ecdsa_key_get_public(dkey, + &block->derived_key); + derive_block_aes_key(&iv, + &skey, + label, + pkey); + GNUNET_break(payload_len + sizeof(uint32_t) == + GNUNET_CRYPTO_symmetric_encrypt(payload, + payload_len + sizeof(uint32_t), + &skey, + &iv, + &block[1])); } if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_sign (dkey, - &block->purpose, - &block->signature)) - { - GNUNET_break (0); - GNUNET_free (dkey); - GNUNET_free (block); - return NULL; - } - GNUNET_free (dkey); + GNUNET_CRYPTO_ecdsa_sign(dkey, + &block->purpose, + &block->signature)) + { + GNUNET_break(0); + GNUNET_free(dkey); + GNUNET_free(block); + return NULL; + } + GNUNET_free(dkey); return block; } @@ -187,30 +187,29 @@ block_create (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, * @return NULL on error (block too large) */ struct GNUNET_GNSRECORD_Block * -GNUNET_GNSRECORD_block_create (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, - struct GNUNET_TIME_Absolute expire, - const char *label, - const struct GNUNET_GNSRECORD_Data *rd, - unsigned int rd_count) +GNUNET_GNSRECORD_block_create(const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, + struct GNUNET_TIME_Absolute expire, + const char *label, + const struct GNUNET_GNSRECORD_Data *rd, + unsigned int rd_count) { struct GNUNET_CRYPTO_EcdsaPublicKey pkey; - GNUNET_CRYPTO_ecdsa_key_get_public (key, - &pkey); - return block_create (key, - &pkey, - expire, - label, - rd, - rd_count); + GNUNET_CRYPTO_ecdsa_key_get_public(key, + &pkey); + return block_create(key, + &pkey, + expire, + label, + rd, + rd_count); } /** * Line in cache mapping private keys to public keys. */ -struct KeyCacheLine -{ +struct KeyCacheLine { /** * A private key. */ @@ -220,7 +219,6 @@ struct KeyCacheLine * Associated public key. */ struct GNUNET_CRYPTO_EcdsaPublicKey pkey; - }; @@ -237,33 +235,33 @@ struct KeyCacheLine * @return NULL on error (block too large) */ struct GNUNET_GNSRECORD_Block * -GNUNET_GNSRECORD_block_create2 (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, - struct GNUNET_TIME_Absolute expire, - const char *label, - const struct GNUNET_GNSRECORD_Data *rd, - unsigned int rd_count) +GNUNET_GNSRECORD_block_create2(const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, + struct GNUNET_TIME_Absolute expire, + const char *label, + const struct GNUNET_GNSRECORD_Data *rd, + unsigned int rd_count) { #define CSIZE 64 static struct KeyCacheLine cache[CSIZE]; struct KeyCacheLine *line; - line = &cache[(*(unsigned int *) key) % CSIZE]; - if (0 != memcmp (&line->key, - key, - sizeof (*key))) - { - /* cache miss, recompute */ - line->key = *key; - GNUNET_CRYPTO_ecdsa_key_get_public (key, - &line->pkey); - } + line = &cache[(*(unsigned int *)key) % CSIZE]; + if (0 != memcmp(&line->key, + key, + sizeof(*key))) + { + /* cache miss, recompute */ + line->key = *key; + GNUNET_CRYPTO_ecdsa_key_get_public(key, + &line->pkey); + } #undef CSIZE - return block_create (key, - &line->pkey, - expire, - label, - rd, - rd_count); + return block_create(key, + &line->pkey, + expire, + label, + rd, + rd_count); } @@ -276,12 +274,12 @@ GNUNET_GNSRECORD_block_create2 (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, * @return #GNUNET_OK if the signature is valid */ int -GNUNET_GNSRECORD_block_verify (const struct GNUNET_GNSRECORD_Block *block) +GNUNET_GNSRECORD_block_verify(const struct GNUNET_GNSRECORD_Block *block) { - return GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN, - &block->purpose, - &block->signature, - &block->derived_key); + return GNUNET_CRYPTO_ecdsa_verify(GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN, + &block->purpose, + &block->signature, + &block->derived_key); } @@ -297,124 +295,124 @@ GNUNET_GNSRECORD_block_verify (const struct GNUNET_GNSRECORD_Block *block) * not well-formed */ int -GNUNET_GNSRECORD_block_decrypt (const struct GNUNET_GNSRECORD_Block *block, - const struct GNUNET_CRYPTO_EcdsaPublicKey *zone_key, - const char *label, - GNUNET_GNSRECORD_RecordCallback proc, - void *proc_cls) +GNUNET_GNSRECORD_block_decrypt(const struct GNUNET_GNSRECORD_Block *block, + const struct GNUNET_CRYPTO_EcdsaPublicKey *zone_key, + const char *label, + GNUNET_GNSRECORD_RecordCallback proc, + void *proc_cls) { - size_t payload_len = ntohl (block->purpose.size) - - sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) - - sizeof (struct GNUNET_TIME_AbsoluteNBO); + size_t payload_len = ntohl(block->purpose.size) - + sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose) - + sizeof(struct GNUNET_TIME_AbsoluteNBO); struct GNUNET_CRYPTO_SymmetricInitializationVector iv; struct GNUNET_CRYPTO_SymmetricSessionKey skey; - if (ntohl (block->purpose.size) < - sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) + - sizeof (struct GNUNET_TIME_AbsoluteNBO)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - derive_block_aes_key (&iv, - &skey, - label, - zone_key); + if (ntohl(block->purpose.size) < + sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose) + + sizeof(struct GNUNET_TIME_AbsoluteNBO)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + derive_block_aes_key(&iv, + &skey, + label, + zone_key); { char payload[payload_len]; uint32_t rd_count; - GNUNET_break (payload_len == - GNUNET_CRYPTO_symmetric_decrypt (&block[1], payload_len, - &skey, &iv, - payload)); - GNUNET_memcpy (&rd_count, - payload, - sizeof (uint32_t)); - rd_count = ntohl (rd_count); + GNUNET_break(payload_len == + GNUNET_CRYPTO_symmetric_decrypt(&block[1], payload_len, + &skey, &iv, + payload)); + GNUNET_memcpy(&rd_count, + payload, + sizeof(uint32_t)); + rd_count = ntohl(rd_count); if (rd_count > 2048) - { - /* limit to sane value */ - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + /* limit to sane value */ + GNUNET_break_op(0); + return GNUNET_SYSERR; + } { struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL(rd_count)]; unsigned int j; struct GNUNET_TIME_Absolute now; if (GNUNET_OK != - GNUNET_GNSRECORD_records_deserialize (payload_len - sizeof (uint32_t), - &payload[sizeof (uint32_t)], - rd_count, - rd)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - /* hide expired records */ - now = GNUNET_TIME_absolute_get (); - j = 0; - for (unsigned int i=0;i= now.abs_value_us) && - (0 == (rd[k].flags & GNUNET_GNSRECORD_RF_SHADOW_RECORD)) ) + } + + if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_SHADOW_RECORD)) { - include_record = GNUNET_NO; /* We have a non-expired, non-shadow record of the same type */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Ignoring shadow record\n"); - break; + int include_record = GNUNET_YES; + /* Shadow record, figure out if we have a not expired active record */ + for (unsigned int k = 0; k < rd_count; k++) + { + if (k == i) + continue; + if (rd[i].expiration_time < now.abs_value_us) + include_record = GNUNET_NO; /* Shadow record is expired */ + if ((rd[k].record_type == rd[i].record_type) && + (rd[k].expiration_time >= now.abs_value_us) && + (0 == (rd[k].flags & GNUNET_GNSRECORD_RF_SHADOW_RECORD))) + { + include_record = GNUNET_NO; /* We have a non-expired, non-shadow record of the same type */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Ignoring shadow record\n"); + break; + } + } + if (GNUNET_YES == include_record) + { + rd[i].flags ^= GNUNET_GNSRECORD_RF_SHADOW_RECORD; /* Remove Flag */ + if (j != i) + rd[j] = rd[i]; + j++; + } + } + else if (rd[i].expiration_time >= now.abs_value_us) + { + /* Include this record */ + if (j != i) + rd[j] = rd[i]; + j++; + } + else + { + struct GNUNET_TIME_Absolute at; + + at.abs_value_us = rd[i].expiration_time; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Excluding record that expired %s (%llu ago)\n", + GNUNET_STRINGS_absolute_time_to_string(at), + (unsigned long long)rd[i].expiration_time - now.abs_value_us); } - } - if (GNUNET_YES == include_record) - { - rd[i].flags ^= GNUNET_GNSRECORD_RF_SHADOW_RECORD; /* Remove Flag */ - if (j != i) - rd[j] = rd[i]; - j++; - } - } - else if (rd[i].expiration_time >= now.abs_value_us) - { - /* Include this record */ - if (j != i) - rd[j] = rd[i]; - j++; } - else - { - struct GNUNET_TIME_Absolute at; - - at.abs_value_us = rd[i].expiration_time; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Excluding record that expired %s (%llu ago)\n", - GNUNET_STRINGS_absolute_time_to_string (at), - (unsigned long long) rd[i].expiration_time - now.abs_value_us); - } - } rd_count = j; if (NULL != proc) - proc (proc_cls, - rd_count, - (0 != rd_count) ? rd : NULL); + proc(proc_cls, + rd_count, + (0 != rd_count) ? rd : NULL); } } return GNUNET_OK; @@ -429,17 +427,17 @@ GNUNET_GNSRECORD_block_decrypt (const struct GNUNET_GNSRECORD_Block *block, * @param query hash to use for the query */ void -GNUNET_GNSRECORD_query_from_private_key (const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - struct GNUNET_HashCode *query) +GNUNET_GNSRECORD_query_from_private_key(const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + struct GNUNET_HashCode *query) { struct GNUNET_CRYPTO_EcdsaPublicKey pub; - GNUNET_CRYPTO_ecdsa_key_get_public (zone, - &pub); - GNUNET_GNSRECORD_query_from_public_key (&pub, - label, - query); + GNUNET_CRYPTO_ecdsa_key_get_public(zone, + &pub); + GNUNET_GNSRECORD_query_from_public_key(&pub, + label, + query); } @@ -451,19 +449,19 @@ GNUNET_GNSRECORD_query_from_private_key (const struct GNUNET_CRYPTO_EcdsaPrivate * @param query hash to use for the query */ void -GNUNET_GNSRECORD_query_from_public_key (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub, - const char *label, - struct GNUNET_HashCode *query) +GNUNET_GNSRECORD_query_from_public_key(const struct GNUNET_CRYPTO_EcdsaPublicKey *pub, + const char *label, + struct GNUNET_HashCode *query) { struct GNUNET_CRYPTO_EcdsaPublicKey pd; - GNUNET_CRYPTO_ecdsa_public_key_derive (pub, - label, - "gns", - &pd); - GNUNET_CRYPTO_hash (&pd, - sizeof (pd), - query); + GNUNET_CRYPTO_ecdsa_public_key_derive(pub, + label, + "gns", + &pd); + GNUNET_CRYPTO_hash(&pd, + sizeof(pd), + query); } diff --git a/src/gnsrecord/gnsrecord_misc.c b/src/gnsrecord/gnsrecord_misc.c index 50dd2086b..159f078ee 100644 --- a/src/gnsrecord/gnsrecord_misc.c +++ b/src/gnsrecord/gnsrecord_misc.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnsrecord/gnsrecord_misc.c @@ -35,7 +35,7 @@ #include "gnunet_tun_lib.h" -#define LOG(kind,...) GNUNET_log_from (kind, "gnsrecord",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "gnsrecord", __VA_ARGS__) /** * Convert a UTF-8 string to UTF-8 lowercase @@ -43,12 +43,12 @@ * @return converted result */ char * -GNUNET_GNSRECORD_string_to_lowercase (const char *src) +GNUNET_GNSRECORD_string_to_lowercase(const char *src) { char *res; - res = GNUNET_strdup (src); - GNUNET_STRINGS_utf8_tolower (src, res); + res = GNUNET_strdup(src); + GNUNET_STRINGS_utf8_tolower(src, res); return res; } @@ -62,19 +62,19 @@ GNUNET_GNSRECORD_string_to_lowercase (const char *src) * @return string form; will be overwritten by next call to #GNUNET_GNSRECORD_z2s */ const char * -GNUNET_GNSRECORD_z2s (const struct GNUNET_CRYPTO_EcdsaPublicKey *z) +GNUNET_GNSRECORD_z2s(const struct GNUNET_CRYPTO_EcdsaPublicKey *z) { - static char buf[sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) * 8]; + static char buf[sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) * 8]; char *end; - end = GNUNET_STRINGS_data_to_string ((const unsigned char *) z, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey), - buf, sizeof (buf)); + end = GNUNET_STRINGS_data_to_string((const unsigned char *)z, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey), + buf, sizeof(buf)); if (NULL == end) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } *end = '\0'; return buf; } @@ -90,51 +90,51 @@ GNUNET_GNSRECORD_z2s (const struct GNUNET_CRYPTO_EcdsaPublicKey *z) * @return #GNUNET_YES if the records are equal or #GNUNET_NO if they are not */ int -GNUNET_GNSRECORD_records_cmp (const struct GNUNET_GNSRECORD_Data *a, - const struct GNUNET_GNSRECORD_Data *b) +GNUNET_GNSRECORD_records_cmp(const struct GNUNET_GNSRECORD_Data *a, + const struct GNUNET_GNSRECORD_Data *b) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Comparing records\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Comparing records\n"); if (a->record_type != b->record_type) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Record type %lu != %lu\n", a->record_type, b->record_type); - return GNUNET_NO; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Record type %lu != %lu\n", a->record_type, b->record_type); + return GNUNET_NO; + } if ((a->expiration_time != b->expiration_time) && ((a->expiration_time != 0) && (b->expiration_time != 0))) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Expiration time %llu != %llu\n", - a->expiration_time, - b->expiration_time); - return GNUNET_NO; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Expiration time %llu != %llu\n", + a->expiration_time, + b->expiration_time); + return GNUNET_NO; + } if ((a->flags & GNUNET_GNSRECORD_RF_RCMP_FLAGS) - != (b->flags & GNUNET_GNSRECORD_RF_RCMP_FLAGS)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Flags %lu (%lu) != %lu (%lu)\n", a->flags, - a->flags & GNUNET_GNSRECORD_RF_RCMP_FLAGS, b->flags, - b->flags & GNUNET_GNSRECORD_RF_RCMP_FLAGS); - return GNUNET_NO; - } + != (b->flags & GNUNET_GNSRECORD_RF_RCMP_FLAGS)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Flags %lu (%lu) != %lu (%lu)\n", a->flags, + a->flags & GNUNET_GNSRECORD_RF_RCMP_FLAGS, b->flags, + b->flags & GNUNET_GNSRECORD_RF_RCMP_FLAGS); + return GNUNET_NO; + } if (a->data_size != b->data_size) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Data size %lu != %lu\n", - a->data_size, - b->data_size); - return GNUNET_NO; - } - if (0 != memcmp (a->data, b->data, a->data_size)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Data contents do not match\n"); - return GNUNET_NO; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Records are equal\n"); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Data size %lu != %lu\n", + a->data_size, + b->data_size); + return GNUNET_NO; + } + if (0 != memcmp(a->data, b->data, a->data_size)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Data contents do not match\n"); + return GNUNET_NO; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Records are equal\n"); return GNUNET_YES; } @@ -149,8 +149,8 @@ GNUNET_GNSRECORD_records_cmp (const struct GNUNET_GNSRECORD_Data *a, * @return absolute expiration time */ struct GNUNET_TIME_Absolute -GNUNET_GNSRECORD_record_get_expiration_time (unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +GNUNET_GNSRECORD_record_get_expiration_time(unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_TIME_Absolute expire; struct GNUNET_TIME_Absolute at; @@ -162,44 +162,44 @@ GNUNET_GNSRECORD_record_get_expiration_time (unsigned int rd_count, return GNUNET_TIME_UNIT_ZERO_ABS; expire = GNUNET_TIME_UNIT_FOREVER_ABS; for (unsigned int c = 0; c < rd_count; c++) - { - if (0 != (rd[c].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) { - rt.rel_value_us = rd[c].expiration_time; - at = GNUNET_TIME_relative_to_absolute (rt); - } - else - { - at.abs_value_us = rd[c].expiration_time; - } - - for (unsigned int c2 = 0; c2 < rd_count; c2++) - { - /* Check for shadow record */ - if ( (c == c2) || - (rd[c].record_type != rd[c2].record_type) || - (0 == (rd[c2].flags & GNUNET_GNSRECORD_RF_SHADOW_RECORD)) ) - continue; - /* We have a shadow record */ - if (0 != (rd[c2].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) - { - rt_shadow.rel_value_us = rd[c2].expiration_time; - at_shadow = GNUNET_TIME_relative_to_absolute (rt_shadow); - } + if (0 != (rd[c].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) + { + rt.rel_value_us = rd[c].expiration_time; + at = GNUNET_TIME_relative_to_absolute(rt); + } else - { - at_shadow.abs_value_us = rd[c2].expiration_time; - } - at = GNUNET_TIME_absolute_max (at, - at_shadow); + { + at.abs_value_us = rd[c].expiration_time; + } + + for (unsigned int c2 = 0; c2 < rd_count; c2++) + { + /* Check for shadow record */ + if ((c == c2) || + (rd[c].record_type != rd[c2].record_type) || + (0 == (rd[c2].flags & GNUNET_GNSRECORD_RF_SHADOW_RECORD))) + continue; + /* We have a shadow record */ + if (0 != (rd[c2].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) + { + rt_shadow.rel_value_us = rd[c2].expiration_time; + at_shadow = GNUNET_TIME_relative_to_absolute(rt_shadow); + } + else + { + at_shadow.abs_value_us = rd[c2].expiration_time; + } + at = GNUNET_TIME_absolute_max(at, + at_shadow); + } + expire = GNUNET_TIME_absolute_min(at, + expire); } - expire = GNUNET_TIME_absolute_min (at, - expire); - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Determined expiration time for block with %u records to be %s\n", - rd_count, - GNUNET_STRINGS_absolute_time_to_string (expire)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Determined expiration time for block with %u records to be %s\n", + rd_count, + GNUNET_STRINGS_absolute_time_to_string(expire)); return expire; } @@ -211,14 +211,14 @@ GNUNET_GNSRECORD_record_get_expiration_time (unsigned int rd_count, * #GNUNET_NO if not */ int -GNUNET_GNSRECORD_is_expired (const struct GNUNET_GNSRECORD_Data *rd) +GNUNET_GNSRECORD_is_expired(const struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_TIME_Absolute at; if (0 != (rd->flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) return GNUNET_NO; at.abs_value_us = rd->expiration_time; - return (0 == GNUNET_TIME_absolute_get_remaining (at).rel_value_us) ? GNUNET_YES : GNUNET_NO; + return (0 == GNUNET_TIME_absolute_get_remaining(at).rel_value_us) ? GNUNET_YES : GNUNET_NO; } @@ -233,17 +233,17 @@ GNUNET_GNSRECORD_is_expired (const struct GNUNET_GNSRECORD_Data *rd) * key in an encoding suitable for DNS labels. */ const char * -GNUNET_GNSRECORD_pkey_to_zkey (const struct GNUNET_CRYPTO_EcdsaPublicKey *pkey) +GNUNET_GNSRECORD_pkey_to_zkey(const struct GNUNET_CRYPTO_EcdsaPublicKey *pkey) { static char ret[128]; char *pkeys; - pkeys = GNUNET_CRYPTO_ecdsa_public_key_to_string (pkey); - GNUNET_snprintf (ret, - sizeof (ret), - "%s", - pkeys); - GNUNET_free (pkeys); + pkeys = GNUNET_CRYPTO_ecdsa_public_key_to_string(pkey); + GNUNET_snprintf(ret, + sizeof(ret), + "%s", + pkeys); + GNUNET_free(pkeys); return ret; } @@ -258,13 +258,13 @@ GNUNET_GNSRECORD_pkey_to_zkey (const struct GNUNET_CRYPTO_EcdsaPublicKey *pkey) * @return #GNUNET_SYSERR if @a zkey has the wrong syntax */ int -GNUNET_GNSRECORD_zkey_to_pkey (const char *zkey, - struct GNUNET_CRYPTO_EcdsaPublicKey *pkey) +GNUNET_GNSRECORD_zkey_to_pkey(const char *zkey, + struct GNUNET_CRYPTO_EcdsaPublicKey *pkey) { if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (zkey, - strlen (zkey), - pkey)) + GNUNET_CRYPTO_ecdsa_public_key_from_string(zkey, + strlen(zkey), + pkey)) return GNUNET_SYSERR; return GNUNET_OK; } diff --git a/src/gnsrecord/gnsrecord_serialization.c b/src/gnsrecord/gnsrecord_serialization.c index be1dc1889..9d2c858ef 100644 --- a/src/gnsrecord/gnsrecord_serialization.c +++ b/src/gnsrecord/gnsrecord_serialization.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnsrecord/gnsrecord_serialization.c @@ -35,7 +35,7 @@ #include "gnunet_tun_lib.h" -#define LOG(kind,...) GNUNET_log_from (kind, "gnsrecord",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "gnsrecord", __VA_ARGS__) /** * Set to 1 to check that all records are well-formed (can be converted @@ -49,9 +49,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Internal format of a record in the serialized form. */ -struct NetworkRecord -{ - +struct NetworkRecord { /** * Expiration time for the DNS record; relative or absolute depends * on @e flags, network byte order. @@ -72,7 +70,6 @@ struct NetworkRecord * Flags for the record, network byte order. */ uint32_t flags GNUNET_PACKED; - }; GNUNET_NETWORK_STRUCT_END @@ -87,44 +84,44 @@ GNUNET_NETWORK_STRUCT_END * @return the required size to serialize, -1 on error */ ssize_t -GNUNET_GNSRECORD_records_get_size (unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +GNUNET_GNSRECORD_records_get_size(unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { size_t ret; if (0 == rd_count) return 0; - - ret = sizeof (struct NetworkRecord) * rd_count; - for (unsigned int i=0;i SSIZE_MAX) - { - GNUNET_break (0); - return -1; - } + { + GNUNET_break(0); + return -1; + } //Do not pad PKEY if (GNUNET_GNSRECORD_TYPE_PKEY == rd->record_type) return ret; @@ -140,7 +137,7 @@ GNUNET_GNSRECORD_records_get_size (unsigned int rd_count, ret |= ret >> 8; ret |= ret >> 16; ret++; - return (ssize_t) ret; + return (ssize_t)ret; } @@ -154,65 +151,65 @@ GNUNET_GNSRECORD_records_get_size (unsigned int rd_count, * @return the size of serialized records, -1 if records do not fit */ ssize_t -GNUNET_GNSRECORD_records_serialize (unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd, - size_t dest_size, - char *dest) +GNUNET_GNSRECORD_records_serialize(unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd, + size_t dest_size, + char *dest) { struct NetworkRecord rec; size_t off; off = 0; - for (unsigned int i=0;i dest_size) || - (off + sizeof (rec) < off) ) - { - GNUNET_break (0); - return -1; - } - GNUNET_memcpy (&dest[off], - &rec, - sizeof (rec)); - off += sizeof (rec); - if ( (off + rd[i].data_size > dest_size) || - (off + rd[i].data_size < off) ) + for (unsigned int i = 0; i < rd_count; i++) { - GNUNET_break (0); - return -1; - } - GNUNET_memcpy (&dest[off], - rd[i].data, - rd[i].data_size); - off += rd[i].data_size; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Serializing record %u with flags %d and expiration time %llu\n", + i, + rd[i].flags, + (unsigned long long)rd[i].expiration_time); + rec.expiration_time = GNUNET_htonll(rd[i].expiration_time); + rec.data_size = htonl((uint32_t)rd[i].data_size); + rec.record_type = htonl(rd[i].record_type); + rec.flags = htonl(rd[i].flags); + if ((off + sizeof(rec) > dest_size) || + (off + sizeof(rec) < off)) + { + GNUNET_break(0); + return -1; + } + GNUNET_memcpy(&dest[off], + &rec, + sizeof(rec)); + off += sizeof(rec); + if ((off + rd[i].data_size > dest_size) || + (off + rd[i].data_size < off)) + { + GNUNET_break(0); + return -1; + } + GNUNET_memcpy(&dest[off], + rd[i].data, + rd[i].data_size); + off += rd[i].data_size; #if DEBUG_GNSRECORDS - { - char *str; - - str = GNUNET_GNSRECORD_value_to_string (rd[i].record_type, - rd[i].data, - rd[i].data_size); - if (NULL == str) { - GNUNET_break_op (0); - return -1; + char *str; + + str = GNUNET_GNSRECORD_value_to_string(rd[i].record_type, + rd[i].data, + rd[i].data_size); + if (NULL == str) + { + GNUNET_break_op(0); + return -1; + } + GNUNET_free(str); } - GNUNET_free (str); - } #endif - } - memset (&dest[off], - 0, - dest_size-off); + } + memset(&dest[off], + 0, + dest_size - off); return dest_size; } @@ -227,60 +224,60 @@ GNUNET_GNSRECORD_records_serialize (unsigned int rd_count, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_GNSRECORD_records_deserialize (size_t len, - const char *src, - unsigned int rd_count, - struct GNUNET_GNSRECORD_Data *dest) +GNUNET_GNSRECORD_records_deserialize(size_t len, + const char *src, + unsigned int rd_count, + struct GNUNET_GNSRECORD_Data *dest) { struct NetworkRecord rec; size_t off; off = 0; - for (unsigned int i=0;i len) || - (off + sizeof (rec) < off) ) + for (unsigned int i = 0; i < rd_count; i++) { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - GNUNET_memcpy (&rec, - &src[off], - sizeof (rec)); - dest[i].expiration_time = GNUNET_ntohll (rec.expiration_time); - dest[i].data_size = ntohl ((uint32_t) rec.data_size); - dest[i].record_type = ntohl (rec.record_type); - dest[i].flags = ntohl (rec.flags); - off += sizeof (rec); - if ( (off + dest[i].data_size > len) || - (off + dest[i].data_size < off) ) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - dest[i].data = &src[off]; - off += dest[i].data_size; + if ((off + sizeof(rec) > len) || + (off + sizeof(rec) < off)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + GNUNET_memcpy(&rec, + &src[off], + sizeof(rec)); + dest[i].expiration_time = GNUNET_ntohll(rec.expiration_time); + dest[i].data_size = ntohl((uint32_t)rec.data_size); + dest[i].record_type = ntohl(rec.record_type); + dest[i].flags = ntohl(rec.flags); + off += sizeof(rec); + if ((off + dest[i].data_size > len) || + (off + dest[i].data_size < off)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + dest[i].data = &src[off]; + off += dest[i].data_size; #if GNUNET_EXTRA_LOGGING - { - char *str; - - str = GNUNET_GNSRECORD_value_to_string (dest[i].record_type, - dest[i].data, - dest[i].data_size); - if (NULL == str) { - GNUNET_break_op (0); - return GNUNET_SYSERR; + char *str; + + str = GNUNET_GNSRECORD_value_to_string(dest[i].record_type, + dest[i].data, + dest[i].data_size); + if (NULL == str) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + GNUNET_free(str); } - GNUNET_free (str); - } #endif - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Deserialized record %u with flags %d and expiration time %llu\n", - i, - dest[i].flags, - (unsigned long long) dest[i].expiration_time); - } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Deserialized record %u with flags %d and expiration time %llu\n", + i, + dest[i].flags, + (unsigned long long)dest[i].expiration_time); + } return GNUNET_OK; } diff --git a/src/gnsrecord/perf_gnsrecord_crypto.c b/src/gnsrecord/perf_gnsrecord_crypto.c index a7cff9d48..a4fffd238 100644 --- a/src/gnsrecord/perf_gnsrecord_crypto.c +++ b/src/gnsrecord/perf_gnsrecord_crypto.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnsrecord/test_gnsrecord_crypto.c * @brief testcase for block creation, verification and decryption @@ -43,29 +43,29 @@ static struct GNUNET_GNSRECORD_Data * -create_record (int count) +create_record(int count) { struct GNUNET_GNSRECORD_Data *rd; - rd = GNUNET_new_array (count, - struct GNUNET_GNSRECORD_Data); + rd = GNUNET_new_array(count, + struct GNUNET_GNSRECORD_Data); for (unsigned int c = 0; c < count; c++) - { - rd[c].expiration_time = GNUNET_TIME_absolute_get().abs_value_us + 1000000000; - rd[c].record_type = TEST_RECORD_TYPE; - rd[c].data_size = TEST_RECORD_DATALEN; - rd[c].data = GNUNET_malloc(TEST_RECORD_DATALEN); - memset ((char *) rd[c].data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); - } + { + rd[c].expiration_time = GNUNET_TIME_absolute_get().abs_value_us + 1000000000; + rd[c].record_type = TEST_RECORD_TYPE; + rd[c].data_size = TEST_RECORD_DATALEN; + rd[c].data = GNUNET_malloc(TEST_RECORD_DATALEN); + memset((char *)rd[c].data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); + } return rd; } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_GNSRECORD_Block *block; struct GNUNET_HashCode query; @@ -75,45 +75,45 @@ run (void *cls, struct GNUNET_CRYPTO_EcdsaPrivateKey * privkey; struct GNUNET_TIME_Absolute expire; - (void) cls; - (void) args; - (void) cfgfile; - (void) cfg; + (void)cls; + (void)args; + (void)cfgfile; + (void)cfg; expire = GNUNET_TIME_absolute_get(); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (NULL != privkey); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(NULL != privkey); /* test block creation */ s_name = "DUMMY.dummy.gnunet"; - s_rd = create_record (RECORDS); - start_time = GNUNET_TIME_absolute_get (); - for (unsigned int i=0;i. SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnsrecord/plugin_gnsrecord_dns.c @@ -39,222 +39,234 @@ * @return NULL on error, otherwise human-readable representation of the value */ static char * -dns_value_to_string (void *cls, - uint32_t type, - const void *data, - size_t data_size) +dns_value_to_string(void *cls, + uint32_t type, + const void *data, + size_t data_size) { char *result; char tmp[INET6_ADDRSTRLEN]; switch (type) - { - case GNUNET_DNSPARSER_TYPE_A: - if (data_size != sizeof (struct in_addr)) - return NULL; - if (NULL == inet_ntop (AF_INET, data, tmp, sizeof (tmp))) - return NULL; - return GNUNET_strdup (tmp); - case GNUNET_DNSPARSER_TYPE_NS: { - char *ns; - size_t off; - - off = 0; - ns = GNUNET_DNSPARSER_parse_name (data, data_size, &off); - if ((NULL == ns) || (off != data_size)) { - GNUNET_break_op (0); - GNUNET_free_non_null (ns); - return NULL; + case GNUNET_DNSPARSER_TYPE_A: + if (data_size != sizeof(struct in_addr)) + return NULL; + if (NULL == inet_ntop(AF_INET, data, tmp, sizeof(tmp))) + return NULL; + return GNUNET_strdup(tmp); + + case GNUNET_DNSPARSER_TYPE_NS: { + char *ns; + size_t off; + + off = 0; + ns = GNUNET_DNSPARSER_parse_name(data, data_size, &off); + if ((NULL == ns) || (off != data_size)) + { + GNUNET_break_op(0); + GNUNET_free_non_null(ns); + return NULL; + } + return ns; } - return ns; - } - case GNUNET_DNSPARSER_TYPE_CNAME: { - char *cname; - size_t off; - - off = 0; - cname = GNUNET_DNSPARSER_parse_name (data, data_size, &off); - if ((NULL == cname) || (off != data_size)) - { - GNUNET_break_op (0); - GNUNET_free_non_null (cname); - return NULL; + + case GNUNET_DNSPARSER_TYPE_CNAME: { + char *cname; + size_t off; + + off = 0; + cname = GNUNET_DNSPARSER_parse_name(data, data_size, &off); + if ((NULL == cname) || (off != data_size)) + { + GNUNET_break_op(0); + GNUNET_free_non_null(cname); + return NULL; + } + return cname; } - return cname; - } - case GNUNET_DNSPARSER_TYPE_SOA: { - struct GNUNET_DNSPARSER_SoaRecord *soa; - size_t off; - - off = 0; - soa = GNUNET_DNSPARSER_parse_soa (data, data_size, &off); - if ((NULL == soa) || (off != data_size)) - { - GNUNET_break_op (0); - if (NULL != soa) - GNUNET_DNSPARSER_free_soa (soa); - return NULL; + + case GNUNET_DNSPARSER_TYPE_SOA: { + struct GNUNET_DNSPARSER_SoaRecord *soa; + size_t off; + + off = 0; + soa = GNUNET_DNSPARSER_parse_soa(data, data_size, &off); + if ((NULL == soa) || (off != data_size)) + { + GNUNET_break_op(0); + if (NULL != soa) + GNUNET_DNSPARSER_free_soa(soa); + return NULL; + } + GNUNET_asprintf(&result, + "rname=%s mname=%s %lu,%lu,%lu,%lu,%lu", + soa->rname, + soa->mname, + soa->serial, + soa->refresh, + soa->retry, + soa->expire, + soa->minimum_ttl); + GNUNET_DNSPARSER_free_soa(soa); + return result; } - GNUNET_asprintf (&result, - "rname=%s mname=%s %lu,%lu,%lu,%lu,%lu", - soa->rname, - soa->mname, - soa->serial, - soa->refresh, - soa->retry, - soa->expire, - soa->minimum_ttl); - GNUNET_DNSPARSER_free_soa (soa); - return result; - } - case GNUNET_DNSPARSER_TYPE_PTR: { - char *ptr; - size_t off; - - off = 0; - ptr = GNUNET_DNSPARSER_parse_name (data, data_size, &off); - if ((NULL == ptr) || (off != data_size)) - { - GNUNET_break_op (0); - GNUNET_free_non_null (ptr); - return NULL; + + case GNUNET_DNSPARSER_TYPE_PTR: { + char *ptr; + size_t off; + + off = 0; + ptr = GNUNET_DNSPARSER_parse_name(data, data_size, &off); + if ((NULL == ptr) || (off != data_size)) + { + GNUNET_break_op(0); + GNUNET_free_non_null(ptr); + return NULL; + } + return ptr; } - return ptr; - } - case GNUNET_DNSPARSER_TYPE_CERT: { - struct GNUNET_DNSPARSER_CertRecord *cert; - size_t off; - char *base64; - int len; - - off = 0; - cert = GNUNET_DNSPARSER_parse_cert (data, data_size, &off); - if ((NULL == cert) || (off != data_size)) - { - GNUNET_break_op (0); - GNUNET_DNSPARSER_free_cert (cert); - return NULL; + + case GNUNET_DNSPARSER_TYPE_CERT: { + struct GNUNET_DNSPARSER_CertRecord *cert; + size_t off; + char *base64; + int len; + + off = 0; + cert = GNUNET_DNSPARSER_parse_cert(data, data_size, &off); + if ((NULL == cert) || (off != data_size)) + { + GNUNET_break_op(0); + GNUNET_DNSPARSER_free_cert(cert); + return NULL; + } + len = GNUNET_STRINGS_base64_encode(cert->certificate_data, + cert->certificate_size, + &base64); + GNUNET_asprintf(&result, + "%u %u %u %.*s", + cert->cert_type, + cert->cert_tag, + cert->algorithm, + len, + base64); + GNUNET_free(base64); + GNUNET_DNSPARSER_free_cert(cert); + return result; } - len = GNUNET_STRINGS_base64_encode (cert->certificate_data, - cert->certificate_size, - &base64); - GNUNET_asprintf (&result, - "%u %u %u %.*s", - cert->cert_type, - cert->cert_tag, - cert->algorithm, - len, - base64); - GNUNET_free (base64); - GNUNET_DNSPARSER_free_cert (cert); - return result; - } - case GNUNET_DNSPARSER_TYPE_MX: { - struct GNUNET_DNSPARSER_MxRecord *mx; - size_t off; - - off = 0; - mx = GNUNET_DNSPARSER_parse_mx (data, data_size, &off); - if ((NULL == mx) || (off != data_size)) - { - GNUNET_break_op (0); - GNUNET_DNSPARSER_free_mx (mx); - return NULL; + + case GNUNET_DNSPARSER_TYPE_MX: { + struct GNUNET_DNSPARSER_MxRecord *mx; + size_t off; + + off = 0; + mx = GNUNET_DNSPARSER_parse_mx(data, data_size, &off); + if ((NULL == mx) || (off != data_size)) + { + GNUNET_break_op(0); + GNUNET_DNSPARSER_free_mx(mx); + return NULL; + } + GNUNET_asprintf(&result, + "%u,%s", + (unsigned int)mx->preference, + mx->mxhost); + GNUNET_DNSPARSER_free_mx(mx); + return result; } - GNUNET_asprintf (&result, - "%u,%s", - (unsigned int) mx->preference, - mx->mxhost); - GNUNET_DNSPARSER_free_mx (mx); - return result; - } - case GNUNET_DNSPARSER_TYPE_TXT: - return GNUNET_strndup (data, data_size); - case GNUNET_DNSPARSER_TYPE_AAAA: - if (data_size != sizeof (struct in6_addr)) - return NULL; - if (NULL == inet_ntop (AF_INET6, data, tmp, sizeof (tmp))) - return NULL; - return GNUNET_strdup (tmp); - case GNUNET_DNSPARSER_TYPE_SRV: { - struct GNUNET_DNSPARSER_SrvRecord *srv; - size_t off; - - off = 0; - srv = GNUNET_DNSPARSER_parse_srv (data, data_size, &off); - if ((NULL == srv) || (off != data_size)) - { - GNUNET_break_op (0); - if (NULL != srv) - GNUNET_DNSPARSER_free_srv (srv); - return NULL; + + case GNUNET_DNSPARSER_TYPE_TXT: + return GNUNET_strndup(data, data_size); + + case GNUNET_DNSPARSER_TYPE_AAAA: + if (data_size != sizeof(struct in6_addr)) + return NULL; + if (NULL == inet_ntop(AF_INET6, data, tmp, sizeof(tmp))) + return NULL; + return GNUNET_strdup(tmp); + + case GNUNET_DNSPARSER_TYPE_SRV: { + struct GNUNET_DNSPARSER_SrvRecord *srv; + size_t off; + + off = 0; + srv = GNUNET_DNSPARSER_parse_srv(data, data_size, &off); + if ((NULL == srv) || (off != data_size)) + { + GNUNET_break_op(0); + if (NULL != srv) + GNUNET_DNSPARSER_free_srv(srv); + return NULL; + } + GNUNET_asprintf(&result, + "%d %d %d %s", + srv->priority, + srv->weight, + srv->port, + srv->target); + GNUNET_DNSPARSER_free_srv(srv); + return result; } - GNUNET_asprintf (&result, - "%d %d %d %s", - srv->priority, - srv->weight, - srv->port, - srv->target); - GNUNET_DNSPARSER_free_srv (srv); - return result; - } - case GNUNET_DNSPARSER_TYPE_TLSA: { - const struct GNUNET_TUN_DnsTlsaRecord *tlsa; - char *tlsa_str; - char *hex; - - if (data_size < sizeof (struct GNUNET_TUN_DnsTlsaRecord)) - return NULL; /* malformed */ - tlsa = data; - hex = - GNUNET_DNSPARSER_bin_to_hex (&tlsa[1], - data_size - - sizeof (struct GNUNET_TUN_DnsTlsaRecord)); - if (0 == GNUNET_asprintf (&tlsa_str, - "%u %u %u %s", - (unsigned int) tlsa->usage, - (unsigned int) tlsa->selector, - (unsigned int) tlsa->matching_type, - hex)) - { - GNUNET_free (hex); - GNUNET_free (tlsa_str); - return NULL; + + case GNUNET_DNSPARSER_TYPE_TLSA: { + const struct GNUNET_TUN_DnsTlsaRecord *tlsa; + char *tlsa_str; + char *hex; + + if (data_size < sizeof(struct GNUNET_TUN_DnsTlsaRecord)) + return NULL; /* malformed */ + tlsa = data; + hex = + GNUNET_DNSPARSER_bin_to_hex(&tlsa[1], + data_size - + sizeof(struct GNUNET_TUN_DnsTlsaRecord)); + if (0 == GNUNET_asprintf(&tlsa_str, + "%u %u %u %s", + (unsigned int)tlsa->usage, + (unsigned int)tlsa->selector, + (unsigned int)tlsa->matching_type, + hex)) + { + GNUNET_free(hex); + GNUNET_free(tlsa_str); + return NULL; + } + GNUNET_free(hex); + return tlsa_str; } - GNUNET_free (hex); - return tlsa_str; - } - case GNUNET_DNSPARSER_TYPE_CAA: { //RFC6844 - const struct GNUNET_DNSPARSER_CaaRecord *caa; - char tag[15]; // between 1 and 15 bytes - char value[data_size]; - char *caa_str; - if (data_size < sizeof (struct GNUNET_DNSPARSER_CaaRecord)) - return NULL; /* malformed */ - caa = data; - if ((1 > caa->tag_len) || (15 < caa->tag_len)) - return NULL; /* malformed */ - memset (tag, 0, sizeof (tag)); - memset (value, 0, data_size); - memcpy (tag, &caa[1], caa->tag_len); - memcpy (value, - (char *) &caa[1] + caa->tag_len, - data_size - caa->tag_len - 2); - if (0 == GNUNET_asprintf (&caa_str, - "%u %s %s", - (unsigned int) caa->flags, - tag, - value)) - { - GNUNET_free (caa_str); + + case GNUNET_DNSPARSER_TYPE_CAA: { //RFC6844 + const struct GNUNET_DNSPARSER_CaaRecord *caa; + char tag[15]; // between 1 and 15 bytes + char value[data_size]; + char *caa_str; + if (data_size < sizeof(struct GNUNET_DNSPARSER_CaaRecord)) + return NULL; /* malformed */ + caa = data; + if ((1 > caa->tag_len) || (15 < caa->tag_len)) + return NULL; /* malformed */ + memset(tag, 0, sizeof(tag)); + memset(value, 0, data_size); + memcpy(tag, &caa[1], caa->tag_len); + memcpy(value, + (char *)&caa[1] + caa->tag_len, + data_size - caa->tag_len - 2); + if (0 == GNUNET_asprintf(&caa_str, + "%u %s %s", + (unsigned int)caa->flags, + tag, + value)) + { + GNUNET_free(caa_str); + return NULL; + } + return caa_str; + } + + default: return NULL; } - return caa_str; - } - default: - return NULL; - } } @@ -265,27 +277,26 @@ dns_value_to_string (void *cls, * @return the value, 0 if not found */ static unsigned int -rfc4398_mnemonic_to_value (const char *mnemonic) +rfc4398_mnemonic_to_value(const char *mnemonic) { - static struct - { + static struct { const char *mnemonic; unsigned int val; - } table[] = {{"PKIX", 1}, - {"SPKI", 2}, - {"PGP", 3}, - {"IPKIX", 4}, - {"ISPKI", 5}, - {"IPGP", 6}, - {"ACPKIX", 7}, - {"IACPKIX", 8}, - {"URI", 253}, - {"OID", 254}, - {NULL, 0}}; + } table[] = { { "PKIX", 1 }, + { "SPKI", 2 }, + { "PGP", 3 }, + { "IPKIX", 4 }, + { "ISPKI", 5 }, + { "IPGP", 6 }, + { "ACPKIX", 7 }, + { "IACPKIX", 8 }, + { "URI", 253 }, + { "OID", 254 }, + { NULL, 0 } }; unsigned int i; for (i = 0; NULL != table[i].mnemonic; i++) - if (0 == strcasecmp (mnemonic, table[i].mnemonic)) + if (0 == strcasecmp(mnemonic, table[i].mnemonic)) return table[i].val; return 0; } @@ -298,25 +309,24 @@ rfc4398_mnemonic_to_value (const char *mnemonic) * @return the value, 0 if not found */ static unsigned int -rfc4034_mnemonic_to_value (const char *mnemonic) +rfc4034_mnemonic_to_value(const char *mnemonic) { - static struct - { + static struct { const char *mnemonic; unsigned int val; - } table[] = {{"RSAMD5", 1}, - {"DH", 2}, - {"DSA", 3}, - {"ECC", 4}, - {"RSASHA1", 5}, - {"INDIRECT", 252}, - {"PRIVATEDNS", 253}, - {"PRIVATEOID", 254}, - {NULL, 0}}; + } table[] = { { "RSAMD5", 1 }, + { "DH", 2 }, + { "DSA", 3 }, + { "ECC", 4 }, + { "RSASHA1", 5 }, + { "INDIRECT", 252 }, + { "PRIVATEDNS", 253 }, + { "PRIVATEOID", 254 }, + { NULL, 0 } }; unsigned int i; for (i = 0; NULL != table[i].mnemonic; i++) - if (0 == strcasecmp (mnemonic, table[i].mnemonic)) + if (0 == strcasecmp(mnemonic, table[i].mnemonic)) return table[i].val; return 0; } @@ -334,11 +344,11 @@ rfc4034_mnemonic_to_value (const char *mnemonic) * @return #GNUNET_OK on success */ static int -dns_string_to_value (void *cls, - uint32_t type, - const char *s, - void **data, - size_t *data_size) +dns_string_to_value(void *cls, + uint32_t type, + const char *s, + void **data, + size_t *data_size) { struct in_addr value_a; struct in6_addr value_aaaa; @@ -347,341 +357,353 @@ dns_string_to_value (void *cls, if (NULL == s) return GNUNET_SYSERR; switch (type) - { - case GNUNET_DNSPARSER_TYPE_A: - if (1 != inet_pton (AF_INET, s, &value_a)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse IPv4 address `%s'\n"), - s); - return GNUNET_SYSERR; - } - *data = GNUNET_new (struct in_addr); - GNUNET_memcpy (*data, &value_a, sizeof (value_a)); - *data_size = sizeof (value_a); - return GNUNET_OK; - case GNUNET_DNSPARSER_TYPE_NS: { - char nsbuf[256]; - size_t off; - - off = 0; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_name (nsbuf, sizeof (nsbuf), &off, s)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to serialize NS record with value `%s'\n"), - s); - return GNUNET_SYSERR; - } - *data_size = off; - *data = GNUNET_malloc (off); - GNUNET_memcpy (*data, nsbuf, off); - return GNUNET_OK; - } - case GNUNET_DNSPARSER_TYPE_CNAME: { - char cnamebuf[256]; - size_t off; - - off = 0; - if (GNUNET_OK != GNUNET_DNSPARSER_builder_add_name (cnamebuf, - sizeof (cnamebuf), - &off, - s)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to serialize CNAME record with value `%s'\n"), - s); - return GNUNET_SYSERR; - } - *data_size = off; - *data = GNUNET_malloc (off); - GNUNET_memcpy (*data, cnamebuf, off); - return GNUNET_OK; - } - case GNUNET_DNSPARSER_TYPE_CERT: { - char *sdup; - const char *typep; - const char *keyp; - const char *algp; - const char *certp; - unsigned int type; - unsigned int key; - unsigned int alg; - size_t cert_size; - char *cert_data; - struct GNUNET_DNSPARSER_CertRecord cert; - - sdup = GNUNET_strdup (s); - typep = strtok (sdup, " "); - if ((NULL == typep) || - ((0 == (type = rfc4398_mnemonic_to_value (typep))) && - ((1 != sscanf (typep, "%u", &type)) || (type > UINT16_MAX)))) - { - GNUNET_free (sdup); - return GNUNET_SYSERR; - } - keyp = strtok (NULL, " "); - if ((NULL == keyp) || (1 != sscanf (keyp, "%u", &key)) || - (key > UINT16_MAX)) { - GNUNET_free (sdup); - return GNUNET_SYSERR; - } - alg = 0; - algp = strtok (NULL, " "); - if ((NULL == algp) || - ((0 == (type = rfc4034_mnemonic_to_value (typep))) && - ((1 != sscanf (algp, "%u", &alg)) || (alg > UINT8_MAX)))) - { - GNUNET_free (sdup); - return GNUNET_SYSERR; - } - certp = strtok (NULL, " "); - if ((NULL == certp) || (0 == strlen (certp))) - { - GNUNET_free (sdup); - return GNUNET_SYSERR; - } - cert_size = GNUNET_STRINGS_base64_decode (certp, - strlen (certp), - (void **) &cert_data); - GNUNET_free (sdup); - cert.cert_type = type; - cert.cert_tag = key; - cert.algorithm = alg; - cert.certificate_size = cert_size; - cert.certificate_data = cert_data; - { - char certbuf[cert_size + sizeof (struct GNUNET_TUN_DnsCertRecord)]; + case GNUNET_DNSPARSER_TYPE_A: + if (1 != inet_pton(AF_INET, s, &value_a)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse IPv4 address `%s'\n"), + s); + return GNUNET_SYSERR; + } + *data = GNUNET_new(struct in_addr); + GNUNET_memcpy(*data, &value_a, sizeof(value_a)); + *data_size = sizeof(value_a); + return GNUNET_OK; + + case GNUNET_DNSPARSER_TYPE_NS: { + char nsbuf[256]; size_t off; off = 0; - if (GNUNET_OK != GNUNET_DNSPARSER_builder_add_cert (certbuf, - sizeof (certbuf), - &off, - &cert)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to serialize CERT record with %u bytes\n"), - (unsigned int) cert_size); - GNUNET_free (cert_data); - return GNUNET_SYSERR; - } + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_name(nsbuf, sizeof(nsbuf), &off, s)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to serialize NS record with value `%s'\n"), + s); + return GNUNET_SYSERR; + } *data_size = off; - *data = GNUNET_malloc (off); - GNUNET_memcpy (*data, certbuf, off); - } - GNUNET_free (cert_data); - return GNUNET_OK; - } - case GNUNET_DNSPARSER_TYPE_SOA: { - struct GNUNET_DNSPARSER_SoaRecord soa; - char soabuf[540]; - char soa_rname[253 + 1]; - char soa_mname[253 + 1]; - unsigned int soa_serial; - unsigned int soa_refresh; - unsigned int soa_retry; - unsigned int soa_expire; - unsigned int soa_min; - size_t off; - - if (7 != sscanf (s, - "rname=%253s mname=%253s %u,%u,%u,%u,%u", - soa_rname, - soa_mname, - &soa_serial, - &soa_refresh, - &soa_retry, - &soa_expire, - &soa_min)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse SOA record `%s'\n"), - s); - return GNUNET_SYSERR; - } - soa.mname = soa_mname; - soa.rname = soa_rname; - soa.serial = (uint32_t) soa_serial; - soa.refresh = (uint32_t) soa_refresh; - soa.retry = (uint32_t) soa_retry; - soa.expire = (uint32_t) soa_expire; - soa.minimum_ttl = (uint32_t) soa_min; - off = 0; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_soa (soabuf, sizeof (soabuf), &off, &soa)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to serialize SOA record with mname `%s' and rname `%s'\n"), - soa_mname, - soa_rname); - return GNUNET_SYSERR; + *data = GNUNET_malloc(off); + GNUNET_memcpy(*data, nsbuf, off); + return GNUNET_OK; } - *data_size = off; - *data = GNUNET_malloc (off); - GNUNET_memcpy (*data, soabuf, off); - return GNUNET_OK; - } - case GNUNET_DNSPARSER_TYPE_PTR: { - char ptrbuf[256]; - size_t off; - - off = 0; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_name (ptrbuf, sizeof (ptrbuf), &off, s)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to serialize PTR record with value `%s'\n"), - s); - return GNUNET_SYSERR; + + case GNUNET_DNSPARSER_TYPE_CNAME: { + char cnamebuf[256]; + size_t off; + + off = 0; + if (GNUNET_OK != GNUNET_DNSPARSER_builder_add_name(cnamebuf, + sizeof(cnamebuf), + &off, + s)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to serialize CNAME record with value `%s'\n"), + s); + return GNUNET_SYSERR; + } + *data_size = off; + *data = GNUNET_malloc(off); + GNUNET_memcpy(*data, cnamebuf, off); + return GNUNET_OK; } - *data_size = off; - *data = GNUNET_malloc (off); - GNUNET_memcpy (*data, ptrbuf, off); - return GNUNET_OK; - } - case GNUNET_DNSPARSER_TYPE_MX: { - struct GNUNET_DNSPARSER_MxRecord mx; - char mxbuf[258]; - char mxhost[253 + 1]; - unsigned int mx_pref; - size_t off; - - if (2 != sscanf (s, "%u,%253s", &mx_pref, mxhost)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse MX record `%s'\n"), - s); - return GNUNET_SYSERR; + + case GNUNET_DNSPARSER_TYPE_CERT: { + char *sdup; + const char *typep; + const char *keyp; + const char *algp; + const char *certp; + unsigned int type; + unsigned int key; + unsigned int alg; + size_t cert_size; + char *cert_data; + struct GNUNET_DNSPARSER_CertRecord cert; + + sdup = GNUNET_strdup(s); + typep = strtok(sdup, " "); + if ((NULL == typep) || + ((0 == (type = rfc4398_mnemonic_to_value(typep))) && + ((1 != sscanf(typep, "%u", &type)) || (type > UINT16_MAX)))) + { + GNUNET_free(sdup); + return GNUNET_SYSERR; + } + keyp = strtok(NULL, " "); + if ((NULL == keyp) || (1 != sscanf(keyp, "%u", &key)) || + (key > UINT16_MAX)) + { + GNUNET_free(sdup); + return GNUNET_SYSERR; + } + alg = 0; + algp = strtok(NULL, " "); + if ((NULL == algp) || + ((0 == (type = rfc4034_mnemonic_to_value(typep))) && + ((1 != sscanf(algp, "%u", &alg)) || (alg > UINT8_MAX)))) + { + GNUNET_free(sdup); + return GNUNET_SYSERR; + } + certp = strtok(NULL, " "); + if ((NULL == certp) || (0 == strlen(certp))) + { + GNUNET_free(sdup); + return GNUNET_SYSERR; + } + cert_size = GNUNET_STRINGS_base64_decode(certp, + strlen(certp), + (void **)&cert_data); + GNUNET_free(sdup); + cert.cert_type = type; + cert.cert_tag = key; + cert.algorithm = alg; + cert.certificate_size = cert_size; + cert.certificate_data = cert_data; + { + char certbuf[cert_size + sizeof(struct GNUNET_TUN_DnsCertRecord)]; + size_t off; + + off = 0; + if (GNUNET_OK != GNUNET_DNSPARSER_builder_add_cert(certbuf, + sizeof(certbuf), + &off, + &cert)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to serialize CERT record with %u bytes\n"), + (unsigned int)cert_size); + GNUNET_free(cert_data); + return GNUNET_SYSERR; + } + *data_size = off; + *data = GNUNET_malloc(off); + GNUNET_memcpy(*data, certbuf, off); + } + GNUNET_free(cert_data); + return GNUNET_OK; } - mx.preference = (uint16_t) mx_pref; - mx.mxhost = mxhost; - off = 0; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_mx (mxbuf, sizeof (mxbuf), &off, &mx)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to serialize MX record with hostname `%s'\n"), - mxhost); - return GNUNET_SYSERR; + case GNUNET_DNSPARSER_TYPE_SOA: { + struct GNUNET_DNSPARSER_SoaRecord soa; + char soabuf[540]; + char soa_rname[253 + 1]; + char soa_mname[253 + 1]; + unsigned int soa_serial; + unsigned int soa_refresh; + unsigned int soa_retry; + unsigned int soa_expire; + unsigned int soa_min; + size_t off; + + if (7 != sscanf(s, + "rname=%253s mname=%253s %u,%u,%u,%u,%u", + soa_rname, + soa_mname, + &soa_serial, + &soa_refresh, + &soa_retry, + &soa_expire, + &soa_min)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse SOA record `%s'\n"), + s); + return GNUNET_SYSERR; + } + soa.mname = soa_mname; + soa.rname = soa_rname; + soa.serial = (uint32_t)soa_serial; + soa.refresh = (uint32_t)soa_refresh; + soa.retry = (uint32_t)soa_retry; + soa.expire = (uint32_t)soa_expire; + soa.minimum_ttl = (uint32_t)soa_min; + off = 0; + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_soa(soabuf, sizeof(soabuf), &off, &soa)) + { + GNUNET_log( + GNUNET_ERROR_TYPE_ERROR, + _("Failed to serialize SOA record with mname `%s' and rname `%s'\n"), + soa_mname, + soa_rname); + return GNUNET_SYSERR; + } + *data_size = off; + *data = GNUNET_malloc(off); + GNUNET_memcpy(*data, soabuf, off); + return GNUNET_OK; } - *data_size = off; - *data = GNUNET_malloc (off); - GNUNET_memcpy (*data, mxbuf, off); - return GNUNET_OK; - } - case GNUNET_DNSPARSER_TYPE_SRV: { - struct GNUNET_DNSPARSER_SrvRecord srv; - char srvbuf[270]; - char srvtarget[253 + 1]; - unsigned int priority; - unsigned int weight; - unsigned int port; - size_t off; - - if (4 != sscanf (s, "%u %u %u %253s", &priority, &weight, &port, srvtarget)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse SRV record `%s'\n"), - s); - return GNUNET_SYSERR; + + case GNUNET_DNSPARSER_TYPE_PTR: { + char ptrbuf[256]; + size_t off; + + off = 0; + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_name(ptrbuf, sizeof(ptrbuf), &off, s)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to serialize PTR record with value `%s'\n"), + s); + return GNUNET_SYSERR; + } + *data_size = off; + *data = GNUNET_malloc(off); + GNUNET_memcpy(*data, ptrbuf, off); + return GNUNET_OK; } - srv.priority = (uint16_t) priority; - srv.weight = (uint16_t) weight; - srv.port = (uint16_t) port; - srv.target = srvtarget; - off = 0; - if (GNUNET_OK != - GNUNET_DNSPARSER_builder_add_srv (srvbuf, sizeof (srvbuf), &off, &srv)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to serialize SRV record with target `%s'\n"), - srvtarget); - return GNUNET_SYSERR; + + case GNUNET_DNSPARSER_TYPE_MX: { + struct GNUNET_DNSPARSER_MxRecord mx; + char mxbuf[258]; + char mxhost[253 + 1]; + unsigned int mx_pref; + size_t off; + + if (2 != sscanf(s, "%u,%253s", &mx_pref, mxhost)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse MX record `%s'\n"), + s); + return GNUNET_SYSERR; + } + mx.preference = (uint16_t)mx_pref; + mx.mxhost = mxhost; + off = 0; + + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_mx(mxbuf, sizeof(mxbuf), &off, &mx)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to serialize MX record with hostname `%s'\n"), + mxhost); + return GNUNET_SYSERR; + } + *data_size = off; + *data = GNUNET_malloc(off); + GNUNET_memcpy(*data, mxbuf, off); + return GNUNET_OK; } - *data_size = off; - *data = GNUNET_malloc (off); - GNUNET_memcpy (*data, srvbuf, off); - return GNUNET_OK; - } - case GNUNET_DNSPARSER_TYPE_TXT: - *data = GNUNET_strdup (s); - *data_size = strlen (s); - return GNUNET_OK; - case GNUNET_DNSPARSER_TYPE_AAAA: - if (1 != inet_pton (AF_INET6, s, &value_aaaa)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse IPv6 address `%s'\n"), - s); - return GNUNET_SYSERR; + + case GNUNET_DNSPARSER_TYPE_SRV: { + struct GNUNET_DNSPARSER_SrvRecord srv; + char srvbuf[270]; + char srvtarget[253 + 1]; + unsigned int priority; + unsigned int weight; + unsigned int port; + size_t off; + + if (4 != sscanf(s, "%u %u %u %253s", &priority, &weight, &port, srvtarget)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse SRV record `%s'\n"), + s); + return GNUNET_SYSERR; + } + srv.priority = (uint16_t)priority; + srv.weight = (uint16_t)weight; + srv.port = (uint16_t)port; + srv.target = srvtarget; + off = 0; + if (GNUNET_OK != + GNUNET_DNSPARSER_builder_add_srv(srvbuf, sizeof(srvbuf), &off, &srv)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to serialize SRV record with target `%s'\n"), + srvtarget); + return GNUNET_SYSERR; + } + *data_size = off; + *data = GNUNET_malloc(off); + GNUNET_memcpy(*data, srvbuf, off); + return GNUNET_OK; } - *data = GNUNET_new (struct in6_addr); - *data_size = sizeof (struct in6_addr); - GNUNET_memcpy (*data, &value_aaaa, sizeof (value_aaaa)); - return GNUNET_OK; - case GNUNET_DNSPARSER_TYPE_TLSA: { - unsigned int usage; - unsigned int selector; - unsigned int matching_type; - size_t slen = strlen (s) + 1; - char hex[slen]; - - if (4 != sscanf (s, "%u %u %u %s", &usage, &selector, &matching_type, hex)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse TLSA record string `%s'\n"), - s); - *data_size = 0; - return GNUNET_SYSERR; + + case GNUNET_DNSPARSER_TYPE_TXT: + *data = GNUNET_strdup(s); + *data_size = strlen(s); + return GNUNET_OK; + + case GNUNET_DNSPARSER_TYPE_AAAA: + if (1 != inet_pton(AF_INET6, s, &value_aaaa)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse IPv6 address `%s'\n"), + s); + return GNUNET_SYSERR; + } + *data = GNUNET_new(struct in6_addr); + *data_size = sizeof(struct in6_addr); + GNUNET_memcpy(*data, &value_aaaa, sizeof(value_aaaa)); + return GNUNET_OK; + + case GNUNET_DNSPARSER_TYPE_TLSA: { + unsigned int usage; + unsigned int selector; + unsigned int matching_type; + size_t slen = strlen(s) + 1; + char hex[slen]; + + if (4 != sscanf(s, "%u %u %u %s", &usage, &selector, &matching_type, hex)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse TLSA record string `%s'\n"), + s); + *data_size = 0; + return GNUNET_SYSERR; + } + + *data_size = sizeof(struct GNUNET_TUN_DnsTlsaRecord) + strlen(hex) / 2; + *data = tlsa = GNUNET_malloc(*data_size); + tlsa->usage = (uint8_t)usage; + tlsa->selector = (uint8_t)selector; + tlsa->matching_type = (uint8_t)matching_type; + if (strlen(hex) / 2 != GNUNET_DNSPARSER_hex_to_bin(hex, &tlsa[1])) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse TLSA record string `%s'\n"), + s); + GNUNET_free(*data); + *data = NULL; + *data_size = 0; + return GNUNET_SYSERR; + } + return GNUNET_OK; } - *data_size = sizeof (struct GNUNET_TUN_DnsTlsaRecord) + strlen (hex) / 2; - *data = tlsa = GNUNET_malloc (*data_size); - tlsa->usage = (uint8_t) usage; - tlsa->selector = (uint8_t) selector; - tlsa->matching_type = (uint8_t) matching_type; - if (strlen (hex) / 2 != GNUNET_DNSPARSER_hex_to_bin (hex, &tlsa[1])) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse TLSA record string `%s'\n"), - s); - GNUNET_free (*data); - *data = NULL; - *data_size = 0; - return GNUNET_SYSERR; + case GNUNET_DNSPARSER_TYPE_CAA: { //RFC6844 + struct GNUNET_DNSPARSER_CaaRecord *caa; + unsigned int flags; + char tag[15]; //Max tag length 15 + char value[strlen(s) + 1]; //Should be more than enough + + if (3 != sscanf(s, "%u %s %[^\n]", &flags, tag, value)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to parse CAA record string `%s'\n"), + s); + *data_size = 0; + return GNUNET_SYSERR; + } + *data_size = sizeof(struct GNUNET_DNSPARSER_CaaRecord) + strlen(tag) + + strlen(value); + *data = caa = GNUNET_malloc(*data_size); + caa->flags = flags; + memcpy(&caa[1], tag, strlen(tag)); + caa->tag_len = strlen(tag); + memcpy((char *)&caa[1] + caa->tag_len, value, strlen(value)); + return GNUNET_OK; } - return GNUNET_OK; - } - case GNUNET_DNSPARSER_TYPE_CAA: { //RFC6844 - struct GNUNET_DNSPARSER_CaaRecord *caa; - unsigned int flags; - char tag[15]; //Max tag length 15 - char value[strlen (s) + 1]; //Should be more than enough - - if (3 != sscanf (s, "%u %s %[^\n]", &flags, tag, value)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Unable to parse CAA record string `%s'\n"), - s); - *data_size = 0; + + default: return GNUNET_SYSERR; } - *data_size = sizeof (struct GNUNET_DNSPARSER_CaaRecord) + strlen (tag) + - strlen (value); - *data = caa = GNUNET_malloc (*data_size); - caa->flags = flags; - memcpy (&caa[1], tag, strlen (tag)); - caa->tag_len = strlen (tag); - memcpy ((char *) &caa[1] + caa->tag_len, value, strlen (value)); - return GNUNET_OK; - } - default: - return GNUNET_SYSERR; - } } @@ -689,23 +711,22 @@ dns_string_to_value (void *cls, * Mapping of record type numbers to human-readable * record type names. */ -static struct -{ +static struct { const char *name; uint32_t number; -} name_map[] = {{"A", GNUNET_DNSPARSER_TYPE_A}, - {"NS", GNUNET_DNSPARSER_TYPE_NS}, - {"CNAME", GNUNET_DNSPARSER_TYPE_CNAME}, - {"SOA", GNUNET_DNSPARSER_TYPE_SOA}, - {"PTR", GNUNET_DNSPARSER_TYPE_PTR}, - {"MX", GNUNET_DNSPARSER_TYPE_MX}, - {"TXT", GNUNET_DNSPARSER_TYPE_TXT}, - {"AAAA", GNUNET_DNSPARSER_TYPE_AAAA}, - {"SRV", GNUNET_DNSPARSER_TYPE_SRV}, - {"TLSA", GNUNET_DNSPARSER_TYPE_TLSA}, - {"CERT", GNUNET_DNSPARSER_TYPE_CERT}, - {"CAA", GNUNET_DNSPARSER_TYPE_CAA}, - {NULL, UINT32_MAX}}; +} name_map[] = { { "A", GNUNET_DNSPARSER_TYPE_A }, + { "NS", GNUNET_DNSPARSER_TYPE_NS }, + { "CNAME", GNUNET_DNSPARSER_TYPE_CNAME }, + { "SOA", GNUNET_DNSPARSER_TYPE_SOA }, + { "PTR", GNUNET_DNSPARSER_TYPE_PTR }, + { "MX", GNUNET_DNSPARSER_TYPE_MX }, + { "TXT", GNUNET_DNSPARSER_TYPE_TXT }, + { "AAAA", GNUNET_DNSPARSER_TYPE_AAAA }, + { "SRV", GNUNET_DNSPARSER_TYPE_SRV }, + { "TLSA", GNUNET_DNSPARSER_TYPE_TLSA }, + { "CERT", GNUNET_DNSPARSER_TYPE_CERT }, + { "CAA", GNUNET_DNSPARSER_TYPE_CAA }, + { NULL, UINT32_MAX } }; /** @@ -716,13 +737,13 @@ static struct * @return corresponding number, UINT32_MAX on error */ static uint32_t -dns_typename_to_number (void *cls, const char *dns_typename) +dns_typename_to_number(void *cls, const char *dns_typename) { unsigned int i; i = 0; while ((NULL != name_map[i].name) && - (0 != strcasecmp (dns_typename, name_map[i].name))) + (0 != strcasecmp(dns_typename, name_map[i].name))) i++; return name_map[i].number; } @@ -736,7 +757,7 @@ dns_typename_to_number (void *cls, const char *dns_typename) * @return corresponding typestring, NULL on error */ static const char * -dns_number_to_typename (void *cls, uint32_t type) +dns_number_to_typename(void *cls, uint32_t type) { unsigned int i; @@ -754,11 +775,11 @@ dns_number_to_typename (void *cls, uint32_t type) * @return the exported block API */ void * -libgnunet_plugin_gnsrecord_dns_init (void *cls) +libgnunet_plugin_gnsrecord_dns_init(void *cls) { struct GNUNET_GNSRECORD_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_GNSRECORD_PluginFunctions); + api = GNUNET_new(struct GNUNET_GNSRECORD_PluginFunctions); api->value_to_string = &dns_value_to_string; api->string_to_value = &dns_string_to_value; api->typename_to_number = &dns_typename_to_number; @@ -774,11 +795,11 @@ libgnunet_plugin_gnsrecord_dns_init (void *cls) * @return NULL */ void * -libgnunet_plugin_gnsrecord_dns_done (void *cls) +libgnunet_plugin_gnsrecord_dns_done(void *cls) { struct GNUNET_GNSRECORD_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/gnsrecord/test_gnsrecord_block_expiration.c b/src/gnsrecord/test_gnsrecord_block_expiration.c index 1a9dbc105..24aa3d921 100644 --- a/src/gnsrecord/test_gnsrecord_block_expiration.c +++ b/src/gnsrecord/test_gnsrecord_block_expiration.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnsrecord/test_gnsrecord_crypto.c * @brief testcase for block creation, verification and decryption @@ -44,17 +44,17 @@ static int res; static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_GNSRECORD_Data rd[2]; struct GNUNET_TIME_Absolute expiration_abs; struct GNUNET_TIME_Absolute expiration_abs_shadow; expiration_abs.abs_value_us = GNUNET_TIME_absolute_get().abs_value_us + - GNUNET_TIME_UNIT_SECONDS.rel_value_us; + GNUNET_TIME_UNIT_SECONDS.rel_value_us; expiration_abs_shadow.abs_value_us = GNUNET_TIME_absolute_get().abs_value_us + - GNUNET_TIME_UNIT_MINUTES.rel_value_us; + GNUNET_TIME_UNIT_MINUTES.rel_value_us; /* create record */ rd[0].expiration_time = expiration_abs.abs_value_us; @@ -62,42 +62,41 @@ run (void *cls, char *const *args, const char *cfgfile, rd[0].data_size = TEST_RECORD_DATALEN; rd[0].data = GNUNET_malloc(TEST_RECORD_DATALEN); rd[0].flags = GNUNET_GNSRECORD_RF_NONE; - memset ((char *) rd[0].data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); + memset((char *)rd[0].data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); rd[1].expiration_time = expiration_abs.abs_value_us; rd[1].record_type = TEST_RECORD_TYPE; rd[1].data_size = TEST_RECORD_DATALEN; rd[1].data = GNUNET_malloc(TEST_RECORD_DATALEN); rd[1].flags = GNUNET_GNSRECORD_RF_NONE; - memset ((char *) rd[1].data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); + memset((char *)rd[1].data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); - GNUNET_assert (expiration_abs.abs_value_us == GNUNET_GNSRECORD_record_get_expiration_time(2, rd).abs_value_us); + GNUNET_assert(expiration_abs.abs_value_us == GNUNET_GNSRECORD_record_get_expiration_time(2, rd).abs_value_us); rd[1].expiration_time = expiration_abs_shadow.abs_value_us; rd[1].record_type = TEST_RECORD_TYPE; rd[1].data_size = TEST_RECORD_DATALEN; rd[1].data = GNUNET_malloc(TEST_RECORD_DATALEN); rd[1].flags = GNUNET_GNSRECORD_RF_SHADOW_RECORD; - memset ((char *) rd[1].data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); + memset((char *)rd[1].data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); - GNUNET_assert (expiration_abs_shadow.abs_value_us == GNUNET_GNSRECORD_record_get_expiration_time(2, rd).abs_value_us); + GNUNET_assert(expiration_abs_shadow.abs_value_us == GNUNET_GNSRECORD_record_get_expiration_time(2, rd).abs_value_us); res = 0; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { static char *const argvx[] = { "test-gnsrecord-crypto", - NULL - }; + NULL }; static struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; res = 1; - GNUNET_PROGRAM_run ((sizeof (argvx) / sizeof (char *)) - 1, argvx, "test-namestore-api", - "nohelp", options, &run, &res); + GNUNET_PROGRAM_run((sizeof(argvx) / sizeof(char *)) - 1, argvx, "test-namestore-api", + "nohelp", options, &run, &res); return res; } diff --git a/src/gnsrecord/test_gnsrecord_crypto.c b/src/gnsrecord/test_gnsrecord_crypto.c index 35cc5d34b..6be870e17 100644 --- a/src/gnsrecord/test_gnsrecord_crypto.c +++ b/src/gnsrecord/test_gnsrecord_crypto.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnsrecord/test_gnsrecord_crypto.c * @brief testcase for block creation, verification and decryption @@ -51,54 +51,53 @@ static int res; static struct GNUNET_GNSRECORD_Data * -create_record (int count) +create_record(int count) { struct GNUNET_GNSRECORD_Data *rd; - rd = GNUNET_new_array (count, struct GNUNET_GNSRECORD_Data); + rd = GNUNET_new_array(count, struct GNUNET_GNSRECORD_Data); for (unsigned int c = 0; c < count; c++) - { - rd[c].expiration_time = GNUNET_TIME_absolute_get().abs_value_us + 1000000000; - rd[c].record_type = TEST_RECORD_TYPE; - rd[c].data_size = TEST_RECORD_DATALEN; - rd[c].data = GNUNET_malloc(TEST_RECORD_DATALEN); - memset ((char *) rd[c].data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); - } + { + rd[c].expiration_time = GNUNET_TIME_absolute_get().abs_value_us + 1000000000; + rd[c].record_type = TEST_RECORD_TYPE; + rd[c].data_size = TEST_RECORD_DATALEN; + rd[c].data = GNUNET_malloc(TEST_RECORD_DATALEN); + memset((char *)rd[c].data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); + } return rd; } static void -rd_decrypt_cb (void *cls, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +rd_decrypt_cb(void *cls, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { char rd_cmp_data[TEST_RECORD_DATALEN]; - GNUNET_assert (RECORDS == rd_count); - GNUNET_assert (NULL != rd); - memset (rd_cmp_data, - 'a', - TEST_RECORD_DATALEN); + GNUNET_assert(RECORDS == rd_count); + GNUNET_assert(NULL != rd); + memset(rd_cmp_data, + 'a', + TEST_RECORD_DATALEN); for (unsigned int c = 0; c < rd_count; c++) - { - GNUNET_assert (TEST_RECORD_TYPE == rd[c].record_type); - GNUNET_assert (TEST_RECORD_DATALEN == rd[c].data_size); - GNUNET_assert (0 == memcmp (&rd_cmp_data, + { + GNUNET_assert(TEST_RECORD_TYPE == rd[c].record_type); + GNUNET_assert(TEST_RECORD_DATALEN == rd[c].data_size); + GNUNET_assert(0 == memcmp(&rd_cmp_data, rd[c].data, TEST_RECORD_DATALEN)); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Block was decrypted successfully \n"); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Block was decrypted successfully \n"); res = 0; - } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_GNSRECORD_Block *block; struct GNUNET_CRYPTO_EcdsaPublicKey pubkey; @@ -106,48 +105,48 @@ run (void *cls, struct GNUNET_HashCode query_priv; struct GNUNET_TIME_Absolute expire = GNUNET_TIME_absolute_get(); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (NULL != privkey); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(NULL != privkey); /* get public key */ - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, - &pubkey); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, + &pubkey); /* test query derivation */ - GNUNET_GNSRECORD_query_from_private_key (privkey, - "testlabel", - &query_priv); - GNUNET_GNSRECORD_query_from_public_key (&pubkey, + GNUNET_GNSRECORD_query_from_private_key(privkey, "testlabel", - &query_pub); - GNUNET_assert (0 == memcmp (&query_priv, - &query_pub, - sizeof (struct GNUNET_HashCode))); + &query_priv); + GNUNET_GNSRECORD_query_from_public_key(&pubkey, + "testlabel", + &query_pub); + GNUNET_assert(0 == memcmp(&query_priv, + &query_pub, + sizeof(struct GNUNET_HashCode))); /* create record */ s_name = "DUMMY.dummy.gnunet"; - s_rd = create_record (RECORDS); + s_rd = create_record(RECORDS); /* Create block */ - GNUNET_assert (NULL != (block = - GNUNET_GNSRECORD_block_create (privkey, + GNUNET_assert(NULL != (block = + GNUNET_GNSRECORD_block_create(privkey, expire, s_name, s_rd, RECORDS))); - GNUNET_assert (GNUNET_OK == - GNUNET_GNSRECORD_block_verify (block)); - GNUNET_assert (GNUNET_OK == - GNUNET_GNSRECORD_block_decrypt (block, - &pubkey, - s_name, - &rd_decrypt_cb, - s_name)); - GNUNET_free (block); - GNUNET_free (privkey); + GNUNET_assert(GNUNET_OK == + GNUNET_GNSRECORD_block_verify(block)); + GNUNET_assert(GNUNET_OK == + GNUNET_GNSRECORD_block_decrypt(block, + &pubkey, + s_name, + &rd_decrypt_cb, + s_name)); + GNUNET_free(block); + GNUNET_free(privkey); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { static char *const argvx[] = { "test-gnsrecord-crypto", @@ -158,11 +157,11 @@ main (int argc, char *argv[]) }; res = 1; - GNUNET_PROGRAM_run ((sizeof (argvx) / sizeof (char *)) - 1, - argvx, - "test-gnsrecord-crypto", - "nohelp", options, - &run, &res); + GNUNET_PROGRAM_run((sizeof(argvx) / sizeof(char *)) - 1, + argvx, + "test-gnsrecord-crypto", + "nohelp", options, + &run, &res); return res; } diff --git a/src/gnsrecord/test_gnsrecord_serialization.c b/src/gnsrecord/test_gnsrecord_serialization.c index f2ee1a479..34dcff5cb 100644 --- a/src/gnsrecord/test_gnsrecord_serialization.c +++ b/src/gnsrecord/test_gnsrecord_serialization.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnsrecord/test_gnsrecord_serialization.c * @brief testcase for gnsrecord_serialization.c @@ -26,16 +26,16 @@ #include "gnunet_gnsrecord_lib.h" #include "gnunet_dnsparser_lib.h" -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static int res; static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { size_t len; int c; @@ -44,112 +44,111 @@ run (void *cls, size_t data_len; struct GNUNET_GNSRECORD_Data src[rd_count]; - memset(src, '\0', rd_count * sizeof (struct GNUNET_GNSRECORD_Data)); + memset(src, '\0', rd_count * sizeof(struct GNUNET_GNSRECORD_Data)); data_len = 0; for (c = 0; c < rd_count; c++) - { - src[c].record_type = GNUNET_DNSPARSER_TYPE_TXT; - src[c].data_size = data_len; - src[c].data = GNUNET_malloc (data_len); + { + src[c].record_type = GNUNET_DNSPARSER_TYPE_TXT; + src[c].data_size = data_len; + src[c].data = GNUNET_malloc(data_len); - /* Setting data to data_len * record_type */ - memset ((char *) src[c].data, 'a', data_len); - data_len += 10; - } + /* Setting data to data_len * record_type */ + memset((char *)src[c].data, 'a', data_len); + data_len += 10; + } res = 0; - len = GNUNET_GNSRECORD_records_get_size (rd_count, src); + len = GNUNET_GNSRECORD_records_get_size(rd_count, src); char rd_ser[len]; - GNUNET_assert (len == - GNUNET_GNSRECORD_records_serialize (rd_count, - src, - len, - rd_ser)); + GNUNET_assert(len == + GNUNET_GNSRECORD_records_serialize(rd_count, + src, + len, + rd_ser)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Serialized data len: %u\n", - (unsigned int) len); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Serialized data len: %u\n", + (unsigned int)len); - GNUNET_assert (rd_ser != NULL); + GNUNET_assert(rd_ser != NULL); { struct GNUNET_GNSRECORD_Data dst[rd_count]; - GNUNET_assert (GNUNET_OK == - GNUNET_GNSRECORD_records_deserialize (len, - rd_ser, - rd_count, - dst)); + GNUNET_assert(GNUNET_OK == + GNUNET_GNSRECORD_records_deserialize(len, + rd_ser, + rd_count, + dst)); - GNUNET_assert (dst != NULL); + GNUNET_assert(dst != NULL); for (c = 0; c < rd_count; c++) - { - if (src[c].data_size != dst[c].data_size) - { - GNUNET_break (0); - res = 1; - } - if (src[c].expiration_time != dst[c].expiration_time) - { - GNUNET_break (0); - res = 1; - } - if (src[c].flags != dst[c].flags) - { - GNUNET_break (0); - res = 1; - } - if (src[c].record_type != dst[c].record_type) { - GNUNET_break (0); - res = 1; - } - - { - size_t data_size = src[c].data_size; - char data[data_size]; + if (src[c].data_size != dst[c].data_size) + { + GNUNET_break(0); + res = 1; + } + if (src[c].expiration_time != dst[c].expiration_time) + { + GNUNET_break(0); + res = 1; + } + if (src[c].flags != dst[c].flags) + { + GNUNET_break(0); + res = 1; + } + if (src[c].record_type != dst[c].record_type) + { + GNUNET_break(0); + res = 1; + } - memset (data, 'a', data_size); - if (0 != memcmp (data, dst[c].data, data_size)) - { - GNUNET_break (0); - res = 1; - } - if (0 != memcmp (data, src[c].data, data_size)) - { - GNUNET_break (0); - res = 1; - } - if (0 != memcmp (src[c].data, dst[c].data, src[c].data_size)) { - GNUNET_break (0); - res = 1; + size_t data_size = src[c].data_size; + char data[data_size]; + + memset(data, 'a', data_size); + if (0 != memcmp(data, dst[c].data, data_size)) + { + GNUNET_break(0); + res = 1; + } + if (0 != memcmp(data, src[c].data, data_size)) + { + GNUNET_break(0); + res = 1; + } + if (0 != memcmp(src[c].data, dst[c].data, src[c].data_size)) + { + GNUNET_break(0); + res = 1; + } } } - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Element [%i]: EQUAL\n", c); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Element [%i]: EQUAL\n", c); } for (c = 0; c < rd_count; c++) - { - GNUNET_free ((void *)src[c].data); - } + { + GNUNET_free((void *)src[c].data); + } } int -main (int argcx, char *argvx[]) +main(int argcx, char *argvx[]) { static char *const argv[] = { "test_gnsrecord_serialization", - NULL - }; + NULL }; static struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; res = 1; - GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, argv, "test_namestore_record_serialization", - "nohelp", options, &run, &res); + GNUNET_PROGRAM_run((sizeof(argv) / sizeof(char *)) - 1, argv, "test_namestore_record_serialization", + "nohelp", options, &run, &res); return res; } diff --git a/src/hello/address.c b/src/hello/address.c index 9aaafeb53..3936a0133 100644 --- a/src/hello/address.c +++ b/src/hello/address.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hello/address.c @@ -36,8 +36,8 @@ * @return #GNUNET_YES or #GNUNET_NO */ int -GNUNET_HELLO_address_check_option (const struct GNUNET_HELLO_Address * address, - enum GNUNET_HELLO_AddressInfo option) +GNUNET_HELLO_address_check_option(const struct GNUNET_HELLO_Address * address, + enum GNUNET_HELLO_AddressInfo option) { if (option == (address->local_info & option)) return GNUNET_YES; @@ -52,10 +52,10 @@ GNUNET_HELLO_address_check_option (const struct GNUNET_HELLO_Address * address, * @return the size */ size_t -GNUNET_HELLO_address_get_size (const struct GNUNET_HELLO_Address * address) +GNUNET_HELLO_address_get_size(const struct GNUNET_HELLO_Address * address) { - return sizeof (struct GNUNET_HELLO_Address) + address->address_length + - strlen (address->transport_name) + 1; + return sizeof(struct GNUNET_HELLO_Address) + address->address_length + + strlen(address->transport_name) + 1; } @@ -70,31 +70,31 @@ GNUNET_HELLO_address_get_size (const struct GNUNET_HELLO_Address * address) * @return the address struct */ struct GNUNET_HELLO_Address * -GNUNET_HELLO_address_allocate (const struct GNUNET_PeerIdentity *peer, - const char *transport_name, - const void *address, - size_t address_length, - enum GNUNET_HELLO_AddressInfo local_info) +GNUNET_HELLO_address_allocate(const struct GNUNET_PeerIdentity *peer, + const char *transport_name, + const void *address, + size_t address_length, + enum GNUNET_HELLO_AddressInfo local_info) { struct GNUNET_HELLO_Address *addr; size_t slen; char *end; - slen = strlen (transport_name) + 1; - addr = GNUNET_malloc (sizeof (struct GNUNET_HELLO_Address) + - address_length + slen); + slen = strlen(transport_name) + 1; + addr = GNUNET_malloc(sizeof(struct GNUNET_HELLO_Address) + + address_length + slen); addr->peer = *peer; addr->address = &addr[1]; addr->address_length = address_length; addr->local_info = local_info; - end = (char *) &addr[1]; + end = (char *)&addr[1]; addr->transport_name = &end[address_length]; - GNUNET_memcpy (end, - address, - address_length); - GNUNET_memcpy (&end[address_length], - transport_name, - slen); + GNUNET_memcpy(end, + address, + address_length); + GNUNET_memcpy(&end[address_length], + transport_name, + slen); return addr; } @@ -106,15 +106,15 @@ GNUNET_HELLO_address_allocate (const struct GNUNET_PeerIdentity *peer, * @return a copy of the address struct */ struct GNUNET_HELLO_Address * -GNUNET_HELLO_address_copy (const struct GNUNET_HELLO_Address *address) +GNUNET_HELLO_address_copy(const struct GNUNET_HELLO_Address *address) { if (NULL == address) return NULL; - return GNUNET_HELLO_address_allocate (&address->peer, - address->transport_name, - address->address, - address->address_length, - address->local_info); + return GNUNET_HELLO_address_allocate(&address->peer, + address->transport_name, + address->address, + address->address_length, + address->local_info); } @@ -127,30 +127,30 @@ GNUNET_HELLO_address_copy (const struct GNUNET_HELLO_Address *address) * @return 0 if the addresses are equal, -1 if a1a2. */ int -GNUNET_HELLO_address_cmp (const struct GNUNET_HELLO_Address *a1, - const struct GNUNET_HELLO_Address *a2) +GNUNET_HELLO_address_cmp(const struct GNUNET_HELLO_Address *a1, + const struct GNUNET_HELLO_Address *a2) { int ret; - if ( (NULL == a1) && - (NULL == a2) ) + if ((NULL == a1) && + (NULL == a2)) return 0; if (NULL == a1) return 1; if (NULL == a2) return -1; - ret = strcmp (a1->transport_name, a2->transport_name); + ret = strcmp(a1->transport_name, a2->transport_name); if (0 != ret) return ret; if (a1->local_info != a2->local_info) - return (((int) a1->local_info) < ((int) a2->local_info)) ? -1 : 1; + return (((int)a1->local_info) < ((int)a2->local_info)) ? -1 : 1; if (a1->address_length < a2->address_length) return -1; if (a1->address_length > a2->address_length) return 1; - return memcmp (a1->address, - a2->address, - a1->address_length); + return memcmp(a1->address, + a2->address, + a1->address_length); } diff --git a/src/hello/gnunet-hello.c b/src/hello/gnunet-hello.c index 612b5110a..1b572b904 100644 --- a/src/hello/gnunet-hello.c +++ b/src/hello/gnunet-hello.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hello/gnunet-hello.c * @brief change HELLO files to never expire @@ -29,8 +29,7 @@ /** * Closure for #add_to_buf(). */ -struct AddContext -{ +struct AddContext { /** * Where to add. */ @@ -59,17 +58,17 @@ static int address_count; * @return #GNUNET_OK keep iterating */ static int -add_to_buf (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +add_to_buf(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { struct AddContext *ac = cls; size_t ret; - ret = GNUNET_HELLO_add_address (address, - GNUNET_TIME_UNIT_FOREVER_ABS, - ac->buf, - ac->max); + ret = GNUNET_HELLO_add_address(address, + GNUNET_TIME_UNIT_FOREVER_ABS, + ac->buf, + ac->max); ac->buf += ret; ac->max -= ret; ac->ret += ret; @@ -87,7 +86,7 @@ add_to_buf (void *cls, * @return number of bytes added, 0 to terminate */ static ssize_t -add_from_hello (void *cls, size_t max, void *buf) +add_from_hello(void *cls, size_t max, void *buf) { struct GNUNET_HELLO_Message **orig = cls; struct AddContext ac; @@ -97,116 +96,117 @@ add_from_hello (void *cls, size_t max, void *buf) ac.buf = buf; ac.max = max; ac.ret = 0; - GNUNET_assert ( + GNUNET_assert( NULL == - GNUNET_HELLO_iterate_addresses (*orig, GNUNET_NO, &add_to_buf, &ac)); + GNUNET_HELLO_iterate_addresses(*orig, GNUNET_NO, &add_to_buf, &ac)); *orig = NULL; return ac.ret; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { struct GNUNET_DISK_FileHandle *fh; struct GNUNET_HELLO_Message *orig; struct GNUNET_HELLO_Message *result; struct GNUNET_PeerIdentity pid; uint64_t fsize; + address_count = 0; - GNUNET_log_setup ("gnunet-hello", "INFO", NULL); + GNUNET_log_setup("gnunet-hello", "INFO", NULL); if (argc != 2) - { - fprintf (stderr, "%s", _ ("Call with name of HELLO file to modify.\n")); - return 1; - } + { + fprintf(stderr, "%s", _("Call with name of HELLO file to modify.\n")); + return 1; + } if (GNUNET_OK != - GNUNET_DISK_file_size (argv[1], &fsize, GNUNET_YES, GNUNET_YES)) - { - fprintf (stderr, - _ ("Error accessing file `%s': %s\n"), - argv[1], - strerror (errno)); - return 1; - } - if (fsize > 65536) - { - fprintf (stderr, _ ("File `%s' is too big to be a HELLO\n"), argv[1]); - return 1; - } - if (fsize < sizeof (struct GNUNET_MessageHeader)) - { - fprintf (stderr, _ ("File `%s' is too small to be a HELLO\n"), argv[1]); - return 1; - } - fh = GNUNET_DISK_file_open (argv[1], - GNUNET_DISK_OPEN_READ, - GNUNET_DISK_PERM_USER_READ); - if (NULL == fh) - { - fprintf (stderr, - _ ("Error opening file `%s': %s\n"), - argv[1], - strerror (errno)); - return 1; - } - { - char buf[fsize] GNUNET_ALIGN; - - GNUNET_assert (fsize == GNUNET_DISK_file_read (fh, buf, fsize)); - GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh)); - orig = (struct GNUNET_HELLO_Message *) buf; - if ((fsize < GNUNET_HELLO_size (orig)) || - (GNUNET_OK != GNUNET_HELLO_get_id (orig, &pid))) + GNUNET_DISK_file_size(argv[1], &fsize, GNUNET_YES, GNUNET_YES)) { - fprintf (stderr, - _ ("Did not find well-formed HELLO in file `%s'\n"), - argv[1]); + fprintf(stderr, + _("Error accessing file `%s': %s\n"), + argv[1], + strerror(errno)); return 1; } + if (fsize > 65536) { - char *pids; - - pids = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid.public_key); - fprintf (stdout, "Processing HELLO for peer `%s'\n", pids); - GNUNET_free (pids); + fprintf(stderr, _("File `%s' is too big to be a HELLO\n"), argv[1]); + return 1; } - result = GNUNET_HELLO_create (&pid.public_key, - &add_from_hello, - &orig, - GNUNET_HELLO_is_friend_only (orig)); - GNUNET_assert (NULL != result); - fh = - GNUNET_DISK_file_open (argv[1], - GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE); - if (NULL == fh) + if (fsize < sizeof(struct GNUNET_MessageHeader)) { - fprintf (stderr, - _ ("Error opening file `%s': %s\n"), - argv[1], - strerror (errno)); - GNUNET_free (result); + fprintf(stderr, _("File `%s' is too small to be a HELLO\n"), argv[1]); return 1; } - fsize = GNUNET_HELLO_size (result); - if (fsize != GNUNET_DISK_file_write (fh, result, fsize)) + fh = GNUNET_DISK_file_open(argv[1], + GNUNET_DISK_OPEN_READ, + GNUNET_DISK_PERM_USER_READ); + if (NULL == fh) { - fprintf (stderr, - _ ("Error writing HELLO to file `%s': %s\n"), - argv[1], - strerror (errno)); - (void) GNUNET_DISK_file_close (fh); + fprintf(stderr, + _("Error opening file `%s': %s\n"), + argv[1], + strerror(errno)); return 1; } - GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh)); + { + char buf[fsize] GNUNET_ALIGN; + + GNUNET_assert(fsize == GNUNET_DISK_file_read(fh, buf, fsize)); + GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fh)); + orig = (struct GNUNET_HELLO_Message *)buf; + if ((fsize < GNUNET_HELLO_size(orig)) || + (GNUNET_OK != GNUNET_HELLO_get_id(orig, &pid))) + { + fprintf(stderr, + _("Did not find well-formed HELLO in file `%s'\n"), + argv[1]); + return 1; + } + { + char *pids; + + pids = GNUNET_CRYPTO_eddsa_public_key_to_string(&pid.public_key); + fprintf(stdout, "Processing HELLO for peer `%s'\n", pids); + GNUNET_free(pids); + } + result = GNUNET_HELLO_create(&pid.public_key, + &add_from_hello, + &orig, + GNUNET_HELLO_is_friend_only(orig)); + GNUNET_assert(NULL != result); + fh = + GNUNET_DISK_file_open(argv[1], + GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE); + if (NULL == fh) + { + fprintf(stderr, + _("Error opening file `%s': %s\n"), + argv[1], + strerror(errno)); + GNUNET_free(result); + return 1; + } + fsize = GNUNET_HELLO_size(result); + if (fsize != GNUNET_DISK_file_write(fh, result, fsize)) + { + fprintf(stderr, + _("Error writing HELLO to file `%s': %s\n"), + argv[1], + strerror(errno)); + (void)GNUNET_DISK_file_close(fh); + return 1; + } + GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fh)); } - fprintf (stderr, - _ ("Modified %u addresses, wrote %u bytes\n"), - address_count, - (unsigned int) fsize); + fprintf(stderr, + _("Modified %u addresses, wrote %u bytes\n"), + address_count, + (unsigned int)fsize); return 0; } diff --git a/src/hello/hello-ng.c b/src/hello/hello-ng.c index 29ab17f9b..f44fff032 100644 --- a/src/hello/hello-ng.c +++ b/src/hello/hello-ng.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hello/hello-ng.c @@ -33,8 +33,7 @@ /** * Binary block we sign when we sign an address. */ -struct SignedAddress -{ +struct SignedAddress { /** * Purpose must be #GNUNET_SIGNATURE_PURPOSE_TRANSPORT_ADDRESS */ @@ -63,7 +62,7 @@ struct SignedAddress * @param result_size[out] set to size of @a result */ void -GNUNET_HELLO_sign_address ( +GNUNET_HELLO_sign_address( const char *address, enum GNUNET_NetworkType nt, struct GNUNET_TIME_Absolute mono_time, @@ -75,22 +74,22 @@ GNUNET_HELLO_sign_address ( struct GNUNET_CRYPTO_EddsaSignature sig; char *sig_str; - sa.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_ADDRESS); - sa.purpose.size = htonl (sizeof (sa)); - sa.mono_time = GNUNET_TIME_absolute_hton (mono_time); - GNUNET_CRYPTO_hash (address, strlen (address), &sa.h_addr); - GNUNET_assert (GNUNET_YES == - GNUNET_CRYPTO_eddsa_sign (private_key, &sa.purpose, &sig)); + sa.purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_TRANSPORT_ADDRESS); + sa.purpose.size = htonl(sizeof(sa)); + sa.mono_time = GNUNET_TIME_absolute_hton(mono_time); + GNUNET_CRYPTO_hash(address, strlen(address), &sa.h_addr); + GNUNET_assert(GNUNET_YES == + GNUNET_CRYPTO_eddsa_sign(private_key, &sa.purpose, &sig)); sig_str = NULL; - (void) GNUNET_STRINGS_base64_encode (&sig, sizeof (sig), &sig_str); + (void)GNUNET_STRINGS_base64_encode(&sig, sizeof(sig), &sig_str); *result_size = - 1 + GNUNET_asprintf ((char **) result, - "%s;%llu;%u;%s", - sig_str, - (unsigned long long) mono_time.abs_value_us, - (unsigned int) nt, - address); - GNUNET_free (sig_str); + 1 + GNUNET_asprintf((char **)result, + "%s;%llu;%u;%s", + sig_str, + (unsigned long long)mono_time.abs_value_us, + (unsigned int)nt, + address); + GNUNET_free(sig_str); } @@ -105,11 +104,11 @@ GNUNET_HELLO_sign_address ( * @return NULL on error, otherwise the address */ char * -GNUNET_HELLO_extract_address (const void *raw, - size_t raw_size, - const struct GNUNET_PeerIdentity *pid, - enum GNUNET_NetworkType *nt, - struct GNUNET_TIME_Absolute *mono_time) +GNUNET_HELLO_extract_address(const void *raw, + size_t raw_size, + const struct GNUNET_PeerIdentity *pid, + enum GNUNET_NetworkType *nt, + struct GNUNET_TIME_Absolute *mono_time) { const struct GNUNET_CRYPTO_EddsaPublicKey *public_key = &pid->public_key; const char *raws = raw; @@ -124,59 +123,59 @@ GNUNET_HELLO_extract_address (const void *raw, struct GNUNET_CRYPTO_EddsaSignature *sig; if ('\0' != raws[raw_size]) - { - GNUNET_break_op (0); - return NULL; - } - if (NULL == (sc = strchr (raws, ';'))) - { - GNUNET_break_op (0); - return NULL; - } - if (NULL == (sc2 = strchr (sc + 1, ';'))) - { - GNUNET_break_op (0); - return NULL; - } - if (NULL == (sc3 = strchr (sc2 + 1, ';'))) - { - GNUNET_break_op (0); - return NULL; - } - if (1 != sscanf (sc + 1, "%llu;%u;", &raw_us, &raw_nt)) - { - GNUNET_break_op (0); - return NULL; - } + { + GNUNET_break_op(0); + return NULL; + } + if (NULL == (sc = strchr(raws, ';'))) + { + GNUNET_break_op(0); + return NULL; + } + if (NULL == (sc2 = strchr(sc + 1, ';'))) + { + GNUNET_break_op(0); + return NULL; + } + if (NULL == (sc3 = strchr(sc2 + 1, ';'))) + { + GNUNET_break_op(0); + return NULL; + } + if (1 != sscanf(sc + 1, "%llu;%u;", &raw_us, &raw_nt)) + { + GNUNET_break_op(0); + return NULL; + } raw_mono_time.abs_value_us = raw_us; sig = NULL; - if (sizeof (struct GNUNET_CRYPTO_EddsaSignature) != - GNUNET_STRINGS_base64_decode (raws, sc - raws, (void **) &sig)) - { - GNUNET_break_op (0); - GNUNET_free_non_null (sig); - return NULL; - } + if (sizeof(struct GNUNET_CRYPTO_EddsaSignature) != + GNUNET_STRINGS_base64_decode(raws, sc - raws, (void **)&sig)) + { + GNUNET_break_op(0); + GNUNET_free_non_null(sig); + return NULL; + } raw_addr = sc3 + 1; - sa.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_ADDRESS); - sa.purpose.size = htonl (sizeof (sa)); - sa.mono_time = GNUNET_TIME_absolute_hton (raw_mono_time); - GNUNET_CRYPTO_hash (raw_addr, strlen (raw_addr), &sa.h_addr); + sa.purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_TRANSPORT_ADDRESS); + sa.purpose.size = htonl(sizeof(sa)); + sa.mono_time = GNUNET_TIME_absolute_hton(raw_mono_time); + GNUNET_CRYPTO_hash(raw_addr, strlen(raw_addr), &sa.h_addr); if (GNUNET_YES != - GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_ADDRESS, - &sa.purpose, - sig, - public_key)) - { - GNUNET_break_op (0); - GNUNET_free (sig); - return NULL; - } - GNUNET_free (sig); + GNUNET_CRYPTO_eddsa_verify(GNUNET_SIGNATURE_PURPOSE_TRANSPORT_ADDRESS, + &sa.purpose, + sig, + public_key)) + { + GNUNET_break_op(0); + GNUNET_free(sig); + return NULL; + } + GNUNET_free(sig); *mono_time = raw_mono_time; - *nt = (enum GNUNET_NetworkType) raw_nt; - return GNUNET_strdup (raw_addr); + *nt = (enum GNUNET_NetworkType)raw_nt; + return GNUNET_strdup(raw_addr); } @@ -188,12 +187,12 @@ GNUNET_HELLO_extract_address (const void *raw, * @return NULL if the address is mal-formed, otherwise the prefix */ char * -GNUNET_HELLO_address_to_prefix (const char *address) +GNUNET_HELLO_address_to_prefix(const char *address) { const char *dash; - dash = strchr (address, '-'); + dash = strchr(address, '-'); if (NULL == dash) return NULL; - return GNUNET_strndup (address, dash - address); + return GNUNET_strndup(address, dash - address); } diff --git a/src/hello/hello.c b/src/hello/hello.c index f803f4370..021451a08 100644 --- a/src/hello/hello.c +++ b/src/hello/hello.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hello/hello.c @@ -33,8 +33,7 @@ /** * Context used for building our own URI. */ -struct GNUNET_HELLO_ComposeUriContext -{ +struct GNUNET_HELLO_ComposeUriContext { /** * Final URI. */ @@ -50,8 +49,7 @@ struct GNUNET_HELLO_ComposeUriContext /** * Context for #add_address_to_hello(). */ -struct GNUNET_HELLO_ParseUriContext -{ +struct GNUNET_HELLO_ParseUriContext { /** * Position in the URI with the next address to parse. */ @@ -86,7 +84,7 @@ struct GNUNET_HELLO_ParseUriContext * @return #GNUNET_YES for friend-only or #GNUNET_NO otherwise */ int -GNUNET_HELLO_is_friend_only (const struct GNUNET_HELLO_Message *h) +GNUNET_HELLO_is_friend_only(const struct GNUNET_HELLO_Message *h) { if (GNUNET_YES == ntohl(h->friend_only)) return GNUNET_YES; @@ -106,27 +104,27 @@ GNUNET_HELLO_is_friend_only (const struct GNUNET_HELLO_Message *h) * the target buffer was not big enough. */ size_t -GNUNET_HELLO_add_address (const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration, - char *target, - size_t max) +GNUNET_HELLO_add_address(const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration, + char *target, + size_t max) { uint16_t alen; size_t slen; struct GNUNET_TIME_AbsoluteNBO exp; - slen = strlen (address->transport_name) + 1; - if (slen + sizeof (uint16_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO) + + slen = strlen(address->transport_name) + 1; + if (slen + sizeof(uint16_t) + sizeof(struct GNUNET_TIME_AbsoluteNBO) + address->address_length > max) return 0; - exp = GNUNET_TIME_absolute_hton (expiration); - alen = htons ((uint16_t) address->address_length); - GNUNET_memcpy (target, address->transport_name, slen); - GNUNET_memcpy (&target[slen], &alen, sizeof (uint16_t)); - slen += sizeof (uint16_t); - GNUNET_memcpy (&target[slen], &exp, sizeof (struct GNUNET_TIME_AbsoluteNBO)); - slen += sizeof (struct GNUNET_TIME_AbsoluteNBO); - GNUNET_memcpy (&target[slen], address->address, address->address_length); + exp = GNUNET_TIME_absolute_hton(expiration); + alen = htons((uint16_t)address->address_length); + GNUNET_memcpy(target, address->transport_name, slen); + GNUNET_memcpy(&target[slen], &alen, sizeof(uint16_t)); + slen += sizeof(uint16_t); + GNUNET_memcpy(&target[slen], &exp, sizeof(struct GNUNET_TIME_AbsoluteNBO)); + slen += sizeof(struct GNUNET_TIME_AbsoluteNBO); + GNUNET_memcpy(&target[slen], address->address, address->address_length); slen += address->address_length; return slen; } @@ -141,9 +139,9 @@ GNUNET_HELLO_add_address (const struct GNUNET_HELLO_Address *address, * @return size of the entry, or 0 if @a max is not large enough */ static size_t -get_hello_address_size (const char *buf, - size_t max, - uint16_t *ralen) +get_hello_address_size(const char *buf, + size_t max, + uint16_t *ralen) { const char *pos; uint16_t alen; @@ -154,34 +152,34 @@ get_hello_address_size (const char *buf, pos = buf; slen = 1; while ((left > 0) && ('\0' != *pos)) - { - left--; - pos++; - slen++; - } + { + left--; + pos++; + slen++; + } if (0 == left) - { - /* 0-termination not found */ - GNUNET_break_op (0); - return 0; - } + { + /* 0-termination not found */ + GNUNET_break_op(0); + return 0; + } pos++; - if (left < sizeof (uint16_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO)) - { - /* not enough space for addrlen */ - GNUNET_break_op (0); - return 0; - } - GNUNET_memcpy (&alen, pos, sizeof (uint16_t)); - alen = ntohs (alen); + if (left < sizeof(uint16_t) + sizeof(struct GNUNET_TIME_AbsoluteNBO)) + { + /* not enough space for addrlen */ + GNUNET_break_op(0); + return 0; + } + GNUNET_memcpy(&alen, pos, sizeof(uint16_t)); + alen = ntohs(alen); *ralen = alen; - slen += alen + sizeof (uint16_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO); + slen += alen + sizeof(uint16_t) + sizeof(struct GNUNET_TIME_AbsoluteNBO); if (max < slen) - { - /* not enough space for addr */ - GNUNET_break_op (0); - return 0; - } + { + /* not enough space for addr */ + GNUNET_break_op(0); + return 0; + } return slen; } @@ -201,41 +199,41 @@ get_hello_address_size (const char *buf, * @return the hello message */ struct GNUNET_HELLO_Message * -GNUNET_HELLO_create (const struct GNUNET_CRYPTO_EddsaPublicKey *public_key, - GNUNET_HELLO_GenerateAddressListCallback addrgen, - void *addrgen_cls, - int friend_only) +GNUNET_HELLO_create(const struct GNUNET_CRYPTO_EddsaPublicKey *public_key, + GNUNET_HELLO_GenerateAddressListCallback addrgen, + void *addrgen_cls, + int friend_only) { char buffer[GNUNET_MAX_MESSAGE_SIZE - 1 - 256 - - sizeof (struct GNUNET_HELLO_Message)]; + sizeof(struct GNUNET_HELLO_Message)]; size_t max; size_t used; size_t ret; struct GNUNET_HELLO_Message *hello; - GNUNET_assert (NULL != public_key); - GNUNET_assert ( (GNUNET_YES == friend_only) || - (GNUNET_NO == friend_only) ); - max = sizeof (buffer); + GNUNET_assert(NULL != public_key); + GNUNET_assert((GNUNET_YES == friend_only) || + (GNUNET_NO == friend_only)); + max = sizeof(buffer); used = 0; if (NULL != addrgen) - { - while (GNUNET_SYSERR != (ret = addrgen (addrgen_cls, - max, - &buffer[used]))) { - max -= ret; - used += ret; + while (GNUNET_SYSERR != (ret = addrgen(addrgen_cls, + max, + &buffer[used]))) + { + max -= ret; + used += ret; + } } - } - hello = GNUNET_malloc (sizeof (struct GNUNET_HELLO_Message) + used); - hello->header.type = htons (GNUNET_MESSAGE_TYPE_HELLO); - hello->header.size = htons (sizeof (struct GNUNET_HELLO_Message) + used); - hello->friend_only = htonl (friend_only); + hello = GNUNET_malloc(sizeof(struct GNUNET_HELLO_Message) + used); + hello->header.type = htons(GNUNET_MESSAGE_TYPE_HELLO); + hello->header.size = htons(sizeof(struct GNUNET_HELLO_Message) + used); + hello->friend_only = htonl(friend_only); hello->publicKey = *public_key; - GNUNET_memcpy (&hello[1], - buffer, - used); + GNUNET_memcpy(&hello[1], + buffer, + used); return hello; } @@ -251,10 +249,10 @@ GNUNET_HELLO_create (const struct GNUNET_CRYPTO_EddsaPublicKey *public_key, * @return modified HELLO message */ struct GNUNET_HELLO_Message * -GNUNET_HELLO_iterate_addresses (const struct GNUNET_HELLO_Message *msg, - int return_modified, - GNUNET_HELLO_AddressIterator it, - void *it_cls) +GNUNET_HELLO_iterate_addresses(const struct GNUNET_HELLO_Message *msg, + int return_modified, + GNUNET_HELLO_AddressIterator it, + void *it_cls) { struct GNUNET_HELLO_Address address; uint16_t msize; @@ -268,69 +266,69 @@ GNUNET_HELLO_iterate_addresses (const struct GNUNET_HELLO_Message *msg, struct GNUNET_TIME_AbsoluteNBO expire; int iret; - msize = GNUNET_HELLO_size (msg); - if ((msize < sizeof (struct GNUNET_HELLO_Message)) || - (ntohs (msg->header.type) != GNUNET_MESSAGE_TYPE_HELLO)) - { - GNUNET_break_op (0); - return NULL; - } + msize = GNUNET_HELLO_size(msg); + if ((msize < sizeof(struct GNUNET_HELLO_Message)) || + (ntohs(msg->header.type) != GNUNET_MESSAGE_TYPE_HELLO)) + { + GNUNET_break_op(0); + return NULL; + } ret = NULL; if (return_modified) - { - ret = GNUNET_malloc (msize); - GNUNET_memcpy (ret, - msg, - msize); - } - inptr = (const char *) &msg[1]; - insize = msize - sizeof (struct GNUNET_HELLO_Message); + { + ret = GNUNET_malloc(msize); + GNUNET_memcpy(ret, + msg, + msize); + } + inptr = (const char *)&msg[1]; + insize = msize - sizeof(struct GNUNET_HELLO_Message); wpos = 0; - woff = (NULL != ret) ? (char *) &ret[1] : NULL; + woff = (NULL != ret) ? (char *)&ret[1] : NULL; address.peer.public_key = msg->publicKey; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "HELLO has %u bytes of address data\n", - (unsigned int) insize); - + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "HELLO has %u bytes of address data\n", + (unsigned int)insize); + while (insize > 0) - { - esize = get_hello_address_size (inptr, - insize, - &alen); - if (0 == esize) { - GNUNET_break (0); - GNUNET_free_non_null (ret); - return NULL; + esize = get_hello_address_size(inptr, + insize, + &alen); + if (0 == esize) + { + GNUNET_break(0); + GNUNET_free_non_null(ret); + return NULL; + } + /* need GNUNET_memcpy() due to possibility of misalignment */ + GNUNET_memcpy(&expire, + &inptr[esize - alen - sizeof(struct GNUNET_TIME_AbsoluteNBO)], + sizeof(struct GNUNET_TIME_AbsoluteNBO)); + address.address = &inptr[esize - alen]; + address.address_length = alen; + address.transport_name = inptr; + address.local_info = GNUNET_HELLO_ADDRESS_INFO_NONE; + iret = it(it_cls, + &address, + GNUNET_TIME_absolute_ntoh(expire)); + if (GNUNET_SYSERR == iret) + break; + if ((GNUNET_OK == iret) && + (NULL != ret)) + { + /* copy address over */ + GNUNET_memcpy(woff, + inptr, + esize); + woff += esize; + wpos += esize; + } + insize -= esize; + inptr += esize; } - /* need GNUNET_memcpy() due to possibility of misalignment */ - GNUNET_memcpy (&expire, - &inptr[esize - alen - sizeof (struct GNUNET_TIME_AbsoluteNBO)], - sizeof (struct GNUNET_TIME_AbsoluteNBO)); - address.address = &inptr[esize - alen]; - address.address_length = alen; - address.transport_name = inptr; - address.local_info = GNUNET_HELLO_ADDRESS_INFO_NONE; - iret = it (it_cls, - &address, - GNUNET_TIME_absolute_ntoh (expire)); - if (GNUNET_SYSERR == iret) - break; - if ( (GNUNET_OK == iret) && - (NULL != ret) ) - { - /* copy address over */ - GNUNET_memcpy (woff, - inptr, - esize); - woff += esize; - wpos += esize; - } - insize -= esize; - inptr += esize; - } if (NULL != ret) - ret->header.size = ntohs (sizeof (struct GNUNET_HELLO_Message) + wpos); + ret->header.size = ntohs(sizeof(struct GNUNET_HELLO_Message) + wpos); return ret; } @@ -338,8 +336,7 @@ GNUNET_HELLO_iterate_addresses (const struct GNUNET_HELLO_Message *msg, /** * Closure for #get_match_exp(). */ -struct ExpireContext -{ +struct ExpireContext { /** * Address we are looking for. */ @@ -366,14 +363,14 @@ struct ExpireContext * @return #GNUNET_SYSERR if we found a matching address, #GNUNET_OK otherwise */ static int -get_match_exp (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +get_match_exp(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { struct ExpireContext *ec = cls; - if (0 != GNUNET_HELLO_address_cmp (address, - ec->address)) + if (0 != GNUNET_HELLO_address_cmp(address, + ec->address)) return GNUNET_OK; ec->found = GNUNET_YES; ec->expiration = expiration; @@ -384,8 +381,7 @@ get_match_exp (void *cls, /** * Context for a #GNUNET_HELLO_Merge operation. */ -struct MergeContext -{ +struct MergeContext { /** * First HELLO we are merging. */ @@ -424,7 +420,6 @@ struct MergeContext * copy addresses with strictly later expiration times? */ int take_equal; - }; @@ -439,9 +434,9 @@ struct MergeContext * @return always #GNUNET_OK */ static int -copy_latest (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +copy_latest(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { struct MergeContext *mc = cls; struct ExpireContext ec; @@ -449,22 +444,22 @@ copy_latest (void *cls, ec.address = address; ec.found = GNUNET_NO; /* check if address exists in other */ - GNUNET_HELLO_iterate_addresses (mc->other, - GNUNET_NO, - &get_match_exp, - &ec); - if ( (GNUNET_NO == ec.found) || - (ec.expiration.abs_value_us < expiration.abs_value_us) || - ( (ec.expiration.abs_value_us == expiration.abs_value_us) && - (GNUNET_YES == mc->take_equal) ) ) - { - /* copy address to buffer */ - mc->ret += - GNUNET_HELLO_add_address (address, - expiration, - &mc->buf[mc->ret], - mc->max - mc->ret); - } + GNUNET_HELLO_iterate_addresses(mc->other, + GNUNET_NO, + &get_match_exp, + &ec); + if ((GNUNET_NO == ec.found) || + (ec.expiration.abs_value_us < expiration.abs_value_us) || + ((ec.expiration.abs_value_us == expiration.abs_value_us) && + (GNUNET_YES == mc->take_equal))) + { + /* copy address to buffer */ + mc->ret += + GNUNET_HELLO_add_address(address, + expiration, + &mc->buf[mc->ret], + mc->max - mc->ret); + } return GNUNET_OK; } @@ -480,9 +475,9 @@ copy_latest (void *cls, * @return #GNUNET_SYSERR to end iteration, otherwise number of bytes written to @a buf */ static ssize_t -merge_addr (void *cls, - size_t max, - void *buf) +merge_addr(void *cls, + size_t max, + void *buf) { struct MergeContext *mc = cls; @@ -494,17 +489,17 @@ merge_addr (void *cls, mc->take_equal = GNUNET_NO; mc->other = mc->h2; /* copy addresses from h1, if strictly larger expiration than h2 */ - GNUNET_HELLO_iterate_addresses (mc->h1, - GNUNET_NO, - ©_latest, - mc); + GNUNET_HELLO_iterate_addresses(mc->h1, + GNUNET_NO, + ©_latest, + mc); mc->take_equal = GNUNET_YES; mc->other = mc->h1; /* copy addresses from h2, if larger or equal expiration than h1 */ - GNUNET_HELLO_iterate_addresses (mc->h2, - GNUNET_NO, - ©_latest, - mc); + GNUNET_HELLO_iterate_addresses(mc->h2, + GNUNET_NO, + ©_latest, + mc); /* set marker to stop iteration */ mc->h1 = NULL; return mc->ret; @@ -521,8 +516,8 @@ merge_addr (void *cls, * @return the combined HELLO message */ struct GNUNET_HELLO_Message * -GNUNET_HELLO_merge (const struct GNUNET_HELLO_Message *h1, - const struct GNUNET_HELLO_Message *h2) +GNUNET_HELLO_merge(const struct GNUNET_HELLO_Message *h1, + const struct GNUNET_HELLO_Message *h2) { struct MergeContext mc = { h1, h2, NULL, NULL, 0, 0, 0 }; int friend_only; @@ -530,12 +525,12 @@ GNUNET_HELLO_merge (const struct GNUNET_HELLO_Message *h1, if (h1->friend_only != h2->friend_only) friend_only = GNUNET_YES; /* One of the HELLOs is friend only */ else - friend_only = ntohl (h1->friend_only); /* Both HELLO's have the same type */ + friend_only = ntohl(h1->friend_only); /* Both HELLO's have the same type */ - return GNUNET_HELLO_create (&h1->publicKey, - &merge_addr, - &mc, - friend_only); + return GNUNET_HELLO_create(&h1->publicKey, + &merge_addr, + &mc, + friend_only); } @@ -543,8 +538,7 @@ GNUNET_HELLO_merge (const struct GNUNET_HELLO_Message *h1, * Context used in #GNUNET_HELLO_iterate_new_addresses() to * figure out which addresses are in fact 'new'. */ -struct DeltaContext -{ +struct DeltaContext { /** * We should ignore addresses that expire before this time. */ @@ -581,9 +575,9 @@ struct DeltaContext * whatever the iterator returned. */ static int -delta_match (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +delta_match(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { struct DeltaContext *dc = cls; int ret; @@ -591,17 +585,17 @@ delta_match (void *cls, ec.address = address; ec.found = GNUNET_NO; - GNUNET_HELLO_iterate_addresses (dc->old_hello, - GNUNET_NO, - &get_match_exp, - &ec); - if ( (GNUNET_YES == ec.found) && - ( (ec.expiration.abs_value_us > expiration.abs_value_us) || - (ec.expiration.abs_value_us >= dc->expiration_limit.abs_value_us))) + GNUNET_HELLO_iterate_addresses(dc->old_hello, + GNUNET_NO, + &get_match_exp, + &ec); + if ((GNUNET_YES == ec.found) && + ((ec.expiration.abs_value_us > expiration.abs_value_us) || + (ec.expiration.abs_value_us >= dc->expiration_limit.abs_value_us))) return GNUNET_YES; /* skip: found and boring */ - ret = dc->it (dc->it_cls, - address, - expiration); + ret = dc->it(dc->it_cls, + address, + expiration); return ret; } @@ -620,11 +614,11 @@ delta_match (void *cls, * @param it_cls closure for @a it */ void -GNUNET_HELLO_iterate_new_addresses (const struct GNUNET_HELLO_Message *new_hello, - const struct GNUNET_HELLO_Message *old_hello, - struct GNUNET_TIME_Absolute expiration_limit, - GNUNET_HELLO_AddressIterator it, - void *it_cls) +GNUNET_HELLO_iterate_new_addresses(const struct GNUNET_HELLO_Message *new_hello, + const struct GNUNET_HELLO_Message *old_hello, + struct GNUNET_TIME_Absolute expiration_limit, + GNUNET_HELLO_AddressIterator it, + void *it_cls) { struct DeltaContext dc; @@ -632,11 +626,11 @@ GNUNET_HELLO_iterate_new_addresses (const struct GNUNET_HELLO_Message *new_hello dc.it = it; dc.it_cls = it_cls; dc.old_hello = old_hello; - GNUNET_assert (NULL == - GNUNET_HELLO_iterate_addresses (new_hello, - GNUNET_NO, - &delta_match, - &dc)); + GNUNET_assert(NULL == + GNUNET_HELLO_iterate_addresses(new_hello, + GNUNET_NO, + &delta_match, + &dc)); } @@ -646,12 +640,12 @@ GNUNET_HELLO_iterate_new_addresses (const struct GNUNET_HELLO_Message *new_hello * @return the size, 0 if HELLO is invalid */ uint16_t -GNUNET_HELLO_size (const struct GNUNET_HELLO_Message *hello) +GNUNET_HELLO_size(const struct GNUNET_HELLO_Message *hello) { - uint16_t ret = ntohs (hello->header.size); + uint16_t ret = ntohs(hello->header.size); - if ((ret < sizeof (struct GNUNET_HELLO_Message)) || - (ntohs (hello->header.type) != GNUNET_MESSAGE_TYPE_HELLO)) + if ((ret < sizeof(struct GNUNET_HELLO_Message)) || + (ntohs(hello->header.type) != GNUNET_MESSAGE_TYPE_HELLO)) return 0; return ret; } @@ -665,13 +659,13 @@ GNUNET_HELLO_size (const struct GNUNET_HELLO_Message *hello) * @return #GNUNET_SYSERR if the HELLO was malformed */ int -GNUNET_HELLO_get_id (const struct GNUNET_HELLO_Message *hello, - struct GNUNET_PeerIdentity *peer) +GNUNET_HELLO_get_id(const struct GNUNET_HELLO_Message *hello, + struct GNUNET_PeerIdentity *peer) { - uint16_t ret = ntohs (hello->header.size); + uint16_t ret = ntohs(hello->header.size); - if ((ret < sizeof (struct GNUNET_HELLO_Message)) || - (ntohs (hello->header.type) != GNUNET_MESSAGE_TYPE_HELLO)) + if ((ret < sizeof(struct GNUNET_HELLO_Message)) || + (ntohs(hello->header.type) != GNUNET_MESSAGE_TYPE_HELLO)) return GNUNET_SYSERR; peer->public_key = hello->publicKey; return GNUNET_OK; @@ -687,12 +681,12 @@ GNUNET_HELLO_get_id (const struct GNUNET_HELLO_Message *hello, * @return header or NULL if the HELLO was malformed */ struct GNUNET_MessageHeader * -GNUNET_HELLO_get_header (struct GNUNET_HELLO_Message *hello) +GNUNET_HELLO_get_header(struct GNUNET_HELLO_Message *hello) { - uint16_t ret = ntohs (hello->header.size); + uint16_t ret = ntohs(hello->header.size); - if ((ret < sizeof (struct GNUNET_HELLO_Message)) || - (ntohs (hello->header.type) != GNUNET_MESSAGE_TYPE_HELLO)) + if ((ret < sizeof(struct GNUNET_HELLO_Message)) || + (ntohs(hello->header.type) != GNUNET_MESSAGE_TYPE_HELLO)) return NULL; return &hello->header; @@ -702,8 +696,7 @@ GNUNET_HELLO_get_header (struct GNUNET_HELLO_Message *hello) /** * Context used for comparing HELLOs in #GNUNET_HELLO_equals(). */ -struct EqualsContext -{ +struct EqualsContext { /** * Addresses that expired before this date are ignored for * the comparisson. @@ -737,7 +730,6 @@ struct EqualsContext * Did we find the address we were looking for? */ int found; - }; @@ -754,22 +746,22 @@ struct EqualsContext * #GNUNET_SYSERR if the address does match. */ static int -find_other_matching (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +find_other_matching(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { struct EqualsContext *ec = cls; if (expiration.abs_value_us < ec->expiration_limit.abs_value_us) return GNUNET_YES; - if (0 == GNUNET_HELLO_address_cmp (address, ec->address)) - { - ec->found = GNUNET_YES; - if (expiration.abs_value_us < ec->expiration.abs_value_us) - ec->result = GNUNET_TIME_absolute_min (expiration, - ec->result); - return GNUNET_SYSERR; - } + if (0 == GNUNET_HELLO_address_cmp(address, ec->address)) + { + ec->found = GNUNET_YES; + if (expiration.abs_value_us < ec->expiration.abs_value_us) + ec->result = GNUNET_TIME_absolute_min(expiration, + ec->result); + return GNUNET_SYSERR; + } return GNUNET_YES; } @@ -787,9 +779,9 @@ find_other_matching (void *cls, * #GNUNET_SYSERR if it was not found */ static int -find_matching (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +find_matching(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { struct EqualsContext *ec = cls; @@ -798,16 +790,16 @@ find_matching (void *cls, ec->address = address; ec->expiration = expiration; ec->found = GNUNET_NO; - GNUNET_HELLO_iterate_addresses (ec->ref, - GNUNET_NO, - &find_other_matching, - ec); + GNUNET_HELLO_iterate_addresses(ec->ref, + GNUNET_NO, + &find_other_matching, + ec); if (GNUNET_NO == ec->found) - { - /* not found, we differ *now* */ - ec->result = GNUNET_TIME_UNIT_ZERO_ABS; - return GNUNET_SYSERR; - } + { + /* not found, we differ *now* */ + ec->result = GNUNET_TIME_UNIT_ZERO_ABS; + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -829,32 +821,32 @@ find_matching (void *cls, * do not match at all */ struct GNUNET_TIME_Absolute -GNUNET_HELLO_equals (const struct GNUNET_HELLO_Message *h1, - const struct GNUNET_HELLO_Message *h2, - struct GNUNET_TIME_Absolute now) +GNUNET_HELLO_equals(const struct GNUNET_HELLO_Message *h1, + const struct GNUNET_HELLO_Message *h2, + struct GNUNET_TIME_Absolute now) { struct EqualsContext ec; if (h1->header.type != h2->header.type) return GNUNET_TIME_UNIT_ZERO_ABS; if (0 != - GNUNET_memcmp (&h1->publicKey, - &h2->publicKey)) + GNUNET_memcmp(&h1->publicKey, + &h2->publicKey)) return GNUNET_TIME_UNIT_ZERO_ABS; ec.expiration_limit = now; ec.result = GNUNET_TIME_UNIT_FOREVER_ABS; ec.ref = h2; - GNUNET_HELLO_iterate_addresses (h1, - GNUNET_NO, - &find_matching, - &ec); + GNUNET_HELLO_iterate_addresses(h1, + GNUNET_NO, + &find_matching, + &ec); if (ec.result.abs_value_us == GNUNET_TIME_UNIT_ZERO.rel_value_us) return ec.result; ec.ref = h1; - GNUNET_HELLO_iterate_addresses (h2, - GNUNET_NO, - &find_matching, - &ec); + GNUNET_HELLO_iterate_addresses(h2, + GNUNET_NO, + &find_matching, + &ec); return ec.result; } @@ -869,13 +861,13 @@ GNUNET_HELLO_equals (const struct GNUNET_HELLO_Message *h1, * @return #GNUNET_OK (always) */ static int -find_max_expire (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +find_max_expire(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { struct GNUNET_TIME_Absolute *max = cls; - *max = GNUNET_TIME_absolute_max (*max, expiration); + *max = GNUNET_TIME_absolute_max(*max, expiration); return GNUNET_OK; } @@ -887,15 +879,15 @@ find_max_expire (void *cls, * @return time the last address expires, 0 if there are no addresses in the HELLO */ struct GNUNET_TIME_Absolute -GNUNET_HELLO_get_last_expiration (const struct GNUNET_HELLO_Message *msg) +GNUNET_HELLO_get_last_expiration(const struct GNUNET_HELLO_Message *msg) { struct GNUNET_TIME_Absolute ret; ret = GNUNET_TIME_UNIT_ZERO_ABS; - GNUNET_HELLO_iterate_addresses (msg, - GNUNET_NO, - &find_max_expire, - &ret); + GNUNET_HELLO_iterate_addresses(msg, + GNUNET_NO, + &find_max_expire, + &ret); return ret; } @@ -954,9 +946,9 @@ GNUNET_HELLO_get_last_expiration (const struct GNUNET_HELLO_Message *msg) * @return #GNUNET_OK (continue iteration). */ static int -add_address_to_uri (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +add_address_to_uri(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { struct GNUNET_HELLO_ComposeUriContext *ctx = cls; struct GNUNET_TRANSPORT_PluginFunctions *papi; @@ -969,49 +961,49 @@ add_address_to_uri (void *cls, struct tm *t; time_t seconds; - papi = ctx->plugins_find (address->transport_name); + papi = ctx->plugins_find(address->transport_name); if (NULL == papi) - { - /* Not an error - we might just not have the right plugin. */ - return GNUNET_OK; - } + { + /* Not an error - we might just not have the right plugin. */ + return GNUNET_OK; + } if (NULL == papi->address_to_string) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "URI conversion not implemented for plugin `%s'\n", - address->transport_name); - return GNUNET_OK; - } - addr = papi->address_to_string (papi->cls, - address->address, - address->address_length); - if ( (NULL == addr) || - (0 == strlen(addr)) ) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "URI conversion not implemented for plugin `%s'\n", + address->transport_name); + return GNUNET_OK; + } + addr = papi->address_to_string(papi->cls, + address->address, + address->address_length); + if ((NULL == addr) || + (0 == strlen(addr))) return GNUNET_OK; - addr_dup = GNUNET_strdup (addr); - if (NULL != (pos = strstr (addr_dup, "_server"))) - GNUNET_memcpy (pos, - client_str, - strlen (client_str)); /* Replace all server addresses with client addresses */ + addr_dup = GNUNET_strdup(addr); + if (NULL != (pos = strstr(addr_dup, "_server"))) + GNUNET_memcpy(pos, + client_str, + strlen(client_str)); /* Replace all server addresses with client addresses */ seconds = expiration.abs_value_us / 1000LL / 1000LL; - t = gmtime (&seconds); - - GNUNET_asprintf (&ret, - "%s%c%s%c%s%c%s", - ctx->uri, - GNUNET_HELLO_URI_SEP, - strftime (tbuf, - sizeof (tbuf), - "%Y%m%d%H%M%S", - t) ? tbuf : "0", - GNUNET_HELLO_URI_SEP, - address->transport_name, - GNUNET_HELLO_URI_SEP, - addr_dup); - GNUNET_free (addr_dup); - GNUNET_free (ctx->uri); + t = gmtime(&seconds); + + GNUNET_asprintf(&ret, + "%s%c%s%c%s%c%s", + ctx->uri, + GNUNET_HELLO_URI_SEP, + strftime(tbuf, + sizeof(tbuf), + "%Y%m%d%H%M%S", + t) ? tbuf : "0", + GNUNET_HELLO_URI_SEP, + address->transport_name, + GNUNET_HELLO_URI_SEP, + addr_dup); + GNUNET_free(addr_dup); + GNUNET_free(ctx->uri); ctx->uri = ret; return GNUNET_OK; } @@ -1025,25 +1017,25 @@ add_address_to_uri (void *cls, * @return Hello URI string */ char * -GNUNET_HELLO_compose_uri (const struct GNUNET_HELLO_Message *hello, - GNUNET_HELLO_TransportPluginsFind plugins_find) +GNUNET_HELLO_compose_uri(const struct GNUNET_HELLO_Message *hello, + GNUNET_HELLO_TransportPluginsFind plugins_find) { struct GNUNET_HELLO_ComposeUriContext ctx; char *pkey; ctx.plugins_find = plugins_find; - pkey = GNUNET_CRYPTO_eddsa_public_key_to_string (&hello->publicKey); - GNUNET_asprintf (&ctx.uri, - "%s%s", - (GNUNET_YES == GNUNET_HELLO_is_friend_only (hello)) - ? GNUNET_FRIEND_HELLO_URI_PREFIX - : GNUNET_HELLO_URI_PREFIX, - pkey); - GNUNET_free (pkey); - GNUNET_HELLO_iterate_addresses (hello, - GNUNET_NO, - &add_address_to_uri, - &ctx); + pkey = GNUNET_CRYPTO_eddsa_public_key_to_string(&hello->publicKey); + GNUNET_asprintf(&ctx.uri, + "%s%s", + (GNUNET_YES == GNUNET_HELLO_is_friend_only(hello)) + ? GNUNET_FRIEND_HELLO_URI_PREFIX + : GNUNET_HELLO_URI_PREFIX, + pkey); + GNUNET_free(pkey); + GNUNET_HELLO_iterate_addresses(hello, + GNUNET_NO, + &add_address_to_uri, + &ctx); return ctx.uri; } @@ -1061,9 +1053,9 @@ GNUNET_HELLO_compose_uri (const struct GNUNET_HELLO_Message *hello, * @return number of bytes added to buffer, #GNUNET_SYSERR on error */ static ssize_t -add_address_to_hello (void *cls, - size_t max, - void *buffer) +add_address_to_hello(void *cls, + size_t max, + void *buffer) { struct GNUNET_HELLO_ParseUriContext *ctx = cls; const char *tname; @@ -1083,119 +1075,119 @@ add_address_to_hello (void *cls, if (NULL == ctx->pos) return GNUNET_SYSERR; if (GNUNET_HELLO_URI_SEP != ctx->pos[0]) - { - ctx->ret = GNUNET_SYSERR; - GNUNET_break (0); - return GNUNET_SYSERR; - } - ctx->pos++; - - if ( ('0' == ctx->pos[0]) && - (GNUNET_HELLO_URI_SEP == ctx->pos[1]) ) - { - expire = GNUNET_TIME_UNIT_FOREVER_ABS; - tname = ctx->pos + 1; - } - else - { - memset (&expiration_time, 0, sizeof (expiration_time)); - tname = strptime (ctx->pos, - "%Y%m%d%H%M%S", - &expiration_time); - if (NULL == tname) { ctx->ret = GNUNET_SYSERR; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to parse HELLO message: missing expiration time\n")); - GNUNET_break (0); + GNUNET_break(0); return GNUNET_SYSERR; } + ctx->pos++; - expiration_seconds = mktime (&expiration_time); - if (expiration_seconds == (time_t) -1) + if (('0' == ctx->pos[0]) && + (GNUNET_HELLO_URI_SEP == ctx->pos[1])) + { + expire = GNUNET_TIME_UNIT_FOREVER_ABS; + tname = ctx->pos + 1; + } + else + { + memset(&expiration_time, 0, sizeof(expiration_time)); + tname = strptime(ctx->pos, + "%Y%m%d%H%M%S", + &expiration_time); + if (NULL == tname) + { + ctx->ret = GNUNET_SYSERR; + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to parse HELLO message: missing expiration time\n")); + GNUNET_break(0); + return GNUNET_SYSERR; + } + + expiration_seconds = mktime(&expiration_time); + if (expiration_seconds == (time_t)-1) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to parse HELLO message: invalid expiration time\n")); + ctx->ret = GNUNET_SYSERR; + GNUNET_break(0); + return GNUNET_SYSERR; + } + expire.abs_value_us = expiration_seconds * 1000LL * 1000LL; + } + if (GNUNET_HELLO_URI_SEP != tname[0]) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to parse HELLO message: invalid expiration time\n")); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to parse HELLO message: malformed\n")); ctx->ret = GNUNET_SYSERR; - GNUNET_break (0); + GNUNET_break(0); return GNUNET_SYSERR; } - expire.abs_value_us = expiration_seconds * 1000LL * 1000LL; - } - if (GNUNET_HELLO_URI_SEP != tname[0]) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to parse HELLO message: malformed\n")); - ctx->ret = GNUNET_SYSERR; - GNUNET_break (0); - return GNUNET_SYSERR; - } tname++; - address = strchr (tname, - (int) GNUNET_HELLO_URI_SEP); + address = strchr(tname, + (int)GNUNET_HELLO_URI_SEP); if (NULL == address) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to parse HELLO message: missing transport plugin\n")); - ctx->ret = GNUNET_SYSERR; - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to parse HELLO message: missing transport plugin\n")); + ctx->ret = GNUNET_SYSERR; + GNUNET_break(0); + return GNUNET_SYSERR; + } address++; - end = strchr (address, (int) GNUNET_HELLO_URI_SEP); + end = strchr(address, (int)GNUNET_HELLO_URI_SEP); ctx->pos = end; - ctx->counter_total ++; - plugin_name = GNUNET_strndup (tname, address - (tname+1)); - papi = ctx->plugins_find (plugin_name); + ctx->counter_total++; + plugin_name = GNUNET_strndup(tname, address - (tname + 1)); + papi = ctx->plugins_find(plugin_name); if (NULL == papi) - { - /* Not an error - we might just not have the right plugin. - * Skip this part, advance to the next one and recurse. - * But only if this is not the end of string. - */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Plugin `%s' not found, skipping address\n"), - plugin_name); - GNUNET_free (plugin_name); - return 0; - } + { + /* Not an error - we might just not have the right plugin. + * Skip this part, advance to the next one and recurse. + * But only if this is not the end of string. + */ + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Plugin `%s' not found, skipping address\n"), + plugin_name); + GNUNET_free(plugin_name); + return 0; + } if (NULL == papi->string_to_address) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Plugin `%s' does not support URIs yet\n"), - plugin_name); - GNUNET_free (plugin_name); - GNUNET_break (0); - return 0; - } - uri_address = GNUNET_strndup (address, end - address); + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Plugin `%s' does not support URIs yet\n"), + plugin_name); + GNUNET_free(plugin_name); + GNUNET_break(0); + return 0; + } + uri_address = GNUNET_strndup(address, end - address); if (GNUNET_OK != - papi->string_to_address (papi->cls, - uri_address, - strlen (uri_address) + 1, - &addr, - &addr_len)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to parse `%s' as an address for plugin `%s'\n"), - uri_address, - plugin_name); - GNUNET_free (plugin_name); - GNUNET_free (uri_address); - return 0; - } - GNUNET_free (uri_address); + papi->string_to_address(papi->cls, + uri_address, + strlen(uri_address) + 1, + &addr, + &addr_len)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to parse `%s' as an address for plugin `%s'\n"), + uri_address, + plugin_name); + GNUNET_free(plugin_name); + GNUNET_free(uri_address); + return 0; + } + GNUNET_free(uri_address); /* address.peer is unset - not used by add_address() */ haddr.address_length = addr_len; haddr.address = addr; haddr.transport_name = plugin_name; - ret = GNUNET_HELLO_add_address (&haddr, - expire, - buffer, - max); - ctx->counter_added ++; - GNUNET_free (addr); - GNUNET_free (plugin_name); + ret = GNUNET_HELLO_add_address(&haddr, + expire, + buffer, + max); + ctx->counter_added++; + GNUNET_free(addr); + GNUNET_free(plugin_name); return ret; } @@ -1210,39 +1202,39 @@ add_address_to_hello (void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR if the URI was invalid, #GNUNET_NO on other errors */ int -GNUNET_HELLO_parse_uri (const char *uri, - struct GNUNET_CRYPTO_EddsaPublicKey *pubkey, - struct GNUNET_HELLO_Message **hello, - GNUNET_HELLO_TransportPluginsFind plugins_find) +GNUNET_HELLO_parse_uri(const char *uri, + struct GNUNET_CRYPTO_EddsaPublicKey *pubkey, + struct GNUNET_HELLO_Message **hello, + GNUNET_HELLO_TransportPluginsFind plugins_find) { const char *pks; const char *exc; int friend_only; struct GNUNET_HELLO_ParseUriContext ctx; - if (0 == strncmp (uri, - GNUNET_HELLO_URI_PREFIX, - strlen (GNUNET_HELLO_URI_PREFIX))) - { - pks = &uri[strlen (GNUNET_HELLO_URI_PREFIX)]; - friend_only = GNUNET_NO; - } - else if (0 == strncmp (uri, - GNUNET_FRIEND_HELLO_URI_PREFIX, - strlen (GNUNET_FRIEND_HELLO_URI_PREFIX))) - { - pks = &uri[strlen (GNUNET_FRIEND_HELLO_URI_PREFIX)]; - friend_only = GNUNET_YES; - } + if (0 == strncmp(uri, + GNUNET_HELLO_URI_PREFIX, + strlen(GNUNET_HELLO_URI_PREFIX))) + { + pks = &uri[strlen(GNUNET_HELLO_URI_PREFIX)]; + friend_only = GNUNET_NO; + } + else if (0 == strncmp(uri, + GNUNET_FRIEND_HELLO_URI_PREFIX, + strlen(GNUNET_FRIEND_HELLO_URI_PREFIX))) + { + pks = &uri[strlen(GNUNET_FRIEND_HELLO_URI_PREFIX)]; + friend_only = GNUNET_YES; + } else return GNUNET_SYSERR; - exc = strchr (pks, GNUNET_HELLO_URI_SEP); + exc = strchr(pks, GNUNET_HELLO_URI_SEP); if (GNUNET_OK != - GNUNET_STRINGS_string_to_data (pks, - (NULL == exc) ? strlen (pks) : (exc - pks), - (unsigned char *) pubkey, - sizeof (*pubkey))) + GNUNET_STRINGS_string_to_data(pks, + (NULL == exc) ? strlen(pks) : (exc - pks), + (unsigned char *)pubkey, + sizeof(*pubkey))) return GNUNET_SYSERR; ctx.pos = exc; @@ -1250,15 +1242,15 @@ GNUNET_HELLO_parse_uri (const char *uri, ctx.counter_total = 0; ctx.counter_added = 0; ctx.plugins_find = plugins_find; - *hello = GNUNET_HELLO_create (pubkey, - &add_address_to_hello, - &ctx, - friend_only); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "HELLO URI contained %u addresses, added %u addresses\n", - ctx.counter_total, - ctx.counter_added); + *hello = GNUNET_HELLO_create(pubkey, + &add_address_to_hello, + &ctx, + friend_only); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "HELLO URI contained %u addresses, added %u addresses\n", + ctx.counter_total, + ctx.counter_added); return ctx.ret; } diff --git a/src/hello/test_friend_hello.c b/src/hello/test_friend_hello.c index 9e1a3297c..7cbb019c6 100644 --- a/src/hello/test_friend_hello.c +++ b/src/hello/test_friend_hello.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hello/test_friend_hello.c * @brief test for hello.c @@ -27,73 +27,73 @@ static ssize_t -my_addr_gen (void *cls, - size_t max, - void *buf) +my_addr_gen(void *cls, + size_t max, + void *buf) { unsigned int *i = cls; size_t ret; struct GNUNET_HELLO_Address address; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "DEBUG: my_addr_gen called with i = %d\n", *i); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "DEBUG: my_addr_gen called with i = %d\n", *i); if (0 == *i) return GNUNET_SYSERR; /* Stop iteration */ - memset (&address.peer, 0, sizeof (struct GNUNET_PeerIdentity)); + memset(&address.peer, 0, sizeof(struct GNUNET_PeerIdentity)); address.address = "address_information"; address.transport_name = "test"; address.address_length = *i; ret = - GNUNET_HELLO_add_address (&address, GNUNET_TIME_absolute_get (), buf, - max); + GNUNET_HELLO_add_address(&address, GNUNET_TIME_absolute_get(), buf, + max); (*i)--; return ret; } static int -check_addr (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +check_addr(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { unsigned int *i = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "DEBUG: check_addr called with i = %d and addrlen = %u\n", - *i, (unsigned int) address->address_length); - GNUNET_assert (address->address_length > 0); - GNUNET_assert (*i & (1 << (address->address_length - 1))); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "DEBUG: check_addr called with i = %d and addrlen = %u\n", + *i, (unsigned int)address->address_length); + GNUNET_assert(address->address_length > 0); + GNUNET_assert(*i & (1 << (address->address_length - 1))); *i -= (1 << (address->address_length - 1)); - GNUNET_assert (0 == - strncmp ("address_information", address->address, - address->address_length)); - GNUNET_assert (0 == strcmp ("test", address->transport_name)); + GNUNET_assert(0 == + strncmp("address_information", address->address, + address->address_length)); + GNUNET_assert(0 == strcmp("test", address->transport_name)); return GNUNET_OK; } static int -remove_some (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +remove_some(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { unsigned int *i = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "DEBUG: remove_some called with i = %d and addrlen = %u\n", - *i, (unsigned int) address->address_length); - GNUNET_assert (address->address_length > 0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "DEBUG: remove_some called with i = %d and addrlen = %u\n", + *i, (unsigned int)address->address_length); + GNUNET_assert(address->address_length > 0); if (*i & (1 << (address->address_length - 1))) - { - *i -= (1 << (address->address_length - 1)); - return GNUNET_NO; - } + { + *i -= (1 << (address->address_length - 1)); + return GNUNET_NO; + } return GNUNET_OK; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { struct GNUNET_HELLO_Message *msg1; struct GNUNET_HELLO_Message *msg2; @@ -102,84 +102,84 @@ main (int argc, char *argv[]) struct GNUNET_TIME_Absolute startup_time; unsigned int i; - GNUNET_log_setup ("test-hello", "DEBUG", NULL); - startup_time = GNUNET_TIME_absolute_get (); - memset (&publicKey, 42, sizeof (publicKey)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing HELLO creation (without addresses)...\n"); + GNUNET_log_setup("test-hello", "DEBUG", NULL); + startup_time = GNUNET_TIME_absolute_get(); + memset(&publicKey, 42, sizeof(publicKey)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing HELLO creation (without addresses)...\n"); i = 0; - msg1 = GNUNET_HELLO_create (&publicKey, &my_addr_gen, &i, GNUNET_YES); - GNUNET_assert (msg1 != NULL); - GNUNET_assert (0 < GNUNET_HELLO_size (msg1)); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing address iteration (empty set)...\n"); - GNUNET_assert (NULL == - GNUNET_HELLO_iterate_addresses (msg1, GNUNET_NO, &check_addr, - &i)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing HELLO creation (with one address)...\n"); + msg1 = GNUNET_HELLO_create(&publicKey, &my_addr_gen, &i, GNUNET_YES); + GNUNET_assert(msg1 != NULL); + GNUNET_assert(0 < GNUNET_HELLO_size(msg1)); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing address iteration (empty set)...\n"); + GNUNET_assert(NULL == + GNUNET_HELLO_iterate_addresses(msg1, GNUNET_NO, &check_addr, + &i)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing HELLO creation (with one address)...\n"); i = 1; - msg2 = GNUNET_HELLO_create (&publicKey, &my_addr_gen, &i, GNUNET_YES); - GNUNET_assert (msg2 != NULL); - GNUNET_assert (GNUNET_HELLO_size (msg1) < GNUNET_HELLO_size (msg2)); + msg2 = GNUNET_HELLO_create(&publicKey, &my_addr_gen, &i, GNUNET_YES); + GNUNET_assert(msg2 != NULL); + GNUNET_assert(GNUNET_HELLO_size(msg1) < GNUNET_HELLO_size(msg2)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing address iteration (one address)...\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing address iteration (one address)...\n"); i = 1; - GNUNET_assert (NULL == - GNUNET_HELLO_iterate_addresses (msg2, GNUNET_NO, &check_addr, - &i)); - GNUNET_assert (i == 0); - GNUNET_free (msg1); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing HELLO creation (with two addresses)...\n"); + GNUNET_assert(NULL == + GNUNET_HELLO_iterate_addresses(msg2, GNUNET_NO, &check_addr, + &i)); + GNUNET_assert(i == 0); + GNUNET_free(msg1); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing HELLO creation (with two addresses)...\n"); i = 2; - msg3 = GNUNET_HELLO_create (&publicKey, &my_addr_gen, &i, GNUNET_YES); - GNUNET_assert (msg3 != NULL); - GNUNET_assert (GNUNET_HELLO_size (msg2) < GNUNET_HELLO_size (msg3)); + msg3 = GNUNET_HELLO_create(&publicKey, &my_addr_gen, &i, GNUNET_YES); + GNUNET_assert(msg3 != NULL); + GNUNET_assert(GNUNET_HELLO_size(msg2) < GNUNET_HELLO_size(msg3)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing address iteration (two addresses)...\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing address iteration (two addresses)...\n"); i = 3; - GNUNET_assert (NULL == - GNUNET_HELLO_iterate_addresses (msg3, GNUNET_NO, &check_addr, - &i)); - GNUNET_assert (i == 0); + GNUNET_assert(NULL == + GNUNET_HELLO_iterate_addresses(msg3, GNUNET_NO, &check_addr, + &i)); + GNUNET_assert(i == 0); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing HELLO merge...\n"); - msg1 = GNUNET_HELLO_merge (msg2, msg3); - GNUNET_assert (GNUNET_HELLO_size (msg1) == GNUNET_HELLO_size (msg3)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing HELLO merge...\n"); + msg1 = GNUNET_HELLO_merge(msg2, msg3); + GNUNET_assert(GNUNET_HELLO_size(msg1) == GNUNET_HELLO_size(msg3)); i = 3; - GNUNET_assert (NULL == - GNUNET_HELLO_iterate_addresses (msg1, GNUNET_NO, &check_addr, - &i)); - GNUNET_assert (i == 0); - GNUNET_free (msg1); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing address iteration to copy HELLO...\n"); + GNUNET_assert(NULL == + GNUNET_HELLO_iterate_addresses(msg1, GNUNET_NO, &check_addr, + &i)); + GNUNET_assert(i == 0); + GNUNET_free(msg1); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing address iteration to copy HELLO...\n"); i = 2; - msg1 = GNUNET_HELLO_iterate_addresses (msg3, GNUNET_YES, &remove_some, &i); - GNUNET_assert (msg1 != NULL); - GNUNET_assert (i == 0); + msg1 = GNUNET_HELLO_iterate_addresses(msg3, GNUNET_YES, &remove_some, &i); + GNUNET_assert(msg1 != NULL); + GNUNET_assert(i == 0); i = 1; - GNUNET_assert (NULL == - GNUNET_HELLO_iterate_addresses (msg1, GNUNET_NO, &check_addr, - &i)); - GNUNET_assert (i == 0); - GNUNET_free (msg1); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing delta address iteration...\n"); + GNUNET_assert(NULL == + GNUNET_HELLO_iterate_addresses(msg1, GNUNET_NO, &check_addr, + &i)); + GNUNET_assert(i == 0); + GNUNET_free(msg1); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing delta address iteration...\n"); i = 2; - GNUNET_HELLO_iterate_new_addresses (msg3, msg2, startup_time, &check_addr, - &i); - GNUNET_assert (i == 0); - GNUNET_free (msg2); - GNUNET_free (msg3); + GNUNET_HELLO_iterate_new_addresses(msg3, msg2, startup_time, &check_addr, + &i); + GNUNET_assert(i == 0); + GNUNET_free(msg2); + GNUNET_free(msg3); return 0; /* testcase passed */ } diff --git a/src/hello/test_hello.c b/src/hello/test_hello.c index 1f9c398fa..f3134a7ad 100644 --- a/src/hello/test_hello.c +++ b/src/hello/test_hello.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hello/test_hello.c * @brief test for hello.c @@ -35,27 +35,27 @@ * @return */ static ssize_t -my_addr_gen (void *cls, - size_t max, - void *buf) +my_addr_gen(void *cls, + size_t max, + void *buf) { unsigned int *i = cls; size_t ret; struct GNUNET_HELLO_Address address; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "DEBUG: my_addr_gen called with i = %d\n", - *i); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "DEBUG: my_addr_gen called with i = %d\n", + *i); if (0 == *i) return GNUNET_SYSERR; - memset (&address.peer, 0, sizeof (struct GNUNET_PeerIdentity)); + memset(&address.peer, 0, sizeof(struct GNUNET_PeerIdentity)); address.address = "address_information"; address.transport_name = "test"; address.address_length = *i; - ret = GNUNET_HELLO_add_address (&address, - GNUNET_TIME_absolute_get (), - buf, - max); + ret = GNUNET_HELLO_add_address(&address, + GNUNET_TIME_absolute_get(), + buf, + max); (*i)--; return ret; } @@ -70,25 +70,25 @@ my_addr_gen (void *cls, * @return */ static int -check_addr (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +check_addr(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { unsigned int *i = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "DEBUG: check_addr called with i = %d and addrlen = %u\n", - *i, - (unsigned int) address->address_length); - GNUNET_assert (address->address_length > 0); - GNUNET_assert (*i & (1 << (address->address_length - 1))); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "DEBUG: check_addr called with i = %d and addrlen = %u\n", + *i, + (unsigned int)address->address_length); + GNUNET_assert(address->address_length > 0); + GNUNET_assert(*i & (1 << (address->address_length - 1))); *i -= (1 << (address->address_length - 1)); - GNUNET_assert (0 == - strncmp ("address_information", - address->address, - address->address_length)); - GNUNET_assert (0 == strcmp ("test", - address->transport_name)); + GNUNET_assert(0 == + strncmp("address_information", + address->address, + address->address_length)); + GNUNET_assert(0 == strcmp("test", + address->transport_name)); return GNUNET_OK; } @@ -102,29 +102,29 @@ check_addr (void *cls, * @return */ static int -remove_some (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +remove_some(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { unsigned int *i = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "DEBUG: remove_some called with i = %d and addrlen = %u\n", - *i, - (unsigned int) address->address_length); - GNUNET_assert (address->address_length > 0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "DEBUG: remove_some called with i = %d and addrlen = %u\n", + *i, + (unsigned int)address->address_length); + GNUNET_assert(address->address_length > 0); if (*i & (1 << (address->address_length - 1))) - { - *i -= (1 << (address->address_length - 1)); - return GNUNET_NO; - } + { + *i -= (1 << (address->address_length - 1)); + return GNUNET_NO; + } return GNUNET_OK; } int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { struct GNUNET_HELLO_Message *msg1; struct GNUNET_HELLO_Message *msg2; @@ -134,118 +134,118 @@ main (int argc, struct GNUNET_TIME_Absolute startup_time; unsigned int i; - GNUNET_log_setup ("test-hello", - "DEBUG", - NULL); - startup_time = GNUNET_TIME_absolute_get (); - memset (&publicKey, 42, sizeof (publicKey)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing HELLO creation (without addresses)...\n"); + GNUNET_log_setup("test-hello", + "DEBUG", + NULL); + startup_time = GNUNET_TIME_absolute_get(); + memset(&publicKey, 42, sizeof(publicKey)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing HELLO creation (without addresses)...\n"); i = 0; - msg1 = GNUNET_HELLO_create (&publicKey, - &my_addr_gen, - &i, - GNUNET_NO); - GNUNET_assert (msg1 != NULL); - GNUNET_assert (0 < GNUNET_HELLO_size (msg1)); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing address iteration (empty set)...\n"); - GNUNET_assert (NULL == - GNUNET_HELLO_iterate_addresses (msg1, - GNUNET_NO, - &check_addr, - &i)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing HELLO creation (with one address)...\n"); + msg1 = GNUNET_HELLO_create(&publicKey, + &my_addr_gen, + &i, + GNUNET_NO); + GNUNET_assert(msg1 != NULL); + GNUNET_assert(0 < GNUNET_HELLO_size(msg1)); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing address iteration (empty set)...\n"); + GNUNET_assert(NULL == + GNUNET_HELLO_iterate_addresses(msg1, + GNUNET_NO, + &check_addr, + &i)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing HELLO creation (with one address)...\n"); i = 1; - msg2 = GNUNET_HELLO_create (&publicKey, - &my_addr_gen, - &i, - GNUNET_NO); - GNUNET_assert (msg2 != NULL); - GNUNET_assert (GNUNET_HELLO_size (msg1) < GNUNET_HELLO_size (msg2)); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing address iteration (one address)...\n"); + msg2 = GNUNET_HELLO_create(&publicKey, + &my_addr_gen, + &i, + GNUNET_NO); + GNUNET_assert(msg2 != NULL); + GNUNET_assert(GNUNET_HELLO_size(msg1) < GNUNET_HELLO_size(msg2)); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing address iteration (one address)...\n"); i = 1; - GNUNET_assert (NULL == - GNUNET_HELLO_iterate_addresses (msg2, - GNUNET_NO, - &check_addr, - &i)); - GNUNET_assert (i == 0); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing get_key from HELLO...\n"); - GNUNET_assert (GNUNET_OK == GNUNET_HELLO_get_id (msg2, &pid)); - GNUNET_assert (0 == GNUNET_memcmp (&publicKey, - &pid.public_key)); - GNUNET_free (msg1); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing HELLO creation (with two addresses)...\n"); + GNUNET_assert(NULL == + GNUNET_HELLO_iterate_addresses(msg2, + GNUNET_NO, + &check_addr, + &i)); + GNUNET_assert(i == 0); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing get_key from HELLO...\n"); + GNUNET_assert(GNUNET_OK == GNUNET_HELLO_get_id(msg2, &pid)); + GNUNET_assert(0 == GNUNET_memcmp(&publicKey, + &pid.public_key)); + GNUNET_free(msg1); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing HELLO creation (with two addresses)...\n"); i = 2; - msg3 = GNUNET_HELLO_create (&publicKey, - &my_addr_gen, - &i, - GNUNET_NO); - GNUNET_assert (msg3 != NULL); - GNUNET_assert (GNUNET_HELLO_size (msg2) < GNUNET_HELLO_size (msg3)); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing address iteration (two addresses)...\n"); + msg3 = GNUNET_HELLO_create(&publicKey, + &my_addr_gen, + &i, + GNUNET_NO); + GNUNET_assert(msg3 != NULL); + GNUNET_assert(GNUNET_HELLO_size(msg2) < GNUNET_HELLO_size(msg3)); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing address iteration (two addresses)...\n"); i = 3; - GNUNET_assert (NULL == - GNUNET_HELLO_iterate_addresses (msg3, - GNUNET_NO, - &check_addr, - &i)); - GNUNET_assert (i == 0); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing HELLO merge...\n"); - msg1 = GNUNET_HELLO_merge (msg2, msg3); - GNUNET_assert (GNUNET_HELLO_size (msg1) == GNUNET_HELLO_size (msg3)); + GNUNET_assert(NULL == + GNUNET_HELLO_iterate_addresses(msg3, + GNUNET_NO, + &check_addr, + &i)); + GNUNET_assert(i == 0); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing HELLO merge...\n"); + msg1 = GNUNET_HELLO_merge(msg2, msg3); + GNUNET_assert(GNUNET_HELLO_size(msg1) == GNUNET_HELLO_size(msg3)); i = 3; - GNUNET_assert (NULL == - GNUNET_HELLO_iterate_addresses (msg1, - GNUNET_NO, - &check_addr, - &i)); - GNUNET_assert (i == 0); - GNUNET_free (msg1); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing address iteration to copy HELLO...\n"); + GNUNET_assert(NULL == + GNUNET_HELLO_iterate_addresses(msg1, + GNUNET_NO, + &check_addr, + &i)); + GNUNET_assert(i == 0); + GNUNET_free(msg1); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing address iteration to copy HELLO...\n"); i = 2; - msg1 = GNUNET_HELLO_iterate_addresses (msg3, - GNUNET_YES, - &remove_some, - &i); - GNUNET_assert (msg1 != NULL); - GNUNET_assert (i == 0); + msg1 = GNUNET_HELLO_iterate_addresses(msg3, + GNUNET_YES, + &remove_some, + &i); + GNUNET_assert(msg1 != NULL); + GNUNET_assert(i == 0); i = 1; - GNUNET_assert (NULL == - GNUNET_HELLO_iterate_addresses (msg1, - GNUNET_NO, - &check_addr, - &i)); - GNUNET_assert (i == 0); - GNUNET_free (msg1); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing delta address iteration...\n"); + GNUNET_assert(NULL == + GNUNET_HELLO_iterate_addresses(msg1, + GNUNET_NO, + &check_addr, + &i)); + GNUNET_assert(i == 0); + GNUNET_free(msg1); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing delta address iteration...\n"); i = 2; - GNUNET_HELLO_iterate_new_addresses (msg3, - msg2, - startup_time, - &check_addr, - &i); - GNUNET_assert (i == 0); - GNUNET_free (msg2); - GNUNET_free (msg3); + GNUNET_HELLO_iterate_new_addresses(msg3, + msg2, + startup_time, + &check_addr, + &i); + GNUNET_assert(i == 0); + GNUNET_free(msg2); + GNUNET_free(msg3); return 0; /* testcase passed */ } diff --git a/src/hostlist/gnunet-daemon-hostlist.c b/src/hostlist/gnunet-daemon-hostlist.c index 760d5f543..7c1863dc0 100644 --- a/src/hostlist/gnunet-daemon-hostlist.c +++ b/src/hostlist/gnunet-daemon-hostlist.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hostlist/gnunet-daemon-hostlist.c @@ -102,8 +102,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * unaligned!) * 4) address (address-length bytes; possibly unaligned!) */ -struct GNUNET_HOSTLIST_ADV_Message -{ +struct GNUNET_HOSTLIST_ADV_Message { /** * Type will be GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT. */ @@ -130,8 +129,8 @@ static struct GNUNET_PeerIdentity me; * @param my_identity our peer's identity */ static void -core_init (void *cls, - const struct GNUNET_PeerIdentity *my_identity) +core_init(void *cls, + const struct GNUNET_PeerIdentity *my_identity) { me = *my_identity; } @@ -145,26 +144,26 @@ core_init (void *cls, * @return #GNUNET_OK if message is well-formed */ static int -check_advertisement (void *cls, - const struct GNUNET_MessageHeader *message) +check_advertisement(void *cls, + const struct GNUNET_MessageHeader *message) { size_t size; size_t uri_size; const char *uri; - size = ntohs (message->size); - if (size <= sizeof (struct GNUNET_MessageHeader)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - uri = (const char *) &message[1]; - uri_size = size - sizeof (struct GNUNET_MessageHeader); + size = ntohs(message->size); + if (size <= sizeof(struct GNUNET_MessageHeader)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + uri = (const char *)&message[1]; + uri_size = size - sizeof(struct GNUNET_MessageHeader); if (uri[uri_size - 1] != '\0') - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -177,13 +176,13 @@ check_advertisement (void *cls, * @return #GNUNET_OK on success */ static void -handle_advertisement (void *cls, - const struct GNUNET_MessageHeader *message) +handle_advertisement(void *cls, + const struct GNUNET_MessageHeader *message) { - const char *uri = (const char *) &message[1]; - - GNUNET_assert (NULL != client_adv_handler); - (void) (*client_adv_handler) (uri); + const char *uri = (const char *)&message[1]; + + GNUNET_assert(NULL != client_adv_handler); + (void)(*client_adv_handler)(uri); } @@ -197,28 +196,28 @@ handle_advertisement (void *cls, * @return peer */ static void * -connect_handler (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +connect_handler(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { - if (0 == GNUNET_memcmp (&me, - peer)) + if (0 == GNUNET_memcmp(&me, + peer)) return NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "A new peer connected, notifying client and server\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "A new peer connected, notifying client and server\n"); if (NULL != client_ch) - GNUNET_assert (NULL == - (*client_ch) (cls, - peer, - mq)); + GNUNET_assert(NULL == + (*client_ch)(cls, + peer, + mq)); #if HAVE_MHD if (NULL != server_ch) - GNUNET_assert (NULL == - (*server_ch) (cls, - peer, - mq)); + GNUNET_assert(NULL == + (*server_ch)(cls, + peer, + mq)); #endif - return (void *) peer; + return (void *)peer; } @@ -230,18 +229,18 @@ connect_handler (void *cls, * @param peer peer identity this notification is about */ static void -disconnect_handler (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *internal_cls) +disconnect_handler(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *internal_cls) { - if (0 == GNUNET_memcmp (&me, - peer)) + if (0 == GNUNET_memcmp(&me, + peer)) return; /* call hostlist client disconnect handler */ if (NULL != client_dh) - (*client_dh) (cls, - peer, - NULL); + (*client_dh)(cls, + peer, + NULL); } @@ -252,31 +251,31 @@ disconnect_handler (void *cls, * @param cls NULL */ static void -cleaning_task (void *cls) +cleaning_task(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Hostlist daemon is shutting down\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Hostlist daemon is shutting down\n"); if (NULL != core) - { - GNUNET_CORE_disconnect (core); - core = NULL; - } + { + GNUNET_CORE_disconnect(core); + core = NULL; + } if (bootstrapping) - { - GNUNET_HOSTLIST_client_stop (); - } + { + GNUNET_HOSTLIST_client_stop(); + } #if HAVE_MHD if (provide_hostlist) - { - GNUNET_HOSTLIST_server_stop (); - } + { + GNUNET_HOSTLIST_server_stop(); + } #endif if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, - GNUNET_NO); - stats = NULL; - } + { + GNUNET_STATISTICS_destroy(stats, + GNUNET_NO); + stats = NULL; + } } @@ -289,71 +288,72 @@ cleaning_task (void *cls) * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_MQ_MessageHandler learn_handlers[] = { - GNUNET_MQ_hd_var_size (advertisement, - GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(advertisement, + GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_MessageHandler no_learn_handlers[] = { - GNUNET_MQ_handler_end () + GNUNET_MQ_handler_end() }; - if ((! bootstrapping) && (! learning) + + if ((!bootstrapping) && (!learning) #if HAVE_MHD - && (! provide_hostlist) + && (!provide_hostlist) #endif ) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("None of the functions for the hostlist daemon were enabled. I have no reason to run!\n")); - return; - } - stats = GNUNET_STATISTICS_create ("hostlist", cfg); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("None of the functions for the hostlist daemon were enabled. I have no reason to run!\n")); + return; + } + stats = GNUNET_STATISTICS_create("hostlist", cfg); if (NULL == stats) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } if (bootstrapping) - GNUNET_HOSTLIST_client_start (cfg, - stats, - &client_ch, - &client_dh, - &client_adv_handler, - learning); + GNUNET_HOSTLIST_client_start(cfg, + stats, + &client_ch, + &client_dh, + &client_adv_handler, + learning); core = - GNUNET_CORE_connect (cfg, - NULL, - &core_init, - &connect_handler, - &disconnect_handler, - learning ? learn_handlers : no_learn_handlers); + GNUNET_CORE_connect(cfg, + NULL, + &core_init, + &connect_handler, + &disconnect_handler, + learning ? learn_handlers : no_learn_handlers); #if HAVE_MHD if (provide_hostlist) - GNUNET_HOSTLIST_server_start (cfg, - stats, - core, - &server_ch, - advertising); + GNUNET_HOSTLIST_server_start(cfg, + stats, + core, + &server_ch, + advertising); #endif - GNUNET_SCHEDULER_add_shutdown (&cleaning_task, - NULL); + GNUNET_SCHEDULER_add_shutdown(&cleaning_task, + NULL); if (NULL == core) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect to `%s' service.\n"), "core"); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to `%s' service.\n"), "core"); + GNUNET_SCHEDULER_shutdown(); + return; + } } @@ -365,46 +365,46 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { #if HAVE_MHD - GNUNET_GETOPT_option_flag ('a', - "advertise", - gettext_noop ("advertise our hostlist to other peers"), - &advertising), + GNUNET_GETOPT_option_flag('a', + "advertise", + gettext_noop("advertise our hostlist to other peers"), + &advertising), #endif - GNUNET_GETOPT_option_flag ('b', - "bootstrap", - gettext_noop ("bootstrap using hostlists (it is highly recommended that you always use this option)"), - &bootstrapping), - GNUNET_GETOPT_option_flag ('e', - "enable-learning", - gettext_noop ("enable learning about hostlist servers from other peers"), - &learning), + GNUNET_GETOPT_option_flag('b', + "bootstrap", + gettext_noop("bootstrap using hostlists (it is highly recommended that you always use this option)"), + &bootstrapping), + GNUNET_GETOPT_option_flag('e', + "enable-learning", + gettext_noop("enable learning about hostlist servers from other peers"), + &learning), #if HAVE_MHD - GNUNET_GETOPT_option_flag ('p', - "provide-hostlist", - gettext_noop ("provide a hostlist server"), - &provide_hostlist), + GNUNET_GETOPT_option_flag('p', + "provide-hostlist", + gettext_noop("provide a hostlist server"), + &provide_hostlist), #endif GNUNET_GETOPT_OPTION_END }; int ret; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; - GNUNET_log_setup ("hostlist", "WARNING", NULL); + GNUNET_log_setup("hostlist", "WARNING", NULL); ret = - (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, - "hostlist", - _("GNUnet hostlist server and client"), - options, - &run, NULL)) ? 0 : 1; - GNUNET_free ((void*) argv); + (GNUNET_OK == + GNUNET_PROGRAM_run(argc, argv, + "hostlist", + _("GNUnet hostlist server and client"), + options, + &run, NULL)) ? 0 : 1; + GNUNET_free((void*)argv); return ret; } diff --git a/src/hostlist/gnunet-daemon-hostlist.h b/src/hostlist/gnunet-daemon-hostlist.h index df4c54db0..aec413fe6 100644 --- a/src/hostlist/gnunet-daemon-hostlist.h +++ b/src/hostlist/gnunet-daemon-hostlist.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hostlist/gnunet-daemon-hostlist.h diff --git a/src/hostlist/gnunet-daemon-hostlist_client.c b/src/hostlist/gnunet-daemon-hostlist_client.c index 0428e64b8..af3fd6fce 100644 --- a/src/hostlist/gnunet-daemon-hostlist_client.c +++ b/src/hostlist/gnunet-daemon-hostlist_client.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hostlist/gnunet-daemon-hostlist_client.c * @brief hostlist support. Downloads HELLOs via HTTP. @@ -49,19 +49,19 @@ * Time interval hostlists are saved to disk */ #define SAVING_INTERVAL \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 30) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 30) /** * Time interval between two hostlist tests */ #define TESTING_INTERVAL \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 3) /** * Time interval for download dispatcher before a download is re-scheduled */ #define WAITING_INTERVAL \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1) /** * Defines concerning the hostlist quality metric @@ -91,8 +91,7 @@ /** * A single hostlist obtained by hostlist advertisements */ -struct Hostlist -{ +struct Hostlist { /** * previous entry, used to manage entries in a double linked list */ @@ -321,7 +320,7 @@ static struct GNUNET_PEERINFO_Handle *pi; * @return number of bytes that were processed (always size*nmemb) */ static size_t -callback_download (void *ptr, size_t size, size_t nmemb, void *ctx) +callback_download(void *ptr, size_t size, size_t nmemb, void *ctx) { static char download_buffer[GNUNET_MAX_MESSAGE_SIZE - 1]; const char *cbuf = ptr; @@ -334,85 +333,85 @@ callback_download (void *ptr, size_t size, size_t nmemb, void *ctx) total = size * nmemb; stat_bytes_downloaded += total; if ((total == 0) || (stat_bogus_url)) - { - return total; /* ok, no data or bogus data */ - } - - GNUNET_STATISTICS_update (stats, - gettext_noop ( - "# bytes downloaded from hostlist servers"), - (int64_t) total, - GNUNET_NO); - left = total; - while ((left > 0) || (download_pos > 0)) - { - cpy = GNUNET_MIN (left, GNUNET_MAX_MESSAGE_SIZE - 1 - download_pos); - GNUNET_memcpy (&download_buffer[download_pos], cbuf, cpy); - cbuf += cpy; - download_pos += cpy; - left -= cpy; - if (download_pos < sizeof (struct GNUNET_MessageHeader)) - { - GNUNET_assert (0 == left); - break; - } - msg = (const struct GNUNET_MessageHeader *) download_buffer; - msize = ntohs (msg->size); - if (msize < sizeof (struct GNUNET_MessageHeader)) { - GNUNET_STATISTICS_update ( - stats, - gettext_noop ("# invalid HELLOs downloaded from hostlist servers"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Invalid `%s' message received from hostlist at `%s'\n"), - "HELLO", - current_url); - stat_hellos_obtained++; - stat_bogus_url = 1; - return total; + return total; /* ok, no data or bogus data */ } - if (download_pos < msize) - { - GNUNET_assert (left == 0); - break; - } - if (GNUNET_HELLO_size ((const struct GNUNET_HELLO_Message *) msg) == msize) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received valid `%s' message from hostlist server.\n", - "HELLO"); - GNUNET_STATISTICS_update ( - stats, - gettext_noop ("# valid HELLOs downloaded from hostlist servers"), - 1, - GNUNET_NO); - stat_hellos_obtained++; - (void) - GNUNET_PEERINFO_add_peer (pi, - (const struct GNUNET_HELLO_Message *) msg, - NULL, - NULL); - } - else + + GNUNET_STATISTICS_update(stats, + gettext_noop( + "# bytes downloaded from hostlist servers"), + (int64_t)total, + GNUNET_NO); + left = total; + while ((left > 0) || (download_pos > 0)) { - GNUNET_STATISTICS_update ( - stats, - gettext_noop ("# invalid HELLOs downloaded from hostlist servers"), - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Invalid `%s' message received from hostlist at `%s'\n"), - "HELLO", - current_url); - stat_bogus_url = GNUNET_YES; - stat_hellos_obtained++; - return total; + cpy = GNUNET_MIN(left, GNUNET_MAX_MESSAGE_SIZE - 1 - download_pos); + GNUNET_memcpy(&download_buffer[download_pos], cbuf, cpy); + cbuf += cpy; + download_pos += cpy; + left -= cpy; + if (download_pos < sizeof(struct GNUNET_MessageHeader)) + { + GNUNET_assert(0 == left); + break; + } + msg = (const struct GNUNET_MessageHeader *)download_buffer; + msize = ntohs(msg->size); + if (msize < sizeof(struct GNUNET_MessageHeader)) + { + GNUNET_STATISTICS_update( + stats, + gettext_noop("# invalid HELLOs downloaded from hostlist servers"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Invalid `%s' message received from hostlist at `%s'\n"), + "HELLO", + current_url); + stat_hellos_obtained++; + stat_bogus_url = 1; + return total; + } + if (download_pos < msize) + { + GNUNET_assert(left == 0); + break; + } + if (GNUNET_HELLO_size((const struct GNUNET_HELLO_Message *)msg) == msize) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received valid `%s' message from hostlist server.\n", + "HELLO"); + GNUNET_STATISTICS_update( + stats, + gettext_noop("# valid HELLOs downloaded from hostlist servers"), + 1, + GNUNET_NO); + stat_hellos_obtained++; + (void) + GNUNET_PEERINFO_add_peer(pi, + (const struct GNUNET_HELLO_Message *)msg, + NULL, + NULL); + } + else + { + GNUNET_STATISTICS_update( + stats, + gettext_noop("# invalid HELLOs downloaded from hostlist servers"), + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Invalid `%s' message received from hostlist at `%s'\n"), + "HELLO", + current_url); + stat_bogus_url = GNUNET_YES; + stat_hellos_obtained++; + return total; + } + memmove(download_buffer, &download_buffer[msize], download_pos - msize); + download_pos -= msize; } - memmove (download_buffer, &download_buffer[msize], download_pos - msize); - download_pos -= msize; - } return total; } @@ -423,63 +422,63 @@ callback_download (void *ptr, size_t size, size_t nmemb, void *ctx) * @return NULL if there is no URL available */ static char * -get_bootstrap_server () +get_bootstrap_server() { char *servers; char *ret; size_t urls; size_t pos; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "HOSTLIST", - "SERVERS", - &servers)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING, - "hostlist", - "SERVERS"); - return NULL; - } + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "HOSTLIST", + "SERVERS", + &servers)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_WARNING, + "hostlist", + "SERVERS"); + return NULL; + } urls = 0; - if (strlen (servers) > 0) - { - urls++; - pos = strlen (servers) - 1; - while (pos > 0) + if (strlen(servers) > 0) { - if (servers[pos] == ' ') - urls++; - pos--; + urls++; + pos = strlen(servers) - 1; + while (pos > 0) + { + if (servers[pos] == ' ') + urls++; + pos--; + } } - } if (urls == 0) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING, - "hostlist", - "SERVERS"); - GNUNET_free (servers); - return NULL; - } - - urls = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, urls) + 1; - pos = strlen (servers) - 1; - while (pos > 0) - { - if (servers[pos] == ' ') { - urls--; - servers[pos] = '\0'; + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_WARNING, + "hostlist", + "SERVERS"); + GNUNET_free(servers); + return NULL; } - if (urls == 0) + + urls = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, urls) + 1; + pos = strlen(servers) - 1; + while (pos > 0) { - pos++; - break; + if (servers[pos] == ' ') + { + urls--; + servers[pos] = '\0'; + } + if (urls == 0) + { + pos++; + break; + } + pos--; } - pos--; - } - ret = GNUNET_strdup (&servers[pos]); - GNUNET_free (servers); + ret = GNUNET_strdup(&servers[pos]); + GNUNET_free(servers); return ret; } @@ -489,64 +488,64 @@ get_bootstrap_server () * @return uri to use, NULL if there is no URL available */ static char * -download_get_url () +download_get_url() { uint32_t index; unsigned int counter; struct Hostlist *pos; if (GNUNET_NO == stat_learning) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Using preconfigured bootstrap server\n"); - current_hostlist = NULL; - return get_bootstrap_server (); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Using preconfigured bootstrap server\n"); + current_hostlist = NULL; + return get_bootstrap_server(); + } if ((GNUNET_YES == stat_testing_hostlist) && (NULL != hostlist_to_test)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing new advertised hostlist if it is obtainable\n"); - current_hostlist = hostlist_to_test; - return GNUNET_strdup (hostlist_to_test->hostlist_uri); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing new advertised hostlist if it is obtainable\n"); + current_hostlist = hostlist_to_test; + return GNUNET_strdup(hostlist_to_test->hostlist_uri); + } if ((GNUNET_YES == stat_use_bootstrap) || (linked_list_size == 0)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Using preconfigured bootstrap server\n"); - current_hostlist = NULL; - return get_bootstrap_server (); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Using preconfigured bootstrap server\n"); + current_hostlist = NULL; + return get_bootstrap_server(); + } index = - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, linked_list_size); + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, linked_list_size); counter = 0; pos = linked_list_head; while (counter < index) - { - pos = pos->next; - counter++; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Using learned hostlist `%s'\n", - pos->hostlist_uri); + { + pos = pos->next; + counter++; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Using learned hostlist `%s'\n", + pos->hostlist_uri); current_hostlist = pos; - return GNUNET_strdup (pos->hostlist_uri); + return GNUNET_strdup(pos->hostlist_uri); } #define CURL_EASY_SETOPT(c, a, b) \ do \ - { \ - ret = curl_easy_setopt (c, a, b); \ - if (CURLE_OK != ret) \ + { \ + ret = curl_easy_setopt(c, a, b); \ + if (CURLE_OK != ret) \ GNUNET_log (GNUNET_ERROR_TYPE_WARNING, \ - _ ("%s failed at %s:%d: `%s'\n"), \ + _("%s failed at %s:%d: `%s'\n"), \ "curl_easy_setopt", \ __FILE__, \ __LINE__, \ - curl_easy_strerror (ret)); \ - } while (0) + curl_easy_strerror(ret)); \ + } while (0) /** @@ -555,7 +554,7 @@ download_get_url () * @param shutdown set if called because of shutdown, entries in linked list will be destroyed */ static void -save_hostlist_file (int shutdown); +save_hostlist_file(int shutdown); /** @@ -566,7 +565,7 @@ save_hostlist_file (int shutdown); * @return result */ static uint64_t -checked_add (uint64_t val1, uint64_t val2) +checked_add(uint64_t val1, uint64_t val2) { static uint64_t temp; static uint64_t maxv; @@ -589,11 +588,11 @@ checked_add (uint64_t val1, uint64_t val2) * @return result */ static uint64_t -checked_sub (uint64_t val1, uint64_t val2) +checked_sub(uint64_t val1, uint64_t val2) { if (val1 <= val2) return 0; - return (val1 - val2); + return(val1 - val2); } @@ -604,17 +603,17 @@ checked_sub (uint64_t val1, uint64_t val2) * @return #GNUNET_YES if existing in linked list, #GNUNET_NO if not */ static int -linked_list_contains (const char *uri) +linked_list_contains(const char *uri) { struct Hostlist *pos; pos = linked_list_head; while (pos != NULL) - { - if (0 == strcmp (pos->hostlist_uri, uri)) - return GNUNET_YES; - pos = pos->next; - } + { + if (0 == strcmp(pos->hostlist_uri, uri)) + return GNUNET_YES; + pos = pos->next; + } return GNUNET_NO; } @@ -624,7 +623,7 @@ linked_list_contains (const char *uri) * @return hostlist with lowest quality */ static struct Hostlist * -linked_list_get_lowest_quality () +linked_list_get_lowest_quality() { struct Hostlist *pos; struct Hostlist *lowest; @@ -634,11 +633,11 @@ linked_list_get_lowest_quality () lowest = linked_list_head; pos = linked_list_head->next; while (pos != NULL) - { - if (pos->quality < lowest->quality) - lowest = pos; - pos = pos->next; - } + { + if (pos->quality < lowest->quality) + lowest = pos; + pos = pos->next; + } return lowest; } @@ -649,34 +648,34 @@ linked_list_get_lowest_quality () * quality is dismissed */ static void -insert_hostlist () +insert_hostlist() { struct Hostlist *lowest_quality; if (MAX_NUMBER_HOSTLISTS <= linked_list_size) - { - /* No free entries available, replace existing entry */ - lowest_quality = linked_list_get_lowest_quality (); - GNUNET_assert (lowest_quality != NULL); - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Removing hostlist with URI `%s' which has the worst quality of all (%llu)\n", - lowest_quality->hostlist_uri, - (unsigned long long) lowest_quality->quality); - GNUNET_CONTAINER_DLL_remove (linked_list_head, - linked_list_tail, - lowest_quality); - linked_list_size--; - GNUNET_free (lowest_quality); - } - GNUNET_CONTAINER_DLL_insert (linked_list_head, - linked_list_tail, - hostlist_to_test); + { + /* No free entries available, replace existing entry */ + lowest_quality = linked_list_get_lowest_quality(); + GNUNET_assert(lowest_quality != NULL); + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Removing hostlist with URI `%s' which has the worst quality of all (%llu)\n", + lowest_quality->hostlist_uri, + (unsigned long long)lowest_quality->quality); + GNUNET_CONTAINER_DLL_remove(linked_list_head, + linked_list_tail, + lowest_quality); + linked_list_size--; + GNUNET_free(lowest_quality); + } + GNUNET_CONTAINER_DLL_insert(linked_list_head, + linked_list_tail, + hostlist_to_test); linked_list_size++; - GNUNET_STATISTICS_set (stats, - gettext_noop ("# advertised hostlist URIs"), - linked_list_size, - GNUNET_NO); + GNUNET_STATISTICS_set(stats, + gettext_noop("# advertised hostlist URIs"), + linked_list_size, + GNUNET_NO); stat_testing_hostlist = GNUNET_NO; } @@ -685,37 +684,37 @@ insert_hostlist () * Method updating hostlist statistics */ static void -update_hostlist () +update_hostlist() { char *stat; if (((stat_use_bootstrap == GNUNET_NO) && (NULL != current_hostlist)) || ((stat_testing_hostlist == GNUNET_YES) && (NULL != current_hostlist))) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Updating hostlist statics for URI `%s'\n", - current_hostlist->hostlist_uri); - current_hostlist->hello_count = stat_hellos_obtained; - current_hostlist->time_last_usage = GNUNET_TIME_absolute_get (); - current_hostlist->quality = - checked_add (current_hostlist->quality, - (stat_hellos_obtained * HOSTLIST_SUCCESSFUL_HELLO)); - if (GNUNET_YES == stat_download_successful) { - current_hostlist->times_used++; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Updating hostlist statics for URI `%s'\n", + current_hostlist->hostlist_uri); + current_hostlist->hello_count = stat_hellos_obtained; + current_hostlist->time_last_usage = GNUNET_TIME_absolute_get(); current_hostlist->quality = - checked_add (current_hostlist->quality, HOSTLIST_SUCCESSFUL_DOWNLOAD); - GNUNET_asprintf (&stat, - gettext_noop ("# advertised URI `%s' downloaded"), - current_hostlist->hostlist_uri); - - GNUNET_STATISTICS_update (stats, stat, 1, GNUNET_YES); - GNUNET_free (stat); + checked_add(current_hostlist->quality, + (stat_hellos_obtained * HOSTLIST_SUCCESSFUL_HELLO)); + if (GNUNET_YES == stat_download_successful) + { + current_hostlist->times_used++; + current_hostlist->quality = + checked_add(current_hostlist->quality, HOSTLIST_SUCCESSFUL_DOWNLOAD); + GNUNET_asprintf(&stat, + gettext_noop("# advertised URI `%s' downloaded"), + current_hostlist->hostlist_uri); + + GNUNET_STATISTICS_update(stats, stat, 1, GNUNET_YES); + GNUNET_free(stat); + } + else + current_hostlist->quality = + checked_sub(current_hostlist->quality, HOSTLIST_FAILED_DOWNLOAD); } - else - current_hostlist->quality = - checked_sub (current_hostlist->quality, HOSTLIST_FAILED_DOWNLOAD); - } current_hostlist = NULL; /* Alternating the usage of preconfigured and learned hostlists */ @@ -723,12 +722,12 @@ update_hostlist () return; if (GNUNET_YES == stat_learning) - { - if (stat_use_bootstrap == GNUNET_YES) - stat_use_bootstrap = GNUNET_NO; - else - stat_use_bootstrap = GNUNET_YES; - } + { + if (stat_use_bootstrap == GNUNET_YES) + stat_use_bootstrap = GNUNET_NO; + else + stat_use_bootstrap = GNUNET_YES; + } else stat_use_bootstrap = GNUNET_YES; } @@ -739,58 +738,58 @@ update_hostlist () * hostlist and schedule the next task. */ static void -clean_up () +clean_up() { CURLMcode mret; if ((stat_testing_hostlist == GNUNET_YES) && (GNUNET_NO == stat_download_successful) && (NULL != hostlist_to_test)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_INFO, - _ ( - "Advertised hostlist with URI `%s' could not be downloaded. Advertised URI gets dismissed.\n"), - hostlist_to_test->hostlist_uri); - } + { + GNUNET_log( + GNUNET_ERROR_TYPE_INFO, + _( + "Advertised hostlist with URI `%s' could not be downloaded. Advertised URI gets dismissed.\n"), + hostlist_to_test->hostlist_uri); + } if (stat_testing_hostlist == GNUNET_YES) - { - stat_testing_hostlist = GNUNET_NO; - } + { + stat_testing_hostlist = GNUNET_NO; + } if (NULL != hostlist_to_test) - { - GNUNET_free (hostlist_to_test); - hostlist_to_test = NULL; - } + { + GNUNET_free(hostlist_to_test); + hostlist_to_test = NULL; + } if (NULL != multi) - { - mret = curl_multi_remove_handle (multi, curl); - if (mret != CURLM_OK) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("%s failed at %s:%d: `%s'\n"), - "curl_multi_remove_handle", - __FILE__, - __LINE__, - curl_multi_strerror (mret)); + mret = curl_multi_remove_handle(multi, curl); + if (mret != CURLM_OK) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("%s failed at %s:%d: `%s'\n"), + "curl_multi_remove_handle", + __FILE__, + __LINE__, + curl_multi_strerror(mret)); + } + mret = curl_multi_cleanup(multi); + if (mret != CURLM_OK) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("%s failed at %s:%d: `%s'\n"), + "curl_multi_cleanup", + __FILE__, + __LINE__, + curl_multi_strerror(mret)); + multi = NULL; } - mret = curl_multi_cleanup (multi); - if (mret != CURLM_OK) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("%s failed at %s:%d: `%s'\n"), - "curl_multi_cleanup", - __FILE__, - __LINE__, - curl_multi_strerror (mret)); - multi = NULL; - } if (NULL != curl) - { - curl_easy_cleanup (curl); - curl = NULL; - } - GNUNET_free_non_null (current_url); + { + curl_easy_cleanup(curl); + curl = NULL; + } + GNUNET_free_non_null(current_url); current_url = NULL; stat_bytes_downloaded = 0; stat_download_in_progress = GNUNET_NO; @@ -805,7 +804,7 @@ clean_up () * @param tc task context, unused */ static void -task_download (void *cls); +task_download(void *cls); /** @@ -813,7 +812,7 @@ task_download (void *cls); * receiving task with the scheduler. */ static void -download_prepare () +download_prepare() { CURLMcode mret; fd_set rs; @@ -826,50 +825,50 @@ download_prepare () struct GNUNET_TIME_Relative rtime; max = -1; - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); - mret = curl_multi_fdset (multi, &rs, &ws, &es, &max); + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); + mret = curl_multi_fdset(multi, &rs, &ws, &es, &max); if (mret != CURLM_OK) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("%s failed at %s:%d: `%s'\n"), - "curl_multi_fdset", - __FILE__, - __LINE__, - curl_multi_strerror (mret)); - clean_up (); - return; - } - mret = curl_multi_timeout (multi, &timeout); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("%s failed at %s:%d: `%s'\n"), + "curl_multi_fdset", + __FILE__, + __LINE__, + curl_multi_strerror(mret)); + clean_up(); + return; + } + mret = curl_multi_timeout(multi, &timeout); if (mret != CURLM_OK) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("%s failed at %s:%d: `%s'\n"), - "curl_multi_timeout", - __FILE__, - __LINE__, - curl_multi_strerror (mret)); - clean_up (); - return; - } - rtime = GNUNET_TIME_relative_min ( - GNUNET_TIME_absolute_get_remaining (end_time), - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, timeout)); - grs = GNUNET_NETWORK_fdset_create (); - gws = GNUNET_NETWORK_fdset_create (); - GNUNET_NETWORK_fdset_copy_native (grs, &rs, max + 1); - GNUNET_NETWORK_fdset_copy_native (gws, &ws, max + 1); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Scheduling task for hostlist download using cURL\n"); - ti_download = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, - rtime, - grs, - gws, - &task_download, - multi); - GNUNET_NETWORK_fdset_destroy (gws); - GNUNET_NETWORK_fdset_destroy (grs); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("%s failed at %s:%d: `%s'\n"), + "curl_multi_timeout", + __FILE__, + __LINE__, + curl_multi_strerror(mret)); + clean_up(); + return; + } + rtime = GNUNET_TIME_relative_min( + GNUNET_TIME_absolute_get_remaining(end_time), + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, timeout)); + grs = GNUNET_NETWORK_fdset_create(); + gws = GNUNET_NETWORK_fdset_create(); + GNUNET_NETWORK_fdset_copy_native(grs, &rs, max + 1); + GNUNET_NETWORK_fdset_copy_native(gws, &ws, max + 1); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Scheduling task for hostlist download using cURL\n"); + ti_download = GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT, + rtime, + grs, + gws, + &task_download, + multi); + GNUNET_NETWORK_fdset_destroy(gws); + GNUNET_NETWORK_fdset_destroy(grs); } @@ -880,93 +879,95 @@ download_prepare () * @param cls closure, unused */ static void -task_download (void *cls) +task_download(void *cls) { int running; struct CURLMsg *msg; CURLMcode mret; ti_download = NULL; - if (0 == GNUNET_TIME_absolute_get_remaining (end_time).rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Timeout trying to download hostlist from `%s'\n"), - current_url); - update_hostlist (); - clean_up (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Ready for processing hostlist client request\n"); - do - { - running = 0; - if (stat_bytes_downloaded > MAX_BYTES_PER_HOSTLISTS) + if (0 == GNUNET_TIME_absolute_get_remaining(end_time).rel_value_us) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ( - "Download limit of %u bytes exceeded, stopping download\n"), - MAX_BYTES_PER_HOSTLISTS); - clean_up (); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Timeout trying to download hostlist from `%s'\n"), + current_url); + update_hostlist(); + clean_up(); return; } - mret = curl_multi_perform (multi, &running); - if (running == 0) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Ready for processing hostlist client request\n"); + do { - do - { - msg = curl_multi_info_read (multi, &running); - GNUNET_break (msg != NULL); - if (msg == NULL) - break; - switch (msg->msg) + running = 0; + if (stat_bytes_downloaded > MAX_BYTES_PER_HOSTLISTS) { - case CURLMSG_DONE: - if ((msg->data.result != CURLE_OK) && - (msg->data.result != CURLE_GOT_NOTHING)) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Download of hostlist from `%s' failed: `%s'\n"), - current_url, - curl_easy_strerror (msg->data.result)); - else - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Download of hostlist `%s' completed.\n"), - current_url); - stat_download_successful = GNUNET_YES; - update_hostlist (); - if (GNUNET_YES == stat_testing_hostlist) + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _( + "Download limit of %u bytes exceeded, stopping download\n"), + MAX_BYTES_PER_HOSTLISTS); + clean_up(); + return; + } + mret = curl_multi_perform(multi, &running); + if (running == 0) + { + do { - GNUNET_log ( - GNUNET_ERROR_TYPE_INFO, - _ ("Adding successfully tested hostlist `%s' datastore.\n"), - current_url); - insert_hostlist (); - hostlist_to_test = NULL; - stat_testing_hostlist = GNUNET_NO; + msg = curl_multi_info_read(multi, &running); + GNUNET_break(msg != NULL); + if (msg == NULL) + break; + switch (msg->msg) + { + case CURLMSG_DONE: + if ((msg->data.result != CURLE_OK) && + (msg->data.result != CURLE_GOT_NOTHING)) + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Download of hostlist from `%s' failed: `%s'\n"), + current_url, + curl_easy_strerror(msg->data.result)); + else + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Download of hostlist `%s' completed.\n"), + current_url); + stat_download_successful = GNUNET_YES; + update_hostlist(); + if (GNUNET_YES == stat_testing_hostlist) + { + GNUNET_log( + GNUNET_ERROR_TYPE_INFO, + _("Adding successfully tested hostlist `%s' datastore.\n"), + current_url); + insert_hostlist(); + hostlist_to_test = NULL; + stat_testing_hostlist = GNUNET_NO; + } + } + clean_up(); + return; + + default: + break; + } } - } - clean_up (); - return; - default: - break; + while ((running > 0)); } - - } while ((running > 0)); } - } while (mret == CURLM_CALL_MULTI_PERFORM); + while (mret == CURLM_CALL_MULTI_PERFORM); if (mret != CURLM_OK) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("%s failed at %s:%d: `%s'\n"), - "curl_multi_perform", - __FILE__, - __LINE__, - curl_multi_strerror (mret)); - clean_up (); - } - download_prepare (); + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("%s failed at %s:%d: `%s'\n"), + "curl_multi_perform", + __FILE__, + __LINE__, + curl_multi_strerror(mret)); + clean_up(); + } + download_prepare(); } @@ -975,133 +976,133 @@ task_download (void *cls) * data. */ static void -download_hostlist () +download_hostlist() { CURLcode ret; CURLMcode mret; - current_url = download_get_url (); + current_url = download_get_url(); if (current_url == NULL) return; - curl = curl_easy_init (); + curl = curl_easy_init(); multi = NULL; if (curl == NULL) - { - GNUNET_break (0); - clean_up (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK, - _ ("Bootstrapping using hostlist at `%s'.\n"), - current_url); + { + GNUNET_break(0); + clean_up(); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK, + _("Bootstrapping using hostlist at `%s'.\n"), + current_url); stat_download_in_progress = GNUNET_YES; stat_download_successful = GNUNET_NO; stat_hellos_obtained = 0; stat_bytes_downloaded = 0; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# hostlist downloads initiated"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# hostlist downloads initiated"), + 1, + GNUNET_NO); if (NULL != proxy) - { - CURL_EASY_SETOPT (curl, CURLOPT_PROXY, proxy); - CURL_EASY_SETOPT (curl, CURLOPT_PROXYTYPE, proxy_type); - if (NULL != proxy_username) - CURL_EASY_SETOPT (curl, CURLOPT_PROXYUSERNAME, proxy_username); - if (NULL != proxy_password) - CURL_EASY_SETOPT (curl, CURLOPT_PROXYPASSWORD, proxy_password); - } + { + CURL_EASY_SETOPT(curl, CURLOPT_PROXY, proxy); + CURL_EASY_SETOPT(curl, CURLOPT_PROXYTYPE, proxy_type); + if (NULL != proxy_username) + CURL_EASY_SETOPT(curl, CURLOPT_PROXYUSERNAME, proxy_username); + if (NULL != proxy_password) + CURL_EASY_SETOPT(curl, CURLOPT_PROXYPASSWORD, proxy_password); + } download_pos = 0; stat_bogus_url = 0; - CURL_EASY_SETOPT (curl, CURLOPT_WRITEFUNCTION, &callback_download); + CURL_EASY_SETOPT(curl, CURLOPT_WRITEFUNCTION, &callback_download); if (ret != CURLE_OK) - { - clean_up (); - return; - } - CURL_EASY_SETOPT (curl, CURLOPT_WRITEDATA, NULL); + { + clean_up(); + return; + } + CURL_EASY_SETOPT(curl, CURLOPT_WRITEDATA, NULL); if (ret != CURLE_OK) - { - clean_up (); - return; - } - CURL_EASY_SETOPT (curl, CURLOPT_FOLLOWLOCATION, 1); - CURL_EASY_SETOPT (curl, - CURLOPT_REDIR_PROTOCOLS, - CURLPROTO_HTTP | CURLPROTO_HTTPS); - CURL_EASY_SETOPT (curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); - CURL_EASY_SETOPT (curl, CURLOPT_MAXREDIRS, 4); + { + clean_up(); + return; + } + CURL_EASY_SETOPT(curl, CURLOPT_FOLLOWLOCATION, 1); + CURL_EASY_SETOPT(curl, + CURLOPT_REDIR_PROTOCOLS, + CURLPROTO_HTTP | CURLPROTO_HTTPS); + CURL_EASY_SETOPT(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); + CURL_EASY_SETOPT(curl, CURLOPT_MAXREDIRS, 4); /* no need to abort if the above failed */ - CURL_EASY_SETOPT (curl, CURLOPT_URL, current_url); + CURL_EASY_SETOPT(curl, CURLOPT_URL, current_url); if (ret != CURLE_OK) - { - clean_up (); - return; - } - CURL_EASY_SETOPT (curl, CURLOPT_FAILONERROR, 1); + { + clean_up(); + return; + } + CURL_EASY_SETOPT(curl, CURLOPT_FAILONERROR, 1); #if 0 - CURL_EASY_SETOPT (curl, CURLOPT_VERBOSE, 1); + CURL_EASY_SETOPT(curl, CURLOPT_VERBOSE, 1); #endif - CURL_EASY_SETOPT (curl, CURLOPT_BUFFERSIZE, GNUNET_MAX_MESSAGE_SIZE); - if (0 == strncmp (current_url, "http", 4)) - CURL_EASY_SETOPT (curl, CURLOPT_USERAGENT, "GNUnet"); - CURL_EASY_SETOPT (curl, CURLOPT_CONNECTTIMEOUT, 60L); - CURL_EASY_SETOPT (curl, CURLOPT_TIMEOUT, 60L); - multi = curl_multi_init (); + CURL_EASY_SETOPT(curl, CURLOPT_BUFFERSIZE, GNUNET_MAX_MESSAGE_SIZE); + if (0 == strncmp(current_url, "http", 4)) + CURL_EASY_SETOPT(curl, CURLOPT_USERAGENT, "GNUnet"); + CURL_EASY_SETOPT(curl, CURLOPT_CONNECTTIMEOUT, 60L); + CURL_EASY_SETOPT(curl, CURLOPT_TIMEOUT, 60L); + multi = curl_multi_init(); if (multi == NULL) - { - GNUNET_break (0); - /* clean_up (); */ - return; - } - mret = curl_multi_add_handle (multi, curl); + { + GNUNET_break(0); + /* clean_up (); */ + return; + } + mret = curl_multi_add_handle(multi, curl); if (mret != CURLM_OK) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("%s failed at %s:%d: `%s'\n"), - "curl_multi_add_handle", - __FILE__, - __LINE__, - curl_multi_strerror (mret)); - mret = curl_multi_cleanup (multi); - if (mret != CURLM_OK) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("%s failed at %s:%d: `%s'\n"), - "curl_multi_cleanup", - __FILE__, - __LINE__, - curl_multi_strerror (mret)); - multi = NULL; - clean_up (); - return; - } - end_time = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES); - download_prepare (); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("%s failed at %s:%d: `%s'\n"), + "curl_multi_add_handle", + __FILE__, + __LINE__, + curl_multi_strerror(mret)); + mret = curl_multi_cleanup(multi); + if (mret != CURLM_OK) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("%s failed at %s:%d: `%s'\n"), + "curl_multi_cleanup", + __FILE__, + __LINE__, + curl_multi_strerror(mret)); + multi = NULL; + clean_up(); + return; + } + end_time = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_MINUTES); + download_prepare(); } static void -task_download_dispatcher (void *cls) +task_download_dispatcher(void *cls) { ti_download_dispatcher_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download is initiated...\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Download is initiated...\n"); if (GNUNET_NO == stat_download_in_progress) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download can start immediately...\n"); - download_hostlist (); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Download can start immediately...\n"); + download_hostlist(); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Download in progess, have to wait...\n"); - ti_download_dispatcher_task = - GNUNET_SCHEDULER_add_delayed (WAITING_INTERVAL, - &task_download_dispatcher, - NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Download in progess, have to wait...\n"); + ti_download_dispatcher_task = + GNUNET_SCHEDULER_add_delayed(WAITING_INTERVAL, + &task_download_dispatcher, + NULL); + } } @@ -1111,49 +1112,49 @@ task_download_dispatcher (void *cls) * this task again for a later time. */ static void -task_check (void *cls) +task_check(void *cls) { static int once; struct GNUNET_TIME_Relative delay; ti_check_download = NULL; if (stats == NULL) - { - curl_global_cleanup (); - return; /* in shutdown */ - } + { + curl_global_cleanup(); + return; /* in shutdown */ + } if ((stat_connection_count < MIN_CONNECTIONS) && (NULL == ti_download_dispatcher_task)) ti_download_dispatcher_task = - GNUNET_SCHEDULER_add_now (&task_download_dispatcher, NULL); + GNUNET_SCHEDULER_add_now(&task_download_dispatcher, NULL); delay = hostlist_delay; if (0 == hostlist_delay.rel_value_us) hostlist_delay = GNUNET_TIME_UNIT_SECONDS; else - hostlist_delay = GNUNET_TIME_relative_multiply (hostlist_delay, 2); + hostlist_delay = GNUNET_TIME_relative_multiply(hostlist_delay, 2); if (hostlist_delay.rel_value_us > GNUNET_TIME_UNIT_HOURS.rel_value_us * (1 + stat_connection_count)) hostlist_delay = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, - (1 + stat_connection_count)); - GNUNET_STATISTICS_set (stats, - gettext_noop ( - "# milliseconds between hostlist downloads"), - hostlist_delay.rel_value_us / 1000LL, - GNUNET_YES); + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_HOURS, + (1 + stat_connection_count)); + GNUNET_STATISTICS_set(stats, + gettext_noop( + "# milliseconds between hostlist downloads"), + hostlist_delay.rel_value_us / 1000LL, + GNUNET_YES); if (0 == once) - { - delay = GNUNET_TIME_UNIT_ZERO; - once = 1; - } - GNUNET_log ( + { + delay = GNUNET_TIME_UNIT_ZERO; + once = 1; + } + GNUNET_log( GNUNET_ERROR_TYPE_INFO, - _ ("Have %u/%u connections. Will consider downloading hostlist in %s\n"), + _("Have %u/%u connections. Will consider downloading hostlist in %s\n"), stat_connection_count, MIN_CONNECTIONS, - GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES)); - ti_check_download = GNUNET_SCHEDULER_add_delayed (delay, &task_check, NULL); + GNUNET_STRINGS_relative_time_to_string(delay, GNUNET_YES)); + ti_check_download = GNUNET_SCHEDULER_add_delayed(delay, &task_check, NULL); } @@ -1163,12 +1164,12 @@ task_check (void *cls) * @param cls closure */ static void -task_testing_intervall_reset (void *cls) +task_testing_intervall_reset(void *cls) { ti_testing_intervall_task = NULL; stat_testing_allowed = GNUNET_OK; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing new hostlist advertisements is allowed again\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing new hostlist advertisements is allowed again\n"); } @@ -1178,17 +1179,17 @@ task_testing_intervall_reset (void *cls) * @param cls closure */ static void -task_hostlist_saving (void *cls) +task_hostlist_saving(void *cls) { ti_saving_task = NULL; - save_hostlist_file (GNUNET_NO); + save_hostlist_file(GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Hostlists will be saved to file again in %s\n", - GNUNET_STRINGS_relative_time_to_string (SAVING_INTERVAL, - GNUNET_YES)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Hostlists will be saved to file again in %s\n", + GNUNET_STRINGS_relative_time_to_string(SAVING_INTERVAL, + GNUNET_YES)); ti_saving_task = - GNUNET_SCHEDULER_add_delayed (SAVING_INTERVAL, &task_hostlist_saving, NULL); + GNUNET_SCHEDULER_add_delayed(SAVING_INTERVAL, &task_hostlist_saving, NULL); } @@ -1200,16 +1201,16 @@ task_hostlist_saving (void *cls) * @param mq message queue for transmissions to @a peer */ static void * -handler_connect (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +handler_connect(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { - GNUNET_assert (stat_connection_count < UINT_MAX); + GNUNET_assert(stat_connection_count < UINT_MAX); stat_connection_count++; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# active connections"), - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# active connections"), + 1, + GNUNET_NO); return NULL; } @@ -1221,16 +1222,16 @@ handler_connect (void *cls, * @param peer peer identity this notification is about */ static void -handler_disconnect (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *internal_cls) +handler_disconnect(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *internal_cls) { - GNUNET_assert (stat_connection_count > 0); + GNUNET_assert(stat_connection_count > 0); stat_connection_count--; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# active connections"), - -1, - GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# active connections"), + -1, + GNUNET_NO); } @@ -1240,57 +1241,57 @@ handler_disconnect (void *cls, * @param uri the advertised URI */ static void -handler_advertisement (const char *uri) +handler_advertisement(const char *uri) { size_t uri_size; struct Hostlist *hostlist; - uri_size = strlen (uri) + 1; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Hostlist client recieved advertisement containing URI `%s'\n", - uri); - if (GNUNET_NO != linked_list_contains (uri)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "URI `%s' is already known\n", uri); - return; - } + uri_size = strlen(uri) + 1; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Hostlist client recieved advertisement containing URI `%s'\n", + uri); + if (GNUNET_NO != linked_list_contains(uri)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "URI `%s' is already known\n", uri); + return; + } if (GNUNET_NO == stat_testing_allowed) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Currently not accepting new advertisements: interval between to advertisements is not reached\n"); - return; - } + { + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Currently not accepting new advertisements: interval between to advertisements is not reached\n"); + return; + } if (GNUNET_YES == stat_testing_hostlist) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Currently not accepting new advertisements: we are already testing a hostlist\n"); - return; - } + { + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Currently not accepting new advertisements: we are already testing a hostlist\n"); + return; + } - hostlist = GNUNET_malloc (sizeof (struct Hostlist) + uri_size); - hostlist->hostlist_uri = (const char *) &hostlist[1]; - GNUNET_memcpy (&hostlist[1], uri, uri_size); - hostlist->time_creation = GNUNET_TIME_absolute_get (); + hostlist = GNUNET_malloc(sizeof(struct Hostlist) + uri_size); + hostlist->hostlist_uri = (const char *)&hostlist[1]; + GNUNET_memcpy(&hostlist[1], uri, uri_size); + hostlist->time_creation = GNUNET_TIME_absolute_get(); hostlist->quality = HOSTLIST_INITIAL; hostlist_to_test = hostlist; stat_testing_hostlist = GNUNET_YES; stat_testing_allowed = GNUNET_NO; ti_testing_intervall_task = - GNUNET_SCHEDULER_add_delayed (TESTING_INTERVAL, - &task_testing_intervall_reset, - NULL); + GNUNET_SCHEDULER_add_delayed(TESTING_INTERVAL, + &task_testing_intervall_reset, + NULL); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing new hostlist advertisements is locked for the next %s\n", - GNUNET_STRINGS_relative_time_to_string (TESTING_INTERVAL, - GNUNET_YES)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing new hostlist advertisements is locked for the next %s\n", + GNUNET_STRINGS_relative_time_to_string(TESTING_INTERVAL, + GNUNET_YES)); ti_download_dispatcher_task = - GNUNET_SCHEDULER_add_now (&task_download_dispatcher, NULL); + GNUNET_SCHEDULER_add_now(&task_download_dispatcher, NULL); } @@ -1303,18 +1304,18 @@ handler_advertisement (const char *uri) * successfully obtained, #GNUNET_SYSERR if not. */ static void -primary_task (void *cls, int success) +primary_task(void *cls, int success) { if (NULL != ti_check_download) - { - GNUNET_SCHEDULER_cancel (ti_check_download); - ti_check_download = NULL; - } + { + GNUNET_SCHEDULER_cancel(ti_check_download); + ti_check_download = NULL; + } sget = NULL; - GNUNET_assert (NULL != stats); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Statistics request done, scheduling hostlist download\n"); - ti_check_download = GNUNET_SCHEDULER_add_now (&task_check, NULL); + GNUNET_assert(NULL != stats); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Statistics request done, scheduling hostlist download\n"); + ti_check_download = GNUNET_SCHEDULER_add_now(&task_check, NULL); } @@ -1327,11 +1328,11 @@ primary_task (void *cls, int success) * successfully obtained, #GNUNET_SYSERR if not. */ static void -stat_timeout_task (void *cls) +stat_timeout_task(void *cls) { - GNUNET_STATISTICS_get_cancel (sget); + GNUNET_STATISTICS_get_cancel(sget); sget = NULL; - ti_check_download = GNUNET_SCHEDULER_add_now (&task_check, NULL); + ti_check_download = GNUNET_SCHEDULER_add_now(&task_check, NULL); } @@ -1345,17 +1346,17 @@ stat_timeout_task (void *cls) * @param is_persistent unused, will be #GNUNET_YES */ static int -process_stat (void *cls, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +process_stat(void *cls, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { hostlist_delay.rel_value_us = value * 1000LL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Initial time between hostlist downloads is %s\n", - GNUNET_STRINGS_relative_time_to_string (hostlist_delay, - GNUNET_YES)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Initial time between hostlist downloads is %s\n", + GNUNET_STRINGS_relative_time_to_string(hostlist_delay, + GNUNET_YES)); return GNUNET_OK; } @@ -1364,7 +1365,7 @@ process_stat (void *cls, * Method to load persistent hostlist file during hostlist client startup */ static void -load_hostlist_file () +load_hostlist_file() { char *filename; char *uri; @@ -1379,87 +1380,87 @@ load_hostlist_file () struct GNUNET_BIO_ReadHandle *rh; uri = NULL; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, - "HOSTLIST", - "HOSTLISTFILE", - &filename)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING, - "hostlist", - "HOSTLISTFILE"); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Loading saved hostlist entries from file `%s' \n"), - filename); - if (GNUNET_NO == GNUNET_DISK_file_test (filename)) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Hostlist file `%s' does not exist\n"), - filename); - GNUNET_free (filename); - return; - } + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(cfg, + "HOSTLIST", + "HOSTLISTFILE", + &filename)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_WARNING, + "hostlist", + "HOSTLISTFILE"); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Loading saved hostlist entries from file `%s' \n"), + filename); + if (GNUNET_NO == GNUNET_DISK_file_test(filename)) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Hostlist file `%s' does not exist\n"), + filename); + GNUNET_free(filename); + return; + } - rh = GNUNET_BIO_read_open (filename); + rh = GNUNET_BIO_read_open(filename); if (NULL == rh) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ( - "Could not open file `%s' for reading to load hostlists: %s\n"), - filename, - strerror (errno)); - GNUNET_free (filename); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _( + "Could not open file `%s' for reading to load hostlists: %s\n"), + filename, + strerror(errno)); + GNUNET_free(filename); + return; + } counter = 0; - while ((GNUNET_OK == GNUNET_BIO_read_string (rh, "url", &uri, MAX_URL_LEN)) && + while ((GNUNET_OK == GNUNET_BIO_read_string(rh, "url", &uri, MAX_URL_LEN)) && (NULL != uri) && - (GNUNET_OK == GNUNET_BIO_read_int32 (rh, ×_used)) && - (GNUNET_OK == GNUNET_BIO_read_int64 (rh, &quality)) && - (GNUNET_OK == GNUNET_BIO_read_int64 (rh, &last_used)) && - (GNUNET_OK == GNUNET_BIO_read_int64 (rh, &created)) && - (GNUNET_OK == GNUNET_BIO_read_int32 (rh, &hellos_returned))) - { - hostlist = GNUNET_malloc (sizeof (struct Hostlist) + strlen (uri) + 1); - hostlist->hello_count = hellos_returned; - hostlist->hostlist_uri = (const char *) &hostlist[1]; - GNUNET_memcpy (&hostlist[1], uri, strlen (uri) + 1); - hostlist->quality = quality; - hostlist->time_creation.abs_value_us = created; - hostlist->time_last_usage.abs_value_us = last_used; - GNUNET_CONTAINER_DLL_insert (linked_list_head, linked_list_tail, hostlist); - linked_list_size++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Added hostlist entry eith URI `%s' \n", - hostlist->hostlist_uri); - GNUNET_free (uri); - uri = NULL; - counter++; - if (counter >= MAX_NUMBER_HOSTLISTS) - break; - } - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("%u hostlist URIs loaded from file\n"), - counter); - GNUNET_STATISTICS_set (stats, - gettext_noop ("# hostlist URIs read from file"), - counter, - GNUNET_YES); - GNUNET_STATISTICS_set (stats, - gettext_noop ("# advertised hostlist URIs"), - linked_list_size, - GNUNET_NO); - - GNUNET_free_non_null (uri); + (GNUNET_OK == GNUNET_BIO_read_int32(rh, ×_used)) && + (GNUNET_OK == GNUNET_BIO_read_int64(rh, &quality)) && + (GNUNET_OK == GNUNET_BIO_read_int64(rh, &last_used)) && + (GNUNET_OK == GNUNET_BIO_read_int64(rh, &created)) && + (GNUNET_OK == GNUNET_BIO_read_int32(rh, &hellos_returned))) + { + hostlist = GNUNET_malloc(sizeof(struct Hostlist) + strlen(uri) + 1); + hostlist->hello_count = hellos_returned; + hostlist->hostlist_uri = (const char *)&hostlist[1]; + GNUNET_memcpy(&hostlist[1], uri, strlen(uri) + 1); + hostlist->quality = quality; + hostlist->time_creation.abs_value_us = created; + hostlist->time_last_usage.abs_value_us = last_used; + GNUNET_CONTAINER_DLL_insert(linked_list_head, linked_list_tail, hostlist); + linked_list_size++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Added hostlist entry eith URI `%s' \n", + hostlist->hostlist_uri); + GNUNET_free(uri); + uri = NULL; + counter++; + if (counter >= MAX_NUMBER_HOSTLISTS) + break; + } + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("%u hostlist URIs loaded from file\n"), + counter); + GNUNET_STATISTICS_set(stats, + gettext_noop("# hostlist URIs read from file"), + counter, + GNUNET_YES); + GNUNET_STATISTICS_set(stats, + gettext_noop("# advertised hostlist URIs"), + linked_list_size, + GNUNET_NO); + + GNUNET_free_non_null(uri); emsg = NULL; - (void) GNUNET_BIO_read_close (rh, &emsg); + (void)GNUNET_BIO_read_close(rh, &emsg); if (emsg != NULL) - GNUNET_free (emsg); - GNUNET_free (filename); + GNUNET_free(emsg); + GNUNET_free(filename); } @@ -1469,7 +1470,7 @@ load_hostlist_file () * @param shutdown set if called because of shutdown, entries in linked list will be destroyed */ static void -save_hostlist_file (int shutdown) +save_hostlist_file(int shutdown) { char *filename; struct Hostlist *pos; @@ -1477,80 +1478,80 @@ save_hostlist_file (int shutdown) int ok; uint32_t counter; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, - "HOSTLIST", - "HOSTLISTFILE", - &filename)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING, - "hostlist", - "HOSTLISTFILE"); - return; - } - if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename)) - { - GNUNET_free (filename); - return; - } - wh = GNUNET_BIO_write_open (filename); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(cfg, + "HOSTLIST", + "HOSTLISTFILE", + &filename)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_WARNING, + "hostlist", + "HOSTLISTFILE"); + return; + } + if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file(filename)) + { + GNUNET_free(filename); + return; + } + wh = GNUNET_BIO_write_open(filename); if (NULL == wh) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ( - "Could not open file `%s' for writing to save hostlists: %s\n"), - filename, - strerror (errno)); - GNUNET_free (filename); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Writing %u hostlist URIs to `%s'\n"), - linked_list_size, - filename); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _( + "Could not open file `%s' for writing to save hostlists: %s\n"), + filename, + strerror(errno)); + GNUNET_free(filename); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Writing %u hostlist URIs to `%s'\n"), + linked_list_size, + filename); /* add code to write hostlists to file using bio */ ok = GNUNET_YES; counter = 0; while (NULL != (pos = linked_list_head)) - { - if (GNUNET_YES == shutdown) { - GNUNET_CONTAINER_DLL_remove (linked_list_head, linked_list_tail, pos); - linked_list_size--; - } - if (GNUNET_YES == ok) - { - if ((GNUNET_OK != GNUNET_BIO_write_string (wh, pos->hostlist_uri)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, pos->times_used)) || - (GNUNET_OK != GNUNET_BIO_write_int64 (wh, pos->quality)) || - (GNUNET_OK != - GNUNET_BIO_write_int64 (wh, pos->time_last_usage.abs_value_us)) || - (GNUNET_OK != - GNUNET_BIO_write_int64 (wh, pos->time_creation.abs_value_us)) || - (GNUNET_OK != GNUNET_BIO_write_int32 (wh, pos->hello_count))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Error writing hostlist URIs to file `%s'\n"), - filename); - ok = GNUNET_NO; - } - } + if (GNUNET_YES == shutdown) + { + GNUNET_CONTAINER_DLL_remove(linked_list_head, linked_list_tail, pos); + linked_list_size--; + } + if (GNUNET_YES == ok) + { + if ((GNUNET_OK != GNUNET_BIO_write_string(wh, pos->hostlist_uri)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, pos->times_used)) || + (GNUNET_OK != GNUNET_BIO_write_int64(wh, pos->quality)) || + (GNUNET_OK != + GNUNET_BIO_write_int64(wh, pos->time_last_usage.abs_value_us)) || + (GNUNET_OK != + GNUNET_BIO_write_int64(wh, pos->time_creation.abs_value_us)) || + (GNUNET_OK != GNUNET_BIO_write_int32(wh, pos->hello_count))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Error writing hostlist URIs to file `%s'\n"), + filename); + ok = GNUNET_NO; + } + } - if (GNUNET_YES == shutdown) - GNUNET_free (pos); - counter++; - if (counter >= MAX_NUMBER_HOSTLISTS) - break; - } - GNUNET_STATISTICS_set (stats, - gettext_noop ("# hostlist URIs written to file"), - counter, - GNUNET_YES); - - if (GNUNET_OK != GNUNET_BIO_write_close (wh)) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Error writing hostlist URIs to file `%s'\n"), - filename); - GNUNET_free (filename); + if (GNUNET_YES == shutdown) + GNUNET_free(pos); + counter++; + if (counter >= MAX_NUMBER_HOSTLISTS) + break; + } + GNUNET_STATISTICS_set(stats, + gettext_noop("# hostlist URIs written to file"), + counter, + GNUNET_YES); + + if (GNUNET_OK != GNUNET_BIO_write_close(wh)) + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Error writing hostlist URIs to file `%s'\n"), + filename); + GNUNET_free(filename); } @@ -1566,94 +1567,94 @@ save_hostlist_file (int shutdown) * @return #GNUNET_OK on success */ int -GNUNET_HOSTLIST_client_start (const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_STATISTICS_Handle *st, - GNUNET_CORE_ConnectEventHandler *ch, - GNUNET_CORE_DisconnectEventHandler *dh, - GNUNET_HOSTLIST_UriHandler *msgh, - int learn) +GNUNET_HOSTLIST_client_start(const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_STATISTICS_Handle *st, + GNUNET_CORE_ConnectEventHandler *ch, + GNUNET_CORE_DisconnectEventHandler *dh, + GNUNET_HOSTLIST_UriHandler *msgh, + int learn) { char *filename; char *proxytype_str; int result; - GNUNET_assert (NULL != st); - if (0 != curl_global_init (CURL_GLOBAL_WIN32)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + GNUNET_assert(NULL != st); + if (0 != curl_global_init(CURL_GLOBAL_WIN32)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } cfg = c; stats = st; /* Read proxy configuration */ - pi = GNUNET_PEERINFO_connect (c); + pi = GNUNET_PEERINFO_connect(c); if (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (cfg, "HOSTLIST", "PROXY", &proxy)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found proxy host: `%s'\n", proxy); - /* proxy username */ - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, - "HOSTLIST", - "PROXY_USERNAME", - &proxy_username)) + GNUNET_CONFIGURATION_get_value_string(cfg, "HOSTLIST", "PROXY", &proxy)) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found proxy username name: `%s'\n", - proxy_username); - } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Found proxy host: `%s'\n", proxy); + /* proxy username */ + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, + "HOSTLIST", + "PROXY_USERNAME", + &proxy_username)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found proxy username name: `%s'\n", + proxy_username); + } - /* proxy password */ - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, - "HOSTLIST", - "PROXY_PASSWORD", - &proxy_password)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found proxy password name: `%s'\n", - proxy_password); - } + /* proxy password */ + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, + "HOSTLIST", + "PROXY_PASSWORD", + &proxy_password)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found proxy password name: `%s'\n", + proxy_password); + } - /* proxy type */ - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, - "HOSTLIST", - "PROXY_TYPE", - &proxytype_str)) - { - GNUNET_STRINGS_utf8_toupper (proxytype_str, proxytype_str); - proxy_type = CURLPROXY_HTTP; - if (0 == strcmp (proxytype_str, "HTTP")) - proxy_type = CURLPROXY_HTTP; - else if (0 == strcmp (proxytype_str, "HTTP_1_0")) - proxy_type = CURLPROXY_HTTP_1_0; - else if (0 == strcmp (proxytype_str, "SOCKS4")) - proxy_type = CURLPROXY_SOCKS4; - else if (0 == strcmp (proxytype_str, "SOCKS5")) - proxy_type = CURLPROXY_SOCKS5; - else if (0 == strcmp (proxytype_str, "SOCKS4A")) - proxy_type = CURLPROXY_SOCKS4A; - else if (0 == strcmp (proxytype_str, "SOCKS5_HOSTNAME")) - proxy_type = CURLPROXY_SOCKS5_HOSTNAME; - else - { - GNUNET_log ( - GNUNET_ERROR_TYPE_ERROR, - _ ( - "Invalid proxy type: `%s', disabling proxy! Check configuration!\n"), - proxytype_str); - GNUNET_free (proxytype_str); - GNUNET_free (proxy); - proxy = NULL; - GNUNET_free_non_null (proxy_username); - proxy_username = NULL; - GNUNET_free_non_null (proxy_password); - proxy_password = NULL; - - return GNUNET_SYSERR; - } + /* proxy type */ + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, + "HOSTLIST", + "PROXY_TYPE", + &proxytype_str)) + { + GNUNET_STRINGS_utf8_toupper(proxytype_str, proxytype_str); + proxy_type = CURLPROXY_HTTP; + if (0 == strcmp(proxytype_str, "HTTP")) + proxy_type = CURLPROXY_HTTP; + else if (0 == strcmp(proxytype_str, "HTTP_1_0")) + proxy_type = CURLPROXY_HTTP_1_0; + else if (0 == strcmp(proxytype_str, "SOCKS4")) + proxy_type = CURLPROXY_SOCKS4; + else if (0 == strcmp(proxytype_str, "SOCKS5")) + proxy_type = CURLPROXY_SOCKS5; + else if (0 == strcmp(proxytype_str, "SOCKS4A")) + proxy_type = CURLPROXY_SOCKS4A; + else if (0 == strcmp(proxytype_str, "SOCKS5_HOSTNAME")) + proxy_type = CURLPROXY_SOCKS5_HOSTNAME; + else + { + GNUNET_log( + GNUNET_ERROR_TYPE_ERROR, + _( + "Invalid proxy type: `%s', disabling proxy! Check configuration!\n"), + proxytype_str); + GNUNET_free(proxytype_str); + GNUNET_free(proxy); + proxy = NULL; + GNUNET_free_non_null(proxy_username); + proxy_username = NULL; + GNUNET_free_non_null(proxy_password); + proxy_password = NULL; + + return GNUNET_SYSERR; + } + } + GNUNET_free_non_null(proxytype_str); } - GNUNET_free_non_null (proxytype_str); - } stat_learning = learn; *ch = &handler_connect; @@ -1665,67 +1666,67 @@ GNUNET_HOSTLIST_client_start (const struct GNUNET_CONFIGURATION_Handle *c, stat_testing_allowed = GNUNET_YES; if (GNUNET_YES == stat_learning) - { - *msgh = &handler_advertisement; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Learning is enabled on this peer\n")); - load_hostlist_file (); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Hostlists will be saved to file again in %s\n", - GNUNET_STRINGS_relative_time_to_string (SAVING_INTERVAL, + { + *msgh = &handler_advertisement; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Learning is enabled on this peer\n")); + load_hostlist_file(); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Hostlists will be saved to file again in %s\n", + GNUNET_STRINGS_relative_time_to_string(SAVING_INTERVAL, GNUNET_YES)); - ti_saving_task = GNUNET_SCHEDULER_add_delayed (SAVING_INTERVAL, - &task_hostlist_saving, - NULL); - } + ti_saving_task = GNUNET_SCHEDULER_add_delayed(SAVING_INTERVAL, + &task_hostlist_saving, + NULL); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Learning is not enabled on this peer\n")); - *msgh = NULL; - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_filename (cfg, - "HOSTLIST", - "HOSTLISTFILE", - &filename)) { - if (GNUNET_YES == GNUNET_DISK_file_test (filename)) - { - result = remove (filename); - if (0 == result) - GNUNET_log ( - GNUNET_ERROR_TYPE_INFO, - _ ( - "Since learning is not enabled on this peer, hostlist file `%s' was removed\n"), - filename); - else - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, - "remove", - filename); - } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Learning is not enabled on this peer\n")); + *msgh = NULL; + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_filename(cfg, + "HOSTLIST", + "HOSTLISTFILE", + &filename)) + { + if (GNUNET_YES == GNUNET_DISK_file_test(filename)) + { + result = remove(filename); + if (0 == result) + GNUNET_log( + GNUNET_ERROR_TYPE_INFO, + _( + "Since learning is not enabled on this peer, hostlist file `%s' was removed\n"), + filename); + else + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, + "remove", + filename); + } + } + GNUNET_free(filename); } - GNUNET_free (filename); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Loading stats value on hostlist download frequency\n"); - sget = GNUNET_STATISTICS_get (stats, - "hostlist", - gettext_noop ( - "# milliseconds between hostlist downloads"), - &primary_task, - &process_stat, - NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Loading stats value on hostlist download frequency\n"); + sget = GNUNET_STATISTICS_get(stats, + "hostlist", + gettext_noop( + "# milliseconds between hostlist downloads"), + &primary_task, + &process_stat, + NULL); if (NULL == sget) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Statistics request failed, scheduling hostlist download\n"); - ti_check_download = GNUNET_SCHEDULER_add_now (&task_check, NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Statistics request failed, scheduling hostlist download\n"); + ti_check_download = GNUNET_SCHEDULER_add_now(&task_check, NULL); + } else - { - ti_check_download = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, - &stat_timeout_task, - NULL); - } + { + ti_check_download = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES, + &stat_timeout_task, + NULL); + } return GNUNET_OK; } @@ -1734,56 +1735,56 @@ GNUNET_HOSTLIST_client_start (const struct GNUNET_CONFIGURATION_Handle *c, * Stop downloading hostlists from hostlist servers as necessary. */ void -GNUNET_HOSTLIST_client_stop () +GNUNET_HOSTLIST_client_stop() { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Hostlist client shutdown\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Hostlist client shutdown\n"); if (NULL != sget) - { - GNUNET_STATISTICS_get_cancel (sget); - sget = NULL; - } + { + GNUNET_STATISTICS_get_cancel(sget); + sget = NULL; + } stats = NULL; if (GNUNET_YES == stat_learning) - save_hostlist_file (GNUNET_YES); + save_hostlist_file(GNUNET_YES); if (NULL != ti_saving_task) - { - GNUNET_SCHEDULER_cancel (ti_saving_task); - ti_saving_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(ti_saving_task); + ti_saving_task = NULL; + } if (NULL != ti_download_dispatcher_task) - { - GNUNET_SCHEDULER_cancel (ti_download_dispatcher_task); - ti_download_dispatcher_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(ti_download_dispatcher_task); + ti_download_dispatcher_task = NULL; + } if (NULL != ti_testing_intervall_task) - { - GNUNET_SCHEDULER_cancel (ti_testing_intervall_task); - ti_testing_intervall_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(ti_testing_intervall_task); + ti_testing_intervall_task = NULL; + } if (NULL != ti_download) - { - GNUNET_SCHEDULER_cancel (ti_download); - ti_download = NULL; - update_hostlist (); - clean_up (); - } + { + GNUNET_SCHEDULER_cancel(ti_download); + ti_download = NULL; + update_hostlist(); + clean_up(); + } if (NULL != ti_check_download) - { - GNUNET_SCHEDULER_cancel (ti_check_download); - ti_check_download = NULL; - curl_global_cleanup (); - } - GNUNET_free_non_null (proxy); + { + GNUNET_SCHEDULER_cancel(ti_check_download); + ti_check_download = NULL; + curl_global_cleanup(); + } + GNUNET_free_non_null(proxy); proxy = NULL; - GNUNET_free_non_null (proxy_username); + GNUNET_free_non_null(proxy_username); proxy_username = NULL; - GNUNET_free_non_null (proxy_password); + GNUNET_free_non_null(proxy_password); proxy_password = NULL; if (NULL != pi) - { - GNUNET_PEERINFO_disconnect (pi); - pi = NULL; - } + { + GNUNET_PEERINFO_disconnect(pi); + pi = NULL; + } cfg = NULL; } diff --git a/src/hostlist/gnunet-daemon-hostlist_client.h b/src/hostlist/gnunet-daemon-hostlist_client.h index 8ac5bdb58..4268b26dd 100644 --- a/src/hostlist/gnunet-daemon-hostlist_client.h +++ b/src/hostlist/gnunet-daemon-hostlist_client.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hostlist/gnunet-daemon-hostlist_client.h * @brief hostlist support. Downloads HELLOs via HTTP. @@ -51,19 +51,19 @@ typedef void * @return #GNUNET_OK on success */ int -GNUNET_HOSTLIST_client_start (const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_STATISTICS_Handle *st, - GNUNET_CORE_ConnectEventHandler *ch, - GNUNET_CORE_DisconnectEventHandler *dh, - GNUNET_HOSTLIST_UriHandler *msgh, - int learn); +GNUNET_HOSTLIST_client_start(const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_STATISTICS_Handle *st, + GNUNET_CORE_ConnectEventHandler *ch, + GNUNET_CORE_DisconnectEventHandler *dh, + GNUNET_HOSTLIST_UriHandler *msgh, + int learn); /** * Stop downloading hostlists from hostlist servers as necessary. */ void -GNUNET_HOSTLIST_client_stop (void); +GNUNET_HOSTLIST_client_stop(void); #endif diff --git a/src/hostlist/gnunet-daemon-hostlist_server.c b/src/hostlist/gnunet-daemon-hostlist_server.c index 8764586d6..b4e0df34e 100644 --- a/src/hostlist/gnunet-daemon-hostlist_server.c +++ b/src/hostlist/gnunet-daemon-hostlist_server.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hostlist/gnunet-daemon-hostlist_server.c @@ -39,7 +39,7 @@ * time out? */ #define GNUNET_ADV_TIMEOUT \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5) /** @@ -106,8 +106,7 @@ static char *hostlist_uri; /** * Context for #host_processor(). */ -struct HostSet -{ +struct HostSet { /** * Iterator used to build @e data (NULL when done). */ @@ -138,13 +137,13 @@ static struct HostSet *builder; * @param response response to add headers to */ static void -add_cors_headers (struct MHD_Response *response) +add_cors_headers(struct MHD_Response *response) { - MHD_add_response_header (response, "Access-Control-Allow-Origin", "*"); - MHD_add_response_header (response, - "Access-Control-Allow-Methods", - "GET, OPTIONS"); - MHD_add_response_header (response, "Access-Control-Max-Age", "86400"); + MHD_add_response_header(response, "Access-Control-Allow-Origin", "*"); + MHD_add_response_header(response, + "Access-Control-Allow-Methods", + "GET, OPTIONS"); + MHD_add_response_header(response, "Access-Control-Max-Age", "86400"); } @@ -152,27 +151,27 @@ add_cors_headers (struct MHD_Response *response) * Function that assembles our response. */ static void -finish_response () +finish_response() { if (NULL != response) - MHD_destroy_response (response); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Creating hostlist response with %u bytes\n", - (unsigned int) builder->size); - response = MHD_create_response_from_buffer (builder->size, - builder->data, - MHD_RESPMEM_MUST_FREE); - add_cors_headers (response); + MHD_destroy_response(response); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Creating hostlist response with %u bytes\n", + (unsigned int)builder->size); + response = MHD_create_response_from_buffer(builder->size, + builder->data, + MHD_RESPMEM_MUST_FREE); + add_cors_headers(response); if ((NULL == daemon_handle_v4) && (NULL == daemon_handle_v6)) - { - MHD_destroy_response (response); - response = NULL; - } - GNUNET_STATISTICS_set (stats, - gettext_noop ("bytes in hostlist"), - builder->size, - GNUNET_YES); - GNUNET_free (builder); + { + MHD_destroy_response(response); + response = NULL; + } + GNUNET_STATISTICS_set(stats, + gettext_noop("bytes in hostlist"), + builder->size, + GNUNET_YES); + GNUNET_free(builder); builder = NULL; } @@ -186,20 +185,20 @@ finish_response () * @return #GNUNET_SYSERR to stop iterating (unless expiration has occured) */ static int -check_has_addr (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +check_has_addr(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { int *arg = cls; - if (0 == GNUNET_TIME_absolute_get_remaining (expiration).rel_value_us) - { - GNUNET_STATISTICS_update (stats, - gettext_noop ("expired addresses encountered"), - 1, - GNUNET_YES); - return GNUNET_YES; /* ignore this address */ - } + if (0 == GNUNET_TIME_absolute_get_remaining(expiration).rel_value_us) + { + GNUNET_STATISTICS_update(stats, + gettext_noop("expired addresses encountered"), + 1, + GNUNET_YES); + return GNUNET_YES; /* ignore this address */ + } *arg = GNUNET_YES; return GNUNET_SYSERR; } @@ -215,73 +214,73 @@ check_has_addr (void *cls, * @param err_msg message */ static void -host_processor (void *cls, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello, - const char *err_msg) +host_processor(void *cls, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello, + const char *err_msg) { size_t old; size_t s; int has_addr; if (NULL != err_msg) - { - GNUNET_assert (NULL == peer); - builder->pitr = NULL; - GNUNET_free_non_null (builder->data); - GNUNET_free (builder); - builder = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Error in communication with PEERINFO service: %s\n"), - err_msg); - return; - } + { + GNUNET_assert(NULL == peer); + builder->pitr = NULL; + GNUNET_free_non_null(builder->data); + GNUNET_free(builder); + builder = NULL; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Error in communication with PEERINFO service: %s\n"), + err_msg); + return; + } if (NULL == peer) - { - builder->pitr = NULL; - finish_response (); - return; - } + { + builder->pitr = NULL; + finish_response(); + return; + } if (NULL == hello) return; has_addr = GNUNET_NO; - GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &check_has_addr, &has_addr); + GNUNET_HELLO_iterate_addresses(hello, GNUNET_NO, &check_has_addr, &has_addr); if (GNUNET_NO == has_addr) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "HELLO for peer `%4s' has no address, not suitable for hostlist!\n", - GNUNET_i2s (peer)); - GNUNET_STATISTICS_update (stats, - gettext_noop ( - "HELLOs without addresses encountered (ignored)"), - 1, - GNUNET_NO); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "HELLO for peer `%4s' has no address, not suitable for hostlist!\n", + GNUNET_i2s(peer)); + GNUNET_STATISTICS_update(stats, + gettext_noop( + "HELLOs without addresses encountered (ignored)"), + 1, + GNUNET_NO); + return; + } old = builder->size; - s = GNUNET_HELLO_size (hello); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received %u bytes of `%s' from peer `%s' for hostlist.\n", - (unsigned int) s, - "HELLO", - GNUNET_i2s (peer)); + s = GNUNET_HELLO_size(hello); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received %u bytes of `%s' from peer `%s' for hostlist.\n", + (unsigned int)s, + "HELLO", + GNUNET_i2s(peer)); if ((old + s >= GNUNET_MAX_MALLOC_CHECKED) || (old + s >= MAX_BYTES_PER_HOSTLISTS)) - { - /* too large, skip! */ - GNUNET_STATISTICS_update (stats, - gettext_noop ( - "bytes not included in hostlist (size limit)"), - s, - GNUNET_NO); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Adding peer `%s' to hostlist (%u bytes)\n", - GNUNET_i2s (peer), - (unsigned int) s); - GNUNET_array_grow (builder->data, builder->size, old + s); - GNUNET_memcpy (&builder->data[old], hello, s); + { + /* too large, skip! */ + GNUNET_STATISTICS_update(stats, + gettext_noop( + "bytes not included in hostlist (size limit)"), + s, + GNUNET_NO); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Adding peer `%s' to hostlist (%u bytes)\n", + GNUNET_i2s(peer), + (unsigned int)s); + GNUNET_array_grow(builder->data, builder->size, old + s); + GNUNET_memcpy(&builder->data[old], hello, s); } @@ -295,17 +294,17 @@ host_processor (void *cls, * @return #MHD_YES if connection is allowed, #MHD_NO if not (we are not ready) */ static int -accept_policy_callback (void *cls, - const struct sockaddr *addr, - socklen_t addrlen) +accept_policy_callback(void *cls, + const struct sockaddr *addr, + socklen_t addrlen) { if (NULL == response) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Received request for hostlist, but I am not yet ready; rejecting!\n"); - return MHD_NO; - } + { + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Received request for hostlist, but I am not yet ready; rejecting!\n"); + return MHD_NO; + } return MHD_YES; /* accept all */ } @@ -346,80 +345,80 @@ accept_policy_callback (void *cls, * error while handling the request */ static int -access_handler_callback (void *cls, - struct MHD_Connection *connection, - const char *url, - const char *method, - const char *version, - const char *upload_data, - size_t *upload_data_size, - void **con_cls) +access_handler_callback(void *cls, + struct MHD_Connection *connection, + const char *url, + const char *method, + const char *version, + const char *upload_data, + size_t *upload_data_size, + void **con_cls) { static int dummy; /* CORS pre-flight request */ - if (0 == strcmp (MHD_HTTP_METHOD_OPTIONS, method)) - { - struct MHD_Response *options_response; - int rc; - - options_response = - MHD_create_response_from_buffer (0, NULL, MHD_RESPMEM_PERSISTENT); - add_cors_headers (options_response); - rc = MHD_queue_response (connection, MHD_HTTP_OK, options_response); - MHD_destroy_response (options_response); - return rc; - } - if (0 != strcmp (method, MHD_HTTP_METHOD_GET)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Refusing `%s' request to hostlist server\n"), - method); - GNUNET_STATISTICS_update (stats, - gettext_noop ( - "hostlist requests refused (not HTTP GET)"), - 1, - GNUNET_YES); - return MHD_NO; - } + if (0 == strcmp(MHD_HTTP_METHOD_OPTIONS, method)) + { + struct MHD_Response *options_response; + int rc; + + options_response = + MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT); + add_cors_headers(options_response); + rc = MHD_queue_response(connection, MHD_HTTP_OK, options_response); + MHD_destroy_response(options_response); + return rc; + } + if (0 != strcmp(method, MHD_HTTP_METHOD_GET)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Refusing `%s' request to hostlist server\n"), + method); + GNUNET_STATISTICS_update(stats, + gettext_noop( + "hostlist requests refused (not HTTP GET)"), + 1, + GNUNET_YES); + return MHD_NO; + } if (NULL == *con_cls) - { - (*con_cls) = &dummy; - return MHD_YES; - } + { + (*con_cls) = &dummy; + return MHD_YES; + } if (0 != *upload_data_size) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Refusing `%s' request with %llu bytes of upload data\n"), - method, - (unsigned long long) *upload_data_size); - GNUNET_STATISTICS_update (stats, - gettext_noop ( - "hostlist requests refused (upload data)"), - 1, - GNUNET_YES); - return MHD_NO; /* do not support upload data */ - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Refusing `%s' request with %llu bytes of upload data\n"), + method, + (unsigned long long)*upload_data_size); + GNUNET_STATISTICS_update(stats, + gettext_noop( + "hostlist requests refused (upload data)"), + 1, + GNUNET_YES); + return MHD_NO; /* do not support upload data */ + } if (NULL == response) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_WARNING, - _ ( - "Could not handle hostlist request since I do not have a response yet\n")); - GNUNET_STATISTICS_update (stats, - gettext_noop ( - "hostlist requests refused (not ready)"), - 1, - GNUNET_YES); - return MHD_NO; /* internal error, no response yet */ - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Received request for our hostlist\n")); - GNUNET_STATISTICS_update (stats, - gettext_noop ("hostlist requests processed"), - 1, - GNUNET_YES); - return MHD_queue_response (connection, MHD_HTTP_OK, response); + { + GNUNET_log( + GNUNET_ERROR_TYPE_WARNING, + _( + "Could not handle hostlist request since I do not have a response yet\n")); + GNUNET_STATISTICS_update(stats, + gettext_noop( + "hostlist requests refused (not ready)"), + 1, + GNUNET_YES); + return MHD_NO; /* internal error, no response yet */ + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Received request for our hostlist\n")); + GNUNET_STATISTICS_update(stats, + gettext_noop("hostlist requests processed"), + 1, + GNUNET_YES); + return MHD_queue_response(connection, MHD_HTTP_OK, response); } @@ -433,33 +432,33 @@ access_handler_callback (void *cls, * @return number of bytes copied to @a buf */ static void -adv_transmit (struct GNUNET_MQ_Handle *mq) +adv_transmit(struct GNUNET_MQ_Handle *mq) { static uint64_t hostlist_adv_count; size_t uri_size; /* Including \0 termination! */ struct GNUNET_MessageHeader *header; struct GNUNET_MQ_Envelope *env; - uri_size = strlen (hostlist_uri) + 1; - env = GNUNET_MQ_msg_extra (header, - uri_size, - GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT); - GNUNET_memcpy (&header[1], hostlist_uri, uri_size); - GNUNET_MQ_env_set_options (env, - GNUNET_MQ_PREF_CORK_ALLOWED | - GNUNET_MQ_PREF_UNRELIABLE); - GNUNET_MQ_send (mq, env); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sent advertisement message: Copied %u bytes into buffer!\n", - (unsigned int) uri_size); + uri_size = strlen(hostlist_uri) + 1; + env = GNUNET_MQ_msg_extra(header, + uri_size, + GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT); + GNUNET_memcpy(&header[1], hostlist_uri, uri_size); + GNUNET_MQ_env_set_options(env, + GNUNET_MQ_PREF_CORK_ALLOWED | + GNUNET_MQ_PREF_UNRELIABLE); + GNUNET_MQ_send(mq, env); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sent advertisement message: Copied %u bytes into buffer!\n", + (unsigned int)uri_size); hostlist_adv_count++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - " # Sent advertisement message: %llu\n", - (unsigned long long) hostlist_adv_count); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# hostlist advertisements send"), - 1, - GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + " # Sent advertisement message: %llu\n", + (unsigned long long)hostlist_adv_count); + GNUNET_STATISTICS_update(stats, + gettext_noop("# hostlist advertisements send"), + 1, + GNUNET_NO); } @@ -472,34 +471,34 @@ adv_transmit (struct GNUNET_MQ_Handle *mq) * @return NULL (must!) */ static void * -connect_handler (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +connect_handler(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { size_t size; - if (! advertising) + if (!advertising) return NULL; if (NULL == hostlist_uri) return NULL; - size = strlen (hostlist_uri) + 1; - if (size + sizeof (struct GNUNET_MessageHeader) >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return NULL; - } - size += sizeof (struct GNUNET_MessageHeader); + size = strlen(hostlist_uri) + 1; + if (size + sizeof(struct GNUNET_MessageHeader) >= GNUNET_MAX_MESSAGE_SIZE) + { + GNUNET_break(0); + return NULL; + } + size += sizeof(struct GNUNET_MessageHeader); if (NULL == core) - { - GNUNET_break (0); - return NULL; - } - GNUNET_log ( + { + GNUNET_break(0); + return NULL; + } + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "Asked CORE to transmit advertisement message with a size of %u bytes to peer `%s'\n", - (unsigned int) size, - GNUNET_i2s (peer)); - adv_transmit (mq); + (unsigned int)size, + GNUNET_i2s(peer)); + adv_transmit(mq); return NULL; } @@ -514,36 +513,36 @@ connect_handler (void *cls, * @param err_msg NULL if successful, otherwise contains error message */ static void -process_notify (void *cls, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello, - const char *err_msg) +process_notify(void *cls, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello, + const char *err_msg) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Peerinfo is notifying us to rebuild our hostlist\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Peerinfo is notifying us to rebuild our hostlist\n"); if (NULL != err_msg) - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Error in communication with PEERINFO service: %s\n"), - err_msg); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Error in communication with PEERINFO service: %s\n"), + err_msg); if (NULL != builder) - { - /* restart re-build already in progress ... */ - if (NULL != builder->pitr) { - GNUNET_PEERINFO_iterate_cancel (builder->pitr); - builder->pitr = NULL; + /* restart re-build already in progress ... */ + if (NULL != builder->pitr) + { + GNUNET_PEERINFO_iterate_cancel(builder->pitr); + builder->pitr = NULL; + } + GNUNET_free_non_null(builder->data); + builder->size = 0; + builder->data = NULL; } - GNUNET_free_non_null (builder->data); - builder->size = 0; - builder->data = NULL; - } else - { - builder = GNUNET_new (struct HostSet); - } - GNUNET_assert (NULL != peerinfo); + { + builder = GNUNET_new(struct HostSet); + } + GNUNET_assert(NULL != peerinfo); builder->pitr = - GNUNET_PEERINFO_iterate (peerinfo, GNUNET_NO, NULL, &host_processor, NULL); + GNUNET_PEERINFO_iterate(peerinfo, GNUNET_NO, NULL, &host_processor, NULL); } @@ -552,7 +551,7 @@ process_notify (void *cls, * starts the task waiting for them. */ static struct GNUNET_SCHEDULER_Task * -prepare_daemon (struct MHD_Daemon *daemon_handle); +prepare_daemon(struct MHD_Daemon *daemon_handle); /** @@ -562,7 +561,7 @@ prepare_daemon (struct MHD_Daemon *daemon_handle); * @param cls the `struct MHD_Daemon` of the HTTP server to run */ static void -run_daemon (void *cls) +run_daemon(void *cls) { struct MHD_Daemon *daemon_handle = cls; @@ -570,11 +569,11 @@ run_daemon (void *cls) hostlist_task_v4 = NULL; else hostlist_task_v6 = NULL; - GNUNET_assert (MHD_YES == MHD_run (daemon_handle)); + GNUNET_assert(MHD_YES == MHD_run(daemon_handle)); if (daemon_handle == daemon_handle_v4) - hostlist_task_v4 = prepare_daemon (daemon_handle); + hostlist_task_v4 = prepare_daemon(daemon_handle); else - hostlist_task_v6 = prepare_daemon (daemon_handle); + hostlist_task_v6 = prepare_daemon(daemon_handle); } @@ -585,7 +584,7 @@ run_daemon (void *cls) * @param daemon_handle HTTP server to prepare to run */ static struct GNUNET_SCHEDULER_Task * -prepare_daemon (struct MHD_Daemon *daemon_handle) +prepare_daemon(struct MHD_Daemon *daemon_handle) { struct GNUNET_SCHEDULER_Task *ret; fd_set rs; @@ -598,28 +597,28 @@ prepare_daemon (struct MHD_Daemon *daemon_handle) int haveto; struct GNUNET_TIME_Relative tv; - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); - wrs = GNUNET_NETWORK_fdset_create (); - wws = GNUNET_NETWORK_fdset_create (); + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); + wrs = GNUNET_NETWORK_fdset_create(); + wws = GNUNET_NETWORK_fdset_create(); max = -1; - GNUNET_assert (MHD_YES == MHD_get_fdset (daemon_handle, &rs, &ws, &es, &max)); - haveto = MHD_get_timeout (daemon_handle, &timeout); + GNUNET_assert(MHD_YES == MHD_get_fdset(daemon_handle, &rs, &ws, &es, &max)); + haveto = MHD_get_timeout(daemon_handle, &timeout); if (haveto == MHD_YES) - tv.rel_value_us = (uint64_t) timeout * 1000LL; + tv.rel_value_us = (uint64_t)timeout * 1000LL; else tv = GNUNET_TIME_UNIT_FOREVER_REL; - GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1); - GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1); - ret = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH, - tv, - wrs, - wws, - &run_daemon, - daemon_handle); - GNUNET_NETWORK_fdset_destroy (wrs); - GNUNET_NETWORK_fdset_destroy (wws); + GNUNET_NETWORK_fdset_copy_native(wrs, &rs, max + 1); + GNUNET_NETWORK_fdset_copy_native(wws, &ws, max + 1); + ret = GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_HIGH, + tv, + wrs, + wws, + &run_daemon, + daemon_handle); + GNUNET_NETWORK_fdset_destroy(wrs); + GNUNET_NETWORK_fdset_destroy(wws); return ret; } @@ -635,11 +634,11 @@ prepare_daemon (struct MHD_Daemon *daemon_handle) * @return #GNUNET_OK on success */ int -GNUNET_HOSTLIST_server_start (const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_STATISTICS_Handle *st, - struct GNUNET_CORE_Handle *co, - GNUNET_CORE_ConnectEventHandler *server_ch, - int advertise) +GNUNET_HOSTLIST_server_start(const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_STATISTICS_Handle *st, + struct GNUNET_CORE_Handle *co, + GNUNET_CORE_ConnectEventHandler *server_ch, + int advertise) { unsigned long long port; char *hostname; @@ -654,189 +653,189 @@ GNUNET_HOSTLIST_server_start (const struct GNUNET_CONFIGURATION_Handle *c, const struct sockaddr *sa6; advertising = advertise; - if (! advertising) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Advertising not enabled on this hostlist server\n"); - } + if (!advertising) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Advertising not enabled on this hostlist server\n"); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Advertising enabled on this hostlist server\n"); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Advertising enabled on this hostlist server\n"); + } cfg = c; stats = st; - peerinfo = GNUNET_PEERINFO_connect (cfg); + peerinfo = GNUNET_PEERINFO_connect(cfg); if (NULL == peerinfo) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Could not access PEERINFO service. Exiting.\n")); - return GNUNET_SYSERR; - } - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, - "HOSTLIST", - "HTTPPORT", - &port)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Could not access PEERINFO service. Exiting.\n")); + return GNUNET_SYSERR; + } + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, + "HOSTLIST", + "HTTPPORT", + &port)) return GNUNET_SYSERR; if ((0 == port) || (port > UINT16_MAX)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Invalid port number %llu. Exiting.\n"), - port); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Invalid port number %llu. Exiting.\n"), + port); + return GNUNET_SYSERR; + } if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (cfg, - "HOSTLIST", - "EXTERNAL_DNS_NAME", - &hostname)) - hostname = GNUNET_RESOLVER_local_fqdn_get (); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Hostlist service starts on %s:%llu\n"), - hostname, - port); + GNUNET_CONFIGURATION_get_value_string(cfg, + "HOSTLIST", + "EXTERNAL_DNS_NAME", + &hostname)) + hostname = GNUNET_RESOLVER_local_fqdn_get(); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Hostlist service starts on %s:%llu\n"), + hostname, + port); if (NULL != hostname) - { - size = strlen (hostname); - if (size + 15 > MAX_URL_LEN) { - GNUNET_break (0); + size = strlen(hostname); + if (size + 15 > MAX_URL_LEN) + { + GNUNET_break(0); + } + else + { + GNUNET_asprintf(&hostlist_uri, + "http://%s:%u/", + hostname, + (unsigned int)port); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Address to obtain hostlist: `%s'\n"), + hostlist_uri); + } + GNUNET_free(hostname); } - else - { - GNUNET_asprintf (&hostlist_uri, - "http://%s:%u/", - hostname, - (unsigned int) port); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Address to obtain hostlist: `%s'\n"), - hostlist_uri); - } - GNUNET_free (hostname); - } - if (GNUNET_CONFIGURATION_have_value (cfg, "HOSTLIST", "BINDTOIPV4")) - { - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "HOSTLIST", - "BINDTOIP", - &ipv4)) + if (GNUNET_CONFIGURATION_have_value(cfg, "HOSTLIST", "BINDTOIPV4")) { - GNUNET_log ( - GNUNET_ERROR_TYPE_WARNING, - _ ("BINDTOIP does not a valid IPv4 address! Ignoring BINDTOIPV4.\n")); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "HOSTLIST", + "BINDTOIP", + &ipv4)) + { + GNUNET_log( + GNUNET_ERROR_TYPE_WARNING, + _("BINDTOIP does not a valid IPv4 address! Ignoring BINDTOIPV4.\n")); + } } - } else ipv4 = NULL; - if (GNUNET_CONFIGURATION_have_value (cfg, "HOSTLIST", "BINDTOIPV6")) - { - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "HOSTLIST", - "BINDTOIP", - &ipv6)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_WARNING, - _ ("BINDTOIP does not a valid IPv4 address! Ignoring BINDTOIPV6.\n")); + if (GNUNET_CONFIGURATION_have_value(cfg, "HOSTLIST", "BINDTOIPV6")) + { + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "HOSTLIST", + "BINDTOIP", + &ipv6)) + { + GNUNET_log( + GNUNET_ERROR_TYPE_WARNING, + _("BINDTOIP does not a valid IPv4 address! Ignoring BINDTOIPV6.\n")); + } } - } else ipv6 = NULL; sa4 = NULL; if (NULL != ipv4) - { - if (1 == inet_pton (AF_INET, ipv4, &i4)) { - memset (&v4, 0, sizeof (v4)); - v4.sin_family = AF_INET; - v4.sin_addr = i4; - v4.sin_port = htons (port); + if (1 == inet_pton(AF_INET, ipv4, &i4)) + { + memset(&v4, 0, sizeof(v4)); + v4.sin_family = AF_INET; + v4.sin_addr = i4; + v4.sin_port = htons(port); #if HAVE_SOCKADDR_IN_SIN_LEN - v4.sin_len = sizeof (v4); + v4.sin_len = sizeof(v4); #endif - sa4 = (const struct sockaddr *) &v4; - } - else - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ( - "`%s' is not a valid IPv4 address! Ignoring BINDTOIPV4.\n"), - ipv4); - GNUNET_free (ipv4); - } + sa4 = (const struct sockaddr *)&v4; + } + else + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _( + "`%s' is not a valid IPv4 address! Ignoring BINDTOIPV4.\n"), + ipv4); + GNUNET_free(ipv4); + } sa6 = NULL; if (NULL != ipv6) - { - if (1 == inet_pton (AF_INET6, ipv6, &i6)) { - memset (&v6, 0, sizeof (v6)); - v6.sin6_family = AF_INET6; - v6.sin6_addr = i6; - v6.sin6_port = htons (port); + if (1 == inet_pton(AF_INET6, ipv6, &i6)) + { + memset(&v6, 0, sizeof(v6)); + v6.sin6_family = AF_INET6; + v6.sin6_addr = i6; + v6.sin6_port = htons(port); #if HAVE_SOCKADDR_IN_SIN_LEN - v6.sin6_len = sizeof (v6); + v6.sin6_len = sizeof(v6); #endif - sa6 = (const struct sockaddr *) &v6; - } - else - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ( - "`%s' is not a valid IPv6 address! Ignoring BINDTOIPV6.\n"), - ipv6); - GNUNET_free (ipv6); - } - - daemon_handle_v6 = MHD_start_daemon (MHD_USE_IPv6 | MHD_USE_DEBUG, - (uint16_t) port, - &accept_policy_callback, - NULL, - &access_handler_callback, - NULL, - MHD_OPTION_CONNECTION_LIMIT, - (unsigned int) 128, - MHD_OPTION_PER_IP_CONNECTION_LIMIT, - (unsigned int) 32, - MHD_OPTION_CONNECTION_TIMEOUT, - (unsigned int) 16, - MHD_OPTION_CONNECTION_MEMORY_LIMIT, - (size_t) (16 * 1024), - MHD_OPTION_SOCK_ADDR, - sa6, - MHD_OPTION_END); - daemon_handle_v4 = MHD_start_daemon (MHD_NO_FLAG | MHD_USE_DEBUG, - (uint16_t) port, - &accept_policy_callback, - NULL, - &access_handler_callback, - NULL, - MHD_OPTION_CONNECTION_LIMIT, - (unsigned int) 128, - MHD_OPTION_PER_IP_CONNECTION_LIMIT, - (unsigned int) 32, - MHD_OPTION_CONNECTION_TIMEOUT, - (unsigned int) 16, - MHD_OPTION_CONNECTION_MEMORY_LIMIT, - (size_t) (16 * 1024), - MHD_OPTION_SOCK_ADDR, - sa4, - MHD_OPTION_END); + sa6 = (const struct sockaddr *)&v6; + } + else + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _( + "`%s' is not a valid IPv6 address! Ignoring BINDTOIPV6.\n"), + ipv6); + GNUNET_free(ipv6); + } + + daemon_handle_v6 = MHD_start_daemon(MHD_USE_IPv6 | MHD_USE_DEBUG, + (uint16_t)port, + &accept_policy_callback, + NULL, + &access_handler_callback, + NULL, + MHD_OPTION_CONNECTION_LIMIT, + (unsigned int)128, + MHD_OPTION_PER_IP_CONNECTION_LIMIT, + (unsigned int)32, + MHD_OPTION_CONNECTION_TIMEOUT, + (unsigned int)16, + MHD_OPTION_CONNECTION_MEMORY_LIMIT, + (size_t)(16 * 1024), + MHD_OPTION_SOCK_ADDR, + sa6, + MHD_OPTION_END); + daemon_handle_v4 = MHD_start_daemon(MHD_NO_FLAG | MHD_USE_DEBUG, + (uint16_t)port, + &accept_policy_callback, + NULL, + &access_handler_callback, + NULL, + MHD_OPTION_CONNECTION_LIMIT, + (unsigned int)128, + MHD_OPTION_PER_IP_CONNECTION_LIMIT, + (unsigned int)32, + MHD_OPTION_CONNECTION_TIMEOUT, + (unsigned int)16, + MHD_OPTION_CONNECTION_MEMORY_LIMIT, + (size_t)(16 * 1024), + MHD_OPTION_SOCK_ADDR, + sa4, + MHD_OPTION_END); if ((NULL == daemon_handle_v6) && (NULL == daemon_handle_v4)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Could not start hostlist HTTP server on port %u\n"), - (unsigned short) port); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Could not start hostlist HTTP server on port %u\n"), + (unsigned short)port); + return GNUNET_SYSERR; + } core = co; *server_ch = &connect_handler; if (NULL != daemon_handle_v4) - hostlist_task_v4 = prepare_daemon (daemon_handle_v4); + hostlist_task_v4 = prepare_daemon(daemon_handle_v4); if (NULL != daemon_handle_v6) - hostlist_task_v6 = prepare_daemon (daemon_handle_v6); - notify = GNUNET_PEERINFO_notify (cfg, GNUNET_NO, &process_notify, NULL); + hostlist_task_v6 = prepare_daemon(daemon_handle_v6); + notify = GNUNET_PEERINFO_notify(cfg, GNUNET_NO, &process_notify, NULL); return GNUNET_OK; } @@ -845,55 +844,55 @@ GNUNET_HOSTLIST_server_start (const struct GNUNET_CONFIGURATION_Handle *c, * Stop server offering our hostlist. */ void -GNUNET_HOSTLIST_server_stop () +GNUNET_HOSTLIST_server_stop() { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Hostlist server shutdown\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Hostlist server shutdown\n"); if (NULL != hostlist_task_v6) - { - GNUNET_SCHEDULER_cancel (hostlist_task_v6); - hostlist_task_v6 = NULL; - } + { + GNUNET_SCHEDULER_cancel(hostlist_task_v6); + hostlist_task_v6 = NULL; + } if (NULL != hostlist_task_v4) - { - GNUNET_SCHEDULER_cancel (hostlist_task_v4); - hostlist_task_v4 = NULL; - } + { + GNUNET_SCHEDULER_cancel(hostlist_task_v4); + hostlist_task_v4 = NULL; + } if (NULL != daemon_handle_v4) - { - MHD_stop_daemon (daemon_handle_v4); - daemon_handle_v4 = NULL; - } + { + MHD_stop_daemon(daemon_handle_v4); + daemon_handle_v4 = NULL; + } if (NULL != daemon_handle_v6) - { - MHD_stop_daemon (daemon_handle_v6); - daemon_handle_v6 = NULL; - } + { + MHD_stop_daemon(daemon_handle_v6); + daemon_handle_v6 = NULL; + } if (NULL != response) - { - MHD_destroy_response (response); - response = NULL; - } + { + MHD_destroy_response(response); + response = NULL; + } if (NULL != notify) - { - GNUNET_PEERINFO_notify_cancel (notify); - notify = NULL; - } + { + GNUNET_PEERINFO_notify_cancel(notify); + notify = NULL; + } if (NULL != builder) - { - if (NULL != builder->pitr) { - GNUNET_PEERINFO_iterate_cancel (builder->pitr); - builder->pitr = NULL; + if (NULL != builder->pitr) + { + GNUNET_PEERINFO_iterate_cancel(builder->pitr); + builder->pitr = NULL; + } + GNUNET_free_non_null(builder->data); + GNUNET_free(builder); + builder = NULL; } - GNUNET_free_non_null (builder->data); - GNUNET_free (builder); - builder = NULL; - } if (NULL != peerinfo) - { - GNUNET_PEERINFO_disconnect (peerinfo); - peerinfo = NULL; - } + { + GNUNET_PEERINFO_disconnect(peerinfo); + peerinfo = NULL; + } cfg = NULL; stats = NULL; core = NULL; diff --git a/src/hostlist/gnunet-daemon-hostlist_server.h b/src/hostlist/gnunet-daemon-hostlist_server.h index bb0efef41..407675b41 100644 --- a/src/hostlist/gnunet-daemon-hostlist_server.h +++ b/src/hostlist/gnunet-daemon-hostlist_server.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hostlist/gnunet-daemon-hostlist_server.h @@ -43,18 +43,18 @@ * @return #GNUNET_OK on success */ int -GNUNET_HOSTLIST_server_start (const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_STATISTICS_Handle *st, - struct GNUNET_CORE_Handle *core, - GNUNET_CORE_ConnectEventHandler *server_ch, - int advertise); +GNUNET_HOSTLIST_server_start(const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_STATISTICS_Handle *st, + struct GNUNET_CORE_Handle *core, + GNUNET_CORE_ConnectEventHandler *server_ch, + int advertise); /** * Stop server offering our hostlist. */ void -GNUNET_HOSTLIST_server_stop (void); +GNUNET_HOSTLIST_server_stop(void); #endif diff --git a/src/hostlist/test_gnunet_daemon_hostlist.c b/src/hostlist/test_gnunet_daemon_hostlist.c index 557b91d1c..d6853c184 100644 --- a/src/hostlist/test_gnunet_daemon_hostlist.c +++ b/src/hostlist/test_gnunet_daemon_hostlist.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hostlist/test_gnunet_daemon_hostlist.c * @brief test for gnunet_daemon_hostslist.c @@ -32,14 +32,13 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 150) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 150) static int ok; static struct GNUNET_SCHEDULER_Task *timeout_task; -struct PeerContext -{ +struct PeerContext { struct GNUNET_CONFIGURATION_Handle *cfg; struct GNUNET_TRANSPORT_CoreHandle *th; struct GNUNET_MessageHeader *hello; @@ -53,29 +52,29 @@ static struct PeerContext p2; static void -clean_up (void *cls) +clean_up(void *cls) { if (NULL != p1.th) - { - if (NULL != p1.ghh) { - GNUNET_TRANSPORT_hello_get_cancel (p1.ghh); - p1.ghh = NULL; + if (NULL != p1.ghh) + { + GNUNET_TRANSPORT_hello_get_cancel(p1.ghh); + p1.ghh = NULL; + } + GNUNET_TRANSPORT_core_disconnect(p1.th); + p1.th = NULL; } - GNUNET_TRANSPORT_core_disconnect (p1.th); - p1.th = NULL; - } if (NULL != p2.th) - { - if (NULL != p2.ghh) { - GNUNET_TRANSPORT_hello_get_cancel (p2.ghh); - p2.ghh = NULL; + if (NULL != p2.ghh) + { + GNUNET_TRANSPORT_hello_get_cancel(p2.ghh); + p2.ghh = NULL; + } + GNUNET_TRANSPORT_core_disconnect(p2.th); + p2.th = NULL; } - GNUNET_TRANSPORT_core_disconnect (p2.th); - p2.th = NULL; - } - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -83,12 +82,12 @@ clean_up (void *cls) * Timeout, give up. */ static void -timeout_error (void *cls) +timeout_error(void *cls) { timeout_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Timeout trying to connect peers, test failed.\n"); - clean_up (NULL); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Timeout trying to connect peers, test failed.\n"); + clean_up(NULL); } @@ -101,92 +100,92 @@ timeout_error (void *cls) * @param mq message queue to send messages to the peer */ static void * -notify_connect (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +notify_connect(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peers connected, shutting down.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Peers connected, shutting down.\n"); ok = 0; if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } - GNUNET_SCHEDULER_add_now (&clean_up, NULL); + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } + GNUNET_SCHEDULER_add_now(&clean_up, NULL); return NULL; } static void -process_hello (void *cls, const struct GNUNET_MessageHeader *message) +process_hello(void *cls, const struct GNUNET_MessageHeader *message) { struct PeerContext *p = cls; - GNUNET_TRANSPORT_hello_get_cancel (p->ghh); + GNUNET_TRANSPORT_hello_get_cancel(p->ghh); p->ghh = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received HELLO, starting hostlist service.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received HELLO, starting hostlist service.\n"); } static void -setup_peer (struct PeerContext *p, const char *cfgname) +setup_peer(struct PeerContext *p, const char *cfgname) { char *binary; - binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-arm"); - p->cfg = GNUNET_CONFIGURATION_create (); - p->arm_proc = GNUNET_OS_start_process (GNUNET_YES, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - NULL, - NULL, - NULL, - binary, - "gnunet-service-arm", - "-c", - cfgname, - NULL); - GNUNET_assert (GNUNET_OK == GNUNET_CONFIGURATION_load (p->cfg, cfgname)); - p->th = GNUNET_TRANSPORT_core_connect (p->cfg, - NULL, - NULL, - p, - ¬ify_connect, - NULL, - NULL); - GNUNET_assert (NULL != p->th); - p->ghh = GNUNET_TRANSPORT_hello_get (p->cfg, - GNUNET_TRANSPORT_AC_ANY, - &process_hello, - p); - GNUNET_free (binary); + binary = GNUNET_OS_get_libexec_binary_path("gnunet-service-arm"); + p->cfg = GNUNET_CONFIGURATION_create(); + p->arm_proc = GNUNET_OS_start_process(GNUNET_YES, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + NULL, + NULL, + NULL, + binary, + "gnunet-service-arm", + "-c", + cfgname, + NULL); + GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_load(p->cfg, cfgname)); + p->th = GNUNET_TRANSPORT_core_connect(p->cfg, + NULL, + NULL, + p, + ¬ify_connect, + NULL, + NULL); + GNUNET_assert(NULL != p->th); + p->ghh = GNUNET_TRANSPORT_hello_get(p->cfg, + GNUNET_TRANSPORT_AC_ANY, + &process_hello, + p); + GNUNET_free(binary); } static void -waitpid_task (void *cls) +waitpid_task(void *cls) { struct PeerContext *p = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Killing ARM process.\n"); - if (0 != GNUNET_OS_process_kill (p->arm_proc, GNUNET_TERM_SIG)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill"); - if (GNUNET_OK != GNUNET_OS_process_wait (p->arm_proc)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "waitpid"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "ARM process %u stopped\n", - GNUNET_OS_process_get_pid (p->arm_proc)); - GNUNET_OS_process_destroy (p->arm_proc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Killing ARM process.\n"); + if (0 != GNUNET_OS_process_kill(p->arm_proc, GNUNET_TERM_SIG)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill"); + if (GNUNET_OK != GNUNET_OS_process_wait(p->arm_proc)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "waitpid"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "ARM process %u stopped\n", + GNUNET_OS_process_get_pid(p->arm_proc)); + GNUNET_OS_process_destroy(p->arm_proc); p->arm_proc = NULL; - GNUNET_CONFIGURATION_destroy (p->cfg); + GNUNET_CONFIGURATION_destroy(p->cfg); } static void -stop_arm (struct PeerContext *p) +stop_arm(struct PeerContext *p) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Asking ARM to stop core service\n"); - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &waitpid_task, p); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Asking ARM to stop core service\n"); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, &waitpid_task, p); } @@ -194,67 +193,68 @@ stop_arm (struct PeerContext *p) * Try again to connect to transport service. */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - stop_arm (&p1); - stop_arm (&p2); + stop_arm(&p1); + stop_arm(&p2); } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - GNUNET_assert (ok == 1); + GNUNET_assert(ok == 1); ok++; - timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, &timeout_error, NULL); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); - setup_peer (&p1, "test_gnunet_daemon_hostlist_peer1.conf"); - setup_peer (&p2, "test_gnunet_daemon_hostlist_peer2.conf"); + timeout_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, &timeout_error, NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); + setup_peer(&p1, "test_gnunet_daemon_hostlist_peer1.conf"); + setup_peer(&p2, "test_gnunet_daemon_hostlist_peer2.conf"); } static int -check () +check() { - char *const argv[] = {"test-gnunet-daemon-hostlist", - "-c", - "test_gnunet_daemon_hostlist_data.conf", - NULL}; - struct GNUNET_GETOPT_CommandLineOption options[] = {GNUNET_GETOPT_OPTION_END}; + char *const argv[] = { "test-gnunet-daemon-hostlist", + "-c", + "test_gnunet_daemon_hostlist_data.conf", + NULL }; + struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; + ok = 1; - GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, - argv, - "test-gnunet-daemon-hostlist", - "nohelp", - options, - &run, - &ok); + GNUNET_PROGRAM_run((sizeof(argv) / sizeof(char *)) - 1, + argv, + "test-gnunet-daemon-hostlist", + "nohelp", + options, + &run, + &ok); return ok; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { int ret; - GNUNET_DISK_purge_cfg_dir ("test_gnunet_daemon_hostlist_peer1.conf", - "GNUNET_TEST_HOME"); - GNUNET_DISK_purge_cfg_dir ("test_gnunet_daemon_hostlist_peer2.conf", - "GNUNET_TEST_HOME"); - GNUNET_DISK_purge_cfg_dir ("test_gnunet_daemon_hostlist_data.conf", - "GNUNET_TEST_HOME"); - GNUNET_log_setup ("test-gnunet-daemon-hostlist", "WARNING", NULL); - ret = check (); - GNUNET_DISK_purge_cfg_dir ("test_gnunet_daemon_hostlist_peer1.conf", - "GNUNET_TEST_HOME"); - GNUNET_DISK_purge_cfg_dir ("test_gnunet_daemon_hostlist_peer2.conf", - "GNUNET_TEST_HOME"); - GNUNET_DISK_purge_cfg_dir ("test_gnunet_daemon_hostlist_data.conf", - "GNUNET_TEST_HOME"); + GNUNET_DISK_purge_cfg_dir("test_gnunet_daemon_hostlist_peer1.conf", + "GNUNET_TEST_HOME"); + GNUNET_DISK_purge_cfg_dir("test_gnunet_daemon_hostlist_peer2.conf", + "GNUNET_TEST_HOME"); + GNUNET_DISK_purge_cfg_dir("test_gnunet_daemon_hostlist_data.conf", + "GNUNET_TEST_HOME"); + GNUNET_log_setup("test-gnunet-daemon-hostlist", "WARNING", NULL); + ret = check(); + GNUNET_DISK_purge_cfg_dir("test_gnunet_daemon_hostlist_peer1.conf", + "GNUNET_TEST_HOME"); + GNUNET_DISK_purge_cfg_dir("test_gnunet_daemon_hostlist_peer2.conf", + "GNUNET_TEST_HOME"); + GNUNET_DISK_purge_cfg_dir("test_gnunet_daemon_hostlist_data.conf", + "GNUNET_TEST_HOME"); return ret; } diff --git a/src/hostlist/test_gnunet_daemon_hostlist_learning.c b/src/hostlist/test_gnunet_daemon_hostlist_learning.c index a18255e6d..fa72ac828 100644 --- a/src/hostlist/test_gnunet_daemon_hostlist_learning.c +++ b/src/hostlist/test_gnunet_daemon_hostlist_learning.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hostlist/test_gnunet_daemon_hostlist_learning.c * @brief test for gnunet_daemon_hostslist.c @@ -35,13 +35,12 @@ /** * How long until wait until testcases fails */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 180) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 180) -#define CHECK_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1) +#define CHECK_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1) -struct PeerContext -{ +struct PeerContext { struct GNUNET_CONFIGURATION_Handle *cfg; struct GNUNET_MessageHeader *hello; struct GNUNET_CORE_Handle *core; @@ -79,86 +78,86 @@ static struct GNUNET_STATISTICS_GetHandle *advsent_stat; static void -shutdown_testcase () +shutdown_testcase() { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Shutdown testcase....\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Shutdown testcase....\n"); if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } if (NULL != download_stats) - { - GNUNET_STATISTICS_get_cancel (download_stats); - download_stats = NULL; - } + { + GNUNET_STATISTICS_get_cancel(download_stats); + download_stats = NULL; + } if (NULL != urisrecv_stat) - { - GNUNET_STATISTICS_get_cancel (urisrecv_stat); - urisrecv_stat = NULL; - } + { + GNUNET_STATISTICS_get_cancel(urisrecv_stat); + urisrecv_stat = NULL; + } if (NULL != advsent_stat) - { - GNUNET_STATISTICS_get_cancel (advsent_stat); - advsent_stat = NULL; - } + { + GNUNET_STATISTICS_get_cancel(advsent_stat); + advsent_stat = NULL; + } if (NULL != adv_peer.stats) - { - GNUNET_STATISTICS_destroy (adv_peer.stats, GNUNET_NO); - adv_peer.stats = NULL; - } + { + GNUNET_STATISTICS_destroy(adv_peer.stats, GNUNET_NO); + adv_peer.stats = NULL; + } if (NULL != learn_peer.stats) - { - GNUNET_STATISTICS_destroy (learn_peer.stats, GNUNET_NO); - learn_peer.stats = NULL; - } + { + GNUNET_STATISTICS_destroy(learn_peer.stats, GNUNET_NO); + learn_peer.stats = NULL; + } if (NULL != check_task) - { - GNUNET_SCHEDULER_cancel (check_task); - check_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(check_task); + check_task = NULL; + } if (NULL != current_adv_uri) - { - GNUNET_free (current_adv_uri); - current_adv_uri = NULL; - } + { + GNUNET_free(current_adv_uri); + current_adv_uri = NULL; + } if (NULL != adv_peer.core) - { - GNUNET_CORE_disconnect (adv_peer.core); - adv_peer.core = NULL; - } + { + GNUNET_CORE_disconnect(adv_peer.core); + adv_peer.core = NULL; + } if (NULL != learn_peer.core) - { - GNUNET_CORE_disconnect (learn_peer.core); - learn_peer.core = NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Killing hostlist server ARM process.\n"); - if (0 != GNUNET_OS_process_kill (adv_peer.arm_proc, - GNUNET_TERM_SIG)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "kill"); + { + GNUNET_CORE_disconnect(learn_peer.core); + learn_peer.core = NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Killing hostlist server ARM process.\n"); + if (0 != GNUNET_OS_process_kill(adv_peer.arm_proc, + GNUNET_TERM_SIG)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "kill"); if (GNUNET_OK != - GNUNET_OS_process_wait (adv_peer.arm_proc)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "waitpid"); - GNUNET_OS_process_destroy (adv_peer.arm_proc); + GNUNET_OS_process_wait(adv_peer.arm_proc)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "waitpid"); + GNUNET_OS_process_destroy(adv_peer.arm_proc); adv_peer.arm_proc = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Killing hostlist client ARM process.\n"); - if (0 != GNUNET_OS_process_kill (learn_peer.arm_proc, - GNUNET_TERM_SIG)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "kill"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Killing hostlist client ARM process.\n"); + if (0 != GNUNET_OS_process_kill(learn_peer.arm_proc, + GNUNET_TERM_SIG)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "kill"); if (GNUNET_OK != - GNUNET_OS_process_wait (learn_peer.arm_proc)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "waitpid"); - GNUNET_OS_process_destroy (learn_peer.arm_proc); + GNUNET_OS_process_wait(learn_peer.arm_proc)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "waitpid"); + GNUNET_OS_process_destroy(learn_peer.arm_proc); learn_peer.arm_proc = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Shutdown complete....\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Shutdown complete....\n"); } @@ -166,111 +165,112 @@ shutdown_testcase () * Timeout, give up. */ static void -timeout_error (void *cls) +timeout_error(void *cls) { timeout_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Timeout while executing testcase, test failed.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Timeout while executing testcase, test failed.\n"); timeout = GNUNET_YES; - shutdown_testcase (); + shutdown_testcase(); } static void -process_downloads_done (void *cls, int success) +process_downloads_done(void *cls, int success) { download_stats = NULL; } static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - shutdown_testcase (); + shutdown_testcase(); } static int -process_downloads (void *cls, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +process_downloads(void *cls, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { - if ( (value >= 2) && - (GNUNET_NO == learned_hostlist_downloaded) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Peer has successfully downloaded advertised URI\n"); - learned_hostlist_downloaded = GNUNET_YES; - if ((learned_hostlist_saved == GNUNET_YES) && (adv_sent == GNUNET_YES)) + if ((value >= 2) && + (GNUNET_NO == learned_hostlist_downloaded)) { - GNUNET_SCHEDULER_add_now (&do_shutdown, NULL); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Peer has successfully downloaded advertised URI\n"); + learned_hostlist_downloaded = GNUNET_YES; + if ((learned_hostlist_saved == GNUNET_YES) && (adv_sent == GNUNET_YES)) + { + GNUNET_SCHEDULER_add_now(&do_shutdown, NULL); + } } - } return GNUNET_OK; } static void -process_uris_recv_done (void *cls, int success) +process_uris_recv_done(void *cls, int success) { urisrecv_stat = NULL; } static int -process_uris_recv (void *cls, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +process_uris_recv(void *cls, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { struct PeerContext *pc = cls; - if ( (pc == &learn_peer) && - (value == 1) && - (learned_hostlist_saved == GNUNET_NO) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Peer has successfully saved advertised URI\n"); - learned_hostlist_saved = GNUNET_YES; - if ( (learned_hostlist_downloaded == GNUNET_YES) && - (adv_sent == GNUNET_YES) ) + + if ((pc == &learn_peer) && + (value == 1) && + (learned_hostlist_saved == GNUNET_NO)) { - GNUNET_SCHEDULER_add_now (&do_shutdown, - NULL); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Peer has successfully saved advertised URI\n"); + learned_hostlist_saved = GNUNET_YES; + if ((learned_hostlist_downloaded == GNUNET_YES) && + (adv_sent == GNUNET_YES)) + { + GNUNET_SCHEDULER_add_now(&do_shutdown, + NULL); + } } - } return GNUNET_OK; } static void -process_adv_sent_done (void *cls, int success) +process_adv_sent_done(void *cls, int success) { advsent_stat = NULL; } static int -process_adv_sent (void *cls, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +process_adv_sent(void *cls, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { if ((value >= 1) && (adv_sent == GNUNET_NO)) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Server has successfully sent advertisement\n"); - adv_sent = GNUNET_YES; - if ((learned_hostlist_downloaded == GNUNET_YES) && - (learned_hostlist_saved == GNUNET_YES)) { - GNUNET_SCHEDULER_add_now (&do_shutdown, - NULL); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Server has successfully sent advertisement\n"); + adv_sent = GNUNET_YES; + if ((learned_hostlist_downloaded == GNUNET_YES) && + (learned_hostlist_saved == GNUNET_YES)) + { + GNUNET_SCHEDULER_add_now(&do_shutdown, + NULL); + } } - } return GNUNET_OK; } @@ -279,69 +279,70 @@ process_adv_sent (void *cls, * Check the server statistics regularly */ static void -check_statistics (void *cls) +check_statistics(void *cls) { char *stat; check_task = NULL; - GNUNET_asprintf (&stat, - gettext_noop ("# advertised URI `%s' downloaded"), - current_adv_uri); + GNUNET_asprintf(&stat, + gettext_noop("# advertised URI `%s' downloaded"), + current_adv_uri); if (NULL != learn_peer.stats) - { - if (NULL != download_stats) - GNUNET_STATISTICS_get_cancel (download_stats); - download_stats = - GNUNET_STATISTICS_get (learn_peer.stats, - "hostlist", - stat, - &process_downloads_done, - &process_downloads, - &learn_peer); - if (NULL != urisrecv_stat) - GNUNET_STATISTICS_get_cancel (urisrecv_stat); - urisrecv_stat = - GNUNET_STATISTICS_get (learn_peer.stats, "hostlist", - gettext_noop ("# advertised hostlist URIs"), - &process_uris_recv_done, &process_uris_recv, - &learn_peer); - } - GNUNET_free (stat); + { + if (NULL != download_stats) + GNUNET_STATISTICS_get_cancel(download_stats); + download_stats = + GNUNET_STATISTICS_get(learn_peer.stats, + "hostlist", + stat, + &process_downloads_done, + &process_downloads, + &learn_peer); + if (NULL != urisrecv_stat) + GNUNET_STATISTICS_get_cancel(urisrecv_stat); + urisrecv_stat = + GNUNET_STATISTICS_get(learn_peer.stats, "hostlist", + gettext_noop("# advertised hostlist URIs"), + &process_uris_recv_done, &process_uris_recv, + &learn_peer); + } + GNUNET_free(stat); if (NULL != adv_peer.stats) - { - if (NULL != advsent_stat) - GNUNET_STATISTICS_get_cancel (advsent_stat); - advsent_stat = - GNUNET_STATISTICS_get (adv_peer.stats, "hostlist", - gettext_noop ("# hostlist advertisements send"), - &process_adv_sent_done, - &process_adv_sent, - NULL); - } + { + if (NULL != advsent_stat) + GNUNET_STATISTICS_get_cancel(advsent_stat); + advsent_stat = + GNUNET_STATISTICS_get(adv_peer.stats, "hostlist", + gettext_noop("# hostlist advertisements send"), + &process_adv_sent_done, + &process_adv_sent, + NULL); + } check_task = - GNUNET_SCHEDULER_add_delayed (CHECK_INTERVAL, - &check_statistics, - NULL); + GNUNET_SCHEDULER_add_delayed(CHECK_INTERVAL, + &check_statistics, + NULL); } static int -check_ad_arrive (void *cls, - const struct GNUNET_MessageHeader *message) +check_ad_arrive(void *cls, + const struct GNUNET_MessageHeader *message) { - const char *end = (const char *) &message[1]; - if ('\0' != end[ntohs (message->size) - sizeof (struct GNUNET_MessageHeader) - 1]) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + const char *end = (const char *)&message[1]; + + if ('\0' != end[ntohs(message->size) - sizeof(struct GNUNET_MessageHeader) - 1]) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } static void -handle_ad_arrive (void *cls, - const struct GNUNET_MessageHeader *message) +handle_ad_arrive(void *cls, + const struct GNUNET_MessageHeader *message) { char *hostname; char *expected_uri; @@ -349,132 +350,132 @@ handle_ad_arrive (void *cls, const char *end; if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_number (adv_peer.cfg, - "HOSTLIST", - "HTTPPORT", - &port)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not read advertising server's configuration\n"); - return; - } + GNUNET_CONFIGURATION_get_value_number(adv_peer.cfg, + "HOSTLIST", + "HTTPPORT", + &port)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not read advertising server's configuration\n"); + return; + } if (GNUNET_SYSERR == - GNUNET_CONFIGURATION_get_value_string (adv_peer.cfg, - "HOSTLIST", - "EXTERNAL_DNS_NAME", - &hostname)) - hostname = GNUNET_RESOLVER_local_fqdn_get (); - GNUNET_asprintf (&expected_uri, - "http://%s:%u/", - hostname != NULL ? hostname : "localhost", - (unsigned int) port); - end = (const char *) &message[1]; - current_adv_uri = GNUNET_strdup (end); - if (0 == strcmp (expected_uri, - current_adv_uri)) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Received hostlist advertisement with URI `%s' as expected\n", - current_adv_uri); - adv_arrived = GNUNET_YES; - adv_sent = GNUNET_YES; - } + GNUNET_CONFIGURATION_get_value_string(adv_peer.cfg, + "HOSTLIST", + "EXTERNAL_DNS_NAME", + &hostname)) + hostname = GNUNET_RESOLVER_local_fqdn_get(); + GNUNET_asprintf(&expected_uri, + "http://%s:%u/", + hostname != NULL ? hostname : "localhost", + (unsigned int)port); + end = (const char *)&message[1]; + current_adv_uri = GNUNET_strdup(end); + if (0 == strcmp(expected_uri, + current_adv_uri)) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Received hostlist advertisement with URI `%s' as expected\n", + current_adv_uri); + adv_arrived = GNUNET_YES; + adv_sent = GNUNET_YES; + } else - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Expected URI `%s' and received URI `%s' differ\n", - expected_uri, - current_adv_uri); - GNUNET_free (expected_uri); - GNUNET_free_non_null (hostname); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Expected URI `%s' and received URI `%s' differ\n", + expected_uri, + current_adv_uri); + GNUNET_free(expected_uri); + GNUNET_free_non_null(hostname); } static void -setup_learn_peer (struct PeerContext *p, - const char *cfgname) +setup_learn_peer(struct PeerContext *p, + const char *cfgname) { struct GNUNET_MQ_MessageHandler learn_handlers[] = { - GNUNET_MQ_hd_var_size (ad_arrive, - GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(ad_arrive, + GNUNET_MESSAGE_TYPE_HOSTLIST_ADVERTISEMENT, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end() }; char *filename; unsigned int result; char *binary; - binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-arm"); - p->cfg = GNUNET_CONFIGURATION_create (); + binary = GNUNET_OS_get_libexec_binary_path("gnunet-service-arm"); + p->cfg = GNUNET_CONFIGURATION_create(); p->arm_proc = - GNUNET_OS_start_process (GNUNET_YES, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - NULL, NULL, NULL, - binary, - "gnunet-service-arm", - "-c", cfgname, NULL); - GNUNET_assert (GNUNET_OK == - GNUNET_CONFIGURATION_load (p->cfg, - cfgname)); + GNUNET_OS_start_process(GNUNET_YES, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + NULL, NULL, NULL, + binary, + "gnunet-service-arm", + "-c", cfgname, NULL); + GNUNET_assert(GNUNET_OK == + GNUNET_CONFIGURATION_load(p->cfg, + cfgname)); if (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (p->cfg, - "HOSTLIST", - "HOSTLISTFILE", - &filename)) - { - if (GNUNET_YES == GNUNET_DISK_file_test (filename)) + GNUNET_CONFIGURATION_get_value_string(p->cfg, + "HOSTLIST", + "HOSTLISTFILE", + &filename)) { - result = unlink (filename); - if (result == 0) - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Hostlist file `%s' was removed\n"), - filename); + if (GNUNET_YES == GNUNET_DISK_file_test(filename)) + { + result = unlink(filename); + if (result == 0) + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Hostlist file `%s' was removed\n"), + filename); + } + GNUNET_free(filename); } - GNUNET_free (filename); - } - p->core = GNUNET_CORE_connect (p->cfg, - NULL, - NULL, - NULL, - NULL, - learn_handlers); - GNUNET_assert (NULL != p->core); - p->stats = GNUNET_STATISTICS_create ("hostlist", - p->cfg); - GNUNET_assert (NULL != p->stats); - GNUNET_free (binary); + p->core = GNUNET_CORE_connect(p->cfg, + NULL, + NULL, + NULL, + NULL, + learn_handlers); + GNUNET_assert(NULL != p->core); + p->stats = GNUNET_STATISTICS_create("hostlist", + p->cfg); + GNUNET_assert(NULL != p->stats); + GNUNET_free(binary); } static void -setup_adv_peer (struct PeerContext *p, - const char *cfgname) +setup_adv_peer(struct PeerContext *p, + const char *cfgname) { char *binary; - binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-arm"); - p->cfg = GNUNET_CONFIGURATION_create (); + binary = GNUNET_OS_get_libexec_binary_path("gnunet-service-arm"); + p->cfg = GNUNET_CONFIGURATION_create(); p->arm_proc = - GNUNET_OS_start_process (GNUNET_YES, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - NULL, NULL, NULL, - binary, - "gnunet-service-arm", - "-c", cfgname, NULL); - GNUNET_assert (GNUNET_OK == - GNUNET_CONFIGURATION_load (p->cfg, - cfgname)); - p->stats = GNUNET_STATISTICS_create ("hostlist", p->cfg); - GNUNET_assert (NULL != p->stats); - GNUNET_free (binary); + GNUNET_OS_start_process(GNUNET_YES, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + NULL, NULL, NULL, + binary, + "gnunet-service-arm", + "-c", cfgname, NULL); + GNUNET_assert(GNUNET_OK == + GNUNET_CONFIGURATION_load(p->cfg, + cfgname)); + p->stats = GNUNET_STATISTICS_create("hostlist", p->cfg); + GNUNET_assert(NULL != p->stats); + GNUNET_free(binary); } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { timeout = GNUNET_NO; adv_sent = GNUNET_NO; @@ -485,22 +486,22 @@ run (void *cls, cfg = c; - setup_adv_peer (&adv_peer, - "test_learning_adv_peer.conf"); - setup_learn_peer (&learn_peer, - "test_learning_learn_peer.conf"); - timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &timeout_error, - NULL); + setup_adv_peer(&adv_peer, + "test_learning_adv_peer.conf"); + setup_learn_peer(&learn_peer, + "test_learning_learn_peer.conf"); + timeout_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &timeout_error, + NULL); check_task = - GNUNET_SCHEDULER_add_delayed (CHECK_INTERVAL, - &check_statistics, - NULL); + GNUNET_SCHEDULER_add_delayed(CHECK_INTERVAL, + &check_statistics, + NULL); } static int -check () +check() { unsigned int failed; @@ -513,44 +514,44 @@ check () GNUNET_GETOPT_OPTION_END }; - GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, - argv, - "test-gnunet-daemon-hostlist-learning", - "nohelp", - options, - &run, - NULL); + GNUNET_PROGRAM_run((sizeof(argv) / sizeof(char *)) - 1, + argv, + "test-gnunet-daemon-hostlist-learning", + "nohelp", + options, + &run, + NULL); failed = GNUNET_NO; if (timeout == GNUNET_YES) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Testcase timeout\n"); - failed = GNUNET_YES; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Testcase timeout\n"); + failed = GNUNET_YES; + } if (adv_arrived != GNUNET_YES) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Learning peer did not receive advertisement from server\n"); - failed = GNUNET_YES; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Learning peer did not receive advertisement from server\n"); + failed = GNUNET_YES; + } if (learned_hostlist_saved == GNUNET_NO) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Advertised hostlist was not saved in datastore\n"); - failed = GNUNET_YES; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Advertised hostlist was not saved in datastore\n"); + failed = GNUNET_YES; + } if (learned_hostlist_downloaded == GNUNET_NO) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Advertised hostlist could not be downloaded from server\n"); - failed = GNUNET_YES; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Advertised hostlist could not be downloaded from server\n"); + failed = GNUNET_YES; + } if (adv_sent == GNUNET_NO) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Advertised was not sent from server to client\n"); - failed = GNUNET_YES; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Advertised was not sent from server to client\n"); + failed = GNUNET_YES; + } if (GNUNET_YES == failed) return GNUNET_YES; return GNUNET_NO; @@ -558,29 +559,29 @@ check () int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { int ret; - GNUNET_DISK_purge_cfg_dir ("test_learning_learn_peer.conf", - "GNUNET_TEST_HOME"); - GNUNET_DISK_purge_cfg_dir ("test_learning_adv_peer.conf", - "GNUNET_TEST_HOME"); - GNUNET_log_setup ("test-gnunet-daemon-hostlist", - "WARNING", - NULL); - ret = check (); - GNUNET_DISK_purge_cfg_dir ("test_learning_learn_peer.conf", - "GNUNET_TEST_HOME"); - GNUNET_DISK_purge_cfg_dir ("test_learning_adv_peer.conf", - "GNUNET_TEST_HOME"); + GNUNET_DISK_purge_cfg_dir("test_learning_learn_peer.conf", + "GNUNET_TEST_HOME"); + GNUNET_DISK_purge_cfg_dir("test_learning_adv_peer.conf", + "GNUNET_TEST_HOME"); + GNUNET_log_setup("test-gnunet-daemon-hostlist", + "WARNING", + NULL); + ret = check(); + GNUNET_DISK_purge_cfg_dir("test_learning_learn_peer.conf", + "GNUNET_TEST_HOME"); + GNUNET_DISK_purge_cfg_dir("test_learning_adv_peer.conf", + "GNUNET_TEST_HOME"); if (GNUNET_YES == - GNUNET_DISK_file_test ("hostlists_learn_peer.file")) - { - if (0 == unlink ("hostlists_learn_peer.file")) - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Hostlist file hostlists_learn_peer.file was removed\n"); - } + GNUNET_DISK_file_test("hostlists_learn_peer.file")) + { + if (0 == unlink("hostlists_learn_peer.file")) + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Hostlist file hostlists_learn_peer.file was removed\n"); + } return ret; } diff --git a/src/hostlist/test_gnunet_daemon_hostlist_reconnect.c b/src/hostlist/test_gnunet_daemon_hostlist_reconnect.c index 6aaa7ae2e..783da1d20 100644 --- a/src/hostlist/test_gnunet_daemon_hostlist_reconnect.c +++ b/src/hostlist/test_gnunet_daemon_hostlist_reconnect.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file hostlist/test_gnunet_daemon_hostlist_reconnect.c * @brief test for gnunet-daemon-hostslist.c; tries to re-start the peers @@ -32,14 +32,13 @@ /** * How long until we give up on transmitting the message? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 150) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 150) static int ok; static struct GNUNET_SCHEDULER_Task *timeout_task; -struct PeerContext -{ +struct PeerContext { struct GNUNET_CONFIGURATION_Handle *cfg; struct GNUNET_TRANSPORT_CoreHandle *th; struct GNUNET_MessageHeader *hello; @@ -56,12 +55,12 @@ static struct PeerContext p2; * Timeout, give up. */ static void -timeout_error (void *cls) +timeout_error(void *cls) { timeout_task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Timeout trying to connect peers, test failed.\n"); - GNUNET_SCHEDULER_shutdown (); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Timeout trying to connect peers, test failed.\n"); + GNUNET_SCHEDULER_shutdown(); } @@ -75,87 +74,87 @@ timeout_error (void *cls) * @return NULL */ static void * -notify_connect (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +notify_connect(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peers connected, shutting down.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Peers connected, shutting down.\n"); ok = 0; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); return NULL; } static void -process_hello (void *cls, const struct GNUNET_MessageHeader *message) +process_hello(void *cls, const struct GNUNET_MessageHeader *message) { struct PeerContext *p = cls; - GNUNET_TRANSPORT_hello_get_cancel (p->ghh); + GNUNET_TRANSPORT_hello_get_cancel(p->ghh); p->ghh = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received HELLO, starting hostlist service.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received HELLO, starting hostlist service.\n"); } static void -setup_peer (struct PeerContext *p, const char *cfgname) +setup_peer(struct PeerContext *p, const char *cfgname) { char *binary; - binary = GNUNET_OS_get_libexec_binary_path ("gnunet-service-arm"); - p->cfg = GNUNET_CONFIGURATION_create (); - p->arm_proc = GNUNET_OS_start_process (GNUNET_YES, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - NULL, - NULL, - NULL, - binary, - "gnunet-service-arm", - "-c", - cfgname, - NULL); - GNUNET_assert (GNUNET_OK == GNUNET_CONFIGURATION_load (p->cfg, cfgname)); - p->th = GNUNET_TRANSPORT_core_connect (p->cfg, - NULL, - NULL, - p, - ¬ify_connect, - NULL, - NULL); - GNUNET_assert (NULL != p->th); - p->ghh = GNUNET_TRANSPORT_hello_get (p->cfg, - GNUNET_TRANSPORT_AC_ANY, - &process_hello, - p); - GNUNET_free (binary); + binary = GNUNET_OS_get_libexec_binary_path("gnunet-service-arm"); + p->cfg = GNUNET_CONFIGURATION_create(); + p->arm_proc = GNUNET_OS_start_process(GNUNET_YES, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + NULL, + NULL, + NULL, + binary, + "gnunet-service-arm", + "-c", + cfgname, + NULL); + GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_load(p->cfg, cfgname)); + p->th = GNUNET_TRANSPORT_core_connect(p->cfg, + NULL, + NULL, + p, + ¬ify_connect, + NULL, + NULL); + GNUNET_assert(NULL != p->th); + p->ghh = GNUNET_TRANSPORT_hello_get(p->cfg, + GNUNET_TRANSPORT_AC_ANY, + &process_hello, + p); + GNUNET_free(binary); } static void -waitpid_task (void *cls) +waitpid_task(void *cls) { struct PeerContext *p = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Killing ARM process.\n"); - if (0 != GNUNET_OS_process_kill (p->arm_proc, GNUNET_TERM_SIG)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill"); - if (GNUNET_OK != GNUNET_OS_process_wait (p->arm_proc)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "waitpid"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "ARM process %u stopped\n", - GNUNET_OS_process_get_pid (p->arm_proc)); - GNUNET_OS_process_destroy (p->arm_proc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Killing ARM process.\n"); + if (0 != GNUNET_OS_process_kill(p->arm_proc, GNUNET_TERM_SIG)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill"); + if (GNUNET_OK != GNUNET_OS_process_wait(p->arm_proc)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "waitpid"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "ARM process %u stopped\n", + GNUNET_OS_process_get_pid(p->arm_proc)); + GNUNET_OS_process_destroy(p->arm_proc); p->arm_proc = NULL; - GNUNET_CONFIGURATION_destroy (p->cfg); + GNUNET_CONFIGURATION_destroy(p->cfg); } static void -stop_arm (struct PeerContext *p) +stop_arm(struct PeerContext *p) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Asking ARM to stop core service\n"); - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &waitpid_task, p); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Asking ARM to stop core service\n"); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, &waitpid_task, p); } @@ -163,98 +162,99 @@ stop_arm (struct PeerContext *p) * Try again to connect to transport service. */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } if (NULL != p1.ghh) - { - GNUNET_TRANSPORT_hello_get_cancel (p1.ghh); - p1.ghh = NULL; - } + { + GNUNET_TRANSPORT_hello_get_cancel(p1.ghh); + p1.ghh = NULL; + } if (NULL != p1.th) - { - GNUNET_TRANSPORT_core_disconnect (p1.th); - p1.th = NULL; - } + { + GNUNET_TRANSPORT_core_disconnect(p1.th); + p1.th = NULL; + } if (NULL != p2.ghh) - { - GNUNET_TRANSPORT_hello_get_cancel (p2.ghh); - p2.ghh = NULL; - } + { + GNUNET_TRANSPORT_hello_get_cancel(p2.ghh); + p2.ghh = NULL; + } if (NULL != p2.th) - { - GNUNET_TRANSPORT_core_disconnect (p2.th); - p2.th = NULL; - } - stop_arm (&p1); - stop_arm (&p2); + { + GNUNET_TRANSPORT_core_disconnect(p2.th); + p2.th = NULL; + } + stop_arm(&p1); + stop_arm(&p2); } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - GNUNET_assert (ok == 1); + GNUNET_assert(ok == 1); ok++; - timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, &timeout_error, NULL); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); - setup_peer (&p1, "test_gnunet_daemon_hostlist_peer1.conf"); - setup_peer (&p2, "test_gnunet_daemon_hostlist_peer2.conf"); + timeout_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, &timeout_error, NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); + setup_peer(&p1, "test_gnunet_daemon_hostlist_peer1.conf"); + setup_peer(&p2, "test_gnunet_daemon_hostlist_peer2.conf"); } int -main (int argcx, char *argvx[]) +main(int argcx, char *argvx[]) { - static char *const argv[] = {"test-gnunet-daemon-hostlist", - "-c", - "test_gnunet_daemon_hostlist_data.conf", - NULL}; + static char *const argv[] = { "test-gnunet-daemon-hostlist", + "-c", + "test_gnunet_daemon_hostlist_data.conf", + NULL }; static struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_OPTION_END}; - - GNUNET_DISK_purge_cfg_dir ("test_gnunet_daemon_hostlist_peer1.conf", - "GNUNET_TEST_HOME"); - GNUNET_DISK_purge_cfg_dir ("test_gnunet_daemon_hostlist_peer2.conf", - "GNUNET_TEST_HOME"); - GNUNET_DISK_purge_cfg_dir ("test_gnunet_daemon_hostlist_data.conf", - "GNUNET_TEST_HOME"); - GNUNET_log_setup ("test-gnunet-daemon-hostlist", "WARNING", NULL); + GNUNET_GETOPT_OPTION_END + }; + + GNUNET_DISK_purge_cfg_dir("test_gnunet_daemon_hostlist_peer1.conf", + "GNUNET_TEST_HOME"); + GNUNET_DISK_purge_cfg_dir("test_gnunet_daemon_hostlist_peer2.conf", + "GNUNET_TEST_HOME"); + GNUNET_DISK_purge_cfg_dir("test_gnunet_daemon_hostlist_data.conf", + "GNUNET_TEST_HOME"); + GNUNET_log_setup("test-gnunet-daemon-hostlist", "WARNING", NULL); ok = 1; - GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, - argv, - "test-gnunet-daemon-hostlist", - "nohelp", - options, - &run, - &ok); + GNUNET_PROGRAM_run((sizeof(argv) / sizeof(char *)) - 1, + argv, + "test-gnunet-daemon-hostlist", + "nohelp", + options, + &run, + &ok); if (0 == ok) - { - fprintf (stderr, "%s", "."); - /* now do it again */ - ok = 1; - GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1, - argv, - "test-gnunet-daemon-hostlist", - "nohelp", - options, - &run, - &ok); - fprintf (stderr, "%s", ".\n"); - } - GNUNET_DISK_purge_cfg_dir ("test_gnunet_daemon_hostlist_peer1.conf", - "GNUNET_TEST_HOME"); - GNUNET_DISK_purge_cfg_dir ("test_gnunet_daemon_hostlist_peer2.conf", - "GNUNET_TEST_HOME"); - GNUNET_DISK_purge_cfg_dir ("test_gnunet_daemon_hostlist_data.conf", - "GNUNET_TEST_HOME"); + { + fprintf(stderr, "%s", "."); + /* now do it again */ + ok = 1; + GNUNET_PROGRAM_run((sizeof(argv) / sizeof(char *)) - 1, + argv, + "test-gnunet-daemon-hostlist", + "nohelp", + options, + &run, + &ok); + fprintf(stderr, "%s", ".\n"); + } + GNUNET_DISK_purge_cfg_dir("test_gnunet_daemon_hostlist_peer1.conf", + "GNUNET_TEST_HOME"); + GNUNET_DISK_purge_cfg_dir("test_gnunet_daemon_hostlist_peer2.conf", + "GNUNET_TEST_HOME"); + GNUNET_DISK_purge_cfg_dir("test_gnunet_daemon_hostlist_data.conf", + "GNUNET_TEST_HOME"); return ok; } diff --git a/src/identity/gnunet-identity.c b/src/identity/gnunet-identity.c index 41878fc1e..d86fd2166 100644 --- a/src/identity/gnunet-identity.c +++ b/src/identity/gnunet-identity.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file identity/gnunet-identity.c * @brief IDENTITY management command line tool @@ -112,29 +112,29 @@ static int global_ret; * @param cls NULL */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { if (NULL != set_op) - { - GNUNET_IDENTITY_cancel (set_op); - set_op = NULL; - } + { + GNUNET_IDENTITY_cancel(set_op); + set_op = NULL; + } if (NULL != create_op) - { - GNUNET_IDENTITY_cancel (create_op); - create_op = NULL; - } + { + GNUNET_IDENTITY_cancel(create_op); + create_op = NULL; + } if (NULL != delete_op) - { - GNUNET_IDENTITY_cancel (delete_op); - delete_op = NULL; - } + { + GNUNET_IDENTITY_cancel(delete_op); + delete_op = NULL; + } if (NULL != set_ego) - { - GNUNET_free (set_ego); - set_ego = NULL; - } - GNUNET_IDENTITY_disconnect (sh); + { + GNUNET_free(set_ego); + set_ego = NULL; + } + GNUNET_IDENTITY_disconnect(sh); sh = NULL; } @@ -143,15 +143,15 @@ shutdown_task (void *cls) * Test if we are finished yet. */ static void -test_finished () +test_finished() { if ((NULL == create_op) && (NULL == delete_op) && (NULL == set_op) && - (NULL == set_subsystem) && (! list) && (! monitor)) - { - if (TIMEOUT_STATUS_CODE == global_ret) - global_ret = 0; - GNUNET_SCHEDULER_shutdown (); - } + (NULL == set_subsystem) && (!list) && (!monitor)) + { + if (TIMEOUT_STATUS_CODE == global_ret) + global_ret = 0; + GNUNET_SCHEDULER_shutdown(); + } } @@ -162,14 +162,14 @@ test_finished () * @param emsg NULL on success, otherwise an error message */ static void -delete_finished (void *cls, const char *emsg) +delete_finished(void *cls, const char *emsg) { struct GNUNET_IDENTITY_Operation **op = cls; *op = NULL; if (NULL != emsg) - fprintf (stderr, "%s\n", gettext (emsg)); - test_finished (); + fprintf(stderr, "%s\n", gettext(emsg)); + test_finished(); } @@ -181,40 +181,40 @@ delete_finished (void *cls, const char *emsg) * @param emsg error message, NULL on success */ static void -create_finished (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, - const char *emsg) +create_finished(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, + const char *emsg) { struct GNUNET_IDENTITY_Operation **op = cls; *op = NULL; if (NULL == pk) - { - fprintf (stderr, _ ("Failed to create ego: %s\n"), emsg); - global_ret = 1; - } - else if (verbose) - { - struct GNUNET_CRYPTO_EcdsaPublicKey pub; - char *pubs; - - GNUNET_CRYPTO_ecdsa_key_get_public (pk, &pub); - pubs = GNUNET_CRYPTO_ecdsa_public_key_to_string (&pub); - if (private_keys) { - char *privs; - - privs = GNUNET_CRYPTO_ecdsa_private_key_to_string (pk); - fprintf (stdout, "%s - %s\n", pubs, privs); - GNUNET_free (privs); + fprintf(stderr, _("Failed to create ego: %s\n"), emsg); + global_ret = 1; } - else + else if (verbose) { - fprintf (stdout, "%s\n", pubs); + struct GNUNET_CRYPTO_EcdsaPublicKey pub; + char *pubs; + + GNUNET_CRYPTO_ecdsa_key_get_public(pk, &pub); + pubs = GNUNET_CRYPTO_ecdsa_public_key_to_string(&pub); + if (private_keys) + { + char *privs; + + privs = GNUNET_CRYPTO_ecdsa_private_key_to_string(pk); + fprintf(stdout, "%s - %s\n", pubs, privs); + GNUNET_free(privs); + } + else + { + fprintf(stdout, "%s\n", pubs); + } + GNUNET_free(pubs); } - GNUNET_free (pubs); - } - test_finished (); + test_finished(); } @@ -225,15 +225,15 @@ create_finished (void *cls, * @param emsg error message (NULL on success) */ static void -set_done (void *cls, const char *emsg) +set_done(void *cls, const char *emsg) { set_op = NULL; if (NULL != emsg) - { - fprintf (stderr, _ ("Failed to set default ego: %s\n"), emsg); - global_ret = 1; - } - test_finished (); + { + fprintf(stderr, _("Failed to set default ego: %s\n"), emsg); + global_ret = 1; + } + test_finished(); } @@ -269,72 +269,72 @@ set_done (void *cls, const char *emsg) * @param identifier identifier assigned by the user for this ego, * NULL if the user just deleted the ego and it * must thus no longer be used -*/ + */ static void -print_ego (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *identifier) +print_ego(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *identifier) { struct GNUNET_CRYPTO_EcdsaPublicKey pk; char *s; char *privs; if ((NULL != set_ego) && (NULL != set_subsystem) && (NULL != ego) && - (NULL != identifier) && (0 == strcmp (identifier, set_ego))) - { - set_op = GNUNET_IDENTITY_set (sh, set_subsystem, ego, &set_done, NULL); - GNUNET_free (set_subsystem); - set_subsystem = NULL; - GNUNET_free (set_ego); - set_ego = NULL; - } + (NULL != identifier) && (0 == strcmp(identifier, set_ego))) + { + set_op = GNUNET_IDENTITY_set(sh, set_subsystem, ego, &set_done, NULL); + GNUNET_free(set_subsystem); + set_subsystem = NULL; + GNUNET_free(set_ego); + set_ego = NULL; + } if ((NULL == ego) && (NULL != set_ego) && (NULL != set_subsystem)) - { - fprintf (stderr, - "Could not set ego to `%s' for subsystem `%s', ego not known\n", - set_ego, - set_subsystem); - GNUNET_free (set_subsystem); - set_subsystem = NULL; - GNUNET_free (set_ego); - set_ego = NULL; - } - if ((NULL == ego) && (! monitor)) - { - list = 0; - test_finished (); - return; - } - if (! (list | monitor)) + { + fprintf(stderr, + "Could not set ego to `%s' for subsystem `%s', ego not known\n", + set_ego, + set_subsystem); + GNUNET_free(set_subsystem); + set_subsystem = NULL; + GNUNET_free(set_ego); + set_ego = NULL; + } + if ((NULL == ego) && (!monitor)) + { + list = 0; + test_finished(); + return; + } + if (!(list | monitor)) return; if ((NULL == ego) || (NULL == identifier)) return; - if ((NULL != set_ego) && (0 != strcmp (identifier, set_ego))) + if ((NULL != set_ego) && (0 != strcmp(identifier, set_ego))) return; - GNUNET_IDENTITY_ego_get_public_key (ego, &pk); - s = GNUNET_CRYPTO_ecdsa_public_key_to_string (&pk); - privs = GNUNET_CRYPTO_ecdsa_private_key_to_string ( - GNUNET_IDENTITY_ego_get_private_key (ego)); + GNUNET_IDENTITY_ego_get_public_key(ego, &pk); + s = GNUNET_CRYPTO_ecdsa_public_key_to_string(&pk); + privs = GNUNET_CRYPTO_ecdsa_private_key_to_string( + GNUNET_IDENTITY_ego_get_private_key(ego)); if ((monitor) || (NULL != identifier)) - { - if (quiet) { - if (private_keys) - fprintf (stdout, "%s - %s\n", s, privs); + if (quiet) + { + if (private_keys) + fprintf(stdout, "%s - %s\n", s, privs); + else + fprintf(stdout, "%s\n", s); + } else - fprintf (stdout, "%s\n", s); + { + if (private_keys) + fprintf(stdout, "%s - %s - %s\n", identifier, s, privs); + else + fprintf(stdout, "%s - %s\n", identifier, s); + } } - else - { - if (private_keys) - fprintf (stdout, "%s - %s - %s\n", identifier, s, privs); - else - fprintf (stdout, "%s - %s\n", identifier, s); - } - } - GNUNET_free (privs); - GNUNET_free (s); + GNUNET_free(privs); + GNUNET_free(s); } @@ -347,30 +347,30 @@ print_ego (void *cls, * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { if ((NULL != set_subsystem) && (NULL == set_ego)) - { - fprintf (stderr, "Option -s requires option -e to be specified as well.\n"); - return; - } - sh = GNUNET_IDENTITY_connect (cfg, - (monitor | list) || (NULL != set_ego) || - (NULL != set_subsystem) - ? &print_ego - : NULL, - NULL); + { + fprintf(stderr, "Option -s requires option -e to be specified as well.\n"); + return; + } + sh = GNUNET_IDENTITY_connect(cfg, + (monitor | list) || (NULL != set_ego) || + (NULL != set_subsystem) + ? &print_ego + : NULL, + NULL); if (NULL != delete_ego) delete_op = - GNUNET_IDENTITY_delete (sh, delete_ego, &delete_finished, &delete_op); + GNUNET_IDENTITY_delete(sh, delete_ego, &delete_finished, &delete_op); if (NULL != create_ego) create_op = - GNUNET_IDENTITY_create (sh, create_ego, &create_finished, &create_op); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); - test_finished (); + GNUNET_IDENTITY_create(sh, create_ego, &create_finished, &create_op); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); + test_finished(); } @@ -382,64 +382,64 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_string ('C', - "create", - "NAME", - gettext_noop ("create ego NAME"), - &create_ego), - GNUNET_GETOPT_option_string ('D', - "delete", - "NAME", - gettext_noop ("delete ego NAME "), - &delete_ego), - GNUNET_GETOPT_option_flag ('d', - "display", - gettext_noop ("display all egos"), - &list), - GNUNET_GETOPT_option_flag ('q', - "quiet", - gettext_noop ("reduce output"), - &quiet), - GNUNET_GETOPT_option_string ( - 'e', - "ego", - "NAME", - gettext_noop ( - "set default identity to NAME for a subsystem SUBSYSTEM (use together with -s) or restrict results to NAME (use together with -d)"), - &set_ego), - GNUNET_GETOPT_option_flag ('m', - "monitor", - gettext_noop ("run in monitor mode egos"), - &monitor), - GNUNET_GETOPT_option_flag ('p', - "private-keys", - gettext_noop ("display private keys as well"), - &private_keys), - GNUNET_GETOPT_option_string ( - 's', - "set", - "SUBSYSTEM", - gettext_noop ( - "set default identity to EGO for a subsystem SUBSYSTEM (use together with -e)"), - &set_subsystem), - GNUNET_GETOPT_option_verbose (&verbose), - GNUNET_GETOPT_OPTION_END}; + { GNUNET_GETOPT_option_string('C', + "create", + "NAME", + gettext_noop("create ego NAME"), + &create_ego), + GNUNET_GETOPT_option_string('D', + "delete", + "NAME", + gettext_noop("delete ego NAME "), + &delete_ego), + GNUNET_GETOPT_option_flag('d', + "display", + gettext_noop("display all egos"), + &list), + GNUNET_GETOPT_option_flag('q', + "quiet", + gettext_noop("reduce output"), + &quiet), + GNUNET_GETOPT_option_string( + 'e', + "ego", + "NAME", + gettext_noop( + "set default identity to NAME for a subsystem SUBSYSTEM (use together with -s) or restrict results to NAME (use together with -d)"), + &set_ego), + GNUNET_GETOPT_option_flag('m', + "monitor", + gettext_noop("run in monitor mode egos"), + &monitor), + GNUNET_GETOPT_option_flag('p', + "private-keys", + gettext_noop("display private keys as well"), + &private_keys), + GNUNET_GETOPT_option_string( + 's', + "set", + "SUBSYSTEM", + gettext_noop( + "set default identity to EGO for a subsystem SUBSYSTEM (use together with -e)"), + &set_subsystem), + GNUNET_GETOPT_option_verbose(&verbose), + GNUNET_GETOPT_OPTION_END }; int res; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 4; global_ret = TIMEOUT_STATUS_CODE; /* timeout */ - res = GNUNET_PROGRAM_run (argc, - argv, - "gnunet-identity", - gettext_noop ("Maintain egos"), - options, - &run, - NULL); - GNUNET_free ((void *) argv); + res = GNUNET_PROGRAM_run(argc, + argv, + "gnunet-identity", + gettext_noop("Maintain egos"), + options, + &run, + NULL); + GNUNET_free((void *)argv); if (GNUNET_OK != res) return 3; diff --git a/src/identity/gnunet-service-identity.c b/src/identity/gnunet-service-identity.c index 34fad3272..f399b2566 100644 --- a/src/identity/gnunet-service-identity.c +++ b/src/identity/gnunet-service-identity.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2013 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet. + Copyright (C) 2013 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -42,9 +42,7 @@ /** * Information we keep about each ego. */ -struct Ego -{ - +struct Ego { /** * We keep egos in a DLL. */ @@ -116,15 +114,15 @@ static struct Ego *ego_tail; * @return full filename for the given ego */ static char * -get_ego_filename (struct Ego *ego) +get_ego_filename(struct Ego *ego) { char *filename; - GNUNET_asprintf (&filename, - "%s%s%s", - ego_directory, - DIR_SEPARATOR_STR, - ego->identifier); + GNUNET_asprintf(&filename, + "%s%s%s", + ego_directory, + DIR_SEPARATOR_STR, + ego->identifier); return filename; } @@ -136,11 +134,11 @@ get_ego_filename (struct Ego *ego) * @param app_ctx @a client */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p disconnected\n", client); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Client %p disconnected\n", client); } @@ -153,9 +151,9 @@ client_disconnect_cb (void *cls, * @return internal namestore client structure for this client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { return client; } @@ -166,33 +164,33 @@ client_connect_cb (void *cls, * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { struct Ego *e; if (NULL != nc) - { - GNUNET_notification_context_destroy (nc); - nc = NULL; - } + { + GNUNET_notification_context_destroy(nc); + nc = NULL; + } if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, GNUNET_NO); - stats = NULL; - } - GNUNET_CONFIGURATION_destroy (subsystem_cfg); + { + GNUNET_STATISTICS_destroy(stats, GNUNET_NO); + stats = NULL; + } + GNUNET_CONFIGURATION_destroy(subsystem_cfg); subsystem_cfg = NULL; - GNUNET_free (subsystem_cfg_file); + GNUNET_free(subsystem_cfg_file); subsystem_cfg_file = NULL; - GNUNET_free (ego_directory); + GNUNET_free(ego_directory); ego_directory = NULL; while (NULL != (e = ego_head)) - { - GNUNET_CONTAINER_DLL_remove (ego_head, ego_tail, e); - GNUNET_free (e->pk); - GNUNET_free (e->identifier); - GNUNET_free (e); - } + { + GNUNET_CONTAINER_DLL_remove(ego_head, ego_tail, e); + GNUNET_free(e->pk); + GNUNET_free(e->identifier); + GNUNET_free(e); + } } @@ -204,9 +202,9 @@ shutdown_task (void *cls) * @param emsg error message to include (or NULL for none) */ static void -send_result_code (struct GNUNET_SERVICE_Client *client, - uint32_t result_code, - const char *emsg) +send_result_code(struct GNUNET_SERVICE_Client *client, + uint32_t result_code, + const char *emsg) { struct ResultCodeMessage *rcm; struct GNUNET_MQ_Envelope *env; @@ -215,17 +213,17 @@ send_result_code (struct GNUNET_SERVICE_Client *client, if (NULL == emsg) elen = 0; else - elen = strlen (emsg) + 1; + elen = strlen(emsg) + 1; env = - GNUNET_MQ_msg_extra (rcm, elen, GNUNET_MESSAGE_TYPE_IDENTITY_RESULT_CODE); - rcm->result_code = htonl (result_code); + GNUNET_MQ_msg_extra(rcm, elen, GNUNET_MESSAGE_TYPE_IDENTITY_RESULT_CODE); + rcm->result_code = htonl(result_code); if (0 < elen) - GNUNET_memcpy (&rcm[1], emsg, elen); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending result %d (%s) to client\n", - (int) result_code, - emsg); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); + GNUNET_memcpy(&rcm[1], emsg, elen); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending result %d (%s) to client\n", + (int)result_code, + emsg); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); } @@ -236,18 +234,18 @@ send_result_code (struct GNUNET_SERVICE_Client *client, * @return corresponding update message */ static struct GNUNET_MQ_Envelope * -create_update_message (struct Ego *ego) +create_update_message(struct Ego *ego) { struct UpdateMessage *um; struct GNUNET_MQ_Envelope *env; size_t name_len; - name_len = (NULL == ego->identifier) ? 0 : (strlen (ego->identifier) + 1); - env = GNUNET_MQ_msg_extra (um, name_len, GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE); - um->name_len = htons (name_len); - um->end_of_list = htons (GNUNET_NO); + name_len = (NULL == ego->identifier) ? 0 : (strlen(ego->identifier) + 1); + env = GNUNET_MQ_msg_extra(um, name_len, GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE); + um->name_len = htons(name_len); + um->end_of_list = htons(GNUNET_NO); um->private_key = *ego->pk; - GNUNET_memcpy (&um[1], ego->identifier, name_len); + GNUNET_memcpy(&um[1], ego->identifier, name_len); return env; } @@ -260,20 +258,20 @@ create_update_message (struct Ego *ego) * @return corresponding set default message */ static struct GNUNET_MQ_Envelope * -create_set_default_message (struct Ego *ego, const char *servicename) +create_set_default_message(struct Ego *ego, const char *servicename) { struct SetDefaultMessage *sdm; struct GNUNET_MQ_Envelope *env; size_t name_len; - name_len = (NULL == servicename) ? 0 : (strlen (servicename) + 1); - env = GNUNET_MQ_msg_extra (sdm, - name_len, - GNUNET_MESSAGE_TYPE_IDENTITY_SET_DEFAULT); - sdm->name_len = htons (name_len); - sdm->reserved = htons (0); + name_len = (NULL == servicename) ? 0 : (strlen(servicename) + 1); + env = GNUNET_MQ_msg_extra(sdm, + name_len, + GNUNET_MESSAGE_TYPE_IDENTITY_SET_DEFAULT); + sdm->name_len = htons(name_len); + sdm->reserved = htons(0); sdm->private_key = *ego->pk; - GNUNET_memcpy (&sdm[1], servicename, name_len); + GNUNET_memcpy(&sdm[1], servicename, name_len); return env; } @@ -288,27 +286,27 @@ create_set_default_message (struct Ego *ego, const char *servicename) * @param message the message received */ static void -handle_start_message (void *cls, const struct GNUNET_MessageHeader *message) +handle_start_message(void *cls, const struct GNUNET_MessageHeader *message) { struct GNUNET_SERVICE_Client *client = cls; struct UpdateMessage *ume; struct GNUNET_MQ_Envelope *env; struct Ego *ego; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received START message from client\n"); - GNUNET_SERVICE_client_mark_monitor (client); - GNUNET_SERVICE_client_disable_continue_warning (client); - GNUNET_notification_context_add (nc, GNUNET_SERVICE_client_get_mq (client)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received START message from client\n"); + GNUNET_SERVICE_client_mark_monitor(client); + GNUNET_SERVICE_client_disable_continue_warning(client); + GNUNET_notification_context_add(nc, GNUNET_SERVICE_client_get_mq(client)); for (ego = ego_head; NULL != ego; ego = ego->next) - { - env = create_update_message (ego); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); - } - env = GNUNET_MQ_msg_extra (ume, 0, GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE); - ume->end_of_list = htons (GNUNET_YES); - ume->name_len = htons (0); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); - GNUNET_SERVICE_client_continue (client); + { + env = create_update_message(ego); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); + } + env = GNUNET_MQ_msg_extra(ume, 0, GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE); + ume->end_of_list = htons(GNUNET_YES); + ume->name_len = htons(0); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); + GNUNET_SERVICE_client_continue(client); } @@ -321,9 +319,9 @@ handle_start_message (void *cls, const struct GNUNET_MessageHeader *message) * @return #GNUNET_SYSERR if message was ill-formed */ static int -check_lookup_message (void *cls, const struct LookupMessage *message) +check_lookup_message(void *cls, const struct LookupMessage *message) { - GNUNET_MQ_check_zero_termination (message); + GNUNET_MQ_check_zero_termination(message); return GNUNET_OK; } @@ -336,26 +334,26 @@ check_lookup_message (void *cls, const struct LookupMessage *message) * @param message the message received */ static void -handle_lookup_message (void *cls, const struct LookupMessage *message) +handle_lookup_message(void *cls, const struct LookupMessage *message) { struct GNUNET_SERVICE_Client *client = cls; const char *name; struct GNUNET_MQ_Envelope *env; struct Ego *ego; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received LOOKUP message from client\n"); - name = (const char *) &message[1]; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received LOOKUP message from client\n"); + name = (const char *)&message[1]; for (ego = ego_head; NULL != ego; ego = ego->next) - { - if (0 != strcasecmp (name, ego->identifier)) - continue; - env = create_update_message (ego); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); - GNUNET_SERVICE_client_continue (client); - return; - } - send_result_code (client, 0, "ego not found"); - GNUNET_SERVICE_client_continue (client); + { + if (0 != strcasecmp(name, ego->identifier)) + continue; + env = create_update_message(ego); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); + GNUNET_SERVICE_client_continue(client); + return; + } + send_result_code(client, 0, "ego not found"); + GNUNET_SERVICE_client_continue(client); } @@ -368,9 +366,9 @@ handle_lookup_message (void *cls, const struct LookupMessage *message) * @return #GNUNET_SYSERR if message was ill-formed */ static int -check_lookup_by_suffix_message (void *cls, const struct LookupMessage *message) +check_lookup_by_suffix_message(void *cls, const struct LookupMessage *message) { - GNUNET_MQ_check_zero_termination (message); + GNUNET_MQ_check_zero_termination(message); return GNUNET_OK; } @@ -383,41 +381,40 @@ check_lookup_by_suffix_message (void *cls, const struct LookupMessage *message) * @param message the message received */ static void -handle_lookup_by_suffix_message (void *cls, const struct LookupMessage *message) +handle_lookup_by_suffix_message(void *cls, const struct LookupMessage *message) { struct GNUNET_SERVICE_Client *client = cls; const char *name; struct GNUNET_MQ_Envelope *env; struct Ego *lprefix; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received LOOKUP_BY_SUFFIX message from client\n"); - name = (const char *) &message[1]; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received LOOKUP_BY_SUFFIX message from client\n"); + name = (const char *)&message[1]; lprefix = NULL; for (struct Ego *ego = ego_head; NULL != ego; ego = ego->next) - { - - if ((strlen (ego->identifier) <= strlen (name)) && - (0 == strcmp (ego->identifier, - &name[strlen (name) - strlen (ego->identifier)])) && - ((strlen (name) == strlen (ego->identifier)) || - ('.' == name[strlen (name) - strlen (ego->identifier) - 1])) && - ((NULL == lprefix) || - (strlen (ego->identifier) > strlen (lprefix->identifier)))) { - /* found better match, update! */ - lprefix = ego; + if ((strlen(ego->identifier) <= strlen(name)) && + (0 == strcmp(ego->identifier, + &name[strlen(name) - strlen(ego->identifier)])) && + ((strlen(name) == strlen(ego->identifier)) || + ('.' == name[strlen(name) - strlen(ego->identifier) - 1])) && + ((NULL == lprefix) || + (strlen(ego->identifier) > strlen(lprefix->identifier)))) + { + /* found better match, update! */ + lprefix = ego; + } } - } if (NULL != lprefix) - { - env = create_update_message (lprefix); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); - GNUNET_SERVICE_client_continue (client); - return; - } - send_result_code (client, 0, "ego not found"); - GNUNET_SERVICE_client_continue (client); + { + env = create_update_message(lprefix); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); + GNUNET_SERVICE_client_continue(client); + return; + } + send_result_code(client, 0, "ego not found"); + GNUNET_SERVICE_client_continue(client); } @@ -429,26 +426,26 @@ handle_lookup_by_suffix_message (void *cls, const struct LookupMessage *message) * @return #GNUNET_OK if @a msg is well-formed */ static int -check_get_default_message (void *cls, const struct GetDefaultMessage *msg) +check_get_default_message(void *cls, const struct GetDefaultMessage *msg) { uint16_t size; uint16_t name_len; const char *name; - size = ntohs (msg->header.size); - if (size <= sizeof (struct GetDefaultMessage)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - name = (const char *) &msg[1]; - name_len = ntohs (msg->name_len); - if ((name_len + sizeof (struct GetDefaultMessage) != size) || - (0 != ntohs (msg->reserved)) || ('\0' != name[name_len - 1])) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + size = ntohs(msg->header.size); + if (size <= sizeof(struct GetDefaultMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + name = (const char *)&msg[1]; + name_len = ntohs(msg->name_len); + if ((name_len + sizeof(struct GetDefaultMessage) != size) || + (0 != ntohs(msg->reserved)) || ('\0' != name[name_len - 1])) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -462,7 +459,7 @@ check_get_default_message (void *cls, const struct GetDefaultMessage *msg) * @param message the message received */ static void -handle_get_default_message (void *cls, const struct GetDefaultMessage *gdm) +handle_get_default_message(void *cls, const struct GetDefaultMessage *gdm) { struct GNUNET_MQ_Envelope *env; struct GNUNET_SERVICE_Client *client = cls; @@ -471,41 +468,41 @@ handle_get_default_message (void *cls, const struct GetDefaultMessage *gdm) char *identifier; - name = GNUNET_strdup ((const char *) &gdm[1]); - GNUNET_STRINGS_utf8_tolower ((const char *) &gdm[1], name); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received GET_DEFAULT for service `%s' from client\n", - name); - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (subsystem_cfg, - name, - "DEFAULT_IDENTIFIER", - &identifier)) - { - send_result_code (client, 1, gettext_noop ("no default known")); - GNUNET_SERVICE_client_continue (client); - GNUNET_free (name); - return; - } - for (ego = ego_head; NULL != ego; ego = ego->next) - { - if (0 == strcmp (ego->identifier, identifier)) + name = GNUNET_strdup((const char *)&gdm[1]); + GNUNET_STRINGS_utf8_tolower((const char *)&gdm[1], name); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received GET_DEFAULT for service `%s' from client\n", + name); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(subsystem_cfg, + name, + "DEFAULT_IDENTIFIER", + &identifier)) { - env = create_set_default_message (ego, name); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); - GNUNET_SERVICE_client_continue (client); - GNUNET_free (identifier); - GNUNET_free (name); + send_result_code(client, 1, gettext_noop("no default known")); + GNUNET_SERVICE_client_continue(client); + GNUNET_free(name); return; } - } - GNUNET_free (identifier); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Failed to find ego `%s'\n", name); - GNUNET_free (name); - send_result_code (client, - 1, - gettext_noop ( - "default configured, but ego unknown (internal error)")); - GNUNET_SERVICE_client_continue (client); + for (ego = ego_head; NULL != ego; ego = ego->next) + { + if (0 == strcmp(ego->identifier, identifier)) + { + env = create_set_default_message(ego, name); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); + GNUNET_SERVICE_client_continue(client); + GNUNET_free(identifier); + GNUNET_free(name); + return; + } + } + GNUNET_free(identifier); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Failed to find ego `%s'\n", name); + GNUNET_free(name); + send_result_code(client, + 1, + gettext_noop( + "default configured, but ego unknown (internal error)")); + GNUNET_SERVICE_client_continue(client); } @@ -517,10 +514,10 @@ handle_get_default_message (void *cls, const struct GetDefaultMessage *gdm) * @return 0 if the keys are equal */ static int -key_cmp (const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk1, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk2) +key_cmp(const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk1, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk2) { - return GNUNET_memcmp (pk1, pk2); + return GNUNET_memcmp(pk1, pk2); } /** @@ -531,31 +528,31 @@ key_cmp (const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk1, * @return #GNUNET_OK if @a msg is well-formed */ static int -check_set_default_message (void *cls, const struct SetDefaultMessage *msg) +check_set_default_message(void *cls, const struct SetDefaultMessage *msg) { uint16_t size; uint16_t name_len; const char *str; - size = ntohs (msg->header.size); - if (size <= sizeof (struct SetDefaultMessage)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - name_len = ntohs (msg->name_len); - GNUNET_break (0 == ntohs (msg->reserved)); - if (name_len + sizeof (struct SetDefaultMessage) != size) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - str = (const char *) &msg[1]; + size = ntohs(msg->header.size); + if (size <= sizeof(struct SetDefaultMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + name_len = ntohs(msg->name_len); + GNUNET_break(0 == ntohs(msg->reserved)); + if (name_len + sizeof(struct SetDefaultMessage) != size) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + str = (const char *)&msg[1]; if ('\0' != str[name_len - 1]) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -568,43 +565,43 @@ check_set_default_message (void *cls, const struct SetDefaultMessage *msg) * @param message the message received */ static void -handle_set_default_message (void *cls, const struct SetDefaultMessage *sdm) +handle_set_default_message(void *cls, const struct SetDefaultMessage *sdm) { struct Ego *ego; struct GNUNET_SERVICE_Client *client = cls; char *str; - str = GNUNET_strdup ((const char *) &sdm[1]); - GNUNET_STRINGS_utf8_tolower ((const char *) &sdm[1], str); + str = GNUNET_strdup((const char *)&sdm[1]); + GNUNET_STRINGS_utf8_tolower((const char *)&sdm[1], str); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received SET_DEFAULT for service `%s' from client\n", - str); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received SET_DEFAULT for service `%s' from client\n", + str); for (ego = ego_head; NULL != ego; ego = ego->next) - { - if (0 == key_cmp (ego->pk, &sdm->private_key)) { - GNUNET_CONFIGURATION_set_value_string (subsystem_cfg, - str, - "DEFAULT_IDENTIFIER", - ego->identifier); - if (GNUNET_OK != - GNUNET_CONFIGURATION_write (subsystem_cfg, subsystem_cfg_file)) - GNUNET_log ( - GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to write subsystem default identifier map to `%s'.\n"), - subsystem_cfg_file); - send_result_code (client, 0, NULL); - GNUNET_SERVICE_client_continue (client); - GNUNET_free (str); - return; + if (0 == key_cmp(ego->pk, &sdm->private_key)) + { + GNUNET_CONFIGURATION_set_value_string(subsystem_cfg, + str, + "DEFAULT_IDENTIFIER", + ego->identifier); + if (GNUNET_OK != + GNUNET_CONFIGURATION_write(subsystem_cfg, subsystem_cfg_file)) + GNUNET_log( + GNUNET_ERROR_TYPE_ERROR, + _("Failed to write subsystem default identifier map to `%s'.\n"), + subsystem_cfg_file); + send_result_code(client, 0, NULL); + GNUNET_SERVICE_client_continue(client); + GNUNET_free(str); + return; + } } - } - send_result_code (client, - 1, - _ ("Unknown ego specified for service (internal error)")); - GNUNET_free (str); - GNUNET_SERVICE_client_continue (client); + send_result_code(client, + 1, + _("Unknown ego specified for service (internal error)")); + GNUNET_free(str); + GNUNET_SERVICE_client_continue(client); } @@ -614,21 +611,21 @@ handle_set_default_message (void *cls, const struct SetDefaultMessage *sdm) * @param ego ego to send the update for */ static void -notify_listeners (struct Ego *ego) +notify_listeners(struct Ego *ego) { struct UpdateMessage *um; size_t name_len; - name_len = (NULL == ego->identifier) ? 0 : (strlen (ego->identifier) + 1); - um = GNUNET_malloc (sizeof (struct UpdateMessage) + name_len); - um->header.type = htons (GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE); - um->header.size = htons (sizeof (struct UpdateMessage) + name_len); - um->name_len = htons (name_len); - um->end_of_list = htons (GNUNET_NO); + name_len = (NULL == ego->identifier) ? 0 : (strlen(ego->identifier) + 1); + um = GNUNET_malloc(sizeof(struct UpdateMessage) + name_len); + um->header.type = htons(GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE); + um->header.size = htons(sizeof(struct UpdateMessage) + name_len); + um->name_len = htons(name_len); + um->end_of_list = htons(GNUNET_NO); um->private_key = *ego->pk; - GNUNET_memcpy (&um[1], ego->identifier, name_len); - GNUNET_notification_context_broadcast (nc, &um->header, GNUNET_NO); - GNUNET_free (um); + GNUNET_memcpy(&um[1], ego->identifier, name_len); + GNUNET_notification_context_broadcast(nc, &um->header, GNUNET_NO); + GNUNET_free(um); } /** @@ -639,32 +636,31 @@ notify_listeners (struct Ego *ego) * @return #GNUNET_OK if @a msg is well-formed */ static int -check_create_message (void *cls, const struct CreateRequestMessage *msg) +check_create_message(void *cls, const struct CreateRequestMessage *msg) { - uint16_t size; uint16_t name_len; const char *str; - size = ntohs (msg->header.size); - if (size <= sizeof (struct CreateRequestMessage)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - name_len = ntohs (msg->name_len); - GNUNET_break (0 == ntohs (msg->reserved)); - if (name_len + sizeof (struct CreateRequestMessage) != size) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - str = (const char *) &msg[1]; + size = ntohs(msg->header.size); + if (size <= sizeof(struct CreateRequestMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + name_len = ntohs(msg->name_len); + GNUNET_break(0 == ntohs(msg->reserved)); + if (name_len + sizeof(struct CreateRequestMessage) != size) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + str = (const char *)&msg[1]; if ('\0' != str[name_len - 1]) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -677,56 +673,55 @@ check_create_message (void *cls, const struct CreateRequestMessage *msg) * @param message the message received */ static void -handle_create_message (void *cls, const struct CreateRequestMessage *crm) +handle_create_message(void *cls, const struct CreateRequestMessage *crm) { struct GNUNET_SERVICE_Client *client = cls; struct Ego *ego; char *str; char *fn; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received CREATE message from client\n"); - str = GNUNET_strdup ((const char *) &crm[1]); - GNUNET_STRINGS_utf8_tolower ((const char *) &crm[1], str); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received CREATE message from client\n"); + str = GNUNET_strdup((const char *)&crm[1]); + GNUNET_STRINGS_utf8_tolower((const char *)&crm[1], str); for (ego = ego_head; NULL != ego; ego = ego->next) - { - if (0 == strcmp (ego->identifier, str)) { - send_result_code (client, - 1, - gettext_noop ( - "identifier already in use for another ego")); - GNUNET_SERVICE_client_continue (client); - GNUNET_free (str); - return; + if (0 == strcmp(ego->identifier, str)) + { + send_result_code(client, + 1, + gettext_noop( + "identifier already in use for another ego")); + GNUNET_SERVICE_client_continue(client); + GNUNET_free(str); + return; + } } - } - ego = GNUNET_new (struct Ego); - ego->pk = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPrivateKey); + ego = GNUNET_new(struct Ego); + ego->pk = GNUNET_new(struct GNUNET_CRYPTO_EcdsaPrivateKey); *ego->pk = crm->private_key; - ego->identifier = GNUNET_strdup (str); - GNUNET_CONTAINER_DLL_insert (ego_head, ego_tail, ego); - send_result_code (client, 0, NULL); - fn = get_ego_filename (ego); - (void) GNUNET_DISK_directory_create_for_file (fn); - if (sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey) != - GNUNET_DISK_fn_write (fn, - &crm->private_key, - sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey), - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "write", fn); - GNUNET_free (fn); - GNUNET_free (str); - notify_listeners (ego); - GNUNET_SERVICE_client_continue (client); + ego->identifier = GNUNET_strdup(str); + GNUNET_CONTAINER_DLL_insert(ego_head, ego_tail, ego); + send_result_code(client, 0, NULL); + fn = get_ego_filename(ego); + (void)GNUNET_DISK_directory_create_for_file(fn); + if (sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey) != + GNUNET_DISK_fn_write(fn, + &crm->private_key, + sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey), + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "write", fn); + GNUNET_free(fn); + GNUNET_free(str); + notify_listeners(ego); + GNUNET_SERVICE_client_continue(client); } /** * Closure for 'handle_ego_rename'. */ -struct RenameContext -{ +struct RenameContext { /** * Old name. */ @@ -746,26 +741,26 @@ struct RenameContext * @param section a section in the configuration to process */ static void -handle_ego_rename (void *cls, const char *section) +handle_ego_rename(void *cls, const char *section) { struct RenameContext *rc = cls; char *id; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (subsystem_cfg, - section, - "DEFAULT_IDENTIFIER", - &id)) + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(subsystem_cfg, + section, + "DEFAULT_IDENTIFIER", + &id)) return; - if (0 != strcmp (id, rc->old_name)) - { - GNUNET_free (id); - return; - } - GNUNET_CONFIGURATION_set_value_string (subsystem_cfg, - section, - "DEFAULT_IDENTIFIER", - rc->new_name); - GNUNET_free (id); + if (0 != strcmp(id, rc->old_name)) + { + GNUNET_free(id); + return; + } + GNUNET_CONFIGURATION_set_value_string(subsystem_cfg, + section, + "DEFAULT_IDENTIFIER", + rc->new_name); + GNUNET_free(id); } /** @@ -776,7 +771,7 @@ handle_ego_rename (void *cls, const char *section) * @return #GNUNET_OK if @a msg is well-formed */ static int -check_rename_message (void *cls, const struct RenameMessage *msg) +check_rename_message(void *cls, const struct RenameMessage *msg) { uint16_t size; uint16_t old_name_len; @@ -784,23 +779,23 @@ check_rename_message (void *cls, const struct RenameMessage *msg) const char *old_name; const char *new_name; - size = ntohs (msg->header.size); - if (size <= sizeof (struct RenameMessage)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - old_name_len = ntohs (msg->old_name_len); - new_name_len = ntohs (msg->new_name_len); - old_name = (const char *) &msg[1]; + size = ntohs(msg->header.size); + if (size <= sizeof(struct RenameMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + old_name_len = ntohs(msg->old_name_len); + new_name_len = ntohs(msg->new_name_len); + old_name = (const char *)&msg[1]; new_name = &old_name[old_name_len]; - if ((old_name_len + new_name_len + sizeof (struct RenameMessage) != size) || + if ((old_name_len + new_name_len + sizeof(struct RenameMessage) != size) || ('\0' != old_name[old_name_len - 1]) || ('\0' != new_name[new_name_len - 1])) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -815,7 +810,7 @@ check_rename_message (void *cls, const struct RenameMessage *msg) * @param message the message received */ static void -handle_rename_message (void *cls, const struct RenameMessage *rm) +handle_rename_message(void *cls, const struct RenameMessage *rm) { uint16_t old_name_len; struct Ego *ego; @@ -827,65 +822,65 @@ handle_rename_message (void *cls, const struct RenameMessage *rm) char *fn_new; const char *old_name_tmp; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received RENAME message from client\n"); - old_name_len = ntohs (rm->old_name_len); - old_name_tmp = (const char *) &rm[1]; - old_name = GNUNET_strdup (old_name_tmp); - GNUNET_STRINGS_utf8_tolower (old_name_tmp, old_name); - new_name = GNUNET_strdup (&old_name_tmp[old_name_len]); - GNUNET_STRINGS_utf8_tolower (&old_name_tmp[old_name_len], new_name); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received RENAME message from client\n"); + old_name_len = ntohs(rm->old_name_len); + old_name_tmp = (const char *)&rm[1]; + old_name = GNUNET_strdup(old_name_tmp); + GNUNET_STRINGS_utf8_tolower(old_name_tmp, old_name); + new_name = GNUNET_strdup(&old_name_tmp[old_name_len]); + GNUNET_STRINGS_utf8_tolower(&old_name_tmp[old_name_len], new_name); /* check if new name is already in use */ for (ego = ego_head; NULL != ego; ego = ego->next) - { - if (0 == strcmp (ego->identifier, new_name)) { - send_result_code (client, 1, gettext_noop ("target name already exists")); - GNUNET_SERVICE_client_continue (client); - GNUNET_free (old_name); - GNUNET_free (new_name); - return; + if (0 == strcmp(ego->identifier, new_name)) + { + send_result_code(client, 1, gettext_noop("target name already exists")); + GNUNET_SERVICE_client_continue(client); + GNUNET_free(old_name); + GNUNET_free(new_name); + return; + } } - } /* locate old name and, if found, perform rename */ for (ego = ego_head; NULL != ego; ego = ego->next) - { - if (0 == strcmp (ego->identifier, old_name)) { - fn_old = get_ego_filename (ego); - GNUNET_free (ego->identifier); - rename_ctx.old_name = old_name; - rename_ctx.new_name = new_name; - GNUNET_CONFIGURATION_iterate_sections (subsystem_cfg, - &handle_ego_rename, - &rename_ctx); - if (GNUNET_OK != - GNUNET_CONFIGURATION_write (subsystem_cfg, subsystem_cfg_file)) - GNUNET_log ( - GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to write subsystem default identifier map to `%s'.\n"), - subsystem_cfg_file); - ego->identifier = GNUNET_strdup (new_name); - fn_new = get_ego_filename (ego); - if (0 != rename (fn_old, fn_new)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rename", fn_old); - GNUNET_free (fn_old); - GNUNET_free (fn_new); - GNUNET_free (old_name); - GNUNET_free (new_name); - notify_listeners (ego); - send_result_code (client, 0, NULL); - GNUNET_SERVICE_client_continue (client); - return; + if (0 == strcmp(ego->identifier, old_name)) + { + fn_old = get_ego_filename(ego); + GNUNET_free(ego->identifier); + rename_ctx.old_name = old_name; + rename_ctx.new_name = new_name; + GNUNET_CONFIGURATION_iterate_sections(subsystem_cfg, + &handle_ego_rename, + &rename_ctx); + if (GNUNET_OK != + GNUNET_CONFIGURATION_write(subsystem_cfg, subsystem_cfg_file)) + GNUNET_log( + GNUNET_ERROR_TYPE_ERROR, + _("Failed to write subsystem default identifier map to `%s'.\n"), + subsystem_cfg_file); + ego->identifier = GNUNET_strdup(new_name); + fn_new = get_ego_filename(ego); + if (0 != rename(fn_old, fn_new)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "rename", fn_old); + GNUNET_free(fn_old); + GNUNET_free(fn_new); + GNUNET_free(old_name); + GNUNET_free(new_name); + notify_listeners(ego); + send_result_code(client, 0, NULL); + GNUNET_SERVICE_client_continue(client); + return; + } } - } /* failed to locate old name */ - send_result_code (client, 1, gettext_noop ("no matching ego found")); - GNUNET_free (old_name); - GNUNET_free (new_name); - GNUNET_SERVICE_client_continue (client); + send_result_code(client, 1, gettext_noop("no matching ego found")); + GNUNET_free(old_name); + GNUNET_free(new_name); + GNUNET_SERVICE_client_continue(client); } @@ -897,26 +892,26 @@ handle_rename_message (void *cls, const struct RenameMessage *rm) * @param section a section in the configuration to process */ static void -handle_ego_delete (void *cls, const char *section) +handle_ego_delete(void *cls, const char *section) { const char *identifier = cls; char *id; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (subsystem_cfg, - section, - "DEFAULT_IDENTIFIER", - &id)) + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(subsystem_cfg, + section, + "DEFAULT_IDENTIFIER", + &id)) return; - if (0 != strcmp (id, identifier)) - { - GNUNET_free (id); - return; - } - GNUNET_CONFIGURATION_set_value_string (subsystem_cfg, - section, - "DEFAULT_IDENTIFIER", - NULL); - GNUNET_free (id); + if (0 != strcmp(id, identifier)) + { + GNUNET_free(id); + return; + } + GNUNET_CONFIGURATION_set_value_string(subsystem_cfg, + section, + "DEFAULT_IDENTIFIER", + NULL); + GNUNET_free(id); } /** @@ -927,26 +922,26 @@ handle_ego_delete (void *cls, const char *section) * @return #GNUNET_OK if @a msg is well-formed */ static int -check_delete_message (void *cls, const struct DeleteMessage *msg) +check_delete_message(void *cls, const struct DeleteMessage *msg) { uint16_t size; uint16_t name_len; const char *name; - size = ntohs (msg->header.size); - if (size <= sizeof (struct DeleteMessage)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - name = (const char *) &msg[1]; - name_len = ntohs (msg->name_len); - if ((name_len + sizeof (struct DeleteMessage) != size) || - (0 != ntohs (msg->reserved)) || ('\0' != name[name_len - 1])) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + size = ntohs(msg->header.size); + if (size <= sizeof(struct DeleteMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + name = (const char *)&msg[1]; + name_len = ntohs(msg->name_len); + if ((name_len + sizeof(struct DeleteMessage) != size) || + (0 != ntohs(msg->reserved)) || ('\0' != name[name_len - 1])) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -960,50 +955,50 @@ check_delete_message (void *cls, const struct DeleteMessage *msg) * @param message the message received */ static void -handle_delete_message (void *cls, const struct DeleteMessage *dm) +handle_delete_message(void *cls, const struct DeleteMessage *dm) { struct Ego *ego; char *name; char *fn; struct GNUNET_SERVICE_Client *client = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received DELETE message from client\n"); - name = GNUNET_strdup ((const char *) &dm[1]); - GNUNET_STRINGS_utf8_tolower ((const char *) &dm[1], name); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received DELETE message from client\n"); + name = GNUNET_strdup((const char *)&dm[1]); + GNUNET_STRINGS_utf8_tolower((const char *)&dm[1], name); for (ego = ego_head; NULL != ego; ego = ego->next) - { - if (0 == strcmp (ego->identifier, name)) { - GNUNET_CONTAINER_DLL_remove (ego_head, ego_tail, ego); - GNUNET_CONFIGURATION_iterate_sections (subsystem_cfg, - &handle_ego_delete, - ego->identifier); - if (GNUNET_OK != - GNUNET_CONFIGURATION_write (subsystem_cfg, subsystem_cfg_file)) - GNUNET_log ( - GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to write subsystem default identifier map to `%s'.\n"), - subsystem_cfg_file); - fn = get_ego_filename (ego); - if (0 != unlink (fn)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn); - GNUNET_free (fn); - GNUNET_free (ego->identifier); - ego->identifier = NULL; - notify_listeners (ego); - GNUNET_free (ego->pk); - GNUNET_free (ego); - GNUNET_free (name); - send_result_code (client, 0, NULL); - GNUNET_SERVICE_client_continue (client); - return; + if (0 == strcmp(ego->identifier, name)) + { + GNUNET_CONTAINER_DLL_remove(ego_head, ego_tail, ego); + GNUNET_CONFIGURATION_iterate_sections(subsystem_cfg, + &handle_ego_delete, + ego->identifier); + if (GNUNET_OK != + GNUNET_CONFIGURATION_write(subsystem_cfg, subsystem_cfg_file)) + GNUNET_log( + GNUNET_ERROR_TYPE_ERROR, + _("Failed to write subsystem default identifier map to `%s'.\n"), + subsystem_cfg_file); + fn = get_ego_filename(ego); + if (0 != unlink(fn)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", fn); + GNUNET_free(fn); + GNUNET_free(ego->identifier); + ego->identifier = NULL; + notify_listeners(ego); + GNUNET_free(ego->pk); + GNUNET_free(ego); + GNUNET_free(name); + send_result_code(client, 0, NULL); + GNUNET_SERVICE_client_continue(client); + return; + } } - } - send_result_code (client, 1, gettext_noop ("no matching ego found")); - GNUNET_free (name); - GNUNET_SERVICE_client_continue (client); + send_result_code(client, 1, gettext_noop("no matching ego found")); + GNUNET_free(name); + GNUNET_SERVICE_client_continue(client); } @@ -1018,30 +1013,30 @@ handle_delete_message (void *cls, const struct DeleteMessage *dm) * #GNUNET_SYSERR to abort iteration with error! */ static int -process_ego_file (void *cls, const char *filename) +process_ego_file(void *cls, const char *filename) { struct Ego *ego; const char *fn; - fn = strrchr (filename, (int) DIR_SEPARATOR); + fn = strrchr(filename, (int)DIR_SEPARATOR); if (NULL == fn) - { - GNUNET_break (0); - return GNUNET_OK; - } - ego = GNUNET_new (struct Ego); - ego->pk = GNUNET_CRYPTO_ecdsa_key_create_from_file (filename); + { + GNUNET_break(0); + return GNUNET_OK; + } + ego = GNUNET_new(struct Ego); + ego->pk = GNUNET_CRYPTO_ecdsa_key_create_from_file(filename); if (NULL == ego->pk) - { - GNUNET_free (ego); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to parse ego information in `%s'\n"), - filename); - return GNUNET_OK; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Loaded ego `%s'\n", fn + 1); - ego->identifier = GNUNET_strdup (fn + 1); - GNUNET_CONTAINER_DLL_insert (ego_head, ego_tail, ego); + { + GNUNET_free(ego); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to parse ego information in `%s'\n"), + filename); + return GNUNET_OK; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Loaded ego `%s'\n", fn + 1); + ego->identifier = GNUNET_strdup(fn + 1); + GNUNET_CONTAINER_DLL_insert(ego_head, ego_tail, ego); return GNUNET_OK; } @@ -1054,103 +1049,103 @@ process_ego_file (void *cls, const char *filename) * @param c configuration to use */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *service) { cfg = c; - nc = GNUNET_notification_context_create (1); - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, - "identity", - "EGODIR", - &ego_directory)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "identity", "EGODIR"); - GNUNET_SCHEDULER_shutdown (); - return; - } + nc = GNUNET_notification_context_create(1); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(cfg, + "identity", + "EGODIR", + &ego_directory)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "identity", "EGODIR"); + GNUNET_SCHEDULER_shutdown(); + return; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (cfg, - "identity", - "SUBSYSTEM_CFG", - &subsystem_cfg_file)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "identity", - "SUBSYSTEM_CFG"); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Loading subsystem configuration `%s'\n", - subsystem_cfg_file); - subsystem_cfg = GNUNET_CONFIGURATION_create (); - if ((GNUNET_YES == GNUNET_DISK_file_test (subsystem_cfg_file)) && + GNUNET_CONFIGURATION_get_value_filename(cfg, + "identity", + "SUBSYSTEM_CFG", + &subsystem_cfg_file)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "identity", + "SUBSYSTEM_CFG"); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Loading subsystem configuration `%s'\n", + subsystem_cfg_file); + subsystem_cfg = GNUNET_CONFIGURATION_create(); + if ((GNUNET_YES == GNUNET_DISK_file_test(subsystem_cfg_file)) && (GNUNET_OK != - GNUNET_CONFIGURATION_parse (subsystem_cfg, subsystem_cfg_file))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ( - "Failed to parse subsystem identity configuration file `%s'\n"), - subsystem_cfg_file); - GNUNET_SCHEDULER_shutdown (); - return; - } - stats = GNUNET_STATISTICS_create ("identity", cfg); - if (GNUNET_OK != GNUNET_DISK_directory_create (ego_directory)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to create directory `%s' for storing egos\n"), - ego_directory); - } - GNUNET_DISK_directory_scan (ego_directory, &process_ego_file, NULL); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + GNUNET_CONFIGURATION_parse(subsystem_cfg, subsystem_cfg_file))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _( + "Failed to parse subsystem identity configuration file `%s'\n"), + subsystem_cfg_file); + GNUNET_SCHEDULER_shutdown(); + return; + } + stats = GNUNET_STATISTICS_create("identity", cfg); + if (GNUNET_OK != GNUNET_DISK_directory_create(ego_directory)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to create directory `%s' for storing egos\n"), + ego_directory); + } + GNUNET_DISK_directory_scan(ego_directory, &process_ego_file, NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); } /** * Define "main" method using service macro. */ -GNUNET_SERVICE_MAIN ( +GNUNET_SERVICE_MAIN( "identity", GNUNET_SERVICE_OPTION_NONE, &run, &client_connect_cb, &client_disconnect_cb, NULL, - GNUNET_MQ_hd_fixed_size (start_message, - GNUNET_MESSAGE_TYPE_IDENTITY_START, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_hd_var_size (lookup_message, - GNUNET_MESSAGE_TYPE_IDENTITY_LOOKUP, - struct LookupMessage, - NULL), - GNUNET_MQ_hd_var_size (lookup_by_suffix_message, - GNUNET_MESSAGE_TYPE_IDENTITY_LOOKUP_BY_SUFFIX, - struct LookupMessage, - NULL), - GNUNET_MQ_hd_var_size (get_default_message, - GNUNET_MESSAGE_TYPE_IDENTITY_GET_DEFAULT, - struct GetDefaultMessage, - NULL), - GNUNET_MQ_hd_var_size (set_default_message, - GNUNET_MESSAGE_TYPE_IDENTITY_SET_DEFAULT, - struct SetDefaultMessage, - NULL), - GNUNET_MQ_hd_var_size (create_message, - GNUNET_MESSAGE_TYPE_IDENTITY_CREATE, - struct CreateRequestMessage, - NULL), - GNUNET_MQ_hd_var_size (rename_message, - GNUNET_MESSAGE_TYPE_IDENTITY_RENAME, - struct RenameMessage, - NULL), - GNUNET_MQ_hd_var_size (delete_message, - GNUNET_MESSAGE_TYPE_IDENTITY_DELETE, - struct DeleteMessage, - NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_hd_fixed_size(start_message, + GNUNET_MESSAGE_TYPE_IDENTITY_START, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_hd_var_size(lookup_message, + GNUNET_MESSAGE_TYPE_IDENTITY_LOOKUP, + struct LookupMessage, + NULL), + GNUNET_MQ_hd_var_size(lookup_by_suffix_message, + GNUNET_MESSAGE_TYPE_IDENTITY_LOOKUP_BY_SUFFIX, + struct LookupMessage, + NULL), + GNUNET_MQ_hd_var_size(get_default_message, + GNUNET_MESSAGE_TYPE_IDENTITY_GET_DEFAULT, + struct GetDefaultMessage, + NULL), + GNUNET_MQ_hd_var_size(set_default_message, + GNUNET_MESSAGE_TYPE_IDENTITY_SET_DEFAULT, + struct SetDefaultMessage, + NULL), + GNUNET_MQ_hd_var_size(create_message, + GNUNET_MESSAGE_TYPE_IDENTITY_CREATE, + struct CreateRequestMessage, + NULL), + GNUNET_MQ_hd_var_size(rename_message, + GNUNET_MESSAGE_TYPE_IDENTITY_RENAME, + struct RenameMessage, + NULL), + GNUNET_MQ_hd_var_size(delete_message, + GNUNET_MESSAGE_TYPE_IDENTITY_DELETE, + struct DeleteMessage, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-identity.c */ diff --git a/src/identity/identity.h b/src/identity/identity.h index 6ef16e39d..6a4090ad8 100644 --- a/src/identity/identity.h +++ b/src/identity/identity.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -39,8 +39,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * GET_DEFAULT maybe answered with this message on failure; * CREATE and RENAME will always be answered with this message. */ -struct ResultCodeMessage -{ +struct ResultCodeMessage { /** * Type: #GNUNET_MESSAGE_TYPE_IDENTITY_RESULT_CODE */ @@ -59,8 +58,7 @@ struct ResultCodeMessage /** * Client informs service about desire to lookup a (single) pseudonym. */ -struct LookupMessage -{ +struct LookupMessage { /** * Type: #GNUNET_MESSAGE_TYPE_IDENTITY_LOOKUP or * #GNUNET_MESSAGE_TYPE_IDENTITY_LOOKUP_BY_SUFFIX @@ -74,8 +72,7 @@ struct LookupMessage /** * Service informs client about status of a pseudonym. */ -struct UpdateMessage -{ +struct UpdateMessage { /** * Type: #GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE */ @@ -105,8 +102,7 @@ struct UpdateMessage * Client requests knowledge about default identity for * a subsystem from identity service. */ -struct GetDefaultMessage -{ +struct GetDefaultMessage { /** * Type: #GNUNET_MESSAGE_TYPE_IDENTITY_GET_DEFAULT */ @@ -131,8 +127,7 @@ struct GetDefaultMessage * Used from service to client as a result to the GET_DEFAULT * message, used from client to service to SET_DEFAULT. */ -struct SetDefaultMessage -{ +struct SetDefaultMessage { /** * Type: #GNUNET_MESSAGE_TYPE_IDENTITY_SET_DEFAULT */ @@ -161,8 +156,7 @@ struct SetDefaultMessage * Client requests creation of an identity. Service * will respond with a result code. */ -struct CreateRequestMessage -{ +struct CreateRequestMessage { /** * Type: #GNUNET_MESSAGE_TYPE_IDENTITY_CREATE */ @@ -191,8 +185,7 @@ struct CreateRequestMessage * Client requests renaming of an identity. Service * will respond with a result code. */ -struct RenameMessage -{ +struct RenameMessage { /** * Type: #GNUNET_MESSAGE_TYPE_IDENTITY_RENAME */ @@ -217,8 +210,7 @@ struct RenameMessage * Client requests deletion of an identity. Service * will respond with a result code. */ -struct DeleteMessage -{ +struct DeleteMessage { /** * Type: #GNUNET_MESSAGE_TYPE_IDENTITY_DELETE */ @@ -242,8 +234,7 @@ GNUNET_NETWORK_STRUCT_END /** * Handle for an ego. */ -struct GNUNET_IDENTITY_Ego -{ +struct GNUNET_IDENTITY_Ego { /** * Private key associated with this ego. */ diff --git a/src/identity/identity_api.c b/src/identity/identity_api.c index c463da641..530ee2d13 100644 --- a/src/identity/identity_api.c +++ b/src/identity/identity_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file identity/identity_api.c @@ -30,15 +30,13 @@ #include "gnunet_identity_service.h" #include "identity.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "identity-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "identity-api", __VA_ARGS__) /** * Handle for an operation with the identity service. */ -struct GNUNET_IDENTITY_Operation -{ - +struct GNUNET_IDENTITY_Operation { /** * Main identity handle. */ @@ -93,8 +91,7 @@ struct GNUNET_IDENTITY_Operation /** * Handle for the service. */ -struct GNUNET_IDENTITY_Handle -{ +struct GNUNET_IDENTITY_Handle { /** * Configuration to use. */ @@ -154,7 +151,7 @@ struct GNUNET_IDENTITY_Handle * @return handle for the anonymous user, must not be freed */ const struct GNUNET_IDENTITY_Ego * -GNUNET_IDENTITY_ego_get_anonymous () +GNUNET_IDENTITY_ego_get_anonymous() { static struct GNUNET_IDENTITY_Ego anon; struct GNUNET_CRYPTO_EcdsaPublicKey pub; @@ -162,9 +159,9 @@ GNUNET_IDENTITY_ego_get_anonymous () if (NULL != anon.pk) return &anon; anon.pk = (struct GNUNET_CRYPTO_EcdsaPrivateKey *) - GNUNET_CRYPTO_ecdsa_key_get_anonymous (); - GNUNET_CRYPTO_ecdsa_key_get_public (anon.pk, &pub); - GNUNET_CRYPTO_hash (&pub, sizeof (pub), &anon.id); + GNUNET_CRYPTO_ecdsa_key_get_anonymous(); + GNUNET_CRYPTO_ecdsa_key_get_public(anon.pk, &pub); + GNUNET_CRYPTO_hash(&pub, sizeof(pub), &anon.id); return &anon; } @@ -175,7 +172,7 @@ GNUNET_IDENTITY_ego_get_anonymous () * @param cls handle to the identity service. */ static void -reconnect (void *cls); +reconnect(void *cls); /** @@ -187,18 +184,18 @@ reconnect (void *cls); * @return #GNUNET_OK (continue to iterate) */ static int -free_ego (void *cls, const struct GNUNET_HashCode *key, void *value) +free_ego(void *cls, const struct GNUNET_HashCode *key, void *value) { struct GNUNET_IDENTITY_Handle *h = cls; struct GNUNET_IDENTITY_Ego *ego = value; if (NULL != h->cb) - h->cb (h->cb_cls, ego, &ego->ctx, NULL); - GNUNET_free (ego->pk); - GNUNET_free (ego->name); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (h->egos, key, value)); - GNUNET_free (ego); + h->cb(h->cb_cls, ego, &ego->ctx, NULL); + GNUNET_free(ego->pk); + GNUNET_free(ego->name); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(h->egos, key, value)); + GNUNET_free(ego); return GNUNET_OK; } @@ -209,38 +206,38 @@ free_ego (void *cls, const struct GNUNET_HashCode *key, void *value) * @param h transport service to reconnect */ static void -reschedule_connect (struct GNUNET_IDENTITY_Handle *h) +reschedule_connect(struct GNUNET_IDENTITY_Handle *h) { struct GNUNET_IDENTITY_Operation *op; - GNUNET_assert (NULL == h->reconnect_task); + GNUNET_assert(NULL == h->reconnect_task); if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } while (NULL != (op = h->op_head)) - { - GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, op); - if (NULL != op->cont) - op->cont (op->cls, "Error in communication with the identity service"); - else if (NULL != op->cb) - op->cb (op->cls, NULL, NULL, NULL); - else if (NULL != op->create_cont) - op->create_cont (op->cls, - NULL, - "Failed to communicate with the identity service"); - GNUNET_free_non_null (op->pk); - GNUNET_free (op); - } - GNUNET_CONTAINER_multihashmap_iterate (h->egos, &free_ego, h); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Scheduling task to reconnect to identity service in %s.\n", - GNUNET_STRINGS_relative_time_to_string (h->reconnect_delay, GNUNET_YES)); + { + GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, op); + if (NULL != op->cont) + op->cont(op->cls, "Error in communication with the identity service"); + else if (NULL != op->cb) + op->cb(op->cls, NULL, NULL, NULL); + else if (NULL != op->create_cont) + op->create_cont(op->cls, + NULL, + "Failed to communicate with the identity service"); + GNUNET_free_non_null(op->pk); + GNUNET_free(op); + } + GNUNET_CONTAINER_multihashmap_iterate(h->egos, &free_ego, h); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Scheduling task to reconnect to identity service in %s.\n", + GNUNET_STRINGS_relative_time_to_string(h->reconnect_delay, GNUNET_YES)); h->reconnect_task = - GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, &reconnect, h); - h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay); + GNUNET_SCHEDULER_add_delayed(h->reconnect_delay, &reconnect, h); + h->reconnect_delay = GNUNET_TIME_STD_BACKOFF(h->reconnect_delay); } @@ -253,11 +250,11 @@ reschedule_connect (struct GNUNET_IDENTITY_Handle *h) * @param error error code */ static void -mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_IDENTITY_Handle *h = cls; - reschedule_connect (h); + reschedule_connect(h); } @@ -270,10 +267,10 @@ mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @return #GNUNET_OK if the message is well-formed */ static int -check_identity_result_code (void *cls, const struct ResultCodeMessage *rcm) +check_identity_result_code(void *cls, const struct ResultCodeMessage *rcm) { - if (sizeof (*rcm) != htons (rcm->header.size)) - GNUNET_MQ_check_zero_termination (rcm); + if (sizeof(*rcm) != htons(rcm->header.size)) + GNUNET_MQ_check_zero_termination(rcm); return GNUNET_OK; } @@ -285,29 +282,29 @@ check_identity_result_code (void *cls, const struct ResultCodeMessage *rcm) * @param rcm result message received */ static void -handle_identity_result_code (void *cls, const struct ResultCodeMessage *rcm) +handle_identity_result_code(void *cls, const struct ResultCodeMessage *rcm) { struct GNUNET_IDENTITY_Handle *h = cls; struct GNUNET_IDENTITY_Operation *op; - uint16_t size = ntohs (rcm->header.size) - sizeof (*rcm); - const char *str = (0 == size) ? NULL : (const char *) &rcm[1]; + uint16_t size = ntohs(rcm->header.size) - sizeof(*rcm); + const char *str = (0 == size) ? NULL : (const char *)&rcm[1]; op = h->op_head; if (NULL == op) - { - GNUNET_break (0); - reschedule_connect (h); - return; - } - GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, op); + { + GNUNET_break(0); + reschedule_connect(h); + return; + } + GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, op); if (NULL != op->cont) - op->cont (op->cls, str); + op->cont(op->cls, str); else if (NULL != op->cb) - op->cb (op->cls, NULL, NULL, NULL); + op->cb(op->cls, NULL, NULL, NULL); else if (NULL != op->create_cont) - op->create_cont (op->cls, (NULL == str) ? op->pk : NULL, str); - GNUNET_free_non_null (op->pk); - GNUNET_free (op); + op->create_cont(op->cls, (NULL == str) ? op->pk : NULL, str); + GNUNET_free_non_null(op->pk); + GNUNET_free(op); } @@ -319,18 +316,18 @@ handle_identity_result_code (void *cls, const struct ResultCodeMessage *rcm) * @return #GNUNET_OK if the message is well-formed */ static int -check_identity_update (void *cls, const struct UpdateMessage *um) +check_identity_update(void *cls, const struct UpdateMessage *um) { - uint16_t size = ntohs (um->header.size); - uint16_t name_len = ntohs (um->name_len); - const char *str = (const char *) &um[1]; + uint16_t size = ntohs(um->header.size); + uint16_t name_len = ntohs(um->name_len); + const char *str = (const char *)&um[1]; - if ((size != name_len + sizeof (struct UpdateMessage)) || + if ((size != name_len + sizeof(struct UpdateMessage)) || ((0 != name_len) && ('\0' != str[name_len - 1]))) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -342,70 +339,70 @@ check_identity_update (void *cls, const struct UpdateMessage *um) * @param um message received */ static void -handle_identity_update (void *cls, const struct UpdateMessage *um) +handle_identity_update(void *cls, const struct UpdateMessage *um) { struct GNUNET_IDENTITY_Handle *h = cls; - uint16_t name_len = ntohs (um->name_len); - const char *str = (0 == name_len) ? NULL : (const char *) &um[1]; + uint16_t name_len = ntohs(um->name_len); + const char *str = (0 == name_len) ? NULL : (const char *)&um[1]; struct GNUNET_CRYPTO_EcdsaPublicKey pub; struct GNUNET_HashCode id; struct GNUNET_IDENTITY_Ego *ego; - if (GNUNET_YES == ntohs (um->end_of_list)) - { - /* end of initial list of data */ - if (NULL != h->cb) - h->cb (h->cb_cls, NULL, NULL, NULL); - return; - } - GNUNET_CRYPTO_ecdsa_key_get_public (&um->private_key, &pub); - GNUNET_CRYPTO_hash (&pub, sizeof (pub), &id); - ego = GNUNET_CONTAINER_multihashmap_get (h->egos, &id); - if (NULL == ego) - { - /* ego was created */ - if (NULL == str) + if (GNUNET_YES == ntohs(um->end_of_list)) { - /* deletion of unknown ego? not allowed */ - GNUNET_break (0); - reschedule_connect (h); + /* end of initial list of data */ + if (NULL != h->cb) + h->cb(h->cb_cls, NULL, NULL, NULL); return; } - ego = GNUNET_new (struct GNUNET_IDENTITY_Ego); - ego->pk = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPrivateKey); - *ego->pk = um->private_key; - ego->name = GNUNET_strdup (str); - ego->id = id; - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_put ( - h->egos, - &ego->id, - ego, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - } + GNUNET_CRYPTO_ecdsa_key_get_public(&um->private_key, &pub); + GNUNET_CRYPTO_hash(&pub, sizeof(pub), &id); + ego = GNUNET_CONTAINER_multihashmap_get(h->egos, &id); + if (NULL == ego) + { + /* ego was created */ + if (NULL == str) + { + /* deletion of unknown ego? not allowed */ + GNUNET_break(0); + reschedule_connect(h); + return; + } + ego = GNUNET_new(struct GNUNET_IDENTITY_Ego); + ego->pk = GNUNET_new(struct GNUNET_CRYPTO_EcdsaPrivateKey); + *ego->pk = um->private_key; + ego->name = GNUNET_strdup(str); + ego->id = id; + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_put( + h->egos, + &ego->id, + ego, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + } if (NULL == str) - { - /* ego was deleted */ - GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (h->egos, + { + /* ego was deleted */ + GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(h->egos, &ego->id, ego)); - } + } else - { - /* ego changed name */ - GNUNET_free (ego->name); - ego->name = GNUNET_strdup (str); - } + { + /* ego changed name */ + GNUNET_free(ego->name); + ego->name = GNUNET_strdup(str); + } /* inform application about change */ if (NULL != h->cb) - h->cb (h->cb_cls, ego, &ego->ctx, str); + h->cb(h->cb_cls, ego, &ego->ctx, str); /* complete deletion */ if (NULL == str) - { - GNUNET_free (ego->pk); - GNUNET_free (ego->name); - GNUNET_free (ego); - } + { + GNUNET_free(ego->pk); + GNUNET_free(ego->name); + GNUNET_free(ego); + } } @@ -418,18 +415,18 @@ handle_identity_update (void *cls, const struct UpdateMessage *um) * @return #GNUNET_OK if the message is well-formed */ static int -check_identity_set_default (void *cls, const struct SetDefaultMessage *sdm) +check_identity_set_default(void *cls, const struct SetDefaultMessage *sdm) { - uint16_t size = ntohs (sdm->header.size) - sizeof (*sdm); - uint16_t name_len = ntohs (sdm->name_len); - const char *str = (const char *) &sdm[1]; + uint16_t size = ntohs(sdm->header.size) - sizeof(*sdm); + uint16_t name_len = ntohs(sdm->name_len); + const char *str = (const char *)&sdm[1]; if ((size != name_len) || ((0 != name_len) && ('\0' != str[name_len - 1]))) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - GNUNET_break (0 == ntohs (sdm->reserved)); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + GNUNET_break(0 == ntohs(sdm->reserved)); return GNUNET_OK; } @@ -442,7 +439,7 @@ check_identity_set_default (void *cls, const struct SetDefaultMessage *sdm) * @param sdm message received */ static void -handle_identity_set_default (void *cls, const struct SetDefaultMessage *sdm) +handle_identity_set_default(void *cls, const struct SetDefaultMessage *sdm) { struct GNUNET_IDENTITY_Handle *h = cls; struct GNUNET_IDENTITY_Operation *op; @@ -450,28 +447,28 @@ handle_identity_set_default (void *cls, const struct SetDefaultMessage *sdm) struct GNUNET_HashCode id; struct GNUNET_IDENTITY_Ego *ego; - GNUNET_CRYPTO_ecdsa_key_get_public (&sdm->private_key, &pub); - GNUNET_CRYPTO_hash (&pub, sizeof (pub), &id); - ego = GNUNET_CONTAINER_multihashmap_get (h->egos, &id); + GNUNET_CRYPTO_ecdsa_key_get_public(&sdm->private_key, &pub); + GNUNET_CRYPTO_hash(&pub, sizeof(pub), &id); + ego = GNUNET_CONTAINER_multihashmap_get(h->egos, &id); if (NULL == ego) - { - GNUNET_break (0); - reschedule_connect (h); - return; - } + { + GNUNET_break(0); + reschedule_connect(h); + return; + } op = h->op_head; if (NULL == op) - { - GNUNET_break (0); - reschedule_connect (h); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received SET_DEFAULT message from identity service\n"); - GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, op); + { + GNUNET_break(0); + reschedule_connect(h); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received SET_DEFAULT message from identity service\n"); + GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, op); if (NULL != op->cb) - op->cb (op->cls, ego, &ego->ctx, ego->name); - GNUNET_free (op); + op->cb(op->cls, ego, &ego->ctx, ego->name); + GNUNET_free(op); } @@ -481,38 +478,38 @@ handle_identity_set_default (void *cls, const struct SetDefaultMessage *sdm) * @param cls handle to the identity service. */ static void -reconnect (void *cls) +reconnect(void *cls) { struct GNUNET_IDENTITY_Handle *h = cls; struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_var_size (identity_result_code, - GNUNET_MESSAGE_TYPE_IDENTITY_RESULT_CODE, - struct ResultCodeMessage, - h), - GNUNET_MQ_hd_var_size (identity_update, - GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE, - struct UpdateMessage, - h), - GNUNET_MQ_hd_var_size (identity_set_default, - GNUNET_MESSAGE_TYPE_IDENTITY_SET_DEFAULT, - struct SetDefaultMessage, - h), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_var_size(identity_result_code, + GNUNET_MESSAGE_TYPE_IDENTITY_RESULT_CODE, + struct ResultCodeMessage, + h), + GNUNET_MQ_hd_var_size(identity_update, + GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE, + struct UpdateMessage, + h), + GNUNET_MQ_hd_var_size(identity_set_default, + GNUNET_MESSAGE_TYPE_IDENTITY_SET_DEFAULT, + struct SetDefaultMessage, + h), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; h->reconnect_task = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Connecting to identity service.\n"); - GNUNET_assert (NULL == h->mq); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Connecting to identity service.\n"); + GNUNET_assert(NULL == h->mq); h->mq = - GNUNET_CLIENT_connect (h->cfg, "identity", handlers, &mq_error_handler, h); + GNUNET_CLIENT_connect(h->cfg, "identity", handlers, &mq_error_handler, h); if (NULL == h->mq) return; if (NULL != h->cb) - { - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_IDENTITY_START); - GNUNET_MQ_send (h->mq, env); - } + { + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_IDENTITY_START); + GNUNET_MQ_send(h->mq, env); + } } @@ -525,23 +522,23 @@ reconnect (void *cls) * @return handle to use */ struct GNUNET_IDENTITY_Handle * -GNUNET_IDENTITY_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_IDENTITY_Callback cb, - void *cb_cls) +GNUNET_IDENTITY_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_IDENTITY_Callback cb, + void *cb_cls) { struct GNUNET_IDENTITY_Handle *h; - h = GNUNET_new (struct GNUNET_IDENTITY_Handle); + h = GNUNET_new(struct GNUNET_IDENTITY_Handle); h->cfg = cfg; h->cb = cb; h->cb_cls = cb_cls; - h->egos = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_YES); - reconnect (h); + h->egos = GNUNET_CONTAINER_multihashmap_create(16, GNUNET_YES); + reconnect(h); if (NULL == h->mq) - { - GNUNET_free (h); - return NULL; - } + { + GNUNET_free(h); + return NULL; + } return h; } @@ -553,7 +550,7 @@ GNUNET_IDENTITY_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return associated ECC key, valid as long as the ego is valid */ const struct GNUNET_CRYPTO_EcdsaPrivateKey * -GNUNET_IDENTITY_ego_get_private_key (const struct GNUNET_IDENTITY_Ego *ego) +GNUNET_IDENTITY_ego_get_private_key(const struct GNUNET_IDENTITY_Ego *ego) { return ego->pk; } @@ -566,10 +563,10 @@ GNUNET_IDENTITY_ego_get_private_key (const struct GNUNET_IDENTITY_Ego *ego) * @param pk set to ego's public key */ void -GNUNET_IDENTITY_ego_get_public_key (const struct GNUNET_IDENTITY_Ego *ego, - struct GNUNET_CRYPTO_EcdsaPublicKey *pk) +GNUNET_IDENTITY_ego_get_public_key(const struct GNUNET_IDENTITY_Ego *ego, + struct GNUNET_CRYPTO_EcdsaPublicKey *pk) { - GNUNET_CRYPTO_ecdsa_key_get_public (ego->pk, pk); + GNUNET_CRYPTO_ecdsa_key_get_public(ego->pk, pk); } @@ -584,10 +581,10 @@ GNUNET_IDENTITY_ego_get_public_key (const struct GNUNET_IDENTITY_Ego *ego, * @return handle to abort the operation */ struct GNUNET_IDENTITY_Operation * -GNUNET_IDENTITY_get (struct GNUNET_IDENTITY_Handle *h, - const char *service_name, - GNUNET_IDENTITY_Callback cb, - void *cb_cls) +GNUNET_IDENTITY_get(struct GNUNET_IDENTITY_Handle *h, + const char *service_name, + GNUNET_IDENTITY_Callback cb, + void *cb_cls) { struct GNUNET_IDENTITY_Operation *op; struct GNUNET_MQ_Envelope *env; @@ -596,24 +593,24 @@ GNUNET_IDENTITY_get (struct GNUNET_IDENTITY_Handle *h, if (NULL == h->mq) return NULL; - GNUNET_assert (NULL != h->cb); - slen = strlen (service_name) + 1; - if (slen >= GNUNET_MAX_MESSAGE_SIZE - sizeof (struct GetDefaultMessage)) - { - GNUNET_break (0); - return NULL; - } - op = GNUNET_new (struct GNUNET_IDENTITY_Operation); + GNUNET_assert(NULL != h->cb); + slen = strlen(service_name) + 1; + if (slen >= GNUNET_MAX_MESSAGE_SIZE - sizeof(struct GetDefaultMessage)) + { + GNUNET_break(0); + return NULL; + } + op = GNUNET_new(struct GNUNET_IDENTITY_Operation); op->h = h; op->cb = cb; op->cls = cb_cls; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, op); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, op); env = - GNUNET_MQ_msg_extra (gdm, slen, GNUNET_MESSAGE_TYPE_IDENTITY_GET_DEFAULT); - gdm->name_len = htons (slen); - gdm->reserved = htons (0); - GNUNET_memcpy (&gdm[1], service_name, slen); - GNUNET_MQ_send (h->mq, env); + GNUNET_MQ_msg_extra(gdm, slen, GNUNET_MESSAGE_TYPE_IDENTITY_GET_DEFAULT); + gdm->name_len = htons(slen); + gdm->reserved = htons(0); + GNUNET_memcpy(&gdm[1], service_name, slen); + GNUNET_MQ_send(h->mq, env); return op; } @@ -629,11 +626,11 @@ GNUNET_IDENTITY_get (struct GNUNET_IDENTITY_Handle *h, * @return handle to abort the operation */ struct GNUNET_IDENTITY_Operation * -GNUNET_IDENTITY_set (struct GNUNET_IDENTITY_Handle *h, - const char *service_name, - struct GNUNET_IDENTITY_Ego *ego, - GNUNET_IDENTITY_Continuation cont, - void *cont_cls) +GNUNET_IDENTITY_set(struct GNUNET_IDENTITY_Handle *h, + const char *service_name, + struct GNUNET_IDENTITY_Ego *ego, + GNUNET_IDENTITY_Continuation cont, + void *cont_cls) { struct GNUNET_IDENTITY_Operation *op; struct GNUNET_MQ_Envelope *env; @@ -642,25 +639,25 @@ GNUNET_IDENTITY_set (struct GNUNET_IDENTITY_Handle *h, if (NULL == h->mq) return NULL; - GNUNET_assert (NULL != h->cb); - slen = strlen (service_name) + 1; - if (slen >= GNUNET_MAX_MESSAGE_SIZE - sizeof (struct SetDefaultMessage)) - { - GNUNET_break (0); - return NULL; - } - op = GNUNET_new (struct GNUNET_IDENTITY_Operation); + GNUNET_assert(NULL != h->cb); + slen = strlen(service_name) + 1; + if (slen >= GNUNET_MAX_MESSAGE_SIZE - sizeof(struct SetDefaultMessage)) + { + GNUNET_break(0); + return NULL; + } + op = GNUNET_new(struct GNUNET_IDENTITY_Operation); op->h = h; op->cont = cont; op->cls = cont_cls; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, op); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, op); env = - GNUNET_MQ_msg_extra (sdm, slen, GNUNET_MESSAGE_TYPE_IDENTITY_SET_DEFAULT); - sdm->name_len = htons (slen); - sdm->reserved = htons (0); + GNUNET_MQ_msg_extra(sdm, slen, GNUNET_MESSAGE_TYPE_IDENTITY_SET_DEFAULT); + sdm->name_len = htons(slen); + sdm->reserved = htons(0); sdm->private_key = *ego->pk; - GNUNET_memcpy (&sdm[1], service_name, slen); - GNUNET_MQ_send (h->mq, env); + GNUNET_memcpy(&sdm[1], service_name, slen); + GNUNET_MQ_send(h->mq, env); return op; } @@ -675,10 +672,10 @@ GNUNET_IDENTITY_set (struct GNUNET_IDENTITY_Handle *h, * @return handle to abort the operation */ struct GNUNET_IDENTITY_Operation * -GNUNET_IDENTITY_create (struct GNUNET_IDENTITY_Handle *h, - const char *name, - GNUNET_IDENTITY_CreateContinuation cont, - void *cont_cls) +GNUNET_IDENTITY_create(struct GNUNET_IDENTITY_Handle *h, + const char *name, + GNUNET_IDENTITY_CreateContinuation cont, + void *cont_cls) { struct GNUNET_IDENTITY_Operation *op; struct GNUNET_MQ_Envelope *env; @@ -688,25 +685,25 @@ GNUNET_IDENTITY_create (struct GNUNET_IDENTITY_Handle *h, if (NULL == h->mq) return NULL; - slen = strlen (name) + 1; - if (slen >= GNUNET_MAX_MESSAGE_SIZE - sizeof (struct CreateRequestMessage)) - { - GNUNET_break (0); - return NULL; - } - op = GNUNET_new (struct GNUNET_IDENTITY_Operation); + slen = strlen(name) + 1; + if (slen >= GNUNET_MAX_MESSAGE_SIZE - sizeof(struct CreateRequestMessage)) + { + GNUNET_break(0); + return NULL; + } + op = GNUNET_new(struct GNUNET_IDENTITY_Operation); op->h = h; op->create_cont = cont; op->cls = cont_cls; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, op); - env = GNUNET_MQ_msg_extra (crm, slen, GNUNET_MESSAGE_TYPE_IDENTITY_CREATE); - crm->name_len = htons (slen); - crm->reserved = htons (0); - pk = GNUNET_CRYPTO_ecdsa_key_create (); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, op); + env = GNUNET_MQ_msg_extra(crm, slen, GNUNET_MESSAGE_TYPE_IDENTITY_CREATE); + crm->name_len = htons(slen); + crm->reserved = htons(0); + pk = GNUNET_CRYPTO_ecdsa_key_create(); crm->private_key = *pk; op->pk = pk; - GNUNET_memcpy (&crm[1], name, slen); - GNUNET_MQ_send (h->mq, env); + GNUNET_memcpy(&crm[1], name, slen); + GNUNET_MQ_send(h->mq, env); return op; } @@ -722,11 +719,11 @@ GNUNET_IDENTITY_create (struct GNUNET_IDENTITY_Handle *h, * @return handle to abort the operation */ struct GNUNET_IDENTITY_Operation * -GNUNET_IDENTITY_rename (struct GNUNET_IDENTITY_Handle *h, - const char *old_name, - const char *new_name, - GNUNET_IDENTITY_Continuation cb, - void *cb_cls) +GNUNET_IDENTITY_rename(struct GNUNET_IDENTITY_Handle *h, + const char *old_name, + const char *new_name, + GNUNET_IDENTITY_Continuation cb, + void *cb_cls) { struct GNUNET_IDENTITY_Operation *op; struct GNUNET_MQ_Envelope *env; @@ -737,30 +734,30 @@ GNUNET_IDENTITY_rename (struct GNUNET_IDENTITY_Handle *h, if (NULL == h->mq) return NULL; - slen_old = strlen (old_name) + 1; - slen_new = strlen (new_name) + 1; + slen_old = strlen(old_name) + 1; + slen_new = strlen(new_name) + 1; if ((slen_old >= GNUNET_MAX_MESSAGE_SIZE) || (slen_new >= GNUNET_MAX_MESSAGE_SIZE) || (slen_old + slen_new >= - GNUNET_MAX_MESSAGE_SIZE - sizeof (struct RenameMessage))) - { - GNUNET_break (0); - return NULL; - } - op = GNUNET_new (struct GNUNET_IDENTITY_Operation); + GNUNET_MAX_MESSAGE_SIZE - sizeof(struct RenameMessage))) + { + GNUNET_break(0); + return NULL; + } + op = GNUNET_new(struct GNUNET_IDENTITY_Operation); op->h = h; op->cont = cb; op->cls = cb_cls; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, op); - env = GNUNET_MQ_msg_extra (grm, - slen_old + slen_new, - GNUNET_MESSAGE_TYPE_IDENTITY_RENAME); - grm->old_name_len = htons (slen_old); - grm->new_name_len = htons (slen_new); - dst = (char *) &grm[1]; - GNUNET_memcpy (dst, old_name, slen_old); - GNUNET_memcpy (&dst[slen_old], new_name, slen_new); - GNUNET_MQ_send (h->mq, env); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, op); + env = GNUNET_MQ_msg_extra(grm, + slen_old + slen_new, + GNUNET_MESSAGE_TYPE_IDENTITY_RENAME); + grm->old_name_len = htons(slen_old); + grm->new_name_len = htons(slen_new); + dst = (char *)&grm[1]; + GNUNET_memcpy(dst, old_name, slen_old); + GNUNET_memcpy(&dst[slen_old], new_name, slen_new); + GNUNET_MQ_send(h->mq, env); return op; } @@ -775,10 +772,10 @@ GNUNET_IDENTITY_rename (struct GNUNET_IDENTITY_Handle *h, * @return handle to abort the operation */ struct GNUNET_IDENTITY_Operation * -GNUNET_IDENTITY_delete (struct GNUNET_IDENTITY_Handle *h, - const char *name, - GNUNET_IDENTITY_Continuation cb, - void *cb_cls) +GNUNET_IDENTITY_delete(struct GNUNET_IDENTITY_Handle *h, + const char *name, + GNUNET_IDENTITY_Continuation cb, + void *cb_cls) { struct GNUNET_IDENTITY_Operation *op; struct GNUNET_MQ_Envelope *env; @@ -787,22 +784,22 @@ GNUNET_IDENTITY_delete (struct GNUNET_IDENTITY_Handle *h, if (NULL == h->mq) return NULL; - slen = strlen (name) + 1; - if (slen >= GNUNET_MAX_MESSAGE_SIZE - sizeof (struct DeleteMessage)) - { - GNUNET_break (0); - return NULL; - } - op = GNUNET_new (struct GNUNET_IDENTITY_Operation); + slen = strlen(name) + 1; + if (slen >= GNUNET_MAX_MESSAGE_SIZE - sizeof(struct DeleteMessage)) + { + GNUNET_break(0); + return NULL; + } + op = GNUNET_new(struct GNUNET_IDENTITY_Operation); op->h = h; op->cont = cb; op->cls = cb_cls; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, op); - env = GNUNET_MQ_msg_extra (gdm, slen, GNUNET_MESSAGE_TYPE_IDENTITY_DELETE); - gdm->name_len = htons (slen); - gdm->reserved = htons (0); - GNUNET_memcpy (&gdm[1], name, slen); - GNUNET_MQ_send (h->mq, env); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, op); + env = GNUNET_MQ_msg_extra(gdm, slen, GNUNET_MESSAGE_TYPE_IDENTITY_DELETE); + gdm->name_len = htons(slen); + gdm->reserved = htons(0); + GNUNET_memcpy(&gdm[1], name, slen); + GNUNET_MQ_send(h->mq, env); return op; } @@ -816,16 +813,16 @@ GNUNET_IDENTITY_delete (struct GNUNET_IDENTITY_Handle *h, * @param op operation to cancel */ void -GNUNET_IDENTITY_cancel (struct GNUNET_IDENTITY_Operation *op) +GNUNET_IDENTITY_cancel(struct GNUNET_IDENTITY_Operation *op) { op->cont = NULL; op->cb = NULL; op->create_cont = NULL; if (NULL != op->pk) - { - GNUNET_free (op->pk); - op->pk = NULL; - } + { + GNUNET_free(op->pk); + op->pk = NULL; + } } @@ -835,35 +832,35 @@ GNUNET_IDENTITY_cancel (struct GNUNET_IDENTITY_Operation *op) * @param h handle to destroy */ void -GNUNET_IDENTITY_disconnect (struct GNUNET_IDENTITY_Handle *h) +GNUNET_IDENTITY_disconnect(struct GNUNET_IDENTITY_Handle *h) { struct GNUNET_IDENTITY_Operation *op; - GNUNET_assert (NULL != h); + GNUNET_assert(NULL != h); if (h->reconnect_task != NULL) - { - GNUNET_SCHEDULER_cancel (h->reconnect_task); - h->reconnect_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(h->reconnect_task); + h->reconnect_task = NULL; + } if (NULL != h->egos) - { - GNUNET_CONTAINER_multihashmap_iterate (h->egos, &free_ego, h); - GNUNET_CONTAINER_multihashmap_destroy (h->egos); - h->egos = NULL; - } + { + GNUNET_CONTAINER_multihashmap_iterate(h->egos, &free_ego, h); + GNUNET_CONTAINER_multihashmap_destroy(h->egos); + h->egos = NULL; + } while (NULL != (op = h->op_head)) - { - GNUNET_break (NULL == op->cont); - GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, op); - GNUNET_free_non_null (op->pk); - GNUNET_free (op); - } + { + GNUNET_break(NULL == op->cont); + GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, op); + GNUNET_free_non_null(op->pk); + GNUNET_free(op); + } if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } - GNUNET_free (h); + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } + GNUNET_free(h); } /* end of identity_api.c */ diff --git a/src/identity/identity_api_lookup.c b/src/identity/identity_api_lookup.c index 56ebf6f47..faf647c07 100644 --- a/src/identity/identity_api_lookup.c +++ b/src/identity/identity_api_lookup.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file identity/identity_api_lookup.c @@ -28,15 +28,13 @@ #include "gnunet_identity_service.h" #include "identity.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "identity-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "identity-api", __VA_ARGS__) /** * Handle for ego lookup. */ -struct GNUNET_IDENTITY_EgoLookup -{ - +struct GNUNET_IDENTITY_EgoLookup { /** * Connection to service. */ @@ -68,10 +66,10 @@ struct GNUNET_IDENTITY_EgoLookup * @return #GNUNET_OK if the message is well-formed */ static int -check_identity_result_code (void *cls, const struct ResultCodeMessage *rcm) +check_identity_result_code(void *cls, const struct ResultCodeMessage *rcm) { - if (sizeof (*rcm) != htons (rcm->header.size)) - GNUNET_MQ_check_zero_termination (rcm); + if (sizeof(*rcm) != htons(rcm->header.size)) + GNUNET_MQ_check_zero_termination(rcm); return GNUNET_OK; } @@ -83,12 +81,12 @@ check_identity_result_code (void *cls, const struct ResultCodeMessage *rcm) * @param rcm result message received */ static void -handle_identity_result_code (void *cls, const struct ResultCodeMessage *rcm) +handle_identity_result_code(void *cls, const struct ResultCodeMessage *rcm) { struct GNUNET_IDENTITY_EgoLookup *el = cls; - el->cb (el->cb_cls, NULL); - GNUNET_IDENTITY_ego_lookup_cancel (el); + el->cb(el->cb_cls, NULL); + GNUNET_IDENTITY_ego_lookup_cancel(el); } @@ -100,18 +98,18 @@ handle_identity_result_code (void *cls, const struct ResultCodeMessage *rcm) * @return #GNUNET_OK if the message is well-formed */ static int -check_identity_update (void *cls, const struct UpdateMessage *um) +check_identity_update(void *cls, const struct UpdateMessage *um) { - uint16_t size = ntohs (um->header.size); - uint16_t name_len = ntohs (um->name_len); - const char *str = (const char *) &um[1]; + uint16_t size = ntohs(um->header.size); + uint16_t name_len = ntohs(um->name_len); + const char *str = (const char *)&um[1]; - if ((size != name_len + sizeof (struct UpdateMessage)) || + if ((size != name_len + sizeof(struct UpdateMessage)) || ((0 != name_len) && ('\0' != str[name_len - 1]))) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -123,23 +121,23 @@ check_identity_update (void *cls, const struct UpdateMessage *um) * @param um message received */ static void -handle_identity_update (void *cls, const struct UpdateMessage *um) +handle_identity_update(void *cls, const struct UpdateMessage *um) { struct GNUNET_IDENTITY_EgoLookup *el = cls; - uint16_t name_len = ntohs (um->name_len); - const char *str = (0 == name_len) ? NULL : (const char *) &um[1]; + uint16_t name_len = ntohs(um->name_len); + const char *str = (0 == name_len) ? NULL : (const char *)&um[1]; struct GNUNET_CRYPTO_EcdsaPublicKey pub; struct GNUNET_HashCode id; struct GNUNET_IDENTITY_Ego ego; - GNUNET_break (GNUNET_YES != ntohs (um->end_of_list)); - GNUNET_CRYPTO_ecdsa_key_get_public (&um->private_key, &pub); - GNUNET_CRYPTO_hash (&pub, sizeof (pub), &id); - ego.pk = (struct GNUNET_CRYPTO_EcdsaPrivateKey *) &um->private_key; - ego.name = (char *) str; + GNUNET_break(GNUNET_YES != ntohs(um->end_of_list)); + GNUNET_CRYPTO_ecdsa_key_get_public(&um->private_key, &pub); + GNUNET_CRYPTO_hash(&pub, sizeof(pub), &id); + ego.pk = (struct GNUNET_CRYPTO_EcdsaPrivateKey *)&um->private_key; + ego.name = (char *)str; ego.id = id; - el->cb (el->cb_cls, &ego); - GNUNET_IDENTITY_ego_lookup_cancel (el); + el->cb(el->cb_cls, &ego); + GNUNET_IDENTITY_ego_lookup_cancel(el); } @@ -152,11 +150,11 @@ handle_identity_update (void *cls, const struct UpdateMessage *um) * @param error error code */ static void -mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_IDENTITY_EgoLookup *el = cls; - el->cb (el->cb_cls, NULL); + el->cb(el->cb_cls, NULL); } @@ -170,46 +168,46 @@ mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @return NULL on error */ struct GNUNET_IDENTITY_EgoLookup * -GNUNET_IDENTITY_ego_lookup (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *name, - GNUNET_IDENTITY_EgoCallback cb, - void *cb_cls) +GNUNET_IDENTITY_ego_lookup(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *name, + GNUNET_IDENTITY_EgoCallback cb, + void *cb_cls) { struct GNUNET_IDENTITY_EgoLookup *el; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *req; size_t nlen; - GNUNET_assert (NULL != cb); - el = GNUNET_new (struct GNUNET_IDENTITY_EgoLookup); + GNUNET_assert(NULL != cb); + el = GNUNET_new(struct GNUNET_IDENTITY_EgoLookup); el->cb = cb; el->cb_cls = cb_cls; { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_var_size (identity_result_code, - GNUNET_MESSAGE_TYPE_IDENTITY_RESULT_CODE, - struct ResultCodeMessage, - el), - GNUNET_MQ_hd_var_size (identity_update, - GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE, - struct UpdateMessage, - el), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_var_size(identity_result_code, + GNUNET_MESSAGE_TYPE_IDENTITY_RESULT_CODE, + struct ResultCodeMessage, + el), + GNUNET_MQ_hd_var_size(identity_update, + GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE, + struct UpdateMessage, + el), + GNUNET_MQ_handler_end() }; el->mq = - GNUNET_CLIENT_connect (cfg, "identity", handlers, &mq_error_handler, el); + GNUNET_CLIENT_connect(cfg, "identity", handlers, &mq_error_handler, el); } if (NULL == el->mq) - { - GNUNET_break (0); - GNUNET_free (el); - return NULL; - } - el->name = GNUNET_strdup (name); - nlen = strlen (name) + 1; - env = GNUNET_MQ_msg_extra (req, nlen, GNUNET_MESSAGE_TYPE_IDENTITY_LOOKUP); - memcpy (&req[1], name, nlen); - GNUNET_MQ_send (el->mq, env); + { + GNUNET_break(0); + GNUNET_free(el); + return NULL; + } + el->name = GNUNET_strdup(name); + nlen = strlen(name) + 1; + env = GNUNET_MQ_msg_extra(req, nlen, GNUNET_MESSAGE_TYPE_IDENTITY_LOOKUP); + memcpy(&req[1], name, nlen); + GNUNET_MQ_send(el->mq, env); return el; } @@ -220,11 +218,11 @@ GNUNET_IDENTITY_ego_lookup (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param el handle for lookup to abort */ void -GNUNET_IDENTITY_ego_lookup_cancel (struct GNUNET_IDENTITY_EgoLookup *el) +GNUNET_IDENTITY_ego_lookup_cancel(struct GNUNET_IDENTITY_EgoLookup *el) { - GNUNET_MQ_destroy (el->mq); - GNUNET_free (el->name); - GNUNET_free (el); + GNUNET_MQ_destroy(el->mq); + GNUNET_free(el->name); + GNUNET_free(el); } diff --git a/src/identity/identity_api_suffix_lookup.c b/src/identity/identity_api_suffix_lookup.c index 685030e40..51d8f39a6 100644 --- a/src/identity/identity_api_suffix_lookup.c +++ b/src/identity/identity_api_suffix_lookup.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file identity/identity_api_suffix_lookup.c @@ -28,15 +28,13 @@ #include "gnunet_identity_service.h" #include "identity.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "identity-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "identity-api", __VA_ARGS__) /** * Handle for ego lookup. */ -struct GNUNET_IDENTITY_EgoSuffixLookup -{ - +struct GNUNET_IDENTITY_EgoSuffixLookup { /** * Connection to service. */ @@ -68,11 +66,11 @@ struct GNUNET_IDENTITY_EgoSuffixLookup * @return #GNUNET_OK if the message is well-formed */ static int -check_identity_result_code (void *cls, const struct ResultCodeMessage *rcm) +check_identity_result_code(void *cls, const struct ResultCodeMessage *rcm) { - (void) cls; - if (sizeof (*rcm) != htons (rcm->header.size)) - GNUNET_MQ_check_zero_termination (rcm); + (void)cls; + if (sizeof(*rcm) != htons(rcm->header.size)) + GNUNET_MQ_check_zero_termination(rcm); return GNUNET_OK; } @@ -84,13 +82,13 @@ check_identity_result_code (void *cls, const struct ResultCodeMessage *rcm) * @param rcm result message received */ static void -handle_identity_result_code (void *cls, const struct ResultCodeMessage *rcm) +handle_identity_result_code(void *cls, const struct ResultCodeMessage *rcm) { struct GNUNET_IDENTITY_EgoSuffixLookup *el = cls; - (void) rcm; - el->cb (el->cb_cls, NULL, NULL); - GNUNET_IDENTITY_ego_lookup_by_suffix_cancel (el); + (void)rcm; + el->cb(el->cb_cls, NULL, NULL); + GNUNET_IDENTITY_ego_lookup_by_suffix_cancel(el); } @@ -102,19 +100,19 @@ handle_identity_result_code (void *cls, const struct ResultCodeMessage *rcm) * @return #GNUNET_OK if the message is well-formed */ static int -check_identity_update (void *cls, const struct UpdateMessage *um) +check_identity_update(void *cls, const struct UpdateMessage *um) { - uint16_t size = ntohs (um->header.size); - uint16_t name_len = ntohs (um->name_len); - const char *str = (const char *) &um[1]; + uint16_t size = ntohs(um->header.size); + uint16_t name_len = ntohs(um->name_len); + const char *str = (const char *)&um[1]; - (void) cls; - if ((size != name_len + sizeof (struct UpdateMessage)) || + (void)cls; + if ((size != name_len + sizeof(struct UpdateMessage)) || ((0 != name_len) && ('\0' != str[name_len - 1]))) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -126,14 +124,14 @@ check_identity_update (void *cls, const struct UpdateMessage *um) * @param um message received */ static void -handle_identity_update (void *cls, const struct UpdateMessage *um) +handle_identity_update(void *cls, const struct UpdateMessage *um) { struct GNUNET_IDENTITY_EgoSuffixLookup *el = cls; - uint16_t name_len = ntohs (um->name_len); - const char *str = (0 == name_len) ? NULL : (const char *) &um[1]; + uint16_t name_len = ntohs(um->name_len); + const char *str = (0 == name_len) ? NULL : (const char *)&um[1]; - el->cb (el->cb_cls, &um->private_key, str); - GNUNET_IDENTITY_ego_lookup_by_suffix_cancel (el); + el->cb(el->cb_cls, &um->private_key, str); + GNUNET_IDENTITY_ego_lookup_by_suffix_cancel(el); } @@ -146,13 +144,13 @@ handle_identity_update (void *cls, const struct UpdateMessage *um) * @param error error code */ static void -mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_IDENTITY_EgoSuffixLookup *el = cls; - (void) error; - el->cb (el->cb_cls, NULL, NULL); - GNUNET_IDENTITY_ego_lookup_by_suffix_cancel (el); + (void)error; + el->cb(el->cb_cls, NULL, NULL); + GNUNET_IDENTITY_ego_lookup_by_suffix_cancel(el); } @@ -166,46 +164,46 @@ mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @return NULL on error */ struct GNUNET_IDENTITY_EgoSuffixLookup * -GNUNET_IDENTITY_ego_lookup_by_suffix (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *suffix, - GNUNET_IDENTITY_EgoSuffixCallback cb, - void *cb_cls) +GNUNET_IDENTITY_ego_lookup_by_suffix(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *suffix, + GNUNET_IDENTITY_EgoSuffixCallback cb, + void *cb_cls) { struct GNUNET_IDENTITY_EgoSuffixLookup *el; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *req; size_t nlen; - GNUNET_assert (NULL != cb); - el = GNUNET_new (struct GNUNET_IDENTITY_EgoSuffixLookup); + GNUNET_assert(NULL != cb); + el = GNUNET_new(struct GNUNET_IDENTITY_EgoSuffixLookup); el->cb = cb; el->cb_cls = cb_cls; { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_var_size (identity_result_code, - GNUNET_MESSAGE_TYPE_IDENTITY_RESULT_CODE, - struct ResultCodeMessage, - el), - GNUNET_MQ_hd_var_size (identity_update, - GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE, - struct UpdateMessage, - el), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_var_size(identity_result_code, + GNUNET_MESSAGE_TYPE_IDENTITY_RESULT_CODE, + struct ResultCodeMessage, + el), + GNUNET_MQ_hd_var_size(identity_update, + GNUNET_MESSAGE_TYPE_IDENTITY_UPDATE, + struct UpdateMessage, + el), + GNUNET_MQ_handler_end() }; el->mq = - GNUNET_CLIENT_connect (cfg, "identity", handlers, &mq_error_handler, el); + GNUNET_CLIENT_connect(cfg, "identity", handlers, &mq_error_handler, el); } if (NULL == el->mq) - { - GNUNET_break (0); - GNUNET_free (el); - return NULL; - } - el->suffix = GNUNET_strdup (suffix); - nlen = strlen (suffix) + 1; - env = GNUNET_MQ_msg_extra (req, nlen, GNUNET_MESSAGE_TYPE_IDENTITY_LOOKUP_BY_SUFFIX); - memcpy (&req[1], suffix, nlen); - GNUNET_MQ_send (el->mq, env); + { + GNUNET_break(0); + GNUNET_free(el); + return NULL; + } + el->suffix = GNUNET_strdup(suffix); + nlen = strlen(suffix) + 1; + env = GNUNET_MQ_msg_extra(req, nlen, GNUNET_MESSAGE_TYPE_IDENTITY_LOOKUP_BY_SUFFIX); + memcpy(&req[1], suffix, nlen); + GNUNET_MQ_send(el->mq, env); return el; } @@ -216,11 +214,11 @@ GNUNET_IDENTITY_ego_lookup_by_suffix (const struct GNUNET_CONFIGURATION_Handle * * @param el handle for lookup to abort */ void -GNUNET_IDENTITY_ego_lookup_by_suffix_cancel (struct GNUNET_IDENTITY_EgoSuffixLookup *el) +GNUNET_IDENTITY_ego_lookup_by_suffix_cancel(struct GNUNET_IDENTITY_EgoSuffixLookup *el) { - GNUNET_MQ_destroy (el->mq); - GNUNET_free (el->suffix); - GNUNET_free (el); + GNUNET_MQ_destroy(el->mq); + GNUNET_free(el->suffix); + GNUNET_free(el); } diff --git a/src/identity/plugin_rest_identity.c b/src/identity/plugin_rest_identity.c index ac1965a75..1f6ec94ee 100644 --- a/src/identity/plugin_rest_identity.c +++ b/src/identity/plugin_rest_identity.c @@ -1,6 +1,6 @@ /* - This file is part of GNUnet. - Copyright (C) 2012-2015 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2012-2015 GNUnet e.V. GNUnet is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published @@ -129,16 +129,14 @@ static char *allow_methods; /** * @brief struct returned by the initialization function of the plugin */ -struct Plugin -{ +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; }; /** * The ego list */ -struct EgoEntry -{ +struct EgoEntry { /** * DLL */ @@ -168,8 +166,7 @@ struct EgoEntry /** * The request handle */ -struct RequestHandle -{ +struct RequestHandle { /** * The data from the REST request */ @@ -257,38 +254,38 @@ struct RequestHandle * @param handle Handle to clean up */ static void -cleanup_handle (void *cls) +cleanup_handle(void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; struct EgoEntry *ego_tmp; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); if (NULL != handle->timeout_task) - { - GNUNET_SCHEDULER_cancel (handle->timeout_task); - handle->timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(handle->timeout_task); + handle->timeout_task = NULL; + } if (NULL != handle->url) - GNUNET_free (handle->url); + GNUNET_free(handle->url); if (NULL != handle->emsg) - GNUNET_free (handle->emsg); + GNUNET_free(handle->emsg); if (NULL != handle->name) - GNUNET_free (handle->name); + GNUNET_free(handle->name); if (NULL != handle->identity_handle) - GNUNET_IDENTITY_disconnect (handle->identity_handle); + GNUNET_IDENTITY_disconnect(handle->identity_handle); for (ego_entry = handle->ego_head; NULL != ego_entry;) - { - ego_tmp = ego_entry; - ego_entry = ego_entry->next; - GNUNET_free (ego_tmp->identifier); - GNUNET_free (ego_tmp->keystring); - GNUNET_free (ego_tmp); - } - - GNUNET_free (handle); + { + ego_tmp = ego_entry; + ego_entry = ego_entry->next; + GNUNET_free(ego_tmp->identifier); + GNUNET_free(ego_tmp->keystring); + GNUNET_free(ego_tmp); + } + + GNUNET_free(handle); } /** @@ -297,26 +294,26 @@ cleanup_handle (void *cls) * @param cls the `struct RequestHandle` */ static void -do_error (void *cls) +do_error(void *cls) { struct RequestHandle *handle = cls; struct MHD_Response *resp; - json_t *json_error = json_object (); + json_t *json_error = json_object(); char *response; if (NULL == handle->emsg) - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_ERROR_UNKNOWN); + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_ERROR_UNKNOWN); - json_object_set_new (json_error, "error", json_string (handle->emsg)); + json_object_set_new(json_error, "error", json_string(handle->emsg)); if (0 == handle->response_code) handle->response_code = MHD_HTTP_OK; - response = json_dumps (json_error, 0); - resp = GNUNET_REST_create_response (response); - handle->proc (handle->proc_cls, resp, handle->response_code); - json_decref (json_error); - GNUNET_free (response); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + response = json_dumps(json_error, 0); + resp = GNUNET_REST_create_response(response); + handle->proc(handle->proc_cls, resp, handle->response_code); + json_decref(json_error); + GNUNET_free(response); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } @@ -330,29 +327,30 @@ do_error (void *cls) * @return EgoEntry or NULL if not found */ struct EgoEntry * -get_egoentry (struct RequestHandle *handle, char *pubkey, char *name) +get_egoentry(struct RequestHandle *handle, char *pubkey, char *name) { struct EgoEntry *ego_entry; + if (NULL != pubkey) - { - for (ego_entry = handle->ego_head; NULL != ego_entry; - ego_entry = ego_entry->next) { - if (0 != strcasecmp (pubkey, ego_entry->keystring)) - continue; - return ego_entry; + for (ego_entry = handle->ego_head; NULL != ego_entry; + ego_entry = ego_entry->next) + { + if (0 != strcasecmp(pubkey, ego_entry->keystring)) + continue; + return ego_entry; + } } - } if (NULL != name) - { - for (ego_entry = handle->ego_head; NULL != ego_entry; - ego_entry = ego_entry->next) { - if (0 != strcasecmp (name, ego_entry->identifier)) - continue; - return ego_entry; + for (ego_entry = handle->ego_head; NULL != ego_entry; + ego_entry = ego_entry->next) + { + if (0 != strcasecmp(name, ego_entry->identifier)) + continue; + return ego_entry; + } } - } return NULL; } @@ -366,10 +364,10 @@ get_egoentry (struct RequestHandle *handle, char *pubkey, char *name) * @param name the id of the ego */ static void -ego_get_for_subsystem (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +ego_get_for_subsystem(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { struct RequestHandle *handle = cls; struct MHD_Response *resp; @@ -379,34 +377,34 @@ ego_get_for_subsystem (void *cls, char *public_key_string; if (NULL == ego) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } - GNUNET_IDENTITY_ego_get_public_key (ego, &public_key); - public_key_string = GNUNET_CRYPTO_ecdsa_public_key_to_string (&public_key); + GNUNET_IDENTITY_ego_get_public_key(ego, &public_key); + public_key_string = GNUNET_CRYPTO_ecdsa_public_key_to_string(&public_key); // create json with subsystem identity - json_root = json_object (); - json_object_set_new (json_root, - GNUNET_REST_IDENTITY_PARAM_PUBKEY, - json_string (public_key_string)); - json_object_set_new (json_root, - GNUNET_REST_IDENTITY_PARAM_NAME, - json_string (name)); - - result_str = json_dumps (json_root, 0); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result_str); - resp = GNUNET_REST_create_response (result_str); - - json_decref (json_root); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_free (result_str); - GNUNET_free (public_key_string); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + json_root = json_object(); + json_object_set_new(json_root, + GNUNET_REST_IDENTITY_PARAM_PUBKEY, + json_string(public_key_string)); + json_object_set_new(json_root, + GNUNET_REST_IDENTITY_PARAM_NAME, + json_string(name)); + + result_str = json_dumps(json_root, 0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result_str); + resp = GNUNET_REST_create_response(result_str); + + json_decref(json_root); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_free(result_str); + GNUNET_free(public_key_string); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } /** @@ -417,35 +415,35 @@ ego_get_for_subsystem (void *cls, * @param cls the RequestHandle */ void -ego_get_subsystem (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +ego_get_subsystem(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; char *subsystem; - if (strlen (GNUNET_REST_API_NS_IDENTITY_SUBSYSTEM) >= strlen (handle->url)) - { - handle->emsg = GNUNET_strdup ("Missing subsystem name"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - subsystem = &handle->url[strlen (GNUNET_REST_API_NS_IDENTITY_SUBSYSTEM) + 1]; + if (strlen(GNUNET_REST_API_NS_IDENTITY_SUBSYSTEM) >= strlen(handle->url)) + { + handle->emsg = GNUNET_strdup("Missing subsystem name"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + subsystem = &handle->url[strlen(GNUNET_REST_API_NS_IDENTITY_SUBSYSTEM) + 1]; //requested default identity of subsystem - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Looking for %s's ego\n", subsystem); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Looking for %s's ego\n", subsystem); - handle->op = GNUNET_IDENTITY_get (handle->identity_handle, - subsystem, - &ego_get_for_subsystem, - handle); + handle->op = GNUNET_IDENTITY_get(handle->identity_handle, + subsystem, + &ego_get_for_subsystem, + handle); if (NULL == handle->op) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } } @@ -457,9 +455,9 @@ ego_get_subsystem (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ void -ego_get_all (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +ego_get_all(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; @@ -468,30 +466,30 @@ ego_get_all (struct GNUNET_REST_RequestHandle *con_handle, json_t *json_ego; char *result_str; - json_root = json_array (); + json_root = json_array(); //Return ego/egos for (ego_entry = handle->ego_head; NULL != ego_entry; ego_entry = ego_entry->next) - { - json_ego = json_object (); - json_object_set_new (json_ego, - GNUNET_REST_IDENTITY_PARAM_PUBKEY, - json_string (ego_entry->keystring)); - json_object_set_new (json_ego, - GNUNET_REST_IDENTITY_PARAM_NAME, - json_string (ego_entry->identifier)); - json_array_append (json_root, json_ego); - json_decref (json_ego); - } - - result_str = json_dumps (json_root, 0); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result_str); - resp = GNUNET_REST_create_response (result_str); - - json_decref (json_root); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_free (result_str); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + { + json_ego = json_object(); + json_object_set_new(json_ego, + GNUNET_REST_IDENTITY_PARAM_PUBKEY, + json_string(ego_entry->keystring)); + json_object_set_new(json_ego, + GNUNET_REST_IDENTITY_PARAM_NAME, + json_string(ego_entry->identifier)); + json_array_append(json_root, json_ego); + json_decref(json_ego); + } + + result_str = json_dumps(json_root, 0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result_str); + resp = GNUNET_REST_create_response(result_str); + + json_decref(json_root); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_free(result_str); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } @@ -502,28 +500,28 @@ ego_get_all (struct GNUNET_REST_RequestHandle *con_handle, * @param ego_entry the struct EgoEntry for the response */ void -ego_get_response (struct RequestHandle *handle, struct EgoEntry *ego_entry) +ego_get_response(struct RequestHandle *handle, struct EgoEntry *ego_entry) { struct MHD_Response *resp; json_t *json_ego; char *result_str; - json_ego = json_object (); - json_object_set_new (json_ego, - GNUNET_REST_IDENTITY_PARAM_PUBKEY, - json_string (ego_entry->keystring)); - json_object_set_new (json_ego, - GNUNET_REST_IDENTITY_PARAM_NAME, - json_string (ego_entry->identifier)); - - result_str = json_dumps (json_ego, 0); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result_str); - resp = GNUNET_REST_create_response (result_str); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - - json_decref (json_ego); - GNUNET_free (result_str); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + json_ego = json_object(); + json_object_set_new(json_ego, + GNUNET_REST_IDENTITY_PARAM_PUBKEY, + json_string(ego_entry->keystring)); + json_object_set_new(json_ego, + GNUNET_REST_IDENTITY_PARAM_NAME, + json_string(ego_entry->identifier)); + + result_str = json_dumps(json_ego, 0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result_str); + resp = GNUNET_REST_create_response(result_str); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + + json_decref(json_ego); + GNUNET_free(result_str); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } @@ -535,9 +533,9 @@ ego_get_response (struct RequestHandle *handle, struct EgoEntry *ego_entry) * @param cls the RequestHandle */ void -ego_get_pubkey (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +ego_get_pubkey(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; @@ -545,25 +543,25 @@ ego_get_pubkey (struct GNUNET_REST_RequestHandle *con_handle, keystring = NULL; - if (strlen (GNUNET_REST_API_NS_IDENTITY_PUBKEY) >= strlen (handle->url)) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_MISSING_PUBKEY); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - keystring = &handle->url[strlen (GNUNET_REST_API_NS_IDENTITY_PUBKEY) + 1]; - ego_entry = get_egoentry (handle, keystring, NULL); + if (strlen(GNUNET_REST_API_NS_IDENTITY_PUBKEY) >= strlen(handle->url)) + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_MISSING_PUBKEY); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + keystring = &handle->url[strlen(GNUNET_REST_API_NS_IDENTITY_PUBKEY) + 1]; + ego_entry = get_egoentry(handle, keystring, NULL); if (NULL == ego_entry) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - - ego_get_response (handle, ego_entry); + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + + ego_get_response(handle, ego_entry); } /** @@ -574,9 +572,9 @@ ego_get_pubkey (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ void -ego_get_name (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +ego_get_name(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; @@ -584,25 +582,25 @@ ego_get_name (struct GNUNET_REST_RequestHandle *con_handle, egoname = NULL; - if (strlen (GNUNET_REST_API_NS_IDENTITY_NAME) >= strlen (handle->url)) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_MISSING_NAME); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - egoname = &handle->url[strlen (GNUNET_REST_API_NS_IDENTITY_NAME) + 1]; - ego_entry = get_egoentry (handle, NULL, egoname); + if (strlen(GNUNET_REST_API_NS_IDENTITY_NAME) >= strlen(handle->url)) + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_MISSING_NAME); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + egoname = &handle->url[strlen(GNUNET_REST_API_NS_IDENTITY_NAME) + 1]; + ego_entry = get_egoentry(handle, NULL, egoname); if (NULL == ego_entry) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - - ego_get_response (handle, ego_entry); + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + + ego_get_response(handle, ego_entry); } @@ -613,25 +611,25 @@ ego_get_name (struct GNUNET_REST_RequestHandle *con_handle, * @param emsg error message */ static void -do_finished (void *cls, const char *emsg) +do_finished(void *cls, const char *emsg) { struct RequestHandle *handle = cls; struct MHD_Response *resp; handle->op = NULL; if (NULL != emsg) - { - handle->emsg = GNUNET_strdup (emsg); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(emsg); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } if (0 == handle->response_code) - { - handle->response_code = MHD_HTTP_NO_CONTENT; - } - resp = GNUNET_REST_create_response (NULL); - handle->proc (handle->proc_cls, resp, handle->response_code); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + { + handle->response_code = MHD_HTTP_NO_CONTENT; + } + resp = GNUNET_REST_create_response(NULL); + handle->proc(handle->proc_cls, resp, handle->response_code); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } @@ -643,14 +641,14 @@ do_finished (void *cls, const char *emsg) * @param emsg error message */ static void -do_finished_create (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, - const char *emsg) +do_finished_create(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, + const char *emsg) { struct RequestHandle *handle = cls; - (void) pk; - do_finished (handle, emsg); + (void)pk; + do_finished(handle, emsg); } @@ -661,7 +659,7 @@ do_finished_create (void *cls, * @param ego_entry the struct EgoEntry we want to edit */ void -ego_edit (struct RequestHandle *handle, struct EgoEntry *ego_entry) +ego_edit(struct RequestHandle *handle, struct EgoEntry *ego_entry) { struct EgoEntry *ego_entry_tmp; struct MHD_Response *resp; @@ -673,79 +671,78 @@ ego_edit (struct RequestHandle *handle, struct EgoEntry *ego_entry) //if no data if (0 >= handle->data_size) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_NO_DATA); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_NO_DATA); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } //if not json term_data[handle->data_size] = '\0'; - GNUNET_memcpy (term_data, handle->data, handle->data_size); - data_js = json_loads (term_data, JSON_DECODE_ANY, &err); + GNUNET_memcpy(term_data, handle->data, handle->data_size); + data_js = json_loads(term_data, JSON_DECODE_ANY, &err); if (NULL == data_js) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_NO_DATA); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_NO_DATA); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } newname = NULL; //NEW NAME json_state = 0; - json_state = json_unpack (data_js, - "{s:s!}", - GNUNET_REST_IDENTITY_PARAM_NEWNAME, - &newname); + json_state = json_unpack(data_js, + "{s:s!}", + GNUNET_REST_IDENTITY_PARAM_NEWNAME, + &newname); //Change name with pubkey or name identifier if (0 != json_state) - { - - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_DATA_INVALID); - GNUNET_SCHEDULER_add_now (&do_error, handle); - json_decref (data_js); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_DATA_INVALID); + GNUNET_SCHEDULER_add_now(&do_error, handle); + json_decref(data_js); + return; + } if (NULL == newname) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_DATA_INVALID); - GNUNET_SCHEDULER_add_now (&do_error, handle); - json_decref (data_js); - return; - } - - if (0 >= strlen (newname)) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_DATA_INVALID); - GNUNET_SCHEDULER_add_now (&do_error, handle); - json_decref (data_js); - return; - } - - ego_entry_tmp = get_egoentry (handle, NULL, newname); + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_DATA_INVALID); + GNUNET_SCHEDULER_add_now(&do_error, handle); + json_decref(data_js); + return; + } + + if (0 >= strlen(newname)) + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_DATA_INVALID); + GNUNET_SCHEDULER_add_now(&do_error, handle); + json_decref(data_js); + return; + } + + ego_entry_tmp = get_egoentry(handle, NULL, newname); if (NULL != ego_entry_tmp) - { - //Ego with same name not allowed (even if its the ego we change) - resp = GNUNET_REST_create_response (NULL); - handle->proc (handle->proc_cls, resp, MHD_HTTP_CONFLICT); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); - json_decref (data_js); - return; - } - handle->op = GNUNET_IDENTITY_rename (handle->identity_handle, - ego_entry->identifier, - newname, - &do_finished, - handle); + { + //Ego with same name not allowed (even if its the ego we change) + resp = GNUNET_REST_create_response(NULL); + handle->proc(handle->proc_cls, resp, MHD_HTTP_CONFLICT); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); + json_decref(data_js); + return; + } + handle->op = GNUNET_IDENTITY_rename(handle->identity_handle, + ego_entry->identifier, + newname, + &do_finished, + handle); if (NULL == handle->op) - { - handle->emsg = GNUNET_strdup ("Rename failed"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - json_decref (data_js); - return; - } - json_decref (data_js); + { + handle->emsg = GNUNET_strdup("Rename failed"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + json_decref(data_js); + return; + } + json_decref(data_js); return; } @@ -758,9 +755,9 @@ ego_edit (struct RequestHandle *handle, struct EgoEntry *ego_entry) * @param cls the RequestHandle */ void -ego_edit_pubkey (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +ego_edit_pubkey(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; @@ -768,25 +765,25 @@ ego_edit_pubkey (struct GNUNET_REST_RequestHandle *con_handle, keystring = NULL; - if (strlen (GNUNET_REST_API_NS_IDENTITY_PUBKEY) >= strlen (handle->url)) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_MISSING_PUBKEY); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - keystring = &handle->url[strlen (GNUNET_REST_API_NS_IDENTITY_PUBKEY) + 1]; - ego_entry = get_egoentry (handle, keystring, NULL); + if (strlen(GNUNET_REST_API_NS_IDENTITY_PUBKEY) >= strlen(handle->url)) + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_MISSING_PUBKEY); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + keystring = &handle->url[strlen(GNUNET_REST_API_NS_IDENTITY_PUBKEY) + 1]; + ego_entry = get_egoentry(handle, keystring, NULL); if (NULL == ego_entry) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - - ego_edit (handle, ego_entry); + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + + ego_edit(handle, ego_entry); } /** @@ -797,9 +794,9 @@ ego_edit_pubkey (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ void -ego_edit_name (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +ego_edit_name(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; @@ -807,25 +804,25 @@ ego_edit_name (struct GNUNET_REST_RequestHandle *con_handle, name = NULL; - if (strlen (GNUNET_REST_API_NS_IDENTITY_NAME) >= strlen (handle->url)) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_MISSING_NAME); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - name = &handle->url[strlen (GNUNET_REST_API_NS_IDENTITY_NAME) + 1]; - ego_entry = get_egoentry (handle, NULL, name); + if (strlen(GNUNET_REST_API_NS_IDENTITY_NAME) >= strlen(handle->url)) + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_MISSING_NAME); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + name = &handle->url[strlen(GNUNET_REST_API_NS_IDENTITY_NAME) + 1]; + ego_entry = get_egoentry(handle, NULL, name); if (NULL == ego_entry) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - - ego_edit (handle, ego_entry); + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + + ego_edit(handle, ego_entry); } /** @@ -836,9 +833,9 @@ ego_edit_name (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ void -ego_edit_subsystem (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +ego_edit_subsystem(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; @@ -851,88 +848,88 @@ ego_edit_subsystem (struct GNUNET_REST_RequestHandle *con_handle, name = NULL; - if (strlen (GNUNET_REST_API_NS_IDENTITY_SUBSYSTEM) >= strlen (handle->url)) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_MISSING_NAME); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - name = &handle->url[strlen (GNUNET_REST_API_NS_IDENTITY_SUBSYSTEM) + 1]; - ego_entry = get_egoentry (handle, NULL, name); + if (strlen(GNUNET_REST_API_NS_IDENTITY_SUBSYSTEM) >= strlen(handle->url)) + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_MISSING_NAME); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + name = &handle->url[strlen(GNUNET_REST_API_NS_IDENTITY_SUBSYSTEM) + 1]; + ego_entry = get_egoentry(handle, NULL, name); if (NULL == ego_entry) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } //if no data if (0 >= handle->data_size) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_NO_DATA); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_NO_DATA); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } //if not json term_data[handle->data_size] = '\0'; - GNUNET_memcpy (term_data, handle->data, handle->data_size); - data_js = json_loads (term_data, JSON_DECODE_ANY, &err); + GNUNET_memcpy(term_data, handle->data, handle->data_size); + data_js = json_loads(term_data, JSON_DECODE_ANY, &err); if (NULL == data_js) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_NO_DATA); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_NO_DATA); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } newsubsys = NULL; //SUBSYSTEM json_state = 0; - json_state = json_unpack (data_js, - "{s:s!}", - GNUNET_REST_IDENTITY_PARAM_SUBSYSTEM, - &newsubsys); + json_state = json_unpack(data_js, + "{s:s!}", + GNUNET_REST_IDENTITY_PARAM_SUBSYSTEM, + &newsubsys); //Change subsystem with pubkey or name identifier if (0 != json_state) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_DATA_INVALID); - GNUNET_SCHEDULER_add_now (&do_error, handle); - json_decref (data_js); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_DATA_INVALID); + GNUNET_SCHEDULER_add_now(&do_error, handle); + json_decref(data_js); + return; + } if (NULL == newsubsys) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_DATA_INVALID); - GNUNET_SCHEDULER_add_now (&do_error, handle); - json_decref (data_js); - return; - } - - if (0 >= strlen (newsubsys)) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_DATA_INVALID); - GNUNET_SCHEDULER_add_now (&do_error, handle); - json_decref (data_js); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_DATA_INVALID); + GNUNET_SCHEDULER_add_now(&do_error, handle); + json_decref(data_js); + return; + } + + if (0 >= strlen(newsubsys)) + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_DATA_INVALID); + GNUNET_SCHEDULER_add_now(&do_error, handle); + json_decref(data_js); + return; + } handle->response_code = MHD_HTTP_NO_CONTENT; - handle->op = GNUNET_IDENTITY_set (handle->identity_handle, - newsubsys, - ego_entry->ego, - &do_finished, - handle); + handle->op = GNUNET_IDENTITY_set(handle->identity_handle, + newsubsys, + ego_entry->ego, + &do_finished, + handle); if (NULL == handle->op) - { - handle->emsg = GNUNET_strdup ("Setting subsystem failed"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - json_decref (data_js); + { + handle->emsg = GNUNET_strdup("Setting subsystem failed"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + json_decref(data_js); return; } @@ -944,9 +941,9 @@ ego_edit_subsystem (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ void -ego_create (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +ego_create(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; @@ -957,73 +954,73 @@ ego_create (struct GNUNET_REST_RequestHandle *con_handle, int json_unpack_state; char term_data[handle->data_size + 1]; - if (strlen (GNUNET_REST_API_NS_IDENTITY) != strlen (handle->url)) - { - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + if (strlen(GNUNET_REST_API_NS_IDENTITY) != strlen(handle->url)) + { + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } if (0 >= handle->data_size) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_NO_DATA); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_NO_DATA); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } term_data[handle->data_size] = '\0'; - GNUNET_memcpy (term_data, handle->data, handle->data_size); - data_js = json_loads (term_data, JSON_DECODE_ANY, &err); + GNUNET_memcpy(term_data, handle->data, handle->data_size); + data_js = json_loads(term_data, JSON_DECODE_ANY, &err); if (NULL == data_js) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_NO_DATA); - GNUNET_SCHEDULER_add_now (&do_error, handle); - json_decref (data_js); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_NO_DATA); + GNUNET_SCHEDULER_add_now(&do_error, handle); + json_decref(data_js); + return; + } json_unpack_state = 0; json_unpack_state = - json_unpack (data_js, "{s:s!}", GNUNET_REST_IDENTITY_PARAM_NAME, &egoname); + json_unpack(data_js, "{s:s!}", GNUNET_REST_IDENTITY_PARAM_NAME, &egoname); if (0 != json_unpack_state) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_DATA_INVALID); - GNUNET_SCHEDULER_add_now (&do_error, handle); - json_decref (data_js); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_DATA_INVALID); + GNUNET_SCHEDULER_add_now(&do_error, handle); + json_decref(data_js); + return; + } if (NULL == egoname) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_DATA_INVALID); - GNUNET_SCHEDULER_add_now (&do_error, handle); - json_decref (data_js); - return; - } - if (0 >= strlen (egoname)) - { - json_decref (data_js); - handle->emsg = GNUNET_strdup (GNUNET_REST_ERROR_DATA_INVALID); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - GNUNET_STRINGS_utf8_tolower (egoname, egoname); + { + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_DATA_INVALID); + GNUNET_SCHEDULER_add_now(&do_error, handle); + json_decref(data_js); + return; + } + if (0 >= strlen(egoname)) + { + json_decref(data_js); + handle->emsg = GNUNET_strdup(GNUNET_REST_ERROR_DATA_INVALID); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + GNUNET_STRINGS_utf8_tolower(egoname, egoname); for (ego_entry = handle->ego_head; NULL != ego_entry; ego_entry = ego_entry->next) - { - if (0 == strcasecmp (egoname, ego_entry->identifier)) { - resp = GNUNET_REST_create_response (NULL); - handle->proc (handle->proc_cls, resp, MHD_HTTP_CONFLICT); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); - json_decref (data_js); - return; + if (0 == strcasecmp(egoname, ego_entry->identifier)) + { + resp = GNUNET_REST_create_response(NULL); + handle->proc(handle->proc_cls, resp, MHD_HTTP_CONFLICT); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); + json_decref(data_js); + return; + } } - } - handle->name = GNUNET_strdup (egoname); - json_decref (data_js); + handle->name = GNUNET_strdup(egoname); + json_decref(data_js); handle->response_code = MHD_HTTP_CREATED; - handle->op = GNUNET_IDENTITY_create (handle->identity_handle, - handle->name, - &do_finished_create, - handle); + handle->op = GNUNET_IDENTITY_create(handle->identity_handle, + handle->name, + &do_finished_create, + handle); } /** @@ -1034,9 +1031,9 @@ ego_create (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ void -ego_delete_pubkey (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +ego_delete_pubkey(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; @@ -1044,29 +1041,29 @@ ego_delete_pubkey (struct GNUNET_REST_RequestHandle *con_handle, keystring = NULL; - if (strlen (GNUNET_REST_API_NS_IDENTITY_PUBKEY) >= strlen (handle->url)) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_MISSING_PUBKEY); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - keystring = &handle->url[strlen (GNUNET_REST_API_NS_IDENTITY_PUBKEY) + 1]; - ego_entry = get_egoentry (handle, keystring, NULL); + if (strlen(GNUNET_REST_API_NS_IDENTITY_PUBKEY) >= strlen(handle->url)) + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_MISSING_PUBKEY); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + keystring = &handle->url[strlen(GNUNET_REST_API_NS_IDENTITY_PUBKEY) + 1]; + ego_entry = get_egoentry(handle, keystring, NULL); if (NULL == ego_entry) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } handle->response_code = MHD_HTTP_NO_CONTENT; - handle->op = GNUNET_IDENTITY_delete (handle->identity_handle, - ego_entry->identifier, - &do_finished, - handle); + handle->op = GNUNET_IDENTITY_delete(handle->identity_handle, + ego_entry->identifier, + &do_finished, + handle); } @@ -1078,9 +1075,9 @@ ego_delete_pubkey (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ void -ego_delete_name (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +ego_delete_name(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; @@ -1088,29 +1085,29 @@ ego_delete_name (struct GNUNET_REST_RequestHandle *con_handle, name = NULL; - if (strlen (GNUNET_REST_API_NS_IDENTITY_NAME) >= strlen (handle->url)) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_MISSING_NAME); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - name = &handle->url[strlen (GNUNET_REST_API_NS_IDENTITY_NAME) + 1]; - ego_entry = get_egoentry (handle, NULL, name); + if (strlen(GNUNET_REST_API_NS_IDENTITY_NAME) >= strlen(handle->url)) + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_MISSING_NAME); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + name = &handle->url[strlen(GNUNET_REST_API_NS_IDENTITY_NAME) + 1]; + ego_entry = get_egoentry(handle, NULL, name); if (NULL == ego_entry) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } handle->response_code = MHD_HTTP_NO_CONTENT; - handle->op = GNUNET_IDENTITY_delete (handle->identity_handle, - ego_entry->identifier, - &do_finished, - handle); + handle->op = GNUNET_IDENTITY_delete(handle->identity_handle, + ego_entry->identifier, + &do_finished, + handle); } @@ -1122,18 +1119,18 @@ ego_delete_name (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ static void -options_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +options_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct MHD_Response *resp; struct RequestHandle *handle = cls; //For now, independent of path return all options - resp = GNUNET_REST_create_response (NULL); - MHD_add_response_header (resp, "Access-Control-Allow-Methods", allow_methods); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + resp = GNUNET_REST_create_response(NULL); + MHD_add_response_header(resp, "Access-Control-Allow-Methods", allow_methods); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); return; } @@ -1143,39 +1140,39 @@ options_cont (struct GNUNET_REST_RequestHandle *con_handle, * @param handle the request handle */ static void -init_cont (struct RequestHandle *handle) +init_cont(struct RequestHandle *handle) { struct GNUNET_REST_RequestHandlerError err; static const struct GNUNET_REST_RequestHandler handlers[] = - {{MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_IDENTITY_ALL, &ego_get_all}, - {MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_IDENTITY_PUBKEY, &ego_get_pubkey}, - {MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_IDENTITY_NAME, &ego_get_name}, - {MHD_HTTP_METHOD_GET, - GNUNET_REST_API_NS_IDENTITY_SUBSYSTEM, - &ego_get_subsystem}, - {MHD_HTTP_METHOD_PUT, - GNUNET_REST_API_NS_IDENTITY_PUBKEY, - &ego_edit_pubkey}, - {MHD_HTTP_METHOD_PUT, GNUNET_REST_API_NS_IDENTITY_NAME, &ego_edit_name}, - {MHD_HTTP_METHOD_PUT, - GNUNET_REST_API_NS_IDENTITY_SUBSYSTEM, - &ego_edit_subsystem}, - {MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_IDENTITY, &ego_create}, - {MHD_HTTP_METHOD_DELETE, - GNUNET_REST_API_NS_IDENTITY_PUBKEY, - &ego_delete_pubkey}, - {MHD_HTTP_METHOD_DELETE, - GNUNET_REST_API_NS_IDENTITY_NAME, - &ego_delete_name}, - {MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_IDENTITY, &options_cont}, - GNUNET_REST_HANDLER_END}; + { { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_IDENTITY_ALL, &ego_get_all }, + { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_IDENTITY_PUBKEY, &ego_get_pubkey }, + { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_IDENTITY_NAME, &ego_get_name }, + { MHD_HTTP_METHOD_GET, + GNUNET_REST_API_NS_IDENTITY_SUBSYSTEM, + &ego_get_subsystem }, + { MHD_HTTP_METHOD_PUT, + GNUNET_REST_API_NS_IDENTITY_PUBKEY, + &ego_edit_pubkey }, + { MHD_HTTP_METHOD_PUT, GNUNET_REST_API_NS_IDENTITY_NAME, &ego_edit_name }, + { MHD_HTTP_METHOD_PUT, + GNUNET_REST_API_NS_IDENTITY_SUBSYSTEM, + &ego_edit_subsystem }, + { MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_IDENTITY, &ego_create }, + { MHD_HTTP_METHOD_DELETE, + GNUNET_REST_API_NS_IDENTITY_PUBKEY, + &ego_delete_pubkey }, + { MHD_HTTP_METHOD_DELETE, + GNUNET_REST_API_NS_IDENTITY_NAME, + &ego_delete_name }, + { MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_IDENTITY, &options_cont }, + GNUNET_REST_HANDLER_END }; if (GNUNET_NO == - GNUNET_REST_handle_request (handle->rest_handle, handlers, &err, handle)) - { - handle->response_code = err.error_code; - GNUNET_SCHEDULER_add_now (&do_error, handle); - } + GNUNET_REST_handle_request(handle->rest_handle, handlers, &err, handle)) + { + handle->response_code = err.error_code; + GNUNET_SCHEDULER_add_now(&do_error, handle); + } } /** @@ -1212,32 +1209,32 @@ init_cont (struct RequestHandle *handle) * must thus no longer be used */ static void -init_egos (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *identifier) +init_egos(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *identifier) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; struct GNUNET_CRYPTO_EcdsaPublicKey pk; if ((NULL == ego) && (ID_REST_STATE_INIT == handle->state)) - { - handle->state = ID_REST_STATE_POST_INIT; - init_cont (handle); - return; - } + { + handle->state = ID_REST_STATE_POST_INIT; + init_cont(handle); + return; + } if (ID_REST_STATE_INIT == handle->state) - { - ego_entry = GNUNET_new (struct EgoEntry); - GNUNET_IDENTITY_ego_get_public_key (ego, &pk); - ego_entry->keystring = GNUNET_CRYPTO_ecdsa_public_key_to_string (&pk); - ego_entry->ego = ego; - GNUNET_asprintf (&ego_entry->identifier, "%s", identifier); - GNUNET_CONTAINER_DLL_insert_tail (handle->ego_head, - handle->ego_tail, - ego_entry); - } + { + ego_entry = GNUNET_new(struct EgoEntry); + GNUNET_IDENTITY_ego_get_public_key(ego, &pk); + ego_entry->keystring = GNUNET_CRYPTO_ecdsa_public_key_to_string(&pk); + ego_entry->ego = ego; + GNUNET_asprintf(&ego_entry->identifier, "%s", identifier); + GNUNET_CONTAINER_DLL_insert_tail(handle->ego_head, + handle->ego_tail, + ego_entry); + } } /** @@ -1252,11 +1249,11 @@ init_egos (void *cls, * @return GNUNET_OK if request accepted */ static void -rest_process_request (struct GNUNET_REST_RequestHandle *rest_handle, - GNUNET_REST_ResultProcessor proc, - void *proc_cls) +rest_process_request(struct GNUNET_REST_RequestHandle *rest_handle, + GNUNET_REST_ResultProcessor proc, + void *proc_cls) { - struct RequestHandle *handle = GNUNET_new (struct RequestHandle); + struct RequestHandle *handle = GNUNET_new(struct RequestHandle); handle->response_code = 0; handle->timeout = GNUNET_TIME_UNIT_FOREVER_REL; @@ -1266,17 +1263,17 @@ rest_process_request (struct GNUNET_REST_RequestHandle *rest_handle, handle->data = rest_handle->data; handle->data_size = rest_handle->data_size; - handle->url = GNUNET_strdup (rest_handle->url); - if (handle->url[strlen (handle->url) - 1] == '/') - handle->url[strlen (handle->url) - 1] = '\0'; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n"); + handle->url = GNUNET_strdup(rest_handle->url); + if (handle->url[strlen(handle->url) - 1] == '/') + handle->url[strlen(handle->url) - 1] = '\0'; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n"); - handle->identity_handle = GNUNET_IDENTITY_connect (cfg, &init_egos, handle); + handle->identity_handle = GNUNET_IDENTITY_connect(cfg, &init_egos, handle); handle->timeout_task = - GNUNET_SCHEDULER_add_delayed (handle->timeout, &do_error, handle); + GNUNET_SCHEDULER_add_delayed(handle->timeout, &do_error, handle); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connected\n"); } /** @@ -1286,7 +1283,7 @@ rest_process_request (struct GNUNET_REST_RequestHandle *rest_handle, * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_rest_identity_init (void *cls) +libgnunet_plugin_rest_identity_init(void *cls) { static struct Plugin plugin; struct GNUNET_REST_Plugin *api; @@ -1294,21 +1291,21 @@ libgnunet_plugin_rest_identity_init (void *cls) cfg = cls; if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.cfg = cfg; - api = GNUNET_new (struct GNUNET_REST_Plugin); + api = GNUNET_new(struct GNUNET_REST_Plugin); api->cls = &plugin; api->name = GNUNET_REST_API_NS_IDENTITY; api->process_request = &rest_process_request; - GNUNET_asprintf (&allow_methods, - "%s, %s, %s, %s, %s", - MHD_HTTP_METHOD_GET, - MHD_HTTP_METHOD_POST, - MHD_HTTP_METHOD_PUT, - MHD_HTTP_METHOD_DELETE, - MHD_HTTP_METHOD_OPTIONS); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Identity REST API initialized\n")); + GNUNET_asprintf(&allow_methods, + "%s, %s, %s, %s, %s", + MHD_HTTP_METHOD_GET, + MHD_HTTP_METHOD_POST, + MHD_HTTP_METHOD_PUT, + MHD_HTTP_METHOD_DELETE, + MHD_HTTP_METHOD_OPTIONS); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, _("Identity REST API initialized\n")); return api; } @@ -1319,15 +1316,16 @@ libgnunet_plugin_rest_identity_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_rest_identity_done (void *cls) +libgnunet_plugin_rest_identity_done(void *cls) { struct GNUNET_REST_Plugin *api = cls; struct Plugin *plugin = api->cls; + plugin->cfg = NULL; - GNUNET_free_non_null (allow_methods); - GNUNET_free (api); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Identity REST plugin is finished\n"); + GNUNET_free_non_null(allow_methods); + GNUNET_free(api); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Identity REST plugin is finished\n"); return NULL; } diff --git a/src/identity/test_identity.c b/src/identity/test_identity.c index 74c052917..7f7371422 100644 --- a/src/identity/test_identity.c +++ b/src/identity/test_identity.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file identity/test_identity.c @@ -29,7 +29,7 @@ #include "gnunet_testing_lib.h" -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) /** @@ -54,33 +54,33 @@ static struct GNUNET_SCHEDULER_Task *endbadly_task; #define CHECK(cond) \ do \ - { \ - if (! (cond)) \ - { \ - GNUNET_break (0); \ - end (); \ - return; \ - } \ - } while (0) + { \ + if (!(cond)) \ + { \ + GNUNET_break(0); \ + end(); \ + return; \ + } \ + } while (0) /** * Clean up all resources used. */ static void -cleanup (void *cls) +cleanup(void *cls) { - (void) cls; + (void)cls; if (NULL != op) - { - GNUNET_IDENTITY_cancel (op); - op = NULL; - } + { + GNUNET_IDENTITY_cancel(op); + op = NULL; + } if (NULL != h) - { - GNUNET_IDENTITY_disconnect (h); - h = NULL; - } + { + GNUNET_IDENTITY_disconnect(h); + h = NULL; + } } @@ -90,9 +90,9 @@ cleanup (void *cls) * @param cls NULL */ static void -endbadly (void *cls) +endbadly(void *cls) { - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -100,14 +100,14 @@ endbadly (void *cls) * Finish the testcase (successfully). */ static void -end () +end() { if (NULL != endbadly_task) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } + GNUNET_SCHEDULER_shutdown(); } @@ -123,57 +123,64 @@ end () * must thus no longer be used */ static void -notification_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *identifier) +notification_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *identifier) { static struct GNUNET_IDENTITY_Ego *my_ego; static int round; switch (round) - { - case 0: /* end of initial iteration */ - CHECK (NULL == ego); - CHECK (NULL == identifier); - break; - case 1: /* create */ - CHECK (NULL != ego); - CHECK (NULL != identifier); - CHECK (0 == strcmp (identifier, "test-id")); - my_ego = ego; - *ctx = &round; - break; - case 2: /* rename */ - CHECK (my_ego == ego); - CHECK (NULL != identifier); - CHECK (0 == strcmp (identifier, "test")); - CHECK (*ctx == &round); - break; - case 3: /* reconnect-down */ - CHECK (my_ego == ego); - CHECK (NULL == identifier); - CHECK (*ctx == &round); - *ctx = NULL; - break; - case 4: /* reconnect-up */ - CHECK (NULL != identifier); - CHECK (0 == strcmp (identifier, "test")); - my_ego = ego; - *ctx = &round; - break; - case 5: /* end of iteration after reconnect */ - CHECK (NULL == ego); - CHECK (NULL == identifier); - break; - case 6: /* delete */ - CHECK (my_ego == ego); - CHECK (*ctx == &round); - *ctx = NULL; - break; - default: - CHECK (0); - } + { + case 0: /* end of initial iteration */ + CHECK(NULL == ego); + CHECK(NULL == identifier); + break; + + case 1: /* create */ + CHECK(NULL != ego); + CHECK(NULL != identifier); + CHECK(0 == strcmp(identifier, "test-id")); + my_ego = ego; + *ctx = &round; + break; + + case 2: /* rename */ + CHECK(my_ego == ego); + CHECK(NULL != identifier); + CHECK(0 == strcmp(identifier, "test")); + CHECK(*ctx == &round); + break; + + case 3: /* reconnect-down */ + CHECK(my_ego == ego); + CHECK(NULL == identifier); + CHECK(*ctx == &round); + *ctx = NULL; + break; + + case 4: /* reconnect-up */ + CHECK(NULL != identifier); + CHECK(0 == strcmp(identifier, "test")); + my_ego = ego; + *ctx = &round; + break; + + case 5: /* end of iteration after reconnect */ + CHECK(NULL == ego); + CHECK(NULL == identifier); + break; + + case 6: /* delete */ + CHECK(my_ego == ego); + CHECK(*ctx == &round); + *ctx = NULL; + break; + + default: + CHECK(0); + } round++; } @@ -185,12 +192,12 @@ notification_cb (void *cls, * @param emsg (should also be NULL) */ static void -delete_cont (void *cls, const char *emsg) +delete_cont(void *cls, const char *emsg) { op = NULL; - CHECK (NULL == emsg); + CHECK(NULL == emsg); res = 0; - end (); + end(); } @@ -200,9 +207,9 @@ delete_cont (void *cls, const char *emsg) * @param cls NULL */ static void -finally_delete (void *cls) +finally_delete(void *cls) { - op = GNUNET_IDENTITY_delete (h, "test", &delete_cont, NULL); + op = GNUNET_IDENTITY_delete(h, "test", &delete_cont, NULL); } @@ -213,13 +220,13 @@ finally_delete (void *cls) * @param emsg (should also be NULL) */ static void -fail_rename_cont (void *cls, const char *emsg) +fail_rename_cont(void *cls, const char *emsg) { - CHECK (NULL != emsg); + CHECK(NULL != emsg); op = NULL; - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &finally_delete, - NULL); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &finally_delete, + NULL); } @@ -230,10 +237,10 @@ fail_rename_cont (void *cls, const char *emsg) * @param emsg (should also be NULL) */ static void -success_rename_cont (void *cls, const char *emsg) +success_rename_cont(void *cls, const char *emsg) { - CHECK (NULL == emsg); - op = GNUNET_IDENTITY_rename (h, "test-id", "test", &fail_rename_cont, NULL); + CHECK(NULL == emsg); + op = GNUNET_IDENTITY_rename(h, "test-id", "test", &fail_rename_cont, NULL); } @@ -245,14 +252,14 @@ success_rename_cont (void *cls, const char *emsg) * @param emsg error message */ static void -create_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, - const char *emsg) +create_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, + const char *emsg) { - CHECK (NULL != pk); - CHECK (NULL == emsg); + CHECK(NULL != pk); + CHECK(NULL == emsg); op = - GNUNET_IDENTITY_rename (h, "test-id", "test", &success_rename_cont, NULL); + GNUNET_IDENTITY_rename(h, "test-id", "test", &success_rename_cont, NULL); } @@ -264,30 +271,30 @@ create_cb (void *cls, * @param peer handle to access more of the peer (not used) */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, &endbadly, NULL); - GNUNET_SCHEDULER_add_shutdown (&cleanup, NULL); - h = GNUNET_IDENTITY_connect (cfg, ¬ification_cb, NULL); - CHECK (NULL != h); - op = GNUNET_IDENTITY_create (h, "test-id", &create_cb, NULL); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, &endbadly, NULL); + GNUNET_SCHEDULER_add_shutdown(&cleanup, NULL); + h = GNUNET_IDENTITY_connect(cfg, ¬ification_cb, NULL); + CHECK(NULL != h); + op = GNUNET_IDENTITY_create(h, "test-id", &create_cb, NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - GNUNET_DISK_directory_remove ("/tmp/gnunet/test-identity-service"); + GNUNET_DISK_directory_remove("/tmp/gnunet/test-identity-service"); res = 1; - if (0 != GNUNET_TESTING_service_run ("test-identity", - "identity", - "test_identity.conf", - &run, - NULL)) + if (0 != GNUNET_TESTING_service_run("test-identity", + "identity", + "test_identity.conf", + &run, + NULL)) return 1; - GNUNET_DISK_directory_remove ("/tmp/gnunet/test-identity-service"); + GNUNET_DISK_directory_remove("/tmp/gnunet/test-identity-service"); return res; } diff --git a/src/identity/test_identity_defaults.c b/src/identity/test_identity_defaults.c index 71e70e7ba..6e14022c6 100644 --- a/src/identity/test_identity_defaults.c +++ b/src/identity/test_identity_defaults.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file identity/test_identity.c @@ -29,7 +29,7 @@ #include "gnunet_testing_lib.h" -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) /** @@ -54,33 +54,33 @@ static struct GNUNET_SCHEDULER_Task *endbadly_task; #define CHECK(cond) \ do \ - { \ - if (! (cond)) \ - { \ - GNUNET_break (0); \ - end (); \ - return; \ - } \ - } while (0) + { \ + if (!(cond)) \ + { \ + GNUNET_break(0); \ + end(); \ + return; \ + } \ + } while (0) /** * Clean up all resources used. */ static void -cleanup (void *cls) +cleanup(void *cls) { - (void) cls; + (void)cls; if (NULL != op) - { - GNUNET_IDENTITY_cancel (op); - op = NULL; - } + { + GNUNET_IDENTITY_cancel(op); + op = NULL; + } if (NULL != h) - { - GNUNET_IDENTITY_disconnect (h); - h = NULL; - } + { + GNUNET_IDENTITY_disconnect(h); + h = NULL; + } } @@ -90,9 +90,9 @@ cleanup (void *cls) * @param cls NULL */ static void -endbadly (void *cls) +endbadly(void *cls) { - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); res = 1; } @@ -101,14 +101,14 @@ endbadly (void *cls) * Termiante the testcase. */ static void -end () +end() { if (NULL != endbadly_task) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } + GNUNET_SCHEDULER_shutdown(); } @@ -119,12 +119,12 @@ end () * @param emsg (should also be NULL) */ static void -delete_cont (void *cls, const char *emsg) +delete_cont(void *cls, const char *emsg) { op = NULL; - CHECK (NULL == emsg); + CHECK(NULL == emsg); res = 0; - end (); + end(); } @@ -135,16 +135,16 @@ delete_cont (void *cls, const char *emsg) * @param emsg (should also be NULL) */ static void -get_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *identifier) +get_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *identifier) { op = NULL; - CHECK (NULL != ego); - CHECK (NULL != identifier); - CHECK (0 == strcmp (identifier, "test-id")); - op = GNUNET_IDENTITY_delete (h, "test-id", &delete_cont, NULL); + CHECK(NULL != ego); + CHECK(NULL != identifier); + CHECK(0 == strcmp(identifier, "test-id")); + op = GNUNET_IDENTITY_delete(h, "test-id", &delete_cont, NULL); } @@ -160,15 +160,15 @@ get_cb (void *cls, * must thus no longer be used */ static void -dummy_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *identifier) +dummy_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *identifier) { - (void) cls; - (void) ego; - (void) ctx; - (void) identifier; + (void)cls; + (void)ego; + (void)ctx; + (void)identifier; } @@ -180,15 +180,15 @@ dummy_cb (void *cls, * @param peer handle to access more of the peer (not used) */ static void -run_get (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run_get(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, &endbadly, NULL); - GNUNET_SCHEDULER_add_shutdown (&cleanup, NULL); - h = GNUNET_IDENTITY_connect (cfg, &dummy_cb, NULL); - CHECK (NULL != h); - op = GNUNET_IDENTITY_get (h, "test-service", &get_cb, NULL); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, &endbadly, NULL); + GNUNET_SCHEDULER_add_shutdown(&cleanup, NULL); + h = GNUNET_IDENTITY_connect(cfg, &dummy_cb, NULL); + CHECK(NULL != h); + op = GNUNET_IDENTITY_get(h, "test-service", &get_cb, NULL); } @@ -199,11 +199,11 @@ run_get (void *cls, * @param emsg (should also be NULL) */ static void -success_set_cont (void *cls, const char *emsg) +success_set_cont(void *cls, const char *emsg) { op = NULL; - CHECK (NULL == emsg); - end (); + CHECK(NULL == emsg); + end(); } @@ -219,16 +219,16 @@ success_set_cont (void *cls, const char *emsg) * must thus no longer be used */ static void -notification_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *identifier) +notification_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *identifier) { if (NULL == ego) return; /* skip first call */ if (NULL == identifier) return; /* deletion / shutdown */ - op = GNUNET_IDENTITY_set (h, "test-service", ego, &success_set_cont, NULL); + op = GNUNET_IDENTITY_set(h, "test-service", ego, &success_set_cont, NULL); } @@ -240,12 +240,12 @@ notification_cb (void *cls, * @param emsg error message */ static void -create_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, - const char *emsg) +create_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pk, + const char *emsg) { - CHECK (NULL == emsg); - CHECK (NULL != pk); + CHECK(NULL == emsg); + CHECK(NULL != pk); op = NULL; } @@ -258,36 +258,36 @@ create_cb (void *cls, * @param peer handle to access more of the peer (not used) */ static void -run_set (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run_set(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, &endbadly, NULL); - GNUNET_SCHEDULER_add_shutdown (&cleanup, NULL); - h = GNUNET_IDENTITY_connect (cfg, ¬ification_cb, NULL); - CHECK (NULL != h); - op = GNUNET_IDENTITY_create (h, "test-id", &create_cb, NULL); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, &endbadly, NULL); + GNUNET_SCHEDULER_add_shutdown(&cleanup, NULL); + h = GNUNET_IDENTITY_connect(cfg, ¬ification_cb, NULL); + CHECK(NULL != h); + op = GNUNET_IDENTITY_create(h, "test-id", &create_cb, NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - GNUNET_DISK_directory_remove ("/tmp/gnunet/test-identity-service"); + GNUNET_DISK_directory_remove("/tmp/gnunet/test-identity-service"); res = 1; - if (0 != GNUNET_TESTING_service_run ("test-identity-defaults", - "identity", - "test_identity.conf", - &run_set, - NULL)) + if (0 != GNUNET_TESTING_service_run("test-identity-defaults", + "identity", + "test_identity.conf", + &run_set, + NULL)) return 1; - if (0 != GNUNET_TESTING_service_run ("test-identity-defaults", - "identity", - "test_identity.conf", - &run_get, - NULL)) + if (0 != GNUNET_TESTING_service_run("test-identity-defaults", + "identity", + "test_identity.conf", + &run_get, + NULL)) return 1; - GNUNET_DISK_directory_remove ("/tmp/gnunet/test-identity-service"); + GNUNET_DISK_directory_remove("/tmp/gnunet/test-identity-service"); return res; } diff --git a/src/include/block_dns.h b/src/include/block_dns.h index 399b34962..2e94e8c02 100644 --- a/src/include/block_dns.h +++ b/src/include/block_dns.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -37,8 +37,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * This is the structure describing an DNS exit service. */ -struct GNUNET_DNS_Advertisement -{ +struct GNUNET_DNS_Advertisement { /** * Signature of the peer affirming that it is offering the service. */ @@ -59,7 +58,6 @@ struct GNUNET_DNS_Advertisement * The peer providing this service */ struct GNUNET_PeerIdentity peer; - }; GNUNET_NETWORK_STRUCT_END diff --git a/src/include/block_fs.h b/src/include/block_fs.h index b5c8d71d4..fb651909a 100644 --- a/src/include/block_fs.h +++ b/src/include/block_fs.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -47,9 +47,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * @brief universal block for keyword and namespace search results */ -struct UBlock -{ - +struct UBlock { /** * Signature using pseudonym and search keyword / identifier. */ @@ -72,7 +70,6 @@ struct UBlock /* 0-terminated URI here */ /* variable-size Meta-Data follows here */ - }; @@ -81,8 +78,7 @@ struct UBlock * can be obtained directly from reading * the plaintext file) */ -struct OnDemandBlock -{ +struct OnDemandBlock { /** * Hash code of the entire content of the * file that was indexed (used to uniquely @@ -95,7 +91,6 @@ struct OnDemandBlock * this on-demand encoded block? (in NBO) */ uint64_t offset GNUNET_PACKED; - }; GNUNET_NETWORK_STRUCT_END diff --git a/src/include/block_regex.h b/src/include/block_regex.h index 499655977..e29785cdf 100644 --- a/src/include/block_regex.h +++ b/src/include/block_regex.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file @@ -31,7 +31,7 @@ extern "C" { #if 0 - /* keep Emacsens' auto-indent happy */ +/* keep Emacsens' auto-indent happy */ } #endif #endif @@ -46,9 +46,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * @brief Block to announce a peer accepting a state. */ -struct RegexAcceptBlock -{ - +struct RegexAcceptBlock { /** * Accept blocks must be signed. Signature * goes over expiration time and key. diff --git a/src/include/compat.h b/src/include/compat.h index b24d09653..1a1103a81 100644 --- a/src/include/compat.h +++ b/src/include/compat.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Martin Schanzenbach @@ -33,7 +33,7 @@ extern "C" { #endif - /** +/** * memrchr as defined in glibc * * @param s pointer to memory @@ -41,11 +41,11 @@ extern "C" * @param n search character limit */ void* -GN_memrchr_ (const void *s, - int c, - size_t n); +GN_memrchr_(const void *s, + int c, + size_t n); #ifndef HAVE_MEMRCHR -#define memrchr(s,c,n) GN_memrchr_(s,c,n) +#define memrchr(s, c, n) GN_memrchr_(s, c, n) #endif #ifdef __cplusplus diff --git a/src/include/gauger.h b/src/include/gauger.h index 54ba7f1f7..d23883742 100644 --- a/src/include/gauger.h +++ b/src/include/gauger.h @@ -17,67 +17,67 @@ #include #include -#define GAUGER(category, counter, value, unit)\ -{\ - char* __gauger_v[10];\ - char __gauger_s[32];\ - pid_t __gauger_p;\ - if(!(__gauger_p=fork())){\ - close (1); \ - close (2); \ - if(!fork()){\ - sprintf(__gauger_s,"%Lf", (long double) (value));\ - __gauger_v[0] = "gauger";\ - __gauger_v[1] = "-n";\ - __gauger_v[2] = (char*) (counter); \ - __gauger_v[3] = "-d";\ - __gauger_v[4] = __gauger_s;\ - __gauger_v[5] = "-u";\ - __gauger_v[6] = (char*) (unit); \ - __gauger_v[7] = "-c";\ - __gauger_v[8] = (char*) (category); \ - __gauger_v[9] = (char*) NULL;\ - execvp("gauger",__gauger_v);\ - _exit(1);\ - }else{\ - _exit(0);\ - }\ - }else{\ - waitpid(__gauger_p,NULL,0);\ - }\ -} +#define GAUGER(category, counter, value, unit) \ + { \ + char* __gauger_v[10]; \ + char __gauger_s[32]; \ + pid_t __gauger_p; \ + if (!(__gauger_p = fork())) { \ + close(1); \ + close(2); \ + if (!fork()) { \ + sprintf(__gauger_s, "%Lf", (long double)(value)); \ + __gauger_v[0] = "gauger"; \ + __gauger_v[1] = "-n"; \ + __gauger_v[2] = (char*)(counter); \ + __gauger_v[3] = "-d"; \ + __gauger_v[4] = __gauger_s; \ + __gauger_v[5] = "-u"; \ + __gauger_v[6] = (char*)(unit); \ + __gauger_v[7] = "-c"; \ + __gauger_v[8] = (char*)(category); \ + __gauger_v[9] = (char*)NULL; \ + execvp("gauger", __gauger_v); \ + _exit(1); \ + }else{ \ + _exit(0); \ + } \ + }else{ \ + waitpid(__gauger_p, NULL, 0); \ + } \ + } -#define GAUGER_ID(category, counter, value, unit, id)\ -{\ - char* __gauger_v[12];\ - char __gauger_s[32];\ - pid_t __gauger_p;\ - if(!(__gauger_p=fork())){\ - close (1); \ - close (2); \ - if(!fork()){\ - sprintf(__gauger_s,"%Lf", (long double) (value));\ - __gauger_v[0] = "gauger";\ - __gauger_v[1] = "-n";\ - __gauger_v[2] = (char*) (counter); \ - __gauger_v[3] = "-d";\ - __gauger_v[4] = __gauger_s;\ - __gauger_v[5] = "-u";\ - __gauger_v[6] = (char*) (unit); \ - __gauger_v[7] = "-i";\ - __gauger_v[8] = id;\ - __gauger_v[9] = "-c";\ - __gauger_v[10] = (char *) (category); \ - __gauger_v[11] = (char *) NULL;\ - execvp("gauger",__gauger_v);\ - _exit(1);\ - }else{\ - _exit(0);\ - }\ - }else{\ - waitpid(__gauger_p, NULL, 0);\ - }\ -} +#define GAUGER_ID(category, counter, value, unit, id) \ + { \ + char* __gauger_v[12]; \ + char __gauger_s[32]; \ + pid_t __gauger_p; \ + if (!(__gauger_p = fork())) { \ + close(1); \ + close(2); \ + if (!fork()) { \ + sprintf(__gauger_s, "%Lf", (long double)(value)); \ + __gauger_v[0] = "gauger"; \ + __gauger_v[1] = "-n"; \ + __gauger_v[2] = (char*)(counter); \ + __gauger_v[3] = "-d"; \ + __gauger_v[4] = __gauger_s; \ + __gauger_v[5] = "-u"; \ + __gauger_v[6] = (char*)(unit); \ + __gauger_v[7] = "-i"; \ + __gauger_v[8] = id; \ + __gauger_v[9] = "-c"; \ + __gauger_v[10] = (char *)(category); \ + __gauger_v[11] = (char *)NULL; \ + execvp("gauger", __gauger_v); \ + _exit(1); \ + }else{ \ + _exit(0); \ + } \ + }else{ \ + waitpid(__gauger_p, NULL, 0); \ + } \ + } #else /* WINDOWS */ @@ -85,25 +85,25 @@ #include #include -#define GAUGER(category, counter, value, unit)\ -{\ - char __gauger_commandline[MAX_PATH];\ +#define GAUGER(category, counter, value, unit) \ + { \ + char __gauger_commandline[MAX_PATH]; \ \ - snprintf (__gauger_commandline, MAX_PATH, "gauger.py -n \"%s\" -d \"%Lf\" -u \"%s\" -c \"%s\"",\ - (counter), (long double) (value), (unit), (category)); \ - __gauger_commandline[MAX_PATH - 1] = '\0';\ - system (__gauger_commandline);\ -} + snprintf(__gauger_commandline, MAX_PATH, "gauger.py -n \"%s\" -d \"%Lf\" -u \"%s\" -c \"%s\"", \ + (counter), (long double)(value), (unit), (category)); \ + __gauger_commandline[MAX_PATH - 1] = '\0'; \ + system(__gauger_commandline); \ + } -#define GAUGER_ID(category, counter, value, unit, id)\ -{\ - char __gauger_commandline[MAX_PATH];\ +#define GAUGER_ID(category, counter, value, unit, id) \ + { \ + char __gauger_commandline[MAX_PATH]; \ \ - snprintf (__gauger_commandline, MAX_PATH, "gauger.py -n \"%s\" -d \"%Lf\" -u \"%s\" -i \"%s\" -c \"%s\"",\ - (counter), (long double) (value), (unit), (id), (category)); \ - __gauger_commandline[MAX_PATH - 1] = '\0';\ - system (__gauger_commandline);\ -} + snprintf(__gauger_commandline, MAX_PATH, "gauger.py -n \"%s\" -d \"%Lf\" -u \"%s\" -i \"%s\" -c \"%s\"", \ + (counter), (long double)(value), (unit), (id), (category)); \ + __gauger_commandline[MAX_PATH - 1] = '\0'; \ + system(__gauger_commandline); \ + } #endif // WINDOWS diff --git a/src/include/gettext.h b/src/include/gettext.h index 9a5be728f..1eb6cee93 100644 --- a/src/include/gettext.h +++ b/src/include/gettext.h @@ -42,20 +42,20 @@ for invalid uses of the value returned from these functions. On pre-ANSI systems without 'const', the config.h file is supposed to contain "#define const". */ -#define gettext(Msgid) ((const char *) (Msgid)) -#define dgettext(Domainname, Msgid) ((const char *) (Msgid)) -#define dcgettext(Domainname, Msgid, Category) ((const char *) (Msgid)) +#define gettext(Msgid) ((const char *)(Msgid)) +#define dgettext(Domainname, Msgid) ((const char *)(Msgid)) +#define dcgettext(Domainname, Msgid, Category) ((const char *)(Msgid)) #define ngettext(Msgid1, Msgid2, N) \ - ((N) == 1 ? (const char *) (Msgid1) : (const char *) (Msgid2)) + ((N) == 1 ? (const char *)(Msgid1) : (const char *)(Msgid2)) #define dngettext(Domainname, Msgid1, Msgid2, N) \ - ((N) == 1 ? (const char *) (Msgid1) : (const char *) (Msgid2)) + ((N) == 1 ? (const char *)(Msgid1) : (const char *)(Msgid2)) #define dcngettext(Domainname, Msgid1, Msgid2, N, Category) \ - ((N) == 1 ? (const char *) (Msgid1) : (const char *) (Msgid2)) + ((N) == 1 ? (const char *)(Msgid1) : (const char *)(Msgid2)) /* slight modification here to avoid warnings: generate GNUNET_NO code, not even the cast... */ #define textdomain(Domainname) #define bindtextdomain(Domainname, Dirname) -#define bind_textdomain_codeset(Domainname, Codeset) ((const char *) (Codeset)) +#define bind_textdomain_codeset(Domainname, Codeset) ((const char *)(Codeset)) #endif diff --git a/src/include/gnunet_abe_lib.h b/src/include/gnunet_abe_lib.h index 89129ea32..1988f4dec 100644 --- a/src/include/gnunet_abe_lib.h +++ b/src/include/gnunet_abe_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file include/gnunet_abe_lib.h @@ -60,7 +60,7 @@ struct GNUNET_CRYPTO_AbeKey; * @return fresh private key; free using #GNUNET_ABE_cpabe_delete_master_key */ struct GNUNET_ABE_AbeMasterKey * -GNUNET_ABE_cpabe_create_master_key (void); +GNUNET_ABE_cpabe_create_master_key(void); /** * @ingroup abe @@ -70,7 +70,7 @@ GNUNET_ABE_cpabe_create_master_key (void); * @return fresh private key; free using #GNUNET_free */ void -GNUNET_ABE_cpabe_delete_master_key (struct GNUNET_ABE_AbeMasterKey *key); +GNUNET_ABE_cpabe_delete_master_key(struct GNUNET_ABE_AbeMasterKey *key); /** * @ingroup abe @@ -81,8 +81,8 @@ GNUNET_ABE_cpabe_delete_master_key (struct GNUNET_ABE_AbeMasterKey *key); * @return fresh private key; free using #GNUNET_ABE_cpabe_delete_key */ struct GNUNET_ABE_AbeKey * -GNUNET_ABE_cpabe_create_key (struct GNUNET_ABE_AbeMasterKey *key, - char **attrs); +GNUNET_ABE_cpabe_create_key(struct GNUNET_ABE_AbeMasterKey *key, + char **attrs); /** * @ingroup abe @@ -93,8 +93,8 @@ GNUNET_ABE_cpabe_create_key (struct GNUNET_ABE_AbeMasterKey *key, * @return fresh private key; free using #GNUNET_free */ void -GNUNET_ABE_cpabe_delete_key (struct GNUNET_ABE_AbeKey *key, - int delete_pub); +GNUNET_ABE_cpabe_delete_key(struct GNUNET_ABE_AbeKey *key, + int delete_pub); /** @@ -109,11 +109,11 @@ GNUNET_ABE_cpabe_delete_key (struct GNUNET_ABE_AbeKey *key, * @return the size of the encrypted block, -1 for errors */ ssize_t -GNUNET_ABE_cpabe_encrypt (const void *block, - size_t size, - const char *policy, - const struct GNUNET_ABE_AbeMasterKey *key, - void **result); +GNUNET_ABE_cpabe_encrypt(const void *block, + size_t size, + const char *policy, + const struct GNUNET_ABE_AbeMasterKey *key, + void **result); /** * @ingroup abe @@ -126,10 +126,10 @@ GNUNET_ABE_cpabe_encrypt (const void *block, * @return the size of the encrypted block, -1 for errors */ ssize_t -GNUNET_ABE_cpabe_decrypt (const void *block, - size_t size, - const struct GNUNET_ABE_AbeKey *key, - void **result); +GNUNET_ABE_cpabe_decrypt(const void *block, + size_t size, + const struct GNUNET_ABE_AbeKey *key, + void **result); /** * @ingroup abe @@ -140,8 +140,8 @@ GNUNET_ABE_cpabe_decrypt (const void *block, * @return the size of the encrypted block, -1 for errors */ ssize_t -GNUNET_ABE_cpabe_serialize_key (const struct GNUNET_ABE_AbeKey *key, - void **result); +GNUNET_ABE_cpabe_serialize_key(const struct GNUNET_ABE_AbeKey *key, + void **result); /** * @ingroup abe @@ -152,8 +152,8 @@ GNUNET_ABE_cpabe_serialize_key (const struct GNUNET_ABE_AbeKey *key, * @return the ABE key. NULL of unsuccessful */ struct GNUNET_ABE_AbeKey* -GNUNET_ABE_cpabe_deserialize_key (const void *data, - size_t len); +GNUNET_ABE_cpabe_deserialize_key(const void *data, + size_t len); /** * @ingroup abe @@ -164,8 +164,8 @@ GNUNET_ABE_cpabe_deserialize_key (const void *data, * @return the size of the encrypted block, -1 for errors */ ssize_t -GNUNET_ABE_cpabe_serialize_master_key (const struct GNUNET_ABE_AbeMasterKey *key, - void **result); +GNUNET_ABE_cpabe_serialize_master_key(const struct GNUNET_ABE_AbeMasterKey *key, + void **result); /** * @ingroup abe @@ -176,8 +176,8 @@ GNUNET_ABE_cpabe_serialize_master_key (const struct GNUNET_ABE_AbeMasterKey *key * @return the ABE key. NULL of unsuccessful */ struct GNUNET_ABE_AbeMasterKey* -GNUNET_ABE_cpabe_deserialize_master_key (const void *data, - size_t len); +GNUNET_ABE_cpabe_deserialize_master_key(const void *data, + size_t len); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_applications.h b/src/include/gnunet_applications.h index 493e1f53e..1e2ac59f7 100644 --- a/src/include/gnunet_applications.h +++ b/src/include/gnunet_applications.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff diff --git a/src/include/gnunet_arm_service.h b/src/include/gnunet_arm_service.h index 1f9d250d0..faf89128f 100644 --- a/src/include/gnunet_arm_service.h +++ b/src/include/gnunet_arm_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -54,8 +54,7 @@ extern "C" /** * Statuses of the requests that client can send to ARM. */ -enum GNUNET_ARM_RequestStatus -{ +enum GNUNET_ARM_RequestStatus { /** * Message was sent successfully. */ @@ -65,15 +64,13 @@ enum GNUNET_ARM_RequestStatus * We disconnected from ARM, and request was not sent. */ GNUNET_ARM_REQUEST_DISCONNECTED = 2 - }; /** * Statuses of services. */ -enum GNUNET_ARM_ServiceStatus -{ +enum GNUNET_ARM_ServiceStatus { /** * Dummy message. */ @@ -99,8 +96,7 @@ enum GNUNET_ARM_ServiceStatus /** * Replies to ARM requests */ -enum GNUNET_ARM_Result -{ +enum GNUNET_ARM_Result { /** * Service was stopped (never sent for ARM itself). */ @@ -222,9 +218,9 @@ typedef void * @return context to use for further ARM operations, NULL on error. */ struct GNUNET_ARM_Handle * -GNUNET_ARM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_ARM_ConnectionStatusCallback conn_status, - void *conn_status_cls); +GNUNET_ARM_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_ARM_ConnectionStatusCallback conn_status, + void *conn_status_cls); /** @@ -233,7 +229,7 @@ GNUNET_ARM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param h the handle that was being used */ void -GNUNET_ARM_disconnect (struct GNUNET_ARM_Handle *h); +GNUNET_ARM_disconnect(struct GNUNET_ARM_Handle *h); /** @@ -243,7 +239,7 @@ GNUNET_ARM_disconnect (struct GNUNET_ARM_Handle *h); * @param op operation to cancel */ void -GNUNET_ARM_operation_cancel (struct GNUNET_ARM_Operation *op); +GNUNET_ARM_operation_cancel(struct GNUNET_ARM_Operation *op); /** @@ -255,9 +251,9 @@ GNUNET_ARM_operation_cancel (struct GNUNET_ARM_Operation *op); * @return handle for the operation, NULL on error */ struct GNUNET_ARM_Operation * -GNUNET_ARM_request_service_list (struct GNUNET_ARM_Handle *h, - GNUNET_ARM_ServiceListCallback cont, - void *cont_cls); +GNUNET_ARM_request_service_list(struct GNUNET_ARM_Handle *h, + GNUNET_ARM_ServiceListCallback cont, + void *cont_cls); /** @@ -275,10 +271,10 @@ GNUNET_ARM_request_service_list (struct GNUNET_ARM_Handle *h, * @return handle for the operation, NULL on error */ struct GNUNET_ARM_Operation * -GNUNET_ARM_request_service_stop (struct GNUNET_ARM_Handle *h, - const char *service_name, - GNUNET_ARM_ResultCallback cont, - void *cont_cls); +GNUNET_ARM_request_service_stop(struct GNUNET_ARM_Handle *h, + const char *service_name, + GNUNET_ARM_ResultCallback cont, + void *cont_cls); /** @@ -292,11 +288,11 @@ GNUNET_ARM_request_service_stop (struct GNUNET_ARM_Handle *h, * @return handle for the operation, NULL on error */ struct GNUNET_ARM_Operation * -GNUNET_ARM_request_service_start (struct GNUNET_ARM_Handle *h, - const char *service_name, - enum GNUNET_OS_InheritStdioFlags std_inheritance, - GNUNET_ARM_ResultCallback cont, - void *cont_cls); +GNUNET_ARM_request_service_start(struct GNUNET_ARM_Handle *h, + const char *service_name, + enum GNUNET_OS_InheritStdioFlags std_inheritance, + GNUNET_ARM_ResultCallback cont, + void *cont_cls); /** @@ -330,9 +326,9 @@ typedef void * @return context to use for further ARM monitor operations, NULL on error. */ struct GNUNET_ARM_MonitorHandle * -GNUNET_ARM_monitor_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_ARM_ServiceStatusCallback cont, - void *cont_cls); +GNUNET_ARM_monitor_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_ARM_ServiceStatusCallback cont, + void *cont_cls); /** @@ -341,7 +337,7 @@ GNUNET_ARM_monitor_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param h the handle that was being used */ void -GNUNET_ARM_monitor_stop (struct GNUNET_ARM_MonitorHandle *h); +GNUNET_ARM_monitor_stop(struct GNUNET_ARM_MonitorHandle *h); #if 0 /* keep Emacsens' auto-indent happy */ { diff --git a/src/include/gnunet_ats_application_service.h b/src/include/gnunet_ats_application_service.h index fbc6f48ac..f11807f22 100644 --- a/src/include/gnunet_ats_application_service.h +++ b/src/include/gnunet_ats_application_service.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2015, 2018 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2015, 2018 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -51,7 +51,7 @@ struct GNUNET_ATS_ApplicationHandle; * @return ats application handle, NULL on error */ struct GNUNET_ATS_ApplicationHandle * -GNUNET_ATS_application_init (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_ATS_application_init(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -60,7 +60,7 @@ GNUNET_ATS_application_init (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param ch handle to destroy */ void -GNUNET_ATS_application_done (struct GNUNET_ATS_ApplicationHandle *ch); +GNUNET_ATS_application_done(struct GNUNET_ATS_ApplicationHandle *ch); /** @@ -82,10 +82,10 @@ struct GNUNET_ATS_ApplicationSuggestHandle; * @return suggestion handle, NULL if request is already pending */ struct GNUNET_ATS_ApplicationSuggestHandle * -GNUNET_ATS_application_suggest (struct GNUNET_ATS_ApplicationHandle *ch, - const struct GNUNET_PeerIdentity *peer, - enum GNUNET_MQ_PreferenceKind pk, - struct GNUNET_BANDWIDTH_Value32NBO bw); +GNUNET_ATS_application_suggest(struct GNUNET_ATS_ApplicationHandle *ch, + const struct GNUNET_PeerIdentity *peer, + enum GNUNET_MQ_PreferenceKind pk, + struct GNUNET_BANDWIDTH_Value32NBO bw); /** @@ -94,7 +94,7 @@ GNUNET_ATS_application_suggest (struct GNUNET_ATS_ApplicationHandle *ch, * @param sh handle */ void -GNUNET_ATS_application_suggest_cancel (struct GNUNET_ATS_ApplicationSuggestHandle *sh); +GNUNET_ATS_application_suggest_cancel(struct GNUNET_ATS_ApplicationSuggestHandle *sh); /** @} */ /* end of group */ diff --git a/src/include/gnunet_ats_plugin.h b/src/include/gnunet_ats_plugin.h index da00f277c..e2f052678 100644 --- a/src/include/gnunet_ats_plugin.h +++ b/src/include/gnunet_ats_plugin.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet - Copyright (C) 2009-2015 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2009-2015 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -163,9 +163,7 @@ typedef void * Each solver is required to set up and return an instance * of this struct during initialization. */ -struct GNUNET_ATS_SolverFunctions -{ - +struct GNUNET_ATS_SolverFunctions { /** * Closure to pass to all solver functions in this struct. */ @@ -248,8 +246,7 @@ struct GNUNET_ATS_SolverFunctions * #GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP * */ -enum GAS_Solver_Operation -{ +enum GAS_Solver_Operation { /** * A solution iteration has been started */ @@ -311,8 +308,7 @@ enum GAS_Solver_Operation /** * Status of a GAS_Solver_Operation operation */ -enum GAS_Solver_Status -{ +enum GAS_Solver_Status { /** * Success */ @@ -328,8 +324,7 @@ enum GAS_Solver_Status /** * Status of the operation */ -enum GAS_Solver_Additional_Information -{ +enum GAS_Solver_Additional_Information { /** * No more specific information */ @@ -416,8 +411,7 @@ typedef unsigned int * of this type as to the initialization function * of the ATS plugins. */ -struct GNUNET_ATS_PluginEnvironment -{ +struct GNUNET_ATS_PluginEnvironment { /** * Configuration handle to be used by the solver */ diff --git a/src/include/gnunet_ats_plugin_new.h b/src/include/gnunet_ats_plugin_new.h index 633343272..f9005ee73 100644 --- a/src/include/gnunet_ats_plugin_new.h +++ b/src/include/gnunet_ats_plugin_new.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet - Copyright (C) 2009-2015, 2018 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2009-2015, 2018 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -47,7 +47,6 @@ * Preference being expressed by an application client. */ struct GNUNET_ATS_Preference { - /** * Peer to get address suggestions for. */ @@ -74,7 +73,6 @@ struct GNUNET_ATS_Session; * Plugin-relevant information about a session. */ struct GNUNET_ATS_SessionData { - /** * Peer the session is with. */ @@ -89,12 +87,11 @@ struct GNUNET_ATS_SessionData { * Handle to the session that has the given properties. */ struct GNUNET_ATS_Session *session; - + /** * Is the session inbound only? */ int inbound_only; - }; /** @@ -116,9 +113,7 @@ struct GNUNET_ATS_SessionHandle; * Each solver is required to set up and return an instance * of this struct during initialization. */ -struct GNUNET_ATS_SolverFunctions -{ - +struct GNUNET_ATS_SolverFunctions { /** * Closure to pass to all solver functions in this struct. */ @@ -133,20 +128,20 @@ struct GNUNET_ATS_SolverFunctions */ struct GNUNET_ATS_PreferenceHandle * (*preference_add)(void *cls, - const struct GNUNET_ATS_Preference *pref); + const struct GNUNET_ATS_Preference *pref); /** * The plugin should end respecting a preference. * * @param cls the closure - * @param ph whatever @e preference_add returned + * @param ph whatever @e preference_add returned * @param pref the preference to delete * @return plugin's internal representation, or NULL */ void - (*preference_del)(void *cls, - struct GNUNET_ATS_PreferenceHandle *ph, - const struct GNUNET_ATS_Preference *pref); + (*preference_del)(void *cls, + struct GNUNET_ATS_PreferenceHandle *ph, + const struct GNUNET_ATS_Preference *pref); /** * Transport established a new session with performance @@ -159,8 +154,8 @@ struct GNUNET_ATS_SolverFunctions */ struct GNUNET_ATS_SessionHandle * (*session_add)(void *cls, - const struct GNUNET_ATS_SessionData *data, - const char *address); + const struct GNUNET_ATS_SessionData *data, + const char *address); /** * @a data changed for a given @a sh, solver should consider @@ -172,8 +167,8 @@ struct GNUNET_ATS_SolverFunctions */ void (*session_update)(void *cls, - struct GNUNET_ATS_SessionHandle *sh, - const struct GNUNET_ATS_SessionData *data); + struct GNUNET_ATS_SessionHandle *sh, + const struct GNUNET_ATS_SessionData *data); /** * A session went away. Solver should update accordingly. @@ -184,9 +179,8 @@ struct GNUNET_ATS_SolverFunctions */ void (*session_del)(void *cls, - struct GNUNET_ATS_SessionHandle *sh, - const struct GNUNET_ATS_SessionData *data); - + struct GNUNET_ATS_SessionHandle *sh, + const struct GNUNET_ATS_SessionData *data); }; @@ -195,8 +189,7 @@ struct GNUNET_ATS_SolverFunctions * of this type as to the initialization function * of the ATS plugins. */ -struct GNUNET_ATS_PluginEnvironment -{ +struct GNUNET_ATS_PluginEnvironment { /** * Configuration handle to be used by the solver */ @@ -222,11 +215,11 @@ struct GNUNET_ATS_PluginEnvironment */ void (*suggest_cb) (void *cls, - const struct GNUNET_PeerIdentity *pid, - const char *address); + const struct GNUNET_PeerIdentity *pid, + const char *address); /** - * Tell the transport that it should allocate the given + * Tell the transport that it should allocate the given * bandwidth to the specified session. * * @param cls closure, NULL @@ -237,15 +230,14 @@ struct GNUNET_ATS_PluginEnvironment */ void (*allocate_cb) (void *cls, - struct GNUNET_ATS_Session *session, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_BANDWIDTH_Value32NBO bw_in, - struct GNUNET_BANDWIDTH_Value32NBO bw_out); - + struct GNUNET_ATS_Session *session, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_BANDWIDTH_Value32NBO bw_in, + struct GNUNET_BANDWIDTH_Value32NBO bw_out); }; - + #endif /** @} */ /* end of group */ diff --git a/src/include/gnunet_ats_service.h b/src/include/gnunet_ats_service.h index 7ea624f5e..a226c7b55 100644 --- a/src/include/gnunet_ats_service.h +++ b/src/include/gnunet_ats_service.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2015 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2015 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -68,9 +68,7 @@ /** * ATS performance characteristics for an address. */ -struct GNUNET_ATS_Properties -{ - +struct GNUNET_ATS_Properties { /** * Delay. Time between when the time packet is sent and the packet * arrives. FOREVER if we did not measure yet. @@ -104,7 +102,6 @@ struct GNUNET_ATS_Properties * This property does not change. */ enum GNUNET_NetworkType scope; - }; @@ -112,9 +109,7 @@ struct GNUNET_ATS_Properties * ATS performance characteristics for an address in * network byte order (for IPC). */ -struct GNUNET_ATS_PropertiesNBO -{ - +struct GNUNET_ATS_PropertiesNBO { /** * Actual traffic on this connection from this peer to the other peer. * Includes transport overhead. @@ -148,7 +143,6 @@ struct GNUNET_ATS_PropertiesNBO * arrives. FOREVER if we did not measure yet. */ struct GNUNET_TIME_RelativeNBO delay; - }; @@ -164,8 +158,8 @@ struct GNUNET_ATS_PropertiesNBO * @param hbo value read */ void -GNUNET_ATS_properties_hton (struct GNUNET_ATS_PropertiesNBO *nbo, - const struct GNUNET_ATS_Properties *hbo); +GNUNET_ATS_properties_hton(struct GNUNET_ATS_PropertiesNBO *nbo, + const struct GNUNET_ATS_Properties *hbo); /** @@ -175,8 +169,8 @@ GNUNET_ATS_properties_hton (struct GNUNET_ATS_PropertiesNBO *nbo, * @param nbo value read */ void -GNUNET_ATS_properties_ntoh (struct GNUNET_ATS_Properties *hbo, - const struct GNUNET_ATS_PropertiesNBO *nbo); +GNUNET_ATS_properties_ntoh(struct GNUNET_ATS_Properties *hbo, + const struct GNUNET_ATS_PropertiesNBO *nbo); @@ -201,7 +195,7 @@ struct GNUNET_ATS_ConnectivitySuggestHandle; * @return ats connectivity handle, NULL on error */ struct GNUNET_ATS_ConnectivityHandle * -GNUNET_ATS_connectivity_init (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_ATS_connectivity_init(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -210,7 +204,7 @@ GNUNET_ATS_connectivity_init (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param ch handle to destroy */ void -GNUNET_ATS_connectivity_done (struct GNUNET_ATS_ConnectivityHandle *ch); +GNUNET_ATS_connectivity_done(struct GNUNET_ATS_ConnectivityHandle *ch); /** @@ -223,9 +217,9 @@ GNUNET_ATS_connectivity_done (struct GNUNET_ATS_ConnectivityHandle *ch); * @return suggestion handle, NULL if request is already pending */ struct GNUNET_ATS_ConnectivitySuggestHandle * -GNUNET_ATS_connectivity_suggest (struct GNUNET_ATS_ConnectivityHandle *ch, - const struct GNUNET_PeerIdentity *peer, - uint32_t strength); +GNUNET_ATS_connectivity_suggest(struct GNUNET_ATS_ConnectivityHandle *ch, + const struct GNUNET_PeerIdentity *peer, + uint32_t strength); /** @@ -234,7 +228,7 @@ GNUNET_ATS_connectivity_suggest (struct GNUNET_ATS_ConnectivityHandle *ch, * @param sh handle */ void -GNUNET_ATS_connectivity_suggest_cancel (struct GNUNET_ATS_ConnectivitySuggestHandle *sh); +GNUNET_ATS_connectivity_suggest_cancel(struct GNUNET_ATS_ConnectivitySuggestHandle *sh); /* ******************************** Scheduling API ***************************** */ @@ -284,9 +278,9 @@ typedef void * @return ats context */ struct GNUNET_ATS_SchedulingHandle * -GNUNET_ATS_scheduling_init (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_ATS_AddressSuggestionCallback suggest_cb, - void *suggest_cb_cls); +GNUNET_ATS_scheduling_init(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_ATS_AddressSuggestionCallback suggest_cb, + void *suggest_cb_cls); /** @@ -295,7 +289,7 @@ GNUNET_ATS_scheduling_init (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param sh handle to release */ void -GNUNET_ATS_scheduling_done (struct GNUNET_ATS_SchedulingHandle *sh); +GNUNET_ATS_scheduling_done(struct GNUNET_ATS_SchedulingHandle *sh); /** @@ -317,10 +311,10 @@ struct GNUNET_ATS_AddressRecord; * address is invalid) */ struct GNUNET_ATS_AddressRecord * -GNUNET_ATS_address_add (struct GNUNET_ATS_SchedulingHandle *sh, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_ATS_Session *session, - const struct GNUNET_ATS_Properties *prop); +GNUNET_ATS_address_add(struct GNUNET_ATS_SchedulingHandle *sh, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_ATS_Session *session, + const struct GNUNET_ATS_Properties *prop); /** @@ -330,8 +324,8 @@ GNUNET_ATS_address_add (struct GNUNET_ATS_SchedulingHandle *sh, * @param session session handle */ void -GNUNET_ATS_address_add_session (struct GNUNET_ATS_AddressRecord *ar, - struct GNUNET_ATS_Session *session); +GNUNET_ATS_address_add_session(struct GNUNET_ATS_AddressRecord *ar, + struct GNUNET_ATS_Session *session); /** @@ -347,8 +341,8 @@ GNUNET_ATS_address_add_session (struct GNUNET_ATS_AddressRecord *ar, * use it still to establish a new session */ int -GNUNET_ATS_address_del_session (struct GNUNET_ATS_AddressRecord *ar, - struct GNUNET_ATS_Session *session); +GNUNET_ATS_address_del_session(struct GNUNET_ATS_AddressRecord *ar, + struct GNUNET_ATS_Session *session); /** @@ -365,8 +359,8 @@ GNUNET_ATS_address_del_session (struct GNUNET_ATS_AddressRecord *ar, * @param prop performance data for the address */ void -GNUNET_ATS_address_update (struct GNUNET_ATS_AddressRecord *ar, - const struct GNUNET_ATS_Properties *prop); +GNUNET_ATS_address_update(struct GNUNET_ATS_AddressRecord *ar, + const struct GNUNET_ATS_Properties *prop); /** @@ -376,7 +370,7 @@ GNUNET_ATS_address_update (struct GNUNET_ATS_AddressRecord *ar, * expired and ATS may no longer use it */ void -GNUNET_ATS_address_destroy (struct GNUNET_ATS_AddressRecord *ar); +GNUNET_ATS_address_destroy(struct GNUNET_ATS_AddressRecord *ar); @@ -422,14 +416,14 @@ struct GNUNET_ATS_AddressListHandle; * * @param cfg configuration to use * @param addr_info_cb callback called when performance characteristics for - * an address change + * an address change * @param addr_info_cb_cls closure for @a addr_info_cb * @return ats performance context */ struct GNUNET_ATS_PerformanceHandle * -GNUNET_ATS_performance_init (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_ATS_AddressInformationCallback addr_info_cb, - void *addr_info_cb_cls); +GNUNET_ATS_performance_init(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_ATS_AddressInformationCallback addr_info_cb, + void *addr_info_cb_cls); /** @@ -445,11 +439,11 @@ GNUNET_ATS_performance_init (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return handle to abort the operation */ struct GNUNET_ATS_AddressListHandle * -GNUNET_ATS_performance_list_addresses (struct GNUNET_ATS_PerformanceHandle *ph, - const struct GNUNET_PeerIdentity *peer, - int all, - GNUNET_ATS_AddressInformationCallback infocb, - void *infocb_cls); +GNUNET_ATS_performance_list_addresses(struct GNUNET_ATS_PerformanceHandle *ph, + const struct GNUNET_PeerIdentity *peer, + int all, + GNUNET_ATS_AddressInformationCallback infocb, + void *infocb_cls); /** @@ -458,7 +452,7 @@ GNUNET_ATS_performance_list_addresses (struct GNUNET_ATS_PerformanceHandle *ph, * @param alh the `struct GNUNET_ATS_AddressListHandle` handle to cancel */ void -GNUNET_ATS_performance_list_addresses_cancel (struct GNUNET_ATS_AddressListHandle *alh); +GNUNET_ATS_performance_list_addresses_cancel(struct GNUNET_ATS_AddressListHandle *alh); /** @@ -467,7 +461,7 @@ GNUNET_ATS_performance_list_addresses_cancel (struct GNUNET_ATS_AddressListHandl * @param ph handle */ void -GNUNET_ATS_performance_done (struct GNUNET_ATS_PerformanceHandle *ph); +GNUNET_ATS_performance_done(struct GNUNET_ATS_PerformanceHandle *ph); /** @@ -508,11 +502,11 @@ struct GNUNET_ATS_ReservationContext; * @deprecated will be replaced soon */ struct GNUNET_ATS_ReservationContext * -GNUNET_ATS_reserve_bandwidth (struct GNUNET_ATS_PerformanceHandle *ph, - const struct GNUNET_PeerIdentity *peer, - int32_t amount, - GNUNET_ATS_ReservationCallback rcb, - void *rcb_cls); +GNUNET_ATS_reserve_bandwidth(struct GNUNET_ATS_PerformanceHandle *ph, + const struct GNUNET_PeerIdentity *peer, + int32_t amount, + GNUNET_ATS_ReservationCallback rcb, + void *rcb_cls); /** @@ -521,25 +515,23 @@ GNUNET_ATS_reserve_bandwidth (struct GNUNET_ATS_PerformanceHandle *ph, * @param rc context returned by the original GNUNET_ATS_reserve_bandwidth call */ void -GNUNET_ATS_reserve_bandwidth_cancel (struct GNUNET_ATS_ReservationContext *rc); +GNUNET_ATS_reserve_bandwidth_cancel(struct GNUNET_ATS_ReservationContext *rc); /** * ATS preference types as array initializer */ -#define GNUNET_ATS_PreferenceType {GNUNET_ATS_PREFERENCE_BANDWIDTH, GNUNET_ATS_PREFERENCE_LATENCY, GNUNET_ATS_PREFERENCE_END} +#define GNUNET_ATS_PreferenceType { GNUNET_ATS_PREFERENCE_BANDWIDTH, GNUNET_ATS_PREFERENCE_LATENCY, GNUNET_ATS_PREFERENCE_END } /** * ATS preference types as string array initializer */ -#define GNUNET_ATS_PreferenceTypeString {"BANDWIDTH", "LATENCY", "END" } +#define GNUNET_ATS_PreferenceTypeString { "BANDWIDTH", "LATENCY", "END" } /** * Enum defining all known preference categories. */ -enum GNUNET_ATS_PreferenceKind -{ - +enum GNUNET_ATS_PreferenceKind { /** * Change the peer's bandwidth value (value per byte of bandwidth in * the goal function) to the given amount. The argument is followed @@ -561,7 +553,6 @@ enum GNUNET_ATS_PreferenceKind * End of preference list. */ GNUNET_ATS_PREFERENCE_END = 2 - }; @@ -572,7 +563,7 @@ enum GNUNET_ATS_PreferenceKind * @return a string or NULL if invalid */ const char * -GNUNET_ATS_print_preference_type (enum GNUNET_ATS_PreferenceKind type); +GNUNET_ATS_print_preference_type(enum GNUNET_ATS_PreferenceKind type); /** @@ -584,9 +575,9 @@ GNUNET_ATS_print_preference_type (enum GNUNET_ATS_PreferenceKind type); * desired changes */ void -GNUNET_ATS_performance_change_preference (struct GNUNET_ATS_PerformanceHandle *ph, - const struct GNUNET_PeerIdentity *peer, - ...); +GNUNET_ATS_performance_change_preference(struct GNUNET_ATS_PerformanceHandle *ph, + const struct GNUNET_PeerIdentity *peer, + ...); /** @@ -607,10 +598,10 @@ GNUNET_ATS_performance_change_preference (struct GNUNET_ATS_PerformanceHandle *p * @param ... #GNUNET_ATS_PREFERENCE_END-terminated specification of the desired changes */ void -GNUNET_ATS_performance_give_feedback (struct GNUNET_ATS_PerformanceHandle *ph, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_TIME_Relative scope, - ...); +GNUNET_ATS_performance_give_feedback(struct GNUNET_ATS_PerformanceHandle *ph, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_TIME_Relative scope, + ...); #endif diff --git a/src/include/gnunet_ats_transport_service.h b/src/include/gnunet_ats_transport_service.h index 287f0600d..67138ae92 100644 --- a/src/include/gnunet_ats_transport_service.h +++ b/src/include/gnunet_ats_transport_service.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2015, 2018 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2015, 2018 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -43,9 +43,7 @@ /** * ATS performance characteristics for a session. */ -struct GNUNET_ATS_Properties -{ - +struct GNUNET_ATS_Properties { /** * Delay. Time between when the time packet is sent and the packet * arrives. FOREVER if we did not (successfully) measure yet. @@ -106,7 +104,6 @@ struct GNUNET_ATS_Properties * What characteristics does this communicator have? */ enum GNUNET_TRANSPORT_CommunicatorCharacteristics cc; - }; @@ -166,11 +163,11 @@ typedef void * @return ats context */ struct GNUNET_ATS_TransportHandle * -GNUNET_ATS_transport_init (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_ATS_AllocationCallback alloc_cb, - void *alloc_cb_cls, - GNUNET_ATS_SuggestionCallback suggest_cb, - void *suggest_cb_cls); +GNUNET_ATS_transport_init(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_ATS_AllocationCallback alloc_cb, + void *alloc_cb_cls, + GNUNET_ATS_SuggestionCallback suggest_cb, + void *suggest_cb_cls); /** @@ -179,7 +176,7 @@ GNUNET_ATS_transport_init (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param ath handle to release */ void -GNUNET_ATS_transport_done (struct GNUNET_ATS_TransportHandle *ath); +GNUNET_ATS_transport_done(struct GNUNET_ATS_TransportHandle *ath); /** @@ -203,11 +200,11 @@ struct GNUNET_ATS_SessionRecord; * session is invalid) */ struct GNUNET_ATS_SessionRecord * -GNUNET_ATS_session_add (struct GNUNET_ATS_TransportHandle *ath, - const struct GNUNET_PeerIdentity *pid, - const char *address, - struct GNUNET_ATS_Session *session, - const struct GNUNET_ATS_Properties *prop); +GNUNET_ATS_session_add(struct GNUNET_ATS_TransportHandle *ath, + const struct GNUNET_PeerIdentity *pid, + const char *address, + struct GNUNET_ATS_Session *session, + const struct GNUNET_ATS_Properties *prop); /** @@ -218,8 +215,8 @@ GNUNET_ATS_session_add (struct GNUNET_ATS_TransportHandle *ath, * @param prop performance data for the session */ void -GNUNET_ATS_session_update (struct GNUNET_ATS_SessionRecord *ar, - const struct GNUNET_ATS_Properties *prop); +GNUNET_ATS_session_update(struct GNUNET_ATS_SessionRecord *ar, + const struct GNUNET_ATS_Properties *prop); /** @@ -230,7 +227,7 @@ GNUNET_ATS_session_update (struct GNUNET_ATS_SessionRecord *ar, * @param ar session record to drop */ void -GNUNET_ATS_session_del (struct GNUNET_ATS_SessionRecord *ar); +GNUNET_ATS_session_del(struct GNUNET_ATS_SessionRecord *ar); #endif diff --git a/src/include/gnunet_bandwidth_lib.h b/src/include/gnunet_bandwidth_lib.h index f941624af..945c0321a 100644 --- a/src/include/gnunet_bandwidth_lib.h +++ b/src/include/gnunet_bandwidth_lib.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -47,8 +47,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * 32-bit bandwidth used for network exchange by GNUnet, in bytes per second. */ -struct GNUNET_BANDWIDTH_Value32NBO -{ +struct GNUNET_BANDWIDTH_Value32NBO { /** * The actual value (bytes per second). */ @@ -83,8 +82,7 @@ typedef void (*GNUNET_BANDWIDTH_ExcessNotificationCallback) (void *cls); * structures (reducing malloc-ing); however, values should not be * accessed directly by clients (hence the '__'). */ -struct GNUNET_BANDWIDTH_Tracker -{ +struct GNUNET_BANDWIDTH_Tracker { /** * Closure for @e update_cb. */ @@ -140,7 +138,7 @@ struct GNUNET_BANDWIDTH_Tracker /** * Convenience definition to use for 0-bandwidth. */ -#define GNUNET_BANDWIDTH_ZERO GNUNET_BANDWIDTH_value_init (0) +#define GNUNET_BANDWIDTH_ZERO GNUNET_BANDWIDTH_value_init(0) /** @@ -150,13 +148,13 @@ struct GNUNET_BANDWIDTH_Tracker * @return the new bandwidth value */ struct GNUNET_BANDWIDTH_Value32NBO -GNUNET_BANDWIDTH_value_init (uint32_t bytes_per_second); +GNUNET_BANDWIDTH_value_init(uint32_t bytes_per_second); /** * Maximum possible bandwidth value. */ -#define GNUNET_BANDWIDTH_VALUE_MAX GNUNET_BANDWIDTH_value_init (UINT32_MAX) +#define GNUNET_BANDWIDTH_VALUE_MAX GNUNET_BANDWIDTH_value_init(UINT32_MAX) /** @@ -168,7 +166,7 @@ GNUNET_BANDWIDTH_value_init (uint32_t bytes_per_second); * @return number of bytes available at bps until deadline */ uint64_t -GNUNET_BANDWIDTH_value_get_available_until ( +GNUNET_BANDWIDTH_value_get_available_until( struct GNUNET_BANDWIDTH_Value32NBO bps, struct GNUNET_TIME_Relative deadline); @@ -182,8 +180,8 @@ GNUNET_BANDWIDTH_value_get_available_until ( * @return how long it would take */ struct GNUNET_TIME_Relative -GNUNET_BANDWIDTH_value_get_delay_for (struct GNUNET_BANDWIDTH_Value32NBO bps, - uint64_t size); +GNUNET_BANDWIDTH_value_get_delay_for(struct GNUNET_BANDWIDTH_Value32NBO bps, + uint64_t size); /** @@ -194,8 +192,8 @@ GNUNET_BANDWIDTH_value_get_delay_for (struct GNUNET_BANDWIDTH_Value32NBO bps, * @return the min of b1 and b2 */ struct GNUNET_BANDWIDTH_Value32NBO -GNUNET_BANDWIDTH_value_min (struct GNUNET_BANDWIDTH_Value32NBO b1, - struct GNUNET_BANDWIDTH_Value32NBO b2); +GNUNET_BANDWIDTH_value_min(struct GNUNET_BANDWIDTH_Value32NBO b1, + struct GNUNET_BANDWIDTH_Value32NBO b2); /** @@ -206,8 +204,8 @@ GNUNET_BANDWIDTH_value_min (struct GNUNET_BANDWIDTH_Value32NBO b1, * @return the min of b1 and b2 */ struct GNUNET_BANDWIDTH_Value32NBO -GNUNET_BANDWIDTH_value_max (struct GNUNET_BANDWIDTH_Value32NBO b1, - struct GNUNET_BANDWIDTH_Value32NBO b2); +GNUNET_BANDWIDTH_value_max(struct GNUNET_BANDWIDTH_Value32NBO b1, + struct GNUNET_BANDWIDTH_Value32NBO b2); /** @@ -218,8 +216,8 @@ GNUNET_BANDWIDTH_value_max (struct GNUNET_BANDWIDTH_Value32NBO b1, * @return the sum of b1 and b2 */ struct GNUNET_BANDWIDTH_Value32NBO -GNUNET_BANDWIDTH_value_sum (struct GNUNET_BANDWIDTH_Value32NBO b1, - struct GNUNET_BANDWIDTH_Value32NBO b2); +GNUNET_BANDWIDTH_value_sum(struct GNUNET_BANDWIDTH_Value32NBO b1, + struct GNUNET_BANDWIDTH_Value32NBO b2); /** @@ -239,7 +237,7 @@ GNUNET_BANDWIDTH_value_sum (struct GNUNET_BANDWIDTH_Value32NBO b1, * may accumulate before it expires */ void -GNUNET_BANDWIDTH_tracker_init ( +GNUNET_BANDWIDTH_tracker_init( struct GNUNET_BANDWIDTH_Tracker *av, GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb, void *update_cb_cls, @@ -266,7 +264,7 @@ GNUNET_BANDWIDTH_tracker_init ( * @param excess_cb_cls closure for @a excess_cb */ void -GNUNET_BANDWIDTH_tracker_init2 ( +GNUNET_BANDWIDTH_tracker_init2( struct GNUNET_BANDWIDTH_Tracker *av, GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb, void *update_cb_cls, @@ -282,7 +280,7 @@ GNUNET_BANDWIDTH_tracker_init2 ( * @param av the respective trackers */ void -GNUNET_BANDWIDTH_tracker_notification_stop ( +GNUNET_BANDWIDTH_tracker_notification_stop( struct GNUNET_BANDWIDTH_Tracker *av); @@ -298,8 +296,8 @@ GNUNET_BANDWIDTH_tracker_notification_stop ( * @return #GNUNET_YES if this consumption is above the limit */ int -GNUNET_BANDWIDTH_tracker_consume (struct GNUNET_BANDWIDTH_Tracker *av, - ssize_t size); +GNUNET_BANDWIDTH_tracker_consume(struct GNUNET_BANDWIDTH_Tracker *av, + ssize_t size); /** @@ -312,8 +310,8 @@ GNUNET_BANDWIDTH_tracker_consume (struct GNUNET_BANDWIDTH_Tracker *av, * @return time to wait for consumption to be OK */ struct GNUNET_TIME_Relative -GNUNET_BANDWIDTH_tracker_get_delay (struct GNUNET_BANDWIDTH_Tracker *av, - size_t size); +GNUNET_BANDWIDTH_tracker_get_delay(struct GNUNET_BANDWIDTH_Tracker *av, + size_t size); /** @@ -324,7 +322,7 @@ GNUNET_BANDWIDTH_tracker_get_delay (struct GNUNET_BANDWIDTH_Tracker *av, * @return number of bytes available for consumption right now */ int64_t -GNUNET_BANDWIDTH_tracker_get_available (struct GNUNET_BANDWIDTH_Tracker *av); +GNUNET_BANDWIDTH_tracker_get_available(struct GNUNET_BANDWIDTH_Tracker *av); /** @@ -334,7 +332,7 @@ GNUNET_BANDWIDTH_tracker_get_available (struct GNUNET_BANDWIDTH_Tracker *av); * @param bytes_per_second_limit new limit to assume */ void -GNUNET_BANDWIDTH_tracker_update_quota ( +GNUNET_BANDWIDTH_tracker_update_quota( struct GNUNET_BANDWIDTH_Tracker *av, struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit); diff --git a/src/include/gnunet_bio_lib.h b/src/include/gnunet_bio_lib.h index e90e85832..a1fd0e6ac 100644 --- a/src/include/gnunet_bio_lib.h +++ b/src/include/gnunet_bio_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -55,7 +55,7 @@ struct GNUNET_BIO_ReadHandle; * @return IO handle on success, NULL on error */ struct GNUNET_BIO_ReadHandle * -GNUNET_BIO_read_open (const char *fn); +GNUNET_BIO_read_open(const char *fn); /** @@ -67,7 +67,7 @@ GNUNET_BIO_read_open (const char *fn); * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_BIO_read_close (struct GNUNET_BIO_ReadHandle *h, char **emsg); +GNUNET_BIO_read_close(struct GNUNET_BIO_ReadHandle *h, char **emsg); /** @@ -80,8 +80,8 @@ GNUNET_BIO_read_close (struct GNUNET_BIO_ReadHandle *h, char **emsg); * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure */ int -GNUNET_BIO_read (struct GNUNET_BIO_ReadHandle *h, const char *what, - void *result, size_t len); +GNUNET_BIO_read(struct GNUNET_BIO_ReadHandle *h, const char *what, + void *result, size_t len); /** @@ -95,9 +95,9 @@ GNUNET_BIO_read (struct GNUNET_BIO_ReadHandle *h, const char *what, * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure */ int -GNUNET_BIO_read_fn (struct GNUNET_BIO_ReadHandle *h, - const char *file, int line, - void *result, size_t len); +GNUNET_BIO_read_fn(struct GNUNET_BIO_ReadHandle *h, + const char *file, int line, + void *result, size_t len); /** * Read 0-terminated string from a file. @@ -110,8 +110,8 @@ GNUNET_BIO_read_fn (struct GNUNET_BIO_ReadHandle *h, * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure */ int -GNUNET_BIO_read_string (struct GNUNET_BIO_ReadHandle *h, const char *what, - char **result, size_t max_length); +GNUNET_BIO_read_string(struct GNUNET_BIO_ReadHandle *h, const char *what, + char **result, size_t max_length); /** @@ -123,8 +123,8 @@ GNUNET_BIO_read_string (struct GNUNET_BIO_ReadHandle *h, const char *what, * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure */ int -GNUNET_BIO_read_meta_data (struct GNUNET_BIO_ReadHandle *h, const char *what, - struct GNUNET_CONTAINER_MetaData **result); +GNUNET_BIO_read_meta_data(struct GNUNET_BIO_ReadHandle *h, const char *what, + struct GNUNET_CONTAINER_MetaData **result); /** @@ -133,7 +133,7 @@ GNUNET_BIO_read_meta_data (struct GNUNET_BIO_ReadHandle *h, const char *what, * @param h hande to open file * @param f address of float to read */ -#define GNUNET_BIO_read_float(h, f) (GNUNET_BIO_read_fn (h, __FILE__, __LINE__, f, sizeof(float))) +#define GNUNET_BIO_read_float(h, f) (GNUNET_BIO_read_fn(h, __FILE__, __LINE__, f, sizeof(float))) @@ -143,7 +143,7 @@ GNUNET_BIO_read_meta_data (struct GNUNET_BIO_ReadHandle *h, const char *what, * @param h hande to open file * @param f address of double to read */ -#define GNUNET_BIO_read_double(h, f) (GNUNET_BIO_read_fn (h, __FILE__, __LINE__, f, sizeof(double))) +#define GNUNET_BIO_read_double(h, f) (GNUNET_BIO_read_fn(h, __FILE__, __LINE__, f, sizeof(double))) /** @@ -156,8 +156,8 @@ GNUNET_BIO_read_meta_data (struct GNUNET_BIO_ReadHandle *h, const char *what, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_BIO_read_int32__ (struct GNUNET_BIO_ReadHandle *h, const char *file, - int line, int32_t * i); +GNUNET_BIO_read_int32__(struct GNUNET_BIO_ReadHandle *h, const char *file, + int line, int32_t * i); /** @@ -166,7 +166,7 @@ GNUNET_BIO_read_int32__ (struct GNUNET_BIO_ReadHandle *h, const char *file, * @param h hande to open file * @param i address of 32-bit integer to read */ -#define GNUNET_BIO_read_int32(h, i) GNUNET_BIO_read_int32__ (h, __FILE__, __LINE__, (int32_t*) i) +#define GNUNET_BIO_read_int32(h, i) GNUNET_BIO_read_int32__(h, __FILE__, __LINE__, (int32_t*)i) /** @@ -179,8 +179,8 @@ GNUNET_BIO_read_int32__ (struct GNUNET_BIO_ReadHandle *h, const char *file, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_BIO_read_int64__ (struct GNUNET_BIO_ReadHandle *h, const char *file, - int line, int64_t * i); +GNUNET_BIO_read_int64__(struct GNUNET_BIO_ReadHandle *h, const char *file, + int line, int64_t * i); /** @@ -189,7 +189,7 @@ GNUNET_BIO_read_int64__ (struct GNUNET_BIO_ReadHandle *h, const char *file, * @param h hande to open file * @param i address of 64-bit integer to read */ -#define GNUNET_BIO_read_int64(h, i) GNUNET_BIO_read_int64__ (h, __FILE__, __LINE__, (int64_t*) i) +#define GNUNET_BIO_read_int64(h, i) GNUNET_BIO_read_int64__(h, __FILE__, __LINE__, (int64_t*)i) /** @@ -204,7 +204,7 @@ struct GNUNET_BIO_WriteHandle; * @return IO handle on success, NULL on error */ struct GNUNET_BIO_WriteHandle * -GNUNET_BIO_write_open (const char *fn); +GNUNET_BIO_write_open(const char *fn); /** @@ -214,7 +214,7 @@ GNUNET_BIO_write_open (const char *fn); * @return GNUNET_OK on success, GNUNET_SYSERR otherwise */ int -GNUNET_BIO_write_close (struct GNUNET_BIO_WriteHandle *h); +GNUNET_BIO_write_close(struct GNUNET_BIO_WriteHandle *h); /** @@ -226,8 +226,8 @@ GNUNET_BIO_write_close (struct GNUNET_BIO_WriteHandle *h); * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_BIO_write (struct GNUNET_BIO_WriteHandle *h, const void *buffer, - size_t n); +GNUNET_BIO_write(struct GNUNET_BIO_WriteHandle *h, const void *buffer, + size_t n); /** @@ -238,7 +238,7 @@ GNUNET_BIO_write (struct GNUNET_BIO_WriteHandle *h, const void *buffer, * the file is closed */ int -GNUNET_BIO_flush (struct GNUNET_BIO_WriteHandle *h); +GNUNET_BIO_flush(struct GNUNET_BIO_WriteHandle *h); /** @@ -249,7 +249,7 @@ GNUNET_BIO_flush (struct GNUNET_BIO_WriteHandle *h); * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_BIO_write_string (struct GNUNET_BIO_WriteHandle *h, const char *s); +GNUNET_BIO_write_string(struct GNUNET_BIO_WriteHandle *h, const char *s); /** @@ -260,8 +260,8 @@ GNUNET_BIO_write_string (struct GNUNET_BIO_WriteHandle *h, const char *s); * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_BIO_write_meta_data (struct GNUNET_BIO_WriteHandle *h, - const struct GNUNET_CONTAINER_MetaData *m); +GNUNET_BIO_write_meta_data(struct GNUNET_BIO_WriteHandle *h, + const struct GNUNET_CONTAINER_MetaData *m); @@ -271,7 +271,7 @@ GNUNET_BIO_write_meta_data (struct GNUNET_BIO_WriteHandle *h, * @param h hande to open file * @param f float to write (must be a variable) */ -#define GNUNET_BIO_write_float(h, f) GNUNET_BIO_write (h, &f, sizeof(float)) +#define GNUNET_BIO_write_float(h, f) GNUNET_BIO_write(h, &f, sizeof(float)) @@ -281,7 +281,7 @@ GNUNET_BIO_write_meta_data (struct GNUNET_BIO_WriteHandle *h, * @param h hande to open file * @param f double to write (must be a variable) */ -#define GNUNET_BIO_write_double(h, f) GNUNET_BIO_write (h, &f, sizeof(double)) +#define GNUNET_BIO_write_double(h, f) GNUNET_BIO_write(h, &f, sizeof(double)) /** @@ -292,7 +292,7 @@ GNUNET_BIO_write_meta_data (struct GNUNET_BIO_WriteHandle *h, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_BIO_write_int32 (struct GNUNET_BIO_WriteHandle *h, int32_t i); +GNUNET_BIO_write_int32(struct GNUNET_BIO_WriteHandle *h, int32_t i); /** @@ -303,7 +303,7 @@ GNUNET_BIO_write_int32 (struct GNUNET_BIO_WriteHandle *h, int32_t i); * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_BIO_write_int64 (struct GNUNET_BIO_WriteHandle *h, int64_t i); +GNUNET_BIO_write_int64(struct GNUNET_BIO_WriteHandle *h, int64_t i); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_block_group_lib.h b/src/include/gnunet_block_group_lib.h index 777ef7dd6..91d193015 100644 --- a/src/include/gnunet_block_group_lib.h +++ b/src/include/gnunet_block_group_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -57,8 +57,8 @@ extern "C" * @return must be a power of two and smaller or equal to 2^15. */ size_t -GNUNET_BLOCK_GROUP_compute_bloomfilter_size (unsigned int entry_count, - unsigned int k); +GNUNET_BLOCK_GROUP_compute_bloomfilter_size(unsigned int entry_count, + unsigned int k); /** @@ -75,13 +75,13 @@ GNUNET_BLOCK_GROUP_compute_bloomfilter_size (unsigned int entry_count, * by this @a type of block (this is not an error) */ struct GNUNET_BLOCK_Group * -GNUNET_BLOCK_GROUP_bf_create (void *cls, - size_t bf_size, - unsigned int bf_k, - enum GNUNET_BLOCK_Type type, - uint32_t nonce, - const void *raw_data, - size_t raw_data_size); +GNUNET_BLOCK_GROUP_bf_create(void *cls, + size_t bf_size, + unsigned int bf_k, + enum GNUNET_BLOCK_Type type, + uint32_t nonce, + const void *raw_data, + size_t raw_data_size); /** @@ -95,8 +95,8 @@ GNUNET_BLOCK_GROUP_bf_create (void *cls, * #GNUNET_NO if @a hc was definitively not in @bg (but now is) */ int -GNUNET_BLOCK_GROUP_bf_test_and_set (struct GNUNET_BLOCK_Group *bg, - const struct GNUNET_HashCode *hc); +GNUNET_BLOCK_GROUP_bf_test_and_set(struct GNUNET_BLOCK_Group *bg, + const struct GNUNET_HashCode *hc); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_block_lib.h b/src/include/gnunet_block_lib.h index c85d3702b..29b64759c 100644 --- a/src/include/gnunet_block_lib.h +++ b/src/include/gnunet_block_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -44,8 +44,7 @@ extern "C" /** * Blocks in the datastore and the datacache must have a unique type. */ -enum GNUNET_BLOCK_Type -{ +enum GNUNET_BLOCK_Type { /** * Any type of block, used as a wildcard when searching. Should * never be attached to a specific block. @@ -143,9 +142,7 @@ enum GNUNET_BLOCK_Type /** * Flags that can be set to control the evaluation. */ -enum GNUNET_BLOCK_EvaluationOptions -{ - +enum GNUNET_BLOCK_EvaluationOptions { /** * Default behavior. */ @@ -162,8 +159,7 @@ enum GNUNET_BLOCK_EvaluationOptions /** * Possible ways for how a block may relate to a query. */ -enum GNUNET_BLOCK_EvaluationResult -{ +enum GNUNET_BLOCK_EvaluationResult { /** * Valid result, and there may be more. */ @@ -222,9 +218,9 @@ struct GNUNET_BLOCK_Context; * @param hc where to store the result. */ void -GNUNET_BLOCK_mingle_hash (const struct GNUNET_HashCode *in, - uint32_t mingle_number, - struct GNUNET_HashCode *hc); +GNUNET_BLOCK_mingle_hash(const struct GNUNET_HashCode *in, + uint32_t mingle_number, + struct GNUNET_HashCode *hc); /** @@ -234,7 +230,7 @@ GNUNET_BLOCK_mingle_hash (const struct GNUNET_HashCode *in, * @return NULL on error */ struct GNUNET_BLOCK_Context * -GNUNET_BLOCK_context_create (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_BLOCK_context_create(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -243,7 +239,7 @@ GNUNET_BLOCK_context_create (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param ctx context to destroy */ void -GNUNET_BLOCK_context_destroy (struct GNUNET_BLOCK_Context *ctx); +GNUNET_BLOCK_context_destroy(struct GNUNET_BLOCK_Context *ctx); /** @@ -267,12 +263,12 @@ struct GNUNET_BLOCK_Group; * by this @a type of block (this is not an error) */ struct GNUNET_BLOCK_Group * -GNUNET_BLOCK_group_create (struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - uint32_t nonce, - const void *raw_data, - size_t raw_data_size, - ...); +GNUNET_BLOCK_group_create(struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + uint32_t nonce, + const void *raw_data, + size_t raw_data_size, + ...); /** @@ -286,10 +282,10 @@ GNUNET_BLOCK_group_create (struct GNUNET_BLOCK_Context *ctx, * supported, #GNUNET_SYSERR on error */ int -GNUNET_BLOCK_group_serialize (struct GNUNET_BLOCK_Group *bg, - uint32_t *nonce, - void **raw_data, - size_t *raw_data_size); +GNUNET_BLOCK_group_serialize(struct GNUNET_BLOCK_Group *bg, + uint32_t *nonce, + void **raw_data, + size_t *raw_data_size); /** @@ -298,7 +294,7 @@ GNUNET_BLOCK_group_serialize (struct GNUNET_BLOCK_Group *bg, * @param bg group to destroy, NULL is allowed */ void -GNUNET_BLOCK_group_destroy (struct GNUNET_BLOCK_Group *bg); +GNUNET_BLOCK_group_destroy(struct GNUNET_BLOCK_Group *bg); /** @@ -320,15 +316,15 @@ GNUNET_BLOCK_group_destroy (struct GNUNET_BLOCK_Group *bg); * @return characterization of result */ enum GNUNET_BLOCK_EvaluationResult -GNUNET_BLOCK_evaluate (struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *group, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode *query, - const void *xquery, - size_t xquery_size, - const void *reply_block, - size_t reply_block_size); +GNUNET_BLOCK_evaluate(struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *group, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode *query, + const void *xquery, + size_t xquery_size, + const void *reply_block, + size_t reply_block_size); /** @@ -345,11 +341,11 @@ GNUNET_BLOCK_evaluate (struct GNUNET_BLOCK_Context *ctx, * (or if extracting a key from a block of this type does not work) */ int -GNUNET_BLOCK_get_key (struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - const void *block, - size_t block_size, - struct GNUNET_HashCode *key); +GNUNET_BLOCK_get_key(struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + const void *block, + size_t block_size, + struct GNUNET_HashCode *key); /** @@ -364,9 +360,9 @@ GNUNET_BLOCK_get_key (struct GNUNET_BLOCK_Context *ctx, * @return #GNUNET_SYSERR if not supported, #GNUNET_OK on success */ int -GNUNET_BLOCK_group_set_seen (struct GNUNET_BLOCK_Group *bg, - const struct GNUNET_HashCode *seen_results, - unsigned int seen_results_count); +GNUNET_BLOCK_group_set_seen(struct GNUNET_BLOCK_Group *bg, + const struct GNUNET_HashCode *seen_results, + unsigned int seen_results_count); /** @@ -382,8 +378,8 @@ GNUNET_BLOCK_group_set_seen (struct GNUNET_BLOCK_Group *bg, * #GNUNET_SYSERR if merging is not supported */ int -GNUNET_BLOCK_group_merge (struct GNUNET_BLOCK_Group *bg1, - struct GNUNET_BLOCK_Group *bg2); +GNUNET_BLOCK_group_merge(struct GNUNET_BLOCK_Group *bg1, + struct GNUNET_BLOCK_Group *bg2); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_block_plugin.h b/src/include/gnunet_block_plugin.h index f0438c82f..025d33c45 100644 --- a/src/include/gnunet_block_plugin.h +++ b/src/include/gnunet_block_plugin.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -97,9 +97,7 @@ typedef void * Block group data. The plugin must initialize the callbacks * and can use the @e internal_cls as it likes. */ -struct GNUNET_BLOCK_Group -{ - +struct GNUNET_BLOCK_Group { /** * Context owning the block group. Set by the main block library. */ @@ -138,7 +136,6 @@ struct GNUNET_BLOCK_Group * Internal data structure of the plugin. */ void *internal_cls; - }; @@ -183,16 +180,16 @@ typedef struct GNUNET_BLOCK_Group * * @return characterization of result */ typedef enum GNUNET_BLOCK_EvaluationResult -(*GNUNET_BLOCK_EvaluationFunction) (void *cls, - struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *group, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode *query, - const void *xquery, - size_t xquery_size, - const void *reply_block, - size_t reply_block_size); +(*GNUNET_BLOCK_EvaluationFunction)(void *cls, + struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *group, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode *query, + const void *xquery, + size_t xquery_size, + const void *reply_block, + size_t reply_block_size); /** @@ -221,9 +218,7 @@ typedef int * Each plugin is required to return a pointer to a struct of this * type as the return value from its entry point. */ -struct GNUNET_BLOCK_PluginFunctions -{ - +struct GNUNET_BLOCK_PluginFunctions { /** * Closure for all of the callbacks. */ diff --git a/src/include/gnunet_cadet_service.h b/src/include/gnunet_cadet_service.h index 819e39353..dccc51464 100644 --- a/src/include/gnunet_cadet_service.h +++ b/src/include/gnunet_cadet_service.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff * @author Bart Polot @@ -70,8 +70,7 @@ struct GNUNET_CADET_Port; /** * Hash uniquely identifying a connection below a tunnel. */ -struct GNUNET_CADET_ConnectionTunnelIdentifier -{ +struct GNUNET_CADET_ConnectionTunnelIdentifier { struct GNUNET_ShortHashCode connection_of_tunnel; }; @@ -79,8 +78,7 @@ struct GNUNET_CADET_ConnectionTunnelIdentifier /** * Number identifying a CADET channel within a tunnel. */ -struct GNUNET_CADET_ChannelTunnelNumber -{ +struct GNUNET_CADET_ChannelTunnelNumber { /** * Which number does this channel have that uniquely identfies * it within its tunnel, in network byte order. @@ -154,7 +152,7 @@ typedef void (*GNUNET_CADET_WindowSizeEventHandler) ( * @return Handle to the cadet service NULL on error. */ struct GNUNET_CADET_Handle * -GNUNET_CADET_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_CADET_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -166,7 +164,7 @@ GNUNET_CADET_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param handle connection to cadet to disconnect */ void -GNUNET_CADET_disconnect (struct GNUNET_CADET_Handle *handle); +GNUNET_CADET_disconnect(struct GNUNET_CADET_Handle *handle); /** @@ -183,13 +181,13 @@ GNUNET_CADET_disconnect (struct GNUNET_CADET_Handle *handle); * @return Port handle, NULL if port is in use */ struct GNUNET_CADET_Port * -GNUNET_CADET_open_port (struct GNUNET_CADET_Handle *h, - const struct GNUNET_HashCode *port, - GNUNET_CADET_ConnectEventHandler connects, - void *connects_cls, - GNUNET_CADET_WindowSizeEventHandler window_changes, - GNUNET_CADET_DisconnectEventHandler disconnects, - const struct GNUNET_MQ_MessageHandler *handlers); +GNUNET_CADET_open_port(struct GNUNET_CADET_Handle *h, + const struct GNUNET_HashCode *port, + GNUNET_CADET_ConnectEventHandler connects, + void *connects_cls, + GNUNET_CADET_WindowSizeEventHandler window_changes, + GNUNET_CADET_DisconnectEventHandler disconnects, + const struct GNUNET_MQ_MessageHandler *handlers); /** @@ -199,7 +197,7 @@ GNUNET_CADET_open_port (struct GNUNET_CADET_Handle *h, * @param p Port handle. */ void -GNUNET_CADET_close_port (struct GNUNET_CADET_Port *p); +GNUNET_CADET_close_port(struct GNUNET_CADET_Port *p); /** @@ -223,13 +221,13 @@ GNUNET_CADET_close_port (struct GNUNET_CADET_Port *p); * @return Handle to the channel. */ struct GNUNET_CADET_Channel * -GNUNET_CADET_channel_create (struct GNUNET_CADET_Handle *h, - void *channel_cls, - const struct GNUNET_PeerIdentity *destination, - const struct GNUNET_HashCode *port, - GNUNET_CADET_WindowSizeEventHandler window_changes, - GNUNET_CADET_DisconnectEventHandler disconnects, - const struct GNUNET_MQ_MessageHandler *handlers); +GNUNET_CADET_channel_create(struct GNUNET_CADET_Handle *h, + void *channel_cls, + const struct GNUNET_PeerIdentity *destination, + const struct GNUNET_HashCode *port, + GNUNET_CADET_WindowSizeEventHandler window_changes, + GNUNET_CADET_DisconnectEventHandler disconnects, + const struct GNUNET_MQ_MessageHandler *handlers); /** @@ -242,7 +240,7 @@ GNUNET_CADET_channel_create (struct GNUNET_CADET_Handle *h, * @param channel Channel handle, becomes invalid after this call. */ void -GNUNET_CADET_channel_destroy (struct GNUNET_CADET_Channel *channel); +GNUNET_CADET_channel_destroy(struct GNUNET_CADET_Channel *channel); /** @@ -252,7 +250,7 @@ GNUNET_CADET_channel_destroy (struct GNUNET_CADET_Channel *channel); * @return The message queue of the channel. */ struct GNUNET_MQ_Handle * -GNUNET_CADET_get_mq (const struct GNUNET_CADET_Channel *channel); +GNUNET_CADET_get_mq(const struct GNUNET_CADET_Channel *channel); /** @@ -263,7 +261,7 @@ GNUNET_CADET_get_mq (const struct GNUNET_CADET_Channel *channel); * @param channel Channel that will be allowed to call another handler. */ void -GNUNET_CADET_receive_done (struct GNUNET_CADET_Channel *channel); +GNUNET_CADET_receive_done(struct GNUNET_CADET_Channel *channel); /** @@ -276,25 +274,21 @@ GNUNET_CADET_receive_done (struct GNUNET_CADET_Channel *channel); * @return A GNUNET_HashCode usable for the new CADET API. */ const struct GNUNET_HashCode * -GC_u2h (uint32_t port); +GC_u2h(uint32_t port); -enum GNUNET_CADET_ChannelInfoOption -{ +enum GNUNET_CADET_ChannelInfoOption { /** * Who is the peer at the other end of the channel. * Only for use in @c GNUNET_CADET_channel_get_info * struct GNUNET_PeerIdentity *peer */ GNUNET_CADET_OPTION_PEER = 0x0 - }; /** * Union to retrieve info about a channel. */ -union GNUNET_CADET_ChannelInfo -{ - +union GNUNET_CADET_ChannelInfo { /** * #GNUNET_YES / #GNUNET_NO, for binary flags. */ @@ -315,9 +309,9 @@ union GNUNET_CADET_ChannelInfo * @return Union with an answer to the query. */ const union GNUNET_CADET_ChannelInfo * -GNUNET_CADET_channel_get_info (struct GNUNET_CADET_Channel *channel, - enum GNUNET_CADET_ChannelInfoOption option, - ...); +GNUNET_CADET_channel_get_info(struct GNUNET_CADET_Channel *channel, + enum GNUNET_CADET_ChannelInfoOption option, + ...); /******************************************************************************/ @@ -334,8 +328,7 @@ GNUNET_CADET_channel_get_info (struct GNUNET_CADET_Channel *channel, /** * Internal details about a channel. */ -struct GNUNET_CADET_ChannelInternals -{ +struct GNUNET_CADET_ChannelInternals { /** * Root of the channel */ @@ -377,10 +370,10 @@ struct GNUNET_CADET_ChannelMonitor; * @param callback_cls Closure for @c callback. */ struct GNUNET_CADET_ChannelMonitor * -GNUNET_CADET_get_channel (const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_PeerIdentity *peer, - GNUNET_CADET_ChannelCB callback, - void *callback_cls); +GNUNET_CADET_get_channel(const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_PeerIdentity *peer, + GNUNET_CADET_ChannelCB callback, + void *callback_cls); /** @@ -390,14 +383,13 @@ GNUNET_CADET_get_channel (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return Closure that was given to #GNUNET_CADET_get_channel(). */ void * -GNUNET_CADET_get_channel_cancel (struct GNUNET_CADET_ChannelMonitor *cm); +GNUNET_CADET_get_channel_cancel(struct GNUNET_CADET_ChannelMonitor *cm); /** * Information we return per peer. */ -struct GNUNET_CADET_PeerListEntry -{ +struct GNUNET_CADET_PeerListEntry { /** * Which peer is the information about? */ @@ -451,9 +443,9 @@ struct GNUNET_CADET_PeersLister; * @return NULL on error */ struct GNUNET_CADET_PeersLister * -GNUNET_CADET_list_peers (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_CADET_PeersCB callback, - void *callback_cls); +GNUNET_CADET_list_peers(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_CADET_PeersCB callback, + void *callback_cls); /** @@ -463,14 +455,13 @@ GNUNET_CADET_list_peers (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return Closure that was given to #GNUNET_CADET_list_peers(). */ void * -GNUNET_CADET_list_peers_cancel (struct GNUNET_CADET_PeersLister *pl); +GNUNET_CADET_list_peers_cancel(struct GNUNET_CADET_PeersLister *pl); /** * Detailed information we return per peer. */ -struct GNUNET_CADET_PeerPathDetail -{ +struct GNUNET_CADET_PeerPathDetail { /** * Peer this is about. */ @@ -523,10 +514,10 @@ struct GNUNET_CADET_GetPath; * @return NULL on error */ struct GNUNET_CADET_GetPath * -GNUNET_CADET_get_path (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_PeerIdentity *id, - GNUNET_CADET_PathCB callback, - void *callback_cls); +GNUNET_CADET_get_path(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_PeerIdentity *id, + GNUNET_CADET_PathCB callback, + void *callback_cls); /** @@ -536,14 +527,13 @@ GNUNET_CADET_get_path (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return closure from #GNUNET_CADET_get_path(). */ void * -GNUNET_CADET_get_path_cancel (struct GNUNET_CADET_GetPath *gp); +GNUNET_CADET_get_path_cancel(struct GNUNET_CADET_GetPath *gp); /** * Details about a tunnel managed by CADET. */ -struct GNUNET_CADET_TunnelDetails -{ +struct GNUNET_CADET_TunnelDetails { /** * Target of the tunnel. */ @@ -602,9 +592,9 @@ struct GNUNET_CADET_ListTunnels; * @return NULL on error */ struct GNUNET_CADET_ListTunnels * -GNUNET_CADET_list_tunnels (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_CADET_TunnelsCB callback, - void *callback_cls); +GNUNET_CADET_list_tunnels(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_CADET_TunnelsCB callback, + void *callback_cls); /** @@ -614,7 +604,7 @@ GNUNET_CADET_list_tunnels (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return Closure given to #GNUNET_CADET_list_tunnels(), if any. */ void * -GNUNET_CADET_list_tunnels_cancel (struct GNUNET_CADET_ListTunnels *lt); +GNUNET_CADET_list_tunnels_cancel(struct GNUNET_CADET_ListTunnels *lt); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_client_lib.h b/src/include/gnunet_client_lib.h index c8c5c2885..8e4984124 100644 --- a/src/include/gnunet_client_lib.h +++ b/src/include/gnunet_client_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -57,11 +57,11 @@ extern "C" * @return the message queue, NULL on error */ struct GNUNET_MQ_Handle * -GNUNET_CLIENT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *service_name, - const struct GNUNET_MQ_MessageHandler *handlers, - GNUNET_MQ_ErrorHandler error_handler, - void *error_handler_cls); +GNUNET_CLIENT_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *service_name, + const struct GNUNET_MQ_MessageHandler *handlers, + GNUNET_MQ_ErrorHandler error_handler, + void *error_handler_cls); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_common.h b/src/include/gnunet_common.h index 6eed12ddb..afaf3a4de 100644 --- a/src/include/gnunet_common.h +++ b/src/include/gnunet_common.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file include/gnunet_common.h @@ -116,7 +116,7 @@ extern "C" { /** * wrap va_arg for enums */ -#define GNUNET_VA_ARG_ENUM(va, X) ((enum X) va_arg (va, int)) +#define GNUNET_VA_ARG_ENUM(va, X) ((enum X)va_arg(va, int)) /** @@ -133,36 +133,36 @@ extern "C" { */ #if __BYTE_ORDER == __LITTLE_ENDIAN -#define GNUNET_htobe16(x) __bswap_16 (x) +#define GNUNET_htobe16(x) __bswap_16(x) #define GNUNET_htole16(x) (x) -#define GNUNET_be16toh(x) __bswap_16 (x) +#define GNUNET_be16toh(x) __bswap_16(x) #define GNUNET_le16toh(x) (x) -#define GNUNET_htobe32(x) __bswap_32 (x) +#define GNUNET_htobe32(x) __bswap_32(x) #define GNUNET_htole32(x) (x) -#define GNUNET_be32toh(x) __bswap_32 (x) +#define GNUNET_be32toh(x) __bswap_32(x) #define GNUNET_le32toh(x) (x) -#define GNUNET_htobe64(x) __bswap_64 (x) +#define GNUNET_htobe64(x) __bswap_64(x) #define GNUNET_htole64(x) (x) -#define GNUNET_be64toh(x) __bswap_64 (x) +#define GNUNET_be64toh(x) __bswap_64(x) #define GNUNET_le64toh(x) (x) #endif #if __BYTE_ORDER == __BIG_ENDIAN #define GNUNET_htobe16(x) (x) -#define GNUNET_htole16(x) __bswap_16 (x) +#define GNUNET_htole16(x) __bswap_16(x) #define GNUNET_be16toh(x) (x) -#define GNUNET_le16toh(x) __bswap_16 (x) +#define GNUNET_le16toh(x) __bswap_16(x) #define GNUNET_htobe32(x) (x) -#define GNUNET_htole32(x) __bswap_32 (x) +#define GNUNET_htole32(x) __bswap_32(x) #define GNUNET_be32toh(x) (x) -#define GNUNET_le32toh(x) __bswap_32 (x) +#define GNUNET_le32toh(x) __bswap_32(x) #define GNUNET_htobe64(x) (x) -#define GNUNET_htole64(x) __bswap_64 (x) +#define GNUNET_htole64(x) __bswap_64(x) #define GNUNET_be64toh(x) (x) -#define GNUNET_le64toh(x) __bswap_64 (x) +#define GNUNET_le64toh(x) __bswap_64(x) #endif @@ -178,7 +178,7 @@ extern "C" { * on the stack with a variable-length that might be zero, write * "int[GNUNET_NZL(n)] x;" instead of "int[n] x". */ -#define GNUNET_NZL(l) GNUNET_MAX (1, l) +#define GNUNET_NZL(l) GNUNET_MAX(1, l) /** @@ -201,9 +201,9 @@ extern "C" { * bug #33594. */ #ifdef __BIGGEST_ALIGNMENT__ -#define GNUNET_ALIGN __attribute__ ((aligned (__BIGGEST_ALIGNMENT__))) +#define GNUNET_ALIGN __attribute__ ((aligned(__BIGGEST_ALIGNMENT__))) #else -#define GNUNET_ALIGN __attribute__ ((aligned (8))) +#define GNUNET_ALIGN __attribute__ ((aligned(8))) #endif /** @@ -224,7 +224,7 @@ extern "C" { * so we *only* use this on W32 (see #670578 from Debian); fortunately, * W32 doesn't run on sparc anyway. */ -#define GNUNET_NETWORK_STRUCT_BEGIN _Pragma ("pack(push)") _Pragma ("pack(1)") +#define GNUNET_NETWORK_STRUCT_BEGIN _Pragma("pack(push)") _Pragma ("pack(1)") /** * gcc 4.x-ism to pack structures even on W32 (to be used after structs) @@ -232,7 +232,7 @@ extern "C" { * so we *only* use this on W32 (see #670578 from Debian); fortunately, * W32 doesn't run on sparc anyway. */ -#define GNUNET_NETWORK_STRUCT_END _Pragma ("pack(pop)") +#define GNUNET_NETWORK_STRUCT_END _Pragma("pack(pop)") #else #error gcc 4.x or higher required on W32 systems @@ -256,9 +256,8 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * @brief A 512-bit hashcode. These are the default length for GNUnet, using SHA-512. */ -struct GNUNET_HashCode -{ - uint32_t bits[512 / 8 / sizeof (uint32_t)]; /* = 16 */ +struct GNUNET_HashCode { + uint32_t bits[512 / 8 / sizeof(uint32_t)]; /* = 16 */ }; @@ -266,17 +265,15 @@ struct GNUNET_HashCode * @brief A 256-bit hashcode. Used under special conditions, like when space * is critical and security is not impacted by it. */ -struct GNUNET_ShortHashCode -{ - uint32_t bits[256 / 8 / sizeof (uint32_t)]; /* = 8 */ +struct GNUNET_ShortHashCode { + uint32_t bits[256 / 8 / sizeof(uint32_t)]; /* = 8 */ }; /** * A UUID, a 128 bit random value. */ -struct GNUNET_Uuid -{ +struct GNUNET_Uuid { /** * 128 random bits. */ @@ -287,9 +284,7 @@ struct GNUNET_Uuid /** * Header for all communications. */ -struct GNUNET_MessageHeader -{ - +struct GNUNET_MessageHeader { /** * The length of the struct (in bytes, including the length field itself), * in big-endian format. @@ -306,8 +301,7 @@ struct GNUNET_MessageHeader /** * Answer from service to client about last operation. */ -struct GNUNET_OperationResultMessage -{ +struct GNUNET_OperationResultMessage { struct GNUNET_MessageHeader header; uint32_t reserved GNUNET_PACKED; @@ -329,9 +323,8 @@ struct GNUNET_OperationResultMessage /** * Identifier for an asynchronous execution context. */ -struct GNUNET_AsyncScopeId -{ - uint32_t bits[16 / sizeof (uint32_t)]; /* = 16 bytes */ +struct GNUNET_AsyncScopeId { + uint32_t bits[16 / sizeof(uint32_t)]; /* = 16 bytes */ }; GNUNET_NETWORK_STRUCT_END @@ -340,8 +333,7 @@ GNUNET_NETWORK_STRUCT_END /** * Saved async scope identifier or root scope. */ -struct GNUNET_AsyncScopeSave -{ +struct GNUNET_AsyncScopeSave { /** * Saved scope. Unused if 'have_scope==GNUNET_NO'. */ @@ -398,8 +390,7 @@ typedef void (*GNUNET_ResultCallback) (void *cls, * @ingroup logging * Types of errors. */ -enum GNUNET_ErrorType -{ +enum GNUNET_ErrorType { GNUNET_ERROR_TYPE_UNSPECIFIED = -1, GNUNET_ERROR_TYPE_NONE = 0, GNUNET_ERROR_TYPE_ERROR = 1, @@ -439,16 +430,16 @@ typedef void (*GNUNET_Logger) (void *cls, * @return number of log calls to be ignored */ int -GNUNET_get_log_skip (void); +GNUNET_get_log_skip(void); -#if ! defined(GNUNET_CULL_LOGGING) +#if !defined(GNUNET_CULL_LOGGING) int -GNUNET_get_log_call_status (int caller_level, - const char *comp, - const char *file, - const char *function, - int line); +GNUNET_get_log_call_status(int caller_level, + const char *comp, + const char *file, + const char *function, + int line); #endif @@ -461,8 +452,8 @@ GNUNET_get_log_call_status (int caller_level, * @param ... arguments for format string */ void -GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...) - __attribute__ ((format (printf, 2, 3))); +GNUNET_log_nocheck(enum GNUNET_ErrorType kind, const char *message, ...) +__attribute__ ((format(printf, 2, 3))); /* from glib */ #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__) @@ -470,19 +461,19 @@ GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...) __extension__({ \ int _gnunet_boolean_var_; \ if (expr) \ - _gnunet_boolean_var_ = 1; \ + _gnunet_boolean_var_ = 1; \ else \ - _gnunet_boolean_var_ = 0; \ + _gnunet_boolean_var_ = 0; \ _gnunet_boolean_var_; \ - }) -#define GN_LIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR (expr), 1)) -#define GN_UNLIKELY(expr) (__builtin_expect (_GNUNET_BOOLEAN_EXPR (expr), 0)) + }) +#define GN_LIKELY(expr) (__builtin_expect(_GNUNET_BOOLEAN_EXPR(expr), 1)) +#define GN_UNLIKELY(expr) (__builtin_expect(_GNUNET_BOOLEAN_EXPR(expr), 0)) #else #define GN_LIKELY(expr) (expr) #define GN_UNLIKELY(expr) (expr) #endif -#if ! defined(GNUNET_LOG_CALL_STATUS) +#if !defined(GNUNET_LOG_CALL_STATUS) #define GNUNET_LOG_CALL_STATUS -1 #endif @@ -498,12 +489,12 @@ GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...) * @param ... arguments for format string */ void -GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, - const char *comp, - const char *message, - ...); +GNUNET_log_from_nocheck(enum GNUNET_ErrorType kind, + const char *comp, + const char *message, + ...); -#if ! defined(GNUNET_CULL_LOGGING) +#if !defined(GNUNET_CULL_LOGGING) #define GNUNET_log_from(kind, comp, ...) \ do \ { \ @@ -511,21 +502,21 @@ GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, if ((GNUNET_EXTRA_LOGGING > 0) || \ ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) \ { \ - if (GN_UNLIKELY (log_call_enabled == -1)) \ - log_call_enabled = \ - GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \ - (comp), \ - __FILE__, \ - __FUNCTION__, \ - __LINE__); \ - if (GN_UNLIKELY (GNUNET_get_log_skip () > 0)) \ + if (GN_UNLIKELY(log_call_enabled == -1)) \ + log_call_enabled = \ + GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \ + (comp), \ + __FILE__, \ + __FUNCTION__, \ + __LINE__); \ + if (GN_UNLIKELY(GNUNET_get_log_skip() > 0)) \ { \ - GNUNET_log_skip (-1, GNUNET_NO); \ + GNUNET_log_skip(-1, GNUNET_NO); \ } \ else \ { \ - if (GN_UNLIKELY (log_call_enabled)) \ - GNUNET_log_from_nocheck ((kind), comp, __VA_ARGS__); \ + if (GN_UNLIKELY(log_call_enabled)) \ + GNUNET_log_from_nocheck ((kind), comp, __VA_ARGS__); \ } \ } \ } while (0) @@ -537,21 +528,21 @@ GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, if ((GNUNET_EXTRA_LOGGING > 0) || \ ((GNUNET_ERROR_TYPE_DEBUG & (kind)) == 0)) \ { \ - if (GN_UNLIKELY (log_call_enabled == -1)) \ - log_call_enabled = \ - GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \ - NULL, \ - __FILE__, \ - __FUNCTION__, \ - __LINE__); \ - if (GN_UNLIKELY (GNUNET_get_log_skip () > 0)) \ + if (GN_UNLIKELY(log_call_enabled == -1)) \ + log_call_enabled = \ + GNUNET_get_log_call_status ((kind) & (~GNUNET_ERROR_TYPE_BULK), \ + NULL, \ + __FILE__, \ + __FUNCTION__, \ + __LINE__); \ + if (GN_UNLIKELY(GNUNET_get_log_skip() > 0)) \ { \ - GNUNET_log_skip (-1, GNUNET_NO); \ + GNUNET_log_skip(-1, GNUNET_NO); \ } \ else \ { \ - if (GN_UNLIKELY (log_call_enabled)) \ - GNUNET_log_nocheck ((kind), __VA_ARGS__); \ + if (GN_UNLIKELY(log_call_enabled)) \ + GNUNET_log_nocheck ((kind), __VA_ARGS__); \ } \ } \ } while (0) @@ -570,9 +561,9 @@ GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, * @param option name of missing option */ void -GNUNET_log_config_missing (enum GNUNET_ErrorType kind, - const char *section, - const char *option); +GNUNET_log_config_missing(enum GNUNET_ErrorType kind, + const char *section, + const char *option); /** @@ -585,10 +576,10 @@ GNUNET_log_config_missing (enum GNUNET_ErrorType kind, * @param required what is required that is invalid about the option */ void -GNUNET_log_config_invalid (enum GNUNET_ErrorType kind, - const char *section, - const char *option, - const char *required); +GNUNET_log_config_invalid(enum GNUNET_ErrorType kind, + const char *section, + const char *option, + const char *required); /** @@ -598,7 +589,7 @@ GNUNET_log_config_invalid (enum GNUNET_ErrorType kind, * first log the location of the failure. */ void -GNUNET_abort_ (void) GNUNET_NORETURN; +GNUNET_abort_(void) GNUNET_NORETURN; /** @@ -609,7 +600,7 @@ GNUNET_abort_ (void) GNUNET_NORETURN; * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero */ void -GNUNET_log_skip (int n, int check_reset); +GNUNET_log_skip(int n, int check_reset); /** @@ -622,7 +613,7 @@ GNUNET_log_skip (int n, int check_reset); * @return #GNUNET_OK on success, #GNUNET_SYSERR if logfile could not be opened */ int -GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile); +GNUNET_log_setup(const char *comp, const char *loglevel, const char *logfile); /** @@ -636,7 +627,7 @@ GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile); * @param logger_cls closure for @a logger */ void -GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls); +GNUNET_logger_add(GNUNET_Logger logger, void *logger_cls); /** @@ -647,7 +638,7 @@ GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls); * @param logger_cls closure for @a logger */ void -GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls); +GNUNET_logger_remove(GNUNET_Logger logger, void *logger_cls); /** @@ -660,7 +651,7 @@ GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls); * @return string */ const char * -GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc); +GNUNET_sh2s(const struct GNUNET_ShortHashCode *shc); /** @@ -673,7 +664,7 @@ GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc); * @return string */ const char * -GNUNET_uuid2s (const struct GNUNET_Uuid *uuid); +GNUNET_uuid2s(const struct GNUNET_Uuid *uuid); /** @@ -686,7 +677,7 @@ GNUNET_uuid2s (const struct GNUNET_Uuid *uuid); * @return string */ const char * -GNUNET_h2s (const struct GNUNET_HashCode *hc); +GNUNET_h2s(const struct GNUNET_HashCode *hc); /** @@ -701,7 +692,7 @@ GNUNET_h2s (const struct GNUNET_HashCode *hc); * @return string */ const char * -GNUNET_h2s2 (const struct GNUNET_HashCode *hc); +GNUNET_h2s2(const struct GNUNET_HashCode *hc); /** @@ -715,7 +706,7 @@ GNUNET_h2s2 (const struct GNUNET_HashCode *hc); * @return string */ const char * -GNUNET_h2s_full (const struct GNUNET_HashCode *hc); +GNUNET_h2s_full(const struct GNUNET_HashCode *hc); /** @@ -740,7 +731,7 @@ struct GNUNET_CRYPTO_EcdhePublicKey; * @return string */ const char * -GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p); +GNUNET_p2s(const struct GNUNET_CRYPTO_EddsaPublicKey *p); /** @@ -753,7 +744,7 @@ GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p); * @return string */ const char * -GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p); +GNUNET_p2s2(const struct GNUNET_CRYPTO_EddsaPublicKey *p); /** @@ -766,7 +757,7 @@ GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p); * @return string */ const char * -GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p); +GNUNET_e2s(const struct GNUNET_CRYPTO_EcdhePublicKey *p); /** @@ -779,7 +770,7 @@ GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p); * @return string */ const char * -GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p); +GNUNET_e2s2(const struct GNUNET_CRYPTO_EcdhePublicKey *p); /** @@ -793,7 +784,7 @@ GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p); * call to #GNUNET_i2s(). */ const char * -GNUNET_i2s (const struct GNUNET_PeerIdentity *pid); +GNUNET_i2s(const struct GNUNET_PeerIdentity *pid); /** @@ -809,7 +800,7 @@ GNUNET_i2s (const struct GNUNET_PeerIdentity *pid); * call to #GNUNET_i2s(). */ const char * -GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid); +GNUNET_i2s2(const struct GNUNET_PeerIdentity *pid); /** @@ -823,7 +814,7 @@ GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid); * call to #GNUNET_i2s_full(). */ const char * -GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid); +GNUNET_i2s_full(const struct GNUNET_PeerIdentity *pid); /** @@ -838,7 +829,7 @@ GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid); * will be overwritten by next call to #GNUNET_a2s(). */ const char * -GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen); +GNUNET_a2s(const struct sockaddr *addr, socklen_t addrlen); /** @@ -849,7 +840,7 @@ GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen); * @return string corresponding to the type */ const char * -GNUNET_error_type_to_string (enum GNUNET_ErrorType kind); +GNUNET_error_type_to_string(enum GNUNET_ErrorType kind); /** @@ -859,13 +850,13 @@ GNUNET_error_type_to_string (enum GNUNET_ErrorType kind); #define GNUNET_assert(cond) \ do \ { \ - if (! (cond)) \ + if (!(cond)) \ { \ - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \ - _ ("Assertion failed at %s:%d. Aborting.\n"), \ - __FILE__, \ - __LINE__); \ - GNUNET_abort_ (); \ + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, \ + _("Assertion failed at %s:%d. Aborting.\n"), \ + __FILE__, \ + __LINE__); \ + GNUNET_abort_(); \ } \ } while (0) @@ -877,13 +868,13 @@ GNUNET_error_type_to_string (enum GNUNET_ErrorType kind); #define GNUNET_assert_at(cond, f, l) \ do \ { \ - if (! (cond)) \ + if (!(cond)) \ { \ - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \ - _ ("Assertion failed at %s:%d. Aborting.\n"), \ - f, \ - l); \ - GNUNET_abort_ (); \ + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, \ + _("Assertion failed at %s:%d. Aborting.\n"), \ + f, \ + l); \ + GNUNET_abort_(); \ } \ } while (0) @@ -898,14 +889,14 @@ GNUNET_error_type_to_string (enum GNUNET_ErrorType kind); #define GNUNET_assert_from(cond, comp) \ do \ { \ - if (! (cond)) \ + if (!(cond)) \ { \ - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, \ - comp, \ - _ ("Assertion failed at %s:%d. Aborting.\n"), \ - __FILE__, \ - __LINE__); \ - GNUNET_abort_ (); \ + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, \ + comp, \ + _("Assertion failed at %s:%d. Aborting.\n"), \ + __FILE__, \ + __LINE__); \ + GNUNET_abort_(); \ } \ } while (0) @@ -918,12 +909,12 @@ GNUNET_error_type_to_string (enum GNUNET_ErrorType kind); #define GNUNET_break(cond) \ do \ { \ - if (! (cond)) \ + if (!(cond)) \ { \ - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, \ - _ ("Assertion failed at %s:%d.\n"), \ - __FILE__, \ - __LINE__); \ + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, \ + _("Assertion failed at %s:%d.\n"), \ + __FILE__, \ + __LINE__); \ } \ } while (0) @@ -940,12 +931,12 @@ GNUNET_error_type_to_string (enum GNUNET_ErrorType kind); #define GNUNET_break_op(cond) \ do \ { \ - if (! (cond)) \ + if (!(cond)) \ { \ - GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, \ - _ ("External protocol violation detected at %s:%d.\n"), \ - __FILE__, \ - __LINE__); \ + GNUNET_log(GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, \ + _("External protocol violation detected at %s:%d.\n"), \ + __FILE__, \ + __LINE__); \ } \ } while (0) @@ -959,12 +950,12 @@ GNUNET_error_type_to_string (enum GNUNET_ErrorType kind); #define GNUNET_log_strerror(level, cmd) \ do \ { \ - GNUNET_log (level, \ - _ ("`%s' failed at %s:%d with error: %s\n"), \ - cmd, \ - __FILE__, \ - __LINE__, \ - strerror (errno)); \ + GNUNET_log(level, \ + _("`%s' failed at %s:%d with error: %s\n"), \ + cmd, \ + __FILE__, \ + __LINE__, \ + strerror(errno)); \ } while (0) @@ -977,13 +968,13 @@ GNUNET_error_type_to_string (enum GNUNET_ErrorType kind); #define GNUNET_log_from_strerror(level, component, cmd) \ do \ { \ - GNUNET_log_from (level, \ - component, \ - _ ("`%s' failed at %s:%d with error: %s\n"), \ - cmd, \ - __FILE__, \ - __LINE__, \ - strerror (errno)); \ + GNUNET_log_from(level, \ + component, \ + _("`%s' failed at %s:%d with error: %s\n"), \ + cmd, \ + __FILE__, \ + __LINE__, \ + strerror(errno)); \ } while (0) @@ -996,13 +987,13 @@ GNUNET_error_type_to_string (enum GNUNET_ErrorType kind); #define GNUNET_log_strerror_file(level, cmd, filename) \ do \ { \ - GNUNET_log (level, \ - _ ("`%s' failed on file `%s' at %s:%d with error: %s\n"), \ - cmd, \ - filename, \ - __FILE__, \ - __LINE__, \ - strerror (errno)); \ + GNUNET_log(level, \ + _("`%s' failed on file `%s' at %s:%d with error: %s\n"), \ + cmd, \ + filename, \ + __FILE__, \ + __LINE__, \ + strerror(errno)); \ } while (0) @@ -1015,14 +1006,14 @@ GNUNET_error_type_to_string (enum GNUNET_ErrorType kind); #define GNUNET_log_from_strerror_file(level, component, cmd, filename) \ do \ { \ - GNUNET_log_from (level, \ - component, \ - _ ("`%s' failed on file `%s' at %s:%d with error: %s\n"), \ - cmd, \ - filename, \ - __FILE__, \ - __LINE__, \ - strerror (errno)); \ + GNUNET_log_from(level, \ + component, \ + _("`%s' failed on file `%s' at %s:%d with error: %s\n"), \ + cmd, \ + filename, \ + __FILE__, \ + __LINE__, \ + strerror(errno)); \ } while (0) /* ************************* endianess conversion ****************** */ @@ -1036,7 +1027,7 @@ GNUNET_error_type_to_string (enum GNUNET_ErrorType kind); * @return The same value in network byte order. */ uint64_t -GNUNET_htonll (uint64_t n); +GNUNET_htonll(uint64_t n); /** @@ -1048,7 +1039,7 @@ GNUNET_htonll (uint64_t n); * @return The same value in host byte order. */ uint64_t -GNUNET_ntohll (uint64_t n); +GNUNET_ntohll(uint64_t n); /** @@ -1060,7 +1051,7 @@ GNUNET_ntohll (uint64_t n); * @return The same value in network byte order. */ double -GNUNET_hton_double (double d); +GNUNET_hton_double(double d); /** @@ -1072,7 +1063,7 @@ GNUNET_hton_double (double d); * @return The same value in host byte order. */ double -GNUNET_ntoh_double (double d); +GNUNET_ntoh_double(double d); /* ************************* allocation functions ****************** */ @@ -1091,7 +1082,7 @@ GNUNET_ntoh_double (double d); * * @param type name of the struct or union, i.e. pass 'struct Foo'. */ -#define GNUNET_new(type) (type *) GNUNET_malloc (sizeof (type)) +#define GNUNET_new(type) (type *)GNUNET_malloc(sizeof(type)) /** @@ -1100,9 +1091,9 @@ GNUNET_ntoh_double (double d); */ #define GNUNET_memcmp(a, b) \ ({ \ - const typeof (*b) *_a = (a); \ - const typeof (*a) *_b = (b); \ - memcmp (_a, _b, sizeof (*a)); \ + const typeof (*b) * _a = (a); \ + const typeof (*a) * _b = (b); \ + memcmp(_a, _b, sizeof(*a)); \ }) @@ -1115,7 +1106,7 @@ GNUNET_ntoh_double (double d); #define GNUNET_is_zero(a) \ ({ \ static const typeof (*a) _z; \ - memcmp ((a), &_z, sizeof (_z)); \ + memcmp((a), &_z, sizeof(_z)); \ }) @@ -1133,7 +1124,7 @@ GNUNET_ntoh_double (double d); { \ if (0 != n) \ { \ - (void) memcpy (dst, src, n); \ + (void)memcpy(dst, src, n); \ } \ } while (0) @@ -1147,7 +1138,7 @@ GNUNET_ntoh_double (double d); * @param n number of elements in the array * @param type name of the struct or union, i.e. pass 'struct Foo'. */ -#define GNUNET_new_array(n, type) (type *) GNUNET_malloc ((n) * sizeof (type)) +#define GNUNET_new_array(n, type) (type *)GNUNET_malloc((n) * sizeof(type)) /** * @ingroup memory @@ -1159,7 +1150,7 @@ GNUNET_ntoh_double (double d); * @param type name of the struct or union, i.e. pass 'struct Foo'. */ #define GNUNET_new_array_2d(n, m, type) \ - (type **) GNUNET_xnew_array_2d_ (n, m, sizeof (type), __FILE__, __LINE__) + (type **)GNUNET_xnew_array_2d_(n, m, sizeof(type), __FILE__, __LINE__) /** * @ingroup memory @@ -1172,7 +1163,7 @@ GNUNET_ntoh_double (double d); * @param type name of the struct or union, i.e. pass 'struct Foo'. */ #define GNUNET_new_array_3d(n, m, o, type) \ - (type ***) GNUNET_xnew_array_3d_ (n, m, o, sizeof (type), __FILE__, __LINE__) + (type ***)GNUNET_xnew_array_3d_(n, m, o, sizeof(type), __FILE__, __LINE__) /** * @ingroup memory @@ -1183,7 +1174,7 @@ GNUNET_ntoh_double (double d); * smaller than 40 MB. * @return pointer to size bytes of memory, never NULL (!) */ -#define GNUNET_malloc(size) GNUNET_xmalloc_ (size, __FILE__, __LINE__) +#define GNUNET_malloc(size) GNUNET_xmalloc_(size, __FILE__, __LINE__) /** * @ingroup memory @@ -1193,7 +1184,7 @@ GNUNET_ntoh_double (double d); * @param size the number of bytes in buf (and size of the allocation) * @return pointer to size bytes of memory, never NULL (!) */ -#define GNUNET_memdup(buf, size) GNUNET_xmemdup_ (buf, size, __FILE__, __LINE__) +#define GNUNET_memdup(buf, size) GNUNET_xmemdup_(buf, size, __FILE__, __LINE__) /** * @ingroup memory @@ -1204,7 +1195,7 @@ GNUNET_ntoh_double (double d); * @return pointer to size bytes of memory, NULL if we do not have enough memory */ #define GNUNET_malloc_large(size) \ - GNUNET_xmalloc_unchecked_ (size, __FILE__, __LINE__) + GNUNET_xmalloc_unchecked_(size, __FILE__, __LINE__) /** * @ingroup memory @@ -1216,7 +1207,7 @@ GNUNET_ntoh_double (double d); * @return pointer to size bytes of memory */ #define GNUNET_realloc(ptr, size) \ - GNUNET_xrealloc_ (ptr, size, __FILE__, __LINE__) + GNUNET_xrealloc_(ptr, size, __FILE__, __LINE__) /** * @ingroup memory @@ -1227,7 +1218,7 @@ GNUNET_ntoh_double (double d); * @param ptr location where to free the memory. ptr must have * been returned by #GNUNET_strdup, #GNUNET_strndup, #GNUNET_malloc or #GNUNET_array_grow earlier. */ -#define GNUNET_free(ptr) GNUNET_xfree_ (ptr, __FILE__, __LINE__) +#define GNUNET_free(ptr) GNUNET_xfree_(ptr, __FILE__, __LINE__) /** * @ingroup memory @@ -1242,7 +1233,7 @@ GNUNET_ntoh_double (double d); void *__x__ = ptr; \ if (__x__ != NULL) \ { \ - GNUNET_free (__x__); \ + GNUNET_free(__x__); \ } \ } while (0) @@ -1254,7 +1245,7 @@ GNUNET_ntoh_double (double d); * @param a pointer to a zero-terminated string * @return a copy of the string including zero-termination */ -#define GNUNET_strdup(a) GNUNET_xstrdup_ (a, __FILE__, __LINE__) +#define GNUNET_strdup(a) GNUNET_xstrdup_(a, __FILE__, __LINE__) /** * @ingroup memory @@ -1266,7 +1257,7 @@ GNUNET_ntoh_double (double d); * @return a partial copy of the string including zero-termination */ #define GNUNET_strndup(a, length) \ - GNUNET_xstrndup_ (a, length, __FILE__, __LINE__) + GNUNET_xstrndup_(a, length, __FILE__, __LINE__) /** * @ingroup memory @@ -1304,12 +1295,12 @@ GNUNET_ntoh_double (double d); * free the vector (then, arr will be NULL afterwards). */ #define GNUNET_array_grow(arr, size, tsize) \ - GNUNET_xgrow_ ((void **) &(arr), \ - sizeof ((arr)[0]), \ - &size, \ - tsize, \ - __FILE__, \ - __LINE__) + GNUNET_xgrow_((void **)&(arr), \ + sizeof((arr)[0]), \ + &size, \ + tsize, \ + __FILE__, \ + __LINE__) /** * @ingroup memory @@ -1327,7 +1318,7 @@ GNUNET_ntoh_double (double d); #define GNUNET_array_append(arr, size, element) \ do \ { \ - GNUNET_array_grow (arr, size, size + 1); \ + GNUNET_array_grow(arr, size, size + 1); \ (arr)[size - 1] = element; \ } while (0) @@ -1342,7 +1333,7 @@ GNUNET_ntoh_double (double d); * @return number of bytes written to buf or negative value on error */ int -GNUNET_snprintf (char *buf, size_t size, const char *format, ...); +GNUNET_snprintf(char *buf, size_t size, const char *format, ...); /** @@ -1355,7 +1346,7 @@ GNUNET_snprintf (char *buf, size_t size, const char *format, ...); * @return number of bytes in "*buf" excluding 0-termination */ int -GNUNET_asprintf (char **buf, const char *format, ...); +GNUNET_asprintf(char **buf, const char *format, ...); /* ************** internal implementations, use macros above! ************** */ @@ -1372,7 +1363,7 @@ GNUNET_asprintf (char **buf, const char *format, ...); * @return allocated memory, never NULL */ void * -GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber); +GNUNET_xmalloc_(size_t size, const char *filename, int linenumber); /** @@ -1390,11 +1381,11 @@ GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber); * @return allocated memory, never NULL */ void ** -GNUNET_xnew_array_2d_ (size_t n, - size_t m, - size_t elementSize, - const char *filename, - int linenumber); +GNUNET_xnew_array_2d_(size_t n, + size_t m, + size_t elementSize, + const char *filename, + int linenumber); /** @@ -1413,12 +1404,12 @@ GNUNET_xnew_array_2d_ (size_t n, * @return allocated memory, never NULL */ void *** -GNUNET_xnew_array_3d_ (size_t n, - size_t m, - size_t o, - size_t elementSize, - const char *filename, - int linenumber); +GNUNET_xnew_array_3d_(size_t n, + size_t m, + size_t o, + size_t elementSize, + const char *filename, + int linenumber); /** @@ -1433,10 +1424,10 @@ GNUNET_xnew_array_3d_ (size_t n, * @return allocated memory, never NULL */ void * -GNUNET_xmemdup_ (const void *buf, - size_t size, - const char *filename, - int linenumber); +GNUNET_xmemdup_(const void *buf, + size_t size, + const char *filename, + int linenumber); /** @@ -1452,7 +1443,7 @@ GNUNET_xmemdup_ (const void *buf, * @return pointer to size bytes of memory, NULL if we do not have enough memory */ void * -GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber); +GNUNET_xmalloc_unchecked_(size_t size, const char *filename, int linenumber); /** @@ -1460,7 +1451,7 @@ GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber); * memory is available. */ void * -GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber); +GNUNET_xrealloc_(void *ptr, size_t n, const char *filename, int linenumber); /** @@ -1473,7 +1464,7 @@ GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber); * @param linenumber line where this call is being made (for debugging) */ void -GNUNET_xfree_ (void *ptr, const char *filename, int linenumber); +GNUNET_xfree_(void *ptr, const char *filename, int linenumber); /** @@ -1484,7 +1475,7 @@ GNUNET_xfree_ (void *ptr, const char *filename, int linenumber); * @return the duplicated string */ char * -GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber); +GNUNET_xstrdup_(const char *str, const char *filename, int linenumber); /** * Dup partially a string. Don't call GNUNET_xstrndup_ directly. Use the #GNUNET_strndup macro. @@ -1496,10 +1487,10 @@ GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber); * @return the duplicated string */ char * -GNUNET_xstrndup_ (const char *str, - size_t len, - const char *filename, - int linenumber); +GNUNET_xstrndup_(const char *str, + size_t len, + const char *filename, + int linenumber); /** * Grow an array, the new elements are zeroed out. @@ -1517,12 +1508,12 @@ GNUNET_xstrndup_ (const char *str, * @param linenumber line where this call is being made (for debugging) */ void -GNUNET_xgrow_ (void **old, - size_t elementSize, - unsigned int *oldCount, - unsigned int newCount, - const char *filename, - int linenumber); +GNUNET_xgrow_(void **old, + size_t elementSize, + unsigned int *oldCount, + unsigned int newCount, + const char *filename, + int linenumber); /** @@ -1533,7 +1524,7 @@ GNUNET_xgrow_ (void **old, * @return duplicate of the message */ struct GNUNET_MessageHeader * -GNUNET_copy_message (const struct GNUNET_MessageHeader *msg); +GNUNET_copy_message(const struct GNUNET_MessageHeader *msg); /** @@ -1543,8 +1534,8 @@ GNUNET_copy_message (const struct GNUNET_MessageHeader *msg); * @param old_scope[out] location to save the old scope */ void -GNUNET_async_scope_enter (const struct GNUNET_AsyncScopeId *aid, - struct GNUNET_AsyncScopeSave *old_scope); +GNUNET_async_scope_enter(const struct GNUNET_AsyncScopeId *aid, + struct GNUNET_AsyncScopeSave *old_scope); /** @@ -1553,7 +1544,7 @@ GNUNET_async_scope_enter (const struct GNUNET_AsyncScopeId *aid, * @param old_scope scope to restore */ void -GNUNET_async_scope_restore (struct GNUNET_AsyncScopeSave *old_scope); +GNUNET_async_scope_restore(struct GNUNET_AsyncScopeSave *old_scope); /** @@ -1562,7 +1553,7 @@ GNUNET_async_scope_restore (struct GNUNET_AsyncScopeSave *old_scope); * @param[out] scope_ret pointer to where the result is stored */ void -GNUNET_async_scope_get (struct GNUNET_AsyncScopeSave *scope_ret); +GNUNET_async_scope_get(struct GNUNET_AsyncScopeSave *scope_ret); /** @@ -1571,7 +1562,7 @@ GNUNET_async_scope_get (struct GNUNET_AsyncScopeSave *scope_ret); * @param[out] aid_ret pointer to where the result is stored */ void -GNUNET_async_scope_fresh (struct GNUNET_AsyncScopeId *aid_ret); +GNUNET_async_scope_fresh(struct GNUNET_AsyncScopeId *aid_ret); #if __STDC_VERSION__ < 199901L @@ -1590,8 +1581,7 @@ GNUNET_async_scope_fresh (struct GNUNET_AsyncScopeId *aid_ret); * be in gnunet_scheduler_lib.h, but it works if we declare it here. * Naturally, logically this is part of the scheduler. */ -enum GNUNET_SCHEDULER_Priority -{ +enum GNUNET_SCHEDULER_Priority { /** * Run with the same priority as the current job. */ diff --git a/src/include/gnunet_configuration_lib.h b/src/include/gnunet_configuration_lib.h index a0e73f474..4d1bb6b79 100644 --- a/src/include/gnunet_configuration_lib.h +++ b/src/include/gnunet_configuration_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -51,7 +51,7 @@ struct GNUNET_CONFIGURATION_Handle; * @return fresh configuration object */ struct GNUNET_CONFIGURATION_Handle * -GNUNET_CONFIGURATION_create (void); +GNUNET_CONFIGURATION_create(void); /** @@ -61,7 +61,7 @@ GNUNET_CONFIGURATION_create (void); * @return duplicate configuration */ struct GNUNET_CONFIGURATION_Handle * -GNUNET_CONFIGURATION_dup (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_CONFIGURATION_dup(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -70,7 +70,7 @@ GNUNET_CONFIGURATION_dup (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param cfg configuration to destroy */ void -GNUNET_CONFIGURATION_destroy (struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_CONFIGURATION_destroy(struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -83,8 +83,8 @@ GNUNET_CONFIGURATION_destroy (struct GNUNET_CONFIGURATION_Handle *cfg); * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_load (struct GNUNET_CONFIGURATION_Handle *cfg, - const char *filename); +GNUNET_CONFIGURATION_load(struct GNUNET_CONFIGURATION_Handle *cfg, + const char *filename); /** @@ -96,8 +96,8 @@ GNUNET_CONFIGURATION_load (struct GNUNET_CONFIGURATION_Handle *cfg, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_load_from (struct GNUNET_CONFIGURATION_Handle *cfg, - const char *defaults_d); +GNUNET_CONFIGURATION_load_from(struct GNUNET_CONFIGURATION_Handle *cfg, + const char *defaults_d); /** @@ -109,8 +109,8 @@ GNUNET_CONFIGURATION_load_from (struct GNUNET_CONFIGURATION_Handle *cfg, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_parse (struct GNUNET_CONFIGURATION_Handle *cfg, - const char *filename); +GNUNET_CONFIGURATION_parse(struct GNUNET_CONFIGURATION_Handle *cfg, + const char *filename); /** @@ -122,8 +122,8 @@ GNUNET_CONFIGURATION_parse (struct GNUNET_CONFIGURATION_Handle *cfg, * present. This memory should be freed by the caller */ char * -GNUNET_CONFIGURATION_serialize (const struct GNUNET_CONFIGURATION_Handle *cfg, - size_t *size); +GNUNET_CONFIGURATION_serialize(const struct GNUNET_CONFIGURATION_Handle *cfg, + size_t *size); /** @@ -138,10 +138,10 @@ GNUNET_CONFIGURATION_serialize (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_deserialize (struct GNUNET_CONFIGURATION_Handle *cfg, - const char *mem, - size_t size, - const char *basedir); +GNUNET_CONFIGURATION_deserialize(struct GNUNET_CONFIGURATION_Handle *cfg, + const char *mem, + size_t size, + const char *basedir); /** @@ -152,8 +152,8 @@ GNUNET_CONFIGURATION_deserialize (struct GNUNET_CONFIGURATION_Handle *cfg, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_write (struct GNUNET_CONFIGURATION_Handle *cfg, - const char *filename); +GNUNET_CONFIGURATION_write(struct GNUNET_CONFIGURATION_Handle *cfg, + const char *filename); /** @@ -164,9 +164,9 @@ GNUNET_CONFIGURATION_write (struct GNUNET_CONFIGURATION_Handle *cfg, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_write_diffs (const struct GNUNET_CONFIGURATION_Handle *cfg_default, - const struct GNUNET_CONFIGURATION_Handle *cfg_new, - const char *filename); +GNUNET_CONFIGURATION_write_diffs(const struct GNUNET_CONFIGURATION_Handle *cfg_default, + const struct GNUNET_CONFIGURATION_Handle *cfg_new, + const char *filename); /** @@ -177,8 +177,8 @@ GNUNET_CONFIGURATION_write_diffs (const struct GNUNET_CONFIGURATION_Handle *cfg_ * @return configuration with only the differences, never NULL */ struct GNUNET_CONFIGURATION_Handle * -GNUNET_CONFIGURATION_get_diff (const struct GNUNET_CONFIGURATION_Handle *cfg_default, - const struct GNUNET_CONFIGURATION_Handle *cfg_new); +GNUNET_CONFIGURATION_get_diff(const struct GNUNET_CONFIGURATION_Handle *cfg_default, + const struct GNUNET_CONFIGURATION_Handle *cfg_new); /** @@ -189,7 +189,7 @@ GNUNET_CONFIGURATION_get_diff (const struct GNUNET_CONFIGURATION_Handle *cfg_def * @return #GNUNET_NO if clean, #GNUNET_YES if dirty, #GNUNET_SYSERR on error (i.e. last save failed) */ int -GNUNET_CONFIGURATION_is_dirty (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_CONFIGURATION_is_dirty(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -201,7 +201,7 @@ GNUNET_CONFIGURATION_is_dirty (const struct GNUNET_CONFIGURATION_Handle *cfg); */ typedef int (*GNUNET_CONFIGURATION_Callback)(void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg); + const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -216,9 +216,9 @@ typedef int * otherwise return value from @a cb. */ int -GNUNET_CONFIGURATION_parse_and_run (const char *filename, - GNUNET_CONFIGURATION_Callback cb, - void *cb_cls); +GNUNET_CONFIGURATION_parse_and_run(const char *filename, + GNUNET_CONFIGURATION_Callback cb, + void *cb_cls); /** @@ -255,9 +255,9 @@ typedef void * @param iter_cls closure for @a iter */ void -GNUNET_CONFIGURATION_iterate (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_CONFIGURATION_Iterator iter, - void *iter_cls); +GNUNET_CONFIGURATION_iterate(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_CONFIGURATION_Iterator iter, + void *iter_cls); /** @@ -268,9 +268,9 @@ GNUNET_CONFIGURATION_iterate (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param iter_cls closure for @a iter */ void -GNUNET_CONFIGURATION_iterate_sections (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_CONFIGURATION_Section_Iterator iter, - void *iter_cls); +GNUNET_CONFIGURATION_iterate_sections(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_CONFIGURATION_Section_Iterator iter, + void *iter_cls); /** @@ -280,8 +280,8 @@ GNUNET_CONFIGURATION_iterate_sections (const struct GNUNET_CONFIGURATION_Handle * @param section name of the section to remove */ void -GNUNET_CONFIGURATION_remove_section (struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section); +GNUNET_CONFIGURATION_remove_section(struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section); /** @@ -294,10 +294,10 @@ GNUNET_CONFIGURATION_remove_section (struct GNUNET_CONFIGURATION_Handle *cfg, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_get_value_number (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - unsigned long long *number); +GNUNET_CONFIGURATION_get_value_number(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + unsigned long long *number); /** @@ -310,10 +310,10 @@ GNUNET_CONFIGURATION_get_value_number (const struct GNUNET_CONFIGURATION_Handle * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_get_value_float (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - float *number); +GNUNET_CONFIGURATION_get_value_float(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + float *number); /** @@ -326,10 +326,10 @@ GNUNET_CONFIGURATION_get_value_float (const struct GNUNET_CONFIGURATION_Handle * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_get_value_time (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - struct GNUNET_TIME_Relative *time); +GNUNET_CONFIGURATION_get_value_time(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + struct GNUNET_TIME_Relative *time); @@ -343,10 +343,10 @@ GNUNET_CONFIGURATION_get_value_time (const struct GNUNET_CONFIGURATION_Handle *c * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_get_value_size (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - unsigned long long *size); +GNUNET_CONFIGURATION_get_value_size(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + unsigned long long *size); /** @@ -358,9 +358,9 @@ GNUNET_CONFIGURATION_get_value_size (const struct GNUNET_CONFIGURATION_Handle *c * @return #GNUNET_YES if so, #GNUNET_NO if not. */ int -GNUNET_CONFIGURATION_have_value (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option); +GNUNET_CONFIGURATION_have_value(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option); /** @@ -374,10 +374,10 @@ GNUNET_CONFIGURATION_have_value (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_get_value_string (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - char **value); +GNUNET_CONFIGURATION_get_value_string(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + char **value); /** @@ -392,10 +392,10 @@ GNUNET_CONFIGURATION_get_value_string (const struct GNUNET_CONFIGURATION_Handle * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_get_value_filename (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - char **value); +GNUNET_CONFIGURATION_get_value_filename(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + char **value); /** @@ -409,11 +409,11 @@ GNUNET_CONFIGURATION_get_value_filename (const struct GNUNET_CONFIGURATION_Handl * @return number of filenames iterated over, -1 on error */ int -GNUNET_CONFIGURATION_iterate_value_filenames (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - GNUNET_FileNameCallback cb, - void *cb_cls); +GNUNET_CONFIGURATION_iterate_value_filenames(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + GNUNET_FileNameCallback cb, + void *cb_cls); /** * Iterate over values of a section in the configuration. @@ -424,10 +424,10 @@ GNUNET_CONFIGURATION_iterate_value_filenames (const struct GNUNET_CONFIGURATION_ * @param iter_cls closure for @a iter */ void -GNUNET_CONFIGURATION_iterate_section_values (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - GNUNET_CONFIGURATION_Iterator iter, - void *iter_cls); +GNUNET_CONFIGURATION_iterate_section_values(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + GNUNET_CONFIGURATION_Iterator iter, + void *iter_cls); /** * Get a configuration value that should be in a set of @@ -442,11 +442,11 @@ GNUNET_CONFIGURATION_iterate_section_values (const struct GNUNET_CONFIGURATION_H * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_CONFIGURATION_get_value_choice (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - const char *const *choices, - const char **value); +GNUNET_CONFIGURATION_get_value_choice(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + const char *const *choices, + const char **value); /** * Get a configuration value that should be in a set of @@ -458,9 +458,9 @@ GNUNET_CONFIGURATION_get_value_choice (const struct GNUNET_CONFIGURATION_Handle * @return #GNUNET_YES, #GNUNET_NO or if option has no valid value, #GNUNET_SYSERR */ int -GNUNET_CONFIGURATION_get_value_yesno (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option); +GNUNET_CONFIGURATION_get_value_yesno(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option); /** @@ -476,11 +476,11 @@ GNUNET_CONFIGURATION_get_value_yesno (const struct GNUNET_CONFIGURATION_Handle * * #GNUNET_SYSERR on decoding error */ int -GNUNET_CONFIGURATION_get_data (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - void *buf, - size_t buf_size); +GNUNET_CONFIGURATION_get_data(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + void *buf, + size_t buf_size); /** @@ -500,8 +500,8 @@ GNUNET_CONFIGURATION_get_data (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return $-expanded string */ char * -GNUNET_CONFIGURATION_expand_dollar (const struct GNUNET_CONFIGURATION_Handle *cfg, - char *orig); +GNUNET_CONFIGURATION_expand_dollar(const struct GNUNET_CONFIGURATION_Handle *cfg, + char *orig); /** @@ -513,10 +513,10 @@ GNUNET_CONFIGURATION_expand_dollar (const struct GNUNET_CONFIGURATION_Handle *cf * @param number value to set */ void -GNUNET_CONFIGURATION_set_value_number (struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - unsigned long long number); +GNUNET_CONFIGURATION_set_value_number(struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + unsigned long long number); /** @@ -528,10 +528,10 @@ GNUNET_CONFIGURATION_set_value_number (struct GNUNET_CONFIGURATION_Handle *cfg, * @param value value to set */ void -GNUNET_CONFIGURATION_set_value_string (struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - const char *value); +GNUNET_CONFIGURATION_set_value_string(struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + const char *value); /** @@ -546,10 +546,10 @@ GNUNET_CONFIGURATION_set_value_string (struct GNUNET_CONFIGURATION_Handle *cfg, * #GNUNET_SYSERR if the filename is not in the list */ int -GNUNET_CONFIGURATION_remove_value_filename (struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - const char *value); +GNUNET_CONFIGURATION_remove_value_filename(struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + const char *value); /** @@ -564,10 +564,10 @@ GNUNET_CONFIGURATION_remove_value_filename (struct GNUNET_CONFIGURATION_Handle * * #GNUNET_SYSERR if the filename already in the list */ int -GNUNET_CONFIGURATION_append_value_filename (struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section, - const char *option, - const char *value); +GNUNET_CONFIGURATION_append_value_filename(struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section, + const char *option, + const char *value); #if 0 /* keep Emacsens' auto-indent happy */ { diff --git a/src/include/gnunet_consensus_service.h b/src/include/gnunet_consensus_service.h index 19736f241..e864b5337 100644 --- a/src/include/gnunet_consensus_service.h +++ b/src/include/gnunet_consensus_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -93,14 +93,14 @@ struct GNUNET_CONSENSUS_Handle; * @return handle to use, NULL on error */ struct GNUNET_CONSENSUS_Handle * -GNUNET_CONSENSUS_create (const struct GNUNET_CONFIGURATION_Handle *cfg, - unsigned int num_peers, - const struct GNUNET_PeerIdentity *peers, - const struct GNUNET_HashCode *session_id, - struct GNUNET_TIME_Absolute start, - struct GNUNET_TIME_Absolute deadline, - GNUNET_CONSENSUS_ElementCallback new_element_cb, - void *new_element_cls); +GNUNET_CONSENSUS_create(const struct GNUNET_CONFIGURATION_Handle *cfg, + unsigned int num_peers, + const struct GNUNET_PeerIdentity *peers, + const struct GNUNET_HashCode *session_id, + struct GNUNET_TIME_Absolute start, + struct GNUNET_TIME_Absolute deadline, + GNUNET_CONSENSUS_ElementCallback new_element_cb, + void *new_element_cls); /** @@ -132,10 +132,10 @@ typedef void (*GNUNET_CONSENSUS_InsertDoneCallback) (void *cls, * @param idc_cls closure for @a idc */ void -GNUNET_CONSENSUS_insert (struct GNUNET_CONSENSUS_Handle *consensus, - const struct GNUNET_SET_Element *element, - GNUNET_CONSENSUS_InsertDoneCallback idc, - void *idc_cls); +GNUNET_CONSENSUS_insert(struct GNUNET_CONSENSUS_Handle *consensus, + const struct GNUNET_SET_Element *element, + GNUNET_CONSENSUS_InsertDoneCallback idc, + void *idc_cls); @@ -156,9 +156,9 @@ typedef void (*GNUNET_CONSENSUS_ConcludeCallback) (void *cls); * @param conclude_cls closure for the conclude callback */ void -GNUNET_CONSENSUS_conclude (struct GNUNET_CONSENSUS_Handle *consensus, - GNUNET_CONSENSUS_ConcludeCallback conclude, - void *conclude_cls); +GNUNET_CONSENSUS_conclude(struct GNUNET_CONSENSUS_Handle *consensus, + GNUNET_CONSENSUS_ConcludeCallback conclude, + void *conclude_cls); /** @@ -168,7 +168,7 @@ GNUNET_CONSENSUS_conclude (struct GNUNET_CONSENSUS_Handle *consensus, * @param consensus handle to destroy */ void -GNUNET_CONSENSUS_destroy (struct GNUNET_CONSENSUS_Handle *consensus); +GNUNET_CONSENSUS_destroy(struct GNUNET_CONSENSUS_Handle *consensus); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_constants.h b/src/include/gnunet_constants.h index 7e4653a97..39dbd4425 100644 --- a/src/include/gnunet_constants.h +++ b/src/include/gnunet_constants.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -48,35 +48,35 @@ extern "C" * so that at least one maximum-size message can be send roughly once * per minute. */ -#define GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT GNUNET_BANDWIDTH_value_init (1024) +#define GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT GNUNET_BANDWIDTH_value_init(1024) /** * After how long do we consider a connection to a peer dead * if we don't receive messages from the peer? */ -#define GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5) +#define GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5) /** * How long do we delay reading more from a peer after a quota violation? */ -#define GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2) +#define GNUNET_CONSTANTS_QUOTA_VIOLATION_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 2) /** * After how long do we consider a service unresponsive * even if we assume that the service commonly does not * respond instantly (DNS, Database, etc.). */ -#define GNUNET_CONSTANTS_SERVICE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 10) +#define GNUNET_CONSTANTS_SERVICE_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10) /** * How long do we delay messages to get larger packet sizes (CORKing)? */ -#define GNUNET_CONSTANTS_MAX_CORK_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1) +#define GNUNET_CONSTANTS_MAX_CORK_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1) /** * After what amount of latency for a message do we print a warning? */ -#define GNUNET_CONSTANTS_LATENCY_WARN GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3) +#define GNUNET_CONSTANTS_LATENCY_WARN GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 3) /** * Until which load do we consider the peer overly idle @@ -100,20 +100,20 @@ extern "C" * validated? This value is also used for our own addresses when we * create a HELLO. */ -#define GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12) +#define GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_HOURS, 12) /** * How long do we cache records at most in the DHT? */ -#define GNUNET_CONSTANTS_DHT_MAX_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 24) +#define GNUNET_CONSTANTS_DHT_MAX_EXPIRATION GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_HOURS, 24) /** * Size of the `struct EncryptedMessage` of the core (which * is the per-message overhead of the core). */ -#define GNUNET_CONSTANTS_CORE_SIZE_ENCRYPTED_MESSAGE (24 + sizeof (struct GNUNET_HashCode)) +#define GNUNET_CONSTANTS_CORE_SIZE_ENCRYPTED_MESSAGE (24 + sizeof(struct GNUNET_HashCode)) /** * What is the maximum size for encrypted messages? Note that this @@ -141,7 +141,7 @@ extern "C" * Maximum message size that can be sent on CADET. */ #define GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE \ -(GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE - GNUNET_CONSTANTS_CADET_P2P_OVERHEAD) + (GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE - GNUNET_CONSTANTS_CADET_P2P_OVERHEAD) /** * Largest block that can be stored in the DHT. diff --git a/src/include/gnunet_container_lib.h b/src/include/gnunet_container_lib.h index 8796fdcb6..d811995ff 100644 --- a/src/include/gnunet_container_lib.h +++ b/src/include/gnunet_container_lib.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -67,10 +67,10 @@ * #GNUNET_NO if compression did not help */ int -GNUNET_try_compression (const char *data, - size_t old_size, - char **result, - size_t *new_size); +GNUNET_try_compression(const char *data, + size_t old_size, + char **result, + size_t *new_size); /** @@ -84,7 +84,7 @@ GNUNET_try_compression (const char *data, * @return NULL on error, buffer of @a output_size decompressed bytes otherwise */ char * -GNUNET_decompress (const char *input, size_t input_size, size_t output_size); +GNUNET_decompress(const char *input, size_t input_size, size_t output_size); #if HAVE_EXTRACTOR_H @@ -99,8 +99,7 @@ GNUNET_decompress (const char *input, size_t input_size, size_t output_size); * Enumeration defining various sources of keywords. See also * http://dublincore.org/documents/1998/09/dces/ */ -enum EXTRACTOR_MetaType -{ +enum EXTRACTOR_MetaType { EXTRACTOR_METATYPE_RESERVED = 0, EXTRACTOR_METATYPE_MIMETYPE = 1, EXTRACTOR_METATYPE_FILENAME = 2, @@ -124,14 +123,12 @@ enum EXTRACTOR_MetaType EXTRACTOR_METATYPE_ORIGINAL_TITLE = 162, EXTRACTOR_METATYPE_GNUNET_FULL_DATA = 174, EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME = 180, - }; /** * Format in which the extracted meta data is presented. */ -enum EXTRACTOR_MetaFormat -{ +enum EXTRACTOR_MetaFormat { /** * Format is unknown. */ @@ -231,9 +228,9 @@ typedef int (*GNUNET_CONTAINER_HashCodeIterator) (void *cls, * @return the bloomfilter */ struct GNUNET_CONTAINER_BloomFilter * -GNUNET_CONTAINER_bloomfilter_load (const char *filename, - size_t size, - unsigned int k); +GNUNET_CONTAINER_bloomfilter_load(const char *filename, + size_t size, + unsigned int k); /** @@ -251,9 +248,9 @@ GNUNET_CONTAINER_bloomfilter_load (const char *filename, * @return the bloomfilter */ struct GNUNET_CONTAINER_BloomFilter * -GNUNET_CONTAINER_bloomfilter_init (const char *data, - size_t size, - unsigned int k); +GNUNET_CONTAINER_bloomfilter_init(const char *data, + size_t size, + unsigned int k); /** @@ -266,7 +263,7 @@ GNUNET_CONTAINER_bloomfilter_init (const char *data, * @return #GNUNET_SYSERR if the data array of the wrong size */ int -GNUNET_CONTAINER_bloomfilter_get_raw_data ( +GNUNET_CONTAINER_bloomfilter_get_raw_data( const struct GNUNET_CONTAINER_BloomFilter *bf, char *data, size_t size); @@ -281,7 +278,7 @@ GNUNET_CONTAINER_bloomfilter_get_raw_data ( * @return #GNUNET_YES if the element is in the filter, #GNUNET_NO if not */ int -GNUNET_CONTAINER_bloomfilter_test ( +GNUNET_CONTAINER_bloomfilter_test( const struct GNUNET_CONTAINER_BloomFilter *bf, const struct GNUNET_HashCode *e); @@ -294,8 +291,8 @@ GNUNET_CONTAINER_bloomfilter_test ( * @param e the element */ void -GNUNET_CONTAINER_bloomfilter_add (struct GNUNET_CONTAINER_BloomFilter *bf, - const struct GNUNET_HashCode *e); +GNUNET_CONTAINER_bloomfilter_add(struct GNUNET_CONTAINER_BloomFilter *bf, + const struct GNUNET_HashCode *e); /** @@ -306,8 +303,8 @@ GNUNET_CONTAINER_bloomfilter_add (struct GNUNET_CONTAINER_BloomFilter *bf, * @param e the element to remove */ void -GNUNET_CONTAINER_bloomfilter_remove (struct GNUNET_CONTAINER_BloomFilter *bf, - const struct GNUNET_HashCode *e); +GNUNET_CONTAINER_bloomfilter_remove(struct GNUNET_CONTAINER_BloomFilter *bf, + const struct GNUNET_HashCode *e); /** @@ -318,7 +315,7 @@ GNUNET_CONTAINER_bloomfilter_remove (struct GNUNET_CONTAINER_BloomFilter *bf, * @return copy of bf */ struct GNUNET_CONTAINER_BloomFilter * -GNUNET_CONTAINER_bloomfilter_copy ( +GNUNET_CONTAINER_bloomfilter_copy( const struct GNUNET_CONTAINER_BloomFilter *bf); @@ -331,7 +328,7 @@ GNUNET_CONTAINER_bloomfilter_copy ( * @param bf the filter */ void -GNUNET_CONTAINER_bloomfilter_free (struct GNUNET_CONTAINER_BloomFilter *bf); +GNUNET_CONTAINER_bloomfilter_free(struct GNUNET_CONTAINER_BloomFilter *bf); /** @@ -341,7 +338,7 @@ GNUNET_CONTAINER_bloomfilter_free (struct GNUNET_CONTAINER_BloomFilter *bf); * @return addresses set per element in the bf */ size_t -GNUNET_CONTAINER_bloomfilter_get_element_addresses ( +GNUNET_CONTAINER_bloomfilter_get_element_addresses( const struct GNUNET_CONTAINER_BloomFilter *bf); @@ -353,7 +350,7 @@ GNUNET_CONTAINER_bloomfilter_get_element_addresses ( * @return number of bytes used for the data of the bloom filter */ size_t -GNUNET_CONTAINER_bloomfilter_get_size ( +GNUNET_CONTAINER_bloomfilter_get_size( const struct GNUNET_CONTAINER_BloomFilter *bf); @@ -364,7 +361,7 @@ GNUNET_CONTAINER_bloomfilter_get_size ( * @param bf the filter */ void -GNUNET_CONTAINER_bloomfilter_clear (struct GNUNET_CONTAINER_BloomFilter *bf); +GNUNET_CONTAINER_bloomfilter_clear(struct GNUNET_CONTAINER_BloomFilter *bf); /** @@ -380,9 +377,9 @@ GNUNET_CONTAINER_bloomfilter_clear (struct GNUNET_CONTAINER_BloomFilter *bf); * @return #GNUNET_OK on success */ int -GNUNET_CONTAINER_bloomfilter_or (struct GNUNET_CONTAINER_BloomFilter *bf, - const char *data, - size_t size); +GNUNET_CONTAINER_bloomfilter_or(struct GNUNET_CONTAINER_BloomFilter *bf, + const char *data, + size_t size); /** @@ -396,7 +393,7 @@ GNUNET_CONTAINER_bloomfilter_or (struct GNUNET_CONTAINER_BloomFilter *bf, * @return #GNUNET_OK on success */ int -GNUNET_CONTAINER_bloomfilter_or2 ( +GNUNET_CONTAINER_bloomfilter_or2( struct GNUNET_CONTAINER_BloomFilter *bf, const struct GNUNET_CONTAINER_BloomFilter *to_or); @@ -414,11 +411,11 @@ GNUNET_CONTAINER_bloomfilter_or2 ( * @param k the new number of #GNUNET_CRYPTO_hash-function to apply per element */ void -GNUNET_CONTAINER_bloomfilter_resize (struct GNUNET_CONTAINER_BloomFilter *bf, - GNUNET_CONTAINER_HashCodeIterator iterator, - void *iterator_cls, - size_t size, - unsigned int k); +GNUNET_CONTAINER_bloomfilter_resize(struct GNUNET_CONTAINER_BloomFilter *bf, + GNUNET_CONTAINER_HashCodeIterator iterator, + void *iterator_cls, + size_t size, + unsigned int k); /* ****************** metadata ******************* */ @@ -437,7 +434,7 @@ struct GNUNET_CONTAINER_MetaData; * @return empty meta-data container */ struct GNUNET_CONTAINER_MetaData * -GNUNET_CONTAINER_meta_data_create (void); +GNUNET_CONTAINER_meta_data_create(void); /** @@ -448,7 +445,7 @@ GNUNET_CONTAINER_meta_data_create (void); * @return duplicate meta-data container */ struct GNUNET_CONTAINER_MetaData * -GNUNET_CONTAINER_meta_data_duplicate ( +GNUNET_CONTAINER_meta_data_duplicate( const struct GNUNET_CONTAINER_MetaData *md); @@ -459,7 +456,7 @@ GNUNET_CONTAINER_meta_data_duplicate ( * @param md what to free */ void -GNUNET_CONTAINER_meta_data_destroy (struct GNUNET_CONTAINER_MetaData *md); +GNUNET_CONTAINER_meta_data_destroy(struct GNUNET_CONTAINER_MetaData *md); /** @@ -474,7 +471,7 @@ GNUNET_CONTAINER_meta_data_destroy (struct GNUNET_CONTAINER_MetaData *md); * @return #GNUNET_YES if they are equal */ int -GNUNET_CONTAINER_meta_data_test_equal ( +GNUNET_CONTAINER_meta_data_test_equal( const struct GNUNET_CONTAINER_MetaData *md1, const struct GNUNET_CONTAINER_MetaData *md2); @@ -498,13 +495,13 @@ GNUNET_CONTAINER_meta_data_test_equal ( * data_mime_type and plugin_name are not considered for "exists" checks */ int -GNUNET_CONTAINER_meta_data_insert (struct GNUNET_CONTAINER_MetaData *md, - const char *plugin_name, - enum EXTRACTOR_MetaType type, - enum EXTRACTOR_MetaFormat format, - const char *data_mime_type, - const char *data, - size_t data_size); +GNUNET_CONTAINER_meta_data_insert(struct GNUNET_CONTAINER_MetaData *md, + const char *plugin_name, + enum EXTRACTOR_MetaType type, + enum EXTRACTOR_MetaFormat format, + const char *data_mime_type, + const char *data, + size_t data_size); /** @@ -516,8 +513,8 @@ GNUNET_CONTAINER_meta_data_insert (struct GNUNET_CONTAINER_MetaData *md, * @param in metadata to merge */ void -GNUNET_CONTAINER_meta_data_merge (struct GNUNET_CONTAINER_MetaData *md, - const struct GNUNET_CONTAINER_MetaData *in); +GNUNET_CONTAINER_meta_data_merge(struct GNUNET_CONTAINER_MetaData *md, + const struct GNUNET_CONTAINER_MetaData *in); /** @@ -532,10 +529,10 @@ GNUNET_CONTAINER_meta_data_merge (struct GNUNET_CONTAINER_MetaData *md, * @return #GNUNET_OK on success, #GNUNET_SYSERR if the item does not exist in md */ int -GNUNET_CONTAINER_meta_data_delete (struct GNUNET_CONTAINER_MetaData *md, - enum EXTRACTOR_MetaType type, - const char *data, - size_t data_size); +GNUNET_CONTAINER_meta_data_delete(struct GNUNET_CONTAINER_MetaData *md, + enum EXTRACTOR_MetaType type, + const char *data, + size_t data_size); /** @@ -545,7 +542,7 @@ GNUNET_CONTAINER_meta_data_delete (struct GNUNET_CONTAINER_MetaData *md, * @param md metadata to manipulate */ void -GNUNET_CONTAINER_meta_data_clear (struct GNUNET_CONTAINER_MetaData *md); +GNUNET_CONTAINER_meta_data_clear(struct GNUNET_CONTAINER_MetaData *md); /** @@ -556,7 +553,7 @@ GNUNET_CONTAINER_meta_data_clear (struct GNUNET_CONTAINER_MetaData *md); * @param md metadata to modify */ void -GNUNET_CONTAINER_meta_data_add_publication_date ( +GNUNET_CONTAINER_meta_data_add_publication_date( struct GNUNET_CONTAINER_MetaData *md); @@ -571,9 +568,9 @@ GNUNET_CONTAINER_meta_data_add_publication_date ( * @return number of entries */ int -GNUNET_CONTAINER_meta_data_iterate (const struct GNUNET_CONTAINER_MetaData *md, - EXTRACTOR_MetaDataProcessor iter, - void *iter_cls); +GNUNET_CONTAINER_meta_data_iterate(const struct GNUNET_CONTAINER_MetaData *md, + EXTRACTOR_MetaDataProcessor iter, + void *iter_cls); /** @@ -588,7 +585,7 @@ GNUNET_CONTAINER_meta_data_iterate (const struct GNUNET_CONTAINER_MetaData *md, * @return NULL if no entry was found */ char * -GNUNET_CONTAINER_meta_data_get_by_type ( +GNUNET_CONTAINER_meta_data_get_by_type( const struct GNUNET_CONTAINER_MetaData *md, enum EXTRACTOR_MetaType type); @@ -606,7 +603,7 @@ GNUNET_CONTAINER_meta_data_get_by_type ( * otherwise client is responsible for freeing the value! */ char * -GNUNET_CONTAINER_meta_data_get_first_by_types ( +GNUNET_CONTAINER_meta_data_get_first_by_types( const struct GNUNET_CONTAINER_MetaData *md, ...); @@ -621,7 +618,7 @@ GNUNET_CONTAINER_meta_data_get_first_by_types ( * @return number of bytes in thumbnail, 0 if not available */ size_t -GNUNET_CONTAINER_meta_data_get_thumbnail ( +GNUNET_CONTAINER_meta_data_get_thumbnail( const struct GNUNET_CONTAINER_MetaData *md, unsigned char **thumb); @@ -630,8 +627,7 @@ GNUNET_CONTAINER_meta_data_get_thumbnail ( * @ingroup metadata * Options for metadata serialization. */ -enum GNUNET_CONTAINER_MetaDataSerializationOptions -{ +enum GNUNET_CONTAINER_MetaDataSerializationOptions { /** * @ingroup metadata * Serialize all of the data. @@ -669,7 +665,7 @@ enum GNUNET_CONTAINER_MetaDataSerializationOptions * space) */ ssize_t -GNUNET_CONTAINER_meta_data_serialize ( +GNUNET_CONTAINER_meta_data_serialize( const struct GNUNET_CONTAINER_MetaData *md, char **target, size_t max, @@ -684,7 +680,7 @@ GNUNET_CONTAINER_meta_data_serialize ( * @return number of bytes needed for serialization, -1 on error */ ssize_t -GNUNET_CONTAINER_meta_data_get_serialized_size ( +GNUNET_CONTAINER_meta_data_get_serialized_size( const struct GNUNET_CONTAINER_MetaData *md); @@ -698,7 +694,7 @@ GNUNET_CONTAINER_meta_data_get_serialized_size ( * bad format) */ struct GNUNET_CONTAINER_MetaData * -GNUNET_CONTAINER_meta_data_deserialize (const char *input, size_t size); +GNUNET_CONTAINER_meta_data_deserialize(const char *input, size_t size); /* ******************************* HashMap **************************** */ @@ -720,9 +716,7 @@ struct GNUNET_CONTAINER_MultiHashMapIterator; * @ingroup hashmap * Options for storing values in the HashMap. */ -enum GNUNET_CONTAINER_MultiHashMapOption -{ - +enum GNUNET_CONTAINER_MultiHashMapOption { /** * @ingroup hashmap * If a value with the given key exists, replace it. Note that the @@ -791,7 +785,7 @@ typedef int (*GNUNET_CONTAINER_MulitHashMapIteratorCallback) ( * @return NULL on error */ struct GNUNET_CONTAINER_MultiHashMap * -GNUNET_CONTAINER_multihashmap_create (unsigned int len, int do_not_copy_keys); +GNUNET_CONTAINER_multihashmap_create(unsigned int len, int do_not_copy_keys); /** @@ -802,7 +796,7 @@ GNUNET_CONTAINER_multihashmap_create (unsigned int len, int do_not_copy_keys); * @param map the map */ void -GNUNET_CONTAINER_multihashmap_destroy ( +GNUNET_CONTAINER_multihashmap_destroy( struct GNUNET_CONTAINER_MultiHashMap *map); @@ -818,7 +812,7 @@ GNUNET_CONTAINER_multihashmap_destroy ( * key-value pairs with value NULL */ void * -GNUNET_CONTAINER_multihashmap_get ( +GNUNET_CONTAINER_multihashmap_get( const struct GNUNET_CONTAINER_MultiHashMap *map, const struct GNUNET_HashCode *key); @@ -836,9 +830,9 @@ GNUNET_CONTAINER_multihashmap_get ( * is not in the map */ int -GNUNET_CONTAINER_multihashmap_remove (struct GNUNET_CONTAINER_MultiHashMap *map, - const struct GNUNET_HashCode *key, - const void *value); +GNUNET_CONTAINER_multihashmap_remove(struct GNUNET_CONTAINER_MultiHashMap *map, + const struct GNUNET_HashCode *key, + const void *value); /** * @ingroup hashmap @@ -850,7 +844,7 @@ GNUNET_CONTAINER_multihashmap_remove (struct GNUNET_CONTAINER_MultiHashMap *map, * @return number of values removed */ int -GNUNET_CONTAINER_multihashmap_remove_all ( +GNUNET_CONTAINER_multihashmap_remove_all( struct GNUNET_CONTAINER_MultiHashMap *map, const struct GNUNET_HashCode *key); @@ -864,7 +858,7 @@ GNUNET_CONTAINER_multihashmap_remove_all ( * @return number of values removed */ unsigned int -GNUNET_CONTAINER_multihashmap_clear (struct GNUNET_CONTAINER_MultiHashMap *map); +GNUNET_CONTAINER_multihashmap_clear(struct GNUNET_CONTAINER_MultiHashMap *map); /** @@ -878,7 +872,7 @@ GNUNET_CONTAINER_multihashmap_clear (struct GNUNET_CONTAINER_MultiHashMap *map); * #GNUNET_NO if not */ int -GNUNET_CONTAINER_multihashmap_contains ( +GNUNET_CONTAINER_multihashmap_contains( const struct GNUNET_CONTAINER_MultiHashMap *map, const struct GNUNET_HashCode *key); @@ -895,7 +889,7 @@ GNUNET_CONTAINER_multihashmap_contains ( * #GNUNET_NO if not */ int -GNUNET_CONTAINER_multihashmap_contains_value ( +GNUNET_CONTAINER_multihashmap_contains_value( const struct GNUNET_CONTAINER_MultiHashMap *map, const struct GNUNET_HashCode *key, const void *value); @@ -915,7 +909,7 @@ GNUNET_CONTAINER_multihashmap_contains_value ( * value already exists */ int -GNUNET_CONTAINER_multihashmap_put ( +GNUNET_CONTAINER_multihashmap_put( struct GNUNET_CONTAINER_MultiHashMap *map, const struct GNUNET_HashCode *key, void *value, @@ -929,7 +923,7 @@ GNUNET_CONTAINER_multihashmap_put ( * @return the number of key value pairs */ unsigned int -GNUNET_CONTAINER_multihashmap_size ( +GNUNET_CONTAINER_multihashmap_size( const struct GNUNET_CONTAINER_MultiHashMap *map); @@ -944,7 +938,7 @@ GNUNET_CONTAINER_multihashmap_size ( * #GNUNET_SYSERR if it aborted iteration */ int -GNUNET_CONTAINER_multihashmap_iterate ( +GNUNET_CONTAINER_multihashmap_iterate( struct GNUNET_CONTAINER_MultiHashMap *map, GNUNET_CONTAINER_MulitHashMapIteratorCallback it, void *it_cls); @@ -964,7 +958,7 @@ GNUNET_CONTAINER_multihashmap_iterate ( * @return an iterator over the given multihashmap @a map */ struct GNUNET_CONTAINER_MultiHashMapIterator * -GNUNET_CONTAINER_multihashmap_iterator_create ( +GNUNET_CONTAINER_multihashmap_iterator_create( const struct GNUNET_CONTAINER_MultiHashMap *map); @@ -984,7 +978,7 @@ GNUNET_CONTAINER_multihashmap_iterator_create ( * #GNUNET_NO if we are out of elements */ int -GNUNET_CONTAINER_multihashmap_iterator_next ( +GNUNET_CONTAINER_multihashmap_iterator_next( struct GNUNET_CONTAINER_MultiHashMapIterator *iter, struct GNUNET_HashCode *key, const void **value); @@ -997,7 +991,7 @@ GNUNET_CONTAINER_multihashmap_iterator_next ( * @param iter the iterator to destroy */ void -GNUNET_CONTAINER_multihashmap_iterator_destroy ( +GNUNET_CONTAINER_multihashmap_iterator_destroy( struct GNUNET_CONTAINER_MultiHashMapIterator *iter); @@ -1013,7 +1007,7 @@ GNUNET_CONTAINER_multihashmap_iterator_destroy ( * #GNUNET_SYSERR if it aborted iteration */ int -GNUNET_CONTAINER_multihashmap_get_multiple ( +GNUNET_CONTAINER_multihashmap_get_multiple( struct GNUNET_CONTAINER_MultiHashMap *map, const struct GNUNET_HashCode *key, GNUNET_CONTAINER_MulitHashMapIteratorCallback it, @@ -1032,7 +1026,7 @@ GNUNET_CONTAINER_multihashmap_get_multiple ( * @return the number of key value pairs processed, zero or one. */ unsigned int -GNUNET_CONTAINER_multihashmap_get_random ( +GNUNET_CONTAINER_multihashmap_get_random( const struct GNUNET_CONTAINER_MultiHashMap *map, GNUNET_CONTAINER_MulitHashMapIteratorCallback it, void *it_cls); @@ -1080,7 +1074,7 @@ struct GNUNET_CONTAINER_MultiPeerMap; * @return NULL on error */ struct GNUNET_CONTAINER_MultiPeerMap * -GNUNET_CONTAINER_multipeermap_create (unsigned int len, int do_not_copy_keys); +GNUNET_CONTAINER_multipeermap_create(unsigned int len, int do_not_copy_keys); /** @@ -1091,7 +1085,7 @@ GNUNET_CONTAINER_multipeermap_create (unsigned int len, int do_not_copy_keys); * @param map the map */ void -GNUNET_CONTAINER_multipeermap_destroy ( +GNUNET_CONTAINER_multipeermap_destroy( struct GNUNET_CONTAINER_MultiPeerMap *map); @@ -1107,7 +1101,7 @@ GNUNET_CONTAINER_multipeermap_destroy ( * key-value pairs with value NULL */ void * -GNUNET_CONTAINER_multipeermap_get ( +GNUNET_CONTAINER_multipeermap_get( const struct GNUNET_CONTAINER_MultiPeerMap *map, const struct GNUNET_PeerIdentity *key); @@ -1125,9 +1119,9 @@ GNUNET_CONTAINER_multipeermap_get ( * is not in the map */ int -GNUNET_CONTAINER_multipeermap_remove (struct GNUNET_CONTAINER_MultiPeerMap *map, - const struct GNUNET_PeerIdentity *key, - const void *value); +GNUNET_CONTAINER_multipeermap_remove(struct GNUNET_CONTAINER_MultiPeerMap *map, + const struct GNUNET_PeerIdentity *key, + const void *value); /** * @ingroup hashmap @@ -1139,7 +1133,7 @@ GNUNET_CONTAINER_multipeermap_remove (struct GNUNET_CONTAINER_MultiPeerMap *map, * @return number of values removed */ int -GNUNET_CONTAINER_multipeermap_remove_all ( +GNUNET_CONTAINER_multipeermap_remove_all( struct GNUNET_CONTAINER_MultiPeerMap *map, const struct GNUNET_PeerIdentity *key); @@ -1155,7 +1149,7 @@ GNUNET_CONTAINER_multipeermap_remove_all ( * #GNUNET_NO if not */ int -GNUNET_CONTAINER_multipeermap_contains ( +GNUNET_CONTAINER_multipeermap_contains( const struct GNUNET_CONTAINER_MultiPeerMap *map, const struct GNUNET_PeerIdentity *key); @@ -1172,7 +1166,7 @@ GNUNET_CONTAINER_multipeermap_contains ( * #GNUNET_NO if not */ int -GNUNET_CONTAINER_multipeermap_contains_value ( +GNUNET_CONTAINER_multipeermap_contains_value( const struct GNUNET_CONTAINER_MultiPeerMap *map, const struct GNUNET_PeerIdentity *key, const void *value); @@ -1192,7 +1186,7 @@ GNUNET_CONTAINER_multipeermap_contains_value ( * value already exists */ int -GNUNET_CONTAINER_multipeermap_put ( +GNUNET_CONTAINER_multipeermap_put( struct GNUNET_CONTAINER_MultiPeerMap *map, const struct GNUNET_PeerIdentity *key, void *value, @@ -1207,7 +1201,7 @@ GNUNET_CONTAINER_multipeermap_put ( * @return the number of key value pairs */ unsigned int -GNUNET_CONTAINER_multipeermap_size ( +GNUNET_CONTAINER_multipeermap_size( const struct GNUNET_CONTAINER_MultiPeerMap *map); @@ -1222,7 +1216,7 @@ GNUNET_CONTAINER_multipeermap_size ( * #GNUNET_SYSERR if it aborted iteration */ int -GNUNET_CONTAINER_multipeermap_iterate ( +GNUNET_CONTAINER_multipeermap_iterate( struct GNUNET_CONTAINER_MultiPeerMap *map, GNUNET_CONTAINER_PeerMapIterator it, void *it_cls); @@ -1243,7 +1237,7 @@ struct GNUNET_CONTAINER_MultiPeerMapIterator; * @return an iterator over the given multihashmap @a map */ struct GNUNET_CONTAINER_MultiPeerMapIterator * -GNUNET_CONTAINER_multipeermap_iterator_create ( +GNUNET_CONTAINER_multipeermap_iterator_create( const struct GNUNET_CONTAINER_MultiPeerMap *map); @@ -1263,7 +1257,7 @@ GNUNET_CONTAINER_multipeermap_iterator_create ( * #GNUNET_NO if we are out of elements */ int -GNUNET_CONTAINER_multipeermap_iterator_next ( +GNUNET_CONTAINER_multipeermap_iterator_next( struct GNUNET_CONTAINER_MultiPeerMapIterator *iter, struct GNUNET_PeerIdentity *key, const void **value); @@ -1276,7 +1270,7 @@ GNUNET_CONTAINER_multipeermap_iterator_next ( * @param iter the iterator to destroy */ void -GNUNET_CONTAINER_multipeermap_iterator_destroy ( +GNUNET_CONTAINER_multipeermap_iterator_destroy( struct GNUNET_CONTAINER_MultiPeerMapIterator *iter); @@ -1292,7 +1286,7 @@ GNUNET_CONTAINER_multipeermap_iterator_destroy ( * #GNUNET_SYSERR if it aborted iteration */ int -GNUNET_CONTAINER_multipeermap_get_multiple ( +GNUNET_CONTAINER_multipeermap_get_multiple( struct GNUNET_CONTAINER_MultiPeerMap *map, const struct GNUNET_PeerIdentity *key, GNUNET_CONTAINER_PeerMapIterator it, @@ -1311,7 +1305,7 @@ GNUNET_CONTAINER_multipeermap_get_multiple ( * @return the number of key value pairs processed, zero or one. */ unsigned int -GNUNET_CONTAINER_multipeermap_get_random ( +GNUNET_CONTAINER_multipeermap_get_random( const struct GNUNET_CONTAINER_MultiPeerMap *map, GNUNET_CONTAINER_PeerMapIterator it, void *it_cls); @@ -1359,7 +1353,7 @@ struct GNUNET_CONTAINER_MultiShortmap; * @return NULL on error */ struct GNUNET_CONTAINER_MultiShortmap * -GNUNET_CONTAINER_multishortmap_create (unsigned int len, int do_not_copy_keys); +GNUNET_CONTAINER_multishortmap_create(unsigned int len, int do_not_copy_keys); /** @@ -1370,7 +1364,7 @@ GNUNET_CONTAINER_multishortmap_create (unsigned int len, int do_not_copy_keys); * @param map the map */ void -GNUNET_CONTAINER_multishortmap_destroy ( +GNUNET_CONTAINER_multishortmap_destroy( struct GNUNET_CONTAINER_MultiShortmap *map); @@ -1386,7 +1380,7 @@ GNUNET_CONTAINER_multishortmap_destroy ( * key-value pairs with value NULL */ void * -GNUNET_CONTAINER_multishortmap_get ( +GNUNET_CONTAINER_multishortmap_get( const struct GNUNET_CONTAINER_MultiShortmap *map, const struct GNUNET_ShortHashCode *key); @@ -1404,7 +1398,7 @@ GNUNET_CONTAINER_multishortmap_get ( * is not in the map */ int -GNUNET_CONTAINER_multishortmap_remove ( +GNUNET_CONTAINER_multishortmap_remove( struct GNUNET_CONTAINER_MultiShortmap *map, const struct GNUNET_ShortHashCode *key, const void *value); @@ -1419,7 +1413,7 @@ GNUNET_CONTAINER_multishortmap_remove ( * @return number of values removed */ int -GNUNET_CONTAINER_multishortmap_remove_all ( +GNUNET_CONTAINER_multishortmap_remove_all( struct GNUNET_CONTAINER_MultiShortmap *map, const struct GNUNET_ShortHashCode *key); @@ -1435,7 +1429,7 @@ GNUNET_CONTAINER_multishortmap_remove_all ( * #GNUNET_NO if not */ int -GNUNET_CONTAINER_multishortmap_contains ( +GNUNET_CONTAINER_multishortmap_contains( const struct GNUNET_CONTAINER_MultiShortmap *map, const struct GNUNET_ShortHashCode *key); @@ -1452,7 +1446,7 @@ GNUNET_CONTAINER_multishortmap_contains ( * #GNUNET_NO if not */ int -GNUNET_CONTAINER_multishortmap_contains_value ( +GNUNET_CONTAINER_multishortmap_contains_value( const struct GNUNET_CONTAINER_MultiShortmap *map, const struct GNUNET_ShortHashCode *key, const void *value); @@ -1472,7 +1466,7 @@ GNUNET_CONTAINER_multishortmap_contains_value ( * value already exists */ int -GNUNET_CONTAINER_multishortmap_put ( +GNUNET_CONTAINER_multishortmap_put( struct GNUNET_CONTAINER_MultiShortmap *map, const struct GNUNET_ShortHashCode *key, void *value, @@ -1487,7 +1481,7 @@ GNUNET_CONTAINER_multishortmap_put ( * @return the number of key value pairs */ unsigned int -GNUNET_CONTAINER_multishortmap_size ( +GNUNET_CONTAINER_multishortmap_size( const struct GNUNET_CONTAINER_MultiShortmap *map); @@ -1502,7 +1496,7 @@ GNUNET_CONTAINER_multishortmap_size ( * #GNUNET_SYSERR if it aborted iteration */ int -GNUNET_CONTAINER_multishortmap_iterate ( +GNUNET_CONTAINER_multishortmap_iterate( struct GNUNET_CONTAINER_MultiShortmap *map, GNUNET_CONTAINER_ShortmapIterator it, void *it_cls); @@ -1525,7 +1519,7 @@ struct GNUNET_CONTAINER_MultiShortmapIterator; * @return an iterator over the given multihashmap @a map */ struct GNUNET_CONTAINER_MultiShortmapIterator * -GNUNET_CONTAINER_multishortmap_iterator_create ( +GNUNET_CONTAINER_multishortmap_iterator_create( const struct GNUNET_CONTAINER_MultiShortmap *map); @@ -1545,7 +1539,7 @@ GNUNET_CONTAINER_multishortmap_iterator_create ( * #GNUNET_NO if we are out of elements */ int -GNUNET_CONTAINER_multishortmap_iterator_next ( +GNUNET_CONTAINER_multishortmap_iterator_next( struct GNUNET_CONTAINER_MultiShortmapIterator *iter, struct GNUNET_ShortHashCode *key, const void **value); @@ -1558,7 +1552,7 @@ GNUNET_CONTAINER_multishortmap_iterator_next ( * @param iter the iterator to destroy */ void -GNUNET_CONTAINER_multishortmap_iterator_destroy ( +GNUNET_CONTAINER_multishortmap_iterator_destroy( struct GNUNET_CONTAINER_MultiShortmapIterator *iter); @@ -1574,7 +1568,7 @@ GNUNET_CONTAINER_multishortmap_iterator_destroy ( * #GNUNET_SYSERR if it aborted iteration */ int -GNUNET_CONTAINER_multishortmap_get_multiple ( +GNUNET_CONTAINER_multishortmap_get_multiple( struct GNUNET_CONTAINER_MultiShortmap *map, const struct GNUNET_ShortHashCode *key, GNUNET_CONTAINER_ShortmapIterator it, @@ -1593,7 +1587,7 @@ GNUNET_CONTAINER_multishortmap_get_multiple ( * @return the number of key value pairs processed, zero or one. */ unsigned int -GNUNET_CONTAINER_multishortmap_get_random ( +GNUNET_CONTAINER_multishortmap_get_random( const struct GNUNET_CONTAINER_MultiShortmap *map, GNUNET_CONTAINER_ShortmapIterator it, void *it_cls); @@ -1642,7 +1636,7 @@ struct GNUNET_CONTAINER_MultiUuidmap; * @return NULL on error */ struct GNUNET_CONTAINER_MultiUuidmap * -GNUNET_CONTAINER_multiuuidmap_create (unsigned int len, int do_not_copy_keys); +GNUNET_CONTAINER_multiuuidmap_create(unsigned int len, int do_not_copy_keys); /** @@ -1653,7 +1647,7 @@ GNUNET_CONTAINER_multiuuidmap_create (unsigned int len, int do_not_copy_keys); * @param map the map */ void -GNUNET_CONTAINER_multiuuidmap_destroy ( +GNUNET_CONTAINER_multiuuidmap_destroy( struct GNUNET_CONTAINER_MultiUuidmap *map); @@ -1669,7 +1663,7 @@ GNUNET_CONTAINER_multiuuidmap_destroy ( * key-value pairs with value NULL */ void * -GNUNET_CONTAINER_multiuuidmap_get ( +GNUNET_CONTAINER_multiuuidmap_get( const struct GNUNET_CONTAINER_MultiUuidmap *map, const struct GNUNET_Uuid *key); @@ -1687,9 +1681,9 @@ GNUNET_CONTAINER_multiuuidmap_get ( * is not in the map */ int -GNUNET_CONTAINER_multiuuidmap_remove (struct GNUNET_CONTAINER_MultiUuidmap *map, - const struct GNUNET_Uuid *key, - const void *value); +GNUNET_CONTAINER_multiuuidmap_remove(struct GNUNET_CONTAINER_MultiUuidmap *map, + const struct GNUNET_Uuid *key, + const void *value); /** * @ingroup hashmap @@ -1701,7 +1695,7 @@ GNUNET_CONTAINER_multiuuidmap_remove (struct GNUNET_CONTAINER_MultiUuidmap *map, * @return number of values removed */ int -GNUNET_CONTAINER_multiuuidmap_remove_all ( +GNUNET_CONTAINER_multiuuidmap_remove_all( struct GNUNET_CONTAINER_MultiUuidmap *map, const struct GNUNET_Uuid *key); @@ -1717,7 +1711,7 @@ GNUNET_CONTAINER_multiuuidmap_remove_all ( * #GNUNET_NO if not */ int -GNUNET_CONTAINER_multiuuidmap_contains ( +GNUNET_CONTAINER_multiuuidmap_contains( const struct GNUNET_CONTAINER_MultiUuidmap *map, const struct GNUNET_Uuid *key); @@ -1734,7 +1728,7 @@ GNUNET_CONTAINER_multiuuidmap_contains ( * #GNUNET_NO if not */ int -GNUNET_CONTAINER_multiuuidmap_contains_value ( +GNUNET_CONTAINER_multiuuidmap_contains_value( const struct GNUNET_CONTAINER_MultiUuidmap *map, const struct GNUNET_Uuid *key, const void *value); @@ -1754,7 +1748,7 @@ GNUNET_CONTAINER_multiuuidmap_contains_value ( * value already exists */ int -GNUNET_CONTAINER_multiuuidmap_put ( +GNUNET_CONTAINER_multiuuidmap_put( struct GNUNET_CONTAINER_MultiUuidmap *map, const struct GNUNET_Uuid *key, void *value, @@ -1769,7 +1763,7 @@ GNUNET_CONTAINER_multiuuidmap_put ( * @return the number of key value pairs */ unsigned int -GNUNET_CONTAINER_multiuuidmap_size ( +GNUNET_CONTAINER_multiuuidmap_size( const struct GNUNET_CONTAINER_MultiUuidmap *map); @@ -1784,7 +1778,7 @@ GNUNET_CONTAINER_multiuuidmap_size ( * #GNUNET_SYSERR if it aborted iteration */ int -GNUNET_CONTAINER_multiuuidmap_iterate ( +GNUNET_CONTAINER_multiuuidmap_iterate( struct GNUNET_CONTAINER_MultiUuidmap *map, GNUNET_CONTAINER_MultiUuidmapIteratorCallback it, void *it_cls); @@ -1807,7 +1801,7 @@ struct GNUNET_CONTAINER_MultiUuidmapIterator; * @return an iterator over the given multihashmap @a map */ struct GNUNET_CONTAINER_MultiUuidmapIterator * -GNUNET_CONTAINER_multiuuidmap_iterator_create ( +GNUNET_CONTAINER_multiuuidmap_iterator_create( const struct GNUNET_CONTAINER_MultiUuidmap *map); @@ -1827,7 +1821,7 @@ GNUNET_CONTAINER_multiuuidmap_iterator_create ( * #GNUNET_NO if we are out of elements */ int -GNUNET_CONTAINER_multiuuidmap_iterator_next ( +GNUNET_CONTAINER_multiuuidmap_iterator_next( struct GNUNET_CONTAINER_MultiUuidmapIterator *iter, struct GNUNET_Uuid *key, const void **value); @@ -1840,7 +1834,7 @@ GNUNET_CONTAINER_multiuuidmap_iterator_next ( * @param iter the iterator to destroy */ void -GNUNET_CONTAINER_multiuuidmap_iterator_destroy ( +GNUNET_CONTAINER_multiuuidmap_iterator_destroy( struct GNUNET_CONTAINER_MultiUuidmapIterator *iter); @@ -1856,7 +1850,7 @@ GNUNET_CONTAINER_multiuuidmap_iterator_destroy ( * #GNUNET_SYSERR if it aborted iteration */ int -GNUNET_CONTAINER_multiuuidmap_get_multiple ( +GNUNET_CONTAINER_multiuuidmap_get_multiple( struct GNUNET_CONTAINER_MultiUuidmap *map, const struct GNUNET_Uuid *key, GNUNET_CONTAINER_MultiUuidmapIteratorCallback it, @@ -1875,7 +1869,7 @@ GNUNET_CONTAINER_multiuuidmap_get_multiple ( * @return the number of key value pairs processed, zero or one. */ unsigned int -GNUNET_CONTAINER_multiuuidmap_get_random ( +GNUNET_CONTAINER_multiuuidmap_get_random( const struct GNUNET_CONTAINER_MultiUuidmap *map, GNUNET_CONTAINER_MultiUuidmapIteratorCallback it, void *it_cls); @@ -1922,7 +1916,7 @@ typedef int (*GNUNET_CONTAINER_MulitHashMapIterator32Callback) (void *cls, * @return NULL on error */ struct GNUNET_CONTAINER_MultiHashMap32 * -GNUNET_CONTAINER_multihashmap32_create (unsigned int len); +GNUNET_CONTAINER_multihashmap32_create(unsigned int len); /** @@ -1933,7 +1927,7 @@ GNUNET_CONTAINER_multihashmap32_create (unsigned int len); * @param map the map */ void -GNUNET_CONTAINER_multihashmap32_destroy ( +GNUNET_CONTAINER_multihashmap32_destroy( struct GNUNET_CONTAINER_MultiHashMap32 *map); @@ -1945,7 +1939,7 @@ GNUNET_CONTAINER_multihashmap32_destroy ( * @return the number of key value pairs */ unsigned int -GNUNET_CONTAINER_multihashmap32_size ( +GNUNET_CONTAINER_multihashmap32_size( const struct GNUNET_CONTAINER_MultiHashMap32 *map); @@ -1961,7 +1955,7 @@ GNUNET_CONTAINER_multihashmap32_size ( * key-value pairs with value NULL */ void * -GNUNET_CONTAINER_multihashmap32_get ( +GNUNET_CONTAINER_multihashmap32_get( const struct GNUNET_CONTAINER_MultiHashMap32 *map, uint32_t key); @@ -1977,7 +1971,7 @@ GNUNET_CONTAINER_multihashmap32_get ( * #GNUNET_SYSERR if it aborted iteration */ int -GNUNET_CONTAINER_multihashmap32_iterate ( +GNUNET_CONTAINER_multihashmap32_iterate( struct GNUNET_CONTAINER_MultiHashMap32 *map, GNUNET_CONTAINER_MulitHashMapIterator32Callback it, void *it_cls); @@ -1996,7 +1990,7 @@ GNUNET_CONTAINER_multihashmap32_iterate ( * is not in the map */ int -GNUNET_CONTAINER_multihashmap32_remove ( +GNUNET_CONTAINER_multihashmap32_remove( struct GNUNET_CONTAINER_MultiHashMap32 *map, uint32_t key, const void *value); @@ -2012,7 +2006,7 @@ GNUNET_CONTAINER_multihashmap32_remove ( * @return number of values removed */ int -GNUNET_CONTAINER_multihashmap32_remove_all ( +GNUNET_CONTAINER_multihashmap32_remove_all( struct GNUNET_CONTAINER_MultiHashMap32 *map, uint32_t key); @@ -2028,7 +2022,7 @@ GNUNET_CONTAINER_multihashmap32_remove_all ( * #GNUNET_NO if not */ int -GNUNET_CONTAINER_multihashmap32_contains ( +GNUNET_CONTAINER_multihashmap32_contains( const struct GNUNET_CONTAINER_MultiHashMap32 *map, uint32_t key); @@ -2045,7 +2039,7 @@ GNUNET_CONTAINER_multihashmap32_contains ( * #GNUNET_NO if not */ int -GNUNET_CONTAINER_multihashmap32_contains_value ( +GNUNET_CONTAINER_multihashmap32_contains_value( const struct GNUNET_CONTAINER_MultiHashMap32 *map, uint32_t key, const void *value); @@ -2065,7 +2059,7 @@ GNUNET_CONTAINER_multihashmap32_contains_value ( * value already exists */ int -GNUNET_CONTAINER_multihashmap32_put ( +GNUNET_CONTAINER_multihashmap32_put( struct GNUNET_CONTAINER_MultiHashMap32 *map, uint32_t key, void *value, @@ -2084,7 +2078,7 @@ GNUNET_CONTAINER_multihashmap32_put ( * #GNUNET_SYSERR if it aborted iteration */ int -GNUNET_CONTAINER_multihashmap32_get_multiple ( +GNUNET_CONTAINER_multihashmap32_get_multiple( struct GNUNET_CONTAINER_MultiHashMap32 *map, uint32_t key, GNUNET_CONTAINER_MulitHashMapIterator32Callback it, @@ -2104,7 +2098,7 @@ GNUNET_CONTAINER_multihashmap32_get_multiple ( * @return an iterator over the given multihashmap map */ struct GNUNET_CONTAINER_MultiHashMap32Iterator * -GNUNET_CONTAINER_multihashmap32_iterator_create ( +GNUNET_CONTAINER_multihashmap32_iterator_create( const struct GNUNET_CONTAINER_MultiHashMap32 *map); @@ -2123,7 +2117,7 @@ GNUNET_CONTAINER_multihashmap32_iterator_create ( * #GNUNET_NO if we are out of elements */ int -GNUNET_CONTAINER_multihashmap32_iterator_next ( +GNUNET_CONTAINER_multihashmap32_iterator_next( struct GNUNET_CONTAINER_MultiHashMap32Iterator *iter, uint32_t *key, const void **value); @@ -2135,7 +2129,7 @@ GNUNET_CONTAINER_multihashmap32_iterator_next ( * @param iter the iterator to destroy */ void -GNUNET_CONTAINER_multihashmap32_iterator_destroy ( +GNUNET_CONTAINER_multihashmap32_iterator_destroy( struct GNUNET_CONTAINER_MultiHashMapIterator *iter); @@ -2153,17 +2147,17 @@ GNUNET_CONTAINER_multihashmap32_iterator_destroy ( */ #define GNUNET_CONTAINER_DLL_insert(head, tail, element) \ do \ - { \ - GNUNET_assert (((element)->prev == NULL) && ((head) != (element))); \ - GNUNET_assert (((element)->next == NULL) && ((tail) != (element))); \ - (element)->next = (head); \ - (element)->prev = NULL; \ - if ((tail) == NULL) \ + { \ + GNUNET_assert(((element)->prev == NULL) && ((head) != (element))); \ + GNUNET_assert(((element)->next == NULL) && ((tail) != (element))); \ + (element)->next = (head); \ + (element)->prev = NULL; \ + if ((tail) == NULL) \ (tail) = element; \ - else \ - (head)->prev = element; \ - (head) = (element); \ - } while (0) + else \ + (head) ->prev = element; \ + (head) = (element); \ + } while (0) /** @@ -2177,17 +2171,17 @@ GNUNET_CONTAINER_multihashmap32_iterator_destroy ( */ #define GNUNET_CONTAINER_DLL_insert_tail(head, tail, element) \ do \ - { \ - GNUNET_assert (((element)->prev == NULL) && ((head) != (element))); \ - GNUNET_assert (((element)->next == NULL) && ((tail) != (element))); \ - (element)->prev = (tail); \ - (element)->next = NULL; \ - if ((head) == NULL) \ + { \ + GNUNET_assert(((element)->prev == NULL) && ((head) != (element))); \ + GNUNET_assert(((element)->next == NULL) && ((tail) != (element))); \ + (element)->prev = (tail); \ + (element)->next = NULL; \ + if ((head) == NULL) \ (head) = element; \ - else \ - (tail)->next = element; \ - (tail) = (element); \ - } while (0) + else \ + (tail) ->next = element; \ + (tail) = (element); \ + } while (0) /** @@ -2202,25 +2196,25 @@ GNUNET_CONTAINER_multihashmap32_iterator_destroy ( */ #define GNUNET_CONTAINER_DLL_insert_after(head, tail, other, element) \ do \ - { \ - GNUNET_assert (((element)->prev == NULL) && ((head) != (element))); \ - GNUNET_assert (((element)->next == NULL) && ((tail) != (element))); \ - (element)->prev = (other); \ - if (NULL == other) \ - { \ - (element)->next = (head); \ - (head) = (element); \ - } \ - else \ - { \ - (element)->next = (other)->next; \ - (other)->next = (element); \ - } \ - if (NULL == (element)->next) \ + { \ + GNUNET_assert(((element)->prev == NULL) && ((head) != (element))); \ + GNUNET_assert(((element)->next == NULL) && ((tail) != (element))); \ + (element)->prev = (other); \ + if (NULL == other) \ + { \ + (element)->next = (head); \ + (head) = (element); \ + } \ + else \ + { \ + (element)->next = (other)->next; \ + (other)->next = (element); \ + } \ + if (NULL == (element)->next) \ (tail) = (element); \ - else \ - (element)->next->prev = (element); \ - } while (0) + else \ + (element) ->next->prev = (element); \ + } while (0) /** @@ -2235,25 +2229,25 @@ GNUNET_CONTAINER_multihashmap32_iterator_destroy ( */ #define GNUNET_CONTAINER_DLL_insert_before(head, tail, other, element) \ do \ - { \ - GNUNET_assert (((element)->prev == NULL) && ((head) != (element))); \ - GNUNET_assert (((element)->next == NULL) && ((tail) != (element))); \ - (element)->next = (other); \ - if (NULL == other) \ - { \ - (element)->prev = (tail); \ - (tail) = (element); \ - } \ - else \ - { \ - (element)->prev = (other)->prev; \ - (other)->prev = (element); \ - } \ - if (NULL == (element)->prev) \ + { \ + GNUNET_assert(((element)->prev == NULL) && ((head) != (element))); \ + GNUNET_assert(((element)->next == NULL) && ((tail) != (element))); \ + (element)->next = (other); \ + if (NULL == other) \ + { \ + (element)->prev = (tail); \ + (tail) = (element); \ + } \ + else \ + { \ + (element)->prev = (other)->prev; \ + (other)->prev = (element); \ + } \ + if (NULL == (element)->prev) \ (head) = (element); \ - else \ - (element)->prev->next = (element); \ - } while (0) + else \ + (element) ->prev->next = (element); \ + } while (0) /** @@ -2272,20 +2266,20 @@ GNUNET_CONTAINER_multihashmap32_iterator_destroy ( */ #define GNUNET_CONTAINER_DLL_remove(head, tail, element) \ do \ - { \ - GNUNET_assert (((element)->prev != NULL) || ((head) == (element))); \ - GNUNET_assert (((element)->next != NULL) || ((tail) == (element))); \ - if ((element)->prev == NULL) \ + { \ + GNUNET_assert(((element)->prev != NULL) || ((head) == (element))); \ + GNUNET_assert(((element)->next != NULL) || ((tail) == (element))); \ + if ((element)->prev == NULL) \ (head) = (element)->next; \ - else \ - (element)->prev->next = (element)->next; \ - if ((element)->next == NULL) \ + else \ + (element) ->prev->next = (element)->next; \ + if ((element)->next == NULL) \ (tail) = (element)->prev; \ - else \ - (element)->next->prev = (element)->prev; \ - (element)->next = NULL; \ - (element)->prev = NULL; \ - } while (0) + else \ + (element) ->next->prev = (element)->prev; \ + (element)->next = NULL; \ + (element)->prev = NULL; \ + } while (0) /* ************ Multi-DLL interface, allows DLL elements to be @@ -2303,17 +2297,17 @@ GNUNET_CONTAINER_multihashmap32_iterator_destroy ( */ #define GNUNET_CONTAINER_MDLL_insert(mdll, head, tail, element) \ do \ - { \ - GNUNET_assert (((element)->prev_##mdll == NULL) && ((head) != (element))); \ - GNUNET_assert (((element)->next_##mdll == NULL) && ((tail) != (element))); \ - (element)->next_##mdll = (head); \ - (element)->prev_##mdll = NULL; \ - if ((tail) == NULL) \ + { \ + GNUNET_assert(((element)->prev_ ## mdll == NULL) && ((head) != (element))); \ + GNUNET_assert(((element)->next_ ## mdll == NULL) && ((tail) != (element))); \ + (element)->next_ ## mdll = (head); \ + (element)->prev_ ## mdll = NULL; \ + if ((tail) == NULL) \ (tail) = element; \ - else \ - (head)->prev_##mdll = element; \ - (head) = (element); \ - } while (0) + else \ + (head) ->prev_ ## mdll = element; \ + (head) = (element); \ + } while (0) /** @@ -2328,17 +2322,17 @@ GNUNET_CONTAINER_multihashmap32_iterator_destroy ( */ #define GNUNET_CONTAINER_MDLL_insert_tail(mdll, head, tail, element) \ do \ - { \ - GNUNET_assert (((element)->prev_##mdll == NULL) && ((head) != (element))); \ - GNUNET_assert (((element)->next_##mdll == NULL) && ((tail) != (element))); \ - (element)->prev_##mdll = (tail); \ - (element)->next_##mdll = NULL; \ - if ((head) == NULL) \ + { \ + GNUNET_assert(((element)->prev_ ## mdll == NULL) && ((head) != (element))); \ + GNUNET_assert(((element)->next_ ## mdll == NULL) && ((tail) != (element))); \ + (element)->prev_ ## mdll = (tail); \ + (element)->next_ ## mdll = NULL; \ + if ((head) == NULL) \ (head) = element; \ - else \ - (tail)->next_##mdll = element; \ - (tail) = (element); \ - } while (0) + else \ + (tail) ->next_ ## mdll = element; \ + (tail) = (element); \ + } while (0) /** @@ -2354,25 +2348,25 @@ GNUNET_CONTAINER_multihashmap32_iterator_destroy ( */ #define GNUNET_CONTAINER_MDLL_insert_after(mdll, head, tail, other, element) \ do \ - { \ - GNUNET_assert (((element)->prev_##mdll == NULL) && ((head) != (element))); \ - GNUNET_assert (((element)->next_##mdll == NULL) && ((tail) != (element))); \ - (element)->prev_##mdll = (other); \ - if (NULL == other) \ - { \ - (element)->next_##mdll = (head); \ - (head) = (element); \ - } \ - else \ - { \ - (element)->next_##mdll = (other)->next_##mdll; \ - (other)->next_##mdll = (element); \ - } \ - if (NULL == (element)->next_##mdll) \ + { \ + GNUNET_assert(((element)->prev_ ## mdll == NULL) && ((head) != (element))); \ + GNUNET_assert(((element)->next_ ## mdll == NULL) && ((tail) != (element))); \ + (element)->prev_ ## mdll = (other); \ + if (NULL == other) \ + { \ + (element)->next_ ## mdll = (head); \ + (head) = (element); \ + } \ + else \ + { \ + (element)->next_ ## mdll = (other)->next_ ## mdll; \ + (other)->next_ ## mdll = (element); \ + } \ + if (NULL == (element)->next_ ## mdll) \ (tail) = (element); \ - else \ - (element)->next_##mdll->prev_##mdll = (element); \ - } while (0) + else \ + (element) ->next_ ## mdll->prev_ ## mdll = (element); \ + } while (0) /** @@ -2388,25 +2382,25 @@ GNUNET_CONTAINER_multihashmap32_iterator_destroy ( */ #define GNUNET_CONTAINER_MDLL_insert_before(mdll, head, tail, other, element) \ do \ - { \ - GNUNET_assert (((element)->prev_##mdll == NULL) && ((head) != (element))); \ - GNUNET_assert (((element)->next_##mdll == NULL) && ((tail) != (element))); \ - (element)->next_##mdll = (other); \ - if (NULL == other) \ - { \ - (element)->prev = (tail); \ - (tail) = (element); \ - } \ - else \ - { \ - (element)->prev_##mdll = (other)->prev_##mdll; \ - (other)->prev_##mdll = (element); \ - } \ - if (NULL == (element)->prev_##mdll) \ + { \ + GNUNET_assert(((element)->prev_ ## mdll == NULL) && ((head) != (element))); \ + GNUNET_assert(((element)->next_ ## mdll == NULL) && ((tail) != (element))); \ + (element)->next_ ## mdll = (other); \ + if (NULL == other) \ + { \ + (element)->prev = (tail); \ + (tail) = (element); \ + } \ + else \ + { \ + (element)->prev_ ## mdll = (other)->prev_ ## mdll; \ + (other)->prev_ ## mdll = (element); \ + } \ + if (NULL == (element)->prev_ ## mdll) \ (head) = (element); \ - else \ - (element)->prev_##mdll->next_##mdll = (element); \ - } while (0) + else \ + (element) ->prev_ ## mdll->next_ ## mdll = (element); \ + } while (0) /** @@ -2422,20 +2416,20 @@ GNUNET_CONTAINER_multihashmap32_iterator_destroy ( */ #define GNUNET_CONTAINER_MDLL_remove(mdll, head, tail, element) \ do \ - { \ - GNUNET_assert (((element)->prev_##mdll != NULL) || ((head) == (element))); \ - GNUNET_assert (((element)->next_##mdll != NULL) || ((tail) == (element))); \ - if ((element)->prev_##mdll == NULL) \ - (head) = (element)->next_##mdll; \ - else \ - (element)->prev_##mdll->next_##mdll = (element)->next_##mdll; \ - if ((element)->next_##mdll == NULL) \ - (tail) = (element)->prev_##mdll; \ - else \ - (element)->next_##mdll->prev_##mdll = (element)->prev_##mdll; \ - (element)->next_##mdll = NULL; \ - (element)->prev_##mdll = NULL; \ - } while (0) + { \ + GNUNET_assert(((element)->prev_ ## mdll != NULL) || ((head) == (element))); \ + GNUNET_assert(((element)->next_ ## mdll != NULL) || ((tail) == (element))); \ + if ((element)->prev_ ## mdll == NULL) \ + (head) = (element)->next_ ## mdll; \ + else \ + (element) ->prev_ ## mdll->next_ ## mdll = (element)->next_ ## mdll; \ + if ((element)->next_ ## mdll == NULL) \ + (tail) = (element)->prev_ ## mdll; \ + else \ + (element) ->next_ ## mdll->prev_ ## mdll = (element)->prev_ ## mdll; \ + (element)->next_ ## mdll = NULL; \ + (element)->prev_ ## mdll = NULL; \ + } while (0) /** @@ -2458,29 +2452,29 @@ GNUNET_CONTAINER_multihashmap32_iterator_destroy ( tail, \ element) \ do \ - { \ - if ((NULL == head) || (0 < comparator (comparator_cls, element, head))) \ - { \ - /* insert at head, element < head */ \ - GNUNET_CONTAINER_DLL_insert (head, tail, element); \ - } \ - else \ - { \ - TYPE *pos; \ + { \ + if ((NULL == head) || (0 < comparator(comparator_cls, element, head))) \ + { \ + /* insert at head, element < head */ \ + GNUNET_CONTAINER_DLL_insert(head, tail, element); \ + } \ + else \ + { \ + TYPE *pos; \ \ - for (pos = head; NULL != pos; pos = pos->next) \ - if (0 < comparator (comparator_cls, element, pos)) \ + for (pos = head; NULL != pos; pos = pos->next) \ + if (0 < comparator(comparator_cls, element, pos)) \ break; /* element < pos */ \ - if (NULL == pos) /* => element > tail */ \ - { \ - GNUNET_CONTAINER_DLL_insert_tail (head, tail, element); \ - } \ - else /* prev < element < pos */ \ - { \ - GNUNET_CONTAINER_DLL_insert_after (head, tail, pos->prev, element); \ - } \ - } \ - } while (0) + if (NULL == pos) /* => element > tail */ \ + { \ + GNUNET_CONTAINER_DLL_insert_tail(head, tail, element); \ + } \ + else /* prev < element < pos */ \ + { \ + GNUNET_CONTAINER_DLL_insert_after(head, tail, pos->prev, element); \ + } \ + } \ + } while (0) /* ******************** Heap *************** */ @@ -2497,8 +2491,7 @@ typedef uint64_t GNUNET_CONTAINER_HeapCostType; * @ingroup heap * Heap type, either max or min. */ -enum GNUNET_CONTAINER_HeapOrder -{ +enum GNUNET_CONTAINER_HeapOrder { /** * @ingroup heap * Heap with the maximum cost at the root. @@ -2535,7 +2528,7 @@ struct GNUNET_CONTAINER_HeapNode; * @return handle to the heap */ struct GNUNET_CONTAINER_Heap * -GNUNET_CONTAINER_heap_create (enum GNUNET_CONTAINER_HeapOrder order); +GNUNET_CONTAINER_heap_create(enum GNUNET_CONTAINER_HeapOrder order); /** @@ -2546,7 +2539,7 @@ GNUNET_CONTAINER_heap_create (enum GNUNET_CONTAINER_HeapOrder order); * @param heap heap to destroy */ void -GNUNET_CONTAINER_heap_destroy (struct GNUNET_CONTAINER_Heap *heap); +GNUNET_CONTAINER_heap_destroy(struct GNUNET_CONTAINER_Heap *heap); /** @@ -2557,7 +2550,7 @@ GNUNET_CONTAINER_heap_destroy (struct GNUNET_CONTAINER_Heap *heap); * @return Element at the root, or NULL if heap is empty. */ void * -GNUNET_CONTAINER_heap_peek (const struct GNUNET_CONTAINER_Heap *heap); +GNUNET_CONTAINER_heap_peek(const struct GNUNET_CONTAINER_Heap *heap); /** @@ -2570,9 +2563,9 @@ GNUNET_CONTAINER_heap_peek (const struct GNUNET_CONTAINER_Heap *heap); * #GNUNET_NO if the heap is empty. */ int -GNUNET_CONTAINER_heap_peek2 (const struct GNUNET_CONTAINER_Heap *heap, - void **element, - GNUNET_CONTAINER_HeapCostType *cost); +GNUNET_CONTAINER_heap_peek2(const struct GNUNET_CONTAINER_Heap *heap, + void **element, + GNUNET_CONTAINER_HeapCostType *cost); /** @@ -2583,7 +2576,7 @@ GNUNET_CONTAINER_heap_peek2 (const struct GNUNET_CONTAINER_Heap *heap, * @return number of elements stored */ unsigned int -GNUNET_CONTAINER_heap_get_size (const struct GNUNET_CONTAINER_Heap *heap); +GNUNET_CONTAINER_heap_get_size(const struct GNUNET_CONTAINER_Heap *heap); /** @@ -2594,7 +2587,7 @@ GNUNET_CONTAINER_heap_get_size (const struct GNUNET_CONTAINER_Heap *heap); * @return cost of the node */ GNUNET_CONTAINER_HeapCostType -GNUNET_CONTAINER_heap_node_get_cost ( +GNUNET_CONTAINER_heap_node_get_cost( const struct GNUNET_CONTAINER_HeapNode *node); @@ -2625,9 +2618,9 @@ typedef int (*GNUNET_CONTAINER_HeapIterator) ( * @param iterator_cls closure for @a iterator */ void -GNUNET_CONTAINER_heap_iterate (const struct GNUNET_CONTAINER_Heap *heap, - GNUNET_CONTAINER_HeapIterator iterator, - void *iterator_cls); +GNUNET_CONTAINER_heap_iterate(const struct GNUNET_CONTAINER_Heap *heap, + GNUNET_CONTAINER_HeapIterator iterator, + void *iterator_cls); /** * @ingroup heap @@ -2642,7 +2635,7 @@ GNUNET_CONTAINER_heap_iterate (const struct GNUNET_CONTAINER_Heap *heap, * NULL if the tree is empty. */ void * -GNUNET_CONTAINER_heap_walk_get_next (struct GNUNET_CONTAINER_Heap *heap); +GNUNET_CONTAINER_heap_walk_get_next(struct GNUNET_CONTAINER_Heap *heap); /** @@ -2655,9 +2648,9 @@ GNUNET_CONTAINER_heap_walk_get_next (struct GNUNET_CONTAINER_Heap *heap); * @return node for the new element */ struct GNUNET_CONTAINER_HeapNode * -GNUNET_CONTAINER_heap_insert (struct GNUNET_CONTAINER_Heap *heap, - void *element, - GNUNET_CONTAINER_HeapCostType cost); +GNUNET_CONTAINER_heap_insert(struct GNUNET_CONTAINER_Heap *heap, + void *element, + GNUNET_CONTAINER_HeapCostType cost); /** @@ -2668,7 +2661,7 @@ GNUNET_CONTAINER_heap_insert (struct GNUNET_CONTAINER_Heap *heap, * @return element data stored at the root node */ void * -GNUNET_CONTAINER_heap_remove_root (struct GNUNET_CONTAINER_Heap *heap); +GNUNET_CONTAINER_heap_remove_root(struct GNUNET_CONTAINER_Heap *heap); /** @@ -2679,7 +2672,7 @@ GNUNET_CONTAINER_heap_remove_root (struct GNUNET_CONTAINER_Heap *heap); * @return element data stored at the node, NULL if heap is empty */ void * -GNUNET_CONTAINER_heap_remove_node (struct GNUNET_CONTAINER_HeapNode *node); +GNUNET_CONTAINER_heap_remove_node(struct GNUNET_CONTAINER_HeapNode *node); /** @@ -2690,8 +2683,8 @@ GNUNET_CONTAINER_heap_remove_node (struct GNUNET_CONTAINER_HeapNode *node); * @param new_cost new cost for the node */ void -GNUNET_CONTAINER_heap_update_cost (struct GNUNET_CONTAINER_HeapNode *node, - GNUNET_CONTAINER_HeapCostType new_cost); +GNUNET_CONTAINER_heap_update_cost(struct GNUNET_CONTAINER_HeapNode *node, + GNUNET_CONTAINER_HeapCostType new_cost); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_conversation_service.h b/src/include/gnunet_conversation_service.h index 64da5380e..a15e71f0d 100644 --- a/src/include/gnunet_conversation_service.h +++ b/src/include/gnunet_conversation_service.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet - Copyright (C) 2013, 2014, 2016 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet + Copyright (C) 2013, 2014, 2016 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -53,7 +53,7 @@ #ifdef __cplusplus extern "C" { -#if 0 /* keep Emacsens' auto-indent happy */ +#if 0 /* keep Emacsens' auto-indent happy */ } #endif #endif @@ -86,9 +86,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * may also specify the phone line that is used (typically zero). * The version is also right now always zero. */ -struct GNUNET_CONVERSATION_PhoneRecord -{ - +struct GNUNET_CONVERSATION_PhoneRecord { /** * Version of the phone record, for now always one. We may * use other versions for anonymously hosted phone lines in @@ -110,7 +108,6 @@ struct GNUNET_CONVERSATION_PhoneRecord * Phone line (CADET port) to connect to. */ struct GNUNET_HashCode line_port; - }; GNUNET_NETWORK_STRUCT_END @@ -118,8 +115,7 @@ GNUNET_NETWORK_STRUCT_END /** * Information about active callers to a phone. */ -enum GNUNET_CONVERSATION_PhoneEventCode -{ +enum GNUNET_CONVERSATION_PhoneEventCode { /** * We are the callee and the phone is ringing. * We should accept the call or hang up. @@ -131,7 +127,6 @@ enum GNUNET_CONVERSATION_PhoneEventCode * We must no longer use the caller's handle. */ GNUNET_CONVERSATION_EC_PHONE_HUNG_UP - }; @@ -155,9 +150,7 @@ typedef void * progresses from ring over ready to terminated. Steps may * be skipped. */ -enum GNUNET_CONVERSATION_CallerEventCode -{ - +enum GNUNET_CONVERSATION_CallerEventCode { /** * We are the callee and the caller suspended the call. Note that * both sides can independently suspend and resume calls; a call is @@ -171,7 +164,6 @@ enum GNUNET_CONVERSATION_CallerEventCode * only "working" of both sides are active. */ GNUNET_CONVERSATION_EC_CALLER_RESUME - }; @@ -212,10 +204,10 @@ struct GNUNET_CONVERSATION_Phone; * @param event_handler_cls closure for @a event_handler */ struct GNUNET_CONVERSATION_Phone * -GNUNET_CONVERSATION_phone_create (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_IDENTITY_Ego *ego, - GNUNET_CONVERSATION_PhoneEventHandler event_handler, - void *event_handler_cls); +GNUNET_CONVERSATION_phone_create(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_IDENTITY_Ego *ego, + GNUNET_CONVERSATION_PhoneEventHandler event_handler, + void *event_handler_cls); /** @@ -227,8 +219,8 @@ GNUNET_CONVERSATION_phone_create (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param rd namestore record to fill in */ void -GNUNET_CONVERSATION_phone_get_record (struct GNUNET_CONVERSATION_Phone *phone, - struct GNUNET_GNSRECORD_Data *rd); +GNUNET_CONVERSATION_phone_get_record(struct GNUNET_CONVERSATION_Phone *phone, + struct GNUNET_GNSRECORD_Data *rd); /** @@ -242,11 +234,11 @@ GNUNET_CONVERSATION_phone_get_record (struct GNUNET_CONVERSATION_Phone *phone, * @param mic microphone to use */ void -GNUNET_CONVERSATION_caller_pick_up (struct GNUNET_CONVERSATION_Caller *caller, - GNUNET_CONVERSATION_CallerEventHandler event_handler, - void *event_handler_cls, - struct GNUNET_SPEAKER_Handle *speaker, - struct GNUNET_MICROPHONE_Handle *mic); +GNUNET_CONVERSATION_caller_pick_up(struct GNUNET_CONVERSATION_Caller *caller, + GNUNET_CONVERSATION_CallerEventHandler event_handler, + void *event_handler_cls, + struct GNUNET_SPEAKER_Handle *speaker, + struct GNUNET_MICROPHONE_Handle *mic); /** @@ -257,7 +249,7 @@ GNUNET_CONVERSATION_caller_pick_up (struct GNUNET_CONVERSATION_Caller *caller, * @param caller call to suspend */ void -GNUNET_CONVERSATION_caller_suspend (struct GNUNET_CONVERSATION_Caller *caller); +GNUNET_CONVERSATION_caller_suspend(struct GNUNET_CONVERSATION_Caller *caller); /** @@ -268,9 +260,9 @@ GNUNET_CONVERSATION_caller_suspend (struct GNUNET_CONVERSATION_Caller *caller); * @param mic microphone to use */ void -GNUNET_CONVERSATION_caller_resume (struct GNUNET_CONVERSATION_Caller *caller, - struct GNUNET_SPEAKER_Handle *speaker, - struct GNUNET_MICROPHONE_Handle *mic); +GNUNET_CONVERSATION_caller_resume(struct GNUNET_CONVERSATION_Caller *caller, + struct GNUNET_SPEAKER_Handle *speaker, + struct GNUNET_MICROPHONE_Handle *mic); /** @@ -280,7 +272,7 @@ GNUNET_CONVERSATION_caller_resume (struct GNUNET_CONVERSATION_Caller *caller, * @param caller who should we hang up on */ void -GNUNET_CONVERSATION_caller_hang_up (struct GNUNET_CONVERSATION_Caller *caller); +GNUNET_CONVERSATION_caller_hang_up(struct GNUNET_CONVERSATION_Caller *caller); /** @@ -289,7 +281,7 @@ GNUNET_CONVERSATION_caller_hang_up (struct GNUNET_CONVERSATION_Caller *caller); * @param phone phone to destroy */ void -GNUNET_CONVERSATION_phone_destroy (struct GNUNET_CONVERSATION_Phone *phone); +GNUNET_CONVERSATION_phone_destroy(struct GNUNET_CONVERSATION_Phone *phone); /* *********************** CALL API ************************ */ @@ -303,9 +295,7 @@ struct GNUNET_CONVERSATION_Call; /** * Information about the current status of a call. */ -enum GNUNET_CONVERSATION_CallEventCode -{ - +enum GNUNET_CONVERSATION_CallEventCode { /** * We are the caller and are now ringing the other party (GNS lookup * succeeded). @@ -354,7 +344,6 @@ enum GNUNET_CONVERSATION_CallEventCode * is restarted during a call. */ GNUNET_CONVERSATION_EC_CALL_ERROR - }; @@ -385,13 +374,13 @@ typedef void * @return handle for the call */ struct GNUNET_CONVERSATION_Call * -GNUNET_CONVERSATION_call_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_IDENTITY_Ego *caller_id, - const char *callee, - struct GNUNET_SPEAKER_Handle *speaker, - struct GNUNET_MICROPHONE_Handle *mic, - GNUNET_CONVERSATION_CallEventHandler event_handler, - void *event_handler_cls); +GNUNET_CONVERSATION_call_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_IDENTITY_Ego *caller_id, + const char *callee, + struct GNUNET_SPEAKER_Handle *speaker, + struct GNUNET_MICROPHONE_Handle *mic, + GNUNET_CONVERSATION_CallEventHandler event_handler, + void *event_handler_cls); /** @@ -401,7 +390,7 @@ GNUNET_CONVERSATION_call_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param call call to pause */ void -GNUNET_CONVERSATION_call_suspend (struct GNUNET_CONVERSATION_Call *call); +GNUNET_CONVERSATION_call_suspend(struct GNUNET_CONVERSATION_Call *call); /** @@ -412,9 +401,9 @@ GNUNET_CONVERSATION_call_suspend (struct GNUNET_CONVERSATION_Call *call); * @param mic microphone to use */ void -GNUNET_CONVERSATION_call_resume (struct GNUNET_CONVERSATION_Call *call, - struct GNUNET_SPEAKER_Handle *speaker, - struct GNUNET_MICROPHONE_Handle *mic); +GNUNET_CONVERSATION_call_resume(struct GNUNET_CONVERSATION_Call *call, + struct GNUNET_SPEAKER_Handle *speaker, + struct GNUNET_MICROPHONE_Handle *mic); /** @@ -423,10 +412,10 @@ GNUNET_CONVERSATION_call_resume (struct GNUNET_CONVERSATION_Call *call, * @param call call to terminate */ void -GNUNET_CONVERSATION_call_stop (struct GNUNET_CONVERSATION_Call *call); +GNUNET_CONVERSATION_call_stop(struct GNUNET_CONVERSATION_Call *call); -#if 0 /* keep Emacsens' auto-indent happy */ +#if 0 /* keep Emacsens' auto-indent happy */ { #endif #ifdef __cplusplus diff --git a/src/include/gnunet_core_service.h b/src/include/gnunet_core_service.h index 111eb529d..4e6c48ee8 100644 --- a/src/include/gnunet_core_service.h +++ b/src/include/gnunet_core_service.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff * @@ -125,12 +125,12 @@ typedef void (*GNUNET_CORE_StartupCallback) ( * NULL on error (in this case, init is never called) */ struct GNUNET_CORE_Handle * -GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - void *cls, - GNUNET_CORE_StartupCallback init, - GNUNET_CORE_ConnectEventHandler connects, - GNUNET_CORE_DisconnectEventHandler disconnects, - const struct GNUNET_MQ_MessageHandler *handlers); +GNUNET_CORE_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + void *cls, + GNUNET_CORE_StartupCallback init, + GNUNET_CORE_ConnectEventHandler connects, + GNUNET_CORE_DisconnectEventHandler disconnects, + const struct GNUNET_MQ_MessageHandler *handlers); /** @@ -139,7 +139,7 @@ GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param handle connection to core to disconnect */ void -GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle); +GNUNET_CORE_disconnect(struct GNUNET_CORE_Handle *handle); /** @@ -150,8 +150,8 @@ GNUNET_CORE_disconnect (struct GNUNET_CORE_Handle *handle); * @return NULL if @a pid is not connected */ struct GNUNET_MQ_Handle * -GNUNET_CORE_get_mq (const struct GNUNET_CORE_Handle *h, - const struct GNUNET_PeerIdentity *pid); +GNUNET_CORE_get_mq(const struct GNUNET_CORE_Handle *h, + const struct GNUNET_PeerIdentity *pid); /** @@ -173,8 +173,7 @@ struct GNUNET_CORE_MonitorHandle; * #GNUNET_CORE_KX_STATE_REKEY_SENT until the rekey operation is * confirmed by a PONG from the other peer. */ -enum GNUNET_CORE_KxState -{ +enum GNUNET_CORE_KxState { /** * No handshake yet. */ @@ -228,7 +227,6 @@ enum GNUNET_CORE_KxState * crashed and thus all connection state should be assumed lost. */ GNUNET_CORE_KX_CORE_DISCONNECT - }; @@ -265,9 +263,9 @@ typedef void (*GNUNET_CORE_MonitorCallback) ( * @return NULL on error */ struct GNUNET_CORE_MonitorHandle * -GNUNET_CORE_monitor_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_CORE_MonitorCallback peer_cb, - void *peer_cb_cls); +GNUNET_CORE_monitor_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_CORE_MonitorCallback peer_cb, + void *peer_cb_cls); /** @@ -276,7 +274,7 @@ GNUNET_CORE_monitor_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param mh monitor to stop */ void -GNUNET_CORE_monitor_stop (struct GNUNET_CORE_MonitorHandle *mh); +GNUNET_CORE_monitor_stop(struct GNUNET_CORE_MonitorHandle *mh); /** @@ -292,8 +290,8 @@ GNUNET_CORE_monitor_stop (struct GNUNET_CORE_MonitorHandle *mh); * @return #GNUNET_YES if the peer is connected to us; #GNUNET_NO if not */ int -GNUNET_CORE_is_peer_connected_sync (const struct GNUNET_CORE_Handle *h, - const struct GNUNET_PeerIdentity *pid); +GNUNET_CORE_is_peer_connected_sync(const struct GNUNET_CORE_Handle *h, + const struct GNUNET_PeerIdentity *pid); /** @@ -310,8 +308,8 @@ GNUNET_CORE_is_peer_connected_sync (const struct GNUNET_CORE_Handle *h, * to the target peer */ struct GNUNET_MQ_Handle * -GNUNET_CORE_mq_create (struct GNUNET_CORE_Handle *h, - const struct GNUNET_PeerIdentity *target); +GNUNET_CORE_mq_create(struct GNUNET_CORE_Handle *h, + const struct GNUNET_PeerIdentity *target); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_credential_service.h b/src/include/gnunet_credential_service.h index c925b0da8..9e1672ba3 100644 --- a/src/include/gnunet_credential_service.h +++ b/src/include/gnunet_credential_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -56,10 +56,9 @@ struct GNUNET_CREDENTIAL_Handle; struct GNUNET_CREDENTIAL_Request; /* -* Enum used for checking whether the issuer has the authority to issue credentials or is just a subject -*/ + * Enum used for checking whether the issuer has the authority to issue credentials or is just a subject + */ enum GNUNET_CREDENTIAL_CredentialFlags { - //Subject had credentials before, but have been revoked now GNUNET_CREDENTIAL_FLAG_REVOKED=0, @@ -68,7 +67,6 @@ enum GNUNET_CREDENTIAL_CredentialFlags { //Issuer flag is used to signify that the subject is allowed to issue this credential and delegate issuance GNUNET_CREDENTIAL_FLAG_ISSUER=2 - }; GNUNET_NETWORK_STRUCT_BEGIN @@ -76,7 +74,6 @@ GNUNET_NETWORK_STRUCT_BEGIN * The attribute delegation record */ struct GNUNET_CREDENTIAL_DelegationRecord { - /** * Number of delegation sets in this record */ @@ -96,7 +93,6 @@ struct GNUNET_CREDENTIAL_DelegationRecord { * The attribute delegation record */ struct GNUNET_CREDENTIAL_DelegationRecordSet { - /** * Public key of the subject this attribute was delegated to */ @@ -115,7 +111,6 @@ GNUNET_NETWORK_STRUCT_END * The attribute delegation record */ struct GNUNET_CREDENTIAL_DelegationSet { - /** * Public key of the subject this attribute was delegated to */ @@ -134,7 +129,6 @@ struct GNUNET_CREDENTIAL_DelegationSet { * A delegation */ struct GNUNET_CREDENTIAL_Delegation { - /** * The issuer of the delegation */ @@ -171,7 +165,6 @@ struct GNUNET_CREDENTIAL_Delegation { * A credential */ struct GNUNET_CREDENTIAL_Credential { - /** * The issuer of the credential */ @@ -201,7 +194,6 @@ struct GNUNET_CREDENTIAL_Credential { * The attribute */ const char *issuer_attribute; - }; @@ -213,7 +205,7 @@ struct GNUNET_CREDENTIAL_Credential { * @return handle to the Credential service, or NULL on error */ struct GNUNET_CREDENTIAL_Handle * -GNUNET_CREDENTIAL_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_CREDENTIAL_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -222,7 +214,7 @@ GNUNET_CREDENTIAL_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param handle connection to shut down */ void -GNUNET_CREDENTIAL_disconnect (struct GNUNET_CREDENTIAL_Handle *handle); +GNUNET_CREDENTIAL_disconnect(struct GNUNET_CREDENTIAL_Handle *handle); /** @@ -235,10 +227,10 @@ GNUNET_CREDENTIAL_disconnect (struct GNUNET_CREDENTIAL_Handle *handle); * @param credential the credentials */ typedef void (*GNUNET_CREDENTIAL_CredentialResultProcessor) (void *cls, - unsigned int d_count, - struct GNUNET_CREDENTIAL_Delegation *delegation_chain, - unsigned int c_count, - struct GNUNET_CREDENTIAL_Credential *credential); + unsigned int d_count, + struct GNUNET_CREDENTIAL_Delegation *delegation_chain, + unsigned int c_count, + struct GNUNET_CREDENTIAL_Credential *credential); /** * Iterator called on obtained result for an attribute delegation. @@ -280,23 +272,23 @@ typedef void (*GNUNET_CREDENTIAL_RemoveDelegateResultProcessor) (void *cls, * @return handle to the queued request */ struct GNUNET_CREDENTIAL_Request* -GNUNET_CREDENTIAL_verify (struct GNUNET_CREDENTIAL_Handle *handle, +GNUNET_CREDENTIAL_verify(struct GNUNET_CREDENTIAL_Handle *handle, + const struct GNUNET_CRYPTO_EcdsaPublicKey *issuer_key, + const char *issuer_attribute, + const struct GNUNET_CRYPTO_EcdsaPublicKey *subject_key, + uint32_t credential_count, + const struct GNUNET_CREDENTIAL_Credential *credentials, + GNUNET_CREDENTIAL_CredentialResultProcessor proc, + void *proc_cls); + +struct GNUNET_CREDENTIAL_Request* +GNUNET_CREDENTIAL_collect(struct GNUNET_CREDENTIAL_Handle *handle, const struct GNUNET_CRYPTO_EcdsaPublicKey *issuer_key, const char *issuer_attribute, - const struct GNUNET_CRYPTO_EcdsaPublicKey *subject_key, - uint32_t credential_count, - const struct GNUNET_CREDENTIAL_Credential *credentials, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *subject_key, GNUNET_CREDENTIAL_CredentialResultProcessor proc, void *proc_cls); -struct GNUNET_CREDENTIAL_Request* -GNUNET_CREDENTIAL_collect (struct GNUNET_CREDENTIAL_Handle *handle, - const struct GNUNET_CRYPTO_EcdsaPublicKey *issuer_key, - const char *issuer_attribute, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *subject_key, - GNUNET_CREDENTIAL_CredentialResultProcessor proc, - void *proc_cls); - /** * Delegate an attribute * @@ -310,13 +302,13 @@ GNUNET_CREDENTIAL_collect (struct GNUNET_CREDENTIAL_Handle *handle, * @return handle to the queued request */ struct GNUNET_CREDENTIAL_Request * -GNUNET_CREDENTIAL_add_delegation (struct GNUNET_CREDENTIAL_Handle *handle, - struct GNUNET_IDENTITY_Ego *issuer, - const char *attribute, - struct GNUNET_CRYPTO_EcdsaPublicKey *subject, - const char *delegated_attribute, - GNUNET_CREDENTIAL_DelegateResultProcessor proc, - void *proc_cls); +GNUNET_CREDENTIAL_add_delegation(struct GNUNET_CREDENTIAL_Handle *handle, + struct GNUNET_IDENTITY_Ego *issuer, + const char *attribute, + struct GNUNET_CRYPTO_EcdsaPublicKey *subject, + const char *delegated_attribute, + GNUNET_CREDENTIAL_DelegateResultProcessor proc, + void *proc_cls); /** * Remove a delegation @@ -329,11 +321,11 @@ GNUNET_CREDENTIAL_add_delegation (struct GNUNET_CREDENTIAL_Handle *handle, * @return handle to the queued request */ struct GNUNET_CREDENTIAL_Request * -GNUNET_CREDENTIAL_remove_delegation (struct GNUNET_CREDENTIAL_Handle *handle, - struct GNUNET_IDENTITY_Ego *issuer, - const char *attribute, - GNUNET_CREDENTIAL_RemoveDelegateResultProcessor proc, - void *proc_cls); +GNUNET_CREDENTIAL_remove_delegation(struct GNUNET_CREDENTIAL_Handle *handle, + struct GNUNET_IDENTITY_Ego *issuer, + const char *attribute, + GNUNET_CREDENTIAL_RemoveDelegateResultProcessor proc, + void *proc_cls); @@ -347,10 +339,10 @@ GNUNET_CREDENTIAL_remove_delegation (struct GNUNET_CREDENTIAL_Handle *handle, * @return handle to the queued request */ struct GNUNET_CREDENTIAL_Credential* -GNUNET_CREDENTIAL_credential_issue (const struct GNUNET_CRYPTO_EcdsaPrivateKey *issuer, - struct GNUNET_CRYPTO_EcdsaPublicKey *subject, - const char *attribute, - struct GNUNET_TIME_Absolute *expiration); +GNUNET_CREDENTIAL_credential_issue(const struct GNUNET_CRYPTO_EcdsaPrivateKey *issuer, + struct GNUNET_CRYPTO_EcdsaPublicKey *subject, + const char *attribute, + struct GNUNET_TIME_Absolute *expiration); @@ -360,7 +352,7 @@ GNUNET_CREDENTIAL_credential_issue (const struct GNUNET_CRYPTO_EcdsaPrivateKey * * @param lr the lookup request to cancel */ void -GNUNET_CREDENTIAL_request_cancel (struct GNUNET_CREDENTIAL_Request *lr); +GNUNET_CREDENTIAL_request_cancel(struct GNUNET_CREDENTIAL_Request *lr); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_crypto_lib.h b/src/include/gnunet_crypto_lib.h index 140a1b48c..6e347c52b 100644 --- a/src/include/gnunet_crypto_lib.h +++ b/src/include/gnunet_crypto_lib.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file include/gnunet_crypto_lib.h @@ -71,8 +71,7 @@ struct GNUNET_PeerIdentity; * Desired quality level for random numbers. * @ingroup crypto */ -enum GNUNET_CRYPTO_Quality -{ +enum GNUNET_CRYPTO_Quality { /** * No good quality of the operation is needed (i.e., * random numbers can be pseudo-random). @@ -113,8 +112,7 @@ enum GNUNET_CRYPTO_Quality /** * @brief 0-terminated ASCII encoding of a struct GNUNET_HashCode. */ -struct GNUNET_CRYPTO_HashAsciiEncoded -{ +struct GNUNET_CRYPTO_HashAsciiEncoded { unsigned char encoding[104]; }; @@ -127,8 +125,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * this must be followed by "size - 8" bytes of * the actual signed data */ -struct GNUNET_CRYPTO_EccSignaturePurpose -{ +struct GNUNET_CRYPTO_EccSignaturePurpose { /** * How many bytes does this signature sign? * (including this purpose header); in network @@ -150,9 +147,7 @@ struct GNUNET_CRYPTO_EccSignaturePurpose * @brief an ECC signature using EdDSA. * See cr.yp.to/papers.html#ed25519 */ -struct GNUNET_CRYPTO_EddsaSignature -{ - +struct GNUNET_CRYPTO_EddsaSignature { /** * R value. */ @@ -168,9 +163,7 @@ struct GNUNET_CRYPTO_EddsaSignature /** * @brief an ECC signature using ECDSA */ -struct GNUNET_CRYPTO_EcdsaSignature -{ - +struct GNUNET_CRYPTO_EcdsaSignature { /** * R value. */ @@ -187,8 +180,7 @@ struct GNUNET_CRYPTO_EcdsaSignature * Public ECC key (always for curve Ed25519) encoded in a format * suitable for network transmission and EdDSA signatures. */ -struct GNUNET_CRYPTO_EddsaPublicKey -{ +struct GNUNET_CRYPTO_EddsaPublicKey { /** * Point Q consists of a y-value mod p (256 bits); the x-value is * always positive. The point is stored in Ed25519 standard @@ -202,8 +194,7 @@ struct GNUNET_CRYPTO_EddsaPublicKey * Public ECC key (always for Curve25519) encoded in a format suitable * for network transmission and ECDSA signatures. */ -struct GNUNET_CRYPTO_EcdsaPublicKey -{ +struct GNUNET_CRYPTO_EcdsaPublicKey { /** * Q consists of an x- and a y-value, each mod p (256 bits), given * here in affine coordinates and Ed25519 standard compact format. @@ -215,8 +206,7 @@ struct GNUNET_CRYPTO_EcdsaPublicKey /** * The identity of the host (wraps the signing key of the peer). */ -struct GNUNET_PeerIdentity -{ +struct GNUNET_PeerIdentity { struct GNUNET_CRYPTO_EddsaPublicKey public_key; }; @@ -226,8 +216,7 @@ struct GNUNET_PeerIdentity * for network transmission and encryption (ECDH), * See http://cr.yp.to/ecdh.html */ -struct GNUNET_CRYPTO_EcdhePublicKey -{ +struct GNUNET_CRYPTO_EcdhePublicKey { /** * Q consists of an x- and a y-value, each mod p (256 bits), given * here in affine coordinates and Ed25519 standard compact format. @@ -240,8 +229,7 @@ struct GNUNET_CRYPTO_EcdhePublicKey * Private ECC key encoded for transmission. To be used only for ECDH * key exchange (ECDHE to be precise). */ -struct GNUNET_CRYPTO_EcdhePrivateKey -{ +struct GNUNET_CRYPTO_EcdhePrivateKey { /** * d is a value mod n, where n has at most 256 bits. */ @@ -252,8 +240,7 @@ struct GNUNET_CRYPTO_EcdhePrivateKey * Private ECC key encoded for transmission. To be used only for ECDSA * signatures. */ -struct GNUNET_CRYPTO_EcdsaPrivateKey -{ +struct GNUNET_CRYPTO_EcdsaPrivateKey { /** * d is a value mod n, where n has at most 256 bits. */ @@ -264,8 +251,7 @@ struct GNUNET_CRYPTO_EcdsaPrivateKey * Private ECC key encoded for transmission. To be used only for EdDSA * signatures. */ -struct GNUNET_CRYPTO_EddsaPrivateKey -{ +struct GNUNET_CRYPTO_EddsaPrivateKey { /** * d is a value mod n, where n has at most 256 bits. */ @@ -276,8 +262,7 @@ struct GNUNET_CRYPTO_EddsaPrivateKey /** * @brief type for session keys */ -struct GNUNET_CRYPTO_SymmetricSessionKey -{ +struct GNUNET_CRYPTO_SymmetricSessionKey { /** * Actual key for AES. */ @@ -297,8 +282,7 @@ GNUNET_NETWORK_STRUCT_END * NOTE: must be smaller (!) in size than the * `struct GNUNET_HashCode`. */ -struct GNUNET_CRYPTO_SymmetricInitializationVector -{ +struct GNUNET_CRYPTO_SymmetricInitializationVector { unsigned char aes_iv[GNUNET_CRYPTO_AES_KEY_LENGTH / 2]; unsigned char twofish_iv[GNUNET_CRYPTO_AES_KEY_LENGTH / 2]; @@ -308,8 +292,7 @@ struct GNUNET_CRYPTO_SymmetricInitializationVector /** * @brief type for (message) authentication keys */ -struct GNUNET_CRYPTO_AuthKey -{ +struct GNUNET_CRYPTO_AuthKey { unsigned char key[GNUNET_CRYPTO_HASH_LENGTH]; }; @@ -324,8 +307,7 @@ struct GNUNET_CRYPTO_AuthKey /** * Paillier public key. */ -struct GNUNET_CRYPTO_PaillierPublicKey -{ +struct GNUNET_CRYPTO_PaillierPublicKey { /** * N value. */ @@ -336,8 +318,7 @@ struct GNUNET_CRYPTO_PaillierPublicKey /** * Paillier private key. */ -struct GNUNET_CRYPTO_PaillierPrivateKey -{ +struct GNUNET_CRYPTO_PaillierPrivateKey { /** * Lambda-component of the private key. */ @@ -352,8 +333,7 @@ struct GNUNET_CRYPTO_PaillierPrivateKey /** * Paillier ciphertext. */ -struct GNUNET_CRYPTO_PaillierCiphertext -{ +struct GNUNET_CRYPTO_PaillierCiphertext { /** * Guaranteed minimum number of homomorphic operations with this ciphertext, * in network byte order (NBO). @@ -377,7 +357,7 @@ struct GNUNET_CRYPTO_PaillierCiphertext * @param seed the seed to use */ void -GNUNET_CRYPTO_seed_weak_random (int32_t seed); +GNUNET_CRYPTO_seed_weak_random(int32_t seed); /** @@ -389,7 +369,7 @@ GNUNET_CRYPTO_seed_weak_random (int32_t seed); * @return crc8 value */ uint8_t -GNUNET_CRYPTO_crc8_n (const void *buf, size_t len); +GNUNET_CRYPTO_crc8_n(const void *buf, size_t len); /** @@ -401,7 +381,7 @@ GNUNET_CRYPTO_crc8_n (const void *buf, size_t len); * @return updated crc sum (must be subjected to #GNUNET_CRYPTO_crc16_finish to get actual crc16) */ uint32_t -GNUNET_CRYPTO_crc16_step (uint32_t sum, const void *buf, size_t len); +GNUNET_CRYPTO_crc16_step(uint32_t sum, const void *buf, size_t len); /** @@ -411,7 +391,7 @@ GNUNET_CRYPTO_crc16_step (uint32_t sum, const void *buf, size_t len); * @return crc16 value */ uint16_t -GNUNET_CRYPTO_crc16_finish (uint32_t sum); +GNUNET_CRYPTO_crc16_finish(uint32_t sum); /** @@ -423,7 +403,7 @@ GNUNET_CRYPTO_crc16_finish (uint32_t sum); * @return crc16 value */ uint16_t -GNUNET_CRYPTO_crc16_n (const void *buf, size_t len); +GNUNET_CRYPTO_crc16_n(const void *buf, size_t len); /** @@ -436,7 +416,7 @@ GNUNET_CRYPTO_crc16_n (const void *buf, size_t len); * @return the resulting CRC32 checksum */ int32_t -GNUNET_CRYPTO_crc32_n (const void *buf, size_t len); +GNUNET_CRYPTO_crc32_n(const void *buf, size_t len); /** * @ingroup crypto @@ -447,7 +427,7 @@ GNUNET_CRYPTO_crc32_n (const void *buf, size_t len); * @param length buffer length */ void -GNUNET_CRYPTO_zero_keys (void *buffer, size_t length); +GNUNET_CRYPTO_zero_keys(void *buffer, size_t length); /** @@ -459,9 +439,9 @@ GNUNET_CRYPTO_zero_keys (void *buffer, size_t length); * @param length buffer length */ void -GNUNET_CRYPTO_random_block (enum GNUNET_CRYPTO_Quality mode, - void *buffer, - size_t length); +GNUNET_CRYPTO_random_block(enum GNUNET_CRYPTO_Quality mode, + void *buffer, + size_t length); /** * @ingroup crypto @@ -472,7 +452,7 @@ GNUNET_CRYPTO_random_block (enum GNUNET_CRYPTO_Quality mode, * @return a random value in the interval [0,@a i) (exclusive). */ uint32_t -GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i); +GNUNET_CRYPTO_random_u32(enum GNUNET_CRYPTO_Quality mode, uint32_t i); /** @@ -484,7 +464,7 @@ GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i); * @return random 64-bit number */ uint64_t -GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max); +GNUNET_CRYPTO_random_u64(enum GNUNET_CRYPTO_Quality mode, uint64_t max); /** @@ -497,7 +477,7 @@ GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max); * @return the permutation array (allocated from heap) */ unsigned int * -GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n); +GNUNET_CRYPTO_random_permute(enum GNUNET_CRYPTO_Quality mode, unsigned int n); /** @@ -507,7 +487,7 @@ GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n); * @param key key to initialize */ void -GNUNET_CRYPTO_symmetric_create_session_key ( +GNUNET_CRYPTO_symmetric_create_session_key( struct GNUNET_CRYPTO_SymmetricSessionKey *key); @@ -523,7 +503,7 @@ GNUNET_CRYPTO_symmetric_create_session_key ( * @return the size of the encrypted block, -1 for errors */ ssize_t -GNUNET_CRYPTO_symmetric_encrypt ( +GNUNET_CRYPTO_symmetric_encrypt( const void *block, size_t size, const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey, @@ -543,7 +523,7 @@ GNUNET_CRYPTO_symmetric_encrypt ( * @return -1 on failure, size of decrypted block on success */ ssize_t -GNUNET_CRYPTO_symmetric_decrypt ( +GNUNET_CRYPTO_symmetric_decrypt( const void *block, size_t size, const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey, @@ -561,7 +541,7 @@ GNUNET_CRYPTO_symmetric_decrypt ( * @param ... pairs of void * & size_t for context chunks, terminated by NULL */ void -GNUNET_CRYPTO_symmetric_derive_iv ( +GNUNET_CRYPTO_symmetric_derive_iv( struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, const void *salt, @@ -578,7 +558,7 @@ GNUNET_CRYPTO_symmetric_derive_iv ( * @param argp pairs of void * & size_t for context chunks, terminated by NULL */ void -GNUNET_CRYPTO_symmetric_derive_iv_v ( +GNUNET_CRYPTO_symmetric_derive_iv_v( struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, const void *salt, @@ -594,8 +574,8 @@ GNUNET_CRYPTO_symmetric_derive_iv_v ( * safely cast to char*, a '\\0' termination is set). */ void -GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode *block, - struct GNUNET_CRYPTO_HashAsciiEncoded *result); +GNUNET_CRYPTO_hash_to_enc(const struct GNUNET_HashCode *block, + struct GNUNET_CRYPTO_HashAsciiEncoded *result); /** @@ -608,9 +588,9 @@ GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode *block, * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding */ int -GNUNET_CRYPTO_hash_from_string2 (const char *enc, - size_t enclen, - struct GNUNET_HashCode *result); +GNUNET_CRYPTO_hash_from_string2(const char *enc, + size_t enclen, + struct GNUNET_HashCode *result); /** @@ -622,7 +602,7 @@ GNUNET_CRYPTO_hash_from_string2 (const char *enc, * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding */ #define GNUNET_CRYPTO_hash_from_string(enc, result) \ - GNUNET_CRYPTO_hash_from_string2 (enc, strlen (enc), result) + GNUNET_CRYPTO_hash_from_string2(enc, strlen(enc), result) /** @@ -638,8 +618,8 @@ GNUNET_CRYPTO_hash_from_string2 (const char *enc, * @return number between 0 and UINT32_MAX */ uint32_t -GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode *a, - const struct GNUNET_HashCode *b); +GNUNET_CRYPTO_hash_distance_u32(const struct GNUNET_HashCode *a, + const struct GNUNET_HashCode *b); /** @@ -651,9 +631,9 @@ GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode *a, * @param ret pointer to where to write the hashcode */ void -GNUNET_CRYPTO_hash (const void *block, - size_t size, - struct GNUNET_HashCode *ret); +GNUNET_CRYPTO_hash(const void *block, + size_t size, + struct GNUNET_HashCode *ret); /** @@ -668,7 +648,7 @@ struct GNUNET_HashContext; * @return context for incremental hash computation */ struct GNUNET_HashContext * -GNUNET_CRYPTO_hash_context_start (void); +GNUNET_CRYPTO_hash_context_start(void); /** @@ -679,9 +659,9 @@ GNUNET_CRYPTO_hash_context_start (void); * @param size number of bytes in @a buf */ void -GNUNET_CRYPTO_hash_context_read (struct GNUNET_HashContext *hc, - const void *buf, - size_t size); +GNUNET_CRYPTO_hash_context_read(struct GNUNET_HashContext *hc, + const void *buf, + size_t size); /** @@ -691,8 +671,8 @@ GNUNET_CRYPTO_hash_context_read (struct GNUNET_HashContext *hc, * @param r_hash where to write the latest / final hash code */ void -GNUNET_CRYPTO_hash_context_finish (struct GNUNET_HashContext *hc, - struct GNUNET_HashCode *r_hash); +GNUNET_CRYPTO_hash_context_finish(struct GNUNET_HashContext *hc, + struct GNUNET_HashCode *r_hash); /** @@ -701,7 +681,7 @@ GNUNET_CRYPTO_hash_context_finish (struct GNUNET_HashContext *hc, * @param hc hash context to destroy */ void -GNUNET_CRYPTO_hash_context_abort (struct GNUNET_HashContext *hc); +GNUNET_CRYPTO_hash_context_abort(struct GNUNET_HashContext *hc); /** @@ -716,11 +696,11 @@ GNUNET_CRYPTO_hash_context_abort (struct GNUNET_HashContext *hc); * @param hmac where to store the hmac */ void -GNUNET_CRYPTO_hmac_raw (const void *key, - size_t key_len, - const void *plaintext, - size_t plaintext_len, - struct GNUNET_HashCode *hmac); +GNUNET_CRYPTO_hmac_raw(const void *key, + size_t key_len, + const void *plaintext, + size_t plaintext_len, + struct GNUNET_HashCode *hmac); /** @@ -733,10 +713,10 @@ GNUNET_CRYPTO_hmac_raw (const void *key, * @param hmac where to store the hmac */ void -GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key, - const void *plaintext, - size_t plaintext_len, - struct GNUNET_HashCode *hmac); +GNUNET_CRYPTO_hmac(const struct GNUNET_CRYPTO_AuthKey *key, + const void *plaintext, + size_t plaintext_len, + struct GNUNET_HashCode *hmac); /** @@ -769,11 +749,11 @@ struct GNUNET_CRYPTO_FileHashContext; * @return NULL on (immediate) errror */ struct GNUNET_CRYPTO_FileHashContext * -GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority, - const char *filename, - size_t blocksize, - GNUNET_CRYPTO_HashCompletedCallback callback, - void *callback_cls); +GNUNET_CRYPTO_hash_file(enum GNUNET_SCHEDULER_Priority priority, + const char *filename, + size_t blocksize, + GNUNET_CRYPTO_HashCompletedCallback callback, + void *callback_cls); /** @@ -782,7 +762,7 @@ GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority, * @param fhc operation to cancel (callback must not yet have been invoked) */ void -GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc); +GNUNET_CRYPTO_hash_file_cancel(struct GNUNET_CRYPTO_FileHashContext *fhc); /** @@ -793,8 +773,8 @@ GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc); * @param result hash code that is randomized */ void -GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode, - struct GNUNET_HashCode *result); +GNUNET_CRYPTO_hash_create_random(enum GNUNET_CRYPTO_Quality mode, + struct GNUNET_HashCode *result); /** @@ -806,9 +786,9 @@ GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode, * @param result set to @a b - @a a */ void -GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode *a, - const struct GNUNET_HashCode *b, - struct GNUNET_HashCode *result); +GNUNET_CRYPTO_hash_difference(const struct GNUNET_HashCode *a, + const struct GNUNET_HashCode *b, + struct GNUNET_HashCode *result); /** @@ -820,9 +800,9 @@ GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode *a, * @param result set to @a a + @a delta */ void -GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode *a, - const struct GNUNET_HashCode *delta, - struct GNUNET_HashCode *result); +GNUNET_CRYPTO_hash_sum(const struct GNUNET_HashCode *a, + const struct GNUNET_HashCode *delta, + struct GNUNET_HashCode *result); /** @@ -834,9 +814,9 @@ GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode *a, * @param result set to @a a ^ @a b */ void -GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode *a, - const struct GNUNET_HashCode *b, - struct GNUNET_HashCode *result); +GNUNET_CRYPTO_hash_xor(const struct GNUNET_HashCode *a, + const struct GNUNET_HashCode *b, + struct GNUNET_HashCode *result); /** @@ -848,7 +828,7 @@ GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode *a, * @param iv set to a valid initialization vector */ void -GNUNET_CRYPTO_hash_to_aes_key ( +GNUNET_CRYPTO_hash_to_aes_key( const struct GNUNET_HashCode *hc, struct GNUNET_CRYPTO_SymmetricSessionKey *skey, struct GNUNET_CRYPTO_SymmetricInitializationVector *iv); @@ -863,8 +843,8 @@ GNUNET_CRYPTO_hash_to_aes_key ( * @return Bit \a bit from hashcode \a code, -1 for invalid index */ int -GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode *code, - unsigned int bit); +GNUNET_CRYPTO_hash_get_bit(const struct GNUNET_HashCode *code, + unsigned int bit); /** @@ -880,8 +860,8 @@ GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode *code, * @return the number of bits that match */ unsigned int -GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode *first, - const struct GNUNET_HashCode *second); +GNUNET_CRYPTO_hash_matching_bits(const struct GNUNET_HashCode *first, + const struct GNUNET_HashCode *second); /** @@ -894,8 +874,8 @@ GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode *first, * @return 1 if @a h1 > @a h2, -1 if @a h1 < @a h2 and 0 if @a h1 == @a h2. */ int -GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1, - const struct GNUNET_HashCode *h2); +GNUNET_CRYPTO_hash_cmp(const struct GNUNET_HashCode *h1, + const struct GNUNET_HashCode *h2); /** @@ -909,9 +889,9 @@ GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1, * @return -1 if @a h1 is closer, 1 if @a h2 is closer and 0 if @a h1== @a h2. */ int -GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1, - const struct GNUNET_HashCode *h2, - const struct GNUNET_HashCode *target); +GNUNET_CRYPTO_hash_xorcmp(const struct GNUNET_HashCode *h1, + const struct GNUNET_HashCode *h2, + const struct GNUNET_HashCode *target); /** @@ -924,7 +904,7 @@ GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1, * @param argp pair of void * & size_t for context chunks, terminated by NULL */ void -GNUNET_CRYPTO_hmac_derive_key_v ( +GNUNET_CRYPTO_hmac_derive_key_v( struct GNUNET_CRYPTO_AuthKey *key, const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey, const void *salt, @@ -942,7 +922,7 @@ GNUNET_CRYPTO_hmac_derive_key_v ( * @param ... pair of void * & size_t for context chunks, terminated by NULL */ void -GNUNET_CRYPTO_hmac_derive_key ( +GNUNET_CRYPTO_hmac_derive_key( struct GNUNET_CRYPTO_AuthKey *key, const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey, const void *salt, @@ -965,15 +945,15 @@ GNUNET_CRYPTO_hmac_derive_key ( * @return #GNUNET_YES on success */ int -GNUNET_CRYPTO_hkdf (void *result, - size_t out_len, - int xtr_algo, - int prf_algo, - const void *xts, - size_t xts_len, - const void *skm, - size_t skm_len, - ...); +GNUNET_CRYPTO_hkdf(void *result, + size_t out_len, + int xtr_algo, + int prf_algo, + const void *xts, + size_t xts_len, + const void *skm, + size_t skm_len, + ...); /** @@ -991,15 +971,15 @@ GNUNET_CRYPTO_hkdf (void *result, * @return #GNUNET_YES on success */ int -GNUNET_CRYPTO_hkdf_v (void *result, - size_t out_len, - int xtr_algo, - int prf_algo, - const void *xts, - size_t xts_len, - const void *skm, - size_t skm_len, - va_list argp); +GNUNET_CRYPTO_hkdf_v(void *result, + size_t out_len, + int xtr_algo, + int prf_algo, + const void *xts, + size_t xts_len, + const void *skm, + size_t skm_len, + va_list argp); /** @@ -1014,13 +994,13 @@ GNUNET_CRYPTO_hkdf_v (void *result, * @return #GNUNET_YES on success */ int -GNUNET_CRYPTO_kdf_v (void *result, - size_t out_len, - const void *xts, - size_t xts_len, - const void *skm, - size_t skm_len, - va_list argp); +GNUNET_CRYPTO_kdf_v(void *result, + size_t out_len, + const void *xts, + size_t xts_len, + const void *skm, + size_t skm_len, + va_list argp); /** @@ -1036,13 +1016,13 @@ GNUNET_CRYPTO_kdf_v (void *result, * @param ctx context string */ void -GNUNET_CRYPTO_kdf_mod_mpi (gcry_mpi_t *r, - gcry_mpi_t n, - const void *xts, - size_t xts_len, - const void *skm, - size_t skm_len, - const char *ctx); +GNUNET_CRYPTO_kdf_mod_mpi(gcry_mpi_t *r, + gcry_mpi_t n, + const void *xts, + size_t xts_len, + const void *skm, + size_t skm_len, + const char *ctx); /** @@ -1058,13 +1038,13 @@ GNUNET_CRYPTO_kdf_mod_mpi (gcry_mpi_t *r, * @return #GNUNET_YES on success */ int -GNUNET_CRYPTO_kdf (void *result, - size_t out_len, - const void *xts, - size_t xts_len, - const void *skm, - size_t skm_len, - ...); +GNUNET_CRYPTO_kdf(void *result, + size_t out_len, + const void *xts, + size_t xts_len, + const void *skm, + size_t skm_len, + ...); /** @@ -1075,7 +1055,7 @@ GNUNET_CRYPTO_kdf (void *result, * @param pub where to write the public key */ void -GNUNET_CRYPTO_ecdsa_key_get_public ( +GNUNET_CRYPTO_ecdsa_key_get_public( const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv, struct GNUNET_CRYPTO_EcdsaPublicKey *pub); @@ -1087,7 +1067,7 @@ GNUNET_CRYPTO_ecdsa_key_get_public ( * @param pub where to write the public key */ void -GNUNET_CRYPTO_eddsa_key_get_public ( +GNUNET_CRYPTO_eddsa_key_get_public( const struct GNUNET_CRYPTO_EddsaPrivateKey *priv, struct GNUNET_CRYPTO_EddsaPublicKey *pub); @@ -1100,7 +1080,7 @@ GNUNET_CRYPTO_eddsa_key_get_public ( * @param pub where to write the public key */ void -GNUNET_CRYPTO_ecdhe_key_get_public ( +GNUNET_CRYPTO_ecdhe_key_get_public( const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, struct GNUNET_CRYPTO_EcdhePublicKey *pub); @@ -1112,7 +1092,7 @@ GNUNET_CRYPTO_ecdhe_key_get_public ( * @return string representing @a pub */ char * -GNUNET_CRYPTO_ecdsa_public_key_to_string ( +GNUNET_CRYPTO_ecdsa_public_key_to_string( const struct GNUNET_CRYPTO_EcdsaPublicKey *pub); /** @@ -1122,7 +1102,7 @@ GNUNET_CRYPTO_ecdsa_public_key_to_string ( * @return string representing @a priv */ char * -GNUNET_CRYPTO_ecdsa_private_key_to_string ( +GNUNET_CRYPTO_ecdsa_private_key_to_string( const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv); @@ -1133,7 +1113,7 @@ GNUNET_CRYPTO_ecdsa_private_key_to_string ( * @return string representing @a pub */ char * -GNUNET_CRYPTO_eddsa_private_key_to_string ( +GNUNET_CRYPTO_eddsa_private_key_to_string( const struct GNUNET_CRYPTO_EddsaPrivateKey *priv); @@ -1144,7 +1124,7 @@ GNUNET_CRYPTO_eddsa_private_key_to_string ( * @return string representing @a pub */ char * -GNUNET_CRYPTO_eddsa_public_key_to_string ( +GNUNET_CRYPTO_eddsa_public_key_to_string( const struct GNUNET_CRYPTO_EddsaPublicKey *pub); @@ -1157,7 +1137,7 @@ GNUNET_CRYPTO_eddsa_public_key_to_string ( * @return #GNUNET_OK on success */ int -GNUNET_CRYPTO_ecdsa_public_key_from_string ( +GNUNET_CRYPTO_ecdsa_public_key_from_string( const char *enc, size_t enclen, struct GNUNET_CRYPTO_EcdsaPublicKey *pub); @@ -1172,7 +1152,7 @@ GNUNET_CRYPTO_ecdsa_public_key_from_string ( * @return #GNUNET_OK on success */ int -GNUNET_CRYPTO_eddsa_private_key_from_string ( +GNUNET_CRYPTO_eddsa_private_key_from_string( const char *enc, size_t enclen, struct GNUNET_CRYPTO_EddsaPrivateKey *pub); @@ -1187,7 +1167,7 @@ GNUNET_CRYPTO_eddsa_private_key_from_string ( * @return #GNUNET_OK on success */ int -GNUNET_CRYPTO_eddsa_public_key_from_string ( +GNUNET_CRYPTO_eddsa_public_key_from_string( const char *enc, size_t enclen, struct GNUNET_CRYPTO_EddsaPublicKey *pub); @@ -1209,7 +1189,7 @@ GNUNET_CRYPTO_eddsa_public_key_from_string ( * permission denied); free using #GNUNET_free */ struct GNUNET_CRYPTO_EcdsaPrivateKey * -GNUNET_CRYPTO_ecdsa_key_create_from_file (const char *filename); +GNUNET_CRYPTO_ecdsa_key_create_from_file(const char *filename); /** @@ -1228,7 +1208,7 @@ GNUNET_CRYPTO_ecdsa_key_create_from_file (const char *filename); * permission denied); free using #GNUNET_free */ struct GNUNET_CRYPTO_EddsaPrivateKey * -GNUNET_CRYPTO_eddsa_key_create_from_file (const char *filename); +GNUNET_CRYPTO_eddsa_key_create_from_file(const char *filename); /** @@ -1247,7 +1227,7 @@ struct GNUNET_CONFIGURATION_Handle; * permission denied); free using #GNUNET_free */ struct GNUNET_CRYPTO_EddsaPrivateKey * -GNUNET_CRYPTO_eddsa_key_create_from_configuration ( +GNUNET_CRYPTO_eddsa_key_create_from_configuration( const struct GNUNET_CONFIGURATION_Handle *cfg); @@ -1258,7 +1238,7 @@ GNUNET_CRYPTO_eddsa_key_create_from_configuration ( * @return fresh private key; free using #GNUNET_free */ struct GNUNET_CRYPTO_EcdsaPrivateKey * -GNUNET_CRYPTO_ecdsa_key_create (void); +GNUNET_CRYPTO_ecdsa_key_create(void); /** @@ -1268,7 +1248,7 @@ GNUNET_CRYPTO_ecdsa_key_create (void); * @return fresh private key; free using #GNUNET_free */ struct GNUNET_CRYPTO_EddsaPrivateKey * -GNUNET_CRYPTO_eddsa_key_create (void); +GNUNET_CRYPTO_eddsa_key_create(void); /** @@ -1279,7 +1259,7 @@ GNUNET_CRYPTO_eddsa_key_create (void); * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure */ int -GNUNET_CRYPTO_ecdhe_key_create2 (struct GNUNET_CRYPTO_EcdhePrivateKey *pk); +GNUNET_CRYPTO_ecdhe_key_create2(struct GNUNET_CRYPTO_EcdhePrivateKey *pk); /** @@ -1289,7 +1269,7 @@ GNUNET_CRYPTO_ecdhe_key_create2 (struct GNUNET_CRYPTO_EcdhePrivateKey *pk); * @return fresh private key; free using #GNUNET_free */ struct GNUNET_CRYPTO_EcdhePrivateKey * -GNUNET_CRYPTO_ecdhe_key_create (void); +GNUNET_CRYPTO_ecdhe_key_create(void); /** @@ -1299,7 +1279,7 @@ GNUNET_CRYPTO_ecdhe_key_create (void); * @param pk location of the key */ void -GNUNET_CRYPTO_eddsa_key_clear (struct GNUNET_CRYPTO_EddsaPrivateKey *pk); +GNUNET_CRYPTO_eddsa_key_clear(struct GNUNET_CRYPTO_EddsaPrivateKey *pk); /** @@ -1309,7 +1289,7 @@ GNUNET_CRYPTO_eddsa_key_clear (struct GNUNET_CRYPTO_EddsaPrivateKey *pk); * @param pk location of the key */ void -GNUNET_CRYPTO_ecdsa_key_clear (struct GNUNET_CRYPTO_EcdsaPrivateKey *pk); +GNUNET_CRYPTO_ecdsa_key_clear(struct GNUNET_CRYPTO_EcdsaPrivateKey *pk); /** @@ -1319,7 +1299,7 @@ GNUNET_CRYPTO_ecdsa_key_clear (struct GNUNET_CRYPTO_EcdsaPrivateKey *pk); * @param pk location of the key */ void -GNUNET_CRYPTO_ecdhe_key_clear (struct GNUNET_CRYPTO_EcdhePrivateKey *pk); +GNUNET_CRYPTO_ecdhe_key_clear(struct GNUNET_CRYPTO_EcdhePrivateKey *pk); /** @@ -1329,7 +1309,7 @@ GNUNET_CRYPTO_ecdhe_key_clear (struct GNUNET_CRYPTO_EcdhePrivateKey *pk); * @return "anonymous" private key; do not free */ const struct GNUNET_CRYPTO_EcdsaPrivateKey * -GNUNET_CRYPTO_ecdsa_key_get_anonymous (void); +GNUNET_CRYPTO_ecdsa_key_get_anonymous(void); /** @@ -1338,11 +1318,11 @@ GNUNET_CRYPTO_ecdsa_key_get_anonymous (void); * configuration file (!). This function is used so that * at a later point code can be certain that reading a * hostkey is fast (for example in time-dependent testcases). -* + * * @param cfg_name name of the configuration file to use */ void -GNUNET_CRYPTO_eddsa_setup_hostkey (const char *cfg_name); +GNUNET_CRYPTO_eddsa_setup_hostkey(const char *cfg_name); /** @@ -1355,8 +1335,8 @@ GNUNET_CRYPTO_eddsa_setup_hostkey (const char *cfg_name); * could not be retrieved */ int -GNUNET_CRYPTO_get_peer_identity (const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_PeerIdentity *dst); +GNUNET_CRYPTO_get_peer_identity(const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_PeerIdentity *dst); /** @@ -1369,8 +1349,7 @@ struct GNUNET_CRYPTO_EccDlogContext; * Point on a curve (always for Curve25519) encoded in a format suitable * for network transmission (ECDH), see http://cr.yp.to/ecdh.html. */ -struct GNUNET_CRYPTO_EccPoint -{ +struct GNUNET_CRYPTO_EccPoint { /** * Q consists of an x- and a y-value, each mod p (256 bits), given * here in affine coordinates and Ed25519 standard compact format. @@ -1387,7 +1366,7 @@ struct GNUNET_CRYPTO_EccPoint * @return NULL on error */ struct GNUNET_CRYPTO_EccDlogContext * -GNUNET_CRYPTO_ecc_dlog_prepare (unsigned int max, unsigned int mem); +GNUNET_CRYPTO_ecc_dlog_prepare(unsigned int max, unsigned int mem); /** @@ -1399,8 +1378,8 @@ GNUNET_CRYPTO_ecc_dlog_prepare (unsigned int max, unsigned int mem); * @return INT_MAX if dlog failed, otherwise the factor */ int -GNUNET_CRYPTO_ecc_dlog (struct GNUNET_CRYPTO_EccDlogContext *edc, - gcry_mpi_point_t input); +GNUNET_CRYPTO_ecc_dlog(struct GNUNET_CRYPTO_EccDlogContext *edc, + gcry_mpi_point_t input); /** @@ -1417,7 +1396,7 @@ GNUNET_CRYPTO_ecc_dlog (struct GNUNET_CRYPTO_EccDlogContext *edc, * must be freed using #GNUNET_CRYPTO_ecc_free() */ gcry_mpi_point_t -GNUNET_CRYPTO_ecc_dexp (struct GNUNET_CRYPTO_EccDlogContext *edc, int val); +GNUNET_CRYPTO_ecc_dexp(struct GNUNET_CRYPTO_EccDlogContext *edc, int val); /** @@ -1430,8 +1409,8 @@ GNUNET_CRYPTO_ecc_dexp (struct GNUNET_CRYPTO_EccDlogContext *edc, int val); * must be freed using #GNUNET_CRYPTO_ecc_free() */ gcry_mpi_point_t -GNUNET_CRYPTO_ecc_dexp_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc, - gcry_mpi_t val); +GNUNET_CRYPTO_ecc_dexp_mpi(struct GNUNET_CRYPTO_EccDlogContext *edc, + gcry_mpi_t val); /** @@ -1444,9 +1423,9 @@ GNUNET_CRYPTO_ecc_dexp_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc, * must be freed using #GNUNET_CRYPTO_ecc_free() */ gcry_mpi_point_t -GNUNET_CRYPTO_ecc_pmul_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc, - gcry_mpi_point_t p, - gcry_mpi_t val); +GNUNET_CRYPTO_ecc_pmul_mpi(struct GNUNET_CRYPTO_EccDlogContext *edc, + gcry_mpi_point_t p, + gcry_mpi_t val); /** @@ -1457,9 +1436,9 @@ GNUNET_CRYPTO_ecc_pmul_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc, * @param[out] bin binary point representation */ void -GNUNET_CRYPTO_ecc_point_to_bin (struct GNUNET_CRYPTO_EccDlogContext *edc, - gcry_mpi_point_t point, - struct GNUNET_CRYPTO_EccPoint *bin); +GNUNET_CRYPTO_ecc_point_to_bin(struct GNUNET_CRYPTO_EccDlogContext *edc, + gcry_mpi_point_t point, + struct GNUNET_CRYPTO_EccPoint *bin); /** @@ -1470,8 +1449,8 @@ GNUNET_CRYPTO_ecc_point_to_bin (struct GNUNET_CRYPTO_EccDlogContext *edc, * @return computational representation */ gcry_mpi_point_t -GNUNET_CRYPTO_ecc_bin_to_point (struct GNUNET_CRYPTO_EccDlogContext *edc, - const struct GNUNET_CRYPTO_EccPoint *bin); +GNUNET_CRYPTO_ecc_bin_to_point(struct GNUNET_CRYPTO_EccDlogContext *edc, + const struct GNUNET_CRYPTO_EccPoint *bin); /** @@ -1483,9 +1462,9 @@ GNUNET_CRYPTO_ecc_bin_to_point (struct GNUNET_CRYPTO_EccDlogContext *edc, * @return @a a + @a b, must be freed using #GNUNET_CRYPTO_ecc_free() */ gcry_mpi_point_t -GNUNET_CRYPTO_ecc_add (struct GNUNET_CRYPTO_EccDlogContext *edc, - gcry_mpi_point_t a, - gcry_mpi_point_t b); +GNUNET_CRYPTO_ecc_add(struct GNUNET_CRYPTO_EccDlogContext *edc, + gcry_mpi_point_t a, + gcry_mpi_point_t b); /** @@ -1498,9 +1477,9 @@ GNUNET_CRYPTO_ecc_add (struct GNUNET_CRYPTO_EccDlogContext *edc, * @param[out] r_inv set to the additive inverse of @a r */ void -GNUNET_CRYPTO_ecc_rnd (struct GNUNET_CRYPTO_EccDlogContext *edc, - gcry_mpi_point_t *r, - gcry_mpi_point_t *r_inv); +GNUNET_CRYPTO_ecc_rnd(struct GNUNET_CRYPTO_EccDlogContext *edc, + gcry_mpi_point_t *r, + gcry_mpi_point_t *r_inv); /** @@ -1512,9 +1491,9 @@ GNUNET_CRYPTO_ecc_rnd (struct GNUNET_CRYPTO_EccDlogContext *edc, * @param[out] r_inv set to the multiplicative inverse of @a r */ void -GNUNET_CRYPTO_ecc_rnd_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc, - gcry_mpi_t *r, - gcry_mpi_t *r_inv); +GNUNET_CRYPTO_ecc_rnd_mpi(struct GNUNET_CRYPTO_EccDlogContext *edc, + gcry_mpi_t *r, + gcry_mpi_t *r_inv); /** @@ -1524,7 +1503,7 @@ GNUNET_CRYPTO_ecc_rnd_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc, * @return random value mod n. */ gcry_mpi_t -GNUNET_CRYPTO_ecc_random_mod_n (struct GNUNET_CRYPTO_EccDlogContext *edc); +GNUNET_CRYPTO_ecc_random_mod_n(struct GNUNET_CRYPTO_EccDlogContext *edc); /** @@ -1533,7 +1512,7 @@ GNUNET_CRYPTO_ecc_random_mod_n (struct GNUNET_CRYPTO_EccDlogContext *edc); * @param p point to free */ void -GNUNET_CRYPTO_ecc_free (gcry_mpi_point_t p); +GNUNET_CRYPTO_ecc_free(gcry_mpi_point_t p); /** @@ -1542,7 +1521,7 @@ GNUNET_CRYPTO_ecc_free (gcry_mpi_point_t p); * @param dlc dlog context */ void -GNUNET_CRYPTO_ecc_dlog_release (struct GNUNET_CRYPTO_EccDlogContext *dlc); +GNUNET_CRYPTO_ecc_dlog_release(struct GNUNET_CRYPTO_EccDlogContext *dlc); /** @@ -1555,9 +1534,9 @@ GNUNET_CRYPTO_ecc_dlog_release (struct GNUNET_CRYPTO_EccDlogContext *dlc); * @return #GNUNET_SYSERR on error, #GNUNET_OK on success */ int -GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, - const struct GNUNET_CRYPTO_EcdhePublicKey *pub, - struct GNUNET_HashCode *key_material); +GNUNET_CRYPTO_ecc_ecdh(const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, + const struct GNUNET_CRYPTO_EcdhePublicKey *pub, + struct GNUNET_HashCode *key_material); /** @@ -1571,9 +1550,9 @@ GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, * @return #GNUNET_SYSERR on error, #GNUNET_OK on success */ int -GNUNET_CRYPTO_eddsa_ecdh (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv, - const struct GNUNET_CRYPTO_EcdhePublicKey *pub, - struct GNUNET_HashCode *key_material); +GNUNET_CRYPTO_eddsa_ecdh(const struct GNUNET_CRYPTO_EddsaPrivateKey *priv, + const struct GNUNET_CRYPTO_EcdhePublicKey *pub, + struct GNUNET_HashCode *key_material); /** * @ingroup crypto @@ -1586,9 +1565,9 @@ GNUNET_CRYPTO_eddsa_ecdh (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv, * @return #GNUNET_SYSERR on error, #GNUNET_OK on success */ int -GNUNET_CRYPTO_ecdsa_ecdh (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv, - const struct GNUNET_CRYPTO_EcdhePublicKey *pub, - struct GNUNET_HashCode *key_material); +GNUNET_CRYPTO_ecdsa_ecdh(const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv, + const struct GNUNET_CRYPTO_EcdhePublicKey *pub, + struct GNUNET_HashCode *key_material); /** @@ -1602,9 +1581,9 @@ GNUNET_CRYPTO_ecdsa_ecdh (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv, * @return #GNUNET_SYSERR on error, #GNUNET_OK on success */ int -GNUNET_CRYPTO_ecdh_eddsa (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, - const struct GNUNET_CRYPTO_EddsaPublicKey *pub, - struct GNUNET_HashCode *key_material); +GNUNET_CRYPTO_ecdh_eddsa(const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, + const struct GNUNET_CRYPTO_EddsaPublicKey *pub, + struct GNUNET_HashCode *key_material); /** * @ingroup crypto @@ -1617,9 +1596,9 @@ GNUNET_CRYPTO_ecdh_eddsa (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, * @return #GNUNET_SYSERR on error, #GNUNET_OK on success */ int -GNUNET_CRYPTO_ecdh_ecdsa (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, - const struct GNUNET_CRYPTO_EcdsaPublicKey *pub, - struct GNUNET_HashCode *key_material); +GNUNET_CRYPTO_ecdh_ecdsa(const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, + const struct GNUNET_CRYPTO_EcdsaPublicKey *pub, + struct GNUNET_HashCode *key_material); /** @@ -1632,7 +1611,7 @@ GNUNET_CRYPTO_ecdh_ecdsa (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, * @return #GNUNET_SYSERR on error, #GNUNET_OK on success */ int -GNUNET_CRYPTO_eddsa_sign ( +GNUNET_CRYPTO_eddsa_sign( const struct GNUNET_CRYPTO_EddsaPrivateKey *priv, const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose, struct GNUNET_CRYPTO_EddsaSignature *sig); @@ -1648,7 +1627,7 @@ GNUNET_CRYPTO_eddsa_sign ( * @return #GNUNET_SYSERR on error, #GNUNET_OK on success */ int -GNUNET_CRYPTO_ecdsa_sign ( +GNUNET_CRYPTO_ecdsa_sign( const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv, const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose, struct GNUNET_CRYPTO_EcdsaSignature *sig); @@ -1664,7 +1643,7 @@ GNUNET_CRYPTO_ecdsa_sign ( * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid */ int -GNUNET_CRYPTO_eddsa_verify ( +GNUNET_CRYPTO_eddsa_verify( uint32_t purpose, const struct GNUNET_CRYPTO_EccSignaturePurpose *validate, const struct GNUNET_CRYPTO_EddsaSignature *sig, @@ -1682,7 +1661,7 @@ GNUNET_CRYPTO_eddsa_verify ( * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid */ int -GNUNET_CRYPTO_ecdsa_verify ( +GNUNET_CRYPTO_ecdsa_verify( uint32_t purpose, const struct GNUNET_CRYPTO_EccSignaturePurpose *validate, const struct GNUNET_CRYPTO_EcdsaSignature *sig, @@ -1703,7 +1682,7 @@ GNUNET_CRYPTO_ecdsa_verify ( * @return derived private key */ struct GNUNET_CRYPTO_EcdsaPrivateKey * -GNUNET_CRYPTO_ecdsa_private_key_derive ( +GNUNET_CRYPTO_ecdsa_private_key_derive( const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv, const char *label, const char *context); @@ -1721,7 +1700,7 @@ GNUNET_CRYPTO_ecdsa_private_key_derive ( * @param result where to write the derived public key */ void -GNUNET_CRYPTO_ecdsa_public_key_derive ( +GNUNET_CRYPTO_ecdsa_public_key_derive( const struct GNUNET_CRYPTO_EcdsaPublicKey *pub, const char *label, const char *context, @@ -1737,7 +1716,7 @@ GNUNET_CRYPTO_ecdsa_public_key_derive ( * @param val value to write to @a buf */ void -GNUNET_CRYPTO_mpi_print_unsigned (void *buf, size_t size, gcry_mpi_t val); +GNUNET_CRYPTO_mpi_print_unsigned(void *buf, size_t size, gcry_mpi_t val); /** @@ -1750,9 +1729,9 @@ GNUNET_CRYPTO_mpi_print_unsigned (void *buf, size_t size, gcry_mpi_t val); * @param size number of bytes in @a data */ void -GNUNET_CRYPTO_mpi_scan_unsigned (gcry_mpi_t *result, - const void *data, - size_t size); +GNUNET_CRYPTO_mpi_scan_unsigned(gcry_mpi_t *result, + const void *data, + size_t size); /** @@ -1762,7 +1741,7 @@ GNUNET_CRYPTO_mpi_scan_unsigned (gcry_mpi_t *result, * @param[out] private_key Where to store the private key? */ void -GNUNET_CRYPTO_paillier_create ( +GNUNET_CRYPTO_paillier_create( struct GNUNET_CRYPTO_PaillierPublicKey *public_key, struct GNUNET_CRYPTO_PaillierPrivateKey *private_key); @@ -1779,7 +1758,7 @@ GNUNET_CRYPTO_paillier_create ( * or -1 if less than one homomorphic operation is possible */ int -GNUNET_CRYPTO_paillier_encrypt ( +GNUNET_CRYPTO_paillier_encrypt( const struct GNUNET_CRYPTO_PaillierPublicKey *public_key, const gcry_mpi_t m, int desired_ops, @@ -1795,7 +1774,7 @@ GNUNET_CRYPTO_paillier_encrypt ( * @param[out] m Decryption of @a ciphertext with @private_key. */ void -GNUNET_CRYPTO_paillier_decrypt ( +GNUNET_CRYPTO_paillier_decrypt( const struct GNUNET_CRYPTO_PaillierPrivateKey *private_key, const struct GNUNET_CRYPTO_PaillierPublicKey *public_key, const struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext, @@ -1816,7 +1795,7 @@ GNUNET_CRYPTO_paillier_decrypt ( * #GNUNET_SYSERR if no more homomorphic operations are remaining. */ int -GNUNET_CRYPTO_paillier_hom_add ( +GNUNET_CRYPTO_paillier_hom_add( const struct GNUNET_CRYPTO_PaillierPublicKey *public_key, const struct GNUNET_CRYPTO_PaillierCiphertext *c1, const struct GNUNET_CRYPTO_PaillierCiphertext *c2, @@ -1830,7 +1809,7 @@ GNUNET_CRYPTO_paillier_hom_add ( * @return the number of remaining homomorphic operations */ int -GNUNET_CRYPTO_paillier_hom_get_remaining ( +GNUNET_CRYPTO_paillier_hom_get_remaining( const struct GNUNET_CRYPTO_PaillierCiphertext *c); @@ -1850,8 +1829,7 @@ struct GNUNET_CRYPTO_RsaPublicKey; /** * Constant-size pre-secret for blinding key generation. */ -struct GNUNET_CRYPTO_RsaBlindingKeySecret -{ +struct GNUNET_CRYPTO_RsaBlindingKeySecret { /** * Bits used to generate the blinding key. 256 bits * of entropy is enough. @@ -1872,7 +1850,7 @@ struct GNUNET_CRYPTO_RsaSignature; * @return fresh private key */ struct GNUNET_CRYPTO_RsaPrivateKey * -GNUNET_CRYPTO_rsa_private_key_create (unsigned int len); +GNUNET_CRYPTO_rsa_private_key_create(unsigned int len); /** @@ -1881,7 +1859,7 @@ GNUNET_CRYPTO_rsa_private_key_create (unsigned int len); * @param key pointer to the memory to free */ void -GNUNET_CRYPTO_rsa_private_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *key); +GNUNET_CRYPTO_rsa_private_key_free(struct GNUNET_CRYPTO_RsaPrivateKey *key); /** @@ -1893,7 +1871,7 @@ GNUNET_CRYPTO_rsa_private_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *key); * @return size of memory allocatedin @a buffer */ size_t -GNUNET_CRYPTO_rsa_private_key_encode ( +GNUNET_CRYPTO_rsa_private_key_encode( const struct GNUNET_CRYPTO_RsaPrivateKey *key, char **buffer); @@ -1907,7 +1885,7 @@ GNUNET_CRYPTO_rsa_private_key_encode ( * @return NULL on error */ struct GNUNET_CRYPTO_RsaPrivateKey * -GNUNET_CRYPTO_rsa_private_key_decode (const char *buf, size_t len); +GNUNET_CRYPTO_rsa_private_key_decode(const char *buf, size_t len); /** @@ -1917,7 +1895,7 @@ GNUNET_CRYPTO_rsa_private_key_decode (const char *buf, size_t len); * @return the duplicate key; NULL upon error */ struct GNUNET_CRYPTO_RsaPrivateKey * -GNUNET_CRYPTO_rsa_private_key_dup ( +GNUNET_CRYPTO_rsa_private_key_dup( const struct GNUNET_CRYPTO_RsaPrivateKey *key); @@ -1928,7 +1906,7 @@ GNUNET_CRYPTO_rsa_private_key_dup ( * @retur NULL on error, otherwise the public key */ struct GNUNET_CRYPTO_RsaPublicKey * -GNUNET_CRYPTO_rsa_private_key_get_public ( +GNUNET_CRYPTO_rsa_private_key_get_public( const struct GNUNET_CRYPTO_RsaPrivateKey *priv); @@ -1939,8 +1917,8 @@ GNUNET_CRYPTO_rsa_private_key_get_public ( * @param hc where to store the hash code */ void -GNUNET_CRYPTO_rsa_public_key_hash (const struct GNUNET_CRYPTO_RsaPublicKey *key, - struct GNUNET_HashCode *hc); +GNUNET_CRYPTO_rsa_public_key_hash(const struct GNUNET_CRYPTO_RsaPublicKey *key, + struct GNUNET_HashCode *hc); /** @@ -1950,7 +1928,7 @@ GNUNET_CRYPTO_rsa_public_key_hash (const struct GNUNET_CRYPTO_RsaPublicKey *key, * @return length of the key in bits */ unsigned int -GNUNET_CRYPTO_rsa_public_key_len (const struct GNUNET_CRYPTO_RsaPublicKey *key); +GNUNET_CRYPTO_rsa_public_key_len(const struct GNUNET_CRYPTO_RsaPublicKey *key); /** @@ -1959,7 +1937,7 @@ GNUNET_CRYPTO_rsa_public_key_len (const struct GNUNET_CRYPTO_RsaPublicKey *key); * @param key pointer to the memory to free */ void -GNUNET_CRYPTO_rsa_public_key_free (struct GNUNET_CRYPTO_RsaPublicKey *key); +GNUNET_CRYPTO_rsa_public_key_free(struct GNUNET_CRYPTO_RsaPublicKey *key); /** @@ -1971,7 +1949,7 @@ GNUNET_CRYPTO_rsa_public_key_free (struct GNUNET_CRYPTO_RsaPublicKey *key); * @return size of memory allocated in @a buffer */ size_t -GNUNET_CRYPTO_rsa_public_key_encode ( +GNUNET_CRYPTO_rsa_public_key_encode( const struct GNUNET_CRYPTO_RsaPublicKey *key, char **buffer); @@ -1985,7 +1963,7 @@ GNUNET_CRYPTO_rsa_public_key_encode ( * @return NULL on error */ struct GNUNET_CRYPTO_RsaPublicKey * -GNUNET_CRYPTO_rsa_public_key_decode (const char *buf, size_t len); +GNUNET_CRYPTO_rsa_public_key_decode(const char *buf, size_t len); /** @@ -1995,7 +1973,7 @@ GNUNET_CRYPTO_rsa_public_key_decode (const char *buf, size_t len); * @return the duplicate key; NULL upon error */ struct GNUNET_CRYPTO_RsaPublicKey * -GNUNET_CRYPTO_rsa_public_key_dup (const struct GNUNET_CRYPTO_RsaPublicKey *key); +GNUNET_CRYPTO_rsa_public_key_dup(const struct GNUNET_CRYPTO_RsaPublicKey *key); /** @@ -2006,8 +1984,8 @@ GNUNET_CRYPTO_rsa_public_key_dup (const struct GNUNET_CRYPTO_RsaPublicKey *key); * @return 0 if the two are equal */ int -GNUNET_CRYPTO_rsa_signature_cmp (struct GNUNET_CRYPTO_RsaSignature *s1, - struct GNUNET_CRYPTO_RsaSignature *s2); +GNUNET_CRYPTO_rsa_signature_cmp(struct GNUNET_CRYPTO_RsaSignature *s1, + struct GNUNET_CRYPTO_RsaSignature *s2); /** * Compare the values of two private keys. @@ -2017,8 +1995,8 @@ GNUNET_CRYPTO_rsa_signature_cmp (struct GNUNET_CRYPTO_RsaSignature *s1, * @return 0 if the two are equal */ int -GNUNET_CRYPTO_rsa_private_key_cmp (struct GNUNET_CRYPTO_RsaPrivateKey *p1, - struct GNUNET_CRYPTO_RsaPrivateKey *p2); +GNUNET_CRYPTO_rsa_private_key_cmp(struct GNUNET_CRYPTO_RsaPrivateKey *p1, + struct GNUNET_CRYPTO_RsaPrivateKey *p2); /** @@ -2029,8 +2007,8 @@ GNUNET_CRYPTO_rsa_private_key_cmp (struct GNUNET_CRYPTO_RsaPrivateKey *p1, * @return 0 if the two are equal */ int -GNUNET_CRYPTO_rsa_public_key_cmp (struct GNUNET_CRYPTO_RsaPublicKey *p1, - struct GNUNET_CRYPTO_RsaPublicKey *p2); +GNUNET_CRYPTO_rsa_public_key_cmp(struct GNUNET_CRYPTO_RsaPublicKey *p1, + struct GNUNET_CRYPTO_RsaPublicKey *p2); /** @@ -2044,11 +2022,11 @@ GNUNET_CRYPTO_rsa_public_key_cmp (struct GNUNET_CRYPTO_RsaPublicKey *p1, * @return #GNUNET_YES if successful, #GNUNET_NO if RSA key is malicious */ int -GNUNET_CRYPTO_rsa_blind (const struct GNUNET_HashCode *hash, - const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks, - struct GNUNET_CRYPTO_RsaPublicKey *pkey, - char **buf, - size_t *buf_size); +GNUNET_CRYPTO_rsa_blind(const struct GNUNET_HashCode *hash, + const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks, + struct GNUNET_CRYPTO_RsaPublicKey *pkey, + char **buf, + size_t *buf_size); /** @@ -2060,9 +2038,9 @@ GNUNET_CRYPTO_rsa_blind (const struct GNUNET_HashCode *hash, * @return NULL on error, signature on success */ struct GNUNET_CRYPTO_RsaSignature * -GNUNET_CRYPTO_rsa_sign_blinded (const struct GNUNET_CRYPTO_RsaPrivateKey *key, - const void *msg, - size_t msg_len); +GNUNET_CRYPTO_rsa_sign_blinded(const struct GNUNET_CRYPTO_RsaPrivateKey *key, + const void *msg, + size_t msg_len); /** @@ -2073,8 +2051,8 @@ GNUNET_CRYPTO_rsa_sign_blinded (const struct GNUNET_CRYPTO_RsaPrivateKey *key, * @return NULL on error, including a malicious RSA key, signature on success */ struct GNUNET_CRYPTO_RsaSignature * -GNUNET_CRYPTO_rsa_sign_fdh (const struct GNUNET_CRYPTO_RsaPrivateKey *key, - const struct GNUNET_HashCode *hash); +GNUNET_CRYPTO_rsa_sign_fdh(const struct GNUNET_CRYPTO_RsaPrivateKey *key, + const struct GNUNET_HashCode *hash); /** @@ -2083,7 +2061,7 @@ GNUNET_CRYPTO_rsa_sign_fdh (const struct GNUNET_CRYPTO_RsaPrivateKey *key, * @param sig memory to free */ void -GNUNET_CRYPTO_rsa_signature_free (struct GNUNET_CRYPTO_RsaSignature *sig); +GNUNET_CRYPTO_rsa_signature_free(struct GNUNET_CRYPTO_RsaSignature *sig); /** @@ -2094,7 +2072,7 @@ GNUNET_CRYPTO_rsa_signature_free (struct GNUNET_CRYPTO_RsaSignature *sig); * @return size of memory allocated in @a buffer */ size_t -GNUNET_CRYPTO_rsa_signature_encode ( +GNUNET_CRYPTO_rsa_signature_encode( const struct GNUNET_CRYPTO_RsaSignature *sig, char **buffer); @@ -2108,7 +2086,7 @@ GNUNET_CRYPTO_rsa_signature_encode ( * @return NULL on error */ struct GNUNET_CRYPTO_RsaSignature * -GNUNET_CRYPTO_rsa_signature_decode (const char *buf, size_t len); +GNUNET_CRYPTO_rsa_signature_decode(const char *buf, size_t len); /** @@ -2118,7 +2096,7 @@ GNUNET_CRYPTO_rsa_signature_decode (const char *buf, size_t len); * @return the duplicate key; NULL upon error */ struct GNUNET_CRYPTO_RsaSignature * -GNUNET_CRYPTO_rsa_signature_dup (const struct GNUNET_CRYPTO_RsaSignature *sig); +GNUNET_CRYPTO_rsa_signature_dup(const struct GNUNET_CRYPTO_RsaSignature *sig); /** @@ -2132,9 +2110,9 @@ GNUNET_CRYPTO_rsa_signature_dup (const struct GNUNET_CRYPTO_RsaSignature *sig); * @return unblinded signature on success, NULL if RSA key is bad or malicious. */ struct GNUNET_CRYPTO_RsaSignature * -GNUNET_CRYPTO_rsa_unblind (const struct GNUNET_CRYPTO_RsaSignature *sig, - const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks, - struct GNUNET_CRYPTO_RsaPublicKey *pkey); +GNUNET_CRYPTO_rsa_unblind(const struct GNUNET_CRYPTO_RsaSignature *sig, + const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks, + struct GNUNET_CRYPTO_RsaPublicKey *pkey); /** @@ -2147,9 +2125,9 @@ GNUNET_CRYPTO_rsa_unblind (const struct GNUNET_CRYPTO_RsaSignature *sig, * @returns #GNUNET_YES if ok, #GNUNET_NO if RSA key is malicious, #GNUNET_SYSERR if signature */ int -GNUNET_CRYPTO_rsa_verify (const struct GNUNET_HashCode *hash, - const struct GNUNET_CRYPTO_RsaSignature *sig, - const struct GNUNET_CRYPTO_RsaPublicKey *public_key); +GNUNET_CRYPTO_rsa_verify(const struct GNUNET_HashCode *hash, + const struct GNUNET_CRYPTO_RsaSignature *sig, + const struct GNUNET_CRYPTO_RsaPublicKey *public_key); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_curl_lib.h b/src/include/gnunet_curl_lib.h index e9378794e..af0e929a5 100644 --- a/src/include/gnunet_curl_lib.h +++ b/src/include/gnunet_curl_lib.h @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2014, 2015, 2016 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet + Copyright (C) 2014, 2015, 2016 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/include/gnunet_curl_lib.h * @brief library to make it easy to download JSON replies over HTTP @@ -54,9 +54,7 @@ typedef void * @brief Buffer data structure we use to buffer the HTTP download * before giving it to the JSON parser. */ -struct GNUNET_CURL_DownloadBuffer -{ - +struct GNUNET_CURL_DownloadBuffer { /** * Download buffer */ @@ -72,7 +70,6 @@ struct GNUNET_CURL_DownloadBuffer * (i.e. response too large). */ int eno; - }; @@ -91,7 +88,7 @@ typedef void * /** * Deallocate the response. - * + * * @param response object to clean */ typedef void @@ -106,8 +103,8 @@ typedef void * @return library context */ struct GNUNET_CURL_Context * -GNUNET_CURL_init (GNUNET_CURL_RescheduleCallback cb, - void *cb_cls); +GNUNET_CURL_init(GNUNET_CURL_RescheduleCallback cb, + void *cb_cls); /** @@ -137,12 +134,12 @@ GNUNET_CURL_init (GNUNET_CURL_RescheduleCallback cb, * proceed immediately with #GNUNET_CURL_perform(). */ void -GNUNET_CURL_get_select_info (struct GNUNET_CURL_Context *ctx, - fd_set *read_fd_set, - fd_set *write_fd_set, - fd_set *except_fd_set, - int *max_fd, - long *timeout); +GNUNET_CURL_get_select_info(struct GNUNET_CURL_Context *ctx, + fd_set *read_fd_set, + fd_set *write_fd_set, + fd_set *except_fd_set, + int *max_fd, + long *timeout); /** @@ -153,8 +150,8 @@ GNUNET_CURL_get_select_info (struct GNUNET_CURL_Context *ctx, * @return #GNUNET_OK if no errors occurred, #GNUNET_SYSERR otherwise. */ int -GNUNET_CURL_append_header (struct GNUNET_CURL_Context *ctx, - const char *header); +GNUNET_CURL_append_header(struct GNUNET_CURL_Context *ctx, + const char *header); /** * Run the main event loop for the CURL interaction. @@ -162,7 +159,7 @@ GNUNET_CURL_append_header (struct GNUNET_CURL_Context *ctx, * @param ctx the library context */ void -GNUNET_CURL_perform (struct GNUNET_CURL_Context *ctx); +GNUNET_CURL_perform(struct GNUNET_CURL_Context *ctx); /** @@ -174,9 +171,9 @@ GNUNET_CURL_perform (struct GNUNET_CURL_Context *ctx); * @param rc cleans/frees the response */ void -GNUNET_CURL_perform2 (struct GNUNET_CURL_Context *ctx, - GNUNET_CURL_RawParser rp, - GNUNET_CURL_ResponseCleaner rc); +GNUNET_CURL_perform2(struct GNUNET_CURL_Context *ctx, + GNUNET_CURL_RawParser rp, + GNUNET_CURL_ResponseCleaner rc); /** * Cleanup library initialisation resources. This function should be called @@ -186,7 +183,7 @@ GNUNET_CURL_perform2 (struct GNUNET_CURL_Context *ctx, * @param ctx the library context */ void -GNUNET_CURL_fini (struct GNUNET_CURL_Context *ctx); +GNUNET_CURL_fini(struct GNUNET_CURL_Context *ctx); /** @@ -224,11 +221,11 @@ typedef void * @return NULL on error (in this case, @eh is still released!) */ struct GNUNET_CURL_Job * -GNUNET_CURL_job_add (struct GNUNET_CURL_Context *ctx, - CURL *eh, - int add_json, - GNUNET_CURL_JobCompletionCallback jcc, - void *jcc_cls); +GNUNET_CURL_job_add(struct GNUNET_CURL_Context *ctx, + CURL *eh, + int add_json, + GNUNET_CURL_JobCompletionCallback jcc, + void *jcc_cls); /** @@ -248,7 +245,7 @@ GNUNET_CURL_job_add (struct GNUNET_CURL_Context *ctx, * @return NULL on error (in this case, @eh is still released!) */ struct GNUNET_CURL_Job * -GNUNET_CURL_job_add2 (struct GNUNET_CURL_Context *ctx, +GNUNET_CURL_job_add2(struct GNUNET_CURL_Context *ctx, CURL *eh, const struct curl_slist *job_headers, GNUNET_CURL_JobCompletionCallback jcc, @@ -262,7 +259,7 @@ GNUNET_CURL_job_add2 (struct GNUNET_CURL_Context *ctx, * @param job job to cancel */ void -GNUNET_CURL_job_cancel (struct GNUNET_CURL_Job *job); +GNUNET_CURL_job_cancel(struct GNUNET_CURL_Job *job); /* ******* GNUnet SCHEDULER integration ************ */ @@ -281,7 +278,7 @@ struct GNUNET_CURL_RescheduleContext; * @return closure for #GNUNET_CURL_gnunet_scheduler_reschedule(). */ struct GNUNET_CURL_RescheduleContext * -GNUNET_CURL_gnunet_rc_create (struct GNUNET_CURL_Context *ctx); +GNUNET_CURL_gnunet_rc_create(struct GNUNET_CURL_Context *ctx); /** * Initialize reschedule context; with custom response parser @@ -290,9 +287,9 @@ GNUNET_CURL_gnunet_rc_create (struct GNUNET_CURL_Context *ctx); * @return closure for #GNUNET_CURL_gnunet_scheduler_reschedule(). */ struct GNUNET_CURL_RescheduleContext * -GNUNET_CURL_gnunet_rc_create_with_parser (struct GNUNET_CURL_Context *ctx, - GNUNET_CURL_RawParser rp, - GNUNET_CURL_ResponseCleaner rc); +GNUNET_CURL_gnunet_rc_create_with_parser(struct GNUNET_CURL_Context *ctx, + GNUNET_CURL_RawParser rp, + GNUNET_CURL_ResponseCleaner rc); /** @@ -301,7 +298,7 @@ GNUNET_CURL_gnunet_rc_create_with_parser (struct GNUNET_CURL_Context *ctx, * @param rc context to destroy */ void -GNUNET_CURL_gnunet_rc_destroy (struct GNUNET_CURL_RescheduleContext *rc); +GNUNET_CURL_gnunet_rc_destroy(struct GNUNET_CURL_RescheduleContext *rc); /** @@ -314,7 +311,7 @@ GNUNET_CURL_gnunet_rc_destroy (struct GNUNET_CURL_RescheduleContext *rc); * (pointer to a pointer!) */ void -GNUNET_CURL_gnunet_scheduler_reschedule (void *cls); +GNUNET_CURL_gnunet_scheduler_reschedule(void *cls); /** @@ -324,7 +321,7 @@ GNUNET_CURL_gnunet_scheduler_reschedule (void *cls); * @param header_name name of the header to send. */ void -GNUNET_CURL_enable_async_scope_header (struct GNUNET_CURL_Context *ctx, const char *header_name); +GNUNET_CURL_enable_async_scope_header(struct GNUNET_CURL_Context *ctx, const char *header_name); #endif diff --git a/src/include/gnunet_datacache_lib.h b/src/include/gnunet_datacache_lib.h index 568e60d42..19de3ceea 100644 --- a/src/include/gnunet_datacache_lib.h +++ b/src/include/gnunet_datacache_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -63,8 +63,8 @@ struct GNUNET_DATACACHE_Handle; * @return handle to use to access the service */ struct GNUNET_DATACACHE_Handle * -GNUNET_DATACACHE_create (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section); +GNUNET_DATACACHE_create(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section); /** @@ -73,7 +73,7 @@ GNUNET_DATACACHE_create (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param h handle to the datastore */ void -GNUNET_DATACACHE_destroy (struct GNUNET_DATACACHE_Handle *h); +GNUNET_DATACACHE_destroy(struct GNUNET_DATACACHE_Handle *h); /** @@ -115,15 +115,15 @@ typedef int * @return #GNUNET_OK on success, #GNUNET_SYSERR on error, #GNUNET_NO if duplicate */ int -GNUNET_DATACACHE_put (struct GNUNET_DATACACHE_Handle *h, - const struct GNUNET_HashCode *key, - uint32_t xor_distance, - size_t data_size, - const char *data, - enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute discard_time, - unsigned int path_info_len, - const struct GNUNET_PeerIdentity *path_info); +GNUNET_DATACACHE_put(struct GNUNET_DATACACHE_Handle *h, + const struct GNUNET_HashCode *key, + uint32_t xor_distance, + size_t data_size, + const char *data, + enum GNUNET_BLOCK_Type type, + struct GNUNET_TIME_Absolute discard_time, + unsigned int path_info_len, + const struct GNUNET_PeerIdentity *path_info); /** @@ -138,11 +138,11 @@ GNUNET_DATACACHE_put (struct GNUNET_DATACACHE_Handle *h, * @return the number of results found */ unsigned int -GNUNET_DATACACHE_get (struct GNUNET_DATACACHE_Handle *h, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls); +GNUNET_DATACACHE_get(struct GNUNET_DATACACHE_Handle *h, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls); /** @@ -154,9 +154,9 @@ GNUNET_DATACACHE_get (struct GNUNET_DATACACHE_Handle *h, * @return the number of results found (zero or 1) */ unsigned int -GNUNET_DATACACHE_get_random (struct GNUNET_DATACACHE_Handle *h, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls); +GNUNET_DATACACHE_get_random(struct GNUNET_DATACACHE_Handle *h, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls); /** @@ -173,11 +173,11 @@ GNUNET_DATACACHE_get_random (struct GNUNET_DATACACHE_Handle *h, * @return the number of results found */ unsigned int -GNUNET_DATACACHE_get_closest (struct GNUNET_DATACACHE_Handle *h, - const struct GNUNET_HashCode *key, - unsigned int num_results, - GNUNET_DATACACHE_Iterator iter, - void *iter_cls); +GNUNET_DATACACHE_get_closest(struct GNUNET_DATACACHE_Handle *h, + const struct GNUNET_HashCode *key, + unsigned int num_results, + GNUNET_DATACACHE_Iterator iter, + void *iter_cls); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_datacache_plugin.h b/src/include/gnunet_datacache_plugin.h index 5a4e6dc0d..b4e6dbe8e 100644 --- a/src/include/gnunet_datacache_plugin.h +++ b/src/include/gnunet_datacache_plugin.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -61,9 +61,7 @@ typedef void * of this type as the first and only argument to the * entry point of each datastore plugin. */ -struct GNUNET_DATACACHE_PluginEnvironment -{ - +struct GNUNET_DATACACHE_PluginEnvironment { /** * Configuration to use. */ @@ -89,16 +87,13 @@ struct GNUNET_DATACACHE_PluginEnvironment * How much space are we allowed to use? */ unsigned long long quota; - }; /** * @brief struct returned by the initialization function of the plugin */ -struct GNUNET_DATACACHE_PluginFunctions -{ - +struct GNUNET_DATACACHE_PluginFunctions { /** * Closure to pass to all plugin functions. */ @@ -122,11 +117,11 @@ struct GNUNET_DATACACHE_PluginFunctions const struct GNUNET_HashCode *key, uint32_t xor_distance, size_t size, - const char *data, + const char *data, enum GNUNET_BLOCK_Type type, - struct GNUNET_TIME_Absolute discard_time, - unsigned int path_info_len, - const struct GNUNET_PeerIdentity *path_info); + struct GNUNET_TIME_Absolute discard_time, + unsigned int path_info_len, + const struct GNUNET_PeerIdentity *path_info); /** * Iterate over the results for a particular key @@ -185,7 +180,6 @@ struct GNUNET_DATACACHE_PluginFunctions unsigned int num_results, GNUNET_DATACACHE_Iterator iter, void *iter_cls); - }; diff --git a/src/include/gnunet_datastore_plugin.h b/src/include/gnunet_datastore_plugin.h index ccd604845..95b12f7ad 100644 --- a/src/include/gnunet_datastore_plugin.h +++ b/src/include/gnunet_datastore_plugin.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -55,7 +55,7 @@ */ typedef void (*GNUNET_DATASTORE_DiskUtilizationChange) (void *cls, - int delta); + int delta); /** @@ -63,8 +63,7 @@ typedef void * of this type as the first and only argument to the * entry point of each datastore plugin. */ -struct GNUNET_DATASTORE_PluginEnvironment -{ +struct GNUNET_DATASTORE_PluginEnvironment { /** * Configuration to use. */ @@ -79,7 +78,6 @@ struct GNUNET_DATASTORE_PluginEnvironment * Closure. */ void *cls; - }; @@ -125,7 +123,7 @@ typedef int */ typedef void (*PluginEstimateSize) (void *cls, - unsigned long long *estimate); + unsigned long long *estimate); /** @@ -140,10 +138,10 @@ typedef void */ typedef void (*PluginPutCont) (void *cls, - const struct GNUNET_HashCode *key, - uint32_t size, - int status, - const char *msg); + const struct GNUNET_HashCode *key, + uint32_t size, + int status, + const char *msg); /** @@ -188,8 +186,8 @@ typedef void */ typedef void (*PluginKeyProcessor) (void *cls, - const struct GNUNET_HashCode *key, - unsigned int count); + const struct GNUNET_HashCode *key, + unsigned int count); /** @@ -201,7 +199,7 @@ typedef void */ typedef void (*PluginGetKeys) (void *cls, - PluginKeyProcessor proc, + PluginKeyProcessor proc, void *proc_cls); @@ -277,8 +275,8 @@ typedef void */ typedef void (*PluginGetRandom) (void *cls, - PluginDatumProcessor proc, - void *proc_cls); + PluginDatumProcessor proc, + void *proc_cls); /** @@ -313,9 +311,7 @@ typedef void * Each plugin is required to return a pointer to a struct of this * type as the return value from its entry point. */ -struct GNUNET_DATASTORE_PluginFunctions -{ - +struct GNUNET_DATASTORE_PluginFunctions { /** * Closure to use for all of the following callbacks * (except "next_request"). diff --git a/src/include/gnunet_datastore_service.h b/src/include/gnunet_datastore_service.h index b5b9d4306..e4cd4a915 100644 --- a/src/include/gnunet_datastore_service.h +++ b/src/include/gnunet_datastore_service.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -72,7 +72,7 @@ struct GNUNET_DATASTORE_Handle; * @return handle to use to access the service */ struct GNUNET_DATASTORE_Handle * -GNUNET_DATASTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_DATASTORE_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -83,8 +83,8 @@ GNUNET_DATASTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param drop set to #GNUNET_YES to delete all data in datastore (!) */ void -GNUNET_DATASTORE_disconnect (struct GNUNET_DATASTORE_Handle *h, - int drop); +GNUNET_DATASTORE_disconnect(struct GNUNET_DATASTORE_Handle *h, + int drop); /** @@ -123,11 +123,11 @@ typedef void * (or rather, will already have been invoked) */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_reserve (struct GNUNET_DATASTORE_Handle *h, - uint64_t amount, - uint32_t entries, - GNUNET_DATASTORE_ContinuationWithStatus cont, - void *cont_cls); +GNUNET_DATASTORE_reserve(struct GNUNET_DATASTORE_Handle *h, + uint64_t amount, + uint32_t entries, + GNUNET_DATASTORE_ContinuationWithStatus cont, + void *cont_cls); /** @@ -156,20 +156,20 @@ GNUNET_DATASTORE_reserve (struct GNUNET_DATASTORE_Handle *h, * (or rather, will already have been invoked) */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_put (struct GNUNET_DATASTORE_Handle *h, - uint32_t rid, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - enum GNUNET_BLOCK_Type type, - uint32_t priority, - uint32_t anonymity, - uint32_t replication, - struct GNUNET_TIME_Absolute expiration, - unsigned int queue_priority, - unsigned int max_queue_size, - GNUNET_DATASTORE_ContinuationWithStatus cont, - void *cont_cls); +GNUNET_DATASTORE_put(struct GNUNET_DATASTORE_Handle *h, + uint32_t rid, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + enum GNUNET_BLOCK_Type type, + uint32_t priority, + uint32_t anonymity, + uint32_t replication, + struct GNUNET_TIME_Absolute expiration, + unsigned int queue_priority, + unsigned int max_queue_size, + GNUNET_DATASTORE_ContinuationWithStatus cont, + void *cont_cls); /** @@ -193,11 +193,11 @@ GNUNET_DATASTORE_put (struct GNUNET_DATASTORE_Handle *h, * (or rather, will already have been invoked) */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_release_reserve (struct GNUNET_DATASTORE_Handle *h, - uint32_t rid, unsigned int queue_priority, - unsigned int max_queue_size, - GNUNET_DATASTORE_ContinuationWithStatus cont, - void *cont_cls); +GNUNET_DATASTORE_release_reserve(struct GNUNET_DATASTORE_Handle *h, + uint32_t rid, unsigned int queue_priority, + unsigned int max_queue_size, + GNUNET_DATASTORE_ContinuationWithStatus cont, + void *cont_cls); /** @@ -220,14 +220,14 @@ GNUNET_DATASTORE_release_reserve (struct GNUNET_DATASTORE_Handle *h, * (or rather, will already have been invoked) */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_remove (struct GNUNET_DATASTORE_Handle *h, - const struct GNUNET_HashCode *key, - size_t size, - const void *data, - unsigned int queue_priority, - unsigned int max_queue_size, - GNUNET_DATASTORE_ContinuationWithStatus cont, - void *cont_cls); +GNUNET_DATASTORE_remove(struct GNUNET_DATASTORE_Handle *h, + const struct GNUNET_HashCode *key, + size_t size, + const void *data, + unsigned int queue_priority, + unsigned int max_queue_size, + GNUNET_DATASTORE_ContinuationWithStatus cont, + void *cont_cls); /** @@ -277,15 +277,15 @@ typedef void * cancel */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_get_key (struct GNUNET_DATASTORE_Handle *h, - uint64_t next_uid, - bool random, - const struct GNUNET_HashCode *key, - enum GNUNET_BLOCK_Type type, - unsigned int queue_priority, - unsigned int max_queue_size, - GNUNET_DATASTORE_DatumProcessor proc, - void *proc_cls); +GNUNET_DATASTORE_get_key(struct GNUNET_DATASTORE_Handle *h, + uint64_t next_uid, + bool random, + const struct GNUNET_HashCode *key, + enum GNUNET_BLOCK_Type type, + unsigned int queue_priority, + unsigned int max_queue_size, + GNUNET_DATASTORE_DatumProcessor proc, + void *proc_cls); /** @@ -305,13 +305,13 @@ GNUNET_DATASTORE_get_key (struct GNUNET_DATASTORE_Handle *h, * cancel */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_get_zero_anonymity (struct GNUNET_DATASTORE_Handle *h, - uint64_t next_uid, - unsigned int queue_priority, - unsigned int max_queue_size, - enum GNUNET_BLOCK_Type type, - GNUNET_DATASTORE_DatumProcessor proc, - void *proc_cls); +GNUNET_DATASTORE_get_zero_anonymity(struct GNUNET_DATASTORE_Handle *h, + uint64_t next_uid, + unsigned int queue_priority, + unsigned int max_queue_size, + enum GNUNET_BLOCK_Type type, + GNUNET_DATASTORE_DatumProcessor proc, + void *proc_cls); /** @@ -333,11 +333,11 @@ GNUNET_DATASTORE_get_zero_anonymity (struct GNUNET_DATASTORE_Handle *h, * cancel */ struct GNUNET_DATASTORE_QueueEntry * -GNUNET_DATASTORE_get_for_replication (struct GNUNET_DATASTORE_Handle *h, - unsigned int queue_priority, - unsigned int max_queue_size, - GNUNET_DATASTORE_DatumProcessor proc, - void *proc_cls); +GNUNET_DATASTORE_get_for_replication(struct GNUNET_DATASTORE_Handle *h, + unsigned int queue_priority, + unsigned int max_queue_size, + GNUNET_DATASTORE_DatumProcessor proc, + void *proc_cls); @@ -348,7 +348,7 @@ GNUNET_DATASTORE_get_for_replication (struct GNUNET_DATASTORE_Handle *h, * @param qe operation to cancel */ void -GNUNET_DATASTORE_cancel (struct GNUNET_DATASTORE_QueueEntry *qe); +GNUNET_DATASTORE_cancel(struct GNUNET_DATASTORE_QueueEntry *qe); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_db_lib.h b/src/include/gnunet_db_lib.h index ea3b8d519..c7568c934 100644 --- a/src/include/gnunet_db_lib.h +++ b/src/include/gnunet_db_lib.h @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2017 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2017 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file include/gnunet_db_lib.h * @brief shared defintions for transactional databases @@ -31,8 +31,7 @@ * Can be combined with a function that returns the number * of results, so all non-negative values indicate success. */ -enum GNUNET_DB_QueryStatus -{ +enum GNUNET_DB_QueryStatus { /** * A hard error occurred, retrying will not help. */ @@ -57,9 +56,8 @@ enum GNUNET_DB_QueryStatus */ GNUNET_DB_STATUS_SUCCESS_ONE_RESULT = 1 - /* Larger values may be returned for SELECT statements - that returned more than one result. */ - + /* Larger values may be returned for SELECT statements + that returned more than one result. */ }; #endif diff --git a/src/include/gnunet_dht_service.h b/src/include/gnunet_dht_service.h index d9bbccbdf..e22d2b5df 100644 --- a/src/include/gnunet_dht_service.h +++ b/src/include/gnunet_dht_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -74,8 +74,7 @@ struct GNUNET_DHT_FindPeerHandle; /** * Options for routing. */ -enum GNUNET_DHT_RouteOption -{ +enum GNUNET_DHT_RouteOption { /** * Default. Do nothing special. */ @@ -119,8 +118,8 @@ enum GNUNET_DHT_RouteOption * @return NULL on error */ struct GNUNET_DHT_Handle * -GNUNET_DHT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - unsigned int ht_len); +GNUNET_DHT_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + unsigned int ht_len); /** @@ -129,7 +128,7 @@ GNUNET_DHT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param handle connection to shut down */ void -GNUNET_DHT_disconnect (struct GNUNET_DHT_Handle *handle); +GNUNET_DHT_disconnect(struct GNUNET_DHT_Handle *handle); /* *************** Standard API: get and put ******************* */ @@ -160,16 +159,16 @@ struct GNUNET_DHT_PutHandle; * (size too big) */ struct GNUNET_DHT_PutHandle * -GNUNET_DHT_put (struct GNUNET_DHT_Handle *handle, - const struct GNUNET_HashCode *key, - uint32_t desired_replication_level, - enum GNUNET_DHT_RouteOption options, - enum GNUNET_BLOCK_Type type, - size_t size, - const void *data, - struct GNUNET_TIME_Absolute exp, - GNUNET_SCHEDULER_TaskCallback cont, - void *cont_cls); +GNUNET_DHT_put(struct GNUNET_DHT_Handle *handle, + const struct GNUNET_HashCode *key, + uint32_t desired_replication_level, + enum GNUNET_DHT_RouteOption options, + enum GNUNET_BLOCK_Type type, + size_t size, + const void *data, + struct GNUNET_TIME_Absolute exp, + GNUNET_SCHEDULER_TaskCallback cont, + void *cont_cls); /** @@ -184,7 +183,7 @@ GNUNET_DHT_put (struct GNUNET_DHT_Handle *handle, * @param ph put operation to cancel ('cont' will no longer be called) */ void -GNUNET_DHT_put_cancel (struct GNUNET_DHT_PutHandle *ph); +GNUNET_DHT_put_cancel(struct GNUNET_DHT_PutHandle *ph); /** @@ -234,15 +233,15 @@ typedef void * @return handle to stop the async get */ struct GNUNET_DHT_GetHandle * -GNUNET_DHT_get_start (struct GNUNET_DHT_Handle *handle, - enum GNUNET_BLOCK_Type type, - const struct GNUNET_HashCode *key, - uint32_t desired_replication_level, - enum GNUNET_DHT_RouteOption options, - const void *xquery, - size_t xquery_size, - GNUNET_DHT_GetIterator iter, - void *iter_cls); +GNUNET_DHT_get_start(struct GNUNET_DHT_Handle *handle, + enum GNUNET_BLOCK_Type type, + const struct GNUNET_HashCode *key, + uint32_t desired_replication_level, + enum GNUNET_DHT_RouteOption options, + const void *xquery, + size_t xquery_size, + GNUNET_DHT_GetIterator iter, + void *iter_cls); /** @@ -256,9 +255,9 @@ GNUNET_DHT_get_start (struct GNUNET_DHT_Handle *handle, * to be blocked */ void -GNUNET_DHT_get_filter_known_results (struct GNUNET_DHT_GetHandle *get_handle, - unsigned int num_results, - const struct GNUNET_HashCode *results); +GNUNET_DHT_get_filter_known_results(struct GNUNET_DHT_GetHandle *get_handle, + unsigned int num_results, + const struct GNUNET_HashCode *results); /** * Stop async DHT-get. Frees associated resources. @@ -266,7 +265,7 @@ GNUNET_DHT_get_filter_known_results (struct GNUNET_DHT_GetHandle *get_handle, * @param get_handle GET operation to stop. */ void -GNUNET_DHT_get_stop (struct GNUNET_DHT_GetHandle *get_handle); +GNUNET_DHT_get_stop(struct GNUNET_DHT_GetHandle *get_handle); /* *************** Extended API: monitor ******************* */ @@ -369,13 +368,13 @@ typedef void * @return Handle to stop monitoring. */ struct GNUNET_DHT_MonitorHandle * -GNUNET_DHT_monitor_start (struct GNUNET_DHT_Handle *handle, - enum GNUNET_BLOCK_Type type, - const struct GNUNET_HashCode *key, - GNUNET_DHT_MonitorGetCB get_cb, - GNUNET_DHT_MonitorGetRespCB get_resp_cb, - GNUNET_DHT_MonitorPutCB put_cb, - void *cb_cls); +GNUNET_DHT_monitor_start(struct GNUNET_DHT_Handle *handle, + enum GNUNET_BLOCK_Type type, + const struct GNUNET_HashCode *key, + GNUNET_DHT_MonitorGetCB get_cb, + GNUNET_DHT_MonitorGetRespCB get_resp_cb, + GNUNET_DHT_MonitorPutCB put_cb, + void *cb_cls); /** @@ -386,7 +385,7 @@ GNUNET_DHT_monitor_start (struct GNUNET_DHT_Handle *handle, * #GNUNET_DHT_monitor_start(). */ void -GNUNET_DHT_monitor_stop (struct GNUNET_DHT_MonitorHandle *handle); +GNUNET_DHT_monitor_stop(struct GNUNET_DHT_MonitorHandle *handle); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_disk_lib.h b/src/include/gnunet_disk_lib.h index 367789722..f693615f1 100644 --- a/src/include/gnunet_disk_lib.h +++ b/src/include/gnunet_disk_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff * @@ -38,8 +38,7 @@ struct GNUNET_DISK_PipeHandle; /** * Type of a handle. */ -enum GNUNET_FILE_Type -{ +enum GNUNET_FILE_Type { /** * Handle represents an event. */ @@ -59,9 +58,7 @@ enum GNUNET_FILE_Type /** * Handle used to access files (and pipes). */ -struct GNUNET_DISK_FileHandle -{ - +struct GNUNET_DISK_FileHandle { #if WINDOWS /** * File handle under W32. @@ -83,12 +80,10 @@ struct GNUNET_DISK_FileHandle */ OVERLAPPED *oOverlapWrite; #else - /** * File handle on other OSes. */ int fd; - #endif }; @@ -113,9 +108,7 @@ extern "C" /** * Specifies how a file should be opened. */ -enum GNUNET_DISK_OpenFlags -{ - +enum GNUNET_DISK_OpenFlags { /** * Open the file for reading */ @@ -155,8 +148,7 @@ enum GNUNET_DISK_OpenFlags /** * Specifies what type of memory map is desired. */ -enum GNUNET_DISK_MapType -{ +enum GNUNET_DISK_MapType { /** * Read-only memory map. */ @@ -177,8 +169,7 @@ enum GNUNET_DISK_MapType /** * File access permissions, UNIX-style. */ -enum GNUNET_DISK_AccessPermissions -{ +enum GNUNET_DISK_AccessPermissions { /** * Nobody is allowed to do anything to the file. */ @@ -235,8 +226,7 @@ enum GNUNET_DISK_AccessPermissions * Constants for specifying how to seek. Do not change values or order, * some of the code depends on the specific numeric values! */ -enum GNUNET_DISK_Seek -{ +enum GNUNET_DISK_Seek { /** * Seek an absolute position (from the start of the file). */ @@ -257,8 +247,7 @@ enum GNUNET_DISK_Seek /** * Enumeration identifying the two ends of a pipe. */ -enum GNUNET_DISK_PipeEnd -{ +enum GNUNET_DISK_PipeEnd { /** * The reading-end of a pipe. */ @@ -278,7 +267,7 @@ enum GNUNET_DISK_PipeEnd * @return #GNUNET_YES if invalid, #GNUNET_NO if valid */ int -GNUNET_DISK_handle_invalid (const struct GNUNET_DISK_FileHandle *h); +GNUNET_DISK_handle_invalid(const struct GNUNET_DISK_FileHandle *h); /** @@ -290,7 +279,7 @@ GNUNET_DISK_handle_invalid (const struct GNUNET_DISK_FileHandle *h); * else (will print an error message in that case, too). */ int -GNUNET_DISK_file_test (const char *fil); +GNUNET_DISK_file_test(const char *fil); /** @@ -301,7 +290,7 @@ GNUNET_DISK_file_test (const char *fil); * @param fil name of the file to back up */ void -GNUNET_DISK_file_backup (const char *fil); +GNUNET_DISK_file_backup(const char *fil); /** @@ -312,8 +301,8 @@ GNUNET_DISK_file_backup (const char *fil); * @return the new position on success, GNUNET_SYSERR otherwise */ off_t -GNUNET_DISK_file_seek (const struct GNUNET_DISK_FileHandle *h, off_t offset, - enum GNUNET_DISK_Seek whence); +GNUNET_DISK_file_seek(const struct GNUNET_DISK_FileHandle *h, off_t offset, + enum GNUNET_DISK_Seek whence); /** @@ -331,10 +320,10 @@ GNUNET_DISK_file_seek (const struct GNUNET_DISK_FileHandle *h, off_t offset, * @return #GNUNET_SYSERR on error, #GNUNET_OK on success */ int -GNUNET_DISK_file_size (const char *filename, - uint64_t *size, - int include_symbolic_links, - int single_file_mode); +GNUNET_DISK_file_size(const char *filename, + uint64_t *size, + int include_symbolic_links, + int single_file_mode); /** @@ -353,9 +342,9 @@ GNUNET_DISK_file_size (const char *filename, * @return #GNUNET_OK on success */ int -GNUNET_DISK_file_get_identifiers (const char *filename, - uint64_t *dev, - uint64_t *ino); +GNUNET_DISK_file_get_identifiers(const char *filename, + uint64_t *dev, + uint64_t *ino); /** @@ -370,7 +359,7 @@ GNUNET_DISK_file_get_identifiers (const char *filename, * file on disk in directory for temporary files */ char * -GNUNET_DISK_mktemp (const char *t); +GNUNET_DISK_mktemp(const char *t); /** @@ -383,7 +372,7 @@ GNUNET_DISK_mktemp (const char *t); * @return NULL on error, otherwise name of freshly created directory */ char * -GNUNET_DISK_mkdtemp (const char *t); +GNUNET_DISK_mkdtemp(const char *t); /** @@ -399,9 +388,9 @@ GNUNET_DISK_mkdtemp (const char *t); * @return IO handle on success, NULL on error */ struct GNUNET_DISK_FileHandle * -GNUNET_DISK_file_open (const char *fn, - enum GNUNET_DISK_OpenFlags flags, - enum GNUNET_DISK_AccessPermissions perm); +GNUNET_DISK_file_open(const char *fn, + enum GNUNET_DISK_OpenFlags flags, + enum GNUNET_DISK_AccessPermissions perm); /** @@ -412,8 +401,8 @@ GNUNET_DISK_file_open (const char *fn, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_DISK_file_handle_size (struct GNUNET_DISK_FileHandle *fh, - off_t *size); +GNUNET_DISK_file_handle_size(struct GNUNET_DISK_FileHandle *fh, + off_t *size); /** @@ -426,10 +415,10 @@ GNUNET_DISK_file_handle_size (struct GNUNET_DISK_FileHandle *fh, * @return handle to the new pipe, NULL on error */ struct GNUNET_DISK_PipeHandle * -GNUNET_DISK_pipe (int blocking_read, - int blocking_write, - int inherit_read, - int inherit_write); +GNUNET_DISK_pipe(int blocking_read, + int blocking_write, + int inherit_read, + int inherit_write); /** @@ -443,9 +432,9 @@ GNUNET_DISK_pipe (int blocking_read, * @return handle to the new pipe, NULL on error */ struct GNUNET_DISK_PipeHandle * -GNUNET_DISK_pipe_from_fd (int blocking_read, - int blocking_write, - int fd[2]); +GNUNET_DISK_pipe_from_fd(int blocking_read, + int blocking_write, + int fd[2]); /** @@ -454,7 +443,7 @@ GNUNET_DISK_pipe_from_fd (int blocking_read, * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p); +GNUNET_DISK_pipe_close(struct GNUNET_DISK_PipeHandle *p); /** @@ -465,8 +454,8 @@ GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p); * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_DISK_pipe_close_end (struct GNUNET_DISK_PipeHandle *p, - enum GNUNET_DISK_PipeEnd end); +GNUNET_DISK_pipe_close_end(struct GNUNET_DISK_PipeHandle *p, + enum GNUNET_DISK_PipeEnd end); /** @@ -482,8 +471,8 @@ GNUNET_DISK_pipe_close_end (struct GNUNET_DISK_PipeHandle *p, * (or if that end is not present or is closed). */ struct GNUNET_DISK_FileHandle * -GNUNET_DISK_pipe_detach_end (struct GNUNET_DISK_PipeHandle *p, - enum GNUNET_DISK_PipeEnd end); +GNUNET_DISK_pipe_detach_end(struct GNUNET_DISK_PipeHandle *p, + enum GNUNET_DISK_PipeEnd end); /** * Close an open file. @@ -492,7 +481,7 @@ GNUNET_DISK_pipe_detach_end (struct GNUNET_DISK_PipeHandle *p, * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h); +GNUNET_DISK_file_close(struct GNUNET_DISK_FileHandle *h); /** @@ -503,8 +492,8 @@ GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h); * @return handle for the respective end */ const struct GNUNET_DISK_FileHandle * -GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p, - enum GNUNET_DISK_PipeEnd n); +GNUNET_DISK_pipe_handle(const struct GNUNET_DISK_PipeHandle *p, + enum GNUNET_DISK_PipeEnd n); #if WINDOWS @@ -516,7 +505,7 @@ GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p, * @return GNUnet file handle corresponding to the W32 handle */ struct GNUNET_DISK_FileHandle * -GNUNET_DISK_get_handle_from_w32_handle (HANDLE osfh); +GNUNET_DISK_get_handle_from_w32_handle(HANDLE osfh); #endif /** @@ -529,9 +518,9 @@ GNUNET_DISK_get_handle_from_w32_handle (HANDLE osfh); * @param require_gid_match #GNUNET_YES means 770 unless @a require_uid_match is set */ void -GNUNET_DISK_fix_permissions (const char *fn, - int require_uid_match, - int require_gid_match); +GNUNET_DISK_fix_permissions(const char *fn, + int require_uid_match, + int require_gid_match); /** @@ -541,7 +530,7 @@ GNUNET_DISK_fix_permissions (const char *fn, * @return file handle corresponding to the descriptor */ struct GNUNET_DISK_FileHandle * -GNUNET_DISK_get_handle_from_int_fd (int fno); +GNUNET_DISK_get_handle_from_int_fd(int fno); /** @@ -551,7 +540,7 @@ GNUNET_DISK_get_handle_from_int_fd (int fno); * @return file handle corresponding to the descriptor */ struct GNUNET_DISK_FileHandle * -GNUNET_DISK_get_handle_from_native (FILE *fd); +GNUNET_DISK_get_handle_from_native(FILE *fd); /** @@ -563,9 +552,9 @@ GNUNET_DISK_get_handle_from_native (FILE *fd); * @return the number of bytes read on success, #GNUNET_SYSERR on failure */ ssize_t -GNUNET_DISK_file_read (const struct GNUNET_DISK_FileHandle *h, - void *result, - size_t len); +GNUNET_DISK_file_read(const struct GNUNET_DISK_FileHandle *h, + void *result, + size_t len); /** @@ -579,9 +568,9 @@ GNUNET_DISK_file_read (const struct GNUNET_DISK_FileHandle *h, * @return the number of bytes read on success, #GNUNET_SYSERR on failure */ ssize_t -GNUNET_DISK_file_read_non_blocking (const struct GNUNET_DISK_FileHandle * h, - void *result, - size_t len); +GNUNET_DISK_file_read_non_blocking(const struct GNUNET_DISK_FileHandle * h, + void *result, + size_t len); /** @@ -593,9 +582,9 @@ GNUNET_DISK_file_read_non_blocking (const struct GNUNET_DISK_FileHandle * h, * @return number of bytes read, #GNUNET_SYSERR on failure */ ssize_t -GNUNET_DISK_fn_read (const char *fn, - void *result, - size_t len); +GNUNET_DISK_fn_read(const char *fn, + void *result, + size_t len); /** @@ -607,9 +596,9 @@ GNUNET_DISK_fn_read (const char *fn, * @return number of bytes written on success, #GNUNET_SYSERR on error */ ssize_t -GNUNET_DISK_file_write (const struct GNUNET_DISK_FileHandle *h, - const void *buffer, - size_t n); +GNUNET_DISK_file_write(const struct GNUNET_DISK_FileHandle *h, + const void *buffer, + size_t n); /** @@ -621,9 +610,9 @@ GNUNET_DISK_file_write (const struct GNUNET_DISK_FileHandle *h, * @return number of bytes written on success, #GNUNET_SYSERR on error */ ssize_t -GNUNET_DISK_file_write_blocking (const struct GNUNET_DISK_FileHandle *h, - const void *buffer, - size_t n); +GNUNET_DISK_file_write_blocking(const struct GNUNET_DISK_FileHandle *h, + const void *buffer, + size_t n); /** @@ -637,10 +626,10 @@ GNUNET_DISK_file_write_blocking (const struct GNUNET_DISK_FileHandle *h, * @return number of bytes written on success, #GNUNET_SYSERR on error */ ssize_t -GNUNET_DISK_fn_write (const char *fn, - const void *buffer, - size_t n, - enum GNUNET_DISK_AccessPermissions mode); +GNUNET_DISK_fn_write(const char *fn, + const void *buffer, + size_t n, + enum GNUNET_DISK_AccessPermissions mode); /** @@ -651,8 +640,8 @@ GNUNET_DISK_fn_write (const char *fn, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_DISK_file_copy (const char *src, - const char *dst); +GNUNET_DISK_file_copy(const char *src, + const char *dst); /** @@ -664,9 +653,9 @@ GNUNET_DISK_file_copy (const char *src, * @return the number of files found, -1 on error */ int -GNUNET_DISK_directory_scan (const char *dir_name, - GNUNET_FileNameCallback callback, - void *callback_cls); +GNUNET_DISK_directory_scan(const char *dir_name, + GNUNET_FileNameCallback callback, + void *callback_cls); /** @@ -678,7 +667,7 @@ GNUNET_DISK_directory_scan (const char *dir_name, * #GNUNET_NO if directory exists but is not writeable */ int -GNUNET_DISK_directory_create_for_file (const char *filename); +GNUNET_DISK_directory_create_for_file(const char *filename); /** @@ -694,7 +683,7 @@ GNUNET_DISK_directory_create_for_file (const char *filename); * does not exist or `stat`ed */ int -GNUNET_DISK_directory_test (const char *fil, int is_readable); +GNUNET_DISK_directory_test(const char *fil, int is_readable); /** @@ -705,7 +694,7 @@ GNUNET_DISK_directory_test (const char *fil, int is_readable); * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_DISK_directory_remove (const char *filename); +GNUNET_DISK_directory_remove(const char *filename); /** @@ -716,8 +705,8 @@ GNUNET_DISK_directory_remove (const char *filename); * @param option option with the dir name to purge */ void -GNUNET_DISK_purge_cfg_dir (const char *cfg_filename, - const char *option); +GNUNET_DISK_purge_cfg_dir(const char *cfg_filename, + const char *option); /** @@ -727,7 +716,7 @@ GNUNET_DISK_purge_cfg_dir (const char *cfg_filename, * @returns #GNUNET_SYSERR on failure, #GNUNET_OK otherwise */ int -GNUNET_DISK_directory_create (const char *dir); +GNUNET_DISK_directory_create(const char *dir); /** @@ -740,9 +729,9 @@ GNUNET_DISK_directory_create (const char *dir); * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_DISK_file_lock (struct GNUNET_DISK_FileHandle *fh, - off_t lock_start, - off_t lock_end, int excl); +GNUNET_DISK_file_lock(struct GNUNET_DISK_FileHandle *fh, + off_t lock_start, + off_t lock_end, int excl); /** @@ -754,9 +743,9 @@ GNUNET_DISK_file_lock (struct GNUNET_DISK_FileHandle *fh, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_DISK_file_unlock (struct GNUNET_DISK_FileHandle *fh, - off_t unlock_start, - off_t unlock_end); +GNUNET_DISK_file_unlock(struct GNUNET_DISK_FileHandle *fh, + off_t unlock_start, + off_t unlock_end); /** @@ -764,7 +753,7 @@ GNUNET_DISK_file_unlock (struct GNUNET_DISK_FileHandle *fh, * @param fn the filename to canonicalize */ void -GNUNET_DISK_filename_canonicalize (char *fn); +GNUNET_DISK_filename_canonicalize(char *fn); /** @@ -774,8 +763,8 @@ GNUNET_DISK_filename_canonicalize (char *fn); * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure */ int -GNUNET_DISK_file_change_owner (const char *filename, - const char *user); +GNUNET_DISK_file_change_owner(const char *filename, + const char *user); /** @@ -793,10 +782,10 @@ struct GNUNET_DISK_MapHandle; * @return pointer to the mapped memory region, NULL on failure */ void * -GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h, - struct GNUNET_DISK_MapHandle **m, - enum GNUNET_DISK_MapType access, - size_t len); +GNUNET_DISK_file_map(const struct GNUNET_DISK_FileHandle *h, + struct GNUNET_DISK_MapHandle **m, + enum GNUNET_DISK_MapType access, + size_t len); /** @@ -806,7 +795,7 @@ GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h, * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h); +GNUNET_DISK_file_unmap(struct GNUNET_DISK_MapHandle *h); /** @@ -816,7 +805,7 @@ GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h); * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h); +GNUNET_DISK_file_sync(const struct GNUNET_DISK_FileHandle *h); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_dns_service.h b/src/include/gnunet_dns_service.h index d31476d87..e97429d1d 100644 --- a/src/include/gnunet_dns_service.h +++ b/src/include/gnunet_dns_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -49,9 +49,7 @@ struct GNUNET_DNS_RequestHandle; /** * Flags that specify when to call the client's handler. */ -enum GNUNET_DNS_Flags -{ - +enum GNUNET_DNS_Flags { /** * Useless option: never call the client. */ @@ -94,7 +92,6 @@ enum GNUNET_DNS_Flags * not allowed for MONITOR peers. */ GNUNET_DNS_FLAG_RESPONSE_MONITOR = 8 - }; @@ -137,7 +134,7 @@ typedef void * @param rh request that should now be forwarded */ void -GNUNET_DNS_request_forward (struct GNUNET_DNS_RequestHandle *rh); +GNUNET_DNS_request_forward(struct GNUNET_DNS_RequestHandle *rh); /** @@ -147,7 +144,7 @@ GNUNET_DNS_request_forward (struct GNUNET_DNS_RequestHandle *rh); * @param rh request that should now be dropped */ void -GNUNET_DNS_request_drop (struct GNUNET_DNS_RequestHandle *rh); +GNUNET_DNS_request_drop(struct GNUNET_DNS_RequestHandle *rh); /** @@ -161,9 +158,9 @@ GNUNET_DNS_request_drop (struct GNUNET_DNS_RequestHandle *rh); * @param reply reply data */ void -GNUNET_DNS_request_answer (struct GNUNET_DNS_RequestHandle *rh, - uint16_t reply_length, - const char *reply); +GNUNET_DNS_request_answer(struct GNUNET_DNS_RequestHandle *rh, + uint16_t reply_length, + const char *reply); /** @@ -176,10 +173,10 @@ GNUNET_DNS_request_answer (struct GNUNET_DNS_RequestHandle *rh, * @return DNS handle */ struct GNUNET_DNS_Handle * -GNUNET_DNS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - enum GNUNET_DNS_Flags flags, - GNUNET_DNS_RequestHandler rh, - void *rh_cls); +GNUNET_DNS_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + enum GNUNET_DNS_Flags flags, + GNUNET_DNS_RequestHandler rh, + void *rh_cls); /** @@ -188,7 +185,7 @@ GNUNET_DNS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param dh DNS handle */ void -GNUNET_DNS_disconnect (struct GNUNET_DNS_Handle *dh); +GNUNET_DNS_disconnect(struct GNUNET_DNS_Handle *dh); #endif diff --git a/src/include/gnunet_dnsparser_lib.h b/src/include/gnunet_dnsparser_lib.h index 6f81c8e04..bf1869b91 100644 --- a/src/include/gnunet_dnsparser_lib.h +++ b/src/include/gnunet_dnsparser_lib.h @@ -92,9 +92,7 @@ /** * A DNS query. */ -struct GNUNET_DNSPARSER_Query -{ - +struct GNUNET_DNSPARSER_Query { /** * Name of the record that the query is for (0-terminated). * In UTF-8 format. The library will convert from and to DNS-IDNA @@ -113,16 +111,13 @@ struct GNUNET_DNSPARSER_Query * See GNUNET_TUN_DNS_CLASS_*. */ uint16_t dns_traffic_class; - }; /** * Information from MX records (RFC 1035). */ -struct GNUNET_DNSPARSER_MxRecord -{ - +struct GNUNET_DNSPARSER_MxRecord { /** * Preference for this entry (lower value is higher preference). */ @@ -136,16 +131,13 @@ struct GNUNET_DNSPARSER_MxRecord * creating the DNS packet will fail. */ char *mxhost; - }; /** * Information from SRV records (RFC 2782). */ -struct GNUNET_DNSPARSER_SrvRecord -{ - +struct GNUNET_DNSPARSER_SrvRecord { /** * Hostname offering the service. * In UTF-8 format. The library will convert from and to DNS-IDNA @@ -173,15 +165,13 @@ struct GNUNET_DNSPARSER_SrvRecord * TCP or UDP port of the service. */ uint16_t port; - }; /** * DNS CERT types as defined in RFC 4398. */ -enum GNUNET_DNSPARSER_CertType -{ +enum GNUNET_DNSPARSER_CertType { /** * Reserved value */ @@ -233,8 +223,7 @@ enum GNUNET_DNSPARSER_CertType * DNSCERT algorithms as defined in http://www.iana.org/assignments/ * dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml, under dns-sec-alg-numbers-1 */ -enum GNUNET_DNSPARSER_CertAlgorithm -{ +enum GNUNET_DNSPARSER_CertAlgorithm { /** * No defined */ @@ -304,16 +293,13 @@ enum GNUNET_DNSPARSER_CertAlgorithm * ECDSA Curve P-384/SHA384 */ GNUNET_DNSPARSER_CERTALGO_ECDSA_P384SHA384 = 14 - }; /** * Information from CERT records (RFC 4034). */ -struct GNUNET_DNSPARSER_CertRecord -{ - +struct GNUNET_DNSPARSER_CertRecord { /** * Certificate type */ @@ -338,16 +324,13 @@ struct GNUNET_DNSPARSER_CertRecord * Data of the certificate. */ char *certificate_data; - }; /** * Information from SOA records (RFC 1035). */ -struct GNUNET_DNSPARSER_SoaRecord -{ - +struct GNUNET_DNSPARSER_SoaRecord { /** * The domainname of the name server that was the * original or primary source of data for this zone. @@ -395,7 +378,6 @@ struct GNUNET_DNSPARSER_SoaRecord * from this zone. */ uint32_t minimum_ttl; - }; @@ -404,8 +386,7 @@ struct GNUNET_DNSPARSER_SoaRecord * The tag is followed by the tag_len. * The value is followed by the tag for (d - tag_len - 2) bytes */ -struct GNUNET_DNSPARSER_CaaRecord -{ +struct GNUNET_DNSPARSER_CaaRecord { /** * The flags of the CAA record. */ @@ -422,9 +403,7 @@ struct GNUNET_DNSPARSER_CaaRecord /** * Binary record information (unparsed). */ -struct GNUNET_DNSPARSER_RawRecord -{ - +struct GNUNET_DNSPARSER_RawRecord { /** * Binary record data. */ @@ -440,9 +419,7 @@ struct GNUNET_DNSPARSER_RawRecord /** * A DNS response record. */ -struct GNUNET_DNSPARSER_Record -{ - +struct GNUNET_DNSPARSER_Record { /** * Name of the record that the query is for (0-terminated). * In UTF-8 format. The library will convert from and to DNS-IDNA @@ -455,9 +432,7 @@ struct GNUNET_DNSPARSER_Record /** * Payload of the record (which one of these is valid depends on the 'type'). */ - union - { - + union { /** * For NS, CNAME and PTR records, this is the uncompressed 0-terminated hostname. * In UTF-8 format. The library will convert from and to DNS-IDNA @@ -491,7 +466,6 @@ struct GNUNET_DNSPARSER_Record * Raw data for all other types. */ struct GNUNET_DNSPARSER_RawRecord raw; - } data; @@ -509,15 +483,13 @@ struct GNUNET_DNSPARSER_Record * See GNUNET_TUN_DNS_CLASS_*. */ uint16_t dns_traffic_class; - }; /** * Easy-to-process, parsed version of a DNS packet. */ -struct GNUNET_DNSPARSER_Packet -{ +struct GNUNET_DNSPARSER_Packet { /** * Array of all queries in the packet, must contain "num_queries" entries. */ @@ -567,7 +539,6 @@ struct GNUNET_DNSPARSER_Packet * DNS ID (to match replies to requests). */ uint16_t id; - }; @@ -580,7 +551,7 @@ struct GNUNET_DNSPARSER_Packet * #GNUNET_SYSERR if the label is not valid for DNS names */ int -GNUNET_DNSPARSER_check_label (const char *label); +GNUNET_DNSPARSER_check_label(const char *label); /** @@ -593,7 +564,7 @@ GNUNET_DNSPARSER_check_label (const char *label); * #GNUNET_SYSERR if the label is not valid for DNS names */ int -GNUNET_DNSPARSER_check_name (const char *name); +GNUNET_DNSPARSER_check_name(const char *name); /** @@ -605,8 +576,8 @@ GNUNET_DNSPARSER_check_name (const char *name); * @return NULL on error, otherwise the parsed packet */ struct GNUNET_DNSPARSER_Packet * -GNUNET_DNSPARSER_parse (const char *udp_payload, - size_t udp_payload_length); +GNUNET_DNSPARSER_parse(const char *udp_payload, + size_t udp_payload_length); /** @@ -615,7 +586,7 @@ GNUNET_DNSPARSER_parse (const char *udp_payload, * @param p packet to free */ void -GNUNET_DNSPARSER_free_packet (struct GNUNET_DNSPARSER_Packet *p); +GNUNET_DNSPARSER_free_packet(struct GNUNET_DNSPARSER_Packet *p); /** @@ -633,10 +604,10 @@ GNUNET_DNSPARSER_free_packet (struct GNUNET_DNSPARSER_Packet *p); * #GNUNET_OK if @a p was packed completely into @a buf */ int -GNUNET_DNSPARSER_pack (const struct GNUNET_DNSPARSER_Packet *p, - uint16_t max, - char **buf, - size_t *buf_length); +GNUNET_DNSPARSER_pack(const struct GNUNET_DNSPARSER_Packet *p, + uint16_t max, + char **buf, + size_t *buf_length); /* ***************** low-level packing API ******************** */ @@ -654,10 +625,10 @@ GNUNET_DNSPARSER_pack (const struct GNUNET_DNSPARSER_Packet *p, * #GNUNET_OK if @a name was added to @a dst */ int -GNUNET_DNSPARSER_builder_add_name (char *dst, - size_t dst_len, - size_t *off, - const char *name); +GNUNET_DNSPARSER_builder_add_name(char *dst, + size_t dst_len, + size_t *off, + const char *name); /** @@ -673,10 +644,10 @@ GNUNET_DNSPARSER_builder_add_name (char *dst, * #GNUNET_OK if @a query was added to @a dst */ int -GNUNET_DNSPARSER_builder_add_query (char *dst, - size_t dst_len, - size_t *off, - const struct GNUNET_DNSPARSER_Query *query); +GNUNET_DNSPARSER_builder_add_query(char *dst, + size_t dst_len, + size_t *off, + const struct GNUNET_DNSPARSER_Query *query); /** @@ -692,10 +663,10 @@ GNUNET_DNSPARSER_builder_add_query (char *dst, * #GNUNET_OK if @a mx was added to @a dst */ int -GNUNET_DNSPARSER_builder_add_mx (char *dst, - size_t dst_len, - size_t *off, - const struct GNUNET_DNSPARSER_MxRecord *mx); +GNUNET_DNSPARSER_builder_add_mx(char *dst, + size_t dst_len, + size_t *off, + const struct GNUNET_DNSPARSER_MxRecord *mx); /** @@ -711,10 +682,10 @@ GNUNET_DNSPARSER_builder_add_mx (char *dst, * #GNUNET_OK if @a soa was added to @a dst */ int -GNUNET_DNSPARSER_builder_add_soa (char *dst, - size_t dst_len, - size_t *off, - const struct GNUNET_DNSPARSER_SoaRecord *soa); +GNUNET_DNSPARSER_builder_add_soa(char *dst, + size_t dst_len, + size_t *off, + const struct GNUNET_DNSPARSER_SoaRecord *soa); /** @@ -730,10 +701,10 @@ GNUNET_DNSPARSER_builder_add_soa (char *dst, * #GNUNET_OK if @a soa was added to @a dst */ int -GNUNET_DNSPARSER_builder_add_cert (char *dst, - size_t dst_len, - size_t *off, - const struct GNUNET_DNSPARSER_CertRecord *cert); +GNUNET_DNSPARSER_builder_add_cert(char *dst, + size_t dst_len, + size_t *off, + const struct GNUNET_DNSPARSER_CertRecord *cert); /** @@ -749,10 +720,10 @@ GNUNET_DNSPARSER_builder_add_cert (char *dst, * #GNUNET_OK if @a srv was added to @a dst */ int -GNUNET_DNSPARSER_builder_add_srv (char *dst, - size_t dst_len, - size_t *off, - const struct GNUNET_DNSPARSER_SrvRecord *srv); +GNUNET_DNSPARSER_builder_add_srv(char *dst, + size_t dst_len, + size_t *off, + const struct GNUNET_DNSPARSER_SrvRecord *srv); /* ***************** low-level parsing API ******************** */ @@ -767,10 +738,10 @@ GNUNET_DNSPARSER_builder_add_srv (char *dst, * @return #GNUNET_OK on success, #GNUNET_SYSERR if the record is malformed */ int -GNUNET_DNSPARSER_parse_record (const char *udp_payload, - size_t udp_payload_length, - size_t *off, - struct GNUNET_DNSPARSER_Record *r); +GNUNET_DNSPARSER_parse_record(const char *udp_payload, + size_t udp_payload_length, + size_t *off, + struct GNUNET_DNSPARSER_Record *r); /** @@ -783,9 +754,9 @@ GNUNET_DNSPARSER_parse_record (const char *udp_payload, * @return name as 0-terminated C string on success, NULL if the payload is malformed */ char * -GNUNET_DNSPARSER_parse_name (const char *udp_payload, - size_t udp_payload_length, - size_t *off); +GNUNET_DNSPARSER_parse_name(const char *udp_payload, + size_t udp_payload_length, + size_t *off); /** @@ -799,10 +770,10 @@ GNUNET_DNSPARSER_parse_name (const char *udp_payload, * @return #GNUNET_OK on success, #GNUNET_SYSERR if the query is malformed */ int -GNUNET_DNSPARSER_parse_query (const char *udp_payload, - size_t udp_payload_length, - size_t *off, - struct GNUNET_DNSPARSER_Query *q); +GNUNET_DNSPARSER_parse_query(const char *udp_payload, + size_t udp_payload_length, + size_t *off, + struct GNUNET_DNSPARSER_Query *q); /** @@ -815,9 +786,9 @@ GNUNET_DNSPARSER_parse_query (const char *udp_payload, * @return the parsed SOA record, NULL on error */ struct GNUNET_DNSPARSER_SoaRecord * -GNUNET_DNSPARSER_parse_soa (const char *udp_payload, - size_t udp_payload_length, - size_t *off); +GNUNET_DNSPARSER_parse_soa(const char *udp_payload, + size_t udp_payload_length, + size_t *off); /** @@ -830,9 +801,9 @@ GNUNET_DNSPARSER_parse_soa (const char *udp_payload, * @return the parsed CERT record, NULL on error */ struct GNUNET_DNSPARSER_CertRecord * -GNUNET_DNSPARSER_parse_cert (const char *udp_payload, - size_t udp_payload_length, - size_t *off); +GNUNET_DNSPARSER_parse_cert(const char *udp_payload, + size_t udp_payload_length, + size_t *off); /** @@ -845,9 +816,9 @@ GNUNET_DNSPARSER_parse_cert (const char *udp_payload, * @return the parsed MX record, NULL on error */ struct GNUNET_DNSPARSER_MxRecord * -GNUNET_DNSPARSER_parse_mx (const char *udp_payload, - size_t udp_payload_length, - size_t *off); +GNUNET_DNSPARSER_parse_mx(const char *udp_payload, + size_t udp_payload_length, + size_t *off); /** @@ -860,9 +831,9 @@ GNUNET_DNSPARSER_parse_mx (const char *udp_payload, * @return the parsed SRV record, NULL on error */ struct GNUNET_DNSPARSER_SrvRecord * -GNUNET_DNSPARSER_parse_srv (const char *udp_payload, - size_t udp_payload_length, - size_t *off); +GNUNET_DNSPARSER_parse_srv(const char *udp_payload, + size_t udp_payload_length, + size_t *off); /* ***************** low-level duplication API ******************** */ @@ -873,7 +844,7 @@ GNUNET_DNSPARSER_parse_srv (const char *udp_payload, * @return the newly allocated record */ struct GNUNET_DNSPARSER_Record * -GNUNET_DNSPARSER_duplicate_record (const struct GNUNET_DNSPARSER_Record *r); +GNUNET_DNSPARSER_duplicate_record(const struct GNUNET_DNSPARSER_Record *r); /** @@ -883,7 +854,7 @@ GNUNET_DNSPARSER_duplicate_record (const struct GNUNET_DNSPARSER_Record *r); * @return the newly allocated record */ struct GNUNET_DNSPARSER_SoaRecord * -GNUNET_DNSPARSER_duplicate_soa_record (const struct GNUNET_DNSPARSER_SoaRecord *r); +GNUNET_DNSPARSER_duplicate_soa_record(const struct GNUNET_DNSPARSER_SoaRecord *r); /** @@ -893,7 +864,7 @@ GNUNET_DNSPARSER_duplicate_soa_record (const struct GNUNET_DNSPARSER_SoaRecord * * @return the newly allocated record */ struct GNUNET_DNSPARSER_CertRecord * -GNUNET_DNSPARSER_duplicate_cert_record (const struct GNUNET_DNSPARSER_CertRecord *r); +GNUNET_DNSPARSER_duplicate_cert_record(const struct GNUNET_DNSPARSER_CertRecord *r); /** @@ -903,7 +874,7 @@ GNUNET_DNSPARSER_duplicate_cert_record (const struct GNUNET_DNSPARSER_CertRecord * @return the newly allocated record */ struct GNUNET_DNSPARSER_MxRecord * -GNUNET_DNSPARSER_duplicate_mx_record (const struct GNUNET_DNSPARSER_MxRecord *r); +GNUNET_DNSPARSER_duplicate_mx_record(const struct GNUNET_DNSPARSER_MxRecord *r); /** @@ -913,7 +884,7 @@ GNUNET_DNSPARSER_duplicate_mx_record (const struct GNUNET_DNSPARSER_MxRecord *r) * @return the newly allocated record */ struct GNUNET_DNSPARSER_SrvRecord * -GNUNET_DNSPARSER_duplicate_srv_record (const struct GNUNET_DNSPARSER_SrvRecord *r); +GNUNET_DNSPARSER_duplicate_srv_record(const struct GNUNET_DNSPARSER_SrvRecord *r); /* ***************** low-level deallocation API ******************** */ @@ -924,7 +895,7 @@ GNUNET_DNSPARSER_duplicate_srv_record (const struct GNUNET_DNSPARSER_SrvRecord * * @param r record to free */ void -GNUNET_DNSPARSER_free_record (struct GNUNET_DNSPARSER_Record *r); +GNUNET_DNSPARSER_free_record(struct GNUNET_DNSPARSER_Record *r); /** @@ -933,7 +904,7 @@ GNUNET_DNSPARSER_free_record (struct GNUNET_DNSPARSER_Record *r); * @param mx record to free */ void -GNUNET_DNSPARSER_free_mx (struct GNUNET_DNSPARSER_MxRecord *mx); +GNUNET_DNSPARSER_free_mx(struct GNUNET_DNSPARSER_MxRecord *mx); /** @@ -942,7 +913,7 @@ GNUNET_DNSPARSER_free_mx (struct GNUNET_DNSPARSER_MxRecord *mx); * @param srv record to free */ void -GNUNET_DNSPARSER_free_srv (struct GNUNET_DNSPARSER_SrvRecord *srv); +GNUNET_DNSPARSER_free_srv(struct GNUNET_DNSPARSER_SrvRecord *srv); /** @@ -951,7 +922,7 @@ GNUNET_DNSPARSER_free_srv (struct GNUNET_DNSPARSER_SrvRecord *srv); * @param soa record to free */ void -GNUNET_DNSPARSER_free_soa (struct GNUNET_DNSPARSER_SoaRecord *soa); +GNUNET_DNSPARSER_free_soa(struct GNUNET_DNSPARSER_SoaRecord *soa); /** @@ -960,7 +931,7 @@ GNUNET_DNSPARSER_free_soa (struct GNUNET_DNSPARSER_SoaRecord *soa); * @param cert record to free */ void -GNUNET_DNSPARSER_free_cert (struct GNUNET_DNSPARSER_CertRecord *cert); +GNUNET_DNSPARSER_free_cert(struct GNUNET_DNSPARSER_CertRecord *cert); /** @@ -971,8 +942,8 @@ GNUNET_DNSPARSER_free_cert (struct GNUNET_DNSPARSER_CertRecord *cert); * @return HEX string (lower case) */ char * -GNUNET_DNSPARSER_bin_to_hex (const void *data, - size_t data_size); +GNUNET_DNSPARSER_bin_to_hex(const void *data, + size_t data_size); /** @@ -984,8 +955,8 @@ GNUNET_DNSPARSER_bin_to_hex (const void *data, * @return number of bytes written to data */ size_t -GNUNET_DNSPARSER_hex_to_bin (const char *hex, - void *data); +GNUNET_DNSPARSER_hex_to_bin(const char *hex, + void *data); #endif diff --git a/src/include/gnunet_dnsstub_lib.h b/src/include/gnunet_dnsstub_lib.h index 5d134e44a..ff59e1292 100644 --- a/src/include/gnunet_dnsstub_lib.h +++ b/src/include/gnunet_dnsstub_lib.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -52,7 +52,7 @@ struct GNUNET_DNSSTUB_RequestSocket; * @return NULL on error */ struct GNUNET_DNSSTUB_Context * -GNUNET_DNSSTUB_start (unsigned int num_sockets); +GNUNET_DNSSTUB_start(unsigned int num_sockets); /** @@ -64,8 +64,8 @@ GNUNET_DNSSTUB_start (unsigned int num_sockets); * @return #GNUNET_OK on success */ int -GNUNET_DNSSTUB_add_dns_ip (struct GNUNET_DNSSTUB_Context *ctx, - const char *dns_ip); +GNUNET_DNSSTUB_add_dns_ip(struct GNUNET_DNSSTUB_Context *ctx, + const char *dns_ip); /** @@ -77,8 +77,8 @@ GNUNET_DNSSTUB_add_dns_ip (struct GNUNET_DNSSTUB_Context *ctx, * @return #GNUNET_OK on success */ int -GNUNET_DNSSTUB_add_dns_sa (struct GNUNET_DNSSTUB_Context *ctx, - const struct sockaddr *sa); +GNUNET_DNSSTUB_add_dns_sa(struct GNUNET_DNSSTUB_Context *ctx, + const struct sockaddr *sa); /** @@ -89,8 +89,8 @@ GNUNET_DNSSTUB_add_dns_sa (struct GNUNET_DNSSTUB_Context *ctx, * @param retry_frequ how long to wait between retries */ void -GNUNET_DNSSTUB_set_retry (struct GNUNET_DNSSTUB_Context *ctx, - struct GNUNET_TIME_Relative retry_freq); +GNUNET_DNSSTUB_set_retry(struct GNUNET_DNSSTUB_Context *ctx, + struct GNUNET_TIME_Relative retry_freq); /** * Cleanup DNSSTUB resolver. @@ -98,7 +98,7 @@ GNUNET_DNSSTUB_set_retry (struct GNUNET_DNSSTUB_Context *ctx, * @param ctx stub resolver to clean up */ void -GNUNET_DNSSTUB_stop (struct GNUNET_DNSSTUB_Context *ctx); +GNUNET_DNSSTUB_stop(struct GNUNET_DNSSTUB_Context *ctx); /** @@ -128,11 +128,11 @@ typedef void * @return socket used for the request, NULL on error */ struct GNUNET_DNSSTUB_RequestSocket * -GNUNET_DNSSTUB_resolve (struct GNUNET_DNSSTUB_Context *ctx, - const void *request, - size_t request_len, - GNUNET_DNSSTUB_ResultCallback rc, - void *rc_cls); +GNUNET_DNSSTUB_resolve(struct GNUNET_DNSSTUB_Context *ctx, + const void *request, + size_t request_len, + GNUNET_DNSSTUB_ResultCallback rc, + void *rc_cls); /** @@ -141,7 +141,7 @@ GNUNET_DNSSTUB_resolve (struct GNUNET_DNSSTUB_Context *ctx, * @param rs resolution to cancel */ void -GNUNET_DNSSTUB_resolve_cancel (struct GNUNET_DNSSTUB_RequestSocket *rs); +GNUNET_DNSSTUB_resolve_cancel(struct GNUNET_DNSSTUB_RequestSocket *rs); #endif diff --git a/src/include/gnunet_fragmentation_lib.h b/src/include/gnunet_fragmentation_lib.h index f76bfc23f..3004c7a44 100644 --- a/src/include/gnunet_fragmentation_lib.h +++ b/src/include/gnunet_fragmentation_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff * @@ -88,14 +88,14 @@ typedef void * @return the fragmentation context */ struct GNUNET_FRAGMENT_Context * -GNUNET_FRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats, - uint16_t mtu, - struct GNUNET_BANDWIDTH_Tracker *tracker, - struct GNUNET_TIME_Relative msg_delay, - struct GNUNET_TIME_Relative ack_delay, - const struct GNUNET_MessageHeader *msg, - GNUNET_FRAGMENT_MessageProcessor proc, - void *proc_cls); +GNUNET_FRAGMENT_context_create(struct GNUNET_STATISTICS_Handle *stats, + uint16_t mtu, + struct GNUNET_BANDWIDTH_Tracker *tracker, + struct GNUNET_TIME_Relative msg_delay, + struct GNUNET_TIME_Relative ack_delay, + const struct GNUNET_MessageHeader *msg, + GNUNET_FRAGMENT_MessageProcessor proc, + void *proc_cls); /** @@ -106,7 +106,7 @@ GNUNET_FRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats, * @param fc fragmentation context */ void -GNUNET_FRAGMENT_context_transmission_done (struct GNUNET_FRAGMENT_Context *fc); +GNUNET_FRAGMENT_context_transmission_done(struct GNUNET_FRAGMENT_Context *fc); /** @@ -121,8 +121,8 @@ GNUNET_FRAGMENT_context_transmission_done (struct GNUNET_FRAGMENT_Context *fc); * #GNUNET_SYSERR if this ack is not valid for this fc */ int -GNUNET_FRAGMENT_process_ack (struct GNUNET_FRAGMENT_Context *fc, - const struct GNUNET_MessageHeader *msg); +GNUNET_FRAGMENT_process_ack(struct GNUNET_FRAGMENT_Context *fc, + const struct GNUNET_MessageHeader *msg); /** @@ -136,9 +136,9 @@ GNUNET_FRAGMENT_process_ack (struct GNUNET_FRAGMENT_Context *fc, * last message, set to FOREVER if the message was not fully transmitted (OUT only) */ void -GNUNET_FRAGMENT_context_destroy (struct GNUNET_FRAGMENT_Context *fc, - struct GNUNET_TIME_Relative *msg_delay, - struct GNUNET_TIME_Relative *ack_delay); +GNUNET_FRAGMENT_context_destroy(struct GNUNET_FRAGMENT_Context *fc, + struct GNUNET_TIME_Relative *msg_delay, + struct GNUNET_TIME_Relative *ack_delay); /** @@ -148,7 +148,7 @@ GNUNET_FRAGMENT_context_destroy (struct GNUNET_FRAGMENT_Context *fc, * @return ack in human-readable format */ const char * -GNUNET_FRAGMENT_print_ack (const struct GNUNET_MessageHeader *ack); +GNUNET_FRAGMENT_print_ack(const struct GNUNET_MessageHeader *ack); /** @@ -187,12 +187,12 @@ typedef void * @return the defragmentation context */ struct GNUNET_DEFRAGMENT_Context * -GNUNET_DEFRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats, - uint16_t mtu, - unsigned int num_msgs, - void *cls, - GNUNET_FRAGMENT_MessageProcessor proc, - GNUNET_DEFRAGMENT_AckProcessor ackp); +GNUNET_DEFRAGMENT_context_create(struct GNUNET_STATISTICS_Handle *stats, + uint16_t mtu, + unsigned int num_msgs, + void *cls, + GNUNET_FRAGMENT_MessageProcessor proc, + GNUNET_DEFRAGMENT_AckProcessor ackp); /** @@ -201,7 +201,7 @@ GNUNET_DEFRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats, * @param dc defragmentation context */ void -GNUNET_DEFRAGMENT_context_destroy (struct GNUNET_DEFRAGMENT_Context *dc); +GNUNET_DEFRAGMENT_context_destroy(struct GNUNET_DEFRAGMENT_Context *dc); /** @@ -214,8 +214,8 @@ GNUNET_DEFRAGMENT_context_destroy (struct GNUNET_DEFRAGMENT_Context *dc); * #GNUNET_SYSERR on error */ int -GNUNET_DEFRAGMENT_process_fragment (struct GNUNET_DEFRAGMENT_Context *dc, - const struct GNUNET_MessageHeader *msg); +GNUNET_DEFRAGMENT_process_fragment(struct GNUNET_DEFRAGMENT_Context *dc, + const struct GNUNET_MessageHeader *msg); diff --git a/src/include/gnunet_friends_lib.h b/src/include/gnunet_friends_lib.h index 8a25be07c..64e7f39d8 100644 --- a/src/include/gnunet_friends_lib.h +++ b/src/include/gnunet_friends_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -61,9 +61,9 @@ typedef void (*GNUNET_FRIENDS_Callback)(void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR on parsing errors */ int -GNUNET_FRIENDS_parse (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_FRIENDS_Callback cb, - void *cb_cls); +GNUNET_FRIENDS_parse(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_FRIENDS_Callback cb, + void *cb_cls); /** @@ -80,7 +80,7 @@ struct GNUNET_FRIENDS_Writer; * @return NULL on error */ struct GNUNET_FRIENDS_Writer * -GNUNET_FRIENDS_write_start (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_FRIENDS_write_start(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -90,7 +90,7 @@ GNUNET_FRIENDS_write_start (const struct GNUNET_CONFIGURATION_Handle *cfg); * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_FRIENDS_write_stop (struct GNUNET_FRIENDS_Writer *w); +GNUNET_FRIENDS_write_stop(struct GNUNET_FRIENDS_Writer *w); /** @@ -101,8 +101,8 @@ GNUNET_FRIENDS_write_stop (struct GNUNET_FRIENDS_Writer *w); * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_FRIENDS_write (struct GNUNET_FRIENDS_Writer *w, - const struct GNUNET_PeerIdentity *friend_id); +GNUNET_FRIENDS_write(struct GNUNET_FRIENDS_Writer *w, + const struct GNUNET_PeerIdentity *friend_id); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_fs_service.h b/src/include/gnunet_fs_service.h index 5ee863d12..688c6d489 100644 --- a/src/include/gnunet_fs_service.h +++ b/src/include/gnunet_fs_service.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff * @@ -80,7 +80,7 @@ extern "C" * How often do we signal applications that a probe for a particular * search result is running? (used to visualize probes). */ -#define GNUNET_FS_PROBE_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250) +#define GNUNET_FS_PROBE_UPDATE_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250) /** * A Universal Resource Identifier (URI), opaque. @@ -112,8 +112,8 @@ typedef int * @return #GNUNET_OK on success */ int -GNUNET_FS_uri_to_key (const struct GNUNET_FS_Uri *uri, - struct GNUNET_HashCode *key); +GNUNET_FS_uri_to_key(const struct GNUNET_FS_Uri *uri, + struct GNUNET_HashCode *key); /** @@ -123,7 +123,7 @@ GNUNET_FS_uri_to_key (const struct GNUNET_FS_Uri *uri, * @return the UTF-8 string */ char * -GNUNET_FS_uri_to_string (const struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_to_string(const struct GNUNET_FS_Uri *uri); /** @@ -134,7 +134,7 @@ GNUNET_FS_uri_to_string (const struct GNUNET_FS_Uri *uri); * @return string with the keywords */ char * -GNUNET_FS_uri_ksk_to_string_fancy (const struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_ksk_to_string_fancy(const struct GNUNET_FS_Uri *uri); /** @@ -146,9 +146,9 @@ GNUNET_FS_uri_ksk_to_string_fancy (const struct GNUNET_FS_Uri *uri); * @param is_mandatory is this keyword mandatory? */ void -GNUNET_FS_uri_ksk_add_keyword (struct GNUNET_FS_Uri *uri, - const char *keyword, - int is_mandatory); +GNUNET_FS_uri_ksk_add_keyword(struct GNUNET_FS_Uri *uri, + const char *keyword, + int is_mandatory); /** @@ -159,8 +159,8 @@ GNUNET_FS_uri_ksk_add_keyword (struct GNUNET_FS_Uri *uri, * @param keyword keyword to add */ void -GNUNET_FS_uri_ksk_remove_keyword (struct GNUNET_FS_Uri *uri, - const char *keyword); +GNUNET_FS_uri_ksk_remove_keyword(struct GNUNET_FS_Uri *uri, + const char *keyword); /** @@ -171,8 +171,8 @@ GNUNET_FS_uri_ksk_remove_keyword (struct GNUNET_FS_Uri *uri, * @return NULL on error */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_parse (const char *uri, - char **emsg); +GNUNET_FS_uri_parse(const char *uri, + char **emsg); /** @@ -181,7 +181,7 @@ GNUNET_FS_uri_parse (const char *uri, * @param uri uri to free */ void -GNUNET_FS_uri_destroy (struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_destroy(struct GNUNET_FS_Uri *uri); /** @@ -191,7 +191,7 @@ GNUNET_FS_uri_destroy (struct GNUNET_FS_Uri *uri); * @return 0 if this is not a keyword URI */ unsigned int -GNUNET_FS_uri_ksk_get_keyword_count (const struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_ksk_get_keyword_count(const struct GNUNET_FS_Uri *uri); /** @@ -204,9 +204,9 @@ GNUNET_FS_uri_ksk_get_keyword_count (const struct GNUNET_FS_Uri *uri); * keywords iterated over until iterator aborted */ int -GNUNET_FS_uri_ksk_get_keywords (const struct GNUNET_FS_Uri *uri, - GNUNET_FS_KeywordIterator iterator, - void *iterator_cls); +GNUNET_FS_uri_ksk_get_keywords(const struct GNUNET_FS_Uri *uri, + GNUNET_FS_KeywordIterator iterator, + void *iterator_cls); /** @@ -217,8 +217,8 @@ GNUNET_FS_uri_ksk_get_keywords (const struct GNUNET_FS_Uri *uri, * @return #GNUNET_SYSERR if this is not a location URI, otherwise #GNUNET_OK */ int -GNUNET_FS_uri_loc_get_peer_identity (const struct GNUNET_FS_Uri *uri, - struct GNUNET_PeerIdentity *peer); +GNUNET_FS_uri_loc_get_peer_identity(const struct GNUNET_FS_Uri *uri, + struct GNUNET_PeerIdentity *peer); /** @@ -228,7 +228,7 @@ GNUNET_FS_uri_loc_get_peer_identity (const struct GNUNET_FS_Uri *uri, * @return NULL if argument is not a location URI */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_loc_get_uri (const struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_loc_get_uri(const struct GNUNET_FS_Uri *uri); /** @@ -238,7 +238,7 @@ GNUNET_FS_uri_loc_get_uri (const struct GNUNET_FS_Uri *uri); * @return expiration time of the URI */ struct GNUNET_TIME_Absolute -GNUNET_FS_uri_loc_get_expiration (const struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_loc_get_expiration(const struct GNUNET_FS_Uri *uri); /** @@ -254,9 +254,9 @@ GNUNET_FS_uri_loc_get_expiration (const struct GNUNET_FS_Uri *uri); * @return the location URI, NULL on error */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_loc_create (const struct GNUNET_FS_Uri *base_uri, - const struct GNUNET_CRYPTO_EddsaPrivateKey *sign_key, - struct GNUNET_TIME_Absolute expiration_time); +GNUNET_FS_uri_loc_create(const struct GNUNET_FS_Uri *base_uri, + const struct GNUNET_CRYPTO_EddsaPrivateKey *sign_key, + struct GNUNET_TIME_Absolute expiration_time); /** @@ -267,8 +267,8 @@ GNUNET_FS_uri_loc_create (const struct GNUNET_FS_Uri *base_uri, * @return merged URI, NULL on error */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_ksk_merge (const struct GNUNET_FS_Uri *u1, - const struct GNUNET_FS_Uri *u2); +GNUNET_FS_uri_ksk_merge(const struct GNUNET_FS_Uri *u1, + const struct GNUNET_FS_Uri *u2); /** @@ -278,7 +278,7 @@ GNUNET_FS_uri_ksk_merge (const struct GNUNET_FS_Uri *u1, * @return copy of the URI */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_dup (const struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_dup(const struct GNUNET_FS_Uri *uri); /** @@ -299,8 +299,8 @@ GNUNET_FS_uri_dup (const struct GNUNET_FS_Uri *uri); * if keywords is not legal (i.e. empty). */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_ksk_create (const char *keywords, - char **emsg); +GNUNET_FS_uri_ksk_create(const char *keywords, + char **emsg); /** @@ -321,8 +321,8 @@ GNUNET_FS_uri_ksk_create (const char *keywords, * if keywords is not legal (i.e. empty). */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_ksk_create_from_args (unsigned int argc, - const char **argv); +GNUNET_FS_uri_ksk_create_from_args(unsigned int argc, + const char **argv); /** @@ -333,8 +333,8 @@ GNUNET_FS_uri_ksk_create_from_args (unsigned int argc, * @return #GNUNET_YES if the URIs are equal */ int -GNUNET_FS_uri_test_equal (const struct GNUNET_FS_Uri *u1, - const struct GNUNET_FS_Uri *u2); +GNUNET_FS_uri_test_equal(const struct GNUNET_FS_Uri *u1, + const struct GNUNET_FS_Uri *u2); /** @@ -344,7 +344,7 @@ GNUNET_FS_uri_test_equal (const struct GNUNET_FS_Uri *u1, * @return #GNUNET_YES if this is an SKS uri */ int -GNUNET_FS_uri_test_sks (const struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_test_sks(const struct GNUNET_FS_Uri *uri); /** @@ -355,8 +355,8 @@ GNUNET_FS_uri_test_sks (const struct GNUNET_FS_Uri *uri); * @return an FS URI for the given namespace and identifier */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_sks_create (const struct GNUNET_CRYPTO_EcdsaPublicKey *ns, - const char *id); +GNUNET_FS_uri_sks_create(const struct GNUNET_CRYPTO_EcdsaPublicKey *ns, + const char *id); /** @@ -368,8 +368,8 @@ GNUNET_FS_uri_sks_create (const struct GNUNET_CRYPTO_EcdsaPublicKey *ns, * @return #GNUNET_OK on success */ int -GNUNET_FS_uri_sks_get_namespace (const struct GNUNET_FS_Uri *uri, - struct GNUNET_CRYPTO_EcdsaPublicKey *pseudonym); +GNUNET_FS_uri_sks_get_namespace(const struct GNUNET_FS_Uri *uri, + struct GNUNET_CRYPTO_EcdsaPublicKey *pseudonym); /** @@ -379,7 +379,7 @@ GNUNET_FS_uri_sks_get_namespace (const struct GNUNET_FS_Uri *uri, * @return NULL on error (not a valid SKS URI) */ char * -GNUNET_FS_uri_sks_get_content_id (const struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_sks_get_content_id(const struct GNUNET_FS_Uri *uri); /** @@ -389,7 +389,7 @@ GNUNET_FS_uri_sks_get_content_id (const struct GNUNET_FS_Uri *uri); * @return #GNUNET_YES if this is a KSK uri */ int -GNUNET_FS_uri_test_ksk (const struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_test_ksk(const struct GNUNET_FS_Uri *uri); /** @@ -399,7 +399,7 @@ GNUNET_FS_uri_test_ksk (const struct GNUNET_FS_Uri *uri); * @return #GNUNET_YES if this is a CHK uri */ int -GNUNET_FS_uri_test_chk (const struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_test_chk(const struct GNUNET_FS_Uri *uri); /** @@ -410,7 +410,7 @@ GNUNET_FS_uri_test_chk (const struct GNUNET_FS_Uri *uri); * @return size of the file as specified in the CHK URI */ uint64_t -GNUNET_FS_uri_chk_get_file_size (const struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_chk_get_file_size(const struct GNUNET_FS_Uri *uri); /** @@ -420,7 +420,7 @@ GNUNET_FS_uri_chk_get_file_size (const struct GNUNET_FS_Uri *uri); * @return #GNUNET_YES if this is a LOC uri */ int -GNUNET_FS_uri_test_loc (const struct GNUNET_FS_Uri *uri); +GNUNET_FS_uri_test_loc(const struct GNUNET_FS_Uri *uri); /** @@ -432,8 +432,8 @@ GNUNET_FS_uri_test_loc (const struct GNUNET_FS_Uri *uri); * @return NULL on error, otherwise a KSK URI */ struct GNUNET_FS_Uri * -GNUNET_FS_uri_ksk_create_from_meta_data (const struct GNUNET_CONTAINER_MetaData - *md); +GNUNET_FS_uri_ksk_create_from_meta_data(const struct GNUNET_CONTAINER_MetaData + *md); /* ******************** command-line option parsing API *********************** */ @@ -448,11 +448,11 @@ GNUNET_FS_uri_ksk_create_from_meta_data (const struct GNUNET_CONTAINER_MetaData * @param[out] topKeywords set to the desired value */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_FS_GETOPT_KEYWORDS (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - struct GNUNET_FS_Uri **topKeywords); +GNUNET_FS_GETOPT_KEYWORDS(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + struct GNUNET_FS_Uri **topKeywords); /** * Allow user to specify metadata. @@ -464,11 +464,11 @@ GNUNET_FS_GETOPT_KEYWORDS (char shortName, * @param[out] metadata set to the desired value */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_FS_GETOPT_METADATA (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - struct GNUNET_CONTAINER_MetaData **meta); +GNUNET_FS_GETOPT_METADATA(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + struct GNUNET_CONTAINER_MetaData **meta); /** * Command-line option parser function that allows the user to specify @@ -483,10 +483,10 @@ GNUNET_FS_GETOPT_METADATA (char shortName, * @return #GNUNET_OK on success */ int -GNUNET_FS_getopt_set_metadata (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, - void *scls, - const char *option, - const char *value); +GNUNET_FS_getopt_set_metadata(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, + void *scls, + const char *option, + const char *value); @@ -504,8 +504,7 @@ GNUNET_FS_getopt_set_metadata (struct GNUNET_GETOPT_CommandLineProcessorContext * are typically generated either due to explicit client requests * or because of suspend/resume operations. */ -enum GNUNET_FS_Status -{ +enum GNUNET_FS_Status { /** * Notification that we have started to publish a file structure. */ @@ -724,7 +723,6 @@ enum GNUNET_FS_Status * Notification that we are making progress sharing a directory. */ GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY = 37 - }; @@ -772,21 +770,15 @@ struct GNUNET_FS_FileInformation; * Argument given to the progress callback with * information about what is going on. */ -struct GNUNET_FS_ProgressInfo -{ - +struct GNUNET_FS_ProgressInfo { /** * Values that depend on the event type. */ - union - { - + union { /** * Values for all "GNUNET_FS_STATUS_PUBLISH_*" events. */ - struct - { - + struct { /** * Context for controlling the upload. */ @@ -848,54 +840,47 @@ struct GNUNET_FS_ProgressInfo /** * Additional values for specific events. */ - union - { - + union { /** - * These values are only valid for - * #GNUNET_FS_STATUS_PUBLISH_PROGRESS events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_PUBLISH_PROGRESS events. + */ + struct { /** - * Data block we just published. - */ + * Data block we just published. + */ const void *data; /** - * At what offset in the file is "data"? - */ + * At what offset in the file is "data"? + */ uint64_t offset; /** - * Length of the data block. - */ + * Length of the data block. + */ uint64_t data_len; /** - * Depth of the given block in the tree; - * 0 would be the lowest level (DBLOCKs). - */ + * Depth of the given block in the tree; + * 0 would be the lowest level (DBLOCKs). + */ unsigned int depth; - } progress; /** - * These values are only valid for - * #GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_PUBLISH_PROGRESS_DIRECTORY events. + */ + struct { /** - * How far are we along in the overall directory? - */ + * How far are we along in the overall directory? + */ uint64_t completed; /** - * How big do we estimate the entire directory to be? - */ + * How big do we estimate the entire directory to be? + */ uint64_t total; /** @@ -905,77 +890,63 @@ struct GNUNET_FS_ProgressInfo * "publish"-level of this struct.) */ struct GNUNET_TIME_Relative eta; - } progress_directory; /** - * These values are only valid for - * #GNUNET_FS_STATUS_PUBLISH_RESUME events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_PUBLISH_RESUME events. + */ + struct { /** - * Error message, NULL if no error was encountered so far. - */ + * Error message, NULL if no error was encountered so far. + */ const char *message; /** - * URI of the file (if the download had been completed) - */ + * URI of the file (if the download had been completed) + */ const struct GNUNET_FS_Uri *chk_uri; /** - * SKS URI of the file (if the download had been completed) - */ + * SKS URI of the file (if the download had been completed) + */ const struct GNUNET_FS_Uri *sks_uri; - } resume; /** - * These values are only valid for - * #GNUNET_FS_STATUS_PUBLISH_COMPLETED events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_PUBLISH_COMPLETED events. + */ + struct { /** - * CHK URI of the file. - */ + * CHK URI of the file. + */ const struct GNUNET_FS_Uri *chk_uri; /** - * SKS URI of the file (if the download had been completed) - */ + * SKS URI of the file (if the download had been completed) + */ const struct GNUNET_FS_Uri *sks_uri; - } completed; /** - * These values are only valid for - * #GNUNET_FS_STATUS_PUBLISH_ERROR events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_PUBLISH_ERROR events. + */ + struct { /** - * Error message, never NULL. - */ + * Error message, never NULL. + */ const char *message; - } error; - } specifics; - } publish; /** * Values for all "GNUNET_FS_STATUS_DOWNLOAD_*" events. */ - struct - { - + struct { /** * Context for controlling the download. */ @@ -1049,121 +1020,103 @@ struct GNUNET_FS_ProgressInfo /** * Additional values for specific events. */ - union - { - + union { /** - * These values are only valid for - * #GNUNET_FS_STATUS_DOWNLOAD_PROGRESS events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_DOWNLOAD_PROGRESS events. + */ + struct { /** - * Data block we just obtained, can be NULL (even if - * data_len > 0) if we found the entire block 'intact' on - * disk. In this case, it is also possible for 'data_len' - * to be larger than an individual (32k) block. - */ + * Data block we just obtained, can be NULL (even if + * data_len > 0) if we found the entire block 'intact' on + * disk. In this case, it is also possible for 'data_len' + * to be larger than an individual (32k) block. + */ const void *data; /** - * At what offset in the file is "data"? - */ + * At what offset in the file is "data"? + */ uint64_t offset; /** - * Length of the data block. - */ + * Length of the data block. + */ uint64_t data_len; /** - * How much time passed between us asking for this block and + * How much time passed between us asking for this block and * actually getting it? #GNUNET_TIME_UNIT_FOREVER_REL if unknown. - */ + */ struct GNUNET_TIME_Relative block_download_duration; /** - * Depth of the given block in the tree; - * 0 would be the lowest level (DBLOCKS). - */ + * Depth of the given block in the tree; + * 0 would be the lowest level (DBLOCKS). + */ unsigned int depth; /** - * How much respect did we offer for downloading this block? (estimate, - * because we might have the same request pending for multiple clients, - * and of course because a transmission may have failed at a lower - * layer). - */ + * How much respect did we offer for downloading this block? (estimate, + * because we might have the same request pending for multiple clients, + * and of course because a transmission may have failed at a lower + * layer). + */ uint32_t respect_offered; /** - * How often did we transmit the request? (estimate, - * because we might have the same request pending for multiple clients, - * and of course because a transmission may have failed at a lower - * layer). - */ + * How often did we transmit the request? (estimate, + * because we might have the same request pending for multiple clients, + * and of course because a transmission may have failed at a lower + * layer). + */ uint32_t num_transmissions; - } progress; /** - * These values are only valid for - * #GNUNET_FS_STATUS_DOWNLOAD_START events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_DOWNLOAD_START events. + */ + struct { /** - * Known metadata for the download. - */ + * Known metadata for the download. + */ const struct GNUNET_CONTAINER_MetaData *meta; - } start; /** - * These values are only valid for - * #GNUNET_FS_STATUS_DOWNLOAD_RESUME events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_DOWNLOAD_RESUME events. + */ + struct { /** - * Known metadata for the download. - */ + * Known metadata for the download. + */ const struct GNUNET_CONTAINER_MetaData *meta; /** - * Error message, NULL if we have not encountered any error yet. - */ + * Error message, NULL if we have not encountered any error yet. + */ const char *message; - } resume; /** - * These values are only valid for - * #GNUNET_FS_STATUS_DOWNLOAD_ERROR events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_DOWNLOAD_ERROR events. + */ + struct { /** - * Error message. - */ + * Error message. + */ const char *message; - } error; - } specifics; - } download; /** * Values for all "GNUNET_FS_STATUS_SEARCH_*" events. */ - struct - { - + struct { /** * Context for controlling the search, NULL for * searches that were not explicitly triggered @@ -1211,262 +1164,232 @@ struct GNUNET_FS_ProgressInfo /** * Additional values for specific events. */ - union - { - + union { /** - * These values are only valid for - * #GNUNET_FS_STATUS_SEARCH_RESULT events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_SEARCH_RESULT events. + */ + struct { /** - * Metadata for the search result. - */ + * Metadata for the search result. + */ const struct GNUNET_CONTAINER_MetaData *meta; /** - * URI for the search result. - */ + * URI for the search result. + */ const struct GNUNET_FS_Uri *uri; /** - * Handle to the result (for starting downloads). - */ + * Handle to the result (for starting downloads). + */ struct GNUNET_FS_SearchResult *result; /** - * Applicability rank (the larger, the better the result - * fits the search criteria). - */ + * Applicability rank (the larger, the better the result + * fits the search criteria). + */ uint32_t applicability_rank; - } result; /** - * These values are only valid for - * #GNUNET_FS_STATUS_SEARCH_RESUME_RESULT events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_SEARCH_RESUME_RESULT events. + */ + struct { /** - * Metadata for the search result. - */ + * Metadata for the search result. + */ const struct GNUNET_CONTAINER_MetaData *meta; /** - * URI for the search result. - */ + * URI for the search result. + */ const struct GNUNET_FS_Uri *uri; /** - * Handle to the result (for starting downloads). - */ + * Handle to the result (for starting downloads). + */ struct GNUNET_FS_SearchResult *result; /** - * Current availability rank (negative: - * unavailable, positive: available) - */ + * Current availability rank (negative: + * unavailable, positive: available) + */ int32_t availability_rank; /** - * On how many total queries is the given - * availability_rank based? - */ + * On how many total queries is the given + * availability_rank based? + */ uint32_t availability_certainty; /** - * Updated applicability rank (the larger, - * the better the result fits the search - * criteria). - */ + * Updated applicability rank (the larger, + * the better the result fits the search + * criteria). + */ uint32_t applicability_rank; - } resume_result; /** - * These values are only valid for - * #GNUNET_FS_STATUS_SEARCH_UPDATE events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_SEARCH_UPDATE events. + */ + struct { /** - * Private context set for for this result - * during the "RESULT" event. - */ + * Private context set for for this result + * during the "RESULT" event. + */ void *cctx; /** - * Metadata for the search result. - */ + * Metadata for the search result. + */ const struct GNUNET_CONTAINER_MetaData *meta; /** - * URI for the search result. - */ + * URI for the search result. + */ const struct GNUNET_FS_Uri *uri; /** - * Current availability rank (negative: - * unavailable, positive: available) - */ + * Current availability rank (negative: + * unavailable, positive: available) + */ int32_t availability_rank; /** - * On how many total queries is the given - * availability_rank based? - */ + * On how many total queries is the given + * availability_rank based? + */ uint32_t availability_certainty; /** - * Updated applicability rank (the larger, - * the better the result fits the search - * criteria). - */ + * Updated applicability rank (the larger, + * the better the result fits the search + * criteria). + */ uint32_t applicability_rank; - /** - * How long has the current probe been active? - */ - struct GNUNET_TIME_Relative current_probe_time; - + /** + * How long has the current probe been active? + */ + struct GNUNET_TIME_Relative current_probe_time; } update; /** - * These values are only valid for - * #GNUNET_FS_STATUS_SEARCH_RESULT_SUSPEND events. - * These events are automatically triggered for - * each search result before the - * #GNUNET_FS_STATUS_SEARCH_SUSPEND event. This - * happens primarily to give the client a chance - * to clean up the "cctx" (if needed). - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_SEARCH_RESULT_SUSPEND events. + * These events are automatically triggered for + * each search result before the + * #GNUNET_FS_STATUS_SEARCH_SUSPEND event. This + * happens primarily to give the client a chance + * to clean up the "cctx" (if needed). + */ + struct { /** - * Private context set for for this result - * during the "RESULT" event. - */ + * Private context set for for this result + * during the "RESULT" event. + */ void *cctx; /** - * Metadata for the search result. - */ + * Metadata for the search result. + */ const struct GNUNET_CONTAINER_MetaData *meta; /** - * URI for the search result. - */ + * URI for the search result. + */ const struct GNUNET_FS_Uri *uri; - } result_suspend; /** - * These values are only valid for - * #GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED events. - * These events are automatically triggered for - * each search result before the - * #GNUNET_FS_STATUS_SEARCH_STOPPED event. This - * happens primarily to give the client a chance - * to clean up the "cctx" (if needed). - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_SEARCH_RESULT_STOPPED events. + * These events are automatically triggered for + * each search result before the + * #GNUNET_FS_STATUS_SEARCH_STOPPED event. This + * happens primarily to give the client a chance + * to clean up the "cctx" (if needed). + */ + struct { /** - * Private context set for for this result - * during the "RESULT" event. - */ + * Private context set for for this result + * during the "RESULT" event. + */ void *cctx; /** - * Metadata for the search result. - */ + * Metadata for the search result. + */ const struct GNUNET_CONTAINER_MetaData *meta; /** - * URI for the search result. - */ + * URI for the search result. + */ const struct GNUNET_FS_Uri *uri; - } result_stopped; /** - * These values are only valid for - * #GNUNET_FS_STATUS_SEARCH_RESUME events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_SEARCH_RESUME events. + */ + struct { /** - * Error message, NULL if we have not encountered any error yet. - */ + * Error message, NULL if we have not encountered any error yet. + */ const char *message; /** - * Is this search currently paused? - */ + * Is this search currently paused? + */ int is_paused; - } resume; /** - * These values are only valid for - * #GNUNET_FS_STATUS_SEARCH_ERROR events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_SEARCH_ERROR events. + */ + struct { /** - * Error message. - */ + * Error message. + */ const char *message; - } error; /** - * Values for #GNUNET_FS_STATUS_SEARCH_RESULT_NAMESPACE events. - */ - struct - { - + * Values for #GNUNET_FS_STATUS_SEARCH_RESULT_NAMESPACE events. + */ + struct { /** - * Short, human-readable name of the namespace. - */ + * Short, human-readable name of the namespace. + */ const char *name; /** - * Root identifier for the namespace, can be NULL. - */ + * Root identifier for the namespace, can be NULL. + */ const char *root; /** - * Metadata for the namespace. - */ + * Metadata for the namespace. + */ const struct GNUNET_CONTAINER_MetaData *meta; /** - * Public key of the namespace. - */ + * Public key of the namespace. + */ struct GNUNET_CRYPTO_EcdsaPublicKey pseudonym; - } ns; - } specifics; - } search; /** * Values for all "GNUNET_FS_STATUS_UNINDEX_*" events. */ - struct - { - + struct { /** * Context for controlling the unindexing. */ @@ -1510,71 +1433,57 @@ struct GNUNET_FS_ProgressInfo /** * Additional values for specific events. */ - union - { - + union { /** - * These values are only valid for - * #GNUNET_FS_STATUS_UNINDEX_PROGRESS events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_UNINDEX_PROGRESS events. + */ + struct { /** - * Data block we just unindexed. - */ + * Data block we just unindexed. + */ const void *data; /** - * At what offset in the file is "data"? - */ + * At what offset in the file is "data"? + */ uint64_t offset; /** - * Length of the data block. - */ + * Length of the data block. + */ uint64_t data_len; /** - * Depth of the given block in the tree; - * 0 would be the lowest level (DBLOCKS). - */ + * Depth of the given block in the tree; + * 0 would be the lowest level (DBLOCKS). + */ unsigned int depth; - } progress; /** - * These values are only valid for - * #GNUNET_FS_STATUS_UNINDEX_RESUME events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_UNINDEX_RESUME events. + */ + struct { /** - * Error message, NULL if we have not encountered any error yet. - */ + * Error message, NULL if we have not encountered any error yet. + */ const char *message; - } resume; /** - * These values are only valid for - * #GNUNET_FS_STATUS_UNINDEX_ERROR events. - */ - struct - { - + * These values are only valid for + * #GNUNET_FS_STATUS_UNINDEX_ERROR events. + */ + struct { /** - * Error message. - */ + * Error message. + */ const char *message; - } error; - } specifics; - } unindex; - } value; /** @@ -1612,8 +1521,7 @@ typedef void * /** * General (global) option flags for file-sharing. */ -enum GNUNET_FS_Flags -{ +enum GNUNET_FS_Flags { /** * No special flags set. */ @@ -1637,9 +1545,7 @@ enum GNUNET_FS_Flags /** * Options specified in the VARARGs portion of GNUNET_FS_start. */ -enum GNUNET_FS_OPTIONS -{ - +enum GNUNET_FS_OPTIONS { /** * Last option in the VARARG list. */ @@ -1666,9 +1572,7 @@ enum GNUNET_FS_OPTIONS * Settings for publishing a block (which may of course also * apply to an entire directory or file). */ -struct GNUNET_FS_BlockOptions -{ - +struct GNUNET_FS_BlockOptions { /** * At what time should the block expire? Data blocks (DBLOCKS and * IBLOCKS) may still be used even if they are expired (however, @@ -1703,7 +1607,6 @@ struct GNUNET_FS_BlockOptions * first place). */ uint32_t replication_level; - }; @@ -1725,12 +1628,12 @@ struct GNUNET_FS_Handle; * @return NULL on error */ struct GNUNET_FS_Handle * -GNUNET_FS_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *client_name, - GNUNET_FS_ProgressCallback upcb, - void *upcb_cls, - enum GNUNET_FS_Flags flags, - ...); +GNUNET_FS_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *client_name, + GNUNET_FS_ProgressCallback upcb, + void *upcb_cls, + enum GNUNET_FS_Flags flags, + ...); /** @@ -1743,7 +1646,7 @@ GNUNET_FS_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param h handle that was returned from #GNUNET_FS_start() */ void -GNUNET_FS_stop (struct GNUNET_FS_Handle *h); +GNUNET_FS_stop(struct GNUNET_FS_Handle *h); /** @@ -1782,7 +1685,7 @@ typedef int * to read this fi-struct from disk. */ const char * -GNUNET_FS_file_information_get_id (struct GNUNET_FS_FileInformation *s); +GNUNET_FS_file_information_get_id(struct GNUNET_FS_FileInformation *s); /** @@ -1792,7 +1695,7 @@ GNUNET_FS_file_information_get_id (struct GNUNET_FS_FileInformation *s); * @return "filename" field of the structure (can be NULL) */ const char * -GNUNET_FS_file_information_get_filename (struct GNUNET_FS_FileInformation *s); +GNUNET_FS_file_information_get_filename(struct GNUNET_FS_FileInformation *s); /** @@ -1804,8 +1707,8 @@ GNUNET_FS_file_information_get_filename (struct GNUNET_FS_FileInformation *s); * @param filename filename to set */ void -GNUNET_FS_file_information_set_filename (struct GNUNET_FS_FileInformation *s, - const char *filename); +GNUNET_FS_file_information_set_filename(struct GNUNET_FS_FileInformation *s, + const char *filename); /** @@ -1823,13 +1726,13 @@ GNUNET_FS_file_information_set_filename (struct GNUNET_FS_FileInformation *s, * @return publish structure entry for the file */ struct GNUNET_FS_FileInformation * -GNUNET_FS_file_information_create_from_file (struct GNUNET_FS_Handle *h, - void *client_info, - const char *filename, - const struct GNUNET_FS_Uri *keywords, - const struct GNUNET_CONTAINER_MetaData *meta, - int do_index, - const struct GNUNET_FS_BlockOptions *bo); +GNUNET_FS_file_information_create_from_file(struct GNUNET_FS_Handle *h, + void *client_info, + const char *filename, + const struct GNUNET_FS_Uri *keywords, + const struct GNUNET_CONTAINER_MetaData *meta, + int do_index, + const struct GNUNET_FS_BlockOptions *bo); /** @@ -1849,14 +1752,14 @@ GNUNET_FS_file_information_create_from_file (struct GNUNET_FS_Handle *h, * @return publish structure entry for the file */ struct GNUNET_FS_FileInformation * -GNUNET_FS_file_information_create_from_data (struct GNUNET_FS_Handle *h, - void *client_info, - uint64_t length, - void *data, - const struct GNUNET_FS_Uri *keywords, - const struct GNUNET_CONTAINER_MetaData *meta, - int do_index, - const struct GNUNET_FS_BlockOptions *bo); +GNUNET_FS_file_information_create_from_data(struct GNUNET_FS_Handle *h, + void *client_info, + uint64_t length, + void *data, + const struct GNUNET_FS_Uri *keywords, + const struct GNUNET_CONTAINER_MetaData *meta, + int do_index, + const struct GNUNET_FS_BlockOptions *bo); /** @@ -1904,18 +1807,18 @@ typedef size_t * @return publish structure entry for the file */ struct GNUNET_FS_FileInformation * -GNUNET_FS_file_information_create_from_reader (struct GNUNET_FS_Handle *h, - void *client_info, - uint64_t length, - GNUNET_FS_DataReader reader, - void *reader_cls, - const struct GNUNET_FS_Uri - *keywords, - const struct - GNUNET_CONTAINER_MetaData *meta, - int do_index, - const struct - GNUNET_FS_BlockOptions *bo); +GNUNET_FS_file_information_create_from_reader(struct GNUNET_FS_Handle *h, + void *client_info, + uint64_t length, + GNUNET_FS_DataReader reader, + void *reader_cls, + const struct GNUNET_FS_Uri + *keywords, + const struct + GNUNET_CONTAINER_MetaData *meta, + int do_index, + const struct + GNUNET_FS_BlockOptions *bo); /** @@ -1931,16 +1834,16 @@ GNUNET_FS_file_information_create_from_reader (struct GNUNET_FS_Handle *h, * @return publish structure entry for the directory , NULL on error */ struct GNUNET_FS_FileInformation * -GNUNET_FS_file_information_create_empty_directory (struct GNUNET_FS_Handle *h, - void *client_info, - const struct GNUNET_FS_Uri - *keywords, - const struct - GNUNET_CONTAINER_MetaData - *meta, - const struct - GNUNET_FS_BlockOptions *bo, - const char *filename); +GNUNET_FS_file_information_create_empty_directory(struct GNUNET_FS_Handle *h, + void *client_info, + const struct GNUNET_FS_Uri + *keywords, + const struct + GNUNET_CONTAINER_MetaData + *meta, + const struct + GNUNET_FS_BlockOptions *bo, + const char *filename); /** @@ -1950,8 +1853,8 @@ GNUNET_FS_file_information_create_empty_directory (struct GNUNET_FS_Handle *h, * @return #GNUNET_YES if so, #GNUNET_NO if not */ int -GNUNET_FS_file_information_is_directory (const struct GNUNET_FS_FileInformation - *ent); +GNUNET_FS_file_information_is_directory(const struct GNUNET_FS_FileInformation + *ent); /** @@ -1966,8 +1869,8 @@ GNUNET_FS_file_information_is_directory (const struct GNUNET_FS_FileInformation * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_FS_file_information_add (struct GNUNET_FS_FileInformation *dir, - struct GNUNET_FS_FileInformation *ent); +GNUNET_FS_file_information_add(struct GNUNET_FS_FileInformation *dir, + struct GNUNET_FS_FileInformation *ent); /** @@ -1985,9 +1888,9 @@ GNUNET_FS_file_information_add (struct GNUNET_FS_FileInformation *dir, * @param proc_cls closure for @a proc */ void -GNUNET_FS_file_information_inspect (struct GNUNET_FS_FileInformation *dir, - GNUNET_FS_FileInformationProcessor proc, - void *proc_cls); +GNUNET_FS_file_information_inspect(struct GNUNET_FS_FileInformation *dir, + GNUNET_FS_FileInformationProcessor proc, + void *proc_cls); /** @@ -2001,17 +1904,16 @@ GNUNET_FS_file_information_inspect (struct GNUNET_FS_FileInformation *dir, * @param cleaner_cls closure for @a cleaner */ void -GNUNET_FS_file_information_destroy (struct GNUNET_FS_FileInformation *fi, - GNUNET_FS_FileInformationProcessor cleaner, - void *cleaner_cls); +GNUNET_FS_file_information_destroy(struct GNUNET_FS_FileInformation *fi, + GNUNET_FS_FileInformationProcessor cleaner, + void *cleaner_cls); /** * Options for publishing. Compatible options * can be OR'ed together. */ -enum GNUNET_FS_PublishOptions -{ +enum GNUNET_FS_PublishOptions { /** * No options (use defaults for everything). */ @@ -2039,12 +1941,12 @@ enum GNUNET_FS_PublishOptions * @return context that can be used to control the publish operation */ struct GNUNET_FS_PublishContext * -GNUNET_FS_publish_start (struct GNUNET_FS_Handle *h, - struct GNUNET_FS_FileInformation *fi, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, - const char *nid, - const char *nuid, - enum GNUNET_FS_PublishOptions options); +GNUNET_FS_publish_start(struct GNUNET_FS_Handle *h, + struct GNUNET_FS_FileInformation *fi, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, + const char *nid, + const char *nuid, + enum GNUNET_FS_PublishOptions options); /** @@ -2056,7 +1958,7 @@ GNUNET_FS_publish_start (struct GNUNET_FS_Handle *h, * @param pc context for the publication to stop */ void -GNUNET_FS_publish_stop (struct GNUNET_FS_PublishContext *pc); +GNUNET_FS_publish_stop(struct GNUNET_FS_PublishContext *pc); /** @@ -2093,13 +1995,13 @@ struct GNUNET_FS_PublishKskContext; * @return NULL on error (@a cont will still be called) */ struct GNUNET_FS_PublishKskContext * -GNUNET_FS_publish_ksk (struct GNUNET_FS_Handle *h, - const struct GNUNET_FS_Uri *ksk_uri, - const struct GNUNET_CONTAINER_MetaData *meta, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_FS_BlockOptions *bo, - enum GNUNET_FS_PublishOptions options, - GNUNET_FS_PublishContinuation cont, void *cont_cls); +GNUNET_FS_publish_ksk(struct GNUNET_FS_Handle *h, + const struct GNUNET_FS_Uri *ksk_uri, + const struct GNUNET_CONTAINER_MetaData *meta, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_FS_BlockOptions *bo, + enum GNUNET_FS_PublishOptions options, + GNUNET_FS_PublishContinuation cont, void *cont_cls); /** @@ -2108,7 +2010,7 @@ GNUNET_FS_publish_ksk (struct GNUNET_FS_Handle *h, * @param pkc context of the operation to abort. */ void -GNUNET_FS_publish_ksk_cancel (struct GNUNET_FS_PublishKskContext *pkc); +GNUNET_FS_publish_ksk_cancel(struct GNUNET_FS_PublishKskContext *pkc); /** @@ -2133,15 +2035,15 @@ struct GNUNET_FS_PublishSksContext; * @return NULL on error (@a cont will still be called) */ struct GNUNET_FS_PublishSksContext * -GNUNET_FS_publish_sks (struct GNUNET_FS_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, - const char *identifier, - const char *update, - const struct GNUNET_CONTAINER_MetaData *meta, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_FS_BlockOptions *bo, - enum GNUNET_FS_PublishOptions options, - GNUNET_FS_PublishContinuation cont, void *cont_cls); +GNUNET_FS_publish_sks(struct GNUNET_FS_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, + const char *identifier, + const char *update, + const struct GNUNET_CONTAINER_MetaData *meta, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_FS_BlockOptions *bo, + enum GNUNET_FS_PublishOptions options, + GNUNET_FS_PublishContinuation cont, void *cont_cls); /** @@ -2150,7 +2052,7 @@ GNUNET_FS_publish_sks (struct GNUNET_FS_Handle *h, * @param psc context of the operation to abort. */ void -GNUNET_FS_publish_sks_cancel (struct GNUNET_FS_PublishSksContext *psc); +GNUNET_FS_publish_sks_cancel(struct GNUNET_FS_PublishSksContext *psc); /** @@ -2182,9 +2084,9 @@ struct GNUNET_FS_GetIndexedContext; * @return NULL on error (@a iterator is not called) */ struct GNUNET_FS_GetIndexedContext * -GNUNET_FS_get_indexed_files (struct GNUNET_FS_Handle *h, - GNUNET_FS_IndexedFileProcessor iterator, - void *iterator_cls); +GNUNET_FS_get_indexed_files(struct GNUNET_FS_Handle *h, + GNUNET_FS_IndexedFileProcessor iterator, + void *iterator_cls); /** @@ -2193,7 +2095,7 @@ GNUNET_FS_get_indexed_files (struct GNUNET_FS_Handle *h, * @param gic operation to cancel */ void -GNUNET_FS_get_indexed_files_cancel (struct GNUNET_FS_GetIndexedContext *gic); +GNUNET_FS_get_indexed_files_cancel(struct GNUNET_FS_GetIndexedContext *gic); /** @@ -2205,9 +2107,9 @@ GNUNET_FS_get_indexed_files_cancel (struct GNUNET_FS_GetIndexedContext *gic); * @return NULL on error, otherwise handle */ struct GNUNET_FS_UnindexContext * -GNUNET_FS_unindex_start (struct GNUNET_FS_Handle *h, - const char *filename, - void *cctx); +GNUNET_FS_unindex_start(struct GNUNET_FS_Handle *h, + const char *filename, + void *cctx); /** @@ -2216,7 +2118,7 @@ GNUNET_FS_unindex_start (struct GNUNET_FS_Handle *h, * @param uc handle */ void -GNUNET_FS_unindex_stop (struct GNUNET_FS_UnindexContext *uc); +GNUNET_FS_unindex_stop(struct GNUNET_FS_UnindexContext *uc); /** @@ -2229,10 +2131,10 @@ GNUNET_FS_unindex_stop (struct GNUNET_FS_UnindexContext *uc); * @param next_id identifier that should be used for updates */ typedef void (*GNUNET_FS_IdentifierProcessor) (void *cls, - const char *last_id, + const char *last_id, const struct GNUNET_FS_Uri *last_uri, const struct GNUNET_CONTAINER_MetaData *last_meta, - const char *next_id); + const char *next_id); /** @@ -2257,27 +2159,26 @@ typedef void (*GNUNET_FS_IdentifierProcessor) (void *cls, * @param ip_cls closure for @a ip */ void -GNUNET_FS_namespace_list_updateable (struct GNUNET_FS_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, - const char *next_id, - GNUNET_FS_IdentifierProcessor ip, - void *ip_cls); +GNUNET_FS_namespace_list_updateable(struct GNUNET_FS_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *ns, + const char *next_id, + GNUNET_FS_IdentifierProcessor ip, + void *ip_cls); /** * Options for searching. Compatible options * can be OR'ed together. */ -enum GNUNET_FS_SearchOptions -{ - /** - * No options (use defaults for everything). - */ +enum GNUNET_FS_SearchOptions { + /** + * No options (use defaults for everything). + */ GNUNET_FS_SEARCH_OPTION_NONE = 0, - /** - * Only search the local host, do not search remote systems (no P2P) - */ + /** + * Only search the local host, do not search remote systems (no P2P) + */ GNUNET_FS_SEARCH_OPTION_LOOPBACK_ONLY = 1 }; @@ -2294,9 +2195,9 @@ enum GNUNET_FS_SearchOptions * @return context that can be used to control the search */ struct GNUNET_FS_SearchContext * -GNUNET_FS_search_start (struct GNUNET_FS_Handle *h, - const struct GNUNET_FS_Uri *uri, uint32_t anonymity, - enum GNUNET_FS_SearchOptions options, void *cctx); +GNUNET_FS_search_start(struct GNUNET_FS_Handle *h, + const struct GNUNET_FS_Uri *uri, uint32_t anonymity, + enum GNUNET_FS_SearchOptions options, void *cctx); /** @@ -2305,7 +2206,7 @@ GNUNET_FS_search_start (struct GNUNET_FS_Handle *h, * @param sc context for the search that should be paused */ void -GNUNET_FS_search_pause (struct GNUNET_FS_SearchContext *sc); +GNUNET_FS_search_pause(struct GNUNET_FS_SearchContext *sc); /** @@ -2314,7 +2215,7 @@ GNUNET_FS_search_pause (struct GNUNET_FS_SearchContext *sc); * @param sc context for the search that should be resumed */ void -GNUNET_FS_search_continue (struct GNUNET_FS_SearchContext *sc); +GNUNET_FS_search_continue(struct GNUNET_FS_SearchContext *sc); /** @@ -2323,7 +2224,7 @@ GNUNET_FS_search_continue (struct GNUNET_FS_SearchContext *sc); * @param sc context for the search that should be stopped */ void -GNUNET_FS_search_stop (struct GNUNET_FS_SearchContext *sc); +GNUNET_FS_search_stop(struct GNUNET_FS_SearchContext *sc); /** @@ -2337,11 +2238,11 @@ GNUNET_FS_search_stop (struct GNUNET_FS_SearchContext *sc); * @return the search result handle to access the probe activity */ struct GNUNET_FS_SearchResult * -GNUNET_FS_probe (struct GNUNET_FS_Handle *h, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *meta, - void *client_info, - uint32_t anonymity); +GNUNET_FS_probe(struct GNUNET_FS_Handle *h, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *meta, + void *client_info, + uint32_t anonymity); /** @@ -2352,15 +2253,14 @@ GNUNET_FS_probe (struct GNUNET_FS_Handle *h, * @return the value of the 'client_info' pointer */ void * -GNUNET_FS_probe_stop (struct GNUNET_FS_SearchResult *sr); +GNUNET_FS_probe_stop(struct GNUNET_FS_SearchResult *sr); /** * Options for downloading. Compatible options * can be OR'ed together. */ -enum GNUNET_FS_DownloadOptions -{ +enum GNUNET_FS_DownloadOptions { /** * No options (use defaults for everything). */ @@ -2426,13 +2326,13 @@ enum GNUNET_FS_DownloadOptions * @return context that can be used to control this download */ struct GNUNET_FS_DownloadContext * -GNUNET_FS_download_start (struct GNUNET_FS_Handle *h, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *meta, - const char *filename, const char *tempname, - uint64_t offset, uint64_t length, uint32_t anonymity, - enum GNUNET_FS_DownloadOptions options, void *cctx, - struct GNUNET_FS_DownloadContext *parent); +GNUNET_FS_download_start(struct GNUNET_FS_Handle *h, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *meta, + const char *filename, const char *tempname, + uint64_t offset, uint64_t length, uint32_t anonymity, + enum GNUNET_FS_DownloadOptions options, void *cctx, + struct GNUNET_FS_DownloadContext *parent); /** @@ -2470,13 +2370,13 @@ GNUNET_FS_download_start (struct GNUNET_FS_Handle *h, * @return context that can be used to control this download */ struct GNUNET_FS_DownloadContext * -GNUNET_FS_download_start_from_search (struct GNUNET_FS_Handle *h, - struct GNUNET_FS_SearchResult *sr, - const char *filename, - const char *tempname, uint64_t offset, - uint64_t length, uint32_t anonymity, - enum GNUNET_FS_DownloadOptions options, - void *cctx); +GNUNET_FS_download_start_from_search(struct GNUNET_FS_Handle *h, + struct GNUNET_FS_SearchResult *sr, + const char *filename, + const char *tempname, uint64_t offset, + uint64_t length, uint32_t anonymity, + enum GNUNET_FS_DownloadOptions options, + void *cctx); /** @@ -2486,7 +2386,7 @@ GNUNET_FS_download_start_from_search (struct GNUNET_FS_Handle *h, * @param do_delete delete files of incomplete downloads */ void -GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc, int do_delete); +GNUNET_FS_download_stop(struct GNUNET_FS_DownloadContext *dc, int do_delete); /** @@ -2495,7 +2395,7 @@ GNUNET_FS_download_stop (struct GNUNET_FS_DownloadContext *dc, int do_delete); * @param dc handle for the download */ void -GNUNET_FS_download_suspend (struct GNUNET_FS_DownloadContext *dc); +GNUNET_FS_download_suspend(struct GNUNET_FS_DownloadContext *dc); /** @@ -2504,7 +2404,7 @@ GNUNET_FS_download_suspend (struct GNUNET_FS_DownloadContext *dc); * @param dc handle for the download */ void -GNUNET_FS_download_resume (struct GNUNET_FS_DownloadContext *dc); +GNUNET_FS_download_resume(struct GNUNET_FS_DownloadContext *dc); @@ -2523,8 +2423,8 @@ GNUNET_FS_download_resume (struct GNUNET_FS_DownloadContext *dc); * we have no mime-type information (treat as #GNUNET_NO) */ int -GNUNET_FS_meta_data_test_for_directory (const struct GNUNET_CONTAINER_MetaData - *md); +GNUNET_FS_meta_data_test_for_directory(const struct GNUNET_CONTAINER_MetaData + *md); /** @@ -2534,7 +2434,7 @@ GNUNET_FS_meta_data_test_for_directory (const struct GNUNET_CONTAINER_MetaData * @param md metadata to add mimetype to */ void -GNUNET_FS_meta_data_make_directory (struct GNUNET_CONTAINER_MetaData *md); +GNUNET_FS_meta_data_make_directory(struct GNUNET_CONTAINER_MetaData *md); /** @@ -2544,7 +2444,7 @@ GNUNET_FS_meta_data_make_directory (struct GNUNET_CONTAINER_MetaData *md); * @return NULL if meta data is useless for suggesting a filename */ char * -GNUNET_FS_meta_data_suggest_filename (const struct GNUNET_CONTAINER_MetaData *md); +GNUNET_FS_meta_data_suggest_filename(const struct GNUNET_CONTAINER_MetaData *md); /** @@ -2592,10 +2492,10 @@ typedef void (*GNUNET_FS_DirectoryEntryProcessor) (void *cls, * #GNUNET_SYSERR if 'data' does not represent a directory */ int -GNUNET_FS_directory_list_contents (size_t size, const void *data, - uint64_t offset, - GNUNET_FS_DirectoryEntryProcessor dep, - void *dep_cls); +GNUNET_FS_directory_list_contents(size_t size, const void *data, + uint64_t offset, + GNUNET_FS_DirectoryEntryProcessor dep, + void *dep_cls); /** @@ -2610,8 +2510,8 @@ struct GNUNET_FS_DirectoryBuilder; * @param mdir metadata for the directory */ struct GNUNET_FS_DirectoryBuilder * -GNUNET_FS_directory_builder_create (const struct GNUNET_CONTAINER_MetaData - *mdir); +GNUNET_FS_directory_builder_create(const struct GNUNET_CONTAINER_MetaData + *mdir); /** @@ -2625,10 +2525,10 @@ GNUNET_FS_directory_builder_create (const struct GNUNET_CONTAINER_MetaData * by the uri */ void -GNUNET_FS_directory_builder_add (struct GNUNET_FS_DirectoryBuilder *bld, - const struct GNUNET_FS_Uri *uri, - const struct GNUNET_CONTAINER_MetaData *md, - const void *data); +GNUNET_FS_directory_builder_add(struct GNUNET_FS_DirectoryBuilder *bld, + const struct GNUNET_FS_Uri *uri, + const struct GNUNET_CONTAINER_MetaData *md, + const void *data); /** @@ -2642,8 +2542,8 @@ GNUNET_FS_directory_builder_add (struct GNUNET_FS_DirectoryBuilder *bld, * @return #GNUNET_OK on success */ int -GNUNET_FS_directory_builder_finish (struct GNUNET_FS_DirectoryBuilder *bld, - size_t * rsize, void **rdata); +GNUNET_FS_directory_builder_finish(struct GNUNET_FS_DirectoryBuilder *bld, + size_t * rsize, void **rdata); /* ******************** DirScanner API *********************** */ @@ -2651,9 +2551,7 @@ GNUNET_FS_directory_builder_finish (struct GNUNET_FS_DirectoryBuilder *bld, /** * Progress reasons of the directory scanner. */ -enum GNUNET_FS_DirScannerProgressUpdateReason -{ - +enum GNUNET_FS_DirScannerProgressUpdateReason { /** * We've started processing a file or directory. */ @@ -2685,7 +2583,6 @@ enum GNUNET_FS_DirScannerProgressUpdateReason * There was an internal error. Application should abort the scan. */ GNUNET_FS_DIRSCANNER_INTERNAL_ERROR - }; @@ -2701,16 +2598,15 @@ enum GNUNET_FS_DirScannerProgressUpdateReason * @param reason kind of progress we are making */ typedef void (*GNUNET_FS_DirScannerProgressCallback) (void *cls, - const char *filename, - int is_directory, - enum GNUNET_FS_DirScannerProgressUpdateReason reason); + const char *filename, + int is_directory, + enum GNUNET_FS_DirScannerProgressUpdateReason reason); /** * A node of a directory tree (produced by dirscanner) */ -struct GNUNET_FS_ShareTreeItem -{ +struct GNUNET_FS_ShareTreeItem { /** * This is a doubly-linked list */ @@ -2763,7 +2659,6 @@ struct GNUNET_FS_ShareTreeItem * #GNUNET_YES if this is a directory */ int is_directory; - }; @@ -2785,11 +2680,11 @@ struct GNUNET_FS_DirScanner; * @return directory scanner object to be used for controlling the scanner */ struct GNUNET_FS_DirScanner * -GNUNET_FS_directory_scan_start (const char *filename, - int disable_extractor, - const char *ex, - GNUNET_FS_DirScannerProgressCallback cb, - void *cb_cls); +GNUNET_FS_directory_scan_start(const char *filename, + int disable_extractor, + const char *ex, + GNUNET_FS_DirScannerProgressCallback cb, + void *cb_cls); /** @@ -2799,7 +2694,7 @@ GNUNET_FS_directory_scan_start (const char *filename, * @param ds directory scanner structure */ void -GNUNET_FS_directory_scan_abort (struct GNUNET_FS_DirScanner *ds); +GNUNET_FS_directory_scan_abort(struct GNUNET_FS_DirScanner *ds); /** @@ -2811,7 +2706,7 @@ GNUNET_FS_directory_scan_abort (struct GNUNET_FS_DirScanner *ds); * @return the results of the scan (a directory tree) */ struct GNUNET_FS_ShareTreeItem * -GNUNET_FS_directory_scan_get_result (struct GNUNET_FS_DirScanner *ds); +GNUNET_FS_directory_scan_get_result(struct GNUNET_FS_DirScanner *ds); /** @@ -2821,7 +2716,7 @@ GNUNET_FS_directory_scan_get_result (struct GNUNET_FS_DirScanner *ds); * @param toplevel toplevel directory in the tree, returned by the scanner */ void -GNUNET_FS_share_tree_trim (struct GNUNET_FS_ShareTreeItem *toplevel); +GNUNET_FS_share_tree_trim(struct GNUNET_FS_ShareTreeItem *toplevel); /** @@ -2830,7 +2725,7 @@ GNUNET_FS_share_tree_trim (struct GNUNET_FS_ShareTreeItem *toplevel); * @param toplevel toplevel of the tree to be freed */ void -GNUNET_FS_share_tree_free (struct GNUNET_FS_ShareTreeItem *toplevel); +GNUNET_FS_share_tree_free(struct GNUNET_FS_ShareTreeItem *toplevel); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_getopt_lib.h b/src/include/gnunet_getopt_lib.h index 1e99c63d0..ef744fbc9 100644 --- a/src/include/gnunet_getopt_lib.h +++ b/src/include/gnunet_getopt_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -44,9 +44,7 @@ extern "C" { /** * @brief General context for command line processors. */ -struct GNUNET_GETOPT_CommandLineProcessorContext -{ - +struct GNUNET_GETOPT_CommandLineProcessorContext { /** * Name of the application */ @@ -98,9 +96,7 @@ typedef int (*GNUNET_GETOPT_CommandLineOptionProcessor) ( /** * @brief Definition of a command line option. */ -struct GNUNET_GETOPT_CommandLineOption -{ - +struct GNUNET_GETOPT_CommandLineOption { /** * Short name of the option. */ @@ -162,7 +158,7 @@ struct GNUNET_GETOPT_CommandLineOption * @param about string with brief description of the application */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_help (const char *about); +GNUNET_GETOPT_option_help(const char *about); /** @@ -172,7 +168,7 @@ GNUNET_GETOPT_option_help (const char *about); * @param version string with the version number */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_version (const char *version); +GNUNET_GETOPT_option_version(const char *version); /** @@ -181,7 +177,7 @@ GNUNET_GETOPT_option_version (const char *version); * @param[out] logfn set to the name of the logfile */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_logfile (char **logfn); +GNUNET_GETOPT_option_logfile(char **logfn); /** @@ -194,11 +190,11 @@ GNUNET_GETOPT_option_logfile (char **logfn); * @param[out] str set to the string */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_string (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - char **str); +GNUNET_GETOPT_option_string(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + char **str); /** * Allow user to specify a filename (automatically path expanded). @@ -210,11 +206,11 @@ GNUNET_GETOPT_option_string (char shortName, * @param[out] str set to the string */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_filename (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - char **str); +GNUNET_GETOPT_option_filename(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + char **str); /** @@ -229,12 +225,12 @@ GNUNET_GETOPT_option_filename (char shortName, * @param val_size size of @a val in bytes */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_base32_fixed_size (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - void *val, - size_t val_size); +GNUNET_GETOPT_option_base32_fixed_size(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + void *val, + size_t val_size); /** @@ -254,12 +250,12 @@ GNUNET_GETOPT_option_base32_fixed_size (char shortName, argumentHelp, \ description, \ val) \ - GNUNET_GETOPT_option_base32_fixed_size (shortName, \ - name, \ - argumentHelp, \ - description, \ - val, \ - sizeof (*val)) + GNUNET_GETOPT_option_base32_fixed_size(shortName, \ + name, \ + argumentHelp, \ + description, \ + val, \ + sizeof(*val)) /** @@ -272,10 +268,10 @@ GNUNET_GETOPT_option_base32_fixed_size (char shortName, * @param[out] val set to 1 if the option is present */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_flag (char shortName, - const char *name, - const char *description, - int *val); +GNUNET_GETOPT_option_flag(char shortName, + const char *name, + const char *description, + int *val); /** @@ -288,11 +284,11 @@ GNUNET_GETOPT_option_flag (char shortName, * @param[out] val set to the value specified at the command line */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_uint (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - unsigned int *val); +GNUNET_GETOPT_option_uint(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + unsigned int *val); /** @@ -305,11 +301,11 @@ GNUNET_GETOPT_option_uint (char shortName, * @param[out] val set to the value specified at the command line */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_uint16 (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - uint16_t *val); +GNUNET_GETOPT_option_uint16(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + uint16_t *val); /** @@ -322,11 +318,11 @@ GNUNET_GETOPT_option_uint16 (char shortName, * @param[out] val set to the value specified at the command line */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_ulong (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - unsigned long long *val); +GNUNET_GETOPT_option_ulong(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + unsigned long long *val); /** @@ -340,11 +336,11 @@ GNUNET_GETOPT_option_ulong (char shortName, * @param[out] val set to the time specified at the command line */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_relative_time (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - struct GNUNET_TIME_Relative *val); +GNUNET_GETOPT_option_relative_time(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + struct GNUNET_TIME_Relative *val); /** @@ -358,11 +354,11 @@ GNUNET_GETOPT_option_relative_time (char shortName, * @param[out] val set to the time specified at the command line */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_absolute_time (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - struct GNUNET_TIME_Absolute *val); +GNUNET_GETOPT_option_absolute_time(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + struct GNUNET_TIME_Absolute *val); /** @@ -375,10 +371,10 @@ GNUNET_GETOPT_option_absolute_time (char shortName, * @param[out] val set to 1 if the option is present */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_increment_uint (char shortName, - const char *name, - const char *description, - unsigned int *val); +GNUNET_GETOPT_option_increment_uint(char shortName, + const char *name, + const char *description, + unsigned int *val); /** @@ -388,7 +384,7 @@ GNUNET_GETOPT_option_increment_uint (char shortName, * @param[out] level set to the log level */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_loglevel (char **level); +GNUNET_GETOPT_option_loglevel(char **level); /** @@ -398,7 +394,7 @@ GNUNET_GETOPT_option_loglevel (char **level); * @param[out] level set to the verbosity level */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_verbose (unsigned int *level); +GNUNET_GETOPT_option_verbose(unsigned int *level); /** @@ -407,7 +403,7 @@ GNUNET_GETOPT_option_verbose (unsigned int *level); * @param[out] logfn set to the name of the logfile */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_logfile (char **logfn); +GNUNET_GETOPT_option_logfile(char **logfn); /** @@ -416,7 +412,7 @@ GNUNET_GETOPT_option_logfile (char **logfn); * @param[out] fn set to the name of the configuration file */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_cfgfile (char **fn); +GNUNET_GETOPT_option_cfgfile(char **fn); /** @@ -426,7 +422,7 @@ GNUNET_GETOPT_option_cfgfile (char **fn); * @return @a opt with the mandatory flag set. */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_mandatory (struct GNUNET_GETOPT_CommandLineOption opt); +GNUNET_GETOPT_option_mandatory(struct GNUNET_GETOPT_CommandLineOption opt); /** @@ -436,7 +432,7 @@ GNUNET_GETOPT_option_mandatory (struct GNUNET_GETOPT_CommandLineOption opt); * @return @a opt with the exclusive flag set. */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_GETOPT_option_exclusive (struct GNUNET_GETOPT_CommandLineOption opt); +GNUNET_GETOPT_option_exclusive(struct GNUNET_GETOPT_CommandLineOption opt); /** @@ -459,10 +455,10 @@ GNUNET_GETOPT_option_exclusive (struct GNUNET_GETOPT_CommandLineOption opt); * argument, or #GNUNET_SYSERR on error */ int -GNUNET_GETOPT_run (const char *binaryOptions, - const struct GNUNET_GETOPT_CommandLineOption *allOptions, - unsigned int argc, - char *const *argv); +GNUNET_GETOPT_run(const char *binaryOptions, + const struct GNUNET_GETOPT_CommandLineOption *allOptions, + unsigned int argc, + char *const *argv); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_gns_service.h b/src/include/gnunet_gns_service.h index ca92e8221..f66bec61e 100644 --- a/src/include/gnunet_gns_service.h +++ b/src/include/gnunet_gns_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -76,7 +76,7 @@ struct GNUNET_GNS_LookupWithTldRequest; * @return handle to the GNS service, or NULL on error */ struct GNUNET_GNS_Handle * -GNUNET_GNS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_GNS_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -85,7 +85,7 @@ GNUNET_GNS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param handle connection to shut down */ void -GNUNET_GNS_disconnect (struct GNUNET_GNS_Handle *handle); +GNUNET_GNS_disconnect(struct GNUNET_GNS_Handle *handle); /** @@ -104,8 +104,7 @@ typedef void (*GNUNET_GNS_LookupResultProcessor) ( /** * Options for the GNS lookup. */ -enum GNUNET_GNS_LocalOptions -{ +enum GNUNET_GNS_LocalOptions { /** * Defaults, look in cache, then in DHT. */ @@ -121,7 +120,6 @@ enum GNUNET_GNS_LocalOptions * is our local namestore), for the others, the DHT is OK. */ GNUNET_GNS_LO_LOCAL_MASTER = 2 - }; @@ -138,13 +136,13 @@ enum GNUNET_GNS_LocalOptions * @return handle to the queued request */ struct GNUNET_GNS_LookupRequest * -GNUNET_GNS_lookup (struct GNUNET_GNS_Handle *handle, - const char *name, - const struct GNUNET_CRYPTO_EcdsaPublicKey *zone, - uint32_t type, - enum GNUNET_GNS_LocalOptions options, - GNUNET_GNS_LookupResultProcessor proc, - void *proc_cls); +GNUNET_GNS_lookup(struct GNUNET_GNS_Handle *handle, + const char *name, + const struct GNUNET_CRYPTO_EcdsaPublicKey *zone, + uint32_t type, + enum GNUNET_GNS_LocalOptions options, + GNUNET_GNS_LookupResultProcessor proc, + void *proc_cls); /** @@ -154,7 +152,7 @@ GNUNET_GNS_lookup (struct GNUNET_GNS_Handle *handle, * @return closure from the lookup result processor */ void * -GNUNET_GNS_lookup_cancel (struct GNUNET_GNS_LookupRequest *lr); +GNUNET_GNS_lookup_cancel(struct GNUNET_GNS_LookupRequest *lr); /** @@ -188,12 +186,12 @@ typedef void (*GNUNET_GNS_LookupResultProcessor2) ( * @return handle to the get request */ struct GNUNET_GNS_LookupWithTldRequest * -GNUNET_GNS_lookup_with_tld (struct GNUNET_GNS_Handle *handle, - const char *name, - uint32_t type, - enum GNUNET_GNS_LocalOptions options, - GNUNET_GNS_LookupResultProcessor2 proc, - void *proc_cls); +GNUNET_GNS_lookup_with_tld(struct GNUNET_GNS_Handle *handle, + const char *name, + uint32_t type, + enum GNUNET_GNS_LocalOptions options, + GNUNET_GNS_LookupResultProcessor2 proc, + void *proc_cls); /** @@ -203,7 +201,7 @@ GNUNET_GNS_lookup_with_tld (struct GNUNET_GNS_Handle *handle, * @return closure from the lookup result processor */ void * -GNUNET_GNS_lookup_with_tld_cancel (struct GNUNET_GNS_LookupWithTldRequest *ltr); +GNUNET_GNS_lookup_with_tld_cancel(struct GNUNET_GNS_LookupWithTldRequest *ltr); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_gnsrecord_lib.h b/src/include/gnunet_gnsrecord_lib.h index a92cdc2e7..5effa855f 100644 --- a/src/include/gnunet_gnsrecord_lib.h +++ b/src/include/gnunet_gnsrecord_lib.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -145,7 +145,6 @@ extern "C" { * Flags that can be set for a record. */ enum GNUNET_GNSRECORD_Flags { - /** * No special options. */ @@ -194,7 +193,6 @@ enum GNUNET_GNSRECORD_Flags { * A GNS record. */ struct GNUNET_GNSRECORD_Data { - /** * Binary value stored in the DNS record. Note: "data" must never * be individually 'malloc'ed, but instead always points into some @@ -255,7 +253,6 @@ struct GNUNET_GNSRECORD_PlaceData { * Information we have in an encrypted block with record data (i.e. in the DHT). */ struct GNUNET_GNSRECORD_Block { - /** * Signature of the block. */ @@ -292,7 +289,6 @@ struct GNUNET_GNSRECORD_Block { * records inseparable from the "main" A/AAAA/VPN/etc. records. */ struct GNUNET_GNSRECORD_BoxRecord { - /** * Protocol of the boxed record (6 = TCP, 17 = UDP, etc.). * Yes, in IP protocols are usually limited to 8 bits. In NBO. @@ -344,7 +340,7 @@ GNUNET_NETWORK_STRUCT_END * @param rd array of records with data to store */ typedef void (*GNUNET_GNSRECORD_RecordCallback) ( - void *cls, unsigned int rd_count, const struct GNUNET_GNSRECORD_Data *rd); + void *cls, unsigned int rd_count, const struct GNUNET_GNSRECORD_Data *rd); /* ***************** API related to GNSRECORD plugins ************** */ @@ -359,8 +355,8 @@ typedef void (*GNUNET_GNSRECORD_RecordCallback) ( * @return NULL on error, otherwise human-readable representation of the value */ char * -GNUNET_GNSRECORD_value_to_string (uint32_t type, const void *data, - size_t data_size); +GNUNET_GNSRECORD_value_to_string(uint32_t type, const void *data, + size_t data_size); /** @@ -374,8 +370,8 @@ GNUNET_GNSRECORD_value_to_string (uint32_t type, const void *data, * @return #GNUNET_OK on success */ int -GNUNET_GNSRECORD_string_to_value (uint32_t type, const char *s, void **data, - size_t *data_size); +GNUNET_GNSRECORD_string_to_value(uint32_t type, const char *s, void **data, + size_t *data_size); /** @@ -385,7 +381,7 @@ GNUNET_GNSRECORD_string_to_value (uint32_t type, const char *s, void **data, * @return corresponding number, UINT32_MAX on error */ uint32_t -GNUNET_GNSRECORD_typename_to_number (const char *dns_typename); +GNUNET_GNSRECORD_typename_to_number(const char *dns_typename); /** @@ -395,7 +391,7 @@ GNUNET_GNSRECORD_typename_to_number (const char *dns_typename); * @return corresponding typestring, NULL on error */ const char * -GNUNET_GNSRECORD_number_to_typename (uint32_t type); +GNUNET_GNSRECORD_number_to_typename(uint32_t type); /* convenience APIs for serializing / deserializing GNS records */ @@ -409,8 +405,8 @@ GNUNET_GNSRECORD_number_to_typename (uint32_t type); * @return the required size to serialize, -1 on error */ ssize_t -GNUNET_GNSRECORD_records_get_size (unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd); +GNUNET_GNSRECORD_records_get_size(unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd); /** @@ -423,9 +419,9 @@ GNUNET_GNSRECORD_records_get_size (unsigned int rd_count, * @return the size of serialized records, -1 if records do not fit */ ssize_t -GNUNET_GNSRECORD_records_serialize (unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd, - size_t dest_size, char *dest); +GNUNET_GNSRECORD_records_serialize(unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd, + size_t dest_size, char *dest); /** @@ -438,9 +434,9 @@ GNUNET_GNSRECORD_records_serialize (unsigned int rd_count, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_GNSRECORD_records_deserialize (size_t len, const char *src, - unsigned int rd_count, - struct GNUNET_GNSRECORD_Data *dest); +GNUNET_GNSRECORD_records_deserialize(size_t len, const char *src, + unsigned int rd_count, + struct GNUNET_GNSRECORD_Data *dest); /* ******* general APIs relating to blocks, records and labels ******** */ @@ -454,7 +450,7 @@ GNUNET_GNSRECORD_records_deserialize (size_t len, const char *src, * #GNUNET_NO if not */ int -GNUNET_GNSRECORD_is_expired (const struct GNUNET_GNSRECORD_Data *rd); +GNUNET_GNSRECORD_is_expired(const struct GNUNET_GNSRECORD_Data *rd); /** @@ -463,7 +459,7 @@ GNUNET_GNSRECORD_is_expired (const struct GNUNET_GNSRECORD_Data *rd); * @return converted result */ char * -GNUNET_GNSRECORD_string_to_lowercase (const char *src); +GNUNET_GNSRECORD_string_to_lowercase(const char *src); /** @@ -476,7 +472,7 @@ GNUNET_GNSRECORD_string_to_lowercase (const char *src); * #GNUNET_GNSRECORD_z2s. */ const char * -GNUNET_GNSRECORD_z2s (const struct GNUNET_CRYPTO_EcdsaPublicKey *z); +GNUNET_GNSRECORD_z2s(const struct GNUNET_CRYPTO_EcdsaPublicKey *z); /** @@ -490,7 +486,7 @@ GNUNET_GNSRECORD_z2s (const struct GNUNET_CRYPTO_EcdsaPublicKey *z); * key in an encoding suitable for DNS labels. */ const char * -GNUNET_GNSRECORD_pkey_to_zkey (const struct GNUNET_CRYPTO_EcdsaPublicKey *pkey); +GNUNET_GNSRECORD_pkey_to_zkey(const struct GNUNET_CRYPTO_EcdsaPublicKey *pkey); /** @@ -503,8 +499,8 @@ GNUNET_GNSRECORD_pkey_to_zkey (const struct GNUNET_CRYPTO_EcdsaPublicKey *pkey); * @return #GNUNET_SYSERR if @a zkey has the wrong syntax */ int -GNUNET_GNSRECORD_zkey_to_pkey (const char *zkey, - struct GNUNET_CRYPTO_EcdsaPublicKey *pkey); +GNUNET_GNSRECORD_zkey_to_pkey(const char *zkey, + struct GNUNET_CRYPTO_EcdsaPublicKey *pkey); /** @@ -515,9 +511,9 @@ GNUNET_GNSRECORD_zkey_to_pkey (const char *zkey, * @param query hash to use for the query */ void -GNUNET_GNSRECORD_query_from_private_key ( - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, const char *label, - struct GNUNET_HashCode *query); +GNUNET_GNSRECORD_query_from_private_key( + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, const char *label, + struct GNUNET_HashCode *query); /** @@ -528,9 +524,9 @@ GNUNET_GNSRECORD_query_from_private_key ( * @param query hash to use for the query */ void -GNUNET_GNSRECORD_query_from_public_key ( - const struct GNUNET_CRYPTO_EcdsaPublicKey *pub, const char *label, - struct GNUNET_HashCode *query); +GNUNET_GNSRECORD_query_from_public_key( + const struct GNUNET_CRYPTO_EcdsaPublicKey *pub, const char *label, + struct GNUNET_HashCode *query); /** @@ -543,11 +539,11 @@ GNUNET_GNSRECORD_query_from_public_key ( * @param rd_count number of records in @a rd */ struct GNUNET_GNSRECORD_Block * -GNUNET_GNSRECORD_block_create (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, - struct GNUNET_TIME_Absolute expire, - const char *label, - const struct GNUNET_GNSRECORD_Data *rd, - unsigned int rd_count); +GNUNET_GNSRECORD_block_create(const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, + struct GNUNET_TIME_Absolute expire, + const char *label, + const struct GNUNET_GNSRECORD_Data *rd, + unsigned int rd_count); /** @@ -562,11 +558,11 @@ GNUNET_GNSRECORD_block_create (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, * @param rd_count number of records in @a rd */ struct GNUNET_GNSRECORD_Block * -GNUNET_GNSRECORD_block_create2 (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, - struct GNUNET_TIME_Absolute expire, - const char *label, - const struct GNUNET_GNSRECORD_Data *rd, - unsigned int rd_count); +GNUNET_GNSRECORD_block_create2(const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, + struct GNUNET_TIME_Absolute expire, + const char *label, + const struct GNUNET_GNSRECORD_Data *rd, + unsigned int rd_count); /** @@ -577,7 +573,7 @@ GNUNET_GNSRECORD_block_create2 (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, * @return #GNUNET_OK if the signature is valid */ int -GNUNET_GNSRECORD_block_verify (const struct GNUNET_GNSRECORD_Block *block); +GNUNET_GNSRECORD_block_verify(const struct GNUNET_GNSRECORD_Block *block); /** @@ -592,10 +588,10 @@ GNUNET_GNSRECORD_block_verify (const struct GNUNET_GNSRECORD_Block *block); * not well-formed */ int -GNUNET_GNSRECORD_block_decrypt ( - const struct GNUNET_GNSRECORD_Block *block, - const struct GNUNET_CRYPTO_EcdsaPublicKey *zone_key, const char *label, - GNUNET_GNSRECORD_RecordCallback proc, void *proc_cls); +GNUNET_GNSRECORD_block_decrypt( + const struct GNUNET_GNSRECORD_Block *block, + const struct GNUNET_CRYPTO_EcdsaPublicKey *zone_key, const char *label, + GNUNET_GNSRECORD_RecordCallback proc, void *proc_cls); /** @@ -606,8 +602,8 @@ GNUNET_GNSRECORD_block_decrypt ( * @return #GNUNET_YES if the records are equal, or #GNUNET_NO if not. */ int -GNUNET_GNSRECORD_records_cmp (const struct GNUNET_GNSRECORD_Data *a, - const struct GNUNET_GNSRECORD_Data *b); +GNUNET_GNSRECORD_records_cmp(const struct GNUNET_GNSRECORD_Data *a, + const struct GNUNET_GNSRECORD_Data *b); /** @@ -620,8 +616,8 @@ GNUNET_GNSRECORD_records_cmp (const struct GNUNET_GNSRECORD_Data *a, * @return absolute expiration time */ struct GNUNET_TIME_Absolute -GNUNET_GNSRECORD_record_get_expiration_time ( - unsigned int rd_count, const struct GNUNET_GNSRECORD_Data *rd); +GNUNET_GNSRECORD_record_get_expiration_time( + unsigned int rd_count, const struct GNUNET_GNSRECORD_Data *rd); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_gnsrecord_plugin.h b/src/include/gnunet_gnsrecord_plugin.h index cc10e3e7f..7ce1b22e6 100644 --- a/src/include/gnunet_gnsrecord_plugin.h +++ b/src/include/gnunet_gnsrecord_plugin.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -55,9 +55,9 @@ extern "C" */ typedef char * (*GNUNET_GNSRECORD_ValueToStringFunction) (void *cls, - uint32_t type, - const void *data, - size_t data_size); + uint32_t type, + const void *data, + size_t data_size); /** @@ -74,10 +74,10 @@ typedef char * */ typedef int (*GNUNET_GNSRECORD_StringToValueFunction) (void *cls, - uint32_t type, - const char *s, - void **data, - size_t *data_size); + uint32_t type, + const char *s, + void **data, + size_t *data_size); /** @@ -90,7 +90,7 @@ typedef int */ typedef uint32_t (*GNUNET_GNSRECORD_TypenameToNumberFunction) (void *cls, - const char *dns_typename); + const char *dns_typename); /** @@ -103,16 +103,14 @@ typedef uint32_t */ typedef const char * (*GNUNET_GNSRECORD_NumberToTypenameFunction) (void *cls, - uint32_t type); + uint32_t type); /** * Each plugin is required to return a pointer to a struct of this * type as the return value from its entry point. */ -struct GNUNET_GNSRECORD_PluginFunctions -{ - +struct GNUNET_GNSRECORD_PluginFunctions { /** * Closure for all of the callbacks. */ @@ -137,7 +135,6 @@ struct GNUNET_GNSRECORD_PluginFunctions * Number to typename. */ GNUNET_GNSRECORD_NumberToTypenameFunction number_to_typename; - }; /** @} */ /* end of group */ diff --git a/src/include/gnunet_hello_lib.h b/src/include/gnunet_hello_lib.h index 3b494f0a2..9fe158852 100644 --- a/src/include/gnunet_hello_lib.h +++ b/src/include/gnunet_hello_lib.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -65,8 +65,7 @@ extern "C" { * These information are only valid for the local peer and are not serialized * when a #GNUNET_HELLO_Message is created */ -enum GNUNET_HELLO_AddressInfo -{ +enum GNUNET_HELLO_AddressInfo { /** * No additional information */ @@ -86,9 +85,7 @@ enum GNUNET_HELLO_AddressInfo * separated. This is NOT the format that would be used * on the wire. */ -struct GNUNET_HELLO_Address -{ - +struct GNUNET_HELLO_Address { /** * For which peer is this an address? */ @@ -135,11 +132,11 @@ struct GNUNET_HELLO_Address * @return the address struct */ struct GNUNET_HELLO_Address * -GNUNET_HELLO_address_allocate (const struct GNUNET_PeerIdentity *peer, - const char *transport_name, - const void *address, - size_t address_length, - enum GNUNET_HELLO_AddressInfo local_info); +GNUNET_HELLO_address_allocate(const struct GNUNET_PeerIdentity *peer, + const char *transport_name, + const void *address, + size_t address_length, + enum GNUNET_HELLO_AddressInfo local_info); /** @@ -149,7 +146,7 @@ GNUNET_HELLO_address_allocate (const struct GNUNET_PeerIdentity *peer, * @return a copy of the address struct */ struct GNUNET_HELLO_Address * -GNUNET_HELLO_address_copy (const struct GNUNET_HELLO_Address *address); +GNUNET_HELLO_address_copy(const struct GNUNET_HELLO_Address *address); /** @@ -161,8 +158,8 @@ GNUNET_HELLO_address_copy (const struct GNUNET_HELLO_Address *address); * @return 0 if the addresses are equal, -1 if @a a1< @a a2, 1 if @a a1> @a a2. */ int -GNUNET_HELLO_address_cmp (const struct GNUNET_HELLO_Address *a1, - const struct GNUNET_HELLO_Address *a2); +GNUNET_HELLO_address_cmp(const struct GNUNET_HELLO_Address *a1, + const struct GNUNET_HELLO_Address *a2); /** @@ -172,7 +169,7 @@ GNUNET_HELLO_address_cmp (const struct GNUNET_HELLO_Address *a1, * @return the size */ size_t -GNUNET_HELLO_address_get_size (const struct GNUNET_HELLO_Address *address); +GNUNET_HELLO_address_get_size(const struct GNUNET_HELLO_Address *address); /** @@ -183,8 +180,8 @@ GNUNET_HELLO_address_get_size (const struct GNUNET_HELLO_Address *address); * @return #GNUNET_YES or #GNUNET_NO */ int -GNUNET_HELLO_address_check_option (const struct GNUNET_HELLO_Address *address, - enum GNUNET_HELLO_AddressInfo option); +GNUNET_HELLO_address_check_option(const struct GNUNET_HELLO_Address *address, + enum GNUNET_HELLO_AddressInfo option); /** @@ -192,7 +189,7 @@ GNUNET_HELLO_address_check_option (const struct GNUNET_HELLO_Address *address, * * @param addr address to free */ -#define GNUNET_HELLO_address_free(addr) GNUNET_free (addr) +#define GNUNET_HELLO_address_free(addr) GNUNET_free(addr) GNUNET_NETWORK_STRUCT_BEGIN @@ -210,8 +207,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * unaligned!) * 4) address (address-length bytes; possibly unaligned!) */ -struct GNUNET_HELLO_Message -{ +struct GNUNET_HELLO_Message { /** * Type will be #GNUNET_MESSAGE_TYPE_HELLO. */ @@ -237,7 +233,7 @@ GNUNET_NETWORK_STRUCT_END * @return #GNUNET_YES for friend-only or #GNUNET_NO otherwise */ int -GNUNET_HELLO_is_friend_only (const struct GNUNET_HELLO_Message *h); +GNUNET_HELLO_is_friend_only(const struct GNUNET_HELLO_Message *h); /** @@ -252,10 +248,10 @@ GNUNET_HELLO_is_friend_only (const struct GNUNET_HELLO_Message *h); * the target buffer was not big enough. */ size_t -GNUNET_HELLO_add_address (const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration, - char *target, - size_t max); +GNUNET_HELLO_add_address(const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration, + char *target, + size_t max); /** @@ -289,10 +285,10 @@ typedef ssize_t (*GNUNET_HELLO_GenerateAddressListCallback) (void *cls, * @return the hello message */ struct GNUNET_HELLO_Message * -GNUNET_HELLO_create (const struct GNUNET_CRYPTO_EddsaPublicKey *public_key, - GNUNET_HELLO_GenerateAddressListCallback addrgen, - void *addrgen_cls, - int friend_only); +GNUNET_HELLO_create(const struct GNUNET_CRYPTO_EddsaPublicKey *public_key, + GNUNET_HELLO_GenerateAddressListCallback addrgen, + void *addrgen_cls, + int friend_only); /** @@ -302,7 +298,7 @@ GNUNET_HELLO_create (const struct GNUNET_CRYPTO_EddsaPublicKey *public_key, * @return the size, 0 if HELLO is invalid */ uint16_t -GNUNET_HELLO_size (const struct GNUNET_HELLO_Message *hello); +GNUNET_HELLO_size(const struct GNUNET_HELLO_Message *hello); /** @@ -315,8 +311,8 @@ GNUNET_HELLO_size (const struct GNUNET_HELLO_Message *hello); * @return the combined hello message */ struct GNUNET_HELLO_Message * -GNUNET_HELLO_merge (const struct GNUNET_HELLO_Message *h1, - const struct GNUNET_HELLO_Message *h2); +GNUNET_HELLO_merge(const struct GNUNET_HELLO_Message *h1, + const struct GNUNET_HELLO_Message *h2); /** @@ -336,9 +332,9 @@ GNUNET_HELLO_merge (const struct GNUNET_HELLO_Message *h1, * do not match at all */ struct GNUNET_TIME_Absolute -GNUNET_HELLO_equals (const struct GNUNET_HELLO_Message *h1, - const struct GNUNET_HELLO_Message *h2, - struct GNUNET_TIME_Absolute now); +GNUNET_HELLO_equals(const struct GNUNET_HELLO_Message *h1, + const struct GNUNET_HELLO_Message *h2, + struct GNUNET_TIME_Absolute now); /** @@ -364,7 +360,7 @@ typedef int (*GNUNET_HELLO_AddressIterator) ( * @return time the last address expires, 0 if there are no addresses in the HELLO */ struct GNUNET_TIME_Absolute -GNUNET_HELLO_get_last_expiration (const struct GNUNET_HELLO_Message *msg); +GNUNET_HELLO_get_last_expiration(const struct GNUNET_HELLO_Message *msg); /** @@ -380,10 +376,10 @@ GNUNET_HELLO_get_last_expiration (const struct GNUNET_HELLO_Message *msg); * @return the modified HELLO or NULL */ struct GNUNET_HELLO_Message * -GNUNET_HELLO_iterate_addresses (const struct GNUNET_HELLO_Message *msg, - int return_modified, - GNUNET_HELLO_AddressIterator it, - void *it_cls); +GNUNET_HELLO_iterate_addresses(const struct GNUNET_HELLO_Message *msg, + int return_modified, + GNUNET_HELLO_AddressIterator it, + void *it_cls); /** @@ -400,7 +396,7 @@ GNUNET_HELLO_iterate_addresses (const struct GNUNET_HELLO_Message *msg, * @param it_cls closure for @a it */ void -GNUNET_HELLO_iterate_new_addresses ( +GNUNET_HELLO_iterate_new_addresses( const struct GNUNET_HELLO_Message *new_hello, const struct GNUNET_HELLO_Message *old_hello, struct GNUNET_TIME_Absolute expiration_limit, @@ -416,8 +412,8 @@ GNUNET_HELLO_iterate_new_addresses ( * @return #GNUNET_SYSERR if the HELLO was malformed */ int -GNUNET_HELLO_get_id (const struct GNUNET_HELLO_Message *hello, - struct GNUNET_PeerIdentity *peer); +GNUNET_HELLO_get_id(const struct GNUNET_HELLO_Message *hello, + struct GNUNET_PeerIdentity *peer); /** @@ -429,7 +425,7 @@ GNUNET_HELLO_get_id (const struct GNUNET_HELLO_Message *hello, * @return header or NULL if the HELLO was malformed */ struct GNUNET_MessageHeader * -GNUNET_HELLO_get_header (struct GNUNET_HELLO_Message *hello); +GNUNET_HELLO_get_header(struct GNUNET_HELLO_Message *hello); /** @@ -440,7 +436,7 @@ GNUNET_HELLO_get_header (struct GNUNET_HELLO_Message *hello); * @return NULL if a plugin with name @a name is not known/loadable */ typedef struct GNUNET_TRANSPORT_PluginFunctions *( - *GNUNET_HELLO_TransportPluginsFind) (const char *name); +*GNUNET_HELLO_TransportPluginsFind) (const char *name); /** @@ -451,8 +447,8 @@ typedef struct GNUNET_TRANSPORT_PluginFunctions *( * @return Hello URI string */ char * -GNUNET_HELLO_compose_uri (const struct GNUNET_HELLO_Message *hello, - GNUNET_HELLO_TransportPluginsFind plugins_find); +GNUNET_HELLO_compose_uri(const struct GNUNET_HELLO_Message *hello, + GNUNET_HELLO_TransportPluginsFind plugins_find); /** @@ -465,10 +461,10 @@ GNUNET_HELLO_compose_uri (const struct GNUNET_HELLO_Message *hello, * @return #GNUNET_OK on success, #GNUNET_SYSERR if the URI was invalid, #GNUNET_NO on other errors */ int -GNUNET_HELLO_parse_uri (const char *uri, - struct GNUNET_CRYPTO_EddsaPublicKey *pubkey, - struct GNUNET_HELLO_Message **hello, - GNUNET_HELLO_TransportPluginsFind plugins_find); +GNUNET_HELLO_parse_uri(const char *uri, + struct GNUNET_CRYPTO_EddsaPublicKey *pubkey, + struct GNUNET_HELLO_Message **hello, + GNUNET_HELLO_TransportPluginsFind plugins_find); /* NG API */ @@ -486,7 +482,7 @@ GNUNET_HELLO_parse_uri (const char *uri, * @param result_size[out] set to size of @a result */ void -GNUNET_HELLO_sign_address ( +GNUNET_HELLO_sign_address( const char *address, enum GNUNET_NetworkType nt, struct GNUNET_TIME_Absolute mono_time, @@ -506,11 +502,11 @@ GNUNET_HELLO_sign_address ( * @return NULL on error, otherwise the address */ char * -GNUNET_HELLO_extract_address (const void *raw, - size_t raw_size, - const struct GNUNET_PeerIdentity *pid, - enum GNUNET_NetworkType *nt, - struct GNUNET_TIME_Absolute *mono_time); +GNUNET_HELLO_extract_address(const void *raw, + size_t raw_size, + const struct GNUNET_PeerIdentity *pid, + enum GNUNET_NetworkType *nt, + struct GNUNET_TIME_Absolute *mono_time); /** @@ -521,7 +517,7 @@ GNUNET_HELLO_extract_address (const void *raw, * @return NULL if the address is mal-formed, otherwise the prefix */ char * -GNUNET_HELLO_address_to_prefix (const char *address); +GNUNET_HELLO_address_to_prefix(const char *address); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_helper_lib.h b/src/include/gnunet_helper_lib.h index 5a34daf78..e6b3ae535 100644 --- a/src/include/gnunet_helper_lib.h +++ b/src/include/gnunet_helper_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Philipp Toelke @@ -74,12 +74,12 @@ typedef void * @return the new Handle, NULL on error */ struct GNUNET_HELPER_Handle * -GNUNET_HELPER_start (int with_control_pipe, - const char *binary_name, - char *const binary_argv[], - GNUNET_MessageTokenizerCallback cb, - GNUNET_HELPER_ExceptionCallback exp_cb, - void *cb_cls); +GNUNET_HELPER_start(int with_control_pipe, + const char *binary_name, + char *const binary_argv[], + GNUNET_MessageTokenizerCallback cb, + GNUNET_HELPER_ExceptionCallback exp_cb, + void *cb_cls); /** @@ -92,7 +92,7 @@ GNUNET_HELPER_start (int with_control_pipe, * @return #GNUNET_OK on success; #GNUNET_SYSERR on error */ int -GNUNET_HELPER_kill (struct GNUNET_HELPER_Handle *h, int soft_kill); +GNUNET_HELPER_kill(struct GNUNET_HELPER_Handle *h, int soft_kill); /** @@ -104,7 +104,7 @@ GNUNET_HELPER_kill (struct GNUNET_HELPER_Handle *h, int soft_kill); * @return #GNUNET_OK on success; #GNUNET_SYSERR on error */ int -GNUNET_HELPER_wait (struct GNUNET_HELPER_Handle *h); +GNUNET_HELPER_wait(struct GNUNET_HELPER_Handle *h); /** @@ -113,7 +113,7 @@ GNUNET_HELPER_wait (struct GNUNET_HELPER_Handle *h); * @param h the helper handle to free */ void -GNUNET_HELPER_destroy (struct GNUNET_HELPER_Handle *h); +GNUNET_HELPER_destroy(struct GNUNET_HELPER_Handle *h); /** @@ -125,7 +125,7 @@ GNUNET_HELPER_destroy (struct GNUNET_HELPER_Handle *h); * stdin; #GNUNET_NO to signal termination by sending SIGTERM to helper */ void -GNUNET_HELPER_stop (struct GNUNET_HELPER_Handle *h, int soft_kill); +GNUNET_HELPER_stop(struct GNUNET_HELPER_Handle *h, int soft_kill); /** @@ -137,7 +137,7 @@ GNUNET_HELPER_stop (struct GNUNET_HELPER_Handle *h, int soft_kill); * #GNUNET_SYSERR during GNUNET_HELPER_destroy */ typedef void (*GNUNET_HELPER_Continuation)(void *cls, - int result); + int result); /** @@ -160,11 +160,11 @@ struct GNUNET_HELPER_SendHandle; * not be abortable) */ struct GNUNET_HELPER_SendHandle * -GNUNET_HELPER_send (struct GNUNET_HELPER_Handle *h, - const struct GNUNET_MessageHeader *msg, - int can_drop, - GNUNET_HELPER_Continuation cont, - void *cont_cls); +GNUNET_HELPER_send(struct GNUNET_HELPER_Handle *h, + const struct GNUNET_MessageHeader *msg, + int can_drop, + GNUNET_HELPER_Continuation cont, + void *cont_cls); /** @@ -174,7 +174,7 @@ GNUNET_HELPER_send (struct GNUNET_HELPER_Handle *h, * @param sh operation to cancel */ void -GNUNET_HELPER_send_cancel (struct GNUNET_HELPER_SendHandle *sh); +GNUNET_HELPER_send_cancel(struct GNUNET_HELPER_SendHandle *sh); #endif diff --git a/src/include/gnunet_identity_service.h b/src/include/gnunet_identity_service.h index 52ed1e908..8a77e76e0 100644 --- a/src/include/gnunet_identity_service.h +++ b/src/include/gnunet_identity_service.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -80,7 +80,7 @@ struct GNUNET_IDENTITY_Operation; * @return associated ECC key, valid as long as the ego is valid */ const struct GNUNET_CRYPTO_EcdsaPrivateKey * -GNUNET_IDENTITY_ego_get_private_key (const struct GNUNET_IDENTITY_Ego *ego); +GNUNET_IDENTITY_ego_get_private_key(const struct GNUNET_IDENTITY_Ego *ego); /** @@ -89,7 +89,7 @@ GNUNET_IDENTITY_ego_get_private_key (const struct GNUNET_IDENTITY_Ego *ego); * @return handle for the anonymous user, must not be freed */ const struct GNUNET_IDENTITY_Ego * -GNUNET_IDENTITY_ego_get_anonymous (void); +GNUNET_IDENTITY_ego_get_anonymous(void); /** @@ -99,8 +99,8 @@ GNUNET_IDENTITY_ego_get_anonymous (void); * @param pk set to ego's public key */ void -GNUNET_IDENTITY_ego_get_public_key (const struct GNUNET_IDENTITY_Ego *ego, - struct GNUNET_CRYPTO_EcdsaPublicKey *pk); +GNUNET_IDENTITY_ego_get_public_key(const struct GNUNET_IDENTITY_Ego *ego, + struct GNUNET_CRYPTO_EcdsaPublicKey *pk); /** @@ -152,9 +152,9 @@ typedef void (*GNUNET_IDENTITY_Callback) (void *cls, * @return handle to communicate with identity service */ struct GNUNET_IDENTITY_Handle * -GNUNET_IDENTITY_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_IDENTITY_Callback cb, - void *cb_cls); +GNUNET_IDENTITY_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_IDENTITY_Callback cb, + void *cb_cls); /** @@ -167,10 +167,10 @@ GNUNET_IDENTITY_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return handle to abort the operation */ struct GNUNET_IDENTITY_Operation * -GNUNET_IDENTITY_get (struct GNUNET_IDENTITY_Handle *id, - const char *service_name, - GNUNET_IDENTITY_Callback cb, - void *cb_cls); +GNUNET_IDENTITY_get(struct GNUNET_IDENTITY_Handle *id, + const char *service_name, + GNUNET_IDENTITY_Callback cb, + void *cb_cls); /** @@ -194,11 +194,11 @@ typedef void (*GNUNET_IDENTITY_Continuation) (void *cls, const char *emsg); * @return handle to abort the operation */ struct GNUNET_IDENTITY_Operation * -GNUNET_IDENTITY_set (struct GNUNET_IDENTITY_Handle *id, - const char *service_name, - struct GNUNET_IDENTITY_Ego *ego, - GNUNET_IDENTITY_Continuation cont, - void *cont_cls); +GNUNET_IDENTITY_set(struct GNUNET_IDENTITY_Handle *id, + const char *service_name, + struct GNUNET_IDENTITY_Ego *ego, + GNUNET_IDENTITY_Continuation cont, + void *cont_cls); /** @@ -207,7 +207,7 @@ GNUNET_IDENTITY_set (struct GNUNET_IDENTITY_Handle *id, * @param h identity service to disconnect */ void -GNUNET_IDENTITY_disconnect (struct GNUNET_IDENTITY_Handle *h); +GNUNET_IDENTITY_disconnect(struct GNUNET_IDENTITY_Handle *h); /** @@ -234,10 +234,10 @@ typedef void (*GNUNET_IDENTITY_CreateContinuation) ( * @return handle to abort the operation */ struct GNUNET_IDENTITY_Operation * -GNUNET_IDENTITY_create (struct GNUNET_IDENTITY_Handle *id, - const char *name, - GNUNET_IDENTITY_CreateContinuation cont, - void *cont_cls); +GNUNET_IDENTITY_create(struct GNUNET_IDENTITY_Handle *id, + const char *name, + GNUNET_IDENTITY_CreateContinuation cont, + void *cont_cls); /** @@ -251,11 +251,11 @@ GNUNET_IDENTITY_create (struct GNUNET_IDENTITY_Handle *id, * @return handle to abort the operation */ struct GNUNET_IDENTITY_Operation * -GNUNET_IDENTITY_rename (struct GNUNET_IDENTITY_Handle *id, - const char *old_name, - const char *new_name, - GNUNET_IDENTITY_Continuation cb, - void *cb_cls); +GNUNET_IDENTITY_rename(struct GNUNET_IDENTITY_Handle *id, + const char *old_name, + const char *new_name, + GNUNET_IDENTITY_Continuation cb, + void *cb_cls); /** @@ -268,10 +268,10 @@ GNUNET_IDENTITY_rename (struct GNUNET_IDENTITY_Handle *id, * @return handle to abort the operation */ struct GNUNET_IDENTITY_Operation * -GNUNET_IDENTITY_delete (struct GNUNET_IDENTITY_Handle *id, - const char *name, - GNUNET_IDENTITY_Continuation cb, - void *cb_cls); +GNUNET_IDENTITY_delete(struct GNUNET_IDENTITY_Handle *id, + const char *name, + GNUNET_IDENTITY_Continuation cb, + void *cb_cls); /** @@ -283,7 +283,7 @@ GNUNET_IDENTITY_delete (struct GNUNET_IDENTITY_Handle *id, * @param op operation to cancel */ void -GNUNET_IDENTITY_cancel (struct GNUNET_IDENTITY_Operation *op); +GNUNET_IDENTITY_cancel(struct GNUNET_IDENTITY_Operation *op); /* ************* convenience API to lookup an ego ***************** */ @@ -314,10 +314,10 @@ struct GNUNET_IDENTITY_EgoLookup; * @return NULL on error */ struct GNUNET_IDENTITY_EgoLookup * -GNUNET_IDENTITY_ego_lookup (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *name, - GNUNET_IDENTITY_EgoCallback cb, - void *cb_cls); +GNUNET_IDENTITY_ego_lookup(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *name, + GNUNET_IDENTITY_EgoCallback cb, + void *cb_cls); /** @@ -326,7 +326,7 @@ GNUNET_IDENTITY_ego_lookup (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param el handle for lookup to abort */ void -GNUNET_IDENTITY_ego_lookup_cancel (struct GNUNET_IDENTITY_EgoLookup *el); +GNUNET_IDENTITY_ego_lookup_cancel(struct GNUNET_IDENTITY_EgoLookup *el); /** * Function called with the result. @@ -360,10 +360,10 @@ struct GNUNET_IDENTITY_EgoSuffixLookup; * @return handle to abort the operation */ struct GNUNET_IDENTITY_EgoSuffixLookup * -GNUNET_IDENTITY_ego_lookup_by_suffix (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *suffix, - GNUNET_IDENTITY_EgoSuffixCallback cb, - void *cb_cls); +GNUNET_IDENTITY_ego_lookup_by_suffix(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *suffix, + GNUNET_IDENTITY_EgoSuffixCallback cb, + void *cb_cls); /** @@ -372,7 +372,7 @@ GNUNET_IDENTITY_ego_lookup_by_suffix (const struct GNUNET_CONFIGURATION_Handle * * @param el handle for lookup to abort */ void -GNUNET_IDENTITY_ego_lookup_by_suffix_cancel (struct GNUNET_IDENTITY_EgoSuffixLookup *el); +GNUNET_IDENTITY_ego_lookup_by_suffix_cancel(struct GNUNET_IDENTITY_EgoSuffixLookup *el); #if 0 /* keep Emacsens' auto-indent happy */ { diff --git a/src/include/gnunet_json_lib.h b/src/include/gnunet_json_lib.h index bba994d03..3ca4bf729 100644 --- a/src/include/gnunet_json_lib.h +++ b/src/include/gnunet_json_lib.h @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2014, 2015, 2016 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2014, 2015, 2016 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnunet_json_lib.h * @brief functions to parse JSON objects into GNUnet objects @@ -67,8 +67,7 @@ typedef void (*GNUNET_JSON_Cleaner) (void *cls, /** * @brief Entry in parser specification for #GNUNET_JSON_parse(). */ -struct GNUNET_JSON_Specification -{ +struct GNUNET_JSON_Specification { /** * Function for how to parse this type of entry. */ @@ -126,10 +125,10 @@ struct GNUNET_JSON_Specification * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_JSON_parse (const json_t *root, - struct GNUNET_JSON_Specification *spec, - const char **error_json_name, - unsigned int *error_line); +GNUNET_JSON_parse(const json_t *root, + struct GNUNET_JSON_Specification *spec, + const char **error_json_name, + unsigned int *error_line); /** @@ -139,7 +138,7 @@ GNUNET_JSON_parse (const json_t *root, * @param spec specification of the parse operation */ void -GNUNET_JSON_parse_free (struct GNUNET_JSON_Specification *spec); +GNUNET_JSON_parse_free(struct GNUNET_JSON_Specification *spec); /* ****************** Canonical parser specifications ******************* */ @@ -149,7 +148,7 @@ GNUNET_JSON_parse_free (struct GNUNET_JSON_Specification *spec); * End of a parser specification. */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_end (void); +GNUNET_JSON_spec_end(void); /** @@ -159,7 +158,7 @@ GNUNET_JSON_spec_end (void); * @return spec copy of @a spec with optional bit set */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_mark_optional (struct GNUNET_JSON_Specification spec); +GNUNET_JSON_spec_mark_optional(struct GNUNET_JSON_Specification spec); /** @@ -171,7 +170,7 @@ GNUNET_JSON_spec_mark_optional (struct GNUNET_JSON_Specification spec); * @param size number of bytes expected in @a obj */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_fixed (const char *name, void *obj, size_t size); +GNUNET_JSON_spec_fixed(const char *name, void *obj, size_t size); /** @@ -182,7 +181,7 @@ GNUNET_JSON_spec_fixed (const char *name, void *obj, size_t size); * @param obj pointer where to write the data (type of `*obj` will determine size) */ #define GNUNET_JSON_spec_fixed_auto(name, obj) \ - GNUNET_JSON_spec_fixed (name, obj, sizeof (*obj)) + GNUNET_JSON_spec_fixed(name, obj, sizeof(*obj)) /** @@ -194,7 +193,7 @@ GNUNET_JSON_spec_fixed (const char *name, void *obj, size_t size); * @param[out] size where to store the number of bytes allocated for @a obj */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_varsize (const char *name, void **obj, size_t *size); +GNUNET_JSON_spec_varsize(const char *name, void **obj, size_t *size); /** @@ -204,7 +203,7 @@ GNUNET_JSON_spec_varsize (const char *name, void **obj, size_t *size); * @param strptr where to store a pointer to the field */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_string (const char *name, const char **strptr); +GNUNET_JSON_spec_string(const char *name, const char **strptr); /** * JSON object. @@ -213,7 +212,7 @@ GNUNET_JSON_spec_string (const char *name, const char **strptr); * @param[out] jsonp where to store the JSON found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_json (const char *name, json_t **jsonp); +GNUNET_JSON_spec_json(const char *name, json_t **jsonp); /** @@ -223,7 +222,7 @@ GNUNET_JSON_spec_json (const char *name, json_t **jsonp); * @param[out] u8 where to store the integer found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_uint8 (const char *name, uint8_t *u8); +GNUNET_JSON_spec_uint8(const char *name, uint8_t *u8); /** @@ -233,7 +232,7 @@ GNUNET_JSON_spec_uint8 (const char *name, uint8_t *u8); * @param[out] u16 where to store the integer found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_uint16 (const char *name, uint16_t *u16); +GNUNET_JSON_spec_uint16(const char *name, uint16_t *u16); /** @@ -243,7 +242,7 @@ GNUNET_JSON_spec_uint16 (const char *name, uint16_t *u16); * @param[out] u32 where to store the integer found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_uint32 (const char *name, uint32_t *u32); +GNUNET_JSON_spec_uint32(const char *name, uint32_t *u32); /** @@ -253,7 +252,7 @@ GNUNET_JSON_spec_uint32 (const char *name, uint32_t *u32); * @param[out] u64 where to store the integer found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_uint64 (const char *name, uint64_t *u64); +GNUNET_JSON_spec_uint64(const char *name, uint64_t *u64); /** @@ -263,7 +262,7 @@ GNUNET_JSON_spec_uint64 (const char *name, uint64_t *u64); * @param[out] boolean where to store the boolean found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_boolean (const char *name, int *boolean); +GNUNET_JSON_spec_boolean(const char *name, int *boolean); /* ************ GNUnet-specific parser specifications ******************* */ @@ -275,8 +274,8 @@ GNUNET_JSON_spec_boolean (const char *name, int *boolean); * @param[out] at where to store the absolute time found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_absolute_time (const char *name, - struct GNUNET_TIME_Absolute *at); +GNUNET_JSON_spec_absolute_time(const char *name, + struct GNUNET_TIME_Absolute *at); /** @@ -286,8 +285,8 @@ GNUNET_JSON_spec_absolute_time (const char *name, * @param[out] at where to store the absolute time found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_absolute_time_nbo (const char *name, - struct GNUNET_TIME_AbsoluteNBO *at); +GNUNET_JSON_spec_absolute_time_nbo(const char *name, + struct GNUNET_TIME_AbsoluteNBO *at); /** @@ -297,8 +296,8 @@ GNUNET_JSON_spec_absolute_time_nbo (const char *name, * @param[out] rt where to store the relative time found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_relative_time (const char *name, - struct GNUNET_TIME_Relative *rt); +GNUNET_JSON_spec_relative_time(const char *name, + struct GNUNET_TIME_Relative *rt); /** @@ -308,8 +307,8 @@ GNUNET_JSON_spec_relative_time (const char *name, * @param pk where to store the RSA key found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_rsa_public_key (const char *name, - struct GNUNET_CRYPTO_RsaPublicKey **pk); +GNUNET_JSON_spec_rsa_public_key(const char *name, + struct GNUNET_CRYPTO_RsaPublicKey **pk); /** @@ -319,8 +318,8 @@ GNUNET_JSON_spec_rsa_public_key (const char *name, * @param sig where to store the RSA signature found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_rsa_signature (const char *name, - struct GNUNET_CRYPTO_RsaSignature **sig); +GNUNET_JSON_spec_rsa_signature(const char *name, + struct GNUNET_CRYPTO_RsaSignature **sig); /** @@ -330,9 +329,9 @@ GNUNET_JSON_spec_rsa_signature (const char *name, * @return JSON Specification */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_gnsrecord (struct GNUNET_GNSRECORD_Data **rd, - unsigned int *rd_count, - char **name); +GNUNET_JSON_spec_gnsrecord(struct GNUNET_GNSRECORD_Data **rd, + unsigned int *rd_count, + char **name); /* ****************** Generic generator interface ******************* */ @@ -347,7 +346,7 @@ GNUNET_JSON_spec_gnsrecord (struct GNUNET_GNSRECORD_Data **rd, * @return json string that encodes @a data */ json_t * -GNUNET_JSON_from_data (const void *data, size_t size); +GNUNET_JSON_from_data(const void *data, size_t size); /** @@ -358,7 +357,7 @@ GNUNET_JSON_from_data (const void *data, size_t size); * @return json string that encodes @a data */ #define GNUNET_JSON_from_data_auto(ptr) \ - GNUNET_JSON_from_data (ptr, sizeof (*ptr)) + GNUNET_JSON_from_data(ptr, sizeof(*ptr)) /** @@ -368,7 +367,7 @@ GNUNET_JSON_from_data (const void *data, size_t size); * @return a json string with the timestamp in @a stamp */ json_t * -GNUNET_JSON_from_time_abs (struct GNUNET_TIME_Absolute stamp); +GNUNET_JSON_from_time_abs(struct GNUNET_TIME_Absolute stamp); /** @@ -378,7 +377,7 @@ GNUNET_JSON_from_time_abs (struct GNUNET_TIME_Absolute stamp); * @return a json string with the timestamp in @a stamp */ json_t * -GNUNET_JSON_from_time_abs_nbo (struct GNUNET_TIME_AbsoluteNBO stamp); +GNUNET_JSON_from_time_abs_nbo(struct GNUNET_TIME_AbsoluteNBO stamp); /** @@ -388,7 +387,7 @@ GNUNET_JSON_from_time_abs_nbo (struct GNUNET_TIME_AbsoluteNBO stamp); * @return a json string with the timestamp in @a stamp */ json_t * -GNUNET_JSON_from_time_rel (struct GNUNET_TIME_Relative stamp); +GNUNET_JSON_from_time_rel(struct GNUNET_TIME_Relative stamp); /** @@ -398,7 +397,7 @@ GNUNET_JSON_from_time_rel (struct GNUNET_TIME_Relative stamp); * @return corresponding JSON encoding */ json_t * -GNUNET_JSON_from_rsa_public_key (const struct GNUNET_CRYPTO_RsaPublicKey *pk); +GNUNET_JSON_from_rsa_public_key(const struct GNUNET_CRYPTO_RsaPublicKey *pk); /** @@ -408,7 +407,7 @@ GNUNET_JSON_from_rsa_public_key (const struct GNUNET_CRYPTO_RsaPublicKey *pk); * @return corresponding JSON encoding */ json_t * -GNUNET_JSON_from_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *sig); +GNUNET_JSON_from_rsa_signature(const struct GNUNET_CRYPTO_RsaSignature *sig); /** * Convert Gns record to JSON. @@ -418,17 +417,16 @@ GNUNET_JSON_from_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *sig); * @return corresponding JSON encoding */ json_t * -GNUNET_JSON_from_gnsrecord (const char *rname, - const struct GNUNET_GNSRECORD_Data *rd, - unsigned int rd_count); +GNUNET_JSON_from_gnsrecord(const char *rname, + const struct GNUNET_GNSRECORD_Data *rd, + unsigned int rd_count); /* ******************* Helpers for MHD upload handling ******************* */ /** * Return codes from #GNUNET_JSON_post_parser(). */ -enum GNUNET_JSON_PostResult -{ +enum GNUNET_JSON_PostResult { /** * Parsing successful, JSON result is in `*json`. */ @@ -472,12 +470,12 @@ enum GNUNET_JSON_PostResult * @return result code indicating the status of the operation */ enum GNUNET_JSON_PostResult -GNUNET_JSON_post_parser (size_t buffer_max, - struct MHD_Connection *connection, - void **con_cls, - const char *upload_data, - size_t *upload_data_size, - json_t **json); +GNUNET_JSON_post_parser(size_t buffer_max, + struct MHD_Connection *connection, + void **con_cls, + const char *upload_data, + size_t *upload_data_size, + json_t **json); /** @@ -488,7 +486,7 @@ GNUNET_JSON_post_parser (size_t buffer_max, * #GNUNET_JSON_post_parser(), to be cleaned up */ void -GNUNET_JSON_post_parser_cleanup (void *con_cls); +GNUNET_JSON_post_parser_cleanup(void *con_cls); /* ****************** GETOPT JSON helper ******************* */ @@ -504,11 +502,11 @@ GNUNET_JSON_post_parser_cleanup (void *con_cls); * @param[out] val set to the JSON specified at the command line */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_JSON_getopt (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - json_t **json); +GNUNET_JSON_getopt(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + json_t **json); #endif diff --git a/src/include/gnunet_load_lib.h b/src/include/gnunet_load_lib.h index f38b66b88..1e786181f 100644 --- a/src/include/gnunet_load_lib.h +++ b/src/include/gnunet_load_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -57,7 +57,7 @@ struct GNUNET_LOAD_Value; * @return the new load value */ struct GNUNET_LOAD_Value * -GNUNET_LOAD_value_init (struct GNUNET_TIME_Relative autodecline); +GNUNET_LOAD_value_init(struct GNUNET_TIME_Relative autodecline); /** @@ -67,8 +67,8 @@ GNUNET_LOAD_value_init (struct GNUNET_TIME_Relative autodecline); * @param autodecline frequency of load decline */ void -GNUNET_LOAD_value_set_decline (struct GNUNET_LOAD_Value *load, - struct GNUNET_TIME_Relative autodecline); +GNUNET_LOAD_value_set_decline(struct GNUNET_LOAD_Value *load, + struct GNUNET_TIME_Relative autodecline); /** @@ -76,7 +76,7 @@ GNUNET_LOAD_value_set_decline (struct GNUNET_LOAD_Value *load, * * @param lv value to free */ -#define GNUNET_LOAD_value_free(lv) GNUNET_free (lv) +#define GNUNET_LOAD_value_free(lv) GNUNET_free(lv) /** @@ -89,7 +89,7 @@ GNUNET_LOAD_value_set_decline (struct GNUNET_LOAD_Value *load, * that we could not do proper calculations */ double -GNUNET_LOAD_get_load (struct GNUNET_LOAD_Value *load); +GNUNET_LOAD_get_load(struct GNUNET_LOAD_Value *load); /** @@ -99,7 +99,7 @@ GNUNET_LOAD_get_load (struct GNUNET_LOAD_Value *load); * @return zero if update was never called */ double -GNUNET_LOAD_get_average (struct GNUNET_LOAD_Value *load); +GNUNET_LOAD_get_average(struct GNUNET_LOAD_Value *load); /** @@ -109,7 +109,7 @@ GNUNET_LOAD_get_average (struct GNUNET_LOAD_Value *load); * @param data latest measurement value (for example, delay) */ void -GNUNET_LOAD_update (struct GNUNET_LOAD_Value *load, uint64_t data); +GNUNET_LOAD_update(struct GNUNET_LOAD_Value *load, uint64_t data); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_microphone_lib.h b/src/include/gnunet_microphone_lib.h index 46e5bfa25..f5cf4abc6 100644 --- a/src/include/gnunet_microphone_lib.h +++ b/src/include/gnunet_microphone_lib.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet - Copyright (C) 2013 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet + Copyright (C) 2013 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -36,7 +36,7 @@ #ifdef __cplusplus extern "C" { -#if 0 /* keep Emacsens' auto-indent happy */ +#if 0 /* keep Emacsens' auto-indent happy */ } #endif #endif @@ -51,8 +51,8 @@ extern "C" * @param data audio data to play */ typedef void (*GNUNET_MICROPHONE_RecordedDataCallback)(void *cls, - size_t data_size, - const void *data); + size_t data_size, + const void *data); /** * Enable a microphone. @@ -63,8 +63,8 @@ typedef void (*GNUNET_MICROPHONE_RecordedDataCallback)(void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ typedef int (*GNUNET_MICROPHONE_EnableCallback)(void *cls, - GNUNET_MICROPHONE_RecordedDataCallback rdc, - void *rdc_cls); + GNUNET_MICROPHONE_RecordedDataCallback rdc, + void *rdc_cls); /** * Function that disables a microphone. @@ -84,9 +84,7 @@ typedef void (*GNUNET_MICROPHONE_DestroyCallback)(void *cls); /** * A microphone is a device that can capture or otherwise produce audio data. */ -struct GNUNET_MICROPHONE_Handle -{ - +struct GNUNET_MICROPHONE_Handle { /** * Turn on the microphone. */ @@ -106,7 +104,6 @@ struct GNUNET_MICROPHONE_Handle * Closure for the callbacks. */ void *cls; - }; @@ -118,7 +115,7 @@ struct GNUNET_MICROPHONE_Handle * @return NULL on error */ struct GNUNET_MICROPHONE_Handle * -GNUNET_MICROPHONE_create_from_hardware (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_MICROPHONE_create_from_hardware(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -127,10 +124,10 @@ GNUNET_MICROPHONE_create_from_hardware (const struct GNUNET_CONFIGURATION_Handle * @param microphone microphone to destroy */ void -GNUNET_MICROPHONE_destroy (struct GNUNET_MICROPHONE_Handle *microphone); +GNUNET_MICROPHONE_destroy(struct GNUNET_MICROPHONE_Handle *microphone); -#if 0 /* keep Emacsens' auto-indent happy */ +#if 0 /* keep Emacsens' auto-indent happy */ { #endif #ifdef __cplusplus diff --git a/src/include/gnunet_mq_lib.h b/src/include/gnunet_mq_lib.h index f3073d54b..1839a68bd 100644 --- a/src/include/gnunet_mq_lib.h +++ b/src/include/gnunet_mq_lib.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Florian Dold @@ -50,9 +50,9 @@ * @return the MQ message */ #define GNUNET_MQ_msg_extra(mvar, esize, type) \ - GNUNET_MQ_msg_ (((struct GNUNET_MessageHeader **) &(mvar)), \ - (esize) + sizeof *(mvar), \ - (type)) + GNUNET_MQ_msg_(((struct GNUNET_MessageHeader **)&(mvar)), \ + (esize) + sizeof *(mvar), \ + (type)) /** * Allocate a GNUNET_MQ_Envelope. @@ -64,7 +64,7 @@ * @param type type of the message * @return the allocated envelope */ -#define GNUNET_MQ_msg(mvar, type) GNUNET_MQ_msg_extra (mvar, 0, type) +#define GNUNET_MQ_msg(mvar, type) GNUNET_MQ_msg_extra(mvar, 0, type) /** @@ -74,7 +74,7 @@ * @param type type of the message */ #define GNUNET_MQ_msg_header(type) \ - GNUNET_MQ_msg_ (NULL, sizeof (struct GNUNET_MessageHeader), type) + GNUNET_MQ_msg_(NULL, sizeof(struct GNUNET_MessageHeader), type) /** @@ -86,7 +86,7 @@ * @param type type of the message */ #define GNUNET_MQ_msg_header_extra(mh, esize, type) \ - GNUNET_MQ_msg_ (&mh, (esize) + sizeof (struct GNUNET_MessageHeader), type) + GNUNET_MQ_msg_(&mh, (esize) + sizeof(struct GNUNET_MessageHeader), type) /** @@ -102,11 +102,11 @@ #define GNUNET_MQ_msg_nested_mh(mvar, type, mh) \ ({ \ struct GNUNET_MQ_Envelope *_ev; \ - _ev = GNUNET_MQ_msg_nested_mh_ ((struct GNUNET_MessageHeader **) &(mvar), \ - sizeof (*(mvar)), \ - (type), \ - (mh)); \ - (void) (mvar)->header; /* type check */ \ + _ev = GNUNET_MQ_msg_nested_mh_((struct GNUNET_MessageHeader **)&(mvar), \ + sizeof(*(mvar)), \ + (type), \ + (mh)); \ + (void)(mvar)->header; /* type check */ \ _ev; \ }) @@ -120,8 +120,8 @@ * or NULL if the given message in @a var does not have any space after the message struct */ #define GNUNET_MQ_extract_nested_mh(var) \ - GNUNET_MQ_extract_nested_mh_ ((struct GNUNET_MessageHeader *) (var), \ - sizeof (*(var))) + GNUNET_MQ_extract_nested_mh_((struct GNUNET_MessageHeader *)(var), \ + sizeof(*(var))) /** @@ -133,8 +133,8 @@ * OR NULL in case of a malformed message. */ const struct GNUNET_MessageHeader * -GNUNET_MQ_extract_nested_mh_ (const struct GNUNET_MessageHeader *mh, - uint16_t base_size); +GNUNET_MQ_extract_nested_mh_(const struct GNUNET_MessageHeader *mh, + uint16_t base_size); /** @@ -150,7 +150,7 @@ struct GNUNET_MQ_Envelope; * @return message contained in the envelope */ const struct GNUNET_MessageHeader * -GNUNET_MQ_env_get_msg (const struct GNUNET_MQ_Envelope *env); +GNUNET_MQ_env_get_msg(const struct GNUNET_MQ_Envelope *env); /** @@ -160,7 +160,7 @@ GNUNET_MQ_env_get_msg (const struct GNUNET_MQ_Envelope *env); * @return next one, or NULL */ const struct GNUNET_MQ_Envelope * -GNUNET_MQ_env_next (const struct GNUNET_MQ_Envelope *env); +GNUNET_MQ_env_next(const struct GNUNET_MQ_Envelope *env); /** @@ -173,10 +173,10 @@ GNUNET_MQ_env_next (const struct GNUNET_MQ_Envelope *env); * @param nested_mh the message to append to the message after base_size */ struct GNUNET_MQ_Envelope * -GNUNET_MQ_msg_nested_mh_ (struct GNUNET_MessageHeader **mhp, - uint16_t base_size, - uint16_t type, - const struct GNUNET_MessageHeader *nested_mh); +GNUNET_MQ_msg_nested_mh_(struct GNUNET_MessageHeader **mhp, + uint16_t base_size, + uint16_t type, + const struct GNUNET_MessageHeader *nested_mh); /** @@ -188,8 +188,7 @@ struct GNUNET_MQ_Handle; /** * Error codes for the queue. */ -enum GNUNET_MQ_Error -{ +enum GNUNET_MQ_Error { /** * Failed to read message from the network. * FIXME: Likely not properly distinguished @@ -224,9 +223,7 @@ enum GNUNET_MQ_Error /** * Per envelope preferences and priorities. */ -enum GNUNET_MQ_PriorityPreferences -{ - +enum GNUNET_MQ_PriorityPreferences { /** * Lowest priority, i.e. background traffic (i.e. NSE, FS). * This is the default! @@ -297,7 +294,6 @@ enum GNUNET_MQ_PriorityPreferences * Flag to indicate that out-of-order delivery is OK. */ GNUNET_MQ_PREF_OUT_OF_ORDER = 256, - }; @@ -386,9 +382,9 @@ typedef void (*GNUNET_MQ_ErrorHandler) (void *cls, enum GNUNET_MQ_Error error); * @param[in|out] env element to insert at the tail */ void -GNUNET_MQ_dll_insert_head (struct GNUNET_MQ_Envelope **env_head, - struct GNUNET_MQ_Envelope **env_tail, - struct GNUNET_MQ_Envelope *env); +GNUNET_MQ_dll_insert_head(struct GNUNET_MQ_Envelope **env_head, + struct GNUNET_MQ_Envelope **env_tail, + struct GNUNET_MQ_Envelope *env); /** @@ -404,9 +400,9 @@ GNUNET_MQ_dll_insert_head (struct GNUNET_MQ_Envelope **env_head, * @param[in|out] env element to insert at the tail */ void -GNUNET_MQ_dll_insert_tail (struct GNUNET_MQ_Envelope **env_head, - struct GNUNET_MQ_Envelope **env_tail, - struct GNUNET_MQ_Envelope *env); +GNUNET_MQ_dll_insert_tail(struct GNUNET_MQ_Envelope **env_head, + struct GNUNET_MQ_Envelope **env_tail, + struct GNUNET_MQ_Envelope *env); /** @@ -422,9 +418,9 @@ GNUNET_MQ_dll_insert_tail (struct GNUNET_MQ_Envelope **env_head, * @param[in|out] env element to remove from the DLL */ void -GNUNET_MQ_dll_remove (struct GNUNET_MQ_Envelope **env_head, - struct GNUNET_MQ_Envelope **env_tail, - struct GNUNET_MQ_Envelope *env); +GNUNET_MQ_dll_remove(struct GNUNET_MQ_Envelope **env_head, + struct GNUNET_MQ_Envelope **env_tail, + struct GNUNET_MQ_Envelope *env); /** @@ -438,7 +434,7 @@ GNUNET_MQ_dll_remove (struct GNUNET_MQ_Envelope **env_head, * Needs to be freed with #GNUNET_free. */ struct GNUNET_MQ_MessageHandler * -GNUNET_MQ_copy_handlers (const struct GNUNET_MQ_MessageHandler *handlers); +GNUNET_MQ_copy_handlers(const struct GNUNET_MQ_MessageHandler *handlers); /** @@ -454,9 +450,9 @@ GNUNET_MQ_copy_handlers (const struct GNUNET_MQ_MessageHandler *handlers); * Needs to be freed with #GNUNET_free. */ struct GNUNET_MQ_MessageHandler * -GNUNET_MQ_copy_handlers2 (const struct GNUNET_MQ_MessageHandler *handlers, - GNUNET_MQ_MessageCallback agpl_handler, - void *agpl_cls); +GNUNET_MQ_copy_handlers2(const struct GNUNET_MQ_MessageHandler *handlers, + GNUNET_MQ_MessageCallback agpl_handler, + void *agpl_cls); /** @@ -466,14 +462,13 @@ GNUNET_MQ_copy_handlers2 (const struct GNUNET_MQ_MessageHandler *handlers, * @return The number of handlers in the array. */ unsigned int -GNUNET_MQ_count_handlers (const struct GNUNET_MQ_MessageHandler *handlers); +GNUNET_MQ_count_handlers(const struct GNUNET_MQ_MessageHandler *handlers); /** * Message handler for a specific message type. */ -struct GNUNET_MQ_MessageHandler -{ +struct GNUNET_MQ_MessageHandler { /** * Callback to validate a message of the specified @e type. * The closure given to @e mv will be this struct (not @e ctx). @@ -549,12 +544,12 @@ struct GNUNET_MQ_MessageHandler */ #define GNUNET_MQ_hd_fixed_size(name, code, str, ctx) \ ({ \ - void (*_cb) (void *cls, const str *msg) = &handle_##name; \ - ((struct GNUNET_MQ_MessageHandler){NULL, \ - (GNUNET_MQ_MessageCallback) _cb, \ - (ctx), \ - (code), \ - sizeof (str)}); \ + void (*_cb)(void *cls, const str *msg) = &handle_ ## name; \ + ((struct GNUNET_MQ_MessageHandler){ NULL, \ + (GNUNET_MQ_MessageCallback)_cb, \ + (ctx), \ + (code), \ + sizeof(str) }); \ }) @@ -600,14 +595,14 @@ struct GNUNET_MQ_MessageHandler */ #define GNUNET_MQ_hd_var_size(name, code, str, ctx) \ __extension__({ \ - int (*_mv) (void *cls, const str *msg) = &check_##name; \ - void (*_cb) (void *cls, const str *msg) = &handle_##name; \ - ((struct GNUNET_MQ_MessageHandler){(GNUNET_MQ_MessageValidationCallback) \ - _mv, \ - (GNUNET_MQ_MessageCallback) _cb, \ - (ctx), \ - (code), \ - sizeof (str)}); \ + int (*_mv)(void *cls, const str *msg) = &check_ ## name; \ + void (*_cb)(void *cls, const str *msg) = &handle_ ## name; \ + ((struct GNUNET_MQ_MessageHandler){ (GNUNET_MQ_MessageValidationCallback) \ + _mv, \ + (GNUNET_MQ_MessageCallback)_cb, \ + (ctx), \ + (code), \ + sizeof(str) }); \ }) @@ -623,15 +618,15 @@ struct GNUNET_MQ_MessageHandler */ #define GNUNET_MQ_check_zero_termination(m) \ { \ - const char *str = (const char *) &m[1]; \ + const char *str = (const char *)&m[1]; \ const struct GNUNET_MessageHeader *hdr = \ - (const struct GNUNET_MessageHeader *) m; \ - uint16_t slen = ntohs (hdr->size) - sizeof (*m); \ - if ((0 == slen) || (memchr (str, 0, slen) != &str[slen - 1])) \ - { \ - GNUNET_break (0); \ - return GNUNET_NO; \ - } \ + (const struct GNUNET_MessageHeader *)m; \ + uint16_t slen = ntohs(hdr->size) - sizeof(*m); \ + if ((0 == slen) || (memchr(str, 0, slen) != &str[slen - 1])) \ + { \ + GNUNET_break(0); \ + return GNUNET_NO; \ + } \ } @@ -650,16 +645,16 @@ struct GNUNET_MQ_MessageHandler #define GNUNET_MQ_check_boxed_message(m) \ { \ const struct GNUNET_MessageHeader *inbox = \ - (const struct GNUNET_MessageHeader *) &m[1]; \ + (const struct GNUNET_MessageHeader *)&m[1]; \ const struct GNUNET_MessageHeader *hdr = \ - (const struct GNUNET_MessageHeader *) m; \ - uint16_t slen = ntohs (hdr->size) - sizeof (*m); \ - if ((slen < sizeof (struct GNUNET_MessageHeader)) || \ - (slen != ntohs (inbox->size))) \ - { \ - GNUNET_break (0); \ - return GNUNET_NO; \ - } \ + (const struct GNUNET_MessageHeader *)m; \ + uint16_t slen = ntohs(hdr->size) - sizeof(*m); \ + if ((slen < sizeof(struct GNUNET_MessageHeader)) || \ + (slen != ntohs(inbox->size))) \ + { \ + GNUNET_break(0); \ + return GNUNET_NO; \ + } \ } @@ -676,8 +671,8 @@ struct GNUNET_MQ_MessageHandler * #GNUNET_SYSERR if message was rejected by check function */ int -GNUNET_MQ_handle_message (const struct GNUNET_MQ_MessageHandler *handlers, - const struct GNUNET_MessageHeader *mh); +GNUNET_MQ_handle_message(const struct GNUNET_MQ_MessageHandler *handlers, + const struct GNUNET_MessageHeader *mh); /** @@ -689,9 +684,9 @@ GNUNET_MQ_handle_message (const struct GNUNET_MQ_MessageHandler *handlers, * @return the allocated MQ message */ struct GNUNET_MQ_Envelope * -GNUNET_MQ_msg_ (struct GNUNET_MessageHeader **mhp, - uint16_t size, - uint16_t type); +GNUNET_MQ_msg_(struct GNUNET_MessageHeader **mhp, + uint16_t size, + uint16_t type); /** @@ -701,7 +696,7 @@ GNUNET_MQ_msg_ (struct GNUNET_MessageHeader **mhp, * @return envelope containing @a hdr */ struct GNUNET_MQ_Envelope * -GNUNET_MQ_msg_copy (const struct GNUNET_MessageHeader *hdr); +GNUNET_MQ_msg_copy(const struct GNUNET_MessageHeader *hdr); /** @@ -712,7 +707,7 @@ GNUNET_MQ_msg_copy (const struct GNUNET_MessageHeader *hdr); * @param mqm the message to discard */ void -GNUNET_MQ_discard (struct GNUNET_MQ_Envelope *mqm); +GNUNET_MQ_discard(struct GNUNET_MQ_Envelope *mqm); /** @@ -723,7 +718,7 @@ GNUNET_MQ_discard (struct GNUNET_MQ_Envelope *mqm); * @return the current envelope */ struct GNUNET_MQ_Envelope * -GNUNET_MQ_get_current_envelope (struct GNUNET_MQ_Handle *mq); +GNUNET_MQ_get_current_envelope(struct GNUNET_MQ_Handle *mq); /** @@ -734,7 +729,7 @@ GNUNET_MQ_get_current_envelope (struct GNUNET_MQ_Handle *mq); * @return copy of @a env */ struct GNUNET_MQ_Envelope * -GNUNET_MQ_env_copy (struct GNUNET_MQ_Envelope *env); +GNUNET_MQ_env_copy(struct GNUNET_MQ_Envelope *env); /** @@ -744,7 +739,7 @@ GNUNET_MQ_env_copy (struct GNUNET_MQ_Envelope *env); * @return the last envelope in the queue */ struct GNUNET_MQ_Envelope * -GNUNET_MQ_get_last_envelope (struct GNUNET_MQ_Handle *mq); +GNUNET_MQ_get_last_envelope(struct GNUNET_MQ_Handle *mq); /** @@ -756,8 +751,8 @@ GNUNET_MQ_get_last_envelope (struct GNUNET_MQ_Handle *mq); * @param pp priority and preferences to set for @a env */ void -GNUNET_MQ_env_set_options (struct GNUNET_MQ_Envelope *env, - enum GNUNET_MQ_PriorityPreferences pp); +GNUNET_MQ_env_set_options(struct GNUNET_MQ_Envelope *env, + enum GNUNET_MQ_PriorityPreferences pp); /** @@ -767,7 +762,7 @@ GNUNET_MQ_env_set_options (struct GNUNET_MQ_Envelope *env, * @return priority and preferences to use */ enum GNUNET_MQ_PriorityPreferences -GNUNET_MQ_env_get_options (struct GNUNET_MQ_Envelope *env); +GNUNET_MQ_env_get_options(struct GNUNET_MQ_Envelope *env); /** @@ -779,8 +774,8 @@ GNUNET_MQ_env_get_options (struct GNUNET_MQ_Envelope *env); * @return combined priority and preferences to use */ enum GNUNET_MQ_PriorityPreferences -GNUNET_MQ_env_combine_options (enum GNUNET_MQ_PriorityPreferences p1, - enum GNUNET_MQ_PriorityPreferences p2); +GNUNET_MQ_env_combine_options(enum GNUNET_MQ_PriorityPreferences p1, + enum GNUNET_MQ_PriorityPreferences p2); /** @@ -791,7 +786,7 @@ GNUNET_MQ_env_combine_options (enum GNUNET_MQ_PriorityPreferences p1, * @return NULL if queue is empty (or has no envelope that is not under transmission) */ struct GNUNET_MQ_Envelope * -GNUNET_MQ_unsent_head (struct GNUNET_MQ_Handle *mq); +GNUNET_MQ_unsent_head(struct GNUNET_MQ_Handle *mq); /** @@ -801,8 +796,8 @@ GNUNET_MQ_unsent_head (struct GNUNET_MQ_Handle *mq); * @param pp priority and preferences to use by default */ void -GNUNET_MQ_set_options (struct GNUNET_MQ_Handle *mq, - enum GNUNET_MQ_PriorityPreferences pp); +GNUNET_MQ_set_options(struct GNUNET_MQ_Handle *mq, + enum GNUNET_MQ_PriorityPreferences pp); /** @@ -812,7 +807,7 @@ GNUNET_MQ_set_options (struct GNUNET_MQ_Handle *mq, * @return number of queued, non-transmitted messages */ unsigned int -GNUNET_MQ_get_length (struct GNUNET_MQ_Handle *mq); +GNUNET_MQ_get_length(struct GNUNET_MQ_Handle *mq); /** @@ -823,7 +818,7 @@ GNUNET_MQ_get_length (struct GNUNET_MQ_Handle *mq); * @param ev the envelope with the message to send. */ void -GNUNET_MQ_send (struct GNUNET_MQ_Handle *mq, struct GNUNET_MQ_Envelope *ev); +GNUNET_MQ_send(struct GNUNET_MQ_Handle *mq, struct GNUNET_MQ_Envelope *ev); /** @@ -834,8 +829,8 @@ GNUNET_MQ_send (struct GNUNET_MQ_Handle *mq, struct GNUNET_MQ_Envelope *ev); * @param ev the envelope with the message to send. */ void -GNUNET_MQ_send_copy (struct GNUNET_MQ_Handle *mq, - const struct GNUNET_MQ_Envelope *ev); +GNUNET_MQ_send_copy(struct GNUNET_MQ_Handle *mq, + const struct GNUNET_MQ_Envelope *ev); /** @@ -846,7 +841,7 @@ GNUNET_MQ_send_copy (struct GNUNET_MQ_Handle *mq, * @param ev queued envelope to cancel */ void -GNUNET_MQ_send_cancel (struct GNUNET_MQ_Envelope *ev); +GNUNET_MQ_send_cancel(struct GNUNET_MQ_Envelope *ev); /** @@ -856,7 +851,7 @@ GNUNET_MQ_send_cancel (struct GNUNET_MQ_Envelope *ev); * @param assoc_data to associate */ uint32_t -GNUNET_MQ_assoc_add (struct GNUNET_MQ_Handle *mq, void *assoc_data); +GNUNET_MQ_assoc_add(struct GNUNET_MQ_Handle *mq, void *assoc_data); /** @@ -867,7 +862,7 @@ GNUNET_MQ_assoc_add (struct GNUNET_MQ_Handle *mq, void *assoc_data); * @return the associated data */ void * -GNUNET_MQ_assoc_get (struct GNUNET_MQ_Handle *mq, uint32_t request_id); +GNUNET_MQ_assoc_get(struct GNUNET_MQ_Handle *mq, uint32_t request_id); /** @@ -878,7 +873,7 @@ GNUNET_MQ_assoc_get (struct GNUNET_MQ_Handle *mq, uint32_t request_id); * @return the associated data */ void * -GNUNET_MQ_assoc_remove (struct GNUNET_MQ_Handle *mq, uint32_t request_id); +GNUNET_MQ_assoc_remove(struct GNUNET_MQ_Handle *mq, uint32_t request_id); /** @@ -894,13 +889,13 @@ GNUNET_MQ_assoc_remove (struct GNUNET_MQ_Handle *mq, uint32_t request_id); * @return a new message queue */ struct GNUNET_MQ_Handle * -GNUNET_MQ_queue_for_callbacks (GNUNET_MQ_SendImpl send, - GNUNET_MQ_DestroyImpl destroy, - GNUNET_MQ_CancelImpl cancel, - void *impl_state, - const struct GNUNET_MQ_MessageHandler *handlers, - GNUNET_MQ_ErrorHandler error_handler, - void *cls); +GNUNET_MQ_queue_for_callbacks(GNUNET_MQ_SendImpl send, + GNUNET_MQ_DestroyImpl destroy, + GNUNET_MQ_CancelImpl cancel, + void *impl_state, + const struct GNUNET_MQ_MessageHandler *handlers, + GNUNET_MQ_ErrorHandler error_handler, + void *cls); /** @@ -911,8 +906,8 @@ GNUNET_MQ_queue_for_callbacks (GNUNET_MQ_SendImpl send, * @param handlers_cls new closure to use */ void -GNUNET_MQ_set_handlers_closure (struct GNUNET_MQ_Handle *mq, - void *handlers_cls); +GNUNET_MQ_set_handlers_closure(struct GNUNET_MQ_Handle *mq, + void *handlers_cls); /** @@ -925,9 +920,9 @@ GNUNET_MQ_set_handlers_closure (struct GNUNET_MQ_Handle *mq, * @param cb_cls closure for the callback */ void -GNUNET_MQ_notify_sent (struct GNUNET_MQ_Envelope *ev, - GNUNET_SCHEDULER_TaskCallback cb, - void *cb_cls); +GNUNET_MQ_notify_sent(struct GNUNET_MQ_Envelope *ev, + GNUNET_SCHEDULER_TaskCallback cb, + void *cb_cls); /** @@ -936,7 +931,7 @@ GNUNET_MQ_notify_sent (struct GNUNET_MQ_Envelope *ev, * @param mq message queue to destroy */ void -GNUNET_MQ_destroy (struct GNUNET_MQ_Handle *mq); +GNUNET_MQ_destroy(struct GNUNET_MQ_Handle *mq); /** @@ -956,9 +951,9 @@ struct GNUNET_MQ_DestroyNotificationHandle; * @return handle for #GNUNET_MQ_destroy_notify_cancel(). */ struct GNUNET_MQ_DestroyNotificationHandle * -GNUNET_MQ_destroy_notify (struct GNUNET_MQ_Handle *mq, - GNUNET_SCHEDULER_TaskCallback cb, - void *cb_cls); +GNUNET_MQ_destroy_notify(struct GNUNET_MQ_Handle *mq, + GNUNET_SCHEDULER_TaskCallback cb, + void *cb_cls); /** * Cancel registration from #GNUNET_MQ_destroy_notify(). @@ -966,7 +961,7 @@ GNUNET_MQ_destroy_notify (struct GNUNET_MQ_Handle *mq, * @param dnh handle for registration to cancel */ void -GNUNET_MQ_destroy_notify_cancel ( +GNUNET_MQ_destroy_notify_cancel( struct GNUNET_MQ_DestroyNotificationHandle *dnh); @@ -981,8 +976,8 @@ GNUNET_MQ_destroy_notify_cancel ( * @param mh message to dispatch */ void -GNUNET_MQ_inject_message (struct GNUNET_MQ_Handle *mq, - const struct GNUNET_MessageHeader *mh); +GNUNET_MQ_inject_message(struct GNUNET_MQ_Handle *mq, + const struct GNUNET_MessageHeader *mh); /** @@ -996,8 +991,8 @@ GNUNET_MQ_inject_message (struct GNUNET_MQ_Handle *mq, * @param error the error type */ void -GNUNET_MQ_inject_error (struct GNUNET_MQ_Handle *mq, - enum GNUNET_MQ_Error error); +GNUNET_MQ_inject_error(struct GNUNET_MQ_Handle *mq, + enum GNUNET_MQ_Error error); /** @@ -1011,7 +1006,7 @@ GNUNET_MQ_inject_error (struct GNUNET_MQ_Handle *mq, * @param mq message queue to send the next message with */ void -GNUNET_MQ_impl_send_continue (struct GNUNET_MQ_Handle *mq); +GNUNET_MQ_impl_send_continue(struct GNUNET_MQ_Handle *mq); /** @@ -1025,7 +1020,7 @@ GNUNET_MQ_impl_send_continue (struct GNUNET_MQ_Handle *mq); * @param mq message queue to send the next message with */ void -GNUNET_MQ_impl_send_in_flight (struct GNUNET_MQ_Handle *mq); +GNUNET_MQ_impl_send_in_flight(struct GNUNET_MQ_Handle *mq); /** @@ -1043,7 +1038,7 @@ GNUNET_MQ_impl_send_in_flight (struct GNUNET_MQ_Handle *mq); * @return message to send, never NULL */ void * -GNUNET_MQ_impl_state (struct GNUNET_MQ_Handle *mq); +GNUNET_MQ_impl_state(struct GNUNET_MQ_Handle *mq); /** @@ -1056,7 +1051,7 @@ GNUNET_MQ_impl_state (struct GNUNET_MQ_Handle *mq); * @return message to send, never NULL */ const struct GNUNET_MessageHeader * -GNUNET_MQ_impl_current (struct GNUNET_MQ_Handle *mq); +GNUNET_MQ_impl_current(struct GNUNET_MQ_Handle *mq); /** @@ -1064,9 +1059,7 @@ GNUNET_MQ_impl_current (struct GNUNET_MQ_Handle *mq); * * @deprecated will be replaced by `enum GNUNET_MQ_PriorityPreference` */ -enum GNUNET_MQ_PreferenceKind -{ - +enum GNUNET_MQ_PreferenceKind { /** * No preference was expressed. */ @@ -1091,10 +1084,9 @@ enum GNUNET_MQ_PreferenceKind GNUNET_MQ_PREFERENCE_RELIABILITY = 3 /** - * Number of preference values allowed. - */ + * Number of preference values allowed. + */ #define GNUNET_MQ_PREFERENCE_COUNT 4 - }; @@ -1107,7 +1099,7 @@ enum GNUNET_MQ_PreferenceKind * @deprecated will be replaced by `enum GNUNET_MQ_PriorityPreference` */ const char * -GNUNET_MQ_preference_to_string (enum GNUNET_MQ_PreferenceKind type); +GNUNET_MQ_preference_to_string(enum GNUNET_MQ_PreferenceKind type); #endif diff --git a/src/include/gnunet_mst_lib.h b/src/include/gnunet_mst_lib.h index b048f94bc..2956ac24f 100644 --- a/src/include/gnunet_mst_lib.h +++ b/src/include/gnunet_mst_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -78,8 +78,8 @@ typedef int * @return handle to tokenizer */ struct GNUNET_MessageStreamTokenizer * -GNUNET_MST_create (GNUNET_MessageTokenizerCallback cb, - void *cb_cls); +GNUNET_MST_create(GNUNET_MessageTokenizerCallback cb, + void *cb_cls); /** @@ -97,11 +97,11 @@ GNUNET_MST_create (GNUNET_MessageTokenizerCallback cb, * #GNUNET_SYSERR if the data stream is corrupt */ int -GNUNET_MST_from_buffer (struct GNUNET_MessageStreamTokenizer *mst, - const char *buf, - size_t size, - int purge, - int one_shot); +GNUNET_MST_from_buffer(struct GNUNET_MessageStreamTokenizer *mst, + const char *buf, + size_t size, + int purge, + int one_shot); /** @@ -119,10 +119,10 @@ GNUNET_MST_from_buffer (struct GNUNET_MessageStreamTokenizer *mst, * #GNUNET_SYSERR if the data stream is corrupt */ int -GNUNET_MST_read (struct GNUNET_MessageStreamTokenizer *mst, - struct GNUNET_NETWORK_Handle *sock, - int purge, - int one_shot); +GNUNET_MST_read(struct GNUNET_MessageStreamTokenizer *mst, + struct GNUNET_NETWORK_Handle *sock, + int purge, + int one_shot); /** @@ -137,8 +137,8 @@ GNUNET_MST_read (struct GNUNET_MessageStreamTokenizer *mst, * #GNUNET_SYSERR if the data stream is corrupt */ int -GNUNET_MST_next (struct GNUNET_MessageStreamTokenizer *mst, - int one_shot); +GNUNET_MST_next(struct GNUNET_MessageStreamTokenizer *mst, + int one_shot); /** @@ -147,7 +147,7 @@ GNUNET_MST_next (struct GNUNET_MessageStreamTokenizer *mst, * @param mst tokenizer to destroy */ void -GNUNET_MST_destroy (struct GNUNET_MessageStreamTokenizer *mst); +GNUNET_MST_destroy(struct GNUNET_MessageStreamTokenizer *mst); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_my_lib.h b/src/include/gnunet_my_lib.h index 744a646f0..1805c2795 100644 --- a/src/include/gnunet_my_lib.h +++ b/src/include/gnunet_my_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff * @author Christophe Genevey @@ -62,7 +62,7 @@ struct GNUNET_MY_QueryParam; */ typedef int (*GNUNET_MY_QueryConverter)(void *cls, - const struct GNUNET_MY_QueryParam *qp, + const struct GNUNET_MY_QueryParam *qp, MYSQL_BIND *qbind); @@ -74,22 +74,20 @@ typedef int */ typedef void (*GNUNET_MY_QueryCleanup)(void *cls, - MYSQL_BIND *qbind); + MYSQL_BIND *qbind); /** * Information we pass to #GNUNET_MY_exec_prepared() to * initialize the arguments of the prepared statement. */ -struct GNUNET_MY_QueryParam -{ - +struct GNUNET_MY_QueryParam { /** * Function to call for the type conversion. */ GNUNET_MY_QueryConverter conv; - /** + /** * Function to call for cleaning up the query. Can be NULL. */ GNUNET_MY_QueryCleanup cleaner; @@ -113,7 +111,6 @@ struct GNUNET_MY_QueryParam * Information to pass to @e conv. Size of @a data. */ unsigned long data_len; - }; /** @@ -132,8 +129,8 @@ struct GNUNET_MY_QueryParam * @oaran ptr_size number of bytes in @a ptr */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_fixed_size (const void *ptr, - size_t ptr_size); +GNUNET_MY_query_param_fixed_size(const void *ptr, + size_t ptr_size); /** @@ -145,9 +142,9 @@ GNUNET_MY_query_param_fixed_size (const void *ptr, * @return TBD */ int -GNUNET_MY_exec_prepared (struct GNUNET_MYSQL_Context *mc, - struct GNUNET_MYSQL_StatementHandle *sh, - struct GNUNET_MY_QueryParam *params); +GNUNET_MY_exec_prepared(struct GNUNET_MYSQL_Context *mc, + struct GNUNET_MYSQL_StatementHandle *sh, + struct GNUNET_MY_QueryParam *params); /** @@ -194,9 +191,7 @@ typedef void * Information we pass to #GNUNET_MY_extract_result() to * initialize the arguments of the prepared statement. */ -struct GNUNET_MY_ResultSpec -{ - +struct GNUNET_MY_ResultSpec { /** * Function to call to initialize the MYSQL_BIND array. */ @@ -207,7 +202,7 @@ struct GNUNET_MY_ResultSpec */ GNUNET_MY_ResultConverter post_conv; - /** + /** * Function to call for cleaning up the result. Can be NULL. */ GNUNET_MY_ResultCleanup cleaner; @@ -250,7 +245,6 @@ struct GNUNET_MY_ResultSpec * Memory for MySQL to notify us about NULL values. */ my_bool is_null; - }; @@ -271,88 +265,88 @@ struct GNUNET_MY_ResultSpec * @oaran ptr_size number of bytes available at @a ptr */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_fixed_size (void *ptr, - size_t ptr_size); +GNUNET_MY_result_spec_fixed_size(void *ptr, + size_t ptr_size); /** - * Generate query parameter for a string - * - *@param ptr pointer to the string query parameter to pass - */ + * Generate query parameter for a string + * + *@param ptr pointer to the string query parameter to pass + */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_string (const char *ptr); +GNUNET_MY_query_param_string(const char *ptr); /** - * Generate fixed-size query parameter with size determined - * by variable type. - * - * @param x pointer to the query parameter to pass - */ -#define GNUNET_MY_query_param_auto_from_type(x) GNUNET_MY_query_param_fixed_size ((x), sizeof (*(x))) + * Generate fixed-size query parameter with size determined + * by variable type. + * + * @param x pointer to the query parameter to pass + */ +#define GNUNET_MY_query_param_auto_from_type(x) GNUNET_MY_query_param_fixed_size((x), sizeof(*(x))) /** - * Generate query parameter for an RSA public key. The - * database must contain a BLOB type in the respective position. - * - * @param x the query parameter to pass - * @return array entry for the query parameters to use - */ + * Generate query parameter for an RSA public key. The + * database must contain a BLOB type in the respective position. + * + * @param x the query parameter to pass + * @return array entry for the query parameters to use + */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_rsa_public_key (const struct GNUNET_CRYPTO_RsaPublicKey *x); +GNUNET_MY_query_param_rsa_public_key(const struct GNUNET_CRYPTO_RsaPublicKey *x); /** - * Generate query parameter for an RSA signature. The - * database must contain a BLOB type in the respective position - * - *@param x the query parameter to pass - *@return array entry for the query parameters to use - */ + * Generate query parameter for an RSA signature. The + * database must contain a BLOB type in the respective position + * + *@param x the query parameter to pass + *@return array entry for the query parameters to use + */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *x); +GNUNET_MY_query_param_rsa_signature(const struct GNUNET_CRYPTO_RsaSignature *x); /** - * Generate query parameter for an absolute time value. - * The database must store a 64-bit integer. - * - *@param x pointer to the query parameter to pass - *@return array entry for the query parameters to use - */ + * Generate query parameter for an absolute time value. + * The database must store a 64-bit integer. + * + *@param x pointer to the query parameter to pass + *@return array entry for the query parameters to use + */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_absolute_time (const struct GNUNET_TIME_Absolute *x); +GNUNET_MY_query_param_absolute_time(const struct GNUNET_TIME_Absolute *x); /** - * Generate query parameter for an absolute time value. - * The database must store a 64-bit integer. - * - *@param x pointer to the query parameter to pass - */ + * Generate query parameter for an absolute time value. + * The database must store a 64-bit integer. + * + *@param x pointer to the query parameter to pass + */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_absolute_time_nbo (const struct GNUNET_TIME_AbsoluteNBO *x); +GNUNET_MY_query_param_absolute_time_nbo(const struct GNUNET_TIME_AbsoluteNBO *x); /** - * Generate query parameter for an uint16_t in host byte order. - * - * @param x pointer to the query parameter to pass - */ + * Generate query parameter for an uint16_t in host byte order. + * + * @param x pointer to the query parameter to pass + */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_uint16 (const uint16_t *x); +GNUNET_MY_query_param_uint16(const uint16_t *x); /** - * Generate query parameter for an uint32_t in host byte order - * - *@param x pointer to the query parameter to pass - */ + * Generate query parameter for an uint32_t in host byte order + * + *@param x pointer to the query parameter to pass + */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_uint32 (const uint32_t *x); +GNUNET_MY_query_param_uint32(const uint32_t *x); /** - * Generate query parameter for an uint64_t in host byte order - * - *@param x pointer to the query parameter to pass - */ + * Generate query parameter for an uint64_t in host byte order + * + *@param x pointer to the query parameter to pass + */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_uint64 (const uint64_t *x); +GNUNET_MY_query_param_uint64(const uint64_t *x); /** * We expect a fixed-size result, with size determined by the type of `* dst` @@ -361,7 +355,7 @@ GNUNET_MY_query_param_uint64 (const uint64_t *x); * @spec dst point to where to store the result, type fits expected result size * @return array entry for the result specification to use */ -#define GNUNET_MY_result_spec_auto_from_type(dst) GNUNET_MY_result_spec_fixed_size ((dst), sizeof (*(dst))) +#define GNUNET_MY_result_spec_auto_from_type(dst) GNUNET_MY_result_spec_fixed_size((dst), sizeof(*(dst))) /** @@ -372,8 +366,8 @@ GNUNET_MY_query_param_uint64 (const uint64_t *x); * @return array entru for the result specification to use */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_variable_size (void **dst, - size_t *ptr_size); +GNUNET_MY_result_spec_variable_size(void **dst, + size_t *ptr_size); /** * RSA public key expected @@ -383,7 +377,7 @@ GNUNET_MY_result_spec_variable_size (void **dst, * @return array entry for the result specification to use */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_rsa_public_key (struct GNUNET_CRYPTO_RsaPublicKey **rsa); +GNUNET_MY_result_spec_rsa_public_key(struct GNUNET_CRYPTO_RsaPublicKey **rsa); /** @@ -393,62 +387,62 @@ GNUNET_MY_result_spec_rsa_public_key (struct GNUNET_CRYPTO_RsaPublicKey **rsa); * @return array entry for the result specification to use */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_rsa_signature (struct GNUNET_CRYPTO_RsaSignature **sig); +GNUNET_MY_result_spec_rsa_signature(struct GNUNET_CRYPTO_RsaSignature **sig); /** - * 0- terminated string exprected. - * - * @param[out] dst where to store the result, allocated - * @return array entry for the result specification to use - */ + * 0- terminated string exprected. + * + * @param[out] dst where to store the result, allocated + * @return array entry for the result specification to use + */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_string (char **dst); +GNUNET_MY_result_spec_string(char **dst); /** - * Absolute time expected - * - * @param name name of the field in the table - * @param[out] at where to store the result - * @return array entry for the result specification to use - */ + * Absolute time expected + * + * @param name name of the field in the table + * @param[out] at where to store the result + * @return array entry for the result specification to use + */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_absolute_time (struct GNUNET_TIME_Absolute *at); +GNUNET_MY_result_spec_absolute_time(struct GNUNET_TIME_Absolute *at); /** - * Absolute time in network byte order expected - * - * @param[out] at where to store the result - * @return array entry for the result specification to use - */ + * Absolute time in network byte order expected + * + * @param[out] at where to store the result + * @return array entry for the result specification to use + */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_absolute_time_nbo (struct GNUNET_TIME_AbsoluteNBO *at); +GNUNET_MY_result_spec_absolute_time_nbo(struct GNUNET_TIME_AbsoluteNBO *at); /** - * uint16_t expected - * - * @param[out] u16 where to store the result - * @return array entry for the result specification to use - */ + * uint16_t expected + * + * @param[out] u16 where to store the result + * @return array entry for the result specification to use + */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_uint16 (uint16_t *u16); +GNUNET_MY_result_spec_uint16(uint16_t *u16); /** - * uint32_t expected - * - * @param[out] u32 where to store the result - * @return array entry for the result specification to use - */ + * uint32_t expected + * + * @param[out] u32 where to store the result + * @return array entry for the result specification to use + */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_uint32 (uint32_t *u32); +GNUNET_MY_result_spec_uint32(uint32_t *u32); /** - * uint64_t expected. - * - * @param[out] u64 where to store the result - * @return array entry for the result specification to use - */ + * uint64_t expected. + * + * @param[out] u64 where to store the result + * @return array entry for the result specification to use + */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_uint64 (uint64_t *u64); +GNUNET_MY_result_spec_uint64(uint64_t *u64); /** @@ -463,8 +457,8 @@ GNUNET_MY_result_spec_uint64 (uint64_t *u64); * #GNUNET_SYSERR if a result was invalid */ int -GNUNET_MY_extract_result (struct GNUNET_MYSQL_StatementHandle *sh, - struct GNUNET_MY_ResultSpec *specs); +GNUNET_MY_extract_result(struct GNUNET_MYSQL_StatementHandle *sh, + struct GNUNET_MY_ResultSpec *specs); /** @@ -475,8 +469,8 @@ GNUNET_MY_extract_result (struct GNUNET_MYSQL_StatementHandle *sh, * @param qbind mysql query */ void -GNUNET_MY_cleanup_query (struct GNUNET_MY_QueryParam *qp, - MYSQL_BIND *qbind); +GNUNET_MY_cleanup_query(struct GNUNET_MY_QueryParam *qp, + MYSQL_BIND *qbind); /** @@ -486,7 +480,7 @@ GNUNET_MY_cleanup_query (struct GNUNET_MY_QueryParam *qp, * @param rs reult specification to clean up */ void -GNUNET_MY_cleanup_result (struct GNUNET_MY_ResultSpec *rs); +GNUNET_MY_cleanup_result(struct GNUNET_MY_ResultSpec *rs); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_mysql_lib.h b/src/include/gnunet_mysql_lib.h index dbbcd2b19..0fef43a5a 100644 --- a/src/include/gnunet_mysql_lib.h +++ b/src/include/gnunet_mysql_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff * @@ -77,8 +77,8 @@ typedef int * @return the mysql context */ struct GNUNET_MYSQL_Context * -GNUNET_MYSQL_context_create (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section); +GNUNET_MYSQL_context_create(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section); /** @@ -87,7 +87,7 @@ GNUNET_MYSQL_context_create (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param mc context to destroy */ void -GNUNET_MYSQL_context_destroy (struct GNUNET_MYSQL_Context *mc); +GNUNET_MYSQL_context_destroy(struct GNUNET_MYSQL_Context *mc); /** @@ -98,7 +98,7 @@ GNUNET_MYSQL_context_destroy (struct GNUNET_MYSQL_Context *mc); * @param mc mysql context */ void -GNUNET_MYSQL_statements_invalidate (struct GNUNET_MYSQL_Context *mc); +GNUNET_MYSQL_statements_invalidate(struct GNUNET_MYSQL_Context *mc); /** @@ -110,7 +110,7 @@ GNUNET_MYSQL_statements_invalidate (struct GNUNET_MYSQL_Context *mc); * @return MySQL statement handle, NULL on error */ MYSQL_STMT * -GNUNET_MYSQL_statement_get_stmt (struct GNUNET_MYSQL_StatementHandle *sh); +GNUNET_MYSQL_statement_get_stmt(struct GNUNET_MYSQL_StatementHandle *sh); /** @@ -122,8 +122,8 @@ GNUNET_MYSQL_statement_get_stmt (struct GNUNET_MYSQL_StatementHandle *sh); * @return prepared statement, NULL on error */ struct GNUNET_MYSQL_StatementHandle * -GNUNET_MYSQL_statement_prepare (struct GNUNET_MYSQL_Context *mc, - const char *query); +GNUNET_MYSQL_statement_prepare(struct GNUNET_MYSQL_Context *mc, + const char *query); /** @@ -135,8 +135,8 @@ GNUNET_MYSQL_statement_prepare (struct GNUNET_MYSQL_Context *mc, * #GNUNET_SYSERR if there was a problem */ int -GNUNET_MYSQL_statement_run (struct GNUNET_MYSQL_Context *mc, - const char *sql); +GNUNET_MYSQL_statement_run(struct GNUNET_MYSQL_Context *mc, + const char *sql); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_namecache_plugin.h b/src/include/gnunet_namecache_plugin.h index 5281fd3dc..8d3c4fb61 100644 --- a/src/include/gnunet_namecache_plugin.h +++ b/src/include/gnunet_namecache_plugin.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -54,15 +54,13 @@ extern "C" * @param block lookup result */ typedef void (*GNUNET_NAMECACHE_BlockCallback) (void *cls, - const struct GNUNET_GNSRECORD_Block *block); + const struct GNUNET_GNSRECORD_Block *block); /** * @brief struct returned by the initialization function of the plugin */ -struct GNUNET_NAMECACHE_PluginFunctions -{ - +struct GNUNET_NAMECACHE_PluginFunctions { /** * Closure to pass to all plugin functions. */ @@ -77,7 +75,7 @@ struct GNUNET_NAMECACHE_PluginFunctions * @return #GNUNET_OK on success, else #GNUNET_SYSERR */ int (*cache_block) (void *cls, - const struct GNUNET_GNSRECORD_Block *block); + const struct GNUNET_GNSRECORD_Block *block); /** @@ -91,10 +89,8 @@ struct GNUNET_NAMECACHE_PluginFunctions * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error */ int (*lookup_block) (void *cls, - const struct GNUNET_HashCode *query, - GNUNET_NAMECACHE_BlockCallback iter, void *iter_cls); - - + const struct GNUNET_HashCode *query, + GNUNET_NAMECACHE_BlockCallback iter, void *iter_cls); }; diff --git a/src/include/gnunet_namecache_service.h b/src/include/gnunet_namecache_service.h index da0235fc1..271d16d19 100644 --- a/src/include/gnunet_namecache_service.h +++ b/src/include/gnunet_namecache_service.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -74,7 +74,7 @@ struct GNUNET_NAMECACHE_Handle; * @return handle to use to access the service */ struct GNUNET_NAMECACHE_Handle * -GNUNET_NAMECACHE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_NAMECACHE_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -85,7 +85,7 @@ GNUNET_NAMECACHE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param h handle to the namecache */ void -GNUNET_NAMECACHE_disconnect (struct GNUNET_NAMECACHE_Handle *h); +GNUNET_NAMECACHE_disconnect(struct GNUNET_NAMECACHE_Handle *h); /** @@ -116,10 +116,10 @@ typedef void * @return handle to abort the request, NULL on error */ struct GNUNET_NAMECACHE_QueueEntry * -GNUNET_NAMECACHE_block_cache (struct GNUNET_NAMECACHE_Handle *h, - const struct GNUNET_GNSRECORD_Block *block, - GNUNET_NAMECACHE_ContinuationWithStatus cont, - void *cont_cls); +GNUNET_NAMECACHE_block_cache(struct GNUNET_NAMECACHE_Handle *h, + const struct GNUNET_GNSRECORD_Block *block, + GNUNET_NAMECACHE_ContinuationWithStatus cont, + void *cont_cls); /** @@ -146,10 +146,10 @@ typedef void * @return a handle that can be used to cancel, NULL on error */ struct GNUNET_NAMECACHE_QueueEntry * -GNUNET_NAMECACHE_lookup_block (struct GNUNET_NAMECACHE_Handle *h, - const struct GNUNET_HashCode *derived_hash, - GNUNET_NAMECACHE_BlockProcessor proc, - void *proc_cls); +GNUNET_NAMECACHE_lookup_block(struct GNUNET_NAMECACHE_Handle *h, + const struct GNUNET_HashCode *derived_hash, + GNUNET_NAMECACHE_BlockProcessor proc, + void *proc_cls); /** @@ -161,7 +161,7 @@ GNUNET_NAMECACHE_lookup_block (struct GNUNET_NAMECACHE_Handle *h, * @param qe operation to cancel */ void -GNUNET_NAMECACHE_cancel (struct GNUNET_NAMECACHE_QueueEntry *qe); +GNUNET_NAMECACHE_cancel(struct GNUNET_NAMECACHE_QueueEntry *qe); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_namestore_plugin.h b/src/include/gnunet_namestore_plugin.h index 3b603b4c0..b942bb592 100644 --- a/src/include/gnunet_namestore_plugin.h +++ b/src/include/gnunet_namestore_plugin.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -56,19 +56,17 @@ extern "C" */ typedef void (*GNUNET_NAMESTORE_RecordIterator) (void *cls, - uint64_t serial, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd); + uint64_t serial, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd); /** * @brief struct returned by the initialization function of the plugin */ -struct GNUNET_NAMESTORE_PluginFunctions -{ - +struct GNUNET_NAMESTORE_PluginFunctions { /** * Closure to pass to all plugin functions. */ @@ -87,10 +85,10 @@ struct GNUNET_NAMESTORE_PluginFunctions */ int (*store_records) (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd); + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd); /** * Lookup records in the datastore for which we are the authority. @@ -104,10 +102,10 @@ struct GNUNET_NAMESTORE_PluginFunctions */ int (*lookup_records) (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - GNUNET_NAMESTORE_RecordIterator iter, - void *iter_cls); + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + GNUNET_NAMESTORE_RecordIterator iter, + void *iter_cls); /** @@ -126,11 +124,11 @@ struct GNUNET_NAMESTORE_PluginFunctions */ int (*iterate_records) (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - uint64_t serial, - uint64_t limit, - GNUNET_NAMESTORE_RecordIterator iter, - void *iter_cls); + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + uint64_t serial, + uint64_t limit, + GNUNET_NAMESTORE_RecordIterator iter, + void *iter_cls); /** @@ -146,12 +144,10 @@ struct GNUNET_NAMESTORE_PluginFunctions */ int (*zone_to_name) (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone, - GNUNET_NAMESTORE_RecordIterator iter, - void *iter_cls); - - + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone, + GNUNET_NAMESTORE_RecordIterator iter, + void *iter_cls); }; diff --git a/src/include/gnunet_namestore_service.h b/src/include/gnunet_namestore_service.h index 9b6beef28..36221f195 100644 --- a/src/include/gnunet_namestore_service.h +++ b/src/include/gnunet_namestore_service.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -74,7 +74,7 @@ struct GNUNET_NAMESTORE_ZoneIterator; * @return handle to use to access the service */ struct GNUNET_NAMESTORE_Handle * -GNUNET_NAMESTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_NAMESTORE_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -85,7 +85,7 @@ GNUNET_NAMESTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param h handle to the namestore */ void -GNUNET_NAMESTORE_disconnect (struct GNUNET_NAMESTORE_Handle *h); +GNUNET_NAMESTORE_disconnect(struct GNUNET_NAMESTORE_Handle *h); /** @@ -125,13 +125,13 @@ typedef void * @return handle to abort the request */ struct GNUNET_NAMESTORE_QueueEntry * -GNUNET_NAMESTORE_records_store (struct GNUNET_NAMESTORE_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd, - GNUNET_NAMESTORE_ContinuationWithStatus cont, - void *cont_cls); +GNUNET_NAMESTORE_records_store(struct GNUNET_NAMESTORE_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd, + GNUNET_NAMESTORE_ContinuationWithStatus cont, + void *cont_cls); /** @@ -162,11 +162,11 @@ typedef void * @return handle to abort the request */ struct GNUNET_NAMESTORE_QueueEntry * -GNUNET_NAMESTORE_set_nick (struct GNUNET_NAMESTORE_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, - const char *nick, - GNUNET_NAMESTORE_ContinuationWithStatus cont, - void *cont_cls); +GNUNET_NAMESTORE_set_nick(struct GNUNET_NAMESTORE_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, + const char *nick, + GNUNET_NAMESTORE_ContinuationWithStatus cont, + void *cont_cls); /** @@ -184,13 +184,13 @@ GNUNET_NAMESTORE_set_nick (struct GNUNET_NAMESTORE_Handle *h, * @return handle to abort the request */ struct GNUNET_NAMESTORE_QueueEntry * -GNUNET_NAMESTORE_records_lookup (struct GNUNET_NAMESTORE_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, - const char *label, - GNUNET_SCHEDULER_TaskCallback error_cb, - void *error_cb_cls, - GNUNET_NAMESTORE_RecordMonitor rm, - void *rm_cls); +GNUNET_NAMESTORE_records_lookup(struct GNUNET_NAMESTORE_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, + const char *label, + GNUNET_SCHEDULER_TaskCallback error_cb, + void *error_cb_cls, + GNUNET_NAMESTORE_RecordMonitor rm, + void *rm_cls); /** @@ -211,13 +211,13 @@ GNUNET_NAMESTORE_records_lookup (struct GNUNET_NAMESTORE_Handle *h, * cancel */ struct GNUNET_NAMESTORE_QueueEntry * -GNUNET_NAMESTORE_zone_to_name (struct GNUNET_NAMESTORE_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone, - GNUNET_SCHEDULER_TaskCallback error_cb, - void *error_cb_cls, - GNUNET_NAMESTORE_RecordMonitor proc, - void *proc_cls); +GNUNET_NAMESTORE_zone_to_name(struct GNUNET_NAMESTORE_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone, + GNUNET_SCHEDULER_TaskCallback error_cb, + void *error_cb_cls, + GNUNET_NAMESTORE_RecordMonitor proc, + void *proc_cls); /** @@ -229,7 +229,7 @@ GNUNET_NAMESTORE_zone_to_name (struct GNUNET_NAMESTORE_Handle *h, * @param qe operation to cancel */ void -GNUNET_NAMESTORE_cancel (struct GNUNET_NAMESTORE_QueueEntry *qe); +GNUNET_NAMESTORE_cancel(struct GNUNET_NAMESTORE_QueueEntry *qe); /** @@ -258,14 +258,14 @@ GNUNET_NAMESTORE_cancel (struct GNUNET_NAMESTORE_QueueEntry *qe); * @return an iterator handle to use for iteration */ struct GNUNET_NAMESTORE_ZoneIterator * -GNUNET_NAMESTORE_zone_iteration_start (struct GNUNET_NAMESTORE_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - GNUNET_SCHEDULER_TaskCallback error_cb, - void *error_cb_cls, - GNUNET_NAMESTORE_RecordMonitor proc, - void *proc_cls, - GNUNET_SCHEDULER_TaskCallback finish_cb, - void *finish_cb_cls); +GNUNET_NAMESTORE_zone_iteration_start(struct GNUNET_NAMESTORE_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + GNUNET_SCHEDULER_TaskCallback error_cb, + void *error_cb_cls, + GNUNET_NAMESTORE_RecordMonitor proc, + void *proc_cls, + GNUNET_SCHEDULER_TaskCallback finish_cb, + void *finish_cb_cls); /** @@ -277,8 +277,8 @@ GNUNET_NAMESTORE_zone_iteration_start (struct GNUNET_NAMESTORE_Handle *h, * (before #GNUNET_NAMESTORE_zone_iterator_next is to be called again) */ void -GNUNET_NAMESTORE_zone_iterator_next (struct GNUNET_NAMESTORE_ZoneIterator *it, - uint64_t limit); +GNUNET_NAMESTORE_zone_iterator_next(struct GNUNET_NAMESTORE_ZoneIterator *it, + uint64_t limit); /** @@ -289,7 +289,7 @@ GNUNET_NAMESTORE_zone_iterator_next (struct GNUNET_NAMESTORE_ZoneIterator *it, * @param it the iterator */ void -GNUNET_NAMESTORE_zone_iteration_stop (struct GNUNET_NAMESTORE_ZoneIterator *it); +GNUNET_NAMESTORE_zone_iteration_stop(struct GNUNET_NAMESTORE_ZoneIterator *it); /** @@ -326,15 +326,15 @@ struct GNUNET_NAMESTORE_ZoneMonitor; * @return handle to stop monitoring */ struct GNUNET_NAMESTORE_ZoneMonitor * -GNUNET_NAMESTORE_zone_monitor_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - int iterate_first, - GNUNET_SCHEDULER_TaskCallback error_cb, - void *error_cb_cls, - GNUNET_NAMESTORE_RecordMonitor monitor, - void *monitor_cls, - GNUNET_SCHEDULER_TaskCallback sync_cb, - void *sync_cb_cls); +GNUNET_NAMESTORE_zone_monitor_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + int iterate_first, + GNUNET_SCHEDULER_TaskCallback error_cb, + void *error_cb_cls, + GNUNET_NAMESTORE_RecordMonitor monitor, + void *monitor_cls, + GNUNET_SCHEDULER_TaskCallback sync_cb, + void *sync_cb_cls); /** @@ -359,8 +359,8 @@ GNUNET_NAMESTORE_zone_monitor_start (const struct GNUNET_CONFIGURATION_Handle *c * (before #GNUNET_NAMESTORE_zone_monitor_next is to be called again) */ void -GNUNET_NAMESTORE_zone_monitor_next (struct GNUNET_NAMESTORE_ZoneMonitor *zm, - uint64_t limit); +GNUNET_NAMESTORE_zone_monitor_next(struct GNUNET_NAMESTORE_ZoneMonitor *zm, + uint64_t limit); /** @@ -369,7 +369,7 @@ GNUNET_NAMESTORE_zone_monitor_next (struct GNUNET_NAMESTORE_ZoneMonitor *zm, * @param zm handle to the monitor activity to stop */ void -GNUNET_NAMESTORE_zone_monitor_stop (struct GNUNET_NAMESTORE_ZoneMonitor *zm); +GNUNET_NAMESTORE_zone_monitor_stop(struct GNUNET_NAMESTORE_ZoneMonitor *zm); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_nat_auto_service.h b/src/include/gnunet_nat_auto_service.h index dd74d1eeb..b40c515a5 100644 --- a/src/include/gnunet_nat_auto_service.h +++ b/src/include/gnunet_nat_auto_service.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -56,11 +56,11 @@ struct GNUNET_NAT_AUTO_Test; * @return handle to cancel NAT test */ struct GNUNET_NAT_AUTO_Test * -GNUNET_NAT_AUTO_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - uint8_t proto, - const char *section_name, - GNUNET_NAT_TestCallback report, - void *report_cls); +GNUNET_NAT_AUTO_test_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + uint8_t proto, + const char *section_name, + GNUNET_NAT_TestCallback report, + void *report_cls); /** @@ -69,7 +69,7 @@ GNUNET_NAT_AUTO_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param tst test to stop. */ void -GNUNET_NAT_AUTO_test_stop (struct GNUNET_NAT_AUTO_Test *tst); +GNUNET_NAT_AUTO_test_stop(struct GNUNET_NAT_AUTO_Test *tst); /** @@ -85,7 +85,7 @@ struct GNUNET_NAT_AUTO_AutoHandle; * @return point to a static string containing the error code */ const char * -GNUNET_NAT_AUTO_status2string (enum GNUNET_NAT_StatusCode err); +GNUNET_NAT_AUTO_status2string(enum GNUNET_NAT_StatusCode err); /** @@ -99,9 +99,9 @@ GNUNET_NAT_AUTO_status2string (enum GNUNET_NAT_StatusCode err); */ typedef void (*GNUNET_NAT_AUTO_AutoResultCallback)(void *cls, - const struct GNUNET_CONFIGURATION_Handle *diff, - enum GNUNET_NAT_StatusCode result, - enum GNUNET_NAT_Type type); + const struct GNUNET_CONFIGURATION_Handle *diff, + enum GNUNET_NAT_StatusCode result, + enum GNUNET_NAT_Type type); /** @@ -114,9 +114,9 @@ typedef void * @return handle to cancel operation */ struct GNUNET_NAT_AUTO_AutoHandle * -GNUNET_NAT_AUTO_autoconfig_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_NAT_AUTO_AutoResultCallback cb, - void *cb_cls); +GNUNET_NAT_AUTO_autoconfig_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_NAT_AUTO_AutoResultCallback cb, + void *cb_cls); /** @@ -125,7 +125,7 @@ GNUNET_NAT_AUTO_autoconfig_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param ah handle for operation to abort */ void -GNUNET_NAT_AUTO_autoconfig_cancel (struct GNUNET_NAT_AUTO_AutoHandle *ah); +GNUNET_NAT_AUTO_autoconfig_cancel(struct GNUNET_NAT_AUTO_AutoHandle *ah); #endif diff --git a/src/include/gnunet_nat_service.h b/src/include/gnunet_nat_service.h index b96b2386e..7f0e9764b 100644 --- a/src/include/gnunet_nat_service.h +++ b/src/include/gnunet_nat_service.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -49,9 +49,7 @@ * an equivalent enum in gnunet_transport_hello_service.h; * might ultimately belong with the new HELLO definition. */ -enum GNUNET_NAT_AddressClass -{ - +enum GNUNET_NAT_AddressClass { /** * No address. */ @@ -87,7 +85,7 @@ enum GNUNET_NAT_AddressClass * Useful for broadcasts. */ GNUNET_NAT_AC_LAN = 8, - + /** * Addresses useful in the local wired network, * i.e. a MAC. Sensitive, but obvious to people nearby. @@ -112,12 +110,12 @@ enum GNUNET_NAT_AddressClass * Loopback addresses, only useful under special cirumstances. */ GNUNET_NAT_AC_LOOPBACK = 64, - + /** * Addresses that should be our external IP address * on the outside of a NAT. Might be incorrectly determined. * Used as a bit in combination with #GNUNET_NAT_AC_GLOBAL, - * or in case of double-NAT with + * or in case of double-NAT with * #GNUNET_NAT_AC_LAN. */ GNUNET_NAT_AC_EXTERN = 128, @@ -132,15 +130,13 @@ enum GNUNET_NAT_AddressClass * Bitmask for "any" address. */ GNUNET_NAT_AC_ANY = 65535 - }; /** * Error Types for the NAT subsystem (which can then later be converted/resolved to a string) */ -enum GNUNET_NAT_StatusCode -{ +enum GNUNET_NAT_StatusCode { /** * Just the default */ @@ -235,7 +231,6 @@ enum GNUNET_NAT_StatusCode * */ GNUNET_NAT_ERROR_HELPER_NAT_CLIENT_NOT_FOUND - }; @@ -243,8 +238,7 @@ enum GNUNET_NAT_StatusCode /** * What the situation of the NAT connectivity */ -enum GNUNET_NAT_Type -{ +enum GNUNET_NAT_Type { /** * We have a direct connection */ @@ -269,7 +263,6 @@ enum GNUNET_NAT_Type * We know nothing about the NAT. */ GNUNET_NAT_TYPE_UNKNOWN - }; @@ -281,7 +274,7 @@ enum GNUNET_NAT_Type * @param cls closure * @param app_ctx[in,out] location where the app can store stuff * on add and retrieve it on remove - * @param add_remove #GNUNET_YES to add a new public IP address, + * @param add_remove #GNUNET_YES to add a new public IP address, * #GNUNET_NO to remove a previous (now invalid) one * @param ac address class the address belongs to * @param addr either the previous or the new public IP address @@ -289,9 +282,9 @@ enum GNUNET_NAT_Type */ typedef void (*GNUNET_NAT_AddressCallback) (void *cls, - void **app_ctx, + void **app_ctx, int add_remove, - enum GNUNET_NAT_AddressClass ac, + enum GNUNET_NAT_AddressClass ac, const struct sockaddr *addr, socklen_t addrlen); @@ -307,7 +300,7 @@ typedef void */ typedef void (*GNUNET_NAT_ReversalCallback) (void *cls, - const struct sockaddr *remote_addr, + const struct sockaddr *remote_addr, socklen_t remote_addrlen); @@ -338,15 +331,15 @@ struct GNUNET_NAT_Handle; * @return NULL on error, otherwise handle that can be used to unregister */ struct GNUNET_NAT_Handle * -GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *config_section, - uint8_t proto, - unsigned int num_addrs, - const struct sockaddr **addrs, - const socklen_t *addrlens, - GNUNET_NAT_AddressCallback address_callback, - GNUNET_NAT_ReversalCallback reversal_callback, - void *callback_cls); +GNUNET_NAT_register(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *config_section, + uint8_t proto, + unsigned int num_addrs, + const struct sockaddr **addrs, + const socklen_t *addrlens, + GNUNET_NAT_AddressCallback address_callback, + GNUNET_NAT_ReversalCallback reversal_callback, + void *callback_cls); /** @@ -363,9 +356,9 @@ GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg, * #GNUNET_SYSERR if the address is malformed */ int -GNUNET_NAT_test_address (struct GNUNET_NAT_Handle *nh, - const void *addr, - socklen_t addrlen); +GNUNET_NAT_test_address(struct GNUNET_NAT_Handle *nh, + const void *addr, + socklen_t addrlen); /** @@ -376,14 +369,14 @@ GNUNET_NAT_test_address (struct GNUNET_NAT_Handle *nh, * @param nh handle (used for configuration) * @param local_sa our local address of the peer (IPv4-only) * @param remote_sa the remote address of the peer (IPv4-only) - * @return #GNUNET_SYSERR on error, + * @return #GNUNET_SYSERR on error, * #GNUNET_NO if connection reversal is unavailable, * #GNUNET_OK otherwise (presumably in progress) */ int -GNUNET_NAT_request_reversal (struct GNUNET_NAT_Handle *nh, - const struct sockaddr_in *local_sa, - const struct sockaddr_in *remote_sa); +GNUNET_NAT_request_reversal(struct GNUNET_NAT_Handle *nh, + const struct sockaddr_in *local_sa, + const struct sockaddr_in *remote_sa); /** @@ -394,7 +387,7 @@ GNUNET_NAT_request_reversal (struct GNUNET_NAT_Handle *nh, * @param nh the handle to unregister */ void -GNUNET_NAT_unregister (struct GNUNET_NAT_Handle *nh); +GNUNET_NAT_unregister(struct GNUNET_NAT_Handle *nh); /** @@ -406,7 +399,7 @@ GNUNET_NAT_unregister (struct GNUNET_NAT_Handle *nh); * * The function does some basic sanity checks on packet size and * content, try to extract a bit of information. - * + * * At the moment this only processes BIND requests, and returns the * externally visible address of the request to the rest of the * NAT logic. @@ -421,11 +414,11 @@ GNUNET_NAT_unregister (struct GNUNET_NAT_Handle *nh); * #GNUNET_SYSERR on internal error handling the packet */ int -GNUNET_NAT_stun_handle_packet (struct GNUNET_NAT_Handle *nh, - const struct sockaddr *sender_addr, - size_t sender_addr_len, - const void *data, - size_t data_size); +GNUNET_NAT_stun_handle_packet(struct GNUNET_NAT_Handle *nh, + const struct sockaddr *sender_addr, + size_t sender_addr_len, + const void *data, + size_t data_size); /** @@ -445,7 +438,7 @@ struct GNUNET_NAT_STUN_Handle; */ typedef void (*GNUNET_NAT_TestCallback) (void *cls, - enum GNUNET_NAT_StatusCode result); + enum GNUNET_NAT_StatusCode result); /** @@ -463,11 +456,11 @@ typedef void * @return NULL on error */ struct GNUNET_NAT_STUN_Handle * -GNUNET_NAT_stun_make_request (const char *server, - uint16_t port, - struct GNUNET_NETWORK_Handle *sock, - GNUNET_NAT_TestCallback cb, - void *cb_cls); +GNUNET_NAT_stun_make_request(const char *server, + uint16_t port, + struct GNUNET_NETWORK_Handle *sock, + GNUNET_NAT_TestCallback cb, + void *cb_cls); /** @@ -477,7 +470,7 @@ GNUNET_NAT_stun_make_request (const char *server, * @param rh request to cancel */ void -GNUNET_NAT_stun_make_request_cancel (struct GNUNET_NAT_STUN_Handle *rh); +GNUNET_NAT_stun_make_request_cancel(struct GNUNET_NAT_STUN_Handle *rh); #endif diff --git a/src/include/gnunet_nc_lib.h b/src/include/gnunet_nc_lib.h index 2bfa7040c..1bdb474ea 100644 --- a/src/include/gnunet_nc_lib.h +++ b/src/include/gnunet_nc_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff * @@ -54,7 +54,7 @@ struct GNUNET_NotificationContext; * @return handle to the notification context */ struct GNUNET_NotificationContext * -GNUNET_notification_context_create (unsigned int queue_length); +GNUNET_notification_context_create(unsigned int queue_length); /** @@ -63,7 +63,7 @@ GNUNET_notification_context_create (unsigned int queue_length); * @param nc context to destroy. */ void -GNUNET_notification_context_destroy (struct GNUNET_NotificationContext *nc); +GNUNET_notification_context_destroy(struct GNUNET_NotificationContext *nc); /** @@ -73,8 +73,8 @@ GNUNET_notification_context_destroy (struct GNUNET_NotificationContext *nc); * @param mq message queue add */ void -GNUNET_notification_context_add (struct GNUNET_NotificationContext *nc, - struct GNUNET_MQ_Handle *mq); +GNUNET_notification_context_add(struct GNUNET_NotificationContext *nc, + struct GNUNET_MQ_Handle *mq); /** @@ -85,9 +85,9 @@ GNUNET_notification_context_add (struct GNUNET_NotificationContext *nc, * @param can_drop can this message be dropped due to queue length limitations */ void -GNUNET_notification_context_broadcast (struct GNUNET_NotificationContext *nc, - const struct GNUNET_MessageHeader *msg, - int can_drop); +GNUNET_notification_context_broadcast(struct GNUNET_NotificationContext *nc, + const struct GNUNET_MessageHeader *msg, + int can_drop); /** * Return active number of subscribers in this context. @@ -96,6 +96,6 @@ GNUNET_notification_context_broadcast (struct GNUNET_NotificationContext *nc, * @return number of current subscribers */ unsigned int -GNUNET_notification_context_get_size (struct GNUNET_NotificationContext *nc); +GNUNET_notification_context_get_size(struct GNUNET_NotificationContext *nc); #endif diff --git a/src/include/gnunet_network_lib.h b/src/include/gnunet_network_lib.h index 6c02f3577..2a91621a3 100644 --- a/src/include/gnunet_network_lib.h +++ b/src/include/gnunet_network_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Nils Durner @@ -49,9 +49,7 @@ struct GNUNET_NETWORK_Handle; /** * @brief collection of IO descriptors */ -struct GNUNET_NETWORK_FDSet -{ - +struct GNUNET_NETWORK_FDSet { /** * Maximum number of any socket descriptor in the set (plus one) */ @@ -80,9 +78,7 @@ struct GNUNET_NETWORK_FDSet * smaller than @e handles_size. */ unsigned int handles_pos; - #endif - }; #include "gnunet_disk_lib.h" @@ -95,7 +91,7 @@ struct GNUNET_NETWORK_FDSet * @return #GNUNET_OK if the PF is supported */ int -GNUNET_NETWORK_test_pf (int pf); +GNUNET_NETWORK_test_pf(int pf); /** @@ -108,7 +104,7 @@ GNUNET_NETWORK_test_pf (int pf); * @return shortened unixpath, NULL on error */ char * -GNUNET_NETWORK_shorten_unixpath (char *unixpath); +GNUNET_NETWORK_shorten_unixpath(char *unixpath); #ifndef WINDOWS @@ -122,7 +118,7 @@ GNUNET_NETWORK_shorten_unixpath (char *unixpath); * @param un unix domain socket address to check */ void -GNUNET_NETWORK_unix_precheck (const struct sockaddr_un *un); +GNUNET_NETWORK_unix_precheck(const struct sockaddr_un *un); #endif @@ -137,9 +133,9 @@ GNUNET_NETWORK_unix_precheck (const struct sockaddr_un *un); * @return client socket */ struct GNUNET_NETWORK_Handle * -GNUNET_NETWORK_socket_accept (const struct GNUNET_NETWORK_Handle *desc, - struct sockaddr *address, - socklen_t *address_len); +GNUNET_NETWORK_socket_accept(const struct GNUNET_NETWORK_Handle *desc, + struct sockaddr *address, + socklen_t *address_len); /** @@ -149,7 +145,7 @@ GNUNET_NETWORK_socket_accept (const struct GNUNET_NETWORK_Handle *desc, * @return NULL on error (including not supported on target platform) */ struct GNUNET_NETWORK_Handle * -GNUNET_NETWORK_socket_box_native (SOCKTYPE fd); +GNUNET_NETWORK_socket_box_native(SOCKTYPE fd); /** @@ -160,8 +156,8 @@ GNUNET_NETWORK_socket_box_native (SOCKTYPE fd); * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_NETWORK_socket_set_blocking (struct GNUNET_NETWORK_Handle *fd, - int doBlock); +GNUNET_NETWORK_socket_set_blocking(struct GNUNET_NETWORK_Handle *fd, + int doBlock); /** @@ -173,9 +169,9 @@ GNUNET_NETWORK_socket_set_blocking (struct GNUNET_NETWORK_Handle *fd, * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_NETWORK_socket_bind (struct GNUNET_NETWORK_Handle *desc, - const struct sockaddr *address, - socklen_t address_len); +GNUNET_NETWORK_socket_bind(struct GNUNET_NETWORK_Handle *desc, + const struct sockaddr *address, + socklen_t address_len); /** * Close a socket. @@ -184,7 +180,7 @@ GNUNET_NETWORK_socket_bind (struct GNUNET_NETWORK_Handle *desc, * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_NETWORK_socket_close (struct GNUNET_NETWORK_Handle *desc); +GNUNET_NETWORK_socket_close(struct GNUNET_NETWORK_Handle *desc); /** @@ -193,7 +189,7 @@ GNUNET_NETWORK_socket_close (struct GNUNET_NETWORK_Handle *desc); * @param desc socket */ void -GNUNET_NETWORK_socket_free_memory_only_ (struct GNUNET_NETWORK_Handle *desc); +GNUNET_NETWORK_socket_free_memory_only_(struct GNUNET_NETWORK_Handle *desc); /** @@ -205,9 +201,9 @@ GNUNET_NETWORK_socket_free_memory_only_ (struct GNUNET_NETWORK_Handle *desc); * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_NETWORK_socket_connect (const struct GNUNET_NETWORK_Handle *desc, - const struct sockaddr *address, - socklen_t address_len); +GNUNET_NETWORK_socket_connect(const struct GNUNET_NETWORK_Handle *desc, + const struct sockaddr *address, + socklen_t address_len); /** @@ -221,11 +217,11 @@ GNUNET_NETWORK_socket_connect (const struct GNUNET_NETWORK_Handle *desc, * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_NETWORK_socket_getsockopt (const struct GNUNET_NETWORK_Handle *desc, - int level, - int optname, - void *optval, - socklen_t *optlen); +GNUNET_NETWORK_socket_getsockopt(const struct GNUNET_NETWORK_Handle *desc, + int level, + int optname, + void *optval, + socklen_t *optlen); /** @@ -236,8 +232,8 @@ GNUNET_NETWORK_socket_getsockopt (const struct GNUNET_NETWORK_Handle *desc, * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_NETWORK_socket_listen (const struct GNUNET_NETWORK_Handle *desc, - int backlog); +GNUNET_NETWORK_socket_listen(const struct GNUNET_NETWORK_Handle *desc, + int backlog); /** @@ -247,7 +243,7 @@ GNUNET_NETWORK_socket_listen (const struct GNUNET_NETWORK_Handle *desc, * @returns #GNUNET_SYSERR if no data is available, or on error! */ ssize_t -GNUNET_NETWORK_socket_recvfrom_amount (const struct GNUNET_NETWORK_Handle *desc); +GNUNET_NETWORK_socket_recvfrom_amount(const struct GNUNET_NETWORK_Handle *desc); /** @@ -261,11 +257,11 @@ GNUNET_NETWORK_socket_recvfrom_amount (const struct GNUNET_NETWORK_Handle *desc) * @param addrlen length of the addr */ ssize_t -GNUNET_NETWORK_socket_recvfrom (const struct GNUNET_NETWORK_Handle *desc, - void *buffer, - size_t length, - struct sockaddr *src_addr, - socklen_t *addrlen); +GNUNET_NETWORK_socket_recvfrom(const struct GNUNET_NETWORK_Handle *desc, + void *buffer, + size_t length, + struct sockaddr *src_addr, + socklen_t *addrlen); /** @@ -277,9 +273,9 @@ GNUNET_NETWORK_socket_recvfrom (const struct GNUNET_NETWORK_Handle *desc, * @return number of bytes read */ ssize_t -GNUNET_NETWORK_socket_recv (const struct GNUNET_NETWORK_Handle *desc, - void *buffer, - size_t length); +GNUNET_NETWORK_socket_recv(const struct GNUNET_NETWORK_Handle *desc, + void *buffer, + size_t length); /** @@ -292,10 +288,10 @@ GNUNET_NETWORK_socket_recv (const struct GNUNET_NETWORK_Handle *desc, * @return number of selected sockets, #GNUNET_SYSERR on error */ int -GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds, - struct GNUNET_NETWORK_FDSet *wfds, - struct GNUNET_NETWORK_FDSet *efds, - struct GNUNET_TIME_Relative timeout); +GNUNET_NETWORK_socket_select(struct GNUNET_NETWORK_FDSet *rfds, + struct GNUNET_NETWORK_FDSet *wfds, + struct GNUNET_NETWORK_FDSet *efds, + struct GNUNET_TIME_Relative timeout); /** @@ -307,9 +303,9 @@ GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds, * @return number of bytes sent, #GNUNET_SYSERR on error */ ssize_t -GNUNET_NETWORK_socket_send (const struct GNUNET_NETWORK_Handle *desc, - const void *buffer, - size_t length); +GNUNET_NETWORK_socket_send(const struct GNUNET_NETWORK_Handle *desc, + const void *buffer, + size_t length); /** @@ -324,11 +320,11 @@ GNUNET_NETWORK_socket_send (const struct GNUNET_NETWORK_Handle *desc, * @return number of bytes sent, #GNUNET_SYSERR on error */ ssize_t -GNUNET_NETWORK_socket_sendto (const struct GNUNET_NETWORK_Handle *desc, - const void *message, - size_t length, - const struct sockaddr *dest_addr, - socklen_t dest_len); +GNUNET_NETWORK_socket_sendto(const struct GNUNET_NETWORK_Handle *desc, + const void *message, + size_t length, + const struct sockaddr *dest_addr, + socklen_t dest_len); /** @@ -342,11 +338,11 @@ GNUNET_NETWORK_socket_sendto (const struct GNUNET_NETWORK_Handle *desc, * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_NETWORK_socket_setsockopt (struct GNUNET_NETWORK_Handle *fd, - int level, - int option_name, - const void *option_value, - socklen_t option_len); +GNUNET_NETWORK_socket_setsockopt(struct GNUNET_NETWORK_Handle *fd, + int level, + int option_name, + const void *option_value, + socklen_t option_len); /** @@ -357,8 +353,8 @@ GNUNET_NETWORK_socket_setsockopt (struct GNUNET_NETWORK_Handle *fd, * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_NETWORK_socket_shutdown (struct GNUNET_NETWORK_Handle *desc, - int how); +GNUNET_NETWORK_socket_shutdown(struct GNUNET_NETWORK_Handle *desc, + int how); /** @@ -371,7 +367,7 @@ GNUNET_NETWORK_socket_shutdown (struct GNUNET_NETWORK_Handle *desc, * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_NETWORK_socket_disable_corking (struct GNUNET_NETWORK_Handle *desc); +GNUNET_NETWORK_socket_disable_corking(struct GNUNET_NETWORK_Handle *desc); /** @@ -385,9 +381,9 @@ GNUNET_NETWORK_socket_disable_corking (struct GNUNET_NETWORK_Handle *desc); * @return new socket, NULL on error */ struct GNUNET_NETWORK_Handle * -GNUNET_NETWORK_socket_create (int domain, - int type, - int protocol); +GNUNET_NETWORK_socket_create(int domain, + int type, + int protocol); /** @@ -396,7 +392,7 @@ GNUNET_NETWORK_socket_create (int domain, * @param fds fd set to clear */ void -GNUNET_NETWORK_fdset_zero (struct GNUNET_NETWORK_FDSet *fds); +GNUNET_NETWORK_fdset_zero(struct GNUNET_NETWORK_FDSet *fds); /** @@ -406,8 +402,8 @@ GNUNET_NETWORK_fdset_zero (struct GNUNET_NETWORK_FDSet *fds); * @param desc socket to add */ void -GNUNET_NETWORK_fdset_set (struct GNUNET_NETWORK_FDSet *fds, - const struct GNUNET_NETWORK_Handle *desc); +GNUNET_NETWORK_fdset_set(struct GNUNET_NETWORK_FDSet *fds, + const struct GNUNET_NETWORK_Handle *desc); #if WINDOWS @@ -418,8 +414,8 @@ GNUNET_NETWORK_fdset_set (struct GNUNET_NETWORK_FDSet *fds, * @param h the file handle to add */ void -GNUNET_NETWORK_fdset_handle_set_native_w32_handle (struct GNUNET_NETWORK_FDSet *fds, - HANDLE h); +GNUNET_NETWORK_fdset_handle_set_native_w32_handle(struct GNUNET_NETWORK_FDSet *fds, + HANDLE h); #endif @@ -431,8 +427,8 @@ GNUNET_NETWORK_fdset_handle_set_native_w32_handle (struct GNUNET_NETWORK_FDSet * * @return #GNUNET_YES if the socket is in the set */ int -GNUNET_NETWORK_fdset_isset (const struct GNUNET_NETWORK_FDSet *fds, - const struct GNUNET_NETWORK_Handle *desc); +GNUNET_NETWORK_fdset_isset(const struct GNUNET_NETWORK_FDSet *fds, + const struct GNUNET_NETWORK_Handle *desc); /** @@ -442,8 +438,8 @@ GNUNET_NETWORK_fdset_isset (const struct GNUNET_NETWORK_FDSet *fds, * @param src the fd set to add from */ void -GNUNET_NETWORK_fdset_add (struct GNUNET_NETWORK_FDSet *dst, - const struct GNUNET_NETWORK_FDSet *src); +GNUNET_NETWORK_fdset_add(struct GNUNET_NETWORK_FDSet *dst, + const struct GNUNET_NETWORK_FDSet *src); /** @@ -453,8 +449,8 @@ GNUNET_NETWORK_fdset_add (struct GNUNET_NETWORK_FDSet *dst, * @param from source */ void -GNUNET_NETWORK_fdset_copy (struct GNUNET_NETWORK_FDSet *to, - const struct GNUNET_NETWORK_FDSet *from); +GNUNET_NETWORK_fdset_copy(struct GNUNET_NETWORK_FDSet *to, + const struct GNUNET_NETWORK_FDSet *from); /** @@ -464,7 +460,7 @@ GNUNET_NETWORK_fdset_copy (struct GNUNET_NETWORK_FDSet *to, * @return POSIX file descriptor */ int -GNUNET_NETWORK_get_fd (const struct GNUNET_NETWORK_Handle *desc); +GNUNET_NETWORK_get_fd(const struct GNUNET_NETWORK_Handle *desc); /** @@ -474,7 +470,7 @@ GNUNET_NETWORK_get_fd (const struct GNUNET_NETWORK_Handle *desc); * @return POSIX file descriptor */ struct sockaddr* -GNUNET_NETWORK_get_addr (const struct GNUNET_NETWORK_Handle *desc); +GNUNET_NETWORK_get_addr(const struct GNUNET_NETWORK_Handle *desc); /** @@ -484,7 +480,7 @@ GNUNET_NETWORK_get_addr (const struct GNUNET_NETWORK_Handle *desc); * @return socklen_t for sockaddr */ socklen_t -GNUNET_NETWORK_get_addrlen (const struct GNUNET_NETWORK_Handle *desc); +GNUNET_NETWORK_get_addrlen(const struct GNUNET_NETWORK_Handle *desc); /** @@ -495,9 +491,9 @@ GNUNET_NETWORK_get_addrlen (const struct GNUNET_NETWORK_Handle *desc); * @param nfds the biggest socket number in from + 1 */ void -GNUNET_NETWORK_fdset_copy_native (struct GNUNET_NETWORK_FDSet *to, - const fd_set *from, - int nfds); +GNUNET_NETWORK_fdset_copy_native(struct GNUNET_NETWORK_FDSet *to, + const fd_set *from, + int nfds); /** @@ -507,8 +503,8 @@ GNUNET_NETWORK_fdset_copy_native (struct GNUNET_NETWORK_FDSet *to, * @param nfd native FD to set */ void -GNUNET_NETWORK_fdset_set_native (struct GNUNET_NETWORK_FDSet *to, - int nfd); +GNUNET_NETWORK_fdset_set_native(struct GNUNET_NETWORK_FDSet *to, + int nfd); /** @@ -519,8 +515,8 @@ GNUNET_NETWORK_fdset_set_native (struct GNUNET_NETWORK_FDSet *to, * @return #GNUNET_YES if to contains nfd */ int -GNUNET_NETWORK_fdset_test_native (const struct GNUNET_NETWORK_FDSet *to, - int nfd); +GNUNET_NETWORK_fdset_test_native(const struct GNUNET_NETWORK_FDSet *to, + int nfd); /** @@ -530,8 +526,8 @@ GNUNET_NETWORK_fdset_test_native (const struct GNUNET_NETWORK_FDSet *to, * @param h the file handle to add */ void -GNUNET_NETWORK_fdset_handle_set (struct GNUNET_NETWORK_FDSet *fds, - const struct GNUNET_DISK_FileHandle *h); +GNUNET_NETWORK_fdset_handle_set(struct GNUNET_NETWORK_FDSet *fds, + const struct GNUNET_DISK_FileHandle *h); /** @@ -542,8 +538,8 @@ GNUNET_NETWORK_fdset_handle_set (struct GNUNET_NETWORK_FDSet *fds, * @param h the file handle to add */ void -GNUNET_NETWORK_fdset_handle_set_first (struct GNUNET_NETWORK_FDSet *fds, - const struct GNUNET_DISK_FileHandle *h); +GNUNET_NETWORK_fdset_handle_set_first(struct GNUNET_NETWORK_FDSet *fds, + const struct GNUNET_DISK_FileHandle *h); /** @@ -554,8 +550,8 @@ GNUNET_NETWORK_fdset_handle_set_first (struct GNUNET_NETWORK_FDSet *fds, * @return #GNUNET_YES if the file handle is part of the set */ int -GNUNET_NETWORK_fdset_handle_isset (const struct GNUNET_NETWORK_FDSet *fds, - const struct GNUNET_DISK_FileHandle *h); +GNUNET_NETWORK_fdset_handle_isset(const struct GNUNET_NETWORK_FDSet *fds, + const struct GNUNET_DISK_FileHandle *h); /** @@ -566,8 +562,8 @@ GNUNET_NETWORK_fdset_handle_isset (const struct GNUNET_NETWORK_FDSet *fds, * @return #GNUNET_YES if they do overlap, #GNUNET_NO otherwise */ int -GNUNET_NETWORK_fdset_overlap (const struct GNUNET_NETWORK_FDSet *fds1, - const struct GNUNET_NETWORK_FDSet *fds2); +GNUNET_NETWORK_fdset_overlap(const struct GNUNET_NETWORK_FDSet *fds1, + const struct GNUNET_NETWORK_FDSet *fds2); /** @@ -576,7 +572,7 @@ GNUNET_NETWORK_fdset_overlap (const struct GNUNET_NETWORK_FDSet *fds1, * @return a new fd set */ struct GNUNET_NETWORK_FDSet * -GNUNET_NETWORK_fdset_create (void); +GNUNET_NETWORK_fdset_create(void); /** @@ -585,7 +581,7 @@ GNUNET_NETWORK_fdset_create (void); * @param fds fd set */ void -GNUNET_NETWORK_fdset_destroy (struct GNUNET_NETWORK_FDSet *fds); +GNUNET_NETWORK_fdset_destroy(struct GNUNET_NETWORK_FDSet *fds); /** @@ -596,8 +592,8 @@ GNUNET_NETWORK_fdset_destroy (struct GNUNET_NETWORK_FDSet *fds); * @return #GNUNET_OK if the port is available, #GNUNET_NO if not */ int -GNUNET_NETWORK_test_port_free (int ipproto, - uint16_t port); +GNUNET_NETWORK_test_port_free(int ipproto, + uint16_t port); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_nse_service.h b/src/include/gnunet_nse_service.h index 08282058a..31b128533 100644 --- a/src/include/gnunet_nse_service.h +++ b/src/include/gnunet_nse_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -92,8 +92,8 @@ typedef void (*GNUNET_NSE_Callback) (void *cls, * @return handle to use in #GNUNET_NSE_disconnect to stop NSE from invoking the callbacks */ struct GNUNET_NSE_Handle * -GNUNET_NSE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_NSE_Callback func, void *func_cls); +GNUNET_NSE_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_NSE_Callback func, void *func_cls); /** @@ -102,7 +102,7 @@ GNUNET_NSE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param h handle to destroy */ void -GNUNET_NSE_disconnect (struct GNUNET_NSE_Handle *h); +GNUNET_NSE_disconnect(struct GNUNET_NSE_Handle *h); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_nt_lib.h b/src/include/gnunet_nt_lib.h index 1da92a79a..48f3d7352 100644 --- a/src/include/gnunet_nt_lib.h +++ b/src/include/gnunet_nt_lib.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2015, 2018 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2015, 2018 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -32,8 +32,7 @@ /** * Types of networks (with separate quotas) we support. */ -enum GNUNET_NetworkType -{ +enum GNUNET_NetworkType { /** * Category of last resort. */ @@ -68,7 +67,6 @@ enum GNUNET_NetworkType * Number of network types supported by ATS */ #define GNUNET_NT_COUNT 6 - }; @@ -79,7 +77,7 @@ enum GNUNET_NetworkType * @return a string or NULL if invalid */ const char * -GNUNET_NT_to_string (enum GNUNET_NetworkType net); +GNUNET_NT_to_string(enum GNUNET_NetworkType net); /** @@ -97,9 +95,9 @@ struct GNUNET_NT_InterfaceScanner; * @return type of the network the address belongs to */ enum GNUNET_NetworkType -GNUNET_NT_scanner_get_type (struct GNUNET_NT_InterfaceScanner *is, - const struct sockaddr *addr, - socklen_t addrlen); +GNUNET_NT_scanner_get_type(struct GNUNET_NT_InterfaceScanner *is, + const struct sockaddr *addr, + socklen_t addrlen); /** @@ -108,7 +106,7 @@ GNUNET_NT_scanner_get_type (struct GNUNET_NT_InterfaceScanner *is, * @return scanner handle, NULL on error */ struct GNUNET_NT_InterfaceScanner * -GNUNET_NT_scanner_init (void); +GNUNET_NT_scanner_init(void); /** @@ -117,7 +115,7 @@ GNUNET_NT_scanner_init (void); * @param is scanner we are done with */ void -GNUNET_NT_scanner_done (struct GNUNET_NT_InterfaceScanner *is); +GNUNET_NT_scanner_done(struct GNUNET_NT_InterfaceScanner *is); #endif diff --git a/src/include/gnunet_op_lib.h b/src/include/gnunet_op_lib.h index d04577e2d..c96db354d 100644 --- a/src/include/gnunet_op_lib.h +++ b/src/include/gnunet_op_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file @@ -40,14 +40,14 @@ struct GNUNET_OP_Handle; * Create new operations handle. */ struct GNUNET_OP_Handle * -GNUNET_OP_create (); +GNUNET_OP_create(); /** * Destroy operations handle. */ void -GNUNET_OP_destroy (struct GNUNET_OP_Handle *h); +GNUNET_OP_destroy(struct GNUNET_OP_Handle *h); /** @@ -59,7 +59,7 @@ GNUNET_OP_destroy (struct GNUNET_OP_Handle *h); * @return Operation ID to use. */ uint64_t -GNUNET_OP_get_next_id (struct GNUNET_OP_Handle *h); +GNUNET_OP_get_next_id(struct GNUNET_OP_Handle *h); /** @@ -80,11 +80,11 @@ GNUNET_OP_get_next_id (struct GNUNET_OP_Handle *h); * #GNUNET_NO if not found. */ int -GNUNET_OP_get (struct GNUNET_OP_Handle *h, - uint64_t op_id, - GNUNET_ResultCallback *result_cb, - void **cls, - void **ctx); +GNUNET_OP_get(struct GNUNET_OP_Handle *h, + uint64_t op_id, + GNUNET_ResultCallback *result_cb, + void **cls, + void **ctx); /** @@ -102,10 +102,10 @@ GNUNET_OP_get (struct GNUNET_OP_Handle *h, * @return ID of the new operation. */ uint64_t -GNUNET_OP_add (struct GNUNET_OP_Handle *h, - GNUNET_ResultCallback result_cb, - void *cls, - void *ctx); +GNUNET_OP_add(struct GNUNET_OP_Handle *h, + GNUNET_ResultCallback result_cb, + void *cls, + void *ctx); /** @@ -128,12 +128,12 @@ GNUNET_OP_add (struct GNUNET_OP_Handle *h, * #GNUNET_NO if the operation was not found. */ int -GNUNET_OP_result (struct GNUNET_OP_Handle *h, - uint64_t op_id, - int64_t result_code, - const void *data, - uint16_t data_size, - void **ctx); +GNUNET_OP_result(struct GNUNET_OP_Handle *h, + uint64_t op_id, + int64_t result_code, + const void *data, + uint16_t data_size, + void **ctx); /** @@ -148,8 +148,8 @@ GNUNET_OP_result (struct GNUNET_OP_Handle *h, * #GNUNET_NO if the operation was not found. */ int -GNUNET_OP_remove (struct GNUNET_OP_Handle *h, - uint64_t op_id); +GNUNET_OP_remove(struct GNUNET_OP_Handle *h, + uint64_t op_id); #endif // GNUNET_OP_H diff --git a/src/include/gnunet_os_lib.h b/src/include/gnunet_os_lib.h index b632ab262..e5bc7146b 100644 --- a/src/include/gnunet_os_lib.h +++ b/src/include/gnunet_os_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -65,9 +65,7 @@ extern "C" * Flags that determine which of the standard streams * should be inherited by the child process. */ -enum GNUNET_OS_InheritStdioFlags -{ - +enum GNUNET_OS_InheritStdioFlags { /** * No standard streams should be inherited. */ @@ -114,8 +112,7 @@ struct GNUNET_OS_Process; /** * Possible installation paths to request */ -enum GNUNET_OS_InstallationPathKind -{ +enum GNUNET_OS_InstallationPathKind { /** * Return the "PREFIX" directory given to configure. */ @@ -169,8 +166,7 @@ enum GNUNET_OS_InstallationPathKind /** * Process status types */ -enum GNUNET_OS_ProcessStatusType -{ +enum GNUNET_OS_ProcessStatusType { /** * The process is not known to the OS (or at * least not one of our children). @@ -203,8 +199,7 @@ enum GNUNET_OS_ProcessStatusType * Project-specific data used to help the OS subsystem * find installation paths. */ -struct GNUNET_OS_ProjectData -{ +struct GNUNET_OS_ProjectData { /** * Name of a library that is installed in the "lib/" directory of * the project, such as "libgnunetutil". Used to locate the @@ -295,14 +290,14 @@ struct GNUNET_OS_ProjectData * Return default project data used by 'libgnunetutil' for GNUnet. */ const struct GNUNET_OS_ProjectData * -GNUNET_OS_project_data_default (void); +GNUNET_OS_project_data_default(void); /** * @return current (actual) project data. */ const struct GNUNET_OS_ProjectData * -GNUNET_OS_project_data_get (void); +GNUNET_OS_project_data_get(void); /** @@ -311,7 +306,7 @@ GNUNET_OS_project_data_get (void); * @param pd project data used to determine paths. */ void -GNUNET_OS_init (const struct GNUNET_OS_ProjectData *pd); +GNUNET_OS_init(const struct GNUNET_OS_ProjectData *pd); /** @@ -323,7 +318,7 @@ GNUNET_OS_init (const struct GNUNET_OS_ProjectData *pd); * @return a pointer to the dir path (to be freed by the caller) */ char * -GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind); +GNUNET_OS_installation_get_path(enum GNUNET_OS_InstallationPathKind dirkind); /** @@ -335,7 +330,7 @@ GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind); * @return full path to the binary, if possible, otherwise copy of 'progname' */ char * -GNUNET_OS_get_libexec_binary_path (const char *progname); +GNUNET_OS_get_libexec_binary_path(const char *progname); /** @@ -351,8 +346,8 @@ GNUNET_OS_get_libexec_binary_path (const char *progname); * otherwise */ char * -GNUNET_OS_get_suid_binary_path (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *progname); +GNUNET_OS_get_suid_binary_path(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *progname); /** @@ -384,8 +379,8 @@ typedef int * @param proc_cls closure for @a proc */ void -GNUNET_OS_network_interfaces_list (GNUNET_OS_NetworkInterfaceProcessor proc, - void *proc_cls); +GNUNET_OS_network_interfaces_list(GNUNET_OS_NetworkInterfaceProcessor proc, + void *proc_cls); /** * @brief Get maximum string length returned by gethostname() @@ -408,7 +403,7 @@ GNUNET_OS_network_interfaces_list (GNUNET_OS_NetworkInterfaceProcessor proc, * @return pointer to the process sturcutre for this process */ struct GNUNET_OS_Process * -GNUNET_OS_process_current (void); +GNUNET_OS_process_current(void); /** @@ -419,8 +414,8 @@ GNUNET_OS_process_current (void); * @return 0 on success, -1 on error */ int -GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, - int sig); +GNUNET_OS_process_kill(struct GNUNET_OS_Process *proc, + int sig); /** @@ -429,7 +424,7 @@ GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, * @param proc pointer to process structure */ void -GNUNET_OS_process_destroy (struct GNUNET_OS_Process *proc); +GNUNET_OS_process_destroy(struct GNUNET_OS_Process *proc); /** @@ -440,7 +435,7 @@ GNUNET_OS_process_destroy (struct GNUNET_OS_Process *proc); * @return the current process id */ pid_t -GNUNET_OS_process_get_pid (struct GNUNET_OS_Process *proc); +GNUNET_OS_process_get_pid(struct GNUNET_OS_Process *proc); /** @@ -456,13 +451,13 @@ GNUNET_OS_process_get_pid (struct GNUNET_OS_Process *proc); * @return pointer to process structure of the new process, NULL on error */ struct GNUNET_OS_Process * -GNUNET_OS_start_process_vap (int pipe_control, - enum GNUNET_OS_InheritStdioFlags std_inheritance, - struct GNUNET_DISK_PipeHandle *pipe_stdin, - struct GNUNET_DISK_PipeHandle *pipe_stdout, - struct GNUNET_DISK_PipeHandle *pipe_stderr, - const char *filename, - char *const argv[]); +GNUNET_OS_start_process_vap(int pipe_control, + enum GNUNET_OS_InheritStdioFlags std_inheritance, + struct GNUNET_DISK_PipeHandle *pipe_stdin, + struct GNUNET_DISK_PipeHandle *pipe_stdout, + struct GNUNET_DISK_PipeHandle *pipe_stderr, + const char *filename, + char *const argv[]); /** @@ -478,12 +473,12 @@ GNUNET_OS_start_process_vap (int pipe_control, * @return pointer to process structure of the new process, NULL on error */ struct GNUNET_OS_Process * -GNUNET_OS_start_process (int pipe_control, - enum GNUNET_OS_InheritStdioFlags std_inheritance, - struct GNUNET_DISK_PipeHandle *pipe_stdin, - struct GNUNET_DISK_PipeHandle *pipe_stdout, - struct GNUNET_DISK_PipeHandle *pipe_stderr, - const char *filename, ...); +GNUNET_OS_start_process(int pipe_control, + enum GNUNET_OS_InheritStdioFlags std_inheritance, + struct GNUNET_DISK_PipeHandle *pipe_stdin, + struct GNUNET_DISK_PipeHandle *pipe_stdout, + struct GNUNET_DISK_PipeHandle *pipe_stderr, + const char *filename, ...); /** @@ -499,12 +494,12 @@ GNUNET_OS_start_process (int pipe_control, * @return pointer to process structure of the new process, NULL on error */ struct GNUNET_OS_Process * -GNUNET_OS_start_process_va (int pipe_control, - enum GNUNET_OS_InheritStdioFlags std_inheritance, - struct GNUNET_DISK_PipeHandle *pipe_stdin, - struct GNUNET_DISK_PipeHandle *pipe_stdout, - struct GNUNET_DISK_PipeHandle *pipe_stderr, - const char *filename, va_list va); +GNUNET_OS_start_process_va(int pipe_control, + enum GNUNET_OS_InheritStdioFlags std_inheritance, + struct GNUNET_DISK_PipeHandle *pipe_stdin, + struct GNUNET_DISK_PipeHandle *pipe_stdout, + struct GNUNET_DISK_PipeHandle *pipe_stderr, + const char *filename, va_list va); /** * Start a process. @@ -519,11 +514,11 @@ GNUNET_OS_start_process_va (int pipe_control, * @return pointer to process structure of the new process, NULL on error */ struct GNUNET_OS_Process * -GNUNET_OS_start_process_v (int pipe_control, - enum GNUNET_OS_InheritStdioFlags std_inheritance, - const SOCKTYPE *lsocks, - const char *filename, - char *const argv[]); +GNUNET_OS_start_process_v(int pipe_control, + enum GNUNET_OS_InheritStdioFlags std_inheritance, + const SOCKTYPE *lsocks, + const char *filename, + char *const argv[]); /** @@ -545,10 +540,10 @@ GNUNET_OS_start_process_v (int pipe_control, * @return pointer to process structure of the new process, NULL on error */ struct GNUNET_OS_Process * -GNUNET_OS_start_process_s (int pipe_control, - unsigned int std_inheritance, - const SOCKTYPE * lsocks, - const char *filename, ...); +GNUNET_OS_start_process_s(int pipe_control, + unsigned int std_inheritance, + const SOCKTYPE * lsocks, + const char *filename, ...); /** @@ -573,7 +568,7 @@ typedef void * @param cmd handle to the process */ void -GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd); +GNUNET_OS_command_stop(struct GNUNET_OS_CommandHandle *cmd); /** @@ -588,11 +583,11 @@ GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd); * @return NULL on error */ struct GNUNET_OS_CommandHandle * -GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, - void *proc_cls, - struct GNUNET_TIME_Relative timeout, - const char *binary, - ...); +GNUNET_OS_command_run(GNUNET_OS_LineProcessor proc, + void *proc_cls, + struct GNUNET_TIME_Relative timeout, + const char *binary, + ...); /** @@ -605,9 +600,9 @@ GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, * @return #GNUNET_OK on success, #GNUNET_NO if the process is still running, #GNUNET_SYSERR otherwise */ int -GNUNET_OS_process_status (struct GNUNET_OS_Process *proc, - enum GNUNET_OS_ProcessStatusType *type, - unsigned long *code); +GNUNET_OS_process_status(struct GNUNET_OS_Process *proc, + enum GNUNET_OS_ProcessStatusType *type, + unsigned long *code); /** @@ -621,7 +616,7 @@ GNUNET_OS_process_status (struct GNUNET_OS_Process *proc, * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise */ int -GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc); +GNUNET_OS_process_wait(struct GNUNET_OS_Process *proc); @@ -635,9 +630,9 @@ GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc); * @return #GNUNET_OK on success, #GNUNET_NO if the process is still running, #GNUNET_SYSERR otherwise */ int -GNUNET_OS_process_wait_status (struct GNUNET_OS_Process *proc, - enum GNUNET_OS_ProcessStatusType *type, - unsigned long *code); +GNUNET_OS_process_wait_status(struct GNUNET_OS_Process *proc, + enum GNUNET_OS_ProcessStatusType *type, + unsigned long *code); /** @@ -649,7 +644,7 @@ GNUNET_OS_process_wait_status (struct GNUNET_OS_Process *proc, * @param cls closure (unused) */ void -GNUNET_OS_install_parent_control_handler (void *cls); +GNUNET_OS_install_parent_control_handler(void *cls); /** @@ -670,9 +665,9 @@ GNUNET_OS_install_parent_control_handler (void *cls); * #GNUNET_SYSERR on error (no such binary or not executable) */ int -GNUNET_OS_check_helper_binary (const char *binary, - int check_suid, - const char *params); +GNUNET_OS_check_helper_binary(const char *binary, + int check_suid, + const char *params); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_peer_lib.h b/src/include/gnunet_peer_lib.h index b1c7220e2..e7caa1062 100644 --- a/src/include/gnunet_peer_lib.h +++ b/src/include/gnunet_peer_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -58,7 +58,7 @@ typedef unsigned int GNUNET_PEER_Id; * @return the interned identity or 0. */ GNUNET_PEER_Id -GNUNET_PEER_search (const struct GNUNET_PeerIdentity *pid); +GNUNET_PEER_search(const struct GNUNET_PeerIdentity *pid); /** @@ -69,7 +69,7 @@ GNUNET_PEER_search (const struct GNUNET_PeerIdentity *pid); * @return the interned identity. */ GNUNET_PEER_Id -GNUNET_PEER_intern (const struct GNUNET_PeerIdentity *pid); +GNUNET_PEER_intern(const struct GNUNET_PeerIdentity *pid); /** @@ -79,7 +79,7 @@ GNUNET_PEER_intern (const struct GNUNET_PeerIdentity *pid); * @param delta how much to change the RC */ void -GNUNET_PEER_change_rc (GNUNET_PEER_Id id, int delta); +GNUNET_PEER_change_rc(GNUNET_PEER_Id id, int delta); /** @@ -89,8 +89,8 @@ GNUNET_PEER_change_rc (GNUNET_PEER_Id id, int delta); * @param count size of the @a ids array */ void -GNUNET_PEER_decrement_rcs (const GNUNET_PEER_Id *ids, - unsigned int count); +GNUNET_PEER_decrement_rcs(const GNUNET_PEER_Id *ids, + unsigned int count); /** @@ -100,8 +100,8 @@ GNUNET_PEER_decrement_rcs (const GNUNET_PEER_Id *ids, * @param pid where to write the normal peer identity */ void -GNUNET_PEER_resolve (GNUNET_PEER_Id id, - struct GNUNET_PeerIdentity *pid); +GNUNET_PEER_resolve(GNUNET_PEER_Id id, + struct GNUNET_PeerIdentity *pid); /** @@ -111,7 +111,7 @@ GNUNET_PEER_resolve (GNUNET_PEER_Id id, * @return pointer to peer identity, valid as long @a id is valid */ const struct GNUNET_PeerIdentity * -GNUNET_PEER_resolve2 (GNUNET_PEER_Id id); +GNUNET_PEER_resolve2(GNUNET_PEER_Id id); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_peerinfo_service.h b/src/include/gnunet_peerinfo_service.h index 6fc48f806..f7663c43e 100644 --- a/src/include/gnunet_peerinfo_service.h +++ b/src/include/gnunet_peerinfo_service.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff * @@ -64,7 +64,7 @@ struct GNUNET_PEERINFO_Handle; * etablishment may happen asynchronously). */ struct GNUNET_PEERINFO_Handle * -GNUNET_PEERINFO_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_PEERINFO_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -77,7 +77,7 @@ GNUNET_PEERINFO_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param h handle to disconnect */ void -GNUNET_PEERINFO_disconnect (struct GNUNET_PEERINFO_Handle *h); +GNUNET_PEERINFO_disconnect(struct GNUNET_PEERINFO_Handle *h); /** @@ -99,10 +99,10 @@ GNUNET_PEERINFO_disconnect (struct GNUNET_PEERINFO_Handle *h); * calling @a cont must be prevented) */ struct GNUNET_MQ_Envelope * -GNUNET_PEERINFO_add_peer (struct GNUNET_PEERINFO_Handle *h, - const struct GNUNET_HELLO_Message *hello, - GNUNET_SCHEDULER_TaskCallback cont, - void *cont_cls); +GNUNET_PEERINFO_add_peer(struct GNUNET_PEERINFO_Handle *h, + const struct GNUNET_HELLO_Message *hello, + GNUNET_SCHEDULER_TaskCallback cont, + void *cont_cls); /** @@ -145,11 +145,11 @@ struct GNUNET_PEERINFO_IteratorContext; * @return iterator context */ struct GNUNET_PEERINFO_IteratorContext * -GNUNET_PEERINFO_iterate (struct GNUNET_PEERINFO_Handle *h, - int include_friend_only, - const struct GNUNET_PeerIdentity *peer, - GNUNET_PEERINFO_Processor callback, - void *callback_cls); +GNUNET_PEERINFO_iterate(struct GNUNET_PEERINFO_Handle *h, + int include_friend_only, + const struct GNUNET_PeerIdentity *peer, + GNUNET_PEERINFO_Processor callback, + void *callback_cls); /** @@ -158,7 +158,7 @@ GNUNET_PEERINFO_iterate (struct GNUNET_PEERINFO_Handle *h, * @param ic context of the iterator to cancel */ void -GNUNET_PEERINFO_iterate_cancel (struct GNUNET_PEERINFO_IteratorContext *ic); +GNUNET_PEERINFO_iterate_cancel(struct GNUNET_PEERINFO_IteratorContext *ic); /** @@ -183,10 +183,10 @@ struct GNUNET_PEERINFO_NotifyContext; * @return NULL on error */ struct GNUNET_PEERINFO_NotifyContext * -GNUNET_PEERINFO_notify (const struct GNUNET_CONFIGURATION_Handle *cfg, - int include_friend_only, - GNUNET_PEERINFO_Processor callback, - void *callback_cls); +GNUNET_PEERINFO_notify(const struct GNUNET_CONFIGURATION_Handle *cfg, + int include_friend_only, + GNUNET_PEERINFO_Processor callback, + void *callback_cls); /** @@ -195,7 +195,7 @@ GNUNET_PEERINFO_notify (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param nc context to stop notifying */ void -GNUNET_PEERINFO_notify_cancel (struct GNUNET_PEERINFO_NotifyContext *nc); +GNUNET_PEERINFO_notify_cancel(struct GNUNET_PEERINFO_NotifyContext *nc); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_peerstore_plugin.h b/src/include/gnunet_peerstore_plugin.h index bd5d18068..20130dec2 100644 --- a/src/include/gnunet_peerstore_plugin.h +++ b/src/include/gnunet_peerstore_plugin.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Omar Tarabai @@ -46,9 +46,7 @@ extern "C" /** * @brief struct returned by the initialization function of the plugin */ -struct GNUNET_PEERSTORE_PluginFunctions -{ - +struct GNUNET_PEERSTORE_PluginFunctions { /** * Closure to pass to all plugin functions. */ @@ -119,7 +117,6 @@ struct GNUNET_PEERSTORE_PluginFunctions struct GNUNET_TIME_Absolute now, GNUNET_PEERSTORE_Continuation cont, void *cont_cls); - }; diff --git a/src/include/gnunet_peerstore_service.h b/src/include/gnunet_peerstore_service.h index ad80a3fa3..ac390ada2 100644 --- a/src/include/gnunet_peerstore_service.h +++ b/src/include/gnunet_peerstore_service.h @@ -71,9 +71,7 @@ extern "C" { /** * Options for storing values in PEERSTORE */ -enum GNUNET_PEERSTORE_StoreOption -{ - +enum GNUNET_PEERSTORE_StoreOption { /** * Possibly store multiple values under given key. */ @@ -84,7 +82,6 @@ enum GNUNET_PEERSTORE_StoreOption * storing the given value. */ GNUNET_PEERSTORE_STOREOPTION_REPLACE = 1 - }; /** @@ -100,9 +97,7 @@ struct GNUNET_PEERSTORE_StoreContext; /** * Single PEERSTORE record */ -struct GNUNET_PEERSTORE_Record -{ - +struct GNUNET_PEERSTORE_Record { /** * Responsible sub system string */ @@ -169,7 +164,7 @@ typedef void (*GNUNET_PEERSTORE_Processor) ( * @return NULL on error */ struct GNUNET_PEERSTORE_Handle * -GNUNET_PEERSTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_PEERSTORE_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -181,7 +176,7 @@ GNUNET_PEERSTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param sync_first send any pending STORE requests before disconnecting */ void -GNUNET_PEERSTORE_disconnect (struct GNUNET_PEERSTORE_Handle *h, int sync_first); +GNUNET_PEERSTORE_disconnect(struct GNUNET_PEERSTORE_Handle *h, int sync_first); /** @@ -201,16 +196,16 @@ GNUNET_PEERSTORE_disconnect (struct GNUNET_PEERSTORE_Handle *h, int sync_first); * @param cont_cls Closure for @a cont */ struct GNUNET_PEERSTORE_StoreContext * -GNUNET_PEERSTORE_store (struct GNUNET_PEERSTORE_Handle *h, - const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - const void *value, - size_t size, - struct GNUNET_TIME_Absolute expiry, - enum GNUNET_PEERSTORE_StoreOption options, - GNUNET_PEERSTORE_Continuation cont, - void *cont_cls); +GNUNET_PEERSTORE_store(struct GNUNET_PEERSTORE_Handle *h, + const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + const void *value, + size_t size, + struct GNUNET_TIME_Absolute expiry, + enum GNUNET_PEERSTORE_StoreOption options, + GNUNET_PEERSTORE_Continuation cont, + void *cont_cls); /** @@ -219,7 +214,7 @@ GNUNET_PEERSTORE_store (struct GNUNET_PEERSTORE_Handle *h, * @param sc Store request context */ void -GNUNET_PEERSTORE_store_cancel (struct GNUNET_PEERSTORE_StoreContext *sc); +GNUNET_PEERSTORE_store_cancel(struct GNUNET_PEERSTORE_StoreContext *sc); /** @@ -233,12 +228,12 @@ GNUNET_PEERSTORE_store_cancel (struct GNUNET_PEERSTORE_StoreContext *sc); * @param callback_cls closure for @a callback */ struct GNUNET_PEERSTORE_IterateContext * -GNUNET_PEERSTORE_iterate (struct GNUNET_PEERSTORE_Handle *h, - const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - GNUNET_PEERSTORE_Processor callback, - void *callback_cls); +GNUNET_PEERSTORE_iterate(struct GNUNET_PEERSTORE_Handle *h, + const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + GNUNET_PEERSTORE_Processor callback, + void *callback_cls); /** @@ -248,7 +243,7 @@ GNUNET_PEERSTORE_iterate (struct GNUNET_PEERSTORE_Handle *h, * @param ic Iterate request context as returned by GNUNET_PEERSTORE_iterate() */ void -GNUNET_PEERSTORE_iterate_cancel (struct GNUNET_PEERSTORE_IterateContext *ic); +GNUNET_PEERSTORE_iterate_cancel(struct GNUNET_PEERSTORE_IterateContext *ic); /** @@ -264,12 +259,12 @@ GNUNET_PEERSTORE_iterate_cancel (struct GNUNET_PEERSTORE_IterateContext *ic); * @return Handle to watch request */ struct GNUNET_PEERSTORE_WatchContext * -GNUNET_PEERSTORE_watch (struct GNUNET_PEERSTORE_Handle *h, - const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - GNUNET_PEERSTORE_Processor callback, - void *callback_cls); +GNUNET_PEERSTORE_watch(struct GNUNET_PEERSTORE_Handle *h, + const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + GNUNET_PEERSTORE_Processor callback, + void *callback_cls); /** @@ -278,7 +273,7 @@ GNUNET_PEERSTORE_watch (struct GNUNET_PEERSTORE_Handle *h, * @param wc handle to the watch request */ void -GNUNET_PEERSTORE_watch_cancel (struct GNUNET_PEERSTORE_WatchContext *wc); +GNUNET_PEERSTORE_watch_cancel(struct GNUNET_PEERSTORE_WatchContext *wc); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_plugin_lib.h b/src/include/gnunet_plugin_lib.h index bfcf1924f..67e6b5131 100644 --- a/src/include/gnunet_plugin_lib.h +++ b/src/include/gnunet_plugin_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -66,7 +66,7 @@ typedef void * * @return #GNUNET_YES if the plugin exists, #GNUNET_NO if not */ int -GNUNET_PLUGIN_test (const char *library_name); +GNUNET_PLUGIN_test(const char *library_name); /** @@ -82,8 +82,8 @@ GNUNET_PLUGIN_test (const char *library_name); * @return whatever the initialization function returned, NULL on error */ void * -GNUNET_PLUGIN_load (const char *library_name, - void *arg); +GNUNET_PLUGIN_load(const char *library_name, + void *arg); /** @@ -115,10 +115,10 @@ typedef void * @param cb_cls closure for @a cb */ void -GNUNET_PLUGIN_load_all (const char *basename, - void *arg, - GNUNET_PLUGIN_LoaderCallback cb, - void *cb_cls); +GNUNET_PLUGIN_load_all(const char *basename, + void *arg, + GNUNET_PLUGIN_LoaderCallback cb, + void *cb_cls); /** @@ -131,8 +131,8 @@ GNUNET_PLUGIN_load_all (const char *basename, * or a "char *" representing the error message */ void * -GNUNET_PLUGIN_unload (const char *library_name, - void *arg); +GNUNET_PLUGIN_unload(const char *library_name, + void *arg); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_pq_lib.h b/src/include/gnunet_pq_lib.h index 1734fb94d..fcd886521 100644 --- a/src/include/gnunet_pq_lib.h +++ b/src/include/gnunet_pq_lib.h @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2016, 2017 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2016, 2017 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file include/gnunet_pq_lib.h * @brief helper functions for Postgres DB interactions @@ -60,9 +60,7 @@ typedef int (*GNUNET_PQ_QueryConverter) (void *cls, /** * @brief Description of a DB query parameter. */ -struct GNUNET_PQ_QueryParam -{ - +struct GNUNET_PQ_QueryParam { /** * Function for how to handle this type of entry. */ @@ -107,7 +105,7 @@ struct GNUNET_PQ_QueryParam * @oaran ptr_size number of bytes in @a ptr */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_fixed_size (const void *ptr, size_t ptr_size); +GNUNET_PQ_query_param_fixed_size(const void *ptr, size_t ptr_size); /** @@ -116,7 +114,7 @@ GNUNET_PQ_query_param_fixed_size (const void *ptr, size_t ptr_size); * @param ptr pointer to the string query parameter to pass */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_string (const char *ptr); +GNUNET_PQ_query_param_string(const char *ptr); /** @@ -126,7 +124,7 @@ GNUNET_PQ_query_param_string (const char *ptr); * @param x pointer to the query parameter to pass. */ #define GNUNET_PQ_query_param_auto_from_type(x) \ - GNUNET_PQ_query_param_fixed_size ((x), sizeof (*(x))) + GNUNET_PQ_query_param_fixed_size((x), sizeof(*(x))) /** @@ -136,7 +134,7 @@ GNUNET_PQ_query_param_string (const char *ptr); * @param x the query parameter to pass. */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_rsa_public_key ( +GNUNET_PQ_query_param_rsa_public_key( const struct GNUNET_CRYPTO_RsaPublicKey *x); @@ -147,7 +145,7 @@ GNUNET_PQ_query_param_rsa_public_key ( * @param x the query parameter to pass */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_rsa_signature ( +GNUNET_PQ_query_param_rsa_signature( const struct GNUNET_CRYPTO_RsaSignature *x); @@ -158,7 +156,7 @@ GNUNET_PQ_query_param_rsa_signature ( * @param x pointer to the query parameter to pass */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_absolute_time (const struct GNUNET_TIME_Absolute *x); +GNUNET_PQ_query_param_absolute_time(const struct GNUNET_TIME_Absolute *x); /** @@ -168,7 +166,7 @@ GNUNET_PQ_query_param_absolute_time (const struct GNUNET_TIME_Absolute *x); * @param x pointer to the query parameter to pass */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_absolute_time_nbo ( +GNUNET_PQ_query_param_absolute_time_nbo( const struct GNUNET_TIME_AbsoluteNBO *x); @@ -178,7 +176,7 @@ GNUNET_PQ_query_param_absolute_time_nbo ( * @param x pointer to the query parameter to pass */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_uint16 (const uint16_t *x); +GNUNET_PQ_query_param_uint16(const uint16_t *x); /** @@ -187,7 +185,7 @@ GNUNET_PQ_query_param_uint16 (const uint16_t *x); * @param x pointer to the query parameter to pass */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_uint32 (const uint32_t *x); +GNUNET_PQ_query_param_uint32(const uint32_t *x); /** @@ -196,7 +194,7 @@ GNUNET_PQ_query_param_uint32 (const uint32_t *x); * @param x pointer to the query parameter to pass */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_uint64 (const uint64_t *x); +GNUNET_PQ_query_param_uint64(const uint64_t *x); /* ************************* pq_result_helper.c functions ************************ */ @@ -236,9 +234,7 @@ typedef void (*GNUNET_PQ_ResultCleanup) (void *cls, void *rd); /** * @brief Description of a DB result cell. */ -struct GNUNET_PQ_ResultSpec -{ - +struct GNUNET_PQ_ResultSpec { /** * What is the format of the result? */ @@ -299,9 +295,9 @@ struct GNUNET_PQ_ResultSpec * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_variable_size (const char *name, - void **dst, - size_t *sptr); +GNUNET_PQ_result_spec_variable_size(const char *name, + void **dst, + size_t *sptr); /** @@ -313,7 +309,7 @@ GNUNET_PQ_result_spec_variable_size (const char *name, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_fixed_size (const char *name, void *dst, size_t dst_size); +GNUNET_PQ_result_spec_fixed_size(const char *name, void *dst, size_t dst_size); /** @@ -324,7 +320,7 @@ GNUNET_PQ_result_spec_fixed_size (const char *name, void *dst, size_t dst_size); * @return array entry for the result specification to use */ #define GNUNET_PQ_result_spec_auto_from_type(name, dst) \ - GNUNET_PQ_result_spec_fixed_size (name, (dst), sizeof (*(dst))) + GNUNET_PQ_result_spec_fixed_size(name, (dst), sizeof(*(dst))) /** @@ -335,7 +331,7 @@ GNUNET_PQ_result_spec_fixed_size (const char *name, void *dst, size_t dst_size); * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_string (const char *name, char **dst); +GNUNET_PQ_result_spec_string(const char *name, char **dst); /** @@ -346,8 +342,8 @@ GNUNET_PQ_result_spec_string (const char *name, char **dst); * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_rsa_public_key (const char *name, - struct GNUNET_CRYPTO_RsaPublicKey **rsa); +GNUNET_PQ_result_spec_rsa_public_key(const char *name, + struct GNUNET_CRYPTO_RsaPublicKey **rsa); /** @@ -358,8 +354,8 @@ GNUNET_PQ_result_spec_rsa_public_key (const char *name, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_rsa_signature (const char *name, - struct GNUNET_CRYPTO_RsaSignature **sig); +GNUNET_PQ_result_spec_rsa_signature(const char *name, + struct GNUNET_CRYPTO_RsaSignature **sig); /** @@ -370,8 +366,8 @@ GNUNET_PQ_result_spec_rsa_signature (const char *name, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_absolute_time (const char *name, - struct GNUNET_TIME_Absolute *at); +GNUNET_PQ_result_spec_absolute_time(const char *name, + struct GNUNET_TIME_Absolute *at); /** @@ -382,8 +378,8 @@ GNUNET_PQ_result_spec_absolute_time (const char *name, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_absolute_time_nbo (const char *name, - struct GNUNET_TIME_AbsoluteNBO *at); +GNUNET_PQ_result_spec_absolute_time_nbo(const char *name, + struct GNUNET_TIME_AbsoluteNBO *at); /** @@ -394,7 +390,7 @@ GNUNET_PQ_result_spec_absolute_time_nbo (const char *name, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_uint16 (const char *name, uint16_t *u16); +GNUNET_PQ_result_spec_uint16(const char *name, uint16_t *u16); /** @@ -405,7 +401,7 @@ GNUNET_PQ_result_spec_uint16 (const char *name, uint16_t *u16); * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_uint32 (const char *name, uint32_t *u32); +GNUNET_PQ_result_spec_uint32(const char *name, uint32_t *u32); /** @@ -416,7 +412,7 @@ GNUNET_PQ_result_spec_uint32 (const char *name, uint32_t *u32); * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_uint64 (const char *name, uint64_t *u64); +GNUNET_PQ_result_spec_uint64(const char *name, uint64_t *u64); /* ************************* pq.c functions ************************ */ @@ -431,9 +427,9 @@ GNUNET_PQ_result_spec_uint64 (const char *name, uint64_t *u64); * @deprecated (should become an internal API) */ PGresult * -GNUNET_PQ_exec_prepared (PGconn *db_conn, - const char *name, - const struct GNUNET_PQ_QueryParam *params); +GNUNET_PQ_exec_prepared(PGconn *db_conn, + const char *name, + const struct GNUNET_PQ_QueryParam *params); /** @@ -448,9 +444,9 @@ GNUNET_PQ_exec_prepared (PGconn *db_conn, * @deprecated (should become an internal API) */ int -GNUNET_PQ_extract_result (PGresult *result, - struct GNUNET_PQ_ResultSpec *rs, - int row); +GNUNET_PQ_extract_result(PGresult *result, + struct GNUNET_PQ_ResultSpec *rs, + int row); /** @@ -460,7 +456,7 @@ GNUNET_PQ_extract_result (PGresult *result, * @param rs reult specification to clean up */ void -GNUNET_PQ_cleanup_result (struct GNUNET_PQ_ResultSpec *rs); +GNUNET_PQ_cleanup_result(struct GNUNET_PQ_ResultSpec *rs); /* ******************** pq_eval.c functions ************** */ @@ -480,9 +476,9 @@ GNUNET_PQ_cleanup_result (struct GNUNET_PQ_ResultSpec *rs); * @deprecated (low level, let's see if we can do with just the high-level functions) */ enum GNUNET_DB_QueryStatus -GNUNET_PQ_eval_result (PGconn *connection, - const char *statement_name, - PGresult *result); +GNUNET_PQ_eval_result(PGconn *connection, + const char *statement_name, + PGresult *result); /** @@ -502,9 +498,9 @@ GNUNET_PQ_eval_result (PGconn *connection, * zero; if INSERT was successful, we return one. */ enum GNUNET_DB_QueryStatus -GNUNET_PQ_eval_prepared_non_select (PGconn *connection, - const char *statement_name, - const struct GNUNET_PQ_QueryParam *params); +GNUNET_PQ_eval_prepared_non_select(PGconn *connection, + const char *statement_name, + const struct GNUNET_PQ_QueryParam *params); /** @@ -536,11 +532,11 @@ typedef void (*GNUNET_PQ_PostgresResultHandler) (void *cls, * codes to `enum GNUNET_DB_QueryStatus`. */ enum GNUNET_DB_QueryStatus -GNUNET_PQ_eval_prepared_multi_select (PGconn *connection, - const char *statement_name, - const struct GNUNET_PQ_QueryParam *params, - GNUNET_PQ_PostgresResultHandler rh, - void *rh_cls); +GNUNET_PQ_eval_prepared_multi_select(PGconn *connection, + const char *statement_name, + const struct GNUNET_PQ_QueryParam *params, + GNUNET_PQ_PostgresResultHandler rh, + void *rh_cls); /** @@ -559,7 +555,7 @@ GNUNET_PQ_eval_prepared_multi_select (PGconn *connection, * codes to `enum GNUNET_DB_QueryStatus`. */ enum GNUNET_DB_QueryStatus -GNUNET_PQ_eval_prepared_singleton_select ( +GNUNET_PQ_eval_prepared_singleton_select( PGconn *connection, const char *statement_name, const struct GNUNET_PQ_QueryParam *params, @@ -573,9 +569,7 @@ GNUNET_PQ_eval_prepared_singleton_select ( * Information needed to prepare a list of SQL statements using * #GNUNET_PQ_prepare_statements(). */ -struct GNUNET_PQ_PreparedStatement -{ - +struct GNUNET_PQ_PreparedStatement { /** * Name of the statement. */ @@ -611,9 +605,9 @@ struct GNUNET_PQ_PreparedStatement * @return initialized struct */ struct GNUNET_PQ_PreparedStatement -GNUNET_PQ_make_prepare (const char *name, - const char *sql, - unsigned int num_args); +GNUNET_PQ_make_prepare(const char *name, + const char *sql, + unsigned int num_args); /** @@ -626,8 +620,8 @@ GNUNET_PQ_make_prepare (const char *name, * #GNUNET_SYSERR on error */ int -GNUNET_PQ_prepare_statements (PGconn *connection, - const struct GNUNET_PQ_PreparedStatement *ps); +GNUNET_PQ_prepare_statements(PGconn *connection, + const struct GNUNET_PQ_PreparedStatement *ps); /* ******************** pq_exec.c functions ************** */ @@ -637,9 +631,7 @@ GNUNET_PQ_prepare_statements (PGconn *connection, * Information needed to run a list of SQL statements using * #GNUNET_PQ_exec_statements(). */ -struct GNUNET_PQ_ExecuteStatement -{ - +struct GNUNET_PQ_ExecuteStatement { /** * Actual SQL statement. */ @@ -668,7 +660,7 @@ struct GNUNET_PQ_ExecuteStatement * @return initialized struct */ struct GNUNET_PQ_ExecuteStatement -GNUNET_PQ_make_execute (const char *sql); +GNUNET_PQ_make_execute(const char *sql); /** @@ -679,7 +671,7 @@ GNUNET_PQ_make_execute (const char *sql); * @return initialized struct */ struct GNUNET_PQ_ExecuteStatement -GNUNET_PQ_make_try_execute (const char *sql); +GNUNET_PQ_make_try_execute(const char *sql); /** @@ -692,8 +684,8 @@ GNUNET_PQ_make_try_execute (const char *sql); * #GNUNET_SYSERR on error */ int -GNUNET_PQ_exec_statements (PGconn *connection, - const struct GNUNET_PQ_ExecuteStatement *es); +GNUNET_PQ_exec_statements(PGconn *connection, + const struct GNUNET_PQ_ExecuteStatement *es); /* ******************** pq_connect.c functions ************** */ @@ -708,7 +700,7 @@ GNUNET_PQ_exec_statements (PGconn *connection, * @return NULL on error */ PGconn * -GNUNET_PQ_connect (const char *config_str); +GNUNET_PQ_connect(const char *config_str); /** @@ -720,8 +712,8 @@ GNUNET_PQ_connect (const char *config_str); * @return the postgres handle, NULL on error */ PGconn * -GNUNET_PQ_connect_with_cfg (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section); +GNUNET_PQ_connect_with_cfg(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section); #endif /* GNUNET_PQ_LIB_H_ */ diff --git a/src/include/gnunet_program_lib.h b/src/include/gnunet_program_lib.h index c434c9170..a65a7510d 100644 --- a/src/include/gnunet_program_lib.h +++ b/src/include/gnunet_program_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -75,14 +75,14 @@ typedef void * @return #GNUNET_SYSERR on error, #GNUNET_OK on success */ int -GNUNET_PROGRAM_run2 (int argc, - char *const *argv, - const char *binaryName, - const char *binaryHelp, - const struct GNUNET_GETOPT_CommandLineOption *options, - GNUNET_PROGRAM_Main task, - void *task_cls, - int run_without_scheduler); +GNUNET_PROGRAM_run2(int argc, + char *const *argv, + const char *binaryName, + const char *binaryHelp, + const struct GNUNET_GETOPT_CommandLineOption *options, + GNUNET_PROGRAM_Main task, + void *task_cls, + int run_without_scheduler); /** @@ -99,13 +99,13 @@ GNUNET_PROGRAM_run2 (int argc, * @return #GNUNET_SYSERR on error, #GNUNET_OK on success */ int -GNUNET_PROGRAM_run (int argc, - char *const *argv, - const char *binaryName, - const char *binaryHelp, - const struct GNUNET_GETOPT_CommandLineOption *options, - GNUNET_PROGRAM_Main task, - void *task_cls); +GNUNET_PROGRAM_run(int argc, + char *const *argv, + const char *binaryName, + const char *binaryHelp, + const struct GNUNET_GETOPT_CommandLineOption *options, + GNUNET_PROGRAM_Main task, + void *task_cls); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_protocols.h b/src/include/gnunet_protocols.h index 45bfa4f1b..c932c44d0 100644 --- a/src/include/gnunet_protocols.h +++ b/src/include/gnunet_protocols.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -85,8 +85,8 @@ extern "C" { #define GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE 5 /******************************************************************************* - * AGPL source code download - * *****************************************************************************/ +* AGPL source code download +* *****************************************************************************/ /** * Message to request source code link. @@ -3048,8 +3048,8 @@ extern "C" { /******************************************************* - NEW (TNG) Transport service - ******************************************************* */ + NEW (TNG) Transport service + ******************************************************* */ /** * @brief inform transport to add an address of this peer diff --git a/src/include/gnunet_reclaim_attribute_lib.h b/src/include/gnunet_reclaim_attribute_lib.h index e96937ea8..527a3977e 100644 --- a/src/include/gnunet_reclaim_attribute_lib.h +++ b/src/include/gnunet_reclaim_attribute_lib.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Martin Schanzenbach @@ -54,8 +54,7 @@ extern "C" { /** * An attribute. */ -struct GNUNET_RECLAIM_ATTRIBUTE_Claim -{ +struct GNUNET_RECLAIM_ATTRIBUTE_Claim { /** * ID */ @@ -93,8 +92,7 @@ struct GNUNET_RECLAIM_ATTRIBUTE_Claim /** * A list of GNUNET_RECLAIM_ATTRIBUTE_Claim structures. */ -struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList -{ +struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList { /** * List head */ @@ -107,8 +105,7 @@ struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList }; -struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry -{ +struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry { /** * DLL */ @@ -136,10 +133,10 @@ struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry * @return the new attribute */ struct GNUNET_RECLAIM_ATTRIBUTE_Claim * -GNUNET_RECLAIM_ATTRIBUTE_claim_new (const char *attr_name, - uint32_t type, - const void *data, - size_t data_size); +GNUNET_RECLAIM_ATTRIBUTE_claim_new(const char *attr_name, + uint32_t type, + const void *data, + size_t data_size); /** @@ -149,7 +146,7 @@ GNUNET_RECLAIM_ATTRIBUTE_claim_new (const char *attr_name, * @return the required buffer size */ size_t -GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size ( +GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size( const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs); @@ -159,7 +156,7 @@ GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size ( * @param attrs list to destroy */ void -GNUNET_RECLAIM_ATTRIBUTE_list_destroy ( +GNUNET_RECLAIM_ATTRIBUTE_list_destroy( struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs); @@ -172,7 +169,7 @@ GNUNET_RECLAIM_ATTRIBUTE_list_destroy ( * @param data_size claim payload size */ void -GNUNET_RECLAIM_ATTRIBUTE_list_add ( +GNUNET_RECLAIM_ATTRIBUTE_list_add( struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, const char *attr_name, uint32_t type, @@ -188,7 +185,7 @@ GNUNET_RECLAIM_ATTRIBUTE_list_add ( * @return length of serialized data */ size_t -GNUNET_RECLAIM_ATTRIBUTE_list_serialize ( +GNUNET_RECLAIM_ATTRIBUTE_list_serialize( const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, char *result); @@ -201,7 +198,7 @@ GNUNET_RECLAIM_ATTRIBUTE_list_serialize ( * @return a GNUNET_IDENTITY_PROVIDER_AttributeList, must be free'd by caller */ struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList * -GNUNET_RECLAIM_ATTRIBUTE_list_deserialize (const char *data, size_t data_size); +GNUNET_RECLAIM_ATTRIBUTE_list_deserialize(const char *data, size_t data_size); /** @@ -211,7 +208,7 @@ GNUNET_RECLAIM_ATTRIBUTE_list_deserialize (const char *data, size_t data_size); * @return the required buffer size */ size_t -GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size ( +GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size( const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr); @@ -223,7 +220,7 @@ GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size ( * @return length of serialized data */ size_t -GNUNET_RECLAIM_ATTRIBUTE_serialize ( +GNUNET_RECLAIM_ATTRIBUTE_serialize( const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr, char *result); @@ -237,7 +234,7 @@ GNUNET_RECLAIM_ATTRIBUTE_serialize ( * @return a GNUNET_IDENTITY_PROVIDER_Attribute, must be free'd by caller */ struct GNUNET_RECLAIM_ATTRIBUTE_Claim * -GNUNET_RECLAIM_ATTRIBUTE_deserialize (const char *data, size_t data_size); +GNUNET_RECLAIM_ATTRIBUTE_deserialize(const char *data, size_t data_size); /** @@ -246,7 +243,7 @@ GNUNET_RECLAIM_ATTRIBUTE_deserialize (const char *data, size_t data_size); * @return copied claim list */ struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList * -GNUNET_RECLAIM_ATTRIBUTE_list_dup ( +GNUNET_RECLAIM_ATTRIBUTE_list_dup( const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs); @@ -257,7 +254,7 @@ GNUNET_RECLAIM_ATTRIBUTE_list_dup ( * @return corresponding number, UINT32_MAX on error */ uint32_t -GNUNET_RECLAIM_ATTRIBUTE_typename_to_number (const char *typename); +GNUNET_RECLAIM_ATTRIBUTE_typename_to_number(const char *typename); /** * Convert human-readable version of a 'claim' of an attribute to the binary @@ -270,10 +267,10 @@ GNUNET_RECLAIM_ATTRIBUTE_typename_to_number (const char *typename); * @return #GNUNET_OK on success */ int -GNUNET_RECLAIM_ATTRIBUTE_string_to_value (uint32_t type, - const char *s, - void **data, - size_t *data_size); +GNUNET_RECLAIM_ATTRIBUTE_string_to_value(uint32_t type, + const char *s, + void **data, + size_t *data_size); /** @@ -285,9 +282,9 @@ GNUNET_RECLAIM_ATTRIBUTE_string_to_value (uint32_t type, * @return NULL on error, otherwise human-readable representation of the claim */ char * -GNUNET_RECLAIM_ATTRIBUTE_value_to_string (uint32_t type, - const void *data, - size_t data_size); +GNUNET_RECLAIM_ATTRIBUTE_value_to_string(uint32_t type, + const void *data, + size_t data_size); /** @@ -297,7 +294,7 @@ GNUNET_RECLAIM_ATTRIBUTE_value_to_string (uint32_t type, * @return corresponding typestring, NULL on error */ const char * -GNUNET_RECLAIM_ATTRIBUTE_number_to_typename (uint32_t type); +GNUNET_RECLAIM_ATTRIBUTE_number_to_typename(uint32_t type); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_reclaim_attribute_plugin.h b/src/include/gnunet_reclaim_attribute_plugin.h index c05c80b07..d35916379 100644 --- a/src/include/gnunet_reclaim_attribute_plugin.h +++ b/src/include/gnunet_reclaim_attribute_plugin.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Martin Schanzenbach @@ -108,9 +108,7 @@ typedef const char *(*GNUNET_RECLAIM_ATTRIBUTE_NumberToTypenameFunction) ( * Each plugin is required to return a pointer to a struct of this * type as the return value from its entry point. */ -struct GNUNET_RECLAIM_ATTRIBUTE_PluginFunctions -{ - +struct GNUNET_RECLAIM_ATTRIBUTE_PluginFunctions { /** * Closure for all of the callbacks. */ diff --git a/src/include/gnunet_reclaim_service.h b/src/include/gnunet_reclaim_service.h index 8d7babd7c..9f0a141c9 100644 --- a/src/include/gnunet_reclaim_service.h +++ b/src/include/gnunet_reclaim_service.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Martin Schanzenbach @@ -64,8 +64,7 @@ struct GNUNET_RECLAIM_Operation; * The contents of a ticket must be protected and should be treated as a * shared secret between user and relying party. */ -struct GNUNET_RECLAIM_Ticket -{ +struct GNUNET_RECLAIM_Ticket { /** * The ticket issuer (= the user) */ @@ -92,7 +91,7 @@ struct GNUNET_RECLAIM_Ticket * @param ticket the ticket */ typedef void (*GNUNET_RECLAIM_TicketCallback) ( - void *cls, const struct GNUNET_RECLAIM_Ticket *ticket); + void *cls, const struct GNUNET_RECLAIM_Ticket *ticket); /** @@ -116,8 +115,8 @@ typedef void (*GNUNET_RECLAIM_ContinuationWithStatus) (void *cls, * @param attr The attribute */ typedef void (*GNUNET_RECLAIM_AttributeResult) ( - void *cls, const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, - const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr); + void *cls, const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, + const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr); /** @@ -127,7 +126,7 @@ typedef void (*GNUNET_RECLAIM_AttributeResult) ( * @return handle to communicate with the service */ struct GNUNET_RECLAIM_Handle * -GNUNET_RECLAIM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_RECLAIM_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -143,12 +142,12 @@ GNUNET_RECLAIM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); * @return handle Used to to abort the request */ struct GNUNET_RECLAIM_Operation * -GNUNET_RECLAIM_attribute_store ( - struct GNUNET_RECLAIM_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, - const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr, - const struct GNUNET_TIME_Relative *exp_interval, - GNUNET_RECLAIM_ContinuationWithStatus cont, void *cont_cls); +GNUNET_RECLAIM_attribute_store( + struct GNUNET_RECLAIM_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, + const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr, + const struct GNUNET_TIME_Relative *exp_interval, + GNUNET_RECLAIM_ContinuationWithStatus cont, void *cont_cls); /** @@ -163,11 +162,11 @@ GNUNET_RECLAIM_attribute_store ( * @return handle Used to to abort the request */ struct GNUNET_RECLAIM_Operation * -GNUNET_RECLAIM_attribute_delete ( - struct GNUNET_RECLAIM_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, - const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr, - GNUNET_RECLAIM_ContinuationWithStatus cont, void *cont_cls); +GNUNET_RECLAIM_attribute_delete( + struct GNUNET_RECLAIM_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, + const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr, + GNUNET_RECLAIM_ContinuationWithStatus cont, void *cont_cls); /** @@ -195,12 +194,12 @@ GNUNET_RECLAIM_attribute_delete ( * @return an iterator Handle to use for iteration */ struct GNUNET_RECLAIM_AttributeIterator * -GNUNET_RECLAIM_get_attributes_start ( - struct GNUNET_RECLAIM_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, - GNUNET_SCHEDULER_TaskCallback error_cb, void *error_cb_cls, - GNUNET_RECLAIM_AttributeResult proc, void *proc_cls, - GNUNET_SCHEDULER_TaskCallback finish_cb, void *finish_cb_cls); +GNUNET_RECLAIM_get_attributes_start( + struct GNUNET_RECLAIM_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, + GNUNET_SCHEDULER_TaskCallback error_cb, void *error_cb_cls, + GNUNET_RECLAIM_AttributeResult proc, void *proc_cls, + GNUNET_SCHEDULER_TaskCallback finish_cb, void *finish_cb_cls); /** @@ -210,8 +209,8 @@ GNUNET_RECLAIM_get_attributes_start ( * @param it The iterator */ void -GNUNET_RECLAIM_get_attributes_next ( - struct GNUNET_RECLAIM_AttributeIterator *it); +GNUNET_RECLAIM_get_attributes_next( + struct GNUNET_RECLAIM_AttributeIterator *it); /** @@ -222,8 +221,8 @@ GNUNET_RECLAIM_get_attributes_next ( * @param it the iterator */ void -GNUNET_RECLAIM_get_attributes_stop ( - struct GNUNET_RECLAIM_AttributeIterator *it); +GNUNET_RECLAIM_get_attributes_stop( + struct GNUNET_RECLAIM_AttributeIterator *it); /** @@ -240,12 +239,12 @@ GNUNET_RECLAIM_get_attributes_stop ( * @return handle to abort the operation */ struct GNUNET_RECLAIM_Operation * -GNUNET_RECLAIM_ticket_issue ( - struct GNUNET_RECLAIM_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *iss, - const struct GNUNET_CRYPTO_EcdsaPublicKey *rp, - const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, - GNUNET_RECLAIM_TicketCallback cb, void *cb_cls); +GNUNET_RECLAIM_ticket_issue( + struct GNUNET_RECLAIM_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *iss, + const struct GNUNET_CRYPTO_EcdsaPublicKey *rp, + const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, + GNUNET_RECLAIM_TicketCallback cb, void *cb_cls); /** @@ -262,11 +261,11 @@ GNUNET_RECLAIM_ticket_issue ( * @return handle to abort the operation */ struct GNUNET_RECLAIM_Operation * -GNUNET_RECLAIM_ticket_revoke ( - struct GNUNET_RECLAIM_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, - const struct GNUNET_RECLAIM_Ticket *ticket, - GNUNET_RECLAIM_ContinuationWithStatus cb, void *cb_cls); +GNUNET_RECLAIM_ticket_revoke( + struct GNUNET_RECLAIM_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, + const struct GNUNET_RECLAIM_Ticket *ticket, + GNUNET_RECLAIM_ContinuationWithStatus cb, void *cb_cls); /** @@ -282,11 +281,11 @@ GNUNET_RECLAIM_ticket_revoke ( * @return handle to abort the operation */ struct GNUNET_RECLAIM_Operation * -GNUNET_RECLAIM_ticket_consume ( - struct GNUNET_RECLAIM_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, - const struct GNUNET_RECLAIM_Ticket *ticket, - GNUNET_RECLAIM_AttributeResult cb, void *cb_cls); +GNUNET_RECLAIM_ticket_consume( + struct GNUNET_RECLAIM_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, + const struct GNUNET_RECLAIM_Ticket *ticket, + GNUNET_RECLAIM_AttributeResult cb, void *cb_cls); /** @@ -307,12 +306,12 @@ GNUNET_RECLAIM_ticket_consume ( * @return an iterator handle to use for iteration */ struct GNUNET_RECLAIM_TicketIterator * -GNUNET_RECLAIM_ticket_iteration_start ( - struct GNUNET_RECLAIM_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, - GNUNET_SCHEDULER_TaskCallback error_cb, void *error_cb_cls, - GNUNET_RECLAIM_TicketCallback proc, void *proc_cls, - GNUNET_SCHEDULER_TaskCallback finish_cb, void *finish_cb_cls); +GNUNET_RECLAIM_ticket_iteration_start( + struct GNUNET_RECLAIM_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, + GNUNET_SCHEDULER_TaskCallback error_cb, void *error_cb_cls, + GNUNET_RECLAIM_TicketCallback proc, void *proc_cls, + GNUNET_SCHEDULER_TaskCallback finish_cb, void *finish_cb_cls); /** @@ -322,7 +321,7 @@ GNUNET_RECLAIM_ticket_iteration_start ( * @param it the iterator */ void -GNUNET_RECLAIM_ticket_iteration_next (struct GNUNET_RECLAIM_TicketIterator *it); +GNUNET_RECLAIM_ticket_iteration_next(struct GNUNET_RECLAIM_TicketIterator *it); /** @@ -333,7 +332,7 @@ GNUNET_RECLAIM_ticket_iteration_next (struct GNUNET_RECLAIM_TicketIterator *it); * @param it the iterator */ void -GNUNET_RECLAIM_ticket_iteration_stop (struct GNUNET_RECLAIM_TicketIterator *it); +GNUNET_RECLAIM_ticket_iteration_stop(struct GNUNET_RECLAIM_TicketIterator *it); /** @@ -342,7 +341,7 @@ GNUNET_RECLAIM_ticket_iteration_stop (struct GNUNET_RECLAIM_TicketIterator *it); * @param h identity provider service to disconnect */ void -GNUNET_RECLAIM_disconnect (struct GNUNET_RECLAIM_Handle *h); +GNUNET_RECLAIM_disconnect(struct GNUNET_RECLAIM_Handle *h); /** @@ -354,7 +353,7 @@ GNUNET_RECLAIM_disconnect (struct GNUNET_RECLAIM_Handle *h); * @param op operation to cancel */ void -GNUNET_RECLAIM_cancel (struct GNUNET_RECLAIM_Operation *op); +GNUNET_RECLAIM_cancel(struct GNUNET_RECLAIM_Operation *op); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_regex_service.h b/src/include/gnunet_regex_service.h index 4976adc6a..19cead5d4 100644 --- a/src/include/gnunet_regex_service.h +++ b/src/include/gnunet_regex_service.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Maximilian Szengel * @author Christian Grothoff @@ -77,10 +77,10 @@ struct GNUNET_REGEX_Search; * Must be freed by calling #GNUNET_REGEX_announce_cancel. */ struct GNUNET_REGEX_Announcement * -GNUNET_REGEX_announce (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *regex, - struct GNUNET_TIME_Relative refresh_delay, - uint16_t compression); +GNUNET_REGEX_announce(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *regex, + struct GNUNET_TIME_Relative refresh_delay, + uint16_t compression); /** @@ -89,7 +89,7 @@ GNUNET_REGEX_announce (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param a handle returned by a previous #GNUNET_REGEX_announce call. */ void -GNUNET_REGEX_announce_cancel (struct GNUNET_REGEX_Announcement *a); +GNUNET_REGEX_announce_cancel(struct GNUNET_REGEX_Announcement *a); /** @@ -124,10 +124,10 @@ typedef void * Must be freed by calling #GNUNET_REGEX_search_cancel. */ struct GNUNET_REGEX_Search * -GNUNET_REGEX_search (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *string, - GNUNET_REGEX_Found callback, - void *callback_cls); +GNUNET_REGEX_search(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *string, + GNUNET_REGEX_Found callback, + void *callback_cls); /** @@ -136,7 +136,7 @@ GNUNET_REGEX_search (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param s Handle returned by a previous #GNUNET_REGEX_search call. */ void -GNUNET_REGEX_search_cancel (struct GNUNET_REGEX_Search *s); +GNUNET_REGEX_search_cancel(struct GNUNET_REGEX_Search *s); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_resolver_service.h b/src/include/gnunet_resolver_service.h index 1929feec6..1536a93ca 100644 --- a/src/include/gnunet_resolver_service.h +++ b/src/include/gnunet_resolver_service.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -70,14 +70,14 @@ struct GNUNET_RESOLVER_RequestHandle; * @param cfg configuration to use */ void -GNUNET_RESOLVER_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_RESOLVER_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** * Destroy the connection to the resolver service. */ void -GNUNET_RESOLVER_disconnect (void); +GNUNET_RESOLVER_disconnect(void); /** @@ -91,11 +91,11 @@ GNUNET_RESOLVER_disconnect (void); * @return handle that can be used to cancel the request, NULL on error */ struct GNUNET_RESOLVER_RequestHandle * -GNUNET_RESOLVER_ip_get (const char *hostname, - int af, - struct GNUNET_TIME_Relative timeout, - GNUNET_RESOLVER_AddressCallback callback, - void *callback_cls); +GNUNET_RESOLVER_ip_get(const char *hostname, + int af, + struct GNUNET_TIME_Relative timeout, + GNUNET_RESOLVER_AddressCallback callback, + void *callback_cls); /** @@ -108,10 +108,10 @@ GNUNET_RESOLVER_ip_get (const char *hostname, * @return handle that can be used to cancel the request, NULL on error */ struct GNUNET_RESOLVER_RequestHandle * -GNUNET_RESOLVER_hostname_resolve (int af, - struct GNUNET_TIME_Relative timeout, - GNUNET_RESOLVER_AddressCallback callback, - void *cls); +GNUNET_RESOLVER_hostname_resolve(int af, + struct GNUNET_TIME_Relative timeout, + GNUNET_RESOLVER_AddressCallback callback, + void *cls); /** @@ -131,7 +131,7 @@ typedef void * @return local hostname, caller must free */ char * -GNUNET_RESOLVER_local_fqdn_get (void); +GNUNET_RESOLVER_local_fqdn_get(void); /** @@ -146,12 +146,12 @@ GNUNET_RESOLVER_local_fqdn_get (void); * @return handle that can be used to cancel the request, NULL on error */ struct GNUNET_RESOLVER_RequestHandle * -GNUNET_RESOLVER_hostname_get (const struct sockaddr *sa, - socklen_t salen, - int do_resolve, - struct GNUNET_TIME_Relative timeout, - GNUNET_RESOLVER_HostnameCallback callback, - void *cls); +GNUNET_RESOLVER_hostname_get(const struct sockaddr *sa, + socklen_t salen, + int do_resolve, + struct GNUNET_TIME_Relative timeout, + GNUNET_RESOLVER_HostnameCallback callback, + void *cls); /** @@ -163,7 +163,7 @@ GNUNET_RESOLVER_hostname_get (const struct sockaddr *sa, * @param rh handle of request to cancel */ void -GNUNET_RESOLVER_request_cancel (struct GNUNET_RESOLVER_RequestHandle *rh); +GNUNET_RESOLVER_request_cancel(struct GNUNET_RESOLVER_RequestHandle *rh); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_rest_lib.h b/src/include/gnunet_rest_lib.h index 83741ab95..e70759590 100644 --- a/src/include/gnunet_rest_lib.h +++ b/src/include/gnunet_rest_lib.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -34,10 +34,9 @@ #include "gnunet_util_lib.h" #include -#define GNUNET_REST_HANDLER_END {NULL, NULL, NULL} +#define GNUNET_REST_HANDLER_END { NULL, NULL, NULL } -struct GNUNET_REST_RequestHandle -{ +struct GNUNET_REST_RequestHandle { /** * Map of url parameters */ @@ -69,14 +68,12 @@ struct GNUNET_REST_RequestHandle size_t data_size; }; -struct GNUNET_REST_RequestHandlerError -{ +struct GNUNET_REST_RequestHandlerError { int error_code; char* error_text; }; -struct GNUNET_REST_RequestHandler -{ +struct GNUNET_REST_RequestHandler { /** * Http method to handle */ @@ -93,7 +90,6 @@ struct GNUNET_REST_RequestHandler void (*proc) (struct GNUNET_REST_RequestHandle *handle, const char *url, void *cls); - }; @@ -116,7 +112,7 @@ typedef void (*GNUNET_REST_ResultProcessor) (void *cls, * @return GNUNET_YES if namespace matches */ int -GNUNET_REST_namespace_match (const char *url, const char *namespace); +GNUNET_REST_namespace_match(const char *url, const char *namespace); /** * Create REST MHD response @@ -124,15 +120,15 @@ GNUNET_REST_namespace_match (const char *url, const char *namespace); * @param data result * @return MHD response */ - struct MHD_Response* -GNUNET_REST_create_response (const char *data); +struct MHD_Response* +GNUNET_REST_create_response(const char *data); int -GNUNET_REST_handle_request (struct GNUNET_REST_RequestHandle *conn, - const struct GNUNET_REST_RequestHandler *handlers, - struct GNUNET_REST_RequestHandlerError *err, - void *cls); +GNUNET_REST_handle_request(struct GNUNET_REST_RequestHandle *conn, + const struct GNUNET_REST_RequestHandler *handlers, + struct GNUNET_REST_RequestHandlerError *err, + void *cls); #endif diff --git a/src/include/gnunet_rest_plugin.h b/src/include/gnunet_rest_plugin.h index 54eeb902d..596f9937a 100644 --- a/src/include/gnunet_rest_plugin.h +++ b/src/include/gnunet_rest_plugin.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach * @@ -45,9 +45,7 @@ extern "C" /** * @brief struct returned by the initialization function of the plugin */ -struct GNUNET_REST_Plugin -{ - +struct GNUNET_REST_Plugin { /** * * The closure of the plugin @@ -74,7 +72,6 @@ struct GNUNET_REST_Plugin void (*process_request) (struct GNUNET_REST_RequestHandle *handle, GNUNET_REST_ResultProcessor proc, void *proc_cls); - }; diff --git a/src/include/gnunet_revocation_service.h b/src/include/gnunet_revocation_service.h index 5fb2ed7c5..2acbe89d8 100644 --- a/src/include/gnunet_revocation_service.h +++ b/src/include/gnunet_revocation_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -65,7 +65,7 @@ struct GNUNET_REVOCATION_Query; * */ typedef void (*GNUNET_REVOCATION_Callback) (void *cls, - int is_valid); + int is_valid); /** @@ -78,9 +78,9 @@ typedef void (*GNUNET_REVOCATION_Callback) (void *cls, * @return handle to use in #GNUNET_REVOCATION_query_cancel to stop REVOCATION from invoking the callback */ struct GNUNET_REVOCATION_Query * -GNUNET_REVOCATION_query (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_CRYPTO_EcdsaPublicKey *key, - GNUNET_REVOCATION_Callback func, void *func_cls); +GNUNET_REVOCATION_query(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_CRYPTO_EcdsaPublicKey *key, + GNUNET_REVOCATION_Callback func, void *func_cls); /** @@ -89,7 +89,7 @@ GNUNET_REVOCATION_query (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param q query to cancel */ void -GNUNET_REVOCATION_query_cancel (struct GNUNET_REVOCATION_Query *q); +GNUNET_REVOCATION_query_cancel(struct GNUNET_REVOCATION_Query *q); /** @@ -114,11 +114,11 @@ struct GNUNET_REVOCATION_Handle; * @return handle to use in #GNUNET_REVOCATION_revoke_cancel to stop REVOCATION from invoking the callback */ struct GNUNET_REVOCATION_Handle * -GNUNET_REVOCATION_revoke (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_CRYPTO_EcdsaPublicKey *key, - const struct GNUNET_CRYPTO_EcdsaSignature *sig, - uint64_t pow, - GNUNET_REVOCATION_Callback func, void *func_cls); +GNUNET_REVOCATION_revoke(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_CRYPTO_EcdsaPublicKey *key, + const struct GNUNET_CRYPTO_EcdsaSignature *sig, + uint64_t pow, + GNUNET_REVOCATION_Callback func, void *func_cls); /** @@ -127,7 +127,7 @@ GNUNET_REVOCATION_revoke (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param h operation to cancel */ void -GNUNET_REVOCATION_revoke_cancel (struct GNUNET_REVOCATION_Handle *h); +GNUNET_REVOCATION_revoke_cancel(struct GNUNET_REVOCATION_Handle *h); /** @@ -140,9 +140,9 @@ GNUNET_REVOCATION_revoke_cancel (struct GNUNET_REVOCATION_Handle *h); * @return #GNUNET_YES if the @a pow is acceptable, #GNUNET_NO if not */ int -GNUNET_REVOCATION_check_pow (const struct GNUNET_CRYPTO_EcdsaPublicKey *key, - uint64_t pow, - unsigned int matching_bits); +GNUNET_REVOCATION_check_pow(const struct GNUNET_CRYPTO_EcdsaPublicKey *key, + uint64_t pow, + unsigned int matching_bits); /** @@ -152,8 +152,8 @@ GNUNET_REVOCATION_check_pow (const struct GNUNET_CRYPTO_EcdsaPublicKey *key, * @param sig where to write the revocation signature */ void -GNUNET_REVOCATION_sign_revocation (const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, - struct GNUNET_CRYPTO_EcdsaSignature *sig); +GNUNET_REVOCATION_sign_revocation(const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, + struct GNUNET_CRYPTO_EcdsaSignature *sig); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_rps_service.h b/src/include/gnunet_rps_service.h index b669c55ef..a580d1cc2 100644 --- a/src/include/gnunet_rps_service.h +++ b/src/include/gnunet_rps_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -62,8 +62,8 @@ struct GNUNET_RPS_Request_Handle; * @param peers array with num_peers PeerIDs */ typedef void (* GNUNET_RPS_NotifyReadyCB) (void *cls, - uint64_t num_peers, - const struct GNUNET_PeerIdentity *peers); + uint64_t num_peers, + const struct GNUNET_PeerIdentity *peers); /** @@ -76,9 +76,9 @@ typedef void (* GNUNET_RPS_NotifyReadyCB) (void *cls, * @param num_observed Number of IDs this sampler has observed */ typedef void (* GNUNET_RPS_NotifyReadySingleInfoCB) (void *cls, - const struct GNUNET_PeerIdentity *peer, - double probability, - uint32_t num_observed); + const struct GNUNET_PeerIdentity *peer, + double probability, + uint32_t num_observed); /** @@ -88,7 +88,7 @@ typedef void (* GNUNET_RPS_NotifyReadySingleInfoCB) (void *cls, * @return handle to the rps service */ struct GNUNET_RPS_Handle * -GNUNET_RPS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_RPS_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -98,8 +98,8 @@ GNUNET_RPS_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param shared_value The shared value that defines the members of the sub (-group) */ void -GNUNET_RPS_sub_start (struct GNUNET_RPS_Handle *h, - const char *shared_value); +GNUNET_RPS_sub_start(struct GNUNET_RPS_Handle *h, + const char *shared_value); /** @@ -109,8 +109,8 @@ GNUNET_RPS_sub_start (struct GNUNET_RPS_Handle *h, * @param shared_value The shared value that defines the members of the sub (-group) */ void -GNUNET_RPS_sub_stop (struct GNUNET_RPS_Handle *h, - const char *shared_value); +GNUNET_RPS_sub_stop(struct GNUNET_RPS_Handle *h, + const char *shared_value); /** @@ -128,9 +128,9 @@ GNUNET_RPS_sub_stop (struct GNUNET_RPS_Handle *h, * @return handle to this request */ struct GNUNET_RPS_Request_Handle * -GNUNET_RPS_request_peers (struct GNUNET_RPS_Handle *h, uint32_t n, - GNUNET_RPS_NotifyReadyCB ready_cb, - void *cls); +GNUNET_RPS_request_peers(struct GNUNET_RPS_Handle *h, uint32_t n, + GNUNET_RPS_NotifyReadyCB ready_cb, + void *cls); /** @@ -142,9 +142,9 @@ GNUNET_RPS_request_peers (struct GNUNET_RPS_Handle *h, uint32_t n, * @return a handle to cancel this request */ struct GNUNET_RPS_Request_Handle_Single_Info * -GNUNET_RPS_request_peer_info (struct GNUNET_RPS_Handle *rps_handle, - GNUNET_RPS_NotifyReadySingleInfoCB ready_cb, - void *cls); +GNUNET_RPS_request_peer_info(struct GNUNET_RPS_Handle *rps_handle, + GNUNET_RPS_NotifyReadySingleInfoCB ready_cb, + void *cls); /** @@ -155,8 +155,8 @@ GNUNET_RPS_request_peer_info (struct GNUNET_RPS_Handle *rps_handle, * @param ids the ids of the peers seeded */ void -GNUNET_RPS_seed_ids (struct GNUNET_RPS_Handle *h, uint32_t n, - const struct GNUNET_PeerIdentity * ids); +GNUNET_RPS_seed_ids(struct GNUNET_RPS_Handle *h, uint32_t n, + const struct GNUNET_PeerIdentity * ids); /** * Cancle an issued request. @@ -164,7 +164,7 @@ GNUNET_RPS_seed_ids (struct GNUNET_RPS_Handle *h, uint32_t n, * @param rh handle of the pending request to be canceled */ void -GNUNET_RPS_request_cancel (struct GNUNET_RPS_Request_Handle *rh); +GNUNET_RPS_request_cancel(struct GNUNET_RPS_Request_Handle *rh); /** @@ -173,8 +173,8 @@ GNUNET_RPS_request_cancel (struct GNUNET_RPS_Request_Handle *rh); * @param rhs request handle of request to cancle */ void -GNUNET_RPS_request_single_info_cancel ( - struct GNUNET_RPS_Request_Handle_Single_Info *rhs); +GNUNET_RPS_request_single_info_cancel( + struct GNUNET_RPS_Request_Handle_Single_Info *rhs); #if ENABLE_MALICIOUS @@ -192,12 +192,12 @@ GNUNET_RPS_request_single_info_cancel ( * if @type is 2 the last id is the id of the * peer to be isolated from the rest */ - void -GNUNET_RPS_act_malicious (struct GNUNET_RPS_Handle *h, - uint32_t type, - uint32_t num_peers, - const struct GNUNET_PeerIdentity *ids, - const struct GNUNET_PeerIdentity *target_peer); +void +GNUNET_RPS_act_malicious(struct GNUNET_RPS_Handle *h, + uint32_t type, + uint32_t num_peers, + const struct GNUNET_PeerIdentity *ids, + const struct GNUNET_PeerIdentity *target_peer); #endif /* ENABLE_MALICIOUS */ /* Get internals for debugging/profiling purposes */ @@ -212,10 +212,10 @@ GNUNET_RPS_act_malicious (struct GNUNET_RPS_Handle *h, * @param ready_cb the callback called when the peers are available */ void -GNUNET_RPS_view_request (struct GNUNET_RPS_Handle *rps_handle, - uint32_t num_updates, - GNUNET_RPS_NotifyReadyCB view_update_cb, - void *cls); +GNUNET_RPS_view_request(struct GNUNET_RPS_Handle *rps_handle, + uint32_t num_updates, + GNUNET_RPS_NotifyReadyCB view_update_cb, + void *cls); /** @@ -226,9 +226,9 @@ GNUNET_RPS_view_request (struct GNUNET_RPS_Handle *rps_handle, * @param ready_cb the callback called when the peers are available */ struct GNUNET_RPS_StreamRequestHandle * -GNUNET_RPS_stream_request (struct GNUNET_RPS_Handle *rps_handle, - GNUNET_RPS_NotifyReadyCB stream_input_cb, - void *cls); +GNUNET_RPS_stream_request(struct GNUNET_RPS_Handle *rps_handle, + GNUNET_RPS_NotifyReadyCB stream_input_cb, + void *cls); /** @@ -237,7 +237,7 @@ GNUNET_RPS_stream_request (struct GNUNET_RPS_Handle *rps_handle, * @param srh The request handle to cancel */ void -GNUNET_RPS_stream_cancel (struct GNUNET_RPS_StreamRequestHandle *srh); +GNUNET_RPS_stream_cancel(struct GNUNET_RPS_StreamRequestHandle *srh); /** @@ -245,8 +245,8 @@ GNUNET_RPS_stream_cancel (struct GNUNET_RPS_StreamRequestHandle *srh); * * @param h the handle to the rps service */ - void -GNUNET_RPS_disconnect (struct GNUNET_RPS_Handle *h); +void +GNUNET_RPS_disconnect(struct GNUNET_RPS_Handle *h); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_scalarproduct_service.h b/src/include/gnunet_scalarproduct_service.h index 5d61946bb..512d72260 100644 --- a/src/include/gnunet_scalarproduct_service.h +++ b/src/include/gnunet_scalarproduct_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -49,9 +49,7 @@ extern "C" { /** * Result status values for the computation. */ -enum GNUNET_SCALARPRODUCT_ResponseStatus -{ - +enum GNUNET_SCALARPRODUCT_ResponseStatus { /** * Operation is still active (never returned, used internally). */ @@ -95,8 +93,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * An element key-value pair for scalarproduct */ -struct GNUNET_SCALARPRODUCT_Element -{ +struct GNUNET_SCALARPRODUCT_Element { /** * Key used to identify matching pairs of values to multiply. */ @@ -155,13 +152,13 @@ struct GNUNET_SCALARPRODUCT_ComputationHandle; * @return a new handle for this computation */ struct GNUNET_SCALARPRODUCT_ComputationHandle * -GNUNET_SCALARPRODUCT_start_computation (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_HashCode *session_key, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_SCALARPRODUCT_Element *elements, - uint32_t element_count, - GNUNET_SCALARPRODUCT_DatumProcessor cont, - void *cont_cls); +GNUNET_SCALARPRODUCT_start_computation(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_HashCode *session_key, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_SCALARPRODUCT_Element *elements, + uint32_t element_count, + GNUNET_SCALARPRODUCT_DatumProcessor cont, + void *cont_cls); /** @@ -176,12 +173,12 @@ GNUNET_SCALARPRODUCT_start_computation (const struct GNUNET_CONFIGURATION_Handle * @return a new handle for this computation */ struct GNUNET_SCALARPRODUCT_ComputationHandle * -GNUNET_SCALARPRODUCT_accept_computation (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_HashCode *key, - const struct GNUNET_SCALARPRODUCT_Element *elements, - uint32_t element_count, - GNUNET_SCALARPRODUCT_ContinuationWithStatus cont, - void *cont_cls); +GNUNET_SCALARPRODUCT_accept_computation(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_HashCode *key, + const struct GNUNET_SCALARPRODUCT_Element *elements, + uint32_t element_count, + GNUNET_SCALARPRODUCT_ContinuationWithStatus cont, + void *cont_cls); /** @@ -191,7 +188,7 @@ GNUNET_SCALARPRODUCT_accept_computation (const struct GNUNET_CONFIGURATION_Handl * @param h computation handle to terminate */ void -GNUNET_SCALARPRODUCT_cancel (struct GNUNET_SCALARPRODUCT_ComputationHandle *h); +GNUNET_SCALARPRODUCT_cancel(struct GNUNET_SCALARPRODUCT_ComputationHandle *h); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_scheduler_lib.h b/src/include/gnunet_scheduler_lib.h index 3f0350f54..39b16a1b4 100644 --- a/src/include/gnunet_scheduler_lib.h +++ b/src/include/gnunet_scheduler_lib.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -52,8 +52,7 @@ struct GNUNET_SCHEDULER_Task; * Reasons why the schedule may have triggered * the task now. */ -enum GNUNET_SCHEDULER_Reason -{ +enum GNUNET_SCHEDULER_Reason { /** * This task is not ready. */ @@ -100,9 +99,7 @@ enum GNUNET_SCHEDULER_Reason * Possible events on FDs, used as a bitmask. * Modelled after GPollFD. */ -enum GNUNET_SCHEDULER_EventType -{ - +enum GNUNET_SCHEDULER_EventType { /** * No event (useful for timeout). */ @@ -137,16 +134,13 @@ enum GNUNET_SCHEDULER_EventType * */ GNUNET_SCHEDULER_ET_NVAL = 32 - }; /** * Information about an event relating to a file descriptor/socket. */ -struct GNUNET_SCHEDULER_FdInfo -{ - +struct GNUNET_SCHEDULER_FdInfo { /** * GNUnet network socket the event is about, matches @a sock, * NULL if this is about a file handle or if no network @@ -170,15 +164,13 @@ struct GNUNET_SCHEDULER_FdInfo * Underlying OS handle the event was about. */ int sock; - }; /** * Context information passed to each scheduler task. */ -struct GNUNET_SCHEDULER_TaskContext -{ +struct GNUNET_SCHEDULER_TaskContext { /** * Reason why the task is run now */ @@ -210,7 +202,6 @@ struct GNUNET_SCHEDULER_TaskContext * @deprecated */ const struct GNUNET_NETWORK_FDSet *write_ready; - }; @@ -228,8 +219,8 @@ struct GNUNET_SCHEDULER_TaskContext * @param fdi information about the related FD */ void -GNUNET_SCHEDULER_task_ready (struct GNUNET_SCHEDULER_Task *task, - struct GNUNET_SCHEDULER_FdInfo *fdi); +GNUNET_SCHEDULER_task_ready(struct GNUNET_SCHEDULER_Task *task, + struct GNUNET_SCHEDULER_FdInfo *fdi); /** @@ -241,7 +232,7 @@ struct GNUNET_SCHEDULER_Handle; /** * Function called by external event loop implementations to tell the * scheduler to run some of the tasks that are ready. Must be called - * only after #GNUNET_SCHEDULER_driver_init has been called and before + * only after #GNUNET_SCHEDULER_driver_init has been called and before * #GNUNET_SCHEDULER_driver_done is called. * This function may return even though there are tasks left to run * just to give other tasks a chance as well. If we return #GNUNET_YES, @@ -259,23 +250,21 @@ struct GNUNET_SCHEDULER_Handle; * if we are done running tasks (yield to block) */ int -GNUNET_SCHEDULER_do_work (struct GNUNET_SCHEDULER_Handle *sh); +GNUNET_SCHEDULER_do_work(struct GNUNET_SCHEDULER_Handle *sh); /** * API an external event loop has to implement for * #GNUNET_SCHEDULER_driver_init. */ -struct GNUNET_SCHEDULER_Driver -{ - +struct GNUNET_SCHEDULER_Driver { /** * Closure to pass to the functions in this struct. */ void *cls; /** - * Add a @a task to be run if the conditions specified in the + * Add a @a task to be run if the conditions specified in the * et field of the given @a fdi are satisfied. The et field will * be cleared after this call and the driver is expected to set * the type of the actual event before passing @a fdi to @@ -289,7 +278,7 @@ struct GNUNET_SCHEDULER_Driver */ int (*add)(void *cls, - struct GNUNET_SCHEDULER_Task *task, + struct GNUNET_SCHEDULER_Task *task, struct GNUNET_SCHEDULER_FdInfo *fdi); /** @@ -304,7 +293,7 @@ struct GNUNET_SCHEDULER_Driver */ int (*del)(void *cls, - struct GNUNET_SCHEDULER_Task *task); + struct GNUNET_SCHEDULER_Task *task); /** * Set time at which we definitively want to get a wakeup call. @@ -314,8 +303,7 @@ struct GNUNET_SCHEDULER_Driver */ void (*set_wakeup)(void *cls, - struct GNUNET_TIME_Absolute dt); - + struct GNUNET_TIME_Absolute dt); }; @@ -332,7 +320,7 @@ typedef void * Function called by external event loop implementations to initialize * the scheduler. An external implementation has to provide @a driver * which contains callbacks for the scheduler (see definition of struct - * #GNUNET_SCHEDULER_Driver). The callbacks are used to instruct the + * #GNUNET_SCHEDULER_Driver). The callbacks are used to instruct the * external implementation to watch for events. If it detects any of * those events it is expected to call #GNUNET_SCHEDULER_do_work to let * the scheduler handle it. If an event is related to a specific task @@ -341,11 +329,11 @@ typedef void * before by calling #GNUNET_SCHEDULER_task_ready. * * This function has to be called before any tasks are scheduled and - * before GNUNET_SCHEDULER_do_work is called for the first time. It + * before GNUNET_SCHEDULER_do_work is called for the first time. It * allocates resources that have to be freed again by calling * #GNUNET_SCHEDULER_driver_done. * - * This function installs the same signal handlers as + * This function installs the same signal handlers as * #GNUNET_SCHEDULER_run. This means SIGTERM (and other similar signals) * will induce a call to #GNUNET_SCHEDULER_shutdown during the next * call to #GNUNET_SCHEDULER_do_work. As a result, SIGTERM causes all @@ -360,7 +348,7 @@ typedef void * #GNUNET_SCHEDULER_driver_done */ struct GNUNET_SCHEDULER_Handle * -GNUNET_SCHEDULER_driver_init (const struct GNUNET_SCHEDULER_Driver *driver); +GNUNET_SCHEDULER_driver_init(const struct GNUNET_SCHEDULER_Driver *driver); /** @@ -368,7 +356,7 @@ GNUNET_SCHEDULER_driver_init (const struct GNUNET_SCHEDULER_Driver *driver); * by external event loop implementations after the scheduler has * shut down. This is the case if both of the following conditions * are met: - * + * * - all tasks the scheduler has added through the driver's add * callback have been removed again through the driver's del * callback @@ -378,7 +366,7 @@ GNUNET_SCHEDULER_driver_init (const struct GNUNET_SCHEDULER_Driver *driver); * @param sh the handle returned by #GNUNET_SCHEDULER_driver_init */ void -GNUNET_SCHEDULER_driver_done (struct GNUNET_SCHEDULER_Handle *sh); +GNUNET_SCHEDULER_driver_done(struct GNUNET_SCHEDULER_Handle *sh); /** @@ -387,7 +375,7 @@ GNUNET_SCHEDULER_driver_done (struct GNUNET_SCHEDULER_Handle *sh); * @return NULL on error */ struct GNUNET_SCHEDULER_Driver * -GNUNET_SCHEDULER_driver_select (void); +GNUNET_SCHEDULER_driver_select(void); /** @@ -424,8 +412,8 @@ typedef int * @param task_cls closure of @a task */ void -GNUNET_SCHEDULER_run (GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_run(GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** * Initialize and run scheduler. This function will return when all @@ -439,9 +427,9 @@ GNUNET_SCHEDULER_run (GNUNET_SCHEDULER_TaskCallback task, * @param task_cls closure of @a task */ void -GNUNET_SCHEDULER_run_with_optional_signals (int install_signals, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_run_with_optional_signals(int install_signals, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -451,7 +439,7 @@ GNUNET_SCHEDULER_run_with_optional_signals (int install_signals, * will be delayed until the next shutdown signal. */ void -GNUNET_SCHEDULER_shutdown (void); +GNUNET_SCHEDULER_shutdown(void); /** @@ -466,7 +454,7 @@ GNUNET_SCHEDULER_shutdown (void); * @return number of tasks pending right now */ unsigned int -GNUNET_SCHEDULER_get_load (enum GNUNET_SCHEDULER_Priority p); +GNUNET_SCHEDULER_get_load(enum GNUNET_SCHEDULER_Priority p); /** @@ -476,7 +464,7 @@ GNUNET_SCHEDULER_get_load (enum GNUNET_SCHEDULER_Priority p); * @return task context with information why the current task is run */ const struct GNUNET_SCHEDULER_TaskContext * -GNUNET_SCHEDULER_get_task_context (void); +GNUNET_SCHEDULER_get_task_context(void); /** @@ -492,7 +480,7 @@ GNUNET_SCHEDULER_get_task_context (void); * @return original closure of the task */ void * -GNUNET_SCHEDULER_cancel (struct GNUNET_SCHEDULER_Task *task); +GNUNET_SCHEDULER_cancel(struct GNUNET_SCHEDULER_Task *task); /** @@ -506,10 +494,10 @@ GNUNET_SCHEDULER_cancel (struct GNUNET_SCHEDULER_Task *task); * @param priority priority to use for the task */ void -GNUNET_SCHEDULER_add_with_reason_and_priority (GNUNET_SCHEDULER_TaskCallback task, - void *task_cls, - enum GNUNET_SCHEDULER_Reason reason, - enum GNUNET_SCHEDULER_Priority priority); +GNUNET_SCHEDULER_add_with_reason_and_priority(GNUNET_SCHEDULER_TaskCallback task, + void *task_cls, + enum GNUNET_SCHEDULER_Reason reason, + enum GNUNET_SCHEDULER_Priority priority); /** @@ -522,9 +510,9 @@ GNUNET_SCHEDULER_add_with_reason_and_priority (GNUNET_SCHEDULER_TaskCallback tas * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_with_priority (enum GNUNET_SCHEDULER_Priority prio, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_with_priority(enum GNUNET_SCHEDULER_Priority prio, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -543,8 +531,8 @@ GNUNET_SCHEDULER_add_with_priority (enum GNUNET_SCHEDULER_Priority prio, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_now (GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_now(GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -558,8 +546,8 @@ GNUNET_SCHEDULER_add_now (GNUNET_SCHEDULER_TaskCallback task, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_shutdown (GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_shutdown(GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -577,9 +565,9 @@ GNUNET_SCHEDULER_add_shutdown (GNUNET_SCHEDULER_TaskCallback task, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_now_with_lifeness (int lifeness, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_now_with_lifeness(int lifeness, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -594,9 +582,9 @@ GNUNET_SCHEDULER_add_now_with_lifeness (int lifeness, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_delayed (struct GNUNET_TIME_Relative delay, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_delayed(struct GNUNET_TIME_Relative delay, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -611,9 +599,9 @@ GNUNET_SCHEDULER_add_delayed (struct GNUNET_TIME_Relative delay, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_at (struct GNUNET_TIME_Absolute at, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_at(struct GNUNET_TIME_Absolute at, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -628,10 +616,10 @@ GNUNET_SCHEDULER_add_at (struct GNUNET_TIME_Absolute at, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_delayed_with_priority (struct GNUNET_TIME_Relative delay, - enum GNUNET_SCHEDULER_Priority priority, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_delayed_with_priority(struct GNUNET_TIME_Relative delay, + enum GNUNET_SCHEDULER_Priority priority, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -646,10 +634,10 @@ GNUNET_SCHEDULER_add_delayed_with_priority (struct GNUNET_TIME_Relative delay, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_at_with_priority (struct GNUNET_TIME_Absolute at, - enum GNUNET_SCHEDULER_Priority priority, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_at_with_priority(struct GNUNET_TIME_Absolute at, + enum GNUNET_SCHEDULER_Priority priority, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -673,10 +661,10 @@ GNUNET_SCHEDULER_add_at_with_priority (struct GNUNET_TIME_Absolute at, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_read_net (struct GNUNET_TIME_Relative delay, - struct GNUNET_NETWORK_Handle *rfd, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_read_net(struct GNUNET_TIME_Relative delay, + struct GNUNET_NETWORK_Handle *rfd, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -702,11 +690,11 @@ GNUNET_SCHEDULER_add_read_net (struct GNUNET_TIME_Relative delay, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_read_net_with_priority (struct GNUNET_TIME_Relative delay, - enum GNUNET_SCHEDULER_Priority priority, - struct GNUNET_NETWORK_Handle *rfd, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_read_net_with_priority(struct GNUNET_TIME_Relative delay, + enum GNUNET_SCHEDULER_Priority priority, + struct GNUNET_NETWORK_Handle *rfd, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -731,10 +719,10 @@ GNUNET_SCHEDULER_add_read_net_with_priority (struct GNUNET_TIME_Relative delay, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_write_net (struct GNUNET_TIME_Relative delay, - struct GNUNET_NETWORK_Handle *wfd, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_write_net(struct GNUNET_TIME_Relative delay, + struct GNUNET_NETWORK_Handle *wfd, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -761,13 +749,13 @@ GNUNET_SCHEDULER_add_write_net (struct GNUNET_TIME_Relative delay, * only valid until "task" is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_net_with_priority (struct GNUNET_TIME_Relative delay, - enum GNUNET_SCHEDULER_Priority priority, - struct GNUNET_NETWORK_Handle *fd, - int on_read, - int on_write, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_net_with_priority(struct GNUNET_TIME_Relative delay, + enum GNUNET_SCHEDULER_Priority priority, + struct GNUNET_NETWORK_Handle *fd, + int on_read, + int on_write, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -791,10 +779,10 @@ GNUNET_SCHEDULER_add_net_with_priority (struct GNUNET_TIME_Relative delay, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_read_file (struct GNUNET_TIME_Relative delay, - const struct GNUNET_DISK_FileHandle *rfd, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_read_file(struct GNUNET_TIME_Relative delay, + const struct GNUNET_DISK_FileHandle *rfd, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -818,10 +806,10 @@ GNUNET_SCHEDULER_add_read_file (struct GNUNET_TIME_Relative delay, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_write_file (struct GNUNET_TIME_Relative delay, - const struct GNUNET_DISK_FileHandle *wfd, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_write_file(struct GNUNET_TIME_Relative delay, + const struct GNUNET_DISK_FileHandle *wfd, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -848,12 +836,12 @@ GNUNET_SCHEDULER_add_write_file (struct GNUNET_TIME_Relative delay, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_file_with_priority (struct GNUNET_TIME_Relative delay, - enum GNUNET_SCHEDULER_Priority priority, - const struct GNUNET_DISK_FileHandle *fd, - int on_read, int on_write, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_file_with_priority(struct GNUNET_TIME_Relative delay, + enum GNUNET_SCHEDULER_Priority priority, + const struct GNUNET_DISK_FileHandle *fd, + int on_read, int on_write, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** @@ -888,12 +876,12 @@ GNUNET_SCHEDULER_add_file_with_priority (struct GNUNET_TIME_Relative delay, * only valid until @a task is started! */ struct GNUNET_SCHEDULER_Task * -GNUNET_SCHEDULER_add_select (enum GNUNET_SCHEDULER_Priority prio, - struct GNUNET_TIME_Relative delay, - const struct GNUNET_NETWORK_FDSet *rs, - const struct GNUNET_NETWORK_FDSet *ws, - GNUNET_SCHEDULER_TaskCallback task, - void *task_cls); +GNUNET_SCHEDULER_add_select(enum GNUNET_SCHEDULER_Priority prio, + struct GNUNET_TIME_Relative delay, + const struct GNUNET_NETWORK_FDSet *rs, + const struct GNUNET_NETWORK_FDSet *ws, + GNUNET_SCHEDULER_TaskCallback task, + void *task_cls); /** * Sets the select function to use in the scheduler (scheduler_select). @@ -902,8 +890,8 @@ GNUNET_SCHEDULER_add_select (enum GNUNET_SCHEDULER_Priority prio, * @param new_select_cls closure for @a new_select */ void -GNUNET_SCHEDULER_set_select (GNUNET_SCHEDULER_select new_select, - void *new_select_cls); +GNUNET_SCHEDULER_set_select(GNUNET_SCHEDULER_select new_select, + void *new_select_cls); @@ -920,7 +908,7 @@ GNUNET_SCHEDULER_set_select (GNUNET_SCHEDULER_select new_select, * @param aid the asynchronous scope id to enter */ void -GNUNET_SCHEDULER_begin_async_scope (struct GNUNET_AsyncScopeId *aid); +GNUNET_SCHEDULER_begin_async_scope(struct GNUNET_AsyncScopeId *aid); diff --git a/src/include/gnunet_secretsharing_service.h b/src/include/gnunet_secretsharing_service.h index 69cfa4514..40c98b857 100644 --- a/src/include/gnunet_secretsharing_service.h +++ b/src/include/gnunet_secretsharing_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -60,39 +60,39 @@ extern "C" * The q-parameter for ElGamal encryption, a 1024-bit safe prime. */ #define GNUNET_SECRETSHARING_ELGAMAL_P_HEX \ - "0x08a347d3d69e8b2dd7d1b12a08dfbccbebf4ca" \ - "6f4269a0814e158a34312964d946b3ef22882317" \ - "2bcf30fc08f772774cb404f9bc002a6f66b09a79" \ - "d810d67c4f8cb3bedc6060e3c8ef874b1b64df71" \ - "6c7d2b002da880e269438d5a776e6b5f253c8df5" \ - "6a16b1c7ce58def07c03db48238aadfc52a354a2" \ - "7ed285b0c1675cad3f3" + "0x08a347d3d69e8b2dd7d1b12a08dfbccbebf4ca" \ + "6f4269a0814e158a34312964d946b3ef22882317" \ + "2bcf30fc08f772774cb404f9bc002a6f66b09a79" \ + "d810d67c4f8cb3bedc6060e3c8ef874b1b64df71" \ + "6c7d2b002da880e269438d5a776e6b5f253c8df5" \ + "6a16b1c7ce58def07c03db48238aadfc52a354a2" \ + "7ed285b0c1675cad3f3" /** * The q-parameter for ElGamal encryption, * a 1023-bit Sophie Germain prime, q = (p-1)/2 */ #define GNUNET_SECRETSHARING_ELGAMAL_Q_HEX \ - "0x0451a3e9eb4f4596ebe8d895046fde65f5fa65" \ - "37a134d040a70ac51a1894b26ca359f79144118b" \ - "95e7987e047bb93ba65a027cde001537b3584d3c" \ - "ec086b3e27c659df6e303071e477c3a58db26fb8" \ - "b63e958016d4407134a1c6ad3bb735af929e46fa" \ - "b50b58e3e72c6f783e01eda411c556fe2951aa51" \ - "3f6942d860b3ae569f9" + "0x0451a3e9eb4f4596ebe8d895046fde65f5fa65" \ + "37a134d040a70ac51a1894b26ca359f79144118b" \ + "95e7987e047bb93ba65a027cde001537b3584d3c" \ + "ec086b3e27c659df6e303071e477c3a58db26fb8" \ + "b63e958016d4407134a1c6ad3bb735af929e46fa" \ + "b50b58e3e72c6f783e01eda411c556fe2951aa51" \ + "3f6942d860b3ae569f9" /** * The g-parameter for ElGamal encryption, * a generator of the unique size q subgroup of Z_p^* */ #define GNUNET_SECRETSHARING_ELGAMAL_G_HEX \ - "0x05c00c36d2e822950087ef09d8252994adc4e4" \ - "8fe3ec70269f035b46063aff0c99b633fd64df43" \ - "02442e1914c829a41505a275438871f365e91c12" \ - "3d5303ef9e90f4b8cb89bf86cc9b513e74a72634" \ - "9cfd9f953674fab5d511e1c078fc72d72b34086f" \ - "c82b4b951989eb85325cb203ff98df76bc366bba" \ - "1d7024c3650f60d0da" + "0x05c00c36d2e822950087ef09d8252994adc4e4" \ + "8fe3ec70269f035b46063aff0c99b633fd64df43" \ + "02442e1914c829a41505a275438871f365e91c12" \ + "3d5303ef9e90f4b8cb89bf86cc9b513e74a72634" \ + "9cfd9f953674fab5d511e1c078fc72d72b34086f" \ + "c82b4b951989eb85325cb203ff98df76bc366bba" \ + "1d7024c3650f60d0da" @@ -119,19 +119,17 @@ struct GNUNET_SECRETSHARING_DecryptionHandle; /** * Public key of a group sharing a secret. */ -struct GNUNET_SECRETSHARING_PublicKey -{ - uint32_t bits[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 / sizeof (uint32_t)]; +struct GNUNET_SECRETSHARING_PublicKey { + uint32_t bits[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 / sizeof(uint32_t)]; }; /** * Encrypted field element. */ -struct GNUNET_SECRETSHARING_Ciphertext -{ - uint32_t c1_bits[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 / sizeof (uint32_t)]; - uint32_t c2_bits[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 / sizeof (uint32_t)]; +struct GNUNET_SECRETSHARING_Ciphertext { + uint32_t c1_bits[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 / sizeof(uint32_t)]; + uint32_t c2_bits[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 / sizeof(uint32_t)]; }; @@ -141,12 +139,11 @@ struct GNUNET_SECRETSHARING_Ciphertext * Note that we are not operating in GF(2^n), thus not every * bit pattern is a valid plain text. */ -struct GNUNET_SECRETSHARING_Plaintext -{ +struct GNUNET_SECRETSHARING_Plaintext { /** * Value of the message. */ - uint32_t bits[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 / sizeof (uint32_t)]; + uint32_t bits[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 / sizeof(uint32_t)]; }; @@ -205,15 +202,15 @@ typedef void * @param cls closure for @a cb */ struct GNUNET_SECRETSHARING_Session * -GNUNET_SECRETSHARING_create_session (const struct GNUNET_CONFIGURATION_Handle *cfg, - unsigned int num_peers, - const struct GNUNET_PeerIdentity *peers, - const struct GNUNET_HashCode *session_id, - struct GNUNET_TIME_Absolute start, - struct GNUNET_TIME_Absolute deadline, - unsigned int threshold, - GNUNET_SECRETSHARING_SecretReadyCallback cb, - void *cls); +GNUNET_SECRETSHARING_create_session(const struct GNUNET_CONFIGURATION_Handle *cfg, + unsigned int num_peers, + const struct GNUNET_PeerIdentity *peers, + const struct GNUNET_HashCode *session_id, + struct GNUNET_TIME_Absolute start, + struct GNUNET_TIME_Absolute deadline, + unsigned int threshold, + GNUNET_SECRETSHARING_SecretReadyCallback cb, + void *cls); /** @@ -223,7 +220,7 @@ GNUNET_SECRETSHARING_create_session (const struct GNUNET_CONFIGURATION_Handle *c * @param s session to destroy */ void -GNUNET_SECRETSHARING_session_destroy (struct GNUNET_SECRETSHARING_Session *s); +GNUNET_SECRETSHARING_session_destroy(struct GNUNET_SECRETSHARING_Session *s); /** @@ -240,9 +237,9 @@ GNUNET_SECRETSHARING_session_destroy (struct GNUNET_SECRETSHARING_Session *s); * @return #GNUNET_YES on succes, #GNUNET_SYSERR if the message is invalid (invalid range) */ int -GNUNET_SECRETSHARING_encrypt (const struct GNUNET_SECRETSHARING_PublicKey *public_key, - const struct GNUNET_SECRETSHARING_Plaintext *plaintext, - struct GNUNET_SECRETSHARING_Ciphertext *result_ciphertext); +GNUNET_SECRETSHARING_encrypt(const struct GNUNET_SECRETSHARING_PublicKey *public_key, + const struct GNUNET_SECRETSHARING_Plaintext *plaintext, + struct GNUNET_SECRETSHARING_Ciphertext *result_ciphertext); /** @@ -262,13 +259,13 @@ GNUNET_SECRETSHARING_encrypt (const struct GNUNET_SECRETSHARING_PublicKey *publi * @return handle to cancel the operation */ struct GNUNET_SECRETSHARING_DecryptionHandle * -GNUNET_SECRETSHARING_decrypt (const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_SECRETSHARING_Share *share, - const struct GNUNET_SECRETSHARING_Ciphertext *ciphertext, - struct GNUNET_TIME_Absolute start, - struct GNUNET_TIME_Absolute deadline, - GNUNET_SECRETSHARING_DecryptCallback decrypt_cb, - void *decrypt_cb_cls); +GNUNET_SECRETSHARING_decrypt(const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_SECRETSHARING_Share *share, + const struct GNUNET_SECRETSHARING_Ciphertext *ciphertext, + struct GNUNET_TIME_Absolute start, + struct GNUNET_TIME_Absolute deadline, + GNUNET_SECRETSHARING_DecryptCallback decrypt_cb, + void *decrypt_cb_cls); /** @@ -280,7 +277,7 @@ GNUNET_SECRETSHARING_decrypt (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param dh to cancel */ void -GNUNET_SECRETSHARING_decrypt_cancel (struct GNUNET_SECRETSHARING_DecryptionHandle *dh); +GNUNET_SECRETSHARING_decrypt_cancel(struct GNUNET_SECRETSHARING_DecryptionHandle *dh); /** @@ -293,7 +290,7 @@ GNUNET_SECRETSHARING_decrypt_cancel (struct GNUNET_SECRETSHARING_DecryptionHandl * @return The share, or NULL on error. */ struct GNUNET_SECRETSHARING_Share * -GNUNET_SECRETSHARING_share_read (const void *data, size_t len, size_t *readlen); +GNUNET_SECRETSHARING_share_read(const void *data, size_t len, size_t *readlen); /** @@ -308,21 +305,21 @@ GNUNET_SECRETSHARING_share_read (const void *data, size_t len, size_t *readlen); * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure. */ int -GNUNET_SECRETSHARING_share_write (const struct GNUNET_SECRETSHARING_Share *share, - void *buf, size_t buflen, size_t *writelen); +GNUNET_SECRETSHARING_share_write(const struct GNUNET_SECRETSHARING_Share *share, + void *buf, size_t buflen, size_t *writelen); void -GNUNET_SECRETSHARING_share_destroy (struct GNUNET_SECRETSHARING_Share *share); +GNUNET_SECRETSHARING_share_destroy(struct GNUNET_SECRETSHARING_Share *share); int -GNUNET_SECRETSHARING_plaintext_generate (struct GNUNET_SECRETSHARING_Plaintext *plaintext, - gcry_mpi_t exponent); +GNUNET_SECRETSHARING_plaintext_generate(struct GNUNET_SECRETSHARING_Plaintext *plaintext, + gcry_mpi_t exponent); int -GNUNET_SECRETSHARING_plaintext_generate_i (struct GNUNET_SECRETSHARING_Plaintext *plaintext, - int64_t exponent); +GNUNET_SECRETSHARING_plaintext_generate_i(struct GNUNET_SECRETSHARING_Plaintext *plaintext, + int64_t exponent); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_service_lib.h b/src/include/gnunet_service_lib.h index fce912277..9cdf4d459 100644 --- a/src/include/gnunet_service_lib.h +++ b/src/include/gnunet_service_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -50,8 +50,7 @@ extern "C" /** * Options for the service (bitmask). */ -enum GNUNET_SERVICE_Options -{ +enum GNUNET_SERVICE_Options { /** * Use defaults. Terminates all client connections and the listen * sockets immediately upon receiving the shutdown signal. @@ -165,12 +164,12 @@ typedef void * @return NULL on error */ struct GNUNET_SERVICE_Handle * -GNUNET_SERVICE_start (const char *service_name, - const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_SERVICE_ConnectHandler connect_cb, - GNUNET_SERVICE_DisconnectHandler disconnect_cb, - void *cls, - const struct GNUNET_MQ_MessageHandler *handlers); +GNUNET_SERVICE_start(const char *service_name, + const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_SERVICE_ConnectHandler connect_cb, + GNUNET_SERVICE_DisconnectHandler disconnect_cb, + void *cls, + const struct GNUNET_MQ_MessageHandler *handlers); /** @@ -179,7 +178,7 @@ GNUNET_SERVICE_start (const char *service_name, * @param srv service to stop */ void -GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Handle *srv); +GNUNET_SERVICE_stop(struct GNUNET_SERVICE_Handle *srv); /** @@ -224,15 +223,15 @@ GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Handle *srv); * @return 0 on success, non-zero on error */ int -GNUNET_SERVICE_run_ (int argc, - char *const *argv, - const char *service_name, - enum GNUNET_SERVICE_Options options, - GNUNET_SERVICE_InitCallback service_init_cb, - GNUNET_SERVICE_ConnectHandler connect_cb, - GNUNET_SERVICE_DisconnectHandler disconnect_cb, - void *cls, - const struct GNUNET_MQ_MessageHandler *handlers); +GNUNET_SERVICE_run_(int argc, + char *const *argv, + const char *service_name, + enum GNUNET_SERVICE_Options options, + GNUNET_SERVICE_InitCallback service_init_cb, + GNUNET_SERVICE_ConnectHandler connect_cb, + GNUNET_SERVICE_DisconnectHandler disconnect_cb, + void *cls, + const struct GNUNET_MQ_MessageHandler *handlers); /** @@ -286,29 +285,29 @@ GNUNET_SERVICE_run_ (int argc, * &disconnect_cb, * closure_for_cb, * GNUNET_MQ_hd_var_size (get, - * GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST, - * struct GNUNET_RESOLVER_GetMessage, + * GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST, + * struct GNUNET_RESOLVER_GetMessage, * NULL), * GNUNET_MQ_handler_end ()); * */ -#define GNUNET_SERVICE_MAIN(service_name,service_options,init_cb,connect_cb,disconnect_cb,cls,...) \ +#define GNUNET_SERVICE_MAIN(service_name, service_options, init_cb, connect_cb, disconnect_cb, cls, ...) \ int \ - main (int argc,\ - char *const *argv)\ + main(int argc, \ + char *const *argv) \ { \ struct GNUNET_MQ_MessageHandler mh[] = { \ __VA_ARGS__ \ - }; \ - return GNUNET_SERVICE_run_ (argc, \ - argv, \ - service_name, \ - service_options, \ - init_cb, \ - connect_cb, \ - disconnect_cb, \ - cls, \ - mh); \ + }; \ + return GNUNET_SERVICE_run_(argc, \ + argv, \ + service_name, \ + service_options, \ + init_cb, \ + connect_cb, \ + disconnect_cb, \ + cls, \ + mh); \ } @@ -319,7 +318,7 @@ GNUNET_SERVICE_run_ (int argc, * @param sh service to stop accepting connections. */ void -GNUNET_SERVICE_suspend (struct GNUNET_SERVICE_Handle *sh); +GNUNET_SERVICE_suspend(struct GNUNET_SERVICE_Handle *sh); /** @@ -328,7 +327,7 @@ GNUNET_SERVICE_suspend (struct GNUNET_SERVICE_Handle *sh); * @param sh service to resume accepting connections. */ void -GNUNET_SERVICE_resume (struct GNUNET_SERVICE_Handle *sh); +GNUNET_SERVICE_resume(struct GNUNET_SERVICE_Handle *sh); /** @@ -338,7 +337,7 @@ GNUNET_SERVICE_resume (struct GNUNET_SERVICE_Handle *sh); * @param c the client to continue receiving from */ void -GNUNET_SERVICE_client_continue (struct GNUNET_SERVICE_Client *c); +GNUNET_SERVICE_client_continue(struct GNUNET_SERVICE_Client *c); /** @@ -348,7 +347,7 @@ GNUNET_SERVICE_client_continue (struct GNUNET_SERVICE_Client *c); * @return the message queue of @a c */ struct GNUNET_MQ_Handle * -GNUNET_SERVICE_client_get_mq (struct GNUNET_SERVICE_Client *c); +GNUNET_SERVICE_client_get_mq(struct GNUNET_SERVICE_Client *c); /** @@ -360,7 +359,7 @@ GNUNET_SERVICE_client_get_mq (struct GNUNET_SERVICE_Client *c); * @param c client for which to disable the warning */ void -GNUNET_SERVICE_client_disable_continue_warning (struct GNUNET_SERVICE_Client *c); +GNUNET_SERVICE_client_disable_continue_warning(struct GNUNET_SERVICE_Client *c); /** @@ -379,7 +378,7 @@ GNUNET_SERVICE_client_disable_continue_warning (struct GNUNET_SERVICE_Client *c) * @param c client to disconnect now */ void -GNUNET_SERVICE_client_drop (struct GNUNET_SERVICE_Client *c); +GNUNET_SERVICE_client_drop(struct GNUNET_SERVICE_Client *c); /** @@ -388,7 +387,7 @@ GNUNET_SERVICE_client_drop (struct GNUNET_SERVICE_Client *c); * @param sh server to shutdown */ void -GNUNET_SERVICE_shutdown (struct GNUNET_SERVICE_Handle *sh); +GNUNET_SERVICE_shutdown(struct GNUNET_SERVICE_Handle *sh); /** @@ -404,7 +403,7 @@ GNUNET_SERVICE_shutdown (struct GNUNET_SERVICE_Handle *sh); * @param c client to mark as a monitor */ void -GNUNET_SERVICE_client_mark_monitor (struct GNUNET_SERVICE_Client *c); +GNUNET_SERVICE_client_mark_monitor(struct GNUNET_SERVICE_Client *c); /** @@ -415,7 +414,7 @@ GNUNET_SERVICE_client_mark_monitor (struct GNUNET_SERVICE_Client *c); * @param c client to persist the socket (never to be closed) */ void -GNUNET_SERVICE_client_persist (struct GNUNET_SERVICE_Client *c); +GNUNET_SERVICE_client_persist(struct GNUNET_SERVICE_Client *c); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_set_service.h b/src/include/gnunet_set_service.h index ac54153e1..4016fc362 100644 --- a/src/include/gnunet_set_service.h +++ b/src/include/gnunet_set_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -52,7 +52,7 @@ extern "C" /** * Maximum size of a context message for set operation requests. */ -#define GNUNET_SET_CONTEXT_MESSAGE_MAX_SIZE ((1<<16) - 1024) +#define GNUNET_SET_CONTEXT_MESSAGE_MAX_SIZE ((1 << 16) - 1024) /** @@ -79,8 +79,7 @@ struct GNUNET_SET_OperationHandle; /** * The operation that a set set supports. */ -enum GNUNET_SET_OperationType -{ +enum GNUNET_SET_OperationType { /** * A purely local set that does not support any operation. */ @@ -101,8 +100,7 @@ enum GNUNET_SET_OperationType /** * Status for the result callback */ -enum GNUNET_SET_Status -{ +enum GNUNET_SET_Status { /** * Everything went ok, we are transmitting an element of the * result (in set, or to be removed from set, depending on @@ -157,8 +155,7 @@ enum GNUNET_SET_Status /** * The way results are given to the client. */ -enum GNUNET_SET_ResultMode -{ +enum GNUNET_SET_ResultMode { /** * Client gets every element in the resulting set. * @@ -193,8 +190,7 @@ enum GNUNET_SET_ResultMode /** * Element stored in a set. */ -struct GNUNET_SET_Element -{ +struct GNUNET_SET_Element { /** * Number of bytes in the buffer pointed to by data. */ @@ -217,8 +213,7 @@ struct GNUNET_SET_Element * * Used as tag for struct #GNUNET_SET_Option. */ -enum GNUNET_SET_OptionType -{ +enum GNUNET_SET_OptionType { /** * List terminator. */ @@ -248,8 +243,7 @@ enum GNUNET_SET_OptionType /** * Option for set operations. */ -struct GNUNET_SET_Option -{ +struct GNUNET_SET_Option { /** * Type of the option. */ @@ -341,8 +335,8 @@ typedef void * @return a handle to the set */ struct GNUNET_SET_Handle * -GNUNET_SET_create (const struct GNUNET_CONFIGURATION_Handle *cfg, - enum GNUNET_SET_OperationType op); +GNUNET_SET_create(const struct GNUNET_CONFIGURATION_Handle *cfg, + enum GNUNET_SET_OperationType op); /** @@ -359,10 +353,10 @@ GNUNET_SET_create (const struct GNUNET_CONFIGURATION_Handle *cfg, * set is invalid (e.g. the set service crashed) */ int -GNUNET_SET_add_element (struct GNUNET_SET_Handle *set, - const struct GNUNET_SET_Element *element, - GNUNET_SET_Continuation cont, - void *cont_cls); +GNUNET_SET_add_element(struct GNUNET_SET_Handle *set, + const struct GNUNET_SET_Element *element, + GNUNET_SET_Continuation cont, + void *cont_cls); /** @@ -379,16 +373,16 @@ GNUNET_SET_add_element (struct GNUNET_SET_Handle *set, * set is invalid (e.g. the set service crashed) */ int -GNUNET_SET_remove_element (struct GNUNET_SET_Handle *set, - const struct GNUNET_SET_Element *element, - GNUNET_SET_Continuation cont, - void *cont_cls); +GNUNET_SET_remove_element(struct GNUNET_SET_Handle *set, + const struct GNUNET_SET_Element *element, + GNUNET_SET_Continuation cont, + void *cont_cls); void -GNUNET_SET_copy_lazy (struct GNUNET_SET_Handle *set, - GNUNET_SET_CopyReadyCallback cb, - void *cls); +GNUNET_SET_copy_lazy(struct GNUNET_SET_Handle *set, + GNUNET_SET_CopyReadyCallback cb, + void *cls); /** @@ -400,7 +394,7 @@ GNUNET_SET_copy_lazy (struct GNUNET_SET_Handle *set, * @param set set to destroy */ void -GNUNET_SET_destroy (struct GNUNET_SET_Handle *set); +GNUNET_SET_destroy(struct GNUNET_SET_Handle *set); /** @@ -418,13 +412,13 @@ GNUNET_SET_destroy (struct GNUNET_SET_Handle *set); * @return a handle to cancel the operation */ struct GNUNET_SET_OperationHandle * -GNUNET_SET_prepare (const struct GNUNET_PeerIdentity *other_peer, - const struct GNUNET_HashCode *app_id, - const struct GNUNET_MessageHeader *context_msg, - enum GNUNET_SET_ResultMode result_mode, - struct GNUNET_SET_Option options[], - GNUNET_SET_ResultIterator result_cb, - void *result_cls); +GNUNET_SET_prepare(const struct GNUNET_PeerIdentity *other_peer, + const struct GNUNET_HashCode *app_id, + const struct GNUNET_MessageHeader *context_msg, + enum GNUNET_SET_ResultMode result_mode, + struct GNUNET_SET_Option options[], + GNUNET_SET_ResultIterator result_cb, + void *result_cls); /** @@ -442,11 +436,11 @@ GNUNET_SET_prepare (const struct GNUNET_PeerIdentity *other_peer, * @return a handle that can be used to cancel the listen operation */ struct GNUNET_SET_ListenHandle * -GNUNET_SET_listen (const struct GNUNET_CONFIGURATION_Handle *cfg, - enum GNUNET_SET_OperationType op_type, - const struct GNUNET_HashCode *app_id, - GNUNET_SET_ListenCallback listen_cb, - void *listen_cls); +GNUNET_SET_listen(const struct GNUNET_CONFIGURATION_Handle *cfg, + enum GNUNET_SET_OperationType op_type, + const struct GNUNET_HashCode *app_id, + GNUNET_SET_ListenCallback listen_cb, + void *listen_cls); /** @@ -458,7 +452,7 @@ GNUNET_SET_listen (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param lh handle for the listen operation */ void -GNUNET_SET_listen_cancel (struct GNUNET_SET_ListenHandle *lh); +GNUNET_SET_listen_cancel(struct GNUNET_SET_ListenHandle *lh); /** @@ -476,11 +470,11 @@ GNUNET_SET_listen_cancel (struct GNUNET_SET_ListenHandle *lh); * @return a handle to cancel the operation */ struct GNUNET_SET_OperationHandle * -GNUNET_SET_accept (struct GNUNET_SET_Request *request, - enum GNUNET_SET_ResultMode result_mode, - struct GNUNET_SET_Option options[], - GNUNET_SET_ResultIterator result_cb, - void *result_cls); +GNUNET_SET_accept(struct GNUNET_SET_Request *request, + enum GNUNET_SET_ResultMode result_mode, + struct GNUNET_SET_Option options[], + GNUNET_SET_ResultIterator result_cb, + void *result_cls); /** @@ -497,8 +491,8 @@ GNUNET_SET_accept (struct GNUNET_SET_Request *request, * set is invalid (e.g. the set service crashed) */ int -GNUNET_SET_commit (struct GNUNET_SET_OperationHandle *oh, - struct GNUNET_SET_Handle *set); +GNUNET_SET_commit(struct GNUNET_SET_OperationHandle *oh, + struct GNUNET_SET_Handle *set); /** @@ -509,7 +503,7 @@ GNUNET_SET_commit (struct GNUNET_SET_OperationHandle *oh, * @param oh set operation to cancel */ void -GNUNET_SET_operation_cancel (struct GNUNET_SET_OperationHandle *oh); +GNUNET_SET_operation_cancel(struct GNUNET_SET_OperationHandle *oh); /** @@ -526,9 +520,9 @@ GNUNET_SET_operation_cancel (struct GNUNET_SET_OperationHandle *oh); * #GNUNET_SYSERR if the set is invalid (e.g. the server crashed, disconnected) */ int -GNUNET_SET_iterate (struct GNUNET_SET_Handle *set, - GNUNET_SET_ElementIterator iter, - void *iter_cls); +GNUNET_SET_iterate(struct GNUNET_SET_Handle *set, + GNUNET_SET_ElementIterator iter, + void *iter_cls); /** @@ -539,7 +533,7 @@ GNUNET_SET_iterate (struct GNUNET_SET_Handle *set, * @param set the set to stop iterating over */ void -GNUNET_SET_iterate_cancel (struct GNUNET_SET_Handle *set); +GNUNET_SET_iterate_cancel(struct GNUNET_SET_Handle *set); /** @@ -550,7 +544,7 @@ GNUNET_SET_iterate_cancel (struct GNUNET_SET_Handle *set); * @return the copied element */ struct GNUNET_SET_Element * -GNUNET_SET_element_dup (const struct GNUNET_SET_Element *element); +GNUNET_SET_element_dup(const struct GNUNET_SET_Element *element); /** @@ -561,8 +555,8 @@ GNUNET_SET_element_dup (const struct GNUNET_SET_Element *element); * should be stored */ void -GNUNET_SET_element_hash (const struct GNUNET_SET_Element *element, - struct GNUNET_HashCode *ret_hash); +GNUNET_SET_element_hash(const struct GNUNET_SET_Element *element, + struct GNUNET_HashCode *ret_hash); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_signal_lib.h b/src/include/gnunet_signal_lib.h index 167da160a..5d6e861a9 100644 --- a/src/include/gnunet_signal_lib.h +++ b/src/include/gnunet_signal_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -68,8 +68,8 @@ typedef void * @return context that can be used to restore, NULL on error */ struct GNUNET_SIGNAL_Context * -GNUNET_SIGNAL_handler_install (int signal, - GNUNET_SIGNAL_Handler handler); +GNUNET_SIGNAL_handler_install(int signal, + GNUNET_SIGNAL_Handler handler); /** @@ -79,7 +79,7 @@ GNUNET_SIGNAL_handler_install (int signal, * signal handler was installed */ void -GNUNET_SIGNAL_handler_uninstall (struct GNUNET_SIGNAL_Context *ctx); +GNUNET_SIGNAL_handler_uninstall(struct GNUNET_SIGNAL_Context *ctx); /** @@ -90,7 +90,7 @@ GNUNET_SIGNAL_handler_uninstall (struct GNUNET_SIGNAL_Context *ctx); * @param sig the signal to raise */ void -GNUNET_SIGNAL_raise (const int sig); +GNUNET_SIGNAL_raise(const int sig); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_signatures.h b/src/include/gnunet_signatures.h index 30a4bb761..6801c641e 100644 --- a/src/include/gnunet_signatures.h +++ b/src/include/gnunet_signatures.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff diff --git a/src/include/gnunet_socks.h b/src/include/gnunet_socks.h index b82fc2afb..68a4677dd 100644 --- a/src/include/gnunet_socks.h +++ b/src/include/gnunet_socks.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Jeffrey Burdges @@ -52,8 +52,8 @@ extern "C" * @return GNUNET_YES if so, GNUNET_NO if not */ int -GNUNET_SOCKS_check_service (const char *service_name, - const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_SOCKS_check_service(const char *service_name, + const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -65,8 +65,8 @@ GNUNET_SOCKS_check_service (const char *service_name, * NULL if SOCKS not configured or not configured properly */ struct GNUNET_CONNECTION_Handle * -GNUNET_SOCKS_do_connect (const char *service_name, - const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_SOCKS_do_connect(const char *service_name, + const struct GNUNET_CONFIGURATION_Handle *cfg); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_speaker_lib.h b/src/include/gnunet_speaker_lib.h index 71f643791..261ea5981 100644 --- a/src/include/gnunet_speaker_lib.h +++ b/src/include/gnunet_speaker_lib.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet - Copyright (C) 2013 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet + Copyright (C) 2013 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -36,7 +36,7 @@ #ifdef __cplusplus extern "C" { -#if 0 /* keep Emacsens' auto-indent happy */ +#if 0 /* keep Emacsens' auto-indent happy */ } #endif #endif @@ -74,16 +74,14 @@ typedef void (*GNUNET_SPEAKER_DestroyCallback)(void *cls); * opaque to the API but should be OPUS. */ typedef void (*GNUNET_SPEAKER_PlayCallback)(void *cls, - size_t data_size, - const void *data); + size_t data_size, + const void *data); /** * A speaker is a device that can play or record audio data. */ -struct GNUNET_SPEAKER_Handle -{ - +struct GNUNET_SPEAKER_Handle { /** * Turn on the speaker. */ @@ -108,7 +106,6 @@ struct GNUNET_SPEAKER_Handle * Closure for the callbacks. */ void *cls; - }; @@ -120,7 +117,7 @@ struct GNUNET_SPEAKER_Handle * @return NULL on error */ struct GNUNET_SPEAKER_Handle * -GNUNET_SPEAKER_create_from_hardware (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_SPEAKER_create_from_hardware(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -129,10 +126,10 @@ GNUNET_SPEAKER_create_from_hardware (const struct GNUNET_CONFIGURATION_Handle *c * @param speaker speaker to destroy */ void -GNUNET_SPEAKER_destroy (struct GNUNET_SPEAKER_Handle *speaker); +GNUNET_SPEAKER_destroy(struct GNUNET_SPEAKER_Handle *speaker); -#if 0 /* keep Emacsens' auto-indent happy */ +#if 0 /* keep Emacsens' auto-indent happy */ { #endif #ifdef __cplusplus diff --git a/src/include/gnunet_sq_lib.h b/src/include/gnunet_sq_lib.h index ebc79d098..31ac0675c 100644 --- a/src/include/gnunet_sq_lib.h +++ b/src/include/gnunet_sq_lib.h @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2017 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet + Copyright (C) 2017 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file include/gnunet_sq_lib.h * @brief helper functions for Sqlite3 DB interactions @@ -42,18 +42,16 @@ */ typedef int (*GNUNET_SQ_QueryConverter)(void *cls, - const void *data, - size_t data_len, - sqlite3_stmt *stmt, + const void *data, + size_t data_len, + sqlite3_stmt *stmt, unsigned int off); /** * @brief Description of a DB query parameter. */ -struct GNUNET_SQ_QueryParam -{ - +struct GNUNET_SQ_QueryParam { /** * Function for how to handle this type of entry. */ @@ -95,8 +93,8 @@ struct GNUNET_SQ_QueryParam * @oaran ptr_size number of bytes in @a ptr */ struct GNUNET_SQ_QueryParam -GNUNET_SQ_query_param_fixed_size (const void *ptr, - size_t ptr_size); +GNUNET_SQ_query_param_fixed_size(const void *ptr, + size_t ptr_size); @@ -106,7 +104,7 @@ GNUNET_SQ_query_param_fixed_size (const void *ptr, * @param ptr pointer to the string query parameter to pass */ struct GNUNET_SQ_QueryParam -GNUNET_SQ_query_param_string (const char *ptr); +GNUNET_SQ_query_param_string(const char *ptr); /** @@ -115,7 +113,7 @@ GNUNET_SQ_query_param_string (const char *ptr); * * @param x pointer to the query parameter to pass. */ -#define GNUNET_SQ_query_param_auto_from_type(x) GNUNET_SQ_query_param_fixed_size ((x), sizeof (*(x))) +#define GNUNET_SQ_query_param_auto_from_type(x) GNUNET_SQ_query_param_fixed_size((x), sizeof(*(x))) /** @@ -125,7 +123,7 @@ GNUNET_SQ_query_param_string (const char *ptr); * @param x the query parameter to pass. */ struct GNUNET_SQ_QueryParam -GNUNET_SQ_query_param_rsa_public_key (const struct GNUNET_CRYPTO_RsaPublicKey *x); +GNUNET_SQ_query_param_rsa_public_key(const struct GNUNET_CRYPTO_RsaPublicKey *x); /** @@ -135,7 +133,7 @@ GNUNET_SQ_query_param_rsa_public_key (const struct GNUNET_CRYPTO_RsaPublicKey *x * @param x the query parameter to pass */ struct GNUNET_SQ_QueryParam -GNUNET_SQ_query_param_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *x); +GNUNET_SQ_query_param_rsa_signature(const struct GNUNET_CRYPTO_RsaSignature *x); /** @@ -145,7 +143,7 @@ GNUNET_SQ_query_param_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *x) * @param x pointer to the query parameter to pass */ struct GNUNET_SQ_QueryParam -GNUNET_SQ_query_param_absolute_time (const struct GNUNET_TIME_Absolute *x); +GNUNET_SQ_query_param_absolute_time(const struct GNUNET_TIME_Absolute *x); /** @@ -155,7 +153,7 @@ GNUNET_SQ_query_param_absolute_time (const struct GNUNET_TIME_Absolute *x); * @param x pointer to the query parameter to pass */ struct GNUNET_SQ_QueryParam -GNUNET_SQ_query_param_absolute_time_nbo (const struct GNUNET_TIME_AbsoluteNBO *x); +GNUNET_SQ_query_param_absolute_time_nbo(const struct GNUNET_TIME_AbsoluteNBO *x); /** @@ -164,7 +162,7 @@ GNUNET_SQ_query_param_absolute_time_nbo (const struct GNUNET_TIME_AbsoluteNBO *x * @param x pointer to the query parameter to pass */ struct GNUNET_SQ_QueryParam -GNUNET_SQ_query_param_uint16 (const uint16_t *x); +GNUNET_SQ_query_param_uint16(const uint16_t *x); /** @@ -173,7 +171,7 @@ GNUNET_SQ_query_param_uint16 (const uint16_t *x); * @param x pointer to the query parameter to pass */ struct GNUNET_SQ_QueryParam -GNUNET_SQ_query_param_uint32 (const uint32_t *x); +GNUNET_SQ_query_param_uint32(const uint32_t *x); /** @@ -182,7 +180,7 @@ GNUNET_SQ_query_param_uint32 (const uint32_t *x); * @param x pointer to the query parameter to pass */ struct GNUNET_SQ_QueryParam -GNUNET_SQ_query_param_uint64 (const uint64_t *x); +GNUNET_SQ_query_param_uint64(const uint64_t *x); /** @@ -193,8 +191,8 @@ GNUNET_SQ_query_param_uint64 (const uint64_t *x); * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_SQ_bind (sqlite3_stmt *stmt, - const struct GNUNET_SQ_QueryParam *params); +GNUNET_SQ_bind(sqlite3_stmt *stmt, + const struct GNUNET_SQ_QueryParam *params); /** @@ -204,8 +202,8 @@ GNUNET_SQ_bind (sqlite3_stmt *stmt, * @param stmt statement to reset */ void -GNUNET_SQ_reset (sqlite3 *dbh, - sqlite3_stmt *stmt); +GNUNET_SQ_reset(sqlite3 *dbh, + sqlite3_stmt *stmt); /** @@ -222,10 +220,10 @@ GNUNET_SQ_reset (sqlite3 *dbh, */ typedef int (*GNUNET_SQ_ResultConverter)(void *cls, - sqlite3_stmt *result, + sqlite3_stmt *result, unsigned int column, - size_t *dst_size, - void *dst); + size_t *dst_size, + void *dst); /** @@ -247,9 +245,7 @@ typedef void /** * @brief Description of a DB result cell. */ -struct GNUNET_SQ_ResultSpec -{ - +struct GNUNET_SQ_ResultSpec { /** * What is the format of the result? */ @@ -289,7 +285,6 @@ struct GNUNET_SQ_ResultSpec * Number of parameters (columns) eaten by this operation. */ unsigned int num_params; - }; @@ -309,8 +304,8 @@ struct GNUNET_SQ_ResultSpec * @return array entry for the result specification to use */ struct GNUNET_SQ_ResultSpec -GNUNET_SQ_result_spec_variable_size (void **dst, - size_t *sptr); +GNUNET_SQ_result_spec_variable_size(void **dst, + size_t *sptr); /** @@ -321,8 +316,8 @@ GNUNET_SQ_result_spec_variable_size (void **dst, * @return array entry for the result specification to use */ struct GNUNET_SQ_ResultSpec -GNUNET_SQ_result_spec_fixed_size (void *dst, - size_t dst_size); +GNUNET_SQ_result_spec_fixed_size(void *dst, + size_t dst_size); /** @@ -331,7 +326,7 @@ GNUNET_SQ_result_spec_fixed_size (void *dst, * @param dst point to where to store the result, type fits expected result size * @return array entry for the result specification to use */ -#define GNUNET_SQ_result_spec_auto_from_type(dst) GNUNET_SQ_result_spec_fixed_size ((dst), sizeof (*(dst))) +#define GNUNET_SQ_result_spec_auto_from_type(dst) GNUNET_SQ_result_spec_fixed_size((dst), sizeof(*(dst))) /** @@ -342,8 +337,8 @@ GNUNET_SQ_result_spec_fixed_size (void *dst, * @return array entry for the result specification to use */ struct GNUNET_SQ_ResultSpec -GNUNET_SQ_result_spec_variable_size (void **dst, - size_t *sptr); +GNUNET_SQ_result_spec_variable_size(void **dst, + size_t *sptr); /** @@ -353,7 +348,7 @@ GNUNET_SQ_result_spec_variable_size (void **dst, * @return array entry for the result specification to use */ struct GNUNET_SQ_ResultSpec -GNUNET_SQ_result_spec_string (char **dst); +GNUNET_SQ_result_spec_string(char **dst); /** @@ -363,7 +358,7 @@ GNUNET_SQ_result_spec_string (char **dst); * @return array entry for the result specification to use */ struct GNUNET_SQ_ResultSpec -GNUNET_SQ_result_spec_rsa_public_key (struct GNUNET_CRYPTO_RsaPublicKey **rsa); +GNUNET_SQ_result_spec_rsa_public_key(struct GNUNET_CRYPTO_RsaPublicKey **rsa); /** @@ -373,7 +368,7 @@ GNUNET_SQ_result_spec_rsa_public_key (struct GNUNET_CRYPTO_RsaPublicKey **rsa); * @return array entry for the result specification to use */ struct GNUNET_SQ_ResultSpec -GNUNET_SQ_result_spec_rsa_signature (struct GNUNET_CRYPTO_RsaSignature **sig); +GNUNET_SQ_result_spec_rsa_signature(struct GNUNET_CRYPTO_RsaSignature **sig); /** @@ -383,7 +378,7 @@ GNUNET_SQ_result_spec_rsa_signature (struct GNUNET_CRYPTO_RsaSignature **sig); * @return array entry for the result specification to use */ struct GNUNET_SQ_ResultSpec -GNUNET_SQ_result_spec_absolute_time (struct GNUNET_TIME_Absolute *at); +GNUNET_SQ_result_spec_absolute_time(struct GNUNET_TIME_Absolute *at); /** @@ -393,7 +388,7 @@ GNUNET_SQ_result_spec_absolute_time (struct GNUNET_TIME_Absolute *at); * @return array entry for the result specification to use */ struct GNUNET_SQ_ResultSpec -GNUNET_SQ_result_spec_absolute_time_nbo (struct GNUNET_TIME_AbsoluteNBO *at); +GNUNET_SQ_result_spec_absolute_time_nbo(struct GNUNET_TIME_AbsoluteNBO *at); /** @@ -403,7 +398,7 @@ GNUNET_SQ_result_spec_absolute_time_nbo (struct GNUNET_TIME_AbsoluteNBO *at); * @return array entry for the result specification to use */ struct GNUNET_SQ_ResultSpec -GNUNET_SQ_result_spec_uint16 (uint16_t *u16); +GNUNET_SQ_result_spec_uint16(uint16_t *u16); /** @@ -413,7 +408,7 @@ GNUNET_SQ_result_spec_uint16 (uint16_t *u16); * @return array entry for the result specification to use */ struct GNUNET_SQ_ResultSpec -GNUNET_SQ_result_spec_uint32 (uint32_t *u32); +GNUNET_SQ_result_spec_uint32(uint32_t *u32); /** @@ -423,7 +418,7 @@ GNUNET_SQ_result_spec_uint32 (uint32_t *u32); * @return array entry for the result specification to use */ struct GNUNET_SQ_ResultSpec -GNUNET_SQ_result_spec_uint64 (uint64_t *u64); +GNUNET_SQ_result_spec_uint64(uint64_t *u64); /** @@ -436,8 +431,8 @@ GNUNET_SQ_result_spec_uint64 (uint64_t *u64); * #GNUNET_SYSERR if a result was invalid (non-existing field) */ int -GNUNET_SQ_extract_result (sqlite3_stmt *result, - struct GNUNET_SQ_ResultSpec *rs); +GNUNET_SQ_extract_result(sqlite3_stmt *result, + struct GNUNET_SQ_ResultSpec *rs); /** @@ -447,7 +442,7 @@ GNUNET_SQ_extract_result (sqlite3_stmt *result, * @param rs reult specification to clean up */ void -GNUNET_SQ_cleanup_result (struct GNUNET_SQ_ResultSpec *rs); +GNUNET_SQ_cleanup_result(struct GNUNET_SQ_ResultSpec *rs); @@ -459,7 +454,6 @@ GNUNET_SQ_cleanup_result (struct GNUNET_SQ_ResultSpec *rs); * #GNUNET_SQ_exec_statements(). */ struct GNUNET_SQ_PrepareStatement { - /** * Actual SQL statement. */ @@ -469,7 +463,6 @@ struct GNUNET_SQ_PrepareStatement { * Where to store handle? */ sqlite3_stmt **pstmt; - }; @@ -487,8 +480,8 @@ struct GNUNET_SQ_PrepareStatement { * @return initialized struct */ struct GNUNET_SQ_PrepareStatement -GNUNET_SQ_make_prepare (const char *sql, - sqlite3_stmt **pstmt); +GNUNET_SQ_make_prepare(const char *sql, + sqlite3_stmt **pstmt); @@ -501,8 +494,8 @@ GNUNET_SQ_make_prepare (const char *sql, * @return #GNUNET_OK on success */ int -GNUNET_SQ_prepare (sqlite3 *dbh, - const struct GNUNET_SQ_PrepareStatement *ps); +GNUNET_SQ_prepare(sqlite3 *dbh, + const struct GNUNET_SQ_PrepareStatement *ps); /* ******************** sq_exec.c functions ************** */ @@ -513,7 +506,6 @@ GNUNET_SQ_prepare (sqlite3 *dbh, * #GNUNET_SQ_exec_statements(). */ struct GNUNET_SQ_ExecuteStatement { - /** * Actual SQL statement. */ @@ -523,7 +515,6 @@ struct GNUNET_SQ_ExecuteStatement { * Should we ignore errors? */ int ignore_errors; - }; @@ -540,7 +531,7 @@ struct GNUNET_SQ_ExecuteStatement { * @return initialized struct */ struct GNUNET_SQ_ExecuteStatement -GNUNET_SQ_make_execute (const char *sql); +GNUNET_SQ_make_execute(const char *sql); /** @@ -551,7 +542,7 @@ GNUNET_SQ_make_execute (const char *sql); * @return initialized struct */ struct GNUNET_SQ_ExecuteStatement -GNUNET_SQ_make_try_execute (const char *sql); +GNUNET_SQ_make_try_execute(const char *sql); /** @@ -564,8 +555,8 @@ GNUNET_SQ_make_try_execute (const char *sql); * #GNUNET_SYSERR on error */ int -GNUNET_SQ_exec_statements (sqlite3 *dbh, - const struct GNUNET_SQ_ExecuteStatement *es); +GNUNET_SQ_exec_statements(sqlite3 *dbh, + const struct GNUNET_SQ_ExecuteStatement *es); diff --git a/src/include/gnunet_statistics_service.h b/src/include/gnunet_statistics_service.h index 94fa49358..3dd6e9ce1 100644 --- a/src/include/gnunet_statistics_service.h +++ b/src/include/gnunet_statistics_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -85,8 +85,8 @@ typedef int * @return handle to use */ struct GNUNET_STATISTICS_Handle * -GNUNET_STATISTICS_create (const char *subsystem, - const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_STATISTICS_create(const char *subsystem, + const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -97,8 +97,8 @@ GNUNET_STATISTICS_create (const char *subsystem, * be completed */ void -GNUNET_STATISTICS_destroy (struct GNUNET_STATISTICS_Handle *h, - int sync_first); +GNUNET_STATISTICS_destroy(struct GNUNET_STATISTICS_Handle *h, + int sync_first); /** @@ -112,11 +112,11 @@ GNUNET_STATISTICS_destroy (struct GNUNET_STATISTICS_Handle *h, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_STATISTICS_watch (struct GNUNET_STATISTICS_Handle *handle, - const char *subsystem, - const char *name, - GNUNET_STATISTICS_Iterator proc, - void *proc_cls); +GNUNET_STATISTICS_watch(struct GNUNET_STATISTICS_Handle *handle, + const char *subsystem, + const char *name, + GNUNET_STATISTICS_Iterator proc, + void *proc_cls); /** @@ -130,11 +130,11 @@ GNUNET_STATISTICS_watch (struct GNUNET_STATISTICS_Handle *handle, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error (no such watch) */ int -GNUNET_STATISTICS_watch_cancel (struct GNUNET_STATISTICS_Handle *handle, - const char *subsystem, - const char *name, - GNUNET_STATISTICS_Iterator proc, - void *proc_cls); +GNUNET_STATISTICS_watch_cancel(struct GNUNET_STATISTICS_Handle *handle, + const char *subsystem, + const char *name, + GNUNET_STATISTICS_Iterator proc, + void *proc_cls); /** @@ -168,12 +168,12 @@ struct GNUNET_STATISTICS_GetHandle; * @return NULL on error */ struct GNUNET_STATISTICS_GetHandle * -GNUNET_STATISTICS_get (struct GNUNET_STATISTICS_Handle *handle, - const char *subsystem, - const char *name, - GNUNET_STATISTICS_Callback cont, - GNUNET_STATISTICS_Iterator proc, - void *cls); +GNUNET_STATISTICS_get(struct GNUNET_STATISTICS_Handle *handle, + const char *subsystem, + const char *name, + GNUNET_STATISTICS_Callback cont, + GNUNET_STATISTICS_Iterator proc, + void *cls); /** @@ -183,7 +183,7 @@ GNUNET_STATISTICS_get (struct GNUNET_STATISTICS_Handle *handle, * @param gh handle of the request to cancel */ void -GNUNET_STATISTICS_get_cancel (struct GNUNET_STATISTICS_GetHandle *gh); +GNUNET_STATISTICS_get_cancel(struct GNUNET_STATISTICS_GetHandle *gh); /** @@ -196,10 +196,10 @@ GNUNET_STATISTICS_get_cancel (struct GNUNET_STATISTICS_GetHandle *gh); * @param make_persistent should the value be kept across restarts? */ void -GNUNET_STATISTICS_set (struct GNUNET_STATISTICS_Handle *handle, - const char *name, - uint64_t value, - int make_persistent); +GNUNET_STATISTICS_set(struct GNUNET_STATISTICS_Handle *handle, + const char *name, + uint64_t value, + int make_persistent); /** @@ -212,10 +212,10 @@ GNUNET_STATISTICS_set (struct GNUNET_STATISTICS_Handle *handle, * @param make_persistent should the value be kept across restarts? */ void -GNUNET_STATISTICS_update (struct GNUNET_STATISTICS_Handle *handle, - const char *name, - int64_t delta, - int make_persistent); +GNUNET_STATISTICS_update(struct GNUNET_STATISTICS_Handle *handle, + const char *name, + int64_t delta, + int make_persistent); diff --git a/src/include/gnunet_strings_lib.h b/src/include/gnunet_strings_lib.h index db657f54e..25dfada42 100644 --- a/src/include/gnunet_strings_lib.h +++ b/src/include/gnunet_strings_lib.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -61,8 +61,8 @@ extern "C" * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size, - unsigned long long *size); +GNUNET_STRINGS_fancy_size_to_bytes(const char *fancy_size, + unsigned long long *size); /** @@ -74,8 +74,8 @@ GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time, - struct GNUNET_TIME_Relative *rtime); +GNUNET_STRINGS_fancy_time_to_relative(const char *fancy_time, + struct GNUNET_TIME_Relative *rtime); /** @@ -89,8 +89,8 @@ GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time, - struct GNUNET_TIME_Absolute *atime); +GNUNET_STRINGS_fancy_time_to_absolute(const char *fancy_time, + struct GNUNET_TIME_Absolute *atime); /** @@ -100,7 +100,7 @@ GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time, * @return fancy representation of the size (possibly rounded) for humans */ char * -GNUNET_STRINGS_byte_size_fancy (unsigned long long size); +GNUNET_STRINGS_byte_size_fancy(unsigned long long size); /** @@ -117,9 +117,9 @@ GNUNET_STRINGS_byte_size_fancy (unsigned long long size); * string is returned. */ char * -GNUNET_STRINGS_conv (const char *input, size_t len, - const char *input_charset, - const char *output_charset); +GNUNET_STRINGS_conv(const char *input, size_t len, + const char *input_charset, + const char *output_charset); /** @@ -133,9 +133,9 @@ GNUNET_STRINGS_conv (const char *input, size_t len, * @return the converted string (0-terminated) */ char * -GNUNET_STRINGS_to_utf8 (const char *input, - size_t len, - const char *charset); +GNUNET_STRINGS_to_utf8(const char *input, + size_t len, + const char *charset); /** @@ -150,9 +150,9 @@ GNUNET_STRINGS_to_utf8 (const char *input, * string is returned. */ char * -GNUNET_STRINGS_from_utf8 (const char *input, - size_t len, - const char *charset); +GNUNET_STRINGS_from_utf8(const char *input, + size_t len, + const char *charset); /** @@ -163,8 +163,8 @@ GNUNET_STRINGS_from_utf8 (const char *input, * @param output output buffer */ void -GNUNET_STRINGS_utf8_tolower (const char *input, - char *output); +GNUNET_STRINGS_utf8_tolower(const char *input, + char *output); /** @@ -175,8 +175,8 @@ GNUNET_STRINGS_utf8_tolower (const char *input, * @param output output buffer */ void -GNUNET_STRINGS_utf8_toupper (const char *input, - char *output); +GNUNET_STRINGS_utf8_toupper(const char *input, + char *output); /** @@ -188,7 +188,7 @@ GNUNET_STRINGS_utf8_toupper (const char *input, * NULL is returned on error */ char * -GNUNET_STRINGS_filename_expand (const char *fil); +GNUNET_STRINGS_filename_expand(const char *fil); /** @@ -211,10 +211,10 @@ GNUNET_STRINGS_filename_expand (const char *fil); * (or number of bytes that would have been written) */ size_t -GNUNET_STRINGS_buffer_fill (char *buffer, - size_t size, - unsigned int count, - ...); +GNUNET_STRINGS_buffer_fill(char *buffer, + size_t size, + unsigned int count, + ...); /** @@ -230,9 +230,9 @@ GNUNET_STRINGS_buffer_fill (char *buffer, * in the buffer, or 0 on error. */ unsigned int -GNUNET_STRINGS_buffer_tokenize (const char *buffer, - size_t size, - unsigned int count, ...); +GNUNET_STRINGS_buffer_tokenize(const char *buffer, + size_t size, + unsigned int count, ...); @@ -247,7 +247,7 @@ GNUNET_STRINGS_buffer_tokenize (const char *buffer, * @return timestamp in human-readable form in local time */ const char * -GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t); +GNUNET_STRINGS_absolute_time_to_string(struct GNUNET_TIME_Absolute t); /** @@ -261,8 +261,8 @@ GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t); * @return string in human-readable form */ const char * -GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta, - int do_round); +GNUNET_STRINGS_relative_time_to_string(struct GNUNET_TIME_Relative delta, + int do_round); /** @@ -277,7 +277,7 @@ GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta, * itself. */ const char * -GNUNET_STRINGS_get_short_name (const char *filename); +GNUNET_STRINGS_get_short_name(const char *filename); /** @@ -293,10 +293,10 @@ GNUNET_STRINGS_get_short_name (const char *filename); * @return pointer to the next byte in 'out' or NULL on error. */ char * -GNUNET_STRINGS_data_to_string (const void *data, - size_t size, - char *out, - size_t out_size); +GNUNET_STRINGS_data_to_string(const void *data, + size_t size, + char *out, + size_t out_size); /** @@ -310,8 +310,8 @@ GNUNET_STRINGS_data_to_string (const void *data, * @return freshly allocated, null-terminated string */ char * -GNUNET_STRINGS_data_to_string_alloc (const void *buf, - size_t size); +GNUNET_STRINGS_data_to_string_alloc(const void *buf, + size_t size); /** @@ -325,10 +325,10 @@ GNUNET_STRINGS_data_to_string_alloc (const void *buf, * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding */ int -GNUNET_STRINGS_string_to_data (const char *enc, - size_t enclen, - void *out, - size_t out_size); +GNUNET_STRINGS_string_to_data(const char *enc, + size_t enclen, + void *out, + size_t out_size); /** @@ -341,9 +341,9 @@ GNUNET_STRINGS_string_to_data (const char *enc, * @return the size of the output */ size_t -GNUNET_STRINGS_base64_encode (const void *in, - size_t len, - char **output); +GNUNET_STRINGS_base64_encode(const void *in, + size_t len, + char **output); /** @@ -356,9 +356,9 @@ GNUNET_STRINGS_base64_encode (const void *in, * @return the size of the output */ size_t -GNUNET_STRINGS_base64_decode (const char *data, - size_t len, - void **output); +GNUNET_STRINGS_base64_decode(const char *data, + size_t len, + void **output); /** @@ -369,8 +369,8 @@ GNUNET_STRINGS_base64_decode (const char *data, * @return string representing the array of @a pids */ char * -GNUNET_STRINGS_pp2s (const struct GNUNET_PeerIdentity *pids, - unsigned int num_pids); +GNUNET_STRINGS_pp2s(const struct GNUNET_PeerIdentity *pids, + unsigned int num_pids); /** @@ -390,9 +390,9 @@ GNUNET_STRINGS_pp2s (const struct GNUNET_PeerIdentity *pids, * (if they weren't NULL). */ int -GNUNET_STRINGS_parse_uri (const char *path, - char **scheme_part, - const char **path_part); +GNUNET_STRINGS_parse_uri(const char *path, + char **scheme_part, + const char **path_part); /** @@ -410,17 +410,16 @@ GNUNET_STRINGS_parse_uri (const char *path, * @return #GNUNET_YES if 'filename' is absolute, #GNUNET_NO otherwise. */ int -GNUNET_STRINGS_path_is_absolute (const char *filename, - int can_be_uri, - int *r_is_uri, - char **r_uri_scheme); +GNUNET_STRINGS_path_is_absolute(const char *filename, + int can_be_uri, + int *r_is_uri, + char **r_uri_scheme); /** * Flags for what we should check a file for. */ -enum GNUNET_STRINGS_FilenameCheck -{ +enum GNUNET_STRINGS_FilenameCheck { /** * Check that it exists. */ @@ -453,8 +452,8 @@ enum GNUNET_STRINGS_FilenameCheck * fails, #GNUNET_SYSERR when a check can't be performed */ int -GNUNET_STRINGS_check_filename (const char *filename, - enum GNUNET_STRINGS_FilenameCheck checks); +GNUNET_STRINGS_check_filename(const char *filename, + enum GNUNET_STRINGS_FilenameCheck checks); /** @@ -469,9 +468,9 @@ GNUNET_STRINGS_check_filename (const char *filename, * case the contents of r_buf are undefined. */ int -GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr, - uint16_t addrlen, - struct sockaddr_in6 *r_buf); +GNUNET_STRINGS_to_address_ipv6(const char *zt_addr, + uint16_t addrlen, + struct sockaddr_in6 *r_buf); /** @@ -485,9 +484,9 @@ GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr, * the contents of r_buf are undefined. */ int -GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, - uint16_t addrlen, - struct sockaddr_in *r_buf); +GNUNET_STRINGS_to_address_ipv4(const char *zt_addr, + uint16_t addrlen, + struct sockaddr_in *r_buf); /** @@ -500,9 +499,9 @@ GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, * @return 0 on error, otherwise number of bytes in @a sa */ size_t -GNUNET_STRINGS_parse_socket_addr (const char *addr, - uint8_t *af, - struct sockaddr **sa); +GNUNET_STRINGS_parse_socket_addr(const char *addr, + uint8_t *af, + struct sockaddr **sa); /** @@ -517,9 +516,9 @@ GNUNET_STRINGS_parse_socket_addr (const char *addr, * case the contents of r_buf are undefined. */ int -GNUNET_STRINGS_to_address_ip (const char *addr, - uint16_t addrlen, - struct sockaddr_storage *r_buf); +GNUNET_STRINGS_to_address_ip(const char *addr, + uint16_t addrlen, + struct sockaddr_storage *r_buf); /** @@ -535,10 +534,10 @@ GNUNET_STRINGS_to_address_ip (const char *addr, * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure */ int -GNUNET_STRINGS_get_utf8_args (int argc, - char *const *argv, - int *u8argc, - char *const **u8argv); +GNUNET_STRINGS_get_utf8_args(int argc, + char *const *argv, + int *u8argc, + char *const **u8argv); /** @@ -554,7 +553,7 @@ GNUNET_STRINGS_get_utf8_args (int argc, * @param n the length of the string to copy, including its terminating null * byte * @return the length of the string that was copied, excluding the terminating - * null byte + * null byte */ size_t GNUNET_strlcpy(char *dst, const char *src, size_t n); @@ -562,9 +561,7 @@ GNUNET_strlcpy(char *dst, const char *src, size_t n); /* ***************** IPv4/IPv6 parsing ****************** */ -struct GNUNET_STRINGS_PortPolicy -{ - +struct GNUNET_STRINGS_PortPolicy { /** * Starting port range (0 if none given). */ @@ -580,15 +577,13 @@ struct GNUNET_STRINGS_PortPolicy * ("!" in policy). */ int negate_portrange; - }; /** * @brief IPV4 network in CIDR notation. */ -struct GNUNET_STRINGS_IPv4NetworkPolicy -{ +struct GNUNET_STRINGS_IPv4NetworkPolicy { /** * IPv4 address. */ @@ -603,15 +598,13 @@ struct GNUNET_STRINGS_IPv4NetworkPolicy * Policy for port access. */ struct GNUNET_STRINGS_PortPolicy pp; - }; /** * @brief network in CIDR notation for IPV6. */ -struct GNUNET_STRINGS_IPv6NetworkPolicy -{ +struct GNUNET_STRINGS_IPv6NetworkPolicy { /** * IPv6 address. */ @@ -626,7 +619,6 @@ struct GNUNET_STRINGS_IPv6NetworkPolicy * Policy for port access. */ struct GNUNET_STRINGS_PortPolicy pp; - }; @@ -642,7 +634,7 @@ struct GNUNET_STRINGS_IPv6NetworkPolicy * NULL if the synatx is flawed */ struct GNUNET_STRINGS_IPv4NetworkPolicy * -GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX); +GNUNET_STRINGS_parse_ipv4_policy(const char *routeListX); /** @@ -657,7 +649,7 @@ GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX); * @return the converted list, 0-terminated, NULL if the synatx is flawed */ struct GNUNET_STRINGS_IPv6NetworkPolicy * -GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX); +GNUNET_STRINGS_parse_ipv6_policy(const char *routeListX); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_testbed_logger_service.h b/src/include/gnunet_testbed_logger_service.h index 6dece2915..5d820e20b 100644 --- a/src/include/gnunet_testbed_logger_service.h +++ b/src/include/gnunet_testbed_logger_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -56,7 +56,7 @@ struct GNUNET_TESTBED_LOGGER_Handle; * upon any error */ struct GNUNET_TESTBED_LOGGER_Handle * -GNUNET_TESTBED_LOGGER_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_TESTBED_LOGGER_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -65,7 +65,7 @@ GNUNET_TESTBED_LOGGER_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param h the logger handle */ void -GNUNET_TESTBED_LOGGER_disconnect (struct GNUNET_TESTBED_LOGGER_Handle *h); +GNUNET_TESTBED_LOGGER_disconnect(struct GNUNET_TESTBED_LOGGER_Handle *h); /** @@ -90,9 +90,9 @@ typedef void * @param size how many bytes of @a data to send */ void -GNUNET_TESTBED_LOGGER_write (struct GNUNET_TESTBED_LOGGER_Handle *h, - const void *data, - size_t size); +GNUNET_TESTBED_LOGGER_write(struct GNUNET_TESTBED_LOGGER_Handle *h, + const void *data, + size_t size); /** @@ -103,9 +103,9 @@ GNUNET_TESTBED_LOGGER_write (struct GNUNET_TESTBED_LOGGER_Handle *h, * @param cb_cls the closure for @a cb */ void -GNUNET_TESTBED_LOGGER_flush (struct GNUNET_TESTBED_LOGGER_Handle *h, - GNUNET_TESTBED_LOGGER_FlushCompletion cb, - void *cb_cls); +GNUNET_TESTBED_LOGGER_flush(struct GNUNET_TESTBED_LOGGER_Handle *h, + GNUNET_TESTBED_LOGGER_FlushCompletion cb, + void *cb_cls); /** @@ -116,7 +116,7 @@ GNUNET_TESTBED_LOGGER_flush (struct GNUNET_TESTBED_LOGGER_Handle *h, * @param h the logger handle */ void -GNUNET_TESTBED_LOGGER_flush_cancel (struct GNUNET_TESTBED_LOGGER_Handle *h); +GNUNET_TESTBED_LOGGER_flush_cancel(struct GNUNET_TESTBED_LOGGER_Handle *h); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_testbed_service.h b/src/include/gnunet_testbed_service.h index db626df0e..5acf885dc 100644 --- a/src/include/gnunet_testbed_service.h +++ b/src/include/gnunet_testbed_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -89,10 +89,10 @@ struct GNUNET_TESTBED_Controller; * @return handle to the host, NULL on error */ struct GNUNET_TESTBED_Host * -GNUNET_TESTBED_host_create (const char *hostname, - const char *username, - const struct GNUNET_CONFIGURATION_Handle *cfg, - uint16_t port); +GNUNET_TESTBED_host_create(const char *hostname, + const char *username, + const struct GNUNET_CONFIGURATION_Handle *cfg, + uint16_t port); @@ -112,12 +112,12 @@ GNUNET_TESTBED_host_create (const char *hostname, * @return handle to the host, NULL on error */ struct GNUNET_TESTBED_Host * -GNUNET_TESTBED_host_create_with_id (uint32_t id, - const char *hostname, - const char *username, - const struct GNUNET_CONFIGURATION_Handle - *cfg, - uint16_t port); +GNUNET_TESTBED_host_create_with_id(uint32_t id, + const char *hostname, + const char *username, + const struct GNUNET_CONFIGURATION_Handle + *cfg, + uint16_t port); /** @@ -133,10 +133,10 @@ GNUNET_TESTBED_host_create_with_id (uint32_t id, * @return number of hosts returned in 'hosts', 0 on error */ unsigned int -GNUNET_TESTBED_hosts_load_from_file (const char *filename, - const struct GNUNET_CONFIGURATION_Handle - *cfg, - struct GNUNET_TESTBED_Host ***hosts); +GNUNET_TESTBED_hosts_load_from_file(const char *filename, + const struct GNUNET_CONFIGURATION_Handle + *cfg, + struct GNUNET_TESTBED_Host ***hosts); /** @@ -152,10 +152,10 @@ GNUNET_TESTBED_hosts_load_from_file (const char *filename, * @return number of hosts returned in 'hosts', 0 on error */ unsigned int -GNUNET_TESTBED_hosts_load_from_loadleveler (const struct - GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTBED_Host - ***hosts); +GNUNET_TESTBED_hosts_load_from_loadleveler(const struct + GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTBED_Host + ***hosts); /** * Destroy a host handle. Must only be called once everything @@ -164,7 +164,7 @@ GNUNET_TESTBED_hosts_load_from_loadleveler (const struct * @param host handle to destroy */ void -GNUNET_TESTBED_host_destroy (struct GNUNET_TESTBED_Host *host); +GNUNET_TESTBED_host_destroy(struct GNUNET_TESTBED_Host *host); /** @@ -201,11 +201,11 @@ typedef void * GNUNET_TESTBED_is_host_habitable_cancel() */ struct GNUNET_TESTBED_HostHabitableCheckHandle * -GNUNET_TESTBED_is_host_habitable (const struct GNUNET_TESTBED_Host *host, - const struct GNUNET_CONFIGURATION_Handle - *config, - GNUNET_TESTBED_HostHabitableCallback cb, - void *cb_cls); +GNUNET_TESTBED_is_host_habitable(const struct GNUNET_TESTBED_Host *host, + const struct GNUNET_CONFIGURATION_Handle + *config, + GNUNET_TESTBED_HostHabitableCallback cb, + void *cb_cls); /** @@ -214,9 +214,9 @@ GNUNET_TESTBED_is_host_habitable (const struct GNUNET_TESTBED_Host *host, * @param handle the habitability check handle */ void -GNUNET_TESTBED_is_host_habitable_cancel (struct - GNUNET_TESTBED_HostHabitableCheckHandle - *handle); +GNUNET_TESTBED_is_host_habitable_cancel(struct + GNUNET_TESTBED_HostHabitableCheckHandle + *handle); /** * Obtain the host's hostname. @@ -225,15 +225,14 @@ GNUNET_TESTBED_is_host_habitable_cancel (struct * @return hostname of the host */ const char * -GNUNET_TESTBED_host_get_hostname (const struct GNUNET_TESTBED_Host *host); +GNUNET_TESTBED_host_get_hostname(const struct GNUNET_TESTBED_Host *host); /** * Enumeration with (at most 64) possible event types that * can be monitored using the testbed framework. */ -enum GNUNET_TESTBED_EventType -{ +enum GNUNET_TESTBED_EventType { /** * A peer has been started. */ @@ -258,16 +257,13 @@ enum GNUNET_TESTBED_EventType * A requested testbed operation has been completed. */ GNUNET_TESTBED_ET_OPERATION_FINISHED = 4, - }; /** * Types of information that can be requested about a peer. */ -enum GNUNET_TESTBED_PeerInformationType -{ - +enum GNUNET_TESTBED_PeerInformationType { /** * Special value (not valid for requesting information) * that is used in the event struct if a 'generic' pointer @@ -291,7 +287,6 @@ enum GNUNET_TESTBED_PeerInformationType * 'GNUNET_TESTNIG_operation_done' is called. */ GNUNET_TESTBED_PIT_IDENTITY - }; @@ -299,9 +294,7 @@ enum GNUNET_TESTBED_PeerInformationType * Argument to GNUNET_TESTBED_ControllerCallback with details about * the event. */ -struct GNUNET_TESTBED_EventInformation -{ - +struct GNUNET_TESTBED_EventInformation { /** * Type of the event. */ @@ -320,14 +313,11 @@ struct GNUNET_TESTBED_EventInformation /** * Details about the event. */ - union - { - + union { /** * Details about peer start event. */ - struct - { + struct { /** * Handle for the host where the peer * was started. @@ -338,27 +328,22 @@ struct GNUNET_TESTBED_EventInformation * Handle for the peer that was started. */ struct GNUNET_TESTBED_Peer *peer; - } peer_start; /** * Details about peer stop event. */ - struct - { - + struct { /** * Handle for the peer that was started. */ struct GNUNET_TESTBED_Peer *peer; - } peer_stop; /** * Details about connect event. */ - struct - { + struct { /** * Handle for one of the connected peers. */ @@ -368,14 +353,12 @@ struct GNUNET_TESTBED_EventInformation * Handle for one of the connected peers. */ struct GNUNET_TESTBED_Peer *peer2; - } peer_connect; /** * Details about disconnect event. */ - struct - { + struct { /** * Handle for one of the disconnected peers. */ @@ -385,14 +368,12 @@ struct GNUNET_TESTBED_EventInformation * Handle for one of the disconnected peers. */ struct GNUNET_TESTBED_Peer *peer2; - } peer_disconnect; /** * Details about an operation finished event. */ - struct - { + struct { /** * Error message for the operation, NULL on success. */ @@ -403,11 +384,8 @@ struct GNUNET_TESTBED_EventInformation * (whatever the GNUNET_TESTBED_ConnectAdapter returned). */ void *generic; - } operation_finished; - } details; - }; @@ -468,10 +446,10 @@ typedef void * @return the controller process handle, NULL on errors */ struct GNUNET_TESTBED_ControllerProc * -GNUNET_TESTBED_controller_start (const char *trusted_ip, - struct GNUNET_TESTBED_Host *host, - GNUNET_TESTBED_ControllerStatusCallback cb, - void *cls); +GNUNET_TESTBED_controller_start(const char *trusted_ip, + struct GNUNET_TESTBED_Host *host, + GNUNET_TESTBED_ControllerStatusCallback cb, + void *cls); /** @@ -483,7 +461,7 @@ GNUNET_TESTBED_controller_start (const char *trusted_ip, * @param cproc the controller process handle */ void -GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cproc); +GNUNET_TESTBED_controller_stop(struct GNUNET_TESTBED_ControllerProc *cproc); /** @@ -503,10 +481,10 @@ GNUNET_TESTBED_controller_stop (struct GNUNET_TESTBED_ControllerProc *cproc); * @return handle to the controller */ struct GNUNET_TESTBED_Controller * -GNUNET_TESTBED_controller_connect (struct GNUNET_TESTBED_Host *host, - uint64_t event_mask, - GNUNET_TESTBED_ControllerCallback cc, - void *cc_cls); +GNUNET_TESTBED_controller_connect(struct GNUNET_TESTBED_Host *host, + uint64_t event_mask, + GNUNET_TESTBED_ControllerCallback cc, + void *cc_cls); /** @@ -517,7 +495,7 @@ GNUNET_TESTBED_controller_connect (struct GNUNET_TESTBED_Host *host, * @param c handle to controller to stop */ void -GNUNET_TESTBED_controller_disconnect (struct GNUNET_TESTBED_Controller *c); +GNUNET_TESTBED_controller_disconnect(struct GNUNET_TESTBED_Controller *c); /** @@ -553,10 +531,10 @@ typedef void * is not cancelled */ struct GNUNET_TESTBED_HostRegistrationHandle * -GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller, - struct GNUNET_TESTBED_Host *host, - GNUNET_TESTBED_HostRegistrationCompletion cc, - void *cc_cls); +GNUNET_TESTBED_register_host(struct GNUNET_TESTBED_Controller *controller, + struct GNUNET_TESTBED_Host *host, + GNUNET_TESTBED_HostRegistrationCompletion cc, + void *cc_cls); /** @@ -569,8 +547,8 @@ GNUNET_TESTBED_register_host (struct GNUNET_TESTBED_Controller *controller, * @param handle the registration handle to cancel */ void -GNUNET_TESTBED_cancel_registration (struct GNUNET_TESTBED_HostRegistrationHandle - *handle); +GNUNET_TESTBED_cancel_registration(struct GNUNET_TESTBED_HostRegistrationHandle + *handle); /** @@ -616,11 +594,11 @@ typedef void * @return the operation handle */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_controller_link (void *op_cls, - struct GNUNET_TESTBED_Controller *master, - struct GNUNET_TESTBED_Host *delegated_host, - struct GNUNET_TESTBED_Host *slave_host, - int is_subordinate); +GNUNET_TESTBED_controller_link(void *op_cls, + struct GNUNET_TESTBED_Controller *master, + struct GNUNET_TESTBED_Host *delegated_host, + struct GNUNET_TESTBED_Host *slave_host, + int is_subordinate); /** @@ -639,9 +617,9 @@ GNUNET_TESTBED_controller_link (void *op_cls, * master */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_get_slave_config (void *op_cls, - struct GNUNET_TESTBED_Controller *master, - struct GNUNET_TESTBED_Host *slave_host); +GNUNET_TESTBED_get_slave_config(void *op_cls, + struct GNUNET_TESTBED_Controller *master, + struct GNUNET_TESTBED_Host *slave_host); /** @@ -689,11 +667,11 @@ typedef void * @return the operation handle */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_peer_create (struct GNUNET_TESTBED_Controller *controller, - struct GNUNET_TESTBED_Host *host, - const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_TESTBED_PeerCreateCallback cb, - void *cls); +GNUNET_TESTBED_peer_create(struct GNUNET_TESTBED_Controller *controller, + struct GNUNET_TESTBED_Host *host, + const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_TESTBED_PeerCreateCallback cb, + void *cls); /** @@ -719,10 +697,10 @@ typedef void * @return handle to the operation */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_peer_start (void *op_cls, - struct GNUNET_TESTBED_Peer *peer, - GNUNET_TESTBED_PeerChurnCallback pcc, - void *pcc_cls); +GNUNET_TESTBED_peer_start(void *op_cls, + struct GNUNET_TESTBED_Peer *peer, + GNUNET_TESTBED_PeerChurnCallback pcc, + void *pcc_cls); /** @@ -738,17 +716,16 @@ GNUNET_TESTBED_peer_start (void *op_cls, * @return handle to the operation */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_peer_stop (void *op_cls, - struct GNUNET_TESTBED_Peer *peer, - GNUNET_TESTBED_PeerChurnCallback pcc, - void *pcc_cls); +GNUNET_TESTBED_peer_stop(void *op_cls, + struct GNUNET_TESTBED_Peer *peer, + GNUNET_TESTBED_PeerChurnCallback pcc, + void *pcc_cls); /** * Data returned from GNUNET_TESTBED_peer_get_information */ -struct GNUNET_TESTBED_PeerInformation -{ +struct GNUNET_TESTBED_PeerInformation { /** * Peer information type; captures which of the types * in the 'op_result' is actually in use. @@ -758,8 +735,7 @@ struct GNUNET_TESTBED_PeerInformation /** * The result of the get information operation; Choose according to the pit */ - union - { + union { /** * The configuration of the peer */ @@ -805,11 +781,11 @@ typedef void * @return handle to the operation */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_peer_get_information (struct GNUNET_TESTBED_Peer *peer, - enum GNUNET_TESTBED_PeerInformationType - pit, - GNUNET_TESTBED_PeerInfoCallback cb, - void *cb_cls); +GNUNET_TESTBED_peer_get_information(struct GNUNET_TESTBED_Peer *peer, + enum GNUNET_TESTBED_PeerInformationType + pit, + GNUNET_TESTBED_PeerInfoCallback cb, + void *cb_cls); /** @@ -821,8 +797,8 @@ GNUNET_TESTBED_peer_get_information (struct GNUNET_TESTBED_Peer *peer, * @return handle to the operation */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_peer_update_configuration (struct GNUNET_TESTBED_Peer *peer, - const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_TESTBED_peer_update_configuration(struct GNUNET_TESTBED_Peer *peer, + const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -833,7 +809,7 @@ GNUNET_TESTBED_peer_update_configuration (struct GNUNET_TESTBED_Peer *peer, * @return handle to the operation */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_peer_destroy (struct GNUNET_TESTBED_Peer *peer); +GNUNET_TESTBED_peer_destroy(struct GNUNET_TESTBED_Peer *peer); /** @@ -852,12 +828,12 @@ GNUNET_TESTBED_peer_destroy (struct GNUNET_TESTBED_Peer *peer); * @return an operation handle; NULL upon error (peer not running) */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_peer_manage_service (void *op_cls, - struct GNUNET_TESTBED_Peer *peer, - const char *service_name, - GNUNET_TESTBED_OperationCompletionCallback cb, - void *cb_cls, - unsigned int start); +GNUNET_TESTBED_peer_manage_service(void *op_cls, + struct GNUNET_TESTBED_Peer *peer, + const char *service_name, + GNUNET_TESTBED_OperationCompletionCallback cb, + void *cb_cls, + unsigned int start); /** @@ -876,18 +852,17 @@ GNUNET_TESTBED_peer_manage_service (void *op_cls, * present */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_shutdown_peers (struct GNUNET_TESTBED_Controller *c, - void *op_cls, - GNUNET_TESTBED_OperationCompletionCallback cb, - void *cb_cls); +GNUNET_TESTBED_shutdown_peers(struct GNUNET_TESTBED_Controller *c, + void *op_cls, + GNUNET_TESTBED_OperationCompletionCallback cb, + void *cb_cls); /** * Options for peer connections. */ -enum GNUNET_TESTBED_ConnectOption -{ +enum GNUNET_TESTBED_ConnectOption { /** * No option (not valid as an argument). */ @@ -907,7 +882,6 @@ enum GNUNET_TESTBED_ConnectOption * particular transports, force simulation of particular latencies * or message loss rates, or set bandwidth limitations. */ - }; @@ -924,11 +898,11 @@ enum GNUNET_TESTBED_ConnectOption * time is not allowed */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_underlay_configure_link_va (void *op_cls, - struct GNUNET_TESTBED_Peer *p1, - struct GNUNET_TESTBED_Peer *p2, - enum GNUNET_TESTBED_ConnectOption co, - va_list ap); +GNUNET_TESTBED_underlay_configure_link_va(void *op_cls, + struct GNUNET_TESTBED_Peer *p1, + struct GNUNET_TESTBED_Peer *p2, + enum GNUNET_TESTBED_ConnectOption co, + va_list ap); /** @@ -944,10 +918,10 @@ GNUNET_TESTBED_underlay_configure_link_va (void *op_cls, * time is not allowed */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_underlay_configure_link (void *op_cls, - struct GNUNET_TESTBED_Peer *p1, - struct GNUNET_TESTBED_Peer *p2, - enum GNUNET_TESTBED_ConnectOption co, ...); +GNUNET_TESTBED_underlay_configure_link(void *op_cls, + struct GNUNET_TESTBED_Peer *p1, + struct GNUNET_TESTBED_Peer *p2, + enum GNUNET_TESTBED_ConnectOption co, ...); @@ -955,8 +929,7 @@ GNUNET_TESTBED_underlay_configure_link (void *op_cls, * Topologies and topology options supported for testbeds. Options should always * end with #GNUNET_TESTBED_TOPOLOGY_OPTION_END */ -enum GNUNET_TESTBED_TopologyOption -{ +enum GNUNET_TESTBED_TopologyOption { /** * A clique (everyone connected to everyone else). No options. If there are N * peers this topology results in (N * (N -1)) connections. @@ -1063,11 +1036,11 @@ enum GNUNET_TESTBED_TopologyOption * is not allowed at this time */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_underlay_configure_topology_va (void *op_cls, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - enum GNUNET_TESTBED_TopologyOption topo, - va_list ap); +GNUNET_TESTBED_underlay_configure_topology_va(void *op_cls, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + enum GNUNET_TESTBED_TopologyOption topo, + va_list ap); /** @@ -1082,11 +1055,11 @@ GNUNET_TESTBED_underlay_configure_topology_va (void *op_cls, * is not allowed at this time */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_underlay_configure_topology (void *op_cls, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - enum GNUNET_TESTBED_TopologyOption topo, - ...); +GNUNET_TESTBED_underlay_configure_topology(void *op_cls, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + enum GNUNET_TESTBED_TopologyOption topo, + ...); /** @@ -1104,11 +1077,11 @@ GNUNET_TESTBED_underlay_configure_topology (void *op_cls, * not running or underlay disallows) */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_overlay_connect (void *op_cls, - GNUNET_TESTBED_OperationCompletionCallback cb, - void *cb_cls, - struct GNUNET_TESTBED_Peer *p1, - struct GNUNET_TESTBED_Peer *p2); +GNUNET_TESTBED_overlay_connect(void *op_cls, + GNUNET_TESTBED_OperationCompletionCallback cb, + void *cb_cls, + struct GNUNET_TESTBED_Peer *p1, + struct GNUNET_TESTBED_Peer *p2); /** @@ -1121,8 +1094,8 @@ GNUNET_TESTBED_overlay_connect (void *op_cls, * @param nfailures the number of overlay connects which failed */ typedef void (*GNUNET_TESTBED_TopologyCompletionCallback) (void *cls, - unsigned int nsuccess, - unsigned int nfailures); + unsigned int nsuccess, + unsigned int nfailures); /** @@ -1146,15 +1119,15 @@ typedef void (*GNUNET_TESTBED_TopologyCompletionCallback) (void *cls, * not running or underlay disallows) or if num_peers is less than 2 */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_overlay_configure_topology_va (void *op_cls, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - unsigned int *max_connections, - GNUNET_TESTBED_TopologyCompletionCallback - comp_cb, - void *comp_cb_cls, - enum GNUNET_TESTBED_TopologyOption topo, - va_list va); +GNUNET_TESTBED_overlay_configure_topology_va(void *op_cls, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + unsigned int *max_connections, + GNUNET_TESTBED_TopologyCompletionCallback + comp_cb, + void *comp_cb_cls, + enum GNUNET_TESTBED_TopologyOption topo, + va_list va); /** @@ -1178,15 +1151,15 @@ GNUNET_TESTBED_overlay_configure_topology_va (void *op_cls, * not running or underlay disallows) or if num_peers is less than 2 */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_overlay_configure_topology (void *op_cls, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - unsigned int *max_connections, - GNUNET_TESTBED_TopologyCompletionCallback - comp_cb, - void *comp_cb_cls, - enum GNUNET_TESTBED_TopologyOption topo, - ...); +GNUNET_TESTBED_overlay_configure_topology(void *op_cls, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + unsigned int *max_connections, + GNUNET_TESTBED_TopologyCompletionCallback + comp_cb, + void *comp_cb_cls, + enum GNUNET_TESTBED_TopologyOption topo, + ...); /** @@ -1200,8 +1173,8 @@ GNUNET_TESTBED_overlay_configure_topology (void *op_cls, * be written to. */ void -GNUNET_TESTBED_overlay_write_topology_to_file (struct GNUNET_TESTBED_Controller *controller, - const char *filename); +GNUNET_TESTBED_overlay_write_topology_to_file(struct GNUNET_TESTBED_Controller *controller, + const char *filename); /** @@ -1244,7 +1217,7 @@ typedef void (*GNUNET_TESTBED_ServiceConnectCompletionCallback) (void *cls, struct GNUNET_TESTBED_Operation *op, void *ca_result, - const char *emsg ); + const char *emsg); /** @@ -1270,14 +1243,14 @@ typedef void * @return handle for the operation */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_service_connect (void *op_cls, - struct GNUNET_TESTBED_Peer *peer, - const char *service_name, - GNUNET_TESTBED_ServiceConnectCompletionCallback cb, - void *cb_cls, - GNUNET_TESTBED_ConnectAdapter ca, - GNUNET_TESTBED_DisconnectAdapter da, - void *cada_cls); +GNUNET_TESTBED_service_connect(void *op_cls, + struct GNUNET_TESTBED_Peer *peer, + const char *service_name, + GNUNET_TESTBED_ServiceConnectCompletionCallback cb, + void *cb_cls, + GNUNET_TESTBED_ConnectAdapter ca, + GNUNET_TESTBED_DisconnectAdapter da, + void *cada_cls); /** @@ -1302,7 +1275,7 @@ GNUNET_TESTBED_service_connect (void *op_cls, * @param operation operation to signal completion or cancellation */ void -GNUNET_TESTBED_operation_done (struct GNUNET_TESTBED_Operation *operation); +GNUNET_TESTBED_operation_done(struct GNUNET_TESTBED_Operation *operation); /** @@ -1341,12 +1314,12 @@ typedef int * @return operation handle to cancel the operation */ struct GNUNET_TESTBED_Operation * -GNUNET_TESTBED_get_statistics (unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - const char *subsystem, const char *name, - GNUNET_TESTBED_StatisticsIterator proc, - GNUNET_TESTBED_OperationCompletionCallback cont, - void *cls); +GNUNET_TESTBED_get_statistics(unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + const char *subsystem, const char *name, + GNUNET_TESTBED_StatisticsIterator proc, + GNUNET_TESTBED_OperationCompletionCallback cont, + void *cls); /** @@ -1358,7 +1331,7 @@ GNUNET_TESTBED_get_statistics (unsigned int num_peers, * @return The peer's unique ID. */ uint32_t -GNUNET_TESTBED_get_index (const struct GNUNET_TESTBED_Peer *peer); +GNUNET_TESTBED_get_index(const struct GNUNET_TESTBED_Peer *peer); /** @@ -1424,14 +1397,14 @@ typedef void * @param test_master_cls closure for 'test_master'. */ void -GNUNET_TESTBED_run (const char *host_filename, - const struct GNUNET_CONFIGURATION_Handle *cfg, - unsigned int num_peers, - uint64_t event_mask, - GNUNET_TESTBED_ControllerCallback cc, - void *cc_cls, - GNUNET_TESTBED_TestMaster test_master, - void *test_master_cls); +GNUNET_TESTBED_run(const char *host_filename, + const struct GNUNET_CONFIGURATION_Handle *cfg, + unsigned int num_peers, + uint64_t event_mask, + GNUNET_TESTBED_ControllerCallback cc, + void *cc_cls, + GNUNET_TESTBED_TestMaster test_master, + void *test_master_cls); /** @@ -1473,14 +1446,14 @@ GNUNET_TESTBED_run (const char *host_filename, * @return #GNUNET_SYSERR on error, #GNUNET_OK on success */ int -GNUNET_TESTBED_test_run (const char *testname, - const char *cfg_filename, - unsigned int num_peers, - uint64_t event_mask, - GNUNET_TESTBED_ControllerCallback cc, - void *cc_cls, - GNUNET_TESTBED_TestMaster test_master, - void *test_master_cls); +GNUNET_TESTBED_test_run(const char *testname, + const char *cfg_filename, + unsigned int num_peers, + uint64_t event_mask, + GNUNET_TESTBED_ControllerCallback cc, + void *cc_cls, + GNUNET_TESTBED_TestMaster test_master, + void *test_master_cls); /** @@ -1491,7 +1464,7 @@ GNUNET_TESTBED_test_run (const char *testname, * @return handle to the master controller */ struct GNUNET_TESTBED_Controller * -GNUNET_TESTBED_run_get_controller_handle (struct GNUNET_TESTBED_RunHandle *h); +GNUNET_TESTBED_run_get_controller_handle(struct GNUNET_TESTBED_RunHandle *h); /** @@ -1503,8 +1476,7 @@ struct GNUNET_TESTBED_Barrier; /** * Status of a barrier */ -enum GNUNET_TESTBED_BarrierStatus -{ +enum GNUNET_TESTBED_BarrierStatus { /** * Barrier initialised successfully */ @@ -1519,7 +1491,6 @@ enum GNUNET_TESTBED_BarrierStatus * Error status */ GNUNET_TESTBED_BARRIERSTATUS_ERROR, - }; @@ -1561,11 +1532,11 @@ typedef void * @return barrier handle */ struct GNUNET_TESTBED_Barrier * -GNUNET_TESTBED_barrier_init (struct GNUNET_TESTBED_Controller *controller, - const char *name, - unsigned int quorum, - GNUNET_TESTBED_barrier_status_cb cb, - void *cb_cls); +GNUNET_TESTBED_barrier_init(struct GNUNET_TESTBED_Controller *controller, + const char *name, + unsigned int quorum, + GNUNET_TESTBED_barrier_status_cb cb, + void *cb_cls); /** @@ -1574,7 +1545,7 @@ GNUNET_TESTBED_barrier_init (struct GNUNET_TESTBED_Controller *controller, * @param barrier the barrier handle */ void -GNUNET_TESTBED_barrier_cancel (struct GNUNET_TESTBED_Barrier *barrier); +GNUNET_TESTBED_barrier_cancel(struct GNUNET_TESTBED_Barrier *barrier); /** @@ -1611,9 +1582,9 @@ typedef void * anytime before the callback is called. NULL upon error. */ struct GNUNET_TESTBED_BarrierWaitHandle * -GNUNET_TESTBED_barrier_wait (const char *name, - GNUNET_TESTBED_barrier_wait_cb cb, - void *cls); +GNUNET_TESTBED_barrier_wait(const char *name, + GNUNET_TESTBED_barrier_wait_cb cb, + void *cls); /** @@ -1623,7 +1594,7 @@ GNUNET_TESTBED_barrier_wait (const char *name, * @param h the barrier wait handle */ void -GNUNET_TESTBED_barrier_wait_cancel (struct GNUNET_TESTBED_BarrierWaitHandle *h); +GNUNET_TESTBED_barrier_wait_cancel(struct GNUNET_TESTBED_BarrierWaitHandle *h); /** @@ -1637,8 +1608,7 @@ struct GNUNET_TESTBED_UnderlayLinkModel; * The type of GNUNET_TESTBED_UnderlayLinkModel * @ingroup underlay */ -enum GNUNET_TESTBED_UnderlayLinkModelType -{ +enum GNUNET_TESTBED_UnderlayLinkModelType { /** * The model is based on white listing of peers to which underlay connections * are permitted. Underlay connections to all other peers will not be @@ -1665,8 +1635,8 @@ enum GNUNET_TESTBED_UnderlayLinkModelType * @return the model */ struct GNUNET_TESTBED_UnderlayLinkModel * -GNUNET_TESTBED_underlaylinkmodel_create (struct GNUNET_TESTBED_Peer *peer, - enum GNUNET_TESTBED_UnderlayLinkModelType type); +GNUNET_TESTBED_underlaylinkmodel_create(struct GNUNET_TESTBED_Peer *peer, + enum GNUNET_TESTBED_UnderlayLinkModelType type); /** @@ -1679,8 +1649,8 @@ GNUNET_TESTBED_underlaylinkmodel_create (struct GNUNET_TESTBED_Peer *peer, * @param peer the peer to add */ void -GNUNET_TESTBED_underlaylinkmodel_add_peer (struct GNUNET_TESTBED_UnderlayLinkModel *model, - struct GNUNET_TESTBED_Peer *peer); +GNUNET_TESTBED_underlaylinkmodel_add_peer(struct GNUNET_TESTBED_UnderlayLinkModel *model, + struct GNUNET_TESTBED_Peer *peer); /** @@ -1695,11 +1665,11 @@ GNUNET_TESTBED_underlaylinkmodel_add_peer (struct GNUNET_TESTBED_UnderlayLinkMod * @param bandwidth bandwidth of the link in kilobytes per second [kB/s] */ void -GNUNET_TESTBED_underlaylinkmodel_set_link (struct GNUNET_TESTBED_UnderlayLinkModel *model, - struct GNUNET_TESTBED_Peer *peer, - uint32_t latency, - uint32_t loss, - uint32_t bandwidth); +GNUNET_TESTBED_underlaylinkmodel_set_link(struct GNUNET_TESTBED_UnderlayLinkModel *model, + struct GNUNET_TESTBED_Peer *peer, + uint32_t latency, + uint32_t loss, + uint32_t bandwidth); /** @@ -1709,7 +1679,7 @@ GNUNET_TESTBED_underlaylinkmodel_set_link (struct GNUNET_TESTBED_UnderlayLinkMod * @param model the model to commit */ void -GNUNET_TESTBED_underlaylinkmodel_commit (struct GNUNET_TESTBED_UnderlayLinkModel *model); +GNUNET_TESTBED_underlaylinkmodel_commit(struct GNUNET_TESTBED_UnderlayLinkModel *model); /** @@ -1721,7 +1691,7 @@ GNUNET_TESTBED_underlaylinkmodel_commit (struct GNUNET_TESTBED_UnderlayLinkModel * @param model the model to unallocate */ void -GNUNET_TESTBED_underlaylinkmodel_free (struct GNUNET_TESTBED_UnderlayLinkModel *model); +GNUNET_TESTBED_underlaylinkmodel_free(struct GNUNET_TESTBED_UnderlayLinkModel *model); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_testing_lib.h b/src/include/gnunet_testing_lib.h index 0317b2007..370360eb1 100644 --- a/src/include/gnunet_testing_lib.h +++ b/src/include/gnunet_testing_lib.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -56,7 +56,7 @@ extern "C" /** * Size of each hostkey in the hostkey file (in BYTES). */ -#define GNUNET_TESTING_HOSTKEYFILESIZE sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey) +#define GNUNET_TESTING_HOSTKEYFILESIZE sizeof(struct GNUNET_CRYPTO_EddsaPrivateKey) /** * The environmental variable, if set, that dictates where testing should place @@ -81,8 +81,7 @@ struct GNUNET_TESTING_Peer; /** * Specification of a service that is to be shared among peers */ -struct GNUNET_TESTING_SharedService -{ +struct GNUNET_TESTING_SharedService { /** * The name of the service. */ @@ -122,11 +121,11 @@ struct GNUNET_TESTING_SharedService * @return handle to this system, NULL on error */ struct GNUNET_TESTING_System * -GNUNET_TESTING_system_create (const char *testdir, - const char *trusted_ip, - const char *hostname, - const struct GNUNET_TESTING_SharedService * - shared_services); +GNUNET_TESTING_system_create(const char *testdir, + const char *trusted_ip, + const char *hostname, + const struct GNUNET_TESTING_SharedService * + shared_services); /** @@ -154,12 +153,12 @@ GNUNET_TESTING_system_create (const char *testdir, * @return handle to this system, NULL on error */ struct GNUNET_TESTING_System * -GNUNET_TESTING_system_create_with_portrange (const char *testdir, - const char *trusted_ip, - const char *hostname, - const struct GNUNET_TESTING_SharedService *shared_services, - uint16_t lowport, - uint16_t highport); +GNUNET_TESTING_system_create_with_portrange(const char *testdir, + const char *trusted_ip, + const char *hostname, + const struct GNUNET_TESTING_SharedService *shared_services, + uint16_t lowport, + uint16_t highport); /** @@ -170,8 +169,8 @@ GNUNET_TESTING_system_create_with_portrange (const char *testdir, * be removed (clean up on shutdown)? */ void -GNUNET_TESTING_system_destroy (struct GNUNET_TESTING_System *system, - int remove_paths); +GNUNET_TESTING_system_destroy(struct GNUNET_TESTING_System *system, + int remove_paths); /** @@ -192,9 +191,9 @@ GNUNET_TESTING_system_destroy (struct GNUNET_TESTING_System *system, * @return NULL on error (not enough keys) */ struct GNUNET_CRYPTO_EddsaPrivateKey * -GNUNET_TESTING_hostkey_get (const struct GNUNET_TESTING_System *system, - uint32_t key_number, - struct GNUNET_PeerIdentity *id); +GNUNET_TESTING_hostkey_get(const struct GNUNET_TESTING_System *system, + uint32_t key_number, + struct GNUNET_PeerIdentity *id); /** @@ -204,7 +203,7 @@ GNUNET_TESTING_hostkey_get (const struct GNUNET_TESTING_System *system, * @return 0 if no free port was available */ uint16_t -GNUNET_TESTING_reserve_port (struct GNUNET_TESTING_System *system); +GNUNET_TESTING_reserve_port(struct GNUNET_TESTING_System *system); /** @@ -215,8 +214,8 @@ GNUNET_TESTING_reserve_port (struct GNUNET_TESTING_System *system); * @param port reserved port to release */ void -GNUNET_TESTING_release_port (struct GNUNET_TESTING_System *system, - uint16_t port); +GNUNET_TESTING_release_port(struct GNUNET_TESTING_System *system, + uint16_t port); /** @@ -237,8 +236,8 @@ GNUNET_TESTING_release_port (struct GNUNET_TESTING_System *system, * be incomplete and should not be used there upon */ int -GNUNET_TESTING_configuration_create (struct GNUNET_TESTING_System *system, - struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_TESTING_configuration_create(struct GNUNET_TESTING_System *system, + struct GNUNET_CONFIGURATION_Handle *cfg); // FIXME: add dual to 'release' ports again... @@ -256,11 +255,11 @@ GNUNET_TESTING_configuration_create (struct GNUNET_TESTING_System *system, * @return handle to the peer, NULL on error */ struct GNUNET_TESTING_Peer * -GNUNET_TESTING_peer_configure (struct GNUNET_TESTING_System *system, - struct GNUNET_CONFIGURATION_Handle *cfg, - uint32_t key_number, - struct GNUNET_PeerIdentity *id, - char **emsg); +GNUNET_TESTING_peer_configure(struct GNUNET_TESTING_System *system, + struct GNUNET_CONFIGURATION_Handle *cfg, + uint32_t key_number, + struct GNUNET_PeerIdentity *id, + char **emsg); /** @@ -270,8 +269,8 @@ GNUNET_TESTING_peer_configure (struct GNUNET_TESTING_System *system, * @param id identifier for the daemon, will be set */ void -GNUNET_TESTING_peer_get_identity (struct GNUNET_TESTING_Peer *peer, - struct GNUNET_PeerIdentity *id); +GNUNET_TESTING_peer_get_identity(struct GNUNET_TESTING_Peer *peer, + struct GNUNET_PeerIdentity *id); /** @@ -282,7 +281,7 @@ GNUNET_TESTING_peer_get_identity (struct GNUNET_TESTING_Peer *peer, * #GNUNET_SYSERR on error (i.e. peer already running) */ int -GNUNET_TESTING_peer_start (struct GNUNET_TESTING_Peer *peer); +GNUNET_TESTING_peer_start(struct GNUNET_TESTING_Peer *peer); /** @@ -295,7 +294,7 @@ GNUNET_TESTING_peer_start (struct GNUNET_TESTING_Peer *peer); * #GNUNET_SYSERR on error (i.e. peer not running) */ int -GNUNET_TESTING_peer_stop (struct GNUNET_TESTING_Peer *peer); +GNUNET_TESTING_peer_stop(struct GNUNET_TESTING_Peer *peer); /** @@ -306,7 +305,7 @@ GNUNET_TESTING_peer_stop (struct GNUNET_TESTING_Peer *peer); * @param peer peer to destroy */ void -GNUNET_TESTING_peer_destroy (struct GNUNET_TESTING_Peer *peer); +GNUNET_TESTING_peer_destroy(struct GNUNET_TESTING_Peer *peer); /** @@ -317,7 +316,7 @@ GNUNET_TESTING_peer_destroy (struct GNUNET_TESTING_Peer *peer); * or upon any error while sending SIGTERM */ int -GNUNET_TESTING_peer_kill (struct GNUNET_TESTING_Peer *peer); +GNUNET_TESTING_peer_kill(struct GNUNET_TESTING_Peer *peer); /** @@ -328,7 +327,7 @@ GNUNET_TESTING_peer_kill (struct GNUNET_TESTING_Peer *peer); * or upon any error while waiting */ int -GNUNET_TESTING_peer_wait (struct GNUNET_TESTING_Peer *peer); +GNUNET_TESTING_peer_wait(struct GNUNET_TESTING_Peer *peer); /** @@ -357,9 +356,9 @@ typedef void * upon any error. */ int -GNUNET_TESTING_peer_stop_async (struct GNUNET_TESTING_Peer *peer, - GNUNET_TESTING_PeerStopCallback cb, - void *cb_cls); +GNUNET_TESTING_peer_stop_async(struct GNUNET_TESTING_Peer *peer, + GNUNET_TESTING_PeerStopCallback cb, + void *cb_cls); /** @@ -372,7 +371,7 @@ GNUNET_TESTING_peer_stop_async (struct GNUNET_TESTING_Peer *peer, * before. */ void -GNUNET_TESTING_peer_stop_async_cancel (struct GNUNET_TESTING_Peer *peer); +GNUNET_TESTING_peer_stop_async_cancel(struct GNUNET_TESTING_Peer *peer); /** @@ -406,10 +405,10 @@ typedef void * @return 0 on success, 1 on error */ int -GNUNET_TESTING_peer_run (const char *testdir, - const char *cfgfilename, - GNUNET_TESTING_TestMain tm, - void *tm_cls); +GNUNET_TESTING_peer_run(const char *testdir, + const char *cfgfilename, + GNUNET_TESTING_TestMain tm, + void *tm_cls); /** @@ -434,11 +433,11 @@ GNUNET_TESTING_peer_run (const char *testdir, * @return 0 on success, 1 on error */ int -GNUNET_TESTING_service_run (const char *testdir, - const char *service_name, - const char *cfgfilename, - GNUNET_TESTING_TestMain tm, - void *tm_cls); +GNUNET_TESTING_service_run(const char *testdir, + const char *service_name, + const char *cfgfilename, + GNUNET_TESTING_TestMain tm, + void *tm_cls); /** @@ -455,7 +454,7 @@ GNUNET_TESTING_service_run (const char *testdir, * NULL if argv0 has no '_' */ char * -GNUNET_TESTING_get_testname_from_underscore (const char *argv0); +GNUNET_TESTING_get_testname_from_underscore(const char *argv0); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_time_lib.h b/src/include/gnunet_time_lib.h index d0da267a9..28a76e3ef 100644 --- a/src/include/gnunet_time_lib.h +++ b/src/include/gnunet_time_lib.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -45,8 +45,7 @@ extern "C" /** * Time for absolute times used by GNUnet, in microseconds. */ -struct GNUNET_TIME_Absolute -{ +struct GNUNET_TIME_Absolute { /** * The actual value. */ @@ -57,8 +56,7 @@ struct GNUNET_TIME_Absolute * Time for relative time used by GNUnet, in microseconds. * Always positive, so we can only refer to future time. */ -struct GNUNET_TIME_Relative -{ +struct GNUNET_TIME_Relative { /** * The actual value. */ @@ -70,8 +68,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Time for relative time used by GNUnet, in microseconds and in network byte order. */ -struct GNUNET_TIME_RelativeNBO -{ +struct GNUNET_TIME_RelativeNBO { /** * The actual value (in network byte order). */ @@ -82,8 +79,7 @@ struct GNUNET_TIME_RelativeNBO /** * Time for absolute time used by GNUnet, in microseconds and in network byte order. */ -struct GNUNET_TIME_AbsoluteNBO -{ +struct GNUNET_TIME_AbsoluteNBO { /** * The actual value (in network byte order). */ @@ -129,41 +125,41 @@ GNUNET_NETWORK_STRUCT_END /** * One day. */ -#define GNUNET_TIME_UNIT_DAYS GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_HOURS, 24) +#define GNUNET_TIME_UNIT_DAYS GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_HOURS, 24) /** * One week. */ -#define GNUNET_TIME_UNIT_WEEKS GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_DAYS, 7) +#define GNUNET_TIME_UNIT_WEEKS GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_DAYS, 7) /** * One month (30 days). */ -#define GNUNET_TIME_UNIT_MONTHS GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_DAYS, 30) +#define GNUNET_TIME_UNIT_MONTHS GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_DAYS, 30) /** * One year (365 days). */ -#define GNUNET_TIME_UNIT_YEARS GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_DAYS, 365) +#define GNUNET_TIME_UNIT_YEARS GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_DAYS, 365) /** * Constant used to specify "forever". This constant * will be treated specially in all time operations. */ -#define GNUNET_TIME_UNIT_FOREVER_REL GNUNET_TIME_relative_get_forever_ () +#define GNUNET_TIME_UNIT_FOREVER_REL GNUNET_TIME_relative_get_forever_() /** * Constant used to specify "forever". This constant * will be treated specially in all time operations. */ -#define GNUNET_TIME_UNIT_FOREVER_ABS GNUNET_TIME_absolute_get_forever_ () +#define GNUNET_TIME_UNIT_FOREVER_ABS GNUNET_TIME_absolute_get_forever_() /** * Threshold after which exponential backoff should not increase (15 m). */ -#define GNUNET_TIME_STD_EXPONENTIAL_BACKOFF_THRESHOLD GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define GNUNET_TIME_STD_EXPONENTIAL_BACKOFF_THRESHOLD GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) /** @@ -172,8 +168,8 @@ GNUNET_NETWORK_STRUCT_END * * @param r current backoff time, initially zero */ -#define GNUNET_TIME_STD_BACKOFF(r) GNUNET_TIME_relative_min (GNUNET_TIME_STD_EXPONENTIAL_BACKOFF_THRESHOLD, \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_max (GNUNET_TIME_UNIT_MILLISECONDS, (r)), 2)); +#define GNUNET_TIME_STD_BACKOFF(r) GNUNET_TIME_relative_min(GNUNET_TIME_STD_EXPONENTIAL_BACKOFF_THRESHOLD, \ + GNUNET_TIME_relative_multiply(GNUNET_TIME_relative_max(GNUNET_TIME_UNIT_MILLISECONDS, (r)), 2)); /** @@ -191,10 +187,10 @@ GNUNET_TIME_randomized_backoff(struct GNUNET_TIME_Relative rt, struct GNUNET_TIM /** * Return a random time value between 0.5*r and 1.5*r. - * + * * @param r input time for scaling * @return randomized time - */ + */ struct GNUNET_TIME_Relative GNUNET_TIME_randomize(struct GNUNET_TIME_Relative r); @@ -203,63 +199,63 @@ GNUNET_TIME_randomize(struct GNUNET_TIME_Relative r); * Return relative time of 0ms. */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_get_zero_ (void); +GNUNET_TIME_relative_get_zero_(void); /** * Return absolute time of 0ms. */ struct GNUNET_TIME_Absolute -GNUNET_TIME_absolute_get_zero_ (void); +GNUNET_TIME_absolute_get_zero_(void); /** * Return relative time of 1 microsecond. */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_get_unit_ (void); +GNUNET_TIME_relative_get_unit_(void); /** * Return relative time of 1ms. */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_get_millisecond_ (void); +GNUNET_TIME_relative_get_millisecond_(void); /** * Return relative time of 1s. */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_get_second_ (void); +GNUNET_TIME_relative_get_second_(void); /** * Return relative time of 1 minute. */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_get_minute_ (void); +GNUNET_TIME_relative_get_minute_(void); /** * Return relative time of 1 hour. */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_get_hour_ (void); +GNUNET_TIME_relative_get_hour_(void); /** * Return "forever". */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_get_forever_ (void); +GNUNET_TIME_relative_get_forever_(void); /** * Return "forever". */ struct GNUNET_TIME_Absolute -GNUNET_TIME_absolute_get_forever_ (void); +GNUNET_TIME_absolute_get_forever_(void); /** @@ -268,7 +264,7 @@ GNUNET_TIME_absolute_get_forever_ (void); * @return the current time */ struct GNUNET_TIME_Absolute -GNUNET_TIME_absolute_get (void); +GNUNET_TIME_absolute_get(void); /** @@ -279,7 +275,7 @@ GNUNET_TIME_absolute_get (void); * @return timestamp that is "rel" in the future, or FOREVER if rel==FOREVER (or if we would overflow) */ struct GNUNET_TIME_Absolute -GNUNET_TIME_relative_to_absolute (struct GNUNET_TIME_Relative rel); +GNUNET_TIME_relative_to_absolute(struct GNUNET_TIME_Relative rel); /** @@ -291,7 +287,7 @@ GNUNET_TIME_relative_to_absolute (struct GNUNET_TIME_Relative rel); * it was just now rounded */ int -GNUNET_TIME_round_abs (struct GNUNET_TIME_Absolute *at); +GNUNET_TIME_round_abs(struct GNUNET_TIME_Absolute *at); /** @@ -303,7 +299,7 @@ GNUNET_TIME_round_abs (struct GNUNET_TIME_Absolute *at); * it was just now rounded */ int -GNUNET_TIME_round_rel (struct GNUNET_TIME_Relative *rt); +GNUNET_TIME_round_rel(struct GNUNET_TIME_Relative *rt); /** @@ -314,8 +310,8 @@ GNUNET_TIME_round_rel (struct GNUNET_TIME_Relative *rt); * @return timestamp that is smaller */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_min (struct GNUNET_TIME_Relative t1, - struct GNUNET_TIME_Relative t2); +GNUNET_TIME_relative_min(struct GNUNET_TIME_Relative t1, + struct GNUNET_TIME_Relative t2); @@ -327,8 +323,8 @@ GNUNET_TIME_relative_min (struct GNUNET_TIME_Relative t1, * @return timestamp that is larger */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_max (struct GNUNET_TIME_Relative t1, - struct GNUNET_TIME_Relative t2); +GNUNET_TIME_relative_max(struct GNUNET_TIME_Relative t1, + struct GNUNET_TIME_Relative t2); /** @@ -339,8 +335,8 @@ GNUNET_TIME_relative_max (struct GNUNET_TIME_Relative t1, * @return timestamp that is smaller */ struct GNUNET_TIME_Absolute -GNUNET_TIME_absolute_min (struct GNUNET_TIME_Absolute t1, - struct GNUNET_TIME_Absolute t2); +GNUNET_TIME_absolute_min(struct GNUNET_TIME_Absolute t1, + struct GNUNET_TIME_Absolute t2); /** @@ -351,8 +347,8 @@ GNUNET_TIME_absolute_min (struct GNUNET_TIME_Absolute t1, * @return timestamp that is smaller */ struct GNUNET_TIME_Absolute -GNUNET_TIME_absolute_max (struct GNUNET_TIME_Absolute t1, - struct GNUNET_TIME_Absolute t2); +GNUNET_TIME_absolute_max(struct GNUNET_TIME_Absolute t1, + struct GNUNET_TIME_Absolute t2); /** @@ -363,7 +359,7 @@ GNUNET_TIME_absolute_max (struct GNUNET_TIME_Absolute t1, * @return future - now, or 0 if now >= future, or FOREVER if future==FOREVER. */ struct GNUNET_TIME_Relative -GNUNET_TIME_absolute_get_remaining (struct GNUNET_TIME_Absolute future); +GNUNET_TIME_absolute_get_remaining(struct GNUNET_TIME_Absolute future); /** @@ -377,9 +373,9 @@ GNUNET_TIME_absolute_get_remaining (struct GNUNET_TIME_Absolute future); * assuming it continues at the same speed */ struct GNUNET_TIME_Relative -GNUNET_TIME_calculate_eta (struct GNUNET_TIME_Absolute start, - uint64_t finished, - uint64_t total); +GNUNET_TIME_calculate_eta(struct GNUNET_TIME_Absolute start, + uint64_t finished, + uint64_t total); /** @@ -392,8 +388,8 @@ GNUNET_TIME_calculate_eta (struct GNUNET_TIME_Absolute start, * @return 0 if start >= end; FOREVER if end==FOREVER; otherwise end - start */ struct GNUNET_TIME_Relative -GNUNET_TIME_absolute_get_difference (struct GNUNET_TIME_Absolute start, - struct GNUNET_TIME_Absolute end); +GNUNET_TIME_absolute_get_difference(struct GNUNET_TIME_Absolute start, + struct GNUNET_TIME_Absolute end); /** @@ -404,7 +400,7 @@ GNUNET_TIME_absolute_get_difference (struct GNUNET_TIME_Absolute start, * @return 0 if hence > now, otherwise now-hence. */ struct GNUNET_TIME_Relative -GNUNET_TIME_absolute_get_duration (struct GNUNET_TIME_Absolute whence); +GNUNET_TIME_absolute_get_duration(struct GNUNET_TIME_Absolute whence); /** @@ -416,8 +412,8 @@ GNUNET_TIME_absolute_get_duration (struct GNUNET_TIME_Absolute whence); * @return FOREVER if either argument is FOREVER or on overflow; start+duration otherwise */ struct GNUNET_TIME_Absolute -GNUNET_TIME_absolute_add (struct GNUNET_TIME_Absolute start, - struct GNUNET_TIME_Relative duration); +GNUNET_TIME_absolute_add(struct GNUNET_TIME_Absolute start, + struct GNUNET_TIME_Relative duration); /** @@ -429,8 +425,8 @@ GNUNET_TIME_absolute_add (struct GNUNET_TIME_Absolute start, * @return ZERO if start <= duration, or FOREVER if start time is FOREVER; start-duration otherwise */ struct GNUNET_TIME_Absolute -GNUNET_TIME_absolute_subtract (struct GNUNET_TIME_Absolute start, - struct GNUNET_TIME_Relative duration); +GNUNET_TIME_absolute_subtract(struct GNUNET_TIME_Absolute start, + struct GNUNET_TIME_Relative duration); /** @@ -441,8 +437,8 @@ GNUNET_TIME_absolute_subtract (struct GNUNET_TIME_Absolute start, * @return FOREVER if rel=FOREVER or on overflow; otherwise rel*factor */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_multiply (struct GNUNET_TIME_Relative rel, - unsigned long long factor); +GNUNET_TIME_relative_multiply(struct GNUNET_TIME_Relative rel, + unsigned long long factor); /** @@ -453,8 +449,8 @@ GNUNET_TIME_relative_multiply (struct GNUNET_TIME_Relative rel, * @return FOREVER if rel=FOREVER or on overflow; otherwise rel*factor */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_saturating_multiply (struct GNUNET_TIME_Relative rel, - unsigned long long factor); +GNUNET_TIME_relative_saturating_multiply(struct GNUNET_TIME_Relative rel, + unsigned long long factor); /** @@ -465,8 +461,8 @@ GNUNET_TIME_relative_saturating_multiply (struct GNUNET_TIME_Relative rel, * @return FOREVER if rel=FOREVER or factor==0; otherwise rel/factor */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_divide (struct GNUNET_TIME_Relative rel, - unsigned long long factor); +GNUNET_TIME_relative_divide(struct GNUNET_TIME_Relative rel, + unsigned long long factor); /** @@ -477,8 +473,8 @@ GNUNET_TIME_relative_divide (struct GNUNET_TIME_Relative rel, * @return FOREVER if either argument is FOREVER or on overflow; a1+a2 otherwise */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_add (struct GNUNET_TIME_Relative a1, - struct GNUNET_TIME_Relative a2); +GNUNET_TIME_relative_add(struct GNUNET_TIME_Relative a1, + struct GNUNET_TIME_Relative a2); /** @@ -489,8 +485,8 @@ GNUNET_TIME_relative_add (struct GNUNET_TIME_Relative a1, * @return ZERO if a2>=a1 (including both FOREVER), FOREVER if a1 is FOREVER, a1-a2 otherwise */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_subtract (struct GNUNET_TIME_Relative a1, - struct GNUNET_TIME_Relative a2); +GNUNET_TIME_relative_subtract(struct GNUNET_TIME_Relative a1, + struct GNUNET_TIME_Relative a2); /** @@ -500,7 +496,7 @@ GNUNET_TIME_relative_subtract (struct GNUNET_TIME_Relative a1, * @return converted time value */ struct GNUNET_TIME_RelativeNBO -GNUNET_TIME_relative_hton (struct GNUNET_TIME_Relative a); +GNUNET_TIME_relative_hton(struct GNUNET_TIME_Relative a); /** @@ -510,7 +506,7 @@ GNUNET_TIME_relative_hton (struct GNUNET_TIME_Relative a); * @return converted time value */ struct GNUNET_TIME_Relative -GNUNET_TIME_relative_ntoh (struct GNUNET_TIME_RelativeNBO a); +GNUNET_TIME_relative_ntoh(struct GNUNET_TIME_RelativeNBO a); /** @@ -520,7 +516,7 @@ GNUNET_TIME_relative_ntoh (struct GNUNET_TIME_RelativeNBO a); * @return converted time value */ struct GNUNET_TIME_AbsoluteNBO -GNUNET_TIME_absolute_hton (struct GNUNET_TIME_Absolute a); +GNUNET_TIME_absolute_hton(struct GNUNET_TIME_Absolute a); /** @@ -530,7 +526,7 @@ GNUNET_TIME_absolute_hton (struct GNUNET_TIME_Absolute a); * @return converted time value */ struct GNUNET_TIME_Absolute -GNUNET_TIME_absolute_ntoh (struct GNUNET_TIME_AbsoluteNBO a); +GNUNET_TIME_absolute_ntoh(struct GNUNET_TIME_AbsoluteNBO a); /** @@ -539,7 +535,7 @@ GNUNET_TIME_absolute_ntoh (struct GNUNET_TIME_AbsoluteNBO a); * @param offset the offset to skew the locale time by */ void -GNUNET_TIME_set_offset (long long offset); +GNUNET_TIME_set_offset(long long offset); /** @@ -548,14 +544,14 @@ GNUNET_TIME_set_offset (long long offset); * @return the offset we currently skew the locale time by */ long long -GNUNET_TIME_get_offset (void); +GNUNET_TIME_get_offset(void); /** * Return the current year (i.e. '2011'). */ unsigned int -GNUNET_TIME_get_current_year (void); +GNUNET_TIME_get_current_year(void); /** @@ -565,7 +561,7 @@ GNUNET_TIME_get_current_year (void); * @return absolute time for January 1st of that year. */ struct GNUNET_TIME_Absolute -GNUNET_TIME_year_to_time (unsigned int year); +GNUNET_TIME_year_to_time(unsigned int year); /** @@ -575,7 +571,7 @@ GNUNET_TIME_year_to_time (unsigned int year); * @return year a year (after 1970), 0 on error */ unsigned int -GNUNET_TIME_time_to_year (struct GNUNET_TIME_Absolute at); +GNUNET_TIME_time_to_year(struct GNUNET_TIME_Absolute at); /** @@ -603,7 +599,7 @@ struct GNUNET_CONFIGURATION_Handle; * @return monotonically increasing time */ struct GNUNET_TIME_Absolute -GNUNET_TIME_absolute_get_monotonic (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_TIME_absolute_get_monotonic(const struct GNUNET_CONFIGURATION_Handle *cfg); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_transport_application_service.h b/src/include/gnunet_transport_application_service.h index c12bd7441..2219cf7a7 100644 --- a/src/include/gnunet_transport_application_service.h +++ b/src/include/gnunet_transport_application_service.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2010-2015, 2018, 2019 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2010-2015, 2018, 2019 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -50,7 +50,7 @@ struct GNUNET_TRANSPORT_ApplicationHandle; * @return ats application handle, NULL on error */ struct GNUNET_TRANSPORT_ApplicationHandle * -GNUNET_TRANSPORT_application_init ( +GNUNET_TRANSPORT_application_init( const struct GNUNET_CONFIGURATION_Handle *cfg); @@ -60,7 +60,7 @@ GNUNET_TRANSPORT_application_init ( * @param ch handle to destroy */ void -GNUNET_TRANSPORT_application_done ( +GNUNET_TRANSPORT_application_done( struct GNUNET_TRANSPORT_ApplicationHandle *ch); @@ -75,7 +75,7 @@ GNUNET_TRANSPORT_application_done ( * @return suggest handle, NULL if a request is already pending */ struct GNUNET_TRANSPORT_ApplicationSuggestHandle * -GNUNET_TRANSPORT_application_suggest ( +GNUNET_TRANSPORT_application_suggest( struct GNUNET_TRANSPORT_ApplicationHandle *ch, const struct GNUNET_PeerIdentity *peer, enum GNUNET_MQ_PriorityPreferences pk, @@ -88,7 +88,7 @@ GNUNET_TRANSPORT_application_suggest ( * @param sh handle to stop */ void -GNUNET_TRANSPORT_application_suggest_cancel ( +GNUNET_TRANSPORT_application_suggest_cancel( struct GNUNET_TRANSPORT_ApplicationSuggestHandle *sh); @@ -108,7 +108,7 @@ GNUNET_TRANSPORT_application_suggest_cancel ( * @param addr address to validate */ void -GNUNET_TRANSPORT_application_validate ( +GNUNET_TRANSPORT_application_validate( struct GNUNET_TRANSPORT_ApplicationHandle *ch, const struct GNUNET_PeerIdentity *peer, enum GNUNET_NetworkType nt, diff --git a/src/include/gnunet_transport_communication_service.h b/src/include/gnunet_transport_communication_service.h index ea1ff732e..e7c8be0c6 100644 --- a/src/include/gnunet_transport_communication_service.h +++ b/src/include/gnunet_transport_communication_service.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -87,9 +87,7 @@ struct GNUNET_TRANSPORT_CommunicatorHandle; * FIXME: may want to distinguish bi-directional as well, * should we define a bit for that? Needed in DV logic (handle_dv_learn)! */ -enum GNUNET_TRANSPORT_CommunicatorCharacteristics -{ - +enum GNUNET_TRANSPORT_CommunicatorCharacteristics { /** * Characteristics are unknown (i.e. DV). */ @@ -104,7 +102,6 @@ enum GNUNET_TRANSPORT_CommunicatorCharacteristics * Transmission is unreliable (i.e. UDP) */ GNUNET_TRANSPORT_CC_UNRELIABLE = 2 - }; @@ -146,7 +143,7 @@ typedef void (*GNUNET_TRANSPORT_CommunicatorNotify) ( * @return NULL on error */ struct GNUNET_TRANSPORT_CommunicatorHandle * -GNUNET_TRANSPORT_communicator_connect ( +GNUNET_TRANSPORT_communicator_connect( const struct GNUNET_CONFIGURATION_Handle *cfg, const char *config_section_name, const char *addr_prefix, @@ -163,7 +160,7 @@ GNUNET_TRANSPORT_communicator_connect ( * @param ch handle returned from connect */ void -GNUNET_TRANSPORT_communicator_disconnect ( +GNUNET_TRANSPORT_communicator_disconnect( struct GNUNET_TRANSPORT_CommunicatorHandle *ch); @@ -203,7 +200,7 @@ typedef void (*GNUNET_TRANSPORT_MessageCompletedCallback) (void *cls, * the tranport service is not yet up */ int -GNUNET_TRANSPORT_communicator_receive ( +GNUNET_TRANSPORT_communicator_receive( struct GNUNET_TRANSPORT_CommunicatorHandle *handle, const struct GNUNET_PeerIdentity *sender, const struct GNUNET_MessageHeader *msg, @@ -224,9 +221,7 @@ struct GNUNET_TRANSPORT_QueueHandle; /** * Possible states of a connection. */ -enum GNUNET_TRANSPORT_ConnectionStatus -{ - +enum GNUNET_TRANSPORT_ConnectionStatus { /** * Connection is down. */ @@ -260,7 +255,7 @@ enum GNUNET_TRANSPORT_ConnectionStatus * @return API handle identifying the new MQ */ struct GNUNET_TRANSPORT_QueueHandle * -GNUNET_TRANSPORT_communicator_mq_add ( +GNUNET_TRANSPORT_communicator_mq_add( struct GNUNET_TRANSPORT_CommunicatorHandle *ch, const struct GNUNET_PeerIdentity *peer, const char *address, @@ -277,7 +272,7 @@ GNUNET_TRANSPORT_communicator_mq_add ( * @param qh handle for the queue that must be invalidated */ void -GNUNET_TRANSPORT_communicator_mq_del (struct GNUNET_TRANSPORT_QueueHandle *qh); +GNUNET_TRANSPORT_communicator_mq_del(struct GNUNET_TRANSPORT_QueueHandle *qh); /** @@ -297,7 +292,7 @@ struct GNUNET_TRANSPORT_AddressIdentifier; * @param expiration when does the communicator forsee this address expiring? */ struct GNUNET_TRANSPORT_AddressIdentifier * -GNUNET_TRANSPORT_communicator_address_add ( +GNUNET_TRANSPORT_communicator_address_add( struct GNUNET_TRANSPORT_CommunicatorHandle *ch, const char *address, enum GNUNET_NetworkType nt, @@ -311,7 +306,7 @@ GNUNET_TRANSPORT_communicator_address_add ( * @param ai address that is no longer provided */ void -GNUNET_TRANSPORT_communicator_address_remove ( +GNUNET_TRANSPORT_communicator_address_remove( struct GNUNET_TRANSPORT_AddressIdentifier *ai); @@ -334,7 +329,7 @@ GNUNET_TRANSPORT_communicator_address_remove ( * notify-API to @a pid's communicator @a comm */ void -GNUNET_TRANSPORT_communicator_notify ( +GNUNET_TRANSPORT_communicator_notify( struct GNUNET_TRANSPORT_CommunicatorHandle *ch, const struct GNUNET_PeerIdentity *pid, const char *comm, diff --git a/src/include/gnunet_transport_core_service.h b/src/include/gnunet_transport_core_service.h index 076514779..e9ae4a2b4 100644 --- a/src/include/gnunet_transport_core_service.h +++ b/src/include/gnunet_transport_core_service.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff * @@ -107,12 +107,12 @@ typedef void (*GNUNET_TRANSPORT_NotifyDisconnect) ( * @return NULL on error */ struct GNUNET_TRANSPORT_CoreHandle * -GNUNET_TRANSPORT_core_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_PeerIdentity *self, - const struct GNUNET_MQ_MessageHandler *handlers, - void *cls, - GNUNET_TRANSPORT_NotifyConnect nc, - GNUNET_TRANSPORT_NotifyDisconnect nd); +GNUNET_TRANSPORT_core_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_PeerIdentity *self, + const struct GNUNET_MQ_MessageHandler *handlers, + void *cls, + GNUNET_TRANSPORT_NotifyConnect nc, + GNUNET_TRANSPORT_NotifyDisconnect nd); /** @@ -121,7 +121,7 @@ GNUNET_TRANSPORT_core_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param handle handle returned from connect */ void -GNUNET_TRANSPORT_core_disconnect (struct GNUNET_TRANSPORT_CoreHandle *handle); +GNUNET_TRANSPORT_core_disconnect(struct GNUNET_TRANSPORT_CoreHandle *handle); /** @@ -145,8 +145,8 @@ GNUNET_TRANSPORT_core_disconnect (struct GNUNET_TRANSPORT_CoreHandle *handle); * @param pid which peer was the message from that was fully processed by CORE */ void -GNUNET_TRANSPORT_core_receive_continue (struct GNUNET_TRANSPORT_CoreHandle *ch, - const struct GNUNET_PeerIdentity *pid); +GNUNET_TRANSPORT_core_receive_continue(struct GNUNET_TRANSPORT_CoreHandle *ch, + const struct GNUNET_PeerIdentity *pid); /** @@ -158,8 +158,8 @@ GNUNET_TRANSPORT_core_receive_continue (struct GNUNET_TRANSPORT_CoreHandle *ch, * @return NULL if disconnected, otherwise message queue for @a peer */ struct GNUNET_MQ_Handle * -GNUNET_TRANSPORT_core_get_mq (struct GNUNET_TRANSPORT_CoreHandle *handle, - const struct GNUNET_PeerIdentity *peer); +GNUNET_TRANSPORT_core_get_mq(struct GNUNET_TRANSPORT_CoreHandle *handle, + const struct GNUNET_PeerIdentity *peer); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_transport_hello_service.h b/src/include/gnunet_transport_hello_service.h index fe863c058..512103c54 100644 --- a/src/include/gnunet_transport_hello_service.h +++ b/src/include/gnunet_transport_hello_service.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -58,9 +58,7 @@ extern "C" { * classes to filter addresses by which domain they make * sense to be used in. These are used in a bitmask. */ -enum GNUNET_TRANSPORT_AddressClass -{ - +enum GNUNET_TRANSPORT_AddressClass { /** * No address. */ @@ -108,7 +106,6 @@ enum GNUNET_TRANSPORT_AddressClass * Bitmask for "any" address. */ GNUNET_TRANSPORT_AC_ANY = 65535 - }; @@ -141,10 +138,10 @@ struct GNUNET_TRANSPORT_HelloGetHandle; * @return handle to cancel the operation */ struct GNUNET_TRANSPORT_HelloGetHandle * -GNUNET_TRANSPORT_hello_get (const struct GNUNET_CONFIGURATION_Handle *cfg, - enum GNUNET_TRANSPORT_AddressClass ac, - GNUNET_TRANSPORT_HelloUpdateCallback rec, - void *rec_cls); +GNUNET_TRANSPORT_hello_get(const struct GNUNET_CONFIGURATION_Handle *cfg, + enum GNUNET_TRANSPORT_AddressClass ac, + GNUNET_TRANSPORT_HelloUpdateCallback rec, + void *rec_cls); /** @@ -153,7 +150,7 @@ GNUNET_TRANSPORT_hello_get (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param ghh handle to cancel */ void -GNUNET_TRANSPORT_hello_get_cancel (struct GNUNET_TRANSPORT_HelloGetHandle *ghh); +GNUNET_TRANSPORT_hello_get_cancel(struct GNUNET_TRANSPORT_HelloGetHandle *ghh); /** @@ -183,9 +180,9 @@ typedef void (*GNUNET_TRANSPORT_AddressCallback) ( * @return #GNUNET_OK if hello was well-formed, #GNUNET_SYSERR if not */ int -GNUNET_TRANSPORT_hello_parse (const struct GNUNET_MessageHeader *hello, - GNUNET_TRANSPORT_AddressCallback cb, - void *cb_cls); +GNUNET_TRANSPORT_hello_parse(const struct GNUNET_MessageHeader *hello, + GNUNET_TRANSPORT_AddressCallback cb, + void *cb_cls); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_transport_manipulation_service.h b/src/include/gnunet_transport_manipulation_service.h index 5b37345b0..3149d1dd5 100644 --- a/src/include/gnunet_transport_manipulation_service.h +++ b/src/include/gnunet_transport_manipulation_service.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -66,7 +66,7 @@ struct GNUNET_TRANSPORT_ManipulationHandle; * @return NULL on error */ struct GNUNET_TRANSPORT_ManipulationHandle * -GNUNET_TRANSPORT_manipulation_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_TRANSPORT_manipulation_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -75,7 +75,7 @@ GNUNET_TRANSPORT_manipulation_connect (const struct GNUNET_CONFIGURATION_Handle * @param handle handle returned from connect */ void -GNUNET_TRANSPORT_manipulation_disconnect (struct GNUNET_TRANSPORT_ManipulationHandle *handle); +GNUNET_TRANSPORT_manipulation_disconnect(struct GNUNET_TRANSPORT_ManipulationHandle *handle); /** @@ -91,11 +91,11 @@ GNUNET_TRANSPORT_manipulation_disconnect (struct GNUNET_TRANSPORT_ManipulationHa * with one message delay. */ void -GNUNET_TRANSPORT_manipulation_set (struct GNUNET_TRANSPORT_ManipulationHandle *handle, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_ATS_Properties *prop, - struct GNUNET_TIME_Relative delay_in, - struct GNUNET_TIME_Relative delay_out); +GNUNET_TRANSPORT_manipulation_set(struct GNUNET_TRANSPORT_ManipulationHandle *handle, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_ATS_Properties *prop, + struct GNUNET_TIME_Relative delay_in, + struct GNUNET_TIME_Relative delay_out); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_transport_monitor_service.h b/src/include/gnunet_transport_monitor_service.h index f83fa7e9f..a67fca778 100644 --- a/src/include/gnunet_transport_monitor_service.h +++ b/src/include/gnunet_transport_monitor_service.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -56,9 +56,7 @@ extern "C" /** * Information about another peer's address. */ -struct GNUNET_TRANSPORT_MonitorInformation -{ - +struct GNUNET_TRANSPORT_MonitorInformation { /** * Address we have for the peer, human-readable, 0-terminated, in UTF-8. */ @@ -103,7 +101,6 @@ struct GNUNET_TRANSPORT_MonitorInformation * Current estimate of the RTT. */ struct GNUNET_TIME_Relative rtt; - }; @@ -162,11 +159,11 @@ struct GNUNET_TRANSPORT_MonitorContext; * @param cb_cls closure for @a mc */ struct GNUNET_TRANSPORT_MonitorContext * -GNUNET_TRANSPORT_monitor (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_PeerIdentity *peer, - int one_shot, - GNUNET_TRANSPORT_MonitorCallback cb, - void *cb_cls); +GNUNET_TRANSPORT_monitor(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_PeerIdentity *peer, + int one_shot, + GNUNET_TRANSPORT_MonitorCallback cb, + void *cb_cls); /** @@ -175,7 +172,7 @@ GNUNET_TRANSPORT_monitor (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param mc handle for the request to cancel */ void -GNUNET_TRANSPORT_monitor_cancel (struct GNUNET_TRANSPORT_MonitorContext *mc); +GNUNET_TRANSPORT_monitor_cancel(struct GNUNET_TRANSPORT_MonitorContext *mc); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_transport_plugin.h b/src/include/gnunet_transport_plugin.h index ed5244987..12ecb88f2 100644 --- a/src/include/gnunet_transport_plugin.h +++ b/src/include/gnunet_transport_plugin.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -134,9 +134,9 @@ typedef struct GNUNET_TIME_Relative * @return type of the network the address belongs to */ typedef enum GNUNET_NetworkType -(*GNUNET_TRANSPORT_AddressToType) (void *cls, - const struct sockaddr *addr, - size_t addrlen); +(*GNUNET_TRANSPORT_AddressToType)(void *cls, + const struct sockaddr *addr, + size_t addrlen); /** @@ -203,8 +203,7 @@ typedef const struct GNUNET_MessageHeader * * of this type as the first and only argument to the * entry point of each transport plugin. */ -struct GNUNET_TRANSPORT_PluginEnvironment -{ +struct GNUNET_TRANSPORT_PluginEnvironment { /** * Configuration to use. */ @@ -277,7 +276,6 @@ struct GNUNET_TRANSPORT_PluginEnvironment * UDP) can ignore this value. */ uint32_t max_connections; - }; @@ -550,8 +548,8 @@ typedef int * @return the network type */ typedef enum GNUNET_NetworkType -(*GNUNET_TRANSPORT_GetNetworkType) (void *cls, - struct GNUNET_ATS_Session *session); +(*GNUNET_TRANSPORT_GetNetworkType)(void *cls, + struct GNUNET_ATS_Session *session); /** @@ -562,8 +560,8 @@ typedef enum GNUNET_NetworkType * @return the network type */ typedef enum GNUNET_NetworkType -(*GNUNET_TRANSPORT_GetNetworkTypeForAddress) (void *cls, - const struct GNUNET_HELLO_Address *address); +(*GNUNET_TRANSPORT_GetNetworkTypeForAddress)(void *cls, + const struct GNUNET_HELLO_Address *address); /** @@ -606,9 +604,7 @@ typedef void * Each plugin is required to return a pointer to a struct of this * type as the return value from its entry point. */ -struct GNUNET_TRANSPORT_PluginFunctions -{ - +struct GNUNET_TRANSPORT_PluginFunctions { /** * Closure for all of the callbacks. */ diff --git a/src/include/gnunet_transport_service.h b/src/include/gnunet_transport_service.h index 80949b417..735e216e8 100644 --- a/src/include/gnunet_transport_service.h +++ b/src/include/gnunet_transport_service.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -75,10 +75,10 @@ struct GNUNET_TRANSPORT_OfferHelloHandle; * */ struct GNUNET_TRANSPORT_OfferHelloHandle * -GNUNET_TRANSPORT_offer_hello (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_MessageHeader *hello, - GNUNET_SCHEDULER_TaskCallback cont, - void *cont_cls); +GNUNET_TRANSPORT_offer_hello(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_MessageHeader *hello, + GNUNET_SCHEDULER_TaskCallback cont, + void *cont_cls); /** @@ -87,7 +87,7 @@ GNUNET_TRANSPORT_offer_hello (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param ohh the `struct GNUNET_TRANSPORT_OfferHelloHandle` to cancel */ void -GNUNET_TRANSPORT_offer_hello_cancel ( +GNUNET_TRANSPORT_offer_hello_cancel( struct GNUNET_TRANSPORT_OfferHelloHandle *ohh); @@ -133,7 +133,7 @@ typedef void (*GNUNET_TRANSPORT_AddressToStringCallback) (void *cls, * @return handle to cancel the operation, NULL on error */ struct GNUNET_TRANSPORT_AddressToStringContext * -GNUNET_TRANSPORT_address_to_string ( +GNUNET_TRANSPORT_address_to_string( const struct GNUNET_CONFIGURATION_Handle *cfg, const struct GNUNET_HELLO_Address *address, int numeric, @@ -148,7 +148,7 @@ GNUNET_TRANSPORT_address_to_string ( * @param alc the context handle */ void -GNUNET_TRANSPORT_address_to_string_cancel ( +GNUNET_TRANSPORT_address_to_string_cancel( struct GNUNET_TRANSPORT_AddressToStringContext *alc); @@ -211,8 +211,7 @@ GNUNET_TRANSPORT_address_to_string_cancel ( * to 0). * */ -enum GNUNET_TRANSPORT_PeerState -{ +enum GNUNET_TRANSPORT_PeerState { /** * Fresh peer or completely disconnected */ @@ -289,7 +288,7 @@ enum GNUNET_TRANSPORT_PeerState * @param state the state */ const char * -GNUNET_TRANSPORT_ps2s (enum GNUNET_TRANSPORT_PeerState state); +GNUNET_TRANSPORT_ps2s(enum GNUNET_TRANSPORT_PeerState state); /** @@ -299,7 +298,7 @@ GNUNET_TRANSPORT_ps2s (enum GNUNET_TRANSPORT_PeerState state); * @return #GNUNET_YES or #GNUNET_NO */ int -GNUNET_TRANSPORT_is_connected (enum GNUNET_TRANSPORT_PeerState state); +GNUNET_TRANSPORT_is_connected(enum GNUNET_TRANSPORT_PeerState state); /** @@ -361,7 +360,7 @@ typedef void (*GNUNET_TRANSPORT_PeerIterateCallback) ( * @param peer_callback_cls closure for @a peer_callback */ struct GNUNET_TRANSPORT_PeerMonitoringContext * -GNUNET_TRANSPORT_monitor_peers ( +GNUNET_TRANSPORT_monitor_peers( const struct GNUNET_CONFIGURATION_Handle *cfg, const struct GNUNET_PeerIdentity *peer, int one_shot, @@ -375,7 +374,7 @@ GNUNET_TRANSPORT_monitor_peers ( * @param pic handle for the request to cancel */ void -GNUNET_TRANSPORT_monitor_peers_cancel ( +GNUNET_TRANSPORT_monitor_peers_cancel( struct GNUNET_TRANSPORT_PeerMonitoringContext *pic); @@ -414,9 +413,9 @@ typedef int (*GNUNET_TRANSPORT_BlacklistCallback) ( * @return NULL on error, otherwise handle for cancellation */ struct GNUNET_TRANSPORT_Blacklist * -GNUNET_TRANSPORT_blacklist (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_TRANSPORT_BlacklistCallback cb, - void *cb_cls); +GNUNET_TRANSPORT_blacklist(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_TRANSPORT_BlacklistCallback cb, + void *cb_cls); /** @@ -426,7 +425,7 @@ GNUNET_TRANSPORT_blacklist (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param br handle of the request that is to be cancelled */ void -GNUNET_TRANSPORT_blacklist_cancel (struct GNUNET_TRANSPORT_Blacklist *br); +GNUNET_TRANSPORT_blacklist_cancel(struct GNUNET_TRANSPORT_Blacklist *br); /** @@ -444,9 +443,7 @@ struct GNUNET_TRANSPORT_PluginSession; /** * Possible states of a session in a plugin. */ -enum GNUNET_TRANSPORT_SessionState -{ - +enum GNUNET_TRANSPORT_SessionState { /** * The session was created (first call for each session object). */ @@ -473,16 +470,13 @@ enum GNUNET_TRANSPORT_SessionState * Last call for each session object. */ GNUNET_TRANSPORT_SS_DONE - }; /** * Information about a plugin's session. */ -struct GNUNET_TRANSPORT_SessionInfo -{ - +struct GNUNET_TRANSPORT_SessionInfo { /** * New state of the session. */ @@ -561,9 +555,9 @@ typedef void (*GNUNET_TRANSPORT_SessionMonitorCallback) ( * @return NULL on error, otherwise handle for cancellation */ struct GNUNET_TRANSPORT_PluginMonitor * -GNUNET_TRANSPORT_monitor_plugins (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_TRANSPORT_SessionMonitorCallback cb, - void *cb_cls); +GNUNET_TRANSPORT_monitor_plugins(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_TRANSPORT_SessionMonitorCallback cb, + void *cb_cls); /** @@ -574,7 +568,7 @@ GNUNET_TRANSPORT_monitor_plugins (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param pm handle of the request that is to be cancelled */ void -GNUNET_TRANSPORT_monitor_plugins_cancel ( +GNUNET_TRANSPORT_monitor_plugins_cancel( struct GNUNET_TRANSPORT_PluginMonitor *pm); @@ -659,13 +653,13 @@ typedef void (*GNUNET_TRANSPORT_NotifyExcessBandwidth) ( * @return NULL on error */ struct GNUNET_TRANSPORT_CoreHandle * -GNUNET_TRANSPORT_core_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - const struct GNUNET_PeerIdentity *self, - const struct GNUNET_MQ_MessageHandler *handlers, - void *cls, - GNUNET_TRANSPORT_NotifyConnect nc, - GNUNET_TRANSPORT_NotifyDisconnect nd, - GNUNET_TRANSPORT_NotifyExcessBandwidth neb); +GNUNET_TRANSPORT_core_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + const struct GNUNET_PeerIdentity *self, + const struct GNUNET_MQ_MessageHandler *handlers, + void *cls, + GNUNET_TRANSPORT_NotifyConnect nc, + GNUNET_TRANSPORT_NotifyDisconnect nd, + GNUNET_TRANSPORT_NotifyExcessBandwidth neb); /** @@ -674,7 +668,7 @@ GNUNET_TRANSPORT_core_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param handle handle returned from connect */ void -GNUNET_TRANSPORT_core_disconnect (struct GNUNET_TRANSPORT_CoreHandle *handle); +GNUNET_TRANSPORT_core_disconnect(struct GNUNET_TRANSPORT_CoreHandle *handle); /** @@ -685,8 +679,8 @@ GNUNET_TRANSPORT_core_disconnect (struct GNUNET_TRANSPORT_CoreHandle *handle); * @return NULL if disconnected, otherwise message queue for @a peer */ struct GNUNET_MQ_Handle * -GNUNET_TRANSPORT_core_get_mq (struct GNUNET_TRANSPORT_CoreHandle *handle, - const struct GNUNET_PeerIdentity *peer); +GNUNET_TRANSPORT_core_get_mq(struct GNUNET_TRANSPORT_CoreHandle *handle, + const struct GNUNET_PeerIdentity *peer); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/include/gnunet_tun_lib.h b/src/include/gnunet_tun_lib.h index c01e641c1..941f394aa 100644 --- a/src/include/gnunet_tun_lib.h +++ b/src/include/gnunet_tun_lib.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Philipp Toelke @@ -78,8 +78,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Header from Linux TUN interface. */ -struct GNUNET_TUN_Layer2PacketHeader -{ +struct GNUNET_TUN_Layer2PacketHeader { /** * Some flags (unused). */ @@ -95,8 +94,7 @@ struct GNUNET_TUN_Layer2PacketHeader /** * Standard IPv4 header. */ -struct GNUNET_TUN_IPv4Header -{ +struct GNUNET_TUN_IPv4Header { #if __BYTE_ORDER == __LITTLE_ENDIAN unsigned int header_length : 4 GNUNET_PACKED; unsigned int version : 4 GNUNET_PACKED; @@ -152,8 +150,7 @@ struct GNUNET_TUN_IPv4Header /** * Standard IPv6 header. */ -struct GNUNET_TUN_IPv6Header -{ +struct GNUNET_TUN_IPv6Header { #if __BYTE_ORDER == __LITTLE_ENDIAN unsigned int traffic_class_h : 4 GNUNET_PACKED; unsigned int version : 4 GNUNET_PACKED; @@ -208,8 +205,7 @@ struct GNUNET_TUN_IPv6Header /** * TCP packet header. */ -struct GNUNET_TUN_TcpHeader -{ +struct GNUNET_TUN_TcpHeader { /** * Source port (in NBO). */ @@ -276,8 +272,7 @@ struct GNUNET_TUN_TcpHeader /** * UDP packet header. */ -struct GNUNET_TUN_UdpHeader -{ +struct GNUNET_TUN_UdpHeader { /** * Source port (in NBO). */ @@ -336,8 +331,7 @@ struct GNUNET_TUN_UdpHeader /** * DNS flags (largely RFC 1035 / RFC 2136). */ -struct GNUNET_TUN_DnsFlags -{ +struct GNUNET_TUN_DnsFlags { #if __BYTE_ORDER == __LITTLE_ENDIAN /** * Set to 1 if recursion is desired (client -> server) @@ -389,7 +383,6 @@ struct GNUNET_TUN_DnsFlags */ unsigned int recursion_available : 1 GNUNET_PACKED; #elif __BYTE_ORDER == __BIG_ENDIAN - /** * query:0, response:1 */ @@ -443,15 +436,13 @@ struct GNUNET_TUN_DnsFlags #else #error byteorder undefined #endif - } GNUNET_GCC_STRUCT_LAYOUT; /** * DNS header. */ -struct GNUNET_TUN_DnsHeader -{ +struct GNUNET_TUN_DnsHeader { /** * Unique identifier for the request/response. */ @@ -487,8 +478,7 @@ struct GNUNET_TUN_DnsHeader /** * Payload of DNS SOA record (header). */ -struct GNUNET_TUN_DnsSoaRecord -{ +struct GNUNET_TUN_DnsSoaRecord { /** * The version number of the original copy of the zone. (NBO) */ @@ -522,9 +512,7 @@ struct GNUNET_TUN_DnsSoaRecord /** * Payload of DNS SRV record (header). */ -struct GNUNET_TUN_DnsSrvRecord -{ - +struct GNUNET_TUN_DnsSrvRecord { /** * Preference for this entry (lower value is higher preference). Clients * will contact hosts from the lowest-priority group first and fall back @@ -551,9 +539,7 @@ struct GNUNET_TUN_DnsSrvRecord /** * Payload of DNS CERT record. */ -struct GNUNET_TUN_DnsCertRecord -{ - +struct GNUNET_TUN_DnsCertRecord { /** * Certificate type */ @@ -577,9 +563,7 @@ struct GNUNET_TUN_DnsCertRecord * Payload of DNSSEC TLSA record. * http://datatracker.ietf.org/doc/draft-ietf-dane-protocol/ */ -struct GNUNET_TUN_DnsTlsaRecord -{ - +struct GNUNET_TUN_DnsTlsaRecord { /** * Certificate usage * 0: CA cert @@ -623,8 +607,7 @@ struct GNUNET_TUN_DnsTlsaRecord /** * Payload of GNS VPN record */ -struct GNUNET_TUN_GnsVpnRecord -{ +struct GNUNET_TUN_GnsVpnRecord { /** * The peer to contact */ @@ -642,8 +625,7 @@ struct GNUNET_TUN_GnsVpnRecord /** * DNS query prefix. */ -struct GNUNET_TUN_DnsQueryLine -{ +struct GNUNET_TUN_DnsQueryLine { /** * Desired type (GNUNET_DNSPARSER_TYPE_XXX). (NBO) */ @@ -659,8 +641,7 @@ struct GNUNET_TUN_DnsQueryLine /** * General DNS record prefix. */ -struct GNUNET_TUN_DnsRecordLine -{ +struct GNUNET_TUN_DnsRecordLine { /** * Record type (GNUNET_DNSPARSER_TYPE_XXX). (NBO) */ @@ -703,19 +684,16 @@ struct GNUNET_TUN_DnsRecordLine /** * ICMP header. */ -struct GNUNET_TUN_IcmpHeader -{ +struct GNUNET_TUN_IcmpHeader { uint8_t type; uint8_t code; uint16_t crc GNUNET_PACKED; - union - { + union { /** * ICMP Echo (request/reply) */ - struct - { + struct { uint16_t identifier GNUNET_PACKED; uint16_t sequence_number GNUNET_PACKED; } echo; @@ -723,8 +701,7 @@ struct GNUNET_TUN_IcmpHeader /** * ICMP Destination Unreachable (RFC 1191) */ - struct ih_pmtu - { + struct ih_pmtu { uint16_t empty GNUNET_PACKED; uint16_t next_hop_mtu GNUNET_PACKED; /* followed by original IP header + first 8 bytes of original IP datagram @@ -740,7 +717,6 @@ struct GNUNET_TUN_IcmpHeader * MTU for packets that are too big (IPv6). */ uint32_t packet_too_big_mtu GNUNET_PACKED; - } quench; }; @@ -759,11 +735,11 @@ GNUNET_NETWORK_STRUCT_END * @param dst destination IP address to use */ void -GNUNET_TUN_initialize_ipv4_header (struct GNUNET_TUN_IPv4Header *ip, - uint8_t protocol, - uint16_t payload_length, - const struct in_addr *src, - const struct in_addr *dst); +GNUNET_TUN_initialize_ipv4_header(struct GNUNET_TUN_IPv4Header *ip, + uint8_t protocol, + uint16_t payload_length, + const struct in_addr *src, + const struct in_addr *dst); /** @@ -777,11 +753,11 @@ GNUNET_TUN_initialize_ipv4_header (struct GNUNET_TUN_IPv4Header *ip, * @param dst destination IP address to use */ void -GNUNET_TUN_initialize_ipv6_header (struct GNUNET_TUN_IPv6Header *ip, - uint8_t protocol, - uint16_t payload_length, - const struct in6_addr *src, - const struct in6_addr *dst); +GNUNET_TUN_initialize_ipv6_header(struct GNUNET_TUN_IPv6Header *ip, + uint8_t protocol, + uint16_t payload_length, + const struct in6_addr *src, + const struct in6_addr *dst); /** * Calculate IPv4 TCP checksum. @@ -792,10 +768,10 @@ GNUNET_TUN_initialize_ipv6_header (struct GNUNET_TUN_IPv6Header *ip, * @param payload_length number of bytes of TCP @a payload */ void -GNUNET_TUN_calculate_tcp4_checksum (const struct GNUNET_TUN_IPv4Header *ip, - struct GNUNET_TUN_TcpHeader *tcp, - const void *payload, - uint16_t payload_length); +GNUNET_TUN_calculate_tcp4_checksum(const struct GNUNET_TUN_IPv4Header *ip, + struct GNUNET_TUN_TcpHeader *tcp, + const void *payload, + uint16_t payload_length); /** * Calculate IPv6 TCP checksum. @@ -806,10 +782,10 @@ GNUNET_TUN_calculate_tcp4_checksum (const struct GNUNET_TUN_IPv4Header *ip, * @param payload_length number of bytes of TCP payload */ void -GNUNET_TUN_calculate_tcp6_checksum (const struct GNUNET_TUN_IPv6Header *ip, - struct GNUNET_TUN_TcpHeader *tcp, - const void *payload, - uint16_t payload_length); +GNUNET_TUN_calculate_tcp6_checksum(const struct GNUNET_TUN_IPv6Header *ip, + struct GNUNET_TUN_TcpHeader *tcp, + const void *payload, + uint16_t payload_length); /** * Calculate IPv4 UDP checksum. @@ -820,10 +796,10 @@ GNUNET_TUN_calculate_tcp6_checksum (const struct GNUNET_TUN_IPv6Header *ip, * @param payload_length number of bytes of UDP @a payload */ void -GNUNET_TUN_calculate_udp4_checksum (const struct GNUNET_TUN_IPv4Header *ip, - struct GNUNET_TUN_UdpHeader *udp, - const void *payload, - uint16_t payload_length); +GNUNET_TUN_calculate_udp4_checksum(const struct GNUNET_TUN_IPv4Header *ip, + struct GNUNET_TUN_UdpHeader *udp, + const void *payload, + uint16_t payload_length); /** @@ -835,10 +811,10 @@ GNUNET_TUN_calculate_udp4_checksum (const struct GNUNET_TUN_IPv4Header *ip, * @param payload_length number of bytes of @a payload */ void -GNUNET_TUN_calculate_udp6_checksum (const struct GNUNET_TUN_IPv6Header *ip, - struct GNUNET_TUN_UdpHeader *udp, - const void *payload, - uint16_t payload_length); +GNUNET_TUN_calculate_udp6_checksum(const struct GNUNET_TUN_IPv6Header *ip, + struct GNUNET_TUN_UdpHeader *udp, + const void *payload, + uint16_t payload_length); /** @@ -849,9 +825,9 @@ GNUNET_TUN_calculate_udp6_checksum (const struct GNUNET_TUN_IPv6Header *ip, * @param payload_length number of bytes of @a payload */ void -GNUNET_TUN_calculate_icmp_checksum (struct GNUNET_TUN_IcmpHeader *icmp, - const void *payload, - uint16_t payload_length); +GNUNET_TUN_calculate_icmp_checksum(struct GNUNET_TUN_IcmpHeader *icmp, + const void *payload, + uint16_t payload_length); /** @@ -863,9 +839,9 @@ GNUNET_TUN_calculate_icmp_checksum (struct GNUNET_TUN_IcmpHeader *icmp, * bytes long. */ void -GNUNET_TUN_ipv4toregexsearch (const struct in_addr *ip, - uint16_t port, - char *rxstr); +GNUNET_TUN_ipv4toregexsearch(const struct in_addr *ip, + uint16_t port, + char *rxstr); /** @@ -877,9 +853,9 @@ GNUNET_TUN_ipv4toregexsearch (const struct in_addr *ip, * bytes long. */ void -GNUNET_TUN_ipv6toregexsearch (const struct in6_addr *ipv6, - uint16_t port, - char *rxstr); +GNUNET_TUN_ipv6toregexsearch(const struct in6_addr *ipv6, + uint16_t port, + char *rxstr); /** @@ -892,7 +868,7 @@ GNUNET_TUN_ipv6toregexsearch (const struct in6_addr *ipv6, * @return regular expression, NULL on error */ char * -GNUNET_TUN_ipv6policy2regex (const char *policy); +GNUNET_TUN_ipv6policy2regex(const char *policy); /** @@ -905,7 +881,7 @@ GNUNET_TUN_ipv6policy2regex (const char *policy); * @return regular expression, NULL on error */ char * -GNUNET_TUN_ipv4policy2regex (const char *policy); +GNUNET_TUN_ipv4policy2regex(const char *policy); /** @@ -917,8 +893,8 @@ GNUNET_TUN_ipv4policy2regex (const char *policy); * @param[out] hc corresponding hash */ void -GNUNET_TUN_service_name_to_hash (const char *service_name, - struct GNUNET_HashCode *hc); +GNUNET_TUN_service_name_to_hash(const char *service_name, + struct GNUNET_HashCode *hc); /** @@ -930,9 +906,9 @@ GNUNET_TUN_service_name_to_hash (const char *service_name, * @return #GNUNET_YES if they are equal */ int -GNUNET_TUN_sockaddr_cmp (const struct sockaddr *sa, - const struct sockaddr *sb, - int include_port); +GNUNET_TUN_sockaddr_cmp(const struct sockaddr *sa, + const struct sockaddr *sb, + int include_port); /** @@ -945,9 +921,9 @@ GNUNET_TUN_sockaddr_cmp (const struct sockaddr *sa, * @param[out] cadet_port CADET port to use */ void -GNUNET_TUN_compute_service_cadet_port (const struct GNUNET_HashCode *desc, - uint16_t ip_port, - struct GNUNET_HashCode *cadet_port); +GNUNET_TUN_compute_service_cadet_port(const struct GNUNET_HashCode *desc, + uint16_t ip_port, + struct GNUNET_HashCode *cadet_port); #endif diff --git a/src/include/gnunet_util_lib.h b/src/include/gnunet_util_lib.h index a7bd7ce4b..24ad4e4e5 100644 --- a/src/include/gnunet_util_lib.h +++ b/src/include/gnunet_util_lib.h @@ -50,7 +50,7 @@ extern "C" /** * Smallest supported message. */ -#define GNUNET_MIN_MESSAGE_SIZE sizeof (struct GNUNET_MessageHeader) +#define GNUNET_MIN_MESSAGE_SIZE sizeof(struct GNUNET_MessageHeader) /** * NOTE: You MUST adjust this URL to point to the location of a diff --git a/src/include/gnunet_util_taler_wallet_lib.h b/src/include/gnunet_util_taler_wallet_lib.h index d986c29a4..a036824f6 100644 --- a/src/include/gnunet_util_taler_wallet_lib.h +++ b/src/include/gnunet_util_taler_wallet_lib.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . diff --git a/src/include/gnunet_vpn_service.h b/src/include/gnunet_vpn_service.h index 2096bf539..7e066b14f 100644 --- a/src/include/gnunet_vpn_service.h +++ b/src/include/gnunet_vpn_service.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -59,8 +59,8 @@ struct GNUNET_VPN_RedirectionRequest; * specified target peer; NULL on error */ typedef void (*GNUNET_VPN_AllocationCallback)(void *cls, - int af, - const void *address); + int af, + const void *address); /** @@ -69,7 +69,7 @@ typedef void (*GNUNET_VPN_AllocationCallback)(void *cls, * @param rr request to cancel */ void -GNUNET_VPN_cancel_request (struct GNUNET_VPN_RedirectionRequest *rr); +GNUNET_VPN_cancel_request(struct GNUNET_VPN_RedirectionRequest *rr); /** @@ -95,14 +95,14 @@ GNUNET_VPN_cancel_request (struct GNUNET_VPN_RedirectionRequest *rr); * anyway) */ struct GNUNET_VPN_RedirectionRequest * -GNUNET_VPN_redirect_to_peer (struct GNUNET_VPN_Handle *vh, - int result_af, - uint8_t protocol, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HashCode *serv, - struct GNUNET_TIME_Absolute expiration_time, - GNUNET_VPN_AllocationCallback cb, - void *cb_cls); +GNUNET_VPN_redirect_to_peer(struct GNUNET_VPN_Handle *vh, + int result_af, + uint8_t protocol, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HashCode *serv, + struct GNUNET_TIME_Absolute expiration_time, + GNUNET_VPN_AllocationCallback cb, + void *cb_cls); /** @@ -129,13 +129,13 @@ GNUNET_VPN_redirect_to_peer (struct GNUNET_VPN_Handle *vh, * anyway) */ struct GNUNET_VPN_RedirectionRequest * -GNUNET_VPN_redirect_to_ip (struct GNUNET_VPN_Handle *vh, - int result_af, - int addr_af, - const void *addr, - struct GNUNET_TIME_Absolute expiration_time, - GNUNET_VPN_AllocationCallback cb, - void *cb_cls); +GNUNET_VPN_redirect_to_ip(struct GNUNET_VPN_Handle *vh, + int result_af, + int addr_af, + const void *addr, + struct GNUNET_TIME_Absolute expiration_time, + GNUNET_VPN_AllocationCallback cb, + void *cb_cls); /** @@ -145,7 +145,7 @@ GNUNET_VPN_redirect_to_ip (struct GNUNET_VPN_Handle *vh, * @return VPN handle */ struct GNUNET_VPN_Handle * -GNUNET_VPN_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); +GNUNET_VPN_connect(const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -154,7 +154,7 @@ GNUNET_VPN_connect (const struct GNUNET_CONFIGURATION_Handle *cfg); * @param vh VPN handle */ void -GNUNET_VPN_disconnect (struct GNUNET_VPN_Handle *vh); +GNUNET_VPN_disconnect(struct GNUNET_VPN_Handle *vh); #endif diff --git a/src/include/platform.h b/src/include/platform.h index 6a3e8e4b8..e12d08e44 100644 --- a/src/include/platform.h +++ b/src/include/platform.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Nils Durner @@ -39,7 +39,7 @@ #endif #ifdef WINDOWS -#define BREAKPOINT asm("int $3;"); +#define BREAKPOINT asm ("int $3;"); #define GNUNET_SIGCHLD 17 #else #define BREAKPOINT @@ -223,11 +223,11 @@ /** * GNU gettext support macro. */ -#define _(String) dgettext(PACKAGE,String) +#define _(String) dgettext(PACKAGE, String) #define LIBEXTRACTOR_GETTEXT_DOMAIN "libextractor" #else #include "libintlemu.h" -#define _(String) dgettext("org.gnunet.gnunet",String) +#define _(String) dgettext("org.gnunet.gnunet", String) #define LIBEXTRACTOR_GETTEXT_DOMAIN "org.gnunet.libextractor" #endif @@ -249,7 +249,7 @@ #ifdef DARWIN #define __BYTE_ORDER BYTE_ORDER #define __BIG_ENDIAN BIG_ENDIAN - /* not available on darwin, override configure */ +/* not available on darwin, override configure */ #undef HAVE_STAT64 #undef HAVE_MREMAP #endif @@ -257,7 +257,7 @@ #if !HAVE_ATOLL long long -atoll (const char *nptr); +atoll(const char *nptr); #endif #if ENABLE_NLS diff --git a/src/include/tap-windows.h b/src/include/tap-windows.h index c9eb38eba..37f4129c0 100644 --- a/src/include/tap-windows.h +++ b/src/include/tap-windows.h @@ -37,25 +37,25 @@ * ============= */ -#define TAP_WIN_CONTROL_CODE(request,method) \ - CTL_CODE (FILE_DEVICE_UNKNOWN, request, method, FILE_ANY_ACCESS) +#define TAP_WIN_CONTROL_CODE(request, method) \ + CTL_CODE(FILE_DEVICE_UNKNOWN, request, method, FILE_ANY_ACCESS) /* Present in 8.1 */ -#define TAP_WIN_IOCTL_GET_MAC TAP_WIN_CONTROL_CODE (1, METHOD_BUFFERED) -#define TAP_WIN_IOCTL_GET_VERSION TAP_WIN_CONTROL_CODE (2, METHOD_BUFFERED) -#define TAP_WIN_IOCTL_GET_MTU TAP_WIN_CONTROL_CODE (3, METHOD_BUFFERED) -#define TAP_WIN_IOCTL_GET_INFO TAP_WIN_CONTROL_CODE (4, METHOD_BUFFERED) -#define TAP_WIN_IOCTL_CONFIG_POINT_TO_POINT TAP_WIN_CONTROL_CODE (5, METHOD_BUFFERED) -#define TAP_WIN_IOCTL_SET_MEDIA_STATUS TAP_WIN_CONTROL_CODE (6, METHOD_BUFFERED) -#define TAP_WIN_IOCTL_CONFIG_DHCP_MASQ TAP_WIN_CONTROL_CODE (7, METHOD_BUFFERED) -#define TAP_WIN_IOCTL_GET_LOG_LINE TAP_WIN_CONTROL_CODE (8, METHOD_BUFFERED) -#define TAP_WIN_IOCTL_CONFIG_DHCP_SET_OPT TAP_WIN_CONTROL_CODE (9, METHOD_BUFFERED) +#define TAP_WIN_IOCTL_GET_MAC TAP_WIN_CONTROL_CODE(1, METHOD_BUFFERED) +#define TAP_WIN_IOCTL_GET_VERSION TAP_WIN_CONTROL_CODE(2, METHOD_BUFFERED) +#define TAP_WIN_IOCTL_GET_MTU TAP_WIN_CONTROL_CODE(3, METHOD_BUFFERED) +#define TAP_WIN_IOCTL_GET_INFO TAP_WIN_CONTROL_CODE(4, METHOD_BUFFERED) +#define TAP_WIN_IOCTL_CONFIG_POINT_TO_POINT TAP_WIN_CONTROL_CODE(5, METHOD_BUFFERED) +#define TAP_WIN_IOCTL_SET_MEDIA_STATUS TAP_WIN_CONTROL_CODE(6, METHOD_BUFFERED) +#define TAP_WIN_IOCTL_CONFIG_DHCP_MASQ TAP_WIN_CONTROL_CODE(7, METHOD_BUFFERED) +#define TAP_WIN_IOCTL_GET_LOG_LINE TAP_WIN_CONTROL_CODE(8, METHOD_BUFFERED) +#define TAP_WIN_IOCTL_CONFIG_DHCP_SET_OPT TAP_WIN_CONTROL_CODE(9, METHOD_BUFFERED) /* Added in 8.2 */ /* obsoletes TAP_WIN_IOCTL_CONFIG_POINT_TO_POINT */ -#define TAP_WIN_IOCTL_CONFIG_TUN TAP_WIN_CONTROL_CODE (10, METHOD_BUFFERED) +#define TAP_WIN_IOCTL_CONFIG_TUN TAP_WIN_CONTROL_CODE(10, METHOD_BUFFERED) /* * ================= diff --git a/src/include/winproc.h b/src/include/winproc.h index 3910321d7..139f07e61 100644 --- a/src/include/winproc.h +++ b/src/include/winproc.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Nils Durner @@ -60,175 +60,174 @@ extern "C" #define MAX_NAME_LENGTH 25 #endif - typedef DWORD WINAPI (*TNtQuerySystemInformation) (int, PVOID, ULONG, PULONG); - typedef DWORD WINAPI (*TGetIfEntry) (PMIB_IFROW pIfRow); - typedef DWORD WINAPI (*TGetIpAddrTable) (PMIB_IPADDRTABLE pIpAddrTable, - PULONG pdwSize, BOOL bOrder); - typedef DWORD WINAPI (*TGetIfTable) (PMIB_IFTABLE pIfTable, PULONG pdwSize, - BOOL bOrder); - typedef DWORD WINAPI (*TGetBestInterfaceEx) (struct sockaddr *, PDWORD); - /* TODO: Explicitly import -A variants (i.e. TCreateHardLinkA) or -W - * variants (TCreateHardLinkW), etc. - */ - typedef DWORD WINAPI (*TCreateHardLink) (LPCTSTR lpFileName, - LPCTSTR lpExistingFileName, - LPSECURITY_ATTRIBUTES - lpSecurityAttributes); - typedef SC_HANDLE WINAPI (*TOpenSCManager) (LPCTSTR lpMachineName, - LPCTSTR lpDatabaseName, - DWORD dwDesiredAccess); - typedef SC_HANDLE WINAPI (*TCreateService) (SC_HANDLE hSCManager, - LPCTSTR lpServiceName, - LPCTSTR lpDisplayName, - DWORD dwDesiredAccess, - DWORD dwServiceType, - DWORD dwStartType, - DWORD dwErrorControl, - LPCTSTR lpBinaryPathName, - LPCTSTR lpLoadOrderGroup, - LPDWORD lpdwTagId, - LPCTSTR lpDependencies, - LPCTSTR lpServiceStartName, - LPCTSTR lpPassword); - typedef BOOL WINAPI (*TCloseServiceHandle) (SC_HANDLE hSCObject); - typedef BOOL WINAPI (*TDeleteService) (SC_HANDLE hService); - typedef SERVICE_STATUS_HANDLE WINAPI (*TRegisterServiceCtrlHandler) (LPCTSTR - lpServiceName, - LPHANDLER_FUNCTION - lpHandlerProc); - typedef BOOL WINAPI (*TSetServiceStatus) (SERVICE_STATUS_HANDLE - hServiceStatus, - LPSERVICE_STATUS lpServiceStatus); - typedef BOOL WINAPI (*TStartServiceCtrlDispatcher) (const - LPSERVICE_TABLE_ENTRY - lpServiceTable); - typedef BOOL WINAPI (*TControlService) (SC_HANDLE hService, DWORD dwControl, - LPSERVICE_STATUS lpServiceStatus); - typedef SC_HANDLE WINAPI (*TOpenService) (SC_HANDLE hSCManager, - LPCTSTR lpServiceName, +typedef DWORD WINAPI (*TNtQuerySystemInformation) (int, PVOID, ULONG, PULONG); +typedef DWORD WINAPI (*TGetIfEntry) (PMIB_IFROW pIfRow); +typedef DWORD WINAPI (*TGetIpAddrTable) (PMIB_IPADDRTABLE pIpAddrTable, + PULONG pdwSize, BOOL bOrder); +typedef DWORD WINAPI (*TGetIfTable) (PMIB_IFTABLE pIfTable, PULONG pdwSize, + BOOL bOrder); +typedef DWORD WINAPI (*TGetBestInterfaceEx) (struct sockaddr *, PDWORD); +/* TODO: Explicitly import -A variants (i.e. TCreateHardLinkA) or -W + * variants (TCreateHardLinkW), etc. + */ +typedef DWORD WINAPI (*TCreateHardLink) (LPCTSTR lpFileName, + LPCTSTR lpExistingFileName, + LPSECURITY_ATTRIBUTES + lpSecurityAttributes); +typedef SC_HANDLE WINAPI (*TOpenSCManager) (LPCTSTR lpMachineName, + LPCTSTR lpDatabaseName, DWORD dwDesiredAccess); - typedef DWORD WINAPI (*TGetAdaptersInfo) (PIP_ADAPTER_INFO pAdapterInfo, - PULONG pOutBufLen); - typedef NET_API_STATUS WINAPI (*TNetUserAdd) (LPCWSTR, DWORD, PBYTE, PDWORD); - typedef NET_API_STATUS WINAPI (*TNetUserSetInfo) (LPCWSTR servername, - LPCWSTR username, - DWORD level, LPBYTE buf, - LPDWORD param_err); - typedef NTSTATUS NTAPI (*TLsaOpenPolicy) (PLSA_UNICODE_STRING, - PLSA_OBJECT_ATTRIBUTES, ACCESS_MASK, - PLSA_HANDLE); - typedef NTSTATUS NTAPI (*TLsaAddAccountRights) (LSA_HANDLE, PSID, - PLSA_UNICODE_STRING, ULONG); - typedef NTSTATUS NTAPI (*TLsaRemoveAccountRights) (LSA_HANDLE, PSID, BOOLEAN, - PLSA_UNICODE_STRING, - ULONG); - typedef NTSTATUS NTAPI (*TLsaClose) (LSA_HANDLE); - typedef BOOL WINAPI (*TLookupAccountName) (LPCTSTR lpSystemName, - LPCTSTR lpAccountName, PSID Sid, - LPDWORD cbSid, - LPTSTR ReferencedDomainName, - LPDWORD cchReferencedDomainName, - PSID_NAME_USE peUse); - - typedef BOOL WINAPI (*TGetFileSecurity) (LPCTSTR lpFileName, - SECURITY_INFORMATION - RequestedInformation, - PSECURITY_DESCRIPTOR - pSecurityDescriptor, DWORD nLength, - LPDWORD lpnLengthNeeded); - typedef BOOL WINAPI (*TInitializeSecurityDescriptor) (PSECURITY_DESCRIPTOR - pSecurityDescriptor, - DWORD dwRevision); - typedef BOOL WINAPI (*TGetSecurityDescriptorDacl) (PSECURITY_DESCRIPTOR - pSecurityDescriptor, - LPBOOL lpbDaclPresent, - PACL * pDacl, - LPBOOL lpbDaclDefaulted); - typedef BOOL WINAPI (*TGetAclInformation) (PACL pAcl, LPVOID pAclInformation, - DWORD nAclInformationLength, - ACL_INFORMATION_CLASS - dwAclInformationClass); - typedef BOOL WINAPI (*TInitializeAcl) (PACL pAcl, DWORD nAclLength, - DWORD dwAclRevision); - typedef BOOL WINAPI (*TGetAce) (PACL pAcl, DWORD dwAceIndex, LPVOID * pAce); - typedef BOOL WINAPI (*TEqualSid) (PSID pSid1, PSID pSid2); - typedef BOOL WINAPI (*TAddAce) (PACL pAcl, DWORD dwAceRevision, - DWORD dwStartingAceIndex, LPVOID pAceList, - DWORD nAceListLength); - typedef BOOL WINAPI (*TAddAccessAllowedAce) (PACL pAcl, DWORD dwAceRevision, - DWORD AccessMask, PSID pSid); - typedef BOOL WINAPI (*TSetNamedSecurityInfo) (LPTSTR pObjectName, - SE_OBJECT_TYPE ObjectType, - SECURITY_INFORMATION - SecurityInfo, PSID psidOwner, - PSID psidGroup, PACL pDacl, - PACL pSacl); - - extern TGetBestInterfaceEx GNGetBestInterfaceEx; - extern TNtQuerySystemInformation GNNtQuerySystemInformation; - extern TGetIfEntry GNGetIfEntry; - extern TGetIpAddrTable GNGetIpAddrTable; - extern TGetIfTable GNGetIfTable; - extern TCreateHardLink GNCreateHardLink; - extern TOpenSCManager GNOpenSCManager; - extern TCreateService GNCreateService; - extern TCloseServiceHandle GNCloseServiceHandle; - extern TDeleteService GNDeleteService; - extern TRegisterServiceCtrlHandler GNRegisterServiceCtrlHandler; - extern TSetServiceStatus GNSetServiceStatus; - extern TStartServiceCtrlDispatcher GNStartServiceCtrlDispatcher; - extern TControlService GNControlService; - extern TOpenService GNOpenService; - extern TGetAdaptersInfo GNGetAdaptersInfo; - extern TNetUserAdd GNNetUserAdd; - extern TNetUserSetInfo GNNetUserSetInfo; - extern TLsaOpenPolicy GNLsaOpenPolicy; - extern TLsaAddAccountRights GNLsaAddAccountRights; - extern TLsaRemoveAccountRights GNLsaRemoveAccountRights; - extern TLsaClose GNLsaClose; - extern TLookupAccountName GNLookupAccountName; - extern TGetFileSecurity GNGetFileSecurity; - extern TInitializeSecurityDescriptor GNInitializeSecurityDescriptor; - extern TGetSecurityDescriptorDacl GNGetSecurityDescriptorDacl; - extern TGetAclInformation GNGetAclInformation; - extern TInitializeAcl GNInitializeAcl; - extern TGetAce GNGetAce; - extern TEqualSid GNEqualSid; - extern TAddAce GNAddAce; - extern TAddAccessAllowedAce GNAddAccessAllowedAce; - extern TSetNamedSecurityInfo GNSetNamedSecurityInfo; - - - BOOL CreateShortcut (const char *pszSrc, const char *pszDest); - BOOL DereferenceShortcut (char *pszShortcut); - long QueryRegistry (HKEY hMainKey, const char *pszKey, const char *pszSubKey, - char *pszBuffer, long *pdLength); - int ListNICs (void (*callback) (void *, const char *, int), void *cls); - BOOL AddPathAccessRights (char *lpszFileName, char *lpszAccountName, - DWORD dwAccessMask); - char *winErrorStr (const char *prefix, int dwErr); - void EnumNICs (PMIB_IFTABLE * pIfTable, PMIB_IPADDRTABLE * pAddrTable); +typedef SC_HANDLE WINAPI (*TCreateService) (SC_HANDLE hSCManager, + LPCTSTR lpServiceName, + LPCTSTR lpDisplayName, + DWORD dwDesiredAccess, + DWORD dwServiceType, + DWORD dwStartType, + DWORD dwErrorControl, + LPCTSTR lpBinaryPathName, + LPCTSTR lpLoadOrderGroup, + LPDWORD lpdwTagId, + LPCTSTR lpDependencies, + LPCTSTR lpServiceStartName, + LPCTSTR lpPassword); +typedef BOOL WINAPI (*TCloseServiceHandle) (SC_HANDLE hSCObject); +typedef BOOL WINAPI (*TDeleteService) (SC_HANDLE hService); +typedef SERVICE_STATUS_HANDLE WINAPI (*TRegisterServiceCtrlHandler) (LPCTSTR + lpServiceName, + LPHANDLER_FUNCTION + lpHandlerProc); +typedef BOOL WINAPI (*TSetServiceStatus) (SERVICE_STATUS_HANDLE + hServiceStatus, + LPSERVICE_STATUS lpServiceStatus); +typedef BOOL WINAPI (*TStartServiceCtrlDispatcher) (const + LPSERVICE_TABLE_ENTRY + lpServiceTable); +typedef BOOL WINAPI (*TControlService) (SC_HANDLE hService, DWORD dwControl, + LPSERVICE_STATUS lpServiceStatus); +typedef SC_HANDLE WINAPI (*TOpenService) (SC_HANDLE hSCManager, + LPCTSTR lpServiceName, + DWORD dwDesiredAccess); +typedef DWORD WINAPI (*TGetAdaptersInfo) (PIP_ADAPTER_INFO pAdapterInfo, + PULONG pOutBufLen); +typedef NET_API_STATUS WINAPI (*TNetUserAdd) (LPCWSTR, DWORD, PBYTE, PDWORD); +typedef NET_API_STATUS WINAPI (*TNetUserSetInfo) (LPCWSTR servername, + LPCWSTR username, + DWORD level, LPBYTE buf, + LPDWORD param_err); +typedef NTSTATUS NTAPI (*TLsaOpenPolicy) (PLSA_UNICODE_STRING, + PLSA_OBJECT_ATTRIBUTES, ACCESS_MASK, + PLSA_HANDLE); +typedef NTSTATUS NTAPI (*TLsaAddAccountRights) (LSA_HANDLE, PSID, + PLSA_UNICODE_STRING, ULONG); +typedef NTSTATUS NTAPI (*TLsaRemoveAccountRights) (LSA_HANDLE, PSID, BOOLEAN, + PLSA_UNICODE_STRING, + ULONG); +typedef NTSTATUS NTAPI (*TLsaClose) (LSA_HANDLE); +typedef BOOL WINAPI (*TLookupAccountName) (LPCTSTR lpSystemName, + LPCTSTR lpAccountName, PSID Sid, + LPDWORD cbSid, + LPTSTR ReferencedDomainName, + LPDWORD cchReferencedDomainName, + PSID_NAME_USE peUse); + +typedef BOOL WINAPI (*TGetFileSecurity) (LPCTSTR lpFileName, + SECURITY_INFORMATION + RequestedInformation, + PSECURITY_DESCRIPTOR + pSecurityDescriptor, DWORD nLength, + LPDWORD lpnLengthNeeded); +typedef BOOL WINAPI (*TInitializeSecurityDescriptor) (PSECURITY_DESCRIPTOR + pSecurityDescriptor, + DWORD dwRevision); +typedef BOOL WINAPI (*TGetSecurityDescriptorDacl) (PSECURITY_DESCRIPTOR + pSecurityDescriptor, + LPBOOL lpbDaclPresent, + PACL * pDacl, + LPBOOL lpbDaclDefaulted); +typedef BOOL WINAPI (*TGetAclInformation) (PACL pAcl, LPVOID pAclInformation, + DWORD nAclInformationLength, + ACL_INFORMATION_CLASS + dwAclInformationClass); +typedef BOOL WINAPI (*TInitializeAcl) (PACL pAcl, DWORD nAclLength, + DWORD dwAclRevision); +typedef BOOL WINAPI (*TGetAce) (PACL pAcl, DWORD dwAceIndex, LPVOID * pAce); +typedef BOOL WINAPI (*TEqualSid) (PSID pSid1, PSID pSid2); +typedef BOOL WINAPI (*TAddAce) (PACL pAcl, DWORD dwAceRevision, + DWORD dwStartingAceIndex, LPVOID pAceList, + DWORD nAceListLength); +typedef BOOL WINAPI (*TAddAccessAllowedAce) (PACL pAcl, DWORD dwAceRevision, + DWORD AccessMask, PSID pSid); +typedef BOOL WINAPI (*TSetNamedSecurityInfo) (LPTSTR pObjectName, + SE_OBJECT_TYPE ObjectType, + SECURITY_INFORMATION + SecurityInfo, PSID psidOwner, + PSID psidGroup, PACL pDacl, + PACL pSacl); + +extern TGetBestInterfaceEx GNGetBestInterfaceEx; +extern TNtQuerySystemInformation GNNtQuerySystemInformation; +extern TGetIfEntry GNGetIfEntry; +extern TGetIpAddrTable GNGetIpAddrTable; +extern TGetIfTable GNGetIfTable; +extern TCreateHardLink GNCreateHardLink; +extern TOpenSCManager GNOpenSCManager; +extern TCreateService GNCreateService; +extern TCloseServiceHandle GNCloseServiceHandle; +extern TDeleteService GNDeleteService; +extern TRegisterServiceCtrlHandler GNRegisterServiceCtrlHandler; +extern TSetServiceStatus GNSetServiceStatus; +extern TStartServiceCtrlDispatcher GNStartServiceCtrlDispatcher; +extern TControlService GNControlService; +extern TOpenService GNOpenService; +extern TGetAdaptersInfo GNGetAdaptersInfo; +extern TNetUserAdd GNNetUserAdd; +extern TNetUserSetInfo GNNetUserSetInfo; +extern TLsaOpenPolicy GNLsaOpenPolicy; +extern TLsaAddAccountRights GNLsaAddAccountRights; +extern TLsaRemoveAccountRights GNLsaRemoveAccountRights; +extern TLsaClose GNLsaClose; +extern TLookupAccountName GNLookupAccountName; +extern TGetFileSecurity GNGetFileSecurity; +extern TInitializeSecurityDescriptor GNInitializeSecurityDescriptor; +extern TGetSecurityDescriptorDacl GNGetSecurityDescriptorDacl; +extern TGetAclInformation GNGetAclInformation; +extern TInitializeAcl GNInitializeAcl; +extern TGetAce GNGetAce; +extern TEqualSid GNEqualSid; +extern TAddAce GNAddAce; +extern TAddAccessAllowedAce GNAddAccessAllowedAce; +extern TSetNamedSecurityInfo GNSetNamedSecurityInfo; + + +BOOL CreateShortcut(const char *pszSrc, const char *pszDest); +BOOL DereferenceShortcut(char *pszShortcut); +long QueryRegistry(HKEY hMainKey, const char *pszKey, const char *pszSubKey, + char *pszBuffer, long *pdLength); +int ListNICs(void (*callback)(void *, const char *, int), void *cls); +BOOL AddPathAccessRights(char *lpszFileName, char *lpszAccountName, + DWORD dwAccessMask); +char *winErrorStr(const char *prefix, int dwErr); +void EnumNICs(PMIB_IFTABLE * pIfTable, PMIB_IPADDRTABLE * pAddrTable); #define ENUMNICS3_MASK_OK 0x01 #define ENUMNICS3_BCAST_OK 0x02 - struct EnumNICs3_results - { - unsigned char flags; - int is_default; - char pretty_name[1001]; - size_t addr_size; - SOCKADDR_STORAGE address; - SOCKADDR_STORAGE mask; - SOCKADDR_STORAGE broadcast; - }; - - int EnumNICs3 (struct EnumNICs3_results **, int *EnumNICs3_results_count); - void EnumNICs3_free (struct EnumNICs3_results *); - int GNInitWinEnv (); - void GNShutdownWinEnv (); - - BOOL SafeTerminateProcess (HANDLE hProcess, UINT uExitCode, DWORD dwTimeout); +struct EnumNICs3_results { + unsigned char flags; + int is_default; + char pretty_name[1001]; + size_t addr_size; + SOCKADDR_STORAGE address; + SOCKADDR_STORAGE mask; + SOCKADDR_STORAGE broadcast; +}; + +int EnumNICs3(struct EnumNICs3_results **, int *EnumNICs3_results_count); +void EnumNICs3_free(struct EnumNICs3_results *); +int GNInitWinEnv(); +void GNShutdownWinEnv(); + +BOOL SafeTerminateProcess(HANDLE hProcess, UINT uExitCode, DWORD dwTimeout); #ifdef __cplusplus } #endif diff --git a/src/json/json.c b/src/json/json.c index fe6117c20..ecdea0294 100644 --- a/src/json/json.c +++ b/src/json/json.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2014-2017 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2014-2017 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file json/json.c * @brief functions to parse JSON snippets @@ -42,34 +42,34 @@ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ int -GNUNET_JSON_parse (const json_t *root, - struct GNUNET_JSON_Specification *spec, - const char **error_json_name, - unsigned int *error_line) +GNUNET_JSON_parse(const json_t *root, + struct GNUNET_JSON_Specification *spec, + const char **error_json_name, + unsigned int *error_line) { if (NULL == root) return GNUNET_SYSERR; for (unsigned int i = 0; NULL != spec[i].parser; i++) - { - json_t *pos; - - if (NULL == spec[i].field) - pos = (json_t *) root; - else - pos = json_object_get (root, spec[i].field); - if ((NULL == pos) && (spec[i].is_optional)) - continue; - if ((NULL == pos) || - (GNUNET_OK != spec[i].parser (spec[i].cls, pos, &spec[i]))) { - if (NULL != error_json_name) - *error_json_name = spec[i].field; - if (NULL != error_line) - *error_line = i; - GNUNET_JSON_parse_free (spec); - return GNUNET_SYSERR; + json_t *pos; + + if (NULL == spec[i].field) + pos = (json_t *)root; + else + pos = json_object_get(root, spec[i].field); + if ((NULL == pos) && (spec[i].is_optional)) + continue; + if ((NULL == pos) || + (GNUNET_OK != spec[i].parser(spec[i].cls, pos, &spec[i]))) + { + if (NULL != error_json_name) + *error_json_name = spec[i].field; + if (NULL != error_line) + *error_line = i; + GNUNET_JSON_parse_free(spec); + return GNUNET_SYSERR; + } } - } return GNUNET_OK; /* all OK! */ } @@ -81,7 +81,7 @@ GNUNET_JSON_parse (const json_t *root, * @return spec copy of @a spec with optional bit set */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_mark_optional (struct GNUNET_JSON_Specification spec) +GNUNET_JSON_spec_mark_optional(struct GNUNET_JSON_Specification spec) { struct GNUNET_JSON_Specification ret = spec; @@ -97,11 +97,11 @@ GNUNET_JSON_spec_mark_optional (struct GNUNET_JSON_Specification spec) * @param spec specification of the parse operation */ void -GNUNET_JSON_parse_free (struct GNUNET_JSON_Specification *spec) +GNUNET_JSON_parse_free(struct GNUNET_JSON_Specification *spec) { for (unsigned int i = 0; NULL != spec[i].parser; i++) if (NULL != spec[i].cleaner) - spec[i].cleaner (spec[i].cls, &spec[i]); + spec[i].cleaner(spec[i].cls, &spec[i]); } @@ -118,24 +118,24 @@ GNUNET_JSON_parse_free (struct GNUNET_JSON_Specification *spec) * @return #GNUNET_OK if parsing the value worked */ static int -set_json (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, - void *scls, - const char *option, - const char *value) +set_json(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, + void *scls, + const char *option, + const char *value) { json_t **json = scls; json_error_t error; - *json = json_loads (value, JSON_REJECT_DUPLICATES, &error); + *json = json_loads(value, JSON_REJECT_DUPLICATES, &error); if (NULL == *json) - { - fprintf (stderr, - _ ("Failed to parse JSON in option `%s': %s (%s)\n"), - option, - error.text, - error.source); - return GNUNET_SYSERR; - } + { + fprintf(stderr, + _("Failed to parse JSON in option `%s': %s (%s)\n"), + option, + error.text, + error.source); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -150,19 +150,19 @@ set_json (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, * @param[out] val set to the JSON specified at the command line */ struct GNUNET_GETOPT_CommandLineOption -GNUNET_JSON_getopt (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - json_t **json) +GNUNET_JSON_getopt(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + json_t **json) { - struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = shortName, - .name = name, - .argumentHelp = argumentHelp, - .description = description, - .require_argument = 1, - .processor = &set_json, - .scls = (void *) json}; + struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName, + .name = name, + .argumentHelp = argumentHelp, + .description = description, + .require_argument = 1, + .processor = &set_json, + .scls = (void *)json }; return clo; } diff --git a/src/json/json_generator.c b/src/json/json_generator.c index de6898da6..61993c86a 100644 --- a/src/json/json_generator.c +++ b/src/json/json_generator.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2014, 2015, 2016 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2014, 2015, 2016 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file json/json_generator.c * @brief helper functions for generating JSON from GNUnet data structures @@ -36,15 +36,15 @@ * @return json string that encodes @a data */ json_t * -GNUNET_JSON_from_data (const void *data, - size_t size) +GNUNET_JSON_from_data(const void *data, + size_t size) { char *buf; json_t *json; - buf = GNUNET_STRINGS_data_to_string_alloc (data, size); - json = json_string (buf); - GNUNET_free (buf); + buf = GNUNET_STRINGS_data_to_string_alloc(data, size); + json = json_string(buf); + GNUNET_free(buf); return json; } @@ -56,22 +56,22 @@ GNUNET_JSON_from_data (const void *data, * @return a json string with the timestamp in @a stamp */ json_t * -GNUNET_JSON_from_time_abs (struct GNUNET_TIME_Absolute stamp) +GNUNET_JSON_from_time_abs(struct GNUNET_TIME_Absolute stamp) { json_t *j; char *mystr; int ret; - GNUNET_assert (GNUNET_OK == - GNUNET_TIME_round_abs (&stamp)); + GNUNET_assert(GNUNET_OK == + GNUNET_TIME_round_abs(&stamp)); if (stamp.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us) - return json_string ("/never/"); - ret = GNUNET_asprintf (&mystr, - "/Date(%llu)/", - (unsigned long long) (stamp.abs_value_us / (1000LL * 1000LL))); - GNUNET_assert (ret > 0); - j = json_string (mystr); - GNUNET_free (mystr); + return json_string("/never/"); + ret = GNUNET_asprintf(&mystr, + "/Date(%llu)/", + (unsigned long long)(stamp.abs_value_us / (1000LL * 1000LL))); + GNUNET_assert(ret > 0); + j = json_string(mystr); + GNUNET_free(mystr); return j; } @@ -83,9 +83,9 @@ GNUNET_JSON_from_time_abs (struct GNUNET_TIME_Absolute stamp) * @return a json string with the timestamp in @a stamp */ json_t * -GNUNET_JSON_from_time_abs_nbo (struct GNUNET_TIME_AbsoluteNBO stamp) +GNUNET_JSON_from_time_abs_nbo(struct GNUNET_TIME_AbsoluteNBO stamp) { - return GNUNET_JSON_from_time_abs (GNUNET_TIME_absolute_ntoh (stamp)); + return GNUNET_JSON_from_time_abs(GNUNET_TIME_absolute_ntoh(stamp)); } @@ -96,22 +96,22 @@ GNUNET_JSON_from_time_abs_nbo (struct GNUNET_TIME_AbsoluteNBO stamp) * @return a json string with the timestamp in @a stamp */ json_t * -GNUNET_JSON_from_time_rel (struct GNUNET_TIME_Relative stamp) +GNUNET_JSON_from_time_rel(struct GNUNET_TIME_Relative stamp) { json_t *j; char *mystr; int ret; - GNUNET_assert (GNUNET_OK == - GNUNET_TIME_round_rel (&stamp)); + GNUNET_assert(GNUNET_OK == + GNUNET_TIME_round_rel(&stamp)); if (stamp.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) - return json_string ("/forever/"); - ret = GNUNET_asprintf (&mystr, - "/Delay(%llu)/", - (unsigned long long) (stamp.rel_value_us / (1000LL * 1000LL))); - GNUNET_assert (ret > 0); - j = json_string (mystr); - GNUNET_free (mystr); + return json_string("/forever/"); + ret = GNUNET_asprintf(&mystr, + "/Delay(%llu)/", + (unsigned long long)(stamp.rel_value_us / (1000LL * 1000LL))); + GNUNET_assert(ret > 0); + j = json_string(mystr); + GNUNET_free(mystr); return j; } @@ -123,17 +123,17 @@ GNUNET_JSON_from_time_rel (struct GNUNET_TIME_Relative stamp) * @return corresponding JSON encoding */ json_t * -GNUNET_JSON_from_rsa_public_key (const struct GNUNET_CRYPTO_RsaPublicKey *pk) +GNUNET_JSON_from_rsa_public_key(const struct GNUNET_CRYPTO_RsaPublicKey *pk) { char *buf; size_t buf_len; json_t *ret; - buf_len = GNUNET_CRYPTO_rsa_public_key_encode (pk, - &buf); - ret = GNUNET_JSON_from_data (buf, - buf_len); - GNUNET_free (buf); + buf_len = GNUNET_CRYPTO_rsa_public_key_encode(pk, + &buf); + ret = GNUNET_JSON_from_data(buf, + buf_len); + GNUNET_free(buf); return ret; } @@ -145,17 +145,17 @@ GNUNET_JSON_from_rsa_public_key (const struct GNUNET_CRYPTO_RsaPublicKey *pk) * @return corresponding JSON encoding */ json_t * -GNUNET_JSON_from_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *sig) +GNUNET_JSON_from_rsa_signature(const struct GNUNET_CRYPTO_RsaSignature *sig) { char *buf; size_t buf_len; json_t *ret; - buf_len = GNUNET_CRYPTO_rsa_signature_encode (sig, - &buf); - ret = GNUNET_JSON_from_data (buf, - buf_len); - GNUNET_free (buf); + buf_len = GNUNET_CRYPTO_rsa_signature_encode(sig, + &buf); + ret = GNUNET_JSON_from_data(buf, + buf_len); + GNUNET_free(buf); return ret; } @@ -167,9 +167,9 @@ GNUNET_JSON_from_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *sig) * @return corresponding JSON encoding */ json_t * -GNUNET_JSON_from_gnsrecord (const char* rname, - const struct GNUNET_GNSRECORD_Data *rd, - unsigned int rd_count) +GNUNET_JSON_from_gnsrecord(const char* rname, + const struct GNUNET_GNSRECORD_Data *rd, + unsigned int rd_count) { struct GNUNET_TIME_Absolute expiration_time; const char *expiration_time_str; @@ -179,36 +179,36 @@ GNUNET_JSON_from_gnsrecord (const char* rname, json_t *record; json_t *records; - data = json_object (); - json_object_set_new (data, - "record_name", - json_string (rname)); - records = json_array (); + data = json_object(); + json_object_set_new(data, + "record_name", + json_string(rname)); + records = json_array(); for (int i = 0; i < rd_count; i++) - { - value_str = GNUNET_GNSRECORD_value_to_string (rd[i].record_type, - rd[i].data, - rd[i].data_size); - expiration_time = GNUNET_GNSRECORD_record_get_expiration_time(1, &rd[i]); - expiration_time_str = GNUNET_STRINGS_absolute_time_to_string (expiration_time); - record_type_str = GNUNET_GNSRECORD_number_to_typename (rd[i].record_type); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Packing %s %s %s %d\n", - value_str, record_type_str, expiration_time_str, rd[i].flags); - record = json_pack ("{s:s,s:s,s:s,s:i}", - "value", - value_str, - "record_type", - record_type_str, - "expiration_time", - expiration_time_str, - "flag", - rd[i].flags); - GNUNET_assert (NULL != record); - GNUNET_free (value_str); - json_array_append_new (records, record); - } - json_object_set_new (data, "data", records); + { + value_str = GNUNET_GNSRECORD_value_to_string(rd[i].record_type, + rd[i].data, + rd[i].data_size); + expiration_time = GNUNET_GNSRECORD_record_get_expiration_time(1, &rd[i]); + expiration_time_str = GNUNET_STRINGS_absolute_time_to_string(expiration_time); + record_type_str = GNUNET_GNSRECORD_number_to_typename(rd[i].record_type); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Packing %s %s %s %d\n", + value_str, record_type_str, expiration_time_str, rd[i].flags); + record = json_pack("{s:s,s:s,s:s,s:i}", + "value", + value_str, + "record_type", + record_type_str, + "expiration_time", + expiration_time_str, + "flag", + rd[i].flags); + GNUNET_assert(NULL != record); + GNUNET_free(value_str); + json_array_append_new(records, record); + } + json_object_set_new(data, "data", records); return data; } diff --git a/src/json/json_gnsrecord.c b/src/json/json_gnsrecord.c index 2ba4da591..5991683bb 100644 --- a/src/json/json_gnsrecord.c +++ b/src/json/json_gnsrecord.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file json/json_gnsrecord.c @@ -35,8 +35,7 @@ #define GNUNET_JSON_GNSRECORD_RECORD_NAME "record_name" #define GNUNET_JSON_GNSRECORD_NEVER "never" -struct GnsRecordInfo -{ +struct GnsRecordInfo { char **name; unsigned int *rd_count; @@ -46,20 +45,20 @@ struct GnsRecordInfo static void -cleanup_recordinfo (struct GnsRecordInfo *gnsrecord_info) +cleanup_recordinfo(struct GnsRecordInfo *gnsrecord_info) { if (NULL != *(gnsrecord_info->rd)) - { - for (int i = 0; i < *(gnsrecord_info->rd_count); i++) { - if (NULL != (*(gnsrecord_info->rd))[i].data) - GNUNET_free ((char *) (*(gnsrecord_info->rd))[i].data); + for (int i = 0; i < *(gnsrecord_info->rd_count); i++) + { + if (NULL != (*(gnsrecord_info->rd))[i].data) + GNUNET_free((char *)(*(gnsrecord_info->rd))[i].data); + } + GNUNET_free(*(gnsrecord_info->rd)); + *(gnsrecord_info->rd) = NULL; } - GNUNET_free (*(gnsrecord_info->rd)); - *(gnsrecord_info->rd) = NULL; - } if (NULL != *(gnsrecord_info->name)) - GNUNET_free (*(gnsrecord_info->name)); + GNUNET_free(*(gnsrecord_info->name)); *(gnsrecord_info->name) = NULL; } @@ -73,7 +72,7 @@ cleanup_recordinfo (struct GnsRecordInfo *gnsrecord_info) * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_record (json_t *data, struct GNUNET_GNSRECORD_Data *rd) +parse_record(json_t *data, struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_TIME_Absolute abs_expiration_time; struct GNUNET_TIME_Relative rel_expiration_time; @@ -84,59 +83,59 @@ parse_record (json_t *data, struct GNUNET_GNSRECORD_Data *rd) int unpack_state = 0; //interpret single gns record - unpack_state = json_unpack (data, - "{s:s, s:s, s:s, s?:i!}", - GNUNET_JSON_GNSRECORD_VALUE, - &value, - GNUNET_JSON_GNSRECORD_TYPE, - &record_type, - GNUNET_JSON_GNSRECORD_EXPIRATION_TIME, - &expiration_time, - GNUNET_JSON_GNSRECORD_FLAG, - &flag); + unpack_state = json_unpack(data, + "{s:s, s:s, s:s, s?:i!}", + GNUNET_JSON_GNSRECORD_VALUE, + &value, + GNUNET_JSON_GNSRECORD_TYPE, + &record_type, + GNUNET_JSON_GNSRECORD_EXPIRATION_TIME, + &expiration_time, + GNUNET_JSON_GNSRECORD_FLAG, + &flag); if (0 != unpack_state) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error gnsdata object has a wrong format!\n"); - return GNUNET_SYSERR; - } - rd->record_type = GNUNET_GNSRECORD_typename_to_number (record_type); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error gnsdata object has a wrong format!\n"); + return GNUNET_SYSERR; + } + rd->record_type = GNUNET_GNSRECORD_typename_to_number(record_type); if (UINT32_MAX == rd->record_type) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unsupported type\n"); - return GNUNET_SYSERR; - } - if (GNUNET_OK != GNUNET_GNSRECORD_string_to_value (rd->record_type, - value, - (void**)&rd->data, - &rd->data_size)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Value invalid for record type\n"); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Unsupported type\n"); + return GNUNET_SYSERR; + } + if (GNUNET_OK != GNUNET_GNSRECORD_string_to_value(rd->record_type, + value, + (void**)&rd->data, + &rd->data_size)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Value invalid for record type\n"); + return GNUNET_SYSERR; + } - if (0 == strcmp (expiration_time, GNUNET_JSON_GNSRECORD_NEVER)) - { - rd->expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us; - } + if (0 == strcmp(expiration_time, GNUNET_JSON_GNSRECORD_NEVER)) + { + rd->expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us; + } else if (GNUNET_OK == - GNUNET_STRINGS_fancy_time_to_absolute (expiration_time, - &abs_expiration_time)) - { - rd->expiration_time = abs_expiration_time.abs_value_us; - } + GNUNET_STRINGS_fancy_time_to_absolute(expiration_time, + &abs_expiration_time)) + { + rd->expiration_time = abs_expiration_time.abs_value_us; + } else if (GNUNET_OK == - GNUNET_STRINGS_fancy_time_to_relative (expiration_time, - &rel_expiration_time)) - { - rd->expiration_time = rel_expiration_time.rel_value_us; - } + GNUNET_STRINGS_fancy_time_to_relative(expiration_time, + &rel_expiration_time)) + { + rd->expiration_time = rel_expiration_time.rel_value_us; + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Expiration time invalid\n"); - return GNUNET_SYSERR; - } - rd->flags = (enum GNUNET_GNSRECORD_Flags) flag; + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Expiration time invalid\n"); + return GNUNET_SYSERR; + } + rd->flags = (enum GNUNET_GNSRECORD_Flags)flag; return GNUNET_OK; } @@ -150,23 +149,23 @@ parse_record (json_t *data, struct GNUNET_GNSRECORD_Data *rd) * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_record_data (struct GnsRecordInfo *gnsrecord_info, json_t *data) +parse_record_data(struct GnsRecordInfo *gnsrecord_info, json_t *data) { - GNUNET_assert (NULL != data); - if (! json_is_array (data)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error gns record data JSON is not an array!\n"); - return GNUNET_SYSERR; - } - *(gnsrecord_info->rd_count) = json_array_size (data); - *(gnsrecord_info->rd) = GNUNET_malloc (sizeof (struct GNUNET_GNSRECORD_Data) * - json_array_size (data)); + GNUNET_assert(NULL != data); + if (!json_is_array(data)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error gns record data JSON is not an array!\n"); + return GNUNET_SYSERR; + } + *(gnsrecord_info->rd_count) = json_array_size(data); + *(gnsrecord_info->rd) = GNUNET_malloc(sizeof(struct GNUNET_GNSRECORD_Data) * + json_array_size(data)); size_t index; json_t *value; - json_array_foreach (data, index, value) + json_array_foreach(data, index, value) { - if (GNUNET_OK != parse_record (value, &(*(gnsrecord_info->rd))[index])) + if (GNUNET_OK != parse_record(value, &(*(gnsrecord_info->rd))[index])) return GNUNET_SYSERR; } return GNUNET_OK; @@ -174,42 +173,42 @@ parse_record_data (struct GnsRecordInfo *gnsrecord_info, json_t *data) static int -parse_gnsrecordobject (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_gnsrecordobject(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { struct GnsRecordInfo *gnsrecord_info; int unpack_state = 0; const char *name; json_t *data; - GNUNET_assert (NULL != root); - if (! json_is_object (root)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error record JSON is not an object!\n"); - return GNUNET_SYSERR; - } + GNUNET_assert(NULL != root); + if (!json_is_object(root)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error record JSON is not an object!\n"); + return GNUNET_SYSERR; + } //interpret single gns record - unpack_state = json_unpack (root, - "{s:s, s:o!}", - GNUNET_JSON_GNSRECORD_RECORD_NAME, - &name, - GNUNET_JSON_GNSRECORD_RECORD_DATA, - &data); + unpack_state = json_unpack(root, + "{s:s, s:o!}", + GNUNET_JSON_GNSRECORD_RECORD_NAME, + &name, + GNUNET_JSON_GNSRECORD_RECORD_DATA, + &data); if (0 != unpack_state) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error namestore records object has a wrong format!\n"); - return GNUNET_SYSERR; - } - gnsrecord_info = (struct GnsRecordInfo *) spec->ptr; - *(gnsrecord_info->name) = GNUNET_strdup (name); - if (GNUNET_OK != parse_record_data (gnsrecord_info, data)) - { - cleanup_recordinfo (gnsrecord_info); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error namestore records object has a wrong format!\n"); + return GNUNET_SYSERR; + } + gnsrecord_info = (struct GnsRecordInfo *)spec->ptr; + *(gnsrecord_info->name) = GNUNET_strdup(name); + if (GNUNET_OK != parse_record_data(gnsrecord_info, data)) + { + cleanup_recordinfo(gnsrecord_info); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -221,10 +220,11 @@ parse_gnsrecordobject (void *cls, * @param[out] spec where to free the data */ static void -clean_gnsrecordobject (void *cls, struct GNUNET_JSON_Specification *spec) +clean_gnsrecordobject(void *cls, struct GNUNET_JSON_Specification *spec) { - struct GnsRecordInfo *gnsrecord_info = (struct GnsRecordInfo *) spec->ptr; - GNUNET_free (gnsrecord_info); + struct GnsRecordInfo *gnsrecord_info = (struct GnsRecordInfo *)spec->ptr; + + GNUNET_free(gnsrecord_info); } @@ -235,21 +235,22 @@ clean_gnsrecordobject (void *cls, struct GNUNET_JSON_Specification *spec) * @return JSON Specification */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_gnsrecord (struct GNUNET_GNSRECORD_Data **rd, - unsigned int *rd_count, - char **name) +GNUNET_JSON_spec_gnsrecord(struct GNUNET_GNSRECORD_Data **rd, + unsigned int *rd_count, + char **name) { - struct GnsRecordInfo *gnsrecord_info = GNUNET_new (struct GnsRecordInfo); + struct GnsRecordInfo *gnsrecord_info = GNUNET_new(struct GnsRecordInfo); + gnsrecord_info->rd = rd; gnsrecord_info->name = name; gnsrecord_info->rd_count = rd_count; - struct GNUNET_JSON_Specification ret = {.parser = &parse_gnsrecordobject, - .cleaner = &clean_gnsrecordobject, - .cls = NULL, - .field = NULL, - .ptr = (struct GnsRecordInfo *) - gnsrecord_info, - .ptr_size = 0, - .size_ptr = NULL}; + struct GNUNET_JSON_Specification ret = { .parser = &parse_gnsrecordobject, + .cleaner = &clean_gnsrecordobject, + .cls = NULL, + .field = NULL, + .ptr = (struct GnsRecordInfo *) + gnsrecord_info, + .ptr_size = 0, + .size_ptr = NULL }; return ret; } diff --git a/src/json/json_helper.c b/src/json/json_helper.c index fdbb13267..a732219c1 100644 --- a/src/json/json_helper.c +++ b/src/json/json_helper.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2014, 2015, 2016 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet + Copyright (C) 2014, 2015, 2016 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file json/json_helper.c * @brief functions to generate specifciations for JSON parsing @@ -32,13 +32,14 @@ * End of a parser specification. */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_end () +GNUNET_JSON_spec_end() { struct GNUNET_JSON_Specification ret = { .parser = NULL, .cleaner = NULL, .cls = NULL }; + return ret; } @@ -52,33 +53,33 @@ GNUNET_JSON_spec_end () * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_fixed_data (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_fixed_data(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { const char *enc; unsigned int len; - if (NULL == (enc = json_string_value (root))) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - len = strlen (enc); + if (NULL == (enc = json_string_value(root))) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + len = strlen(enc); if (((len * 5) / 8) != spec->ptr_size) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } if (GNUNET_OK != - GNUNET_STRINGS_string_to_data (enc, - len, - spec->ptr, - spec->ptr_size)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + GNUNET_STRINGS_string_to_data(enc, + len, + spec->ptr, + spec->ptr_size)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -92,9 +93,9 @@ parse_fixed_data (void *cls, * @param size number of bytes expected in @a obj */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_fixed (const char *name, - void *obj, - size_t size) +GNUNET_JSON_spec_fixed(const char *name, + void *obj, + size_t size) { struct GNUNET_JSON_Specification ret = { .parser = &parse_fixed_data, @@ -105,6 +106,7 @@ GNUNET_JSON_spec_fixed (const char *name, .ptr_size = size, .size_ptr = NULL }; + return ret; } @@ -118,39 +120,39 @@ GNUNET_JSON_spec_fixed (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_variable_data (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_variable_data(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { const char *str; size_t size; void *data; int res; - str = json_string_value (root); + str = json_string_value(root); if (NULL == str) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - size = (strlen (str) * 5) / 8; + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + size = (strlen(str) * 5) / 8; if (size >= 1024) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - data = GNUNET_malloc (size); - res = GNUNET_STRINGS_string_to_data (str, - strlen (str), - data, - size); + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + data = GNUNET_malloc(size); + res = GNUNET_STRINGS_string_to_data(str, + strlen(str), + data, + size); if (GNUNET_OK != res) - { - GNUNET_break_op (0); - GNUNET_free (data); - return GNUNET_SYSERR; - } - *(void**) spec->ptr = data; + { + GNUNET_break_op(0); + GNUNET_free(data); + return GNUNET_SYSERR; + } + *(void**)spec->ptr = data; *spec->size_ptr = size; return GNUNET_OK; } @@ -163,15 +165,15 @@ parse_variable_data (void *cls, * @param[out] spec where to free the data */ static void -clean_variable_data (void *cls, - struct GNUNET_JSON_Specification *spec) +clean_variable_data(void *cls, + struct GNUNET_JSON_Specification *spec) { if (0 != *spec->size_ptr) - { - GNUNET_free (*(void **) spec->ptr); - *(void**) spec->ptr = NULL; - *spec->size_ptr = 0; - } + { + GNUNET_free(*(void **)spec->ptr); + *(void**)spec->ptr = NULL; + *spec->size_ptr = 0; + } } @@ -184,9 +186,9 @@ clean_variable_data (void *cls, * @param[out] size where to store the number of bytes allocated for @a obj */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_varsize (const char *name, - void **obj, - size_t *size) +GNUNET_JSON_spec_varsize(const char *name, + void **obj, + size_t *size) { struct GNUNET_JSON_Specification ret = { .parser = &parse_variable_data, @@ -197,6 +199,7 @@ GNUNET_JSON_spec_varsize (const char *name, .ptr_size = 0, .size_ptr = size }; + *obj = NULL; *size = 0; return ret; @@ -212,19 +215,19 @@ GNUNET_JSON_spec_varsize (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_string (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_string(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { const char *str; - str = json_string_value (root); + str = json_string_value(root); if (NULL == str) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - *(const char **) spec->ptr = str; + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + *(const char **)spec->ptr = str; return GNUNET_OK; } @@ -236,8 +239,8 @@ parse_string (void *cls, * @param strptr where to store a pointer to the field */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_string (const char *name, - const char **strptr) +GNUNET_JSON_spec_string(const char *name, + const char **strptr) { struct GNUNET_JSON_Specification ret = { .parser = &parse_string, @@ -248,6 +251,7 @@ GNUNET_JSON_spec_string (const char *name, .ptr_size = 0, .size_ptr = NULL }; + *strptr = NULL; return ret; } @@ -262,17 +266,17 @@ GNUNET_JSON_spec_string (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_object (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) -{ - if (! (json_is_object (root) || json_is_array (root)) ) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - json_incref (root); - *(json_t **) spec->ptr = root; +parse_object(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) +{ + if (!(json_is_object(root) || json_is_array(root))) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + json_incref(root); + *(json_t **)spec->ptr = root; return GNUNET_OK; } @@ -284,16 +288,16 @@ parse_object (void *cls, * @param[out] spec where to free the data */ static void -clean_object (void *cls, - struct GNUNET_JSON_Specification *spec) +clean_object(void *cls, + struct GNUNET_JSON_Specification *spec) { - json_t **ptr = (json_t **) spec->ptr; + json_t **ptr = (json_t **)spec->ptr; if (NULL != *ptr) - { - json_decref (*ptr); - *ptr = NULL; - } + { + json_decref(*ptr); + *ptr = NULL; + } } @@ -304,8 +308,8 @@ clean_object (void *cls, * @param[out] jsonp where to store the JSON found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_json (const char *name, - json_t **jsonp) +GNUNET_JSON_spec_json(const char *name, + json_t **jsonp) { struct GNUNET_JSON_Specification ret = { .parser = &parse_object, @@ -316,6 +320,7 @@ GNUNET_JSON_spec_json (const char *name, .ptr_size = 0, .size_ptr = NULL }; + *jsonp = NULL; return ret; } @@ -330,25 +335,25 @@ GNUNET_JSON_spec_json (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_u8 (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_u8(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { json_int_t val; uint8_t *up = spec->ptr; - if (! json_is_integer (root)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - val = json_integer_value (root); - if ( (0 > val) || (val > UINT8_MAX) ) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - *up = (uint8_t) val; + if (!json_is_integer(root)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + val = json_integer_value(root); + if ((0 > val) || (val > UINT8_MAX)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + *up = (uint8_t)val; return GNUNET_OK; } @@ -360,8 +365,8 @@ parse_u8 (void *cls, * @param[out] u8 where to store the integer found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_uint8 (const char *name, - uint8_t *u8) +GNUNET_JSON_spec_uint8(const char *name, + uint8_t *u8) { struct GNUNET_JSON_Specification ret = { .parser = &parse_u8, @@ -369,9 +374,10 @@ GNUNET_JSON_spec_uint8 (const char *name, .cls = NULL, .field = name, .ptr = u8, - .ptr_size = sizeof (uint8_t), + .ptr_size = sizeof(uint8_t), .size_ptr = NULL }; + return ret; } @@ -385,25 +391,25 @@ GNUNET_JSON_spec_uint8 (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_u16 (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_u16(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { json_int_t val; uint16_t *up = spec->ptr; - if (! json_is_integer (root)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - val = json_integer_value (root); - if ( (0 > val) || (val > UINT16_MAX) ) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - *up = (uint16_t) val; + if (!json_is_integer(root)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + val = json_integer_value(root); + if ((0 > val) || (val > UINT16_MAX)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + *up = (uint16_t)val; return GNUNET_OK; } @@ -415,8 +421,8 @@ parse_u16 (void *cls, * @param[out] u16 where to store the integer found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_uint16 (const char *name, - uint16_t *u16) +GNUNET_JSON_spec_uint16(const char *name, + uint16_t *u16) { struct GNUNET_JSON_Specification ret = { .parser = &parse_u16, @@ -424,9 +430,10 @@ GNUNET_JSON_spec_uint16 (const char *name, .cls = NULL, .field = name, .ptr = u16, - .ptr_size = sizeof (uint16_t), + .ptr_size = sizeof(uint16_t), .size_ptr = NULL }; + return ret; } @@ -440,25 +447,25 @@ GNUNET_JSON_spec_uint16 (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_u32 (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_u32(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { json_int_t val; uint32_t *up = spec->ptr; - if (! json_is_integer (root)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - val = json_integer_value (root); - if ( (0 > val) || (val > UINT32_MAX) ) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - *up = (uint32_t) val; + if (!json_is_integer(root)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + val = json_integer_value(root); + if ((0 > val) || (val > UINT32_MAX)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + *up = (uint32_t)val; return GNUNET_OK; } @@ -470,8 +477,8 @@ parse_u32 (void *cls, * @param[out] u32 where to store the integer found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_uint32 (const char *name, - uint32_t *u32) +GNUNET_JSON_spec_uint32(const char *name, + uint32_t *u32) { struct GNUNET_JSON_Specification ret = { .parser = &parse_u32, @@ -479,9 +486,10 @@ GNUNET_JSON_spec_uint32 (const char *name, .cls = NULL, .field = name, .ptr = u32, - .ptr_size = sizeof (uint32_t), + .ptr_size = sizeof(uint32_t), .size_ptr = NULL }; + return ret; } @@ -495,20 +503,20 @@ GNUNET_JSON_spec_uint32 (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_u64 (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_u64(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { json_int_t val; uint64_t *up = spec->ptr; - if (! json_is_integer (root)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - val = json_integer_value (root); - *up = (uint64_t) val; + if (!json_is_integer(root)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + val = json_integer_value(root); + *up = (uint64_t)val; return GNUNET_OK; } @@ -520,8 +528,8 @@ parse_u64 (void *cls, * @param[out] u64 where to store the integer found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_uint64 (const char *name, - uint64_t *u64) +GNUNET_JSON_spec_uint64(const char *name, + uint64_t *u64) { struct GNUNET_JSON_Specification ret = { .parser = &parse_u64, @@ -529,9 +537,10 @@ GNUNET_JSON_spec_uint64 (const char *name, .cls = NULL, .field = name, .ptr = u64, - .ptr_size = sizeof (uint64_t), + .ptr_size = sizeof(uint64_t), .size_ptr = NULL }; + return ret; } @@ -547,45 +556,45 @@ GNUNET_JSON_spec_uint64 (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_abs_time (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_abs_time(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { struct GNUNET_TIME_Absolute *abs = spec->ptr; const char *val; unsigned long long int tval; - val = json_string_value (root); + val = json_string_value(root); if (NULL == val) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if ( (0 == strcasecmp (val, - "/forever/")) || - (0 == strcasecmp (val, - "/end of time/")) || - (0 == strcasecmp (val, - "/never/")) ) - { - *abs = GNUNET_TIME_UNIT_FOREVER_ABS; - return GNUNET_OK; - } - if (1 != sscanf (val, - "/Date(%llu)/", - &tval)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if ((0 == strcasecmp(val, + "/forever/")) || + (0 == strcasecmp(val, + "/end of time/")) || + (0 == strcasecmp(val, + "/never/"))) + { + *abs = GNUNET_TIME_UNIT_FOREVER_ABS; + return GNUNET_OK; + } + if (1 != sscanf(val, + "/Date(%llu)/", + &tval)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } /* Time is in seconds in JSON, but in microseconds in GNUNET_TIME_Absolute */ abs->abs_value_us = tval * 1000LL * 1000LL; - if ( (abs->abs_value_us) / 1000LL / 1000LL != tval) - { - /* Integer overflow */ - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + if ((abs->abs_value_us) / 1000LL / 1000LL != tval) + { + /* Integer overflow */ + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -597,8 +606,8 @@ parse_abs_time (void *cls, * @param[out] at where to store the absolute time found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_absolute_time (const char *name, - struct GNUNET_TIME_Absolute *at) +GNUNET_JSON_spec_absolute_time(const char *name, + struct GNUNET_TIME_Absolute *at) { struct GNUNET_JSON_Specification ret = { .parser = &parse_abs_time, @@ -606,9 +615,10 @@ GNUNET_JSON_spec_absolute_time (const char *name, .cls = NULL, .field = name, .ptr = at, - .ptr_size = sizeof (uint64_t), + .ptr_size = sizeof(uint64_t), .size_ptr = NULL }; + return ret; } @@ -622,47 +632,47 @@ GNUNET_JSON_spec_absolute_time (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_abs_time_nbo (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_abs_time_nbo(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { struct GNUNET_TIME_AbsoluteNBO *abs = spec->ptr; const char *val; unsigned long long int tval; struct GNUNET_TIME_Absolute a; - val = json_string_value (root); + val = json_string_value(root); if (NULL == val) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if ( (0 == strcasecmp (val, - "/forever/")) || - (0 == strcasecmp (val, - "/end of time/")) || - (0 == strcasecmp (val, - "/never/")) ) - { - *abs = GNUNET_TIME_absolute_hton (GNUNET_TIME_UNIT_FOREVER_ABS); - return GNUNET_OK; - } - if (1 != sscanf (val, - "/Date(%llu)/", - &tval)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if ((0 == strcasecmp(val, + "/forever/")) || + (0 == strcasecmp(val, + "/end of time/")) || + (0 == strcasecmp(val, + "/never/"))) + { + *abs = GNUNET_TIME_absolute_hton(GNUNET_TIME_UNIT_FOREVER_ABS); + return GNUNET_OK; + } + if (1 != sscanf(val, + "/Date(%llu)/", + &tval)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } /* Time is in seconds in JSON, but in microseconds in GNUNET_TIME_Absolute */ a.abs_value_us = tval * 1000LL * 1000LL; - if ( (a.abs_value_us) / 1000LL / 1000LL != tval) - { - /* Integer overflow */ - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - *abs = GNUNET_TIME_absolute_hton (a); + if ((a.abs_value_us) / 1000LL / 1000LL != tval) + { + /* Integer overflow */ + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + *abs = GNUNET_TIME_absolute_hton(a); return GNUNET_OK; } @@ -674,8 +684,8 @@ parse_abs_time_nbo (void *cls, * @param[out] at where to store the absolute time found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_absolute_time_nbo (const char *name, - struct GNUNET_TIME_AbsoluteNBO *at) +GNUNET_JSON_spec_absolute_time_nbo(const char *name, + struct GNUNET_TIME_AbsoluteNBO *at) { struct GNUNET_JSON_Specification ret = { .parser = &parse_abs_time_nbo, @@ -683,9 +693,10 @@ GNUNET_JSON_spec_absolute_time_nbo (const char *name, .cls = NULL, .field = name, .ptr = at, - .ptr_size = sizeof (uint64_t), + .ptr_size = sizeof(uint64_t), .size_ptr = NULL }; + return ret; } @@ -699,41 +710,41 @@ GNUNET_JSON_spec_absolute_time_nbo (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_rel_time (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_rel_time(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { struct GNUNET_TIME_Relative *rel = spec->ptr; const char *val; unsigned long long int tval; - val = json_string_value (root); + val = json_string_value(root); if (NULL == val) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if ( (0 == strcasecmp (val, - "/forever/")) ) - { - *rel = GNUNET_TIME_UNIT_FOREVER_REL; - return GNUNET_OK; - } - if (1 != sscanf (val, - "/Delay(%llu)/", - &tval)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if ((0 == strcasecmp(val, + "/forever/"))) + { + *rel = GNUNET_TIME_UNIT_FOREVER_REL; + return GNUNET_OK; + } + if (1 != sscanf(val, + "/Delay(%llu)/", + &tval)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } /* Time is in seconds in JSON, but in microseconds in GNUNET_TIME_Relative */ rel->rel_value_us = tval * 1000LL * 1000LL; - if ( (rel->rel_value_us) / 1000LL / 1000LL != tval) - { - /* Integer overflow */ - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + if ((rel->rel_value_us) / 1000LL / 1000LL != tval) + { + /* Integer overflow */ + GNUNET_break_op(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -745,8 +756,8 @@ parse_rel_time (void *cls, * @param[out] rt where to store the relative time found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_relative_time (const char *name, - struct GNUNET_TIME_Relative *rt) +GNUNET_JSON_spec_relative_time(const char *name, + struct GNUNET_TIME_Relative *rt) { struct GNUNET_JSON_Specification ret = { .parser = &parse_rel_time, @@ -754,9 +765,10 @@ GNUNET_JSON_spec_relative_time (const char *name, .cls = NULL, .field = name, .ptr = rt, - .ptr_size = sizeof (uint64_t), + .ptr_size = sizeof(uint64_t), .size_ptr = NULL }; + return ret; } @@ -770,9 +782,9 @@ GNUNET_JSON_spec_relative_time (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_rsa_public_key (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_rsa_public_key(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { struct GNUNET_CRYPTO_RsaPublicKey **pk = spec->ptr; const char *enc; @@ -780,32 +792,32 @@ parse_rsa_public_key (void *cls, size_t len; size_t buf_len; - if (NULL == (enc = json_string_value (root))) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - len = strlen (enc); - buf_len = (len * 5) / 8; - buf = GNUNET_malloc (buf_len); + if (NULL == (enc = json_string_value(root))) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + len = strlen(enc); + buf_len = (len * 5) / 8; + buf = GNUNET_malloc(buf_len); if (GNUNET_OK != - GNUNET_STRINGS_string_to_data (enc, - len, - buf, - buf_len)) - { - GNUNET_break_op (0); - GNUNET_free (buf); - return GNUNET_SYSERR; - } - if (NULL == (*pk = GNUNET_CRYPTO_rsa_public_key_decode (buf, - buf_len))) - { - GNUNET_break_op (0); - GNUNET_free (buf); - return GNUNET_SYSERR; - } - GNUNET_free (buf); + GNUNET_STRINGS_string_to_data(enc, + len, + buf, + buf_len)) + { + GNUNET_break_op(0); + GNUNET_free(buf); + return GNUNET_SYSERR; + } + if (NULL == (*pk = GNUNET_CRYPTO_rsa_public_key_decode(buf, + buf_len))) + { + GNUNET_break_op(0); + GNUNET_free(buf); + return GNUNET_SYSERR; + } + GNUNET_free(buf); return GNUNET_OK; } @@ -817,16 +829,16 @@ parse_rsa_public_key (void *cls, * @param[out] spec where to free the data */ static void -clean_rsa_public_key (void *cls, - struct GNUNET_JSON_Specification *spec) +clean_rsa_public_key(void *cls, + struct GNUNET_JSON_Specification *spec) { struct GNUNET_CRYPTO_RsaPublicKey **pk = spec->ptr; if (NULL != *pk) - { - GNUNET_CRYPTO_rsa_public_key_free (*pk); - *pk = NULL; - } + { + GNUNET_CRYPTO_rsa_public_key_free(*pk); + *pk = NULL; + } } @@ -837,8 +849,8 @@ clean_rsa_public_key (void *cls, * @param pk where to store the RSA key found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_rsa_public_key (const char *name, - struct GNUNET_CRYPTO_RsaPublicKey **pk) +GNUNET_JSON_spec_rsa_public_key(const char *name, + struct GNUNET_CRYPTO_RsaPublicKey **pk) { struct GNUNET_JSON_Specification ret = { .parser = &parse_rsa_public_key, @@ -849,6 +861,7 @@ GNUNET_JSON_spec_rsa_public_key (const char *name, .ptr_size = 0, .size_ptr = NULL }; + *pk = NULL; return ret; } @@ -863,9 +876,9 @@ GNUNET_JSON_spec_rsa_public_key (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_rsa_signature (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_rsa_signature(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { struct GNUNET_CRYPTO_RsaSignature **sig = spec->ptr; size_t size; @@ -873,32 +886,32 @@ parse_rsa_signature (void *cls, int res; void *buf; - str = json_string_value (root); + str = json_string_value(root); if (NULL == str) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - size = (strlen (str) * 5) / 8; - buf = GNUNET_malloc (size); - res = GNUNET_STRINGS_string_to_data (str, - strlen (str), - buf, - size); + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + size = (strlen(str) * 5) / 8; + buf = GNUNET_malloc(size); + res = GNUNET_STRINGS_string_to_data(str, + strlen(str), + buf, + size); if (GNUNET_OK != res) - { - GNUNET_free (buf); - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if (NULL == (*sig = GNUNET_CRYPTO_rsa_signature_decode (buf, - size))) - { - GNUNET_break_op (0); - GNUNET_free (buf); - return GNUNET_SYSERR; - } - GNUNET_free (buf); + { + GNUNET_free(buf); + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if (NULL == (*sig = GNUNET_CRYPTO_rsa_signature_decode(buf, + size))) + { + GNUNET_break_op(0); + GNUNET_free(buf); + return GNUNET_SYSERR; + } + GNUNET_free(buf); return GNUNET_OK; } @@ -910,16 +923,16 @@ parse_rsa_signature (void *cls, * @param[out] spec where to free the data */ static void -clean_rsa_signature (void *cls, - struct GNUNET_JSON_Specification *spec) +clean_rsa_signature(void *cls, + struct GNUNET_JSON_Specification *spec) { struct GNUNET_CRYPTO_RsaSignature **sig = spec->ptr; if (NULL != *sig) - { - GNUNET_CRYPTO_rsa_signature_free (*sig); - *sig = NULL; - } + { + GNUNET_CRYPTO_rsa_signature_free(*sig); + *sig = NULL; + } } @@ -930,8 +943,8 @@ clean_rsa_signature (void *cls, * @param sig where to store the RSA signature found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_rsa_signature (const char *name, - struct GNUNET_CRYPTO_RsaSignature **sig) +GNUNET_JSON_spec_rsa_signature(const char *name, + struct GNUNET_CRYPTO_RsaSignature **sig) { struct GNUNET_JSON_Specification ret = { .parser = &parse_rsa_signature, @@ -942,6 +955,7 @@ GNUNET_JSON_spec_rsa_signature (const char *name, .ptr_size = 0, .size_ptr = NULL }; + *sig = NULL; return ret; } @@ -956,18 +970,18 @@ GNUNET_JSON_spec_rsa_signature (const char *name, * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_boolean (void *cls, - json_t *root, - struct GNUNET_JSON_Specification *spec) +parse_boolean(void *cls, + json_t *root, + struct GNUNET_JSON_Specification *spec) { int *bp = spec->ptr; - if (! json_is_boolean (root)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - *bp = json_boolean_value (root) ? GNUNET_YES : GNUNET_NO; + if (!json_is_boolean(root)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + *bp = json_boolean_value(root) ? GNUNET_YES : GNUNET_NO; return GNUNET_OK; } @@ -979,8 +993,8 @@ parse_boolean (void *cls, * @param[out] boolean where to store the boolean found under @a name */ struct GNUNET_JSON_Specification -GNUNET_JSON_spec_boolean (const char *name, - int *boolean) +GNUNET_JSON_spec_boolean(const char *name, + int *boolean) { struct GNUNET_JSON_Specification ret = { .parser = &parse_boolean, @@ -988,9 +1002,10 @@ GNUNET_JSON_spec_boolean (const char *name, .cls = NULL, .field = name, .ptr = boolean, - .ptr_size = sizeof (int), + .ptr_size = sizeof(int), .size_ptr = NULL }; + return ret; } diff --git a/src/json/json_mhd.c b/src/json/json_mhd.c index 2112d4646..0b4dcfee8 100644 --- a/src/json/json_mhd.c +++ b/src/json/json_mhd.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2014, 2015, 2016 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2014, 2015, 2016 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file json/json_mhd.c * @brief functions to parse JSON snippets we receive via MHD @@ -40,8 +40,7 @@ /** * Buffer for POST requests. */ -struct Buffer -{ +struct Buffer { /** * Allocated memory */ @@ -75,19 +74,19 @@ struct Buffer * @return a GNUnet result code */ static int -buffer_init (struct Buffer *buf, - const void *data, - size_t data_size, - size_t alloc_size, - size_t max_size) +buffer_init(struct Buffer *buf, + const void *data, + size_t data_size, + size_t alloc_size, + size_t max_size) { if ((data_size > max_size) || (alloc_size > max_size)) return GNUNET_SYSERR; if (data_size > alloc_size) alloc_size = data_size; - buf->data = GNUNET_malloc (alloc_size); + buf->data = GNUNET_malloc(alloc_size); buf->alloc = alloc_size; - GNUNET_memcpy (buf->data, data, data_size); + GNUNET_memcpy(buf->data, data, data_size); buf->fill = data_size; buf->max = max_size; return GNUNET_OK; @@ -101,9 +100,9 @@ buffer_init (struct Buffer *buf, * @param buf buffer to de-initialize */ static void -buffer_deinit (struct Buffer *buf) +buffer_deinit(struct Buffer *buf) { - GNUNET_free (buf->data); + GNUNET_free(buf->data); buf->data = NULL; } @@ -119,28 +118,28 @@ buffer_deinit (struct Buffer *buf) * #GNUNET_NO if the buffer can't accomodate for the new data */ static int -buffer_append (struct Buffer *buf, - const void *data, - size_t data_size, - size_t max_size) +buffer_append(struct Buffer *buf, + const void *data, + size_t data_size, + size_t max_size) { if (buf->fill + data_size > max_size) return GNUNET_NO; if (buf->fill + data_size > buf->alloc) - { - char *new_buf; - size_t new_size = buf->alloc; - while (new_size < buf->fill + data_size) - new_size += 2; - if (new_size > max_size) - return GNUNET_NO; - new_buf = GNUNET_malloc (new_size); - GNUNET_memcpy (new_buf, buf->data, buf->fill); - GNUNET_free (buf->data); - buf->data = new_buf; - buf->alloc = new_size; - } - GNUNET_memcpy (buf->data + buf->fill, data, data_size); + { + char *new_buf; + size_t new_size = buf->alloc; + while (new_size < buf->fill + data_size) + new_size += 2; + if (new_size > max_size) + return GNUNET_NO; + new_buf = GNUNET_malloc(new_size); + GNUNET_memcpy(new_buf, buf->data, buf->fill); + GNUNET_free(buf->data); + buf->data = new_buf; + buf->alloc = new_size; + } + GNUNET_memcpy(buf->data + buf->fill, data, data_size); buf->fill += data_size; return GNUNET_OK; } @@ -153,89 +152,95 @@ buffer_append (struct Buffer *buf, * @return result code indicating the status of the operation */ static enum GNUNET_JSON_PostResult -inflate_data (struct Buffer *buf) +inflate_data(struct Buffer *buf) { z_stream z; char *tmp; size_t tmp_size; int ret; - memset (&z, 0, sizeof (z)); - z.next_in = (Bytef *) buf->data; + memset(&z, 0, sizeof(z)); + z.next_in = (Bytef *)buf->data; z.avail_in = buf->fill; - tmp_size = GNUNET_MIN (buf->max, buf->fill * 4); - tmp = GNUNET_malloc (tmp_size); - z.next_out = (Bytef *) tmp; + tmp_size = GNUNET_MIN(buf->max, buf->fill * 4); + tmp = GNUNET_malloc(tmp_size); + z.next_out = (Bytef *)tmp; z.avail_out = tmp_size; - ret = inflateInit (&z); + ret = inflateInit(&z); switch (ret) - { - case Z_MEM_ERROR: - GNUNET_break (0); - return GNUNET_JSON_PR_OUT_OF_MEMORY; - case Z_STREAM_ERROR: - GNUNET_break_op (0); - return GNUNET_JSON_PR_JSON_INVALID; - case Z_OK: - break; - } - while (1) - { - ret = inflate (&z, 0); - switch (ret) { case Z_MEM_ERROR: - GNUNET_break (0); - GNUNET_break (Z_OK == inflateEnd (&z)); - GNUNET_free (tmp); + GNUNET_break(0); return GNUNET_JSON_PR_OUT_OF_MEMORY; - case Z_DATA_ERROR: - GNUNET_break (0); - GNUNET_break (Z_OK == inflateEnd (&z)); - GNUNET_free (tmp); - return GNUNET_JSON_PR_JSON_INVALID; - case Z_NEED_DICT: - GNUNET_break (0); - GNUNET_break (Z_OK == inflateEnd (&z)); - GNUNET_free (tmp); + + case Z_STREAM_ERROR: + GNUNET_break_op(0); return GNUNET_JSON_PR_JSON_INVALID; + case Z_OK: - if ((0 < z.avail_out) && (0 == z.avail_in)) - { - /* truncated input stream */ - GNUNET_break (0); - GNUNET_break (Z_OK == inflateEnd (&z)); - GNUNET_free (tmp); - return GNUNET_JSON_PR_JSON_INVALID; - } - if (0 < z.avail_out) - continue; /* just call it again */ - /* output buffer full, can we grow it? */ - if (tmp_size == buf->max) - { - /* already at max */ - GNUNET_break (0); - GNUNET_break (Z_OK == inflateEnd (&z)); - GNUNET_free (tmp); - return GNUNET_JSON_PR_OUT_OF_MEMORY; - } - if (tmp_size * 2 < tmp_size) - tmp_size = buf->max; - else - tmp_size = GNUNET_MIN (buf->max, tmp_size * 2); - tmp = GNUNET_realloc (tmp, tmp_size); - z.next_out = (Bytef *) &tmp[z.total_out]; - continue; - case Z_STREAM_END: - /* decompression successful, make 'tmp' the new 'data' */ - GNUNET_free (buf->data); - buf->data = tmp; - buf->alloc = tmp_size; - buf->fill = z.total_out; - GNUNET_break (Z_OK == inflateEnd (&z)); - return GNUNET_JSON_PR_SUCCESS; /* at least for now */ + break; } - } /* while (1) */ + while (1) + { + ret = inflate(&z, 0); + switch (ret) + { + case Z_MEM_ERROR: + GNUNET_break(0); + GNUNET_break(Z_OK == inflateEnd(&z)); + GNUNET_free(tmp); + return GNUNET_JSON_PR_OUT_OF_MEMORY; + + case Z_DATA_ERROR: + GNUNET_break(0); + GNUNET_break(Z_OK == inflateEnd(&z)); + GNUNET_free(tmp); + return GNUNET_JSON_PR_JSON_INVALID; + + case Z_NEED_DICT: + GNUNET_break(0); + GNUNET_break(Z_OK == inflateEnd(&z)); + GNUNET_free(tmp); + return GNUNET_JSON_PR_JSON_INVALID; + + case Z_OK: + if ((0 < z.avail_out) && (0 == z.avail_in)) + { + /* truncated input stream */ + GNUNET_break(0); + GNUNET_break(Z_OK == inflateEnd(&z)); + GNUNET_free(tmp); + return GNUNET_JSON_PR_JSON_INVALID; + } + if (0 < z.avail_out) + continue; /* just call it again */ + /* output buffer full, can we grow it? */ + if (tmp_size == buf->max) + { + /* already at max */ + GNUNET_break(0); + GNUNET_break(Z_OK == inflateEnd(&z)); + GNUNET_free(tmp); + return GNUNET_JSON_PR_OUT_OF_MEMORY; + } + if (tmp_size * 2 < tmp_size) + tmp_size = buf->max; + else + tmp_size = GNUNET_MIN(buf->max, tmp_size * 2); + tmp = GNUNET_realloc(tmp, tmp_size); + z.next_out = (Bytef *)&tmp[z.total_out]; + continue; + + case Z_STREAM_END: + /* decompression successful, make 'tmp' the new 'data' */ + GNUNET_free(buf->data); + buf->data = tmp; + buf->alloc = tmp_size; + buf->fill = z.total_out; + GNUNET_break(Z_OK == inflateEnd(&z)); + return GNUNET_JSON_PR_SUCCESS; /* at least for now */ + } + } /* while (1) */ } @@ -255,12 +260,12 @@ inflate_data (struct Buffer *buf) * @return result code indicating the status of the operation */ enum GNUNET_JSON_PostResult -GNUNET_JSON_post_parser (size_t buffer_max, - struct MHD_Connection *connection, - void **con_cls, - const char *upload_data, - size_t *upload_data_size, - json_t **json) +GNUNET_JSON_post_parser(size_t buffer_max, + struct MHD_Connection *connection, + void **con_cls, + const char *upload_data, + size_t *upload_data_size, + json_t **json) { struct Buffer *r = *con_cls; const char *ce; @@ -268,72 +273,71 @@ GNUNET_JSON_post_parser (size_t buffer_max, *json = NULL; if (NULL == *con_cls) - { - - /* We are seeing a fresh POST request. */ - r = GNUNET_new (struct Buffer); - if (GNUNET_OK != buffer_init (r, - upload_data, - *upload_data_size, - REQUEST_BUFFER_INITIAL, - buffer_max)) { - *con_cls = NULL; - buffer_deinit (r); - GNUNET_free (r); - return GNUNET_JSON_PR_OUT_OF_MEMORY; + /* We are seeing a fresh POST request. */ + r = GNUNET_new(struct Buffer); + if (GNUNET_OK != buffer_init(r, + upload_data, + *upload_data_size, + REQUEST_BUFFER_INITIAL, + buffer_max)) + { + *con_cls = NULL; + buffer_deinit(r); + GNUNET_free(r); + return GNUNET_JSON_PR_OUT_OF_MEMORY; + } + /* everything OK, wait for more POST data */ + *upload_data_size = 0; + *con_cls = r; + return GNUNET_JSON_PR_CONTINUE; } - /* everything OK, wait for more POST data */ - *upload_data_size = 0; - *con_cls = r; - return GNUNET_JSON_PR_CONTINUE; - } if (0 != *upload_data_size) - { - /* We are seeing an old request with more data available. */ - - if (GNUNET_OK != - buffer_append (r, upload_data, *upload_data_size, buffer_max)) { - /* Request too long */ - *con_cls = NULL; - buffer_deinit (r); - GNUNET_free (r); - return GNUNET_JSON_PR_REQUEST_TOO_LARGE; + /* We are seeing an old request with more data available. */ + + if (GNUNET_OK != + buffer_append(r, upload_data, *upload_data_size, buffer_max)) + { + /* Request too long */ + *con_cls = NULL; + buffer_deinit(r); + GNUNET_free(r); + return GNUNET_JSON_PR_REQUEST_TOO_LARGE; + } + /* everything OK, wait for more POST data */ + *upload_data_size = 0; + return GNUNET_JSON_PR_CONTINUE; } - /* everything OK, wait for more POST data */ - *upload_data_size = 0; - return GNUNET_JSON_PR_CONTINUE; - } /* We have seen the whole request. */ - ce = MHD_lookup_connection_value (connection, - MHD_HEADER_KIND, - MHD_HTTP_HEADER_CONTENT_ENCODING); - if ((NULL != ce) && (0 == strcasecmp ("deflate", ce))) - { - ret = inflate_data (r); - if (GNUNET_JSON_PR_SUCCESS != ret) + ce = MHD_lookup_connection_value(connection, + MHD_HEADER_KIND, + MHD_HTTP_HEADER_CONTENT_ENCODING); + if ((NULL != ce) && (0 == strcasecmp("deflate", ce))) { - buffer_deinit (r); - GNUNET_free (r); - *con_cls = NULL; - return ret; + ret = inflate_data(r); + if (GNUNET_JSON_PR_SUCCESS != ret) + { + buffer_deinit(r); + GNUNET_free(r); + *con_cls = NULL; + return ret; + } } - } - *json = json_loadb (r->data, r->fill, 0, NULL); + *json = json_loadb(r->data, r->fill, 0, NULL); if (NULL == *json) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Failed to parse JSON request body\n"); - buffer_deinit (r); - GNUNET_free (r); - *con_cls = NULL; - return GNUNET_JSON_PR_JSON_INVALID; - } - buffer_deinit (r); - GNUNET_free (r); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Failed to parse JSON request body\n"); + buffer_deinit(r); + GNUNET_free(r); + *con_cls = NULL; + return GNUNET_JSON_PR_JSON_INVALID; + } + buffer_deinit(r); + GNUNET_free(r); *con_cls = NULL; return GNUNET_JSON_PR_SUCCESS; @@ -348,15 +352,15 @@ GNUNET_JSON_post_parser (size_t buffer_max, * #GNUNET_JSON_post_parser(), to be cleaned up */ void -GNUNET_JSON_post_parser_cleanup (void *con_cls) +GNUNET_JSON_post_parser_cleanup(void *con_cls) { struct Buffer *r = con_cls; if (NULL != r) - { - buffer_deinit (r); - GNUNET_free (r); - } + { + buffer_deinit(r); + GNUNET_free(r); + } } /* end of mhd_json.c */ diff --git a/src/json/test_json.c b/src/json/test_json.c index 40fb7f090..4b9fbc710 100644 --- a/src/json/test_json.c +++ b/src/json/test_json.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - (C) 2015, 2016 GNUnet e.V. + This file is part of GNUnet + (C) 2015, 2016 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file json/test_json.c @@ -34,32 +34,32 @@ * @return 0 on success */ static int -test_abs_time () +test_abs_time() { json_t *j; struct GNUNET_TIME_Absolute a1; struct GNUNET_TIME_Absolute a2; - struct GNUNET_JSON_Specification s1[] = {GNUNET_JSON_spec_absolute_time (NULL, + struct GNUNET_JSON_Specification s1[] = { GNUNET_JSON_spec_absolute_time(NULL, &a2), - GNUNET_JSON_spec_end ()}; - struct GNUNET_JSON_Specification s2[] = {GNUNET_JSON_spec_absolute_time (NULL, + GNUNET_JSON_spec_end() }; + struct GNUNET_JSON_Specification s2[] = { GNUNET_JSON_spec_absolute_time(NULL, &a2), - GNUNET_JSON_spec_end ()}; + GNUNET_JSON_spec_end() }; - a1 = GNUNET_TIME_absolute_get (); - GNUNET_TIME_round_abs (&a1); - j = GNUNET_JSON_from_time_abs (a1); - GNUNET_assert (NULL != j); - GNUNET_assert (GNUNET_OK == GNUNET_JSON_parse (j, s1, NULL, NULL)); - GNUNET_assert (a1.abs_value_us == a2.abs_value_us); - json_decref (j); + a1 = GNUNET_TIME_absolute_get(); + GNUNET_TIME_round_abs(&a1); + j = GNUNET_JSON_from_time_abs(a1); + GNUNET_assert(NULL != j); + GNUNET_assert(GNUNET_OK == GNUNET_JSON_parse(j, s1, NULL, NULL)); + GNUNET_assert(a1.abs_value_us == a2.abs_value_us); + json_decref(j); a1 = GNUNET_TIME_UNIT_FOREVER_ABS; - j = GNUNET_JSON_from_time_abs (a1); - GNUNET_assert (NULL != j); - GNUNET_assert (GNUNET_OK == GNUNET_JSON_parse (j, s2, NULL, NULL)); - GNUNET_assert (a1.abs_value_us == a2.abs_value_us); - json_decref (j); + j = GNUNET_JSON_from_time_abs(a1); + GNUNET_assert(NULL != j); + GNUNET_assert(GNUNET_OK == GNUNET_JSON_parse(j, s2, NULL, NULL)); + GNUNET_assert(a1.abs_value_us == a2.abs_value_us); + json_decref(j); return 0; } @@ -70,31 +70,31 @@ test_abs_time () * @return 0 on success */ static int -test_rel_time () +test_rel_time() { json_t *j; struct GNUNET_TIME_Relative r1; struct GNUNET_TIME_Relative r2; - struct GNUNET_JSON_Specification s1[] = {GNUNET_JSON_spec_relative_time (NULL, + struct GNUNET_JSON_Specification s1[] = { GNUNET_JSON_spec_relative_time(NULL, &r2), - GNUNET_JSON_spec_end ()}; - struct GNUNET_JSON_Specification s2[] = {GNUNET_JSON_spec_relative_time (NULL, + GNUNET_JSON_spec_end() }; + struct GNUNET_JSON_Specification s2[] = { GNUNET_JSON_spec_relative_time(NULL, &r2), - GNUNET_JSON_spec_end ()}; + GNUNET_JSON_spec_end() }; r1 = GNUNET_TIME_UNIT_SECONDS; - j = GNUNET_JSON_from_time_rel (r1); - GNUNET_assert (NULL != j); - GNUNET_assert (GNUNET_OK == GNUNET_JSON_parse (j, s1, NULL, NULL)); - GNUNET_assert (r1.rel_value_us == r2.rel_value_us); - json_decref (j); + j = GNUNET_JSON_from_time_rel(r1); + GNUNET_assert(NULL != j); + GNUNET_assert(GNUNET_OK == GNUNET_JSON_parse(j, s1, NULL, NULL)); + GNUNET_assert(r1.rel_value_us == r2.rel_value_us); + json_decref(j); r1 = GNUNET_TIME_UNIT_FOREVER_REL; - j = GNUNET_JSON_from_time_rel (r1); - GNUNET_assert (NULL != j); - GNUNET_assert (GNUNET_OK == GNUNET_JSON_parse (j, s2, NULL, NULL)); - GNUNET_assert (r1.rel_value_us == r2.rel_value_us); - json_decref (j); + j = GNUNET_JSON_from_time_rel(r1); + GNUNET_assert(NULL != j); + GNUNET_assert(GNUNET_OK == GNUNET_JSON_parse(j, s2, NULL, NULL)); + GNUNET_assert(r1.rel_value_us == r2.rel_value_us); + json_decref(j); return 0; } @@ -105,26 +105,26 @@ test_rel_time () * @return 0 on success */ static int -test_raw () +test_raw() { char blob[256]; unsigned int i; json_t *j; for (i = 0; i <= 256; i++) - { - char blob2[256]; - struct GNUNET_JSON_Specification spec[] = {GNUNET_JSON_spec_fixed (NULL, - blob2, - i), - GNUNET_JSON_spec_end ()}; - - memset (blob, i, i); - j = GNUNET_JSON_from_data (blob, i); - GNUNET_assert (NULL != j); - GNUNET_assert (GNUNET_OK == GNUNET_JSON_parse (j, spec, NULL, NULL)); - GNUNET_assert (0 == memcmp (blob, blob2, i)); - } + { + char blob2[256]; + struct GNUNET_JSON_Specification spec[] = { GNUNET_JSON_spec_fixed(NULL, + blob2, + i), + GNUNET_JSON_spec_end() }; + + memset(blob, i, i); + j = GNUNET_JSON_from_data(blob, i); + GNUNET_assert(NULL != j); + GNUNET_assert(GNUNET_OK == GNUNET_JSON_parse(j, spec, NULL, NULL)); + GNUNET_assert(0 == memcmp(blob, blob2, i)); + } return 0; } @@ -135,36 +135,36 @@ test_raw () * @return 0 on success */ static int -test_rsa () +test_rsa() { struct GNUNET_CRYPTO_RsaPublicKey *pub; struct GNUNET_CRYPTO_RsaPublicKey *pub2; struct GNUNET_JSON_Specification pspec[] = - {GNUNET_JSON_spec_rsa_public_key (NULL, &pub2), GNUNET_JSON_spec_end ()}; + { GNUNET_JSON_spec_rsa_public_key(NULL, &pub2), GNUNET_JSON_spec_end() }; struct GNUNET_CRYPTO_RsaSignature *sig; struct GNUNET_CRYPTO_RsaSignature *sig2; struct GNUNET_JSON_Specification sspec[] = - {GNUNET_JSON_spec_rsa_signature (NULL, &sig2), GNUNET_JSON_spec_end ()}; + { GNUNET_JSON_spec_rsa_signature(NULL, &sig2), GNUNET_JSON_spec_end() }; struct GNUNET_CRYPTO_RsaPrivateKey *priv; struct GNUNET_HashCode msg; json_t *jp; json_t *js; - priv = GNUNET_CRYPTO_rsa_private_key_create (1024); - pub = GNUNET_CRYPTO_rsa_private_key_get_public (priv); - memset (&msg, 42, sizeof (msg)); - sig = GNUNET_CRYPTO_rsa_sign_fdh (priv, &msg); - GNUNET_assert (NULL != (jp = GNUNET_JSON_from_rsa_public_key (pub))); - GNUNET_assert (NULL != (js = GNUNET_JSON_from_rsa_signature (sig))); - GNUNET_assert (GNUNET_OK == GNUNET_JSON_parse (jp, pspec, NULL, NULL)); - GNUNET_assert (GNUNET_OK == GNUNET_JSON_parse (js, sspec, NULL, NULL)); - GNUNET_break (0 == GNUNET_CRYPTO_rsa_signature_cmp (sig, sig2)); - GNUNET_break (0 == GNUNET_CRYPTO_rsa_public_key_cmp (pub, pub2)); - GNUNET_CRYPTO_rsa_signature_free (sig); - GNUNET_CRYPTO_rsa_signature_free (sig2); - GNUNET_CRYPTO_rsa_private_key_free (priv); - GNUNET_CRYPTO_rsa_public_key_free (pub); - GNUNET_CRYPTO_rsa_public_key_free (pub2); + priv = GNUNET_CRYPTO_rsa_private_key_create(1024); + pub = GNUNET_CRYPTO_rsa_private_key_get_public(priv); + memset(&msg, 42, sizeof(msg)); + sig = GNUNET_CRYPTO_rsa_sign_fdh(priv, &msg); + GNUNET_assert(NULL != (jp = GNUNET_JSON_from_rsa_public_key(pub))); + GNUNET_assert(NULL != (js = GNUNET_JSON_from_rsa_signature(sig))); + GNUNET_assert(GNUNET_OK == GNUNET_JSON_parse(jp, pspec, NULL, NULL)); + GNUNET_assert(GNUNET_OK == GNUNET_JSON_parse(js, sspec, NULL, NULL)); + GNUNET_break(0 == GNUNET_CRYPTO_rsa_signature_cmp(sig, sig2)); + GNUNET_break(0 == GNUNET_CRYPTO_rsa_public_key_cmp(pub, pub2)); + GNUNET_CRYPTO_rsa_signature_free(sig); + GNUNET_CRYPTO_rsa_signature_free(sig2); + GNUNET_CRYPTO_rsa_private_key_free(priv); + GNUNET_CRYPTO_rsa_public_key_free(pub); + GNUNET_CRYPTO_rsa_public_key_free(pub2); return 0; } @@ -175,47 +175,47 @@ test_rsa () * @return 0 on success */ static int -test_boolean () +test_boolean() { int b1; int b2; json_t *json; - struct GNUNET_JSON_Specification pspec[] = {GNUNET_JSON_spec_boolean ("b1", + struct GNUNET_JSON_Specification pspec[] = { GNUNET_JSON_spec_boolean("b1", &b1), - GNUNET_JSON_spec_boolean ("b2", + GNUNET_JSON_spec_boolean("b2", &b2), - GNUNET_JSON_spec_end ()}; + GNUNET_JSON_spec_end() }; - json = json_object (); - json_object_set_new (json, "b1", json_true ()); - json_object_set_new (json, "b2", json_false ()); + json = json_object(); + json_object_set_new(json, "b1", json_true()); + json_object_set_new(json, "b2", json_false()); - GNUNET_assert (GNUNET_OK == GNUNET_JSON_parse (json, pspec, NULL, NULL)); + GNUNET_assert(GNUNET_OK == GNUNET_JSON_parse(json, pspec, NULL, NULL)); - GNUNET_assert (GNUNET_YES == b1); - GNUNET_assert (GNUNET_NO == b2); + GNUNET_assert(GNUNET_YES == b1); + GNUNET_assert(GNUNET_NO == b2); - json_object_set_new (json, "b1", json_integer (42)); + json_object_set_new(json, "b1", json_integer(42)); - GNUNET_assert (GNUNET_OK != GNUNET_JSON_parse (json, pspec, NULL, NULL)); + GNUNET_assert(GNUNET_OK != GNUNET_JSON_parse(json, pspec, NULL, NULL)); return 0; } int -main (int argc, const char *const argv[]) +main(int argc, const char *const argv[]) { - GNUNET_log_setup ("test-json", "WARNING", NULL); - if (0 != test_abs_time ()) + GNUNET_log_setup("test-json", "WARNING", NULL); + if (0 != test_abs_time()) return 1; - if (0 != test_rel_time ()) + if (0 != test_rel_time()) return 1; - if (0 != test_raw ()) + if (0 != test_raw()) return 1; - if (0 != test_rsa ()) + if (0 != test_rsa()) return 1; - if (0 != test_boolean ()) + if (0 != test_boolean()) return 1; /* FIXME: test EdDSA signature conversion... */ return 0; diff --git a/src/json/test_json_mhd.c b/src/json/test_json_mhd.c index 73efc4d97..213b95e12 100644 --- a/src/json/test_json_mhd.c +++ b/src/json/test_json_mhd.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - (C) 2019 GNUnet e.V. + This file is part of GNUnet + (C) 2019 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file json/test_json_mhd.c @@ -37,65 +37,69 @@ static int global_ret; static int -access_handler_cb (void *cls, - struct MHD_Connection *connection, - const char *url, - const char *method, - const char *version, - const char *upload_data, - size_t *upload_data_size, - void **con_cls) +access_handler_cb(void *cls, + struct MHD_Connection *connection, + const char *url, + const char *method, + const char *version, + const char *upload_data, + size_t *upload_data_size, + void **con_cls) { int ret; json_t *json; struct MHD_Response *resp; json = NULL; - ret = GNUNET_JSON_post_parser (MAX_SIZE, - connection, - con_cls, - upload_data, - upload_data_size, - &json); + ret = GNUNET_JSON_post_parser(MAX_SIZE, + connection, + con_cls, + upload_data, + upload_data_size, + &json); switch (ret) - { - case GNUNET_JSON_PR_SUCCESS: - if (json_equal (bigj, json)) - { - global_ret = 0; - } - else { - GNUNET_break (0); - global_ret = 6; + case GNUNET_JSON_PR_SUCCESS: + if (json_equal(bigj, json)) + { + global_ret = 0; + } + else + { + GNUNET_break(0); + global_ret = 6; + } + json_decref(json); + resp = MHD_create_response_from_buffer(3, "OK\n", MHD_RESPMEM_PERSISTENT); + ret = MHD_queue_response(connection, MHD_HTTP_OK, resp); + MHD_destroy_response(resp); + return ret; + + case GNUNET_JSON_PR_CONTINUE: + return MHD_YES; + + case GNUNET_JSON_PR_OUT_OF_MEMORY: + GNUNET_break(0); + global_ret = 3; + break; + + case GNUNET_JSON_PR_REQUEST_TOO_LARGE: + GNUNET_break(0); + global_ret = 4; + break; + + case GNUNET_JSON_PR_JSON_INVALID: + GNUNET_break(0); + global_ret = 5; + break; } - json_decref (json); - resp = MHD_create_response_from_buffer (3, "OK\n", MHD_RESPMEM_PERSISTENT); - ret = MHD_queue_response (connection, MHD_HTTP_OK, resp); - MHD_destroy_response (resp); - return ret; - case GNUNET_JSON_PR_CONTINUE: - return MHD_YES; - case GNUNET_JSON_PR_OUT_OF_MEMORY: - GNUNET_break (0); - global_ret = 3; - break; - case GNUNET_JSON_PR_REQUEST_TOO_LARGE: - GNUNET_break (0); - global_ret = 4; - break; - case GNUNET_JSON_PR_JSON_INVALID: - GNUNET_break (0); - global_ret = 5; - break; - } - GNUNET_break (0); + GNUNET_break(0); return MHD_NO; } int -main (int argc, const char *const argv[]) +main(int argc, const char *const argv[]) { struct MHD_Daemon *daemon; uint16_t port; @@ -108,79 +112,79 @@ main (int argc, const char *const argv[]) uLongf dlen; struct curl_slist *json_header; - GNUNET_log_setup ("test-json-mhd", "WARNING", NULL); + GNUNET_log_setup("test-json-mhd", "WARNING", NULL); global_ret = 2; - daemon = MHD_start_daemon (MHD_USE_DUAL_STACK | MHD_USE_AUTO_INTERNAL_THREAD, - 0, - NULL, - NULL, - &access_handler_cb, - NULL, - MHD_OPTION_END); + daemon = MHD_start_daemon(MHD_USE_DUAL_STACK | MHD_USE_AUTO_INTERNAL_THREAD, + 0, + NULL, + NULL, + &access_handler_cb, + NULL, + MHD_OPTION_END); if (NULL == daemon) return 77; - bigj = json_object (); - json_object_set_new (bigj, "test", json_string ("value")); + bigj = json_object(); + json_object_set_new(bigj, "test", json_string("value")); for (unsigned int i = 0; i < 1000; i++) - { - char tmp[5]; + { + char tmp[5]; - GNUNET_snprintf (tmp, sizeof (tmp), "%u", i); - json_object_set_new (bigj, tmp, json_string (tmp)); - } - str = json_dumps (bigj, JSON_INDENT (2)); - slen = strlen (str); + GNUNET_snprintf(tmp, sizeof(tmp), "%u", i); + json_object_set_new(bigj, tmp, json_string(tmp)); + } + str = json_dumps(bigj, JSON_INDENT(2)); + slen = strlen(str); #ifdef compressBound - dlen = compressBound (slen); + dlen = compressBound(slen); #else dlen = slen + slen / 100 + 20; /* documentation says 100.1% oldSize + 12 bytes, but we * should be able to overshoot by more to be safe */ #endif - post_data = GNUNET_malloc (dlen); + post_data = GNUNET_malloc(dlen); if (Z_OK != - compress2 ((Bytef *) post_data, &dlen, (const Bytef *) str, slen, 9)) - { - GNUNET_break (0); - MHD_stop_daemon (daemon); - json_decref (bigj); - GNUNET_free (post_data); - GNUNET_free (str); - return 1; - } - post_data_size = (long) dlen; - port = MHD_get_daemon_info (daemon, MHD_DAEMON_INFO_BIND_PORT)->port; - easy = curl_easy_init (); - GNUNET_asprintf (&url, "http://localhost:%u/", (unsigned int) port); - curl_easy_setopt (easy, CURLOPT_VERBOSE, 0); - curl_easy_setopt (easy, CURLOPT_URL, url); - curl_easy_setopt (easy, CURLOPT_POST, 1); - curl_easy_setopt (easy, CURLOPT_POSTFIELDS, post_data); - curl_easy_setopt (easy, CURLOPT_POSTFIELDSIZE, post_data_size); - - json_header = curl_slist_append (NULL, "Content-Type: application/json"); - json_header = curl_slist_append (json_header, "Content-Encoding: deflate"); - curl_easy_setopt (easy, CURLOPT_HTTPHEADER, json_header); - if (0 != curl_easy_perform (easy)) - { - GNUNET_break (0); - MHD_stop_daemon (daemon); - GNUNET_free (url); - json_decref (bigj); - GNUNET_free (post_data); - GNUNET_free (str); - curl_slist_free_all (json_header); - curl_easy_cleanup (easy); - return 1; - } - MHD_stop_daemon (daemon); - GNUNET_free (url); - json_decref (bigj); - GNUNET_free (post_data); - GNUNET_free (str); - curl_slist_free_all (json_header); - curl_easy_cleanup (easy); + compress2((Bytef *)post_data, &dlen, (const Bytef *)str, slen, 9)) + { + GNUNET_break(0); + MHD_stop_daemon(daemon); + json_decref(bigj); + GNUNET_free(post_data); + GNUNET_free(str); + return 1; + } + post_data_size = (long)dlen; + port = MHD_get_daemon_info(daemon, MHD_DAEMON_INFO_BIND_PORT)->port; + easy = curl_easy_init(); + GNUNET_asprintf(&url, "http://localhost:%u/", (unsigned int)port); + curl_easy_setopt(easy, CURLOPT_VERBOSE, 0); + curl_easy_setopt(easy, CURLOPT_URL, url); + curl_easy_setopt(easy, CURLOPT_POST, 1); + curl_easy_setopt(easy, CURLOPT_POSTFIELDS, post_data); + curl_easy_setopt(easy, CURLOPT_POSTFIELDSIZE, post_data_size); + + json_header = curl_slist_append(NULL, "Content-Type: application/json"); + json_header = curl_slist_append(json_header, "Content-Encoding: deflate"); + curl_easy_setopt(easy, CURLOPT_HTTPHEADER, json_header); + if (0 != curl_easy_perform(easy)) + { + GNUNET_break(0); + MHD_stop_daemon(daemon); + GNUNET_free(url); + json_decref(bigj); + GNUNET_free(post_data); + GNUNET_free(str); + curl_slist_free_all(json_header); + curl_easy_cleanup(easy); + return 1; + } + MHD_stop_daemon(daemon); + GNUNET_free(url); + json_decref(bigj); + GNUNET_free(post_data); + GNUNET_free(str); + curl_slist_free_all(json_header); + curl_easy_cleanup(easy); return global_ret; } diff --git a/src/my/my.c b/src/my/my.c index dd2140c31..bee18145d 100644 --- a/src/my/my.c +++ b/src/my/my.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file my/my.c * @brief library to help with access to a MySQL database @@ -35,69 +35,69 @@ * @param sh handle to SELECT statment * @param params parameters to the statement * @return - #GNUNET_YES if we can prepare all statement - #GNUNET_SYSERR if we can't prepare all statement + #GNUNET_YES if we can prepare all statement + #GNUNET_SYSERR if we can't prepare all statement */ int -GNUNET_MY_exec_prepared (struct GNUNET_MYSQL_Context *mc, - struct GNUNET_MYSQL_StatementHandle *sh, - struct GNUNET_MY_QueryParam *params) +GNUNET_MY_exec_prepared(struct GNUNET_MYSQL_Context *mc, + struct GNUNET_MYSQL_StatementHandle *sh, + struct GNUNET_MY_QueryParam *params) { const struct GNUNET_MY_QueryParam *p; unsigned int num; MYSQL_STMT *stmt; num = 0; - for (unsigned int i=0;NULL != params[i].conv;i++) + for (unsigned int i = 0; NULL != params[i].conv; i++) num += params[i].num_params; { MYSQL_BIND qbind[num]; unsigned int off; - memset (qbind, - 0, - sizeof(qbind)); + memset(qbind, + 0, + sizeof(qbind)); off = 0; - for (unsigned int i=0;NULL != (p = ¶ms[i])->conv;i++) - { - if (GNUNET_OK != - p->conv (p->conv_cls, - p, - &qbind[off])) + for (unsigned int i = 0; NULL != (p = ¶ms[i])->conv; i++) + { + if (GNUNET_OK != + p->conv(p->conv_cls, + p, + &qbind[off])) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Conversion for MySQL query failed at offset %u\n", + i); + return GNUNET_SYSERR; + } + off += p->num_params; + } + stmt = GNUNET_MYSQL_statement_get_stmt(sh); + if (mysql_stmt_bind_param(stmt, + qbind)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Conversion for MySQL query failed at offset %u\n", - i); + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "my", + _("`%s' failed at %s:%d with error: %s\n"), + "mysql_stmt_bind_param", + __FILE__, __LINE__, + mysql_stmt_error(stmt)); + GNUNET_MYSQL_statements_invalidate(mc); return GNUNET_SYSERR; } - off += p->num_params; - } - stmt = GNUNET_MYSQL_statement_get_stmt (sh); - if (mysql_stmt_bind_param (stmt, - qbind)) - { - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "my", - _("`%s' failed at %s:%d with error: %s\n"), - "mysql_stmt_bind_param", - __FILE__, __LINE__, - mysql_stmt_error (stmt)); - GNUNET_MYSQL_statements_invalidate (mc); - return GNUNET_SYSERR; - } - if (mysql_stmt_execute (stmt)) - { - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "my", - _("`%s' failed at %s:%d with error: %s\n"), - "mysql_stmt_execute", __FILE__, __LINE__, - mysql_stmt_error (stmt)); - GNUNET_MYSQL_statements_invalidate (mc); - return GNUNET_SYSERR; - } - GNUNET_MY_cleanup_query (params, - qbind); + if (mysql_stmt_execute(stmt)) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "my", + _("`%s' failed at %s:%d with error: %s\n"), + "mysql_stmt_execute", __FILE__, __LINE__, + mysql_stmt_error(stmt)); + GNUNET_MYSQL_statements_invalidate(mc); + return GNUNET_SYSERR; + } + GNUNET_MY_cleanup_query(params, + qbind); } return GNUNET_OK; } @@ -111,13 +111,13 @@ GNUNET_MY_exec_prepared (struct GNUNET_MYSQL_Context *mc, * @param qbind array of parameter to clean up */ void -GNUNET_MY_cleanup_query (struct GNUNET_MY_QueryParam *qp, - MYSQL_BIND *qbind) +GNUNET_MY_cleanup_query(struct GNUNET_MY_QueryParam *qp, + MYSQL_BIND *qbind) { - for (unsigned int i=0; NULL != qp[i].conv ;i++) + for (unsigned int i = 0; NULL != qp[i].conv; i++) if (NULL != qp[i].cleaner) - qp[i].cleaner (qp[i].conv_cls, - &qbind[i]); + qp[i].cleaner(qp[i].conv_cls, + &qbind[i]); } @@ -133,115 +133,115 @@ GNUNET_MY_cleanup_query (struct GNUNET_MY_QueryParam *qp, * #GNUNET_SYSERR if a result was invalid */ int -GNUNET_MY_extract_result (struct GNUNET_MYSQL_StatementHandle *sh, - struct GNUNET_MY_ResultSpec *rs) +GNUNET_MY_extract_result(struct GNUNET_MYSQL_StatementHandle *sh, + struct GNUNET_MY_ResultSpec *rs) { unsigned int num_fields; int ret; MYSQL_STMT *stmt; - stmt = GNUNET_MYSQL_statement_get_stmt (sh); + stmt = GNUNET_MYSQL_statement_get_stmt(sh); if (NULL == stmt) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } if (NULL == rs) - { - mysql_stmt_free_result (stmt); - return GNUNET_NO; - } + { + mysql_stmt_free_result(stmt); + return GNUNET_NO; + } num_fields = 0; - for (unsigned int i=0;NULL != rs[i].pre_conv;i++) + for (unsigned int i = 0; NULL != rs[i].pre_conv; i++) num_fields += rs[i].num_fields; - if (mysql_stmt_field_count (stmt) != num_fields) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Number of fields mismatch between SQL result and result specification\n"); - return GNUNET_SYSERR; - } + if (mysql_stmt_field_count(stmt) != num_fields) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Number of fields mismatch between SQL result and result specification\n"); + return GNUNET_SYSERR; + } { MYSQL_BIND result[num_fields]; unsigned int field_off; - memset (result, 0, sizeof (MYSQL_BIND) * num_fields); + memset(result, 0, sizeof(MYSQL_BIND) * num_fields); field_off = 0; - for (unsigned int i=0;NULL != rs[i].pre_conv;i++) - { - struct GNUNET_MY_ResultSpec *rp = &rs[i]; + for (unsigned int i = 0; NULL != rs[i].pre_conv; i++) + { + struct GNUNET_MY_ResultSpec *rp = &rs[i]; - if (GNUNET_OK != - rp->pre_conv (rp->conv_cls, - rp, - stmt, - field_off, - &result[field_off])) + if (GNUNET_OK != + rp->pre_conv(rp->conv_cls, + rp, + stmt, + field_off, + &result[field_off])) + + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Pre-conversion for MySQL result failed at offset %u\n", + i); + return GNUNET_SYSERR; + } + field_off += rp->num_fields; + } + if (mysql_stmt_bind_result(stmt, result)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Pre-conversion for MySQL result failed at offset %u\n", - i); + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "my", + _("%s failed at %s:%d with error: %s\n"), + "mysql_stmt_bind_result", + __FILE__, __LINE__, + mysql_stmt_error(stmt)); return GNUNET_SYSERR; } - field_off += rp->num_fields; - } - - if (mysql_stmt_bind_result (stmt, result)) - { - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "my", - _("%s failed at %s:%d with error: %s\n"), - "mysql_stmt_bind_result", - __FILE__, __LINE__, - mysql_stmt_error (stmt)); - return GNUNET_SYSERR; - } #if TEST_OPTIMIZATION - (void) mysql_stmt_store_result (stmt); + (void)mysql_stmt_store_result(stmt); #endif - ret = mysql_stmt_fetch (stmt); + ret = mysql_stmt_fetch(stmt); if (MYSQL_NO_DATA == ret) - { - mysql_stmt_free_result (stmt); - return GNUNET_NO; - } + { + mysql_stmt_free_result(stmt); + return GNUNET_NO; + } if (1 == ret) - { - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "my", - _("%s failed at %s:%d with error: %s\n"), - "mysql_stmt_fetch", - __FILE__, __LINE__, - mysql_stmt_error (stmt)); - GNUNET_MY_cleanup_result (rs); - mysql_stmt_free_result (stmt); - return GNUNET_SYSERR; - } + { + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "my", + _("%s failed at %s:%d with error: %s\n"), + "mysql_stmt_fetch", + __FILE__, __LINE__, + mysql_stmt_error(stmt)); + GNUNET_MY_cleanup_result(rs); + mysql_stmt_free_result(stmt); + return GNUNET_SYSERR; + } field_off = 0; - for (unsigned int i=0;NULL != rs[i].post_conv;i++) - { - struct GNUNET_MY_ResultSpec *rp = &rs[i]; + for (unsigned int i = 0; NULL != rs[i].post_conv; i++) + { + struct GNUNET_MY_ResultSpec *rp = &rs[i]; - if (NULL != rp->post_conv) - if (GNUNET_OK != - rp->post_conv (rp->conv_cls, - rp, - stmt, - field_off, - &result[field_off])) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Post-conversion for MySQL result failed at offset %u\n", - i); - mysql_stmt_free_result (stmt); - GNUNET_MY_cleanup_result (rs); - return GNUNET_SYSERR; - } - field_off += rp->num_fields; - } + if (NULL != rp->post_conv) + if (GNUNET_OK != + rp->post_conv(rp->conv_cls, + rp, + stmt, + field_off, + &result[field_off])) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Post-conversion for MySQL result failed at offset %u\n", + i); + mysql_stmt_free_result(stmt); + GNUNET_MY_cleanup_result(rs); + return GNUNET_SYSERR; + } + field_off += rp->num_fields; + } } return GNUNET_OK; } @@ -254,12 +254,12 @@ GNUNET_MY_extract_result (struct GNUNET_MYSQL_StatementHandle *sh, * @param rs result specification to clean up */ void -GNUNET_MY_cleanup_result (struct GNUNET_MY_ResultSpec *rs) +GNUNET_MY_cleanup_result(struct GNUNET_MY_ResultSpec *rs) { - for (unsigned int i=0;NULL != rs[i].post_conv;i++) + for (unsigned int i = 0; NULL != rs[i].post_conv; i++) if (NULL != rs[i].cleaner) - rs[i].cleaner (rs[i].conv_cls, - &rs[i]); + rs[i].cleaner(rs[i].conv_cls, + &rs[i]); } diff --git a/src/my/my_query_helper.c b/src/my/my_query_helper.c index 8d4435b01..764021057 100644 --- a/src/my/my_query_helper.c +++ b/src/my/my_query_helper.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file my/my_query_helper.c * @brief library to help with access to a MySQL database @@ -36,11 +36,11 @@ * @param qbind array of parameter to clean up */ static void -my_clean_query (void *cls, - MYSQL_BIND *qbind) +my_clean_query(void *cls, + MYSQL_BIND *qbind) { - (void) cls; - GNUNET_free (qbind[0].buffer); + (void)cls; + GNUNET_free(qbind[0].buffer); } @@ -53,13 +53,13 @@ my_clean_query (void *cls, * @return -1 on error */ static int -my_conv_fixed_size (void *cls, - const struct GNUNET_MY_QueryParam *qp, - MYSQL_BIND *qbind) +my_conv_fixed_size(void *cls, + const struct GNUNET_MY_QueryParam *qp, + MYSQL_BIND *qbind) { - (void) cls; - GNUNET_assert (1 == qp->num_params); - qbind->buffer = (void *) qp->data; + (void)cls; + GNUNET_assert(1 == qp->num_params); + qbind->buffer = (void *)qp->data; qbind->buffer_length = qp->data_len; qbind->buffer_type = MYSQL_TYPE_BLOB; @@ -75,8 +75,8 @@ my_conv_fixed_size (void *cls, * @param ptr_size number of bytes in @a ptr */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_fixed_size (const void *ptr, - size_t ptr_size) +GNUNET_MY_query_param_fixed_size(const void *ptr, + size_t ptr_size) { struct GNUNET_MY_QueryParam qp = { .conv = &my_conv_fixed_size, @@ -84,8 +84,9 @@ GNUNET_MY_query_param_fixed_size (const void *ptr, .conv_cls = NULL, .num_params = 1, .data = ptr, - .data_len = (unsigned long) ptr_size + .data_len = (unsigned long)ptr_size }; + return qp; } @@ -99,13 +100,13 @@ GNUNET_MY_query_param_fixed_size (const void *ptr, * @return -1 on error */ static int -my_conv_string (void *cls, - const struct GNUNET_MY_QueryParam *qp, - MYSQL_BIND *qbind) +my_conv_string(void *cls, + const struct GNUNET_MY_QueryParam *qp, + MYSQL_BIND *qbind) { - (void) cls; - GNUNET_assert (1 == qp->num_params); - qbind->buffer = (void *) qp->data; + (void)cls; + GNUNET_assert(1 == qp->num_params); + qbind->buffer = (void *)qp->data; qbind->buffer_length = qp->data_len; qbind->buffer_type = MYSQL_TYPE_STRING; return 1; @@ -118,7 +119,7 @@ my_conv_string (void *cls, * @param ptr pointer to the string query parameter to pass */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_string (const char *ptr) +GNUNET_MY_query_param_string(const char *ptr) { struct GNUNET_MY_QueryParam qp = { .conv = &my_conv_string, @@ -126,8 +127,9 @@ GNUNET_MY_query_param_string (const char *ptr) .conv_cls = NULL, .num_params = 1, .data = ptr, - .data_len = strlen (ptr) + .data_len = strlen(ptr) }; + return qp; } @@ -141,14 +143,14 @@ GNUNET_MY_query_param_string (const char *ptr) * @return -1 on error */ static int -my_conv_uint16 (void *cls, - const struct GNUNET_MY_QueryParam *qp, - MYSQL_BIND *qbind) +my_conv_uint16(void *cls, + const struct GNUNET_MY_QueryParam *qp, + MYSQL_BIND *qbind) { - (void) cls; - GNUNET_assert (1 == qp->num_params); - qbind->buffer = (void *) qp->data; - qbind->buffer_length = sizeof (uint16_t); + (void)cls; + GNUNET_assert(1 == qp->num_params); + qbind->buffer = (void *)qp->data; + qbind->buffer_length = sizeof(uint16_t); qbind->buffer_type = MYSQL_TYPE_SHORT; qbind->is_unsigned = 1; return 1; @@ -161,7 +163,7 @@ my_conv_uint16 (void *cls, * @param x pointer to the query parameter to pass */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_uint16 (const uint16_t *x) +GNUNET_MY_query_param_uint16(const uint16_t *x) { struct GNUNET_MY_QueryParam res = { .conv = &my_conv_uint16, @@ -169,7 +171,7 @@ GNUNET_MY_query_param_uint16 (const uint16_t *x) .conv_cls = NULL, .num_params = 1, .data = x, - .data_len = sizeof (*x) + .data_len = sizeof(*x) }; return res; @@ -185,13 +187,13 @@ GNUNET_MY_query_param_uint16 (const uint16_t *x) * @return -1 on error */ static int -my_conv_uint32 (void *cls, - const struct GNUNET_MY_QueryParam *qp, - MYSQL_BIND *qbind) +my_conv_uint32(void *cls, + const struct GNUNET_MY_QueryParam *qp, + MYSQL_BIND *qbind) { - (void) cls; - GNUNET_assert (1 == qp->num_params); - qbind->buffer = (void *) qp->data; + (void)cls; + GNUNET_assert(1 == qp->num_params); + qbind->buffer = (void *)qp->data; qbind->buffer_length = sizeof(uint32_t); qbind->buffer_type = MYSQL_TYPE_LONG; qbind->is_unsigned = 1; @@ -205,7 +207,7 @@ my_conv_uint32 (void *cls, * @param x pointer to the query parameter to pass */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_uint32 (const uint32_t *x) +GNUNET_MY_query_param_uint32(const uint32_t *x) { struct GNUNET_MY_QueryParam res = { .conv = &my_conv_uint32, @@ -213,7 +215,7 @@ GNUNET_MY_query_param_uint32 (const uint32_t *x) .conv_cls = NULL, .num_params = 1, .data = x, - .data_len = sizeof (*x) + .data_len = sizeof(*x) }; return res; @@ -229,14 +231,14 @@ GNUNET_MY_query_param_uint32 (const uint32_t *x) * @return -1 on error */ static int -my_conv_uint64 (void *cls, - const struct GNUNET_MY_QueryParam *qp, - MYSQL_BIND * qbind) +my_conv_uint64(void *cls, + const struct GNUNET_MY_QueryParam *qp, + MYSQL_BIND * qbind) { - (void) cls; - GNUNET_assert (1 == qp->num_params); - qbind->buffer = (void *) qp->data; - qbind->buffer_length = sizeof (uint64_t); + (void)cls; + GNUNET_assert(1 == qp->num_params); + qbind->buffer = (void *)qp->data; + qbind->buffer_length = sizeof(uint64_t); qbind->buffer_type = MYSQL_TYPE_LONGLONG; qbind->is_unsigned = 1; return 1; @@ -249,7 +251,7 @@ my_conv_uint64 (void *cls, * @param x pointer to the query parameter to pass */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_uint64 (const uint64_t *x) +GNUNET_MY_query_param_uint64(const uint64_t *x) { struct GNUNET_MY_QueryParam res = { .conv = &my_conv_uint64, @@ -273,19 +275,19 @@ GNUNET_MY_query_param_uint64 (const uint64_t *x) * @return -1 on error */ static int -my_conv_rsa_public_key (void *cls, - const struct GNUNET_MY_QueryParam *qp, - MYSQL_BIND * qbind) +my_conv_rsa_public_key(void *cls, + const struct GNUNET_MY_QueryParam *qp, + MYSQL_BIND * qbind) { const struct GNUNET_CRYPTO_RsaPublicKey *rsa = qp->data; char *buf; size_t buf_size; - (void) cls; + (void)cls; GNUNET_assert(1 == qp->num_params); - buf_size = GNUNET_CRYPTO_rsa_public_key_encode (rsa, - &buf); - qbind->buffer = (void *) buf; + buf_size = GNUNET_CRYPTO_rsa_public_key_encode(rsa, + &buf); + qbind->buffer = (void *)buf; qbind->buffer_length = buf_size; qbind->buffer_type = MYSQL_TYPE_BLOB; return 1; @@ -300,7 +302,7 @@ my_conv_rsa_public_key (void *cls, * @return array entry for the query parameters to use */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_rsa_public_key (const struct GNUNET_CRYPTO_RsaPublicKey *x) +GNUNET_MY_query_param_rsa_public_key(const struct GNUNET_CRYPTO_RsaPublicKey *x) { struct GNUNET_MY_QueryParam res = { .conv = &my_conv_rsa_public_key, @@ -316,27 +318,27 @@ GNUNET_MY_query_param_rsa_public_key (const struct GNUNET_CRYPTO_RsaPublicKey *x /** - * Function called to convert input argument into SQL parameters - * - *@param cls closure - *@param pq data about the query - *@param qbind array of parameters to initialize - *@return -1 on error - */ + * Function called to convert input argument into SQL parameters + * + *@param cls closure + *@param pq data about the query + *@param qbind array of parameters to initialize + *@return -1 on error + */ static int -my_conv_rsa_signature (void *cls, - const struct GNUNET_MY_QueryParam *qp, - MYSQL_BIND *qbind) +my_conv_rsa_signature(void *cls, + const struct GNUNET_MY_QueryParam *qp, + MYSQL_BIND *qbind) { const struct GNUNET_CRYPTO_RsaSignature *sig = qp->data; char *buf; size_t buf_size; - (void) cls; + (void)cls; GNUNET_assert(1 == qp->num_params); - buf_size = GNUNET_CRYPTO_rsa_signature_encode (sig, - &buf); - qbind->buffer = (void *) buf; + buf_size = GNUNET_CRYPTO_rsa_signature_encode(sig, + &buf); + qbind->buffer = (void *)buf; qbind->buffer_length = buf_size; qbind->buffer_type = MYSQL_TYPE_BLOB; return 1; @@ -351,7 +353,7 @@ my_conv_rsa_signature (void *cls, * @return array entry for the query parameters to use */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *x) +GNUNET_MY_query_param_rsa_signature(const struct GNUNET_CRYPTO_RsaSignature *x) { struct GNUNET_MY_QueryParam res = { .conv = &my_conv_rsa_signature, @@ -361,6 +363,7 @@ GNUNET_MY_query_param_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *x) .data = (x), .data_len = 0 }; + return res; } @@ -373,9 +376,9 @@ GNUNET_MY_query_param_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *x) * @return array entry for the query parameters to use */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_absolute_time (const struct GNUNET_TIME_Absolute *x) +GNUNET_MY_query_param_absolute_time(const struct GNUNET_TIME_Absolute *x) { - return GNUNET_MY_query_param_uint64 (&x->abs_value_us); + return GNUNET_MY_query_param_uint64(&x->abs_value_us); } @@ -386,9 +389,9 @@ GNUNET_MY_query_param_absolute_time (const struct GNUNET_TIME_Absolute *x) * @param x pointer to the query parameter to pass */ struct GNUNET_MY_QueryParam -GNUNET_MY_query_param_absolute_time_nbo (const struct GNUNET_TIME_AbsoluteNBO *x) +GNUNET_MY_query_param_absolute_time_nbo(const struct GNUNET_TIME_AbsoluteNBO *x) { - return GNUNET_MY_query_param_auto_from_type (&x->abs_value_us__); + return GNUNET_MY_query_param_auto_from_type(&x->abs_value_us__); } diff --git a/src/my/my_result_helper.c b/src/my/my_result_helper.c index 75a340014..2fedc1f19 100644 --- a/src/my/my_result_helper.c +++ b/src/my/my_result_helper.c @@ -1,22 +1,22 @@ - /* - This file is part of GNUnet - Copyright (C) 2014, 2015, 2016 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - - SPDX-License-Identifier: AGPL3.0-or-later -*/ +/* + This file is part of GNUnet + Copyright (C) 2014, 2015, 2016 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + SPDX-License-Identifier: AGPL3.0-or-later + */ /** * @file my/my_result_helper.c * @brief functions to extract result values @@ -41,11 +41,11 @@ * #GNUNET_SYSERR if a result was invalid */ static int -pre_extract_varsize_blob (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +pre_extract_varsize_blob(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { results[0].buffer = NULL; results[0].buffer_length = 0; @@ -70,39 +70,39 @@ pre_extract_varsize_blob (void *cls, * #GNUNET_SYSERR if a result was invalid */ static int -post_extract_varsize_blob (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +post_extract_varsize_blob(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { void *buf; size_t size; if (*results->is_null) return GNUNET_SYSERR; - size = (size_t) rs->mysql_bind_output_length; + size = (size_t)rs->mysql_bind_output_length; if (rs->mysql_bind_output_length != size) return GNUNET_SYSERR; /* 'unsigned long' does not fit in size_t!? */ - buf = GNUNET_malloc (size); + buf = GNUNET_malloc(size); results[0].buffer = buf; results[0].buffer_length = size; results[0].buffer_type = MYSQL_TYPE_BLOB; if (0 != - mysql_stmt_fetch_column (stmt, - results, - column, - 0)) - { - GNUNET_free (buf); - return GNUNET_SYSERR; - } - - *(void **) rs->dst = buf; + mysql_stmt_fetch_column(stmt, + results, + column, + 0)) + { + GNUNET_free(buf); + return GNUNET_SYSERR; + } + + *(void **)rs->dst = buf; *rs->result_size = size; return GNUNET_OK; @@ -116,16 +116,16 @@ post_extract_varsize_blob (void *cls, * @param[in,out] rs */ static void -cleanup_varsize_blob (void *cls, - struct GNUNET_MY_ResultSpec *rs) +cleanup_varsize_blob(void *cls, + struct GNUNET_MY_ResultSpec *rs) { void **ptr = (void **)rs->dst; if (NULL != *ptr) - { - GNUNET_free (*ptr); - *ptr = NULL; - } + { + GNUNET_free(*ptr); + *ptr = NULL; + } } @@ -137,7 +137,7 @@ cleanup_varsize_blob (void *cls, * @return array entru for the result specification to use */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_variable_size (void **dst, +GNUNET_MY_result_spec_variable_size(void **dst, size_t *ptr_size) { struct GNUNET_MY_ResultSpec res = @@ -145,7 +145,7 @@ GNUNET_MY_result_spec_variable_size (void **dst, .pre_conv = &pre_extract_varsize_blob, .post_conv = &post_extract_varsize_blob, .cleaner = &cleanup_varsize_blob, - .dst = (void *)(dst), + .dst = (void *)(dst), .result_size = ptr_size, .num_fields = 1 }; @@ -167,11 +167,11 @@ GNUNET_MY_result_spec_variable_size (void **dst, * #GNUNET_SYSERR if a result was invalid(non-existing field or NULL) */ static int -pre_extract_fixed_blob (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +pre_extract_fixed_blob(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { results[0].buffer = rs->dst; results[0].buffer_length = rs->dst_size; @@ -198,11 +198,11 @@ pre_extract_fixed_blob (void *cls, * #GNUNET_SYSERR if a result was invalid(non-existing field or NULL) */ static int -post_extract_fixed_blob (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +post_extract_fixed_blob(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { if (*results->is_null) return GNUNET_SYSERR; @@ -221,8 +221,8 @@ post_extract_fixed_blob (void *cls, * @return array entry for the result specification to use */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_fixed_size (void *ptr, - size_t ptr_size) +GNUNET_MY_result_spec_fixed_size(void *ptr, + size_t ptr_size) { struct GNUNET_MY_ResultSpec res = { @@ -239,23 +239,23 @@ GNUNET_MY_result_spec_fixed_size (void *ptr, /** - * Extract data from a Mysql database @a result at row @a row - * - * @param cls closure - * @param[in,out] rs - * @param stmt the mysql statement that is being run - * @param column the column that is being processed - * @param[out] results - * @return - * #GNUNET_OK if all results could be extracted - * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) - */ + * Extract data from a Mysql database @a result at row @a row + * + * @param cls closure + * @param[in,out] rs + * @param stmt the mysql statement that is being run + * @param column the column that is being processed + * @param[out] results + * @return + * #GNUNET_OK if all results could be extracted + * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) + */ static int -pre_extract_rsa_public_key (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +pre_extract_rsa_public_key(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { results[0].buffer = NULL; results[0].buffer_length = 0; @@ -269,24 +269,24 @@ pre_extract_rsa_public_key (void *cls, /** - * Check size of extracted fixed size data from a Mysql database @a - * result at row @a row - * - * @param cls closure - * @param[in,out] rs - * @param stmt the mysql statement that is being run - * @param column the column that is being processed - * @param[out] results - * @return - * #GNUNET_OK if all results could be extracted - * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) - */ + * Check size of extracted fixed size data from a Mysql database @a + * result at row @a row + * + * @param cls closure + * @param[in,out] rs + * @param stmt the mysql statement that is being run + * @param column the column that is being processed + * @param[out] results + * @return + * #GNUNET_OK if all results could be extracted + * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) + */ static int -post_extract_rsa_public_key (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +post_extract_rsa_public_key(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { struct GNUNET_CRYPTO_RsaPublicKey **pk = rs->dst; @@ -295,34 +295,34 @@ post_extract_rsa_public_key (void *cls, if (*results->is_null) return GNUNET_SYSERR; - size = (size_t) rs->mysql_bind_output_length; + size = (size_t)rs->mysql_bind_output_length; if (rs->mysql_bind_output_length != size) return GNUNET_SYSERR; /* 'unsigned long' does not fit in size_t!? */ - buf = GNUNET_malloc (size); + buf = GNUNET_malloc(size); results[0].buffer = buf; results[0].buffer_length = size; results[0].buffer_type = MYSQL_TYPE_BLOB; if (0 != - mysql_stmt_fetch_column (stmt, - results, - column, - 0)) - { - GNUNET_free (buf); - return GNUNET_SYSERR; - } - - *pk = GNUNET_CRYPTO_rsa_public_key_decode (buf, - size); - GNUNET_free (buf); + mysql_stmt_fetch_column(stmt, + results, + column, + 0)) + { + GNUNET_free(buf); + return GNUNET_SYSERR; + } + + *pk = GNUNET_CRYPTO_rsa_public_key_decode(buf, + size); + GNUNET_free(buf); if (NULL == *pk) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Results contains bogus public key value (fail to decode)\n"); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Results contains bogus public key value (fail to decode)\n"); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -336,34 +336,34 @@ post_extract_rsa_public_key (void *cls, * @param rs result data to clean up */ static void -clean_rsa_public_key (void *cls, - struct GNUNET_MY_ResultSpec *rs) +clean_rsa_public_key(void *cls, + struct GNUNET_MY_ResultSpec *rs) { struct GNUNET_CRYPTO_RsaPublicKey **pk = rs->dst; if (NULL != *pk) - { - GNUNET_CRYPTO_rsa_public_key_free (*pk); - *pk = NULL; - } + { + GNUNET_CRYPTO_rsa_public_key_free(*pk); + *pk = NULL; + } } /** - * RSA public key expected - * - * @param name name of the field in the table - * @param[out] rsa where to store the result - * @return array entry for the result specification to use - */ + * RSA public key expected + * + * @param name name of the field in the table + * @param[out] rsa where to store the result + * @return array entry for the result specification to use + */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_rsa_public_key (struct GNUNET_CRYPTO_RsaPublicKey **rsa) +GNUNET_MY_result_spec_rsa_public_key(struct GNUNET_CRYPTO_RsaPublicKey **rsa) { struct GNUNET_MY_ResultSpec res = { .pre_conv = &pre_extract_rsa_public_key, .post_conv = &post_extract_rsa_public_key, .cleaner = &clean_rsa_public_key, - .dst = (void *) rsa, + .dst = (void *)rsa, .dst_size = 0, .num_fields = 1 }; @@ -373,23 +373,23 @@ GNUNET_MY_result_spec_rsa_public_key (struct GNUNET_CRYPTO_RsaPublicKey **rsa) /** - * Extract data from a Mysql database @a result at row @a row. - * - * @param cls closure - * @param[in,out] rs - * @param stmt the mysql statement that is being run - * @param column the column that is being processed - * @param[out] results - * @return - * #GNUNET_OK if all results could be extracted - * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) - */ + * Extract data from a Mysql database @a result at row @a row. + * + * @param cls closure + * @param[in,out] rs + * @param stmt the mysql statement that is being run + * @param column the column that is being processed + * @param[out] results + * @return + * #GNUNET_OK if all results could be extracted + * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) + */ static int -pre_extract_rsa_signature (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +pre_extract_rsa_signature(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { results[0].buffer = 0; results[0].buffer_length = 0; @@ -403,23 +403,23 @@ pre_extract_rsa_signature (void *cls, /** - * Extract data from a Mysql database @a result at row @a row. - * - * @param cls closure - * @param[in,out] rs - * @param stmt the mysql statement that is being run - * @param column the column that is being processed - * @param[out] results - * @return - * #GNUNET_OK if all results could be extracted - * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) - */ + * Extract data from a Mysql database @a result at row @a row. + * + * @param cls closure + * @param[in,out] rs + * @param stmt the mysql statement that is being run + * @param column the column that is being processed + * @param[out] results + * @return + * #GNUNET_OK if all results could be extracted + * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) + */ static int -post_extract_rsa_signature (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +post_extract_rsa_signature(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { struct GNUNET_CRYPTO_RsaSignature **sig = rs->dst; void *buf; @@ -427,34 +427,34 @@ post_extract_rsa_signature (void *cls, if (*results->is_null) return GNUNET_SYSERR; - size = (size_t) rs->mysql_bind_output_length; + size = (size_t)rs->mysql_bind_output_length; if (rs->mysql_bind_output_length != size) return GNUNET_SYSERR; /* 'unsigned long' does not fit in size_t!? */ - buf = GNUNET_malloc (size); + buf = GNUNET_malloc(size); results[0].buffer = buf; results[0].buffer_length = size; results[0].buffer_type = MYSQL_TYPE_BLOB; if (0 != - mysql_stmt_fetch_column (stmt, - results, - column, - 0)) - { - GNUNET_free (buf); - return GNUNET_SYSERR; - } - - *sig = GNUNET_CRYPTO_rsa_signature_decode (buf, - size); - GNUNET_free (buf); + mysql_stmt_fetch_column(stmt, + results, + column, + 0)) + { + GNUNET_free(buf); + return GNUNET_SYSERR; + } + + *sig = GNUNET_CRYPTO_rsa_signature_decode(buf, + size); + GNUNET_free(buf); if (NULL == *sig) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Resuls contains bogus signature value (fails to decode)\n"); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Resuls contains bogus signature value (fails to decode)\n"); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -467,27 +467,27 @@ post_extract_rsa_signature (void *cls, * @param rd result data to clean up */ static void -clean_rsa_signature (void *cls, - struct GNUNET_MY_ResultSpec *rs) +clean_rsa_signature(void *cls, + struct GNUNET_MY_ResultSpec *rs) { struct GNUNET_CRYPTO_RsaSignature **sig = rs->dst; if (NULL != *sig) - { - GNUNET_CRYPTO_rsa_signature_free (*sig); - *sig = NULL; - } + { + GNUNET_CRYPTO_rsa_signature_free(*sig); + *sig = NULL; + } } /** - * RSA signature expected. - * - * @param[out] sig where to store the result; - * @return array entry for the result specification to use - */ + * RSA signature expected. + * + * @param[out] sig where to store the result; + * @return array entry for the result specification to use + */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_rsa_signature (struct GNUNET_CRYPTO_RsaSignature **sig) +GNUNET_MY_result_spec_rsa_signature(struct GNUNET_CRYPTO_RsaSignature **sig) { struct GNUNET_MY_ResultSpec res = { @@ -498,6 +498,7 @@ GNUNET_MY_result_spec_rsa_signature (struct GNUNET_CRYPTO_RsaSignature **sig) .dst_size = 0, .num_fields = 1 }; + return res; } @@ -515,11 +516,11 @@ GNUNET_MY_result_spec_rsa_signature (struct GNUNET_CRYPTO_RsaSignature **sig) * #GNUNET_SYSERR if a result was invalid (non existing field or NULL) */ static int -pre_extract_string (void * cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +pre_extract_string(void * cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { results[0].buffer = NULL; results[0].buffer_length = 0; @@ -545,39 +546,39 @@ pre_extract_string (void * cls, * #GNUNET_SYSERR if a result was invalid (non existing field or NULL) */ static int -post_extract_string (void * cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +post_extract_string(void * cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { - size_t size = (size_t) rs->mysql_bind_output_length; + size_t size = (size_t)rs->mysql_bind_output_length; char *buf; if (rs->mysql_bind_output_length != size) return GNUNET_SYSERR; if (*results->is_null) - { - *(void **) rs->dst = NULL; - return GNUNET_OK; - } + { + *(void **)rs->dst = NULL; + return GNUNET_OK; + } - buf = GNUNET_malloc (size); + buf = GNUNET_malloc(size); results[0].buffer = buf; results[0].buffer_length = size; results[0].buffer_type = MYSQL_TYPE_BLOB; if (0 != - mysql_stmt_fetch_column (stmt, - results, - column, - 0)) - { - GNUNET_free (buf); - return GNUNET_SYSERR; - } + mysql_stmt_fetch_column(stmt, + results, + column, + 0)) + { + GNUNET_free(buf); + return GNUNET_SYSERR; + } buf[size] = '\0'; - *(void **) rs->dst = buf; + *(void **)rs->dst = buf; return GNUNET_OK; } @@ -589,16 +590,17 @@ post_extract_string (void * cls, * @return array entry for the result specification to use */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_string (char **dst) +GNUNET_MY_result_spec_string(char **dst) { struct GNUNET_MY_ResultSpec res = { .pre_conv = &pre_extract_string, .post_conv = &post_extract_string, .cleaner = NULL, - .dst = (void *) dst, + .dst = (void *)dst, .dst_size = 0, .num_fields = 1 }; + return res; } @@ -609,25 +611,26 @@ GNUNET_MY_result_spec_string (char **dst) * @param name name of the field in the table * @param[out] at where to store the result * @return array entry for the result specification to use - */ + */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_absolute_time (struct GNUNET_TIME_Absolute *at) +GNUNET_MY_result_spec_absolute_time(struct GNUNET_TIME_Absolute *at) { - return GNUNET_MY_result_spec_uint64 (&at->abs_value_us); + return GNUNET_MY_result_spec_uint64(&at->abs_value_us); } /** - * Absolute time in network byte order expected - * - * @param[out] at where to store the result - * @return array entry for the result specification to use - */ + * Absolute time in network byte order expected + * + * @param[out] at where to store the result + * @return array entry for the result specification to use + */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_absolute_time_nbo (struct GNUNET_TIME_AbsoluteNBO *at) +GNUNET_MY_result_spec_absolute_time_nbo(struct GNUNET_TIME_AbsoluteNBO *at) { struct GNUNET_MY_ResultSpec res = - GNUNET_MY_result_spec_auto_from_type (&at->abs_value_us__); + GNUNET_MY_result_spec_auto_from_type(&at->abs_value_us__); + return res; } @@ -645,11 +648,11 @@ GNUNET_MY_result_spec_absolute_time_nbo (struct GNUNET_TIME_AbsoluteNBO *at) * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) */ static int -pre_extract_uint16 (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +pre_extract_uint16(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { results[0].buffer = rs->dst; results[0].buffer_length = rs->dst_size; @@ -675,11 +678,11 @@ pre_extract_uint16 (void *cls, * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) */ static int -post_extract_uint16 (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +post_extract_uint16(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { if (rs->dst_size != rs->mysql_bind_output_length) return GNUNET_SYSERR; @@ -696,39 +699,40 @@ post_extract_uint16 (void *cls, * @return array entry for the result specification to use */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_uint16 (uint16_t *u16) +GNUNET_MY_result_spec_uint16(uint16_t *u16) { struct GNUNET_MY_ResultSpec res = { .pre_conv = &pre_extract_uint16, .post_conv = &post_extract_uint16, .cleaner = NULL, - .dst = (void *) u16, - .dst_size = sizeof (*u16), + .dst = (void *)u16, + .dst_size = sizeof(*u16), .num_fields = 1 }; + return res; } /** - * Extrac data from a MYSQL database @a result at row @a row - * - * @param cls closure - * @param cls closure - * @param[in,out] rs - * @param stmt the mysql statement that is being run - * @param column the column that is being processed - * @param[out] results - * @return - * #GNUNET_OK if all results could be extracted - * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) - */ + * Extrac data from a MYSQL database @a result at row @a row + * + * @param cls closure + * @param cls closure + * @param[in,out] rs + * @param stmt the mysql statement that is being run + * @param column the column that is being processed + * @param[out] results + * @return + * #GNUNET_OK if all results could be extracted + * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) + */ static int -pre_extract_uint32 (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +pre_extract_uint32(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { results[0].buffer = rs->dst; results[0].buffer_length = rs->dst_size; @@ -742,24 +746,24 @@ pre_extract_uint32 (void *cls, /** - * Extrac data from a MYSQL database @a result at row @a row - * - * @param cls closure - * @param cls closure - * @param[in,out] rs - * @param stmt the mysql statement that is being run - * @param column the column that is being processed - * @param[out] results - * @return - * #GNUNET_OK if all results could be extracted - * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) - */ + * Extrac data from a MYSQL database @a result at row @a row + * + * @param cls closure + * @param cls closure + * @param[in,out] rs + * @param stmt the mysql statement that is being run + * @param column the column that is being processed + * @param[out] results + * @return + * #GNUNET_OK if all results could be extracted + * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) + */ static int -post_extract_uint32 (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT * stmt, - unsigned int column, - MYSQL_BIND *results) +post_extract_uint32(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT * stmt, + unsigned int column, + MYSQL_BIND *results) { if (rs->dst_size != rs->mysql_bind_output_length) return GNUNET_SYSERR; @@ -770,22 +774,23 @@ post_extract_uint32 (void *cls, /** - * uint32_t expected - * - * @param[out] u32 where to store the result - * @return array entry for the result specification to use - */ + * uint32_t expected + * + * @param[out] u32 where to store the result + * @return array entry for the result specification to use + */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_uint32 (uint32_t *u32) +GNUNET_MY_result_spec_uint32(uint32_t *u32) { struct GNUNET_MY_ResultSpec res = { .pre_conv = &pre_extract_uint32, .post_conv = &post_extract_uint32, .cleaner = NULL, - .dst = (void *) u32, - .dst_size = sizeof (*u32), + .dst = (void *)u32, + .dst_size = sizeof(*u32), .num_fields = 1 }; + return res; } @@ -803,13 +808,13 @@ GNUNET_MY_result_spec_uint32 (uint32_t *u32) * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) */ static int -pre_extract_uint64 (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +pre_extract_uint64(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { - if (sizeof (uint64_t) != rs->dst_size) + if (sizeof(uint64_t) != rs->dst_size) return GNUNET_SYSERR; results[0].buffer = rs->dst; results[0].buffer_length = rs->dst_size; @@ -835,13 +840,13 @@ pre_extract_uint64 (void *cls, * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) */ static int -post_extract_uint64 (void *cls, - struct GNUNET_MY_ResultSpec *rs, - MYSQL_STMT *stmt, - unsigned int column, - MYSQL_BIND *results) +post_extract_uint64(void *cls, + struct GNUNET_MY_ResultSpec *rs, + MYSQL_STMT *stmt, + unsigned int column, + MYSQL_BIND *results) { - if (sizeof (uint64_t) != rs->dst_size) + if (sizeof(uint64_t) != rs->dst_size) return GNUNET_SYSERR; if (*results->is_null) return GNUNET_SYSERR; @@ -856,16 +861,17 @@ post_extract_uint64 (void *cls, * @return array entry for the result specification to use */ struct GNUNET_MY_ResultSpec -GNUNET_MY_result_spec_uint64 (uint64_t *u64) +GNUNET_MY_result_spec_uint64(uint64_t *u64) { struct GNUNET_MY_ResultSpec res = { .pre_conv = &pre_extract_uint64, .post_conv = &post_extract_uint64, .cleaner = NULL, - .dst = (void *) u64, - .dst_size = sizeof (*u64), + .dst = (void *)u64, + .dst_size = sizeof(*u64), .num_fields = 1 }; + return res; } diff --git a/src/my/test_my.c b/src/my/test_my.c index 556d2baa2..d9dcc71f9 100644 --- a/src/my/test_my.c +++ b/src/my/test_my.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file my/test_my.c * @brief Tests for convenience MySQL database @@ -30,23 +30,23 @@ /** - * Run actual test queries. - * - * @param contexte the current context of mysql - * @return 0 on succes - */ + * Run actual test queries. + * + * @param contexte the current context of mysql + * @return 0 on succes + */ static int -run_queries (struct GNUNET_MYSQL_Context *context) +run_queries(struct GNUNET_MYSQL_Context *context) { struct GNUNET_CRYPTO_RsaPublicKey *pub = NULL; struct GNUNET_CRYPTO_RsaPublicKey *pub2 = NULL; struct GNUNET_CRYPTO_RsaSignature *sig = NULL;; struct GNUNET_CRYPTO_RsaSignature *sig2 = NULL; - struct GNUNET_TIME_Absolute abs_time = GNUNET_TIME_absolute_get (); + struct GNUNET_TIME_Absolute abs_time = GNUNET_TIME_absolute_get(); struct GNUNET_TIME_Absolute abs_time2; struct GNUNET_TIME_Absolute forever = GNUNET_TIME_UNIT_FOREVER_ABS; struct GNUNET_TIME_Absolute forever2; - const struct GNUNET_TIME_AbsoluteNBO abs_time_nbo = GNUNET_TIME_absolute_hton (abs_time); + const struct GNUNET_TIME_AbsoluteNBO abs_time_nbo = GNUNET_TIME_absolute_hton(abs_time); struct GNUNET_HashCode hc; struct GNUNET_HashCode hc2; const char msg[] = "hello"; @@ -71,163 +71,163 @@ run_queries (struct GNUNET_MYSQL_Context *context) struct GNUNET_CRYPTO_RsaPrivateKey *priv = NULL; struct GNUNET_HashCode hmsg; - priv = GNUNET_CRYPTO_rsa_private_key_create (1024); - pub = GNUNET_CRYPTO_rsa_private_key_get_public (priv); - memset (&hmsg, 42, sizeof(hmsg)); - sig = GNUNET_CRYPTO_rsa_sign_fdh (priv, - &hmsg); + priv = GNUNET_CRYPTO_rsa_private_key_create(1024); + pub = GNUNET_CRYPTO_rsa_private_key_get_public(priv); + memset(&hmsg, 42, sizeof(hmsg)); + sig = GNUNET_CRYPTO_rsa_sign_fdh(priv, + &hmsg); u16 = 16; u32 = 32; u64 = UINT64_MAX; - memset (&hc, 0, sizeof(hc)); - memset (&hc2, 0, sizeof(hc2)); + memset(&hc, 0, sizeof(hc)); + memset(&hc2, 0, sizeof(hc2)); statements_handle_insert - = GNUNET_MYSQL_statement_prepare (context, - "INSERT INTO test_my2 (" - " pub" - ",sig" - ",abs_time" - ",forever" - ",abs_time_nbo" - ",hash" - ",vsize" - ",str" - ",u16" - ",u32" - ",u64" - ") VALUES " - "( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + = GNUNET_MYSQL_statement_prepare(context, + "INSERT INTO test_my2 (" + " pub" + ",sig" + ",abs_time" + ",forever" + ",abs_time_nbo" + ",hash" + ",vsize" + ",str" + ",u16" + ",u32" + ",u64" + ") VALUES " + "( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); if (NULL == statements_handle_insert) - { - fprintf (stderr, "Failed to prepared statement INSERT\n"); - GNUNET_CRYPTO_rsa_signature_free (sig); - GNUNET_CRYPTO_rsa_private_key_free (priv); - GNUNET_CRYPTO_rsa_public_key_free (pub); - return 1; - } + { + fprintf(stderr, "Failed to prepared statement INSERT\n"); + GNUNET_CRYPTO_rsa_signature_free(sig); + GNUNET_CRYPTO_rsa_private_key_free(priv); + GNUNET_CRYPTO_rsa_public_key_free(pub); + return 1; + } struct GNUNET_MY_QueryParam params_insert[] = { - GNUNET_MY_query_param_rsa_public_key (pub), - GNUNET_MY_query_param_rsa_signature (sig), - GNUNET_MY_query_param_absolute_time (&abs_time), - GNUNET_MY_query_param_absolute_time (&forever), - GNUNET_MY_query_param_absolute_time_nbo (&abs_time_nbo), - GNUNET_MY_query_param_auto_from_type (&hc), - GNUNET_MY_query_param_fixed_size (msg, strlen (msg)), - GNUNET_MY_query_param_string (msg3), - GNUNET_MY_query_param_uint16 (&u16), - GNUNET_MY_query_param_uint32 (&u32), - GNUNET_MY_query_param_uint64 (&u64), + GNUNET_MY_query_param_rsa_public_key(pub), + GNUNET_MY_query_param_rsa_signature(sig), + GNUNET_MY_query_param_absolute_time(&abs_time), + GNUNET_MY_query_param_absolute_time(&forever), + GNUNET_MY_query_param_absolute_time_nbo(&abs_time_nbo), + GNUNET_MY_query_param_auto_from_type(&hc), + GNUNET_MY_query_param_fixed_size(msg, strlen(msg)), + GNUNET_MY_query_param_string(msg3), + GNUNET_MY_query_param_uint16(&u16), + GNUNET_MY_query_param_uint32(&u32), + GNUNET_MY_query_param_uint64(&u64), GNUNET_MY_query_param_end }; if (GNUNET_OK != GNUNET_MY_exec_prepared(context, - statements_handle_insert, - params_insert)) - { - fprintf (stderr, "Failed to execute prepared statement INSERT\n"); - GNUNET_CRYPTO_rsa_signature_free (sig); - GNUNET_CRYPTO_rsa_private_key_free (priv); - GNUNET_CRYPTO_rsa_public_key_free (pub); + statements_handle_insert, + params_insert)) + { + fprintf(stderr, "Failed to execute prepared statement INSERT\n"); + GNUNET_CRYPTO_rsa_signature_free(sig); + GNUNET_CRYPTO_rsa_private_key_free(priv); + GNUNET_CRYPTO_rsa_public_key_free(pub); return 1; - } + } statements_handle_select - = GNUNET_MYSQL_statement_prepare (context, - "SELECT" - " pub" - ",sig" - ",abs_time" - ",forever" - ",hash" - ",vsize" - ",str" - ",u16" - ",u32" - ",u64" - " FROM test_my2"); + = GNUNET_MYSQL_statement_prepare(context, + "SELECT" + " pub" + ",sig" + ",abs_time" + ",forever" + ",hash" + ",vsize" + ",str" + ",u16" + ",u32" + ",u64" + " FROM test_my2"); if (NULL == statements_handle_select) - { - fprintf(stderr, "Failed to prepared statement SELECT\n"); - GNUNET_CRYPTO_rsa_signature_free (sig); - GNUNET_CRYPTO_rsa_private_key_free (priv); - GNUNET_CRYPTO_rsa_public_key_free (pub); - return 1; - } + { + fprintf(stderr, "Failed to prepared statement SELECT\n"); + GNUNET_CRYPTO_rsa_signature_free(sig); + GNUNET_CRYPTO_rsa_private_key_free(priv); + GNUNET_CRYPTO_rsa_public_key_free(pub); + return 1; + } struct GNUNET_MY_QueryParam params_select[] = { GNUNET_MY_query_param_end }; - if (GNUNET_OK != GNUNET_MY_exec_prepared (context, - statements_handle_select, - params_select)) - { - fprintf (stderr, "Failed to execute prepared statement SELECT\n"); - GNUNET_CRYPTO_rsa_signature_free (sig); - GNUNET_CRYPTO_rsa_private_key_free (priv); - GNUNET_CRYPTO_rsa_public_key_free (pub); - return 1; - } + if (GNUNET_OK != GNUNET_MY_exec_prepared(context, + statements_handle_select, + params_select)) + { + fprintf(stderr, "Failed to execute prepared statement SELECT\n"); + GNUNET_CRYPTO_rsa_signature_free(sig); + GNUNET_CRYPTO_rsa_private_key_free(priv); + GNUNET_CRYPTO_rsa_public_key_free(pub); + return 1; + } struct GNUNET_MY_ResultSpec results_select[] = { - GNUNET_MY_result_spec_rsa_public_key (&pub2), - GNUNET_MY_result_spec_rsa_signature (&sig2), - GNUNET_MY_result_spec_absolute_time (&abs_time2), - GNUNET_MY_result_spec_absolute_time (&forever2), - GNUNET_MY_result_spec_auto_from_type (&hc2), - GNUNET_MY_result_spec_variable_size (&msg2, &msg2_len), - GNUNET_MY_result_spec_string (&msg4), - GNUNET_MY_result_spec_uint16 (&u162), - GNUNET_MY_result_spec_uint32 (&u322), - GNUNET_MY_result_spec_uint64 (&u642), + GNUNET_MY_result_spec_rsa_public_key(&pub2), + GNUNET_MY_result_spec_rsa_signature(&sig2), + GNUNET_MY_result_spec_absolute_time(&abs_time2), + GNUNET_MY_result_spec_absolute_time(&forever2), + GNUNET_MY_result_spec_auto_from_type(&hc2), + GNUNET_MY_result_spec_variable_size(&msg2, &msg2_len), + GNUNET_MY_result_spec_string(&msg4), + GNUNET_MY_result_spec_uint16(&u162), + GNUNET_MY_result_spec_uint32(&u322), + GNUNET_MY_result_spec_uint64(&u642), GNUNET_MY_result_spec_end }; - ret = GNUNET_MY_extract_result (statements_handle_select, - results_select); - - GNUNET_assert (GNUNET_YES == ret); - GNUNET_break (abs_time.abs_value_us == abs_time2.abs_value_us); - GNUNET_break (forever.abs_value_us == forever2.abs_value_us); - GNUNET_break (0 == - memcmp (&hc, - &hc2, - sizeof (struct GNUNET_HashCode))); - - GNUNET_assert (NULL != sig2); - GNUNET_assert (NULL != pub2); - GNUNET_break (0 == - GNUNET_CRYPTO_rsa_signature_cmp (sig, - sig2)); - GNUNET_break (0 == - GNUNET_CRYPTO_rsa_public_key_cmp (pub, - pub2)); - - GNUNET_break (strlen (msg) == msg2_len); - GNUNET_break (0 == - strncmp (msg, - msg2, - msg2_len)); - - GNUNET_break (strlen (msg3) == strlen(msg4)); - GNUNET_break (0 == - strcmp (msg3, - msg4)); - - GNUNET_break (16 == u162); - GNUNET_break (32 == u322); - GNUNET_break (UINT64_MAX == u642); - - GNUNET_MY_cleanup_result (results_select); - - GNUNET_CRYPTO_rsa_signature_free (sig); - GNUNET_CRYPTO_rsa_private_key_free (priv); - GNUNET_CRYPTO_rsa_public_key_free (pub); + ret = GNUNET_MY_extract_result(statements_handle_select, + results_select); + + GNUNET_assert(GNUNET_YES == ret); + GNUNET_break(abs_time.abs_value_us == abs_time2.abs_value_us); + GNUNET_break(forever.abs_value_us == forever2.abs_value_us); + GNUNET_break(0 == + memcmp(&hc, + &hc2, + sizeof(struct GNUNET_HashCode))); + + GNUNET_assert(NULL != sig2); + GNUNET_assert(NULL != pub2); + GNUNET_break(0 == + GNUNET_CRYPTO_rsa_signature_cmp(sig, + sig2)); + GNUNET_break(0 == + GNUNET_CRYPTO_rsa_public_key_cmp(pub, + pub2)); + + GNUNET_break(strlen(msg) == msg2_len); + GNUNET_break(0 == + strncmp(msg, + msg2, + msg2_len)); + + GNUNET_break(strlen(msg3) == strlen(msg4)); + GNUNET_break(0 == + strcmp(msg3, + msg4)); + + GNUNET_break(16 == u162); + GNUNET_break(32 == u322); + GNUNET_break(UINT64_MAX == u642); + + GNUNET_MY_cleanup_result(results_select); + + GNUNET_CRYPTO_rsa_signature_free(sig); + GNUNET_CRYPTO_rsa_private_key_free(priv); + GNUNET_CRYPTO_rsa_public_key_free(pub); if (GNUNET_OK != ret) return 1; @@ -237,63 +237,63 @@ run_queries (struct GNUNET_MYSQL_Context *context) int -main (int argc, const char *const argv[]) +main(int argc, const char *const argv[]) { struct GNUNET_CONFIGURATION_Handle *config; struct GNUNET_MYSQL_Context *context; int ret; - GNUNET_log_setup ("test-my", - "WARNING", - NULL); + GNUNET_log_setup("test-my", + "WARNING", + NULL); - config = GNUNET_CONFIGURATION_create (); + config = GNUNET_CONFIGURATION_create(); if (GNUNET_OK != - GNUNET_CONFIGURATION_parse (config, "test_my.conf")) - { - fprintf (stderr, "Failed to parse configuaration\n"); - return 1; - } + GNUNET_CONFIGURATION_parse(config, "test_my.conf")) + { + fprintf(stderr, "Failed to parse configuaration\n"); + return 1; + } - context = GNUNET_MYSQL_context_create (config, - "datastore-mysql"); + context = GNUNET_MYSQL_context_create(config, + "datastore-mysql"); if (NULL == context) - { - fprintf(stderr, "Failed to connect to database\n"); - return 77; - } + { + fprintf(stderr, "Failed to connect to database\n"); + return 77; + } - (void) GNUNET_MYSQL_statement_run (context, - "DROP TABLE test_my2;"); + (void)GNUNET_MYSQL_statement_run(context, + "DROP TABLE test_my2;"); if (GNUNET_OK != - GNUNET_MYSQL_statement_run (context, - "CREATE TABLE IF NOT EXISTS test_my2(" - " pub BLOB NOT NULL" - ",sig BLOB NOT NULL" - ",abs_time BIGINT NOT NULL" - ",forever BIGINT NOT NULL" - ",abs_time_nbo BIGINT NOT NULL" - ",hash BLOB NOT NULL CHECK(LENGTH(hash)=64)" - ",vsize BLOB NOT NULL" - ",str BLOB NOT NULL" - ",u16 SMALLINT NOT NULL" - ",u32 INT NOT NULL" - ",u64 BIGINT NOT NULL" - ")")) - { - fprintf (stderr, - "Failed to create table. Database likely not setup correctly.\n"); - GNUNET_MYSQL_statements_invalidate (context); - GNUNET_MYSQL_context_destroy (context); - - return 77; - } - - ret = run_queries (context); - - GNUNET_MYSQL_context_destroy (context); - GNUNET_free (config); + GNUNET_MYSQL_statement_run(context, + "CREATE TABLE IF NOT EXISTS test_my2(" + " pub BLOB NOT NULL" + ",sig BLOB NOT NULL" + ",abs_time BIGINT NOT NULL" + ",forever BIGINT NOT NULL" + ",abs_time_nbo BIGINT NOT NULL" + ",hash BLOB NOT NULL CHECK(LENGTH(hash)=64)" + ",vsize BLOB NOT NULL" + ",str BLOB NOT NULL" + ",u16 SMALLINT NOT NULL" + ",u32 INT NOT NULL" + ",u64 BIGINT NOT NULL" + ")")) + { + fprintf(stderr, + "Failed to create table. Database likely not setup correctly.\n"); + GNUNET_MYSQL_statements_invalidate(context); + GNUNET_MYSQL_context_destroy(context); + + return 77; + } + + ret = run_queries(context); + + GNUNET_MYSQL_context_destroy(context); + GNUNET_free(config); return ret; } diff --git a/src/mysql/mysql.c b/src/mysql/mysql.c index c78fbeb4b..50f5683d7 100644 --- a/src/mysql/mysql.c +++ b/src/mysql/mysql.c @@ -12,12 +12,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file mysql/mysql.c * @brief library to help with access to a MySQL database @@ -41,16 +41,16 @@ */ #define DIE_MYSQL(cmd, dbh) \ do \ - { \ - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, \ - "mysql", \ - _ ("`%s' failed at %s:%d with error: %s\n"), \ - cmd, \ - __FILE__, \ - __LINE__, \ - mysql_error ((dbh)->dbf)); \ - GNUNET_assert (0); \ - } while (0); + { \ + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, \ + "mysql", \ + _("`%s' failed at %s:%d with error: %s\n"), \ + cmd, \ + __FILE__, \ + __LINE__, \ + mysql_error((dbh)->dbf)); \ + GNUNET_assert(0); \ + } while (0); /** * Log an error message at log-level 'level' that indicates @@ -59,23 +59,21 @@ */ #define LOG_MYSQL(level, cmd, dbh) \ do \ - { \ - GNUNET_log_from (level, \ - "mysql", \ - _ ("`%s' failed at %s:%d with error: %s\n"), \ - cmd, \ - __FILE__, \ - __LINE__, \ - mysql_error ((dbh)->dbf)); \ - } while (0); + { \ + GNUNET_log_from(level, \ + "mysql", \ + _("`%s' failed at %s:%d with error: %s\n"), \ + cmd, \ + __FILE__, \ + __LINE__, \ + mysql_error((dbh)->dbf)); \ + } while (0); /** * Mysql context. */ -struct GNUNET_MYSQL_Context -{ - +struct GNUNET_MYSQL_Context { /** * Our configuration. */ @@ -111,9 +109,7 @@ struct GNUNET_MYSQL_Context /** * Handle for a prepared statement. */ -struct GNUNET_MYSQL_StatementHandle -{ - +struct GNUNET_MYSQL_StatementHandle { /** * Kept in a DLL. */ @@ -154,8 +150,8 @@ struct GNUNET_MYSQL_StatementHandle * @return NULL on error */ static char * -get_my_cnf_path (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section) +get_my_cnf_path(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section) { char *cnffile; char *home_dir; @@ -167,51 +163,51 @@ get_my_cnf_path (const struct GNUNET_CONFIGURATION_Handle *cfg, int configured; #ifndef WINDOWS - pw = getpwuid (getuid ()); - if (! pw) - { - GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_ERROR, "mysql", "getpwuid"); - return NULL; - } - if (GNUNET_YES == GNUNET_CONFIGURATION_have_value (cfg, section, "CONFIG")) - { - GNUNET_assert (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_filename (cfg, + pw = getpwuid(getuid()); + if (!pw) + { + GNUNET_log_from_strerror(GNUNET_ERROR_TYPE_ERROR, "mysql", "getpwuid"); + return NULL; + } + if (GNUNET_YES == GNUNET_CONFIGURATION_have_value(cfg, section, "CONFIG")) + { + GNUNET_assert(GNUNET_OK == + GNUNET_CONFIGURATION_get_value_filename(cfg, section, "CONFIG", &cnffile)); - configured = GNUNET_YES; - } + configured = GNUNET_YES; + } else - { - home_dir = GNUNET_strdup (pw->pw_dir); - GNUNET_asprintf (&cnffile, "%s/.my.cnf", home_dir); - GNUNET_free (home_dir); - configured = GNUNET_NO; - } + { + home_dir = GNUNET_strdup(pw->pw_dir); + GNUNET_asprintf(&cnffile, "%s/.my.cnf", home_dir); + GNUNET_free(home_dir); + configured = GNUNET_NO; + } #else - home_dir = (char *) GNUNET_malloc (_MAX_PATH + 1); - plibc_conv_to_win_path ("~/", home_dir); - GNUNET_asprintf (&cnffile, "%s/.my.cnf", home_dir); - GNUNET_free (home_dir); + home_dir = (char *)GNUNET_malloc(_MAX_PATH + 1); + plibc_conv_to_win_path("~/", home_dir); + GNUNET_asprintf(&cnffile, "%s/.my.cnf", home_dir); + GNUNET_free(home_dir); configured = GNUNET_NO; #endif - GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, - "mysql", - _ ("Trying to use file `%s' for MySQL configuration.\n"), - cnffile); - if ((0 != STAT (cnffile, &st)) || (0 != ACCESS (cnffile, R_OK)) || - (! S_ISREG (st.st_mode))) - { - if (configured == GNUNET_YES) - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "mysql", - _ ("Could not access file `%s': %s\n"), - cnffile, - strerror (errno)); - GNUNET_free (cnffile); - return NULL; - } + GNUNET_log_from(GNUNET_ERROR_TYPE_INFO, + "mysql", + _("Trying to use file `%s' for MySQL configuration.\n"), + cnffile); + if ((0 != STAT(cnffile, &st)) || (0 != ACCESS(cnffile, R_OK)) || + (!S_ISREG(st.st_mode))) + { + if (configured == GNUNET_YES) + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "mysql", + _("Could not access file `%s': %s\n"), + cnffile, + strerror(errno)); + GNUNET_free(cnffile); + return NULL; + } return cnffile; } @@ -224,7 +220,7 @@ get_my_cnf_path (const struct GNUNET_CONFIGURATION_Handle *cfg, * @return #GNUNET_OK on success */ static int -iopen (struct GNUNET_MYSQL_Context *mc) +iopen(struct GNUNET_MYSQL_Context *mc) { char *mysql_dbname; char *mysql_server; @@ -234,88 +230,88 @@ iopen (struct GNUNET_MYSQL_Context *mc) my_bool reconnect; unsigned int timeout; - mc->dbf = mysql_init (NULL); + mc->dbf = mysql_init(NULL); if (mc->dbf == NULL) return GNUNET_SYSERR; if (mc->cnffile != NULL) - mysql_options (mc->dbf, MYSQL_READ_DEFAULT_FILE, mc->cnffile); - mysql_options (mc->dbf, MYSQL_READ_DEFAULT_GROUP, "client"); + mysql_options(mc->dbf, MYSQL_READ_DEFAULT_FILE, mc->cnffile); + mysql_options(mc->dbf, MYSQL_READ_DEFAULT_GROUP, "client"); reconnect = 0; - mysql_options (mc->dbf, MYSQL_OPT_RECONNECT, &reconnect); - mysql_options (mc->dbf, MYSQL_OPT_CONNECT_TIMEOUT, (const void *) &timeout); - mysql_options (mc->dbf, MYSQL_SET_CHARSET_NAME, "UTF8"); + mysql_options(mc->dbf, MYSQL_OPT_RECONNECT, &reconnect); + mysql_options(mc->dbf, MYSQL_OPT_CONNECT_TIMEOUT, (const void *)&timeout); + mysql_options(mc->dbf, MYSQL_SET_CHARSET_NAME, "UTF8"); timeout = 60; /* in seconds */ - mysql_options (mc->dbf, MYSQL_OPT_READ_TIMEOUT, (const void *) &timeout); - mysql_options (mc->dbf, MYSQL_OPT_WRITE_TIMEOUT, (const void *) &timeout); + mysql_options(mc->dbf, MYSQL_OPT_READ_TIMEOUT, (const void *)&timeout); + mysql_options(mc->dbf, MYSQL_OPT_WRITE_TIMEOUT, (const void *)&timeout); mysql_dbname = NULL; if (GNUNET_YES == - GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section, "DATABASE")) - GNUNET_assert (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (mc->cfg, - mc->section, - "DATABASE", - &mysql_dbname)); + GNUNET_CONFIGURATION_have_value(mc->cfg, mc->section, "DATABASE")) + GNUNET_assert(GNUNET_OK == + GNUNET_CONFIGURATION_get_value_string(mc->cfg, + mc->section, + "DATABASE", + &mysql_dbname)); else - mysql_dbname = GNUNET_strdup ("gnunet"); + mysql_dbname = GNUNET_strdup("gnunet"); mysql_user = NULL; if (GNUNET_YES == - GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section, "USER")) - { - GNUNET_assert (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (mc->cfg, + GNUNET_CONFIGURATION_have_value(mc->cfg, mc->section, "USER")) + { + GNUNET_assert(GNUNET_OK == + GNUNET_CONFIGURATION_get_value_string(mc->cfg, mc->section, "USER", &mysql_user)); - } + } mysql_password = NULL; if (GNUNET_YES == - GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section, "PASSWORD")) - { - GNUNET_assert (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (mc->cfg, + GNUNET_CONFIGURATION_have_value(mc->cfg, mc->section, "PASSWORD")) + { + GNUNET_assert(GNUNET_OK == + GNUNET_CONFIGURATION_get_value_string(mc->cfg, mc->section, "PASSWORD", &mysql_password)); - } + } mysql_server = NULL; if (GNUNET_YES == - GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section, "HOST")) - { - GNUNET_assert (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (mc->cfg, + GNUNET_CONFIGURATION_have_value(mc->cfg, mc->section, "HOST")) + { + GNUNET_assert(GNUNET_OK == + GNUNET_CONFIGURATION_get_value_string(mc->cfg, mc->section, "HOST", &mysql_server)); - } + } mysql_port = 0; if (GNUNET_YES == - GNUNET_CONFIGURATION_have_value (mc->cfg, mc->section, "PORT")) - { - GNUNET_assert (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_number (mc->cfg, + GNUNET_CONFIGURATION_have_value(mc->cfg, mc->section, "PORT")) + { + GNUNET_assert(GNUNET_OK == + GNUNET_CONFIGURATION_get_value_number(mc->cfg, mc->section, "PORT", &mysql_port)); - } - - GNUNET_assert (mysql_dbname != NULL); - mysql_real_connect (mc->dbf, - mysql_server, - mysql_user, - mysql_password, - mysql_dbname, - (unsigned int) mysql_port, - NULL, - CLIENT_IGNORE_SIGPIPE); - GNUNET_free_non_null (mysql_server); - GNUNET_free_non_null (mysql_user); - GNUNET_free_non_null (mysql_password); - GNUNET_free (mysql_dbname); - if (mysql_error (mc->dbf)[0]) - { - LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR, "mysql_real_connect", mc); - return GNUNET_SYSERR; - } + } + + GNUNET_assert(mysql_dbname != NULL); + mysql_real_connect(mc->dbf, + mysql_server, + mysql_user, + mysql_password, + mysql_dbname, + (unsigned int)mysql_port, + NULL, + CLIENT_IGNORE_SIGPIPE); + GNUNET_free_non_null(mysql_server); + GNUNET_free_non_null(mysql_user); + GNUNET_free_non_null(mysql_password); + GNUNET_free(mysql_dbname); + if (mysql_error(mc->dbf)[0]) + { + LOG_MYSQL(GNUNET_ERROR_TYPE_ERROR, "mysql_real_connect", mc); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -328,15 +324,15 @@ iopen (struct GNUNET_MYSQL_Context *mc) * @return the mysql context */ struct GNUNET_MYSQL_Context * -GNUNET_MYSQL_context_create (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *section) +GNUNET_MYSQL_context_create(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *section) { struct GNUNET_MYSQL_Context *mc; - mc = GNUNET_new (struct GNUNET_MYSQL_Context); + mc = GNUNET_new(struct GNUNET_MYSQL_Context); mc->cfg = cfg; mc->section = section; - mc->cnffile = get_my_cnf_path (cfg, section); + mc->cnffile = get_my_cnf_path(cfg, section); return mc; } @@ -349,24 +345,24 @@ GNUNET_MYSQL_context_create (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param mc mysql context */ void -GNUNET_MYSQL_statements_invalidate (struct GNUNET_MYSQL_Context *mc) +GNUNET_MYSQL_statements_invalidate(struct GNUNET_MYSQL_Context *mc) { struct GNUNET_MYSQL_StatementHandle *sh; for (sh = mc->shead; NULL != sh; sh = sh->next) - { - if (GNUNET_YES == sh->valid) { - mysql_stmt_close (sh->statement); - sh->valid = GNUNET_NO; + if (GNUNET_YES == sh->valid) + { + mysql_stmt_close(sh->statement); + sh->valid = GNUNET_NO; + } + sh->statement = NULL; } - sh->statement = NULL; - } if (NULL != mc->dbf) - { - mysql_close (mc->dbf); - mc->dbf = NULL; - } + { + mysql_close(mc->dbf); + mc->dbf = NULL; + } } @@ -376,19 +372,19 @@ GNUNET_MYSQL_statements_invalidate (struct GNUNET_MYSQL_Context *mc) * @param mc context to destroy */ void -GNUNET_MYSQL_context_destroy (struct GNUNET_MYSQL_Context *mc) +GNUNET_MYSQL_context_destroy(struct GNUNET_MYSQL_Context *mc) { struct GNUNET_MYSQL_StatementHandle *sh; - GNUNET_MYSQL_statements_invalidate (mc); + GNUNET_MYSQL_statements_invalidate(mc); while (NULL != (sh = mc->shead)) - { - GNUNET_CONTAINER_DLL_remove (mc->shead, mc->stail, sh); - GNUNET_free (sh->query); - GNUNET_free (sh); - } - GNUNET_free (mc); - mysql_library_end (); + { + GNUNET_CONTAINER_DLL_remove(mc->shead, mc->stail, sh); + GNUNET_free(sh->query); + GNUNET_free(sh); + } + GNUNET_free(mc); + mysql_library_end(); } @@ -401,15 +397,15 @@ GNUNET_MYSQL_context_destroy (struct GNUNET_MYSQL_Context *mc) * @return prepared statement, NULL on error */ struct GNUNET_MYSQL_StatementHandle * -GNUNET_MYSQL_statement_prepare (struct GNUNET_MYSQL_Context *mc, - const char *query) +GNUNET_MYSQL_statement_prepare(struct GNUNET_MYSQL_Context *mc, + const char *query) { struct GNUNET_MYSQL_StatementHandle *sh; - sh = GNUNET_new (struct GNUNET_MYSQL_StatementHandle); + sh = GNUNET_new(struct GNUNET_MYSQL_StatementHandle); sh->mc = mc; - sh->query = GNUNET_strdup (query); - GNUNET_CONTAINER_DLL_insert (mc->shead, mc->stail, sh); + sh->query = GNUNET_strdup(query); + GNUNET_CONTAINER_DLL_insert(mc->shead, mc->stail, sh); return sh; } @@ -423,17 +419,17 @@ GNUNET_MYSQL_statement_prepare (struct GNUNET_MYSQL_Context *mc, * #GNUNET_SYSERR if there was a problem */ int -GNUNET_MYSQL_statement_run (struct GNUNET_MYSQL_Context *mc, const char *sql) +GNUNET_MYSQL_statement_run(struct GNUNET_MYSQL_Context *mc, const char *sql) { - if ((NULL == mc->dbf) && (GNUNET_OK != iopen (mc))) - return GNUNET_SYSERR; - mysql_query (mc->dbf, sql); - if (mysql_error (mc->dbf)[0]) - { - LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR, "mysql_query", mc); - GNUNET_MYSQL_statements_invalidate (mc); + if ((NULL == mc->dbf) && (GNUNET_OK != iopen(mc))) return GNUNET_SYSERR; - } + mysql_query(mc->dbf, sql); + if (mysql_error(mc->dbf)[0]) + { + LOG_MYSQL(GNUNET_ERROR_TYPE_ERROR, "mysql_query", mc); + GNUNET_MYSQL_statements_invalidate(mc); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -446,32 +442,32 @@ GNUNET_MYSQL_statement_run (struct GNUNET_MYSQL_Context *mc, const char *sql) * @return #GNUNET_OK on success */ static int -prepare_statement (struct GNUNET_MYSQL_StatementHandle *sh) +prepare_statement(struct GNUNET_MYSQL_StatementHandle *sh) { struct GNUNET_MYSQL_Context *mc = sh->mc; if (GNUNET_YES == sh->valid) return GNUNET_OK; - if ((NULL == mc->dbf) && (GNUNET_OK != iopen (mc))) + if ((NULL == mc->dbf) && (GNUNET_OK != iopen(mc))) return GNUNET_SYSERR; - sh->statement = mysql_stmt_init (mc->dbf); + sh->statement = mysql_stmt_init(mc->dbf); if (NULL == sh->statement) - { - GNUNET_MYSQL_statements_invalidate (mc); - return GNUNET_SYSERR; - } - if (0 != mysql_stmt_prepare (sh->statement, sh->query, strlen (sh->query))) - { - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "mysql", - "prepare_statement: %s\n", - sh->query); - LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR, "mysql_stmt_prepare", mc); - mysql_stmt_close (sh->statement); - sh->statement = NULL; - GNUNET_MYSQL_statements_invalidate (mc); - return GNUNET_SYSERR; - } + { + GNUNET_MYSQL_statements_invalidate(mc); + return GNUNET_SYSERR; + } + if (0 != mysql_stmt_prepare(sh->statement, sh->query, strlen(sh->query))) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "mysql", + "prepare_statement: %s\n", + sh->query); + LOG_MYSQL(GNUNET_ERROR_TYPE_ERROR, "mysql_stmt_prepare", mc); + mysql_stmt_close(sh->statement); + sh->statement = NULL; + GNUNET_MYSQL_statements_invalidate(mc); + return GNUNET_SYSERR; + } sh->valid = GNUNET_YES; return GNUNET_OK; } @@ -486,9 +482,9 @@ prepare_statement (struct GNUNET_MYSQL_StatementHandle *sh) * @return MySQL statement handle, NULL on error */ MYSQL_STMT * -GNUNET_MYSQL_statement_get_stmt (struct GNUNET_MYSQL_StatementHandle *sh) +GNUNET_MYSQL_statement_get_stmt(struct GNUNET_MYSQL_StatementHandle *sh) { - (void) prepare_statement (sh); + (void)prepare_statement(sh); return sh->statement; } diff --git a/src/namecache/gnunet-namecache.c b/src/namecache/gnunet-namecache.c index 509f86fc0..2d387b543 100644 --- a/src/namecache/gnunet-namecache.c +++ b/src/namecache/gnunet-namecache.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnunet-namecache.c * @brief command line tool to inspect the name cache @@ -70,18 +70,18 @@ static int ret; * @param cls unused */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { if (NULL != qe) - { - GNUNET_NAMECACHE_cancel (qe); - qe = NULL; - } + { + GNUNET_NAMECACHE_cancel(qe); + qe = NULL; + } if (NULL != ns) - { - GNUNET_NAMECACHE_disconnect (ns); - ns = NULL; - } + { + GNUNET_NAMECACHE_disconnect(ns); + ns = NULL; + } } @@ -93,37 +93,37 @@ do_shutdown (void *cls) * @param rd array of records with data to store */ static void -display_records_from_block (void *cls, - unsigned int rd_len, - const struct GNUNET_GNSRECORD_Data *rd) +display_records_from_block(void *cls, + unsigned int rd_len, + const struct GNUNET_GNSRECORD_Data *rd) { const char *typestring; char *s; unsigned int i; if (0 == rd_len) - { - fprintf (stdout, _ ("No records found for `%s'"), name); - return; - } - fprintf (stdout, "%s:\n", name); + { + fprintf(stdout, _("No records found for `%s'"), name); + return; + } + fprintf(stdout, "%s:\n", name); for (i = 0; i < rd_len; i++) - { - typestring = GNUNET_GNSRECORD_number_to_typename (rd[i].record_type); - s = GNUNET_GNSRECORD_value_to_string (rd[i].record_type, - rd[i].data, - rd[i].data_size); - if (NULL == s) { - fprintf (stdout, - _ ("\tCorrupt or unsupported record of type %u\n"), - (unsigned int) rd[i].record_type); - continue; + typestring = GNUNET_GNSRECORD_number_to_typename(rd[i].record_type); + s = GNUNET_GNSRECORD_value_to_string(rd[i].record_type, + rd[i].data, + rd[i].data_size); + if (NULL == s) + { + fprintf(stdout, + _("\tCorrupt or unsupported record of type %u\n"), + (unsigned int)rd[i].record_type); + continue; + } + fprintf(stdout, "\t%s: %s\n", typestring, s); + GNUNET_free(s); } - fprintf (stdout, "\t%s: %s\n", typestring, s); - GNUNET_free (s); - } - fprintf (stdout, "%s", "\n"); + fprintf(stdout, "%s", "\n"); } @@ -134,23 +134,23 @@ display_records_from_block (void *cls, * @param block NULL if not found */ static void -handle_block (void *cls, const struct GNUNET_GNSRECORD_Block *block) +handle_block(void *cls, const struct GNUNET_GNSRECORD_Block *block) { qe = NULL; if (NULL == block) - { - fprintf (stderr, "No matching block found\n"); - } + { + fprintf(stderr, "No matching block found\n"); + } else if (GNUNET_OK != - GNUNET_GNSRECORD_block_decrypt (block, - &pubkey, - name, - &display_records_from_block, - NULL)) - { - fprintf (stderr, "Failed to decrypt block!\n"); - } - GNUNET_SCHEDULER_shutdown (); + GNUNET_GNSRECORD_block_decrypt(block, + &pubkey, + name, + &display_records_from_block, + NULL)) + { + fprintf(stderr, "Failed to decrypt block!\n"); + } + GNUNET_SCHEDULER_shutdown(); } @@ -163,36 +163,36 @@ handle_block (void *cls, const struct GNUNET_GNSRECORD_Block *block) * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_HashCode dhash; if (NULL == pkey) - { - fprintf (stderr, _ ("You must specify which zone should be accessed\n")); - return; - } + { + fprintf(stderr, _("You must specify which zone should be accessed\n")); + return; + } if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (pkey, strlen (pkey), &pubkey)) - { - fprintf (stderr, _ ("Invalid public key for zone `%s'\n"), pkey); - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_CRYPTO_ecdsa_public_key_from_string(pkey, strlen(pkey), &pubkey)) + { + fprintf(stderr, _("Invalid public key for zone `%s'\n"), pkey); + GNUNET_SCHEDULER_shutdown(); + return; + } if (NULL == name) - { - fprintf (stderr, _ ("You must specify a name\n")); - return; - } - - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL); - ns = GNUNET_NAMECACHE_connect (cfg); - GNUNET_GNSRECORD_query_from_public_key (&pubkey, name, &dhash); - qe = GNUNET_NAMECACHE_lookup_block (ns, &dhash, &handle_block, NULL); + { + fprintf(stderr, _("You must specify a name\n")); + return; + } + + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); + ns = GNUNET_NAMECACHE_connect(cfg); + GNUNET_GNSRECORD_query_from_public_key(&pubkey, name, &dhash); + qe = GNUNET_NAMECACHE_lookup_block(ns, &dhash, &handle_block, NULL); } @@ -204,41 +204,41 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_string ('n', - "name", - "NAME", - gettext_noop ( - "name of the record to add/delete/display"), - &name), - - GNUNET_GETOPT_option_string ( - 'z', - "zone", - "PKEY", - gettext_noop ("specifies the public key of the zone to look in"), - &pkey), - - GNUNET_GETOPT_OPTION_END}; - - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + { GNUNET_GETOPT_option_string('n', + "name", + "NAME", + gettext_noop( + "name of the record to add/delete/display"), + &name), + + GNUNET_GETOPT_option_string( + 'z', + "zone", + "PKEY", + gettext_noop("specifies the public key of the zone to look in"), + &pkey), + + GNUNET_GETOPT_OPTION_END }; + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; - GNUNET_log_setup ("gnunet-namecache", "WARNING", NULL); - if (GNUNET_OK != GNUNET_PROGRAM_run (argc, - argv, - "gnunet-namecache", - _ ("GNUnet zone manipulation tool"), - options, - &run, - NULL)) - { - GNUNET_free ((void *) argv); - return 1; - } - GNUNET_free ((void *) argv); + GNUNET_log_setup("gnunet-namecache", "WARNING", NULL); + if (GNUNET_OK != GNUNET_PROGRAM_run(argc, + argv, + "gnunet-namecache", + _("GNUnet zone manipulation tool"), + options, + &run, + NULL)) + { + GNUNET_free((void *)argv); + return 1; + } + GNUNET_free((void *)argv); return ret; } diff --git a/src/namecache/gnunet-service-namecache.c b/src/namecache/gnunet-service-namecache.c index 00d9d81b5..e9f45a4fc 100644 --- a/src/namecache/gnunet-service-namecache.c +++ b/src/namecache/gnunet-service-namecache.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namecache/gnunet-service-namecache.c @@ -33,15 +33,13 @@ #include "gnunet_signatures.h" #include "namecache.h" -#define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename) +#define LOG_STRERROR_FILE(kind, syscall, filename) GNUNET_log_from_strerror_file(kind, "util", syscall, filename) /** * A namecache client */ -struct NamecacheClient -{ - +struct NamecacheClient { /** * The client */ @@ -51,7 +49,6 @@ struct NamecacheClient * The message queue to talk to @e client. */ struct GNUNET_MQ_Handle *mq; - }; @@ -82,21 +79,21 @@ static char *db_lib_name; * @param cls unused */ static void -cleanup_task (void *cls) +cleanup_task(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Stopping namecache service\n"); - GNUNET_break (NULL == - GNUNET_PLUGIN_unload (db_lib_name, - GSN_database)); - GNUNET_free (db_lib_name); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Stopping namecache service\n"); + GNUNET_break(NULL == + GNUNET_PLUGIN_unload(db_lib_name, + GSN_database)); + GNUNET_free(db_lib_name); db_lib_name = NULL; if (NULL != statistics) - { - GNUNET_STATISTICS_destroy (statistics, - GNUNET_NO); - statistics = NULL; - } + { + GNUNET_STATISTICS_destroy(statistics, + GNUNET_NO); + statistics = NULL; + } } @@ -109,16 +106,16 @@ cleanup_task (void *cls) * @param app_ctx the `struct NamecacheClient` for this @a client */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { struct NamecacheClient *nc = app_ctx; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Client %p disconnected\n", - client); - GNUNET_free (nc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Client %p disconnected\n", + client); + GNUNET_free(nc); } @@ -131,16 +128,16 @@ client_disconnect_cb (void *cls, * @return internal namecache client structure for this client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { struct NamecacheClient *nc; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Client %p connected\n", - client); - nc = GNUNET_new (struct NamecacheClient); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Client %p connected\n", + client); + nc = GNUNET_new(struct NamecacheClient); nc->client = client; nc->mq = mq; return nc; @@ -151,8 +148,7 @@ client_connect_cb (void *cls, * Context for name lookups passed from #handle_lookup_block to * #handle_lookup_block_it as closure */ -struct LookupBlockContext -{ +struct LookupBlockContext { /** * The client to send the response to */ @@ -162,7 +158,7 @@ struct LookupBlockContext * Operation id for the name lookup */ uint32_t request_id; - + /** * Lookup status */ @@ -177,8 +173,8 @@ struct LookupBlockContext * @param block the block */ static void -handle_lookup_block_it (void *cls, - const struct GNUNET_GNSRECORD_Block *block) +handle_lookup_block_it(void *cls, + const struct GNUNET_GNSRECORD_Block *block) { struct LookupBlockContext *lnc = cls; struct GNUNET_MQ_Envelope *env; @@ -186,37 +182,37 @@ handle_lookup_block_it (void *cls, size_t esize; size_t bsize; - bsize = ntohl (block->purpose.size); - if (bsize < - (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) + sizeof (struct GNUNET_TIME_AbsoluteNBO))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Malformed block."); - lnc->status = GNUNET_SYSERR; - return; - } - esize = ntohl (block->purpose.size) - - sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) - - sizeof (struct GNUNET_TIME_AbsoluteNBO); - env = GNUNET_MQ_msg_extra (r, - esize, - GNUNET_MESSAGE_TYPE_NAMECACHE_LOOKUP_BLOCK_RESPONSE); - r->gns_header.r_id = htonl (lnc->request_id); + bsize = ntohl(block->purpose.size); + if (bsize < + (sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose) + sizeof(struct GNUNET_TIME_AbsoluteNBO))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Malformed block."); + lnc->status = GNUNET_SYSERR; + return; + } + esize = ntohl(block->purpose.size) + - sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose) + - sizeof(struct GNUNET_TIME_AbsoluteNBO); + env = GNUNET_MQ_msg_extra(r, + esize, + GNUNET_MESSAGE_TYPE_NAMECACHE_LOOKUP_BLOCK_RESPONSE); + r->gns_header.r_id = htonl(lnc->request_id); r->expire = block->expiration_time; r->signature = block->signature; r->derived_key = block->derived_key; - GNUNET_memcpy (&r[1], - &block[1], - esize); - GNUNET_STATISTICS_update (statistics, - "blocks found in cache", - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending NAMECACHE_LOOKUP_BLOCK_RESPONSE message with expiration time %s\n", - GNUNET_STRINGS_absolute_time_to_string (GNUNET_TIME_absolute_ntoh (r->expire))); - GNUNET_MQ_send (lnc->nc->mq, - env); + GNUNET_memcpy(&r[1], + &block[1], + esize); + GNUNET_STATISTICS_update(statistics, + "blocks found in cache", + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending NAMECACHE_LOOKUP_BLOCK_RESPONSE message with expiration time %s\n", + GNUNET_STRINGS_absolute_time_to_string(GNUNET_TIME_absolute_ntoh(r->expire))); + GNUNET_MQ_send(lnc->nc->mq, + env); } @@ -227,8 +223,8 @@ handle_lookup_block_it (void *cls, * @param the inbound message */ static void -handle_lookup_block (void *cls, - const struct LookupBlockMessage *ln_msg) +handle_lookup_block(void *cls, + const struct LookupBlockMessage *ln_msg) { struct NamecacheClient *nc = cls; struct GNUNET_MQ_Envelope *env; @@ -236,40 +232,40 @@ handle_lookup_block (void *cls, struct LookupBlockResponseMessage *zir_end; int ret; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received NAMECACHE_LOOKUP_BLOCK message\n"); - GNUNET_STATISTICS_update (statistics, - "blocks looked up", - 1, - GNUNET_NO); - lnc.request_id = ntohl (ln_msg->gns_header.r_id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received NAMECACHE_LOOKUP_BLOCK message\n"); + GNUNET_STATISTICS_update(statistics, + "blocks looked up", + 1, + GNUNET_NO); + lnc.request_id = ntohl(ln_msg->gns_header.r_id); lnc.nc = nc; lnc.status = GNUNET_OK; if (GNUNET_SYSERR == - (ret = GSN_database->lookup_block (GSN_database->cls, - &ln_msg->query, - &handle_lookup_block_it, - &lnc))) - { - /* internal error (in database plugin); might be best to just hang up on - plugin rather than to signal that there are 'no' results, which - might also be false... */ - GNUNET_break (0); - GNUNET_SERVICE_client_drop (nc->client); - return; - } + (ret = GSN_database->lookup_block(GSN_database->cls, + &ln_msg->query, + &handle_lookup_block_it, + &lnc))) + { + /* internal error (in database plugin); might be best to just hang up on + plugin rather than to signal that there are 'no' results, which + might also be false... */ + GNUNET_break(0); + GNUNET_SERVICE_client_drop(nc->client); + return; + } if ((0 == ret) || (GNUNET_SYSERR == lnc.status)) - { - /* no records match at all, generate empty response */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending empty NAMECACHE_LOOKUP_BLOCK_RESPONSE message\n"); - env = GNUNET_MQ_msg (zir_end, - GNUNET_MESSAGE_TYPE_NAMECACHE_LOOKUP_BLOCK_RESPONSE); - zir_end->gns_header.r_id = ln_msg->gns_header.r_id; - GNUNET_MQ_send (nc->mq, - env); - } - GNUNET_SERVICE_client_continue (nc->client); + { + /* no records match at all, generate empty response */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending empty NAMECACHE_LOOKUP_BLOCK_RESPONSE message\n"); + env = GNUNET_MQ_msg(zir_end, + GNUNET_MESSAGE_TYPE_NAMECACHE_LOOKUP_BLOCK_RESPONSE); + zir_end->gns_header.r_id = ln_msg->gns_header.r_id; + GNUNET_MQ_send(nc->mq, + env); + } + GNUNET_SERVICE_client_continue(nc->client); } @@ -281,8 +277,8 @@ handle_lookup_block (void *cls, * @return #GNUNET_OK (always fine) */ static int -check_block_cache (void *cls, - const struct BlockCacheMessage *rp_msg) +check_block_cache(void *cls, + const struct BlockCacheMessage *rp_msg) { return GNUNET_OK; } @@ -295,8 +291,8 @@ check_block_cache (void *cls, * @param rp_msg message to process */ static void -handle_block_cache (void *cls, - const struct BlockCacheMessage *rp_msg) +handle_block_cache(void *cls, + const struct BlockCacheMessage *rp_msg) { struct NamecacheClient *nc = cls; struct GNUNET_MQ_Envelope *env; @@ -305,34 +301,34 @@ handle_block_cache (void *cls, size_t esize; int res; - GNUNET_STATISTICS_update (statistics, - "blocks cached", - 1, - GNUNET_NO); - esize = ntohs (rp_msg->gns_header.header.size) - sizeof (struct BlockCacheMessage); - block = GNUNET_malloc (sizeof (struct GNUNET_GNSRECORD_Block) + esize); + GNUNET_STATISTICS_update(statistics, + "blocks cached", + 1, + GNUNET_NO); + esize = ntohs(rp_msg->gns_header.header.size) - sizeof(struct BlockCacheMessage); + block = GNUNET_malloc(sizeof(struct GNUNET_GNSRECORD_Block) + esize); block->signature = rp_msg->signature; block->derived_key = rp_msg->derived_key; - block->purpose.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) + - sizeof (struct GNUNET_TIME_AbsoluteNBO) + - esize); + block->purpose.size = htonl(sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose) + + sizeof(struct GNUNET_TIME_AbsoluteNBO) + + esize); block->expiration_time = rp_msg->expire; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received NAMECACHE_BLOCK_CACHE message with expiration time %s\n", - GNUNET_STRINGS_absolute_time_to_string (GNUNET_TIME_absolute_ntoh (block->expiration_time))); - GNUNET_memcpy (&block[1], - &rp_msg[1], - esize); - res = GSN_database->cache_block (GSN_database->cls, - block); - GNUNET_free (block); - env = GNUNET_MQ_msg (rpr_msg, - GNUNET_MESSAGE_TYPE_NAMECACHE_BLOCK_CACHE_RESPONSE); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received NAMECACHE_BLOCK_CACHE message with expiration time %s\n", + GNUNET_STRINGS_absolute_time_to_string(GNUNET_TIME_absolute_ntoh(block->expiration_time))); + GNUNET_memcpy(&block[1], + &rp_msg[1], + esize); + res = GSN_database->cache_block(GSN_database->cls, + block); + GNUNET_free(block); + env = GNUNET_MQ_msg(rpr_msg, + GNUNET_MESSAGE_TYPE_NAMECACHE_BLOCK_CACHE_RESPONSE); rpr_msg->gns_header.r_id = rp_msg->gns_header.r_id; - rpr_msg->op_result = htonl (res); - GNUNET_MQ_send (nc->mq, - env); - GNUNET_SERVICE_client_continue (nc->client); + rpr_msg->op_result = htonl(res); + GNUNET_MQ_send(nc->mq, + env); + GNUNET_SERVICE_client_continue(nc->client); } @@ -344,46 +340,46 @@ handle_block_cache (void *cls, * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_SERVICE_Handle *service) { char *database; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting namecache service\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting namecache service\n"); GSN_cfg = cfg; /* Loading database plugin */ if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "namecache", - "database", - &database)) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "No database backend configured\n"); - - GNUNET_asprintf (&db_lib_name, - "libgnunet_plugin_namecache_%s", - database); - GSN_database = GNUNET_PLUGIN_load (db_lib_name, - (void *) GSN_cfg); - GNUNET_free (database); + GNUNET_CONFIGURATION_get_value_string(cfg, + "namecache", + "database", + &database)) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "No database backend configured\n"); + + GNUNET_asprintf(&db_lib_name, + "libgnunet_plugin_namecache_%s", + database); + GSN_database = GNUNET_PLUGIN_load(db_lib_name, + (void *)GSN_cfg); + GNUNET_free(database); if (NULL == GSN_database) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not load database backend `%s'\n", - db_lib_name); - GNUNET_SCHEDULER_add_now (&cleanup_task, - NULL); - return; - } - statistics = GNUNET_STATISTICS_create ("namecache", - cfg); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not load database backend `%s'\n", + db_lib_name); + GNUNET_SCHEDULER_add_now(&cleanup_task, + NULL); + return; + } + statistics = GNUNET_STATISTICS_create("namecache", + cfg); /* Configuring server handles */ - GNUNET_SCHEDULER_add_shutdown (&cleanup_task, - NULL); + GNUNET_SCHEDULER_add_shutdown(&cleanup_task, + NULL); } @@ -391,21 +387,21 @@ run (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("namecache", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_fixed_size (lookup_block, - GNUNET_MESSAGE_TYPE_NAMECACHE_LOOKUP_BLOCK, - struct LookupBlockMessage, - NULL), - GNUNET_MQ_hd_var_size (block_cache, - GNUNET_MESSAGE_TYPE_NAMECACHE_BLOCK_CACHE, - struct BlockCacheMessage, - NULL), - GNUNET_MQ_handler_end ()); + ("namecache", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_fixed_size(lookup_block, + GNUNET_MESSAGE_TYPE_NAMECACHE_LOOKUP_BLOCK, + struct LookupBlockMessage, + NULL), + GNUNET_MQ_hd_var_size(block_cache, + GNUNET_MESSAGE_TYPE_NAMECACHE_BLOCK_CACHE, + struct BlockCacheMessage, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-namecache.c */ diff --git a/src/namecache/namecache.h b/src/namecache/namecache.h index 1c9fe6b95..fa7c75c11 100644 --- a/src/namecache/namecache.h +++ b/src/namecache/namecache.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namecache/namecache.h @@ -37,8 +37,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Generic namecache message with op id */ -struct GNUNET_NAMECACHE_Header -{ +struct GNUNET_NAMECACHE_Header { /** * header.type will be GNUNET_MESSAGE_TYPE_NAMECACHE_* * header.size will be message size @@ -55,8 +54,7 @@ struct GNUNET_NAMECACHE_Header /** * Lookup a block in the namecache */ -struct LookupBlockMessage -{ +struct LookupBlockMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMECACHE_LOOKUP_BLOCK */ @@ -66,15 +64,13 @@ struct LookupBlockMessage * The query. */ struct GNUNET_HashCode query GNUNET_PACKED; - }; /** * Lookup response */ -struct LookupBlockResponseMessage -{ +struct LookupBlockResponseMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMECACHE_LOOKUP_BLOCK_RESPONSE */ @@ -102,8 +98,7 @@ struct LookupBlockResponseMessage /** * Cache a record in the namecache. */ -struct BlockCacheMessage -{ +struct BlockCacheMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMECACHE_BLOCK_CACHE */ @@ -131,8 +126,7 @@ struct BlockCacheMessage /** * Response to a request to cache a block. */ -struct BlockCacheResponseMessage -{ +struct BlockCacheResponseMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMECACHE_BLOCK_CACHE_RESPONSE */ diff --git a/src/namecache/namecache_api.c b/src/namecache/namecache_api.c index b91c1ac8f..9cf9eca77 100644 --- a/src/namecache/namecache_api.c +++ b/src/namecache/namecache_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namecache/namecache_api.c @@ -37,16 +37,14 @@ #include "namecache.h" -#define LOG(kind,...) GNUNET_log_from (kind, "namecache-api",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "namecache-api", __VA_ARGS__) /** * An QueueEntry used to store information for a pending * NAMECACHE record operation */ -struct GNUNET_NAMECACHE_QueueEntry -{ - +struct GNUNET_NAMECACHE_QueueEntry { /** * Kept in a DLL. */ @@ -86,16 +84,13 @@ struct GNUNET_NAMECACHE_QueueEntry * The operation id this zone iteration operation has */ uint32_t op_id; - }; /** * Connection to the NAMECACHE service. */ -struct GNUNET_NAMECACHE_Handle -{ - +struct GNUNET_NAMECACHE_Handle { /** * Configuration to use. */ @@ -140,7 +135,6 @@ struct GNUNET_NAMECACHE_Handle * The last operation id used for a NAMECACHE operation */ uint32_t last_op_id_used; - }; @@ -150,7 +144,7 @@ struct GNUNET_NAMECACHE_Handle * @param h our handle */ static void -force_reconnect (struct GNUNET_NAMECACHE_Handle *h); +force_reconnect(struct GNUNET_NAMECACHE_Handle *h); /** @@ -161,21 +155,21 @@ force_reconnect (struct GNUNET_NAMECACHE_Handle *h); * @return NULL if not found, otherwise the queue entry (removed from the queue) */ static struct GNUNET_NAMECACHE_QueueEntry * -find_qe (struct GNUNET_NAMECACHE_Handle *h, - uint32_t rid) +find_qe(struct GNUNET_NAMECACHE_Handle *h, + uint32_t rid) { struct GNUNET_NAMECACHE_QueueEntry *qe; for (qe = h->op_head; qe != NULL; qe = qe->next) - { - if (qe->op_id == rid) { - GNUNET_CONTAINER_DLL_remove (h->op_head, - h->op_tail, - qe); - return qe; + if (qe->op_id == rid) + { + GNUNET_CONTAINER_DLL_remove(h->op_head, + h->op_tail, + qe); + return qe; + } } - } return NULL; } @@ -188,8 +182,8 @@ find_qe (struct GNUNET_NAMECACHE_Handle *h, * @param msg the message we received */ static int -check_lookup_block_response (void *cls, - const struct LookupBlockResponseMessage *msg) +check_lookup_block_response(void *cls, + const struct LookupBlockResponseMessage *msg) { /* any length will do, format validation is in handler */ return GNUNET_OK; @@ -204,62 +198,62 @@ check_lookup_block_response (void *cls, * @param msg the message we received */ static void -handle_lookup_block_response (void *cls, - const struct LookupBlockResponseMessage *msg) +handle_lookup_block_response(void *cls, + const struct LookupBlockResponseMessage *msg) { struct GNUNET_NAMECACHE_Handle *h = cls; size_t size; struct GNUNET_NAMECACHE_QueueEntry *qe; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received LOOKUP_BLOCK_RESPONSE\n"); - qe = find_qe (h, - ntohl (msg->gns_header.r_id)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received LOOKUP_BLOCK_RESPONSE\n"); + qe = find_qe(h, + ntohl(msg->gns_header.r_id)); if (NULL == qe) return; - if (0 == GNUNET_TIME_absolute_ntoh (msg->expire).abs_value_us) - { - /* no match found */ - if (NULL != qe->block_proc) - qe->block_proc (qe->block_proc_cls, - NULL); - GNUNET_free (qe); - return; - } - size = ntohs (msg->gns_header.header.size) - - sizeof (struct LookupBlockResponseMessage); + if (0 == GNUNET_TIME_absolute_ntoh(msg->expire).abs_value_us) + { + /* no match found */ + if (NULL != qe->block_proc) + qe->block_proc(qe->block_proc_cls, + NULL); + GNUNET_free(qe); + return; + } + size = ntohs(msg->gns_header.header.size) + - sizeof(struct LookupBlockResponseMessage); { - char buf[size + sizeof (struct GNUNET_GNSRECORD_Block)] GNUNET_ALIGN; + char buf[size + sizeof(struct GNUNET_GNSRECORD_Block)] GNUNET_ALIGN; struct GNUNET_GNSRECORD_Block *block; - block = (struct GNUNET_GNSRECORD_Block *) buf; + block = (struct GNUNET_GNSRECORD_Block *)buf; block->signature = msg->signature; block->derived_key = msg->derived_key; - block->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN); - block->purpose.size = htonl (size + - sizeof (struct GNUNET_TIME_AbsoluteNBO) + - sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose)); + block->purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_GNS_RECORD_SIGN); + block->purpose.size = htonl(size + + sizeof(struct GNUNET_TIME_AbsoluteNBO) + + sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose)); block->expiration_time = msg->expire; - GNUNET_memcpy (&block[1], - &msg[1], - size); + GNUNET_memcpy(&block[1], + &msg[1], + size); if (GNUNET_OK != - GNUNET_GNSRECORD_block_verify (block)) - { - GNUNET_break (0); - if (NULL != qe->block_proc) - qe->block_proc (qe->block_proc_cls, - NULL); - force_reconnect (h); - } + GNUNET_GNSRECORD_block_verify(block)) + { + GNUNET_break(0); + if (NULL != qe->block_proc) + qe->block_proc(qe->block_proc_cls, + NULL); + force_reconnect(h); + } else - { - if (NULL != qe->block_proc) - qe->block_proc (qe->block_proc_cls, - block); - } + { + if (NULL != qe->block_proc) + qe->block_proc(qe->block_proc_cls, + block); + } } - GNUNET_free (qe); + GNUNET_free(qe); } @@ -273,28 +267,28 @@ handle_lookup_block_response (void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and we did NOT notify the client */ static void -handle_block_cache_response (void *cls, - const struct BlockCacheResponseMessage *msg) +handle_block_cache_response(void *cls, + const struct BlockCacheResponseMessage *msg) { struct GNUNET_NAMECACHE_Handle *h = cls; struct GNUNET_NAMECACHE_QueueEntry *qe; int res; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received BLOCK_CACHE_RESPONSE\n"); - qe = find_qe (h, - ntohl (msg->gns_header.r_id)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received BLOCK_CACHE_RESPONSE\n"); + qe = find_qe(h, + ntohl(msg->gns_header.r_id)); if (NULL == qe) return; - res = ntohl (msg->op_result); + res = ntohl(msg->op_result); /* TODO: add actual error message from namecache to response... */ if (NULL != qe->cont) - qe->cont (qe->cont_cls, - res, - (GNUNET_OK == res) - ? NULL - : _("Namecache failed to cache block")); - GNUNET_free (qe); + qe->cont(qe->cont_cls, + res, + (GNUNET_OK == res) + ? NULL + : _("Namecache failed to cache block")); + GNUNET_free(qe); } @@ -307,12 +301,12 @@ handle_block_cache_response (void *cls, * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_NAMECACHE_Handle *h = cls; - force_reconnect (h); + force_reconnect(h); } @@ -322,25 +316,26 @@ mq_error_handler (void *cls, * @param h the handle to the NAMECACHE service */ static void -reconnect (struct GNUNET_NAMECACHE_Handle *h) +reconnect(struct GNUNET_NAMECACHE_Handle *h) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (lookup_block_response, - GNUNET_MESSAGE_TYPE_NAMECACHE_LOOKUP_BLOCK_RESPONSE, - struct LookupBlockResponseMessage, - h), - GNUNET_MQ_hd_fixed_size (block_cache_response, - GNUNET_MESSAGE_TYPE_NAMECACHE_BLOCK_CACHE_RESPONSE, - struct BlockCacheResponseMessage, - h), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(lookup_block_response, + GNUNET_MESSAGE_TYPE_NAMECACHE_LOOKUP_BLOCK_RESPONSE, + struct LookupBlockResponseMessage, + h), + GNUNET_MQ_hd_fixed_size(block_cache_response, + GNUNET_MESSAGE_TYPE_NAMECACHE_BLOCK_CACHE_RESPONSE, + struct BlockCacheResponseMessage, + h), + GNUNET_MQ_handler_end() }; - GNUNET_assert (NULL == h->mq); - h->mq = GNUNET_CLIENT_connect (h->cfg, - "namecache", - handlers, - &mq_error_handler, - h); + + GNUNET_assert(NULL == h->mq); + h->mq = GNUNET_CLIENT_connect(h->cfg, + "namecache", + handlers, + &mq_error_handler, + h); } @@ -350,12 +345,12 @@ reconnect (struct GNUNET_NAMECACHE_Handle *h) * @param cls handle to use to re-connect. */ static void -reconnect_task (void *cls) +reconnect_task(void *cls) { struct GNUNET_NAMECACHE_Handle *h = cls; h->reconnect_task = NULL; - reconnect (h); + reconnect(h); } @@ -365,30 +360,30 @@ reconnect_task (void *cls) * @param h our handle */ static void -force_reconnect (struct GNUNET_NAMECACHE_Handle *h) +force_reconnect(struct GNUNET_NAMECACHE_Handle *h) { struct GNUNET_NAMECACHE_QueueEntry *qe; h->reconnect = GNUNET_NO; - GNUNET_MQ_destroy (h->mq); + GNUNET_MQ_destroy(h->mq); h->mq = NULL; while (NULL != (qe = h->op_head)) - { - GNUNET_CONTAINER_DLL_remove (h->op_head, - h->op_tail, - qe); - if (NULL != qe->cont) - qe->cont (qe->cont_cls, - GNUNET_SYSERR, - _("Error communicating with namecache service")); - GNUNET_free (qe); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Reconnecting to namecache\n"); - h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay); - h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, - &reconnect_task, - h); + { + GNUNET_CONTAINER_DLL_remove(h->op_head, + h->op_tail, + qe); + if (NULL != qe->cont) + qe->cont(qe->cont_cls, + GNUNET_SYSERR, + _("Error communicating with namecache service")); + GNUNET_free(qe); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Reconnecting to namecache\n"); + h->reconnect_delay = GNUNET_TIME_STD_BACKOFF(h->reconnect_delay); + h->reconnect_task = GNUNET_SCHEDULER_add_delayed(h->reconnect_delay, + &reconnect_task, + h); } @@ -399,7 +394,7 @@ force_reconnect (struct GNUNET_NAMECACHE_Handle *h) * @return next operation id to use */ static uint32_t -get_op_id (struct GNUNET_NAMECACHE_Handle *h) +get_op_id(struct GNUNET_NAMECACHE_Handle *h) { return h->last_op_id_used++; } @@ -412,18 +407,18 @@ get_op_id (struct GNUNET_NAMECACHE_Handle *h) * @return handle to the GNS service, or NULL on error */ struct GNUNET_NAMECACHE_Handle * -GNUNET_NAMECACHE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_NAMECACHE_connect(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_NAMECACHE_Handle *h; - h = GNUNET_new (struct GNUNET_NAMECACHE_Handle); + h = GNUNET_new(struct GNUNET_NAMECACHE_Handle); h->cfg = cfg; - reconnect (h); + reconnect(h); if (NULL == h->mq) - { - GNUNET_free (h); - return NULL; - } + { + GNUNET_free(h); + return NULL; + } return h; } @@ -435,29 +430,29 @@ GNUNET_NAMECACHE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) * @param h handle to the namecache */ void -GNUNET_NAMECACHE_disconnect (struct GNUNET_NAMECACHE_Handle *h) +GNUNET_NAMECACHE_disconnect(struct GNUNET_NAMECACHE_Handle *h) { struct GNUNET_NAMECACHE_QueueEntry *q; - GNUNET_break (NULL == h->op_head); + GNUNET_break(NULL == h->op_head); while (NULL != (q = h->op_head)) - { - GNUNET_CONTAINER_DLL_remove (h->op_head, - h->op_tail, - q); - GNUNET_free (q); - } + { + GNUNET_CONTAINER_DLL_remove(h->op_head, + h->op_tail, + q); + GNUNET_free(q); + } if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } if (NULL != h->reconnect_task) - { - GNUNET_SCHEDULER_cancel (h->reconnect_task); - h->reconnect_task = NULL; - } - GNUNET_free (h); + { + GNUNET_SCHEDULER_cancel(h->reconnect_task); + h->reconnect_task = NULL; + } + GNUNET_free(h); } @@ -472,10 +467,10 @@ GNUNET_NAMECACHE_disconnect (struct GNUNET_NAMECACHE_Handle *h) * @return handle to abort the request, NULL on error */ struct GNUNET_NAMECACHE_QueueEntry * -GNUNET_NAMECACHE_block_cache (struct GNUNET_NAMECACHE_Handle *h, - const struct GNUNET_GNSRECORD_Block *block, - GNUNET_NAMECACHE_ContinuationWithStatus cont, - void *cont_cls) +GNUNET_NAMECACHE_block_cache(struct GNUNET_NAMECACHE_Handle *h, + const struct GNUNET_GNSRECORD_Block *block, + GNUNET_NAMECACHE_ContinuationWithStatus cont, + void *cont_cls) { struct GNUNET_NAMECACHE_QueueEntry *qe; struct BlockCacheMessage *msg; @@ -485,33 +480,33 @@ GNUNET_NAMECACHE_block_cache (struct GNUNET_NAMECACHE_Handle *h, if (NULL == h->mq) return NULL; - blen = ntohl (block->purpose.size); - GNUNET_assert (blen > (sizeof (struct GNUNET_TIME_AbsoluteNBO) + - sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose))); - blen -= (sizeof (struct GNUNET_TIME_AbsoluteNBO) + - sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose)); - rid = get_op_id (h); - qe = GNUNET_new (struct GNUNET_NAMECACHE_QueueEntry); + blen = ntohl(block->purpose.size); + GNUNET_assert(blen > (sizeof(struct GNUNET_TIME_AbsoluteNBO) + + sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose))); + blen -= (sizeof(struct GNUNET_TIME_AbsoluteNBO) + + sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose)); + rid = get_op_id(h); + qe = GNUNET_new(struct GNUNET_NAMECACHE_QueueEntry); qe->nsh = h; qe->cont = cont; qe->cont_cls = cont_cls; qe->op_id = rid; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, - h->op_tail, - qe); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, + h->op_tail, + qe); /* send msg */ - env = GNUNET_MQ_msg_extra (msg, - blen, - GNUNET_MESSAGE_TYPE_NAMECACHE_BLOCK_CACHE); - msg->gns_header.r_id = htonl (rid); + env = GNUNET_MQ_msg_extra(msg, + blen, + GNUNET_MESSAGE_TYPE_NAMECACHE_BLOCK_CACHE); + msg->gns_header.r_id = htonl(rid); msg->expire = block->expiration_time; msg->signature = block->signature; msg->derived_key = block->derived_key; - GNUNET_memcpy (&msg[1], - &block[1], - blen); - GNUNET_MQ_send (h->mq, - env); + GNUNET_memcpy(&msg[1], + &block[1], + blen); + GNUNET_MQ_send(h->mq, + env); return qe; } @@ -528,10 +523,10 @@ GNUNET_NAMECACHE_block_cache (struct GNUNET_NAMECACHE_Handle *h, * @return a handle that can be used to cancel, NULL on error */ struct GNUNET_NAMECACHE_QueueEntry * -GNUNET_NAMECACHE_lookup_block (struct GNUNET_NAMECACHE_Handle *h, - const struct GNUNET_HashCode *derived_hash, - GNUNET_NAMECACHE_BlockProcessor proc, - void *proc_cls) +GNUNET_NAMECACHE_lookup_block(struct GNUNET_NAMECACHE_Handle *h, + const struct GNUNET_HashCode *derived_hash, + GNUNET_NAMECACHE_BlockProcessor proc, + void *proc_cls) { struct GNUNET_NAMECACHE_QueueEntry *qe; struct LookupBlockMessage *msg; @@ -540,24 +535,24 @@ GNUNET_NAMECACHE_lookup_block (struct GNUNET_NAMECACHE_Handle *h, if (NULL == h->mq) return NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Looking for block under %s\n", - GNUNET_h2s (derived_hash)); - rid = get_op_id (h); - qe = GNUNET_new (struct GNUNET_NAMECACHE_QueueEntry); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Looking for block under %s\n", + GNUNET_h2s(derived_hash)); + rid = get_op_id(h); + qe = GNUNET_new(struct GNUNET_NAMECACHE_QueueEntry); qe->nsh = h; qe->block_proc = proc; qe->block_proc_cls = proc_cls; qe->op_id = rid; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, - h->op_tail, - qe); - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_NAMECACHE_LOOKUP_BLOCK); - msg->gns_header.r_id = htonl (rid); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, + h->op_tail, + qe); + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_NAMECACHE_LOOKUP_BLOCK); + msg->gns_header.r_id = htonl(rid); msg->query = *derived_hash; - GNUNET_MQ_send (h->mq, - env); + GNUNET_MQ_send(h->mq, + env); return qe; } @@ -569,13 +564,13 @@ GNUNET_NAMECACHE_lookup_block (struct GNUNET_NAMECACHE_Handle *h, * @param qe operation to cancel */ void -GNUNET_NAMECACHE_cancel (struct GNUNET_NAMECACHE_QueueEntry *qe) +GNUNET_NAMECACHE_cancel(struct GNUNET_NAMECACHE_QueueEntry *qe) { struct GNUNET_NAMECACHE_Handle *h = qe->nsh; - GNUNET_CONTAINER_DLL_remove (h->op_head, - h->op_tail, - qe); + GNUNET_CONTAINER_DLL_remove(h->op_head, + h->op_tail, + qe); GNUNET_free(qe); } diff --git a/src/namecache/plugin_namecache_flat.c b/src/namecache/plugin_namecache_flat.c index c093cb2a9..c48056a29 100644 --- a/src/namecache/plugin_namecache_flat.c +++ b/src/namecache/plugin_namecache_flat.c @@ -1,22 +1,22 @@ - /* - * This file is part of GNUnet - * Copyright (C) 2009-2015 GNUnet e.V. - * - * GNUnet is free software: you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * GNUnet is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - - SPDX-License-Identifier: AGPL3.0-or-later - */ +/* + * This file is part of GNUnet + * Copyright (C) 2009-2015 GNUnet e.V. + * + * GNUnet is free software: you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * GNUnet is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + + SPDX-License-Identifier: AGPL3.0-or-later + */ /** * @file namecache/plugin_namecache_flat.c @@ -33,9 +33,7 @@ /** * Context for all functions in this plugin. */ -struct Plugin -{ - +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; /** @@ -47,11 +45,9 @@ struct Plugin * HashMap */ struct GNUNET_CONTAINER_MultiHashMap *hm; - }; -struct FlatFileEntry -{ +struct FlatFileEntry { /** * Block */ @@ -61,7 +57,6 @@ struct FlatFileEntry * query */ struct GNUNET_HashCode query; - }; /** @@ -73,7 +68,7 @@ struct FlatFileEntry * @return #GNUNET_OK on success */ static int -database_setup (struct Plugin *plugin) +database_setup(struct Plugin *plugin) { char *afsdir; char* block_buffer; @@ -86,107 +81,108 @@ database_setup (struct Plugin *plugin) struct GNUNET_DISK_FileHandle *fh; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, - "namecache-flat", - "FILENAME", - &afsdir)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "namecache-flat", "FILENAME"); - return GNUNET_SYSERR; - } - if (GNUNET_OK != GNUNET_DISK_file_test (afsdir)) - { - if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir)) + GNUNET_CONFIGURATION_get_value_filename(plugin->cfg, + "namecache-flat", + "FILENAME", + &afsdir)) { - GNUNET_break (0); - GNUNET_free (afsdir); + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "namecache-flat", "FILENAME"); return GNUNET_SYSERR; } - } + if (GNUNET_OK != GNUNET_DISK_file_test(afsdir)) + { + if (GNUNET_OK != GNUNET_DISK_directory_create_for_file(afsdir)) + { + GNUNET_break(0); + GNUNET_free(afsdir); + return GNUNET_SYSERR; + } + } /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */ plugin->fn = afsdir; /* Load data from file into hashmap */ - plugin->hm = GNUNET_CONTAINER_multihashmap_create (10, - GNUNET_NO); - fh = GNUNET_DISK_file_open (afsdir, - GNUNET_DISK_OPEN_CREATE | - GNUNET_DISK_OPEN_READWRITE, - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_USER_READ); + plugin->hm = GNUNET_CONTAINER_multihashmap_create(10, + GNUNET_NO); + fh = GNUNET_DISK_file_open(afsdir, + GNUNET_DISK_OPEN_CREATE | + GNUNET_DISK_OPEN_READWRITE, + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_USER_READ); if (NULL == fh) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to initialize file: %s.\n"), - afsdir); - return GNUNET_SYSERR; - } - - if (GNUNET_SYSERR == GNUNET_DISK_file_size (afsdir, - &size, - GNUNET_YES, - GNUNET_YES)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to get filesize: %s.\n"), - afsdir); - GNUNET_DISK_file_close (fh); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to initialize file: %s.\n"), + afsdir); + return GNUNET_SYSERR; + } + + if (GNUNET_SYSERR == GNUNET_DISK_file_size(afsdir, + &size, + GNUNET_YES, + GNUNET_YES)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to get filesize: %s.\n"), + afsdir); + GNUNET_DISK_file_close(fh); + return GNUNET_SYSERR; + } if (0 == size) - { - GNUNET_DISK_file_close (fh); - return GNUNET_OK; - } - - buffer = GNUNET_malloc (size + 1); - - if (GNUNET_SYSERR == GNUNET_DISK_file_read (fh, - buffer, - size)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to read file: %s.\n"), - afsdir); - GNUNET_free (buffer); - GNUNET_DISK_file_close (fh); - return GNUNET_SYSERR; - } + { + GNUNET_DISK_file_close(fh); + return GNUNET_OK; + } + + buffer = GNUNET_malloc(size + 1); + + if (GNUNET_SYSERR == GNUNET_DISK_file_read(fh, + buffer, + size)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to read file: %s.\n"), + afsdir); + GNUNET_free(buffer); + GNUNET_DISK_file_close(fh); + return GNUNET_SYSERR; + } buffer[size] = '\0'; - GNUNET_DISK_file_close (fh); + GNUNET_DISK_file_close(fh); if (0 < size) - { - line = strtok (buffer, "\n"); - while (line != NULL) { - query = strtok (line, ","); - if (NULL == query) - break; - block = strtok (NULL, ","); - if (NULL == block) - break; - line = strtok (NULL, "\n"); - entry = GNUNET_malloc (sizeof (struct FlatFileEntry)); - GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_hash_from_string (query, - &entry->query)); - GNUNET_STRINGS_base64_decode (block, - strlen (block), - (void**)&block_buffer); - entry->block = (struct GNUNET_GNSRECORD_Block *) block_buffer; - if (GNUNET_OK != - GNUNET_CONTAINER_multihashmap_put (plugin->hm, - &entry->query, - entry, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - GNUNET_free (entry); - GNUNET_break (0); - } + { + line = strtok(buffer, "\n"); + while (line != NULL) + { + query = strtok(line, ","); + if (NULL == query) + break; + block = strtok(NULL, ","); + if (NULL == block) + break; + line = strtok(NULL, "\n"); + entry = GNUNET_malloc(sizeof(struct FlatFileEntry)); + GNUNET_assert(GNUNET_OK == GNUNET_CRYPTO_hash_from_string(query, + &entry->query)); + GNUNET_STRINGS_base64_decode(block, + strlen(block), + (void**)&block_buffer); + entry->block = (struct GNUNET_GNSRECORD_Block *)block_buffer; + if (GNUNET_OK != + GNUNET_CONTAINER_multihashmap_put(plugin->hm, + &entry->query, + entry, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_free(entry); + GNUNET_break(0); + } + } } - } - GNUNET_free (buffer); + GNUNET_free(buffer); return GNUNET_OK; } @@ -196,9 +192,9 @@ database_setup (struct Plugin *plugin) * @param plugin the plugin context */ static int -store_and_free_entries (void *cls, - const struct GNUNET_HashCode *key, - void *value) +store_and_free_entries(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GNUNET_DISK_FileHandle *fh = cls; struct FlatFileEntry *entry = value; @@ -208,29 +204,29 @@ store_and_free_entries (void *cls, struct GNUNET_CRYPTO_HashAsciiEncoded query; size_t block_size; - block_size = ntohl (entry->block->purpose.size) + - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) + - sizeof (struct GNUNET_CRYPTO_EcdsaSignature); - - GNUNET_STRINGS_base64_encode ((char*)entry->block, - block_size, - &block_b64); - GNUNET_CRYPTO_hash_to_enc (&entry->query, - &query); - GNUNET_asprintf (&line, - "%s,%s\n", - (char*)&query, - block_b64); - - GNUNET_free (block_b64); - - GNUNET_DISK_file_write (fh, - line, - strlen (line)); - - GNUNET_free (entry->block); - GNUNET_free (entry); - GNUNET_free (line); + block_size = ntohl(entry->block->purpose.size) + + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) + + sizeof(struct GNUNET_CRYPTO_EcdsaSignature); + + GNUNET_STRINGS_base64_encode((char*)entry->block, + block_size, + &block_b64); + GNUNET_CRYPTO_hash_to_enc(&entry->query, + &query); + GNUNET_asprintf(&line, + "%s,%s\n", + (char*)&query, + block_b64); + + GNUNET_free(block_b64); + + GNUNET_DISK_file_write(fh, + line, + strlen(line)); + + GNUNET_free(entry->block); + GNUNET_free(entry); + GNUNET_free(line); return GNUNET_YES; } @@ -240,49 +236,49 @@ store_and_free_entries (void *cls, * @param plugin the plugin context (state for this module) */ static void -database_shutdown (struct Plugin *plugin) +database_shutdown(struct Plugin *plugin) { struct GNUNET_DISK_FileHandle *fh; - fh = GNUNET_DISK_file_open (plugin->fn, - GNUNET_DISK_OPEN_CREATE | - GNUNET_DISK_OPEN_TRUNCATE | - GNUNET_DISK_OPEN_READWRITE, - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_USER_READ); + + fh = GNUNET_DISK_file_open(plugin->fn, + GNUNET_DISK_OPEN_CREATE | + GNUNET_DISK_OPEN_TRUNCATE | + GNUNET_DISK_OPEN_READWRITE, + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_USER_READ); if (NULL == fh) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to initialize file: %s.\n"), - plugin->fn); - return; - } - - GNUNET_CONTAINER_multihashmap_iterate (plugin->hm, - &store_and_free_entries, - fh); - GNUNET_CONTAINER_multihashmap_destroy (plugin->hm); - GNUNET_DISK_file_close (fh); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to initialize file: %s.\n"), + plugin->fn); + return; + } + GNUNET_CONTAINER_multihashmap_iterate(plugin->hm, + &store_and_free_entries, + fh); + GNUNET_CONTAINER_multihashmap_destroy(plugin->hm); + GNUNET_DISK_file_close(fh); } static int -expire_blocks (void *cls, - const struct GNUNET_HashCode *key, - void *value) +expire_blocks(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct Plugin *plugin = cls; struct FlatFileEntry *entry = value; struct GNUNET_TIME_Absolute now; struct GNUNET_TIME_Absolute expiration; - now = GNUNET_TIME_absolute_get (); - expiration = GNUNET_TIME_absolute_ntoh (entry->block->expiration_time); + now = GNUNET_TIME_absolute_get(); + expiration = GNUNET_TIME_absolute_ntoh(entry->block->expiration_time); - if (0 == GNUNET_TIME_absolute_get_difference (now, - expiration).rel_value_us) - { - GNUNET_CONTAINER_multihashmap_remove_all (plugin->hm, key); - } + if (0 == GNUNET_TIME_absolute_get_difference(now, + expiration).rel_value_us) + { + GNUNET_CONTAINER_multihashmap_remove_all(plugin->hm, key); + } return GNUNET_YES; } @@ -294,11 +290,11 @@ expire_blocks (void *cls, * @param plugin the plugin */ static void -namecache_expire_blocks (struct Plugin *plugin) +namecache_expire_blocks(struct Plugin *plugin) { - GNUNET_CONTAINER_multihashmap_iterate (plugin->hm, - &expire_blocks, - plugin); + GNUNET_CONTAINER_multihashmap_iterate(plugin->hm, + &expire_blocks, + plugin); } @@ -310,43 +306,43 @@ namecache_expire_blocks (struct Plugin *plugin) * @return #GNUNET_OK on success, else #GNUNET_SYSERR */ static int -namecache_cache_block (void *cls, - const struct GNUNET_GNSRECORD_Block *block) +namecache_cache_block(void *cls, + const struct GNUNET_GNSRECORD_Block *block) { struct Plugin *plugin = cls; struct GNUNET_HashCode query; struct FlatFileEntry *entry; size_t block_size; - namecache_expire_blocks (plugin); - GNUNET_CRYPTO_hash (&block->derived_key, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey), - &query); - block_size = ntohl (block->purpose.size) + - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) + - sizeof (struct GNUNET_CRYPTO_EcdsaSignature); + namecache_expire_blocks(plugin); + GNUNET_CRYPTO_hash(&block->derived_key, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey), + &query); + block_size = ntohl(block->purpose.size) + + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) + + sizeof(struct GNUNET_CRYPTO_EcdsaSignature); if (block_size > 64 * 65536) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - entry = GNUNET_malloc (sizeof (struct FlatFileEntry)); - entry->block = GNUNET_malloc (block_size); - GNUNET_memcpy (entry->block, block, block_size); - GNUNET_CONTAINER_multihashmap_remove_all (plugin->hm, &query); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + entry = GNUNET_malloc(sizeof(struct FlatFileEntry)); + entry->block = GNUNET_malloc(block_size); + GNUNET_memcpy(entry->block, block, block_size); + GNUNET_CONTAINER_multihashmap_remove_all(plugin->hm, &query); if (GNUNET_OK != - GNUNET_CONTAINER_multihashmap_put (plugin->hm, - &query, - entry, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - GNUNET_free (entry); - GNUNET_break (0); - return GNUNET_SYSERR; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Caching block under derived key `%s'\n", - GNUNET_h2s_full (&query)); + GNUNET_CONTAINER_multihashmap_put(plugin->hm, + &query, + entry, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_free(entry); + GNUNET_break(0); + return GNUNET_SYSERR; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Caching block under derived key `%s'\n", + GNUNET_h2s_full(&query)); return GNUNET_OK; } @@ -362,20 +358,20 @@ namecache_cache_block (void *cls, * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error */ static int -namecache_lookup_block (void *cls, - const struct GNUNET_HashCode *query, - GNUNET_NAMECACHE_BlockCallback iter, void *iter_cls) +namecache_lookup_block(void *cls, + const struct GNUNET_HashCode *query, + GNUNET_NAMECACHE_BlockCallback iter, void *iter_cls) { struct Plugin *plugin = cls; const struct GNUNET_GNSRECORD_Block *block; - block = GNUNET_CONTAINER_multihashmap_get (plugin->hm, query); + block = GNUNET_CONTAINER_multihashmap_get(plugin->hm, query); if (NULL == block) return GNUNET_NO; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found block under derived key `%s'\n", - GNUNET_h2s_full (query)); - iter (iter_cls, block); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found block under derived key `%s'\n", + GNUNET_h2s_full(query)); + iter(iter_cls, block); return GNUNET_YES; } @@ -387,7 +383,7 @@ namecache_lookup_block (void *cls, * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_namecache_flat_init (void *cls) +libgnunet_plugin_namecache_flat_init(void *cls) { static struct Plugin plugin; const struct GNUNET_CONFIGURATION_Handle *cfg = cls; @@ -395,19 +391,19 @@ libgnunet_plugin_namecache_flat_init (void *cls) if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.cfg = cfg; - if (GNUNET_OK != database_setup (&plugin)) - { - database_shutdown (&plugin); - return NULL; - } - api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions); + if (GNUNET_OK != database_setup(&plugin)) + { + database_shutdown(&plugin); + return NULL; + } + api = GNUNET_new(struct GNUNET_NAMECACHE_PluginFunctions); api->cls = &plugin; api->cache_block = &namecache_cache_block; api->lookup_block = &namecache_lookup_block; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("flat plugin running\n")); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("flat plugin running\n")); return api; } @@ -419,16 +415,16 @@ libgnunet_plugin_namecache_flat_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_namecache_flat_done (void *cls) +libgnunet_plugin_namecache_flat_done(void *cls) { struct GNUNET_NAMECACHE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - database_shutdown (plugin); + database_shutdown(plugin); plugin->cfg = NULL; - GNUNET_free (api); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "flat plugin is finished\n"); + GNUNET_free(api); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "flat plugin is finished\n"); return NULL; } diff --git a/src/namecache/plugin_namecache_postgres.c b/src/namecache/plugin_namecache_postgres.c index 1d6d9f392..6d0e4e918 100644 --- a/src/namecache/plugin_namecache_postgres.c +++ b/src/namecache/plugin_namecache_postgres.c @@ -1,22 +1,22 @@ - /* - * This file is part of GNUnet - * Copyright (C) 2009-2013, 2016, 2017 GNUnet e.V. - * - * GNUnet is free software: you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * GNUnet is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - - SPDX-License-Identifier: AGPL3.0-or-later - */ +/* + * This file is part of GNUnet + * Copyright (C) 2009-2013, 2016, 2017 GNUnet e.V. + * + * GNUnet is free software: you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * GNUnet is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + + SPDX-License-Identifier: AGPL3.0-or-later + */ /** * @file namecache/plugin_namecache_postgres.c @@ -31,22 +31,19 @@ #include "namecache.h" -#define LOG(kind,...) GNUNET_log_from (kind, "namecache-postgres", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "namecache-postgres", __VA_ARGS__) /** * Context for all functions in this plugin. */ -struct Plugin -{ - +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; /** * Native Postgres database handle. */ PGconn *dbh; - }; @@ -59,81 +56,81 @@ struct Plugin * @return #GNUNET_OK on success */ static int -database_setup (struct Plugin *plugin) +database_setup(struct Plugin *plugin) { struct GNUNET_PQ_ExecuteStatement es_temporary = - GNUNET_PQ_make_execute ("CREATE TEMPORARY TABLE IF NOT EXISTS ns096blocks (" - " query BYTEA NOT NULL DEFAULT ''," - " block BYTEA NOT NULL DEFAULT ''," - " expiration_time BIGINT NOT NULL DEFAULT 0" - ")" - "WITH OIDS"); + GNUNET_PQ_make_execute("CREATE TEMPORARY TABLE IF NOT EXISTS ns096blocks (" + " query BYTEA NOT NULL DEFAULT ''," + " block BYTEA NOT NULL DEFAULT ''," + " expiration_time BIGINT NOT NULL DEFAULT 0" + ")" + "WITH OIDS"); struct GNUNET_PQ_ExecuteStatement es_default = - GNUNET_PQ_make_execute ("CREATE TABLE IF NOT EXISTS ns096blocks (" - " query BYTEA NOT NULL DEFAULT ''," - " block BYTEA NOT NULL DEFAULT ''," - " expiration_time BIGINT NOT NULL DEFAULT 0" - ")" - "WITH OIDS"); + GNUNET_PQ_make_execute("CREATE TABLE IF NOT EXISTS ns096blocks (" + " query BYTEA NOT NULL DEFAULT ''," + " block BYTEA NOT NULL DEFAULT ''," + " expiration_time BIGINT NOT NULL DEFAULT 0" + ")" + "WITH OIDS"); const struct GNUNET_PQ_ExecuteStatement *cr; - plugin->dbh = GNUNET_PQ_connect_with_cfg (plugin->cfg, - "namecache-postgres"); + plugin->dbh = GNUNET_PQ_connect_with_cfg(plugin->cfg, + "namecache-postgres"); if (NULL == plugin->dbh) return GNUNET_SYSERR; if (GNUNET_YES == - GNUNET_CONFIGURATION_get_value_yesno (plugin->cfg, - "namecache-postgres", - "TEMPORARY_TABLE")) - { - cr = &es_temporary; - } + GNUNET_CONFIGURATION_get_value_yesno(plugin->cfg, + "namecache-postgres", + "TEMPORARY_TABLE")) + { + cr = &es_temporary; + } else - { - cr = &es_default; - } + { + cr = &es_default; + } { struct GNUNET_PQ_ExecuteStatement es[] = { *cr, - GNUNET_PQ_make_try_execute ("CREATE INDEX ir_query_hash ON ns096blocks (query,expiration_time)"), - GNUNET_PQ_make_try_execute ("CREATE INDEX ir_block_expiration ON ns096blocks (expiration_time)"), + GNUNET_PQ_make_try_execute("CREATE INDEX ir_query_hash ON ns096blocks (query,expiration_time)"), + GNUNET_PQ_make_try_execute("CREATE INDEX ir_block_expiration ON ns096blocks (expiration_time)"), GNUNET_PQ_EXECUTE_STATEMENT_END }; if (GNUNET_OK != - GNUNET_PQ_exec_statements (plugin->dbh, - es)) - { - PQfinish (plugin->dbh); - plugin->dbh = NULL; - return GNUNET_SYSERR; - } + GNUNET_PQ_exec_statements(plugin->dbh, + es)) + { + PQfinish(plugin->dbh); + plugin->dbh = NULL; + return GNUNET_SYSERR; + } } { struct GNUNET_PQ_PreparedStatement ps[] = { - GNUNET_PQ_make_prepare ("cache_block", - "INSERT INTO ns096blocks (query, block, expiration_time) VALUES " - "($1, $2, $3)", 3), - GNUNET_PQ_make_prepare ("expire_blocks", - "DELETE FROM ns096blocks WHERE expiration_time<$1", 1), - GNUNET_PQ_make_prepare ("delete_block", - "DELETE FROM ns096blocks WHERE query=$1 AND expiration_time<=$2", 2), - GNUNET_PQ_make_prepare ("lookup_block", - "SELECT block FROM ns096blocks WHERE query=$1" - " ORDER BY expiration_time DESC LIMIT 1", 1), + GNUNET_PQ_make_prepare("cache_block", + "INSERT INTO ns096blocks (query, block, expiration_time) VALUES " + "($1, $2, $3)", 3), + GNUNET_PQ_make_prepare("expire_blocks", + "DELETE FROM ns096blocks WHERE expiration_time<$1", 1), + GNUNET_PQ_make_prepare("delete_block", + "DELETE FROM ns096blocks WHERE query=$1 AND expiration_time<=$2", 2), + GNUNET_PQ_make_prepare("lookup_block", + "SELECT block FROM ns096blocks WHERE query=$1" + " ORDER BY expiration_time DESC LIMIT 1", 1), GNUNET_PQ_PREPARED_STATEMENT_END }; if (GNUNET_OK != - GNUNET_PQ_prepare_statements (plugin->dbh, - ps)) - { - PQfinish (plugin->dbh); - plugin->dbh = NULL; - return GNUNET_SYSERR; - } + GNUNET_PQ_prepare_statements(plugin->dbh, + ps)) + { + PQfinish(plugin->dbh); + plugin->dbh = NULL; + return GNUNET_SYSERR; + } } return GNUNET_OK; @@ -146,19 +143,19 @@ database_setup (struct Plugin *plugin) * @param plugin the plugin */ static void -namecache_postgres_expire_blocks (struct Plugin *plugin) +namecache_postgres_expire_blocks(struct Plugin *plugin) { - struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get (); + struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get(); struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_absolute_time (&now), + GNUNET_PQ_query_param_absolute_time(&now), GNUNET_PQ_query_param_end }; enum GNUNET_DB_QueryStatus res; - res = GNUNET_PQ_eval_prepared_non_select (plugin->dbh, - "expire_blocks", - params); - GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR != res); + res = GNUNET_PQ_eval_prepared_non_select(plugin->dbh, + "expire_blocks", + params); + GNUNET_break(GNUNET_DB_STATUS_HARD_ERROR != res); } @@ -170,21 +167,21 @@ namecache_postgres_expire_blocks (struct Plugin *plugin) * @param expiration_time how old does the block have to be for deletion */ static void -delete_old_block (struct Plugin *plugin, - const struct GNUNET_HashCode *query, - struct GNUNET_TIME_AbsoluteNBO expiration_time) +delete_old_block(struct Plugin *plugin, + const struct GNUNET_HashCode *query, + struct GNUNET_TIME_AbsoluteNBO expiration_time) { struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_auto_from_type (query), - GNUNET_PQ_query_param_absolute_time_nbo (&expiration_time), + GNUNET_PQ_query_param_auto_from_type(query), + GNUNET_PQ_query_param_absolute_time_nbo(&expiration_time), GNUNET_PQ_query_param_end }; enum GNUNET_DB_QueryStatus res; - res = GNUNET_PQ_eval_prepared_non_select (plugin->dbh, - "delete_block", - params); - GNUNET_break (GNUNET_DB_STATUS_HARD_ERROR != res); + res = GNUNET_PQ_eval_prepared_non_select(plugin->dbh, + "delete_block", + params); + GNUNET_break(GNUNET_DB_STATUS_HARD_ERROR != res); } @@ -196,38 +193,38 @@ delete_old_block (struct Plugin *plugin, * @return #GNUNET_OK on success, else #GNUNET_SYSERR */ static int -namecache_postgres_cache_block (void *cls, - const struct GNUNET_GNSRECORD_Block *block) +namecache_postgres_cache_block(void *cls, + const struct GNUNET_GNSRECORD_Block *block) { struct Plugin *plugin = cls; struct GNUNET_HashCode query; - size_t block_size = ntohl (block->purpose.size) + - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) + - sizeof (struct GNUNET_CRYPTO_EcdsaSignature); + size_t block_size = ntohl(block->purpose.size) + + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) + + sizeof(struct GNUNET_CRYPTO_EcdsaSignature); struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_auto_from_type (&query), - GNUNET_PQ_query_param_fixed_size (block, block_size), - GNUNET_PQ_query_param_absolute_time_nbo (&block->expiration_time), + GNUNET_PQ_query_param_auto_from_type(&query), + GNUNET_PQ_query_param_fixed_size(block, block_size), + GNUNET_PQ_query_param_absolute_time_nbo(&block->expiration_time), GNUNET_PQ_query_param_end }; enum GNUNET_DB_QueryStatus res; - namecache_postgres_expire_blocks (plugin); - GNUNET_CRYPTO_hash (&block->derived_key, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey), - &query); + namecache_postgres_expire_blocks(plugin); + GNUNET_CRYPTO_hash(&block->derived_key, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey), + &query); if (block_size > 64 * 65536) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - delete_old_block (plugin, - &query, - block->expiration_time); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + delete_old_block(plugin, + &query, + block->expiration_time); - res = GNUNET_PQ_eval_prepared_non_select (plugin->dbh, - "cache_block", - params); + res = GNUNET_PQ_eval_prepared_non_select(plugin->dbh, + "cache_block", + params); if (0 > res) return GNUNET_SYSERR; return GNUNET_OK; @@ -245,57 +242,57 @@ namecache_postgres_cache_block (void *cls, * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error */ static int -namecache_postgres_lookup_block (void *cls, - const struct GNUNET_HashCode *query, - GNUNET_NAMECACHE_BlockCallback iter, - void *iter_cls) +namecache_postgres_lookup_block(void *cls, + const struct GNUNET_HashCode *query, + GNUNET_NAMECACHE_BlockCallback iter, + void *iter_cls) { struct Plugin *plugin = cls; size_t bsize; struct GNUNET_GNSRECORD_Block *block; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_auto_from_type (query), + GNUNET_PQ_query_param_auto_from_type(query), GNUNET_PQ_query_param_end }; struct GNUNET_PQ_ResultSpec rs[] = { - GNUNET_PQ_result_spec_variable_size ("block", - (void **) &block, - &bsize), + GNUNET_PQ_result_spec_variable_size("block", + (void **)&block, + &bsize), GNUNET_PQ_result_spec_end }; enum GNUNET_DB_QueryStatus res; - res = GNUNET_PQ_eval_prepared_singleton_select (plugin->dbh, - "lookup_block", - params, - rs); + res = GNUNET_PQ_eval_prepared_singleton_select(plugin->dbh, + "lookup_block", + params, + rs); if (0 > res) - { - LOG (GNUNET_ERROR_TYPE_WARNING, - "Failing lookup block in namecache (postgres error)\n"); - return GNUNET_SYSERR; - } + { + LOG(GNUNET_ERROR_TYPE_WARNING, + "Failing lookup block in namecache (postgres error)\n"); + return GNUNET_SYSERR; + } if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == res) - { - /* no result */ - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Ending iteration (no more results)\n"); - return GNUNET_NO; - } - if ( (bsize < sizeof (*block)) || - (bsize != ntohl (block->purpose.size) + - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) + - sizeof (struct GNUNET_CRYPTO_EcdsaSignature)) ) - { - GNUNET_break (0); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Failing lookup (corrupt block)\n"); - GNUNET_PQ_cleanup_result (rs); - return GNUNET_SYSERR; - } - iter (iter_cls, - block); - GNUNET_PQ_cleanup_result (rs); + { + /* no result */ + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Ending iteration (no more results)\n"); + return GNUNET_NO; + } + if ((bsize < sizeof(*block)) || + (bsize != ntohl(block->purpose.size) + + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) + + sizeof(struct GNUNET_CRYPTO_EcdsaSignature))) + { + GNUNET_break(0); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Failing lookup (corrupt block)\n"); + GNUNET_PQ_cleanup_result(rs); + return GNUNET_SYSERR; + } + iter(iter_cls, + block); + GNUNET_PQ_cleanup_result(rs); return GNUNET_OK; } @@ -307,9 +304,9 @@ namecache_postgres_lookup_block (void *cls, * @param plugin the plugin context (state for this module) */ static void -database_shutdown (struct Plugin *plugin) +database_shutdown(struct Plugin *plugin) { - PQfinish (plugin->dbh); + PQfinish(plugin->dbh); plugin->dbh = NULL; } @@ -321,7 +318,7 @@ database_shutdown (struct Plugin *plugin) * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_namecache_postgres_init (void *cls) +libgnunet_plugin_namecache_postgres_init(void *cls) { static struct Plugin plugin; const struct GNUNET_CONFIGURATION_Handle *cfg = cls; @@ -329,19 +326,19 @@ libgnunet_plugin_namecache_postgres_init (void *cls) if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.cfg = cfg; - if (GNUNET_OK != database_setup (&plugin)) - { - database_shutdown (&plugin); - return NULL; - } - api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions); + if (GNUNET_OK != database_setup(&plugin)) + { + database_shutdown(&plugin); + return NULL; + } + api = GNUNET_new(struct GNUNET_NAMECACHE_PluginFunctions); api->cls = &plugin; api->cache_block = &namecache_postgres_cache_block; api->lookup_block = &namecache_postgres_lookup_block; - LOG (GNUNET_ERROR_TYPE_INFO, - "Postgres namecache plugin running\n"); + LOG(GNUNET_ERROR_TYPE_INFO, + "Postgres namecache plugin running\n"); return api; } @@ -353,16 +350,16 @@ libgnunet_plugin_namecache_postgres_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_namecache_postgres_done (void *cls) +libgnunet_plugin_namecache_postgres_done(void *cls) { struct GNUNET_NAMECACHE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - database_shutdown (plugin); + database_shutdown(plugin); plugin->cfg = NULL; - GNUNET_free (api); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Postgres namecache plugin is finished\n"); + GNUNET_free(api); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Postgres namecache plugin is finished\n"); return NULL; } diff --git a/src/namecache/plugin_namecache_sqlite.c b/src/namecache/plugin_namecache_sqlite.c index f493e015f..e52438b4e 100644 --- a/src/namecache/plugin_namecache_sqlite.c +++ b/src/namecache/plugin_namecache_sqlite.c @@ -1,22 +1,22 @@ - /* - * This file is part of GNUnet - * Copyright (C) 2009-2013 GNUnet e.V. - * - * GNUnet is free software: you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * GNUnet is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - - SPDX-License-Identifier: AGPL3.0-or-later - */ +/* + * This file is part of GNUnet + * Copyright (C) 2009-2013 GNUnet e.V. + * + * GNUnet is free software: you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * GNUnet is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + + SPDX-License-Identifier: AGPL3.0-or-later + */ /** * @file namecache/plugin_namecache_sqlite.c @@ -49,17 +49,15 @@ * a failure of the command 'cmd' on file 'filename' * with the message given by strerror(errno). */ -#define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from (level, "namecache-sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0) +#define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from(level, "namecache-sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while (0) -#define LOG(kind,...) GNUNET_log_from (kind, "namecache-sqlite", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "namecache-sqlite", __VA_ARGS__) /** * Context for all functions in this plugin. */ -struct Plugin -{ - +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; /** @@ -91,7 +89,6 @@ struct Plugin * Precompiled SQL for removing expired blocks */ sqlite3_stmt *expire_blocks; - }; @@ -104,100 +101,100 @@ struct Plugin * @return #GNUNET_OK on success */ static int -database_setup (struct Plugin *plugin) +database_setup(struct Plugin *plugin) { struct GNUNET_SQ_ExecuteStatement es[] = { - GNUNET_SQ_make_try_execute ("PRAGMA temp_store=MEMORY"), - GNUNET_SQ_make_try_execute ("PRAGMA synchronous=NORMAL"), - GNUNET_SQ_make_try_execute ("PRAGMA legacy_file_format=OFF"), - GNUNET_SQ_make_try_execute ("PRAGMA auto_vacuum=INCREMENTAL"), - GNUNET_SQ_make_try_execute ("PRAGMA encoding=\"UTF-8\""), - GNUNET_SQ_make_try_execute ("PRAGMA locking_mode=EXCLUSIVE"), - GNUNET_SQ_make_try_execute ("PRAGMA page_size=4092"), - GNUNET_SQ_make_try_execute ("PRAGMA journal_mode=WAL"), - GNUNET_SQ_make_execute ("CREATE TABLE IF NOT EXISTS ns096blocks (" - " query BLOB NOT NULL," - " block BLOB NOT NULL," - " expiration_time INT8 NOT NULL" - ")"), - GNUNET_SQ_make_execute ("CREATE INDEX IF NOT EXISTS ir_query_hash " - "ON ns096blocks (query,expiration_time)"), - GNUNET_SQ_make_execute ("CREATE INDEX IF NOT EXISTS ir_block_expiration " - "ON ns096blocks (expiration_time)"), + GNUNET_SQ_make_try_execute("PRAGMA temp_store=MEMORY"), + GNUNET_SQ_make_try_execute("PRAGMA synchronous=NORMAL"), + GNUNET_SQ_make_try_execute("PRAGMA legacy_file_format=OFF"), + GNUNET_SQ_make_try_execute("PRAGMA auto_vacuum=INCREMENTAL"), + GNUNET_SQ_make_try_execute("PRAGMA encoding=\"UTF-8\""), + GNUNET_SQ_make_try_execute("PRAGMA locking_mode=EXCLUSIVE"), + GNUNET_SQ_make_try_execute("PRAGMA page_size=4092"), + GNUNET_SQ_make_try_execute("PRAGMA journal_mode=WAL"), + GNUNET_SQ_make_execute("CREATE TABLE IF NOT EXISTS ns096blocks (" + " query BLOB NOT NULL," + " block BLOB NOT NULL," + " expiration_time INT8 NOT NULL" + ")"), + GNUNET_SQ_make_execute("CREATE INDEX IF NOT EXISTS ir_query_hash " + "ON ns096blocks (query,expiration_time)"), + GNUNET_SQ_make_execute("CREATE INDEX IF NOT EXISTS ir_block_expiration " + "ON ns096blocks (expiration_time)"), GNUNET_SQ_EXECUTE_STATEMENT_END }; struct GNUNET_SQ_PrepareStatement ps[] = { - GNUNET_SQ_make_prepare ("INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)", - &plugin->cache_block), - GNUNET_SQ_make_prepare ("DELETE FROM ns096blocks WHERE expiration_timeexpire_blocks), - GNUNET_SQ_make_prepare ("DELETE FROM ns096blocks WHERE query=? AND expiration_time<=?", - &plugin->delete_block), - GNUNET_SQ_make_prepare ("SELECT block FROM ns096blocks WHERE query=? " - "ORDER BY expiration_time DESC LIMIT 1", - &plugin->lookup_block), + GNUNET_SQ_make_prepare("INSERT INTO ns096blocks (query,block,expiration_time) VALUES (?, ?, ?)", + &plugin->cache_block), + GNUNET_SQ_make_prepare("DELETE FROM ns096blocks WHERE expiration_timeexpire_blocks), + GNUNET_SQ_make_prepare("DELETE FROM ns096blocks WHERE query=? AND expiration_time<=?", + &plugin->delete_block), + GNUNET_SQ_make_prepare("SELECT block FROM ns096blocks WHERE query=? " + "ORDER BY expiration_time DESC LIMIT 1", + &plugin->lookup_block), GNUNET_SQ_PREPARE_END }; char *afsdir; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, - "namecache-sqlite", - "FILENAME", - &afsdir)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "namecache-sqlite", - "FILENAME"); - return GNUNET_SYSERR; - } - if (GNUNET_OK != - GNUNET_DISK_file_test (afsdir)) - { - if (GNUNET_OK != - GNUNET_DISK_directory_create_for_file (afsdir)) + GNUNET_CONFIGURATION_get_value_filename(plugin->cfg, + "namecache-sqlite", + "FILENAME", + &afsdir)) { - GNUNET_break (0); - GNUNET_free (afsdir); + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "namecache-sqlite", + "FILENAME"); return GNUNET_SYSERR; } - } + if (GNUNET_OK != + GNUNET_DISK_file_test(afsdir)) + { + if (GNUNET_OK != + GNUNET_DISK_directory_create_for_file(afsdir)) + { + GNUNET_break(0); + GNUNET_free(afsdir); + return GNUNET_SYSERR; + } + } /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */ plugin->fn = afsdir; /* Open database and precompile statements */ if (SQLITE_OK != - sqlite3_open (plugin->fn, &plugin->dbh)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Unable to initialize SQLite: %s.\n"), - sqlite3_errmsg (plugin->dbh)); - return GNUNET_SYSERR; - } + sqlite3_open(plugin->fn, &plugin->dbh)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Unable to initialize SQLite: %s.\n"), + sqlite3_errmsg(plugin->dbh)); + return GNUNET_SYSERR; + } if (GNUNET_OK != - GNUNET_SQ_exec_statements (plugin->dbh, - es)) - { - GNUNET_break (0); - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Failed to setup database at `%s'\n"), - plugin->fn); - return GNUNET_SYSERR; - } - GNUNET_break (SQLITE_OK == - sqlite3_busy_timeout (plugin->dbh, - BUSY_TIMEOUT_MS)); - + GNUNET_SQ_exec_statements(plugin->dbh, + es)) + { + GNUNET_break(0); + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Failed to setup database at `%s'\n"), + plugin->fn); + return GNUNET_SYSERR; + } + GNUNET_break(SQLITE_OK == + sqlite3_busy_timeout(plugin->dbh, + BUSY_TIMEOUT_MS)); + if (GNUNET_OK != - GNUNET_SQ_prepare (plugin->dbh, - ps)) - { - GNUNET_break (0); - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Failed to setup database at `%s'\n"), - plugin->fn); - return GNUNET_SYSERR; - } + GNUNET_SQ_prepare(plugin->dbh, + ps)) + { + GNUNET_break(0); + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Failed to setup database at `%s'\n"), + plugin->fn); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -209,50 +206,50 @@ database_setup (struct Plugin *plugin) * @param plugin the plugin context (state for this module) */ static void -database_shutdown (struct Plugin *plugin) +database_shutdown(struct Plugin *plugin) { int result; sqlite3_stmt *stmt; if (NULL != plugin->cache_block) - sqlite3_finalize (plugin->cache_block); + sqlite3_finalize(plugin->cache_block); if (NULL != plugin->lookup_block) - sqlite3_finalize (plugin->lookup_block); + sqlite3_finalize(plugin->lookup_block); if (NULL != plugin->expire_blocks) - sqlite3_finalize (plugin->expire_blocks); + sqlite3_finalize(plugin->expire_blocks); if (NULL != plugin->delete_block) - sqlite3_finalize (plugin->delete_block); - result = sqlite3_close (plugin->dbh); + sqlite3_finalize(plugin->delete_block); + result = sqlite3_close(plugin->dbh); if (result == SQLITE_BUSY) - { - LOG (GNUNET_ERROR_TYPE_WARNING, - _("Tried to close sqlite without finalizing all prepared statements.\n")); - stmt = sqlite3_next_stmt (plugin->dbh, - NULL); - while (stmt != NULL) { - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "sqlite", - "Closing statement %p\n", - stmt); - result = sqlite3_finalize (stmt); - if (result != SQLITE_OK) - GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, - "sqlite", - "Failed to close statement %p: %d\n", - stmt, - result); - stmt = sqlite3_next_stmt (plugin->dbh, - NULL); + LOG(GNUNET_ERROR_TYPE_WARNING, + _("Tried to close sqlite without finalizing all prepared statements.\n")); + stmt = sqlite3_next_stmt(plugin->dbh, + NULL); + while (stmt != NULL) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "sqlite", + "Closing statement %p\n", + stmt); + result = sqlite3_finalize(stmt); + if (result != SQLITE_OK) + GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, + "sqlite", + "Failed to close statement %p: %d\n", + stmt, + result); + stmt = sqlite3_next_stmt(plugin->dbh, + NULL); + } + result = sqlite3_close(plugin->dbh); } - result = sqlite3_close (plugin->dbh); - } if (SQLITE_OK != result) - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR, - "sqlite3_close"); + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR, + "sqlite3_close"); - GNUNET_free_non_null (plugin->fn); + GNUNET_free_non_null(plugin->fn); } @@ -262,48 +259,50 @@ database_shutdown (struct Plugin *plugin) * @param plugin the plugin */ static void -namecache_sqlite_expire_blocks (struct Plugin *plugin) +namecache_sqlite_expire_blocks(struct Plugin *plugin) { struct GNUNET_TIME_Absolute now; struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_absolute_time (&now), + GNUNET_SQ_query_param_absolute_time(&now), GNUNET_SQ_query_param_end }; int n; - now = GNUNET_TIME_absolute_get (); + now = GNUNET_TIME_absolute_get(); if (GNUNET_OK != - GNUNET_SQ_bind (plugin->expire_blocks, - params)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_XXXX"); - GNUNET_SQ_reset (plugin->dbh, - plugin->expire_blocks); - return; - } - n = sqlite3_step (plugin->expire_blocks); - GNUNET_SQ_reset (plugin->dbh, - plugin->expire_blocks); + GNUNET_SQ_bind(plugin->expire_blocks, + params)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_XXXX"); + GNUNET_SQ_reset(plugin->dbh, + plugin->expire_blocks); + return; + } + n = sqlite3_step(plugin->expire_blocks); + GNUNET_SQ_reset(plugin->dbh, + plugin->expire_blocks); switch (n) - { - case SQLITE_DONE: - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "sqlite", - "Records expired\n"); - return; - case SQLITE_BUSY: - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - return; - default: - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - return; - } + { + case SQLITE_DONE: + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "sqlite", + "Records expired\n"); + return; + + case SQLITE_BUSY: + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + return; + + default: + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + return; + } } @@ -315,120 +314,123 @@ namecache_sqlite_expire_blocks (struct Plugin *plugin) * @return #GNUNET_OK on success, else #GNUNET_SYSERR */ static int -namecache_sqlite_cache_block (void *cls, - const struct GNUNET_GNSRECORD_Block *block) +namecache_sqlite_cache_block(void *cls, + const struct GNUNET_GNSRECORD_Block *block) { static struct GNUNET_TIME_Absolute last_expire; struct Plugin *plugin = cls; struct GNUNET_HashCode query; struct GNUNET_TIME_Absolute expiration; - size_t block_size = ntohl (block->purpose.size) + - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) + - sizeof (struct GNUNET_CRYPTO_EcdsaSignature); + size_t block_size = ntohl(block->purpose.size) + + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) + + sizeof(struct GNUNET_CRYPTO_EcdsaSignature); struct GNUNET_SQ_QueryParam del_params[] = { - GNUNET_SQ_query_param_auto_from_type (&query), - GNUNET_SQ_query_param_absolute_time (&expiration), + GNUNET_SQ_query_param_auto_from_type(&query), + GNUNET_SQ_query_param_absolute_time(&expiration), GNUNET_SQ_query_param_end }; struct GNUNET_SQ_QueryParam ins_params[] = { - GNUNET_SQ_query_param_auto_from_type (&query), - GNUNET_SQ_query_param_fixed_size (block, - block_size), - GNUNET_SQ_query_param_absolute_time (&expiration), + GNUNET_SQ_query_param_auto_from_type(&query), + GNUNET_SQ_query_param_fixed_size(block, + block_size), + GNUNET_SQ_query_param_absolute_time(&expiration), GNUNET_SQ_query_param_end }; int n; /* run expiration of old cache entries once per hour */ - if (GNUNET_TIME_absolute_get_duration (last_expire).rel_value_us > + if (GNUNET_TIME_absolute_get_duration(last_expire).rel_value_us > GNUNET_TIME_UNIT_HOURS.rel_value_us) - { - last_expire = GNUNET_TIME_absolute_get (); - namecache_sqlite_expire_blocks (plugin); - } - GNUNET_CRYPTO_hash (&block->derived_key, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey), - &query); - expiration = GNUNET_TIME_absolute_ntoh (block->expiration_time); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Caching new version of block %s (expires %s)\n", - GNUNET_h2s (&query), - GNUNET_STRINGS_absolute_time_to_string (expiration)); + { + last_expire = GNUNET_TIME_absolute_get(); + namecache_sqlite_expire_blocks(plugin); + } + GNUNET_CRYPTO_hash(&block->derived_key, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey), + &query); + expiration = GNUNET_TIME_absolute_ntoh(block->expiration_time); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Caching new version of block %s (expires %s)\n", + GNUNET_h2s(&query), + GNUNET_STRINGS_absolute_time_to_string(expiration)); if (block_size > 64 * 65536) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } /* delete old version of the block */ if (GNUNET_OK != - GNUNET_SQ_bind (plugin->delete_block, - del_params)) - { - LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_XXXX"); - GNUNET_SQ_reset (plugin->dbh, - plugin->delete_block); - return GNUNET_SYSERR; - } - n = sqlite3_step (plugin->delete_block); + GNUNET_SQ_bind(plugin->delete_block, + del_params)) + { + LOG_SQLITE(plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_XXXX"); + GNUNET_SQ_reset(plugin->dbh, + plugin->delete_block); + return GNUNET_SYSERR; + } + n = sqlite3_step(plugin->delete_block); switch (n) - { - case SQLITE_DONE: - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "sqlite", - "Old block deleted\n"); - break; - case SQLITE_BUSY: - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - break; - default: - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - break; - } - GNUNET_SQ_reset (plugin->dbh, - plugin->delete_block); + { + case SQLITE_DONE: + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "sqlite", + "Old block deleted\n"); + break; + + case SQLITE_BUSY: + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + break; + + default: + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + break; + } + GNUNET_SQ_reset(plugin->dbh, + plugin->delete_block); /* insert new version of the block */ if (GNUNET_OK != - GNUNET_SQ_bind (plugin->cache_block, - ins_params)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_XXXX"); - GNUNET_SQ_reset (plugin->dbh, - plugin->cache_block); - return GNUNET_SYSERR; - - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Caching block under derived key `%s'\n", - GNUNET_h2s_full (&query)); - n = sqlite3_step (plugin->cache_block); - GNUNET_SQ_reset (plugin->dbh, - plugin->cache_block); + GNUNET_SQ_bind(plugin->cache_block, + ins_params)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_XXXX"); + GNUNET_SQ_reset(plugin->dbh, + plugin->cache_block); + return GNUNET_SYSERR; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Caching block under derived key `%s'\n", + GNUNET_h2s_full(&query)); + n = sqlite3_step(plugin->cache_block); + GNUNET_SQ_reset(plugin->dbh, + plugin->cache_block); switch (n) - { - case SQLITE_DONE: - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Record stored\n"); - return GNUNET_OK; - case SQLITE_BUSY: - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - return GNUNET_NO; - default: - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - return GNUNET_SYSERR; - } + { + case SQLITE_DONE: + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Record stored\n"); + return GNUNET_OK; + + case SQLITE_BUSY: + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + return GNUNET_NO; + + default: + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + return GNUNET_SYSERR; + } } @@ -443,10 +445,10 @@ namecache_sqlite_cache_block (void *cls, * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error */ static int -namecache_sqlite_lookup_block (void *cls, - const struct GNUNET_HashCode *query, - GNUNET_NAMECACHE_BlockCallback iter, - void *iter_cls) +namecache_sqlite_lookup_block(void *cls, + const struct GNUNET_HashCode *query, + GNUNET_NAMECACHE_BlockCallback iter, + void *iter_cls) { struct Plugin *plugin = cls; int ret; @@ -454,75 +456,75 @@ namecache_sqlite_lookup_block (void *cls, size_t block_size; const struct GNUNET_GNSRECORD_Block *block; struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_auto_from_type (query), + GNUNET_SQ_query_param_auto_from_type(query), GNUNET_SQ_query_param_end }; struct GNUNET_SQ_ResultSpec rs[] = { - GNUNET_SQ_result_spec_variable_size ((void **) &block, - &block_size), + GNUNET_SQ_result_spec_variable_size((void **)&block, + &block_size), GNUNET_SQ_result_spec_end }; if (GNUNET_OK != - GNUNET_SQ_bind (plugin->lookup_block, - params)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_XXXX"); - GNUNET_SQ_reset (plugin->dbh, - plugin->lookup_block); - return GNUNET_SYSERR; - } - ret = GNUNET_NO; - if (SQLITE_ROW == - (sret = sqlite3_step (plugin->lookup_block))) - { - if (GNUNET_OK != - GNUNET_SQ_extract_result (plugin->lookup_block, - rs)) + GNUNET_SQ_bind(plugin->lookup_block, + params)) { - GNUNET_break (0); - ret = GNUNET_SYSERR; - } - else if ( (block_size < sizeof (struct GNUNET_GNSRECORD_Block)) || - (ntohl (block->purpose.size) + - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey) + - sizeof (struct GNUNET_CRYPTO_EcdsaSignature) != block_size) ) - { - GNUNET_break (0); - GNUNET_SQ_cleanup_result (rs); - ret = GNUNET_SYSERR; + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_XXXX"); + GNUNET_SQ_reset(plugin->dbh, + plugin->lookup_block); + return GNUNET_SYSERR; } - else + ret = GNUNET_NO; + if (SQLITE_ROW == + (sret = sqlite3_step(plugin->lookup_block))) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found block under derived key `%s'\n", - GNUNET_h2s_full (query)); - iter (iter_cls, - block); - GNUNET_SQ_cleanup_result (rs); - ret = GNUNET_YES; + if (GNUNET_OK != + GNUNET_SQ_extract_result(plugin->lookup_block, + rs)) + { + GNUNET_break(0); + ret = GNUNET_SYSERR; + } + else if ((block_size < sizeof(struct GNUNET_GNSRECORD_Block)) || + (ntohl(block->purpose.size) + + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey) + + sizeof(struct GNUNET_CRYPTO_EcdsaSignature) != block_size)) + { + GNUNET_break(0); + GNUNET_SQ_cleanup_result(rs); + ret = GNUNET_SYSERR; + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found block under derived key `%s'\n", + GNUNET_h2s_full(query)); + iter(iter_cls, + block); + GNUNET_SQ_cleanup_result(rs); + ret = GNUNET_YES; + } } - } else - { - if (SQLITE_DONE != sret) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR, - "sqlite_step"); - ret = GNUNET_SYSERR; - } - else { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "No block found under derived key `%s'\n", - GNUNET_h2s_full (query)); + if (SQLITE_DONE != sret) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR, + "sqlite_step"); + ret = GNUNET_SYSERR; + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "No block found under derived key `%s'\n", + GNUNET_h2s_full(query)); + } } - } - GNUNET_SQ_reset (plugin->dbh, - plugin->lookup_block); + GNUNET_SQ_reset(plugin->dbh, + plugin->lookup_block); return ret; } @@ -534,7 +536,7 @@ namecache_sqlite_lookup_block (void *cls, * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_namecache_sqlite_init (void *cls) +libgnunet_plugin_namecache_sqlite_init(void *cls) { static struct Plugin plugin; const struct GNUNET_CONFIGURATION_Handle *cfg = cls; @@ -542,19 +544,19 @@ libgnunet_plugin_namecache_sqlite_init (void *cls) if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.cfg = cfg; - if (GNUNET_OK != database_setup (&plugin)) - { - database_shutdown (&plugin); - return NULL; - } - api = GNUNET_new (struct GNUNET_NAMECACHE_PluginFunctions); + if (GNUNET_OK != database_setup(&plugin)) + { + database_shutdown(&plugin); + return NULL; + } + api = GNUNET_new(struct GNUNET_NAMECACHE_PluginFunctions); api->cls = &plugin; api->cache_block = &namecache_sqlite_cache_block; api->lookup_block = &namecache_sqlite_lookup_block; - LOG (GNUNET_ERROR_TYPE_INFO, - _("Sqlite database running\n")); + LOG(GNUNET_ERROR_TYPE_INFO, + _("Sqlite database running\n")); return api; } @@ -566,16 +568,16 @@ libgnunet_plugin_namecache_sqlite_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_namecache_sqlite_done (void *cls) +libgnunet_plugin_namecache_sqlite_done(void *cls) { struct GNUNET_NAMECACHE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - database_shutdown (plugin); + database_shutdown(plugin); plugin->cfg = NULL; - GNUNET_free (api); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "sqlite plugin is finished\n"); + GNUNET_free(api); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "sqlite plugin is finished\n"); return NULL; } diff --git a/src/namecache/test_namecache_api_cache_block.c b/src/namecache/test_namecache_api_cache_block.c index 1d522e7fb..def6cedb3 100644 --- a/src/namecache/test_namecache_api_cache_block.c +++ b/src/namecache/test_namecache_api_cache_block.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namecache/test_namecache_api.c * @brief testcase for namecache_api.c: store a record and perform a lookup @@ -32,7 +32,7 @@ #define TEST_RECORD_DATA 'a' -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static struct GNUNET_NAMECACHE_Handle *nsh; @@ -49,19 +49,19 @@ static struct GNUNET_NAMECACHE_QueueEntry *nsqe; static void -cleanup () +cleanup() { if (NULL != nsh) - { - GNUNET_NAMECACHE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMECACHE_disconnect(nsh); + nsh = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_free(privkey); + privkey = NULL; + } + GNUNET_SCHEDULER_shutdown(); } @@ -71,177 +71,178 @@ cleanup () * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { if (NULL != nsqe) - { - GNUNET_NAMECACHE_cancel (nsqe); - nsqe = NULL; - } - cleanup (); + { + GNUNET_NAMECACHE_cancel(nsqe); + nsqe = NULL; + } + cleanup(); res = 1; } static void -end (void *cls) +end(void *cls) { - cleanup (); + cleanup(); res = 0; } static void -rd_decrypt_cb (void *cls, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +rd_decrypt_cb(void *cls, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { char rd_cmp_data[TEST_RECORD_DATALEN]; - GNUNET_assert (1 == rd_count); - GNUNET_assert (NULL != rd); + GNUNET_assert(1 == rd_count); + GNUNET_assert(NULL != rd); - memset (rd_cmp_data, 'a', TEST_RECORD_DATALEN); + memset(rd_cmp_data, 'a', TEST_RECORD_DATALEN); - GNUNET_assert (TEST_RECORD_TYPE == rd[0].record_type); - GNUNET_assert (TEST_RECORD_DATALEN == rd[0].data_size); - GNUNET_assert (0 == memcmp (&rd_cmp_data, rd[0].data, TEST_RECORD_DATALEN)); + GNUNET_assert(TEST_RECORD_TYPE == rd[0].record_type); + GNUNET_assert(TEST_RECORD_DATALEN == rd[0].data_size); + GNUNET_assert(0 == memcmp(&rd_cmp_data, rd[0].data, TEST_RECORD_DATALEN)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Block was decrypted successfully \n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Block was decrypted successfully \n"); - GNUNET_SCHEDULER_add_now (&end, NULL); + GNUNET_SCHEDULER_add_now(&end, NULL); } static void -name_lookup_proc (void *cls, - const struct GNUNET_GNSRECORD_Block *block) +name_lookup_proc(void *cls, + const struct GNUNET_GNSRECORD_Block *block) { const char *name = cls; + nsqe = NULL; - GNUNET_assert (NULL != cls); + GNUNET_assert(NULL != cls); if (endbadly_task != NULL) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } if (NULL == block) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namecache returned no block\n")); - if (NULL != endbadly_task) - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Namecache returned block, decrypting \n"); - GNUNET_assert (GNUNET_OK == GNUNET_GNSRECORD_block_decrypt(block, - &pubkey, name, &rd_decrypt_cb, (void *) name)); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namecache returned no block\n")); + if (NULL != endbadly_task) + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Namecache returned block, decrypting \n"); + GNUNET_assert(GNUNET_OK == GNUNET_GNSRECORD_block_decrypt(block, + &pubkey, name, &rd_decrypt_cb, (void *)name)); } static void -cache_cont (void *cls, int32_t success, const char *emsg) +cache_cont(void *cls, int32_t success, const char *emsg) { const char *name = cls; struct GNUNET_HashCode derived_hash; - GNUNET_assert (NULL != cls); + GNUNET_assert(NULL != cls); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name store cached record for `%s': %s\n", - name, - (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name store cached record for `%s': %s\n", + name, + (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); /* Create derived hash */ - GNUNET_GNSRECORD_query_from_public_key (&pubkey, name, &derived_hash); + GNUNET_GNSRECORD_query_from_public_key(&pubkey, name, &derived_hash); - nsqe = GNUNET_NAMECACHE_lookup_block (nsh, &derived_hash, - &name_lookup_proc, (void *) name); + nsqe = GNUNET_NAMECACHE_lookup_block(nsh, &derived_hash, + &name_lookup_proc, (void *)name); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct GNUNET_GNSRECORD_Data rd; struct GNUNET_GNSRECORD_Block *block; char *hostkey_file; const char * name = "dummy.dummy.gnunet"; - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, NULL); - GNUNET_asprintf (&hostkey_file, - "zonefiles%s%s", - DIR_SEPARATOR_STR, - "N0UJMP015AFUNR2BTNM3FKPBLG38913BL8IDMCO2H0A1LIB81960.zkey"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Using zonekey file `%s' \n", hostkey_file); - privkey = GNUNET_CRYPTO_ecdsa_key_create_from_file (hostkey_file); - GNUNET_free (hostkey_file); - GNUNET_assert (privkey != NULL); - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, &pubkey); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, NULL); + GNUNET_asprintf(&hostkey_file, + "zonefiles%s%s", + DIR_SEPARATOR_STR, + "N0UJMP015AFUNR2BTNM3FKPBLG38913BL8IDMCO2H0A1LIB81960.zkey"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Using zonekey file `%s' \n", hostkey_file); + privkey = GNUNET_CRYPTO_ecdsa_key_create_from_file(hostkey_file); + GNUNET_free(hostkey_file); + GNUNET_assert(privkey != NULL); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, &pubkey); rd.expiration_time = GNUNET_TIME_absolute_get().abs_value_us + 10000000000; rd.record_type = TEST_RECORD_TYPE; rd.data_size = TEST_RECORD_DATALEN; - rd.data = GNUNET_malloc (TEST_RECORD_DATALEN); + rd.data = GNUNET_malloc(TEST_RECORD_DATALEN); rd.flags = 0; - memset ((char *) rd.data, 'a', TEST_RECORD_DATALEN); - block = GNUNET_GNSRECORD_block_create (privkey, - GNUNET_TIME_UNIT_FOREVER_ABS, - name, &rd, 1); + memset((char *)rd.data, 'a', TEST_RECORD_DATALEN); + block = GNUNET_GNSRECORD_block_create(privkey, + GNUNET_TIME_UNIT_FOREVER_ABS, + name, &rd, 1); if (NULL == block) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Namecache cannot cache no block!\n"); - GNUNET_SCHEDULER_shutdown (); - GNUNET_free (block); - return; - } - - nsh = GNUNET_NAMECACHE_connect (cfg); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Namecache cannot cache no block!\n"); + GNUNET_SCHEDULER_shutdown(); + GNUNET_free(block); + return; + } + + nsh = GNUNET_NAMECACHE_connect(cfg); if (NULL == nsh) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namecache cannot connect to namecache\n")); - GNUNET_SCHEDULER_shutdown (); - GNUNET_free (block); - return; - } - GNUNET_break (NULL != nsh); - - nsqe = GNUNET_NAMECACHE_block_cache (nsh, - block, - &cache_cont, (void *) name); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namecache cannot connect to namecache\n")); + GNUNET_SCHEDULER_shutdown(); + GNUNET_free(block); + return; + } + GNUNET_break(NULL != nsh); + + nsqe = GNUNET_NAMECACHE_block_cache(nsh, + block, + &cache_cont, (void *)name); if (NULL == nsqe) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namecache cannot cache no block\n")); - } - GNUNET_free (block); - GNUNET_free ((void *)rd.data); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namecache cannot cache no block\n")); + } + GNUNET_free(block); + GNUNET_free((void *)rd.data); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - GNUNET_DISK_directory_remove ("/tmp/test-gnunet-namecache/"); + GNUNET_DISK_directory_remove("/tmp/test-gnunet-namecache/"); res = 1; if (0 != - GNUNET_TESTING_service_run ("test-namecache-api", - "namecache", - "test_namecache_api.conf", - &run, - NULL)) + GNUNET_TESTING_service_run("test-namecache-api", + "namecache", + "test_namecache_api.conf", + &run, + NULL)) return 1; return res; } diff --git a/src/namecache/test_plugin_namecache.c b/src/namecache/test_plugin_namecache.c index 4939bc4b6..5c52bb375 100644 --- a/src/namecache/test_plugin_namecache.c +++ b/src/namecache/test_plugin_namecache.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /* * @file namecache/test_plugin_namecache.c * @brief Test for the namecache plugins @@ -43,13 +43,13 @@ static const char *plugin_name; * @param api api to unload */ static void -unload_plugin (struct GNUNET_NAMECACHE_PluginFunctions *api) +unload_plugin(struct GNUNET_NAMECACHE_PluginFunctions *api) { char *libname; - GNUNET_asprintf (&libname, "libgnunet_plugin_namecache_%s", plugin_name); - GNUNET_break (NULL == GNUNET_PLUGIN_unload (libname, api)); - GNUNET_free (libname); + GNUNET_asprintf(&libname, "libgnunet_plugin_namecache_%s", plugin_name); + GNUNET_break(NULL == GNUNET_PLUGIN_unload(libname, api)); + GNUNET_free(libname); } @@ -60,47 +60,47 @@ unload_plugin (struct GNUNET_NAMECACHE_PluginFunctions *api) * @return NULL on error */ static struct GNUNET_NAMECACHE_PluginFunctions * -load_plugin (const struct GNUNET_CONFIGURATION_Handle *cfg) +load_plugin(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_NAMECACHE_PluginFunctions *ret; char *libname; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Loading `%s' namecache plugin\n"), - plugin_name); - GNUNET_asprintf (&libname, "libgnunet_plugin_namecache_%s", plugin_name); - if (NULL == (ret = GNUNET_PLUGIN_load (libname, (void*) cfg))) - { - fprintf (stderr, "Failed to load plugin `%s'!\n", plugin_name); - GNUNET_free (libname); - return NULL; - } - GNUNET_free (libname); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Loading `%s' namecache plugin\n"), + plugin_name); + GNUNET_asprintf(&libname, "libgnunet_plugin_namecache_%s", plugin_name); + if (NULL == (ret = GNUNET_PLUGIN_load(libname, (void*)cfg))) + { + fprintf(stderr, "Failed to load plugin `%s'!\n", plugin_name); + GNUNET_free(libname); + return NULL; + } + GNUNET_free(libname); return ret; } static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_NAMECACHE_PluginFunctions *nsp; ok = 0; - nsp = load_plugin (cfg); + nsp = load_plugin(cfg); if (NULL == nsp) - { - fprintf (stderr, - "%s", - "Failed to initialize namecache. Database likely not setup, skipping test.\n"); - return; - } - - unload_plugin (nsp); + { + fprintf(stderr, + "%s", + "Failed to initialize namecache. Database likely not setup, skipping test.\n"); + return; + } + + unload_plugin(nsp); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { char cfg_name[PATH_MAX]; char *const xargv[] = { @@ -113,18 +113,18 @@ main (int argc, char *argv[]) GNUNET_GETOPT_OPTION_END }; - GNUNET_DISK_directory_remove ("/tmp/gnunet-test-plugin-namecache-sqlite"); - GNUNET_log_setup ("test-plugin-namecache", - "WARNING", - NULL); - plugin_name = GNUNET_TESTING_get_testname_from_underscore (argv[0]); - GNUNET_snprintf (cfg_name, sizeof (cfg_name), "test_plugin_namecache_%s.conf", - plugin_name); - GNUNET_PROGRAM_run ((sizeof (xargv) / sizeof (char *)) - 1, xargv, - "test-plugin-namecache", "nohelp", options, &run, NULL); + GNUNET_DISK_directory_remove("/tmp/gnunet-test-plugin-namecache-sqlite"); + GNUNET_log_setup("test-plugin-namecache", + "WARNING", + NULL); + plugin_name = GNUNET_TESTING_get_testname_from_underscore(argv[0]); + GNUNET_snprintf(cfg_name, sizeof(cfg_name), "test_plugin_namecache_%s.conf", + plugin_name); + GNUNET_PROGRAM_run((sizeof(xargv) / sizeof(char *)) - 1, xargv, + "test-plugin-namecache", "nohelp", options, &run, NULL); if (ok != 0) - fprintf (stderr, "Missed some testcases: %d\n", ok); - GNUNET_DISK_directory_remove ("/tmp/gnunet-test-plugin-namecache-sqlite"); + fprintf(stderr, "Missed some testcases: %d\n", ok); + GNUNET_DISK_directory_remove("/tmp/gnunet-test-plugin-namecache-sqlite"); return ok; } diff --git a/src/namestore/gnunet-namestore-fcfsd.c b/src/namestore/gnunet-namestore-fcfsd.c index 58e824ea6..3abf1ed21 100644 --- a/src/namestore/gnunet-namestore-fcfsd.c +++ b/src/namestore/gnunet-namestore-fcfsd.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnunet-namestore-fcfsd.c * @brief HTTP daemon that offers first-come-first-serve GNS domain registration @@ -74,41 +74,38 @@ /** * Phases a request goes through. */ -enum Phase - { - /** - * Start phase (parsing POST, checking). - */ - RP_START = 0, - - /** - * Lookup to see if the domain name is taken. - */ - RP_LOOKUP, - - /** - * Storing of the record. - */ - RP_PUT, - - /** - * We're done with success. - */ - RP_SUCCESS, - - /** - * Send failure message. - */ - RP_FAIL - }; +enum Phase { + /** + * Start phase (parsing POST, checking). + */ + RP_START = 0, + + /** + * Lookup to see if the domain name is taken. + */ + RP_LOOKUP, + + /** + * Storing of the record. + */ + RP_PUT, + + /** + * We're done with success. + */ + RP_SUCCESS, + + /** + * Send failure message. + */ + RP_FAIL +}; /** * Data kept per request. */ -struct Request -{ - +struct Request { /** * Associated session. */ @@ -119,7 +116,7 @@ struct Request * a POST request). */ struct MHD_PostProcessor *pp; - + /** * MHD Connection */ @@ -161,14 +158,12 @@ struct Request char public_key[128]; struct GNUNET_CRYPTO_EcdsaPublicKey pub; - }; /** * Zoneinfo request */ -struct ZoneinfoRequest -{ +struct ZoneinfoRequest { /** * List iterator */ @@ -247,21 +242,21 @@ static char *zone; * @param cls unused */ static void -do_httpd (void *cls); +do_httpd(void *cls); /** * Schedule task to run MHD server now. */ static void -run_httpd_now () +run_httpd_now() { if (NULL != httpd_task) - { - GNUNET_SCHEDULER_cancel (httpd_task); - httpd_task = NULL; - } - httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd, NULL); + { + GNUNET_SCHEDULER_cancel(httpd_task); + httpd_task = NULL; + } + httpd_task = GNUNET_SCHEDULER_add_now(&do_httpd, NULL); } @@ -269,22 +264,22 @@ run_httpd_now () * Create fresh version of zone information. */ static void -update_zoneinfo_page (void *cls); +update_zoneinfo_page(void *cls); + - /** * Function called on error in zone iteration. */ static void -zone_iteration_error (void *cls) +zone_iteration_error(void *cls) { struct ZoneinfoRequest *zr = cls; zr->list_it = NULL; - GNUNET_free (zr->zoneinfo); - GNUNET_SCHEDULER_cancel (uzp_task); - uzp_task = GNUNET_SCHEDULER_add_now (&update_zoneinfo_page, - NULL); + GNUNET_free(zr->zoneinfo); + GNUNET_SCHEDULER_cancel(uzp_task); + uzp_task = GNUNET_SCHEDULER_add_now(&update_zoneinfo_page, + NULL); } @@ -292,7 +287,7 @@ zone_iteration_error (void *cls) * Function called once the zone iteration is done. */ static void -zone_iteration_end (void *cls) +zone_iteration_end(void *cls) { struct ZoneinfoRequest *zr = cls; struct MHD_Response *response; @@ -301,19 +296,19 @@ zone_iteration_end (void *cls) zr->list_it = NULL; /* return static form */ - GNUNET_asprintf (&full_page, - ZONEINFO_PAGE, - zr->zoneinfo, - zr->zoneinfo); - response = MHD_create_response_from_buffer (strlen (full_page), - (void *) full_page, - MHD_RESPMEM_MUST_FREE); - MHD_add_response_header (response, - MHD_HTTP_HEADER_CONTENT_TYPE, - MIME_HTML); - MHD_destroy_response (info_page); + GNUNET_asprintf(&full_page, + ZONEINFO_PAGE, + zr->zoneinfo, + zr->zoneinfo); + response = MHD_create_response_from_buffer(strlen(full_page), + (void *)full_page, + MHD_RESPMEM_MUST_FREE); + MHD_add_response_header(response, + MHD_HTTP_HEADER_CONTENT_TYPE, + MIME_HTML); + MHD_destroy_response(info_page); info_page = response; - GNUNET_free (zr->zoneinfo); + GNUNET_free(zr->zoneinfo); } @@ -328,59 +323,59 @@ zone_iteration_end (void *cls) * @param rd array of records with data to store */ static void -iterate_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *name, - unsigned int rd_len, - const struct GNUNET_GNSRECORD_Data *rd) +iterate_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *name, + unsigned int rd_len, + const struct GNUNET_GNSRECORD_Data *rd) { struct ZoneinfoRequest *zr = cls; size_t bytes_free; char* pkey; char* new_buf; - (void) zone_key; + (void)zone_key; if (1 != rd_len) - { - GNUNET_NAMESTORE_zone_iterator_next (zr->list_it, - 1); - return; - } + { + GNUNET_NAMESTORE_zone_iterator_next(zr->list_it, + 1); + return; + } if (GNUNET_GNSRECORD_TYPE_PKEY != rd->record_type) - { - GNUNET_NAMESTORE_zone_iterator_next (zr->list_it, - 1); - return; - } + { + GNUNET_NAMESTORE_zone_iterator_next(zr->list_it, + 1); + return; + } bytes_free = zr->buf_len - zr->write_offset; - pkey = GNUNET_GNSRECORD_value_to_string (rd->record_type, - rd->data, - rd->data_size); + pkey = GNUNET_GNSRECORD_value_to_string(rd->record_type, + rd->data, + rd->data_size); if (NULL == pkey) - { - GNUNET_break (0); - GNUNET_NAMESTORE_zone_iterator_next (zr->list_it, - 1); - return; - } - if (bytes_free < (strlen (name) + strlen (pkey) + 40)) - { - new_buf = GNUNET_malloc (zr->buf_len * 2); - GNUNET_memcpy (new_buf, zr->zoneinfo, zr->write_offset); - GNUNET_free (zr->zoneinfo); - zr->zoneinfo = new_buf; - zr->buf_len *= 2; - } - sprintf (zr->zoneinfo + zr->write_offset, - "%s%s", - name, - pkey); - zr->write_offset = strlen (zr->zoneinfo); - GNUNET_NAMESTORE_zone_iterator_next (zr->list_it, - 1); - GNUNET_free (pkey); + { + GNUNET_break(0); + GNUNET_NAMESTORE_zone_iterator_next(zr->list_it, + 1); + return; + } + if (bytes_free < (strlen(name) + strlen(pkey) + 40)) + { + new_buf = GNUNET_malloc(zr->buf_len * 2); + GNUNET_memcpy(new_buf, zr->zoneinfo, zr->write_offset); + GNUNET_free(zr->zoneinfo); + zr->zoneinfo = new_buf; + zr->buf_len *= 2; + } + sprintf(zr->zoneinfo + zr->write_offset, + "%s%s", + name, + pkey); + zr->write_offset = strlen(zr->zoneinfo); + GNUNET_NAMESTORE_zone_iterator_next(zr->list_it, + 1); + GNUNET_free(pkey); } @@ -389,12 +384,12 @@ iterate_cb (void *cls, * * @param connection connection to use */ -static int -serve_zoneinfo_page (struct MHD_Connection *connection) +static int +serve_zoneinfo_page(struct MHD_Connection *connection) { - return MHD_queue_response (connection, - MHD_HTTP_OK, - info_page); + return MHD_queue_response(connection, + MHD_HTTP_OK, + info_page); } @@ -402,27 +397,27 @@ serve_zoneinfo_page (struct MHD_Connection *connection) * Create fresh version of zone information. */ static void -update_zoneinfo_page (void *cls) -{ +update_zoneinfo_page(void *cls) +{ static struct ZoneinfoRequest zr; - (void) cls; - uzp_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, - &update_zoneinfo_page, - NULL); + (void)cls; + uzp_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES, + &update_zoneinfo_page, + NULL); if (NULL != zr.list_it) - return; - zr.zoneinfo = GNUNET_malloc (DEFAULT_ZONEINFO_BUFSIZE); + return; + zr.zoneinfo = GNUNET_malloc(DEFAULT_ZONEINFO_BUFSIZE); zr.buf_len = DEFAULT_ZONEINFO_BUFSIZE; zr.write_offset = 0; - zr.list_it = GNUNET_NAMESTORE_zone_iteration_start (ns, - &fcfs_zone_pkey, - &zone_iteration_error, - &zr, - &iterate_cb, - &zr, - &zone_iteration_end, - &zr); + zr.list_it = GNUNET_NAMESTORE_zone_iteration_start(ns, + &fcfs_zone_pkey, + &zone_iteration_error, + &zr, + &iterate_cb, + &zr, + &zone_iteration_end, + &zr); } @@ -433,22 +428,22 @@ update_zoneinfo_page (void *cls) * @return #MHD_YES on success */ static int -serve_main_page (struct MHD_Connection *connection) +serve_main_page(struct MHD_Connection *connection) { int ret; struct MHD_Response *response; /* return static form */ - response = MHD_create_response_from_buffer (strlen (MAIN_PAGE), - (void *) MAIN_PAGE, - MHD_RESPMEM_PERSISTENT); - MHD_add_response_header (response, - MHD_HTTP_HEADER_CONTENT_TYPE, - MIME_HTML); - ret = MHD_queue_response (connection, - MHD_HTTP_OK, - response); - MHD_destroy_response (response); + response = MHD_create_response_from_buffer(strlen(MAIN_PAGE), + (void *)MAIN_PAGE, + MHD_RESPMEM_PERSISTENT); + MHD_add_response_header(response, + MHD_HTTP_HEADER_CONTENT_TYPE, + MIME_HTML); + ret = MHD_queue_response(connection, + MHD_HTTP_OK, + response); + MHD_destroy_response(response); return ret; } @@ -461,30 +456,30 @@ serve_main_page (struct MHD_Connection *connection) * @param connection connection to use */ static int -fill_s_reply (const char *info, - struct Request *request, - struct MHD_Connection *connection) +fill_s_reply(const char *info, + struct Request *request, + struct MHD_Connection *connection) { int ret; char *reply; struct MHD_Response *response; - (void) request; - GNUNET_asprintf (&reply, - SUBMIT_PAGE, - info, - info); + (void)request; + GNUNET_asprintf(&reply, + SUBMIT_PAGE, + info, + info); /* return static form */ - response = MHD_create_response_from_buffer (strlen (reply), - (void *) reply, - MHD_RESPMEM_MUST_FREE); - MHD_add_response_header (response, - MHD_HTTP_HEADER_CONTENT_TYPE, - MIME_HTML); - ret = MHD_queue_response (connection, - MHD_HTTP_OK, - response); - MHD_destroy_response (response); + response = MHD_create_response_from_buffer(strlen(reply), + (void *)reply, + MHD_RESPMEM_MUST_FREE); + MHD_add_response_header(response, + MHD_HTTP_HEADER_CONTENT_TYPE, + MIME_HTML); + ret = MHD_queue_response(connection, + MHD_HTTP_OK, + response); + MHD_destroy_response(response); return ret; } @@ -509,45 +504,45 @@ fill_s_reply (const char *info, * MHD_NO to abort the iteration */ static int -post_iterator (void *cls, - enum MHD_ValueKind kind, - const char *key, - const char *filename, - const char *content_type, - const char *transfer_encoding, - const char *data, - uint64_t off, - size_t size) +post_iterator(void *cls, + enum MHD_ValueKind kind, + const char *key, + const char *filename, + const char *content_type, + const char *transfer_encoding, + const char *data, + uint64_t off, + size_t size) { struct Request *request = cls; - (void) kind; - (void) filename; - (void) content_type; - (void) transfer_encoding; - if (0 == strcmp ("domain", key)) + (void)kind; + (void)filename; + (void)content_type; + (void)transfer_encoding; + if (0 == strcmp("domain", key)) { if (size + off >= sizeof(request->domain_name)) - size = sizeof (request->domain_name) - off - 1; - GNUNET_memcpy (&request->domain_name[off], - data, - size); - request->domain_name[size+off] = '\0'; + size = sizeof(request->domain_name) - off - 1; + GNUNET_memcpy(&request->domain_name[off], + data, + size); + request->domain_name[size + off] = '\0'; return MHD_YES; } - if (0 == strcmp ("pkey", key)) + if (0 == strcmp("pkey", key)) { if (size + off >= sizeof(request->public_key)) - size = sizeof (request->public_key) - off - 1; - GNUNET_memcpy (&request->public_key[off], - data, - size); - request->public_key[size+off] = '\0'; + size = sizeof(request->public_key) - off - 1; + GNUNET_memcpy(&request->public_key[off], + data, + size); + request->public_key[size + off] = '\0'; return MHD_YES; } - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unsupported form value `%s'\n"), - key); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unsupported form value `%s'\n"), + key); return MHD_YES; } @@ -563,25 +558,25 @@ post_iterator (void *cls, * @param emsg NULL on success, otherwise an error message */ static void -put_continuation (void *cls, - int32_t success, - const char *emsg) +put_continuation(void *cls, + int32_t success, + const char *emsg) { struct Request *request = cls; request->qe = NULL; if (0 >= success) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Failed to create record for domain `%s': %s\n"), - request->domain_name, - emsg); - request->phase = RP_FAIL; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to create record for domain `%s': %s\n"), + request->domain_name, + emsg); + request->phase = RP_FAIL; + } else request->phase = RP_SUCCESS; - MHD_resume_connection (request->con); - run_httpd_now (); + MHD_resume_connection(request->con); + run_httpd_now(); } @@ -589,15 +584,15 @@ put_continuation (void *cls, * Function called if we had an error in zone-to-name mapping. */ static void -zone_to_name_error (void *cls) +zone_to_name_error(void *cls) { struct Request *request = cls; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Error when mapping zone to name\n")); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Error when mapping zone to name\n")); request->phase = RP_FAIL; - MHD_resume_connection (request->con); - run_httpd_now (); + MHD_resume_connection(request->con); + run_httpd_now(); } @@ -611,39 +606,39 @@ zone_to_name_error (void *cls) * @param rd array of records with data to store */ static void -zone_to_name_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *name, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +zone_to_name_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *name, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct Request *request = cls; struct GNUNET_GNSRECORD_Data r; - (void) rd; - (void) zone_key; + (void)rd; + (void)zone_key; request->qe = NULL; if (0 != rd_count) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Found existing name `%s' for the given key\n"), - name); - request->phase = RP_FAIL; - MHD_resume_connection (request->con); - run_httpd_now (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Found existing name `%s' for the given key\n"), + name); + request->phase = RP_FAIL; + MHD_resume_connection(request->con); + run_httpd_now(); + return; + } r.data = &request->pub; - r.data_size = sizeof (request->pub); + r.data_size = sizeof(request->pub); r.expiration_time = UINT64_MAX; r.record_type = GNUNET_GNSRECORD_TYPE_PKEY; r.flags = GNUNET_GNSRECORD_RF_NONE; - request->qe = GNUNET_NAMESTORE_records_store (ns, - &fcfs_zone_pkey, - request->domain_name, - 1, &r, - &put_continuation, - request); + request->qe = GNUNET_NAMESTORE_records_store(ns, + &fcfs_zone_pkey, + request->domain_name, + 1, &r, + &put_continuation, + request); } @@ -651,13 +646,14 @@ zone_to_name_cb (void *cls, * We encountered an error in the name lookup. */ static void -lookup_it_error (void *cls) +lookup_it_error(void *cls) { struct Request *request = cls; - MHD_resume_connection (request->con); + + MHD_resume_connection(request->con); request->qe = NULL; request->phase = RP_FAIL; - run_httpd_now (); + run_httpd_now(); } @@ -672,57 +668,58 @@ lookup_it_error (void *cls) * @param rd array of records with data to store */ static void -lookup_it_processor (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zonekey, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +lookup_it_processor(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zonekey, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct Request *request = cls; - (void) label; - (void) rd; - (void) zonekey; - if (0 == strcmp (label, request->domain_name)) { - GNUNET_break (0 != rd_count); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Found %u existing records for domain `%s'\n"), - rd_count, - request->domain_name); - request->phase = RP_FAIL; - } - GNUNET_NAMESTORE_zone_iterator_next (request->lookup_it, 1); + (void)label; + (void)rd; + (void)zonekey; + if (0 == strcmp(label, request->domain_name)) + { + GNUNET_break(0 != rd_count); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Found %u existing records for domain `%s'\n"), + rd_count, + request->domain_name); + request->phase = RP_FAIL; + } + GNUNET_NAMESTORE_zone_iterator_next(request->lookup_it, 1); } static void -lookup_it_finished (void *cls) +lookup_it_finished(void *cls) { struct Request *request = cls; - + if (RP_FAIL == request->phase) - { - MHD_resume_connection (request->con); - run_httpd_now (); - return; - } + { + MHD_resume_connection(request->con); + run_httpd_now(); + return; + } if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (request->public_key, - strlen (request->public_key), - &request->pub)) - { - GNUNET_break (0); - request->phase = RP_FAIL; - MHD_resume_connection (request->con); - run_httpd_now (); - return; - } - request->qe = GNUNET_NAMESTORE_zone_to_name (ns, - &fcfs_zone_pkey, - &request->pub, - &zone_to_name_error, - request, - &zone_to_name_cb, - request); + GNUNET_CRYPTO_ecdsa_public_key_from_string(request->public_key, + strlen(request->public_key), + &request->pub)) + { + GNUNET_break(0); + request->phase = RP_FAIL; + MHD_resume_connection(request->con); + run_httpd_now(); + return; + } + request->qe = GNUNET_NAMESTORE_zone_to_name(ns, + &fcfs_zone_pkey, + &request->pub, + &zone_to_name_error, + request, + &zone_to_name_cb, + request); } /** @@ -749,136 +746,141 @@ lookup_it_finished (void *cls) * error while handling the request */ static int -create_response (void *cls, - struct MHD_Connection *connection, - const char *url, - const char *method, - const char *version, - const char *upload_data, - size_t *upload_data_size, - void **ptr) +create_response(void *cls, + struct MHD_Connection *connection, + const char *url, + const char *method, + const char *version, + const char *upload_data, + size_t *upload_data_size, + void **ptr) { struct MHD_Response *response; struct Request *request; struct GNUNET_CRYPTO_EcdsaPublicKey pub; int ret; - (void) cls; - (void) version; - if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) || - (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) ) - { - if (0 == strcmp (url, FCFS_ZONEINFO_URL)) - ret = serve_zoneinfo_page (connection); - else - ret = serve_main_page (connection); - if (ret != MHD_YES) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to create page for `%s'\n"), - url); - return ret; - } - if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) - { - request = *ptr; - if (NULL == request) + (void)cls; + (void)version; + if ((0 == strcmp(method, MHD_HTTP_METHOD_GET)) || + (0 == strcmp(method, MHD_HTTP_METHOD_HEAD))) { - request = GNUNET_new (struct Request); - request->con = connection; - *ptr = request; - request->pp = MHD_create_post_processor (connection, - 1024, - &post_iterator, - request); - if (NULL == request->pp) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to setup post processor for `%s'\n"), - url); - return MHD_NO; /* internal error */ - } - return MHD_YES; - } - if (NULL != request->pp) - { - /* evaluate POST data */ - MHD_post_process (request->pp, - upload_data, - *upload_data_size); - if (0 != *upload_data_size) - { - *upload_data_size = 0; - return MHD_YES; - } - /* done with POST data, serve response */ - MHD_destroy_post_processor (request->pp); - request->pp = NULL; + if (0 == strcmp(url, FCFS_ZONEINFO_URL)) + ret = serve_zoneinfo_page(connection); + else + ret = serve_main_page(connection); + if (ret != MHD_YES) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to create page for `%s'\n"), + url); + return ret; } - if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (request->public_key, - strlen (request->public_key), - &pub)) + if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) { - /* parse error */ - return fill_s_reply ("Failed to parse given public key", - request, connection); - } - switch (request->phase) - { - case RP_START: - if (NULL != strchr (request->domain_name, (int) '.')) + request = *ptr; + if (NULL == request) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Domain name must not contain `.'\n")); - request->phase = RP_FAIL; - return fill_s_reply ("Domain name must not contain `.', sorry.", - request, - connection); + request = GNUNET_new(struct Request); + request->con = connection; + *ptr = request; + request->pp = MHD_create_post_processor(connection, + 1024, + &post_iterator, + request); + if (NULL == request->pp) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to setup post processor for `%s'\n"), + url); + return MHD_NO; /* internal error */ + } + return MHD_YES; } - if (NULL != strchr (request->domain_name, (int) '+')) + if (NULL != request->pp) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Domain name must not contain `+'\n")); - request->phase = RP_FAIL; - return fill_s_reply ("Domain name must not contain `+', sorry.", - request, connection); + /* evaluate POST data */ + MHD_post_process(request->pp, + upload_data, + *upload_data_size); + if (0 != *upload_data_size) + { + *upload_data_size = 0; + return MHD_YES; + } + /* done with POST data, serve response */ + MHD_destroy_post_processor(request->pp); + request->pp = NULL; } - request->phase = RP_LOOKUP; - MHD_suspend_connection (request->con); - request->lookup_it - = GNUNET_NAMESTORE_zone_iteration_start (ns, - &fcfs_zone_pkey, - &lookup_it_error, - request, - &lookup_it_processor, - request, - &lookup_it_finished, - request); - break; - case RP_LOOKUP: - break; - case RP_PUT: - break; - case RP_FAIL: - return fill_s_reply ("Request failed, sorry.", - request, connection); - case RP_SUCCESS: - return fill_s_reply ("Success.", - request, connection); - default: - GNUNET_break (0); - return MHD_NO; + if (GNUNET_OK != + GNUNET_CRYPTO_ecdsa_public_key_from_string(request->public_key, + strlen(request->public_key), + &pub)) + { + /* parse error */ + return fill_s_reply("Failed to parse given public key", + request, connection); + } + switch (request->phase) + { + case RP_START: + if (NULL != strchr(request->domain_name, (int)'.')) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Domain name must not contain `.'\n")); + request->phase = RP_FAIL; + return fill_s_reply("Domain name must not contain `.', sorry.", + request, + connection); + } + if (NULL != strchr(request->domain_name, (int)'+')) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Domain name must not contain `+'\n")); + request->phase = RP_FAIL; + return fill_s_reply("Domain name must not contain `+', sorry.", + request, connection); + } + request->phase = RP_LOOKUP; + MHD_suspend_connection(request->con); + request->lookup_it + = GNUNET_NAMESTORE_zone_iteration_start(ns, + &fcfs_zone_pkey, + &lookup_it_error, + request, + &lookup_it_processor, + request, + &lookup_it_finished, + request); + break; + + case RP_LOOKUP: + break; + + case RP_PUT: + break; + + case RP_FAIL: + return fill_s_reply("Request failed, sorry.", + request, connection); + + case RP_SUCCESS: + return fill_s_reply("Success.", + request, connection); + + default: + GNUNET_break(0); + return MHD_NO; + } + return MHD_YES; /* will have a reply later... */ } - return MHD_YES; /* will have a reply later... */ - } /* unsupported HTTP method */ - response = MHD_create_response_from_buffer (strlen (METHOD_ERROR), - (void *) METHOD_ERROR, - MHD_RESPMEM_PERSISTENT); - ret = MHD_queue_response (connection, - MHD_HTTP_NOT_ACCEPTABLE, - response); - MHD_destroy_response (response); + response = MHD_create_response_from_buffer(strlen(METHOD_ERROR), + (void *)METHOD_ERROR, + MHD_RESPMEM_PERSISTENT); + ret = MHD_queue_response(connection, + MHD_HTTP_NOT_ACCEPTABLE, + response); + MHD_destroy_response(response); return ret; } @@ -893,23 +895,23 @@ create_response (void *cls, * @param toe status code */ static void -request_completed_callback (void *cls, - struct MHD_Connection *connection, - void **con_cls, - enum MHD_RequestTerminationCode toe) +request_completed_callback(void *cls, + struct MHD_Connection *connection, + void **con_cls, + enum MHD_RequestTerminationCode toe) { struct Request *request = *con_cls; - (void) cls; - (void) connection; - (void) toe; + (void)cls; + (void)connection; + (void)toe; if (NULL == request) return; if (NULL != request->pp) - MHD_destroy_post_processor (request->pp); + MHD_destroy_post_processor(request->pp); if (NULL != request->qe) - GNUNET_NAMESTORE_cancel (request->qe); - GNUNET_free (request); + GNUNET_NAMESTORE_cancel(request->qe); + GNUNET_free(request); } @@ -920,7 +922,7 @@ request_completed_callback (void *cls, * Schedule tasks to run MHD server. */ static void -run_httpd () +run_httpd() { fd_set rs; fd_set ws; @@ -933,44 +935,44 @@ run_httpd () UNSIGNED_MHD_LONG_LONG timeout; struct GNUNET_TIME_Relative tv; - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); - wrs = GNUNET_NETWORK_fdset_create (); - wes = GNUNET_NETWORK_fdset_create (); - wws = GNUNET_NETWORK_fdset_create (); + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); + wrs = GNUNET_NETWORK_fdset_create(); + wes = GNUNET_NETWORK_fdset_create(); + wws = GNUNET_NETWORK_fdset_create(); max = -1; - GNUNET_assert (MHD_YES == - MHD_get_fdset (httpd, - &rs, - &ws, - &es, - &max)); - haveto = MHD_get_timeout (httpd, - &timeout); + GNUNET_assert(MHD_YES == + MHD_get_fdset(httpd, + &rs, + &ws, + &es, + &max)); + haveto = MHD_get_timeout(httpd, + &timeout); if (haveto == MHD_YES) - tv.rel_value_us = (uint64_t) timeout * 1000LL; + tv.rel_value_us = (uint64_t)timeout * 1000LL; else tv = GNUNET_TIME_UNIT_FOREVER_REL; - GNUNET_NETWORK_fdset_copy_native (wrs, - &rs, - max + 1); - GNUNET_NETWORK_fdset_copy_native (wws, - &ws, - max + 1); - GNUNET_NETWORK_fdset_copy_native (wes, - &es, - max + 1); + GNUNET_NETWORK_fdset_copy_native(wrs, + &rs, + max + 1); + GNUNET_NETWORK_fdset_copy_native(wws, + &ws, + max + 1); + GNUNET_NETWORK_fdset_copy_native(wes, + &es, + max + 1); httpd_task = - GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_HIGH, - tv, - wrs, - wws, - &do_httpd, - NULL); - GNUNET_NETWORK_fdset_destroy (wrs); - GNUNET_NETWORK_fdset_destroy (wws); - GNUNET_NETWORK_fdset_destroy (wes); + GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_HIGH, + tv, + wrs, + wws, + &do_httpd, + NULL); + GNUNET_NETWORK_fdset_destroy(wrs); + GNUNET_NETWORK_fdset_destroy(wws); + GNUNET_NETWORK_fdset_destroy(wes); } @@ -980,12 +982,12 @@ run_httpd () * @param cls unused */ static void -do_httpd (void *cls) +do_httpd(void *cls) { - (void) cls; + (void)cls; httpd_task = NULL; - MHD_run (httpd); - run_httpd (); + MHD_run(httpd); + run_httpd(); } @@ -995,39 +997,39 @@ do_httpd (void *cls) * @param cls unused */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - (void) cls; + (void)cls; if (NULL != httpd_task) - { - GNUNET_SCHEDULER_cancel (httpd_task); - httpd_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(httpd_task); + httpd_task = NULL; + } if (NULL != uzp_task) - { - GNUNET_SCHEDULER_cancel (uzp_task); - uzp_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(uzp_task); + uzp_task = NULL; + } if (NULL != ns) - { - GNUNET_NAMESTORE_disconnect (ns); - ns = NULL; - } + { + GNUNET_NAMESTORE_disconnect(ns); + ns = NULL; + } if (NULL != httpd) - { - MHD_stop_daemon (httpd); - httpd = NULL; - } + { + MHD_stop_daemon(httpd); + httpd = NULL; + } if (NULL != id_op) - { - GNUNET_IDENTITY_cancel (id_op); - id_op = NULL; - } + { + GNUNET_IDENTITY_cancel(id_op); + id_op = NULL; + } if (NULL != identity) - { - GNUNET_IDENTITY_disconnect (identity); - identity = NULL; - } + { + GNUNET_IDENTITY_disconnect(identity); + identity = NULL; + } } @@ -1051,56 +1053,55 @@ do_shutdown (void *cls) * must thus no longer be used */ static void -identity_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +identity_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { int options; - (void) cls; - (void) ctx; + (void)cls; + (void)ctx; if (NULL == name) return; - if (0 != strcmp (name, - zone)) + if (0 != strcmp(name, + zone)) return; if (NULL == ego) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No ego configured for `fcfsd` subsystem\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } - fcfs_zone_pkey = *GNUNET_IDENTITY_ego_get_private_key (ego); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No ego configured for `fcfsd` subsystem\n")); + GNUNET_SCHEDULER_shutdown(); + return; + } + fcfs_zone_pkey = *GNUNET_IDENTITY_ego_get_private_key(ego); options = MHD_USE_DUAL_STACK | MHD_USE_DEBUG | MHD_ALLOW_SUSPEND_RESUME; do - { - httpd = MHD_start_daemon (options, - (uint16_t) port, - NULL, NULL, - &create_response, NULL, - MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 128, - MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int) 1, - MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 16, - MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t) (4 * 1024), - MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL, - MHD_OPTION_END); - if (MHD_USE_DEBUG == options) - break; - options = MHD_USE_DEBUG; - } + { + httpd = MHD_start_daemon(options, + (uint16_t)port, + NULL, NULL, + &create_response, NULL, + MHD_OPTION_CONNECTION_LIMIT, (unsigned int)128, + MHD_OPTION_PER_IP_CONNECTION_LIMIT, (unsigned int)1, + MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int)16, + MHD_OPTION_CONNECTION_MEMORY_LIMIT, (size_t)(4 * 1024), + MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL, + MHD_OPTION_END); + if (MHD_USE_DEBUG == options) + break; + options = MHD_USE_DEBUG; + } while (NULL == httpd); if (NULL == httpd) - { - - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to start HTTP server\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } - run_httpd (); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to start HTTP server\n")); + GNUNET_SCHEDULER_shutdown(); + return; + } + run_httpd(); } @@ -1113,44 +1114,44 @@ identity_cb (void *cls, * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - (void) cls; - (void) args; - (void) cfgfile; + (void)cls; + (void)args; + (void)cfgfile; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (cfg, - "fcfsd", - "HTTPPORT", - &port)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "fcfsd", "HTTPPORT"); - return; - } - ns = GNUNET_NAMESTORE_connect (cfg); + GNUNET_CONFIGURATION_get_value_number(cfg, + "fcfsd", + "HTTPPORT", + &port)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "fcfsd", "HTTPPORT"); + return; + } + ns = GNUNET_NAMESTORE_connect(cfg); if (NULL == ns) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect to namestore\n")); - return; - } - identity = GNUNET_IDENTITY_connect (cfg, - &identity_cb, - NULL); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to namestore\n")); + return; + } + identity = GNUNET_IDENTITY_connect(cfg, + &identity_cb, + NULL); if (NULL == identity) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect to identity\n")); - return; - } - uzp_task = GNUNET_SCHEDULER_add_now (&update_zoneinfo_page, - NULL); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to identity\n")); + return; + } + uzp_task = GNUNET_SCHEDULER_add_now(&update_zoneinfo_page, + NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); } @@ -1162,38 +1163,38 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, - char *const *argv) +main(int argc, + char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_option_mandatory - (GNUNET_GETOPT_option_string ('z', - "zone", - "EGO", - gettext_noop ("name of the zone that is to be managed by FCFSD"), - &zone)), + GNUNET_GETOPT_option_mandatory + (GNUNET_GETOPT_option_string('z', + "zone", + "EGO", + gettext_noop("name of the zone that is to be managed by FCFSD"), + &zone)), GNUNET_GETOPT_OPTION_END }; int ret; if (GNUNET_OK != - GNUNET_STRINGS_get_utf8_args (argc, argv, - &argc, &argv)) + GNUNET_STRINGS_get_utf8_args(argc, argv, + &argc, &argv)) return 2; - GNUNET_log_setup ("fcfsd", - "WARNING", - NULL); + GNUNET_log_setup("fcfsd", + "WARNING", + NULL); ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-namestore-fcfsd", - _("GNU Name System First Come First Serve name registration service"), - options, - &run, NULL)) ? 0 : 1; - GNUNET_free ((void*) argv); - GNUNET_CRYPTO_ecdsa_key_clear (&fcfs_zone_pkey); + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-namestore-fcfsd", + _("GNU Name System First Come First Serve name registration service"), + options, + &run, NULL)) ? 0 : 1; + GNUNET_free((void*)argv); + GNUNET_CRYPTO_ecdsa_key_clear(&fcfs_zone_pkey); return ret; } diff --git a/src/namestore/gnunet-namestore.c b/src/namestore/gnunet-namestore.c index 2b814206b..cc1362a51 100644 --- a/src/namestore/gnunet-namestore.c +++ b/src/namestore/gnunet-namestore.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file gnunet-namestore.c * @brief command line tool to manipulate the local zone @@ -37,8 +37,7 @@ /** * Entry in record set for bulk processing. */ -struct RecordSetEntry -{ +struct RecordSetEntry { /** * Kept in a linked list. */ @@ -228,75 +227,75 @@ static struct RecordSetEntry *recordset; * @param cls unused */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - (void) cls; + (void)cls; if (NULL != get_default) - { - GNUNET_IDENTITY_cancel (get_default); - get_default = NULL; - } + { + GNUNET_IDENTITY_cancel(get_default); + get_default = NULL; + } if (NULL != idh) - { - GNUNET_IDENTITY_disconnect (idh); - idh = NULL; - } + { + GNUNET_IDENTITY_disconnect(idh); + idh = NULL; + } if (NULL != el) - { - GNUNET_IDENTITY_ego_lookup_cancel (el); - el = NULL; - } + { + GNUNET_IDENTITY_ego_lookup_cancel(el); + el = NULL; + } if (NULL != list_it) - { - GNUNET_NAMESTORE_zone_iteration_stop (list_it); - list_it = NULL; - } + { + GNUNET_NAMESTORE_zone_iteration_stop(list_it); + list_it = NULL; + } if (NULL != add_qe) - { - GNUNET_NAMESTORE_cancel (add_qe); - add_qe = NULL; - } + { + GNUNET_NAMESTORE_cancel(add_qe); + add_qe = NULL; + } if (NULL != set_qe) - { - GNUNET_NAMESTORE_cancel (set_qe); - set_qe = NULL; - } + { + GNUNET_NAMESTORE_cancel(set_qe); + set_qe = NULL; + } if (NULL != add_qe_uri) - { - GNUNET_NAMESTORE_cancel (add_qe_uri); - add_qe_uri = NULL; - } + { + GNUNET_NAMESTORE_cancel(add_qe_uri); + add_qe_uri = NULL; + } if (NULL != get_qe) - { - GNUNET_NAMESTORE_cancel (get_qe); - get_qe = NULL; - } + { + GNUNET_NAMESTORE_cancel(get_qe); + get_qe = NULL; + } if (NULL != del_qe) - { - GNUNET_NAMESTORE_cancel (del_qe); - del_qe = NULL; - } + { + GNUNET_NAMESTORE_cancel(del_qe); + del_qe = NULL; + } if (NULL != ns) - { - GNUNET_NAMESTORE_disconnect (ns); - ns = NULL; - } - memset (&zone_pkey, 0, sizeof (zone_pkey)); + { + GNUNET_NAMESTORE_disconnect(ns); + ns = NULL; + } + memset(&zone_pkey, 0, sizeof(zone_pkey)); if (NULL != uri) - { - GNUNET_free (uri); - uri = NULL; - } + { + GNUNET_free(uri); + uri = NULL; + } if (NULL != zm) - { - GNUNET_NAMESTORE_zone_monitor_stop (zm); - zm = NULL; - } + { + GNUNET_NAMESTORE_zone_monitor_stop(zm); + zm = NULL; + } if (NULL != data) - { - GNUNET_free (data); - data = NULL; - } + { + GNUNET_free(data); + data = NULL; + } } @@ -304,11 +303,11 @@ do_shutdown (void *cls) * Check if we are finished, and if so, perform shutdown. */ static void -test_finished () +test_finished() { if ((NULL == add_qe) && (NULL == add_qe_uri) && (NULL == get_qe) && (NULL == del_qe) && (NULL == reverse_qe) && (NULL == list_it)) - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -323,21 +322,21 @@ test_finished () * @param emsg NULL on success, otherwise an error message */ static void -add_continuation (void *cls, int32_t success, const char *emsg) +add_continuation(void *cls, int32_t success, const char *emsg) { struct GNUNET_NAMESTORE_QueueEntry **qe = cls; *qe = NULL; if (GNUNET_YES != success) - { - fprintf (stderr, - _ ("Adding record failed: %s\n"), - (GNUNET_NO == success) ? "record exists" : emsg); - if (GNUNET_NO != success) - ret = 1; - } + { + fprintf(stderr, + _("Adding record failed: %s\n"), + (GNUNET_NO == success) ? "record exists" : emsg); + if (GNUNET_NO != success) + ret = 1; + } ret = 0; - test_finished (); + test_finished(); } @@ -352,25 +351,25 @@ add_continuation (void *cls, int32_t success, const char *emsg) * @param emsg NULL on success, otherwise an error message */ static void -del_continuation (void *cls, int32_t success, const char *emsg) +del_continuation(void *cls, int32_t success, const char *emsg) { - (void) cls; + (void)cls; del_qe = NULL; if (GNUNET_NO == success) - { - fprintf (stderr, - _ ("Deleting record failed, record does not exist%s%s\n"), - (NULL != emsg) ? ": " : "", - (NULL != emsg) ? emsg : ""); - } + { + fprintf(stderr, + _("Deleting record failed, record does not exist%s%s\n"), + (NULL != emsg) ? ": " : "", + (NULL != emsg) ? emsg : ""); + } if (GNUNET_SYSERR == success) - { - fprintf (stderr, - _ ("Deleting record failed%s%s\n"), - (NULL != emsg) ? ": " : "", - (NULL != emsg) ? emsg : ""); - } - test_finished (); + { + fprintf(stderr, + _("Deleting record failed%s%s\n"), + (NULL != emsg) ? ": " : "", + (NULL != emsg) ? emsg : ""); + } + test_finished(); } @@ -378,11 +377,11 @@ del_continuation (void *cls, int32_t success, const char *emsg) * Function called when we are done with a zone iteration. */ static void -zone_iteration_finished (void *cls) +zone_iteration_finished(void *cls) { - (void) cls; + (void)cls; list_it = NULL; - test_finished (); + test_finished(); } @@ -390,13 +389,13 @@ zone_iteration_finished (void *cls) * Function called when we encountered an error in a zone iteration. */ static void -zone_iteration_error_cb (void *cls) +zone_iteration_error_cb(void *cls) { - (void) cls; + (void)cls; list_it = NULL; - fprintf (stderr, "Error iterating over zone\n"); + fprintf(stderr, "Error iterating over zone\n"); ret = 1; - test_finished (); + test_finished(); } @@ -408,9 +407,9 @@ zone_iteration_error_cb (void *cls) * @param rd array of records with data to store */ static void -display_record (const char *rname, - unsigned int rd_len, - const struct GNUNET_GNSRECORD_Data *rd) +display_record(const char *rname, + unsigned int rd_len, + const struct GNUNET_GNSRECORD_Data *rd) { const char *typestr; char *s; @@ -419,69 +418,69 @@ display_record (const char *rname, struct GNUNET_TIME_Relative rt; int have_record; - if ((NULL != name) && (0 != strcmp (name, rname))) - { - GNUNET_NAMESTORE_zone_iterator_next (list_it, 1); - return; - } + if ((NULL != name) && (0 != strcmp(name, rname))) + { + GNUNET_NAMESTORE_zone_iterator_next(list_it, 1); + return; + } have_record = GNUNET_NO; for (unsigned int i = 0; i < rd_len; i++) - { - if ((GNUNET_GNSRECORD_TYPE_NICK == rd[i].record_type) && - (0 != strcmp (rname, GNUNET_GNS_EMPTY_LABEL_AT))) - continue; - if ((type != rd[i].record_type) && (GNUNET_GNSRECORD_TYPE_ANY != type)) - continue; - have_record = GNUNET_YES; - break; - } + { + if ((GNUNET_GNSRECORD_TYPE_NICK == rd[i].record_type) && + (0 != strcmp(rname, GNUNET_GNS_EMPTY_LABEL_AT))) + continue; + if ((type != rd[i].record_type) && (GNUNET_GNSRECORD_TYPE_ANY != type)) + continue; + have_record = GNUNET_YES; + break; + } if (GNUNET_NO == have_record) return; - fprintf (stdout, "%s:\n", rname); + fprintf(stdout, "%s:\n", rname); if (NULL != typestring) - type = GNUNET_GNSRECORD_typename_to_number (typestring); + type = GNUNET_GNSRECORD_typename_to_number(typestring); else type = GNUNET_GNSRECORD_TYPE_ANY; for (unsigned int i = 0; i < rd_len; i++) - { - if ((GNUNET_GNSRECORD_TYPE_NICK == rd[i].record_type) && - (0 != strcmp (rname, GNUNET_GNS_EMPTY_LABEL_AT))) - continue; - if ((type != rd[i].record_type) && (GNUNET_GNSRECORD_TYPE_ANY != type)) - continue; - typestr = GNUNET_GNSRECORD_number_to_typename (rd[i].record_type); - s = GNUNET_GNSRECORD_value_to_string (rd[i].record_type, - rd[i].data, - rd[i].data_size); - if (NULL == s) { - fprintf (stdout, - _ ("\tCorrupt or unsupported record of type %u\n"), - (unsigned int) rd[i].record_type); - continue; + if ((GNUNET_GNSRECORD_TYPE_NICK == rd[i].record_type) && + (0 != strcmp(rname, GNUNET_GNS_EMPTY_LABEL_AT))) + continue; + if ((type != rd[i].record_type) && (GNUNET_GNSRECORD_TYPE_ANY != type)) + continue; + typestr = GNUNET_GNSRECORD_number_to_typename(rd[i].record_type); + s = GNUNET_GNSRECORD_value_to_string(rd[i].record_type, + rd[i].data, + rd[i].data_size); + if (NULL == s) + { + fprintf(stdout, + _("\tCorrupt or unsupported record of type %u\n"), + (unsigned int)rd[i].record_type); + continue; + } + if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) + { + rt.rel_value_us = rd[i].expiration_time; + ets = GNUNET_STRINGS_relative_time_to_string(rt, GNUNET_YES); + } + else + { + at.abs_value_us = rd[i].expiration_time; + ets = GNUNET_STRINGS_absolute_time_to_string(at); + } + fprintf(stdout, + "\t%s: %s (%s)\t%s\t%s\n", + typestr, + s, + ets, + (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_PRIVATE)) ? "PRIVATE" + : "PUBLIC", + (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_SHADOW_RECORD)) ? "SHADOW" + : ""); + GNUNET_free(s); } - if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) - { - rt.rel_value_us = rd[i].expiration_time; - ets = GNUNET_STRINGS_relative_time_to_string (rt, GNUNET_YES); - } - else - { - at.abs_value_us = rd[i].expiration_time; - ets = GNUNET_STRINGS_absolute_time_to_string (at); - } - fprintf (stdout, - "\t%s: %s (%s)\t%s\t%s\n", - typestr, - s, - ets, - (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_PRIVATE)) ? "PRIVATE" - : "PUBLIC", - (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_SHADOW_RECORD)) ? "SHADOW" - : ""); - GNUNET_free (s); - } - fprintf (stdout, "%s", "\n"); + fprintf(stdout, "%s", "\n"); } @@ -495,16 +494,16 @@ display_record (const char *rname, * @param rd array of records with data to store */ static void -display_record_iterator (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *rname, - unsigned int rd_len, - const struct GNUNET_GNSRECORD_Data *rd) +display_record_iterator(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *rname, + unsigned int rd_len, + const struct GNUNET_GNSRECORD_Data *rd) { - (void) cls; - (void) zone_key; - display_record (rname, rd_len, rd); - GNUNET_NAMESTORE_zone_iterator_next (list_it, 1); + (void)cls; + (void)zone_key; + display_record(rname, rd_len, rd); + GNUNET_NAMESTORE_zone_iterator_next(list_it, 1); } @@ -518,16 +517,16 @@ display_record_iterator (void *cls, * @param rd array of records with data to store */ static void -display_record_monitor (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *rname, - unsigned int rd_len, - const struct GNUNET_GNSRECORD_Data *rd) +display_record_monitor(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *rname, + unsigned int rd_len, + const struct GNUNET_GNSRECORD_Data *rd) { - (void) cls; - (void) zone_key; - display_record (rname, rd_len, rd); - GNUNET_NAMESTORE_zone_monitor_next (zm, 1); + (void)cls; + (void)zone_key; + display_record(rname, rd_len, rd); + GNUNET_NAMESTORE_zone_monitor_next(zm, 1); } @@ -541,17 +540,17 @@ display_record_monitor (void *cls, * @param rd array of records with data to store */ static void -display_record_lookup (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *rname, - unsigned int rd_len, - const struct GNUNET_GNSRECORD_Data *rd) +display_record_lookup(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *rname, + unsigned int rd_len, + const struct GNUNET_GNSRECORD_Data *rd) { - (void) cls; - (void) zone_key; + (void)cls; + (void)zone_key; get_qe = NULL; - display_record (rname, rd_len, rd); - test_finished (); + display_record(rname, rd_len, rd); + test_finished(); } @@ -561,10 +560,10 @@ display_record_lookup (void *cls, * @param cls NULL */ static void -sync_cb (void *cls) +sync_cb(void *cls) { - (void) cls; - fprintf (stdout, "%s", "Monitor is now in sync.\n"); + (void)cls; + fprintf(stdout, "%s", "Monitor is now in sync.\n"); } @@ -574,10 +573,10 @@ sync_cb (void *cls) * @param cls NULL */ static void -monitor_error_cb (void *cls) +monitor_error_cb(void *cls) { - (void) cls; - fprintf (stderr, "%s", "Monitor disconnected and out of sync.\n"); + (void)cls; + fprintf(stderr, "%s", "Monitor disconnected and out of sync.\n"); } @@ -587,12 +586,12 @@ monitor_error_cb (void *cls) * @param cls NULL */ static void -lookup_error_cb (void *cls) +lookup_error_cb(void *cls) { - (void) cls; + (void)cls; get_qe = NULL; - fprintf (stderr, "%s", "Failed to lookup record.\n"); - test_finished (); + fprintf(stderr, "%s", "Failed to lookup record.\n"); + test_finished(); } @@ -600,13 +599,13 @@ lookup_error_cb (void *cls) * Function called if lookup fails. */ static void -add_error_cb (void *cls) +add_error_cb(void *cls) { - (void) cls; + (void)cls; add_qe = NULL; - GNUNET_break (0); + GNUNET_break(0); ret = 1; - test_finished (); + test_finished(); } @@ -621,114 +620,118 @@ add_error_cb (void *cls) * @param rd array of records with data to store */ static void -get_existing_record (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *rec_name, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +get_existing_record(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *rec_name, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_GNSRECORD_Data rdn[rd_count + 1]; struct GNUNET_GNSRECORD_Data *rde; - (void) cls; - (void) zone_key; + (void)cls; + (void)zone_key; add_qe = NULL; - if (0 != strcmp (rec_name, name)) - { - GNUNET_break (0); - ret = 1; - test_finished (); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received %u records for name `%s'\n", - rd_count, - rec_name); - for (unsigned int i = 0; i < rd_count; i++) - { - switch (rd[i].record_type) + if (0 != strcmp(rec_name, name)) { - case GNUNET_DNSPARSER_TYPE_CNAME: - fprintf ( - stderr, - _ ( - "A %s record exists already under `%s', no other records can be added.\n"), - "CNAME", - rec_name); + GNUNET_break(0); ret = 1; - test_finished (); + test_finished(); return; - case GNUNET_GNSRECORD_TYPE_PKEY: - fprintf ( - stderr, - _ ( - "A %s record exists already under `%s', no other records can be added.\n"), - "PKEY", - rec_name); - ret = 1; - test_finished (); - return; - case GNUNET_DNSPARSER_TYPE_SOA: - if (GNUNET_DNSPARSER_TYPE_SOA == type) - { - fprintf ( - stderr, - _ ( - "A SOA record exists already under `%s', cannot add a second SOA to the same zone.\n"), - rec_name); - ret = 1; - test_finished (); - return; - } - break; } - } - switch (type) - { - case GNUNET_DNSPARSER_TYPE_CNAME: - if (0 != rd_count) + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received %u records for name `%s'\n", + rd_count, + rec_name); + for (unsigned int i = 0; i < rd_count; i++) { - fprintf (stderr, - _ ( - "Records already exist under `%s', cannot add `%s' record.\n"), - rec_name, - "CNAME"); - ret = 1; - test_finished (); - return; + switch (rd[i].record_type) + { + case GNUNET_DNSPARSER_TYPE_CNAME: + fprintf( + stderr, + _( + "A %s record exists already under `%s', no other records can be added.\n"), + "CNAME", + rec_name); + ret = 1; + test_finished(); + return; + + case GNUNET_GNSRECORD_TYPE_PKEY: + fprintf( + stderr, + _( + "A %s record exists already under `%s', no other records can be added.\n"), + "PKEY", + rec_name); + ret = 1; + test_finished(); + return; + + case GNUNET_DNSPARSER_TYPE_SOA: + if (GNUNET_DNSPARSER_TYPE_SOA == type) + { + fprintf( + stderr, + _( + "A SOA record exists already under `%s', cannot add a second SOA to the same zone.\n"), + rec_name); + ret = 1; + test_finished(); + return; + } + break; + } } - break; - case GNUNET_GNSRECORD_TYPE_PKEY: - if (0 != rd_count) + switch (type) { - fprintf (stderr, - _ ( - "Records already exist under `%s', cannot add `%s' record.\n"), - rec_name, - "PKEY"); - ret = 1; - test_finished (); - return; + case GNUNET_DNSPARSER_TYPE_CNAME: + if (0 != rd_count) + { + fprintf(stderr, + _( + "Records already exist under `%s', cannot add `%s' record.\n"), + rec_name, + "CNAME"); + ret = 1; + test_finished(); + return; + } + break; + + case GNUNET_GNSRECORD_TYPE_PKEY: + if (0 != rd_count) + { + fprintf(stderr, + _( + "Records already exist under `%s', cannot add `%s' record.\n"), + rec_name, + "PKEY"); + ret = 1; + test_finished(); + return; + } + break; + + case GNUNET_GNSRECORD_TYPE_GNS2DNS: + for (unsigned int i = 0; i < rd_count; i++) + if (GNUNET_GNSRECORD_TYPE_GNS2DNS != rd[i].record_type) + { + fprintf( + stderr, + _( + "Non-GNS2DNS records already exist under `%s', cannot add GNS2DNS record.\n"), + rec_name); + ret = 1; + test_finished(); + return; + } + break; } - break; - case GNUNET_GNSRECORD_TYPE_GNS2DNS: - for (unsigned int i = 0; i < rd_count; i++) - if (GNUNET_GNSRECORD_TYPE_GNS2DNS != rd[i].record_type) - { - fprintf ( - stderr, - _ ( - "Non-GNS2DNS records already exist under `%s', cannot add GNS2DNS record.\n"), - rec_name); - ret = 1; - test_finished (); - return; - } - break; - } - memset (rdn, 0, sizeof (struct GNUNET_GNSRECORD_Data)); - GNUNET_memcpy (&rdn[1], rd, rd_count * sizeof (struct GNUNET_GNSRECORD_Data)); + memset(rdn, 0, sizeof(struct GNUNET_GNSRECORD_Data)); + GNUNET_memcpy(&rdn[1], rd, rd_count * sizeof(struct GNUNET_GNSRECORD_Data)); rde = &rdn[0]; rde->data = data; rde->data_size = data_size; @@ -742,14 +745,14 @@ get_existing_record (void *cls, rde->flags |= GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION; else if (GNUNET_NO != etime_is_rel) rde->expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us; - GNUNET_assert (NULL != name); - add_qe = GNUNET_NAMESTORE_records_store (ns, - &zone_pkey, - name, - rd_count + 1, - rde, - &add_continuation, - &add_qe); + GNUNET_assert(NULL != name); + add_qe = GNUNET_NAMESTORE_records_store(ns, + &zone_pkey, + name, + rd_count + 1, + rde, + &add_continuation, + &add_qe); } @@ -757,11 +760,11 @@ get_existing_record (void *cls, * Function called if we encountered an error in zone-to-name. */ static void -reverse_error_cb (void *cls) +reverse_error_cb(void *cls) { - (void) cls; + (void)cls; reverse_qe = NULL; - fprintf (stdout, "%s.zkey\n", reverse_pkey); + fprintf(stdout, "%s.zkey\n", reverse_pkey); } @@ -776,22 +779,22 @@ reverse_error_cb (void *cls) * @param rd array of records with data to store */ static void -handle_reverse_lookup (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +handle_reverse_lookup(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { - (void) cls; - (void) zone; - (void) rd_count; - (void) rd; + (void)cls; + (void)zone; + (void)rd_count; + (void)rd; reverse_qe = NULL; if (NULL == label) - fprintf (stdout, "%s\n", reverse_pkey); + fprintf(stdout, "%s\n", reverse_pkey); else - fprintf (stdout, "%s.%s\n", label, ego_name); - test_finished (); + fprintf(stdout, "%s.%s\n", label, ego_name); + test_finished(); } @@ -799,13 +802,13 @@ handle_reverse_lookup (void *cls, * Function called if lookup for deletion fails. */ static void -del_lookup_error_cb (void *cls) +del_lookup_error_cb(void *cls) { - (void) cls; + (void)cls; del_qe = NULL; - GNUNET_break (0); + GNUNET_break(0); ret = 1; - test_finished (); + test_finished(); } @@ -821,80 +824,80 @@ del_lookup_error_cb (void *cls) * @param rd existing records */ static void -del_monitor (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +del_monitor(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_GNSRECORD_Data rdx[rd_count]; unsigned int rd_left; uint32_t type; char *vs; - (void) cls; - (void) zone; + (void)cls; + (void)zone; del_qe = NULL; if (0 == rd_count) - { - fprintf (stderr, - _ ( - "There are no records under label `%s' that could be deleted.\n"), - label); - ret = 1; - test_finished (); - return; - } + { + fprintf(stderr, + _( + "There are no records under label `%s' that could be deleted.\n"), + label); + ret = 1; + test_finished(); + return; + } if ((NULL == value) && (NULL == typestring)) - { - /* delete everything */ - del_qe = GNUNET_NAMESTORE_records_store (ns, - &zone_pkey, - name, - 0, - NULL, - &del_continuation, - NULL); - return; - } + { + /* delete everything */ + del_qe = GNUNET_NAMESTORE_records_store(ns, + &zone_pkey, + name, + 0, + NULL, + &del_continuation, + NULL); + return; + } rd_left = 0; if (NULL != typestring) - type = GNUNET_GNSRECORD_typename_to_number (typestring); + type = GNUNET_GNSRECORD_typename_to_number(typestring); else type = GNUNET_GNSRECORD_TYPE_ANY; for (unsigned int i = 0; i < rd_count; i++) - { - vs = NULL; - if (! (((GNUNET_GNSRECORD_TYPE_ANY == type) || - (rd[i].record_type == type)) && - ((NULL == value) || - (NULL == - (vs = (GNUNET_GNSRECORD_value_to_string (rd[i].record_type, + { + vs = NULL; + if (!(((GNUNET_GNSRECORD_TYPE_ANY == type) || + (rd[i].record_type == type)) && + ((NULL == value) || + (NULL == + (vs = (GNUNET_GNSRECORD_value_to_string(rd[i].record_type, rd[i].data, rd[i].data_size)))) || - (0 == strcmp (vs, value))))) - rdx[rd_left++] = rd[i]; - GNUNET_free_non_null (vs); - } + (0 == strcmp(vs, value))))) + rdx[rd_left++] = rd[i]; + GNUNET_free_non_null(vs); + } if (rd_count == rd_left) - { - /* nothing got deleted */ - fprintf ( - stderr, - _ ( - "There are no records under label `%s' that match the request for deletion.\n"), - label); - test_finished (); - return; - } + { + /* nothing got deleted */ + fprintf( + stderr, + _( + "There are no records under label `%s' that match the request for deletion.\n"), + label); + test_finished(); + return; + } /* delete everything but what we copied to 'rdx' */ - del_qe = GNUNET_NAMESTORE_records_store (ns, - &zone_pkey, - name, - rd_left, - rdx, - &del_continuation, - NULL); + del_qe = GNUNET_NAMESTORE_records_store(ns, + &zone_pkey, + name, + rd_left, + rdx, + &del_continuation, + NULL); } @@ -907,39 +910,39 @@ del_monitor (void *cls, * @return #GNUNET_OK on success */ static int -parse_expiration (const char *expirationstring, - int *etime_is_rel, - uint64_t *etime) +parse_expiration(const char *expirationstring, + int *etime_is_rel, + uint64_t *etime) { struct GNUNET_TIME_Relative etime_rel; struct GNUNET_TIME_Absolute etime_abs; - if (0 == strcmp (expirationstring, "never")) - { - *etime = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us; - *etime_is_rel = GNUNET_NO; - return GNUNET_OK; - } + if (0 == strcmp(expirationstring, "never")) + { + *etime = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us; + *etime_is_rel = GNUNET_NO; + return GNUNET_OK; + } if (GNUNET_OK == - GNUNET_STRINGS_fancy_time_to_relative (expirationstring, &etime_rel)) - { - *etime_is_rel = GNUNET_YES; - *etime = etime_rel.rel_value_us; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Storing record with relative expiration time of %s\n", - GNUNET_STRINGS_relative_time_to_string (etime_rel, GNUNET_NO)); - return GNUNET_OK; - } + GNUNET_STRINGS_fancy_time_to_relative(expirationstring, &etime_rel)) + { + *etime_is_rel = GNUNET_YES; + *etime = etime_rel.rel_value_us; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Storing record with relative expiration time of %s\n", + GNUNET_STRINGS_relative_time_to_string(etime_rel, GNUNET_NO)); + return GNUNET_OK; + } if (GNUNET_OK == - GNUNET_STRINGS_fancy_time_to_absolute (expirationstring, &etime_abs)) - { - *etime_is_rel = GNUNET_NO; - *etime = etime_abs.abs_value_us; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Storing record with absolute expiration time of %s\n", - GNUNET_STRINGS_absolute_time_to_string (etime_abs)); - return GNUNET_OK; - } + GNUNET_STRINGS_fancy_time_to_absolute(expirationstring, &etime_abs)) + { + *etime_is_rel = GNUNET_NO; + *etime = etime_abs.abs_value_us; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Storing record with absolute expiration time of %s\n", + GNUNET_STRINGS_absolute_time_to_string(etime_abs)); + return GNUNET_OK; + } return GNUNET_SYSERR; } @@ -955,19 +958,19 @@ parse_expiration (const char *expirationstring, * @param emsg NULL on success, otherwise an error message */ static void -replace_cont (void *cls, int success, const char *emsg) +replace_cont(void *cls, int success, const char *emsg) { - (void) cls; + (void)cls; set_qe = NULL; if (GNUNET_OK != success) - { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - _ ("Failed to replace records: %s\n"), - emsg); - ret = 1; /* fail from 'main' */ - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + _("Failed to replace records: %s\n"), + emsg); + ret = 1; /* fail from 'main' */ + } + GNUNET_SCHEDULER_shutdown(); } @@ -978,261 +981,261 @@ replace_cont (void *cls, int success, const char *emsg) * @param cfg configuration to use */ static void -run_with_zone_pkey (const struct GNUNET_CONFIGURATION_Handle *cfg) +run_with_zone_pkey(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_GNSRECORD_Data rd; - if (! (add | del | list | (NULL != nickstring) | (NULL != uri) | - (NULL != reverse_pkey) | (NULL != recordset))) - { - /* nothing more to be done */ - fprintf (stderr, _ ("No options given\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } - ns = GNUNET_NAMESTORE_connect (cfg); - if (NULL == ns) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to connect to namestore\n")); - return; - } - - if (NULL != recordset) - { - /* replace entire record set */ - unsigned int rd_count; - struct GNUNET_GNSRECORD_Data *rd; - - if (NULL == name) + if (!(add | del | list | (NULL != nickstring) | (NULL != uri) | + (NULL != reverse_pkey) | (NULL != recordset))) { - fprintf (stderr, - _ ("Missing option `%s' for operation `%s'\n"), - "-R", - _ ("replace")); - GNUNET_SCHEDULER_shutdown (); - ret = 1; - return; - } - rd_count = 0; - for (struct RecordSetEntry *e = recordset; NULL != e; e = e->next) - rd_count++; - rd = GNUNET_new_array (rd_count, struct GNUNET_GNSRECORD_Data); - rd_count = 0; - for (struct RecordSetEntry *e = recordset; NULL != e; e = e->next) - { - rd[rd_count] = e->record; - rd_count++; - } - set_qe = GNUNET_NAMESTORE_records_store (ns, - &zone_pkey, - name, - rd_count, - rd, - &replace_cont, - NULL); - GNUNET_free (rd); - return; - } - - if (add) - { - if (NULL == name) - { - fprintf (stderr, - _ ("Missing option `%s' for operation `%s'\n"), - "-n", - _ ("add")); - GNUNET_SCHEDULER_shutdown (); - ret = 1; - return; - } - if (NULL == typestring) - { - fprintf (stderr, - _ ("Missing option `%s' for operation `%s'\n"), - "-t", - _ ("add")); - GNUNET_SCHEDULER_shutdown (); - ret = 1; + /* nothing more to be done */ + fprintf(stderr, _("No options given\n")); + GNUNET_SCHEDULER_shutdown(); return; } - type = GNUNET_GNSRECORD_typename_to_number (typestring); - if (UINT32_MAX == type) - { - fprintf (stderr, _ ("Unsupported type `%s'\n"), typestring); - GNUNET_SCHEDULER_shutdown (); - ret = 1; - return; - } - if (NULL == value) - { - fprintf (stderr, - _ ("Missing option `%s' for operation `%s'\n"), - "-V", - _ ("add")); - ret = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } - if (GNUNET_OK != - GNUNET_GNSRECORD_string_to_value (type, value, &data, &data_size)) + ns = GNUNET_NAMESTORE_connect(cfg); + if (NULL == ns) { - fprintf (stderr, - _ ("Value `%s' invalid for record type `%s'\n"), - value, - typestring); - GNUNET_SCHEDULER_shutdown (); - ret = 1; + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to namestore\n")); return; } - if (NULL == expirationstring) + + if (NULL != recordset) { - fprintf (stderr, - _ ("Missing option `%s' for operation `%s'\n"), - "-e", - _ ("add")); - GNUNET_SCHEDULER_shutdown (); - ret = 1; + /* replace entire record set */ + unsigned int rd_count; + struct GNUNET_GNSRECORD_Data *rd; + + if (NULL == name) + { + fprintf(stderr, + _("Missing option `%s' for operation `%s'\n"), + "-R", + _("replace")); + GNUNET_SCHEDULER_shutdown(); + ret = 1; + return; + } + rd_count = 0; + for (struct RecordSetEntry *e = recordset; NULL != e; e = e->next) + rd_count++; + rd = GNUNET_new_array(rd_count, struct GNUNET_GNSRECORD_Data); + rd_count = 0; + for (struct RecordSetEntry *e = recordset; NULL != e; e = e->next) + { + rd[rd_count] = e->record; + rd_count++; + } + set_qe = GNUNET_NAMESTORE_records_store(ns, + &zone_pkey, + name, + rd_count, + rd, + &replace_cont, + NULL); + GNUNET_free(rd); return; } - if (GNUNET_OK != parse_expiration (expirationstring, &etime_is_rel, &etime)) + + if (add) { - fprintf (stderr, _ ("Invalid time format `%s'\n"), expirationstring); - GNUNET_SCHEDULER_shutdown (); - ret = 1; - return; + if (NULL == name) + { + fprintf(stderr, + _("Missing option `%s' for operation `%s'\n"), + "-n", + _("add")); + GNUNET_SCHEDULER_shutdown(); + ret = 1; + return; + } + if (NULL == typestring) + { + fprintf(stderr, + _("Missing option `%s' for operation `%s'\n"), + "-t", + _("add")); + GNUNET_SCHEDULER_shutdown(); + ret = 1; + return; + } + type = GNUNET_GNSRECORD_typename_to_number(typestring); + if (UINT32_MAX == type) + { + fprintf(stderr, _("Unsupported type `%s'\n"), typestring); + GNUNET_SCHEDULER_shutdown(); + ret = 1; + return; + } + if (NULL == value) + { + fprintf(stderr, + _("Missing option `%s' for operation `%s'\n"), + "-V", + _("add")); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } + if (GNUNET_OK != + GNUNET_GNSRECORD_string_to_value(type, value, &data, &data_size)) + { + fprintf(stderr, + _("Value `%s' invalid for record type `%s'\n"), + value, + typestring); + GNUNET_SCHEDULER_shutdown(); + ret = 1; + return; + } + if (NULL == expirationstring) + { + fprintf(stderr, + _("Missing option `%s' for operation `%s'\n"), + "-e", + _("add")); + GNUNET_SCHEDULER_shutdown(); + ret = 1; + return; + } + if (GNUNET_OK != parse_expiration(expirationstring, &etime_is_rel, &etime)) + { + fprintf(stderr, _("Invalid time format `%s'\n"), expirationstring); + GNUNET_SCHEDULER_shutdown(); + ret = 1; + return; + } + add_qe = GNUNET_NAMESTORE_records_lookup(ns, + &zone_pkey, + name, + &add_error_cb, + NULL, + &get_existing_record, + NULL); } - add_qe = GNUNET_NAMESTORE_records_lookup (ns, - &zone_pkey, - name, - &add_error_cb, - NULL, - &get_existing_record, - NULL); - } if (del) - { - if (NULL == name) { - fprintf (stderr, - _ ("Missing option `%s' for operation `%s'\n"), - "-n", - _ ("del")); - GNUNET_SCHEDULER_shutdown (); - ret = 1; - return; + if (NULL == name) + { + fprintf(stderr, + _("Missing option `%s' for operation `%s'\n"), + "-n", + _("del")); + GNUNET_SCHEDULER_shutdown(); + ret = 1; + return; + } + del_qe = GNUNET_NAMESTORE_records_lookup(ns, + &zone_pkey, + name, + &del_lookup_error_cb, + NULL, + &del_monitor, + NULL); } - del_qe = GNUNET_NAMESTORE_records_lookup (ns, - &zone_pkey, - name, - &del_lookup_error_cb, - NULL, - &del_monitor, - NULL); - } if (list) - { - if (NULL != name) - get_qe = GNUNET_NAMESTORE_records_lookup (ns, - &zone_pkey, - name, - &lookup_error_cb, - NULL, - &display_record_lookup, - NULL); - else - list_it = GNUNET_NAMESTORE_zone_iteration_start (ns, - &zone_pkey, - &zone_iteration_error_cb, - NULL, - &display_record_iterator, - NULL, - &zone_iteration_finished, - NULL); - } + { + if (NULL != name) + get_qe = GNUNET_NAMESTORE_records_lookup(ns, + &zone_pkey, + name, + &lookup_error_cb, + NULL, + &display_record_lookup, + NULL); + else + list_it = GNUNET_NAMESTORE_zone_iteration_start(ns, + &zone_pkey, + &zone_iteration_error_cb, + NULL, + &display_record_iterator, + NULL, + &zone_iteration_finished, + NULL); + } if (NULL != reverse_pkey) - { - struct GNUNET_CRYPTO_EcdsaPublicKey pubkey; - - if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (reverse_pkey, - strlen (reverse_pkey), - &pubkey)) { - fprintf (stderr, - _ ("Invalid public key for reverse lookup `%s'\n"), - reverse_pkey); - GNUNET_SCHEDULER_shutdown (); + struct GNUNET_CRYPTO_EcdsaPublicKey pubkey; + + if (GNUNET_OK != + GNUNET_CRYPTO_ecdsa_public_key_from_string(reverse_pkey, + strlen(reverse_pkey), + &pubkey)) + { + fprintf(stderr, + _("Invalid public key for reverse lookup `%s'\n"), + reverse_pkey); + GNUNET_SCHEDULER_shutdown(); + } + reverse_qe = GNUNET_NAMESTORE_zone_to_name(ns, + &zone_pkey, + &pubkey, + &reverse_error_cb, + NULL, + &handle_reverse_lookup, + NULL); } - reverse_qe = GNUNET_NAMESTORE_zone_to_name (ns, - &zone_pkey, - &pubkey, - &reverse_error_cb, - NULL, - &handle_reverse_lookup, - NULL); - } if (NULL != uri) - { - char sh[105]; - char sname[64]; - struct GNUNET_CRYPTO_EcdsaPublicKey pkey; - - GNUNET_STRINGS_utf8_tolower (uri, uri); - if ((2 != (sscanf (uri, "gnunet://gns/%52s/%63s", sh, sname))) || - (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (sh, strlen (sh), &pkey))) { - fprintf (stderr, _ ("Invalid URI `%s'\n"), uri); - GNUNET_SCHEDULER_shutdown (); - ret = 1; - return; + char sh[105]; + char sname[64]; + struct GNUNET_CRYPTO_EcdsaPublicKey pkey; + + GNUNET_STRINGS_utf8_tolower(uri, uri); + if ((2 != (sscanf(uri, "gnunet://gns/%52s/%63s", sh, sname))) || + (GNUNET_OK != + GNUNET_CRYPTO_ecdsa_public_key_from_string(sh, strlen(sh), &pkey))) + { + fprintf(stderr, _("Invalid URI `%s'\n"), uri); + GNUNET_SCHEDULER_shutdown(); + ret = 1; + return; + } + memset(&rd, 0, sizeof(rd)); + rd.data = &pkey; + rd.data_size = sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey); + rd.record_type = GNUNET_GNSRECORD_TYPE_PKEY; + rd.expiration_time = etime; + if (GNUNET_YES == etime_is_rel) + rd.flags |= GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION; + if (1 == is_shadow) + rd.flags |= GNUNET_GNSRECORD_RF_SHADOW_RECORD; + add_qe_uri = GNUNET_NAMESTORE_records_store(ns, + &zone_pkey, + sname, + 1, + &rd, + &add_continuation, + &add_qe_uri); } - memset (&rd, 0, sizeof (rd)); - rd.data = &pkey; - rd.data_size = sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey); - rd.record_type = GNUNET_GNSRECORD_TYPE_PKEY; - rd.expiration_time = etime; - if (GNUNET_YES == etime_is_rel) - rd.flags |= GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION; - if (1 == is_shadow) - rd.flags |= GNUNET_GNSRECORD_RF_SHADOW_RECORD; - add_qe_uri = GNUNET_NAMESTORE_records_store (ns, - &zone_pkey, - sname, - 1, - &rd, - &add_continuation, - &add_qe_uri); - } if (NULL != nickstring) - { - if (0 == strlen (nickstring)) { - fprintf (stderr, _ ("Invalid nick `%s'\n"), nickstring); - GNUNET_SCHEDULER_shutdown (); - ret = 1; - return; + if (0 == strlen(nickstring)) + { + fprintf(stderr, _("Invalid nick `%s'\n"), nickstring); + GNUNET_SCHEDULER_shutdown(); + ret = 1; + return; + } + add_qe_uri = GNUNET_NAMESTORE_set_nick(ns, + &zone_pkey, + nickstring, + &add_continuation, + &add_qe_uri); } - add_qe_uri = GNUNET_NAMESTORE_set_nick (ns, - &zone_pkey, - nickstring, - &add_continuation, - &add_qe_uri); - } if (monitor) - { - zm = GNUNET_NAMESTORE_zone_monitor_start (cfg, - &zone_pkey, - GNUNET_YES, - &monitor_error_cb, - NULL, - &display_record_monitor, - NULL, - &sync_cb, - NULL); - } + { + zm = GNUNET_NAMESTORE_zone_monitor_start(cfg, + &zone_pkey, + GNUNET_YES, + &monitor_error_cb, + NULL, + &display_record_monitor, + NULL, + &sync_cb, + NULL); + } } @@ -1244,37 +1247,37 @@ run_with_zone_pkey (const struct GNUNET_CONFIGURATION_Handle *cfg) * @param ego an ego known to identity service, or NULL */ static void -identity_cb (void *cls, const struct GNUNET_IDENTITY_Ego *ego) +identity_cb(void *cls, const struct GNUNET_IDENTITY_Ego *ego) { const struct GNUNET_CONFIGURATION_Handle *cfg = cls; el = NULL; - if ((NULL != name) && (0 != strchr (name, '.'))) - { - fprintf (stderr, - _ ("Label `%s' contains `.' which is not allowed\n"), - name); - GNUNET_SCHEDULER_shutdown (); - ret = -1; - return; - } + if ((NULL != name) && (0 != strchr(name, '.'))) + { + fprintf(stderr, + _("Label `%s' contains `.' which is not allowed\n"), + name); + GNUNET_SCHEDULER_shutdown(); + ret = -1; + return; + } if (NULL == ego) - { - if (NULL != ego_name) { - fprintf (stderr, - _ ("Ego `%s' not known to identity service\n"), - ego_name); + if (NULL != ego_name) + { + fprintf(stderr, + _("Ego `%s' not known to identity service\n"), + ego_name); + } + GNUNET_SCHEDULER_shutdown(); + ret = -1; + return; } - GNUNET_SCHEDULER_shutdown (); - ret = -1; - return; - } - zone_pkey = *GNUNET_IDENTITY_ego_get_private_key (ego); - GNUNET_free_non_null (ego_name); + zone_pkey = *GNUNET_IDENTITY_ego_get_private_key(ego); + GNUNET_free_non_null(ego_name); ego_name = NULL; - run_with_zone_pkey (cfg); + run_with_zone_pkey(cfg); } @@ -1289,27 +1292,27 @@ identity_cb (void *cls, const struct GNUNET_IDENTITY_Ego *ego) * @param name unused */ static void -default_ego_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +default_ego_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { const struct GNUNET_CONFIGURATION_Handle *cfg = cls; - (void) ctx; - (void) name; + (void)ctx; + (void)name; get_default = NULL; if (NULL == ego) - { - fprintf (stderr, _ ("No default ego configured in identity service\n")); - GNUNET_SCHEDULER_shutdown (); - ret = -1; - return; - } + { + fprintf(stderr, _("No default ego configured in identity service\n")); + GNUNET_SCHEDULER_shutdown(); + ret = -1; + return; + } else - { - identity_cb ((void *) cfg, ego); - } + { + identity_cb((void *)cfg, ego); + } } @@ -1326,19 +1329,19 @@ default_ego_cb (void *cls, * @param name name associated with @a ego */ static void -id_connect_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +id_connect_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { const struct GNUNET_CONFIGURATION_Handle *cfg = cls; - (void) ctx; - (void) name; + (void)ctx; + (void)name; if (NULL != ego) return; get_default = - GNUNET_IDENTITY_get (idh, "namestore", &default_ego_cb, (void *) cfg); + GNUNET_IDENTITY_get(idh, "namestore", &default_ego_cb, (void *)cfg); } @@ -1351,53 +1354,53 @@ id_connect_cb (void *cls, * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { const char *pkey_str; - (void) cls; - (void) args; - (void) cfgfile; + (void)cls; + (void)args; + (void)cfgfile; if (NULL != args[0]) - GNUNET_log ( + GNUNET_log( GNUNET_ERROR_TYPE_WARNING, - _ ("Superfluous command line arguments (starting with `%s') ignored\n"), + _("Superfluous command line arguments (starting with `%s') ignored\n"), args[0]); if ((NULL != args[0]) && (NULL == uri)) - uri = GNUNET_strdup (args[0]); + uri = GNUNET_strdup(args[0]); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, (void *) cfg); - pkey_str = getenv ("GNUNET_NAMESTORE_EGO_PRIVATE_KEY"); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, (void *)cfg); + pkey_str = getenv("GNUNET_NAMESTORE_EGO_PRIVATE_KEY"); if (NULL != pkey_str) - { - if (GNUNET_OK != GNUNET_STRINGS_string_to_data (pkey_str, - strlen (pkey_str), - &zone_pkey, - sizeof (zone_pkey))) { - fprintf (stderr, - "Malformed private key `%s' in $%s\n", - pkey_str, - "GNUNET_NAMESTORE_EGO_PRIVATE_KEY"); - ret = 1; - GNUNET_SCHEDULER_shutdown (); + if (GNUNET_OK != GNUNET_STRINGS_string_to_data(pkey_str, + strlen(pkey_str), + &zone_pkey, + sizeof(zone_pkey))) + { + fprintf(stderr, + "Malformed private key `%s' in $%s\n", + pkey_str, + "GNUNET_NAMESTORE_EGO_PRIVATE_KEY"); + ret = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } + run_with_zone_pkey(cfg); return; } - run_with_zone_pkey (cfg); - return; - } if (NULL == ego_name) - { - idh = GNUNET_IDENTITY_connect (cfg, &id_connect_cb, (void *) cfg); - if (NULL == idh) - fprintf (stderr, _ ("Cannot connect to identity service\n")); - ret = -1; - return; - } - el = GNUNET_IDENTITY_ego_lookup (cfg, ego_name, &identity_cb, (void *) cfg); + { + idh = GNUNET_IDENTITY_connect(cfg, &id_connect_cb, (void *)cfg); + if (NULL == idh) + fprintf(stderr, _("Cannot connect to identity service\n")); + ret = -1; + return; + } + el = GNUNET_IDENTITY_ego_lookup(cfg, ego_name, &identity_cb, (void *)cfg); } @@ -1419,10 +1422,10 @@ run (void *cls, * @return #GNUNET_OK on success */ static int -multirecord_process (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, - void *scls, - const char *option, - const char *value) +multirecord_process(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, + void *scls, + const char *option, + const char *value) { struct RecordSetEntry **head = scls; struct RecordSetEntry *r; @@ -1433,94 +1436,94 @@ multirecord_process (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, int etime_is_rel; void *raw_data; - (void) ctx; - (void) option; - cp = GNUNET_strdup (value); - tok = strtok_r (cp, " ", &saveptr); + (void)ctx; + (void)option; + cp = GNUNET_strdup(value); + tok = strtok_r(cp, " ", &saveptr); if (NULL == tok) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Empty record line argument is not allowed.\n")); - GNUNET_free (cp); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Empty record line argument is not allowed.\n")); + GNUNET_free(cp); + return GNUNET_SYSERR; + } { char *etime_in_s; - GNUNET_asprintf (&etime_in_s, "%s s", tok); + GNUNET_asprintf(&etime_in_s, "%s s", tok); if (GNUNET_OK != - parse_expiration (etime_in_s, &etime_is_rel, &record.expiration_time)) + parse_expiration(etime_in_s, &etime_is_rel, &record.expiration_time)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Invalid expiration time `%s' (must be without unit)\n"), + tok); + GNUNET_free(cp); + GNUNET_free(etime_in_s); + return GNUNET_SYSERR; + } + GNUNET_free(etime_in_s); + } + tok = strtok_r(NULL, " ", &saveptr); + if (NULL == tok) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Invalid expiration time `%s' (must be without unit)\n"), - tok); - GNUNET_free (cp); - GNUNET_free (etime_in_s); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Missing entries in record line `%s'.\n"), + value); + GNUNET_free(cp); return GNUNET_SYSERR; } - GNUNET_free (etime_in_s); - } - tok = strtok_r (NULL, " ", &saveptr); - if (NULL == tok) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Missing entries in record line `%s'.\n"), - value); - GNUNET_free (cp); - return GNUNET_SYSERR; - } - record.record_type = GNUNET_GNSRECORD_typename_to_number (tok); + record.record_type = GNUNET_GNSRECORD_typename_to_number(tok); if (UINT32_MAX == record.record_type) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Unknown record type `%s'\n"), tok); - GNUNET_free (cp); - return GNUNET_SYSERR; - } - tok = strtok_r (NULL, " ", &saveptr); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Unknown record type `%s'\n"), tok); + GNUNET_free(cp); + return GNUNET_SYSERR; + } + tok = strtok_r(NULL, " ", &saveptr); if (NULL == tok) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Missing entries in record line `%s'.\n"), - value); - GNUNET_free (cp); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Missing entries in record line `%s'.\n"), + value); + GNUNET_free(cp); + return GNUNET_SYSERR; + } record.flags = GNUNET_GNSRECORD_RF_NONE; if (etime_is_rel) record.flags |= GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION; - if (NULL == strchr (tok, (unsigned char) 'p')) /* p = public */ + if (NULL == strchr(tok, (unsigned char)'p')) /* p = public */ record.flags |= GNUNET_GNSRECORD_RF_PRIVATE; - if (NULL != strchr (tok, (unsigned char) 's')) + if (NULL != strchr(tok, (unsigned char)'s')) record.flags |= GNUNET_GNSRECORD_RF_SHADOW_RECORD; /* find beginning of record value */ - tok = strchr (&value[tok - cp], (unsigned char) ' '); + tok = strchr(&value[tok - cp], (unsigned char)' '); if (NULL == tok) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Missing entries in record line `%s'.\n"), - value); - GNUNET_free (cp); - return GNUNET_SYSERR; - } - GNUNET_free (cp); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Missing entries in record line `%s'.\n"), + value); + GNUNET_free(cp); + return GNUNET_SYSERR; + } + GNUNET_free(cp); tok++; /* skip space */ - if (GNUNET_OK != GNUNET_GNSRECORD_string_to_value (record.record_type, - tok, - &raw_data, - &record.data_size)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Invalid record data for type %s: `%s'.\n"), - GNUNET_GNSRECORD_number_to_typename (record.record_type), - tok); - return GNUNET_SYSERR; - } + if (GNUNET_OK != GNUNET_GNSRECORD_string_to_value(record.record_type, + tok, + &raw_data, + &record.data_size)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Invalid record data for type %s: `%s'.\n"), + GNUNET_GNSRECORD_number_to_typename(record.record_type), + tok); + return GNUNET_SYSERR; + } - r = GNUNET_malloc (sizeof (struct RecordSetEntry) + record.data_size); + r = GNUNET_malloc(sizeof(struct RecordSetEntry) + record.data_size); r->next = *head; record.data = &r[1]; - memcpy (&r[1], raw_data, record.data_size); - GNUNET_free (raw_data); + memcpy(&r[1], raw_data, record.data_size); + GNUNET_free(raw_data); r->record = record; *head = r; return GNUNET_OK; @@ -1537,20 +1540,20 @@ multirecord_process (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, * @param[out] topKeywords set to the desired value */ struct GNUNET_GETOPT_CommandLineOption -multirecord_option (char shortName, - const char *name, - const char *argumentHelp, - const char *description, - struct RecordSetEntry **rs) +multirecord_option(char shortName, + const char *name, + const char *argumentHelp, + const char *description, + struct RecordSetEntry **rs) { - struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = shortName, - .name = name, - .argumentHelp = argumentHelp, - .description = description, - .require_argument = 1, - .processor = - &multirecord_process, - .scls = (void *) rs}; + struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName, + .name = name, + .argumentHelp = argumentHelp, + .description = description, + .require_argument = 1, + .processor = + &multirecord_process, + .scls = (void *)rs }; return clo; } @@ -1564,112 +1567,112 @@ multirecord_option (char shortName, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_flag ('a', "add", gettext_noop ("add record"), &add), - GNUNET_GETOPT_option_flag ('d', - "delete", - gettext_noop ("delete record"), - &del), - GNUNET_GETOPT_option_flag ('D', - "display", - gettext_noop ("display records"), - &list), - GNUNET_GETOPT_option_string ( - 'e', - "expiration", - "TIME", - gettext_noop ( - "expiration time for record to use (for adding only), \"never\" is possible"), - &expirationstring), - GNUNET_GETOPT_option_string ('i', - "nick", - "NICKNAME", - gettext_noop ( - "set the desired nick name for the zone"), - &nickstring), - GNUNET_GETOPT_option_flag ('m', - "monitor", - gettext_noop ( - "monitor changes in the namestore"), - &monitor), - GNUNET_GETOPT_option_string ('n', - "name", - "NAME", - gettext_noop ( - "name of the record to add/delete/display"), - &name), - GNUNET_GETOPT_option_string ('r', - "reverse", - "PKEY", - gettext_noop ( - "determine our name for the given PKEY"), - &reverse_pkey), - multirecord_option ( - 'R', - "replace", - "RECORDLINE", - gettext_noop ( - "set record set to values given by (possibly multiple) RECORDLINES; can be specified multiple times"), - &recordset), - GNUNET_GETOPT_option_string ('t', - "type", - "TYPE", - gettext_noop ( - "type of the record to add/delete/display"), - &typestring), - GNUNET_GETOPT_option_string ('u', - "uri", - "URI", - gettext_noop ("URI to import into our zone"), - &uri), - GNUNET_GETOPT_option_string ('V', - "value", - "VALUE", - gettext_noop ( - "value of the record to add/delete"), - &value), - GNUNET_GETOPT_option_flag ('p', - "public", - gettext_noop ("create or list public record"), - &is_public), - GNUNET_GETOPT_option_flag ( - 's', - "shadow", - gettext_noop ( - "create shadow record (only valid if all other records of the same type have expired"), - &is_shadow), - GNUNET_GETOPT_option_string ('z', - "zone", - "EGO", - gettext_noop ( - "name of the ego controlling the zone"), - &ego_name), - GNUNET_GETOPT_OPTION_END}; + { GNUNET_GETOPT_option_flag('a', "add", gettext_noop("add record"), &add), + GNUNET_GETOPT_option_flag('d', + "delete", + gettext_noop("delete record"), + &del), + GNUNET_GETOPT_option_flag('D', + "display", + gettext_noop("display records"), + &list), + GNUNET_GETOPT_option_string( + 'e', + "expiration", + "TIME", + gettext_noop( + "expiration time for record to use (for adding only), \"never\" is possible"), + &expirationstring), + GNUNET_GETOPT_option_string('i', + "nick", + "NICKNAME", + gettext_noop( + "set the desired nick name for the zone"), + &nickstring), + GNUNET_GETOPT_option_flag('m', + "monitor", + gettext_noop( + "monitor changes in the namestore"), + &monitor), + GNUNET_GETOPT_option_string('n', + "name", + "NAME", + gettext_noop( + "name of the record to add/delete/display"), + &name), + GNUNET_GETOPT_option_string('r', + "reverse", + "PKEY", + gettext_noop( + "determine our name for the given PKEY"), + &reverse_pkey), + multirecord_option( + 'R', + "replace", + "RECORDLINE", + gettext_noop( + "set record set to values given by (possibly multiple) RECORDLINES; can be specified multiple times"), + &recordset), + GNUNET_GETOPT_option_string('t', + "type", + "TYPE", + gettext_noop( + "type of the record to add/delete/display"), + &typestring), + GNUNET_GETOPT_option_string('u', + "uri", + "URI", + gettext_noop("URI to import into our zone"), + &uri), + GNUNET_GETOPT_option_string('V', + "value", + "VALUE", + gettext_noop( + "value of the record to add/delete"), + &value), + GNUNET_GETOPT_option_flag('p', + "public", + gettext_noop("create or list public record"), + &is_public), + GNUNET_GETOPT_option_flag( + 's', + "shadow", + gettext_noop( + "create shadow record (only valid if all other records of the same type have expired"), + &is_shadow), + GNUNET_GETOPT_option_string('z', + "zone", + "EGO", + gettext_noop( + "name of the ego controlling the zone"), + &ego_name), + GNUNET_GETOPT_OPTION_END }; int lret; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; is_public = -1; is_shadow = -1; - GNUNET_log_setup ("gnunet-namestore", "WARNING", NULL); + GNUNET_log_setup("gnunet-namestore", "WARNING", NULL); if (GNUNET_OK != - (lret = GNUNET_PROGRAM_run (argc, - argv, - "gnunet-namestore", - _ ("GNUnet zone manipulation tool"), - options, - &run, - NULL))) - { - GNUNET_free ((void *) argv); - GNUNET_CRYPTO_ecdsa_key_clear (&zone_pkey); - return lret; - } - GNUNET_free ((void *) argv); - GNUNET_CRYPTO_ecdsa_key_clear (&zone_pkey); + (lret = GNUNET_PROGRAM_run(argc, + argv, + "gnunet-namestore", + _("GNUnet zone manipulation tool"), + options, + &run, + NULL))) + { + GNUNET_free((void *)argv); + GNUNET_CRYPTO_ecdsa_key_clear(&zone_pkey); + return lret; + } + GNUNET_free((void *)argv); + GNUNET_CRYPTO_ecdsa_key_clear(&zone_pkey); return ret; } diff --git a/src/namestore/gnunet-service-namestore.c b/src/namestore/gnunet-service-namestore.c index 3a925b952..71754081e 100644 --- a/src/namestore/gnunet-service-namestore.c +++ b/src/namestore/gnunet-service-namestore.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/gnunet-service-namestore.c @@ -36,7 +36,7 @@ #include "namestore.h" #define LOG_STRERROR_FILE(kind, syscall, filename) \ - GNUNET_log_from_strerror_file (kind, "util", syscall, filename) + GNUNET_log_from_strerror_file(kind, "util", syscall, filename) /** * If a monitor takes more than 1 minute to process an event, print a warning. @@ -57,8 +57,7 @@ struct NamestoreClient; /** * A namestore iteration operation. */ -struct ZoneIteration -{ +struct ZoneIteration { /** * Next element in the DLL */ @@ -125,9 +124,7 @@ struct ZoneIteration /** * A namestore client */ -struct NamestoreClient -{ - +struct NamestoreClient { /** * The client */ @@ -155,8 +152,7 @@ struct NamestoreClient /** * A namestore monitor. */ -struct ZoneMonitor -{ +struct ZoneMonitor { /** * Next element in the DLL */ @@ -233,9 +229,7 @@ struct ZoneMonitor /** * Pending operation on the namecache. */ -struct CacheOperation -{ - +struct CacheOperation { /** * Kept in a DLL. */ @@ -273,8 +267,7 @@ struct CacheOperation * Information for an ongoing #handle_record_store() operation. * Needed as we may wait for monitors to be ready for the notification. */ -struct StoreActivity -{ +struct StoreActivity { /** * Kept in a DLL. */ @@ -311,8 +304,7 @@ struct StoreActivity /** * Entry in list of cached nick resolutions. */ -struct NickCache -{ +struct NickCache { /** * Zone the cache entry is for. */ @@ -419,38 +411,38 @@ static int disable_namecache; * @param cls unused */ static void -cleanup_task (void *cls) +cleanup_task(void *cls) { struct CacheOperation *cop; - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Stopping namestore service\n"); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Stopping namestore service\n"); while (NULL != (cop = cop_head)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Aborting incomplete namecache operation\n"); - GNUNET_NAMECACHE_cancel (cop->qe); - GNUNET_CONTAINER_DLL_remove (cop_head, cop_tail, cop); - GNUNET_free (cop); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Aborting incomplete namecache operation\n"); + GNUNET_NAMECACHE_cancel(cop->qe); + GNUNET_CONTAINER_DLL_remove(cop_head, cop_tail, cop); + GNUNET_free(cop); + } if (NULL != namecache) - { - GNUNET_NAMECACHE_disconnect (namecache); - namecache = NULL; - } - GNUNET_break (NULL == GNUNET_PLUGIN_unload (db_lib_name, GSN_database)); - GNUNET_free (db_lib_name); + { + GNUNET_NAMECACHE_disconnect(namecache); + namecache = NULL; + } + GNUNET_break(NULL == GNUNET_PLUGIN_unload(db_lib_name, GSN_database)); + GNUNET_free(db_lib_name); db_lib_name = NULL; if (NULL != monitor_nc) - { - GNUNET_notification_context_destroy (monitor_nc); - monitor_nc = NULL; - } + { + GNUNET_notification_context_destroy(monitor_nc); + monitor_nc = NULL; + } if (NULL != statistics) - { - GNUNET_STATISTICS_destroy (statistics, GNUNET_NO); - statistics = NULL; - } + { + GNUNET_STATISTICS_destroy(statistics, GNUNET_NO); + statistics = NULL; + } } @@ -460,11 +452,11 @@ cleanup_task (void *cls) * @param sa activity to free */ static void -free_store_activity (struct StoreActivity *sa) +free_store_activity(struct StoreActivity *sa) { - GNUNET_CONTAINER_DLL_remove (sa_head, sa_tail, sa); - GNUNET_free (sa->conv_name); - GNUNET_free (sa); + GNUNET_CONTAINER_DLL_remove(sa_head, sa_tail, sa); + GNUNET_free(sa->conv_name); + GNUNET_free(sa); } @@ -481,37 +473,37 @@ free_store_activity (struct StoreActivity *sa) * @param rd records stored under @a label in the zone */ static void -lookup_nick_it (void *cls, - uint64_t seq, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +lookup_nick_it(void *cls, + uint64_t seq, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_GNSRECORD_Data **res = cls; - (void) private_key; - GNUNET_assert (0 != seq); - if (0 != strcmp (label, GNUNET_GNS_EMPTY_LABEL_AT)) - { - GNUNET_break (0); - return; - } - for (unsigned int c = 0; c < rd_count; c++) - { - if (GNUNET_GNSRECORD_TYPE_NICK == rd[c].record_type) + (void)private_key; + GNUNET_assert(0 != seq); + if (0 != strcmp(label, GNUNET_GNS_EMPTY_LABEL_AT)) { - (*res) = - GNUNET_malloc (rd[c].data_size + sizeof (struct GNUNET_GNSRECORD_Data)); - (*res)->data = &(*res)[1]; - GNUNET_memcpy ((void *) (*res)->data, rd[c].data, rd[c].data_size); - (*res)->data_size = rd[c].data_size; - (*res)->expiration_time = rd[c].expiration_time; - (*res)->flags = rd[c].flags; - (*res)->record_type = GNUNET_GNSRECORD_TYPE_NICK; + GNUNET_break(0); return; } - } + for (unsigned int c = 0; c < rd_count; c++) + { + if (GNUNET_GNSRECORD_TYPE_NICK == rd[c].record_type) + { + (*res) = + GNUNET_malloc(rd[c].data_size + sizeof(struct GNUNET_GNSRECORD_Data)); + (*res)->data = &(*res)[1]; + GNUNET_memcpy((void *)(*res)->data, rd[c].data, rd[c].data_size); + (*res)->data_size = rd[c].data_size; + (*res)->expiration_time = rd[c].expiration_time; + (*res)->flags = rd[c].flags; + (*res)->record_type = GNUNET_GNSRECORD_TYPE_NICK; + return; + } + } (*res) = NULL; } @@ -523,39 +515,39 @@ lookup_nick_it (void *cls, * @param nick nick entry to cache */ static void -cache_nick (const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const struct GNUNET_GNSRECORD_Data *nick) +cache_nick(const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const struct GNUNET_GNSRECORD_Data *nick) { struct NickCache *oldest; oldest = NULL; for (unsigned int i = 0; i < NC_SIZE; i++) - { - struct NickCache *pos = &nick_cache[i]; - - if ((NULL == oldest) || - (oldest->last_used.abs_value_us > pos->last_used.abs_value_us)) - oldest = pos; - if (0 == GNUNET_memcmp (zone, &pos->zone)) { - oldest = pos; - break; + struct NickCache *pos = &nick_cache[i]; + + if ((NULL == oldest) || + (oldest->last_used.abs_value_us > pos->last_used.abs_value_us)) + oldest = pos; + if (0 == GNUNET_memcmp(zone, &pos->zone)) + { + oldest = pos; + break; + } } - } - GNUNET_free_non_null (oldest->rd); + GNUNET_free_non_null(oldest->rd); oldest->zone = *zone; if (NULL != nick) - { - oldest->rd = GNUNET_malloc (sizeof (*nick) + nick->data_size); - *oldest->rd = *nick; - oldest->rd->data = &oldest->rd[1]; - memcpy (&oldest->rd[1], nick->data, nick->data_size); - } + { + oldest->rd = GNUNET_malloc(sizeof(*nick) + nick->data_size); + *oldest->rd = *nick; + oldest->rd->data = &oldest->rd[1]; + memcpy(&oldest->rd[1], nick->data, nick->data_size); + } else - { - oldest->rd = NULL; - } - oldest->last_used = GNUNET_TIME_absolute_get (); + { + oldest->rd = NULL; + } + oldest->last_used = GNUNET_TIME_absolute_get(); } @@ -566,7 +558,7 @@ cache_nick (const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, * @return NULL if no NICK record was found */ static struct GNUNET_GNSRECORD_Data * -get_nick_record (const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone) +get_nick_record(const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone) { struct GNUNET_CRYPTO_EcdsaPublicKey pub; struct GNUNET_GNSRECORD_Data *nick; @@ -574,53 +566,53 @@ get_nick_record (const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone) /* check cache first */ for (unsigned int i = 0; i < NC_SIZE; i++) - { - struct NickCache *pos = &nick_cache[i]; - if ((NULL != pos->rd) && (0 == GNUNET_memcmp (zone, &pos->zone))) { - if (NULL == pos->rd) - return NULL; - nick = GNUNET_malloc (sizeof (*nick) + pos->rd->data_size); - *nick = *pos->rd; - nick->data = &nick[1]; - memcpy (&nick[1], pos->rd->data, pos->rd->data_size); - pos->last_used = GNUNET_TIME_absolute_get (); - return nick; + struct NickCache *pos = &nick_cache[i]; + if ((NULL != pos->rd) && (0 == GNUNET_memcmp(zone, &pos->zone))) + { + if (NULL == pos->rd) + return NULL; + nick = GNUNET_malloc(sizeof(*nick) + pos->rd->data_size); + *nick = *pos->rd; + nick->data = &nick[1]; + memcpy(&nick[1], pos->rd->data, pos->rd->data_size); + pos->last_used = GNUNET_TIME_absolute_get(); + return nick; + } } - } nick = NULL; - res = GSN_database->lookup_records (GSN_database->cls, - zone, - GNUNET_GNS_EMPTY_LABEL_AT, - &lookup_nick_it, - &nick); + res = GSN_database->lookup_records(GSN_database->cls, + zone, + GNUNET_GNS_EMPTY_LABEL_AT, + &lookup_nick_it, + &nick); if ((GNUNET_OK != res) || (NULL == nick)) - { -#if ! defined(GNUNET_CULL_LOGGING) - static int do_log = GNUNET_LOG_CALL_STATUS; - - if (0 == do_log) - do_log = GNUNET_get_log_call_status (GNUNET_ERROR_TYPE_DEBUG, - "namestore", - __FILE__, - __FUNCTION__, - __LINE__); - if (1 == do_log) { - GNUNET_CRYPTO_ecdsa_key_get_public (zone, &pub); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, - "No nick name set for zone `%s'\n", - GNUNET_GNSRECORD_z2s (&pub)); - } +#if !defined(GNUNET_CULL_LOGGING) + static int do_log = GNUNET_LOG_CALL_STATUS; + + if (0 == do_log) + do_log = GNUNET_get_log_call_status(GNUNET_ERROR_TYPE_DEBUG, + "namestore", + __FILE__, + __FUNCTION__, + __LINE__); + if (1 == do_log) + { + GNUNET_CRYPTO_ecdsa_key_get_public(zone, &pub); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, + "No nick name set for zone `%s'\n", + GNUNET_GNSRECORD_z2s(&pub)); + } #endif - /* update cache */ - cache_nick (zone, NULL); - return NULL; - } + /* update cache */ + cache_nick(zone, NULL); + return NULL; + } /* update cache */ - cache_nick (zone, nick); + cache_nick(zone, nick); return nick; } @@ -641,11 +633,11 @@ get_nick_record (const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone) * allocated in the same chunk of memory! */ static void -merge_with_nick_records (const struct GNUNET_GNSRECORD_Data *nick_rd, - unsigned int rd2_length, - const struct GNUNET_GNSRECORD_Data *rd2, - unsigned int *rdc_res, - struct GNUNET_GNSRECORD_Data **rd_res) +merge_with_nick_records(const struct GNUNET_GNSRECORD_Data *nick_rd, + unsigned int rd2_length, + const struct GNUNET_GNSRECORD_Data *rd2, + unsigned int *rdc_res, + struct GNUNET_GNSRECORD_Data **rd_res) { uint64_t latest_expiration; size_t req; @@ -655,54 +647,54 @@ merge_with_nick_records (const struct GNUNET_GNSRECORD_Data *nick_rd, (*rdc_res) = 1 + rd2_length; if (0 == 1 + rd2_length) - { - GNUNET_break (0); - (*rd_res) = NULL; - return; - } - req = sizeof (struct GNUNET_GNSRECORD_Data) + nick_rd->data_size; - for (unsigned int i = 0; i < rd2_length; i++) - { - const struct GNUNET_GNSRECORD_Data *orig = &rd2[i]; - - if (req + sizeof (struct GNUNET_GNSRECORD_Data) + orig->data_size < req) { - GNUNET_break (0); + GNUNET_break(0); (*rd_res) = NULL; return; } - req += sizeof (struct GNUNET_GNSRECORD_Data) + orig->data_size; - } - target = GNUNET_malloc (req); + req = sizeof(struct GNUNET_GNSRECORD_Data) + nick_rd->data_size; + for (unsigned int i = 0; i < rd2_length; i++) + { + const struct GNUNET_GNSRECORD_Data *orig = &rd2[i]; + + if (req + sizeof(struct GNUNET_GNSRECORD_Data) + orig->data_size < req) + { + GNUNET_break(0); + (*rd_res) = NULL; + return; + } + req += sizeof(struct GNUNET_GNSRECORD_Data) + orig->data_size; + } + target = GNUNET_malloc(req); (*rd_res) = target; - data = (char *) &target[1 + rd2_length]; + data = (char *)&target[1 + rd2_length]; data_offset = 0; latest_expiration = 0; for (unsigned int i = 0; i < rd2_length; i++) - { - const struct GNUNET_GNSRECORD_Data *orig = &rd2[i]; - - if (0 != (orig->flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) { - if ((GNUNET_TIME_absolute_get ().abs_value_us + orig->expiration_time) > - latest_expiration) + const struct GNUNET_GNSRECORD_Data *orig = &rd2[i]; + + if (0 != (orig->flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) + { + if ((GNUNET_TIME_absolute_get().abs_value_us + orig->expiration_time) > + latest_expiration) + latest_expiration = orig->expiration_time; + } + else if (orig->expiration_time > latest_expiration) latest_expiration = orig->expiration_time; + target[i] = *orig; + target[i].data = (void *)&data[data_offset]; + GNUNET_memcpy(&data[data_offset], orig->data, orig->data_size); + data_offset += orig->data_size; } - else if (orig->expiration_time > latest_expiration) - latest_expiration = orig->expiration_time; - target[i] = *orig; - target[i].data = (void *) &data[data_offset]; - GNUNET_memcpy (&data[data_offset], orig->data, orig->data_size); - data_offset += orig->data_size; - } /* append nick */ target[rd2_length] = *nick_rd; target[rd2_length].expiration_time = latest_expiration; - target[rd2_length].data = (void *) &data[data_offset]; - GNUNET_memcpy (&data[data_offset], nick_rd->data, nick_rd->data_size); + target[rd2_length].data = (void *)&data[data_offset]; + GNUNET_memcpy(&data[data_offset], nick_rd->data, nick_rd->data_size); data_offset += nick_rd->data_size; - GNUNET_assert (req == (sizeof (struct GNUNET_GNSRECORD_Data)) * (*rdc_res) + - data_offset); + GNUNET_assert(req == (sizeof(struct GNUNET_GNSRECORD_Data)) * (*rdc_res) + + data_offset); } @@ -718,12 +710,12 @@ merge_with_nick_records (const struct GNUNET_GNSRECORD_Data *nick_rd, * @param rd array of records */ static void -send_lookup_response (struct NamestoreClient *nc, - uint32_t request_id, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *name, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +send_lookup_response(struct NamestoreClient *nc, + uint32_t request_id, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *name, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_MQ_Envelope *env; struct RecordResultMessage *zir_msg; @@ -735,63 +727,63 @@ send_lookup_response (struct NamestoreClient *nc, char *name_tmp; char *rd_ser; - nick = get_nick_record (zone_key); - GNUNET_assert (-1 != GNUNET_GNSRECORD_records_get_size (rd_count, rd)); + nick = get_nick_record(zone_key); + GNUNET_assert(-1 != GNUNET_GNSRECORD_records_get_size(rd_count, rd)); - if ((NULL != nick) && (0 != strcmp (name, GNUNET_GNS_EMPTY_LABEL_AT))) - { - nick->flags = - (nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE; - merge_with_nick_records (nick, rd_count, rd, &res_count, &res); - GNUNET_free (nick); - } + if ((NULL != nick) && (0 != strcmp(name, GNUNET_GNS_EMPTY_LABEL_AT))) + { + nick->flags = + (nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE; + merge_with_nick_records(nick, rd_count, rd, &res_count, &res); + GNUNET_free(nick); + } else - { - res_count = rd_count; - res = (struct GNUNET_GNSRECORD_Data *) rd; - } + { + res_count = rd_count; + res = (struct GNUNET_GNSRECORD_Data *)rd; + } - GNUNET_assert (-1 != GNUNET_GNSRECORD_records_get_size (res_count, res)); + GNUNET_assert(-1 != GNUNET_GNSRECORD_records_get_size(res_count, res)); - name_len = strlen (name) + 1; - rd_ser_len = GNUNET_GNSRECORD_records_get_size (res_count, res); + name_len = strlen(name) + 1; + rd_ser_len = GNUNET_GNSRECORD_records_get_size(res_count, res); if (rd_ser_len < 0) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (nc->client); - return; - } - if (((size_t) rd_ser_len) >= UINT16_MAX - name_len - sizeof (*zir_msg)) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (nc->client); - return; - } - env = GNUNET_MQ_msg_extra (zir_msg, - name_len + rd_ser_len, - GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT); - zir_msg->gns_header.r_id = htonl (request_id); - zir_msg->name_len = htons (name_len); - zir_msg->rd_count = htons (res_count); - zir_msg->rd_len = htons ((uint16_t) rd_ser_len); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(nc->client); + return; + } + if (((size_t)rd_ser_len) >= UINT16_MAX - name_len - sizeof(*zir_msg)) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(nc->client); + return; + } + env = GNUNET_MQ_msg_extra(zir_msg, + name_len + rd_ser_len, + GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT); + zir_msg->gns_header.r_id = htonl(request_id); + zir_msg->name_len = htons(name_len); + zir_msg->rd_count = htons(res_count); + zir_msg->rd_len = htons((uint16_t)rd_ser_len); zir_msg->private_key = *zone_key; - name_tmp = (char *) &zir_msg[1]; - GNUNET_memcpy (name_tmp, name, name_len); + name_tmp = (char *)&zir_msg[1]; + GNUNET_memcpy(name_tmp, name, name_len); rd_ser = &name_tmp[name_len]; - GNUNET_assert ( + GNUNET_assert( rd_ser_len == - GNUNET_GNSRECORD_records_serialize (res_count, res, rd_ser_len, rd_ser)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending RECORD_RESULT message with %u records\n", - res_count); - GNUNET_STATISTICS_update (statistics, - "Record sets sent to clients", - 1, - GNUNET_NO); - GNUNET_MQ_send (nc->mq, env); + GNUNET_GNSRECORD_records_serialize(res_count, res, rd_ser_len, rd_ser)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending RECORD_RESULT message with %u records\n", + res_count); + GNUNET_STATISTICS_update(statistics, + "Record sets sent to clients", + 1, + GNUNET_NO); + GNUNET_MQ_send(nc->mq, env); if (rd != res) - GNUNET_free (res); + GNUNET_free(res); } @@ -803,23 +795,23 @@ send_lookup_response (struct NamestoreClient *nc, * @param rid client's request ID */ static void -send_store_response (struct NamestoreClient *nc, int res, uint32_t rid) +send_store_response(struct NamestoreClient *nc, int res, uint32_t rid) { struct GNUNET_MQ_Envelope *env; struct RecordStoreResponseMessage *rcr_msg; - GNUNET_assert (NULL != nc); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending RECORD_STORE_RESPONSE message\n"); - GNUNET_STATISTICS_update (statistics, - "Store requests completed", - 1, - GNUNET_NO); - env = GNUNET_MQ_msg (rcr_msg, - GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE); - rcr_msg->gns_header.r_id = htonl (rid); - rcr_msg->op_result = htonl (res); - GNUNET_MQ_send (nc->mq, env); + GNUNET_assert(NULL != nc); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending RECORD_STORE_RESPONSE message\n"); + GNUNET_STATISTICS_update(statistics, + "Store requests completed", + 1, + GNUNET_NO); + env = GNUNET_MQ_msg(rcr_msg, + GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE); + rcr_msg->gns_header.r_id = htonl(rid); + rcr_msg->op_result = htonl(res); + GNUNET_MQ_send(nc->mq, env); } @@ -830,21 +822,21 @@ send_store_response (struct NamestoreClient *nc, int res, uint32_t rid) * @param zi zone iteration we are processing */ static void -zone_iteration_done_client_continue (struct ZoneIteration *zi) +zone_iteration_done_client_continue(struct ZoneIteration *zi) { struct GNUNET_MQ_Envelope *env; struct GNUNET_NAMESTORE_Header *em; - GNUNET_SERVICE_client_continue (zi->nc->client); - if (! zi->send_end) + GNUNET_SERVICE_client_continue(zi->nc->client); + if (!zi->send_end) return; /* send empty response to indicate end of list */ - env = GNUNET_MQ_msg (em, GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT_END); - em->r_id = htonl (zi->request_id); - GNUNET_MQ_send (zi->nc->mq, env); + env = GNUNET_MQ_msg(em, GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT_END); + em->r_id = htonl(zi->request_id); + GNUNET_MQ_send(zi->nc->mq, env); - GNUNET_CONTAINER_DLL_remove (zi->nc->op_head, zi->nc->op_tail, zi); - GNUNET_free (zi); + GNUNET_CONTAINER_DLL_remove(zi->nc->op_head, zi->nc->op_tail, zi); + GNUNET_free(zi); } @@ -856,30 +848,30 @@ zone_iteration_done_client_continue (struct ZoneIteration *zi) * @param emsg error messages */ static void -finish_cache_operation (void *cls, int32_t success, const char *emsg) +finish_cache_operation(void *cls, int32_t success, const char *emsg) { struct CacheOperation *cop = cls; struct ZoneIteration *zi; if (NULL != emsg) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to replicate block in namecache: %s\n"), - emsg); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to replicate block in namecache: %s\n"), + emsg); else - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "CACHE operation completed\n"); - GNUNET_CONTAINER_DLL_remove (cop_head, cop_tail, cop); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "CACHE operation completed\n"); + GNUNET_CONTAINER_DLL_remove(cop_head, cop_tail, cop); if (NULL != cop->nc) - send_store_response (cop->nc, success, cop->rid); + send_store_response(cop->nc, success, cop->rid); if (NULL != (zi = cop->zi)) - { - zi->cache_ops--; - if (0 == zi->cache_ops) { - /* unchoke zone iteration, cache has caught up */ - zone_iteration_done_client_continue (zi); + zi->cache_ops--; + if (0 == zi->cache_ops) + { + /* unchoke zone iteration, cache has caught up */ + zone_iteration_done_client_continue(zi); + } } - } - GNUNET_free (cop); + GNUNET_free(cop); } @@ -896,13 +888,13 @@ finish_cache_operation (void *cls, int32_t success, const char *emsg) * @param rd records stored under the given @a name */ static void -refresh_block (struct NamestoreClient *nc, - struct ZoneIteration *zi, - uint32_t rid, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *name, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +refresh_block(struct NamestoreClient *nc, + struct ZoneIteration *zi, + uint32_t rid, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *name, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_GNSRECORD_Block *block; struct CacheOperation *cop; @@ -912,64 +904,64 @@ refresh_block (struct NamestoreClient *nc, unsigned int res_count; struct GNUNET_TIME_Absolute exp_time; - nick = get_nick_record (zone_key); + nick = get_nick_record(zone_key); res_count = rd_count; - res = (struct GNUNET_GNSRECORD_Data *) rd; /* fixme: a bit unclean... */ + res = (struct GNUNET_GNSRECORD_Data *)rd; /* fixme: a bit unclean... */ if (NULL != nick) - { - nick->flags = - (nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE; - merge_with_nick_records (nick, rd_count, rd, &res_count, &res); - GNUNET_free (nick); - } + { + nick->flags = + (nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ GNUNET_GNSRECORD_RF_PRIVATE; + merge_with_nick_records(nick, rd_count, rd, &res_count, &res); + GNUNET_free(nick); + } if (0 == res_count) - { - if (NULL != nc) - send_store_response (nc, GNUNET_OK, rid); - return; /* no data, no need to update cache */ - } + { + if (NULL != nc) + send_store_response(nc, GNUNET_OK, rid); + return; /* no data, no need to update cache */ + } if (GNUNET_YES == disable_namecache) - { - GNUNET_STATISTICS_update (statistics, - "Namecache updates skipped (NC disabled)", - 1, - GNUNET_NO); - if (NULL != nc) - send_store_response (nc, GNUNET_OK, rid); - return; - } - exp_time = GNUNET_GNSRECORD_record_get_expiration_time (res_count, res); + { + GNUNET_STATISTICS_update(statistics, + "Namecache updates skipped (NC disabled)", + 1, + GNUNET_NO); + if (NULL != nc) + send_store_response(nc, GNUNET_OK, rid); + return; + } + exp_time = GNUNET_GNSRECORD_record_get_expiration_time(res_count, res); if (cache_keys) block = - GNUNET_GNSRECORD_block_create2 (zone_key, exp_time, name, res, res_count); + GNUNET_GNSRECORD_block_create2(zone_key, exp_time, name, res, res_count); else block = - GNUNET_GNSRECORD_block_create (zone_key, exp_time, name, res, res_count); - GNUNET_assert (NULL != block); - GNUNET_CRYPTO_ecdsa_key_get_public (zone_key, &pkey); - GNUNET_log ( + GNUNET_GNSRECORD_block_create(zone_key, exp_time, name, res, res_count); + GNUNET_assert(NULL != block); + GNUNET_CRYPTO_ecdsa_key_get_public(zone_key, &pkey); + GNUNET_log( GNUNET_ERROR_TYPE_DEBUG, "Caching block for label `%s' with %u records and expiration %s in zone `%s' in namecache\n", name, res_count, - GNUNET_STRINGS_absolute_time_to_string (exp_time), - GNUNET_GNSRECORD_z2s (&pkey)); - GNUNET_STATISTICS_update (statistics, - "Namecache updates pushed", - 1, - GNUNET_NO); - cop = GNUNET_new (struct CacheOperation); + GNUNET_STRINGS_absolute_time_to_string(exp_time), + GNUNET_GNSRECORD_z2s(&pkey)); + GNUNET_STATISTICS_update(statistics, + "Namecache updates pushed", + 1, + GNUNET_NO); + cop = GNUNET_new(struct CacheOperation); cop->nc = nc; cop->zi = zi; if (NULL != zi) zi->cache_ops++; cop->rid = rid; - GNUNET_CONTAINER_DLL_insert (cop_head, cop_tail, cop); - cop->qe = GNUNET_NAMECACHE_block_cache (namecache, - block, - &finish_cache_operation, - cop); - GNUNET_free (block); + GNUNET_CONTAINER_DLL_insert(cop_head, cop_tail, cop); + cop->qe = GNUNET_NAMECACHE_block_cache(namecache, + block, + &finish_cache_operation, + cop); + GNUNET_free(block); } @@ -979,16 +971,16 @@ refresh_block (struct NamestoreClient *nc, * @param cls a `struct ZoneMonitor` to warn about */ static void -warn_monitor_slow (void *cls) +warn_monitor_slow(void *cls) { struct ZoneMonitor *zm = cls; - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "No response from monitor since %s\n", - GNUNET_STRINGS_absolute_time_to_string (zm->sa_waiting_start)); - zm->sa_wait_warning = GNUNET_SCHEDULER_add_delayed (MONITOR_STALL_WARN_DELAY, - &warn_monitor_slow, - zm); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "No response from monitor since %s\n", + GNUNET_STRINGS_absolute_time_to_string(zm->sa_waiting_start)); + zm->sa_wait_warning = GNUNET_SCHEDULER_add_delayed(MONITOR_STALL_WARN_DELAY, + &warn_monitor_slow, + zm); } @@ -998,7 +990,7 @@ warn_monitor_slow (void *cls) * @param sa store activity to process */ static void -continue_store_activity (struct StoreActivity *sa) +continue_store_activity(struct StoreActivity *sa) { const struct RecordStoreMessage *rp_msg = sa->rsm; unsigned int rd_count; @@ -1008,63 +1000,63 @@ continue_store_activity (struct StoreActivity *sa) const char *name_tmp; const char *rd_ser; - rid = ntohl (rp_msg->gns_header.r_id); - name_len = ntohs (rp_msg->name_len); - rd_count = ntohs (rp_msg->rd_count); - rd_ser_len = ntohs (rp_msg->rd_len); - name_tmp = (const char *) &rp_msg[1]; + rid = ntohl(rp_msg->gns_header.r_id); + name_len = ntohs(rp_msg->name_len); + rd_count = ntohs(rp_msg->rd_count); + rd_ser_len = ntohs(rp_msg->rd_len); + name_tmp = (const char *)&rp_msg[1]; rd_ser = &name_tmp[name_len]; { - struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL (rd_count)]; + struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL(rd_count)]; /* We did this before, must succeed again */ - GNUNET_assert ( + GNUNET_assert( GNUNET_OK == - GNUNET_GNSRECORD_records_deserialize (rd_ser_len, rd_ser, rd_count, rd)); + GNUNET_GNSRECORD_records_deserialize(rd_ser_len, rd_ser, rd_count, rd)); for (struct ZoneMonitor *zm = sa->zm_pos; NULL != zm; zm = sa->zm_pos) - { - if ((0 != GNUNET_memcmp (&rp_msg->private_key, &zm->zone)) && - (0 != GNUNET_memcmp (&zm->zone, &zero))) - { - sa->zm_pos = zm->next; /* not interesting to this monitor */ - continue; - } - if (zm->limit == zm->iteration_cnt) { - zm->sa_waiting = GNUNET_YES; - zm->sa_waiting_start = GNUNET_TIME_absolute_get (); - if (NULL != zm->sa_wait_warning) - GNUNET_SCHEDULER_cancel (zm->sa_wait_warning); - zm->sa_wait_warning = - GNUNET_SCHEDULER_add_delayed (MONITOR_STALL_WARN_DELAY, - &warn_monitor_slow, - zm); - return; /* blocked on zone monitor */ + if ((0 != GNUNET_memcmp(&rp_msg->private_key, &zm->zone)) && + (0 != GNUNET_memcmp(&zm->zone, &zero))) + { + sa->zm_pos = zm->next; /* not interesting to this monitor */ + continue; + } + if (zm->limit == zm->iteration_cnt) + { + zm->sa_waiting = GNUNET_YES; + zm->sa_waiting_start = GNUNET_TIME_absolute_get(); + if (NULL != zm->sa_wait_warning) + GNUNET_SCHEDULER_cancel(zm->sa_wait_warning); + zm->sa_wait_warning = + GNUNET_SCHEDULER_add_delayed(MONITOR_STALL_WARN_DELAY, + &warn_monitor_slow, + zm); + return; /* blocked on zone monitor */ + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Notifying monitor about changes under label `%s'\n", + sa->conv_name); + zm->limit--; + send_lookup_response(zm->nc, + 0, + &rp_msg->private_key, + sa->conv_name, + rd_count, + rd); + sa->zm_pos = zm->next; } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Notifying monitor about changes under label `%s'\n", - sa->conv_name); - zm->limit--; - send_lookup_response (zm->nc, - 0, - &rp_msg->private_key, - sa->conv_name, - rd_count, - rd); - sa->zm_pos = zm->next; - } /* great, done with the monitors, unpack (again) for refresh_block operation */ - refresh_block (sa->nc, - NULL, - rid, - &rp_msg->private_key, - sa->conv_name, - rd_count, - rd); + refresh_block(sa->nc, + NULL, + rid, + &rp_msg->private_key, + sa->conv_name, + rd_count, + rd); } - GNUNET_SERVICE_client_continue (sa->nc->client); - free_store_activity (sa); + GNUNET_SERVICE_client_continue(sa->nc->client); + free_store_activity(sa); } @@ -1077,64 +1069,64 @@ continue_store_activity (struct StoreActivity *sa) * @param app_ctx the `struct NamestoreClient` of @a client */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { struct NamestoreClient *nc = app_ctx; struct ZoneIteration *no; struct CacheOperation *cop; - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p disconnected\n", client); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Client %p disconnected\n", client); for (struct ZoneMonitor *zm = monitor_head; NULL != zm; zm = zm->next) - { - struct StoreActivity *san; - - if (nc != zm->nc) - continue; - GNUNET_CONTAINER_DLL_remove (monitor_head, monitor_tail, zm); - if (NULL != zm->task) { - GNUNET_SCHEDULER_cancel (zm->task); - zm->task = NULL; - } - if (NULL != zm->sa_wait_warning) - { - GNUNET_SCHEDULER_cancel (zm->sa_wait_warning); - zm->sa_wait_warning = NULL; - } - for (struct StoreActivity *sa = sa_head; NULL != sa; sa = san) - { - san = sa->next; - if (zm == sa->zm_pos) - { - sa->zm_pos = zm->next; - /* this may free sa */ - continue_store_activity (sa); - } + struct StoreActivity *san; + + if (nc != zm->nc) + continue; + GNUNET_CONTAINER_DLL_remove(monitor_head, monitor_tail, zm); + if (NULL != zm->task) + { + GNUNET_SCHEDULER_cancel(zm->task); + zm->task = NULL; + } + if (NULL != zm->sa_wait_warning) + { + GNUNET_SCHEDULER_cancel(zm->sa_wait_warning); + zm->sa_wait_warning = NULL; + } + for (struct StoreActivity *sa = sa_head; NULL != sa; sa = san) + { + san = sa->next; + if (zm == sa->zm_pos) + { + sa->zm_pos = zm->next; + /* this may free sa */ + continue_store_activity(sa); + } + } + GNUNET_free(zm); + break; } - GNUNET_free (zm); - break; - } for (struct StoreActivity *sa = sa_head; NULL != sa; sa = sa->next) - { - if (sa->nc == nc) { - /* this may free sa */ - free_store_activity (sa); - break; /* there can only be one per nc */ + if (sa->nc == nc) + { + /* this may free sa */ + free_store_activity(sa); + break; /* there can only be one per nc */ + } } - } while (NULL != (no = nc->op_head)) - { - GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, no); - GNUNET_free (no); - } + { + GNUNET_CONTAINER_DLL_remove(nc->op_head, nc->op_tail, no); + GNUNET_free(no); + } for (cop = cop_head; NULL != cop; cop = cop->next) if (nc == cop->nc) cop->nc = NULL; - GNUNET_free (nc); + GNUNET_free(nc); } @@ -1147,15 +1139,15 @@ client_disconnect_cb (void *cls, * @return internal namestore client structure for this client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { struct NamestoreClient *nc; - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p connected\n", client); - nc = GNUNET_new (struct NamestoreClient); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Client %p connected\n", client); + nc = GNUNET_new(struct NamestoreClient); nc->client = client; nc->mq = mq; return nc; @@ -1165,9 +1157,7 @@ client_connect_cb (void *cls, /** * Closure for #lookup_it(). */ -struct RecordLookupContext -{ - +struct RecordLookupContext { /** * FIXME. */ @@ -1213,93 +1203,93 @@ struct RecordLookupContext * @param rd array of records with data to store */ static void -lookup_it (void *cls, - uint64_t seq, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +lookup_it(void *cls, + uint64_t seq, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct RecordLookupContext *rlc = cls; - (void) private_key; - GNUNET_assert (0 != seq); - if (0 != strcmp (label, rlc->label)) + (void)private_key; + GNUNET_assert(0 != seq); + if (0 != strcmp(label, rlc->label)) return; rlc->found = GNUNET_YES; if (0 == rd_count) - { - rlc->rd_ser_len = 0; - rlc->res_rd_count = 0; - rlc->res_rd = NULL; - return; - } - if ((NULL != rlc->nick) && (0 != strcmp (label, GNUNET_GNS_EMPTY_LABEL_AT))) - { - /* Merge */ - struct GNUNET_GNSRECORD_Data *rd_res; - unsigned int rdc_res; - - rd_res = NULL; - rdc_res = 0; - rlc->nick->flags = (rlc->nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ - GNUNET_GNSRECORD_RF_PRIVATE; - merge_with_nick_records (rlc->nick, rd_count, rd, &rdc_res, &rd_res); - rlc->rd_ser_len = GNUNET_GNSRECORD_records_get_size (rdc_res, rd_res); - if (rlc->rd_ser_len < 0) { - GNUNET_break (0); - GNUNET_free (rd_res); - rlc->found = GNUNET_NO; rlc->rd_ser_len = 0; - return; - } - rlc->res_rd_count = rdc_res; - rlc->res_rd = GNUNET_malloc (rlc->rd_ser_len); - if (rlc->rd_ser_len != GNUNET_GNSRECORD_records_serialize (rdc_res, - rd_res, - rlc->rd_ser_len, - rlc->res_rd)) - { - GNUNET_break (0); - GNUNET_free (rlc->res_rd); - rlc->res_rd = NULL; rlc->res_rd_count = 0; - rlc->rd_ser_len = 0; - GNUNET_free (rd_res); - rlc->found = GNUNET_NO; + rlc->res_rd = NULL; return; } - GNUNET_free (rd_res); - GNUNET_free (rlc->nick); - rlc->nick = NULL; - } - else - { - rlc->rd_ser_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd); - if (rlc->rd_ser_len < 0) + if ((NULL != rlc->nick) && (0 != strcmp(label, GNUNET_GNS_EMPTY_LABEL_AT))) { - GNUNET_break (0); - rlc->found = GNUNET_NO; - rlc->rd_ser_len = 0; - return; + /* Merge */ + struct GNUNET_GNSRECORD_Data *rd_res; + unsigned int rdc_res; + + rd_res = NULL; + rdc_res = 0; + rlc->nick->flags = (rlc->nick->flags | GNUNET_GNSRECORD_RF_PRIVATE) ^ + GNUNET_GNSRECORD_RF_PRIVATE; + merge_with_nick_records(rlc->nick, rd_count, rd, &rdc_res, &rd_res); + rlc->rd_ser_len = GNUNET_GNSRECORD_records_get_size(rdc_res, rd_res); + if (rlc->rd_ser_len < 0) + { + GNUNET_break(0); + GNUNET_free(rd_res); + rlc->found = GNUNET_NO; + rlc->rd_ser_len = 0; + return; + } + rlc->res_rd_count = rdc_res; + rlc->res_rd = GNUNET_malloc(rlc->rd_ser_len); + if (rlc->rd_ser_len != GNUNET_GNSRECORD_records_serialize(rdc_res, + rd_res, + rlc->rd_ser_len, + rlc->res_rd)) + { + GNUNET_break(0); + GNUNET_free(rlc->res_rd); + rlc->res_rd = NULL; + rlc->res_rd_count = 0; + rlc->rd_ser_len = 0; + GNUNET_free(rd_res); + rlc->found = GNUNET_NO; + return; + } + GNUNET_free(rd_res); + GNUNET_free(rlc->nick); + rlc->nick = NULL; } - rlc->res_rd_count = rd_count; - rlc->res_rd = GNUNET_malloc (rlc->rd_ser_len); - if (rlc->rd_ser_len != GNUNET_GNSRECORD_records_serialize (rd_count, - rd, - rlc->rd_ser_len, - rlc->res_rd)) + else { - GNUNET_break (0); - GNUNET_free (rlc->res_rd); - rlc->res_rd = NULL; - rlc->res_rd_count = 0; - rlc->rd_ser_len = 0; - rlc->found = GNUNET_NO; - return; + rlc->rd_ser_len = GNUNET_GNSRECORD_records_get_size(rd_count, rd); + if (rlc->rd_ser_len < 0) + { + GNUNET_break(0); + rlc->found = GNUNET_NO; + rlc->rd_ser_len = 0; + return; + } + rlc->res_rd_count = rd_count; + rlc->res_rd = GNUNET_malloc(rlc->rd_ser_len); + if (rlc->rd_ser_len != GNUNET_GNSRECORD_records_serialize(rd_count, + rd, + rlc->rd_ser_len, + rlc->res_rd)) + { + GNUNET_break(0); + GNUNET_free(rlc->res_rd); + rlc->res_rd = NULL; + rlc->res_rd_count = 0; + rlc->rd_ser_len = 0; + rlc->found = GNUNET_NO; + return; + } } - } } @@ -1311,20 +1301,20 @@ lookup_it (void *cls, * @return #GNUNET_OK if @a ll_msg is well-formed */ static int -check_record_lookup (void *cls, const struct LabelLookupMessage *ll_msg) +check_record_lookup(void *cls, const struct LabelLookupMessage *ll_msg) { uint32_t name_len; size_t src_size; - (void) cls; - name_len = ntohl (ll_msg->label_len); - src_size = ntohs (ll_msg->gns_header.header.size); - if (name_len != src_size - sizeof (struct LabelLookupMessage)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - GNUNET_MQ_check_zero_termination (ll_msg); + (void)cls; + name_len = ntohl(ll_msg->label_len); + src_size = ntohs(ll_msg->gns_header.header.size); + if (name_len != src_size - sizeof(struct LabelLookupMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + GNUNET_MQ_check_zero_termination(ll_msg); return GNUNET_OK; } @@ -1336,7 +1326,7 @@ check_record_lookup (void *cls, const struct LabelLookupMessage *ll_msg) * @param ll_msg message of type `struct LabelLookupMessage` */ static void -handle_record_lookup (void *cls, const struct LabelLookupMessage *ll_msg) +handle_record_lookup(void *cls, const struct LabelLookupMessage *ll_msg) { struct NamestoreClient *nc = cls; struct GNUNET_MQ_Envelope *env; @@ -1348,52 +1338,52 @@ handle_record_lookup (void *cls, const struct LabelLookupMessage *ll_msg) uint32_t name_len; int res; - name_len = ntohl (ll_msg->label_len); - name_tmp = (const char *) &ll_msg[1]; - GNUNET_SERVICE_client_continue (nc->client); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received NAMESTORE_RECORD_LOOKUP message for name `%s'\n", - name_tmp); + name_len = ntohl(ll_msg->label_len); + name_tmp = (const char *)&ll_msg[1]; + GNUNET_SERVICE_client_continue(nc->client); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received NAMESTORE_RECORD_LOOKUP message for name `%s'\n", + name_tmp); - conv_name = GNUNET_GNSRECORD_string_to_lowercase (name_tmp); + conv_name = GNUNET_GNSRECORD_string_to_lowercase(name_tmp); if (NULL == conv_name) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error converting name `%s'\n", - name_tmp); - GNUNET_SERVICE_client_drop (nc->client); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error converting name `%s'\n", + name_tmp); + GNUNET_SERVICE_client_drop(nc->client); + return; + } rlc.label = conv_name; rlc.found = GNUNET_NO; rlc.res_rd_count = 0; rlc.res_rd = NULL; rlc.rd_ser_len = 0; - rlc.nick = get_nick_record (&ll_msg->zone); - res = GSN_database->lookup_records (GSN_database->cls, - &ll_msg->zone, - conv_name, - &lookup_it, - &rlc); - GNUNET_free (conv_name); + rlc.nick = get_nick_record(&ll_msg->zone); + res = GSN_database->lookup_records(GSN_database->cls, + &ll_msg->zone, + conv_name, + &lookup_it, + &rlc); + GNUNET_free(conv_name); env = - GNUNET_MQ_msg_extra (llr_msg, - name_len + rlc.rd_ser_len, - GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP_RESPONSE); + GNUNET_MQ_msg_extra(llr_msg, + name_len + rlc.rd_ser_len, + GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP_RESPONSE); llr_msg->gns_header.r_id = ll_msg->gns_header.r_id; llr_msg->private_key = ll_msg->zone; - llr_msg->name_len = htons (name_len); - llr_msg->rd_count = htons (rlc.res_rd_count); - llr_msg->rd_len = htons (rlc.rd_ser_len); - res_name = (char *) &llr_msg[1]; + llr_msg->name_len = htons(name_len); + llr_msg->rd_count = htons(rlc.res_rd_count); + llr_msg->rd_len = htons(rlc.rd_ser_len); + res_name = (char *)&llr_msg[1]; if ((GNUNET_YES == rlc.found) && (GNUNET_OK == res)) - llr_msg->found = ntohs (GNUNET_YES); + llr_msg->found = ntohs(GNUNET_YES); else - llr_msg->found = ntohs (GNUNET_NO); - GNUNET_memcpy (&llr_msg[1], name_tmp, name_len); - GNUNET_memcpy (&res_name[name_len], rlc.res_rd, rlc.rd_ser_len); - GNUNET_MQ_send (nc->mq, env); - GNUNET_free_non_null (rlc.res_rd); + llr_msg->found = ntohs(GNUNET_NO); + GNUNET_memcpy(&llr_msg[1], name_tmp, name_len); + GNUNET_memcpy(&res_name[name_len], rlc.res_rd, rlc.rd_ser_len); + GNUNET_MQ_send(nc->mq, env); + GNUNET_free_non_null(rlc.res_rd); } @@ -1405,7 +1395,7 @@ handle_record_lookup (void *cls, const struct LabelLookupMessage *ll_msg) * @return #GNUNET_OK if @a rp_msg is well-formed */ static int -check_record_store (void *cls, const struct RecordStoreMessage *rp_msg) +check_record_store(void *cls, const struct RecordStoreMessage *rp_msg) { size_t name_len; size_t msg_size; @@ -1413,27 +1403,27 @@ check_record_store (void *cls, const struct RecordStoreMessage *rp_msg) size_t rd_ser_len; const char *name_tmp; - (void) cls; - name_len = ntohs (rp_msg->name_len); - msg_size = ntohs (rp_msg->gns_header.header.size); - rd_ser_len = ntohs (rp_msg->rd_len); - msg_size_exp = sizeof (struct RecordStoreMessage) + name_len + rd_ser_len; + (void)cls; + name_len = ntohs(rp_msg->name_len); + msg_size = ntohs(rp_msg->gns_header.header.size); + rd_ser_len = ntohs(rp_msg->rd_len); + msg_size_exp = sizeof(struct RecordStoreMessage) + name_len + rd_ser_len; if (msg_size != msg_size_exp) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } if ((0 == name_len) || (name_len > MAX_NAME_LEN)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - name_tmp = (const char *) &rp_msg[1]; + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + name_tmp = (const char *)&rp_msg[1]; if ('\0' != name_tmp[name_len - 1]) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1445,7 +1435,7 @@ check_record_store (void *cls, const struct RecordStoreMessage *rp_msg) * @param rp_msg message of type `struct RecordStoreMessage` */ static void -handle_record_store (void *cls, const struct RecordStoreMessage *rp_msg) +handle_record_store(void *cls, const struct RecordStoreMessage *rp_msg) { struct NamestoreClient *nc = cls; size_t name_len; @@ -1458,112 +1448,112 @@ handle_record_store (void *cls, const struct RecordStoreMessage *rp_msg) int res; struct StoreActivity *sa; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received NAMESTORE_RECORD_STORE message\n"); - rid = ntohl (rp_msg->gns_header.r_id); - name_len = ntohs (rp_msg->name_len); - rd_count = ntohs (rp_msg->rd_count); - rd_ser_len = ntohs (rp_msg->rd_len); - GNUNET_break (0 == ntohs (rp_msg->reserved)); - name_tmp = (const char *) &rp_msg[1]; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received NAMESTORE_RECORD_STORE message\n"); + rid = ntohl(rp_msg->gns_header.r_id); + name_len = ntohs(rp_msg->name_len); + rd_count = ntohs(rp_msg->rd_count); + rd_ser_len = ntohs(rp_msg->rd_len); + GNUNET_break(0 == ntohs(rp_msg->reserved)); + name_tmp = (const char *)&rp_msg[1]; rd_ser = &name_tmp[name_len]; { - struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL (rd_count)]; + struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL(rd_count)]; if (GNUNET_OK != - GNUNET_GNSRECORD_records_deserialize (rd_ser_len, rd_ser, rd_count, rd)) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (nc->client); - return; - } + GNUNET_GNSRECORD_records_deserialize(rd_ser_len, rd_ser, rd_count, rd)) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(nc->client); + return; + } /* Extracting and converting private key */ - conv_name = GNUNET_GNSRECORD_string_to_lowercase (name_tmp); + conv_name = GNUNET_GNSRECORD_string_to_lowercase(name_tmp); if (NULL == conv_name) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error converting name `%s'\n", - name_tmp); - GNUNET_SERVICE_client_drop (nc->client); - return; - } - GNUNET_STATISTICS_update (statistics, - "Well-formed store requests received", - 1, - GNUNET_NO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Creating %u records for name `%s'\n", - (unsigned int) rd_count, - conv_name); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error converting name `%s'\n", + name_tmp); + GNUNET_SERVICE_client_drop(nc->client); + return; + } + GNUNET_STATISTICS_update(statistics, + "Well-formed store requests received", + 1, + GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Creating %u records for name `%s'\n", + (unsigned int)rd_count, + conv_name); if ((0 == rd_count) && - (GNUNET_NO == GSN_database->lookup_records (GSN_database->cls, - &rp_msg->private_key, - conv_name, - NULL, - 0))) - { - /* This name does not exist, so cannot be removed */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name `%s' does not exist, no deletion required\n", - conv_name); - res = GNUNET_NO; - } - else - { - /* remove "NICK" records, unless this is for the - #GNUNET_GNS_EMPTY_LABEL_AT label */ - struct GNUNET_GNSRECORD_Data rd_clean[GNUNET_NZL (rd_count)]; - unsigned int rd_clean_off; - int have_nick; - - rd_clean_off = 0; - have_nick = GNUNET_NO; - for (unsigned int i = 0; i < rd_count; i++) + (GNUNET_NO == GSN_database->lookup_records(GSN_database->cls, + &rp_msg->private_key, + conv_name, + NULL, + 0))) { - rd_clean[rd_clean_off] = rd[i]; - if ((0 == strcmp (GNUNET_GNS_EMPTY_LABEL_AT, conv_name)) || - (GNUNET_GNSRECORD_TYPE_NICK != rd[i].record_type)) - rd_clean_off++; - - if ((0 == strcmp (GNUNET_GNS_EMPTY_LABEL_AT, conv_name)) && - (GNUNET_GNSRECORD_TYPE_NICK == rd[i].record_type)) - { - cache_nick (&rp_msg->private_key, &rd[i]); - have_nick = GNUNET_YES; - } + /* This name does not exist, so cannot be removed */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name `%s' does not exist, no deletion required\n", + conv_name); + res = GNUNET_NO; } - if ((0 == strcmp (GNUNET_GNS_EMPTY_LABEL_AT, conv_name)) && - (GNUNET_NO == have_nick)) + else { - /* remove nick record from cache, in case we have one there */ - cache_nick (&rp_msg->private_key, NULL); + /* remove "NICK" records, unless this is for the + #GNUNET_GNS_EMPTY_LABEL_AT label */ + struct GNUNET_GNSRECORD_Data rd_clean[GNUNET_NZL(rd_count)]; + unsigned int rd_clean_off; + int have_nick; + + rd_clean_off = 0; + have_nick = GNUNET_NO; + for (unsigned int i = 0; i < rd_count; i++) + { + rd_clean[rd_clean_off] = rd[i]; + if ((0 == strcmp(GNUNET_GNS_EMPTY_LABEL_AT, conv_name)) || + (GNUNET_GNSRECORD_TYPE_NICK != rd[i].record_type)) + rd_clean_off++; + + if ((0 == strcmp(GNUNET_GNS_EMPTY_LABEL_AT, conv_name)) && + (GNUNET_GNSRECORD_TYPE_NICK == rd[i].record_type)) + { + cache_nick(&rp_msg->private_key, &rd[i]); + have_nick = GNUNET_YES; + } + } + if ((0 == strcmp(GNUNET_GNS_EMPTY_LABEL_AT, conv_name)) && + (GNUNET_NO == have_nick)) + { + /* remove nick record from cache, in case we have one there */ + cache_nick(&rp_msg->private_key, NULL); + } + res = GSN_database->store_records(GSN_database->cls, + &rp_msg->private_key, + conv_name, + rd_clean_off, + rd_clean); } - res = GSN_database->store_records (GSN_database->cls, - &rp_msg->private_key, - conv_name, - rd_clean_off, - rd_clean); - } if (GNUNET_OK != res) - { - /* store not successful, not need to tell monitors */ - send_store_response (nc, res, rid); - GNUNET_SERVICE_client_continue (nc->client); - GNUNET_free (conv_name); - return; - } + { + /* store not successful, not need to tell monitors */ + send_store_response(nc, res, rid); + GNUNET_SERVICE_client_continue(nc->client); + GNUNET_free(conv_name); + return; + } - sa = GNUNET_malloc (sizeof (struct StoreActivity) + - ntohs (rp_msg->gns_header.header.size)); - GNUNET_CONTAINER_DLL_insert (sa_head, sa_tail, sa); + sa = GNUNET_malloc(sizeof(struct StoreActivity) + + ntohs(rp_msg->gns_header.header.size)); + GNUNET_CONTAINER_DLL_insert(sa_head, sa_tail, sa); sa->nc = nc; - sa->rsm = (const struct RecordStoreMessage *) &sa[1]; - GNUNET_memcpy (&sa[1], rp_msg, ntohs (rp_msg->gns_header.header.size)); + sa->rsm = (const struct RecordStoreMessage *)&sa[1]; + GNUNET_memcpy(&sa[1], rp_msg, ntohs(rp_msg->gns_header.header.size)); sa->zm_pos = monitor_head; sa->conv_name = conv_name; - continue_store_activity (sa); + continue_store_activity(sa); } } @@ -1572,8 +1562,7 @@ handle_record_store (void *cls, const struct RecordStoreMessage *rp_msg) * Context for record remove operations passed from #handle_zone_to_name to * #handle_zone_to_name_it as closure */ -struct ZoneToNameCtx -{ +struct ZoneToNameCtx { /** * Namestore client */ @@ -1604,12 +1593,12 @@ struct ZoneToNameCtx * @param rd record data */ static void -handle_zone_to_name_it (void *cls, - uint64_t seq, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *name, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +handle_zone_to_name_it(void *cls, + uint64_t seq, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *name, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct ZoneToNameCtx *ztn_ctx = cls; struct GNUNET_MQ_Envelope *env; @@ -1621,45 +1610,45 @@ handle_zone_to_name_it (void *cls, char *name_tmp; char *rd_tmp; - GNUNET_assert (0 != seq); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found result for zone-to-name lookup: `%s'\n", - name); + GNUNET_assert(0 != seq); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found result for zone-to-name lookup: `%s'\n", + name); res = GNUNET_YES; - name_len = (NULL == name) ? 0 : strlen (name) + 1; - rd_ser_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd); + name_len = (NULL == name) ? 0 : strlen(name) + 1; + rd_ser_len = GNUNET_GNSRECORD_records_get_size(rd_count, rd); if (rd_ser_len < 0) - { - GNUNET_break (0); - ztn_ctx->success = GNUNET_SYSERR; - return; - } - msg_size = sizeof (struct ZoneToNameResponseMessage) + name_len + rd_ser_len; + { + GNUNET_break(0); + ztn_ctx->success = GNUNET_SYSERR; + return; + } + msg_size = sizeof(struct ZoneToNameResponseMessage) + name_len + rd_ser_len; if (msg_size >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - ztn_ctx->success = GNUNET_SYSERR; - return; - } + { + GNUNET_break(0); + ztn_ctx->success = GNUNET_SYSERR; + return; + } env = - GNUNET_MQ_msg_extra (ztnr_msg, - name_len + rd_ser_len, - GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE); - ztnr_msg->gns_header.header.size = htons (msg_size); - ztnr_msg->gns_header.r_id = htonl (ztn_ctx->rid); - ztnr_msg->res = htons (res); - ztnr_msg->rd_len = htons (rd_ser_len); - ztnr_msg->rd_count = htons (rd_count); - ztnr_msg->name_len = htons (name_len); + GNUNET_MQ_msg_extra(ztnr_msg, + name_len + rd_ser_len, + GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE); + ztnr_msg->gns_header.header.size = htons(msg_size); + ztnr_msg->gns_header.r_id = htonl(ztn_ctx->rid); + ztnr_msg->res = htons(res); + ztnr_msg->rd_len = htons(rd_ser_len); + ztnr_msg->rd_count = htons(rd_count); + ztnr_msg->name_len = htons(name_len); ztnr_msg->zone = *zone_key; - name_tmp = (char *) &ztnr_msg[1]; - GNUNET_memcpy (name_tmp, name, name_len); + name_tmp = (char *)&ztnr_msg[1]; + GNUNET_memcpy(name_tmp, name, name_len); rd_tmp = &name_tmp[name_len]; - GNUNET_assert ( + GNUNET_assert( rd_ser_len == - GNUNET_GNSRECORD_records_serialize (rd_count, rd, rd_ser_len, rd_tmp)); + GNUNET_GNSRECORD_records_serialize(rd_count, rd, rd_ser_len, rd_tmp)); ztn_ctx->success = GNUNET_OK; - GNUNET_MQ_send (ztn_ctx->nc->mq, env); + GNUNET_MQ_send(ztn_ctx->nc->mq, env); } @@ -1670,41 +1659,41 @@ handle_zone_to_name_it (void *cls, * @param ztn_msg message of type 'struct ZoneToNameMessage' */ static void -handle_zone_to_name (void *cls, const struct ZoneToNameMessage *ztn_msg) +handle_zone_to_name(void *cls, const struct ZoneToNameMessage *ztn_msg) { struct NamestoreClient *nc = cls; struct ZoneToNameCtx ztn_ctx; struct GNUNET_MQ_Envelope *env; struct ZoneToNameResponseMessage *ztnr_msg; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received ZONE_TO_NAME message\n"); - ztn_ctx.rid = ntohl (ztn_msg->gns_header.r_id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received ZONE_TO_NAME message\n"); + ztn_ctx.rid = ntohl(ztn_msg->gns_header.r_id); ztn_ctx.nc = nc; ztn_ctx.success = GNUNET_NO; - if (GNUNET_SYSERR == GSN_database->zone_to_name (GSN_database->cls, - &ztn_msg->zone, - &ztn_msg->value_zone, - &handle_zone_to_name_it, - &ztn_ctx)) - { - /* internal error, hang up instead of signalling something - that might be wrong */ - GNUNET_break (0); - GNUNET_SERVICE_client_drop (nc->client); - return; - } + if (GNUNET_SYSERR == GSN_database->zone_to_name(GSN_database->cls, + &ztn_msg->zone, + &ztn_msg->value_zone, + &handle_zone_to_name_it, + &ztn_ctx)) + { + /* internal error, hang up instead of signalling something + that might be wrong */ + GNUNET_break(0); + GNUNET_SERVICE_client_drop(nc->client); + return; + } if (GNUNET_NO == ztn_ctx.success) - { - /* no result found, send empty response */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found no result for zone-to-name lookup.\n"); - env = GNUNET_MQ_msg (ztnr_msg, - GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE); - ztnr_msg->gns_header.r_id = ztn_msg->gns_header.r_id; - ztnr_msg->res = htons (GNUNET_NO); - GNUNET_MQ_send (nc->mq, env); - } - GNUNET_SERVICE_client_continue (nc->client); + { + /* no result found, send empty response */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found no result for zone-to-name lookup.\n"); + env = GNUNET_MQ_msg(ztnr_msg, + GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE); + ztnr_msg->gns_header.r_id = ztn_msg->gns_header.r_id; + ztnr_msg->res = htons(GNUNET_NO); + GNUNET_MQ_send(nc->mq, env); + } + GNUNET_SERVICE_client_continue(nc->client); } @@ -1712,8 +1701,7 @@ handle_zone_to_name (void *cls, const struct ZoneToNameMessage *ztn_msg) * Context for record remove operations passed from * #run_zone_iteration_round to #zone_iterate_proc as closure */ -struct ZoneIterationProcResult -{ +struct ZoneIterationProcResult { /** * The zone iteration handle */ @@ -1737,53 +1725,53 @@ struct ZoneIterationProcResult * @param rd record data */ static void -zone_iterate_proc (void *cls, - uint64_t seq, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *name, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +zone_iterate_proc(void *cls, + uint64_t seq, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *name, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct ZoneIterationProcResult *proc = cls; int do_refresh_block; - GNUNET_assert (0 != seq); + GNUNET_assert(0 != seq); if ((NULL == zone_key) && (NULL == name)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Iteration done\n"); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Iteration done\n"); + return; + } if ((NULL == zone_key) || (NULL == name)) - { - /* what is this!? should never happen */ - GNUNET_break (0); - return; - } + { + /* what is this!? should never happen */ + GNUNET_break(0); + return; + } if (0 == proc->limit) - { - /* what is this!? should never happen */ - GNUNET_break (0); - return; - } + { + /* what is this!? should never happen */ + GNUNET_break(0); + return; + } proc->limit--; proc->zi->seq = seq; - send_lookup_response (proc->zi->nc, - proc->zi->request_id, - zone_key, - name, - rd_count, - rd); + send_lookup_response(proc->zi->nc, + proc->zi->request_id, + zone_key, + name, + rd_count, + rd); do_refresh_block = GNUNET_NO; for (unsigned int i = 0; i < rd_count; i++) if (0 != (rd[i].flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) - { - do_refresh_block = GNUNET_YES; - break; - } + { + do_refresh_block = GNUNET_YES; + break; + } if (GNUNET_YES == do_refresh_block) - refresh_block (NULL, proc->zi, 0, zone_key, name, rd_count, rd); + refresh_block(NULL, proc->zi, 0, zone_key, name, rd_count, rd); } @@ -1794,42 +1782,42 @@ zone_iterate_proc (void *cls, * @param limit number of results to return in one pass */ static void -run_zone_iteration_round (struct ZoneIteration *zi, uint64_t limit) +run_zone_iteration_round(struct ZoneIteration *zi, uint64_t limit) { struct ZoneIterationProcResult proc; struct GNUNET_TIME_Absolute start; struct GNUNET_TIME_Relative duration; - memset (&proc, 0, sizeof (proc)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Asked to return up to %llu records at position %llu\n", - (unsigned long long) limit, - (unsigned long long) zi->seq); + memset(&proc, 0, sizeof(proc)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Asked to return up to %llu records at position %llu\n", + (unsigned long long)limit, + (unsigned long long)zi->seq); proc.zi = zi; proc.limit = limit; - start = GNUNET_TIME_absolute_get (); - GNUNET_break (GNUNET_SYSERR != - GSN_database->iterate_records (GSN_database->cls, - (0 == GNUNET_is_zero (&zi->zone)) - ? NULL - : &zi->zone, - zi->seq, - limit, - &zone_iterate_proc, - &proc)); - duration = GNUNET_TIME_absolute_get_duration (start); - duration = GNUNET_TIME_relative_divide (duration, limit - proc.limit); - GNUNET_STATISTICS_set (statistics, - "NAMESTORE iteration delay (μs/record)", - duration.rel_value_us, - GNUNET_NO); + start = GNUNET_TIME_absolute_get(); + GNUNET_break(GNUNET_SYSERR != + GSN_database->iterate_records(GSN_database->cls, + (0 == GNUNET_is_zero(&zi->zone)) + ? NULL + : &zi->zone, + zi->seq, + limit, + &zone_iterate_proc, + &proc)); + duration = GNUNET_TIME_absolute_get_duration(start); + duration = GNUNET_TIME_relative_divide(duration, limit - proc.limit); + GNUNET_STATISTICS_set(statistics, + "NAMESTORE iteration delay (μs/record)", + duration.rel_value_us, + GNUNET_NO); if (0 == proc.limit) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Returned %llu results, more results available\n", - (unsigned long long) limit); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Returned %llu results, more results available\n", + (unsigned long long)limit); zi->send_end = (0 != proc.limit); if (0 == zi->cache_ops) - zone_iteration_done_client_continue (zi); + zone_iteration_done_client_continue(zi); } @@ -1840,22 +1828,22 @@ run_zone_iteration_round (struct ZoneIteration *zi, uint64_t limit) * @param zis_msg message from the client */ static void -handle_iteration_start (void *cls, - const struct ZoneIterationStartMessage *zis_msg) +handle_iteration_start(void *cls, + const struct ZoneIterationStartMessage *zis_msg) { struct NamestoreClient *nc = cls; struct ZoneIteration *zi; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ZONE_ITERATION_START message\n"); - zi = GNUNET_new (struct ZoneIteration); - zi->request_id = ntohl (zis_msg->gns_header.r_id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ZONE_ITERATION_START message\n"); + zi = GNUNET_new(struct ZoneIteration); + zi->request_id = ntohl(zis_msg->gns_header.r_id); zi->offset = 0; zi->nc = nc; zi->zone = zis_msg->zone; - GNUNET_CONTAINER_DLL_insert (nc->op_head, nc->op_tail, zi); - run_zone_iteration_round (zi, 1); + GNUNET_CONTAINER_DLL_insert(nc->op_head, nc->op_tail, zi); + run_zone_iteration_round(zi, 1); } @@ -1866,28 +1854,28 @@ handle_iteration_start (void *cls, * @param zis_msg message from the client */ static void -handle_iteration_stop (void *cls, - const struct ZoneIterationStopMessage *zis_msg) +handle_iteration_stop(void *cls, + const struct ZoneIterationStopMessage *zis_msg) { struct NamestoreClient *nc = cls; struct ZoneIteration *zi; uint32_t rid; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ZONE_ITERATION_STOP message\n"); - rid = ntohl (zis_msg->gns_header.r_id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ZONE_ITERATION_STOP message\n"); + rid = ntohl(zis_msg->gns_header.r_id); for (zi = nc->op_head; NULL != zi; zi = zi->next) if (zi->request_id == rid) break; if (NULL == zi) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (nc->client); - return; - } - GNUNET_CONTAINER_DLL_remove (nc->op_head, nc->op_tail, zi); - GNUNET_free (zi); - GNUNET_SERVICE_client_continue (nc->client); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(nc->client); + return; + } + GNUNET_CONTAINER_DLL_remove(nc->op_head, nc->op_tail, zi); + GNUNET_free(zi); + GNUNET_SERVICE_client_continue(nc->client); } @@ -1898,32 +1886,32 @@ handle_iteration_stop (void *cls, * @param message message from the client */ static void -handle_iteration_next (void *cls, - const struct ZoneIterationNextMessage *zis_msg) +handle_iteration_next(void *cls, + const struct ZoneIterationNextMessage *zis_msg) { struct NamestoreClient *nc = cls; struct ZoneIteration *zi; uint32_t rid; uint64_t limit; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ZONE_ITERATION_NEXT message\n"); - GNUNET_STATISTICS_update (statistics, - "Iteration NEXT messages received", - 1, - GNUNET_NO); - rid = ntohl (zis_msg->gns_header.r_id); - limit = GNUNET_ntohll (zis_msg->limit); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ZONE_ITERATION_NEXT message\n"); + GNUNET_STATISTICS_update(statistics, + "Iteration NEXT messages received", + 1, + GNUNET_NO); + rid = ntohl(zis_msg->gns_header.r_id); + limit = GNUNET_ntohll(zis_msg->limit); for (zi = nc->op_head; NULL != zi; zi = zi->next) if (zi->request_id == rid) break; if (NULL == zi) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (nc->client); - return; - } - run_zone_iteration_round (zi, limit); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(nc->client); + return; + } + run_zone_iteration_round(zi, limit); } @@ -1933,37 +1921,37 @@ handle_iteration_next (void *cls, * monitor not being ready. */ static void -monitor_unblock (struct ZoneMonitor *zm) +monitor_unblock(struct ZoneMonitor *zm) { struct StoreActivity *sa = sa_head; while ((NULL != sa) && (zm->limit > zm->iteration_cnt)) - { - struct StoreActivity *sn = sa->next; + { + struct StoreActivity *sn = sa->next; - if (sa->zm_pos == zm) - continue_store_activity (sa); - sa = sn; - } + if (sa->zm_pos == zm) + continue_store_activity(sa); + sa = sn; + } if (zm->limit > zm->iteration_cnt) - { - zm->sa_waiting = GNUNET_NO; - if (NULL != zm->sa_wait_warning) { - GNUNET_SCHEDULER_cancel (zm->sa_wait_warning); - zm->sa_wait_warning = NULL; + zm->sa_waiting = GNUNET_NO; + if (NULL != zm->sa_wait_warning) + { + GNUNET_SCHEDULER_cancel(zm->sa_wait_warning); + zm->sa_wait_warning = NULL; + } } - } else if (GNUNET_YES == zm->sa_waiting) - { - zm->sa_waiting_start = GNUNET_TIME_absolute_get (); - if (NULL != zm->sa_wait_warning) - GNUNET_SCHEDULER_cancel (zm->sa_wait_warning); - zm->sa_wait_warning = - GNUNET_SCHEDULER_add_delayed (MONITOR_STALL_WARN_DELAY, - &warn_monitor_slow, - zm); - } + { + zm->sa_waiting_start = GNUNET_TIME_absolute_get(); + if (NULL != zm->sa_wait_warning) + GNUNET_SCHEDULER_cancel(zm->sa_wait_warning); + zm->sa_wait_warning = + GNUNET_SCHEDULER_add_delayed(MONITOR_STALL_WARN_DELAY, + &warn_monitor_slow, + zm); + } } @@ -1973,18 +1961,18 @@ monitor_unblock (struct ZoneMonitor *zm) * @param zm monitor that is now in sync */ static void -monitor_sync (struct ZoneMonitor *zm) +monitor_sync(struct ZoneMonitor *zm) { struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *sync; - env = GNUNET_MQ_msg (sync, GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_SYNC); - GNUNET_MQ_send (zm->nc->mq, env); + env = GNUNET_MQ_msg(sync, GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_SYNC); + GNUNET_MQ_send(zm->nc->mq, env); /* mark iteration done */ zm->in_first_iteration = GNUNET_NO; zm->iteration_cnt = 0; if ((zm->limit > 0) && (zm->sa_waiting)) - monitor_unblock (zm); + monitor_unblock(zm); } @@ -1994,7 +1982,7 @@ monitor_sync (struct ZoneMonitor *zm) * @param cls zone monitor that does its initial iteration */ static void -monitor_iteration_next (void *cls); +monitor_iteration_next(void *cls); /** @@ -2008,32 +1996,32 @@ monitor_iteration_next (void *cls); * @param rd array of records */ static void -monitor_iterate_cb (void *cls, - uint64_t seq, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *name, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +monitor_iterate_cb(void *cls, + uint64_t seq, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *name, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct ZoneMonitor *zm = cls; - GNUNET_assert (0 != seq); + GNUNET_assert(0 != seq); zm->seq = seq; - GNUNET_assert (NULL != name); - GNUNET_STATISTICS_update (statistics, - "Monitor notifications sent", - 1, - GNUNET_NO); + GNUNET_assert(NULL != name); + GNUNET_STATISTICS_update(statistics, + "Monitor notifications sent", + 1, + GNUNET_NO); zm->limit--; zm->iteration_cnt--; - send_lookup_response (zm->nc, 0, zone_key, name, rd_count, rd); + send_lookup_response(zm->nc, 0, zone_key, name, rd_count, rd); if ((0 == zm->iteration_cnt) && (0 != zm->limit)) - { - /* We are done with the current iteration batch, AND the - client would right now accept more, so go again! */ - GNUNET_assert (NULL == zm->task); - zm->task = GNUNET_SCHEDULER_add_now (&monitor_iteration_next, zm); - } + { + /* We are done with the current iteration batch, AND the + client would right now accept more, so go again! */ + GNUNET_assert(NULL == zm->task); + zm->task = GNUNET_SCHEDULER_add_now(&monitor_iteration_next, zm); + } } @@ -2044,25 +2032,25 @@ monitor_iterate_cb (void *cls, * @param zis_msg message from the client */ static void -handle_monitor_start (void *cls, const struct ZoneMonitorStartMessage *zis_msg) +handle_monitor_start(void *cls, const struct ZoneMonitorStartMessage *zis_msg) { struct NamestoreClient *nc = cls; struct ZoneMonitor *zm; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received ZONE_MONITOR_START message\n"); - zm = GNUNET_new (struct ZoneMonitor); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received ZONE_MONITOR_START message\n"); + zm = GNUNET_new(struct ZoneMonitor); zm->nc = nc; zm->zone = zis_msg->zone; zm->limit = 1; - zm->in_first_iteration = (GNUNET_YES == ntohl (zis_msg->iterate_first)); - GNUNET_CONTAINER_DLL_insert (monitor_head, monitor_tail, zm); - GNUNET_SERVICE_client_mark_monitor (nc->client); - GNUNET_SERVICE_client_continue (nc->client); - GNUNET_notification_context_add (monitor_nc, nc->mq); + zm->in_first_iteration = (GNUNET_YES == ntohl(zis_msg->iterate_first)); + GNUNET_CONTAINER_DLL_insert(monitor_head, monitor_tail, zm); + GNUNET_SERVICE_client_mark_monitor(nc->client); + GNUNET_SERVICE_client_continue(nc->client); + GNUNET_notification_context_add(monitor_nc, nc->mq); if (zm->in_first_iteration) - zm->task = GNUNET_SCHEDULER_add_now (&monitor_iteration_next, zm); + zm->task = GNUNET_SCHEDULER_add_now(&monitor_iteration_next, zm); else - monitor_sync (zm); + monitor_sync(zm); } @@ -2072,36 +2060,36 @@ handle_monitor_start (void *cls, const struct ZoneMonitorStartMessage *zis_msg) * @param cls zone monitor that does its initial iteration */ static void -monitor_iteration_next (void *cls) +monitor_iteration_next(void *cls) { struct ZoneMonitor *zm = cls; int ret; zm->task = NULL; - GNUNET_assert (0 == zm->iteration_cnt); + GNUNET_assert(0 == zm->iteration_cnt); if (zm->limit > 16) zm->iteration_cnt = zm->limit / 2; /* leave half for monitor events */ else zm->iteration_cnt = zm->limit; /* use it all */ - ret = GSN_database->iterate_records (GSN_database->cls, - (0 == GNUNET_is_zero (&zm->zone)) - ? NULL - : &zm->zone, - zm->seq, - zm->iteration_cnt, - &monitor_iterate_cb, - zm); + ret = GSN_database->iterate_records(GSN_database->cls, + (0 == GNUNET_is_zero(&zm->zone)) + ? NULL + : &zm->zone, + zm->seq, + zm->iteration_cnt, + &monitor_iterate_cb, + zm); if (GNUNET_SYSERR == ret) - { - GNUNET_SERVICE_client_drop (zm->nc->client); - return; - } + { + GNUNET_SERVICE_client_drop(zm->nc->client); + return; + } if (GNUNET_NO == ret) - { - /* empty zone */ - monitor_sync (zm); - return; - } + { + /* empty zone */ + monitor_sync(zm); + return; + } } @@ -2112,55 +2100,55 @@ monitor_iteration_next (void *cls) * @param nm message from the client */ static void -handle_monitor_next (void *cls, const struct ZoneMonitorNextMessage *nm) +handle_monitor_next(void *cls, const struct ZoneMonitorNextMessage *nm) { struct NamestoreClient *nc = cls; struct ZoneMonitor *zm; uint64_t inc; - inc = GNUNET_ntohll (nm->limit); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ZONE_MONITOR_NEXT message with limit %llu\n", - (unsigned long long) inc); + inc = GNUNET_ntohll(nm->limit); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ZONE_MONITOR_NEXT message with limit %llu\n", + (unsigned long long)inc); for (zm = monitor_head; NULL != zm; zm = zm->next) if (zm->nc == nc) break; if (NULL == zm) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (nc->client); - return; - } - GNUNET_SERVICE_client_continue (nc->client); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(nc->client); + return; + } + GNUNET_SERVICE_client_continue(nc->client); if (zm->limit + inc < zm->limit) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (nc->client); - return; - } + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(nc->client); + return; + } zm->limit += inc; if ((zm->in_first_iteration) && (zm->limit == inc)) - { - /* We are still iterating, and the previous iteration must - have stopped due to the client's limit, so continue it! */ - GNUNET_assert (NULL == zm->task); - zm->task = GNUNET_SCHEDULER_add_now (&monitor_iteration_next, zm); - } - GNUNET_assert (zm->iteration_cnt <= zm->limit); + { + /* We are still iterating, and the previous iteration must + have stopped due to the client's limit, so continue it! */ + GNUNET_assert(NULL == zm->task); + zm->task = GNUNET_SCHEDULER_add_now(&monitor_iteration_next, zm); + } + GNUNET_assert(zm->iteration_cnt <= zm->limit); if ((zm->limit > zm->iteration_cnt) && (zm->sa_waiting)) - { - monitor_unblock (zm); - } + { + monitor_unblock(zm); + } else if (GNUNET_YES == zm->sa_waiting) - { - if (NULL != zm->sa_wait_warning) - GNUNET_SCHEDULER_cancel (zm->sa_wait_warning); - zm->sa_waiting_start = GNUNET_TIME_absolute_get (); - zm->sa_wait_warning = - GNUNET_SCHEDULER_add_delayed (MONITOR_STALL_WARN_DELAY, - &warn_monitor_slow, - zm); - } + { + if (NULL != zm->sa_wait_warning) + GNUNET_SCHEDULER_cancel(zm->sa_wait_warning); + zm->sa_waiting_start = GNUNET_TIME_absolute_get(); + zm->sa_wait_warning = + GNUNET_SCHEDULER_add_delayed(MONITOR_STALL_WARN_DELAY, + &warn_monitor_slow, + zm); + } } @@ -2172,92 +2160,92 @@ handle_monitor_next (void *cls, const struct ZoneMonitorNextMessage *nm) * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_SERVICE_Handle *service) { char *database; - (void) cls; - (void) service; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting namestore service\n"); + (void)cls; + (void)service; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Starting namestore service\n"); cache_keys = - GNUNET_CONFIGURATION_get_value_yesno (cfg, "namestore", "CACHE_KEYS"); + GNUNET_CONFIGURATION_get_value_yesno(cfg, "namestore", "CACHE_KEYS"); disable_namecache = - GNUNET_CONFIGURATION_get_value_yesno (cfg, "namecache", "DISABLE"); + GNUNET_CONFIGURATION_get_value_yesno(cfg, "namecache", "DISABLE"); GSN_cfg = cfg; - monitor_nc = GNUNET_notification_context_create (1); + monitor_nc = GNUNET_notification_context_create(1); if (GNUNET_YES != disable_namecache) - { - namecache = GNUNET_NAMECACHE_connect (cfg); - GNUNET_assert (NULL != namecache); - } + { + namecache = GNUNET_NAMECACHE_connect(cfg); + GNUNET_assert(NULL != namecache); + } /* Loading database plugin */ - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "namestore", - "database", - &database)) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No database backend configured\n"); - - GNUNET_asprintf (&db_lib_name, "libgnunet_plugin_namestore_%s", database); - GSN_database = GNUNET_PLUGIN_load (db_lib_name, (void *) GSN_cfg); - GNUNET_free (database); - statistics = GNUNET_STATISTICS_create ("namestore", cfg); - GNUNET_SCHEDULER_add_shutdown (&cleanup_task, NULL); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "namestore", + "database", + &database)) + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No database backend configured\n"); + + GNUNET_asprintf(&db_lib_name, "libgnunet_plugin_namestore_%s", database); + GSN_database = GNUNET_PLUGIN_load(db_lib_name, (void *)GSN_cfg); + GNUNET_free(database); + statistics = GNUNET_STATISTICS_create("namestore", cfg); + GNUNET_SCHEDULER_add_shutdown(&cleanup_task, NULL); if (NULL == GSN_database) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not load database backend `%s'\n", - db_lib_name); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not load database backend `%s'\n", + db_lib_name); + GNUNET_SCHEDULER_shutdown(); + return; + } } /** * Define "main" method using service macro. */ -GNUNET_SERVICE_MAIN ( +GNUNET_SERVICE_MAIN( "namestore", GNUNET_SERVICE_OPTION_NONE, &run, &client_connect_cb, &client_disconnect_cb, NULL, - GNUNET_MQ_hd_var_size (record_store, - GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE, - struct RecordStoreMessage, - NULL), - GNUNET_MQ_hd_var_size (record_lookup, - GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP, - struct LabelLookupMessage, - NULL), - GNUNET_MQ_hd_fixed_size (zone_to_name, - GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME, - struct ZoneToNameMessage, - NULL), - GNUNET_MQ_hd_fixed_size (iteration_start, - GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START, - struct ZoneIterationStartMessage, - NULL), - GNUNET_MQ_hd_fixed_size (iteration_next, - GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT, - struct ZoneIterationNextMessage, - NULL), - GNUNET_MQ_hd_fixed_size (iteration_stop, - GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP, - struct ZoneIterationStopMessage, - NULL), - GNUNET_MQ_hd_fixed_size (monitor_start, - GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START, - struct ZoneMonitorStartMessage, - NULL), - GNUNET_MQ_hd_fixed_size (monitor_next, - GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_NEXT, - struct ZoneMonitorNextMessage, - NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_hd_var_size(record_store, + GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE, + struct RecordStoreMessage, + NULL), + GNUNET_MQ_hd_var_size(record_lookup, + GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP, + struct LabelLookupMessage, + NULL), + GNUNET_MQ_hd_fixed_size(zone_to_name, + GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME, + struct ZoneToNameMessage, + NULL), + GNUNET_MQ_hd_fixed_size(iteration_start, + GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START, + struct ZoneIterationStartMessage, + NULL), + GNUNET_MQ_hd_fixed_size(iteration_next, + GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT, + struct ZoneIterationNextMessage, + NULL), + GNUNET_MQ_hd_fixed_size(iteration_stop, + GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP, + struct ZoneIterationStopMessage, + NULL), + GNUNET_MQ_hd_fixed_size(monitor_start, + GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START, + struct ZoneMonitorStartMessage, + NULL), + GNUNET_MQ_hd_fixed_size(monitor_next, + GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_NEXT, + struct ZoneMonitorNextMessage, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-namestore.c */ diff --git a/src/namestore/gnunet-zoneimport.c b/src/namestore/gnunet-zoneimport.c index 4c5205ab3..60d8b0537 100644 --- a/src/namestore/gnunet-zoneimport.c +++ b/src/namestore/gnunet-zoneimport.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/namestore/gnunet-zoneimport.c * @brief import a DNS zone for publication in GNS, incremental @@ -57,7 +57,7 @@ * How long do we wait at least between series of requests? */ #define SERIES_DELAY \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MICROSECONDS, 10) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MICROSECONDS, 10) /** * How long do DNS records have to last at least after being imported? @@ -76,9 +76,7 @@ static struct GNUNET_TIME_Relative minimum_expiration_time; * each dot represents a zone cut, we then need to create a * zone on-the-fly to capture those records properly. */ -struct Zone -{ - +struct Zone { /** * Kept in a DLL. */ @@ -104,8 +102,7 @@ struct Zone /** * Record for the request to be stored by GNS. */ -struct Record -{ +struct Record { /** * Kept in a DLL. */ @@ -128,8 +125,7 @@ struct Record * thus optimizing it is crucial for the overall memory consumption of * the zone importer. */ -struct Request -{ +struct Request { /** * Requests are kept in a heap while waiting to be resolved. */ @@ -379,28 +375,28 @@ typedef void (*RecordProcessor) (void *cls, * @param rp_cls closure for @a rp */ static void -for_all_records (const struct GNUNET_DNSPARSER_Packet *p, - RecordProcessor rp, - void *rp_cls) +for_all_records(const struct GNUNET_DNSPARSER_Packet *p, + RecordProcessor rp, + void *rp_cls) { for (unsigned int i = 0; i < p->num_answers; i++) - { - struct GNUNET_DNSPARSER_Record *rs = &p->answers[i]; + { + struct GNUNET_DNSPARSER_Record *rs = &p->answers[i]; - rp (rp_cls, rs); - } + rp(rp_cls, rs); + } for (unsigned int i = 0; i < p->num_authority_records; i++) - { - struct GNUNET_DNSPARSER_Record *rs = &p->authority_records[i]; + { + struct GNUNET_DNSPARSER_Record *rs = &p->authority_records[i]; - rp (rp_cls, rs); - } + rp(rp_cls, rs); + } for (unsigned int i = 0; i < p->num_additional_records; i++) - { - struct GNUNET_DNSPARSER_Record *rs = &p->additional_records[i]; + { + struct GNUNET_DNSPARSER_Record *rs = &p->additional_records[i]; - rp (rp_cls, rs); - } + rp(rp_cls, rs); + } } @@ -412,23 +408,23 @@ for_all_records (const struct GNUNET_DNSPARSER_Packet *p, * overwritten upon the next request! */ static const char * -get_label (struct Request *req) +get_label(struct Request *req) { static char label[64]; const char *dot; - dot = strchr (req->hostname, (unsigned char) '.'); + dot = strchr(req->hostname, (unsigned char)'.'); if (NULL == dot) - { - GNUNET_break (0); - return NULL; - } - if (((size_t) (dot - req->hostname)) >= sizeof (label)) - { - GNUNET_break (0); - return NULL; - } - GNUNET_memcpy (label, req->hostname, dot - req->hostname); + { + GNUNET_break(0); + return NULL; + } + if (((size_t)(dot - req->hostname)) >= sizeof(label)) + { + GNUNET_break(0); + return NULL; + } + GNUNET_memcpy(label, req->hostname, dot - req->hostname); label[dot - req->hostname] = '\0'; return label; } @@ -443,7 +439,7 @@ get_label (struct Request *req) * allocated query buffer */ static void * -build_dns_query (struct Request *req, size_t *raw_size) +build_dns_query(struct Request *req, size_t *raw_size) { static char raw[512]; char *rawp; @@ -451,37 +447,37 @@ build_dns_query (struct Request *req, size_t *raw_size) struct GNUNET_DNSPARSER_Query q; int ret; - q.name = (char *) req->hostname; + q.name = (char *)req->hostname; q.type = GNUNET_DNSPARSER_TYPE_NS; q.dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; - memset (&p, 0, sizeof (p)); + memset(&p, 0, sizeof(p)); p.num_queries = 1; p.queries = &q; p.id = req->id; - ret = GNUNET_DNSPARSER_pack (&p, UINT16_MAX, &rawp, raw_size); + ret = GNUNET_DNSPARSER_pack(&p, UINT16_MAX, &rawp, raw_size); if (GNUNET_OK != ret) - { - if (GNUNET_NO == ret) - GNUNET_free (rawp); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to pack query for hostname `%s'\n", - req->hostname); - rejects++; - return NULL; - } - if (*raw_size > sizeof (raw)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to pack query for hostname `%s'\n", - req->hostname); - rejects++; - GNUNET_break (0); - GNUNET_free (rawp); - return NULL; - } - GNUNET_memcpy (raw, rawp, *raw_size); - GNUNET_free (rawp); + { + if (GNUNET_NO == ret) + GNUNET_free(rawp); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to pack query for hostname `%s'\n", + req->hostname); + rejects++; + return NULL; + } + if (*raw_size > sizeof(raw)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to pack query for hostname `%s'\n", + req->hostname); + rejects++; + GNUNET_break(0); + GNUNET_free(rawp); + return NULL; + } + GNUNET_memcpy(raw, rawp, *raw_size); + GNUNET_free(rawp); return raw; } @@ -492,16 +488,16 @@ build_dns_query (struct Request *req, size_t *raw_size) * @param req request to free records of */ static void -free_records (struct Request *req) +free_records(struct Request *req) { struct Record *rec; /* Free records */ while (NULL != (rec = req->rec_head)) - { - GNUNET_CONTAINER_DLL_remove (req->rec_head, req->rec_tail, rec); - GNUNET_free (rec); - } + { + GNUNET_CONTAINER_DLL_remove(req->rec_head, req->rec_tail, rec); + GNUNET_free(rec); + } } @@ -511,10 +507,10 @@ free_records (struct Request *req) * @param req request to free */ static void -free_request (struct Request *req) +free_request(struct Request *req) { - free_records (req); - GNUNET_free (req); + free_records(req); + GNUNET_free(req); } @@ -524,7 +520,7 @@ free_request (struct Request *req) * @param cls NULL */ static void -process_queue (void *cls); +process_queue(void *cls); /** @@ -533,17 +529,17 @@ process_queue (void *cls); * @param req request to insert into #req_heap */ static void -insert_sorted (struct Request *req) +insert_sorted(struct Request *req) { req->hn = - GNUNET_CONTAINER_heap_insert (req_heap, req, req->expires.abs_value_us); - if (req == GNUNET_CONTAINER_heap_peek (req_heap)) - { - if (NULL != t) - GNUNET_SCHEDULER_cancel (t); - sleep_time_reg_proc = GNUNET_TIME_absolute_get (); - t = GNUNET_SCHEDULER_add_at (req->expires, &process_queue, NULL); - } + GNUNET_CONTAINER_heap_insert(req_heap, req, req->expires.abs_value_us); + if (req == GNUNET_CONTAINER_heap_peek(req_heap)) + { + if (NULL != t) + GNUNET_SCHEDULER_cancel(t); + sleep_time_reg_proc = GNUNET_TIME_absolute_get(); + t = GNUNET_SCHEDULER_add_at(req->expires, &process_queue, NULL); + } } @@ -557,30 +553,29 @@ insert_sorted (struct Request *req) * @param data_len number of bytes in @a data */ static void -add_record (struct Request *req, - uint32_t type, - struct GNUNET_TIME_Absolute expiration_time, - const void *data, - size_t data_len) +add_record(struct Request *req, + uint32_t type, + struct GNUNET_TIME_Absolute expiration_time, + const void *data, + size_t data_len) { struct Record *rec; - rec = GNUNET_malloc (sizeof (struct Record) + data_len); + rec = GNUNET_malloc(sizeof(struct Record) + data_len); rec->grd.data = &rec[1]; rec->grd.expiration_time = expiration_time.abs_value_us; rec->grd.data_size = data_len; rec->grd.record_type = type; rec->grd.flags = GNUNET_GNSRECORD_RF_NONE; - GNUNET_memcpy (&rec[1], data, data_len); - GNUNET_CONTAINER_DLL_insert (req->rec_head, req->rec_tail, rec); + GNUNET_memcpy(&rec[1], data, data_len); + GNUNET_CONTAINER_DLL_insert(req->rec_head, req->rec_tail, rec); } /** * Closure for #check_for_glue. */ -struct GlueClosure -{ +struct GlueClosure { /** * Overall request we are processing. */ @@ -605,113 +600,115 @@ struct GlueClosure * @param rec record that may contain glue information */ static void -check_for_glue (void *cls, const struct GNUNET_DNSPARSER_Record *rec) +check_for_glue(void *cls, const struct GNUNET_DNSPARSER_Record *rec) { struct GlueClosure *gc = cls; char dst[65536]; size_t dst_len; size_t off; char ip[INET6_ADDRSTRLEN + 1]; - socklen_t ip_size = (socklen_t) sizeof (ip); + socklen_t ip_size = (socklen_t)sizeof(ip); struct GNUNET_TIME_Absolute expiration_time; struct GNUNET_TIME_Relative left; - if (0 != strcasecmp (rec->name, gc->ns)) + if (0 != strcasecmp(rec->name, gc->ns)) return; expiration_time = rec->expiration_time; - left = GNUNET_TIME_absolute_get_remaining (expiration_time); + left = GNUNET_TIME_absolute_get_remaining(expiration_time); if (0 == left.rel_value_us) return; /* ignore expired glue records */ /* if expiration window is too short, bump it to configured minimum */ if (left.rel_value_us < minimum_expiration_time.rel_value_us) expiration_time = - GNUNET_TIME_relative_to_absolute (minimum_expiration_time); - dst_len = sizeof (dst); + GNUNET_TIME_relative_to_absolute(minimum_expiration_time); + dst_len = sizeof(dst); off = 0; switch (rec->type) - { - case GNUNET_DNSPARSER_TYPE_A: - if (sizeof (struct in_addr) != rec->data.raw.data_len) - { - GNUNET_break (0); - return; - } - if (NULL == inet_ntop (AF_INET, rec->data.raw.data, ip, ip_size)) - { - GNUNET_break (0); - return; - } - if ((GNUNET_OK == GNUNET_DNSPARSER_builder_add_name (dst, - dst_len, - &off, - gc->req->hostname)) && - (GNUNET_OK == - GNUNET_DNSPARSER_builder_add_name (dst, dst_len, &off, ip))) - { - add_record (gc->req, - GNUNET_GNSRECORD_TYPE_GNS2DNS, - expiration_time, - dst, - off); - gc->found = GNUNET_YES; - } - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - if (sizeof (struct in6_addr) != rec->data.raw.data_len) - { - GNUNET_break (0); - return; - } - if (NULL == inet_ntop (AF_INET6, rec->data.raw.data, ip, ip_size)) - { - GNUNET_break (0); - return; - } - if ((GNUNET_OK == GNUNET_DNSPARSER_builder_add_name (dst, - dst_len, - &off, - gc->req->hostname)) && - (GNUNET_OK == - GNUNET_DNSPARSER_builder_add_name (dst, dst_len, &off, ip))) - { - add_record (gc->req, - GNUNET_GNSRECORD_TYPE_GNS2DNS, - expiration_time, - dst, - off); - gc->found = GNUNET_YES; - } - break; - case GNUNET_DNSPARSER_TYPE_CNAME: - if ((GNUNET_OK == GNUNET_DNSPARSER_builder_add_name (dst, - dst_len, - &off, - gc->req->hostname)) && - (GNUNET_OK == GNUNET_DNSPARSER_builder_add_name (dst, - dst_len, - &off, - rec->data.hostname))) { - add_record (gc->req, - GNUNET_GNSRECORD_TYPE_GNS2DNS, - expiration_time, - dst, - off); - gc->found = GNUNET_YES; + case GNUNET_DNSPARSER_TYPE_A: + if (sizeof(struct in_addr) != rec->data.raw.data_len) + { + GNUNET_break(0); + return; + } + if (NULL == inet_ntop(AF_INET, rec->data.raw.data, ip, ip_size)) + { + GNUNET_break(0); + return; + } + if ((GNUNET_OK == GNUNET_DNSPARSER_builder_add_name(dst, + dst_len, + &off, + gc->req->hostname)) && + (GNUNET_OK == + GNUNET_DNSPARSER_builder_add_name(dst, dst_len, &off, ip))) + { + add_record(gc->req, + GNUNET_GNSRECORD_TYPE_GNS2DNS, + expiration_time, + dst, + off); + gc->found = GNUNET_YES; + } + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + if (sizeof(struct in6_addr) != rec->data.raw.data_len) + { + GNUNET_break(0); + return; + } + if (NULL == inet_ntop(AF_INET6, rec->data.raw.data, ip, ip_size)) + { + GNUNET_break(0); + return; + } + if ((GNUNET_OK == GNUNET_DNSPARSER_builder_add_name(dst, + dst_len, + &off, + gc->req->hostname)) && + (GNUNET_OK == + GNUNET_DNSPARSER_builder_add_name(dst, dst_len, &off, ip))) + { + add_record(gc->req, + GNUNET_GNSRECORD_TYPE_GNS2DNS, + expiration_time, + dst, + off); + gc->found = GNUNET_YES; + } + break; + + case GNUNET_DNSPARSER_TYPE_CNAME: + if ((GNUNET_OK == GNUNET_DNSPARSER_builder_add_name(dst, + dst_len, + &off, + gc->req->hostname)) && + (GNUNET_OK == GNUNET_DNSPARSER_builder_add_name(dst, + dst_len, + &off, + rec->data.hostname))) + { + add_record(gc->req, + GNUNET_GNSRECORD_TYPE_GNS2DNS, + expiration_time, + dst, + off); + gc->found = GNUNET_YES; + } + break; + + default: + /* useless, do nothing */ + break; } - break; - default: - /* useless, do nothing */ - break; - } } /** * Closure for #process_record(). */ -struct ProcessRecordContext -{ +struct ProcessRecordContext { /** * Answer we got back and are currently parsing, or NULL * if not active. @@ -732,7 +729,7 @@ struct ProcessRecordContext * @param rec response */ static void -process_record (void *cls, const struct GNUNET_DNSPARSER_Record *rec) +process_record(void *cls, const struct GNUNET_DNSPARSER_Record *rec) { struct ProcessRecordContext *prc = cls; struct Request *req = prc->req; @@ -742,175 +739,183 @@ process_record (void *cls, const struct GNUNET_DNSPARSER_Record *rec) struct GNUNET_TIME_Absolute expiration_time; struct GNUNET_TIME_Relative left; - dst_len = sizeof (dst); + dst_len = sizeof(dst); off = 0; records++; - if (0 != strcasecmp (rec->name, req->hostname)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "DNS returned record from zone `%s' of type %u while resolving `%s'\n", - rec->name, - (unsigned int) rec->type, - req->hostname); - return; /* does not match hostname, might be glue, but - not useful for this pass! */ - } + if (0 != strcasecmp(rec->name, req->hostname)) + { + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "DNS returned record from zone `%s' of type %u while resolving `%s'\n", + rec->name, + (unsigned int)rec->type, + req->hostname); + return; /* does not match hostname, might be glue, but + not useful for this pass! */ + } expiration_time = rec->expiration_time; - left = GNUNET_TIME_absolute_get_remaining (expiration_time); + left = GNUNET_TIME_absolute_get_remaining(expiration_time); if (0 == left.rel_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "DNS returned expired record for `%s'\n", - req->hostname); - GNUNET_STATISTICS_update (stats, - "# expired records obtained from DNS", - 1, - GNUNET_NO); - return; /* record expired */ - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "DNS returned expired record for `%s'\n", + req->hostname); + GNUNET_STATISTICS_update(stats, + "# expired records obtained from DNS", + 1, + GNUNET_NO); + return; /* record expired */ + } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "DNS returned record that expires at %s for `%s'\n", - GNUNET_STRINGS_absolute_time_to_string (expiration_time), - req->hostname); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "DNS returned record that expires at %s for `%s'\n", + GNUNET_STRINGS_absolute_time_to_string(expiration_time), + req->hostname); /* if expiration window is too short, bump it to configured minimum */ if (left.rel_value_us < minimum_expiration_time.rel_value_us) expiration_time = - GNUNET_TIME_relative_to_absolute (minimum_expiration_time); + GNUNET_TIME_relative_to_absolute(minimum_expiration_time); switch (rec->type) - { - case GNUNET_DNSPARSER_TYPE_NS: { - struct GlueClosure gc; - - /* check for glue */ - gc.req = req; - gc.ns = rec->data.hostname; - gc.found = GNUNET_NO; - for_all_records (prc->p, &check_for_glue, &gc); - if ((GNUNET_NO == gc.found) && - (GNUNET_OK == GNUNET_DNSPARSER_builder_add_name (dst, + { + case GNUNET_DNSPARSER_TYPE_NS: { + struct GlueClosure gc; + + /* check for glue */ + gc.req = req; + gc.ns = rec->data.hostname; + gc.found = GNUNET_NO; + for_all_records(prc->p, &check_for_glue, &gc); + if ((GNUNET_NO == gc.found) && + (GNUNET_OK == GNUNET_DNSPARSER_builder_add_name(dst, + dst_len, + &off, + req->hostname)) && + (GNUNET_OK == GNUNET_DNSPARSER_builder_add_name(dst, + dst_len, + &off, + rec->data.hostname))) + { + /* FIXME: actually check if this is out-of-bailiwick, + and if not request explicit resolution... */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Converted OOB (`%s') NS record for `%s'\n", + rec->data.hostname, + rec->name); + add_record(req, + GNUNET_GNSRECORD_TYPE_GNS2DNS, + expiration_time, + dst, + off); + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Converted NS record for `%s' using glue\n", + rec->name); + } + break; + } + + case GNUNET_DNSPARSER_TYPE_CNAME: + if (GNUNET_OK == GNUNET_DNSPARSER_builder_add_name(dst, dst_len, &off, - req->hostname)) && - (GNUNET_OK == GNUNET_DNSPARSER_builder_add_name (dst, + rec->data.hostname)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Converting CNAME (`%s') record for `%s'\n", + rec->data.hostname, + rec->name); + add_record(req, rec->type, expiration_time, dst, off); + } + break; + + case GNUNET_DNSPARSER_TYPE_DNAME: + /* No support for DNAME in GNS yet! FIXME: support later! */ + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "FIXME: not supported: %s DNAME %s\n", + rec->name, + rec->data.hostname); + break; + + case GNUNET_DNSPARSER_TYPE_MX: + if (GNUNET_OK == + GNUNET_DNSPARSER_builder_add_mx(dst, dst_len, &off, rec->data.mx)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Converting MX (`%s') record for `%s'\n", + rec->data.mx->mxhost, + rec->name); + add_record(req, rec->type, expiration_time, dst, off); + } + break; + + case GNUNET_DNSPARSER_TYPE_SOA: + if (GNUNET_OK == + GNUNET_DNSPARSER_builder_add_soa(dst, dst_len, &off, rec->data.soa)) + { + /* NOTE: GNS does not really use SOAs */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Converting SOA record for `%s'\n", + rec->name); + add_record(req, rec->type, expiration_time, dst, off); + } + break; + + case GNUNET_DNSPARSER_TYPE_SRV: + if (GNUNET_OK == + GNUNET_DNSPARSER_builder_add_srv(dst, dst_len, &off, rec->data.srv)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Converting SRV record for `%s'\n", + rec->name); + add_record(req, rec->type, expiration_time, dst, off); + } + break; + + case GNUNET_DNSPARSER_TYPE_PTR: + if (GNUNET_OK == GNUNET_DNSPARSER_builder_add_name(dst, dst_len, &off, - rec->data.hostname))) - { - /* FIXME: actually check if this is out-of-bailiwick, - and if not request explicit resolution... */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Converted OOB (`%s') NS record for `%s'\n", - rec->data.hostname, - rec->name); - add_record (req, - GNUNET_GNSRECORD_TYPE_GNS2DNS, - expiration_time, - dst, - off); - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Converted NS record for `%s' using glue\n", - rec->name); - } - break; - } - case GNUNET_DNSPARSER_TYPE_CNAME: - if (GNUNET_OK == GNUNET_DNSPARSER_builder_add_name (dst, - dst_len, - &off, - rec->data.hostname)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Converting CNAME (`%s') record for `%s'\n", - rec->data.hostname, - rec->name); - add_record (req, rec->type, expiration_time, dst, off); - } - break; - case GNUNET_DNSPARSER_TYPE_DNAME: - /* No support for DNAME in GNS yet! FIXME: support later! */ - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "FIXME: not supported: %s DNAME %s\n", - rec->name, - rec->data.hostname); - break; - case GNUNET_DNSPARSER_TYPE_MX: - if (GNUNET_OK == - GNUNET_DNSPARSER_builder_add_mx (dst, dst_len, &off, rec->data.mx)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Converting MX (`%s') record for `%s'\n", - rec->data.mx->mxhost, - rec->name); - add_record (req, rec->type, expiration_time, dst, off); - } - break; - case GNUNET_DNSPARSER_TYPE_SOA: - if (GNUNET_OK == - GNUNET_DNSPARSER_builder_add_soa (dst, dst_len, &off, rec->data.soa)) - { - /* NOTE: GNS does not really use SOAs */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Converting SOA record for `%s'\n", - rec->name); - add_record (req, rec->type, expiration_time, dst, off); - } - break; - case GNUNET_DNSPARSER_TYPE_SRV: - if (GNUNET_OK == - GNUNET_DNSPARSER_builder_add_srv (dst, dst_len, &off, rec->data.srv)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Converting SRV record for `%s'\n", - rec->name); - add_record (req, rec->type, expiration_time, dst, off); - } - break; - case GNUNET_DNSPARSER_TYPE_PTR: - if (GNUNET_OK == GNUNET_DNSPARSER_builder_add_name (dst, - dst_len, - &off, - rec->data.hostname)) - { - /* !?: what does a PTR record do in a regular TLD??? */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Converting PTR record for `%s' (weird)\n", - rec->name); - add_record (req, rec->type, expiration_time, dst, off); - } - break; - case GNUNET_DNSPARSER_TYPE_CERT: - if (GNUNET_OK == - GNUNET_DNSPARSER_builder_add_cert (dst, dst_len, &off, rec->data.cert)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Converting CERT record for `%s'\n", - rec->name); - add_record (req, rec->type, expiration_time, dst, off); - } - break; + rec->data.hostname)) + { + /* !?: what does a PTR record do in a regular TLD??? */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Converting PTR record for `%s' (weird)\n", + rec->name); + add_record(req, rec->type, expiration_time, dst, off); + } + break; + + case GNUNET_DNSPARSER_TYPE_CERT: + if (GNUNET_OK == + GNUNET_DNSPARSER_builder_add_cert(dst, dst_len, &off, rec->data.cert)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Converting CERT record for `%s'\n", + rec->name); + add_record(req, rec->type, expiration_time, dst, off); + } + break; + /* Rest is 'raw' encoded and just needs to be copied IF the hostname matches the requested name; otherwise we simply cannot use it. */ - case GNUNET_DNSPARSER_TYPE_A: - case GNUNET_DNSPARSER_TYPE_AAAA: - case GNUNET_DNSPARSER_TYPE_TXT: - default: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Converting record of type %u for `%s'\n", - (unsigned int) rec->type, - rec->name); - add_record (req, - rec->type, - expiration_time, - rec->data.raw.data, - rec->data.raw.data_len); - break; - } + case GNUNET_DNSPARSER_TYPE_A: + case GNUNET_DNSPARSER_TYPE_AAAA: + case GNUNET_DNSPARSER_TYPE_TXT: + default: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Converting record of type %u for `%s'\n", + (unsigned int)rec->type, + rec->name); + add_record(req, + rec->type, + expiration_time, + rec->data.raw.data, + rec->data.raw.data_len); + break; + } } @@ -925,89 +930,89 @@ process_record (void *cls, const struct GNUNET_DNSPARSER_Record *rec) * @param emsg NULL on success, otherwise an error message */ static void -store_completed_cb (void *cls, int32_t success, const char *emsg) +store_completed_cb(void *cls, int32_t success, const char *emsg) { static struct GNUNET_TIME_Absolute last; struct Request *req = cls; req->qe = NULL; if (GNUNET_SYSERR == success) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to store zone data for `%s': %s\n", - req->hostname, - emsg); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to store zone data for `%s': %s\n", + req->hostname, + emsg); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Stored records under `%s' (%d)\n", - req->hostname, - success); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Stored records under `%s' (%d)\n", + req->hostname, + success); + } total_reg_proc_dns_ns++; /* finished regular processing */ pending_rs--; - free_records (req); + free_records(req); /* compute NAMESTORE statistics */ { static uint64_t total_ns_latency_cnt; static struct GNUNET_TIME_Relative total_ns_latency; struct GNUNET_TIME_Relative ns_latency; - ns_latency = GNUNET_TIME_absolute_get_duration (req->op_start_time); - total_ns_latency = GNUNET_TIME_relative_add (total_ns_latency, ns_latency); + ns_latency = GNUNET_TIME_absolute_get_duration(req->op_start_time); + total_ns_latency = GNUNET_TIME_relative_add(total_ns_latency, ns_latency); if (0 == total_ns_latency_cnt) - last = GNUNET_TIME_absolute_get (); + last = GNUNET_TIME_absolute_get(); total_ns_latency_cnt++; if (0 == (total_ns_latency_cnt % 1000)) - { - struct GNUNET_TIME_Relative delta; - - delta = GNUNET_TIME_absolute_get_duration (last); - last = GNUNET_TIME_absolute_get (); - fprintf (stderr, - "Processed 1000 records in %s\n", - GNUNET_STRINGS_relative_time_to_string (delta, GNUNET_YES)); - GNUNET_STATISTICS_set (stats, - "# average NAMESTORE PUT latency (μs)", - total_ns_latency.rel_value_us / - total_ns_latency_cnt, - GNUNET_NO); - } + { + struct GNUNET_TIME_Relative delta; + + delta = GNUNET_TIME_absolute_get_duration(last); + last = GNUNET_TIME_absolute_get(); + fprintf(stderr, + "Processed 1000 records in %s\n", + GNUNET_STRINGS_relative_time_to_string(delta, GNUNET_YES)); + GNUNET_STATISTICS_set(stats, + "# average NAMESTORE PUT latency (μs)", + total_ns_latency.rel_value_us / + total_ns_latency_cnt, + GNUNET_NO); + } } /* compute and publish overall velocity */ if (0 == (total_reg_proc_dns_ns % 100)) - { - struct GNUNET_TIME_Relative runtime; - - runtime = GNUNET_TIME_absolute_get_duration (start_time_reg_proc); - runtime = GNUNET_TIME_relative_subtract (runtime, idle_time); - runtime = - GNUNET_TIME_relative_divide (runtime, - total_reg_proc_dns + total_reg_proc_dns_ns); - GNUNET_STATISTICS_set (stats, - "# Regular processing completed without NAMESTORE", - total_reg_proc_dns, - GNUNET_NO); - GNUNET_STATISTICS_set (stats, - "# Regular processing completed with NAMESTORE PUT", - total_reg_proc_dns_ns, - GNUNET_NO); - GNUNET_STATISTICS_set (stats, - "# average request processing latency (μs)", - runtime.rel_value_us, - GNUNET_NO); - GNUNET_STATISTICS_set (stats, - "# total time spent idle (μs)", - idle_time.rel_value_us, - GNUNET_NO); - } + { + struct GNUNET_TIME_Relative runtime; + + runtime = GNUNET_TIME_absolute_get_duration(start_time_reg_proc); + runtime = GNUNET_TIME_relative_subtract(runtime, idle_time); + runtime = + GNUNET_TIME_relative_divide(runtime, + total_reg_proc_dns + total_reg_proc_dns_ns); + GNUNET_STATISTICS_set(stats, + "# Regular processing completed without NAMESTORE", + total_reg_proc_dns, + GNUNET_NO); + GNUNET_STATISTICS_set(stats, + "# Regular processing completed with NAMESTORE PUT", + total_reg_proc_dns_ns, + GNUNET_NO); + GNUNET_STATISTICS_set(stats, + "# average request processing latency (μs)", + runtime.rel_value_us, + GNUNET_NO); + GNUNET_STATISTICS_set(stats, + "# total time spent idle (μs)", + idle_time.rel_value_us, + GNUNET_NO); + } if (NULL == t) - { - sleep_time_reg_proc = GNUNET_TIME_absolute_get (); - t = GNUNET_SCHEDULER_add_now (&process_queue, NULL); - } + { + sleep_time_reg_proc = GNUNET_TIME_absolute_get(); + t = GNUNET_SCHEDULER_add_now(&process_queue, NULL); + } } @@ -1019,148 +1024,148 @@ store_completed_cb (void *cls, int32_t success, const char *emsg) * @param dns_len number of bytes in @a dns */ static void -process_result (void *cls, - const struct GNUNET_TUN_DnsHeader *dns, - size_t dns_len) +process_result(void *cls, + const struct GNUNET_TUN_DnsHeader *dns, + size_t dns_len) { struct Request *req = cls; struct Record *rec; struct GNUNET_DNSPARSER_Packet *p; unsigned int rd_count; - GNUNET_assert (NULL == req->hn); + GNUNET_assert(NULL == req->hn); if (NULL == dns) - { - /* stub gave up */ - GNUNET_CONTAINER_DLL_remove (req_head, req_tail, req); - pending--; - if (NULL == t) { - sleep_time_reg_proc = GNUNET_TIME_absolute_get (); - t = GNUNET_SCHEDULER_add_now (&process_queue, NULL); + /* stub gave up */ + GNUNET_CONTAINER_DLL_remove(req_head, req_tail, req); + pending--; + if (NULL == t) + { + sleep_time_reg_proc = GNUNET_TIME_absolute_get(); + t = GNUNET_SCHEDULER_add_now(&process_queue, NULL); + } + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Stub gave up on DNS reply for `%s'\n", + req->hostname); + GNUNET_STATISTICS_update(stats, "# DNS lookups timed out", 1, GNUNET_NO); + if (req->issue_num > MAX_RETRIES) + { + failures++; + free_request(req); + GNUNET_STATISTICS_update(stats, "# requests given up on", 1, GNUNET_NO); + return; + } + total_reg_proc_dns++; + req->rs = NULL; + insert_sorted(req); + return; } - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Stub gave up on DNS reply for `%s'\n", - req->hostname); - GNUNET_STATISTICS_update (stats, "# DNS lookups timed out", 1, GNUNET_NO); - if (req->issue_num > MAX_RETRIES) + if (req->id != dns->id) { - failures++; - free_request (req); - GNUNET_STATISTICS_update (stats, "# requests given up on", 1, GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "DNS ID did not match request, ignoring reply\n"); + GNUNET_STATISTICS_update(stats, "# DNS ID mismatches", 1, GNUNET_NO); return; } - total_reg_proc_dns++; - req->rs = NULL; - insert_sorted (req); - return; - } - if (req->id != dns->id) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "DNS ID did not match request, ignoring reply\n"); - GNUNET_STATISTICS_update (stats, "# DNS ID mismatches", 1, GNUNET_NO); - return; - } - GNUNET_CONTAINER_DLL_remove (req_head, req_tail, req); - GNUNET_DNSSTUB_resolve_cancel (req->rs); + GNUNET_CONTAINER_DLL_remove(req_head, req_tail, req); + GNUNET_DNSSTUB_resolve_cancel(req->rs); req->rs = NULL; pending--; - p = GNUNET_DNSPARSER_parse ((const char *) dns, dns_len); + p = GNUNET_DNSPARSER_parse((const char *)dns, dns_len); if (NULL == p) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to parse DNS reply for `%s'\n", - req->hostname); - GNUNET_STATISTICS_update (stats, "# DNS parser errors", 1, GNUNET_NO); - if (NULL == t) - { - sleep_time_reg_proc = GNUNET_TIME_absolute_get (); - t = GNUNET_SCHEDULER_add_now (&process_queue, NULL); - } - if (req->issue_num > MAX_RETRIES) { - failures++; - free_request (req); - GNUNET_STATISTICS_update (stats, "# requests given up on", 1, GNUNET_NO); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to parse DNS reply for `%s'\n", + req->hostname); + GNUNET_STATISTICS_update(stats, "# DNS parser errors", 1, GNUNET_NO); + if (NULL == t) + { + sleep_time_reg_proc = GNUNET_TIME_absolute_get(); + t = GNUNET_SCHEDULER_add_now(&process_queue, NULL); + } + if (req->issue_num > MAX_RETRIES) + { + failures++; + free_request(req); + GNUNET_STATISTICS_update(stats, "# requests given up on", 1, GNUNET_NO); + return; + } + insert_sorted(req); return; } - insert_sorted (req); - return; - } /* import new records */ req->issue_num = 0; /* success, reset counter! */ { - struct ProcessRecordContext prc = {.req = req, .p = p}; + struct ProcessRecordContext prc = { .req = req, .p = p }; - for_all_records (p, &process_record, &prc); + for_all_records(p, &process_record, &prc); } - GNUNET_DNSPARSER_free_packet (p); + GNUNET_DNSPARSER_free_packet(p); /* count records found, determine minimum expiration time */ req->expires = GNUNET_TIME_UNIT_FOREVER_ABS; { struct GNUNET_TIME_Relative dns_latency; - dns_latency = GNUNET_TIME_absolute_get_duration (req->op_start_time); + dns_latency = GNUNET_TIME_absolute_get_duration(req->op_start_time); total_dns_latency = - GNUNET_TIME_relative_add (total_dns_latency, dns_latency); + GNUNET_TIME_relative_add(total_dns_latency, dns_latency); total_dns_latency_cnt++; if (0 == (total_dns_latency_cnt % 1000)) - { - GNUNET_STATISTICS_set (stats, - "# average DNS lookup latency (μs)", - total_dns_latency.rel_value_us / - total_dns_latency_cnt, - GNUNET_NO); - } + { + GNUNET_STATISTICS_set(stats, + "# average DNS lookup latency (μs)", + total_dns_latency.rel_value_us / + total_dns_latency_cnt, + GNUNET_NO); + } } rd_count = 0; for (rec = req->rec_head; NULL != rec; rec = rec->next) - { - struct GNUNET_TIME_Absolute at; + { + struct GNUNET_TIME_Absolute at; - at.abs_value_us = rec->grd.expiration_time; - req->expires = GNUNET_TIME_absolute_min (req->expires, at); - rd_count++; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Obtained %u records for `%s'\n", - rd_count, - req->hostname); + at.abs_value_us = rec->grd.expiration_time; + req->expires = GNUNET_TIME_absolute_min(req->expires, at); + rd_count++; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Obtained %u records for `%s'\n", + rd_count, + req->hostname); /* Instead of going for SOA, simplified for now to look each day in case we got an empty response */ if (0 == rd_count) - { - req->expires = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_DAYS); - GNUNET_STATISTICS_update (stats, - "# empty DNS replies (usually NXDOMAIN)", - 1, - GNUNET_NO); - } + { + req->expires = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_DAYS); + GNUNET_STATISTICS_update(stats, + "# empty DNS replies (usually NXDOMAIN)", + 1, + GNUNET_NO); + } else - { - record_sets++; - } + { + record_sets++; + } /* convert records to namestore import format */ { - struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL (rd_count)]; + struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL(rd_count)]; unsigned int off = 0; /* convert linked list into array */ for (rec = req->rec_head; NULL != rec; rec = rec->next) rd[off++] = rec->grd; pending_rs++; - req->op_start_time = GNUNET_TIME_absolute_get (); - req->qe = GNUNET_NAMESTORE_records_store (ns, - &req->zone->key, - get_label (req), - rd_count, - rd, - &store_completed_cb, - req); - GNUNET_assert (NULL != req->qe); + req->op_start_time = GNUNET_TIME_absolute_get(); + req->qe = GNUNET_NAMESTORE_records_store(ns, + &req->zone->key, + get_label(req), + rd_count, + rd, + &store_completed_cb, + req); + GNUNET_assert(NULL != req->qe); } - insert_sorted (req); + insert_sorted(req); } @@ -1170,7 +1175,7 @@ process_result (void *cls, * @param cls NULL */ static void -process_queue (void *cls) +process_queue(void *cls) { struct Request *req; unsigned int series; @@ -1178,82 +1183,82 @@ process_queue (void *cls) size_t raw_size; struct GNUNET_TIME_Relative delay; - (void) cls; - delay = GNUNET_TIME_absolute_get_duration (sleep_time_reg_proc); - idle_time = GNUNET_TIME_relative_add (idle_time, delay); + (void)cls; + delay = GNUNET_TIME_absolute_get_duration(sleep_time_reg_proc); + idle_time = GNUNET_TIME_relative_add(idle_time, delay); series = 0; t = NULL; while (pending + pending_rs < THRESH) - { - req = GNUNET_CONTAINER_heap_peek (req_heap); - if (NULL == req) - break; - if (NULL != req->qe) - return; /* namestore op still pending */ - if (NULL != req->rs) { - GNUNET_break (0); - return; /* already submitted */ + req = GNUNET_CONTAINER_heap_peek(req_heap); + if (NULL == req) + break; + if (NULL != req->qe) + return; /* namestore op still pending */ + if (NULL != req->rs) + { + GNUNET_break(0); + return; /* already submitted */ + } + if (GNUNET_TIME_absolute_get_remaining(req->expires).rel_value_us > 0) + break; + GNUNET_assert(req == GNUNET_CONTAINER_heap_remove_root(req_heap)); + req->hn = NULL; + GNUNET_CONTAINER_DLL_insert(req_head, req_tail, req); + GNUNET_assert(NULL == req->rs); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Requesting resolution for `%s'\n", + req->hostname); + raw = build_dns_query(req, &raw_size); + if (NULL == raw) + { + GNUNET_break(0); + free_request(req); + continue; + } + req->op_start_time = GNUNET_TIME_absolute_get(); + req->rs = GNUNET_DNSSTUB_resolve(ctx, raw, raw_size, &process_result, req); + GNUNET_assert(NULL != req->rs); + req->issue_num++; + lookups++; + pending++; + series++; + if (series > MAX_SERIES) + break; } - if (GNUNET_TIME_absolute_get_remaining (req->expires).rel_value_us > 0) - break; - GNUNET_assert (req == GNUNET_CONTAINER_heap_remove_root (req_heap)); - req->hn = NULL; - GNUNET_CONTAINER_DLL_insert (req_head, req_tail, req); - GNUNET_assert (NULL == req->rs); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Requesting resolution for `%s'\n", - req->hostname); - raw = build_dns_query (req, &raw_size); - if (NULL == raw) + if (pending + pending_rs >= THRESH) { - GNUNET_break (0); - free_request (req); - continue; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Stopped processing queue (%u+%u/%u)]\n", + pending, + pending_rs, + THRESH); + return; /* wait for replies */ } - req->op_start_time = GNUNET_TIME_absolute_get (); - req->rs = GNUNET_DNSSTUB_resolve (ctx, raw, raw_size, &process_result, req); - GNUNET_assert (NULL != req->rs); - req->issue_num++; - lookups++; - pending++; - series++; - if (series > MAX_SERIES) - break; - } - if (pending + pending_rs >= THRESH) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Stopped processing queue (%u+%u/%u)]\n", - pending, - pending_rs, - THRESH); - return; /* wait for replies */ - } - req = GNUNET_CONTAINER_heap_peek (req_heap); + req = GNUNET_CONTAINER_heap_peek(req_heap); if (NULL == req) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Stopped processing queue: empty queue\n"); - return; - } - if (GNUNET_TIME_absolute_get_remaining (req->expires).rel_value_us > 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Waiting until %s for next record (`%s') to expire\n", - GNUNET_STRINGS_absolute_time_to_string (req->expires), - req->hostname); - if (NULL != t) - GNUNET_SCHEDULER_cancel (t); - sleep_time_reg_proc = GNUNET_TIME_absolute_get (); - t = GNUNET_SCHEDULER_add_at (req->expires, &process_queue, NULL); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Throttling\n"); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Stopped processing queue: empty queue\n"); + return; + } + if (GNUNET_TIME_absolute_get_remaining(req->expires).rel_value_us > 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Waiting until %s for next record (`%s') to expire\n", + GNUNET_STRINGS_absolute_time_to_string(req->expires), + req->hostname); + if (NULL != t) + GNUNET_SCHEDULER_cancel(t); + sleep_time_reg_proc = GNUNET_TIME_absolute_get(); + t = GNUNET_SCHEDULER_add_at(req->expires, &process_queue, NULL); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Throttling\n"); if (NULL != t) - GNUNET_SCHEDULER_cancel (t); - sleep_time_reg_proc = GNUNET_TIME_absolute_get (); - t = GNUNET_SCHEDULER_add_delayed (SERIES_DELAY, &process_queue, NULL); + GNUNET_SCHEDULER_cancel(t); + sleep_time_reg_proc = GNUNET_TIME_absolute_get(); + t = GNUNET_SCHEDULER_add_delayed(SERIES_DELAY, &process_queue, NULL); } @@ -1267,13 +1272,13 @@ process_queue (void *cls) * @return #GNUNET_OK */ static int -free_request_it (void *cls, const struct GNUNET_HashCode *key, void *value) +free_request_it(void *cls, const struct GNUNET_HashCode *key, void *value) { struct Request *req = value; - (void) cls; - (void) key; - free_request (req); + (void)cls; + (void)key; + free_request(req); return GNUNET_OK; } @@ -1284,73 +1289,73 @@ free_request_it (void *cls, const struct GNUNET_HashCode *key, void *value) * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { struct Request *req; struct Zone *zone; - (void) cls; + (void)cls; if (NULL != id) - { - GNUNET_IDENTITY_disconnect (id); - id = NULL; - } + { + GNUNET_IDENTITY_disconnect(id); + id = NULL; + } if (NULL != t) - { - GNUNET_SCHEDULER_cancel (t); - t = NULL; - } + { + GNUNET_SCHEDULER_cancel(t); + t = NULL; + } while (NULL != (req = req_head)) - { - GNUNET_CONTAINER_DLL_remove (req_head, req_tail, req); - if (NULL != req->qe) - GNUNET_NAMESTORE_cancel (req->qe); - free_request (req); - } - while (NULL != (req = GNUNET_CONTAINER_heap_remove_root (req_heap))) - { - req->hn = NULL; - if (NULL != req->qe) - GNUNET_NAMESTORE_cancel (req->qe); - free_request (req); - } + { + GNUNET_CONTAINER_DLL_remove(req_head, req_tail, req); + if (NULL != req->qe) + GNUNET_NAMESTORE_cancel(req->qe); + free_request(req); + } + while (NULL != (req = GNUNET_CONTAINER_heap_remove_root(req_heap))) + { + req->hn = NULL; + if (NULL != req->qe) + GNUNET_NAMESTORE_cancel(req->qe); + free_request(req); + } if (NULL != zone_it) - { - GNUNET_NAMESTORE_zone_iteration_stop (zone_it); - zone_it = NULL; - } + { + GNUNET_NAMESTORE_zone_iteration_stop(zone_it); + zone_it = NULL; + } if (NULL != ns) - { - GNUNET_NAMESTORE_disconnect (ns); - ns = NULL; - } + { + GNUNET_NAMESTORE_disconnect(ns); + ns = NULL; + } if (NULL != ctx) - { - GNUNET_DNSSTUB_stop (ctx); - ctx = NULL; - } + { + GNUNET_DNSSTUB_stop(ctx); + ctx = NULL; + } if (NULL != req_heap) - { - GNUNET_CONTAINER_heap_destroy (req_heap); - req_heap = NULL; - } + { + GNUNET_CONTAINER_heap_destroy(req_heap); + req_heap = NULL; + } if (NULL != ns_pending) - { - GNUNET_CONTAINER_multihashmap_iterate (ns_pending, &free_request_it, NULL); - GNUNET_CONTAINER_multihashmap_destroy (ns_pending); - ns_pending = NULL; - } + { + GNUNET_CONTAINER_multihashmap_iterate(ns_pending, &free_request_it, NULL); + GNUNET_CONTAINER_multihashmap_destroy(ns_pending); + ns_pending = NULL; + } while (NULL != (zone = zone_head)) - { - GNUNET_CONTAINER_DLL_remove (zone_head, zone_tail, zone); - GNUNET_free (zone->domain); - GNUNET_free (zone); - } + { + GNUNET_CONTAINER_DLL_remove(zone_head, zone_tail, zone); + GNUNET_free(zone->domain); + GNUNET_free(zone); + } if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, GNUNET_NO); - stats = NULL; - } + { + GNUNET_STATISTICS_destroy(stats, GNUNET_NO); + stats = NULL; + } } @@ -1361,7 +1366,7 @@ do_shutdown (void *cls) * @param cls NULL */ static void -iterate_zones (void *cls); +iterate_zones(void *cls); /** @@ -1371,16 +1376,16 @@ iterate_zones (void *cls); * @param cls a `struct Zone` */ static void -ns_lookup_error_cb (void *cls) +ns_lookup_error_cb(void *cls) { struct Zone *zone = cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Failed to load data from namestore for zone `%s'\n", - zone->domain); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Failed to load data from namestore for zone `%s'\n", + zone->domain); zone_it = NULL; ns_iterator_trigger_next = 0; - iterate_zones (NULL); + iterate_zones(NULL); } @@ -1394,11 +1399,11 @@ ns_lookup_error_cb (void *cls) * @param rd array of records with data to store */ static void -ns_lookup_result_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +ns_lookup_result_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *key, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct Zone *zone = cls; struct Request *req; @@ -1406,85 +1411,85 @@ ns_lookup_result_cb (void *cls, char *fqdn; ns_iterator_trigger_next--; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Obtained NAMESTORE reply, %llu left in round\n", - (unsigned long long) ns_iterator_trigger_next); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Obtained NAMESTORE reply, %llu left in round\n", + (unsigned long long)ns_iterator_trigger_next); if (0 == ns_iterator_trigger_next) - { - ns_iterator_trigger_next = NS_BATCH_SIZE; - GNUNET_STATISTICS_update (stats, - "# NAMESTORE records requested from cache", - ns_iterator_trigger_next, - GNUNET_NO); - GNUNET_NAMESTORE_zone_iterator_next (zone_it, ns_iterator_trigger_next); - } - GNUNET_asprintf (&fqdn, "%s.%s", label, zone->domain); - GNUNET_CRYPTO_hash (fqdn, strlen (fqdn) + 1, &hc); - GNUNET_free (fqdn); - req = GNUNET_CONTAINER_multihashmap_get (ns_pending, &hc); + { + ns_iterator_trigger_next = NS_BATCH_SIZE; + GNUNET_STATISTICS_update(stats, + "# NAMESTORE records requested from cache", + ns_iterator_trigger_next, + GNUNET_NO); + GNUNET_NAMESTORE_zone_iterator_next(zone_it, ns_iterator_trigger_next); + } + GNUNET_asprintf(&fqdn, "%s.%s", label, zone->domain); + GNUNET_CRYPTO_hash(fqdn, strlen(fqdn) + 1, &hc); + GNUNET_free(fqdn); + req = GNUNET_CONTAINER_multihashmap_get(ns_pending, &hc); if (NULL == req) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Ignoring record `%s' in zone `%s': not on my list!\n", - label, - zone->domain); - return; - } - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_remove (ns_pending, &hc, req)); - GNUNET_break (0 == GNUNET_memcmp (key, &req->zone->key)); - GNUNET_break (0 == strcasecmp (label, get_label (req))); + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Ignoring record `%s' in zone `%s': not on my list!\n", + label, + zone->domain); + return; + } + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_remove(ns_pending, &hc, req)); + GNUNET_break(0 == GNUNET_memcmp(key, &req->zone->key)); + GNUNET_break(0 == strcasecmp(label, get_label(req))); for (unsigned int i = 0; i < rd_count; i++) - { - struct GNUNET_TIME_Absolute at; - - if (0 != (rd->flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) { - struct GNUNET_TIME_Relative rel; + struct GNUNET_TIME_Absolute at; - rel.rel_value_us = rd->expiration_time; - at = GNUNET_TIME_relative_to_absolute (rel); + if (0 != (rd->flags & GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION)) + { + struct GNUNET_TIME_Relative rel; + + rel.rel_value_us = rd->expiration_time; + at = GNUNET_TIME_relative_to_absolute(rel); + } + else + { + at.abs_value_us = rd->expiration_time; + } + add_record(req, rd->record_type, at, rd->data, rd->data_size); } - else + if (0 == rd_count) { - at.abs_value_us = rd->expiration_time; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Empty record set in namestore for `%s'\n", + req->hostname); } - add_record (req, rd->record_type, at, rd->data, rd->data_size); - } - if (0 == rd_count) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Empty record set in namestore for `%s'\n", - req->hostname); - } else - { - unsigned int pos = 0; - - cached++; - req->expires = GNUNET_TIME_UNIT_FOREVER_ABS; - for (struct Record *rec = req->rec_head; NULL != rec; rec = rec->next) { - struct GNUNET_TIME_Absolute at; - - at.abs_value_us = rec->grd.expiration_time; - req->expires = GNUNET_TIME_absolute_min (req->expires, at); - pos++; + unsigned int pos = 0; + + cached++; + req->expires = GNUNET_TIME_UNIT_FOREVER_ABS; + for (struct Record *rec = req->rec_head; NULL != rec; rec = rec->next) + { + struct GNUNET_TIME_Absolute at; + + at.abs_value_us = rec->grd.expiration_time; + req->expires = GNUNET_TIME_absolute_min(req->expires, at); + pos++; + } + if (0 == pos) + req->expires = GNUNET_TIME_UNIT_ZERO_ABS; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Hot-start with %u existing records for `%s'\n", + pos, + req->hostname); } - if (0 == pos) - req->expires = GNUNET_TIME_UNIT_ZERO_ABS; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Hot-start with %u existing records for `%s'\n", - pos, - req->hostname); - } - free_records (req); + free_records(req); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding `%s' to worklist to start at %s\n", - req->hostname, - GNUNET_STRINGS_absolute_time_to_string (req->expires)); - insert_sorted (req); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding `%s' to worklist to start at %s\n", + req->hostname, + GNUNET_STRINGS_absolute_time_to_string(req->expires)); + insert_sorted(req); } @@ -1494,7 +1499,7 @@ ns_lookup_result_cb (void *cls, * @param hostname name to resolve */ static void -queue (const char *hostname) +queue(const char *hostname) { struct Request *req; const char *dot; @@ -1502,55 +1507,55 @@ queue (const char *hostname) size_t hlen; struct GNUNET_HashCode hc; - if (GNUNET_OK != GNUNET_DNSPARSER_check_name (hostname)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Refusing invalid hostname `%s'\n", - hostname); - rejects++; - return; - } - dot = strchr (hostname, (unsigned char) '.'); + if (GNUNET_OK != GNUNET_DNSPARSER_check_name(hostname)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Refusing invalid hostname `%s'\n", + hostname); + rejects++; + return; + } + dot = strchr(hostname, (unsigned char)'.'); if (NULL == dot) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Refusing invalid hostname `%s' (lacks '.')\n", - hostname); - rejects++; - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Refusing invalid hostname `%s' (lacks '.')\n", + hostname); + rejects++; + return; + } for (zone = zone_head; NULL != zone; zone = zone->next) - if (0 == strcmp (zone->domain, dot + 1)) + if (0 == strcmp(zone->domain, dot + 1)) break; if (NULL == zone) - { - rejects++; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Domain name `%s' not in ego list!\n", - dot + 1); - return; - } + { + rejects++; + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Domain name `%s' not in ego list!\n", + dot + 1); + return; + } - hlen = strlen (hostname) + 1; - req = GNUNET_malloc (sizeof (struct Request) + hlen); + hlen = strlen(hostname) + 1; + req = GNUNET_malloc(sizeof(struct Request) + hlen); req->zone = zone; - req->hostname = (char *) &req[1]; - GNUNET_memcpy (req->hostname, hostname, hlen); - req->id = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, - UINT16_MAX); - GNUNET_CRYPTO_hash (req->hostname, hlen, &hc); - if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put ( - ns_pending, - &hc, - req, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Duplicate hostname `%s' ignored\n", - hostname); - GNUNET_free (req); - return; - } + req->hostname = (char *)&req[1]; + GNUNET_memcpy(req->hostname, hostname, hlen); + req->id = (uint16_t)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, + UINT16_MAX); + GNUNET_CRYPTO_hash(req->hostname, hlen, &hc); + if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put( + ns_pending, + &hc, + req, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Duplicate hostname `%s' ignored\n", + hostname); + GNUNET_free(req); + return; + } } @@ -1566,13 +1571,13 @@ queue (const char *hostname) * @return #GNUNET_OK (continue to iterate) */ static int -move_to_queue (void *cls, const struct GNUNET_HashCode *key, void *value) +move_to_queue(void *cls, const struct GNUNET_HashCode *key, void *value) { struct Request *req = value; - (void) cls; - (void) key; - insert_sorted (req); + (void)cls; + (void)key; + insert_sorted(req); return GNUNET_OK; } @@ -1584,65 +1589,65 @@ move_to_queue (void *cls, const struct GNUNET_HashCode *key, void *value) * @param cls NULL */ static void -iterate_zones (void *cls) +iterate_zones(void *cls) { static struct Zone *last; - (void) cls; + (void)cls; if (NULL != zone_it) - { - zone_it = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished iteration over zone `%s'!\n", - last->domain); - /* subtract left-overs from previous iteration */ - GNUNET_STATISTICS_update (stats, - "# NAMESTORE records requested from cache", - (long long) (-ns_iterator_trigger_next), - GNUNET_NO); - ns_iterator_trigger_next = 0; - } - GNUNET_assert (NULL != zone_tail); + { + zone_it = NULL; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished iteration over zone `%s'!\n", + last->domain); + /* subtract left-overs from previous iteration */ + GNUNET_STATISTICS_update(stats, + "# NAMESTORE records requested from cache", + (long long)(-ns_iterator_trigger_next), + GNUNET_NO); + ns_iterator_trigger_next = 0; + } + GNUNET_assert(NULL != zone_tail); if (zone_tail == last) - { - /* Done iterating over relevant zones in NAMESTORE, move - rest of hash map to work queue as well. */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished all NAMESTORE iterations!\n"); - GNUNET_STATISTICS_set (stats, - "# Domain names without cached reply", - GNUNET_CONTAINER_multihashmap_size (ns_pending), - GNUNET_NO); - GNUNET_CONTAINER_multihashmap_iterate (ns_pending, &move_to_queue, NULL); - GNUNET_CONTAINER_multihashmap_destroy (ns_pending); - ns_pending = NULL; - start_time_reg_proc = GNUNET_TIME_absolute_get (); - total_reg_proc_dns = 0; - total_reg_proc_dns_ns = 0; - return; - } + { + /* Done iterating over relevant zones in NAMESTORE, move + rest of hash map to work queue as well. */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished all NAMESTORE iterations!\n"); + GNUNET_STATISTICS_set(stats, + "# Domain names without cached reply", + GNUNET_CONTAINER_multihashmap_size(ns_pending), + GNUNET_NO); + GNUNET_CONTAINER_multihashmap_iterate(ns_pending, &move_to_queue, NULL); + GNUNET_CONTAINER_multihashmap_destroy(ns_pending); + ns_pending = NULL; + start_time_reg_proc = GNUNET_TIME_absolute_get(); + total_reg_proc_dns = 0; + total_reg_proc_dns_ns = 0; + return; + } if (NULL == last) last = zone_head; else last = last->next; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting iteration over zone `%s'!\n", - last->domain); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting iteration over zone `%s'!\n", + last->domain); /* subtract left-overs from previous iteration */ - GNUNET_STATISTICS_update (stats, - "# NAMESTORE records requested from cache", - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(stats, + "# NAMESTORE records requested from cache", + 1, + GNUNET_NO); ns_iterator_trigger_next = 1; - GNUNET_STATISTICS_update (stats, "# zones iterated", 1, GNUNET_NO); - zone_it = GNUNET_NAMESTORE_zone_iteration_start (ns, - &last->key, - &ns_lookup_error_cb, - NULL, - &ns_lookup_result_cb, - last, - &iterate_zones, - NULL); + GNUNET_STATISTICS_update(stats, "# zones iterated", 1, GNUNET_NO); + zone_it = GNUNET_NAMESTORE_zone_iteration_start(ns, + &last->key, + &ns_lookup_error_cb, + NULL, + &ns_lookup_result_cb, + last, + &iterate_zones, + NULL); } @@ -1652,44 +1657,44 @@ iterate_zones (void *cls) * @param cls NULL */ static void -process_stdin (void *cls) +process_stdin(void *cls) { static struct GNUNET_TIME_Absolute last; static uint64_t idot; char hn[256]; - (void) cls; + (void)cls; t = NULL; if (NULL != id) - { - GNUNET_IDENTITY_disconnect (id); - id = NULL; - } - while (NULL != fgets (hn, sizeof (hn), stdin)) - { - if (strlen (hn) > 0) - hn[strlen (hn) - 1] = '\0'; /* eat newline */ - if (0 == idot) - last = GNUNET_TIME_absolute_get (); - idot++; - if (0 == idot % 100000) { - struct GNUNET_TIME_Relative delta; - - delta = GNUNET_TIME_absolute_get_duration (last); - last = GNUNET_TIME_absolute_get (); - fprintf (stderr, - "Read 100000 domain names in %s\n", - GNUNET_STRINGS_relative_time_to_string (delta, GNUNET_YES)); - GNUNET_STATISTICS_set (stats, "# domain names provided", idot, GNUNET_NO); + GNUNET_IDENTITY_disconnect(id); + id = NULL; } - queue (hn); - } - fprintf (stderr, - "Done reading %llu domain names\n", - (unsigned long long) idot); - GNUNET_STATISTICS_set (stats, "# domain names provided", idot, GNUNET_NO); - iterate_zones (NULL); + while (NULL != fgets(hn, sizeof(hn), stdin)) + { + if (strlen(hn) > 0) + hn[strlen(hn) - 1] = '\0'; /* eat newline */ + if (0 == idot) + last = GNUNET_TIME_absolute_get(); + idot++; + if (0 == idot % 100000) + { + struct GNUNET_TIME_Relative delta; + + delta = GNUNET_TIME_absolute_get_duration(last); + last = GNUNET_TIME_absolute_get(); + fprintf(stderr, + "Read 100000 domain names in %s\n", + GNUNET_STRINGS_relative_time_to_string(delta, GNUNET_YES)); + GNUNET_STATISTICS_set(stats, "# domain names provided", idot, GNUNET_NO); + } + queue(hn); + } + fprintf(stderr, + "Done reading %llu domain names\n", + (unsigned long long)idot); + GNUNET_STATISTICS_set(stats, "# domain names provided", idot, GNUNET_NO); + iterate_zones(NULL); } @@ -1728,36 +1733,36 @@ process_stdin (void *cls) * must thus no longer be used */ static void -identity_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +identity_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { - (void) cls; - (void) ctx; + (void)cls; + (void)ctx; if (NULL == ego) - { - /* end of iteration */ - if (NULL == zone_head) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No zone found\n"); - GNUNET_SCHEDULER_shutdown (); + /* end of iteration */ + if (NULL == zone_head) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No zone found\n"); + GNUNET_SCHEDULER_shutdown(); + return; + } + /* zone_head non-null, process hostnames from stdin */ + t = GNUNET_SCHEDULER_add_now(&process_stdin, NULL); return; } - /* zone_head non-null, process hostnames from stdin */ - t = GNUNET_SCHEDULER_add_now (&process_stdin, NULL); - return; - } if (NULL != name) - { - struct Zone *zone; + { + struct Zone *zone; - zone = GNUNET_new (struct Zone); - zone->key = *GNUNET_IDENTITY_ego_get_private_key (ego); - zone->domain = GNUNET_strdup (name); - GNUNET_CONTAINER_DLL_insert (zone_head, zone_tail, zone); - } + zone = GNUNET_new(struct Zone); + zone->key = *GNUNET_IDENTITY_ego_get_private_key(ego); + zone->domain = GNUNET_strdup(name); + GNUNET_CONTAINER_DLL_insert(zone_head, zone_tail, zone); + } } @@ -1771,52 +1776,52 @@ identity_cb (void *cls, * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - (void) cls; - (void) args; - (void) cfgfile; - stats = GNUNET_STATISTICS_create ("zoneimport", cfg); - req_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); - ns_pending = GNUNET_CONTAINER_multihashmap_create (map_size, GNUNET_NO); + (void)cls; + (void)args; + (void)cfgfile; + stats = GNUNET_STATISTICS_create("zoneimport", cfg); + req_heap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN); + ns_pending = GNUNET_CONTAINER_multihashmap_create(map_size, GNUNET_NO); if (NULL == ns_pending) - { - fprintf (stderr, "Failed to allocate memory for main hash map\n"); - return; - } - ctx = GNUNET_DNSSTUB_start (256); + { + fprintf(stderr, "Failed to allocate memory for main hash map\n"); + return; + } + ctx = GNUNET_DNSSTUB_start(256); if (NULL == ctx) - { - fprintf (stderr, "Failed to initialize GNUnet DNS STUB\n"); - return; - } + { + fprintf(stderr, "Failed to initialize GNUnet DNS STUB\n"); + return; + } if (NULL == args[0]) - { - fprintf (stderr, - "You must provide a list of DNS resolvers on the command line\n"); - return; - } - for (unsigned int i = 0; NULL != args[i]; i++) - { - if (GNUNET_OK != GNUNET_DNSSTUB_add_dns_ip (ctx, args[i])) { - fprintf (stderr, "Failed to use `%s' for DNS resolver\n", args[i]); + fprintf(stderr, + "You must provide a list of DNS resolvers on the command line\n"); return; } - } + for (unsigned int i = 0; NULL != args[i]; i++) + { + if (GNUNET_OK != GNUNET_DNSSTUB_add_dns_ip(ctx, args[i])) + { + fprintf(stderr, "Failed to use `%s' for DNS resolver\n", args[i]); + return; + } + } - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL); - ns = GNUNET_NAMESTORE_connect (cfg); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); + ns = GNUNET_NAMESTORE_connect(cfg); if (NULL == ns) - { - GNUNET_SCHEDULER_shutdown (); - return; - } - id = GNUNET_IDENTITY_connect (cfg, &identity_cb, NULL); + { + GNUNET_SCHEDULER_shutdown(); + return; + } + id = GNUNET_IDENTITY_connect(cfg, &identity_cb, NULL); } @@ -1828,46 +1833,46 @@ run (void *cls, * @return 0 on success */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_uint ('s', - "size", - "MAPSIZE", - gettext_noop ( - "size to use for the main hash map"), - &map_size), - GNUNET_GETOPT_option_relative_time ( - 'm', - "minimum-expiration", - "RELATIVETIME", - gettext_noop ("minimum expiration time we assume for imported records"), - &minimum_expiration_time), - GNUNET_GETOPT_OPTION_END}; + { GNUNET_GETOPT_option_uint('s', + "size", + "MAPSIZE", + gettext_noop( + "size to use for the main hash map"), + &map_size), + GNUNET_GETOPT_option_relative_time( + 'm', + "minimum-expiration", + "RELATIVETIME", + gettext_noop("minimum expiration time we assume for imported records"), + &minimum_expiration_time), + GNUNET_GETOPT_OPTION_END }; int ret; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; - if (GNUNET_OK != (ret = GNUNET_PROGRAM_run (argc, - argv, - "gnunet-zoneimport", - "import DNS zone into namestore", - options, - &run, - NULL))) + if (GNUNET_OK != (ret = GNUNET_PROGRAM_run(argc, + argv, + "gnunet-zoneimport", + "import DNS zone into namestore", + options, + &run, + NULL))) return ret; - GNUNET_free ((void *) argv); - fprintf (stderr, - "Rejected %u names, had %u cached, did %u lookups, stored %u record sets\n" - "Found %u records, %u lookups failed, %u/%u pending on shutdown\n", - rejects, - cached, - lookups, - record_sets, - records, - failures, - pending, - pending_rs); + GNUNET_free((void *)argv); + fprintf(stderr, + "Rejected %u names, had %u cached, did %u lookups, stored %u record sets\n" + "Found %u records, %u lookups failed, %u/%u pending on shutdown\n", + rejects, + cached, + lookups, + record_sets, + records, + failures, + pending, + pending_rs); return 0; } diff --git a/src/namestore/namestore.h b/src/namestore/namestore.h index 67d61f9b3..e9a38f0b4 100644 --- a/src/namestore/namestore.h +++ b/src/namestore/namestore.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/namestore.h @@ -37,8 +37,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Generic namestore message with op id */ -struct GNUNET_NAMESTORE_Header -{ +struct GNUNET_NAMESTORE_Header { /** * header.type will be GNUNET_MESSAGE_TYPE_NAMESTORE_* * header.size will be message size @@ -55,8 +54,7 @@ struct GNUNET_NAMESTORE_Header /** * Store a record to the namestore (as authority). */ -struct RecordStoreMessage -{ +struct RecordStoreMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE */ @@ -102,8 +100,7 @@ struct RecordStoreMessage /** * Response to a record storage request. */ -struct RecordStoreResponseMessage -{ +struct RecordStoreResponseMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE */ @@ -119,8 +116,7 @@ struct RecordStoreResponseMessage /** * Lookup a label */ -struct LabelLookupMessage -{ +struct LabelLookupMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP */ @@ -145,8 +141,7 @@ struct LabelLookupMessage /** * Lookup a label */ -struct LabelLookupResponseMessage -{ +struct LabelLookupResponseMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP_RESPONSE */ @@ -189,8 +184,7 @@ struct LabelLookupResponseMessage /** * Lookup a name for a zone hash */ -struct ZoneToNameMessage -{ +struct ZoneToNameMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME */ @@ -211,8 +205,7 @@ struct ZoneToNameMessage /** * Respone for zone to name lookup */ -struct ZoneToNameResponseMessage -{ +struct ZoneToNameResponseMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE */ @@ -248,15 +241,13 @@ struct ZoneToNameResponseMessage * name with length name_len * serialized record data with rd_count records */ - }; /** * Record is returned from the namestore (as authority). */ -struct RecordResultMessage -{ +struct RecordResultMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT */ @@ -297,8 +288,7 @@ struct RecordResultMessage /** * Start monitoring a zone. */ -struct ZoneMonitorStartMessage -{ +struct ZoneMonitorStartMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START */ @@ -314,15 +304,13 @@ struct ZoneMonitorStartMessage * Zone key. */ struct GNUNET_CRYPTO_EcdsaPrivateKey zone; - }; /** * Ask for next result of zone iteration for the given operation */ -struct ZoneMonitorNextMessage -{ +struct ZoneMonitorNextMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_NEXT */ @@ -339,7 +327,6 @@ struct ZoneMonitorNextMessage * should be send again). In NBO. */ uint64_t limit; - }; @@ -347,8 +334,7 @@ struct ZoneMonitorNextMessage /** * Start a zone iteration for the given zone */ -struct ZoneIterationStartMessage -{ +struct ZoneIterationStartMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START */ @@ -358,15 +344,13 @@ struct ZoneIterationStartMessage * Zone key. All zeros for "all zones". */ struct GNUNET_CRYPTO_EcdsaPrivateKey zone; - }; /** * Ask for next result of zone iteration for the given operation */ -struct ZoneIterationNextMessage -{ +struct ZoneIterationNextMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT */ @@ -378,15 +362,13 @@ struct ZoneIterationNextMessage * should be send again). In NBO. */ uint64_t limit; - }; /** * Stop zone iteration for the given operation */ -struct ZoneIterationStopMessage -{ +struct ZoneIterationStopMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP */ diff --git a/src/namestore/namestore_api.c b/src/namestore/namestore_api.c index 6c64062ea..c80ca0bd5 100644 --- a/src/namestore/namestore_api.c +++ b/src/namestore/namestore_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/namestore_api.c @@ -38,7 +38,7 @@ #include "namestore.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "namestore-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "namestore-api", __VA_ARGS__) /** * We grant the namestore up to 1 minute of latency, if it is slower than @@ -50,9 +50,7 @@ * An QueueEntry used to store information for a pending * NAMESTORE record operation */ -struct GNUNET_NAMESTORE_QueueEntry -{ - +struct GNUNET_NAMESTORE_QueueEntry { /** * Kept in a DLL. */ @@ -119,9 +117,7 @@ struct GNUNET_NAMESTORE_QueueEntry /** * Handle for a zone iterator operation */ -struct GNUNET_NAMESTORE_ZoneIterator -{ - +struct GNUNET_NAMESTORE_ZoneIterator { /** * Kept in a DLL. */ @@ -188,9 +184,7 @@ struct GNUNET_NAMESTORE_ZoneIterator /** * Connection to the NAMESTORE service. */ -struct GNUNET_NAMESTORE_Handle -{ - +struct GNUNET_NAMESTORE_Handle { /** * Configuration to use. */ @@ -249,7 +243,7 @@ struct GNUNET_NAMESTORE_Handle * @param h our handle */ static void -force_reconnect (struct GNUNET_NAMESTORE_Handle *h); +force_reconnect(struct GNUNET_NAMESTORE_Handle *h); /** @@ -260,7 +254,7 @@ force_reconnect (struct GNUNET_NAMESTORE_Handle *h); * @return NULL if @a rid was not found */ static struct GNUNET_NAMESTORE_QueueEntry * -find_qe (struct GNUNET_NAMESTORE_Handle *h, uint32_t rid) +find_qe(struct GNUNET_NAMESTORE_Handle *h, uint32_t rid) { struct GNUNET_NAMESTORE_QueueEntry *qe; @@ -279,7 +273,7 @@ find_qe (struct GNUNET_NAMESTORE_Handle *h, uint32_t rid) * @return NULL if @a rid was not found */ static struct GNUNET_NAMESTORE_ZoneIterator * -find_zi (struct GNUNET_NAMESTORE_Handle *h, uint32_t rid) +find_zi(struct GNUNET_NAMESTORE_Handle *h, uint32_t rid) { struct GNUNET_NAMESTORE_ZoneIterator *ze; @@ -296,16 +290,16 @@ find_zi (struct GNUNET_NAMESTORE_Handle *h, uint32_t rid) * @param qe entry to free */ static void -free_qe (struct GNUNET_NAMESTORE_QueueEntry *qe) +free_qe(struct GNUNET_NAMESTORE_QueueEntry *qe) { struct GNUNET_NAMESTORE_Handle *h = qe->h; - GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, qe); + GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, qe); if (NULL != qe->env) - GNUNET_MQ_discard (qe->env); + GNUNET_MQ_discard(qe->env); if (NULL != qe->timeout_task) - GNUNET_SCHEDULER_cancel (qe->timeout_task); - GNUNET_free (qe); + GNUNET_SCHEDULER_cancel(qe->timeout_task); + GNUNET_free(qe); } @@ -315,14 +309,14 @@ free_qe (struct GNUNET_NAMESTORE_QueueEntry *qe) * @param ze entry to free */ static void -free_ze (struct GNUNET_NAMESTORE_ZoneIterator *ze) +free_ze(struct GNUNET_NAMESTORE_ZoneIterator *ze) { struct GNUNET_NAMESTORE_Handle *h = ze->h; - GNUNET_CONTAINER_DLL_remove (h->z_head, h->z_tail, ze); + GNUNET_CONTAINER_DLL_remove(h->z_head, h->z_tail, ze); if (NULL != ze->env) - GNUNET_MQ_discard (ze->env); - GNUNET_free (ze); + GNUNET_MQ_discard(ze->env); + GNUNET_free(ze); } @@ -336,16 +330,16 @@ free_ze (struct GNUNET_NAMESTORE_ZoneIterator *ze) * @return #GNUNET_OK if @a rd_buf is well-formed */ static int -check_rd (size_t rd_len, const void *rd_buf, unsigned int rd_count) +check_rd(size_t rd_len, const void *rd_buf, unsigned int rd_count) { struct GNUNET_GNSRECORD_Data rd[rd_count]; if (GNUNET_OK != - GNUNET_GNSRECORD_records_deserialize (rd_len, rd_buf, rd_count, rd)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + GNUNET_GNSRECORD_records_deserialize(rd_len, rd_buf, rd_count, rd)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -358,27 +352,27 @@ check_rd (size_t rd_len, const void *rd_buf, unsigned int rd_count) * @param msg the message we received */ static void -handle_record_store_response (void *cls, - const struct RecordStoreResponseMessage *msg) +handle_record_store_response(void *cls, + const struct RecordStoreResponseMessage *msg) { struct GNUNET_NAMESTORE_Handle *h = cls; struct GNUNET_NAMESTORE_QueueEntry *qe; int res; const char *emsg; - qe = find_qe (h, ntohl (msg->gns_header.r_id)); - res = ntohl (msg->op_result); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received RECORD_STORE_RESPONSE with result %d\n", - res); + qe = find_qe(h, ntohl(msg->gns_header.r_id)); + res = ntohl(msg->op_result); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received RECORD_STORE_RESPONSE with result %d\n", + res); /* TODO: add actual error message from namestore to response... */ if (GNUNET_SYSERR == res) - emsg = _ ("Namestore failed to store record\n"); + emsg = _("Namestore failed to store record\n"); else emsg = NULL; if (NULL != qe->cont) - qe->cont (qe->cont_cls, res, emsg); - free_qe (qe); + qe->cont(qe->cont_cls, res, emsg); + free_qe(qe); } @@ -391,7 +385,7 @@ handle_record_store_response (void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -check_lookup_result (void *cls, const struct LabelLookupResponseMessage *msg) +check_lookup_result(void *cls, const struct LabelLookupResponseMessage *msg) { const char *name; size_t exp_msg_len; @@ -399,32 +393,32 @@ check_lookup_result (void *cls, const struct LabelLookupResponseMessage *msg) size_t name_len; size_t rd_len; - (void) cls; - rd_len = ntohs (msg->rd_len); - msg_len = ntohs (msg->gns_header.header.size); - name_len = ntohs (msg->name_len); - exp_msg_len = sizeof (*msg) + name_len + rd_len; + (void)cls; + rd_len = ntohs(msg->rd_len); + msg_len = ntohs(msg->gns_header.header.size); + name_len = ntohs(msg->name_len); + exp_msg_len = sizeof(*msg) + name_len + rd_len; if (msg_len != exp_msg_len) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - name = (const char *) &msg[1]; + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + name = (const char *)&msg[1]; if ((name_len > 0) && ('\0' != name[name_len - 1])) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (GNUNET_NO == ntohs (msg->found)) - { - if (0 != ntohs (msg->rd_count)) { - GNUNET_break (0); + GNUNET_break(0); return GNUNET_SYSERR; } - return GNUNET_OK; - } - return check_rd (rd_len, &name[name_len], ntohs (msg->rd_count)); + if (GNUNET_NO == ntohs(msg->found)) + { + if (0 != ntohs(msg->rd_count)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + return GNUNET_OK; + } + return check_rd(rd_len, &name[name_len], ntohs(msg->rd_count)); } @@ -436,7 +430,7 @@ check_lookup_result (void *cls, const struct LabelLookupResponseMessage *msg) * @param msg the message we received */ static void -handle_lookup_result (void *cls, const struct LabelLookupResponseMessage *msg) +handle_lookup_result(void *cls, const struct LabelLookupResponseMessage *msg) { struct GNUNET_NAMESTORE_Handle *h = cls; struct GNUNET_NAMESTORE_QueueEntry *qe; @@ -446,40 +440,40 @@ handle_lookup_result (void *cls, const struct LabelLookupResponseMessage *msg) size_t rd_len; unsigned int rd_count; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Received RECORD_LOOKUP_RESULT\n"); - qe = find_qe (h, ntohl (msg->gns_header.r_id)); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Received RECORD_LOOKUP_RESULT\n"); + qe = find_qe(h, ntohl(msg->gns_header.r_id)); if (NULL == qe) return; - rd_len = ntohs (msg->rd_len); - rd_count = ntohs (msg->rd_count); - name_len = ntohs (msg->name_len); - name = (const char *) &msg[1]; - if (GNUNET_NO == ntohs (msg->found)) - { - /* label was not in namestore */ - if (NULL != qe->proc) - qe->proc (qe->proc_cls, &msg->private_key, name, 0, NULL); - free_qe (qe); - return; - } + rd_len = ntohs(msg->rd_len); + rd_count = ntohs(msg->rd_count); + name_len = ntohs(msg->name_len); + name = (const char *)&msg[1]; + if (GNUNET_NO == ntohs(msg->found)) + { + /* label was not in namestore */ + if (NULL != qe->proc) + qe->proc(qe->proc_cls, &msg->private_key, name, 0, NULL); + free_qe(qe); + return; + } rd_tmp = &name[name_len]; { struct GNUNET_GNSRECORD_Data rd[rd_count]; - GNUNET_assert ( + GNUNET_assert( GNUNET_OK == - GNUNET_GNSRECORD_records_deserialize (rd_len, rd_tmp, rd_count, rd)); + GNUNET_GNSRECORD_records_deserialize(rd_len, rd_tmp, rd_count, rd)); if (0 == name_len) name = NULL; if (NULL != qe->proc) - qe->proc (qe->proc_cls, - &msg->private_key, - name, - rd_count, - (rd_count > 0) ? rd : NULL); + qe->proc(qe->proc_cls, + &msg->private_key, + name, + rd_count, + (rd_count > 0) ? rd : NULL); } - free_qe (qe); + free_qe(qe); } @@ -492,7 +486,7 @@ handle_lookup_result (void *cls, const struct LabelLookupResponseMessage *msg) * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -check_record_result (void *cls, const struct RecordResultMessage *msg) +check_record_result(void *cls, const struct RecordResultMessage *msg) { static struct GNUNET_CRYPTO_EcdsaPrivateKey priv_dummy; const char *name; @@ -500,32 +494,32 @@ check_record_result (void *cls, const struct RecordResultMessage *msg) size_t name_len; size_t rd_len; - (void) cls; - rd_len = ntohs (msg->rd_len); - msg_len = ntohs (msg->gns_header.header.size); - name_len = ntohs (msg->name_len); - if (0 != ntohs (msg->reserved)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (msg_len != sizeof (struct RecordResultMessage) + name_len + rd_len) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - name = (const char *) &msg[1]; + (void)cls; + rd_len = ntohs(msg->rd_len); + msg_len = ntohs(msg->gns_header.header.size); + name_len = ntohs(msg->name_len); + if (0 != ntohs(msg->reserved)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (msg_len != sizeof(struct RecordResultMessage) + name_len + rd_len) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + name = (const char *)&msg[1]; if ((0 == name_len) || ('\0' != name[name_len - 1])) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (0 == GNUNET_memcmp (&msg->private_key, &priv_dummy)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - return check_rd (rd_len, &name[name_len], ntohs (msg->rd_count)); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (0 == GNUNET_memcmp(&msg->private_key, &priv_dummy)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + return check_rd(rd_len, &name[name_len], ntohs(msg->rd_count)); } @@ -537,7 +531,7 @@ check_record_result (void *cls, const struct RecordResultMessage *msg) * @param msg the message we received */ static void -handle_record_result (void *cls, const struct RecordResultMessage *msg) +handle_record_result(void *cls, const struct RecordResultMessage *msg) { struct GNUNET_NAMESTORE_Handle *h = cls; struct GNUNET_NAMESTORE_QueueEntry *qe; @@ -548,49 +542,49 @@ handle_record_result (void *cls, const struct RecordResultMessage *msg) size_t rd_len; unsigned int rd_count; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Received RECORD_RESULT\n"); - rd_len = ntohs (msg->rd_len); - rd_count = ntohs (msg->rd_count); - name_len = ntohs (msg->name_len); - ze = find_zi (h, ntohl (msg->gns_header.r_id)); - qe = find_qe (h, ntohl (msg->gns_header.r_id)); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Received RECORD_RESULT\n"); + rd_len = ntohs(msg->rd_len); + rd_count = ntohs(msg->rd_count); + name_len = ntohs(msg->name_len); + ze = find_zi(h, ntohl(msg->gns_header.r_id)); + qe = find_qe(h, ntohl(msg->gns_header.r_id)); if ((NULL == ze) && (NULL == qe)) return; /* rid not found */ if ((NULL != ze) && (NULL != qe)) - { - GNUNET_break (0); /* rid ambigous */ - force_reconnect (h); - return; - } - name = (const char *) &msg[1]; + { + GNUNET_break(0); /* rid ambigous */ + force_reconnect(h); + return; + } + name = (const char *)&msg[1]; rd_tmp = &name[name_len]; { struct GNUNET_GNSRECORD_Data rd[rd_count]; - GNUNET_assert ( + GNUNET_assert( GNUNET_OK == - GNUNET_GNSRECORD_records_deserialize (rd_len, rd_tmp, rd_count, rd)); + GNUNET_GNSRECORD_records_deserialize(rd_len, rd_tmp, rd_count, rd)); if (0 == name_len) name = NULL; if (NULL != qe) - { - if (NULL != qe->proc) - qe->proc (qe->proc_cls, - &msg->private_key, - name, - rd_count, - (rd_count > 0) ? rd : NULL); - free_qe (qe); - return; - } + { + if (NULL != qe->proc) + qe->proc(qe->proc_cls, + &msg->private_key, + name, + rd_count, + (rd_count > 0) ? rd : NULL); + free_qe(qe); + return; + } if (NULL != ze) - { - if (NULL != ze->proc) - ze->proc (ze->proc_cls, &msg->private_key, name, rd_count, rd); - return; - } + { + if (NULL != ze->proc) + ze->proc(ze->proc_cls, &msg->private_key, name, rd_count, rd); + return; + } } - GNUNET_assert (0); + GNUNET_assert(0); } @@ -602,33 +596,33 @@ handle_record_result (void *cls, const struct RecordResultMessage *msg) * @param msg the message we received */ static void -handle_record_result_end (void *cls, const struct GNUNET_NAMESTORE_Header *msg) +handle_record_result_end(void *cls, const struct GNUNET_NAMESTORE_Header *msg) { struct GNUNET_NAMESTORE_Handle *h = cls; struct GNUNET_NAMESTORE_QueueEntry *qe; struct GNUNET_NAMESTORE_ZoneIterator *ze; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Received RECORD_RESULT_END\n"); - ze = find_zi (h, ntohl (msg->r_id)); - qe = find_qe (h, ntohl (msg->r_id)); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Received RECORD_RESULT_END\n"); + ze = find_zi(h, ntohl(msg->r_id)); + qe = find_qe(h, ntohl(msg->r_id)); if ((NULL == ze) && (NULL == qe)) return; /* rid not found */ if ((NULL != ze) && (NULL != qe)) - { - GNUNET_break (0); /* rid ambigous */ - force_reconnect (h); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, "Zone iteration completed!\n"); + { + GNUNET_break(0); /* rid ambigous */ + force_reconnect(h); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, "Zone iteration completed!\n"); if (NULL == ze) - { - GNUNET_break (0); - force_reconnect (h); - return; - } + { + GNUNET_break(0); + force_reconnect(h); + return; + } if (NULL != ze->finish_cb) - ze->finish_cb (ze->finish_cb_cls); - free_ze (ze); + ze->finish_cb(ze->finish_cb_cls); + free_ze(ze); } @@ -641,31 +635,31 @@ handle_record_result_end (void *cls, const struct GNUNET_NAMESTORE_Header *msg) * @return #GNUNET_OK on success, #GNUNET_SYSERR if message malformed */ static int -check_zone_to_name_response (void *cls, - const struct ZoneToNameResponseMessage *msg) +check_zone_to_name_response(void *cls, + const struct ZoneToNameResponseMessage *msg) { size_t name_len; size_t rd_ser_len; const char *name_tmp; - (void) cls; - if (GNUNET_OK != ntohs (msg->res)) + (void)cls; + if (GNUNET_OK != ntohs(msg->res)) return GNUNET_OK; - name_len = ntohs (msg->name_len); - rd_ser_len = ntohs (msg->rd_len); - if (ntohs (msg->gns_header.header.size) != - sizeof (struct ZoneToNameResponseMessage) + name_len + rd_ser_len) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - name_tmp = (const char *) &msg[1]; + name_len = ntohs(msg->name_len); + rd_ser_len = ntohs(msg->rd_len); + if (ntohs(msg->gns_header.header.size) != + sizeof(struct ZoneToNameResponseMessage) + name_len + rd_ser_len) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + name_tmp = (const char *)&msg[1]; if ((name_len > 0) && ('\0' != name_tmp[name_len - 1])) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - return check_rd (rd_ser_len, &name_tmp[name_len], ntohs (msg->rd_count)); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + return check_rd(rd_ser_len, &name_tmp[name_len], ntohs(msg->rd_count)); } @@ -677,8 +671,8 @@ check_zone_to_name_response (void *cls, * @param msg the message we received */ static void -handle_zone_to_name_response (void *cls, - const struct ZoneToNameResponseMessage *msg) +handle_zone_to_name_response(void *cls, + const struct ZoneToNameResponseMessage *msg) { struct GNUNET_NAMESTORE_Handle *h = cls; struct GNUNET_NAMESTORE_QueueEntry *qe; @@ -689,54 +683,57 @@ handle_zone_to_name_response (void *cls, const char *name_tmp; const char *rd_tmp; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Received ZONE_TO_NAME_RESPONSE\n"); - qe = find_qe (h, ntohl (msg->gns_header.r_id)); - res = ntohs (msg->res); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Received ZONE_TO_NAME_RESPONSE\n"); + qe = find_qe(h, ntohl(msg->gns_header.r_id)); + res = ntohs(msg->res); switch (res) - { - case GNUNET_SYSERR: - LOG (GNUNET_ERROR_TYPE_DEBUG, - "An error occurred during zone to name operation\n"); - break; - case GNUNET_NO: - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Namestore has no result for zone to name mapping \n"); - if (NULL != qe->proc) - qe->proc (qe->proc_cls, &msg->zone, NULL, 0, NULL); - free_qe (qe); - return; - case GNUNET_YES: - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Namestore has result for zone to name mapping \n"); - name_len = ntohs (msg->name_len); - rd_count = ntohs (msg->rd_count); - rd_ser_len = ntohs (msg->rd_len); - name_tmp = (const char *) &msg[1]; - rd_tmp = &name_tmp[name_len]; { - struct GNUNET_GNSRECORD_Data rd[rd_count]; + case GNUNET_SYSERR: + LOG(GNUNET_ERROR_TYPE_DEBUG, + "An error occurred during zone to name operation\n"); + break; + + case GNUNET_NO: + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Namestore has no result for zone to name mapping \n"); + if (NULL != qe->proc) + qe->proc(qe->proc_cls, &msg->zone, NULL, 0, NULL); + free_qe(qe); + return; - GNUNET_assert (GNUNET_OK == - GNUNET_GNSRECORD_records_deserialize (rd_ser_len, + case GNUNET_YES: + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Namestore has result for zone to name mapping \n"); + name_len = ntohs(msg->name_len); + rd_count = ntohs(msg->rd_count); + rd_ser_len = ntohs(msg->rd_len); + name_tmp = (const char *)&msg[1]; + rd_tmp = &name_tmp[name_len]; + { + struct GNUNET_GNSRECORD_Data rd[rd_count]; + + GNUNET_assert(GNUNET_OK == + GNUNET_GNSRECORD_records_deserialize(rd_ser_len, rd_tmp, rd_count, rd)); - /* normal end, call continuation with result */ - if (NULL != qe->proc) - qe->proc (qe->proc_cls, &msg->zone, name_tmp, rd_count, rd); - /* return is important here: break would call continuation with error! */ - free_qe (qe); + /* normal end, call continuation with result */ + if (NULL != qe->proc) + qe->proc(qe->proc_cls, &msg->zone, name_tmp, rd_count, rd); + /* return is important here: break would call continuation with error! */ + free_qe(qe); + return; + } + + default: + GNUNET_break(0); + force_reconnect(h); return; } - default: - GNUNET_break (0); - force_reconnect (h); - return; - } /* error case, call continuation with error */ if (NULL != qe->error_cb) - qe->error_cb (qe->error_cb_cls); - free_qe (qe); + qe->error_cb(qe->error_cb_cls); + free_qe(qe); } @@ -749,12 +746,12 @@ handle_zone_to_name_response (void *cls, * @param error error code */ static void -mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_NAMESTORE_Handle *h = cls; - (void) error; - force_reconnect (h); + (void)error; + force_reconnect(h); } @@ -764,49 +761,49 @@ mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @param h the handle to the NAMESTORE service */ static void -reconnect (struct GNUNET_NAMESTORE_Handle *h) +reconnect(struct GNUNET_NAMESTORE_Handle *h) { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_fixed_size (record_store_response, - GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE, - struct RecordStoreResponseMessage, - h), - GNUNET_MQ_hd_var_size (zone_to_name_response, - GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE, - struct ZoneToNameResponseMessage, - h), - GNUNET_MQ_hd_var_size (record_result, - GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT, - struct RecordResultMessage, + { GNUNET_MQ_hd_fixed_size(record_store_response, + GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE_RESPONSE, + struct RecordStoreResponseMessage, h), - GNUNET_MQ_hd_fixed_size (record_result_end, - GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT_END, - struct GNUNET_NAMESTORE_Header, - h), - GNUNET_MQ_hd_var_size (lookup_result, - GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP_RESPONSE, - struct LabelLookupResponseMessage, + GNUNET_MQ_hd_var_size(zone_to_name_response, + GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME_RESPONSE, + struct ZoneToNameResponseMessage, + h), + GNUNET_MQ_hd_var_size(record_result, + GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT, + struct RecordResultMessage, + h), + GNUNET_MQ_hd_fixed_size(record_result_end, + GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT_END, + struct GNUNET_NAMESTORE_Header, h), - GNUNET_MQ_handler_end ()}; + GNUNET_MQ_hd_var_size(lookup_result, + GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP_RESPONSE, + struct LabelLookupResponseMessage, + h), + GNUNET_MQ_handler_end() }; struct GNUNET_NAMESTORE_ZoneIterator *it; struct GNUNET_NAMESTORE_QueueEntry *qe; - GNUNET_assert (NULL == h->mq); + GNUNET_assert(NULL == h->mq); h->mq = - GNUNET_CLIENT_connect (h->cfg, "namestore", handlers, &mq_error_handler, h); + GNUNET_CLIENT_connect(h->cfg, "namestore", handlers, &mq_error_handler, h); if (NULL == h->mq) return; /* re-transmit pending requests that waited for a reconnect... */ for (it = h->z_head; NULL != it; it = it->next) - { - GNUNET_MQ_send (h->mq, it->env); - it->env = NULL; - } + { + GNUNET_MQ_send(h->mq, it->env); + it->env = NULL; + } for (qe = h->op_head; NULL != qe; qe = qe->next) - { - GNUNET_MQ_send (h->mq, qe->env); - qe->env = NULL; - } + { + GNUNET_MQ_send(h->mq, qe->env); + qe->env = NULL; + } } @@ -816,12 +813,12 @@ reconnect (struct GNUNET_NAMESTORE_Handle *h) * @param cls handle to use to re-connect. */ static void -reconnect_task (void *cls) +reconnect_task(void *cls) { struct GNUNET_NAMESTORE_Handle *h = cls; h->reconnect_task = NULL; - reconnect (h); + reconnect(h); } @@ -831,34 +828,34 @@ reconnect_task (void *cls) * @param h our handle */ static void -force_reconnect (struct GNUNET_NAMESTORE_Handle *h) +force_reconnect(struct GNUNET_NAMESTORE_Handle *h) { struct GNUNET_NAMESTORE_ZoneIterator *ze; struct GNUNET_NAMESTORE_QueueEntry *qe; - GNUNET_MQ_destroy (h->mq); + GNUNET_MQ_destroy(h->mq); h->mq = NULL; while (NULL != (ze = h->z_head)) - { - if (NULL != ze->error_cb) - ze->error_cb (ze->error_cb_cls); - free_ze (ze); - } + { + if (NULL != ze->error_cb) + ze->error_cb(ze->error_cb_cls); + free_ze(ze); + } while (NULL != (qe = h->op_head)) - { - if (NULL != qe->error_cb) - qe->error_cb (qe->error_cb_cls); - if (NULL != qe->cont) - qe->cont (qe->cont_cls, - GNUNET_SYSERR, - "failure in communication with namestore service"); - free_qe (qe); - } + { + if (NULL != qe->error_cb) + qe->error_cb(qe->error_cb_cls); + if (NULL != qe->cont) + qe->cont(qe->cont_cls, + GNUNET_SYSERR, + "failure in communication with namestore service"); + free_qe(qe); + } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Reconnecting to namestore\n"); - h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Reconnecting to namestore\n"); + h->reconnect_delay = GNUNET_TIME_STD_BACKOFF(h->reconnect_delay); h->reconnect_task = - GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, &reconnect_task, h); + GNUNET_SCHEDULER_add_delayed(h->reconnect_delay, &reconnect_task, h); } @@ -869,7 +866,7 @@ force_reconnect (struct GNUNET_NAMESTORE_Handle *h) * @return next operation id to use */ static uint32_t -get_op_id (struct GNUNET_NAMESTORE_Handle *h) +get_op_id(struct GNUNET_NAMESTORE_Handle *h) { return h->last_op_id_used++; } @@ -882,18 +879,18 @@ get_op_id (struct GNUNET_NAMESTORE_Handle *h) * @return handle to the GNS service, or NULL on error */ struct GNUNET_NAMESTORE_Handle * -GNUNET_NAMESTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_NAMESTORE_connect(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_NAMESTORE_Handle *h; - h = GNUNET_new (struct GNUNET_NAMESTORE_Handle); + h = GNUNET_new(struct GNUNET_NAMESTORE_Handle); h->cfg = cfg; - reconnect (h); + reconnect(h); if (NULL == h->mq) - { - GNUNET_free (h); - return NULL; - } + { + GNUNET_free(h); + return NULL; + } return h; } @@ -905,35 +902,35 @@ GNUNET_NAMESTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) * @param h handle to the namestore */ void -GNUNET_NAMESTORE_disconnect (struct GNUNET_NAMESTORE_Handle *h) +GNUNET_NAMESTORE_disconnect(struct GNUNET_NAMESTORE_Handle *h) { struct GNUNET_NAMESTORE_QueueEntry *q; struct GNUNET_NAMESTORE_ZoneIterator *z; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); - GNUNET_break (NULL == h->op_head); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); + GNUNET_break(NULL == h->op_head); while (NULL != (q = h->op_head)) - { - GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, q); - GNUNET_free (q); - } - GNUNET_break (NULL == h->z_head); + { + GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, q); + GNUNET_free(q); + } + GNUNET_break(NULL == h->z_head); while (NULL != (z = h->z_head)) - { - GNUNET_CONTAINER_DLL_remove (h->z_head, h->z_tail, z); - GNUNET_free (z); - } + { + GNUNET_CONTAINER_DLL_remove(h->z_head, h->z_tail, z); + GNUNET_free(z); + } if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } if (NULL != h->reconnect_task) - { - GNUNET_SCHEDULER_cancel (h->reconnect_task); - h->reconnect_task = NULL; - } - GNUNET_free (h); + { + GNUNET_SCHEDULER_cancel(h->reconnect_task); + h->reconnect_task = NULL; + } + GNUNET_free(h); } @@ -944,21 +941,21 @@ GNUNET_NAMESTORE_disconnect (struct GNUNET_NAMESTORE_Handle *h) * @param cls a `struct GNUNET_NAMESTORE_QueueEntry *` */ static void -warn_delay (void *cls) +warn_delay(void *cls) { struct GNUNET_NAMESTORE_QueueEntry *qe = cls; qe->timeout_task = NULL; - LOG (GNUNET_ERROR_TYPE_WARNING, - "Did not receive response from namestore after %s!\n", - GNUNET_STRINGS_relative_time_to_string (NAMESTORE_DELAY_TOLERANCE, - GNUNET_YES)); + LOG(GNUNET_ERROR_TYPE_WARNING, + "Did not receive response from namestore after %s!\n", + GNUNET_STRINGS_relative_time_to_string(NAMESTORE_DELAY_TOLERANCE, + GNUNET_YES)); if (NULL != qe->cont) - { - qe->cont (qe->cont_cls, GNUNET_SYSERR, "timeout"); - qe->cont = NULL; - } - GNUNET_NAMESTORE_cancel (qe); + { + qe->cont(qe->cont_cls, GNUNET_SYSERR, "timeout"); + qe->cont = NULL; + } + GNUNET_NAMESTORE_cancel(qe); } @@ -977,7 +974,7 @@ warn_delay (void *cls) * @return handle to abort the request */ struct GNUNET_NAMESTORE_QueueEntry * -GNUNET_NAMESTORE_records_store ( +GNUNET_NAMESTORE_records_store( struct GNUNET_NAMESTORE_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, const char *label, @@ -996,69 +993,69 @@ GNUNET_NAMESTORE_records_store ( struct RecordStoreMessage *msg; ssize_t sret; - name_len = strlen (label) + 1; + name_len = strlen(label) + 1; if (name_len > MAX_NAME_LEN) - { - GNUNET_break (0); - return NULL; - } - rd_ser_len = GNUNET_GNSRECORD_records_get_size (rd_count, rd); + { + GNUNET_break(0); + return NULL; + } + rd_ser_len = GNUNET_GNSRECORD_records_get_size(rd_count, rd); if (rd_ser_len < 0) - { - GNUNET_break (0); - return NULL; - } + { + GNUNET_break(0); + return NULL; + } if (rd_ser_len > UINT16_MAX) - { - GNUNET_break (0); - return NULL; - } - rid = get_op_id (h); - qe = GNUNET_new (struct GNUNET_NAMESTORE_QueueEntry); + { + GNUNET_break(0); + return NULL; + } + rid = get_op_id(h); + qe = GNUNET_new(struct GNUNET_NAMESTORE_QueueEntry); qe->h = h; qe->cont = cont; qe->cont_cls = cont_cls; qe->op_id = rid; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, qe); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, qe); /* setup msg */ - env = GNUNET_MQ_msg_extra (msg, - name_len + rd_ser_len, - GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE); - msg->gns_header.r_id = htonl (rid); - msg->name_len = htons (name_len); - msg->rd_count = htons (rd_count); - msg->rd_len = htons (rd_ser_len); - msg->reserved = htons (0); + env = GNUNET_MQ_msg_extra(msg, + name_len + rd_ser_len, + GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_STORE); + msg->gns_header.r_id = htonl(rid); + msg->name_len = htons(name_len); + msg->rd_count = htons(rd_count); + msg->rd_len = htons(rd_ser_len); + msg->reserved = htons(0); msg->private_key = *pkey; - name_tmp = (char *) &msg[1]; - GNUNET_memcpy (name_tmp, label, name_len); + name_tmp = (char *)&msg[1]; + GNUNET_memcpy(name_tmp, label, name_len); rd_ser = &name_tmp[name_len]; - sret = GNUNET_GNSRECORD_records_serialize (rd_count, rd, rd_ser_len, rd_ser); + sret = GNUNET_GNSRECORD_records_serialize(rd_count, rd, rd_ser_len, rd_ser); if ((0 > sret) || (sret != rd_ser_len)) - { - GNUNET_break (0); - GNUNET_free (env); - return NULL; - } - GNUNET_assert (rd_ser_len == sret); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending NAMESTORE_RECORD_STORE message for name `%s' with %u records\n", - label, - rd_count); + { + GNUNET_break(0); + GNUNET_free(env); + return NULL; + } + GNUNET_assert(rd_ser_len == sret); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending NAMESTORE_RECORD_STORE message for name `%s' with %u records\n", + label, + rd_count); qe->timeout_task = - GNUNET_SCHEDULER_add_delayed (NAMESTORE_DELAY_TOLERANCE, &warn_delay, qe); + GNUNET_SCHEDULER_add_delayed(NAMESTORE_DELAY_TOLERANCE, &warn_delay, qe); if (NULL == h->mq) - { - qe->env = env; - LOG (GNUNET_ERROR_TYPE_WARNING, - "Delaying NAMESTORE_RECORD_STORE message as namestore is not ready!\n"); - } + { + qe->env = env; + LOG(GNUNET_ERROR_TYPE_WARNING, + "Delaying NAMESTORE_RECORD_STORE message as namestore is not ready!\n"); + } else - { - GNUNET_MQ_send (h->mq, env); - } + { + GNUNET_MQ_send(h->mq, env); + } return qe; } @@ -1074,29 +1071,29 @@ GNUNET_NAMESTORE_records_store ( * @return handle to abort the request */ struct GNUNET_NAMESTORE_QueueEntry * -GNUNET_NAMESTORE_set_nick (struct GNUNET_NAMESTORE_Handle *h, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, - const char *nick, - GNUNET_NAMESTORE_ContinuationWithStatus cont, - void *cont_cls) +GNUNET_NAMESTORE_set_nick(struct GNUNET_NAMESTORE_Handle *h, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, + const char *nick, + GNUNET_NAMESTORE_ContinuationWithStatus cont, + void *cont_cls) { struct GNUNET_GNSRECORD_Data rd; if (NULL == h->mq) return NULL; - memset (&rd, 0, sizeof (rd)); + memset(&rd, 0, sizeof(rd)); rd.data = nick; - rd.data_size = strlen (nick) + 1; + rd.data_size = strlen(nick) + 1; rd.record_type = GNUNET_GNSRECORD_TYPE_NICK; rd.expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us; rd.flags |= GNUNET_GNSRECORD_RF_PRIVATE; - return GNUNET_NAMESTORE_records_store (h, - pkey, - GNUNET_GNS_EMPTY_LABEL_AT, - 1, - &rd, - cont, - cont_cls); + return GNUNET_NAMESTORE_records_store(h, + pkey, + GNUNET_GNS_EMPTY_LABEL_AT, + 1, + &rd, + cont, + cont_cls); } @@ -1113,7 +1110,7 @@ GNUNET_NAMESTORE_set_nick (struct GNUNET_NAMESTORE_Handle *h, * @return handle to abort the request */ struct GNUNET_NAMESTORE_QueueEntry * -GNUNET_NAMESTORE_records_lookup ( +GNUNET_NAMESTORE_records_lookup( struct GNUNET_NAMESTORE_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, const char *label, @@ -1127,32 +1124,32 @@ GNUNET_NAMESTORE_records_lookup ( struct LabelLookupMessage *msg; size_t label_len; - if (1 == (label_len = strlen (label) + 1)) - { - GNUNET_break (0); - return NULL; - } + if (1 == (label_len = strlen(label) + 1)) + { + GNUNET_break(0); + return NULL; + } - qe = GNUNET_new (struct GNUNET_NAMESTORE_QueueEntry); + qe = GNUNET_new(struct GNUNET_NAMESTORE_QueueEntry); qe->h = h; qe->error_cb = error_cb; qe->error_cb_cls = error_cb_cls; qe->proc = rm; qe->proc_cls = rm_cls; - qe->op_id = get_op_id (h); - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, qe); + qe->op_id = get_op_id(h); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, qe); - env = GNUNET_MQ_msg_extra (msg, - label_len, - GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP); - msg->gns_header.r_id = htonl (qe->op_id); + env = GNUNET_MQ_msg_extra(msg, + label_len, + GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_LOOKUP); + msg->gns_header.r_id = htonl(qe->op_id); msg->zone = *pkey; - msg->label_len = htonl (label_len); - GNUNET_memcpy (&msg[1], label, label_len); + msg->label_len = htonl(label_len); + GNUNET_memcpy(&msg[1], label, label_len); if (NULL == h->mq) qe->env = env; else - GNUNET_MQ_send (h->mq, env); + GNUNET_MQ_send(h->mq, env); return qe; } @@ -1173,7 +1170,7 @@ GNUNET_NAMESTORE_records_lookup ( * cancel */ struct GNUNET_NAMESTORE_QueueEntry * -GNUNET_NAMESTORE_zone_to_name ( +GNUNET_NAMESTORE_zone_to_name( struct GNUNET_NAMESTORE_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone, @@ -1187,24 +1184,24 @@ GNUNET_NAMESTORE_zone_to_name ( struct ZoneToNameMessage *msg; uint32_t rid; - rid = get_op_id (h); - qe = GNUNET_new (struct GNUNET_NAMESTORE_QueueEntry); + rid = get_op_id(h); + qe = GNUNET_new(struct GNUNET_NAMESTORE_QueueEntry); qe->h = h; qe->error_cb = error_cb; qe->error_cb_cls = error_cb_cls; qe->proc = proc; qe->proc_cls = proc_cls; qe->op_id = rid; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, qe); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, qe); - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME); - msg->gns_header.r_id = htonl (rid); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_TO_NAME); + msg->gns_header.r_id = htonl(rid); msg->zone = *zone; msg->value_zone = *value_zone; if (NULL == h->mq) qe->env = env; else - GNUNET_MQ_send (h->mq, env); + GNUNET_MQ_send(h->mq, env); return qe; } @@ -1229,7 +1226,7 @@ GNUNET_NAMESTORE_zone_to_name ( * @return an iterator handle to use for iteration */ struct GNUNET_NAMESTORE_ZoneIterator * -GNUNET_NAMESTORE_zone_iteration_start ( +GNUNET_NAMESTORE_zone_iteration_start( struct GNUNET_NAMESTORE_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, GNUNET_SCHEDULER_TaskCallback error_cb, @@ -1244,9 +1241,9 @@ GNUNET_NAMESTORE_zone_iteration_start ( struct ZoneIterationStartMessage *msg; uint32_t rid; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending ZONE_ITERATION_START message\n"); - rid = get_op_id (h); - it = GNUNET_new (struct GNUNET_NAMESTORE_ZoneIterator); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Sending ZONE_ITERATION_START message\n"); + rid = get_op_id(h); + it = GNUNET_new(struct GNUNET_NAMESTORE_ZoneIterator); it->h = h; it->error_cb = error_cb; it->error_cb_cls = error_cb_cls; @@ -1257,15 +1254,15 @@ GNUNET_NAMESTORE_zone_iteration_start ( it->op_id = rid; if (NULL != zone) it->zone = *zone; - GNUNET_CONTAINER_DLL_insert_tail (h->z_head, h->z_tail, it); - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START); - msg->gns_header.r_id = htonl (rid); + GNUNET_CONTAINER_DLL_insert_tail(h->z_head, h->z_tail, it); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_START); + msg->gns_header.r_id = htonl(rid); if (NULL != zone) msg->zone = *zone; if (NULL == h->mq) it->env = env; else - GNUNET_MQ_send (h->mq, env); + GNUNET_MQ_send(h->mq, env); return it; } @@ -1279,20 +1276,20 @@ GNUNET_NAMESTORE_zone_iteration_start ( * (before #GNUNET_NAMESTORE_zone_iterator_next is to be called again) */ void -GNUNET_NAMESTORE_zone_iterator_next (struct GNUNET_NAMESTORE_ZoneIterator *it, - uint64_t limit) +GNUNET_NAMESTORE_zone_iterator_next(struct GNUNET_NAMESTORE_ZoneIterator *it, + uint64_t limit) { struct GNUNET_NAMESTORE_Handle *h = it->h; struct ZoneIterationNextMessage *msg; struct GNUNET_MQ_Envelope *env; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending ZONE_ITERATION_NEXT message with limit %llu\n", - (unsigned long long) limit); - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT); - msg->gns_header.r_id = htonl (it->op_id); - msg->limit = GNUNET_htonll (limit); - GNUNET_MQ_send (h->mq, env); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending ZONE_ITERATION_NEXT message with limit %llu\n", + (unsigned long long)limit); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_NEXT); + msg->gns_header.r_id = htonl(it->op_id); + msg->limit = GNUNET_htonll(limit); + GNUNET_MQ_send(h->mq, env); } @@ -1302,21 +1299,21 @@ GNUNET_NAMESTORE_zone_iterator_next (struct GNUNET_NAMESTORE_ZoneIterator *it, * @param it the iterator */ void -GNUNET_NAMESTORE_zone_iteration_stop (struct GNUNET_NAMESTORE_ZoneIterator *it) +GNUNET_NAMESTORE_zone_iteration_stop(struct GNUNET_NAMESTORE_ZoneIterator *it) { struct GNUNET_NAMESTORE_Handle *h = it->h; struct GNUNET_MQ_Envelope *env; struct ZoneIterationStopMessage *msg; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending ZONE_ITERATION_STOP message\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending ZONE_ITERATION_STOP message\n"); if (NULL != h->mq) - { - env = - GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP); - msg->gns_header.r_id = htonl (it->op_id); - GNUNET_MQ_send (h->mq, env); - } - free_ze (it); + { + env = + GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_NAMESTORE_ZONE_ITERATION_STOP); + msg->gns_header.r_id = htonl(it->op_id); + GNUNET_MQ_send(h->mq, env); + } + free_ze(it); } @@ -1327,9 +1324,9 @@ GNUNET_NAMESTORE_zone_iteration_stop (struct GNUNET_NAMESTORE_ZoneIterator *it) * @param qe operation to cancel */ void -GNUNET_NAMESTORE_cancel (struct GNUNET_NAMESTORE_QueueEntry *qe) +GNUNET_NAMESTORE_cancel(struct GNUNET_NAMESTORE_QueueEntry *qe) { - free_qe (qe); + free_qe(qe); } diff --git a/src/namestore/namestore_api_monitor.c b/src/namestore/namestore_api_monitor.c index 2881a28ac..d87a76eed 100644 --- a/src/namestore/namestore_api_monitor.c +++ b/src/namestore/namestore_api_monitor.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/namestore_api_monitor.c * @brief API to monitor changes in the NAMESTORE @@ -37,8 +37,7 @@ /** * Handle for a monitoring activity. */ -struct GNUNET_NAMESTORE_ZoneMonitor -{ +struct GNUNET_NAMESTORE_ZoneMonitor { /** * Configuration (to reconnect). */ @@ -97,7 +96,7 @@ struct GNUNET_NAMESTORE_ZoneMonitor * @param zm monitor to reconnect */ static void -reconnect (struct GNUNET_NAMESTORE_ZoneMonitor *zm); +reconnect(struct GNUNET_NAMESTORE_ZoneMonitor *zm); /** @@ -107,14 +106,14 @@ reconnect (struct GNUNET_NAMESTORE_ZoneMonitor *zm); * @param msg the sync message */ static void -handle_sync (void *cls, const struct GNUNET_MessageHeader *msg) +handle_sync(void *cls, const struct GNUNET_MessageHeader *msg) { struct GNUNET_NAMESTORE_ZoneMonitor *zm = cls; - (void) cls; - (void) msg; + (void)cls; + (void)msg; if (NULL != zm->sync_cb) - zm->sync_cb (zm->sync_cb_cls); + zm->sync_cb(zm->sync_cb_cls); } @@ -126,7 +125,7 @@ handle_sync (void *cls, const struct GNUNET_MessageHeader *msg) * @param lrm the message from the service. */ static int -check_result (void *cls, const struct RecordResultMessage *lrm) +check_result(void *cls, const struct RecordResultMessage *lrm) { struct GNUNET_NAMESTORE_ZoneMonitor *zm = cls; size_t lrm_len; @@ -137,49 +136,49 @@ check_result (void *cls, const struct RecordResultMessage *lrm) const char *name_tmp; const char *rd_ser_tmp; - (void) cls; - if ((0 != GNUNET_memcmp (&lrm->private_key, &zm->zone)) && - (0 != GNUNET_is_zero (&zm->zone))) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - lrm_len = ntohs (lrm->gns_header.header.size); - rd_len = ntohs (lrm->rd_len); - rd_count = ntohs (lrm->rd_count); - name_len = ntohs (lrm->name_len); + (void)cls; + if ((0 != GNUNET_memcmp(&lrm->private_key, &zm->zone)) && + (0 != GNUNET_is_zero(&zm->zone))) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + lrm_len = ntohs(lrm->gns_header.header.size); + rd_len = ntohs(lrm->rd_len); + rd_count = ntohs(lrm->rd_count); + name_len = ntohs(lrm->name_len); if (name_len > MAX_NAME_LEN) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - exp_lrm_len = sizeof (struct RecordResultMessage) + name_len + rd_len; + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + exp_lrm_len = sizeof(struct RecordResultMessage) + name_len + rd_len; if (lrm_len != exp_lrm_len) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } if (0 == name_len) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - name_tmp = (const char *) &lrm[1]; + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + name_tmp = (const char *)&lrm[1]; if (name_tmp[name_len - 1] != '\0') - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - rd_ser_tmp = (const char *) &name_tmp[name_len]; + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + rd_ser_tmp = (const char *)&name_tmp[name_len]; { struct GNUNET_GNSRECORD_Data rd[rd_count]; if (GNUNET_OK != - GNUNET_GNSRECORD_records_deserialize (rd_len, rd_ser_tmp, rd_count, rd)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + GNUNET_GNSRECORD_records_deserialize(rd_len, rd_ser_tmp, rd_count, rd)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } } return GNUNET_OK; } @@ -193,7 +192,7 @@ check_result (void *cls, const struct RecordResultMessage *lrm) * @param lrm the message from the service. */ static void -handle_result (void *cls, const struct RecordResultMessage *lrm) +handle_result(void *cls, const struct RecordResultMessage *lrm) { struct GNUNET_NAMESTORE_ZoneMonitor *zm = cls; size_t name_len; @@ -202,18 +201,18 @@ handle_result (void *cls, const struct RecordResultMessage *lrm) const char *name_tmp; const char *rd_ser_tmp; - rd_len = ntohs (lrm->rd_len); - rd_count = ntohs (lrm->rd_count); - name_len = ntohs (lrm->name_len); - name_tmp = (const char *) &lrm[1]; - rd_ser_tmp = (const char *) &name_tmp[name_len]; + rd_len = ntohs(lrm->rd_len); + rd_count = ntohs(lrm->rd_count); + name_len = ntohs(lrm->name_len); + name_tmp = (const char *)&lrm[1]; + rd_ser_tmp = (const char *)&name_tmp[name_len]; { struct GNUNET_GNSRECORD_Data rd[rd_count]; - GNUNET_assert ( + GNUNET_assert( GNUNET_OK == - GNUNET_GNSRECORD_records_deserialize (rd_len, rd_ser_tmp, rd_count, rd)); - zm->monitor (zm->monitor_cls, &lrm->private_key, name_tmp, rd_count, rd); + GNUNET_GNSRECORD_records_deserialize(rd_len, rd_ser_tmp, rd_count, rd)); + zm->monitor(zm->monitor_cls, &lrm->private_key, name_tmp, rd_count, rd); } } @@ -227,12 +226,12 @@ handle_result (void *cls, const struct RecordResultMessage *lrm) * @param error error code */ static void -mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_NAMESTORE_ZoneMonitor *zm = cls; - (void) error; - reconnect (zm); + (void)error; + reconnect(zm); } @@ -242,37 +241,37 @@ mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @param zm monitor to reconnect */ static void -reconnect (struct GNUNET_NAMESTORE_ZoneMonitor *zm) +reconnect(struct GNUNET_NAMESTORE_ZoneMonitor *zm) { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_fixed_size (sync, - GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_SYNC, - struct GNUNET_MessageHeader, - zm), - GNUNET_MQ_hd_var_size (result, - GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT, - struct RecordResultMessage, + { GNUNET_MQ_hd_fixed_size(sync, + GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_SYNC, + struct GNUNET_MessageHeader, zm), - GNUNET_MQ_handler_end ()}; + GNUNET_MQ_hd_var_size(result, + GNUNET_MESSAGE_TYPE_NAMESTORE_RECORD_RESULT, + struct RecordResultMessage, + zm), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *env; struct ZoneMonitorStartMessage *sm; if (NULL != zm->mq) - { - GNUNET_MQ_destroy (zm->mq); - zm->error_cb (zm->error_cb_cls); - } - zm->mq = GNUNET_CLIENT_connect (zm->cfg, - "namestore", - handlers, - &mq_error_handler, - zm); + { + GNUNET_MQ_destroy(zm->mq); + zm->error_cb(zm->error_cb_cls); + } + zm->mq = GNUNET_CLIENT_connect(zm->cfg, + "namestore", + handlers, + &mq_error_handler, + zm); if (NULL == zm->mq) return; - env = GNUNET_MQ_msg (sm, GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START); - sm->iterate_first = htonl (zm->iterate_first); + env = GNUNET_MQ_msg(sm, GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_START); + sm->iterate_first = htonl(zm->iterate_first); sm->zone = zm->zone; - GNUNET_MQ_send (zm->mq, env); + GNUNET_MQ_send(zm->mq, env); } @@ -300,7 +299,7 @@ reconnect (struct GNUNET_NAMESTORE_ZoneMonitor *zm) * @return handle to stop monitoring */ struct GNUNET_NAMESTORE_ZoneMonitor * -GNUNET_NAMESTORE_zone_monitor_start ( +GNUNET_NAMESTORE_zone_monitor_start( const struct GNUNET_CONFIGURATION_Handle *cfg, const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, int iterate_first, @@ -313,7 +312,7 @@ GNUNET_NAMESTORE_zone_monitor_start ( { struct GNUNET_NAMESTORE_ZoneMonitor *zm; - zm = GNUNET_new (struct GNUNET_NAMESTORE_ZoneMonitor); + zm = GNUNET_new(struct GNUNET_NAMESTORE_ZoneMonitor); if (NULL != zone) zm->zone = *zone; zm->iterate_first = iterate_first; @@ -324,12 +323,12 @@ GNUNET_NAMESTORE_zone_monitor_start ( zm->sync_cb = sync_cb; zm->sync_cb_cls = sync_cb_cls; zm->cfg = cfg; - reconnect (zm); + reconnect(zm); if (NULL == zm->mq) - { - GNUNET_free (zm); - return NULL; - } + { + GNUNET_free(zm); + return NULL; + } return zm; } @@ -356,15 +355,15 @@ GNUNET_NAMESTORE_zone_monitor_start ( * (before #GNUNET_NAMESTORE_zone_monitor_next is to be called again) */ void -GNUNET_NAMESTORE_zone_monitor_next (struct GNUNET_NAMESTORE_ZoneMonitor *zm, - uint64_t limit) +GNUNET_NAMESTORE_zone_monitor_next(struct GNUNET_NAMESTORE_ZoneMonitor *zm, + uint64_t limit) { struct GNUNET_MQ_Envelope *env; struct ZoneMonitorNextMessage *nm; - env = GNUNET_MQ_msg (nm, GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_NEXT); - nm->limit = GNUNET_htonll (limit); - GNUNET_MQ_send (zm->mq, env); + env = GNUNET_MQ_msg(nm, GNUNET_MESSAGE_TYPE_NAMESTORE_MONITOR_NEXT); + nm->limit = GNUNET_htonll(limit); + GNUNET_MQ_send(zm->mq, env); } @@ -374,14 +373,14 @@ GNUNET_NAMESTORE_zone_monitor_next (struct GNUNET_NAMESTORE_ZoneMonitor *zm, * @param zm handle to the monitor activity to stop */ void -GNUNET_NAMESTORE_zone_monitor_stop (struct GNUNET_NAMESTORE_ZoneMonitor *zm) +GNUNET_NAMESTORE_zone_monitor_stop(struct GNUNET_NAMESTORE_ZoneMonitor *zm) { if (NULL != zm->mq) - { - GNUNET_MQ_destroy (zm->mq); - zm->mq = NULL; - } - GNUNET_free (zm); + { + GNUNET_MQ_destroy(zm->mq); + zm->mq = NULL; + } + GNUNET_free(zm); } /* end of namestore_api_monitor.c */ diff --git a/src/namestore/perf_namestore_api_zone_iteration.c b/src/namestore/perf_namestore_api_zone_iteration.c index 156f9227c..6b79a35f6 100644 --- a/src/namestore/perf_namestore_api_zone_iteration.c +++ b/src/namestore/perf_namestore_api_zone_iteration.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/perf_namestore_api_zone_iteration.c * @brief testcase for zone iteration functionality: iterate all zones @@ -35,7 +35,7 @@ * modern system, so 30 minutes should be OK even for very, very * slow systems. */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 30) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 30) /** * The runtime of the benchmark is expected to be linear @@ -87,39 +87,39 @@ static struct GNUNET_TIME_Absolute start; * @param cls NULL */ static void -end (void *cls) +end(void *cls) { - (void) cls; + (void)cls; if (NULL != qe) - { - GNUNET_NAMESTORE_cancel (qe); - qe = NULL; - } + { + GNUNET_NAMESTORE_cancel(qe); + qe = NULL; + } if (NULL != zi) - { - GNUNET_NAMESTORE_zone_iteration_stop (zi); - zi = NULL; - } + { + GNUNET_NAMESTORE_zone_iteration_stop(zi); + zi = NULL; + } if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } if (NULL != t) - { - GNUNET_SCHEDULER_cancel (t); - t = NULL; - } + { + GNUNET_SCHEDULER_cancel(t); + t = NULL; + } if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } + { + GNUNET_free(privkey); + privkey = NULL; + } } @@ -128,228 +128,228 @@ end (void *cls) * fail hard but return "skipped". */ static void -timeout (void *cls) +timeout(void *cls) { - (void) cls; + (void)cls; timeout_task = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); res = 77; } static struct GNUNET_GNSRECORD_Data * -create_record (unsigned int count) +create_record(unsigned int count) { struct GNUNET_GNSRECORD_Data *rd; - rd = GNUNET_malloc (count + sizeof (struct GNUNET_GNSRECORD_Data)); - rd->expiration_time = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS).abs_value_us; + rd = GNUNET_malloc(count + sizeof(struct GNUNET_GNSRECORD_Data)); + rd->expiration_time = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS).abs_value_us; rd->record_type = TEST_RECORD_TYPE; rd->data_size = count; - rd->data = (void *) &rd[1]; + rd->data = (void *)&rd[1]; rd->flags = 0; - memset (&rd[1], - 'a', - count); + memset(&rd[1], + 'a', + count); return rd; } static void -zone_end (void *cls) +zone_end(void *cls) { struct GNUNET_TIME_Relative delay; zi = NULL; - delay = GNUNET_TIME_absolute_get_duration (start); - fprintf (stdout, - "Iterating over %u records took %s\n", - off, - GNUNET_STRINGS_relative_time_to_string (delay, - GNUNET_YES)); + delay = GNUNET_TIME_absolute_get_duration(start); + fprintf(stdout, + "Iterating over %u records took %s\n", + off, + GNUNET_STRINGS_relative_time_to_string(delay, + GNUNET_YES)); if (BENCHMARK_SIZE == off) - { - res = 0; - } + { + res = 0; + } else - { - GNUNET_break (0); - res = 1; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_break(0); + res = 1; + } + GNUNET_SCHEDULER_shutdown(); } static void -fail_cb (void *cls) +fail_cb(void *cls) { zi = NULL; res = 2; - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); } static void -zone_proc (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +zone_proc(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_GNSRECORD_Data *wrd; unsigned int xoff; - GNUNET_assert (NULL != zone); - if (1 != sscanf (label, - "l%u", - &xoff)) - { - res = 3; - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } - if ( (xoff > BENCHMARK_SIZE) || - (0 != (seen[xoff / 8] & (1U << (xoff % 8)))) ) - { - res = 3; - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_assert(NULL != zone); + if (1 != sscanf(label, + "l%u", + &xoff)) + { + res = 3; + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + if ((xoff > BENCHMARK_SIZE) || + (0 != (seen[xoff / 8] & (1U << (xoff % 8))))) + { + res = 3; + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } seen[xoff / 8] |= (1U << (xoff % 8)); - wrd = create_record (xoff % MAX_REC_SIZE); - if ( (rd->record_type != wrd->record_type) || - (rd->data_size != wrd->data_size) || - (rd->flags != wrd->flags) ) - { - res = 4; - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - GNUNET_free (wrd); - return; - } - if (0 != memcmp (rd->data, - wrd->data, - wrd->data_size)) - { - res = 4; - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - GNUNET_free (wrd); - return; - } - GNUNET_free (wrd); - if (0 != GNUNET_memcmp (zone, - privkey)) - { - res = 5; - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } + wrd = create_record(xoff % MAX_REC_SIZE); + if ((rd->record_type != wrd->record_type) || + (rd->data_size != wrd->data_size) || + (rd->flags != wrd->flags)) + { + res = 4; + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + GNUNET_free(wrd); + return; + } + if (0 != memcmp(rd->data, + wrd->data, + wrd->data_size)) + { + res = 4; + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + GNUNET_free(wrd); + return; + } + GNUNET_free(wrd); + if (0 != GNUNET_memcmp(zone, + privkey)) + { + res = 5; + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } off++; left_until_next--; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Obtained record %u, expecting %u more until asking for mor explicitly\n", - off, - left_until_next); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Obtained record %u, expecting %u more until asking for mor explicitly\n", + off, + left_until_next); if (0 == left_until_next) - { - left_until_next = BLOCK_SIZE; - GNUNET_NAMESTORE_zone_iterator_next (zi, - left_until_next); - } + { + left_until_next = BLOCK_SIZE; + GNUNET_NAMESTORE_zone_iterator_next(zi, + left_until_next); + } } static void -publish_record (void *cls); +publish_record(void *cls); static void -put_cont (void *cls, - int32_t success, - const char *emsg) +put_cont(void *cls, + int32_t success, + const char *emsg) { - (void) cls; + (void)cls; qe = NULL; if (GNUNET_OK != success) - { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } - t = GNUNET_SCHEDULER_add_now (&publish_record, - NULL); + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + t = GNUNET_SCHEDULER_add_now(&publish_record, + NULL); } static void -publish_record (void *cls) +publish_record(void *cls) { struct GNUNET_GNSRECORD_Data *rd; char *label; - (void) cls; + (void)cls; t = NULL; if (BENCHMARK_SIZE == off) - { - struct GNUNET_TIME_Relative delay; + { + struct GNUNET_TIME_Relative delay; - delay = GNUNET_TIME_absolute_get_duration (start); - fprintf (stdout, - "Inserting %u records took %s\n", - off, - GNUNET_STRINGS_relative_time_to_string (delay, + delay = GNUNET_TIME_absolute_get_duration(start); + fprintf(stdout, + "Inserting %u records took %s\n", + off, + GNUNET_STRINGS_relative_time_to_string(delay, GNUNET_YES)); - start = GNUNET_TIME_absolute_get (); - off = 0; - left_until_next = 1; - zi = GNUNET_NAMESTORE_zone_iteration_start (nsh, - NULL, - &fail_cb, - NULL, - &zone_proc, - NULL, - &zone_end, - NULL); - GNUNET_assert (NULL != zi); - return; - } - rd = create_record ((++off) % MAX_REC_SIZE); - GNUNET_asprintf (&label, - "l%u", - off); - qe = GNUNET_NAMESTORE_records_store (nsh, - privkey, - label, - 1, rd, - &put_cont, - NULL); - GNUNET_free (label); - GNUNET_free (rd); + start = GNUNET_TIME_absolute_get(); + off = 0; + left_until_next = 1; + zi = GNUNET_NAMESTORE_zone_iteration_start(nsh, + NULL, + &fail_cb, + NULL, + &zone_proc, + NULL, + &zone_end, + NULL); + GNUNET_assert(NULL != zi); + return; + } + rd = create_record((++off) % MAX_REC_SIZE); + GNUNET_asprintf(&label, + "l%u", + off); + qe = GNUNET_NAMESTORE_records_store(nsh, + privkey, + label, + 1, rd, + &put_cont, + NULL); + GNUNET_free(label); + GNUNET_free(rd); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - GNUNET_SCHEDULER_add_shutdown (&end, - NULL); - timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &timeout, - NULL); - nsh = GNUNET_NAMESTORE_connect (cfg); - GNUNET_assert (NULL != nsh); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (NULL != privkey); - start = GNUNET_TIME_absolute_get (); - t = GNUNET_SCHEDULER_add_now (&publish_record, + GNUNET_SCHEDULER_add_shutdown(&end, NULL); + timeout_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &timeout, + NULL); + nsh = GNUNET_NAMESTORE_connect(cfg); + GNUNET_assert(NULL != nsh); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(NULL != privkey); + start = GNUNET_TIME_absolute_get(); + t = GNUNET_SCHEDULER_add_now(&publish_record, + NULL); } @@ -357,25 +357,25 @@ run (void *cls, int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("perf-namestore-api-zone-iteration", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("perf-namestore-api-zone-iteration", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/plugin_namestore_flat.c b/src/namestore/plugin_namestore_flat.c index 4e1d33907..083609359 100644 --- a/src/namestore/plugin_namestore_flat.c +++ b/src/namestore/plugin_namestore_flat.c @@ -1,22 +1,22 @@ - /* - * This file is part of GNUnet - * Copyright (C) 2009-2015, 2018, 2019 GNUnet e.V. - * - * GNUnet is free software: you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * GNUnet is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - - SPDX-License-Identifier: AGPL3.0-or-later - */ +/* + * This file is part of GNUnet + * Copyright (C) 2009-2015, 2018, 2019 GNUnet e.V. + * + * GNUnet is free software: you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * GNUnet is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + + SPDX-License-Identifier: AGPL3.0-or-later + */ /** * @file namestore/plugin_namestore_flat.c * @brief file-based namestore backend @@ -33,9 +33,7 @@ /** * Context for all functions in this plugin. */ -struct Plugin -{ - +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; /** @@ -47,12 +45,10 @@ struct Plugin * HashMap */ struct GNUNET_CONTAINER_MultiHashMap *hm; - }; -struct FlatFileEntry -{ +struct FlatFileEntry { /** * Entry zone */ @@ -77,7 +73,6 @@ struct FlatFileEntry * Label */ char *label; - }; @@ -89,27 +84,27 @@ struct FlatFileEntry * @param h[out] initialized hash */ static void -hash_pkey_and_label (const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, - const char *label, - struct GNUNET_HashCode *h) +hash_pkey_and_label(const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, + const char *label, + struct GNUNET_HashCode *h) { char *key; size_t label_len; size_t key_len; - label_len = strlen (label); - key_len = label_len + sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey); - key = GNUNET_malloc (key_len); - GNUNET_memcpy (key, - label, - label_len); - GNUNET_memcpy (key + label_len, - pkey, - sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)); - GNUNET_CRYPTO_hash (key, - key_len, - h); - GNUNET_free (key); + label_len = strlen(label); + key_len = label_len + sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey); + key = GNUNET_malloc(key_len); + GNUNET_memcpy(key, + label, + label_len); + GNUNET_memcpy(key + label_len, + pkey, + sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey)); + GNUNET_CRYPTO_hash(key, + key_len, + h); + GNUNET_free(key); } @@ -122,7 +117,7 @@ hash_pkey_and_label (const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, * @return #GNUNET_OK on success */ static int -database_setup (struct Plugin *plugin) +database_setup(struct Plugin *plugin) { char *flatdbfile; char *record_data; @@ -141,188 +136,188 @@ database_setup (struct Plugin *plugin) struct GNUNET_DISK_MapHandle *mh; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, - "namestore-flat", - "FILENAME", - &flatdbfile)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "namestore-flat", - "FILENAME"); - return GNUNET_SYSERR; - } - if (GNUNET_OK != - GNUNET_DISK_file_test (flatdbfile)) - { - if (GNUNET_OK != - GNUNET_DISK_directory_create_for_file (flatdbfile)) + GNUNET_CONFIGURATION_get_value_filename(plugin->cfg, + "namestore-flat", + "FILENAME", + &flatdbfile)) { - GNUNET_break (0); - GNUNET_free (flatdbfile); + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "namestore-flat", + "FILENAME"); return GNUNET_SYSERR; } - } + if (GNUNET_OK != + GNUNET_DISK_file_test(flatdbfile)) + { + if (GNUNET_OK != + GNUNET_DISK_directory_create_for_file(flatdbfile)) + { + GNUNET_break(0); + GNUNET_free(flatdbfile); + return GNUNET_SYSERR; + } + } /* flatdbfile should be UTF-8-encoded. If it isn't, it's a bug */ plugin->fn = flatdbfile; /* Load data from file into hashmap */ - plugin->hm = GNUNET_CONTAINER_multihashmap_create (10, - GNUNET_NO); - fh = GNUNET_DISK_file_open (flatdbfile, - GNUNET_DISK_OPEN_CREATE | - GNUNET_DISK_OPEN_READWRITE, - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_USER_READ); + plugin->hm = GNUNET_CONTAINER_multihashmap_create(10, + GNUNET_NO); + fh = GNUNET_DISK_file_open(flatdbfile, + GNUNET_DISK_OPEN_CREATE | + GNUNET_DISK_OPEN_READWRITE, + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_USER_READ); if (NULL == fh) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to initialize file: %s.\n"), - flatdbfile); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to initialize file: %s.\n"), + flatdbfile); + return GNUNET_SYSERR; + } if (GNUNET_SYSERR == - GNUNET_DISK_file_size (flatdbfile, - &size, - GNUNET_YES, - GNUNET_YES)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to get filesize: %s.\n"), - flatdbfile); - GNUNET_DISK_file_close (fh); - return GNUNET_SYSERR; - } + GNUNET_DISK_file_size(flatdbfile, + &size, + GNUNET_YES, + GNUNET_YES)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to get filesize: %s.\n"), + flatdbfile); + GNUNET_DISK_file_close(fh); + return GNUNET_SYSERR; + } if (size > SIZE_MAX) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("File too big to map: %llu bytes.\n"), - (unsigned long long) size); - GNUNET_DISK_file_close (fh); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("File too big to map: %llu bytes.\n"), + (unsigned long long)size); + GNUNET_DISK_file_close(fh); + return GNUNET_SYSERR; + } if (0 == size) - { - GNUNET_DISK_file_close (fh); - return GNUNET_OK; - } - buffer = GNUNET_DISK_file_map (fh, - &mh, - GNUNET_DISK_MAP_TYPE_READ, - size); + { + GNUNET_DISK_file_close(fh); + return GNUNET_OK; + } + buffer = GNUNET_DISK_file_map(fh, + &mh, + GNUNET_DISK_MAP_TYPE_READ, + size); if (NULL == buffer) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "mmap"); - GNUNET_DISK_file_close (fh); - return GNUNET_SYSERR; - } - if ('\0' != buffer[size-1]) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore database file `%s' malformed\n"), - flatdbfile); - GNUNET_DISK_file_unmap (mh); - GNUNET_DISK_file_close (fh); - return GNUNET_SYSERR; - } + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "mmap"); + GNUNET_DISK_file_close(fh); + return GNUNET_SYSERR; + } + if ('\0' != buffer[size - 1]) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore database file `%s' malformed\n"), + flatdbfile); + GNUNET_DISK_file_unmap(mh); + GNUNET_DISK_file_close(fh); + return GNUNET_SYSERR; + } - line = strtok (buffer, "\n"); + line = strtok(buffer, "\n"); while (NULL != line) - { - zone_private_key = strtok (line, ","); - if (NULL == zone_private_key) - break; - rvalue = strtok (NULL, ","); - if (NULL == rvalue) - break; - record_count = strtok (NULL, ","); - if (NULL == record_count) - break; - record_data_b64 = strtok (NULL, ","); - if (NULL == record_data_b64) - break; - label = strtok (NULL, ","); - if (NULL == label) - break; - line = strtok (NULL, "\n"); - entry = GNUNET_new (struct FlatFileEntry); { - unsigned long long ll; - - if (1 != sscanf (rvalue, - "%llu", - &ll)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error parsing entry\n"); - GNUNET_free (entry); + zone_private_key = strtok(line, ","); + if (NULL == zone_private_key) + break; + rvalue = strtok(NULL, ","); + if (NULL == rvalue) + break; + record_count = strtok(NULL, ","); + if (NULL == record_count) break; + record_data_b64 = strtok(NULL, ","); + if (NULL == record_data_b64) + break; + label = strtok(NULL, ","); + if (NULL == label) + break; + line = strtok(NULL, "\n"); + entry = GNUNET_new(struct FlatFileEntry); + { + unsigned long long ll; + + if (1 != sscanf(rvalue, + "%llu", + &ll)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error parsing entry\n"); + GNUNET_free(entry); + break; + } + entry->rvalue = (uint64_t)ll; } - entry->rvalue = (uint64_t) ll; - } - { - unsigned int ui; + { + unsigned int ui; + + if (1 != sscanf(record_count, + "%u", + &ui)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error parsing entry\n"); + GNUNET_free(entry); + break; + } + entry->record_count = (uint32_t)ui; + } + entry->label = GNUNET_strdup(label); + record_data_size + = GNUNET_STRINGS_base64_decode(record_data_b64, + strlen(record_data_b64), + (void **)&record_data); + entry->record_data = + GNUNET_new_array(entry->record_count, + struct GNUNET_GNSRECORD_Data); + if (GNUNET_OK != + GNUNET_GNSRECORD_records_deserialize(record_data_size, + record_data, + entry->record_count, + entry->record_data)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to deserialize record %s\n", + label); + GNUNET_free(entry->label); + GNUNET_free(entry); + GNUNET_free(record_data); + break; + } + GNUNET_free(record_data); - if (1 != sscanf (record_count, - "%u", - &ui)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error parsing entry\n"); - GNUNET_free (entry); - break; + struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key; + + GNUNET_STRINGS_base64_decode(zone_private_key, + strlen(zone_private_key), + (void**)&private_key); + entry->private_key = *private_key; + GNUNET_free(private_key); } - entry->record_count = (uint32_t) ui; - } - entry->label = GNUNET_strdup (label); - record_data_size - = GNUNET_STRINGS_base64_decode (record_data_b64, - strlen (record_data_b64), - (void **) &record_data); - entry->record_data = - GNUNET_new_array (entry->record_count, - struct GNUNET_GNSRECORD_Data); - if (GNUNET_OK != - GNUNET_GNSRECORD_records_deserialize (record_data_size, - record_data, - entry->record_count, - entry->record_data)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to deserialize record %s\n", - label); - GNUNET_free (entry->label); - GNUNET_free (entry); - GNUNET_free (record_data); - break; - } - GNUNET_free (record_data); - - { - struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key; - - GNUNET_STRINGS_base64_decode (zone_private_key, - strlen (zone_private_key), - (void**)&private_key); - entry->private_key = *private_key; - GNUNET_free (private_key); - } - - hash_pkey_and_label (&entry->private_key, - label, - &hkey); - if (GNUNET_OK != - GNUNET_CONTAINER_multihashmap_put (plugin->hm, - &hkey, - entry, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - GNUNET_free (entry); - GNUNET_break (0); + + hash_pkey_and_label(&entry->private_key, + label, + &hkey); + if (GNUNET_OK != + GNUNET_CONTAINER_multihashmap_put(plugin->hm, + &hkey, + entry, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_free(entry); + GNUNET_break(0); + } } - } - GNUNET_DISK_file_unmap (mh); - GNUNET_DISK_file_close (fh); + GNUNET_DISK_file_unmap(mh); + GNUNET_DISK_file_close(fh); return GNUNET_OK; } @@ -335,9 +330,9 @@ database_setup (struct Plugin *plugin) * @param value a `struct FlatFileEntry` */ static int -store_and_free_entries (void *cls, - const struct GNUNET_HashCode *key, - void *value) +store_and_free_entries(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GNUNET_DISK_FileHandle *fh = cls; struct FlatFileEntry *entry = value; @@ -346,61 +341,61 @@ store_and_free_entries (void *cls, char *record_data_b64; ssize_t data_size; - (void) key; - GNUNET_STRINGS_base64_encode (&entry->private_key, - sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey), - &zone_private_key); - data_size = GNUNET_GNSRECORD_records_get_size (entry->record_count, - entry->record_data); + (void)key; + GNUNET_STRINGS_base64_encode(&entry->private_key, + sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey), + &zone_private_key); + data_size = GNUNET_GNSRECORD_records_get_size(entry->record_count, + entry->record_data); if (data_size < 0) - { - GNUNET_break (0); - GNUNET_free (zone_private_key); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + GNUNET_free(zone_private_key); + return GNUNET_SYSERR; + } if (data_size >= UINT16_MAX) - { - GNUNET_break (0); - GNUNET_free (zone_private_key); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + GNUNET_free(zone_private_key); + return GNUNET_SYSERR; + } { char data[data_size]; ssize_t ret; - ret = GNUNET_GNSRECORD_records_serialize (entry->record_count, - entry->record_data, - data_size, - data); - if ( (ret < 0) || - (data_size != ret) ) - { - GNUNET_break (0); - GNUNET_free (zone_private_key); - return GNUNET_SYSERR; - } - GNUNET_STRINGS_base64_encode (data, - data_size, - &record_data_b64); + ret = GNUNET_GNSRECORD_records_serialize(entry->record_count, + entry->record_data, + data_size, + data); + if ((ret < 0) || + (data_size != ret)) + { + GNUNET_break(0); + GNUNET_free(zone_private_key); + return GNUNET_SYSERR; + } + GNUNET_STRINGS_base64_encode(data, + data_size, + &record_data_b64); } - GNUNET_asprintf (&line, - "%s,%llu,%u,%s,%s\n", - zone_private_key, - (unsigned long long) entry->rvalue, - (unsigned int) entry->record_count, - record_data_b64, - entry->label); - GNUNET_free (record_data_b64); - GNUNET_free (zone_private_key); - - GNUNET_DISK_file_write (fh, - line, - strlen (line)); - - GNUNET_free (line); - GNUNET_free (entry->label); - GNUNET_free (entry->record_data); - GNUNET_free (entry); + GNUNET_asprintf(&line, + "%s,%llu,%u,%s,%s\n", + zone_private_key, + (unsigned long long)entry->rvalue, + (unsigned int)entry->record_count, + record_data_b64, + entry->label); + GNUNET_free(record_data_b64); + GNUNET_free(zone_private_key); + + GNUNET_DISK_file_write(fh, + line, + strlen(line)); + + GNUNET_free(line); + GNUNET_free(entry->label); + GNUNET_free(entry->record_data); + GNUNET_free(entry); return GNUNET_YES; } @@ -411,33 +406,33 @@ store_and_free_entries (void *cls, * @param plugin the plugin context (state for this module) */ static void -database_shutdown (struct Plugin *plugin) +database_shutdown(struct Plugin *plugin) { struct GNUNET_DISK_FileHandle *fh; - fh = GNUNET_DISK_file_open (plugin->fn, - GNUNET_DISK_OPEN_CREATE | - GNUNET_DISK_OPEN_TRUNCATE | - GNUNET_DISK_OPEN_READWRITE, - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_USER_READ); + fh = GNUNET_DISK_file_open(plugin->fn, + GNUNET_DISK_OPEN_CREATE | + GNUNET_DISK_OPEN_TRUNCATE | + GNUNET_DISK_OPEN_READWRITE, + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_USER_READ); if (NULL == fh) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to initialize file: %s.\n"), - plugin->fn); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to initialize file: %s.\n"), + plugin->fn); + return; + } - GNUNET_CONTAINER_multihashmap_iterate (plugin->hm, - &store_and_free_entries, - fh); - GNUNET_CONTAINER_multihashmap_destroy (plugin->hm); + GNUNET_CONTAINER_multihashmap_iterate(plugin->hm, + &store_and_free_entries, + fh); + GNUNET_CONTAINER_multihashmap_destroy(plugin->hm); /* append 0-terminator */ - GNUNET_DISK_file_write (fh, - "", - 1); - GNUNET_DISK_file_close (fh); + GNUNET_DISK_file_write(fh, + "", + 1); + GNUNET_DISK_file_close(fh); } @@ -453,57 +448,57 @@ database_shutdown (struct Plugin *plugin) * @return #GNUNET_OK on success, else #GNUNET_SYSERR */ static int -namestore_flat_store_records (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +namestore_flat_store_records(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct Plugin *plugin = cls; uint64_t rvalue; struct GNUNET_HashCode hkey; struct FlatFileEntry *entry; - rvalue = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, - UINT64_MAX); - hash_pkey_and_label (zone_key, - label, - &hkey); - GNUNET_CONTAINER_multihashmap_remove_all (plugin->hm, - &hkey); + rvalue = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, + UINT64_MAX); + hash_pkey_and_label(zone_key, + label, + &hkey); + GNUNET_CONTAINER_multihashmap_remove_all(plugin->hm, + &hkey); if (0 == rd_count) - { - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "sqlite", - "Record deleted\n"); - return GNUNET_OK; - } - entry = GNUNET_new (struct FlatFileEntry); - GNUNET_asprintf (&entry->label, - label, - strlen (label)); - GNUNET_memcpy (&entry->private_key, - zone_key, - sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)); + { + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "sqlite", + "Record deleted\n"); + return GNUNET_OK; + } + entry = GNUNET_new(struct FlatFileEntry); + GNUNET_asprintf(&entry->label, + label, + strlen(label)); + GNUNET_memcpy(&entry->private_key, + zone_key, + sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey)); entry->rvalue = rvalue; entry->record_count = rd_count; - entry->record_data = GNUNET_new_array (rd_count, - struct GNUNET_GNSRECORD_Data); + entry->record_data = GNUNET_new_array(rd_count, + struct GNUNET_GNSRECORD_Data); for (unsigned int i = 0; i < rd_count; i++) - { - entry->record_data[i].expiration_time = rd[i].expiration_time; - entry->record_data[i].record_type = rd[i].record_type; - entry->record_data[i].flags = rd[i].flags; - entry->record_data[i].data_size = rd[i].data_size; - entry->record_data[i].data = GNUNET_malloc (rd[i].data_size); - GNUNET_memcpy ((char*)entry->record_data[i].data, - rd[i].data, - rd[i].data_size); - } - return GNUNET_CONTAINER_multihashmap_put (plugin->hm, - &hkey, - entry, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY); + { + entry->record_data[i].expiration_time = rd[i].expiration_time; + entry->record_data[i].record_type = rd[i].record_type; + entry->record_data[i].flags = rd[i].flags; + entry->record_data[i].data_size = rd[i].data_size; + entry->record_data[i].data = GNUNET_malloc(rd[i].data_size); + GNUNET_memcpy((char*)entry->record_data[i].data, + rd[i].data, + rd[i].data_size); + } + return GNUNET_CONTAINER_multihashmap_put(plugin->hm, + &hkey, + entry, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY); } @@ -518,36 +513,36 @@ namestore_flat_store_records (void *cls, * @return #GNUNET_OK on success, #GNUNET_NO for no results, else #GNUNET_SYSERR */ static int -namestore_flat_lookup_records (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - GNUNET_NAMESTORE_RecordIterator iter, - void *iter_cls) +namestore_flat_lookup_records(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + GNUNET_NAMESTORE_RecordIterator iter, + void *iter_cls) { struct Plugin *plugin = cls; struct FlatFileEntry *entry; struct GNUNET_HashCode hkey; if (NULL == zone) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - hash_pkey_and_label (zone, - label, - &hkey); - entry = GNUNET_CONTAINER_multihashmap_get (plugin->hm, - &hkey); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + hash_pkey_and_label(zone, + label, + &hkey); + entry = GNUNET_CONTAINER_multihashmap_get(plugin->hm, + &hkey); if (NULL == entry) return GNUNET_NO; if (NULL != iter) - iter (iter_cls, - 1, /* zero is illegal */ - &entry->private_key, - entry->label, - entry->record_count, - entry->record_data); + iter(iter_cls, + 1, /* zero is illegal */ + &entry->private_key, + entry->label, + entry->record_count, + entry->record_data); return GNUNET_YES; } @@ -555,8 +550,7 @@ namestore_flat_lookup_records (void *cls, /** * Closure for #iterate_zones. */ -struct IterateContext -{ +struct IterateContext { /** * How many more records should we skip before returning results? */ @@ -587,7 +581,6 @@ struct IterateContext * Closure for @e iter. */ void *iter_cls; - }; @@ -600,34 +593,34 @@ struct IterateContext * @return #GNUNET_YES to continue the iteration */ static int -iterate_zones (void *cls, - const struct GNUNET_HashCode *key, - void *value) +iterate_zones(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct IterateContext *ic = cls; struct FlatFileEntry *entry = value; - (void) key; + (void)key; if (0 == ic->limit) return GNUNET_NO; - if ( (NULL != ic->zone) && - (0 != GNUNET_memcmp (&entry->private_key, - ic->zone)) ) + if ((NULL != ic->zone) && + (0 != GNUNET_memcmp(&entry->private_key, + ic->zone))) return GNUNET_YES; ic->pos++; if (ic->offset > 0) - { - ic->offset--; - return GNUNET_YES; - } - ic->iter (ic->iter_cls, - ic->pos, - (NULL == ic->zone) - ? &entry->private_key - : ic->zone, - entry->label, - entry->record_count, - entry->record_data); + { + ic->offset--; + return GNUNET_YES; + } + ic->iter(ic->iter_cls, + ic->pos, + (NULL == ic->zone) + ? &entry->private_key + : ic->zone, + entry->label, + entry->record_count, + entry->record_data); ic->limit--; if (0 == ic->limit) return GNUNET_NO; @@ -648,12 +641,12 @@ iterate_zones (void *cls, * @return #GNUNET_OK on success, #GNUNET_NO if there were no more results, #GNUNET_SYSERR on error */ static int -namestore_flat_iterate_records (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - uint64_t serial, - uint64_t limit, - GNUNET_NAMESTORE_RecordIterator iter, - void *iter_cls) +namestore_flat_iterate_records(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + uint64_t serial, + uint64_t limit, + GNUNET_NAMESTORE_RecordIterator iter, + void *iter_cls) { struct Plugin *plugin = cls; struct IterateContext ic; @@ -664,9 +657,9 @@ namestore_flat_iterate_records (void *cls, ic.iter = iter; ic.iter_cls = iter_cls; ic.zone = zone; - GNUNET_CONTAINER_multihashmap_iterate (plugin->hm, - &iterate_zones, - &ic); + GNUNET_CONTAINER_multihashmap_iterate(plugin->hm, + &iterate_zones, + &ic); return (0 == ic.limit) ? GNUNET_OK : GNUNET_NO; } @@ -674,8 +667,7 @@ namestore_flat_iterate_records (void *cls, /** * Closure for #zone_to_name. */ -struct ZoneToNameContext -{ +struct ZoneToNameContext { const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone; const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone; GNUNET_NAMESTORE_RecordIterator iter; @@ -686,35 +678,35 @@ struct ZoneToNameContext static int -zone_to_name (void *cls, - const struct GNUNET_HashCode *key, - void *value) +zone_to_name(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct ZoneToNameContext *ztn = cls; struct FlatFileEntry *entry = value; - (void) key; - if (0 != GNUNET_memcmp (&entry->private_key, - ztn->zone)) + (void)key; + if (0 != GNUNET_memcmp(&entry->private_key, + ztn->zone)) return GNUNET_YES; for (unsigned int i = 0; i < entry->record_count; i++) - { - if (GNUNET_GNSRECORD_TYPE_PKEY != entry->record_data[i].record_type) - continue; - if (0 == memcmp (ztn->value_zone, - entry->record_data[i].data, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey))) { - ztn->iter (ztn->iter_cls, - i + 1, /* zero is illegal! */ - &entry->private_key, - entry->label, - entry->record_count, - entry->record_data); - ztn->result_found = GNUNET_YES; + if (GNUNET_GNSRECORD_TYPE_PKEY != entry->record_data[i].record_type) + continue; + if (0 == memcmp(ztn->value_zone, + entry->record_data[i].data, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey))) + { + ztn->iter(ztn->iter_cls, + i + 1, /* zero is illegal! */ + &entry->private_key, + entry->label, + entry->record_count, + entry->record_data); + ztn->result_found = GNUNET_YES; + } } - } return GNUNET_YES; } @@ -731,11 +723,11 @@ zone_to_name (void *cls, * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error */ static int -namestore_flat_zone_to_name (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone, - GNUNET_NAMESTORE_RecordIterator iter, - void *iter_cls) +namestore_flat_zone_to_name(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone, + GNUNET_NAMESTORE_RecordIterator iter, + void *iter_cls) { struct Plugin *plugin = cls; struct ZoneToNameContext ztn = { @@ -746,12 +738,12 @@ namestore_flat_zone_to_name (void *cls, .result_found = GNUNET_NO }; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Performing reverse lookup for `%s'\n", - GNUNET_GNSRECORD_z2s (value_zone)); - GNUNET_CONTAINER_multihashmap_iterate (plugin->hm, - &zone_to_name, - &ztn); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Performing reverse lookup for `%s'\n", + GNUNET_GNSRECORD_z2s(value_zone)); + GNUNET_CONTAINER_multihashmap_iterate(plugin->hm, + &zone_to_name, + &ztn); return ztn.result_found; } @@ -763,7 +755,7 @@ namestore_flat_zone_to_name (void *cls, * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_namestore_flat_init (void *cls) +libgnunet_plugin_namestore_flat_init(void *cls) { static struct Plugin plugin; const struct GNUNET_CONFIGURATION_Handle *cfg = cls; @@ -771,23 +763,23 @@ libgnunet_plugin_namestore_flat_init (void *cls) if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, - 0, - sizeof (struct Plugin)); + memset(&plugin, + 0, + sizeof(struct Plugin)); plugin.cfg = cfg; - if (GNUNET_OK != database_setup (&plugin)) - { - database_shutdown (&plugin); - return NULL; - } - api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions); + if (GNUNET_OK != database_setup(&plugin)) + { + database_shutdown(&plugin); + return NULL; + } + api = GNUNET_new(struct GNUNET_NAMESTORE_PluginFunctions); api->cls = &plugin; api->store_records = &namestore_flat_store_records; api->iterate_records = &namestore_flat_iterate_records; api->zone_to_name = &namestore_flat_zone_to_name; api->lookup_records = &namestore_flat_lookup_records; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Flat file database running\n")); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Flat file database running\n")); return api; } @@ -799,16 +791,16 @@ libgnunet_plugin_namestore_flat_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_namestore_flat_done (void *cls) +libgnunet_plugin_namestore_flat_done(void *cls) { struct GNUNET_NAMESTORE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - database_shutdown (plugin); + database_shutdown(plugin); plugin->cfg = NULL; - GNUNET_free (api); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Flat file plugin is finished\n"); + GNUNET_free(api); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Flat file plugin is finished\n"); return NULL; } diff --git a/src/namestore/plugin_namestore_postgres.c b/src/namestore/plugin_namestore_postgres.c index f2e065882..ac35b01b4 100644 --- a/src/namestore/plugin_namestore_postgres.c +++ b/src/namestore/plugin_namestore_postgres.c @@ -1,22 +1,22 @@ - /* - * This file is part of GNUnet - * Copyright (C) 2009-2013, 2016-2018 GNUnet e.V. - * - * GNUnet is free software: you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published - * by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * GNUnet is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - - SPDX-License-Identifier: AGPL3.0-or-later - */ +/* + * This file is part of GNUnet + * Copyright (C) 2009-2013, 2016-2018 GNUnet e.V. + * + * GNUnet is free software: you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * GNUnet is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + + SPDX-License-Identifier: AGPL3.0-or-later + */ /** * @file namestore/plugin_namestore_postgres.c @@ -31,15 +31,13 @@ #include "namestore.h" -#define LOG(kind,...) GNUNET_log_from (kind, "namestore-postgres", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "namestore-postgres", __VA_ARGS__) /** * Context for all functions in this plugin. */ -struct Plugin -{ - +struct Plugin { /** * Our configuration. */ @@ -49,7 +47,6 @@ struct Plugin * Native Postgres database handle. */ PGconn *dbh; - }; @@ -62,136 +59,136 @@ struct Plugin * @return #GNUNET_OK on success */ static int -database_setup (struct Plugin *plugin) +database_setup(struct Plugin *plugin) { struct GNUNET_PQ_ExecuteStatement es_temporary = - GNUNET_PQ_make_execute ("CREATE TEMPORARY TABLE IF NOT EXISTS ns098records (" - " seq BIGSERIAL PRIMARY KEY," - " zone_private_key BYTEA NOT NULL DEFAULT ''," - " pkey BYTEA DEFAULT ''," - " rvalue BYTEA NOT NULL DEFAULT ''," - " record_count INTEGER NOT NULL DEFAULT 0," - " record_data BYTEA NOT NULL DEFAULT ''," - " label TEXT NOT NULL DEFAULT ''," - " CONSTRAINT zl UNIQUE (zone_private_key,label)" - ")" - "WITH OIDS"); + GNUNET_PQ_make_execute("CREATE TEMPORARY TABLE IF NOT EXISTS ns098records (" + " seq BIGSERIAL PRIMARY KEY," + " zone_private_key BYTEA NOT NULL DEFAULT ''," + " pkey BYTEA DEFAULT ''," + " rvalue BYTEA NOT NULL DEFAULT ''," + " record_count INTEGER NOT NULL DEFAULT 0," + " record_data BYTEA NOT NULL DEFAULT ''," + " label TEXT NOT NULL DEFAULT ''," + " CONSTRAINT zl UNIQUE (zone_private_key,label)" + ")" + "WITH OIDS"); struct GNUNET_PQ_ExecuteStatement es_default = - GNUNET_PQ_make_execute ("CREATE TABLE IF NOT EXISTS ns098records (" - " seq BIGSERIAL PRIMARY KEY," - " zone_private_key BYTEA NOT NULL DEFAULT ''," - " pkey BYTEA DEFAULT ''," - " rvalue BYTEA NOT NULL DEFAULT ''," - " record_count INTEGER NOT NULL DEFAULT 0," - " record_data BYTEA NOT NULL DEFAULT ''," - " label TEXT NOT NULL DEFAULT ''," - " CONSTRAINT zl UNIQUE (zone_private_key,label)" - ")" - "WITH OIDS"); + GNUNET_PQ_make_execute("CREATE TABLE IF NOT EXISTS ns098records (" + " seq BIGSERIAL PRIMARY KEY," + " zone_private_key BYTEA NOT NULL DEFAULT ''," + " pkey BYTEA DEFAULT ''," + " rvalue BYTEA NOT NULL DEFAULT ''," + " record_count INTEGER NOT NULL DEFAULT 0," + " record_data BYTEA NOT NULL DEFAULT ''," + " label TEXT NOT NULL DEFAULT ''," + " CONSTRAINT zl UNIQUE (zone_private_key,label)" + ")" + "WITH OIDS"); const struct GNUNET_PQ_ExecuteStatement *cr; - plugin->dbh = GNUNET_PQ_connect_with_cfg (plugin->cfg, - "namestore-postgres"); + plugin->dbh = GNUNET_PQ_connect_with_cfg(plugin->cfg, + "namestore-postgres"); if (NULL == plugin->dbh) return GNUNET_SYSERR; if (GNUNET_YES == - GNUNET_CONFIGURATION_get_value_yesno (plugin->cfg, - "namestore-postgres", - "ASYNC_COMMIT")) - { - struct GNUNET_PQ_ExecuteStatement es[] = { - GNUNET_PQ_make_try_execute ("SET synchronous_commit TO off"), - GNUNET_PQ_EXECUTE_STATEMENT_END - }; - - if (GNUNET_OK != - GNUNET_PQ_exec_statements (plugin->dbh, - es)) + GNUNET_CONFIGURATION_get_value_yesno(plugin->cfg, + "namestore-postgres", + "ASYNC_COMMIT")) { - PQfinish (plugin->dbh); - plugin->dbh = NULL; - return GNUNET_SYSERR; + struct GNUNET_PQ_ExecuteStatement es[] = { + GNUNET_PQ_make_try_execute("SET synchronous_commit TO off"), + GNUNET_PQ_EXECUTE_STATEMENT_END + }; + + if (GNUNET_OK != + GNUNET_PQ_exec_statements(plugin->dbh, + es)) + { + PQfinish(plugin->dbh); + plugin->dbh = NULL; + return GNUNET_SYSERR; + } } - } if (GNUNET_YES == - GNUNET_CONFIGURATION_get_value_yesno (plugin->cfg, - "namestore-postgres", - "TEMPORARY_TABLE")) - { - cr = &es_temporary; - } + GNUNET_CONFIGURATION_get_value_yesno(plugin->cfg, + "namestore-postgres", + "TEMPORARY_TABLE")) + { + cr = &es_temporary; + } else - { - cr = &es_default; - } + { + cr = &es_default; + } { struct GNUNET_PQ_ExecuteStatement es[] = { *cr, - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_reverse " - "ON ns098records (zone_private_key,pkey)"), - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_iter " - "ON ns098records (zone_private_key,seq)"), - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_label " - "ON ns098records (label)"), - GNUNET_PQ_make_try_execute ("CREATE INDEX IF NOT EXISTS zone_label " - "ON ns098records (zone_private_key,label)"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS ir_pkey_reverse " + "ON ns098records (zone_private_key,pkey)"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS ir_pkey_iter " + "ON ns098records (zone_private_key,seq)"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS ir_label " + "ON ns098records (label)"), + GNUNET_PQ_make_try_execute("CREATE INDEX IF NOT EXISTS zone_label " + "ON ns098records (zone_private_key,label)"), GNUNET_PQ_EXECUTE_STATEMENT_END }; if (GNUNET_OK != - GNUNET_PQ_exec_statements (plugin->dbh, - es)) - { - PQfinish (plugin->dbh); - plugin->dbh = NULL; - return GNUNET_SYSERR; - } + GNUNET_PQ_exec_statements(plugin->dbh, + es)) + { + PQfinish(plugin->dbh); + plugin->dbh = NULL; + return GNUNET_SYSERR; + } } { struct GNUNET_PQ_PreparedStatement ps[] = { - GNUNET_PQ_make_prepare ("store_records", - "INSERT INTO ns098records" - " (zone_private_key, pkey, rvalue, record_count, record_data, label)" - " VALUES ($1, $2, $3, $4, $5, $6)" - " ON CONFLICT ON CONSTRAINT zl" - " DO UPDATE" - " SET pkey=$2,rvalue=$3,record_count=$4,record_data=$5" - " WHERE ns098records.zone_private_key = $1" - " AND ns098records.label = $6", - 6), - GNUNET_PQ_make_prepare ("delete_records", - "DELETE FROM ns098records " - "WHERE zone_private_key=$1 AND label=$2", - 2), - GNUNET_PQ_make_prepare ("zone_to_name", - "SELECT seq,record_count,record_data,label FROM ns098records" - " WHERE zone_private_key=$1 AND pkey=$2", - 2), - GNUNET_PQ_make_prepare ("iterate_zone", - "SELECT seq,record_count,record_data,label FROM ns098records " - "WHERE zone_private_key=$1 AND seq > $2 ORDER BY seq ASC LIMIT $3", - 3), - GNUNET_PQ_make_prepare ("iterate_all_zones", - "SELECT seq,record_count,record_data,label,zone_private_key" - " FROM ns098records WHERE seq > $1 ORDER BY seq ASC LIMIT $2", - 2), - GNUNET_PQ_make_prepare ("lookup_label", - "SELECT seq,record_count,record_data,label " - "FROM ns098records WHERE zone_private_key=$1 AND label=$2", - 2), + GNUNET_PQ_make_prepare("store_records", + "INSERT INTO ns098records" + " (zone_private_key, pkey, rvalue, record_count, record_data, label)" + " VALUES ($1, $2, $3, $4, $5, $6)" + " ON CONFLICT ON CONSTRAINT zl" + " DO UPDATE" + " SET pkey=$2,rvalue=$3,record_count=$4,record_data=$5" + " WHERE ns098records.zone_private_key = $1" + " AND ns098records.label = $6", + 6), + GNUNET_PQ_make_prepare("delete_records", + "DELETE FROM ns098records " + "WHERE zone_private_key=$1 AND label=$2", + 2), + GNUNET_PQ_make_prepare("zone_to_name", + "SELECT seq,record_count,record_data,label FROM ns098records" + " WHERE zone_private_key=$1 AND pkey=$2", + 2), + GNUNET_PQ_make_prepare("iterate_zone", + "SELECT seq,record_count,record_data,label FROM ns098records " + "WHERE zone_private_key=$1 AND seq > $2 ORDER BY seq ASC LIMIT $3", + 3), + GNUNET_PQ_make_prepare("iterate_all_zones", + "SELECT seq,record_count,record_data,label,zone_private_key" + " FROM ns098records WHERE seq > $1 ORDER BY seq ASC LIMIT $2", + 2), + GNUNET_PQ_make_prepare("lookup_label", + "SELECT seq,record_count,record_data,label " + "FROM ns098records WHERE zone_private_key=$1 AND label=$2", + 2), GNUNET_PQ_PREPARED_STATEMENT_END }; if (GNUNET_OK != - GNUNET_PQ_prepare_statements (plugin->dbh, - ps)) - { - PQfinish (plugin->dbh); - plugin->dbh = NULL; - return GNUNET_SYSERR; - } + GNUNET_PQ_prepare_statements(plugin->dbh, + ps)) + { + PQfinish(plugin->dbh); + plugin->dbh = NULL; + return GNUNET_SYSERR; + } } return GNUNET_OK; @@ -210,97 +207,97 @@ database_setup (struct Plugin *plugin) * @return #GNUNET_OK on success, else #GNUNET_SYSERR */ static int -namestore_postgres_store_records (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +namestore_postgres_store_records(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct Plugin *plugin = cls; struct GNUNET_CRYPTO_EcdsaPublicKey pkey; uint64_t rvalue; - uint32_t rd_count32 = (uint32_t) rd_count; + uint32_t rd_count32 = (uint32_t)rd_count; ssize_t data_size; - memset (&pkey, - 0, - sizeof (pkey)); - for (unsigned int i=0;i= UINT16_MAX) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } /* if record set is empty, delete existing records */ if (0 == rd_count) - { - struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_auto_from_type (zone_key), - GNUNET_PQ_query_param_string (label), - GNUNET_PQ_query_param_end - }; - enum GNUNET_DB_QueryStatus res; - - res = GNUNET_PQ_eval_prepared_non_select (plugin->dbh, - "delete_records", - params); - if ( (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != res) && - (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS != res) ) { - GNUNET_break (0); - return GNUNET_SYSERR; + struct GNUNET_PQ_QueryParam params[] = { + GNUNET_PQ_query_param_auto_from_type(zone_key), + GNUNET_PQ_query_param_string(label), + GNUNET_PQ_query_param_end + }; + enum GNUNET_DB_QueryStatus res; + + res = GNUNET_PQ_eval_prepared_non_select(plugin->dbh, + "delete_records", + params); + if ((GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != res) && + (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS != res)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "postgres", + "Record deleted\n"); + return GNUNET_OK; } - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "postgres", - "Record deleted\n"); - return GNUNET_OK; - } /* otherwise, UPSERT (i.e. UPDATE if exists, otherwise INSERT) */ { char data[data_size]; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_auto_from_type (zone_key), - GNUNET_PQ_query_param_auto_from_type (&pkey), - GNUNET_PQ_query_param_uint64 (&rvalue), - GNUNET_PQ_query_param_uint32 (&rd_count32), - GNUNET_PQ_query_param_fixed_size (data, data_size), - GNUNET_PQ_query_param_string (label), + GNUNET_PQ_query_param_auto_from_type(zone_key), + GNUNET_PQ_query_param_auto_from_type(&pkey), + GNUNET_PQ_query_param_uint64(&rvalue), + GNUNET_PQ_query_param_uint32(&rd_count32), + GNUNET_PQ_query_param_fixed_size(data, data_size), + GNUNET_PQ_query_param_string(label), GNUNET_PQ_query_param_end }; enum GNUNET_DB_QueryStatus res; ssize_t ret; - ret = GNUNET_GNSRECORD_records_serialize (rd_count, - rd, - data_size, - data); - if ( (ret < 0) || - (data_size != ret) ) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + ret = GNUNET_GNSRECORD_records_serialize(rd_count, + rd, + data_size, + data); + if ((ret < 0) || + (data_size != ret)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } - res = GNUNET_PQ_eval_prepared_non_select (plugin->dbh, - "store_records", - params); + res = GNUNET_PQ_eval_prepared_non_select(plugin->dbh, + "store_records", + params); if (GNUNET_DB_STATUS_SUCCESS_ONE_RESULT != res) return GNUNET_SYSERR; } @@ -311,8 +308,7 @@ namestore_postgres_store_records (void *cls, /** * Closure for #parse_result_call_iterator. */ -struct ParserContext -{ +struct ParserContext { /** * Function to call for each result. */ @@ -345,81 +341,81 @@ struct ParserContext * @param num_result the number of results in @a result */ static void -parse_result_call_iterator (void *cls, - PGresult *res, - unsigned int num_results) +parse_result_call_iterator(void *cls, + PGresult *res, + unsigned int num_results) { struct ParserContext *pc = cls; if (NULL == pc->iter) return; /* no need to do more work */ - for (unsigned int i=0;izone_key) ? rs_with_zone : rs_without_zone; - if (GNUNET_YES != - GNUNET_PQ_extract_result (res, - rs, - i)) - { - GNUNET_break (0); - return; - } - - if (record_count > 64 * 1024) - { - /* sanity check, don't stack allocate far too much just - because database might contain a large value here */ - GNUNET_break (0); - GNUNET_PQ_cleanup_result (rs); - return; - } - + for (unsigned int i = 0; i < num_results; i++) { - struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL(record_count)]; + uint64_t serial; + void *data; + size_t data_size; + uint32_t record_count; + char *label; + struct GNUNET_CRYPTO_EcdsaPrivateKey zk; + struct GNUNET_PQ_ResultSpec rs_with_zone[] = { + GNUNET_PQ_result_spec_uint64("seq", &serial), + GNUNET_PQ_result_spec_uint32("record_count", &record_count), + GNUNET_PQ_result_spec_variable_size("record_data", &data, &data_size), + GNUNET_PQ_result_spec_string("label", &label), + GNUNET_PQ_result_spec_auto_from_type("zone_private_key", &zk), + GNUNET_PQ_result_spec_end + }; + struct GNUNET_PQ_ResultSpec rs_without_zone[] = { + GNUNET_PQ_result_spec_uint64("seq", &serial), + GNUNET_PQ_result_spec_uint32("record_count", &record_count), + GNUNET_PQ_result_spec_variable_size("record_data", &data, &data_size), + GNUNET_PQ_result_spec_string("label", &label), + GNUNET_PQ_result_spec_end + }; + struct GNUNET_PQ_ResultSpec *rs; + + rs = (NULL == pc->zone_key) ? rs_with_zone : rs_without_zone; + if (GNUNET_YES != + GNUNET_PQ_extract_result(res, + rs, + i)) + { + GNUNET_break(0); + return; + } + + if (record_count > 64 * 1024) + { + /* sanity check, don't stack allocate far too much just + because database might contain a large value here */ + GNUNET_break(0); + GNUNET_PQ_cleanup_result(rs); + return; + } - GNUNET_assert (0 != serial); - if (GNUNET_OK != - GNUNET_GNSRECORD_records_deserialize (data_size, - data, - record_count, - rd)) { - GNUNET_break (0); - GNUNET_PQ_cleanup_result (rs); - return; + struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL(record_count)]; + + GNUNET_assert(0 != serial); + if (GNUNET_OK != + GNUNET_GNSRECORD_records_deserialize(data_size, + data, + record_count, + rd)) + { + GNUNET_break(0); + GNUNET_PQ_cleanup_result(rs); + return; + } + pc->iter(pc->iter_cls, + serial, + (NULL == pc->zone_key) ? &zk : pc->zone_key, + label, + record_count, + rd); } - pc->iter (pc->iter_cls, - serial, - (NULL == pc->zone_key) ? &zk : pc->zone_key, - label, - record_count, - rd); + GNUNET_PQ_cleanup_result(rs); } - GNUNET_PQ_cleanup_result (rs); - } pc->limit -= num_results; } @@ -435,34 +431,34 @@ parse_result_call_iterator (void *cls, * @return #GNUNET_OK on success, #GNUNET_NO for no results, else #GNUNET_SYSERR */ static int -namestore_postgres_lookup_records (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - GNUNET_NAMESTORE_RecordIterator iter, - void *iter_cls) +namestore_postgres_lookup_records(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + GNUNET_NAMESTORE_RecordIterator iter, + void *iter_cls) { struct Plugin *plugin = cls; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_auto_from_type (zone), - GNUNET_PQ_query_param_string (label), + GNUNET_PQ_query_param_auto_from_type(zone), + GNUNET_PQ_query_param_string(label), GNUNET_PQ_query_param_end }; struct ParserContext pc; enum GNUNET_DB_QueryStatus res; if (NULL == zone) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } pc.iter = iter; pc.iter_cls = iter_cls; pc.zone_key = zone; - res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh, - "lookup_label", - params, - &parse_result_call_iterator, - &pc); + res = GNUNET_PQ_eval_prepared_multi_select(plugin->dbh, + "lookup_label", + params, + &parse_result_call_iterator, + &pc); if (res < 0) return GNUNET_SYSERR; if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == res) @@ -484,12 +480,12 @@ namestore_postgres_lookup_records (void *cls, * @return #GNUNET_OK on success, #GNUNET_NO if there were no more results, #GNUNET_SYSERR on error */ static int -namestore_postgres_iterate_records (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - uint64_t serial, - uint64_t limit, - GNUNET_NAMESTORE_RecordIterator iter, - void *iter_cls) +namestore_postgres_iterate_records(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + uint64_t serial, + uint64_t limit, + GNUNET_NAMESTORE_RecordIterator iter, + void *iter_cls) { struct Plugin *plugin = cls; enum GNUNET_DB_QueryStatus res; @@ -500,39 +496,39 @@ namestore_postgres_iterate_records (void *cls, pc.zone_key = zone; pc.limit = limit; if (NULL == zone) - { - struct GNUNET_PQ_QueryParam params_without_zone[] = { - GNUNET_PQ_query_param_uint64 (&serial), - GNUNET_PQ_query_param_uint64 (&limit), - GNUNET_PQ_query_param_end - }; - - res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh, - "iterate_all_zones", - params_without_zone, - &parse_result_call_iterator, - &pc); - } + { + struct GNUNET_PQ_QueryParam params_without_zone[] = { + GNUNET_PQ_query_param_uint64(&serial), + GNUNET_PQ_query_param_uint64(&limit), + GNUNET_PQ_query_param_end + }; + + res = GNUNET_PQ_eval_prepared_multi_select(plugin->dbh, + "iterate_all_zones", + params_without_zone, + &parse_result_call_iterator, + &pc); + } else - { - struct GNUNET_PQ_QueryParam params_with_zone[] = { - GNUNET_PQ_query_param_auto_from_type (zone), - GNUNET_PQ_query_param_uint64 (&serial), - GNUNET_PQ_query_param_uint64 (&limit), - GNUNET_PQ_query_param_end - }; - - res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh, - "iterate_zone", - params_with_zone, - &parse_result_call_iterator, - &pc); - } + { + struct GNUNET_PQ_QueryParam params_with_zone[] = { + GNUNET_PQ_query_param_auto_from_type(zone), + GNUNET_PQ_query_param_uint64(&serial), + GNUNET_PQ_query_param_uint64(&limit), + GNUNET_PQ_query_param_end + }; + + res = GNUNET_PQ_eval_prepared_multi_select(plugin->dbh, + "iterate_zone", + params_with_zone, + &parse_result_call_iterator, + &pc); + } if (res < 0) return GNUNET_SYSERR; - if ( (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == res) || - (pc.limit > 0) ) + if ((GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == res) || + (pc.limit > 0)) return GNUNET_NO; return GNUNET_OK; } @@ -550,15 +546,15 @@ namestore_postgres_iterate_records (void *cls, * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error */ static int -namestore_postgres_zone_to_name (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone, - GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls) +namestore_postgres_zone_to_name(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone, + GNUNET_NAMESTORE_RecordIterator iter, void *iter_cls) { struct Plugin *plugin = cls; struct GNUNET_PQ_QueryParam params[] = { - GNUNET_PQ_query_param_auto_from_type (zone), - GNUNET_PQ_query_param_auto_from_type (value_zone), + GNUNET_PQ_query_param_auto_from_type(zone), + GNUNET_PQ_query_param_auto_from_type(value_zone), GNUNET_PQ_query_param_end }; enum GNUNET_DB_QueryStatus res; @@ -567,11 +563,11 @@ namestore_postgres_zone_to_name (void *cls, pc.iter = iter; pc.iter_cls = iter_cls; pc.zone_key = zone; - res = GNUNET_PQ_eval_prepared_multi_select (plugin->dbh, - "zone_to_name", - params, - &parse_result_call_iterator, - &pc); + res = GNUNET_PQ_eval_prepared_multi_select(plugin->dbh, + "zone_to_name", + params, + &parse_result_call_iterator, + &pc); if (res < 0) return GNUNET_SYSERR; return GNUNET_OK; @@ -585,9 +581,9 @@ namestore_postgres_zone_to_name (void *cls, * @param plugin the plugin context (state for this module) */ static void -database_shutdown (struct Plugin *plugin) +database_shutdown(struct Plugin *plugin) { - PQfinish (plugin->dbh); + PQfinish(plugin->dbh); plugin->dbh = NULL; } @@ -599,7 +595,7 @@ database_shutdown (struct Plugin *plugin) * @return NULL on error, othrewise the plugin context */ void * -libgnunet_plugin_namestore_postgres_init (void *cls) +libgnunet_plugin_namestore_postgres_init(void *cls) { static struct Plugin plugin; const struct GNUNET_CONFIGURATION_Handle *cfg = cls; @@ -607,21 +603,21 @@ libgnunet_plugin_namestore_postgres_init (void *cls) if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.cfg = cfg; - if (GNUNET_OK != database_setup (&plugin)) - { - database_shutdown (&plugin); - return NULL; - } - api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions); + if (GNUNET_OK != database_setup(&plugin)) + { + database_shutdown(&plugin); + return NULL; + } + api = GNUNET_new(struct GNUNET_NAMESTORE_PluginFunctions); api->cls = &plugin; api->store_records = &namestore_postgres_store_records; api->iterate_records = &namestore_postgres_iterate_records; api->zone_to_name = &namestore_postgres_zone_to_name; api->lookup_records = &namestore_postgres_lookup_records; - LOG (GNUNET_ERROR_TYPE_INFO, - "Postgres namestore plugin running\n"); + LOG(GNUNET_ERROR_TYPE_INFO, + "Postgres namestore plugin running\n"); return api; } @@ -633,16 +629,16 @@ libgnunet_plugin_namestore_postgres_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_namestore_postgres_done (void *cls) +libgnunet_plugin_namestore_postgres_done(void *cls) { struct GNUNET_NAMESTORE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - database_shutdown (plugin); + database_shutdown(plugin); plugin->cfg = NULL; - GNUNET_free (api); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Postgres namestore plugin is finished\n"); + GNUNET_free(api); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Postgres namestore plugin is finished\n"); return NULL; } diff --git a/src/namestore/plugin_namestore_sqlite.c b/src/namestore/plugin_namestore_sqlite.c index e4bfcde16..ba031217d 100644 --- a/src/namestore/plugin_namestore_sqlite.c +++ b/src/namestore/plugin_namestore_sqlite.c @@ -50,17 +50,15 @@ * a failure of the command 'cmd' on file 'filename' * with the message given by strerror(errno). */ -#define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from (level, "namestore-sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0) +#define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from(level, "namestore-sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while (0) -#define LOG(kind,...) GNUNET_log_from (kind, "namestore-sqlite", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "namestore-sqlite", __VA_ARGS__) /** * Context for all functions in this plugin. */ -struct Plugin -{ - +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; /** @@ -114,123 +112,123 @@ struct Plugin * @return #GNUNET_OK on success */ static int -database_setup (struct Plugin *plugin) +database_setup(struct Plugin *plugin) { char *sqlite_filename; struct GNUNET_SQ_ExecuteStatement es[] = { - GNUNET_SQ_make_try_execute ("PRAGMA temp_store=MEMORY"), - GNUNET_SQ_make_try_execute ("PRAGMA synchronous=NORMAL"), - GNUNET_SQ_make_try_execute ("PRAGMA legacy_file_format=OFF"), - GNUNET_SQ_make_try_execute ("PRAGMA auto_vacuum=INCREMENTAL"), - GNUNET_SQ_make_try_execute ("PRAGMA encoding=\"UTF-8\""), - GNUNET_SQ_make_try_execute ("PRAGMA locking_mode=EXCLUSIVE"), - GNUNET_SQ_make_try_execute ("PRAGMA journal_mode=WAL"), - GNUNET_SQ_make_try_execute ("PRAGMA page_size=4092"), - GNUNET_SQ_make_execute ("CREATE TABLE IF NOT EXISTS ns098records (" - " uid INTEGER PRIMARY KEY," - " zone_private_key BLOB NOT NULL," - " pkey BLOB," - " rvalue INT8 NOT NULL," - " record_count INT NOT NULL," - " record_data BLOB NOT NULL," - " label TEXT NOT NULL" - ")"), - GNUNET_SQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_reverse " - "ON ns098records (zone_private_key,pkey)"), - GNUNET_SQ_make_try_execute ("CREATE INDEX IF NOT EXISTS ir_pkey_iter " - "ON ns098records (zone_private_key,uid)"), + GNUNET_SQ_make_try_execute("PRAGMA temp_store=MEMORY"), + GNUNET_SQ_make_try_execute("PRAGMA synchronous=NORMAL"), + GNUNET_SQ_make_try_execute("PRAGMA legacy_file_format=OFF"), + GNUNET_SQ_make_try_execute("PRAGMA auto_vacuum=INCREMENTAL"), + GNUNET_SQ_make_try_execute("PRAGMA encoding=\"UTF-8\""), + GNUNET_SQ_make_try_execute("PRAGMA locking_mode=EXCLUSIVE"), + GNUNET_SQ_make_try_execute("PRAGMA journal_mode=WAL"), + GNUNET_SQ_make_try_execute("PRAGMA page_size=4092"), + GNUNET_SQ_make_execute("CREATE TABLE IF NOT EXISTS ns098records (" + " uid INTEGER PRIMARY KEY," + " zone_private_key BLOB NOT NULL," + " pkey BLOB," + " rvalue INT8 NOT NULL," + " record_count INT NOT NULL," + " record_data BLOB NOT NULL," + " label TEXT NOT NULL" + ")"), + GNUNET_SQ_make_try_execute("CREATE INDEX IF NOT EXISTS ir_pkey_reverse " + "ON ns098records (zone_private_key,pkey)"), + GNUNET_SQ_make_try_execute("CREATE INDEX IF NOT EXISTS ir_pkey_iter " + "ON ns098records (zone_private_key,uid)"), GNUNET_SQ_EXECUTE_STATEMENT_END }; struct GNUNET_SQ_PrepareStatement ps[] = { - GNUNET_SQ_make_prepare ("INSERT INTO ns098records " - "(zone_private_key,pkey,rvalue,record_count,record_data,label)" - " VALUES (?, ?, ?, ?, ?, ?)", - &plugin->store_records), - GNUNET_SQ_make_prepare ("DELETE FROM ns098records " - "WHERE zone_private_key=? AND label=?", - &plugin->delete_records), - GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label" - " FROM ns098records" - " WHERE zone_private_key=? AND pkey=?", - &plugin->zone_to_name), - GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label" - " FROM ns098records" - " WHERE zone_private_key=? AND uid > ?" - " ORDER BY uid ASC" - " LIMIT ?", - &plugin->iterate_zone), - GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label,zone_private_key" - " FROM ns098records" - " WHERE uid > ?" - " ORDER BY uid ASC" - " LIMIT ?", - &plugin->iterate_all_zones), - GNUNET_SQ_make_prepare ("SELECT uid,record_count,record_data,label" - " FROM ns098records" - " WHERE zone_private_key=? AND label=?", - &plugin->lookup_label), + GNUNET_SQ_make_prepare("INSERT INTO ns098records " + "(zone_private_key,pkey,rvalue,record_count,record_data,label)" + " VALUES (?, ?, ?, ?, ?, ?)", + &plugin->store_records), + GNUNET_SQ_make_prepare("DELETE FROM ns098records " + "WHERE zone_private_key=? AND label=?", + &plugin->delete_records), + GNUNET_SQ_make_prepare("SELECT uid,record_count,record_data,label" + " FROM ns098records" + " WHERE zone_private_key=? AND pkey=?", + &plugin->zone_to_name), + GNUNET_SQ_make_prepare("SELECT uid,record_count,record_data,label" + " FROM ns098records" + " WHERE zone_private_key=? AND uid > ?" + " ORDER BY uid ASC" + " LIMIT ?", + &plugin->iterate_zone), + GNUNET_SQ_make_prepare("SELECT uid,record_count,record_data,label,zone_private_key" + " FROM ns098records" + " WHERE uid > ?" + " ORDER BY uid ASC" + " LIMIT ?", + &plugin->iterate_all_zones), + GNUNET_SQ_make_prepare("SELECT uid,record_count,record_data,label" + " FROM ns098records" + " WHERE zone_private_key=? AND label=?", + &plugin->lookup_label), GNUNET_SQ_PREPARE_END }; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, - "namestore-sqlite", - "FILENAME", - &sqlite_filename)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "namestore-sqlite", - "FILENAME"); - return GNUNET_SYSERR; - } - if (GNUNET_OK != - GNUNET_DISK_file_test (sqlite_filename)) - { - if (GNUNET_OK != - GNUNET_DISK_directory_create_for_file (sqlite_filename)) + GNUNET_CONFIGURATION_get_value_filename(plugin->cfg, + "namestore-sqlite", + "FILENAME", + &sqlite_filename)) { - GNUNET_break (0); - GNUNET_free (sqlite_filename); + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "namestore-sqlite", + "FILENAME"); return GNUNET_SYSERR; } - } + if (GNUNET_OK != + GNUNET_DISK_file_test(sqlite_filename)) + { + if (GNUNET_OK != + GNUNET_DISK_directory_create_for_file(sqlite_filename)) + { + GNUNET_break(0); + GNUNET_free(sqlite_filename); + return GNUNET_SYSERR; + } + } /* sqlite_filename should be UTF-8-encoded. If it isn't, it's a bug */ plugin->fn = sqlite_filename; /* Open database and precompile statements */ if (SQLITE_OK != - sqlite3_open (plugin->fn, - &plugin->dbh)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Unable to initialize SQLite: %s.\n"), - sqlite3_errmsg (plugin->dbh)); - return GNUNET_SYSERR; - } - GNUNET_break (SQLITE_OK == - sqlite3_busy_timeout (plugin->dbh, - BUSY_TIMEOUT_MS)); + sqlite3_open(plugin->fn, + &plugin->dbh)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Unable to initialize SQLite: %s.\n"), + sqlite3_errmsg(plugin->dbh)); + return GNUNET_SYSERR; + } + GNUNET_break(SQLITE_OK == + sqlite3_busy_timeout(plugin->dbh, + BUSY_TIMEOUT_MS)); if (GNUNET_OK != - GNUNET_SQ_exec_statements (plugin->dbh, - es)) - { - GNUNET_break (0); - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Failed to setup database at `%s'\n"), - plugin->fn); - return GNUNET_SYSERR; - } + GNUNET_SQ_exec_statements(plugin->dbh, + es)) + { + GNUNET_break(0); + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Failed to setup database at `%s'\n"), + plugin->fn); + return GNUNET_SYSERR; + } if (GNUNET_OK != - GNUNET_SQ_prepare (plugin->dbh, - ps)) - { - GNUNET_break (0); - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Failed to setup database at `%s'\n"), - plugin->fn); - return GNUNET_SYSERR; - } + GNUNET_SQ_prepare(plugin->dbh, + ps)) + { + GNUNET_break(0); + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Failed to setup database at `%s'\n"), + plugin->fn); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -241,54 +239,54 @@ database_setup (struct Plugin *plugin) * @param plugin the plugin context (state for this module) */ static void -database_shutdown (struct Plugin *plugin) +database_shutdown(struct Plugin *plugin) { int result; sqlite3_stmt *stmt; if (NULL != plugin->store_records) - sqlite3_finalize (plugin->store_records); + sqlite3_finalize(plugin->store_records); if (NULL != plugin->delete_records) - sqlite3_finalize (plugin->delete_records); + sqlite3_finalize(plugin->delete_records); if (NULL != plugin->iterate_zone) - sqlite3_finalize (plugin->iterate_zone); + sqlite3_finalize(plugin->iterate_zone); if (NULL != plugin->iterate_all_zones) - sqlite3_finalize (plugin->iterate_all_zones); + sqlite3_finalize(plugin->iterate_all_zones); if (NULL != plugin->zone_to_name) - sqlite3_finalize (plugin->zone_to_name); + sqlite3_finalize(plugin->zone_to_name); if (NULL != plugin->lookup_label) - sqlite3_finalize (plugin->lookup_label); - result = sqlite3_close (plugin->dbh); + sqlite3_finalize(plugin->lookup_label); + result = sqlite3_close(plugin->dbh); if (result == SQLITE_BUSY) - { - LOG (GNUNET_ERROR_TYPE_WARNING, - _("Tried to close sqlite without finalizing all prepared statements.\n")); - stmt = sqlite3_next_stmt (plugin->dbh, - NULL); - while (NULL != stmt) { - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "sqlite", - "Closing statement %p\n", - stmt); - result = sqlite3_finalize (stmt); - if (result != SQLITE_OK) - GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, - "sqlite", - "Failed to close statement %p: %d\n", - stmt, - result); - stmt = sqlite3_next_stmt (plugin->dbh, - NULL); + LOG(GNUNET_ERROR_TYPE_WARNING, + _("Tried to close sqlite without finalizing all prepared statements.\n")); + stmt = sqlite3_next_stmt(plugin->dbh, + NULL); + while (NULL != stmt) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "sqlite", + "Closing statement %p\n", + stmt); + result = sqlite3_finalize(stmt); + if (result != SQLITE_OK) + GNUNET_log_from(GNUNET_ERROR_TYPE_WARNING, + "sqlite", + "Failed to close statement %p: %d\n", + stmt, + result); + stmt = sqlite3_next_stmt(plugin->dbh, + NULL); + } + result = sqlite3_close(plugin->dbh); } - result = sqlite3_close (plugin->dbh); - } if (SQLITE_OK != result) - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR, - "sqlite3_close"); + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR, + "sqlite3_close"); - GNUNET_free_non_null (plugin->fn); + GNUNET_free_non_null(plugin->fn); } @@ -304,11 +302,11 @@ database_shutdown (struct Plugin *plugin) * @return #GNUNET_OK on success, else #GNUNET_SYSERR */ static int -namestore_sqlite_store_records (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +namestore_sqlite_store_records(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct Plugin *plugin = cls; int n; @@ -316,121 +314,122 @@ namestore_sqlite_store_records (void *cls, uint64_t rvalue; ssize_t data_size; - memset (&pkey, - 0, - sizeof (pkey)); - for (unsigned int i=0;i 64 * 65536) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } { /* First delete 'old' records */ char data[data_size]; struct GNUNET_SQ_QueryParam dparams[] = { - GNUNET_SQ_query_param_auto_from_type (zone_key), - GNUNET_SQ_query_param_string (label), + GNUNET_SQ_query_param_auto_from_type(zone_key), + GNUNET_SQ_query_param_string(label), GNUNET_SQ_query_param_end }; ssize_t ret; - ret = GNUNET_GNSRECORD_records_serialize (rd_count, - rd, - data_size, - data); - if ( (ret < 0) || - (data_size != ret) ) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + ret = GNUNET_GNSRECORD_records_serialize(rd_count, + rd, + data_size, + data); + if ((ret < 0) || + (data_size != ret)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } if (GNUNET_OK != - GNUNET_SQ_bind (plugin->delete_records, - dparams)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_XXXX"); - GNUNET_SQ_reset (plugin->dbh, - plugin->delete_records); - return GNUNET_SYSERR; - - } - n = sqlite3_step (plugin->delete_records); - GNUNET_SQ_reset (plugin->dbh, - plugin->delete_records); + GNUNET_SQ_bind(plugin->delete_records, + dparams)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_XXXX"); + GNUNET_SQ_reset(plugin->dbh, + plugin->delete_records); + return GNUNET_SYSERR; + } + n = sqlite3_step(plugin->delete_records); + GNUNET_SQ_reset(plugin->dbh, + plugin->delete_records); if (0 != rd_count) - { - uint32_t rd_count32 = (uint32_t) rd_count; - struct GNUNET_SQ_QueryParam sparams[] = { - GNUNET_SQ_query_param_auto_from_type (zone_key), - GNUNET_SQ_query_param_auto_from_type (&pkey), - GNUNET_SQ_query_param_uint64 (&rvalue), - GNUNET_SQ_query_param_uint32 (&rd_count32), - GNUNET_SQ_query_param_fixed_size (data, data_size), - GNUNET_SQ_query_param_string (label), - GNUNET_SQ_query_param_end - }; - - if (GNUNET_OK != - GNUNET_SQ_bind (plugin->store_records, - sparams)) { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_XXXX"); - GNUNET_SQ_reset (plugin->dbh, - plugin->store_records); - return GNUNET_SYSERR; + uint32_t rd_count32 = (uint32_t)rd_count; + struct GNUNET_SQ_QueryParam sparams[] = { + GNUNET_SQ_query_param_auto_from_type(zone_key), + GNUNET_SQ_query_param_auto_from_type(&pkey), + GNUNET_SQ_query_param_uint64(&rvalue), + GNUNET_SQ_query_param_uint32(&rd_count32), + GNUNET_SQ_query_param_fixed_size(data, data_size), + GNUNET_SQ_query_param_string(label), + GNUNET_SQ_query_param_end + }; + + if (GNUNET_OK != + GNUNET_SQ_bind(plugin->store_records, + sparams)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_XXXX"); + GNUNET_SQ_reset(plugin->dbh, + plugin->store_records); + return GNUNET_SYSERR; + } + n = sqlite3_step(plugin->store_records); + GNUNET_SQ_reset(plugin->dbh, + plugin->store_records); } - n = sqlite3_step (plugin->store_records); - GNUNET_SQ_reset (plugin->dbh, - plugin->store_records); - } } switch (n) - { + { case SQLITE_DONE: if (0 != rd_count) - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "sqlite", - "Record stored\n"); + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "sqlite", + "Record stored\n"); else - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "sqlite", - "Record deleted\n"); + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "sqlite", + "Record deleted\n"); return GNUNET_OK; + case SQLITE_BUSY: - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); return GNUNET_NO; + default: - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); return GNUNET_SYSERR; - } + } } @@ -448,108 +447,108 @@ namestore_sqlite_store_records (void *cls, * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error */ static int -get_records_and_call_iterator (struct Plugin *plugin, - sqlite3_stmt *stmt, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - uint64_t limit, - GNUNET_NAMESTORE_RecordIterator iter, - void *iter_cls) +get_records_and_call_iterator(struct Plugin *plugin, + sqlite3_stmt *stmt, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + uint64_t limit, + GNUNET_NAMESTORE_RecordIterator iter, + void *iter_cls) { int ret; int sret; ret = GNUNET_OK; - for (uint64_t i = 0;i 64 * 1024) ) - { - /* sanity check, don't stack allocate far too much just - because database might contain a large value here */ - GNUNET_break (0); - ret = GNUNET_SYSERR; - break; - } - else - { - struct GNUNET_GNSRECORD_Data rd[record_count]; + sret = sqlite3_step(stmt); - GNUNET_assert (0 != seq); - if (GNUNET_OK != - GNUNET_GNSRECORD_records_deserialize (data_size, - data, - record_count, - rd)) + if (SQLITE_DONE == sret) { - GNUNET_break (0); - ret = GNUNET_SYSERR; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Iteration done (no results)\n"); + ret = GNUNET_NO; break; } - else + if (SQLITE_ROW != sret) { - if (NULL != zone_key) - zk = *zone_key; - if (NULL != iter) - iter (iter_cls, - seq, - &zk, - label, - record_count, - rd); + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR, + "sqlite_step"); + ret = GNUNET_SYSERR; + break; } + + { + uint64_t seq; + uint32_t record_count; + size_t data_size; + void *data; + char *label; + struct GNUNET_CRYPTO_EcdsaPrivateKey zk; + struct GNUNET_SQ_ResultSpec rs[] = { + GNUNET_SQ_result_spec_uint64(&seq), + GNUNET_SQ_result_spec_uint32(&record_count), + GNUNET_SQ_result_spec_variable_size(&data, + &data_size), + GNUNET_SQ_result_spec_string(&label), + GNUNET_SQ_result_spec_end + }; + struct GNUNET_SQ_ResultSpec rsx[] = { + GNUNET_SQ_result_spec_uint64(&seq), + GNUNET_SQ_result_spec_uint32(&record_count), + GNUNET_SQ_result_spec_variable_size(&data, + &data_size), + GNUNET_SQ_result_spec_string(&label), + GNUNET_SQ_result_spec_auto_from_type(&zk), + GNUNET_SQ_result_spec_end + }; + + ret = GNUNET_SQ_extract_result(stmt, + (NULL == zone_key) + ? rsx + : rs); + if ((GNUNET_OK != ret) || + (record_count > 64 * 1024)) + { + /* sanity check, don't stack allocate far too much just + because database might contain a large value here */ + GNUNET_break(0); + ret = GNUNET_SYSERR; + break; + } + else + { + struct GNUNET_GNSRECORD_Data rd[record_count]; + + GNUNET_assert(0 != seq); + if (GNUNET_OK != + GNUNET_GNSRECORD_records_deserialize(data_size, + data, + record_count, + rd)) + { + GNUNET_break(0); + ret = GNUNET_SYSERR; + break; + } + else + { + if (NULL != zone_key) + zk = *zone_key; + if (NULL != iter) + iter(iter_cls, + seq, + &zk, + label, + record_count, + rd); + } + } + GNUNET_SQ_cleanup_result(rs); } - GNUNET_SQ_cleanup_result (rs); } - } - GNUNET_SQ_reset (plugin->dbh, - stmt); + GNUNET_SQ_reset(plugin->dbh, + stmt); return ret; } @@ -565,40 +564,40 @@ get_records_and_call_iterator (struct Plugin *plugin, * @return #GNUNET_OK on success, #GNUNET_NO for no results, else #GNUNET_SYSERR */ static int -namestore_sqlite_lookup_records (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - GNUNET_NAMESTORE_RecordIterator iter, - void *iter_cls) +namestore_sqlite_lookup_records(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + GNUNET_NAMESTORE_RecordIterator iter, + void *iter_cls) { struct Plugin *plugin = cls; struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_auto_from_type (zone), - GNUNET_SQ_query_param_string (label), + GNUNET_SQ_query_param_auto_from_type(zone), + GNUNET_SQ_query_param_string(label), GNUNET_SQ_query_param_end }; if (NULL == zone) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } if (GNUNET_OK != - GNUNET_SQ_bind (plugin->lookup_label, - params)) - { - LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_XXXX"); - GNUNET_SQ_reset (plugin->dbh, - plugin->lookup_label); - return GNUNET_SYSERR; - } - return get_records_and_call_iterator (plugin, - plugin->lookup_label, - zone, - 1, - iter, - iter_cls); + GNUNET_SQ_bind(plugin->lookup_label, + params)) + { + LOG_SQLITE(plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_XXXX"); + GNUNET_SQ_reset(plugin->dbh, + plugin->lookup_label); + return GNUNET_SYSERR; + } + return get_records_and_call_iterator(plugin, + plugin->lookup_label, + zone, + 1, + iter, + iter_cls); } @@ -615,57 +614,57 @@ namestore_sqlite_lookup_records (void *cls, * @return #GNUNET_OK on success, #GNUNET_NO if there were no more results, #GNUNET_SYSERR on error */ static int -namestore_sqlite_iterate_records (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - uint64_t serial, - uint64_t limit, - GNUNET_NAMESTORE_RecordIterator iter, - void *iter_cls) +namestore_sqlite_iterate_records(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + uint64_t serial, + uint64_t limit, + GNUNET_NAMESTORE_RecordIterator iter, + void *iter_cls) { struct Plugin *plugin = cls; sqlite3_stmt *stmt; int err; if (NULL == zone) - { - struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_uint64 (&serial), - GNUNET_SQ_query_param_uint64 (&limit), - GNUNET_SQ_query_param_end - }; + { + struct GNUNET_SQ_QueryParam params[] = { + GNUNET_SQ_query_param_uint64(&serial), + GNUNET_SQ_query_param_uint64(&limit), + GNUNET_SQ_query_param_end + }; - stmt = plugin->iterate_all_zones; - err = GNUNET_SQ_bind (stmt, - params); - } + stmt = plugin->iterate_all_zones; + err = GNUNET_SQ_bind(stmt, + params); + } else - { - struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_auto_from_type (zone), - GNUNET_SQ_query_param_uint64 (&serial), - GNUNET_SQ_query_param_uint64 (&limit), - GNUNET_SQ_query_param_end - }; + { + struct GNUNET_SQ_QueryParam params[] = { + GNUNET_SQ_query_param_auto_from_type(zone), + GNUNET_SQ_query_param_uint64(&serial), + GNUNET_SQ_query_param_uint64(&limit), + GNUNET_SQ_query_param_end + }; - stmt = plugin->iterate_zone; - err = GNUNET_SQ_bind (stmt, - params); - } + stmt = plugin->iterate_zone; + err = GNUNET_SQ_bind(stmt, + params); + } if (GNUNET_OK != err) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_XXXX"); - GNUNET_SQ_reset (plugin->dbh, - stmt); - return GNUNET_SYSERR; - } - return get_records_and_call_iterator (plugin, - stmt, - zone, - limit, - iter, - iter_cls); + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_XXXX"); + GNUNET_SQ_reset(plugin->dbh, + stmt); + return GNUNET_SYSERR; + } + return get_records_and_call_iterator(plugin, + stmt, + zone, + limit, + iter, + iter_cls); } @@ -681,39 +680,39 @@ namestore_sqlite_iterate_records (void *cls, * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error */ static int -namestore_sqlite_zone_to_name (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone, - GNUNET_NAMESTORE_RecordIterator iter, - void *iter_cls) +namestore_sqlite_zone_to_name(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const struct GNUNET_CRYPTO_EcdsaPublicKey *value_zone, + GNUNET_NAMESTORE_RecordIterator iter, + void *iter_cls) { struct Plugin *plugin = cls; struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_auto_from_type (zone), - GNUNET_SQ_query_param_auto_from_type (value_zone), + GNUNET_SQ_query_param_auto_from_type(zone), + GNUNET_SQ_query_param_auto_from_type(value_zone), GNUNET_SQ_query_param_end }; if (GNUNET_OK != - GNUNET_SQ_bind (plugin->zone_to_name, - params)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_XXXX"); - GNUNET_SQ_reset (plugin->dbh, - plugin->zone_to_name); - return GNUNET_SYSERR; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Performing reverse lookup for `%s'\n", - GNUNET_GNSRECORD_z2s (value_zone)); - return get_records_and_call_iterator (plugin, - plugin->zone_to_name, - zone, - 1, - iter, - iter_cls); + GNUNET_SQ_bind(plugin->zone_to_name, + params)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_XXXX"); + GNUNET_SQ_reset(plugin->dbh, + plugin->zone_to_name); + return GNUNET_SYSERR; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Performing reverse lookup for `%s'\n", + GNUNET_GNSRECORD_z2s(value_zone)); + return get_records_and_call_iterator(plugin, + plugin->zone_to_name, + zone, + 1, + iter, + iter_cls); } @@ -724,7 +723,7 @@ namestore_sqlite_zone_to_name (void *cls, * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_namestore_sqlite_init (void *cls) +libgnunet_plugin_namestore_sqlite_init(void *cls) { static struct Plugin plugin; const struct GNUNET_CONFIGURATION_Handle *cfg = cls; @@ -732,23 +731,23 @@ libgnunet_plugin_namestore_sqlite_init (void *cls) if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, - 0, - sizeof (struct Plugin)); + memset(&plugin, + 0, + sizeof(struct Plugin)); plugin.cfg = cfg; - if (GNUNET_OK != database_setup (&plugin)) - { - database_shutdown (&plugin); - return NULL; - } - api = GNUNET_new (struct GNUNET_NAMESTORE_PluginFunctions); + if (GNUNET_OK != database_setup(&plugin)) + { + database_shutdown(&plugin); + return NULL; + } + api = GNUNET_new(struct GNUNET_NAMESTORE_PluginFunctions); api->cls = &plugin; api->store_records = &namestore_sqlite_store_records; api->iterate_records = &namestore_sqlite_iterate_records; api->zone_to_name = &namestore_sqlite_zone_to_name; api->lookup_records = &namestore_sqlite_lookup_records; - LOG (GNUNET_ERROR_TYPE_INFO, - _("Sqlite database running\n")); + LOG(GNUNET_ERROR_TYPE_INFO, + _("Sqlite database running\n")); return api; } @@ -760,16 +759,16 @@ libgnunet_plugin_namestore_sqlite_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_namestore_sqlite_done (void *cls) +libgnunet_plugin_namestore_sqlite_done(void *cls) { struct GNUNET_NAMESTORE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - database_shutdown (plugin); + database_shutdown(plugin); plugin->cfg = NULL; - GNUNET_free (api); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "sqlite plugin is finished\n"); + GNUNET_free(api); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "sqlite plugin is finished\n"); return NULL; } diff --git a/src/namestore/plugin_rest_namestore.c b/src/namestore/plugin_rest_namestore.c index 1d8c180fb..42fbf8347 100644 --- a/src/namestore/plugin_rest_namestore.c +++ b/src/namestore/plugin_rest_namestore.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach * @author Philippe Buschmann @@ -87,16 +87,14 @@ static char *allow_methods; /** * @brief struct returned by the initialization function of the plugin */ -struct Plugin -{ +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; }; /** * The default namestore ego */ -struct EgoEntry -{ +struct EgoEntry { /** * DLL */ @@ -126,8 +124,7 @@ struct EgoEntry /** * The request handle */ -struct RequestHandle -{ +struct RequestHandle { /** * Records to store */ @@ -244,61 +241,61 @@ struct RequestHandle * @param handle Handle to clean up */ static void -cleanup_handle (void *cls) +cleanup_handle(void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; struct EgoEntry *ego_tmp; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); if (NULL != handle->timeout_task) - { - GNUNET_SCHEDULER_cancel (handle->timeout_task); - handle->timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(handle->timeout_task); + handle->timeout_task = NULL; + } if (NULL != handle->record_name) - GNUNET_free (handle->record_name); + GNUNET_free(handle->record_name); if (NULL != handle->url) - GNUNET_free (handle->url); + GNUNET_free(handle->url); if (NULL != handle->emsg) - GNUNET_free (handle->emsg); + GNUNET_free(handle->emsg); if (NULL != handle->rd) - { - for (int i = 0; i < handle->rd_count; i++) { - if (NULL != handle->rd[i].data) - GNUNET_free ((void *) handle->rd[i].data); + for (int i = 0; i < handle->rd_count; i++) + { + if (NULL != handle->rd[i].data) + GNUNET_free((void *)handle->rd[i].data); + } + GNUNET_free(handle->rd); } - GNUNET_free (handle->rd); - } if (NULL != handle->timeout_task) - GNUNET_SCHEDULER_cancel (handle->timeout_task); + GNUNET_SCHEDULER_cancel(handle->timeout_task); if (NULL != handle->list_it) - GNUNET_NAMESTORE_zone_iteration_stop (handle->list_it); + GNUNET_NAMESTORE_zone_iteration_stop(handle->list_it); if (NULL != handle->add_qe) - GNUNET_NAMESTORE_cancel (handle->add_qe); + GNUNET_NAMESTORE_cancel(handle->add_qe); if (NULL != handle->identity_handle) - GNUNET_IDENTITY_disconnect (handle->identity_handle); + GNUNET_IDENTITY_disconnect(handle->identity_handle); if (NULL != handle->ns_handle) - { - GNUNET_NAMESTORE_disconnect (handle->ns_handle); - } + { + GNUNET_NAMESTORE_disconnect(handle->ns_handle); + } for (ego_entry = handle->ego_head; NULL != ego_entry;) - { - ego_tmp = ego_entry; - ego_entry = ego_entry->next; - GNUNET_free (ego_tmp->identifier); - GNUNET_free (ego_tmp->keystring); - GNUNET_free (ego_tmp); - } + { + ego_tmp = ego_entry; + ego_entry = ego_entry->next; + GNUNET_free(ego_tmp->identifier); + GNUNET_free(ego_tmp->keystring); + GNUNET_free(ego_tmp); + } if (NULL != handle->resp_object) - { - json_decref (handle->resp_object); - } + { + json_decref(handle->resp_object); + } - GNUNET_free (handle); + GNUNET_free(handle); } @@ -308,26 +305,26 @@ cleanup_handle (void *cls) * @param cls the `struct RequestHandle` */ static void -do_error (void *cls) +do_error(void *cls) { struct RequestHandle *handle = cls; struct MHD_Response *resp; - json_t *json_error = json_object (); + json_t *json_error = json_object(); char *response; if (NULL == handle->emsg) - handle->emsg = GNUNET_strdup (GNUNET_REST_NAMESTORE_ERROR_UNKNOWN); + handle->emsg = GNUNET_strdup(GNUNET_REST_NAMESTORE_ERROR_UNKNOWN); - json_object_set_new (json_error, "error", json_string (handle->emsg)); + json_object_set_new(json_error, "error", json_string(handle->emsg)); if (0 == handle->response_code) handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; - response = json_dumps (json_error, 0); - resp = GNUNET_REST_create_response (response); - handle->proc (handle->proc_cls, resp, handle->response_code); - json_decref (json_error); - GNUNET_free (response); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + response = json_dumps(json_error, 0); + resp = GNUNET_REST_create_response(response); + handle->proc(handle->proc_cls, resp, handle->response_code); + json_decref(json_error); + GNUNET_free(response); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } @@ -341,19 +338,20 @@ do_error (void *cls) * @return EgoEntry or NULL if not found */ struct EgoEntry * -get_egoentry_namestore (struct RequestHandle *handle, char *name) +get_egoentry_namestore(struct RequestHandle *handle, char *name) { struct EgoEntry *ego_entry; + if (NULL != name) - { - for (ego_entry = handle->ego_head; NULL != ego_entry; - ego_entry = ego_entry->next) { - if (0 != strcasecmp (name, ego_entry->identifier)) - continue; - return ego_entry; + for (ego_entry = handle->ego_head; NULL != ego_entry; + ego_entry = ego_entry->next) + { + if (0 != strcasecmp(name, ego_entry->identifier)) + continue; + return ego_entry; + } } - } return NULL; } @@ -364,11 +362,12 @@ get_egoentry_namestore (struct RequestHandle *handle, char *name) * @param cls the `struct RequestHandle` */ static void -namestore_iteration_error (void *cls) +namestore_iteration_error(void *cls) { struct RequestHandle *handle = cls; - handle->emsg = GNUNET_strdup (GNUNET_REST_NAMESTORE_FAILED); - GNUNET_SCHEDULER_add_now (&do_error, handle); + + handle->emsg = GNUNET_strdup(GNUNET_REST_NAMESTORE_FAILED); + GNUNET_SCHEDULER_add_now(&do_error, handle); return; } @@ -381,27 +380,27 @@ namestore_iteration_error (void *cls) * @param emsg the error message (can be NULL) */ static void -create_finished (void *cls, int32_t success, const char *emsg) +create_finished(void *cls, int32_t success, const char *emsg) { struct RequestHandle *handle = cls; struct MHD_Response *resp; handle->add_qe = NULL; if (GNUNET_YES != success) - { - if (NULL != emsg) { - handle->emsg = GNUNET_strdup (emsg); - GNUNET_SCHEDULER_add_now (&do_error, handle); + if (NULL != emsg) + { + handle->emsg = GNUNET_strdup(emsg); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + handle->emsg = GNUNET_strdup("Error storing records"); + GNUNET_SCHEDULER_add_now(&do_error, handle); return; } - handle->emsg = GNUNET_strdup ("Error storing records"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - resp = GNUNET_REST_create_response (NULL); - handle->proc (handle->proc_cls, resp, MHD_HTTP_NO_CONTENT); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + resp = GNUNET_REST_create_response(NULL); + handle->proc(handle->proc_cls, resp, MHD_HTTP_NO_CONTENT); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } @@ -413,34 +412,34 @@ create_finished (void *cls, int32_t success, const char *emsg) * @param emsg the error message (can be NULL) */ static void -del_finished (void *cls, int32_t success, const char *emsg) +del_finished(void *cls, int32_t success, const char *emsg) { struct RequestHandle *handle = cls; handle->add_qe = NULL; if (GNUNET_NO == success) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup ("No record found"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup("No record found"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } if (GNUNET_SYSERR == success) - { - if (NULL != emsg) { - handle->emsg = GNUNET_strdup (emsg); - GNUNET_SCHEDULER_add_now (&do_error, handle); + if (NULL != emsg) + { + handle->emsg = GNUNET_strdup(emsg); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + handle->emsg = GNUNET_strdup("Deleting record failed"); + GNUNET_SCHEDULER_add_now(&do_error, handle); return; } - handle->emsg = GNUNET_strdup ("Deleting record failed"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - handle->proc (handle->proc_cls, - GNUNET_REST_create_response (NULL), - MHD_HTTP_NO_CONTENT); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + handle->proc(handle->proc_cls, + GNUNET_REST_create_response(NULL), + MHD_HTTP_NO_CONTENT); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } @@ -451,7 +450,7 @@ del_finished (void *cls, int32_t success, const char *emsg) * @param cls the `struct RequestHandle` */ static void -namestore_list_finished (void *cls) +namestore_list_finished(void *cls) { struct RequestHandle *handle = cls; char *result_str; @@ -460,14 +459,14 @@ namestore_list_finished (void *cls) handle->list_it = NULL; if (NULL == handle->resp_object) - handle->resp_object = json_array (); - - result_str = json_dumps (handle->resp_object, 0); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result_str); - resp = GNUNET_REST_create_response (result_str); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_free_non_null (result_str); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + handle->resp_object = json_array(); + + result_str = json_dumps(handle->resp_object, 0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result_str); + resp = GNUNET_REST_create_response(result_str); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_free_non_null(result_str); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } @@ -477,22 +476,22 @@ namestore_list_finished (void *cls) * @param handle the RequestHandle */ static void -namestore_list_iteration (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *rname, - unsigned int rd_len, - const struct GNUNET_GNSRECORD_Data *rd) +namestore_list_iteration(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *rname, + unsigned int rd_len, + const struct GNUNET_GNSRECORD_Data *rd) { struct RequestHandle *handle = cls; json_t *record_obj; if (NULL == handle->resp_object) - handle->resp_object = json_array (); - record_obj = GNUNET_JSON_from_gnsrecord (rname, - rd, - rd_len); - json_array_append_new (handle->resp_object, record_obj); - GNUNET_NAMESTORE_zone_iterator_next (handle->list_it, 1); + handle->resp_object = json_array(); + record_obj = GNUNET_JSON_from_gnsrecord(rname, + rd, + rd_len); + json_array_append_new(handle->resp_object, record_obj); + GNUNET_NAMESTORE_zone_iterator_next(handle->list_it, 1); } @@ -504,9 +503,9 @@ namestore_list_iteration (void *cls, * @param cls the RequestHandle */ void -namestore_get (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +namestore_get(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; @@ -516,75 +515,77 @@ namestore_get (struct GNUNET_REST_RequestHandle *con_handle, ego_entry = NULL; // set zone to name if given - if (strlen (GNUNET_REST_API_NS_NAMESTORE) < strlen (handle->url)) - { - egoname = &handle->url[strlen (GNUNET_REST_API_NS_NAMESTORE) + 1]; - ego_entry = get_egoentry_namestore (handle, egoname); - - if (NULL == ego_entry) + if (strlen(GNUNET_REST_API_NS_NAMESTORE) < strlen(handle->url)) { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; + egoname = &handle->url[strlen(GNUNET_REST_API_NS_NAMESTORE) + 1]; + ego_entry = get_egoentry_namestore(handle, egoname); + + if (NULL == ego_entry) + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } } - } if (NULL != ego_entry) - handle->zone_pkey = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego); + handle->zone_pkey = GNUNET_IDENTITY_ego_get_private_key(ego_entry->ego); handle->list_it = - GNUNET_NAMESTORE_zone_iteration_start (handle->ns_handle, - handle->zone_pkey, - &namestore_iteration_error, - handle, - &namestore_list_iteration, - handle, - &namestore_list_finished, - handle); + GNUNET_NAMESTORE_zone_iteration_start(handle->ns_handle, + handle->zone_pkey, + &namestore_iteration_error, + handle, + &namestore_list_iteration, + handle, + &namestore_list_finished, + handle); if (NULL == handle->list_it) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_NAMESTORE_FAILED); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_NAMESTORE_FAILED); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } } static void -ns_lookup_error_cb (void *cls) +ns_lookup_error_cb(void *cls) { struct RequestHandle *handle = cls; - handle->emsg = GNUNET_strdup (GNUNET_REST_NAMESTORE_FAILED); - GNUNET_SCHEDULER_add_now (&do_error, handle); + + handle->emsg = GNUNET_strdup(GNUNET_REST_NAMESTORE_FAILED); + GNUNET_SCHEDULER_add_now(&do_error, handle); } static void -ns_lookup_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +ns_lookup_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct RequestHandle *handle = cls; struct GNUNET_GNSRECORD_Data rd_new[rd_count + handle->rd_count]; + for (int i = 0; i < rd_count; i++) rd_new[i] = rd[i]; for (int j = 0; j < handle->rd_count; j++) rd_new[rd_count + j] = handle->rd[j]; - handle->add_qe = GNUNET_NAMESTORE_records_store (handle->ns_handle, - handle->zone_pkey, - handle->record_name, - rd_count + handle->rd_count, - rd_new, - &create_finished, - handle); + handle->add_qe = GNUNET_NAMESTORE_records_store(handle->ns_handle, + handle->zone_pkey, + handle->record_name, + rd_count + handle->rd_count, + rd_new, + &create_finished, + handle); if (NULL == handle->add_qe) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_NAMESTORE_FAILED); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_NAMESTORE_FAILED); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } } @@ -596,9 +597,9 @@ ns_lookup_cb (void *cls, * @param cls the RequestHandle */ void -namestore_add (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +namestore_add(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; @@ -609,67 +610,67 @@ namestore_add (struct GNUNET_REST_RequestHandle *con_handle, char term_data[handle->rest_handle->data_size + 1]; if (0 >= handle->rest_handle->data_size) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_NAMESTORE_NO_DATA); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_NAMESTORE_NO_DATA); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } term_data[handle->rest_handle->data_size] = '\0'; - GNUNET_memcpy (term_data, - handle->rest_handle->data, - handle->rest_handle->data_size); - data_js = json_loads (term_data, JSON_DECODE_ANY, &err); + GNUNET_memcpy(term_data, + handle->rest_handle->data, + handle->rest_handle->data_size); + data_js = json_loads(term_data, JSON_DECODE_ANY, &err); struct GNUNET_JSON_Specification gnsspec[] = - {GNUNET_JSON_spec_gnsrecord (&handle->rd, &handle->rd_count, &handle->record_name), GNUNET_JSON_spec_end ()}; - if (GNUNET_OK != GNUNET_JSON_parse (data_js, gnsspec, NULL, NULL)) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_NAMESTORE_INVALID_DATA); - GNUNET_SCHEDULER_add_now (&do_error, handle); - json_decref (data_js); - return; - } - GNUNET_JSON_parse_free (gnsspec); - if (0 >= strlen (handle->record_name)) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_NAMESTORE_INVALID_DATA); - GNUNET_SCHEDULER_add_now (&do_error, handle); - json_decref (data_js); - return; - } - json_decref (data_js); + { GNUNET_JSON_spec_gnsrecord(&handle->rd, &handle->rd_count, &handle->record_name), GNUNET_JSON_spec_end() }; + if (GNUNET_OK != GNUNET_JSON_parse(data_js, gnsspec, NULL, NULL)) + { + handle->emsg = GNUNET_strdup(GNUNET_REST_NAMESTORE_INVALID_DATA); + GNUNET_SCHEDULER_add_now(&do_error, handle); + json_decref(data_js); + return; + } + GNUNET_JSON_parse_free(gnsspec); + if (0 >= strlen(handle->record_name)) + { + handle->emsg = GNUNET_strdup(GNUNET_REST_NAMESTORE_INVALID_DATA); + GNUNET_SCHEDULER_add_now(&do_error, handle); + json_decref(data_js); + return; + } + json_decref(data_js); egoname = NULL; ego_entry = NULL; // set zone to name if given - if (strlen (GNUNET_REST_API_NS_NAMESTORE) < strlen (handle->url)) - { - egoname = &handle->url[strlen (GNUNET_REST_API_NS_NAMESTORE) + 1]; - ego_entry = get_egoentry_namestore (handle, egoname); - - if (NULL == ego_entry) + if (strlen(GNUNET_REST_API_NS_NAMESTORE) < strlen(handle->url)) { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; + egoname = &handle->url[strlen(GNUNET_REST_API_NS_NAMESTORE) + 1]; + ego_entry = get_egoentry_namestore(handle, egoname); + + if (NULL == ego_entry) + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } } - } if (NULL != ego_entry) - handle->zone_pkey = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego); - handle->add_qe = GNUNET_NAMESTORE_records_lookup (handle->ns_handle, - handle->zone_pkey, - handle->record_name, - &ns_lookup_error_cb, - handle, - &ns_lookup_cb, - handle); + handle->zone_pkey = GNUNET_IDENTITY_ego_get_private_key(ego_entry->ego); + handle->add_qe = GNUNET_NAMESTORE_records_lookup(handle->ns_handle, + handle->zone_pkey, + handle->record_name, + &ns_lookup_error_cb, + handle, + &ns_lookup_cb, + handle); if (NULL == handle->add_qe) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_NAMESTORE_FAILED); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_NAMESTORE_FAILED); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } } @@ -681,9 +682,9 @@ namestore_add (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ void -namestore_delete (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +namestore_delete(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct GNUNET_HashCode key; @@ -694,46 +695,46 @@ namestore_delete (struct GNUNET_REST_RequestHandle *con_handle, ego_entry = NULL; // set zone to name if given - if (strlen (GNUNET_REST_API_NS_NAMESTORE) < strlen (handle->url)) - { - egoname = &handle->url[strlen (GNUNET_REST_API_NS_NAMESTORE) + 1]; - ego_entry = get_egoentry_namestore (handle, egoname); - - if (NULL == ego_entry) + if (strlen(GNUNET_REST_API_NS_NAMESTORE) < strlen(handle->url)) { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup (GNUNET_REST_IDENTITY_NOT_FOUND); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; + egoname = &handle->url[strlen(GNUNET_REST_API_NS_NAMESTORE) + 1]; + ego_entry = get_egoentry_namestore(handle, egoname); + + if (NULL == ego_entry) + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup(GNUNET_REST_IDENTITY_NOT_FOUND); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } } - } if (NULL != ego_entry) - handle->zone_pkey = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego); + handle->zone_pkey = GNUNET_IDENTITY_ego_get_private_key(ego_entry->ego); - GNUNET_CRYPTO_hash ("record_name", strlen ("record_name"), &key); + GNUNET_CRYPTO_hash("record_name", strlen("record_name"), &key); if (GNUNET_NO == - GNUNET_CONTAINER_multihashmap_contains (con_handle->url_param_map, &key)) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_NAMESTORE_INVALID_DATA); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - handle->record_name = GNUNET_strdup ( - GNUNET_CONTAINER_multihashmap_get (con_handle->url_param_map, &key)); - - handle->add_qe = GNUNET_NAMESTORE_records_store (handle->ns_handle, - handle->zone_pkey, - handle->record_name, - 0, - NULL, - &del_finished, - handle); + GNUNET_CONTAINER_multihashmap_contains(con_handle->url_param_map, &key)) + { + handle->emsg = GNUNET_strdup(GNUNET_REST_NAMESTORE_INVALID_DATA); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + handle->record_name = GNUNET_strdup( + GNUNET_CONTAINER_multihashmap_get(con_handle->url_param_map, &key)); + + handle->add_qe = GNUNET_NAMESTORE_records_store(handle->ns_handle, + handle->zone_pkey, + handle->record_name, + 0, + NULL, + &del_finished, + handle); if (NULL == handle->add_qe) - { - handle->emsg = GNUNET_strdup (GNUNET_REST_NAMESTORE_FAILED); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(GNUNET_REST_NAMESTORE_FAILED); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } } @@ -745,18 +746,18 @@ namestore_delete (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ static void -options_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +options_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct MHD_Response *resp; struct RequestHandle *handle = cls; // independent of path return all options - resp = GNUNET_REST_create_response (NULL); - MHD_add_response_header (resp, "Access-Control-Allow-Methods", allow_methods); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + resp = GNUNET_REST_create_response(NULL); + MHD_add_response_header(resp, "Access-Control-Allow-Methods", allow_methods); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); return; } @@ -767,22 +768,22 @@ options_cont (struct GNUNET_REST_RequestHandle *con_handle, * @param handle the request handle */ static void -init_cont (struct RequestHandle *handle) +init_cont(struct RequestHandle *handle) { struct GNUNET_REST_RequestHandlerError err; static const struct GNUNET_REST_RequestHandler handlers[] = - {{MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_NAMESTORE, &namestore_get}, - {MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_NAMESTORE, &namestore_add}, - {MHD_HTTP_METHOD_DELETE, GNUNET_REST_API_NS_NAMESTORE, &namestore_delete}, - {MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_NAMESTORE, &options_cont}, - GNUNET_REST_HANDLER_END}; + { { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_NAMESTORE, &namestore_get }, + { MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_NAMESTORE, &namestore_add }, + { MHD_HTTP_METHOD_DELETE, GNUNET_REST_API_NS_NAMESTORE, &namestore_delete }, + { MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_NAMESTORE, &options_cont }, + GNUNET_REST_HANDLER_END }; if (GNUNET_NO == - GNUNET_REST_handle_request (handle->rest_handle, handlers, &err, handle)) - { - handle->response_code = err.error_code; - GNUNET_SCHEDULER_add_now (&do_error, handle); - } + GNUNET_REST_handle_request(handle->rest_handle, handlers, &err, handle)) + { + handle->response_code = err.error_code; + GNUNET_SCHEDULER_add_now(&do_error, handle); + } } @@ -818,32 +819,32 @@ init_cont (struct RequestHandle *handle) * must thus no longer be used */ static void -id_connect_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +id_connect_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; struct GNUNET_CRYPTO_EcdsaPublicKey pk; if ((NULL == ego) && (ID_REST_STATE_INIT == handle->state)) - { - handle->state = ID_REST_STATE_POST_INIT; - init_cont (handle); - return; - } + { + handle->state = ID_REST_STATE_POST_INIT; + init_cont(handle); + return; + } if (ID_REST_STATE_INIT == handle->state) - { - ego_entry = GNUNET_new (struct EgoEntry); - GNUNET_IDENTITY_ego_get_public_key (ego, &pk); - ego_entry->keystring = GNUNET_CRYPTO_ecdsa_public_key_to_string (&pk); - ego_entry->ego = ego; - GNUNET_asprintf (&ego_entry->identifier, "%s", name); - GNUNET_CONTAINER_DLL_insert_tail (handle->ego_head, - handle->ego_tail, - ego_entry); - } + { + ego_entry = GNUNET_new(struct EgoEntry); + GNUNET_IDENTITY_ego_get_public_key(ego, &pk); + ego_entry->keystring = GNUNET_CRYPTO_ecdsa_public_key_to_string(&pk); + ego_entry->ego = ego; + GNUNET_asprintf(&ego_entry->identifier, "%s", name); + GNUNET_CONTAINER_DLL_insert_tail(handle->ego_head, + handle->ego_tail, + ego_entry); + } } @@ -859,11 +860,11 @@ id_connect_cb (void *cls, * @return GNUNET_OK if request accepted */ static void -rest_process_request (struct GNUNET_REST_RequestHandle *rest_handle, - GNUNET_REST_ResultProcessor proc, - void *proc_cls) +rest_process_request(struct GNUNET_REST_RequestHandle *rest_handle, + GNUNET_REST_ResultProcessor proc, + void *proc_cls) { - struct RequestHandle *handle = GNUNET_new (struct RequestHandle); + struct RequestHandle *handle = GNUNET_new(struct RequestHandle); handle->response_code = 0; handle->timeout = GNUNET_TIME_UNIT_FOREVER_REL; @@ -872,18 +873,18 @@ rest_process_request (struct GNUNET_REST_RequestHandle *rest_handle, handle->rest_handle = rest_handle; handle->zone_pkey = NULL; - handle->url = GNUNET_strdup (rest_handle->url); - if (handle->url[strlen (handle->url) - 1] == '/') - handle->url[strlen (handle->url) - 1] = '\0'; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n"); + handle->url = GNUNET_strdup(rest_handle->url); + if (handle->url[strlen(handle->url) - 1] == '/') + handle->url[strlen(handle->url) - 1] = '\0'; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n"); - handle->ns_handle = GNUNET_NAMESTORE_connect (cfg); + handle->ns_handle = GNUNET_NAMESTORE_connect(cfg); handle->identity_handle = - GNUNET_IDENTITY_connect (cfg, &id_connect_cb, handle); + GNUNET_IDENTITY_connect(cfg, &id_connect_cb, handle); handle->timeout_task = - GNUNET_SCHEDULER_add_delayed (handle->timeout, &do_error, handle); + GNUNET_SCHEDULER_add_delayed(handle->timeout, &do_error, handle); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connected\n"); } @@ -894,7 +895,7 @@ rest_process_request (struct GNUNET_REST_RequestHandle *rest_handle, * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_rest_namestore_init (void *cls) +libgnunet_plugin_rest_namestore_init(void *cls) { static struct Plugin plugin; struct GNUNET_REST_Plugin *api; @@ -902,21 +903,21 @@ libgnunet_plugin_rest_namestore_init (void *cls) cfg = cls; if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.cfg = cfg; - api = GNUNET_new (struct GNUNET_REST_Plugin); + api = GNUNET_new(struct GNUNET_REST_Plugin); api->cls = &plugin; api->name = GNUNET_REST_API_NS_NAMESTORE; api->process_request = &rest_process_request; - GNUNET_asprintf (&allow_methods, - "%s, %s, %s, %s, %s", - MHD_HTTP_METHOD_GET, - MHD_HTTP_METHOD_POST, - MHD_HTTP_METHOD_PUT, - MHD_HTTP_METHOD_DELETE, - MHD_HTTP_METHOD_OPTIONS); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Namestore REST API initialized\n")); + GNUNET_asprintf(&allow_methods, + "%s, %s, %s, %s, %s", + MHD_HTTP_METHOD_GET, + MHD_HTTP_METHOD_POST, + MHD_HTTP_METHOD_PUT, + MHD_HTTP_METHOD_DELETE, + MHD_HTTP_METHOD_OPTIONS); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, _("Namestore REST API initialized\n")); return api; } @@ -928,15 +929,16 @@ libgnunet_plugin_rest_namestore_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_rest_namestore_done (void *cls) +libgnunet_plugin_rest_namestore_done(void *cls) { struct GNUNET_REST_Plugin *api = cls; struct Plugin *plugin = api->cls; + plugin->cfg = NULL; - GNUNET_free_non_null (allow_methods); - GNUNET_free (api); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Namestore REST plugin is finished\n"); + GNUNET_free_non_null(allow_methods); + GNUNET_free(api); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Namestore REST plugin is finished\n"); return NULL; } diff --git a/src/namestore/test_common.c b/src/namestore/test_common.c index 6d9761701..d88d1feb9 100644 --- a/src/namestore/test_common.c +++ b/src/namestore/test_common.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_common.c * @brief common functions for testcase setup @@ -26,36 +26,36 @@ * test if we can load the plugin @a name. */ static int -TNC_test_plugin (const char *cfg_name) +TNC_test_plugin(const char *cfg_name) { char *database; char *db_lib_name; struct GNUNET_NAMESTORE_PluginFunctions *db; struct GNUNET_CONFIGURATION_Handle *cfg; - cfg = GNUNET_CONFIGURATION_create (); - if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, cfg_name)) - { - GNUNET_break (0); - GNUNET_CONFIGURATION_destroy (cfg); - return GNUNET_SYSERR; - } - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "namestore", - "database", - &database)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No database backend configured\n"); - GNUNET_CONFIGURATION_destroy (cfg); - return GNUNET_SYSERR; - } - GNUNET_asprintf (&db_lib_name, "libgnunet_plugin_namestore_%s", database); - GNUNET_free (database); - db = GNUNET_PLUGIN_load (db_lib_name, (void *) cfg); + cfg = GNUNET_CONFIGURATION_create(); + if (GNUNET_OK != GNUNET_CONFIGURATION_load(cfg, cfg_name)) + { + GNUNET_break(0); + GNUNET_CONFIGURATION_destroy(cfg); + return GNUNET_SYSERR; + } + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "namestore", + "database", + &database)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No database backend configured\n"); + GNUNET_CONFIGURATION_destroy(cfg); + return GNUNET_SYSERR; + } + GNUNET_asprintf(&db_lib_name, "libgnunet_plugin_namestore_%s", database); + GNUNET_free(database); + db = GNUNET_PLUGIN_load(db_lib_name, (void *)cfg); if (NULL != db) - GNUNET_break (NULL == GNUNET_PLUGIN_unload (db_lib_name, db)); - GNUNET_free (db_lib_name); - GNUNET_CONFIGURATION_destroy (cfg); + GNUNET_break(NULL == GNUNET_PLUGIN_unload(db_lib_name, db)); + GNUNET_free(db_lib_name); + GNUNET_CONFIGURATION_destroy(cfg); if (NULL == db) return GNUNET_NO; return GNUNET_YES; @@ -68,13 +68,13 @@ TNC_test_plugin (const char *cfg_name) */ #define SETUP_CFG(plugin_name, cfg_name) \ do \ - { \ - plugin_name = GNUNET_TESTING_get_testname_from_underscore (argv[0]); \ - GNUNET_asprintf (&cfg_name, "test_namestore_api_%s.conf", plugin_name); \ - if (! TNC_test_plugin (cfg_name)) \ - { \ - GNUNET_free (cfg_name); \ - return 77; \ - } \ - GNUNET_DISK_purge_cfg_dir (cfg_name, "GNUNET_TEST_HOME"); \ - } while (0) + { \ + plugin_name = GNUNET_TESTING_get_testname_from_underscore(argv[0]); \ + GNUNET_asprintf(&cfg_name, "test_namestore_api_%s.conf", plugin_name); \ + if (!TNC_test_plugin(cfg_name)) \ + { \ + GNUNET_free(cfg_name); \ + return 77; \ + } \ + GNUNET_DISK_purge_cfg_dir(cfg_name, "GNUNET_TEST_HOME"); \ + } while (0) diff --git a/src/namestore/test_namestore_api_lookup_nick.c b/src/namestore/test_namestore_api_lookup_nick.c index 392a2521d..130f9bc1e 100644 --- a/src/namestore/test_namestore_api_lookup_nick.c +++ b/src/namestore/test_namestore_api_lookup_nick.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_lookup_nick.c * @brief testcase for namestore_api.c: NICK records @@ -34,7 +34,7 @@ #define TEST_RECORD_DATA 'a' -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) static struct GNUNET_NAMESTORE_Handle *nsh; @@ -55,20 +55,20 @@ static const char * name = "d"; static void -cleanup () +cleanup() { - GNUNET_free_non_null ((void *)rd_orig.data); + GNUNET_free_non_null((void *)rd_orig.data); if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_free(privkey); + privkey = NULL; + } + GNUNET_SCHEDULER_shutdown(); } @@ -79,32 +79,32 @@ cleanup () * @param tc scheduler context */ static void -endbadly (void *cls) +endbadly(void *cls) { if (NULL != nsqe) - { - GNUNET_NAMESTORE_cancel (nsqe); - nsqe = NULL; - } - cleanup (); + { + GNUNET_NAMESTORE_cancel(nsqe); + nsqe = NULL; + } + cleanup(); res = 1; } static void -end (void *cls) +end(void *cls) { - cleanup (); + cleanup(); res = 0; } static void -lookup_it (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +lookup_it(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { nsqe = NULL; int c; @@ -112,222 +112,221 @@ lookup_it (void *cls, int found_nick = GNUNET_NO; if (0 != GNUNET_memcmp(privkey, zone)) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL ); - return; - } + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } if (NULL == label) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL ); - return; - } - - if (0 != strcmp (label, name)) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL ); - return; - } - - if (2 != rd_count) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL ); - return; - } + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } - for (c = 0; c < rd_count; c++) - { - if (GNUNET_GNSRECORD_TYPE_NICK == rd[c].record_type) + if (0 != strcmp(label, name)) { - if (rd[c].data_size != strlen(TEST_NICK)+1) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL ); - return; - } - if (0 != (rd[c].flags & GNUNET_GNSRECORD_RF_PRIVATE)) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL ); - return; - } - if (0 != strcmp(rd[c].data, TEST_NICK)) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL ); - return; - } - found_nick = GNUNET_YES; + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; } - else + + if (2 != rd_count) { - if (rd[c].record_type != TEST_RECORD_TYPE) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL ); - return; - } - if (rd[c].data_size != TEST_RECORD_DATALEN) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL ); - return; - } - if (0 != memcmp (rd[c].data, rd_orig.data, TEST_RECORD_DATALEN)) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL ); - return; - } - if (rd[c].flags != rd->flags) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL ); - return; - } - found_record = GNUNET_YES; + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; } - } + for (c = 0; c < rd_count; c++) + { + if (GNUNET_GNSRECORD_TYPE_NICK == rd[c].record_type) + { + if (rd[c].data_size != strlen(TEST_NICK) + 1) + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + if (0 != (rd[c].flags & GNUNET_GNSRECORD_RF_PRIVATE)) + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + if (0 != strcmp(rd[c].data, TEST_NICK)) + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + found_nick = GNUNET_YES; + } + else + { + if (rd[c].record_type != TEST_RECORD_TYPE) + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + if (rd[c].data_size != TEST_RECORD_DATALEN) + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + if (0 != memcmp(rd[c].data, rd_orig.data, TEST_RECORD_DATALEN)) + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + if (rd[c].flags != rd->flags) + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + found_record = GNUNET_YES; + } + } /* Done */ if ((GNUNET_YES == found_nick) && (GNUNET_YES == found_record)) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - GNUNET_SCHEDULER_add_now (&end, NULL ); - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + GNUNET_SCHEDULER_add_now(&end, NULL); + } else - { - GNUNET_break (0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - GNUNET_SCHEDULER_add_now (&endbadly, NULL ); - } + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + } } static void -fail_cb (void *cls) +fail_cb(void *cls) { - GNUNET_assert (0); + GNUNET_assert(0); } static void -put_cont (void *cls, int32_t success, const char *emsg) +put_cont(void *cls, int32_t success, const char *emsg) { const char *name = cls; nsqe = NULL; - GNUNET_assert (NULL != cls); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name store added record for `%s': %s\n", - name, - (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); + GNUNET_assert(NULL != cls); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name store added record for `%s': %s\n", + name, + (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); if (GNUNET_OK != success) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } /* Lookup */ - nsqe = GNUNET_NAMESTORE_records_lookup (nsh, - privkey, - name, - &fail_cb, - NULL, - &lookup_it, - NULL); + nsqe = GNUNET_NAMESTORE_records_lookup(nsh, + privkey, + name, + &fail_cb, + NULL, + &lookup_it, + NULL); } static void -nick_cont (void *cls, int32_t success, const char *emsg) +nick_cont(void *cls, int32_t success, const char *emsg) { const char *name = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Nick added : %s\n", - (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Nick added : %s\n", + (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); rd_orig.expiration_time = GNUNET_TIME_absolute_get().abs_value_us; rd_orig.record_type = TEST_RECORD_TYPE; rd_orig.data_size = TEST_RECORD_DATALEN; - rd_orig.data = GNUNET_malloc (TEST_RECORD_DATALEN); + rd_orig.data = GNUNET_malloc(TEST_RECORD_DATALEN); rd_orig.flags = 0; - memset ((char *) rd_orig.data, 'a', TEST_RECORD_DATALEN); + memset((char *)rd_orig.data, 'a', TEST_RECORD_DATALEN); - nsqe = GNUNET_NAMESTORE_records_store (nsh, privkey, name, - 1, &rd_orig, &put_cont, (void *) name); + nsqe = GNUNET_NAMESTORE_records_store(nsh, privkey, name, + 1, &rd_orig, &put_cont, (void *)name); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, - NULL); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey != NULL); - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, - &pubkey); - - nsh = GNUNET_NAMESTORE_connect (cfg); - GNUNET_break (NULL != nsh); - - nsqe = GNUNET_NAMESTORE_set_nick (nsh, - privkey, - TEST_NICK, - &nick_cont, - (void *) name); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, + NULL); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey != NULL); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, + &pubkey); + + nsh = GNUNET_NAMESTORE_connect(cfg); + GNUNET_break(NULL != nsh); + + nsqe = GNUNET_NAMESTORE_set_nick(nsh, + privkey, + TEST_NICK, + &nick_cont, + (void *)name); if (NULL == nsqe) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore cannot store no block\n")); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore cannot store no block\n")); + } } #include "test_common.c" int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-lookup-nick", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-lookup-nick", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_lookup_private.c b/src/namestore/test_namestore_api_lookup_private.c index cf9bfc20c..a387720a0 100644 --- a/src/namestore/test_namestore_api_lookup_private.c +++ b/src/namestore/test_namestore_api_lookup_private.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_store.c * @brief testcase for namestore_api.c: store a record @@ -32,7 +32,7 @@ #define TEST_RECORD_DATA 'a' -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) static struct GNUNET_NAMESTORE_Handle *nsh; @@ -51,19 +51,19 @@ static const char * name = "d"; static void -cleanup () +cleanup() { if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_free(privkey); + privkey = NULL; + } + GNUNET_SCHEDULER_shutdown(); } @@ -73,152 +73,152 @@ cleanup () * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { endbadly_task = NULL; if (NULL != nsqe) - { - GNUNET_NAMESTORE_cancel (nsqe); - nsqe = NULL; - } - cleanup (); + { + GNUNET_NAMESTORE_cancel(nsqe); + nsqe = NULL; + } + cleanup(); res = 1; } static void -end (void *cls) +end(void *cls) { - cleanup (); + cleanup(); res = 0; } static void -lookup_it (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +lookup_it(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { nsqe = NULL; - if (0 != GNUNET_memcmp (privkey, - zone)) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } + if (0 != GNUNET_memcmp(privkey, + zone)) + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } if (NULL == label) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } - - if (0 != strcmp (label, name)) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + + if (0 != strcmp(label, name)) + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } if (1 != rd_count) - { - GNUNET_break(0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } /* Done */ - GNUNET_SCHEDULER_cancel (endbadly_task); + GNUNET_SCHEDULER_cancel(endbadly_task); endbadly_task = NULL; - GNUNET_SCHEDULER_add_now (&end, NULL); + GNUNET_SCHEDULER_add_now(&end, NULL); } static void -fail_cb (void *cls) +fail_cb(void *cls) { - GNUNET_assert (0); + GNUNET_assert(0); } static void -put_cont (void *cls, - int32_t success, - const char *emsg) +put_cont(void *cls, + int32_t success, + const char *emsg) { const char *name = cls; nsqe = NULL; - GNUNET_assert (NULL != cls); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name store added record for `%s': %s\n", - name, - (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); + GNUNET_assert(NULL != cls); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name store added record for `%s': %s\n", + name, + (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); if (GNUNET_OK != success) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } /* Lookup */ - nsqe = GNUNET_NAMESTORE_records_lookup (nsh, - privkey, - name, - &fail_cb, - NULL, - &lookup_it, - NULL); + nsqe = GNUNET_NAMESTORE_records_lookup(nsh, + privkey, + name, + &fail_cb, + NULL, + &lookup_it, + NULL); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct GNUNET_GNSRECORD_Data rd; - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, - NULL); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey != NULL); - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, &pubkey); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, + NULL); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey != NULL); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, &pubkey); rd.expiration_time = GNUNET_TIME_absolute_get().abs_value_us; rd.record_type = TEST_RECORD_TYPE; rd.data_size = TEST_RECORD_DATALEN; - rd.data = GNUNET_malloc (TEST_RECORD_DATALEN); + rd.data = GNUNET_malloc(TEST_RECORD_DATALEN); rd.flags = 0; - memset ((char *) rd.data, 'a', TEST_RECORD_DATALEN); - - nsh = GNUNET_NAMESTORE_connect (cfg); - GNUNET_break (NULL != nsh); - nsqe = GNUNET_NAMESTORE_records_store (nsh, - privkey, - name, - 1, - &rd, - &put_cont, - (void *) name); + memset((char *)rd.data, 'a', TEST_RECORD_DATALEN); + + nsh = GNUNET_NAMESTORE_connect(cfg); + GNUNET_break(NULL != nsh); + nsqe = GNUNET_NAMESTORE_records_store(nsh, + privkey, + name, + 1, + &rd, + &put_cont, + (void *)name); if (NULL == nsqe) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore cannot store no block\n")); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore cannot store no block\n")); + } - GNUNET_free ((void *)rd.data); + GNUNET_free((void *)rd.data); } @@ -226,7 +226,7 @@ run (void *cls, int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *plugin_name; char *cfg_name; @@ -234,16 +234,16 @@ main (int argc, char *argv[]) SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-lookup-private", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-lookup-private", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_lookup_public.c b/src/namestore/test_namestore_api_lookup_public.c index 460be0a18..01f07eb39 100644 --- a/src/namestore/test_namestore_api_lookup_public.c +++ b/src/namestore/test_namestore_api_lookup_public.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api.c * @brief testcase for namestore_api.c: store a record and perform a lookup @@ -33,7 +33,7 @@ #define TEST_RECORD_DATA 'a' -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static struct GNUNET_NAMESTORE_Handle *nsh; @@ -54,24 +54,24 @@ static struct GNUNET_NAMECACHE_QueueEntry *ncqe; static void -cleanup () +cleanup() { if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } if (NULL != nch) - { - GNUNET_NAMECACHE_disconnect (nch); - nch = NULL; - } + { + GNUNET_NAMECACHE_disconnect(nch); + nch = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_free(privkey); + privkey = NULL; + } + GNUNET_SCHEDULER_shutdown(); } @@ -81,145 +81,145 @@ cleanup () * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { if (NULL != nsqe) - { - GNUNET_NAMESTORE_cancel (nsqe); - nsqe = NULL; - } + { + GNUNET_NAMESTORE_cancel(nsqe); + nsqe = NULL; + } if (NULL != ncqe) - { - GNUNET_NAMECACHE_cancel (ncqe); - ncqe = NULL; - } - cleanup (); + { + GNUNET_NAMECACHE_cancel(ncqe); + ncqe = NULL; + } + cleanup(); res = 1; } static void -end (void *cls) +end(void *cls) { - cleanup (); + cleanup(); res = 0; } static void -rd_decrypt_cb (void *cls, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +rd_decrypt_cb(void *cls, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { char rd_cmp_data[TEST_RECORD_DATALEN]; - GNUNET_assert (1 == rd_count); - GNUNET_assert (NULL != rd); + GNUNET_assert(1 == rd_count); + GNUNET_assert(NULL != rd); - memset (rd_cmp_data, 'a', TEST_RECORD_DATALEN); + memset(rd_cmp_data, 'a', TEST_RECORD_DATALEN); - GNUNET_assert (TEST_RECORD_TYPE == rd[0].record_type); - GNUNET_assert (TEST_RECORD_DATALEN == rd[0].data_size); - GNUNET_assert (0 == memcmp (&rd_cmp_data, rd[0].data, TEST_RECORD_DATALEN)); + GNUNET_assert(TEST_RECORD_TYPE == rd[0].record_type); + GNUNET_assert(TEST_RECORD_DATALEN == rd[0].data_size); + GNUNET_assert(0 == memcmp(&rd_cmp_data, rd[0].data, TEST_RECORD_DATALEN)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Block was decrypted successfully \n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Block was decrypted successfully \n"); - GNUNET_SCHEDULER_add_now (&end, NULL); + GNUNET_SCHEDULER_add_now(&end, NULL); } static void -name_lookup_proc (void *cls, - const struct GNUNET_GNSRECORD_Block *block) +name_lookup_proc(void *cls, + const struct GNUNET_GNSRECORD_Block *block) { const char *name = cls; ncqe = NULL; - GNUNET_assert (NULL != cls); + GNUNET_assert(NULL != cls); if (endbadly_task != NULL) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } if (NULL == block) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore returned no block\n")); - if (endbadly_task != NULL) - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Namestore returned block, decrypting \n"); - GNUNET_assert (GNUNET_OK == GNUNET_GNSRECORD_block_decrypt(block, - &pubkey, name, &rd_decrypt_cb, (void *) name)); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore returned no block\n")); + if (endbadly_task != NULL) + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Namestore returned block, decrypting \n"); + GNUNET_assert(GNUNET_OK == GNUNET_GNSRECORD_block_decrypt(block, + &pubkey, name, &rd_decrypt_cb, (void *)name)); } static void -put_cont (void *cls, int32_t success, const char *emsg) +put_cont(void *cls, int32_t success, const char *emsg) { const char *name = cls; struct GNUNET_HashCode derived_hash; struct GNUNET_CRYPTO_EcdsaPublicKey pubkey; nsqe = NULL; - GNUNET_assert (NULL != cls); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name store added record for `%s': %s\n", - name, - (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); + GNUNET_assert(NULL != cls); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name store added record for `%s': %s\n", + name, + (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); /* Create derived hash */ - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, &pubkey); - GNUNET_GNSRECORD_query_from_public_key (&pubkey, name, &derived_hash); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, &pubkey); + GNUNET_GNSRECORD_query_from_public_key(&pubkey, name, &derived_hash); - ncqe = GNUNET_NAMECACHE_lookup_block (nch, &derived_hash, - &name_lookup_proc, (void *) name); + ncqe = GNUNET_NAMECACHE_lookup_block(nch, &derived_hash, + &name_lookup_proc, (void *)name); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct GNUNET_GNSRECORD_Data rd; const char * name = "dummy.dummy.gnunet"; - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, - NULL); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey != NULL); - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, - &pubkey); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, + NULL); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey != NULL); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, + &pubkey); rd.expiration_time = GNUNET_TIME_absolute_get().abs_value_us + 1000000000; rd.record_type = TEST_RECORD_TYPE; rd.data_size = TEST_RECORD_DATALEN; - rd.data = GNUNET_malloc (TEST_RECORD_DATALEN); + rd.data = GNUNET_malloc(TEST_RECORD_DATALEN); rd.flags = 0; - memset ((char *) rd.data, 'a', TEST_RECORD_DATALEN); - - nsh = GNUNET_NAMESTORE_connect (cfg); - nch = GNUNET_NAMECACHE_connect (cfg); - GNUNET_break (NULL != nsh); - GNUNET_break (NULL != nch); - nsqe = GNUNET_NAMESTORE_records_store (nsh, privkey, name, - 1, &rd, &put_cont, (void *) name); + memset((char *)rd.data, 'a', TEST_RECORD_DATALEN); + + nsh = GNUNET_NAMESTORE_connect(cfg); + nch = GNUNET_NAMECACHE_connect(cfg); + GNUNET_break(NULL != nsh); + GNUNET_break(NULL != nch); + nsqe = GNUNET_NAMESTORE_records_store(nsh, privkey, name, + 1, &rd, &put_cont, (void *)name); if (NULL == nsqe) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore cannot store no block\n")); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore cannot store no block\n")); + } - GNUNET_free ((void *)rd.data); + GNUNET_free((void *)rd.data); } @@ -227,24 +227,24 @@ run (void *cls, int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_lookup_shadow.c b/src/namestore/test_namestore_api_lookup_shadow.c index 1938054d4..d25cdcdbb 100644 --- a/src/namestore/test_namestore_api_lookup_shadow.c +++ b/src/namestore/test_namestore_api_lookup_shadow.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_lookup_shadow.c * @brief testcase for namestore_api.c: store a shadow record and perform a lookup @@ -35,7 +35,7 @@ #define TEST_RECORD_DATA 'a' -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static struct GNUNET_NAMESTORE_Handle *nsh; @@ -56,24 +56,24 @@ static struct GNUNET_NAMECACHE_QueueEntry *ncqe; static void -cleanup () +cleanup() { if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } if (NULL != nch) - { - GNUNET_NAMECACHE_disconnect (nch); - nch = NULL; - } + { + GNUNET_NAMECACHE_disconnect(nch); + nch = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_free(privkey); + privkey = NULL; + } + GNUNET_SCHEDULER_shutdown(); } @@ -83,178 +83,178 @@ cleanup () * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { if (NULL != nsqe) - { - GNUNET_NAMESTORE_cancel (nsqe); - nsqe = NULL; - } + { + GNUNET_NAMESTORE_cancel(nsqe); + nsqe = NULL; + } if (NULL != ncqe) - { - GNUNET_NAMECACHE_cancel (ncqe); - ncqe = NULL; - } - cleanup (); + { + GNUNET_NAMECACHE_cancel(ncqe); + ncqe = NULL; + } + cleanup(); res = 1; } static void -end (void *cls) +end(void *cls) { - cleanup (); + cleanup(); res = 0; } static void -rd_decrypt_cb (void *cls, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +rd_decrypt_cb(void *cls, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { char rd_cmp_data[TEST_RECORD_DATALEN]; if (1 != rd_count) - { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; - } + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } if (NULL == rd) - { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; - } - memset (rd_cmp_data, 'a', TEST_RECORD_DATALEN); + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } + memset(rd_cmp_data, 'a', TEST_RECORD_DATALEN); if (TEST_RECORD_TYPE != rd[0].record_type) - { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; - } + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } if (TEST_RECORD_DATALEN != rd[0].data_size) - { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; - } - if (0 != memcmp (&rd_cmp_data, rd[0].data, TEST_RECORD_DATALEN)) - { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; - } + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } + if (0 != memcmp(&rd_cmp_data, rd[0].data, TEST_RECORD_DATALEN)) + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } if (0 != (GNUNET_GNSRECORD_RF_SHADOW_RECORD & rd[0].flags)) - { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; - } + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Block was decrypted successfully \n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Block was decrypted successfully \n"); - GNUNET_SCHEDULER_add_now (&end, NULL); + GNUNET_SCHEDULER_add_now(&end, NULL); } static void -name_lookup_proc (void *cls, - const struct GNUNET_GNSRECORD_Block *block) +name_lookup_proc(void *cls, + const struct GNUNET_GNSRECORD_Block *block) { const char *name = cls; ncqe = NULL; - GNUNET_assert (NULL != cls); + GNUNET_assert(NULL != cls); if (endbadly_task != NULL) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } if (NULL == block) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore returned no block\n")); - if (endbadly_task != NULL) - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Namestore returned block, decrypting \n"); - GNUNET_assert (GNUNET_OK == GNUNET_GNSRECORD_block_decrypt(block, - &pubkey, name, &rd_decrypt_cb, (void *) name)); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore returned no block\n")); + if (endbadly_task != NULL) + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Namestore returned block, decrypting \n"); + GNUNET_assert(GNUNET_OK == GNUNET_GNSRECORD_block_decrypt(block, + &pubkey, name, &rd_decrypt_cb, (void *)name)); } static void -put_cont (void *cls, int32_t success, const char *emsg) +put_cont(void *cls, int32_t success, const char *emsg) { const char *name = cls; struct GNUNET_HashCode derived_hash; struct GNUNET_CRYPTO_EcdsaPublicKey pubkey; nsqe = NULL; - GNUNET_assert (NULL != cls); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name store added record for `%s': %s\n", - name, - (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); + GNUNET_assert(NULL != cls); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name store added record for `%s': %s\n", + name, + (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); /* Create derived hash */ - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, &pubkey); - GNUNET_GNSRECORD_query_from_public_key (&pubkey, name, &derived_hash); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, &pubkey); + GNUNET_GNSRECORD_query_from_public_key(&pubkey, name, &derived_hash); - ncqe = GNUNET_NAMECACHE_lookup_block (nch, &derived_hash, - &name_lookup_proc, (void *) name); + ncqe = GNUNET_NAMECACHE_lookup_block(nch, &derived_hash, + &name_lookup_proc, (void *)name); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct GNUNET_GNSRECORD_Data rd; const char * name = "dummy.dummy.gnunet"; - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, - NULL); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey != NULL); - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, - &pubkey); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, + NULL); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey != NULL); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, + &pubkey); rd.expiration_time = GNUNET_TIME_absolute_get().abs_value_us + 1000000000; rd.record_type = TEST_RECORD_TYPE; rd.data_size = TEST_RECORD_DATALEN; - rd.data = GNUNET_malloc (TEST_RECORD_DATALEN); + rd.data = GNUNET_malloc(TEST_RECORD_DATALEN); rd.flags = GNUNET_GNSRECORD_RF_SHADOW_RECORD; - memset ((char *) rd.data, 'a', TEST_RECORD_DATALEN); - - nsh = GNUNET_NAMESTORE_connect (cfg); - nch = GNUNET_NAMECACHE_connect (cfg); - GNUNET_break (NULL != nsh); - GNUNET_break (NULL != nch); - nsqe = GNUNET_NAMESTORE_records_store (nsh, - privkey, - name, - 1, - &rd, - &put_cont, - (void *) name); + memset((char *)rd.data, 'a', TEST_RECORD_DATALEN); + + nsh = GNUNET_NAMESTORE_connect(cfg); + nch = GNUNET_NAMECACHE_connect(cfg); + GNUNET_break(NULL != nsh); + GNUNET_break(NULL != nch); + nsqe = GNUNET_NAMESTORE_records_store(nsh, + privkey, + name, + 1, + &rd, + &put_cont, + (void *)name); if (NULL == nsqe) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore cannot store no block\n")); - } - GNUNET_free ((void *)rd.data); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore cannot store no block\n")); + } + GNUNET_free((void *)rd.data); } @@ -262,24 +262,24 @@ run (void *cls, int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-lookup-shadow", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-lookup-shadow", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_lookup_shadow_filter.c b/src/namestore/test_namestore_api_lookup_shadow_filter.c index 3d1dbfacf..d8d6b8a29 100644 --- a/src/namestore/test_namestore_api_lookup_shadow_filter.c +++ b/src/namestore/test_namestore_api_lookup_shadow_filter.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_lookup_shadow_filter.c * @brief testcase for namestore_api.c: store a record with short expiration @@ -37,8 +37,8 @@ #define TEST_RECORD_DATA 'a' #define TEST_SHADOW_RECORD_DATA 'b' -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) -#define EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) +#define EXPIRATION GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) static struct GNUNET_NAMESTORE_Handle *nsh; @@ -70,24 +70,24 @@ static struct GNUNET_CRYPTO_EcdsaPublicKey pubkey; static void -cleanup () +cleanup() { if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } if (NULL != nch) - { - GNUNET_NAMECACHE_disconnect (nch); - nch = NULL; - } + { + GNUNET_NAMECACHE_disconnect(nch); + nch = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_free(privkey); + privkey = NULL; + } + GNUNET_SCHEDULER_shutdown(); } @@ -97,239 +97,240 @@ cleanup () * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { if (NULL != delayed_lookup_task) - { - GNUNET_SCHEDULER_cancel (delayed_lookup_task); - delayed_lookup_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(delayed_lookup_task); + delayed_lookup_task = NULL; + } if (NULL != nsqe) - { - GNUNET_NAMESTORE_cancel (nsqe); - nsqe = NULL; - } + { + GNUNET_NAMESTORE_cancel(nsqe); + nsqe = NULL; + } if (NULL != ncqe) - { - GNUNET_NAMECACHE_cancel (ncqe); - ncqe = NULL; - } - cleanup (); + { + GNUNET_NAMECACHE_cancel(ncqe); + ncqe = NULL; + } + cleanup(); res = 1; } static void -end (void *cls) +end(void *cls) { - cleanup (); + cleanup(); res = 0; } static void -rd_decrypt_cb (void *cls, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +rd_decrypt_cb(void *cls, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_GNSRECORD_Data *expected_rd = cls; char rd_cmp_data[TEST_RECORD_DATALEN]; if (1 != rd_count) - { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; - } - if (NULL == rd) - { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; - } - if (expected_rd == &records[0]) - { - /* Expecting active record */ - memset (rd_cmp_data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); - if (TEST_RECORD_TYPE != rd[0].record_type) - { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; - } - if (TEST_RECORD_DATALEN != rd[0].data_size) { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); return; } - if (0 != memcmp (&rd_cmp_data, rd[0].data, TEST_RECORD_DATALEN)) + if (NULL == rd) { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); return; } - if (0 != (GNUNET_GNSRECORD_RF_SHADOW_RECORD & rd[0].flags)) + if (expected_rd == &records[0]) { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; + /* Expecting active record */ + memset(rd_cmp_data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); + if (TEST_RECORD_TYPE != rd[0].record_type) + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } + if (TEST_RECORD_DATALEN != rd[0].data_size) + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } + if (0 != memcmp(&rd_cmp_data, rd[0].data, TEST_RECORD_DATALEN)) + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } + if (0 != (GNUNET_GNSRECORD_RF_SHADOW_RECORD & rd[0].flags)) + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Block was decrypted successfully with active record\n"); } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Block was decrypted successfully with active record\n"); - } if (expected_rd == &records[1]) - { - /* Expecting shadow record but without shadow flag*/ - memset (rd_cmp_data, TEST_SHADOW_RECORD_DATA, TEST_RECORD_DATALEN); - if (TEST_RECORD_TYPE != rd[0].record_type) { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; + /* Expecting shadow record but without shadow flag*/ + memset(rd_cmp_data, TEST_SHADOW_RECORD_DATA, TEST_RECORD_DATALEN); + if (TEST_RECORD_TYPE != rd[0].record_type) + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } + if (TEST_RECORD_DATALEN != rd[0].data_size) + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } + if (0 != memcmp(&rd_cmp_data, rd[0].data, TEST_RECORD_DATALEN)) + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } + if (0 != (GNUNET_GNSRECORD_RF_SHADOW_RECORD & rd[0].flags)) + { + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + GNUNET_break(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Block was decrypted successfully with former shadow record \n"); + GNUNET_SCHEDULER_add_now(&end, NULL); } - if (TEST_RECORD_DATALEN != rd[0].data_size) - { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; - } - if (0 != memcmp (&rd_cmp_data, rd[0].data, TEST_RECORD_DATALEN)) - { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; - } - if (0 != (GNUNET_GNSRECORD_RF_SHADOW_RECORD & rd[0].flags)) - { - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - GNUNET_break (0); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Block was decrypted successfully with former shadow record \n"); - GNUNET_SCHEDULER_add_now (&end, NULL ); - } } static void -name_lookup_active_proc (void *cls, - const struct GNUNET_GNSRECORD_Block *block) +name_lookup_active_proc(void *cls, + const struct GNUNET_GNSRECORD_Block *block) { struct GNUNET_GNSRECORD_Data *expected_rd = cls; - GNUNET_assert (NULL != expected_rd); + + GNUNET_assert(NULL != expected_rd); ncqe = NULL; ncqe_shadow = NULL; if (endbadly_task != NULL) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } if (NULL == block) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore returned no block\n")); - if (endbadly_task != NULL) - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Namestore returned block, decrypting \n"); - GNUNET_assert (GNUNET_OK == GNUNET_GNSRECORD_block_decrypt(block, - &pubkey, TEST_NAME, &rd_decrypt_cb, expected_rd)); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore returned no block\n")); + if (endbadly_task != NULL) + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Namestore returned block, decrypting \n"); + GNUNET_assert(GNUNET_OK == GNUNET_GNSRECORD_block_decrypt(block, + &pubkey, TEST_NAME, &rd_decrypt_cb, expected_rd)); } static void -name_lookup_shadow (void *cls) +name_lookup_shadow(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Performing lookup for shadow record \n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Performing lookup for shadow record \n"); delayed_lookup_task = NULL; - ncqe_shadow = GNUNET_NAMECACHE_lookup_block (nch, &derived_hash, - &name_lookup_active_proc, &records[1]); + ncqe_shadow = GNUNET_NAMECACHE_lookup_block(nch, &derived_hash, + &name_lookup_active_proc, &records[1]); } static void -put_cont (void *cls, int32_t success, const char *emsg) +put_cont(void *cls, int32_t success, const char *emsg) { nsqe = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name store added record for `%s': %s\n", - TEST_NAME, - (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name store added record for `%s': %s\n", + TEST_NAME, + (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); /* Create derived hash */ - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, &pubkey); - GNUNET_GNSRECORD_query_from_public_key (&pubkey, TEST_NAME, &derived_hash); - - if (0 == GNUNET_TIME_absolute_get_remaining(record_expiration).rel_value_us ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Test to too long to store records, cannot run test!\n"); - GNUNET_SCHEDULER_add_now (&end, NULL ); - return; - } + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, &pubkey); + GNUNET_GNSRECORD_query_from_public_key(&pubkey, TEST_NAME, &derived_hash); + + if (0 == GNUNET_TIME_absolute_get_remaining(record_expiration).rel_value_us) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Test to too long to store records, cannot run test!\n"); + GNUNET_SCHEDULER_add_now(&end, NULL); + return; + } /* Lookup active record now */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Performing lookup for active record \n"); - ncqe = GNUNET_NAMECACHE_lookup_block (nch, &derived_hash, - &name_lookup_active_proc, &records[0]); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Performing lookup for active record \n"); + ncqe = GNUNET_NAMECACHE_lookup_block(nch, &derived_hash, + &name_lookup_active_proc, &records[0]); - delayed_lookup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply (EXPIRATION, 2), &name_lookup_shadow, NULL); + delayed_lookup_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(EXPIRATION, 2), &name_lookup_shadow, NULL); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, - NULL); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey != NULL); - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, - &pubkey); - - record_expiration = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), - EXPIRATION); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, + NULL); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey != NULL); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, + &pubkey); + + record_expiration = GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), + EXPIRATION); records[0].expiration_time = record_expiration.abs_value_us; records[0].record_type = TEST_RECORD_TYPE; records[0].data_size = TEST_RECORD_DATALEN; - records[0].data = GNUNET_malloc (TEST_RECORD_DATALEN); + records[0].data = GNUNET_malloc(TEST_RECORD_DATALEN); records[0].flags = GNUNET_GNSRECORD_RF_NONE; - memset ((char *) records[0].data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); + memset((char *)records[0].data, TEST_RECORD_DATA, TEST_RECORD_DATALEN); records[1].expiration_time = GNUNET_TIME_absolute_get().abs_value_us + 1000000000; records[1].record_type = TEST_RECORD_TYPE; records[1].data_size = TEST_RECORD_DATALEN; - records[1].data = GNUNET_malloc (TEST_RECORD_DATALEN); + records[1].data = GNUNET_malloc(TEST_RECORD_DATALEN); records[1].flags = GNUNET_GNSRECORD_RF_SHADOW_RECORD; - memset ((char *) records[1].data, TEST_SHADOW_RECORD_DATA, TEST_RECORD_DATALEN); - - nsh = GNUNET_NAMESTORE_connect (cfg); - nch = GNUNET_NAMECACHE_connect (cfg); - GNUNET_break (NULL != nsh); - GNUNET_break (NULL != nch); - nsqe = GNUNET_NAMESTORE_records_store (nsh, privkey, TEST_NAME, - 2, records, &put_cont, NULL); + memset((char *)records[1].data, TEST_SHADOW_RECORD_DATA, TEST_RECORD_DATALEN); + + nsh = GNUNET_NAMESTORE_connect(cfg); + nch = GNUNET_NAMECACHE_connect(cfg); + GNUNET_break(NULL != nsh); + GNUNET_break(NULL != nch); + nsqe = GNUNET_NAMESTORE_records_store(nsh, privkey, TEST_NAME, + 2, records, &put_cont, NULL); if (NULL == nsqe) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore cannot store no block\n")); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore cannot store no block\n")); + } - GNUNET_free ((void *) records[0].data); - GNUNET_free ((void *) records[1].data); + GNUNET_free((void *)records[0].data); + GNUNET_free((void *)records[1].data); } @@ -337,24 +338,24 @@ run (void *cls, int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-lookup-shadow-filter", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-lookup-shadow-filter", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_monitoring.c b/src/namestore/test_namestore_api_monitoring.c index 8fbeb6479..f1ee980cc 100644 --- a/src/namestore/test_namestore_api_monitoring.c +++ b/src/namestore/test_namestore_api_monitoring.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_monitoring.c * @brief testcase for zone monitoring functionality: monitor first, then add records @@ -31,7 +31,7 @@ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static struct GNUNET_NAMESTORE_Handle * nsh; @@ -62,63 +62,63 @@ struct GNUNET_NAMESTORE_QueueEntry * ns_ops[3]; static void -do_shutdown () +do_shutdown() { if (NULL != zm) - { - GNUNET_NAMESTORE_zone_monitor_stop (zm); - zm = NULL; - } + { + GNUNET_NAMESTORE_zone_monitor_stop(zm); + zm = NULL; + } if (NULL != ns_ops[0]) - { - GNUNET_NAMESTORE_cancel(ns_ops[0]); - ns_ops[0] = NULL; - } + { + GNUNET_NAMESTORE_cancel(ns_ops[0]); + ns_ops[0] = NULL; + } if (NULL != ns_ops[1]) - { - GNUNET_NAMESTORE_cancel(ns_ops[1]); - ns_ops[1] = NULL; - } + { + GNUNET_NAMESTORE_cancel(ns_ops[1]); + ns_ops[1] = NULL; + } if (NULL != ns_ops[2]) - { - GNUNET_NAMESTORE_cancel(ns_ops[2]); - ns_ops[2] = NULL; - } + { + GNUNET_NAMESTORE_cancel(ns_ops[2]); + ns_ops[2] = NULL; + } if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } GNUNET_free_non_null(s_name_1); GNUNET_free_non_null(s_name_2); GNUNET_free_non_null(s_name_3); if (s_rd_1 != NULL) - { - GNUNET_free ((void *)s_rd_1->data); - GNUNET_free (s_rd_1); - } + { + GNUNET_free((void *)s_rd_1->data); + GNUNET_free(s_rd_1); + } if (s_rd_2 != NULL) - { - GNUNET_free ((void *)s_rd_2->data); - GNUNET_free (s_rd_2); - } + { + GNUNET_free((void *)s_rd_2->data); + GNUNET_free(s_rd_2); + } if (s_rd_3 != NULL) - { - GNUNET_free ((void *)s_rd_3->data); - GNUNET_free (s_rd_3); - } + { + GNUNET_free((void *)s_rd_3->data); + GNUNET_free(s_rd_3); + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } + { + GNUNET_free(privkey); + privkey = NULL; + } if (NULL != privkey2) - { - GNUNET_free (privkey2); - privkey2 = NULL; - } + { + GNUNET_free(privkey2); + privkey2 = NULL; + } } @@ -128,218 +128,218 @@ do_shutdown () * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { - do_shutdown (); + do_shutdown(); res = 1; } static void -end (void *cls) +end(void *cls) { - do_shutdown (); + do_shutdown(); res = 0; } static void -zone_proc (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *name, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +zone_proc(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *name, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { static int returned_records; static int fail = GNUNET_NO; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Comparing results name %s\n", - name); - if (0 != GNUNET_memcmp (zone_key, - privkey)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Monitoring returned wrong zone key\n"); - GNUNET_break (0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } - - if (0 == strcmp (name, s_name_1)) - { - if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_1)) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Comparing results name %s\n", + name); + if (0 != GNUNET_memcmp(zone_key, + privkey)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Monitoring returned wrong zone key\n"); + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + + if (0 == strcmp(name, s_name_1)) { - GNUNET_break (0); - fail = GNUNET_YES; + if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_1)) + { + GNUNET_break(0); + fail = GNUNET_YES; + } } - } - else if (0 == strcmp (name, s_name_2)) - { - if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_2)) + else if (0 == strcmp(name, s_name_2)) { - GNUNET_break (0); - fail = GNUNET_YES; + if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_2)) + { + GNUNET_break(0); + fail = GNUNET_YES; + } } - } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Invalid name %s\n", - name); - GNUNET_break (0); - fail = GNUNET_YES; - } - GNUNET_NAMESTORE_zone_monitor_next (zm, - 1); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Invalid name %s\n", + name); + GNUNET_break(0); + fail = GNUNET_YES; + } + GNUNET_NAMESTORE_zone_monitor_next(zm, + 1); if (2 == ++returned_records) - { - if (endbadly_task != NULL) { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; + if (endbadly_task != NULL) + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } + if (GNUNET_YES == fail) + GNUNET_SCHEDULER_add_now(&endbadly, NULL); + else + GNUNET_SCHEDULER_add_now(&end, NULL); } - if (GNUNET_YES == fail) - GNUNET_SCHEDULER_add_now (&endbadly, NULL); - else - GNUNET_SCHEDULER_add_now (&end, NULL); - } } static void -put_cont (void *cls, - int32_t success, - const char *emsg) +put_cont(void *cls, + int32_t success, + const char *emsg) { static int c = 0; char *label = cls; - if (0 == strcmp (label, s_name_1)) + if (0 == strcmp(label, s_name_1)) ns_ops[0] = NULL; - else if (0 == strcmp (label, s_name_2)) + else if (0 == strcmp(label, s_name_2)) ns_ops[1] = NULL; - else if (0 == strcmp (label, s_name_3)) + else if (0 == strcmp(label, s_name_3)) ns_ops[2] = NULL; if (success == GNUNET_OK) - { - c++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record %u: `%s'\n", - c, - label); - } + { + c++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record %u: `%s'\n", + c, + label); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create record `%s'\n", - label); - GNUNET_break (0); - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, - NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create record `%s'\n", + label); + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, + NULL); + } } static struct GNUNET_GNSRECORD_Data * -create_record (unsigned int count) +create_record(unsigned int count) { struct GNUNET_GNSRECORD_Data *rd; - rd = GNUNET_new_array (count, - struct GNUNET_GNSRECORD_Data); + rd = GNUNET_new_array(count, + struct GNUNET_GNSRECORD_Data); for (unsigned int c = 0; c < count; c++) - { - rd[c].expiration_time = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS).abs_value_us; - rd[c].record_type = TEST_RECORD_TYPE; - rd[c].data_size = 50; - rd[c].data = GNUNET_malloc(50); - rd[c].flags = 0; - memset ((char *) rd[c].data, 'a', 50); - } + { + rd[c].expiration_time = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS).abs_value_us; + rd[c].record_type = TEST_RECORD_TYPE; + rd[c].data_size = 50; + rd[c].data = GNUNET_malloc(50); + rd[c].flags = 0; + memset((char *)rd[c].data, 'a', 50); + } return rd; } static void -fail_cb (void *cls) +fail_cb(void *cls) { - GNUNET_assert (0); + GNUNET_assert(0); } static void -sync_cb (void *cls) +sync_cb(void *cls) { /* do nothing */ } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { res = 1; - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey != NULL); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey != NULL); /* Start monitoring */ - zm = GNUNET_NAMESTORE_zone_monitor_start (cfg, - privkey, - GNUNET_YES, - &fail_cb, - NULL, - &zone_proc, - NULL, - &sync_cb, - NULL); + zm = GNUNET_NAMESTORE_zone_monitor_start(cfg, + privkey, + GNUNET_YES, + &fail_cb, + NULL, + &zone_proc, + NULL, + &sync_cb, + NULL); if (NULL == zm) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create zone monitor\n"); - GNUNET_break (0); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } - - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, &endbadly, NULL); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create zone monitor\n"); + GNUNET_break(0); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, &endbadly, NULL); /* Connect to namestore */ - nsh = GNUNET_NAMESTORE_connect (cfg); + nsh = GNUNET_NAMESTORE_connect(cfg); if (NULL == nsh) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connect to namestore\n"); - GNUNET_break (0); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Connect to namestore\n"); + GNUNET_break(0); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } - privkey2 = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey2 != NULL); + privkey2 = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey2 != NULL); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 3\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 3\n"); /* name in different zone */ GNUNET_asprintf(&s_name_3, "dummy3"); s_rd_3 = create_record(1); - GNUNET_assert (NULL != (ns_ops[2] = - GNUNET_NAMESTORE_records_store (nsh, - privkey2, - s_name_3, - 1, - s_rd_3, - &put_cont, - s_name_3))); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 1\n"); + GNUNET_assert(NULL != (ns_ops[2] = + GNUNET_NAMESTORE_records_store(nsh, + privkey2, + s_name_3, + 1, + s_rd_3, + &put_cont, + s_name_3))); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 1\n"); GNUNET_asprintf(&s_name_1, "dummy1"); s_rd_1 = create_record(1); - GNUNET_assert (NULL != (ns_ops[0] = - GNUNET_NAMESTORE_records_store (nsh, + GNUNET_assert(NULL != (ns_ops[0] = + GNUNET_NAMESTORE_records_store(nsh, privkey, s_name_1, 1, @@ -348,11 +348,11 @@ run (void *cls, s_name_1))); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Created record 2 \n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Created record 2 \n"); GNUNET_asprintf(&s_name_2, "dummy2"); s_rd_2 = create_record(1); - GNUNET_assert (NULL != (ns_ops[1] = - GNUNET_NAMESTORE_records_store (nsh, + GNUNET_assert(NULL != (ns_ops[1] = + GNUNET_NAMESTORE_records_store(nsh, privkey, s_name_2, 1, @@ -366,25 +366,25 @@ run (void *cls, int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-monitoring", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-monitoring", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_monitoring_existing.c b/src/namestore/test_namestore_api_monitoring_existing.c index e54046c85..97432b2a2 100644 --- a/src/namestore/test_namestore_api_monitoring_existing.c +++ b/src/namestore/test_namestore_api_monitoring_existing.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_monitoring_existing.c * @brief testcase for zone monitoring functionality: add records first, then monitor @@ -30,7 +30,7 @@ #define TEST_RECORD_TYPE GNUNET_DNSPARSER_TYPE_TXT -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) static const struct GNUNET_CONFIGURATION_Handle *cfg; @@ -67,311 +67,311 @@ struct GNUNET_NAMESTORE_QueueEntry * ns_ops[3]; * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { endbadly_task = NULL; - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); res = 1; } static void -end (void *cls) +end(void *cls) { if (NULL != zm) - { - GNUNET_NAMESTORE_zone_monitor_stop (zm); - zm = NULL; - } + { + GNUNET_NAMESTORE_zone_monitor_stop(zm); + zm = NULL; + } if (NULL != ns_ops[0]) - { - GNUNET_NAMESTORE_cancel(ns_ops[0]); - ns_ops[0] = NULL; - } + { + GNUNET_NAMESTORE_cancel(ns_ops[0]); + ns_ops[0] = NULL; + } if (NULL != ns_ops[1]) - { - GNUNET_NAMESTORE_cancel(ns_ops[1]); - ns_ops[1] = NULL; - } + { + GNUNET_NAMESTORE_cancel(ns_ops[1]); + ns_ops[1] = NULL; + } if (NULL != ns_ops[2]) - { - GNUNET_NAMESTORE_cancel(ns_ops[2]); - ns_ops[2] = NULL; - } + { + GNUNET_NAMESTORE_cancel(ns_ops[2]); + ns_ops[2] = NULL; + } if (NULL != endbadly_task) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } if (NULL != s_rd_1) - { - GNUNET_free ((void *)s_rd_1->data); - GNUNET_free (s_rd_1); - } + { + GNUNET_free((void *)s_rd_1->data); + GNUNET_free(s_rd_1); + } if (NULL != s_rd_2) - { - GNUNET_free ((void *)s_rd_2->data); - GNUNET_free (s_rd_2); - } + { + GNUNET_free((void *)s_rd_2->data); + GNUNET_free(s_rd_2); + } if (NULL != s_rd_3) - { - GNUNET_free ((void *)s_rd_3->data); - GNUNET_free (s_rd_3); - } + { + GNUNET_free((void *)s_rd_3->data); + GNUNET_free(s_rd_3); + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } + { + GNUNET_free(privkey); + privkey = NULL; + } if (NULL != privkey2) - { - GNUNET_free (privkey2); - privkey2 = NULL; - } + { + GNUNET_free(privkey2); + privkey2 = NULL; + } } static void -zone_proc (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *name, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +zone_proc(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *name, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { static int returned_records; static int fail = GNUNET_NO; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Comparing results name %s\n", - name); - if (0 != GNUNET_memcmp (zone_key, - privkey)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Monitoring returned wrong zone key\n"); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } - - if (0 == strcmp (name, - s_name_1)) - { - if (GNUNET_YES != - GNUNET_GNSRECORD_records_cmp (rd, - s_rd_1)) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Comparing results name %s\n", + name); + if (0 != GNUNET_memcmp(zone_key, + privkey)) { - GNUNET_break (0); - fail = GNUNET_YES; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Monitoring returned wrong zone key\n"); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; } - } - else if (0 == strcmp (name, - s_name_2)) - { - if (GNUNET_YES != - GNUNET_GNSRECORD_records_cmp (rd, - s_rd_2)) + + if (0 == strcmp(name, + s_name_1)) { - GNUNET_break (0); - fail = GNUNET_YES; + if (GNUNET_YES != + GNUNET_GNSRECORD_records_cmp(rd, + s_rd_1)) + { + GNUNET_break(0); + fail = GNUNET_YES; + } + } + else if (0 == strcmp(name, + s_name_2)) + { + if (GNUNET_YES != + GNUNET_GNSRECORD_records_cmp(rd, + s_rd_2)) + { + GNUNET_break(0); + fail = GNUNET_YES; + } } - } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Invalid name %s\n", - name); - GNUNET_break (0); - fail = GNUNET_YES; - } - GNUNET_NAMESTORE_zone_monitor_next (zm, - 1); - if (2 == ++returned_records) - { - GNUNET_SCHEDULER_shutdown (); - if (GNUNET_YES == fail) { - GNUNET_break (0); - res = 1; + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Invalid name %s\n", + name); + GNUNET_break(0); + fail = GNUNET_YES; } - else + GNUNET_NAMESTORE_zone_monitor_next(zm, + 1); + if (2 == ++returned_records) { - res = 0; + GNUNET_SCHEDULER_shutdown(); + if (GNUNET_YES == fail) + { + GNUNET_break(0); + res = 1; + } + else + { + res = 0; + } } - } } static void -fail_cb (void *cls) +fail_cb(void *cls) { - GNUNET_assert (0); + GNUNET_assert(0); } static void -sync_cb (void *cls) +sync_cb(void *cls) { /* do nothing */ } static void -put_cont (void *cls, - int32_t success, - const char *emsg) +put_cont(void *cls, + int32_t success, + const char *emsg) { static int c = 0; const char *label = cls; - if (0 == strcmp (label, - s_name_1)) + if (0 == strcmp(label, + s_name_1)) ns_ops[0] = NULL; - else if (0 == strcmp (label, - s_name_2)) + else if (0 == strcmp(label, + s_name_2)) ns_ops[1] = NULL; - else if (0 == strcmp (label, - s_name_3)) + else if (0 == strcmp(label, + s_name_3)) ns_ops[2] = NULL; if (success == GNUNET_OK) - { - c++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record %u: `%s'\n", - c, - label); - } + { + c++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record %u: `%s'\n", + c, + label); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to created records\n"); - GNUNET_break (0); - res = 1; - GNUNET_SCHEDULER_shutdown (); - return; - } - - if (3 == c) - { - /* Start monitoring */ - zm = GNUNET_NAMESTORE_zone_monitor_start (cfg, - privkey, - GNUNET_YES, - &fail_cb, - NULL, - &zone_proc, - NULL, - &sync_cb, - NULL); - if (NULL == zm) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create zone monitor\n"); - GNUNET_break (0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to created records\n"); + GNUNET_break(0); res = 1; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); return; } - } + + if (3 == c) + { + /* Start monitoring */ + zm = GNUNET_NAMESTORE_zone_monitor_start(cfg, + privkey, + GNUNET_YES, + &fail_cb, + NULL, + &zone_proc, + NULL, + &sync_cb, + NULL); + if (NULL == zm) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create zone monitor\n"); + GNUNET_break(0); + res = 1; + GNUNET_SCHEDULER_shutdown(); + return; + } + } } static struct GNUNET_GNSRECORD_Data * -create_record (unsigned int count) +create_record(unsigned int count) { struct GNUNET_GNSRECORD_Data *rd; - rd = GNUNET_new_array (count, - struct GNUNET_GNSRECORD_Data); + rd = GNUNET_new_array(count, + struct GNUNET_GNSRECORD_Data); for (unsigned int c = 0; c < count; c++) - { - rd[c].expiration_time = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS).abs_value_us; - rd[c].record_type = TEST_RECORD_TYPE; - rd[c].data_size = 50; - rd[c].data = GNUNET_malloc(50); - rd[c].flags = 0; - memset ((char *) rd[c].data, - 'a', - 50); - } + { + rd[c].expiration_time = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS).abs_value_us; + rd[c].record_type = TEST_RECORD_TYPE; + rd[c].data_size = 50; + rd[c].data = GNUNET_malloc(50); + rd[c].flags = 0; + memset((char *)rd[c].data, + 'a', + 50); + } return rd; } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *mycfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *mycfg, + struct GNUNET_TESTING_Peer *peer) { res = 1; - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (NULL != privkey); - privkey2 = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (NULL != privkey2); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(NULL != privkey); + privkey2 = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(NULL != privkey2); cfg = mycfg; - GNUNET_SCHEDULER_add_shutdown (&end, - NULL); - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, - NULL); + GNUNET_SCHEDULER_add_shutdown(&end, + NULL); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, + NULL); /* Connect to namestore */ - nsh = GNUNET_NAMESTORE_connect (cfg); + nsh = GNUNET_NAMESTORE_connect(cfg); if (NULL == nsh) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Connect to namestore failed\n"); - GNUNET_break (0); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, - NULL); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 3\n"); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Connect to namestore failed\n"); + GNUNET_break(0); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, + NULL); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 3\n"); /* name in different zone */ s_name_3 = "dummy3"; s_rd_3 = create_record(1); - GNUNET_assert (NULL != (ns_ops[2] = - GNUNET_NAMESTORE_records_store (nsh, + GNUNET_assert(NULL != (ns_ops[2] = + GNUNET_NAMESTORE_records_store(nsh, privkey2, s_name_3, 1, s_rd_3, &put_cont, - (void *) s_name_3))); + (void *)s_name_3))); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 1\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 1\n"); s_name_1 = "dummy1"; - s_rd_1 = create_record (1); - GNUNET_assert (NULL != (ns_ops[0] = - GNUNET_NAMESTORE_records_store (nsh, - privkey, - s_name_1, - 1, - s_rd_1, - &put_cont, - (void *) s_name_1))); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 2 \n"); + s_rd_1 = create_record(1); + GNUNET_assert(NULL != (ns_ops[0] = + GNUNET_NAMESTORE_records_store(nsh, + privkey, + s_name_1, + 1, + s_rd_1, + &put_cont, + (void *)s_name_1))); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 2 \n"); s_name_2 = "dummy2"; - s_rd_2 = create_record (1); - GNUNET_assert (NULL != (ns_ops[1] = - GNUNET_NAMESTORE_records_store (nsh, + s_rd_2 = create_record(1); + GNUNET_assert(NULL != (ns_ops[1] = + GNUNET_NAMESTORE_records_store(nsh, privkey, s_name_2, 1, s_rd_2, &put_cont, - (void *) s_name_2))); + (void *)s_name_2))); } @@ -379,26 +379,26 @@ run (void *cls, int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-monitoring-existing", - cfg_name, - &run, - NULL)) - { - GNUNET_break (0); - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-monitoring-existing", + cfg_name, + &run, + NULL)) + { + GNUNET_break(0); + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_remove.c b/src/namestore/test_namestore_api_remove.c index 4c3d55efc..b2334667e 100644 --- a/src/namestore/test_namestore_api_remove.c +++ b/src/namestore/test_namestore_api_remove.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api.c * @brief testcase for namestore_api.c to: remove record @@ -32,7 +32,7 @@ #define TEST_RECORD_DATA 'a' -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static struct GNUNET_NAMESTORE_Handle *nsh; @@ -51,19 +51,19 @@ static struct GNUNET_NAMESTORE_QueueEntry *nsqe; static void -cleanup () +cleanup() { if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_free(privkey); + privkey = NULL; + } + GNUNET_SCHEDULER_shutdown(); } @@ -73,127 +73,127 @@ cleanup () * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { if (NULL != nsqe) - { - GNUNET_NAMESTORE_cancel (nsqe); - nsqe = NULL; - } - cleanup (); + { + GNUNET_NAMESTORE_cancel(nsqe); + nsqe = NULL; + } + cleanup(); res = 1; } static void -end (void *cls) +end(void *cls) { - cleanup (); + cleanup(); res = 0; } static void -remove_cont (void *cls, - int32_t success, - const char *emsg) +remove_cont(void *cls, + int32_t success, + const char *emsg) { nsqe = NULL; if (GNUNET_YES != success) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Records could not be removed: `%s'\n"), - emsg); - if (NULL != endbadly_task) - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Records could not be removed: `%s'\n"), + emsg); + if (NULL != endbadly_task) + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Records were removed, perform lookup\n"); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Records were removed, perform lookup\n"); removed = GNUNET_YES; if (NULL != endbadly_task) - GNUNET_SCHEDULER_cancel (endbadly_task); - GNUNET_SCHEDULER_add_now (&end, NULL); + GNUNET_SCHEDULER_cancel(endbadly_task); + GNUNET_SCHEDULER_add_now(&end, NULL); } static void -put_cont (void *cls, - int32_t success, - const char *emsg) +put_cont(void *cls, + int32_t success, + const char *emsg) { const char *name = cls; - GNUNET_assert (NULL != cls); + GNUNET_assert(NULL != cls); nsqe = NULL; if (GNUNET_SYSERR == success) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Namestore could not store record: `%s'\n", - emsg); - if (endbadly_task != NULL) - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = GNUNET_SCHEDULER_add_now (&endbadly, NULL); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name store added record for `%s': %s\n", - name, - (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); - nsqe = GNUNET_NAMESTORE_records_store (nsh, - privkey, - name, - 0, NULL, - &remove_cont, (void *) name); + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Namestore could not store record: `%s'\n", + emsg); + if (endbadly_task != NULL) + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = GNUNET_SCHEDULER_add_now(&endbadly, NULL); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name store added record for `%s': %s\n", + name, + (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); + nsqe = GNUNET_NAMESTORE_records_store(nsh, + privkey, + name, + 0, NULL, + &remove_cont, (void *)name); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct GNUNET_GNSRECORD_Data rd; const char * name = "dummy.dummy.gnunet"; - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, - NULL); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey != NULL); - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, - &pubkey); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, + NULL); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey != NULL); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, + &pubkey); removed = GNUNET_NO; rd.expiration_time = GNUNET_TIME_absolute_get().abs_value_us; rd.record_type = TEST_RECORD_TYPE; rd.data_size = TEST_RECORD_DATALEN; - rd.data = GNUNET_malloc (TEST_RECORD_DATALEN); + rd.data = GNUNET_malloc(TEST_RECORD_DATALEN); rd.flags = 0; - memset ((char *) rd.data, - 'a', - TEST_RECORD_DATALEN); - - nsh = GNUNET_NAMESTORE_connect (cfg); - GNUNET_break (NULL != nsh); - nsqe = GNUNET_NAMESTORE_records_store (nsh, - privkey, - name, - 1, - &rd, - &put_cont, - (void *) name); + memset((char *)rd.data, + 'a', + TEST_RECORD_DATALEN); + + nsh = GNUNET_NAMESTORE_connect(cfg); + GNUNET_break(NULL != nsh); + nsqe = GNUNET_NAMESTORE_records_store(nsh, + privkey, + name, + 1, + &rd, + &put_cont, + (void *)name); if (NULL == nsqe) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore cannot store no block\n")); - } - GNUNET_free ((void *)rd.data); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore cannot store no block\n")); + } + GNUNET_free((void *)rd.data); } @@ -201,24 +201,24 @@ run (void *cls, int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-remove", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-remove", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_remove_not_existing_record.c b/src/namestore/test_namestore_api_remove_not_existing_record.c index c8110fe6b..fee06e3af 100644 --- a/src/namestore/test_namestore_api_remove_not_existing_record.c +++ b/src/namestore/test_namestore_api_remove_not_existing_record.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_remove_not_existing_record.c * @brief testcase for namestore_api.c @@ -31,7 +31,7 @@ #define TEST_RECORD_DATA 'a' -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static struct GNUNET_NAMESTORE_Handle *nsh; @@ -48,19 +48,19 @@ static struct GNUNET_NAMESTORE_QueueEntry *nsqe; static void -cleanup () +cleanup() { if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_free(privkey); + privkey = NULL; + } + GNUNET_SCHEDULER_shutdown(); } @@ -70,85 +70,87 @@ cleanup () * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { if (NULL != nsqe) - { - GNUNET_NAMESTORE_cancel (nsqe); - nsqe = NULL; - } - cleanup (); + { + GNUNET_NAMESTORE_cancel(nsqe); + nsqe = NULL; + } + cleanup(); res = 1; } static void -end (void *cls) +end(void *cls) { - cleanup (); + cleanup(); res = 0; } static void -put_cont (void *cls, - int32_t success, - const char *emsg) +put_cont(void *cls, + int32_t success, + const char *emsg) { - GNUNET_assert (NULL != cls); + GNUNET_assert(NULL != cls); nsqe = NULL; if (endbadly_task != NULL) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } switch (success) - { + { case GNUNET_NO: /* We expected GNUNET_NO, since record was not found */ - GNUNET_SCHEDULER_add_now (&end, NULL); + GNUNET_SCHEDULER_add_now(&end, NULL); break; + case GNUNET_OK: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Namestore could remove non-existing record: `%s'\n", - (NULL !=emsg) ? emsg : ""); - GNUNET_SCHEDULER_add_now (&endbadly, NULL); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Namestore could remove non-existing record: `%s'\n", + (NULL != emsg) ? emsg : ""); + GNUNET_SCHEDULER_add_now(&endbadly, NULL); break; + case GNUNET_SYSERR: default: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Namestore failed: `%s'\n", - (NULL !=emsg) ? emsg : ""); - GNUNET_SCHEDULER_add_now (&endbadly, NULL); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Namestore failed: `%s'\n", + (NULL != emsg) ? emsg : ""); + GNUNET_SCHEDULER_add_now(&endbadly, NULL); break; - } + } } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { const char * name = "dummy.dummy.gnunet"; - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, - NULL); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey != NULL); - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, &pubkey); - - nsh = GNUNET_NAMESTORE_connect (cfg); - GNUNET_break (NULL != nsh); - nsqe = GNUNET_NAMESTORE_records_store (nsh, privkey, name, - 0, NULL, - &put_cont, (void *) name); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, + NULL); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey != NULL); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, &pubkey); + + nsh = GNUNET_NAMESTORE_connect(cfg); + GNUNET_break(NULL != nsh); + nsqe = GNUNET_NAMESTORE_records_store(nsh, privkey, name, + 0, NULL, + &put_cont, (void *)name); if (NULL == nsqe) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore cannot store no block\n")); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore cannot store no block\n")); + } } @@ -156,24 +158,24 @@ run (void *cls, int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-remove-non-existing-record", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-remove-non-existing-record", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_store.c b/src/namestore/test_namestore_api_store.c index 0dbad8ce3..622227471 100644 --- a/src/namestore/test_namestore_api_store.c +++ b/src/namestore/test_namestore_api_store.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_store.c * @brief testcase for namestore_api.c: store a record @@ -32,7 +32,7 @@ #define TEST_RECORD_DATA 'a' -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static struct GNUNET_NAMESTORE_Handle *nsh; @@ -49,19 +49,19 @@ static struct GNUNET_NAMESTORE_QueueEntry *nsqe; static void -cleanup () +cleanup() { if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_free(privkey); + privkey = NULL; + } + GNUNET_SCHEDULER_shutdown(); } @@ -71,80 +71,80 @@ cleanup () * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { if (NULL != nsqe) - { - GNUNET_NAMESTORE_cancel (nsqe); - nsqe = NULL; - } - cleanup (); + { + GNUNET_NAMESTORE_cancel(nsqe); + nsqe = NULL; + } + cleanup(); res = 1; } static void -end (void *cls) +end(void *cls) { - cleanup (); + cleanup(); res = 0; } static void -put_cont (void *cls, int32_t success, const char *emsg) +put_cont(void *cls, int32_t success, const char *emsg) { const char *name = cls; nsqe = NULL; - GNUNET_assert (NULL != cls); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name store added record for `%s': %s\n", - name, - (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); - GNUNET_SCHEDULER_cancel (endbadly_task); + GNUNET_assert(NULL != cls); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name store added record for `%s': %s\n", + name, + (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); + GNUNET_SCHEDULER_cancel(endbadly_task); endbadly_task = NULL; - GNUNET_SCHEDULER_add_now (&end, NULL); + GNUNET_SCHEDULER_add_now(&end, NULL); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct GNUNET_GNSRECORD_Data rd; const char * name = "dummy.dummy.gnunet"; - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, NULL); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey != NULL); - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, &pubkey); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, NULL); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey != NULL); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, &pubkey); rd.expiration_time = GNUNET_TIME_absolute_get().abs_value_us; rd.record_type = TEST_RECORD_TYPE; rd.data_size = TEST_RECORD_DATALEN; - rd.data = GNUNET_malloc (TEST_RECORD_DATALEN); + rd.data = GNUNET_malloc(TEST_RECORD_DATALEN); rd.flags = 0; - memset ((char *) rd.data, 'a', TEST_RECORD_DATALEN); - - nsh = GNUNET_NAMESTORE_connect (cfg); - GNUNET_break (NULL != nsh); - nsqe = GNUNET_NAMESTORE_records_store (nsh, - privkey, - name, - 1, - &rd, - &put_cont, - (void *) name); + memset((char *)rd.data, 'a', TEST_RECORD_DATALEN); + + nsh = GNUNET_NAMESTORE_connect(cfg); + GNUNET_break(NULL != nsh); + nsqe = GNUNET_NAMESTORE_records_store(nsh, + privkey, + name, + 1, + &rd, + &put_cont, + (void *)name); if (NULL == nsqe) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore cannot store no block\n")); - } - GNUNET_free ((void *)rd.data); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore cannot store no block\n")); + } + GNUNET_free((void *)rd.data); } @@ -152,24 +152,24 @@ run (void *cls, int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_store_update.c b/src/namestore/test_namestore_api_store_update.c index b1c0770ae..5e9885b3e 100644 --- a/src/namestore/test_namestore_api_store_update.c +++ b/src/namestore/test_namestore_api_store_update.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_store_update.c * @brief testcase for namestore_api.c: store a record, update it and perform a lookup @@ -39,7 +39,7 @@ #define TEST_RECORD_DATA2 'b' -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static struct GNUNET_NAMESTORE_Handle *nsh; @@ -69,217 +69,217 @@ static const char *name = "dummy"; * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { - GNUNET_break (0); + GNUNET_break(0); endbadly_task = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); res = 1; } static void -end (void *cls) +end(void *cls) { if (NULL != endbadly_task) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } if (NULL != nsqe) - { - GNUNET_NAMESTORE_cancel (nsqe); - nsqe = NULL; - } + { + GNUNET_NAMESTORE_cancel(nsqe); + nsqe = NULL; + } if (NULL != ncqe) - { - GNUNET_NAMECACHE_cancel (ncqe); - ncqe = NULL; - } + { + GNUNET_NAMECACHE_cancel(ncqe); + ncqe = NULL; + } if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } if (NULL != nch) - { - GNUNET_NAMECACHE_disconnect (nch); - nch = NULL; - } + { + GNUNET_NAMECACHE_disconnect(nch); + nch = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } + { + GNUNET_free(privkey); + privkey = NULL; + } } static void -put_cont (void *cls, - int32_t success, - const char *emsg); +put_cont(void *cls, + int32_t success, + const char *emsg); static void -rd_decrypt_cb (void *cls, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +rd_decrypt_cb(void *cls, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct GNUNET_GNSRECORD_Data rd_new; - GNUNET_assert (1 == rd_count); - GNUNET_assert (NULL != rd); + GNUNET_assert(1 == rd_count); + GNUNET_assert(NULL != rd); if (GNUNET_NO == update_performed) - { - char rd_cmp_data[TEST_RECORD_DATALEN]; - - memset (rd_cmp_data, - TEST_RECORD_DATA, - TEST_RECORD_DATALEN); - GNUNET_assert (TEST_RECORD_TYPE == rd[0].record_type); - GNUNET_assert (TEST_RECORD_DATALEN == rd[0].data_size); - GNUNET_assert (0 == memcmp (&rd_cmp_data, + { + char rd_cmp_data[TEST_RECORD_DATALEN]; + + memset(rd_cmp_data, + TEST_RECORD_DATA, + TEST_RECORD_DATALEN); + GNUNET_assert(TEST_RECORD_TYPE == rd[0].record_type); + GNUNET_assert(TEST_RECORD_DATALEN == rd[0].data_size); + GNUNET_assert(0 == memcmp(&rd_cmp_data, rd[0].data, TEST_RECORD_DATALEN)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Block was decrypted successfully, updating record \n"); - - rd_new.flags = GNUNET_GNSRECORD_RF_NONE; - rd_new.expiration_time = GNUNET_TIME_absolute_get().abs_value_us + 1000000000; - rd_new.record_type = TEST_RECORD_TYPE; - rd_new.data_size = TEST_RECORD_DATALEN2; - rd_new.data = GNUNET_malloc (TEST_RECORD_DATALEN2); - memset ((char *) rd_new.data, - TEST_RECORD_DATA2, - TEST_RECORD_DATALEN2); - - nsqe = GNUNET_NAMESTORE_records_store (nsh, - privkey, - name, - 1, - &rd_new, - &put_cont, - (void *) name); - update_performed = GNUNET_YES; - } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Block was decrypted successfully, updating record \n"); + + rd_new.flags = GNUNET_GNSRECORD_RF_NONE; + rd_new.expiration_time = GNUNET_TIME_absolute_get().abs_value_us + 1000000000; + rd_new.record_type = TEST_RECORD_TYPE; + rd_new.data_size = TEST_RECORD_DATALEN2; + rd_new.data = GNUNET_malloc(TEST_RECORD_DATALEN2); + memset((char *)rd_new.data, + TEST_RECORD_DATA2, + TEST_RECORD_DATALEN2); + + nsqe = GNUNET_NAMESTORE_records_store(nsh, + privkey, + name, + 1, + &rd_new, + &put_cont, + (void *)name); + update_performed = GNUNET_YES; + } else - { - char rd_cmp_data[TEST_RECORD_DATALEN2]; - - memset (rd_cmp_data, - TEST_RECORD_DATA2, - TEST_RECORD_DATALEN2); - GNUNET_assert (TEST_RECORD_TYPE == rd[0].record_type); - GNUNET_assert (TEST_RECORD_DATALEN2 == rd[0].data_size); - GNUNET_assert (0 == memcmp (&rd_cmp_data, + { + char rd_cmp_data[TEST_RECORD_DATALEN2]; + + memset(rd_cmp_data, + TEST_RECORD_DATA2, + TEST_RECORD_DATALEN2); + GNUNET_assert(TEST_RECORD_TYPE == rd[0].record_type); + GNUNET_assert(TEST_RECORD_DATALEN2 == rd[0].data_size); + GNUNET_assert(0 == memcmp(&rd_cmp_data, rd[0].data, TEST_RECORD_DATALEN2)); - GNUNET_SCHEDULER_shutdown (); - res = 0; - } + GNUNET_SCHEDULER_shutdown(); + res = 0; + } } static void -name_lookup_proc (void *cls, - const struct GNUNET_GNSRECORD_Block *block) +name_lookup_proc(void *cls, + const struct GNUNET_GNSRECORD_Block *block) { const char *name = cls; ncqe = NULL; - GNUNET_assert (NULL != cls); + GNUNET_assert(NULL != cls); if (NULL == block) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namecache returned no block for `%s'\n"), - name); - GNUNET_SCHEDULER_shutdown (); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Namecache returned block, decrypting \n"); - GNUNET_assert (GNUNET_OK == - GNUNET_GNSRECORD_block_decrypt (block, - &pubkey, - name, - &rd_decrypt_cb, - (void *) name)); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namecache returned no block for `%s'\n"), + name); + GNUNET_SCHEDULER_shutdown(); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Namecache returned block, decrypting \n"); + GNUNET_assert(GNUNET_OK == + GNUNET_GNSRECORD_block_decrypt(block, + &pubkey, + name, + &rd_decrypt_cb, + (void *)name)); } static void -put_cont (void *cls, - int32_t success, - const char *emsg) +put_cont(void *cls, + int32_t success, + const char *emsg) { const char *name = cls; struct GNUNET_HashCode derived_hash; nsqe = NULL; - GNUNET_assert (NULL != cls); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name store added record for `%s': %s\n", - name, - (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); + GNUNET_assert(NULL != cls); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name store added record for `%s': %s\n", + name, + (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); /* Create derived hash */ - GNUNET_GNSRECORD_query_from_private_key (privkey, - name, - &derived_hash); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Looking in namecache for `%s'\n", - GNUNET_h2s (&derived_hash)); - ncqe = GNUNET_NAMECACHE_lookup_block (nch, - &derived_hash, - &name_lookup_proc, (void *) name); + GNUNET_GNSRECORD_query_from_private_key(privkey, + name, + &derived_hash); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Looking in namecache for `%s'\n", + GNUNET_h2s(&derived_hash)); + ncqe = GNUNET_NAMECACHE_lookup_block(nch, + &derived_hash, + &name_lookup_proc, (void *)name); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct GNUNET_GNSRECORD_Data rd; update_performed = GNUNET_NO; - GNUNET_SCHEDULER_add_shutdown (&end, - NULL); - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, - NULL); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey != NULL); - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, - &pubkey); + GNUNET_SCHEDULER_add_shutdown(&end, + NULL); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, + NULL); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey != NULL); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, + &pubkey); rd.flags = GNUNET_GNSRECORD_RF_NONE; rd.expiration_time = GNUNET_TIME_absolute_get().abs_value_us + 1000000000; rd.record_type = TEST_RECORD_TYPE; rd.data_size = TEST_RECORD_DATALEN; - rd.data = GNUNET_malloc (TEST_RECORD_DATALEN); - memset ((char *) rd.data, - TEST_RECORD_DATA, - TEST_RECORD_DATALEN); - - nsh = GNUNET_NAMESTORE_connect (cfg); - GNUNET_break (NULL != nsh); - nch = GNUNET_NAMECACHE_connect (cfg); - GNUNET_break (NULL != nch); - nsqe = GNUNET_NAMESTORE_records_store (nsh, - privkey, - name, - 1, - &rd, - &put_cont, - (void *) name); + rd.data = GNUNET_malloc(TEST_RECORD_DATALEN); + memset((char *)rd.data, + TEST_RECORD_DATA, + TEST_RECORD_DATALEN); + + nsh = GNUNET_NAMESTORE_connect(cfg); + GNUNET_break(NULL != nsh); + nch = GNUNET_NAMECACHE_connect(cfg); + GNUNET_break(NULL != nch); + nsqe = GNUNET_NAMESTORE_records_store(nsh, + privkey, + name, + 1, + &rd, + &put_cont, + (void *)name); if (NULL == nsqe) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore cannot store no block\n")); - } - GNUNET_free ((void *)rd.data); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore cannot store no block\n")); + } + GNUNET_free((void *)rd.data); } @@ -287,25 +287,25 @@ run (void *cls, int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-store-update", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-store-update", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_zone_iteration.c b/src/namestore/test_namestore_api_zone_iteration.c index 94331f89e..62686403a 100644 --- a/src/namestore/test_namestore_api_zone_iteration.c +++ b/src/namestore/test_namestore_api_zone_iteration.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_zone_iteration.c * @brief testcase for zone iteration functionality: iterate all zones @@ -30,7 +30,7 @@ #define TEST_RECORD_TYPE GNUNET_DNSPARSER_TYPE_TXT -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static struct GNUNET_NAMESTORE_Handle * nsh; @@ -67,268 +67,268 @@ static struct GNUNET_GNSRECORD_Data *s_rd_3; * @param tc scheduler context */ static void -endbadly (void *cls) +endbadly(void *cls) { endbadly_task = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); res = 1; } static void -end (void *cls) +end(void *cls) { if (NULL != zi) - { - GNUNET_NAMESTORE_zone_iteration_stop (zi); - zi = NULL; - } + { + GNUNET_NAMESTORE_zone_iteration_stop(zi); + zi = NULL; + } if (NULL != endbadly_task) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } + { + GNUNET_free(privkey); + privkey = NULL; + } if (NULL != privkey2) - { - GNUNET_free (privkey2); - privkey2 = NULL; - } - GNUNET_free_non_null (s_name_1); - GNUNET_free_non_null (s_name_2); - GNUNET_free_non_null (s_name_3); + { + GNUNET_free(privkey2); + privkey2 = NULL; + } + GNUNET_free_non_null(s_name_1); + GNUNET_free_non_null(s_name_2); + GNUNET_free_non_null(s_name_3); if (NULL != s_rd_1) - { - GNUNET_free ((void *)s_rd_1->data); - GNUNET_free (s_rd_1); - } + { + GNUNET_free((void *)s_rd_1->data); + GNUNET_free(s_rd_1); + } if (NULL != s_rd_2) - { - GNUNET_free ((void *)s_rd_2->data); - GNUNET_free (s_rd_2); - } + { + GNUNET_free((void *)s_rd_2->data); + GNUNET_free(s_rd_2); + } if (NULL != s_rd_3) - { - GNUNET_free ((void *)s_rd_3->data); - GNUNET_free (s_rd_3); - } + { + GNUNET_free((void *)s_rd_3->data); + GNUNET_free(s_rd_3); + } if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } } static void -zone_end (void *cls) +zone_end(void *cls) { - GNUNET_break (3 == returned_records); + GNUNET_break(3 == returned_records); if (3 == returned_records) - { - res = 0; /* Last iteraterator callback, we are done */ - zi = NULL; - } + { + res = 0; /* Last iteraterator callback, we are done */ + zi = NULL; + } else res = 1; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received last result, iteration done after receing %u results\n", - returned_records); - GNUNET_SCHEDULER_shutdown (); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received last result, iteration done after receing %u results\n", + returned_records); + GNUNET_SCHEDULER_shutdown(); } static void -fail_cb (void *cls) +fail_cb(void *cls) { - GNUNET_assert (0); + GNUNET_assert(0); } static void -zone_proc (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +zone_proc(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { int failed = GNUNET_NO; - GNUNET_assert (NULL != zone); - if (0 == GNUNET_memcmp (zone, - privkey)) - { - if (0 == strcmp (label, s_name_1)) + GNUNET_assert(NULL != zone); + if (0 == GNUNET_memcmp(zone, + privkey)) { - if (rd_count == 1) - { - if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_1)) + if (0 == strcmp(label, s_name_1)) { - failed = GNUNET_YES; - GNUNET_break (0); + if (rd_count == 1) + { + if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_1)) + { + failed = GNUNET_YES; + GNUNET_break(0); + } + } + else + { + failed = GNUNET_YES; + GNUNET_break(0); + } + } + else if (0 == strcmp(label, s_name_2)) + { + if (rd_count == 1) + { + if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_2)) + { + failed = GNUNET_YES; + GNUNET_break(0); + } + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Received invalid record count\n"); + failed = GNUNET_YES; + GNUNET_break(0); + } } - } else - { - failed = GNUNET_YES; - GNUNET_break (0); - } - } - else if (0 == strcmp (label, s_name_2)) - { - if (rd_count == 1) - { - if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_2)) { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Comparing result failed: got name `%s' for first zone\n", + label); failed = GNUNET_YES; - GNUNET_break (0); + GNUNET_break(0); } - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Received invalid record count\n"); - failed = GNUNET_YES; - GNUNET_break (0); - } } - else + else if (0 == GNUNET_memcmp(zone, + privkey2)) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Comparing result failed: got name `%s' for first zone\n", - label); - failed = GNUNET_YES; - GNUNET_break (0); - } - } - else if (0 == GNUNET_memcmp (zone, - privkey2)) - { - if (0 == strcmp (label, s_name_3)) - { - if (rd_count == 1) - { - if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_3)) + if (0 == strcmp(label, s_name_3)) { - failed = GNUNET_YES; - GNUNET_break (0); + if (rd_count == 1) + { + if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_3)) + { + failed = GNUNET_YES; + GNUNET_break(0); + } + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Received invalid record count\n"); + failed = GNUNET_YES; + GNUNET_break(0); + } } - } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Received invalid record count\n"); - failed = GNUNET_YES; - GNUNET_break (0); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Comparing result failed: got name `%s' for first zone\n", + label); + failed = GNUNET_YES; + GNUNET_break(0); + } } - else + else { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Comparing result failed: got name `%s' for first zone\n", - label); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Received invalid zone\n"); failed = GNUNET_YES; - GNUNET_break (0); + GNUNET_break(0); } - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Received invalid zone\n"); - failed = GNUNET_YES; - GNUNET_break (0); - } if (failed == GNUNET_NO) - { - returned_records ++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Telling namestore to send the next result\n"); - GNUNET_NAMESTORE_zone_iterator_next (zi, - 1); - } + { + returned_records++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Telling namestore to send the next result\n"); + GNUNET_NAMESTORE_zone_iterator_next(zi, + 1); + } else - { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - res = 1; - } + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + res = 1; + } } static void -put_cont (void *cls, - int32_t success, - const char *emsg) +put_cont(void *cls, + int32_t success, + const char *emsg) { static int c = 0; if (success == GNUNET_OK) - { - c++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record %u \n", - c); - } + { + c++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record %u \n", + c); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to created records: `%s'\n", - emsg); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - res = 1; - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to created records: `%s'\n", + emsg); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + res = 1; + return; + } if (c == 3) - { - res = 1; - returned_records = 0; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "All records created, starting iteration over all zones \n"); - zi = GNUNET_NAMESTORE_zone_iteration_start (nsh, - NULL, - &fail_cb, - NULL, - &zone_proc, - NULL, - &zone_end, - NULL); - if (zi == NULL) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create zone iterator\n"); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); res = 1; - return; + returned_records = 0; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "All records created, starting iteration over all zones \n"); + zi = GNUNET_NAMESTORE_zone_iteration_start(nsh, + NULL, + &fail_cb, + NULL, + &zone_proc, + NULL, + &zone_end, + NULL); + if (zi == NULL) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create zone iterator\n"); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + res = 1; + return; + } } - } } static struct GNUNET_GNSRECORD_Data * -create_record (unsigned int count) +create_record(unsigned int count) { struct GNUNET_GNSRECORD_Data * rd; - rd = GNUNET_new_array (count, - struct GNUNET_GNSRECORD_Data); + rd = GNUNET_new_array(count, + struct GNUNET_GNSRECORD_Data); for (unsigned int c = 0; c < count; c++) - { - rd[c].expiration_time = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS).abs_value_us; - rd[c].record_type = TEST_RECORD_TYPE; - rd[c].data_size = 50; - rd[c].data = GNUNET_malloc(50); - rd[c].flags = 0; - memset ((char *) rd[c].data, 'a', 50); - } + { + rd[c].expiration_time = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS).abs_value_us; + rd[c].record_type = TEST_RECORD_TYPE; + rd[c].data_size = 50; + rd[c].data = GNUNET_malloc(50); + rd[c].flags = 0; + memset((char *)rd[c].data, 'a', 50); + } return rd; } @@ -339,128 +339,128 @@ create_record (unsigned int count) * start the actual tests by filling the zone. */ static void -empty_zone_proc (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +empty_zone_proc(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { - GNUNET_assert (nsh == cls); + GNUNET_assert(nsh == cls); if (NULL != zone) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Expected empty zone but received zone private key\n")); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - res = 1; - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Expected empty zone but received zone private key\n")); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + res = 1; + return; + } if ((NULL != label) || (NULL != rd) || (0 != rd_count)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Expected no zone content but received data\n")); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - res = 1; - return; - } - GNUNET_assert (0); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Expected no zone content but received data\n")); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + res = 1; + return; + } + GNUNET_assert(0); } static void -empty_zone_end (void *cls) +empty_zone_end(void *cls) { char *hostkey_file; zi = NULL; - GNUNET_asprintf (&hostkey_file, - "zonefiles%s%s", - DIR_SEPARATOR_STR, - "N0UJMP015AFUNR2BTNM3FKPBLG38913BL8IDMCO2H0A1LIB81960.zkey"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Using zonekey file `%s' \n", - hostkey_file); + GNUNET_asprintf(&hostkey_file, + "zonefiles%s%s", + DIR_SEPARATOR_STR, + "N0UJMP015AFUNR2BTNM3FKPBLG38913BL8IDMCO2H0A1LIB81960.zkey"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Using zonekey file `%s' \n", + hostkey_file); privkey = GNUNET_CRYPTO_ecdsa_key_create_from_file(hostkey_file); - GNUNET_free (hostkey_file); - GNUNET_assert (privkey != NULL); - - GNUNET_asprintf (&hostkey_file, - "zonefiles%s%s", - DIR_SEPARATOR_STR, - "HGU0A0VCU334DN7F2I9UIUMVQMM7JMSD142LIMNUGTTV9R0CF4EG.zkey"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Using zonekey file `%s' \n", - hostkey_file); + GNUNET_free(hostkey_file); + GNUNET_assert(privkey != NULL); + + GNUNET_asprintf(&hostkey_file, + "zonefiles%s%s", + DIR_SEPARATOR_STR, + "HGU0A0VCU334DN7F2I9UIUMVQMM7JMSD142LIMNUGTTV9R0CF4EG.zkey"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Using zonekey file `%s' \n", + hostkey_file); privkey2 = GNUNET_CRYPTO_ecdsa_key_create_from_file(hostkey_file); - GNUNET_free (hostkey_file); - GNUNET_assert (privkey2 != NULL); + GNUNET_free(hostkey_file); + GNUNET_assert(privkey2 != NULL); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Created record 1\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Created record 1\n"); GNUNET_asprintf(&s_name_1, "dummy1"); s_rd_1 = create_record(1); - GNUNET_NAMESTORE_records_store (nsh, - privkey, - s_name_1, - 1, s_rd_1, - &put_cont, - NULL); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 2 \n"); + GNUNET_NAMESTORE_records_store(nsh, + privkey, + s_name_1, + 1, s_rd_1, + &put_cont, + NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 2 \n"); GNUNET_asprintf(&s_name_2, "dummy2"); s_rd_2 = create_record(1); - GNUNET_NAMESTORE_records_store (nsh, - privkey, - s_name_2, - 1, s_rd_2, - &put_cont, - NULL); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 3\n"); + GNUNET_NAMESTORE_records_store(nsh, + privkey, + s_name_2, + 1, s_rd_2, + &put_cont, + NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 3\n"); /* name in different zone */ GNUNET_asprintf(&s_name_3, "dummy3"); s_rd_3 = create_record(1); - GNUNET_NAMESTORE_records_store (nsh, - privkey2, - s_name_3, - 1, - s_rd_3, - &put_cont, - NULL); + GNUNET_NAMESTORE_records_store(nsh, + privkey2, + s_name_3, + 1, + s_rd_3, + &put_cont, + NULL); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, - NULL); - GNUNET_SCHEDULER_add_shutdown (&end, - NULL); - - nsh = GNUNET_NAMESTORE_connect (cfg); - GNUNET_break (NULL != nsh); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, + NULL); + GNUNET_SCHEDULER_add_shutdown(&end, + NULL); + + nsh = GNUNET_NAMESTORE_connect(cfg); + GNUNET_break(NULL != nsh); /* first, iterate over empty namestore */ - zi = GNUNET_NAMESTORE_zone_iteration_start (nsh, - NULL, - &fail_cb, - NULL, - &empty_zone_proc, - nsh, - &empty_zone_end, - NULL); + zi = GNUNET_NAMESTORE_zone_iteration_start(nsh, + NULL, + &fail_cb, + NULL, + &empty_zone_proc, + nsh, + &empty_zone_end, + NULL); if (NULL == zi) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create zone iterator\n"); - GNUNET_break (0); - res = 1; - GNUNET_SCHEDULER_shutdown (); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create zone iterator\n"); + GNUNET_break(0); + res = 1; + GNUNET_SCHEDULER_shutdown(); + } } @@ -468,24 +468,24 @@ run (void *cls, int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-zone-iteration", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-zone-iteration", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_zone_iteration_nick.c b/src/namestore/test_namestore_api_zone_iteration_nick.c index 069c6d831..739e71c05 100644 --- a/src/namestore/test_namestore_api_zone_iteration_nick.c +++ b/src/namestore/test_namestore_api_zone_iteration_nick.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_zone_iteration.c * @brief testcase for zone iteration functionality: iterate all zones @@ -32,7 +32,7 @@ #define ZONE_NICK_1 "nick1" #define ZONE_NICK_2 "nick2" -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static struct GNUNET_NAMESTORE_Handle * nsh; @@ -69,266 +69,266 @@ static struct GNUNET_NAMESTORE_QueueEntry *nsqe; * @param tc scheduler context */ static void -end (void *cls) +end(void *cls) { if (NULL != zi) - { - GNUNET_NAMESTORE_zone_iteration_stop (zi); - zi = NULL; - } + { + GNUNET_NAMESTORE_zone_iteration_stop(zi); + zi = NULL; + } if (nsh != NULL) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } - GNUNET_free_non_null (s_name_1); - GNUNET_free_non_null (s_name_2); - GNUNET_free_non_null (s_name_3); + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } + GNUNET_free_non_null(s_name_1); + GNUNET_free_non_null(s_name_2); + GNUNET_free_non_null(s_name_3); if (s_rd_1 != NULL) - { - GNUNET_free ((void *)s_rd_1->data); - GNUNET_free (s_rd_1); - } + { + GNUNET_free((void *)s_rd_1->data); + GNUNET_free(s_rd_1); + } if (s_rd_2 != NULL) - { - GNUNET_free ((void *)s_rd_2->data); - GNUNET_free (s_rd_2); - } + { + GNUNET_free((void *)s_rd_2->data); + GNUNET_free(s_rd_2); + } if (s_rd_3 != NULL) - { - GNUNET_free ((void *)s_rd_3->data); - GNUNET_free (s_rd_3); - } + { + GNUNET_free((void *)s_rd_3->data); + GNUNET_free(s_rd_3); + } if (privkey != NULL) - { - GNUNET_free (privkey); - privkey = NULL; - } + { + GNUNET_free(privkey); + privkey = NULL; + } if (privkey2 != NULL) - { - GNUNET_free (privkey2); - privkey2 = NULL; - } + { + GNUNET_free(privkey2); + privkey2 = NULL; + } } static int -check_zone_1 (const char *label, unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +check_zone_1(const char *label, unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { - for (unsigned int c = 0; c< rd_count ; c++) - { - if ( (rd[c].record_type == GNUNET_GNSRECORD_TYPE_NICK) && - (0 != strcmp (rd[c].data, ZONE_NICK_1)) ) + for (unsigned int c = 0; c < rd_count; c++) { - GNUNET_break (0); - return GNUNET_YES; + if ((rd[c].record_type == GNUNET_GNSRECORD_TYPE_NICK) && + (0 != strcmp(rd[c].data, ZONE_NICK_1))) + { + GNUNET_break(0); + return GNUNET_YES; + } } - } return GNUNET_NO; } static int -check_zone_2 (const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +check_zone_2(const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { - for (unsigned int c = 0; c< rd_count ; c++) - { - if ( (rd[c].record_type == GNUNET_GNSRECORD_TYPE_NICK) && - (0 != strcmp (rd[c].data, ZONE_NICK_2)) ) + for (unsigned int c = 0; c < rd_count; c++) { - GNUNET_break (0); - return GNUNET_YES; + if ((rd[c].record_type == GNUNET_GNSRECORD_TYPE_NICK) && + (0 != strcmp(rd[c].data, ZONE_NICK_2))) + { + GNUNET_break(0); + return GNUNET_YES; + } } - } return GNUNET_NO; } static void -zone_proc_end (void *cls) +zone_proc_end(void *cls) { zi = NULL; res = 0; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received last result, iteration done after receing %u results\n", - returned_records); - GNUNET_SCHEDULER_shutdown (); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received last result, iteration done after receing %u results\n", + returned_records); + GNUNET_SCHEDULER_shutdown(); } static void -zone_proc (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +zone_proc(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { int failed = GNUNET_NO; - GNUNET_assert (NULL != zone); - if (0 == GNUNET_memcmp (zone, privkey)) - { - failed = check_zone_1 (label, rd_count, rd); - if (GNUNET_YES == failed) - GNUNET_break (0); - } - else if (0 == GNUNET_memcmp (zone, privkey2)) - { - failed = check_zone_2 (label, rd_count, rd); - if (GNUNET_YES == failed) - GNUNET_break (0); - } + GNUNET_assert(NULL != zone); + if (0 == GNUNET_memcmp(zone, privkey)) + { + failed = check_zone_1(label, rd_count, rd); + if (GNUNET_YES == failed) + GNUNET_break(0); + } + else if (0 == GNUNET_memcmp(zone, privkey2)) + { + failed = check_zone_2(label, rd_count, rd); + if (GNUNET_YES == failed) + GNUNET_break(0); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Received invalid zone\n"); - failed = GNUNET_YES; - GNUNET_break (0); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Received invalid zone\n"); + failed = GNUNET_YES; + GNUNET_break(0); + } if (failed == GNUNET_NO) - { - returned_records ++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Telling namestore to send the next result\n"); - GNUNET_NAMESTORE_zone_iterator_next (zi, - 1); - } + { + returned_records++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Telling namestore to send the next result\n"); + GNUNET_NAMESTORE_zone_iterator_next(zi, + 1); + } else - { - GNUNET_break (0); - res = 1; - GNUNET_SCHEDULER_shutdown (); - } + { + GNUNET_break(0); + res = 1; + GNUNET_SCHEDULER_shutdown(); + } } static void -fail_cb (void *cls) +fail_cb(void *cls) { - GNUNET_assert (0); + GNUNET_assert(0); } static void -put_cont (void *cls, - int32_t success, - const char *emsg) +put_cont(void *cls, + int32_t success, + const char *emsg) { static int c = 0; if (success == GNUNET_OK) - { - c++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Created record %u \n", c); - } + { + c++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Created record %u \n", c); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to created records: `%s'\n", - emsg); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Failed to created records: `%s'\n", + emsg); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } if (c == 3) - { - res = 1; - returned_records = 0; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "All records created, starting iteration over all zones \n"); - zi = GNUNET_NAMESTORE_zone_iteration_start (nsh, - NULL, - &fail_cb, - NULL, - &zone_proc, - NULL, - &zone_proc_end, - NULL); - if (zi == NULL) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to create zone iterator\n"); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; + res = 1; + returned_records = 0; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "All records created, starting iteration over all zones \n"); + zi = GNUNET_NAMESTORE_zone_iteration_start(nsh, + NULL, + &fail_cb, + NULL, + &zone_proc, + NULL, + &zone_proc_end, + NULL); + if (zi == NULL) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Failed to create zone iterator\n"); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } } - } } static struct GNUNET_GNSRECORD_Data * -create_record (unsigned int count) +create_record(unsigned int count) { struct GNUNET_GNSRECORD_Data * rd; - rd = GNUNET_new_array (count, - struct GNUNET_GNSRECORD_Data); + rd = GNUNET_new_array(count, + struct GNUNET_GNSRECORD_Data); for (unsigned int c = 0; c < count; c++) - { - rd[c].expiration_time = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS).abs_value_us; - rd[c].record_type = TEST_RECORD_TYPE; - rd[c].data_size = 50; - rd[c].data = GNUNET_malloc(50); - rd[c].flags = 0; - memset ((char *) rd[c].data, 'a', 50); - } + { + rd[c].expiration_time = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS).abs_value_us; + rd[c].record_type = TEST_RECORD_TYPE; + rd[c].data_size = 50; + rd[c].data = GNUNET_malloc(50); + rd[c].flags = 0; + memset((char *)rd[c].data, 'a', 50); + } return rd; } static void -nick_2_cont (void *cls, - int32_t success, - const char *emsg) +nick_2_cont(void *cls, + int32_t success, + const char *emsg) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Nick added : %s\n", - (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Nick added : %s\n", + (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Created record 1\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Created record 1\n"); GNUNET_asprintf(&s_name_1, "dummy1"); s_rd_1 = create_record(1); - GNUNET_NAMESTORE_records_store (nsh, privkey, s_name_1, - 1, s_rd_1, - &put_cont, NULL); + GNUNET_NAMESTORE_records_store(nsh, privkey, s_name_1, + 1, s_rd_1, + &put_cont, NULL); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 2 \n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 2 \n"); GNUNET_asprintf(&s_name_2, "dummy2"); s_rd_2 = create_record(1); - GNUNET_NAMESTORE_records_store (nsh, privkey, s_name_2, - 1, s_rd_2, &put_cont, NULL); + GNUNET_NAMESTORE_records_store(nsh, privkey, s_name_2, + 1, s_rd_2, &put_cont, NULL); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 3\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 3\n"); /* name in different zone */ GNUNET_asprintf(&s_name_3, "dummy3"); s_rd_3 = create_record(1); - GNUNET_NAMESTORE_records_store (nsh, privkey2, s_name_3, - 1, s_rd_3, - &put_cont, NULL); + GNUNET_NAMESTORE_records_store(nsh, privkey2, s_name_3, + 1, s_rd_3, + &put_cont, NULL); } static void -nick_1_cont (void *cls, int32_t success, const char *emsg) +nick_1_cont(void *cls, int32_t success, const char *emsg) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Nick 1 added : %s\n", - (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Nick 1 added : %s\n", + (success == GNUNET_OK) ? "SUCCESS" : "FAIL"); - nsqe = GNUNET_NAMESTORE_set_nick (nsh, privkey2, ZONE_NICK_2, &nick_2_cont, &privkey2); + nsqe = GNUNET_NAMESTORE_set_nick(nsh, privkey2, ZONE_NICK_2, &nick_2_cont, &privkey2); if (NULL == nsqe) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore cannot store no block\n")); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore cannot store no block\n")); + } } @@ -338,70 +338,69 @@ nick_1_cont (void *cls, int32_t success, const char *emsg) * start the actual tests by filling the zone. */ static void -empty_zone_proc (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +empty_zone_proc(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { - GNUNET_assert (nsh == cls); + GNUNET_assert(nsh == cls); if (NULL != zone) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Expected empty zone but received zone private key\n")); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Expected empty zone but received zone private key\n")); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } if ((NULL != label) || (NULL != rd) || (0 != rd_count)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Expected no zone content but received data\n")); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_assert (0); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Expected no zone content but received data\n")); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_assert(0); } static void -empty_zone_end (void *cls) +empty_zone_end(void *cls) { - GNUNET_assert (nsh == cls); + GNUNET_assert(nsh == cls); zi = NULL; - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey != NULL); - privkey2 = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey2 != NULL); - - nsqe = GNUNET_NAMESTORE_set_nick (nsh, - privkey, - ZONE_NICK_1, - &nick_1_cont, - &privkey); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey != NULL); + privkey2 = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey2 != NULL); + + nsqe = GNUNET_NAMESTORE_set_nick(nsh, + privkey, + ZONE_NICK_1, + &nick_1_cont, + &privkey); if (NULL == nsqe) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Namestore cannot store no block\n")); - } - + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Namestore cannot store no block\n")); + } } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - nsh = GNUNET_NAMESTORE_connect (cfg); - GNUNET_break (NULL != nsh); - GNUNET_SCHEDULER_add_shutdown (&end, - NULL); + nsh = GNUNET_NAMESTORE_connect(cfg); + GNUNET_break(NULL != nsh); + GNUNET_SCHEDULER_add_shutdown(&end, + NULL); /* first, iterate over empty namestore */ zi = GNUNET_NAMESTORE_zone_iteration_start(nsh, - NULL, + NULL, &fail_cb, NULL, &empty_zone_proc, @@ -409,12 +408,12 @@ run (void *cls, &empty_zone_end, nsh); if (NULL == zi) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create zone iterator\n"); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create zone iterator\n"); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + } } @@ -422,24 +421,24 @@ run (void *cls, int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-zone-iteration-nick", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-zone-iteration-nick", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_zone_iteration_specific_zone.c b/src/namestore/test_namestore_api_zone_iteration_specific_zone.c index e3c6d698a..924e1eb1e 100644 --- a/src/namestore/test_namestore_api_zone_iteration_specific_zone.c +++ b/src/namestore/test_namestore_api_zone_iteration_specific_zone.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_zone_iteration_specific_zone.c * @brief testcase for zone iteration functionality: iterate over a specific zone @@ -31,7 +31,7 @@ #define TEST_RECORD_TYPE GNUNET_DNSPARSER_TYPE_TXT -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static struct GNUNET_NAMESTORE_Handle * nsh; @@ -67,246 +67,246 @@ static struct GNUNET_GNSRECORD_Data *s_rd_3; * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { endbadly_task = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); res = 1; } static void -end (void *cls) +end(void *cls) { if (NULL != zi) - { - GNUNET_NAMESTORE_zone_iteration_stop (zi); - zi = NULL; - } + { + GNUNET_NAMESTORE_zone_iteration_stop(zi); + zi = NULL; + } if (NULL != endbadly_task) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } + { + GNUNET_free(privkey); + privkey = NULL; + } if (NULL != privkey2) - { - GNUNET_free (privkey2); - privkey2 = NULL; - } - GNUNET_free_non_null (s_name_1); - GNUNET_free_non_null (s_name_2); - GNUNET_free_non_null (s_name_3); + { + GNUNET_free(privkey2); + privkey2 = NULL; + } + GNUNET_free_non_null(s_name_1); + GNUNET_free_non_null(s_name_2); + GNUNET_free_non_null(s_name_3); if (s_rd_1 != NULL) - { - GNUNET_free ((void *)s_rd_1->data); - GNUNET_free (s_rd_1); - } + { + GNUNET_free((void *)s_rd_1->data); + GNUNET_free(s_rd_1); + } if (s_rd_2 != NULL) - { - GNUNET_free ((void *)s_rd_2->data); - GNUNET_free (s_rd_2); - } + { + GNUNET_free((void *)s_rd_2->data); + GNUNET_free(s_rd_2); + } if (s_rd_3 != NULL) - { - GNUNET_free ((void *)s_rd_3->data); - GNUNET_free (s_rd_3); - } + { + GNUNET_free((void *)s_rd_3->data); + GNUNET_free(s_rd_3); + } if (nsh != NULL) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } } static void -fail_cb (void *cls) +fail_cb(void *cls) { - GNUNET_assert (0); + GNUNET_assert(0); zi = NULL; } static void -zone_proc (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +zone_proc(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { int failed = GNUNET_NO; - GNUNET_assert (NULL != zone); - if (0 == GNUNET_memcmp (zone, - privkey)) - { - if (0 == strcmp (label, s_name_1)) + GNUNET_assert(NULL != zone); + if (0 == GNUNET_memcmp(zone, + privkey)) { - if (rd_count == 1) - { - if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp (rd, s_rd_1)) + if (0 == strcmp(label, s_name_1)) { - failed = GNUNET_YES; - GNUNET_break (0); + if (rd_count == 1) + { + if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_1)) + { + failed = GNUNET_YES; + GNUNET_break(0); + } + } + else + { + failed = GNUNET_YES; + GNUNET_break(0); + } + } + else if (0 == strcmp(label, s_name_2)) + { + if (rd_count == 1) + { + if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_2)) + { + failed = GNUNET_YES; + GNUNET_break(0); + } + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Received invalid record count\n"); + failed = GNUNET_YES; + GNUNET_break(0); + } } - } else - { - failed = GNUNET_YES; - GNUNET_break (0); - } - } - else if (0 == strcmp (label, s_name_2)) - { - if (rd_count == 1) - { - if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_2)) { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Comparing result failed: got name `%s' for first zone\n", + label); failed = GNUNET_YES; - GNUNET_break (0); + GNUNET_break(0); } - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Received invalid record count\n"); - failed = GNUNET_YES; - GNUNET_break (0); - } } - else + else if (0 == GNUNET_memcmp(zone, privkey2)) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Comparing result failed: got name `%s' for first zone\n", - label); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Received data for not requested zone\n"); failed = GNUNET_YES; - GNUNET_break (0); + GNUNET_break(0); } - } - else if (0 == GNUNET_memcmp (zone, privkey2)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Received data for not requested zone\n"); - failed = GNUNET_YES; - GNUNET_break (0); - } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Received invalid zone\n"); - failed = GNUNET_YES; - GNUNET_break (0); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Received invalid zone\n"); + failed = GNUNET_YES; + GNUNET_break(0); + } if (failed == GNUNET_NO) - { - returned_records ++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Telling namestore to send the next result\n"); - GNUNET_NAMESTORE_zone_iterator_next (zi, - 1); - } + { + returned_records++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Telling namestore to send the next result\n"); + GNUNET_NAMESTORE_zone_iterator_next(zi, + 1); + } else - { - GNUNET_break (0); - res = 2; - GNUNET_SCHEDULER_shutdown (); - } + { + GNUNET_break(0); + res = 2; + GNUNET_SCHEDULER_shutdown(); + } } static void -zone_proc_end (void *cls) +zone_proc_end(void *cls) { zi = NULL; - GNUNET_break (2 == returned_records); + GNUNET_break(2 == returned_records); if (2 == returned_records) - { - res = 0; /* Last iteraterator callback, we are done */ - } + { + res = 0; /* Last iteraterator callback, we are done */ + } else - { - res = 1; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received last result, iteration done after receing %u results\n", - returned_records); - GNUNET_SCHEDULER_shutdown (); + { + res = 1; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received last result, iteration done after receing %u results\n", + returned_records); + GNUNET_SCHEDULER_shutdown(); } static void -put_cont (void *cls, - int32_t success, - const char *emsg) +put_cont(void *cls, + int32_t success, + const char *emsg) { static int c = 0; if (success == GNUNET_OK) - { - c++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record %u \n", c); - } + { + c++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record %u \n", c); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to created records: `%s'\n", - emsg); - GNUNET_break (0); - res = 2; - GNUNET_SCHEDULER_shutdown (); - return; - } - - if (c == 3) - { - res = 1; - returned_records = 0; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "All records created, starting iteration over all zones \n"); - zi = GNUNET_NAMESTORE_zone_iteration_start(nsh, - privkey, - &fail_cb, - NULL, - &zone_proc, - NULL, - &zone_proc_end, - NULL); - if (zi == NULL) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create zone iterator\n"); - GNUNET_break (0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to created records: `%s'\n", + emsg); + GNUNET_break(0); res = 2; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); return; } - } + + if (c == 3) + { + res = 1; + returned_records = 0; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "All records created, starting iteration over all zones \n"); + zi = GNUNET_NAMESTORE_zone_iteration_start(nsh, + privkey, + &fail_cb, + NULL, + &zone_proc, + NULL, + &zone_proc_end, + NULL); + if (zi == NULL) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create zone iterator\n"); + GNUNET_break(0); + res = 2; + GNUNET_SCHEDULER_shutdown(); + return; + } + } } static struct GNUNET_GNSRECORD_Data * -create_record (unsigned int count) +create_record(unsigned int count) { struct GNUNET_GNSRECORD_Data *rd; - rd = GNUNET_new_array (count, - struct GNUNET_GNSRECORD_Data); + rd = GNUNET_new_array(count, + struct GNUNET_GNSRECORD_Data); for (unsigned int c = 0; c < count; c++) - { - rd[c].expiration_time = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS).abs_value_us; - rd[c].record_type = TEST_RECORD_TYPE; - rd[c].data_size = 50; - rd[c].data = GNUNET_malloc(50); - rd[c].flags = 0; - memset ((char *) rd[c].data, 'a', 50); - } + { + rd[c].expiration_time = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS).abs_value_us; + rd[c].record_type = TEST_RECORD_TYPE; + rd[c].data_size = 50; + rd[c].data = GNUNET_malloc(50); + rd[c].flags = 0; + memset((char *)rd[c].data, 'a', 50); + } return rd; } @@ -317,114 +317,114 @@ create_record (unsigned int count) * start the actual tests by filling the zone. */ static void -empty_zone_proc (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +empty_zone_proc(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { - GNUNET_assert (nsh == cls); + GNUNET_assert(nsh == cls); if (NULL != zone) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Expected empty zone but received zone private key\n")); - GNUNET_break (0); - res = 2; - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Expected empty zone but received zone private key\n")); + GNUNET_break(0); + res = 2; + GNUNET_SCHEDULER_shutdown(); + return; + } if ((NULL != label) || (NULL != rd) || (0 != rd_count)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Expected no zone content but received data\n")); - GNUNET_break (0); - res = 2; - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_assert (0); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Expected no zone content but received data\n")); + GNUNET_break(0); + res = 2; + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_assert(0); } static void -empty_zone_proc_end (void *cls) +empty_zone_proc_end(void *cls) { zi = NULL; - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey != NULL); - privkey2 = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (privkey2 != NULL); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 1\n"); - GNUNET_asprintf (&s_name_1, - "dummy1"); - s_rd_1 = create_record (1); - GNUNET_NAMESTORE_records_store (nsh, - privkey, - s_name_1, - 1, - s_rd_1, - &put_cont, - NULL); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 2 \n"); - GNUNET_asprintf (&s_name_2, - "dummy2"); - s_rd_2 = create_record (1); - GNUNET_NAMESTORE_records_store (nsh, - privkey, - s_name_2, - 1, - s_rd_2, - &put_cont, - NULL); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 3\n"); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey != NULL); + privkey2 = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(privkey2 != NULL); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 1\n"); + GNUNET_asprintf(&s_name_1, + "dummy1"); + s_rd_1 = create_record(1); + GNUNET_NAMESTORE_records_store(nsh, + privkey, + s_name_1, + 1, + s_rd_1, + &put_cont, + NULL); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 2 \n"); + GNUNET_asprintf(&s_name_2, + "dummy2"); + s_rd_2 = create_record(1); + GNUNET_NAMESTORE_records_store(nsh, + privkey, + s_name_2, + 1, + s_rd_2, + &put_cont, + NULL); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 3\n"); /* name in different zone */ - GNUNET_asprintf (&s_name_3, - "dummy3"); - s_rd_3 = create_record (1); - GNUNET_NAMESTORE_records_store (nsh, - privkey2, - s_name_3, - 1, s_rd_3, - &put_cont, - NULL); + GNUNET_asprintf(&s_name_3, + "dummy3"); + s_rd_3 = create_record(1); + GNUNET_NAMESTORE_records_store(nsh, + privkey2, + s_name_3, + 1, s_rd_3, + &put_cont, + NULL); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - GNUNET_SCHEDULER_add_shutdown (&end, - NULL); - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, - NULL); - nsh = GNUNET_NAMESTORE_connect (cfg); - GNUNET_break (NULL != nsh); + GNUNET_SCHEDULER_add_shutdown(&end, + NULL); + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, + NULL); + nsh = GNUNET_NAMESTORE_connect(cfg); + GNUNET_break(NULL != nsh); /* first, iterate over empty namestore */ - zi = GNUNET_NAMESTORE_zone_iteration_start (nsh, - NULL, - &fail_cb, - NULL, - &empty_zone_proc, - nsh, - &empty_zone_proc_end, - nsh); + zi = GNUNET_NAMESTORE_zone_iteration_start(nsh, + NULL, + &fail_cb, + NULL, + &empty_zone_proc, + nsh, + &empty_zone_proc_end, + nsh); if (NULL == zi) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create zone iterator\n"); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create zone iterator\n"); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + } } @@ -432,24 +432,24 @@ run (void *cls, int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-zone-iteration-specific-zone", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-zone-iteration-specific-zone", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_zone_iteration_stop.c b/src/namestore/test_namestore_api_zone_iteration_stop.c index 28f424b23..89007c82c 100644 --- a/src/namestore/test_namestore_api_zone_iteration_stop.c +++ b/src/namestore/test_namestore_api_zone_iteration_stop.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_zone_iteration_stop.c * @brief testcase for zone iteration functionality: stop iterating of zones @@ -29,8 +29,8 @@ #define TEST_RECORD_TYPE GNUNET_DNSPARSER_TYPE_TXT -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) -#define WAIT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) +#define WAIT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 2) static struct GNUNET_NAMESTORE_Handle * nsh; @@ -63,257 +63,257 @@ static struct GNUNET_GNSRECORD_Data *s_rd_3; * @param cls handle to use to re-connect. */ static void -end (void *cls) +end(void *cls) { if (NULL != zi) - { - GNUNET_NAMESTORE_zone_iteration_stop (zi); - zi = NULL; - } + { + GNUNET_NAMESTORE_zone_iteration_stop(zi); + zi = NULL; + } if (nsh != NULL) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } - GNUNET_free_non_null (s_name_1); - GNUNET_free_non_null (s_name_2); - GNUNET_free_non_null (s_name_3); + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } + GNUNET_free_non_null(s_name_1); + GNUNET_free_non_null(s_name_2); + GNUNET_free_non_null(s_name_3); if (s_rd_1 != NULL) - { - GNUNET_free ((void *)s_rd_1->data); - GNUNET_free (s_rd_1); - } + { + GNUNET_free((void *)s_rd_1->data); + GNUNET_free(s_rd_1); + } if (s_rd_2 != NULL) - { - GNUNET_free ((void *)s_rd_2->data); - GNUNET_free (s_rd_2); - } + { + GNUNET_free((void *)s_rd_2->data); + GNUNET_free(s_rd_2); + } if (s_rd_3 != NULL) - { - GNUNET_free ((void *)s_rd_3->data); - GNUNET_free (s_rd_3); - } + { + GNUNET_free((void *)s_rd_3->data); + GNUNET_free(s_rd_3); + } if (privkey != NULL) - { - GNUNET_free (privkey); - privkey = NULL; - } + { + GNUNET_free(privkey); + privkey = NULL; + } if (privkey2 != NULL) - { - GNUNET_free (privkey2); - privkey2 = NULL; - } + { + GNUNET_free(privkey2); + privkey2 = NULL; + } } static void -delayed_end (void *cls) +delayed_end(void *cls) { - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } static void -fail_cb (void *cls) +fail_cb(void *cls) { - GNUNET_assert (0); + GNUNET_assert(0); } static void -zone_proc (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +zone_proc(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { int failed = GNUNET_NO; - GNUNET_assert (NULL != zone); - if (0 == GNUNET_memcmp (zone, privkey)) - { - if (0 == strcmp (label, s_name_1)) + GNUNET_assert(NULL != zone); + if (0 == GNUNET_memcmp(zone, privkey)) { - if (rd_count == 1) - { - if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_1)) + if (0 == strcmp(label, s_name_1)) { - failed = GNUNET_YES; - GNUNET_break (0); + if (rd_count == 1) + { + if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_1)) + { + failed = GNUNET_YES; + GNUNET_break(0); + } + } + else + { + failed = GNUNET_YES; + GNUNET_break(0); + } + } + else if (0 == strcmp(label, s_name_2)) + { + if (rd_count == 1) + { + if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_2)) + { + failed = GNUNET_YES; + GNUNET_break(0); + } + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Received invalid record count\n"); + failed = GNUNET_YES; + GNUNET_break(0); + } } - } else - { - failed = GNUNET_YES; - GNUNET_break (0); - } - } - else if (0 == strcmp (label, s_name_2)) - { - if (rd_count == 1) - { - if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_2)) { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Comparing result failed: got name `%s' for first zone\n", label); failed = GNUNET_YES; - GNUNET_break (0); + GNUNET_break(0); } - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Received invalid record count\n"); - failed = GNUNET_YES; - GNUNET_break (0); - } - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Comparing result failed: got name `%s' for first zone\n", label); - failed = GNUNET_YES; - GNUNET_break (0); } - } - else if (0 == GNUNET_memcmp (zone, privkey2)) - { - if (0 == strcmp (label, s_name_3)) + else if (0 == GNUNET_memcmp(zone, privkey2)) { - if (rd_count == 1) - { - if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_3)) + if (0 == strcmp(label, s_name_3)) { - failed = GNUNET_YES; - GNUNET_break (0); + if (rd_count == 1) + { + if (GNUNET_YES != GNUNET_GNSRECORD_records_cmp(rd, s_rd_3)) + { + failed = GNUNET_YES; + GNUNET_break(0); + } + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Received invalid record count\n"); + failed = GNUNET_YES; + GNUNET_break(0); + } } - } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Received invalid record count\n"); - failed = GNUNET_YES; - GNUNET_break (0); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Comparing result failed: got name `%s' for first zone\n", label); + failed = GNUNET_YES; + GNUNET_break(0); + } } - else + else { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Comparing result failed: got name `%s' for first zone\n", label); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Received invalid zone\n"); failed = GNUNET_YES; - GNUNET_break (0); + GNUNET_break(0); } - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Received invalid zone\n"); - failed = GNUNET_YES; - GNUNET_break (0); - } if (failed == GNUNET_NO) - { - if (1 == returned_records) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Telling namestore to stop zone iteration\n"); - GNUNET_NAMESTORE_zone_iteration_stop (zi); - zi = NULL; - res = 0; - GNUNET_SCHEDULER_add_delayed (WAIT, - &delayed_end, - NULL); - return; + if (1 == returned_records) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Telling namestore to stop zone iteration\n"); + GNUNET_NAMESTORE_zone_iteration_stop(zi); + zi = NULL; + res = 0; + GNUNET_SCHEDULER_add_delayed(WAIT, + &delayed_end, + NULL); + return; + } + returned_records++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Telling namestore to send the next result\n"); + GNUNET_NAMESTORE_zone_iterator_next(zi, + 1); } - returned_records ++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Telling namestore to send the next result\n"); - GNUNET_NAMESTORE_zone_iterator_next (zi, - 1); - } else - { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - } + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + } } static void -zone_proc_end (void *cls) +zone_proc_end(void *cls) { - GNUNET_break (1 <= returned_records); + GNUNET_break(1 <= returned_records); if (1 >= returned_records) res = 1; /* Last iteraterator callback, we are done */ else res = 0; zi = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received last result, iteration done after receing %u results\n", - returned_records); - GNUNET_SCHEDULER_add_now (&end, NULL); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received last result, iteration done after receing %u results\n", + returned_records); + GNUNET_SCHEDULER_add_now(&end, NULL); } static void -put_cont (void *cls, int32_t success, const char *emsg) +put_cont(void *cls, int32_t success, const char *emsg) { static int c = 0; if (success == GNUNET_OK) - { - c++; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Created record %u \n", c); - } + { + c++; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Created record %u \n", c); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to created records: `%s'\n", - emsg); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Failed to created records: `%s'\n", + emsg); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } if (c == 3) - { - res = 1; - returned_records = 0; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "All records created, starting iteration over all zones \n"); - zi = GNUNET_NAMESTORE_zone_iteration_start (nsh, - NULL, - &fail_cb, - NULL, - &zone_proc, - NULL, - &zone_proc_end, - NULL); - if (zi == NULL) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create zone iterator\n"); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; + res = 1; + returned_records = 0; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "All records created, starting iteration over all zones \n"); + zi = GNUNET_NAMESTORE_zone_iteration_start(nsh, + NULL, + &fail_cb, + NULL, + &zone_proc, + NULL, + &zone_proc_end, + NULL); + if (zi == NULL) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create zone iterator\n"); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } } - } } static struct GNUNET_GNSRECORD_Data * -create_record (unsigned int count) +create_record(unsigned int count) { struct GNUNET_GNSRECORD_Data *rd; - rd = GNUNET_new_array (count, - struct GNUNET_GNSRECORD_Data); + rd = GNUNET_new_array(count, + struct GNUNET_GNSRECORD_Data); for (unsigned int c = 0; c < count; c++) - { - rd[c].expiration_time = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS).abs_value_us; - rd[c].record_type = TEST_RECORD_TYPE; - rd[c].data_size = 50; - rd[c].data = GNUNET_malloc(50); - rd[c].flags = 0; - memset ((char *) rd[c].data, 'a', 50); - } + { + rd[c].expiration_time = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS).abs_value_us; + rd[c].record_type = TEST_RECORD_TYPE; + rd[c].data_size = 50; + rd[c].data = GNUNET_malloc(50); + rd[c].flags = 0; + memset((char *)rd[c].data, 'a', 50); + } return rd; } @@ -324,86 +324,85 @@ create_record (unsigned int count) * start the actual tests by filling the zone. */ static void -empty_zone_proc (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +empty_zone_proc(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { - - GNUNET_assert (nsh == cls); + GNUNET_assert(nsh == cls); if (NULL != zone) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Expected empty zone but received zone private key\n")); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Expected empty zone but received zone private key\n")); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } if ((NULL != label) || (NULL != rd) || (0 != rd_count)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Expected no zone content but received data\n")); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_assert (0); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Expected no zone content but received data\n")); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_assert(0); } static void -empty_zone_proc_end (void *cls) +empty_zone_proc_end(void *cls) { char *hostkey_file; - GNUNET_assert (nsh == cls); + GNUNET_assert(nsh == cls); zi = NULL; GNUNET_asprintf(&hostkey_file, "zonefiles%s%s", DIR_SEPARATOR_STR, "N0UJMP015AFUNR2BTNM3FKPBLG38913BL8IDMCO2H0A1LIB81960.zkey"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Using zonekey file `%s' \n", - hostkey_file); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Using zonekey file `%s' \n", + hostkey_file); privkey = GNUNET_CRYPTO_ecdsa_key_create_from_file(hostkey_file); - GNUNET_free (hostkey_file); - GNUNET_assert (privkey != NULL); - - GNUNET_asprintf (&hostkey_file, - "zonefiles%s%s", - DIR_SEPARATOR_STR, - "HGU0A0VCU334DN7F2I9UIUMVQMM7JMSD142LIMNUGTTV9R0CF4EG.zkey"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Using zonekey file `%s'\n", - hostkey_file); + GNUNET_free(hostkey_file); + GNUNET_assert(privkey != NULL); + + GNUNET_asprintf(&hostkey_file, + "zonefiles%s%s", + DIR_SEPARATOR_STR, + "HGU0A0VCU334DN7F2I9UIUMVQMM7JMSD142LIMNUGTTV9R0CF4EG.zkey"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Using zonekey file `%s'\n", + hostkey_file); privkey2 = GNUNET_CRYPTO_ecdsa_key_create_from_file(hostkey_file); - GNUNET_free (hostkey_file); - GNUNET_assert (privkey2 != NULL); + GNUNET_free(hostkey_file); + GNUNET_assert(privkey2 != NULL); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 1\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 1\n"); GNUNET_asprintf(&s_name_1, "dummy1"); s_rd_1 = create_record(1); GNUNET_NAMESTORE_records_store(nsh, privkey, s_name_1, - 1, s_rd_1, &put_cont, NULL); + 1, s_rd_1, &put_cont, NULL); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 2 \n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 2 \n"); GNUNET_asprintf(&s_name_2, "dummy2"); s_rd_2 = create_record(1); - GNUNET_NAMESTORE_records_store (nsh, - privkey, - s_name_2, - 1, - s_rd_2, - &put_cont, NULL); + GNUNET_NAMESTORE_records_store(nsh, + privkey, + s_name_2, + 1, + s_rd_2, + &put_cont, NULL); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Created record 3\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Created record 3\n"); /* name in different zone */ GNUNET_asprintf(&s_name_3, "dummy3"); @@ -418,30 +417,30 @@ empty_zone_proc_end (void *cls) static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - nsh = GNUNET_NAMESTORE_connect (cfg); - GNUNET_break (NULL != nsh); - GNUNET_SCHEDULER_add_shutdown (&end, - NULL); + nsh = GNUNET_NAMESTORE_connect(cfg); + GNUNET_break(NULL != nsh); + GNUNET_SCHEDULER_add_shutdown(&end, + NULL); /* first, iterate over empty namestore */ - zi = GNUNET_NAMESTORE_zone_iteration_start (nsh, - NULL, - &fail_cb, - NULL, - &empty_zone_proc, - nsh, - &empty_zone_proc_end, - nsh); + zi = GNUNET_NAMESTORE_zone_iteration_start(nsh, + NULL, + &fail_cb, + NULL, + &empty_zone_proc, + nsh, + &empty_zone_proc_end, + nsh); if (NULL == zi) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create zone iterator\n"); - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create zone iterator\n"); + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + } } @@ -449,24 +448,24 @@ run (void *cls, int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { const char *plugin_name; char *cfg_name; - SETUP_CFG (plugin_name, cfg_name); + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-zone-iteration-stop", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-zone-iteration-stop", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_namestore_api_zone_to_name.c b/src/namestore/test_namestore_api_zone_to_name.c index cb580572e..0c02c9a52 100644 --- a/src/namestore/test_namestore_api_zone_to_name.c +++ b/src/namestore/test_namestore_api_zone_to_name.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file namestore/test_namestore_api_zone_to_name.c * @brief testcase for zone to name translation @@ -35,7 +35,7 @@ #define TEST_RECORD_DATA 'a' -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 100) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 100) static struct GNUNET_NAMESTORE_Handle *nsh; @@ -61,180 +61,180 @@ static struct GNUNET_NAMESTORE_QueueEntry *qe; * @param cls handle to use to re-connect. */ static void -endbadly (void *cls) +endbadly(void *cls) { - (void) cls; - GNUNET_SCHEDULER_shutdown (); + (void)cls; + GNUNET_SCHEDULER_shutdown(); res = 1; } static void -end (void *cls) +end(void *cls) { if (NULL != qe) - { - GNUNET_NAMESTORE_cancel (qe); - qe = NULL; - } + { + GNUNET_NAMESTORE_cancel(qe); + qe = NULL; + } if (NULL != endbadly_task) - { - GNUNET_SCHEDULER_cancel (endbadly_task); - endbadly_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(endbadly_task); + endbadly_task = NULL; + } if (NULL != privkey) - { - GNUNET_free (privkey); - privkey = NULL; - } + { + GNUNET_free(privkey); + privkey = NULL; + } if (NULL != nsh) - { - GNUNET_NAMESTORE_disconnect (nsh); - nsh = NULL; - } + { + GNUNET_NAMESTORE_disconnect(nsh); + nsh = NULL; + } } static void -zone_to_name_proc (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, - const char *n, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +zone_to_name_proc(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key, + const char *n, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { int fail = GNUNET_NO; qe = NULL; - if ( (NULL == zone_key) && - (NULL == n) && - (0 == rd_count) && - (NULL == rd) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "No result found\n"); - res = 1; - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Result found: `%s'\n", - n); - if ( (NULL == n) || - (0 != strcmp (n, - s_name))) + if ((NULL == zone_key) && + (NULL == n) && + (0 == rd_count) && + (NULL == rd)) { - fail = GNUNET_YES; - GNUNET_break (0); - } - if (1 != rd_count) - { - fail = GNUNET_YES; - GNUNET_break (0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "No result found\n"); + res = 1; } - if ( (NULL == zone_key) || - (0 != GNUNET_memcmp (zone_key, - privkey))) + else { - fail = GNUNET_YES; - GNUNET_break (0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Result found: `%s'\n", + n); + if ((NULL == n) || + (0 != strcmp(n, + s_name))) + { + fail = GNUNET_YES; + GNUNET_break(0); + } + if (1 != rd_count) + { + fail = GNUNET_YES; + GNUNET_break(0); + } + if ((NULL == zone_key) || + (0 != GNUNET_memcmp(zone_key, + privkey))) + { + fail = GNUNET_YES; + GNUNET_break(0); + } + if (fail == GNUNET_NO) + res = 0; + else + res = 1; } - if (fail == GNUNET_NO) - res = 0; - else - res = 1; - } - GNUNET_SCHEDULER_add_now (&end, - NULL); + GNUNET_SCHEDULER_add_now(&end, + NULL); } static void -error_cb (void *cls) +error_cb(void *cls) { - (void) cls; + (void)cls; qe = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Not found!\n"); - GNUNET_SCHEDULER_shutdown (); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Not found!\n"); + GNUNET_SCHEDULER_shutdown(); res = 2; } static void -put_cont (void *cls, - int32_t success, - const char *emsg) +put_cont(void *cls, + int32_t success, + const char *emsg) { char *name = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Name store added record for `%s': %s\n", - name, - (success == GNUNET_OK) ? "SUCCESS" : emsg); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Name store added record for `%s': %s\n", + name, + (success == GNUNET_OK) ? "SUCCESS" : emsg); if (success == GNUNET_OK) - { - res = 0; - - qe = GNUNET_NAMESTORE_zone_to_name (nsh, - privkey, - &s_zone_value, - &error_cb, - NULL, - &zone_to_name_proc, - NULL); - } + { + res = 0; + + qe = GNUNET_NAMESTORE_zone_to_name(nsh, + privkey, + &s_zone_value, + &error_cb, + NULL, + &zone_to_name_proc, + NULL); + } else - { - res = 1; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to put records for name `%s'\n", - name); - GNUNET_SCHEDULER_add_now (&end, - NULL); - } + { + res = 1; + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to put records for name `%s'\n", + name); + GNUNET_SCHEDULER_add_now(&end, + NULL); + } } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - (void) cls; - (void) peer; - endbadly_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &endbadly, - NULL); - GNUNET_SCHEDULER_add_shutdown (&end, - NULL); - GNUNET_asprintf (&s_name, "dummy"); - privkey = GNUNET_CRYPTO_ecdsa_key_create (); - GNUNET_assert (NULL != privkey); + (void)cls; + (void)peer; + endbadly_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &endbadly, + NULL); + GNUNET_SCHEDULER_add_shutdown(&end, + NULL); + GNUNET_asprintf(&s_name, "dummy"); + privkey = GNUNET_CRYPTO_ecdsa_key_create(); + GNUNET_assert(NULL != privkey); /* get public key */ - GNUNET_CRYPTO_ecdsa_key_get_public (privkey, - &pubkey); + GNUNET_CRYPTO_ecdsa_key_get_public(privkey, + &pubkey); - GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, - &s_zone_value, - sizeof (s_zone_value)); + GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_WEAK, + &s_zone_value, + sizeof(s_zone_value)); { struct GNUNET_GNSRECORD_Data rd; rd.expiration_time = GNUNET_TIME_absolute_get().abs_value_us; rd.record_type = GNUNET_GNSRECORD_TYPE_PKEY; - rd.data_size = sizeof (s_zone_value); + rd.data_size = sizeof(s_zone_value); rd.data = &s_zone_value; rd.flags = 0; - nsh = GNUNET_NAMESTORE_connect (cfg); - GNUNET_break (NULL != nsh); - GNUNET_NAMESTORE_records_store (nsh, - privkey, - s_name, - 1, - &rd, - &put_cont, - NULL); + nsh = GNUNET_NAMESTORE_connect(cfg); + GNUNET_break(NULL != nsh); + GNUNET_NAMESTORE_records_store(nsh, + privkey, + s_name, + 1, + &rd, + &put_cont, + NULL); } } @@ -243,26 +243,26 @@ run (void *cls, int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { const char *plugin_name; char *cfg_name; - (void) argc; - SETUP_CFG (plugin_name, cfg_name); + (void)argc; + SETUP_CFG(plugin_name, cfg_name); res = 1; if (0 != - GNUNET_TESTING_peer_run ("test-namestore-api-zone-to-name", - cfg_name, - &run, - NULL)) - { - res = 1; - } - GNUNET_DISK_purge_cfg_dir (cfg_name, - "GNUNET_TEST_HOME"); - GNUNET_free (cfg_name); + GNUNET_TESTING_peer_run("test-namestore-api-zone-to-name", + cfg_name, + &run, + NULL)) + { + res = 1; + } + GNUNET_DISK_purge_cfg_dir(cfg_name, + "GNUNET_TEST_HOME"); + GNUNET_free(cfg_name); return res; } diff --git a/src/namestore/test_plugin_namestore.c b/src/namestore/test_plugin_namestore.c index b4ed4c70d..8fb30b651 100644 --- a/src/namestore/test_plugin_namestore.c +++ b/src/namestore/test_plugin_namestore.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /* * @file namestore/test_plugin_namestore.c * @brief Test for the namestore plugins @@ -45,13 +45,13 @@ static const char *plugin_name; * @param api api to unload */ static void -unload_plugin (struct GNUNET_NAMESTORE_PluginFunctions *api) +unload_plugin(struct GNUNET_NAMESTORE_PluginFunctions *api) { char *libname; - GNUNET_asprintf (&libname, "libgnunet_plugin_namestore_%s", plugin_name); - GNUNET_break (NULL == GNUNET_PLUGIN_unload (libname, api)); - GNUNET_free (libname); + GNUNET_asprintf(&libname, "libgnunet_plugin_namestore_%s", plugin_name); + GNUNET_break(NULL == GNUNET_PLUGIN_unload(libname, api)); + GNUNET_free(libname); } @@ -62,33 +62,33 @@ unload_plugin (struct GNUNET_NAMESTORE_PluginFunctions *api) * @return NULL on error */ static struct GNUNET_NAMESTORE_PluginFunctions * -load_plugin (const struct GNUNET_CONFIGURATION_Handle *cfg) +load_plugin(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_NAMESTORE_PluginFunctions *ret; char *libname; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Loading `%s' namestore plugin\n"), - plugin_name); - GNUNET_asprintf (&libname, "libgnunet_plugin_namestore_%s", plugin_name); - if (NULL == (ret = GNUNET_PLUGIN_load (libname, (void *) cfg))) - { - fprintf (stderr, "Failed to load plugin `%s'!\n", plugin_name); - GNUNET_free (libname); - return NULL; - } - GNUNET_free (libname); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Loading `%s' namestore plugin\n"), + plugin_name); + GNUNET_asprintf(&libname, "libgnunet_plugin_namestore_%s", plugin_name); + if (NULL == (ret = GNUNET_PLUGIN_load(libname, (void *)cfg))) + { + fprintf(stderr, "Failed to load plugin `%s'!\n", plugin_name); + GNUNET_free(libname); + return NULL; + } + GNUNET_free(libname); return ret; } static void -test_record (void *cls, - uint64_t seq, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +test_record(void *cls, + uint64_t seq, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *private_key, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { int *idp = cls; int id = *idp; @@ -96,106 +96,106 @@ test_record (void *cls, char tname[64]; unsigned int trd_count = 1 + (id % 1024); - GNUNET_snprintf (tname, sizeof (tname), "a%u", (unsigned int) id); - GNUNET_assert (trd_count == rd_count); + GNUNET_snprintf(tname, sizeof(tname), "a%u", (unsigned int)id); + GNUNET_assert(trd_count == rd_count); for (unsigned int i = 0; i < trd_count; i++) - { - GNUNET_assert (rd[i].data_size == id % 10); - GNUNET_assert (0 == memcmp ("Hello World", rd[i].data, id % 10)); - GNUNET_assert (rd[i].record_type == TEST_RECORD_TYPE); - GNUNET_assert (rd[i].flags == 0); - } - memset (&tzone_private_key, (id % 241), sizeof (tzone_private_key)); - GNUNET_assert (0 == strcmp (label, tname)); - GNUNET_assert (0 == GNUNET_memcmp (&tzone_private_key, private_key)); + { + GNUNET_assert(rd[i].data_size == id % 10); + GNUNET_assert(0 == memcmp("Hello World", rd[i].data, id % 10)); + GNUNET_assert(rd[i].record_type == TEST_RECORD_TYPE); + GNUNET_assert(rd[i].flags == 0); + } + memset(&tzone_private_key, (id % 241), sizeof(tzone_private_key)); + GNUNET_assert(0 == strcmp(label, tname)); + GNUNET_assert(0 == GNUNET_memcmp(&tzone_private_key, private_key)); } static void -get_record (struct GNUNET_NAMESTORE_PluginFunctions *nsp, int id) +get_record(struct GNUNET_NAMESTORE_PluginFunctions *nsp, int id) { - GNUNET_assert ( + GNUNET_assert( GNUNET_OK == - nsp->iterate_records (nsp->cls, NULL, 0, 1, &test_record, &id)); + nsp->iterate_records(nsp->cls, NULL, 0, 1, &test_record, &id)); } static void -put_record (struct GNUNET_NAMESTORE_PluginFunctions *nsp, int id) +put_record(struct GNUNET_NAMESTORE_PluginFunctions *nsp, int id) { struct GNUNET_CRYPTO_EcdsaPrivateKey zone_private_key; char label[64]; unsigned int rd_count = 1 + (id % 1024); - struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL (rd_count)]; + struct GNUNET_GNSRECORD_Data rd[GNUNET_NZL(rd_count)]; struct GNUNET_CRYPTO_EcdsaSignature signature; - GNUNET_snprintf (label, sizeof (label), "a%u", (unsigned int) id); + GNUNET_snprintf(label, sizeof(label), "a%u", (unsigned int)id); for (unsigned int i = 0; i < rd_count; i++) - { - rd[i].data = "Hello World"; - rd[i].data_size = id % 10; - rd[i].expiration_time = - GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_MINUTES).abs_value_us; - rd[i].record_type = TEST_RECORD_TYPE; - rd[i].flags = 0; - } - memset (&zone_private_key, (id % 241), sizeof (zone_private_key)); - memset (&signature, (id % 243), sizeof (signature)); - GNUNET_assert ( + { + rd[i].data = "Hello World"; + rd[i].data_size = id % 10; + rd[i].expiration_time = + GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_MINUTES).abs_value_us; + rd[i].record_type = TEST_RECORD_TYPE; + rd[i].flags = 0; + } + memset(&zone_private_key, (id % 241), sizeof(zone_private_key)); + memset(&signature, (id % 243), sizeof(signature)); + GNUNET_assert( GNUNET_OK == - nsp->store_records (nsp->cls, &zone_private_key, label, rd_count, rd)); + nsp->store_records(nsp->cls, &zone_private_key, label, rd_count, rd)); } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_NAMESTORE_PluginFunctions *nsp; ok = 0; - nsp = load_plugin (cfg); + nsp = load_plugin(cfg); if (NULL == nsp) - { - fprintf ( - stderr, - "%s", - "Failed to initialize namestore. Database likely not setup, skipping test.\n"); - return; - } - put_record (nsp, 1); - get_record (nsp, 1); - - unload_plugin (nsp); + { + fprintf( + stderr, + "%s", + "Failed to initialize namestore. Database likely not setup, skipping test.\n"); + return; + } + put_record(nsp, 1); + get_record(nsp, 1); + + unload_plugin(nsp); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { char cfg_name[PATH_MAX]; - char *const xargv[] = {"test-plugin-namestore", "-c", cfg_name, NULL}; - struct GNUNET_GETOPT_CommandLineOption options[] = {GNUNET_GETOPT_OPTION_END}; - - GNUNET_log_setup ("test-plugin-namestore", "WARNING", NULL); - plugin_name = GNUNET_TESTING_get_testname_from_underscore (argv[0]); - GNUNET_snprintf (cfg_name, - sizeof (cfg_name), - "test_plugin_namestore_%s.conf", - plugin_name); - GNUNET_DISK_purge_cfg_dir (cfg_name, "GNUNET_TMP"); - GNUNET_PROGRAM_run ((sizeof (xargv) / sizeof (char *)) - 1, - xargv, - "test-plugin-namestore", - "nohelp", - options, - &run, - NULL); - GNUNET_DISK_purge_cfg_dir (cfg_name, "GNUNET_TMP"); + char *const xargv[] = { "test-plugin-namestore", "-c", cfg_name, NULL }; + struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; + + GNUNET_log_setup("test-plugin-namestore", "WARNING", NULL); + plugin_name = GNUNET_TESTING_get_testname_from_underscore(argv[0]); + GNUNET_snprintf(cfg_name, + sizeof(cfg_name), + "test_plugin_namestore_%s.conf", + plugin_name); + GNUNET_DISK_purge_cfg_dir(cfg_name, "GNUNET_TMP"); + GNUNET_PROGRAM_run((sizeof(xargv) / sizeof(char *)) - 1, + xargv, + "test-plugin-namestore", + "nohelp", + options, + &run, + NULL); + GNUNET_DISK_purge_cfg_dir(cfg_name, "GNUNET_TMP"); if (ok != 0) - fprintf (stderr, "Missed some testcases: %d\n", ok); + fprintf(stderr, "Missed some testcases: %d\n", ok); return ok; } diff --git a/src/nat-auto/gnunet-nat-auto.c b/src/nat-auto/gnunet-nat-auto.c index 106d60228..87850509d 100644 --- a/src/nat-auto/gnunet-nat-auto.c +++ b/src/nat-auto/gnunet-nat-auto.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/nat/gnunet-nat-auto.c @@ -90,13 +90,13 @@ static uint8_t proto; * terminate. */ static void -test_finished () +test_finished() { if (NULL != ah) return; if (NULL != nt) return; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -109,16 +109,16 @@ test_finished () * @param value value of the option */ static void -auto_conf_iter (void *cls, - const char *section, - const char *option, - const char *value) +auto_conf_iter(void *cls, + const char *section, + const char *option, + const char *value) { struct GNUNET_CONFIGURATION_Handle *new_cfg = cls; - printf ("%s: %s\n", option, value); + printf("%s: %s\n", option, value); if (NULL != new_cfg) - GNUNET_CONFIGURATION_set_value_string (new_cfg, section, option, value); + GNUNET_CONFIGURATION_set_value_string(new_cfg, section, option, value); } @@ -132,10 +132,10 @@ auto_conf_iter (void *cls, * @param type what the situation of the NAT */ static void -auto_config_cb (void *cls, - const struct GNUNET_CONFIGURATION_Handle *diff, - enum GNUNET_NAT_StatusCode result, - enum GNUNET_NAT_Type type) +auto_config_cb(void *cls, + const struct GNUNET_CONFIGURATION_Handle *diff, + enum GNUNET_NAT_StatusCode result, + enum GNUNET_NAT_Type type) { const char *nat_type; char unknown_type[64]; @@ -143,80 +143,84 @@ auto_config_cb (void *cls, ah = NULL; switch (type) - { - case GNUNET_NAT_TYPE_NO_NAT: - nat_type = "NO NAT"; - break; - case GNUNET_NAT_TYPE_UNREACHABLE_NAT: - nat_type = "NAT but we can traverse"; - break; - case GNUNET_NAT_TYPE_STUN_PUNCHED_NAT: - nat_type = "NAT but STUN is able to identify the correct information"; - break; - case GNUNET_NAT_TYPE_UPNP_NAT: - nat_type = "NAT but UPNP opened the ports"; - break; - default: - sprintf (unknown_type, "NAT unknown, type %u", type); - nat_type = unknown_type; - break; - } - - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "NAT status: %s/%s\n", - GNUNET_NAT_AUTO_status2string (result), - nat_type); + { + case GNUNET_NAT_TYPE_NO_NAT: + nat_type = "NO NAT"; + break; + + case GNUNET_NAT_TYPE_UNREACHABLE_NAT: + nat_type = "NAT but we can traverse"; + break; + + case GNUNET_NAT_TYPE_STUN_PUNCHED_NAT: + nat_type = "NAT but STUN is able to identify the correct information"; + break; + + case GNUNET_NAT_TYPE_UPNP_NAT: + nat_type = "NAT but UPNP opened the ports"; + break; + + default: + sprintf(unknown_type, "NAT unknown, type %u", type); + nat_type = unknown_type; + break; + } + + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "NAT status: %s/%s\n", + GNUNET_NAT_AUTO_status2string(result), + nat_type); if (NULL == diff) return; /* Shortcut: if there are no changes suggested, bail out early. */ - if (GNUNET_NO == GNUNET_CONFIGURATION_is_dirty (diff)) - { - test_finished (); - return; - } + if (GNUNET_NO == GNUNET_CONFIGURATION_is_dirty(diff)) + { + test_finished(); + return; + } /* Apply diff to original configuration and show changes to the user */ - new_cfg = write_cfg ? GNUNET_CONFIGURATION_dup (cfg) : NULL; + new_cfg = write_cfg ? GNUNET_CONFIGURATION_dup(cfg) : NULL; - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - _ ("Suggested configuration changes:\n")); - GNUNET_CONFIGURATION_iterate_section_values (diff, - "nat", - &auto_conf_iter, - new_cfg); + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + _("Suggested configuration changes:\n")); + GNUNET_CONFIGURATION_iterate_section_values(diff, + "nat", + &auto_conf_iter, + new_cfg); /* If desired, write configuration to file; we write only the changes to the defaults to keep things compact. */ if (write_cfg) - { - struct GNUNET_CONFIGURATION_Handle *def_cfg; - - GNUNET_CONFIGURATION_set_value_string (new_cfg, "ARM", "CONFIG", NULL); - def_cfg = GNUNET_CONFIGURATION_create (); - GNUNET_break (GNUNET_OK == GNUNET_CONFIGURATION_load (def_cfg, NULL)); - if (GNUNET_OK != - GNUNET_CONFIGURATION_write_diffs (def_cfg, new_cfg, cfg_file)) { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - _ ("Failed to write configuration to `%s'\n"), - cfg_file); - global_ret = 1; + struct GNUNET_CONFIGURATION_Handle *def_cfg; + + GNUNET_CONFIGURATION_set_value_string(new_cfg, "ARM", "CONFIG", NULL); + def_cfg = GNUNET_CONFIGURATION_create(); + GNUNET_break(GNUNET_OK == GNUNET_CONFIGURATION_load(def_cfg, NULL)); + if (GNUNET_OK != + GNUNET_CONFIGURATION_write_diffs(def_cfg, new_cfg, cfg_file)) + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + _("Failed to write configuration to `%s'\n"), + cfg_file); + global_ret = 1; + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + _("Wrote updated configuration to `%s'\n"), + cfg_file); + } + GNUNET_CONFIGURATION_destroy(def_cfg); } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - _ ("Wrote updated configuration to `%s'\n"), - cfg_file); - } - GNUNET_CONFIGURATION_destroy (def_cfg); - } if (NULL != new_cfg) - GNUNET_CONFIGURATION_destroy (new_cfg); - test_finished (); + GNUNET_CONFIGURATION_destroy(new_cfg); + test_finished(); } @@ -228,11 +232,11 @@ auto_config_cb (void *cls, * @param result #GNUNET_NAT_ERROR_SUCCESS on success, otherwise the specific error code */ static void -test_report_cb (void *cls, enum GNUNET_NAT_StatusCode result) +test_report_cb(void *cls, enum GNUNET_NAT_StatusCode result) { nt = NULL; - printf ("NAT test result: %s\n", GNUNET_NAT_AUTO_status2string (result)); - test_finished (); + printf("NAT test result: %s\n", GNUNET_NAT_AUTO_status2string(result)); + test_finished(); } @@ -242,18 +246,18 @@ test_report_cb (void *cls, enum GNUNET_NAT_StatusCode result) * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { if (NULL != ah) - { - GNUNET_NAT_AUTO_autoconfig_cancel (ah); - ah = NULL; - } + { + GNUNET_NAT_AUTO_autoconfig_cancel(ah); + ah = NULL; + } if (NULL != nt) - { - GNUNET_NAT_AUTO_test_stop (nt); - nt = NULL; - } + { + GNUNET_NAT_AUTO_test_stop(nt); + nt = NULL; + } } @@ -266,29 +270,29 @@ do_shutdown (void *cls) * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { cfg_file = cfgfile; cfg = c; - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); if (do_auto) - { - ah = GNUNET_NAT_AUTO_autoconfig_start (c, &auto_config_cb, NULL); - } + { + ah = GNUNET_NAT_AUTO_autoconfig_start(c, &auto_config_cb, NULL); + } if (use_tcp && use_udp) - { - if (do_auto) + { + if (do_auto) + return; + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, "Cannot use TCP and UDP\n"); + global_ret = 1; return; - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, "Cannot use TCP and UDP\n"); - global_ret = 1; - return; - } + } proto = 0; if (use_tcp) proto = IPPROTO_TCP; @@ -296,14 +300,14 @@ run (void *cls, proto = IPPROTO_UDP; if (NULL != section_name) - { - nt = GNUNET_NAT_AUTO_test_start (c, - proto, - section_name, - &test_report_cb, - NULL); - } - test_finished (); + { + nt = GNUNET_NAT_AUTO_test_start(c, + proto, + section_name, + &test_report_cb, + NULL); + } + test_finished(); } @@ -315,47 +319,47 @@ run (void *cls, * @return 0 on success, -1 on error */ int -main (int argc, char *const argv[]) +main(int argc, char *const argv[]) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_flag ('a', - "auto", - gettext_noop ("run autoconfiguration"), - &do_auto), - - GNUNET_GETOPT_option_string ( - 'S', - "section", - "NAME", - gettext_noop ( - "section name providing the configuration for the adapter"), - §ion_name), - - GNUNET_GETOPT_option_flag ('t', "tcp", gettext_noop ("use TCP"), &use_tcp), - - GNUNET_GETOPT_option_flag ('u', "udp", gettext_noop ("use UDP"), &use_udp), - - GNUNET_GETOPT_option_flag ( - 'w', - "write", - gettext_noop ("write configuration file (for autoconfiguration)"), - &write_cfg), - GNUNET_GETOPT_OPTION_END}; - - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + { GNUNET_GETOPT_option_flag('a', + "auto", + gettext_noop("run autoconfiguration"), + &do_auto), + + GNUNET_GETOPT_option_string( + 'S', + "section", + "NAME", + gettext_noop( + "section name providing the configuration for the adapter"), + §ion_name), + + GNUNET_GETOPT_option_flag('t', "tcp", gettext_noop("use TCP"), &use_tcp), + + GNUNET_GETOPT_option_flag('u', "udp", gettext_noop("use UDP"), &use_udp), + + GNUNET_GETOPT_option_flag( + 'w', + "write", + gettext_noop("write configuration file (for autoconfiguration)"), + &write_cfg), + GNUNET_GETOPT_OPTION_END }; + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; if (GNUNET_OK != - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-nat-auto [options]", - _ ("GNUnet NAT traversal autoconfiguration"), - options, - &run, - NULL)) - { - global_ret = 1; - } - GNUNET_free ((void *) argv); + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-nat-auto [options]", + _("GNUnet NAT traversal autoconfiguration"), + options, + &run, + NULL)) + { + global_ret = 1; + } + GNUNET_free((void *)argv); return global_ret; } diff --git a/src/nat-auto/gnunet-nat-auto_legacy.c b/src/nat-auto/gnunet-nat-auto_legacy.c index 93b544343..333e75529 100644 --- a/src/nat-auto/gnunet-nat-auto_legacy.c +++ b/src/nat-auto/gnunet-nat-auto_legacy.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nat/nat_test.c @@ -28,16 +28,15 @@ #include "gnunet_nat_lib.h" #include "nat.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "nat", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "nat", __VA_ARGS__) #define NAT_SERVER_TIMEOUT \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30) /** * Entry we keep for each incoming connection. */ -struct NatActivity -{ +struct NatActivity { /** * This is a doubly-linked list. */ @@ -68,8 +67,7 @@ struct NatActivity /** * Entry we keep for each connection to the gnunet-nat-service. */ -struct ClientActivity -{ +struct ClientActivity { /** * This is a doubly-linked list. */ @@ -95,9 +93,7 @@ struct ClientActivity /** * Handle to a NAT test. */ -struct GNUNET_NAT_Test -{ - +struct GNUNET_NAT_Test { /** * Configuration used */ @@ -184,22 +180,22 @@ struct GNUNET_NAT_Test * @param addrlen actual lenght of the @a addr */ static void -reversal_cb (void *cls, const struct sockaddr *addr, socklen_t addrlen) +reversal_cb(void *cls, const struct sockaddr *addr, socklen_t addrlen) { struct GNUNET_NAT_Test *h = cls; const struct sockaddr_in *sa; - if (sizeof (struct sockaddr_in) != addrlen) + if (sizeof(struct sockaddr_in) != addrlen) return; - sa = (const struct sockaddr_in *) addr; + sa = (const struct sockaddr_in *)addr; if (h->data != sa->sin_port) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received connection reversal request for wrong port\n"); - return; /* wrong port */ - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received connection reversal request for wrong port\n"); + return; /* wrong port */ + } /* report success */ - h->report (h->report_cls, GNUNET_NAT_ERROR_SUCCESS); + h->report(h->report_cls, GNUNET_NAT_ERROR_SUCCESS); } @@ -210,31 +206,31 @@ reversal_cb (void *cls, const struct sockaddr *addr, socklen_t addrlen) * @param cls the `struct GNUNET_NAT_Test` */ static void -do_udp_read (void *cls) +do_udp_read(void *cls) { struct GNUNET_NAT_Test *tst = cls; uint16_t data; const struct GNUNET_SCHEDULER_TaskContext *tc; - tc = GNUNET_SCHEDULER_get_task_context (); - tst->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - tst->lsock, - &do_udp_read, - tst); + tc = GNUNET_SCHEDULER_get_task_context(); + tst->ltask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + tst->lsock, + &do_udp_read, + tst); if ((NULL != tc->write_ready) && - (GNUNET_NETWORK_fdset_isset (tc->read_ready, tst->lsock)) && - (sizeof (data) == - GNUNET_NETWORK_socket_recv (tst->lsock, &data, sizeof (data)))) - { - if (data == tst->data) - tst->report (tst->report_cls, GNUNET_NAT_ERROR_SUCCESS); - else - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received data mismatches expected value\n"); - } + (GNUNET_NETWORK_fdset_isset(tc->read_ready, tst->lsock)) && + (sizeof(data) == + GNUNET_NETWORK_socket_recv(tst->lsock, &data, sizeof(data)))) + { + if (data == tst->data) + tst->report(tst->report_cls, GNUNET_NAT_ERROR_SUCCESS); + else + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received data mismatches expected value\n"); + } else - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Failed to receive data from inbound connection\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Failed to receive data from inbound connection\n"); } @@ -245,33 +241,33 @@ do_udp_read (void *cls) * @param cls the `struct NatActivity` */ static void -do_read (void *cls) +do_read(void *cls) { struct NatActivity *na = cls; struct GNUNET_NAT_Test *tst; uint16_t data; const struct GNUNET_SCHEDULER_TaskContext *tc; - tc = GNUNET_SCHEDULER_get_task_context (); + tc = GNUNET_SCHEDULER_get_task_context(); na->rtask = NULL; tst = na->h; - GNUNET_CONTAINER_DLL_remove (tst->na_head, tst->na_tail, na); + GNUNET_CONTAINER_DLL_remove(tst->na_head, tst->na_tail, na); if ((NULL != tc->write_ready) && - (GNUNET_NETWORK_fdset_isset (tc->read_ready, na->sock)) && - (sizeof (data) == - GNUNET_NETWORK_socket_recv (na->sock, &data, sizeof (data)))) - { - if (data == tst->data) - tst->report (tst->report_cls, GNUNET_NAT_ERROR_SUCCESS); - else - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received data does not match expected value\n"); - } + (GNUNET_NETWORK_fdset_isset(tc->read_ready, na->sock)) && + (sizeof(data) == + GNUNET_NETWORK_socket_recv(na->sock, &data, sizeof(data)))) + { + if (data == tst->data) + tst->report(tst->report_cls, GNUNET_NAT_ERROR_SUCCESS); + else + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received data does not match expected value\n"); + } else - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Failed to receive data from inbound connection\n"); - GNUNET_NETWORK_socket_close (na->sock); - GNUNET_free (na); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Failed to receive data from inbound connection\n"); + GNUNET_NETWORK_socket_close(na->sock); + GNUNET_free(na); } @@ -282,32 +278,32 @@ do_read (void *cls) * @param cls the `struct GNUNET_NAT_Test` */ static void -do_accept (void *cls) +do_accept(void *cls) { struct GNUNET_NAT_Test *tst = cls; struct GNUNET_NETWORK_Handle *s; struct NatActivity *wl; - tst->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - tst->lsock, - &do_accept, - tst); - s = GNUNET_NETWORK_socket_accept (tst->lsock, NULL, NULL); + tst->ltask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + tst->lsock, + &do_accept, + tst); + s = GNUNET_NETWORK_socket_accept(tst->lsock, NULL, NULL); if (NULL == s) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "accept"); - return; /* odd error */ - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got an inbound connection, waiting for data\n"); - wl = GNUNET_new (struct NatActivity); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_INFO, "accept"); + return; /* odd error */ + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got an inbound connection, waiting for data\n"); + wl = GNUNET_new(struct NatActivity); wl->sock = s; wl->h = tst; - wl->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - wl->sock, - &do_read, - wl); - GNUNET_CONTAINER_DLL_insert (tst->na_head, tst->na_tail, wl); + wl->rtask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + wl->sock, + &do_read, + wl); + GNUNET_CONTAINER_DLL_insert(tst->na_head, tst->na_tail, wl); } @@ -319,14 +315,14 @@ do_accept (void *cls) * @param error error code */ static void -mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct ClientActivity *ca = cls; struct GNUNET_NAT_Test *tst = ca->h; - GNUNET_CONTAINER_DLL_remove (tst->ca_head, tst->ca_tail, ca); - GNUNET_MQ_destroy (ca->mq); - GNUNET_free (ca); + GNUNET_CONTAINER_DLL_remove(tst->ca_head, tst->ca_tail, ca); + GNUNET_MQ_destroy(ca->mq); + GNUNET_free(ca); } @@ -340,10 +336,10 @@ mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @param addrlen actual length of the @a addr */ static void -addr_cb (void *cls, - int add_remove, - const struct sockaddr *addr, - socklen_t addrlen) +addr_cb(void *cls, + int add_remove, + const struct sockaddr *addr, + socklen_t addrlen) { struct GNUNET_NAT_Test *h = cls; struct ClientActivity *ca; @@ -353,39 +349,39 @@ addr_cb (void *cls, if (GNUNET_YES != add_remove) return; - if (addrlen != sizeof (struct sockaddr_in)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "NAT test ignores IPv6 address `%s' returned from NAT library\n", - GNUNET_a2s (addr, addrlen)); - return; /* ignore IPv6 here */ - } - LOG (GNUNET_ERROR_TYPE_INFO, - "Asking gnunet-nat-server to connect to `%s'\n", - GNUNET_a2s (addr, addrlen)); - - ca = GNUNET_new (struct ClientActivity); + if (addrlen != sizeof(struct sockaddr_in)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "NAT test ignores IPv6 address `%s' returned from NAT library\n", + GNUNET_a2s(addr, addrlen)); + return; /* ignore IPv6 here */ + } + LOG(GNUNET_ERROR_TYPE_INFO, + "Asking gnunet-nat-server to connect to `%s'\n", + GNUNET_a2s(addr, addrlen)); + + ca = GNUNET_new(struct ClientActivity); ca->h = h; - ca->mq = GNUNET_CLIENT_connect (h->cfg, - "gnunet-nat-server", - NULL, - &mq_error_handler, - ca); + ca->mq = GNUNET_CLIENT_connect(h->cfg, + "gnunet-nat-server", + NULL, + &mq_error_handler, + ca); if (NULL == ca->mq) - { - GNUNET_free (ca); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to connect to `gnunet-nat-server'\n")); - return; - } - GNUNET_CONTAINER_DLL_insert (h->ca_head, h->ca_tail, ca); - sa = (const struct sockaddr_in *) addr; - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_NAT_TEST); + { + GNUNET_free(ca); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to `gnunet-nat-server'\n")); + return; + } + GNUNET_CONTAINER_DLL_insert(h->ca_head, h->ca_tail, ca); + sa = (const struct sockaddr_in *)addr; + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_NAT_TEST); msg->dst_ipv4 = sa->sin_addr.s_addr; msg->dport = sa->sin_port; msg->data = h->data; - msg->is_tcp = htonl ((uint32_t) h->is_tcp); - GNUNET_MQ_send (ca->mq, env); + msg->is_tcp = htonl((uint32_t)h->is_tcp); + GNUNET_MQ_send(ca->mq, env); } @@ -398,15 +394,15 @@ addr_cb (void *cls, * @param cls handle to the timed out NAT test */ static void -do_timeout (void *cls) +do_timeout(void *cls) { struct GNUNET_NAT_Test *nh = cls; nh->ttask = NULL; - nh->report (nh->report_cls, - (GNUNET_NAT_ERROR_SUCCESS == nh->status) - ? GNUNET_NAT_ERROR_TIMEOUT - : nh->status); + nh->report(nh->report_cls, + (GNUNET_NAT_ERROR_SUCCESS == nh->status) + ? GNUNET_NAT_ERROR_TIMEOUT + : nh->status); } @@ -426,27 +422,27 @@ do_timeout (void *cls) * @return handle to cancel NAT test or NULL. The error is always indicated via the report callback */ struct GNUNET_NAT_Test * -GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - int is_tcp, - uint16_t bnd_port, - uint16_t adv_port, - struct GNUNET_TIME_Relative timeout, - GNUNET_NAT_TestCallback report, - void *report_cls) +GNUNET_NAT_test_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + int is_tcp, + uint16_t bnd_port, + uint16_t adv_port, + struct GNUNET_TIME_Relative timeout, + GNUNET_NAT_TestCallback report, + void *report_cls) { struct GNUNET_NAT_Test *nh; struct sockaddr_in sa; - const struct sockaddr *addrs[] = {(const struct sockaddr *) &sa}; - const socklen_t addrlens[] = {sizeof (sa)}; + const struct sockaddr *addrs[] = { (const struct sockaddr *)&sa }; + const socklen_t addrlens[] = { sizeof(sa) }; - memset (&sa, 0, sizeof (sa)); + memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; - sa.sin_port = htons (bnd_port); + sa.sin_port = htons(bnd_port); #if HAVE_SOCKADDR_IN_SIN_LEN - sa.sin_len = sizeof (sa); + sa.sin_len = sizeof(sa); #endif - nh = GNUNET_new (struct GNUNET_NAT_Test); + nh = GNUNET_new(struct GNUNET_NAT_Test); nh->cfg = cfg; nh->is_tcp = is_tcp; nh->data = bnd_port; @@ -455,93 +451,93 @@ GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg, nh->report_cls = report_cls; nh->status = GNUNET_NAT_ERROR_SUCCESS; if (0 == bnd_port) - { - nh->nat = GNUNET_NAT_register (cfg, - is_tcp, - 0, - 0, - NULL, - NULL, - &addr_cb, - &reversal_cb, - nh, - NULL); - } - else - { - nh->lsock = - GNUNET_NETWORK_socket_create (AF_INET, - (is_tcp == GNUNET_YES) ? SOCK_STREAM - : SOCK_DGRAM, - 0); - if ((nh->lsock == NULL) || - (GNUNET_OK != GNUNET_NETWORK_socket_bind (nh->lsock, - (const struct sockaddr *) &sa, - sizeof (sa)))) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to create listen socket bound to `%s' for NAT test: %s\n"), - GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)), - strerror (errno)); - if (NULL != nh->lsock) - { - GNUNET_NETWORK_socket_close (nh->lsock); - nh->lsock = NULL; - } - nh->status = GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR; - nh->ttask = GNUNET_SCHEDULER_add_now (&do_timeout, nh); - return nh; - } - if (GNUNET_YES == is_tcp) - { - GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_listen (nh->lsock, 5)); - nh->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - nh->lsock, - &do_accept, - nh); - } - else { - nh->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - nh->lsock, - &do_udp_read, - nh); + nh->nat = GNUNET_NAT_register(cfg, + is_tcp, + 0, + 0, + NULL, + NULL, + &addr_cb, + &reversal_cb, + nh, + NULL); } - LOG (GNUNET_ERROR_TYPE_INFO, - "NAT test listens on port %u (%s)\n", - bnd_port, - (GNUNET_YES == is_tcp) ? "tcp" : "udp"); - nh->nat = GNUNET_NAT_register (cfg, - is_tcp, - adv_port, - 1, - addrs, - addrlens, - &addr_cb, - NULL, - nh, - NULL); - if (NULL == nh->nat) + else { - LOG (GNUNET_ERROR_TYPE_INFO, - _ ("NAT test failed to start NAT library\n")); - if (NULL != nh->ltask) - { - GNUNET_SCHEDULER_cancel (nh->ltask); - nh->ltask = NULL; - } - if (NULL != nh->lsock) - { - GNUNET_NETWORK_socket_close (nh->lsock); - nh->lsock = NULL; - } - nh->status = GNUNET_NAT_ERROR_NAT_REGISTER_FAILED; - nh->ttask = GNUNET_SCHEDULER_add_now (&do_timeout, nh); - return nh; + nh->lsock = + GNUNET_NETWORK_socket_create(AF_INET, + (is_tcp == GNUNET_YES) ? SOCK_STREAM + : SOCK_DGRAM, + 0); + if ((nh->lsock == NULL) || + (GNUNET_OK != GNUNET_NETWORK_socket_bind(nh->lsock, + (const struct sockaddr *)&sa, + sizeof(sa)))) + { + GNUNET_log( + GNUNET_ERROR_TYPE_ERROR, + _("Failed to create listen socket bound to `%s' for NAT test: %s\n"), + GNUNET_a2s((const struct sockaddr *)&sa, sizeof(sa)), + strerror(errno)); + if (NULL != nh->lsock) + { + GNUNET_NETWORK_socket_close(nh->lsock); + nh->lsock = NULL; + } + nh->status = GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR; + nh->ttask = GNUNET_SCHEDULER_add_now(&do_timeout, nh); + return nh; + } + if (GNUNET_YES == is_tcp) + { + GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_listen(nh->lsock, 5)); + nh->ltask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + nh->lsock, + &do_accept, + nh); + } + else + { + nh->ltask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + nh->lsock, + &do_udp_read, + nh); + } + LOG(GNUNET_ERROR_TYPE_INFO, + "NAT test listens on port %u (%s)\n", + bnd_port, + (GNUNET_YES == is_tcp) ? "tcp" : "udp"); + nh->nat = GNUNET_NAT_register(cfg, + is_tcp, + adv_port, + 1, + addrs, + addrlens, + &addr_cb, + NULL, + nh, + NULL); + if (NULL == nh->nat) + { + LOG(GNUNET_ERROR_TYPE_INFO, + _("NAT test failed to start NAT library\n")); + if (NULL != nh->ltask) + { + GNUNET_SCHEDULER_cancel(nh->ltask); + nh->ltask = NULL; + } + if (NULL != nh->lsock) + { + GNUNET_NETWORK_socket_close(nh->lsock); + nh->lsock = NULL; + } + nh->status = GNUNET_NAT_ERROR_NAT_REGISTER_FAILED; + nh->ttask = GNUNET_SCHEDULER_add_now(&do_timeout, nh); + return nh; + } } - } - nh->ttask = GNUNET_SCHEDULER_add_delayed (timeout, &do_timeout, nh); + nh->ttask = GNUNET_SCHEDULER_add_delayed(timeout, &do_timeout, nh); return nh; } @@ -552,46 +548,46 @@ GNUNET_NAT_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param tst test to stop. */ void -GNUNET_NAT_test_stop (struct GNUNET_NAT_Test *tst) +GNUNET_NAT_test_stop(struct GNUNET_NAT_Test *tst) { struct NatActivity *pos; struct ClientActivity *cpos; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Stopping NAT test\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Stopping NAT test\n"); while (NULL != (cpos = tst->ca_head)) - { - GNUNET_CONTAINER_DLL_remove (tst->ca_head, tst->ca_tail, cpos); - GNUNET_MQ_destroy (cpos->mq); - GNUNET_free (cpos); - } + { + GNUNET_CONTAINER_DLL_remove(tst->ca_head, tst->ca_tail, cpos); + GNUNET_MQ_destroy(cpos->mq); + GNUNET_free(cpos); + } while (NULL != (pos = tst->na_head)) - { - GNUNET_CONTAINER_DLL_remove (tst->na_head, tst->na_tail, pos); - GNUNET_SCHEDULER_cancel (pos->rtask); - GNUNET_NETWORK_socket_close (pos->sock); - GNUNET_free (pos); - } + { + GNUNET_CONTAINER_DLL_remove(tst->na_head, tst->na_tail, pos); + GNUNET_SCHEDULER_cancel(pos->rtask); + GNUNET_NETWORK_socket_close(pos->sock); + GNUNET_free(pos); + } if (NULL != tst->ttask) - { - GNUNET_SCHEDULER_cancel (tst->ttask); - tst->ttask = NULL; - } + { + GNUNET_SCHEDULER_cancel(tst->ttask); + tst->ttask = NULL; + } if (NULL != tst->ltask) - { - GNUNET_SCHEDULER_cancel (tst->ltask); - tst->ltask = NULL; - } + { + GNUNET_SCHEDULER_cancel(tst->ltask); + tst->ltask = NULL; + } if (NULL != tst->lsock) - { - GNUNET_NETWORK_socket_close (tst->lsock); - tst->lsock = NULL; - } + { + GNUNET_NETWORK_socket_close(tst->lsock); + tst->lsock = NULL; + } if (NULL != tst->nat) - { - GNUNET_NAT_unregister (tst->nat); - tst->nat = NULL; - } - GNUNET_free (tst); + { + GNUNET_NAT_unregister(tst->nat); + tst->nat = NULL; + } + GNUNET_free(tst); } /* end of nat_test.c */ diff --git a/src/nat-auto/gnunet-nat-server.c b/src/nat-auto/gnunet-nat-server.c index c58768982..db44d7629 100644 --- a/src/nat-auto/gnunet-nat-server.c +++ b/src/nat-auto/gnunet-nat-server.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/nat/gnunet-nat-server.c @@ -33,8 +33,7 @@ /** * Information we track per client. */ -struct ClientData -{ +struct ClientData { /** * Timeout task. */ @@ -61,9 +60,9 @@ static const struct GNUNET_CONFIGURATION_Handle *cfg; * @param is_tcp mark for TCP (#GNUNET_YES) or UDP (#GNUNET_NO) */ static void -try_anat (uint32_t dst_ipv4, - uint16_t dport, - int is_tcp) +try_anat(uint32_t dst_ipv4, + uint16_t dport, + int is_tcp) { struct GNUNET_NAT_Handle *h; struct sockaddr_in lsa; @@ -71,45 +70,44 @@ try_anat (uint32_t dst_ipv4, const struct sockaddr *sa; socklen_t sa_len; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Asking for connection reversal with %x and code %u\n", - (unsigned int) dst_ipv4, - (unsigned int) dport); - memset (&lsa, 0, sizeof (lsa)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Asking for connection reversal with %x and code %u\n", + (unsigned int)dst_ipv4, + (unsigned int)dport); + memset(&lsa, 0, sizeof(lsa)); lsa.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN - lsa.sin_len = sizeof (sa); + lsa.sin_len = sizeof(sa); #endif lsa.sin_addr.s_addr = 0; - lsa.sin_port = htons (dport); - memset (&rsa, 0, sizeof (rsa)); + lsa.sin_port = htons(dport); + memset(&rsa, 0, sizeof(rsa)); rsa.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN - rsa.sin_len = sizeof (sa); + rsa.sin_len = sizeof(sa); #endif rsa.sin_addr.s_addr = dst_ipv4; - rsa.sin_port = htons (dport); - sa_len = sizeof (lsa); - sa = (const struct sockaddr *) &lsa; - h = GNUNET_NAT_register (cfg, - "none", - is_tcp ? IPPROTO_TCP : IPPROTO_UDP, - 1, - &sa, - &sa_len, - NULL, NULL, NULL); - GNUNET_NAT_request_reversal (h, - &lsa, - &rsa); - GNUNET_NAT_unregister (h); + rsa.sin_port = htons(dport); + sa_len = sizeof(lsa); + sa = (const struct sockaddr *)&lsa; + h = GNUNET_NAT_register(cfg, + "none", + is_tcp ? IPPROTO_TCP : IPPROTO_UDP, + 1, + &sa, + &sa_len, + NULL, NULL, NULL); + GNUNET_NAT_request_reversal(h, + &lsa, + &rsa); + GNUNET_NAT_unregister(h); } /** * Closure for #tcp_send. */ -struct TcpContext -{ +struct TcpContext { /** * TCP socket. */ @@ -129,24 +127,24 @@ struct TcpContext * @param cls the `struct TcpContext` */ static void -tcp_send (void *cls) +tcp_send(void *cls) { struct TcpContext *ctx = cls; const struct GNUNET_SCHEDULER_TaskContext *tc; - tc = GNUNET_SCHEDULER_get_task_context (); + tc = GNUNET_SCHEDULER_get_task_context(); if ((NULL != tc->write_ready) && - (GNUNET_NETWORK_fdset_isset (tc->write_ready, ctx->s))) - { - if (-1 == - GNUNET_NETWORK_socket_send (ctx->s, &ctx->data, sizeof (ctx->data))) + (GNUNET_NETWORK_fdset_isset(tc->write_ready, ctx->s))) { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_DEBUG, "send"); + if (-1 == + GNUNET_NETWORK_socket_send(ctx->s, &ctx->data, sizeof(ctx->data))) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_DEBUG, "send"); + } + GNUNET_NETWORK_socket_shutdown(ctx->s, SHUT_RDWR); } - GNUNET_NETWORK_socket_shutdown (ctx->s, SHUT_RDWR); - } - GNUNET_NETWORK_socket_close (ctx->s); - GNUNET_free (ctx); + GNUNET_NETWORK_socket_close(ctx->s); + GNUNET_free(ctx); } @@ -159,52 +157,52 @@ tcp_send (void *cls) * @param data data to send */ static void -try_send_tcp (uint32_t dst_ipv4, - uint16_t dport, - uint16_t data) +try_send_tcp(uint32_t dst_ipv4, + uint16_t dport, + uint16_t data) { struct GNUNET_NETWORK_Handle *s; struct sockaddr_in sa; struct TcpContext *ctx; - s = GNUNET_NETWORK_socket_create (AF_INET, - SOCK_STREAM, - 0); + s = GNUNET_NETWORK_socket_create(AF_INET, + SOCK_STREAM, + 0); if (NULL == s) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "socket"); - return; - } - memset (&sa, 0, sizeof (sa)); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "socket"); + return; + } + memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN - sa.sin_len = sizeof (sa); + sa.sin_len = sizeof(sa); #endif sa.sin_addr.s_addr = dst_ipv4; - sa.sin_port = htons (dport); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending TCP message to `%s'\n", - GNUNET_a2s ((struct sockaddr *) &sa, - sizeof (sa))); - if ( (GNUNET_OK != - GNUNET_NETWORK_socket_connect (s, - (const struct sockaddr *) &sa, - sizeof (sa))) && - (errno != EINPROGRESS) ) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "connect"); - GNUNET_NETWORK_socket_close (s); - return; - } - ctx = GNUNET_new (struct TcpContext); + sa.sin_port = htons(dport); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending TCP message to `%s'\n", + GNUNET_a2s((struct sockaddr *)&sa, + sizeof(sa))); + if ((GNUNET_OK != + GNUNET_NETWORK_socket_connect(s, + (const struct sockaddr *)&sa, + sizeof(sa))) && + (errno != EINPROGRESS)) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "connect"); + GNUNET_NETWORK_socket_close(s); + return; + } + ctx = GNUNET_new(struct TcpContext); ctx->s = s; ctx->data = data; - GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_SECONDS, - s, - &tcp_send, - ctx); + GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_SECONDS, + s, + &tcp_send, + ctx); } @@ -217,42 +215,42 @@ try_send_tcp (uint32_t dst_ipv4, * @param data data to send */ static void -try_send_udp (uint32_t dst_ipv4, - uint16_t dport, - uint16_t data) +try_send_udp(uint32_t dst_ipv4, + uint16_t dport, + uint16_t data) { struct GNUNET_NETWORK_Handle *s; struct sockaddr_in sa; - s = GNUNET_NETWORK_socket_create (AF_INET, - SOCK_DGRAM, - 0); + s = GNUNET_NETWORK_socket_create(AF_INET, + SOCK_DGRAM, + 0); if (NULL == s) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "socket"); - return; - } - memset (&sa, 0, sizeof (sa)); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "socket"); + return; + } + memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN - sa.sin_len = sizeof (sa); + sa.sin_len = sizeof(sa); #endif sa.sin_addr.s_addr = dst_ipv4; - sa.sin_port = htons (dport); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending UDP packet to `%s'\n", - GNUNET_a2s ((struct sockaddr *) &sa, - sizeof (sa))); + sa.sin_port = htons(dport); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending UDP packet to `%s'\n", + GNUNET_a2s((struct sockaddr *)&sa, + sizeof(sa))); if (-1 == - GNUNET_NETWORK_socket_sendto (s, - &data, - sizeof (data), - (const struct sockaddr *) &sa, - sizeof (sa))) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, - "sendto"); - GNUNET_NETWORK_socket_close (s); + GNUNET_NETWORK_socket_sendto(s, + &data, + sizeof(data), + (const struct sockaddr *)&sa, + sizeof(sa))) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, + "sendto"); + GNUNET_NETWORK_socket_close(s); } @@ -264,28 +262,28 @@ try_send_udp (uint32_t dst_ipv4, * @param msg message with details about what to test */ static void -handle_test (void *cls, - const struct GNUNET_NAT_AUTO_TestMessage *tm) +handle_test(void *cls, + const struct GNUNET_NAT_AUTO_TestMessage *tm) { struct ClientData *cd = cls; uint16_t dport; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received test request\n"); - dport = ntohs (tm->dport); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received test request\n"); + dport = ntohs(tm->dport); if (0 == dport) - try_anat (tm->dst_ipv4, - ntohs (tm->data), - (int) ntohl (tm->is_tcp)); - else if (GNUNET_YES == ntohl (tm->is_tcp)) - try_send_tcp (tm->dst_ipv4, - dport, - tm->data); + try_anat(tm->dst_ipv4, + ntohs(tm->data), + (int)ntohl(tm->is_tcp)); + else if (GNUNET_YES == ntohl(tm->is_tcp)) + try_send_tcp(tm->dst_ipv4, + dport, + tm->data); else - try_send_udp (tm->dst_ipv4, - dport, - tm->data); - GNUNET_SERVICE_client_drop (cd->client); + try_send_udp(tm->dst_ipv4, + dport, + tm->data); + GNUNET_SERVICE_client_drop(cd->client); } @@ -297,9 +295,9 @@ handle_test (void *cls, * @param srv service handle */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *srv) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *srv) { cfg = c; } @@ -311,12 +309,12 @@ run (void *cls, * @param cls our `struct ClientData` of a client to drop */ static void -force_timeout (void *cls) +force_timeout(void *cls) { struct ClientData *cd = cls; cd->tt = NULL; - GNUNET_SERVICE_client_drop (cd->client); + GNUNET_SERVICE_client_drop(cd->client); } @@ -330,17 +328,17 @@ force_timeout (void *cls) * @return our `struct ClientData` */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + struct GNUNET_MQ_Handle *mq) { struct ClientData *cd; - cd = GNUNET_new (struct ClientData); + cd = GNUNET_new(struct ClientData); cd->client = c; - cd->tt = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &force_timeout, - cd); + cd->tt = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &force_timeout, + cd); return cd; } @@ -353,15 +351,15 @@ client_connect_cb (void *cls, * @param internal_cls our `struct ClientData` */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - void *internal_cls) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + void *internal_cls) { struct ClientData *cd = internal_cls; if (NULL != cd->tt) - GNUNET_SCHEDULER_cancel (cd->tt); - GNUNET_free (cd); + GNUNET_SCHEDULER_cancel(cd->tt); + GNUNET_free(cd); } @@ -369,17 +367,17 @@ client_disconnect_cb (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("nat-server", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_fixed_size (test, - GNUNET_MESSAGE_TYPE_NAT_TEST, - struct GNUNET_NAT_AUTO_TestMessage, - NULL), - GNUNET_MQ_handler_end ()); + ("nat-server", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_fixed_size(test, + GNUNET_MESSAGE_TYPE_NAT_TEST, + struct GNUNET_NAT_AUTO_TestMessage, + NULL), + GNUNET_MQ_handler_end()); #if defined(LINUX) && defined(__GLIBC__) @@ -389,11 +387,11 @@ GNUNET_SERVICE_MAIN * MINIMIZE heap size (way below 128k) since this process doesn't need much. */ void __attribute__ ((constructor)) -GNUNET_ARM_memory_init () +GNUNET_ARM_memory_init() { - mallopt (M_TRIM_THRESHOLD, 4 * 1024); - mallopt (M_TOP_PAD, 1 * 1024); - malloc_trim (0); + mallopt(M_TRIM_THRESHOLD, 4 * 1024); + mallopt(M_TOP_PAD, 1 * 1024); + malloc_trim(0); } #endif diff --git a/src/nat-auto/gnunet-service-nat-auto.c b/src/nat-auto/gnunet-service-nat-auto.c index 0b2995441..199a759ea 100644 --- a/src/nat-auto/gnunet-service-nat-auto.c +++ b/src/nat-auto/gnunet-service-nat-auto.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2016, 2017 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet. + Copyright (C) 2016, 2017 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -45,15 +45,13 @@ /** * How long do we wait until we forcefully terminate autoconfiguration? */ -#define AUTOCONFIG_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define AUTOCONFIG_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) /** * Internal data structure we track for each of our clients. */ -struct ClientHandle -{ - +struct ClientHandle { /** * Kept in a DLL. */ @@ -79,8 +77,7 @@ struct ClientHandle /** * Context for autoconfiguration operations. */ -struct AutoconfigContext -{ +struct AutoconfigContext { /** * Kept in a DLL. */ @@ -170,8 +167,8 @@ static struct GNUNET_STATISTICS_Handle *stats; * @return #GNUNET_OK if message is well-formed */ static int -check_autoconfig_request (void *cls, - const struct GNUNET_NAT_AUTO_AutoconfigRequestMessage *message) +check_autoconfig_request(void *cls, + const struct GNUNET_NAT_AUTO_AutoconfigRequestMessage *message) { return GNUNET_OK; /* checked later */ } @@ -183,13 +180,13 @@ check_autoconfig_request (void *cls, * @param ac autoconfiguration to terminate activities for */ static void -terminate_ac_activities (struct AutoconfigContext *ac) +terminate_ac_activities(struct AutoconfigContext *ac) { if (NULL != ac->timeout_task) - { - GNUNET_SCHEDULER_cancel (ac->timeout_task); - ac->timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(ac->timeout_task); + ac->timeout_task = NULL; + } } @@ -200,7 +197,7 @@ terminate_ac_activities (struct AutoconfigContext *ac) * @param cls the `struct AutoconfigContext` to conclude */ static void -conclude_autoconfig_request (void *cls) +conclude_autoconfig_request(void *cls) { struct AutoconfigContext *ac = cls; struct ClientHandle *ch = ac->ch; @@ -211,34 +208,34 @@ conclude_autoconfig_request (void *cls) struct GNUNET_CONFIGURATION_Handle *diff; ac->timeout_task = NULL; - terminate_ac_activities (ac); + terminate_ac_activities(ac); /* Send back response */ - diff = GNUNET_CONFIGURATION_get_diff (ac->orig, - ac->c); - buf = GNUNET_CONFIGURATION_serialize (diff, - &c_size); - GNUNET_CONFIGURATION_destroy (diff); - env = GNUNET_MQ_msg_extra (arm, - c_size, - GNUNET_MESSAGE_TYPE_NAT_AUTO_CFG_RESULT); - arm->status_code = htonl ((uint32_t) ac->status_code); - arm->type = htonl ((uint32_t) ac->type); - GNUNET_memcpy (&arm[1], - buf, - c_size); - GNUNET_free (buf); - GNUNET_MQ_send (ch->mq, - env); + diff = GNUNET_CONFIGURATION_get_diff(ac->orig, + ac->c); + buf = GNUNET_CONFIGURATION_serialize(diff, + &c_size); + GNUNET_CONFIGURATION_destroy(diff); + env = GNUNET_MQ_msg_extra(arm, + c_size, + GNUNET_MESSAGE_TYPE_NAT_AUTO_CFG_RESULT); + arm->status_code = htonl((uint32_t)ac->status_code); + arm->type = htonl((uint32_t)ac->type); + GNUNET_memcpy(&arm[1], + buf, + c_size); + GNUNET_free(buf); + GNUNET_MQ_send(ch->mq, + env); /* clean up */ - GNUNET_CONFIGURATION_destroy (ac->orig); - GNUNET_CONFIGURATION_destroy (ac->c); - GNUNET_CONTAINER_DLL_remove (ac_head, - ac_tail, - ac); - GNUNET_free (ac); - GNUNET_SERVICE_client_continue (ch->client); + GNUNET_CONFIGURATION_destroy(ac->orig); + GNUNET_CONFIGURATION_destroy(ac->c); + GNUNET_CONTAINER_DLL_remove(ac_head, + ac_tail, + ac); + GNUNET_free(ac); + GNUNET_SERVICE_client_continue(ch->client); } @@ -249,12 +246,12 @@ conclude_autoconfig_request (void *cls) * @param ac autoconfiguation context to check */ static void -check_autoconfig_finished (struct AutoconfigContext *ac) +check_autoconfig_finished(struct AutoconfigContext *ac) { - GNUNET_SCHEDULER_cancel (ac->timeout_task); + GNUNET_SCHEDULER_cancel(ac->timeout_task); ac->timeout_task - = GNUNET_SCHEDULER_add_now (&conclude_autoconfig_request, - ac); + = GNUNET_SCHEDULER_add_now(&conclude_autoconfig_request, + ac); } @@ -264,26 +261,28 @@ check_autoconfig_finished (struct AutoconfigContext *ac) * @param ac autoconfiguration to update */ static void -update_enable_upnpc_option (struct AutoconfigContext *ac) +update_enable_upnpc_option(struct AutoconfigContext *ac) { switch (ac->enable_upnpc) - { - case GNUNET_YES: - GNUNET_CONFIGURATION_set_value_string (ac->c, - "NAT", - "ENABLE_UPNP", - "YES"); - break; - case GNUNET_NO: - GNUNET_CONFIGURATION_set_value_string (ac->c, - "NAT", - "ENABLE_UPNP", - "NO"); - break; - case GNUNET_SYSERR: - /* We are unsure, do not change option */ - break; - } + { + case GNUNET_YES: + GNUNET_CONFIGURATION_set_value_string(ac->c, + "NAT", + "ENABLE_UPNP", + "YES"); + break; + + case GNUNET_NO: + GNUNET_CONFIGURATION_set_value_string(ac->c, + "NAT", + "ENABLE_UPNP", + "NO"); + break; + + case GNUNET_SYSERR: + /* We are unsure, do not change option */ + break; + } } @@ -295,62 +294,62 @@ update_enable_upnpc_option (struct AutoconfigContext *ac) * @param message the message received */ static void -handle_autoconfig_request (void *cls, - const struct GNUNET_NAT_AUTO_AutoconfigRequestMessage *message) +handle_autoconfig_request(void *cls, + const struct GNUNET_NAT_AUTO_AutoconfigRequestMessage *message) { struct ClientHandle *ch = cls; - size_t left = ntohs (message->header.size) - sizeof (*message); + size_t left = ntohs(message->header.size) - sizeof(*message); struct AutoconfigContext *ac; - ac = GNUNET_new (struct AutoconfigContext); + ac = GNUNET_new(struct AutoconfigContext); ac->status_code = GNUNET_NAT_ERROR_SUCCESS; ac->ch = ch; - ac->c = GNUNET_CONFIGURATION_create (); + ac->c = GNUNET_CONFIGURATION_create(); if (GNUNET_OK != - GNUNET_CONFIGURATION_deserialize (ac->c, - (const char *) &message[1], - left, - NULL)) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (ch->client); - GNUNET_CONFIGURATION_destroy (ac->c); - GNUNET_free (ac); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received REQUEST_AUTO_CONFIG message from client\n"); - - GNUNET_CONTAINER_DLL_insert (ac_head, - ac_tail, - ac); + GNUNET_CONFIGURATION_deserialize(ac->c, + (const char *)&message[1], + left, + NULL)) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(ch->client); + GNUNET_CONFIGURATION_destroy(ac->c); + GNUNET_free(ac); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received REQUEST_AUTO_CONFIG message from client\n"); + + GNUNET_CONTAINER_DLL_insert(ac_head, + ac_tail, + ac); ac->orig - = GNUNET_CONFIGURATION_dup (ac->c); + = GNUNET_CONFIGURATION_dup(ac->c); ac->timeout_task - = GNUNET_SCHEDULER_add_delayed (AUTOCONFIG_TIMEOUT, - &conclude_autoconfig_request, - ac); + = GNUNET_SCHEDULER_add_delayed(AUTOCONFIG_TIMEOUT, + &conclude_autoconfig_request, + ac); ac->enable_upnpc = GNUNET_SYSERR; /* undecided */ /* Probe for upnpc */ if (GNUNET_SYSERR == - GNUNET_OS_check_helper_binary ("upnpc", - GNUNET_NO, - NULL)) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("UPnP client `upnpc` command not found, disabling UPnP\n")); - ac->enable_upnpc = GNUNET_NO; - } + GNUNET_OS_check_helper_binary("upnpc", + GNUNET_NO, + NULL)) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("UPnP client `upnpc` command not found, disabling UPnP\n")); + ac->enable_upnpc = GNUNET_NO; + } else - { - /* We might at some point be behind NAT, try upnpc */ - ac->enable_upnpc = GNUNET_YES; - } - update_enable_upnpc_option (ac); + { + /* We might at some point be behind NAT, try upnpc */ + ac->enable_upnpc = GNUNET_YES; + } + update_enable_upnpc_option(ac); /* Finally, check if we are already done */ - check_autoconfig_finished (ac); + check_autoconfig_finished(ac); } @@ -360,24 +359,24 @@ handle_autoconfig_request (void *cls, * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { struct AutoconfigContext *ac; while (NULL != (ac = ac_head)) - { - GNUNET_CONTAINER_DLL_remove (ac_head, - ac_tail, - ac); - terminate_ac_activities (ac); - GNUNET_free (ac); - } + { + GNUNET_CONTAINER_DLL_remove(ac_head, + ac_tail, + ac); + terminate_ac_activities(ac); + GNUNET_free(ac); + } if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, - GNUNET_NO); - stats = NULL; - } + { + GNUNET_STATISTICS_destroy(stats, + GNUNET_NO); + stats = NULL; + } } @@ -389,15 +388,15 @@ shutdown_task (void *cls) * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *service) { cfg = c; - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); - stats = GNUNET_STATISTICS_create ("nat-auto", - cfg); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); + stats = GNUNET_STATISTICS_create("nat-auto", + cfg); } @@ -410,18 +409,18 @@ run (void *cls, * @return a `struct ClientHandle` */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + struct GNUNET_MQ_Handle *mq) { struct ClientHandle *ch; - ch = GNUNET_new (struct ClientHandle); + ch = GNUNET_new(struct ClientHandle); ch->mq = mq; ch->client = c; - GNUNET_CONTAINER_DLL_insert (ch_head, - ch_tail, - ch); + GNUNET_CONTAINER_DLL_insert(ch_head, + ch_tail, + ch); return ch; } @@ -434,16 +433,16 @@ client_connect_cb (void *cls, * @param internal_cls a `struct ClientHandle *` */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - void *internal_cls) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + void *internal_cls) { struct ClientHandle *ch = internal_cls; - GNUNET_CONTAINER_DLL_remove (ch_head, - ch_tail, - ch); - GNUNET_free (ch); + GNUNET_CONTAINER_DLL_remove(ch_head, + ch_tail, + ch); + GNUNET_free(ch); } @@ -451,17 +450,17 @@ client_disconnect_cb (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("nat-auto", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_var_size (autoconfig_request, - GNUNET_MESSAGE_TYPE_NAT_AUTO_REQUEST_CFG, - struct GNUNET_NAT_AUTO_AutoconfigRequestMessage, - NULL), - GNUNET_MQ_handler_end ()); + ("nat-auto", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_var_size(autoconfig_request, + GNUNET_MESSAGE_TYPE_NAT_AUTO_REQUEST_CFG, + struct GNUNET_NAT_AUTO_AutoconfigRequestMessage, + NULL), + GNUNET_MQ_handler_end()); #if defined(LINUX) && defined(__GLIBC__) @@ -471,11 +470,11 @@ GNUNET_SERVICE_MAIN * MINIMIZE heap size (way below 128k) since this process doesn't need much. */ void __attribute__ ((constructor)) -GNUNET_ARM_memory_init () +GNUNET_ARM_memory_init() { - mallopt (M_TRIM_THRESHOLD, 4 * 1024); - mallopt (M_TOP_PAD, 1 * 1024); - malloc_trim (0); + mallopt(M_TRIM_THRESHOLD, 4 * 1024); + mallopt(M_TOP_PAD, 1 * 1024); + malloc_trim(0); } #endif diff --git a/src/nat-auto/gnunet-service-nat-auto_legacy.c b/src/nat-auto/gnunet-service-nat-auto_legacy.c index 00bdeb693..30f1f855d 100644 --- a/src/nat-auto/gnunet-service-nat-auto_legacy.c +++ b/src/nat-auto/gnunet-service-nat-auto_legacy.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nat/nat_auto.c @@ -30,21 +30,20 @@ #include "gnunet_nat_lib.h" #include "nat.h" -#define LOG(kind,...) GNUNET_log_from (kind, "nat", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "nat", __VA_ARGS__) /** * How long do we wait for the NAT test to report success? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15) -#define NAT_SERVER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10) +#define NAT_SERVER_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10) /** * Phases of the auto configuration. */ -enum AutoPhase -{ +enum AutoPhase { /** * Initial start value. */ @@ -58,7 +57,7 @@ enum AutoPhase /** * Test our external IP. */ - AUTO_STUN, + AUTO_STUN, /** * Test our internal IP. @@ -89,16 +88,13 @@ enum AutoPhase * Last phase, we're done. */ AUTO_DONE - }; /** * Handle to auto-configuration in progress. */ -struct GNUNET_NAT_AutoHandle -{ - +struct GNUNET_NAT_AutoHandle { /** * Handle to the active NAT test. */ @@ -209,7 +205,7 @@ static unsigned int stun_port = 3478; * @param ah auto test handle */ static void -next_phase (struct GNUNET_NAT_AutoHandle *ah); +next_phase(struct GNUNET_NAT_AutoHandle *ah); static void @@ -217,12 +213,12 @@ process_stun_reply(struct sockaddr_in *answer, struct GNUNET_NAT_AutoHandle *ah) { ah->stun_ip = inet_ntoa(answer->sin_addr); - ah->stun_port = ntohs (answer->sin_port); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "External IP is: %s , with port %u\n", - ah->stun_ip, - ah->stun_port); - next_phase (ah); + ah->stun_port = ntohs(answer->sin_port); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "External IP is: %s , with port %u\n", + ah->stun_ip, + ah->stun_port); + next_phase(ah); } @@ -230,22 +226,22 @@ process_stun_reply(struct sockaddr_in *answer, * Function that terminates the test. */ static void -stop_stun () +stop_stun() { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Stopping STUN and quitting...\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Stopping STUN and quitting...\n"); /* Clean task */ if (NULL != ltask4) - { - GNUNET_SCHEDULER_cancel (ltask4); - ltask4 = NULL; - } + { + GNUNET_SCHEDULER_cancel(ltask4); + ltask4 = NULL; + } /* Clean socket */ if (NULL != lsock4) - { - GNUNET_NETWORK_socket_close (lsock4); - lsock4 = NULL; - } + { + GNUNET_NETWORK_socket_close(lsock4); + lsock4 = NULL; + } } @@ -256,7 +252,7 @@ stop_stun () * @param cls */ static void -do_udp_read (void *cls) +do_udp_read(void *cls) { struct GNUNET_NAT_AutoHandle *ah = cls; unsigned char reply_buf[1024]; @@ -264,51 +260,51 @@ do_udp_read (void *cls) struct sockaddr_in answer; const struct GNUNET_SCHEDULER_TaskContext *tc; - tc = GNUNET_SCHEDULER_get_task_context (); + tc = GNUNET_SCHEDULER_get_task_context(); if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) && - (GNUNET_NETWORK_fdset_isset (tc->read_ready, - lsock4))) - { - rlen = GNUNET_NETWORK_socket_recv (lsock4, - reply_buf, - sizeof (reply_buf)); - - //Lets handle the packet - memset (&answer, 0, sizeof(struct sockaddr_in)); - if (ah->phase == AUTO_NAT_PUNCHED) + (GNUNET_NETWORK_fdset_isset(tc->read_ready, + lsock4))) { - //Destroy the connection - GNUNET_NETWORK_socket_close (lsock4); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "The external server was able to connect back"); - ah->connected_back = GNUNET_YES; - next_phase (ah); - } - else - { - if (GNUNET_OK == - GNUNET_NAT_stun_handle_packet (reply_buf, rlen, &answer)) - { - //Process the answer - process_stun_reply (&answer, ah); - } + rlen = GNUNET_NETWORK_socket_recv(lsock4, + reply_buf, + sizeof(reply_buf)); + + //Lets handle the packet + memset(&answer, 0, sizeof(struct sockaddr_in)); + if (ah->phase == AUTO_NAT_PUNCHED) + { + //Destroy the connection + GNUNET_NETWORK_socket_close(lsock4); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "The external server was able to connect back"); + ah->connected_back = GNUNET_YES; + next_phase(ah); + } else - { - next_phase (ah); - } + { + if (GNUNET_OK == + GNUNET_NAT_stun_handle_packet(reply_buf, rlen, &answer)) + { + //Process the answer + process_stun_reply(&answer, ah); + } + else + { + next_phase(ah); + } + } } - } else - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "TIMEOUT while waiting for an answer\n"); - if (ah->phase == AUTO_NAT_PUNCHED) { - stop_stun(); - } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "TIMEOUT while waiting for an answer\n"); + if (ah->phase == AUTO_NAT_PUNCHED) + { + stop_stun(); + } - next_phase (ah); - } + next_phase(ah); + } } @@ -318,45 +314,45 @@ do_udp_read (void *cls) * @return NULL on error */ static struct GNUNET_NETWORK_Handle * -bind_v4 () +bind_v4() { struct GNUNET_NETWORK_Handle *ls; struct sockaddr_in sa4; int eno; - memset (&sa4, 0, sizeof (sa4)); + memset(&sa4, 0, sizeof(sa4)); sa4.sin_family = AF_INET; - sa4.sin_port = htons (port); + sa4.sin_port = htons(port); #if HAVE_SOCKADDR_IN_SIN_LEN - sa4.sin_len = sizeof (sa4); + sa4.sin_len = sizeof(sa4); #endif - ls = GNUNET_NETWORK_socket_create (AF_INET, - SOCK_DGRAM, - 0); + ls = GNUNET_NETWORK_socket_create(AF_INET, + SOCK_DGRAM, + 0); if (NULL == ls) return NULL; if (GNUNET_OK != - GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4, - sizeof (sa4))) - { - eno = errno; - GNUNET_NETWORK_socket_close (ls); - errno = eno; - return NULL; - } + GNUNET_NETWORK_socket_bind(ls, (const struct sockaddr *)&sa4, + sizeof(sa4))) + { + eno = errno; + GNUNET_NETWORK_socket_close(ls); + errno = eno; + return NULL; + } return ls; } static void -request_callback (void *cls, - enum GNUNET_NAT_StatusCode result) +request_callback(void *cls, + enum GNUNET_NAT_StatusCode result) { // struct GNUNET_NAT_AutoHandle *ah = cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Request callback: stop and quit\n"); - stop_stun (); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Request callback: stop and quit\n"); + stop_stun(); // next_phase (ah); FIXME this always will be NULL, as called in test_stun() } @@ -371,22 +367,22 @@ request_callback (void *cls, * @param emsg NULL on success, otherwise an error message */ static void -result_callback (void *cls, - enum GNUNET_NAT_StatusCode ret) +result_callback(void *cls, + enum GNUNET_NAT_StatusCode ret) { struct GNUNET_NAT_AutoHandle *ah = cls; if (GNUNET_NAT_ERROR_SUCCESS == ret) - GNUNET_NAT_test_stop (ah->tst); + GNUNET_NAT_test_stop(ah->tst); ah->tst = NULL; ah->ret = ret; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - GNUNET_NAT_ERROR_SUCCESS == ret - ? _("NAT traversal with ICMP Server succeeded.\n") - : _("NAT traversal with ICMP Server failed.\n")); - GNUNET_CONFIGURATION_set_value_string (ah->cfg, "nat", "ENABLE_ICMP_SERVER", - GNUNET_NAT_ERROR_SUCCESS == ret ? "NO" : "YES"); - next_phase (ah); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + GNUNET_NAT_ERROR_SUCCESS == ret + ? _("NAT traversal with ICMP Server succeeded.\n") + : _("NAT traversal with ICMP Server failed.\n")); + GNUNET_CONFIGURATION_set_value_string(ah->cfg, "nat", "ENABLE_ICMP_SERVER", + GNUNET_NAT_ERROR_SUCCESS == ret ? "NO" : "YES"); + next_phase(ah); } @@ -396,16 +392,16 @@ result_callback (void *cls, * @param cls the `struct GNUNET_NAT_AutoHandle` */ static void -reversal_test (void *cls) +reversal_test(void *cls) { struct GNUNET_NAT_AutoHandle *ah = cls; ah->task = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Testing connection reversal with ICMP server.\n")); - GNUNET_RESOLVER_connect (ah->cfg); - ah->tst = GNUNET_NAT_test_start (ah->cfg, GNUNET_YES, 0, 0, TIMEOUT, - &result_callback, ah); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Testing connection reversal with ICMP server.\n")); + GNUNET_RESOLVER_connect(ah->cfg); + ah->tst = GNUNET_NAT_test_start(ah->cfg, GNUNET_YES, 0, 0, TIMEOUT, + &result_callback, ah); } @@ -418,9 +414,9 @@ reversal_test (void *cls) * @param emsg NULL on success, otherwise an error message */ static void -set_external_ipv4 (void *cls, - const struct in_addr *addr, - enum GNUNET_NAT_StatusCode ret) +set_external_ipv4(void *cls, + const struct in_addr *addr, + enum GNUNET_NAT_StatusCode ret) { struct GNUNET_NAT_AutoHandle *ah = cls; char buf[INET_ADDRSTRLEN]; @@ -428,35 +424,35 @@ set_external_ipv4 (void *cls, ah->eh = NULL; ah->ret = ret; if (GNUNET_NAT_ERROR_SUCCESS != ret) - { - next_phase (ah); - return; - } + { + next_phase(ah); + return; + } /* enable 'behind nat' */ - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Detected external IP `%s'\n"), - inet_ntop (AF_INET, - addr, - buf, - sizeof (buf))); - GNUNET_CONFIGURATION_set_value_string (ah->cfg, "nat", "BEHIND_NAT", "YES"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Detected external IP `%s'\n"), + inet_ntop(AF_INET, + addr, + buf, + sizeof(buf))); + GNUNET_CONFIGURATION_set_value_string(ah->cfg, "nat", "BEHIND_NAT", "YES"); /* set external IP address */ - if (NULL == inet_ntop (AF_INET, addr, buf, sizeof (buf))) - { - GNUNET_break (0); - /* actually, this should never happen, as the caller already executed just - * this check, but for consistency (eg: future changes in the caller) - * we still need to report this error... - */ - ah->ret = GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID; - next_phase (ah); - return; - } - GNUNET_CONFIGURATION_set_value_string (ah->cfg, "nat", "EXTERNAL_ADDRESS", - buf); + if (NULL == inet_ntop(AF_INET, addr, buf, sizeof(buf))) + { + GNUNET_break(0); + /* actually, this should never happen, as the caller already executed just + * this check, but for consistency (eg: future changes in the caller) + * we still need to report this error... + */ + ah->ret = GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID; + next_phase(ah); + return; + } + GNUNET_CONFIGURATION_set_value_string(ah->cfg, "nat", "EXTERNAL_ADDRESS", + buf); ah->upnp_set_external_address = GNUNET_YES; - next_phase (ah); + next_phase(ah); } @@ -466,15 +462,15 @@ set_external_ipv4 (void *cls, * @param ah auto setup context */ static void -test_external_ip (struct GNUNET_NAT_AutoHandle *ah) +test_external_ip(struct GNUNET_NAT_AutoHandle *ah) { if (GNUNET_NAT_ERROR_SUCCESS != ah->ret) - next_phase (ah); + next_phase(ah); // FIXME: CPS? /* try to detect external IP */ - ah->eh = GNUNET_NAT_mini_get_external_ipv4 (TIMEOUT, - &set_external_ipv4, ah); + ah->eh = GNUNET_NAT_mini_get_external_ipv4(TIMEOUT, + &set_external_ipv4, ah); } @@ -484,54 +480,53 @@ test_external_ip (struct GNUNET_NAT_AutoHandle *ah) * @param ah auto setup context */ static void -test_stun (struct GNUNET_NAT_AutoHandle *ah) +test_stun(struct GNUNET_NAT_AutoHandle *ah) { - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Running STUN test\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Running STUN test\n"); /* Get port from the configuration */ if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (ah->cfg, - "transport-udp", - "PORT", - &port)) - { - port = 2086; - } + GNUNET_CONFIGURATION_get_value_number(ah->cfg, + "transport-udp", + "PORT", + &port)) + { + port = 2086; + } //Lets create the socket - lsock4 = bind_v4 (); + lsock4 = bind_v4(); if (NULL == lsock4) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind"); - next_phase(ah); - return; - } + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "bind"); + next_phase(ah); + return; + } else - { - //Lets call our function now when it accepts - ltask4 = GNUNET_SCHEDULER_add_read_net (NAT_SERVER_TIMEOUT, - lsock4, - &do_udp_read, - ah); - } - - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "STUN service listens on port %u\n", - (unsigned int) port); + { + //Lets call our function now when it accepts + ltask4 = GNUNET_SCHEDULER_add_read_net(NAT_SERVER_TIMEOUT, + lsock4, + &do_udp_read, + ah); + } + + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "STUN service listens on port %u\n", + (unsigned int)port); if (GNUNET_NO == - GNUNET_NAT_stun_make_request (stun_server, - stun_port, - lsock4, - &request_callback, - NULL)) - { - /*An error happened*/ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "STUN error, stopping\n"); - stop_stun (); - next_phase (ah); - } + GNUNET_NAT_stun_make_request(stun_server, + stun_port, + lsock4, + &request_callback, + NULL)) + { + /*An error happened*/ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "STUN error, stopping\n"); + stop_stun(); + next_phase(ah); + } } @@ -549,57 +544,57 @@ test_stun (struct GNUNET_NAT_AutoHandle *ah) * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort */ static int -process_if (void *cls, - const char *name, - int isDefault, - const struct sockaddr *addr, - const struct sockaddr *broadcast_addr, - const struct sockaddr *netmask, - socklen_t addrlen) +process_if(void *cls, + const char *name, + int isDefault, + const struct sockaddr *addr, + const struct sockaddr *broadcast_addr, + const struct sockaddr *netmask, + socklen_t addrlen) { struct GNUNET_NAT_AutoHandle *ah = cls; const struct sockaddr_in *in; char buf[INET_ADDRSTRLEN]; - if ( (sizeof (struct sockaddr_in6) == addrlen) && - (0 != GNUNET_memcmp (&in6addr_loopback, &((const struct sockaddr_in6 *) addr)->sin6_addr)) && - (! IN6_IS_ADDR_LINKLOCAL(&((const struct sockaddr_in6 *) addr)->sin6_addr)) ) - { - ah->have_v6 = GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("This system has a global IPv6 address, setting IPv6 to supported.\n")); + if ((sizeof(struct sockaddr_in6) == addrlen) && + (0 != GNUNET_memcmp(&in6addr_loopback, &((const struct sockaddr_in6 *)addr)->sin6_addr)) && + (!IN6_IS_ADDR_LINKLOCAL(&((const struct sockaddr_in6 *)addr)->sin6_addr))) + { + ah->have_v6 = GNUNET_YES; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("This system has a global IPv6 address, setting IPv6 to supported.\n")); + return GNUNET_OK; + } + if (addrlen != sizeof(struct sockaddr_in)) return GNUNET_OK; - } - if (addrlen != sizeof (struct sockaddr_in)) - return GNUNET_OK; - in = (const struct sockaddr_in *) addr; + in = (const struct sockaddr_in *)addr; /* set internal IP address */ - if (NULL == inet_ntop (AF_INET, &in->sin_addr, buf, sizeof (buf))) - { - GNUNET_break (0); - return GNUNET_OK; - } - GNUNET_CONFIGURATION_set_value_string (ah->cfg, "nat", "INTERNAL_ADDRESS", - buf); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Detected internal network address `%s'.\n"), - buf); + if (NULL == inet_ntop(AF_INET, &in->sin_addr, buf, sizeof(buf))) + { + GNUNET_break(0); + return GNUNET_OK; + } + GNUNET_CONFIGURATION_set_value_string(ah->cfg, "nat", "INTERNAL_ADDRESS", + buf); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Detected internal network address `%s'.\n"), + buf); ah->ret = GNUNET_NAT_ERROR_SUCCESS; /* Check if our internal IP is the same as the External detect by STUN*/ - if(ah->stun_ip && (strcmp(buf, ah->stun_ip) == 0) ) - { - ah->internal_ip_is_public = GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_INFO,"A internal IP is the sameas the external"); - /* No need to continue*/ - return GNUNET_SYSERR; - } + if (ah->stun_ip && (strcmp(buf, ah->stun_ip) == 0)) + { + ah->internal_ip_is_public = GNUNET_YES; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "A internal IP is the sameas the external"); + /* No need to continue*/ + return GNUNET_SYSERR; + } /* no need to continue iteration if we found the default */ if (!isDefault) @@ -615,15 +610,15 @@ process_if (void *cls, * @param ah auto setup context */ static void -test_local_ip (struct GNUNET_NAT_AutoHandle *ah) +test_local_ip(struct GNUNET_NAT_AutoHandle *ah) { ah->have_v6 = GNUNET_NO; ah->ret = GNUNET_NAT_ERROR_NO_VALID_IF_IP_COMBO; // reset to success if any of the IFs in below iterator has a valid IP - GNUNET_OS_network_interfaces_list (&process_if, ah); + GNUNET_OS_network_interfaces_list(&process_if, ah); - GNUNET_CONFIGURATION_set_value_string (ah->cfg, "nat", "DISABLEV6", - (GNUNET_YES == ah->have_v6) ? "NO" : "YES"); - next_phase (ah); + GNUNET_CONFIGURATION_set_value_string(ah->cfg, "nat", "DISABLEV6", + (GNUNET_YES == ah->have_v6) ? "NO" : "YES"); + next_phase(ah); } @@ -635,15 +630,15 @@ test_local_ip (struct GNUNET_NAT_AutoHandle *ah) * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_NAT_AutoHandle *ah = cls; - GNUNET_MQ_destroy (ah->mq); + GNUNET_MQ_destroy(ah->mq); ah->mq = NULL; /* wait a bit first? */ - next_phase (ah); + next_phase(ah); } @@ -653,50 +648,50 @@ mq_error_handler (void *cls, * @param ah auto setup context */ static void -test_nat_punched (struct GNUNET_NAT_AutoHandle *ah) +test_nat_punched(struct GNUNET_NAT_AutoHandle *ah) { struct GNUNET_NAT_TestMessage *msg; struct GNUNET_MQ_Envelope *env; - if (! ah->stun_ip) - { - LOG (GNUNET_ERROR_TYPE_INFO, - "We don't have a STUN IP"); - next_phase (ah); - return; - } - - LOG (GNUNET_ERROR_TYPE_INFO, - "Asking gnunet-nat-server to connect to `%s'\n", - ah->stun_ip); - ah->mq = GNUNET_CLIENT_connect (ah->cfg, - "gnunet-nat-server", - NULL, - &mq_error_handler, - ah); + if (!ah->stun_ip) + { + LOG(GNUNET_ERROR_TYPE_INFO, + "We don't have a STUN IP"); + next_phase(ah); + return; + } + + LOG(GNUNET_ERROR_TYPE_INFO, + "Asking gnunet-nat-server to connect to `%s'\n", + ah->stun_ip); + ah->mq = GNUNET_CLIENT_connect(ah->cfg, + "gnunet-nat-server", + NULL, + &mq_error_handler, + ah); if (NULL == ah->mq) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect to `gnunet-nat-server'\n")); - next_phase (ah); - return; - } - env = GNUNET_MQ_msg (msg, - GNUNET_MESSAGE_TYPE_NAT_TEST); - msg->dst_ipv4 = inet_addr (ah->stun_ip); - msg->dport = htons (ah->stun_port); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to `gnunet-nat-server'\n")); + next_phase(ah); + return; + } + env = GNUNET_MQ_msg(msg, + GNUNET_MESSAGE_TYPE_NAT_TEST); + msg->dst_ipv4 = inet_addr(ah->stun_ip); + msg->dport = htons(ah->stun_port); msg->data = port; - msg->is_tcp = htonl ((uint32_t) GNUNET_NO); - GNUNET_MQ_send (ah->mq, - env); + msg->is_tcp = htonl((uint32_t)GNUNET_NO); + GNUNET_MQ_send(ah->mq, + env); if (NULL != ltask4) - { - GNUNET_SCHEDULER_cancel (ltask4); - ltask4 = GNUNET_SCHEDULER_add_read_net (NAT_SERVER_TIMEOUT, - lsock4, - &do_udp_read, - ah); - } + { + GNUNET_SCHEDULER_cancel(ltask4); + ltask4 = GNUNET_SCHEDULER_add_read_net(NAT_SERVER_TIMEOUT, + lsock4, + &do_udp_read, + ah); + } } @@ -706,26 +701,24 @@ test_nat_punched (struct GNUNET_NAT_AutoHandle *ah) * @param ah auto setup context */ static void -test_upnpc (struct GNUNET_NAT_AutoHandle *ah) +test_upnpc(struct GNUNET_NAT_AutoHandle *ah) { - int have_upnpc; if (GNUNET_NAT_ERROR_SUCCESS != ah->ret) - next_phase (ah); + next_phase(ah); // test if upnpc is available have_upnpc = (GNUNET_SYSERR != - GNUNET_OS_check_helper_binary ("upnpc", GNUNET_NO, NULL)); + GNUNET_OS_check_helper_binary("upnpc", GNUNET_NO, NULL)); //FIXME: test if upnpc is actually working, that is, if transports start to work once we use UPnP - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - (have_upnpc) - ? _("upnpc found, enabling its use\n") - : _("upnpc not found\n")); - GNUNET_CONFIGURATION_set_value_string (ah->cfg, "nat", "ENABLE_UPNP", - (GNUNET_YES == have_upnpc) ? "YES" : "NO"); - next_phase (ah); - + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + (have_upnpc) + ? _("upnpc found, enabling its use\n") + : _("upnpc not found\n")); + GNUNET_CONFIGURATION_set_value_string(ah->cfg, "nat", "ENABLE_UPNP", + (GNUNET_YES == have_upnpc) ? "YES" : "NO"); + next_phase(ah); } @@ -735,66 +728,66 @@ test_upnpc (struct GNUNET_NAT_AutoHandle *ah) * @param ah auto setup context */ static void -test_icmp_server (struct GNUNET_NAT_AutoHandle *ah) +test_icmp_server(struct GNUNET_NAT_AutoHandle *ah) { - int ext_ip; int nated; int binary; char *tmp; char *helper; + ext_ip = GNUNET_NO; nated = GNUNET_NO; binary = GNUNET_NO; tmp = NULL; - helper = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-server"); - if ( (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (ah->cfg, - "nat", - "EXTERNAL_ADDRESS", - &tmp)) && - (0 < strlen (tmp)) ) - { - ext_ip = GNUNET_OK; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("test_icmp_server not possible, as we have no public IPv4 address\n")); - } + helper = GNUNET_OS_get_libexec_binary_path("gnunet-helper-nat-server"); + if ((GNUNET_OK == + GNUNET_CONFIGURATION_get_value_string(ah->cfg, + "nat", + "EXTERNAL_ADDRESS", + &tmp)) && + (0 < strlen(tmp))) + { + ext_ip = GNUNET_OK; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("test_icmp_server not possible, as we have no public IPv4 address\n")); + } else goto err; if (GNUNET_YES == - GNUNET_CONFIGURATION_get_value_yesno (ah->cfg, - "nat", - "BEHIND_NAT")) - { - nated = GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("test_icmp_server not possible, as we are not behind NAT\n")); - } + GNUNET_CONFIGURATION_get_value_yesno(ah->cfg, + "nat", + "BEHIND_NAT")) + { + nated = GNUNET_YES; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("test_icmp_server not possible, as we are not behind NAT\n")); + } else goto err; if (GNUNET_YES == - GNUNET_OS_check_helper_binary (helper, - GNUNET_YES, - "-d 127.0.0.1" )) - { - binary = GNUNET_OK; // use localhost as source for that one udp-port, ok for testing - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("No working gnunet-helper-nat-server found\n")); - } + GNUNET_OS_check_helper_binary(helper, + GNUNET_YES, + "-d 127.0.0.1")) + { + binary = GNUNET_OK; // use localhost as source for that one udp-port, ok for testing + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("No working gnunet-helper-nat-server found\n")); + } err: - GNUNET_free_non_null (tmp); - GNUNET_free (helper); - - if ( (GNUNET_OK == ext_ip) && - (GNUNET_YES == nated) && - (GNUNET_OK == binary) ) - ah->task = GNUNET_SCHEDULER_add_now (&reversal_test, - ah); + GNUNET_free_non_null(tmp); + GNUNET_free(helper); + + if ((GNUNET_OK == ext_ip) && + (GNUNET_YES == nated) && + (GNUNET_OK == binary)) + ah->task = GNUNET_SCHEDULER_add_now(&reversal_test, + ah); else - next_phase (ah); + next_phase(ah); } @@ -804,51 +797,51 @@ err: * @param ah auto setup context */ static void -test_icmp_client (struct GNUNET_NAT_AutoHandle *ah) +test_icmp_client(struct GNUNET_NAT_AutoHandle *ah) { char *tmp; char *helper; tmp = NULL; - helper = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-nat-client"); - if ( (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (ah->cfg, - "nat", - "INTERNAL_ADDRESS", - &tmp)) && - (0 < strlen (tmp)) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("test_icmp_client not possible, as we have no internal IPv4 address\n")); - } + helper = GNUNET_OS_get_libexec_binary_path("gnunet-helper-nat-client"); + if ((GNUNET_OK == + GNUNET_CONFIGURATION_get_value_string(ah->cfg, + "nat", + "INTERNAL_ADDRESS", + &tmp)) && + (0 < strlen(tmp))) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("test_icmp_client not possible, as we have no internal IPv4 address\n")); + } else goto err; if (GNUNET_YES != - GNUNET_CONFIGURATION_get_value_yesno (ah->cfg, - "nat", - "BEHIND_NAT")) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("test_icmp_server not possible, as we are not behind NAT\n")); - } + GNUNET_CONFIGURATION_get_value_yesno(ah->cfg, + "nat", + "BEHIND_NAT")) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("test_icmp_server not possible, as we are not behind NAT\n")); + } else goto err; if (GNUNET_YES == - GNUNET_OS_check_helper_binary (helper, - GNUNET_YES, - "-d 127.0.0.1 127.0.0.2 42")) - { - // none of these parameters are actually used in privilege testing mode - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("No working gnunet-helper-nat-server found\n")); - } + GNUNET_OS_check_helper_binary(helper, + GNUNET_YES, + "-d 127.0.0.1 127.0.0.2 42")) + { + // none of these parameters are actually used in privilege testing mode + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("No working gnunet-helper-nat-server found\n")); + } err: - GNUNET_free_non_null (tmp); - GNUNET_free (helper); + GNUNET_free_non_null(tmp); + GNUNET_free(helper); - next_phase (ah); + next_phase(ah); } @@ -856,156 +849,161 @@ err: * Run the next phase of the auto test. */ static void -next_phase (struct GNUNET_NAT_AutoHandle *ah) +next_phase(struct GNUNET_NAT_AutoHandle *ah) { struct GNUNET_CONFIGURATION_Handle *diff; ah->phase++; switch (ah->phase) - { - case AUTO_INIT: - GNUNET_assert (0); - break; - case AUTO_EXTERNAL_IP: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Will run AUTO_EXTERNAL_IP\n"); - test_external_ip (ah); - break; - case AUTO_STUN: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Will run AUTO_STUN\n"); - test_stun (ah); - break; - case AUTO_LOCAL_IP: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Will run AUTO_LOCAL_IP\n"); - test_local_ip (ah); - break; - case AUTO_NAT_PUNCHED: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Will run AUTO_NAT_PUNCHED\n"); - test_nat_punched (ah); - break; - case AUTO_UPNPC: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Will run AUTO_UPNPC\n"); - test_upnpc (ah); - break; - case AUTO_ICMP_SERVER: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Will run AUTO_ICMP_SERVER\n"); - test_icmp_server (ah); - break; - case AUTO_ICMP_CLIENT: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Will run AUTO_ICMP_CLIENT\n"); - test_icmp_client (ah); - break; - case AUTO_DONE: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Done with tests\n"); - if (!ah->internal_ip_is_public) { - GNUNET_CONFIGURATION_set_value_string (ah->cfg, - "nat", - "BEHIND_NAT", - "YES"); - - if (ah->connected_back) - { - GNUNET_CONFIGURATION_set_value_string (ah->cfg, - "nat", - "PUNCHED_NAT", - "YES"); - } - else - { - GNUNET_CONFIGURATION_set_value_string (ah->cfg, - "nat", - "PUNCHED_NAT", - "NO"); - } - - if (ah->stun_ip) - { - GNUNET_CONFIGURATION_set_value_string (ah->cfg, - "nat", - "EXTERNAL_ADDRESS", - ah->stun_ip); - if (ah->connected_back) + case AUTO_INIT: + GNUNET_assert(0); + break; + + case AUTO_EXTERNAL_IP: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Will run AUTO_EXTERNAL_IP\n"); + test_external_ip(ah); + break; + + case AUTO_STUN: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Will run AUTO_STUN\n"); + test_stun(ah); + break; + + case AUTO_LOCAL_IP: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Will run AUTO_LOCAL_IP\n"); + test_local_ip(ah); + break; + + case AUTO_NAT_PUNCHED: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Will run AUTO_NAT_PUNCHED\n"); + test_nat_punched(ah); + break; + + case AUTO_UPNPC: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Will run AUTO_UPNPC\n"); + test_upnpc(ah); + break; + + case AUTO_ICMP_SERVER: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Will run AUTO_ICMP_SERVER\n"); + test_icmp_server(ah); + break; + + case AUTO_ICMP_CLIENT: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Will run AUTO_ICMP_CLIENT\n"); + test_icmp_client(ah); + break; + + case AUTO_DONE: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Done with tests\n"); + if (!ah->internal_ip_is_public) { - ah->type = GNUNET_NAT_TYPE_STUN_PUNCHED_NAT; - GNUNET_CONFIGURATION_set_value_string (ah->cfg, - "nat", - "USE_STUN", - "YES"); + GNUNET_CONFIGURATION_set_value_string(ah->cfg, + "nat", + "BEHIND_NAT", + "YES"); + + if (ah->connected_back) + { + GNUNET_CONFIGURATION_set_value_string(ah->cfg, + "nat", + "PUNCHED_NAT", + "YES"); + } + else + { + GNUNET_CONFIGURATION_set_value_string(ah->cfg, + "nat", + "PUNCHED_NAT", + "NO"); + } + + if (ah->stun_ip) + { + GNUNET_CONFIGURATION_set_value_string(ah->cfg, + "nat", + "EXTERNAL_ADDRESS", + ah->stun_ip); + if (ah->connected_back) + { + ah->type = GNUNET_NAT_TYPE_STUN_PUNCHED_NAT; + GNUNET_CONFIGURATION_set_value_string(ah->cfg, + "nat", + "USE_STUN", + "YES"); + } + else + { + ah->type = GNUNET_NAT_TYPE_UNREACHABLE_NAT; + GNUNET_CONFIGURATION_set_value_string(ah->cfg, + "nat", + "USE_STUN", + "NO"); + } + } + if (0 != ah->stun_port) + { + GNUNET_CONFIGURATION_set_value_number(ah->cfg, + "transport-udp", + "ADVERTISED_PORT", + ah->stun_port); + } } - else - { - ah->type = GNUNET_NAT_TYPE_UNREACHABLE_NAT; - GNUNET_CONFIGURATION_set_value_string (ah->cfg, - "nat", - "USE_STUN", - "NO"); - } - - } - if (0 != ah->stun_port) - { - GNUNET_CONFIGURATION_set_value_number (ah->cfg, - "transport-udp", - "ADVERTISED_PORT", - ah->stun_port); - } - - } - else - { - //The internal IP is the same as public, but we didn't got a incoming connection - if (ah->connected_back) - { - ah->type = GNUNET_NAT_TYPE_NO_NAT; - GNUNET_CONFIGURATION_set_value_string (ah->cfg, - "nat", - "BEHIND_NAT", - "NO"); - } else - { - GNUNET_CONFIGURATION_set_value_string (ah->cfg, - "nat", - "BEHIND_NAT", - "YES"); - ah->type = GNUNET_NAT_TYPE_UNREACHABLE_NAT; - if (ah->stun_ip) { - GNUNET_CONFIGURATION_set_value_string (ah->cfg, - "nat", - "EXTERNAL_ADDRESS", - ah->stun_ip); + //The internal IP is the same as public, but we didn't got a incoming connection + if (ah->connected_back) + { + ah->type = GNUNET_NAT_TYPE_NO_NAT; + GNUNET_CONFIGURATION_set_value_string(ah->cfg, + "nat", + "BEHIND_NAT", + "NO"); + } + else + { + GNUNET_CONFIGURATION_set_value_string(ah->cfg, + "nat", + "BEHIND_NAT", + "YES"); + ah->type = GNUNET_NAT_TYPE_UNREACHABLE_NAT; + if (ah->stun_ip) + { + GNUNET_CONFIGURATION_set_value_string(ah->cfg, + "nat", + "EXTERNAL_ADDRESS", + ah->stun_ip); + } + if (0 != ah->stun_port) + { + GNUNET_CONFIGURATION_set_value_number(ah->cfg, + "transport-udp", + "ADVERTISED_PORT", + ah->stun_port); + } + } } - if (0 != ah->stun_port) - { - GNUNET_CONFIGURATION_set_value_number (ah->cfg, - "transport-udp", - "ADVERTISED_PORT", - ah->stun_port); - } - } - } - - diff = GNUNET_CONFIGURATION_get_diff (ah->initial_cfg, - ah->cfg); + diff = GNUNET_CONFIGURATION_get_diff(ah->initial_cfg, + ah->cfg); - ah->fin_cb (ah->fin_cb_cls, - diff, - ah->ret, - ah->type); - GNUNET_CONFIGURATION_destroy (diff); - GNUNET_NAT_autoconfig_cancel (ah); - } + ah->fin_cb(ah->fin_cb_cls, + diff, + ah->ret, + ah->type); + GNUNET_CONFIGURATION_destroy(diff); + GNUNET_NAT_autoconfig_cancel(ah); + } } @@ -1019,26 +1017,26 @@ next_phase (struct GNUNET_NAT_AutoHandle *ah) * @return handle to cancel operation */ struct GNUNET_NAT_AutoHandle * -GNUNET_NAT_autoconfig_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_NAT_AutoResultCallback cb, - void *cb_cls) +GNUNET_NAT_autoconfig_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_NAT_AutoResultCallback cb, + void *cb_cls) { struct GNUNET_NAT_AutoHandle *ah; - ah = GNUNET_new (struct GNUNET_NAT_AutoHandle); + ah = GNUNET_new(struct GNUNET_NAT_AutoHandle); ah->fin_cb = cb; ah->fin_cb_cls = cb_cls; ah->ret = GNUNET_NAT_ERROR_SUCCESS; - ah->cfg = GNUNET_CONFIGURATION_dup (cfg); - ah->initial_cfg = GNUNET_CONFIGURATION_dup (cfg); + ah->cfg = GNUNET_CONFIGURATION_dup(cfg); + ah->initial_cfg = GNUNET_CONFIGURATION_dup(cfg); /* never use loopback addresses if user wanted autoconfiguration */ - GNUNET_CONFIGURATION_set_value_string (ah->cfg, - "nat", - "USE_LOCALADDR", - "NO"); + GNUNET_CONFIGURATION_set_value_string(ah->cfg, + "nat", + "USE_LOCALADDR", + "NO"); - next_phase (ah); + next_phase(ah); return ah; } @@ -1049,31 +1047,31 @@ GNUNET_NAT_autoconfig_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param ah handle for operation to abort */ void -GNUNET_NAT_autoconfig_cancel (struct GNUNET_NAT_AutoHandle *ah) +GNUNET_NAT_autoconfig_cancel(struct GNUNET_NAT_AutoHandle *ah) { if (NULL != ah->tst) - { - GNUNET_NAT_test_stop (ah->tst); - ah->tst = NULL; - } + { + GNUNET_NAT_test_stop(ah->tst); + ah->tst = NULL; + } if (NULL != ah->eh) - { - GNUNET_NAT_mini_get_external_ipv4_cancel (ah->eh); - ah->eh = NULL; - } + { + GNUNET_NAT_mini_get_external_ipv4_cancel(ah->eh); + ah->eh = NULL; + } if (NULL != ah->mq) - { - GNUNET_MQ_destroy (ah->mq); - ah->mq = NULL; - } + { + GNUNET_MQ_destroy(ah->mq); + ah->mq = NULL; + } if (NULL != ah->task) - { - GNUNET_SCHEDULER_cancel (ah->task); - ah->task = NULL; - } - GNUNET_CONFIGURATION_destroy (ah->cfg); - GNUNET_CONFIGURATION_destroy (ah->initial_cfg); - GNUNET_free (ah); + { + GNUNET_SCHEDULER_cancel(ah->task); + ah->task = NULL; + } + GNUNET_CONFIGURATION_destroy(ah->cfg); + GNUNET_CONFIGURATION_destroy(ah->initial_cfg); + GNUNET_free(ah); } diff --git a/src/nat-auto/nat-auto.h b/src/nat-auto/nat-auto.h index 76d877dd3..6ef9b7e1e 100644 --- a/src/nat-auto/nat-auto.h +++ b/src/nat-auto/nat-auto.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/nat-auto/nat-auto.h @@ -36,8 +36,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * Request to test NAT traversal, sent to the gnunet-nat-server * (not the service!). */ -struct GNUNET_NAT_AUTO_TestMessage -{ +struct GNUNET_NAT_AUTO_TestMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_NAT_TEST */ @@ -62,35 +61,31 @@ struct GNUNET_NAT_AUTO_TestMessage * #GNUNET_YES for TCP, #GNUNET_NO for UDP. */ int32_t is_tcp; - }; /** * Client requesting automatic configuration. */ -struct GNUNET_NAT_AUTO_AutoconfigRequestMessage -{ +struct GNUNET_NAT_AUTO_AutoconfigRequestMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_NAT_REQUEST_AUTO_CFG */ struct GNUNET_MessageHeader header; /* Followed by configuration (diff, serialized, compressed) */ - }; /** * Service responding with proposed configuration. */ -struct GNUNET_NAT_AUTO_AutoconfigResultMessage -{ +struct GNUNET_NAT_AUTO_AutoconfigResultMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_NAT_AUTO_CFG_RESULT */ struct GNUNET_MessageHeader header; - + /** * An `enum GNUNET_NAT_StatusCode` in NBO. */ diff --git a/src/nat-auto/nat_auto_api.c b/src/nat-auto/nat_auto_api.c index d7c081e49..ae7bb6514 100644 --- a/src/nat-auto/nat_auto_api.c +++ b/src/nat-auto/nat_auto_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -35,9 +35,7 @@ /** * Handle to auto-configuration in progress. */ -struct GNUNET_NAT_AUTO_AutoHandle -{ - +struct GNUNET_NAT_AUTO_AutoHandle { /** * Configuration we use. */ @@ -57,7 +55,6 @@ struct GNUNET_NAT_AUTO_AutoHandle * Closure for @e arc. */ void *arc_cls; - }; @@ -68,51 +65,70 @@ struct GNUNET_NAT_AUTO_AutoHandle * @return point to a static string containing the error code */ const char * -GNUNET_NAT_AUTO_status2string (enum GNUNET_NAT_StatusCode err) +GNUNET_NAT_AUTO_status2string(enum GNUNET_NAT_StatusCode err) { switch (err) - { - case GNUNET_NAT_ERROR_SUCCESS: - return _ ("Operation Successful"); - case GNUNET_NAT_ERROR_IPC_FAILURE: - return _ ("IPC failure"); - case GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR: - return _ ("Failure in network subsystem, check permissions."); - case GNUNET_NAT_ERROR_TIMEOUT: - return _ ("Encountered timeout while performing operation"); - case GNUNET_NAT_ERROR_NOT_ONLINE: - return _ ("detected that we are offline"); - case GNUNET_NAT_ERROR_UPNPC_NOT_FOUND: - return _ ("`upnpc` command not found"); - case GNUNET_NAT_ERROR_UPNPC_FAILED: - return _ ("Failed to run `upnpc` command"); - case GNUNET_NAT_ERROR_UPNPC_TIMEOUT: - return _ ("`upnpc' command took too long, process killed"); - case GNUNET_NAT_ERROR_UPNPC_PORTMAP_FAILED: - return _ ("`upnpc' command failed to establish port mapping"); - case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_NOT_FOUND: - return _ ("`external-ip' command not found"); - case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_FAILED: - return _ ("Failed to run `external-ip` command"); - case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_OUTPUT_INVALID: - return _ ("`external-ip' command output invalid"); - case GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID: - return _ ("no valid address was returned by `external-ip'"); - case GNUNET_NAT_ERROR_NO_VALID_IF_IP_COMBO: - return _ ("Could not determine interface with internal/local network address"); - case GNUNET_NAT_ERROR_HELPER_NAT_SERVER_NOT_FOUND: - return _ ("No functioning gnunet-helper-nat-server installation found"); - case GNUNET_NAT_ERROR_NAT_TEST_START_FAILED: - return _ ("NAT test could not be initialized"); - case GNUNET_NAT_ERROR_NAT_TEST_TIMEOUT: - return _ ("NAT test timeout reached"); - case GNUNET_NAT_ERROR_NAT_REGISTER_FAILED: - return _ ("could not register NAT"); - case GNUNET_NAT_ERROR_HELPER_NAT_CLIENT_NOT_FOUND: - return _ ("No working gnunet-helper-nat-client installation found"); - default: - return "unknown status code"; - } + { + case GNUNET_NAT_ERROR_SUCCESS: + return _("Operation Successful"); + + case GNUNET_NAT_ERROR_IPC_FAILURE: + return _("IPC failure"); + + case GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR: + return _("Failure in network subsystem, check permissions."); + + case GNUNET_NAT_ERROR_TIMEOUT: + return _("Encountered timeout while performing operation"); + + case GNUNET_NAT_ERROR_NOT_ONLINE: + return _("detected that we are offline"); + + case GNUNET_NAT_ERROR_UPNPC_NOT_FOUND: + return _("`upnpc` command not found"); + + case GNUNET_NAT_ERROR_UPNPC_FAILED: + return _("Failed to run `upnpc` command"); + + case GNUNET_NAT_ERROR_UPNPC_TIMEOUT: + return _("`upnpc' command took too long, process killed"); + + case GNUNET_NAT_ERROR_UPNPC_PORTMAP_FAILED: + return _("`upnpc' command failed to establish port mapping"); + + case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_NOT_FOUND: + return _("`external-ip' command not found"); + + case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_FAILED: + return _("Failed to run `external-ip` command"); + + case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_OUTPUT_INVALID: + return _("`external-ip' command output invalid"); + + case GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID: + return _("no valid address was returned by `external-ip'"); + + case GNUNET_NAT_ERROR_NO_VALID_IF_IP_COMBO: + return _("Could not determine interface with internal/local network address"); + + case GNUNET_NAT_ERROR_HELPER_NAT_SERVER_NOT_FOUND: + return _("No functioning gnunet-helper-nat-server installation found"); + + case GNUNET_NAT_ERROR_NAT_TEST_START_FAILED: + return _("NAT test could not be initialized"); + + case GNUNET_NAT_ERROR_NAT_TEST_TIMEOUT: + return _("NAT test timeout reached"); + + case GNUNET_NAT_ERROR_NAT_REGISTER_FAILED: + return _("could not register NAT"); + + case GNUNET_NAT_ERROR_HELPER_NAT_CLIENT_NOT_FOUND: + return _("No working gnunet-helper-nat-client installation found"); + + default: + return "unknown status code"; + } } @@ -124,8 +140,8 @@ GNUNET_NAT_AUTO_status2string (enum GNUNET_NAT_StatusCode err) * @return #GNUNET_OK if @a res is well-formed (always for now) */ static int -check_auto_result (void *cls, - const struct GNUNET_NAT_AUTO_AutoconfigResultMessage *res) +check_auto_result(void *cls, + const struct GNUNET_NAT_AUTO_AutoconfigResultMessage *res) { return GNUNET_OK; } @@ -138,40 +154,40 @@ check_auto_result (void *cls, * @param res the result */ static void -handle_auto_result (void *cls, - const struct GNUNET_NAT_AUTO_AutoconfigResultMessage *res) +handle_auto_result(void *cls, + const struct GNUNET_NAT_AUTO_AutoconfigResultMessage *res) { struct GNUNET_NAT_AUTO_AutoHandle *ah = cls; size_t left; struct GNUNET_CONFIGURATION_Handle *cfg; enum GNUNET_NAT_Type type - = (enum GNUNET_NAT_Type) ntohl (res->type); + = (enum GNUNET_NAT_Type)ntohl(res->type); enum GNUNET_NAT_StatusCode status - = (enum GNUNET_NAT_StatusCode) ntohl (res->status_code); + = (enum GNUNET_NAT_StatusCode)ntohl(res->status_code); - left = ntohs (res->header.size) - sizeof (*res); - cfg = GNUNET_CONFIGURATION_create (); + left = ntohs(res->header.size) - sizeof(*res); + cfg = GNUNET_CONFIGURATION_create(); if (GNUNET_OK != - GNUNET_CONFIGURATION_deserialize (cfg, - (const char *) &res[1], - left, - NULL)) - { - GNUNET_break (0); - ah->arc (ah->arc_cls, - NULL, - GNUNET_NAT_ERROR_IPC_FAILURE, - type); - } + GNUNET_CONFIGURATION_deserialize(cfg, + (const char *)&res[1], + left, + NULL)) + { + GNUNET_break(0); + ah->arc(ah->arc_cls, + NULL, + GNUNET_NAT_ERROR_IPC_FAILURE, + type); + } else - { - ah->arc (ah->arc_cls, - cfg, - status, - type); - } - GNUNET_CONFIGURATION_destroy (cfg); - GNUNET_NAT_AUTO_autoconfig_cancel (ah); + { + ah->arc(ah->arc_cls, + cfg, + status, + type); + } + GNUNET_CONFIGURATION_destroy(cfg); + GNUNET_NAT_AUTO_autoconfig_cancel(ah); } @@ -182,16 +198,16 @@ handle_auto_result (void *cls, * @param error details about the error */ static void -ah_error_handler (void *cls, - enum GNUNET_MQ_Error error) +ah_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_NAT_AUTO_AutoHandle *ah = cls; - ah->arc (ah->arc_cls, - NULL, - GNUNET_NAT_ERROR_IPC_FAILURE, - GNUNET_NAT_TYPE_UNKNOWN); - GNUNET_NAT_AUTO_autoconfig_cancel (ah); + ah->arc(ah->arc_cls, + NULL, + GNUNET_NAT_ERROR_IPC_FAILURE, + GNUNET_NAT_TYPE_UNKNOWN); + GNUNET_NAT_AUTO_autoconfig_cancel(ah); } @@ -205,55 +221,55 @@ ah_error_handler (void *cls, * @return handle to cancel operation */ struct GNUNET_NAT_AUTO_AutoHandle * -GNUNET_NAT_AUTO_autoconfig_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_NAT_AUTO_AutoResultCallback cb, - void *cb_cls) +GNUNET_NAT_AUTO_autoconfig_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_NAT_AUTO_AutoResultCallback cb, + void *cb_cls) { - struct GNUNET_NAT_AUTO_AutoHandle *ah = GNUNET_new (struct GNUNET_NAT_AUTO_AutoHandle); + struct GNUNET_NAT_AUTO_AutoHandle *ah = GNUNET_new(struct GNUNET_NAT_AUTO_AutoHandle); struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (auto_result, - GNUNET_MESSAGE_TYPE_NAT_AUTO_CFG_RESULT, - struct GNUNET_NAT_AUTO_AutoconfigResultMessage, - ah), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(auto_result, + GNUNET_MESSAGE_TYPE_NAT_AUTO_CFG_RESULT, + struct GNUNET_NAT_AUTO_AutoconfigResultMessage, + ah), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *env; struct GNUNET_NAT_AUTO_AutoconfigRequestMessage *req; char *buf; size_t size; - buf = GNUNET_CONFIGURATION_serialize (cfg, - &size); - if (size > GNUNET_MAX_MESSAGE_SIZE - sizeof (*req)) - { - GNUNET_break (0); - GNUNET_free (buf); - GNUNET_free (ah); - return NULL; - } + buf = GNUNET_CONFIGURATION_serialize(cfg, + &size); + if (size > GNUNET_MAX_MESSAGE_SIZE - sizeof(*req)) + { + GNUNET_break(0); + GNUNET_free(buf); + GNUNET_free(ah); + return NULL; + } ah->arc = cb; ah->arc_cls = cb_cls; - ah->mq = GNUNET_CLIENT_connect (cfg, - "nat", - handlers, - &ah_error_handler, - ah); + ah->mq = GNUNET_CLIENT_connect(cfg, + "nat", + handlers, + &ah_error_handler, + ah); if (NULL == ah->mq) - { - GNUNET_break (0); - GNUNET_free (buf); - GNUNET_free (ah); - return NULL; - } - env = GNUNET_MQ_msg_extra (req, - size, - GNUNET_MESSAGE_TYPE_NAT_AUTO_REQUEST_CFG); - GNUNET_memcpy (&req[1], - buf, - size); - GNUNET_free (buf); - GNUNET_MQ_send (ah->mq, - env); + { + GNUNET_break(0); + GNUNET_free(buf); + GNUNET_free(ah); + return NULL; + } + env = GNUNET_MQ_msg_extra(req, + size, + GNUNET_MESSAGE_TYPE_NAT_AUTO_REQUEST_CFG); + GNUNET_memcpy(&req[1], + buf, + size); + GNUNET_free(buf); + GNUNET_MQ_send(ah->mq, + env); return ah; } @@ -264,10 +280,10 @@ GNUNET_NAT_AUTO_autoconfig_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param ah handle for operation to abort */ void -GNUNET_NAT_AUTO_autoconfig_cancel (struct GNUNET_NAT_AUTO_AutoHandle *ah) +GNUNET_NAT_AUTO_autoconfig_cancel(struct GNUNET_NAT_AUTO_AutoHandle *ah) { - GNUNET_MQ_destroy (ah->mq); - GNUNET_free (ah); + GNUNET_MQ_destroy(ah->mq); + GNUNET_free(ah); } /* end of nat_api_auto.c */ diff --git a/src/nat-auto/nat_auto_api_test.c b/src/nat-auto/nat_auto_api_test.c index 56a2b8d72..daea3063c 100644 --- a/src/nat-auto/nat_auto_api_test.c +++ b/src/nat-auto/nat_auto_api_test.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nat/nat_auto_api_test.c * @brief functions to test if the NAT configuration is successful at achieving NAT traversal (with the help of a gnunet-nat-server) @@ -28,16 +28,15 @@ #include "gnunet_nat_auto_service.h" #include "nat-auto.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "nat-auto", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "nat-auto", __VA_ARGS__) #define NAT_SERVER_TIMEOUT \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30) /** * Entry we keep for each incoming connection. */ -struct NatActivity -{ +struct NatActivity { /** * This is a doubly-linked list. */ @@ -68,8 +67,7 @@ struct NatActivity /** * Entry we keep for each connection to the gnunet-nat-service. */ -struct ClientActivity -{ +struct ClientActivity { /** * This is a doubly-linked list. */ @@ -95,9 +93,7 @@ struct ClientActivity /** * Handle to a NAT test. */ -struct GNUNET_NAT_AUTO_Test -{ - +struct GNUNET_NAT_AUTO_Test { /** * Configuration used */ @@ -184,22 +180,22 @@ struct GNUNET_NAT_AUTO_Test * @param addrlen actual lenght of the @a addr */ static void -reversal_cb (void *cls, const struct sockaddr *addr, socklen_t addrlen) +reversal_cb(void *cls, const struct sockaddr *addr, socklen_t addrlen) { struct GNUNET_NAT_AUTO_Test *h = cls; const struct sockaddr_in *sa; - if (sizeof (struct sockaddr_in) != addrlen) + if (sizeof(struct sockaddr_in) != addrlen) return; - sa = (const struct sockaddr_in *) addr; + sa = (const struct sockaddr_in *)addr; if (h->data != sa->sin_port) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received connection reversal request for wrong port\n"); - return; /* wrong port */ - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received connection reversal request for wrong port\n"); + return; /* wrong port */ + } /* report success */ - h->report (h->report_cls, GNUNET_NAT_ERROR_SUCCESS); + h->report(h->report_cls, GNUNET_NAT_ERROR_SUCCESS); } @@ -210,31 +206,31 @@ reversal_cb (void *cls, const struct sockaddr *addr, socklen_t addrlen) * @param cls the `struct GNUNET_NAT_AUTO_Test` */ static void -do_udp_read (void *cls) +do_udp_read(void *cls) { struct GNUNET_NAT_AUTO_Test *tst = cls; uint16_t data; const struct GNUNET_SCHEDULER_TaskContext *tc; - tc = GNUNET_SCHEDULER_get_task_context (); - tst->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - tst->lsock, - &do_udp_read, - tst); + tc = GNUNET_SCHEDULER_get_task_context(); + tst->ltask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + tst->lsock, + &do_udp_read, + tst); if ((NULL != tc->write_ready) && - (GNUNET_NETWORK_fdset_isset (tc->read_ready, tst->lsock)) && - (sizeof (data) == - GNUNET_NETWORK_socket_recv (tst->lsock, &data, sizeof (data)))) - { - if (data == tst->data) - tst->report (tst->report_cls, GNUNET_NAT_ERROR_SUCCESS); - else - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received data mismatches expected value\n"); - } + (GNUNET_NETWORK_fdset_isset(tc->read_ready, tst->lsock)) && + (sizeof(data) == + GNUNET_NETWORK_socket_recv(tst->lsock, &data, sizeof(data)))) + { + if (data == tst->data) + tst->report(tst->report_cls, GNUNET_NAT_ERROR_SUCCESS); + else + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received data mismatches expected value\n"); + } else - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Failed to receive data from inbound connection\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Failed to receive data from inbound connection\n"); } @@ -245,33 +241,33 @@ do_udp_read (void *cls) * @param cls the `struct NatActivity` */ static void -do_read (void *cls) +do_read(void *cls) { struct NatActivity *na = cls; struct GNUNET_NAT_AUTO_Test *tst; uint16_t data; const struct GNUNET_SCHEDULER_TaskContext *tc; - tc = GNUNET_SCHEDULER_get_task_context (); + tc = GNUNET_SCHEDULER_get_task_context(); na->rtask = NULL; tst = na->h; - GNUNET_CONTAINER_DLL_remove (tst->na_head, tst->na_tail, na); + GNUNET_CONTAINER_DLL_remove(tst->na_head, tst->na_tail, na); if ((NULL != tc->write_ready) && - (GNUNET_NETWORK_fdset_isset (tc->read_ready, na->sock)) && - (sizeof (data) == - GNUNET_NETWORK_socket_recv (na->sock, &data, sizeof (data)))) - { - if (data == tst->data) - tst->report (tst->report_cls, GNUNET_NAT_ERROR_SUCCESS); - else - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received data does not match expected value\n"); - } + (GNUNET_NETWORK_fdset_isset(tc->read_ready, na->sock)) && + (sizeof(data) == + GNUNET_NETWORK_socket_recv(na->sock, &data, sizeof(data)))) + { + if (data == tst->data) + tst->report(tst->report_cls, GNUNET_NAT_ERROR_SUCCESS); + else + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received data does not match expected value\n"); + } else - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Failed to receive data from inbound connection\n"); - GNUNET_NETWORK_socket_close (na->sock); - GNUNET_free (na); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Failed to receive data from inbound connection\n"); + GNUNET_NETWORK_socket_close(na->sock); + GNUNET_free(na); } @@ -282,32 +278,32 @@ do_read (void *cls) * @param cls the `struct GNUNET_NAT_AUTO_Test` */ static void -do_accept (void *cls) +do_accept(void *cls) { struct GNUNET_NAT_AUTO_Test *tst = cls; struct GNUNET_NETWORK_Handle *s; struct NatActivity *wl; - tst->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - tst->lsock, - &do_accept, - tst); - s = GNUNET_NETWORK_socket_accept (tst->lsock, NULL, NULL); + tst->ltask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + tst->lsock, + &do_accept, + tst); + s = GNUNET_NETWORK_socket_accept(tst->lsock, NULL, NULL); if (NULL == s) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, "accept"); - return; /* odd error */ - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got an inbound connection, waiting for data\n"); - wl = GNUNET_new (struct NatActivity); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_INFO, "accept"); + return; /* odd error */ + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got an inbound connection, waiting for data\n"); + wl = GNUNET_new(struct NatActivity); wl->sock = s; wl->h = tst; - wl->rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - wl->sock, - &do_read, - wl); - GNUNET_CONTAINER_DLL_insert (tst->na_head, tst->na_tail, wl); + wl->rtask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + wl->sock, + &do_read, + wl); + GNUNET_CONTAINER_DLL_insert(tst->na_head, tst->na_tail, wl); } @@ -319,14 +315,14 @@ do_accept (void *cls) * @param error error code */ static void -mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct ClientActivity *ca = cls; struct GNUNET_NAT_AUTO_Test *tst = ca->h; - GNUNET_CONTAINER_DLL_remove (tst->ca_head, tst->ca_tail, ca); - GNUNET_MQ_destroy (ca->mq); - GNUNET_free (ca); + GNUNET_CONTAINER_DLL_remove(tst->ca_head, tst->ca_tail, ca); + GNUNET_MQ_destroy(ca->mq); + GNUNET_free(ca); } @@ -343,12 +339,12 @@ mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @param addrlen actual length of the @a addr */ static void -addr_cb (void *cls, - void **app_ctx, - int add_remove, - enum GNUNET_NAT_AddressClass ac, - const struct sockaddr *addr, - socklen_t addrlen) +addr_cb(void *cls, + void **app_ctx, + int add_remove, + enum GNUNET_NAT_AddressClass ac, + const struct sockaddr *addr, + socklen_t addrlen) { struct GNUNET_NAT_AUTO_Test *h = cls; struct ClientActivity *ca; @@ -356,42 +352,42 @@ addr_cb (void *cls, struct GNUNET_NAT_AUTO_TestMessage *msg; const struct sockaddr_in *sa; - (void) app_ctx; + (void)app_ctx; if (GNUNET_YES != add_remove) return; - if (addrlen != sizeof (struct sockaddr_in)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "NAT test ignores IPv6 address `%s' returned from NAT library\n", - GNUNET_a2s (addr, addrlen)); - return; /* ignore IPv6 here */ - } - LOG (GNUNET_ERROR_TYPE_INFO, - "Asking gnunet-nat-server to connect to `%s'\n", - GNUNET_a2s (addr, addrlen)); - - ca = GNUNET_new (struct ClientActivity); + if (addrlen != sizeof(struct sockaddr_in)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "NAT test ignores IPv6 address `%s' returned from NAT library\n", + GNUNET_a2s(addr, addrlen)); + return; /* ignore IPv6 here */ + } + LOG(GNUNET_ERROR_TYPE_INFO, + "Asking gnunet-nat-server to connect to `%s'\n", + GNUNET_a2s(addr, addrlen)); + + ca = GNUNET_new(struct ClientActivity); ca->h = h; - ca->mq = GNUNET_CLIENT_connect (h->cfg, - "gnunet-nat-server", - NULL, - &mq_error_handler, - ca); + ca->mq = GNUNET_CLIENT_connect(h->cfg, + "gnunet-nat-server", + NULL, + &mq_error_handler, + ca); if (NULL == ca->mq) - { - GNUNET_free (ca); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to connect to `gnunet-nat-server'\n")); - return; - } - GNUNET_CONTAINER_DLL_insert (h->ca_head, h->ca_tail, ca); - sa = (const struct sockaddr_in *) addr; - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_NAT_TEST); + { + GNUNET_free(ca); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to `gnunet-nat-server'\n")); + return; + } + GNUNET_CONTAINER_DLL_insert(h->ca_head, h->ca_tail, ca); + sa = (const struct sockaddr_in *)addr; + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_NAT_TEST); msg->dst_ipv4 = sa->sin_addr.s_addr; msg->dport = sa->sin_port; msg->data = h->data; - msg->is_tcp = htonl ((uint32_t) (h->proto == IPPROTO_TCP)); - GNUNET_MQ_send (ca->mq, env); + msg->is_tcp = htonl((uint32_t)(h->proto == IPPROTO_TCP)); + GNUNET_MQ_send(ca->mq, env); } @@ -403,12 +399,12 @@ addr_cb (void *cls, * @param cls handle to the timed out NAT test */ static void -do_fail (void *cls) +do_fail(void *cls) { struct GNUNET_NAT_AUTO_Test *nh = cls; nh->ttask = NULL; - nh->report (nh->report_cls, nh->status); + nh->report(nh->report_cls, nh->status); } @@ -424,128 +420,128 @@ do_fail (void *cls) * @return handle to cancel NAT test */ struct GNUNET_NAT_AUTO_Test * -GNUNET_NAT_AUTO_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg, - uint8_t proto, - const char *section_name, - GNUNET_NAT_TestCallback report, - void *report_cls) +GNUNET_NAT_AUTO_test_start(const struct GNUNET_CONFIGURATION_Handle *cfg, + uint8_t proto, + const char *section_name, + GNUNET_NAT_TestCallback report, + void *report_cls) { struct GNUNET_NAT_AUTO_Test *nh; unsigned long long bnd_port; struct sockaddr_in sa; - const struct sockaddr *addrs[] = {(const struct sockaddr *) &sa}; - const socklen_t addrlens[] = {sizeof (sa)}; + const struct sockaddr *addrs[] = { (const struct sockaddr *)&sa }; + const socklen_t addrlens[] = { sizeof(sa) }; - if ((GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, - section_name, - "PORT", - &bnd_port)) || + if ((GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, + section_name, + "PORT", + &bnd_port)) || (bnd_port > 65535)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to find valid PORT in section `%s'\n"), - section_name); - return NULL; - } - - memset (&sa, 0, sizeof (sa)); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to find valid PORT in section `%s'\n"), + section_name); + return NULL; + } + + memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; - sa.sin_port = htons ((uint16_t) bnd_port); + sa.sin_port = htons((uint16_t)bnd_port); #if HAVE_SOCKADDR_IN_SIN_LEN - sa.sin_len = sizeof (sa); + sa.sin_len = sizeof(sa); #endif - nh = GNUNET_new (struct GNUNET_NAT_AUTO_Test); + nh = GNUNET_new(struct GNUNET_NAT_AUTO_Test); nh->cfg = cfg; nh->proto = proto; - nh->section_name = GNUNET_strdup (section_name); + nh->section_name = GNUNET_strdup(section_name); nh->report = report; nh->report_cls = report_cls; nh->status = GNUNET_NAT_ERROR_SUCCESS; if (0 == bnd_port) - { - nh->nat = GNUNET_NAT_register (cfg, - section_name, - proto, - 0, - NULL, - NULL, - &addr_cb, - &reversal_cb, - nh); - } - else - { - nh->lsock = - GNUNET_NETWORK_socket_create (AF_INET, - (IPPROTO_UDP == proto) ? SOCK_DGRAM - : SOCK_STREAM, - proto); - if ((NULL == nh->lsock) || - (GNUNET_OK != GNUNET_NETWORK_socket_bind (nh->lsock, - (const struct sockaddr *) &sa, - sizeof (sa)))) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to create socket bound to `%s' for NAT test: %s\n"), - GNUNET_a2s ((const struct sockaddr *) &sa, sizeof (sa)), - strerror (errno)); - if (NULL != nh->lsock) - { - GNUNET_NETWORK_socket_close (nh->lsock); - nh->lsock = NULL; - } - nh->status = GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR; - nh->ttask = GNUNET_SCHEDULER_add_now (&do_fail, nh); - return nh; - } - if (IPPROTO_TCP == proto) { - GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_listen (nh->lsock, 5)); - nh->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - nh->lsock, - &do_accept, - nh); + nh->nat = GNUNET_NAT_register(cfg, + section_name, + proto, + 0, + NULL, + NULL, + &addr_cb, + &reversal_cb, + nh); } - else - { - nh->ltask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - nh->lsock, - &do_udp_read, - nh); - } - LOG (GNUNET_ERROR_TYPE_INFO, - "NAT test listens on port %llu (%s)\n", - bnd_port, - (IPPROTO_TCP == proto) ? "tcp" : "udp"); - nh->nat = GNUNET_NAT_register (cfg, - section_name, - proto, - 1, - addrs, - addrlens, - &addr_cb, - NULL, - nh); - if (NULL == nh->nat) + else { - LOG (GNUNET_ERROR_TYPE_INFO, - _ ("NAT test failed to start NAT library\n")); - if (NULL != nh->ltask) - { - GNUNET_SCHEDULER_cancel (nh->ltask); - nh->ltask = NULL; - } - if (NULL != nh->lsock) - { - GNUNET_NETWORK_socket_close (nh->lsock); - nh->lsock = NULL; - } - nh->status = GNUNET_NAT_ERROR_NAT_REGISTER_FAILED; - nh->ttask = GNUNET_SCHEDULER_add_now (&do_fail, nh); - return nh; + nh->lsock = + GNUNET_NETWORK_socket_create(AF_INET, + (IPPROTO_UDP == proto) ? SOCK_DGRAM + : SOCK_STREAM, + proto); + if ((NULL == nh->lsock) || + (GNUNET_OK != GNUNET_NETWORK_socket_bind(nh->lsock, + (const struct sockaddr *)&sa, + sizeof(sa)))) + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Failed to create socket bound to `%s' for NAT test: %s\n"), + GNUNET_a2s((const struct sockaddr *)&sa, sizeof(sa)), + strerror(errno)); + if (NULL != nh->lsock) + { + GNUNET_NETWORK_socket_close(nh->lsock); + nh->lsock = NULL; + } + nh->status = GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR; + nh->ttask = GNUNET_SCHEDULER_add_now(&do_fail, nh); + return nh; + } + if (IPPROTO_TCP == proto) + { + GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_listen(nh->lsock, 5)); + nh->ltask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + nh->lsock, + &do_accept, + nh); + } + else + { + nh->ltask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + nh->lsock, + &do_udp_read, + nh); + } + LOG(GNUNET_ERROR_TYPE_INFO, + "NAT test listens on port %llu (%s)\n", + bnd_port, + (IPPROTO_TCP == proto) ? "tcp" : "udp"); + nh->nat = GNUNET_NAT_register(cfg, + section_name, + proto, + 1, + addrs, + addrlens, + &addr_cb, + NULL, + nh); + if (NULL == nh->nat) + { + LOG(GNUNET_ERROR_TYPE_INFO, + _("NAT test failed to start NAT library\n")); + if (NULL != nh->ltask) + { + GNUNET_SCHEDULER_cancel(nh->ltask); + nh->ltask = NULL; + } + if (NULL != nh->lsock) + { + GNUNET_NETWORK_socket_close(nh->lsock); + nh->lsock = NULL; + } + nh->status = GNUNET_NAT_ERROR_NAT_REGISTER_FAILED; + nh->ttask = GNUNET_SCHEDULER_add_now(&do_fail, nh); + return nh; + } } - } return nh; } @@ -556,47 +552,47 @@ GNUNET_NAT_AUTO_test_start (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param tst test to stop. */ void -GNUNET_NAT_AUTO_test_stop (struct GNUNET_NAT_AUTO_Test *tst) +GNUNET_NAT_AUTO_test_stop(struct GNUNET_NAT_AUTO_Test *tst) { struct NatActivity *pos; struct ClientActivity *cpos; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Stopping NAT test\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Stopping NAT test\n"); while (NULL != (cpos = tst->ca_head)) - { - GNUNET_CONTAINER_DLL_remove (tst->ca_head, tst->ca_tail, cpos); - GNUNET_MQ_destroy (cpos->mq); - GNUNET_free (cpos); - } + { + GNUNET_CONTAINER_DLL_remove(tst->ca_head, tst->ca_tail, cpos); + GNUNET_MQ_destroy(cpos->mq); + GNUNET_free(cpos); + } while (NULL != (pos = tst->na_head)) - { - GNUNET_CONTAINER_DLL_remove (tst->na_head, tst->na_tail, pos); - GNUNET_SCHEDULER_cancel (pos->rtask); - GNUNET_NETWORK_socket_close (pos->sock); - GNUNET_free (pos); - } + { + GNUNET_CONTAINER_DLL_remove(tst->na_head, tst->na_tail, pos); + GNUNET_SCHEDULER_cancel(pos->rtask); + GNUNET_NETWORK_socket_close(pos->sock); + GNUNET_free(pos); + } if (NULL != tst->ttask) - { - GNUNET_SCHEDULER_cancel (tst->ttask); - tst->ttask = NULL; - } + { + GNUNET_SCHEDULER_cancel(tst->ttask); + tst->ttask = NULL; + } if (NULL != tst->ltask) - { - GNUNET_SCHEDULER_cancel (tst->ltask); - tst->ltask = NULL; - } + { + GNUNET_SCHEDULER_cancel(tst->ltask); + tst->ltask = NULL; + } if (NULL != tst->lsock) - { - GNUNET_NETWORK_socket_close (tst->lsock); - tst->lsock = NULL; - } + { + GNUNET_NETWORK_socket_close(tst->lsock); + tst->lsock = NULL; + } if (NULL != tst->nat) - { - GNUNET_NAT_unregister (tst->nat); - tst->nat = NULL; - } - GNUNET_free (tst->section_name); - GNUNET_free (tst); + { + GNUNET_NAT_unregister(tst->nat); + tst->nat = NULL; + } + GNUNET_free(tst->section_name); + GNUNET_free(tst); } /* end of nat_auto_api_test.c */ diff --git a/src/nat/gnunet-helper-nat-client-windows.c b/src/nat/gnunet-helper-nat-client-windows.c index dda6552d8..2dac5d48e 100644 --- a/src/nat/gnunet-helper-nat-client-windows.c +++ b/src/nat/gnunet-helper-nat-client-windows.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/nat/gnunet-helper-nat-client-windows.c @@ -43,7 +43,7 @@ */ #define _GNU_SOURCE /* Instead of including gnunet_common.h */ -#define GNUNET_memcpy(dst,src,n) do { if (0 != n) { (void) memcpy (dst,src,n); } } while (0) +#define GNUNET_memcpy(dst, src, n) do { if (0 != n) { (void)memcpy(dst, src, n); } } while (0) #define FD_SETSIZE 1024 #include @@ -73,9 +73,7 @@ /** * IPv4 header. */ -struct ip_header -{ - +struct ip_header { /** * Version (4 bits) + Internet header length (4 bits) */ @@ -131,8 +129,7 @@ struct ip_header /** * Format of ICMP packet. */ -struct icmp_ttl_exceeded_header -{ +struct icmp_ttl_exceeded_header { uint8_t type; uint8_t code; @@ -144,8 +141,7 @@ struct icmp_ttl_exceeded_header /* followed by original payload */ }; -struct icmp_echo_header -{ +struct icmp_echo_header { uint8_t type; uint8_t code; @@ -158,8 +154,7 @@ struct icmp_echo_header /** * Beginning of UDP packet. */ -struct udp_header -{ +struct udp_header { uint16_t src_port; uint16_t dst_port; @@ -200,14 +195,14 @@ static uint16_t port; * @return 1 on success */ static int -inet_pton (int af, const char *cp, struct in_addr *buf) +inet_pton(int af, const char *cp, struct in_addr *buf) { - buf->s_addr = inet_addr (cp); + buf->s_addr = inet_addr(cp); if (buf->s_addr == INADDR_NONE) - { - fprintf (stderr, "Error %d handling address %s", WSAGetLastError (), cp); - return 0; - } + { + fprintf(stderr, "Error %d handling address %s", WSAGetLastError(), cp); + return 0; + } return 1; } @@ -220,7 +215,7 @@ inet_pton (int af, const char *cp, struct in_addr *buf) * @return the CRC 16. */ static uint16_t -calc_checksum (const uint16_t * data, unsigned int bytes) +calc_checksum(const uint16_t * data, unsigned int bytes) { uint32_t sum; unsigned int i; @@ -229,7 +224,7 @@ calc_checksum (const uint16_t * data, unsigned int bytes) for (i = 0; i < bytes / 2; i++) sum += data[i]; sum = (sum & 0xffff) + (sum >> 16); - sum = htons (0xffff - sum); + sum = htons(0xffff - sum); return sum; } @@ -241,11 +236,11 @@ calc_checksum (const uint16_t * data, unsigned int bytes) * @param other target address */ static void -send_icmp_udp (const struct in_addr *my_ip, const struct in_addr *other) +send_icmp_udp(const struct in_addr *my_ip, const struct in_addr *other) { - char packet[sizeof (struct ip_header) * 2 + - sizeof (struct icmp_ttl_exceeded_header) + - sizeof (struct udp_header)]; + char packet[sizeof(struct ip_header) * 2 + + sizeof(struct icmp_ttl_exceeded_header) + + sizeof(struct udp_header)]; struct ip_header ip_pkt; struct icmp_ttl_exceeded_header icmp_pkt; struct udp_header udp_pkt; @@ -257,8 +252,8 @@ send_icmp_udp (const struct in_addr *my_ip, const struct in_addr *other) off = 0; ip_pkt.vers_ihl = 0x45; ip_pkt.tos = 0; - ip_pkt.pkt_len = htons (sizeof (packet)); - ip_pkt.id = htons (256); + ip_pkt.pkt_len = htons(sizeof(packet)); + ip_pkt.id = htons(256); ip_pkt.flags_frag_offset = 0; ip_pkt.ttl = 128; ip_pkt.proto = IPPROTO_ICMP; @@ -266,23 +261,23 @@ send_icmp_udp (const struct in_addr *my_ip, const struct in_addr *other) ip_pkt.src_ip = my_ip->s_addr; ip_pkt.dst_ip = other->s_addr; ip_pkt.checksum = - htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header))); - GNUNET_memcpy (&packet[off], &ip_pkt, sizeof (struct ip_header)); - off += sizeof (struct ip_header); + htons(calc_checksum((uint16_t *)&ip_pkt, sizeof(struct ip_header))); + GNUNET_memcpy(&packet[off], &ip_pkt, sizeof(struct ip_header)); + off += sizeof(struct ip_header); icmp_pkt.type = ICMP_TIME_EXCEEDED; icmp_pkt.code = 0; icmp_pkt.checksum = 0; icmp_pkt.unused = 0; - GNUNET_memcpy (&packet[off], &icmp_pkt, sizeof (struct icmp_ttl_exceeded_header)); - off += sizeof (struct icmp_ttl_exceeded_header); + GNUNET_memcpy(&packet[off], &icmp_pkt, sizeof(struct icmp_ttl_exceeded_header)); + off += sizeof(struct icmp_ttl_exceeded_header); /* ip header of the presumably 'lost' udp packet */ ip_pkt.vers_ihl = 0x45; ip_pkt.tos = 0; ip_pkt.pkt_len = - htons (sizeof (struct ip_header) + sizeof (struct udp_header)); - ip_pkt.id = htons (0); + htons(sizeof(struct ip_header) + sizeof(struct udp_header)); + ip_pkt.id = htons(0); ip_pkt.flags_frag_offset = 0; ip_pkt.ttl = 128; ip_pkt.proto = IPPROTO_UDP; @@ -290,41 +285,41 @@ send_icmp_udp (const struct in_addr *my_ip, const struct in_addr *other) ip_pkt.src_ip = other->s_addr; ip_pkt.dst_ip = dummy.s_addr; ip_pkt.checksum = - htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header))); - GNUNET_memcpy (&packet[off], &ip_pkt, sizeof (struct ip_header)); - off += sizeof (struct ip_header); + htons(calc_checksum((uint16_t *)&ip_pkt, sizeof(struct ip_header))); + GNUNET_memcpy(&packet[off], &ip_pkt, sizeof(struct ip_header)); + off += sizeof(struct ip_header); /* build UDP header */ - udp_pkt.src_port = htons (NAT_TRAV_PORT); - udp_pkt.dst_port = htons (NAT_TRAV_PORT); - udp_pkt.length = htons (port); + udp_pkt.src_port = htons(NAT_TRAV_PORT); + udp_pkt.dst_port = htons(NAT_TRAV_PORT); + udp_pkt.length = htons(port); udp_pkt.crc = 0; - GNUNET_memcpy (&packet[off], &udp_pkt, sizeof (struct udp_header)); - off += sizeof (struct udp_header); + GNUNET_memcpy(&packet[off], &udp_pkt, sizeof(struct udp_header)); + off += sizeof(struct udp_header); /* no go back to calculate ICMP packet checksum */ icmp_pkt.checksum = - htons (calc_checksum - ((uint16_t *) & packet[off], - sizeof (struct icmp_ttl_exceeded_header) + - sizeof (struct ip_header) + sizeof (struct udp_header))); - GNUNET_memcpy (&packet[sizeof (struct ip_header)], &icmp_pkt, - sizeof (struct icmp_ttl_exceeded_header)); - - memset (&dst, 0, sizeof (dst)); + htons(calc_checksum + ((uint16_t *)&packet[off], + sizeof(struct icmp_ttl_exceeded_header) + + sizeof(struct ip_header) + sizeof(struct udp_header))); + GNUNET_memcpy(&packet[sizeof(struct ip_header)], &icmp_pkt, + sizeof(struct icmp_ttl_exceeded_header)); + + memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; dst.sin_addr = *other; err = - sendto (rawsock, packet, sizeof (packet), 0, (struct sockaddr *) &dst, - sizeof (dst)); + sendto(rawsock, packet, sizeof(packet), 0, (struct sockaddr *)&dst, + sizeof(dst)); if (err < 0) - { - fprintf (stderr, "sendto failed: %s\n", strerror (errno)); - } - else if (sizeof (packet) != (size_t) err) - { - fprintf (stderr, "Error: partial send of ICMP message\n"); - } + { + fprintf(stderr, "sendto failed: %s\n", strerror(errno)); + } + else if (sizeof(packet) != (size_t)err) + { + fprintf(stderr, "Error: partial send of ICMP message\n"); + } } @@ -335,15 +330,15 @@ send_icmp_udp (const struct in_addr *my_ip, const struct in_addr *other) * @param other target address */ static void -send_icmp (const struct in_addr *my_ip, const struct in_addr *other) +send_icmp(const struct in_addr *my_ip, const struct in_addr *other) { struct ip_header ip_pkt; struct icmp_ttl_exceeded_header icmp_ttl; struct icmp_echo_header icmp_echo; struct sockaddr_in dst; - char packet[sizeof (struct ip_header) * 2 + - sizeof (struct icmp_ttl_exceeded_header) + - sizeof (struct icmp_echo_header)]; + char packet[sizeof(struct ip_header) * 2 + + sizeof(struct icmp_ttl_exceeded_header) + + sizeof(struct icmp_echo_header)]; size_t off; int err; @@ -351,8 +346,8 @@ send_icmp (const struct in_addr *my_ip, const struct in_addr *other) off = 0; ip_pkt.vers_ihl = 0x45; ip_pkt.tos = 0; - ip_pkt.pkt_len = htons (sizeof (packet)); - ip_pkt.id = htons (256); + ip_pkt.pkt_len = htons(sizeof(packet)); + ip_pkt.id = htons(256); ip_pkt.flags_frag_offset = 0; ip_pkt.ttl = IPDEFTTL; ip_pkt.proto = IPPROTO_ICMP; @@ -360,24 +355,24 @@ send_icmp (const struct in_addr *my_ip, const struct in_addr *other) ip_pkt.src_ip = my_ip->s_addr; ip_pkt.dst_ip = other->s_addr; ip_pkt.checksum = - htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header))); - GNUNET_memcpy (&packet[off], &ip_pkt, sizeof (struct ip_header)); - off += sizeof (ip_pkt); + htons(calc_checksum((uint16_t *)&ip_pkt, sizeof(struct ip_header))); + GNUNET_memcpy(&packet[off], &ip_pkt, sizeof(struct ip_header)); + off += sizeof(ip_pkt); /* icmp reply: time exceeded */ icmp_ttl.type = ICMP_TIME_EXCEEDED; icmp_ttl.code = 0; icmp_ttl.checksum = 0; icmp_ttl.unused = 0; - GNUNET_memcpy (&packet[off], &icmp_ttl, sizeof (struct icmp_ttl_exceeded_header)); - off += sizeof (struct icmp_ttl_exceeded_header); + GNUNET_memcpy(&packet[off], &icmp_ttl, sizeof(struct icmp_ttl_exceeded_header)); + off += sizeof(struct icmp_ttl_exceeded_header); /* ip header of the presumably 'lost' udp packet */ ip_pkt.vers_ihl = 0x45; ip_pkt.tos = 0; ip_pkt.pkt_len = - htons (sizeof (struct ip_header) + sizeof (struct icmp_echo_header)); - ip_pkt.id = htons (256); + htons(sizeof(struct ip_header) + sizeof(struct icmp_echo_header)); + ip_pkt.id = htons(256); ip_pkt.flags_frag_offset = 0; ip_pkt.ttl = 1; /* real TTL would be 1 on a time exceeded packet */ ip_pkt.proto = IPPROTO_ICMP; @@ -385,44 +380,44 @@ send_icmp (const struct in_addr *my_ip, const struct in_addr *other) ip_pkt.dst_ip = dummy.s_addr; ip_pkt.checksum = 0; ip_pkt.checksum = - htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header))); - GNUNET_memcpy (&packet[off], &ip_pkt, sizeof (struct ip_header)); - off += sizeof (struct ip_header); + htons(calc_checksum((uint16_t *)&ip_pkt, sizeof(struct ip_header))); + GNUNET_memcpy(&packet[off], &ip_pkt, sizeof(struct ip_header)); + off += sizeof(struct ip_header); icmp_echo.type = ICMP_ECHO; icmp_echo.code = 0; - icmp_echo.reserved = htonl (port); + icmp_echo.reserved = htonl(port); icmp_echo.checksum = 0; icmp_echo.checksum = - htons (calc_checksum - ((uint16_t *) & icmp_echo, sizeof (struct icmp_echo_header))); - GNUNET_memcpy (&packet[off], &icmp_echo, sizeof (struct icmp_echo_header)); + htons(calc_checksum + ((uint16_t *)&icmp_echo, sizeof(struct icmp_echo_header))); + GNUNET_memcpy(&packet[off], &icmp_echo, sizeof(struct icmp_echo_header)); /* no go back to calculate ICMP packet checksum */ - off = sizeof (struct ip_header); + off = sizeof(struct ip_header); icmp_ttl.checksum = - htons (calc_checksum - ((uint16_t *) & packet[off], - sizeof (struct icmp_ttl_exceeded_header) + - sizeof (struct ip_header) + sizeof (struct icmp_echo_header))); - GNUNET_memcpy (&packet[off], &icmp_ttl, sizeof (struct icmp_ttl_exceeded_header)); + htons(calc_checksum + ((uint16_t *)&packet[off], + sizeof(struct icmp_ttl_exceeded_header) + + sizeof(struct ip_header) + sizeof(struct icmp_echo_header))); + GNUNET_memcpy(&packet[off], &icmp_ttl, sizeof(struct icmp_ttl_exceeded_header)); - memset (&dst, 0, sizeof (dst)); + memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; dst.sin_addr = *other; err = - sendto (rawsock, packet, sizeof (packet), 0, (struct sockaddr *) &dst, - sizeof (dst)); + sendto(rawsock, packet, sizeof(packet), 0, (struct sockaddr *)&dst, + sizeof(dst)); if (err < 0) - { - fprintf (stderr, "sendto failed: %s\n", strerror (errno)); - } - else if (sizeof (packet) != (size_t) err) - { - fprintf (stderr, "Error: partial send of ICMP message\n"); - } + { + fprintf(stderr, "sendto failed: %s\n", strerror(errno)); + } + else if (sizeof(packet) != (size_t)err) + { + fprintf(stderr, "Error: partial send of ICMP message\n"); + } } @@ -432,100 +427,102 @@ send_icmp (const struct in_addr *my_ip, const struct in_addr *other) * @return INVALID_SOCKET on error */ static SOCKET -make_raw_socket () +make_raw_socket() { DWORD bOptVal = TRUE; - int bOptLen = sizeof (bOptVal); + int bOptLen = sizeof(bOptVal); SOCKET ret; - ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW); + ret = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); if (INVALID_SOCKET == ret) - { - fprintf (stderr, "Error opening RAW socket: %s\n", strerror (errno)); - return INVALID_SOCKET; - } + { + fprintf(stderr, "Error opening RAW socket: %s\n", strerror(errno)); + return INVALID_SOCKET; + } if (0 != - setsockopt (ret, SOL_SOCKET, SO_BROADCAST, (char *) &bOptVal, bOptLen)) - { - fprintf (stderr, "Error setting SO_BROADCAST to ON: %s\n", - strerror (errno)); - closesocket (rawsock); - return INVALID_SOCKET; - } - - if (0 != setsockopt (ret, IPPROTO_IP, IP_HDRINCL, (char *) &bOptVal, bOptLen)) - { - fprintf (stderr, "Error setting IP_HDRINCL to ON: %s\n", strerror (errno)); - closesocket (rawsock); - return INVALID_SOCKET; - } + setsockopt(ret, SOL_SOCKET, SO_BROADCAST, (char *)&bOptVal, bOptLen)) + { + fprintf(stderr, "Error setting SO_BROADCAST to ON: %s\n", + strerror(errno)); + closesocket(rawsock); + return INVALID_SOCKET; + } + + if (0 != setsockopt(ret, IPPROTO_IP, IP_HDRINCL, (char *)&bOptVal, bOptLen)) + { + fprintf(stderr, "Error setting IP_HDRINCL to ON: %s\n", strerror(errno)); + closesocket(rawsock); + return INVALID_SOCKET; + } return ret; } int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct in_addr external; struct in_addr target; WSADATA wsaData; unsigned int p; - if (argc > 1 && 0 != strcmp (argv[1], "-d")){ + if (argc > 1 && 0 != strcmp(argv[1], "-d")) + { privilege_testing = TRUE; - fprintf (stderr, - "%s", - "DEBUG: Running binary in privilege testing mode."); + fprintf(stderr, + "%s", + "DEBUG: Running binary in privilege testing mode."); argv++; argc--; } if (argc != 4) - { - fprintf (stderr, - "%s", - "This program must be started with our IP, the targets external IP, and our port as arguments.\n"); - return 1; - } - if ((1 != inet_pton (AF_INET, argv[1], &external)) || - (1 != inet_pton (AF_INET, argv[2], &target))) - { - fprintf (stderr, - "Error parsing IPv4 address: %s\n", - strerror (errno)); - return 1; - } - if ((1 != sscanf (argv[3], "%u", &p)) || (0 == p) || (0xFFFF < p)) - { - fprintf (stderr, - "Error parsing port value `%s'\n", - argv[3]); - return 1; - } - port = (uint16_t) p; - - if (0 != WSAStartup (MAKEWORD (2, 1), &wsaData)) - { - fprintf (stderr, - "%s", - "Failed to find Winsock 2.1 or better.\n"); - return 2; - } - if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) - { - fprintf (stderr, - "%s", - "Internal error converting dummy IP to binary.\n"); - return 2; - } - if (-1 == (rawsock = make_raw_socket ())) + { + fprintf(stderr, + "%s", + "This program must be started with our IP, the targets external IP, and our port as arguments.\n"); + return 1; + } + if ((1 != inet_pton(AF_INET, argv[1], &external)) || + (1 != inet_pton(AF_INET, argv[2], &target))) + { + fprintf(stderr, + "Error parsing IPv4 address: %s\n", + strerror(errno)); + return 1; + } + if ((1 != sscanf(argv[3], "%u", &p)) || (0 == p) || (0xFFFF < p)) + { + fprintf(stderr, + "Error parsing port value `%s'\n", + argv[3]); + return 1; + } + port = (uint16_t)p; + + if (0 != WSAStartup(MAKEWORD(2, 1), &wsaData)) + { + fprintf(stderr, + "%s", + "Failed to find Winsock 2.1 or better.\n"); + return 2; + } + if (1 != inet_pton(AF_INET, DUMMY_IP, &dummy)) + { + fprintf(stderr, + "%s", + "Internal error converting dummy IP to binary.\n"); + return 2; + } + if (-1 == (rawsock = make_raw_socket())) return 3; - if (!privilege_testing){ - send_icmp (&external, &target); - send_icmp_udp (&external, &target); - } - closesocket (rawsock); - WSACleanup (); + if (!privilege_testing) + { + send_icmp(&external, &target); + send_icmp_udp(&external, &target); + } + closesocket(rawsock); + WSACleanup(); return 0; } diff --git a/src/nat/gnunet-helper-nat-client.c b/src/nat/gnunet-helper-nat-client.c index 54a993452..d5d774964 100644 --- a/src/nat/gnunet-helper-nat-client.c +++ b/src/nat/gnunet-helper-nat-client.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/nat/gnunet-helper-nat-client.c @@ -75,7 +75,7 @@ * @param src source of the copy, may be NULL if @a n is zero * @param n number of bytes to copy */ -#define GNUNET_memcpy(dst,src,n) do { if (0 != n) { (void) memcpy (dst,src,n); } } while (0) +#define GNUNET_memcpy(dst, src, n) do { if (0 != n) { (void)memcpy(dst, src, n); } } while (0) /** * Must match IP given in the server. @@ -92,9 +92,7 @@ /** * IPv4 header. */ -struct ip_header -{ - +struct ip_header { /** * Version (4 bits) + Internet header length (4 bits) */ @@ -149,8 +147,7 @@ struct ip_header /** * Format of ICMP packet. */ -struct icmp_ttl_exceeded_header -{ +struct icmp_ttl_exceeded_header { uint8_t type; uint8_t code; @@ -162,8 +159,7 @@ struct icmp_ttl_exceeded_header /* followed by original payload */ }; -struct icmp_echo_header -{ +struct icmp_echo_header { uint8_t type; uint8_t code; @@ -176,8 +172,7 @@ struct icmp_echo_header /** * Beginning of UDP packet. */ -struct udp_header -{ +struct udp_header { uint16_t src_port; uint16_t dst_port; @@ -211,7 +206,7 @@ static uint16_t port; * @return the CRC 16. */ static uint16_t -calc_checksum (const uint16_t * data, unsigned int bytes) +calc_checksum(const uint16_t * data, unsigned int bytes) { uint32_t sum; unsigned int i; @@ -220,7 +215,7 @@ calc_checksum (const uint16_t * data, unsigned int bytes) for (i = 0; i < bytes / 2; i++) sum += data[i]; sum = (sum & 0xffff) + (sum >> 16); - sum = htons (0xffff - sum); + sum = htons(0xffff - sum); return sum; } @@ -232,11 +227,11 @@ calc_checksum (const uint16_t * data, unsigned int bytes) * @param other target address */ static void -send_icmp_udp (const struct in_addr *my_ip, const struct in_addr *other) +send_icmp_udp(const struct in_addr *my_ip, const struct in_addr *other) { - char packet[sizeof (struct ip_header) * 2 + - sizeof (struct icmp_ttl_exceeded_header) + - sizeof (struct udp_header)]; + char packet[sizeof(struct ip_header) * 2 + + sizeof(struct icmp_ttl_exceeded_header) + + sizeof(struct udp_header)]; struct ip_header ip_pkt; struct icmp_ttl_exceeded_header icmp_pkt; struct udp_header udp_pkt; @@ -249,11 +244,11 @@ send_icmp_udp (const struct in_addr *my_ip, const struct in_addr *other) ip_pkt.vers_ihl = 0x45; ip_pkt.tos = 0; #ifdef FREEBSD - ip_pkt.pkt_len = sizeof (packet); /* Workaround PR kern/21737 */ + ip_pkt.pkt_len = sizeof(packet); /* Workaround PR kern/21737 */ #else - ip_pkt.pkt_len = htons (sizeof (packet)); + ip_pkt.pkt_len = htons(sizeof(packet)); #endif - ip_pkt.id = htons (PACKET_ID); + ip_pkt.id = htons(PACKET_ID); ip_pkt.flags_frag_offset = 0; ip_pkt.ttl = 128; ip_pkt.proto = IPPROTO_ICMP; @@ -261,27 +256,27 @@ send_icmp_udp (const struct in_addr *my_ip, const struct in_addr *other) ip_pkt.src_ip = my_ip->s_addr; ip_pkt.dst_ip = other->s_addr; ip_pkt.checksum = - htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header))); - GNUNET_memcpy (&packet[off], - &ip_pkt, - sizeof (struct ip_header)); - off += sizeof (struct ip_header); + htons(calc_checksum((uint16_t *)&ip_pkt, sizeof(struct ip_header))); + GNUNET_memcpy(&packet[off], + &ip_pkt, + sizeof(struct ip_header)); + off += sizeof(struct ip_header); icmp_pkt.type = ICMP_TIME_EXCEEDED; icmp_pkt.code = 0; icmp_pkt.checksum = 0; icmp_pkt.unused = 0; - GNUNET_memcpy (&packet[off], - &icmp_pkt, - sizeof (struct icmp_ttl_exceeded_header)); - off += sizeof (struct icmp_ttl_exceeded_header); + GNUNET_memcpy(&packet[off], + &icmp_pkt, + sizeof(struct icmp_ttl_exceeded_header)); + off += sizeof(struct icmp_ttl_exceeded_header); /* ip header of the presumably 'lost' udp packet */ ip_pkt.vers_ihl = 0x45; ip_pkt.tos = 0; ip_pkt.pkt_len = - htons (sizeof (struct ip_header) + sizeof (struct udp_header)); - ip_pkt.id = htons (0); + htons(sizeof(struct ip_header) + sizeof(struct udp_header)); + ip_pkt.id = htons(0); ip_pkt.flags_frag_offset = 0; ip_pkt.ttl = 128; ip_pkt.proto = IPPROTO_UDP; @@ -289,49 +284,49 @@ send_icmp_udp (const struct in_addr *my_ip, const struct in_addr *other) ip_pkt.src_ip = other->s_addr; ip_pkt.dst_ip = dummy.s_addr; ip_pkt.checksum = - htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header))); - GNUNET_memcpy (&packet[off], - &ip_pkt, - sizeof (struct ip_header)); - off += sizeof (struct ip_header); + htons(calc_checksum((uint16_t *)&ip_pkt, sizeof(struct ip_header))); + GNUNET_memcpy(&packet[off], + &ip_pkt, + sizeof(struct ip_header)); + off += sizeof(struct ip_header); /* build UDP header */ - udp_pkt.src_port = htons (NAT_TRAV_PORT); - udp_pkt.dst_port = htons (NAT_TRAV_PORT); - udp_pkt.length = htons (port); + udp_pkt.src_port = htons(NAT_TRAV_PORT); + udp_pkt.dst_port = htons(NAT_TRAV_PORT); + udp_pkt.length = htons(port); udp_pkt.crc = 0; - GNUNET_memcpy (&packet[off], - &udp_pkt, - sizeof (struct udp_header)); - off += sizeof (struct udp_header); + GNUNET_memcpy(&packet[off], + &udp_pkt, + sizeof(struct udp_header)); + off += sizeof(struct udp_header); /* set ICMP checksum */ icmp_pkt.checksum = - htons (calc_checksum - ((uint16_t *) & packet[sizeof (struct ip_header)], - sizeof (struct icmp_ttl_exceeded_header) + - sizeof (struct ip_header) + sizeof (struct udp_header))); - GNUNET_memcpy (&packet[sizeof (struct ip_header)], - &icmp_pkt, - sizeof (struct icmp_ttl_exceeded_header)); - - memset (&dst, 0, sizeof (dst)); + htons(calc_checksum + ((uint16_t *)&packet[sizeof(struct ip_header)], + sizeof(struct icmp_ttl_exceeded_header) + + sizeof(struct ip_header) + sizeof(struct udp_header))); + GNUNET_memcpy(&packet[sizeof(struct ip_header)], + &icmp_pkt, + sizeof(struct icmp_ttl_exceeded_header)); + + memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN - dst.sin_len = sizeof (struct sockaddr_in); + dst.sin_len = sizeof(struct sockaddr_in); #endif dst.sin_addr = *other; err = - sendto (rawsock, packet, sizeof (packet), 0, (struct sockaddr *) &dst, - sizeof (dst)); + sendto(rawsock, packet, sizeof(packet), 0, (struct sockaddr *)&dst, + sizeof(dst)); if (err < 0) - { - fprintf (stderr, "sendto failed: %s\n", strerror (errno)); - } - else if (sizeof (packet) != (size_t) err) - { - fprintf (stderr, "Error: partial send of ICMP message with size %lu\n", (unsigned long) off); - } + { + fprintf(stderr, "sendto failed: %s\n", strerror(errno)); + } + else if (sizeof(packet) != (size_t)err) + { + fprintf(stderr, "Error: partial send of ICMP message with size %lu\n", (unsigned long)off); + } } @@ -342,15 +337,15 @@ send_icmp_udp (const struct in_addr *my_ip, const struct in_addr *other) * @param other target address */ static void -send_icmp (const struct in_addr *my_ip, const struct in_addr *other) +send_icmp(const struct in_addr *my_ip, const struct in_addr *other) { struct ip_header ip_pkt; struct icmp_ttl_exceeded_header icmp_ttl; struct icmp_echo_header icmp_echo; struct sockaddr_in dst; - char packet[sizeof (struct ip_header) * 2 + - sizeof (struct icmp_ttl_exceeded_header) + - sizeof (struct icmp_echo_header)]; + char packet[sizeof(struct ip_header) * 2 + + sizeof(struct icmp_ttl_exceeded_header) + + sizeof(struct icmp_echo_header)]; size_t off; int err; @@ -359,11 +354,11 @@ send_icmp (const struct in_addr *my_ip, const struct in_addr *other) ip_pkt.vers_ihl = 0x45; ip_pkt.tos = 0; #ifdef FREEBSD - ip_pkt.pkt_len = sizeof (packet); /* Workaround PR kern/21737 */ + ip_pkt.pkt_len = sizeof(packet); /* Workaround PR kern/21737 */ #else - ip_pkt.pkt_len = htons (sizeof (packet)); + ip_pkt.pkt_len = htons(sizeof(packet)); #endif - ip_pkt.id = htons (PACKET_ID); + ip_pkt.id = htons(PACKET_ID); ip_pkt.flags_frag_offset = 0; ip_pkt.ttl = IPDEFTTL; ip_pkt.proto = IPPROTO_ICMP; @@ -371,28 +366,28 @@ send_icmp (const struct in_addr *my_ip, const struct in_addr *other) ip_pkt.src_ip = my_ip->s_addr; ip_pkt.dst_ip = other->s_addr; ip_pkt.checksum = - htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header))); - GNUNET_memcpy (&packet[off], - &ip_pkt, - sizeof (struct ip_header)); - off = sizeof (ip_pkt); + htons(calc_checksum((uint16_t *)&ip_pkt, sizeof(struct ip_header))); + GNUNET_memcpy(&packet[off], + &ip_pkt, + sizeof(struct ip_header)); + off = sizeof(ip_pkt); /* icmp reply: time exceeded */ icmp_ttl.type = ICMP_TIME_EXCEEDED; icmp_ttl.code = 0; icmp_ttl.checksum = 0; icmp_ttl.unused = 0; - GNUNET_memcpy (&packet[off], - &icmp_ttl, - sizeof (struct icmp_ttl_exceeded_header)); - off += sizeof (struct icmp_ttl_exceeded_header); + GNUNET_memcpy(&packet[off], + &icmp_ttl, + sizeof(struct icmp_ttl_exceeded_header)); + off += sizeof(struct icmp_ttl_exceeded_header); /* ip header of the presumably 'lost' udp packet */ ip_pkt.vers_ihl = 0x45; ip_pkt.tos = 0; ip_pkt.pkt_len = - htons (sizeof (struct ip_header) + sizeof (struct icmp_echo_header)); - ip_pkt.id = htons (PACKET_ID); + htons(sizeof(struct ip_header) + sizeof(struct icmp_echo_header)); + ip_pkt.id = htons(PACKET_ID); ip_pkt.flags_frag_offset = 0; ip_pkt.ttl = 1; /* real TTL would be 1 on a time exceeded packet */ ip_pkt.proto = IPPROTO_ICMP; @@ -400,57 +395,57 @@ send_icmp (const struct in_addr *my_ip, const struct in_addr *other) ip_pkt.dst_ip = dummy.s_addr; ip_pkt.checksum = 0; ip_pkt.checksum = - htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header))); - GNUNET_memcpy (&packet[off], - &ip_pkt, - sizeof (struct ip_header)); - off += sizeof (struct ip_header); + htons(calc_checksum((uint16_t *)&ip_pkt, sizeof(struct ip_header))); + GNUNET_memcpy(&packet[off], + &ip_pkt, + sizeof(struct ip_header)); + off += sizeof(struct ip_header); icmp_echo.type = ICMP_ECHO; icmp_echo.code = 0; - icmp_echo.reserved = htonl (port); + icmp_echo.reserved = htonl(port); icmp_echo.checksum = 0; icmp_echo.checksum = - htons (calc_checksum - ((uint16_t *) &icmp_echo, sizeof (struct icmp_echo_header))); - GNUNET_memcpy (&packet[off], - &icmp_echo, - sizeof (struct icmp_echo_header)); + htons(calc_checksum + ((uint16_t *)&icmp_echo, sizeof(struct icmp_echo_header))); + GNUNET_memcpy(&packet[off], + &icmp_echo, + sizeof(struct icmp_echo_header)); /* no go back to calculate ICMP packet checksum */ - off = sizeof (struct ip_header); + off = sizeof(struct ip_header); icmp_ttl.checksum = - htons (calc_checksum - ((uint16_t *) & packet[off], - sizeof (struct icmp_ttl_exceeded_header) + - sizeof (struct ip_header) + sizeof (struct icmp_echo_header))); - GNUNET_memcpy (&packet[off], - &icmp_ttl, - sizeof (struct icmp_ttl_exceeded_header)); + htons(calc_checksum + ((uint16_t *)&packet[off], + sizeof(struct icmp_ttl_exceeded_header) + + sizeof(struct ip_header) + sizeof(struct icmp_echo_header))); + GNUNET_memcpy(&packet[off], + &icmp_ttl, + sizeof(struct icmp_ttl_exceeded_header)); /* prepare for transmission */ - memset (&dst, 0, sizeof (dst)); + memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN - dst.sin_len = sizeof (struct sockaddr_in); + dst.sin_len = sizeof(struct sockaddr_in); #endif dst.sin_addr = *other; err = - sendto (rawsock, packet, sizeof (packet), 0, (struct sockaddr *) &dst, - sizeof (dst)); + sendto(rawsock, packet, sizeof(packet), 0, (struct sockaddr *)&dst, + sizeof(dst)); if (err < 0) - { - fprintf (stderr, "sendto failed: %s\n", strerror (errno)); - } - else if (sizeof (packet) != (size_t) err) - { - fprintf (stderr, "Error: partial send of ICMP message\n"); - } + { + fprintf(stderr, "sendto failed: %s\n", strerror(errno)); + } + else if (sizeof(packet) != (size_t)err) + { + fprintf(stderr, "Error: partial send of ICMP message\n"); + } } int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { const int one = 1; struct in_addr external; @@ -461,80 +456,80 @@ main (int argc, char *const *argv) int global_ret; /* Create an ICMP raw socket for writing (only operation that requires root) */ - rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_RAW); + rawsock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); raw_eno = errno; /* for later error checking */ /* now drop root privileges */ - uid = getuid (); + uid = getuid(); #ifdef HAVE_SETRESUID - if (0 != setresuid (uid, uid, uid)) - { - fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno)); - global_ret = 1; - goto cleanup; - } + if (0 != setresuid(uid, uid, uid)) + { + fprintf(stderr, "Failed to setresuid: %s\n", strerror(errno)); + global_ret = 1; + goto cleanup; + } #else - if (0 != (setuid (uid) | seteuid (uid))) - { - fprintf (stderr, "Failed to setuid: %s\n", strerror (errno)); - global_ret = 2; - goto cleanup; - } + if (0 != (setuid(uid) | seteuid(uid))) + { + fprintf(stderr, "Failed to setuid: %s\n", strerror(errno)); + global_ret = 2; + goto cleanup; + } #endif if (-1 == rawsock) - { - fprintf (stderr, "Error opening RAW socket: %s\n", strerror (raw_eno)); - global_ret = 3; - goto cleanup; - } + { + fprintf(stderr, "Error opening RAW socket: %s\n", strerror(raw_eno)); + global_ret = 3; + goto cleanup; + } if (0 != - setsockopt (rawsock, SOL_SOCKET, SO_BROADCAST, (char *) &one, sizeof (one))) - { - fprintf (stderr, "setsockopt failed: %s\n", strerror (errno)); - global_ret = 4; - goto cleanup; - } + setsockopt(rawsock, SOL_SOCKET, SO_BROADCAST, (char *)&one, sizeof(one))) + { + fprintf(stderr, "setsockopt failed: %s\n", strerror(errno)); + global_ret = 4; + goto cleanup; + } if (0 != - setsockopt (rawsock, IPPROTO_IP, IP_HDRINCL, (char *) &one, sizeof (one))) - { - fprintf (stderr, "setsockopt failed: %s\n", strerror (errno)); - global_ret = 5; - goto cleanup; - } + setsockopt(rawsock, IPPROTO_IP, IP_HDRINCL, (char *)&one, sizeof(one))) + { + fprintf(stderr, "setsockopt failed: %s\n", strerror(errno)); + global_ret = 5; + goto cleanup; + } if (4 != argc) - { - fprintf (stderr, - "This program must be started with our IP, the targets external IP, and our port as arguments.\n"); - global_ret = 6; - goto cleanup; - } - if ((1 != inet_pton (AF_INET, argv[1], &external)) || - (1 != inet_pton (AF_INET, argv[2], &target))) - { - fprintf (stderr, "Error parsing IPv4 address: %s\n", strerror (errno)); - global_ret = 7; - goto cleanup; - } - if ((1 != sscanf (argv[3], "%u", &p)) || (0 == p) || (0xFFFF < p)) - { - fprintf (stderr, "Error parsing port value `%s'\n", argv[3]); - global_ret = 8; - goto cleanup; - } - port = (uint16_t) p; - if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) - { - fprintf (stderr, "Internal error converting dummy IP to binary.\n"); - global_ret = 9; - goto cleanup; - } - send_icmp (&external, &target); - send_icmp_udp (&external, &target); + { + fprintf(stderr, + "This program must be started with our IP, the targets external IP, and our port as arguments.\n"); + global_ret = 6; + goto cleanup; + } + if ((1 != inet_pton(AF_INET, argv[1], &external)) || + (1 != inet_pton(AF_INET, argv[2], &target))) + { + fprintf(stderr, "Error parsing IPv4 address: %s\n", strerror(errno)); + global_ret = 7; + goto cleanup; + } + if ((1 != sscanf(argv[3], "%u", &p)) || (0 == p) || (0xFFFF < p)) + { + fprintf(stderr, "Error parsing port value `%s'\n", argv[3]); + global_ret = 8; + goto cleanup; + } + port = (uint16_t)p; + if (1 != inet_pton(AF_INET, DUMMY_IP, &dummy)) + { + fprintf(stderr, "Internal error converting dummy IP to binary.\n"); + global_ret = 9; + goto cleanup; + } + send_icmp(&external, &target); + send_icmp_udp(&external, &target); global_ret = 0; - cleanup: +cleanup: if (-1 != rawsock) - (void) close (rawsock); + (void)close(rawsock); return global_ret; } diff --git a/src/nat/gnunet-helper-nat-server-windows.c b/src/nat/gnunet-helper-nat-server-windows.c index f1b4896e8..13a4d8e6f 100644 --- a/src/nat/gnunet-helper-nat-server-windows.c +++ b/src/nat/gnunet-helper-nat-server-windows.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/nat/gnunet-helper-nat-server-windows.c @@ -42,7 +42,7 @@ */ #define _GNU_SOURCE /* Instead of including gnunet_common.h */ -#define GNUNET_memcpy(dst,src,n) do { if (0 != n) { (void) memcpy (dst,src,n); } } while (0) +#define GNUNET_memcpy(dst, src, n) do { if (0 != n) { (void)memcpy(dst, src, n); } } while (0) #define FD_SETSIZE 1024 #include @@ -94,9 +94,7 @@ /** * IPv4 header. */ -struct ip_header -{ - +struct ip_header { /** * Version (4 bits) + Internet header length (4 bits) */ @@ -151,8 +149,7 @@ struct ip_header /** * Format of ICMP packet. */ -struct icmp_ttl_exceeded_header -{ +struct icmp_ttl_exceeded_header { uint8_t type; uint8_t code; @@ -164,8 +161,7 @@ struct icmp_ttl_exceeded_header /* followed by original payload */ }; -struct icmp_echo_header -{ +struct icmp_echo_header { uint8_t type; uint8_t code; @@ -178,8 +174,7 @@ struct icmp_echo_header /** * Beginning of UDP packet. */ -struct udp_header -{ +struct udp_header { uint16_t src_port; uint16_t dst_port; @@ -223,7 +218,7 @@ static struct in_addr dummy; * @return the CRC 16. */ static uint16_t -calc_checksum (const uint16_t * data, unsigned int bytes) +calc_checksum(const uint16_t * data, unsigned int bytes) { uint32_t sum; unsigned int i; @@ -232,7 +227,7 @@ calc_checksum (const uint16_t * data, unsigned int bytes) for (i = 0; i < bytes / 2; i++) sum += data[i]; sum = (sum & 0xffff) + (sum >> 16); - sum = htons (0xffff - sum); + sum = htons(0xffff - sum); return sum; } @@ -246,14 +241,14 @@ calc_checksum (const uint16_t * data, unsigned int bytes) * @return 1 on success */ static int -inet_pton (int af, const char *cp, struct in_addr *buf) +inet_pton(int af, const char *cp, struct in_addr *buf) { - buf->s_addr = inet_addr (cp); + buf->s_addr = inet_addr(cp); if (buf->s_addr == INADDR_NONE) - { - fprintf (stderr, "Error %d handling address %s", WSAGetLastError (), cp); - return 0; - } + { + fprintf(stderr, "Error %d handling address %s", WSAGetLastError(), cp); + return 0; + } return 1; } @@ -264,9 +259,9 @@ inet_pton (int af, const char *cp, struct in_addr *buf) * @param my_ip source address (our ip address) */ static void -send_icmp_echo (const struct in_addr *my_ip) +send_icmp_echo(const struct in_addr *my_ip) { - char packet[sizeof (struct ip_header) + sizeof (struct icmp_echo_header)]; + char packet[sizeof(struct ip_header) + sizeof(struct icmp_echo_header)]; struct icmp_echo_header icmp_echo; struct ip_header ip_pkt; struct sockaddr_in dst; @@ -276,8 +271,8 @@ send_icmp_echo (const struct in_addr *my_ip) off = 0; ip_pkt.vers_ihl = 0x45; ip_pkt.tos = 0; - ip_pkt.pkt_len = htons (sizeof (packet)); - ip_pkt.id = htons (PACKET_ID); + ip_pkt.pkt_len = htons(sizeof(packet)); + ip_pkt.id = htons(PACKET_ID); ip_pkt.flags_frag_offset = 0; ip_pkt.ttl = IPDEFTTL; ip_pkt.proto = IPPROTO_ICMP; @@ -285,35 +280,35 @@ send_icmp_echo (const struct in_addr *my_ip) ip_pkt.src_ip = my_ip->s_addr; ip_pkt.dst_ip = dummy.s_addr; ip_pkt.checksum = - htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header))); - GNUNET_memcpy (&packet[off], &ip_pkt, sizeof (struct ip_header)); - off += sizeof (struct ip_header); + htons(calc_checksum((uint16_t *)&ip_pkt, sizeof(struct ip_header))); + GNUNET_memcpy(&packet[off], &ip_pkt, sizeof(struct ip_header)); + off += sizeof(struct ip_header); icmp_echo.type = ICMP_ECHO; icmp_echo.code = 0; icmp_echo.reserved = 0; icmp_echo.checksum = 0; icmp_echo.checksum = - htons (calc_checksum - ((uint16_t *) & icmp_echo, sizeof (struct icmp_echo_header))); - GNUNET_memcpy (&packet[off], &icmp_echo, sizeof (struct icmp_echo_header)); - off += sizeof (struct icmp_echo_header); + htons(calc_checksum + ((uint16_t *)&icmp_echo, sizeof(struct icmp_echo_header))); + GNUNET_memcpy(&packet[off], &icmp_echo, sizeof(struct icmp_echo_header)); + off += sizeof(struct icmp_echo_header); - memset (&dst, 0, sizeof (dst)); + memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; dst.sin_addr = dummy; err = - sendto (rawsock, packet, off, 0, (struct sockaddr *) &dst, sizeof (dst)); + sendto(rawsock, packet, off, 0, (struct sockaddr *)&dst, sizeof(dst)); if (err < 0) - { + { #if VERBOSE - fprintf (stderr, "sendto failed: %s\n", strerror (errno)); + fprintf(stderr, "sendto failed: %s\n", strerror(errno)); #endif - } + } else if (err != off) - { - fprintf (stderr, "Error: partial send of ICMP message\n"); - } + { + fprintf(stderr, "Error: partial send of ICMP message\n"); + } } @@ -321,26 +316,26 @@ send_icmp_echo (const struct in_addr *my_ip) * Send a UDP message to the dummy IP. */ static void -send_udp () +send_udp() { struct sockaddr_in dst; ssize_t err; - memset (&dst, 0, sizeof (dst)); + memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; dst.sin_addr = dummy; - dst.sin_port = htons (NAT_TRAV_PORT); - err = sendto (udpsock, NULL, 0, 0, (struct sockaddr *) &dst, sizeof (dst)); + dst.sin_port = htons(NAT_TRAV_PORT); + err = sendto(udpsock, NULL, 0, 0, (struct sockaddr *)&dst, sizeof(dst)); if (err < 0) - { + { #if VERBOSE - fprintf (stderr, "sendto failed: %s\n", strerror (errno)); + fprintf(stderr, "sendto failed: %s\n", strerror(errno)); #endif - } + } else if (0 != err) - { - fprintf (stderr, "Error: partial send of ICMP message\n"); - } + { + fprintf(stderr, "Error: partial send of ICMP message\n"); + } } @@ -348,7 +343,7 @@ send_udp () * We've received an ICMP response. Process it. */ static void -process_icmp_response () +process_icmp_response() { char buf[65536]; ssize_t have; @@ -361,78 +356,80 @@ process_icmp_response () uint16_t port; DWORD ssize; - have = read (icmpsock, buf, sizeof (buf)); + have = read(icmpsock, buf, sizeof(buf)); if (have == -1) - { - fprintf (stderr, "Error reading raw socket: %s\n", strerror (errno)); - return; - } + { + fprintf(stderr, "Error reading raw socket: %s\n", strerror(errno)); + return; + } #if VERBOSE - fprintf (stderr, "Received message of %u bytes\n", (unsigned int) have); + fprintf(stderr, "Received message of %u bytes\n", (unsigned int)have); #endif if (have < - (ssize_t) (sizeof (struct ip_header) + - sizeof (struct icmp_ttl_exceeded_header) + - sizeof (struct ip_header))) - { - /* malformed */ - return; - } + (ssize_t)(sizeof(struct ip_header) + + sizeof(struct icmp_ttl_exceeded_header) + + sizeof(struct ip_header))) + { + /* malformed */ + return; + } off = 0; - GNUNET_memcpy (&ip_pkt, &buf[off], sizeof (struct ip_header)); - off += sizeof (struct ip_header); - GNUNET_memcpy (&source_ip, &ip_pkt.src_ip, sizeof (source_ip)); - GNUNET_memcpy (&icmp_ttl, &buf[off], sizeof (struct icmp_ttl_exceeded_header)); - off += sizeof (struct icmp_ttl_exceeded_header); + GNUNET_memcpy(&ip_pkt, &buf[off], sizeof(struct ip_header)); + off += sizeof(struct ip_header); + GNUNET_memcpy(&source_ip, &ip_pkt.src_ip, sizeof(source_ip)); + GNUNET_memcpy(&icmp_ttl, &buf[off], sizeof(struct icmp_ttl_exceeded_header)); + off += sizeof(struct icmp_ttl_exceeded_header); if ((ICMP_TIME_EXCEEDED != icmp_ttl.type) || (0 != icmp_ttl.code)) - { - /* different type than what we want */ - return; - } - /* skip 2nd IP header */ - GNUNET_memcpy (&ip_pkt, &buf[off], sizeof (struct ip_header)); - off += sizeof (struct ip_header); - - switch (ip_pkt.proto) - { - case IPPROTO_ICMP: - if (have != - (sizeof (struct ip_header) * 2 + - sizeof (struct icmp_ttl_exceeded_header) + - sizeof (struct icmp_echo_header))) { - /* malformed */ + /* different type than what we want */ return; } - /* grab ICMP ECHO content */ - GNUNET_memcpy (&icmp_echo, &buf[off], sizeof (struct icmp_echo_header)); - port = (uint16_t) ntohl (icmp_echo.reserved); - break; - case IPPROTO_UDP: - if (have != - (sizeof (struct ip_header) * 2 + - sizeof (struct icmp_ttl_exceeded_header) + sizeof (struct udp_header))) + /* skip 2nd IP header */ + GNUNET_memcpy(&ip_pkt, &buf[off], sizeof(struct ip_header)); + off += sizeof(struct ip_header); + + switch (ip_pkt.proto) { - /* malformed */ + case IPPROTO_ICMP: + if (have != + (sizeof(struct ip_header) * 2 + + sizeof(struct icmp_ttl_exceeded_header) + + sizeof(struct icmp_echo_header))) + { + /* malformed */ + return; + } + /* grab ICMP ECHO content */ + GNUNET_memcpy(&icmp_echo, &buf[off], sizeof(struct icmp_echo_header)); + port = (uint16_t)ntohl(icmp_echo.reserved); + break; + + case IPPROTO_UDP: + if (have != + (sizeof(struct ip_header) * 2 + + sizeof(struct icmp_ttl_exceeded_header) + sizeof(struct udp_header))) + { + /* malformed */ + return; + } + /* grab UDP content */ + GNUNET_memcpy(&udp_pkt, &buf[off], sizeof(struct udp_header)); + port = ntohs(udp_pkt.length); + break; + + default: + /* different type than what we want */ return; } - /* grab UDP content */ - GNUNET_memcpy (&udp_pkt, &buf[off], sizeof (struct udp_header)); - port = ntohs (udp_pkt.length); - break; - default: - /* different type than what we want */ - return; - } - - ssize = sizeof (buf); - WSAAddressToString ((LPSOCKADDR) & source_ip, sizeof (source_ip), NULL, buf, - &ssize); + + ssize = sizeof(buf); + WSAAddressToString((LPSOCKADDR)&source_ip, sizeof(source_ip), NULL, buf, + &ssize); if (port == 0) - fprintf (stdout, "%s\n", buf); + fprintf(stdout, "%s\n", buf); else - fprintf (stdout, "%s:%u\n", buf, (unsigned int) port); - fflush (stdout); + fprintf(stdout, "%s:%u\n", buf, (unsigned int)port); + fflush(stdout); } @@ -442,16 +439,16 @@ process_icmp_response () * @return INVALID_SOCKET on error */ static SOCKET -make_icmp_socket () +make_icmp_socket() { SOCKET ret; - ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP); + ret = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); if (INVALID_SOCKET == ret) - { - fprintf (stderr, "Error opening RAW socket: %s\n", strerror (errno)); - return INVALID_SOCKET; - } + { + fprintf(stderr, "Error opening RAW socket: %s\n", strerror(errno)); + return INVALID_SOCKET; + } return ret; } @@ -462,34 +459,34 @@ make_icmp_socket () * @return INVALID_SOCKET on error */ static SOCKET -make_raw_socket () +make_raw_socket() { DWORD bOptVal = TRUE; - int bOptLen = sizeof (bOptVal); + int bOptLen = sizeof(bOptVal); - rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP); + rawsock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); if (INVALID_SOCKET == rawsock) - { - fprintf (stderr, "Error opening RAW socket: %s\n", strerror (errno)); - return INVALID_SOCKET; - } + { + fprintf(stderr, "Error opening RAW socket: %s\n", strerror(errno)); + return INVALID_SOCKET; + } if (0 != - setsockopt (rawsock, SOL_SOCKET, SO_BROADCAST, (char *) &bOptVal, - bOptLen)) - { - fprintf (stderr, "Error setting SO_BROADCAST to ON: %s\n", - strerror (errno)); - closesocket (rawsock); - return INVALID_SOCKET; - } + setsockopt(rawsock, SOL_SOCKET, SO_BROADCAST, (char *)&bOptVal, + bOptLen)) + { + fprintf(stderr, "Error setting SO_BROADCAST to ON: %s\n", + strerror(errno)); + closesocket(rawsock); + return INVALID_SOCKET; + } if (0 != - setsockopt (rawsock, IPPROTO_IP, IP_HDRINCL, (char *) &bOptVal, bOptLen)) - { - fprintf (stderr, "Error setting IP_HDRINCL to ON: %s\n", strerror (errno)); - closesocket (rawsock); - return INVALID_SOCKET; - } + setsockopt(rawsock, IPPROTO_IP, IP_HDRINCL, (char *)&bOptVal, bOptLen)) + { + fprintf(stderr, "Error setting IP_HDRINCL to ON: %s\n", strerror(errno)); + closesocket(rawsock); + return INVALID_SOCKET; + } return rawsock; } @@ -501,33 +498,33 @@ make_raw_socket () * @return INVALID_SOCKET on error */ static SOCKET -make_udp_socket (const struct in_addr *my_ip) +make_udp_socket(const struct in_addr *my_ip) { SOCKET ret; struct sockaddr_in addr; - ret = socket (AF_INET, SOCK_DGRAM, 0); + ret = socket(AF_INET, SOCK_DGRAM, 0); if (INVALID_SOCKET == ret) - { - fprintf (stderr, "Error opening UDP socket: %s\n", strerror (errno)); - return INVALID_SOCKET; - } - memset (&addr, 0, sizeof (addr)); + { + fprintf(stderr, "Error opening UDP socket: %s\n", strerror(errno)); + return INVALID_SOCKET; + } + memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr = *my_ip; - addr.sin_port = htons (NAT_TRAV_PORT); - if (0 != bind (ret, (struct sockaddr *) &addr, sizeof (addr))) - { - fprintf (stderr, "Error binding UDP socket to port %u: %s\n", NAT_TRAV_PORT, - strerror (errno)); - /* likely problematic, but not certain, try to continue */ - } + addr.sin_port = htons(NAT_TRAV_PORT); + if (0 != bind(ret, (struct sockaddr *)&addr, sizeof(addr))) + { + fprintf(stderr, "Error binding UDP socket to port %u: %s\n", NAT_TRAV_PORT, + strerror(errno)); + /* likely problematic, but not certain, try to continue */ + } return ret; } int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct in_addr external; fd_set rs; @@ -535,79 +532,79 @@ main (int argc, char *const *argv) WSADATA wsaData; unsigned int alt = 0; - if ( (argc > 1) && (0 != strcmp (argv[1], "-d"))) - { - privilege_testing = TRUE; - fprintf (stderr, - "%s", - "DEBUG: Running binary in privilege testing mode."); - argv++; - argc--; - } + if ((argc > 1) && (0 != strcmp(argv[1], "-d"))) + { + privilege_testing = TRUE; + fprintf(stderr, + "%s", + "DEBUG: Running binary in privilege testing mode."); + argv++; + argc--; + } if (2 != argc) - { - fprintf (stderr, - "This program must be started with our (internal NAT) IP as the only argument.\n"); - return 1; - } - if (1 != inet_pton (AF_INET, argv[1], &external)) - { - fprintf (stderr, "Error parsing IPv4 address: %s, error %s\n", argv[1], - strerror (errno)); - return 1; - } - if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) - { - fprintf (stderr, "Internal error converting dummy IP to binary.\n"); - return 2; - } - if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0) - { - fprintf (stderr, "Failed to find Winsock 2.1 or better.\n"); - return 2; - } - if (INVALID_SOCKET == (icmpsock = make_icmp_socket ())) - { - return 3; - } - if (INVALID_SOCKET == (make_raw_socket ())) - { - closesocket (icmpsock); - return 3; - } - if (INVALID_SOCKET == (udpsock = make_udp_socket (&external))) - { - closesocket (icmpsock); - closesocket (rawsock); - return 3; - } - - while ( ! privilege_testing) - { - FD_ZERO (&rs); - FD_SET (icmpsock, &rs); - tv.tv_sec = 0; - tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; - if (-1 == select (icmpsock + 1, &rs, NULL, NULL, &tv)) { - if (errno == EINTR) - continue; - fprintf (stderr, "select failed: %s\n", strerror (errno)); - break; + fprintf(stderr, + "This program must be started with our (internal NAT) IP as the only argument.\n"); + return 1; + } + if (1 != inet_pton(AF_INET, argv[1], &external)) + { + fprintf(stderr, "Error parsing IPv4 address: %s, error %s\n", argv[1], + strerror(errno)); + return 1; + } + if (1 != inet_pton(AF_INET, DUMMY_IP, &dummy)) + { + fprintf(stderr, "Internal error converting dummy IP to binary.\n"); + return 2; + } + if (WSAStartup(MAKEWORD(2, 1), &wsaData) != 0) + { + fprintf(stderr, "Failed to find Winsock 2.1 or better.\n"); + return 2; + } + if (INVALID_SOCKET == (icmpsock = make_icmp_socket())) + { + return 3; + } + if (INVALID_SOCKET == (make_raw_socket())) + { + closesocket(icmpsock); + return 3; + } + if (INVALID_SOCKET == (udpsock = make_udp_socket(&external))) + { + closesocket(icmpsock); + closesocket(rawsock); + return 3; + } + + while (!privilege_testing) + { + FD_ZERO(&rs); + FD_SET(icmpsock, &rs); + tv.tv_sec = 0; + tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; + if (-1 == select(icmpsock + 1, &rs, NULL, NULL, &tv)) + { + if (errno == EINTR) + continue; + fprintf(stderr, "select failed: %s\n", strerror(errno)); + break; + } + if (FD_ISSET(icmpsock, &rs)) + process_icmp_response(); + if (0 == (++alt % 2)) + send_icmp_echo(&external); + else + send_udp(); } - if (FD_ISSET (icmpsock, &rs)) - process_icmp_response (); - if (0 == (++alt % 2)) - send_icmp_echo (&external); - else - send_udp (); - } /* select failed (internal error or OS out of resources) */ - closesocket (icmpsock); - closesocket (rawsock); - closesocket (udpsock); - WSACleanup (); + closesocket(icmpsock); + closesocket(rawsock); + closesocket(udpsock); + WSACleanup(); if (privilege_testing) return 0; return 4; diff --git a/src/nat/gnunet-helper-nat-server.c b/src/nat/gnunet-helper-nat-server.c index 78b926037..f087590c8 100644 --- a/src/nat/gnunet-helper-nat-server.c +++ b/src/nat/gnunet-helper-nat-server.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/nat/gnunet-helper-nat-server.c @@ -79,7 +79,7 @@ * @param src source of the copy, may be NULL if @a n is zero * @param n number of bytes to copy */ -#define GNUNET_memcpy(dst,src,n) do { if (0 != n) { (void) memcpy (dst,src,n); } } while (0) +#define GNUNET_memcpy(dst, src, n) do { if (0 != n) { (void)memcpy(dst, src, n); } } while (0) /** * Should we print some debug output? @@ -109,9 +109,7 @@ /** * IPv4 header. */ -struct ip_header -{ - +struct ip_header { /** * Version (4 bits) + Internet header length (4 bits) */ @@ -166,8 +164,7 @@ struct ip_header /** * Format of ICMP packet. */ -struct icmp_ttl_exceeded_header -{ +struct icmp_ttl_exceeded_header { uint8_t type; uint8_t code; @@ -179,8 +176,7 @@ struct icmp_ttl_exceeded_header /* followed by original payload */ }; -struct icmp_echo_header -{ +struct icmp_echo_header { uint8_t type; uint8_t code; @@ -194,8 +190,7 @@ struct icmp_echo_header /** * Beginning of UDP packet. */ -struct udp_header -{ +struct udp_header { uint16_t src_port; uint16_t dst_port; @@ -234,7 +229,7 @@ static struct in_addr dummy; * @return the CRC 16. */ static uint16_t -calc_checksum (const uint16_t * data, unsigned int bytes) +calc_checksum(const uint16_t * data, unsigned int bytes) { uint32_t sum; unsigned int i; @@ -243,7 +238,7 @@ calc_checksum (const uint16_t * data, unsigned int bytes) for (i = 0; i < bytes / 2; i++) sum += data[i]; sum = (sum & 0xffff) + (sum >> 16); - sum = htons (0xffff - sum); + sum = htons(0xffff - sum); return sum; } @@ -254,9 +249,9 @@ calc_checksum (const uint16_t * data, unsigned int bytes) * @param my_ip source address (our ip address) */ static void -send_icmp_echo (const struct in_addr *my_ip) +send_icmp_echo(const struct in_addr *my_ip) { - char packet[sizeof (struct ip_header) + sizeof (struct icmp_echo_header)]; + char packet[sizeof(struct ip_header) + sizeof(struct icmp_echo_header)]; struct icmp_echo_header icmp_echo; struct ip_header ip_pkt; struct sockaddr_in dst; @@ -266,8 +261,8 @@ send_icmp_echo (const struct in_addr *my_ip) off = 0; ip_pkt.vers_ihl = 0x45; ip_pkt.tos = 0; - ip_pkt.pkt_len = htons (sizeof (packet)); - ip_pkt.id = htons (PACKET_ID); + ip_pkt.pkt_len = htons(sizeof(packet)); + ip_pkt.id = htons(PACKET_ID); ip_pkt.flags_frag_offset = 0; ip_pkt.ttl = IPDEFTTL; ip_pkt.proto = IPPROTO_ICMP; @@ -275,51 +270,51 @@ send_icmp_echo (const struct in_addr *my_ip) ip_pkt.src_ip = my_ip->s_addr; ip_pkt.dst_ip = dummy.s_addr; ip_pkt.checksum = - htons (calc_checksum ((uint16_t *) & ip_pkt, - sizeof (struct ip_header))); - GNUNET_memcpy (&packet[off], - &ip_pkt, - sizeof (struct ip_header)); - off += sizeof (struct ip_header); + htons(calc_checksum((uint16_t *)&ip_pkt, + sizeof(struct ip_header))); + GNUNET_memcpy(&packet[off], + &ip_pkt, + sizeof(struct ip_header)); + off += sizeof(struct ip_header); icmp_echo.type = ICMP_ECHO; icmp_echo.code = 0; icmp_echo.checksum = 0; icmp_echo.reserved = 0; icmp_echo.checksum = - htons (calc_checksum - ((uint16_t *) & icmp_echo, - sizeof (struct icmp_echo_header))); - GNUNET_memcpy (&packet[off], - &icmp_echo, - sizeof (struct icmp_echo_header)); - off += sizeof (struct icmp_echo_header); - - memset (&dst, 0, sizeof (dst)); + htons(calc_checksum + ((uint16_t *)&icmp_echo, + sizeof(struct icmp_echo_header))); + GNUNET_memcpy(&packet[off], + &icmp_echo, + sizeof(struct icmp_echo_header)); + off += sizeof(struct icmp_echo_header); + + memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN - dst.sin_len = sizeof (struct sockaddr_in); + dst.sin_len = sizeof(struct sockaddr_in); #endif dst.sin_addr = dummy; - err = sendto (rawsock, - packet, - off, - 0, - (struct sockaddr *) &dst, - sizeof (dst)); + err = sendto(rawsock, + packet, + off, + 0, + (struct sockaddr *)&dst, + sizeof(dst)); if (err < 0) - { + { #if VERBOSE - fprintf (stderr, - "sendto failed: %s\n", - strerror (errno)); + fprintf(stderr, + "sendto failed: %s\n", + strerror(errno)); #endif - } - else if (sizeof (packet) != err) - { - fprintf (stderr, - "Error: partial send of ICMP message\n"); - } + } + else if (sizeof(packet) != err) + { + fprintf(stderr, + "Error: partial send of ICMP message\n"); + } } @@ -327,37 +322,37 @@ send_icmp_echo (const struct in_addr *my_ip) * Send a UDP message to the dummy IP. */ static void -send_udp () +send_udp() { struct sockaddr_in dst; ssize_t err; - memset (&dst, 0, sizeof (dst)); + memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN - dst.sin_len = sizeof (struct sockaddr_in); + dst.sin_len = sizeof(struct sockaddr_in); #endif dst.sin_addr = dummy; - dst.sin_port = htons (NAT_TRAV_PORT); - err = sendto (udpsock, - NULL, - 0, - 0, - (struct sockaddr *) &dst, - sizeof (dst)); + dst.sin_port = htons(NAT_TRAV_PORT); + err = sendto(udpsock, + NULL, + 0, + 0, + (struct sockaddr *)&dst, + sizeof(dst)); if (err < 0) - { + { #if VERBOSE - fprintf (stderr, - "sendto failed: %s\n", - strerror (errno)); + fprintf(stderr, + "sendto failed: %s\n", + strerror(errno)); #endif - } + } else if (0 != err) - { - fprintf (stderr, - "Error: partial send of ICMP message\n"); - } + { + fprintf(stderr, + "Error: partial send of ICMP message\n"); + } } @@ -365,7 +360,7 @@ send_udp () * We've received an ICMP response. Process it. */ static void -process_icmp_response () +process_icmp_response() { char buf[65536]; ssize_t have; @@ -377,94 +372,96 @@ process_icmp_response () size_t off; uint16_t port; - have = read (icmpsock, buf, sizeof (buf)); + have = read(icmpsock, buf, sizeof(buf)); if (-1 == have) - { - fprintf (stderr, - "Error reading raw socket: %s\n", - strerror (errno)); - return; - } + { + fprintf(stderr, + "Error reading raw socket: %s\n", + strerror(errno)); + return; + } #if VERBOSE - fprintf (stderr, - "Received message of %u bytes\n", - (unsigned int) have); + fprintf(stderr, + "Received message of %u bytes\n", + (unsigned int)have); #endif if (have < - (ssize_t) (sizeof (struct ip_header) + - sizeof (struct icmp_ttl_exceeded_header) + - sizeof (struct ip_header))) - { - /* malformed */ - return; - } + (ssize_t)(sizeof(struct ip_header) + + sizeof(struct icmp_ttl_exceeded_header) + + sizeof(struct ip_header))) + { + /* malformed */ + return; + } off = 0; - GNUNET_memcpy (&ip_pkt, - &buf[off], - sizeof (struct ip_header)); - off += sizeof (struct ip_header); - GNUNET_memcpy (&icmp_ttl, - &buf[off], - sizeof (struct icmp_ttl_exceeded_header)); - off += sizeof (struct icmp_ttl_exceeded_header); + GNUNET_memcpy(&ip_pkt, + &buf[off], + sizeof(struct ip_header)); + off += sizeof(struct ip_header); + GNUNET_memcpy(&icmp_ttl, + &buf[off], + sizeof(struct icmp_ttl_exceeded_header)); + off += sizeof(struct icmp_ttl_exceeded_header); if ((ICMP_TIME_EXCEEDED != icmp_ttl.type) || (0 != icmp_ttl.code)) - { - /* different type than what we want */ - return; - } + { + /* different type than what we want */ + return; + } /* grab source IP of 1st IP header */ source_ip.s_addr = ip_pkt.src_ip; /* skip 2nd IP header */ - GNUNET_memcpy (&ip_pkt, - &buf[off], - sizeof (struct ip_header)); - off += sizeof (struct ip_header); + GNUNET_memcpy(&ip_pkt, + &buf[off], + sizeof(struct ip_header)); + off += sizeof(struct ip_header); switch (ip_pkt.proto) - { - case IPPROTO_ICMP: - if (have != - (sizeof (struct ip_header) * 2 + - sizeof (struct icmp_ttl_exceeded_header) + - sizeof (struct icmp_echo_header))) { - /* malformed */ - return; - } - /* grab ICMP ECHO content */ - GNUNET_memcpy (&icmp_echo, - &buf[off], - sizeof (struct icmp_echo_header)); - port = (uint16_t) ntohl (icmp_echo.reserved); - break; - case IPPROTO_UDP: - if (have != - (sizeof (struct ip_header) * 2 + - sizeof (struct icmp_ttl_exceeded_header) + sizeof (struct udp_header))) - { - /* malformed */ + case IPPROTO_ICMP: + if (have != + (sizeof(struct ip_header) * 2 + + sizeof(struct icmp_ttl_exceeded_header) + + sizeof(struct icmp_echo_header))) + { + /* malformed */ + return; + } + /* grab ICMP ECHO content */ + GNUNET_memcpy(&icmp_echo, + &buf[off], + sizeof(struct icmp_echo_header)); + port = (uint16_t)ntohl(icmp_echo.reserved); + break; + + case IPPROTO_UDP: + if (have != + (sizeof(struct ip_header) * 2 + + sizeof(struct icmp_ttl_exceeded_header) + sizeof(struct udp_header))) + { + /* malformed */ + return; + } + /* grab UDP content */ + GNUNET_memcpy(&udp_pkt, + &buf[off], + sizeof(struct udp_header)); + port = ntohs(udp_pkt.length); + break; + + default: + /* different type than what we want */ return; } - /* grab UDP content */ - GNUNET_memcpy (&udp_pkt, - &buf[off], - sizeof (struct udp_header)); - port = ntohs (udp_pkt.length); - break; - default: - /* different type than what we want */ - return; - } if (port == 0) - fprintf (stdout, "%s\n", - inet_ntop (AF_INET, &source_ip, buf, sizeof (buf))); + fprintf(stdout, "%s\n", + inet_ntop(AF_INET, &source_ip, buf, sizeof(buf))); else - fprintf (stdout, "%s:%u\n", - inet_ntop (AF_INET, &source_ip, buf, sizeof (buf)), - (unsigned int) port); - fflush (stdout); + fprintf(stdout, "%s:%u\n", + inet_ntop(AF_INET, &source_ip, buf, sizeof(buf)), + (unsigned int)port); + fflush(stdout); } @@ -474,34 +471,34 @@ process_icmp_response () * @return -1 on error, 0 on success */ static int -setup_raw_socket () +setup_raw_socket() { const int one = 1; if (-1 == - setsockopt (rawsock, - SOL_SOCKET, - SO_BROADCAST, - (char *) &one, - sizeof (one))) - { - fprintf (stderr, - "setsockopt failed: %s\n", - strerror (errno)); - return -1; - } + setsockopt(rawsock, + SOL_SOCKET, + SO_BROADCAST, + (char *)&one, + sizeof(one))) + { + fprintf(stderr, + "setsockopt failed: %s\n", + strerror(errno)); + return -1; + } if (-1 == - setsockopt (rawsock, - IPPROTO_IP, - IP_HDRINCL, - (char *) &one, - sizeof (one))) - { - fprintf (stderr, - "setsockopt failed: %s\n", - strerror (errno)); - return -1; - } + setsockopt(rawsock, + IPPROTO_IP, + IP_HDRINCL, + (char *)&one, + sizeof(one))) + { + fprintf(stderr, + "setsockopt failed: %s\n", + strerror(errno)); + return -1; + } return 0; } @@ -513,45 +510,45 @@ setup_raw_socket () * @return -1 on error */ static int -make_udp_socket (const struct in_addr *my_ip) +make_udp_socket(const struct in_addr *my_ip) { int ret; struct sockaddr_in addr; - ret = socket (AF_INET, SOCK_DGRAM, 0); + ret = socket(AF_INET, SOCK_DGRAM, 0); if (-1 == ret) - { - fprintf (stderr, - "Error opening UDP socket: %s\n", - strerror (errno)); - return -1; - } - memset (&addr, 0, sizeof (addr)); + { + fprintf(stderr, + "Error opening UDP socket: %s\n", + strerror(errno)); + return -1; + } + memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN - addr.sin_len = sizeof (struct sockaddr_in); + addr.sin_len = sizeof(struct sockaddr_in); #endif addr.sin_addr = *my_ip; - addr.sin_port = htons (NAT_TRAV_PORT); - - if (0 != bind (ret, - (struct sockaddr *) &addr, - sizeof (addr))) - { - fprintf (stderr, - "Error binding UDP socket to port %u: %s\n", - NAT_TRAV_PORT, - strerror (errno)); - (void) close (ret); - return -1; - } + addr.sin_port = htons(NAT_TRAV_PORT); + + if (0 != bind(ret, + (struct sockaddr *)&addr, + sizeof(addr))) + { + fprintf(stderr, + "Error binding UDP socket to port %u: %s\n", + NAT_TRAV_PORT, + strerror(errno)); + (void)close(ret); + return -1; + } return ret; } int -main (int argc, - char *const *argv) +main(int argc, + char *const *argv) { struct in_addr external; fd_set rs; @@ -563,147 +560,147 @@ main (int argc, int global_ret; /* Create an ICMP raw socket for reading (we'll check errors later) */ - icmpsock = socket (AF_INET, - SOCK_RAW, - IPPROTO_ICMP); + icmpsock = socket(AF_INET, + SOCK_RAW, + IPPROTO_ICMP); icmp_eno = errno; /* Create an (ICMP) raw socket for writing (we'll check errors later) */ - rawsock = socket (AF_INET, - SOCK_RAW, - IPPROTO_RAW); + rawsock = socket(AF_INET, + SOCK_RAW, + IPPROTO_RAW); raw_eno = errno; udpsock = -1; /* drop root rights */ - uid = getuid (); + uid = getuid(); #ifdef HAVE_SETRESUID - if (0 != setresuid (uid, uid, uid)) - { - fprintf (stderr, - "Failed to setresuid: %s\n", - strerror (errno)); - global_ret = 1; - goto error_exit; - } + if (0 != setresuid(uid, uid, uid)) + { + fprintf(stderr, + "Failed to setresuid: %s\n", + strerror(errno)); + global_ret = 1; + goto error_exit; + } #else - if (0 != (setuid (uid) | seteuid (uid))) - { - fprintf (stderr, - "Failed to setuid: %s\n", - strerror (errno)); - global_ret = 2; - goto error_exit; - } + if (0 != (setuid(uid) | seteuid(uid))) + { + fprintf(stderr, + "Failed to setuid: %s\n", + strerror(errno)); + global_ret = 2; + goto error_exit; + } #endif /* Now that we run without root rights, we can do error checking... */ if (2 != argc) - { - fprintf (stderr, - "This program must be started with our (internal NAT) IP as the only argument.\n"); - global_ret = 3; - goto error_exit; - } - if (1 != inet_pton (AF_INET, argv[1], &external)) - { - fprintf (stderr, - "Error parsing IPv4 address: %s\n", - strerror (errno)); - global_ret = 4; - goto error_exit; - } - if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) - { - fprintf (stderr, - "Internal error converting dummy IP to binary.\n"); - global_ret = 5; - goto error_exit; - } + { + fprintf(stderr, + "This program must be started with our (internal NAT) IP as the only argument.\n"); + global_ret = 3; + goto error_exit; + } + if (1 != inet_pton(AF_INET, argv[1], &external)) + { + fprintf(stderr, + "Error parsing IPv4 address: %s\n", + strerror(errno)); + global_ret = 4; + goto error_exit; + } + if (1 != inet_pton(AF_INET, DUMMY_IP, &dummy)) + { + fprintf(stderr, + "Internal error converting dummy IP to binary.\n"); + global_ret = 5; + goto error_exit; + } /* error checking icmpsock */ if (-1 == icmpsock) - { - fprintf (stderr, - "Error opening RAW socket: %s\n", - strerror (icmp_eno)); - global_ret = 6; - goto error_exit; - } + { + fprintf(stderr, + "Error opening RAW socket: %s\n", + strerror(icmp_eno)); + global_ret = 6; + goto error_exit; + } if (icmpsock >= FD_SETSIZE) - { - /* this could happen if we were started with a large number of already-open - file descriptors... */ - fprintf (stderr, - "Socket number too large (%d > %u)\n", - icmpsock, - (unsigned int) FD_SETSIZE); - global_ret = 7; - goto error_exit; - } + { + /* this could happen if we were started with a large number of already-open + file descriptors... */ + fprintf(stderr, + "Socket number too large (%d > %u)\n", + icmpsock, + (unsigned int)FD_SETSIZE); + global_ret = 7; + goto error_exit; + } /* error checking rawsock */ if (-1 == rawsock) - { - fprintf (stderr, - "Error opening RAW socket: %s\n", - strerror (raw_eno)); - global_ret = 8; - goto error_exit; - } + { + fprintf(stderr, + "Error opening RAW socket: %s\n", + strerror(raw_eno)); + global_ret = 8; + goto error_exit; + } /* no need to check 'rawsock' against FD_SETSIZE as it is never used with 'select' */ - if (0 != setup_raw_socket ()) - { - global_ret = 9; - goto error_exit; - } + if (0 != setup_raw_socket()) + { + global_ret = 9; + goto error_exit; + } - if (-1 == (udpsock = make_udp_socket (&external))) - { - global_ret = 10; - goto error_exit; - } + if (-1 == (udpsock = make_udp_socket(&external))) + { + global_ret = 10; + goto error_exit; + } alt = 0; while (1) - { - FD_ZERO (&rs); - FD_SET (icmpsock, &rs); - tv.tv_sec = 0; - tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; - if (-1 == select (icmpsock + 1, &rs, NULL, NULL, &tv)) - { - if (errno == EINTR) - continue; - fprintf (stderr, - "select failed: %s\n", - strerror (errno)); - break; - } - if (1 == getppid ()) /* Check the parent process id, if 1 the parent has died, so we should die too */ - break; - if (FD_ISSET (icmpsock, &rs)) { - process_icmp_response (); - continue; + FD_ZERO(&rs); + FD_SET(icmpsock, &rs); + tv.tv_sec = 0; + tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; + if (-1 == select(icmpsock + 1, &rs, NULL, NULL, &tv)) + { + if (errno == EINTR) + continue; + fprintf(stderr, + "select failed: %s\n", + strerror(errno)); + break; + } + if (1 == getppid()) /* Check the parent process id, if 1 the parent has died, so we should die too */ + break; + if (FD_ISSET(icmpsock, &rs)) + { + process_icmp_response(); + continue; + } + if (0 == (++alt % 2)) + send_icmp_echo(&external); + else + send_udp(); } - if (0 == (++alt % 2)) - send_icmp_echo (&external); - else - send_udp (); - } /* select failed (internal error or OS out of resources) */ global_ret = 11; error_exit: if (-1 != icmpsock) - (void) close (icmpsock); + (void)close(icmpsock); if (-1 != rawsock) - (void) close (rawsock); + (void)close(rawsock); if (-1 != udpsock) - (void) close (udpsock); + (void)close(udpsock); return global_ret; } diff --git a/src/nat/gnunet-nat.c b/src/nat/gnunet-nat.c index 6c533374e..d82898f56 100644 --- a/src/nat/gnunet-nat.c +++ b/src/nat/gnunet-nat.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/nat/gnunet-nat.c @@ -95,13 +95,13 @@ static struct GNUNET_SCHEDULER_Task *rtask; * terminate. */ static void -test_finished () +test_finished() { if (NULL != nh) return; if (NULL != rtask) return; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -119,21 +119,21 @@ test_finished () * @param addrlen actual length of the @a addr */ static void -address_cb (void *cls, - void **app_ctx, - int add_remove, - enum GNUNET_NAT_AddressClass ac, - const struct sockaddr *addr, - socklen_t addrlen) +address_cb(void *cls, + void **app_ctx, + int add_remove, + enum GNUNET_NAT_AddressClass ac, + const struct sockaddr *addr, + socklen_t addrlen) { - (void) cls; - (void) app_ctx; - - fprintf (stdout, - "%s %s (%d)\n", - add_remove ? "+" : "-", - GNUNET_a2s (addr, addrlen), - (int) ac); + (void)cls; + (void)app_ctx; + + fprintf(stdout, + "%s %s (%d)\n", + add_remove ? "+" : "-", + GNUNET_a2s(addr, addrlen), + (int)ac); } @@ -147,13 +147,13 @@ address_cb (void *cls, * @param remote_addrlen actual length of the @a remote_addr */ static void -reversal_cb (void *cls, - const struct sockaddr *remote_addr, - socklen_t remote_addrlen) +reversal_cb(void *cls, + const struct sockaddr *remote_addr, + socklen_t remote_addrlen) { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "Connection reversal requested by %s\n", - GNUNET_a2s (remote_addr, remote_addrlen)); + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "Connection reversal requested by %s\n", + GNUNET_a2s(remote_addr, remote_addrlen)); } @@ -163,23 +163,23 @@ reversal_cb (void *cls, * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { if (NULL != nh) - { - GNUNET_NAT_unregister (nh); - nh = NULL; - } + { + GNUNET_NAT_unregister(nh); + nh = NULL; + } if (NULL != ls) - { - GNUNET_NETWORK_socket_close (ls); - ls = NULL; - } + { + GNUNET_NETWORK_socket_close(ls); + ls = NULL; + } if (NULL != rtask) - { - GNUNET_SCHEDULER_cancel (rtask); - rtask = NULL; - } + { + GNUNET_SCHEDULER_cancel(rtask); + rtask = NULL; + } } @@ -187,45 +187,45 @@ do_shutdown (void *cls) * Task to receive incoming packets for STUN processing. */ static void -stun_read_task (void *cls) +stun_read_task(void *cls) { ssize_t size; - rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - ls, - &stun_read_task, - NULL); - size = GNUNET_NETWORK_socket_recvfrom_amount (ls); + rtask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + ls, + &stun_read_task, + NULL); + size = GNUNET_NETWORK_socket_recvfrom_amount(ls); if (size > 0) - { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - global_ret = 1; - return; - } + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + global_ret = 1; + return; + } { char buf[size + 1]; struct sockaddr_storage sa; - socklen_t salen = sizeof (sa); + socklen_t salen = sizeof(sa); ssize_t ret; - ret = GNUNET_NETWORK_socket_recvfrom (ls, - buf, - size + 1, - (struct sockaddr *) &sa, - &salen); + ret = GNUNET_NETWORK_socket_recvfrom(ls, + buf, + size + 1, + (struct sockaddr *)&sa, + &salen); if (ret != size) - { - GNUNET_break (0); - GNUNET_SCHEDULER_shutdown (); - global_ret = 1; - return; - } - (void) GNUNET_NAT_stun_handle_packet (nh, - (const struct sockaddr *) &sa, - salen, - buf, - ret); + { + GNUNET_break(0); + GNUNET_SCHEDULER_shutdown(); + global_ret = 1; + return; + } + (void)GNUNET_NAT_stun_handle_packet(nh, + (const struct sockaddr *)&sa, + salen, + buf, + ret); } } @@ -239,10 +239,10 @@ stun_read_task (void *cls) * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { uint8_t af; struct sockaddr *local_sa; @@ -251,154 +251,156 @@ run (void *cls, size_t remote_len; if (use_tcp && use_udp) - { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, "Cannot use TCP and UDP\n"); - global_ret = 1; - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, "Cannot use TCP and UDP\n"); + global_ret = 1; + return; + } proto = 0; if (use_tcp) proto = IPPROTO_TCP; if (use_udp) proto = IPPROTO_UDP; - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); if (0 == proto) - { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, "Must specify either TCP or UDP\n"); - global_ret = 1; - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, "Must specify either TCP or UDP\n"); + global_ret = 1; + return; + } local_len = 0; local_sa = NULL; remote_len = 0; remote_sa = NULL; if (NULL != local_addr) - { - local_len = - (socklen_t) GNUNET_STRINGS_parse_socket_addr (local_addr, &af, &local_sa); - if (0 == local_len) { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "Invalid socket address `%s'\n", - local_addr); - goto fail_and_shutdown; + local_len = + (socklen_t)GNUNET_STRINGS_parse_socket_addr(local_addr, &af, &local_sa); + if (0 == local_len) + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "Invalid socket address `%s'\n", + local_addr); + goto fail_and_shutdown; + } } - } if (NULL != remote_addr) - { - remote_len = - GNUNET_STRINGS_parse_socket_addr (remote_addr, &af, &remote_sa); - if (0 == remote_len) { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "Invalid socket address `%s'\n", - remote_addr); - goto fail_and_shutdown; + remote_len = + GNUNET_STRINGS_parse_socket_addr(remote_addr, &af, &remote_sa); + if (0 == remote_len) + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "Invalid socket address `%s'\n", + remote_addr); + goto fail_and_shutdown; + } } - } if (NULL != local_addr) - { - if (NULL == section_name) - section_name = GNUNET_strdup ("undefined"); - nh = GNUNET_NAT_register (c, - section_name, - proto, - 1, - (const struct sockaddr **) &local_sa, - &local_len, - &address_cb, - (listen_reversal) ? &reversal_cb : NULL, - NULL); - } - else if (listen_reversal) - { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "Use of `-W` only effective in combination with `-i`\n"); - goto fail_and_shutdown; - } - - if (NULL != remote_addr) - { - int ret; - - if ((NULL == nh) || (sizeof (struct sockaddr_in) != local_len)) { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "Require IPv4 local address to initiate connection reversal\n"); - goto fail_and_shutdown; + if (NULL == section_name) + section_name = GNUNET_strdup("undefined"); + nh = GNUNET_NAT_register(c, + section_name, + proto, + 1, + (const struct sockaddr **)&local_sa, + &local_len, + &address_cb, + (listen_reversal) ? &reversal_cb : NULL, + NULL); } - if (sizeof (struct sockaddr_in) != remote_len) + else if (listen_reversal) { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "Require IPv4 reversal target address\n"); + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "Use of `-W` only effective in combination with `-i`\n"); goto fail_and_shutdown; } - GNUNET_assert (AF_INET == local_sa->sa_family); - GNUNET_assert (AF_INET == remote_sa->sa_family); - ret = GNUNET_NAT_request_reversal (nh, - (const struct sockaddr_in *) local_sa, - (const struct sockaddr_in *) remote_sa); - switch (ret) + + if (NULL != remote_addr) { - case GNUNET_SYSERR: - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "Connection reversal internal error\n"); - break; - case GNUNET_NO: - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "Connection reversal unavailable\n"); - break; - case GNUNET_OK: - /* operation in progress */ - break; + int ret; + + if ((NULL == nh) || (sizeof(struct sockaddr_in) != local_len)) + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "Require IPv4 local address to initiate connection reversal\n"); + goto fail_and_shutdown; + } + if (sizeof(struct sockaddr_in) != remote_len) + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "Require IPv4 reversal target address\n"); + goto fail_and_shutdown; + } + GNUNET_assert(AF_INET == local_sa->sa_family); + GNUNET_assert(AF_INET == remote_sa->sa_family); + ret = GNUNET_NAT_request_reversal(nh, + (const struct sockaddr_in *)local_sa, + (const struct sockaddr_in *)remote_sa); + switch (ret) + { + case GNUNET_SYSERR: + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "Connection reversal internal error\n"); + break; + + case GNUNET_NO: + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "Connection reversal unavailable\n"); + break; + + case GNUNET_OK: + /* operation in progress */ + break; + } } - } if (do_stun) - { - if (NULL == local_addr) - { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "Require local address to support STUN requests\n"); - goto fail_and_shutdown; - } - if (IPPROTO_UDP != proto) { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, "STUN only supported over UDP\n"); - goto fail_and_shutdown; + if (NULL == local_addr) + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "Require local address to support STUN requests\n"); + goto fail_and_shutdown; + } + if (IPPROTO_UDP != proto) + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, "STUN only supported over UDP\n"); + goto fail_and_shutdown; + } + ls = GNUNET_NETWORK_socket_create(af, SOCK_DGRAM, IPPROTO_UDP); + if (NULL == ls) + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, "Failed to create socket\n"); + goto fail_and_shutdown; + } + if (GNUNET_OK != GNUNET_NETWORK_socket_bind(ls, local_sa, local_len)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to bind to %s: %s\n", + GNUNET_a2s(local_sa, local_len), + strerror(errno)); + goto fail_and_shutdown; + } + rtask = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + ls, + &stun_read_task, + NULL); } - ls = GNUNET_NETWORK_socket_create (af, SOCK_DGRAM, IPPROTO_UDP); - if (NULL == ls) - { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, "Failed to create socket\n"); - goto fail_and_shutdown; - } - if (GNUNET_OK != GNUNET_NETWORK_socket_bind (ls, local_sa, local_len)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to bind to %s: %s\n", - GNUNET_a2s (local_sa, local_len), - strerror (errno)); - goto fail_and_shutdown; - } - rtask = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - ls, - &stun_read_task, - NULL); - } - GNUNET_free_non_null (remote_sa); - GNUNET_free_non_null (local_sa); - test_finished (); + GNUNET_free_non_null(remote_sa); + GNUNET_free_non_null(local_sa); + test_finished(); return; fail_and_shutdown: global_ret = 1; - GNUNET_SCHEDULER_shutdown (); - GNUNET_free_non_null (remote_sa); - GNUNET_free_non_null (local_sa); + GNUNET_SCHEDULER_shutdown(); + GNUNET_free_non_null(remote_sa); + GNUNET_free_non_null(local_sa); } @@ -410,63 +412,63 @@ fail_and_shutdown: * @return 0 on success, -1 on error */ int -main (int argc, char *const argv[]) +main(int argc, char *const argv[]) { struct GNUNET_GETOPT_CommandLineOption options[] = { - - GNUNET_GETOPT_option_string ( + GNUNET_GETOPT_option_string( 'i', "in", "ADDRESS", - gettext_noop ("which IP and port are we locally using to bind/listen to"), + gettext_noop("which IP and port are we locally using to bind/listen to"), &local_addr), - GNUNET_GETOPT_option_string ( + GNUNET_GETOPT_option_string( 'r', "remote", "ADDRESS", - gettext_noop ( + gettext_noop( "which remote IP and port should be asked for connection reversal"), &remote_addr), - GNUNET_GETOPT_option_string ( + GNUNET_GETOPT_option_string( 'S', "section", NULL, - gettext_noop ( + gettext_noop( "name of configuration section to find additional options, such as manual host punching data"), §ion_name), - GNUNET_GETOPT_option_flag ('s', - "stun", - gettext_noop ("enable STUN processing"), - &do_stun), + GNUNET_GETOPT_option_flag('s', + "stun", + gettext_noop("enable STUN processing"), + &do_stun), - GNUNET_GETOPT_option_flag ('t', "tcp", gettext_noop ("use TCP"), &use_tcp), + GNUNET_GETOPT_option_flag('t', "tcp", gettext_noop("use TCP"), &use_tcp), - GNUNET_GETOPT_option_flag ('u', "udp", gettext_noop ("use UDP"), &use_udp), + GNUNET_GETOPT_option_flag('u', "udp", gettext_noop("use UDP"), &use_udp), - GNUNET_GETOPT_option_flag ('W', - "watch", - gettext_noop ( - "watch for connection reversal requests"), - &listen_reversal), - GNUNET_GETOPT_OPTION_END}; + GNUNET_GETOPT_option_flag('W', + "watch", + gettext_noop( + "watch for connection reversal requests"), + &listen_reversal), + GNUNET_GETOPT_OPTION_END + }; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; if (GNUNET_OK != - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-nat [options]", - _ ("GNUnet NAT traversal autoconfigure daemon"), - options, - &run, - NULL)) - { - global_ret = 1; - } - GNUNET_free ((void *) argv); + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-nat [options]", + _("GNUnet NAT traversal autoconfigure daemon"), + options, + &run, + NULL)) + { + global_ret = 1; + } + GNUNET_free((void *)argv); return global_ret; } diff --git a/src/nat/gnunet-service-nat.c b/src/nat/gnunet-service-nat.c index 2498a990a..6fd09a7d9 100644 --- a/src/nat/gnunet-service-nat.c +++ b/src/nat/gnunet-service-nat.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2016, 2017 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet. + Copyright (C) 2016, 2017 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -55,24 +55,23 @@ * How often should we ask the OS about a list of active * network interfaces? */ -#define SCAN_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15) +#define SCAN_FREQ GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15) /** * How long do we wait until we forcefully terminate autoconfiguration? */ -#define AUTOCONFIG_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define AUTOCONFIG_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) /** * How often do we scan for changes in how our external (dyndns) hostname resolves? */ -#define DYNDNS_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 7) +#define DYNDNS_FREQUENCY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 7) /** * Information we track per client address. */ -struct ClientAddress -{ +struct ClientAddress { /** * Network address used by the client. */ @@ -84,15 +83,13 @@ struct ClientAddress * pending. */ struct GNUNET_NAT_MiniHandle *mh; - }; /** * List of local addresses this system has. */ -struct LocalAddressList -{ +struct LocalAddressList { /** * This is a linked list. */ @@ -131,16 +128,13 @@ struct LocalAddressList * What type of address is this? */ enum GNUNET_NAT_AddressClass ac; - }; /** * Internal data structure we track for each of our clients. */ -struct ClientHandle -{ - +struct ClientHandle { /** * Kept in a DLL. */ @@ -232,15 +226,13 @@ struct ClientHandle * Client's IPPROTO, e.g. IPPROTO_UDP or IPPROTO_TCP. */ uint8_t proto; - }; /** * External IP address as given to us via some STUN server. */ -struct StunExternalIP -{ +struct StunExternalIP { /** * Kept in a DLL. */ @@ -344,22 +336,22 @@ int enable_upnp; * @param lal entry to free */ static void -free_lal (struct LocalAddressList *lal) +free_lal(struct LocalAddressList *lal) { - GNUNET_CONTAINER_DLL_remove (lal_head, - lal_tail, - lal); + GNUNET_CONTAINER_DLL_remove(lal_head, + lal_tail, + lal); if (NULL != lal->hc) - { - GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE, - "Lost NATed local address %s, stopping NAT server\n", - GNUNET_a2s ((const struct sockaddr *) &lal->addr, - sizeof (struct sockaddr_in))); - - GN_stop_gnunet_nat_server_ (lal->hc); - lal->hc = NULL; - } - GNUNET_free (lal); + { + GNUNET_log(GNUNET_ERROR_TYPE_MESSAGE, + "Lost NATed local address %s, stopping NAT server\n", + GNUNET_a2s((const struct sockaddr *)&lal->addr, + sizeof(struct sockaddr_in))); + + GN_stop_gnunet_nat_server_(lal->hc); + lal->hc = NULL; + } + GNUNET_free(lal); } @@ -367,12 +359,12 @@ free_lal (struct LocalAddressList *lal) * Free the DLL starting at #lal_head. */ static void -destroy_lal () +destroy_lal() { struct LocalAddressList *lal; while (NULL != (lal = lal_head)) - free_lal (lal); + free_lal(lal); } @@ -385,53 +377,55 @@ destroy_lal () * @return #GNUNET_OK if message is well-formed */ static int -check_register (void *cls, - const struct GNUNET_NAT_RegisterMessage *message) +check_register(void *cls, + const struct GNUNET_NAT_RegisterMessage *message) { - uint16_t num_addrs = ntohs (message->num_addrs); - const char *off = (const char *) &message[1]; - size_t left = ntohs (message->header.size) - sizeof (*message); - - for (unsigned int i=0;inum_addrs); + const char *off = (const char *)&message[1]; + size_t left = ntohs(message->header.size) - sizeof(*message); - if (sizeof (sa_family_t) > left) + for (unsigned int i = 0; i < num_addrs; i++) { - GNUNET_break (0); - return GNUNET_SYSERR; - } - switch (sa->sa_family) - { - case AF_INET: - alen = sizeof (struct sockaddr_in); - break; - case AF_INET6: - alen = sizeof (struct sockaddr_in6); - break; + size_t alen; + const struct sockaddr *sa = (const struct sockaddr *)off; + + if (sizeof(sa_family_t) > left) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + switch (sa->sa_family) + { + case AF_INET: + alen = sizeof(struct sockaddr_in); + break; + + case AF_INET6: + alen = sizeof(struct sockaddr_in6); + break; + #if AF_UNIX - case AF_UNIX: - alen = sizeof (struct sockaddr_un); - break; + case AF_UNIX: + alen = sizeof(struct sockaddr_un); + break; #endif - default: - GNUNET_break (0); - return GNUNET_SYSERR; + default: + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (alen > left) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + off += alen; + left -= alen; } - if (alen > left) + if (left != ntohs(message->str_len)) { - GNUNET_break (0); + GNUNET_break(0); return GNUNET_SYSERR; } - off += alen; - left -= alen; - } - if (left != ntohs (message->str_len)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } return GNUNET_OK; } @@ -445,9 +439,9 @@ check_register (void *cls, * @return #GNUNET_YES if @a ip is in @a network */ static int -match_ipv4 (const char *network, - const struct in_addr *ip, - uint8_t bits) +match_ipv4(const char *network, + const struct in_addr *ip, + uint8_t bits) { struct in_addr net; @@ -455,10 +449,10 @@ match_ipv4 (const char *network, return GNUNET_YES; if (0 == bits) return GNUNET_YES; - GNUNET_assert (1 == inet_pton (AF_INET, - network, - &net)); - return ! ((ip->s_addr ^ net.s_addr) & htonl (0xFFFFFFFFu << (32 - bits))); + GNUNET_assert(1 == inet_pton(AF_INET, + network, + &net)); + return !((ip->s_addr ^ net.s_addr) & htonl(0xFFFFFFFFu << (32 - bits))); } @@ -471,9 +465,9 @@ match_ipv4 (const char *network, * @return #GNUNET_YES if @a ip is in @a network */ static int -match_ipv6 (const char *network, - const struct in6_addr *ip, - uint8_t bits) +match_ipv6(const char *network, + const struct in6_addr *ip, + uint8_t bits) { struct in6_addr net; struct in6_addr mask; @@ -481,27 +475,27 @@ match_ipv6 (const char *network, if (0 == bits) return GNUNET_YES; - GNUNET_assert (1 == inet_pton (AF_INET6, - network, - &net)); - memset (&mask, 0, sizeof (mask)); - if (0 == GNUNET_memcmp (&mask, - ip)) + GNUNET_assert(1 == inet_pton(AF_INET6, + network, + &net)); + memset(&mask, 0, sizeof(mask)); + if (0 == GNUNET_memcmp(&mask, + ip)) return GNUNET_YES; off = 0; while (bits > 8) - { - mask.s6_addr[off++] = 0xFF; - bits -= 8; - } + { + mask.s6_addr[off++] = 0xFF; + bits -= 8; + } while (bits > 0) - { - mask.s6_addr[off] = (mask.s6_addr[off] >> 1) + 0x80; - bits--; - } - for (unsigned j = 0; j < sizeof (struct in6_addr) / sizeof (uint32_t); j++) - if (((((uint32_t *) ip)[j] & ((uint32_t *) &mask)[j])) != - (((uint32_t *) &net)[j] & ((int *) &mask)[j])) + { + mask.s6_addr[off] = (mask.s6_addr[off] >> 1) + 0x80; + bits--; + } + for (unsigned j = 0; j < sizeof(struct in6_addr) / sizeof(uint32_t); j++) + if (((((uint32_t *)ip)[j] & ((uint32_t *)&mask)[j])) != + (((uint32_t *)&net)[j] & ((int *)&mask)[j])) return GNUNET_NO; return GNUNET_YES; } @@ -515,14 +509,14 @@ match_ipv6 (const char *network, * @return #GNUNET_YES if @a ip is in a NAT range */ static int -is_nat_v4 (const struct in_addr *ip) +is_nat_v4(const struct in_addr *ip) { return - match_ipv4 ("10.0.0.0", ip, 8) || /* RFC 1918 */ - match_ipv4 ("100.64.0.0", ip, 10) || /* CG-NAT, RFC 6598 */ - match_ipv4 ("192.168.0.0", ip, 12) || /* RFC 1918 */ - match_ipv4 ("169.254.0.0", ip, 16) || /* AUTO, RFC 3927 */ - match_ipv4 ("172.16.0.0", ip, 16); /* RFC 1918 */ + match_ipv4("10.0.0.0", ip, 8) || /* RFC 1918 */ + match_ipv4("100.64.0.0", ip, 10) || /* CG-NAT, RFC 6598 */ + match_ipv4("192.168.0.0", ip, 12) || /* RFC 1918 */ + match_ipv4("169.254.0.0", ip, 16) || /* AUTO, RFC 3927 */ + match_ipv4("172.16.0.0", ip, 16); /* RFC 1918 */ } @@ -534,21 +528,19 @@ is_nat_v4 (const struct in_addr *ip) * @return #GNUNET_YES if @a ip is in a NAT range */ static int -is_nat_v6 (const struct in6_addr *ip) +is_nat_v6(const struct in6_addr *ip) { return - match_ipv6 ("fc00::", ip, 7) || /* RFC 4193 */ - match_ipv6 ("fec0::", ip, 10) || /* RFC 3879 */ - match_ipv6 ("fe80::", ip, 10); /* RFC 4291, link-local */ + match_ipv6("fc00::", ip, 7) || /* RFC 4193 */ + match_ipv6("fec0::", ip, 10) || /* RFC 3879 */ + match_ipv6("fe80::", ip, 10); /* RFC 4291, link-local */ } /** * Closure for #ifc_proc. */ -struct IfcProcContext -{ - +struct IfcProcContext { /** * Head of DLL of local addresses. */ @@ -558,7 +550,6 @@ struct IfcProcContext * Tail of DLL of local addresses. */ struct LocalAddressList *lal_tail; - }; @@ -576,13 +567,13 @@ struct IfcProcContext * @return #GNUNET_OK to continue iteration, #GNUNET_SYSERR to abort */ static int -ifc_proc (void *cls, - const char *name, - int isDefault, - const struct sockaddr *addr, - const struct sockaddr *broadcast_addr, - const struct sockaddr *netmask, - socklen_t addrlen) +ifc_proc(void *cls, + const char *name, + int isDefault, + const struct sockaddr *addr, + const struct sockaddr *broadcast_addr, + const struct sockaddr *netmask, + socklen_t addrlen) { struct IfcProcContext *ifc_ctx = cls; struct LocalAddressList *lal; @@ -592,51 +583,53 @@ ifc_proc (void *cls, enum GNUNET_NAT_AddressClass ac; switch (addr->sa_family) - { - case AF_INET: - alen = sizeof (struct sockaddr_in); - ip4 = &((const struct sockaddr_in *) addr)->sin_addr; - if (match_ipv4 ("127.0.0.0", ip4, 8)) - ac = GNUNET_NAT_AC_LOOPBACK; - else if (is_nat_v4 (ip4)) - ac = GNUNET_NAT_AC_LAN; - else - ac = GNUNET_NAT_AC_GLOBAL; - break; - case AF_INET6: - alen = sizeof (struct sockaddr_in6); - ip6 = &((const struct sockaddr_in6 *) addr)->sin6_addr; - if (match_ipv6 ("::1", ip6, 128)) - ac = GNUNET_NAT_AC_LOOPBACK; - else if (is_nat_v6 (ip6)) - ac = GNUNET_NAT_AC_LAN; - else - ac = GNUNET_NAT_AC_GLOBAL; - if ( (ip6->s6_addr[11] == 0xFF) && - (ip6->s6_addr[12] == 0xFE) ) { - /* contains a MAC, be extra careful! */ - ac |= GNUNET_NAT_AC_PRIVATE; - } - break; + case AF_INET: + alen = sizeof(struct sockaddr_in); + ip4 = &((const struct sockaddr_in *)addr)->sin_addr; + if (match_ipv4("127.0.0.0", ip4, 8)) + ac = GNUNET_NAT_AC_LOOPBACK; + else if (is_nat_v4(ip4)) + ac = GNUNET_NAT_AC_LAN; + else + ac = GNUNET_NAT_AC_GLOBAL; + break; + + case AF_INET6: + alen = sizeof(struct sockaddr_in6); + ip6 = &((const struct sockaddr_in6 *)addr)->sin6_addr; + if (match_ipv6("::1", ip6, 128)) + ac = GNUNET_NAT_AC_LOOPBACK; + else if (is_nat_v6(ip6)) + ac = GNUNET_NAT_AC_LAN; + else + ac = GNUNET_NAT_AC_GLOBAL; + if ((ip6->s6_addr[11] == 0xFF) && + (ip6->s6_addr[12] == 0xFE)) + { + /* contains a MAC, be extra careful! */ + ac |= GNUNET_NAT_AC_PRIVATE; + } + break; + #if AF_UNIX - case AF_UNIX: - GNUNET_break (0); - return GNUNET_OK; + case AF_UNIX: + GNUNET_break(0); + return GNUNET_OK; #endif - default: - GNUNET_break (0); - return GNUNET_OK; - } - lal = GNUNET_malloc (sizeof (*lal)); + default: + GNUNET_break(0); + return GNUNET_OK; + } + lal = GNUNET_malloc(sizeof(*lal)); lal->af = addr->sa_family; lal->ac = ac; - GNUNET_memcpy (&lal->addr, - addr, - alen); - GNUNET_CONTAINER_DLL_insert (ifc_ctx->lal_head, - ifc_ctx->lal_tail, - lal); + GNUNET_memcpy(&lal->addr, + addr, + alen); + GNUNET_CONTAINER_DLL_insert(ifc_ctx->lal_head, + ifc_ctx->lal_tail, + lal); return GNUNET_OK; } @@ -652,30 +645,30 @@ ifc_proc (void *cls, * @param addr_len number of bytes in @a addr */ static void -notify_client (enum GNUNET_NAT_AddressClass ac, - struct ClientHandle *ch, - int add, - const void *addr, - size_t addr_len) +notify_client(enum GNUNET_NAT_AddressClass ac, + struct ClientHandle *ch, + int add, + const void *addr, + size_t addr_len) { struct GNUNET_MQ_Envelope *env; struct GNUNET_NAT_AddressChangeNotificationMessage *msg; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Notifying client about %s of IP %s\n", - add ? "addition" : "removal", - GNUNET_a2s (addr, - addr_len)); - env = GNUNET_MQ_msg_extra (msg, - addr_len, - GNUNET_MESSAGE_TYPE_NAT_ADDRESS_CHANGE); - msg->add_remove = htonl (add); - msg->addr_class = htonl (ac); - GNUNET_memcpy (&msg[1], - addr, - addr_len); - GNUNET_MQ_send (ch->mq, - env); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Notifying client about %s of IP %s\n", + add ? "addition" : "removal", + GNUNET_a2s(addr, + addr_len)); + env = GNUNET_MQ_msg_extra(msg, + addr_len, + GNUNET_MESSAGE_TYPE_NAT_ADDRESS_CHANGE); + msg->add_remove = htonl(add); + msg->addr_class = htonl(ac); + GNUNET_memcpy(&msg[1], + addr, + addr_len); + GNUNET_MQ_send(ch->mq, + env); } @@ -688,121 +681,123 @@ notify_client (enum GNUNET_NAT_AddressClass ac, * @param add #GNUNET_YES to add, #GNUNET_NO to remove */ static void -check_notify_client (struct LocalAddressList *delta, - struct ClientHandle *ch, - int add) +check_notify_client(struct LocalAddressList *delta, + struct ClientHandle *ch, + int add) { size_t alen; struct sockaddr_in v4; struct sockaddr_in6 v6; if (0 == (ch->flags & GNUNET_NAT_RF_ADDRESSES)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Not notifying client as it does not care about addresses\n"); - return; - } - switch (delta->af) - { - case AF_INET: - alen = sizeof (struct sockaddr_in); - GNUNET_memcpy (&v4, - &delta->addr, - alen); - - /* Check for client notifications */ - for (unsigned int i=0;inum_caddrs;i++) { - const struct sockaddr_in *c4; - - if (AF_INET != ch->caddrs[i].ss.ss_family) - continue; /* IPv4 not relevant */ - c4 = (const struct sockaddr_in *) &ch->caddrs[i].ss; - if ( match_ipv4 ("127.0.0.1", &c4->sin_addr, 8) && - (0 != c4->sin_addr.s_addr) && - (! match_ipv4 ("127.0.0.1", &v4.sin_addr, 8)) ) - continue; /* bound to loopback, but this is not loopback */ - if ( (! match_ipv4 ("127.0.0.1", &c4->sin_addr, 8) ) && - match_ipv4 ("127.0.0.1", &v4.sin_addr, 8) ) - continue; /* bound to non-loopback, but this is loopback */ - if ( (0 != (delta->ac & GNUNET_NAT_AC_EXTERN)) && - (0 != c4->sin_addr.s_addr) && - (! is_nat_v4 (&v4.sin_addr)) ) - continue; /* based on external-IP, but this IP is not - from private address range. */ - if ( (0 != GNUNET_memcmp (&v4.sin_addr, - &c4->sin_addr)) && - (0 != c4->sin_addr.s_addr) && - (! is_nat_v4 (&c4->sin_addr)) ) - continue; /* this IP is not from private address range, - and IP does not match. */ - - /* OK, IP seems relevant, notify client */ - if (0 == htons (v4.sin_port)) - v4.sin_port = c4->sin_port; - notify_client (delta->ac, - ch, - add, - &v4, - alen); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Not notifying client as it does not care about addresses\n"); + return; } - break; - case AF_INET6: - alen = sizeof (struct sockaddr_in6); - GNUNET_memcpy (&v6, - &delta->addr, - alen); - for (unsigned int i=0;inum_caddrs;i++) + switch (delta->af) { - const struct sockaddr_in6 *c6; - - if (AF_INET6 != ch->caddrs[i].ss.ss_family) - continue; /* IPv4 not relevant */ - c6 = (const struct sockaddr_in6 *) &ch->caddrs[i].ss; - if ( match_ipv6 ("::1", &c6->sin6_addr, 128) && - (0 != GNUNET_memcmp (&c6->sin6_addr, - &in6addr_any)) && - (! match_ipv6 ("::1", &v6.sin6_addr, 128)) ) - continue; /* bound to loopback, but this is not loopback */ - if ( (! match_ipv6 ("::1", &c6->sin6_addr, 128) ) && - match_ipv6 ("::1", &v6.sin6_addr, 128) ) - continue; /* bound to non-loopback, but this is loopback */ - if ( (0 != (delta->ac & GNUNET_NAT_AC_EXTERN)) && - (0 != GNUNET_memcmp (&c6->sin6_addr, - &in6addr_any)) && - (! is_nat_v6 (&v6.sin6_addr)) ) - continue; /* based on external-IP, but this IP is not - from private address range. */ - if ( (0 != GNUNET_memcmp (&v6.sin6_addr, - &c6->sin6_addr)) && - (0 != GNUNET_memcmp (&c6->sin6_addr, - &in6addr_any)) && - (! is_nat_v6 (&c6->sin6_addr)) ) - continue; /* this IP is not from private address range, - and IP does not match. */ - if ( (match_ipv6 ("fe80::", &c6->sin6_addr, 10)) && - (0 != GNUNET_memcmp (&c6->sin6_addr, - &in6addr_any)) && - (0 != GNUNET_memcmp (&v6.sin6_addr, - &c6->sin6_addr)) && - (0 == (delta->ac & GNUNET_NAT_AC_EXTERN)) ) - continue; /* client bound to link-local, and the other address - does not match and is not an external IP */ - - /* OK, IP seems relevant, notify client */ - if (0 == htons (v6.sin6_port)) - v6.sin6_port = c6->sin6_port; - notify_client (delta->ac, - ch, - add, - &v6, - alen); + case AF_INET: + alen = sizeof(struct sockaddr_in); + GNUNET_memcpy(&v4, + &delta->addr, + alen); + + /* Check for client notifications */ + for (unsigned int i = 0; i < ch->num_caddrs; i++) + { + const struct sockaddr_in *c4; + + if (AF_INET != ch->caddrs[i].ss.ss_family) + continue; /* IPv4 not relevant */ + c4 = (const struct sockaddr_in *)&ch->caddrs[i].ss; + if (match_ipv4("127.0.0.1", &c4->sin_addr, 8) && + (0 != c4->sin_addr.s_addr) && + (!match_ipv4("127.0.0.1", &v4.sin_addr, 8))) + continue; /* bound to loopback, but this is not loopback */ + if ((!match_ipv4("127.0.0.1", &c4->sin_addr, 8)) && + match_ipv4("127.0.0.1", &v4.sin_addr, 8)) + continue; /* bound to non-loopback, but this is loopback */ + if ((0 != (delta->ac & GNUNET_NAT_AC_EXTERN)) && + (0 != c4->sin_addr.s_addr) && + (!is_nat_v4(&v4.sin_addr))) + continue; /* based on external-IP, but this IP is not + from private address range. */ + if ((0 != GNUNET_memcmp(&v4.sin_addr, + &c4->sin_addr)) && + (0 != c4->sin_addr.s_addr) && + (!is_nat_v4(&c4->sin_addr))) + continue; /* this IP is not from private address range, + and IP does not match. */ + + /* OK, IP seems relevant, notify client */ + if (0 == htons(v4.sin_port)) + v4.sin_port = c4->sin_port; + notify_client(delta->ac, + ch, + add, + &v4, + alen); + } + break; + + case AF_INET6: + alen = sizeof(struct sockaddr_in6); + GNUNET_memcpy(&v6, + &delta->addr, + alen); + for (unsigned int i = 0; i < ch->num_caddrs; i++) + { + const struct sockaddr_in6 *c6; + + if (AF_INET6 != ch->caddrs[i].ss.ss_family) + continue; /* IPv4 not relevant */ + c6 = (const struct sockaddr_in6 *)&ch->caddrs[i].ss; + if (match_ipv6("::1", &c6->sin6_addr, 128) && + (0 != GNUNET_memcmp(&c6->sin6_addr, + &in6addr_any)) && + (!match_ipv6("::1", &v6.sin6_addr, 128))) + continue; /* bound to loopback, but this is not loopback */ + if ((!match_ipv6("::1", &c6->sin6_addr, 128)) && + match_ipv6("::1", &v6.sin6_addr, 128)) + continue; /* bound to non-loopback, but this is loopback */ + if ((0 != (delta->ac & GNUNET_NAT_AC_EXTERN)) && + (0 != GNUNET_memcmp(&c6->sin6_addr, + &in6addr_any)) && + (!is_nat_v6(&v6.sin6_addr))) + continue; /* based on external-IP, but this IP is not + from private address range. */ + if ((0 != GNUNET_memcmp(&v6.sin6_addr, + &c6->sin6_addr)) && + (0 != GNUNET_memcmp(&c6->sin6_addr, + &in6addr_any)) && + (!is_nat_v6(&c6->sin6_addr))) + continue; /* this IP is not from private address range, + and IP does not match. */ + if ((match_ipv6("fe80::", &c6->sin6_addr, 10)) && + (0 != GNUNET_memcmp(&c6->sin6_addr, + &in6addr_any)) && + (0 != GNUNET_memcmp(&v6.sin6_addr, + &c6->sin6_addr)) && + (0 == (delta->ac & GNUNET_NAT_AC_EXTERN))) + continue; /* client bound to link-local, and the other address + does not match and is not an external IP */ + + /* OK, IP seems relevant, notify client */ + if (0 == htons(v6.sin6_port)) + v6.sin6_port = c6->sin6_port; + notify_client(delta->ac, + ch, + add, + &v6, + alen); + } + break; + + default: + GNUNET_break(0); + return; } - break; - default: - GNUNET_break (0); - return; - } } @@ -814,15 +809,15 @@ check_notify_client (struct LocalAddressList *delta, * @param add #GNUNET_YES to add, #GNUNET_NO to remove */ static void -notify_clients (struct LocalAddressList *delta, - int add) +notify_clients(struct LocalAddressList *delta, + int add) { for (struct ClientHandle *ch = ch_head; NULL != ch; ch = ch->next) - check_notify_client (delta, - ch, - add); + check_notify_client(delta, + ch, + add); } @@ -835,74 +830,74 @@ notify_clients (struct LocalAddressList *delta, * @param add #GNUNET_YES to add, #GNUNET_NO to remove */ static void -notify_client_external_ipv4_change (void *cls, - const struct in_addr *v4, - int add) +notify_client_external_ipv4_change(void *cls, + const struct in_addr *v4, + int add) { struct ClientHandle *ch = cls; struct sockaddr_in sa; int have_v4; /* (0) check if this impacts 'hole_external' */ - if ( (NULL != ch->hole_external) && - (0 == strcasecmp (ch->hole_external, - "AUTO")) ) - { - struct LocalAddressList lal; - struct sockaddr_in *s4; - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Detected eternal IP, can now back-fill AUTO:%u in hole punching specification of `%s'\n", - (unsigned int) ch->ext_dns_port, - ch->section_name); - memset (&lal, 0, sizeof (lal)); - s4 = (struct sockaddr_in *) &lal.addr; - s4->sin_family = AF_INET; - s4->sin_port = htons (ch->ext_dns_port); - s4->sin_addr = *v4; - lal.af = AF_INET; - lal.ac = GNUNET_NAT_AC_GLOBAL | GNUNET_NAT_AC_MANUAL; - check_notify_client (&lal, - ch, - add); - } + if ((NULL != ch->hole_external) && + (0 == strcasecmp(ch->hole_external, + "AUTO"))) + { + struct LocalAddressList lal; + struct sockaddr_in *s4; + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Detected eternal IP, can now back-fill AUTO:%u in hole punching specification of `%s'\n", + (unsigned int)ch->ext_dns_port, + ch->section_name); + memset(&lal, 0, sizeof(lal)); + s4 = (struct sockaddr_in *)&lal.addr; + s4->sin_family = AF_INET; + s4->sin_port = htons(ch->ext_dns_port); + s4->sin_addr = *v4; + lal.af = AF_INET; + lal.ac = GNUNET_NAT_AC_GLOBAL | GNUNET_NAT_AC_MANUAL; + check_notify_client(&lal, + ch, + add); + } /* (1) check if client cares. */ - if (! ch->natted_address) + if (!ch->natted_address) return; have_v4 = GNUNET_NO; - for (unsigned int i=0;inum_caddrs;i++) - { - const struct sockaddr_storage *ss = &ch->caddrs[i].ss; - - if (AF_INET != ss->ss_family) - continue; - have_v4 = GNUNET_YES; - break; - } + for (unsigned int i = 0; i < ch->num_caddrs; i++) + { + const struct sockaddr_storage *ss = &ch->caddrs[i].ss; + + if (AF_INET != ss->ss_family) + continue; + have_v4 = GNUNET_YES; + break; + } if (GNUNET_NO == have_v4) return; /* IPv6-only */ /* (2) build address info */ - memset (&sa, - 0, - sizeof (sa)); + memset(&sa, + 0, + sizeof(sa)); sa.sin_family = AF_INET; sa.sin_addr = *v4; - sa.sin_port = htons (0); + sa.sin_port = htons(0); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Detected eternal IP %s, notifying client of external IP (without port)\n", - GNUNET_a2s ((const struct sockaddr *) &sa, - sizeof (sa))); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Detected eternal IP %s, notifying client of external IP (without port)\n", + GNUNET_a2s((const struct sockaddr *)&sa, + sizeof(sa))); /* (3) notify client of change */ - notify_client (is_nat_v4 (v4) - ? GNUNET_NAT_AC_EXTERN | GNUNET_NAT_AC_LAN - : GNUNET_NAT_AC_EXTERN | GNUNET_NAT_AC_GLOBAL, - ch, - add, - &sa, - sizeof (sa)); + notify_client(is_nat_v4(v4) + ? GNUNET_NAT_AC_EXTERN | GNUNET_NAT_AC_LAN + : GNUNET_NAT_AC_EXTERN | GNUNET_NAT_AC_GLOBAL, + ch, + add, + &sa, + sizeof(sa)); } @@ -914,54 +909,54 @@ notify_client_external_ipv4_change (void *cls, * @param ra IP address of the peer who wants us to connect to it */ static void -reversal_callback (void *cls, - const struct sockaddr_in *ra) +reversal_callback(void *cls, + const struct sockaddr_in *ra) { struct LocalAddressList *lal = cls; const struct sockaddr_in *l4; - GNUNET_assert (AF_INET == lal->af); - l4 = (const struct sockaddr_in *) &lal->addr; + GNUNET_assert(AF_INET == lal->af); + l4 = (const struct sockaddr_in *)&lal->addr; for (struct ClientHandle *ch = ch_head; NULL != ch; ch = ch->next) - { - struct GNUNET_NAT_ConnectionReversalRequestedMessage *crrm; - struct GNUNET_MQ_Envelope *env; - int match; - - /* Check if client is in applicable range for ICMP NAT traversal - for this local address */ - if (! ch->natted_address) - continue; - match = GNUNET_NO; - for (unsigned int i=0;inum_caddrs;i++) { - struct ClientAddress *ca = &ch->caddrs[i]; - const struct sockaddr_in *c4; - - if (AF_INET != ca->ss.ss_family) - continue; - c4 = (const struct sockaddr_in *) &ca->ss; - if ( (0 != c4->sin_addr.s_addr) && - (l4->sin_addr.s_addr != c4->sin_addr.s_addr) ) - continue; - match = GNUNET_YES; - break; + struct GNUNET_NAT_ConnectionReversalRequestedMessage *crrm; + struct GNUNET_MQ_Envelope *env; + int match; + + /* Check if client is in applicable range for ICMP NAT traversal + for this local address */ + if (!ch->natted_address) + continue; + match = GNUNET_NO; + for (unsigned int i = 0; i < ch->num_caddrs; i++) + { + struct ClientAddress *ca = &ch->caddrs[i]; + const struct sockaddr_in *c4; + + if (AF_INET != ca->ss.ss_family) + continue; + c4 = (const struct sockaddr_in *)&ca->ss; + if ((0 != c4->sin_addr.s_addr) && + (l4->sin_addr.s_addr != c4->sin_addr.s_addr)) + continue; + match = GNUNET_YES; + break; + } + if (!match) + continue; + + /* Notify applicable client about connection reversal request */ + env = GNUNET_MQ_msg_extra(crrm, + sizeof(struct sockaddr_in), + GNUNET_MESSAGE_TYPE_NAT_CONNECTION_REVERSAL_REQUESTED); + GNUNET_memcpy(&crrm[1], + ra, + sizeof(struct sockaddr_in)); + GNUNET_MQ_send(ch->mq, + env); } - if (! match) - continue; - - /* Notify applicable client about connection reversal request */ - env = GNUNET_MQ_msg_extra (crrm, - sizeof (struct sockaddr_in), - GNUNET_MESSAGE_TYPE_NAT_CONNECTION_REVERSAL_REQUESTED); - GNUNET_memcpy (&crrm[1], - ra, - sizeof (struct sockaddr_in)); - GNUNET_MQ_send (ch->mq, - env); - } } @@ -971,104 +966,104 @@ reversal_callback (void *cls, * @param cls NULL */ static void -run_scan (void *cls) +run_scan(void *cls) { struct IfcProcContext ifc_ctx; int found; int have_nat; struct LocalAddressList *lnext; - scan_task = GNUNET_SCHEDULER_add_delayed (SCAN_FREQ, - &run_scan, - NULL); - memset (&ifc_ctx, - 0, - sizeof (ifc_ctx)); - GNUNET_OS_network_interfaces_list (&ifc_proc, - &ifc_ctx); + scan_task = GNUNET_SCHEDULER_add_delayed(SCAN_FREQ, + &run_scan, + NULL); + memset(&ifc_ctx, + 0, + sizeof(ifc_ctx)); + GNUNET_OS_network_interfaces_list(&ifc_proc, + &ifc_ctx); /* remove addresses that disappeared */ for (struct LocalAddressList *lal = lal_head; NULL != lal; lal = lnext) - { - lnext = lal->next; - found = GNUNET_NO; - for (struct LocalAddressList *pos = ifc_ctx.lal_head; - NULL != pos; - pos = pos->next) { - if ( (pos->af == lal->af) && - (0 == memcmp (&lal->addr, - &pos->addr, - (AF_INET == lal->af) - ? sizeof (struct sockaddr_in) - : sizeof (struct sockaddr_in6))) ) - { - found = GNUNET_YES; - } + lnext = lal->next; + found = GNUNET_NO; + for (struct LocalAddressList *pos = ifc_ctx.lal_head; + NULL != pos; + pos = pos->next) + { + if ((pos->af == lal->af) && + (0 == memcmp(&lal->addr, + &pos->addr, + (AF_INET == lal->af) + ? sizeof(struct sockaddr_in) + : sizeof(struct sockaddr_in6)))) + { + found = GNUNET_YES; + } + } + if (GNUNET_NO == found) + { + notify_clients(lal, + GNUNET_NO); + free_lal(lal); + } } - if (GNUNET_NO == found) - { - notify_clients (lal, - GNUNET_NO); - free_lal (lal); - } - } /* add addresses that appeared */ have_nat = GNUNET_NO; for (struct LocalAddressList *pos = ifc_ctx.lal_head; NULL != pos; pos = ifc_ctx.lal_head) - { - found = GNUNET_NO; - if (GNUNET_NAT_AC_LAN == (GNUNET_NAT_AC_LAN & pos->ac)) - have_nat = GNUNET_YES; - for (struct LocalAddressList *lal = lal_head; - NULL != lal; - lal = lal->next) - { - if ( (pos->af == lal->af) && - (0 == memcmp (&lal->addr, - &pos->addr, - (AF_INET == lal->af) - ? sizeof (struct sockaddr_in) - : sizeof (struct sockaddr_in6))) ) - found = GNUNET_YES; - } - GNUNET_CONTAINER_DLL_remove (ifc_ctx.lal_head, - ifc_ctx.lal_tail, - pos); - if (GNUNET_YES == found) - { - GNUNET_free (pos); - } - else { - notify_clients (pos, - GNUNET_YES); - GNUNET_CONTAINER_DLL_insert (lal_head, - lal_tail, - pos); - if ( (AF_INET == pos->af) && - (NULL == pos->hc) && - (0 != (GNUNET_NAT_AC_LAN & pos->ac)) ) - { - const struct sockaddr_in *s4 - = (const struct sockaddr_in *) &pos->addr; - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found NATed local address %s, starting NAT server\n", - GNUNET_a2s ((const struct sockaddr *) &pos->addr, - sizeof (*s4))); - pos->hc = GN_start_gnunet_nat_server_ (&s4->sin_addr, - &reversal_callback, - pos, - cfg); - } + found = GNUNET_NO; + if (GNUNET_NAT_AC_LAN == (GNUNET_NAT_AC_LAN & pos->ac)) + have_nat = GNUNET_YES; + for (struct LocalAddressList *lal = lal_head; + NULL != lal; + lal = lal->next) + { + if ((pos->af == lal->af) && + (0 == memcmp(&lal->addr, + &pos->addr, + (AF_INET == lal->af) + ? sizeof(struct sockaddr_in) + : sizeof(struct sockaddr_in6)))) + found = GNUNET_YES; + } + GNUNET_CONTAINER_DLL_remove(ifc_ctx.lal_head, + ifc_ctx.lal_tail, + pos); + if (GNUNET_YES == found) + { + GNUNET_free(pos); + } + else + { + notify_clients(pos, + GNUNET_YES); + GNUNET_CONTAINER_DLL_insert(lal_head, + lal_tail, + pos); + if ((AF_INET == pos->af) && + (NULL == pos->hc) && + (0 != (GNUNET_NAT_AC_LAN & pos->ac))) + { + const struct sockaddr_in *s4 + = (const struct sockaddr_in *)&pos->addr; + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found NATed local address %s, starting NAT server\n", + GNUNET_a2s((const struct sockaddr *)&pos->addr, + sizeof(*s4))); + pos->hc = GN_start_gnunet_nat_server_(&s4->sin_addr, + &reversal_callback, + pos, + cfg); + } + } } - } - GN_nat_status_changed (have_nat); + GN_nat_status_changed(have_nat); } @@ -1084,81 +1079,91 @@ run_scan (void *cls) * @param result #GNUNET_NAT_ERROR_SUCCESS on success, otherwise the specific error code */ static void -upnp_addr_change_cb (void *cls, - int add_remove, - const struct sockaddr *addr, - socklen_t addrlen, - enum GNUNET_NAT_StatusCode result) +upnp_addr_change_cb(void *cls, + int add_remove, + const struct sockaddr *addr, + socklen_t addrlen, + enum GNUNET_NAT_StatusCode result) { struct ClientHandle *ch = cls; enum GNUNET_NAT_AddressClass ac; switch (result) - { - case GNUNET_NAT_ERROR_SUCCESS: - GNUNET_assert (NULL != addr); - break; - case GNUNET_NAT_ERROR_UPNPC_FAILED: - case GNUNET_NAT_ERROR_UPNPC_TIMEOUT: - case GNUNET_NAT_ERROR_IPC_FAILURE: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Running upnpc failed: %d\n", - result); - return; - case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_NOT_FOUND: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "external-ip binary not found\n"); - return; - case GNUNET_NAT_ERROR_UPNPC_NOT_FOUND: - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "upnpc binary not found\n"); - return; - case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_FAILED: - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "external-ip binary could not be run\n"); - return; - case GNUNET_NAT_ERROR_UPNPC_PORTMAP_FAILED: - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "upnpc failed to create port mapping\n"); - return; - case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_OUTPUT_INVALID: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Invalid output from upnpc\n"); - return; - case GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID: - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Invalid address returned by upnpc\n"); - return; - default: - GNUNET_break (0); /* should not be possible */ - return; - } + { + case GNUNET_NAT_ERROR_SUCCESS: + GNUNET_assert(NULL != addr); + break; + + case GNUNET_NAT_ERROR_UPNPC_FAILED: + case GNUNET_NAT_ERROR_UPNPC_TIMEOUT: + case GNUNET_NAT_ERROR_IPC_FAILURE: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Running upnpc failed: %d\n", + result); + return; + + case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_NOT_FOUND: + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "external-ip binary not found\n"); + return; + + case GNUNET_NAT_ERROR_UPNPC_NOT_FOUND: + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "upnpc binary not found\n"); + return; + + case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_FAILED: + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "external-ip binary could not be run\n"); + return; + + case GNUNET_NAT_ERROR_UPNPC_PORTMAP_FAILED: + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "upnpc failed to create port mapping\n"); + return; + + case GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_OUTPUT_INVALID: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Invalid output from upnpc\n"); + return; + + case GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID: + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Invalid address returned by upnpc\n"); + return; + + default: + GNUNET_break(0); /* should not be possible */ + return; + } switch (addr->sa_family) - { - case AF_INET: - ac = is_nat_v4 (&((const struct sockaddr_in *) addr)->sin_addr) - ? GNUNET_NAT_AC_LAN - : GNUNET_NAT_AC_EXTERN; - break; - case AF_INET6: - ac = is_nat_v6 (&((const struct sockaddr_in6 *) addr)->sin6_addr) - ? GNUNET_NAT_AC_LAN - : GNUNET_NAT_AC_EXTERN; - break; - default: - GNUNET_break (0); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "upnp external address %s: %s\n", - add_remove ? "added" : "removed", - GNUNET_a2s (addr, - addrlen)); - notify_client (ac, - ch, - add_remove, - addr, - addrlen); + { + case AF_INET: + ac = is_nat_v4(&((const struct sockaddr_in *)addr)->sin_addr) + ? GNUNET_NAT_AC_LAN + : GNUNET_NAT_AC_EXTERN; + break; + + case AF_INET6: + ac = is_nat_v6(&((const struct sockaddr_in6 *)addr)->sin6_addr) + ? GNUNET_NAT_AC_LAN + : GNUNET_NAT_AC_EXTERN; + break; + + default: + GNUNET_break(0); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "upnp external address %s: %s\n", + add_remove ? "added" : "removed", + GNUNET_a2s(addr, + addrlen)); + notify_client(ac, + ch, + add_remove, + addr, + addrlen); } @@ -1171,7 +1176,7 @@ upnp_addr_change_cb (void *cls, * @param ch client handle to act upon */ static void -dyndns_lookup (void *cls); +dyndns_lookup(void *cls); /** @@ -1184,9 +1189,9 @@ dyndns_lookup (void *cls); * @param addrlen number of bytes in @a addr */ static void -process_external_ip (void *cls, - const struct sockaddr *addr, - socklen_t addrlen) +process_external_ip(void *cls, + const struct sockaddr *addr, + socklen_t addrlen) { struct ClientHandle *ch = cls; struct LocalAddressList *lal; @@ -1195,84 +1200,86 @@ process_external_ip (void *cls, struct sockaddr_in6 *v6; if (NULL == addr) - { - struct LocalAddressList *laln; - - ch->ext_dns = NULL; - ch->ext_dns_task - = GNUNET_SCHEDULER_add_delayed (dyndns_frequency, - &dyndns_lookup, - ch); - /* Current iteration is over, remove 'old' IPs now */ - for (lal = ch->ext_addr_head; NULL != lal; lal = laln) { - laln = lal->next; - if (GNUNET_YES == lal->old) - { - GNUNET_CONTAINER_DLL_remove (ch->ext_addr_head, - ch->ext_addr_tail, - lal); - check_notify_client (lal, - ch, - GNUNET_NO); - GNUNET_free (lal); - } + struct LocalAddressList *laln; + + ch->ext_dns = NULL; + ch->ext_dns_task + = GNUNET_SCHEDULER_add_delayed(dyndns_frequency, + &dyndns_lookup, + ch); + /* Current iteration is over, remove 'old' IPs now */ + for (lal = ch->ext_addr_head; NULL != lal; lal = laln) + { + laln = lal->next; + if (GNUNET_YES == lal->old) + { + GNUNET_CONTAINER_DLL_remove(ch->ext_addr_head, + ch->ext_addr_tail, + lal); + check_notify_client(lal, + ch, + GNUNET_NO); + GNUNET_free(lal); + } + } + return; } - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got IP `%s' for external address `%s'\n", - GNUNET_a2s (addr, - addrlen), - ch->hole_external); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got IP `%s' for external address `%s'\n", + GNUNET_a2s(addr, + addrlen), + ch->hole_external); /* build sockaddr storage with port number */ - memset (&ss, - 0, - sizeof (ss)); - GNUNET_memcpy (&ss, - addr, - addrlen); + memset(&ss, + 0, + sizeof(ss)); + GNUNET_memcpy(&ss, + addr, + addrlen); switch (addr->sa_family) - { - case AF_INET: - v4 = (struct sockaddr_in *) &ss; - v4->sin_port = htons (ch->ext_dns_port); - break; - case AF_INET6: - v6 = (struct sockaddr_in6 *) &ss; - v6->sin6_port = htons (ch->ext_dns_port); - break; - default: - GNUNET_break (0); - return; - } + { + case AF_INET: + v4 = (struct sockaddr_in *)&ss; + v4->sin_port = htons(ch->ext_dns_port); + break; + + case AF_INET6: + v6 = (struct sockaddr_in6 *)&ss; + v6->sin6_port = htons(ch->ext_dns_port); + break; + + default: + GNUNET_break(0); + return; + } /* See if 'ss' matches any of our known addresses */ for (lal = ch->ext_addr_head; NULL != lal; lal = lal->next) - { - if (GNUNET_NO == lal->old) - continue; /* already processed, skip */ - if ( (addr->sa_family == lal->addr.ss_family) && - (0 == memcmp (&ss, - &lal->addr, - addrlen)) ) { - /* Address unchanged, remember so we do not remove */ - lal->old = GNUNET_NO; - return; /* done here */ + if (GNUNET_NO == lal->old) + continue; /* already processed, skip */ + if ((addr->sa_family == lal->addr.ss_family) && + (0 == memcmp(&ss, + &lal->addr, + addrlen))) + { + /* Address unchanged, remember so we do not remove */ + lal->old = GNUNET_NO; + return; /* done here */ + } } - } /* notify client, and remember IP for later removal! */ - lal = GNUNET_new (struct LocalAddressList); + lal = GNUNET_new(struct LocalAddressList); lal->addr = ss; lal->af = ss.ss_family; lal->ac = GNUNET_NAT_AC_GLOBAL | GNUNET_NAT_AC_MANUAL; - GNUNET_CONTAINER_DLL_insert (ch->ext_addr_head, - ch->ext_addr_tail, - lal); - check_notify_client (lal, - ch, - GNUNET_YES); + GNUNET_CONTAINER_DLL_insert(ch->ext_addr_head, + ch->ext_addr_tail, + lal); + check_notify_client(lal, + ch, + GNUNET_YES); } @@ -1285,24 +1292,24 @@ process_external_ip (void *cls, * @param ch client handle to act upon */ static void -dyndns_lookup (void *cls) +dyndns_lookup(void *cls) { struct ClientHandle *ch = cls; struct LocalAddressList *lal; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Performing DNS lookup for punched hole given for `%s' as `%s:%u'\n", - ch->section_name, - ch->hole_external, - (unsigned int) ch->ext_dns_port); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Performing DNS lookup for punched hole given for `%s' as `%s:%u'\n", + ch->section_name, + ch->hole_external, + (unsigned int)ch->ext_dns_port); for (lal = ch->ext_addr_head; NULL != lal; lal = lal->next) lal->old = GNUNET_YES; ch->ext_dns_task = NULL; - ch->ext_dns = GNUNET_RESOLVER_ip_get (ch->hole_external, - AF_UNSPEC, - GNUNET_TIME_UNIT_MINUTES, - &process_external_ip, - ch); + ch->ext_dns = GNUNET_RESOLVER_ip_get(ch->hole_external, + AF_UNSPEC, + GNUNET_TIME_UNIT_MINUTES, + &process_external_ip, + ch); } @@ -1318,105 +1325,105 @@ dyndns_lookup (void *cls) * @param ch client handle to act upon */ static void -lookup_hole_external (struct ClientHandle *ch) +lookup_hole_external(struct ClientHandle *ch) { char *port; unsigned int pnum; struct sockaddr_in *s4; struct LocalAddressList *lal; - port = strrchr (ch->hole_external, ':'); + port = strrchr(ch->hole_external, ':'); if (NULL == port) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Malformed punched hole specification `%s' (lacks port)\n"), - ch->hole_external); - return; - } - if ( (1 != sscanf (port + 1, - "%u", - &pnum)) || - (pnum > 65535) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Invalid port number in punched hole specification `%s' (lacks port)\n"), - port + 1); - return; - } - ch->ext_dns_port = (uint16_t) pnum; + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Malformed punched hole specification `%s' (lacks port)\n"), + ch->hole_external); + return; + } + if ((1 != sscanf(port + 1, + "%u", + &pnum)) || + (pnum > 65535)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Invalid port number in punched hole specification `%s' (lacks port)\n"), + port + 1); + return; + } + ch->ext_dns_port = (uint16_t)pnum; *port = '\0'; - lal = GNUNET_new (struct LocalAddressList); + lal = GNUNET_new(struct LocalAddressList); if ('[' == *ch->hole_external) - { - struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) &lal->addr; + { + struct sockaddr_in6 *s6 = (struct sockaddr_in6 *)&lal->addr; + + s6->sin6_family = AF_INET6; + if (']' != (ch->hole_external[strlen(ch->hole_external) - 1])) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Malformed punched hole specification `%s' (lacks `]')\n"), + ch->hole_external); + GNUNET_free(lal); + return; + } + ch->hole_external[strlen(ch->hole_external) - 1] = '\0'; + if (1 != inet_pton(AF_INET6, + ch->hole_external + 1, + &s6->sin6_addr)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Malformed punched hole specification `%s' (IPv6 address invalid)"), + ch->hole_external + 1); + GNUNET_free(lal); + return; + } + s6->sin6_port = htons(ch->ext_dns_port); + lal->af = AF_INET6; + lal->ac = GNUNET_NAT_AC_GLOBAL | GNUNET_NAT_AC_MANUAL; + GNUNET_CONTAINER_DLL_insert(ch->ext_addr_head, + ch->ext_addr_tail, + lal); + check_notify_client(lal, + ch, + GNUNET_YES); + return; + } - s6->sin6_family = AF_INET6; - if (']' != (ch->hole_external[strlen(ch->hole_external)-1])) + s4 = (struct sockaddr_in *)&lal->addr; + s4->sin_family = AF_INET; + if (1 == inet_pton(AF_INET, + ch->hole_external, + &s4->sin_addr)) { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Malformed punched hole specification `%s' (lacks `]')\n"), - ch->hole_external); - GNUNET_free (lal); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "IPv4 punched hole given for `%s' via `%s:%u'\n", + ch->section_name, + ch->hole_external, + (unsigned int)ch->ext_dns_port); + s4->sin_port = htons(ch->ext_dns_port); + lal->af = AF_INET; + lal->ac = GNUNET_NAT_AC_GLOBAL | GNUNET_NAT_AC_MANUAL; + GNUNET_CONTAINER_DLL_insert(ch->ext_addr_head, + ch->ext_addr_tail, + lal); + check_notify_client(lal, + ch, + GNUNET_YES); return; } - ch->hole_external[strlen(ch->hole_external)-1] = '\0'; - if (1 != inet_pton (AF_INET6, - ch->hole_external + 1, - &s6->sin6_addr)) + if (0 == strcasecmp(ch->hole_external, + "AUTO")) { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Malformed punched hole specification `%s' (IPv6 address invalid)"), - ch->hole_external + 1); - GNUNET_free (lal); + /* handled in #notify_client_external_ipv4_change() */ + GNUNET_free(lal); return; } - s6->sin6_port = htons (ch->ext_dns_port); - lal->af = AF_INET6; - lal->ac = GNUNET_NAT_AC_GLOBAL | GNUNET_NAT_AC_MANUAL; - GNUNET_CONTAINER_DLL_insert (ch->ext_addr_head, - ch->ext_addr_tail, - lal); - check_notify_client (lal, - ch, - GNUNET_YES); - return; - } - - s4 = (struct sockaddr_in *) &lal->addr; - s4->sin_family = AF_INET; - if (1 == inet_pton (AF_INET, - ch->hole_external, - &s4->sin_addr)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "IPv4 punched hole given for `%s' via `%s:%u'\n", - ch->section_name, - ch->hole_external, - (unsigned int) ch->ext_dns_port); - s4->sin_port = htons (ch->ext_dns_port); - lal->af = AF_INET; - lal->ac = GNUNET_NAT_AC_GLOBAL | GNUNET_NAT_AC_MANUAL; - GNUNET_CONTAINER_DLL_insert (ch->ext_addr_head, - ch->ext_addr_tail, - lal); - check_notify_client (lal, - ch, - GNUNET_YES); - return; - } - if (0 == strcasecmp (ch->hole_external, - "AUTO")) - { - /* handled in #notify_client_external_ipv4_change() */ - GNUNET_free (lal); - return; - } /* got a DNS name, trigger lookup! */ - GNUNET_free (lal); + GNUNET_free(lal); ch->ext_dns_task - = GNUNET_SCHEDULER_add_now (&dyndns_lookup, - ch); + = GNUNET_SCHEDULER_add_now(&dyndns_lookup, + ch); } @@ -1428,132 +1435,134 @@ lookup_hole_external (struct ClientHandle *ch) * @param message the message received */ static void -handle_register (void *cls, - const struct GNUNET_NAT_RegisterMessage *message) +handle_register(void *cls, + const struct GNUNET_NAT_RegisterMessage *message) { struct ClientHandle *ch = cls; const char *off; size_t left; - if ( (0 != ch->proto) || - (NULL != ch->caddrs) ) - { - /* double registration not allowed */ - GNUNET_break (0); - GNUNET_SERVICE_client_drop (ch->client); - return; - } - ch->flags = message->flags; - ch->proto = message->proto; - ch->num_caddrs = ntohs (message->num_addrs); - ch->caddrs = GNUNET_new_array (ch->num_caddrs, - struct ClientAddress); - left = ntohs (message->header.size) - sizeof (*message); - off = (const char *) &message[1]; - for (unsigned int i=0;inum_caddrs;i++) - { - const struct sockaddr *sa = (const struct sockaddr *) off; - size_t alen; - uint16_t port; - int is_nat; - - if (sizeof (sa_family_t) > left) + if ((0 != ch->proto) || + (NULL != ch->caddrs)) { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (ch->client); + /* double registration not allowed */ + GNUNET_break(0); + GNUNET_SERVICE_client_drop(ch->client); return; } - is_nat = GNUNET_NO; - switch (sa->sa_family) + ch->flags = message->flags; + ch->proto = message->proto; + ch->num_caddrs = ntohs(message->num_addrs); + ch->caddrs = GNUNET_new_array(ch->num_caddrs, + struct ClientAddress); + left = ntohs(message->header.size) - sizeof(*message); + off = (const char *)&message[1]; + for (unsigned int i = 0; i < ch->num_caddrs; i++) { - case AF_INET: - { - struct sockaddr_in s4; - - GNUNET_memcpy (&s4, - off, - sizeof (struct sockaddr_in)); - alen = sizeof (struct sockaddr_in); - if (is_nat_v4 (&s4.sin_addr)) - is_nat = GNUNET_YES; - port = ntohs (s4.sin_port); - } - break; - case AF_INET6: - { - struct sockaddr_in6 s6; - - GNUNET_memcpy (&s6, - off, - sizeof (struct sockaddr_in6)); - alen = sizeof (struct sockaddr_in6); - if (is_nat_v6 (&s6.sin6_addr)) - is_nat = GNUNET_YES; - port = ntohs (s6.sin6_port); - } - break; + const struct sockaddr *sa = (const struct sockaddr *)off; + size_t alen; + uint16_t port; + int is_nat; + + if (sizeof(sa_family_t) > left) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(ch->client); + return; + } + is_nat = GNUNET_NO; + switch (sa->sa_family) + { + case AF_INET: + { + struct sockaddr_in s4; + + GNUNET_memcpy(&s4, + off, + sizeof(struct sockaddr_in)); + alen = sizeof(struct sockaddr_in); + if (is_nat_v4(&s4.sin_addr)) + is_nat = GNUNET_YES; + port = ntohs(s4.sin_port); + } + break; + + case AF_INET6: + { + struct sockaddr_in6 s6; + + GNUNET_memcpy(&s6, + off, + sizeof(struct sockaddr_in6)); + alen = sizeof(struct sockaddr_in6); + if (is_nat_v6(&s6.sin6_addr)) + is_nat = GNUNET_YES; + port = ntohs(s6.sin6_port); + } + break; + #if AF_UNIX - case AF_UNIX: - alen = sizeof (struct sockaddr_un); - port = 0; - break; + case AF_UNIX: + alen = sizeof(struct sockaddr_un); + port = 0; + break; #endif - default: - GNUNET_break (0); - GNUNET_SERVICE_client_drop (ch->client); - return; - } - /* store address */ - GNUNET_assert (alen <= left); - GNUNET_assert (alen <= sizeof (struct sockaddr_storage)); - GNUNET_memcpy (&ch->caddrs[i].ss, - off, - alen); - - /* If applicable, try UPNPC NAT punching */ - if ( (is_nat) && - (enable_upnp) && - ( (IPPROTO_TCP == ch->proto) || - (IPPROTO_UDP == ch->proto) ) ) - { - ch->natted_address = GNUNET_YES; - ch->caddrs[i].mh - = GNUNET_NAT_mini_map_start (port, - IPPROTO_TCP == ch->proto, - &upnp_addr_change_cb, - ch); + default: + GNUNET_break(0); + GNUNET_SERVICE_client_drop(ch->client); + return; + } + /* store address */ + GNUNET_assert(alen <= left); + GNUNET_assert(alen <= sizeof(struct sockaddr_storage)); + GNUNET_memcpy(&ch->caddrs[i].ss, + off, + alen); + + /* If applicable, try UPNPC NAT punching */ + if ((is_nat) && + (enable_upnp) && + ((IPPROTO_TCP == ch->proto) || + (IPPROTO_UDP == ch->proto))) + { + ch->natted_address = GNUNET_YES; + ch->caddrs[i].mh + = GNUNET_NAT_mini_map_start(port, + IPPROTO_TCP == ch->proto, + &upnp_addr_change_cb, + ch); + } + + off += alen; } - off += alen; - } - ch->section_name - = GNUNET_strndup (off, - ntohs (message->str_len)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received REGISTER message from client for subsystem `%s'\n", - ch->section_name); + = GNUNET_strndup(off, + ntohs(message->str_len)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received REGISTER message from client for subsystem `%s'\n", + ch->section_name); if (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_string (cfg, - ch->section_name, - "HOLE_EXTERNAL", - &ch->hole_external)) - lookup_hole_external (ch); + GNUNET_CONFIGURATION_get_value_string(cfg, + ch->section_name, + "HOLE_EXTERNAL", + &ch->hole_external)) + lookup_hole_external(ch); /* Actually send IP address list to client */ for (struct LocalAddressList *lal = lal_head; NULL != lal; lal = lal->next) - { - check_notify_client (lal, - ch, - GNUNET_YES); - } + { + check_notify_client(lal, + ch, + GNUNET_YES); + } /* Also consider IPv4 determined by `external-ip` */ ch->external_monitor - = GN_external_ipv4_monitor_start (¬ify_client_external_ipv4_change, - ch); - GNUNET_SERVICE_client_continue (ch->client); + = GN_external_ipv4_monitor_start(¬ify_client_external_ipv4_change, + ch); + GNUNET_SERVICE_client_continue(ch->client); } @@ -1566,22 +1575,22 @@ handle_register (void *cls, * @return #GNUNET_OK if message is well-formed */ static int -check_stun (void *cls, - const struct GNUNET_NAT_HandleStunMessage *message) +check_stun(void *cls, + const struct GNUNET_NAT_HandleStunMessage *message) { - size_t sa_len = ntohs (message->sender_addr_size); - size_t expect = sa_len + ntohs (message->payload_size); - - if (ntohs (message->header.size) - sizeof (*message) != expect) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (sa_len < sizeof (sa_family_t)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + size_t sa_len = ntohs(message->sender_addr_size); + size_t expect = sa_len + ntohs(message->payload_size); + + if (ntohs(message->header.size) - sizeof(*message) != expect) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (sa_len < sizeof(sa_family_t)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1594,33 +1603,33 @@ check_stun (void *cls, * @param add #GNUNET_YES to add, #GNUNET_NO to remove */ static void -notify_clients_stun_change (const struct sockaddr_in *ip, - int add) +notify_clients_stun_change(const struct sockaddr_in *ip, + int add) { for (struct ClientHandle *ch = ch_head; NULL != ch; ch = ch->next) - { - struct sockaddr_in v4; - struct GNUNET_NAT_AddressChangeNotificationMessage *msg; - struct GNUNET_MQ_Envelope *env; - - if (! ch->natted_address) - continue; - v4 = *ip; - v4.sin_port = htons (0); - env = GNUNET_MQ_msg_extra (msg, - sizeof (v4), - GNUNET_MESSAGE_TYPE_NAT_ADDRESS_CHANGE); - msg->add_remove = htonl ((int32_t) add); - msg->addr_class = htonl (GNUNET_NAT_AC_EXTERN | - GNUNET_NAT_AC_GLOBAL); - GNUNET_memcpy (&msg[1], - &v4, - sizeof (v4)); - GNUNET_MQ_send (ch->mq, - env); - } + { + struct sockaddr_in v4; + struct GNUNET_NAT_AddressChangeNotificationMessage *msg; + struct GNUNET_MQ_Envelope *env; + + if (!ch->natted_address) + continue; + v4 = *ip; + v4.sin_port = htons(0); + env = GNUNET_MQ_msg_extra(msg, + sizeof(v4), + GNUNET_MESSAGE_TYPE_NAT_ADDRESS_CHANGE); + msg->add_remove = htonl((int32_t)add); + msg->addr_class = htonl(GNUNET_NAT_AC_EXTERN | + GNUNET_NAT_AC_GLOBAL); + GNUNET_memcpy(&msg[1], + &v4, + sizeof(v4)); + GNUNET_MQ_send(ch->mq, + env); + } } @@ -1632,17 +1641,17 @@ notify_clients_stun_change (const struct sockaddr_in *ip, * @param cls the `struct StunExternalIP` to drop */ static void -stun_ip_timeout (void *cls) +stun_ip_timeout(void *cls) { struct StunExternalIP *se = cls; se->timeout_task = NULL; - notify_clients_stun_change (&se->external_addr, - GNUNET_NO); - GNUNET_CONTAINER_DLL_remove (se_head, - se_tail, - se); - GNUNET_free (se); + notify_clients_stun_change(&se->external_addr, + GNUNET_NO); + GNUNET_CONTAINER_DLL_remove(se_head, + se_tail, + se); + GNUNET_free(se); } @@ -1654,106 +1663,107 @@ stun_ip_timeout (void *cls) * @param message the message received */ static void -handle_stun (void *cls, - const struct GNUNET_NAT_HandleStunMessage *message) +handle_stun(void *cls, + const struct GNUNET_NAT_HandleStunMessage *message) { struct ClientHandle *ch = cls; - const char *buf = (const char *) &message[1]; + const char *buf = (const char *)&message[1]; const struct sockaddr *sa; const void *payload; size_t sa_len; size_t payload_size; struct sockaddr_in external_addr; - sa_len = ntohs (message->sender_addr_size); - payload_size = ntohs (message->payload_size); - sa = (const struct sockaddr *) &buf[0]; - payload = (const struct sockaddr *) &buf[sa_len]; + sa_len = ntohs(message->sender_addr_size); + payload_size = ntohs(message->payload_size); + sa = (const struct sockaddr *)&buf[0]; + payload = (const struct sockaddr *)&buf[sa_len]; switch (sa->sa_family) - { - case AF_INET: - if (sa_len != sizeof (struct sockaddr_in)) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (ch->client); - return; - } - break; - case AF_INET6: - if (sa_len != sizeof (struct sockaddr_in6)) { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (ch->client); - return; + case AF_INET: + if (sa_len != sizeof(struct sockaddr_in)) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(ch->client); + return; + } + break; + + case AF_INET6: + if (sa_len != sizeof(struct sockaddr_in6)) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(ch->client); + return; + } + break; } - break; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received HANDLE_STUN message from client\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received HANDLE_STUN message from client\n"); if (GNUNET_OK == - GNUNET_NAT_stun_handle_packet_ (payload, - payload_size, - &external_addr)) - { - /* We now know that a server at "sa" claims that - we are visible at IP "external_addr". - - We should (for some fixed period of time) tell - all of our clients that listen to a NAT'ed address - that they might want to consider the given 'external_ip' - as their public IP address (this includes TCP and UDP - clients, even if only UDP sends STUN requests). - - If we do not get a renewal, the "external_addr" should be - removed again. The timeout frequency should be configurable - (with a sane default), so that the UDP plugin can tell how - often to re-request STUN. - */ - struct StunExternalIP *se; - - /* Check if we had a prior response from this STUN server */ - for (se = se_head; NULL != se; se = se->next) + GNUNET_NAT_stun_handle_packet_(payload, + payload_size, + &external_addr)) { - if ( (se->stun_server_addr_len != sa_len) || - (0 != memcmp (sa, - &se->stun_server_addr, - sa_len)) ) - continue; /* different STUN server */ - if (0 != GNUNET_memcmp (&external_addr, - &se->external_addr)) - { - /* external IP changed, update! */ - notify_clients_stun_change (&se->external_addr, - GNUNET_NO); - se->external_addr = external_addr; - notify_clients_stun_change (&se->external_addr, - GNUNET_YES); - } - /* update timeout */ - GNUNET_SCHEDULER_cancel (se->timeout_task); - se->timeout_task - = GNUNET_SCHEDULER_add_delayed (stun_stale_timeout, - &stun_ip_timeout, - se); - return; + /* We now know that a server at "sa" claims that + we are visible at IP "external_addr". + + We should (for some fixed period of time) tell + all of our clients that listen to a NAT'ed address + that they might want to consider the given 'external_ip' + as their public IP address (this includes TCP and UDP + clients, even if only UDP sends STUN requests). + + If we do not get a renewal, the "external_addr" should be + removed again. The timeout frequency should be configurable + (with a sane default), so that the UDP plugin can tell how + often to re-request STUN. + */ + struct StunExternalIP *se; + + /* Check if we had a prior response from this STUN server */ + for (se = se_head; NULL != se; se = se->next) + { + if ((se->stun_server_addr_len != sa_len) || + (0 != memcmp(sa, + &se->stun_server_addr, + sa_len))) + continue; /* different STUN server */ + if (0 != GNUNET_memcmp(&external_addr, + &se->external_addr)) + { + /* external IP changed, update! */ + notify_clients_stun_change(&se->external_addr, + GNUNET_NO); + se->external_addr = external_addr; + notify_clients_stun_change(&se->external_addr, + GNUNET_YES); + } + /* update timeout */ + GNUNET_SCHEDULER_cancel(se->timeout_task); + se->timeout_task + = GNUNET_SCHEDULER_add_delayed(stun_stale_timeout, + &stun_ip_timeout, + se); + return; + } + /* STUN server is completely new, create fresh entry */ + se = GNUNET_new(struct StunExternalIP); + se->external_addr = external_addr; + GNUNET_memcpy(&se->stun_server_addr, + sa, + sa_len); + se->stun_server_addr_len = sa_len; + se->timeout_task = GNUNET_SCHEDULER_add_delayed(stun_stale_timeout, + &stun_ip_timeout, + se); + GNUNET_CONTAINER_DLL_insert(se_head, + se_tail, + se); + notify_clients_stun_change(&se->external_addr, + GNUNET_NO); } - /* STUN server is completely new, create fresh entry */ - se = GNUNET_new (struct StunExternalIP); - se->external_addr = external_addr; - GNUNET_memcpy (&se->stun_server_addr, - sa, - sa_len); - se->stun_server_addr_len = sa_len; - se->timeout_task = GNUNET_SCHEDULER_add_delayed (stun_stale_timeout, - &stun_ip_timeout, - se); - GNUNET_CONTAINER_DLL_insert (se_head, - se_tail, - se); - notify_clients_stun_change (&se->external_addr, - GNUNET_NO); - } - GNUNET_SERVICE_client_continue (ch->client); + GNUNET_SERVICE_client_continue(ch->client); } @@ -1767,18 +1777,18 @@ handle_stun (void *cls, * @return #GNUNET_OK if message is well-formed */ static int -check_request_connection_reversal (void *cls, - const struct GNUNET_NAT_RequestConnectionReversalMessage *message) +check_request_connection_reversal(void *cls, + const struct GNUNET_NAT_RequestConnectionReversalMessage *message) { size_t expect; - expect = ntohs (message->local_addr_size) - + ntohs (message->remote_addr_size); - if (ntohs (message->header.size) - sizeof (*message) != expect) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + expect = ntohs(message->local_addr_size) + + ntohs(message->remote_addr_size); + if (ntohs(message->header.size) - sizeof(*message) != expect) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1791,48 +1801,48 @@ check_request_connection_reversal (void *cls, * @param message the message received */ static void -handle_request_connection_reversal (void *cls, - const struct GNUNET_NAT_RequestConnectionReversalMessage *message) +handle_request_connection_reversal(void *cls, + const struct GNUNET_NAT_RequestConnectionReversalMessage *message) { struct ClientHandle *ch = cls; - const char *buf = (const char *) &message[1]; - size_t local_sa_len = ntohs (message->local_addr_size); - size_t remote_sa_len = ntohs (message->remote_addr_size); + const char *buf = (const char *)&message[1]; + size_t local_sa_len = ntohs(message->local_addr_size); + size_t remote_sa_len = ntohs(message->remote_addr_size); struct sockaddr_in l4; struct sockaddr_in r4; int ret; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received REQUEST CONNECTION REVERSAL message from client\n"); - if (local_sa_len != sizeof (struct sockaddr_in)) - { - GNUNET_break_op (0); - GNUNET_SERVICE_client_drop (ch->client); - return; - } - if (remote_sa_len != sizeof (struct sockaddr_in)) - { - GNUNET_break_op (0); - GNUNET_SERVICE_client_drop (ch->client); - return; - } - GNUNET_memcpy (&l4, - buf, - sizeof (struct sockaddr_in)); - GNUNET_break_op (AF_INET == l4.sin_family); - buf += sizeof (struct sockaddr_in); - GNUNET_memcpy (&r4, - buf, - sizeof (struct sockaddr_in)); - GNUNET_break_op (AF_INET == r4.sin_family); - ret = GN_request_connection_reversal (&l4.sin_addr, - ntohs (l4.sin_port), - &r4.sin_addr, - cfg); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received REQUEST CONNECTION REVERSAL message from client\n"); + if (local_sa_len != sizeof(struct sockaddr_in)) + { + GNUNET_break_op(0); + GNUNET_SERVICE_client_drop(ch->client); + return; + } + if (remote_sa_len != sizeof(struct sockaddr_in)) + { + GNUNET_break_op(0); + GNUNET_SERVICE_client_drop(ch->client); + return; + } + GNUNET_memcpy(&l4, + buf, + sizeof(struct sockaddr_in)); + GNUNET_break_op(AF_INET == l4.sin_family); + buf += sizeof(struct sockaddr_in); + GNUNET_memcpy(&r4, + buf, + sizeof(struct sockaddr_in)); + GNUNET_break_op(AF_INET == r4.sin_family); + ret = GN_request_connection_reversal(&l4.sin_addr, + ntohs(l4.sin_port), + &r4.sin_addr, + cfg); if (GNUNET_OK != ret) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Connection reversal request failed\n")); - GNUNET_SERVICE_client_continue (ch->client); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Connection reversal request failed\n")); + GNUNET_SERVICE_client_continue(ch->client); } @@ -1842,31 +1852,31 @@ handle_request_connection_reversal (void *cls, * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { struct StunExternalIP *se; while (NULL != (se = se_head)) - { - GNUNET_CONTAINER_DLL_remove (se_head, - se_tail, - se); - GNUNET_SCHEDULER_cancel (se->timeout_task); - GNUNET_free (se); - } - GN_nat_status_changed (GNUNET_NO); + { + GNUNET_CONTAINER_DLL_remove(se_head, + se_tail, + se); + GNUNET_SCHEDULER_cancel(se->timeout_task); + GNUNET_free(se); + } + GN_nat_status_changed(GNUNET_NO); if (NULL != scan_task) - { - GNUNET_SCHEDULER_cancel (scan_task); - scan_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(scan_task); + scan_task = NULL; + } if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, - GNUNET_NO); - stats = NULL; - } - destroy_lal (); + { + GNUNET_STATISTICS_destroy(stats, + GNUNET_NO); + stats = NULL; + } + destroy_lal(); } @@ -1878,49 +1888,49 @@ shutdown_task (void *cls) * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *service) { cfg = c; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_time (cfg, - "NAT", - "STUN_STALE", - &stun_stale_timeout)) + GNUNET_CONFIGURATION_get_value_time(cfg, + "NAT", + "STUN_STALE", + &stun_stale_timeout)) stun_stale_timeout = GNUNET_TIME_UNIT_HOURS; /* Check for UPnP */ enable_upnp - = GNUNET_CONFIGURATION_get_value_yesno (cfg, - "NAT", - "ENABLE_UPNP"); + = GNUNET_CONFIGURATION_get_value_yesno(cfg, + "NAT", + "ENABLE_UPNP"); if (GNUNET_YES == enable_upnp) - { - /* check if it works */ - if (GNUNET_SYSERR == - GNUNET_OS_check_helper_binary ("upnpc", - GNUNET_NO, - NULL)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("UPnP enabled in configuration, but UPnP client `upnpc` command not found, disabling UPnP\n")); - enable_upnp = GNUNET_SYSERR; + /* check if it works */ + if (GNUNET_SYSERR == + GNUNET_OS_check_helper_binary("upnpc", + GNUNET_NO, + NULL)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("UPnP enabled in configuration, but UPnP client `upnpc` command not found, disabling UPnP\n")); + enable_upnp = GNUNET_SYSERR; + } } - } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_time (cfg, - "nat", - "DYNDNS_FREQUENCY", - &dyndns_frequency)) + GNUNET_CONFIGURATION_get_value_time(cfg, + "nat", + "DYNDNS_FREQUENCY", + &dyndns_frequency)) dyndns_frequency = DYNDNS_FREQUENCY; - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); - stats = GNUNET_STATISTICS_create ("nat", - cfg); - scan_task = GNUNET_SCHEDULER_add_now (&run_scan, - NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); + stats = GNUNET_STATISTICS_create("nat", + cfg); + scan_task = GNUNET_SCHEDULER_add_now(&run_scan, + NULL); } @@ -1933,18 +1943,18 @@ run (void *cls, * @return a `struct ClientHandle` */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + struct GNUNET_MQ_Handle *mq) { struct ClientHandle *ch; - ch = GNUNET_new (struct ClientHandle); + ch = GNUNET_new(struct ClientHandle); ch->mq = mq; ch->client = c; - GNUNET_CONTAINER_DLL_insert (ch_head, - ch_tail, - ch); + GNUNET_CONTAINER_DLL_insert(ch_head, + ch_tail, + ch); return ch; } @@ -1957,50 +1967,50 @@ client_connect_cb (void *cls, * @param internal_cls a `struct ClientHandle *` */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - void *internal_cls) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + void *internal_cls) { struct ClientHandle *ch = internal_cls; struct LocalAddressList *lal; - GNUNET_CONTAINER_DLL_remove (ch_head, - ch_tail, - ch); - for (unsigned int i=0;inum_caddrs;i++) - { - if (NULL != ch->caddrs[i].mh) + GNUNET_CONTAINER_DLL_remove(ch_head, + ch_tail, + ch); + for (unsigned int i = 0; i < ch->num_caddrs; i++) { - GNUNET_NAT_mini_map_stop (ch->caddrs[i].mh); - ch->caddrs[i].mh = NULL; + if (NULL != ch->caddrs[i].mh) + { + GNUNET_NAT_mini_map_stop(ch->caddrs[i].mh); + ch->caddrs[i].mh = NULL; + } } - } - GNUNET_free_non_null (ch->caddrs); + GNUNET_free_non_null(ch->caddrs); while (NULL != (lal = ch->ext_addr_head)) - { - GNUNET_CONTAINER_DLL_remove (ch->ext_addr_head, - ch->ext_addr_tail, - lal); - GNUNET_free (lal); - } + { + GNUNET_CONTAINER_DLL_remove(ch->ext_addr_head, + ch->ext_addr_tail, + lal); + GNUNET_free(lal); + } if (NULL != ch->ext_dns_task) - { - GNUNET_SCHEDULER_cancel (ch->ext_dns_task); - ch->ext_dns_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(ch->ext_dns_task); + ch->ext_dns_task = NULL; + } if (NULL != ch->external_monitor) - { - GN_external_ipv4_monitor_stop (ch->external_monitor); - ch->external_monitor = NULL; - } + { + GN_external_ipv4_monitor_stop(ch->external_monitor); + ch->external_monitor = NULL; + } if (NULL != ch->ext_dns) - { - GNUNET_RESOLVER_request_cancel (ch->ext_dns); - ch->ext_dns = NULL; - } - GNUNET_free_non_null (ch->hole_external); - GNUNET_free_non_null (ch->section_name); - GNUNET_free (ch); + { + GNUNET_RESOLVER_request_cancel(ch->ext_dns); + ch->ext_dns = NULL; + } + GNUNET_free_non_null(ch->hole_external); + GNUNET_free_non_null(ch->section_name); + GNUNET_free(ch); } @@ -2008,25 +2018,25 @@ client_disconnect_cb (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("nat", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_var_size (register, - GNUNET_MESSAGE_TYPE_NAT_REGISTER, - struct GNUNET_NAT_RegisterMessage, - NULL), - GNUNET_MQ_hd_var_size (stun, - GNUNET_MESSAGE_TYPE_NAT_HANDLE_STUN, - struct GNUNET_NAT_HandleStunMessage, - NULL), - GNUNET_MQ_hd_var_size (request_connection_reversal, - GNUNET_MESSAGE_TYPE_NAT_REQUEST_CONNECTION_REVERSAL, - struct GNUNET_NAT_RequestConnectionReversalMessage, - NULL), - GNUNET_MQ_handler_end ()); + ("nat", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_var_size(register, + GNUNET_MESSAGE_TYPE_NAT_REGISTER, + struct GNUNET_NAT_RegisterMessage, + NULL), + GNUNET_MQ_hd_var_size(stun, + GNUNET_MESSAGE_TYPE_NAT_HANDLE_STUN, + struct GNUNET_NAT_HandleStunMessage, + NULL), + GNUNET_MQ_hd_var_size(request_connection_reversal, + GNUNET_MESSAGE_TYPE_NAT_REQUEST_CONNECTION_REVERSAL, + struct GNUNET_NAT_RequestConnectionReversalMessage, + NULL), + GNUNET_MQ_handler_end()); #if defined(LINUX) && defined(__GLIBC__) @@ -2036,11 +2046,11 @@ GNUNET_SERVICE_MAIN * MINIMIZE heap size (way below 128k) since this process doesn't need much. */ void __attribute__ ((constructor)) -GNUNET_ARM_memory_init () +GNUNET_ARM_memory_init() { - mallopt (M_TRIM_THRESHOLD, 4 * 1024); - mallopt (M_TOP_PAD, 1 * 1024); - malloc_trim (0); + mallopt(M_TRIM_THRESHOLD, 4 * 1024); + mallopt(M_TOP_PAD, 1 * 1024); + malloc_trim(0); } #endif diff --git a/src/nat/gnunet-service-nat.h b/src/nat/gnunet-service-nat.h index ec642f6e5..5717306bb 100644 --- a/src/nat/gnunet-service-nat.h +++ b/src/nat/gnunet-service-nat.h @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2016, 2017 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2016, 2017 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ diff --git a/src/nat/gnunet-service-nat_externalip.c b/src/nat/gnunet-service-nat_externalip.c index 282b070d3..c97f7f58b 100644 --- a/src/nat/gnunet-service-nat_externalip.c +++ b/src/nat/gnunet-service-nat_externalip.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * Code to figure out what our external IPv4 address(es) might * be (external IPv4s are what is seen on the rest of the Internet). @@ -54,26 +54,25 @@ * How long do we wait until we re-try running `external-ip` if the * command failed to terminate nicely? */ -#define EXTERN_IP_RETRY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) +#define EXTERN_IP_RETRY_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) /** * How long do we wait until we re-try running `external-ip` if the * command failed (but terminated)? */ -#define EXTERN_IP_RETRY_FAILURE GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 30) +#define EXTERN_IP_RETRY_FAILURE GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 30) /** * How long do we wait until we re-try running `external-ip` if the * command succeeded? */ -#define EXTERN_IP_RETRY_SUCCESS GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5) +#define EXTERN_IP_RETRY_SUCCESS GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5) /** * Handle to monitor for external IP changes. */ -struct GN_ExternalIPMonitor -{ +struct GN_ExternalIPMonitor { /** * Kept in DLL. */ @@ -93,7 +92,6 @@ struct GN_ExternalIPMonitor * Closure for @e cb. */ void *cb_cls; - }; @@ -133,15 +131,15 @@ static struct in_addr mini_external_ipv4; * @param v4 the external address that changed */ static void -notify_monitors_external_ipv4_change (int add, - const struct in_addr *v4) +notify_monitors_external_ipv4_change(int add, + const struct in_addr *v4) { for (struct GN_ExternalIPMonitor *mon = mon_head; NULL != mon; mon = mon->next) - mon->cb (mon->cb_cls, - v4, - add); + mon->cb(mon->cb_cls, + v4, + add); } @@ -152,7 +150,7 @@ notify_monitors_external_ipv4_change (int add, * @param cls NULL */ static void -run_external_ip (void *cls); +run_external_ip(void *cls); /** @@ -165,46 +163,47 @@ run_external_ip (void *cls); * @param result #GNUNET_NAT_ERROR_SUCCESS on success, otherwise the specific error code */ static void -handle_external_ip (void *cls, - const struct in_addr *addr, - enum GNUNET_NAT_StatusCode result) +handle_external_ip(void *cls, + const struct in_addr *addr, + enum GNUNET_NAT_StatusCode result) { char buf[INET_ADDRSTRLEN]; probe_external_ip_op = NULL; - GNUNET_SCHEDULER_cancel (probe_external_ip_task); + GNUNET_SCHEDULER_cancel(probe_external_ip_task); probe_external_ip_task - = GNUNET_SCHEDULER_add_delayed ((NULL == addr) - ? EXTERN_IP_RETRY_FAILURE - : EXTERN_IP_RETRY_SUCCESS, - &run_external_ip, - NULL); + = GNUNET_SCHEDULER_add_delayed((NULL == addr) + ? EXTERN_IP_RETRY_FAILURE + : EXTERN_IP_RETRY_SUCCESS, + &run_external_ip, + NULL); switch (result) - { - case GNUNET_NAT_ERROR_SUCCESS: - GNUNET_assert (NULL != addr); - if (addr->s_addr == mini_external_ipv4.s_addr) - return; /* not change */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Our external IP is now %s\n", - inet_ntop (AF_INET, - addr, - buf, - sizeof (buf))); - if (0 != mini_external_ipv4.s_addr) - notify_monitors_external_ipv4_change (GNUNET_NO, - &mini_external_ipv4); - mini_external_ipv4 = *addr; - notify_monitors_external_ipv4_change (GNUNET_YES, - &mini_external_ipv4); - break; - default: - if (0 != mini_external_ipv4.s_addr) - notify_monitors_external_ipv4_change (GNUNET_NO, - &mini_external_ipv4); - mini_external_ipv4.s_addr = 0; - break; - } + { + case GNUNET_NAT_ERROR_SUCCESS: + GNUNET_assert(NULL != addr); + if (addr->s_addr == mini_external_ipv4.s_addr) + return; /* not change */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Our external IP is now %s\n", + inet_ntop(AF_INET, + addr, + buf, + sizeof(buf))); + if (0 != mini_external_ipv4.s_addr) + notify_monitors_external_ipv4_change(GNUNET_NO, + &mini_external_ipv4); + mini_external_ipv4 = *addr; + notify_monitors_external_ipv4_change(GNUNET_YES, + &mini_external_ipv4); + break; + + default: + if (0 != mini_external_ipv4.s_addr) + notify_monitors_external_ipv4_change(GNUNET_NO, + &mini_external_ipv4); + mini_external_ipv4.s_addr = 0; + break; + } } @@ -215,20 +214,20 @@ handle_external_ip (void *cls, * @param cls NULL */ static void -run_external_ip (void *cls) +run_external_ip(void *cls) { probe_external_ip_task - = GNUNET_SCHEDULER_add_delayed (EXTERN_IP_RETRY_TIMEOUT, - &run_external_ip, - NULL); + = GNUNET_SCHEDULER_add_delayed(EXTERN_IP_RETRY_TIMEOUT, + &run_external_ip, + NULL); if (NULL != probe_external_ip_op) - { - GNUNET_NAT_mini_get_external_ipv4_cancel_ (probe_external_ip_op); - probe_external_ip_op = NULL; - } + { + GNUNET_NAT_mini_get_external_ipv4_cancel_(probe_external_ip_op); + probe_external_ip_op = NULL; + } probe_external_ip_op - = GNUNET_NAT_mini_get_external_ipv4_ (&handle_external_ip, - NULL); + = GNUNET_NAT_mini_get_external_ipv4_(&handle_external_ip, + NULL); } @@ -239,32 +238,32 @@ run_external_ip (void *cls) * @param have_nat #GNUNET_YES if we believe we are behind NAT */ void -GN_nat_status_changed (int have_nat) +GN_nat_status_changed(int have_nat) { if (GNUNET_YES != enable_upnp) return; - if ( (GNUNET_YES == have_nat) && - (NULL == probe_external_ip_task) && - (NULL == probe_external_ip_op) ) - { - probe_external_ip_task - = GNUNET_SCHEDULER_add_now (&run_external_ip, - NULL); - return; - } - if (GNUNET_NO == have_nat) - { - if (NULL != probe_external_ip_task) + if ((GNUNET_YES == have_nat) && + (NULL == probe_external_ip_task) && + (NULL == probe_external_ip_op)) { - GNUNET_SCHEDULER_cancel (probe_external_ip_task); - probe_external_ip_task = NULL; + probe_external_ip_task + = GNUNET_SCHEDULER_add_now(&run_external_ip, + NULL); + return; } - if (NULL != probe_external_ip_op) + if (GNUNET_NO == have_nat) { - GNUNET_NAT_mini_get_external_ipv4_cancel_ (probe_external_ip_op); - probe_external_ip_op = NULL; + if (NULL != probe_external_ip_task) + { + GNUNET_SCHEDULER_cancel(probe_external_ip_task); + probe_external_ip_task = NULL; + } + if (NULL != probe_external_ip_op) + { + GNUNET_NAT_mini_get_external_ipv4_cancel_(probe_external_ip_op); + probe_external_ip_op = NULL; + } } - } } @@ -276,21 +275,21 @@ GN_nat_status_changed (int have_nat) * @return handle to cancel */ struct GN_ExternalIPMonitor * -GN_external_ipv4_monitor_start (GN_NotifyExternalIPv4Change cb, - void *cb_cls) +GN_external_ipv4_monitor_start(GN_NotifyExternalIPv4Change cb, + void *cb_cls) { struct GN_ExternalIPMonitor *mon; - mon = GNUNET_new (struct GN_ExternalIPMonitor); + mon = GNUNET_new(struct GN_ExternalIPMonitor); mon->cb = cb; mon->cb_cls = cb_cls; - GNUNET_CONTAINER_DLL_insert (mon_head, - mon_tail, - mon); + GNUNET_CONTAINER_DLL_insert(mon_head, + mon_tail, + mon); if (0 != mini_external_ipv4.s_addr) - cb (cb_cls, - &mini_external_ipv4, - GNUNET_YES); + cb(cb_cls, + &mini_external_ipv4, + GNUNET_YES); return mon; } @@ -301,12 +300,12 @@ GN_external_ipv4_monitor_start (GN_NotifyExternalIPv4Change cb, * @param mon monitor to call */ void -GN_external_ipv4_monitor_stop (struct GN_ExternalIPMonitor *mon) +GN_external_ipv4_monitor_stop(struct GN_ExternalIPMonitor *mon) { - GNUNET_CONTAINER_DLL_remove (mon_head, - mon_tail, - mon); - GNUNET_free (mon); + GNUNET_CONTAINER_DLL_remove(mon_head, + mon_tail, + mon); + GNUNET_free(mon); } /* end of gnunet-service-nat_externalip.c */ diff --git a/src/nat/gnunet-service-nat_externalip.h b/src/nat/gnunet-service-nat_externalip.h index f93b6793d..41ab49e2f 100644 --- a/src/nat/gnunet-service-nat_externalip.h +++ b/src/nat/gnunet-service-nat_externalip.h @@ -11,19 +11,19 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * Code to figure out what our external IPv4 address(es) might * be (external IPv4s are what is seen on the rest of the Internet). * * This can be implemented using different methods, and we allow * the main service to be notified about changes to what we believe - * is our external IPv4 address. + * is our external IPv4 address. * * Note that this is explicitly only about NATed systems; if one * of our network interfaces has a global IP address this does @@ -46,7 +46,7 @@ * @param have_nat #GNUNET_YES if we believe we are behind NAT */ void -GN_nat_status_changed (int have_nat); +GN_nat_status_changed(int have_nat); /** @@ -58,8 +58,8 @@ GN_nat_status_changed (int have_nat); */ typedef void (*GN_NotifyExternalIPv4Change)(void *cls, - const struct in_addr *ip, - int add_remove); + const struct in_addr *ip, + int add_remove); /** @@ -76,8 +76,8 @@ struct GN_ExternalIPMonitor; * @return handle to cancel */ struct GN_ExternalIPMonitor * -GN_external_ipv4_monitor_start (GN_NotifyExternalIPv4Change cb, - void *cb_cls); +GN_external_ipv4_monitor_start(GN_NotifyExternalIPv4Change cb, + void *cb_cls); /** @@ -86,7 +86,7 @@ GN_external_ipv4_monitor_start (GN_NotifyExternalIPv4Change cb, * @param mon monitor to call */ void -GN_external_ipv4_monitor_stop (struct GN_ExternalIPMonitor *mon); +GN_external_ipv4_monitor_stop(struct GN_ExternalIPMonitor *mon); #endif diff --git a/src/nat/gnunet-service-nat_helper.c b/src/nat/gnunet-service-nat_helper.c index cf5038dd7..42612751d 100644 --- a/src/nat/gnunet-service-nat_helper.c +++ b/src/nat/gnunet-service-nat_helper.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nat/gnunet-service-nat_helper.c @@ -32,9 +32,7 @@ /** * Information we keep per NAT helper process. */ -struct HelperContext -{ - +struct HelperContext { /** * IP address we pass to the NAT helper. */ @@ -89,7 +87,7 @@ struct HelperContext * @param cls a `struct HelperContext` */ static void -restart_nat_server (void *cls); +restart_nat_server(void *cls); /** @@ -98,13 +96,13 @@ restart_nat_server (void *cls); * @param h context of the helper */ static void -try_again (struct HelperContext *h) +try_again(struct HelperContext *h) { - GNUNET_assert (NULL == h->server_read_task); - h->server_retry_delay = GNUNET_TIME_STD_BACKOFF (h->server_retry_delay); - h->server_read_task = GNUNET_SCHEDULER_add_delayed (h->server_retry_delay, - &restart_nat_server, - h); + GNUNET_assert(NULL == h->server_read_task); + h->server_retry_delay = GNUNET_TIME_STD_BACKOFF(h->server_retry_delay); + h->server_read_task = GNUNET_SCHEDULER_add_delayed(h->server_retry_delay, + &restart_nat_server, + h); } @@ -116,7 +114,7 @@ try_again (struct HelperContext *h) * @param cls the `struct HelperContext` */ static void -nat_server_read (void *cls) +nat_server_read(void *cls) { struct HelperContext *h = cls; char mybuf[40]; @@ -126,73 +124,73 @@ nat_server_read (void *cls) struct sockaddr_in sin_addr; h->server_read_task = NULL; - memset (mybuf, 0, sizeof (mybuf)); + memset(mybuf, 0, sizeof(mybuf)); bytes = - GNUNET_DISK_file_read (h->server_stdout_handle, mybuf, sizeof (mybuf)); + GNUNET_DISK_file_read(h->server_stdout_handle, mybuf, sizeof(mybuf)); if (bytes < 1) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished reading from server stdout with code: %d\n", - (int) bytes); - if (0 != GNUNET_OS_process_kill (h->server_proc, GNUNET_TERM_SIG)) - GNUNET_log_from_strerror (GNUNET_ERROR_TYPE_WARNING, "nat", "kill"); - GNUNET_OS_process_wait (h->server_proc); - GNUNET_OS_process_destroy (h->server_proc); - h->server_proc = NULL; - GNUNET_DISK_pipe_close (h->server_stdout); - h->server_stdout = NULL; - h->server_stdout_handle = NULL; - try_again (h); - return; - } - - port_start = NULL; - for (size_t i = 0; i < sizeof (mybuf); i++) - { - if (mybuf[i] == '\n') { - mybuf[i] = '\0'; - break; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished reading from server stdout with code: %d\n", + (int)bytes); + if (0 != GNUNET_OS_process_kill(h->server_proc, GNUNET_TERM_SIG)) + GNUNET_log_from_strerror(GNUNET_ERROR_TYPE_WARNING, "nat", "kill"); + GNUNET_OS_process_wait(h->server_proc); + GNUNET_OS_process_destroy(h->server_proc); + h->server_proc = NULL; + GNUNET_DISK_pipe_close(h->server_stdout); + h->server_stdout = NULL; + h->server_stdout_handle = NULL; + try_again(h); + return; } - if ((mybuf[i] == ':') && (i + 1 < sizeof (mybuf))) + + port_start = NULL; + for (size_t i = 0; i < sizeof(mybuf); i++) { - mybuf[i] = '\0'; - port_start = &mybuf[i + 1]; + if (mybuf[i] == '\n') + { + mybuf[i] = '\0'; + break; + } + if ((mybuf[i] == ':') && (i + 1 < sizeof(mybuf))) + { + mybuf[i] = '\0'; + port_start = &mybuf[i + 1]; + } } - } /* construct socket address of sender */ - memset (&sin_addr, 0, sizeof (sin_addr)); + memset(&sin_addr, 0, sizeof(sin_addr)); sin_addr.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN - sin_addr.sin_len = sizeof (sin_addr); + sin_addr.sin_len = sizeof(sin_addr); #endif - if ((NULL == port_start) || (1 != sscanf (port_start, "%d", &port)) || - (-1 == inet_pton (AF_INET, mybuf, &sin_addr.sin_addr))) - { - /* should we restart gnunet-helper-nat-server? */ - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ( - "gnunet-helper-nat-server generated malformed address `%s'\n"), - mybuf); - h->server_read_task = - GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, - h->server_stdout_handle, - &nat_server_read, - h); - return; - } - sin_addr.sin_port = htons ((uint16_t) port); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "gnunet-helper-nat-server read: %s:%d\n", - mybuf, - port); - h->cb (h->cb_cls, &sin_addr); + if ((NULL == port_start) || (1 != sscanf(port_start, "%d", &port)) || + (-1 == inet_pton(AF_INET, mybuf, &sin_addr.sin_addr))) + { + /* should we restart gnunet-helper-nat-server? */ + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _( + "gnunet-helper-nat-server generated malformed address `%s'\n"), + mybuf); + h->server_read_task = + GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL, + h->server_stdout_handle, + &nat_server_read, + h); + return; + } + sin_addr.sin_port = htons((uint16_t)port); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "gnunet-helper-nat-server read: %s:%d\n", + mybuf, + port); + h->cb(h->cb_cls, &sin_addr); h->server_read_task = - GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, - h->server_stdout_handle, - &nat_server_read, - h); + GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL, + h->server_stdout_handle, + &nat_server_read, + h); } @@ -203,67 +201,67 @@ nat_server_read (void *cls) * @param cls a `struct HelperContext` */ static void -restart_nat_server (void *cls) +restart_nat_server(void *cls) { struct HelperContext *h = cls; char *binary; char ia[INET_ADDRSTRLEN]; h->server_read_task = NULL; - GNUNET_assert (NULL != - inet_ntop (AF_INET, &h->internal_address, ia, sizeof (ia))); + GNUNET_assert(NULL != + inet_ntop(AF_INET, &h->internal_address, ia, sizeof(ia))); /* Start the server process */ - binary = GNUNET_OS_get_suid_binary_path (h->cfg, "gnunet-helper-nat-server"); - if (GNUNET_YES != GNUNET_OS_check_helper_binary (binary, GNUNET_YES, ia)) - { - /* move instantly to max delay, as this is unlikely to be fixed */ - h->server_retry_delay = GNUNET_TIME_STD_EXPONENTIAL_BACKOFF_THRESHOLD; - GNUNET_free (binary); - try_again (h); - return; - } + binary = GNUNET_OS_get_suid_binary_path(h->cfg, "gnunet-helper-nat-server"); + if (GNUNET_YES != GNUNET_OS_check_helper_binary(binary, GNUNET_YES, ia)) + { + /* move instantly to max delay, as this is unlikely to be fixed */ + h->server_retry_delay = GNUNET_TIME_STD_EXPONENTIAL_BACKOFF_THRESHOLD; + GNUNET_free(binary); + try_again(h); + return; + } h->server_stdout = - GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES); + GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES); if (NULL == h->server_stdout) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "pipe"); - GNUNET_free (binary); - try_again (h); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting `%s' at `%s'\n", - "gnunet-helper-nat-server", - ia); - h->server_proc = GNUNET_OS_start_process (GNUNET_NO, - 0, - NULL, - h->server_stdout, - NULL, - binary, - "gnunet-helper-nat-server", - ia, - NULL); - GNUNET_free (binary); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "pipe"); + GNUNET_free(binary); + try_again(h); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting `%s' at `%s'\n", + "gnunet-helper-nat-server", + ia); + h->server_proc = GNUNET_OS_start_process(GNUNET_NO, + 0, + NULL, + h->server_stdout, + NULL, + binary, + "gnunet-helper-nat-server", + ia, + NULL); + GNUNET_free(binary); if (NULL == h->server_proc) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to start %s\n"), - "gnunet-helper-nat-server"); - GNUNET_DISK_pipe_close (h->server_stdout); - h->server_stdout = NULL; - try_again (h); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to start %s\n"), + "gnunet-helper-nat-server"); + GNUNET_DISK_pipe_close(h->server_stdout); + h->server_stdout = NULL; + try_again(h); + return; + } /* Close the write end of the read pipe */ - GNUNET_DISK_pipe_close_end (h->server_stdout, GNUNET_DISK_PIPE_END_WRITE); + GNUNET_DISK_pipe_close_end(h->server_stdout, GNUNET_DISK_PIPE_END_WRITE); h->server_stdout_handle = - GNUNET_DISK_pipe_handle (h->server_stdout, GNUNET_DISK_PIPE_END_READ); + GNUNET_DISK_pipe_handle(h->server_stdout, GNUNET_DISK_PIPE_END_READ); h->server_read_task = - GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, - h->server_stdout_handle, - &nat_server_read, - h); + GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL, + h->server_stdout_handle, + &nat_server_read, + h); } @@ -278,24 +276,24 @@ restart_nat_server (void *cls) * @return NULL on error */ struct HelperContext * -GN_start_gnunet_nat_server_ (const struct in_addr *internal_address, - GN_ReversalCallback cb, - void *cb_cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +GN_start_gnunet_nat_server_(const struct in_addr *internal_address, + GN_ReversalCallback cb, + void *cb_cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct HelperContext *h; - h = GNUNET_new (struct HelperContext); + h = GNUNET_new(struct HelperContext); h->cb = cb; h->cb_cls = cb_cls; h->internal_address = *internal_address; h->cfg = cfg; - restart_nat_server (h); + restart_nat_server(h); if (NULL == h->server_stdout) - { - GN_stop_gnunet_nat_server_ (h); - return NULL; - } + { + GN_stop_gnunet_nat_server_(h); + return NULL; + } return h; } @@ -307,31 +305,31 @@ GN_start_gnunet_nat_server_ (const struct in_addr *internal_address, * @param h helper context to stop */ void -GN_stop_gnunet_nat_server_ (struct HelperContext *h) +GN_stop_gnunet_nat_server_(struct HelperContext *h) { if (NULL != h->server_read_task) - { - GNUNET_SCHEDULER_cancel (h->server_read_task); - h->server_read_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(h->server_read_task); + h->server_read_task = NULL; + } if (NULL != h->server_proc) - { - if (0 != GNUNET_OS_process_kill (h->server_proc, GNUNET_TERM_SIG)) - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill"); - GNUNET_OS_process_wait (h->server_proc); - GNUNET_OS_process_destroy (h->server_proc); - h->server_proc = NULL; - GNUNET_DISK_pipe_close (h->server_stdout); - h->server_stdout = NULL; - h->server_stdout_handle = NULL; - } + { + if (0 != GNUNET_OS_process_kill(h->server_proc, GNUNET_TERM_SIG)) + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill"); + GNUNET_OS_process_wait(h->server_proc); + GNUNET_OS_process_destroy(h->server_proc); + h->server_proc = NULL; + GNUNET_DISK_pipe_close(h->server_stdout); + h->server_stdout = NULL; + h->server_stdout_handle = NULL; + } if (NULL != h->server_stdout) - { - GNUNET_DISK_pipe_close (h->server_stdout); - h->server_stdout = NULL; - h->server_stdout_handle = NULL; - } - GNUNET_free (h); + { + GNUNET_DISK_pipe_close(h->server_stdout); + h->server_stdout = NULL; + h->server_stdout_handle = NULL; + } + GNUNET_free(h); } @@ -348,10 +346,10 @@ GN_stop_gnunet_nat_server_ (struct HelperContext *h) * #GNUNET_OK otherwise */ int -GN_request_connection_reversal (const struct in_addr *internal_address, - uint16_t internal_port, - const struct in_addr *remote_v4, - const struct GNUNET_CONFIGURATION_Handle *cfg) +GN_request_connection_reversal(const struct in_addr *internal_address, + uint16_t internal_port, + const struct in_addr *remote_v4, + const struct GNUNET_CONFIGURATION_Handle *cfg) { char intv4[INET_ADDRSTRLEN]; char remv4[INET_ADDRSTRLEN]; @@ -359,44 +357,44 @@ GN_request_connection_reversal (const struct in_addr *internal_address, struct GNUNET_OS_Process *proc; char *binary; - if (NULL == inet_ntop (AF_INET, internal_address, intv4, INET_ADDRSTRLEN)) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop"); - return GNUNET_SYSERR; - } - if (NULL == inet_ntop (AF_INET, remote_v4, remv4, INET_ADDRSTRLEN)) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "inet_ntop"); - return GNUNET_SYSERR; - } - GNUNET_snprintf (port_as_string, - sizeof (port_as_string), - "%d", - internal_port); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Running gnunet-helper-nat-client %s %s %u\n", - intv4, - remv4, - internal_port); - binary = GNUNET_OS_get_suid_binary_path (cfg, "gnunet-helper-nat-client"); - proc = GNUNET_OS_start_process (GNUNET_NO, - 0, - NULL, - NULL, - NULL, - binary, - "gnunet-helper-nat-client", - intv4, - remv4, - port_as_string, - NULL); - GNUNET_free (binary); + if (NULL == inet_ntop(AF_INET, internal_address, intv4, INET_ADDRSTRLEN)) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "inet_ntop"); + return GNUNET_SYSERR; + } + if (NULL == inet_ntop(AF_INET, remote_v4, remv4, INET_ADDRSTRLEN)) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "inet_ntop"); + return GNUNET_SYSERR; + } + GNUNET_snprintf(port_as_string, + sizeof(port_as_string), + "%d", + internal_port); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Running gnunet-helper-nat-client %s %s %u\n", + intv4, + remv4, + internal_port); + binary = GNUNET_OS_get_suid_binary_path(cfg, "gnunet-helper-nat-client"); + proc = GNUNET_OS_start_process(GNUNET_NO, + 0, + NULL, + NULL, + NULL, + binary, + "gnunet-helper-nat-client", + intv4, + remv4, + port_as_string, + NULL); + GNUNET_free(binary); if (NULL == proc) return GNUNET_SYSERR; /* we know that the gnunet-helper-nat-client will terminate virtually * instantly */ - GNUNET_OS_process_wait (proc); - GNUNET_OS_process_destroy (proc); + GNUNET_OS_process_wait(proc); + GNUNET_OS_process_destroy(proc); return GNUNET_OK; } diff --git a/src/nat/gnunet-service-nat_helper.h b/src/nat/gnunet-service-nat_helper.h index 4c39a374c..e655149bc 100644 --- a/src/nat/gnunet-service-nat_helper.h +++ b/src/nat/gnunet-service-nat_helper.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nat/gnunet-service-nat_helper.h @@ -39,11 +39,11 @@ struct HelperContext; * request from another peer. * * @param cls closure - * @param ra IP address of the peer who wants us to connect to it + * @param ra IP address of the peer who wants us to connect to it */ typedef void (*GN_ReversalCallback) (void *cls, - const struct sockaddr_in *ra); + const struct sockaddr_in *ra); /** @@ -57,12 +57,12 @@ typedef void * @return NULL on error */ struct HelperContext * -GN_start_gnunet_nat_server_ (const struct in_addr *internal_address, - GN_ReversalCallback cb, - void *cb_cls, - const struct GNUNET_CONFIGURATION_Handle *cfg); +GN_start_gnunet_nat_server_(const struct in_addr *internal_address, + GN_ReversalCallback cb, + void *cb_cls, + const struct GNUNET_CONFIGURATION_Handle *cfg); + - /** * Start the gnunet-helper-nat-server and process incoming * requests. @@ -70,7 +70,7 @@ GN_start_gnunet_nat_server_ (const struct in_addr *internal_address, * @param h helper context to stop */ void -GN_stop_gnunet_nat_server_ (struct HelperContext *h); +GN_stop_gnunet_nat_server_(struct HelperContext *h); /** @@ -86,10 +86,10 @@ GN_stop_gnunet_nat_server_ (struct HelperContext *h); * #GNUNET_OK otherwise */ int -GN_request_connection_reversal (const struct in_addr *internal_address, - uint16_t internal_port, - const struct in_addr *remote_v4, - const struct GNUNET_CONFIGURATION_Handle *cfg); +GN_request_connection_reversal(const struct in_addr *internal_address, + uint16_t internal_port, + const struct in_addr *remote_v4, + const struct GNUNET_CONFIGURATION_Handle *cfg); /* end of gnunet-service-nat_helper.h */ diff --git a/src/nat/gnunet-service-nat_mini.c b/src/nat/gnunet-service-nat_mini.c index 375188ff2..94534e81c 100644 --- a/src/nat/gnunet-service-nat_mini.c +++ b/src/nat/gnunet-service-nat_mini.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nat/gnunet-service-nat_mini.c @@ -29,24 +29,24 @@ #include "gnunet-service-nat_mini.h" #include "nat.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "nat", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "nat", __VA_ARGS__) /** * How long do we give upnpc to create a mapping? */ -#define MAP_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15) +#define MAP_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15) /** * How long do we give upnpc to remove a mapping? */ #define UNMAP_TIMEOUT \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 1) /** * How often do we check for changes in the mapping? */ #define MAP_REFRESH_FREQ \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5) /* ************************* external-ip calling ************************ */ @@ -54,9 +54,7 @@ /** * Opaque handle to cancel "GNUNET_NAT_mini_get_external_ipv4" operation. */ -struct GNUNET_NAT_ExternalHandle -{ - +struct GNUNET_NAT_ExternalHandle { /** * Function to call with the result. */ @@ -111,43 +109,43 @@ struct GNUNET_NAT_ExternalHandle * @param cls the `struct GNUNET_NAT_ExternalHandle` */ static void -read_external_ipv4 (void *cls) +read_external_ipv4(void *cls) { struct GNUNET_NAT_ExternalHandle *eh = cls; ssize_t ret; struct in_addr addr; eh->task = NULL; - ret = GNUNET_DISK_file_read (eh->r, - &eh->buf[eh->off], - sizeof (eh->buf) - eh->off); + ret = GNUNET_DISK_file_read(eh->r, + &eh->buf[eh->off], + sizeof(eh->buf) - eh->off); if (ret > 0) - { - /* try to read more */ - eh->off += ret; - eh->task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, - eh->r, - &read_external_ipv4, - eh); - return; - } + { + /* try to read more */ + eh->off += ret; + eh->task = GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL, + eh->r, + &read_external_ipv4, + eh); + return; + } eh->ret = GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_OUTPUT_INVALID; if ((eh->off > 7) && (eh->buf[eh->off - 1] == '\n')) - { - eh->buf[eh->off - 1] = '\0'; - if (1 == inet_pton (AF_INET, eh->buf, &addr)) { - if (0 == addr.s_addr) - eh->ret = - GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID; /* got 0.0.0.0 */ - else - eh->ret = GNUNET_NAT_ERROR_SUCCESS; + eh->buf[eh->off - 1] = '\0'; + if (1 == inet_pton(AF_INET, eh->buf, &addr)) + { + if (0 == addr.s_addr) + eh->ret = + GNUNET_NAT_ERROR_EXTERNAL_IP_ADDRESS_INVALID; /* got 0.0.0.0 */ + else + eh->ret = GNUNET_NAT_ERROR_SUCCESS; + } } - } - eh->cb (eh->cb_cls, - (GNUNET_NAT_ERROR_SUCCESS == eh->ret) ? &addr : NULL, - eh->ret); - GNUNET_NAT_mini_get_external_ipv4_cancel_ (eh); + eh->cb(eh->cb_cls, + (GNUNET_NAT_ERROR_SUCCESS == eh->ret) ? &addr : NULL, + eh->ret); + GNUNET_NAT_mini_get_external_ipv4_cancel_(eh); } @@ -157,13 +155,13 @@ read_external_ipv4 (void *cls) * @param cls the `struct GNUNET_NAT_ExternalHandle` (freed) */ static void -signal_external_ip_error (void *cls) +signal_external_ip_error(void *cls) { struct GNUNET_NAT_ExternalHandle *eh = cls; eh->task = NULL; - eh->cb (eh->cb_cls, NULL, eh->ret); - GNUNET_free (eh); + eh->cb(eh->cb_cls, NULL, eh->ret); + GNUNET_free(eh); } @@ -175,52 +173,52 @@ signal_external_ip_error (void *cls) * @return handle for cancellation (can only be used until @a cb is called), never NULL */ struct GNUNET_NAT_ExternalHandle * -GNUNET_NAT_mini_get_external_ipv4_ (GNUNET_NAT_IPCallback cb, void *cb_cls) +GNUNET_NAT_mini_get_external_ipv4_(GNUNET_NAT_IPCallback cb, void *cb_cls) { struct GNUNET_NAT_ExternalHandle *eh; - eh = GNUNET_new (struct GNUNET_NAT_ExternalHandle); + eh = GNUNET_new(struct GNUNET_NAT_ExternalHandle); eh->cb = cb; eh->cb_cls = cb_cls; eh->ret = GNUNET_NAT_ERROR_SUCCESS; if (GNUNET_SYSERR == - GNUNET_OS_check_helper_binary ("external-ip", GNUNET_NO, NULL)) - { - LOG (GNUNET_ERROR_TYPE_INFO, _ ("`external-ip' command not found\n")); - eh->ret = GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_NOT_FOUND; - eh->task = GNUNET_SCHEDULER_add_now (&signal_external_ip_error, eh); - return eh; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Running `external-ip' to determine our external IP\n"); - eh->opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES); + GNUNET_OS_check_helper_binary("external-ip", GNUNET_NO, NULL)) + { + LOG(GNUNET_ERROR_TYPE_INFO, _("`external-ip' command not found\n")); + eh->ret = GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_NOT_FOUND; + eh->task = GNUNET_SCHEDULER_add_now(&signal_external_ip_error, eh); + return eh; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Running `external-ip' to determine our external IP\n"); + eh->opipe = GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES); if (NULL == eh->opipe) - { - eh->ret = GNUNET_NAT_ERROR_IPC_FAILURE; - eh->task = GNUNET_SCHEDULER_add_now (&signal_external_ip_error, eh); - return eh; - } - eh->eip = GNUNET_OS_start_process (GNUNET_NO, - 0, - NULL, - eh->opipe, - NULL, - "external-ip", - "external-ip", - NULL); + { + eh->ret = GNUNET_NAT_ERROR_IPC_FAILURE; + eh->task = GNUNET_SCHEDULER_add_now(&signal_external_ip_error, eh); + return eh; + } + eh->eip = GNUNET_OS_start_process(GNUNET_NO, + 0, + NULL, + eh->opipe, + NULL, + "external-ip", + "external-ip", + NULL); if (NULL == eh->eip) - { - GNUNET_DISK_pipe_close (eh->opipe); - eh->ret = GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_FAILED; - eh->task = GNUNET_SCHEDULER_add_now (&signal_external_ip_error, eh); - return eh; - } - GNUNET_DISK_pipe_close_end (eh->opipe, GNUNET_DISK_PIPE_END_WRITE); - eh->r = GNUNET_DISK_pipe_handle (eh->opipe, GNUNET_DISK_PIPE_END_READ); - eh->task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, - eh->r, - &read_external_ipv4, - eh); + { + GNUNET_DISK_pipe_close(eh->opipe); + eh->ret = GNUNET_NAT_ERROR_EXTERNAL_IP_UTILITY_FAILED; + eh->task = GNUNET_SCHEDULER_add_now(&signal_external_ip_error, eh); + return eh; + } + GNUNET_DISK_pipe_close_end(eh->opipe, GNUNET_DISK_PIPE_END_WRITE); + eh->r = GNUNET_DISK_pipe_handle(eh->opipe, GNUNET_DISK_PIPE_END_READ); + eh->task = GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL, + eh->r, + &read_external_ipv4, + eh); return eh; } @@ -231,25 +229,25 @@ GNUNET_NAT_mini_get_external_ipv4_ (GNUNET_NAT_IPCallback cb, void *cb_cls) * @param eh operation to cancel */ void -GNUNET_NAT_mini_get_external_ipv4_cancel_ (struct GNUNET_NAT_ExternalHandle *eh) +GNUNET_NAT_mini_get_external_ipv4_cancel_(struct GNUNET_NAT_ExternalHandle *eh) { if (NULL != eh->eip) - { - (void) GNUNET_OS_process_kill (eh->eip, SIGKILL); - GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (eh->eip)); - GNUNET_OS_process_destroy (eh->eip); - } + { + (void)GNUNET_OS_process_kill(eh->eip, SIGKILL); + GNUNET_break(GNUNET_OK == GNUNET_OS_process_wait(eh->eip)); + GNUNET_OS_process_destroy(eh->eip); + } if (NULL != eh->opipe) - { - GNUNET_DISK_pipe_close (eh->opipe); - eh->opipe = NULL; - } + { + GNUNET_DISK_pipe_close(eh->opipe); + eh->opipe = NULL; + } if (NULL != eh->task) - { - GNUNET_SCHEDULER_cancel (eh->task); - eh->task = NULL; - } - GNUNET_free (eh); + { + GNUNET_SCHEDULER_cancel(eh->task); + eh->task = NULL; + } + GNUNET_free(eh); } @@ -259,9 +257,7 @@ GNUNET_NAT_mini_get_external_ipv4_cancel_ (struct GNUNET_NAT_ExternalHandle *eh) /** * Handle to a mapping created with upnpc. */ -struct GNUNET_NAT_MiniHandle -{ - +struct GNUNET_NAT_MiniHandle { /** * Function to call on mapping changes. */ @@ -326,7 +322,7 @@ struct GNUNET_NAT_MiniHandle * @param cls the `struct GNUNET_NAT_MiniHandle` */ static void -do_refresh (void *cls); +do_refresh(void *cls); /** @@ -336,7 +332,7 @@ do_refresh (void *cls); * @param line line of output, NULL at the end */ static void -process_map_output (void *cls, const char *line); +process_map_output(void *cls, const char *line); /** @@ -345,29 +341,29 @@ process_map_output (void *cls, const char *line); * @param mini our handle */ static void -run_upnpc_r (struct GNUNET_NAT_MiniHandle *mini) +run_upnpc_r(struct GNUNET_NAT_MiniHandle *mini) { char pstr[6]; - GNUNET_snprintf (pstr, sizeof (pstr), "%u", (unsigned int) mini->port); - mini->map_cmd = GNUNET_OS_command_run (&process_map_output, - mini, - MAP_TIMEOUT, - "upnpc", - "upnpc", - "-r", - pstr, - mini->is_tcp ? "tcp" : "udp", - NULL); + GNUNET_snprintf(pstr, sizeof(pstr), "%u", (unsigned int)mini->port); + mini->map_cmd = GNUNET_OS_command_run(&process_map_output, + mini, + MAP_TIMEOUT, + "upnpc", + "upnpc", + "-r", + pstr, + mini->is_tcp ? "tcp" : "udp", + NULL); if (NULL == mini->map_cmd) - { - mini->ac (mini->ac_cls, - GNUNET_SYSERR, - NULL, - 0, - GNUNET_NAT_ERROR_UPNPC_FAILED); - return; - } + { + mini->ac(mini->ac_cls, + GNUNET_SYSERR, + NULL, + 0, + GNUNET_NAT_ERROR_UPNPC_FAILED); + return; + } } @@ -379,7 +375,7 @@ run_upnpc_r (struct GNUNET_NAT_MiniHandle *mini) * @param line line of output, NULL at the end */ static void -process_refresh_output (void *cls, const char *line) +process_refresh_output(void *cls, const char *line) { struct GNUNET_NAT_MiniHandle *mini = cls; char pstr[9]; @@ -388,53 +384,53 @@ process_refresh_output (void *cls, const char *line) struct in_addr exip; if (NULL == line) - { - GNUNET_OS_command_stop (mini->refresh_cmd); - mini->refresh_cmd = NULL; - if (GNUNET_NO == mini->found) { - /* mapping disappeared, try to re-create */ - if (GNUNET_YES == mini->did_map) - { - mini->ac (mini->ac_cls, - GNUNET_NO, - (const struct sockaddr *) &mini->current_addr, - sizeof (mini->current_addr), - GNUNET_NAT_ERROR_SUCCESS); - mini->did_map = GNUNET_NO; - } - run_upnpc_r (mini); + GNUNET_OS_command_stop(mini->refresh_cmd); + mini->refresh_cmd = NULL; + if (GNUNET_NO == mini->found) + { + /* mapping disappeared, try to re-create */ + if (GNUNET_YES == mini->did_map) + { + mini->ac(mini->ac_cls, + GNUNET_NO, + (const struct sockaddr *)&mini->current_addr, + sizeof(mini->current_addr), + GNUNET_NAT_ERROR_SUCCESS); + mini->did_map = GNUNET_NO; + } + run_upnpc_r(mini); + } + return; } - return; - } - if (! mini->did_map) + if (!mini->did_map) return; /* never mapped, won't find our mapping anyway */ /* we're looking for output of the form: - * "ExternalIPAddress = 12.134.41.124" */ + * "ExternalIPAddress = 12.134.41.124" */ - s = strstr (line, "ExternalIPAddress = "); + s = strstr(line, "ExternalIPAddress = "); if (NULL != s) - { - s += strlen ("ExternalIPAddress = "); - if (1 != inet_pton (AF_INET, s, &exip)) - return; /* skip */ - if (exip.s_addr == mini->current_addr.sin_addr.s_addr) - return; /* no change */ - /* update mapping */ - mini->ac (mini->ac_cls, - GNUNET_NO, - (const struct sockaddr *) &mini->current_addr, - sizeof (mini->current_addr), - GNUNET_NAT_ERROR_SUCCESS); - mini->current_addr.sin_addr = exip; - mini->ac (mini->ac_cls, - GNUNET_YES, - (const struct sockaddr *) &mini->current_addr, - sizeof (mini->current_addr), - GNUNET_NAT_ERROR_SUCCESS); - return; - } + { + s += strlen("ExternalIPAddress = "); + if (1 != inet_pton(AF_INET, s, &exip)) + return; /* skip */ + if (exip.s_addr == mini->current_addr.sin_addr.s_addr) + return; /* no change */ + /* update mapping */ + mini->ac(mini->ac_cls, + GNUNET_NO, + (const struct sockaddr *)&mini->current_addr, + sizeof(mini->current_addr), + GNUNET_NAT_ERROR_SUCCESS); + mini->current_addr.sin_addr = exip; + mini->ac(mini->ac_cls, + GNUNET_YES, + (const struct sockaddr *)&mini->current_addr, + sizeof(mini->current_addr), + GNUNET_NAT_ERROR_SUCCESS); + return; + } /* * we're looking for output of the form: * @@ -446,32 +442,32 @@ process_refresh_output (void *cls, const char *line) * "%s TCP PORT->STRING:OURPORT *" or * "%s UDP PORT->STRING:OURPORT *" */ - GNUNET_snprintf (pstr, sizeof (pstr), ":%u ", mini->port); - if (NULL == (s = strstr (line, "->"))) + GNUNET_snprintf(pstr, sizeof(pstr), ":%u ", mini->port); + if (NULL == (s = strstr(line, "->"))) return; /* skip */ - if (NULL == strstr (s, pstr)) + if (NULL == strstr(s, pstr)) return; /* skip */ - if (1 != sscanf (line, - (mini->is_tcp) ? "%*u TCP %u->%*s:%*u %*s" - : "%*u UDP %u->%*s:%*u %*s", - &nport)) + if (1 != sscanf(line, + (mini->is_tcp) ? "%*u TCP %u->%*s:%*u %*s" + : "%*u UDP %u->%*s:%*u %*s", + &nport)) return; /* skip */ mini->found = GNUNET_YES; - if (nport == ntohs (mini->current_addr.sin_port)) + if (nport == ntohs(mini->current_addr.sin_port)) return; /* no change */ /* external port changed, update mapping */ - mini->ac (mini->ac_cls, - GNUNET_NO, - (const struct sockaddr *) &mini->current_addr, - sizeof (mini->current_addr), - GNUNET_NAT_ERROR_SUCCESS); - mini->current_addr.sin_port = htons ((uint16_t) nport); - mini->ac (mini->ac_cls, - GNUNET_YES, - (const struct sockaddr *) &mini->current_addr, - sizeof (mini->current_addr), - GNUNET_NAT_ERROR_SUCCESS); + mini->ac(mini->ac_cls, + GNUNET_NO, + (const struct sockaddr *)&mini->current_addr, + sizeof(mini->current_addr), + GNUNET_NAT_ERROR_SUCCESS); + mini->current_addr.sin_port = htons((uint16_t)nport); + mini->ac(mini->ac_cls, + GNUNET_YES, + (const struct sockaddr *)&mini->current_addr, + sizeof(mini->current_addr), + GNUNET_NAT_ERROR_SUCCESS); } @@ -481,44 +477,44 @@ process_refresh_output (void *cls, const char *line) * @param cls the 'struct GNUNET_NAT_MiniHandle' */ static void -do_refresh (void *cls) +do_refresh(void *cls) { struct GNUNET_NAT_MiniHandle *mini = cls; int ac; mini->refresh_task = - GNUNET_SCHEDULER_add_delayed (MAP_REFRESH_FREQ, &do_refresh, mini); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Running `upnpc' to check if our mapping still exists\n"); + GNUNET_SCHEDULER_add_delayed(MAP_REFRESH_FREQ, &do_refresh, mini); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Running `upnpc' to check if our mapping still exists\n"); mini->found = GNUNET_NO; ac = GNUNET_NO; if (NULL != mini->map_cmd) - { - /* took way too long, abort it! */ - GNUNET_OS_command_stop (mini->map_cmd); - mini->map_cmd = NULL; - ac = GNUNET_YES; - } + { + /* took way too long, abort it! */ + GNUNET_OS_command_stop(mini->map_cmd); + mini->map_cmd = NULL; + ac = GNUNET_YES; + } if (NULL != mini->refresh_cmd) - { - /* took way too long, abort it! */ - GNUNET_OS_command_stop (mini->refresh_cmd); - mini->refresh_cmd = NULL; - ac = GNUNET_YES; - } - mini->refresh_cmd = GNUNET_OS_command_run (&process_refresh_output, - mini, - MAP_TIMEOUT, - "upnpc", - "upnpc", - "-l", - NULL); + { + /* took way too long, abort it! */ + GNUNET_OS_command_stop(mini->refresh_cmd); + mini->refresh_cmd = NULL; + ac = GNUNET_YES; + } + mini->refresh_cmd = GNUNET_OS_command_run(&process_refresh_output, + mini, + MAP_TIMEOUT, + "upnpc", + "upnpc", + "-l", + NULL); if (GNUNET_YES == ac) - mini->ac (mini->ac_cls, - GNUNET_SYSERR, - NULL, - 0, - GNUNET_NAT_ERROR_UPNPC_TIMEOUT); + mini->ac(mini->ac_cls, + GNUNET_SYSERR, + NULL, + 0, + GNUNET_NAT_ERROR_UPNPC_TIMEOUT); } @@ -529,7 +525,7 @@ do_refresh (void *cls) * @param line line of output, NULL at the end */ static void -process_map_output (void *cls, const char *line) +process_map_output(void *cls, const char *line) { struct GNUNET_NAT_MiniHandle *mini = cls; const char *ipaddr; @@ -538,51 +534,51 @@ process_map_output (void *cls, const char *line) unsigned int port; if (NULL == line) - { - GNUNET_OS_command_stop (mini->map_cmd); - mini->map_cmd = NULL; - if (GNUNET_YES != mini->did_map) - mini->ac (mini->ac_cls, - GNUNET_SYSERR, - NULL, - 0, - GNUNET_NAT_ERROR_UPNPC_PORTMAP_FAILED); - if (NULL == mini->refresh_task) - mini->refresh_task = - GNUNET_SCHEDULER_add_delayed (MAP_REFRESH_FREQ, &do_refresh, mini); - return; - } + { + GNUNET_OS_command_stop(mini->map_cmd); + mini->map_cmd = NULL; + if (GNUNET_YES != mini->did_map) + mini->ac(mini->ac_cls, + GNUNET_SYSERR, + NULL, + 0, + GNUNET_NAT_ERROR_UPNPC_PORTMAP_FAILED); + if (NULL == mini->refresh_task) + mini->refresh_task = + GNUNET_SCHEDULER_add_delayed(MAP_REFRESH_FREQ, &do_refresh, mini); + return; + } /* * The upnpc output we're after looks like this: * * "external 87.123.42.204:3000 TCP is redirected to internal 192.168.2.150:3000" */ - if ((NULL == (ipaddr = strstr (line, " "))) || - (NULL == (pstr = strstr (ipaddr, ":"))) || - (1 != sscanf (pstr + 1, "%u", &port))) - { - return; /* skip line */ - } - ipa = GNUNET_strdup (ipaddr + 1); - strstr (ipa, ":")[0] = '\0'; - if (1 != inet_pton (AF_INET, ipa, &mini->current_addr.sin_addr)) - { - GNUNET_free (ipa); - return; /* skip line */ - } - GNUNET_free (ipa); - - mini->current_addr.sin_port = htons (port); + if ((NULL == (ipaddr = strstr(line, " "))) || + (NULL == (pstr = strstr(ipaddr, ":"))) || + (1 != sscanf(pstr + 1, "%u", &port))) + { + return; /* skip line */ + } + ipa = GNUNET_strdup(ipaddr + 1); + strstr(ipa, ":")[0] = '\0'; + if (1 != inet_pton(AF_INET, ipa, &mini->current_addr.sin_addr)) + { + GNUNET_free(ipa); + return; /* skip line */ + } + GNUNET_free(ipa); + + mini->current_addr.sin_port = htons(port); mini->current_addr.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN - mini->current_addr.sin_len = sizeof (struct sockaddr_in); + mini->current_addr.sin_len = sizeof(struct sockaddr_in); #endif mini->did_map = GNUNET_YES; - mini->ac (mini->ac_cls, - GNUNET_YES, - (const struct sockaddr *) &mini->current_addr, - sizeof (mini->current_addr), - GNUNET_NAT_ERROR_SUCCESS); + mini->ac(mini->ac_cls, + GNUNET_YES, + (const struct sockaddr *)&mini->current_addr, + sizeof(mini->current_addr), + GNUNET_NAT_ERROR_SUCCESS); } @@ -600,28 +596,28 @@ process_map_output (void *cls, const char *line) * @return NULL on error (no 'upnpc' installed) */ struct GNUNET_NAT_MiniHandle * -GNUNET_NAT_mini_map_start (uint16_t port, - int is_tcp, - GNUNET_NAT_MiniAddressCallback ac, - void *ac_cls) +GNUNET_NAT_mini_map_start(uint16_t port, + int is_tcp, + GNUNET_NAT_MiniAddressCallback ac, + void *ac_cls) { struct GNUNET_NAT_MiniHandle *ret; - if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary ("upnpc", GNUNET_NO, NULL)) - { - LOG (GNUNET_ERROR_TYPE_INFO, _ ("`upnpc' command not found\n")); - ac (ac_cls, GNUNET_SYSERR, NULL, 0, GNUNET_NAT_ERROR_UPNPC_NOT_FOUND); - return NULL; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, "Running `upnpc' to install mapping\n"); - ret = GNUNET_new (struct GNUNET_NAT_MiniHandle); + if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary("upnpc", GNUNET_NO, NULL)) + { + LOG(GNUNET_ERROR_TYPE_INFO, _("`upnpc' command not found\n")); + ac(ac_cls, GNUNET_SYSERR, NULL, 0, GNUNET_NAT_ERROR_UPNPC_NOT_FOUND); + return NULL; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, "Running `upnpc' to install mapping\n"); + ret = GNUNET_new(struct GNUNET_NAT_MiniHandle); ret->ac = ac; ret->ac_cls = ac_cls; ret->is_tcp = is_tcp; ret->port = port; ret->refresh_task = - GNUNET_SCHEDULER_add_delayed (MAP_REFRESH_FREQ, &do_refresh, ret); - run_upnpc_r (ret); + GNUNET_SCHEDULER_add_delayed(MAP_REFRESH_FREQ, &do_refresh, ret); + run_upnpc_r(ret); return ret; } @@ -633,18 +629,18 @@ GNUNET_NAT_mini_map_start (uint16_t port, * @param line line of output, NULL at the end */ static void -process_unmap_output (void *cls, const char *line) +process_unmap_output(void *cls, const char *line) { struct GNUNET_NAT_MiniHandle *mini = cls; if (NULL == line) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, "UPnP unmap done\n"); - GNUNET_OS_command_stop (mini->unmap_cmd); - mini->unmap_cmd = NULL; - GNUNET_free (mini); - return; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "UPnP unmap done\n"); + GNUNET_OS_command_stop(mini->unmap_cmd); + mini->unmap_cmd = NULL; + GNUNET_free(mini); + return; + } /* we don't really care about the output... */ } @@ -658,54 +654,54 @@ process_unmap_output (void *cls, const char *line) * @param mini the handle */ void -GNUNET_NAT_mini_map_stop (struct GNUNET_NAT_MiniHandle *mini) +GNUNET_NAT_mini_map_stop(struct GNUNET_NAT_MiniHandle *mini) { char pstr[6]; if (NULL != mini->refresh_task) - { - GNUNET_SCHEDULER_cancel (mini->refresh_task); - mini->refresh_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(mini->refresh_task); + mini->refresh_task = NULL; + } if (NULL != mini->refresh_cmd) - { - GNUNET_OS_command_stop (mini->refresh_cmd); - mini->refresh_cmd = NULL; - } + { + GNUNET_OS_command_stop(mini->refresh_cmd); + mini->refresh_cmd = NULL; + } if (NULL != mini->map_cmd) - { - GNUNET_OS_command_stop (mini->map_cmd); - mini->map_cmd = NULL; - } + { + GNUNET_OS_command_stop(mini->map_cmd); + mini->map_cmd = NULL; + } if (GNUNET_NO == mini->did_map) - { - GNUNET_free (mini); - return; - } - mini->ac (mini->ac_cls, - GNUNET_NO, - (const struct sockaddr *) &mini->current_addr, - sizeof (mini->current_addr), - GNUNET_NAT_ERROR_SUCCESS); + { + GNUNET_free(mini); + return; + } + mini->ac(mini->ac_cls, + GNUNET_NO, + (const struct sockaddr *)&mini->current_addr, + sizeof(mini->current_addr), + GNUNET_NAT_ERROR_SUCCESS); /* Note: oddly enough, deletion uses the external port whereas * addition uses the internal port; this rarely matters since they * often are the same, but it might... */ - GNUNET_snprintf (pstr, - sizeof (pstr), - "%u", - (unsigned int) ntohs (mini->current_addr.sin_port)); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Unmapping port %u with UPnP\n", - ntohs (mini->current_addr.sin_port)); - mini->unmap_cmd = GNUNET_OS_command_run (&process_unmap_output, - mini, - UNMAP_TIMEOUT, - "upnpc", - "upnpc", - "-d", - pstr, - mini->is_tcp ? "tcp" : "udp", - NULL); + GNUNET_snprintf(pstr, + sizeof(pstr), + "%u", + (unsigned int)ntohs(mini->current_addr.sin_port)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Unmapping port %u with UPnP\n", + ntohs(mini->current_addr.sin_port)); + mini->unmap_cmd = GNUNET_OS_command_run(&process_unmap_output, + mini, + UNMAP_TIMEOUT, + "upnpc", + "upnpc", + "-d", + pstr, + mini->is_tcp ? "tcp" : "udp", + NULL); } diff --git a/src/nat/gnunet-service-nat_mini.h b/src/nat/gnunet-service-nat_mini.h index 4b84fb425..031b8e935 100644 --- a/src/nat/gnunet-service-nat_mini.h +++ b/src/nat/gnunet-service-nat_mini.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nat/gnunet-service-nat_mini.c @@ -54,8 +54,8 @@ struct GNUNET_NAT_ExternalHandle; * @return handle for cancellation (can only be used until @a cb is called), NULL on error */ struct GNUNET_NAT_ExternalHandle * -GNUNET_NAT_mini_get_external_ipv4_ (GNUNET_NAT_IPCallback cb, - void *cb_cls); +GNUNET_NAT_mini_get_external_ipv4_(GNUNET_NAT_IPCallback cb, + void *cb_cls); /** @@ -64,7 +64,7 @@ GNUNET_NAT_mini_get_external_ipv4_ (GNUNET_NAT_IPCallback cb, * @param eh operation to cancel */ void -GNUNET_NAT_mini_get_external_ipv4_cancel_ (struct GNUNET_NAT_ExternalHandle *eh); +GNUNET_NAT_mini_get_external_ipv4_cancel_(struct GNUNET_NAT_ExternalHandle *eh); /** @@ -106,10 +106,10 @@ typedef void * @return NULL on error */ struct GNUNET_NAT_MiniHandle * -GNUNET_NAT_mini_map_start (uint16_t port, - int is_tcp, - GNUNET_NAT_MiniAddressCallback ac, - void *ac_cls); +GNUNET_NAT_mini_map_start(uint16_t port, + int is_tcp, + GNUNET_NAT_MiniAddressCallback ac, + void *ac_cls); /** @@ -121,7 +121,7 @@ GNUNET_NAT_mini_map_start (uint16_t port, * @param mini the handle */ void -GNUNET_NAT_mini_map_stop (struct GNUNET_NAT_MiniHandle *mini); +GNUNET_NAT_mini_map_stop(struct GNUNET_NAT_MiniHandle *mini); #endif diff --git a/src/nat/gnunet-service-nat_stun.c b/src/nat/gnunet-service-nat_stun.c index 639289207..d8b791d0a 100644 --- a/src/nat/gnunet-service-nat_stun.c +++ b/src/nat/gnunet-service-nat_stun.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * This code provides some support for doing STUN transactions. We * receive the simplest possible packet as the STUN server and try @@ -40,15 +40,14 @@ #include "gnunet_util_lib.h" #include "nat_stun.h" -#define LOG(kind,...) GNUNET_log_from (kind, "stun", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "stun", __VA_ARGS__) /** - * Context for #stun_get_mapped(). + * Context for #stun_get_mapped(). * Used to store state across processing attributes. */ -struct StunState -{ +struct StunState { uint16_t attr; }; @@ -65,41 +64,44 @@ struct StunState * @return #GNUNET_OK if @a arg was initialized */ static int -stun_get_mapped (struct StunState *st, - const struct stun_attr *attr, - uint32_t magic, - struct sockaddr_in *arg) +stun_get_mapped(struct StunState *st, + const struct stun_attr *attr, + uint32_t magic, + struct sockaddr_in *arg) { const struct stun_addr *returned_addr; - struct sockaddr_in *sa = (struct sockaddr_in *) arg; - uint16_t type = ntohs (attr->attr); + struct sockaddr_in *sa = (struct sockaddr_in *)arg; + uint16_t type = ntohs(attr->attr); switch (type) - { - case STUN_MAPPED_ADDRESS: - if ( (st->attr == STUN_XOR_MAPPED_ADDRESS) || - (st->attr == STUN_MS_XOR_MAPPED_ADDRESS) ) - return GNUNET_NO; - magic = 0; - break; - case STUN_MS_XOR_MAPPED_ADDRESS: - if (st->attr == STUN_XOR_MAPPED_ADDRESS) + { + case STUN_MAPPED_ADDRESS: + if ((st->attr == STUN_XOR_MAPPED_ADDRESS) || + (st->attr == STUN_MS_XOR_MAPPED_ADDRESS)) + return GNUNET_NO; + magic = 0; + break; + + case STUN_MS_XOR_MAPPED_ADDRESS: + if (st->attr == STUN_XOR_MAPPED_ADDRESS) + return GNUNET_NO; + break; + + case STUN_XOR_MAPPED_ADDRESS: + break; + + default: return GNUNET_NO; - break; - case STUN_XOR_MAPPED_ADDRESS: - break; - default: - return GNUNET_NO; - } - - if (ntohs (attr->len) < sizeof (struct stun_addr)) + } + + if (ntohs(attr->len) < sizeof(struct stun_addr)) return GNUNET_NO; returned_addr = (const struct stun_addr *)(attr + 1); if (AF_INET != returned_addr->family) return GNUNET_NO; st->attr = type; sa->sin_family = AF_INET; - sa->sin_port = returned_addr->port ^ htons (ntohl(magic) >> 16); + sa->sin_port = returned_addr->port ^ htons(ntohl(magic) >> 16); sa->sin_addr.s_addr = returned_addr->addr ^ magic; return GNUNET_OK; } @@ -119,9 +121,9 @@ stun_get_mapped (struct StunState *st, * #GNUNET_NO if the packet is invalid (not a stun packet) */ int -GNUNET_NAT_stun_handle_packet_ (const void *data, - size_t len, - struct sockaddr_in *arg) +GNUNET_NAT_stun_handle_packet_(const void *data, + size_t len, + struct sockaddr_in *arg) { const struct stun_header *hdr; const struct stun_attr *attr; @@ -135,76 +137,76 @@ GNUNET_NAT_stun_handle_packet_ (const void *data, * while 'data' is advanced accordingly. */ if (len < sizeof(struct stun_header)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Packet too short to be a STUN packet\n"); - return GNUNET_NO; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Packet too short to be a STUN packet\n"); + return GNUNET_NO; + } hdr = data; /* Skip header as it is already in hdr */ len -= sizeof(struct stun_header); data += sizeof(struct stun_header); /* len as advertised in the message */ - advertised_message_size = ntohs (hdr->msglen); - message_magic_cookie = ntohl (hdr->magic); + advertised_message_size = ntohs(hdr->msglen); + message_magic_cookie = ntohl(hdr->magic); /* Compare if the cookie match */ if (STUN_MAGIC_COOKIE != message_magic_cookie) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Invalid magic cookie for STUN packet\n"); - return GNUNET_NO; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Invalid magic cookie for STUN packet\n"); + return GNUNET_NO; + } - LOG (GNUNET_ERROR_TYPE_INFO, - "STUN Packet, msg %s (%04x), length: %d\n", - stun_msg2str (ntohs (hdr->msgtype)), - ntohs (hdr->msgtype), - advertised_message_size); + LOG(GNUNET_ERROR_TYPE_INFO, + "STUN Packet, msg %s (%04x), length: %d\n", + stun_msg2str(ntohs(hdr->msgtype)), + ntohs(hdr->msgtype), + advertised_message_size); if (advertised_message_size > len) - { - LOG (GNUNET_ERROR_TYPE_INFO, - "Scrambled STUN packet length (got %d, expecting %d)\n", - advertised_message_size, - (int) len); - return GNUNET_NO; - } - len = advertised_message_size; - memset (&st, 0, sizeof(st)); - - while (len > 0) - { - if (len < sizeof (struct stun_attr)) { - LOG (GNUNET_ERROR_TYPE_INFO, - "Attribute too short (got %d, expecting %d)\n", - (int) len, - (int) sizeof (struct stun_attr)); - break; + LOG(GNUNET_ERROR_TYPE_INFO, + "Scrambled STUN packet length (got %d, expecting %d)\n", + advertised_message_size, + (int)len); + return GNUNET_NO; } - attr = (const struct stun_attr *) data; - - /* compute total attribute length */ - advertised_message_size = ntohs (attr->len) + sizeof (struct stun_attr); + len = advertised_message_size; + memset(&st, 0, sizeof(st)); - /* Check if we still have space in our buffer */ - if (advertised_message_size > len) + while (len > 0) { - LOG (GNUNET_ERROR_TYPE_INFO, - "Inconsistent attribute (length %d exceeds remaining msg len %d)\n", - advertised_message_size, - (int) len); - break; + if (len < sizeof(struct stun_attr)) + { + LOG(GNUNET_ERROR_TYPE_INFO, + "Attribute too short (got %d, expecting %d)\n", + (int)len, + (int)sizeof(struct stun_attr)); + break; + } + attr = (const struct stun_attr *)data; + + /* compute total attribute length */ + advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr); + + /* Check if we still have space in our buffer */ + if (advertised_message_size > len) + { + LOG(GNUNET_ERROR_TYPE_INFO, + "Inconsistent attribute (length %d exceeds remaining msg len %d)\n", + advertised_message_size, + (int)len); + break; + } + if (GNUNET_OK == + stun_get_mapped(&st, + attr, + hdr->magic, + arg)) + ret = GNUNET_OK; + data += advertised_message_size; + len -= advertised_message_size; } - if (GNUNET_OK == - stun_get_mapped (&st, - attr, - hdr->magic, - arg)) - ret = GNUNET_OK; - data += advertised_message_size; - len -= advertised_message_size; - } return ret; } diff --git a/src/nat/gnunet-service-nat_stun.h b/src/nat/gnunet-service-nat_stun.h index 4a61c702f..af6520fbf 100644 --- a/src/nat/gnunet-service-nat_stun.h +++ b/src/nat/gnunet-service-nat_stun.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * This code provides some support for doing STUN transactions. We * receive the simplest possible packet as the STUN server and try @@ -54,8 +54,8 @@ * #GNUNET_NO if the packet is invalid (not a stun packet) */ int -GNUNET_NAT_stun_handle_packet_ (const void *data, - size_t len, - struct sockaddr_in *arg); +GNUNET_NAT_stun_handle_packet_(const void *data, + size_t len, + struct sockaddr_in *arg); #endif diff --git a/src/nat/nat.h b/src/nat/nat.h index 86de3c2f6..62377435a 100644 --- a/src/nat/nat.h +++ b/src/nat/nat.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/nat/nat.h @@ -36,8 +36,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * Request to test NAT traversal, sent to the gnunet-nat-server * (not the service!). */ -struct GNUNET_NAT_TestMessage -{ +struct GNUNET_NAT_TestMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_NAT_TEST */ @@ -62,7 +61,6 @@ struct GNUNET_NAT_TestMessage * #GNUNET_YES for TCP, #GNUNET_NO for UDP. */ int32_t is_tcp; - }; @@ -70,8 +68,7 @@ struct GNUNET_NAT_TestMessage * Flags specifying the events this client would be * interested in being told about. */ -enum GNUNET_NAT_RegisterFlags -{ +enum GNUNET_NAT_RegisterFlags { /** * This client does not want any notifications. */ @@ -93,8 +90,7 @@ enum GNUNET_NAT_RegisterFlags /** * Message sent by a client to register with its addresses. */ -struct GNUNET_NAT_RegisterMessage -{ +struct GNUNET_NAT_RegisterMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_NAT_REGISTER */ @@ -127,15 +123,13 @@ struct GNUNET_NAT_RegisterMessage sockaddr' */ /* Followed by @e str_len section name to use for options */ - }; /** * Client telling the service to (possibly) handle a STUN message. */ -struct GNUNET_NAT_HandleStunMessage -{ +struct GNUNET_NAT_HandleStunMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_NAT_HANDLE_STUN */ @@ -160,8 +154,7 @@ struct GNUNET_NAT_HandleStunMessage /** * Client asking the service to initiate connection reversal. */ -struct GNUNET_NAT_RequestConnectionReversalMessage -{ +struct GNUNET_NAT_RequestConnectionReversalMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_NAT_REQUEST_CONNECTION_REVERSAL */ @@ -180,31 +173,27 @@ struct GNUNET_NAT_RequestConnectionReversalMessage /* followed by a `struct sockaddr` of @e local_addr_size bytes */ /* followed by a `struct sockaddr` of @e remote_addr_size bytes */ - }; /** * Service telling a client that connection reversal was requested. */ -struct GNUNET_NAT_ConnectionReversalRequestedMessage -{ +struct GNUNET_NAT_ConnectionReversalRequestedMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_NAT_CONNECTION_REVERSAL_REQUESTED */ struct GNUNET_MessageHeader header; /* followed by a `struct sockaddr_in` */ - }; /** - * Service notifying the client about changes in the set of + * Service notifying the client about changes in the set of * addresses it has. */ -struct GNUNET_NAT_AddressChangeNotificationMessage -{ +struct GNUNET_NAT_AddressChangeNotificationMessage { /** * Header with type #GNUNET_MESSAGE_TYPE_NAT_ADDRESS_CHANGE */ @@ -212,7 +201,7 @@ struct GNUNET_NAT_AddressChangeNotificationMessage /** * #GNUNET_YES to add, #GNUNET_NO to remove the address from the list. - */ + */ int32_t add_remove GNUNET_PACKED; /** @@ -220,7 +209,6 @@ struct GNUNET_NAT_AddressChangeNotificationMessage */ uint32_t addr_class GNUNET_PACKED; /* followed by a `struct sockaddr` */ - }; diff --git a/src/nat/nat_api.c b/src/nat/nat_api.c index 0dea501d3..877589d85 100644 --- a/src/nat/nat_api.c +++ b/src/nat/nat_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -35,9 +35,7 @@ /** * Entry in DLL of addresses of this peer. */ -struct AddrEntry -{ - +struct AddrEntry { /** * DLL. */ @@ -69,9 +67,7 @@ struct AddrEntry /** * Handle for active NAT registrations. */ -struct GNUNET_NAT_Handle -{ - +struct GNUNET_NAT_Handle { /** * Configuration we use. */ @@ -130,7 +126,7 @@ struct GNUNET_NAT_Handle * @param cls our `struct GNUNET_NAT_Handle *` */ static void -do_connect (void *cls); +do_connect(void *cls); /** @@ -139,29 +135,29 @@ do_connect (void *cls); * @param nh handle to reconnect */ static void -reconnect (struct GNUNET_NAT_Handle *nh) +reconnect(struct GNUNET_NAT_Handle *nh) { struct AddrEntry *ae; if (NULL != nh->mq) - { - GNUNET_MQ_destroy (nh->mq); - nh->mq = NULL; - } + { + GNUNET_MQ_destroy(nh->mq); + nh->mq = NULL; + } while (NULL != (ae = nh->ae_head)) - { - GNUNET_CONTAINER_DLL_remove (nh->ae_head, nh->ae_tail, ae); - nh->address_callback (nh->callback_cls, - &ae->app_ctx, - GNUNET_NO, - ae->ac, - (const struct sockaddr *) &ae[1], - ae->addrlen); - GNUNET_free (ae); - } - nh->reconnect_delay = GNUNET_TIME_STD_BACKOFF (nh->reconnect_delay); + { + GNUNET_CONTAINER_DLL_remove(nh->ae_head, nh->ae_tail, ae); + nh->address_callback(nh->callback_cls, + &ae->app_ctx, + GNUNET_NO, + ae->ac, + (const struct sockaddr *)&ae[1], + ae->addrlen); + GNUNET_free(ae); + } + nh->reconnect_delay = GNUNET_TIME_STD_BACKOFF(nh->reconnect_delay); nh->reconnect_task = - GNUNET_SCHEDULER_add_delayed (nh->reconnect_delay, &do_connect, nh); + GNUNET_SCHEDULER_add_delayed(nh->reconnect_delay, &do_connect, nh); } @@ -173,15 +169,15 @@ reconnect (struct GNUNET_NAT_Handle *nh) * @return #GNUNET_OK if @a crm is well-formed */ static int -check_connection_reversal_request ( +check_connection_reversal_request( void *cls, const struct GNUNET_NAT_ConnectionReversalRequestedMessage *crm) { - if (ntohs (crm->header.size) != sizeof (*crm) + sizeof (struct sockaddr_in)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + if (ntohs(crm->header.size) != sizeof(*crm) + sizeof(struct sockaddr_in)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -193,15 +189,15 @@ check_connection_reversal_request ( * @param crm the message */ static void -handle_connection_reversal_request ( +handle_connection_reversal_request( void *cls, const struct GNUNET_NAT_ConnectionReversalRequestedMessage *crm) { struct GNUNET_NAT_Handle *nh = cls; - nh->reversal_callback (nh->callback_cls, - (const struct sockaddr *) &crm[1], - sizeof (struct sockaddr_in)); + nh->reversal_callback(nh->callback_cls, + (const struct sockaddr *)&crm[1], + sizeof(struct sockaddr_in)); } @@ -213,36 +209,38 @@ handle_connection_reversal_request ( * @return #GNUNET_OK if @a crm is well-formed */ static int -check_address_change_notification ( +check_address_change_notification( void *cls, const struct GNUNET_NAT_AddressChangeNotificationMessage *acn) { - size_t alen = ntohs (acn->header.size) - sizeof (*acn); + size_t alen = ntohs(acn->header.size) - sizeof(*acn); switch (alen) - { - case sizeof (struct sockaddr_in): { - const struct sockaddr_in *s4 = (const struct sockaddr_in *) &acn[1]; - if (AF_INET != s4->sin_family) { - GNUNET_break (0); - return GNUNET_SYSERR; + case sizeof(struct sockaddr_in): { + const struct sockaddr_in *s4 = (const struct sockaddr_in *)&acn[1]; + if (AF_INET != s4->sin_family) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } } - } - break; - case sizeof (struct sockaddr_in6): { - const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *) &acn[1]; - if (AF_INET6 != s6->sin6_family) - { - GNUNET_break (0); + break; + + case sizeof(struct sockaddr_in6): { + const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *)&acn[1]; + if (AF_INET6 != s6->sin6_family) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + } + break; + + default: + GNUNET_break(0); return GNUNET_SYSERR; } - } - break; - default: - GNUNET_break (0); - return GNUNET_SYSERR; - } return GNUNET_OK; } @@ -254,53 +252,53 @@ check_address_change_notification ( * @param acn the message */ static void -handle_address_change_notification ( +handle_address_change_notification( void *cls, const struct GNUNET_NAT_AddressChangeNotificationMessage *acn) { struct GNUNET_NAT_Handle *nh = cls; - size_t alen = ntohs (acn->header.size) - sizeof (*acn); - const struct sockaddr *sa = (const struct sockaddr *) &acn[1]; + size_t alen = ntohs(acn->header.size) - sizeof(*acn); + const struct sockaddr *sa = (const struct sockaddr *)&acn[1]; enum GNUNET_NAT_AddressClass ac; struct AddrEntry *ae; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received address change notification\n"); - ac = (enum GNUNET_NAT_AddressClass) ntohl (acn->addr_class); - if (GNUNET_YES == ntohl (acn->add_remove)) - { - ae = GNUNET_malloc (sizeof (*ae) + alen); - ae->ac = ac; - ae->addrlen = alen; - GNUNET_memcpy (&ae[1], sa, alen); - GNUNET_CONTAINER_DLL_insert (nh->ae_head, nh->ae_tail, ae); - nh->address_callback (nh->callback_cls, - &ae->app_ctx, - ntohl (acn->add_remove), - ac, - sa, - alen); - } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received address change notification\n"); + ac = (enum GNUNET_NAT_AddressClass)ntohl(acn->addr_class); + if (GNUNET_YES == ntohl(acn->add_remove)) + { + ae = GNUNET_malloc(sizeof(*ae) + alen); + ae->ac = ac; + ae->addrlen = alen; + GNUNET_memcpy(&ae[1], sa, alen); + GNUNET_CONTAINER_DLL_insert(nh->ae_head, nh->ae_tail, ae); + nh->address_callback(nh->callback_cls, + &ae->app_ctx, + ntohl(acn->add_remove), + ac, + sa, + alen); + } else - { - for (ae = nh->ae_head; NULL != ae; ae = ae->next) - if ((ae->addrlen == alen) && (0 == memcmp (&ae[1], sa, alen))) - break; - if (NULL == ae) { - GNUNET_break (0); - reconnect (nh); - return; + for (ae = nh->ae_head; NULL != ae; ae = ae->next) + if ((ae->addrlen == alen) && (0 == memcmp(&ae[1], sa, alen))) + break; + if (NULL == ae) + { + GNUNET_break(0); + reconnect(nh); + return; + } + GNUNET_CONTAINER_DLL_remove(nh->ae_head, nh->ae_tail, ae); + nh->address_callback(nh->callback_cls, + &ae->app_ctx, + ntohl(acn->add_remove), + ac, + sa, + alen); + GNUNET_free(ae); } - GNUNET_CONTAINER_DLL_remove (nh->ae_head, nh->ae_tail, ae); - nh->address_callback (nh->callback_cls, - &ae->app_ctx, - ntohl (acn->add_remove), - ac, - sa, - alen); - GNUNET_free (ae); - } } @@ -311,11 +309,11 @@ handle_address_change_notification ( * @param error details about the error */ static void -mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_NAT_Handle *nh = cls; - reconnect (nh); + reconnect(nh); } @@ -325,32 +323,32 @@ mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @param cls our `struct GNUNET_NAT_Handle *` */ static void -do_connect (void *cls) +do_connect(void *cls) { struct GNUNET_NAT_Handle *nh = cls; struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_var_size (connection_reversal_request, - GNUNET_MESSAGE_TYPE_NAT_CONNECTION_REVERSAL_REQUESTED, - struct - GNUNET_NAT_ConnectionReversalRequestedMessage, - nh), - GNUNET_MQ_hd_var_size (address_change_notification, - GNUNET_MESSAGE_TYPE_NAT_ADDRESS_CHANGE, - struct GNUNET_NAT_AddressChangeNotificationMessage, - nh), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_var_size(connection_reversal_request, + GNUNET_MESSAGE_TYPE_NAT_CONNECTION_REVERSAL_REQUESTED, + struct + GNUNET_NAT_ConnectionReversalRequestedMessage, + nh), + GNUNET_MQ_hd_var_size(address_change_notification, + GNUNET_MESSAGE_TYPE_NAT_ADDRESS_CHANGE, + struct GNUNET_NAT_AddressChangeNotificationMessage, + nh), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *env; nh->reconnect_task = NULL; nh->mq = - GNUNET_CLIENT_connect (nh->cfg, "nat", handlers, &mq_error_handler, nh); + GNUNET_CLIENT_connect(nh->cfg, "nat", handlers, &mq_error_handler, nh); if (NULL == nh->mq) - { - reconnect (nh); - return; - } - env = GNUNET_MQ_msg_copy (nh->reg); - GNUNET_MQ_send (nh->mq, env); + { + reconnect(nh); + return; + } + env = GNUNET_MQ_msg_copy(nh->reg); + GNUNET_MQ_send(nh->mq, env); } @@ -375,15 +373,15 @@ do_connect (void *cls) * @return NULL on error, otherwise handle that can be used to unregister */ struct GNUNET_NAT_Handle * -GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *config_section, - uint8_t proto, - unsigned int num_addrs, - const struct sockaddr **addrs, - const socklen_t *addrlens, - GNUNET_NAT_AddressCallback address_callback, - GNUNET_NAT_ReversalCallback reversal_callback, - void *callback_cls) +GNUNET_NAT_register(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *config_section, + uint8_t proto, + unsigned int num_addrs, + const struct sockaddr **addrs, + const socklen_t *addrlens, + GNUNET_NAT_AddressCallback address_callback, + GNUNET_NAT_ReversalCallback reversal_callback, + void *callback_cls) { struct GNUNET_NAT_Handle *nh; struct GNUNET_NAT_RegisterMessage *rm; @@ -394,73 +392,75 @@ GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg, len = 0; for (unsigned int i = 0; i < num_addrs; i++) len += addrlens[i]; - str_len = strlen (config_section) + 1; + str_len = strlen(config_section) + 1; len += str_len; - if ((len > GNUNET_MAX_MESSAGE_SIZE - sizeof (*rm)) || + if ((len > GNUNET_MAX_MESSAGE_SIZE - sizeof(*rm)) || (num_addrs > UINT16_MAX)) - { - GNUNET_break (0); - return NULL; - } - rm = GNUNET_malloc (sizeof (*rm) + len); - rm->header.size = htons (sizeof (*rm) + len); - rm->header.type = htons (GNUNET_MESSAGE_TYPE_NAT_REGISTER); + { + GNUNET_break(0); + return NULL; + } + rm = GNUNET_malloc(sizeof(*rm) + len); + rm->header.size = htons(sizeof(*rm) + len); + rm->header.type = htons(GNUNET_MESSAGE_TYPE_NAT_REGISTER); rm->flags = GNUNET_NAT_RF_NONE; if (NULL != address_callback) rm->flags |= GNUNET_NAT_RF_ADDRESSES; if (NULL != reversal_callback) rm->flags |= GNUNET_NAT_RF_REVERSAL; rm->proto = proto; - rm->str_len = htons (str_len); - rm->num_addrs = htons ((uint16_t) num_addrs); - off = (char *) &rm[1]; + rm->str_len = htons(str_len); + rm->num_addrs = htons((uint16_t)num_addrs); + off = (char *)&rm[1]; for (unsigned int i = 0; i < num_addrs; i++) - { - switch (addrs[i]->sa_family) { - case AF_INET: - if (sizeof (struct sockaddr_in) != addrlens[i]) - { - GNUNET_break (0); - GNUNET_free (rm); - return NULL; - } - break; - case AF_INET6: - if (sizeof (struct sockaddr_in6) != addrlens[i]) - { - GNUNET_break (0); - GNUNET_free (rm); - return NULL; - } - break; + switch (addrs[i]->sa_family) + { + case AF_INET: + if (sizeof(struct sockaddr_in) != addrlens[i]) + { + GNUNET_break(0); + GNUNET_free(rm); + return NULL; + } + break; + + case AF_INET6: + if (sizeof(struct sockaddr_in6) != addrlens[i]) + { + GNUNET_break(0); + GNUNET_free(rm); + return NULL; + } + break; + #if AF_UNIX - case AF_UNIX: - if (sizeof (struct sockaddr_un) != addrlens[i]) - { - GNUNET_break (0); - GNUNET_free (rm); - return NULL; - } - break; + case AF_UNIX: + if (sizeof(struct sockaddr_un) != addrlens[i]) + { + GNUNET_break(0); + GNUNET_free(rm); + return NULL; + } + break; #endif - default: - GNUNET_break (0); - GNUNET_free (rm); - return NULL; + default: + GNUNET_break(0); + GNUNET_free(rm); + return NULL; + } + GNUNET_memcpy(off, addrs[i], addrlens[i]); + off += addrlens[i]; } - GNUNET_memcpy (off, addrs[i], addrlens[i]); - off += addrlens[i]; - } - GNUNET_memcpy (off, config_section, str_len); + GNUNET_memcpy(off, config_section, str_len); - nh = GNUNET_new (struct GNUNET_NAT_Handle); + nh = GNUNET_new(struct GNUNET_NAT_Handle); nh->reg = &rm->header; nh->cfg = cfg; nh->address_callback = address_callback; nh->reversal_callback = reversal_callback; nh->callback_cls = callback_cls; - do_connect (nh); + do_connect(nh); return nh; } @@ -474,7 +474,7 @@ GNUNET_NAT_register (const struct GNUNET_CONFIGURATION_Handle *cfg, * #GNUNET_NO if the packet is invalid (not a stun packet) */ static int -test_stun_packet (const void *data, size_t len) +test_stun_packet(const void *data, size_t len) { const struct stun_header *hdr; const struct stun_attr *attr; @@ -485,71 +485,71 @@ test_stun_packet (const void *data, size_t len) * initial checks it becomes the size of unprocessed options, * while 'data' is advanced accordingly. */ - if (len < sizeof (struct stun_header)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "STUN packet too short (only %d, wanting at least %d)\n", - (int) len, - (int) sizeof (struct stun_header)); - return GNUNET_NO; - } - hdr = (const struct stun_header *) data; + if (len < sizeof(struct stun_header)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "STUN packet too short (only %d, wanting at least %d)\n", + (int)len, + (int)sizeof(struct stun_header)); + return GNUNET_NO; + } + hdr = (const struct stun_header *)data; /* Skip header as it is already in hdr */ - len -= sizeof (struct stun_header); - data += sizeof (struct stun_header); + len -= sizeof(struct stun_header); + data += sizeof(struct stun_header); /* len as advertised in the message */ - advertised_message_size = ntohs (hdr->msglen); + advertised_message_size = ntohs(hdr->msglen); - message_magic_cookie = ntohl (hdr->magic); + message_magic_cookie = ntohl(hdr->magic); /* Compare if the cookie match */ if (STUN_MAGIC_COOKIE != message_magic_cookie) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Invalid magic cookie for STUN\n"); - return GNUNET_NO; - } - - if (advertised_message_size > len) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Scrambled STUN packet length (got %d, expecting %d)\n", - advertised_message_size, - (int) len); - return GNUNET_NO; - } - len = advertised_message_size; - while (len > 0) - { - if (len < sizeof (struct stun_attr)) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Attribute too short in STUN packet (got %d, expecting %d)\n", - (int) len, - (int) sizeof (struct stun_attr)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Invalid magic cookie for STUN\n"); return GNUNET_NO; } - attr = (const struct stun_attr *) data; - - /* compute total attribute length */ - advertised_message_size = ntohs (attr->len) + sizeof (struct stun_attr); - /* Check if we still have space in our buffer */ - if (advertised_message_size > len) + if (advertised_message_size > len) { - GNUNET_log ( - GNUNET_ERROR_TYPE_DEBUG, - "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", - advertised_message_size, - (int) len); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Scrambled STUN packet length (got %d, expecting %d)\n", + advertised_message_size, + (int)len); return GNUNET_NO; } - data += advertised_message_size; - len -= advertised_message_size; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "STUN Packet, msg %04x, length: %d\n", - ntohs (hdr->msgtype), - advertised_message_size); + len = advertised_message_size; + while (len > 0) + { + if (len < sizeof(struct stun_attr)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Attribute too short in STUN packet (got %d, expecting %d)\n", + (int)len, + (int)sizeof(struct stun_attr)); + return GNUNET_NO; + } + attr = (const struct stun_attr *)data; + + /* compute total attribute length */ + advertised_message_size = ntohs(attr->len) + sizeof(struct stun_attr); + + /* Check if we still have space in our buffer */ + if (advertised_message_size > len) + { + GNUNET_log( + GNUNET_ERROR_TYPE_DEBUG, + "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", + advertised_message_size, + (int)len); + return GNUNET_NO; + } + data += advertised_message_size; + len -= advertised_message_size; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "STUN Packet, msg %04x, length: %d\n", + ntohs(hdr->msgtype), + advertised_message_size); return GNUNET_OK; } @@ -578,30 +578,30 @@ test_stun_packet (const void *data, size_t len) * #GNUNET_SYSERR on internal error handling the packet */ int -GNUNET_NAT_stun_handle_packet (struct GNUNET_NAT_Handle *nh, - const struct sockaddr *sender_addr, - size_t sender_addr_len, - const void *data, - size_t data_size) +GNUNET_NAT_stun_handle_packet(struct GNUNET_NAT_Handle *nh, + const struct sockaddr *sender_addr, + size_t sender_addr_len, + const void *data, + size_t data_size) { struct GNUNET_MQ_Envelope *env; struct GNUNET_NAT_HandleStunMessage *hsn; char *buf; - if (GNUNET_YES != test_stun_packet (data, data_size)) + if (GNUNET_YES != test_stun_packet(data, data_size)) return GNUNET_NO; if (NULL == nh->mq) return GNUNET_SYSERR; - env = GNUNET_MQ_msg_extra (hsn, - data_size + sender_addr_len, - GNUNET_MESSAGE_TYPE_NAT_HANDLE_STUN); - hsn->sender_addr_size = htons ((uint16_t) sender_addr_len); - hsn->payload_size = htons ((uint16_t) data_size); - buf = (char *) &hsn[1]; - GNUNET_memcpy (buf, sender_addr, sender_addr_len); + env = GNUNET_MQ_msg_extra(hsn, + data_size + sender_addr_len, + GNUNET_MESSAGE_TYPE_NAT_HANDLE_STUN); + hsn->sender_addr_size = htons((uint16_t)sender_addr_len); + hsn->payload_size = htons((uint16_t)data_size); + buf = (char *)&hsn[1]; + GNUNET_memcpy(buf, sender_addr, sender_addr_len); buf += sender_addr_len; - GNUNET_memcpy (buf, data, data_size); - GNUNET_MQ_send (nh->mq, env); + GNUNET_memcpy(buf, data, data_size); + GNUNET_MQ_send(nh->mq, env); return GNUNET_OK; } @@ -620,20 +620,20 @@ GNUNET_NAT_stun_handle_packet (struct GNUNET_NAT_Handle *nh, * #GNUNET_SYSERR if the address is malformed */ int -GNUNET_NAT_test_address (struct GNUNET_NAT_Handle *nh, - const void *addr, - socklen_t addrlen) +GNUNET_NAT_test_address(struct GNUNET_NAT_Handle *nh, + const void *addr, + socklen_t addrlen) { struct AddrEntry *ae; - if ((addrlen != sizeof (struct sockaddr_in)) && - (addrlen != sizeof (struct sockaddr_in6))) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + if ((addrlen != sizeof(struct sockaddr_in)) && + (addrlen != sizeof(struct sockaddr_in6))) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } for (ae = nh->ae_head; NULL != ae; ae = ae->next) - if ((addrlen == ae->addrlen) && (0 == memcmp (addr, &ae[1], addrlen))) + if ((addrlen == ae->addrlen) && (0 == memcmp(addr, &ae[1], addrlen))) return GNUNET_YES; return GNUNET_NO; } @@ -652,9 +652,9 @@ GNUNET_NAT_test_address (struct GNUNET_NAT_Handle *nh, * #GNUNET_OK otherwise (presumably in progress) */ int -GNUNET_NAT_request_reversal (struct GNUNET_NAT_Handle *nh, - const struct sockaddr_in *local_sa, - const struct sockaddr_in *remote_sa) +GNUNET_NAT_request_reversal(struct GNUNET_NAT_Handle *nh, + const struct sockaddr_in *local_sa, + const struct sockaddr_in *remote_sa) { struct GNUNET_MQ_Envelope *env; struct GNUNET_NAT_RequestConnectionReversalMessage *req; @@ -662,19 +662,19 @@ GNUNET_NAT_request_reversal (struct GNUNET_NAT_Handle *nh, if (NULL == nh->mq) return GNUNET_SYSERR; - GNUNET_break (AF_INET == local_sa->sin_family); - GNUNET_break (AF_INET == remote_sa->sin_family); + GNUNET_break(AF_INET == local_sa->sin_family); + GNUNET_break(AF_INET == remote_sa->sin_family); env = - GNUNET_MQ_msg_extra (req, - 2 * sizeof (struct sockaddr_in), - GNUNET_MESSAGE_TYPE_NAT_REQUEST_CONNECTION_REVERSAL); - req->local_addr_size = htons (sizeof (struct sockaddr_in)); - req->remote_addr_size = htons (sizeof (struct sockaddr_in)); - buf = (char *) &req[1]; - GNUNET_memcpy (buf, local_sa, sizeof (struct sockaddr_in)); - buf += sizeof (struct sockaddr_in); - GNUNET_memcpy (buf, remote_sa, sizeof (struct sockaddr_in)); - GNUNET_MQ_send (nh->mq, env); + GNUNET_MQ_msg_extra(req, + 2 * sizeof(struct sockaddr_in), + GNUNET_MESSAGE_TYPE_NAT_REQUEST_CONNECTION_REVERSAL); + req->local_addr_size = htons(sizeof(struct sockaddr_in)); + req->remote_addr_size = htons(sizeof(struct sockaddr_in)); + buf = (char *)&req[1]; + GNUNET_memcpy(buf, local_sa, sizeof(struct sockaddr_in)); + buf += sizeof(struct sockaddr_in); + GNUNET_memcpy(buf, remote_sa, sizeof(struct sockaddr_in)); + GNUNET_MQ_send(nh->mq, env); return GNUNET_OK; } @@ -687,20 +687,20 @@ GNUNET_NAT_request_reversal (struct GNUNET_NAT_Handle *nh, * @param nh the handle to stop */ void -GNUNET_NAT_unregister (struct GNUNET_NAT_Handle *nh) +GNUNET_NAT_unregister(struct GNUNET_NAT_Handle *nh) { if (NULL != nh->mq) - { - GNUNET_MQ_destroy (nh->mq); - nh->mq = NULL; - } + { + GNUNET_MQ_destroy(nh->mq); + nh->mq = NULL; + } if (NULL != nh->reconnect_task) - { - GNUNET_SCHEDULER_cancel (nh->reconnect_task); - nh->reconnect_task = NULL; - } - GNUNET_free (nh->reg); - GNUNET_free (nh); + { + GNUNET_SCHEDULER_cancel(nh->reconnect_task); + nh->reconnect_task = NULL; + } + GNUNET_free(nh->reg); + GNUNET_free(nh); } diff --git a/src/nat/nat_api_stun.c b/src/nat/nat_api_stun.c index a0931a06f..0f8694867 100644 --- a/src/nat/nat_api_stun.c +++ b/src/nat/nat_api_stun.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * This code provides some support for doing STUN transactions. * We send simplest possible packet ia REQUEST with BIND to a STUN server. @@ -43,9 +43,9 @@ #include "nat_stun.h" -#define LOG(kind,...) GNUNET_log_from (kind, "stun", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "stun", __VA_ARGS__) -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15) /** @@ -53,9 +53,7 @@ * the request prior to the timeout or successful execution. Also * used to track our internal state for the request. */ -struct GNUNET_NAT_STUN_Handle -{ - +struct GNUNET_NAT_STUN_Handle { /** * Handle to a pending DNS lookup request. */ @@ -90,7 +88,6 @@ struct GNUNET_NAT_STUN_Handle * STUN port */ uint16_t stun_port; - }; @@ -102,11 +99,11 @@ struct GNUNET_NAT_STUN_Handle * @return message in a STUN compatible format */ static int -encode_message (enum StunClasses msg_class, - enum StunMethods method) +encode_message(enum StunClasses msg_class, + enum StunMethods method) { return ((msg_class & 1) << 4) | ((msg_class & 2) << 7) | - (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2); + (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2); } @@ -116,12 +113,12 @@ encode_message (enum StunClasses msg_class, * @param req, stun header to be filled */ static void -generate_request_id (struct stun_header *req) +generate_request_id(struct stun_header *req) { req->magic = htonl(STUN_MAGIC_COOKIE); for (unsigned int x = 0; x < 3; x++) - req->id.id[x] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, - UINT32_MAX); + req->id.id[x] = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, + UINT32_MAX); } @@ -133,67 +130,67 @@ generate_request_id (struct stun_header *req) * @param addrlen length of @a addr */ static void -stun_dns_callback (void *cls, - const struct sockaddr *addr, - socklen_t addrlen) +stun_dns_callback(void *cls, + const struct sockaddr *addr, + socklen_t addrlen) { struct GNUNET_NAT_STUN_Handle *rh = cls; struct stun_header req; struct sockaddr_in server; if (NULL == addr) - { - rh->dns_active = NULL; - if (GNUNET_NO == rh->dns_success) - { - LOG (GNUNET_ERROR_TYPE_INFO, - "Error resolving host %s\n", - rh->stun_server); - rh->cb (rh->cb_cls, - GNUNET_NAT_ERROR_NOT_ONLINE); - } - else if (GNUNET_SYSERR == rh->dns_success) { - rh->cb (rh->cb_cls, - GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR); + rh->dns_active = NULL; + if (GNUNET_NO == rh->dns_success) + { + LOG(GNUNET_ERROR_TYPE_INFO, + "Error resolving host %s\n", + rh->stun_server); + rh->cb(rh->cb_cls, + GNUNET_NAT_ERROR_NOT_ONLINE); + } + else if (GNUNET_SYSERR == rh->dns_success) + { + rh->cb(rh->cb_cls, + GNUNET_NAT_ERROR_INTERNAL_NETWORK_ERROR); + } + else + { + rh->cb(rh->cb_cls, + GNUNET_NAT_ERROR_SUCCESS); + } + GNUNET_NAT_stun_make_request_cancel(rh); + return; } - else - { - rh->cb (rh->cb_cls, - GNUNET_NAT_ERROR_SUCCESS); - } - GNUNET_NAT_stun_make_request_cancel (rh); - return; - } rh->dns_success = GNUNET_YES; - memset (&server, 0, sizeof(server)); + memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_addr = ((struct sockaddr_in *)addr)->sin_addr; - server.sin_port = htons (rh->stun_port); + server.sin_port = htons(rh->stun_port); #if HAVE_SOCKADDR_IN_SIN_LEN - server.sin_len = (u_char) sizeof (struct sockaddr_in); + server.sin_len = (u_char)sizeof(struct sockaddr_in); #endif /* Craft the simplest possible STUN packet. A request binding */ - generate_request_id (&req); - req.msglen = htons (0); - req.msgtype = htons (encode_message (STUN_REQUEST, - STUN_BINDING)); + generate_request_id(&req); + req.msglen = htons(0); + req.msgtype = htons(encode_message(STUN_REQUEST, + STUN_BINDING)); /* Send the packet */ if (-1 == - GNUNET_NETWORK_socket_sendto (rh->sock, - &req, - sizeof (req), - (const struct sockaddr *) &server, - sizeof (server))) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "sendto"); - rh->dns_success = GNUNET_SYSERR; - return; - } + GNUNET_NETWORK_socket_sendto(rh->sock, + &req, + sizeof(req), + (const struct sockaddr *)&server, + sizeof(server))) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "sendto"); + rh->dns_success = GNUNET_SYSERR; + return; + } } @@ -209,31 +206,31 @@ stun_dns_callback (void *cls, * @return NULL on error */ struct GNUNET_NAT_STUN_Handle * -GNUNET_NAT_stun_make_request (const char *server, - uint16_t port, - struct GNUNET_NETWORK_Handle *sock, - GNUNET_NAT_TestCallback cb, - void *cb_cls) +GNUNET_NAT_stun_make_request(const char *server, + uint16_t port, + struct GNUNET_NETWORK_Handle *sock, + GNUNET_NAT_TestCallback cb, + void *cb_cls) { struct GNUNET_NAT_STUN_Handle *rh; - rh = GNUNET_new (struct GNUNET_NAT_STUN_Handle); + rh = GNUNET_new(struct GNUNET_NAT_STUN_Handle); rh->sock = sock; rh->cb = cb; rh->cb_cls = cb_cls; - rh->stun_server = GNUNET_strdup (server); + rh->stun_server = GNUNET_strdup(server); rh->stun_port = port; rh->dns_success = GNUNET_NO; - rh->dns_active = GNUNET_RESOLVER_ip_get (rh->stun_server, - AF_INET, - TIMEOUT, - &stun_dns_callback, - rh); + rh->dns_active = GNUNET_RESOLVER_ip_get(rh->stun_server, + AF_INET, + TIMEOUT, + &stun_dns_callback, + rh); if (NULL == rh->dns_active) - { - GNUNET_NAT_stun_make_request_cancel (rh); - return NULL; - } + { + GNUNET_NAT_stun_make_request_cancel(rh); + return NULL; + } return rh; } @@ -245,15 +242,15 @@ GNUNET_NAT_stun_make_request (const char *server, * @param rh request to cancel */ void -GNUNET_NAT_stun_make_request_cancel (struct GNUNET_NAT_STUN_Handle *rh) +GNUNET_NAT_stun_make_request_cancel(struct GNUNET_NAT_STUN_Handle *rh) { if (NULL != rh->dns_active) - { - GNUNET_RESOLVER_request_cancel (rh->dns_active); - rh->dns_active = NULL; - } - GNUNET_free (rh->stun_server); - GNUNET_free (rh); + { + GNUNET_RESOLVER_request_cancel(rh->dns_active); + rh->dns_active = NULL; + } + GNUNET_free(rh->stun_server); + GNUNET_free(rh); } diff --git a/src/nat/nat_stun.h b/src/nat/nat_stun.h index fb5262dfa..85b177271 100644 --- a/src/nat/nat_stun.h +++ b/src/nat/nat_stun.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * Message types for STUN server resolution * @@ -28,18 +28,17 @@ */ -#define STUN_IGNORE (0) -#define STUN_ACCEPT (1) +#define STUN_IGNORE (0) +#define STUN_ACCEPT (1) -#define STUN_MAGIC_COOKIE 0x2112A442 +#define STUN_MAGIC_COOKIE 0x2112A442 typedef struct { uint32_t id[3]; } GNUNET_PACKED stun_trans_id; -struct stun_header -{ +struct stun_header { uint16_t msgtype; uint16_t msglen; uint32_t magic; @@ -47,8 +46,7 @@ struct stun_header } GNUNET_PACKED; -struct stun_attr -{ +struct stun_attr { uint16_t attr; uint16_t len; } GNUNET_PACKED; @@ -57,14 +55,13 @@ struct stun_attr /** * The format normally used for addresses carried by STUN messages. */ -struct stun_addr -{ - uint8_t unused; +struct stun_addr { + uint8_t unused; /** * Address family, we expect AF_INET. */ - uint8_t family; + uint8_t family; /** * Port number. @@ -74,7 +71,7 @@ struct stun_addr /** * IPv4 address. Should this be "struct in_addr"? */ - uint32_t addr; + uint32_t addr; } GNUNET_PACKED; @@ -136,10 +133,10 @@ enum StunAttributes { * @return the converted StunClass */ static enum StunClasses -decode_class (int msg) +decode_class(int msg) { /* Sorry for the magic, but this maps the class according to rfc5245 */ - return (enum StunClasses) ((msg & 0x0010) >> 4) | ((msg & 0x0100) >> 7); + return (enum StunClasses)((msg & 0x0010) >> 4) | ((msg & 0x0100) >> 7); } @@ -150,9 +147,9 @@ decode_class (int msg) * @return the converted StunMethod */ static enum StunMethods -decode_method (int msg) +decode_method(int msg) { - return (enum StunMethods) (msg & 0x000f) | ((msg & 0x00e0) >> 1) | ((msg & 0x3e00) >> 2); + return (enum StunMethods)(msg & 0x000f) | ((msg & 0x00e0) >> 1) | ((msg & 0x3e00) >> 2); } @@ -164,7 +161,7 @@ decode_method (int msg) */ GNUNET_UNUSED static const char * -stun_msg2str (int msg) +stun_msg2str(int msg) { static const struct { enum StunClasses value; @@ -189,25 +186,25 @@ stun_msg2str (int msg) enum StunClasses cvalue; enum StunMethods mvalue; - cvalue = decode_class (msg); + cvalue = decode_class(msg); for (unsigned int i = 0; classes[i].name; i++) if (classes[i].value == cvalue) - { - msg_class = classes[i].name; - break; - } - mvalue = decode_method (msg); + { + msg_class = classes[i].name; + break; + } + mvalue = decode_method(msg); for (unsigned int i = 0; methods[i].name; i++) if (methods[i].value == mvalue) - { - method = methods[i].name; - break; - } - GNUNET_snprintf (result, - sizeof(result), - "%s %s", - method ? : "Unknown Method", - msg_class ? : "Unknown Class Message"); + { + method = methods[i].name; + break; + } + GNUNET_snprintf(result, + sizeof(result), + "%s %s", + method ? : "Unknown Method", + msg_class ? : "Unknown Class Message"); return result; } @@ -220,7 +217,7 @@ stun_msg2str (int msg) */ GNUNET_UNUSED static const char * -stun_attr2str (enum StunAttributes msg) +stun_attr2str(enum StunAttributes msg) { static const struct { enum StunAttributes value; diff --git a/src/nat/test_nat.c b/src/nat/test_nat.c index 80d7cf792..5758f63b9 100644 --- a/src/nat/test_nat.c +++ b/src/nat/test_nat.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * Testcase for port redirection and public IP address retrieval. @@ -43,7 +43,7 @@ /** * Time to wait before stopping NAT, in seconds */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) /** @@ -51,15 +51,15 @@ * believes to be valid for the transport. */ static void -addr_callback (void *cls, int add_remove, const struct sockaddr *addr, - socklen_t addrlen) +addr_callback(void *cls, int add_remove, const struct sockaddr *addr, + socklen_t addrlen) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Address changed: %s `%s' (%u bytes)\n", - add_remove == GNUNET_YES ? "added" : "removed", - GNUNET_a2s (addr, - addrlen), - (unsigned int) addrlen); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Address changed: %s `%s' (%u bytes)\n", + add_remove == GNUNET_YES ? "added" : "removed", + GNUNET_a2s(addr, + addrlen), + (unsigned int)addrlen); } @@ -67,18 +67,17 @@ addr_callback (void *cls, int add_remove, const struct sockaddr *addr, * Function that terminates the test. */ static void -stop (void *cls) +stop(void *cls) { struct GNUNET_NAT_Handle *nat = cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Stopping NAT and quitting...\n"); - GNUNET_NAT_unregister (nat); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Stopping NAT and quitting...\n"); + GNUNET_NAT_unregister(nat); } -struct addr_cls -{ +struct addr_cls { struct sockaddr *addr; socklen_t addrlen; }; @@ -96,21 +95,21 @@ struct addr_cls * @return #GNUNET_OK to continue iterating */ static int -process_if (void *cls, - const char *name, - int isDefault, - const struct sockaddr *addr, - const struct sockaddr *broadcast_addr, - const struct sockaddr *netmask, - socklen_t addrlen) +process_if(void *cls, + const char *name, + int isDefault, + const struct sockaddr *addr, + const struct sockaddr *broadcast_addr, + const struct sockaddr *netmask, + socklen_t addrlen) { struct addr_cls *data = cls; if (addr == NULL) return GNUNET_OK; - GNUNET_free_non_null (data->addr); - data->addr = GNUNET_malloc (addrlen); - GNUNET_memcpy (data->addr, addr, addrlen); + GNUNET_free_non_null(data->addr); + data->addr = GNUNET_malloc(addrlen); + GNUNET_memcpy(data->addr, addr, addrlen); data->addrlen = addrlen; if (isDefault) return GNUNET_SYSERR; @@ -122,44 +121,44 @@ process_if (void *cls, * Main function run with scheduler. */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_NAT_Handle *nat; struct addr_cls data; struct sockaddr *addr; data.addr = NULL; - GNUNET_OS_network_interfaces_list (process_if, &data); + GNUNET_OS_network_interfaces_list(process_if, &data); if (NULL == data.addr) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not find a valid interface address!\n"); - exit (77); /* marks test as skipped */ - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not find a valid interface address!\n"); + exit(77); /* marks test as skipped */ + } addr = data.addr; - GNUNET_assert (addr->sa_family == AF_INET || addr->sa_family == AF_INET6); + GNUNET_assert(addr->sa_family == AF_INET || addr->sa_family == AF_INET6); if (addr->sa_family == AF_INET) - ((struct sockaddr_in *) addr)->sin_port = htons (2086); + ((struct sockaddr_in *)addr)->sin_port = htons(2086); else - ((struct sockaddr_in6 *) addr)->sin6_port = htons (2086); + ((struct sockaddr_in6 *)addr)->sin6_port = htons(2086); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Requesting NAT redirection from address %s...\n", - GNUNET_a2s (addr, data.addrlen)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Requesting NAT redirection from address %s...\n", + GNUNET_a2s(addr, data.addrlen)); - nat = GNUNET_NAT_register (cfg, GNUNET_YES /* tcp */ , - 2086, 1, (const struct sockaddr **) &addr, - &data.addrlen, &addr_callback, NULL, NULL, NULL); - GNUNET_free (addr); - GNUNET_SCHEDULER_add_delayed (TIMEOUT, &stop, nat); + nat = GNUNET_NAT_register(cfg, GNUNET_YES /* tcp */, + 2086, 1, (const struct sockaddr **)&addr, + &data.addrlen, &addr_callback, NULL, NULL, NULL); + GNUNET_free(addr); + GNUNET_SCHEDULER_add_delayed(TIMEOUT, &stop, nat); } int -main (int argc, char *const argv[]) +main(int argc, char *const argv[]) { struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END @@ -171,19 +170,20 @@ main (int argc, char *const argv[]) "test_nat_data.conf", NULL }; - GNUNET_log_setup ("test-nat", - "WARNING", - NULL); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Testing NAT library, timeout set to %s\n", - GNUNET_STRINGS_relative_time_to_string (TIMEOUT, - GNUNET_YES)); - GNUNET_PROGRAM_run (3, - argv_prog, - "test-nat", - "nohelp", - options, - &run, NULL); + + GNUNET_log_setup("test-nat", + "WARNING", + NULL); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Testing NAT library, timeout set to %s\n", + GNUNET_STRINGS_relative_time_to_string(TIMEOUT, + GNUNET_YES)); + GNUNET_PROGRAM_run(3, + argv_prog, + "test-nat", + "nohelp", + options, + &run, NULL); return 0; } diff --git a/src/nat/test_nat_mini.c b/src/nat/test_nat_mini.c index 8a7ff16f4..09231d8ec 100644 --- a/src/nat/test_nat_mini.c +++ b/src/nat/test_nat_mini.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * Testcase for port redirection and public IP address retrieval. @@ -35,31 +35,31 @@ #include "gnunet_nat_lib.h" /* Time to wait before stopping NAT, in seconds */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) /** * Function called on each address that the NAT service * believes to be valid for the transport. */ static void -addr_callback (void *cls, int add_remove, - const struct sockaddr *addr, - socklen_t addrlen, - enum GNUNET_NAT_StatusCode ret) +addr_callback(void *cls, int add_remove, + const struct sockaddr *addr, + socklen_t addrlen, + enum GNUNET_NAT_StatusCode ret) { if (GNUNET_NAT_ERROR_SUCCESS == ret) - { - fprintf (stderr, - "Address changed: %s `%s' (%u bytes)\n", - add_remove == GNUNET_YES - ? "added" : "removed", - GNUNET_a2s (addr, - addrlen), - (unsigned int) addrlen); - } + { + fprintf(stderr, + "Address changed: %s `%s' (%u bytes)\n", + add_remove == GNUNET_YES + ? "added" : "removed", + GNUNET_a2s(addr, + addrlen), + (unsigned int)addrlen); + } else ; - //TODO: proper error handling! + //TODO: proper error handling! } @@ -67,12 +67,12 @@ addr_callback (void *cls, int add_remove, * Function that terminates the test. */ static void -stop (void *cls) +stop(void *cls) { struct GNUNET_NAT_MiniHandle *mini = cls; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Stopping NAT and quitting...\n"); - GNUNET_NAT_mini_map_stop (mini); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Stopping NAT and quitting...\n"); + GNUNET_NAT_mini_map_stop(mini); } #define PORT 10000 @@ -81,27 +81,27 @@ stop (void *cls) * Main function run with scheduler. */ static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_NAT_MiniHandle *mini; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Requesting NAT redirection for port %u...\n", - PORT); - mini = GNUNET_NAT_mini_map_start (PORT, GNUNET_YES /* tcp */ , - &addr_callback, NULL); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Requesting NAT redirection for port %u...\n", + PORT); + mini = GNUNET_NAT_mini_map_start(PORT, GNUNET_YES /* tcp */, + &addr_callback, NULL); if (NULL == mini) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Could not start UPnP interaction\n"); - return; - } - GNUNET_SCHEDULER_add_delayed (TIMEOUT, &stop, mini); + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Could not start UPnP interaction\n"); + return; + } + GNUNET_SCHEDULER_add_delayed(TIMEOUT, &stop, mini); } int -main (int argc, char *const argv[]) +main(int argc, char *const argv[]) { struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END @@ -116,16 +116,16 @@ main (int argc, char *const argv[]) NULL }; - GNUNET_log_setup ("test-nat-mini", - "WARNING", - NULL); + GNUNET_log_setup("test-nat-mini", + "WARNING", + NULL); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "UPnP test for NAT library, timeout set to %s\n", - GNUNET_STRINGS_relative_time_to_string (TIMEOUT, - GNUNET_YES)); - GNUNET_PROGRAM_run (5, argv_prog, "test-nat-mini", "nohelp", options, &run, - NULL); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "UPnP test for NAT library, timeout set to %s\n", + GNUNET_STRINGS_relative_time_to_string(TIMEOUT, + GNUNET_YES)); + GNUNET_PROGRAM_run(5, argv_prog, "test-nat-mini", "nohelp", options, &run, + NULL); return 0; } diff --git a/src/nat/test_nat_test.c b/src/nat/test_nat_test.c index c9479a688..e217c1d29 100644 --- a/src/nat/test_nat_test.c +++ b/src/nat/test_nat_test.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nat/test_nat_test.c * @brief Testcase for NAT testing functions @@ -29,7 +29,7 @@ /** * Time to wait before stopping NAT test, in seconds */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 15) static int ret = 1; @@ -40,32 +40,32 @@ static struct GNUNET_SCHEDULER_Task * tsk; static void -report_result (void *cls, - enum GNUNET_NAT_StatusCode aret) +report_result(void *cls, + enum GNUNET_NAT_StatusCode aret) { if (GNUNET_NAT_ERROR_TIMEOUT == aret) - fprintf (stderr, - "NAT test timed out\n"); + fprintf(stderr, + "NAT test timed out\n"); else if (GNUNET_NAT_ERROR_SUCCESS != aret) - fprintf (stderr, - "NAT test reported error %d\n", aret); + fprintf(stderr, + "NAT test reported error %d\n", aret); else ret = 0; - GNUNET_NAT_test_stop (tst); + GNUNET_NAT_test_stop(tst); tst = NULL; - GNUNET_SCHEDULER_cancel (tsk); + GNUNET_SCHEDULER_cancel(tsk); tsk = NULL; } static void -failed_timeout (void *cls) +failed_timeout(void *cls) { tsk = NULL; - fprintf (stderr, - "NAT test failed to terminate on timeout\n"); + fprintf(stderr, + "NAT test failed to terminate on timeout\n"); ret = 2; - GNUNET_NAT_test_stop (tst); + GNUNET_NAT_test_stop(tst); tst = NULL; } @@ -74,23 +74,22 @@ failed_timeout (void *cls) * Main function run with scheduler. */ static void -run (void *cls, char *const *args, const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { tst = - GNUNET_NAT_test_start (cfg, GNUNET_YES, 1285, 1285, TIMEOUT, - &report_result, - NULL); - tsk = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply (TIMEOUT, - 2), - &failed_timeout, - NULL); - + GNUNET_NAT_test_start(cfg, GNUNET_YES, 1285, 1285, TIMEOUT, + &report_result, + NULL); + tsk = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(TIMEOUT, + 2), + &failed_timeout, + NULL); } int -main (int argc, char *const argv[]) +main(int argc, char *const argv[]) { struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END @@ -104,37 +103,37 @@ main (int argc, char *const argv[]) NULL }; - GNUNET_log_setup ("test-nat-test", - "WARNING", - NULL); + GNUNET_log_setup("test-nat-test", + "WARNING", + NULL); - nat_res = GNUNET_OS_check_helper_binary ("gnunet-nat-server", GNUNET_NO, NULL); + nat_res = GNUNET_OS_check_helper_binary("gnunet-nat-server", GNUNET_NO, NULL); if (GNUNET_SYSERR == nat_res) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Cannot run NAT test: `%s' file not found\n", - "gnunet-nat-server"); - return 0; - } - - gns = GNUNET_OS_start_process (GNUNET_YES, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - NULL, NULL, NULL, - "gnunet-nat-server", - "gnunet-nat-server", - "-c", "test_nat_test_data.conf", - "12345", NULL); - GNUNET_assert (NULL != gns); - GNUNET_PROGRAM_run (3, argv_prog, - "test-nat-test", "nohelp", - options, &run, - NULL); - GNUNET_break (0 == GNUNET_OS_process_kill (gns, GNUNET_TERM_SIG)); - GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (gns)); - GNUNET_OS_process_destroy (gns); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Cannot run NAT test: `%s' file not found\n", + "gnunet-nat-server"); + return 0; + } + + gns = GNUNET_OS_start_process(GNUNET_YES, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + NULL, NULL, NULL, + "gnunet-nat-server", + "gnunet-nat-server", + "-c", "test_nat_test_data.conf", + "12345", NULL); + GNUNET_assert(NULL != gns); + GNUNET_PROGRAM_run(3, argv_prog, + "test-nat-test", "nohelp", + options, &run, + NULL); + GNUNET_break(0 == GNUNET_OS_process_kill(gns, GNUNET_TERM_SIG)); + GNUNET_break(GNUNET_OK == GNUNET_OS_process_wait(gns)); + GNUNET_OS_process_destroy(gns); if (0 != ret) - fprintf (stderr, - "NAT test failed to report success\n"); + fprintf(stderr, + "NAT test failed to report success\n"); return ret; } diff --git a/src/nat/test_stun.c b/src/nat/test_stun.c index ee2db35e5..ee755905e 100644 --- a/src/nat/test_stun.c +++ b/src/nat/test_stun.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * Testcase for STUN server resolution @@ -36,12 +36,12 @@ -#define LOG(kind,...) GNUNET_log_from (kind, "test-stun", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "test-stun", __VA_ARGS__) /** * Time to wait before stopping NAT, in seconds */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) /** @@ -74,10 +74,10 @@ static struct GNUNET_NAT_STUN_Handle *rh; static void print_answer(struct sockaddr_in* answer) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "External IP is: %s , with port %d\n", - inet_ntoa (answer->sin_addr), - ntohs (answer->sin_port)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "External IP is: %s , with port %d\n", + inet_ntoa(answer->sin_addr), + ntohs(answer->sin_port)); } @@ -85,25 +85,25 @@ print_answer(struct sockaddr_in* answer) * Function that terminates the test. */ static void -stop () +stop() { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Stopping NAT and quitting...\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Stopping NAT and quitting...\n"); if (NULL != ltask4) - { - GNUNET_SCHEDULER_cancel (ltask4); - ltask4 = NULL; - } - if(NULL != lsock4) - { - GNUNET_NETWORK_socket_close(lsock4); - lsock4 = NULL; - } + { + GNUNET_SCHEDULER_cancel(ltask4); + ltask4 = NULL; + } + if (NULL != lsock4) + { + GNUNET_NETWORK_socket_close(lsock4); + lsock4 = NULL; + } if (NULL != rh) - { - GNUNET_NAT_stun_make_request_cancel (rh); - rh = NULL; - } + { + GNUNET_NAT_stun_make_request_cancel(rh); + rh = NULL; + } } @@ -114,7 +114,7 @@ stop () * @param cls */ static void -do_udp_read (void *cls) +do_udp_read(void *cls) { //struct GNUNET_NAT_Test *tst = cls; unsigned char reply_buf[1024]; @@ -123,36 +123,36 @@ do_udp_read (void *cls) const struct GNUNET_SCHEDULER_TaskContext *tc; ltask4 = NULL; - tc = GNUNET_SCHEDULER_get_task_context (); - if ( (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) || - (! GNUNET_NETWORK_fdset_isset (tc->read_ready, - lsock4)) ) - { - fprintf (stderr, - "Timeout waiting for STUN response\n"); - stop(); - } - rlen = GNUNET_NETWORK_socket_recv (lsock4, - reply_buf, - sizeof (reply_buf)); - memset (&answer, - 0, - sizeof(struct sockaddr_in)); + tc = GNUNET_SCHEDULER_get_task_context(); + if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) || + (!GNUNET_NETWORK_fdset_isset(tc->read_ready, + lsock4))) + { + fprintf(stderr, + "Timeout waiting for STUN response\n"); + stop(); + } + rlen = GNUNET_NETWORK_socket_recv(lsock4, + reply_buf, + sizeof(reply_buf)); + memset(&answer, + 0, + sizeof(struct sockaddr_in)); if (GNUNET_OK != - GNUNET_NAT_stun_handle_packet (reply_buf, - rlen, - &answer)) - { - fprintf (stderr, - "Unexpected UDP packet, trying to read more\n"); - ltask4 = GNUNET_SCHEDULER_add_read_net (TIMEOUT, - lsock4, - &do_udp_read, NULL); - return; - } + GNUNET_NAT_stun_handle_packet(reply_buf, + rlen, + &answer)) + { + fprintf(stderr, + "Unexpected UDP packet, trying to read more\n"); + ltask4 = GNUNET_SCHEDULER_add_read_net(TIMEOUT, + lsock4, + &do_udp_read, NULL); + return; + } ret = 0; - print_answer (&answer); - stop (); + print_answer(&answer); + stop(); } @@ -162,33 +162,33 @@ do_udp_read (void *cls) * @return NULL on error */ static struct GNUNET_NETWORK_Handle * -bind_v4 () +bind_v4() { struct GNUNET_NETWORK_Handle *ls; struct sockaddr_in sa4; int eno; - memset (&sa4, 0, sizeof (sa4)); + memset(&sa4, 0, sizeof(sa4)); sa4.sin_family = AF_INET; - sa4.sin_port = htons (port); + sa4.sin_port = htons(port); #if HAVE_SOCKADDR_IN_SIN_LEN - sa4.sin_len = sizeof (sa4); + sa4.sin_len = sizeof(sa4); #endif - ls = GNUNET_NETWORK_socket_create (AF_INET, - SOCK_DGRAM, - 0); + ls = GNUNET_NETWORK_socket_create(AF_INET, + SOCK_DGRAM, + 0); if (NULL == ls) return NULL; if (GNUNET_OK != - GNUNET_NETWORK_socket_bind (ls, - (const struct sockaddr *) &sa4, - sizeof (sa4))) - { - eno = errno; - GNUNET_NETWORK_socket_close (ls); - errno = eno; - return NULL; - } + GNUNET_NETWORK_socket_bind(ls, + (const struct sockaddr *)&sa4, + sizeof(sa4))) + { + eno = errno; + GNUNET_NETWORK_socket_close(ls); + errno = eno; + return NULL; + } return ls; } @@ -200,29 +200,29 @@ bind_v4 () * @param error status code from STUN */ static void -request_callback (void *cls, - enum GNUNET_NAT_StatusCode error) +request_callback(void *cls, + enum GNUNET_NAT_StatusCode error) { rh = NULL; if (GNUNET_NAT_ERROR_SUCCESS == error) - { - /* all good, start to receive */ - ltask4 = GNUNET_SCHEDULER_add_read_net (TIMEOUT, - lsock4, - &do_udp_read, - NULL); - return; - } + { + /* all good, start to receive */ + ltask4 = GNUNET_SCHEDULER_add_read_net(TIMEOUT, + lsock4, + &do_udp_read, + NULL); + return; + } if (error == GNUNET_NAT_ERROR_NOT_ONLINE) - { - ret = 77; /* report 'skip' */ - fprintf (stderr, - "System is offline, cannot test STUN request.\n"); - } + { + ret = 77; /* report 'skip' */ + fprintf(stderr, + "System is offline, cannot test STUN request.\n"); + } else - { - ret = error; - } + { + ret = error; + } stop(); } @@ -231,81 +231,81 @@ request_callback (void *cls, * Main function run with scheduler. */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { //Lets create the socket - lsock4 = bind_v4 (); + lsock4 = bind_v4(); if (NULL == lsock4) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "bind"); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Service listens on port %u\n", - (unsigned int) port); - rh = GNUNET_NAT_stun_make_request (stun_server, - stun_port, - lsock4, - &request_callback, NULL); - GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &stop, NULL); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "bind"); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Service listens on port %u\n", + (unsigned int)port); + rh = GNUNET_NAT_stun_make_request(stun_server, + stun_port, + lsock4, + &request_callback, NULL); + GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &stop, NULL); } int -main (int argc, char *const argv[]) +main(int argc, char *const argv[]) { struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_OPTION_END + GNUNET_GETOPT_OPTION_END }; char *const argv_prog[] = { - "test-stun", - "-c", - "test_stun.conf", - NULL + "test-stun", + "-c", + "test_stun.conf", + NULL }; char *fn; struct GNUNET_OS_Process *proc; - GNUNET_log_setup ("test-stun", - "WARNING", - NULL); + GNUNET_log_setup("test-stun", + "WARNING", + NULL); /* Lets start resolver */ - fn = GNUNET_OS_get_libexec_binary_path ("gnunet-service-resolver"); - proc = GNUNET_OS_start_process (GNUNET_YES, - GNUNET_OS_INHERIT_STD_OUT_AND_ERR, - NULL, NULL, NULL, - fn, - "gnunet-service-resolver", - "-c", "test_stun.conf", NULL); + fn = GNUNET_OS_get_libexec_binary_path("gnunet-service-resolver"); + proc = GNUNET_OS_start_process(GNUNET_YES, + GNUNET_OS_INHERIT_STD_OUT_AND_ERR, + NULL, NULL, NULL, + fn, + "gnunet-service-resolver", + "-c", "test_stun.conf", NULL); if (NULL == proc) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "This test was unable to start gnunet-service-resolver, and it is required to run ...\n"); - exit(1); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "This test was unable to start gnunet-service-resolver, and it is required to run ...\n"); + exit(1); + } - GNUNET_PROGRAM_run (3, argv_prog, - "test-stun", "nohelp", - options, - &run, NULL); + GNUNET_PROGRAM_run(3, argv_prog, + "test-stun", "nohelp", + options, + &run, NULL); /* Now kill the resolver */ - if (0 != GNUNET_OS_process_kill (proc, GNUNET_TERM_SIG)) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill"); - } - GNUNET_OS_process_wait (proc); - GNUNET_OS_process_destroy (proc); + if (0 != GNUNET_OS_process_kill(proc, GNUNET_TERM_SIG)) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill"); + } + GNUNET_OS_process_wait(proc); + GNUNET_OS_process_destroy(proc); proc = NULL; - GNUNET_free (fn); + GNUNET_free(fn); return ret; } diff --git a/src/nse/gnunet-nse-profiler.c b/src/nse/gnunet-nse-profiler.c index 12f5f37fb..eaa06b8ed 100644 --- a/src/nse/gnunet-nse-profiler.c +++ b/src/nse/gnunet-nse-profiler.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nse/gnunet-nse-profiler.c * @@ -36,19 +36,18 @@ /** * Generic loggins shorthand */ -#define LOG(kind, ...) GNUNET_log (kind, __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__) /** * Debug logging shorthand */ -#define LOG_DEBUG(...) LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__) +#define LOG_DEBUG(...) LOG(GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__) /** * Information we track for a peer in the testbed. */ -struct NSEPeer -{ +struct NSEPeer { /** * Prev reference in DLL. */ @@ -84,8 +83,7 @@ struct NSEPeer /** * Operation map entry */ -struct OpListEntry -{ +struct OpListEntry { /** * DLL next ptr */ @@ -208,7 +206,7 @@ static char *data_filename; * How long to wait before triggering next round? * Default: 60 s. */ -static struct GNUNET_TIME_Relative wait_time = {60 * 1000}; +static struct GNUNET_TIME_Relative wait_time = { 60 * 1000 }; /** * DLL head for operation list @@ -231,26 +229,26 @@ static struct GNUNET_SCHEDULER_Task *round_task; * STATISTICS that we keep to selected peers. */ static void -close_monitor_connections () +close_monitor_connections() { struct NSEPeer *pos; struct OpListEntry *oplist_entry; while (NULL != (pos = peer_head)) - { - if (NULL != pos->nse_op) - GNUNET_TESTBED_operation_done (pos->nse_op); - if (NULL != pos->stat_op) - GNUNET_TESTBED_operation_done (pos->stat_op); - GNUNET_CONTAINER_DLL_remove (peer_head, peer_tail, pos); - GNUNET_free (pos); - } + { + if (NULL != pos->nse_op) + GNUNET_TESTBED_operation_done(pos->nse_op); + if (NULL != pos->stat_op) + GNUNET_TESTBED_operation_done(pos->stat_op); + GNUNET_CONTAINER_DLL_remove(peer_head, peer_tail, pos); + GNUNET_free(pos); + } while (NULL != (oplist_entry = oplist_head)) - { - GNUNET_CONTAINER_DLL_remove (oplist_head, oplist_tail, oplist_entry); - GNUNET_TESTBED_operation_done (oplist_entry->op); - GNUNET_free (oplist_entry); - } + { + GNUNET_CONTAINER_DLL_remove(oplist_head, oplist_tail, oplist_entry); + GNUNET_TESTBED_operation_done(oplist_entry->op); + GNUNET_free(oplist_entry); + } } @@ -260,30 +258,30 @@ close_monitor_connections () * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - LOG_DEBUG ("Ending test.\n"); - close_monitor_connections (); + LOG_DEBUG("Ending test.\n"); + close_monitor_connections(); if (NULL != round_task) - { - GNUNET_SCHEDULER_cancel (round_task); - round_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(round_task); + round_task = NULL; + } if (NULL != data_file) - { - GNUNET_DISK_file_close (data_file); - data_file = NULL; - } + { + GNUNET_DISK_file_close(data_file); + data_file = NULL; + } if (NULL != output_file) - { - GNUNET_DISK_file_close (output_file); - output_file = NULL; - } + { + GNUNET_DISK_file_close(output_file); + output_file = NULL; + } if (NULL != testing_cfg) - { - GNUNET_CONFIGURATION_destroy (testing_cfg); - testing_cfg = NULL; - } + { + GNUNET_CONFIGURATION_destroy(testing_cfg); + testing_cfg = NULL; + } } @@ -297,35 +295,35 @@ shutdown_task (void *cls) * of the size estimation values seen */ static void -handle_estimate (void *cls, - struct GNUNET_TIME_Absolute timestamp, - double estimate, - double std_dev) +handle_estimate(void *cls, + struct GNUNET_TIME_Absolute timestamp, + double estimate, + double std_dev) { struct NSEPeer *peer = cls; char output_buffer[512]; size_t size; if (NULL == output_file) - { - fprintf (stderr, - "Received network size estimate from peer %p. Size: %f std.dev. %f\n", - peer, - estimate, - std_dev); - return; - } - size = GNUNET_snprintf (output_buffer, - sizeof (output_buffer), - "%p %llu %llu %f %f %f\n", - peer, - peers_running, - (unsigned long long) timestamp.abs_value_us, - GNUNET_NSE_log_estimate_to_n (estimate), - estimate, - std_dev); - if (size != GNUNET_DISK_file_write (output_file, output_buffer, size)) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n"); + { + fprintf(stderr, + "Received network size estimate from peer %p. Size: %f std.dev. %f\n", + peer, + estimate, + std_dev); + return; + } + size = GNUNET_snprintf(output_buffer, + sizeof(output_buffer), + "%p %llu %llu %f %f %f\n", + peer, + peers_running, + (unsigned long long)timestamp.abs_value_us, + GNUNET_NSE_log_estimate_to_n(estimate), + estimate, + std_dev); + if (size != GNUNET_DISK_file_write(output_file, output_buffer, size)) + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n"); } @@ -340,11 +338,11 @@ handle_estimate (void *cls, * @return service handle to return in 'op_result', NULL on error */ static void * -nse_connect_adapter (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg) +nse_connect_adapter(void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg) { struct NSEPeer *current_peer = cls; - return GNUNET_NSE_connect (cfg, &handle_estimate, current_peer); + return GNUNET_NSE_connect(cfg, &handle_estimate, current_peer); } @@ -356,9 +354,9 @@ nse_connect_adapter (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg) * @param op_result service handle returned from the connect adapter */ static void -nse_disconnect_adapter (void *cls, void *op_result) +nse_disconnect_adapter(void *cls, void *op_result) { - GNUNET_NSE_disconnect (op_result); + GNUNET_NSE_disconnect(op_result); } @@ -373,40 +371,40 @@ nse_disconnect_adapter (void *cls, void *op_result) * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration */ static int -stat_iterator (void *cls, - const char *subsystem, - const char *name, - uint64_t value, - int is_persistent) +stat_iterator(void *cls, + const char *subsystem, + const char *name, + uint64_t value, + int is_persistent) { char *output_buffer; struct GNUNET_TIME_Absolute now; int size; unsigned int flag; - GNUNET_assert (NULL != data_file); - now = GNUNET_TIME_absolute_get (); - flag = strcasecmp (subsystem, "core"); + GNUNET_assert(NULL != data_file); + now = GNUNET_TIME_absolute_get(); + flag = strcasecmp(subsystem, "core"); if (0 != flag) flag = 1; - size = GNUNET_asprintf (&output_buffer, - "%llu %llu %u\n", - now.abs_value_us / 1000LL / 1000LL, - value, - flag); + size = GNUNET_asprintf(&output_buffer, + "%llu %llu %u\n", + now.abs_value_us / 1000LL / 1000LL, + value, + flag); if (0 > size) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Error formatting output buffer.\n"); - GNUNET_free (output_buffer); - return GNUNET_SYSERR; - } - if (size != GNUNET_DISK_file_write (data_file, output_buffer, (size_t) size)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n"); - GNUNET_free (output_buffer); - return GNUNET_SYSERR; - } - GNUNET_free (output_buffer); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Error formatting output buffer.\n"); + GNUNET_free(output_buffer); + return GNUNET_SYSERR; + } + if (size != GNUNET_DISK_file_write(data_file, output_buffer, (size_t)size)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n"); + GNUNET_free(output_buffer); + return GNUNET_SYSERR; + } + GNUNET_free(output_buffer); return GNUNET_OK; } @@ -421,11 +419,11 @@ stat_iterator (void *cls, * @return service handle to return in 'op_result', NULL on error */ static void * -stat_connect_adapter (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg) +stat_connect_adapter(void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg) { struct NSEPeer *peer = cls; - peer->sh = GNUNET_STATISTICS_create ("nse-profiler", cfg); + peer->sh = GNUNET_STATISTICS_create("nse-profiler", cfg); return peer->sh; } @@ -437,23 +435,23 @@ stat_connect_adapter (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg) * @param op_result service handle returned from the connect adapter */ static void -stat_disconnect_adapter (void *cls, void *op_result) +stat_disconnect_adapter(void *cls, void *op_result) { struct NSEPeer *peer = cls; - GNUNET_break (GNUNET_OK == - GNUNET_STATISTICS_watch_cancel (peer->sh, - "core", - "# peers connected", - stat_iterator, - peer)); - GNUNET_break (GNUNET_OK == - GNUNET_STATISTICS_watch_cancel (peer->sh, - "nse", - "# peers connected", - stat_iterator, - peer)); - GNUNET_STATISTICS_destroy (op_result, GNUNET_NO); + GNUNET_break(GNUNET_OK == + GNUNET_STATISTICS_watch_cancel(peer->sh, + "core", + "# peers connected", + stat_iterator, + peer)); + GNUNET_break(GNUNET_OK == + GNUNET_STATISTICS_watch_cancel(peer->sh, + "nse", + "# peers connected", + stat_iterator, + peer)); + GNUNET_STATISTICS_destroy(op_result, GNUNET_NO); peer->sh = NULL; } @@ -469,29 +467,29 @@ stat_disconnect_adapter (void *cls, void *op_result) * operation has executed successfully. */ static void -stat_comp_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg) +stat_comp_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg) { struct GNUNET_STATISTICS_Handle *sh = ca_result; struct NSEPeer *peer = cls; if (NULL != emsg) - { - GNUNET_break (0); - return; - } - GNUNET_break (GNUNET_OK == GNUNET_STATISTICS_watch (sh, - "core", - "# peers connected", - stat_iterator, - peer)); - GNUNET_break (GNUNET_OK == GNUNET_STATISTICS_watch (sh, - "nse", - "# peers connected", - stat_iterator, - peer)); + { + GNUNET_break(0); + return; + } + GNUNET_break(GNUNET_OK == GNUNET_STATISTICS_watch(sh, + "core", + "# peers connected", + stat_iterator, + peer)); + GNUNET_break(GNUNET_OK == GNUNET_STATISTICS_watch(sh, + "nse", + "# peers connected", + stat_iterator, + peer)); } @@ -500,7 +498,7 @@ stat_comp_cb (void *cls, * all of the running peers. */ static void -connect_nse_service () +connect_nse_service() { struct NSEPeer *current_peer; unsigned int i; @@ -508,39 +506,39 @@ connect_nse_service () if (0 == connection_limit) return; - LOG_DEBUG ("Connecting to nse service of peers\n"); + LOG_DEBUG("Connecting to nse service of peers\n"); connections = 0; for (i = 0; i < num_peers_in_round[current_round]; i++) - { - if ((num_peers_in_round[current_round] > connection_limit) && - (0 != (i % (num_peers_in_round[current_round] / connection_limit)))) - continue; - LOG_DEBUG ("Connecting to nse service of peer %d\n", i); - current_peer = GNUNET_new (struct NSEPeer); - current_peer->daemon = daemons[i]; - current_peer->nse_op = - GNUNET_TESTBED_service_connect (NULL, - current_peer->daemon, - "nse", - NULL, - NULL, - &nse_connect_adapter, - &nse_disconnect_adapter, - current_peer); - if (NULL != data_file) - current_peer->stat_op = - GNUNET_TESTBED_service_connect (NULL, - current_peer->daemon, - "statistics", - stat_comp_cb, - current_peer, - &stat_connect_adapter, - &stat_disconnect_adapter, - current_peer); - GNUNET_CONTAINER_DLL_insert (peer_head, peer_tail, current_peer); - if (++connections == connection_limit) - break; - } + { + if ((num_peers_in_round[current_round] > connection_limit) && + (0 != (i % (num_peers_in_round[current_round] / connection_limit)))) + continue; + LOG_DEBUG("Connecting to nse service of peer %d\n", i); + current_peer = GNUNET_new(struct NSEPeer); + current_peer->daemon = daemons[i]; + current_peer->nse_op = + GNUNET_TESTBED_service_connect(NULL, + current_peer->daemon, + "nse", + NULL, + NULL, + &nse_connect_adapter, + &nse_disconnect_adapter, + current_peer); + if (NULL != data_file) + current_peer->stat_op = + GNUNET_TESTBED_service_connect(NULL, + current_peer->daemon, + "statistics", + stat_comp_cb, + current_peer, + &stat_connect_adapter, + &stat_disconnect_adapter, + current_peer); + GNUNET_CONTAINER_DLL_insert(peer_head, peer_tail, current_peer); + if (++connections == connection_limit) + break; + } } @@ -550,7 +548,7 @@ connect_nse_service () * @param cls NULL, unused */ static void -next_round (void *cls); +next_round(void *cls); /** @@ -561,11 +559,11 @@ next_round (void *cls); * @param cls unused, NULL */ static void -finish_round (void *cls) +finish_round(void *cls) { - LOG (GNUNET_ERROR_TYPE_INFO, "Have %u connections\n", total_connections); - close_monitor_connections (); - round_task = GNUNET_SCHEDULER_add_now (&next_round, NULL); + LOG(GNUNET_ERROR_TYPE_INFO, "Have %u connections\n", total_connections); + close_monitor_connections(); + round_task = GNUNET_SCHEDULER_add_now(&next_round, NULL); } @@ -575,11 +573,11 @@ finish_round (void *cls) * specified delay before finishing the round). */ static void -run_round () +run_round() { - LOG_DEBUG ("Running round %u\n", current_round); - connect_nse_service (); - GNUNET_SCHEDULER_add_delayed (wait_time, &finish_round, NULL); + LOG_DEBUG("Running round %u\n", current_round); + connect_nse_service(); + GNUNET_SCHEDULER_add_delayed(wait_time, &finish_round, NULL); } @@ -587,12 +585,12 @@ run_round () * Creates an oplist entry and adds it to the oplist DLL */ static struct OpListEntry * -make_oplist_entry () +make_oplist_entry() { struct OpListEntry *entry; - entry = GNUNET_new (struct OpListEntry); - GNUNET_CONTAINER_DLL_insert_tail (oplist_head, oplist_tail, entry); + entry = GNUNET_new(struct OpListEntry); + GNUNET_CONTAINER_DLL_insert_tail(oplist_head, oplist_tail, entry); return entry; } @@ -605,25 +603,25 @@ make_oplist_entry () * @param emsg NULL on success; otherwise an error description */ static void -manage_service_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - const char *emsg) +manage_service_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + const char *emsg) { struct OpListEntry *entry = cls; - GNUNET_TESTBED_operation_done (entry->op); + GNUNET_TESTBED_operation_done(entry->op); if (NULL != emsg) - { - LOG (GNUNET_ERROR_TYPE_ERROR, "Failed to start/stop NSE at a peer\n"); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_assert (0 != entry->delta); + { + LOG(GNUNET_ERROR_TYPE_ERROR, "Failed to start/stop NSE at a peer\n"); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_assert(0 != entry->delta); peers_running += entry->delta; - GNUNET_CONTAINER_DLL_remove (oplist_head, oplist_tail, entry); - GNUNET_free (entry); + GNUNET_CONTAINER_DLL_remove(oplist_head, oplist_tail, entry); + GNUNET_free(entry); if (num_peers_in_round[current_round] == peers_running) - run_round (); + run_round(); } @@ -632,35 +630,35 @@ manage_service_cb (void *cls, * peers for the round */ static void -adjust_running_peers () +adjust_running_peers() { struct OpListEntry *entry; unsigned int i; /* start peers if we have too few */ for (i = peers_running; i < num_peers_in_round[current_round]; i++) - { - entry = make_oplist_entry (); - entry->delta = 1; - entry->op = GNUNET_TESTBED_peer_manage_service (NULL, - daemons[i], - "nse", - &manage_service_cb, - entry, - 1); - } + { + entry = make_oplist_entry(); + entry->delta = 1; + entry->op = GNUNET_TESTBED_peer_manage_service(NULL, + daemons[i], + "nse", + &manage_service_cb, + entry, + 1); + } /* stop peers if we have too many */ for (i = num_peers_in_round[current_round]; i < peers_running; i++) - { - entry = make_oplist_entry (); - entry->delta = -1; - entry->op = GNUNET_TESTBED_peer_manage_service (NULL, - daemons[i], - "nse", - &manage_service_cb, - entry, - 0); - } + { + entry = make_oplist_entry(); + entry->delta = -1; + entry->op = GNUNET_TESTBED_peer_manage_service(NULL, + daemons[i], + "nse", + &manage_service_cb, + entry, + 0); + } } @@ -671,25 +669,25 @@ adjust_running_peers () * @param cls NULL, unused */ static void -next_round (void *cls) +next_round(void *cls) { round_task = NULL; - LOG_DEBUG ("Disconnecting nse service of peers\n"); + LOG_DEBUG("Disconnecting nse service of peers\n"); current_round++; if (current_round == num_rounds) - { - /* this was the last round, terminate */ - ok = 0; - GNUNET_SCHEDULER_shutdown (); - return; - } + { + /* this was the last round, terminate */ + ok = 0; + GNUNET_SCHEDULER_shutdown(); + return; + } if (num_peers_in_round[current_round] == peers_running) - { - /* no need to churn, just run next round */ - run_round (); - return; - } - adjust_running_peers (); + { + /* no need to churn, just run next round */ + run_round(); + return; + } + adjust_running_peers(); } @@ -701,20 +699,22 @@ next_round (void *cls) * @param event information on what is happening */ static void -master_controller_cb (void *cls, - const struct GNUNET_TESTBED_EventInformation *event) +master_controller_cb(void *cls, + const struct GNUNET_TESTBED_EventInformation *event) { switch (event->type) - { - case GNUNET_TESTBED_ET_CONNECT: - total_connections++; - break; - case GNUNET_TESTBED_ET_DISCONNECT: - total_connections--; - break; - default: - break; - } + { + case GNUNET_TESTBED_ET_CONNECT: + total_connections++; + break; + + case GNUNET_TESTBED_ET_DISCONNECT: + total_connections--; + break; + + default: + break; + } } @@ -732,28 +732,28 @@ master_controller_cb (void *cls, * failed */ static void -test_master (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers_, - struct GNUNET_TESTBED_Peer **peers, - unsigned int links_succeeded, - unsigned int links_failed) +test_master(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers_, + struct GNUNET_TESTBED_Peer **peers, + unsigned int links_succeeded, + unsigned int links_failed) { if (NULL == peers) - { - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_SCHEDULER_shutdown(); + return; + } daemons = peers; - GNUNET_break (num_peers_ == num_peers); + GNUNET_break(num_peers_ == num_peers); peers_running = num_peers; if (num_peers_in_round[current_round] == peers_running) - { - /* no need to churn, just run the starting round */ - run_round (); - return; - } - adjust_running_peers (); + { + /* no need to churn, just run the starting round */ + run_round(); + return; + } + adjust_running_peers(); } @@ -766,75 +766,75 @@ test_master (void *cls, * @param cfg configuration handle */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { char *tok; uint64_t event_mask; unsigned int num; ok = 1; - testing_cfg = GNUNET_CONFIGURATION_dup (cfg); - LOG_DEBUG ("Starting daemons.\n"); + testing_cfg = GNUNET_CONFIGURATION_dup(cfg); + LOG_DEBUG("Starting daemons.\n"); if (NULL == num_peer_spec) - { - fprintf (stderr, "You need to specify the number of peers to run\n"); - return; - } - for (tok = strtok (num_peer_spec, ","); NULL != tok; tok = strtok (NULL, ",")) - { - if (1 != sscanf (tok, "%u", &num)) { - fprintf (stderr, "You need to specify numbers, not `%s'\n", tok); + fprintf(stderr, "You need to specify the number of peers to run\n"); return; } - if (0 == num) + for (tok = strtok(num_peer_spec, ","); NULL != tok; tok = strtok(NULL, ",")) { - fprintf (stderr, "Refusing to run a round with 0 peers\n"); - return; + if (1 != sscanf(tok, "%u", &num)) + { + fprintf(stderr, "You need to specify numbers, not `%s'\n", tok); + return; + } + if (0 == num) + { + fprintf(stderr, "Refusing to run a round with 0 peers\n"); + return; + } + GNUNET_array_append(num_peers_in_round, num_rounds, num); + num_peers = GNUNET_MAX(num_peers, num); } - GNUNET_array_append (num_peers_in_round, num_rounds, num); - num_peers = GNUNET_MAX (num_peers, num); - } if (0 == num_peers) - { - fprintf (stderr, "Refusing to run a testbed with no rounds\n"); - return; - } + { + fprintf(stderr, "Refusing to run a testbed with no rounds\n"); + return; + } if ((NULL != data_filename) && (NULL == - (data_file = GNUNET_DISK_file_open (data_filename, - GNUNET_DISK_OPEN_READWRITE | - GNUNET_DISK_OPEN_TRUNCATE | - GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)))) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", data_filename); + (data_file = GNUNET_DISK_file_open(data_filename, + GNUNET_DISK_OPEN_READWRITE | + GNUNET_DISK_OPEN_TRUNCATE | + GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)))) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "open", data_filename); if ((NULL != output_filename) && (NULL == - (output_file = GNUNET_DISK_file_open (output_filename, - GNUNET_DISK_OPEN_READWRITE | - GNUNET_DISK_OPEN_CREATE, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)))) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", output_filename); + (output_file = GNUNET_DISK_file_open(output_filename, + GNUNET_DISK_OPEN_READWRITE | + GNUNET_DISK_OPEN_CREATE, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)))) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "open", output_filename); event_mask = 0LL; event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_START); event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_STOP); event_mask |= (1LL << GNUNET_TESTBED_ET_CONNECT); event_mask |= (1LL << GNUNET_TESTBED_ET_DISCONNECT); - GNUNET_TESTBED_run (hosts_file, - cfg, - num_peers, - event_mask, - master_controller_cb, - NULL, /* master_controller_cb cls */ - &test_master, - NULL); /* test_master cls */ - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + GNUNET_TESTBED_run(hosts_file, + cfg, + num_peers, + event_mask, + master_controller_cb, + NULL, /* master_controller_cb cls */ + &test_master, + NULL); /* test_master cls */ + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); } @@ -844,72 +844,73 @@ run (void *cls, * @return 0 on success */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_uint ( - 'C', - "connections", - "COUNT", - gettext_noop ( - "limit to the number of connections to NSE services, 0 for none"), - &connection_limit), - GNUNET_GETOPT_option_string ( - 'd', - "details", - "FILENAME", - gettext_noop ( - "name of the file for writing connection information and statistics"), - &data_filename), - - GNUNET_GETOPT_option_string ( - 'H', - "hosts", - "FILENAME", - gettext_noop ( - "name of the file with the login information for the testbed"), - &hosts_file), - - GNUNET_GETOPT_option_string ( - 'o', - "output", - "FILENAME", - gettext_noop ("name of the file for writing the main results"), - &output_filename), - - - GNUNET_GETOPT_option_string ( - 'p', - "peers", - "NETWORKSIZESPEC", - gettext_noop ( - "Number of peers to run in each round, separated by commas"), - &num_peer_spec), - - GNUNET_GETOPT_option_increment_uint ( - 'V', - "verbose", - gettext_noop ("be verbose (print progress information)"), - &verbose), - - GNUNET_GETOPT_option_relative_time ('w', - "wait", - "DELAY", - gettext_noop ("delay between rounds"), - &wait_time), - GNUNET_GETOPT_OPTION_END}; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + { GNUNET_GETOPT_option_uint( + 'C', + "connections", + "COUNT", + gettext_noop( + "limit to the number of connections to NSE services, 0 for none"), + &connection_limit), + GNUNET_GETOPT_option_string( + 'd', + "details", + "FILENAME", + gettext_noop( + "name of the file for writing connection information and statistics"), + &data_filename), + + GNUNET_GETOPT_option_string( + 'H', + "hosts", + "FILENAME", + gettext_noop( + "name of the file with the login information for the testbed"), + &hosts_file), + + GNUNET_GETOPT_option_string( + 'o', + "output", + "FILENAME", + gettext_noop("name of the file for writing the main results"), + &output_filename), + + + GNUNET_GETOPT_option_string( + 'p', + "peers", + "NETWORKSIZESPEC", + gettext_noop( + "Number of peers to run in each round, separated by commas"), + &num_peer_spec), + + GNUNET_GETOPT_option_increment_uint( + 'V', + "verbose", + gettext_noop("be verbose (print progress information)"), + &verbose), + + GNUNET_GETOPT_option_relative_time('w', + "wait", + "DELAY", + gettext_noop("delay between rounds"), + &wait_time), + GNUNET_GETOPT_OPTION_END }; + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; if ( GNUNET_OK != - GNUNET_PROGRAM_run (argc, - argv, - "nse-profiler", - gettext_noop ( - "Measure quality and performance of the NSE service."), - options, - &run, - NULL)) + GNUNET_PROGRAM_run(argc, + argv, + "nse-profiler", + gettext_noop( + "Measure quality and performance of the NSE service."), + options, + &run, + NULL)) ok = 1; return ok; } diff --git a/src/nse/gnunet-nse.c b/src/nse/gnunet-nse.c index 73b80e28b..3735373b5 100644 --- a/src/nse/gnunet-nse.c +++ b/src/nse/gnunet-nse.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nse/gnunet-nse.c @@ -44,14 +44,14 @@ static int status; * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - (void) cls; + (void)cls; if (NULL != nse) - { - GNUNET_NSE_disconnect (nse); - nse = NULL; - } + { + GNUNET_NSE_disconnect(nse); + nse = NULL; + } } @@ -65,19 +65,19 @@ do_shutdown (void *cls) * of the size estimation values seen */ static void -handle_estimate (void *cls, - struct GNUNET_TIME_Absolute timestamp, - double estimate, - double std_dev) +handle_estimate(void *cls, + struct GNUNET_TIME_Absolute timestamp, + double estimate, + double std_dev) { - (void) cls; + (void)cls; status = 0; - fprintf (stdout, - "%llu %f %f %f\n", - (unsigned long long) timestamp.abs_value_us, - GNUNET_NSE_log_estimate_to_n (estimate), - estimate, - std_dev); + fprintf(stdout, + "%llu %f %f %f\n", + (unsigned long long)timestamp.abs_value_us, + GNUNET_NSE_log_estimate_to_n(estimate), + estimate, + std_dev); } @@ -90,16 +90,16 @@ handle_estimate (void *cls, * @param cfg configuration handle */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - (void) cls; - (void) args; - (void) cfgfile; - nse = GNUNET_NSE_connect (cfg, &handle_estimate, NULL); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL); + (void)cls; + (void)args; + (void)cfgfile; + nse = GNUNET_NSE_connect(cfg, &handle_estimate, NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); } @@ -109,21 +109,22 @@ run (void *cls, * @return 0 on success */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { static struct GNUNET_GETOPT_CommandLineOption options[] = { - GNUNET_GETOPT_OPTION_END}; + GNUNET_GETOPT_OPTION_END + }; status = 1; if (GNUNET_OK != - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-nse", - gettext_noop ( - "Show network size estimates from NSE service."), - options, - &run, - NULL)) + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-nse", + gettext_noop( + "Show network size estimates from NSE service."), + options, + &run, + NULL)) return 2; return status; } diff --git a/src/nse/gnunet-service-nse.c b/src/nse/gnunet-service-nse.c index fd83d2b67..d71c62541 100644 --- a/src/nse/gnunet-service-nse.c +++ b/src/nse/gnunet-service-nse.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2009, 2010, 2011, 2012, 2013, 2016 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -76,7 +76,7 @@ GNUNET_MQ_PREF_CORK_ALLOWED) #if FREEBSD -#define log2(a) (log (a) / log (2)) +#define log2(a) (log(a) / log(2)) #endif /** @@ -117,9 +117,7 @@ static struct GNUNET_BIO_WriteHandle *histogram; /** * Per-peer information. */ -struct NSEPeerEntry -{ - +struct NSEPeerEntry { /** * Core handle for sending messages to this peer. */ @@ -143,7 +141,6 @@ struct NSEPeerEntry int previous_round; #if ENABLE_NSE_HISTOGRAM - /** * Amount of messages received from this peer on this round. */ @@ -158,7 +155,6 @@ struct NSEPeerEntry * Which size did we tell the peer the network is? */ unsigned int last_transmitted_size; - #endif }; @@ -170,8 +166,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * peer's timer has run out before receiving a * valid reply from another peer. */ -struct GNUNET_NSE_FloodMessage -{ +struct GNUNET_NSE_FloodMessage { /** * Type: #GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD */ @@ -322,7 +317,7 @@ static uint64_t my_proof; * @param em message to fill in */ static void -setup_estimate_message (struct GNUNET_NSE_ClientMessage *em) +setup_estimate_message(struct GNUNET_NSE_ClientMessage *em) { double mean; double sum; @@ -345,19 +340,19 @@ setup_estimate_message (struct GNUNET_NSE_ClientMessage *em) sumweight = 0.0; variance = 0.0; for (unsigned int i = 0; i < estimate_count; i++) - { - unsigned int j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE; + { + unsigned int j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE; - val = htonl (size_estimate_messages[j].matching_bits); - weight = estimate_count + 1 - i; + val = htonl(size_estimate_messages[j].matching_bits); + weight = estimate_count + 1 - i; - temp = weight + sumweight; - q = val - mean; - r = q * weight / temp; - mean += r; - sum += sumweight * q * r; - sumweight = temp; - } + temp = weight + sumweight; + q = val - mean; + r = q * weight / temp; + mean += r; + sum += sumweight * q * r; + sumweight = temp; + } if (estimate_count > 0) variance = (sum / sumweight) * estimate_count / (estimate_count - 1.0); #else @@ -371,44 +366,44 @@ setup_estimate_message (struct GNUNET_NSE_ClientMessage *em) mean = 0.0; for (unsigned int i = 0; i < estimate_count; i++) - { - unsigned int j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE; + { + unsigned int j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE; - val = htonl (size_estimate_messages[j].matching_bits); - sum += val; - vsq += val * val; - } + val = htonl(size_estimate_messages[j].matching_bits); + sum += val; + vsq += val * val; + } if (0 != estimate_count) - { - mean = sum / estimate_count; - variance = (vsq - mean * sum) / - (estimate_count - 1.0); // terrible for numerical stability... - } + { + mean = sum / estimate_count; + variance = (vsq - mean * sum) / + (estimate_count - 1.0); // terrible for numerical stability... + } #endif if (variance >= 0) - std_dev = sqrt (variance); + std_dev = sqrt(variance); else std_dev = variance; /* must be infinity due to estimate_count == 0 */ current_std_dev = std_dev; current_size_estimate = mean; - em->header.size = htons (sizeof (struct GNUNET_NSE_ClientMessage)); - em->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE); - em->reserved = htonl (0); - em->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ()); + em->header.size = htons(sizeof(struct GNUNET_NSE_ClientMessage)); + em->header.type = htons(GNUNET_MESSAGE_TYPE_NSE_ESTIMATE); + em->reserved = htonl(0); + em->timestamp = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get()); { double se = mean - 0.332747; - unsigned int j = GNUNET_CONTAINER_multipeermap_size (peers); + unsigned int j = GNUNET_CONTAINER_multipeermap_size(peers); if (0 == j) j = 1; /* Avoid log2(0); can only happen if CORE didn't report - connection to self yet */ - nsize = log2 (j); - em->size_estimate = GNUNET_hton_double (GNUNET_MAX (se, nsize)); - em->std_deviation = GNUNET_hton_double (std_dev); - GNUNET_STATISTICS_set (stats, - "# nodes in the network (estimate)", - (uint64_t) pow (2, GNUNET_MAX (se, nsize)), - GNUNET_NO); + connection to self yet */ + nsize = log2(j); + em->size_estimate = GNUNET_hton_double(GNUNET_MAX(se, nsize)); + em->std_deviation = GNUNET_hton_double(std_dev); + GNUNET_STATISTICS_set(stats, + "# nodes in the network (estimate)", + (uint64_t)pow(2, GNUNET_MAX(se, nsize)), + GNUNET_NO); } } @@ -423,21 +418,21 @@ setup_estimate_message (struct GNUNET_NSE_ClientMessage *em) * @param message the message received */ static void -handle_start (void *cls, const struct GNUNET_MessageHeader *message) +handle_start(void *cls, const struct GNUNET_MessageHeader *message) { struct GNUNET_SERVICE_Client *client = cls; struct GNUNET_MQ_Handle *mq; struct GNUNET_NSE_ClientMessage em; struct GNUNET_MQ_Envelope *env; - (void) message; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received START message from client\n"); - mq = GNUNET_SERVICE_client_get_mq (client); - GNUNET_notification_context_add (nc, mq); - setup_estimate_message (&em); - env = GNUNET_MQ_msg_copy (&em.header); - GNUNET_MQ_send (mq, env); - GNUNET_SERVICE_client_continue (client); + (void)message; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received START message from client\n"); + mq = GNUNET_SERVICE_client_get_mq(client); + GNUNET_notification_context_add(nc, mq); + setup_estimate_message(&em); + env = GNUNET_MQ_msg_copy(&em.header); + GNUNET_MQ_send(mq, env); + GNUNET_SERVICE_client_continue(client); } @@ -448,16 +443,16 @@ handle_start (void *cls, const struct GNUNET_MessageHeader *message) * @param matching_bits number of matching bits to consider */ static double -get_matching_bits_delay (uint32_t matching_bits) +get_matching_bits_delay(uint32_t matching_bits) { /* Calculated as: S + f/2 - (f / pi) * (atan(x - p')) */ // S is next_timestamp (ignored in return value) // f is frequency (gnunet_nse_interval) // x is matching_bits // p' is current_size_estimate - return ((double) gnunet_nse_interval.rel_value_us / (double) 2.0) - + return ((double)gnunet_nse_interval.rel_value_us / (double)2.0) - ((gnunet_nse_interval.rel_value_us / M_PI) * - atan (matching_bits - current_size_estimate)); + atan(matching_bits - current_size_estimate)); } @@ -468,21 +463,21 @@ get_matching_bits_delay (uint32_t matching_bits) * @return random delay to apply */ static struct GNUNET_TIME_Relative -get_delay_randomization (uint32_t matching_bits) +get_delay_randomization(uint32_t matching_bits) { #if USE_RANDOM_DELAYS struct GNUNET_TIME_Relative ret; uint32_t i; double d; - d = get_matching_bits_delay (matching_bits); - i = (uint32_t) (d / (double) (hop_count_max + 1)); + d = get_matching_bits_delay(matching_bits); + i = (uint32_t)(d / (double)(hop_count_max + 1)); ret.rel_value_us = i; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Randomizing flood using latencies up to %s\n", - GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Randomizing flood using latencies up to %s\n", + GNUNET_STRINGS_relative_time_to_string(ret, GNUNET_YES)); ret.rel_value_us = - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, i + 1); + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, i + 1); return ret; #else return GNUNET_TIME_UNIT_ZERO; @@ -498,18 +493,18 @@ get_delay_randomization (uint32_t matching_bits) * @param result where to write the resulting hash */ static void -pow_hash (const void *buf, size_t buf_len, struct GNUNET_HashCode *result) +pow_hash(const void *buf, size_t buf_len, struct GNUNET_HashCode *result) { - GNUNET_break ( - 0 == gcry_kdf_derive (buf, - buf_len, - GCRY_KDF_SCRYPT, - 1 /* subalgo */, - "gnunet-proof-of-work", - strlen ("gnunet-proof-of-work"), - 2 /* iterations; keep cost of individual op small */, - sizeof (struct GNUNET_HashCode), - result)); + GNUNET_break( + 0 == gcry_kdf_derive(buf, + buf_len, + GCRY_KDF_SCRYPT, + 1 /* subalgo */, + "gnunet-proof-of-work", + strlen("gnunet-proof-of-work"), + 2 /* iterations; keep cost of individual op small */, + sizeof(struct GNUNET_HashCode), + result)); } @@ -521,17 +516,17 @@ pow_hash (const void *buf, size_t buf_len, struct GNUNET_HashCode *result) * @return number of matching bits */ static uint32_t -get_matching_bits (struct GNUNET_TIME_Absolute timestamp, - const struct GNUNET_PeerIdentity *id) +get_matching_bits(struct GNUNET_TIME_Absolute timestamp, + const struct GNUNET_PeerIdentity *id) { struct GNUNET_HashCode timestamp_hash; struct GNUNET_HashCode pid_hash; - GNUNET_CRYPTO_hash (×tamp.abs_value_us, - sizeof (timestamp.abs_value_us), - ×tamp_hash); - GNUNET_CRYPTO_hash (id, sizeof (struct GNUNET_PeerIdentity), &pid_hash); - return GNUNET_CRYPTO_hash_matching_bits (×tamp_hash, &pid_hash); + GNUNET_CRYPTO_hash(×tamp.abs_value_us, + sizeof(timestamp.abs_value_us), + ×tamp_hash); + GNUNET_CRYPTO_hash(id, sizeof(struct GNUNET_PeerIdentity), &pid_hash); + return GNUNET_CRYPTO_hash_matching_bits(×tamp_hash, &pid_hash); } @@ -544,7 +539,7 @@ get_matching_bits (struct GNUNET_TIME_Absolute timestamp, * @return delay that should be applied */ static struct GNUNET_TIME_Relative -get_transmit_delay (int round_offset) +get_transmit_delay(int round_offset) { struct GNUNET_TIME_Relative ret; struct GNUNET_TIME_Absolute tgt; @@ -552,36 +547,37 @@ get_transmit_delay (int round_offset) uint32_t matching_bits; switch (round_offset) - { - case -1: - /* previous round is randomized between 0 and 50 ms */ + { + case -1: + /* previous round is randomized between 0 and 50 ms */ #if USE_RANDOM_DELAYS - ret.rel_value_us = - GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, 50); + ret.rel_value_us = + GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, 50); #else - ret = GNUNET_TIME_UNIT_ZERO; + ret = GNUNET_TIME_UNIT_ZERO; #endif - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Transmitting previous round behind schedule in %s\n", - GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES)); - return ret; - case 0: - /* current round is based on best-known matching_bits */ - matching_bits = - ntohl (size_estimate_messages[estimate_index].matching_bits); - dist_delay = get_matching_bits_delay (matching_bits); - dist_delay += get_delay_randomization (matching_bits).rel_value_us; - ret.rel_value_us = (uint64_t) dist_delay; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "For round %s, delay for %u matching bits is %s\n", - GNUNET_STRINGS_absolute_time_to_string (current_timestamp), - (unsigned int) matching_bits, - GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES)); - /* now consider round start time and add delay to it */ - tgt = GNUNET_TIME_absolute_add (current_timestamp, ret); - return GNUNET_TIME_absolute_get_remaining (tgt); - } - GNUNET_break (0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Transmitting previous round behind schedule in %s\n", + GNUNET_STRINGS_relative_time_to_string(ret, GNUNET_YES)); + return ret; + + case 0: + /* current round is based on best-known matching_bits */ + matching_bits = + ntohl(size_estimate_messages[estimate_index].matching_bits); + dist_delay = get_matching_bits_delay(matching_bits); + dist_delay += get_delay_randomization(matching_bits).rel_value_us; + ret.rel_value_us = (uint64_t)dist_delay; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "For round %s, delay for %u matching bits is %s\n", + GNUNET_STRINGS_absolute_time_to_string(current_timestamp), + (unsigned int)matching_bits, + GNUNET_STRINGS_relative_time_to_string(ret, GNUNET_YES)); + /* now consider round start time and add delay to it */ + tgt = GNUNET_TIME_absolute_add(current_timestamp, ret); + return GNUNET_TIME_absolute_get_remaining(tgt); + } + GNUNET_break(0); return GNUNET_TIME_UNIT_FOREVER_REL; } @@ -592,7 +588,7 @@ get_transmit_delay (int round_offset) * @param cls the `struct NSEPeerEntry *` */ static void -transmit_task_cb (void *cls) +transmit_task_cb(void *cls) { struct NSEPeerEntry *peer_entry = cls; unsigned int idx; @@ -601,51 +597,51 @@ transmit_task_cb (void *cls) peer_entry->transmit_task = NULL; idx = estimate_index; if (GNUNET_NO == peer_entry->previous_round) - { - idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE; - peer_entry->previous_round = GNUNET_YES; - peer_entry->transmit_task = - GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0), - &transmit_task_cb, - peer_entry); - } - if ((0 == ntohl (size_estimate_messages[idx].hop_count)) && + { + idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE; + peer_entry->previous_round = GNUNET_YES; + peer_entry->transmit_task = + GNUNET_SCHEDULER_add_delayed(get_transmit_delay(0), + &transmit_task_cb, + peer_entry); + } + if ((0 == ntohl(size_estimate_messages[idx].hop_count)) && (NULL != proof_task)) - { - GNUNET_STATISTICS_update (stats, - "# flood messages not generated (no proof yet)", - 1, - GNUNET_NO); - return; - } - if (0 == ntohs (size_estimate_messages[idx].header.size)) - { - GNUNET_STATISTICS_update (stats, - "# flood messages not generated (lack of history)", - 1, - GNUNET_NO); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "In round %s, sending to `%s' estimate with %u bits\n", - GNUNET_STRINGS_absolute_time_to_string ( - GNUNET_TIME_absolute_ntoh ( - size_estimate_messages[idx].timestamp)), - GNUNET_i2s (peer_entry->id), - (unsigned int) ntohl (size_estimate_messages[idx].matching_bits)); - if (0 == ntohl (size_estimate_messages[idx].hop_count)) - GNUNET_STATISTICS_update (stats, "# flood messages started", 1, GNUNET_NO); - GNUNET_STATISTICS_update (stats, - "# flood messages transmitted", - 1, - GNUNET_NO); + { + GNUNET_STATISTICS_update(stats, + "# flood messages not generated (no proof yet)", + 1, + GNUNET_NO); + return; + } + if (0 == ntohs(size_estimate_messages[idx].header.size)) + { + GNUNET_STATISTICS_update(stats, + "# flood messages not generated (lack of history)", + 1, + GNUNET_NO); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "In round %s, sending to `%s' estimate with %u bits\n", + GNUNET_STRINGS_absolute_time_to_string( + GNUNET_TIME_absolute_ntoh( + size_estimate_messages[idx].timestamp)), + GNUNET_i2s(peer_entry->id), + (unsigned int)ntohl(size_estimate_messages[idx].matching_bits)); + if (0 == ntohl(size_estimate_messages[idx].hop_count)) + GNUNET_STATISTICS_update(stats, "# flood messages started", 1, GNUNET_NO); + GNUNET_STATISTICS_update(stats, + "# flood messages transmitted", + 1, + GNUNET_NO); #if ENABLE_NSE_HISTOGRAM peer_entry->transmitted_messages++; peer_entry->last_transmitted_size = - ntohl (size_estimate_messages[idx].matching_bits); + ntohl(size_estimate_messages[idx].matching_bits); #endif - env = GNUNET_MQ_msg_copy (&size_estimate_messages[idx].header); - GNUNET_MQ_send (peer_entry->mq, env); + env = GNUNET_MQ_msg_copy(&size_estimate_messages[idx].header); + GNUNET_MQ_send(peer_entry->mq, env); } @@ -656,12 +652,12 @@ transmit_task_cb (void *cls) * clients. */ static void -update_network_size_estimate () +update_network_size_estimate() { struct GNUNET_NSE_ClientMessage em; - setup_estimate_message (&em); - GNUNET_notification_context_broadcast (nc, &em.header, GNUNET_YES); + setup_estimate_message(&em); + GNUNET_notification_context_broadcast(nc, &em.header, GNUNET_YES); } @@ -673,31 +669,31 @@ update_network_size_estimate () * @param ts timestamp to use */ static void -setup_flood_message (unsigned int slot, struct GNUNET_TIME_Absolute ts) +setup_flood_message(unsigned int slot, struct GNUNET_TIME_Absolute ts) { struct GNUNET_NSE_FloodMessage *fm; uint32_t matching_bits; - matching_bits = get_matching_bits (ts, &my_identity); + matching_bits = get_matching_bits(ts, &my_identity); fm = &size_estimate_messages[slot]; - fm->header.size = htons (sizeof (struct GNUNET_NSE_FloodMessage)); - fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD); - fm->hop_count = htonl (0); - fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND); + fm->header.size = htons(sizeof(struct GNUNET_NSE_FloodMessage)); + fm->header.type = htons(GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD); + fm->hop_count = htonl(0); + fm->purpose.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_NSE_SEND); fm->purpose.size = - htonl (sizeof (struct GNUNET_NSE_FloodMessage) - - sizeof (struct GNUNET_MessageHeader) - sizeof (uint32_t) - - sizeof (struct GNUNET_CRYPTO_EddsaSignature)); - fm->matching_bits = htonl (matching_bits); - fm->timestamp = GNUNET_TIME_absolute_hton (ts); + htonl(sizeof(struct GNUNET_NSE_FloodMessage) - + sizeof(struct GNUNET_MessageHeader) - sizeof(uint32_t) - + sizeof(struct GNUNET_CRYPTO_EddsaSignature)); + fm->matching_bits = htonl(matching_bits); + fm->timestamp = GNUNET_TIME_absolute_hton(ts); fm->origin = my_identity; fm->proof_of_work = my_proof; if (nse_work_required > 0) - GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_private_key, - &fm->purpose, - &fm->signature)); + GNUNET_assert(GNUNET_OK == GNUNET_CRYPTO_eddsa_sign(my_private_key, + &fm->purpose, + &fm->signature)); else - memset (&fm->signature, 0, sizeof (fm->signature)); + memset(&fm->signature, 0, sizeof(fm->signature)); } @@ -711,34 +707,34 @@ setup_flood_message (unsigned int slot, struct GNUNET_TIME_Absolute ts) * @return #GNUNET_OK (continue to iterate) */ static int -schedule_current_round (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +schedule_current_round(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct NSEPeerEntry *peer_entry = value; struct GNUNET_TIME_Relative delay; - (void) cls; - (void) key; + (void)cls; + (void)key; if (NULL != peer_entry->transmit_task) - { - GNUNET_SCHEDULER_cancel (peer_entry->transmit_task); - peer_entry->previous_round = GNUNET_NO; - } + { + GNUNET_SCHEDULER_cancel(peer_entry->transmit_task); + peer_entry->previous_round = GNUNET_NO; + } #if ENABLE_NSE_HISTOGRAM if (peer_entry->received_messages > 1) - GNUNET_STATISTICS_update (stats, - "# extra messages", - peer_entry->received_messages - 1, - GNUNET_NO); + GNUNET_STATISTICS_update(stats, + "# extra messages", + peer_entry->received_messages - 1, + GNUNET_NO); peer_entry->transmitted_messages = 0; peer_entry->last_transmitted_size = 0; peer_entry->received_messages = 0; #endif delay = - get_transmit_delay ((GNUNET_NO == peer_entry->previous_round) ? -1 : 0); + get_transmit_delay((GNUNET_NO == peer_entry->previous_round) ? -1 : 0); peer_entry->transmit_task = - GNUNET_SCHEDULER_add_delayed (delay, &transmit_task_cb, peer_entry); + GNUNET_SCHEDULER_add_delayed(delay, &transmit_task_cb, peer_entry); return GNUNET_OK; } @@ -749,46 +745,46 @@ schedule_current_round (void *cls, * @param cls unused */ static void -update_flood_message (void *cls) +update_flood_message(void *cls) { struct GNUNET_TIME_Relative offset; - (void) cls; + (void)cls; flood_task = NULL; - offset = GNUNET_TIME_absolute_get_remaining (next_timestamp); + offset = GNUNET_TIME_absolute_get_remaining(next_timestamp); if (0 != offset.rel_value_us) - { - /* somehow run early, delay more */ - flood_task = - GNUNET_SCHEDULER_add_delayed (offset, &update_flood_message, NULL); - return; - } + { + /* somehow run early, delay more */ + flood_task = + GNUNET_SCHEDULER_add_delayed(offset, &update_flood_message, NULL); + return; + } estimate_index = (estimate_index + 1) % HISTORY_SIZE; if (estimate_count < HISTORY_SIZE) estimate_count++; current_timestamp = next_timestamp; next_timestamp = - GNUNET_TIME_absolute_add (current_timestamp, gnunet_nse_interval); + GNUNET_TIME_absolute_add(current_timestamp, gnunet_nse_interval); if ((current_timestamp.abs_value_us == - GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value_us) && - (get_matching_bits (current_timestamp, &my_identity) < - ntohl (next_message.matching_bits))) - { - /* we received a message for this round way early, use it! */ - size_estimate_messages[estimate_index] = next_message; - size_estimate_messages[estimate_index].hop_count = - htonl (1 + ntohl (next_message.hop_count)); - } + GNUNET_TIME_absolute_ntoh(next_message.timestamp).abs_value_us) && + (get_matching_bits(current_timestamp, &my_identity) < + ntohl(next_message.matching_bits))) + { + /* we received a message for this round way early, use it! */ + size_estimate_messages[estimate_index] = next_message; + size_estimate_messages[estimate_index].hop_count = + htonl(1 + ntohl(next_message.hop_count)); + } else - setup_flood_message (estimate_index, current_timestamp); - next_message.matching_bits = htonl (0); /* reset for 'next' round */ + setup_flood_message(estimate_index, current_timestamp); + next_message.matching_bits = htonl(0); /* reset for 'next' round */ hop_count_max = 0; for (unsigned int i = 0; i < HISTORY_SIZE; i++) hop_count_max = - GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count), hop_count_max); - GNUNET_CONTAINER_multipeermap_iterate (peers, &schedule_current_round, NULL); + GNUNET_MAX(ntohl(size_estimate_messages[i].hop_count), hop_count_max); + GNUNET_CONTAINER_multipeermap_iterate(peers, &schedule_current_round, NULL); flood_task = - GNUNET_SCHEDULER_add_at (next_timestamp, &update_flood_message, NULL); + GNUNET_SCHEDULER_add_at(next_timestamp, &update_flood_message, NULL); } @@ -799,12 +795,12 @@ update_flood_message (void *cls) * @return the number of leading zero bits. */ static unsigned int -count_leading_zeroes (const struct GNUNET_HashCode *hash) +count_leading_zeroes(const struct GNUNET_HashCode *hash) { unsigned int hash_count; hash_count = 0; - while (0 == GNUNET_CRYPTO_hash_get_bit (hash, hash_count)) + while (0 == GNUNET_CRYPTO_hash_get_bit(hash, hash_count)) hash_count++; return hash_count; } @@ -819,20 +815,20 @@ count_leading_zeroes (const struct GNUNET_HashCode *hash) * @return #GNUNET_YES if valid, #GNUNET_NO if not */ static int -check_proof_of_work (const struct GNUNET_CRYPTO_EddsaPublicKey *pkey, - uint64_t val) +check_proof_of_work(const struct GNUNET_CRYPTO_EddsaPublicKey *pkey, + uint64_t val) { - char buf[sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) + - sizeof (val)] GNUNET_ALIGN; + char buf[sizeof(struct GNUNET_CRYPTO_EddsaPublicKey) + + sizeof(val)] GNUNET_ALIGN; struct GNUNET_HashCode result; - GNUNET_memcpy (buf, &val, sizeof (val)); - GNUNET_memcpy (&buf[sizeof (val)], - pkey, - sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)); - pow_hash (buf, sizeof (buf), &result); - return (count_leading_zeroes (&result) >= nse_work_required) ? GNUNET_YES - : GNUNET_NO; + GNUNET_memcpy(buf, &val, sizeof(val)); + GNUNET_memcpy(&buf[sizeof(val)], + pkey, + sizeof(struct GNUNET_CRYPTO_EddsaPublicKey)); + pow_hash(buf, sizeof(buf), &result); + return (count_leading_zeroes(&result) >= nse_work_required) ? GNUNET_YES + : GNUNET_NO; } @@ -840,20 +836,20 @@ check_proof_of_work (const struct GNUNET_CRYPTO_EddsaPublicKey *pkey, * Write our current proof to disk. */ static void -write_proof () +write_proof() { char *proof; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof)) + GNUNET_CONFIGURATION_get_value_filename(cfg, "NSE", "PROOFFILE", &proof)) return; - if (sizeof (my_proof) != GNUNET_DISK_fn_write (proof, - &my_proof, - sizeof (my_proof), - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", proof); - GNUNET_free (proof); + if (sizeof(my_proof) != GNUNET_DISK_fn_write(proof, + &my_proof, + sizeof(my_proof), + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "write", proof); + GNUNET_free(proof); } @@ -863,57 +859,57 @@ write_proof () * @param cls closure (unused) */ static void -find_proof (void *cls) +find_proof(void *cls) { #define ROUND_SIZE 10 uint64_t counter; - char buf[sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) + - sizeof (uint64_t)] GNUNET_ALIGN; + char buf[sizeof(struct GNUNET_CRYPTO_EddsaPublicKey) + + sizeof(uint64_t)] GNUNET_ALIGN; struct GNUNET_HashCode result; unsigned int i; - (void) cls; + (void)cls; proof_task = NULL; - GNUNET_memcpy (&buf[sizeof (uint64_t)], - &my_identity, - sizeof (struct GNUNET_PeerIdentity)); + GNUNET_memcpy(&buf[sizeof(uint64_t)], + &my_identity, + sizeof(struct GNUNET_PeerIdentity)); i = 0; counter = my_proof; while ((counter != UINT64_MAX) && (i < ROUND_SIZE)) - { - GNUNET_memcpy (buf, &counter, sizeof (uint64_t)); - pow_hash (buf, sizeof (buf), &result); - if (nse_work_required <= count_leading_zeroes (&result)) { - my_proof = counter; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Proof of work found: %llu!\n", - (unsigned long long) GNUNET_ntohll (counter)); - write_proof (); - setup_flood_message (estimate_index, current_timestamp); - return; + GNUNET_memcpy(buf, &counter, sizeof(uint64_t)); + pow_hash(buf, sizeof(buf), &result); + if (nse_work_required <= count_leading_zeroes(&result)) + { + my_proof = counter; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Proof of work found: %llu!\n", + (unsigned long long)GNUNET_ntohll(counter)); + write_proof(); + setup_flood_message(estimate_index, current_timestamp); + return; + } + counter++; + i++; } - counter++; - i++; - } if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Testing proofs currently at %llu\n", - (unsigned long long) counter); - /* remember progress every 100 rounds */ - my_proof = counter; - write_proof (); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Testing proofs currently at %llu\n", + (unsigned long long)counter); + /* remember progress every 100 rounds */ + my_proof = counter; + write_proof(); + } else - { - my_proof = counter; - } + { + my_proof = counter; + } proof_task = - GNUNET_SCHEDULER_add_delayed_with_priority (proof_find_delay, - GNUNET_SCHEDULER_PRIORITY_IDLE, - &find_proof, - NULL); + GNUNET_SCHEDULER_add_delayed_with_priority(proof_find_delay, + GNUNET_SCHEDULER_PRIORITY_IDLE, + &find_proof, + NULL); } @@ -927,28 +923,28 @@ find_proof (void *cls) * #GNUNET_NO if the key/signature don't verify */ static int -verify_message_crypto (const struct GNUNET_NSE_FloodMessage *incoming_flood) +verify_message_crypto(const struct GNUNET_NSE_FloodMessage *incoming_flood) { - if (GNUNET_YES != check_proof_of_work (&incoming_flood->origin.public_key, - incoming_flood->proof_of_work)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Proof of work invalid: %llu!\n", - (unsigned long long) GNUNET_ntohll ( - incoming_flood->proof_of_work)); - GNUNET_break_op (0); - return GNUNET_NO; - } + if (GNUNET_YES != check_proof_of_work(&incoming_flood->origin.public_key, + incoming_flood->proof_of_work)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Proof of work invalid: %llu!\n", + (unsigned long long)GNUNET_ntohll( + incoming_flood->proof_of_work)); + GNUNET_break_op(0); + return GNUNET_NO; + } if ((nse_work_required > 0) && (GNUNET_OK != - GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND, - &incoming_flood->purpose, - &incoming_flood->signature, - &incoming_flood->origin.public_key))) - { - GNUNET_break_op (0); - return GNUNET_NO; - } + GNUNET_CRYPTO_eddsa_verify(GNUNET_SIGNATURE_PURPOSE_NSE_SEND, + &incoming_flood->purpose, + &incoming_flood->signature, + &incoming_flood->origin.public_key))) + { + GNUNET_break_op(0); + return GNUNET_NO; + } return GNUNET_YES; } @@ -963,35 +959,35 @@ verify_message_crypto (const struct GNUNET_NSE_FloodMessage *incoming_flood) * @return #GNUNET_OK (continue to iterate) */ static int -update_flood_times (void *cls, - const struct GNUNET_PeerIdentity *key, - void *value) +update_flood_times(void *cls, + const struct GNUNET_PeerIdentity *key, + void *value) { struct NSEPeerEntry *exclude = cls; struct NSEPeerEntry *peer_entry = value; struct GNUNET_TIME_Relative delay; - (void) key; + (void)key; if (peer_entry == exclude) return GNUNET_OK; /* trigger of the update */ if (GNUNET_NO == peer_entry->previous_round) - { - /* still stuck in previous round, no point to update, check that - * we are active here though... */ - if (NULL == peer_entry->transmit_task) { - GNUNET_break (0); + /* still stuck in previous round, no point to update, check that + * we are active here though... */ + if (NULL == peer_entry->transmit_task) + { + GNUNET_break(0); + } + return GNUNET_OK; } - return GNUNET_OK; - } if (NULL != peer_entry->transmit_task) - { - GNUNET_SCHEDULER_cancel (peer_entry->transmit_task); - peer_entry->transmit_task = NULL; - } - delay = get_transmit_delay (0); + { + GNUNET_SCHEDULER_cancel(peer_entry->transmit_task); + peer_entry->transmit_task = NULL; + } + delay = get_transmit_delay(0); peer_entry->transmit_task = - GNUNET_SCHEDULER_add_delayed (delay, &transmit_task_cb, peer_entry); + GNUNET_SCHEDULER_add_delayed(delay, &transmit_task_cb, peer_entry); return GNUNET_OK; } @@ -1003,8 +999,8 @@ update_flood_times (void *cls, * @param incoming_flood received message */ static void -handle_p2p_estimate (void *cls, - const struct GNUNET_NSE_FloodMessage *incoming_flood) +handle_p2p_estimate(void *cls, + const struct GNUNET_NSE_FloodMessage *incoming_flood) { struct NSEPeerEntry *peer_entry = cls; struct GNUNET_TIME_Absolute ts; @@ -1015,34 +1011,34 @@ handle_p2p_estimate (void *cls, { uint64_t t; - t = GNUNET_TIME_absolute_get ().abs_value_us; + t = GNUNET_TIME_absolute_get().abs_value_us; if (NULL != lh) - GNUNET_TESTBED_LOGGER_write (lh, &t, sizeof (uint64_t)); + GNUNET_TESTBED_LOGGER_write(lh, &t, sizeof(uint64_t)); if (NULL != histogram) - GNUNET_BIO_write_int64 (histogram, t); + GNUNET_BIO_write_int64(histogram, t); } #endif - GNUNET_STATISTICS_update (stats, "# flood messages received", 1, GNUNET_NO); - matching_bits = ntohl (incoming_flood->matching_bits); + GNUNET_STATISTICS_update(stats, "# flood messages received", 1, GNUNET_NO); + matching_bits = ntohl(incoming_flood->matching_bits); #if DEBUG_NSE { char origin[5]; char pred[5]; struct GNUNET_PeerIdentity os; - GNUNET_snprintf (origin, - sizeof (origin), - "%s", - GNUNET_i2s (&incoming_flood->origin)); - GNUNET_snprintf (pred, sizeof (pred), "%s", GNUNET_i2s (peer_entry->id)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Flood at %s from `%s' via `%s' at `%s' with bits %u\n", - GNUNET_STRINGS_absolute_time_to_string ( - GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp)), - origin, - pred, - GNUNET_i2s (&my_identity), - (unsigned int) matching_bits); + GNUNET_snprintf(origin, + sizeof(origin), + "%s", + GNUNET_i2s(&incoming_flood->origin)); + GNUNET_snprintf(pred, sizeof(pred), "%s", GNUNET_i2s(peer_entry->id)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Flood at %s from `%s' via `%s' at `%s' with bits %u\n", + GNUNET_STRINGS_absolute_time_to_string( + GNUNET_TIME_absolute_ntoh(incoming_flood->timestamp)), + origin, + pred, + GNUNET_i2s(&my_identity), + (unsigned int)matching_bits); } #endif @@ -1050,122 +1046,122 @@ handle_p2p_estimate (void *cls, peer_entry->received_messages++; if (peer_entry->transmitted_messages > 0 && peer_entry->last_transmitted_size >= matching_bits) - GNUNET_STATISTICS_update (stats, "# cross messages", 1, GNUNET_NO); + GNUNET_STATISTICS_update(stats, "# cross messages", 1, GNUNET_NO); #endif - ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp); + ts = GNUNET_TIME_absolute_ntoh(incoming_flood->timestamp); if (ts.abs_value_us == current_timestamp.abs_value_us) idx = estimate_index; else if (ts.abs_value_us == current_timestamp.abs_value_us - gnunet_nse_interval.rel_value_us) idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE; else if (ts.abs_value_us == next_timestamp.abs_value_us) - { - if (matching_bits <= ntohl (next_message.matching_bits)) - return; /* ignore, simply too early/late */ - if (GNUNET_YES != verify_message_crypto (incoming_flood)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Peer %s is likely ill-configured!\n", - GNUNET_i2s (peer_entry->id)); - GNUNET_break_op (0); + if (matching_bits <= ntohl(next_message.matching_bits)) + return; /* ignore, simply too early/late */ + if (GNUNET_YES != verify_message_crypto(incoming_flood)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Peer %s is likely ill-configured!\n", + GNUNET_i2s(peer_entry->id)); + GNUNET_break_op(0); + return; + } + next_message = *incoming_flood; return; } - next_message = *incoming_flood; - return; - } else - { - GNUNET_STATISTICS_update (stats, - "# flood messages discarded (clock skew too large)", - 1, - GNUNET_NO); - return; - } - if (0 == (GNUNET_memcmp (peer_entry->id, &my_identity))) - { - /* send to self, update our own estimate IF this also comes from us! */ - if (0 == GNUNET_memcmp (&incoming_flood->origin, &my_identity)) - update_network_size_estimate (); - return; - } - if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits)) - { - /* Cancel transmission in the other direction, as this peer clearly has - up-to-date information already. Even if we didn't talk to this peer in - the previous round, we should no longer send it stale information as it - told us about the current round! */ - peer_entry->previous_round = GNUNET_YES; - if (idx != estimate_index) { - /* do not transmit information for the previous round to this peer - anymore (but allow current round) */ + GNUNET_STATISTICS_update(stats, + "# flood messages discarded (clock skew too large)", + 1, + GNUNET_NO); return; } - /* got up-to-date information for current round, cancel transmission to - * this peer altogether */ - if (NULL != peer_entry->transmit_task) + if (0 == (GNUNET_memcmp(peer_entry->id, &my_identity))) { - GNUNET_SCHEDULER_cancel (peer_entry->transmit_task); - peer_entry->transmit_task = NULL; + /* send to self, update our own estimate IF this also comes from us! */ + if (0 == GNUNET_memcmp(&incoming_flood->origin, &my_identity)) + update_network_size_estimate(); + return; } - return; - } - if (matching_bits < ntohl (size_estimate_messages[idx].matching_bits)) - { - if ((idx < estimate_index) && (peer_entry->previous_round == GNUNET_YES)) + if (matching_bits == ntohl(size_estimate_messages[idx].matching_bits)) { - peer_entry->previous_round = GNUNET_NO; + /* Cancel transmission in the other direction, as this peer clearly has + up-to-date information already. Even if we didn't talk to this peer in + the previous round, we should no longer send it stale information as it + told us about the current round! */ + peer_entry->previous_round = GNUNET_YES; + if (idx != estimate_index) + { + /* do not transmit information for the previous round to this peer + anymore (but allow current round) */ + return; + } + /* got up-to-date information for current round, cancel transmission to + * this peer altogether */ + if (NULL != peer_entry->transmit_task) + { + GNUNET_SCHEDULER_cancel(peer_entry->transmit_task); + peer_entry->transmit_task = NULL; + } + return; } - /* push back our result now, that peer is spreading bad information... */ - if (NULL != peer_entry->transmit_task) - GNUNET_SCHEDULER_cancel (peer_entry->transmit_task); - peer_entry->transmit_task = - GNUNET_SCHEDULER_add_now (&transmit_task_cb, peer_entry); - /* Not closer than our most recent message, no need to do work here */ - GNUNET_STATISTICS_update (stats, - "# flood messages ignored (had closer already)", - 1, - GNUNET_NO); - return; - } - if (GNUNET_YES != verify_message_crypto (incoming_flood)) - { - GNUNET_break_op (0); - return; - } - GNUNET_assert (matching_bits > - ntohl (size_estimate_messages[idx].matching_bits)); + if (matching_bits < ntohl(size_estimate_messages[idx].matching_bits)) + { + if ((idx < estimate_index) && (peer_entry->previous_round == GNUNET_YES)) + { + peer_entry->previous_round = GNUNET_NO; + } + /* push back our result now, that peer is spreading bad information... */ + if (NULL != peer_entry->transmit_task) + GNUNET_SCHEDULER_cancel(peer_entry->transmit_task); + peer_entry->transmit_task = + GNUNET_SCHEDULER_add_now(&transmit_task_cb, peer_entry); + /* Not closer than our most recent message, no need to do work here */ + GNUNET_STATISTICS_update(stats, + "# flood messages ignored (had closer already)", + 1, + GNUNET_NO); + return; + } + if (GNUNET_YES != verify_message_crypto(incoming_flood)) + { + GNUNET_break_op(0); + return; + } + GNUNET_assert(matching_bits > + ntohl(size_estimate_messages[idx].matching_bits)); /* Cancel transmission in the other direction, as this peer clearly has * up-to-date information already. */ peer_entry->previous_round = GNUNET_YES; if (idx == estimate_index) - { - /* cancel any activity for current round */ - if (NULL != peer_entry->transmit_task) { - GNUNET_SCHEDULER_cancel (peer_entry->transmit_task); - peer_entry->transmit_task = NULL; + /* cancel any activity for current round */ + if (NULL != peer_entry->transmit_task) + { + GNUNET_SCHEDULER_cancel(peer_entry->transmit_task); + peer_entry->transmit_task = NULL; + } } - } size_estimate_messages[idx] = *incoming_flood; size_estimate_messages[idx].hop_count = - htonl (ntohl (incoming_flood->hop_count) + 1); + htonl(ntohl(incoming_flood->hop_count) + 1); hop_count_max = - GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1, hop_count_max); - GNUNET_STATISTICS_set (stats, - "# estimated network diameter", - hop_count_max, - GNUNET_NO); + GNUNET_MAX(ntohl(incoming_flood->hop_count) + 1, hop_count_max); + GNUNET_STATISTICS_set(stats, + "# estimated network diameter", + hop_count_max, + GNUNET_NO); /* have a new, better size estimate, inform clients */ - update_network_size_estimate (); + update_network_size_estimate(); /* flood to rest */ - GNUNET_CONTAINER_multipeermap_iterate (peers, - &update_flood_times, - peer_entry); + GNUNET_CONTAINER_multipeermap_iterate(peers, + &update_flood_times, + peer_entry); } @@ -1177,33 +1173,33 @@ handle_p2p_estimate (void *cls, * @param peer peer identity this notification is about */ static void * -handle_core_connect (void *cls, - const struct GNUNET_PeerIdentity *peer, - struct GNUNET_MQ_Handle *mq) +handle_core_connect(void *cls, + const struct GNUNET_PeerIdentity *peer, + struct GNUNET_MQ_Handle *mq) { struct NSEPeerEntry *peer_entry; - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Peer `%s' connected to us\n", - GNUNET_i2s (peer)); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Peer `%s' connected to us\n", + GNUNET_i2s(peer)); /* set our default transmission options */ - GNUNET_MQ_set_options (mq, NSE_PRIORITY); + GNUNET_MQ_set_options(mq, NSE_PRIORITY); /* create our peer entry for this peer */ - peer_entry = GNUNET_new (struct NSEPeerEntry); + peer_entry = GNUNET_new(struct NSEPeerEntry); peer_entry->id = peer; peer_entry->mq = mq; - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put ( - peers, - peer_entry->id, - peer_entry, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_put( + peers, + peer_entry->id, + peer_entry, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); peer_entry->transmit_task = - GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1), - &transmit_task_cb, - peer_entry); - GNUNET_STATISTICS_update (stats, "# peers connected", 1, GNUNET_NO); + GNUNET_SCHEDULER_add_delayed(get_transmit_delay(-1), + &transmit_task_cb, + peer_entry); + GNUNET_STATISTICS_update(stats, "# peers connected", 1, GNUNET_NO); return peer_entry; } @@ -1217,25 +1213,25 @@ handle_core_connect (void *cls, * @parma internal_cls the `struct NSEPeerEntry` for the @a peer */ static void -handle_core_disconnect (void *cls, - const struct GNUNET_PeerIdentity *peer, - void *internal_cls) +handle_core_disconnect(void *cls, + const struct GNUNET_PeerIdentity *peer, + void *internal_cls) { struct NSEPeerEntry *pos = internal_cls; - (void) cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Peer `%s' disconnected from us\n", - GNUNET_i2s (peer)); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multipeermap_remove (peers, peer, pos)); + (void)cls; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Peer `%s' disconnected from us\n", + GNUNET_i2s(peer)); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multipeermap_remove(peers, peer, pos)); if (NULL != pos->transmit_task) - { - GNUNET_SCHEDULER_cancel (pos->transmit_task); - pos->transmit_task = NULL; - } - GNUNET_free (pos); - GNUNET_STATISTICS_update (stats, "# peers connected", -1, GNUNET_NO); + { + GNUNET_SCHEDULER_cancel(pos->transmit_task); + pos->transmit_task = NULL; + } + GNUNET_free(pos); + GNUNET_STATISTICS_update(stats, "# peers connected", -1, GNUNET_NO); } @@ -1248,11 +1244,11 @@ handle_core_disconnect (void *cls, * @param size the amount of data sent (ignored) */ static void -flush_comp_cb (void *cls, size_t size) +flush_comp_cb(void *cls, size_t size) { - (void) cls; - (void) size; - GNUNET_TESTBED_LOGGER_disconnect (lh); + (void)cls; + (void)size; + GNUNET_TESTBED_LOGGER_disconnect(lh); lh = NULL; } #endif @@ -1264,60 +1260,60 @@ flush_comp_cb (void *cls, size_t size) * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - (void) cls; + (void)cls; if (NULL != flood_task) - { - GNUNET_SCHEDULER_cancel (flood_task); - flood_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(flood_task); + flood_task = NULL; + } if (NULL != proof_task) - { - GNUNET_SCHEDULER_cancel (proof_task); - proof_task = NULL; - write_proof (); /* remember progress */ - } + { + GNUNET_SCHEDULER_cancel(proof_task); + proof_task = NULL; + write_proof(); /* remember progress */ + } if (NULL != nc) - { - GNUNET_notification_context_destroy (nc); - nc = NULL; - } + { + GNUNET_notification_context_destroy(nc); + nc = NULL; + } if (NULL != core_api) - { - GNUNET_CORE_disconnect (core_api); - core_api = NULL; - } + { + GNUNET_CORE_disconnect(core_api); + core_api = NULL; + } if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, GNUNET_NO); - stats = NULL; - } + { + GNUNET_STATISTICS_destroy(stats, GNUNET_NO); + stats = NULL; + } if (NULL != peers) - { - GNUNET_CONTAINER_multipeermap_destroy (peers); - peers = NULL; - } + { + GNUNET_CONTAINER_multipeermap_destroy(peers); + peers = NULL; + } if (NULL != my_private_key) - { - GNUNET_free (my_private_key); - my_private_key = NULL; - } + { + GNUNET_free(my_private_key); + my_private_key = NULL; + } #if ENABLE_NSE_HISTOGRAM if (NULL != logger_test) - { - GNUNET_CLIENT_service_test_cancel (logger_test); - logger_test = NULL; - } + { + GNUNET_CLIENT_service_test_cancel(logger_test); + logger_test = NULL; + } if (NULL != lh) - { - GNUNET_TESTBED_LOGGER_flush (lh, &flush_comp_cb, NULL); - } + { + GNUNET_TESTBED_LOGGER_flush(lh, &flush_comp_cb, NULL); + } if (NULL != histogram) - { - GNUNET_BIO_write_close (histogram); - histogram = NULL; - } + { + GNUNET_BIO_write_close(histogram); + histogram = NULL; + } #endif } @@ -1329,38 +1325,38 @@ shutdown_task (void *cls) * @param identity the public identity of this peer */ static void -core_init (void *cls, const struct GNUNET_PeerIdentity *identity) +core_init(void *cls, const struct GNUNET_PeerIdentity *identity) { struct GNUNET_TIME_Absolute now; struct GNUNET_TIME_Absolute prev_time; - (void) cls; + (void)cls; if (NULL == identity) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection to core FAILED!\n"); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_assert (0 == GNUNET_memcmp (&my_identity, identity)); - now = GNUNET_TIME_absolute_get (); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Connection to core FAILED!\n"); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_assert(0 == GNUNET_memcmp(&my_identity, identity)); + now = GNUNET_TIME_absolute_get(); current_timestamp.abs_value_us = (now.abs_value_us / gnunet_nse_interval.rel_value_us) * gnunet_nse_interval.rel_value_us; next_timestamp = - GNUNET_TIME_absolute_add (current_timestamp, gnunet_nse_interval); + GNUNET_TIME_absolute_add(current_timestamp, gnunet_nse_interval); estimate_index = HISTORY_SIZE - 1; estimate_count = 0; - if (GNUNET_YES == check_proof_of_work (&my_identity.public_key, my_proof)) - { - int idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE; - prev_time.abs_value_us = - current_timestamp.abs_value_us - gnunet_nse_interval.rel_value_us; - setup_flood_message (idx, prev_time); - setup_flood_message (estimate_index, current_timestamp); - estimate_count++; - } + if (GNUNET_YES == check_proof_of_work(&my_identity.public_key, my_proof)) + { + int idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE; + prev_time.abs_value_us = + current_timestamp.abs_value_us - gnunet_nse_interval.rel_value_us; + setup_flood_message(idx, prev_time); + setup_flood_message(estimate_index, current_timestamp); + estimate_count++; + } flood_task = - GNUNET_SCHEDULER_add_at (next_timestamp, &update_flood_message, NULL); + GNUNET_SCHEDULER_add_at(next_timestamp, &update_flood_message, NULL); } @@ -1374,21 +1370,21 @@ core_init (void *cls, const struct GNUNET_PeerIdentity *identity) * #GNUNET_SYSERR if the configuration is invalid */ static void -status_cb (void *cls, int status) +status_cb(void *cls, int status) { - (void) cls; + (void)cls; logger_test = NULL; if (GNUNET_YES != status) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Testbed logger not running\n"); - return; - } - if (NULL == (lh = GNUNET_TESTBED_LOGGER_connect (cfg))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Cannot connect to the testbed logger. Exiting.\n"); - GNUNET_SCHEDULER_shutdown (); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Testbed logger not running\n"); + return; + } + if (NULL == (lh = GNUNET_TESTBED_LOGGER_connect(cfg))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Cannot connect to the testbed logger. Exiting.\n"); + GNUNET_SCHEDULER_shutdown(); + } } #endif @@ -1401,127 +1397,127 @@ status_cb (void *cls, int status) * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *service) { struct GNUNET_MQ_MessageHandler core_handlers[] = - {GNUNET_MQ_hd_fixed_size (p2p_estimate, - GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD, - struct GNUNET_NSE_FloodMessage, - NULL), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_fixed_size(p2p_estimate, + GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD, + struct GNUNET_NSE_FloodMessage, + NULL), + GNUNET_MQ_handler_end() }; char *proof; struct GNUNET_CRYPTO_EddsaPrivateKey *pk; - (void) cls; - (void) service; + (void)cls; + (void)service; cfg = c; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, - "NSE", - "INTERVAL", - &gnunet_nse_interval)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "NSE", "INTERVAL"); - GNUNET_SCHEDULER_shutdown (); - return; - } - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, - "NSE", - "WORKDELAY", - &proof_find_delay)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "NSE", "WORKDELAY"); - GNUNET_SCHEDULER_shutdown (); - return; - } - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, - "NSE", - "WORKBITS", - &nse_work_required)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "NSE", "WORKBITS"); - GNUNET_SCHEDULER_shutdown (); - return; - } - if (nse_work_required >= sizeof (struct GNUNET_HashCode) * 8) - { - GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, - "NSE", - "WORKBITS", - _ ("Value is too large.\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time(cfg, + "NSE", + "INTERVAL", + &gnunet_nse_interval)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "NSE", "INTERVAL"); + GNUNET_SCHEDULER_shutdown(); + return; + } + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time(cfg, + "NSE", + "WORKDELAY", + &proof_find_delay)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "NSE", "WORKDELAY"); + GNUNET_SCHEDULER_shutdown(); + return; + } + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, + "NSE", + "WORKBITS", + &nse_work_required)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "NSE", "WORKBITS"); + GNUNET_SCHEDULER_shutdown(); + return; + } + if (nse_work_required >= sizeof(struct GNUNET_HashCode) * 8) + { + GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_ERROR, + "NSE", + "WORKBITS", + _("Value is too large.\n")); + GNUNET_SCHEDULER_shutdown(); + return; + } #if ENABLE_NSE_HISTOGRAM { char *histogram_dir; char *histogram_fn; - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_filename (cfg, - "NSE", - "HISTOGRAM_DIR", - &histogram_dir)) - { - GNUNET_assert ( - 0 < GNUNET_asprintf (&histogram_fn, "%s/timestamps", histogram_dir)); - GNUNET_free (histogram_dir); - histogram = GNUNET_BIO_write_open (histogram_fn); - if (NULL == histogram) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Unable to open histogram file `%s'\n", - histogram_fn); - GNUNET_free (histogram_fn); - } - logger_test = GNUNET_CLIENT_service_test ("testbed-logger", - cfg, - GNUNET_TIME_UNIT_SECONDS, - &status_cb, - NULL); + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_filename(cfg, + "NSE", + "HISTOGRAM_DIR", + &histogram_dir)) + { + GNUNET_assert( + 0 < GNUNET_asprintf(&histogram_fn, "%s/timestamps", histogram_dir)); + GNUNET_free(histogram_dir); + histogram = GNUNET_BIO_write_open(histogram_fn); + if (NULL == histogram) + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Unable to open histogram file `%s'\n", + histogram_fn); + GNUNET_free(histogram_fn); + } + logger_test = GNUNET_CLIENT_service_test("testbed-logger", + cfg, + GNUNET_TIME_UNIT_SECONDS, + &status_cb, + NULL); } #endif - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); - pk = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg); - GNUNET_assert (NULL != pk); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); + pk = GNUNET_CRYPTO_eddsa_key_create_from_configuration(cfg); + GNUNET_assert(NULL != pk); my_private_key = pk; - GNUNET_CRYPTO_eddsa_key_get_public (my_private_key, &my_identity.public_key); + GNUNET_CRYPTO_eddsa_key_get_public(my_private_key, &my_identity.public_key); if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "NSE", "PROOFFILE"); - GNUNET_free (my_private_key); - my_private_key = NULL; - GNUNET_SCHEDULER_shutdown (); - return; - } - if ((GNUNET_YES != GNUNET_DISK_file_test (proof)) || - (sizeof (my_proof) != - GNUNET_DISK_fn_read (proof, &my_proof, sizeof (my_proof)))) + GNUNET_CONFIGURATION_get_value_filename(cfg, "NSE", "PROOFFILE", &proof)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "NSE", "PROOFFILE"); + GNUNET_free(my_private_key); + my_private_key = NULL; + GNUNET_SCHEDULER_shutdown(); + return; + } + if ((GNUNET_YES != GNUNET_DISK_file_test(proof)) || + (sizeof(my_proof) != + GNUNET_DISK_fn_read(proof, &my_proof, sizeof(my_proof)))) my_proof = 0; - GNUNET_free (proof); + GNUNET_free(proof); proof_task = - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE, - &find_proof, - NULL); + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_IDLE, + &find_proof, + NULL); - peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_YES); - nc = GNUNET_notification_context_create (1); + peers = GNUNET_CONTAINER_multipeermap_create(128, GNUNET_YES); + nc = GNUNET_notification_context_create(1); /* Connect to core service and register core handlers */ core_api = - GNUNET_CORE_connect (cfg, /* Main configuration */ - NULL, /* Closure passed to functions */ - &core_init, /* Call core_init once connected */ - &handle_core_connect, /* Handle connects */ - &handle_core_disconnect, /* Handle disconnects */ - core_handlers); /* Register these handlers */ + GNUNET_CORE_connect(cfg, /* Main configuration */ + NULL, /* Closure passed to functions */ + &core_init, /* Call core_init once connected */ + &handle_core_connect, /* Handle connects */ + &handle_core_disconnect, /* Handle disconnects */ + core_handlers); /* Register these handlers */ if (NULL == core_api) - { - GNUNET_SCHEDULER_shutdown (); - return; - } - stats = GNUNET_STATISTICS_create ("nse", cfg); + { + GNUNET_SCHEDULER_shutdown(); + return; + } + stats = GNUNET_STATISTICS_create("nse", cfg); } @@ -1534,12 +1530,12 @@ run (void *cls, * @return @a c */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + struct GNUNET_MQ_Handle *mq) { - (void) cls; - (void) mq; + (void)cls; + (void)mq; return c; } @@ -1552,29 +1548,29 @@ client_connect_cb (void *cls, * @param internal_cls should be equal to @a c */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - void *internal_cls) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + void *internal_cls) { - (void) cls; - GNUNET_assert (c == internal_cls); + (void)cls; + GNUNET_assert(c == internal_cls); } /** * Define "main" method using service macro. */ -GNUNET_SERVICE_MAIN ("nse", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_fixed_size (start, - GNUNET_MESSAGE_TYPE_NSE_START, - struct GNUNET_MessageHeader, - NULL), - GNUNET_MQ_handler_end ()); +GNUNET_SERVICE_MAIN("nse", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_fixed_size(start, + GNUNET_MESSAGE_TYPE_NSE_START, + struct GNUNET_MessageHeader, + NULL), + GNUNET_MQ_handler_end()); #if defined(LINUX) && defined(__GLIBC__) @@ -1583,11 +1579,11 @@ GNUNET_SERVICE_MAIN ("nse", /** * MINIMIZE heap size (way below 128k) since this process doesn't need much. */ -void __attribute__ ((constructor)) GNUNET_ARM_memory_init () +void __attribute__ ((constructor)) GNUNET_ARM_memory_init() { - mallopt (M_TRIM_THRESHOLD, 4 * 1024); - mallopt (M_TOP_PAD, 1 * 1024); - malloc_trim (0); + mallopt(M_TRIM_THRESHOLD, 4 * 1024); + mallopt(M_TOP_PAD, 1 * 1024); + malloc_trim(0); } #endif diff --git a/src/nse/nse.h b/src/nse/nse.h index efff57679..b0129addd 100644 --- a/src/nse/nse.h +++ b/src/nse/nse.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Nathan Evans @@ -39,8 +39,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * standard deviation of known estimates. * */ -struct GNUNET_NSE_ClientMessage -{ +struct GNUNET_NSE_ClientMessage { /** * Type: GNUNET_MESSAGE_TYPE_NSE_ESTIMATE */ diff --git a/src/nse/nse_api.c b/src/nse/nse_api.c index 259be75ed..93716eb5f 100644 --- a/src/nse/nse_api.c +++ b/src/nse/nse_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nse/nse_api.c @@ -32,13 +32,12 @@ #include "gnunet_nse_service.h" #include "nse.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "nse-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "nse-api", __VA_ARGS__) /** * Handle for talking with the NSE service. */ -struct GNUNET_NSE_Handle -{ +struct GNUNET_NSE_Handle { /** * Configuration to use. */ @@ -77,7 +76,7 @@ struct GNUNET_NSE_Handle * @param cls closure with the `struct GNUNET_NSE_Handle *` */ static void -reconnect (void *cls); +reconnect(void *cls); /** @@ -90,16 +89,16 @@ reconnect (void *cls); * @param error error code */ static void -mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_NSE_Handle *h = cls; - (void) error; - GNUNET_MQ_destroy (h->mq); + (void)error; + GNUNET_MQ_destroy(h->mq); h->mq = NULL; h->reconnect_task = - GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, &reconnect, h); - h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay); + GNUNET_SCHEDULER_add_delayed(h->reconnect_delay, &reconnect, h); + h->reconnect_delay = GNUNET_TIME_STD_BACKOFF(h->reconnect_delay); } @@ -111,15 +110,15 @@ mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @param client_msg message received */ static void -handle_estimate (void *cls, const struct GNUNET_NSE_ClientMessage *client_msg) +handle_estimate(void *cls, const struct GNUNET_NSE_ClientMessage *client_msg) { struct GNUNET_NSE_Handle *h = cls; h->reconnect_delay = GNUNET_TIME_UNIT_ZERO; - h->recv_cb (h->recv_cb_cls, - GNUNET_TIME_absolute_ntoh (client_msg->timestamp), - GNUNET_ntoh_double (client_msg->size_estimate), - GNUNET_ntoh_double (client_msg->std_deviation)); + h->recv_cb(h->recv_cb_cls, + GNUNET_TIME_absolute_ntoh(client_msg->timestamp), + GNUNET_ntoh_double(client_msg->size_estimate), + GNUNET_ntoh_double(client_msg->std_deviation)); } @@ -129,27 +128,27 @@ handle_estimate (void *cls, const struct GNUNET_NSE_ClientMessage *client_msg) * @param cls the `struct GNUNET_NSE_Handle *` */ static void -reconnect (void *cls) +reconnect(void *cls) { struct GNUNET_NSE_Handle *h = cls; struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_fixed_size (estimate, - GNUNET_MESSAGE_TYPE_NSE_ESTIMATE, - struct GNUNET_NSE_ClientMessage, - h), - GNUNET_MQ_handler_end ()}; + { GNUNET_MQ_hd_fixed_size(estimate, + GNUNET_MESSAGE_TYPE_NSE_ESTIMATE, + struct GNUNET_NSE_ClientMessage, + h), + GNUNET_MQ_handler_end() }; struct GNUNET_MessageHeader *msg; struct GNUNET_MQ_Envelope *env; h->reconnect_task = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Connecting to network size estimation service.\n"); - GNUNET_assert (NULL == h->mq); - h->mq = GNUNET_CLIENT_connect (h->cfg, "nse", handlers, &mq_error_handler, h); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Connecting to network size estimation service.\n"); + GNUNET_assert(NULL == h->mq); + h->mq = GNUNET_CLIENT_connect(h->cfg, "nse", handlers, &mq_error_handler, h); if (NULL == h->mq) return; - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_NSE_START); - GNUNET_MQ_send (h->mq, env); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_NSE_START); + GNUNET_MQ_send(h->mq, env); } @@ -162,24 +161,24 @@ reconnect (void *cls) * @return handle to use */ struct GNUNET_NSE_Handle * -GNUNET_NSE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, - GNUNET_NSE_Callback func, - void *func_cls) +GNUNET_NSE_connect(const struct GNUNET_CONFIGURATION_Handle *cfg, + GNUNET_NSE_Callback func, + void *func_cls) { struct GNUNET_NSE_Handle *h; - GNUNET_assert (NULL != func); - h = GNUNET_new (struct GNUNET_NSE_Handle); + GNUNET_assert(NULL != func); + h = GNUNET_new(struct GNUNET_NSE_Handle); h->cfg = cfg; h->recv_cb = func; h->recv_cb_cls = func_cls; h->reconnect_delay = GNUNET_TIME_UNIT_ZERO; - reconnect (h); + reconnect(h); if (NULL == h->mq) - { - GNUNET_free (h); - return NULL; - } + { + GNUNET_free(h); + return NULL; + } return h; } @@ -190,19 +189,19 @@ GNUNET_NSE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param h handle to destroy */ void -GNUNET_NSE_disconnect (struct GNUNET_NSE_Handle *h) +GNUNET_NSE_disconnect(struct GNUNET_NSE_Handle *h) { if (NULL != h->reconnect_task) - { - GNUNET_SCHEDULER_cancel (h->reconnect_task); - h->reconnect_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(h->reconnect_task); + h->reconnect_task = NULL; + } if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } - GNUNET_free (h); + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } + GNUNET_free(h); } /* end of nse_api.c */ diff --git a/src/nse/perf_kdf.c b/src/nse/perf_kdf.c index 5178f178b..bf4dbe0b2 100644 --- a/src/nse/perf_kdf.c +++ b/src/nse/perf_kdf.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Christian Grothoff @@ -38,47 +38,47 @@ * @param result where to write the resulting hash */ static void -pow_hash (const void *buf, - size_t buf_len, - struct GNUNET_HashCode *result) +pow_hash(const void *buf, + size_t buf_len, + struct GNUNET_HashCode *result) { - GNUNET_break (0 == - gcry_kdf_derive (buf, buf_len, - GCRY_KDF_SCRYPT, - 1 /* subalgo */, - "gnunet-proof-of-work", strlen ("gnunet-proof-of-work"), - 2 /* iterations; keep cost of individual op small */, - sizeof (struct GNUNET_HashCode), result)); + GNUNET_break(0 == + gcry_kdf_derive(buf, buf_len, + GCRY_KDF_SCRYPT, + 1 /* subalgo */, + "gnunet-proof-of-work", strlen("gnunet-proof-of-work"), + 2 /* iterations; keep cost of individual op small */, + sizeof(struct GNUNET_HashCode), result)); } static void -perfHash () +perfHash() { struct GNUNET_HashCode hc; unsigned int i; char buf[64]; - memset (buf, 1, sizeof (buf)); + memset(buf, 1, sizeof(buf)); for (i = 0; i < 1024; i++) - pow_hash (buf, sizeof (buf), &hc); + pow_hash(buf, sizeof(buf), &hc); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { struct GNUNET_TIME_Absolute start; - start = GNUNET_TIME_absolute_get (); - perfHash (); - printf ("Hash perf took %s\n", - GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), - GNUNET_YES)); - GAUGER ("NSE", "Proof-of-work hashing", - 1024.0 / (1.0 + - GNUNET_TIME_absolute_get_duration - (start).rel_value_us / 1000.0), "hashes/ms"); + start = GNUNET_TIME_absolute_get(); + perfHash(); + printf("Hash perf took %s\n", + GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start), + GNUNET_YES)); + GAUGER("NSE", "Proof-of-work hashing", + 1024.0 / (1.0 + + GNUNET_TIME_absolute_get_duration + (start).rel_value_us / 1000.0), "hashes/ms"); return 0; } diff --git a/src/nse/test_nse_api.c b/src/nse/test_nse_api.c index 67ca17127..b739e05a2 100644 --- a/src/nse/test_nse_api.c +++ b/src/nse/test_nse_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nse/test_nse_api.c * @brief testcase for nse_api.c @@ -38,13 +38,13 @@ static struct GNUNET_SCHEDULER_Task * die_task; * @param cls closure */ static void -end_test (void *cls) +end_test(void *cls) { if (h != NULL) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from NSE service.\n"); - GNUNET_NSE_disconnect (h); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Disconnecting from NSE service.\n"); + GNUNET_NSE_disconnect(h); + } } /** @@ -58,46 +58,46 @@ end_test (void *cls) * */ static void -check_nse_message (void *cls, struct GNUNET_TIME_Absolute timestamp, - double estimate, double std_dev) +check_nse_message(void *cls, struct GNUNET_TIME_Absolute timestamp, + double estimate, double std_dev) { int *ok = cls; - fprintf (stderr, - "Received NSE message, estimate %f, standard deviation %f.\n", - estimate, std_dev); + fprintf(stderr, + "Received NSE message, estimate %f, standard deviation %f.\n", + estimate, std_dev); /* Fantastic check below. Expect NaN, the only thing not equal to itself. */ (*ok) = 0; if (die_task != NULL) - GNUNET_SCHEDULER_cancel (die_task); - die_task = GNUNET_SCHEDULER_add_now (&end_test, NULL); + GNUNET_SCHEDULER_cancel(die_task); + die_task = GNUNET_SCHEDULER_add_now(&end_test, NULL); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { die_task = - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply - (GNUNET_TIME_UNIT_MINUTES, 1), &end_test, - NULL); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply + (GNUNET_TIME_UNIT_MINUTES, 1), &end_test, + NULL); - h = GNUNET_NSE_connect (cfg, &check_nse_message, cls); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting to NSE service.\n"); - GNUNET_assert (h != NULL); + h = GNUNET_NSE_connect(cfg, &check_nse_message, cls); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting to NSE service.\n"); + GNUNET_assert(h != NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { int ok = 1; - if (0 != GNUNET_TESTING_peer_run ("test_nse_api", - "test_nse.conf", - &run, &ok)) + if (0 != GNUNET_TESTING_peer_run("test_nse_api", + "test_nse.conf", + &run, &ok)) return 1; return ok; } diff --git a/src/nse/test_nse_multipeer.c b/src/nse/test_nse_multipeer.c index ec5a94f76..88ced26d2 100644 --- a/src/nse/test_nse_multipeer.c +++ b/src/nse/test_nse_multipeer.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nse/test_nse_multipeer.c * @brief Testcase for the network size estimation service. Starts @@ -37,14 +37,13 @@ /** * How long do we run the test? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 300) /** * Information we track for each peer. */ -struct NSEPeer -{ +struct NSEPeer { /** * Handle for NSE connect operation. */ @@ -72,13 +71,13 @@ static int ok; * Task run on timeout to shut everything down. */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { unsigned int i; - for (i=0;iop); + GNUNET_assert(op == peer->op); if (NULL != emsg) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to connect to NSE service: %s\n", - emsg); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to connect to NSE service: %s\n", + emsg); ok = 1; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); return; } peer->nse_handle = nse; @@ -151,12 +150,12 @@ nse_connect_complete_cb (void *cls, * @return service handle to return in 'op_result', NULL on error */ static void * -nse_connect_adapter (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +nse_connect_adapter(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - return GNUNET_NSE_connect (cfg, - &handle_estimate, - cls); + return GNUNET_NSE_connect(cfg, + &handle_estimate, + cls); } @@ -168,10 +167,10 @@ nse_connect_adapter (void *cls, * @param op_result service handle returned from the connect adapter */ static void -nse_disconnect_adapter (void *cls, - void *op_result) +nse_disconnect_adapter(void *cls, + void *op_result) { - GNUNET_NSE_disconnect (op_result); + GNUNET_NSE_disconnect(op_result); } @@ -188,27 +187,27 @@ nse_disconnect_adapter (void *cls, * failed */ static void -run (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers, - struct GNUNET_TESTBED_Peer **peers, - unsigned int links_succeeded, - unsigned int links_failed) +run(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers, + struct GNUNET_TESTBED_Peer **peers, + unsigned int links_succeeded, + unsigned int links_failed) { unsigned int i; - GNUNET_assert (NUM_PEERS == num_peers); - for (i=0;i. SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file nt/nt_api_scanner.c * @brief LAN interface scanning to determine IPs in LAN @@ -30,7 +30,7 @@ /** * How frequently do we scan the interfaces for changes to the addresses? */ -#define INTERFACE_PROCESSING_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2) +#define INTERFACE_PROCESSING_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2) /** @@ -40,22 +40,28 @@ * @return a string or NULL if invalid */ const char * -GNUNET_NT_to_string (enum GNUNET_NetworkType net) +GNUNET_NT_to_string(enum GNUNET_NetworkType net) { switch (net) { case GNUNET_NT_UNSPECIFIED: return "UNSPECIFIED"; + case GNUNET_NT_LOOPBACK: return "LOOPBACK"; + case GNUNET_NT_LAN: return "LAN"; + case GNUNET_NT_WAN: return "WAN"; + case GNUNET_NT_WLAN: return "WLAN"; + case GNUNET_NT_BT: return "BLUETOOTH"; + default: return NULL; } @@ -68,8 +74,7 @@ GNUNET_NT_to_string (enum GNUNET_NetworkType net) * (maybe we can do that heuristically based on interface * name in the future?). */ -struct NT_Network -{ +struct NT_Network { /** * Kept in a DLL. */ @@ -100,9 +105,7 @@ struct NT_Network /** * Handle to the interface scanner. */ -struct GNUNET_NT_InterfaceScanner -{ - +struct GNUNET_NT_InterfaceScanner { /** * Head of LAN networks list. */ @@ -117,7 +120,6 @@ struct GNUNET_NT_InterfaceScanner * Task for periodically refreshing our LAN network list. */ struct GNUNET_SCHEDULER_Task *interface_task; - }; @@ -127,17 +129,17 @@ struct GNUNET_NT_InterfaceScanner * @param is scanner to clean up */ static void -delete_networks (struct GNUNET_NT_InterfaceScanner *is) +delete_networks(struct GNUNET_NT_InterfaceScanner *is) { struct NT_Network *cur; while (NULL != (cur = is->net_head)) - { - GNUNET_CONTAINER_DLL_remove (is->net_head, - is->net_tail, - cur); - GNUNET_free (cur); - } + { + GNUNET_CONTAINER_DLL_remove(is->net_head, + is->net_tail, + cur); + GNUNET_free(cur); + } } @@ -156,116 +158,117 @@ delete_networks (struct GNUNET_NT_InterfaceScanner *is) * @return #GNUNET_OK to continue iteration */ static int -interface_proc (void *cls, - const char *name, - int isDefault, - const struct sockaddr *addr, - const struct sockaddr *broadcast_addr, - const struct sockaddr *netmask, - socklen_t addrlen) +interface_proc(void *cls, + const char *name, + int isDefault, + const struct sockaddr *addr, + const struct sockaddr *broadcast_addr, + const struct sockaddr *netmask, + socklen_t addrlen) { struct GNUNET_NT_InterfaceScanner *is = cls; /* Calculate network */ struct NT_Network *net = NULL; - (void) name; - (void) isDefault; - (void) broadcast_addr; + + (void)name; + (void)isDefault; + (void)broadcast_addr; /* Skipping IPv4 loopback addresses since we have special check */ - if (addr->sa_family == AF_INET) - { - const struct sockaddr_in *a4 = (const struct sockaddr_in *) addr; + if (addr->sa_family == AF_INET) + { + const struct sockaddr_in *a4 = (const struct sockaddr_in *)addr; - if ((a4->sin_addr.s_addr & htonl(0xff000000)) == htonl (0x7f000000)) - return GNUNET_OK; - } + if ((a4->sin_addr.s_addr & htonl(0xff000000)) == htonl(0x7f000000)) + return GNUNET_OK; + } /* Skipping IPv6 loopback addresses since we have special check */ - if (addr->sa_family == AF_INET6) - { - const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *) addr; - if (IN6_IS_ADDR_LOOPBACK (&a6->sin6_addr)) - return GNUNET_OK; - } + if (addr->sa_family == AF_INET6) + { + const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *)addr; + if (IN6_IS_ADDR_LOOPBACK(&a6->sin6_addr)) + return GNUNET_OK; + } if (addr->sa_family == AF_INET) - { - const struct sockaddr_in *addr4 = (const struct sockaddr_in *) addr; - const struct sockaddr_in *netmask4 = (const struct sockaddr_in *) netmask; - struct sockaddr_in *tmp; - struct sockaddr_in network4; - - net = GNUNET_malloc (sizeof (struct NT_Network) + 2 * sizeof (struct sockaddr_in)); - tmp = (struct sockaddr_in *) &net[1]; - net->network = (struct sockaddr *) &tmp[0]; - net->netmask = (struct sockaddr *) &tmp[1]; - net->length = addrlen; - - memset (&network4, - 0, - sizeof (network4)); - network4.sin_family = AF_INET; + { + const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addr; + const struct sockaddr_in *netmask4 = (const struct sockaddr_in *)netmask; + struct sockaddr_in *tmp; + struct sockaddr_in network4; + + net = GNUNET_malloc(sizeof(struct NT_Network) + 2 * sizeof(struct sockaddr_in)); + tmp = (struct sockaddr_in *)&net[1]; + net->network = (struct sockaddr *)&tmp[0]; + net->netmask = (struct sockaddr *)&tmp[1]; + net->length = addrlen; + + memset(&network4, + 0, + sizeof(network4)); + network4.sin_family = AF_INET; #if HAVE_SOCKADDR_IN_SIN_LEN - network4.sin_len = sizeof (network4); + network4.sin_len = sizeof(network4); #endif - network4.sin_addr.s_addr = (addr4->sin_addr.s_addr & netmask4->sin_addr.s_addr); - - GNUNET_memcpy (net->netmask, - netmask4, - sizeof (struct sockaddr_in)); - GNUNET_memcpy (net->network, - &network4, - sizeof (struct sockaddr_in)); - } + network4.sin_addr.s_addr = (addr4->sin_addr.s_addr & netmask4->sin_addr.s_addr); + + GNUNET_memcpy(net->netmask, + netmask4, + sizeof(struct sockaddr_in)); + GNUNET_memcpy(net->network, + &network4, + sizeof(struct sockaddr_in)); + } if (addr->sa_family == AF_INET6) - { - const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *) addr; - const struct sockaddr_in6 *netmask6 = (const struct sockaddr_in6 *) netmask; - struct sockaddr_in6 * tmp; - struct sockaddr_in6 network6; - - net = GNUNET_malloc (sizeof (struct NT_Network) + 2 * sizeof (struct sockaddr_in6)); - tmp = (struct sockaddr_in6 *) &net[1]; - net->network = (struct sockaddr *) &tmp[0]; - net->netmask = (struct sockaddr *) &tmp[1]; - net->length = addrlen; - - memset (&network6, 0, sizeof (network6)); - network6.sin6_family = AF_INET6; + { + const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr; + const struct sockaddr_in6 *netmask6 = (const struct sockaddr_in6 *)netmask; + struct sockaddr_in6 * tmp; + struct sockaddr_in6 network6; + + net = GNUNET_malloc(sizeof(struct NT_Network) + 2 * sizeof(struct sockaddr_in6)); + tmp = (struct sockaddr_in6 *)&net[1]; + net->network = (struct sockaddr *)&tmp[0]; + net->netmask = (struct sockaddr *)&tmp[1]; + net->length = addrlen; + + memset(&network6, 0, sizeof(network6)); + network6.sin6_family = AF_INET6; #if HAVE_SOCKADDR_IN_SIN_LEN - network6.sin6_len = sizeof (network6); + network6.sin6_len = sizeof(network6); #endif - unsigned int c = 0; - uint32_t *addr_elem = (uint32_t *) &addr6->sin6_addr; - uint32_t *mask_elem = (uint32_t *) &netmask6->sin6_addr; - uint32_t *net_elem = (uint32_t *) &network6.sin6_addr; - for (c = 0; c < 4; c++) - net_elem[c] = addr_elem[c] & mask_elem[c]; - - GNUNET_memcpy (net->netmask, - netmask6, - sizeof (struct sockaddr_in6)); - GNUNET_memcpy (net->network, - &network6, - sizeof (struct sockaddr_in6)); - } + unsigned int c = 0; + uint32_t *addr_elem = (uint32_t *)&addr6->sin6_addr; + uint32_t *mask_elem = (uint32_t *)&netmask6->sin6_addr; + uint32_t *net_elem = (uint32_t *)&network6.sin6_addr; + for (c = 0; c < 4; c++) + net_elem[c] = addr_elem[c] & mask_elem[c]; + + GNUNET_memcpy(net->netmask, + netmask6, + sizeof(struct sockaddr_in6)); + GNUNET_memcpy(net->network, + &network6, + sizeof(struct sockaddr_in6)); + } if (NULL == net) return GNUNET_OK; /* odd / unsupported address family */ /* Store in list */ #if VERBOSE_NT - char * netmask = GNUNET_strdup (GNUNET_a2s((struct sockaddr *) net->netmask, addrlen)); - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "nt", - "Adding network `%s', netmask `%s'\n", - GNUNET_a2s ((struct sockaddr *) net->network, - addrlen), - netmask); - GNUNET_free (netmask); + char * netmask = GNUNET_strdup(GNUNET_a2s((struct sockaddr *)net->netmask, addrlen)); + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "nt", + "Adding network `%s', netmask `%s'\n", + GNUNET_a2s((struct sockaddr *)net->network, + addrlen), + netmask); + GNUNET_free(netmask); #endif - GNUNET_CONTAINER_DLL_insert (is->net_head, - is->net_tail, - net); + GNUNET_CONTAINER_DLL_insert(is->net_head, + is->net_tail, + net); return GNUNET_OK; } @@ -277,17 +280,17 @@ interface_proc (void *cls, * @param cls closure */ static void -get_addresses (void *cls) +get_addresses(void *cls) { struct GNUNET_NT_InterfaceScanner *is = cls; is->interface_task = NULL; - delete_networks (is); - GNUNET_OS_network_interfaces_list (&interface_proc, - is); - is->interface_task = GNUNET_SCHEDULER_add_delayed (INTERFACE_PROCESSING_INTERVAL, - &get_addresses, - is); + delete_networks(is); + GNUNET_OS_network_interfaces_list(&interface_proc, + is); + is->interface_task = GNUNET_SCHEDULER_add_delayed(INTERFACE_PROCESSING_INTERVAL, + &get_addresses, + is); } @@ -300,9 +303,9 @@ get_addresses (void *cls) * @return type of the network the address belongs to */ enum GNUNET_NetworkType -GNUNET_NT_scanner_get_type (struct GNUNET_NT_InterfaceScanner *is, - const struct sockaddr *addr, - socklen_t addrlen) +GNUNET_NT_scanner_get_type(struct GNUNET_NT_InterfaceScanner *is, + const struct sockaddr *addr, + socklen_t addrlen) { struct NT_Network *cur = is->net_head; enum GNUNET_NetworkType type = GNUNET_NT_UNSPECIFIED; @@ -312,74 +315,77 @@ GNUNET_NT_scanner_get_type (struct GNUNET_NT_InterfaceScanner *is, case AF_UNIX: type = GNUNET_NT_LOOPBACK; break; + case AF_INET: - { - const struct sockaddr_in *a4 = (const struct sockaddr_in *) addr; + { + const struct sockaddr_in *a4 = (const struct sockaddr_in *)addr; + + if ((a4->sin_addr.s_addr & htonl(0xff000000)) == htonl(0x7f000000)) + type = GNUNET_NT_LOOPBACK; + break; + } - if ((a4->sin_addr.s_addr & htonl(0xff000000)) == htonl (0x7f000000)) - type = GNUNET_NT_LOOPBACK; - break; - } case AF_INET6: - { - const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *) addr; + { + const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *)addr; + + if (IN6_IS_ADDR_LOOPBACK(&a6->sin6_addr)) + type = GNUNET_NT_LOOPBACK; + break; + } - if (IN6_IS_ADDR_LOOPBACK (&a6->sin6_addr)) - type = GNUNET_NT_LOOPBACK; - break; - } default: - GNUNET_break (0); + GNUNET_break(0); break; - } + } /* Check local networks */ while ((NULL != cur) && (GNUNET_NT_UNSPECIFIED == type)) - { - if (addrlen != cur->length) { + if (addrlen != cur->length) + { + cur = cur->next; + continue; + } + if (addr->sa_family == AF_INET) + { + const struct sockaddr_in *a4 = (const struct sockaddr_in *)addr; + const struct sockaddr_in *net4 = (const struct sockaddr_in *)cur->network; + const struct sockaddr_in *mask4 = (const struct sockaddr_in *)cur->netmask; + + if (((a4->sin_addr.s_addr & mask4->sin_addr.s_addr)) == net4->sin_addr.s_addr) + type = GNUNET_NT_LAN; + } + if (addr->sa_family == AF_INET6) + { + const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *)addr; + const struct sockaddr_in6 *net6 = (const struct sockaddr_in6 *)cur->network; + const struct sockaddr_in6 *mask6 = (const struct sockaddr_in6 *)cur->netmask; + + int res = GNUNET_YES; + int c = 0; + uint32_t *addr_elem = (uint32_t *)&a6->sin6_addr; + uint32_t *mask_elem = (uint32_t *)&mask6->sin6_addr; + uint32_t *net_elem = (uint32_t *)&net6->sin6_addr; + for (c = 0; c < 4; c++) + if ((addr_elem[c] & mask_elem[c]) != net_elem[c]) + res = GNUNET_NO; + + if (res == GNUNET_YES) + type = GNUNET_NT_LAN; + } cur = cur->next; - continue; } - if (addr->sa_family == AF_INET) - { - const struct sockaddr_in *a4 = (const struct sockaddr_in *) addr; - const struct sockaddr_in *net4 = (const struct sockaddr_in *) cur->network; - const struct sockaddr_in *mask4 = (const struct sockaddr_in *) cur->netmask; - - if (((a4->sin_addr.s_addr & mask4->sin_addr.s_addr)) == net4->sin_addr.s_addr) - type = GNUNET_NT_LAN; - } - if (addr->sa_family == AF_INET6) - { - const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *) addr; - const struct sockaddr_in6 *net6 = (const struct sockaddr_in6 *) cur->network; - const struct sockaddr_in6 *mask6 = (const struct sockaddr_in6 *) cur->netmask; - - int res = GNUNET_YES; - int c = 0; - uint32_t *addr_elem = (uint32_t *) &a6->sin6_addr; - uint32_t *mask_elem = (uint32_t *) &mask6->sin6_addr; - uint32_t *net_elem = (uint32_t *) &net6->sin6_addr; - for (c = 0; c < 4; c++) - if ((addr_elem[c] & mask_elem[c]) != net_elem[c]) - res = GNUNET_NO; - - if (res == GNUNET_YES) - type = GNUNET_NT_LAN; - } - cur = cur->next; - } /* no local network found for this address, default: WAN */ if (type == GNUNET_NT_UNSPECIFIED) type = GNUNET_NT_WAN; - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "nt-scanner-api", - "`%s' is in network `%s'\n", - GNUNET_a2s (addr, - addrlen), - GNUNET_NT_to_string (type)); + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "nt-scanner-api", + "`%s' is in network `%s'\n", + GNUNET_a2s(addr, + addrlen), + GNUNET_NT_to_string(type)); return type; } @@ -390,16 +396,16 @@ GNUNET_NT_scanner_get_type (struct GNUNET_NT_InterfaceScanner *is, * @return interface scanner */ struct GNUNET_NT_InterfaceScanner * -GNUNET_NT_scanner_init () +GNUNET_NT_scanner_init() { struct GNUNET_NT_InterfaceScanner *is; - is = GNUNET_new (struct GNUNET_NT_InterfaceScanner); - GNUNET_OS_network_interfaces_list (&interface_proc, - is); - is->interface_task = GNUNET_SCHEDULER_add_delayed (INTERFACE_PROCESSING_INTERVAL, - &get_addresses, - is); + is = GNUNET_new(struct GNUNET_NT_InterfaceScanner); + GNUNET_OS_network_interfaces_list(&interface_proc, + is); + is->interface_task = GNUNET_SCHEDULER_add_delayed(INTERFACE_PROCESSING_INTERVAL, + &get_addresses, + is); return is; } @@ -410,15 +416,15 @@ GNUNET_NT_scanner_init () * @param is handle to release */ void -GNUNET_NT_scanner_done (struct GNUNET_NT_InterfaceScanner *is) +GNUNET_NT_scanner_done(struct GNUNET_NT_InterfaceScanner *is) { if (NULL != is->interface_task) - { - GNUNET_SCHEDULER_cancel (is->interface_task); - is->interface_task = NULL; - } - delete_networks (is); - GNUNET_free (is); + { + GNUNET_SCHEDULER_cancel(is->interface_task); + is->interface_task = NULL; + } + delete_networks(is); + GNUNET_free(is); } diff --git a/src/peerinfo-tool/gnunet-peerinfo.c b/src/peerinfo-tool/gnunet-peerinfo.c index fdcaaba58..bd029b2d1 100644 --- a/src/peerinfo-tool/gnunet-peerinfo.c +++ b/src/peerinfo-tool/gnunet-peerinfo.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerinfo-tool/gnunet-peerinfo.c @@ -35,7 +35,7 @@ /** * How long until we time out during address lookup? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) /** * Structure we use to collect printable address information. @@ -45,8 +45,7 @@ struct PrintContext; /** * Record we keep for each printable address. */ -struct AddressRecord -{ +struct AddressRecord { /** * Current address-to-string context (if active, otherwise NULL). */ @@ -72,9 +71,7 @@ struct AddressRecord /** * Structure we use to collect printable address information. */ -struct PrintContext -{ - +struct PrintContext { /** * Kept in DLL. */ @@ -220,7 +217,7 @@ static struct GNUNET_HELLO_Message *my_hello; * @param cls unused */ static void -state_machine (void *cls); +state_machine(void *cls); /* ********************* 'get_info' ******************* */ @@ -231,30 +228,30 @@ state_machine (void *cls); * @param pc printing context */ static void -dump_pc (struct PrintContext *pc) +dump_pc(struct PrintContext *pc) { unsigned int i; - printf (_ ("%sPeer `%s'\n"), - (GNUNET_YES == pc->friend_only) ? "F2F: " : "", - GNUNET_i2s_full (&pc->peer)); + printf(_("%sPeer `%s'\n"), + (GNUNET_YES == pc->friend_only) ? "F2F: " : "", + GNUNET_i2s_full(&pc->peer)); for (i = 0; i < pc->num_addresses; i++) - { - if (NULL != pc->address_list[i].result) { - printf (_ ("\tExpires: %s \t %s\n"), - GNUNET_STRINGS_absolute_time_to_string ( - pc->address_list[i].expiration), - pc->address_list[i].result); - GNUNET_free (pc->address_list[i].result); + if (NULL != pc->address_list[i].result) + { + printf(_("\tExpires: %s \t %s\n"), + GNUNET_STRINGS_absolute_time_to_string( + pc->address_list[i].expiration), + pc->address_list[i].result); + GNUNET_free(pc->address_list[i].result); + } } - } - printf ("\n"); - GNUNET_free_non_null (pc->address_list); - GNUNET_CONTAINER_DLL_remove (pc_head, pc_tail, pc); - GNUNET_free (pc); + printf("\n"); + GNUNET_free_non_null(pc->address_list); + GNUNET_CONTAINER_DLL_remove(pc_head, pc_tail, pc); + GNUNET_free(pc); if ((NULL == pc_head) && (NULL == pic)) - tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL); + tt = GNUNET_SCHEDULER_add_now(&state_machine, NULL); } @@ -272,29 +269,29 @@ dump_pc (struct PrintContext *pc) * if #GNUNET_SYSERR: address is invalid */ static void -process_resolved_address (void *cls, const char *address, int res) +process_resolved_address(void *cls, const char *address, int res) { struct AddressRecord *ar = cls; struct PrintContext *pc = ar->pc; if (NULL != address) - { - if (0 != strlen (address)) { - if (NULL != ar->result) - GNUNET_free (ar->result); - ar->result = GNUNET_strdup (address); + if (0 != strlen(address)) + { + if (NULL != ar->result) + GNUNET_free(ar->result); + ar->result = GNUNET_strdup(address); + } + return; } - return; - } ar->atsc = NULL; if (GNUNET_SYSERR == res) - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Failure: Cannot convert address to string for peer `%s'\n"), - GNUNET_i2s (&ar->pc->peer)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Failure: Cannot convert address to string for peer `%s'\n"), + GNUNET_i2s(&ar->pc->peer)); pc->num_addresses++; if (pc->num_addresses == pc->address_list_size) - dump_pc (pc); + dump_pc(pc); } @@ -307,9 +304,9 @@ process_resolved_address (void *cls, const char *address, int res) * @return #GNUNET_OK to keep the address and continue */ static int -count_address (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +count_address(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { struct PrintContext *pc = cls; @@ -327,28 +324,28 @@ count_address (void *cls, * @return #GNUNET_OK to keep the address and continue */ static int -print_address (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +print_address(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { struct PrintContext *pc = cls; struct AddressRecord *ar; - GNUNET_assert (0 < pc->off); + GNUNET_assert(0 < pc->off); ar = &pc->address_list[--pc->off]; ar->pc = pc; ar->expiration = expiration; - GNUNET_asprintf (&ar->result, - "%s:%u:%u", - address->transport_name, - address->address_length, - address->local_info); - ar->atsc = GNUNET_TRANSPORT_address_to_string (cfg, - address, - no_resolve, - TIMEOUT, - &process_resolved_address, - ar); + GNUNET_asprintf(&ar->result, + "%s:%u:%u", + address->transport_name, + address->address_length, + address->local_info); + ar->atsc = GNUNET_TRANSPORT_address_to_string(cfg, + address, + no_resolve, + TIMEOUT, + &process_resolved_address, + ar); return GNUNET_OK; } @@ -363,50 +360,50 @@ print_address (void *cls, * @param err_msg error message */ static void -print_peer_info (void *cls, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello, - const char *err_msg) +print_peer_info(void *cls, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello, + const char *err_msg) { struct PrintContext *pc; int friend_only; if (NULL == peer) - { - pic = NULL; /* end of iteration */ - if (NULL != err_msg) { - fprintf (stderr, - _ ("Error in communication with PEERINFO service: %s\n"), - err_msg); + pic = NULL; /* end of iteration */ + if (NULL != err_msg) + { + fprintf(stderr, + _("Error in communication with PEERINFO service: %s\n"), + err_msg); + } + if (NULL == pc_head) + tt = GNUNET_SCHEDULER_add_now(&state_machine, NULL); + return; } - if (NULL == pc_head) - tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL); - return; - } friend_only = GNUNET_NO; if (NULL != hello) - friend_only = GNUNET_HELLO_is_friend_only (hello); + friend_only = GNUNET_HELLO_is_friend_only(hello); if ((GNUNET_YES == be_quiet) || (NULL == hello)) - { - printf ("%s%s\n", - (GNUNET_YES == friend_only) ? "F2F: " : "", - GNUNET_i2s_full (peer)); - return; - } - pc = GNUNET_new (struct PrintContext); - GNUNET_CONTAINER_DLL_insert (pc_head, pc_tail, pc); + { + printf("%s%s\n", + (GNUNET_YES == friend_only) ? "F2F: " : "", + GNUNET_i2s_full(peer)); + return; + } + pc = GNUNET_new(struct PrintContext); + GNUNET_CONTAINER_DLL_insert(pc_head, pc_tail, pc); pc->peer = *peer; pc->friend_only = friend_only; - GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &count_address, pc); + GNUNET_HELLO_iterate_addresses(hello, GNUNET_NO, &count_address, pc); if (0 == pc->off) - { - dump_pc (pc); - return; - } + { + dump_pc(pc); + return; + } pc->address_list_size = pc->off; - pc->address_list = GNUNET_malloc (sizeof (struct AddressRecord) * pc->off); - GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &print_address, pc); + pc->address_list = GNUNET_malloc(sizeof(struct AddressRecord) * pc->off); + GNUNET_HELLO_iterate_addresses(hello, GNUNET_NO, &print_address, pc); } /* ************************* DUMP Hello ************************** */ @@ -420,9 +417,9 @@ print_peer_info (void *cls, * @return #GNUNET_OK */ static int -count_addr (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +count_addr(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { int *c = cls; @@ -440,50 +437,50 @@ count_addr (void *cls, * @param err_msg error message */ static void -dump_my_hello () +dump_my_hello() { unsigned int size; unsigned int c_addr; - size = GNUNET_HELLO_size (my_hello); + size = GNUNET_HELLO_size(my_hello); if (0 == size) - { - fprintf (stderr, _ ("Failure: Received invalid %s\n"), "HELLO"); - return; - } - if (GNUNET_SYSERR == GNUNET_DISK_fn_write (dump_hello, - my_hello, - size, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_GROUP_READ | - GNUNET_DISK_PERM_OTHER_READ)) - { - fprintf (stderr, - _ ("Failed to write HELLO with %u bytes to file `%s'\n"), - size, - dump_hello); - if (0 != unlink (dump_hello)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING | - GNUNET_ERROR_TYPE_BULK, - "unlink", - dump_hello); - } + { + fprintf(stderr, _("Failure: Received invalid %s\n"), "HELLO"); + return; + } + if (GNUNET_SYSERR == GNUNET_DISK_fn_write(dump_hello, + my_hello, + size, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_GROUP_READ | + GNUNET_DISK_PERM_OTHER_READ)) + { + fprintf(stderr, + _("Failed to write HELLO with %u bytes to file `%s'\n"), + size, + dump_hello); + if (0 != unlink(dump_hello)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING | + GNUNET_ERROR_TYPE_BULK, + "unlink", + dump_hello); + } c_addr = 0; - GNUNET_HELLO_iterate_addresses (my_hello, GNUNET_NO, count_addr, &c_addr); - - if (! be_quiet) - { - fprintf ( - stderr, - _ ("Wrote %s HELLO containing %u addresses with %u bytes to file `%s'\n"), - (GNUNET_YES == GNUNET_HELLO_is_friend_only (my_hello)) ? "friend-only" - : "public", - c_addr, - size, - dump_hello); - } - GNUNET_free (dump_hello); + GNUNET_HELLO_iterate_addresses(my_hello, GNUNET_NO, count_addr, &c_addr); + + if (!be_quiet) + { + fprintf( + stderr, + _("Wrote %s HELLO containing %u addresses with %u bytes to file `%s'\n"), + (GNUNET_YES == GNUNET_HELLO_is_friend_only(my_hello)) ? "friend-only" + : "public", + c_addr, + size, + dump_hello); + } + GNUNET_free(dump_hello); dump_hello = NULL; } @@ -500,32 +497,32 @@ dump_my_hello () * @param err_msg error message */ static void -print_my_uri (void *cls, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello, - const char *err_msg) +print_my_uri(void *cls, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello, + const char *err_msg) { char *uri; if (NULL == peer) - { - pic = NULL; - if (NULL != err_msg) - fprintf (stderr, - _ ("Error in communication with PEERINFO service: %s\n"), - err_msg); - tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL); - return; - } + { + pic = NULL; + if (NULL != err_msg) + fprintf(stderr, + _("Error in communication with PEERINFO service: %s\n"), + err_msg); + tt = GNUNET_SCHEDULER_add_now(&state_machine, NULL); + return; + } if (NULL == hello) return; - uri = GNUNET_HELLO_compose_uri (hello, &GPI_plugins_find); + uri = GNUNET_HELLO_compose_uri(hello, &GPI_plugins_find); if (NULL != uri) - { - printf ("%s\n", (const char *) uri); - GNUNET_free (uri); - } + { + printf("%s\n", (const char *)uri); + GNUNET_free(uri); + } } @@ -538,10 +535,10 @@ print_my_uri (void *cls, * @param cls closure, NULL */ static void -add_continuation (void *cls) +add_continuation(void *cls) { ac = NULL; - tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL); + tt = GNUNET_SCHEDULER_add_now(&state_machine, NULL); } @@ -555,24 +552,24 @@ add_continuation (void *cls) * #GNUNET_NO on other errors */ static int -parse_hello_uri (const char *put_uri) +parse_hello_uri(const char *put_uri) { struct GNUNET_HELLO_Message *hello = NULL; - int ret = GNUNET_HELLO_parse_uri (put_uri, - &my_peer_identity.public_key, - &hello, - &GPI_plugins_find); + int ret = GNUNET_HELLO_parse_uri(put_uri, + &my_peer_identity.public_key, + &hello, + &GPI_plugins_find); if (NULL != hello) - { - /* WARNING: this adds the address from URI WITHOUT verification! */ - if (GNUNET_OK == ret) - ac = GNUNET_PEERINFO_add_peer (peerinfo, hello, &add_continuation, NULL); - else - tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL); - GNUNET_free (hello); - } + { + /* WARNING: this adds the address from URI WITHOUT verification! */ + if (GNUNET_OK == ret) + ac = GNUNET_PEERINFO_add_peer(peerinfo, hello, &add_continuation, NULL); + else + tt = GNUNET_SCHEDULER_add_now(&state_machine, NULL); + GNUNET_free(hello); + } return ret; } @@ -587,59 +584,59 @@ parse_hello_uri (const char *put_uri) * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { struct PrintContext *pc; struct AddressRecord *ar; unsigned int i; if (NULL != ac) - { - GNUNET_MQ_send_cancel (ac); - ac = NULL; - } + { + GNUNET_MQ_send_cancel(ac); + ac = NULL; + } if (NULL != tt) - { - GNUNET_SCHEDULER_cancel (tt); - tt = NULL; - } + { + GNUNET_SCHEDULER_cancel(tt); + tt = NULL; + } if (NULL != pic) - { - GNUNET_PEERINFO_iterate_cancel (pic); - pic = NULL; - } + { + GNUNET_PEERINFO_iterate_cancel(pic); + pic = NULL; + } if (NULL != gh) - { - GNUNET_TRANSPORT_hello_get_cancel (gh); - gh = NULL; - } + { + GNUNET_TRANSPORT_hello_get_cancel(gh); + gh = NULL; + } while (NULL != (pc = pc_head)) - { - GNUNET_CONTAINER_DLL_remove (pc_head, pc_tail, pc); - for (i = 0; i < pc->address_list_size; i++) { - ar = &pc->address_list[i]; - GNUNET_free_non_null (ar->result); - if (NULL != ar->atsc) - { - GNUNET_TRANSPORT_address_to_string_cancel (ar->atsc); - ar->atsc = NULL; - } + GNUNET_CONTAINER_DLL_remove(pc_head, pc_tail, pc); + for (i = 0; i < pc->address_list_size; i++) + { + ar = &pc->address_list[i]; + GNUNET_free_non_null(ar->result); + if (NULL != ar->atsc) + { + GNUNET_TRANSPORT_address_to_string_cancel(ar->atsc); + ar->atsc = NULL; + } + } + GNUNET_free_non_null(pc->address_list); + GNUNET_free(pc); } - GNUNET_free_non_null (pc->address_list); - GNUNET_free (pc); - } - GPI_plugins_unload (); + GPI_plugins_unload(); if (NULL != peerinfo) - { - GNUNET_PEERINFO_disconnect (peerinfo); - peerinfo = NULL; - } + { + GNUNET_PEERINFO_disconnect(peerinfo); + peerinfo = NULL; + } if (NULL != my_hello) - { - GNUNET_free (my_hello); - my_hello = NULL; - } + { + GNUNET_free(my_hello); + my_hello = NULL; + } } @@ -651,22 +648,22 @@ shutdown_task (void *cls) * @param hello the HELLO message */ static void -hello_callback (void *cls, const struct GNUNET_MessageHeader *hello) +hello_callback(void *cls, const struct GNUNET_MessageHeader *hello) { if (NULL == hello) - { - fprintf (stderr, "Failed to get my own HELLO from this peer!\n"); - GNUNET_SCHEDULER_shutdown (); - return; - } - my_hello = (struct GNUNET_HELLO_Message *) GNUNET_copy_message (hello); - GNUNET_assert (GNUNET_OK == - GNUNET_HELLO_get_id (my_hello, &my_peer_identity)); - GNUNET_TRANSPORT_hello_get_cancel (gh); + { + fprintf(stderr, "Failed to get my own HELLO from this peer!\n"); + GNUNET_SCHEDULER_shutdown(); + return; + } + my_hello = (struct GNUNET_HELLO_Message *)GNUNET_copy_message(hello); + GNUNET_assert(GNUNET_OK == + GNUNET_HELLO_get_id(my_hello, &my_peer_identity)); + GNUNET_TRANSPORT_hello_get_cancel(gh); gh = NULL; if (NULL != dump_hello) - dump_my_hello (); - tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL); + dump_my_hello(); + tt = GNUNET_SCHEDULER_add_now(&state_machine, NULL); } @@ -679,41 +676,41 @@ hello_callback (void *cls, const struct GNUNET_MessageHeader *hello) * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { cfg = c; if ((NULL != args[0]) && (NULL == put_uri) && - (args[0] == strcasestr (args[0], "gnunet://hello/"))) - { - put_uri = GNUNET_strdup (args[0]); - args++; - } + (args[0] == strcasestr(args[0], "gnunet://hello/"))) + { + put_uri = GNUNET_strdup(args[0]); + args++; + } if (NULL != args[0]) - { - fprintf (stderr, _ ("Invalid command line argument `%s'\n"), args[0]); - return; - } - if (NULL == (peerinfo = GNUNET_PEERINFO_connect (cfg))) - { - fprintf (stderr, "%s", "Could not access PEERINFO service. Exiting.\n"); - return; - } + { + fprintf(stderr, _("Invalid command line argument `%s'\n"), args[0]); + return; + } + if (NULL == (peerinfo = GNUNET_PEERINFO_connect(cfg))) + { + fprintf(stderr, "%s", "Could not access PEERINFO service. Exiting.\n"); + return; + } if ((GNUNET_YES == get_self) || (GNUNET_YES == get_uri) || (NULL != dump_hello)) - { - gh = GNUNET_TRANSPORT_hello_get (cfg, - GNUNET_TRANSPORT_AC_ANY, - &hello_callback, - NULL); - } + { + gh = GNUNET_TRANSPORT_hello_get(cfg, + GNUNET_TRANSPORT_AC_ANY, + &hello_callback, + NULL); + } else - { - tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL); - } - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + { + tt = GNUNET_SCHEDULER_add_now(&state_machine, NULL); + } + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); } @@ -724,61 +721,61 @@ run (void *cls, * @param cls unused */ static void -state_machine (void *cls) +state_machine(void *cls) { tt = NULL; if (NULL != put_uri) - { - GPI_plugins_load (cfg); - if (GNUNET_SYSERR == parse_hello_uri (put_uri)) { - fprintf (stderr, _ ("Invalid URI `%s'\n"), put_uri); - GNUNET_SCHEDULER_shutdown (); + GPI_plugins_load(cfg); + if (GNUNET_SYSERR == parse_hello_uri(put_uri)) + { + fprintf(stderr, _("Invalid URI `%s'\n"), put_uri); + GNUNET_SCHEDULER_shutdown(); + } + GNUNET_free(put_uri); + put_uri = NULL; } - GNUNET_free (put_uri); - put_uri = NULL; - } else if (GNUNET_YES == get_info) - { - get_info = GNUNET_NO; - GPI_plugins_load (cfg); - pic = GNUNET_PEERINFO_iterate (peerinfo, - include_friend_only, - NULL, - &print_peer_info, - NULL); - } + { + get_info = GNUNET_NO; + GPI_plugins_load(cfg); + pic = GNUNET_PEERINFO_iterate(peerinfo, + include_friend_only, + NULL, + &print_peer_info, + NULL); + } else if (GNUNET_YES == get_self) - { - get_self = GNUNET_NO; - if (be_quiet) - printf ("%s\n", GNUNET_i2s_full (&my_peer_identity)); - else - printf (_ ("I am peer `%s'.\n"), GNUNET_i2s_full (&my_peer_identity)); - tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL); - } + { + get_self = GNUNET_NO; + if (be_quiet) + printf("%s\n", GNUNET_i2s_full(&my_peer_identity)); + else + printf(_("I am peer `%s'.\n"), GNUNET_i2s_full(&my_peer_identity)); + tt = GNUNET_SCHEDULER_add_now(&state_machine, NULL); + } else if (GNUNET_YES == get_uri) - { - GPI_plugins_load (cfg); - pic = GNUNET_PEERINFO_iterate (peerinfo, - include_friend_only, - &my_peer_identity, - &print_my_uri, - NULL); - get_uri = GNUNET_NO; - } + { + GPI_plugins_load(cfg); + pic = GNUNET_PEERINFO_iterate(peerinfo, + include_friend_only, + &my_peer_identity, + &print_my_uri, + NULL); + get_uri = GNUNET_NO; + } else if (GNUNET_YES == default_operation) - { - /* default operation list all */ - default_operation = GNUNET_NO; - get_info = GNUNET_YES; - tt = GNUNET_SCHEDULER_add_now (&state_machine, NULL); - } + { + /* default operation list all */ + default_operation = GNUNET_NO; + get_info = GNUNET_YES; + tt = GNUNET_SCHEDULER_add_now(&state_machine, NULL); + } else - { - GNUNET_SCHEDULER_shutdown (); - } + { + GNUNET_SCHEDULER_shutdown(); + } default_operation = GNUNET_NO; } @@ -791,71 +788,71 @@ state_machine (void *cls) * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = - {GNUNET_GETOPT_option_flag ('n', - "numeric", - gettext_noop ("don't resolve host names"), - &no_resolve), - - GNUNET_GETOPT_option_flag ('q', - "quiet", - gettext_noop ( - "output only the identity strings"), - &be_quiet), - GNUNET_GETOPT_option_flag ('f', - "friends", - gettext_noop ( - "include friend-only information"), - &include_friend_only), - - GNUNET_GETOPT_option_flag ('s', - "self", - gettext_noop ("output our own identity only"), - &get_self), - - GNUNET_GETOPT_option_flag ('i', - "info", - gettext_noop ("list all known peers"), - &get_info), - - GNUNET_GETOPT_option_string ('d', - "dump-hello", - NULL, - gettext_noop ("dump hello to file"), - &dump_hello), - - GNUNET_GETOPT_option_flag ('g', - "get-hello", - gettext_noop ("also output HELLO uri(s)"), - &get_uri), - - GNUNET_GETOPT_option_string ('p', - "put-hello", - "HELLO", - gettext_noop ( - "add given HELLO uri to the database"), - &put_uri), - - GNUNET_GETOPT_OPTION_END}; + { GNUNET_GETOPT_option_flag('n', + "numeric", + gettext_noop("don't resolve host names"), + &no_resolve), + + GNUNET_GETOPT_option_flag('q', + "quiet", + gettext_noop( + "output only the identity strings"), + &be_quiet), + GNUNET_GETOPT_option_flag('f', + "friends", + gettext_noop( + "include friend-only information"), + &include_friend_only), + + GNUNET_GETOPT_option_flag('s', + "self", + gettext_noop("output our own identity only"), + &get_self), + + GNUNET_GETOPT_option_flag('i', + "info", + gettext_noop("list all known peers"), + &get_info), + + GNUNET_GETOPT_option_string('d', + "dump-hello", + NULL, + gettext_noop("dump hello to file"), + &dump_hello), + + GNUNET_GETOPT_option_flag('g', + "get-hello", + gettext_noop("also output HELLO uri(s)"), + &get_uri), + + GNUNET_GETOPT_option_string('p', + "put-hello", + "HELLO", + gettext_noop( + "add given HELLO uri to the database"), + &put_uri), + + GNUNET_GETOPT_OPTION_END }; int ret; default_operation = GNUNET_YES; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-peerinfo", - gettext_noop ("Print information about peers."), - options, - &run, - NULL)) - ? 0 - : 1; - GNUNET_free ((void *) argv); + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-peerinfo", + gettext_noop("Print information about peers."), + options, + &run, + NULL)) + ? 0 + : 1; + GNUNET_free((void *)argv); return ret; } diff --git a/src/peerinfo-tool/gnunet-peerinfo_plugins.c b/src/peerinfo-tool/gnunet-peerinfo_plugins.c index a8f43a1f1..13730629e 100644 --- a/src/peerinfo-tool/gnunet-peerinfo_plugins.c +++ b/src/peerinfo-tool/gnunet-peerinfo_plugins.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerinfo-tool/gnunet-peerinfo_plugins.c @@ -31,8 +31,7 @@ /** * Entry in doubly-linked list of all of our plugins. */ -struct TransportPlugin -{ +struct TransportPlugin { /** * This is a doubly-linked list. */ @@ -64,7 +63,6 @@ struct TransportPlugin * for this plugin. */ struct GNUNET_TRANSPORT_PluginEnvironment env; - }; /** @@ -88,7 +86,7 @@ static struct TransportPlugin *plugins_tail; * @param cfg configuration to use */ void -GPI_plugins_load (const struct GNUNET_CONFIGURATION_Handle *cfg) +GPI_plugins_load(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct TransportPlugin *plug; struct TransportPlugin *next; @@ -99,41 +97,41 @@ GPI_plugins_load (const struct GNUNET_CONFIGURATION_Handle *cfg) if (NULL != plugins_head) return; /* already loaded */ if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, "TRANSPORT", "PLUGINS", - &plugs)) + GNUNET_CONFIGURATION_get_value_string(cfg, "TRANSPORT", "PLUGINS", + &plugs)) return; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Starting transport plugins `%s'\n"), - plugs); - for (pos = strtok (plugs, " "); pos != NULL; pos = strtok (NULL, " ")) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Loading `%s' transport plugin\n"), - pos); - GNUNET_asprintf (&libname, "libgnunet_plugin_transport_%s", pos); - plug = GNUNET_new (struct TransportPlugin); - plug->short_name = GNUNET_strdup (pos); - plug->lib_name = libname; - plug->env.cfg = cfg; - plug->env.cls = plug->short_name; - GNUNET_CONTAINER_DLL_insert (plugins_head, plugins_tail, plug); - } - GNUNET_free (plugs); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Starting transport plugins `%s'\n"), + plugs); + for (pos = strtok(plugs, " "); pos != NULL; pos = strtok(NULL, " ")) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Loading `%s' transport plugin\n"), + pos); + GNUNET_asprintf(&libname, "libgnunet_plugin_transport_%s", pos); + plug = GNUNET_new(struct TransportPlugin); + plug->short_name = GNUNET_strdup(pos); + plug->lib_name = libname; + plug->env.cfg = cfg; + plug->env.cls = plug->short_name; + GNUNET_CONTAINER_DLL_insert(plugins_head, plugins_tail, plug); + } + GNUNET_free(plugs); next = plugins_head; while (next != NULL) - { - plug = next; - next = plug->next; - plug->api = GNUNET_PLUGIN_load (plug->lib_name, &plug->env); - if (plug->api == NULL) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to load transport plugin for `%s'\n"), - plug->lib_name); - GNUNET_CONTAINER_DLL_remove (plugins_head, plugins_tail, plug); - GNUNET_free (plug->short_name); - GNUNET_free (plug->lib_name); - GNUNET_free (plug); + plug = next; + next = plug->next; + plug->api = GNUNET_PLUGIN_load(plug->lib_name, &plug->env); + if (plug->api == NULL) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to load transport plugin for `%s'\n"), + plug->lib_name); + GNUNET_CONTAINER_DLL_remove(plugins_head, plugins_tail, plug); + GNUNET_free(plug->short_name); + GNUNET_free(plug->lib_name); + GNUNET_free(plug); + } } - } } @@ -141,18 +139,18 @@ GPI_plugins_load (const struct GNUNET_CONFIGURATION_Handle *cfg) * Unload all plugins */ void -GPI_plugins_unload () +GPI_plugins_unload() { struct TransportPlugin *plug; while (NULL != (plug = plugins_head)) - { - GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api)); - GNUNET_free (plug->lib_name); - GNUNET_free (plug->short_name); - GNUNET_CONTAINER_DLL_remove (plugins_head, plugins_tail, plug); - GNUNET_free (plug); - } + { + GNUNET_break(NULL == GNUNET_PLUGIN_unload(plug->lib_name, plug->api)); + GNUNET_free(plug->lib_name); + GNUNET_free(plug->short_name); + GNUNET_CONTAINER_DLL_remove(plugins_head, plugins_tail, plug); + GNUNET_free(plug); + } } @@ -163,31 +161,32 @@ GPI_plugins_unload () * @return the plugin's API, NULL if the plugin is not loaded */ struct GNUNET_TRANSPORT_PluginFunctions * -GPI_plugins_find (const char *name) +GPI_plugins_find(const char *name) { struct TransportPlugin *head = plugins_head; - char *stripped = GNUNET_strdup (name); + char *stripped = GNUNET_strdup(name); char *head_stripped; - char *sep = strchr (stripped, '_'); + char *sep = strchr(stripped, '_'); + if (NULL != sep) sep[0] = '\0'; while (head != NULL) - { - head_stripped = GNUNET_strdup(head->short_name); - char *head_sep = strchr (head_stripped, '_'); - if (NULL != head_sep) - head_sep[0] = '\0'; - if (0 == strcmp (head_stripped, stripped)) { - GNUNET_free (head_stripped); - break; + head_stripped = GNUNET_strdup(head->short_name); + char *head_sep = strchr(head_stripped, '_'); + if (NULL != head_sep) + head_sep[0] = '\0'; + if (0 == strcmp(head_stripped, stripped)) + { + GNUNET_free(head_stripped); + break; + } + GNUNET_free(head_stripped); + head = head->next; } - GNUNET_free (head_stripped); - head = head->next; - } - GNUNET_free (stripped); + GNUNET_free(stripped); if (NULL == head) return NULL; return head->api; diff --git a/src/peerinfo-tool/gnunet-peerinfo_plugins.h b/src/peerinfo-tool/gnunet-peerinfo_plugins.h index 53196677a..b278cfa21 100644 --- a/src/peerinfo-tool/gnunet-peerinfo_plugins.h +++ b/src/peerinfo-tool/gnunet-peerinfo_plugins.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerinfo-tool/gnunet-peerinfo_plugins.h @@ -34,14 +34,14 @@ * @param cfg configuration to use */ void -GPI_plugins_load (const struct GNUNET_CONFIGURATION_Handle *cfg); +GPI_plugins_load(const struct GNUNET_CONFIGURATION_Handle *cfg); /** * Unload all plugins */ void -GPI_plugins_unload (void); +GPI_plugins_unload(void); /** @@ -51,7 +51,7 @@ GPI_plugins_unload (void); * @return the plugin's API, NULL if the plugin is not loaded */ struct GNUNET_TRANSPORT_PluginFunctions * -GPI_plugins_find (const char *name); +GPI_plugins_find(const char *name); #endif diff --git a/src/peerinfo-tool/plugin_rest_peerinfo.c b/src/peerinfo-tool/plugin_rest_peerinfo.c index 24af2c193..238946d54 100644 --- a/src/peerinfo-tool/plugin_rest_peerinfo.c +++ b/src/peerinfo-tool/plugin_rest_peerinfo.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach * @author Philippe Buschmann @@ -61,7 +61,7 @@ /** * How long until we time out during address lookup? */ -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) /** * The configuration handle */ @@ -75,8 +75,7 @@ static char* allow_methods; /** * @brief struct returned by the initialization function of the plugin */ -struct Plugin -{ +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; }; @@ -84,8 +83,7 @@ struct Plugin /** * Record we keep for each printable address. */ -struct AddressRecord -{ +struct AddressRecord { /** * Current address-to-string context (if active, otherwise NULL). */ @@ -111,8 +109,7 @@ struct AddressRecord /** * Structure we use to collect printable address information. */ -struct PrintContext -{ +struct PrintContext { /** * Kept in DLL. */ @@ -157,7 +154,6 @@ struct PrintContext * RequestHandle */ struct RequestHandle *handle; - }; /** @@ -173,8 +169,7 @@ static struct PrintContext *pc_tail; /** * The request handle */ -struct RequestHandle -{ +struct RequestHandle { /** * JSON temporary array */ @@ -214,7 +209,7 @@ struct RequestHandle * Rest connection */ struct GNUNET_REST_RequestHandle *rest_handle; - + /** * Desired timeout for the lookup (default is no timeout). */ @@ -249,7 +244,6 @@ struct RequestHandle * Reponse code */ int response_code; - }; @@ -258,51 +252,51 @@ struct RequestHandle * @param handle Handle to clean up */ static void -cleanup_handle (void *cls) +cleanup_handle(void *cls) { struct RequestHandle *handle = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Cleaning up\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Cleaning up\n"); if (NULL != handle->timeout_task) - { - GNUNET_SCHEDULER_cancel (handle->timeout_task); - handle->timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(handle->timeout_task); + handle->timeout_task = NULL; + } if (NULL != handle->url) - GNUNET_free (handle->url); + GNUNET_free(handle->url); if (NULL != handle->emsg) - GNUNET_free (handle->emsg); + GNUNET_free(handle->emsg); if (NULL != handle->address) - GNUNET_free ((char*)handle->address); + GNUNET_free((char*)handle->address); if (NULL != handle->expiration_str) - GNUNET_free (handle->expiration_str); + GNUNET_free(handle->expiration_str); if (NULL != handle->pubkey) - GNUNET_free (handle->pubkey); + GNUNET_free(handle->pubkey); if (NULL != handle->temp_array) - { - json_decref(handle->temp_array); - handle->temp_array = NULL; - } + { + json_decref(handle->temp_array); + handle->temp_array = NULL; + } if (NULL != handle->response) - { - json_decref(handle->response); - handle->response = NULL; - } + { + json_decref(handle->response); + handle->response = NULL; + } if (NULL != handle->list_it) - { - GNUNET_PEERINFO_iterate_cancel(handle->list_it); - handle->list_it = NULL; - } + { + GNUNET_PEERINFO_iterate_cancel(handle->list_it); + handle->list_it = NULL; + } if (NULL != handle->peerinfo_handle) - { - GNUNET_PEERINFO_disconnect(handle->peerinfo_handle); - handle->peerinfo_handle = NULL; - } - - GNUNET_free (handle); + { + GNUNET_PEERINFO_disconnect(handle->peerinfo_handle); + handle->peerinfo_handle = NULL; + } + + GNUNET_free(handle); } @@ -312,7 +306,7 @@ cleanup_handle (void *cls) * @param cls the `struct RequestHandle` */ static void -do_error (void *cls) +do_error(void *cls) { struct RequestHandle *handle = cls; struct MHD_Response *resp; @@ -322,16 +316,16 @@ do_error (void *cls) if (NULL == handle->emsg) handle->emsg = GNUNET_strdup(GNUNET_REST_PEERINFO_ERROR_UNKNOWN); - json_object_set_new(json_error,"error", json_string(handle->emsg)); + json_object_set_new(json_error, "error", json_string(handle->emsg)); if (0 == handle->response_code) handle->response_code = MHD_HTTP_OK; - response = json_dumps (json_error, 0); - resp = GNUNET_REST_create_response (response); - handle->proc (handle->proc_cls, resp, handle->response_code); + response = json_dumps(json_error, 0); + resp = GNUNET_REST_create_response(response); + handle->proc(handle->proc_cls, resp, handle->response_code); json_decref(json_error); GNUNET_free(response); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } @@ -341,26 +335,26 @@ do_error (void *cls) * @param cls the `struct RequestHandle` */ static void -peerinfo_list_finished (void *cls) +peerinfo_list_finished(void *cls) { struct RequestHandle *handle = cls; char *result_str; struct MHD_Response *resp; if (NULL == handle->response) - { - handle->response_code = MHD_HTTP_NOT_FOUND; - handle->emsg = GNUNET_strdup ("No peers found"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->response_code = MHD_HTTP_NOT_FOUND; + handle->emsg = GNUNET_strdup("No peers found"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } - result_str = json_dumps (handle->response, 0); + result_str = json_dumps(handle->response, 0); GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result_str); - resp = GNUNET_REST_create_response (result_str); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_free_non_null (result_str); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + resp = GNUNET_REST_create_response(result_str); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_free_non_null(result_str); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); } @@ -373,16 +367,16 @@ peerinfo_list_finished (void *cls) * @return #GNUNET_OK to keep the address and continue */ static int -count_address (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +count_address(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { struct PrintContext *pc = cls; - if (0 == GNUNET_TIME_absolute_get_remaining (expiration).rel_value_us) - { - return GNUNET_OK; /* ignore expired address */ - } + if (0 == GNUNET_TIME_absolute_get_remaining(expiration).rel_value_us) + { + return GNUNET_OK; /* ignore expired address */ + } pc->off++; return GNUNET_OK; @@ -395,7 +389,7 @@ count_address (void *cls, * @param pc printing context */ static void -dump_pc (struct PrintContext *pc) +dump_pc(struct PrintContext *pc) { struct RequestHandle *handle; unsigned int i; @@ -411,59 +405,58 @@ dump_pc (struct PrintContext *pc) response_entry = json_object(); for (i = 0; i < pc->num_addresses; i++) - { - if (NULL != pc->address_list[i].result) { - object = json_object (); - address = json_string(pc->address_list[i].result); - expires = json_string( - GNUNET_STRINGS_absolute_time_to_string (pc->address_list[i].expiration)); - json_object_set (object, "address", address); - json_object_set (object, "expires", expires); - - json_decref(address); - json_decref(expires); - - json_array_append(temp_array, object); - json_decref(object); - GNUNET_free (pc->address_list[i].result); + if (NULL != pc->address_list[i].result) + { + object = json_object(); + address = json_string(pc->address_list[i].result); + expires = json_string( + GNUNET_STRINGS_absolute_time_to_string(pc->address_list[i].expiration)); + json_object_set(object, "address", address); + json_object_set(object, "expires", expires); + + json_decref(address); + json_decref(expires); + + json_array_append(temp_array, object); + json_decref(object); + GNUNET_free(pc->address_list[i].result); + } } - } if (0 < json_array_size(temp_array)) - { - GNUNET_asprintf(&friend_and_peer, - "%s%s", - (GNUNET_YES == pc->friend_only) ? "F2F:" : "", - GNUNET_i2s_full (&pc->peer)); - friend_and_peer_json = json_string(friend_and_peer); - json_object_set(response_entry, - GNUNET_REST_PEERINFO_PEER, - friend_and_peer_json); - json_object_set(response_entry, - GNUNET_REST_PEERINFO_ARRAY, - temp_array); - json_array_append(pc->handle->response, response_entry); - json_decref(friend_and_peer_json); - GNUNET_free(friend_and_peer); - } - - json_decref (temp_array); + { + GNUNET_asprintf(&friend_and_peer, + "%s%s", + (GNUNET_YES == pc->friend_only) ? "F2F:" : "", + GNUNET_i2s_full(&pc->peer)); + friend_and_peer_json = json_string(friend_and_peer); + json_object_set(response_entry, + GNUNET_REST_PEERINFO_PEER, + friend_and_peer_json); + json_object_set(response_entry, + GNUNET_REST_PEERINFO_ARRAY, + temp_array); + json_array_append(pc->handle->response, response_entry); + json_decref(friend_and_peer_json); + GNUNET_free(friend_and_peer); + } + + json_decref(temp_array); json_decref(response_entry); - GNUNET_free_non_null (pc->address_list); - GNUNET_CONTAINER_DLL_remove (pc_head, - pc_tail, - pc); + GNUNET_free_non_null(pc->address_list); + GNUNET_CONTAINER_DLL_remove(pc_head, + pc_tail, + pc); handle = pc->handle; - GNUNET_free (pc); - - if ( (NULL == pc_head) && - (NULL == handle->list_it) ) - { - GNUNET_SCHEDULER_add_now (&peerinfo_list_finished, handle); - } + GNUNET_free(pc); + if ((NULL == pc_head) && + (NULL == handle->list_it)) + { + GNUNET_SCHEDULER_add_now(&peerinfo_list_finished, handle); + } } @@ -478,31 +471,31 @@ dump_pc (struct PrintContext *pc) * if #GNUNET_SYSERR: address is invalid */ static void -process_resolved_address (void *cls, - const char *address, - int res) +process_resolved_address(void *cls, + const char *address, + int res) { struct AddressRecord *ar = cls; struct PrintContext *pc = ar->pc; if (NULL != address) - { - if (0 != strlen (address)) { - if (NULL != ar->result) - GNUNET_free (ar->result); - ar->result = GNUNET_strdup (address); + if (0 != strlen(address)) + { + if (NULL != ar->result) + GNUNET_free(ar->result); + ar->result = GNUNET_strdup(address); + } + return; } - return; - } ar->atsc = NULL; if (GNUNET_SYSERR == res) - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Failure: Cannot convert address to string for peer `%s'\n"), - GNUNET_i2s (&ar->pc->peer)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Failure: Cannot convert address to string for peer `%s'\n"), + GNUNET_i2s(&ar->pc->peer)); pc->num_addresses++; if (pc->num_addresses == pc->address_list_size) - dump_pc (ar->pc); + dump_pc(ar->pc); } @@ -515,33 +508,33 @@ process_resolved_address (void *cls, * @return #GNUNET_OK to keep the address and continue */ static int -print_address (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +print_address(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { struct PrintContext *pc = cls; struct AddressRecord *ar; - if (0 == GNUNET_TIME_absolute_get_remaining (expiration).rel_value_us) - { - return GNUNET_OK; /* ignore expired address */ - } + if (0 == GNUNET_TIME_absolute_get_remaining(expiration).rel_value_us) + { + return GNUNET_OK; /* ignore expired address */ + } - GNUNET_assert (0 < pc->off); + GNUNET_assert(0 < pc->off); ar = &pc->address_list[--pc->off]; ar->pc = pc; ar->expiration = expiration; - GNUNET_asprintf (&ar->result, - "%s:%u:%u", - address->transport_name, - address->address_length, - address->local_info); - ar->atsc = GNUNET_TRANSPORT_address_to_string (cfg, - address, - GNUNET_NO, - TIMEOUT, - &process_resolved_address, - ar); + GNUNET_asprintf(&ar->result, + "%s:%u:%u", + address->transport_name, + address->address_length, + address->local_info); + ar->atsc = GNUNET_TRANSPORT_address_to_string(cfg, + address, + GNUNET_NO, + TIMEOUT, + &process_resolved_address, + ar); return GNUNET_OK; } @@ -557,63 +550,63 @@ print_address (void *cls, */ void peerinfo_list_iteration(void *cls, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello, - const char *err_msg) + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello, + const char *err_msg) { struct RequestHandle *handle = cls; struct PrintContext *pc; int friend_only; if (NULL == handle->response) - { - handle->response = json_array(); - } + { + handle->response = json_array(); + } if (NULL == peer) - { - handle->list_it = NULL; - handle->emsg = GNUNET_strdup ("Error in communication with peerinfo"); - if (NULL != err_msg) { - GNUNET_free(handle->emsg); - handle->emsg = GNUNET_strdup (err_msg); - handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; + handle->list_it = NULL; + handle->emsg = GNUNET_strdup("Error in communication with peerinfo"); + if (NULL != err_msg) + { + GNUNET_free(handle->emsg); + handle->emsg = GNUNET_strdup(err_msg); + handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; + } + if (NULL == pc_head) + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; } - if (NULL == pc_head) - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } if (NULL == hello) return; friend_only = GNUNET_NO; if (NULL != hello) - friend_only = GNUNET_HELLO_is_friend_only (hello); + friend_only = GNUNET_HELLO_is_friend_only(hello); pc = GNUNET_new(struct PrintContext); - GNUNET_CONTAINER_DLL_insert (pc_head, - pc_tail, - pc); + GNUNET_CONTAINER_DLL_insert(pc_head, + pc_tail, + pc); pc->peer = *peer; pc->friend_only = friend_only; pc->handle = handle; - GNUNET_HELLO_iterate_addresses (hello, - GNUNET_NO, - &count_address, - pc); + GNUNET_HELLO_iterate_addresses(hello, + GNUNET_NO, + &count_address, + pc); if (0 == pc->off) - { - dump_pc (pc); - return; - } + { + dump_pc(pc); + return; + } pc->address_list_size = pc->off; pc->address_list = GNUNET_malloc( - sizeof(struct AddressRecord) * pc->off); - GNUNET_HELLO_iterate_addresses (hello, - GNUNET_NO, - &print_address, - pc); + sizeof(struct AddressRecord) * pc->off); + GNUNET_HELLO_iterate_addresses(hello, + GNUNET_NO, + &print_address, + pc); } /** @@ -624,9 +617,9 @@ peerinfo_list_iteration(void *cls, * @param cls the RequestHandle */ void -peerinfo_get (struct GNUNET_REST_RequestHandle *con_handle, - const char* url, - void *cls) +peerinfo_get(struct GNUNET_REST_RequestHandle *con_handle, + const char* url, + void *cls) { struct RequestHandle *handle = cls; struct GNUNET_HashCode key; @@ -636,38 +629,38 @@ peerinfo_get (struct GNUNET_REST_RequestHandle *con_handle, char* include_friend_only_str; include_friend_only = GNUNET_NO; - GNUNET_CRYPTO_hash (GNUNET_REST_PEERINFO_FRIEND, - strlen (GNUNET_REST_PEERINFO_FRIEND), - &key); - if ( GNUNET_YES - == GNUNET_CONTAINER_multihashmap_contains (con_handle->url_param_map, - &key)) - { - include_friend_only_str = GNUNET_CONTAINER_multihashmap_get ( - con_handle->url_param_map, &key); - if (0 == strcmp(include_friend_only_str, "yes")) + GNUNET_CRYPTO_hash(GNUNET_REST_PEERINFO_FRIEND, + strlen(GNUNET_REST_PEERINFO_FRIEND), + &key); + if (GNUNET_YES + == GNUNET_CONTAINER_multihashmap_contains(con_handle->url_param_map, + &key)) { - include_friend_only = GNUNET_YES; + include_friend_only_str = GNUNET_CONTAINER_multihashmap_get( + con_handle->url_param_map, &key); + if (0 == strcmp(include_friend_only_str, "yes")) + { + include_friend_only = GNUNET_YES; + } } - } specific_peer = NULL; - GNUNET_CRYPTO_hash (GNUNET_REST_PEERINFO_PEER, - strlen (GNUNET_REST_PEERINFO_PEER), - &key); - if ( GNUNET_YES - == GNUNET_CONTAINER_multihashmap_contains (con_handle->url_param_map, - &key)) - { - //peer_id = *(unsigned int*)GNUNET_CONTAINER_multihashmap_get (con_handle->url_param_map, &key); - //specific_peer = GNUNET_PEER_resolve2(peer_id); - } + GNUNET_CRYPTO_hash(GNUNET_REST_PEERINFO_PEER, + strlen(GNUNET_REST_PEERINFO_PEER), + &key); + if (GNUNET_YES + == GNUNET_CONTAINER_multihashmap_contains(con_handle->url_param_map, + &key)) + { + //peer_id = *(unsigned int*)GNUNET_CONTAINER_multihashmap_get (con_handle->url_param_map, &key); + //specific_peer = GNUNET_PEER_resolve2(peer_id); + } handle->list_it = GNUNET_PEERINFO_iterate(handle->peerinfo_handle, - include_friend_only, - specific_peer, - &peerinfo_list_iteration, - handle); + include_friend_only, + specific_peer, + &peerinfo_list_iteration, + handle); } @@ -680,20 +673,20 @@ peerinfo_get (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ static void -options_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char* url, - void *cls) +options_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char* url, + void *cls) { struct MHD_Response *resp; struct RequestHandle *handle = cls; //independent of path return all options - resp = GNUNET_REST_create_response (NULL); - MHD_add_response_header (resp, - "Access-Control-Allow-Methods", - allow_methods); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_SCHEDULER_add_now (&cleanup_handle, handle); + resp = GNUNET_REST_create_response(NULL); + MHD_add_response_header(resp, + "Access-Control-Allow-Methods", + allow_methods); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_SCHEDULER_add_now(&cleanup_handle, handle); return; } @@ -704,23 +697,23 @@ options_cont (struct GNUNET_REST_RequestHandle *con_handle, * @param handle the request handle */ static void -init_cont (struct RequestHandle *handle) +init_cont(struct RequestHandle *handle) { struct GNUNET_REST_RequestHandlerError err; static const struct GNUNET_REST_RequestHandler handlers[] = { - {MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_PEERINFO, &peerinfo_get}, - {MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_PEERINFO, &options_cont}, + { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_PEERINFO, &peerinfo_get }, + { MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_PEERINFO, &options_cont }, GNUNET_REST_HANDLER_END }; - if (GNUNET_NO == GNUNET_REST_handle_request (handle->rest_handle, - handlers, - &err, - handle)) - { - handle->response_code = err.error_code; - GNUNET_SCHEDULER_add_now (&do_error, handle); - } + if (GNUNET_NO == GNUNET_REST_handle_request(handle->rest_handle, + handlers, + &err, + handle)) + { + handle->response_code = err.error_code; + GNUNET_SCHEDULER_add_now(&do_error, handle); + } } @@ -737,29 +730,29 @@ init_cont (struct RequestHandle *handle) */ static void rest_process_request(struct GNUNET_REST_RequestHandle *rest_handle, - GNUNET_REST_ResultProcessor proc, - void *proc_cls) + GNUNET_REST_ResultProcessor proc, + void *proc_cls) { - struct RequestHandle *handle = GNUNET_new (struct RequestHandle); - + struct RequestHandle *handle = GNUNET_new(struct RequestHandle); + handle->response_code = 0; - handle->timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60); + handle->timeout = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60); handle->proc_cls = proc_cls; handle->proc = proc; handle->rest_handle = rest_handle; - - handle->url = GNUNET_strdup (rest_handle->url); - if (handle->url[strlen (handle->url)-1] == '/') - handle->url[strlen (handle->url)-1] = '\0'; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n"); + + handle->url = GNUNET_strdup(rest_handle->url); + if (handle->url[strlen(handle->url) - 1] == '/') + handle->url[strlen(handle->url) - 1] = '\0'; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n"); handle->peerinfo_handle = GNUNET_PEERINFO_connect(cfg); init_cont(handle); handle->timeout_task = - GNUNET_SCHEDULER_add_delayed (handle->timeout, - &do_error, - handle); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected\n"); + GNUNET_SCHEDULER_add_delayed(handle->timeout, + &do_error, + handle); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connected\n"); } @@ -770,7 +763,7 @@ rest_process_request(struct GNUNET_REST_RequestHandle *rest_handle, * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_rest_peerinfo_init (void *cls) +libgnunet_plugin_rest_peerinfo_init(void *cls) { static struct Plugin plugin; struct GNUNET_REST_Plugin *api; @@ -778,22 +771,22 @@ libgnunet_plugin_rest_peerinfo_init (void *cls) cfg = cls; if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.cfg = cfg; - api = GNUNET_new (struct GNUNET_REST_Plugin); + api = GNUNET_new(struct GNUNET_REST_Plugin); api->cls = &plugin; api->name = GNUNET_REST_API_NS_PEERINFO; api->process_request = &rest_process_request; - GNUNET_asprintf (&allow_methods, - "%s, %s, %s, %s, %s", - MHD_HTTP_METHOD_GET, - MHD_HTTP_METHOD_POST, - MHD_HTTP_METHOD_PUT, - MHD_HTTP_METHOD_DELETE, - MHD_HTTP_METHOD_OPTIONS); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - _("Peerinfo REST API initialized\n")); + GNUNET_asprintf(&allow_methods, + "%s, %s, %s, %s, %s", + MHD_HTTP_METHOD_GET, + MHD_HTTP_METHOD_POST, + MHD_HTTP_METHOD_PUT, + MHD_HTTP_METHOD_DELETE, + MHD_HTTP_METHOD_OPTIONS); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + _("Peerinfo REST API initialized\n")); return api; } @@ -805,16 +798,17 @@ libgnunet_plugin_rest_peerinfo_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_rest_peerinfo_done (void *cls) +libgnunet_plugin_rest_peerinfo_done(void *cls) { struct GNUNET_REST_Plugin *api = cls; struct Plugin *plugin = api->cls; + plugin->cfg = NULL; - GNUNET_free_non_null (allow_methods); - GNUNET_free (api); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Peerinfo REST plugin is finished\n"); + GNUNET_free_non_null(allow_methods); + GNUNET_free(api); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Peerinfo REST plugin is finished\n"); return NULL; } diff --git a/src/peerinfo/gnunet-service-peerinfo.c b/src/peerinfo/gnunet-service-peerinfo.c index a884c5b76..25a3fabd7 100644 --- a/src/peerinfo/gnunet-service-peerinfo.c +++ b/src/peerinfo/gnunet-service-peerinfo.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerinfo/gnunet-service-peerinfo.c @@ -39,21 +39,19 @@ * How often do we scan the HOST_DIR for new entries? */ #define DATA_HOST_FREQ \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15) /** * How often do we discard old entries in data/hosts/? */ #define DATA_HOST_CLEAN_FREQ \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 60) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 60) /** * In-memory cache of known hosts. */ -struct HostEntry -{ - +struct HostEntry { /** * Identity of the peer. */ @@ -74,8 +72,7 @@ struct HostEntry /** * Result of reading a file */ -struct ReadHostFileContext -{ +struct ReadHostFileContext { /** * Hello for the peer (can be NULL) */ @@ -135,7 +132,7 @@ static struct GNUNET_SCHEDULER_Task *cron_scan; * @return generated notification message */ static struct InfoMessage * -make_info_message (const struct HostEntry *he, int include_friend_only) +make_info_message(const struct HostEntry *he, int include_friend_only) { struct InfoMessage *im; struct GNUNET_HELLO_Message *src; @@ -145,12 +142,12 @@ make_info_message (const struct HostEntry *he, int include_friend_only) src = he->friend_only_hello; else src = he->hello; - hs = (NULL == src) ? 0 : GNUNET_HELLO_size (src); - im = GNUNET_malloc (sizeof (struct InfoMessage) + hs); - im->header.size = htons (hs + sizeof (struct InfoMessage)); - im->header.type = htons (GNUNET_MESSAGE_TYPE_PEERINFO_INFO); + hs = (NULL == src) ? 0 : GNUNET_HELLO_size(src); + im = GNUNET_malloc(sizeof(struct InfoMessage) + hs); + im->header.size = htons(hs + sizeof(struct InfoMessage)); + im->header.type = htons(GNUNET_MESSAGE_TYPE_PEERINFO_INFO); im->peer = he->identity; - GNUNET_memcpy (&im[1], src, hs); + GNUNET_memcpy(&im[1], src, hs); return im; } @@ -164,19 +161,19 @@ make_info_message (const struct HostEntry *he, int include_friend_only) * @return #GNUNET_NO if expiration smaller than the current time */ static int -discard_expired (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +discard_expired(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { const struct GNUNET_TIME_Absolute *now = cls; if (now->abs_value_us > expiration.abs_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Removing expired address of transport `%s'\n"), - address->transport_name); - return GNUNET_NO; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Removing expired address of transport `%s'\n"), + address->transport_name); + return GNUNET_NO; + } return GNUNET_OK; } @@ -190,14 +187,14 @@ discard_expired (void *cls, * @return #GNUNET_OK (always) */ static int -count_addresses (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +count_addresses(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { unsigned int *cnt = cls; - (void) address; - (void) expiration; + (void)address; + (void)expiration; (*cnt)++; return GNUNET_OK; } @@ -211,17 +208,17 @@ count_addresses (void *cls, * @return filename of the form DIRECTORY/HOSTID */ static char * -get_host_filename (const struct GNUNET_PeerIdentity *id) +get_host_filename(const struct GNUNET_PeerIdentity *id) { char *fn; if (NULL == networkIdDirectory) return NULL; - GNUNET_asprintf (&fn, - "%s%s%s", - networkIdDirectory, - DIR_SEPARATOR_STR, - GNUNET_i2s_full (id)); + GNUNET_asprintf(&fn, + "%s%s%s", + networkIdDirectory, + DIR_SEPARATOR_STR, + GNUNET_i2s_full(id)); return fn; } @@ -233,24 +230,24 @@ get_host_filename (const struct GNUNET_PeerIdentity *id) * @param entry entry to broadcast about */ static void -notify_all (struct HostEntry *entry) +notify_all(struct HostEntry *entry) { struct InfoMessage *msg_pub; struct InfoMessage *msg_friend; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Notifying all clients about peer `%s'\n", - GNUNET_i2s (&entry->identity)); - msg_pub = make_info_message (entry, GNUNET_NO); - GNUNET_notification_context_broadcast (notify_list, - &msg_pub->header, - GNUNET_NO); - GNUNET_free (msg_pub); - msg_friend = make_info_message (entry, GNUNET_YES); - GNUNET_notification_context_broadcast (notify_friend_only_list, - &msg_friend->header, - GNUNET_NO); - GNUNET_free (msg_friend); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Notifying all clients about peer `%s'\n", + GNUNET_i2s(&entry->identity)); + msg_pub = make_info_message(entry, GNUNET_NO); + GNUNET_notification_context_broadcast(notify_list, + &msg_pub->header, + GNUNET_NO); + GNUNET_free(msg_pub); + msg_friend = make_info_message(entry, GNUNET_YES); + GNUNET_notification_context_broadcast(notify_friend_only_list, + &msg_friend->header, + GNUNET_NO); + GNUNET_free(msg_friend); } @@ -261,8 +258,8 @@ notify_all (struct HostEntry *entry) * @param hello the verified (!) hello message */ static void -update_hello (const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello); +update_hello(const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello); /** @@ -277,9 +274,9 @@ update_hello (const struct GNUNET_PeerIdentity *peer, * @param r ReadHostFileContext to store the resutl */ static void -read_host_file (const char *fn, - int unlink_garbage, - struct ReadHostFileContext *r) +read_host_file(const char *fn, + int unlink_garbage, + struct ReadHostFileContext *r) { char buffer[GNUNET_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN; ssize_t size_total; @@ -293,114 +290,114 @@ read_host_file (const char *fn, r->friend_only_hello = NULL; r->hello = NULL; - if (GNUNET_YES != GNUNET_DISK_file_test (fn)) + if (GNUNET_YES != GNUNET_DISK_file_test(fn)) return; - size_total = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Read %d bytes from `%s'\n", - (int) size_total, - fn); + size_total = GNUNET_DISK_fn_read(fn, buffer, sizeof(buffer)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Read %d bytes from `%s'\n", + (int)size_total, + fn); if ((size_total < 0) || - (((size_t) size_total) < sizeof (struct GNUNET_MessageHeader))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to parse HELLO in file `%s': %s\n"), - fn, - "File has invalid size"); - if ((GNUNET_YES == unlink_garbage) && (0 != unlink (fn)) && - (ENOENT != errno)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn); - return; - } - - read_pos = 0; - while (read_pos < (size_t) size_total) - { - hello = (const struct GNUNET_HELLO_Message *) &buffer[read_pos]; - size_hello = GNUNET_HELLO_size (hello); - if ((0 == size_hello) || (((size_t) size_total) - read_pos < size_hello)) + (((size_t)size_total) < sizeof(struct GNUNET_MessageHeader))) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to parse HELLO in file `%s'\n"), - fn); - if (0 == read_pos) - { - if ((GNUNET_YES == unlink_garbage) && (0 != unlink (fn)) && - (ENOENT != errno)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn); - } - else - { - if ((GNUNET_YES == unlink_garbage) && (0 != truncate (fn, read_pos)) && - (ENOENT != errno)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "truncate", fn); - } + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to parse HELLO in file `%s': %s\n"), + fn, + "File has invalid size"); + if ((GNUNET_YES == unlink_garbage) && (0 != unlink(fn)) && + (ENOENT != errno)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", fn); return; } - now = GNUNET_TIME_absolute_get (); - hello_clean = GNUNET_HELLO_iterate_addresses (hello, - GNUNET_YES, - &discard_expired, - &now); - if (NULL == hello_clean) + read_pos = 0; + while (read_pos < (size_t)size_total) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Failed to parse HELLO in file `%s'\n"), - fn); - if ((GNUNET_YES == unlink_garbage) && (0 != unlink (fn)) && - (ENOENT != errno)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn); - return; - } - left = 0; - (void) GNUNET_HELLO_iterate_addresses (hello_clean, + hello = (const struct GNUNET_HELLO_Message *)&buffer[read_pos]; + size_hello = GNUNET_HELLO_size(hello); + if ((0 == size_hello) || (((size_t)size_total) - read_pos < size_hello)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to parse HELLO in file `%s'\n"), + fn); + if (0 == read_pos) + { + if ((GNUNET_YES == unlink_garbage) && (0 != unlink(fn)) && + (ENOENT != errno)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", fn); + } + else + { + if ((GNUNET_YES == unlink_garbage) && (0 != truncate(fn, read_pos)) && + (ENOENT != errno)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "truncate", fn); + } + return; + } + + now = GNUNET_TIME_absolute_get(); + hello_clean = GNUNET_HELLO_iterate_addresses(hello, + GNUNET_YES, + &discard_expired, + &now); + if (NULL == hello_clean) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to parse HELLO in file `%s'\n"), + fn); + if ((GNUNET_YES == unlink_garbage) && (0 != unlink(fn)) && + (ENOENT != errno)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", fn); + return; + } + left = 0; + (void)GNUNET_HELLO_iterate_addresses(hello_clean, GNUNET_NO, &count_addresses, &left); - if (0 == left) - { - GNUNET_free (hello_clean); - break; - } - - if (GNUNET_NO == GNUNET_HELLO_is_friend_only (hello_clean)) - { - if (NULL == r->hello) - r->hello = hello_clean; + if (0 == left) + { + GNUNET_free(hello_clean); + break; + } + + if (GNUNET_NO == GNUNET_HELLO_is_friend_only(hello_clean)) + { + if (NULL == r->hello) + r->hello = hello_clean; + else + { + GNUNET_break(0); + GNUNET_free(r->hello); + r->hello = hello_clean; + } + } else - { - GNUNET_break (0); - GNUNET_free (r->hello); - r->hello = hello_clean; - } + { + if (NULL == r->friend_only_hello) + r->friend_only_hello = hello_clean; + else + { + GNUNET_break(0); + GNUNET_free(r->friend_only_hello); + r->friend_only_hello = hello_clean; + } + } + read_pos += size_hello; } - else - { - if (NULL == r->friend_only_hello) - r->friend_only_hello = hello_clean; - else - { - GNUNET_break (0); - GNUNET_free (r->friend_only_hello); - r->friend_only_hello = hello_clean; - } - } - read_pos += size_hello; - } if (0 == left) - { - /* no addresses left, remove from disk */ - if ((GNUNET_YES == unlink_garbage) && (0 != unlink (fn))) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Found `%s' and `%s' HELLO message in file\n", - (NULL != r->hello) ? "public" : "NON-public", - (NULL != r->friend_only_hello) ? "friend only" - : "NO friend only"); + { + /* no addresses left, remove from disk */ + if ((GNUNET_YES == unlink_garbage) && (0 != unlink(fn))) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "unlink", fn); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Found `%s' and `%s' HELLO message in file\n", + (NULL != r->hello) ? "public" : "NON-public", + (NULL != r->friend_only_hello) ? "friend only" + : "NO friend only"); } @@ -411,44 +408,44 @@ read_host_file (const char *fn, * @return the HostEntry */ static struct HostEntry * -add_host_to_known_hosts (const struct GNUNET_PeerIdentity *identity) +add_host_to_known_hosts(const struct GNUNET_PeerIdentity *identity) { struct HostEntry *entry; struct ReadHostFileContext r; char *fn; - entry = GNUNET_CONTAINER_multipeermap_get (hostmap, identity); + entry = GNUNET_CONTAINER_multipeermap_get(hostmap, identity); if (NULL == entry) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding new peer `%s'\n", - GNUNET_i2s (identity)); - GNUNET_STATISTICS_update (stats, - gettext_noop ("# peers known"), - 1, - GNUNET_NO); - entry = GNUNET_new (struct HostEntry); - entry->identity = *identity; - GNUNET_assert (GNUNET_OK == - GNUNET_CONTAINER_multipeermap_put ( - hostmap, - &entry->identity, - entry, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); - notify_all (entry); - fn = get_host_filename (identity); - if (NULL != fn) { - read_host_file (fn, GNUNET_YES, &r); - if (NULL != r.hello) - update_hello (identity, r.hello); - if (NULL != r.friend_only_hello) - update_hello (identity, r.friend_only_hello); - GNUNET_free_non_null (r.hello); - GNUNET_free_non_null (r.friend_only_hello); - GNUNET_free (fn); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding new peer `%s'\n", + GNUNET_i2s(identity)); + GNUNET_STATISTICS_update(stats, + gettext_noop("# peers known"), + 1, + GNUNET_NO); + entry = GNUNET_new(struct HostEntry); + entry->identity = *identity; + GNUNET_assert(GNUNET_OK == + GNUNET_CONTAINER_multipeermap_put( + hostmap, + &entry->identity, + entry, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + notify_all(entry); + fn = get_host_filename(identity); + if (NULL != fn) + { + read_host_file(fn, GNUNET_YES, &r); + if (NULL != r.hello) + update_hello(identity, r.hello); + if (NULL != r.friend_only_hello) + update_hello(identity, r.friend_only_hello); + GNUNET_free_non_null(r.hello); + GNUNET_free_non_null(r.friend_only_hello); + GNUNET_free(fn); + } } - } return entry; } @@ -460,27 +457,26 @@ add_host_to_known_hosts (const struct GNUNET_PeerIdentity *identity) * @param fullname name of the file to remove */ static void -remove_garbage (const char *fullname) +remove_garbage(const char *fullname) { - if (0 == unlink (fullname)) - GNUNET_log ( + if (0 == unlink(fullname)) + GNUNET_log( GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, - _ ( + _( "File `%s' in directory `%s' does not match naming convention. Removed.\n"), fullname, networkIdDirectory); else - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "unlink", - fullname); + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "unlink", + fullname); } /** * Closure for #hosts_directory_scan_callback(). */ -struct DirScanContext -{ +struct DirScanContext { /** * #GNUNET_YES if we should remove files that are broken, * #GNUNET_NO if the directory we are iterating over should @@ -506,7 +502,7 @@ struct DirScanContext * @return #GNUNET_OK (continue iteration) */ static int -hosts_directory_scan_callback (void *cls, const char *fullname) +hosts_directory_scan_callback(void *cls, const char *fullname) { struct DirScanContext *dsc = cls; struct GNUNET_PeerIdentity identity; @@ -516,81 +512,81 @@ hosts_directory_scan_callback (void *cls, const char *fullname) struct GNUNET_PeerIdentity id_friend; struct GNUNET_PeerIdentity id; - if (GNUNET_YES != GNUNET_DISK_file_test (fullname)) + if (GNUNET_YES != GNUNET_DISK_file_test(fullname)) return GNUNET_OK; /* ignore non-files */ - filename = strrchr (fullname, DIR_SEPARATOR); - if ((NULL == filename) || (1 > strlen (filename))) + filename = strrchr(fullname, DIR_SEPARATOR); + if ((NULL == filename) || (1 > strlen(filename))) filename = fullname; else filename++; - read_host_file (fullname, dsc->remove_files, &r); + read_host_file(fullname, dsc->remove_files, &r); if ((NULL == r.hello) && (NULL == r.friend_only_hello)) return GNUNET_OK; if (NULL != r.friend_only_hello) - { - if (GNUNET_OK != GNUNET_HELLO_get_id (r.friend_only_hello, &id_friend)) { - if (GNUNET_YES == dsc->remove_files) - remove_garbage (fullname); - return GNUNET_OK; + if (GNUNET_OK != GNUNET_HELLO_get_id(r.friend_only_hello, &id_friend)) + { + if (GNUNET_YES == dsc->remove_files) + remove_garbage(fullname); + return GNUNET_OK; + } + id = id_friend; } - id = id_friend; - } if (NULL != r.hello) - { - if (GNUNET_OK != GNUNET_HELLO_get_id (r.hello, &id_public)) { - if (GNUNET_YES == dsc->remove_files) - remove_garbage (fullname); - return GNUNET_OK; + if (GNUNET_OK != GNUNET_HELLO_get_id(r.hello, &id_public)) + { + if (GNUNET_YES == dsc->remove_files) + remove_garbage(fullname); + return GNUNET_OK; + } + id = id_public; } - id = id_public; - } if ((NULL != r.hello) && (NULL != r.friend_only_hello) && - (0 != GNUNET_memcmp (&id_friend, &id_public))) - { - /* HELLOs are not for the same peer */ - GNUNET_break (0); - if (GNUNET_YES == dsc->remove_files) - remove_garbage (fullname); - return GNUNET_OK; - } - if (GNUNET_OK == - GNUNET_CRYPTO_eddsa_public_key_from_string (filename, - strlen (filename), - &identity.public_key)) - { - if (0 != GNUNET_memcmp (&id, &identity)) + (0 != GNUNET_memcmp(&id_friend, &id_public))) { /* HELLOs are not for the same peer */ - GNUNET_break (0); + GNUNET_break(0); if (GNUNET_YES == dsc->remove_files) - remove_garbage (fullname); + remove_garbage(fullname); return GNUNET_OK; } - } + if (GNUNET_OK == + GNUNET_CRYPTO_eddsa_public_key_from_string(filename, + strlen(filename), + &identity.public_key)) + { + if (0 != GNUNET_memcmp(&id, &identity)) + { + /* HELLOs are not for the same peer */ + GNUNET_break(0); + if (GNUNET_YES == dsc->remove_files) + remove_garbage(fullname); + return GNUNET_OK; + } + } /* ok, found something valid, remember HELLO */ - add_host_to_known_hosts (&id); + add_host_to_known_hosts(&id); if (NULL != r.hello) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Updating peer `%s' public HELLO \n", - GNUNET_i2s (&id)); - update_hello (&id, r.hello); - GNUNET_free (r.hello); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Updating peer `%s' public HELLO \n", + GNUNET_i2s(&id)); + update_hello(&id, r.hello); + GNUNET_free(r.hello); + } if (NULL != r.friend_only_hello) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Updating peer `%s' friend only HELLO \n", - GNUNET_i2s (&id)); - update_hello (&id, r.friend_only_hello); - GNUNET_free (r.friend_only_hello); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Updating peer `%s' friend only HELLO \n", + GNUNET_i2s(&id)); + update_hello(&id, r.friend_only_hello); + GNUNET_free(r.friend_only_hello); + } dsc->matched++; return GNUNET_OK; } @@ -602,39 +598,39 @@ hosts_directory_scan_callback (void *cls, const char *fullname) * @param cls unused */ static void -cron_scan_directory_data_hosts (void *cls) +cron_scan_directory_data_hosts(void *cls) { static unsigned int retries; struct DirScanContext dsc; - (void) cls; + (void)cls; cron_scan = NULL; - if (GNUNET_SYSERR == GNUNET_DISK_directory_create (networkIdDirectory)) - { - cron_scan = - GNUNET_SCHEDULER_add_delayed_with_priority (DATA_HOST_FREQ, - GNUNET_SCHEDULER_PRIORITY_IDLE, - &cron_scan_directory_data_hosts, - NULL); - return; - } + if (GNUNET_SYSERR == GNUNET_DISK_directory_create(networkIdDirectory)) + { + cron_scan = + GNUNET_SCHEDULER_add_delayed_with_priority(DATA_HOST_FREQ, + GNUNET_SCHEDULER_PRIORITY_IDLE, + &cron_scan_directory_data_hosts, + NULL); + return; + } dsc.matched = 0; dsc.remove_files = GNUNET_YES; - GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK, - _ ("Scanning directory `%s'\n"), - networkIdDirectory); - GNUNET_DISK_directory_scan (networkIdDirectory, - &hosts_directory_scan_callback, - &dsc); + GNUNET_log(GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK, + _("Scanning directory `%s'\n"), + networkIdDirectory); + GNUNET_DISK_directory_scan(networkIdDirectory, + &hosts_directory_scan_callback, + &dsc); if ((0 == dsc.matched) && (0 == (++retries & 31))) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, - _ ("Still no peers found in `%s'!\n"), - networkIdDirectory); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, + _("Still no peers found in `%s'!\n"), + networkIdDirectory); cron_scan = - GNUNET_SCHEDULER_add_delayed_with_priority (DATA_HOST_FREQ, - GNUNET_SCHEDULER_PRIORITY_IDLE, - &cron_scan_directory_data_hosts, - NULL); + GNUNET_SCHEDULER_add_delayed_with_priority(DATA_HOST_FREQ, + GNUNET_SCHEDULER_PRIORITY_IDLE, + &cron_scan_directory_data_hosts, + NULL); } @@ -646,29 +642,29 @@ cron_scan_directory_data_hosts (void *cls) * @return merged HELLO */ static struct GNUNET_HELLO_Message * -update_friend_hello (const struct GNUNET_HELLO_Message *hello, - const struct GNUNET_HELLO_Message *friend_hello) +update_friend_hello(const struct GNUNET_HELLO_Message *hello, + const struct GNUNET_HELLO_Message *friend_hello) { struct GNUNET_HELLO_Message *res; struct GNUNET_HELLO_Message *tmp; struct GNUNET_PeerIdentity pid; if (NULL != friend_hello) - { - res = GNUNET_HELLO_merge (hello, friend_hello); - GNUNET_assert (GNUNET_YES == GNUNET_HELLO_is_friend_only (res)); - return res; - } - - if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid)) - { - GNUNET_break (0); - return NULL; - } - tmp = GNUNET_HELLO_create (&pid.public_key, NULL, NULL, GNUNET_YES); - res = GNUNET_HELLO_merge (hello, tmp); - GNUNET_free (tmp); - GNUNET_assert (GNUNET_YES == GNUNET_HELLO_is_friend_only (res)); + { + res = GNUNET_HELLO_merge(hello, friend_hello); + GNUNET_assert(GNUNET_YES == GNUNET_HELLO_is_friend_only(res)); + return res; + } + + if (GNUNET_OK != GNUNET_HELLO_get_id(hello, &pid)) + { + GNUNET_break(0); + return NULL; + } + tmp = GNUNET_HELLO_create(&pid.public_key, NULL, NULL, GNUNET_YES); + res = GNUNET_HELLO_merge(hello, tmp); + GNUNET_free(tmp); + GNUNET_assert(GNUNET_YES == GNUNET_HELLO_is_friend_only(res)); return res; } @@ -680,8 +676,8 @@ update_friend_hello (const struct GNUNET_HELLO_Message *hello, * @param hello the verified (!) hello message */ static void -update_hello (const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello) +update_hello(const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello) { char *fn; struct HostEntry *host; @@ -696,145 +692,144 @@ update_hello (const struct GNUNET_PeerIdentity *peer, unsigned int pos; char *buffer; - host = GNUNET_CONTAINER_multipeermap_get (hostmap, peer); - GNUNET_assert (NULL != host); + host = GNUNET_CONTAINER_multipeermap_get(hostmap, peer); + GNUNET_assert(NULL != host); - friend_hello_type = GNUNET_HELLO_is_friend_only (hello); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Updating %s HELLO for `%s'\n", - (GNUNET_YES == friend_hello_type) ? "friend-only" : "public", - GNUNET_i2s (peer)); + friend_hello_type = GNUNET_HELLO_is_friend_only(hello); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Updating %s HELLO for `%s'\n", + (GNUNET_YES == friend_hello_type) ? "friend-only" : "public", + GNUNET_i2s(peer)); dest = NULL; if (GNUNET_YES == friend_hello_type) - { - dest = &host->friend_only_hello; - } + { + dest = &host->friend_only_hello; + } else - { - dest = &host->hello; - } + { + dest = &host->hello; + } if (NULL == (*dest)) - { - (*dest) = GNUNET_malloc (GNUNET_HELLO_size (hello)); - GNUNET_memcpy ((*dest), hello, GNUNET_HELLO_size (hello)); - } + { + (*dest) = GNUNET_malloc(GNUNET_HELLO_size(hello)); + GNUNET_memcpy((*dest), hello, GNUNET_HELLO_size(hello)); + } else - { - mrg = GNUNET_HELLO_merge ((*dest), hello); - delta = GNUNET_HELLO_equals (mrg, (*dest), GNUNET_TIME_absolute_get ()); - if (delta.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us) { - /* no differences, just ignore the update */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "No change in %s HELLO for `%s'\n", - (GNUNET_YES == friend_hello_type) ? "friend-only" : "public", - GNUNET_i2s (peer)); - GNUNET_free (mrg); - return; + mrg = GNUNET_HELLO_merge((*dest), hello); + delta = GNUNET_HELLO_equals(mrg, (*dest), GNUNET_TIME_absolute_get()); + if (delta.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us) + { + /* no differences, just ignore the update */ + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "No change in %s HELLO for `%s'\n", + (GNUNET_YES == friend_hello_type) ? "friend-only" : "public", + GNUNET_i2s(peer)); + GNUNET_free(mrg); + return; + } + GNUNET_free((*dest)); + (*dest) = mrg; } - GNUNET_free ((*dest)); - (*dest) = mrg; - } if ((NULL != (host->hello)) && (GNUNET_NO == friend_hello_type)) - { - /* Update friend only hello */ - mrg = update_friend_hello (host->hello, host->friend_only_hello); - if (NULL != host->friend_only_hello) - GNUNET_free (host->friend_only_hello); - host->friend_only_hello = mrg; - } + { + /* Update friend only hello */ + mrg = update_friend_hello(host->hello, host->friend_only_hello); + if (NULL != host->friend_only_hello) + GNUNET_free(host->friend_only_hello); + host->friend_only_hello = mrg; + } if (NULL != host->hello) - GNUNET_assert ((GNUNET_NO == GNUNET_HELLO_is_friend_only (host->hello))); + GNUNET_assert((GNUNET_NO == GNUNET_HELLO_is_friend_only(host->hello))); if (NULL != host->friend_only_hello) - GNUNET_assert ( - (GNUNET_YES == GNUNET_HELLO_is_friend_only (host->friend_only_hello))); - - fn = get_host_filename (peer); - if ((NULL != fn) && (GNUNET_OK == GNUNET_DISK_directory_create_for_file (fn))) - { - store_hello = GNUNET_NO; - size = 0; - cnt = 0; - if (NULL != host->hello) - (void) GNUNET_HELLO_iterate_addresses (host->hello, + GNUNET_assert( + (GNUNET_YES == GNUNET_HELLO_is_friend_only(host->friend_only_hello))); + + fn = get_host_filename(peer); + if ((NULL != fn) && (GNUNET_OK == GNUNET_DISK_directory_create_for_file(fn))) + { + store_hello = GNUNET_NO; + size = 0; + cnt = 0; + if (NULL != host->hello) + (void)GNUNET_HELLO_iterate_addresses(host->hello, GNUNET_NO, &count_addresses, &cnt); - if (cnt > 0) - { - store_hello = GNUNET_YES; - size += GNUNET_HELLO_size (host->hello); - } - cnt = 0; - if (NULL != host->friend_only_hello) - (void) GNUNET_HELLO_iterate_addresses (host->friend_only_hello, + if (cnt > 0) + { + store_hello = GNUNET_YES; + size += GNUNET_HELLO_size(host->hello); + } + cnt = 0; + if (NULL != host->friend_only_hello) + (void)GNUNET_HELLO_iterate_addresses(host->friend_only_hello, GNUNET_NO, &count_addresses, &cnt); - store_friend_hello = GNUNET_NO; - if (0 < cnt) - { - store_friend_hello = GNUNET_YES; - size += GNUNET_HELLO_size (host->friend_only_hello); - } - - if ((GNUNET_NO == store_hello) && (GNUNET_NO == store_friend_hello)) - { - /* no valid addresses, don't put HELLO on disk; in fact, - if one exists on disk, remove it */ - (void) unlink (fn); - } - else - { - buffer = GNUNET_malloc (size); - pos = 0; - - if (GNUNET_YES == store_hello) - { - GNUNET_memcpy (buffer, host->hello, GNUNET_HELLO_size (host->hello)); - pos += GNUNET_HELLO_size (host->hello); - } - if (GNUNET_YES == store_friend_hello) - { - GNUNET_memcpy (&buffer[pos], - host->friend_only_hello, - GNUNET_HELLO_size (host->friend_only_hello)); - pos += GNUNET_HELLO_size (host->friend_only_hello); - } - GNUNET_assert (pos == size); - - if (GNUNET_SYSERR == GNUNET_DISK_fn_write (fn, - buffer, - size, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_GROUP_READ | - GNUNET_DISK_PERM_OTHER_READ)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", fn); + store_friend_hello = GNUNET_NO; + if (0 < cnt) + { + store_friend_hello = GNUNET_YES; + size += GNUNET_HELLO_size(host->friend_only_hello); + } + + if ((GNUNET_NO == store_hello) && (GNUNET_NO == store_friend_hello)) + { + /* no valid addresses, don't put HELLO on disk; in fact, + if one exists on disk, remove it */ + (void)unlink(fn); + } else - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Stored %s %s HELLO in %s with total size %u\n", - (GNUNET_YES == store_friend_hello) ? "friend-only" : "", - (GNUNET_YES == store_hello) ? "public" : "", - fn, - size); - GNUNET_free (buffer); + { + buffer = GNUNET_malloc(size); + pos = 0; + + if (GNUNET_YES == store_hello) + { + GNUNET_memcpy(buffer, host->hello, GNUNET_HELLO_size(host->hello)); + pos += GNUNET_HELLO_size(host->hello); + } + if (GNUNET_YES == store_friend_hello) + { + GNUNET_memcpy(&buffer[pos], + host->friend_only_hello, + GNUNET_HELLO_size(host->friend_only_hello)); + pos += GNUNET_HELLO_size(host->friend_only_hello); + } + GNUNET_assert(pos == size); + + if (GNUNET_SYSERR == GNUNET_DISK_fn_write(fn, + buffer, + size, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_GROUP_READ | + GNUNET_DISK_PERM_OTHER_READ)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "write", fn); + else + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Stored %s %s HELLO in %s with total size %u\n", + (GNUNET_YES == store_friend_hello) ? "friend-only" : "", + (GNUNET_YES == store_hello) ? "public" : "", + fn, + size); + GNUNET_free(buffer); + } } - } - GNUNET_free_non_null (fn); - notify_all (host); + GNUNET_free_non_null(fn); + notify_all(host); } /** * Closure for #add_to_tc() */ -struct TransmitContext -{ +struct TransmitContext { /** * Client to transmit to */ @@ -856,7 +851,7 @@ struct TransmitContext * @return #GNUNET_YES (continue to iterate) */ static int -add_to_tc (void *cls, const struct GNUNET_PeerIdentity *key, void *value) +add_to_tc(void *cls, const struct GNUNET_PeerIdentity *key, void *value) { struct TransmitContext *tc = cls; struct HostEntry *pos = value; @@ -867,38 +862,38 @@ add_to_tc (void *cls, const struct GNUNET_PeerIdentity *key, void *value) hs = 0; if ((NULL != pos->hello) && (GNUNET_NO == tc->friend_only)) - { - /* Copy public HELLO */ - hs = GNUNET_HELLO_size (pos->hello); - GNUNET_assert (hs < GNUNET_MAX_MESSAGE_SIZE - sizeof (struct InfoMessage)); - env = GNUNET_MQ_msg_extra (im, hs, GNUNET_MESSAGE_TYPE_PEERINFO_INFO); - GNUNET_memcpy (&im[1], pos->hello, hs); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending public HELLO with size %u for peer `%s'\n", - hs, - GNUNET_i2s (key)); - } + { + /* Copy public HELLO */ + hs = GNUNET_HELLO_size(pos->hello); + GNUNET_assert(hs < GNUNET_MAX_MESSAGE_SIZE - sizeof(struct InfoMessage)); + env = GNUNET_MQ_msg_extra(im, hs, GNUNET_MESSAGE_TYPE_PEERINFO_INFO); + GNUNET_memcpy(&im[1], pos->hello, hs); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending public HELLO with size %u for peer `%s'\n", + hs, + GNUNET_i2s(key)); + } else if ((NULL != pos->friend_only_hello) && (GNUNET_YES == tc->friend_only)) - { - /* Copy friend only HELLO */ - hs = GNUNET_HELLO_size (pos->friend_only_hello); - GNUNET_assert (hs < GNUNET_MAX_MESSAGE_SIZE - sizeof (struct InfoMessage)); - env = GNUNET_MQ_msg_extra (im, hs, GNUNET_MESSAGE_TYPE_PEERINFO_INFO); - GNUNET_memcpy (&im[1], pos->friend_only_hello, hs); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Sending friend-only HELLO with size %u for peer `%s'\n", - hs, - GNUNET_i2s (key)); - } + { + /* Copy friend only HELLO */ + hs = GNUNET_HELLO_size(pos->friend_only_hello); + GNUNET_assert(hs < GNUNET_MAX_MESSAGE_SIZE - sizeof(struct InfoMessage)); + env = GNUNET_MQ_msg_extra(im, hs, GNUNET_MESSAGE_TYPE_PEERINFO_INFO); + GNUNET_memcpy(&im[1], pos->friend_only_hello, hs); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Sending friend-only HELLO with size %u for peer `%s'\n", + hs, + GNUNET_i2s(key)); + } else - { - env = GNUNET_MQ_msg (im, GNUNET_MESSAGE_TYPE_PEERINFO_INFO); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding no HELLO for peer `%s'\n", - GNUNET_i2s (key)); - } + { + env = GNUNET_MQ_msg(im, GNUNET_MESSAGE_TYPE_PEERINFO_INFO); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding no HELLO for peer `%s'\n", + GNUNET_i2s(key)); + } im->peer = pos->identity; - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (tc->client), env); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(tc->client), env); return GNUNET_YES; } @@ -911,7 +906,7 @@ add_to_tc (void *cls, const struct GNUNET_PeerIdentity *key, void *value) * @return #GNUNET_OK (continue iteration) */ static int -discard_hosts_helper (void *cls, const char *fn) +discard_hosts_helper(void *cls, const char *fn) { struct GNUNET_TIME_Absolute *now = cls; char buffer[GNUNET_MAX_MESSAGE_SIZE - 1] GNUNET_ALIGN; @@ -926,82 +921,82 @@ discard_hosts_helper (void *cls, const char *fn) char *writebuffer; uint64_t fsize; - if (GNUNET_OK != GNUNET_DISK_file_size (fn, &fsize, GNUNET_YES, GNUNET_YES)) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING | - GNUNET_ERROR_TYPE_BULK, - "fstat", - fn); - return GNUNET_OK; - } - read_size = GNUNET_DISK_fn_read (fn, buffer, sizeof (buffer)); + if (GNUNET_OK != GNUNET_DISK_file_size(fn, &fsize, GNUNET_YES, GNUNET_YES)) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING | + GNUNET_ERROR_TYPE_BULK, + "fstat", + fn); + return GNUNET_OK; + } + read_size = GNUNET_DISK_fn_read(fn, buffer, sizeof(buffer)); - if ((read_size < (int) sizeof (struct GNUNET_MessageHeader)) || + if ((read_size < (int)sizeof(struct GNUNET_MessageHeader)) || (fsize > GNUNET_MAX_MESSAGE_SIZE)) - { - if (0 != unlink (fn)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING | - GNUNET_ERROR_TYPE_BULK, - "unlink", - fn); - return GNUNET_OK; - } + { + if (0 != unlink(fn)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING | + GNUNET_ERROR_TYPE_BULK, + "unlink", + fn); + return GNUNET_OK; + } - writebuffer = GNUNET_malloc (read_size); + writebuffer = GNUNET_malloc(read_size); read_pos = 0; write_pos = 0; while (read_pos < read_size) - { - /* Check each HELLO */ - hello = (const struct GNUNET_HELLO_Message *) &buffer[read_pos]; - cur_hello_size = GNUNET_HELLO_size (hello); - if (0 == cur_hello_size) { - /* Invalid data, discard */ - if (0 != unlink (fn)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING | - GNUNET_ERROR_TYPE_BULK, - "unlink", - fn); - GNUNET_free (writebuffer); - return GNUNET_OK; - } - new_hello = - GNUNET_HELLO_iterate_addresses (hello, GNUNET_YES, &discard_expired, now); - cnt = 0; - if (NULL != new_hello) - (void) GNUNET_HELLO_iterate_addresses (hello, + /* Check each HELLO */ + hello = (const struct GNUNET_HELLO_Message *)&buffer[read_pos]; + cur_hello_size = GNUNET_HELLO_size(hello); + if (0 == cur_hello_size) + { + /* Invalid data, discard */ + if (0 != unlink(fn)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING | + GNUNET_ERROR_TYPE_BULK, + "unlink", + fn); + GNUNET_free(writebuffer); + return GNUNET_OK; + } + new_hello = + GNUNET_HELLO_iterate_addresses(hello, GNUNET_YES, &discard_expired, now); + cnt = 0; + if (NULL != new_hello) + (void)GNUNET_HELLO_iterate_addresses(hello, GNUNET_NO, &count_addresses, &cnt); - if ((NULL != new_hello) && (0 < cnt)) - { - /* Store new HELLO to write it when done */ - new_hello_size = GNUNET_HELLO_size (new_hello); - GNUNET_memcpy (&writebuffer[write_pos], new_hello, new_hello_size); - write_pos += new_hello_size; + if ((NULL != new_hello) && (0 < cnt)) + { + /* Store new HELLO to write it when done */ + new_hello_size = GNUNET_HELLO_size(new_hello); + GNUNET_memcpy(&writebuffer[write_pos], new_hello, new_hello_size); + write_pos += new_hello_size; + } + read_pos += cur_hello_size; + GNUNET_free_non_null(new_hello); } - read_pos += cur_hello_size; - GNUNET_free_non_null (new_hello); - } if (0 < write_pos) - { - GNUNET_DISK_fn_write (fn, - writebuffer, - write_pos, - GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_GROUP_READ | - GNUNET_DISK_PERM_OTHER_READ); - } - else if (0 != unlink (fn)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING | - GNUNET_ERROR_TYPE_BULK, - "unlink", - fn); - - GNUNET_free (writebuffer); + { + GNUNET_DISK_fn_write(fn, + writebuffer, + write_pos, + GNUNET_DISK_PERM_USER_READ | + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_GROUP_READ | + GNUNET_DISK_PERM_OTHER_READ); + } + else if (0 != unlink(fn)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING | + GNUNET_ERROR_TYPE_BULK, + "unlink", + fn); + + GNUNET_free(writebuffer); return GNUNET_OK; } @@ -1013,20 +1008,20 @@ discard_hosts_helper (void *cls, const char *fn) * @param cls unused */ static void -cron_clean_data_hosts (void *cls) +cron_clean_data_hosts(void *cls) { struct GNUNET_TIME_Absolute now; - (void) cls; + (void)cls; cron_clean = NULL; - now = GNUNET_TIME_absolute_get (); - GNUNET_log (GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK, - _ ("Cleaning up directory `%s'\n"), - networkIdDirectory); - GNUNET_DISK_directory_scan (networkIdDirectory, &discard_hosts_helper, &now); - cron_clean = GNUNET_SCHEDULER_add_delayed (DATA_HOST_CLEAN_FREQ, - &cron_clean_data_hosts, - NULL); + now = GNUNET_TIME_absolute_get(); + GNUNET_log(GNUNET_ERROR_TYPE_INFO | GNUNET_ERROR_TYPE_BULK, + _("Cleaning up directory `%s'\n"), + networkIdDirectory); + GNUNET_DISK_directory_scan(networkIdDirectory, &discard_hosts_helper, &now); + cron_clean = GNUNET_SCHEDULER_add_delayed(DATA_HOST_CLEAN_FREQ, + &cron_clean_data_hosts, + NULL); } @@ -1038,16 +1033,16 @@ cron_clean_data_hosts (void *cls) * @return #GNUNET_OK if @a hello is well-formed */ static int -check_hello (void *cls, const struct GNUNET_HELLO_Message *hello) +check_hello(void *cls, const struct GNUNET_HELLO_Message *hello) { struct GNUNET_PeerIdentity pid; - (void) cls; - if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + (void)cls; + if (GNUNET_OK != GNUNET_HELLO_get_id(hello, &pid)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1059,18 +1054,18 @@ check_hello (void *cls, const struct GNUNET_HELLO_Message *hello) * @param hello the actual message */ static void -handle_hello (void *cls, const struct GNUNET_HELLO_Message *hello) +handle_hello(void *cls, const struct GNUNET_HELLO_Message *hello) { struct GNUNET_SERVICE_Client *client = cls; struct GNUNET_PeerIdentity pid; - GNUNET_assert (GNUNET_OK == GNUNET_HELLO_get_id (hello, &pid)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "HELLO message received for peer `%s'\n", - GNUNET_i2s (&pid)); - add_host_to_known_hosts (&pid); - update_hello (&pid, hello); - GNUNET_SERVICE_client_continue (client); + GNUNET_assert(GNUNET_OK == GNUNET_HELLO_get_id(hello, &pid)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "HELLO message received for peer `%s'\n", + GNUNET_i2s(&pid)); + add_host_to_known_hosts(&pid); + update_hello(&pid, hello); + GNUNET_SERVICE_client_continue(client); } @@ -1081,25 +1076,25 @@ handle_hello (void *cls, const struct GNUNET_HELLO_Message *hello) * @param lpm the actual message */ static void -handle_get (void *cls, const struct ListPeerMessage *lpm) +handle_get(void *cls, const struct ListPeerMessage *lpm) { struct GNUNET_SERVICE_Client *client = cls; struct TransmitContext tcx; struct GNUNET_MessageHeader *msg; struct GNUNET_MQ_Envelope *env; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "GET message received for peer `%s'\n", - GNUNET_i2s (&lpm->peer)); - tcx.friend_only = ntohl (lpm->include_friend_only); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "GET message received for peer `%s'\n", + GNUNET_i2s(&lpm->peer)); + tcx.friend_only = ntohl(lpm->include_friend_only); tcx.client = client; - GNUNET_CONTAINER_multipeermap_get_multiple (hostmap, - &lpm->peer, - &add_to_tc, - &tcx); - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); - GNUNET_SERVICE_client_continue (client); + GNUNET_CONTAINER_multipeermap_get_multiple(hostmap, + &lpm->peer, + &add_to_tc, + &tcx); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); + GNUNET_SERVICE_client_continue(client); } @@ -1110,20 +1105,20 @@ handle_get (void *cls, const struct ListPeerMessage *lpm) * @param lapm the actual message */ static void -handle_get_all (void *cls, const struct ListAllPeersMessage *lapm) +handle_get_all(void *cls, const struct ListAllPeersMessage *lapm) { struct GNUNET_SERVICE_Client *client = cls; struct TransmitContext tcx; struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GET_ALL message received\n"); - tcx.friend_only = ntohl (lapm->include_friend_only); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "GET_ALL message received\n"); + tcx.friend_only = ntohl(lapm->include_friend_only); tcx.client = client; - GNUNET_CONTAINER_multipeermap_iterate (hostmap, &add_to_tc, &tcx); - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); - GNUNET_SERVICE_client_continue (client); + GNUNET_CONTAINER_multipeermap_iterate(hostmap, &add_to_tc, &tcx); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); + GNUNET_SERVICE_client_continue(client); } @@ -1134,7 +1129,7 @@ handle_get_all (void *cls, const struct ListAllPeersMessage *lapm) * @param nm the actual message */ static void -handle_notify (void *cls, const struct NotifyMessage *nm) +handle_notify(void *cls, const struct NotifyMessage *nm) { struct GNUNET_SERVICE_Client *client = cls; struct GNUNET_MQ_Handle *mq; @@ -1142,19 +1137,19 @@ handle_notify (void *cls, const struct NotifyMessage *nm) struct GNUNET_MQ_Envelope *env; struct GNUNET_MessageHeader *msg; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "NOTIFY message received\n"); - mq = GNUNET_SERVICE_client_get_mq (client); - GNUNET_SERVICE_client_mark_monitor (client); - if (ntohl (nm->include_friend_only)) - GNUNET_notification_context_add (notify_friend_only_list, mq); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "NOTIFY message received\n"); + mq = GNUNET_SERVICE_client_get_mq(client); + GNUNET_SERVICE_client_mark_monitor(client); + if (ntohl(nm->include_friend_only)) + GNUNET_notification_context_add(notify_friend_only_list, mq); else - GNUNET_notification_context_add (notify_list, mq); - tcx.friend_only = ntohl (nm->include_friend_only); + GNUNET_notification_context_add(notify_list, mq); + tcx.friend_only = ntohl(nm->include_friend_only); tcx.client = client; - GNUNET_CONTAINER_multipeermap_iterate (hostmap, &add_to_tc, &tcx); - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); - GNUNET_SERVICE_client_continue (client); + GNUNET_CONTAINER_multipeermap_iterate(hostmap, &add_to_tc, &tcx); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); + GNUNET_SERVICE_client_continue(client); } @@ -1167,12 +1162,12 @@ handle_notify (void *cls, const struct NotifyMessage *nm) * @return @a client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { - (void) cls; - (void) mq; + (void)cls; + (void)mq; return client; } @@ -1185,12 +1180,12 @@ client_connect_cb (void *cls, * @param app_ctx should be @a client */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { - (void) cls; - GNUNET_assert (app_ctx == client); + (void)cls; + GNUNET_assert(app_ctx == client); } @@ -1203,15 +1198,15 @@ client_disconnect_cb (void *cls, * @return #GNUNET_YES (continue to iterate) */ static int -free_host_entry (void *cls, const struct GNUNET_PeerIdentity *key, void *value) +free_host_entry(void *cls, const struct GNUNET_PeerIdentity *key, void *value) { struct HostEntry *he = value; - (void) cls; - (void) key; - GNUNET_free_non_null (he->hello); - GNUNET_free_non_null (he->friend_only_hello); - GNUNET_free (he); + (void)cls; + (void)key; + GNUNET_free_non_null(he->hello); + GNUNET_free_non_null(he->friend_only_hello); + GNUNET_free(he); return GNUNET_YES; } @@ -1222,36 +1217,36 @@ free_host_entry (void *cls, const struct GNUNET_PeerIdentity *key, void *value) * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - (void) cls; - GNUNET_notification_context_destroy (notify_list); + (void)cls; + GNUNET_notification_context_destroy(notify_list); notify_list = NULL; - GNUNET_notification_context_destroy (notify_friend_only_list); + GNUNET_notification_context_destroy(notify_friend_only_list); notify_friend_only_list = NULL; - GNUNET_CONTAINER_multipeermap_iterate (hostmap, &free_host_entry, NULL); - GNUNET_CONTAINER_multipeermap_destroy (hostmap); + GNUNET_CONTAINER_multipeermap_iterate(hostmap, &free_host_entry, NULL); + GNUNET_CONTAINER_multipeermap_destroy(hostmap); if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, GNUNET_NO); - stats = NULL; - } + { + GNUNET_STATISTICS_destroy(stats, GNUNET_NO); + stats = NULL; + } if (NULL != cron_clean) - { - GNUNET_SCHEDULER_cancel (cron_clean); - cron_clean = NULL; - } + { + GNUNET_SCHEDULER_cancel(cron_clean); + cron_clean = NULL; + } if (NULL != cron_scan) - { - GNUNET_SCHEDULER_cancel (cron_scan); - cron_scan = NULL; - } + { + GNUNET_SCHEDULER_cancel(cron_scan); + cron_scan = NULL; + } if (NULL != networkIdDirectory) - { - GNUNET_free (networkIdDirectory); - networkIdDirectory = NULL; - } + { + GNUNET_free(networkIdDirectory); + networkIdDirectory = NULL; + } } @@ -1263,9 +1258,9 @@ shutdown_task (void *cls) * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_SERVICE_Handle *service) { char *peerdir; char *ip; @@ -1273,95 +1268,95 @@ run (void *cls, int noio; int use_included; - (void) cls; - (void) service; - hostmap = GNUNET_CONTAINER_multipeermap_create (1024, GNUNET_YES); - stats = GNUNET_STATISTICS_create ("peerinfo", cfg); - notify_list = GNUNET_notification_context_create (0); - notify_friend_only_list = GNUNET_notification_context_create (0); - noio = GNUNET_CONFIGURATION_get_value_yesno (cfg, "peerinfo", "NO_IO"); - use_included = GNUNET_CONFIGURATION_get_value_yesno (cfg, - "peerinfo", - "USE_INCLUDED_HELLOS"); + (void)cls; + (void)service; + hostmap = GNUNET_CONTAINER_multipeermap_create(1024, GNUNET_YES); + stats = GNUNET_STATISTICS_create("peerinfo", cfg); + notify_list = GNUNET_notification_context_create(0); + notify_friend_only_list = GNUNET_notification_context_create(0); + noio = GNUNET_CONFIGURATION_get_value_yesno(cfg, "peerinfo", "NO_IO"); + use_included = GNUNET_CONFIGURATION_get_value_yesno(cfg, + "peerinfo", + "USE_INCLUDED_HELLOS"); if (GNUNET_SYSERR == use_included) use_included = GNUNET_NO; - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); if (GNUNET_YES != noio) - { - GNUNET_assert ( - GNUNET_OK == - GNUNET_CONFIGURATION_get_value_filename (cfg, - "peerinfo", - "HOSTS", - &networkIdDirectory)); - if (GNUNET_OK != GNUNET_DISK_directory_create (networkIdDirectory)) { - GNUNET_SCHEDULER_shutdown (); - return; - } - - cron_scan = - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE, - &cron_scan_directory_data_hosts, - NULL); - - cron_clean = - GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE, - &cron_clean_data_hosts, - NULL); - if (GNUNET_YES == use_included) - { - ip = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR); - GNUNET_asprintf (&peerdir, "%shellos", ip); - GNUNET_free (ip); - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Importing HELLOs from `%s'\n"), - peerdir); - dsc.matched = 0; - dsc.remove_files = GNUNET_NO; - - GNUNET_DISK_directory_scan (peerdir, - &hosts_directory_scan_callback, - &dsc); - GNUNET_free (peerdir); - } - else - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _ ("Skipping import of included HELLOs\n")); + GNUNET_assert( + GNUNET_OK == + GNUNET_CONFIGURATION_get_value_filename(cfg, + "peerinfo", + "HOSTS", + &networkIdDirectory)); + if (GNUNET_OK != GNUNET_DISK_directory_create(networkIdDirectory)) + { + GNUNET_SCHEDULER_shutdown(); + return; + } + + cron_scan = + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_IDLE, + &cron_scan_directory_data_hosts, + NULL); + + cron_clean = + GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_IDLE, + &cron_clean_data_hosts, + NULL); + if (GNUNET_YES == use_included) + { + ip = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_DATADIR); + GNUNET_asprintf(&peerdir, "%shellos", ip); + GNUNET_free(ip); + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Importing HELLOs from `%s'\n"), + peerdir); + dsc.matched = 0; + dsc.remove_files = GNUNET_NO; + + GNUNET_DISK_directory_scan(peerdir, + &hosts_directory_scan_callback, + &dsc); + GNUNET_free(peerdir); + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Skipping import of included HELLOs\n")); + } } - } } /** * Define "main" method using service macro. */ -GNUNET_SERVICE_MAIN ( +GNUNET_SERVICE_MAIN( "peerinfo", GNUNET_SERVICE_OPTION_NONE, &run, &client_connect_cb, &client_disconnect_cb, NULL, - GNUNET_MQ_hd_var_size (hello, - GNUNET_MESSAGE_TYPE_HELLO, - struct GNUNET_HELLO_Message, - NULL), - GNUNET_MQ_hd_fixed_size (get, - GNUNET_MESSAGE_TYPE_PEERINFO_GET, - struct ListPeerMessage, - NULL), - GNUNET_MQ_hd_fixed_size (get_all, - GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL, - struct ListAllPeersMessage, - NULL), - GNUNET_MQ_hd_fixed_size (notify, - GNUNET_MESSAGE_TYPE_PEERINFO_NOTIFY, - struct NotifyMessage, - NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_hd_var_size(hello, + GNUNET_MESSAGE_TYPE_HELLO, + struct GNUNET_HELLO_Message, + NULL), + GNUNET_MQ_hd_fixed_size(get, + GNUNET_MESSAGE_TYPE_PEERINFO_GET, + struct ListPeerMessage, + NULL), + GNUNET_MQ_hd_fixed_size(get_all, + GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL, + struct ListAllPeersMessage, + NULL), + GNUNET_MQ_hd_fixed_size(notify, + GNUNET_MESSAGE_TYPE_PEERINFO_NOTIFY, + struct NotifyMessage, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-peerinfo.c */ diff --git a/src/peerinfo/peerinfo.h b/src/peerinfo/peerinfo.h index ea1c6598c..85501593e 100644 --- a/src/peerinfo/peerinfo.h +++ b/src/peerinfo/peerinfo.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerinfo/peerinfo.h @@ -39,9 +39,7 @@ GNUNET_NETWORK_STRUCT_BEGIN * Message requesting a listing of peers, * restricted to the specified peer identity. */ -struct ListPeerMessage -{ - +struct ListPeerMessage { /** * Type will be GNUNET_MESSAGE_TYPE_PEERINFO_GET */ @@ -57,15 +55,13 @@ struct ListPeerMessage * field, check header.size!). */ struct GNUNET_PeerIdentity peer; - }; /** * Message requesting a listing of all peers, * restricted to the specified peer identity. */ -struct ListAllPeersMessage -{ +struct ListAllPeersMessage { /** * Type will be GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL */ @@ -75,15 +71,13 @@ struct ListAllPeersMessage * Include friend only HELLOs and peers in callbacks */ uint32_t include_friend_only GNUNET_PACKED; - }; /** * Header for all communications. */ -struct NotifyMessage -{ +struct NotifyMessage { /** * Type will be GNUNET_MESSAGE_TYPE_PEERINFO_NOTIFY */ @@ -93,7 +87,6 @@ struct NotifyMessage * Include friend only HELLOs and peers in callbacks */ uint32_t include_friend_only GNUNET_PACKED; - }; @@ -104,9 +97,7 @@ struct NotifyMessage * Check the header.size field to see if a HELLO is * present. */ -struct InfoMessage -{ - +struct InfoMessage { /** * Type will be GNUNET_MESSAGE_TYPE_PEERINFO_INFO */ @@ -121,7 +112,6 @@ struct InfoMessage * About which peer are we talking here? */ struct GNUNET_PeerIdentity peer; - }; GNUNET_NETWORK_STRUCT_END diff --git a/src/peerinfo/peerinfo_api.c b/src/peerinfo/peerinfo_api.c index 485b5e183..ada6f5462 100644 --- a/src/peerinfo/peerinfo_api.c +++ b/src/peerinfo/peerinfo_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerinfo/peerinfo_api.c @@ -28,15 +28,13 @@ #include "gnunet_protocols.h" #include "peerinfo.h" -#define LOG(kind,...) GNUNET_log_from (kind, "peerinfo-api",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "peerinfo-api", __VA_ARGS__) /** * Context for an iteration request. */ -struct GNUNET_PEERINFO_IteratorContext -{ - +struct GNUNET_PEERINFO_IteratorContext { /** * Kept in a DLL. */ @@ -76,15 +74,13 @@ struct GNUNET_PEERINFO_IteratorContext * Only include friends in reply? */ int include_friend_only; - }; /** * Handle to the peerinfo service. */ -struct GNUNET_PEERINFO_Handle -{ +struct GNUNET_PEERINFO_Handle { /** * Our configuration. */ @@ -109,7 +105,6 @@ struct GNUNET_PEERINFO_Handle * ID for a reconnect task. */ struct GNUNET_SCHEDULER_Task *r_task; - }; @@ -119,7 +114,7 @@ struct GNUNET_PEERINFO_Handle * @param h handle to the service */ static void -reconnect (struct GNUNET_PEERINFO_Handle *h); +reconnect(struct GNUNET_PEERINFO_Handle *h); /** @@ -130,18 +125,18 @@ reconnect (struct GNUNET_PEERINFO_Handle *h); * establishment may happen asynchronously). */ struct GNUNET_PEERINFO_Handle * -GNUNET_PEERINFO_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_PEERINFO_connect(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_PEERINFO_Handle *h; - h = GNUNET_new (struct GNUNET_PEERINFO_Handle); + h = GNUNET_new(struct GNUNET_PEERINFO_Handle); h->cfg = cfg; - reconnect (h); + reconnect(h); if (NULL == h->mq) - { - GNUNET_free (h); - return NULL; - } + { + GNUNET_free(h); + return NULL; + } return h; } @@ -156,28 +151,28 @@ GNUNET_PEERINFO_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) * @param h handle to disconnect */ void -GNUNET_PEERINFO_disconnect (struct GNUNET_PEERINFO_Handle *h) +GNUNET_PEERINFO_disconnect(struct GNUNET_PEERINFO_Handle *h) { struct GNUNET_PEERINFO_IteratorContext *ic; while (NULL != (ic = h->ic_head)) - { - GNUNET_CONTAINER_DLL_remove (h->ic_head, - h->ic_tail, - ic); - GNUNET_free (ic); - } + { + GNUNET_CONTAINER_DLL_remove(h->ic_head, + h->ic_tail, + ic); + GNUNET_free(ic); + } if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } if (NULL != h->r_task) - { - GNUNET_SCHEDULER_cancel (h->r_task); - h->r_task = NULL; - } - GNUNET_free (h); + { + GNUNET_SCHEDULER_cancel(h->r_task); + h->r_task = NULL; + } + GNUNET_free(h); } @@ -187,12 +182,12 @@ GNUNET_PEERINFO_disconnect (struct GNUNET_PEERINFO_Handle *h) * @param cls the `struct GNUNET_PEERINFO_Handle *` */ static void -reconnect_task (void *cls) +reconnect_task(void *cls) { struct GNUNET_PEERINFO_Handle *h = cls; h->r_task = NULL; - reconnect (h); + reconnect(h); } @@ -202,26 +197,26 @@ reconnect_task (void *cls) * @param h handle to reconnect */ static void -do_reconnect (struct GNUNET_PEERINFO_Handle *h) +do_reconnect(struct GNUNET_PEERINFO_Handle *h) { struct GNUNET_PEERINFO_IteratorContext *ic = h->ic_head; - GNUNET_MQ_destroy (h->mq); + GNUNET_MQ_destroy(h->mq); h->mq = NULL; if (NULL != ic) - { - GNUNET_CONTAINER_DLL_remove (h->ic_head, - h->ic_tail, - ic); - if (NULL != ic->callback) - ic->callback (ic->callback_cls, - NULL, - NULL, - _("Failed to receive response from `PEERINFO' service.")); - GNUNET_free (ic); - } - h->r_task = GNUNET_SCHEDULER_add_now (&reconnect_task, - h); + { + GNUNET_CONTAINER_DLL_remove(h->ic_head, + h->ic_tail, + ic); + if (NULL != ic->callback) + ic->callback(ic->callback_cls, + NULL, + NULL, + _("Failed to receive response from `PEERINFO' service.")); + GNUNET_free(ic); + } + h->r_task = GNUNET_SCHEDULER_add_now(&reconnect_task, + h); } @@ -233,12 +228,12 @@ do_reconnect (struct GNUNET_PEERINFO_Handle *h) * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_PEERINFO_Handle *h = cls; - do_reconnect (h); + do_reconnect(h); } @@ -252,70 +247,70 @@ mq_error_handler (void *cls, * @return #GNUNET_OK if the message is OK */ static int -check_info (void *cls, - const struct InfoMessage *im) +check_info(void *cls, + const struct InfoMessage *im) { struct GNUNET_PEERINFO_Handle *h = cls; struct GNUNET_PEERINFO_IteratorContext *ic = h->ic_head; - uint16_t ms = ntohs (im->header.size) - sizeof (*im); + uint16_t ms = ntohs(im->header.size) - sizeof(*im); - if (0 != ntohl (im->reserved)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + if (0 != ntohl(im->reserved)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } if (NULL == ic) - { - /* didn't expect a response, bad */ - GNUNET_break (0); - return GNUNET_SYSERR; - } - if ( (GNUNET_YES == ic->have_peer) && - (0 != GNUNET_memcmp (&ic->peer, - &im->peer)) ) - { - /* bogus message (from a different iteration call?); out of sequence! */ - LOG (GNUNET_ERROR_TYPE_ERROR, - "Received HELLO for peer `%s', expected peer `%s'\n", - GNUNET_i2s (&im->peer), - GNUNET_i2s (&ic->peer)); - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (ms > sizeof (struct GNUNET_MessageHeader)) - { - const struct GNUNET_HELLO_Message *hello; - struct GNUNET_PeerIdentity id; - - hello = (const struct GNUNET_HELLO_Message *) &im[1]; - if (ms != GNUNET_HELLO_size (hello)) { - /* malformed message */ - GNUNET_break (0); + /* didn't expect a response, bad */ + GNUNET_break(0); return GNUNET_SYSERR; } - if (GNUNET_OK != - GNUNET_HELLO_get_id (hello, - &id)) + if ((GNUNET_YES == ic->have_peer) && + (0 != GNUNET_memcmp(&ic->peer, + &im->peer))) { - /* malformed message */ - GNUNET_break (0); + /* bogus message (from a different iteration call?); out of sequence! */ + LOG(GNUNET_ERROR_TYPE_ERROR, + "Received HELLO for peer `%s', expected peer `%s'\n", + GNUNET_i2s(&im->peer), + GNUNET_i2s(&ic->peer)); + GNUNET_break(0); return GNUNET_SYSERR; } - if (0 != GNUNET_memcmp (&im->peer, - &id)) + if (ms > sizeof(struct GNUNET_MessageHeader)) + { + const struct GNUNET_HELLO_Message *hello; + struct GNUNET_PeerIdentity id; + + hello = (const struct GNUNET_HELLO_Message *)&im[1]; + if (ms != GNUNET_HELLO_size(hello)) + { + /* malformed message */ + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (GNUNET_OK != + GNUNET_HELLO_get_id(hello, + &id)) + { + /* malformed message */ + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (0 != GNUNET_memcmp(&im->peer, + &id)) + { + /* malformed message */ + GNUNET_break(0); + return GNUNET_SYSERR; + } + } + else if (0 != ms) { /* malformed message */ - GNUNET_break (0); + GNUNET_break(0); return GNUNET_SYSERR; } - } - else if (0 != ms) - { - /* malformed message */ - GNUNET_break (0); - return GNUNET_SYSERR; - } return GNUNET_OK; } @@ -327,22 +322,22 @@ check_info (void *cls, * @param im message received */ static void -handle_info (void *cls, - const struct InfoMessage *im) +handle_info(void *cls, + const struct InfoMessage *im) { struct GNUNET_PEERINFO_Handle *h = cls; struct GNUNET_PEERINFO_IteratorContext *ic = h->ic_head; const struct GNUNET_HELLO_Message *hello = NULL; uint16_t ms; - ms = ntohs (im->header.size); - if (ms > sizeof (struct InfoMessage)) - hello = (const struct GNUNET_HELLO_Message *) &im[1]; + ms = ntohs(im->header.size); + if (ms > sizeof(struct InfoMessage)) + hello = (const struct GNUNET_HELLO_Message *)&im[1]; if (NULL != ic->callback) - ic->callback (ic->callback_cls, - &im->peer, - hello, - NULL); + ic->callback(ic->callback_cls, + &im->peer, + hello, + NULL); } @@ -352,7 +347,7 @@ handle_info (void *cls, * @param h handle */ static void -send_ic_request (struct GNUNET_PEERINFO_Handle *h) +send_ic_request(struct GNUNET_PEERINFO_Handle *h) { struct GNUNET_PEERINFO_IteratorContext *ic = h->ic_head; struct GNUNET_MQ_Envelope *env; @@ -360,35 +355,35 @@ send_ic_request (struct GNUNET_PEERINFO_Handle *h) struct ListPeerMessage *lpm; if (NULL == ic) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } if (NULL == h->mq) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } if (GNUNET_NO == ic->have_peer) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Requesting list of peers from PEERINFO service\n"); - env = GNUNET_MQ_msg (lapm, - GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL); - lapm->include_friend_only = htonl (ic->include_friend_only); - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Requesting list of peers from PEERINFO service\n"); + env = GNUNET_MQ_msg(lapm, + GNUNET_MESSAGE_TYPE_PEERINFO_GET_ALL); + lapm->include_friend_only = htonl(ic->include_friend_only); + } else - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Requesting information on peer `%s' from PEERINFO service\n", - GNUNET_i2s (&ic->peer)); - env = GNUNET_MQ_msg (lpm, - GNUNET_MESSAGE_TYPE_PEERINFO_GET); - lpm->include_friend_only = htonl (ic->include_friend_only); - lpm->peer = ic->peer; - } - GNUNET_MQ_send (h->mq, - env); + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Requesting information on peer `%s' from PEERINFO service\n", + GNUNET_i2s(&ic->peer)); + env = GNUNET_MQ_msg(lpm, + GNUNET_MESSAGE_TYPE_PEERINFO_GET); + lpm->include_friend_only = htonl(ic->include_friend_only); + lpm->peer = ic->peer; + } + GNUNET_MQ_send(h->mq, + env); } @@ -402,32 +397,32 @@ send_ic_request (struct GNUNET_PEERINFO_Handle *h) * @param msg message received, NULL on timeout or fatal error */ static void -handle_end_iteration (void *cls, - const struct GNUNET_MessageHeader *msg) +handle_end_iteration(void *cls, + const struct GNUNET_MessageHeader *msg) { struct GNUNET_PEERINFO_Handle *h = cls; struct GNUNET_PEERINFO_IteratorContext *ic = h->ic_head; if (NULL == ic) - { - /* didn't expect a response, reconnect */ - GNUNET_break (0); - reconnect (h); - return; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received end of list of peers from PEERINFO service\n"); - GNUNET_CONTAINER_DLL_remove (h->ic_head, - h->ic_tail, - ic); + { + /* didn't expect a response, reconnect */ + GNUNET_break(0); + reconnect(h); + return; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received end of list of peers from PEERINFO service\n"); + GNUNET_CONTAINER_DLL_remove(h->ic_head, + h->ic_tail, + ic); if (NULL != h->ic_head) - send_ic_request (h); + send_ic_request(h); if (NULL != ic->callback) - ic->callback (ic->callback_cls, - NULL, - NULL, - NULL); - GNUNET_free (ic); + ic->callback(ic->callback_cls, + NULL, + NULL, + NULL); + GNUNET_free(ic); } @@ -437,37 +432,37 @@ handle_end_iteration (void *cls, * @param h handle to the service */ static void -reconnect (struct GNUNET_PEERINFO_Handle *h) +reconnect(struct GNUNET_PEERINFO_Handle *h) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (info, - GNUNET_MESSAGE_TYPE_PEERINFO_INFO, - struct InfoMessage, - h), - GNUNET_MQ_hd_fixed_size (end_iteration, - GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END, - struct GNUNET_MessageHeader, - h), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(info, + GNUNET_MESSAGE_TYPE_PEERINFO_INFO, + struct InfoMessage, + h), + GNUNET_MQ_hd_fixed_size(end_iteration, + GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END, + struct GNUNET_MessageHeader, + h), + GNUNET_MQ_handler_end() }; if (NULL != h->r_task) - { - GNUNET_SCHEDULER_cancel (h->r_task); - h->r_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(h->r_task); + h->r_task = NULL; + } if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } - h->mq = GNUNET_CLIENT_connect (h->cfg, - "peerinfo", - handlers, - &mq_error_handler, - h); + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } + h->mq = GNUNET_CLIENT_connect(h->cfg, + "peerinfo", + handlers, + &mq_error_handler, + h); if (NULL != h->ic_head) - send_ic_request (h); + send_ic_request(h); } @@ -488,29 +483,29 @@ reconnect (struct GNUNET_PEERINFO_Handle *h) * @return iterator context */ struct GNUNET_PEERINFO_IteratorContext * -GNUNET_PEERINFO_iterate (struct GNUNET_PEERINFO_Handle *h, - int include_friend_only, - const struct GNUNET_PeerIdentity *peer, - GNUNET_PEERINFO_Processor callback, - void *callback_cls) +GNUNET_PEERINFO_iterate(struct GNUNET_PEERINFO_Handle *h, + int include_friend_only, + const struct GNUNET_PeerIdentity *peer, + GNUNET_PEERINFO_Processor callback, + void *callback_cls) { struct GNUNET_PEERINFO_IteratorContext *ic; - ic = GNUNET_new (struct GNUNET_PEERINFO_IteratorContext); + ic = GNUNET_new(struct GNUNET_PEERINFO_IteratorContext); ic->h = h; ic->include_friend_only = include_friend_only; ic->callback = callback; ic->callback_cls = callback_cls; if (NULL != peer) - { - ic->have_peer = GNUNET_YES; - ic->peer = *peer; - } - GNUNET_CONTAINER_DLL_insert_tail (h->ic_head, - h->ic_tail, - ic); + { + ic->have_peer = GNUNET_YES; + ic->peer = *peer; + } + GNUNET_CONTAINER_DLL_insert_tail(h->ic_head, + h->ic_tail, + ic); if (h->ic_head == ic) - send_ic_request (h); + send_ic_request(h); return ic; } @@ -521,17 +516,17 @@ GNUNET_PEERINFO_iterate (struct GNUNET_PEERINFO_Handle *h, * @param ic context of the iterator to cancel */ void -GNUNET_PEERINFO_iterate_cancel (struct GNUNET_PEERINFO_IteratorContext *ic) +GNUNET_PEERINFO_iterate_cancel(struct GNUNET_PEERINFO_IteratorContext *ic) { struct GNUNET_PEERINFO_Handle *h = ic->h; ic->callback = NULL; if (ic == h->ic_head) return; - GNUNET_CONTAINER_DLL_remove (h->ic_head, - h->ic_tail, - ic); - GNUNET_free (ic); + GNUNET_CONTAINER_DLL_remove(h->ic_head, + h->ic_tail, + ic); + GNUNET_free(ic); } @@ -554,29 +549,29 @@ GNUNET_PEERINFO_iterate_cancel (struct GNUNET_PEERINFO_IteratorContext *ic) * calling @a cont must be prevented) */ struct GNUNET_MQ_Envelope * -GNUNET_PEERINFO_add_peer (struct GNUNET_PEERINFO_Handle *h, - const struct GNUNET_HELLO_Message *hello, - GNUNET_SCHEDULER_TaskCallback cont, - void *cont_cls) +GNUNET_PEERINFO_add_peer(struct GNUNET_PEERINFO_Handle *h, + const struct GNUNET_HELLO_Message *hello, + GNUNET_SCHEDULER_TaskCallback cont, + void *cont_cls) { struct GNUNET_MQ_Envelope *env; struct GNUNET_PeerIdentity peer; if (NULL == h->mq) return NULL; - GNUNET_assert (GNUNET_OK == - GNUNET_HELLO_get_id (hello, - &peer)); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Adding peer `%s' to PEERINFO database\n", - GNUNET_i2s (&peer)); - env = GNUNET_MQ_msg_copy ((const struct GNUNET_MessageHeader *) hello); + GNUNET_assert(GNUNET_OK == + GNUNET_HELLO_get_id(hello, + &peer)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Adding peer `%s' to PEERINFO database\n", + GNUNET_i2s(&peer)); + env = GNUNET_MQ_msg_copy((const struct GNUNET_MessageHeader *)hello); if (NULL != cont) - GNUNET_MQ_notify_sent (env, - cont, - cont_cls); - GNUNET_MQ_send (h->mq, - env); + GNUNET_MQ_notify_sent(env, + cont, + cont_cls); + GNUNET_MQ_send(h->mq, + env); return env; } diff --git a/src/peerinfo/peerinfo_api_notify.c b/src/peerinfo/peerinfo_api_notify.c index fc9b64858..130ce3a5d 100644 --- a/src/peerinfo/peerinfo_api_notify.c +++ b/src/peerinfo/peerinfo_api_notify.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerinfo/peerinfo_api_notify.c @@ -29,14 +29,12 @@ #include "gnunet_protocols.h" #include "peerinfo.h" -#define LOG(kind,...) GNUNET_log_from (kind, "peerinfo-api",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "peerinfo-api", __VA_ARGS__) /** * Context for the info handler. */ -struct GNUNET_PEERINFO_NotifyContext -{ - +struct GNUNET_PEERINFO_NotifyContext { /** * Our connection to the PEERINFO service. */ @@ -75,7 +73,7 @@ struct GNUNET_PEERINFO_NotifyContext * @param cls the `struct GNUNET_PEERINFO_NotifyContext *` */ static void -reconnect (void *cls); +reconnect(void *cls); /** @@ -84,12 +82,12 @@ reconnect (void *cls); * @param nc context to reconnect */ static void -do_reconnect (struct GNUNET_PEERINFO_NotifyContext *nc) +do_reconnect(struct GNUNET_PEERINFO_NotifyContext *nc) { - GNUNET_MQ_destroy (nc->mq); + GNUNET_MQ_destroy(nc->mq); nc->mq = NULL; - nc->task = GNUNET_SCHEDULER_add_now (&reconnect, - nc); + nc->task = GNUNET_SCHEDULER_add_now(&reconnect, + nc); } @@ -101,12 +99,12 @@ do_reconnect (struct GNUNET_PEERINFO_NotifyContext *nc) * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_PEERINFO_NotifyContext *nc = cls; - do_reconnect (nc); + do_reconnect(nc); } @@ -118,28 +116,28 @@ mq_error_handler (void *cls, * @return #GNUNET_OK if the message is well-formed */ static int -check_notification (void *cls, - const struct InfoMessage *im) +check_notification(void *cls, + const struct InfoMessage *im) { - uint16_t ms = ntohs (im->header.size) - sizeof (*im); + uint16_t ms = ntohs(im->header.size) - sizeof(*im); - if (ms >= sizeof (struct GNUNET_MessageHeader)) - { - const struct GNUNET_HELLO_Message *hello; - - hello = (const struct GNUNET_HELLO_Message *) &im[1]; - if (ms != GNUNET_HELLO_size (hello)) + if (ms >= sizeof(struct GNUNET_MessageHeader)) { - GNUNET_break (0); - return GNUNET_SYSERR; + const struct GNUNET_HELLO_Message *hello; + + hello = (const struct GNUNET_HELLO_Message *)&im[1]; + if (ms != GNUNET_HELLO_size(hello)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + return GNUNET_OK; } - return GNUNET_OK; - } if (0 != ms) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; /* odd... */ } @@ -151,23 +149,23 @@ check_notification (void *cls, * @param im message received */ static void -handle_notification (void *cls, - const struct InfoMessage *im) +handle_notification(void *cls, + const struct InfoMessage *im) { struct GNUNET_PEERINFO_NotifyContext *nc = cls; const struct GNUNET_HELLO_Message *hello; - uint16_t ms = ntohs (im->header.size) - sizeof (struct InfoMessage); + uint16_t ms = ntohs(im->header.size) - sizeof(struct InfoMessage); if (0 == ms) return; - hello = (const struct GNUNET_HELLO_Message *) &im[1]; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received information about peer `%s' from peerinfo database\n", - GNUNET_i2s (&im->peer)); - nc->callback (nc->callback_cls, - &im->peer, - hello, - NULL); + hello = (const struct GNUNET_HELLO_Message *)&im[1]; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received information about peer `%s' from peerinfo database\n", + GNUNET_i2s(&im->peer)); + nc->callback(nc->callback_cls, + &im->peer, + hello, + NULL); } @@ -181,8 +179,8 @@ handle_notification (void *cls, * @param msg message received, NULL on timeout or fatal error */ static void -handle_end_iteration (void *cls, - const struct GNUNET_MessageHeader *msg) +handle_end_iteration(void *cls, + const struct GNUNET_MessageHeader *msg) { /* these are ignored by the notify API */ } @@ -194,36 +192,36 @@ handle_end_iteration (void *cls, * @param cls the `struct GNUNET_PEERINFO_NotifyContext *` */ static void -reconnect (void *cls) +reconnect(void *cls) { struct GNUNET_PEERINFO_NotifyContext *nc = cls; struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (notification, - GNUNET_MESSAGE_TYPE_PEERINFO_INFO, - struct InfoMessage, - nc), - GNUNET_MQ_hd_fixed_size (end_iteration, - GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END, - struct GNUNET_MessageHeader, - nc), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(notification, + GNUNET_MESSAGE_TYPE_PEERINFO_INFO, + struct InfoMessage, + nc), + GNUNET_MQ_hd_fixed_size(end_iteration, + GNUNET_MESSAGE_TYPE_PEERINFO_INFO_END, + struct GNUNET_MessageHeader, + nc), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *env; struct NotifyMessage *nm; nc->task = NULL; - nc->mq = GNUNET_CLIENT_connect (nc->cfg, - "peerinfo", - handlers, - &mq_error_handler, - nc); + nc->mq = GNUNET_CLIENT_connect(nc->cfg, + "peerinfo", + handlers, + &mq_error_handler, + nc); if (NULL == nc->mq) return; - env = GNUNET_MQ_msg (nm, - GNUNET_MESSAGE_TYPE_PEERINFO_NOTIFY); - nm->include_friend_only = htonl (nc->include_friend_only); - GNUNET_MQ_send (nc->mq, - env); + env = GNUNET_MQ_msg(nm, + GNUNET_MESSAGE_TYPE_PEERINFO_NOTIFY); + nm->include_friend_only = htonl(nc->include_friend_only); + GNUNET_MQ_send(nc->mq, + env); } @@ -243,26 +241,26 @@ reconnect (void *cls) * @return NULL on error */ struct GNUNET_PEERINFO_NotifyContext * -GNUNET_PEERINFO_notify (const struct GNUNET_CONFIGURATION_Handle *cfg, - int include_friend_only, - GNUNET_PEERINFO_Processor callback, - void *callback_cls) +GNUNET_PEERINFO_notify(const struct GNUNET_CONFIGURATION_Handle *cfg, + int include_friend_only, + GNUNET_PEERINFO_Processor callback, + void *callback_cls) { struct GNUNET_PEERINFO_NotifyContext *nc; - nc = GNUNET_new (struct GNUNET_PEERINFO_NotifyContext); + nc = GNUNET_new(struct GNUNET_PEERINFO_NotifyContext); nc->cfg = cfg; nc->callback = callback; nc->callback_cls = callback_cls; nc->include_friend_only = include_friend_only; - reconnect (nc); + reconnect(nc); if (NULL == nc->mq) - { - LOG (GNUNET_ERROR_TYPE_WARNING, - "Could not connect to PEERINFO service.\n"); - GNUNET_free (nc); - return NULL; - } + { + LOG(GNUNET_ERROR_TYPE_WARNING, + "Could not connect to PEERINFO service.\n"); + GNUNET_free(nc); + return NULL; + } return nc; } @@ -273,19 +271,19 @@ GNUNET_PEERINFO_notify (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param nc context to stop notifying */ void -GNUNET_PEERINFO_notify_cancel (struct GNUNET_PEERINFO_NotifyContext *nc) +GNUNET_PEERINFO_notify_cancel(struct GNUNET_PEERINFO_NotifyContext *nc) { if (NULL != nc->mq) - { - GNUNET_MQ_destroy (nc->mq); - nc->mq = NULL; - } + { + GNUNET_MQ_destroy(nc->mq); + nc->mq = NULL; + } if (NULL != nc->task) - { - GNUNET_SCHEDULER_cancel (nc->task); - nc->task = NULL; - } - GNUNET_free (nc); + { + GNUNET_SCHEDULER_cancel(nc->task); + nc->task = NULL; + } + GNUNET_free(nc); } /* end of peerinfo_api_notify.c */ diff --git a/src/peerinfo/perf_peerinfo_api.c b/src/peerinfo/perf_peerinfo_api.c index d56e0c558..b9317478c 100644 --- a/src/peerinfo/perf_peerinfo_api.c +++ b/src/peerinfo/perf_peerinfo_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerinfo/perf_peerinfo_api.c @@ -48,40 +48,40 @@ static struct GNUNET_SCHEDULER_Task *tt; static void -do_shutdown (void *cls) +do_shutdown(void *cls) { if (NULL != tt) - { - GNUNET_SCHEDULER_cancel (tt); - tt = NULL; - } + { + GNUNET_SCHEDULER_cancel(tt); + tt = NULL; + } for (unsigned int i = 0; i < NUM_REQUESTS; i++) if (NULL != ic[i]) - GNUNET_PEERINFO_iterate_cancel (ic[i]); - GNUNET_PEERINFO_disconnect (h); + GNUNET_PEERINFO_iterate_cancel(ic[i]); + GNUNET_PEERINFO_disconnect(h); h = NULL; } static void -do_timeout (void *cls) +do_timeout(void *cls) { tt = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } static int -check_it (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +check_it(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { return GNUNET_OK; } static ssize_t -address_generator (void *cls, size_t max, void *buf) +address_generator(void *cls, size_t max, void *buf) { size_t *agc = cls; ssize_t ret; @@ -91,100 +91,100 @@ address_generator (void *cls, size_t max, void *buf) if (*agc == 0) return GNUNET_SYSERR; /* Done */ - GNUNET_asprintf (&caddress, "Address%d", *agc); + GNUNET_asprintf(&caddress, "Address%d", *agc); address.peer = pid; - address.address_length = strlen (caddress) + 1; + address.address_length = strlen(caddress) + 1; address.address = caddress; address.transport_name = "peerinfotest"; ret = - GNUNET_HELLO_add_address (&address, - GNUNET_TIME_relative_to_absolute - (GNUNET_TIME_UNIT_HOURS), buf, max); - GNUNET_free (caddress); + GNUNET_HELLO_add_address(&address, + GNUNET_TIME_relative_to_absolute + (GNUNET_TIME_UNIT_HOURS), buf, max); + GNUNET_free(caddress); *agc = 0; return ret; } static void -add_peer (size_t i) +add_peer(size_t i) { struct GNUNET_HELLO_Message *h2; - memset (&pid, i, sizeof (pid)); - h2 = GNUNET_HELLO_create (&pid.public_key, - &address_generator, - &i, - GNUNET_NO); - GNUNET_PEERINFO_add_peer (h, h2, NULL, NULL); - GNUNET_free (h2); + memset(&pid, i, sizeof(pid)); + h2 = GNUNET_HELLO_create(&pid.public_key, + &address_generator, + &i, + GNUNET_NO); + GNUNET_PEERINFO_add_peer(h, h2, NULL, NULL); + GNUNET_free(h2); } static void -process (void *cls, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello, - const char *err_msg) +process(void *cls, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello, + const char *err_msg) { struct GNUNET_PEERINFO_IteratorContext **icp = cls; if (NULL == peer) - { - *icp = NULL; - return; - } + { + *icp = NULL; + return; + } numpeers++; - if (0 && (NULL != hello) ) - GNUNET_HELLO_iterate_addresses (hello, - GNUNET_NO, - &check_it, - NULL); + if (0 && (NULL != hello)) + GNUNET_HELLO_iterate_addresses(hello, + GNUNET_NO, + &check_it, + NULL); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - h = GNUNET_PEERINFO_connect (cfg); - GNUNET_assert (h != NULL); + h = GNUNET_PEERINFO_connect(cfg); + GNUNET_assert(h != NULL); for (unsigned int i = 0; i < NUM_REQUESTS; i++) - { - add_peer (i); - ic[i] = GNUNET_PEERINFO_iterate (h, - GNUNET_YES, - NULL, - &process, - &ic[i]); - } - tt = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, - 5), - &do_timeout, - NULL); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); + { + add_peer(i); + ic[i] = GNUNET_PEERINFO_iterate(h, + GNUNET_YES, + NULL, + &process, + &ic[i]); + } + tt = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, + 5), + &do_timeout, + NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); } int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { - if (0 != GNUNET_TESTING_service_run ("perf-gnunet-peerinfo", - "peerinfo", - "test_peerinfo_api_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_service_run("perf-gnunet-peerinfo", + "peerinfo", + "test_peerinfo_api_data.conf", + &run, NULL)) return 1; - fprintf (stderr, - "Received %u/%u calls before timeout\n", - numpeers, - NUM_REQUESTS * NUM_REQUESTS / 2); - GAUGER ("PEERINFO", - "Peerinfo lookups", - numpeers / 5, - "peers/s"); + fprintf(stderr, + "Received %u/%u calls before timeout\n", + numpeers, + NUM_REQUESTS * NUM_REQUESTS / 2); + GAUGER("PEERINFO", + "Peerinfo lookups", + numpeers / 5, + "peers/s"); return 0; } diff --git a/src/peerinfo/test_peerinfo_api.c b/src/peerinfo/test_peerinfo_api.c index 9060cf7b7..4c2184904 100644 --- a/src/peerinfo/test_peerinfo_api.c +++ b/src/peerinfo/test_peerinfo_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerinfo/test_peerinfo_api.c @@ -43,25 +43,25 @@ static int global_ret; static int -check_it (void *cls, const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +check_it(void *cls, const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { unsigned int *agc = cls; if (address != NULL) - { - GNUNET_assert (0 == strcmp ("peerinfotest", address->transport_name)); - GNUNET_assert (0 == - strncmp ("Address", address->address, + { + GNUNET_assert(0 == strcmp("peerinfotest", address->transport_name)); + GNUNET_assert(0 == + strncmp("Address", address->address, address->address_length)); - (*agc) -= (1 << (address->address_length - 1)); - } + (*agc) -= (1 << (address->address_length - 1)); + } return GNUNET_OK; } static ssize_t -address_generator (void *cls, size_t max, void *buf) +address_generator(void *cls, size_t max, void *buf) { size_t *agc = cls; ssize_t ret; @@ -69,14 +69,14 @@ address_generator (void *cls, size_t max, void *buf) if (0 == *agc) return GNUNET_SYSERR; /* Done */ - memset (&address.peer, 0, sizeof (struct GNUNET_PeerIdentity)); + memset(&address.peer, 0, sizeof(struct GNUNET_PeerIdentity)); address.address = "Address"; address.transport_name = "peerinfotest"; address.address_length = *agc; ret = - GNUNET_HELLO_add_address (&address, - GNUNET_TIME_relative_to_absolute - (GNUNET_TIME_UNIT_HOURS), buf, max); + GNUNET_HELLO_add_address(&address, + GNUNET_TIME_relative_to_absolute + (GNUNET_TIME_UNIT_HOURS), buf, max); (*agc)--; return ret; } @@ -84,85 +84,84 @@ address_generator (void *cls, size_t max, void *buf) struct GNUNET_PeerIdentity pid; static void -add_peer () +add_peer() { struct GNUNET_HELLO_Message *h2; size_t agc; agc = 2; - memset (&pid, 32, sizeof (pid)); - h2 = GNUNET_HELLO_create (&pid.public_key, &address_generator, &agc, GNUNET_NO); - GNUNET_PEERINFO_add_peer (h, h2, NULL, NULL); - GNUNET_free (h2); - + memset(&pid, 32, sizeof(pid)); + h2 = GNUNET_HELLO_create(&pid.public_key, &address_generator, &agc, GNUNET_NO); + GNUNET_PEERINFO_add_peer(h, h2, NULL, NULL); + GNUNET_free(h2); } static void -process (void *cls, const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello, const char *err_msg) +process(void *cls, const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello, const char *err_msg) { unsigned int agc; if (err_msg != NULL) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Error in communication with PEERINFO service\n")); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Error in communication with PEERINFO service\n")); + } if (peer == NULL) - { - ic = NULL; - if ((3 == global_ret) && (retries < 50)) { - /* try again */ - retries++; - add_peer (); - ic = GNUNET_PEERINFO_iterate (h, GNUNET_NO, NULL, - &process, - cls); + ic = NULL; + if ((3 == global_ret) && (retries < 50)) + { + /* try again */ + retries++; + add_peer(); + ic = GNUNET_PEERINFO_iterate(h, GNUNET_NO, NULL, + &process, + cls); + return; + } + GNUNET_assert(peer == NULL); + GNUNET_assert(2 == global_ret); + GNUNET_PEERINFO_disconnect(h); + h = NULL; + global_ret = 0; return; } - GNUNET_assert (peer == NULL); - GNUNET_assert (2 == global_ret); - GNUNET_PEERINFO_disconnect (h); - h = NULL; - global_ret = 0; - return; - } if (hello != NULL) - { - GNUNET_assert (3 == global_ret); - agc = 3; - GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, - &check_it, &agc); - GNUNET_assert (agc == 0); - global_ret = 2; - } + { + GNUNET_assert(3 == global_ret); + agc = 3; + GNUNET_HELLO_iterate_addresses(hello, GNUNET_NO, + &check_it, &agc); + GNUNET_assert(agc == 0); + global_ret = 2; + } } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - h = GNUNET_PEERINFO_connect (cfg); - GNUNET_assert (NULL != h); - add_peer (); - ic = GNUNET_PEERINFO_iterate (h, GNUNET_NO, &pid, - &process, cls); + h = GNUNET_PEERINFO_connect(cfg); + GNUNET_assert(NULL != h); + add_peer(); + ic = GNUNET_PEERINFO_iterate(h, GNUNET_NO, &pid, + &process, cls); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { global_ret = 3; - if (0 != GNUNET_TESTING_service_run ("test-gnunet-peerinfo", - "peerinfo", - "test_peerinfo_api_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_service_run("test-gnunet-peerinfo", + "peerinfo", + "test_peerinfo_api_data.conf", + &run, NULL)) return 1; return global_ret; } diff --git a/src/peerinfo/test_peerinfo_api_friend_only.c b/src/peerinfo/test_peerinfo_api_friend_only.c index d9d9200ac..a7bd69e6f 100644 --- a/src/peerinfo/test_peerinfo_api_friend_only.c +++ b/src/peerinfo/test_peerinfo_api_friend_only.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerinfo/test_peerinfo_api_friend_only.c @@ -46,9 +46,9 @@ static int global_ret; static ssize_t -address_generator (void *cls, - size_t max, - void *buf) +address_generator(void *cls, + size_t max, + void *buf) { size_t *agc = cls; ssize_t ret; @@ -56,114 +56,113 @@ address_generator (void *cls, if (0 == *agc) return GNUNET_SYSERR; /* Done */ - memset (&address.peer, - 0, - sizeof (struct GNUNET_PeerIdentity)); + memset(&address.peer, + 0, + sizeof(struct GNUNET_PeerIdentity)); address.address = "Address"; address.transport_name = "peerinfotest"; address.address_length = *agc; - ret = GNUNET_HELLO_add_address (&address, - GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS), - buf, - max); + ret = GNUNET_HELLO_add_address(&address, + GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS), + buf, + max); (*agc)--; return ret; } static void -add_peer () +add_peer() { struct GNUNET_HELLO_Message *h2; size_t agc; agc = 2; - memset (&pid, 32, sizeof (pid)); - h2 = GNUNET_HELLO_create (&pid.public_key, - &address_generator, - &agc, - GNUNET_YES); - GNUNET_PEERINFO_add_peer (h, - h2, - NULL, - NULL); - GNUNET_free (h2); - + memset(&pid, 32, sizeof(pid)); + h2 = GNUNET_HELLO_create(&pid.public_key, + &address_generator, + &agc, + GNUNET_YES); + GNUNET_PEERINFO_add_peer(h, + h2, + NULL, + NULL); + GNUNET_free(h2); } static void -process (void *cls, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello, - const char *err_msg) +process(void *cls, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello, + const char *err_msg) { if (NULL != err_msg) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error in communication with PEERINFO service: %s\n", - err_msg); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error in communication with PEERINFO service: %s\n", + err_msg); + } if (NULL == peer) - { - ic = NULL; - if ((3 == global_ret) && (retries < 50)) { - /* try again */ - retries++; - add_peer (); - ic = GNUNET_PEERINFO_iterate (h, - GNUNET_NO, - NULL, - &process, - cls); + ic = NULL; + if ((3 == global_ret) && (retries < 50)) + { + /* try again */ + retries++; + add_peer(); + ic = GNUNET_PEERINFO_iterate(h, + GNUNET_NO, + NULL, + &process, + cls); + return; + } + GNUNET_assert(peer == NULL); + GNUNET_PEERINFO_disconnect(h); + h = NULL; + global_ret = 0; + return; + } + + if ((NULL != hello) && + (GNUNET_YES == GNUNET_HELLO_is_friend_only(hello))) + { + fprintf(stderr, + "Received friend-only HELLO\n"); + global_ret = 1; + GNUNET_PEERINFO_disconnect(h); + h = NULL; return; } - GNUNET_assert (peer == NULL); - GNUNET_PEERINFO_disconnect (h); - h = NULL; - global_ret = 0; - return; - } - - if ( (NULL != hello) && - (GNUNET_YES == GNUNET_HELLO_is_friend_only (hello)) ) - { - fprintf (stderr, - "Received friend-only HELLO\n"); - global_ret = 1; - GNUNET_PEERINFO_disconnect (h); - h = NULL; - return; - } } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - h = GNUNET_PEERINFO_connect (cfg); - GNUNET_assert (NULL != h); - add_peer (); - ic = GNUNET_PEERINFO_iterate (h, - GNUNET_NO, - &pid, - &process, - NULL); + h = GNUNET_PEERINFO_connect(cfg); + GNUNET_assert(NULL != h); + add_peer(); + ic = GNUNET_PEERINFO_iterate(h, + GNUNET_NO, + &pid, + &process, + NULL); } int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { global_ret = 3; - if (0 != GNUNET_TESTING_service_run ("test-peerinfo-api-friend-only", - "peerinfo", - "test_peerinfo_api_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_service_run("test-peerinfo-api-friend-only", + "peerinfo", + "test_peerinfo_api_data.conf", + &run, NULL)) return 1; return global_ret; } diff --git a/src/peerinfo/test_peerinfo_api_notify_friend_only.c b/src/peerinfo/test_peerinfo_api_notify_friend_only.c index 0a9bfc083..80b5883de 100644 --- a/src/peerinfo/test_peerinfo_api_notify_friend_only.c +++ b/src/peerinfo/test_peerinfo_api_notify_friend_only.c @@ -1,19 +1,19 @@ /* - This file is part of GNUnet. - Copyright (C) 2004, 2009 GNUnet e.V. + This file is part of GNUnet. + Copyright (C) 2004, 2009 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later */ @@ -34,7 +34,7 @@ #include "gnunet_testing_lib.h" #include "peerinfo.h" -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5) static struct GNUNET_PEERINFO_Handle *h; static struct GNUNET_PEERINFO_NotifyContext *pnc_w_fo; @@ -61,46 +61,46 @@ struct GNUNET_PeerIdentity pid; struct GNUNET_SCHEDULER_Task *timeout_task; static void -end_badly (void *cls) +end_badly(void *cls) { timeout_task = NULL; GNUNET_break(0); if (NULL != pnc_wo_fo) - { - GNUNET_PEERINFO_notify_cancel (pnc_wo_fo); - pnc_wo_fo = NULL; - } + { + GNUNET_PEERINFO_notify_cancel(pnc_wo_fo); + pnc_wo_fo = NULL; + } if (NULL != pnc_w_fo) - { - GNUNET_PEERINFO_notify_cancel (pnc_w_fo); - pnc_w_fo = NULL; - } + { + GNUNET_PEERINFO_notify_cancel(pnc_w_fo); + pnc_w_fo = NULL; + } if (NULL != h) - { - GNUNET_PEERINFO_disconnect (h); - h = NULL; - } + { + GNUNET_PEERINFO_disconnect(h); + h = NULL; + } global_ret = 255; } static void -done (void *cls) +done(void *cls) { if (NULL != pnc_w_fo) - GNUNET_PEERINFO_notify_cancel (pnc_w_fo); + GNUNET_PEERINFO_notify_cancel(pnc_w_fo); pnc_w_fo = NULL; if (NULL != pnc_wo_fo) - GNUNET_PEERINFO_notify_cancel (pnc_wo_fo); + GNUNET_PEERINFO_notify_cancel(pnc_wo_fo); pnc_wo_fo = NULL; - GNUNET_PEERINFO_disconnect (h); + GNUNET_PEERINFO_disconnect(h); h = NULL; if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } if ((GNUNET_YES == res_cb_w_fo) && (GNUNET_NO == res_cb_wo_fo)) global_ret = 0; @@ -109,7 +109,7 @@ done (void *cls) } static ssize_t -address_generator (void *cls, size_t max, void *buf) +address_generator(void *cls, size_t max, void *buf) { size_t *agc = cls; ssize_t ret; @@ -117,137 +117,137 @@ address_generator (void *cls, size_t max, void *buf) if (0 == *agc) return GNUNET_SYSERR; /* Done */ - memset (&address.peer, 0, sizeof(struct GNUNET_PeerIdentity)); + memset(&address.peer, 0, sizeof(struct GNUNET_PeerIdentity)); address.address = "Address"; address.transport_name = "peerinfotest"; address.address_length = *agc; - ret = GNUNET_HELLO_add_address (&address, - GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS), buf, max); + ret = GNUNET_HELLO_add_address(&address, + GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS), buf, max); (*agc)--; return ret; } static void -process_w_fo (void *cls, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello, - const char *err_msg) +process_w_fo(void *cls, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello, + const char *err_msg) { if (err_msg != NULL) - { - GNUNET_log(GNUNET_ERROR_TYPE_ERROR, - _("Error in communication with PEERINFO service\n")); - GNUNET_SCHEDULER_add_now (&done, NULL); - return; - } - - if (NULL != peer) - { - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Received callback for peer `%s' %s HELLO\n", GNUNET_i2s (peer), - (NULL != hello) ? "with" : "without"); - - if (NULL == hello) - return; - - if (GNUNET_NO == GNUNET_HELLO_is_friend_only (hello)) { - GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Error in communication with PEERINFO service\n")); + GNUNET_SCHEDULER_add_now(&done, NULL); return; } - GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Received %s HELLO for peer `%s'\n", - (GNUNET_YES == GNUNET_HELLO_is_friend_only (hello)) ? "friend only" : "public", - GNUNET_i2s (peer)); - if (0 == GNUNET_memcmp (&pid, peer)) + if (NULL != peer) { - res_cb_w_fo = GNUNET_YES; - GNUNET_SCHEDULER_add_now (&done, NULL); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Received callback for peer `%s' %s HELLO\n", GNUNET_i2s(peer), + (NULL != hello) ? "with" : "without"); + + if (NULL == hello) + return; + + if (GNUNET_NO == GNUNET_HELLO_is_friend_only(hello)) + { + GNUNET_break(0); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Received %s HELLO for peer `%s'\n", + (GNUNET_YES == GNUNET_HELLO_is_friend_only(hello)) ? "friend only" : "public", + GNUNET_i2s(peer)); + if (0 == GNUNET_memcmp(&pid, peer)) + { + res_cb_w_fo = GNUNET_YES; + GNUNET_SCHEDULER_add_now(&done, NULL); + } + return; } - return; - } } static void -process_wo_fo (void *cls, const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello, const char *err_msg) +process_wo_fo(void *cls, const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello, const char *err_msg) { if (err_msg != NULL) - { - GNUNET_log(GNUNET_ERROR_TYPE_ERROR, - _("Error in communication with PEERINFO service\n")); - GNUNET_SCHEDULER_add_now (&done, NULL); - return; - } - - if (NULL != peer) - { - GNUNET_log(GNUNET_ERROR_TYPE_INFO, - "Received callback for peer `%s' %s HELLO\n", GNUNET_i2s (peer), - (NULL != hello) ? "with" : "without"); - - if (NULL == hello) - return; - - if (GNUNET_YES == GNUNET_HELLO_is_friend_only (hello)) { - GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Error in communication with PEERINFO service\n")); + GNUNET_SCHEDULER_add_now(&done, NULL); return; } - GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Received %s HELLO for peer `%s'\n", - (GNUNET_YES == GNUNET_HELLO_is_friend_only (hello)) ? "friend only" : "public", - GNUNET_i2s (peer)); - if (0 == GNUNET_memcmp (&pid, peer)) + if (NULL != peer) { - GNUNET_break(0); - res_cb_wo_fo = GNUNET_YES; + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Received callback for peer `%s' %s HELLO\n", GNUNET_i2s(peer), + (NULL != hello) ? "with" : "without"); + + if (NULL == hello) + return; + + if (GNUNET_YES == GNUNET_HELLO_is_friend_only(hello)) + { + GNUNET_break(0); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Received %s HELLO for peer `%s'\n", + (GNUNET_YES == GNUNET_HELLO_is_friend_only(hello)) ? "friend only" : "public", + GNUNET_i2s(peer)); + if (0 == GNUNET_memcmp(&pid, peer)) + { + GNUNET_break(0); + res_cb_wo_fo = GNUNET_YES; + } } - } } static void -add_peer () +add_peer() { struct GNUNET_HELLO_Message *h2; size_t agc; agc = 2; - memset (&pid, 32, sizeof(pid)); - h2 = GNUNET_HELLO_create (&pid.public_key, &address_generator, &agc, - GNUNET_YES); - GNUNET_PEERINFO_add_peer (h, h2, NULL, NULL); + memset(&pid, 32, sizeof(pid)); + h2 = GNUNET_HELLO_create(&pid.public_key, &address_generator, &agc, + GNUNET_YES); + GNUNET_PEERINFO_add_peer(h, h2, NULL, NULL); GNUNET_free(h2); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, &end_badly, NULL); + timeout_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, &end_badly, NULL); mycfg = cfg; - pnc_w_fo = GNUNET_PEERINFO_notify (mycfg, GNUNET_YES, &process_w_fo, NULL); - pnc_wo_fo = GNUNET_PEERINFO_notify (mycfg, GNUNET_NO, &process_wo_fo, NULL); - h = GNUNET_PEERINFO_connect (cfg); + pnc_w_fo = GNUNET_PEERINFO_notify(mycfg, GNUNET_YES, &process_w_fo, NULL); + pnc_wo_fo = GNUNET_PEERINFO_notify(mycfg, GNUNET_NO, &process_wo_fo, NULL); + h = GNUNET_PEERINFO_connect(cfg); GNUNET_assert(NULL != h); - add_peer (); + add_peer(); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { res_cb_w_fo = GNUNET_NO; res_cb_wo_fo = GNUNET_NO; global_ret = 3; - if (0 != GNUNET_TESTING_service_run ("test-peerinfo-api-friend-only", - "peerinfo", - "test_peerinfo_api_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_service_run("test-peerinfo-api-friend-only", + "peerinfo", + "test_peerinfo_api_data.conf", + &run, NULL)) return 1; return global_ret; } diff --git a/src/peerinfo/test_peerinfo_shipped_hellos.c b/src/peerinfo/test_peerinfo_shipped_hellos.c index 4da6ef0ac..36deade1e 100644 --- a/src/peerinfo/test_peerinfo_shipped_hellos.c +++ b/src/peerinfo/test_peerinfo_shipped_hellos.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerinfo/test_peerinfo_shipped_hellos.c @@ -40,102 +40,102 @@ static int global_ret; static int -addr_cb (void *cls, - const struct GNUNET_HELLO_Address *address, - struct GNUNET_TIME_Absolute expiration) +addr_cb(void *cls, + const struct GNUNET_HELLO_Address *address, + struct GNUNET_TIME_Absolute expiration) { unsigned int *addr = cls; - (*addr) ++; + (*addr)++; return GNUNET_OK; } static void -process (void *cls, - const struct GNUNET_PeerIdentity *peer, - const struct GNUNET_HELLO_Message *hello, - const char *err_msg) +process(void *cls, + const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_HELLO_Message *hello, + const char *err_msg) { static unsigned int calls = 0; unsigned int addr; if (NULL != err_msg) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error in communication with PEERINFO service: %s\n", - err_msg); - } - if (NULL != peer) - { - addr = 0; - if (NULL != hello) { - GNUNET_HELLO_iterate_addresses (hello, - GNUNET_NO, - &addr_cb, - &addr); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got information about peer %s with %u addresses\n", - GNUNET_i2s (peer), - addr); - calls++; + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error in communication with PEERINFO service: %s\n", + err_msg); } - else + if (NULL != peer) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got no HELLP for peer %s\n", - GNUNET_i2s (peer)); + addr = 0; + if (NULL != hello) + { + GNUNET_HELLO_iterate_addresses(hello, + GNUNET_NO, + &addr_cb, + &addr); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got information about peer %s with %u addresses\n", + GNUNET_i2s(peer), + addr); + calls++; + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got no HELLP for peer %s\n", + GNUNET_i2s(peer)); + } } - } else - { - if (0 == calls) - { - fprintf (stderr, - "Failed: got no callbacks!\n"); - global_ret = 1; - GNUNET_PEERINFO_disconnect (h); - h = NULL; - } - else { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got %u HELLOs in total\n", - calls); - global_ret = 0; - GNUNET_PEERINFO_disconnect (h); - h = NULL; + if (0 == calls) + { + fprintf(stderr, + "Failed: got no callbacks!\n"); + global_ret = 1; + GNUNET_PEERINFO_disconnect(h); + h = NULL; + } + else + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got %u HELLOs in total\n", + calls); + global_ret = 0; + GNUNET_PEERINFO_disconnect(h); + h = NULL; + } } - } } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - h = GNUNET_PEERINFO_connect (cfg); - GNUNET_assert (NULL != h); - ic = GNUNET_PEERINFO_iterate (h, - GNUNET_YES, - NULL, - &process, - cls); - GNUNET_assert (NULL != ic); + h = GNUNET_PEERINFO_connect(cfg); + GNUNET_assert(NULL != h); + ic = GNUNET_PEERINFO_iterate(h, + GNUNET_YES, + NULL, + &process, + cls); + GNUNET_assert(NULL != ic); } int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { global_ret = 3; - if (0 != GNUNET_TESTING_service_run ("test_peerinfo_shipped_hellos", - "peerinfo", - "test_peerinfo_api_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_service_run("test_peerinfo_shipped_hellos", + "peerinfo", + "test_peerinfo_api_data.conf", + &run, NULL)) return 1; return global_ret; } diff --git a/src/peerstore/gnunet-peerstore.c b/src/peerstore/gnunet-peerstore.c index 9d95655b4..891676ebd 100644 --- a/src/peerstore/gnunet-peerstore.c +++ b/src/peerstore/gnunet-peerstore.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerstore/gnunet-peerstore.c @@ -41,13 +41,13 @@ static struct GNUNET_PEERSTORE_Handle *peerstore_handle; * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { if (NULL != peerstore_handle) - { - GNUNET_PEERSTORE_disconnect (peerstore_handle, GNUNET_YES); - peerstore_handle = NULL; - } + { + GNUNET_PEERSTORE_disconnect(peerstore_handle, GNUNET_YES); + peerstore_handle = NULL; + } } @@ -60,15 +60,15 @@ shutdown_task (void *cls) * @param cfg configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); - peerstore_handle = GNUNET_PEERSTORE_connect (cfg); - GNUNET_assert (NULL != peerstore_handle); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); + peerstore_handle = GNUNET_PEERSTORE_connect(cfg); + GNUNET_assert(NULL != peerstore_handle); ret = 0; } @@ -81,15 +81,16 @@ run (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { static const struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; + return (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, "gnunet-peerstore [options [value]]", - gettext_noop ("peerstore"), options, &run, - NULL)) ? ret : 1; + GNUNET_PROGRAM_run(argc, argv, "gnunet-peerstore [options [value]]", + gettext_noop("peerstore"), options, &run, + NULL)) ? ret : 1; } /* end of gnunet-peerstore.c */ diff --git a/src/peerstore/gnunet-service-peerstore.c b/src/peerstore/gnunet-service-peerstore.c index ed1c35535..02ac03e01 100644 --- a/src/peerstore/gnunet-service-peerstore.c +++ b/src/peerstore/gnunet-service-peerstore.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerstore/gnunet-service-peerstore.c @@ -75,25 +75,25 @@ static unsigned int num_clients; * Perform the actual shutdown operations */ static void -do_shutdown () +do_shutdown() { if (NULL != db_lib_name) - { - GNUNET_break (NULL == GNUNET_PLUGIN_unload (db_lib_name, db)); - GNUNET_free (db_lib_name); - db_lib_name = NULL; - } + { + GNUNET_break(NULL == GNUNET_PLUGIN_unload(db_lib_name, db)); + GNUNET_free(db_lib_name); + db_lib_name = NULL; + } if (NULL != watchers) - { - GNUNET_CONTAINER_multihashmap_destroy (watchers); - watchers = NULL; - } + { + GNUNET_CONTAINER_multihashmap_destroy(watchers); + watchers = NULL; + } if (NULL != expire_task) - { - GNUNET_SCHEDULER_cancel (expire_task); - expire_task = NULL; - } - GNUNET_SCHEDULER_shutdown (); + { + GNUNET_SCHEDULER_cancel(expire_task); + expire_task = NULL; + } + GNUNET_SCHEDULER_shutdown(); } @@ -103,42 +103,42 @@ do_shutdown () * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { in_shutdown = GNUNET_YES; if (0 == num_clients) /* Only when no connected clients. */ - do_shutdown (); + do_shutdown(); } /* Forward declaration */ static void -expire_records_continuation (void *cls, int success); +expire_records_continuation(void *cls, int success); /** * Deletes any expired records from storage */ static void -cleanup_expired_records (void *cls) +cleanup_expired_records(void *cls) { int ret; expire_task = NULL; - GNUNET_assert (NULL != db); - ret = db->expire_records (db->cls, - GNUNET_TIME_absolute_get (), - &expire_records_continuation, - NULL); + GNUNET_assert(NULL != db); + ret = db->expire_records(db->cls, + GNUNET_TIME_absolute_get(), + &expire_records_continuation, + NULL); if (GNUNET_OK != ret) - { - GNUNET_assert (NULL == expire_task); - expire_task = GNUNET_SCHEDULER_add_delayed ( - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, - EXPIRED_RECORDS_CLEANUP_INTERVAL), - &cleanup_expired_records, - NULL); - } + { + GNUNET_assert(NULL == expire_task); + expire_task = GNUNET_SCHEDULER_add_delayed( + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, + EXPIRED_RECORDS_CLEANUP_INTERVAL), + &cleanup_expired_records, + NULL); + } } @@ -149,14 +149,14 @@ cleanup_expired_records (void *cls) * @param success count of records deleted or #GNUNET_SYSERR */ static void -expire_records_continuation (void *cls, int success) +expire_records_continuation(void *cls, int success) { if (success > 0) - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%d records expired.\n", success); - GNUNET_assert (NULL == expire_task); - expire_task = GNUNET_SCHEDULER_add_delayed ( - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, - EXPIRED_RECORDS_CLEANUP_INTERVAL), + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "%d records expired.\n", success); + GNUNET_assert(NULL == expire_task); + expire_task = GNUNET_SCHEDULER_add_delayed( + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, + EXPIRED_RECORDS_CLEANUP_INTERVAL), &cleanup_expired_records, NULL); } @@ -171,9 +171,9 @@ expire_records_continuation (void *cls, int success) * @return */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { num_clients++; return client; @@ -189,14 +189,14 @@ client_connect_cb (void *cls, * @return #GNUNET_OK to continue iterating */ static int -client_disconnect_it (void *cls, const struct GNUNET_HashCode *key, void *value) +client_disconnect_it(void *cls, const struct GNUNET_HashCode *key, void *value) { if (value == cls) - { - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (watchers, key, value)); - num_clients++; - } + { + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_remove(watchers, key, value)); + num_clients++; + } return GNUNET_OK; } @@ -208,18 +208,18 @@ client_disconnect_it (void *cls, const struct GNUNET_HashCode *key, void *value) * @param client identification of the client */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_cls) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "A client disconnected, cleaning up.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "A client disconnected, cleaning up.\n"); if (NULL != watchers) - GNUNET_CONTAINER_multihashmap_iterate (watchers, - &client_disconnect_it, - client); + GNUNET_CONTAINER_multihashmap_iterate(watchers, + &client_disconnect_it, + client); num_clients--; if ((0 == num_clients) && in_shutdown) - do_shutdown (); + do_shutdown(); } @@ -232,35 +232,35 @@ client_disconnect_cb (void *cls, * @return #GNUNET_YES to continue iteration */ static void -record_iterator (void *cls, - const struct GNUNET_PEERSTORE_Record *record, - const char *emsg) +record_iterator(void *cls, + const struct GNUNET_PEERSTORE_Record *record, + const char *emsg) { struct GNUNET_PEERSTORE_Record *cls_record = cls; struct GNUNET_MQ_Envelope *env; if (NULL == record) - { - /* No more records */ - struct GNUNET_MessageHeader *endmsg; - - env = GNUNET_MQ_msg (endmsg, GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE_END); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (cls_record->client), env); - if (NULL == emsg) - { - GNUNET_SERVICE_client_continue (cls_record->client); - } - else { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to iterate: %s\n", emsg); - GNUNET_SERVICE_client_drop (cls_record->client); + /* No more records */ + struct GNUNET_MessageHeader *endmsg; + + env = GNUNET_MQ_msg(endmsg, GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE_END); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(cls_record->client), env); + if (NULL == emsg) + { + GNUNET_SERVICE_client_continue(cls_record->client); + } + else + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Failed to iterate: %s\n", emsg); + GNUNET_SERVICE_client_drop(cls_record->client); + } + PEERSTORE_destroy_record(cls_record); + return; } - PEERSTORE_destroy_record (cls_record); - return; - } - env = PEERSTORE_create_record_mq_envelope ( + env = PEERSTORE_create_record_mq_envelope( record->sub_system, &record->peer, record->key, @@ -269,7 +269,7 @@ record_iterator (void *cls, record->expiry, 0, GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE_RECORD); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (cls_record->client), env); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(cls_record->client), env); } @@ -283,14 +283,14 @@ record_iterator (void *cls, * @return #GNUNET_YES to continue iterating */ static int -watch_notifier_it (void *cls, const struct GNUNET_HashCode *key, void *value) +watch_notifier_it(void *cls, const struct GNUNET_HashCode *key, void *value) { struct GNUNET_PEERSTORE_Record *record = cls; struct GNUNET_SERVICE_Client *client = value; struct GNUNET_MQ_Envelope *env; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found a watcher to update.\n"); - env = PEERSTORE_create_record_mq_envelope ( + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Found a watcher to update.\n"); + env = PEERSTORE_create_record_mq_envelope( record->sub_system, &record->peer, record->key, @@ -299,7 +299,7 @@ watch_notifier_it (void *cls, const struct GNUNET_HashCode *key, void *value) record->expiry, 0, GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH_RECORD); - GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); + GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env); return GNUNET_YES; } @@ -310,15 +310,15 @@ watch_notifier_it (void *cls, const struct GNUNET_HashCode *key, void *value) * @param record changed record to update watchers with */ static void -watch_notifier (struct GNUNET_PEERSTORE_Record *record) +watch_notifier(struct GNUNET_PEERSTORE_Record *record) { struct GNUNET_HashCode keyhash; - PEERSTORE_hash_key (record->sub_system, &record->peer, record->key, &keyhash); - GNUNET_CONTAINER_multihashmap_get_multiple (watchers, - &keyhash, - &watch_notifier_it, - record); + PEERSTORE_hash_key(record->sub_system, &record->peer, record->key, &keyhash); + GNUNET_CONTAINER_multihashmap_get_multiple(watchers, + &keyhash, + &watch_notifier_it, + record); } @@ -329,20 +329,20 @@ watch_notifier (struct GNUNET_PEERSTORE_Record *record) * @param hm the actual message */ static void -handle_watch_cancel (void *cls, const struct StoreKeyHashMessage *hm) +handle_watch_cancel(void *cls, const struct StoreKeyHashMessage *hm) { struct GNUNET_SERVICE_Client *client = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a watch cancel request.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received a watch cancel request.\n"); if (GNUNET_OK != - GNUNET_CONTAINER_multihashmap_remove (watchers, &hm->keyhash, client)) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (client); - return; - } + GNUNET_CONTAINER_multihashmap_remove(watchers, &hm->keyhash, client)) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(client); + return; + } num_clients++; - GNUNET_SERVICE_client_continue (client); + GNUNET_SERVICE_client_continue(client); } @@ -353,18 +353,18 @@ handle_watch_cancel (void *cls, const struct StoreKeyHashMessage *hm) * @param hm the actual message */ static void -handle_watch (void *cls, const struct StoreKeyHashMessage *hm) +handle_watch(void *cls, const struct StoreKeyHashMessage *hm) { struct GNUNET_SERVICE_Client *client = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received a watch request.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received a watch request.\n"); num_clients--; /* do not count watchers */ - GNUNET_SERVICE_client_mark_monitor (client); - GNUNET_CONTAINER_multihashmap_put (watchers, - &hm->keyhash, - client, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); - GNUNET_SERVICE_client_continue (client); + GNUNET_SERVICE_client_mark_monitor(client); + GNUNET_CONTAINER_multihashmap_put(watchers, + &hm->keyhash, + client, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + GNUNET_SERVICE_client_continue(client); } @@ -376,23 +376,23 @@ handle_watch (void *cls, const struct StoreKeyHashMessage *hm) * @return #GNUNET_OK if @a srm is well-formed */ static int -check_iterate (void *cls, const struct StoreRecordMessage *srm) +check_iterate(void *cls, const struct StoreRecordMessage *srm) { struct GNUNET_PEERSTORE_Record *record; - record = PEERSTORE_parse_record_message (srm); + record = PEERSTORE_parse_record_message(srm); if (NULL == record) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } if (NULL == record->sub_system) - { - GNUNET_break (0); - PEERSTORE_destroy_record (record); - return GNUNET_SYSERR; - } - PEERSTORE_destroy_record (record); + { + GNUNET_break(0); + PEERSTORE_destroy_record(record); + return GNUNET_SYSERR; + } + PEERSTORE_destroy_record(record); return GNUNET_OK; } @@ -404,30 +404,30 @@ check_iterate (void *cls, const struct StoreRecordMessage *srm) * @param srm the actual message */ static void -handle_iterate (void *cls, const struct StoreRecordMessage *srm) +handle_iterate(void *cls, const struct StoreRecordMessage *srm) { struct GNUNET_SERVICE_Client *client = cls; struct GNUNET_PEERSTORE_Record *record; - record = PEERSTORE_parse_record_message (srm); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Iterate request: ss `%s', peer `%s', key `%s'\n", - record->sub_system, - GNUNET_i2s (&record->peer), - (NULL == record->key) ? "NULL" : record->key); + record = PEERSTORE_parse_record_message(srm); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Iterate request: ss `%s', peer `%s', key `%s'\n", + record->sub_system, + GNUNET_i2s(&record->peer), + (NULL == record->key) ? "NULL" : record->key); record->client = client; if (GNUNET_OK != - db->iterate_records (db->cls, - record->sub_system, - (ntohs (srm->peer_set)) ? &record->peer : NULL, - record->key, - &record_iterator, - record)) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (client); - PEERSTORE_destroy_record (record); - } + db->iterate_records(db->cls, + record->sub_system, + (ntohs(srm->peer_set)) ? &record->peer : NULL, + record->key, + &record_iterator, + record)) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(client); + PEERSTORE_destroy_record(record); + } } @@ -438,21 +438,21 @@ handle_iterate (void *cls, const struct StoreRecordMessage *srm) * @param success result */ static void -store_record_continuation (void *cls, int success) +store_record_continuation(void *cls, int success) { struct GNUNET_PEERSTORE_Record *record = cls; if (GNUNET_OK == success) - { - watch_notifier (record); - GNUNET_SERVICE_client_continue (record->client); - } + { + watch_notifier(record); + GNUNET_SERVICE_client_continue(record->client); + } else - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (record->client); - } - PEERSTORE_destroy_record (record); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(record->client); + } + PEERSTORE_destroy_record(record); } @@ -464,23 +464,23 @@ store_record_continuation (void *cls, int success) * @return #GNUNET_OK if @a srm is well-formed */ static int -check_store (void *cls, const struct StoreRecordMessage *srm) +check_store(void *cls, const struct StoreRecordMessage *srm) { struct GNUNET_PEERSTORE_Record *record; - record = PEERSTORE_parse_record_message (srm); + record = PEERSTORE_parse_record_message(srm); if (NULL == record) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } if ((NULL == record->sub_system) || (NULL == record->key)) - { - GNUNET_break (0); - PEERSTORE_destroy_record (record); - return GNUNET_SYSERR; - } - PEERSTORE_destroy_record (record); + { + GNUNET_break(0); + PEERSTORE_destroy_record(record); + return GNUNET_SYSERR; + } + PEERSTORE_destroy_record(record); return GNUNET_OK; } @@ -492,36 +492,36 @@ check_store (void *cls, const struct StoreRecordMessage *srm) * @param srm the actual message */ static void -handle_store (void *cls, const struct StoreRecordMessage *srm) +handle_store(void *cls, const struct StoreRecordMessage *srm) { struct GNUNET_SERVICE_Client *client = cls; struct GNUNET_PEERSTORE_Record *record; - record = PEERSTORE_parse_record_message (srm); - GNUNET_log ( + record = PEERSTORE_parse_record_message(srm); + GNUNET_log( GNUNET_ERROR_TYPE_INFO, "Received a store request. Sub system `%s' Peer `%s Key `%s' Options: %u.\n", record->sub_system, - GNUNET_i2s (&record->peer), + GNUNET_i2s(&record->peer), record->key, - (uint32_t) ntohl (srm->options)); + (uint32_t)ntohl(srm->options)); record->client = client; - if (GNUNET_OK != db->store_record (db->cls, - record->sub_system, - &record->peer, - record->key, - record->value, - record->value_size, - record->expiry, - ntohl (srm->options), - &store_record_continuation, - record)) - { - GNUNET_break (0); - PEERSTORE_destroy_record (record); - GNUNET_SERVICE_client_drop (client); - return; - } + if (GNUNET_OK != db->store_record(db->cls, + record->sub_system, + &record->peer, + record->key, + record->value, + record->value_size, + record->expiry, + ntohl(srm->options), + &store_record_continuation, + record)) + { + GNUNET_break(0); + PEERSTORE_destroy_record(record); + GNUNET_SERVICE_client_drop(client); + return; + } } @@ -533,69 +533,69 @@ handle_store (void *cls, const struct StoreRecordMessage *srm) * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *service) { char *database; in_shutdown = GNUNET_NO; cfg = c; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "peerstore", - "DATABASE", - &database)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "peerstore", - "DATABASE"); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_asprintf (&db_lib_name, "libgnunet_plugin_peerstore_%s", database); - db = GNUNET_PLUGIN_load (db_lib_name, (void *) cfg); - GNUNET_free (database); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "peerstore", + "DATABASE", + &database)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "peerstore", + "DATABASE"); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_asprintf(&db_lib_name, "libgnunet_plugin_peerstore_%s", database); + db = GNUNET_PLUGIN_load(db_lib_name, (void *)cfg); + GNUNET_free(database); if (NULL == db) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ ("Could not load database backend `%s'\n"), - db_lib_name); - GNUNET_SCHEDULER_shutdown (); - return; - } - watchers = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO); - expire_task = GNUNET_SCHEDULER_add_now (&cleanup_expired_records, NULL); - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Could not load database backend `%s'\n"), + db_lib_name); + GNUNET_SCHEDULER_shutdown(); + return; + } + watchers = GNUNET_CONTAINER_multihashmap_create(10, GNUNET_NO); + expire_task = GNUNET_SCHEDULER_add_now(&cleanup_expired_records, NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL); } /** * Define "main" method using service macro. */ -GNUNET_SERVICE_MAIN ( +GNUNET_SERVICE_MAIN( "peerstore", GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN, &run, &client_connect_cb, &client_disconnect_cb, NULL, - GNUNET_MQ_hd_var_size (store, - GNUNET_MESSAGE_TYPE_PEERSTORE_STORE, - struct StoreRecordMessage, - NULL), - GNUNET_MQ_hd_var_size (iterate, - GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE, - struct StoreRecordMessage, - NULL), - GNUNET_MQ_hd_fixed_size (watch, - GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH, - struct StoreKeyHashMessage, - NULL), - GNUNET_MQ_hd_fixed_size (watch_cancel, - GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH_CANCEL, - struct StoreKeyHashMessage, - NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_hd_var_size(store, + GNUNET_MESSAGE_TYPE_PEERSTORE_STORE, + struct StoreRecordMessage, + NULL), + GNUNET_MQ_hd_var_size(iterate, + GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE, + struct StoreRecordMessage, + NULL), + GNUNET_MQ_hd_fixed_size(watch, + GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH, + struct StoreKeyHashMessage, + NULL), + GNUNET_MQ_hd_fixed_size(watch_cancel, + GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH_CANCEL, + struct StoreKeyHashMessage, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-peerstore.c */ diff --git a/src/peerstore/peerstore.h b/src/peerstore/peerstore.h index 15881e6c8..de5e5908d 100644 --- a/src/peerstore/peerstore.h +++ b/src/peerstore/peerstore.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -33,9 +33,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Message carrying a PEERSTORE record message */ -struct StoreRecordMessage -{ - +struct StoreRecordMessage { /** * GNUnet message header */ @@ -81,16 +79,13 @@ struct StoreRecordMessage uint32_t /* enum GNUNET_PEERSTORE_StoreOption */ options GNUNET_PACKED; /* Followed by key and value */ - }; /** * Message carrying record key hash */ -struct StoreKeyHashMessage -{ - +struct StoreKeyHashMessage { /** * GNUnet message header */ @@ -105,7 +100,6 @@ struct StoreKeyHashMessage * Hash of a record key */ struct GNUNET_HashCode keyhash; - }; GNUNET_NETWORK_STRUCT_END diff --git a/src/peerstore/peerstore_api.c b/src/peerstore/peerstore_api.c index 64bc3ae72..3ce2c5533 100644 --- a/src/peerstore/peerstore_api.c +++ b/src/peerstore/peerstore_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerstore/peerstore_api.c * @brief API for peerstore @@ -28,7 +28,7 @@ #include "peerstore.h" #include "peerstore_common.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "peerstore-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "peerstore-api", __VA_ARGS__) /******************************************************************************/ /************************ DATA STRUCTURES ****************************/ @@ -37,9 +37,7 @@ /** * Handle to the PEERSTORE service. */ -struct GNUNET_PEERSTORE_Handle -{ - +struct GNUNET_PEERSTORE_Handle { /** * Our configuration. */ @@ -94,8 +92,7 @@ struct GNUNET_PEERSTORE_Handle /** * Context for a store request */ -struct GNUNET_PEERSTORE_StoreContext -{ +struct GNUNET_PEERSTORE_StoreContext { /** * Kept in a DLL. */ @@ -160,8 +157,7 @@ struct GNUNET_PEERSTORE_StoreContext /** * Context for a iterate request */ -struct GNUNET_PEERSTORE_IterateContext -{ +struct GNUNET_PEERSTORE_IterateContext { /** * Kept in a DLL. */ @@ -211,8 +207,7 @@ struct GNUNET_PEERSTORE_IterateContext /** * Context for a watch request */ -struct GNUNET_PEERSTORE_WatchContext -{ +struct GNUNET_PEERSTORE_WatchContext { /** * Kept in a DLL. */ @@ -254,7 +249,7 @@ struct GNUNET_PEERSTORE_WatchContext * @param cls a `struct GNUNET_PEERSTORE_Handle *h` */ static void -reconnect (void *cls); +reconnect(void *cls); /** @@ -263,32 +258,32 @@ reconnect (void *cls); * @param h peerstore handle to disconnect */ static void -disconnect (struct GNUNET_PEERSTORE_Handle *h) +disconnect(struct GNUNET_PEERSTORE_Handle *h) { struct GNUNET_PEERSTORE_IterateContext *next; for (struct GNUNET_PEERSTORE_IterateContext *ic = h->iterate_head; NULL != ic; ic = next) - { - next = ic->next; - if (GNUNET_YES == ic->iterating) { - GNUNET_PEERSTORE_Processor icb; - void *icb_cls; - - icb = ic->callback; - icb_cls = ic->callback_cls; - GNUNET_PEERSTORE_iterate_cancel (ic); - if (NULL != icb) - icb (icb_cls, NULL, "Iteration canceled due to reconnection"); + next = ic->next; + if (GNUNET_YES == ic->iterating) + { + GNUNET_PEERSTORE_Processor icb; + void *icb_cls; + + icb = ic->callback; + icb_cls = ic->callback_cls; + GNUNET_PEERSTORE_iterate_cancel(ic); + if (NULL != icb) + icb(icb_cls, NULL, "Iteration canceled due to reconnection"); + } } - } if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } } @@ -299,16 +294,16 @@ disconnect (struct GNUNET_PEERSTORE_Handle *h) * @param h peerstore to reconnect */ static void -disconnect_and_schedule_reconnect (struct GNUNET_PEERSTORE_Handle *h) +disconnect_and_schedule_reconnect(struct GNUNET_PEERSTORE_Handle *h) { - GNUNET_assert (NULL == h->reconnect_task); - disconnect (h); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Scheduling task to reconnect to PEERSTORE service in %s.\n", - GNUNET_STRINGS_relative_time_to_string (h->reconnect_delay, GNUNET_YES)); + GNUNET_assert(NULL == h->reconnect_task); + disconnect(h); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Scheduling task to reconnect to PEERSTORE service in %s.\n", + GNUNET_STRINGS_relative_time_to_string(h->reconnect_delay, GNUNET_YES)); h->reconnect_task = - GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, &reconnect, h); - h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay); + GNUNET_SCHEDULER_add_delayed(h->reconnect_delay, &reconnect, h); + h->reconnect_delay = GNUNET_TIME_STD_BACKOFF(h->reconnect_delay); } @@ -318,7 +313,7 @@ disconnect_and_schedule_reconnect (struct GNUNET_PEERSTORE_Handle *h) * @param cls a `struct GNUNET_PEERSTORE_StoreContext *` */ static void -store_request_sent (void *cls) +store_request_sent(void *cls) { struct GNUNET_PEERSTORE_StoreContext *sc = cls; GNUNET_PEERSTORE_Continuation cont; @@ -326,9 +321,9 @@ store_request_sent (void *cls) cont = sc->cont; cont_cls = sc->cont_cls; - GNUNET_PEERSTORE_store_cancel (sc); + GNUNET_PEERSTORE_store_cancel(sc); if (NULL != cont) - cont (cont_cls, GNUNET_OK); + cont(cont_cls, GNUNET_OK); } @@ -341,14 +336,14 @@ store_request_sent (void *cls) * Function called when we had trouble talking to the service. */ static void -handle_client_error (void *cls, enum GNUNET_MQ_Error error) +handle_client_error(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_PEERSTORE_Handle *h = cls; - LOG (GNUNET_ERROR_TYPE_ERROR, - "Received an error notification from MQ of type: %d\n", - error); - disconnect_and_schedule_reconnect (h); + LOG(GNUNET_ERROR_TYPE_ERROR, + "Received an error notification from MQ of type: %d\n", + error); + disconnect_and_schedule_reconnect(h); } @@ -361,16 +356,16 @@ handle_client_error (void *cls, enum GNUNET_MQ_Error error) * @return #GNUNET_YES (continue to iterate) */ static int -rewatch_it (void *cls, const struct GNUNET_HashCode *key, void *value) +rewatch_it(void *cls, const struct GNUNET_HashCode *key, void *value) { struct GNUNET_PEERSTORE_Handle *h = cls; struct GNUNET_PEERSTORE_WatchContext *wc = value; struct StoreKeyHashMessage *hm; struct GNUNET_MQ_Envelope *ev; - ev = GNUNET_MQ_msg (hm, GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH); + ev = GNUNET_MQ_msg(hm, GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH); hm->keyhash = wc->keyhash; - GNUNET_MQ_send (h->mq, ev); + GNUNET_MQ_send(h->mq, ev); return GNUNET_YES; } @@ -384,11 +379,11 @@ rewatch_it (void *cls, const struct GNUNET_HashCode *key, void *value) * @return #GNUNET_YES to continue iteration */ static int -destroy_watch (void *cls, const struct GNUNET_HashCode *key, void *value) +destroy_watch(void *cls, const struct GNUNET_HashCode *key, void *value) { struct GNUNET_PEERSTORE_WatchContext *wc = value; - GNUNET_PEERSTORE_watch_cancel (wc); + GNUNET_PEERSTORE_watch_cancel(wc); return GNUNET_YES; } @@ -401,14 +396,14 @@ destroy_watch (void *cls, const struct GNUNET_HashCode *key, void *value) * @param h Handle to the service. */ static void -final_disconnect (struct GNUNET_PEERSTORE_Handle *h) +final_disconnect(struct GNUNET_PEERSTORE_Handle *h) { if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } - GNUNET_free (h); + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } + GNUNET_free(h); } @@ -419,19 +414,19 @@ final_disconnect (struct GNUNET_PEERSTORE_Handle *h) * @return NULL on error */ struct GNUNET_PEERSTORE_Handle * -GNUNET_PEERSTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_PEERSTORE_connect(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_PEERSTORE_Handle *h; - h = GNUNET_new (struct GNUNET_PEERSTORE_Handle); + h = GNUNET_new(struct GNUNET_PEERSTORE_Handle); h->cfg = cfg; h->disconnecting = GNUNET_NO; - reconnect (h); + reconnect(h); if (NULL == h->mq) - { - GNUNET_free (h); - return NULL; - } + { + GNUNET_free(h); + return NULL; + } return h; } @@ -445,36 +440,36 @@ GNUNET_PEERSTORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) * @param sync_first send any pending STORE requests before disconnecting */ void -GNUNET_PEERSTORE_disconnect (struct GNUNET_PEERSTORE_Handle *h, int sync_first) +GNUNET_PEERSTORE_disconnect(struct GNUNET_PEERSTORE_Handle *h, int sync_first) { struct GNUNET_PEERSTORE_IterateContext *ic; struct GNUNET_PEERSTORE_StoreContext *sc; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Disconnecting.\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Disconnecting.\n"); if (NULL != h->watches) - { - GNUNET_CONTAINER_multihashmap_iterate (h->watches, &destroy_watch, NULL); - GNUNET_CONTAINER_multihashmap_destroy (h->watches); - h->watches = NULL; - } + { + GNUNET_CONTAINER_multihashmap_iterate(h->watches, &destroy_watch, NULL); + GNUNET_CONTAINER_multihashmap_destroy(h->watches); + h->watches = NULL; + } while (NULL != (ic = h->iterate_head)) - { - GNUNET_break (0); - GNUNET_PEERSTORE_iterate_cancel (ic); - } + { + GNUNET_break(0); + GNUNET_PEERSTORE_iterate_cancel(ic); + } if (NULL != h->store_head) - { - if (GNUNET_YES == sync_first) { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Delaying disconnection due to pending store requests.\n"); - h->disconnecting = GNUNET_YES; - return; + if (GNUNET_YES == sync_first) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Delaying disconnection due to pending store requests.\n"); + h->disconnecting = GNUNET_YES; + return; + } + while (NULL != (sc = h->store_head)) + GNUNET_PEERSTORE_store_cancel(sc); } - while (NULL != (sc = h->store_head)) - GNUNET_PEERSTORE_store_cancel (sc); - } - final_disconnect (h); + final_disconnect(h); } @@ -489,17 +484,17 @@ GNUNET_PEERSTORE_disconnect (struct GNUNET_PEERSTORE_Handle *h, int sync_first) * @param sc Store request context */ void -GNUNET_PEERSTORE_store_cancel (struct GNUNET_PEERSTORE_StoreContext *sc) +GNUNET_PEERSTORE_store_cancel(struct GNUNET_PEERSTORE_StoreContext *sc) { struct GNUNET_PEERSTORE_Handle *h = sc->h; - GNUNET_CONTAINER_DLL_remove (sc->h->store_head, sc->h->store_tail, sc); - GNUNET_free (sc->sub_system); - GNUNET_free (sc->value); - GNUNET_free (sc->key); - GNUNET_free (sc); + GNUNET_CONTAINER_DLL_remove(sc->h->store_head, sc->h->store_tail, sc); + GNUNET_free(sc->sub_system); + GNUNET_free(sc->value); + GNUNET_free(sc->key); + GNUNET_free(sc); if ((GNUNET_YES == h->disconnecting) && (NULL == h->store_head)) - final_disconnect (h); + final_disconnect(h); } @@ -520,41 +515,41 @@ GNUNET_PEERSTORE_store_cancel (struct GNUNET_PEERSTORE_StoreContext *sc) * @param cont_cls Closure for @a cont */ struct GNUNET_PEERSTORE_StoreContext * -GNUNET_PEERSTORE_store (struct GNUNET_PEERSTORE_Handle *h, - const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - const void *value, - size_t size, - struct GNUNET_TIME_Absolute expiry, - enum GNUNET_PEERSTORE_StoreOption options, - GNUNET_PEERSTORE_Continuation cont, - void *cont_cls) +GNUNET_PEERSTORE_store(struct GNUNET_PEERSTORE_Handle *h, + const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + const void *value, + size_t size, + struct GNUNET_TIME_Absolute expiry, + enum GNUNET_PEERSTORE_StoreOption options, + GNUNET_PEERSTORE_Continuation cont, + void *cont_cls) { struct GNUNET_MQ_Envelope *ev; struct GNUNET_PEERSTORE_StoreContext *sc; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Storing value (size: %lu) for subsytem `%s', peer `%s', key `%s'\n", - size, - sub_system, - GNUNET_i2s (peer), - key); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Storing value (size: %lu) for subsytem `%s', peer `%s', key `%s'\n", + size, + sub_system, + GNUNET_i2s(peer), + key); ev = - PEERSTORE_create_record_mq_envelope (sub_system, - peer, - key, - value, - size, - expiry, - options, - GNUNET_MESSAGE_TYPE_PEERSTORE_STORE); - sc = GNUNET_new (struct GNUNET_PEERSTORE_StoreContext); - - sc->sub_system = GNUNET_strdup (sub_system); + PEERSTORE_create_record_mq_envelope(sub_system, + peer, + key, + value, + size, + expiry, + options, + GNUNET_MESSAGE_TYPE_PEERSTORE_STORE); + sc = GNUNET_new(struct GNUNET_PEERSTORE_StoreContext); + + sc->sub_system = GNUNET_strdup(sub_system); sc->peer = *peer; - sc->key = GNUNET_strdup (key); - sc->value = GNUNET_memdup (value, size); + sc->key = GNUNET_strdup(key); + sc->value = GNUNET_memdup(value, size); sc->size = size; sc->expiry = expiry; sc->options = options; @@ -562,9 +557,9 @@ GNUNET_PEERSTORE_store (struct GNUNET_PEERSTORE_Handle *h, sc->cont_cls = cont_cls; sc->h = h; - GNUNET_CONTAINER_DLL_insert_tail (h->store_head, h->store_tail, sc); - GNUNET_MQ_notify_sent (ev, &store_request_sent, sc); - GNUNET_MQ_send (h->mq, ev); + GNUNET_CONTAINER_DLL_insert_tail(h->store_head, h->store_tail, sc); + GNUNET_MQ_notify_sent(ev, &store_request_sent, sc); + GNUNET_MQ_send(h->mq, ev); return sc; } @@ -581,7 +576,7 @@ GNUNET_PEERSTORE_store (struct GNUNET_PEERSTORE_Handle *h, * @param msg message received */ static void -handle_iterate_end (void *cls, const struct GNUNET_MessageHeader *msg) +handle_iterate_end(void *cls, const struct GNUNET_MessageHeader *msg) { struct GNUNET_PEERSTORE_Handle *h = cls; struct GNUNET_PEERSTORE_IterateContext *ic; @@ -590,18 +585,18 @@ handle_iterate_end (void *cls, const struct GNUNET_MessageHeader *msg) ic = h->iterate_head; if (NULL == ic) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _ ("Unexpected iteration response, this should not happen.\n")); - disconnect_and_schedule_reconnect (h); - return; - } + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Unexpected iteration response, this should not happen.\n")); + disconnect_and_schedule_reconnect(h); + return; + } callback = ic->callback; callback_cls = ic->callback_cls; ic->iterating = GNUNET_NO; - GNUNET_PEERSTORE_iterate_cancel (ic); + GNUNET_PEERSTORE_iterate_cancel(ic); if (NULL != callback) - callback (callback_cls, NULL, NULL); + callback(callback_cls, NULL, NULL); h->reconnect_delay = GNUNET_TIME_UNIT_ZERO; } @@ -614,7 +609,7 @@ handle_iterate_end (void *cls, const struct GNUNET_MessageHeader *msg) * @param msg message received */ static int -check_iterate_result (void *cls, const struct StoreRecordMessage *msg) +check_iterate_result(void *cls, const struct StoreRecordMessage *msg) { /* we defer validation to #handle_iterate_result */ return GNUNET_OK; @@ -628,7 +623,7 @@ check_iterate_result (void *cls, const struct StoreRecordMessage *msg) * @param msg message received */ static void -handle_iterate_result (void *cls, const struct StoreRecordMessage *msg) +handle_iterate_result(void *cls, const struct StoreRecordMessage *msg) { struct GNUNET_PEERSTORE_Handle *h = cls; struct GNUNET_PEERSTORE_IterateContext *ic; @@ -638,29 +633,29 @@ handle_iterate_result (void *cls, const struct StoreRecordMessage *msg) ic = h->iterate_head; if (NULL == ic) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _ ("Unexpected iteration response, this should not happen.\n")); - disconnect_and_schedule_reconnect (h); - return; - } + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Unexpected iteration response, this should not happen.\n")); + disconnect_and_schedule_reconnect(h); + return; + } ic->iterating = GNUNET_YES; callback = ic->callback; callback_cls = ic->callback_cls; if (NULL == callback) return; - record = PEERSTORE_parse_record_message (msg); + record = PEERSTORE_parse_record_message(msg); if (NULL == record) - { - callback (callback_cls, - NULL, - _ ("Received a malformed response from service.")); - } + { + callback(callback_cls, + NULL, + _("Received a malformed response from service.")); + } else - { - callback (callback_cls, record, NULL); - PEERSTORE_destroy_record (record); - } + { + callback(callback_cls, record, NULL); + PEERSTORE_destroy_record(record); + } } @@ -671,15 +666,15 @@ handle_iterate_result (void *cls, const struct StoreRecordMessage *msg) * @param ic Iterate request context as returned by GNUNET_PEERSTORE_iterate() */ void -GNUNET_PEERSTORE_iterate_cancel (struct GNUNET_PEERSTORE_IterateContext *ic) +GNUNET_PEERSTORE_iterate_cancel(struct GNUNET_PEERSTORE_IterateContext *ic) { if (GNUNET_NO == ic->iterating) - { - GNUNET_CONTAINER_DLL_remove (ic->h->iterate_head, ic->h->iterate_tail, ic); - GNUNET_free (ic->sub_system); - GNUNET_free_non_null (ic->key); - GNUNET_free (ic); - } + { + GNUNET_CONTAINER_DLL_remove(ic->h->iterate_head, ic->h->iterate_tail, ic); + GNUNET_free(ic->sub_system); + GNUNET_free_non_null(ic->key); + GNUNET_free(ic); + } else ic->callback = NULL; } @@ -697,39 +692,39 @@ GNUNET_PEERSTORE_iterate_cancel (struct GNUNET_PEERSTORE_IterateContext *ic) * @return Handle to iteration request */ struct GNUNET_PEERSTORE_IterateContext * -GNUNET_PEERSTORE_iterate (struct GNUNET_PEERSTORE_Handle *h, - const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - GNUNET_PEERSTORE_Processor callback, - void *callback_cls) +GNUNET_PEERSTORE_iterate(struct GNUNET_PEERSTORE_Handle *h, + const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + GNUNET_PEERSTORE_Processor callback, + void *callback_cls) { struct GNUNET_MQ_Envelope *ev; struct GNUNET_PEERSTORE_IterateContext *ic; ev = - PEERSTORE_create_record_mq_envelope (sub_system, - peer, - key, - NULL, - 0, - GNUNET_TIME_UNIT_FOREVER_ABS, - 0, - GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE); - ic = GNUNET_new (struct GNUNET_PEERSTORE_IterateContext); + PEERSTORE_create_record_mq_envelope(sub_system, + peer, + key, + NULL, + 0, + GNUNET_TIME_UNIT_FOREVER_ABS, + 0, + GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE); + ic = GNUNET_new(struct GNUNET_PEERSTORE_IterateContext); ic->callback = callback; ic->callback_cls = callback_cls; ic->h = h; - ic->sub_system = GNUNET_strdup (sub_system); + ic->sub_system = GNUNET_strdup(sub_system); if (NULL != peer) ic->peer = *peer; if (NULL != key) - ic->key = GNUNET_strdup (key); - GNUNET_CONTAINER_DLL_insert_tail (h->iterate_head, h->iterate_tail, ic); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending an iterate request for sub system `%s'\n", - sub_system); - GNUNET_MQ_send (h->mq, ev); + ic->key = GNUNET_strdup(key); + GNUNET_CONTAINER_DLL_insert_tail(h->iterate_head, h->iterate_tail, ic); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending an iterate request for sub system `%s'\n", + sub_system); + GNUNET_MQ_send(h->mq, ev); return ic; } @@ -745,7 +740,7 @@ GNUNET_PEERSTORE_iterate (struct GNUNET_PEERSTORE_Handle *h, * @param msg message received */ static int -check_watch_record (void *cls, const struct StoreRecordMessage *msg) +check_watch_record(void *cls, const struct StoreRecordMessage *msg) { /* we defer validation to #handle_watch_result */ return GNUNET_OK; @@ -759,35 +754,35 @@ check_watch_record (void *cls, const struct StoreRecordMessage *msg) * @param msg message received */ static void -handle_watch_record (void *cls, const struct StoreRecordMessage *msg) +handle_watch_record(void *cls, const struct StoreRecordMessage *msg) { struct GNUNET_PEERSTORE_Handle *h = cls; struct GNUNET_PEERSTORE_Record *record; struct GNUNET_HashCode keyhash; struct GNUNET_PEERSTORE_WatchContext *wc; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Received a watch record from service.\n"); - record = PEERSTORE_parse_record_message (msg); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Received a watch record from service.\n"); + record = PEERSTORE_parse_record_message(msg); if (NULL == record) - { - disconnect_and_schedule_reconnect (h); - return; - } - PEERSTORE_hash_key (record->sub_system, &record->peer, record->key, &keyhash); + { + disconnect_and_schedule_reconnect(h); + return; + } + PEERSTORE_hash_key(record->sub_system, &record->peer, record->key, &keyhash); // FIXME: what if there are multiple watches for the same key? - wc = GNUNET_CONTAINER_multihashmap_get (h->watches, &keyhash); + wc = GNUNET_CONTAINER_multihashmap_get(h->watches, &keyhash); if (NULL == wc) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _ ("Received a watch result for a non existing watch.\n")); - PEERSTORE_destroy_record (record); - disconnect_and_schedule_reconnect (h); - return; - } + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Received a watch result for a non existing watch.\n")); + PEERSTORE_destroy_record(record); + disconnect_and_schedule_reconnect(h); + return; + } if (NULL != wc->callback) - wc->callback (wc->callback_cls, record, NULL); + wc->callback(wc->callback_cls, record, NULL); h->reconnect_delay = GNUNET_TIME_UNIT_ZERO; - PEERSTORE_destroy_record (record); + PEERSTORE_destroy_record(record); } @@ -797,67 +792,67 @@ handle_watch_record (void *cls, const struct StoreRecordMessage *msg) * @param cls a `struct GNUNET_PEERSTORE_Handle *` */ static void -reconnect (void *cls) +reconnect(void *cls) { struct GNUNET_PEERSTORE_Handle *h = cls; struct GNUNET_MQ_MessageHandler mq_handlers[] = - {GNUNET_MQ_hd_fixed_size (iterate_end, - GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE_END, - struct GNUNET_MessageHeader, - h), - GNUNET_MQ_hd_var_size (iterate_result, - GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE_RECORD, - struct StoreRecordMessage, + { GNUNET_MQ_hd_fixed_size(iterate_end, + GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE_END, + struct GNUNET_MessageHeader, h), - GNUNET_MQ_hd_var_size (watch_record, - GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH_RECORD, - struct StoreRecordMessage, - h), - GNUNET_MQ_handler_end ()}; + GNUNET_MQ_hd_var_size(iterate_result, + GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE_RECORD, + struct StoreRecordMessage, + h), + GNUNET_MQ_hd_var_size(watch_record, + GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH_RECORD, + struct StoreRecordMessage, + h), + GNUNET_MQ_handler_end() }; struct GNUNET_MQ_Envelope *ev; h->reconnect_task = NULL; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Reconnecting...\n"); - h->mq = GNUNET_CLIENT_connect (h->cfg, - "peerstore", - mq_handlers, - &handle_client_error, - h); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Reconnecting...\n"); + h->mq = GNUNET_CLIENT_connect(h->cfg, + "peerstore", + mq_handlers, + &handle_client_error, + h); if (NULL == h->mq) return; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Resending pending requests after reconnect.\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Resending pending requests after reconnect.\n"); if (NULL != h->watches) - GNUNET_CONTAINER_multihashmap_iterate (h->watches, &rewatch_it, h); + GNUNET_CONTAINER_multihashmap_iterate(h->watches, &rewatch_it, h); for (struct GNUNET_PEERSTORE_IterateContext *ic = h->iterate_head; NULL != ic; ic = ic->next) - { - ev = - PEERSTORE_create_record_mq_envelope (ic->sub_system, - &ic->peer, - ic->key, - NULL, - 0, - GNUNET_TIME_UNIT_FOREVER_ABS, - 0, - GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE); - GNUNET_MQ_send (h->mq, ev); - } + { + ev = + PEERSTORE_create_record_mq_envelope(ic->sub_system, + &ic->peer, + ic->key, + NULL, + 0, + GNUNET_TIME_UNIT_FOREVER_ABS, + 0, + GNUNET_MESSAGE_TYPE_PEERSTORE_ITERATE); + GNUNET_MQ_send(h->mq, ev); + } for (struct GNUNET_PEERSTORE_StoreContext *sc = h->store_head; NULL != sc; sc = sc->next) - { - ev = - PEERSTORE_create_record_mq_envelope (sc->sub_system, - &sc->peer, - sc->key, - sc->value, - sc->size, - sc->expiry, - sc->options, - GNUNET_MESSAGE_TYPE_PEERSTORE_STORE); - GNUNET_MQ_notify_sent (ev, &store_request_sent, sc); - GNUNET_MQ_send (h->mq, ev); - } + { + ev = + PEERSTORE_create_record_mq_envelope(sc->sub_system, + &sc->peer, + sc->key, + sc->value, + sc->size, + sc->expiry, + sc->options, + GNUNET_MESSAGE_TYPE_PEERSTORE_STORE); + GNUNET_MQ_notify_sent(ev, &store_request_sent, sc); + GNUNET_MQ_send(h->mq, ev); + } } @@ -867,20 +862,20 @@ reconnect (void *cls) * @param wc handle to the watch request */ void -GNUNET_PEERSTORE_watch_cancel (struct GNUNET_PEERSTORE_WatchContext *wc) +GNUNET_PEERSTORE_watch_cancel(struct GNUNET_PEERSTORE_WatchContext *wc) { struct GNUNET_PEERSTORE_Handle *h = wc->h; struct GNUNET_MQ_Envelope *ev; struct StoreKeyHashMessage *hm; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Canceling watch.\n"); - ev = GNUNET_MQ_msg (hm, GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH_CANCEL); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Canceling watch.\n"); + ev = GNUNET_MQ_msg(hm, GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH_CANCEL); hm->keyhash = wc->keyhash; - GNUNET_MQ_send (h->mq, ev); - GNUNET_assert ( + GNUNET_MQ_send(h->mq, ev); + GNUNET_assert( GNUNET_YES == - GNUNET_CONTAINER_multihashmap_remove (h->watches, &wc->keyhash, wc)); - GNUNET_free (wc); + GNUNET_CONTAINER_multihashmap_remove(h->watches, &wc->keyhash, wc)); + GNUNET_free(wc); } @@ -897,37 +892,37 @@ GNUNET_PEERSTORE_watch_cancel (struct GNUNET_PEERSTORE_WatchContext *wc) * @return Handle to watch request */ struct GNUNET_PEERSTORE_WatchContext * -GNUNET_PEERSTORE_watch (struct GNUNET_PEERSTORE_Handle *h, - const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - GNUNET_PEERSTORE_Processor callback, - void *callback_cls) +GNUNET_PEERSTORE_watch(struct GNUNET_PEERSTORE_Handle *h, + const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + GNUNET_PEERSTORE_Processor callback, + void *callback_cls) { struct GNUNET_MQ_Envelope *ev; struct StoreKeyHashMessage *hm; struct GNUNET_PEERSTORE_WatchContext *wc; - ev = GNUNET_MQ_msg (hm, GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH); - PEERSTORE_hash_key (sub_system, peer, key, &hm->keyhash); - wc = GNUNET_new (struct GNUNET_PEERSTORE_WatchContext); + ev = GNUNET_MQ_msg(hm, GNUNET_MESSAGE_TYPE_PEERSTORE_WATCH); + PEERSTORE_hash_key(sub_system, peer, key, &hm->keyhash); + wc = GNUNET_new(struct GNUNET_PEERSTORE_WatchContext); wc->callback = callback; wc->callback_cls = callback_cls; wc->h = h; wc->keyhash = hm->keyhash; if (NULL == h->watches) - h->watches = GNUNET_CONTAINER_multihashmap_create (5, GNUNET_NO); - GNUNET_assert (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put ( - h->watches, - &wc->keyhash, - wc, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sending a watch request for subsystem `%s', peer `%s', key `%s'.\n", - sub_system, - GNUNET_i2s (peer), - key); - GNUNET_MQ_send (h->mq, ev); + h->watches = GNUNET_CONTAINER_multihashmap_create(5, GNUNET_NO); + GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put( + h->watches, + &wc->keyhash, + wc, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sending a watch request for subsystem `%s', peer `%s', key `%s'.\n", + sub_system, + GNUNET_i2s(peer), + key); + GNUNET_MQ_send(h->mq, ev); return wc; } diff --git a/src/peerstore/peerstore_common.c b/src/peerstore/peerstore_common.c index 0e2cc0514..7fceb1ec0 100644 --- a/src/peerstore/peerstore_common.c +++ b/src/peerstore/peerstore_common.c @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -30,10 +30,10 @@ * */ void -PEERSTORE_hash_key (const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - struct GNUNET_HashCode *ret) +PEERSTORE_hash_key(const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + struct GNUNET_HashCode *ret) { size_t sssize; size_t psize; @@ -42,19 +42,19 @@ PEERSTORE_hash_key (const char *sub_system, void *block; void *blockptr; - sssize = strlen (sub_system) + 1; - psize = sizeof (struct GNUNET_PeerIdentity); - ksize = strlen (key) + 1; + sssize = strlen(sub_system) + 1; + psize = sizeof(struct GNUNET_PeerIdentity); + ksize = strlen(key) + 1; totalsize = sssize + psize + ksize; - block = GNUNET_malloc (totalsize); + block = GNUNET_malloc(totalsize); blockptr = block; - GNUNET_memcpy (blockptr, sub_system, sssize); + GNUNET_memcpy(blockptr, sub_system, sssize); blockptr += sssize; - GNUNET_memcpy (blockptr, peer, psize); + GNUNET_memcpy(blockptr, peer, psize); blockptr += psize; - GNUNET_memcpy (blockptr, key, ksize); - GNUNET_CRYPTO_hash (block, totalsize, ret); - GNUNET_free (block); + GNUNET_memcpy(blockptr, key, ksize); + GNUNET_CRYPTO_hash(block, totalsize, ret); + GNUNET_free(block); } @@ -72,14 +72,14 @@ PEERSTORE_hash_key (const char *sub_system, * @return pointer to record message struct */ struct GNUNET_MQ_Envelope * -PEERSTORE_create_record_mq_envelope (const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - const void *value, - size_t value_size, - struct GNUNET_TIME_Absolute expiry, - enum GNUNET_PEERSTORE_StoreOption options, - uint16_t msg_type) +PEERSTORE_create_record_mq_envelope(const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + const void *value, + size_t value_size, + struct GNUNET_TIME_Absolute expiry, + enum GNUNET_PEERSTORE_StoreOption options, + uint16_t msg_type) { struct StoreRecordMessage *srm; struct GNUNET_MQ_Envelope *ev; @@ -88,32 +88,32 @@ PEERSTORE_create_record_mq_envelope (const char *sub_system, size_t msg_size; void *dummy; - GNUNET_assert (NULL != sub_system); - ss_size = strlen (sub_system) + 1; + GNUNET_assert(NULL != sub_system); + ss_size = strlen(sub_system) + 1; if (NULL == key) key_size = 0; else - key_size = strlen (key) + 1; + key_size = strlen(key) + 1; msg_size = ss_size + key_size + value_size; - ev = GNUNET_MQ_msg_extra (srm, msg_size, msg_type); - srm->key_size = htons (key_size); - srm->expiry = GNUNET_TIME_absolute_hton (expiry); + ev = GNUNET_MQ_msg_extra(srm, msg_size, msg_type); + srm->key_size = htons(key_size); + srm->expiry = GNUNET_TIME_absolute_hton(expiry); if (NULL == peer) - srm->peer_set = htons (GNUNET_NO); + srm->peer_set = htons(GNUNET_NO); else - { - srm->peer_set = htons (GNUNET_YES); - srm->peer = *peer; - } - srm->sub_system_size = htons (ss_size); - srm->value_size = htons (value_size); - srm->options = htonl (options); + { + srm->peer_set = htons(GNUNET_YES); + srm->peer = *peer; + } + srm->sub_system_size = htons(ss_size); + srm->value_size = htons(value_size); + srm->options = htonl(options); dummy = &srm[1]; - GNUNET_memcpy (dummy, sub_system, ss_size); + GNUNET_memcpy(dummy, sub_system, ss_size); dummy += ss_size; - GNUNET_memcpy (dummy, key, key_size); + GNUNET_memcpy(dummy, key, key_size); dummy += key_size; - GNUNET_memcpy (dummy, value, value_size); + GNUNET_memcpy(dummy, value, value_size); return ev; } @@ -125,7 +125,7 @@ PEERSTORE_create_record_mq_envelope (const char *sub_system, * @return Pointer to record or NULL if error */ struct GNUNET_PEERSTORE_Record * -PEERSTORE_parse_record_message (const struct StoreRecordMessage *srm) +PEERSTORE_parse_record_message(const struct StoreRecordMessage *srm) { struct GNUNET_PEERSTORE_Record *record; uint16_t req_size; @@ -134,39 +134,39 @@ PEERSTORE_parse_record_message (const struct StoreRecordMessage *srm) uint16_t value_size; char *dummy; - req_size = ntohs (srm->header.size) - sizeof (*srm); - ss_size = ntohs (srm->sub_system_size); - key_size = ntohs (srm->key_size); - value_size = ntohs (srm->value_size); + req_size = ntohs(srm->header.size) - sizeof(*srm); + ss_size = ntohs(srm->sub_system_size); + key_size = ntohs(srm->key_size); + value_size = ntohs(srm->value_size); if (ss_size + key_size + value_size != req_size) - { - GNUNET_break (0); - return NULL; - } - record = GNUNET_new (struct GNUNET_PEERSTORE_Record); - if (GNUNET_YES == ntohs (srm->peer_set)) - { - record->peer = srm->peer; - } - record->expiry = GNUNET_TIME_absolute_ntoh (srm->expiry); - dummy = (char *) &srm[1]; + { + GNUNET_break(0); + return NULL; + } + record = GNUNET_new(struct GNUNET_PEERSTORE_Record); + if (GNUNET_YES == ntohs(srm->peer_set)) + { + record->peer = srm->peer; + } + record->expiry = GNUNET_TIME_absolute_ntoh(srm->expiry); + dummy = (char *)&srm[1]; if (ss_size > 0) - { - record->sub_system = GNUNET_strdup (dummy); - dummy += ss_size; - } + { + record->sub_system = GNUNET_strdup(dummy); + dummy += ss_size; + } if (key_size > 0) - { - record->key = GNUNET_strdup (dummy); - dummy += key_size; - } + { + record->key = GNUNET_strdup(dummy); + dummy += key_size; + } if (value_size > 0) - { - record->value = GNUNET_malloc (value_size); - GNUNET_memcpy (record->value, - dummy, - value_size); - } + { + record->value = GNUNET_malloc(value_size); + GNUNET_memcpy(record->value, + dummy, + value_size); + } record->value_size = value_size; return record; } @@ -178,16 +178,16 @@ PEERSTORE_parse_record_message (const struct StoreRecordMessage *srm) * @param record */ void -PEERSTORE_destroy_record (struct GNUNET_PEERSTORE_Record *record) +PEERSTORE_destroy_record(struct GNUNET_PEERSTORE_Record *record) { if (NULL != record->sub_system) - GNUNET_free (record->sub_system); + GNUNET_free(record->sub_system); if (NULL != record->key) - GNUNET_free (record->key); + GNUNET_free(record->key); if (NULL != record->value) - { - GNUNET_free (record->value); - record->value = 0; - } - GNUNET_free (record); + { + GNUNET_free(record->value); + record->value = 0; + } + GNUNET_free(record); } diff --git a/src/peerstore/peerstore_common.h b/src/peerstore/peerstore_common.h index 1e3f228b8..6379f61a6 100644 --- a/src/peerstore/peerstore_common.h +++ b/src/peerstore/peerstore_common.h @@ -11,7 +11,7 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . @@ -31,10 +31,10 @@ * */ void -PEERSTORE_hash_key (const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - struct GNUNET_HashCode *ret); +PEERSTORE_hash_key(const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + struct GNUNET_HashCode *ret); /** @@ -51,14 +51,14 @@ PEERSTORE_hash_key (const char *sub_system, * @return pointer to record message struct */ struct GNUNET_MQ_Envelope * -PEERSTORE_create_record_mq_envelope (const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - const void *value, - size_t value_size, - struct GNUNET_TIME_Absolute expiry, - enum GNUNET_PEERSTORE_StoreOption options, - uint16_t msg_type); +PEERSTORE_create_record_mq_envelope(const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + const void *value, + size_t value_size, + struct GNUNET_TIME_Absolute expiry, + enum GNUNET_PEERSTORE_StoreOption options, + uint16_t msg_type); /** @@ -68,7 +68,7 @@ PEERSTORE_create_record_mq_envelope (const char *sub_system, * @return Pointer to record or NULL on error */ struct GNUNET_PEERSTORE_Record * -PEERSTORE_parse_record_message (const struct StoreRecordMessage *srm); +PEERSTORE_parse_record_message(const struct StoreRecordMessage *srm); /** @@ -77,6 +77,6 @@ PEERSTORE_parse_record_message (const struct StoreRecordMessage *srm); * @param record */ void -PEERSTORE_destroy_record (struct GNUNET_PEERSTORE_Record *record); +PEERSTORE_destroy_record(struct GNUNET_PEERSTORE_Record *record); /* end of peerstore_common.h */ diff --git a/src/peerstore/perf_peerstore_store.c b/src/peerstore/perf_peerstore_store.c index 51761cc4f..392dbbb03 100644 --- a/src/peerstore/perf_peerstore_store.c +++ b/src/peerstore/perf_peerstore_store.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerstore/perf_peerstore_store.c * @brief performance test for peerstore store operation @@ -40,68 +40,68 @@ static char *v = "test_peerstore_stress_val"; static int count = 0; static void -disconnect () +disconnect() { if (NULL != h) - GNUNET_PEERSTORE_disconnect (h, GNUNET_YES); - GNUNET_SCHEDULER_shutdown (); + GNUNET_PEERSTORE_disconnect(h, GNUNET_YES); + GNUNET_SCHEDULER_shutdown(); } static void -store () +store() { - GNUNET_PEERSTORE_store (h, ss, &p, k, v, strlen (v) + 1, - GNUNET_TIME_UNIT_FOREVER_ABS, - (count == - 0) ? GNUNET_PEERSTORE_STOREOPTION_REPLACE : - GNUNET_PEERSTORE_STOREOPTION_MULTIPLE, NULL, NULL); + GNUNET_PEERSTORE_store(h, ss, &p, k, v, strlen(v) + 1, + GNUNET_TIME_UNIT_FOREVER_ABS, + (count == + 0) ? GNUNET_PEERSTORE_STOREOPTION_REPLACE : + GNUNET_PEERSTORE_STOREOPTION_MULTIPLE, NULL, NULL); count++; } static void -watch_cb (void *cls, const struct GNUNET_PEERSTORE_Record *record, - const char *emsg) +watch_cb(void *cls, const struct GNUNET_PEERSTORE_Record *record, + const char *emsg) { - GNUNET_assert (NULL == emsg); + GNUNET_assert(NULL == emsg); if (STORES == count) - { - ok = 0; - disconnect (); - } + { + ok = 0; + disconnect(); + } else - store (); + store(); } static void -run (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - memset (&p, 5, sizeof (p)); - h = GNUNET_PEERSTORE_connect (cfg); - GNUNET_assert (NULL != h); - GNUNET_PEERSTORE_watch (h, ss, &p, k, &watch_cb, NULL); - store (); + memset(&p, 5, sizeof(p)); + h = GNUNET_PEERSTORE_connect(cfg); + GNUNET_assert(NULL != h); + GNUNET_PEERSTORE_watch(h, ss, &p, k, &watch_cb, NULL); + store(); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { struct GNUNET_TIME_Absolute start; struct GNUNET_TIME_Relative diff; - start = GNUNET_TIME_absolute_get (); + start = GNUNET_TIME_absolute_get(); if (0 != - GNUNET_TESTING_service_run ("perf-peerstore-store", "peerstore", - "test_peerstore_api_data.conf", &run, NULL)) + GNUNET_TESTING_service_run("perf-peerstore-store", "peerstore", + "test_peerstore_api_data.conf", &run, NULL)) return 1; - diff = GNUNET_TIME_absolute_get_duration (start); - fprintf (stderr, "Stored and retrieved %d records in %s (%s).\n", STORES, - GNUNET_STRINGS_relative_time_to_string (diff, GNUNET_YES), - GNUNET_STRINGS_relative_time_to_string (diff, GNUNET_NO)); + diff = GNUNET_TIME_absolute_get_duration(start); + fprintf(stderr, "Stored and retrieved %d records in %s (%s).\n", STORES, + GNUNET_STRINGS_relative_time_to_string(diff, GNUNET_YES), + GNUNET_STRINGS_relative_time_to_string(diff, GNUNET_NO)); return ok; } diff --git a/src/peerstore/plugin_peerstore_flat.c b/src/peerstore/plugin_peerstore_flat.c index 0cd2522ec..749e270e4 100644 --- a/src/peerstore/plugin_peerstore_flat.c +++ b/src/peerstore/plugin_peerstore_flat.c @@ -32,9 +32,7 @@ /** * Context for all functions in this plugin. */ -struct Plugin -{ - +struct Plugin { /** * Configuration handle */ @@ -94,27 +92,27 @@ struct Plugin * Result found bool */ int iter_result_found; - }; static int -delete_entries (void *cls, - const struct GNUNET_HashCode *key, - void *value) +delete_entries(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct Plugin *plugin = cls; struct GNUNET_PEERSTORE_Record *entry = value; - if (0 != strcmp (plugin->iter_key, entry->key)) + + if (0 != strcmp(plugin->iter_key, entry->key)) return GNUNET_YES; - if (0 != memcmp (plugin->iter_peer, - &entry->peer, - sizeof (struct GNUNET_PeerIdentity))) + if (0 != memcmp(plugin->iter_peer, + &entry->peer, + sizeof(struct GNUNET_PeerIdentity))) return GNUNET_YES; - if (0 != strcmp (plugin->iter_sub_system, entry->sub_system)) + if (0 != strcmp(plugin->iter_sub_system, entry->sub_system)) return GNUNET_YES; - GNUNET_CONTAINER_multihashmap_remove (plugin->hm, key, value); + GNUNET_CONTAINER_multihashmap_remove(plugin->hm, key, value); plugin->deleted_entries++; return GNUNET_YES; } @@ -130,9 +128,9 @@ delete_entries (void *cls, * @return number of deleted records */ static int -peerstore_flat_delete_records (void *cls, const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key) +peerstore_flat_delete_records(void *cls, const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key) { struct Plugin *plugin = cls; @@ -141,25 +139,25 @@ peerstore_flat_delete_records (void *cls, const char *sub_system, plugin->iter_key = key; plugin->deleted_entries = 0; - GNUNET_CONTAINER_multihashmap_iterate (plugin->hm, - &delete_entries, - plugin); + GNUNET_CONTAINER_multihashmap_iterate(plugin->hm, + &delete_entries, + plugin); return plugin->deleted_entries; } static int -expire_entries (void *cls, - const struct GNUNET_HashCode *key, - void *value) +expire_entries(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct Plugin *plugin = cls; struct GNUNET_PEERSTORE_Record *entry = value; if (entry->expiry.abs_value_us < plugin->iter_now.abs_value_us) - { - GNUNET_CONTAINER_multihashmap_remove (plugin->hm, key, value); - plugin->exp_changes++; - } + { + GNUNET_CONTAINER_multihashmap_remove(plugin->hm, key, value); + plugin->exp_changes++; + } return GNUNET_YES; } @@ -176,49 +174,49 @@ expire_entries (void *cls, * called */ static int -peerstore_flat_expire_records (void *cls, struct GNUNET_TIME_Absolute now, - GNUNET_PEERSTORE_Continuation cont, - void *cont_cls) +peerstore_flat_expire_records(void *cls, struct GNUNET_TIME_Absolute now, + GNUNET_PEERSTORE_Continuation cont, + void *cont_cls) { struct Plugin *plugin = cls; + plugin->exp_changes = 0; plugin->iter_now = now; - GNUNET_CONTAINER_multihashmap_iterate (plugin->hm, - &expire_entries, - plugin); + GNUNET_CONTAINER_multihashmap_iterate(plugin->hm, + &expire_entries, + plugin); if (NULL != cont) - { - cont (cont_cls, plugin->exp_changes); - } + { + cont(cont_cls, plugin->exp_changes); + } return GNUNET_OK; - } static int -iterate_entries (void *cls, - const struct GNUNET_HashCode *key, - void *value) +iterate_entries(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct Plugin *plugin = cls; struct GNUNET_PEERSTORE_Record *entry = value; if ((NULL != plugin->iter_peer) && - (0 != memcmp (plugin->iter_peer, - &entry->peer, - sizeof (struct GNUNET_PeerIdentity)))) - { - return GNUNET_YES; - } + (0 != memcmp(plugin->iter_peer, + &entry->peer, + sizeof(struct GNUNET_PeerIdentity)))) + { + return GNUNET_YES; + } if ((NULL != plugin->iter_key) && - (0 != strcmp (plugin->iter_key, - entry->key))) - { - return GNUNET_YES; - } + (0 != strcmp(plugin->iter_key, + entry->key))) + { + return GNUNET_YES; + } if (NULL != plugin->iter) - plugin->iter (plugin->iter_cls, entry, NULL); + plugin->iter(plugin->iter_cls, entry, NULL); plugin->iter_result_found = GNUNET_YES; return GNUNET_YES; } @@ -238,24 +236,25 @@ iterate_entries (void *cls, * called */ static int -peerstore_flat_iterate_records (void *cls, const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - GNUNET_PEERSTORE_Processor iter, - void *iter_cls) +peerstore_flat_iterate_records(void *cls, const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + GNUNET_PEERSTORE_Processor iter, + void *iter_cls) { struct Plugin *plugin = cls; + plugin->iter = iter; plugin->iter_cls = iter_cls; plugin->iter_peer = peer; plugin->iter_sub_system = sub_system; plugin->iter_key = key; - GNUNET_CONTAINER_multihashmap_iterate (plugin->hm, - &iterate_entries, - plugin); + GNUNET_CONTAINER_multihashmap_iterate(plugin->hm, + &iterate_entries, + plugin); if (NULL != iter) - iter (iter_cls, NULL, NULL); + iter(iter_cls, NULL, NULL); return GNUNET_OK; } @@ -278,13 +277,13 @@ peerstore_flat_iterate_records (void *cls, const char *sub_system, * @return #GNUNET_OK on success, else #GNUNET_SYSERR and cont is not called */ static int -peerstore_flat_store_record (void *cls, const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, const void *value, size_t size, - struct GNUNET_TIME_Absolute expiry, - enum GNUNET_PEERSTORE_StoreOption options, - GNUNET_PEERSTORE_Continuation cont, - void *cont_cls) +peerstore_flat_store_record(void *cls, const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, const void *value, size_t size, + struct GNUNET_TIME_Absolute expiry, + enum GNUNET_PEERSTORE_StoreOption options, + GNUNET_PEERSTORE_Continuation cont, + void *cont_cls) { struct Plugin *plugin = cls; struct GNUNET_HashCode hkey; @@ -292,33 +291,33 @@ peerstore_flat_store_record (void *cls, const char *sub_system, const char *peer_id; - entry = GNUNET_new (struct GNUNET_PEERSTORE_Record); - entry->sub_system = GNUNET_strdup (sub_system); - entry->key = GNUNET_strdup (key); - entry->value = GNUNET_malloc (size); - GNUNET_memcpy (entry->value, value, size); + entry = GNUNET_new(struct GNUNET_PEERSTORE_Record); + entry->sub_system = GNUNET_strdup(sub_system); + entry->key = GNUNET_strdup(key); + entry->value = GNUNET_malloc(size); + GNUNET_memcpy(entry->value, value, size); entry->value_size = size; entry->peer = *peer; entry->expiry = expiry; - peer_id = GNUNET_i2s (peer); - GNUNET_CRYPTO_hash (peer_id, - strlen (peer_id), - &hkey); + peer_id = GNUNET_i2s(peer); + GNUNET_CRYPTO_hash(peer_id, + strlen(peer_id), + &hkey); if (GNUNET_PEERSTORE_STOREOPTION_REPLACE == options) - { - peerstore_flat_delete_records (cls, sub_system, peer, key); - } - - GNUNET_CONTAINER_multihashmap_put (plugin->hm, - &hkey, - entry, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); + { + peerstore_flat_delete_records(cls, sub_system, peer, key); + } + + GNUNET_CONTAINER_multihashmap_put(plugin->hm, + &hkey, + entry, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE); if (NULL != cont) - { - cont (cont_cls, GNUNET_OK); - } + { + cont(cont_cls, GNUNET_OK); + } return GNUNET_OK; } @@ -332,7 +331,7 @@ peerstore_flat_store_record (void *cls, const char *sub_system, * @return GNUNET_OK on success */ static int -database_setup (struct Plugin *plugin) +database_setup(struct Plugin *plugin) { char *afsdir; char *key; @@ -349,138 +348,139 @@ database_setup (struct Plugin *plugin) char *line; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "peerstore-flat", - "FILENAME", &afsdir)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "peerstore-flat", - "FILENAME"); - return GNUNET_SYSERR; - } - if (GNUNET_OK != GNUNET_DISK_file_test (afsdir)) - { - if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (afsdir)) + GNUNET_CONFIGURATION_get_value_filename(plugin->cfg, "peerstore-flat", + "FILENAME", &afsdir)) { - GNUNET_break (0); - GNUNET_free (afsdir); + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "peerstore-flat", + "FILENAME"); return GNUNET_SYSERR; } - } + if (GNUNET_OK != GNUNET_DISK_file_test(afsdir)) + { + if (GNUNET_OK != GNUNET_DISK_directory_create_for_file(afsdir)) + { + GNUNET_break(0); + GNUNET_free(afsdir); + return GNUNET_SYSERR; + } + } /* afsdir should be UTF-8-encoded. If it isn't, it's a bug */ plugin->fn = afsdir; - fh = GNUNET_DISK_file_open (afsdir, - GNUNET_DISK_OPEN_CREATE | - GNUNET_DISK_OPEN_READWRITE, - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_USER_READ); + fh = GNUNET_DISK_file_open(afsdir, + GNUNET_DISK_OPEN_CREATE | + GNUNET_DISK_OPEN_READWRITE, + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_USER_READ); if (NULL == fh) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to initialize file: %s.\n"), - afsdir); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to initialize file: %s.\n"), + afsdir); + return GNUNET_SYSERR; + } /* Load data from file into hashmap */ - plugin->hm = GNUNET_CONTAINER_multihashmap_create (10, - GNUNET_NO); - - if (GNUNET_SYSERR == GNUNET_DISK_file_size (afsdir, - &size, - GNUNET_YES, - GNUNET_YES)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to get filesize: %s.\n"), - afsdir); - return GNUNET_SYSERR; - } - - buffer = GNUNET_malloc (size + 1); - - if (GNUNET_SYSERR == GNUNET_DISK_file_read (fh, - buffer, - size)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to read file: %s.\n"), - afsdir); - GNUNET_DISK_file_close (fh); - GNUNET_free (buffer); - return GNUNET_SYSERR; - } + plugin->hm = GNUNET_CONTAINER_multihashmap_create(10, + GNUNET_NO); - buffer[size] = '\0'; - GNUNET_DISK_file_close (fh); - if (0 < size) { - line = strtok (buffer, "\n"); - while (line != NULL) { - sub_system = strtok (line, ","); - if (NULL == sub_system) - break; - peer = strtok (NULL, ","); - if (NULL == peer) - break; - key = strtok (NULL, ","); - if (NULL == key) - break; - value = strtok (NULL, ","); - if (NULL == value) - break; - expiry = strtok (NULL, ","); - if (NULL == expiry) - break; - entry = GNUNET_new (struct GNUNET_PEERSTORE_Record); - entry->sub_system = GNUNET_strdup (sub_system); - entry->key = GNUNET_strdup (key); - { - size_t s; - char *o; - - o = NULL; - s = GNUNET_STRINGS_base64_decode (peer, - strlen (peer), - (void**)&o); - if (sizeof (struct GNUNET_PeerIdentity) == s) - GNUNET_memcpy (&entry->peer, - o, - s); - else - GNUNET_break (0); - GNUNET_free_non_null (o); - } - entry->value_size = GNUNET_STRINGS_base64_decode (value, - strlen (value), - (void**)&entry->value); - if (GNUNET_SYSERR == - GNUNET_STRINGS_fancy_time_to_absolute (expiry, - &entry->expiry)) - { - GNUNET_free (entry->sub_system); - GNUNET_free (entry->key); - GNUNET_free (entry); - break; - } - peer_id = GNUNET_i2s (&entry->peer); - GNUNET_CRYPTO_hash (peer_id, - strlen (peer_id), - &hkey); - - GNUNET_assert (GNUNET_OK == GNUNET_CONTAINER_multihashmap_put (plugin->hm, - &hkey, - entry, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); + if (GNUNET_SYSERR == GNUNET_DISK_file_size(afsdir, + &size, + GNUNET_YES, + GNUNET_YES)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to get filesize: %s.\n"), + afsdir); + return GNUNET_SYSERR; + } + buffer = GNUNET_malloc(size + 1); + + if (GNUNET_SYSERR == GNUNET_DISK_file_read(fh, + buffer, + size)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to read file: %s.\n"), + afsdir); + GNUNET_DISK_file_close(fh); + GNUNET_free(buffer); + return GNUNET_SYSERR; + } + + buffer[size] = '\0'; + GNUNET_DISK_file_close(fh); + if (0 < size) + { + line = strtok(buffer, "\n"); + while (line != NULL) + { + sub_system = strtok(line, ","); + if (NULL == sub_system) + break; + peer = strtok(NULL, ","); + if (NULL == peer) + break; + key = strtok(NULL, ","); + if (NULL == key) + break; + value = strtok(NULL, ","); + if (NULL == value) + break; + expiry = strtok(NULL, ","); + if (NULL == expiry) + break; + entry = GNUNET_new(struct GNUNET_PEERSTORE_Record); + entry->sub_system = GNUNET_strdup(sub_system); + entry->key = GNUNET_strdup(key); + { + size_t s; + char *o; + + o = NULL; + s = GNUNET_STRINGS_base64_decode(peer, + strlen(peer), + (void**)&o); + if (sizeof(struct GNUNET_PeerIdentity) == s) + GNUNET_memcpy(&entry->peer, + o, + s); + else + GNUNET_break(0); + GNUNET_free_non_null(o); + } + entry->value_size = GNUNET_STRINGS_base64_decode(value, + strlen(value), + (void**)&entry->value); + if (GNUNET_SYSERR == + GNUNET_STRINGS_fancy_time_to_absolute(expiry, + &entry->expiry)) + { + GNUNET_free(entry->sub_system); + GNUNET_free(entry->key); + GNUNET_free(entry); + break; + } + peer_id = GNUNET_i2s(&entry->peer); + GNUNET_CRYPTO_hash(peer_id, + strlen(peer_id), + &hkey); + + GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(plugin->hm, + &hkey, + entry, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); + } } - } - GNUNET_free (buffer); + GNUNET_free(buffer); return GNUNET_OK; } static int -store_and_free_entries (void *cls, - const struct GNUNET_HashCode *key, - void *value) +store_and_free_entries(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GNUNET_DISK_FileHandle *fh = cls; struct GNUNET_PEERSTORE_Record *entry = value; @@ -489,32 +489,31 @@ store_and_free_entries (void *cls, const char *expiry; char *val; - GNUNET_STRINGS_base64_encode (entry->value, - entry->value_size, - &val); - expiry = GNUNET_STRINGS_absolute_time_to_string (entry->expiry); - GNUNET_STRINGS_base64_encode ((char*)&entry->peer, - sizeof (struct GNUNET_PeerIdentity), - &peer); - GNUNET_asprintf (&line, - "%s,%s,%s,%s,%s", - entry->sub_system, - peer, - entry->key, - val, - expiry); - GNUNET_free (val); - GNUNET_free (peer); - GNUNET_DISK_file_write (fh, - line, - strlen (line)); - GNUNET_free (entry->sub_system); - GNUNET_free (entry->key); - GNUNET_free (entry->value); - GNUNET_free (entry); - GNUNET_free (line); + GNUNET_STRINGS_base64_encode(entry->value, + entry->value_size, + &val); + expiry = GNUNET_STRINGS_absolute_time_to_string(entry->expiry); + GNUNET_STRINGS_base64_encode((char*)&entry->peer, + sizeof(struct GNUNET_PeerIdentity), + &peer); + GNUNET_asprintf(&line, + "%s,%s,%s,%s,%s", + entry->sub_system, + peer, + entry->key, + val, + expiry); + GNUNET_free(val); + GNUNET_free(peer); + GNUNET_DISK_file_write(fh, + line, + strlen(line)); + GNUNET_free(entry->sub_system); + GNUNET_free(entry->key); + GNUNET_free(entry->value); + GNUNET_free(entry); + GNUNET_free(line); return GNUNET_YES; - } /** @@ -523,27 +522,28 @@ store_and_free_entries (void *cls, * @param plugin the plugin context (state for this module) */ static void -database_shutdown (struct Plugin *plugin) +database_shutdown(struct Plugin *plugin) { struct GNUNET_DISK_FileHandle *fh; - fh = GNUNET_DISK_file_open (plugin->fn, - GNUNET_DISK_OPEN_CREATE | - GNUNET_DISK_OPEN_TRUNCATE | - GNUNET_DISK_OPEN_READWRITE, - GNUNET_DISK_PERM_USER_WRITE | - GNUNET_DISK_PERM_USER_READ); + + fh = GNUNET_DISK_file_open(plugin->fn, + GNUNET_DISK_OPEN_CREATE | + GNUNET_DISK_OPEN_TRUNCATE | + GNUNET_DISK_OPEN_READWRITE, + GNUNET_DISK_PERM_USER_WRITE | + GNUNET_DISK_PERM_USER_READ); if (NULL == fh) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Unable to initialize file: %s.\n"), - plugin->fn); - return; - } - GNUNET_CONTAINER_multihashmap_iterate (plugin->hm, - &store_and_free_entries, - fh); - GNUNET_CONTAINER_multihashmap_destroy (plugin->hm); - GNUNET_DISK_file_close (fh); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Unable to initialize file: %s.\n"), + plugin->fn); + return; + } + GNUNET_CONTAINER_multihashmap_iterate(plugin->hm, + &store_and_free_entries, + fh); + GNUNET_CONTAINER_multihashmap_destroy(plugin->hm); + GNUNET_DISK_file_close(fh); } @@ -554,7 +554,7 @@ database_shutdown (struct Plugin *plugin) * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_peerstore_flat_init (void *cls) +libgnunet_plugin_peerstore_flat_init(void *cls) { static struct Plugin plugin; const struct GNUNET_CONFIGURATION_Handle *cfg = cls; @@ -562,19 +562,19 @@ libgnunet_plugin_peerstore_flat_init (void *cls) if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.cfg = cfg; - if (GNUNET_OK != database_setup (&plugin)) - { - database_shutdown (&plugin); - return NULL; - } - api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions); + if (GNUNET_OK != database_setup(&plugin)) + { + database_shutdown(&plugin); + return NULL; + } + api = GNUNET_new(struct GNUNET_PEERSTORE_PluginFunctions); api->cls = &plugin; api->store_record = &peerstore_flat_store_record; api->iterate_records = &peerstore_flat_iterate_records; api->expire_records = &peerstore_flat_expire_records; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Flat plugin is running\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Flat plugin is running\n"); return api; } @@ -586,15 +586,15 @@ libgnunet_plugin_peerstore_flat_init (void *cls) * @return Always NULL */ void * -libgnunet_plugin_peerstore_flat_done (void *cls) +libgnunet_plugin_peerstore_flat_done(void *cls) { struct GNUNET_PEERSTORE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - database_shutdown (plugin); + database_shutdown(plugin); plugin->cfg = NULL; - GNUNET_free (api); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Flat plugin is finished\n"); + GNUNET_free(api); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Flat plugin is finished\n"); return NULL; } diff --git a/src/peerstore/plugin_peerstore_sqlite.c b/src/peerstore/plugin_peerstore_sqlite.c index 898db2231..5f6617ebc 100644 --- a/src/peerstore/plugin_peerstore_sqlite.c +++ b/src/peerstore/plugin_peerstore_sqlite.c @@ -49,16 +49,14 @@ * a failure of the command 'cmd' on file 'filename' * with the message given by strerror(errno). */ -#define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from (level, "peerstore-sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0) +#define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from(level, "peerstore-sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while (0) -#define LOG(kind,...) GNUNET_log_from (kind, "peerstore-sqlite", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "peerstore-sqlite", __VA_ARGS__) /** * Context for all functions in this plugin. */ -struct Plugin -{ - +struct Plugin { /** * Configuration handle */ @@ -110,7 +108,6 @@ struct Plugin * with given key */ sqlite3_stmt *delete_peerstoredata; - }; @@ -124,46 +121,46 @@ struct Plugin * @return number of deleted records, #GNUNE_SYSERR on error */ static int -peerstore_sqlite_delete_records (void *cls, - const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key) +peerstore_sqlite_delete_records(void *cls, + const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key) { struct Plugin *plugin = cls; sqlite3_stmt *stmt = plugin->delete_peerstoredata; struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_string (sub_system), - GNUNET_SQ_query_param_auto_from_type (peer), - GNUNET_SQ_query_param_string (key), + GNUNET_SQ_query_param_string(sub_system), + GNUNET_SQ_query_param_auto_from_type(peer), + GNUNET_SQ_query_param_string(key), GNUNET_SQ_query_param_end }; int ret; if (GNUNET_OK != - GNUNET_SQ_bind (stmt, - params)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind"); - GNUNET_SQ_reset (plugin->dbh, - stmt); - return GNUNET_SYSERR; - } + GNUNET_SQ_bind(stmt, + params)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind"); + GNUNET_SQ_reset(plugin->dbh, + stmt); + return GNUNET_SYSERR; + } if (SQLITE_DONE != - sqlite3_step (stmt)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - ret = GNUNET_SYSERR; - } + sqlite3_step(stmt)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + ret = GNUNET_SYSERR; + } else - { - ret = sqlite3_changes (plugin->dbh); - } - GNUNET_SQ_reset (plugin->dbh, - stmt); + { + ret = sqlite3_changes(plugin->dbh); + } + GNUNET_SQ_reset(plugin->dbh, + stmt); return ret; } @@ -179,42 +176,42 @@ peerstore_sqlite_delete_records (void *cls, * called */ static int -peerstore_sqlite_expire_records (void *cls, struct GNUNET_TIME_Absolute now, - GNUNET_PEERSTORE_Continuation cont, - void *cont_cls) +peerstore_sqlite_expire_records(void *cls, struct GNUNET_TIME_Absolute now, + GNUNET_PEERSTORE_Continuation cont, + void *cont_cls) { struct Plugin *plugin = cls; sqlite3_stmt *stmt = plugin->expire_peerstoredata; struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_absolute_time (&now), + GNUNET_SQ_query_param_absolute_time(&now), GNUNET_SQ_query_param_end }; if (GNUNET_OK != - GNUNET_SQ_bind (stmt, - params)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind"); - GNUNET_SQ_reset (plugin->dbh, - stmt); - return GNUNET_SYSERR; - } - if (SQLITE_DONE != sqlite3_step (stmt)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - GNUNET_SQ_reset (plugin->dbh, - stmt); - return GNUNET_SYSERR; - } + GNUNET_SQ_bind(stmt, + params)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind"); + GNUNET_SQ_reset(plugin->dbh, + stmt); + return GNUNET_SYSERR; + } + if (SQLITE_DONE != sqlite3_step(stmt)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + GNUNET_SQ_reset(plugin->dbh, + stmt); + return GNUNET_SYSERR; + } if (NULL != cont) - cont (cont_cls, - sqlite3_changes (plugin->dbh)); - GNUNET_SQ_reset (plugin->dbh, - stmt); + cont(cont_cls, + sqlite3_changes(plugin->dbh)); + GNUNET_SQ_reset(plugin->dbh, + stmt); return GNUNET_OK; } @@ -234,12 +231,12 @@ peerstore_sqlite_expire_records (void *cls, struct GNUNET_TIME_Absolute now, * called */ static int -peerstore_sqlite_iterate_records (void *cls, - const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - GNUNET_PEERSTORE_Processor iter, - void *iter_cls) +peerstore_sqlite_iterate_records(void *cls, + const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + GNUNET_PEERSTORE_Processor iter, + void *iter_cls) { struct Plugin *plugin = cls; sqlite3_stmt *stmt; @@ -247,113 +244,113 @@ peerstore_sqlite_iterate_records (void *cls, int sret; struct GNUNET_PEERSTORE_Record rec; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Executing iterate request on sqlite db.\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Executing iterate request on sqlite db.\n"); if (NULL == peer) - { - if (NULL == key) - { - struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_string (sub_system), - GNUNET_SQ_query_param_end - }; - - stmt = plugin->select_peerstoredata; - err = GNUNET_SQ_bind (stmt, - params); - } - else { - struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_string (sub_system), - GNUNET_SQ_query_param_string (key), - GNUNET_SQ_query_param_end - }; - - stmt = plugin->select_peerstoredata_by_key; - err = GNUNET_SQ_bind (stmt, - params); + if (NULL == key) + { + struct GNUNET_SQ_QueryParam params[] = { + GNUNET_SQ_query_param_string(sub_system), + GNUNET_SQ_query_param_end + }; + + stmt = plugin->select_peerstoredata; + err = GNUNET_SQ_bind(stmt, + params); + } + else + { + struct GNUNET_SQ_QueryParam params[] = { + GNUNET_SQ_query_param_string(sub_system), + GNUNET_SQ_query_param_string(key), + GNUNET_SQ_query_param_end + }; + + stmt = plugin->select_peerstoredata_by_key; + err = GNUNET_SQ_bind(stmt, + params); + } } - } else - { - if (NULL == key) { - struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_string (sub_system), - GNUNET_SQ_query_param_auto_from_type (peer), - GNUNET_SQ_query_param_end - }; - - stmt = plugin->select_peerstoredata_by_pid; - err = GNUNET_SQ_bind (stmt, - params); + if (NULL == key) + { + struct GNUNET_SQ_QueryParam params[] = { + GNUNET_SQ_query_param_string(sub_system), + GNUNET_SQ_query_param_auto_from_type(peer), + GNUNET_SQ_query_param_end + }; + + stmt = plugin->select_peerstoredata_by_pid; + err = GNUNET_SQ_bind(stmt, + params); + } + else + { + struct GNUNET_SQ_QueryParam params[] = { + GNUNET_SQ_query_param_string(sub_system), + GNUNET_SQ_query_param_auto_from_type(peer), + GNUNET_SQ_query_param_string(key), + GNUNET_SQ_query_param_end + }; + + stmt = plugin->select_peerstoredata_by_all; + err = GNUNET_SQ_bind(stmt, + params); + } } - else - { - struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_string (sub_system), - GNUNET_SQ_query_param_auto_from_type (peer), - GNUNET_SQ_query_param_string (key), - GNUNET_SQ_query_param_end - }; - - stmt = plugin->select_peerstoredata_by_all; - err = GNUNET_SQ_bind (stmt, - params); - } - } if (GNUNET_OK != err) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind_XXXX"); - GNUNET_SQ_reset (plugin->dbh, - stmt); - return GNUNET_SYSERR; - } + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind_XXXX"); + GNUNET_SQ_reset(plugin->dbh, + stmt); + return GNUNET_SYSERR; + } err = 0; - while (SQLITE_ROW == (sret = sqlite3_step (stmt))) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Returning a matched record.\n"); - struct GNUNET_SQ_ResultSpec rs[] = { - GNUNET_SQ_result_spec_string (&rec.sub_system), - GNUNET_SQ_result_spec_auto_from_type (&rec.peer), - GNUNET_SQ_result_spec_string (&rec.key), - GNUNET_SQ_result_spec_variable_size (&rec.value, &rec.value_size), - GNUNET_SQ_result_spec_absolute_time (&rec.expiry), - GNUNET_SQ_result_spec_end - }; - - if (GNUNET_OK != - GNUNET_SQ_extract_result (stmt, - rs)) + while (SQLITE_ROW == (sret = sqlite3_step(stmt))) { - GNUNET_break (0); - break; + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Returning a matched record.\n"); + struct GNUNET_SQ_ResultSpec rs[] = { + GNUNET_SQ_result_spec_string(&rec.sub_system), + GNUNET_SQ_result_spec_auto_from_type(&rec.peer), + GNUNET_SQ_result_spec_string(&rec.key), + GNUNET_SQ_result_spec_variable_size(&rec.value, &rec.value_size), + GNUNET_SQ_result_spec_absolute_time(&rec.expiry), + GNUNET_SQ_result_spec_end + }; + + if (GNUNET_OK != + GNUNET_SQ_extract_result(stmt, + rs)) + { + GNUNET_break(0); + break; + } + if (NULL != iter) + iter(iter_cls, + &rec, + NULL); + GNUNET_SQ_cleanup_result(rs); } - if (NULL != iter) - iter (iter_cls, - &rec, - NULL); - GNUNET_SQ_cleanup_result (rs); - } if (SQLITE_DONE != sret) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR, - "sqlite_step"); - err = 1; - } - GNUNET_SQ_reset (plugin->dbh, - stmt); + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR, + "sqlite_step"); + err = 1; + } + GNUNET_SQ_reset(plugin->dbh, + stmt); if (NULL != iter) - iter (iter_cls, - NULL, - err ? "sqlite error" : NULL); + iter(iter_cls, + NULL, + err ? "sqlite error" : NULL); return GNUNET_OK; } @@ -376,52 +373,52 @@ peerstore_sqlite_iterate_records (void *cls, * @return #GNUNET_OK on success, else #GNUNET_SYSERR and cont is not called */ static int -peerstore_sqlite_store_record (void *cls, - const char *sub_system, - const struct GNUNET_PeerIdentity *peer, - const char *key, - const void *value, - size_t size, - struct GNUNET_TIME_Absolute expiry, - enum GNUNET_PEERSTORE_StoreOption options, - GNUNET_PEERSTORE_Continuation cont, - void *cont_cls) +peerstore_sqlite_store_record(void *cls, + const char *sub_system, + const struct GNUNET_PeerIdentity *peer, + const char *key, + const void *value, + size_t size, + struct GNUNET_TIME_Absolute expiry, + enum GNUNET_PEERSTORE_StoreOption options, + GNUNET_PEERSTORE_Continuation cont, + void *cont_cls) { struct Plugin *plugin = cls; sqlite3_stmt *stmt = plugin->insert_peerstoredata; struct GNUNET_SQ_QueryParam params[] = { - GNUNET_SQ_query_param_string (sub_system), - GNUNET_SQ_query_param_auto_from_type (peer), - GNUNET_SQ_query_param_string (key), - GNUNET_SQ_query_param_fixed_size (value, size), - GNUNET_SQ_query_param_absolute_time (&expiry), + GNUNET_SQ_query_param_string(sub_system), + GNUNET_SQ_query_param_auto_from_type(peer), + GNUNET_SQ_query_param_string(key), + GNUNET_SQ_query_param_fixed_size(value, size), + GNUNET_SQ_query_param_absolute_time(&expiry), GNUNET_SQ_query_param_end }; if (GNUNET_PEERSTORE_STOREOPTION_REPLACE == options) - { - peerstore_sqlite_delete_records (cls, - sub_system, - peer, - key); - } + { + peerstore_sqlite_delete_records(cls, + sub_system, + peer, + key); + } if (GNUNET_OK != - GNUNET_SQ_bind (stmt, - params)) - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_bind"); - else if (SQLITE_DONE != sqlite3_step (stmt)) - { - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "sqlite3_step"); - } - GNUNET_SQ_reset (plugin->dbh, - stmt); + GNUNET_SQ_bind(stmt, + params)) + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_bind"); + else if (SQLITE_DONE != sqlite3_step(stmt)) + { + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "sqlite3_step"); + } + GNUNET_SQ_reset(plugin->dbh, + stmt); if (NULL != cont) - cont (cont_cls, - GNUNET_OK); + cont(cont_cls, + GNUNET_OK); return GNUNET_OK; } @@ -434,25 +431,25 @@ peerstore_sqlite_store_record (void *cls, * @return 0 on success */ static int -sql_exec (sqlite3 *dbh, - const char *sql) +sql_exec(sqlite3 *dbh, + const char *sql) { int result; - result = sqlite3_exec (dbh, - sql, - NULL, - NULL, - NULL); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Executed `%s' / %d\n", - sql, - result); + result = sqlite3_exec(dbh, + sql, + NULL, + NULL, + NULL); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Executed `%s' / %d\n", + sql, + result); if (SQLITE_OK != result) - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Error executing SQL query: %s\n %s\n"), - sqlite3_errmsg (dbh), - sql); + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Error executing SQL query: %s\n %s\n"), + sqlite3_errmsg(dbh), + sql); return result; } @@ -466,28 +463,28 @@ sql_exec (sqlite3 *dbh, * @return 0 on success */ static int -sql_prepare (sqlite3 *dbh, - const char *sql, - sqlite3_stmt ** stmt) +sql_prepare(sqlite3 *dbh, + const char *sql, + sqlite3_stmt ** stmt) { char *tail; int result; - result = sqlite3_prepare_v2 (dbh, - sql, - strlen (sql), - stmt, - (const char **) &tail); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Prepared `%s' / %p: %d\n", - sql, - *stmt, - result); + result = sqlite3_prepare_v2(dbh, + sql, + strlen(sql), + stmt, + (const char **)&tail); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Prepared `%s' / %p: %d\n", + sql, + *stmt, + result); if (SQLITE_OK != result) - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Error preparing SQL query: %s\n %s\n"), - sqlite3_errmsg (dbh), - sql); + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Error preparing SQL query: %s\n %s\n"), + sqlite3_errmsg(dbh), + sql); return result; } @@ -501,110 +498,110 @@ sql_prepare (sqlite3 *dbh, * @return #GNUNET_OK on success */ static int -database_setup (struct Plugin *plugin) +database_setup(struct Plugin *plugin) { char *filename; if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, - "peerstore-sqlite", - "FILENAME", - &filename)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "peerstore-sqlite", - "FILENAME"); - return GNUNET_SYSERR; - } - if (GNUNET_OK != GNUNET_DISK_file_test (filename)) - { - if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename)) + GNUNET_CONFIGURATION_get_value_filename(plugin->cfg, + "peerstore-sqlite", + "FILENAME", + &filename)) { - GNUNET_break (0); - GNUNET_free (filename); + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "peerstore-sqlite", + "FILENAME"); return GNUNET_SYSERR; } - } + if (GNUNET_OK != GNUNET_DISK_file_test(filename)) + { + if (GNUNET_OK != GNUNET_DISK_directory_create_for_file(filename)) + { + GNUNET_break(0); + GNUNET_free(filename); + return GNUNET_SYSERR; + } + } /* filename should be UTF-8-encoded. If it isn't, it's a bug */ plugin->fn = filename; /* Open database and precompile statements */ - if (SQLITE_OK != sqlite3_open (plugin->fn, - &plugin->dbh)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Unable to initialize SQLite: %s.\n"), - sqlite3_errmsg (plugin->dbh)); - return GNUNET_SYSERR; - } - sql_exec (plugin->dbh, - "PRAGMA temp_store=MEMORY"); - sql_exec (plugin->dbh, - "PRAGMA synchronous=OFF"); - sql_exec (plugin->dbh, - "PRAGMA legacy_file_format=OFF"); - sql_exec (plugin->dbh, - "PRAGMA auto_vacuum=INCREMENTAL"); - sql_exec (plugin->dbh, - "PRAGMA encoding=\"UTF-8\""); - sql_exec (plugin->dbh, - "PRAGMA page_size=4096"); - sqlite3_busy_timeout (plugin->dbh, - BUSY_TIMEOUT_MS); + if (SQLITE_OK != sqlite3_open(plugin->fn, + &plugin->dbh)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Unable to initialize SQLite: %s.\n"), + sqlite3_errmsg(plugin->dbh)); + return GNUNET_SYSERR; + } + sql_exec(plugin->dbh, + "PRAGMA temp_store=MEMORY"); + sql_exec(plugin->dbh, + "PRAGMA synchronous=OFF"); + sql_exec(plugin->dbh, + "PRAGMA legacy_file_format=OFF"); + sql_exec(plugin->dbh, + "PRAGMA auto_vacuum=INCREMENTAL"); + sql_exec(plugin->dbh, + "PRAGMA encoding=\"UTF-8\""); + sql_exec(plugin->dbh, + "PRAGMA page_size=4096"); + sqlite3_busy_timeout(plugin->dbh, + BUSY_TIMEOUT_MS); /* Create tables */ - sql_exec (plugin->dbh, - "CREATE TABLE IF NOT EXISTS peerstoredata (\n" - " sub_system TEXT NOT NULL,\n" - " peer_id BLOB NOT NULL,\n" - " key TEXT NOT NULL,\n" - " value BLOB NULL,\n" - " expiry INT8 NOT NULL" ");"); + sql_exec(plugin->dbh, + "CREATE TABLE IF NOT EXISTS peerstoredata (\n" + " sub_system TEXT NOT NULL,\n" + " peer_id BLOB NOT NULL,\n" + " key TEXT NOT NULL,\n" + " value BLOB NULL,\n" + " expiry INT8 NOT NULL" ");"); /* Create Indices */ if (SQLITE_OK != - sqlite3_exec (plugin->dbh, - "CREATE INDEX IF NOT EXISTS peerstoredata_key_index ON peerstoredata (sub_system, peer_id, key)", - NULL, - NULL, - NULL)) - { - LOG (GNUNET_ERROR_TYPE_ERROR, - _("Unable to create indices: %s.\n"), - sqlite3_errmsg (plugin->dbh)); - return GNUNET_SYSERR; - } + sqlite3_exec(plugin->dbh, + "CREATE INDEX IF NOT EXISTS peerstoredata_key_index ON peerstoredata (sub_system, peer_id, key)", + NULL, + NULL, + NULL)) + { + LOG(GNUNET_ERROR_TYPE_ERROR, + _("Unable to create indices: %s.\n"), + sqlite3_errmsg(plugin->dbh)); + return GNUNET_SYSERR; + } /* Prepare statements */ - sql_prepare (plugin->dbh, - "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry)" - " VALUES (?,?,?,?,?);", - &plugin->insert_peerstoredata); - sql_prepare (plugin->dbh, - "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata" - " WHERE sub_system = ?", - &plugin->select_peerstoredata); - sql_prepare (plugin->dbh, - "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata" - " WHERE sub_system = ?" - " AND peer_id = ?", - &plugin->select_peerstoredata_by_pid); - sql_prepare (plugin->dbh, - "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata" - " WHERE sub_system = ?" - " AND key = ?", - &plugin->select_peerstoredata_by_key); - sql_prepare (plugin->dbh, - "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata" - " WHERE sub_system = ?" - " AND peer_id = ?" " AND key = ?", - &plugin->select_peerstoredata_by_all); - sql_prepare (plugin->dbh, - "DELETE FROM peerstoredata" - " WHERE expiry < ?", - &plugin->expire_peerstoredata); - sql_prepare (plugin->dbh, - "DELETE FROM peerstoredata" - " WHERE sub_system = ?" - " AND peer_id = ?" " AND key = ?", - &plugin->delete_peerstoredata); + sql_prepare(plugin->dbh, + "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry)" + " VALUES (?,?,?,?,?);", + &plugin->insert_peerstoredata); + sql_prepare(plugin->dbh, + "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata" + " WHERE sub_system = ?", + &plugin->select_peerstoredata); + sql_prepare(plugin->dbh, + "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata" + " WHERE sub_system = ?" + " AND peer_id = ?", + &plugin->select_peerstoredata_by_pid); + sql_prepare(plugin->dbh, + "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata" + " WHERE sub_system = ?" + " AND key = ?", + &plugin->select_peerstoredata_by_key); + sql_prepare(plugin->dbh, + "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata" + " WHERE sub_system = ?" + " AND peer_id = ?" " AND key = ?", + &plugin->select_peerstoredata_by_all); + sql_prepare(plugin->dbh, + "DELETE FROM peerstoredata" + " WHERE expiry < ?", + &plugin->expire_peerstoredata); + sql_prepare(plugin->dbh, + "DELETE FROM peerstoredata" + " WHERE sub_system = ?" + " AND peer_id = ?" " AND key = ?", + &plugin->delete_peerstoredata); return GNUNET_OK; } @@ -615,26 +612,26 @@ database_setup (struct Plugin *plugin) * @param plugin the plugin context (state for this module) */ static void -database_shutdown (struct Plugin *plugin) +database_shutdown(struct Plugin *plugin) { int result; sqlite3_stmt *stmt; - while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh, - NULL))) - { - result = sqlite3_finalize (stmt); - if (SQLITE_OK != result) - LOG (GNUNET_ERROR_TYPE_WARNING, - "Failed to close statement %p: %d\n", - stmt, - result); - } - if (SQLITE_OK != sqlite3_close (plugin->dbh)) - LOG_SQLITE (plugin, - GNUNET_ERROR_TYPE_ERROR, - "sqlite3_close"); - GNUNET_free_non_null (plugin->fn); + while (NULL != (stmt = sqlite3_next_stmt(plugin->dbh, + NULL))) + { + result = sqlite3_finalize(stmt); + if (SQLITE_OK != result) + LOG(GNUNET_ERROR_TYPE_WARNING, + "Failed to close statement %p: %d\n", + stmt, + result); + } + if (SQLITE_OK != sqlite3_close(plugin->dbh)) + LOG_SQLITE(plugin, + GNUNET_ERROR_TYPE_ERROR, + "sqlite3_close"); + GNUNET_free_non_null(plugin->fn); } @@ -645,7 +642,7 @@ database_shutdown (struct Plugin *plugin) * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_peerstore_sqlite_init (void *cls) +libgnunet_plugin_peerstore_sqlite_init(void *cls) { static struct Plugin plugin; const struct GNUNET_CONFIGURATION_Handle *cfg = cls; @@ -653,22 +650,22 @@ libgnunet_plugin_peerstore_sqlite_init (void *cls) if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, - 0, - sizeof (struct Plugin)); + memset(&plugin, + 0, + sizeof(struct Plugin)); plugin.cfg = cfg; - if (GNUNET_OK != database_setup (&plugin)) - { - database_shutdown (&plugin); - return NULL; - } - api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions); + if (GNUNET_OK != database_setup(&plugin)) + { + database_shutdown(&plugin); + return NULL; + } + api = GNUNET_new(struct GNUNET_PEERSTORE_PluginFunctions); api->cls = &plugin; api->store_record = &peerstore_sqlite_store_record; api->iterate_records = &peerstore_sqlite_iterate_records; api->expire_records = &peerstore_sqlite_expire_records; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sqlite plugin is running\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sqlite plugin is running\n"); return api; } @@ -680,16 +677,16 @@ libgnunet_plugin_peerstore_sqlite_init (void *cls) * @return Always NULL */ void * -libgnunet_plugin_peerstore_sqlite_done (void *cls) +libgnunet_plugin_peerstore_sqlite_done(void *cls) { struct GNUNET_PEERSTORE_PluginFunctions *api = cls; struct Plugin *plugin = api->cls; - database_shutdown (plugin); + database_shutdown(plugin); plugin->cfg = NULL; - GNUNET_free (api); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Sqlite plugin is finished\n"); + GNUNET_free(api); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Sqlite plugin is finished\n"); return NULL; } diff --git a/src/peerstore/test_peerstore_api_iterate.c b/src/peerstore/test_peerstore_api_iterate.c index a19aad121..185fc8225 100644 --- a/src/peerstore/test_peerstore_api_iterate.c +++ b/src/peerstore/test_peerstore_api_iterate.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerstore/test_peerstore_api_iterate.c * @brief testcase for peerstore iteration operation @@ -42,132 +42,132 @@ static int count = 0; static void -iter3_cb (void *cls, - const struct GNUNET_PEERSTORE_Record *record, - const char *emsg) +iter3_cb(void *cls, + const struct GNUNET_PEERSTORE_Record *record, + const char *emsg) { if (NULL != emsg) - { - GNUNET_PEERSTORE_iterate_cancel (ic); - return; - } + { + GNUNET_PEERSTORE_iterate_cancel(ic); + return; + } if (NULL != record) - { - count++; - return; - } - GNUNET_assert (count == 3); + { + count++; + return; + } + GNUNET_assert(count == 3); ok = 0; - GNUNET_PEERSTORE_disconnect (h, GNUNET_NO); - GNUNET_SCHEDULER_shutdown (); + GNUNET_PEERSTORE_disconnect(h, GNUNET_NO); + GNUNET_SCHEDULER_shutdown(); } static void -iter2_cb (void *cls, - const struct GNUNET_PEERSTORE_Record *record, - const char *emsg) +iter2_cb(void *cls, + const struct GNUNET_PEERSTORE_Record *record, + const char *emsg) { if (NULL != emsg) - { - GNUNET_PEERSTORE_iterate_cancel (ic); - return; - } + { + GNUNET_PEERSTORE_iterate_cancel(ic); + return; + } if (NULL != record) - { - count++; - return; - } - GNUNET_assert (count == 2); + { + count++; + return; + } + GNUNET_assert(count == 2); count = 0; - ic = GNUNET_PEERSTORE_iterate (h, - ss, - NULL, - NULL, - &iter3_cb, - NULL); + ic = GNUNET_PEERSTORE_iterate(h, + ss, + NULL, + NULL, + &iter3_cb, + NULL); } static void -iter1_cb (void *cls, - const struct GNUNET_PEERSTORE_Record *record, - const char *emsg) +iter1_cb(void *cls, + const struct GNUNET_PEERSTORE_Record *record, + const char *emsg) { if (NULL != emsg) - { - GNUNET_PEERSTORE_iterate_cancel (ic); - return; - } + { + GNUNET_PEERSTORE_iterate_cancel(ic); + return; + } if (NULL != record) - { - count++; - return; - } - GNUNET_assert (count == 1); + { + count++; + return; + } + GNUNET_assert(count == 1); count = 0; - ic = GNUNET_PEERSTORE_iterate (h, - ss, - &p1, - NULL, - &iter2_cb, - NULL); + ic = GNUNET_PEERSTORE_iterate(h, + ss, + &p1, + NULL, + &iter2_cb, + NULL); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - h = GNUNET_PEERSTORE_connect (cfg); - GNUNET_assert (NULL != h); - memset (&p1, 1, sizeof (p1)); - memset (&p2, 2, sizeof (p2)); - GNUNET_PEERSTORE_store (h, - ss, - &p1, - k1, - val, - strlen (val) + 1, - GNUNET_TIME_UNIT_FOREVER_ABS, - GNUNET_PEERSTORE_STOREOPTION_REPLACE, - NULL, - NULL); - GNUNET_PEERSTORE_store (h, - ss, - &p1, - k2, - val, - strlen (val) + 1, - GNUNET_TIME_UNIT_FOREVER_ABS, - GNUNET_PEERSTORE_STOREOPTION_REPLACE, - NULL, - NULL); - GNUNET_PEERSTORE_store (h, - ss, - &p2, - k3, - val, - strlen (val) + 1, - GNUNET_TIME_UNIT_FOREVER_ABS, - GNUNET_PEERSTORE_STOREOPTION_REPLACE, - NULL, - NULL); - ic = GNUNET_PEERSTORE_iterate (h, - ss, - &p1, - k1, - &iter1_cb, NULL); + h = GNUNET_PEERSTORE_connect(cfg); + GNUNET_assert(NULL != h); + memset(&p1, 1, sizeof(p1)); + memset(&p2, 2, sizeof(p2)); + GNUNET_PEERSTORE_store(h, + ss, + &p1, + k1, + val, + strlen(val) + 1, + GNUNET_TIME_UNIT_FOREVER_ABS, + GNUNET_PEERSTORE_STOREOPTION_REPLACE, + NULL, + NULL); + GNUNET_PEERSTORE_store(h, + ss, + &p1, + k2, + val, + strlen(val) + 1, + GNUNET_TIME_UNIT_FOREVER_ABS, + GNUNET_PEERSTORE_STOREOPTION_REPLACE, + NULL, + NULL); + GNUNET_PEERSTORE_store(h, + ss, + &p2, + k3, + val, + strlen(val) + 1, + GNUNET_TIME_UNIT_FOREVER_ABS, + GNUNET_PEERSTORE_STOREOPTION_REPLACE, + NULL, + NULL); + ic = GNUNET_PEERSTORE_iterate(h, + ss, + &p1, + k1, + &iter1_cb, NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { if (0 != - GNUNET_TESTING_service_run ("test-gnunet-peerstore", "peerstore", - "test_peerstore_api_data.conf", &run, NULL)) + GNUNET_TESTING_service_run("test-gnunet-peerstore", "peerstore", + "test_peerstore_api_data.conf", &run, NULL)) return 1; return ok; } diff --git a/src/peerstore/test_peerstore_api_store.c b/src/peerstore/test_peerstore_api_store.c index cecf13e05..f557aafa5 100644 --- a/src/peerstore/test_peerstore_api_store.c +++ b/src/peerstore/test_peerstore_api_store.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerstore/test_peerstore_api_store.c * @brief testcase for peerstore store operation @@ -41,40 +41,40 @@ static int count = 0; static void -test3_cont2 (void *cls, - const struct GNUNET_PEERSTORE_Record *record, - const char *emsg) +test3_cont2(void *cls, + const struct GNUNET_PEERSTORE_Record *record, + const char *emsg) { if (NULL != emsg) return; if (NULL != record) - { - GNUNET_assert ((strlen (val3) + 1) == record->value_size); - GNUNET_assert (0 == strcmp ((char *) val3, - (char *) record->value)); - count++; - return; - } - GNUNET_assert (count == 1); + { + GNUNET_assert((strlen(val3) + 1) == record->value_size); + GNUNET_assert(0 == strcmp((char *)val3, + (char *)record->value)); + count++; + return; + } + GNUNET_assert(count == 1); ok = 0; - GNUNET_PEERSTORE_disconnect (h, GNUNET_YES); - GNUNET_SCHEDULER_shutdown (); + GNUNET_PEERSTORE_disconnect(h, GNUNET_YES); + GNUNET_SCHEDULER_shutdown(); } static void -test3_cont (void *cls, - int success) +test3_cont(void *cls, + int success) { if (GNUNET_YES != success) return; count = 0; - GNUNET_PEERSTORE_iterate (h, - subsystem, - &pid, - key, - &test3_cont2, - NULL); + GNUNET_PEERSTORE_iterate(h, + subsystem, + &pid, + key, + &test3_cont2, + NULL); } @@ -82,54 +82,54 @@ test3_cont (void *cls, * Replace the previous 2 records */ static void -test3 () +test3() { - GNUNET_PEERSTORE_store (h, - subsystem, - &pid, - key, - val3, - strlen (val3) + 1, - GNUNET_TIME_UNIT_FOREVER_ABS, - GNUNET_PEERSTORE_STOREOPTION_REPLACE, - &test3_cont, - NULL); + GNUNET_PEERSTORE_store(h, + subsystem, + &pid, + key, + val3, + strlen(val3) + 1, + GNUNET_TIME_UNIT_FOREVER_ABS, + GNUNET_PEERSTORE_STOREOPTION_REPLACE, + &test3_cont, + NULL); } static void -test2_cont2 (void *cls, - const struct GNUNET_PEERSTORE_Record *record, - const char *emsg) +test2_cont2(void *cls, + const struct GNUNET_PEERSTORE_Record *record, + const char *emsg) { if (NULL != emsg) return; if (NULL != record) - { - GNUNET_assert (((strlen (val1) + 1) == record->value_size) || - ((strlen (val2) + 1) == record->value_size)); - GNUNET_assert ((0 == strcmp ((char *) val1, (char *) record->value)) || - (0 == strcmp ((char *) val2, (char *) record->value))); - count++; - return; - } - GNUNET_assert (count == 2); + { + GNUNET_assert(((strlen(val1) + 1) == record->value_size) || + ((strlen(val2) + 1) == record->value_size)); + GNUNET_assert((0 == strcmp((char *)val1, (char *)record->value)) || + (0 == strcmp((char *)val2, (char *)record->value))); + count++; + return; + } + GNUNET_assert(count == 2); count = 0; - test3 (); + test3(); } static void -test2_cont (void *cls, int success) +test2_cont(void *cls, int success) { if (GNUNET_YES != success) return; count = 0; - GNUNET_PEERSTORE_iterate (h, - subsystem, - &pid, key, - &test2_cont2, - NULL); + GNUNET_PEERSTORE_iterate(h, + subsystem, + &pid, key, + &test2_cont2, + NULL); } @@ -137,53 +137,53 @@ test2_cont (void *cls, int success) * Test storing a second value with the same key */ void -test2 () +test2() { - GNUNET_PEERSTORE_store (h, - subsystem, - &pid, - key, - val2, - strlen (val2) + 1, - GNUNET_TIME_UNIT_FOREVER_ABS, - GNUNET_PEERSTORE_STOREOPTION_MULTIPLE, - &test2_cont, - NULL); + GNUNET_PEERSTORE_store(h, + subsystem, + &pid, + key, + val2, + strlen(val2) + 1, + GNUNET_TIME_UNIT_FOREVER_ABS, + GNUNET_PEERSTORE_STOREOPTION_MULTIPLE, + &test2_cont, + NULL); } static void -test1_cont2 (void *cls, - const struct GNUNET_PEERSTORE_Record *record, - const char *emsg) +test1_cont2(void *cls, + const struct GNUNET_PEERSTORE_Record *record, + const char *emsg) { if (NULL != emsg) return; if (NULL != record) - { - GNUNET_assert ((strlen (val1) + 1) == record->value_size); - GNUNET_assert (0 == strcmp ((char *) val1, (char *) record->value)); - count++; - return; - } - GNUNET_assert (count == 1); + { + GNUNET_assert((strlen(val1) + 1) == record->value_size); + GNUNET_assert(0 == strcmp((char *)val1, (char *)record->value)); + count++; + return; + } + GNUNET_assert(count == 1); count = 0; - test2 (); + test2(); } static void -test1_cont (void *cls, int success) +test1_cont(void *cls, int success) { if (GNUNET_YES != success) return; count = 0; - GNUNET_PEERSTORE_iterate (h, - subsystem, - &pid, - key, - &test1_cont2, - NULL); + GNUNET_PEERSTORE_iterate(h, + subsystem, + &pid, + key, + &test1_cont2, + NULL); } @@ -191,40 +191,40 @@ test1_cont (void *cls, int success) * Store a single record */ static void -test1 () +test1() { - GNUNET_PEERSTORE_store (h, - subsystem, - &pid, - key, - val1, - strlen (val1) + 1, - GNUNET_TIME_UNIT_FOREVER_ABS, - GNUNET_PEERSTORE_STOREOPTION_REPLACE, - &test1_cont, - NULL); + GNUNET_PEERSTORE_store(h, + subsystem, + &pid, + key, + val1, + strlen(val1) + 1, + GNUNET_TIME_UNIT_FOREVER_ABS, + GNUNET_PEERSTORE_STOREOPTION_REPLACE, + &test1_cont, + NULL); } static void -run (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { - h = GNUNET_PEERSTORE_connect (cfg); - GNUNET_assert (NULL != h); - memset (&pid, 1, sizeof (pid)); - test1 (); + h = GNUNET_PEERSTORE_connect(cfg); + GNUNET_assert(NULL != h); + memset(&pid, 1, sizeof(pid)); + test1(); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { if (0 != - GNUNET_TESTING_service_run ("test-gnunet-peerstore", - "peerstore", - "test_peerstore_api_data.conf", - &run, NULL)) + GNUNET_TESTING_service_run("test-gnunet-peerstore", + "peerstore", + "test_peerstore_api_data.conf", + &run, NULL)) return 1; return ok; } diff --git a/src/peerstore/test_peerstore_api_sync.c b/src/peerstore/test_peerstore_api_sync.c index 6fe12335e..7df4778be 100644 --- a/src/peerstore/test_peerstore_api_sync.c +++ b/src/peerstore/test_peerstore_api_sync.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerstore/test_peerstore_api_sync.c * @brief testcase for peerstore sync-on-disconnect feature. Stores @@ -80,22 +80,22 @@ static const char *val = "test_peerstore_api_store_val"; * @return #GNUNET_YES (all good, continue) */ static void -iterate_cb (void *cls, - const struct GNUNET_PEERSTORE_Record *record, - const char *emsg) +iterate_cb(void *cls, + const struct GNUNET_PEERSTORE_Record *record, + const char *emsg) { const char *rec_val; - GNUNET_break (NULL == emsg); + GNUNET_break(NULL == emsg); if (NULL == record) - { - GNUNET_PEERSTORE_disconnect (h, - GNUNET_NO); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_PEERSTORE_disconnect(h, + GNUNET_NO); + GNUNET_SCHEDULER_shutdown(); + return; + } rec_val = record->value; - GNUNET_break (0 == strcmp (rec_val, val)); + GNUNET_break(0 == strcmp(rec_val, val)); ok = 0; } @@ -107,14 +107,14 @@ iterate_cb (void *cls, * @param cls NULL */ static void -test_cont (void *cls) +test_cont(void *cls) { - h = GNUNET_PEERSTORE_connect (cfg); - GNUNET_PEERSTORE_iterate (h, - subsystem, - &pid, key, - &iterate_cb, - NULL); + h = GNUNET_PEERSTORE_connect(cfg); + GNUNET_PEERSTORE_iterate(h, + subsystem, + &pid, key, + &iterate_cb, + NULL); } @@ -122,28 +122,28 @@ test_cont (void *cls) * Actually run the test. */ static void -test1 () +test1() { - h = GNUNET_PEERSTORE_connect (cfg); - GNUNET_PEERSTORE_store (h, - subsystem, - &pid, - key, - val, strlen (val) + 1, - GNUNET_TIME_UNIT_FOREVER_ABS, - GNUNET_PEERSTORE_STOREOPTION_REPLACE, - NULL, NULL); - GNUNET_PEERSTORE_disconnect (h, - GNUNET_YES); + h = GNUNET_PEERSTORE_connect(cfg); + GNUNET_PEERSTORE_store(h, + subsystem, + &pid, + key, + val, strlen(val) + 1, + GNUNET_TIME_UNIT_FOREVER_ABS, + GNUNET_PEERSTORE_STOREOPTION_REPLACE, + NULL, NULL); + GNUNET_PEERSTORE_disconnect(h, + GNUNET_YES); h = NULL; /* We need to wait a little bit to give the disconnect a chance to actually finish the operation; otherwise, the test may fail non-deterministically if the new connection is faster than the cleanup routine of the old one. */ - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &test_cont, - NULL); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &test_cont, + NULL); } @@ -155,29 +155,29 @@ test1 () * @param peer handle to our peer (unused) */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_TESTING_Peer *peer) { cfg = c; - memset (&pid, 1, sizeof (pid)); - test1 (); + memset(&pid, 1, sizeof(pid)); + test1(); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { if (0 != - GNUNET_TESTING_service_run ("test-gnunet-peerstore-sync", - "peerstore", - "test_peerstore_api_data.conf", - &run, NULL)) + GNUNET_TESTING_service_run("test-gnunet-peerstore-sync", + "peerstore", + "test_peerstore_api_data.conf", + &run, NULL)) return 1; if (0 != ok) - fprintf (stderr, - "Test failed: %d\n", - ok); + fprintf(stderr, + "Test failed: %d\n", + ok); return ok; } diff --git a/src/peerstore/test_peerstore_api_watch.c b/src/peerstore/test_peerstore_api_watch.c index 9f933f584..1e097ad42 100644 --- a/src/peerstore/test_peerstore_api_watch.c +++ b/src/peerstore/test_peerstore_api_watch.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file peerstore/test_peerstore_api_watch.c * @brief testcase for peerstore watch functionality @@ -39,61 +39,61 @@ static char *val = "test_peerstore_api_watch_val"; static void -watch_cb (void *cls, - const struct GNUNET_PEERSTORE_Record *record, - const char *emsg) +watch_cb(void *cls, + const struct GNUNET_PEERSTORE_Record *record, + const char *emsg) { - GNUNET_assert (NULL == emsg); - GNUNET_assert (0 == strcmp (val, - (char *) record->value)); + GNUNET_assert(NULL == emsg); + GNUNET_assert(0 == strcmp(val, + (char *)record->value)); ok = 0; - GNUNET_PEERSTORE_disconnect (h, - GNUNET_NO); - GNUNET_SCHEDULER_shutdown (); + GNUNET_PEERSTORE_disconnect(h, + GNUNET_NO); + GNUNET_SCHEDULER_shutdown(); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct GNUNET_PeerIdentity p; - h = GNUNET_PEERSTORE_connect (cfg); - GNUNET_assert (NULL != h); - memset (&p, - 4, - sizeof (p)); - GNUNET_PEERSTORE_watch (h, - ss, - &p, - k, - &watch_cb, - NULL); - GNUNET_PEERSTORE_store (h, - ss, - &p, - k, - val, - strlen (val) + 1, - GNUNET_TIME_UNIT_FOREVER_ABS, - GNUNET_PEERSTORE_STOREOPTION_REPLACE, - NULL, - NULL); + h = GNUNET_PEERSTORE_connect(cfg); + GNUNET_assert(NULL != h); + memset(&p, + 4, + sizeof(p)); + GNUNET_PEERSTORE_watch(h, + ss, + &p, + k, + &watch_cb, + NULL); + GNUNET_PEERSTORE_store(h, + ss, + &p, + k, + val, + strlen(val) + 1, + GNUNET_TIME_UNIT_FOREVER_ABS, + GNUNET_PEERSTORE_STOREOPTION_REPLACE, + NULL, + NULL); } int -main (int argc, - char *argv[]) +main(int argc, + char *argv[]) { if (0 != - GNUNET_TESTING_service_run ("test-gnunet-peerstore", - "peerstore", - "test_peerstore_api_data.conf", - &run, - NULL)) + GNUNET_TESTING_service_run("test-gnunet-peerstore", + "peerstore", + "test_peerstore_api_data.conf", + &run, + NULL)) return 1; return ok; } diff --git a/src/peerstore/test_plugin_peerstore.c b/src/peerstore/test_plugin_peerstore.c index 24b5723ff..0664659a4 100644 --- a/src/peerstore/test_plugin_peerstore.c +++ b/src/peerstore/test_plugin_peerstore.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /* * @file namestore/test_plugin_namestore.c * @brief Test for the namestore plugins @@ -48,17 +48,17 @@ static struct GNUNET_PeerIdentity p1; * @param api api to unload */ static void -unload_plugin (struct GNUNET_PEERSTORE_PluginFunctions *api) +unload_plugin(struct GNUNET_PEERSTORE_PluginFunctions *api) { char *libname; - GNUNET_asprintf (&libname, - "libgnunet_plugin_peer_%s", - plugin_name); - GNUNET_break (NULL == - GNUNET_PLUGIN_unload (libname, - api)); - GNUNET_free (libname); + GNUNET_asprintf(&libname, + "libgnunet_plugin_peer_%s", + plugin_name); + GNUNET_break(NULL == + GNUNET_PLUGIN_unload(libname, + api)); + GNUNET_free(libname); } @@ -69,124 +69,123 @@ unload_plugin (struct GNUNET_PEERSTORE_PluginFunctions *api) * @return NULL on error */ static struct GNUNET_PEERSTORE_PluginFunctions * -load_plugin (const struct GNUNET_CONFIGURATION_Handle *cfg) +load_plugin(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_PEERSTORE_PluginFunctions *ret; char *libname; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - _("Loading `%s' peer plugin\n"), - plugin_name); - GNUNET_asprintf (&libname, - "libgnunet_plugin_peerstore_%s", - plugin_name); - if (NULL == (ret = GNUNET_PLUGIN_load (libname, - (void*) cfg))) - { - fprintf (stderr, - "Failed to load plugin `%s'!\n", + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + _("Loading `%s' peer plugin\n"), plugin_name); - GNUNET_free (libname); - return NULL; - } - GNUNET_free (libname); + GNUNET_asprintf(&libname, + "libgnunet_plugin_peerstore_%s", + plugin_name); + if (NULL == (ret = GNUNET_PLUGIN_load(libname, + (void*)cfg))) + { + fprintf(stderr, + "Failed to load plugin `%s'!\n", + plugin_name); + GNUNET_free(libname); + return NULL; + } + GNUNET_free(libname); return ret; } static void -test_record (void *cls, - const struct GNUNET_PEERSTORE_Record *record, - const char *error) +test_record(void *cls, + const struct GNUNET_PEERSTORE_Record *record, + const char *error) { const struct GNUNET_PeerIdentity *id = cls; const char* testval = "test_val"; if (NULL == record) - { - unload_plugin (psp); - return; - } - GNUNET_assert (0 == memcmp (&record->peer, - id, - sizeof (struct GNUNET_PeerIdentity))); - GNUNET_assert (0 == strcmp ("subsys", - record->sub_system)); - GNUNET_assert (0 == strcmp ("key", - record->key)); - GNUNET_assert (0 == memcmp (testval, - record->value, - strlen (testval))); + { + unload_plugin(psp); + return; + } + GNUNET_assert(0 == memcmp(&record->peer, + id, + sizeof(struct GNUNET_PeerIdentity))); + GNUNET_assert(0 == strcmp("subsys", + record->sub_system)); + GNUNET_assert(0 == strcmp("key", + record->key)); + GNUNET_assert(0 == memcmp(testval, + record->value, + strlen(testval))); ok = 0; } static void -get_record (struct GNUNET_PEERSTORE_PluginFunctions *psp, - const struct GNUNET_PeerIdentity *identity) +get_record(struct GNUNET_PEERSTORE_PluginFunctions *psp, + const struct GNUNET_PeerIdentity *identity) { - GNUNET_assert (GNUNET_OK == - psp->iterate_records (psp->cls, - "subsys", - identity, - "key", - &test_record, - (void*)identity)); + GNUNET_assert(GNUNET_OK == + psp->iterate_records(psp->cls, + "subsys", + identity, + "key", + &test_record, + (void*)identity)); } static void -store_cont (void *cls, - int status) +store_cont(void *cls, + int status) { - GNUNET_assert (GNUNET_OK == status); - get_record (psp, - &p1); + GNUNET_assert(GNUNET_OK == status); + get_record(psp, + &p1); } static void -put_record (struct GNUNET_PEERSTORE_PluginFunctions *psp, - const struct GNUNET_PeerIdentity *identity) +put_record(struct GNUNET_PEERSTORE_PluginFunctions *psp, + const struct GNUNET_PeerIdentity *identity) { - GNUNET_assert (GNUNET_OK == - psp->store_record (psp->cls, - "subsys", - identity, - "key", - "test_value", - strlen ("test_value"), - GNUNET_TIME_absolute_get (), - GNUNET_PEERSTORE_STOREOPTION_REPLACE, - &store_cont, - NULL)); + GNUNET_assert(GNUNET_OK == + psp->store_record(psp->cls, + "subsys", + identity, + "key", + "test_value", + strlen("test_value"), + GNUNET_TIME_absolute_get(), + GNUNET_PEERSTORE_STOREOPTION_REPLACE, + &store_cont, + NULL)); } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *cfg) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - ok = 1; - psp = load_plugin (cfg); + psp = load_plugin(cfg); if (NULL == psp) - { - fprintf (stderr, - "%s", - "Failed to initialize peerstore. Database likely not setup, skipping test.\n"); - return; - } - memset (&p1, 1, sizeof (p1)); - put_record (psp, - &p1); + { + fprintf(stderr, + "%s", + "Failed to initialize peerstore. Database likely not setup, skipping test.\n"); + return; + } + memset(&p1, 1, sizeof(p1)); + put_record(psp, + &p1); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { char cfg_name[PATH_MAX]; char *const xargv[] = { @@ -199,25 +198,25 @@ main (int argc, char *argv[]) GNUNET_GETOPT_OPTION_END }; - GNUNET_log_setup ("test-plugin-peerstore", - "WARNING", - NULL); - plugin_name = GNUNET_TESTING_get_testname_from_underscore (argv[0]); - GNUNET_snprintf (cfg_name, - sizeof (cfg_name), - "test_plugin_peerstore_%s.conf", - plugin_name); - GNUNET_PROGRAM_run ((sizeof (xargv) / sizeof (char *)) - 1, - xargv, - "test-plugin-peerstore", - "nohelp", - options, - &run, - NULL); + GNUNET_log_setup("test-plugin-peerstore", + "WARNING", + NULL); + plugin_name = GNUNET_TESTING_get_testname_from_underscore(argv[0]); + GNUNET_snprintf(cfg_name, + sizeof(cfg_name), + "test_plugin_peerstore_%s.conf", + plugin_name); + GNUNET_PROGRAM_run((sizeof(xargv) / sizeof(char *)) - 1, + xargv, + "test-plugin-peerstore", + "nohelp", + options, + &run, + NULL); if (ok != 0) - fprintf (stderr, - "Missed some testcases: %d\n", - ok); + fprintf(stderr, + "Missed some testcases: %d\n", + ok); return ok; } diff --git a/src/pq/pq.c b/src/pq/pq.c index df5ef17ad..a581b4277 100644 --- a/src/pq/pq.c +++ b/src/pq/pq.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2014, 2015, 2016 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2014, 2015, 2016 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file pq/pq.c * @brief helper functions for libpq (PostGres) interactions @@ -38,20 +38,20 @@ * @return postgres result */ PGresult * -GNUNET_PQ_exec_prepared (PGconn *db_conn, - const char *name, - const struct GNUNET_PQ_QueryParam *params) +GNUNET_PQ_exec_prepared(PGconn *db_conn, + const char *name, + const struct GNUNET_PQ_QueryParam *params) { unsigned int len; unsigned int i; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Running prepared statement `%s' on %p\n", - name, - db_conn); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Running prepared statement `%s' on %p\n", + name, + db_conn); /* count the number of parameters */ len = 0; - for (i=0;0 != params[i].num_params;i++) + for (i = 0; 0 != params[i].num_params; i++) len += params[i].num_params; /* new scope to allow stack allocation without alloca */ @@ -70,42 +70,42 @@ GNUNET_PQ_exec_prepared (PGconn *db_conn, off = 0; soff = 0; - for (i=0;0 != params[i].num_params;i++) - { - const struct GNUNET_PQ_QueryParam *x = ¶ms[i]; - - ret = x->conv (x->conv_cls, - x->data, - x->size, - ¶m_values[off], - ¶m_lengths[off], - ¶m_formats[off], - x->num_params, - &scratch[soff], - len - soff); - if (ret < 0) + for (i = 0; 0 != params[i].num_params; i++) { - for (off = 0; off < soff; off++) - GNUNET_free (scratch[off]); - return NULL; + const struct GNUNET_PQ_QueryParam *x = ¶ms[i]; + + ret = x->conv(x->conv_cls, + x->data, + x->size, + ¶m_values[off], + ¶m_lengths[off], + ¶m_formats[off], + x->num_params, + &scratch[soff], + len - soff); + if (ret < 0) + { + for (off = 0; off < soff; off++) + GNUNET_free(scratch[off]); + return NULL; + } + soff += ret; + off += x->num_params; } - soff += ret; - off += x->num_params; - } - GNUNET_assert (off == len); - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "pq", - "Executing prepared SQL statement `%s'\n", - name); - res = PQexecPrepared (db_conn, - name, - len, - (const char **) param_values, - param_lengths, - param_formats, - 1); + GNUNET_assert(off == len); + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "pq", + "Executing prepared SQL statement `%s'\n", + name); + res = PQexecPrepared(db_conn, + name, + len, + (const char **)param_values, + param_lengths, + param_formats, + 1); for (off = 0; off < soff; off++) - GNUNET_free (scratch[off]); + GNUNET_free(scratch[off]); return res; } } @@ -118,14 +118,14 @@ GNUNET_PQ_exec_prepared (PGconn *db_conn, * @param rs reult specification to clean up */ void -GNUNET_PQ_cleanup_result (struct GNUNET_PQ_ResultSpec *rs) +GNUNET_PQ_cleanup_result(struct GNUNET_PQ_ResultSpec *rs) { unsigned int i; - for (i=0; NULL != rs[i].conv; i++) + for (i = 0; NULL != rs[i].conv; i++) if (NULL != rs[i].cleaner) - rs[i].cleaner (rs[i].cls, - rs[i].dst); + rs[i].cleaner(rs[i].cls, + rs[i].dst); } @@ -141,32 +141,32 @@ GNUNET_PQ_cleanup_result (struct GNUNET_PQ_ResultSpec *rs) * #GNUNET_SYSERR if a result was invalid (non-existing field) */ int -GNUNET_PQ_extract_result (PGresult *result, - struct GNUNET_PQ_ResultSpec *rs, - int row) +GNUNET_PQ_extract_result(PGresult *result, + struct GNUNET_PQ_ResultSpec *rs, + int row) { unsigned int i; int ret; - for (i=0; NULL != rs[i].conv; i++) - { - struct GNUNET_PQ_ResultSpec *spec; - - spec = &rs[i]; - ret = spec->conv (spec->cls, - result, - row, - spec->fname, - &spec->dst_size, - spec->dst); - if (GNUNET_OK != ret) + for (i = 0; NULL != rs[i].conv; i++) { - GNUNET_PQ_cleanup_result (rs); - return GNUNET_SYSERR; + struct GNUNET_PQ_ResultSpec *spec; + + spec = &rs[i]; + ret = spec->conv(spec->cls, + result, + row, + spec->fname, + &spec->dst_size, + spec->dst); + if (GNUNET_OK != ret) + { + GNUNET_PQ_cleanup_result(rs); + return GNUNET_SYSERR; + } + if (NULL != spec->result_size) + *spec->result_size = spec->dst_size; } - if (NULL != spec->result_size) - *spec->result_size = spec->dst_size; - } return GNUNET_OK; } diff --git a/src/pq/pq_connect.c b/src/pq/pq_connect.c index a295eb864..2ab049724 100644 --- a/src/pq/pq_connect.c +++ b/src/pq/pq_connect.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2017 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + This file is part of GNUnet + Copyright (C) 2017 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file pq/pq_connect.c * @brief functions to connect to libpq (PostGres) @@ -36,8 +36,8 @@ * @param res information about some libpq event */ static void -pq_notice_receiver_cb (void *arg, - const PGresult *res) +pq_notice_receiver_cb(void *arg, + const PGresult *res) { /* do nothing, intentionally */ } @@ -51,13 +51,13 @@ pq_notice_receiver_cb (void *arg, * @param message information about some libpq event */ static void -pq_notice_processor_cb (void *arg, - const char *message) +pq_notice_processor_cb(void *arg, + const char *message) { - GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, - "pq", - "%s", - message); + GNUNET_log_from(GNUNET_ERROR_TYPE_INFO, + "pq", + "%s", + message); } @@ -70,32 +70,32 @@ pq_notice_processor_cb (void *arg, * @return NULL on error */ PGconn * -GNUNET_PQ_connect (const char *config_str) +GNUNET_PQ_connect(const char *config_str) { PGconn *conn; - conn = PQconnectdb (config_str); - if ( (NULL == conn) || - (CONNECTION_OK != - PQstatus (conn)) ) - { - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "pq", - "Database connection to '%s' failed: %s\n", - config_str, - (NULL != conn) ? - PQerrorMessage (conn) - : "PQconnectdb returned NULL"); - if (NULL != conn) - PQfinish (conn); - return NULL; - } - PQsetNoticeReceiver (conn, - &pq_notice_receiver_cb, + conn = PQconnectdb(config_str); + if ((NULL == conn) || + (CONNECTION_OK != + PQstatus(conn))) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "pq", + "Database connection to '%s' failed: %s\n", + config_str, + (NULL != conn) ? + PQerrorMessage(conn) + : "PQconnectdb returned NULL"); + if (NULL != conn) + PQfinish(conn); + return NULL; + } + PQsetNoticeReceiver(conn, + &pq_notice_receiver_cb, + conn); + PQsetNoticeProcessor(conn, + &pq_notice_processor_cb, conn); - PQsetNoticeProcessor (conn, - &pq_notice_processor_cb, - conn); return conn; } @@ -109,21 +109,21 @@ GNUNET_PQ_connect (const char *config_str) * @return the postgres handle, NULL on error */ PGconn * -GNUNET_PQ_connect_with_cfg (const struct GNUNET_CONFIGURATION_Handle * cfg, - const char *section) +GNUNET_PQ_connect_with_cfg(const struct GNUNET_CONFIGURATION_Handle * cfg, + const char *section) { PGconn *dbh; char *conninfo; /* Open database and precompile statements */ if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - section, - "CONFIG", - &conninfo)) + GNUNET_CONFIGURATION_get_value_string(cfg, + section, + "CONFIG", + &conninfo)) conninfo = NULL; - dbh = GNUNET_PQ_connect (conninfo == NULL ? "" : conninfo); - GNUNET_free_non_null (conninfo); + dbh = GNUNET_PQ_connect(conninfo == NULL ? "" : conninfo); + GNUNET_free_non_null(conninfo); return dbh; } diff --git a/src/pq/pq_eval.c b/src/pq/pq_eval.c index 2beb3475b..0df71e672 100644 --- a/src/pq/pq_eval.c +++ b/src/pq/pq_eval.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2017 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2017 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file pq/pq_eval.c * @brief functions to execute SQL statements with arguments and/or results (PostGres) @@ -57,76 +57,76 @@ * @deprecated (low level, let's see if we can do with just the high-level functions) */ enum GNUNET_DB_QueryStatus -GNUNET_PQ_eval_result (PGconn *connection, - const char *statement_name, - PGresult *result) +GNUNET_PQ_eval_result(PGconn *connection, + const char *statement_name, + PGresult *result) { ExecStatusType est; - est = PQresultStatus (result); - if ( (PGRES_COMMAND_OK != est) && - (PGRES_TUPLES_OK != est) ) - { - const char *sqlstate; - - sqlstate = PQresultErrorField (result, - PG_DIAG_SQLSTATE); - if (NULL == sqlstate) + est = PQresultStatus(result); + if ((PGRES_COMMAND_OK != est) && + (PGRES_TUPLES_OK != est)) { - /* very unexpected... */ - GNUNET_break (0); - return GNUNET_DB_STATUS_HARD_ERROR; - } - if ( (0 == strcmp (sqlstate, + const char *sqlstate; + + sqlstate = PQresultErrorField(result, + PG_DIAG_SQLSTATE); + if (NULL == sqlstate) + { + /* very unexpected... */ + GNUNET_break(0); + return GNUNET_DB_STATUS_HARD_ERROR; + } + if ((0 == strcmp(sqlstate, PQ_DIAG_SQLSTATE_DEADLOCK)) || - (0 == strcmp (sqlstate, - PQ_DIAG_SQLSTATE_SERIALIZATION_FAILURE)) ) - { - /* These two can be retried and have a fair chance of working - the next time */ - GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, - "pq", - "Query `%s' failed with result: %s/%s/%s/%s/%s\n", - statement_name, - PQresultErrorField (result, - PG_DIAG_MESSAGE_PRIMARY), - PQresultErrorField (result, - PG_DIAG_MESSAGE_DETAIL), - PQresultErrorMessage (result), - PQresStatus (PQresultStatus (result)), - PQerrorMessage (connection)); - return GNUNET_DB_STATUS_SOFT_ERROR; - } - if (0 == strcmp (sqlstate, - PQ_DIAG_SQLSTATE_UNIQUE_VIOLATION)) - { - /* Likely no need to retry, INSERT of "same" data. */ - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "pq", - "Query `%s' failed with unique violation: %s/%s/%s/%s/%s\n", - statement_name, - PQresultErrorField (result, - PG_DIAG_MESSAGE_PRIMARY), - PQresultErrorField (result, - PG_DIAG_MESSAGE_DETAIL), - PQresultErrorMessage (result), - PQresStatus (PQresultStatus (result)), - PQerrorMessage (connection)); - return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS; - } - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "pq", - "Query `%s' failed with result: %s/%s/%s/%s/%s\n", - statement_name, - PQresultErrorField (result, + (0 == strcmp(sqlstate, + PQ_DIAG_SQLSTATE_SERIALIZATION_FAILURE))) + { + /* These two can be retried and have a fair chance of working + the next time */ + GNUNET_log_from(GNUNET_ERROR_TYPE_INFO, + "pq", + "Query `%s' failed with result: %s/%s/%s/%s/%s\n", + statement_name, + PQresultErrorField(result, + PG_DIAG_MESSAGE_PRIMARY), + PQresultErrorField(result, + PG_DIAG_MESSAGE_DETAIL), + PQresultErrorMessage(result), + PQresStatus(PQresultStatus(result)), + PQerrorMessage(connection)); + return GNUNET_DB_STATUS_SOFT_ERROR; + } + if (0 == strcmp(sqlstate, + PQ_DIAG_SQLSTATE_UNIQUE_VIOLATION)) + { + /* Likely no need to retry, INSERT of "same" data. */ + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "pq", + "Query `%s' failed with unique violation: %s/%s/%s/%s/%s\n", + statement_name, + PQresultErrorField(result, + PG_DIAG_MESSAGE_PRIMARY), + PQresultErrorField(result, + PG_DIAG_MESSAGE_DETAIL), + PQresultErrorMessage(result), + PQresStatus(PQresultStatus(result)), + PQerrorMessage(connection)); + return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS; + } + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "pq", + "Query `%s' failed with result: %s/%s/%s/%s/%s\n", + statement_name, + PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY), - PQresultErrorField (result, + PQresultErrorField(result, PG_DIAG_MESSAGE_DETAIL), - PQresultErrorMessage (result), - PQresStatus (PQresultStatus (result)), - PQerrorMessage (connection)); - return GNUNET_DB_STATUS_HARD_ERROR; - } + PQresultErrorMessage(result), + PQresStatus(PQresultStatus(result)), + PQerrorMessage(connection)); + return GNUNET_DB_STATUS_HARD_ERROR; + } return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS; } @@ -148,29 +148,29 @@ GNUNET_PQ_eval_result (PGconn *connection, * zero; if INSERT was successful, we return one. */ enum GNUNET_DB_QueryStatus -GNUNET_PQ_eval_prepared_non_select (PGconn *connection, - const char *statement_name, - const struct GNUNET_PQ_QueryParam *params) +GNUNET_PQ_eval_prepared_non_select(PGconn *connection, + const char *statement_name, + const struct GNUNET_PQ_QueryParam *params) { PGresult *result; enum GNUNET_DB_QueryStatus qs; - result = GNUNET_PQ_exec_prepared (connection, - statement_name, - params); - qs = GNUNET_PQ_eval_result (connection, - statement_name, - result); + result = GNUNET_PQ_exec_prepared(connection, + statement_name, + params); + qs = GNUNET_PQ_eval_result(connection, + statement_name, + result); if (GNUNET_DB_STATUS_SUCCESS_NO_RESULTS == qs) - { - const char *tuples; + { + const char *tuples; - /* What an awful API, this function really does return a string */ - tuples = PQcmdTuples (result); - if (NULL != tuples) - qs = strtol (tuples, NULL, 10); - } - PQclear (result); + /* What an awful API, this function really does return a string */ + tuples = PQcmdTuples(result); + if (NULL != tuples) + qs = strtol(tuples, NULL, 10); + } + PQclear(result); return qs; } @@ -191,33 +191,33 @@ GNUNET_PQ_eval_prepared_non_select (PGconn *connection, * codes to `enum GNUNET_DB_QueryStatus`. */ enum GNUNET_DB_QueryStatus -GNUNET_PQ_eval_prepared_multi_select (PGconn *connection, - const char *statement_name, - const struct GNUNET_PQ_QueryParam *params, - GNUNET_PQ_PostgresResultHandler rh, - void *rh_cls) +GNUNET_PQ_eval_prepared_multi_select(PGconn *connection, + const char *statement_name, + const struct GNUNET_PQ_QueryParam *params, + GNUNET_PQ_PostgresResultHandler rh, + void *rh_cls) { PGresult *result; enum GNUNET_DB_QueryStatus qs; unsigned int ret; - result = GNUNET_PQ_exec_prepared (connection, - statement_name, - params); - qs = GNUNET_PQ_eval_result (connection, - statement_name, - result); + result = GNUNET_PQ_exec_prepared(connection, + statement_name, + params); + qs = GNUNET_PQ_eval_result(connection, + statement_name, + result); if (qs < 0) - { - PQclear (result); - return qs; - } - ret = PQntuples (result); + { + PQclear(result); + return qs; + } + ret = PQntuples(result); if (NULL != rh) - rh (rh_cls, - result, - ret); - PQclear (result); + rh(rh_cls, + result, + ret); + PQclear(result); return ret; } @@ -238,46 +238,46 @@ GNUNET_PQ_eval_prepared_multi_select (PGconn *connection, * codes to `enum GNUNET_DB_QueryStatus`. */ enum GNUNET_DB_QueryStatus -GNUNET_PQ_eval_prepared_singleton_select (PGconn *connection, - const char *statement_name, - const struct GNUNET_PQ_QueryParam *params, - struct GNUNET_PQ_ResultSpec *rs) +GNUNET_PQ_eval_prepared_singleton_select(PGconn *connection, + const char *statement_name, + const struct GNUNET_PQ_QueryParam *params, + struct GNUNET_PQ_ResultSpec *rs) { PGresult *result; enum GNUNET_DB_QueryStatus qs; - result = GNUNET_PQ_exec_prepared (connection, - statement_name, - params); - qs = GNUNET_PQ_eval_result (connection, - statement_name, - result); + result = GNUNET_PQ_exec_prepared(connection, + statement_name, + params); + qs = GNUNET_PQ_eval_result(connection, + statement_name, + result); if (qs < 0) - { - PQclear (result); - return qs; - } - if (0 == PQntuples (result)) - { - PQclear (result); - return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS; - } - if (1 != PQntuples (result)) - { - /* more than one result, but there must be at most one */ - GNUNET_break (0); - PQclear (result); - return GNUNET_DB_STATUS_HARD_ERROR; - } + { + PQclear(result); + return qs; + } + if (0 == PQntuples(result)) + { + PQclear(result); + return GNUNET_DB_STATUS_SUCCESS_NO_RESULTS; + } + if (1 != PQntuples(result)) + { + /* more than one result, but there must be at most one */ + GNUNET_break(0); + PQclear(result); + return GNUNET_DB_STATUS_HARD_ERROR; + } if (GNUNET_OK != - GNUNET_PQ_extract_result (result, - rs, - 0)) - { - PQclear (result); - return GNUNET_DB_STATUS_HARD_ERROR; - } - PQclear (result); + GNUNET_PQ_extract_result(result, + rs, + 0)) + { + PQclear(result); + return GNUNET_DB_STATUS_HARD_ERROR; + } + PQclear(result); return GNUNET_DB_STATUS_SUCCESS_ONE_RESULT; } diff --git a/src/pq/pq_exec.c b/src/pq/pq_exec.c index 99eb2b270..6c8002aff 100644 --- a/src/pq/pq_exec.c +++ b/src/pq/pq_exec.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2017 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2017 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file pq/pq_exec.c * @brief functions to execute plain SQL statements (PostGres) @@ -34,7 +34,7 @@ * @return initialized struct */ struct GNUNET_PQ_ExecuteStatement -GNUNET_PQ_make_execute (const char *sql) +GNUNET_PQ_make_execute(const char *sql) { struct GNUNET_PQ_ExecuteStatement es = { .sql = sql, @@ -53,7 +53,7 @@ GNUNET_PQ_make_execute (const char *sql) * @return initialized struct */ struct GNUNET_PQ_ExecuteStatement -GNUNET_PQ_make_try_execute (const char *sql) +GNUNET_PQ_make_try_execute(const char *sql) { struct GNUNET_PQ_ExecuteStatement es = { .sql = sql, @@ -74,38 +74,38 @@ GNUNET_PQ_make_try_execute (const char *sql) * #GNUNET_SYSERR on error */ int -GNUNET_PQ_exec_statements (PGconn *connection, - const struct GNUNET_PQ_ExecuteStatement *es) +GNUNET_PQ_exec_statements(PGconn *connection, + const struct GNUNET_PQ_ExecuteStatement *es) { - for (unsigned int i=0; NULL != es[i].sql; i++) - { - PGresult *result; - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Running statement `%s' on %p\n", - es[i].sql, - connection); - result = PQexec (connection, - es[i].sql); - if ( (GNUNET_NO == es[i].ignore_errors) && - (PGRES_COMMAND_OK != PQresultStatus (result)) ) + for (unsigned int i = 0; NULL != es[i].sql; i++) { - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, - "pq", - "Failed to execute `%s': %s/%s/%s/%s/%s", - es[i].sql, - PQresultErrorField (result, - PG_DIAG_MESSAGE_PRIMARY), - PQresultErrorField (result, - PG_DIAG_MESSAGE_DETAIL), - PQresultErrorMessage (result), - PQresStatus (PQresultStatus (result)), - PQerrorMessage (connection)); - PQclear (result); - return GNUNET_SYSERR; + PGresult *result; + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Running statement `%s' on %p\n", + es[i].sql, + connection); + result = PQexec(connection, + es[i].sql); + if ((GNUNET_NO == es[i].ignore_errors) && + (PGRES_COMMAND_OK != PQresultStatus(result))) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, + "pq", + "Failed to execute `%s': %s/%s/%s/%s/%s", + es[i].sql, + PQresultErrorField(result, + PG_DIAG_MESSAGE_PRIMARY), + PQresultErrorField(result, + PG_DIAG_MESSAGE_DETAIL), + PQresultErrorMessage(result), + PQresStatus(PQresultStatus(result)), + PQerrorMessage(connection)); + PQclear(result); + return GNUNET_SYSERR; + } + PQclear(result); } - PQclear (result); - } return GNUNET_OK; } diff --git a/src/pq/pq_prepare.c b/src/pq/pq_prepare.c index 9a8e4e76f..9899b65bb 100644 --- a/src/pq/pq_prepare.c +++ b/src/pq/pq_prepare.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - Copyright (C) 2017 GNUnet e.V. + This file is part of GNUnet + Copyright (C) 2017 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file pq/pq_prepare.c * @brief functions to connect to libpq (PostGres) @@ -36,9 +36,9 @@ * @return initialized struct */ struct GNUNET_PQ_PreparedStatement -GNUNET_PQ_make_prepare (const char *name, - const char *sql, - unsigned int num_args) +GNUNET_PQ_make_prepare(const char *name, + const char *sql, + unsigned int num_args) { struct GNUNET_PQ_PreparedStatement ps = { .name = name, @@ -60,36 +60,36 @@ GNUNET_PQ_make_prepare (const char *name, * #GNUNET_SYSERR on error */ int -GNUNET_PQ_prepare_statements (PGconn *connection, - const struct GNUNET_PQ_PreparedStatement *ps) +GNUNET_PQ_prepare_statements(PGconn *connection, + const struct GNUNET_PQ_PreparedStatement *ps) { - for (unsigned int i=0;NULL != ps[i].name;i++) - { - PGresult *ret; - - GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, - "pq", - "Preparing SQL statement `%s' as `%s'\n", - ps[i].sql, - ps[i].name); - ret = PQprepare (connection, - ps[i].name, - ps[i].sql, - ps[i].num_arguments, - NULL); - if (PGRES_COMMAND_OK != PQresultStatus (ret)) + for (unsigned int i = 0; NULL != ps[i].name; i++) { - GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, - "pq", - _("PQprepare (`%s' as `%s') failed with error: %s\n"), - ps[i].sql, - ps[i].name, - PQerrorMessage (connection)); - PQclear (ret); - return GNUNET_SYSERR; + PGresult *ret; + + GNUNET_log_from(GNUNET_ERROR_TYPE_DEBUG, + "pq", + "Preparing SQL statement `%s' as `%s'\n", + ps[i].sql, + ps[i].name); + ret = PQprepare(connection, + ps[i].name, + ps[i].sql, + ps[i].num_arguments, + NULL); + if (PGRES_COMMAND_OK != PQresultStatus(ret)) + { + GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, + "pq", + _("PQprepare (`%s' as `%s') failed with error: %s\n"), + ps[i].sql, + ps[i].name, + PQerrorMessage(connection)); + PQclear(ret); + return GNUNET_SYSERR; + } + PQclear(ret); } - PQclear (ret); - } return GNUNET_OK; } diff --git a/src/pq/pq_query_helper.c b/src/pq/pq_query_helper.c index a6ce3c5d8..c3b86ee3d 100644 --- a/src/pq/pq_query_helper.c +++ b/src/pq/pq_query_helper.c @@ -1,22 +1,22 @@ - /* - This file is part of GNUnet - Copyright (C) 2014, 2015, 2016 GNUnet e.V. - - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. - - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - - SPDX-License-Identifier: AGPL3.0-or-later -*/ +/* + This file is part of GNUnet + Copyright (C) 2014, 2015, 2016 GNUnet e.V. + + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. + + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + + SPDX-License-Identifier: AGPL3.0-or-later + */ /** * @file pq/pq_query_helper.c * @brief functions to initialize parameter arrays @@ -42,22 +42,22 @@ * @return -1 on error, number of offsets used in @a scratch otherwise */ static int -qconv_fixed (void *cls, - const void *data, - size_t data_len, - void *param_values[], - int param_lengths[], - int param_formats[], - unsigned int param_length, - void *scratch[], - unsigned int scratch_length) +qconv_fixed(void *cls, + const void *data, + size_t data_len, + void *param_values[], + int param_lengths[], + int param_formats[], + unsigned int param_length, + void *scratch[], + unsigned int scratch_length) { - (void) scratch; - (void) scratch_length; - GNUNET_break (NULL == cls); + (void)scratch; + (void)scratch_length; + GNUNET_break(NULL == cls); if (1 != param_length) return -1; - param_values[0] = (void *) data; + param_values[0] = (void *)data; param_lengths[0] = data_len; param_formats[0] = 1; return 0; @@ -72,11 +72,12 @@ qconv_fixed (void *cls, * @oaran ptr_size number of bytes in @a ptr */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_fixed_size (const void *ptr, - size_t ptr_size) +GNUNET_PQ_query_param_fixed_size(const void *ptr, + size_t ptr_size) { struct GNUNET_PQ_QueryParam res = - { &qconv_fixed, NULL, ptr, ptr_size, 1 }; + { &qconv_fixed, NULL, ptr, ptr_size, 1 }; + return res; } @@ -87,9 +88,9 @@ GNUNET_PQ_query_param_fixed_size (const void *ptr, * @param ptr pointer to the string query parameter to pass */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_string (const char *ptr) +GNUNET_PQ_query_param_string(const char *ptr) { - return GNUNET_PQ_query_param_fixed_size (ptr, strlen (ptr)); + return GNUNET_PQ_query_param_fixed_size(ptr, strlen(ptr)); } @@ -108,29 +109,29 @@ GNUNET_PQ_query_param_string (const char *ptr) * @return -1 on error, number of offsets used in @a scratch otherwise */ static int -qconv_uint16 (void *cls, - const void *data, - size_t data_len, - void *param_values[], - int param_lengths[], - int param_formats[], - unsigned int param_length, - void *scratch[], - unsigned int scratch_length) +qconv_uint16(void *cls, + const void *data, + size_t data_len, + void *param_values[], + int param_lengths[], + int param_formats[], + unsigned int param_length, + void *scratch[], + unsigned int scratch_length) { const uint16_t *u_hbo = data; uint16_t *u_nbo; - (void) scratch; - (void) scratch_length; - GNUNET_break (NULL == cls); + (void)scratch; + (void)scratch_length; + GNUNET_break(NULL == cls); if (1 != param_length) return -1; - u_nbo = GNUNET_new (uint16_t); + u_nbo = GNUNET_new(uint16_t); scratch[0] = u_nbo; - *u_nbo = htons (*u_hbo); - param_values[0] = (void *) u_nbo; - param_lengths[0] = sizeof (uint16_t); + *u_nbo = htons(*u_hbo); + param_values[0] = (void *)u_nbo; + param_lengths[0] = sizeof(uint16_t); param_formats[0] = 1; return 1; } @@ -142,10 +143,11 @@ qconv_uint16 (void *cls, * @param x pointer to the query parameter to pass */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_uint16 (const uint16_t *x) +GNUNET_PQ_query_param_uint16(const uint16_t *x) { struct GNUNET_PQ_QueryParam res = - { &qconv_uint16, NULL, x, sizeof (*x), 1 }; + { &qconv_uint16, NULL, x, sizeof(*x), 1 }; + return res; } @@ -165,29 +167,29 @@ GNUNET_PQ_query_param_uint16 (const uint16_t *x) * @return -1 on error, number of offsets used in @a scratch otherwise */ static int -qconv_uint32 (void *cls, - const void *data, - size_t data_len, - void *param_values[], - int param_lengths[], - int param_formats[], - unsigned int param_length, - void *scratch[], - unsigned int scratch_length) +qconv_uint32(void *cls, + const void *data, + size_t data_len, + void *param_values[], + int param_lengths[], + int param_formats[], + unsigned int param_length, + void *scratch[], + unsigned int scratch_length) { const uint32_t *u_hbo = data; uint32_t *u_nbo; - (void) scratch; - (void) scratch_length; - GNUNET_break (NULL == cls); + (void)scratch; + (void)scratch_length; + GNUNET_break(NULL == cls); if (1 != param_length) return -1; - u_nbo = GNUNET_new (uint32_t); + u_nbo = GNUNET_new(uint32_t); scratch[0] = u_nbo; - *u_nbo = htonl (*u_hbo); - param_values[0] = (void *) u_nbo; - param_lengths[0] = sizeof (uint32_t); + *u_nbo = htonl(*u_hbo); + param_values[0] = (void *)u_nbo; + param_lengths[0] = sizeof(uint32_t); param_formats[0] = 1; return 1; } @@ -199,10 +201,11 @@ qconv_uint32 (void *cls, * @param x pointer to the query parameter to pass */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_uint32 (const uint32_t *x) +GNUNET_PQ_query_param_uint32(const uint32_t *x) { struct GNUNET_PQ_QueryParam res = - { &qconv_uint32, NULL, x, sizeof (*x), 1 }; + { &qconv_uint32, NULL, x, sizeof(*x), 1 }; + return res; } @@ -222,29 +225,29 @@ GNUNET_PQ_query_param_uint32 (const uint32_t *x) * @return -1 on error, number of offsets used in @a scratch otherwise */ static int -qconv_uint64 (void *cls, - const void *data, - size_t data_len, - void *param_values[], - int param_lengths[], - int param_formats[], - unsigned int param_length, - void *scratch[], - unsigned int scratch_length) +qconv_uint64(void *cls, + const void *data, + size_t data_len, + void *param_values[], + int param_lengths[], + int param_formats[], + unsigned int param_length, + void *scratch[], + unsigned int scratch_length) { const uint64_t *u_hbo = data; uint64_t *u_nbo; - (void) scratch; - (void) scratch_length; - GNUNET_break (NULL == cls); + (void)scratch; + (void)scratch_length; + GNUNET_break(NULL == cls); if (1 != param_length) return -1; - u_nbo = GNUNET_new (uint64_t); + u_nbo = GNUNET_new(uint64_t); scratch[0] = u_nbo; - *u_nbo = GNUNET_htonll (*u_hbo); - param_values[0] = (void *) u_nbo; - param_lengths[0] = sizeof (uint64_t); + *u_nbo = GNUNET_htonll(*u_hbo); + param_values[0] = (void *)u_nbo; + param_lengths[0] = sizeof(uint64_t); param_formats[0] = 1; return 1; } @@ -256,10 +259,11 @@ qconv_uint64 (void *cls, * @param x pointer to the query parameter to pass */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_uint64 (const uint64_t *x) +GNUNET_PQ_query_param_uint64(const uint64_t *x) { struct GNUNET_PQ_QueryParam res = - { &qconv_uint64, NULL, x, sizeof (*x), 1 }; + { &qconv_uint64, NULL, x, sizeof(*x), 1 }; + return res; } @@ -279,27 +283,27 @@ GNUNET_PQ_query_param_uint64 (const uint64_t *x) * @return -1 on error, number of offsets used in @a scratch otherwise */ static int -qconv_rsa_public_key (void *cls, - const void *data, - size_t data_len, - void *param_values[], - int param_lengths[], - int param_formats[], - unsigned int param_length, - void *scratch[], - unsigned int scratch_length) +qconv_rsa_public_key(void *cls, + const void *data, + size_t data_len, + void *param_values[], + int param_lengths[], + int param_formats[], + unsigned int param_length, + void *scratch[], + unsigned int scratch_length) { const struct GNUNET_CRYPTO_RsaPublicKey *rsa = data; char *buf; size_t buf_size; - GNUNET_break (NULL == cls); + GNUNET_break(NULL == cls); if (1 != param_length) return -1; - buf_size = GNUNET_CRYPTO_rsa_public_key_encode (rsa, - &buf); + buf_size = GNUNET_CRYPTO_rsa_public_key_encode(rsa, + &buf); scratch[0] = buf; - param_values[0] = (void *) buf; + param_values[0] = (void *)buf; param_lengths[0] = buf_size - 1; /* DB doesn't like the trailing \0 */ param_formats[0] = 1; return 1; @@ -314,10 +318,11 @@ qconv_rsa_public_key (void *cls, * @return array entry for the query parameters to use */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_rsa_public_key (const struct GNUNET_CRYPTO_RsaPublicKey *x) +GNUNET_PQ_query_param_rsa_public_key(const struct GNUNET_CRYPTO_RsaPublicKey *x) { struct GNUNET_PQ_QueryParam res = - { &qconv_rsa_public_key, NULL, (x), 0, 1 }; + { &qconv_rsa_public_key, NULL, (x), 0, 1 }; + return res; } @@ -337,27 +342,27 @@ GNUNET_PQ_query_param_rsa_public_key (const struct GNUNET_CRYPTO_RsaPublicKey *x * @return -1 on error, number of offsets used in @a scratch otherwise */ static int -qconv_rsa_signature (void *cls, - const void *data, - size_t data_len, - void *param_values[], - int param_lengths[], - int param_formats[], - unsigned int param_length, - void *scratch[], - unsigned int scratch_length) +qconv_rsa_signature(void *cls, + const void *data, + size_t data_len, + void *param_values[], + int param_lengths[], + int param_formats[], + unsigned int param_length, + void *scratch[], + unsigned int scratch_length) { const struct GNUNET_CRYPTO_RsaSignature *sig = data; char *buf; size_t buf_size; - GNUNET_break (NULL == cls); + GNUNET_break(NULL == cls); if (1 != param_length) return -1; - buf_size = GNUNET_CRYPTO_rsa_signature_encode (sig, - &buf); + buf_size = GNUNET_CRYPTO_rsa_signature_encode(sig, + &buf); scratch[0] = buf; - param_values[0] = (void *) buf; + param_values[0] = (void *)buf; param_lengths[0] = buf_size - 1; /* DB doesn't like the trailing \0 */ param_formats[0] = 1; return 1; @@ -372,10 +377,11 @@ qconv_rsa_signature (void *cls, * @return array entry for the query parameters to use */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *x) +GNUNET_PQ_query_param_rsa_signature(const struct GNUNET_CRYPTO_RsaSignature *x) { struct GNUNET_PQ_QueryParam res = - { &qconv_rsa_signature, NULL, (x), 0, 1 }; + { &qconv_rsa_signature, NULL, (x), 0, 1 }; + return res; } @@ -395,31 +401,31 @@ GNUNET_PQ_query_param_rsa_signature (const struct GNUNET_CRYPTO_RsaSignature *x) * @return -1 on error, number of offsets used in @a scratch otherwise */ static int -qconv_abs_time (void *cls, - const void *data, - size_t data_len, - void *param_values[], - int param_lengths[], - int param_formats[], - unsigned int param_length, - void *scratch[], - unsigned int scratch_length) +qconv_abs_time(void *cls, + const void *data, + size_t data_len, + void *param_values[], + int param_lengths[], + int param_formats[], + unsigned int param_length, + void *scratch[], + unsigned int scratch_length) { const struct GNUNET_TIME_Absolute *u = data; struct GNUNET_TIME_Absolute abs; uint64_t *u_nbo; - GNUNET_break (NULL == cls); + GNUNET_break(NULL == cls); if (1 != param_length) return -1; abs = *u; if (abs.abs_value_us > INT64_MAX) abs.abs_value_us = INT64_MAX; - u_nbo = GNUNET_new (uint64_t); + u_nbo = GNUNET_new(uint64_t); scratch[0] = u_nbo; - *u_nbo = GNUNET_htonll (abs.abs_value_us); - param_values[0] = (void *) u_nbo; - param_lengths[0] = sizeof (uint64_t); + *u_nbo = GNUNET_htonll(abs.abs_value_us); + param_values[0] = (void *)u_nbo; + param_lengths[0] = sizeof(uint64_t); param_formats[0] = 1; return 1; } @@ -433,10 +439,10 @@ qconv_abs_time (void *cls, * @return array entry for the query parameters to use */ struct GNUNET_PQ_QueryParam -GNUNET_PQ_query_param_absolute_time (const struct GNUNET_TIME_Absolute *x) +GNUNET_PQ_query_param_absolute_time(const struct GNUNET_TIME_Absolute *x) { struct GNUNET_PQ_QueryParam res = - { &qconv_abs_time, NULL, x, sizeof (*x), 1 }; + { &qconv_abs_time, NULL, x, sizeof(*x), 1 }; return res; } @@ -451,7 +457,7 @@ GNUNET_PQ_query_param_absolute_time (const struct GNUNET_TIME_Absolute *x) struct GNUNET_PQ_QueryParam GNUNET_PQ_query_param_absolute_time_nbo(const struct GNUNET_TIME_AbsoluteNBO *x) { - return GNUNET_PQ_query_param_auto_from_type (&x->abs_value_us__); + return GNUNET_PQ_query_param_auto_from_type(&x->abs_value_us__); } diff --git a/src/pq/pq_result_helper.c b/src/pq/pq_result_helper.c index 336ca8c42..89c0207f7 100644 --- a/src/pq/pq_result_helper.c +++ b/src/pq/pq_result_helper.c @@ -1,22 +1,22 @@ - /* - This file is part of GNUnet - Copyright (C) 2014, 2015, 2016 GNUnet e.V. +/* + This file is part of GNUnet + Copyright (C) 2014, 2015, 2016 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . - SPDX-License-Identifier: AGPL3.0-or-later -*/ + SPDX-License-Identifier: AGPL3.0-or-later + */ /** * @file pq/pq_result_helper.c * @brief functions to extract result values @@ -35,17 +35,17 @@ * @param rd result data to clean up */ static void -clean_varsize_blob (void *cls, - void *rd) +clean_varsize_blob(void *cls, + void *rd) { void **dst = rd; - (void) cls; + (void)cls; if (NULL != *dst) - { - GNUNET_free (*dst); - *dst = NULL; - } + { + GNUNET_free(*dst); + *dst = NULL; + } } @@ -63,51 +63,51 @@ clean_varsize_blob (void *cls, * #GNUNET_SYSERR if a result was invalid (non-existing field) */ static int -extract_varsize_blob (void *cls, - PGresult *result, - int row, - const char *fname, - size_t *dst_size, - void *dst) +extract_varsize_blob(void *cls, + PGresult *result, + int row, + const char *fname, + size_t *dst_size, + void *dst) { size_t len; const char *res; void *idst; int fnum; - (void) cls; + (void)cls; *dst_size = 0; - *((void **) dst) = NULL; + *((void **)dst) = NULL; - fnum = PQfnumber (result, - fname); + fnum = PQfnumber(result, + fname); if (fnum < 0) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (PQgetisnull (result, - row, - fnum)) - { - /* Let's allow this for varsize */ - return GNUNET_OK; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (PQgetisnull(result, + row, + fnum)) + { + /* Let's allow this for varsize */ + return GNUNET_OK; + } /* if a field is null, continue but * remember that we now return a different result */ - len = PQgetlength (result, - row, - fnum); - res = PQgetvalue (result, - row, - fnum); - GNUNET_assert (NULL != res); + len = PQgetlength(result, + row, + fnum); + res = PQgetvalue(result, + row, + fnum); + GNUNET_assert(NULL != res); *dst_size = len; - idst = GNUNET_malloc (len); - *((void **) dst) = idst; - GNUNET_memcpy (idst, - res, - len); + idst = GNUNET_malloc(len); + *((void **)dst) = idst; + GNUNET_memcpy(idst, + res, + len); return GNUNET_OK; } @@ -121,14 +121,15 @@ extract_varsize_blob (void *cls, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_variable_size (const char *name, - void **dst, - size_t *sptr) +GNUNET_PQ_result_spec_variable_size(const char *name, + void **dst, + size_t *sptr) { struct GNUNET_PQ_ResultSpec res = - { &extract_varsize_blob, - &clean_varsize_blob, NULL, - (void *) (dst), 0, name, sptr }; + { &extract_varsize_blob, + &clean_varsize_blob, NULL, + (void *)(dst), 0, name, sptr }; + return res; } @@ -147,50 +148,50 @@ GNUNET_PQ_result_spec_variable_size (const char *name, * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) */ static int -extract_fixed_blob (void *cls, - PGresult *result, - int row, - const char *fname, - size_t *dst_size, - void *dst) +extract_fixed_blob(void *cls, + PGresult *result, + int row, + const char *fname, + size_t *dst_size, + void *dst) { size_t len; const char *res; int fnum; - (void) cls; - fnum = PQfnumber (result, - fname); + (void)cls; + fnum = PQfnumber(result, + fname); if (fnum < 0) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (PQgetisnull (result, - row, - fnum)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (PQgetisnull(result, + row, + fnum)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } /* if a field is null, continue but * remember that we now return a different result */ - len = PQgetlength (result, - row, - fnum); + len = PQgetlength(result, + row, + fnum); if (*dst_size != len) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - res = PQgetvalue (result, - row, - fnum); - GNUNET_assert (NULL != res); - GNUNET_memcpy (dst, - res, - len); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + res = PQgetvalue(result, + row, + fnum); + GNUNET_assert(NULL != res); + GNUNET_memcpy(dst, + res, + len); return GNUNET_OK; } @@ -204,14 +205,15 @@ extract_fixed_blob (void *cls, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_fixed_size (const char *name, - void *dst, - size_t dst_size) +GNUNET_PQ_result_spec_fixed_size(const char *name, + void *dst, + size_t dst_size) { struct GNUNET_PQ_ResultSpec res = - { &extract_fixed_blob, - NULL, NULL, - (dst), dst_size, name, NULL }; + { &extract_fixed_blob, + NULL, NULL, + (dst), dst_size, name, NULL }; + return res; } @@ -230,49 +232,49 @@ GNUNET_PQ_result_spec_fixed_size (const char *name, * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) */ static int -extract_rsa_public_key (void *cls, - PGresult *result, - int row, - const char *fname, - size_t *dst_size, - void *dst) +extract_rsa_public_key(void *cls, + PGresult *result, + int row, + const char *fname, + size_t *dst_size, + void *dst) { struct GNUNET_CRYPTO_RsaPublicKey **pk = dst; size_t len; const char *res; int fnum; - (void) cls; + (void)cls; *pk = NULL; - fnum = PQfnumber (result, - fname); + fnum = PQfnumber(result, + fname); if (fnum < 0) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (PQgetisnull (result, - row, - fnum)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (PQgetisnull(result, + row, + fnum)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } /* if a field is null, continue but * remember that we now return a different result */ - len = PQgetlength (result, - row, - fnum); - res = PQgetvalue (result, - row, - fnum); - *pk = GNUNET_CRYPTO_rsa_public_key_decode (res, - len); + len = PQgetlength(result, + row, + fnum); + res = PQgetvalue(result, + row, + fnum); + *pk = GNUNET_CRYPTO_rsa_public_key_decode(res, + len); if (NULL == *pk) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -285,17 +287,17 @@ extract_rsa_public_key (void *cls, * @param rd result data to clean up */ static void -clean_rsa_public_key (void *cls, - void *rd) +clean_rsa_public_key(void *cls, + void *rd) { struct GNUNET_CRYPTO_RsaPublicKey **pk = rd; - (void) cls; + (void)cls; if (NULL != *pk) - { - GNUNET_CRYPTO_rsa_public_key_free (*pk); - *pk = NULL; - } + { + GNUNET_CRYPTO_rsa_public_key_free(*pk); + *pk = NULL; + } } @@ -307,14 +309,15 @@ clean_rsa_public_key (void *cls, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_rsa_public_key (const char *name, - struct GNUNET_CRYPTO_RsaPublicKey **rsa) +GNUNET_PQ_result_spec_rsa_public_key(const char *name, + struct GNUNET_CRYPTO_RsaPublicKey **rsa) { struct GNUNET_PQ_ResultSpec res = - { &extract_rsa_public_key, - &clean_rsa_public_key, - NULL, - (void *) rsa, 0, name, NULL }; + { &extract_rsa_public_key, + &clean_rsa_public_key, + NULL, + (void *)rsa, 0, name, NULL }; + return res; } @@ -333,49 +336,49 @@ GNUNET_PQ_result_spec_rsa_public_key (const char *name, * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) */ static int -extract_rsa_signature (void *cls, - PGresult *result, - int row, - const char *fname, - size_t *dst_size, - void *dst) +extract_rsa_signature(void *cls, + PGresult *result, + int row, + const char *fname, + size_t *dst_size, + void *dst) { struct GNUNET_CRYPTO_RsaSignature **sig = dst; size_t len; const char *res; int fnum; - (void) cls; + (void)cls; *sig = NULL; - fnum = PQfnumber (result, - fname); + fnum = PQfnumber(result, + fname); if (fnum < 0) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (PQgetisnull (result, - row, - fnum)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (PQgetisnull(result, + row, + fnum)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } /* if a field is null, continue but * remember that we now return a different result */ - len = PQgetlength (result, - row, - fnum); - res = PQgetvalue (result, - row, - fnum); - *sig = GNUNET_CRYPTO_rsa_signature_decode (res, - len); + len = PQgetlength(result, + row, + fnum); + res = PQgetvalue(result, + row, + fnum); + *sig = GNUNET_CRYPTO_rsa_signature_decode(res, + len); if (NULL == *sig) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -388,17 +391,17 @@ extract_rsa_signature (void *cls, * @param rd result data to clean up */ static void -clean_rsa_signature (void *cls, - void *rd) +clean_rsa_signature(void *cls, + void *rd) { struct GNUNET_CRYPTO_RsaSignature **sig = rd; - (void) cls; + (void)cls; if (NULL != *sig) - { - GNUNET_CRYPTO_rsa_signature_free (*sig); - *sig = NULL; - } + { + GNUNET_CRYPTO_rsa_signature_free(*sig); + *sig = NULL; + } } @@ -410,14 +413,15 @@ clean_rsa_signature (void *cls, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_rsa_signature (const char *name, - struct GNUNET_CRYPTO_RsaSignature **sig) +GNUNET_PQ_result_spec_rsa_signature(const char *name, + struct GNUNET_CRYPTO_RsaSignature **sig) { struct GNUNET_PQ_ResultSpec res = - { &extract_rsa_signature, - &clean_rsa_signature, - NULL, - (void *) sig, 0, (name), NULL }; + { &extract_rsa_signature, + &clean_rsa_signature, + NULL, + (void *)sig, 0, (name), NULL }; + return res; } @@ -436,49 +440,49 @@ GNUNET_PQ_result_spec_rsa_signature (const char *name, * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) */ static int -extract_string (void *cls, - PGresult *result, - int row, - const char *fname, - size_t *dst_size, - void *dst) +extract_string(void *cls, + PGresult *result, + int row, + const char *fname, + size_t *dst_size, + void *dst) { char **str = dst; size_t len; const char *res; int fnum; - (void) cls; + (void)cls; *str = NULL; - fnum = PQfnumber (result, - fname); + fnum = PQfnumber(result, + fname); if (fnum < 0) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (PQgetisnull (result, - row, - fnum)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (PQgetisnull(result, + row, + fnum)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } /* if a field is null, continue but * remember that we now return a different result */ - len = PQgetlength (result, - row, - fnum); - res = PQgetvalue (result, - row, - fnum); - *str = GNUNET_strndup (res, - len); + len = PQgetlength(result, + row, + fnum); + res = PQgetvalue(result, + row, + fnum); + *str = GNUNET_strndup(res, + len); if (NULL == *str) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -491,17 +495,17 @@ extract_string (void *cls, * @param rd result data to clean up */ static void -clean_string (void *cls, - void *rd) +clean_string(void *cls, + void *rd) { char **str = rd; - (void) cls; + (void)cls; if (NULL != *str) - { - GNUNET_free (*str); - *str = NULL; - } + { + GNUNET_free(*str); + *str = NULL; + } } @@ -513,14 +517,15 @@ clean_string (void *cls, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_string (const char *name, - char **dst) +GNUNET_PQ_result_spec_string(const char *name, + char **dst) { struct GNUNET_PQ_ResultSpec res = - { &extract_string, - &clean_string, - NULL, - (void *) dst, 0, (name), NULL }; + { &extract_string, + &clean_string, + NULL, + (void *)dst, 0, (name), NULL }; + return res; } @@ -539,53 +544,53 @@ GNUNET_PQ_result_spec_string (const char *name, * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) */ static int -extract_abs_time (void *cls, - PGresult *result, - int row, - const char *fname, - size_t *dst_size, - void *dst) +extract_abs_time(void *cls, + PGresult *result, + int row, + const char *fname, + size_t *dst_size, + void *dst) { struct GNUNET_TIME_Absolute *udst = dst; const int64_t *res; int fnum; - (void) cls; - fnum = PQfnumber (result, - fname); + (void)cls; + fnum = PQfnumber(result, + fname); if (fnum < 0) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (PQgetisnull (result, - row, - fnum)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - GNUNET_assert (NULL != dst); - if (sizeof (struct GNUNET_TIME_Absolute) != *dst_size) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (sizeof (int64_t) != - PQgetlength (result, - row, - fnum)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - res = (int64_t *) PQgetvalue (result, - row, - fnum); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (PQgetisnull(result, + row, + fnum)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + GNUNET_assert(NULL != dst); + if (sizeof(struct GNUNET_TIME_Absolute) != *dst_size) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (sizeof(int64_t) != + PQgetlength(result, + row, + fnum)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + res = (int64_t *)PQgetvalue(result, + row, + fnum); if (INT64_MAX == *res) *udst = GNUNET_TIME_UNIT_FOREVER_ABS; else - udst->abs_value_us = GNUNET_ntohll ((uint64_t) *res); + udst->abs_value_us = GNUNET_ntohll((uint64_t)*res); return GNUNET_OK; } @@ -598,14 +603,15 @@ extract_abs_time (void *cls, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_absolute_time (const char *name, - struct GNUNET_TIME_Absolute *at) +GNUNET_PQ_result_spec_absolute_time(const char *name, + struct GNUNET_TIME_Absolute *at) { struct GNUNET_PQ_ResultSpec res = - { &extract_abs_time, - NULL, - NULL, - (void *) at, sizeof (*at), (name), NULL }; + { &extract_abs_time, + NULL, + NULL, + (void *)at, sizeof(*at), (name), NULL }; + return res; } @@ -618,11 +624,12 @@ GNUNET_PQ_result_spec_absolute_time (const char *name, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_absolute_time_nbo (const char *name, - struct GNUNET_TIME_AbsoluteNBO *at) +GNUNET_PQ_result_spec_absolute_time_nbo(const char *name, + struct GNUNET_TIME_AbsoluteNBO *at) { struct GNUNET_PQ_ResultSpec res = GNUNET_PQ_result_spec_auto_from_type(name, &at->abs_value_us__); + return res; } @@ -641,50 +648,50 @@ GNUNET_PQ_result_spec_absolute_time_nbo (const char *name, * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) */ static int -extract_uint16 (void *cls, - PGresult *result, - int row, - const char *fname, - size_t *dst_size, - void *dst) +extract_uint16(void *cls, + PGresult *result, + int row, + const char *fname, + size_t *dst_size, + void *dst) { uint16_t *udst = dst; const uint16_t *res; int fnum; - (void) cls; - fnum = PQfnumber (result, - fname); + (void)cls; + fnum = PQfnumber(result, + fname); if (fnum < 0) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (PQgetisnull (result, - row, - fnum)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - GNUNET_assert (NULL != dst); - if (sizeof (uint16_t) != *dst_size) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (sizeof (uint16_t) != - PQgetlength (result, - row, - fnum)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - res = (uint16_t *) PQgetvalue (result, - row, - fnum); - *udst = ntohs (*res); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (PQgetisnull(result, + row, + fnum)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + GNUNET_assert(NULL != dst); + if (sizeof(uint16_t) != *dst_size) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (sizeof(uint16_t) != + PQgetlength(result, + row, + fnum)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + res = (uint16_t *)PQgetvalue(result, + row, + fnum); + *udst = ntohs(*res); return GNUNET_OK; } @@ -697,14 +704,15 @@ extract_uint16 (void *cls, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_uint16 (const char *name, - uint16_t *u16) +GNUNET_PQ_result_spec_uint16(const char *name, + uint16_t *u16) { struct GNUNET_PQ_ResultSpec res = - { &extract_uint16, - NULL, - NULL, - (void *) u16, sizeof (*u16), (name), NULL }; + { &extract_uint16, + NULL, + NULL, + (void *)u16, sizeof(*u16), (name), NULL }; + return res; } @@ -723,50 +731,50 @@ GNUNET_PQ_result_spec_uint16 (const char *name, * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) */ static int -extract_uint32 (void *cls, - PGresult *result, - int row, - const char *fname, - size_t *dst_size, - void *dst) +extract_uint32(void *cls, + PGresult *result, + int row, + const char *fname, + size_t *dst_size, + void *dst) { uint32_t *udst = dst; const uint32_t *res; int fnum; - (void) cls; - fnum = PQfnumber (result, - fname); + (void)cls; + fnum = PQfnumber(result, + fname); if (fnum < 0) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (PQgetisnull (result, - row, - fnum)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - GNUNET_assert (NULL != dst); - if (sizeof (uint32_t) != *dst_size) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (sizeof (uint32_t) != - PQgetlength (result, - row, - fnum)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - res = (uint32_t *) PQgetvalue (result, - row, - fnum); - *udst = ntohl (*res); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (PQgetisnull(result, + row, + fnum)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + GNUNET_assert(NULL != dst); + if (sizeof(uint32_t) != *dst_size) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (sizeof(uint32_t) != + PQgetlength(result, + row, + fnum)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + res = (uint32_t *)PQgetvalue(result, + row, + fnum); + *udst = ntohl(*res); return GNUNET_OK; } @@ -779,14 +787,15 @@ extract_uint32 (void *cls, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_uint32 (const char *name, - uint32_t *u32) +GNUNET_PQ_result_spec_uint32(const char *name, + uint32_t *u32) { struct GNUNET_PQ_ResultSpec res = - { &extract_uint32, - NULL, - NULL, - (void *) u32, sizeof (*u32), (name), NULL }; + { &extract_uint32, + NULL, + NULL, + (void *)u32, sizeof(*u32), (name), NULL }; + return res; } @@ -805,50 +814,50 @@ GNUNET_PQ_result_spec_uint32 (const char *name, * #GNUNET_SYSERR if a result was invalid (non-existing field or NULL) */ static int -extract_uint64 (void *cls, - PGresult *result, - int row, - const char *fname, - size_t *dst_size, - void *dst) +extract_uint64(void *cls, + PGresult *result, + int row, + const char *fname, + size_t *dst_size, + void *dst) { uint64_t *udst = dst; const uint64_t *res; int fnum; - (void) cls; - fnum = PQfnumber (result, - fname); + (void)cls; + fnum = PQfnumber(result, + fname); if (fnum < 0) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (PQgetisnull (result, - row, - fnum)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - GNUNET_assert (NULL != dst); - if (sizeof (uint64_t) != *dst_size) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - if (sizeof (uint64_t) != - PQgetlength (result, - row, - fnum)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } - res = (uint64_t *) PQgetvalue (result, - row, - fnum); - *udst = GNUNET_ntohll (*res); + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (PQgetisnull(result, + row, + fnum)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + GNUNET_assert(NULL != dst); + if (sizeof(uint64_t) != *dst_size) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + if (sizeof(uint64_t) != + PQgetlength(result, + row, + fnum)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } + res = (uint64_t *)PQgetvalue(result, + row, + fnum); + *udst = GNUNET_ntohll(*res); return GNUNET_OK; } @@ -861,14 +870,15 @@ extract_uint64 (void *cls, * @return array entry for the result specification to use */ struct GNUNET_PQ_ResultSpec -GNUNET_PQ_result_spec_uint64 (const char *name, - uint64_t *u64) +GNUNET_PQ_result_spec_uint64(const char *name, + uint64_t *u64) { struct GNUNET_PQ_ResultSpec res = - { &extract_uint64, - NULL, - NULL, - (void *) u64, sizeof (*u64), (name), NULL }; + { &extract_uint64, + NULL, + NULL, + (void *)u64, sizeof(*u64), (name), NULL }; + return res; } diff --git a/src/pq/test_pq.c b/src/pq/test_pq.c index 67cf32733..df54580d2 100644 --- a/src/pq/test_pq.c +++ b/src/pq/test_pq.c @@ -1,22 +1,22 @@ /* - This file is part of GNUnet - (C) 2015, 2016 GNUnet e.V. + This file is part of GNUnet + (C) 2015, 2016 GNUnet e.V. - GNUnet is free software: you can redistribute it and/or modify it - under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, - or (at your option) any later version. + GNUnet is free software: you can redistribute it and/or modify it + under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, + or (at your option) any later version. - GNUnet is distributed in the hope that it will be useful, but - WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . + GNUnet is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file pq/test_pq.c * @brief Tests for Postgres convenience API @@ -34,52 +34,52 @@ * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure */ static int -postgres_prepare (PGconn *db_conn) +postgres_prepare(PGconn *db_conn) { PGresult *result; #define PREPARE(name, sql, ...) \ do { \ - result = PQprepare (db_conn, name, sql, __VA_ARGS__); \ - if (PGRES_COMMAND_OK != PQresultStatus (result)) \ - { \ - GNUNET_break (0); \ - PQclear (result); result = NULL; \ - return GNUNET_SYSERR; \ - } \ - PQclear (result); result = NULL; \ - } while (0); + result = PQprepare(db_conn, name, sql, __VA_ARGS__); \ + if (PGRES_COMMAND_OK != PQresultStatus(result)) \ + { \ + GNUNET_break(0); \ + PQclear(result); result = NULL; \ + return GNUNET_SYSERR; \ + } \ + PQclear(result); result = NULL; \ + } while (0); - PREPARE ("test_insert", - "INSERT INTO test_pq (" - " pub" - ",sig" - ",abs_time" - ",forever" - ",hash" - ",vsize" - ",u16" - ",u32" - ",u64" - ") VALUES " - "($1, $2, $3, $4, $5, $6," - "$7, $8, $9);", - 9, NULL); - PREPARE ("test_select", - "SELECT" - " pub" - ",sig" - ",abs_time" - ",forever" - ",hash" - ",vsize" - ",u16" - ",u32" - ",u64" - " FROM test_pq" - " ORDER BY abs_time DESC " - " LIMIT 1;", - 0, NULL); + PREPARE("test_insert", + "INSERT INTO test_pq (" + " pub" + ",sig" + ",abs_time" + ",forever" + ",hash" + ",vsize" + ",u16" + ",u32" + ",u64" + ") VALUES " + "($1, $2, $3, $4, $5, $6," + "$7, $8, $9);", + 9, NULL); + PREPARE("test_select", + "SELECT" + " pub" + ",sig" + ",abs_time" + ",forever" + ",hash" + ",vsize" + ",u16" + ",u32" + ",u64" + " FROM test_pq" + " ORDER BY abs_time DESC " + " LIMIT 1;", + 0, NULL); return GNUNET_OK; #undef PREPARE } @@ -91,13 +91,13 @@ postgres_prepare (PGconn *db_conn) * @return 0 on success */ static int -run_queries (PGconn *conn) +run_queries(PGconn *conn) { struct GNUNET_CRYPTO_RsaPublicKey *pub; struct GNUNET_CRYPTO_RsaPublicKey *pub2 = NULL; struct GNUNET_CRYPTO_RsaSignature *sig; struct GNUNET_CRYPTO_RsaSignature *sig2 = NULL; - struct GNUNET_TIME_Absolute abs_time = GNUNET_TIME_absolute_get (); + struct GNUNET_TIME_Absolute abs_time = GNUNET_TIME_absolute_get(); struct GNUNET_TIME_Absolute abs_time2; struct GNUNET_TIME_Absolute forever = GNUNET_TIME_UNIT_FOREVER_ABS; struct GNUNET_TIME_Absolute forever2; @@ -117,102 +117,102 @@ run_queries (PGconn *conn) uint64_t u64; uint64_t u642; - priv = GNUNET_CRYPTO_rsa_private_key_create (1024); - pub = GNUNET_CRYPTO_rsa_private_key_get_public (priv); - memset (&hmsg, 42, sizeof (hmsg)); - sig = GNUNET_CRYPTO_rsa_sign_fdh (priv, - &hmsg); + priv = GNUNET_CRYPTO_rsa_private_key_create(1024); + pub = GNUNET_CRYPTO_rsa_private_key_get_public(priv); + memset(&hmsg, 42, sizeof(hmsg)); + sig = GNUNET_CRYPTO_rsa_sign_fdh(priv, + &hmsg); u16 = 16; u32 = 32; u64 = 64; /* FIXME: test GNUNET_PQ_result_spec_variable_size */ { struct GNUNET_PQ_QueryParam params_insert[] = { - GNUNET_PQ_query_param_rsa_public_key (pub), - GNUNET_PQ_query_param_rsa_signature (sig), - GNUNET_PQ_query_param_absolute_time (&abs_time), - GNUNET_PQ_query_param_absolute_time (&forever), - GNUNET_PQ_query_param_auto_from_type (&hc), - GNUNET_PQ_query_param_fixed_size (msg, strlen (msg)), - GNUNET_PQ_query_param_uint16 (&u16), - GNUNET_PQ_query_param_uint32 (&u32), - GNUNET_PQ_query_param_uint64 (&u64), + GNUNET_PQ_query_param_rsa_public_key(pub), + GNUNET_PQ_query_param_rsa_signature(sig), + GNUNET_PQ_query_param_absolute_time(&abs_time), + GNUNET_PQ_query_param_absolute_time(&forever), + GNUNET_PQ_query_param_auto_from_type(&hc), + GNUNET_PQ_query_param_fixed_size(msg, strlen(msg)), + GNUNET_PQ_query_param_uint16(&u16), + GNUNET_PQ_query_param_uint32(&u32), + GNUNET_PQ_query_param_uint64(&u64), GNUNET_PQ_query_param_end }; struct GNUNET_PQ_QueryParam params_select[] = { GNUNET_PQ_query_param_end }; struct GNUNET_PQ_ResultSpec results_select[] = { - GNUNET_PQ_result_spec_rsa_public_key ("pub", &pub2), - GNUNET_PQ_result_spec_rsa_signature ("sig", &sig2), - GNUNET_PQ_result_spec_absolute_time ("abs_time", &abs_time2), - GNUNET_PQ_result_spec_absolute_time ("forever", &forever2), - GNUNET_PQ_result_spec_auto_from_type ("hash", &hc2), - GNUNET_PQ_result_spec_variable_size ("vsize", &msg2, &msg2_len), - GNUNET_PQ_result_spec_uint16 ("u16", &u162), - GNUNET_PQ_result_spec_uint32 ("u32", &u322), - GNUNET_PQ_result_spec_uint64 ("u64", &u642), + GNUNET_PQ_result_spec_rsa_public_key("pub", &pub2), + GNUNET_PQ_result_spec_rsa_signature("sig", &sig2), + GNUNET_PQ_result_spec_absolute_time("abs_time", &abs_time2), + GNUNET_PQ_result_spec_absolute_time("forever", &forever2), + GNUNET_PQ_result_spec_auto_from_type("hash", &hc2), + GNUNET_PQ_result_spec_variable_size("vsize", &msg2, &msg2_len), + GNUNET_PQ_result_spec_uint16("u16", &u162), + GNUNET_PQ_result_spec_uint32("u32", &u322), + GNUNET_PQ_result_spec_uint64("u64", &u642), GNUNET_PQ_result_spec_end }; - result = GNUNET_PQ_exec_prepared (conn, - "test_insert", - params_insert); - if (PGRES_COMMAND_OK != PQresultStatus (result)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Database failure: %s\n", - PQresultErrorMessage (result)); - PQclear (result); - GNUNET_CRYPTO_rsa_signature_free (sig); - GNUNET_CRYPTO_rsa_private_key_free (priv); - GNUNET_CRYPTO_rsa_public_key_free (pub); - return 1; - } + result = GNUNET_PQ_exec_prepared(conn, + "test_insert", + params_insert); + if (PGRES_COMMAND_OK != PQresultStatus(result)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Database failure: %s\n", + PQresultErrorMessage(result)); + PQclear(result); + GNUNET_CRYPTO_rsa_signature_free(sig); + GNUNET_CRYPTO_rsa_private_key_free(priv); + GNUNET_CRYPTO_rsa_public_key_free(pub); + return 1; + } - PQclear (result); - result = GNUNET_PQ_exec_prepared (conn, - "test_select", - params_select); + PQclear(result); + result = GNUNET_PQ_exec_prepared(conn, + "test_select", + params_select); if (1 != - PQntuples (result)) - { - GNUNET_break (0); - PQclear (result); - GNUNET_CRYPTO_rsa_signature_free (sig); - GNUNET_CRYPTO_rsa_private_key_free (priv); - GNUNET_CRYPTO_rsa_public_key_free (pub); - return 1; - } - ret = GNUNET_PQ_extract_result (result, - results_select, - 0); - GNUNET_break (GNUNET_YES == ret); - GNUNET_break (abs_time.abs_value_us == abs_time2.abs_value_us); - GNUNET_break (forever.abs_value_us == forever2.abs_value_us); - GNUNET_break (0 == - GNUNET_memcmp (&hc, - &hc2)); - GNUNET_break (0 == - GNUNET_CRYPTO_rsa_signature_cmp (sig, - sig2)); - GNUNET_break (0 == - GNUNET_CRYPTO_rsa_public_key_cmp (pub, - pub2)); - GNUNET_break (strlen (msg) == msg2_len); - GNUNET_break (0 == - strncmp (msg, - msg2, - msg2_len)); - GNUNET_break (16 == u162); - GNUNET_break (32 == u322); - GNUNET_break (64 == u642); - GNUNET_PQ_cleanup_result (results_select); - PQclear (result); + PQntuples(result)) + { + GNUNET_break(0); + PQclear(result); + GNUNET_CRYPTO_rsa_signature_free(sig); + GNUNET_CRYPTO_rsa_private_key_free(priv); + GNUNET_CRYPTO_rsa_public_key_free(pub); + return 1; + } + ret = GNUNET_PQ_extract_result(result, + results_select, + 0); + GNUNET_break(GNUNET_YES == ret); + GNUNET_break(abs_time.abs_value_us == abs_time2.abs_value_us); + GNUNET_break(forever.abs_value_us == forever2.abs_value_us); + GNUNET_break(0 == + GNUNET_memcmp(&hc, + &hc2)); + GNUNET_break(0 == + GNUNET_CRYPTO_rsa_signature_cmp(sig, + sig2)); + GNUNET_break(0 == + GNUNET_CRYPTO_rsa_public_key_cmp(pub, + pub2)); + GNUNET_break(strlen(msg) == msg2_len); + GNUNET_break(0 == + strncmp(msg, + msg2, + msg2_len)); + GNUNET_break(16 == u162); + GNUNET_break(32 == u322); + GNUNET_break(64 == u642); + GNUNET_PQ_cleanup_result(results_select); + PQclear(result); } - GNUNET_CRYPTO_rsa_signature_free (sig); - GNUNET_CRYPTO_rsa_private_key_free (priv); - GNUNET_CRYPTO_rsa_public_key_free (pub); + GNUNET_CRYPTO_rsa_signature_free(sig); + GNUNET_CRYPTO_rsa_private_key_free(priv); + GNUNET_CRYPTO_rsa_public_key_free(pub); if (GNUNET_OK != ret) return 1; @@ -221,70 +221,70 @@ run_queries (PGconn *conn) int -main (int argc, - const char *const argv[]) +main(int argc, + const char *const argv[]) { PGconn *conn; PGresult *result; int ret; - GNUNET_log_setup ("test-pq", - "WARNING", - NULL); - conn = PQconnectdb ("postgres:///gnunetcheck"); - if (CONNECTION_OK != PQstatus (conn)) - { - fprintf (stderr, - "Cannot run test, database connection failed: %s\n", - PQerrorMessage (conn)); - GNUNET_break (0); - PQfinish (conn); - return 77; /* signal test was skipped */ - } + GNUNET_log_setup("test-pq", + "WARNING", + NULL); + conn = PQconnectdb("postgres:///gnunetcheck"); + if (CONNECTION_OK != PQstatus(conn)) + { + fprintf(stderr, + "Cannot run test, database connection failed: %s\n", + PQerrorMessage(conn)); + GNUNET_break(0); + PQfinish(conn); + return 77; /* signal test was skipped */ + } - result = PQexec (conn, - "CREATE TEMPORARY TABLE IF NOT EXISTS test_pq (" - " pub BYTEA NOT NULL" - ",sig BYTEA NOT NULL" - ",abs_time INT8 NOT NULL" - ",forever INT8 NOT NULL" - ",hash BYTEA NOT NULL CHECK(LENGTH(hash)=64)" - ",vsize VARCHAR NOT NULL" - ",u16 INT2 NOT NULL" - ",u32 INT4 NOT NULL" - ",u64 INT8 NOT NULL" - ")"); - if (PGRES_COMMAND_OK != PQresultStatus (result)) - { - fprintf (stderr, - "Failed to create table: %s\n", - PQerrorMessage (conn)); - PQclear (result); - PQfinish (conn); - return 1; - } - PQclear (result); + result = PQexec(conn, + "CREATE TEMPORARY TABLE IF NOT EXISTS test_pq (" + " pub BYTEA NOT NULL" + ",sig BYTEA NOT NULL" + ",abs_time INT8 NOT NULL" + ",forever INT8 NOT NULL" + ",hash BYTEA NOT NULL CHECK(LENGTH(hash)=64)" + ",vsize VARCHAR NOT NULL" + ",u16 INT2 NOT NULL" + ",u32 INT4 NOT NULL" + ",u64 INT8 NOT NULL" + ")"); + if (PGRES_COMMAND_OK != PQresultStatus(result)) + { + fprintf(stderr, + "Failed to create table: %s\n", + PQerrorMessage(conn)); + PQclear(result); + PQfinish(conn); + return 1; + } + PQclear(result); if (GNUNET_OK != - postgres_prepare (conn)) - { - GNUNET_break (0); - PQfinish (conn); - return 1; - } - ret = run_queries (conn); - result = PQexec (conn, - "DROP TABLE test_pq"); - if (PGRES_COMMAND_OK != PQresultStatus (result)) - { - fprintf (stderr, - "Failed to create table: %s\n", - PQerrorMessage (conn)); - PQclear (result); - PQfinish (conn); - return 1; - } - PQclear (result); - PQfinish (conn); + postgres_prepare(conn)) + { + GNUNET_break(0); + PQfinish(conn); + return 1; + } + ret = run_queries(conn); + result = PQexec(conn, + "DROP TABLE test_pq"); + if (PGRES_COMMAND_OK != PQresultStatus(result)) + { + fprintf(stderr, + "Failed to create table: %s\n", + PQerrorMessage(conn)); + PQclear(result); + PQfinish(conn); + return 1; + } + PQclear(result); + PQfinish(conn); return ret; } diff --git a/src/pt/gnunet-daemon-pt.c b/src/pt/gnunet-daemon-pt.c index 99cbfebf8..ad22eaab8 100644 --- a/src/pt/gnunet-daemon-pt.c +++ b/src/pt/gnunet-daemon-pt.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file pt/gnunet-daemon-pt.c * @brief tool to manipulate DNS and VPN services to perform protocol translation (IPvX over GNUnet) @@ -58,8 +58,7 @@ /** * Which group of DNS records are we currently processing? */ -enum RequestGroup -{ +enum RequestGroup { /** * DNS answers */ @@ -85,8 +84,7 @@ enum RequestGroup /** * Information tracked per DNS reply that we are processing. */ -struct ReplyContext -{ +struct ReplyContext { /** * Handle to submit the final result. */ @@ -116,7 +114,6 @@ struct ReplyContext * Group that is being modified */ enum RequestGroup group; - }; @@ -125,9 +122,7 @@ struct ReplyContext * as a DNS exit. We try to keep a few channels open and a few * peers in reserve. */ -struct CadetExit -{ - +struct CadetExit { /** * Kept in a DLL. */ @@ -178,7 +173,6 @@ struct CadetExit * Size of the window, 0 if we are busy. */ /* unsigned */ int idle; - }; @@ -186,8 +180,7 @@ struct CadetExit /** * State we keep for a request that is going out via CADET. */ -struct RequestContext -{ +struct RequestContext { /** * We keep these in a DLL. */ @@ -227,7 +220,6 @@ struct RequestContext * ID of the original DNS request (used to match the reply). */ uint16_t dns_id; - }; @@ -310,7 +302,7 @@ static unsigned int dns_exit_available; * We are short on cadet exits, try to open another one. */ static void -try_open_exit (void); +try_open_exit(void); /** @@ -323,24 +315,24 @@ try_open_exit (void); * @return weight of the channel */ static uint32_t -get_channel_weight (struct CadetExit *exit) +get_channel_weight(struct CadetExit *exit) { uint32_t dropped; uint32_t drop_percent; uint32_t good_percent; - GNUNET_assert (exit->num_transmitted >= exit->num_answered); + GNUNET_assert(exit->num_transmitted >= exit->num_answered); dropped = exit->num_transmitted - exit->num_answered; if (exit->num_transmitted > 0) - drop_percent = (uint32_t) ((100LL * dropped) / exit->num_transmitted); + drop_percent = (uint32_t)((100LL * dropped) / exit->num_transmitted); else drop_percent = 50; /* no data */ - if ( (exit->num_transmitted > 20) && - (drop_percent > 25) ) + if ((exit->num_transmitted > 20) && + (drop_percent > 25)) return 0; /* statistically significant, and > 25% loss, die */ good_percent = 100 - drop_percent; - GNUNET_assert (0 != good_percent); - if ( UINT32_MAX / good_percent / good_percent < exit->num_transmitted) + GNUNET_assert(0 != good_percent); + if (UINT32_MAX / good_percent / good_percent < exit->num_transmitted) return UINT32_MAX; /* formula below would overflow */ return 1 + good_percent * good_percent * exit->num_transmitted; } @@ -358,7 +350,7 @@ get_channel_weight (struct CadetExit *exit) * exit that we should use to queue a message with */ static struct CadetExit * -choose_exit () +choose_exit() { struct CadetExit *pos; uint64_t total_transmitted; @@ -367,36 +359,36 @@ choose_exit () total_transmitted = 0; for (pos = exit_head; NULL != pos; pos = pos->next) - { - if (NULL == pos->cadet_channel) - break; - channel_weight = get_channel_weight (pos); - total_transmitted += channel_weight; - /* double weight for idle channels */ - if (0 != pos->idle) + { + if (NULL == pos->cadet_channel) + break; + channel_weight = get_channel_weight(pos); total_transmitted += channel_weight; - } + /* double weight for idle channels */ + if (0 != pos->idle) + total_transmitted += channel_weight; + } if (0 == total_transmitted) - { - /* no channels available, or only a very bad one... */ - return exit_head; - } - selected_offset = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, - total_transmitted); + { + /* no channels available, or only a very bad one... */ + return exit_head; + } + selected_offset = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, + total_transmitted); total_transmitted = 0; for (pos = exit_head; NULL != pos; pos = pos->next) - { - if (NULL == pos->cadet_channel) - break; - channel_weight = get_channel_weight (pos); - total_transmitted += channel_weight; - /* double weight for idle channels */ - if (0 != pos->idle) + { + if (NULL == pos->cadet_channel) + break; + channel_weight = get_channel_weight(pos); total_transmitted += channel_weight; - if (total_transmitted > selected_offset) - return pos; - } - GNUNET_break (0); + /* double weight for idle channels */ + if (0 != pos->idle) + total_transmitted += channel_weight; + if (total_transmitted > selected_offset) + return pos; + } + GNUNET_break(0); return NULL; } @@ -408,33 +400,33 @@ choose_exit () * @param rc context to process */ static void -finish_request (struct ReplyContext *rc) +finish_request(struct ReplyContext *rc) { char *buf; size_t buf_len; if (GNUNET_SYSERR == - GNUNET_DNSPARSER_pack (rc->dns, - MAX_DNS_SIZE, - &buf, - &buf_len)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to pack DNS request. Dropping.\n")); - GNUNET_DNS_request_drop (rc->rh); - } + GNUNET_DNSPARSER_pack(rc->dns, + MAX_DNS_SIZE, + &buf, + &buf_len)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to pack DNS request. Dropping.\n")); + GNUNET_DNS_request_drop(rc->rh); + } else - { - GNUNET_STATISTICS_update (stats, - gettext_noop ("# DNS requests mapped to VPN"), - 1, GNUNET_NO); - GNUNET_DNS_request_answer (rc->rh, - buf_len, - buf); - GNUNET_free (buf); - } - GNUNET_DNSPARSER_free_packet (rc->dns); - GNUNET_free (rc); + { + GNUNET_STATISTICS_update(stats, + gettext_noop("# DNS requests mapped to VPN"), + 1, GNUNET_NO); + GNUNET_DNS_request_answer(rc->rh, + buf_len, + buf); + GNUNET_free(buf); + } + GNUNET_DNSPARSER_free_packet(rc->dns); + GNUNET_free(rc); } @@ -446,7 +438,7 @@ finish_request (struct ReplyContext *rc) * @param rc context to process */ static void -submit_request (struct ReplyContext *rc); +submit_request(struct ReplyContext *rc); /** @@ -465,44 +457,46 @@ submit_request (struct ReplyContext *rc); * specified target peer; NULL on error */ static void -vpn_allocation_callback (void *cls, - int af, - const void *address) +vpn_allocation_callback(void *cls, + int af, + const void *address) { struct ReplyContext *rc = cls; rc->rr = NULL; if (af == AF_UNSPEC) - { - GNUNET_DNS_request_drop (rc->rh); - GNUNET_DNSPARSER_free_packet (rc->dns); - GNUNET_free (rc); - return; - } - GNUNET_STATISTICS_update (stats, - gettext_noop ("# DNS records modified"), - 1, - GNUNET_NO); + { + GNUNET_DNS_request_drop(rc->rh); + GNUNET_DNSPARSER_free_packet(rc->dns); + GNUNET_free(rc); + return; + } + GNUNET_STATISTICS_update(stats, + gettext_noop("# DNS records modified"), + 1, + GNUNET_NO); switch (rc->rec->type) - { - case GNUNET_DNSPARSER_TYPE_A: - GNUNET_assert (AF_INET == af); - GNUNET_memcpy (rc->rec->data.raw.data, - address, - sizeof (struct in_addr)); - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - GNUNET_assert (AF_INET6 == af); - GNUNET_memcpy (rc->rec->data.raw.data, - address, - sizeof (struct in6_addr)); - break; - default: - GNUNET_assert (0); - return; - } + { + case GNUNET_DNSPARSER_TYPE_A: + GNUNET_assert(AF_INET == af); + GNUNET_memcpy(rc->rec->data.raw.data, + address, + sizeof(struct in_addr)); + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + GNUNET_assert(AF_INET6 == af); + GNUNET_memcpy(rc->rec->data.raw.data, + address, + sizeof(struct in6_addr)); + break; + + default: + GNUNET_assert(0); + return; + } rc->rec = NULL; - submit_request (rc); + submit_request(rc); } @@ -516,33 +510,35 @@ vpn_allocation_callback (void *cls, * @param rec record to modify */ static void -modify_address (struct ReplyContext *rc, - struct GNUNET_DNSPARSER_Record *rec) +modify_address(struct ReplyContext *rc, + struct GNUNET_DNSPARSER_Record *rec) { int af; switch (rec->type) - { - case GNUNET_DNSPARSER_TYPE_A: - af = AF_INET; - GNUNET_assert (rec->data.raw.data_len == sizeof (struct in_addr)); - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - af = AF_INET6; - GNUNET_assert (rec->data.raw.data_len == sizeof (struct in6_addr)); - break; - default: - GNUNET_assert (0); - return; - } + { + case GNUNET_DNSPARSER_TYPE_A: + af = AF_INET; + GNUNET_assert(rec->data.raw.data_len == sizeof(struct in_addr)); + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + af = AF_INET6; + GNUNET_assert(rec->data.raw.data_len == sizeof(struct in6_addr)); + break; + + default: + GNUNET_assert(0); + return; + } rc->rec = rec; - rc->rr = GNUNET_VPN_redirect_to_ip (vpn_handle, - af, - af, - rec->data.raw.data, - GNUNET_TIME_relative_to_absolute (TIMEOUT), - &vpn_allocation_callback, - rc); + rc->rr = GNUNET_VPN_redirect_to_ip(vpn_handle, + af, + af, + rec->data.raw.data, + GNUNET_TIME_relative_to_absolute(TIMEOUT), + &vpn_allocation_callback, + rc); } @@ -554,60 +550,65 @@ modify_address (struct ReplyContext *rc, * @param rc context to process */ static void -submit_request (struct ReplyContext *rc) +submit_request(struct ReplyContext *rc) { struct GNUNET_DNSPARSER_Record *ra; unsigned int ra_len; unsigned int i; while (1) - { - switch (rc->group) { - case ANSWERS: - ra = rc->dns->answers; - ra_len = rc->dns->num_answers; - break; - case AUTHORITY_RECORDS: - ra = rc->dns->authority_records; - ra_len = rc->dns->num_authority_records; - break; - case ADDITIONAL_RECORDS: - ra = rc->dns->additional_records; - ra_len = rc->dns->num_additional_records; - break; - case END: - finish_request (rc); - return; - default: - GNUNET_assert (0); + switch (rc->group) + { + case ANSWERS: + ra = rc->dns->answers; + ra_len = rc->dns->num_answers; + break; + + case AUTHORITY_RECORDS: + ra = rc->dns->authority_records; + ra_len = rc->dns->num_authority_records; + break; + + case ADDITIONAL_RECORDS: + ra = rc->dns->additional_records; + ra_len = rc->dns->num_additional_records; + break; + + case END: + finish_request(rc); + return; + + default: + GNUNET_assert(0); + } + for (i = rc->offset; i < ra_len; i++) + { + switch (ra[i].type) + { + case GNUNET_DNSPARSER_TYPE_A: + if (ipv4_pt) + { + rc->offset = i + 1; + modify_address(rc, + &ra[i]); + return; + } + break; + + case GNUNET_DNSPARSER_TYPE_AAAA: + if (ipv6_pt) + { + rc->offset = i + 1; + modify_address(rc, + &ra[i]); + return; + } + break; + } + } + rc->group++; } - for (i=rc->offset;ioffset = i + 1; - modify_address (rc, - &ra[i]); - return; - } - break; - case GNUNET_DNSPARSER_TYPE_AAAA: - if (ipv6_pt) - { - rc->offset = i + 1; - modify_address (rc, - &ra[i]); - return; - } - break; - } - } - rc->group++; - } } @@ -619,25 +620,26 @@ submit_request (struct ReplyContext *rc) * @return #GNUNET_YES if any of the given records require protocol-translation */ static int -work_test (const struct GNUNET_DNSPARSER_Record *ra, - unsigned int ra_len) +work_test(const struct GNUNET_DNSPARSER_Record *ra, + unsigned int ra_len) { unsigned int i; - for (i=0;ianswers, - dns->num_answers); - work |= work_test (dns->authority_records, - dns->num_authority_records); - work |= work_test (dns->additional_records, - dns->num_additional_records); - if (! work) - { - GNUNET_DNS_request_forward (rh); - GNUNET_DNSPARSER_free_packet (dns); - return; - } - rc = GNUNET_new (struct ReplyContext); + work |= work_test(dns->answers, + dns->num_answers); + work |= work_test(dns->authority_records, + dns->num_authority_records); + work |= work_test(dns->additional_records, + dns->num_additional_records); + if (!work) + { + GNUNET_DNS_request_forward(rh); + GNUNET_DNSPARSER_free_packet(dns); + return; + } + rc = GNUNET_new(struct ReplyContext); rc->rh = rh; rc->dns = dns; rc->offset = 0; rc->group = ANSWERS; - submit_request (rc); + submit_request(rc); } @@ -703,41 +705,41 @@ dns_post_request_handler (void *cls, * @param cls the `struct RequestContext` to abort */ static void -timeout_request (void *cls) +timeout_request(void *cls) { struct RequestContext *rc = cls; struct CadetExit *exit = rc->exit; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# DNS requests dropped (timeout)"), - 1, - GNUNET_NO); - GNUNET_DNS_request_drop (rc->rh); - GNUNET_free (rc); - if ( (0 == get_channel_weight (exit)) && - (NULL == exit->receive_queue_head) ) - { - /* this straw broke the camel's back: this channel now has - such a low score that it will not be used; close it! */ - GNUNET_CADET_channel_destroy (exit->cadet_channel); - exit->cadet_channel = NULL; - GNUNET_CONTAINER_DLL_remove (exit_head, - exit_tail, - exit); - GNUNET_CONTAINER_DLL_insert_tail (exit_head, - exit_tail, - exit); - /* go back to semi-innocent: mark as not great, but - avoid a prohibitively negative score (see + GNUNET_STATISTICS_update(stats, + gettext_noop("# DNS requests dropped (timeout)"), + 1, + GNUNET_NO); + GNUNET_DNS_request_drop(rc->rh); + GNUNET_free(rc); + if ((0 == get_channel_weight(exit)) && + (NULL == exit->receive_queue_head)) + { + /* this straw broke the camel's back: this channel now has + such a low score that it will not be used; close it! */ + GNUNET_CADET_channel_destroy(exit->cadet_channel); + exit->cadet_channel = NULL; + GNUNET_CONTAINER_DLL_remove(exit_head, + exit_tail, + exit); + GNUNET_CONTAINER_DLL_insert_tail(exit_head, + exit_tail, + exit); + /* go back to semi-innocent: mark as not great, but + avoid a prohibitively negative score (see #get_channel_weight(), which checks for a certain - minimum number of transmissions before making - up an opinion) */ - exit->num_transmitted = 5; - exit->num_answered = 0; - dns_exit_available--; - /* now try to open an alternative exit */ - try_open_exit (); - } + minimum number of transmissions before making + up an opinion) */ + exit->num_transmitted = 5; + exit->num_answered = 0; + dns_exit_available--; + /* now try to open an alternative exit */ + try_open_exit(); + } } @@ -753,10 +755,10 @@ timeout_request (void *cls) * @param request udp payload of the DNS request */ static void -dns_pre_request_handler (void *cls, - struct GNUNET_DNS_RequestHandle *rh, - size_t request_length, - const char *request) +dns_pre_request_handler(void *cls, + struct GNUNET_DNS_RequestHandle *rh, + size_t request_length, + const char *request) { struct RequestContext *rc; struct GNUNET_MQ_Envelope *env; @@ -764,54 +766,54 @@ dns_pre_request_handler (void *cls, struct GNUNET_TUN_DnsHeader dns; struct CadetExit *exit; - GNUNET_STATISTICS_update (stats, - gettext_noop ("# DNS requests intercepted"), - 1, GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# DNS requests intercepted"), + 1, GNUNET_NO); if (0 == dns_exit_available) - { - GNUNET_STATISTICS_update (stats, - gettext_noop ("# DNS requests dropped (DNS cadet channel down)"), - 1, GNUNET_NO); - GNUNET_DNS_request_drop (rh); - return; - } - if (request_length < sizeof (dns)) - { - GNUNET_STATISTICS_update (stats, - gettext_noop ("# DNS requests dropped (malformed)"), - 1, GNUNET_NO); - GNUNET_DNS_request_drop (rh); - return; - } - exit = choose_exit (); - GNUNET_assert (NULL != exit); - GNUNET_assert (NULL != exit->cadet_channel); - - env = GNUNET_MQ_msg_extra (hdr, - request_length, - GNUNET_MESSAGE_TYPE_VPN_DNS_TO_INTERNET); - GNUNET_memcpy (&hdr[1], - request, - request_length); - rc = GNUNET_new (struct RequestContext); + { + GNUNET_STATISTICS_update(stats, + gettext_noop("# DNS requests dropped (DNS cadet channel down)"), + 1, GNUNET_NO); + GNUNET_DNS_request_drop(rh); + return; + } + if (request_length < sizeof(dns)) + { + GNUNET_STATISTICS_update(stats, + gettext_noop("# DNS requests dropped (malformed)"), + 1, GNUNET_NO); + GNUNET_DNS_request_drop(rh); + return; + } + exit = choose_exit(); + GNUNET_assert(NULL != exit); + GNUNET_assert(NULL != exit->cadet_channel); + + env = GNUNET_MQ_msg_extra(hdr, + request_length, + GNUNET_MESSAGE_TYPE_VPN_DNS_TO_INTERNET); + GNUNET_memcpy(&hdr[1], + request, + request_length); + rc = GNUNET_new(struct RequestContext); rc->exit = exit; rc->rh = rh; - rc->timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &timeout_request, - rc); - GNUNET_memcpy (&dns, - request, - sizeof (dns)); + rc->timeout_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &timeout_request, + rc); + GNUNET_memcpy(&dns, + request, + sizeof(dns)); rc->dns_id = dns.id; rc->env = env; - GNUNET_CONTAINER_DLL_remove (exit->receive_queue_head, - exit->receive_queue_tail, - rc); + GNUNET_CONTAINER_DLL_remove(exit->receive_queue_head, + exit->receive_queue_tail, + rc); if (0 < exit->idle) exit->idle--; exit->num_transmitted++; - GNUNET_MQ_send (GNUNET_CADET_get_mq (exit->cadet_channel), - GNUNET_MQ_env_copy (env)); + GNUNET_MQ_send(GNUNET_CADET_get_mq(exit->cadet_channel), + GNUNET_MQ_env_copy(env)); } @@ -820,8 +822,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Message with a DNS response. */ -struct DnsResponseMessage -{ +struct DnsResponseMessage { /** * GNUnet header, of type #GNUNET_MESSAGE_TYPE_VPN_DNS_FROM_INTERNET */ @@ -846,8 +847,8 @@ GNUNET_NETWORK_STRUCT_END * #GNUNET_SYSERR to close it (signal serious error) */ static int -check_dns_response (void *cls, - const struct DnsResponseMessage *msg) +check_dns_response(void *cls, + const struct DnsResponseMessage *msg) { return GNUNET_OK; /* all OK */ } @@ -860,38 +861,38 @@ check_dns_response (void *cls, * @param msg the actual message */ static void -handle_dns_response (void *cls, - const struct DnsResponseMessage *msg) +handle_dns_response(void *cls, + const struct DnsResponseMessage *msg) { struct CadetExit *exit = cls; size_t mlen; struct RequestContext *rc; - mlen = ntohs (msg->header.size) - sizeof (*msg); + mlen = ntohs(msg->header.size) - sizeof(*msg); for (rc = exit->receive_queue_head; NULL != rc; rc = rc->next) - { - if (msg->dns.id == rc->dns_id) { - GNUNET_STATISTICS_update (stats, - gettext_noop ("# DNS replies received"), - 1, - GNUNET_NO); - GNUNET_DNS_request_answer (rc->rh, - mlen + sizeof (struct GNUNET_TUN_DnsHeader), - (const void*) &msg->dns); - GNUNET_CONTAINER_DLL_remove (exit->receive_queue_head, - exit->receive_queue_tail, - rc); - GNUNET_SCHEDULER_cancel (rc->timeout_task); - GNUNET_MQ_discard (rc->env); - GNUNET_free (rc); - exit->num_answered++; - return; + if (msg->dns.id == rc->dns_id) + { + GNUNET_STATISTICS_update(stats, + gettext_noop("# DNS replies received"), + 1, + GNUNET_NO); + GNUNET_DNS_request_answer(rc->rh, + mlen + sizeof(struct GNUNET_TUN_DnsHeader), + (const void*)&msg->dns); + GNUNET_CONTAINER_DLL_remove(exit->receive_queue_head, + exit->receive_queue_tail, + rc); + GNUNET_SCHEDULER_cancel(rc->timeout_task); + GNUNET_MQ_discard(rc->env); + GNUNET_free(rc); + exit->num_answered++; + return; + } } - } - GNUNET_STATISTICS_update (stats, - gettext_noop ("# DNS replies dropped (too late?)"), - 1, GNUNET_NO); + GNUNET_STATISTICS_update(stats, + gettext_noop("# DNS replies dropped (too late?)"), + 1, GNUNET_NO); } @@ -901,20 +902,20 @@ handle_dns_response (void *cls, * @param exit cadet exit to abort requests for */ static void -abort_all_requests (struct CadetExit *exit) +abort_all_requests(struct CadetExit *exit) { struct RequestContext *rc; while (NULL != (rc = exit->receive_queue_head)) - { - GNUNET_CONTAINER_DLL_remove (exit->receive_queue_head, - exit->receive_queue_tail, - rc); - GNUNET_DNS_request_drop (rc->rh); - GNUNET_SCHEDULER_cancel (rc->timeout_task); - GNUNET_MQ_discard (rc->env); - GNUNET_free (rc); - } + { + GNUNET_CONTAINER_DLL_remove(exit->receive_queue_head, + exit->receive_queue_tail, + rc); + GNUNET_DNS_request_drop(rc->rh); + GNUNET_SCHEDULER_cancel(rc->timeout_task); + GNUNET_MQ_discard(rc->env); + GNUNET_free(rc); + } } @@ -924,60 +925,60 @@ abort_all_requests (struct CadetExit *exit) * @param cls closure, NULL */ static void -cleanup (void *cls) +cleanup(void *cls) { struct CadetExit *exit; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Protocol translation daemon is shutting down now\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Protocol translation daemon is shutting down now\n"); if (NULL != vpn_handle) - { - GNUNET_VPN_disconnect (vpn_handle); - vpn_handle = NULL; - } + { + GNUNET_VPN_disconnect(vpn_handle); + vpn_handle = NULL; + } while (NULL != (exit = exit_head)) - { - GNUNET_CONTAINER_DLL_remove (exit_head, - exit_tail, - exit); - if (NULL != exit->cadet_channel) { - GNUNET_CADET_channel_destroy (exit->cadet_channel); - exit->cadet_channel = NULL; + GNUNET_CONTAINER_DLL_remove(exit_head, + exit_tail, + exit); + if (NULL != exit->cadet_channel) + { + GNUNET_CADET_channel_destroy(exit->cadet_channel); + exit->cadet_channel = NULL; + } + abort_all_requests(exit); + GNUNET_free(exit); } - abort_all_requests (exit); - GNUNET_free (exit); - } if (NULL != cadet_handle) - { - GNUNET_CADET_disconnect (cadet_handle); - cadet_handle = NULL; - } + { + GNUNET_CADET_disconnect(cadet_handle); + cadet_handle = NULL; + } if (NULL != dns_post_handle) - { - GNUNET_DNS_disconnect (dns_post_handle); - dns_post_handle = NULL; - } + { + GNUNET_DNS_disconnect(dns_post_handle); + dns_post_handle = NULL; + } if (NULL != dns_pre_handle) - { - GNUNET_DNS_disconnect (dns_pre_handle); - dns_pre_handle = NULL; - } + { + GNUNET_DNS_disconnect(dns_pre_handle); + dns_pre_handle = NULL; + } if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, GNUNET_YES); - stats = NULL; - } + { + GNUNET_STATISTICS_destroy(stats, GNUNET_YES); + stats = NULL; + } if (NULL != dht_get) - { - GNUNET_DHT_get_stop (dht_get); - dht_get = NULL; - } + { + GNUNET_DHT_get_stop(dht_get); + dht_get = NULL; + } if (NULL != dht) - { - GNUNET_DHT_disconnect (dht); - dht = NULL; - } + { + GNUNET_DHT_disconnect(dht); + dht = NULL; + } } @@ -993,8 +994,8 @@ cleanup (void *cls) * with the channel is stored */ static void -cadet_channel_end_cb (void *cls, - const struct GNUNET_CADET_Channel *channel) +cadet_channel_end_cb(void *cls, + const struct GNUNET_CADET_Channel *channel) { struct CadetExit *exit = cls; struct CadetExit *alt; @@ -1005,20 +1006,20 @@ cadet_channel_end_cb (void *cls, /* open alternative channels */ /* our channel is now closed, move our requests to an alternative channel */ - alt = choose_exit (); + alt = choose_exit(); while (NULL != (rc = exit->receive_queue_head)) - { - GNUNET_CONTAINER_DLL_remove (exit->receive_queue_head, - exit->receive_queue_tail, - rc); - rc->exit = alt; - GNUNET_CONTAINER_DLL_insert (alt->receive_queue_head, - alt->receive_queue_tail, - rc); - GNUNET_MQ_send (GNUNET_CADET_get_mq (alt->cadet_channel), - GNUNET_MQ_env_copy (rc->env)); - } - try_open_exit (); + { + GNUNET_CONTAINER_DLL_remove(exit->receive_queue_head, + exit->receive_queue_tail, + rc); + rc->exit = alt; + GNUNET_CONTAINER_DLL_insert(alt->receive_queue_head, + alt->receive_queue_tail, + rc); + GNUNET_MQ_send(GNUNET_CADET_get_mq(alt->cadet_channel), + GNUNET_MQ_env_copy(rc->env)); + } + try_open_exit(); } @@ -1030,9 +1031,9 @@ cadet_channel_end_cb (void *cls, * @param window_size how much capacity do we have */ static void -channel_idle_notify_cb (void *cls, - const struct GNUNET_CADET_Channel *channel, - int window_size) +channel_idle_notify_cb(void *cls, + const struct GNUNET_CADET_Channel *channel, + int window_size) { struct CadetExit *pos = cls; @@ -1044,69 +1045,69 @@ channel_idle_notify_cb (void *cls, * We are short on cadet exits, try to open another one. */ static void -try_open_exit () +try_open_exit() { struct CadetExit *pos; uint32_t candidate_count; uint32_t candidate_selected; struct GNUNET_HashCode port; - GNUNET_CRYPTO_hash (GNUNET_APPLICATION_PORT_INTERNET_RESOLVER, - strlen (GNUNET_APPLICATION_PORT_INTERNET_RESOLVER), - &port); + GNUNET_CRYPTO_hash(GNUNET_APPLICATION_PORT_INTERNET_RESOLVER, + strlen(GNUNET_APPLICATION_PORT_INTERNET_RESOLVER), + &port); candidate_count = 0; for (pos = exit_head; NULL != pos; pos = pos->next) if (NULL == pos->cadet_channel) candidate_count++; if (0 == candidate_count) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "No DNS exits available yet.\n"); - return; - } - candidate_selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - candidate_count); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "No DNS exits available yet.\n"); + return; + } + candidate_selected = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + candidate_count); candidate_count = 0; for (pos = exit_head; NULL != pos; pos = pos->next) if (NULL == pos->cadet_channel) - { - candidate_count++; - if (candidate_selected < candidate_count) { - struct GNUNET_MQ_MessageHandler cadet_handlers[] = { - GNUNET_MQ_hd_var_size (dns_response, - GNUNET_MESSAGE_TYPE_VPN_DNS_FROM_INTERNET, - struct DnsResponseMessage, - pos), - GNUNET_MQ_handler_end () - }; - - - /* move to the head of the DLL */ - pos->cadet_channel - = GNUNET_CADET_channel_create (cadet_handle, - pos, - &pos->peer, - &port, - &channel_idle_notify_cb, - &cadet_channel_end_cb, - cadet_handlers); - if (NULL == pos->cadet_channel) - { - GNUNET_break (0); - continue; - } - GNUNET_CONTAINER_DLL_remove (exit_head, - exit_tail, - pos); - GNUNET_CONTAINER_DLL_insert (exit_head, - exit_tail, - pos); - dns_exit_available++; - return; + candidate_count++; + if (candidate_selected < candidate_count) + { + struct GNUNET_MQ_MessageHandler cadet_handlers[] = { + GNUNET_MQ_hd_var_size(dns_response, + GNUNET_MESSAGE_TYPE_VPN_DNS_FROM_INTERNET, + struct DnsResponseMessage, + pos), + GNUNET_MQ_handler_end() + }; + + + /* move to the head of the DLL */ + pos->cadet_channel + = GNUNET_CADET_channel_create(cadet_handle, + pos, + &pos->peer, + &port, + &channel_idle_notify_cb, + &cadet_channel_end_cb, + cadet_handlers); + if (NULL == pos->cadet_channel) + { + GNUNET_break(0); + continue; + } + GNUNET_CONTAINER_DLL_remove(exit_head, + exit_tail, + pos); + GNUNET_CONTAINER_DLL_insert(exit_head, + exit_tail, + pos); + dns_exit_available++; + return; + } } - } - GNUNET_assert (NULL == exit_head); + GNUNET_assert(NULL == exit_head); } @@ -1130,42 +1131,42 @@ try_open_exit () * @param data pointer to the result data */ static void -handle_dht_result (void *cls, - struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - enum GNUNET_BLOCK_Type type, - size_t size, const void *data) +handle_dht_result(void *cls, + struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + enum GNUNET_BLOCK_Type type, + size_t size, const void *data) { const struct GNUNET_DNS_Advertisement *ad; struct CadetExit *exit; - if (sizeof (struct GNUNET_DNS_Advertisement) != size) - { - GNUNET_break (0); - return; - } + if (sizeof(struct GNUNET_DNS_Advertisement) != size) + { + GNUNET_break(0); + return; + } ad = data; for (exit = exit_head; NULL != exit; exit = exit->next) - if (0 == GNUNET_memcmp (&ad->peer, - &exit->peer)) + if (0 == GNUNET_memcmp(&ad->peer, + &exit->peer)) break; if (NULL == exit) - { - exit = GNUNET_new (struct CadetExit); - exit->peer = ad->peer; - /* channel is closed, so insert at the end */ - GNUNET_CONTAINER_DLL_insert_tail (exit_head, - exit_tail, - exit); - } - exit->expiration = GNUNET_TIME_absolute_max (exit->expiration, - GNUNET_TIME_absolute_ntoh (ad->expiration_time)); + { + exit = GNUNET_new(struct CadetExit); + exit->peer = ad->peer; + /* channel is closed, so insert at the end */ + GNUNET_CONTAINER_DLL_insert_tail(exit_head, + exit_tail, + exit); + } + exit->expiration = GNUNET_TIME_absolute_max(exit->expiration, + GNUNET_TIME_absolute_ntoh(ad->expiration_time)); if (dns_exit_available < MAX_OPEN_TUNNELS) - try_open_exit (); + try_open_exit(); } @@ -1178,102 +1179,102 @@ handle_dht_result (void *cls, * @param cfg_ configuration */ static void -run (void *cls, char *const *args GNUNET_UNUSED, - const char *cfgfile GNUNET_UNUSED, - const struct GNUNET_CONFIGURATION_Handle *cfg_) +run(void *cls, char *const *args GNUNET_UNUSED, + const char *cfgfile GNUNET_UNUSED, + const struct GNUNET_CONFIGURATION_Handle *cfg_) { struct GNUNET_HashCode dns_key; cfg = cfg_; - stats = GNUNET_STATISTICS_create ("pt", - cfg); - ipv4_pt = GNUNET_CONFIGURATION_get_value_yesno (cfg, - "pt", - "TUNNEL_IPV4"); - ipv6_pt = GNUNET_CONFIGURATION_get_value_yesno (cfg, - "pt", - "TUNNEL_IPV6"); - dns_channel = GNUNET_CONFIGURATION_get_value_yesno (cfg, - "pt", - "TUNNEL_DNS"); - if (! (ipv4_pt || ipv6_pt || dns_channel)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No useful service enabled. Exiting.\n")); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_SCHEDULER_add_shutdown (&cleanup, cls); - if (ipv4_pt || ipv6_pt) - { - dns_post_handle - = GNUNET_DNS_connect (cfg, - GNUNET_DNS_FLAG_POST_RESOLUTION, - &dns_post_request_handler, - NULL); - if (NULL == dns_post_handle) + stats = GNUNET_STATISTICS_create("pt", + cfg); + ipv4_pt = GNUNET_CONFIGURATION_get_value_yesno(cfg, + "pt", + "TUNNEL_IPV4"); + ipv6_pt = GNUNET_CONFIGURATION_get_value_yesno(cfg, + "pt", + "TUNNEL_IPV6"); + dns_channel = GNUNET_CONFIGURATION_get_value_yesno(cfg, + "pt", + "TUNNEL_DNS"); + if (!(ipv4_pt || ipv6_pt || dns_channel)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect to %s service. Exiting.\n"), - "DNS"); - GNUNET_SCHEDULER_shutdown (); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No useful service enabled. Exiting.\n")); + GNUNET_SCHEDULER_shutdown(); return; } - vpn_handle = GNUNET_VPN_connect (cfg); - if (NULL == vpn_handle) + GNUNET_SCHEDULER_add_shutdown(&cleanup, cls); + if (ipv4_pt || ipv6_pt) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect to %s service. Exiting.\n"), - "VPN"); - GNUNET_SCHEDULER_shutdown (); - return; + dns_post_handle + = GNUNET_DNS_connect(cfg, + GNUNET_DNS_FLAG_POST_RESOLUTION, + &dns_post_request_handler, + NULL); + if (NULL == dns_post_handle) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to %s service. Exiting.\n"), + "DNS"); + GNUNET_SCHEDULER_shutdown(); + return; + } + vpn_handle = GNUNET_VPN_connect(cfg); + if (NULL == vpn_handle) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to %s service. Exiting.\n"), + "VPN"); + GNUNET_SCHEDULER_shutdown(); + return; + } } - } if (dns_channel) - { - dns_pre_handle - = GNUNET_DNS_connect (cfg, - GNUNET_DNS_FLAG_PRE_RESOLUTION, - &dns_pre_request_handler, - NULL); - if (NULL == dns_pre_handle) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect to %s service. Exiting.\n"), - "DNS"); - GNUNET_SCHEDULER_shutdown (); - return; - } - cadet_handle = GNUNET_CADET_connect (cfg); - if (NULL == cadet_handle) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect to %s service. Exiting.\n"), - "CADET"); - GNUNET_SCHEDULER_shutdown (); - return; - } - dht = GNUNET_DHT_connect (cfg, 1); - if (NULL == dht) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Failed to connect to %s service. Exiting.\n"), - "DHT"); - GNUNET_SCHEDULER_shutdown (); - return; + dns_pre_handle + = GNUNET_DNS_connect(cfg, + GNUNET_DNS_FLAG_PRE_RESOLUTION, + &dns_pre_request_handler, + NULL); + if (NULL == dns_pre_handle) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to %s service. Exiting.\n"), + "DNS"); + GNUNET_SCHEDULER_shutdown(); + return; + } + cadet_handle = GNUNET_CADET_connect(cfg); + if (NULL == cadet_handle) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to %s service. Exiting.\n"), + "CADET"); + GNUNET_SCHEDULER_shutdown(); + return; + } + dht = GNUNET_DHT_connect(cfg, 1); + if (NULL == dht) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Failed to connect to %s service. Exiting.\n"), + "DHT"); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_CRYPTO_hash("dns", + strlen("dns"), + &dns_key); + dht_get = GNUNET_DHT_get_start(dht, + GNUNET_BLOCK_TYPE_DNS, + &dns_key, + 1, + GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, + NULL, 0, + &handle_dht_result, + NULL); } - GNUNET_CRYPTO_hash ("dns", - strlen ("dns"), - &dns_key); - dht_get = GNUNET_DHT_get_start (dht, - GNUNET_BLOCK_TYPE_DNS, - &dns_key, - 1, - GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE, - NULL, 0, - &handle_dht_result, - NULL); - } } @@ -1285,30 +1286,30 @@ run (void *cls, char *const *args GNUNET_UNUSED, * @return 0 ok, 1 on error */ int -main (int argc, - char *const *argv) +main(int argc, + char *const *argv) { static const struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; int ret; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, - argv, - &argc, - &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, + argv, + &argc, + &argv)) return 2; ret = (GNUNET_OK == - GNUNET_PROGRAM_run (argc, - argv, - "gnunet-daemon-pt", - gettext_noop ("Daemon to run to perform IP protocol translation to GNUnet"), - options, - &run, - NULL)) - ? 0 - : 1; - GNUNET_free ((void*) argv); + GNUNET_PROGRAM_run(argc, + argv, + "gnunet-daemon-pt", + gettext_noop("Daemon to run to perform IP protocol translation to GNUnet"), + options, + &run, + NULL)) + ? 0 + : 1; + GNUNET_free((void*)argv); return ret; } diff --git a/src/pt/test_gns_vpn.c b/src/pt/test_gns_vpn.c index 90405fe37..8a6e3e6d4 100644 --- a/src/pt/test_gns_vpn.c +++ b/src/pt/test_gns_vpn.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file test_gns_vpn.c @@ -49,7 +49,7 @@ #define PORT 8080 #define TEST_DOMAIN "www.gnu" -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30) /** * Return value for #main(). @@ -96,8 +96,7 @@ static int src_af; static int use_v6; -struct CBC -{ +struct CBC { char buf[1024]; size_t pos; }; @@ -106,102 +105,102 @@ static struct CBC cbc; static size_t -copy_buffer (void *ptr, - size_t size, - size_t nmemb, - void *ctx) +copy_buffer(void *ptr, + size_t size, + size_t nmemb, + void *ctx) { struct CBC *cbc = ctx; if (cbc->pos + size * nmemb > sizeof(cbc->buf)) return 0; /* overflow */ - GNUNET_memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); + GNUNET_memcpy(&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static int -mhd_ahc (void *cls, - struct MHD_Connection *connection, - const char *url, - const char *method, - const char *version, - const char *upload_data, size_t *upload_data_size, - void **unused) +mhd_ahc(void *cls, + struct MHD_Connection *connection, + const char *url, + const char *method, + const char *version, + const char *upload_data, size_t *upload_data_size, + void **unused) { static int ptr; struct MHD_Response *response; int ret; - if (0 != strcmp ("GET", method)) + if (0 != strcmp("GET", method)) return MHD_NO; /* unexpected method */ if (&ptr != *unused) - { - *unused = &ptr; - return MHD_YES; - } + { + *unused = &ptr; + return MHD_YES; + } *unused = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MHD sends respose for request to URL `%s'\n", url); - response = MHD_create_response_from_buffer (strlen (url), - (void *) url, - MHD_RESPMEM_MUST_COPY); - ret = MHD_queue_response (connection, MHD_HTTP_OK, response); - MHD_destroy_response (response); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "MHD sends respose for request to URL `%s'\n", url); + response = MHD_create_response_from_buffer(strlen(url), + (void *)url, + MHD_RESPMEM_MUST_COPY); + ret = MHD_queue_response(connection, MHD_HTTP_OK, response); + MHD_destroy_response(response); if (ret == MHD_NO) - abort (); + abort(); return ret; } static void -do_shutdown (void *cls) +do_shutdown(void *cls) { if (NULL != mhd_task_id) - { - GNUNET_SCHEDULER_cancel (mhd_task_id); - mhd_task_id = NULL; - } + { + GNUNET_SCHEDULER_cancel(mhd_task_id); + mhd_task_id = NULL; + } if (NULL != curl_task_id) - { - GNUNET_SCHEDULER_cancel (curl_task_id); - curl_task_id = NULL; - } + { + GNUNET_SCHEDULER_cancel(curl_task_id); + curl_task_id = NULL; + } if (NULL != timeout_task) - { - GNUNET_SCHEDULER_cancel (timeout_task); - timeout_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task); + timeout_task = NULL; + } if (NULL != mhd) - { - MHD_stop_daemon (mhd); - mhd = NULL; - } + { + MHD_stop_daemon(mhd); + mhd = NULL; + } if (NULL != identity) - { - GNUNET_IDENTITY_disconnect (identity); - identity = NULL; - } + { + GNUNET_IDENTITY_disconnect(identity); + identity = NULL; + } if (NULL != qe) - { - GNUNET_NAMESTORE_cancel (qe); - qe = NULL; - } + { + GNUNET_NAMESTORE_cancel(qe); + qe = NULL; + } if (NULL != namestore) - { - GNUNET_NAMESTORE_disconnect (namestore); - namestore = NULL; - } - GNUNET_free_non_null (url); + { + GNUNET_NAMESTORE_disconnect(namestore); + namestore = NULL; + } + GNUNET_free_non_null(url); url = NULL; } static void -do_timeout (void *cls) +do_timeout(void *cls) { timeout_task = NULL; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -209,19 +208,19 @@ do_timeout (void *cls) * Function to run the HTTP client. */ static void -curl_main (void); +curl_main(void); static void -curl_task (void *cls) +curl_task(void *cls) { curl_task_id = NULL; - curl_main (); + curl_main(); } static void -curl_main () +curl_main() { fd_set rs; fd_set ws; @@ -235,102 +234,102 @@ curl_main () struct CURLMsg *msg; max = 0; - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); - curl_multi_perform (multi, &running); + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); + curl_multi_perform(multi, &running); if (running == 0) - { - GNUNET_assert (NULL != (msg = curl_multi_info_read (multi, &running))); - if (msg->msg == CURLMSG_DONE) - { - if (msg->data.result != CURLE_OK) - { - fprintf (stderr, - "%s failed at %s:%d: `%s'\n", - "curl_multi_perform", - __FILE__, - __LINE__, curl_easy_strerror (msg->data.result)); - global_ret = 1; - } - } - curl_multi_remove_handle (multi, curl); - curl_multi_cleanup (multi); - curl_easy_cleanup (curl); - curl = NULL; - multi = NULL; - if (cbc.pos != strlen ("/hello_world")) { - GNUNET_break (0); - global_ret = 2; - } - if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) - { - GNUNET_break (0); - global_ret = 3; + GNUNET_assert(NULL != (msg = curl_multi_info_read(multi, &running))); + if (msg->msg == CURLMSG_DONE) + { + if (msg->data.result != CURLE_OK) + { + fprintf(stderr, + "%s failed at %s:%d: `%s'\n", + "curl_multi_perform", + __FILE__, + __LINE__, curl_easy_strerror(msg->data.result)); + global_ret = 1; + } + } + curl_multi_remove_handle(multi, curl); + curl_multi_cleanup(multi); + curl_easy_cleanup(curl); + curl = NULL; + multi = NULL; + if (cbc.pos != strlen("/hello_world")) + { + GNUNET_break(0); + global_ret = 2; + } + if (0 != strncmp("/hello_world", cbc.buf, strlen("/hello_world"))) + { + GNUNET_break(0); + global_ret = 3; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Download complete, shutting down!\n"); + GNUNET_SCHEDULER_shutdown(); + return; } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Download complete, shutting down!\n"); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_assert (CURLM_OK == curl_multi_fdset (multi, &rs, &ws, &es, &max)); - if ( (CURLM_OK != curl_multi_timeout (multi, &timeout)) || - (-1 == timeout) ) + GNUNET_assert(CURLM_OK == curl_multi_fdset(multi, &rs, &ws, &es, &max)); + if ((CURLM_OK != curl_multi_timeout(multi, &timeout)) || + (-1 == timeout)) delay = GNUNET_TIME_UNIT_SECONDS; else - delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, (unsigned int) timeout); - GNUNET_NETWORK_fdset_copy_native (&nrs, - &rs, - max + 1); - GNUNET_NETWORK_fdset_copy_native (&nws, - &ws, - max + 1); - curl_task_id = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, - delay, - &nrs, - &nws, - &curl_task, - NULL); + delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, (unsigned int)timeout); + GNUNET_NETWORK_fdset_copy_native(&nrs, + &rs, + max + 1); + GNUNET_NETWORK_fdset_copy_native(&nws, + &ws, + max + 1); + curl_task_id = GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT, + delay, + &nrs, + &nws, + &curl_task, + NULL); } static void -start_curl (void *cls) +start_curl(void *cls) { CURLcode ec; curl_task_id = NULL; - GNUNET_asprintf (&url, - "http://%s/hello_world", - TEST_DOMAIN); - curl = curl_easy_init (); - curl_easy_setopt (curl, CURLOPT_URL, url); - curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, ©_buffer); - curl_easy_setopt (curl, CURLOPT_WRITEDATA, &cbc); - curl_easy_setopt (curl, CURLOPT_FAILONERROR, 1); - curl_easy_setopt (curl, CURLOPT_TIMEOUT, 150L); - curl_easy_setopt (curl, CURLOPT_CONNECTTIMEOUT, 150L); - curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1); + GNUNET_asprintf(&url, + "http://%s/hello_world", + TEST_DOMAIN); + curl = curl_easy_init(); + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ©_buffer); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &cbc); + curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); + curl_easy_setopt(curl, CURLOPT_TIMEOUT, 150L); + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 150L); + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); if (CURLE_OK != - (ec = curl_easy_setopt (curl, - CURLOPT_DNS_SERVERS, - "127.0.0.1:53"))) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "curl build without support for CURLOPT_DNS_SERVERS (%s), cannot run test\n", - curl_easy_strerror (ec)); - global_ret = 77; - GNUNET_SCHEDULER_shutdown (); - return; - } - multi = curl_multi_init (); - GNUNET_assert (multi != NULL); - GNUNET_assert (CURLM_OK == curl_multi_add_handle (multi, curl)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Beginning HTTP download from `%s'\n", - url); - curl_main (); + (ec = curl_easy_setopt(curl, + CURLOPT_DNS_SERVERS, + "127.0.0.1:53"))) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "curl build without support for CURLOPT_DNS_SERVERS (%s), cannot run test\n", + curl_easy_strerror(ec)); + global_ret = 77; + GNUNET_SCHEDULER_shutdown(); + return; + } + multi = curl_multi_init(); + GNUNET_assert(multi != NULL); + GNUNET_assert(CURLM_OK == curl_multi_add_handle(multi, curl)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Beginning HTTP download from `%s'\n", + url); + curl_main(); } @@ -347,28 +346,28 @@ start_curl (void *cls) * specified target peer; NULL on error */ static void -commence_testing (void *cls, - int32_t success, - const char *emsg) +commence_testing(void *cls, + int32_t success, + const char *emsg) { qe = NULL; - if ( (NULL != emsg) && - (GNUNET_YES != success) ) - { - fprintf (stderr, - "NS failed to create record %s\n", - emsg); - GNUNET_SCHEDULER_shutdown (); - return; - } + if ((NULL != emsg) && + (GNUNET_YES != success)) + { + fprintf(stderr, + "NS failed to create record %s\n", + emsg); + GNUNET_SCHEDULER_shutdown(); + return; + } /* wait a little bit before downloading, as we just created the record */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Launching cURL request\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Launching cURL request\n"); curl_task_id - = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &start_curl, - NULL); + = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &start_curl, + NULL); } @@ -376,20 +375,20 @@ commence_testing (void *cls, * Function to keep the HTTP server running. */ static void -mhd_main (void); +mhd_main(void); static void -mhd_task (void *cls) +mhd_task(void *cls) { mhd_task_id = NULL; - MHD_run (mhd); - mhd_main (); + MHD_run(mhd); + mhd_main(); } static void -mhd_main () +mhd_main() { struct GNUNET_NETWORK_FDSet nrs; struct GNUNET_NETWORK_FDSet nws; @@ -400,30 +399,30 @@ mhd_main () unsigned MHD_LONG_LONG timeout; struct GNUNET_TIME_Relative delay; - GNUNET_assert (NULL == mhd_task_id); - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); + GNUNET_assert(NULL == mhd_task_id); + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); max_fd = -1; - GNUNET_assert (MHD_YES == - MHD_get_fdset (mhd, &rs, &ws, &es, &max_fd)); - if (MHD_YES == MHD_get_timeout (mhd, &timeout)) - delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, - (unsigned int) timeout); + GNUNET_assert(MHD_YES == + MHD_get_fdset(mhd, &rs, &ws, &es, &max_fd)); + if (MHD_YES == MHD_get_timeout(mhd, &timeout)) + delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, + (unsigned int)timeout); else delay = GNUNET_TIME_UNIT_FOREVER_REL; - GNUNET_NETWORK_fdset_copy_native (&nrs, - &rs, - max_fd + 1); - GNUNET_NETWORK_fdset_copy_native (&nws, - &ws, - max_fd + 1); - mhd_task_id = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, - delay, - &nrs, - &nws, - &mhd_task, - NULL); + GNUNET_NETWORK_fdset_copy_native(&nrs, + &rs, + max_fd + 1); + GNUNET_NETWORK_fdset_copy_native(&nws, + &ws, + max_fd + 1); + mhd_task_id = GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT, + delay, + &nrs, + &nws, + &mhd_task, + NULL); } @@ -436,22 +435,22 @@ mhd_main () * @param flags open flags (O_RDONLY, O_WRONLY) */ static void -open_dev_null (int target_fd, - int flags) +open_dev_null(int target_fd, + int flags) { int fd; - fd = open ("/dev/null", flags); + fd = open("/dev/null", flags); if (-1 == fd) - abort (); + abort(); if (fd == target_fd) return; - if (-1 == dup2 (fd, target_fd)) - { - (void) close (fd); - abort (); - } - (void) close (fd); + if (-1 == dup2(fd, target_fd)) + { + (void)close(fd); + abort(); + } + (void)close(fd); } @@ -463,55 +462,56 @@ open_dev_null (int target_fd, * @return 0 on success, 1 on any error */ static int -fork_and_exec (const char *file, - char *const cmd[]) +fork_and_exec(const char *file, + char *const cmd[]) { int status; pid_t pid; pid_t ret; - pid = fork (); + pid = fork(); if (-1 == pid) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "fork"); - return 1; - } + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "fork"); + return 1; + } if (0 == pid) - { - /* we are the child process */ - /* close stdin/stdout to not cause interference - with the helper's main protocol! */ - (void) close (0); - open_dev_null (0, O_RDONLY); - (void) close (1); - open_dev_null (1, O_WRONLY); - (void) execv (file, cmd); - /* can only get here on error */ - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, - "exec", - file); - _exit (1); - } + { + /* we are the child process */ + /* close stdin/stdout to not cause interference + with the helper's main protocol! */ + (void)close(0); + open_dev_null(0, O_RDONLY); + (void)close(1); + open_dev_null(1, O_WRONLY); + (void)execv(file, cmd); + /* can only get here on error */ + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, + "exec", + file); + _exit(1); + } /* keep running waitpid as long as the only error we get is 'EINTR' */ - while ( (-1 == (ret = waitpid (pid, &status, 0))) && - (errno == EINTR) ); + while ((-1 == (ret = waitpid(pid, &status, 0))) && + (errno == EINTR)) + ; if (-1 == ret) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "waitpid"); - return 1; - } - if (! (WIFEXITED (status) && - (0 == WEXITSTATUS (status))) ) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Process `%s` returned status code %d/%d.\n", - file, - WIFEXITED (status), - WEXITSTATUS (status)); - return 1; - } + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "waitpid"); + return 1; + } + if (!(WIFEXITED(status) && + (0 == WEXITSTATUS(status)))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Process `%s` returned status code %d/%d.\n", + file, + WIFEXITED(status), + WEXITSTATUS(status)); + return 1; + } /* child process completed and returned success, we're happy */ return 0; } @@ -553,10 +553,10 @@ fork_and_exec (const char *file, * must thus no longer be used */ static void -identity_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +identity_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone_key; struct GNUNET_GNSRECORD_Data rd; @@ -566,59 +566,59 @@ identity_cb (void *cls, if (NULL == name) return; if (NULL == ego) - { - if (NULL == qe) { - fprintf (stderr, - "Failed to find master-zone ego\n"); - GNUNET_SCHEDULER_shutdown (); + if (NULL == qe) + { + fprintf(stderr, + "Failed to find master-zone ego\n"); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_IDENTITY_disconnect(identity); + identity = NULL; return; } - GNUNET_IDENTITY_disconnect (identity); - identity = NULL; - return; - } - GNUNET_assert (NULL != name); - if (0 != strcmp (name, - "master-zone")) - { - fprintf (stderr, - "Unexpected name %s\n", - name); - return; - } - zone_key = GNUNET_IDENTITY_ego_get_private_key (ego); + GNUNET_assert(NULL != name); + if (0 != strcmp(name, + "master-zone")) + { + fprintf(stderr, + "Unexpected name %s\n", + name); + return; + } + zone_key = GNUNET_IDENTITY_ego_get_private_key(ego); rd.expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us; - peername = GNUNET_strdup (GNUNET_i2s_full (&id)); - GNUNET_asprintf (&rd_string, - "6 %s %s", - peername, - "www"); - GNUNET_free (peername); - GNUNET_assert (GNUNET_OK == - GNUNET_GNSRECORD_string_to_value (GNUNET_GNSRECORD_TYPE_VPN, - rd_string, - (void**) &rd.data, - &rd.data_size)); + peername = GNUNET_strdup(GNUNET_i2s_full(&id)); + GNUNET_asprintf(&rd_string, + "6 %s %s", + peername, + "www"); + GNUNET_free(peername); + GNUNET_assert(GNUNET_OK == + GNUNET_GNSRECORD_string_to_value(GNUNET_GNSRECORD_TYPE_VPN, + rd_string, + (void**)&rd.data, + &rd.data_size)); rd.record_type = GNUNET_GNSRECORD_TYPE_VPN; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Creating `www` record\n"); - qe = GNUNET_NAMESTORE_records_store (namestore, - zone_key, - "www", - 1, &rd, - &commence_testing, - NULL); - GNUNET_free ((void**)rd.data); - GNUNET_free (rd_string); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Creating `www` record\n"); + qe = GNUNET_NAMESTORE_records_store(namestore, + zone_key, + "www", + 1, &rd, + &commence_testing, + NULL); + GNUNET_free((void**)rd.data); + GNUNET_free(rd_string); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { enum MHD_FLAG flags; @@ -628,19 +628,19 @@ run (void *cls, char *bin_arm; char *config; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Test logic starting...\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Test logic starting...\n"); if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "arm", - "CONFIG", - &config)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to locate configuration file. Skipping test.\n"); - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_CONFIGURATION_get_value_string(cfg, + "arm", + "CONFIG", + &config)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to locate configuration file. Skipping test.\n"); + GNUNET_SCHEDULER_shutdown(); + return; + } char *const identity_args[] = { @@ -680,187 +680,187 @@ run (void *cls, NULL }; - GNUNET_TESTING_peer_get_identity (peer, - &id); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &do_timeout, - NULL); - bin = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR); - GNUNET_asprintf (&bin_identity, - "%s/%s", - bin, - "gnunet-identity"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Creating `master-zone` ego\n"); - if (0 != fork_and_exec (bin_identity, identity_args)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to run `gnunet-identity -C`. Skipping test.\n"); - GNUNET_SCHEDULER_shutdown (); - GNUNET_free (bin_identity); - GNUNET_free (config); - GNUNET_free (bin); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Setting `master-zone` ego as default for `gns-master` and `dns2gns`\n"); - if (0 != fork_and_exec (bin_identity, identity2_args)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to run `gnunet-identity -e`. Skipping test.\n"); - GNUNET_SCHEDULER_shutdown (); - GNUNET_free (bin_identity); - GNUNET_free (config); - GNUNET_free (bin); - return; - } - if (0 != fork_and_exec (bin_identity, identity3_args)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to run `gnunet-identity -e`. Skipping test.\n"); - GNUNET_SCHEDULER_shutdown (); - GNUNET_free (bin_identity); - GNUNET_free (config); - GNUNET_free (bin); - return; - } - GNUNET_free (bin_identity); + GNUNET_TESTING_peer_get_identity(peer, + &id); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); + timeout_task = GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &do_timeout, + NULL); + bin = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_BINDIR); + GNUNET_asprintf(&bin_identity, + "%s/%s", + bin, + "gnunet-identity"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Creating `master-zone` ego\n"); + if (0 != fork_and_exec(bin_identity, identity_args)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to run `gnunet-identity -C`. Skipping test.\n"); + GNUNET_SCHEDULER_shutdown(); + GNUNET_free(bin_identity); + GNUNET_free(config); + GNUNET_free(bin); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Setting `master-zone` ego as default for `gns-master` and `dns2gns`\n"); + if (0 != fork_and_exec(bin_identity, identity2_args)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to run `gnunet-identity -e`. Skipping test.\n"); + GNUNET_SCHEDULER_shutdown(); + GNUNET_free(bin_identity); + GNUNET_free(config); + GNUNET_free(bin); + return; + } + if (0 != fork_and_exec(bin_identity, identity3_args)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to run `gnunet-identity -e`. Skipping test.\n"); + GNUNET_SCHEDULER_shutdown(); + GNUNET_free(bin_identity); + GNUNET_free(config); + GNUNET_free(bin); + return; + } + GNUNET_free(bin_identity); /* do lookup just to launch GNS service */ - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Resolving `www.gnu` zone entry to launch GNS (will yield no answer yet)\n"); - GNUNET_asprintf (&bin_gns, - "%s/%s", - bin, - "gnunet-gns"); - if (0 != fork_and_exec (bin_gns, - gns_args)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to run `gnunet-gns -u. Skipping test.\n"); - GNUNET_SCHEDULER_shutdown (); - GNUNET_free (bin_gns); - GNUNET_free (config); - GNUNET_free (bin); - return; - } - GNUNET_free (bin_gns); - - GNUNET_asprintf (&bin_arm, - "%s/%s", - bin, - "gnunet-arm"); - if (0 != fork_and_exec (bin_arm, - arm_args)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to run `gnunet-arm -i dns2gns. Skipping test.\n"); - GNUNET_SCHEDULER_shutdown (); - GNUNET_free (bin_arm); - GNUNET_free (config); - GNUNET_free (bin); - return; - } - GNUNET_free (bin_arm); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Resolving `www.gnu` zone entry to launch GNS (will yield no answer yet)\n"); + GNUNET_asprintf(&bin_gns, + "%s/%s", + bin, + "gnunet-gns"); + if (0 != fork_and_exec(bin_gns, + gns_args)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to run `gnunet-gns -u. Skipping test.\n"); + GNUNET_SCHEDULER_shutdown(); + GNUNET_free(bin_gns); + GNUNET_free(config); + GNUNET_free(bin); + return; + } + GNUNET_free(bin_gns); + + GNUNET_asprintf(&bin_arm, + "%s/%s", + bin, + "gnunet-arm"); + if (0 != fork_and_exec(bin_arm, + arm_args)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to run `gnunet-arm -i dns2gns. Skipping test.\n"); + GNUNET_SCHEDULER_shutdown(); + GNUNET_free(bin_arm); + GNUNET_free(config); + GNUNET_free(bin); + return; + } + GNUNET_free(bin_arm); - GNUNET_free (config); - GNUNET_free (bin); - sleep (1); /* give dns2gns chance to really run */ + GNUNET_free(config); + GNUNET_free(bin); + sleep(1); /* give dns2gns chance to really run */ - namestore = GNUNET_NAMESTORE_connect (cfg); - GNUNET_assert (NULL != namestore); + namestore = GNUNET_NAMESTORE_connect(cfg); + GNUNET_assert(NULL != namestore); flags = MHD_USE_DEBUG; if (GNUNET_YES == use_v6) flags |= MHD_USE_DUAL_STACK; - mhd = MHD_start_daemon (flags, - PORT, - NULL, NULL, - &mhd_ahc, NULL, - MHD_OPTION_END); - GNUNET_assert (NULL != mhd); - mhd_main (); - - identity = GNUNET_IDENTITY_connect (cfg, - &identity_cb, - NULL); + mhd = MHD_start_daemon(flags, + PORT, + NULL, NULL, + &mhd_ahc, NULL, + MHD_OPTION_END); + GNUNET_assert(NULL != mhd); + mhd_main(); + + identity = GNUNET_IDENTITY_connect(cfg, + &identity_cb, + NULL); } int -main (int argc, - char *const *argv) +main(int argc, + char *const *argv) { char *bin_vpn; char *bin_exit; - GNUNET_log_setup ("test-gns-vpn", - "WARNING", - NULL); - if (0 != ACCESS ("/dev/net/tun", R_OK)) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, - "access", - "/dev/net/tun"); - fprintf (stderr, - "WARNING: System unable to run test, skipping.\n"); - return 77; - } - - bin_vpn = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-vpn"); - bin_exit = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-exit"); - if ( (0 != geteuid ()) && - ( (GNUNET_YES != - GNUNET_OS_check_helper_binary (bin_vpn, - GNUNET_YES, - "-d gnunet-vpn - - 169.1.3.3.7 255.255.255.0")) || //ipv4 only please! - (GNUNET_YES != - GNUNET_OS_check_helper_binary (bin_exit, - GNUNET_YES, - "-d gnunet-vpn - - - 169.1.3.3.7 255.255.255.0")) ) ) //no nat, ipv4 only - { - fprintf (stderr, - "WARNING: gnunet-helper-{exit,vpn} binaries in $PATH are not SUID, refusing to run test (as it would have to fail).\n"); - fprintf (stderr, - "Change $PATH ('.' in $PATH before $GNUNET_PREFIX/bin is problematic) or permissions (run 'make install' as root) to fix this!\n"); - GNUNET_free (bin_vpn); - GNUNET_free (bin_exit); - return 77; - } - GNUNET_free (bin_vpn); - GNUNET_free (bin_exit); + GNUNET_log_setup("test-gns-vpn", + "WARNING", + NULL); + if (0 != ACCESS("/dev/net/tun", R_OK)) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, + "access", + "/dev/net/tun"); + fprintf(stderr, + "WARNING: System unable to run test, skipping.\n"); + return 77; + } + + bin_vpn = GNUNET_OS_get_libexec_binary_path("gnunet-helper-vpn"); + bin_exit = GNUNET_OS_get_libexec_binary_path("gnunet-helper-exit"); + if ((0 != geteuid()) && + ((GNUNET_YES != + GNUNET_OS_check_helper_binary(bin_vpn, + GNUNET_YES, + "-d gnunet-vpn - - 169.1.3.3.7 255.255.255.0")) || //ipv4 only please! + (GNUNET_YES != + GNUNET_OS_check_helper_binary(bin_exit, + GNUNET_YES, + "-d gnunet-vpn - - - 169.1.3.3.7 255.255.255.0")))) //no nat, ipv4 only + { + fprintf(stderr, + "WARNING: gnunet-helper-{exit,vpn} binaries in $PATH are not SUID, refusing to run test (as it would have to fail).\n"); + fprintf(stderr, + "Change $PATH ('.' in $PATH before $GNUNET_PREFIX/bin is problematic) or permissions (run 'make install' as root) to fix this!\n"); + GNUNET_free(bin_vpn); + GNUNET_free(bin_exit); + return 77; + } + GNUNET_free(bin_vpn); + GNUNET_free(bin_exit); dest_ip = "169.254.86.1"; dest_af = AF_INET; src_af = AF_INET; - if (GNUNET_OK == GNUNET_NETWORK_test_pf (PF_INET6)) + if (GNUNET_OK == GNUNET_NETWORK_test_pf(PF_INET6)) use_v6 = GNUNET_YES; else use_v6 = GNUNET_NO; - if ( (GNUNET_OK != GNUNET_NETWORK_test_pf (src_af)) || - (GNUNET_OK != GNUNET_NETWORK_test_pf (dest_af)) ) - { - fprintf (stderr, - "Required address families not supported by this system, skipping test.\n"); - return 77; - } - if (0 != curl_global_init (CURL_GLOBAL_WIN32)) - { - fprintf (stderr, "failed to initialize curl\n"); - return 2; - } + if ((GNUNET_OK != GNUNET_NETWORK_test_pf(src_af)) || + (GNUNET_OK != GNUNET_NETWORK_test_pf(dest_af))) + { + fprintf(stderr, + "Required address families not supported by this system, skipping test.\n"); + return 77; + } + if (0 != curl_global_init(CURL_GLOBAL_WIN32)) + { + fprintf(stderr, "failed to initialize curl\n"); + return 2; + } if (0 != - GNUNET_TESTING_peer_run ("test_gns_vpn", - "test_gns_vpn.conf", - &run, - NULL)) + GNUNET_TESTING_peer_run("test_gns_vpn", + "test_gns_vpn.conf", + &run, + NULL)) return 1; - GNUNET_DISK_directory_remove ("/tmp/gnunet-test-vpn"); + GNUNET_DISK_directory_remove("/tmp/gnunet-test-vpn"); return global_ret; } diff --git a/src/pt/test_gnunet_vpn.c b/src/pt/test_gnunet_vpn.c index 7cc77fe24..ae5910824 100644 --- a/src/pt/test_gnunet_vpn.c +++ b/src/pt/test_gnunet_vpn.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file test_gnunet_vpn.c @@ -32,7 +32,7 @@ #define PORT 48080 -#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 300) +#define TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 300) /** @@ -74,8 +74,7 @@ static int dest_af; static int src_af; -struct CBC -{ +struct CBC { char buf[1024]; size_t pos; }; @@ -84,87 +83,87 @@ static struct CBC cbc; static size_t -copy_buffer (void *ptr, size_t size, size_t nmemb, void *ctx) +copy_buffer(void *ptr, size_t size, size_t nmemb, void *ctx) { struct CBC *cbc = ctx; - if (cbc->pos + size * nmemb > sizeof (cbc->buf)) + if (cbc->pos + size * nmemb > sizeof(cbc->buf)) return 0; /* overflow */ - GNUNET_memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); + GNUNET_memcpy(&cbc->buf[cbc->pos], ptr, size * nmemb); cbc->pos += size * nmemb; return size * nmemb; } static int -mhd_ahc (void *cls, - struct MHD_Connection *connection, - const char *url, - const char *method, - const char *version, - const char *upload_data, - size_t * upload_data_size, - void **unused) +mhd_ahc(void *cls, + struct MHD_Connection *connection, + const char *url, + const char *method, + const char *version, + const char *upload_data, + size_t * upload_data_size, + void **unused) { static int ptr; struct MHD_Response *response; int ret; - if (0 != strcmp ("GET", method)) + if (0 != strcmp("GET", method)) return MHD_NO; /* unexpected method */ if (&ptr != *unused) - { - *unused = &ptr; - return MHD_YES; - } + { + *unused = &ptr; + return MHD_YES; + } *unused = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "MHD sends respose for request to URL `%s'\n", url); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "MHD sends respose for request to URL `%s'\n", url); response = - MHD_create_response_from_buffer (strlen (url), (void *) url, - MHD_RESPMEM_MUST_COPY); - ret = MHD_queue_response (connection, MHD_HTTP_OK, response); - MHD_destroy_response (response); + MHD_create_response_from_buffer(strlen(url), (void *)url, + MHD_RESPMEM_MUST_COPY); + ret = MHD_queue_response(connection, MHD_HTTP_OK, response); + MHD_destroy_response(response); if (ret == MHD_NO) - abort (); + abort(); return ret; } static void -do_shutdown (void *cls) +do_shutdown(void *cls) { if (NULL != mhd_task_id) - { - GNUNET_SCHEDULER_cancel (mhd_task_id); - mhd_task_id = NULL; - } + { + GNUNET_SCHEDULER_cancel(mhd_task_id); + mhd_task_id = NULL; + } if (NULL != curl_task_id) - { - GNUNET_SCHEDULER_cancel (curl_task_id); - curl_task_id = NULL; - } + { + GNUNET_SCHEDULER_cancel(curl_task_id); + curl_task_id = NULL; + } if (NULL != timeout_task_id) - { - GNUNET_SCHEDULER_cancel (timeout_task_id); - timeout_task_id = NULL; - } + { + GNUNET_SCHEDULER_cancel(timeout_task_id); + timeout_task_id = NULL; + } if (NULL != mhd) - { - MHD_stop_daemon (mhd); - mhd = NULL; - } + { + MHD_stop_daemon(mhd); + mhd = NULL; + } if (NULL != rr) - { - GNUNET_VPN_cancel_request (rr); - rr = NULL; - } + { + GNUNET_VPN_cancel_request(rr); + rr = NULL; + } if (NULL != vpn) - { - GNUNET_VPN_disconnect (vpn); - vpn = NULL; - } - GNUNET_free_non_null (url); + { + GNUNET_VPN_disconnect(vpn); + vpn = NULL; + } + GNUNET_free_non_null(url); url = NULL; } @@ -173,7 +172,7 @@ do_shutdown (void *cls) * Function to run the HTTP client. */ static void -curl_main (void *cls) +curl_main(void *cls) { fd_set rs; fd_set ws; @@ -188,55 +187,55 @@ curl_main (void *cls) curl_task_id = NULL; max = 0; - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); - curl_multi_perform (multi, &running); + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); + curl_multi_perform(multi, &running); if (running == 0) - { - GNUNET_assert (NULL != (msg = curl_multi_info_read (multi, &running))); - if (msg->msg == CURLMSG_DONE) { - if (msg->data.result != CURLE_OK) - { - fprintf (stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", - __FILE__, __LINE__, curl_easy_strerror (msg->data.result)); - global_ret = 1; - } + GNUNET_assert(NULL != (msg = curl_multi_info_read(multi, &running))); + if (msg->msg == CURLMSG_DONE) + { + if (msg->data.result != CURLE_OK) + { + fprintf(stderr, "%s failed at %s:%d: `%s'\n", "curl_multi_perform", + __FILE__, __LINE__, curl_easy_strerror(msg->data.result)); + global_ret = 1; + } + } + curl_multi_remove_handle(multi, curl); + curl_multi_cleanup(multi); + curl_easy_cleanup(curl); + curl = NULL; + multi = NULL; + if (cbc.pos != strlen("/hello_world")) + { + GNUNET_break(0); + global_ret = 2; + } + if (0 != strncmp("/hello_world", cbc.buf, strlen("/hello_world"))) + { + GNUNET_break(0); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "You might want to check if your host-based firewall is blocking the connections.\n"); + global_ret = 3; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Download complete, shutting down!\n"); + GNUNET_SCHEDULER_shutdown(); + return; } - curl_multi_remove_handle (multi, curl); - curl_multi_cleanup (multi); - curl_easy_cleanup (curl); - curl = NULL; - multi = NULL; - if (cbc.pos != strlen ("/hello_world")) - { - GNUNET_break (0); - global_ret = 2; - } - if (0 != strncmp ("/hello_world", cbc.buf, strlen ("/hello_world"))) - { - GNUNET_break (0); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "You might want to check if your host-based firewall is blocking the connections.\n"); - global_ret = 3; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Download complete, shutting down!\n"); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_assert (CURLM_OK == curl_multi_fdset (multi, &rs, &ws, &es, &max)); - if ((CURLM_OK != curl_multi_timeout (multi, &timeout)) || (-1 == timeout)) + GNUNET_assert(CURLM_OK == curl_multi_fdset(multi, &rs, &ws, &es, &max)); + if ((CURLM_OK != curl_multi_timeout(multi, &timeout)) || (-1 == timeout)) delay = GNUNET_TIME_UNIT_SECONDS; else delay = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, - (unsigned int) timeout); - GNUNET_NETWORK_fdset_copy_native (&nrs, &rs, max + 1); - GNUNET_NETWORK_fdset_copy_native (&nws, &ws, max + 1); + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, + (unsigned int)timeout); + GNUNET_NETWORK_fdset_copy_native(&nrs, &rs, max + 1); + GNUNET_NETWORK_fdset_copy_native(&nws, &ws, max + 1); curl_task_id = - GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, delay, - &nrs, &nws, &curl_main, NULL); + GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT, delay, + &nrs, &nws, &curl_main, NULL); } @@ -254,53 +253,53 @@ curl_main (void *cls) * specified target peer; NULL on error */ static void -allocation_cb (void *cls, int af, const void *address) +allocation_cb(void *cls, int af, const void *address) { char ips[INET6_ADDRSTRLEN]; rr = NULL; if (src_af != af) - { - fprintf (stderr, - "VPN failed to allocate appropriate address\n"); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + fprintf(stderr, + "VPN failed to allocate appropriate address\n"); + GNUNET_SCHEDULER_shutdown(); + return; + } if (AF_INET6 == af) - GNUNET_asprintf (&url, - "http://[%s]:%u/hello_world", - inet_ntop (af, - address, - ips, - sizeof (ips)), - (unsigned int) PORT); + GNUNET_asprintf(&url, + "http://[%s]:%u/hello_world", + inet_ntop(af, + address, + ips, + sizeof(ips)), + (unsigned int)PORT); else - GNUNET_asprintf (&url, - "http://%s:%u/hello_world", - inet_ntop (af, - address, - ips, - sizeof (ips)), - (unsigned int) PORT); - curl = curl_easy_init (); - curl_easy_setopt (curl, CURLOPT_URL, url); - curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, ©_buffer); - curl_easy_setopt (curl, CURLOPT_WRITEDATA, &cbc); - curl_easy_setopt (curl, CURLOPT_FAILONERROR, 1); - curl_easy_setopt (curl, CURLOPT_TIMEOUT, 150L); - curl_easy_setopt (curl, CURLOPT_CONNECTTIMEOUT, 15L); - curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1); - curl_easy_setopt (curl, CURLOPT_VERBOSE, 0); - - multi = curl_multi_init (); - GNUNET_assert (multi != NULL); - GNUNET_assert (CURLM_OK == curl_multi_add_handle (multi, curl)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Beginning HTTP download from `%s'\n", - url); - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, - &curl_main, - NULL); + GNUNET_asprintf(&url, + "http://%s:%u/hello_world", + inet_ntop(af, + address, + ips, + sizeof(ips)), + (unsigned int)PORT); + curl = curl_easy_init(); + curl_easy_setopt(curl, CURLOPT_URL, url); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ©_buffer); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, &cbc); + curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1); + curl_easy_setopt(curl, CURLOPT_TIMEOUT, 150L); + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15L); + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 0); + + multi = curl_multi_init(); + GNUNET_assert(multi != NULL); + GNUNET_assert(CURLM_OK == curl_multi_add_handle(multi, curl)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Beginning HTTP download from `%s'\n", + url); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, + &curl_main, + NULL); } @@ -308,30 +307,30 @@ allocation_cb (void *cls, int af, const void *address) * Function to keep the HTTP server running. */ static void -mhd_main (void); +mhd_main(void); static void -mhd_task (void *cls) +mhd_task(void *cls) { mhd_task_id = NULL; - MHD_run (mhd); - mhd_main (); + MHD_run(mhd); + mhd_main(); } static void -do_timeout (void *cls) +do_timeout(void *cls) { timeout_task_id = NULL; - GNUNET_SCHEDULER_shutdown (); - GNUNET_break (0); + GNUNET_SCHEDULER_shutdown(); + GNUNET_break(0); global_ret = 1; } static void -mhd_main () +mhd_main() { struct GNUNET_NETWORK_FDSet nrs; struct GNUNET_NETWORK_FDSet nws; @@ -342,76 +341,78 @@ mhd_main () unsigned MHD_LONG_LONG timeout; struct GNUNET_TIME_Relative delay; - GNUNET_assert (NULL == mhd_task_id); - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); + GNUNET_assert(NULL == mhd_task_id); + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); max_fd = -1; - GNUNET_assert (MHD_YES == MHD_get_fdset (mhd, &rs, &ws, &es, &max_fd)); - if (MHD_YES == MHD_get_timeout (mhd, &timeout)) + GNUNET_assert(MHD_YES == MHD_get_fdset(mhd, &rs, &ws, &es, &max_fd)); + if (MHD_YES == MHD_get_timeout(mhd, &timeout)) delay = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, - (unsigned int) timeout); + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, + (unsigned int)timeout); else delay = GNUNET_TIME_UNIT_FOREVER_REL; - GNUNET_NETWORK_fdset_copy_native (&nrs, &rs, max_fd + 1); - GNUNET_NETWORK_fdset_copy_native (&nws, &ws, max_fd + 1); + GNUNET_NETWORK_fdset_copy_native(&nrs, &rs, max_fd + 1); + GNUNET_NETWORK_fdset_copy_native(&nws, &ws, max_fd + 1); mhd_task_id = - GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, delay, - &nrs, &nws, &mhd_task, NULL); + GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT, delay, + &nrs, &nws, &mhd_task, NULL); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { struct in_addr v4; struct in6_addr v6; void *addr; enum MHD_FLAG flags; - vpn = GNUNET_VPN_connect (cfg); - GNUNET_assert (NULL != vpn); + vpn = GNUNET_VPN_connect(cfg); + GNUNET_assert(NULL != vpn); flags = MHD_USE_DEBUG; if (AF_INET6 == dest_af) flags |= MHD_USE_IPv6; mhd = - MHD_start_daemon (flags, PORT, NULL, NULL, &mhd_ahc, NULL, - MHD_OPTION_END); + MHD_start_daemon(flags, PORT, NULL, NULL, &mhd_ahc, NULL, + MHD_OPTION_END); - GNUNET_assert (NULL != mhd); - mhd_main (); + GNUNET_assert(NULL != mhd); + mhd_main(); addr = NULL; switch (dest_af) - { - case AF_INET: - GNUNET_assert (1 == inet_pton (dest_af, dest_ip, &v4)); - addr = &v4; - break; - case AF_INET6: - GNUNET_assert (1 == inet_pton (dest_af, dest_ip, &v6)); - addr = &v6; - break; - default: - GNUNET_assert (0); - } - rr = GNUNET_VPN_redirect_to_ip (vpn, src_af, dest_af, addr, - GNUNET_TIME_UNIT_FOREVER_ABS, &allocation_cb, - NULL); + { + case AF_INET: + GNUNET_assert(1 == inet_pton(dest_af, dest_ip, &v4)); + addr = &v4; + break; + + case AF_INET6: + GNUNET_assert(1 == inet_pton(dest_af, dest_ip, &v6)); + addr = &v6; + break; + + default: + GNUNET_assert(0); + } + rr = GNUNET_VPN_redirect_to_ip(vpn, src_af, dest_af, addr, + GNUNET_TIME_UNIT_FOREVER_ABS, &allocation_cb, + NULL); timeout_task_id = - GNUNET_SCHEDULER_add_delayed (TIMEOUT, - &do_timeout, - NULL); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, + GNUNET_SCHEDULER_add_delayed(TIMEOUT, + &do_timeout, NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); } int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { const char *type; const char *bin; @@ -420,90 +421,90 @@ main (int argc, char *const *argv) int ret = 0; #ifndef MINGW - if (0 != ACCESS ("/dev/net/tun", R_OK)) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, - "access", - "/dev/net/tun"); - fprintf (stderr, - "WARNING: System unable to run test, skipping.\n"); - return 77; - } + if (0 != ACCESS("/dev/net/tun", R_OK)) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, + "access", + "/dev/net/tun"); + fprintf(stderr, + "WARNING: System unable to run test, skipping.\n"); + return 77; + } #endif - vpn_binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-vpn"); - exit_binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-exit"); - if ((GNUNET_YES != (ret = GNUNET_OS_check_helper_binary (vpn_binary, GNUNET_YES, "-d gnunet-vpn - - 169.1.3.3.7 255.255.255.0"))) || //ipv4 only please! - (GNUNET_YES != (ret = GNUNET_OS_check_helper_binary (exit_binary, GNUNET_YES, "-d gnunet-vpn - - - 169.1.3.3.7 255.255.255.0")))) //no nat, ipv4 only - { - GNUNET_free (vpn_binary); - GNUNET_free (exit_binary); - fprintf (stderr, - "WARNING: gnunet-helper-{exit,vpn} binaries are not SUID, refusing to run test (as it would have to fail). %d\n", ret); - return 77; - } - - GNUNET_free (vpn_binary); - GNUNET_free (exit_binary); + vpn_binary = GNUNET_OS_get_libexec_binary_path("gnunet-helper-vpn"); + exit_binary = GNUNET_OS_get_libexec_binary_path("gnunet-helper-exit"); + if ((GNUNET_YES != (ret = GNUNET_OS_check_helper_binary(vpn_binary, GNUNET_YES, "-d gnunet-vpn - - 169.1.3.3.7 255.255.255.0"))) || //ipv4 only please! + (GNUNET_YES != (ret = GNUNET_OS_check_helper_binary(exit_binary, GNUNET_YES, "-d gnunet-vpn - - - 169.1.3.3.7 255.255.255.0")))) //no nat, ipv4 only + { + GNUNET_free(vpn_binary); + GNUNET_free(exit_binary); + fprintf(stderr, + "WARNING: gnunet-helper-{exit,vpn} binaries are not SUID, refusing to run test (as it would have to fail). %d\n", ret); + return 77; + } + + GNUNET_free(vpn_binary); + GNUNET_free(exit_binary); bin = argv[0]; - if (NULL != strstr (bin, "lt-")) - bin = strstr (bin, "lt-") + 4; - type = strstr (bin, "-"); + if (NULL != strstr(bin, "lt-")) + bin = strstr(bin, "lt-") + 4; + type = strstr(bin, "-"); if (NULL == type) - { - fprintf (stderr, - "invalid binary name\n"); - return 1; - } + { + fprintf(stderr, + "invalid binary name\n"); + return 1; + } type++; /* on Windows, .exe is suffixed to these binaries, * thus cease comparison after the 6th char. */ - if (0 == strncmp (type, "4_to_6",6)) - { - dest_ip = "FC5A:04E1:C2BA::1"; - dest_af = AF_INET6; - src_af = AF_INET; - } - else if (0 == strncmp (type, "6_to_4",6)) - { - dest_ip = "169.254.86.1"; - dest_af = AF_INET; - src_af = AF_INET6; - } - else if (0 == strncmp (type, "4_over",6)) - { - dest_ip = "169.254.86.1"; - dest_af = AF_INET; - src_af = AF_INET; - } - else if (0 == strncmp (type, "6_over",6)) - { - dest_ip = "FC5A:04E1:C2BA::1"; - dest_af = AF_INET6; - src_af = AF_INET6; - } + if (0 == strncmp(type, "4_to_6", 6)) + { + dest_ip = "FC5A:04E1:C2BA::1"; + dest_af = AF_INET6; + src_af = AF_INET; + } + else if (0 == strncmp(type, "6_to_4", 6)) + { + dest_ip = "169.254.86.1"; + dest_af = AF_INET; + src_af = AF_INET6; + } + else if (0 == strncmp(type, "4_over", 6)) + { + dest_ip = "169.254.86.1"; + dest_af = AF_INET; + src_af = AF_INET; + } + else if (0 == strncmp(type, "6_over", 6)) + { + dest_ip = "FC5A:04E1:C2BA::1"; + dest_af = AF_INET6; + src_af = AF_INET6; + } else - { - fprintf (stderr, "invalid binary suffix `%s'\n", type); - return 1; - } - if ((GNUNET_OK != GNUNET_NETWORK_test_pf (src_af)) || - (GNUNET_OK != GNUNET_NETWORK_test_pf (dest_af))) - { - fprintf (stderr, - "Required address families not supported by this system, skipping test.\n"); - return 0; - } - if (0 != curl_global_init (CURL_GLOBAL_WIN32)) - { - fprintf (stderr, "failed to initialize curl\n"); - return 2; - } + { + fprintf(stderr, "invalid binary suffix `%s'\n", type); + return 1; + } + if ((GNUNET_OK != GNUNET_NETWORK_test_pf(src_af)) || + (GNUNET_OK != GNUNET_NETWORK_test_pf(dest_af))) + { + fprintf(stderr, + "Required address families not supported by this system, skipping test.\n"); + return 0; + } + if (0 != curl_global_init(CURL_GLOBAL_WIN32)) + { + fprintf(stderr, "failed to initialize curl\n"); + return 2; + } if (0 != - GNUNET_TESTING_peer_run ("test-gnunet-vpn", "test_gnunet_vpn.conf", &run, - NULL)) + GNUNET_TESTING_peer_run("test-gnunet-vpn", "test_gnunet_vpn.conf", &run, + NULL)) return 1; - GNUNET_DISK_directory_remove ("/tmp/gnunet-test-vpn"); + GNUNET_DISK_directory_remove("/tmp/gnunet-test-vpn"); return global_ret; } diff --git a/src/reclaim-attribute/plugin_reclaim_attribute_gnuid.c b/src/reclaim-attribute/plugin_reclaim_attribute_gnuid.c index 8999bcadf..c47148c19 100644 --- a/src/reclaim-attribute/plugin_reclaim_attribute_gnuid.c +++ b/src/reclaim-attribute/plugin_reclaim_attribute_gnuid.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file reclaim-attribute/plugin_reclaim_attribute_gnuid.c @@ -42,19 +42,19 @@ * @return NULL on error, otherwise human-readable representation of the value */ static char * -gnuid_value_to_string (void *cls, - uint32_t type, - const void *data, - size_t data_size) +gnuid_value_to_string(void *cls, + uint32_t type, + const void *data, + size_t data_size) { - switch (type) - { + { case GNUNET_RECLAIM_ATTRIBUTE_TYPE_STRING: - return GNUNET_strndup (data, data_size); + return GNUNET_strndup(data, data_size); + default: return NULL; - } + } } @@ -70,24 +70,24 @@ gnuid_value_to_string (void *cls, * @return #GNUNET_OK on success */ static int -gnuid_string_to_value (void *cls, - uint32_t type, - const char *s, - void **data, - size_t *data_size) +gnuid_string_to_value(void *cls, + uint32_t type, + const char *s, + void **data, + size_t *data_size) { if (NULL == s) return GNUNET_SYSERR; switch (type) - { - + { case GNUNET_RECLAIM_ATTRIBUTE_TYPE_STRING: - *data = GNUNET_strdup (s); - *data_size = strlen (s); + *data = GNUNET_strdup(s); + *data_size = strlen(s); return GNUNET_OK; + default: return GNUNET_SYSERR; - } + } } @@ -95,12 +95,11 @@ gnuid_string_to_value (void *cls, * Mapping of attribute type numbers to human-readable * attribute type names. */ -static struct -{ +static struct { const char *name; uint32_t number; -} gnuid_name_map[] = {{"STRING", GNUNET_RECLAIM_ATTRIBUTE_TYPE_STRING}, - {NULL, UINT32_MAX}}; +} gnuid_name_map[] = { { "STRING", GNUNET_RECLAIM_ATTRIBUTE_TYPE_STRING }, + { NULL, UINT32_MAX } }; /** @@ -111,13 +110,13 @@ static struct * @return corresponding number, UINT32_MAX on error */ static uint32_t -gnuid_typename_to_number (void *cls, const char *gnuid_typename) +gnuid_typename_to_number(void *cls, const char *gnuid_typename) { unsigned int i; i = 0; while ((NULL != gnuid_name_map[i].name) && - (0 != strcasecmp (gnuid_typename, gnuid_name_map[i].name))) + (0 != strcasecmp(gnuid_typename, gnuid_name_map[i].name))) i++; return gnuid_name_map[i].number; } @@ -131,7 +130,7 @@ gnuid_typename_to_number (void *cls, const char *gnuid_typename) * @return corresponding typestring, NULL on error */ static const char * -gnuid_number_to_typename (void *cls, uint32_t type) +gnuid_number_to_typename(void *cls, uint32_t type) { unsigned int i; @@ -149,11 +148,11 @@ gnuid_number_to_typename (void *cls, uint32_t type) * @return the exported block API */ void * -libgnunet_plugin_reclaim_attribute_gnuid_init (void *cls) +libgnunet_plugin_reclaim_attribute_gnuid_init(void *cls) { struct GNUNET_RECLAIM_ATTRIBUTE_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_RECLAIM_ATTRIBUTE_PluginFunctions); + api = GNUNET_new(struct GNUNET_RECLAIM_ATTRIBUTE_PluginFunctions); api->value_to_string = &gnuid_value_to_string; api->string_to_value = &gnuid_string_to_value; api->typename_to_number = &gnuid_typename_to_number; @@ -169,11 +168,11 @@ libgnunet_plugin_reclaim_attribute_gnuid_init (void *cls) * @return NULL */ void * -libgnunet_plugin_reclaim_attribute_gnuid_done (void *cls) +libgnunet_plugin_reclaim_attribute_gnuid_done(void *cls) { struct GNUNET_RECLAIM_ATTRIBUTE_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/reclaim-attribute/reclaim_attribute.c b/src/reclaim-attribute/reclaim_attribute.c index 96e61d431..9ef648708 100644 --- a/src/reclaim-attribute/reclaim_attribute.c +++ b/src/reclaim-attribute/reclaim_attribute.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @file reclaim-attribute/reclaim_attribute.c @@ -32,8 +32,7 @@ /** * Handle for a plugin */ -struct Plugin -{ +struct Plugin { /** * Name of the plugin */ @@ -72,18 +71,18 @@ static int initialized; * @param lib_ret the plugin API pointer */ static void -add_plugin (void *cls, const char *library_name, void *lib_ret) +add_plugin(void *cls, const char *library_name, void *lib_ret) { struct GNUNET_RECLAIM_ATTRIBUTE_PluginFunctions *api = lib_ret; struct Plugin *plugin; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Loading attribute plugin `%s'\n", - library_name); - plugin = GNUNET_new (struct Plugin); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Loading attribute plugin `%s'\n", + library_name); + plugin = GNUNET_new(struct Plugin); plugin->api = api; - plugin->library_name = GNUNET_strdup (library_name); - GNUNET_array_append (attr_plugins, num_plugins, plugin); + plugin->library_name = GNUNET_strdup(library_name); + GNUNET_array_append(attr_plugins, num_plugins, plugin); } @@ -91,15 +90,15 @@ add_plugin (void *cls, const char *library_name, void *lib_ret) * Load plugins */ static void -init () +init() { if (GNUNET_YES == initialized) return; initialized = GNUNET_YES; - GNUNET_PLUGIN_load_all ("libgnunet_plugin_reclaim_attribute_", - NULL, - &add_plugin, - NULL); + GNUNET_PLUGIN_load_all("libgnunet_plugin_reclaim_attribute_", + NULL, + &add_plugin, + NULL); } @@ -110,20 +109,20 @@ init () * @return corresponding number, UINT32_MAX on error */ uint32_t -GNUNET_RECLAIM_ATTRIBUTE_typename_to_number (const char *typename) +GNUNET_RECLAIM_ATTRIBUTE_typename_to_number(const char *typename) { unsigned int i; struct Plugin *plugin; uint32_t ret; - init (); + init(); for (i = 0; i < num_plugins; i++) - { - plugin = attr_plugins[i]; - if (UINT32_MAX != - (ret = plugin->api->typename_to_number (plugin->api->cls, typename))) - return ret; - } + { + plugin = attr_plugins[i]; + if (UINT32_MAX != + (ret = plugin->api->typename_to_number(plugin->api->cls, typename))) + return ret; + } return UINT32_MAX; } @@ -135,20 +134,20 @@ GNUNET_RECLAIM_ATTRIBUTE_typename_to_number (const char *typename) * @return corresponding typestring, NULL on error */ const char * -GNUNET_RECLAIM_ATTRIBUTE_number_to_typename (uint32_t type) +GNUNET_RECLAIM_ATTRIBUTE_number_to_typename(uint32_t type) { unsigned int i; struct Plugin *plugin; const char *ret; - init (); + init(); for (i = 0; i < num_plugins; i++) - { - plugin = attr_plugins[i]; - if (NULL != - (ret = plugin->api->number_to_typename (plugin->api->cls, type))) - return ret; - } + { + plugin = attr_plugins[i]; + if (NULL != + (ret = plugin->api->number_to_typename(plugin->api->cls, type))) + return ret; + } return NULL; } @@ -164,25 +163,25 @@ GNUNET_RECLAIM_ATTRIBUTE_number_to_typename (uint32_t type) * @return #GNUNET_OK on success */ int -GNUNET_RECLAIM_ATTRIBUTE_string_to_value (uint32_t type, - const char *s, - void **data, - size_t *data_size) +GNUNET_RECLAIM_ATTRIBUTE_string_to_value(uint32_t type, + const char *s, + void **data, + size_t *data_size) { unsigned int i; struct Plugin *plugin; - init (); + init(); for (i = 0; i < num_plugins; i++) - { - plugin = attr_plugins[i]; - if (GNUNET_OK == plugin->api->string_to_value (plugin->api->cls, - type, - s, - data, - data_size)) - return GNUNET_OK; - } + { + plugin = attr_plugins[i]; + if (GNUNET_OK == plugin->api->string_to_value(plugin->api->cls, + type, + s, + data, + data_size)) + return GNUNET_OK; + } return GNUNET_SYSERR; } @@ -196,24 +195,24 @@ GNUNET_RECLAIM_ATTRIBUTE_string_to_value (uint32_t type, * @return NULL on error, otherwise human-readable representation of the claim */ char * -GNUNET_RECLAIM_ATTRIBUTE_value_to_string (uint32_t type, - const void *data, - size_t data_size) +GNUNET_RECLAIM_ATTRIBUTE_value_to_string(uint32_t type, + const void *data, + size_t data_size) { unsigned int i; struct Plugin *plugin; char *ret; - init (); + init(); for (i = 0; i < num_plugins; i++) - { - plugin = attr_plugins[i]; - if (NULL != (ret = plugin->api->value_to_string (plugin->api->cls, - type, - data, - data_size))) - return ret; - } + { + plugin = attr_plugins[i]; + if (NULL != (ret = plugin->api->value_to_string(plugin->api->cls, + type, + data, + data_size))) + return ret; + } return NULL; } @@ -228,29 +227,29 @@ GNUNET_RECLAIM_ATTRIBUTE_value_to_string (uint32_t type, * @return the new attribute */ struct GNUNET_RECLAIM_ATTRIBUTE_Claim * -GNUNET_RECLAIM_ATTRIBUTE_claim_new (const char *attr_name, - uint32_t type, - const void *data, - size_t data_size) +GNUNET_RECLAIM_ATTRIBUTE_claim_new(const char *attr_name, + uint32_t type, + const void *data, + size_t data_size) { struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr; char *write_ptr; - char *attr_name_tmp = GNUNET_strdup (attr_name); + char *attr_name_tmp = GNUNET_strdup(attr_name); - GNUNET_STRINGS_utf8_tolower (attr_name, attr_name_tmp); + GNUNET_STRINGS_utf8_tolower(attr_name, attr_name_tmp); - attr = GNUNET_malloc (sizeof (struct GNUNET_RECLAIM_ATTRIBUTE_Claim) + - strlen (attr_name_tmp) + 1 + data_size); + attr = GNUNET_malloc(sizeof(struct GNUNET_RECLAIM_ATTRIBUTE_Claim) + + strlen(attr_name_tmp) + 1 + data_size); attr->type = type; attr->data_size = data_size; attr->version = 0; - write_ptr = (char *) &attr[1]; - GNUNET_memcpy (write_ptr, attr_name_tmp, strlen (attr_name_tmp) + 1); + write_ptr = (char *)&attr[1]; + GNUNET_memcpy(write_ptr, attr_name_tmp, strlen(attr_name_tmp) + 1); attr->name = write_ptr; - write_ptr += strlen (attr->name) + 1; - GNUNET_memcpy (write_ptr, data, data_size); + write_ptr += strlen(attr->name) + 1; + GNUNET_memcpy(write_ptr, data, data_size); attr->data = write_ptr; - GNUNET_free (attr_name_tmp); + GNUNET_free(attr_name_tmp); return attr; } @@ -264,20 +263,21 @@ GNUNET_RECLAIM_ATTRIBUTE_claim_new (const char *attr_name, * @param data_size claim payload size */ void -GNUNET_RECLAIM_ATTRIBUTE_list_add ( - struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *claim_list, - const char *attr_name, - uint32_t type, - const void *data, - size_t data_size) +GNUNET_RECLAIM_ATTRIBUTE_list_add( + struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *claim_list, + const char *attr_name, + uint32_t type, + const void *data, + size_t data_size) { struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le; - le = GNUNET_new (struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry); + + le = GNUNET_new(struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry); le->claim = - GNUNET_RECLAIM_ATTRIBUTE_claim_new (attr_name, type, data, data_size); - GNUNET_CONTAINER_DLL_insert (claim_list->list_head, - claim_list->list_tail, - le); + GNUNET_RECLAIM_ATTRIBUTE_claim_new(attr_name, type, data, data_size); + GNUNET_CONTAINER_DLL_insert(claim_list->list_head, + claim_list->list_tail, + le); } @@ -288,13 +288,14 @@ GNUNET_RECLAIM_ATTRIBUTE_list_add ( * @return the required buffer size */ size_t -GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size ( - const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs) +GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size( + const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs) { struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le; size_t len = 0; + for (le = attrs->list_head; NULL != le; le = le->next) - len += GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size (le->claim); + len += GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size(le->claim); return len; } @@ -307,9 +308,9 @@ GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size ( * @return length of serialized data */ size_t -GNUNET_RECLAIM_ATTRIBUTE_list_serialize ( - const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, - char *result) +GNUNET_RECLAIM_ATTRIBUTE_list_serialize( + const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, + char *result) { struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le; size_t len; @@ -319,11 +320,11 @@ GNUNET_RECLAIM_ATTRIBUTE_list_serialize ( write_ptr = result; total_len = 0; for (le = attrs->list_head; NULL != le; le = le->next) - { - len = GNUNET_RECLAIM_ATTRIBUTE_serialize (le->claim, write_ptr); - total_len += len; - write_ptr += len; - } + { + len = GNUNET_RECLAIM_ATTRIBUTE_serialize(le->claim, write_ptr); + total_len += len; + write_ptr += len; + } return total_len; } @@ -336,32 +337,31 @@ GNUNET_RECLAIM_ATTRIBUTE_list_serialize ( * @return a GNUNET_IDENTITY_PROVIDER_AttributeList, must be free'd by caller */ struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList * -GNUNET_RECLAIM_ATTRIBUTE_list_deserialize (const char *data, size_t data_size) +GNUNET_RECLAIM_ATTRIBUTE_list_deserialize(const char *data, size_t data_size) { struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs; struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le; size_t attr_len; const char *read_ptr; - if (data_size < sizeof (struct Attribute)) + if (data_size < sizeof(struct Attribute)) return NULL; - attrs = GNUNET_new (struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList); + attrs = GNUNET_new(struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList); read_ptr = data; - while (((data + data_size) - read_ptr) >= sizeof (struct Attribute)) - { - - le = GNUNET_new (struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry); - le->claim = - GNUNET_RECLAIM_ATTRIBUTE_deserialize (read_ptr, - data_size - (read_ptr - data)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Deserialized attribute %s\n", - le->claim->name); - GNUNET_CONTAINER_DLL_insert (attrs->list_head, attrs->list_tail, le); - attr_len = GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size (le->claim); - read_ptr += attr_len; - } + while (((data + data_size) - read_ptr) >= sizeof(struct Attribute)) + { + le = GNUNET_new(struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry); + le->claim = + GNUNET_RECLAIM_ATTRIBUTE_deserialize(read_ptr, + data_size - (read_ptr - data)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Deserialized attribute %s\n", + le->claim->name); + GNUNET_CONTAINER_DLL_insert(attrs->list_head, attrs->list_tail, le); + attr_len = GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size(le->claim); + read_ptr += attr_len; + } return attrs; } @@ -372,28 +372,28 @@ GNUNET_RECLAIM_ATTRIBUTE_list_deserialize (const char *data, size_t data_size) * @return copied claim list */ struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList * -GNUNET_RECLAIM_ATTRIBUTE_list_dup ( - const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs) +GNUNET_RECLAIM_ATTRIBUTE_list_dup( + const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs) { struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le; struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *result_le; struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *result; - result = GNUNET_new (struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList); + result = GNUNET_new(struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList); for (le = attrs->list_head; NULL != le; le = le->next) - { - result_le = GNUNET_new (struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry); - result_le->claim = - GNUNET_RECLAIM_ATTRIBUTE_claim_new (le->claim->name, - le->claim->type, - le->claim->data, - le->claim->data_size); - result_le->claim->version = le->claim->version; - result_le->claim->id = le->claim->id; - GNUNET_CONTAINER_DLL_insert (result->list_head, - result->list_tail, - result_le); - } + { + result_le = GNUNET_new(struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry); + result_le->claim = + GNUNET_RECLAIM_ATTRIBUTE_claim_new(le->claim->name, + le->claim->type, + le->claim->data, + le->claim->data_size); + result_le->claim->version = le->claim->version; + result_le->claim->id = le->claim->id; + GNUNET_CONTAINER_DLL_insert(result->list_head, + result->list_tail, + result_le); + } return result; } @@ -404,20 +404,20 @@ GNUNET_RECLAIM_ATTRIBUTE_list_dup ( * @param attrs list to destroy */ void -GNUNET_RECLAIM_ATTRIBUTE_list_destroy ( - struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs) +GNUNET_RECLAIM_ATTRIBUTE_list_destroy( + struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs) { struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le; struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *tmp_le; for (le = attrs->list_head; NULL != le;) - { - GNUNET_free (le->claim); - tmp_le = le; - le = le->next; - GNUNET_free (tmp_le); - } - GNUNET_free (attrs); + { + GNUNET_free(le->claim); + tmp_le = le; + le = le->next; + GNUNET_free(tmp_le); + } + GNUNET_free(attrs); } @@ -428,10 +428,10 @@ GNUNET_RECLAIM_ATTRIBUTE_list_destroy ( * @return the required buffer size */ size_t -GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size ( - const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) +GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size( + const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) { - return sizeof (struct Attribute) + strlen (attr->name) + attr->data_size; + return sizeof(struct Attribute) + strlen(attr->name) + attr->data_size; } @@ -443,32 +443,32 @@ GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size ( * @return length of serialized data */ size_t -GNUNET_RECLAIM_ATTRIBUTE_serialize ( - const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr, - char *result) +GNUNET_RECLAIM_ATTRIBUTE_serialize( + const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr, + char *result) { size_t data_len_ser; size_t name_len; struct Attribute *attr_ser; char *write_ptr; - attr_ser = (struct Attribute *) result; - attr_ser->attribute_type = htons (attr->type); - attr_ser->attribute_version = htonl (attr->version); - attr_ser->attribute_id = GNUNET_htonll (attr->id); - name_len = strlen (attr->name); - attr_ser->name_len = htons (name_len); - write_ptr = (char *) &attr_ser[1]; - GNUNET_memcpy (write_ptr, attr->name, name_len); + attr_ser = (struct Attribute *)result; + attr_ser->attribute_type = htons(attr->type); + attr_ser->attribute_version = htonl(attr->version); + attr_ser->attribute_id = GNUNET_htonll(attr->id); + name_len = strlen(attr->name); + attr_ser->name_len = htons(name_len); + write_ptr = (char *)&attr_ser[1]; + GNUNET_memcpy(write_ptr, attr->name, name_len); write_ptr += name_len; // TODO plugin-ize // data_len_ser = plugin->serialize_attribute_value (attr, // &attr_ser[1]); data_len_ser = attr->data_size; - GNUNET_memcpy (write_ptr, attr->data, attr->data_size); - attr_ser->data_size = htons (data_len_ser); + GNUNET_memcpy(write_ptr, attr->data, attr->data_size); + attr_ser->data_size = htons(data_len_ser); - return sizeof (struct Attribute) + strlen (attr->name) + attr->data_size; + return sizeof(struct Attribute) + strlen(attr->name) + attr->data_size; } @@ -481,7 +481,7 @@ GNUNET_RECLAIM_ATTRIBUTE_serialize ( * @return a GNUNET_IDENTITY_PROVIDER_Attribute, must be free'd by caller */ struct GNUNET_RECLAIM_ATTRIBUTE_Claim * -GNUNET_RECLAIM_ATTRIBUTE_deserialize (const char *data, size_t data_size) +GNUNET_RECLAIM_ATTRIBUTE_deserialize(const char *data, size_t data_size) { struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr; struct Attribute *attr_ser; @@ -489,32 +489,32 @@ GNUNET_RECLAIM_ATTRIBUTE_deserialize (const char *data, size_t data_size) size_t name_len; char *write_ptr; - if (data_size < sizeof (struct Attribute)) + if (data_size < sizeof(struct Attribute)) return NULL; - attr_ser = (struct Attribute *) data; - data_len = ntohs (attr_ser->data_size); - name_len = ntohs (attr_ser->name_len); - if (data_size < sizeof (struct Attribute) + data_len + name_len) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Buffer too small to deserialize\n"); - return NULL; - } - attr = GNUNET_malloc (sizeof (struct GNUNET_RECLAIM_ATTRIBUTE_Claim) + - data_len + name_len + 1); - attr->type = ntohs (attr_ser->attribute_type); - attr->version = ntohl (attr_ser->attribute_version); - attr->id = GNUNET_ntohll (attr_ser->attribute_id); + attr_ser = (struct Attribute *)data; + data_len = ntohs(attr_ser->data_size); + name_len = ntohs(attr_ser->name_len); + if (data_size < sizeof(struct Attribute) + data_len + name_len) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Buffer too small to deserialize\n"); + return NULL; + } + attr = GNUNET_malloc(sizeof(struct GNUNET_RECLAIM_ATTRIBUTE_Claim) + + data_len + name_len + 1); + attr->type = ntohs(attr_ser->attribute_type); + attr->version = ntohl(attr_ser->attribute_version); + attr->id = GNUNET_ntohll(attr_ser->attribute_id); attr->data_size = data_len; - write_ptr = (char *) &attr[1]; - GNUNET_memcpy (write_ptr, &attr_ser[1], name_len); + write_ptr = (char *)&attr[1]; + GNUNET_memcpy(write_ptr, &attr_ser[1], name_len); write_ptr[name_len] = '\0'; attr->name = write_ptr; write_ptr += name_len + 1; - GNUNET_memcpy (write_ptr, (char *) &attr_ser[1] + name_len, attr->data_size); + GNUNET_memcpy(write_ptr, (char *)&attr_ser[1] + name_len, attr->data_size); attr->data = write_ptr; return attr; } diff --git a/src/reclaim-attribute/reclaim_attribute.h b/src/reclaim-attribute/reclaim_attribute.h index b6de147a2..5e87e6e16 100644 --- a/src/reclaim-attribute/reclaim_attribute.h +++ b/src/reclaim-attribute/reclaim_attribute.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach * @file reclaim-attribute/reclaim_attribute.h @@ -31,8 +31,7 @@ /** * Serialized claim */ -struct Attribute -{ +struct Attribute { /** * Attribute type */ diff --git a/src/reclaim/gnunet-reclaim.c b/src/reclaim/gnunet-reclaim.c index b2f6b4c3c..5160aef7f 100644 --- a/src/reclaim/gnunet-reclaim.c +++ b/src/reclaim/gnunet-reclaim.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach * @file src/reclaim/gnunet-reclaim.c @@ -168,175 +168,176 @@ static char *attr_delete; static struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr_to_delete; static void -do_cleanup (void *cls) +do_cleanup(void *cls) { cleanup_task = NULL; if (NULL != timeout) - GNUNET_SCHEDULER_cancel (timeout); + GNUNET_SCHEDULER_cancel(timeout); if (NULL != reclaim_op) - GNUNET_RECLAIM_cancel (reclaim_op); + GNUNET_RECLAIM_cancel(reclaim_op); if (NULL != attr_iterator) - GNUNET_RECLAIM_get_attributes_stop (attr_iterator); + GNUNET_RECLAIM_get_attributes_stop(attr_iterator); if (NULL != ticket_iterator) - GNUNET_RECLAIM_ticket_iteration_stop (ticket_iterator); + GNUNET_RECLAIM_ticket_iteration_stop(ticket_iterator); if (NULL != reclaim_handle) - GNUNET_RECLAIM_disconnect (reclaim_handle); + GNUNET_RECLAIM_disconnect(reclaim_handle); if (NULL != identity_handle) - GNUNET_IDENTITY_disconnect (identity_handle); + GNUNET_IDENTITY_disconnect(identity_handle); if (NULL != abe_key) - GNUNET_free (abe_key); + GNUNET_free(abe_key); if (NULL != attr_list) - GNUNET_free (attr_list); + GNUNET_free(attr_list); if (NULL != attr_to_delete) - GNUNET_free (attr_to_delete); + GNUNET_free(attr_to_delete); } static void -ticket_issue_cb (void *cls, const struct GNUNET_RECLAIM_Ticket *ticket) +ticket_issue_cb(void *cls, const struct GNUNET_RECLAIM_Ticket *ticket) { char *ticket_str; + reclaim_op = NULL; if (NULL != ticket) - { - ticket_str = - GNUNET_STRINGS_data_to_string_alloc (ticket, - sizeof ( - struct GNUNET_RECLAIM_Ticket)); - printf ("%s\n", ticket_str); - GNUNET_free (ticket_str); - } - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); + { + ticket_str = + GNUNET_STRINGS_data_to_string_alloc(ticket, + sizeof( + struct GNUNET_RECLAIM_Ticket)); + printf("%s\n", ticket_str); + GNUNET_free(ticket_str); + } + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); } static void -store_attr_cont (void *cls, int32_t success, const char *emsg) +store_attr_cont(void *cls, int32_t success, const char *emsg) { reclaim_op = NULL; if (GNUNET_SYSERR == success) - { - fprintf (stderr, "%s\n", emsg); - } - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); + { + fprintf(stderr, "%s\n", emsg); + } + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); } static void -process_attrs (void *cls, - const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, - const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) +process_attrs(void *cls, + const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, + const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) { char *value_str; char *id; const char *attr_type; if (NULL == identity) - { - reclaim_op = NULL; - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); - return; - } + { + reclaim_op = NULL; + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); + return; + } if (NULL == attr) - { - ret = 1; - return; - } - value_str = GNUNET_RECLAIM_ATTRIBUTE_value_to_string (attr->type, - attr->data, - attr->data_size); - attr_type = GNUNET_RECLAIM_ATTRIBUTE_number_to_typename (attr->type); - id = GNUNET_STRINGS_data_to_string_alloc (&attr->id, sizeof (uint64_t)); - fprintf (stdout, - "Name: %s; Value: %s (%s); Version %u; ID: %s\n", - attr->name, - value_str, - attr_type, - attr->version, - id); - GNUNET_free (id); + { + ret = 1; + return; + } + value_str = GNUNET_RECLAIM_ATTRIBUTE_value_to_string(attr->type, + attr->data, + attr->data_size); + attr_type = GNUNET_RECLAIM_ATTRIBUTE_number_to_typename(attr->type); + id = GNUNET_STRINGS_data_to_string_alloc(&attr->id, sizeof(uint64_t)); + fprintf(stdout, + "Name: %s; Value: %s (%s); Version %u; ID: %s\n", + attr->name, + value_str, + attr_type, + attr->version, + id); + GNUNET_free(id); } static void -ticket_iter_err (void *cls) +ticket_iter_err(void *cls) { ticket_iterator = NULL; - fprintf (stderr, "Failed to iterate over tickets\n"); - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); + fprintf(stderr, "Failed to iterate over tickets\n"); + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); } static void -ticket_iter_fin (void *cls) +ticket_iter_fin(void *cls) { ticket_iterator = NULL; - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); } static void -ticket_iter (void *cls, const struct GNUNET_RECLAIM_Ticket *ticket) +ticket_iter(void *cls, const struct GNUNET_RECLAIM_Ticket *ticket) { char *aud; char *ref; char *tkt; aud = - GNUNET_STRINGS_data_to_string_alloc (&ticket->audience, - sizeof (struct - GNUNET_CRYPTO_EcdsaPublicKey)); - ref = GNUNET_STRINGS_data_to_string_alloc (&ticket->rnd, sizeof (uint64_t)); + GNUNET_STRINGS_data_to_string_alloc(&ticket->audience, + sizeof(struct + GNUNET_CRYPTO_EcdsaPublicKey)); + ref = GNUNET_STRINGS_data_to_string_alloc(&ticket->rnd, sizeof(uint64_t)); tkt = - GNUNET_STRINGS_data_to_string_alloc (ticket, - sizeof (struct GNUNET_RECLAIM_Ticket)); - fprintf (stdout, "Ticket: %s | ID: %s | Audience: %s\n", tkt, ref, aud); - GNUNET_free (aud); - GNUNET_free (ref); - GNUNET_free (tkt); - GNUNET_RECLAIM_ticket_iteration_next (ticket_iterator); + GNUNET_STRINGS_data_to_string_alloc(ticket, + sizeof(struct GNUNET_RECLAIM_Ticket)); + fprintf(stdout, "Ticket: %s | ID: %s | Audience: %s\n", tkt, ref, aud); + GNUNET_free(aud); + GNUNET_free(ref); + GNUNET_free(tkt); + GNUNET_RECLAIM_ticket_iteration_next(ticket_iterator); } static void -iter_error (void *cls) +iter_error(void *cls) { attr_iterator = NULL; - fprintf (stderr, "Failed to iterate over attributes\n"); - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); + fprintf(stderr, "Failed to iterate over attributes\n"); + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); } static void -timeout_task (void *cls) +timeout_task(void *cls) { timeout = NULL; ret = 1; - fprintf (stderr, "Timeout\n"); + fprintf(stderr, "Timeout\n"); if (NULL == cleanup_task) - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); } static void -process_rvk (void *cls, int success, const char *msg) +process_rvk(void *cls, int success, const char *msg) { reclaim_op = NULL; if (GNUNET_OK != success) - { - fprintf (stderr, "Revocation failed.\n"); - ret = 1; - } - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); + { + fprintf(stderr, "Revocation failed.\n"); + ret = 1; + } + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); } static void -process_delete (void *cls, int success, const char *msg) +process_delete(void *cls, int success, const char *msg) { reclaim_op = NULL; if (GNUNET_OK != success) - { - fprintf (stderr, "Deletion failed.\n"); - ret = 1; - } - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); + { + fprintf(stderr, "Deletion failed.\n"); + ret = 1; + } + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); } static void -iter_finished (void *cls) +iter_finished(void *cls) { char *data; size_t data_size; @@ -344,97 +345,97 @@ iter_finished (void *cls) attr_iterator = NULL; if (list) - { - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); - return; - } + { + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); + return; + } if (issue_attrs) - { - reclaim_op = GNUNET_RECLAIM_ticket_issue (reclaim_handle, - pkey, - &rp_key, - attr_list, - &ticket_issue_cb, - NULL); - return; - } + { + reclaim_op = GNUNET_RECLAIM_ticket_issue(reclaim_handle, + pkey, + &rp_key, + attr_list, + &ticket_issue_cb, + NULL); + return; + } if (consume_ticket) - { - reclaim_op = GNUNET_RECLAIM_ticket_consume (reclaim_handle, + { + reclaim_op = GNUNET_RECLAIM_ticket_consume(reclaim_handle, + pkey, + &ticket, + &process_attrs, + NULL); + timeout = GNUNET_SCHEDULER_add_delayed( + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 10), + &timeout_task, + NULL); + return; + } + if (revoke_ticket) + { + reclaim_op = GNUNET_RECLAIM_ticket_revoke(reclaim_handle, pkey, &ticket, - &process_attrs, + &process_rvk, NULL); - timeout = GNUNET_SCHEDULER_add_delayed ( - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10), - &timeout_task, - NULL); - return; - } - if (revoke_ticket) - { - reclaim_op = GNUNET_RECLAIM_ticket_revoke (reclaim_handle, - pkey, - &ticket, - &process_rvk, - NULL); - return; - } + return; + } if (attr_delete) - { - if (NULL == attr_to_delete) { - fprintf (stdout, "No such attribute ``%s''\n", attr_delete); + if (NULL == attr_to_delete) + { + fprintf(stdout, "No such attribute ``%s''\n", attr_delete); + return; + } + reclaim_op = GNUNET_RECLAIM_attribute_delete(reclaim_handle, + pkey, + attr_to_delete, + &process_delete, + NULL); return; } - reclaim_op = GNUNET_RECLAIM_attribute_delete (reclaim_handle, - pkey, - attr_to_delete, - &process_delete, - NULL); - return; - } if (attr_name) - { - if (NULL == type_str) - type = GNUNET_RECLAIM_ATTRIBUTE_TYPE_STRING; - else - type = GNUNET_RECLAIM_ATTRIBUTE_typename_to_number (type_str); - - GNUNET_assert (GNUNET_SYSERR != - GNUNET_RECLAIM_ATTRIBUTE_string_to_value (type, + { + if (NULL == type_str) + type = GNUNET_RECLAIM_ATTRIBUTE_TYPE_STRING; + else + type = GNUNET_RECLAIM_ATTRIBUTE_typename_to_number(type_str); + + GNUNET_assert(GNUNET_SYSERR != + GNUNET_RECLAIM_ATTRIBUTE_string_to_value(type, attr_value, - (void **) &data, + (void **)&data, &data_size)); - if (NULL != claim) - { - claim->type = type; - claim->data = data; - claim->data_size = data_size; - } - else - { - claim = - GNUNET_RECLAIM_ATTRIBUTE_claim_new (attr_name, type, data, data_size); + if (NULL != claim) + { + claim->type = type; + claim->data = data; + claim->data_size = data_size; + } + else + { + claim = + GNUNET_RECLAIM_ATTRIBUTE_claim_new(attr_name, type, data, data_size); + } + reclaim_op = GNUNET_RECLAIM_attribute_store(reclaim_handle, + pkey, + claim, + &exp_interval, + &store_attr_cont, + NULL); + GNUNET_free(data); + GNUNET_free(claim); + return; } - reclaim_op = GNUNET_RECLAIM_attribute_store (reclaim_handle, - pkey, - claim, - &exp_interval, - &store_attr_cont, - NULL); - GNUNET_free (data); - GNUNET_free (claim); - return; - } - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); } static void -iter_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, - const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) +iter_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, + const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) { struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le; char *attrs_tmp; @@ -444,260 +445,260 @@ iter_cb (void *cls, const char *attr_type; if ((NULL != attr_name) && (NULL != claim)) - { - if (0 == strcasecmp (attr_name, attr->name)) { - claim = GNUNET_RECLAIM_ATTRIBUTE_claim_new (attr->name, - attr->type, - attr->data, - attr->data_size); + if (0 == strcasecmp(attr_name, attr->name)) + { + claim = GNUNET_RECLAIM_ATTRIBUTE_claim_new(attr->name, + attr->type, + attr->data, + attr->data_size); + } } - } else if (issue_attrs) - { - attrs_tmp = GNUNET_strdup (issue_attrs); - attr_str = strtok (attrs_tmp, ","); - while (NULL != attr_str) { - if (0 != strcasecmp (attr_str, attr->name)) - { - attr_str = strtok (NULL, ","); - continue; - } - le = GNUNET_new (struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry); - le->claim = GNUNET_RECLAIM_ATTRIBUTE_claim_new (attr->name, - attr->type, - attr->data, - attr->data_size); - le->claim->version = attr->version; - le->claim->id = attr->id; - GNUNET_CONTAINER_DLL_insert (attr_list->list_head, - attr_list->list_tail, - le); - break; + attrs_tmp = GNUNET_strdup(issue_attrs); + attr_str = strtok(attrs_tmp, ","); + while (NULL != attr_str) + { + if (0 != strcasecmp(attr_str, attr->name)) + { + attr_str = strtok(NULL, ","); + continue; + } + le = GNUNET_new(struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry); + le->claim = GNUNET_RECLAIM_ATTRIBUTE_claim_new(attr->name, + attr->type, + attr->data, + attr->data_size); + le->claim->version = attr->version; + le->claim->id = attr->id; + GNUNET_CONTAINER_DLL_insert(attr_list->list_head, + attr_list->list_tail, + le); + break; + } + GNUNET_free(attrs_tmp); } - GNUNET_free (attrs_tmp); - } else if (attr_delete && (NULL == attr_to_delete)) - { - label = GNUNET_STRINGS_data_to_string_alloc (&attr->id, sizeof (uint64_t)); - if (0 == strcasecmp (attr_delete, label)) { - attr_to_delete = GNUNET_RECLAIM_ATTRIBUTE_claim_new (attr->name, - attr->type, - attr->data, - attr->data_size); - attr_to_delete->id = attr->id; + label = GNUNET_STRINGS_data_to_string_alloc(&attr->id, sizeof(uint64_t)); + if (0 == strcasecmp(attr_delete, label)) + { + attr_to_delete = GNUNET_RECLAIM_ATTRIBUTE_claim_new(attr->name, + attr->type, + attr->data, + attr->data_size); + attr_to_delete->id = attr->id; + } + GNUNET_free(label); } - GNUNET_free (label); - } else if (list) - { - attr_str = GNUNET_RECLAIM_ATTRIBUTE_value_to_string (attr->type, - attr->data, - attr->data_size); - attr_type = GNUNET_RECLAIM_ATTRIBUTE_number_to_typename (attr->type); - id = GNUNET_STRINGS_data_to_string_alloc (&attr->id, sizeof (uint64_t)); - fprintf (stdout, - "Name: %s; Value: %s (%s); Version %u; ID: %s\n", - attr->name, - attr_str, - attr_type, - attr->version, - id); - GNUNET_free (id); - } - GNUNET_RECLAIM_get_attributes_next (attr_iterator); + { + attr_str = GNUNET_RECLAIM_ATTRIBUTE_value_to_string(attr->type, + attr->data, + attr->data_size); + attr_type = GNUNET_RECLAIM_ATTRIBUTE_number_to_typename(attr->type); + id = GNUNET_STRINGS_data_to_string_alloc(&attr->id, sizeof(uint64_t)); + fprintf(stdout, + "Name: %s; Value: %s (%s); Version %u; ID: %s\n", + attr->name, + attr_str, + attr_type, + attr->version, + id); + GNUNET_free(id); + } + GNUNET_RECLAIM_get_attributes_next(attr_iterator); } static void -start_process () +start_process() { if (NULL == pkey) - { - fprintf (stderr, "Ego %s not found\n", ego_name); - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); - return; - } + { + fprintf(stderr, "Ego %s not found\n", ego_name); + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); + return; + } if (list_tickets) - { - ticket_iterator = GNUNET_RECLAIM_ticket_iteration_start (reclaim_handle, - pkey, - &ticket_iter_err, - NULL, - &ticket_iter, - NULL, - &ticket_iter_fin, - NULL); - return; - } + { + ticket_iterator = GNUNET_RECLAIM_ticket_iteration_start(reclaim_handle, + pkey, + &ticket_iter_err, + NULL, + &ticket_iter, + NULL, + &ticket_iter_fin, + NULL); + return; + } if ((NULL != rp) && GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (rp, strlen (rp), &rp_key)) - { - fprintf (stderr, "%s is not a public key!\n", rp); - cleanup_task = GNUNET_SCHEDULER_add_now (&do_cleanup, NULL); - return; - } + GNUNET_CRYPTO_ecdsa_public_key_from_string(rp, strlen(rp), &rp_key)) + { + fprintf(stderr, "%s is not a public key!\n", rp); + cleanup_task = GNUNET_SCHEDULER_add_now(&do_cleanup, NULL); + return; + } if (NULL != consume_ticket) - GNUNET_STRINGS_string_to_data (consume_ticket, - strlen (consume_ticket), - &ticket, - sizeof (struct GNUNET_RECLAIM_Ticket)); + GNUNET_STRINGS_string_to_data(consume_ticket, + strlen(consume_ticket), + &ticket, + sizeof(struct GNUNET_RECLAIM_Ticket)); if (NULL != revoke_ticket) - GNUNET_STRINGS_string_to_data (revoke_ticket, - strlen (revoke_ticket), - &ticket, - sizeof (struct GNUNET_RECLAIM_Ticket)); + GNUNET_STRINGS_string_to_data(revoke_ticket, + strlen(revoke_ticket), + &ticket, + sizeof(struct GNUNET_RECLAIM_Ticket)); - attr_list = GNUNET_new (struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList); + attr_list = GNUNET_new(struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList); claim = NULL; - attr_iterator = GNUNET_RECLAIM_get_attributes_start (reclaim_handle, - pkey, - &iter_error, - NULL, - &iter_cb, - NULL, - &iter_finished, - NULL); + attr_iterator = GNUNET_RECLAIM_get_attributes_start(reclaim_handle, + pkey, + &iter_error, + NULL, + &iter_cb, + NULL, + &iter_finished, + NULL); } static int init = GNUNET_YES; static void -ego_cb (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *name) +ego_cb(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *name) { if (NULL == name) - { - if (GNUNET_YES == init) { - init = GNUNET_NO; - start_process (); + if (GNUNET_YES == init) + { + init = GNUNET_NO; + start_process(); + } + return; } + if (0 != strcmp(name, ego_name)) return; - } - if (0 != strcmp (name, ego_name)) - return; - pkey = GNUNET_IDENTITY_ego_get_private_key (ego); + pkey = GNUNET_IDENTITY_ego_get_private_key(ego); } static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { ret = 0; if (NULL == ego_name) - { - ret = 1; - fprintf (stderr, _ ("Ego is required\n")); - return; - } + { + ret = 1; + fprintf(stderr, _("Ego is required\n")); + return; + } if ((NULL == attr_value) && (NULL != attr_name)) - { - ret = 1; - fprintf (stderr, _ ("Attribute value missing!\n")); - return; - } + { + ret = 1; + fprintf(stderr, _("Attribute value missing!\n")); + return; + } if ((NULL == rp) && (NULL != issue_attrs)) - { - ret = 1; - fprintf (stderr, _ ("Requesting party key is required!\n")); - return; - } + { + ret = 1; + fprintf(stderr, _("Requesting party key is required!\n")); + return; + } - reclaim_handle = GNUNET_RECLAIM_connect (c); + reclaim_handle = GNUNET_RECLAIM_connect(c); // Get Ego - identity_handle = GNUNET_IDENTITY_connect (c, &ego_cb, NULL); + identity_handle = GNUNET_IDENTITY_connect(c, &ego_cb, NULL); } int -main (int argc, char *const argv[]) +main(int argc, char *const argv[]) { exp_interval = GNUNET_TIME_UNIT_HOURS; struct GNUNET_GETOPT_CommandLineOption options[] = { - - GNUNET_GETOPT_option_string ('a', - "add", - "NAME", - gettext_noop ("Add an attribute NAME"), - &attr_name), - GNUNET_GETOPT_option_string ('d', - "delete", - "ID", - gettext_noop ("Delete the attribute with ID"), - &attr_delete), - GNUNET_GETOPT_option_string ('V', - "value", - "VALUE", - gettext_noop ("The attribute VALUE"), - &attr_value), - GNUNET_GETOPT_option_string ('e', - "ego", - "EGO", - gettext_noop ("The EGO to use"), - &ego_name), - GNUNET_GETOPT_option_string ('r', - "rp", - "RP", - gettext_noop ( - "Specify the relying party for issue"), - &rp), - GNUNET_GETOPT_option_flag ('D', - "dump", - gettext_noop ("List attributes for EGO"), - &list), - GNUNET_GETOPT_option_string ( + GNUNET_GETOPT_option_string('a', + "add", + "NAME", + gettext_noop("Add an attribute NAME"), + &attr_name), + GNUNET_GETOPT_option_string('d', + "delete", + "ID", + gettext_noop("Delete the attribute with ID"), + &attr_delete), + GNUNET_GETOPT_option_string('V', + "value", + "VALUE", + gettext_noop("The attribute VALUE"), + &attr_value), + GNUNET_GETOPT_option_string('e', + "ego", + "EGO", + gettext_noop("The EGO to use"), + &ego_name), + GNUNET_GETOPT_option_string('r', + "rp", + "RP", + gettext_noop( + "Specify the relying party for issue"), + &rp), + GNUNET_GETOPT_option_flag('D', + "dump", + gettext_noop("List attributes for EGO"), + &list), + GNUNET_GETOPT_option_string( 'i', "issue", "A1,A2,...", - gettext_noop ( + gettext_noop( "Issue a ticket for a set of attributes separated by comma"), &issue_attrs), - GNUNET_GETOPT_option_string ('C', - "consume", - "TICKET", - gettext_noop ("Consume a ticket"), - &consume_ticket), - GNUNET_GETOPT_option_string ('R', - "revoke", - "TICKET", - gettext_noop ("Revoke a ticket"), - &revoke_ticket), - GNUNET_GETOPT_option_string ('t', - "type", - "TYPE", - gettext_noop ("Type of attribute"), - &type_str), - GNUNET_GETOPT_option_flag ('T', - "tickets", - gettext_noop ("List tickets of ego"), - &list_tickets), - GNUNET_GETOPT_option_relative_time ('E', - "expiration", - "INTERVAL", - gettext_noop ( - "Expiration interval of the attribute"), - &exp_interval), - - GNUNET_GETOPT_OPTION_END}; - if (GNUNET_OK != GNUNET_PROGRAM_run (argc, - argv, - "gnunet-reclaim", - _ ("re:claimID command line tool"), - options, - &run, - NULL)) + GNUNET_GETOPT_option_string('C', + "consume", + "TICKET", + gettext_noop("Consume a ticket"), + &consume_ticket), + GNUNET_GETOPT_option_string('R', + "revoke", + "TICKET", + gettext_noop("Revoke a ticket"), + &revoke_ticket), + GNUNET_GETOPT_option_string('t', + "type", + "TYPE", + gettext_noop("Type of attribute"), + &type_str), + GNUNET_GETOPT_option_flag('T', + "tickets", + gettext_noop("List tickets of ego"), + &list_tickets), + GNUNET_GETOPT_option_relative_time('E', + "expiration", + "INTERVAL", + gettext_noop( + "Expiration interval of the attribute"), + &exp_interval), + + GNUNET_GETOPT_OPTION_END + }; + if (GNUNET_OK != GNUNET_PROGRAM_run(argc, + argv, + "gnunet-reclaim", + _("re:claimID command line tool"), + options, + &run, + NULL)) return 1; else return ret; diff --git a/src/reclaim/gnunet-service-reclaim.c b/src/reclaim/gnunet-service-reclaim.c index 57bff8ed4..23a5db1ed 100644 --- a/src/reclaim/gnunet-service-reclaim.c +++ b/src/reclaim/gnunet-service-reclaim.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach * @file src/reclaim/gnunet-service-reclaim.c @@ -58,8 +58,7 @@ struct IdpClient; /** * A ticket iteration operation. */ -struct TicketIteration -{ +struct TicketIteration { /** * DLL */ @@ -90,8 +89,7 @@ struct TicketIteration /** * An attribute iteration operation. */ -struct AttributeIterator -{ +struct AttributeIterator { /** * Next element in the DLL */ @@ -127,8 +125,7 @@ struct AttributeIterator /** * An idp client */ -struct IdpClient -{ +struct IdpClient { /** * DLL */ @@ -227,8 +224,7 @@ struct IdpClient /** * Handle for attribute deletion request */ -struct AttributeDeleteHandle -{ +struct AttributeDeleteHandle { /** * DLL */ @@ -290,8 +286,7 @@ struct AttributeDeleteHandle /** * Handle for attribute store request */ -struct AttributeStoreHandle -{ +struct AttributeStoreHandle { /** * DLL */ @@ -342,8 +337,7 @@ struct AttributeStoreHandle /** * Handle for ticket consume request */ -struct ConsumeTicketOperation -{ +struct ConsumeTicketOperation { /** * DLL */ @@ -374,8 +368,7 @@ struct ConsumeTicketOperation /** * Ticket revocation request handle */ -struct TicketRevocationOperation -{ +struct TicketRevocationOperation { /** * DLL */ @@ -406,8 +399,7 @@ struct TicketRevocationOperation /** * Ticket issue operation handle */ -struct TicketIssueOperation -{ +struct TicketIssueOperation { /** * DLL */ @@ -447,28 +439,30 @@ static struct IdpClient *client_list_tail = NULL; * @param adh the attribute to cleanup */ static void -cleanup_adh (struct AttributeDeleteHandle *adh) +cleanup_adh(struct AttributeDeleteHandle *adh) { struct TicketRecordsEntry *le; + if (NULL != adh->ns_it) - GNUNET_NAMESTORE_zone_iteration_stop (adh->ns_it); + GNUNET_NAMESTORE_zone_iteration_stop(adh->ns_it); if (NULL != adh->ns_qe) - GNUNET_NAMESTORE_cancel (adh->ns_qe); + GNUNET_NAMESTORE_cancel(adh->ns_qe); if (NULL != adh->label) - GNUNET_free (adh->label); + GNUNET_free(adh->label); if (NULL != adh->claim) - GNUNET_free (adh->claim); - while (NULL != (le = adh->tickets_to_update_head)) { - GNUNET_CONTAINER_DLL_remove (adh->tickets_to_update_head, - adh->tickets_to_update_tail, - le); - if (NULL != le->label) - GNUNET_free (le->label); - if (NULL != le->data) - GNUNET_free (le->data); - GNUNET_free (le); - } - GNUNET_free (adh); + GNUNET_free(adh->claim); + while (NULL != (le = adh->tickets_to_update_head)) + { + GNUNET_CONTAINER_DLL_remove(adh->tickets_to_update_head, + adh->tickets_to_update_tail, + le); + if (NULL != le->label) + GNUNET_free(le->label); + if (NULL != le->data) + GNUNET_free(le->data); + GNUNET_free(le); + } + GNUNET_free(adh); } @@ -478,13 +472,13 @@ cleanup_adh (struct AttributeDeleteHandle *adh) * @param handle handle to clean up */ static void -cleanup_as_handle (struct AttributeStoreHandle *ash) +cleanup_as_handle(struct AttributeStoreHandle *ash) { if (NULL != ash->ns_qe) - GNUNET_NAMESTORE_cancel (ash->ns_qe); + GNUNET_NAMESTORE_cancel(ash->ns_qe); if (NULL != ash->claim) - GNUNET_free (ash->claim); - GNUNET_free (ash); + GNUNET_free(ash->claim); + GNUNET_free(ash); } @@ -494,7 +488,7 @@ cleanup_as_handle (struct AttributeStoreHandle *ash) * @param idp the client to clean up */ static void -cleanup_client (struct IdpClient *idp) +cleanup_client(struct IdpClient *idp) { struct AttributeIterator *ai; struct TicketIteration *ti; @@ -504,46 +498,53 @@ cleanup_client (struct IdpClient *idp) struct AttributeStoreHandle *as; struct AttributeDeleteHandle *adh; - while (NULL != (iss = idp->issue_op_head)) { - GNUNET_CONTAINER_DLL_remove (idp->issue_op_head, idp->issue_op_tail, iss); - GNUNET_free (iss); - } - while (NULL != (ct = idp->consume_op_head)) { - GNUNET_CONTAINER_DLL_remove (idp->consume_op_head, - idp->consume_op_tail, - ct); - if (NULL != ct->ch) - RECLAIM_TICKETS_consume_cancel (ct->ch); - GNUNET_free (ct); - } - while (NULL != (as = idp->store_op_head)) { - GNUNET_CONTAINER_DLL_remove (idp->store_op_head, idp->store_op_tail, as); - cleanup_as_handle (as); - } - while (NULL != (adh = idp->delete_op_head)) { - GNUNET_CONTAINER_DLL_remove (idp->delete_op_head, idp->delete_op_tail, adh); - cleanup_adh (adh); - } - - while (NULL != (ai = idp->attr_iter_head)) { - GNUNET_CONTAINER_DLL_remove (idp->attr_iter_head, idp->attr_iter_tail, ai); - GNUNET_free (ai); - } - while (NULL != (rop = idp->revoke_op_head)) { - GNUNET_CONTAINER_DLL_remove (idp->revoke_op_head, idp->revoke_op_tail, rop); - if (NULL != rop->rh) - RECLAIM_TICKETS_revoke_cancel (rop->rh); - GNUNET_free (rop); - } - while (NULL != (ti = idp->ticket_iter_head)) { - GNUNET_CONTAINER_DLL_remove (idp->ticket_iter_head, - idp->ticket_iter_tail, - ti); - if (NULL != ti->iter) - RECLAIM_TICKETS_iteration_stop (ti->iter); - GNUNET_free (ti); - } - GNUNET_free (idp); + while (NULL != (iss = idp->issue_op_head)) + { + GNUNET_CONTAINER_DLL_remove(idp->issue_op_head, idp->issue_op_tail, iss); + GNUNET_free(iss); + } + while (NULL != (ct = idp->consume_op_head)) + { + GNUNET_CONTAINER_DLL_remove(idp->consume_op_head, + idp->consume_op_tail, + ct); + if (NULL != ct->ch) + RECLAIM_TICKETS_consume_cancel(ct->ch); + GNUNET_free(ct); + } + while (NULL != (as = idp->store_op_head)) + { + GNUNET_CONTAINER_DLL_remove(idp->store_op_head, idp->store_op_tail, as); + cleanup_as_handle(as); + } + while (NULL != (adh = idp->delete_op_head)) + { + GNUNET_CONTAINER_DLL_remove(idp->delete_op_head, idp->delete_op_tail, adh); + cleanup_adh(adh); + } + + while (NULL != (ai = idp->attr_iter_head)) + { + GNUNET_CONTAINER_DLL_remove(idp->attr_iter_head, idp->attr_iter_tail, ai); + GNUNET_free(ai); + } + while (NULL != (rop = idp->revoke_op_head)) + { + GNUNET_CONTAINER_DLL_remove(idp->revoke_op_head, idp->revoke_op_tail, rop); + if (NULL != rop->rh) + RECLAIM_TICKETS_revoke_cancel(rop->rh); + GNUNET_free(rop); + } + while (NULL != (ti = idp->ticket_iter_head)) + { + GNUNET_CONTAINER_DLL_remove(idp->ticket_iter_head, + idp->ticket_iter_tail, + ti); + if (NULL != ti->iter) + RECLAIM_TICKETS_iteration_stop(ti->iter); + GNUNET_free(ti); + } + GNUNET_free(idp); } @@ -551,23 +552,24 @@ cleanup_client (struct IdpClient *idp) * Cleanup task */ static void -cleanup () +cleanup() { struct IdpClient *cl; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); while (NULL != (cl = client_list_head)) - { - GNUNET_CONTAINER_DLL_remove (client_list_head, - client_list_tail, - cl); - cleanup_client (cl); - } - RECLAIM_TICKETS_deinit (); + { + GNUNET_CONTAINER_DLL_remove(client_list_head, + client_list_tail, + cl); + cleanup_client(cl); + } + RECLAIM_TICKETS_deinit(); if (NULL != timeout_task) - GNUNET_SCHEDULER_cancel (timeout_task); + GNUNET_SCHEDULER_cancel(timeout_task); if (NULL != nsh) - GNUNET_NAMESTORE_disconnect (nsh); + GNUNET_NAMESTORE_disconnect(nsh); } @@ -577,10 +579,10 @@ cleanup () * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Shutting down...\n"); - cleanup (); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Shutting down...\n"); + cleanup(); } @@ -593,23 +595,24 @@ do_shutdown (void *cls) * @param success the success status of the request */ static void -send_ticket_result (const struct IdpClient *client, - uint32_t r_id, - const struct GNUNET_RECLAIM_Ticket *ticket, - uint32_t success) +send_ticket_result(const struct IdpClient *client, + uint32_t r_id, + const struct GNUNET_RECLAIM_Ticket *ticket, + uint32_t success) { struct TicketResultMessage *irm; struct GNUNET_MQ_Envelope *env; - env = GNUNET_MQ_msg (irm, - GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_RESULT); - if (NULL != ticket) { - irm->ticket = *ticket; - } + env = GNUNET_MQ_msg(irm, + GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_RESULT); + if (NULL != ticket) + { + irm->ticket = *ticket; + } // TODO add success member - irm->id = htonl (r_id); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending TICKET_RESULT message\n"); - GNUNET_MQ_send (client->mq, env); + irm->id = htonl(r_id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending TICKET_RESULT message\n"); + GNUNET_MQ_send(client->mq, env); } @@ -622,26 +625,28 @@ send_ticket_result (const struct IdpClient *client, * @param emsg error message (NULL of success is GNUNET_OK) */ static void -issue_ticket_result_cb (void *cls, - struct GNUNET_RECLAIM_Ticket *ticket, - int32_t success, - const char *emsg) +issue_ticket_result_cb(void *cls, + struct GNUNET_RECLAIM_Ticket *ticket, + int32_t success, + const char *emsg) { struct TicketIssueOperation *tio = cls; - if (GNUNET_OK != success) { - send_ticket_result (tio->client, tio->r_id, NULL, GNUNET_SYSERR); - GNUNET_CONTAINER_DLL_remove (tio->client->issue_op_head, - tio->client->issue_op_tail, - tio); - GNUNET_free (tio); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error issuing ticket: %s\n", emsg); - return; - } - send_ticket_result (tio->client, tio->r_id, ticket, GNUNET_SYSERR); - GNUNET_CONTAINER_DLL_remove (tio->client->issue_op_head, - tio->client->issue_op_tail, - tio); - GNUNET_free (tio); + + if (GNUNET_OK != success) + { + send_ticket_result(tio->client, tio->r_id, NULL, GNUNET_SYSERR); + GNUNET_CONTAINER_DLL_remove(tio->client->issue_op_head, + tio->client->issue_op_tail, + tio); + GNUNET_free(tio); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error issuing ticket: %s\n", emsg); + return; + } + send_ticket_result(tio->client, tio->r_id, ticket, GNUNET_SYSERR); + GNUNET_CONTAINER_DLL_remove(tio->client->issue_op_head, + tio->client->issue_op_tail, + tio); + GNUNET_free(tio); } @@ -653,15 +658,16 @@ issue_ticket_result_cb (void *cls, * @return GNUNET_OK if message is ok */ static int -check_issue_ticket_message (void *cls, const struct IssueTicketMessage *im) +check_issue_ticket_message(void *cls, const struct IssueTicketMessage *im) { uint16_t size; - size = ntohs (im->header.size); - if (size <= sizeof (struct IssueTicketMessage)) { - GNUNET_break (0); - return GNUNET_SYSERR; - } + size = ntohs(im->header.size); + if (size <= sizeof(struct IssueTicketMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -673,34 +679,34 @@ check_issue_ticket_message (void *cls, const struct IssueTicketMessage *im) * @param im the message */ static void -handle_issue_ticket_message (void *cls, const struct IssueTicketMessage *im) +handle_issue_ticket_message(void *cls, const struct IssueTicketMessage *im) { struct TicketIssueOperation *tio; struct IdpClient *idp = cls; struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs; size_t attrs_len; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received ISSUE_TICKET message\n"); - tio = GNUNET_new (struct TicketIssueOperation); - attrs_len = ntohs (im->attr_len); - attrs = GNUNET_RECLAIM_ATTRIBUTE_list_deserialize ((char *)&im[1], attrs_len); - tio->r_id = ntohl (im->id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received ISSUE_TICKET message\n"); + tio = GNUNET_new(struct TicketIssueOperation); + attrs_len = ntohs(im->attr_len); + attrs = GNUNET_RECLAIM_ATTRIBUTE_list_deserialize((char *)&im[1], attrs_len); + tio->r_id = ntohl(im->id); tio->client = idp; - GNUNET_CONTAINER_DLL_insert (idp->issue_op_head, idp->issue_op_tail, tio); - RECLAIM_TICKETS_issue (&im->identity, - attrs, - &im->rp, - &issue_ticket_result_cb, - tio); - GNUNET_SERVICE_client_continue (idp->client); - GNUNET_RECLAIM_ATTRIBUTE_list_destroy (attrs); + GNUNET_CONTAINER_DLL_insert(idp->issue_op_head, idp->issue_op_tail, tio); + RECLAIM_TICKETS_issue(&im->identity, + attrs, + &im->rp, + &issue_ticket_result_cb, + tio); + GNUNET_SERVICE_client_continue(idp->client); + GNUNET_RECLAIM_ATTRIBUTE_list_destroy(attrs); } /********************************************************** - * Revocation - **********************************************************/ +* Revocation +**********************************************************/ /** * Handles revocation result @@ -709,22 +715,22 @@ handle_issue_ticket_message (void *cls, const struct IssueTicketMessage *im) * @param success revocation result (GNUNET_OK if successful) */ static void -revoke_result_cb (void *cls, int32_t success) +revoke_result_cb(void *cls, int32_t success) { struct TicketRevocationOperation *rop = cls; struct GNUNET_MQ_Envelope *env; struct RevokeTicketResultMessage *trm; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending REVOKE_TICKET_RESULT message\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending REVOKE_TICKET_RESULT message\n"); rop->rh = NULL; - env = GNUNET_MQ_msg (trm, GNUNET_MESSAGE_TYPE_RECLAIM_REVOKE_TICKET_RESULT); - trm->id = htonl (rop->r_id); - trm->success = htonl (success); - GNUNET_MQ_send (rop->client->mq, env); - GNUNET_CONTAINER_DLL_remove (rop->client->revoke_op_head, - rop->client->revoke_op_tail, - rop); - GNUNET_free (rop); + env = GNUNET_MQ_msg(trm, GNUNET_MESSAGE_TYPE_RECLAIM_REVOKE_TICKET_RESULT); + trm->id = htonl(rop->r_id); + trm->success = htonl(success); + GNUNET_MQ_send(rop->client->mq, env); + GNUNET_CONTAINER_DLL_remove(rop->client->revoke_op_head, + rop->client->revoke_op_tail, + rop); + GNUNET_free(rop); } @@ -736,15 +742,16 @@ revoke_result_cb (void *cls, int32_t success) * @return GNUNET_OK if message is ok */ static int -check_revoke_ticket_message (void *cls, const struct RevokeTicketMessage *im) +check_revoke_ticket_message(void *cls, const struct RevokeTicketMessage *im) { uint16_t size; - size = ntohs (im->header.size); - if (size != sizeof (struct RevokeTicketMessage)) { - GNUNET_break (0); - return GNUNET_SYSERR; - } + size = ntohs(im->header.size); + if (size != sizeof(struct RevokeTicketMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -756,19 +763,19 @@ check_revoke_ticket_message (void *cls, const struct RevokeTicketMessage *im) * @param rm the message to handle */ static void -handle_revoke_ticket_message (void *cls, const struct RevokeTicketMessage *rm) +handle_revoke_ticket_message(void *cls, const struct RevokeTicketMessage *rm) { struct TicketRevocationOperation *rop; struct IdpClient *idp = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received REVOKE_TICKET message\n"); - rop = GNUNET_new (struct TicketRevocationOperation); - rop->r_id = ntohl (rm->id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received REVOKE_TICKET message\n"); + rop = GNUNET_new(struct TicketRevocationOperation); + rop->r_id = ntohl(rm->id); rop->client = idp; - GNUNET_CONTAINER_DLL_insert (idp->revoke_op_head, idp->revoke_op_tail, rop); + GNUNET_CONTAINER_DLL_insert(idp->revoke_op_head, idp->revoke_op_tail, rop); rop->rh - = RECLAIM_TICKETS_revoke (&rm->ticket, &rm->identity, &revoke_result_cb, rop); - GNUNET_SERVICE_client_continue (idp->client); + = RECLAIM_TICKETS_revoke(&rm->ticket, &rm->identity, &revoke_result_cb, rop); + GNUNET_SERVICE_client_continue(idp->client); } @@ -782,36 +789,38 @@ handle_revoke_ticket_message (void *cls, const struct RevokeTicketMessage *rm) * @param emsg error message (NULL if success=GNUNET_OK) */ static void -consume_result_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, - const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, - int32_t success, - const char *emsg) +consume_result_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, + const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, + int32_t success, + const char *emsg) { struct ConsumeTicketOperation *cop = cls; struct ConsumeTicketResultMessage *crm; struct GNUNET_MQ_Envelope *env; char *data_tmp; size_t attrs_len; - if (GNUNET_OK != success) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error consuming ticket: %s\n", emsg); - } - attrs_len = GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size (attrs); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending CONSUME_TICKET_RESULT message\n"); - env = GNUNET_MQ_msg_extra (crm, - attrs_len, - GNUNET_MESSAGE_TYPE_RECLAIM_CONSUME_TICKET_RESULT); - crm->id = htonl (cop->r_id); - crm->attrs_len = htons (attrs_len); + + if (GNUNET_OK != success) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error consuming ticket: %s\n", emsg); + } + attrs_len = GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size(attrs); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending CONSUME_TICKET_RESULT message\n"); + env = GNUNET_MQ_msg_extra(crm, + attrs_len, + GNUNET_MESSAGE_TYPE_RECLAIM_CONSUME_TICKET_RESULT); + crm->id = htonl(cop->r_id); + crm->attrs_len = htons(attrs_len); crm->identity = *identity; - crm->result = htonl (success); + crm->result = htonl(success); data_tmp = (char *)&crm[1]; - GNUNET_RECLAIM_ATTRIBUTE_list_serialize (attrs, data_tmp); - GNUNET_MQ_send (cop->client->mq, env); - GNUNET_CONTAINER_DLL_remove (cop->client->consume_op_head, - cop->client->consume_op_tail, - cop); - GNUNET_free (cop); + GNUNET_RECLAIM_ATTRIBUTE_list_serialize(attrs, data_tmp); + GNUNET_MQ_send(cop->client->mq, env); + GNUNET_CONTAINER_DLL_remove(cop->client->consume_op_head, + cop->client->consume_op_tail, + cop); + GNUNET_free(cop); } @@ -822,15 +831,16 @@ consume_result_cb (void *cls, * @param cm the message to handle */ static int -check_consume_ticket_message (void *cls, const struct ConsumeTicketMessage *cm) +check_consume_ticket_message(void *cls, const struct ConsumeTicketMessage *cm) { uint16_t size; - size = ntohs (cm->header.size); - if (size != sizeof (struct ConsumeTicketMessage)) { - GNUNET_break (0); - return GNUNET_SYSERR; - } + size = ntohs(cm->header.size); + if (size != sizeof(struct ConsumeTicketMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -842,24 +852,24 @@ check_consume_ticket_message (void *cls, const struct ConsumeTicketMessage *cm) * @cm the message to handle */ static void -handle_consume_ticket_message (void *cls, const struct ConsumeTicketMessage *cm) +handle_consume_ticket_message(void *cls, const struct ConsumeTicketMessage *cm) { struct ConsumeTicketOperation *cop; struct IdpClient *idp = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received CONSUME_TICKET message\n"); - cop = GNUNET_new (struct ConsumeTicketOperation); - cop->r_id = ntohl (cm->id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received CONSUME_TICKET message\n"); + cop = GNUNET_new(struct ConsumeTicketOperation); + cop->r_id = ntohl(cm->id); cop->client = idp; cop->ch - = RECLAIM_TICKETS_consume (&cm->identity, &cm->ticket, &consume_result_cb, cop); - GNUNET_CONTAINER_DLL_insert (idp->consume_op_head, idp->consume_op_tail, cop); - GNUNET_SERVICE_client_continue (idp->client); + = RECLAIM_TICKETS_consume(&cm->identity, &cm->ticket, &consume_result_cb, cop); + GNUNET_CONTAINER_DLL_insert(idp->consume_op_head, idp->consume_op_tail, cop); + GNUNET_SERVICE_client_continue(idp->client); } /***************************************** - * Attribute store - *****************************************/ +* Attribute store +*****************************************/ /** @@ -870,32 +880,33 @@ handle_consume_ticket_message (void *cls, const struct ConsumeTicketMessage *cm) * @param emsg error message (NULL if success=GNUNET_OK) */ static void -attr_store_cont (void *cls, int32_t success, const char *emsg) +attr_store_cont(void *cls, int32_t success, const char *emsg) { struct AttributeStoreHandle *ash = cls; struct GNUNET_MQ_Envelope *env; struct SuccessResultMessage *acr_msg; ash->ns_qe = NULL; - GNUNET_CONTAINER_DLL_remove (ash->client->store_op_head, - ash->client->store_op_tail, - ash); - - if (GNUNET_SYSERR == success) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to store attribute %s\n", - emsg); - cleanup_as_handle (ash); - GNUNET_SCHEDULER_add_now (&do_shutdown, NULL); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending SUCCESS_RESPONSE message\n"); - env = GNUNET_MQ_msg (acr_msg, GNUNET_MESSAGE_TYPE_RECLAIM_SUCCESS_RESPONSE); - acr_msg->id = htonl (ash->r_id); - acr_msg->op_result = htonl (GNUNET_OK); - GNUNET_MQ_send (ash->client->mq, env); - cleanup_as_handle (ash); + GNUNET_CONTAINER_DLL_remove(ash->client->store_op_head, + ash->client->store_op_tail, + ash); + + if (GNUNET_SYSERR == success) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to store attribute %s\n", + emsg); + cleanup_as_handle(ash); + GNUNET_SCHEDULER_add_now(&do_shutdown, NULL); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending SUCCESS_RESPONSE message\n"); + env = GNUNET_MQ_msg(acr_msg, GNUNET_MESSAGE_TYPE_RECLAIM_SUCCESS_RESPONSE); + acr_msg->id = htonl(ash->r_id); + acr_msg->op_result = htonl(GNUNET_OK); + GNUNET_MQ_send(ash->client->mq, env); + cleanup_as_handle(ash); } @@ -905,7 +916,7 @@ attr_store_cont (void *cls, int32_t success, const char *emsg) * @param cls the AttributeStoreHandle */ static void -attr_store_task (void *cls) +attr_store_task(void *cls) { struct AttributeStoreHandle *ash = cls; struct GNUNET_GNSRECORD_Data rd[1]; @@ -913,32 +924,32 @@ attr_store_task (void *cls) char *label; size_t buf_size; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Storing attribute\n"); - buf_size = GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size (ash->claim); - buf = GNUNET_malloc (buf_size); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Storing attribute\n"); + buf_size = GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size(ash->claim); + buf = GNUNET_malloc(buf_size); // Give the ash a new id if unset if (0 == ash->claim->id) ash->claim->id - = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX); - GNUNET_RECLAIM_ATTRIBUTE_serialize (ash->claim, buf); + = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX); + GNUNET_RECLAIM_ATTRIBUTE_serialize(ash->claim, buf); label - = GNUNET_STRINGS_data_to_string_alloc (&ash->claim->id, sizeof (uint64_t)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Encrypting with label %s\n", label); + = GNUNET_STRINGS_data_to_string_alloc(&ash->claim->id, sizeof(uint64_t)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Encrypting with label %s\n", label); rd[0].data_size = buf_size; rd[0].data = buf; rd[0].record_type = GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR; rd[0].flags = GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION; rd[0].expiration_time = ash->exp.rel_value_us; - ash->ns_qe = GNUNET_NAMESTORE_records_store (nsh, - &ash->identity, - label, - 1, - rd, - &attr_store_cont, - ash); - GNUNET_free (buf); - GNUNET_free (label); + ash->ns_qe = GNUNET_NAMESTORE_records_store(nsh, + &ash->identity, + label, + 1, + rd, + &attr_store_cont, + ash); + GNUNET_free(buf); + GNUNET_free(label); } @@ -949,16 +960,17 @@ attr_store_task (void *cls) * @param sam the message to check */ static int -check_attribute_store_message (void *cls, - const struct AttributeStoreMessage *sam) +check_attribute_store_message(void *cls, + const struct AttributeStoreMessage *sam) { uint16_t size; - size = ntohs (sam->header.size); - if (size <= sizeof (struct AttributeStoreMessage)) { - GNUNET_break (0); - return GNUNET_SYSERR; - } + size = ntohs(sam->header.size); + if (size <= sizeof(struct AttributeStoreMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -970,28 +982,29 @@ check_attribute_store_message (void *cls, * @param sam the message to handle */ static void -handle_attribute_store_message (void *cls, - const struct AttributeStoreMessage *sam) +handle_attribute_store_message(void *cls, + const struct AttributeStoreMessage *sam) { struct AttributeStoreHandle *ash; struct IdpClient *idp = cls; size_t data_len; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received ATTRIBUTE_STORE message\n"); - data_len = ntohs (sam->attr_len); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received ATTRIBUTE_STORE message\n"); + + data_len = ntohs(sam->attr_len); - ash = GNUNET_new (struct AttributeStoreHandle); - ash->claim = GNUNET_RECLAIM_ATTRIBUTE_deserialize ((char *)&sam[1], data_len); + ash = GNUNET_new(struct AttributeStoreHandle); + ash->claim = GNUNET_RECLAIM_ATTRIBUTE_deserialize((char *)&sam[1], data_len); - ash->r_id = ntohl (sam->id); + ash->r_id = ntohl(sam->id); ash->identity = sam->identity; - ash->exp.rel_value_us = GNUNET_ntohll (sam->exp); - GNUNET_CRYPTO_ecdsa_key_get_public (&sam->identity, &ash->identity_pkey); + ash->exp.rel_value_us = GNUNET_ntohll(sam->exp); + GNUNET_CRYPTO_ecdsa_key_get_public(&sam->identity, &ash->identity_pkey); - GNUNET_SERVICE_client_continue (idp->client); + GNUNET_SERVICE_client_continue(idp->client); ash->client = idp; - GNUNET_CONTAINER_DLL_insert (idp->store_op_head, idp->store_op_tail, ash); - GNUNET_SCHEDULER_add_now (&attr_store_task, ash); + GNUNET_CONTAINER_DLL_insert(idp->store_op_head, idp->store_op_tail, ash); + GNUNET_SCHEDULER_add_now(&attr_store_task, ash); } @@ -1002,20 +1015,20 @@ handle_attribute_store_message (void *cls, * @param success the success status */ static void -send_delete_response (struct AttributeDeleteHandle *adh, int32_t success) +send_delete_response(struct AttributeDeleteHandle *adh, int32_t success) { struct GNUNET_MQ_Envelope *env; struct SuccessResultMessage *acr_msg; - GNUNET_CONTAINER_DLL_remove (adh->client->delete_op_head, - adh->client->delete_op_tail, - adh); + GNUNET_CONTAINER_DLL_remove(adh->client->delete_op_head, + adh->client->delete_op_tail, + adh); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending SUCCESS_RESPONSE message\n"); - env = GNUNET_MQ_msg (acr_msg, GNUNET_MESSAGE_TYPE_RECLAIM_SUCCESS_RESPONSE); - acr_msg->id = htonl (adh->r_id); - acr_msg->op_result = htonl (success); - GNUNET_MQ_send (adh->client->mq, env); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending SUCCESS_RESPONSE message\n"); + env = GNUNET_MQ_msg(acr_msg, GNUNET_MESSAGE_TYPE_RECLAIM_SUCCESS_RESPONSE); + acr_msg->id = htonl(adh->r_id); + acr_msg->op_result = htonl(success); + GNUNET_MQ_send(adh->client->mq, env); } @@ -1030,39 +1043,41 @@ send_delete_response (struct AttributeDeleteHandle *adh, int32_t success) * @param rd record data */ static void -ticket_iter (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +ticket_iter(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct AttributeDeleteHandle *adh = cls; struct TicketRecordsEntry *le; int has_changed = GNUNET_NO; - for (int i = 0; i < rd_count; i++) { - if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF != rd[i].record_type) - continue; - if (0 != memcmp (rd[i].data, &adh->claim->id, sizeof (uint64_t))) - continue; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Attribute to delete found (%s)\n", - adh->label); - has_changed = GNUNET_YES; - break; - } - if (GNUNET_YES == has_changed) { - le = GNUNET_new (struct TicketRecordsEntry); - le->data_size = GNUNET_GNSRECORD_records_get_size (rd_count, rd); - le->data = GNUNET_malloc (le->data_size); - le->rd_count = rd_count; - le->label = GNUNET_strdup (label); - GNUNET_GNSRECORD_records_serialize (rd_count, rd, le->data_size, le->data); - GNUNET_CONTAINER_DLL_insert (adh->tickets_to_update_head, - adh->tickets_to_update_tail, - le); - } - GNUNET_NAMESTORE_zone_iterator_next (adh->ns_it, 1); + for (int i = 0; i < rd_count; i++) + { + if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF != rd[i].record_type) + continue; + if (0 != memcmp(rd[i].data, &adh->claim->id, sizeof(uint64_t))) + continue; + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Attribute to delete found (%s)\n", + adh->label); + has_changed = GNUNET_YES; + break; + } + if (GNUNET_YES == has_changed) + { + le = GNUNET_new(struct TicketRecordsEntry); + le->data_size = GNUNET_GNSRECORD_records_get_size(rd_count, rd); + le->data = GNUNET_malloc(le->data_size); + le->rd_count = rd_count; + le->label = GNUNET_strdup(label); + GNUNET_GNSRECORD_records_serialize(rd_count, rd, le->data_size, le->data); + GNUNET_CONTAINER_DLL_insert(adh->tickets_to_update_head, + adh->tickets_to_update_tail, + le); + } + GNUNET_NAMESTORE_zone_iterator_next(adh->ns_it, 1); } @@ -1071,7 +1086,7 @@ ticket_iter (void *cls, * @param cls our deletion handle */ static void -update_tickets (void *cls); +update_tickets(void *cls); /** @@ -1082,11 +1097,12 @@ update_tickets (void *cls); * @param emsg error message (NULL if success=GNUNET_OK) */ static void -ticket_updated (void *cls, int32_t success, const char *emsg) +ticket_updated(void *cls, int32_t success, const char *emsg) { struct AttributeDeleteHandle *adh = cls; + adh->ns_qe = NULL; - GNUNET_SCHEDULER_add_now (&update_tickets, adh); + GNUNET_SCHEDULER_add_now(&update_tickets, adh); } @@ -1098,55 +1114,58 @@ ticket_updated (void *cls, int32_t success, const char *emsg) * @param cls our attribute deletion handle */ static void -update_tickets (void *cls) +update_tickets(void *cls) { struct AttributeDeleteHandle *adh = cls; struct TicketRecordsEntry *le; - if (NULL == adh->tickets_to_update_head) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Finished updatding tickets, success\n"); - send_delete_response (adh, GNUNET_OK); - cleanup_adh (adh); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Updating %s\n", - adh->tickets_to_update_head->label); + + if (NULL == adh->tickets_to_update_head) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Finished updatding tickets, success\n"); + send_delete_response(adh, GNUNET_OK); + cleanup_adh(adh); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Updating %s\n", + adh->tickets_to_update_head->label); le = adh->tickets_to_update_head; - GNUNET_CONTAINER_DLL_remove (adh->tickets_to_update_head, - adh->tickets_to_update_tail, - le); + GNUNET_CONTAINER_DLL_remove(adh->tickets_to_update_head, + adh->tickets_to_update_tail, + le); struct GNUNET_GNSRECORD_Data rd[le->rd_count]; struct GNUNET_GNSRECORD_Data rd_new[le->rd_count - 1]; - if (GNUNET_OK != GNUNET_GNSRECORD_records_deserialize (le->data_size, - le->data, - le->rd_count, - rd)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to deserialize record data!\n"); - send_delete_response (adh, GNUNET_SYSERR); - cleanup_adh (adh); - return; - } + if (GNUNET_OK != GNUNET_GNSRECORD_records_deserialize(le->data_size, + le->data, + le->rd_count, + rd)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to deserialize record data!\n"); + send_delete_response(adh, GNUNET_SYSERR); + cleanup_adh(adh); + return; + } int j = 0; - for (int i = 0; i < le->rd_count; i++) { - if ((GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF == rd[i].record_type) - && (0 == memcmp (rd[i].data, &adh->claim->id, sizeof (uint64_t)))) - continue; - rd_new[j] = rd[i]; - j++; - } - adh->ns_qe = GNUNET_NAMESTORE_records_store (nsh, - &adh->identity, - le->label, - j, - rd_new, - &ticket_updated, - adh); - GNUNET_free (le->label); - GNUNET_free (le->data); - GNUNET_free (le); + for (int i = 0; i < le->rd_count; i++) + { + if ((GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF == rd[i].record_type) + && (0 == memcmp(rd[i].data, &adh->claim->id, sizeof(uint64_t)))) + continue; + rd_new[j] = rd[i]; + j++; + } + adh->ns_qe = GNUNET_NAMESTORE_records_store(nsh, + &adh->identity, + le->label, + j, + rd_new, + &ticket_updated, + adh); + GNUNET_free(le->label); + GNUNET_free(le->data); + GNUNET_free(le); } @@ -1156,11 +1175,12 @@ update_tickets (void *cls) * @param cls our attribute deletion handle */ static void -ticket_iter_fin (void *cls) +ticket_iter_fin(void *cls) { struct AttributeDeleteHandle *adh = cls; + adh->ns_it = NULL; - GNUNET_SCHEDULER_add_now (&update_tickets, adh); + GNUNET_SCHEDULER_add_now(&update_tickets, adh); } @@ -1170,15 +1190,16 @@ ticket_iter_fin (void *cls) * @param cls our attribute deletion handle */ static void -ticket_iter_err (void *cls) +ticket_iter_err(void *cls) { struct AttributeDeleteHandle *adh = cls; + adh->ns_it = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Namestore error on delete %s\n", - adh->label); - send_delete_response (adh, GNUNET_SYSERR); - cleanup_adh (adh); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Namestore error on delete %s\n", + adh->label); + send_delete_response(adh, GNUNET_SYSERR); + cleanup_adh(adh); } @@ -1189,17 +1210,18 @@ ticket_iter_err (void *cls) * @param cls attribute deletion handle */ static void -start_ticket_update (void *cls) +start_ticket_update(void *cls) { struct AttributeDeleteHandle *adh = cls; - adh->ns_it = GNUNET_NAMESTORE_zone_iteration_start (nsh, - &adh->identity, - &ticket_iter_err, - adh, - &ticket_iter, - adh, - &ticket_iter_fin, - adh); + + adh->ns_it = GNUNET_NAMESTORE_zone_iteration_start(nsh, + &adh->identity, + &ticket_iter_err, + adh, + &ticket_iter, + adh, + &ticket_iter_fin, + adh); } @@ -1211,20 +1233,22 @@ start_ticket_update (void *cls) * @param emsg error message (NULL if success=GNUNET_OK) */ static void -attr_delete_cont (void *cls, int32_t success, const char *emsg) +attr_delete_cont(void *cls, int32_t success, const char *emsg) { struct AttributeDeleteHandle *adh = cls; + adh->ns_qe = NULL; - if (GNUNET_SYSERR == success) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error deleting attribute %s\n", - adh->label); - send_delete_response (adh, GNUNET_SYSERR); - cleanup_adh (adh); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Updating tickets...\n"); - GNUNET_SCHEDULER_add_now (&start_ticket_update, adh); + if (GNUNET_SYSERR == success) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error deleting attribute %s\n", + adh->label); + send_delete_response(adh, GNUNET_SYSERR); + cleanup_adh(adh); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Updating tickets...\n"); + GNUNET_SCHEDULER_add_now(&start_ticket_update, adh); } @@ -1235,16 +1259,17 @@ attr_delete_cont (void *cls, int32_t success, const char *emsg) * @dam message to check */ static int -check_attribute_delete_message (void *cls, - const struct AttributeDeleteMessage *dam) +check_attribute_delete_message(void *cls, + const struct AttributeDeleteMessage *dam) { uint16_t size; - size = ntohs (dam->header.size); - if (size <= sizeof (struct AttributeDeleteMessage)) { - GNUNET_break (0); - return GNUNET_SYSERR; - } + size = ntohs(dam->header.size); + if (size <= sizeof(struct AttributeDeleteMessage)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -1256,39 +1281,40 @@ check_attribute_delete_message (void *cls, * @param dam deletion message */ static void -handle_attribute_delete_message (void *cls, - const struct AttributeDeleteMessage *dam) +handle_attribute_delete_message(void *cls, + const struct AttributeDeleteMessage *dam) { struct AttributeDeleteHandle *adh; struct IdpClient *idp = cls; size_t data_len; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received ATTRIBUTE_DELETE message\n"); - data_len = ntohs (dam->attr_len); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received ATTRIBUTE_DELETE message\n"); - adh = GNUNET_new (struct AttributeDeleteHandle); - adh->claim = GNUNET_RECLAIM_ATTRIBUTE_deserialize ((char *)&dam[1], data_len); + data_len = ntohs(dam->attr_len); - adh->r_id = ntohl (dam->id); + adh = GNUNET_new(struct AttributeDeleteHandle); + adh->claim = GNUNET_RECLAIM_ATTRIBUTE_deserialize((char *)&dam[1], data_len); + + adh->r_id = ntohl(dam->id); adh->identity = dam->identity; adh->label - = GNUNET_STRINGS_data_to_string_alloc (&adh->claim->id, sizeof (uint64_t)); - GNUNET_SERVICE_client_continue (idp->client); + = GNUNET_STRINGS_data_to_string_alloc(&adh->claim->id, sizeof(uint64_t)); + GNUNET_SERVICE_client_continue(idp->client); adh->client = idp; - GNUNET_CONTAINER_DLL_insert (idp->delete_op_head, idp->delete_op_tail, adh); - adh->ns_qe = GNUNET_NAMESTORE_records_store (nsh, - &adh->identity, - adh->label, - 0, - NULL, - &attr_delete_cont, - adh); + GNUNET_CONTAINER_DLL_insert(idp->delete_op_head, idp->delete_op_tail, adh); + adh->ns_qe = GNUNET_NAMESTORE_records_store(nsh, + &adh->identity, + adh->label, + 0, + NULL, + &attr_delete_cont, + adh); } /************************************************* - * Attrubute iteration - *************************************************/ +* Attrubute iteration +*************************************************/ /** @@ -1297,21 +1323,21 @@ handle_attribute_delete_message (void *cls, * @param cls our iterator handle */ static void -attr_iter_finished (void *cls) +attr_iter_finished(void *cls) { struct AttributeIterator *ai = cls; struct GNUNET_MQ_Envelope *env; struct AttributeResultMessage *arm; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending ATTRIBUTE_RESULT message\n"); - env = GNUNET_MQ_msg (arm, GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_RESULT); - arm->id = htonl (ai->request_id); - arm->attr_len = htons (0); - GNUNET_MQ_send (ai->client->mq, env); - GNUNET_CONTAINER_DLL_remove (ai->client->attr_iter_head, - ai->client->attr_iter_tail, - ai); - GNUNET_free (ai); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending ATTRIBUTE_RESULT message\n"); + env = GNUNET_MQ_msg(arm, GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_RESULT); + arm->id = htonl(ai->request_id); + arm->attr_len = htons(0); + GNUNET_MQ_send(ai->client->mq, env); + GNUNET_CONTAINER_DLL_remove(ai->client->attr_iter_head, + ai->client->attr_iter_tail, + ai); + GNUNET_free(ai); } /** @@ -1320,12 +1346,12 @@ attr_iter_finished (void *cls) * @param cls our attribute iteration handle */ static void -attr_iter_error (void *cls) +attr_iter_error(void *cls) { struct AttributeIterator *ai = cls; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to iterate over attributes\n"); - attr_iter_finished (ai); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Failed to iterate over attributes\n"); + attr_iter_finished(ai); } @@ -1339,37 +1365,39 @@ attr_iter_error (void *cls) * @param rd records */ static void -attr_iter_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +attr_iter_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct AttributeIterator *ai = cls; struct AttributeResultMessage *arm; struct GNUNET_MQ_Envelope *env; char *data_tmp; - if (rd_count != 1) { - GNUNET_NAMESTORE_zone_iterator_next (ai->ns_it, 1); - return; - } - - if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR != rd->record_type) { - GNUNET_NAMESTORE_zone_iterator_next (ai->ns_it, 1); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found attribute under: %s\n", label); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending ATTRIBUTE_RESULT message\n"); - env = GNUNET_MQ_msg_extra (arm, - rd->data_size, - GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_RESULT); - arm->id = htonl (ai->request_id); - arm->attr_len = htons (rd->data_size); - GNUNET_CRYPTO_ecdsa_key_get_public (zone, &arm->identity); + if (rd_count != 1) + { + GNUNET_NAMESTORE_zone_iterator_next(ai->ns_it, 1); + return; + } + + if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR != rd->record_type) + { + GNUNET_NAMESTORE_zone_iterator_next(ai->ns_it, 1); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Found attribute under: %s\n", label); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending ATTRIBUTE_RESULT message\n"); + env = GNUNET_MQ_msg_extra(arm, + rd->data_size, + GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_RESULT); + arm->id = htonl(ai->request_id); + arm->attr_len = htons(rd->data_size); + GNUNET_CRYPTO_ecdsa_key_get_public(zone, &arm->identity); data_tmp = (char *)&arm[1]; - GNUNET_memcpy (data_tmp, rd->data, rd->data_size); - GNUNET_MQ_send (ai->client->mq, env); + GNUNET_memcpy(data_tmp, rd->data, rd->data_size); + GNUNET_MQ_send(ai->client->mq, env); } @@ -1380,29 +1408,29 @@ attr_iter_cb (void *cls, * @param ais_msg the iteration message to start */ static void -handle_iteration_start (void *cls, - const struct AttributeIterationStartMessage *ais_msg) +handle_iteration_start(void *cls, + const struct AttributeIterationStartMessage *ais_msg) { struct IdpClient *idp = cls; struct AttributeIterator *ai; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ATTRIBUTE_ITERATION_START message\n"); - ai = GNUNET_new (struct AttributeIterator); - ai->request_id = ntohl (ais_msg->id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ATTRIBUTE_ITERATION_START message\n"); + ai = GNUNET_new(struct AttributeIterator); + ai->request_id = ntohl(ais_msg->id); ai->client = idp; ai->identity = ais_msg->identity; - GNUNET_CONTAINER_DLL_insert (idp->attr_iter_head, idp->attr_iter_tail, ai); - ai->ns_it = GNUNET_NAMESTORE_zone_iteration_start (nsh, - &ai->identity, - &attr_iter_error, - ai, - &attr_iter_cb, - ai, - &attr_iter_finished, - ai); - GNUNET_SERVICE_client_continue (idp->client); + GNUNET_CONTAINER_DLL_insert(idp->attr_iter_head, idp->attr_iter_tail, ai); + ai->ns_it = GNUNET_NAMESTORE_zone_iteration_start(nsh, + &ai->identity, + &attr_iter_error, + ai, + &attr_iter_cb, + ai, + &attr_iter_finished, + ai); + GNUNET_SERVICE_client_continue(idp->client); } @@ -1413,28 +1441,29 @@ handle_iteration_start (void *cls, * @param ais_msg the stop message */ static void -handle_iteration_stop (void *cls, - const struct AttributeIterationStopMessage *ais_msg) +handle_iteration_stop(void *cls, + const struct AttributeIterationStopMessage *ais_msg) { struct IdpClient *idp = cls; struct AttributeIterator *ai; uint32_t rid; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received `%s' message\n", - "ATTRIBUTE_ITERATION_STOP"); - rid = ntohl (ais_msg->id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received `%s' message\n", + "ATTRIBUTE_ITERATION_STOP"); + rid = ntohl(ais_msg->id); for (ai = idp->attr_iter_head; NULL != ai; ai = ai->next) if (ai->request_id == rid) break; - if (NULL == ai) { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (idp->client); - return; - } - GNUNET_CONTAINER_DLL_remove (idp->attr_iter_head, idp->attr_iter_tail, ai); - GNUNET_free (ai); - GNUNET_SERVICE_client_continue (idp->client); + if (NULL == ai) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(idp->client); + return; + } + GNUNET_CONTAINER_DLL_remove(idp->attr_iter_head, idp->attr_iter_tail, ai); + GNUNET_free(ai); + GNUNET_SERVICE_client_continue(idp->client); } @@ -1445,31 +1474,32 @@ handle_iteration_stop (void *cls, * @param ais_msg the message */ static void -handle_iteration_next (void *cls, - const struct AttributeIterationNextMessage *ais_msg) +handle_iteration_next(void *cls, + const struct AttributeIterationNextMessage *ais_msg) { struct IdpClient *idp = cls; struct AttributeIterator *ai; uint32_t rid; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received ATTRIBUTE_ITERATION_NEXT message\n"); - rid = ntohl (ais_msg->id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received ATTRIBUTE_ITERATION_NEXT message\n"); + rid = ntohl(ais_msg->id); for (ai = idp->attr_iter_head; NULL != ai; ai = ai->next) if (ai->request_id == rid) break; - if (NULL == ai) { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (idp->client); - return; - } - GNUNET_NAMESTORE_zone_iterator_next (ai->ns_it, 1); - GNUNET_SERVICE_client_continue (idp->client); + if (NULL == ai) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(idp->client); + return; + } + GNUNET_NAMESTORE_zone_iterator_next(ai->ns_it, 1); + GNUNET_SERVICE_client_continue(idp->client); } /****************************************************** - * Ticket iteration - ******************************************************/ +* Ticket iteration +******************************************************/ /** * Got a ticket. Return to client @@ -1478,26 +1508,29 @@ handle_iteration_next (void *cls, * @param ticket the ticket */ static void -ticket_iter_cb (void *cls, struct GNUNET_RECLAIM_Ticket *ticket) +ticket_iter_cb(void *cls, struct GNUNET_RECLAIM_Ticket *ticket) { struct TicketIteration *ti = cls; struct GNUNET_MQ_Envelope *env; struct TicketResultMessage *trm; - env = GNUNET_MQ_msg (trm, GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_RESULT); - if (NULL == ticket) { - /* send empty response to indicate end of list */ - GNUNET_CONTAINER_DLL_remove (ti->client->ticket_iter_head, - ti->client->ticket_iter_tail, - ti); - } else { - trm->ticket = *ticket; - } - trm->id = htonl (ti->r_id); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending TICKET_RESULT message\n"); - GNUNET_MQ_send (ti->client->mq, env); + env = GNUNET_MQ_msg(trm, GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_RESULT); if (NULL == ticket) - GNUNET_free (ti); + { + /* send empty response to indicate end of list */ + GNUNET_CONTAINER_DLL_remove(ti->client->ticket_iter_head, + ti->client->ticket_iter_tail, + ti); + } + else + { + trm->ticket = *ticket; + } + trm->id = htonl(ti->r_id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending TICKET_RESULT message\n"); + GNUNET_MQ_send(ti->client->mq, env); + if (NULL == ticket) + GNUNET_free(ti); } @@ -1508,25 +1541,25 @@ ticket_iter_cb (void *cls, struct GNUNET_RECLAIM_Ticket *ticket) * @param tis_msg the iteration request message */ static void -handle_ticket_iteration_start ( - void *cls, - const struct TicketIterationStartMessage *tis_msg) +handle_ticket_iteration_start( + void *cls, + const struct TicketIterationStartMessage *tis_msg) { struct IdpClient *client = cls; struct TicketIteration *ti; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received TICKET_ITERATION_START message\n"); - ti = GNUNET_new (struct TicketIteration); - ti->r_id = ntohl (tis_msg->id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received TICKET_ITERATION_START message\n"); + ti = GNUNET_new(struct TicketIteration); + ti->r_id = ntohl(tis_msg->id); ti->client = client; - GNUNET_CONTAINER_DLL_insert (client->ticket_iter_head, - client->ticket_iter_tail, - ti); + GNUNET_CONTAINER_DLL_insert(client->ticket_iter_head, + client->ticket_iter_tail, + ti); ti->iter - = RECLAIM_TICKETS_iteration_start (&tis_msg->identity, &ticket_iter_cb, ti); - GNUNET_SERVICE_client_continue (client->client); + = RECLAIM_TICKETS_iteration_start(&tis_msg->identity, &ticket_iter_cb, ti); + GNUNET_SERVICE_client_continue(client->client); } @@ -1537,31 +1570,32 @@ handle_ticket_iteration_start ( * @param tis_msg the stop message */ static void -handle_ticket_iteration_stop (void *cls, - const struct TicketIterationStopMessage *tis_msg) +handle_ticket_iteration_stop(void *cls, + const struct TicketIterationStopMessage *tis_msg) { struct IdpClient *client = cls; struct TicketIteration *ti; uint32_t rid; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received `%s' message\n", - "TICKET_ITERATION_STOP"); - rid = ntohl (tis_msg->id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received `%s' message\n", + "TICKET_ITERATION_STOP"); + rid = ntohl(tis_msg->id); for (ti = client->ticket_iter_head; NULL != ti; ti = ti->next) if (ti->r_id == rid) break; - if (NULL == ti) { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (client->client); - return; - } - RECLAIM_TICKETS_iteration_stop (ti->iter); - GNUNET_CONTAINER_DLL_remove (client->ticket_iter_head, - client->ticket_iter_tail, - ti); - GNUNET_free (ti); - GNUNET_SERVICE_client_continue (client->client); + if (NULL == ti) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(client->client); + return; + } + RECLAIM_TICKETS_iteration_stop(ti->iter); + GNUNET_CONTAINER_DLL_remove(client->ticket_iter_head, + client->ticket_iter_tail, + ti); + GNUNET_free(ti); + GNUNET_SERVICE_client_continue(client->client); } @@ -1572,26 +1606,27 @@ handle_ticket_iteration_stop (void *cls, * @param tis_msg the message */ static void -handle_ticket_iteration_next (void *cls, - const struct TicketIterationNextMessage *tis_msg) +handle_ticket_iteration_next(void *cls, + const struct TicketIterationNextMessage *tis_msg) { struct IdpClient *client = cls; struct TicketIteration *ti; uint32_t rid; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Received TICKET_ITERATION_NEXT message\n"); - rid = ntohl (tis_msg->id); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Received TICKET_ITERATION_NEXT message\n"); + rid = ntohl(tis_msg->id); for (ti = client->ticket_iter_head; NULL != ti; ti = ti->next) if (ti->r_id == rid) break; - if (NULL == ti) { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (client->client); - return; - } - RECLAIM_TICKETS_iteration_next (ti->iter); - GNUNET_SERVICE_client_continue (client->client); + if (NULL == ti) + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(client->client); + return; + } + RECLAIM_TICKETS_iteration_next(ti->iter); + GNUNET_SERVICE_client_continue(client->client); } @@ -1603,26 +1638,28 @@ handle_ticket_iteration_next (void *cls, * @param server the service handle */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *c, - struct GNUNET_SERVICE_Handle *server) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *c, + struct GNUNET_SERVICE_Handle *server) { cfg = c; - if (GNUNET_OK != RECLAIM_TICKETS_init (cfg)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to initialize TICKETS subsystem.\n"); - GNUNET_SCHEDULER_shutdown (); - return; - } + if (GNUNET_OK != RECLAIM_TICKETS_init(cfg)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to initialize TICKETS subsystem.\n"); + GNUNET_SCHEDULER_shutdown(); + return; + } // Connect to identity and namestore services - nsh = GNUNET_NAMESTORE_connect (cfg); - if (NULL == nsh) { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "error connecting to namestore"); - } - - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL); + nsh = GNUNET_NAMESTORE_connect(cfg); + if (NULL == nsh) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "error connecting to namestore"); + } + + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); } @@ -1634,16 +1671,17 @@ run (void *cls, * @param app_ctx @a client */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - void *app_ctx) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + void *app_ctx) { struct IdpClient *idp = app_ctx; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p disconnected\n", client); - GNUNET_CONTAINER_DLL_remove (client_list_head, - client_list_tail, - idp); - cleanup_client (idp); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Client %p disconnected\n", client); + GNUNET_CONTAINER_DLL_remove(client_list_head, + client_list_tail, + idp); + cleanup_client(idp); } @@ -1656,18 +1694,19 @@ client_disconnect_cb (void *cls, * @return internal namestore client structure for this client */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *client, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *client, + struct GNUNET_MQ_Handle *mq) { struct IdpClient *idp; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p connected\n", client); - idp = GNUNET_new (struct IdpClient); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Client %p connected\n", client); + idp = GNUNET_new(struct IdpClient); idp->client = client; idp->mq = mq; - GNUNET_CONTAINER_DLL_insert (client_list_head, - client_list_tail, - idp); + GNUNET_CONTAINER_DLL_insert(client_list_head, + client_list_tail, + idp); return idp; } @@ -1675,57 +1714,57 @@ client_connect_cb (void *cls, /** * Define "main" method using service macro. */ -GNUNET_SERVICE_MAIN ( - "reclaim", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_var_size (attribute_store_message, - GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_STORE, - struct AttributeStoreMessage, - NULL), - GNUNET_MQ_hd_var_size (attribute_delete_message, - GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_DELETE, - struct AttributeDeleteMessage, - NULL), - GNUNET_MQ_hd_fixed_size ( - iteration_start, - GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_START, - struct AttributeIterationStartMessage, - NULL), - GNUNET_MQ_hd_fixed_size (iteration_next, - GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_NEXT, - struct AttributeIterationNextMessage, - NULL), - GNUNET_MQ_hd_fixed_size (iteration_stop, - GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_STOP, - struct AttributeIterationStopMessage, - NULL), - GNUNET_MQ_hd_var_size (issue_ticket_message, - GNUNET_MESSAGE_TYPE_RECLAIM_ISSUE_TICKET, - struct IssueTicketMessage, - NULL), - GNUNET_MQ_hd_var_size (consume_ticket_message, - GNUNET_MESSAGE_TYPE_RECLAIM_CONSUME_TICKET, - struct ConsumeTicketMessage, - NULL), - GNUNET_MQ_hd_fixed_size (ticket_iteration_start, - GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_START, - struct TicketIterationStartMessage, - NULL), - GNUNET_MQ_hd_fixed_size (ticket_iteration_next, - GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_NEXT, - struct TicketIterationNextMessage, - NULL), - GNUNET_MQ_hd_fixed_size (ticket_iteration_stop, - GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_STOP, - struct TicketIterationStopMessage, - NULL), - GNUNET_MQ_hd_var_size (revoke_ticket_message, - GNUNET_MESSAGE_TYPE_RECLAIM_REVOKE_TICKET, - struct RevokeTicketMessage, - NULL), - GNUNET_MQ_handler_end ()); +GNUNET_SERVICE_MAIN( + "reclaim", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_var_size(attribute_store_message, + GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_STORE, + struct AttributeStoreMessage, + NULL), + GNUNET_MQ_hd_var_size(attribute_delete_message, + GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_DELETE, + struct AttributeDeleteMessage, + NULL), + GNUNET_MQ_hd_fixed_size( + iteration_start, + GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_START, + struct AttributeIterationStartMessage, + NULL), + GNUNET_MQ_hd_fixed_size(iteration_next, + GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_NEXT, + struct AttributeIterationNextMessage, + NULL), + GNUNET_MQ_hd_fixed_size(iteration_stop, + GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_STOP, + struct AttributeIterationStopMessage, + NULL), + GNUNET_MQ_hd_var_size(issue_ticket_message, + GNUNET_MESSAGE_TYPE_RECLAIM_ISSUE_TICKET, + struct IssueTicketMessage, + NULL), + GNUNET_MQ_hd_var_size(consume_ticket_message, + GNUNET_MESSAGE_TYPE_RECLAIM_CONSUME_TICKET, + struct ConsumeTicketMessage, + NULL), + GNUNET_MQ_hd_fixed_size(ticket_iteration_start, + GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_START, + struct TicketIterationStartMessage, + NULL), + GNUNET_MQ_hd_fixed_size(ticket_iteration_next, + GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_NEXT, + struct TicketIterationNextMessage, + NULL), + GNUNET_MQ_hd_fixed_size(ticket_iteration_stop, + GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_STOP, + struct TicketIterationStopMessage, + NULL), + GNUNET_MQ_hd_var_size(revoke_ticket_message, + GNUNET_MESSAGE_TYPE_RECLAIM_REVOKE_TICKET, + struct RevokeTicketMessage, + NULL), + GNUNET_MQ_handler_end()); /* end of gnunet-service-reclaim.c */ diff --git a/src/reclaim/gnunet-service-reclaim_tickets.c b/src/reclaim/gnunet-service-reclaim_tickets.c index fcfb2267d..b38a5eb25 100644 --- a/src/reclaim/gnunet-service-reclaim_tickets.c +++ b/src/reclaim/gnunet-service-reclaim_tickets.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach @@ -44,8 +44,7 @@ struct ParallelLookup; /** * A reference to a ticket stored in GNS */ -struct TicketReference -{ +struct TicketReference { /** * DLL */ @@ -71,8 +70,7 @@ struct TicketReference /** * Handle to a consume operation */ -struct RECLAIM_TICKETS_ConsumeHandle -{ +struct RECLAIM_TICKETS_ConsumeHandle { /** * Ticket */ @@ -133,8 +131,7 @@ struct RECLAIM_TICKETS_ConsumeHandle /** * Handle for a parallel GNS lookup job */ -struct ParallelLookup -{ +struct ParallelLookup { /* DLL */ struct ParallelLookup *next; @@ -160,8 +157,7 @@ struct ParallelLookup /** * Ticket issue request handle */ -struct TicketIssueHandle -{ +struct TicketIssueHandle { /** * Attributes to issue */ @@ -202,8 +198,7 @@ struct TicketIssueHandle /** * Ticket iterator */ -struct RECLAIM_TICKETS_Iterator -{ +struct RECLAIM_TICKETS_Iterator { /** * Namestore queue entry */ @@ -221,8 +216,7 @@ struct RECLAIM_TICKETS_Iterator }; -struct RevokedAttributeEntry -{ +struct RevokedAttributeEntry { /** * DLL */ @@ -248,8 +242,7 @@ struct RevokedAttributeEntry /** * Ticket revocation request handle */ -struct RECLAIM_TICKETS_RevokeHandle -{ +struct RECLAIM_TICKETS_RevokeHandle { /** * Issuer Key */ @@ -337,31 +330,32 @@ static struct GNUNET_STATISTICS_Handle *stats; * @param rh the ticket revocation handle */ static void -cleanup_rvk (struct RECLAIM_TICKETS_RevokeHandle *rh) +cleanup_rvk(struct RECLAIM_TICKETS_RevokeHandle *rh) { struct RevokedAttributeEntry *ae; struct TicketRecordsEntry *le; + if (NULL != rh->ns_qe) - GNUNET_NAMESTORE_cancel (rh->ns_qe); + GNUNET_NAMESTORE_cancel(rh->ns_qe); if (NULL != rh->ns_it) - GNUNET_NAMESTORE_zone_iteration_stop (rh->ns_it); + GNUNET_NAMESTORE_zone_iteration_stop(rh->ns_it); while (NULL != (ae = rh->attrs_head)) - { - GNUNET_CONTAINER_DLL_remove (rh->attrs_head, rh->attrs_tail, ae); - GNUNET_free (ae); - } + { + GNUNET_CONTAINER_DLL_remove(rh->attrs_head, rh->attrs_tail, ae); + GNUNET_free(ae); + } while (NULL != (le = rh->tickets_to_update_head)) - { - GNUNET_CONTAINER_DLL_remove (rh->tickets_to_update_head, - rh->tickets_to_update_head, - le); - if (NULL != le->data) - GNUNET_free (le->data); - if (NULL != le->label) - GNUNET_free (le->label); - GNUNET_free (le); - } - GNUNET_free (rh); + { + GNUNET_CONTAINER_DLL_remove(rh->tickets_to_update_head, + rh->tickets_to_update_head, + le); + if (NULL != le->data) + GNUNET_free(le->data); + if (NULL != le->label) + GNUNET_free(le->label); + GNUNET_free(le); + } + GNUNET_free(rh); } @@ -372,7 +366,7 @@ cleanup_rvk (struct RECLAIM_TICKETS_RevokeHandle *rh) * @param cls handle to the operation */ static void -process_tickets (void *cls); +process_tickets(void *cls); /** @@ -384,11 +378,12 @@ process_tickets (void *cls); * @param emsg (NULL on success) */ static void -ticket_processed (void *cls, int32_t success, const char *emsg) +ticket_processed(void *cls, int32_t success, const char *emsg) { struct RECLAIM_TICKETS_RevokeHandle *rvk = cls; + rvk->ns_qe = NULL; - GNUNET_SCHEDULER_add_now (&process_tickets, rvk); + GNUNET_SCHEDULER_add_now(&process_tickets, rvk); } @@ -398,56 +393,57 @@ ticket_processed (void *cls, int32_t success, const char *emsg) * @param cls handle to the operation */ static void -process_tickets (void *cls) +process_tickets(void *cls) { struct RECLAIM_TICKETS_RevokeHandle *rvk = cls; struct TicketRecordsEntry *le; struct RevokedAttributeEntry *ae; + if (NULL == rvk->tickets_to_update_head) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Finished updatding tickets, success\n"); - rvk->cb (rvk->cb_cls, GNUNET_OK); - cleanup_rvk (rvk); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Finished updatding tickets, success\n"); + rvk->cb(rvk->cb_cls, GNUNET_OK); + cleanup_rvk(rvk); + return; + } le = rvk->tickets_to_update_head; - GNUNET_CONTAINER_DLL_remove (rvk->tickets_to_update_head, - rvk->tickets_to_update_tail, - le); + GNUNET_CONTAINER_DLL_remove(rvk->tickets_to_update_head, + rvk->tickets_to_update_tail, + le); struct GNUNET_GNSRECORD_Data rd[le->rd_count]; - if (GNUNET_OK != GNUNET_GNSRECORD_records_deserialize (le->data_size, - le->data, - le->rd_count, - rd)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to deserialize ticket record(s)\n"); - rvk->cb (rvk->cb_cls, GNUNET_SYSERR); - cleanup_rvk (rvk); - return; - } + if (GNUNET_OK != GNUNET_GNSRECORD_records_deserialize(le->data_size, + le->data, + le->rd_count, + rd)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to deserialize ticket record(s)\n"); + rvk->cb(rvk->cb_cls, GNUNET_SYSERR); + cleanup_rvk(rvk); + return; + } for (int i = 0; i < le->rd_count; i++) - { - if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF != rd[i].record_type) - continue; - for (ae = rvk->attrs_head; NULL != ae; ae = ae->next) { - if (0 != memcmp (rd[i].data, &ae->old_id, sizeof (uint64_t))) + if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF != rd[i].record_type) continue; - rd[i].data = &ae->new_id; + for (ae = rvk->attrs_head; NULL != ae; ae = ae->next) + { + if (0 != memcmp(rd[i].data, &ae->old_id, sizeof(uint64_t))) + continue; + rd[i].data = &ae->new_id; + } } - } - rvk->ns_qe = GNUNET_NAMESTORE_records_store (nsh, - &rvk->identity, - le->label, - le->rd_count, - rd, - &ticket_processed, - rvk); - GNUNET_free (le->label); - GNUNET_free (le->data); - GNUNET_free (le); + rvk->ns_qe = GNUNET_NAMESTORE_records_store(nsh, + &rvk->identity, + le->label, + le->rd_count, + rd, + &ticket_processed, + rvk); + GNUNET_free(le->label); + GNUNET_free(le->data); + GNUNET_free(le); } @@ -457,11 +453,12 @@ process_tickets (void *cls) * @param cls handle to the operation */ static void -rvk_ticket_update_finished (void *cls) +rvk_ticket_update_finished(void *cls) { struct RECLAIM_TICKETS_RevokeHandle *rvk = cls; + rvk->ns_it = NULL; - GNUNET_SCHEDULER_add_now (&process_tickets, rvk); + GNUNET_SCHEDULER_add_now(&process_tickets, rvk); } @@ -476,11 +473,11 @@ rvk_ticket_update_finished (void *cls) * @param rd record set */ static void -rvk_ticket_update (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +rvk_ticket_update(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct RECLAIM_TICKETS_RevokeHandle *rvk = cls; struct TicketRecordsEntry *le; @@ -489,32 +486,32 @@ rvk_ticket_update (void *cls, /** Let everything point to the old record **/ for (int i = 0; i < rd_count; i++) - { - if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF != rd[i].record_type) - continue; - for (ae = rvk->attrs_head; NULL != ae; ae = ae->next) { - if (0 != memcmp (rd[i].data, &ae->old_id, sizeof (uint64_t))) + if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF != rd[i].record_type) continue; - has_changed = GNUNET_YES; - break; + for (ae = rvk->attrs_head; NULL != ae; ae = ae->next) + { + if (0 != memcmp(rd[i].data, &ae->old_id, sizeof(uint64_t))) + continue; + has_changed = GNUNET_YES; + break; + } + if (GNUNET_YES == has_changed) + break; } - if (GNUNET_YES == has_changed) - break; - } if (GNUNET_YES == has_changed) - { - le = GNUNET_new (struct TicketRecordsEntry); - le->data_size = GNUNET_GNSRECORD_records_get_size (rd_count, rd); - le->data = GNUNET_malloc (le->data_size); - le->rd_count = rd_count; - le->label = GNUNET_strdup (label); - GNUNET_GNSRECORD_records_serialize (rd_count, rd, le->data_size, le->data); - GNUNET_CONTAINER_DLL_insert (rvk->tickets_to_update_head, - rvk->tickets_to_update_tail, - le); - } - GNUNET_NAMESTORE_zone_iterator_next (rvk->ns_it, 1); + { + le = GNUNET_new(struct TicketRecordsEntry); + le->data_size = GNUNET_GNSRECORD_records_get_size(rd_count, rd); + le->data = GNUNET_malloc(le->data_size); + le->rd_count = rd_count; + le->label = GNUNET_strdup(label); + GNUNET_GNSRECORD_records_serialize(rd_count, rd, le->data_size, le->data); + GNUNET_CONTAINER_DLL_insert(rvk->tickets_to_update_head, + rvk->tickets_to_update_tail, + le); + } + GNUNET_NAMESTORE_zone_iterator_next(rvk->ns_it, 1); } @@ -524,15 +521,16 @@ rvk_ticket_update (void *cls, * @param cls handle to the operation */ static void -rvk_ns_iter_err (void *cls) +rvk_ns_iter_err(void *cls) { struct RECLAIM_TICKETS_RevokeHandle *rvk = cls; + rvk->ns_it = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Namestore error on revocation (id=%" PRIu64 "\n", - rvk->move_attr->old_id); - rvk->cb (rvk->cb_cls, GNUNET_SYSERR); - cleanup_rvk (rvk); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Namestore error on revocation (id=%" PRIu64 "\n", + rvk->move_attr->old_id); + rvk->cb(rvk->cb_cls, GNUNET_SYSERR); + cleanup_rvk(rvk); } @@ -542,15 +540,16 @@ rvk_ns_iter_err (void *cls) * @param cls handle to the operation */ static void -rvk_ns_err (void *cls) +rvk_ns_err(void *cls) { struct RECLAIM_TICKETS_RevokeHandle *rvk = cls; + rvk->ns_qe = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Namestore error on revocation (id=%" PRIu64 "\n", - rvk->move_attr->old_id); - rvk->cb (rvk->cb_cls, GNUNET_SYSERR); - cleanup_rvk (rvk); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Namestore error on revocation (id=%" PRIu64 "\n", + rvk->move_attr->old_id); + rvk->cb(rvk->cb_cls, GNUNET_SYSERR); + cleanup_rvk(rvk); } @@ -564,7 +563,7 @@ rvk_ns_err (void *cls) * @param rvk handle to the operation */ static void -move_attrs (struct RECLAIM_TICKETS_RevokeHandle *rh); +move_attrs(struct RECLAIM_TICKETS_RevokeHandle *rh); /** @@ -573,9 +572,9 @@ move_attrs (struct RECLAIM_TICKETS_RevokeHandle *rh); * @param cls handle to the operation. */ static void -move_attrs_cont (void *cls) +move_attrs_cont(void *cls) { - move_attrs ((struct RECLAIM_TICKETS_RevokeHandle *) cls); + move_attrs((struct RECLAIM_TICKETS_RevokeHandle *)cls); } @@ -588,21 +587,22 @@ move_attrs_cont (void *cls) * @param emsg error message (NULL on success) */ static void -del_attr_finished (void *cls, int32_t success, const char *emsg) +del_attr_finished(void *cls, int32_t success, const char *emsg) { struct RECLAIM_TICKETS_RevokeHandle *rvk = cls; + rvk->ns_qe = NULL; if (GNUNET_SYSERR == success) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error removing attribute: %s\n", - emsg); - rvk->cb (rvk->cb_cls, GNUNET_SYSERR); - cleanup_rvk (rvk); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error removing attribute: %s\n", + emsg); + rvk->cb(rvk->cb_cls, GNUNET_SYSERR); + cleanup_rvk(rvk); + return; + } rvk->move_attr = rvk->move_attr->next; - GNUNET_SCHEDULER_add_now (&move_attrs_cont, rvk); + GNUNET_SCHEDULER_add_now(&move_attrs_cont, rvk); } @@ -616,30 +616,31 @@ del_attr_finished (void *cls, int32_t success, const char *emsg) * @param emsg error message (NULL on success) */ static void -move_attr_finished (void *cls, int32_t success, const char *emsg) +move_attr_finished(void *cls, int32_t success, const char *emsg) { struct RECLAIM_TICKETS_RevokeHandle *rvk = cls; char *label; + rvk->ns_qe = NULL; if (GNUNET_SYSERR == success) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error moving attribute: %s\n", emsg); - rvk->cb (rvk->cb_cls, GNUNET_SYSERR); - cleanup_rvk (rvk); - return; - } - label = GNUNET_STRINGS_data_to_string_alloc (&rvk->move_attr->old_id, - sizeof (uint64_t)); - GNUNET_assert (NULL != label); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Removing attribute %s\n", label); - rvk->ns_qe = GNUNET_NAMESTORE_records_store (nsh, - &rvk->identity, - label, - 0, - NULL, - &del_attr_finished, - rvk); - GNUNET_free (label); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Error moving attribute: %s\n", emsg); + rvk->cb(rvk->cb_cls, GNUNET_SYSERR); + cleanup_rvk(rvk); + return; + } + label = GNUNET_STRINGS_data_to_string_alloc(&rvk->move_attr->old_id, + sizeof(uint64_t)); + GNUNET_assert(NULL != label); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Removing attribute %s\n", label); + rvk->ns_qe = GNUNET_NAMESTORE_records_store(nsh, + &rvk->identity, + label, + 0, + NULL, + &del_attr_finished, + rvk); + GNUNET_free(label); } @@ -653,11 +654,11 @@ move_attr_finished (void *cls, int32_t success, const char *emsg) * @param rd record set (the attribute) */ static void -rvk_move_attr_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +rvk_move_attr_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct RECLAIM_TICKETS_RevokeHandle *rvk = cls; struct GNUNET_RECLAIM_ATTRIBUTE_Claim *claim; @@ -665,46 +666,47 @@ rvk_move_attr_cb (void *cls, struct RevokedAttributeEntry *le; char *new_label; char *attr_data; + rvk->ns_qe = NULL; if (0 == rd_count) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "The attribute %s no longer exists!\n", - label); - le = rvk->move_attr; - rvk->move_attr = le->next; - GNUNET_CONTAINER_DLL_remove (rvk->attrs_head, rvk->attrs_tail, le); - GNUNET_free (le); - GNUNET_SCHEDULER_add_now (&move_attrs_cont, rvk); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "The attribute %s no longer exists!\n", + label); + le = rvk->move_attr; + rvk->move_attr = le->next; + GNUNET_CONTAINER_DLL_remove(rvk->attrs_head, rvk->attrs_tail, le); + GNUNET_free(le); + GNUNET_SCHEDULER_add_now(&move_attrs_cont, rvk); + return; + } /** find a new place for this attribute **/ rvk->move_attr->new_id = - GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX); + GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX); new_rd = *rd; - claim = GNUNET_RECLAIM_ATTRIBUTE_deserialize (rd->data, rd->data_size); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Attribute to update: Name=%s, ID=%" PRIu64 "\n", - claim->name, - claim->id); + claim = GNUNET_RECLAIM_ATTRIBUTE_deserialize(rd->data, rd->data_size); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Attribute to update: Name=%s, ID=%" PRIu64 "\n", + claim->name, + claim->id); claim->id = rvk->move_attr->new_id; - new_rd.data_size = GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size (claim); - attr_data = GNUNET_malloc (rd->data_size); - new_rd.data_size = GNUNET_RECLAIM_ATTRIBUTE_serialize (claim, attr_data); + new_rd.data_size = GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size(claim); + attr_data = GNUNET_malloc(rd->data_size); + new_rd.data_size = GNUNET_RECLAIM_ATTRIBUTE_serialize(claim, attr_data); new_rd.data = attr_data; - new_label = GNUNET_STRINGS_data_to_string_alloc (&rvk->move_attr->new_id, - sizeof (uint64_t)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding attribute %s\n", new_label); - rvk->ns_qe = GNUNET_NAMESTORE_records_store (nsh, - &rvk->identity, - new_label, - 1, - &new_rd, - &move_attr_finished, - rvk); - GNUNET_free (new_label); - GNUNET_free (claim); - GNUNET_free (attr_data); + new_label = GNUNET_STRINGS_data_to_string_alloc(&rvk->move_attr->new_id, + sizeof(uint64_t)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding attribute %s\n", new_label); + rvk->ns_qe = GNUNET_NAMESTORE_records_store(nsh, + &rvk->identity, + new_label, + 1, + &new_rd, + &move_attr_finished, + rvk); + GNUNET_free(new_label); + GNUNET_free(claim); + GNUNET_free(attr_data); } @@ -717,36 +719,36 @@ rvk_move_attr_cb (void *cls, * @param rvk handle to the operation */ static void -move_attrs (struct RECLAIM_TICKETS_RevokeHandle *rvk) +move_attrs(struct RECLAIM_TICKETS_RevokeHandle *rvk) { char *label; if (NULL == rvk->move_attr) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Finished moving attributes\n"); - rvk->ns_it = - GNUNET_NAMESTORE_zone_iteration_start (nsh, - &rvk->identity, - &rvk_ns_iter_err, - rvk, - &rvk_ticket_update, - rvk, - &rvk_ticket_update_finished, - rvk); - return; - } - label = GNUNET_STRINGS_data_to_string_alloc (&rvk->move_attr->old_id, - sizeof (uint64_t)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Moving attribute %s\n", label); - - rvk->ns_qe = GNUNET_NAMESTORE_records_lookup (nsh, - &rvk->identity, - label, - &rvk_ns_err, - rvk, - &rvk_move_attr_cb, - rvk); - GNUNET_free (label); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Finished moving attributes\n"); + rvk->ns_it = + GNUNET_NAMESTORE_zone_iteration_start(nsh, + &rvk->identity, + &rvk_ns_iter_err, + rvk, + &rvk_ticket_update, + rvk, + &rvk_ticket_update_finished, + rvk); + return; + } + label = GNUNET_STRINGS_data_to_string_alloc(&rvk->move_attr->old_id, + sizeof(uint64_t)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Moving attribute %s\n", label); + + rvk->ns_qe = GNUNET_NAMESTORE_records_lookup(nsh, + &rvk->identity, + label, + &rvk_ns_err, + rvk, + &rvk_move_attr_cb, + rvk); + GNUNET_free(label); } @@ -762,28 +764,29 @@ move_attrs (struct RECLAIM_TICKETS_RevokeHandle *rvk) * @param emsg error message (NULL on success) */ static void -remove_ticket_cont (void *cls, int32_t success, const char *emsg) +remove_ticket_cont(void *cls, int32_t success, const char *emsg) { struct RECLAIM_TICKETS_RevokeHandle *rvk = cls; + rvk->ns_qe = NULL; if (GNUNET_SYSERR == success) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n", emsg); - rvk->cb (rvk->cb_cls, GNUNET_SYSERR); - cleanup_rvk (rvk); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Deleted ticket\n"); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", emsg); + rvk->cb(rvk->cb_cls, GNUNET_SYSERR); + cleanup_rvk(rvk); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Deleted ticket\n"); if (0 == rvk->ticket_attrs) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "No attributes to move... strange\n"); - rvk->cb (rvk->cb_cls, GNUNET_OK); - cleanup_rvk (rvk); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "No attributes to move... strange\n"); + rvk->cb(rvk->cb_cls, GNUNET_OK); + cleanup_rvk(rvk); + return; + } rvk->move_attr = rvk->attrs_head; - move_attrs (rvk); + move_attrs(rvk); } @@ -798,38 +801,39 @@ remove_ticket_cont (void *cls, int32_t success, const char *emsg) * @param rd record set */ static void -revoke_attrs_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +revoke_attrs_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct RECLAIM_TICKETS_RevokeHandle *rvk = cls; struct RevokedAttributeEntry *le; + rvk->ns_qe = NULL; /** * Temporarily store attribute references. * We need it later. */ for (int i = 0; i < rd_count; i++) - { - if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF != rd[i].record_type) - continue; - le = GNUNET_new (struct RevokedAttributeEntry); - le->old_id = *((uint64_t *) rd[i].data); - GNUNET_CONTAINER_DLL_insert (rvk->attrs_head, rvk->attrs_tail, le); - rvk->ticket_attrs++; - } + { + if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF != rd[i].record_type) + continue; + le = GNUNET_new(struct RevokedAttributeEntry); + le->old_id = *((uint64_t *)rd[i].data); + GNUNET_CONTAINER_DLL_insert(rvk->attrs_head, rvk->attrs_tail, le); + rvk->ticket_attrs++; + } /** Remove attribute references **/ - rvk->ns_qe = GNUNET_NAMESTORE_records_store (nsh, - &rvk->identity, - label, - 0, - NULL, - &remove_ticket_cont, - rvk); + rvk->ns_qe = GNUNET_NAMESTORE_records_store(nsh, + &rvk->identity, + label, + 0, + NULL, + &remove_ticket_cont, + rvk); } @@ -839,11 +843,12 @@ revoke_attrs_cb (void *cls, * @param cls handle to the operation */ static void -rvk_attrs_err_cb (void *cls) +rvk_attrs_err_cb(void *cls) { struct RECLAIM_TICKETS_RevokeHandle *rvk = cls; - rvk->cb (rvk->cb_cls, GNUNET_SYSERR); - cleanup_rvk (rvk); + + rvk->cb(rvk->cb_cls, GNUNET_SYSERR); + cleanup_rvk(rvk); } @@ -859,31 +864,31 @@ rvk_attrs_err_cb (void *cls) * @return handle to the operation */ struct RECLAIM_TICKETS_RevokeHandle * -RECLAIM_TICKETS_revoke (const struct GNUNET_RECLAIM_Ticket *ticket, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, - RECLAIM_TICKETS_RevokeCallback cb, - void *cb_cls) +RECLAIM_TICKETS_revoke(const struct GNUNET_RECLAIM_Ticket *ticket, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, + RECLAIM_TICKETS_RevokeCallback cb, + void *cb_cls) { struct RECLAIM_TICKETS_RevokeHandle *rvk; char *label; - rvk = GNUNET_new (struct RECLAIM_TICKETS_RevokeHandle); + rvk = GNUNET_new(struct RECLAIM_TICKETS_RevokeHandle); rvk->cb = cb; rvk->cb_cls = cb_cls; rvk->identity = *identity; rvk->ticket = *ticket; - GNUNET_CRYPTO_ecdsa_key_get_public (&rvk->identity, &rvk->ticket.identity); + GNUNET_CRYPTO_ecdsa_key_get_public(&rvk->identity, &rvk->ticket.identity); /** Get shared attributes **/ - label = GNUNET_STRINGS_data_to_string_alloc (&ticket->rnd, sizeof (uint64_t)); - GNUNET_assert (NULL != label); - rvk->ns_qe = GNUNET_NAMESTORE_records_lookup (nsh, - identity, - label, - &rvk_attrs_err_cb, - rvk, - &revoke_attrs_cb, - rvk); - GNUNET_free (label); + label = GNUNET_STRINGS_data_to_string_alloc(&ticket->rnd, sizeof(uint64_t)); + GNUNET_assert(NULL != label); + rvk->ns_qe = GNUNET_NAMESTORE_records_lookup(nsh, + identity, + label, + &rvk_attrs_err_cb, + rvk, + &revoke_attrs_cb, + rvk); + GNUNET_free(label); return rvk; } @@ -894,16 +899,16 @@ RECLAIM_TICKETS_revoke (const struct GNUNET_RECLAIM_Ticket *ticket, * @param rh handle to the operation */ void -RECLAIM_TICKETS_revoke_cancel (struct RECLAIM_TICKETS_RevokeHandle *rh) +RECLAIM_TICKETS_revoke_cancel(struct RECLAIM_TICKETS_RevokeHandle *rh) { - GNUNET_assert (NULL != rh); - cleanup_rvk (rh); + GNUNET_assert(NULL != rh); + cleanup_rvk(rh); } /******************************* - * Ticket consume - *******************************/ +* Ticket consume +*******************************/ /** * Cleanup ticket consume handle @@ -911,27 +916,28 @@ RECLAIM_TICKETS_revoke_cancel (struct RECLAIM_TICKETS_RevokeHandle *rh) * @param cth the handle to clean up */ static void -cleanup_cth (struct RECLAIM_TICKETS_ConsumeHandle *cth) +cleanup_cth(struct RECLAIM_TICKETS_ConsumeHandle *cth) { struct ParallelLookup *lu; + if (NULL != cth->lookup_request) - GNUNET_GNS_lookup_cancel (cth->lookup_request); + GNUNET_GNS_lookup_cancel(cth->lookup_request); if (NULL != cth->kill_task) - GNUNET_SCHEDULER_cancel (cth->kill_task); + GNUNET_SCHEDULER_cancel(cth->kill_task); while (NULL != (lu = cth->parallel_lookups_head)) - { - if (NULL != lu->lookup_request) - GNUNET_GNS_lookup_cancel (lu->lookup_request); - GNUNET_free_non_null (lu->label); - GNUNET_CONTAINER_DLL_remove (cth->parallel_lookups_head, - cth->parallel_lookups_tail, - lu); - GNUNET_free (lu); - } + { + if (NULL != lu->lookup_request) + GNUNET_GNS_lookup_cancel(lu->lookup_request); + GNUNET_free_non_null(lu->label); + GNUNET_CONTAINER_DLL_remove(cth->parallel_lookups_head, + cth->parallel_lookups_tail, + lu); + GNUNET_free(lu); + } if (NULL != cth->attrs) - GNUNET_RECLAIM_ATTRIBUTE_list_destroy (cth->attrs); - GNUNET_free (cth); + GNUNET_RECLAIM_ATTRIBUTE_list_destroy(cth->attrs); + GNUNET_free(cth); } @@ -943,50 +949,51 @@ cleanup_cth (struct RECLAIM_TICKETS_ConsumeHandle *cth) * @param rd record set */ static void -process_parallel_lookup_result (void *cls, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +process_parallel_lookup_result(void *cls, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct ParallelLookup *parallel_lookup = cls; struct RECLAIM_TICKETS_ConsumeHandle *cth = parallel_lookup->handle; struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *attr_le; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Parallel lookup finished (count=%u)\n", - rd_count); - GNUNET_CONTAINER_DLL_remove (cth->parallel_lookups_head, - cth->parallel_lookups_tail, - parallel_lookup); - GNUNET_free (parallel_lookup->label); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Parallel lookup finished (count=%u)\n", + rd_count); + + GNUNET_CONTAINER_DLL_remove(cth->parallel_lookups_head, + cth->parallel_lookups_tail, + parallel_lookup); + GNUNET_free(parallel_lookup->label); - GNUNET_STATISTICS_update (stats, - "attribute_lookup_time_total", - GNUNET_TIME_absolute_get_duration ( - parallel_lookup->lookup_start_time) - .rel_value_us, - GNUNET_YES); - GNUNET_STATISTICS_update (stats, "attribute_lookups_count", 1, GNUNET_YES); + GNUNET_STATISTICS_update(stats, + "attribute_lookup_time_total", + GNUNET_TIME_absolute_get_duration( + parallel_lookup->lookup_start_time) + .rel_value_us, + GNUNET_YES); + GNUNET_STATISTICS_update(stats, "attribute_lookups_count", 1, GNUNET_YES); - GNUNET_free (parallel_lookup); + GNUNET_free(parallel_lookup); if (1 != rd_count) - GNUNET_break (0); // FIXME: We should never find this. + GNUNET_break(0); // FIXME: We should never find this. if (rd->record_type == GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR) - { - attr_le = GNUNET_new (struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry); - attr_le->claim = - GNUNET_RECLAIM_ATTRIBUTE_deserialize (rd->data, rd->data_size); - GNUNET_CONTAINER_DLL_insert (cth->attrs->list_head, - cth->attrs->list_tail, - attr_le); - } + { + attr_le = GNUNET_new(struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry); + attr_le->claim = + GNUNET_RECLAIM_ATTRIBUTE_deserialize(rd->data, rd->data_size); + GNUNET_CONTAINER_DLL_insert(cth->attrs->list_head, + cth->attrs->list_tail, + attr_le); + } if (NULL != cth->parallel_lookups_head) return; // Wait for more /* Else we are done */ - cth->cb (cth->cb_cls, &cth->ticket.identity, cth->attrs, GNUNET_OK, NULL); - cleanup_cth (cth); + cth->cb(cth->cb_cls, &cth->ticket.identity, cth->attrs, GNUNET_OK, NULL); + cleanup_cth(cth); } @@ -996,7 +1003,7 @@ process_parallel_lookup_result (void *cls, * @param cls handle to the operation */ static void -abort_parallel_lookups (void *cls) +abort_parallel_lookups(void *cls) { struct RECLAIM_TICKETS_ConsumeHandle *cth = cls; struct ParallelLookup *lu; @@ -1004,17 +1011,17 @@ abort_parallel_lookups (void *cls) cth->kill_task = NULL; for (lu = cth->parallel_lookups_head; NULL != lu;) - { - GNUNET_GNS_lookup_cancel (lu->lookup_request); - GNUNET_free (lu->label); - tmp = lu->next; - GNUNET_CONTAINER_DLL_remove (cth->parallel_lookups_head, - cth->parallel_lookups_tail, - lu); - GNUNET_free (lu); - lu = tmp; - } - cth->cb (cth->cb_cls, NULL, NULL, GNUNET_SYSERR, "Aborted"); + { + GNUNET_GNS_lookup_cancel(lu->lookup_request); + GNUNET_free(lu->label); + tmp = lu->next; + GNUNET_CONTAINER_DLL_remove(cth->parallel_lookups_head, + cth->parallel_lookups_tail, + lu); + GNUNET_free(lu); + lu = tmp; + } + cth->cb(cth->cb_cls, NULL, NULL, GNUNET_SYSERR, "Aborted"); } @@ -1028,9 +1035,9 @@ abort_parallel_lookups (void *cls) * @param rd record set */ static void -lookup_authz_cb (void *cls, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +lookup_authz_cb(void *cls, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct RECLAIM_TICKETS_ConsumeHandle *cth = cls; struct ParallelLookup *parallel_lookup; @@ -1038,56 +1045,56 @@ lookup_authz_cb (void *cls, cth->lookup_request = NULL; - GNUNET_STATISTICS_update (stats, - "reclaim_authz_lookup_time_total", - GNUNET_TIME_absolute_get_duration ( - cth->lookup_start_time) - .rel_value_us, - GNUNET_YES); - GNUNET_STATISTICS_update (stats, - "reclaim_authz_lookups_count", - 1, - GNUNET_YES); + GNUNET_STATISTICS_update(stats, + "reclaim_authz_lookup_time_total", + GNUNET_TIME_absolute_get_duration( + cth->lookup_start_time) + .rel_value_us, + GNUNET_YES); + GNUNET_STATISTICS_update(stats, + "reclaim_authz_lookups_count", + 1, + GNUNET_YES); for (int i = 0; i < rd_count; i++) - { - if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF != rd[i].record_type) - continue; - lbl = GNUNET_STRINGS_data_to_string_alloc (rd[i].data, rd[i].data_size); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Attribute ref found %s\n", lbl); - parallel_lookup = GNUNET_new (struct ParallelLookup); - parallel_lookup->handle = cth; - parallel_lookup->label = lbl; - parallel_lookup->lookup_start_time = GNUNET_TIME_absolute_get (); - parallel_lookup->lookup_request = - GNUNET_GNS_lookup (gns, - lbl, - &cth->ticket.identity, - GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR, - GNUNET_GNS_LO_DEFAULT, - &process_parallel_lookup_result, - parallel_lookup); - GNUNET_CONTAINER_DLL_insert (cth->parallel_lookups_head, - cth->parallel_lookups_tail, - parallel_lookup); - } + { + if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF != rd[i].record_type) + continue; + lbl = GNUNET_STRINGS_data_to_string_alloc(rd[i].data, rd[i].data_size); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Attribute ref found %s\n", lbl); + parallel_lookup = GNUNET_new(struct ParallelLookup); + parallel_lookup->handle = cth; + parallel_lookup->label = lbl; + parallel_lookup->lookup_start_time = GNUNET_TIME_absolute_get(); + parallel_lookup->lookup_request = + GNUNET_GNS_lookup(gns, + lbl, + &cth->ticket.identity, + GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR, + GNUNET_GNS_LO_DEFAULT, + &process_parallel_lookup_result, + parallel_lookup); + GNUNET_CONTAINER_DLL_insert(cth->parallel_lookups_head, + cth->parallel_lookups_tail, + parallel_lookup); + } /** * We started lookups. Add a timeout task. * FIXME: Really needed here? */ if (NULL != cth->parallel_lookups_head) - { - cth->kill_task = GNUNET_SCHEDULER_add_delayed ( - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 3), - &abort_parallel_lookups, - cth); - return; - } + { + cth->kill_task = GNUNET_SCHEDULER_add_delayed( + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 3), + &abort_parallel_lookups, + cth); + return; + } /** * No references found, return empty attribute list */ - cth->cb (cth->cb_cls, &cth->ticket.identity, cth->attrs, GNUNET_OK, NULL); - cleanup_cth (cth); + cth->cb(cth->cb_cls, &cth->ticket.identity, cth->attrs, GNUNET_OK, NULL); + cleanup_cth(cth); } @@ -1103,36 +1110,37 @@ lookup_authz_cb (void *cls, * @return handle to the operation */ struct RECLAIM_TICKETS_ConsumeHandle * -RECLAIM_TICKETS_consume (const struct GNUNET_CRYPTO_EcdsaPrivateKey *id, - const struct GNUNET_RECLAIM_Ticket *ticket, - RECLAIM_TICKETS_ConsumeCallback cb, - void *cb_cls) +RECLAIM_TICKETS_consume(const struct GNUNET_CRYPTO_EcdsaPrivateKey *id, + const struct GNUNET_RECLAIM_Ticket *ticket, + RECLAIM_TICKETS_ConsumeCallback cb, + void *cb_cls) { struct RECLAIM_TICKETS_ConsumeHandle *cth; char *label; - cth = GNUNET_new (struct RECLAIM_TICKETS_ConsumeHandle); + + cth = GNUNET_new(struct RECLAIM_TICKETS_ConsumeHandle); cth->identity = *id; - GNUNET_CRYPTO_ecdsa_key_get_public (&cth->identity, &cth->identity_pub); - cth->attrs = GNUNET_new (struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList); + GNUNET_CRYPTO_ecdsa_key_get_public(&cth->identity, &cth->identity_pub); + cth->attrs = GNUNET_new(struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList); cth->ticket = *ticket; cth->cb = cb; cth->cb_cls = cb_cls; label = - GNUNET_STRINGS_data_to_string_alloc (&cth->ticket.rnd, sizeof (uint64_t)); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Looking for AuthZ info under %s\n", - label); - cth->lookup_start_time = GNUNET_TIME_absolute_get (); + GNUNET_STRINGS_data_to_string_alloc(&cth->ticket.rnd, sizeof(uint64_t)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Looking for AuthZ info under %s\n", + label); + cth->lookup_start_time = GNUNET_TIME_absolute_get(); cth->lookup_request = - GNUNET_GNS_lookup (gns, - label, - &cth->ticket.identity, - GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF, - GNUNET_GNS_LO_DEFAULT, - &lookup_authz_cb, - cth); - GNUNET_free (label); + GNUNET_GNS_lookup(gns, + label, + &cth->ticket.identity, + GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF, + GNUNET_GNS_LO_DEFAULT, + &lookup_authz_cb, + cth); + GNUNET_free(label); return cth; } @@ -1143,27 +1151,27 @@ RECLAIM_TICKETS_consume (const struct GNUNET_CRYPTO_EcdsaPrivateKey *id, * @param cth the operation to cancel */ void -RECLAIM_TICKETS_consume_cancel (struct RECLAIM_TICKETS_ConsumeHandle *cth) +RECLAIM_TICKETS_consume_cancel(struct RECLAIM_TICKETS_ConsumeHandle *cth) { - cleanup_cth (cth); + cleanup_cth(cth); return; } /******************************* - * Ticket issue - *******************************/ +* Ticket issue +*******************************/ /** * Cleanup ticket consume handle * @param handle the handle to clean up */ static void -cleanup_issue_handle (struct TicketIssueHandle *handle) +cleanup_issue_handle(struct TicketIssueHandle *handle) { if (NULL != handle->ns_qe) - GNUNET_NAMESTORE_cancel (handle->ns_qe); - GNUNET_free (handle); + GNUNET_NAMESTORE_cancel(handle->ns_qe); + GNUNET_free(handle); } @@ -1176,21 +1184,21 @@ cleanup_issue_handle (struct TicketIssueHandle *handle) * @param emsg error message (or NULL on success) */ static void -store_ticket_issue_cont (void *cls, int32_t success, const char *emsg) +store_ticket_issue_cont(void *cls, int32_t success, const char *emsg) { struct TicketIssueHandle *handle = cls; handle->ns_qe = NULL; if (GNUNET_SYSERR == success) - { - handle->cb (handle->cb_cls, - &handle->ticket, - GNUNET_SYSERR, - "Error storing AuthZ ticket in GNS"); - return; - } - handle->cb (handle->cb_cls, &handle->ticket, GNUNET_OK, NULL); - cleanup_issue_handle (handle); + { + handle->cb(handle->cb_cls, + &handle->ticket, + GNUNET_SYSERR, + "Error storing AuthZ ticket in GNS"); + return; + } + handle->cb(handle->cb_cls, &handle->ticket, GNUNET_OK, NULL); + cleanup_issue_handle(handle); } @@ -1202,7 +1210,7 @@ store_ticket_issue_cont (void *cls, int32_t success, const char *emsg) * @param ih handle to the operation containing relevant metadata */ static void -issue_ticket (struct TicketIssueHandle *ih) +issue_ticket(struct TicketIssueHandle *ih) { struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le; struct GNUNET_GNSRECORD_Data *attrs_record; @@ -1214,45 +1222,45 @@ issue_ticket (struct TicketIssueHandle *ih) list_len++; attrs_record = - GNUNET_malloc (list_len * sizeof (struct GNUNET_GNSRECORD_Data)); + GNUNET_malloc(list_len * sizeof(struct GNUNET_GNSRECORD_Data)); i = 0; for (le = ih->attrs->list_head; NULL != le; le = le->next) - { - attrs_record[i].data = &le->claim->id; - attrs_record[i].data_size = sizeof (le->claim->id); - /** - * FIXME: Should this be the attribute expiration time or ticket - * refresh interval? Probably min(attrs.expiration) - */ - attrs_record[i].expiration_time = ticket_refresh_interval.rel_value_us; - attrs_record[i].record_type = GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF; - attrs_record[i].flags = GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION; - i++; - } + { + attrs_record[i].data = &le->claim->id; + attrs_record[i].data_size = sizeof(le->claim->id); + /** + * FIXME: Should this be the attribute expiration time or ticket + * refresh interval? Probably min(attrs.expiration) + */ + attrs_record[i].expiration_time = ticket_refresh_interval.rel_value_us; + attrs_record[i].record_type = GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF; + attrs_record[i].flags = GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION; + i++; + } attrs_record[i].data = &ih->ticket; - attrs_record[i].data_size = sizeof (struct GNUNET_RECLAIM_Ticket); + attrs_record[i].data_size = sizeof(struct GNUNET_RECLAIM_Ticket); attrs_record[i].expiration_time = ticket_refresh_interval.rel_value_us; attrs_record[i].record_type = GNUNET_GNSRECORD_TYPE_RECLAIM_TICKET; attrs_record[i].flags = GNUNET_GNSRECORD_RF_RELATIVE_EXPIRATION | GNUNET_GNSRECORD_RF_PRIVATE; label = - GNUNET_STRINGS_data_to_string_alloc (&ih->ticket.rnd, sizeof (uint64_t)); + GNUNET_STRINGS_data_to_string_alloc(&ih->ticket.rnd, sizeof(uint64_t)); // Publish record - ih->ns_qe = GNUNET_NAMESTORE_records_store (nsh, - &ih->identity, - label, - list_len, - attrs_record, - &store_ticket_issue_cont, - ih); - GNUNET_free (attrs_record); - GNUNET_free (label); + ih->ns_qe = GNUNET_NAMESTORE_records_store(nsh, + &ih->identity, + label, + list_len, + attrs_record, + &store_ticket_issue_cont, + ih); + GNUNET_free(attrs_record); + GNUNET_free(label); } /************************************************* - * Ticket iteration (finding a specific ticket) - *************************************************/ +* Ticket iteration (finding a specific ticket) +*************************************************/ /** @@ -1261,15 +1269,16 @@ issue_ticket (struct TicketIssueHandle *ih) * @param cls handle to the operation */ static void -filter_tickets_error_cb (void *cls) +filter_tickets_error_cb(void *cls) { struct TicketIssueHandle *tih = cls; + tih->ns_it = NULL; - tih->cb (tih->cb_cls, - &tih->ticket, - GNUNET_SYSERR, - "Error storing AuthZ ticket in GNS"); - cleanup_issue_handle (tih); + tih->cb(tih->cb_cls, + &tih->ticket, + GNUNET_SYSERR, + "Error storing AuthZ ticket in GNS"); + cleanup_issue_handle(tih); } @@ -1286,11 +1295,11 @@ filter_tickets_error_cb (void *cls) * @param rd record set */ static void -filter_tickets_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +filter_tickets_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct TicketIssueHandle *tih = cls; struct GNUNET_RECLAIM_Ticket *ticket = NULL; @@ -1298,6 +1307,7 @@ filter_tickets_cb (void *cls, // figure out the number of requested attributes struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le; unsigned int attr_cnt = 0; + for (le = tih->attrs->list_head; NULL != le; le = le->next) attr_cnt++; @@ -1305,53 +1315,53 @@ filter_tickets_cb (void *cls, unsigned int found_attrs_cnt = 0; for (int i = 0; i < rd_count; i++) - { - // found ticket - if (GNUNET_GNSRECORD_TYPE_RECLAIM_TICKET == rd[i].record_type) { - ticket = (struct GNUNET_RECLAIM_Ticket *) rd[i].data; - // cmp audience - if (0 == memcmp (&tih->ticket.audience, - &ticket->audience, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey))) - { - tih->ticket = *ticket; + // found ticket + if (GNUNET_GNSRECORD_TYPE_RECLAIM_TICKET == rd[i].record_type) + { + ticket = (struct GNUNET_RECLAIM_Ticket *)rd[i].data; + // cmp audience + if (0 == memcmp(&tih->ticket.audience, + &ticket->audience, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey))) + { + tih->ticket = *ticket; + continue; + } + ticket = NULL; + } + + // cmp requested attributes with ticket attributes + if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF != rd[i].record_type) continue; - } - ticket = NULL; - } - - // cmp requested attributes with ticket attributes - if (GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF != rd[i].record_type) - continue; - for (le = tih->attrs->list_head; NULL != le; le = le->next) - { - // cmp attr_ref id with requested attr id - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - " %" PRIu64 "\n %" PRIu64 "\n", - *((uint64_t *) rd[i].data), - le->claim->id); - - - if (0 == memcmp (rd[i].data, &le->claim->id, sizeof (uint64_t))) - found_attrs_cnt++; + for (le = tih->attrs->list_head; NULL != le; le = le->next) + { + // cmp attr_ref id with requested attr id + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + " %" PRIu64 "\n %" PRIu64 "\n", + *((uint64_t *)rd[i].data), + le->claim->id); + + + if (0 == memcmp(rd[i].data, &le->claim->id, sizeof(uint64_t))) + found_attrs_cnt++; + } } - } /** * If we found a matching ticket, return that to the caller and * we are done. */ if (attr_cnt == found_attrs_cnt && NULL != ticket) - { - GNUNET_NAMESTORE_zone_iteration_stop (tih->ns_it); - tih->cb (tih->cb_cls, &tih->ticket, GNUNET_OK, NULL); - cleanup_issue_handle (tih); - return; - } + { + GNUNET_NAMESTORE_zone_iteration_stop(tih->ns_it); + tih->cb(tih->cb_cls, &tih->ticket, GNUNET_OK, NULL); + cleanup_issue_handle(tih); + return; + } // ticket not found in current record, checking next record set - GNUNET_NAMESTORE_zone_iterator_next (tih->ns_it, 1); + GNUNET_NAMESTORE_zone_iterator_next(tih->ns_it, 1); } @@ -1363,13 +1373,14 @@ filter_tickets_cb (void *cls, * @param cls handle to the operation */ static void -filter_tickets_finished_cb (void *cls) +filter_tickets_finished_cb(void *cls) { struct TicketIssueHandle *tih = cls; - GNUNET_CRYPTO_ecdsa_key_get_public (&tih->identity, &tih->ticket.identity); + + GNUNET_CRYPTO_ecdsa_key_get_public(&tih->identity, &tih->ticket.identity); tih->ticket.rnd = - GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX); - issue_ticket (tih); + GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX); + issue_ticket(tih); } @@ -1385,36 +1396,37 @@ filter_tickets_finished_cb (void *cls) * FIXME: Return handle?? */ void -RECLAIM_TICKETS_issue (const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, - const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, - const struct GNUNET_CRYPTO_EcdsaPublicKey *audience, - RECLAIM_TICKETS_TicketResult cb, - void *cb_cls) +RECLAIM_TICKETS_issue(const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, + const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, + const struct GNUNET_CRYPTO_EcdsaPublicKey *audience, + RECLAIM_TICKETS_TicketResult cb, + void *cb_cls) { struct TicketIssueHandle *tih; - tih = GNUNET_new (struct TicketIssueHandle); + + tih = GNUNET_new(struct TicketIssueHandle); tih->cb = cb; tih->cb_cls = cb_cls; - tih->attrs = GNUNET_RECLAIM_ATTRIBUTE_list_dup (attrs); + tih->attrs = GNUNET_RECLAIM_ATTRIBUTE_list_dup(attrs); tih->identity = *identity; tih->ticket.audience = *audience; // First check whether the ticket has already been issued tih->ns_it = - GNUNET_NAMESTORE_zone_iteration_start (nsh, - &tih->identity, - &filter_tickets_error_cb, - tih, - &filter_tickets_cb, - tih, - &filter_tickets_finished_cb, - tih); + GNUNET_NAMESTORE_zone_iteration_start(nsh, + &tih->identity, + &filter_tickets_error_cb, + tih, + &filter_tickets_cb, + tih, + &filter_tickets_finished_cb, + tih); } /************************************ - * Ticket iteration - ************************************/ +* Ticket iteration +************************************/ /** * Cleanup ticket iterator @@ -1422,11 +1434,11 @@ RECLAIM_TICKETS_issue (const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, * @param iter handle to the iteration */ static void -cleanup_iter (struct RECLAIM_TICKETS_Iterator *iter) +cleanup_iter(struct RECLAIM_TICKETS_Iterator *iter) { if (NULL != iter->ns_it) - GNUNET_NAMESTORE_zone_iteration_stop (iter->ns_it); - GNUNET_free (iter); + GNUNET_NAMESTORE_zone_iteration_stop(iter->ns_it); + GNUNET_free(iter); } @@ -1442,22 +1454,22 @@ cleanup_iter (struct RECLAIM_TICKETS_Iterator *iter) * @param rd record set containing a ticket */ static void -collect_tickets_cb (void *cls, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, - const char *label, - unsigned int rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +collect_tickets_cb(void *cls, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *zone, + const char *label, + unsigned int rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct RECLAIM_TICKETS_Iterator *iter = cls; for (int i = 0; i < rd_count; i++) - { - if (GNUNET_GNSRECORD_TYPE_RECLAIM_TICKET != rd[i].record_type) - continue; - iter->cb (iter->cb_cls, (struct GNUNET_RECLAIM_Ticket *) rd[i].data); - return; - } - GNUNET_NAMESTORE_zone_iterator_next (iter->ns_it, 1); + { + if (GNUNET_GNSRECORD_TYPE_RECLAIM_TICKET != rd[i].record_type) + continue; + iter->cb(iter->cb_cls, (struct GNUNET_RECLAIM_Ticket *)rd[i].data); + return; + } + GNUNET_NAMESTORE_zone_iterator_next(iter->ns_it, 1); } @@ -1467,12 +1479,13 @@ collect_tickets_cb (void *cls, * @param cls handle to the iteration */ static void -collect_tickets_finished_cb (void *cls) +collect_tickets_finished_cb(void *cls) { struct RECLAIM_TICKETS_Iterator *iter = cls; + iter->ns_it = NULL; - iter->cb (iter->cb_cls, NULL); - cleanup_iter (iter); + iter->cb(iter->cb_cls, NULL); + cleanup_iter(iter); } @@ -1482,12 +1495,13 @@ collect_tickets_finished_cb (void *cls) * @param cls the iteration handle */ static void -collect_tickets_error_cb (void *cls) +collect_tickets_error_cb(void *cls) { struct RECLAIM_TICKETS_Iterator *iter = cls; + iter->ns_it = NULL; - iter->cb (iter->cb_cls, NULL); - cleanup_iter (iter); + iter->cb(iter->cb_cls, NULL); + cleanup_iter(iter); } @@ -1497,9 +1511,9 @@ collect_tickets_error_cb (void *cls) * @param iter the iteration to continue */ void -RECLAIM_TICKETS_iteration_next (struct RECLAIM_TICKETS_Iterator *iter) +RECLAIM_TICKETS_iteration_next(struct RECLAIM_TICKETS_Iterator *iter) { - GNUNET_NAMESTORE_zone_iterator_next (iter->ns_it, 1); + GNUNET_NAMESTORE_zone_iterator_next(iter->ns_it, 1); } @@ -1509,10 +1523,10 @@ RECLAIM_TICKETS_iteration_next (struct RECLAIM_TICKETS_Iterator *iter) * @param iter iteration to cancel */ void -RECLAIM_TICKETS_iteration_stop (struct RECLAIM_TICKETS_Iterator *iter) +RECLAIM_TICKETS_iteration_stop(struct RECLAIM_TICKETS_Iterator *iter) { - GNUNET_NAMESTORE_zone_iteration_stop (iter->ns_it); - cleanup_iter (iter); + GNUNET_NAMESTORE_zone_iteration_stop(iter->ns_it); + cleanup_iter(iter); } @@ -1525,25 +1539,25 @@ RECLAIM_TICKETS_iteration_stop (struct RECLAIM_TICKETS_Iterator *iter) * @return a handle to the iteration */ struct RECLAIM_TICKETS_Iterator * -RECLAIM_TICKETS_iteration_start ( +RECLAIM_TICKETS_iteration_start( const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, RECLAIM_TICKETS_TicketIter cb, void *cb_cls) { struct RECLAIM_TICKETS_Iterator *iter; - iter = GNUNET_new (struct RECLAIM_TICKETS_Iterator); + iter = GNUNET_new(struct RECLAIM_TICKETS_Iterator); iter->cb = cb; iter->cb_cls = cb_cls; iter->ns_it = - GNUNET_NAMESTORE_zone_iteration_start (nsh, - identity, - &collect_tickets_error_cb, - iter, - &collect_tickets_cb, - iter, - &collect_tickets_finished_cb, - iter); + GNUNET_NAMESTORE_zone_iteration_start(nsh, + identity, + &collect_tickets_error_cb, + iter, + &collect_tickets_cb, + iter, + &collect_tickets_finished_cb, + iter); return iter; } @@ -1555,39 +1569,39 @@ RECLAIM_TICKETS_iteration_start ( * @return GNUNET_SYSERR on error */ int -RECLAIM_TICKETS_init (const struct GNUNET_CONFIGURATION_Handle *c) +RECLAIM_TICKETS_init(const struct GNUNET_CONFIGURATION_Handle *c) { // Get ticket expiration time (relative) from config if (GNUNET_OK == - GNUNET_CONFIGURATION_get_value_time (c, - "reclaim", - "TICKET_REFRESH_INTERVAL", - &ticket_refresh_interval)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Configured refresh interval for tickets: %s\n", - GNUNET_STRINGS_relative_time_to_string (ticket_refresh_interval, + GNUNET_CONFIGURATION_get_value_time(c, + "reclaim", + "TICKET_REFRESH_INTERVAL", + &ticket_refresh_interval)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Configured refresh interval for tickets: %s\n", + GNUNET_STRINGS_relative_time_to_string(ticket_refresh_interval, GNUNET_YES)); - } + } else - { - ticket_refresh_interval = DEFAULT_TICKET_REFRESH_INTERVAL; - } + { + ticket_refresh_interval = DEFAULT_TICKET_REFRESH_INTERVAL; + } // Connect to identity and namestore services - nsh = GNUNET_NAMESTORE_connect (c); + nsh = GNUNET_NAMESTORE_connect(c); if (NULL == nsh) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, - "error connecting to namestore"); - return GNUNET_SYSERR; - } - gns = GNUNET_GNS_connect (c); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, + "error connecting to namestore"); + return GNUNET_SYSERR; + } + gns = GNUNET_GNS_connect(c); if (NULL == gns) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "error connecting to gns"); - return GNUNET_SYSERR; - } - stats = GNUNET_STATISTICS_create ("reclaim", c); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "error connecting to gns"); + return GNUNET_SYSERR; + } + stats = GNUNET_STATISTICS_create("reclaim", c); return GNUNET_OK; } @@ -1597,17 +1611,17 @@ RECLAIM_TICKETS_init (const struct GNUNET_CONFIGURATION_Handle *c) * FIXME: cancel all pending operations (gns, ns etc) */ void -RECLAIM_TICKETS_deinit (void) +RECLAIM_TICKETS_deinit(void) { if (NULL != nsh) - GNUNET_NAMESTORE_disconnect (nsh); + GNUNET_NAMESTORE_disconnect(nsh); nsh = NULL; if (NULL != gns) - GNUNET_GNS_disconnect (gns); + GNUNET_GNS_disconnect(gns); gns = NULL; if (NULL != stats) - { - GNUNET_STATISTICS_destroy (stats, GNUNET_NO); - stats = NULL; - } + { + GNUNET_STATISTICS_destroy(stats, GNUNET_NO); + stats = NULL; + } } diff --git a/src/reclaim/gnunet-service-reclaim_tickets.h b/src/reclaim/gnunet-service-reclaim_tickets.h index 05f834b1e..20a7a8e6f 100644 --- a/src/reclaim/gnunet-service-reclaim_tickets.h +++ b/src/reclaim/gnunet-service-reclaim_tickets.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach @@ -63,8 +63,7 @@ struct RECLAIM_TICKETS_RevokeHandle; /** * List of tickets */ -struct TicketRecordsEntry -{ +struct TicketRecordsEntry { /** * DLL */ @@ -162,10 +161,10 @@ typedef void (*RECLAIM_TICKETS_RevokeCallback) (void *cls, int32_t success); * @return handle to the operation */ struct RECLAIM_TICKETS_RevokeHandle * -RECLAIM_TICKETS_revoke (const struct GNUNET_RECLAIM_Ticket *ticket, - const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, - RECLAIM_TICKETS_RevokeCallback cb, - void *cb_cls); +RECLAIM_TICKETS_revoke(const struct GNUNET_RECLAIM_Ticket *ticket, + const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, + RECLAIM_TICKETS_RevokeCallback cb, + void *cb_cls); /** @@ -174,7 +173,7 @@ RECLAIM_TICKETS_revoke (const struct GNUNET_RECLAIM_Ticket *ticket, * @param rh handle to the operation */ void -RECLAIM_TICKETS_revoke_cancel (struct RECLAIM_TICKETS_RevokeHandle *rh); +RECLAIM_TICKETS_revoke_cancel(struct RECLAIM_TICKETS_RevokeHandle *rh); /** @@ -189,10 +188,10 @@ RECLAIM_TICKETS_revoke_cancel (struct RECLAIM_TICKETS_RevokeHandle *rh); * @return handle to the operation */ struct RECLAIM_TICKETS_ConsumeHandle * -RECLAIM_TICKETS_consume (const struct GNUNET_CRYPTO_EcdsaPrivateKey *id, - const struct GNUNET_RECLAIM_Ticket *ticket, - RECLAIM_TICKETS_ConsumeCallback cb, - void *cb_cls); +RECLAIM_TICKETS_consume(const struct GNUNET_CRYPTO_EcdsaPrivateKey *id, + const struct GNUNET_RECLAIM_Ticket *ticket, + RECLAIM_TICKETS_ConsumeCallback cb, + void *cb_cls); /** @@ -201,7 +200,7 @@ RECLAIM_TICKETS_consume (const struct GNUNET_CRYPTO_EcdsaPrivateKey *id, * @param cth the operation to cancel */ void -RECLAIM_TICKETS_consume_cancel (struct RECLAIM_TICKETS_ConsumeHandle *cth); +RECLAIM_TICKETS_consume_cancel(struct RECLAIM_TICKETS_ConsumeHandle *cth); /** @@ -216,11 +215,11 @@ RECLAIM_TICKETS_consume_cancel (struct RECLAIM_TICKETS_ConsumeHandle *cth); * FIXME: Return handle?? */ void -RECLAIM_TICKETS_issue (const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, - const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, - const struct GNUNET_CRYPTO_EcdsaPublicKey *audience, - RECLAIM_TICKETS_TicketResult cb, - void *cb_cls); +RECLAIM_TICKETS_issue(const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, + const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, + const struct GNUNET_CRYPTO_EcdsaPublicKey *audience, + RECLAIM_TICKETS_TicketResult cb, + void *cb_cls); /** @@ -229,7 +228,7 @@ RECLAIM_TICKETS_issue (const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, * @param iter the iteration to continue */ void -RECLAIM_TICKETS_iteration_next (struct RECLAIM_TICKETS_Iterator *iter); +RECLAIM_TICKETS_iteration_next(struct RECLAIM_TICKETS_Iterator *iter); /** @@ -238,7 +237,7 @@ RECLAIM_TICKETS_iteration_next (struct RECLAIM_TICKETS_Iterator *iter); * @param iter iteration to cancel */ void -RECLAIM_TICKETS_iteration_stop (struct RECLAIM_TICKETS_Iterator *iter); +RECLAIM_TICKETS_iteration_stop(struct RECLAIM_TICKETS_Iterator *iter); /** @@ -250,7 +249,7 @@ RECLAIM_TICKETS_iteration_stop (struct RECLAIM_TICKETS_Iterator *iter); * @return a handle to the iteration */ struct RECLAIM_TICKETS_Iterator * -RECLAIM_TICKETS_iteration_start ( +RECLAIM_TICKETS_iteration_start( const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, RECLAIM_TICKETS_TicketIter cb, void *cb_cls); @@ -263,7 +262,7 @@ RECLAIM_TICKETS_iteration_start ( * @return GNUNET_SYSERR on error */ int -RECLAIM_TICKETS_init (const struct GNUNET_CONFIGURATION_Handle *c); +RECLAIM_TICKETS_init(const struct GNUNET_CONFIGURATION_Handle *c); /** @@ -271,6 +270,6 @@ RECLAIM_TICKETS_init (const struct GNUNET_CONFIGURATION_Handle *c); * FIXME: cancel all pending operations (gns, ns etc) */ void -RECLAIM_TICKETS_deinit (void); +RECLAIM_TICKETS_deinit(void); #endif diff --git a/src/reclaim/json_reclaim.c b/src/reclaim/json_reclaim.c index 557caafe2..a98dec717 100644 --- a/src/reclaim/json_reclaim.c +++ b/src/reclaim/json_reclaim.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @file rest-plugins/json_reclaim.c @@ -41,7 +41,7 @@ * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_attr (void *cls, json_t *root, struct GNUNET_JSON_Specification *spec) +parse_attr(void *cls, json_t *root, struct GNUNET_JSON_Specification *spec) { struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr; const char *name_str = NULL; @@ -53,52 +53,52 @@ parse_attr (void *cls, json_t *root, struct GNUNET_JSON_Specification *spec) uint32_t type; size_t data_size; - GNUNET_assert (NULL != root); + GNUNET_assert(NULL != root); - if (! json_is_object (root)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error json is not array nor object!\n"); - return GNUNET_SYSERR; - } + if (!json_is_object(root)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error json is not array nor object!\n"); + return GNUNET_SYSERR; + } // interpret single attribute - unpack_state = json_unpack (root, - "{s:s, s?s, s:s, s:s!}", - "name", - &name_str, - "id", - &id_str, - "type", - &type_str, - "value", - &val_str); + unpack_state = json_unpack(root, + "{s:s, s?s, s:s, s:s!}", + "name", + &name_str, + "id", + &id_str, + "type", + &type_str, + "value", + &val_str); if ((0 != unpack_state) || (NULL == name_str) || (NULL == val_str) || (NULL == type_str)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error json object has a wrong format!\n"); - return GNUNET_SYSERR; - } - type = GNUNET_RECLAIM_ATTRIBUTE_typename_to_number (type_str); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error json object has a wrong format!\n"); + return GNUNET_SYSERR; + } + type = GNUNET_RECLAIM_ATTRIBUTE_typename_to_number(type_str); if (GNUNET_SYSERR == - (GNUNET_RECLAIM_ATTRIBUTE_string_to_value (type, - val_str, - (void **) &data, - &data_size))) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Attribute value invalid!\n"); - return GNUNET_SYSERR; - } - attr = GNUNET_RECLAIM_ATTRIBUTE_claim_new (name_str, type, data, data_size); - if ((NULL == id_str) || (0 == strlen (id_str))) + (GNUNET_RECLAIM_ATTRIBUTE_string_to_value(type, + val_str, + (void **)&data, + &data_size))) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Attribute value invalid!\n"); + return GNUNET_SYSERR; + } + attr = GNUNET_RECLAIM_ATTRIBUTE_claim_new(name_str, type, data, data_size); + if ((NULL == id_str) || (0 == strlen(id_str))) attr->id = 0; else - GNUNET_STRINGS_string_to_data (id_str, - strlen (id_str), - &attr->id, - sizeof (uint64_t)); + GNUNET_STRINGS_string_to_data(id_str, + strlen(id_str), + &attr->id, + sizeof(uint64_t)); - *(struct GNUNET_RECLAIM_ATTRIBUTE_Claim **) spec->ptr = attr; + *(struct GNUNET_RECLAIM_ATTRIBUTE_Claim **)spec->ptr = attr; return GNUNET_OK; } @@ -109,15 +109,16 @@ parse_attr (void *cls, json_t *root, struct GNUNET_JSON_Specification *spec) * @param[out] spec where to free the data */ static void -clean_attr (void *cls, struct GNUNET_JSON_Specification *spec) +clean_attr(void *cls, struct GNUNET_JSON_Specification *spec) { struct GNUNET_RECLAIM_ATTRIBUTE_Claim **attr; - attr = (struct GNUNET_RECLAIM_ATTRIBUTE_Claim **) spec->ptr; + + attr = (struct GNUNET_RECLAIM_ATTRIBUTE_Claim **)spec->ptr; if (NULL != *attr) - { - GNUNET_free (*attr); - *attr = NULL; - } + { + GNUNET_free(*attr); + *attr = NULL; + } } /** @@ -127,15 +128,16 @@ clean_attr (void *cls, struct GNUNET_JSON_Specification *spec) * @return JSON Specification */ struct GNUNET_JSON_Specification -GNUNET_RECLAIM_JSON_spec_claim (struct GNUNET_RECLAIM_ATTRIBUTE_Claim **attr) +GNUNET_RECLAIM_JSON_spec_claim(struct GNUNET_RECLAIM_ATTRIBUTE_Claim **attr) { - struct GNUNET_JSON_Specification ret = {.parser = &parse_attr, - .cleaner = &clean_attr, - .cls = NULL, - .field = NULL, - .ptr = attr, - .ptr_size = 0, - .size_ptr = NULL}; + struct GNUNET_JSON_Specification ret = { .parser = &parse_attr, + .cleaner = &clean_attr, + .cls = NULL, + .field = NULL, + .ptr = attr, + .ptr_size = 0, + .size_ptr = NULL }; + *attr = NULL; return ret; } @@ -148,7 +150,7 @@ GNUNET_RECLAIM_JSON_spec_claim (struct GNUNET_RECLAIM_ATTRIBUTE_Claim **attr) * @return #GNUNET_OK upon successful parsing; #GNUNET_SYSERR upon error */ static int -parse_ticket (void *cls, json_t *root, struct GNUNET_JSON_Specification *spec) +parse_ticket(void *cls, json_t *root, struct GNUNET_JSON_Specification *spec) { struct GNUNET_RECLAIM_Ticket *ticket; const char *rnd_str; @@ -156,63 +158,63 @@ parse_ticket (void *cls, json_t *root, struct GNUNET_JSON_Specification *spec) const char *id_str; int unpack_state; - GNUNET_assert (NULL != root); + GNUNET_assert(NULL != root); - if (! json_is_object (root)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error json is not array nor object!\n"); - return GNUNET_SYSERR; - } + if (!json_is_object(root)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error json is not array nor object!\n"); + return GNUNET_SYSERR; + } // interpret single ticket - unpack_state = json_unpack (root, - "{s:s, s:s, s:s!}", - "rnd", - &rnd_str, - "audience", - &aud_str, - "issuer", - &id_str); + unpack_state = json_unpack(root, + "{s:s, s:s, s:s!}", + "rnd", + &rnd_str, + "audience", + &aud_str, + "issuer", + &id_str); if (0 != unpack_state) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Error json object has a wrong format!\n"); - return GNUNET_SYSERR; - } - ticket = GNUNET_new (struct GNUNET_RECLAIM_Ticket); - if (GNUNET_OK != GNUNET_STRINGS_string_to_data (rnd_str, - strlen (rnd_str), - &ticket->rnd, - sizeof (uint64_t))) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Rnd invalid\n"); - GNUNET_free (ticket); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Error json object has a wrong format!\n"); + return GNUNET_SYSERR; + } + ticket = GNUNET_new(struct GNUNET_RECLAIM_Ticket); + if (GNUNET_OK != GNUNET_STRINGS_string_to_data(rnd_str, + strlen(rnd_str), + &ticket->rnd, + sizeof(uint64_t))) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Rnd invalid\n"); + GNUNET_free(ticket); + return GNUNET_SYSERR; + } if (GNUNET_OK != - GNUNET_STRINGS_string_to_data (id_str, - strlen (id_str), - &ticket->identity, - sizeof ( - struct GNUNET_CRYPTO_EcdsaPublicKey))) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Identity invalid\n"); - GNUNET_free (ticket); - return GNUNET_SYSERR; - } + GNUNET_STRINGS_string_to_data(id_str, + strlen(id_str), + &ticket->identity, + sizeof( + struct GNUNET_CRYPTO_EcdsaPublicKey))) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Identity invalid\n"); + GNUNET_free(ticket); + return GNUNET_SYSERR; + } if (GNUNET_OK != - GNUNET_STRINGS_string_to_data (aud_str, - strlen (aud_str), - &ticket->audience, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey))) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Audience invalid\n"); - GNUNET_free (ticket); - return GNUNET_SYSERR; - } - - *(struct GNUNET_RECLAIM_Ticket **) spec->ptr = ticket; + GNUNET_STRINGS_string_to_data(aud_str, + strlen(aud_str), + &ticket->audience, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey))) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Audience invalid\n"); + GNUNET_free(ticket); + return GNUNET_SYSERR; + } + + *(struct GNUNET_RECLAIM_Ticket **)spec->ptr = ticket; return GNUNET_OK; } @@ -223,15 +225,16 @@ parse_ticket (void *cls, json_t *root, struct GNUNET_JSON_Specification *spec) * @param[out] spec where to free the data */ static void -clean_ticket (void *cls, struct GNUNET_JSON_Specification *spec) +clean_ticket(void *cls, struct GNUNET_JSON_Specification *spec) { struct GNUNET_RECLAIM_Ticket **ticket; - ticket = (struct GNUNET_RECLAIM_Ticket **) spec->ptr; + + ticket = (struct GNUNET_RECLAIM_Ticket **)spec->ptr; if (NULL != *ticket) - { - GNUNET_free (*ticket); - *ticket = NULL; - } + { + GNUNET_free(*ticket); + *ticket = NULL; + } } /** @@ -241,15 +244,16 @@ clean_ticket (void *cls, struct GNUNET_JSON_Specification *spec) * @return JSON Specification */ struct GNUNET_JSON_Specification -GNUNET_RECLAIM_JSON_spec_ticket (struct GNUNET_RECLAIM_Ticket **ticket) +GNUNET_RECLAIM_JSON_spec_ticket(struct GNUNET_RECLAIM_Ticket **ticket) { - struct GNUNET_JSON_Specification ret = {.parser = &parse_ticket, - .cleaner = &clean_ticket, - .cls = NULL, - .field = NULL, - .ptr = ticket, - .ptr_size = 0, - .size_ptr = NULL}; + struct GNUNET_JSON_Specification ret = { .parser = &parse_ticket, + .cleaner = &clean_ticket, + .cls = NULL, + .field = NULL, + .ptr = ticket, + .ptr_size = 0, + .size_ptr = NULL }; + *ticket = NULL; return ret; } diff --git a/src/reclaim/json_reclaim.h b/src/reclaim/json_reclaim.h index 36221ccb4..28db6937e 100644 --- a/src/reclaim/json_reclaim.h +++ b/src/reclaim/json_reclaim.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @file rest-plugins/json_reclaim.h @@ -36,7 +36,7 @@ * @return JSON Specification */ struct GNUNET_JSON_Specification -GNUNET_RECLAIM_JSON_spec_claim (struct GNUNET_RECLAIM_ATTRIBUTE_Claim **attr); +GNUNET_RECLAIM_JSON_spec_claim(struct GNUNET_RECLAIM_ATTRIBUTE_Claim **attr); /** * JSON Specification for Reclaim tickets. @@ -45,4 +45,4 @@ GNUNET_RECLAIM_JSON_spec_claim (struct GNUNET_RECLAIM_ATTRIBUTE_Claim **attr); * @return JSON Specification */ struct GNUNET_JSON_Specification -GNUNET_RECLAIM_JSON_spec_ticket (struct GNUNET_RECLAIM_Ticket **ticket); +GNUNET_RECLAIM_JSON_spec_ticket(struct GNUNET_RECLAIM_Ticket **ticket); diff --git a/src/reclaim/oidc_helper.h b/src/reclaim/oidc_helper.h index 10e43ea27..46bd804e7 100644 --- a/src/reclaim/oidc_helper.h +++ b/src/reclaim/oidc_helper.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @file reclaim/oidc_helper.h @@ -49,12 +49,12 @@ * @return a new base64-encoded JWT string. */ char* -OIDC_id_token_new (const struct GNUNET_CRYPTO_EcdsaPublicKey *aud_key, - const struct GNUNET_CRYPTO_EcdsaPublicKey *sub_key, - const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, - const struct GNUNET_TIME_Relative *expiration_time, - const char *nonce, - const char *secret_key); +OIDC_id_token_new(const struct GNUNET_CRYPTO_EcdsaPublicKey *aud_key, + const struct GNUNET_CRYPTO_EcdsaPublicKey *sub_key, + const struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, + const struct GNUNET_TIME_Relative *expiration_time, + const char *nonce, + const char *secret_key); /** * Builds an OIDC authorization code including @@ -68,11 +68,11 @@ OIDC_id_token_new (const struct GNUNET_CRYPTO_EcdsaPublicKey *aud_key, * @return a new authorization code (caller must free) */ char* -OIDC_build_authz_code (const struct GNUNET_CRYPTO_EcdsaPrivateKey *issuer, - const struct GNUNET_RECLAIM_Ticket *ticket, - struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, - const char *nonce, - const char *code_challenge); +OIDC_build_authz_code(const struct GNUNET_CRYPTO_EcdsaPrivateKey *issuer, + const struct GNUNET_RECLAIM_Ticket *ticket, + struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs, + const char *nonce, + const char *code_challenge); /** * Parse reclaim ticket and nonce from @@ -88,12 +88,12 @@ OIDC_build_authz_code (const struct GNUNET_CRYPTO_EcdsaPrivateKey *issuer, * @return GNUNET_OK if successful, else GNUNET_SYSERR */ int -OIDC_parse_authz_code (const struct GNUNET_CRYPTO_EcdsaPrivateKey *ecdsa_priv, - const char *code, - const char *code_verifier, - struct GNUNET_RECLAIM_Ticket *ticket, - struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList **attrs, - char **nonce); +OIDC_parse_authz_code(const struct GNUNET_CRYPTO_EcdsaPrivateKey *ecdsa_priv, + const char *code, + const char *code_verifier, + struct GNUNET_RECLAIM_Ticket *ticket, + struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList **attrs, + char **nonce); /** * Build a token response for a token request @@ -105,15 +105,15 @@ OIDC_parse_authz_code (const struct GNUNET_CRYPTO_EcdsaPrivateKey *ecdsa_priv, * @param token_response where to store the response */ void -OIDC_build_token_response (const char *access_token, - const char *id_token, - const struct GNUNET_TIME_Relative *expiration_time, - char **token_response); +OIDC_build_token_response(const char *access_token, + const char *id_token, + const struct GNUNET_TIME_Relative *expiration_time, + char **token_response); /** * Generate a new access token */ char* -OIDC_access_token_new (); +OIDC_access_token_new(); #endif diff --git a/src/reclaim/plugin_gnsrecord_reclaim.c b/src/reclaim/plugin_gnsrecord_reclaim.c index 48cdd9811..708142774 100644 --- a/src/reclaim/plugin_gnsrecord_reclaim.c +++ b/src/reclaim/plugin_gnsrecord_reclaim.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file reclaim/plugin_gnsrecord_reclaim.c @@ -40,21 +40,25 @@ * @return NULL on error, otherwise human-readable representation of the value */ static char * -value_to_string (void *cls, uint32_t type, const void *data, size_t data_size) +value_to_string(void *cls, uint32_t type, const void *data, size_t data_size) { - switch (type) { - case GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR: - return GNUNET_STRINGS_data_to_string_alloc (data, data_size); - case GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_REDIRECT: - case GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_CLIENT: - return GNUNET_strndup (data, data_size); - case GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF: - case GNUNET_GNSRECORD_TYPE_RECLAIM_TICKET: - case GNUNET_GNSRECORD_TYPE_RECLAIM_MASTER: - return GNUNET_STRINGS_data_to_string_alloc (data, data_size); - default: - return NULL; - } + switch (type) + { + case GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR: + return GNUNET_STRINGS_data_to_string_alloc(data, data_size); + + case GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_REDIRECT: + case GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_CLIENT: + return GNUNET_strndup(data, data_size); + + case GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF: + case GNUNET_GNSRECORD_TYPE_RECLAIM_TICKET: + case GNUNET_GNSRECORD_TYPE_RECLAIM_MASTER: + return GNUNET_STRINGS_data_to_string_alloc(data, data_size); + + default: + return NULL; + } } @@ -70,26 +74,30 @@ value_to_string (void *cls, uint32_t type, const void *data, size_t data_size) * @return #GNUNET_OK on success */ static int -string_to_value (void *cls, uint32_t type, const char *s, void **data, - size_t *data_size) +string_to_value(void *cls, uint32_t type, const char *s, void **data, + size_t *data_size) { if (NULL == s) return GNUNET_SYSERR; - switch (type) { - case GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR: - return GNUNET_STRINGS_string_to_data (s, strlen (s), *data, *data_size); - case GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_REDIRECT: - case GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_CLIENT: - *data = GNUNET_strdup (s); - *data_size = strlen (s); - return GNUNET_OK; - case GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF: - case GNUNET_GNSRECORD_TYPE_RECLAIM_MASTER: - case GNUNET_GNSRECORD_TYPE_RECLAIM_TICKET: - return GNUNET_STRINGS_string_to_data (s, strlen (s), *data, *data_size); - default: - return GNUNET_SYSERR; - } + switch (type) + { + case GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR: + return GNUNET_STRINGS_string_to_data(s, strlen(s), *data, *data_size); + + case GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_REDIRECT: + case GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_CLIENT: + *data = GNUNET_strdup(s); + *data_size = strlen(s); + return GNUNET_OK; + + case GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF: + case GNUNET_GNSRECORD_TYPE_RECLAIM_MASTER: + case GNUNET_GNSRECORD_TYPE_RECLAIM_TICKET: + return GNUNET_STRINGS_string_to_data(s, strlen(s), *data, *data_size); + + default: + return GNUNET_SYSERR; + } } @@ -101,13 +109,14 @@ static struct { const char *name; uint32_t number; } name_map[] = { - {"RECLAIM_ATTR", GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR}, - {"RECLAIM_ATTR_REF", GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF}, - {"RECLAIM_MASTER", GNUNET_GNSRECORD_TYPE_RECLAIM_MASTER}, - {"RECLAIM_OIDC_CLIENT", GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_CLIENT}, - {"RECLAIM_OIDC_REDIRECT", GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_REDIRECT}, - {"RECLAIM_TICKET", GNUNET_GNSRECORD_TYPE_RECLAIM_TICKET}, - {NULL, UINT32_MAX}}; + { "RECLAIM_ATTR", GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR }, + { "RECLAIM_ATTR_REF", GNUNET_GNSRECORD_TYPE_RECLAIM_ATTR_REF }, + { "RECLAIM_MASTER", GNUNET_GNSRECORD_TYPE_RECLAIM_MASTER }, + { "RECLAIM_OIDC_CLIENT", GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_CLIENT }, + { "RECLAIM_OIDC_REDIRECT", GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_REDIRECT }, + { "RECLAIM_TICKET", GNUNET_GNSRECORD_TYPE_RECLAIM_TICKET }, + { NULL, UINT32_MAX } +}; /** @@ -118,13 +127,13 @@ static struct { * @return corresponding number, UINT32_MAX on error */ static uint32_t -typename_to_number (void *cls, const char *dns_typename) +typename_to_number(void *cls, const char *dns_typename) { unsigned int i; i = 0; while ((NULL != name_map[i].name) && - (0 != strcasecmp (dns_typename, name_map[i].name))) + (0 != strcasecmp(dns_typename, name_map[i].name))) i++; return name_map[i].number; } @@ -138,7 +147,7 @@ typename_to_number (void *cls, const char *dns_typename) * @return corresponding typestring, NULL on error */ static const char * -number_to_typename (void *cls, uint32_t type) +number_to_typename(void *cls, uint32_t type) { unsigned int i; @@ -156,11 +165,11 @@ number_to_typename (void *cls, uint32_t type) * @return the exported block API */ void * -libgnunet_plugin_gnsrecord_reclaim_init (void *cls) +libgnunet_plugin_gnsrecord_reclaim_init(void *cls) { struct GNUNET_GNSRECORD_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_GNSRECORD_PluginFunctions); + api = GNUNET_new(struct GNUNET_GNSRECORD_PluginFunctions); api->value_to_string = &value_to_string; api->string_to_value = &string_to_value; api->typename_to_number = &typename_to_number; @@ -176,11 +185,11 @@ libgnunet_plugin_gnsrecord_reclaim_init (void *cls) * @return NULL */ void * -libgnunet_plugin_gnsrecord_reclaim_done (void *cls) +libgnunet_plugin_gnsrecord_reclaim_done(void *cls) { struct GNUNET_GNSRECORD_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/reclaim/plugin_rest_openid_connect.c b/src/reclaim/plugin_rest_openid_connect.c index bf1e950da..3f1dba254 100644 --- a/src/reclaim/plugin_rest_openid_connect.c +++ b/src/reclaim/plugin_rest_openid_connect.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach * @author Philippe Buschmann @@ -218,13 +218,13 @@ /** * OIDC ignored parameter array */ -static char *OIDC_ignored_parameter_array[] = {"display", - "prompt", - "ui_locales", - "response_mode", - "id_token_hint", - "login_hint", - "acr_values"}; +static char *OIDC_ignored_parameter_array[] = { "display", + "prompt", + "ui_locales", + "response_mode", + "id_token_hint", + "login_hint", + "acr_values" }; /** * OIDC Hash map that keeps track of issued cookies @@ -250,16 +250,14 @@ static char *allow_methods; /** * @brief struct returned by the initialization function of the plugin */ -struct Plugin -{ +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; }; /** * OIDC needed variables */ -struct OIDC_Variables -{ +struct OIDC_Variables { /** * The RP client public key */ @@ -324,8 +322,7 @@ struct OIDC_Variables /** * The ego list */ -struct EgoEntry -{ +struct EgoEntry { /** * DLL */ @@ -353,8 +350,7 @@ struct EgoEntry }; -struct RequestHandle -{ +struct RequestHandle { /** * Ego list */ @@ -511,74 +507,75 @@ struct RequestHandle * @param handle Handle to clean up */ static void -cleanup_handle (struct RequestHandle *handle) +cleanup_handle(struct RequestHandle *handle) { struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *claim_entry; struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *claim_tmp; struct EgoEntry *ego_entry; struct EgoEntry *ego_tmp; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); if (NULL != handle->timeout_task) - GNUNET_SCHEDULER_cancel (handle->timeout_task); + GNUNET_SCHEDULER_cancel(handle->timeout_task); if (NULL != handle->identity_handle) - GNUNET_IDENTITY_disconnect (handle->identity_handle); + GNUNET_IDENTITY_disconnect(handle->identity_handle); if (NULL != handle->attr_it) - GNUNET_RECLAIM_get_attributes_stop (handle->attr_it); + GNUNET_RECLAIM_get_attributes_stop(handle->attr_it); if (NULL != handle->ticket_it) - GNUNET_RECLAIM_ticket_iteration_stop (handle->ticket_it); + GNUNET_RECLAIM_ticket_iteration_stop(handle->ticket_it); if (NULL != handle->idp) - GNUNET_RECLAIM_disconnect (handle->idp); - GNUNET_free_non_null (handle->url); - GNUNET_free_non_null (handle->tld); - GNUNET_free_non_null (handle->redirect_prefix); - GNUNET_free_non_null (handle->redirect_suffix); - GNUNET_free_non_null (handle->emsg); - GNUNET_free_non_null (handle->edesc); + GNUNET_RECLAIM_disconnect(handle->idp); + GNUNET_free_non_null(handle->url); + GNUNET_free_non_null(handle->tld); + GNUNET_free_non_null(handle->redirect_prefix); + GNUNET_free_non_null(handle->redirect_suffix); + GNUNET_free_non_null(handle->emsg); + GNUNET_free_non_null(handle->edesc); if (NULL != handle->gns_op) - GNUNET_GNS_lookup_cancel (handle->gns_op); + GNUNET_GNS_lookup_cancel(handle->gns_op); if (NULL != handle->gns_handle) - GNUNET_GNS_disconnect (handle->gns_handle); + GNUNET_GNS_disconnect(handle->gns_handle); if (NULL != handle->namestore_handle) - GNUNET_NAMESTORE_disconnect (handle->namestore_handle); + GNUNET_NAMESTORE_disconnect(handle->namestore_handle); if (NULL != handle->oidc) - { - GNUNET_free_non_null (handle->oidc->client_id); - GNUNET_free_non_null (handle->oidc->login_identity); - GNUNET_free_non_null (handle->oidc->nonce); - GNUNET_free_non_null (handle->oidc->redirect_uri); - GNUNET_free_non_null (handle->oidc->response_type); - GNUNET_free_non_null (handle->oidc->scope); - GNUNET_free_non_null (handle->oidc->state); - json_decref (handle->oidc->response); - GNUNET_free (handle->oidc); - } + { + GNUNET_free_non_null(handle->oidc->client_id); + GNUNET_free_non_null(handle->oidc->login_identity); + GNUNET_free_non_null(handle->oidc->nonce); + GNUNET_free_non_null(handle->oidc->redirect_uri); + GNUNET_free_non_null(handle->oidc->response_type); + GNUNET_free_non_null(handle->oidc->scope); + GNUNET_free_non_null(handle->oidc->state); + json_decref(handle->oidc->response); + GNUNET_free(handle->oidc); + } if (NULL != handle->attr_list) - { - for (claim_entry = handle->attr_list->list_head; NULL != claim_entry;) { - claim_tmp = claim_entry; - claim_entry = claim_entry->next; - GNUNET_free (claim_tmp->claim); - GNUNET_free (claim_tmp); + for (claim_entry = handle->attr_list->list_head; NULL != claim_entry;) + { + claim_tmp = claim_entry; + claim_entry = claim_entry->next; + GNUNET_free(claim_tmp->claim); + GNUNET_free(claim_tmp); + } + GNUNET_free(handle->attr_list); } - GNUNET_free (handle->attr_list); - } for (ego_entry = handle->ego_head; NULL != ego_entry;) - { - ego_tmp = ego_entry; - ego_entry = ego_entry->next; - GNUNET_free (ego_tmp->identifier); - GNUNET_free (ego_tmp->keystring); - GNUNET_free (ego_tmp); - } - GNUNET_free (handle); + { + ego_tmp = ego_entry; + ego_entry = ego_entry->next; + GNUNET_free(ego_tmp->identifier); + GNUNET_free(ego_tmp->keystring); + GNUNET_free(ego_tmp); + } + GNUNET_free(handle); } static void -cleanup_handle_delayed (void *cls) +cleanup_handle_delayed(void *cls) { - cleanup_handle (cls); + cleanup_handle(cls); } @@ -588,30 +585,30 @@ cleanup_handle_delayed (void *cls) * @param cls the `struct RequestHandle` */ static void -do_error (void *cls) +do_error(void *cls) { struct RequestHandle *handle = cls; struct MHD_Response *resp; char *json_error; - GNUNET_asprintf (&json_error, - "{ \"error\" : \"%s\", \"error_description\" : \"%s\"%s%s%s}", - handle->emsg, - (NULL != handle->edesc) ? handle->edesc : "", - (NULL != handle->oidc->state) ? ", \"state\":\"" : "", - (NULL != handle->oidc->state) ? handle->oidc->state : "", - (NULL != handle->oidc->state) ? "\"" : ""); + GNUNET_asprintf(&json_error, + "{ \"error\" : \"%s\", \"error_description\" : \"%s\"%s%s%s}", + handle->emsg, + (NULL != handle->edesc) ? handle->edesc : "", + (NULL != handle->oidc->state) ? ", \"state\":\"" : "", + (NULL != handle->oidc->state) ? handle->oidc->state : "", + (NULL != handle->oidc->state) ? "\"" : ""); if (0 == handle->response_code) handle->response_code = MHD_HTTP_BAD_REQUEST; - resp = GNUNET_REST_create_response (json_error); + resp = GNUNET_REST_create_response(json_error); if (MHD_HTTP_UNAUTHORIZED == handle->response_code) - MHD_add_response_header (resp, MHD_HTTP_HEADER_WWW_AUTHENTICATE, "Basic"); - MHD_add_response_header (resp, - MHD_HTTP_HEADER_CONTENT_TYPE, - "application/json"); - handle->proc (handle->proc_cls, resp, handle->response_code); - GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle); - GNUNET_free (json_error); + MHD_add_response_header(resp, MHD_HTTP_HEADER_WWW_AUTHENTICATE, "Basic"); + MHD_add_response_header(resp, + MHD_HTTP_HEADER_CONTENT_TYPE, + "application/json"); + handle->proc(handle->proc_cls, resp, handle->response_code); + GNUNET_SCHEDULER_add_now(&cleanup_handle_delayed, handle); + GNUNET_free(json_error); } @@ -622,21 +619,21 @@ do_error (void *cls) * @param cls the `struct RequestHandle` */ static void -do_userinfo_error (void *cls) +do_userinfo_error(void *cls) { struct RequestHandle *handle = cls; struct MHD_Response *resp; char *error; - GNUNET_asprintf (&error, - "error=\"%s\", error_description=\"%s\"", - handle->emsg, - (NULL != handle->edesc) ? handle->edesc : ""); - resp = GNUNET_REST_create_response (""); - MHD_add_response_header (resp, MHD_HTTP_HEADER_WWW_AUTHENTICATE, "Bearer"); - handle->proc (handle->proc_cls, resp, handle->response_code); - GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle); - GNUNET_free (error); + GNUNET_asprintf(&error, + "error=\"%s\", error_description=\"%s\"", + handle->emsg, + (NULL != handle->edesc) ? handle->edesc : ""); + resp = GNUNET_REST_create_response(""); + MHD_add_response_header(resp, MHD_HTTP_HEADER_WWW_AUTHENTICATE, "Bearer"); + handle->proc(handle->proc_cls, resp, handle->response_code); + GNUNET_SCHEDULER_add_now(&cleanup_handle_delayed, handle); + GNUNET_free(error); } @@ -646,23 +643,24 @@ do_userinfo_error (void *cls) * @param cls the `struct RequestHandle` */ static void -do_redirect_error (void *cls) +do_redirect_error(void *cls) { struct RequestHandle *handle = cls; struct MHD_Response *resp; char *redirect; - GNUNET_asprintf (&redirect, - "%s?error=%s&error_description=%s%s%s", - handle->oidc->redirect_uri, - handle->emsg, - handle->edesc, - (NULL != handle->oidc->state) ? "&state=" : "", - (NULL != handle->oidc->state) ? handle->oidc->state : ""); - resp = GNUNET_REST_create_response (""); - MHD_add_response_header (resp, "Location", redirect); - handle->proc (handle->proc_cls, resp, MHD_HTTP_FOUND); - GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle); - GNUNET_free (redirect); + + GNUNET_asprintf(&redirect, + "%s?error=%s&error_description=%s%s%s", + handle->oidc->redirect_uri, + handle->emsg, + handle->edesc, + (NULL != handle->oidc->state) ? "&state=" : "", + (NULL != handle->oidc->state) ? handle->oidc->state : ""); + resp = GNUNET_REST_create_response(""); + MHD_add_response_header(resp, "Location", redirect); + handle->proc(handle->proc_cls, resp, MHD_HTTP_FOUND); + GNUNET_SCHEDULER_add_now(&cleanup_handle_delayed, handle); + GNUNET_free(redirect); } /** @@ -671,12 +669,12 @@ do_redirect_error (void *cls) * @param cls the `struct RequestHandle` */ static void -do_timeout (void *cls) +do_timeout(void *cls) { struct RequestHandle *handle = cls; handle->timeout_task = NULL; - do_error (handle); + do_error(handle); } /** @@ -685,18 +683,18 @@ do_timeout (void *cls) * @param cls the request handle */ static void -return_userinfo_response (void *cls) +return_userinfo_response(void *cls) { char *result_str; struct RequestHandle *handle = cls; struct MHD_Response *resp; - result_str = json_dumps (handle->oidc->response, 0); + result_str = json_dumps(handle->oidc->response, 0); - resp = GNUNET_REST_create_response (result_str); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_free (result_str); - cleanup_handle (handle); + resp = GNUNET_REST_create_response(result_str); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_free(result_str); + cleanup_handle(handle); } @@ -708,18 +706,18 @@ return_userinfo_response (void *cls) * @param cls the RequestHandle */ static void -options_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +options_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct MHD_Response *resp; struct RequestHandle *handle = cls; // For now, independent of path return all options - resp = GNUNET_REST_create_response (NULL); - MHD_add_response_header (resp, "Access-Control-Allow-Methods", allow_methods); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - cleanup_handle (handle); + resp = GNUNET_REST_create_response(NULL); + MHD_add_response_header(resp, "Access-Control-Allow-Methods", allow_methods); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + cleanup_handle(handle); return; } @@ -728,7 +726,7 @@ options_cont (struct GNUNET_REST_RequestHandle *con_handle, * Interprets cookie header and pass its identity keystring to handle */ static void -cookie_identity_interpretation (struct RequestHandle *handle) +cookie_identity_interpretation(struct RequestHandle *handle) { struct GNUNET_HashCode cache_key; char *cookies; @@ -739,142 +737,143 @@ cookie_identity_interpretation (struct RequestHandle *handle) char *value; // gets identity of login try with cookie - GNUNET_CRYPTO_hash (OIDC_COOKIE_HEADER_KEY, - strlen (OIDC_COOKIE_HEADER_KEY), - &cache_key); - if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle - ->header_param_map, - &cache_key)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No cookie found\n"); - return; - } + GNUNET_CRYPTO_hash(OIDC_COOKIE_HEADER_KEY, + strlen(OIDC_COOKIE_HEADER_KEY), + &cache_key); + if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(handle->rest_handle + ->header_param_map, + &cache_key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "No cookie found\n"); + return; + } // splits cookies and find 'Identity' cookie tmp_cookies = - GNUNET_CONTAINER_multihashmap_get (handle->rest_handle->header_param_map, - &cache_key); - cookies = GNUNET_strdup (tmp_cookies); - token = strtok (cookies, delimiter); + GNUNET_CONTAINER_multihashmap_get(handle->rest_handle->header_param_map, + &cache_key); + cookies = GNUNET_strdup(tmp_cookies); + token = strtok(cookies, delimiter); handle->oidc->user_cancelled = GNUNET_NO; handle->oidc->login_identity = NULL; if (NULL == token) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse cookie: %s\n", - cookies); - GNUNET_free (cookies); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse cookie: %s\n", + cookies); + GNUNET_free(cookies); + return; + } while (NULL != token) - { - if (0 == strcmp (token, OIDC_COOKIE_HEADER_ACCESS_DENIED)) { - handle->oidc->user_cancelled = GNUNET_YES; - GNUNET_free (cookies); - return; + if (0 == strcmp(token, OIDC_COOKIE_HEADER_ACCESS_DENIED)) + { + handle->oidc->user_cancelled = GNUNET_YES; + GNUNET_free(cookies); + return; + } + if (NULL != strstr(token, OIDC_COOKIE_HEADER_INFORMATION_KEY)) + break; + token = strtok(NULL, delimiter); } - if (NULL != strstr (token, OIDC_COOKIE_HEADER_INFORMATION_KEY)) - break; - token = strtok (NULL, delimiter); - } if (NULL == token) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "No cookie value to process: %s\n", - cookies); - GNUNET_free (cookies); - return; - } - GNUNET_CRYPTO_hash (token, strlen (token), &cache_key); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "No cookie value to process: %s\n", + cookies); + GNUNET_free(cookies); + return; + } + GNUNET_CRYPTO_hash(token, strlen(token), &cache_key); if (GNUNET_NO == - GNUNET_CONTAINER_multihashmap_contains (OIDC_cookie_jar_map, &cache_key)) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_WARNING, - "Found cookie `%s', but no corresponding expiration entry present...\n", - token); - GNUNET_free (cookies); - return; - } + GNUNET_CONTAINER_multihashmap_contains(OIDC_cookie_jar_map, &cache_key)) + { + GNUNET_log( + GNUNET_ERROR_TYPE_WARNING, + "Found cookie `%s', but no corresponding expiration entry present...\n", + token); + GNUNET_free(cookies); + return; + } relog_time = - GNUNET_CONTAINER_multihashmap_get (OIDC_cookie_jar_map, &cache_key); - current_time = GNUNET_TIME_absolute_get (); + GNUNET_CONTAINER_multihashmap_get(OIDC_cookie_jar_map, &cache_key); + current_time = GNUNET_TIME_absolute_get(); // 30 min after old login -> redirect to login if (current_time.abs_value_us > relog_time->abs_value_us) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Found cookie `%s', but it is expired.\n", - token); - GNUNET_free (cookies); - return; - } - value = strtok (token, OIDC_COOKIE_HEADER_INFORMATION_KEY); - GNUNET_assert (NULL != value); - handle->oidc->login_identity = GNUNET_strdup (value); - GNUNET_free (cookies); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Found cookie `%s', but it is expired.\n", + token); + GNUNET_free(cookies); + return; + } + value = strtok(token, OIDC_COOKIE_HEADER_INFORMATION_KEY); + GNUNET_assert(NULL != value); + handle->oidc->login_identity = GNUNET_strdup(value); + GNUNET_free(cookies); } /** * Redirects to login page stored in configuration file */ static void -login_redirect (void *cls) +login_redirect(void *cls) { char *login_base_url; char *new_redirect; struct MHD_Response *resp; struct RequestHandle *handle = cls; - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, - "reclaim-rest-plugin", - "address", - &login_base_url)) - { - GNUNET_asprintf (&new_redirect, - "%s?%s=%s&%s=%s&%s=%s&%s=%s&%s=%s&%s=%s&%s=%s", - login_base_url, - OIDC_RESPONSE_TYPE_KEY, - handle->oidc->response_type, - OIDC_CLIENT_ID_KEY, - handle->oidc->client_id, - OIDC_REDIRECT_URI_KEY, - handle->oidc->redirect_uri, - OIDC_SCOPE_KEY, - handle->oidc->scope, - OIDC_STATE_KEY, - (NULL != handle->oidc->state) ? handle->oidc->state : "", - OIDC_CODE_CHALLENGE_KEY, - (NULL != handle->oidc->code_challenge) ? handle->oidc->code_challenge : "", - OIDC_NONCE_KEY, - (NULL != handle->oidc->nonce) ? handle->oidc->nonce : ""); - resp = GNUNET_REST_create_response (""); - MHD_add_response_header (resp, "Location", new_redirect); - GNUNET_free (login_base_url); - } + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, + "reclaim-rest-plugin", + "address", + &login_base_url)) + { + GNUNET_asprintf(&new_redirect, + "%s?%s=%s&%s=%s&%s=%s&%s=%s&%s=%s&%s=%s&%s=%s", + login_base_url, + OIDC_RESPONSE_TYPE_KEY, + handle->oidc->response_type, + OIDC_CLIENT_ID_KEY, + handle->oidc->client_id, + OIDC_REDIRECT_URI_KEY, + handle->oidc->redirect_uri, + OIDC_SCOPE_KEY, + handle->oidc->scope, + OIDC_STATE_KEY, + (NULL != handle->oidc->state) ? handle->oidc->state : "", + OIDC_CODE_CHALLENGE_KEY, + (NULL != handle->oidc->code_challenge) ? handle->oidc->code_challenge : "", + OIDC_NONCE_KEY, + (NULL != handle->oidc->nonce) ? handle->oidc->nonce : ""); + resp = GNUNET_REST_create_response(""); + MHD_add_response_header(resp, "Location", new_redirect); + GNUNET_free(login_base_url); + } else - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR); - handle->edesc = GNUNET_strdup ("gnunet configuration failed"); - handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - handle->proc (handle->proc_cls, resp, MHD_HTTP_FOUND); - GNUNET_free (new_redirect); - GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle); + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_SERVER_ERROR); + handle->edesc = GNUNET_strdup("gnunet configuration failed"); + handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + handle->proc(handle->proc_cls, resp, MHD_HTTP_FOUND); + GNUNET_free(new_redirect); + GNUNET_SCHEDULER_add_now(&cleanup_handle_delayed, handle); } /** * Does internal server error when iteration failed. */ static void -oidc_iteration_error (void *cls) +oidc_iteration_error(void *cls) { struct RequestHandle *handle = cls; - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR); + + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_SERVER_ERROR); handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; - GNUNET_SCHEDULER_add_now (&do_error, handle); + GNUNET_SCHEDULER_add_now(&do_error, handle); } @@ -883,7 +882,7 @@ oidc_iteration_error (void *cls) * parameter. Otherwise redirects with error */ static void -oidc_ticket_issue_cb (void *cls, const struct GNUNET_RECLAIM_Ticket *ticket) +oidc_ticket_issue_cb(void *cls, const struct GNUNET_RECLAIM_Ticket *ticket) { struct RequestHandle *handle = cls; struct MHD_Response *resp; @@ -893,72 +892,72 @@ oidc_ticket_issue_cb (void *cls, const struct GNUNET_RECLAIM_Ticket *ticket) handle->idp_op = NULL; if (NULL == ticket) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR); - handle->edesc = GNUNET_strdup ("Server cannot generate ticket."); - GNUNET_SCHEDULER_add_now (&do_redirect_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_SERVER_ERROR); + handle->edesc = GNUNET_strdup("Server cannot generate ticket."); + GNUNET_SCHEDULER_add_now(&do_redirect_error, handle); + return; + } handle->ticket = *ticket; ticket_str = - GNUNET_STRINGS_data_to_string_alloc (&handle->ticket, - sizeof (struct GNUNET_RECLAIM_Ticket)); + GNUNET_STRINGS_data_to_string_alloc(&handle->ticket, + sizeof(struct GNUNET_RECLAIM_Ticket)); // TODO change if more attributes are needed (see max_age) - code_string = OIDC_build_authz_code (&handle->priv_key, - &handle->ticket, - handle->attr_list, - handle->oidc->nonce, - handle->oidc->code_challenge); + code_string = OIDC_build_authz_code(&handle->priv_key, + &handle->ticket, + handle->attr_list, + handle->oidc->nonce, + handle->oidc->code_challenge); if ((NULL != handle->redirect_prefix) && (NULL != handle->redirect_suffix) && (NULL != handle->tld)) - { - - GNUNET_asprintf (&redirect_uri, - "%s.%s/%s?%s=%s&state=%s", - handle->redirect_prefix, - handle->tld, - handle->redirect_suffix, - handle->oidc->response_type, - code_string, - handle->oidc->state); - } + { + GNUNET_asprintf(&redirect_uri, + "%s.%s/%s?%s=%s&state=%s", + handle->redirect_prefix, + handle->tld, + handle->redirect_suffix, + handle->oidc->response_type, + code_string, + handle->oidc->state); + } else - { - GNUNET_asprintf (&redirect_uri, - "%s?%s=%s&state=%s", - handle->oidc->redirect_uri, - handle->oidc->response_type, - code_string, - handle->oidc->state); - } - resp = GNUNET_REST_create_response (""); - MHD_add_response_header (resp, "Location", redirect_uri); - handle->proc (handle->proc_cls, resp, MHD_HTTP_FOUND); - GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle); - GNUNET_free (redirect_uri); - GNUNET_free (ticket_str); - GNUNET_free (code_string); + { + GNUNET_asprintf(&redirect_uri, + "%s?%s=%s&state=%s", + handle->oidc->redirect_uri, + handle->oidc->response_type, + code_string, + handle->oidc->state); + } + resp = GNUNET_REST_create_response(""); + MHD_add_response_header(resp, "Location", redirect_uri); + handle->proc(handle->proc_cls, resp, MHD_HTTP_FOUND); + GNUNET_SCHEDULER_add_now(&cleanup_handle_delayed, handle); + GNUNET_free(redirect_uri); + GNUNET_free(ticket_str); + GNUNET_free(code_string); } static void -oidc_collect_finished_cb (void *cls) +oidc_collect_finished_cb(void *cls) { struct RequestHandle *handle = cls; + handle->attr_it = NULL; handle->ticket_it = NULL; if (NULL == handle->attr_list->list_head) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_SCOPE); - handle->edesc = GNUNET_strdup ("The requested scope is not available."); - GNUNET_SCHEDULER_add_now (&do_redirect_error, handle); - return; - } - handle->idp_op = GNUNET_RECLAIM_ticket_issue (handle->idp, - &handle->priv_key, - &handle->oidc->client_pkey, - handle->attr_list, - &oidc_ticket_issue_cb, - handle); + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_SCOPE); + handle->edesc = GNUNET_strdup("The requested scope is not available."); + GNUNET_SCHEDULER_add_now(&do_redirect_error, handle); + return; + } + handle->idp_op = GNUNET_RECLAIM_ticket_issue(handle->idp, + &handle->priv_key, + &handle->oidc->client_pkey, + handle->attr_list, + &oidc_ticket_issue_cb, + handle); } @@ -966,9 +965,9 @@ oidc_collect_finished_cb (void *cls) * Collects all attributes for an ego if in scope parameter */ static void -oidc_attr_collect (void *cls, - const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, - const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) +oidc_attr_collect(void *cls, + const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, + const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) { struct RequestHandle *handle = cls; struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le; @@ -977,38 +976,38 @@ oidc_attr_collect (void *cls, char delimiter[] = " "; if ((NULL == attr->name) || (NULL == attr->data)) - { - GNUNET_RECLAIM_get_attributes_next (handle->attr_it); - return; - } + { + GNUNET_RECLAIM_get_attributes_next(handle->attr_it); + return; + } - scope_variables = GNUNET_strdup (handle->oidc->scope); - scope_variable = strtok (scope_variables, delimiter); + scope_variables = GNUNET_strdup(handle->oidc->scope); + scope_variable = strtok(scope_variables, delimiter); while (NULL != scope_variable) - { - if (0 == strcmp (attr->name, scope_variable)) - break; - scope_variable = strtok (NULL, delimiter); - } + { + if (0 == strcmp(attr->name, scope_variable)) + break; + scope_variable = strtok(NULL, delimiter); + } if (NULL == scope_variable) - { - GNUNET_RECLAIM_get_attributes_next (handle->attr_it); - GNUNET_free (scope_variables); - return; - } - GNUNET_free (scope_variables); - - le = GNUNET_new (struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry); - le->claim = GNUNET_RECLAIM_ATTRIBUTE_claim_new (attr->name, - attr->type, - attr->data, - attr->data_size); + { + GNUNET_RECLAIM_get_attributes_next(handle->attr_it); + GNUNET_free(scope_variables); + return; + } + GNUNET_free(scope_variables); + + le = GNUNET_new(struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry); + le->claim = GNUNET_RECLAIM_ATTRIBUTE_claim_new(attr->name, + attr->type, + attr->data, + attr->data_size); le->claim->id = attr->id; le->claim->version = attr->version; - GNUNET_CONTAINER_DLL_insert (handle->attr_list->list_head, - handle->attr_list->list_tail, - le); - GNUNET_RECLAIM_get_attributes_next (handle->attr_it); + GNUNET_CONTAINER_DLL_insert(handle->attr_list->list_head, + handle->attr_list->list_tail, + le); + GNUNET_RECLAIM_get_attributes_next(handle->attr_it); } @@ -1016,7 +1015,7 @@ oidc_attr_collect (void *cls, * Checks time and cookie and redirects accordingly */ static void -code_redirect (void *cls) +code_redirect(void *cls) { struct RequestHandle *handle = cls; struct GNUNET_TIME_Absolute current_time; @@ -1026,111 +1025,111 @@ code_redirect (void *cls) struct GNUNET_HashCode cache_key; char *identity_cookie; - GNUNET_asprintf (&identity_cookie, - "Identity=%s", - handle->oidc->login_identity); - GNUNET_CRYPTO_hash (identity_cookie, strlen (identity_cookie), &cache_key); - GNUNET_free (identity_cookie); + GNUNET_asprintf(&identity_cookie, + "Identity=%s", + handle->oidc->login_identity); + GNUNET_CRYPTO_hash(identity_cookie, strlen(identity_cookie), &cache_key); + GNUNET_free(identity_cookie); // No login time for identity -> redirect to login if (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_contains (OIDC_cookie_jar_map, &cache_key)) - { - relog_time = - GNUNET_CONTAINER_multihashmap_get (OIDC_cookie_jar_map, &cache_key); - current_time = GNUNET_TIME_absolute_get (); - // 30 min after old login -> redirect to login - if (current_time.abs_value_us <= relog_time->abs_value_us) - { - if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (handle->oidc - ->login_identity, - strlen ( - handle->oidc - ->login_identity), - &pubkey)) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_COOKIE); - handle->edesc = - GNUNET_strdup ("The cookie of a login identity is not valid"); - GNUNET_SCHEDULER_add_now (&do_redirect_error, handle); - return; - } - // iterate over egos and compare their public key - for (handle->ego_entry = handle->ego_head; NULL != handle->ego_entry; - handle->ego_entry = handle->ego_entry->next) - { - GNUNET_IDENTITY_ego_get_public_key (handle->ego_entry->ego, &ego_pkey); - if (0 == GNUNET_memcmp (&ego_pkey, &pubkey)) + GNUNET_CONTAINER_multihashmap_contains(OIDC_cookie_jar_map, &cache_key)) + { + relog_time = + GNUNET_CONTAINER_multihashmap_get(OIDC_cookie_jar_map, &cache_key); + current_time = GNUNET_TIME_absolute_get(); + // 30 min after old login -> redirect to login + if (current_time.abs_value_us <= relog_time->abs_value_us) { - handle->priv_key = - *GNUNET_IDENTITY_ego_get_private_key (handle->ego_entry->ego); - handle->idp = GNUNET_RECLAIM_connect (cfg); - handle->attr_list = - GNUNET_new (struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList); - handle->attr_it = - GNUNET_RECLAIM_get_attributes_start (handle->idp, - &handle->priv_key, - &oidc_iteration_error, - handle, - &oidc_attr_collect, - handle, - &oidc_collect_finished_cb, - handle); + if (GNUNET_OK != + GNUNET_CRYPTO_ecdsa_public_key_from_string(handle->oidc + ->login_identity, + strlen( + handle->oidc + ->login_identity), + &pubkey)) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_COOKIE); + handle->edesc = + GNUNET_strdup("The cookie of a login identity is not valid"); + GNUNET_SCHEDULER_add_now(&do_redirect_error, handle); + return; + } + // iterate over egos and compare their public key + for (handle->ego_entry = handle->ego_head; NULL != handle->ego_entry; + handle->ego_entry = handle->ego_entry->next) + { + GNUNET_IDENTITY_ego_get_public_key(handle->ego_entry->ego, &ego_pkey); + if (0 == GNUNET_memcmp(&ego_pkey, &pubkey)) + { + handle->priv_key = + *GNUNET_IDENTITY_ego_get_private_key(handle->ego_entry->ego); + handle->idp = GNUNET_RECLAIM_connect(cfg); + handle->attr_list = + GNUNET_new(struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList); + handle->attr_it = + GNUNET_RECLAIM_get_attributes_start(handle->idp, + &handle->priv_key, + &oidc_iteration_error, + handle, + &oidc_attr_collect, + handle, + &oidc_collect_finished_cb, + handle); + return; + } + } + GNUNET_SCHEDULER_add_now(&login_redirect, handle); return; } - } - GNUNET_SCHEDULER_add_now (&login_redirect, handle); - return; } - } } static void -build_redirect (void *cls) +build_redirect(void *cls) { struct RequestHandle *handle = cls; struct MHD_Response *resp; char *redirect_uri; if (GNUNET_YES == handle->oidc->user_cancelled) - { - if ((NULL != handle->redirect_prefix) && - (NULL != handle->redirect_suffix) && (NULL != handle->tld)) - { - GNUNET_asprintf (&redirect_uri, - "%s.%s/%s?error=%s&error_description=%s&state=%s", - handle->redirect_prefix, - handle->tld, - handle->redirect_suffix, - "access_denied", - "User denied access", - handle->oidc->state); - } - else - { - GNUNET_asprintf (&redirect_uri, - "%s?error=%s&error_description=%s&state=%s", - handle->oidc->redirect_uri, - "access_denied", - "User denied access", - handle->oidc->state); - } - resp = GNUNET_REST_create_response (""); - MHD_add_response_header (resp, "Location", redirect_uri); - handle->proc (handle->proc_cls, resp, MHD_HTTP_FOUND); - GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle); - GNUNET_free (redirect_uri); - return; - } - GNUNET_SCHEDULER_add_now (&code_redirect, handle); + { + if ((NULL != handle->redirect_prefix) && + (NULL != handle->redirect_suffix) && (NULL != handle->tld)) + { + GNUNET_asprintf(&redirect_uri, + "%s.%s/%s?error=%s&error_description=%s&state=%s", + handle->redirect_prefix, + handle->tld, + handle->redirect_suffix, + "access_denied", + "User denied access", + handle->oidc->state); + } + else + { + GNUNET_asprintf(&redirect_uri, + "%s?error=%s&error_description=%s&state=%s", + handle->oidc->redirect_uri, + "access_denied", + "User denied access", + handle->oidc->state); + } + resp = GNUNET_REST_create_response(""); + MHD_add_response_header(resp, "Location", redirect_uri); + handle->proc(handle->proc_cls, resp, MHD_HTTP_FOUND); + GNUNET_SCHEDULER_add_now(&cleanup_handle_delayed, handle); + GNUNET_free(redirect_uri); + return; + } + GNUNET_SCHEDULER_add_now(&code_redirect, handle); } static void -lookup_redirect_uri_result (void *cls, - uint32_t rd_count, - const struct GNUNET_GNSRECORD_Data *rd) +lookup_redirect_uri_result(void *cls, + uint32_t rd_count, + const struct GNUNET_GNSRECORD_Data *rd) { struct RequestHandle *handle = cls; char *tmp; @@ -1140,66 +1139,66 @@ lookup_redirect_uri_result (void *cls, handle->gns_op = NULL; if (0 == rd_count) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR); - handle->edesc = - GNUNET_strdup ("Server cannot generate ticket, redirect uri not found."); - GNUNET_SCHEDULER_add_now (&do_redirect_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_SERVER_ERROR); + handle->edesc = + GNUNET_strdup("Server cannot generate ticket, redirect uri not found."); + GNUNET_SCHEDULER_add_now(&do_redirect_error, handle); + return; + } for (int i = 0; i < rd_count; i++) - { - if (GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_REDIRECT != rd[i].record_type) - continue; - if (0 != strncmp (rd[i].data, handle->oidc->redirect_uri, rd[i].data_size)) - continue; - tmp = GNUNET_strndup (rd[i].data, rd[i].data_size); - if (NULL == strstr (tmp, handle->oidc->client_id)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Redirect uri %s does not contain client_id %s\n", - tmp, - handle->oidc->client_id); - } - else - { - pos = strrchr (tmp, (unsigned char) '.'); - if (NULL == pos) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Redirect uri %s contains client_id but is malformed\n", - tmp); - GNUNET_free (tmp); + { + if (GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_REDIRECT != rd[i].record_type) continue; - } - *pos = '\0'; - handle->redirect_prefix = GNUNET_strdup (tmp); - tmp_key_str = pos + 1; - pos = strchr (tmp_key_str, (unsigned char) '/'); - if (NULL == pos) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Redirect uri %s contains client_id but is malformed\n", - tmp); - GNUNET_free (tmp); + if (0 != strncmp(rd[i].data, handle->oidc->redirect_uri, rd[i].data_size)) continue; - } - *pos = '\0'; - handle->redirect_suffix = GNUNET_strdup (pos + 1); - - GNUNET_STRINGS_string_to_data (tmp_key_str, - strlen (tmp_key_str), - &redirect_zone, - sizeof (redirect_zone)); - } - GNUNET_SCHEDULER_add_now (&build_redirect, handle); - GNUNET_free (tmp); - return; - } - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR); + tmp = GNUNET_strndup(rd[i].data, rd[i].data_size); + if (NULL == strstr(tmp, handle->oidc->client_id)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Redirect uri %s does not contain client_id %s\n", + tmp, + handle->oidc->client_id); + } + else + { + pos = strrchr(tmp, (unsigned char)'.'); + if (NULL == pos) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Redirect uri %s contains client_id but is malformed\n", + tmp); + GNUNET_free(tmp); + continue; + } + *pos = '\0'; + handle->redirect_prefix = GNUNET_strdup(tmp); + tmp_key_str = pos + 1; + pos = strchr(tmp_key_str, (unsigned char)'/'); + if (NULL == pos) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Redirect uri %s contains client_id but is malformed\n", + tmp); + GNUNET_free(tmp); + continue; + } + *pos = '\0'; + handle->redirect_suffix = GNUNET_strdup(pos + 1); + + GNUNET_STRINGS_string_to_data(tmp_key_str, + strlen(tmp_key_str), + &redirect_zone, + sizeof(redirect_zone)); + } + GNUNET_SCHEDULER_add_now(&build_redirect, handle); + GNUNET_free(tmp); + return; + } + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_SERVER_ERROR); handle->edesc = - GNUNET_strdup ("Server cannot generate ticket, redirect uri not found."); - GNUNET_SCHEDULER_add_now (&do_redirect_error, handle); + GNUNET_strdup("Server cannot generate ticket, redirect uri not found."); + GNUNET_SCHEDULER_add_now(&do_redirect_error, handle); } @@ -1207,36 +1206,37 @@ lookup_redirect_uri_result (void *cls, * Initiate redirect back to client. */ static void -client_redirect (void *cls) +client_redirect(void *cls) { struct RequestHandle *handle = cls; /* Lookup client redirect uri to verify request */ handle->gns_op = - GNUNET_GNS_lookup (handle->gns_handle, - GNUNET_GNS_EMPTY_LABEL_AT, - &handle->oidc->client_pkey, - GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_REDIRECT, - GNUNET_GNS_LO_DEFAULT, - &lookup_redirect_uri_result, - handle); + GNUNET_GNS_lookup(handle->gns_handle, + GNUNET_GNS_EMPTY_LABEL_AT, + &handle->oidc->client_pkey, + GNUNET_GNSRECORD_TYPE_RECLAIM_OIDC_REDIRECT, + GNUNET_GNS_LO_DEFAULT, + &lookup_redirect_uri_result, + handle); } static char * -get_url_parameter_copy (const struct RequestHandle *handle, const char *key) +get_url_parameter_copy(const struct RequestHandle *handle, const char *key) { struct GNUNET_HashCode hc; char *value; - GNUNET_CRYPTO_hash (key, strlen (key), &hc); - if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle - ->url_param_map, - &hc)) + + GNUNET_CRYPTO_hash(key, strlen(key), &hc); + if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(handle->rest_handle + ->url_param_map, + &hc)) return NULL; value = - GNUNET_CONTAINER_multihashmap_get (handle->rest_handle->url_param_map, &hc); + GNUNET_CONTAINER_multihashmap_get(handle->rest_handle->url_param_map, &hc); if (NULL == value) return NULL; - return GNUNET_strdup (value); + return GNUNET_strdup(value); } @@ -1247,7 +1247,7 @@ get_url_parameter_copy (const struct RequestHandle *handle, const char *key) * @param cls the `struct RequestHandle` */ static void -build_authz_response (void *cls) +build_authz_response(void *cls) { struct RequestHandle *handle = cls; struct GNUNET_HashCode cache_key; @@ -1259,117 +1259,117 @@ build_authz_response (void *cls) // REQUIRED value: redirect_uri handle->oidc->redirect_uri = - get_url_parameter_copy (handle, OIDC_REDIRECT_URI_KEY); + get_url_parameter_copy(handle, OIDC_REDIRECT_URI_KEY); if (NULL == handle->oidc->redirect_uri) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST); - handle->edesc = GNUNET_strdup ("missing parameter redirect_uri"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_REQUEST); + handle->edesc = GNUNET_strdup("missing parameter redirect_uri"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } // REQUIRED value: response_type handle->oidc->response_type = - get_url_parameter_copy (handle, OIDC_RESPONSE_TYPE_KEY); + get_url_parameter_copy(handle, OIDC_RESPONSE_TYPE_KEY); if (NULL == handle->oidc->response_type) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST); - handle->edesc = GNUNET_strdup ("missing parameter response_type"); - GNUNET_SCHEDULER_add_now (&do_redirect_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_REQUEST); + handle->edesc = GNUNET_strdup("missing parameter response_type"); + GNUNET_SCHEDULER_add_now(&do_redirect_error, handle); + return; + } // REQUIRED value: scope - handle->oidc->scope = get_url_parameter_copy (handle, OIDC_SCOPE_KEY); + handle->oidc->scope = get_url_parameter_copy(handle, OIDC_SCOPE_KEY); if (NULL == handle->oidc->scope) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_SCOPE); - handle->edesc = GNUNET_strdup ("missing parameter scope"); - GNUNET_SCHEDULER_add_now (&do_redirect_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_SCOPE); + handle->edesc = GNUNET_strdup("missing parameter scope"); + GNUNET_SCHEDULER_add_now(&do_redirect_error, handle); + return; + } // OPTIONAL value: nonce - handle->oidc->nonce = get_url_parameter_copy (handle, OIDC_NONCE_KEY); + handle->oidc->nonce = get_url_parameter_copy(handle, OIDC_NONCE_KEY); // TODO check other values if needed number_of_ignored_parameter = - sizeof (OIDC_ignored_parameter_array) / sizeof (char *); + sizeof(OIDC_ignored_parameter_array) / sizeof(char *); for (iterator = 0; iterator < number_of_ignored_parameter; iterator++) - { - GNUNET_CRYPTO_hash (OIDC_ignored_parameter_array[iterator], - strlen (OIDC_ignored_parameter_array[iterator]), - &cache_key); - if (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle - ->url_param_map, - &cache_key)) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_ACCESS_DENIED); - GNUNET_asprintf (&handle->edesc, - "Server will not handle parameter: %s", - OIDC_ignored_parameter_array[iterator]); - GNUNET_SCHEDULER_add_now (&do_redirect_error, handle); - return; + { + GNUNET_CRYPTO_hash(OIDC_ignored_parameter_array[iterator], + strlen(OIDC_ignored_parameter_array[iterator]), + &cache_key); + if (GNUNET_YES == + GNUNET_CONTAINER_multihashmap_contains(handle->rest_handle + ->url_param_map, + &cache_key)) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_ACCESS_DENIED); + GNUNET_asprintf(&handle->edesc, + "Server will not handle parameter: %s", + OIDC_ignored_parameter_array[iterator]); + GNUNET_SCHEDULER_add_now(&do_redirect_error, handle); + return; + } } - } // We only support authorization code flows. - if (0 != strcmp (handle->oidc->response_type, - OIDC_EXPECTED_AUTHORIZATION_RESPONSE_TYPE)) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_UNSUPPORTED_RESPONSE_TYPE); - handle->edesc = GNUNET_strdup ("The authorization server does not support " - "obtaining this authorization code."); - GNUNET_SCHEDULER_add_now (&do_redirect_error, handle); - return; - } + if (0 != strcmp(handle->oidc->response_type, + OIDC_EXPECTED_AUTHORIZATION_RESPONSE_TYPE)) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_UNSUPPORTED_RESPONSE_TYPE); + handle->edesc = GNUNET_strdup("The authorization server does not support " + "obtaining this authorization code."); + GNUNET_SCHEDULER_add_now(&do_redirect_error, handle); + return; + } // Checks if scope contains 'openid' - expected_scope = GNUNET_strdup (handle->oidc->scope); + expected_scope = GNUNET_strdup(handle->oidc->scope); char *test; - test = strtok (expected_scope, delimiter); + test = strtok(expected_scope, delimiter); while (NULL != test) - { - if (0 == strcmp (OIDC_EXPECTED_AUTHORIZATION_SCOPE, expected_scope)) - break; - test = strtok (NULL, delimiter); - } + { + if (0 == strcmp(OIDC_EXPECTED_AUTHORIZATION_SCOPE, expected_scope)) + break; + test = strtok(NULL, delimiter); + } if (NULL == test) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_SCOPE); - handle->edesc = - GNUNET_strdup ("The requested scope is invalid, unknown, or malformed."); - GNUNET_SCHEDULER_add_now (&do_redirect_error, handle); - GNUNET_free (expected_scope); - return; - } - - GNUNET_free (expected_scope); + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_SCOPE); + handle->edesc = + GNUNET_strdup("The requested scope is invalid, unknown, or malformed."); + GNUNET_SCHEDULER_add_now(&do_redirect_error, handle); + GNUNET_free(expected_scope); + return; + } + + GNUNET_free(expected_scope); if ((NULL == handle->oidc->login_identity) && (GNUNET_NO == handle->oidc->user_cancelled)) - GNUNET_SCHEDULER_add_now (&login_redirect, handle); + GNUNET_SCHEDULER_add_now(&login_redirect, handle); else - GNUNET_SCHEDULER_add_now (&client_redirect, handle); + GNUNET_SCHEDULER_add_now(&client_redirect, handle); } /** * Iterate over tlds in config */ static void -tld_iter (void *cls, const char *section, const char *option, const char *value) +tld_iter(void *cls, const char *section, const char *option, const char *value) { struct RequestHandle *handle = cls; struct GNUNET_CRYPTO_EcdsaPublicKey pkey; if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (value, strlen (value), &pkey)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Skipping non key %s\n", value); - return; - } - if (0 == GNUNET_memcmp (&pkey, &handle->oidc->client_pkey)) - handle->tld = GNUNET_strdup (option + 1); + GNUNET_CRYPTO_ecdsa_public_key_from_string(value, strlen(value), &pkey)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Skipping non key %s\n", value); + return; + } + if (0 == GNUNET_memcmp(&pkey, &handle->oidc->client_pkey)) + handle->tld = GNUNET_strdup(option + 1); } /** @@ -1380,70 +1380,70 @@ tld_iter (void *cls, const char *section, const char *option, const char *value) * @param cls the RequestHandle */ static void -authorize_endpoint (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +authorize_endpoint(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; struct EgoEntry *tmp_ego; const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv_key; struct GNUNET_CRYPTO_EcdsaPublicKey pkey; - cookie_identity_interpretation (handle); + cookie_identity_interpretation(handle); // RECOMMENDED value: state - REQUIRED for answers - handle->oidc->state = get_url_parameter_copy (handle, OIDC_STATE_KEY); + handle->oidc->state = get_url_parameter_copy(handle, OIDC_STATE_KEY); // REQUIRED value: client_id - handle->oidc->client_id = get_url_parameter_copy (handle, OIDC_CLIENT_ID_KEY); + handle->oidc->client_id = get_url_parameter_copy(handle, OIDC_CLIENT_ID_KEY); if (NULL == handle->oidc->client_id) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST); - handle->edesc = GNUNET_strdup ("missing parameter client_id"); - handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_REQUEST); + handle->edesc = GNUNET_strdup("missing parameter client_id"); + handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } // OPTIONAL value: code_challenge - handle->oidc->code_challenge = get_url_parameter_copy (handle, OIDC_CODE_CHALLENGE_KEY); + handle->oidc->code_challenge = get_url_parameter_copy(handle, OIDC_CODE_CHALLENGE_KEY); if (NULL == handle->oidc->code_challenge) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "OAuth authorization request does not contain PKCE parameters!\n"); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "OAuth authorization request does not contain PKCE parameters!\n"); + } if (GNUNET_OK != - GNUNET_CRYPTO_ecdsa_public_key_from_string (handle->oidc->client_id, - strlen ( - handle->oidc->client_id), - &handle->oidc->client_pkey)) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_UNAUTHORIZED_CLIENT); - handle->edesc = GNUNET_strdup ("The client is not authorized to request an " - "authorization code using this method."); - handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + GNUNET_CRYPTO_ecdsa_public_key_from_string(handle->oidc->client_id, + strlen( + handle->oidc->client_id), + &handle->oidc->client_pkey)) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_UNAUTHORIZED_CLIENT); + handle->edesc = GNUNET_strdup("The client is not authorized to request an " + "authorization code using this method."); + handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } // If we know this identity, translated the corresponding TLD // TODO: We might want to have a reverse lookup functionality for TLDs? for (tmp_ego = handle->ego_head; NULL != tmp_ego; tmp_ego = tmp_ego->next) - { - priv_key = GNUNET_IDENTITY_ego_get_private_key (tmp_ego->ego); - GNUNET_CRYPTO_ecdsa_key_get_public (priv_key, &pkey); - if (0 == GNUNET_memcmp (&pkey, &handle->oidc->client_pkey)) { - handle->tld = GNUNET_strdup (tmp_ego->identifier); - handle->ego_entry = handle->ego_tail; + priv_key = GNUNET_IDENTITY_ego_get_private_key(tmp_ego->ego); + GNUNET_CRYPTO_ecdsa_key_get_public(priv_key, &pkey); + if (0 == GNUNET_memcmp(&pkey, &handle->oidc->client_pkey)) + { + handle->tld = GNUNET_strdup(tmp_ego->identifier); + handle->ego_entry = handle->ego_tail; + } } - } if (NULL == handle->tld) - GNUNET_CONFIGURATION_iterate_section_values (cfg, "gns", tld_iter, handle); + GNUNET_CONFIGURATION_iterate_section_values(cfg, "gns", tld_iter, handle); if (NULL == handle->tld) - handle->tld = GNUNET_strdup (handle->oidc->client_id); - GNUNET_SCHEDULER_add_now (&build_authz_response, handle); + handle->tld = GNUNET_strdup(handle->oidc->client_id); + GNUNET_SCHEDULER_add_now(&build_authz_response, handle); } /** @@ -1454,11 +1454,11 @@ authorize_endpoint (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ static void -login_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +login_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { - struct MHD_Response *resp = GNUNET_REST_create_response (""); + struct MHD_Response *resp = GNUNET_REST_create_response(""); struct RequestHandle *handle = cls; struct GNUNET_HashCode cache_key; struct GNUNET_TIME_Absolute *current_time; @@ -1469,55 +1469,56 @@ login_cont (struct GNUNET_REST_RequestHandle *con_handle, json_error_t error; json_t *identity; char term_data[handle->rest_handle->data_size + 1]; + term_data[handle->rest_handle->data_size] = '\0'; - GNUNET_memcpy (term_data, - handle->rest_handle->data, - handle->rest_handle->data_size); - root = json_loads (term_data, JSON_DECODE_ANY, &error); - identity = json_object_get (root, "identity"); - if (! json_is_string (identity)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error parsing json string from %s\n", - term_data); - handle->proc (handle->proc_cls, resp, MHD_HTTP_BAD_REQUEST); - json_decref (root); - GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle); - return; - } - GNUNET_asprintf (&cookie, "Identity=%s", json_string_value (identity)); - GNUNET_asprintf (&header_val, - "%s;Max-Age=%d", - cookie, - OIDC_COOKIE_EXPIRATION); - MHD_add_response_header (resp, "Set-Cookie", header_val); - MHD_add_response_header (resp, "Access-Control-Allow-Methods", "POST"); - GNUNET_CRYPTO_hash (cookie, strlen (cookie), &cache_key); - - if (0 != strcmp (json_string_value (identity), "Denied")) - { - current_time = GNUNET_new (struct GNUNET_TIME_Absolute); - *current_time = GNUNET_TIME_relative_to_absolute ( - GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_get_second_ (), - OIDC_COOKIE_EXPIRATION)); - last_time = - GNUNET_CONTAINER_multihashmap_get (OIDC_cookie_jar_map, &cache_key); - GNUNET_free_non_null (last_time); - GNUNET_CONTAINER_multihashmap_put (OIDC_cookie_jar_map, - &cache_key, - current_time, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE); - } - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_free (cookie); - GNUNET_free (header_val); - json_decref (root); - GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle); + GNUNET_memcpy(term_data, + handle->rest_handle->data, + handle->rest_handle->data_size); + root = json_loads(term_data, JSON_DECODE_ANY, &error); + identity = json_object_get(root, "identity"); + if (!json_is_string(identity)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error parsing json string from %s\n", + term_data); + handle->proc(handle->proc_cls, resp, MHD_HTTP_BAD_REQUEST); + json_decref(root); + GNUNET_SCHEDULER_add_now(&cleanup_handle_delayed, handle); + return; + } + GNUNET_asprintf(&cookie, "Identity=%s", json_string_value(identity)); + GNUNET_asprintf(&header_val, + "%s;Max-Age=%d", + cookie, + OIDC_COOKIE_EXPIRATION); + MHD_add_response_header(resp, "Set-Cookie", header_val); + MHD_add_response_header(resp, "Access-Control-Allow-Methods", "POST"); + GNUNET_CRYPTO_hash(cookie, strlen(cookie), &cache_key); + + if (0 != strcmp(json_string_value(identity), "Denied")) + { + current_time = GNUNET_new(struct GNUNET_TIME_Absolute); + *current_time = GNUNET_TIME_relative_to_absolute( + GNUNET_TIME_relative_multiply(GNUNET_TIME_relative_get_second_(), + OIDC_COOKIE_EXPIRATION)); + last_time = + GNUNET_CONTAINER_multihashmap_get(OIDC_cookie_jar_map, &cache_key); + GNUNET_free_non_null(last_time); + GNUNET_CONTAINER_multihashmap_put(OIDC_cookie_jar_map, + &cache_key, + current_time, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE); + } + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_free(cookie); + GNUNET_free(header_val); + json_decref(root); + GNUNET_SCHEDULER_add_now(&cleanup_handle_delayed, handle); } static int -check_authorization (struct RequestHandle *handle, - struct GNUNET_CRYPTO_EcdsaPublicKey *cid) +check_authorization(struct RequestHandle *handle, + struct GNUNET_CRYPTO_EcdsaPublicKey *cid) { struct GNUNET_HashCode cache_key; char *authorization; @@ -1527,146 +1528,146 @@ check_authorization (struct RequestHandle *handle, char *pass; char *expected_pass; - GNUNET_CRYPTO_hash (OIDC_AUTHORIZATION_HEADER_KEY, - strlen (OIDC_AUTHORIZATION_HEADER_KEY), - &cache_key); - if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle - ->header_param_map, - &cache_key)) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT); - handle->edesc = GNUNET_strdup ("missing authorization"); - handle->response_code = MHD_HTTP_UNAUTHORIZED; - return GNUNET_SYSERR; - } + GNUNET_CRYPTO_hash(OIDC_AUTHORIZATION_HEADER_KEY, + strlen(OIDC_AUTHORIZATION_HEADER_KEY), + &cache_key); + if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(handle->rest_handle + ->header_param_map, + &cache_key)) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_CLIENT); + handle->edesc = GNUNET_strdup("missing authorization"); + handle->response_code = MHD_HTTP_UNAUTHORIZED; + return GNUNET_SYSERR; + } authorization = - GNUNET_CONTAINER_multihashmap_get (handle->rest_handle->header_param_map, - &cache_key); + GNUNET_CONTAINER_multihashmap_get(handle->rest_handle->header_param_map, + &cache_key); // split header in "Basic" and [content] - credentials = strtok (authorization, " "); - if ((NULL == credentials) || (0 != strcmp ("Basic", credentials))) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT); - handle->response_code = MHD_HTTP_UNAUTHORIZED; - return GNUNET_SYSERR; - } - credentials = strtok (NULL, " "); + credentials = strtok(authorization, " "); + if ((NULL == credentials) || (0 != strcmp("Basic", credentials))) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_CLIENT); + handle->response_code = MHD_HTTP_UNAUTHORIZED; + return GNUNET_SYSERR; + } + credentials = strtok(NULL, " "); if (NULL == credentials) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT); - handle->response_code = MHD_HTTP_UNAUTHORIZED; - return GNUNET_SYSERR; - } - GNUNET_STRINGS_base64_decode (credentials, - strlen (credentials), - (void **) &basic_authorization); + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_CLIENT); + handle->response_code = MHD_HTTP_UNAUTHORIZED; + return GNUNET_SYSERR; + } + GNUNET_STRINGS_base64_decode(credentials, + strlen(credentials), + (void **)&basic_authorization); if (NULL == basic_authorization) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT); - handle->response_code = MHD_HTTP_UNAUTHORIZED; - return GNUNET_SYSERR; - } - client_id = strtok (basic_authorization, ":"); + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_CLIENT); + handle->response_code = MHD_HTTP_UNAUTHORIZED; + return GNUNET_SYSERR; + } + client_id = strtok(basic_authorization, ":"); if (NULL == client_id) - { - GNUNET_free_non_null (basic_authorization); - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT); - handle->response_code = MHD_HTTP_UNAUTHORIZED; - return GNUNET_SYSERR; - } - pass = strtok (NULL, ":"); + { + GNUNET_free_non_null(basic_authorization); + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_CLIENT); + handle->response_code = MHD_HTTP_UNAUTHORIZED; + return GNUNET_SYSERR; + } + pass = strtok(NULL, ":"); if (NULL == pass) - { - GNUNET_free_non_null (basic_authorization); - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT); - handle->response_code = MHD_HTTP_UNAUTHORIZED; - return GNUNET_SYSERR; - } - - // check client password - if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, - "reclaim-rest-plugin", - "OIDC_CLIENT_SECRET", - &expected_pass)) - { - if (0 != strcmp (expected_pass, pass)) - { - GNUNET_free_non_null (basic_authorization); - GNUNET_free (expected_pass); - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT); + { + GNUNET_free_non_null(basic_authorization); + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_CLIENT); handle->response_code = MHD_HTTP_UNAUTHORIZED; return GNUNET_SYSERR; } - GNUNET_free (expected_pass); - } + + // check client password + if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, + "reclaim-rest-plugin", + "OIDC_CLIENT_SECRET", + &expected_pass)) + { + if (0 != strcmp(expected_pass, pass)) + { + GNUNET_free_non_null(basic_authorization); + GNUNET_free(expected_pass); + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_CLIENT); + handle->response_code = MHD_HTTP_UNAUTHORIZED; + return GNUNET_SYSERR; + } + GNUNET_free(expected_pass); + } else - { - GNUNET_free_non_null (basic_authorization); - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR); - handle->edesc = GNUNET_strdup ("gnunet configuration failed"); - handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; - return GNUNET_SYSERR; - } + { + GNUNET_free_non_null(basic_authorization); + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_SERVER_ERROR); + handle->edesc = GNUNET_strdup("gnunet configuration failed"); + handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; + return GNUNET_SYSERR; + } // check client_id for (handle->ego_entry = handle->ego_head; NULL != handle->ego_entry; handle->ego_entry = handle->ego_entry->next) - { - if (0 == strcmp (handle->ego_entry->keystring, client_id)) - break; - } + { + if (0 == strcmp(handle->ego_entry->keystring, client_id)) + break; + } if (NULL == handle->ego_entry) - { - GNUNET_free_non_null (basic_authorization); - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_CLIENT); - handle->response_code = MHD_HTTP_UNAUTHORIZED; - return GNUNET_SYSERR; - } - GNUNET_STRINGS_string_to_data (client_id, - strlen (client_id), - cid, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)); - - GNUNET_free (basic_authorization); + { + GNUNET_free_non_null(basic_authorization); + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_CLIENT); + handle->response_code = MHD_HTTP_UNAUTHORIZED; + return GNUNET_SYSERR; + } + GNUNET_STRINGS_string_to_data(client_id, + strlen(client_id), + cid, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey)); + + GNUNET_free(basic_authorization); return GNUNET_OK; } const struct EgoEntry * -find_ego (struct RequestHandle *handle, - struct GNUNET_CRYPTO_EcdsaPublicKey *test_key) +find_ego(struct RequestHandle *handle, + struct GNUNET_CRYPTO_EcdsaPublicKey *test_key) { struct EgoEntry *ego_entry; struct GNUNET_CRYPTO_EcdsaPublicKey pub_key; for (ego_entry = handle->ego_head; NULL != ego_entry; ego_entry = ego_entry->next) - { - GNUNET_IDENTITY_ego_get_public_key (ego_entry->ego, &pub_key); - if (0 == GNUNET_memcmp (&pub_key, test_key)) - return ego_entry; - } + { + GNUNET_IDENTITY_ego_get_public_key(ego_entry->ego, &pub_key); + if (0 == GNUNET_memcmp(&pub_key, test_key)) + return ego_entry; + } return NULL; } static void -persist_access_token (const struct RequestHandle *handle, - const char *access_token, - const struct GNUNET_RECLAIM_Ticket *ticket) +persist_access_token(const struct RequestHandle *handle, + const char *access_token, + const struct GNUNET_RECLAIM_Ticket *ticket) { struct GNUNET_HashCode hc; struct GNUNET_RECLAIM_Ticket *ticketbuf; - GNUNET_CRYPTO_hash (access_token, strlen (access_token), &hc); - ticketbuf = GNUNET_new (struct GNUNET_RECLAIM_Ticket); + GNUNET_CRYPTO_hash(access_token, strlen(access_token), &hc); + ticketbuf = GNUNET_new(struct GNUNET_RECLAIM_Ticket); *ticketbuf = *ticket; - GNUNET_assert (GNUNET_SYSERR != - GNUNET_CONTAINER_multihashmap_put ( - OIDC_access_token_map, - &hc, - ticketbuf, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); + GNUNET_assert(GNUNET_SYSERR != + GNUNET_CONTAINER_multihashmap_put( + OIDC_access_token_map, + &hc, + ticketbuf, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); } /** @@ -1677,9 +1678,9 @@ persist_access_token (const struct RequestHandle *handle, * @param cls the RequestHandle */ static void -token_endpoint (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +token_endpoint(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; const struct EgoEntry *ego_entry; @@ -1698,16 +1699,17 @@ token_endpoint (struct GNUNET_REST_RequestHandle *con_handle, char *jwt_secret; char *nonce; char *code_verifier; + /* * Check Authorization */ - if (GNUNET_SYSERR == check_authorization (handle, &cid)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "OIDC authorization for token endpoint failed\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + if (GNUNET_SYSERR == check_authorization(handle, &cid)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "OIDC authorization for token endpoint failed\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } /* * Check parameter @@ -1715,148 +1717,148 @@ token_endpoint (struct GNUNET_REST_RequestHandle *con_handle, // TODO Do not allow multiple equal parameter names // REQUIRED grant_type - GNUNET_CRYPTO_hash (OIDC_GRANT_TYPE_KEY, - strlen (OIDC_GRANT_TYPE_KEY), - &cache_key); - grant_type = get_url_parameter_copy (handle, OIDC_GRANT_TYPE_KEY); + GNUNET_CRYPTO_hash(OIDC_GRANT_TYPE_KEY, + strlen(OIDC_GRANT_TYPE_KEY), + &cache_key); + grant_type = get_url_parameter_copy(handle, OIDC_GRANT_TYPE_KEY); if (NULL == grant_type) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST); - handle->edesc = GNUNET_strdup ("missing parameter grant_type"); - handle->response_code = MHD_HTTP_BAD_REQUEST; - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_REQUEST); + handle->edesc = GNUNET_strdup("missing parameter grant_type"); + handle->response_code = MHD_HTTP_BAD_REQUEST; + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } // Check parameter grant_type == "authorization_code" - if (0 != strcmp (OIDC_GRANT_TYPE_VALUE, grant_type)) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_UNSUPPORTED_GRANT_TYPE); - handle->response_code = MHD_HTTP_BAD_REQUEST; - GNUNET_free (grant_type); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - GNUNET_free (grant_type); + if (0 != strcmp(OIDC_GRANT_TYPE_VALUE, grant_type)) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_UNSUPPORTED_GRANT_TYPE); + handle->response_code = MHD_HTTP_BAD_REQUEST; + GNUNET_free(grant_type); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + GNUNET_free(grant_type); // REQUIRED code - code = get_url_parameter_copy (handle, OIDC_CODE_KEY); + code = get_url_parameter_copy(handle, OIDC_CODE_KEY); if (NULL == code) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST); - handle->edesc = GNUNET_strdup ("missing parameter code"); - handle->response_code = MHD_HTTP_BAD_REQUEST; - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - ego_entry = find_ego (handle, &cid); + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_REQUEST); + handle->edesc = GNUNET_strdup("missing parameter code"); + handle->response_code = MHD_HTTP_BAD_REQUEST; + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + ego_entry = find_ego(handle, &cid); if (NULL == ego_entry) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST); - handle->edesc = GNUNET_strdup ("Unknown client"); - handle->response_code = MHD_HTTP_BAD_REQUEST; - GNUNET_free (code); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - privkey = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego); + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_REQUEST); + handle->edesc = GNUNET_strdup("Unknown client"); + handle->response_code = MHD_HTTP_BAD_REQUEST; + GNUNET_free(code); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + privkey = GNUNET_IDENTITY_ego_get_private_key(ego_entry->ego); // REQUIRED code verifier - code_verifier = get_url_parameter_copy (handle, OIDC_CODE_VERIFIER_KEY); + code_verifier = get_url_parameter_copy(handle, OIDC_CODE_VERIFIER_KEY); if (NULL == code_verifier) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST); - handle->edesc = GNUNET_strdup ("missing parameter code_verifier"); - handle->response_code = MHD_HTTP_BAD_REQUEST; - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_REQUEST); + handle->edesc = GNUNET_strdup("missing parameter code_verifier"); + handle->response_code = MHD_HTTP_BAD_REQUEST; + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } // decode code - if (GNUNET_OK != OIDC_parse_authz_code (privkey, code, code_verifier, &ticket, &cl, &nonce)) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST); - handle->edesc = GNUNET_strdup ("invalid code"); - handle->response_code = MHD_HTTP_BAD_REQUEST; - GNUNET_free (code); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - GNUNET_free (code); + if (GNUNET_OK != OIDC_parse_authz_code(privkey, code, code_verifier, &ticket, &cl, &nonce)) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_REQUEST); + handle->edesc = GNUNET_strdup("invalid code"); + handle->response_code = MHD_HTTP_BAD_REQUEST; + GNUNET_free(code); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + GNUNET_free(code); // create jwt - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, - "reclaim-rest-plugin", - "expiration_time", - &expiration_time)) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_SERVER_ERROR); - handle->edesc = GNUNET_strdup ("gnunet configuration failed"); - handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time(cfg, + "reclaim-rest-plugin", + "expiration_time", + &expiration_time)) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_SERVER_ERROR); + handle->edesc = GNUNET_strdup("gnunet configuration failed"); + handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } // TODO OPTIONAL acr,amr,azp - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "reclaim-rest-plugin", - "jwt_secret", - &jwt_secret)) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_REQUEST); - handle->edesc = GNUNET_strdup ("No signing secret configured!"); - handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - id_token = OIDC_id_token_new (&ticket.audience, - &ticket.identity, - cl, - &expiration_time, - (NULL != nonce) ? nonce : NULL, - jwt_secret); - access_token = OIDC_access_token_new (); - OIDC_build_token_response (access_token, - id_token, - &expiration_time, - &json_response); - - persist_access_token (handle, access_token, &ticket); - resp = GNUNET_REST_create_response (json_response); - MHD_add_response_header (resp, "Cache-Control", "no-store"); - MHD_add_response_header (resp, "Pragma", "no-cache"); - MHD_add_response_header (resp, "Content-Type", "application/json"); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_RECLAIM_ATTRIBUTE_list_destroy (cl); - GNUNET_free (access_token); - GNUNET_free (json_response); - GNUNET_free (id_token); - GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "reclaim-rest-plugin", + "jwt_secret", + &jwt_secret)) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_REQUEST); + handle->edesc = GNUNET_strdup("No signing secret configured!"); + handle->response_code = MHD_HTTP_INTERNAL_SERVER_ERROR; + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + id_token = OIDC_id_token_new(&ticket.audience, + &ticket.identity, + cl, + &expiration_time, + (NULL != nonce) ? nonce : NULL, + jwt_secret); + access_token = OIDC_access_token_new(); + OIDC_build_token_response(access_token, + id_token, + &expiration_time, + &json_response); + + persist_access_token(handle, access_token, &ticket); + resp = GNUNET_REST_create_response(json_response); + MHD_add_response_header(resp, "Cache-Control", "no-store"); + MHD_add_response_header(resp, "Pragma", "no-cache"); + MHD_add_response_header(resp, "Content-Type", "application/json"); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_RECLAIM_ATTRIBUTE_list_destroy(cl); + GNUNET_free(access_token); + GNUNET_free(json_response); + GNUNET_free(id_token); + GNUNET_SCHEDULER_add_now(&cleanup_handle_delayed, handle); } /** * Collects claims and stores them in handle */ static void -consume_ticket (void *cls, - const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, - const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) +consume_ticket(void *cls, + const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, + const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) { struct RequestHandle *handle = cls; char *tmp_value; json_t *value; if (NULL == identity) - { - GNUNET_SCHEDULER_add_now (&return_userinfo_response, handle); - return; - } - tmp_value = GNUNET_RECLAIM_ATTRIBUTE_value_to_string (attr->type, - attr->data, - attr->data_size); - value = json_string (tmp_value); - json_object_set_new (handle->oidc->response, attr->name, value); - GNUNET_free (tmp_value); + { + GNUNET_SCHEDULER_add_now(&return_userinfo_response, handle); + return; + } + tmp_value = GNUNET_RECLAIM_ATTRIBUTE_value_to_string(attr->type, + attr->data, + attr->data_size); + value = json_string(tmp_value); + json_object_set_new(handle->oidc->response, attr->name, value); + GNUNET_free(tmp_value); } /** @@ -1867,9 +1869,9 @@ consume_ticket (void *cls, * @param cls the RequestHandle */ static void -userinfo_endpoint (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +userinfo_endpoint(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { // TODO expiration time struct RequestHandle *handle = cls; @@ -1882,87 +1884,87 @@ userinfo_endpoint (struct GNUNET_REST_RequestHandle *con_handle, const struct EgoEntry *ego_entry; const struct GNUNET_CRYPTO_EcdsaPrivateKey *privkey; - GNUNET_CRYPTO_hash (OIDC_AUTHORIZATION_HEADER_KEY, - strlen (OIDC_AUTHORIZATION_HEADER_KEY), - &cache_key); - if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (handle->rest_handle - ->header_param_map, - &cache_key)) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_TOKEN); - handle->edesc = GNUNET_strdup ("No Access Token"); - handle->response_code = MHD_HTTP_UNAUTHORIZED; - GNUNET_SCHEDULER_add_now (&do_userinfo_error, handle); - return; - } + GNUNET_CRYPTO_hash(OIDC_AUTHORIZATION_HEADER_KEY, + strlen(OIDC_AUTHORIZATION_HEADER_KEY), + &cache_key); + if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(handle->rest_handle + ->header_param_map, + &cache_key)) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_TOKEN); + handle->edesc = GNUNET_strdup("No Access Token"); + handle->response_code = MHD_HTTP_UNAUTHORIZED; + GNUNET_SCHEDULER_add_now(&do_userinfo_error, handle); + return; + } authorization = - GNUNET_CONTAINER_multihashmap_get (handle->rest_handle->header_param_map, - &cache_key); + GNUNET_CONTAINER_multihashmap_get(handle->rest_handle->header_param_map, + &cache_key); // split header in "Bearer" and access_token - authorization = GNUNET_strdup (authorization); - authorization_type = strtok (authorization, delimiter); + authorization = GNUNET_strdup(authorization); + authorization_type = strtok(authorization, delimiter); if ((NULL == authorization_type) || - (0 != strcmp ("Bearer", authorization_type))) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_TOKEN); - handle->edesc = GNUNET_strdup ("No Access Token"); - handle->response_code = MHD_HTTP_UNAUTHORIZED; - GNUNET_SCHEDULER_add_now (&do_userinfo_error, handle); - GNUNET_free (authorization); - return; - } - authorization_access_token = strtok (NULL, delimiter); + (0 != strcmp("Bearer", authorization_type))) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_TOKEN); + handle->edesc = GNUNET_strdup("No Access Token"); + handle->response_code = MHD_HTTP_UNAUTHORIZED; + GNUNET_SCHEDULER_add_now(&do_userinfo_error, handle); + GNUNET_free(authorization); + return; + } + authorization_access_token = strtok(NULL, delimiter); if (NULL == authorization_access_token) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_TOKEN); - handle->edesc = GNUNET_strdup ("Access token missing"); - handle->response_code = MHD_HTTP_UNAUTHORIZED; - GNUNET_SCHEDULER_add_now (&do_userinfo_error, handle); - GNUNET_free (authorization); - return; - } - - GNUNET_CRYPTO_hash (authorization_access_token, - strlen (authorization_access_token), - &cache_key); + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_TOKEN); + handle->edesc = GNUNET_strdup("Access token missing"); + handle->response_code = MHD_HTTP_UNAUTHORIZED; + GNUNET_SCHEDULER_add_now(&do_userinfo_error, handle); + GNUNET_free(authorization); + return; + } + + GNUNET_CRYPTO_hash(authorization_access_token, + strlen(authorization_access_token), + &cache_key); if (GNUNET_NO == - GNUNET_CONTAINER_multihashmap_contains (OIDC_access_token_map, - &cache_key)) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_TOKEN); - handle->edesc = GNUNET_strdup ("The access token expired"); - handle->response_code = MHD_HTTP_UNAUTHORIZED; - GNUNET_SCHEDULER_add_now (&do_userinfo_error, handle); - GNUNET_free (authorization); - return; - } + GNUNET_CONTAINER_multihashmap_contains(OIDC_access_token_map, + &cache_key)) + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_TOKEN); + handle->edesc = GNUNET_strdup("The access token expired"); + handle->response_code = MHD_HTTP_UNAUTHORIZED; + GNUNET_SCHEDULER_add_now(&do_userinfo_error, handle); + GNUNET_free(authorization); + return; + } ticket = - GNUNET_CONTAINER_multihashmap_get (OIDC_access_token_map, &cache_key); - GNUNET_assert (NULL != ticket); - ego_entry = find_ego (handle, &ticket->audience); + GNUNET_CONTAINER_multihashmap_get(OIDC_access_token_map, &cache_key); + GNUNET_assert(NULL != ticket); + ego_entry = find_ego(handle, &ticket->audience); if (NULL == ego_entry) - { - handle->emsg = GNUNET_strdup (OIDC_ERROR_KEY_INVALID_TOKEN); - handle->edesc = GNUNET_strdup ("The access token expired"); - handle->response_code = MHD_HTTP_UNAUTHORIZED; - GNUNET_SCHEDULER_add_now (&do_userinfo_error, handle); - GNUNET_free (authorization); - return; - } - - handle->idp = GNUNET_RECLAIM_connect (cfg); - handle->oidc->response = json_object (); - json_object_set_new (handle->oidc->response, - "sub", - json_string (ego_entry->keystring)); - privkey = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego); - handle->idp_op = GNUNET_RECLAIM_ticket_consume (handle->idp, - privkey, - ticket, - consume_ticket, - handle); - GNUNET_free (authorization); + { + handle->emsg = GNUNET_strdup(OIDC_ERROR_KEY_INVALID_TOKEN); + handle->edesc = GNUNET_strdup("The access token expired"); + handle->response_code = MHD_HTTP_UNAUTHORIZED; + GNUNET_SCHEDULER_add_now(&do_userinfo_error, handle); + GNUNET_free(authorization); + return; + } + + handle->idp = GNUNET_RECLAIM_connect(cfg); + handle->oidc->response = json_object(); + json_object_set_new(handle->oidc->response, + "sub", + json_string(ego_entry->keystring)); + privkey = GNUNET_IDENTITY_ego_get_private_key(ego_entry->ego); + handle->idp_op = GNUNET_RECLAIM_ticket_consume(handle->idp, + privkey, + ticket, + consume_ticket, + handle); + GNUNET_free(authorization); } @@ -1972,27 +1974,27 @@ userinfo_endpoint (struct GNUNET_REST_RequestHandle *con_handle, * @param handle the request handle */ static void -init_cont (struct RequestHandle *handle) +init_cont(struct RequestHandle *handle) { struct GNUNET_REST_RequestHandlerError err; static const struct GNUNET_REST_RequestHandler handlers[] = - {{MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_AUTHORIZE, &authorize_endpoint}, - {MHD_HTTP_METHOD_POST, - GNUNET_REST_API_NS_AUTHORIZE, - &authorize_endpoint}, // url-encoded - {MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_LOGIN, &login_cont}, - {MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_TOKEN, &token_endpoint}, - {MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_USERINFO, &userinfo_endpoint}, - {MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_USERINFO, &userinfo_endpoint}, - {MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_OIDC, &options_cont}, - GNUNET_REST_HANDLER_END}; + { { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_AUTHORIZE, &authorize_endpoint }, + { MHD_HTTP_METHOD_POST, + GNUNET_REST_API_NS_AUTHORIZE, + &authorize_endpoint }, // url-encoded + { MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_LOGIN, &login_cont }, + { MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_TOKEN, &token_endpoint }, + { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_USERINFO, &userinfo_endpoint }, + { MHD_HTTP_METHOD_POST, GNUNET_REST_API_NS_USERINFO, &userinfo_endpoint }, + { MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_OIDC, &options_cont }, + GNUNET_REST_HANDLER_END }; if (GNUNET_NO == - GNUNET_REST_handle_request (handle->rest_handle, handlers, &err, handle)) - { - handle->response_code = err.error_code; - GNUNET_SCHEDULER_add_now (&do_error, handle); - } + GNUNET_REST_handle_request(handle->rest_handle, handlers, &err, handle)) + { + handle->response_code = err.error_code; + GNUNET_SCHEDULER_add_now(&do_error, handle); + } } /** @@ -2029,90 +2031,91 @@ init_cont (struct RequestHandle *handle) * must thus no longer be used */ static void -list_ego (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *identifier) +list_ego(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *identifier) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; struct GNUNET_CRYPTO_EcdsaPublicKey pk; if ((NULL == ego) && (ID_REST_STATE_INIT == handle->state)) - { - handle->state = ID_REST_STATE_POST_INIT; - init_cont (handle); - return; - } - GNUNET_assert (NULL != ego); + { + handle->state = ID_REST_STATE_POST_INIT; + init_cont(handle); + return; + } + GNUNET_assert(NULL != ego); if (ID_REST_STATE_INIT == handle->state) - { - ego_entry = GNUNET_new (struct EgoEntry); - GNUNET_IDENTITY_ego_get_public_key (ego, &pk); - ego_entry->keystring = GNUNET_CRYPTO_ecdsa_public_key_to_string (&pk); - ego_entry->ego = ego; - ego_entry->identifier = GNUNET_strdup (identifier); - GNUNET_CONTAINER_DLL_insert_tail (handle->ego_head, - handle->ego_tail, - ego_entry); - return; - } + { + ego_entry = GNUNET_new(struct EgoEntry); + GNUNET_IDENTITY_ego_get_public_key(ego, &pk); + ego_entry->keystring = GNUNET_CRYPTO_ecdsa_public_key_to_string(&pk); + ego_entry->ego = ego; + ego_entry->identifier = GNUNET_strdup(identifier); + GNUNET_CONTAINER_DLL_insert_tail(handle->ego_head, + handle->ego_tail, + ego_entry); + return; + } /* Ego renamed or added */ if (identifier != NULL) - { - for (ego_entry = handle->ego_head; NULL != ego_entry; - ego_entry = ego_entry->next) - { - if (ego_entry->ego == ego) - { - /* Rename */ - GNUNET_free (ego_entry->identifier); - ego_entry->identifier = GNUNET_strdup (identifier); - break; - } - } - if (NULL == ego_entry) { - /* Add */ - ego_entry = GNUNET_new (struct EgoEntry); - GNUNET_IDENTITY_ego_get_public_key (ego, &pk); - ego_entry->keystring = GNUNET_CRYPTO_ecdsa_public_key_to_string (&pk); - ego_entry->ego = ego; - ego_entry->identifier = GNUNET_strdup (identifier); - GNUNET_CONTAINER_DLL_insert_tail (handle->ego_head, - handle->ego_tail, - ego_entry); + for (ego_entry = handle->ego_head; NULL != ego_entry; + ego_entry = ego_entry->next) + { + if (ego_entry->ego == ego) + { + /* Rename */ + GNUNET_free(ego_entry->identifier); + ego_entry->identifier = GNUNET_strdup(identifier); + break; + } + } + if (NULL == ego_entry) + { + /* Add */ + ego_entry = GNUNET_new(struct EgoEntry); + GNUNET_IDENTITY_ego_get_public_key(ego, &pk); + ego_entry->keystring = GNUNET_CRYPTO_ecdsa_public_key_to_string(&pk); + ego_entry->ego = ego; + ego_entry->identifier = GNUNET_strdup(identifier); + GNUNET_CONTAINER_DLL_insert_tail(handle->ego_head, + handle->ego_tail, + ego_entry); + } } - } else - { - /* Delete */ - for (ego_entry = handle->ego_head; NULL != ego_entry; - ego_entry = ego_entry->next) { - if (ego_entry->ego == ego) - break; + /* Delete */ + for (ego_entry = handle->ego_head; NULL != ego_entry; + ego_entry = ego_entry->next) + { + if (ego_entry->ego == ego) + break; + } + if (NULL != ego_entry) + GNUNET_CONTAINER_DLL_remove(handle->ego_head, + handle->ego_tail, + ego_entry); } - if (NULL != ego_entry) - GNUNET_CONTAINER_DLL_remove (handle->ego_head, - handle->ego_tail, - ego_entry); - } } static void -rest_identity_process_request (struct GNUNET_REST_RequestHandle *rest_handle, - GNUNET_REST_ResultProcessor proc, - void *proc_cls) +rest_identity_process_request(struct GNUNET_REST_RequestHandle *rest_handle, + GNUNET_REST_ResultProcessor proc, + void *proc_cls) { - struct RequestHandle *handle = GNUNET_new (struct RequestHandle); - handle->oidc = GNUNET_new (struct OIDC_Variables); + struct RequestHandle *handle = GNUNET_new(struct RequestHandle); + + handle->oidc = GNUNET_new(struct OIDC_Variables); if (NULL == OIDC_cookie_jar_map) - OIDC_cookie_jar_map = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO); + OIDC_cookie_jar_map = GNUNET_CONTAINER_multihashmap_create(10, GNUNET_NO); if (NULL == OIDC_access_token_map) OIDC_access_token_map = - GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO); + GNUNET_CONTAINER_multihashmap_create(10, GNUNET_NO); handle->response_code = 0; handle->timeout = GNUNET_TIME_UNIT_FOREVER_REL; handle->proc_cls = proc_cls; @@ -2120,16 +2123,16 @@ rest_identity_process_request (struct GNUNET_REST_RequestHandle *rest_handle, handle->state = ID_REST_STATE_INIT; handle->rest_handle = rest_handle; - handle->url = GNUNET_strdup (rest_handle->url); - if (handle->url[strlen (handle->url) - 1] == '/') - handle->url[strlen (handle->url) - 1] = '\0'; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n"); - handle->identity_handle = GNUNET_IDENTITY_connect (cfg, &list_ego, handle); - handle->gns_handle = GNUNET_GNS_connect (cfg); - handle->namestore_handle = GNUNET_NAMESTORE_connect (cfg); + handle->url = GNUNET_strdup(rest_handle->url); + if (handle->url[strlen(handle->url) - 1] == '/') + handle->url[strlen(handle->url) - 1] = '\0'; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n"); + handle->identity_handle = GNUNET_IDENTITY_connect(cfg, &list_ego, handle); + handle->gns_handle = GNUNET_GNS_connect(cfg); + handle->namestore_handle = GNUNET_NAMESTORE_connect(cfg); handle->timeout_task = - GNUNET_SCHEDULER_add_delayed (handle->timeout, &do_timeout, handle); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected\n"); + GNUNET_SCHEDULER_add_delayed(handle->timeout, &do_timeout, handle); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connected\n"); } /** @@ -2139,7 +2142,7 @@ rest_identity_process_request (struct GNUNET_REST_RequestHandle *rest_handle, * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_rest_openid_connect_init (void *cls) +libgnunet_plugin_rest_openid_connect_init(void *cls) { static struct Plugin plugin; struct GNUNET_REST_Plugin *api; @@ -2147,22 +2150,22 @@ libgnunet_plugin_rest_openid_connect_init (void *cls) cfg = cls; if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.cfg = cfg; - api = GNUNET_new (struct GNUNET_REST_Plugin); + api = GNUNET_new(struct GNUNET_REST_Plugin); api->cls = &plugin; api->name = GNUNET_REST_API_NS_OIDC; api->process_request = &rest_identity_process_request; - GNUNET_asprintf (&allow_methods, - "%s, %s, %s, %s, %s", - MHD_HTTP_METHOD_GET, - MHD_HTTP_METHOD_POST, - MHD_HTTP_METHOD_PUT, - MHD_HTTP_METHOD_DELETE, - MHD_HTTP_METHOD_OPTIONS); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - _ ("OpenID Connect REST API initialized\n")); + GNUNET_asprintf(&allow_methods, + "%s, %s, %s, %s, %s", + MHD_HTTP_METHOD_GET, + MHD_HTTP_METHOD_POST, + MHD_HTTP_METHOD_PUT, + MHD_HTTP_METHOD_DELETE, + MHD_HTTP_METHOD_OPTIONS); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + _("OpenID Connect REST API initialized\n")); return api; } @@ -2174,33 +2177,34 @@ libgnunet_plugin_rest_openid_connect_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_rest_openid_connect_done (void *cls) +libgnunet_plugin_rest_openid_connect_done(void *cls) { struct GNUNET_REST_Plugin *api = cls; struct Plugin *plugin = api->cls; + plugin->cfg = NULL; struct GNUNET_CONTAINER_MultiHashMapIterator *hashmap_it; void *value = NULL; hashmap_it = - GNUNET_CONTAINER_multihashmap_iterator_create (OIDC_cookie_jar_map); + GNUNET_CONTAINER_multihashmap_iterator_create(OIDC_cookie_jar_map); while (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_iterator_next (hashmap_it, NULL, value)) - GNUNET_free_non_null (value); - GNUNET_CONTAINER_multihashmap_iterator_destroy (hashmap_it); - GNUNET_CONTAINER_multihashmap_destroy (OIDC_cookie_jar_map); + GNUNET_CONTAINER_multihashmap_iterator_next(hashmap_it, NULL, value)) + GNUNET_free_non_null(value); + GNUNET_CONTAINER_multihashmap_iterator_destroy(hashmap_it); + GNUNET_CONTAINER_multihashmap_destroy(OIDC_cookie_jar_map); hashmap_it = - GNUNET_CONTAINER_multihashmap_iterator_create (OIDC_access_token_map); + GNUNET_CONTAINER_multihashmap_iterator_create(OIDC_access_token_map); while (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_iterator_next (hashmap_it, NULL, value)) - GNUNET_free_non_null (value); - GNUNET_CONTAINER_multihashmap_destroy (OIDC_access_token_map); - GNUNET_CONTAINER_multihashmap_iterator_destroy (hashmap_it); - GNUNET_free_non_null (allow_methods); - GNUNET_free (api); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "OpenID Connect REST plugin is finished\n"); + GNUNET_CONTAINER_multihashmap_iterator_next(hashmap_it, NULL, value)) + GNUNET_free_non_null(value); + GNUNET_CONTAINER_multihashmap_destroy(OIDC_access_token_map); + GNUNET_CONTAINER_multihashmap_iterator_destroy(hashmap_it); + GNUNET_free_non_null(allow_methods); + GNUNET_free(api); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "OpenID Connect REST plugin is finished\n"); return NULL; } diff --git a/src/reclaim/plugin_rest_reclaim.c b/src/reclaim/plugin_rest_reclaim.c index 3f2577802..176f46ffc 100644 --- a/src/reclaim/plugin_rest_reclaim.c +++ b/src/reclaim/plugin_rest_reclaim.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach * @author Philippe Buschmann @@ -86,16 +86,14 @@ static char *allow_methods; /** * @brief struct returned by the initialization function of the plugin */ -struct Plugin -{ +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; }; /** * The ego list */ -struct EgoEntry -{ +struct EgoEntry { /** * DLL */ @@ -123,8 +121,7 @@ struct EgoEntry }; -struct RequestHandle -{ +struct RequestHandle { /** * Ego list */ @@ -241,55 +238,56 @@ struct RequestHandle * @param handle Handle to clean up */ static void -cleanup_handle (struct RequestHandle *handle) +cleanup_handle(struct RequestHandle *handle) { struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *claim_entry; struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *claim_tmp; struct EgoEntry *ego_entry; struct EgoEntry *ego_tmp; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); if (NULL != handle->resp_object) - json_decref (handle->resp_object); + json_decref(handle->resp_object); if (NULL != handle->timeout_task) - GNUNET_SCHEDULER_cancel (handle->timeout_task); + GNUNET_SCHEDULER_cancel(handle->timeout_task); if (NULL != handle->identity_handle) - GNUNET_IDENTITY_disconnect (handle->identity_handle); + GNUNET_IDENTITY_disconnect(handle->identity_handle); if (NULL != handle->attr_it) - GNUNET_RECLAIM_get_attributes_stop (handle->attr_it); + GNUNET_RECLAIM_get_attributes_stop(handle->attr_it); if (NULL != handle->ticket_it) - GNUNET_RECLAIM_ticket_iteration_stop (handle->ticket_it); + GNUNET_RECLAIM_ticket_iteration_stop(handle->ticket_it); if (NULL != handle->idp) - GNUNET_RECLAIM_disconnect (handle->idp); + GNUNET_RECLAIM_disconnect(handle->idp); if (NULL != handle->url) - GNUNET_free (handle->url); + GNUNET_free(handle->url); if (NULL != handle->emsg) - GNUNET_free (handle->emsg); + GNUNET_free(handle->emsg); if (NULL != handle->attr_list) - { - for (claim_entry = handle->attr_list->list_head; NULL != claim_entry;) { - claim_tmp = claim_entry; - claim_entry = claim_entry->next; - GNUNET_free (claim_tmp->claim); - GNUNET_free (claim_tmp); + for (claim_entry = handle->attr_list->list_head; NULL != claim_entry;) + { + claim_tmp = claim_entry; + claim_entry = claim_entry->next; + GNUNET_free(claim_tmp->claim); + GNUNET_free(claim_tmp); + } + GNUNET_free(handle->attr_list); } - GNUNET_free (handle->attr_list); - } for (ego_entry = handle->ego_head; NULL != ego_entry;) - { - ego_tmp = ego_entry; - ego_entry = ego_entry->next; - GNUNET_free (ego_tmp->identifier); - GNUNET_free (ego_tmp->keystring); - GNUNET_free (ego_tmp); - } - GNUNET_free (handle); + { + ego_tmp = ego_entry; + ego_entry = ego_entry->next; + GNUNET_free(ego_tmp->identifier); + GNUNET_free(ego_tmp->keystring); + GNUNET_free(ego_tmp); + } + GNUNET_free(handle); } static void -cleanup_handle_delayed (void *cls) +cleanup_handle_delayed(void *cls) { - cleanup_handle (cls); + cleanup_handle(cls); } @@ -299,22 +297,22 @@ cleanup_handle_delayed (void *cls) * @param cls the `struct RequestHandle` */ static void -do_error (void *cls) +do_error(void *cls) { struct RequestHandle *handle = cls; struct MHD_Response *resp; char *json_error; - GNUNET_asprintf (&json_error, "{ \"error\" : \"%s\" }", handle->emsg); + GNUNET_asprintf(&json_error, "{ \"error\" : \"%s\" }", handle->emsg); if (0 == handle->response_code) - { - handle->response_code = MHD_HTTP_BAD_REQUEST; - } - resp = GNUNET_REST_create_response (json_error); - MHD_add_response_header (resp, "Content-Type", "application/json"); - handle->proc (handle->proc_cls, resp, handle->response_code); - GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle); - GNUNET_free (json_error); + { + handle->response_code = MHD_HTTP_BAD_REQUEST; + } + resp = GNUNET_REST_create_response(json_error); + MHD_add_response_header(resp, "Content-Type", "application/json"); + handle->proc(handle->proc_cls, resp, handle->response_code); + GNUNET_SCHEDULER_add_now(&cleanup_handle_delayed, handle); + GNUNET_free(json_error); } @@ -324,37 +322,37 @@ do_error (void *cls) * @param cls the `struct RequestHandle` */ static void -do_timeout (void *cls) +do_timeout(void *cls) { struct RequestHandle *handle = cls; handle->timeout_task = NULL; - do_error (handle); + do_error(handle); } static void -collect_error_cb (void *cls) +collect_error_cb(void *cls) { struct RequestHandle *handle = cls; - do_error (handle); + do_error(handle); } static void -finished_cont (void *cls, int32_t success, const char *emsg) +finished_cont(void *cls, int32_t success, const char *emsg) { struct RequestHandle *handle = cls; struct MHD_Response *resp; - resp = GNUNET_REST_create_response (emsg); + resp = GNUNET_REST_create_response(emsg); if (GNUNET_OK != success) - { - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle); + { + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_SCHEDULER_add_now(&cleanup_handle_delayed, handle); } @@ -364,28 +362,29 @@ finished_cont (void *cls, int32_t success, const char *emsg) * @param cls the request handle */ static void -return_response (void *cls) +return_response(void *cls) { char *result_str; struct RequestHandle *handle = cls; struct MHD_Response *resp; - result_str = json_dumps (handle->resp_object, 0); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result_str); - resp = GNUNET_REST_create_response (result_str); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_free (result_str); - cleanup_handle (handle); + result_str = json_dumps(handle->resp_object, 0); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Result %s\n", result_str); + resp = GNUNET_REST_create_response(result_str); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_free(result_str); + cleanup_handle(handle); } static void -collect_finished_cb (void *cls) +collect_finished_cb(void *cls) { struct RequestHandle *handle = cls; + // Done handle->attr_it = NULL; handle->ticket_it = NULL; - GNUNET_SCHEDULER_add_now (&return_response, handle); + GNUNET_SCHEDULER_add_now(&return_response, handle); } @@ -394,38 +393,38 @@ collect_finished_cb (void *cls) * */ static void -ticket_collect (void *cls, const struct GNUNET_RECLAIM_Ticket *ticket) +ticket_collect(void *cls, const struct GNUNET_RECLAIM_Ticket *ticket) { json_t *json_resource; struct RequestHandle *handle = cls; json_t *value; char *tmp; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding ticket\n"); - tmp = GNUNET_STRINGS_data_to_string_alloc (&ticket->rnd, sizeof (uint64_t)); - json_resource = json_object (); - GNUNET_free (tmp); - json_array_append (handle->resp_object, json_resource); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding ticket\n"); + tmp = GNUNET_STRINGS_data_to_string_alloc(&ticket->rnd, sizeof(uint64_t)); + json_resource = json_object(); + GNUNET_free(tmp); + json_array_append(handle->resp_object, json_resource); tmp = - GNUNET_STRINGS_data_to_string_alloc (&ticket->identity, - sizeof (struct - GNUNET_CRYPTO_EcdsaPublicKey)); - value = json_string (tmp); - json_object_set_new (json_resource, "issuer", value); - GNUNET_free (tmp); + GNUNET_STRINGS_data_to_string_alloc(&ticket->identity, + sizeof(struct + GNUNET_CRYPTO_EcdsaPublicKey)); + value = json_string(tmp); + json_object_set_new(json_resource, "issuer", value); + GNUNET_free(tmp); tmp = - GNUNET_STRINGS_data_to_string_alloc (&ticket->audience, - sizeof (struct - GNUNET_CRYPTO_EcdsaPublicKey)); - value = json_string (tmp); - json_object_set_new (json_resource, "audience", value); - GNUNET_free (tmp); - tmp = GNUNET_STRINGS_data_to_string_alloc (&ticket->rnd, sizeof (uint64_t)); - value = json_string (tmp); - json_object_set_new (json_resource, "rnd", value); - GNUNET_free (tmp); - GNUNET_RECLAIM_ticket_iteration_next (handle->ticket_it); + GNUNET_STRINGS_data_to_string_alloc(&ticket->audience, + sizeof(struct + GNUNET_CRYPTO_EcdsaPublicKey)); + value = json_string(tmp); + json_object_set_new(json_resource, "audience", value); + GNUNET_free(tmp); + tmp = GNUNET_STRINGS_data_to_string_alloc(&ticket->rnd, sizeof(uint64_t)); + value = json_string(tmp); + json_object_set_new(json_resource, "rnd", value); + GNUNET_free(tmp); + GNUNET_RECLAIM_ticket_iteration_next(handle->ticket_it); } @@ -437,57 +436,57 @@ ticket_collect (void *cls, const struct GNUNET_RECLAIM_Ticket *ticket) * @param cls the RequestHandle */ static void -list_tickets_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +list_tickets_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv_key; struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; char *identity; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Getting tickets for %s.\n", - handle->url); - if (strlen (GNUNET_REST_API_NS_IDENTITY_TICKETS) >= strlen (handle->url)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No identity given.\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - identity = handle->url + strlen (GNUNET_REST_API_NS_IDENTITY_TICKETS) + 1; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Getting tickets for %s.\n", + handle->url); + if (strlen(GNUNET_REST_API_NS_IDENTITY_TICKETS) >= strlen(handle->url)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No identity given.\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + identity = handle->url + strlen(GNUNET_REST_API_NS_IDENTITY_TICKETS) + 1; for (ego_entry = handle->ego_head; NULL != ego_entry; ego_entry = ego_entry->next) - if (0 == strcmp (identity, ego_entry->identifier)) + if (0 == strcmp(identity, ego_entry->identifier)) break; - handle->resp_object = json_array (); + handle->resp_object = json_array(); if (NULL == ego_entry) - { - // Done - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Ego %s not found.\n", identity); - GNUNET_SCHEDULER_add_now (&return_response, handle); - return; - } - priv_key = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego); - handle->idp = GNUNET_RECLAIM_connect (cfg); + { + // Done + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Ego %s not found.\n", identity); + GNUNET_SCHEDULER_add_now(&return_response, handle); + return; + } + priv_key = GNUNET_IDENTITY_ego_get_private_key(ego_entry->ego); + handle->idp = GNUNET_RECLAIM_connect(cfg); handle->ticket_it = - GNUNET_RECLAIM_ticket_iteration_start (handle->idp, - priv_key, - &collect_error_cb, - handle, - &ticket_collect, - handle, - &collect_finished_cb, - handle); + GNUNET_RECLAIM_ticket_iteration_start(handle->idp, + priv_key, + &collect_error_cb, + handle, + &ticket_collect, + handle, + &collect_finished_cb, + handle); } static void -add_attribute_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +add_attribute_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity_priv; const char *identity; @@ -499,68 +498,68 @@ add_attribute_cont (struct GNUNET_REST_RequestHandle *con_handle, json_t *data_json; json_error_t err; struct GNUNET_JSON_Specification attrspec[] = - {GNUNET_RECLAIM_JSON_spec_claim (&attribute), GNUNET_JSON_spec_end ()}; - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Adding an attribute for %s.\n", - handle->url); - if (strlen (GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES) >= strlen (handle->url)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No identity given.\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - identity = handle->url + strlen (GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES) + 1; + { GNUNET_RECLAIM_JSON_spec_claim(&attribute), GNUNET_JSON_spec_end() }; + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Adding an attribute for %s.\n", + handle->url); + if (strlen(GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES) >= strlen(handle->url)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No identity given.\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + identity = handle->url + strlen(GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES) + 1; for (ego_entry = handle->ego_head; NULL != ego_entry; ego_entry = ego_entry->next) - if (0 == strcmp (identity, ego_entry->identifier)) + if (0 == strcmp(identity, ego_entry->identifier)) break; if (NULL == ego_entry) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Identity unknown (%s)\n", identity); - return; - } - identity_priv = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Identity unknown (%s)\n", identity); + return; + } + identity_priv = GNUNET_IDENTITY_ego_get_private_key(ego_entry->ego); if (0 >= handle->rest_handle->data_size) - { - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } term_data[handle->rest_handle->data_size] = '\0'; - GNUNET_memcpy (term_data, - handle->rest_handle->data, - handle->rest_handle->data_size); - data_json = json_loads (term_data, JSON_DECODE_ANY, &err); - GNUNET_assert (GNUNET_OK == - GNUNET_JSON_parse (data_json, attrspec, NULL, NULL)); - json_decref (data_json); + GNUNET_memcpy(term_data, + handle->rest_handle->data, + handle->rest_handle->data_size); + data_json = json_loads(term_data, JSON_DECODE_ANY, &err); + GNUNET_assert(GNUNET_OK == + GNUNET_JSON_parse(data_json, attrspec, NULL, NULL)); + json_decref(data_json); if (NULL == attribute) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse attribute from %s\n", - term_data); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse attribute from %s\n", + term_data); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } /** * New ID for attribute */ if (0 == attribute->id) attribute->id = - GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX); - handle->idp = GNUNET_RECLAIM_connect (cfg); + GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX); + handle->idp = GNUNET_RECLAIM_connect(cfg); exp = GNUNET_TIME_UNIT_HOURS; - handle->idp_op = GNUNET_RECLAIM_attribute_store (handle->idp, - identity_priv, - attribute, - &exp, - &finished_cont, - handle); - GNUNET_JSON_parse_free (attrspec); + handle->idp_op = GNUNET_RECLAIM_attribute_store(handle->idp, + identity_priv, + attribute, + &exp, + &finished_cont, + handle); + GNUNET_JSON_parse_free(attrspec); } @@ -569,9 +568,9 @@ add_attribute_cont (struct GNUNET_REST_RequestHandle *con_handle, * */ static void -attr_collect (void *cls, - const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, - const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) +attr_collect(void *cls, + const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, + const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) { struct RequestHandle *handle = cls; json_t *attr_obj; @@ -580,28 +579,28 @@ attr_collect (void *cls, char *id_str; if ((NULL == attr->name) || (NULL == attr->data)) - { - GNUNET_RECLAIM_get_attributes_next (handle->attr_it); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding attribute: %s\n", attr->name); - - tmp_value = GNUNET_RECLAIM_ATTRIBUTE_value_to_string (attr->type, - attr->data, - attr->data_size); - - attr_obj = json_object (); - json_object_set_new (attr_obj, "value", json_string (tmp_value)); - json_object_set_new (attr_obj, "name", json_string (attr->name)); - type = GNUNET_RECLAIM_ATTRIBUTE_number_to_typename (attr->type); - json_object_set_new (attr_obj, "type", json_string (type)); - id_str = GNUNET_STRINGS_data_to_string_alloc (&attr->id, sizeof (uint64_t)); - json_object_set_new (attr_obj, "id", json_string (id_str)); - json_array_append (handle->resp_object, attr_obj); - json_decref (attr_obj); - GNUNET_free (tmp_value); - GNUNET_RECLAIM_get_attributes_next (handle->attr_it); + { + GNUNET_RECLAIM_get_attributes_next(handle->attr_it); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding attribute: %s\n", attr->name); + + tmp_value = GNUNET_RECLAIM_ATTRIBUTE_value_to_string(attr->type, + attr->data, + attr->data_size); + + attr_obj = json_object(); + json_object_set_new(attr_obj, "value", json_string(tmp_value)); + json_object_set_new(attr_obj, "name", json_string(attr->name)); + type = GNUNET_RECLAIM_ATTRIBUTE_number_to_typename(attr->type); + json_object_set_new(attr_obj, "type", json_string(type)); + id_str = GNUNET_STRINGS_data_to_string_alloc(&attr->id, sizeof(uint64_t)); + json_object_set_new(attr_obj, "id", json_string(id_str)); + json_array_append(handle->resp_object, attr_obj); + json_decref(attr_obj); + GNUNET_free(tmp_value); + GNUNET_RECLAIM_get_attributes_next(handle->attr_it); } @@ -613,67 +612,67 @@ attr_collect (void *cls, * @param cls the RequestHandle */ static void -list_attribute_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +list_attribute_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv_key; struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; char *identity; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Getting attributes for %s.\n", - handle->url); - if (strlen (GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES) >= strlen (handle->url)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No identity given.\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - identity = handle->url + strlen (GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES) + 1; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Getting attributes for %s.\n", + handle->url); + if (strlen(GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES) >= strlen(handle->url)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No identity given.\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + identity = handle->url + strlen(GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES) + 1; for (ego_entry = handle->ego_head; NULL != ego_entry; ego_entry = ego_entry->next) - if (0 == strcmp (identity, ego_entry->identifier)) + if (0 == strcmp(identity, ego_entry->identifier)) break; - handle->resp_object = json_array (); + handle->resp_object = json_array(); if (NULL == ego_entry) - { - // Done - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Ego %s not found.\n", identity); - GNUNET_SCHEDULER_add_now (&return_response, handle); - return; - } - priv_key = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego); - handle->idp = GNUNET_RECLAIM_connect (cfg); - handle->attr_it = GNUNET_RECLAIM_get_attributes_start (handle->idp, - priv_key, - &collect_error_cb, - handle, - &attr_collect, - handle, - &collect_finished_cb, - handle); + { + // Done + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Ego %s not found.\n", identity); + GNUNET_SCHEDULER_add_now(&return_response, handle); + return; + } + priv_key = GNUNET_IDENTITY_ego_get_private_key(ego_entry->ego); + handle->idp = GNUNET_RECLAIM_connect(cfg); + handle->attr_it = GNUNET_RECLAIM_get_attributes_start(handle->idp, + priv_key, + &collect_error_cb, + handle, + &attr_collect, + handle, + &collect_finished_cb, + handle); } static void -delete_finished_cb (void *cls, int32_t success, const char *emsg) +delete_finished_cb(void *cls, int32_t success, const char *emsg) { struct RequestHandle *handle = cls; struct MHD_Response *resp; - resp = GNUNET_REST_create_response (emsg); + resp = GNUNET_REST_create_response(emsg); if (GNUNET_OK != success) - { - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - GNUNET_SCHEDULER_add_now (&cleanup_handle_delayed, handle); + { + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + GNUNET_SCHEDULER_add_now(&cleanup_handle_delayed, handle); } @@ -685,9 +684,9 @@ delete_finished_cb (void *cls, int32_t success, const char *emsg) * @param cls the RequestHandle */ static void -delete_attribute_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +delete_attribute_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv_key; struct RequestHandle *handle = cls; @@ -697,56 +696,56 @@ delete_attribute_cont (struct GNUNET_REST_RequestHandle *con_handle, char *identity; char *id; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Deleting attributes.\n"); - if (strlen (GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES) >= strlen (handle->url)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No identity given.\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Deleting attributes.\n"); + if (strlen(GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES) >= strlen(handle->url)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No identity given.\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } identity_id_str = - strdup (handle->url + strlen (GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES) + 1); - identity = strtok (identity_id_str, "/"); - id = strtok (NULL, "/"); + strdup(handle->url + strlen(GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES) + 1); + identity = strtok(identity_id_str, "/"); + id = strtok(NULL, "/"); if ((NULL == identity) || (NULL == id)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Malformed request.\n"); - GNUNET_free (identity_id_str); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Malformed request.\n"); + GNUNET_free(identity_id_str); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } for (ego_entry = handle->ego_head; NULL != ego_entry; ego_entry = ego_entry->next) - if (0 == strcmp (identity, ego_entry->identifier)) + if (0 == strcmp(identity, ego_entry->identifier)) break; - handle->resp_object = json_array (); + handle->resp_object = json_array(); if (NULL == ego_entry) - { - // Done - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Ego %s not found.\n", identity); - GNUNET_free (identity_id_str); - GNUNET_SCHEDULER_add_now (&return_response, handle); - return; - } - priv_key = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego); - handle->idp = GNUNET_RECLAIM_connect (cfg); - memset (&attr, 0, sizeof (struct GNUNET_RECLAIM_ATTRIBUTE_Claim)); - GNUNET_STRINGS_string_to_data (id, strlen (id), &attr.id, sizeof (uint64_t)); + { + // Done + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Ego %s not found.\n", identity); + GNUNET_free(identity_id_str); + GNUNET_SCHEDULER_add_now(&return_response, handle); + return; + } + priv_key = GNUNET_IDENTITY_ego_get_private_key(ego_entry->ego); + handle->idp = GNUNET_RECLAIM_connect(cfg); + memset(&attr, 0, sizeof(struct GNUNET_RECLAIM_ATTRIBUTE_Claim)); + GNUNET_STRINGS_string_to_data(id, strlen(id), &attr.id, sizeof(uint64_t)); attr.name = ""; - handle->idp_op = GNUNET_RECLAIM_attribute_delete (handle->idp, - priv_key, - &attr, - &delete_finished_cb, - handle); - GNUNET_free (identity_id_str); + handle->idp_op = GNUNET_RECLAIM_attribute_delete(handle->idp, + priv_key, + &attr, + &delete_finished_cb, + handle); + GNUNET_free(identity_id_str); } static void -revoke_ticket_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +revoke_ticket_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity_priv; struct RequestHandle *handle = cls; @@ -757,101 +756,101 @@ revoke_ticket_cont (struct GNUNET_REST_RequestHandle *con_handle, json_t *data_json; json_error_t err; struct GNUNET_JSON_Specification tktspec[] = - {GNUNET_RECLAIM_JSON_spec_ticket (&ticket), GNUNET_JSON_spec_end ()}; + { GNUNET_RECLAIM_JSON_spec_ticket(&ticket), GNUNET_JSON_spec_end() }; if (0 >= handle->rest_handle->data_size) - { - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } term_data[handle->rest_handle->data_size] = '\0'; - GNUNET_memcpy (term_data, - handle->rest_handle->data, - handle->rest_handle->data_size); - data_json = json_loads (term_data, JSON_DECODE_ANY, &err); + GNUNET_memcpy(term_data, + handle->rest_handle->data, + handle->rest_handle->data_size); + data_json = json_loads(term_data, JSON_DECODE_ANY, &err); if ((NULL == data_json) || - (GNUNET_OK != GNUNET_JSON_parse (data_json, tktspec, NULL, NULL))) - { - handle->emsg = GNUNET_strdup ("Not a ticket!\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - GNUNET_JSON_parse_free (tktspec); - if (NULL != data_json) - json_decref (data_json); - return; - } - json_decref (data_json); + (GNUNET_OK != GNUNET_JSON_parse(data_json, tktspec, NULL, NULL))) + { + handle->emsg = GNUNET_strdup("Not a ticket!\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + GNUNET_JSON_parse_free(tktspec); + if (NULL != data_json) + json_decref(data_json); + return; + } + json_decref(data_json); if (NULL == ticket) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse ticket from %s\n", - term_data); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse ticket from %s\n", + term_data); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } for (ego_entry = handle->ego_head; NULL != ego_entry; ego_entry = ego_entry->next) - { - GNUNET_IDENTITY_ego_get_public_key (ego_entry->ego, &tmp_pk); - if (0 == memcmp (&ticket->identity, - &tmp_pk, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey))) - break; - } + { + GNUNET_IDENTITY_ego_get_public_key(ego_entry->ego, &tmp_pk); + if (0 == memcmp(&ticket->identity, + &tmp_pk, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey))) + break; + } if (NULL == ego_entry) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Identity unknown\n"); - GNUNET_JSON_parse_free (tktspec); - return; - } - identity_priv = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego); - - handle->idp = GNUNET_RECLAIM_connect (cfg); - handle->idp_op = GNUNET_RECLAIM_ticket_revoke (handle->idp, - identity_priv, - ticket, - &finished_cont, - handle); - GNUNET_JSON_parse_free (tktspec); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Identity unknown\n"); + GNUNET_JSON_parse_free(tktspec); + return; + } + identity_priv = GNUNET_IDENTITY_ego_get_private_key(ego_entry->ego); + + handle->idp = GNUNET_RECLAIM_connect(cfg); + handle->idp_op = GNUNET_RECLAIM_ticket_revoke(handle->idp, + identity_priv, + ticket, + &finished_cont, + handle); + GNUNET_JSON_parse_free(tktspec); } static void -consume_cont (void *cls, - const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, - const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) +consume_cont(void *cls, + const struct GNUNET_CRYPTO_EcdsaPublicKey *identity, + const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr) { struct RequestHandle *handle = cls; char *val_str; json_t *value; if (NULL == identity) - { - GNUNET_SCHEDULER_add_now (&return_response, handle); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding attribute: %s\n", attr->name); - val_str = GNUNET_RECLAIM_ATTRIBUTE_value_to_string (attr->type, - attr->data, - attr->data_size); + { + GNUNET_SCHEDULER_add_now(&return_response, handle); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding attribute: %s\n", attr->name); + val_str = GNUNET_RECLAIM_ATTRIBUTE_value_to_string(attr->type, + attr->data, + attr->data_size); if (NULL == val_str) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to parse value for: %s\n", - attr->name); - return; - } - value = json_string (val_str); - json_object_set_new (handle->resp_object, attr->name, value); - json_decref (value); - GNUNET_free (val_str); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to parse value for: %s\n", + attr->name); + return; + } + value = json_string(val_str); + json_object_set_new(handle->resp_object, attr->name, value); + json_decref(value); + GNUNET_free(val_str); } static void -consume_ticket_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +consume_ticket_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity_priv; struct RequestHandle *handle = cls; @@ -862,59 +861,59 @@ consume_ticket_cont (struct GNUNET_REST_RequestHandle *con_handle, json_t *data_json; json_error_t err; struct GNUNET_JSON_Specification tktspec[] = - {GNUNET_RECLAIM_JSON_spec_ticket (&ticket), GNUNET_JSON_spec_end ()}; + { GNUNET_RECLAIM_JSON_spec_ticket(&ticket), GNUNET_JSON_spec_end() }; if (0 >= handle->rest_handle->data_size) - { - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } term_data[handle->rest_handle->data_size] = '\0'; - GNUNET_memcpy (term_data, - handle->rest_handle->data, - handle->rest_handle->data_size); - data_json = json_loads (term_data, JSON_DECODE_ANY, &err); + GNUNET_memcpy(term_data, + handle->rest_handle->data, + handle->rest_handle->data_size); + data_json = json_loads(term_data, JSON_DECODE_ANY, &err); if (NULL == data_json) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse JSON Object from %s\n", - term_data); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - if (GNUNET_OK != GNUNET_JSON_parse (data_json, tktspec, NULL, NULL)) - { - handle->emsg = GNUNET_strdup ("Not a ticket!\n"); - GNUNET_SCHEDULER_add_now (&do_error, handle); - GNUNET_JSON_parse_free (tktspec); - json_decref (data_json); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse JSON Object from %s\n", + term_data); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + if (GNUNET_OK != GNUNET_JSON_parse(data_json, tktspec, NULL, NULL)) + { + handle->emsg = GNUNET_strdup("Not a ticket!\n"); + GNUNET_SCHEDULER_add_now(&do_error, handle); + GNUNET_JSON_parse_free(tktspec); + json_decref(data_json); + return; + } for (ego_entry = handle->ego_head; NULL != ego_entry; ego_entry = ego_entry->next) - { - GNUNET_IDENTITY_ego_get_public_key (ego_entry->ego, &tmp_pk); - if (0 == memcmp (&ticket->audience, - &tmp_pk, - sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey))) - break; - } + { + GNUNET_IDENTITY_ego_get_public_key(ego_entry->ego, &tmp_pk); + if (0 == memcmp(&ticket->audience, + &tmp_pk, + sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey))) + break; + } if (NULL == ego_entry) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Identity unknown\n"); - GNUNET_JSON_parse_free (tktspec); - return; - } - identity_priv = GNUNET_IDENTITY_ego_get_private_key (ego_entry->ego); - handle->resp_object = json_object (); - handle->idp = GNUNET_RECLAIM_connect (cfg); - handle->idp_op = GNUNET_RECLAIM_ticket_consume (handle->idp, - identity_priv, - ticket, - &consume_cont, - handle); - GNUNET_JSON_parse_free (tktspec); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Identity unknown\n"); + GNUNET_JSON_parse_free(tktspec); + return; + } + identity_priv = GNUNET_IDENTITY_ego_get_private_key(ego_entry->ego); + handle->resp_object = json_object(); + handle->idp = GNUNET_RECLAIM_connect(cfg); + handle->idp_op = GNUNET_RECLAIM_ticket_consume(handle->idp, + identity_priv, + ticket, + &consume_cont, + handle); + GNUNET_JSON_parse_free(tktspec); } @@ -926,18 +925,18 @@ consume_ticket_cont (struct GNUNET_REST_RequestHandle *con_handle, * @param cls the RequestHandle */ static void -options_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +options_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct MHD_Response *resp; struct RequestHandle *handle = cls; // For now, independent of path return all options - resp = GNUNET_REST_create_response (NULL); - MHD_add_response_header (resp, "Access-Control-Allow-Methods", allow_methods); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - cleanup_handle (handle); + resp = GNUNET_REST_create_response(NULL); + MHD_add_response_header(resp, "Access-Control-Allow-Methods", allow_methods); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + cleanup_handle(handle); return; } @@ -947,37 +946,37 @@ options_cont (struct GNUNET_REST_RequestHandle *con_handle, * @param handle the request handle */ static void -init_cont (struct RequestHandle *handle) +init_cont(struct RequestHandle *handle) { struct GNUNET_REST_RequestHandlerError err; static const struct GNUNET_REST_RequestHandler handlers[] = - {{MHD_HTTP_METHOD_GET, - GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES, - &list_attribute_cont}, - {MHD_HTTP_METHOD_POST, + { { MHD_HTTP_METHOD_GET, GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES, - &add_attribute_cont}, - {MHD_HTTP_METHOD_DELETE, - GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES, - &delete_attribute_cont}, - {MHD_HTTP_METHOD_GET, - GNUNET_REST_API_NS_IDENTITY_TICKETS, - &list_tickets_cont}, - {MHD_HTTP_METHOD_POST, - GNUNET_REST_API_NS_IDENTITY_REVOKE, - &revoke_ticket_cont}, - {MHD_HTTP_METHOD_POST, - GNUNET_REST_API_NS_IDENTITY_CONSUME, - &consume_ticket_cont}, - {MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_RECLAIM, &options_cont}, - GNUNET_REST_HANDLER_END}; + &list_attribute_cont }, + { MHD_HTTP_METHOD_POST, + GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES, + &add_attribute_cont }, + { MHD_HTTP_METHOD_DELETE, + GNUNET_REST_API_NS_RECLAIM_ATTRIBUTES, + &delete_attribute_cont }, + { MHD_HTTP_METHOD_GET, + GNUNET_REST_API_NS_IDENTITY_TICKETS, + &list_tickets_cont }, + { MHD_HTTP_METHOD_POST, + GNUNET_REST_API_NS_IDENTITY_REVOKE, + &revoke_ticket_cont }, + { MHD_HTTP_METHOD_POST, + GNUNET_REST_API_NS_IDENTITY_CONSUME, + &consume_ticket_cont }, + { MHD_HTTP_METHOD_OPTIONS, GNUNET_REST_API_NS_RECLAIM, &options_cont }, + GNUNET_REST_HANDLER_END }; if (GNUNET_NO == - GNUNET_REST_handle_request (handle->rest_handle, handlers, &err, handle)) - { - handle->response_code = err.error_code; - GNUNET_SCHEDULER_add_now (&do_error, handle); - } + GNUNET_REST_handle_request(handle->rest_handle, handlers, &err, handle)) + { + handle->response_code = err.error_code; + GNUNET_SCHEDULER_add_now(&do_error, handle); + } } /** @@ -1014,40 +1013,41 @@ init_cont (struct RequestHandle *handle) * must thus no longer be used */ static void -list_ego (void *cls, - struct GNUNET_IDENTITY_Ego *ego, - void **ctx, - const char *identifier) +list_ego(void *cls, + struct GNUNET_IDENTITY_Ego *ego, + void **ctx, + const char *identifier) { struct RequestHandle *handle = cls; struct EgoEntry *ego_entry; struct GNUNET_CRYPTO_EcdsaPublicKey pk; if ((NULL == ego) && (ID_REST_STATE_INIT == handle->state)) - { - handle->state = ID_REST_STATE_POST_INIT; - init_cont (handle); - return; - } + { + handle->state = ID_REST_STATE_POST_INIT; + init_cont(handle); + return; + } if (ID_REST_STATE_INIT == handle->state) - { - ego_entry = GNUNET_new (struct EgoEntry); - GNUNET_IDENTITY_ego_get_public_key (ego, &pk); - ego_entry->keystring = GNUNET_CRYPTO_ecdsa_public_key_to_string (&pk); - ego_entry->ego = ego; - ego_entry->identifier = GNUNET_strdup (identifier); - GNUNET_CONTAINER_DLL_insert_tail (handle->ego_head, - handle->ego_tail, - ego_entry); - } + { + ego_entry = GNUNET_new(struct EgoEntry); + GNUNET_IDENTITY_ego_get_public_key(ego, &pk); + ego_entry->keystring = GNUNET_CRYPTO_ecdsa_public_key_to_string(&pk); + ego_entry->ego = ego; + ego_entry->identifier = GNUNET_strdup(identifier); + GNUNET_CONTAINER_DLL_insert_tail(handle->ego_head, + handle->ego_tail, + ego_entry); + } } static void -rest_identity_process_request (struct GNUNET_REST_RequestHandle *rest_handle, - GNUNET_REST_ResultProcessor proc, - void *proc_cls) +rest_identity_process_request(struct GNUNET_REST_RequestHandle *rest_handle, + GNUNET_REST_ResultProcessor proc, + void *proc_cls) { - struct RequestHandle *handle = GNUNET_new (struct RequestHandle); + struct RequestHandle *handle = GNUNET_new(struct RequestHandle); + handle->response_code = 0; handle->timeout = GNUNET_TIME_UNIT_FOREVER_REL; handle->proc_cls = proc_cls; @@ -1055,14 +1055,14 @@ rest_identity_process_request (struct GNUNET_REST_RequestHandle *rest_handle, handle->state = ID_REST_STATE_INIT; handle->rest_handle = rest_handle; - handle->url = GNUNET_strdup (rest_handle->url); - if (handle->url[strlen (handle->url) - 1] == '/') - handle->url[strlen (handle->url) - 1] = '\0'; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n"); - handle->identity_handle = GNUNET_IDENTITY_connect (cfg, &list_ego, handle); + handle->url = GNUNET_strdup(rest_handle->url); + if (handle->url[strlen(handle->url) - 1] == '/') + handle->url[strlen(handle->url) - 1] = '\0'; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting...\n"); + handle->identity_handle = GNUNET_IDENTITY_connect(cfg, &list_ego, handle); handle->timeout_task = - GNUNET_SCHEDULER_add_delayed (handle->timeout, &do_timeout, handle); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected\n"); + GNUNET_SCHEDULER_add_delayed(handle->timeout, &do_timeout, handle); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connected\n"); } /** @@ -1072,7 +1072,7 @@ rest_identity_process_request (struct GNUNET_REST_RequestHandle *rest_handle, * @return NULL on error, otherwise the plugin context */ void * -libgnunet_plugin_rest_reclaim_init (void *cls) +libgnunet_plugin_rest_reclaim_init(void *cls) { static struct Plugin plugin; struct GNUNET_REST_Plugin *api; @@ -1080,22 +1080,22 @@ libgnunet_plugin_rest_reclaim_init (void *cls) cfg = cls; if (NULL != plugin.cfg) return NULL; /* can only initialize once! */ - memset (&plugin, 0, sizeof (struct Plugin)); + memset(&plugin, 0, sizeof(struct Plugin)); plugin.cfg = cfg; - api = GNUNET_new (struct GNUNET_REST_Plugin); + api = GNUNET_new(struct GNUNET_REST_Plugin); api->cls = &plugin; api->name = GNUNET_REST_API_NS_RECLAIM; api->process_request = &rest_identity_process_request; - GNUNET_asprintf (&allow_methods, - "%s, %s, %s, %s, %s", - MHD_HTTP_METHOD_GET, - MHD_HTTP_METHOD_POST, - MHD_HTTP_METHOD_PUT, - MHD_HTTP_METHOD_DELETE, - MHD_HTTP_METHOD_OPTIONS); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - _ ("Identity Provider REST API initialized\n")); + GNUNET_asprintf(&allow_methods, + "%s, %s, %s, %s, %s", + MHD_HTTP_METHOD_GET, + MHD_HTTP_METHOD_POST, + MHD_HTTP_METHOD_PUT, + MHD_HTTP_METHOD_DELETE, + MHD_HTTP_METHOD_OPTIONS); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + _("Identity Provider REST API initialized\n")); return api; } @@ -1107,16 +1107,17 @@ libgnunet_plugin_rest_reclaim_init (void *cls) * @return always NULL */ void * -libgnunet_plugin_rest_reclaim_done (void *cls) +libgnunet_plugin_rest_reclaim_done(void *cls) { struct GNUNET_REST_Plugin *api = cls; struct Plugin *plugin = api->cls; + plugin->cfg = NULL; - GNUNET_free_non_null (allow_methods); - GNUNET_free (api); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Identity Provider REST plugin is finished\n"); + GNUNET_free_non_null(allow_methods); + GNUNET_free(api); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Identity Provider REST plugin is finished\n"); return NULL; } diff --git a/src/reclaim/reclaim.h b/src/reclaim/reclaim.h index 3c7c05a10..87e343b51 100644 --- a/src/reclaim/reclaim.h +++ b/src/reclaim/reclaim.h @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Martin Schanzenbach @@ -37,8 +37,7 @@ GNUNET_NETWORK_STRUCT_BEGIN /** * Use to store an identity attribute */ -struct AttributeStoreMessage -{ +struct AttributeStoreMessage { /** * Type: #GNUNET_MESSAGE_TYPE_IDENTITY_SET_DEFAULT */ @@ -71,8 +70,7 @@ struct AttributeStoreMessage /** * Use to delete an identity attribute */ -struct AttributeDeleteMessage -{ +struct AttributeDeleteMessage { /** * Type: #GNUNET_MESSAGE_TYPE_IDENTITY_SET_DEFAULT */ @@ -100,8 +98,7 @@ struct AttributeDeleteMessage /** * Attribute store/delete response message */ -struct SuccessResultMessage -{ +struct SuccessResultMessage { /** * Message header */ @@ -121,8 +118,7 @@ struct SuccessResultMessage /** * Attribute is returned from the idp. */ -struct AttributeResultMessage -{ +struct AttributeResultMessage { /** * Message header */ @@ -157,8 +153,7 @@ struct AttributeResultMessage /** * Start a attribute iteration for the given identity */ -struct AttributeIterationStartMessage -{ +struct AttributeIterationStartMessage { /** * Message */ @@ -179,8 +174,7 @@ struct AttributeIterationStartMessage /** * Ask for next result of attribute iteration for the given operation */ -struct AttributeIterationNextMessage -{ +struct AttributeIterationNextMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_NEXT */ @@ -196,8 +190,7 @@ struct AttributeIterationNextMessage /** * Stop attribute iteration for the given operation */ -struct AttributeIterationStopMessage -{ +struct AttributeIterationStopMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_STOP */ @@ -212,8 +205,7 @@ struct AttributeIterationStopMessage /** * Start a ticket iteration for the given identity */ -struct TicketIterationStartMessage -{ +struct TicketIterationStartMessage { /** * Message */ @@ -234,8 +226,7 @@ struct TicketIterationStartMessage /** * Ask for next result of ticket iteration for the given operation */ -struct TicketIterationNextMessage -{ +struct TicketIterationNextMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_NEXT */ @@ -251,8 +242,7 @@ struct TicketIterationNextMessage /** * Stop ticket iteration for the given operation */ -struct TicketIterationStopMessage -{ +struct TicketIterationStopMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_STOP */ @@ -268,8 +258,7 @@ struct TicketIterationStopMessage /** * Ticket issue message */ -struct IssueTicketMessage -{ +struct IssueTicketMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_RECLAIM_ISSUE_TICKET */ @@ -301,8 +290,7 @@ struct IssueTicketMessage /** * Ticket revoke message */ -struct RevokeTicketMessage -{ +struct RevokeTicketMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_RECLAIM_REVOKE_TICKET */ @@ -332,8 +320,7 @@ struct RevokeTicketMessage /** * Ticket revoke message */ -struct RevokeTicketResultMessage -{ +struct RevokeTicketResultMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_RECLAIM_REVOKE_TICKET_RESULT */ @@ -354,8 +341,7 @@ struct RevokeTicketResultMessage /** * Ticket result message */ -struct TicketResultMessage -{ +struct TicketResultMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_RESULT */ @@ -375,8 +361,7 @@ struct TicketResultMessage /** * Ticket consume message */ -struct ConsumeTicketMessage -{ +struct ConsumeTicketMessage { /** * Type will be #GNUNET_MESSAGE_TYPE_RECLAIM_CONSUME_TICKET */ @@ -401,8 +386,7 @@ struct ConsumeTicketMessage /** * Attribute list is returned from the idp. */ -struct ConsumeTicketResultMessage -{ +struct ConsumeTicketResultMessage { /** * Message header */ diff --git a/src/reclaim/reclaim_api.c b/src/reclaim/reclaim_api.c index 725b2b876..a8790cd8e 100644 --- a/src/reclaim/reclaim_api.c +++ b/src/reclaim/reclaim_api.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @file reclaim/reclaim_api.c @@ -32,15 +32,13 @@ #include "gnunet_reclaim_service.h" #include "reclaim.h" -#define LOG(kind, ...) GNUNET_log_from (kind, "reclaim-api", __VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "reclaim-api", __VA_ARGS__) /** * Handle for an operation with the service. */ -struct GNUNET_RECLAIM_Operation -{ - +struct GNUNET_RECLAIM_Operation { /** * Main handle. */ @@ -102,9 +100,7 @@ struct GNUNET_RECLAIM_Operation /** * Handle for a ticket iterator operation */ -struct GNUNET_RECLAIM_TicketIterator -{ - +struct GNUNET_RECLAIM_TicketIterator { /** * Kept in a DLL. */ @@ -166,9 +162,7 @@ struct GNUNET_RECLAIM_TicketIterator /** * Handle for a attribute iterator operation */ -struct GNUNET_RECLAIM_AttributeIterator -{ - +struct GNUNET_RECLAIM_AttributeIterator { /** * Kept in a DLL. */ @@ -235,8 +229,7 @@ struct GNUNET_RECLAIM_AttributeIterator /** * Handle to the service. */ -struct GNUNET_RECLAIM_Handle -{ +struct GNUNET_RECLAIM_Handle { /** * Configuration to use. */ @@ -320,7 +313,7 @@ struct GNUNET_RECLAIM_Handle * @param h handle to the reclaim service. */ static void -reconnect (struct GNUNET_RECLAIM_Handle *h); +reconnect(struct GNUNET_RECLAIM_Handle *h); /** @@ -329,12 +322,12 @@ reconnect (struct GNUNET_RECLAIM_Handle *h); * @param cls the handle */ static void -reconnect_task (void *cls) +reconnect_task(void *cls) { struct GNUNET_RECLAIM_Handle *handle = cls; handle->reconnect_task = NULL; - reconnect (handle); + reconnect(handle); } @@ -344,16 +337,16 @@ reconnect_task (void *cls) * @param handle our service */ static void -force_reconnect (struct GNUNET_RECLAIM_Handle *handle) +force_reconnect(struct GNUNET_RECLAIM_Handle *handle) { - GNUNET_MQ_destroy (handle->mq); + GNUNET_MQ_destroy(handle->mq); handle->mq = NULL; handle->reconnect_backoff = - GNUNET_TIME_STD_BACKOFF (handle->reconnect_backoff); + GNUNET_TIME_STD_BACKOFF(handle->reconnect_backoff); handle->reconnect_task = - GNUNET_SCHEDULER_add_delayed (handle->reconnect_backoff, - &reconnect_task, - handle); + GNUNET_SCHEDULER_add_delayed(handle->reconnect_backoff, + &reconnect_task, + handle); } @@ -363,14 +356,14 @@ force_reconnect (struct GNUNET_RECLAIM_Handle *handle) * @param it entry to free */ static void -free_it (struct GNUNET_RECLAIM_AttributeIterator *it) +free_it(struct GNUNET_RECLAIM_AttributeIterator *it) { struct GNUNET_RECLAIM_Handle *h = it->h; - GNUNET_CONTAINER_DLL_remove (h->it_head, h->it_tail, it); + GNUNET_CONTAINER_DLL_remove(h->it_head, h->it_tail, it); if (NULL != it->env) - GNUNET_MQ_discard (it->env); - GNUNET_free (it); + GNUNET_MQ_discard(it->env); + GNUNET_free(it); } /** @@ -379,13 +372,13 @@ free_it (struct GNUNET_RECLAIM_AttributeIterator *it) * @param op the operation to free */ static void -free_op (struct GNUNET_RECLAIM_Operation *op) +free_op(struct GNUNET_RECLAIM_Operation *op) { if (NULL == op) return; if (NULL != op->env) - GNUNET_MQ_discard (op->env); - GNUNET_free (op); + GNUNET_MQ_discard(op->env); + GNUNET_free(op); } @@ -398,10 +391,11 @@ free_op (struct GNUNET_RECLAIM_Operation *op) * @param error error code */ static void -mq_error_handler (void *cls, enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, enum GNUNET_MQ_Error error) { struct GNUNET_RECLAIM_Handle *handle = cls; - force_reconnect (handle); + + force_reconnect(handle); } @@ -413,11 +407,11 @@ mq_error_handler (void *cls, enum GNUNET_MQ_Error error) * @param msg the message we received */ static void -handle_success_response (void *cls, const struct SuccessResultMessage *msg) +handle_success_response(void *cls, const struct SuccessResultMessage *msg) { struct GNUNET_RECLAIM_Handle *h = cls; struct GNUNET_RECLAIM_Operation *op; - uint32_t r_id = ntohl (msg->id); + uint32_t r_id = ntohl(msg->id); int res; const char *emsg; @@ -427,20 +421,20 @@ handle_success_response (void *cls, const struct SuccessResultMessage *msg) if (NULL == op) return; - res = ntohl (msg->op_result); - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Received SUCCESS_RESPONSE with result %d\n", - res); + res = ntohl(msg->op_result); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Received SUCCESS_RESPONSE with result %d\n", + res); /* TODO: add actual error message to response... */ if (GNUNET_SYSERR == res) - emsg = _ ("failed to store record\n"); + emsg = _("failed to store record\n"); else emsg = NULL; if (NULL != op->as_cb) - op->as_cb (op->cls, res, emsg); - GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, op); - free_op (op); + op->as_cb(op->cls, res, emsg); + GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, op); + free_op(op); } @@ -453,19 +447,19 @@ handle_success_response (void *cls, const struct SuccessResultMessage *msg) * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -check_consume_ticket_result (void *cls, - const struct ConsumeTicketResultMessage *msg) +check_consume_ticket_result(void *cls, + const struct ConsumeTicketResultMessage *msg) { size_t msg_len; size_t attrs_len; - msg_len = ntohs (msg->header.size); - attrs_len = ntohs (msg->attrs_len); - if (msg_len != sizeof (struct ConsumeTicketResultMessage) + attrs_len) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + msg_len = ntohs(msg->header.size); + attrs_len = ntohs(msg->attrs_len); + if (msg_len != sizeof(struct ConsumeTicketResultMessage) + attrs_len) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -478,16 +472,16 @@ check_consume_ticket_result (void *cls, * @param msg the message we received */ static void -handle_consume_ticket_result (void *cls, - const struct ConsumeTicketResultMessage *msg) +handle_consume_ticket_result(void *cls, + const struct ConsumeTicketResultMessage *msg) { struct GNUNET_RECLAIM_Handle *h = cls; struct GNUNET_RECLAIM_Operation *op; size_t attrs_len; - uint32_t r_id = ntohl (msg->id); + uint32_t r_id = ntohl(msg->id); - attrs_len = ntohs (msg->attrs_len); - LOG (GNUNET_ERROR_TYPE_DEBUG, "Processing attribute result.\n"); + attrs_len = ntohs(msg->attrs_len); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Processing attribute result.\n"); for (op = h->op_head; NULL != op; op = op->next) @@ -500,28 +494,28 @@ handle_consume_ticket_result (void *cls, struct GNUNET_RECLAIM_ATTRIBUTE_ClaimList *attrs; struct GNUNET_RECLAIM_ATTRIBUTE_ClaimListEntry *le; attrs = - GNUNET_RECLAIM_ATTRIBUTE_list_deserialize ((char *) &msg[1], attrs_len); + GNUNET_RECLAIM_ATTRIBUTE_list_deserialize((char *)&msg[1], attrs_len); if (NULL != op->ar_cb) - { - if (NULL == attrs) { - op->ar_cb (op->cls, &msg->identity, NULL); + if (NULL == attrs) + { + op->ar_cb(op->cls, &msg->identity, NULL); + } + else + { + for (le = attrs->list_head; NULL != le; le = le->next) + op->ar_cb(op->cls, &msg->identity, le->claim); + GNUNET_RECLAIM_ATTRIBUTE_list_destroy(attrs); + attrs = NULL; + } + op->ar_cb(op->cls, NULL, NULL); } - else - { - for (le = attrs->list_head; NULL != le; le = le->next) - op->ar_cb (op->cls, &msg->identity, le->claim); - GNUNET_RECLAIM_ATTRIBUTE_list_destroy (attrs); - attrs = NULL; - } - op->ar_cb (op->cls, NULL, NULL); - } - GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, op); - free_op (op); - GNUNET_free_non_null (attrs); + GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, op); + free_op(op); + GNUNET_free_non_null(attrs); return; } - GNUNET_assert (0); + GNUNET_assert(0); } @@ -534,18 +528,18 @@ handle_consume_ticket_result (void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR on error */ static int -check_attribute_result (void *cls, const struct AttributeResultMessage *msg) +check_attribute_result(void *cls, const struct AttributeResultMessage *msg) { size_t msg_len; size_t attr_len; - msg_len = ntohs (msg->header.size); - attr_len = ntohs (msg->attr_len); - if (msg_len != sizeof (struct AttributeResultMessage) + attr_len) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + msg_len = ntohs(msg->header.size); + attr_len = ntohs(msg->attr_len); + if (msg_len != sizeof(struct AttributeResultMessage) + attr_len) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -558,17 +552,17 @@ check_attribute_result (void *cls, const struct AttributeResultMessage *msg) * @param msg the message we received */ static void -handle_attribute_result (void *cls, const struct AttributeResultMessage *msg) +handle_attribute_result(void *cls, const struct AttributeResultMessage *msg) { static struct GNUNET_CRYPTO_EcdsaPrivateKey identity_dummy; struct GNUNET_RECLAIM_Handle *h = cls; struct GNUNET_RECLAIM_AttributeIterator *it; struct GNUNET_RECLAIM_Operation *op; size_t attr_len; - uint32_t r_id = ntohl (msg->id); + uint32_t r_id = ntohl(msg->id); - attr_len = ntohs (msg->attr_len); - LOG (GNUNET_ERROR_TYPE_DEBUG, "Processing attribute result.\n"); + attr_len = ntohs(msg->attr_len); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Processing attribute result.\n"); for (it = h->it_head; NULL != it; it = it->next) @@ -581,47 +575,47 @@ handle_attribute_result (void *cls, const struct AttributeResultMessage *msg) return; if ((0 == - (memcmp (&msg->identity, &identity_dummy, sizeof (identity_dummy))))) - { - if ((NULL == it) && (NULL == op)) + (memcmp(&msg->identity, &identity_dummy, sizeof(identity_dummy))))) { - GNUNET_break (0); - force_reconnect (h); + if ((NULL == it) && (NULL == op)) + { + GNUNET_break(0); + force_reconnect(h); + return; + } + if (NULL != it) + { + if (NULL != it->finish_cb) + it->finish_cb(it->finish_cb_cls); + free_it(it); + } + if (NULL != op) + { + if (NULL != op->ar_cb) + op->ar_cb(op->cls, NULL, NULL); + GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, op); + free_op(op); + } return; } - if (NULL != it) - { - if (NULL != it->finish_cb) - it->finish_cb (it->finish_cb_cls); - free_it (it); - } - if (NULL != op) - { - if (NULL != op->ar_cb) - op->ar_cb (op->cls, NULL, NULL); - GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, op); - free_op (op); - } - return; - } { struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr; - attr = GNUNET_RECLAIM_ATTRIBUTE_deserialize ((char *) &msg[1], attr_len); + attr = GNUNET_RECLAIM_ATTRIBUTE_deserialize((char *)&msg[1], attr_len); if (NULL != it) - { - if (NULL != it->proc) - it->proc (it->proc_cls, &msg->identity, attr); - } + { + if (NULL != it->proc) + it->proc(it->proc_cls, &msg->identity, attr); + } else if (NULL != op) - { - if (NULL != op->ar_cb) - op->ar_cb (op->cls, &msg->identity, attr); - } - GNUNET_free (attr); + { + if (NULL != op->ar_cb) + op->ar_cb(op->cls, &msg->identity, attr); + } + GNUNET_free(attr); return; } - GNUNET_assert (0); + GNUNET_assert(0); } @@ -633,13 +627,14 @@ handle_attribute_result (void *cls, const struct AttributeResultMessage *msg) * @param msg the message we received */ static void -handle_ticket_result (void *cls, const struct TicketResultMessage *msg) +handle_ticket_result(void *cls, const struct TicketResultMessage *msg) { struct GNUNET_RECLAIM_Handle *handle = cls; struct GNUNET_RECLAIM_Operation *op; struct GNUNET_RECLAIM_TicketIterator *it; - uint32_t r_id = ntohl (msg->id); + uint32_t r_id = ntohl(msg->id); static const struct GNUNET_RECLAIM_Ticket ticket; + for (op = handle->op_head; NULL != op; op = op->next) if (op->r_id == r_id) break; @@ -649,41 +644,41 @@ handle_ticket_result (void *cls, const struct TicketResultMessage *msg) if ((NULL == op) && (NULL == it)) return; if (NULL != op) - { - GNUNET_CONTAINER_DLL_remove (handle->op_head, handle->op_tail, op); - if (0 == - memcmp (&msg->ticket, &ticket, sizeof (struct GNUNET_RECLAIM_Ticket))) { - if (NULL != op->tr_cb) - op->tr_cb (op->cls, NULL); - } - else - { - if (NULL != op->tr_cb) - op->tr_cb (op->cls, &msg->ticket); + GNUNET_CONTAINER_DLL_remove(handle->op_head, handle->op_tail, op); + if (0 == + memcmp(&msg->ticket, &ticket, sizeof(struct GNUNET_RECLAIM_Ticket))) + { + if (NULL != op->tr_cb) + op->tr_cb(op->cls, NULL); + } + else + { + if (NULL != op->tr_cb) + op->tr_cb(op->cls, &msg->ticket); + } + free_op(op); + return; } - free_op (op); - return; - } else if (NULL != it) - { - if (0 == - memcmp (&msg->ticket, &ticket, sizeof (struct GNUNET_RECLAIM_Ticket))) - { - GNUNET_CONTAINER_DLL_remove (handle->ticket_it_head, - handle->ticket_it_tail, - it); - it->finish_cb (it->finish_cb_cls); - GNUNET_free (it); - } - else { - if (NULL != it->tr_cb) - it->tr_cb (it->cls, &msg->ticket); + if (0 == + memcmp(&msg->ticket, &ticket, sizeof(struct GNUNET_RECLAIM_Ticket))) + { + GNUNET_CONTAINER_DLL_remove(handle->ticket_it_head, + handle->ticket_it_tail, + it); + it->finish_cb(it->finish_cb_cls); + GNUNET_free(it); + } + else + { + if (NULL != it->tr_cb) + it->tr_cb(it->cls, &msg->ticket); + } + return; } - return; - } - GNUNET_break (0); + GNUNET_break(0); } @@ -695,15 +690,15 @@ handle_ticket_result (void *cls, const struct TicketResultMessage *msg) * @param msg the message we received */ static void -handle_revoke_ticket_result (void *cls, - const struct RevokeTicketResultMessage *msg) +handle_revoke_ticket_result(void *cls, + const struct RevokeTicketResultMessage *msg) { struct GNUNET_RECLAIM_Handle *h = cls; struct GNUNET_RECLAIM_Operation *op; - uint32_t r_id = ntohl (msg->id); + uint32_t r_id = ntohl(msg->id); int32_t success; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Processing revocation result.\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Processing revocation result.\n"); for (op = h->op_head; NULL != op; op = op->next) @@ -711,17 +706,17 @@ handle_revoke_ticket_result (void *cls, break; if (NULL == op) return; - success = ntohl (msg->success); + success = ntohl(msg->success); { if (NULL != op->rvk_cb) - { - op->rvk_cb (op->cls, success, NULL); - } - GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, op); - free_op (op); + { + op->rvk_cb(op->cls, success, NULL); + } + GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, op); + free_op(op); return; } - GNUNET_assert (0); + GNUNET_assert(0); } @@ -731,41 +726,41 @@ handle_revoke_ticket_result (void *cls, * @param h handle to the reclaim service. */ static void -reconnect (struct GNUNET_RECLAIM_Handle *h) +reconnect(struct GNUNET_RECLAIM_Handle *h) { struct GNUNET_MQ_MessageHandler handlers[] = - {GNUNET_MQ_hd_fixed_size (success_response, - GNUNET_MESSAGE_TYPE_RECLAIM_SUCCESS_RESPONSE, - struct SuccessResultMessage, - h), - GNUNET_MQ_hd_var_size (attribute_result, - GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_RESULT, - struct AttributeResultMessage, + { GNUNET_MQ_hd_fixed_size(success_response, + GNUNET_MESSAGE_TYPE_RECLAIM_SUCCESS_RESPONSE, + struct SuccessResultMessage, h), - GNUNET_MQ_hd_fixed_size (ticket_result, - GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_RESULT, - struct TicketResultMessage, - h), - GNUNET_MQ_hd_var_size (consume_ticket_result, - GNUNET_MESSAGE_TYPE_RECLAIM_CONSUME_TICKET_RESULT, - struct ConsumeTicketResultMessage, + GNUNET_MQ_hd_var_size(attribute_result, + GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_RESULT, + struct AttributeResultMessage, + h), + GNUNET_MQ_hd_fixed_size(ticket_result, + GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_RESULT, + struct TicketResultMessage, h), - GNUNET_MQ_hd_fixed_size (revoke_ticket_result, - GNUNET_MESSAGE_TYPE_RECLAIM_REVOKE_TICKET_RESULT, - struct RevokeTicketResultMessage, - h), - GNUNET_MQ_handler_end ()}; + GNUNET_MQ_hd_var_size(consume_ticket_result, + GNUNET_MESSAGE_TYPE_RECLAIM_CONSUME_TICKET_RESULT, + struct ConsumeTicketResultMessage, + h), + GNUNET_MQ_hd_fixed_size(revoke_ticket_result, + GNUNET_MESSAGE_TYPE_RECLAIM_REVOKE_TICKET_RESULT, + struct RevokeTicketResultMessage, + h), + GNUNET_MQ_handler_end() }; struct GNUNET_RECLAIM_Operation *op; - GNUNET_assert (NULL == h->mq); - LOG (GNUNET_ERROR_TYPE_DEBUG, "Connecting to reclaim service.\n"); + GNUNET_assert(NULL == h->mq); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Connecting to reclaim service.\n"); h->mq = - GNUNET_CLIENT_connect (h->cfg, "reclaim", handlers, &mq_error_handler, h); + GNUNET_CLIENT_connect(h->cfg, "reclaim", handlers, &mq_error_handler, h); if (NULL == h->mq) return; for (op = h->op_head; NULL != op; op = op->next) - GNUNET_MQ_send_copy (h->mq, op->env); + GNUNET_MQ_send_copy(h->mq, op->env); } @@ -776,18 +771,18 @@ reconnect (struct GNUNET_RECLAIM_Handle *h) * @return handle to use */ struct GNUNET_RECLAIM_Handle * -GNUNET_RECLAIM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) +GNUNET_RECLAIM_connect(const struct GNUNET_CONFIGURATION_Handle *cfg) { struct GNUNET_RECLAIM_Handle *h; - h = GNUNET_new (struct GNUNET_RECLAIM_Handle); + h = GNUNET_new(struct GNUNET_RECLAIM_Handle); h->cfg = cfg; - reconnect (h); + reconnect(h); if (NULL == h->mq) - { - GNUNET_free (h); - return NULL; - } + { + GNUNET_free(h); + return NULL; + } return h; } @@ -801,12 +796,12 @@ GNUNET_RECLAIM_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) * @param op operation to cancel */ void -GNUNET_RECLAIM_cancel (struct GNUNET_RECLAIM_Operation *op) +GNUNET_RECLAIM_cancel(struct GNUNET_RECLAIM_Operation *op) { struct GNUNET_RECLAIM_Handle *h = op->h; - GNUNET_CONTAINER_DLL_remove (h->op_head, h->op_tail, op); - free_op (op); + GNUNET_CONTAINER_DLL_remove(h->op_head, h->op_tail, op); + free_op(op); } @@ -816,21 +811,21 @@ GNUNET_RECLAIM_cancel (struct GNUNET_RECLAIM_Operation *op) * @param h handle to destroy */ void -GNUNET_RECLAIM_disconnect (struct GNUNET_RECLAIM_Handle *h) +GNUNET_RECLAIM_disconnect(struct GNUNET_RECLAIM_Handle *h) { - GNUNET_assert (NULL != h); + GNUNET_assert(NULL != h); if (NULL != h->mq) - { - GNUNET_MQ_destroy (h->mq); - h->mq = NULL; - } + { + GNUNET_MQ_destroy(h->mq); + h->mq = NULL; + } if (NULL != h->reconnect_task) - { - GNUNET_SCHEDULER_cancel (h->reconnect_task); - h->reconnect_task = NULL; - } - GNUNET_assert (NULL == h->op_head); - GNUNET_free (h); + { + GNUNET_SCHEDULER_cancel(h->reconnect_task); + h->reconnect_task = NULL; + } + GNUNET_assert(NULL == h->op_head); + GNUNET_free(h); } /** @@ -846,7 +841,7 @@ GNUNET_RECLAIM_disconnect (struct GNUNET_RECLAIM_Handle *h) * @return handle to abort the request */ struct GNUNET_RECLAIM_Operation * -GNUNET_RECLAIM_attribute_store ( +GNUNET_RECLAIM_attribute_store( struct GNUNET_RECLAIM_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr, @@ -858,25 +853,25 @@ GNUNET_RECLAIM_attribute_store ( struct AttributeStoreMessage *sam; size_t attr_len; - op = GNUNET_new (struct GNUNET_RECLAIM_Operation); + op = GNUNET_new(struct GNUNET_RECLAIM_Operation); op->h = h; op->as_cb = cont; op->cls = cont_cls; op->r_id = h->r_id_gen++; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, op); - attr_len = GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size (attr); - op->env = GNUNET_MQ_msg_extra (sam, - attr_len, - GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_STORE); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, op); + attr_len = GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size(attr); + op->env = GNUNET_MQ_msg_extra(sam, + attr_len, + GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_STORE); sam->identity = *pkey; - sam->id = htonl (op->r_id); - sam->exp = GNUNET_htonll (exp_interval->rel_value_us); + sam->id = htonl(op->r_id); + sam->exp = GNUNET_htonll(exp_interval->rel_value_us); - GNUNET_RECLAIM_ATTRIBUTE_serialize (attr, (char *) &sam[1]); + GNUNET_RECLAIM_ATTRIBUTE_serialize(attr, (char *)&sam[1]); - sam->attr_len = htons (attr_len); + sam->attr_len = htons(attr_len); if (NULL != h->mq) - GNUNET_MQ_send_copy (h->mq, op->env); + GNUNET_MQ_send_copy(h->mq, op->env); return op; } @@ -893,7 +888,7 @@ GNUNET_RECLAIM_attribute_store ( * @return handle Used to to abort the request */ struct GNUNET_RECLAIM_Operation * -GNUNET_RECLAIM_attribute_delete ( +GNUNET_RECLAIM_attribute_delete( struct GNUNET_RECLAIM_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *pkey, const struct GNUNET_RECLAIM_ATTRIBUTE_Claim *attr, @@ -904,23 +899,23 @@ GNUNET_RECLAIM_attribute_delete ( struct AttributeDeleteMessage *dam; size_t attr_len; - op = GNUNET_new (struct GNUNET_RECLAIM_Operation); + op = GNUNET_new(struct GNUNET_RECLAIM_Operation); op->h = h; op->as_cb = cont; op->cls = cont_cls; op->r_id = h->r_id_gen++; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, op); - attr_len = GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size (attr); - op->env = GNUNET_MQ_msg_extra (dam, - attr_len, - GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_DELETE); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, op); + attr_len = GNUNET_RECLAIM_ATTRIBUTE_serialize_get_size(attr); + op->env = GNUNET_MQ_msg_extra(dam, + attr_len, + GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_DELETE); dam->identity = *pkey; - dam->id = htonl (op->r_id); - GNUNET_RECLAIM_ATTRIBUTE_serialize (attr, (char *) &dam[1]); + dam->id = htonl(op->r_id); + GNUNET_RECLAIM_ATTRIBUTE_serialize(attr, (char *)&dam[1]); - dam->attr_len = htons (attr_len); + dam->attr_len = htons(attr_len); if (NULL != h->mq) - GNUNET_MQ_send_copy (h->mq, op->env); + GNUNET_MQ_send_copy(h->mq, op->env); return op; } @@ -950,7 +945,7 @@ GNUNET_RECLAIM_attribute_delete ( * @return an iterator Handle to use for iteration */ struct GNUNET_RECLAIM_AttributeIterator * -GNUNET_RECLAIM_get_attributes_start ( +GNUNET_RECLAIM_get_attributes_start( struct GNUNET_RECLAIM_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, GNUNET_SCHEDULER_TaskCallback error_cb, @@ -966,7 +961,7 @@ GNUNET_RECLAIM_get_attributes_start ( uint32_t rid; rid = h->r_id_gen++; - it = GNUNET_new (struct GNUNET_RECLAIM_AttributeIterator); + it = GNUNET_new(struct GNUNET_RECLAIM_AttributeIterator); it->h = h; it->error_cb = error_cb; it->error_cb_cls = error_cb_cls; @@ -976,15 +971,15 @@ GNUNET_RECLAIM_get_attributes_start ( it->proc_cls = proc_cls; it->r_id = rid; it->identity = *identity; - GNUNET_CONTAINER_DLL_insert_tail (h->it_head, h->it_tail, it); + GNUNET_CONTAINER_DLL_insert_tail(h->it_head, h->it_tail, it); env = - GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_START); - msg->id = htonl (rid); + GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_START); + msg->id = htonl(rid); msg->identity = *identity; if (NULL == h->mq) it->env = env; else - GNUNET_MQ_send (h->mq, env); + GNUNET_MQ_send(h->mq, env); return it; } @@ -996,16 +991,16 @@ GNUNET_RECLAIM_get_attributes_start ( * @param it the iterator */ void -GNUNET_RECLAIM_get_attributes_next (struct GNUNET_RECLAIM_AttributeIterator *it) +GNUNET_RECLAIM_get_attributes_next(struct GNUNET_RECLAIM_AttributeIterator *it) { struct GNUNET_RECLAIM_Handle *h = it->h; struct AttributeIterationNextMessage *msg; struct GNUNET_MQ_Envelope *env; env = - GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_NEXT); - msg->id = htonl (it->r_id); - GNUNET_MQ_send (h->mq, env); + GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_NEXT); + msg->id = htonl(it->r_id); + GNUNET_MQ_send(h->mq, env); } @@ -1017,20 +1012,20 @@ GNUNET_RECLAIM_get_attributes_next (struct GNUNET_RECLAIM_AttributeIterator *it) * @param it the iterator */ void -GNUNET_RECLAIM_get_attributes_stop (struct GNUNET_RECLAIM_AttributeIterator *it) +GNUNET_RECLAIM_get_attributes_stop(struct GNUNET_RECLAIM_AttributeIterator *it) { struct GNUNET_RECLAIM_Handle *h = it->h; struct GNUNET_MQ_Envelope *env; struct AttributeIterationStopMessage *msg; if (NULL != h->mq) - { - env = - GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_STOP); - msg->id = htonl (it->r_id); - GNUNET_MQ_send (h->mq, env); - } - free_it (it); + { + env = + GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_RECLAIM_ATTRIBUTE_ITERATION_STOP); + msg->id = htonl(it->r_id); + GNUNET_MQ_send(h->mq, env); + } + free_it(it); } @@ -1048,7 +1043,7 @@ GNUNET_RECLAIM_get_attributes_stop (struct GNUNET_RECLAIM_AttributeIterator *it) * @return handle to abort the operation */ struct GNUNET_RECLAIM_Operation * -GNUNET_RECLAIM_ticket_issue ( +GNUNET_RECLAIM_ticket_issue( struct GNUNET_RECLAIM_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *iss, const struct GNUNET_CRYPTO_EcdsaPublicKey *rp, @@ -1059,26 +1054,27 @@ GNUNET_RECLAIM_ticket_issue ( struct GNUNET_RECLAIM_Operation *op; struct IssueTicketMessage *tim; size_t attr_len; - fprintf (stderr, "Issuing ticket\n"); - op = GNUNET_new (struct GNUNET_RECLAIM_Operation); + + fprintf(stderr, "Issuing ticket\n"); + op = GNUNET_new(struct GNUNET_RECLAIM_Operation); op->h = h; op->tr_cb = cb; op->cls = cb_cls; op->r_id = h->r_id_gen++; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, op); - attr_len = GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size (attrs); - op->env = GNUNET_MQ_msg_extra (tim, - attr_len, - GNUNET_MESSAGE_TYPE_RECLAIM_ISSUE_TICKET); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, op); + attr_len = GNUNET_RECLAIM_ATTRIBUTE_list_serialize_get_size(attrs); + op->env = GNUNET_MQ_msg_extra(tim, + attr_len, + GNUNET_MESSAGE_TYPE_RECLAIM_ISSUE_TICKET); tim->identity = *iss; tim->rp = *rp; - tim->id = htonl (op->r_id); + tim->id = htonl(op->r_id); - GNUNET_RECLAIM_ATTRIBUTE_list_serialize (attrs, (char *) &tim[1]); + GNUNET_RECLAIM_ATTRIBUTE_list_serialize(attrs, (char *)&tim[1]); - tim->attr_len = htons (attr_len); + tim->attr_len = htons(attr_len); if (NULL != h->mq) - GNUNET_MQ_send_copy (h->mq, op->env); + GNUNET_MQ_send_copy(h->mq, op->env); return op; } @@ -1096,7 +1092,7 @@ GNUNET_RECLAIM_ticket_issue ( * @return handle to abort the operation */ struct GNUNET_RECLAIM_Operation * -GNUNET_RECLAIM_ticket_consume ( +GNUNET_RECLAIM_ticket_consume( struct GNUNET_RECLAIM_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, const struct GNUNET_RECLAIM_Ticket *ticket, @@ -1106,18 +1102,18 @@ GNUNET_RECLAIM_ticket_consume ( struct GNUNET_RECLAIM_Operation *op; struct ConsumeTicketMessage *ctm; - op = GNUNET_new (struct GNUNET_RECLAIM_Operation); + op = GNUNET_new(struct GNUNET_RECLAIM_Operation); op->h = h; op->ar_cb = cb; op->cls = cb_cls; op->r_id = h->r_id_gen++; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, op); - op->env = GNUNET_MQ_msg (ctm, GNUNET_MESSAGE_TYPE_RECLAIM_CONSUME_TICKET); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, op); + op->env = GNUNET_MQ_msg(ctm, GNUNET_MESSAGE_TYPE_RECLAIM_CONSUME_TICKET); ctm->identity = *identity; - ctm->id = htonl (op->r_id); + ctm->id = htonl(op->r_id); ctm->ticket = *ticket; if (NULL != h->mq) - GNUNET_MQ_send_copy (h->mq, op->env); + GNUNET_MQ_send_copy(h->mq, op->env); return op; } @@ -1140,7 +1136,7 @@ GNUNET_RECLAIM_ticket_consume ( * @return an iterator handle to use for iteration */ struct GNUNET_RECLAIM_TicketIterator * -GNUNET_RECLAIM_ticket_iteration_start ( +GNUNET_RECLAIM_ticket_iteration_start( struct GNUNET_RECLAIM_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, GNUNET_SCHEDULER_TaskCallback error_cb, @@ -1156,7 +1152,7 @@ GNUNET_RECLAIM_ticket_iteration_start ( uint32_t rid; rid = h->r_id_gen++; - it = GNUNET_new (struct GNUNET_RECLAIM_TicketIterator); + it = GNUNET_new(struct GNUNET_RECLAIM_TicketIterator); it->h = h; it->error_cb = error_cb; it->error_cb_cls = error_cb_cls; @@ -1165,14 +1161,14 @@ GNUNET_RECLAIM_ticket_iteration_start ( it->tr_cb = proc; it->cls = proc_cls; it->r_id = rid; - GNUNET_CONTAINER_DLL_insert_tail (h->ticket_it_head, h->ticket_it_tail, it); - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_START); - msg->id = htonl (rid); + GNUNET_CONTAINER_DLL_insert_tail(h->ticket_it_head, h->ticket_it_tail, it); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_START); + msg->id = htonl(rid); msg->identity = *identity; if (NULL == h->mq) it->env = env; else - GNUNET_MQ_send (h->mq, env); + GNUNET_MQ_send(h->mq, env); return it; } @@ -1184,15 +1180,15 @@ GNUNET_RECLAIM_ticket_iteration_start ( * @param it the iterator */ void -GNUNET_RECLAIM_ticket_iteration_next (struct GNUNET_RECLAIM_TicketIterator *it) +GNUNET_RECLAIM_ticket_iteration_next(struct GNUNET_RECLAIM_TicketIterator *it) { struct GNUNET_RECLAIM_Handle *h = it->h; struct TicketIterationNextMessage *msg; struct GNUNET_MQ_Envelope *env; - env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_NEXT); - msg->id = htonl (it->r_id); - GNUNET_MQ_send (h->mq, env); + env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_NEXT); + msg->id = htonl(it->r_id); + GNUNET_MQ_send(h->mq, env); } @@ -1204,20 +1200,20 @@ GNUNET_RECLAIM_ticket_iteration_next (struct GNUNET_RECLAIM_TicketIterator *it) * @param it the iterator */ void -GNUNET_RECLAIM_ticket_iteration_stop (struct GNUNET_RECLAIM_TicketIterator *it) +GNUNET_RECLAIM_ticket_iteration_stop(struct GNUNET_RECLAIM_TicketIterator *it) { struct GNUNET_RECLAIM_Handle *h = it->h; struct GNUNET_MQ_Envelope *env; struct TicketIterationStopMessage *msg; if (NULL != h->mq) - { - env = - GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_STOP); - msg->id = htonl (it->r_id); - GNUNET_MQ_send (h->mq, env); - } - GNUNET_free (it); + { + env = + GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_RECLAIM_TICKET_ITERATION_STOP); + msg->id = htonl(it->r_id); + GNUNET_MQ_send(h->mq, env); + } + GNUNET_free(it); } @@ -1235,7 +1231,7 @@ GNUNET_RECLAIM_ticket_iteration_stop (struct GNUNET_RECLAIM_TicketIterator *it) * @return handle to abort the operation */ struct GNUNET_RECLAIM_Operation * -GNUNET_RECLAIM_ticket_revoke ( +GNUNET_RECLAIM_ticket_revoke( struct GNUNET_RECLAIM_Handle *h, const struct GNUNET_CRYPTO_EcdsaPrivateKey *identity, const struct GNUNET_RECLAIM_Ticket *ticket, @@ -1247,21 +1243,21 @@ GNUNET_RECLAIM_ticket_revoke ( uint32_t rid; rid = h->r_id_gen++; - op = GNUNET_new (struct GNUNET_RECLAIM_Operation); + op = GNUNET_new(struct GNUNET_RECLAIM_Operation); op->h = h; op->rvk_cb = cb; op->cls = cb_cls; op->r_id = rid; - GNUNET_CONTAINER_DLL_insert_tail (h->op_head, h->op_tail, op); - op->env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RECLAIM_REVOKE_TICKET); - msg->id = htonl (rid); + GNUNET_CONTAINER_DLL_insert_tail(h->op_head, h->op_tail, op); + op->env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_RECLAIM_REVOKE_TICKET); + msg->id = htonl(rid); msg->identity = *identity; msg->ticket = *ticket; if (NULL != h->mq) - { - GNUNET_MQ_send (h->mq, op->env); - op->env = NULL; - } + { + GNUNET_MQ_send(h->mq, op->env); + op->env = NULL; + } return op; } diff --git a/src/regex/gnunet-daemon-regexprofiler.c b/src/regex/gnunet-daemon-regexprofiler.c index f1c00a554..b9c32f9c7 100644 --- a/src/regex/gnunet-daemon-regexprofiler.c +++ b/src/regex/gnunet-daemon-regexprofiler.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/gnunet-daemon-regexprofiler.c @@ -108,31 +108,31 @@ static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key; * @param cls unused */ static void -shutdown_task (void *cls) +shutdown_task(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "shutting down\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "shutting down\n"); if (NULL != announce_handle) - { - REGEX_INTERNAL_announce_cancel (announce_handle); - announce_handle = NULL; - } + { + REGEX_INTERNAL_announce_cancel(announce_handle); + announce_handle = NULL; + } if (NULL != reannounce_task) - { - GNUNET_free (GNUNET_SCHEDULER_cancel (reannounce_task)); - reannounce_task = NULL; - } + { + GNUNET_free(GNUNET_SCHEDULER_cancel(reannounce_task)); + reannounce_task = NULL; + } if (NULL != dht_handle) - { - GNUNET_DHT_disconnect (dht_handle); - dht_handle = NULL; - } - GNUNET_free (my_private_key); + { + GNUNET_DHT_disconnect(dht_handle); + dht_handle = NULL; + } + GNUNET_free(my_private_key); my_private_key = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Daemon for %s shutting down\n", - policy_filename); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Daemon for %s shutting down\n", + policy_filename); } @@ -142,45 +142,45 @@ shutdown_task (void *cls) * @param cls Closure (regex to announce if needed). */ static void -reannounce_regex (void *cls) +reannounce_regex(void *cls) { char *regex = cls; struct GNUNET_TIME_Relative random_delay; reannounce_task = NULL; if (0 == rounds--) - { - global_ret = 0; - GNUNET_SCHEDULER_shutdown (); - GNUNET_free (regex); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Announcing regex: %s\n", regex); - GNUNET_STATISTICS_update (stats_handle, "# regexes announced", 1, GNUNET_NO); + { + global_ret = 0; + GNUNET_SCHEDULER_shutdown(); + GNUNET_free(regex); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Announcing regex: %s\n", regex); + GNUNET_STATISTICS_update(stats_handle, "# regexes announced", 1, GNUNET_NO); if (NULL == announce_handle && NULL != regex) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "First time, creating regex: %s\n", - regex); - announce_handle = REGEX_INTERNAL_announce (dht_handle, - my_private_key, - regex, - (unsigned int) max_path_compression, - stats_handle); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "First time, creating regex: %s\n", + regex); + announce_handle = REGEX_INTERNAL_announce(dht_handle, + my_private_key, + regex, + (unsigned int)max_path_compression, + stats_handle); + } else - { - GNUNET_assert (NULL != announce_handle); - REGEX_INTERNAL_reannounce (announce_handle); - } + { + GNUNET_assert(NULL != announce_handle); + REGEX_INTERNAL_reannounce(announce_handle); + } random_delay = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MICROSECONDS, - GNUNET_CRYPTO_random_u32 ( - GNUNET_CRYPTO_QUALITY_WEAK, - reannounce_period_max.rel_value_us)); - reannounce_task = GNUNET_SCHEDULER_add_delayed (random_delay, - &reannounce_regex, cls); + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MICROSECONDS, + GNUNET_CRYPTO_random_u32( + GNUNET_CRYPTO_QUALITY_WEAK, + reannounce_period_max.rel_value_us)); + reannounce_task = GNUNET_SCHEDULER_add_delayed(random_delay, + &reannounce_regex, cls); } @@ -191,23 +191,23 @@ reannounce_regex (void *cls) * @param regex regular expression to announce on this peer's cadet. */ static void -announce_regex (const char *regex) +announce_regex(const char *regex) { char *copy; - if (NULL == regex || 0 == strlen (regex)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Cannot announce empty regex\n"); - return; - } - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Daemon for %s starting\n", - policy_filename); - GNUNET_assert (NULL == reannounce_task); - copy = GNUNET_strdup (regex); - reannounce_task = GNUNET_SCHEDULER_add_now (&reannounce_regex, - (void *) copy); + if (NULL == regex || 0 == strlen(regex)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Cannot announce empty regex\n"); + return; + } + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Daemon for %s starting\n", + policy_filename); + GNUNET_assert(NULL == reannounce_task); + copy = GNUNET_strdup(regex); + reannounce_task = GNUNET_SCHEDULER_add_now(&reannounce_regex, + (void *)copy); } @@ -220,16 +220,16 @@ announce_regex (const char *regex) * GNUNET_NO to stop when found */ static int -scan (void *cls, const char *filename) +scan(void *cls, const char *filename) { - long n = (long) cls; + long n = (long)cls; static long c = 0; if (c == n) - { - policy_filename = GNUNET_strdup (filename); - return GNUNET_NO; - } + { + policy_filename = GNUNET_strdup(filename); + return GNUNET_NO; + } c++; return GNUNET_OK; } @@ -244,9 +244,9 @@ scan (void *cls, const char *filename) * @param cfg_ configuration */ static void -run (void *cls, char *const *args GNUNET_UNUSED, - const char *cfgfile GNUNET_UNUSED, - const struct GNUNET_CONFIGURATION_Handle *cfg_) +run(void *cls, char *const *args GNUNET_UNUSED, + const char *cfgfile GNUNET_UNUSED, + const struct GNUNET_CONFIGURATION_Handle *cfg_) { char *regex = NULL; char **components; @@ -255,106 +255,106 @@ run (void *cls, char *const *args GNUNET_UNUSED, cfg = cfg_; - my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg); - GNUNET_assert (NULL != my_private_key); + my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration(cfg); + GNUNET_assert(NULL != my_private_key); if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (cfg, "REGEXPROFILER", - "MAX_PATH_COMPRESSION", - &max_path_compression)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _ - ("%s service is lacking key configuration settings (%s). Exiting.\n"), - "regexprofiler", "max_path_compression"); - global_ret = GNUNET_SYSERR; - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_CONFIGURATION_get_value_number(cfg, "REGEXPROFILER", + "MAX_PATH_COMPRESSION", + &max_path_compression)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _ + ("%s service is lacking key configuration settings (%s). Exiting.\n"), + "regexprofiler", "max_path_compression"); + global_ret = GNUNET_SYSERR; + GNUNET_SCHEDULER_shutdown(); + return; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, "REGEXPROFILER", - "POLICY_DIR", &policy_dir)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "REGEXPROFILER", "POLICY_DIR"); - global_ret = GNUNET_SYSERR; - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_CONFIGURATION_get_value_string(cfg, "REGEXPROFILER", + "POLICY_DIR", &policy_dir)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "REGEXPROFILER", "POLICY_DIR"); + global_ret = GNUNET_SYSERR; + GNUNET_SCHEDULER_shutdown(); + return; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (cfg, "TESTBED", - "PEERID", &peer_id)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "TESTBED", "PEERID"); - global_ret = GNUNET_SYSERR; - GNUNET_free (policy_dir); - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_CONFIGURATION_get_value_number(cfg, "TESTBED", + "PEERID", &peer_id)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "TESTBED", "PEERID"); + global_ret = GNUNET_SYSERR; + GNUNET_free(policy_dir); + GNUNET_SCHEDULER_shutdown(); + return; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, "REGEXPROFILER", - "REGEX_PREFIX", ®ex_prefix)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "REGEXPROFILER", "REGEX_PREFIX"); - global_ret = GNUNET_SYSERR; - GNUNET_free (policy_dir); - GNUNET_SCHEDULER_shutdown (); - return; - } + GNUNET_CONFIGURATION_get_value_string(cfg, "REGEXPROFILER", + "REGEX_PREFIX", ®ex_prefix)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "REGEXPROFILER", "REGEX_PREFIX"); + global_ret = GNUNET_SYSERR; + GNUNET_free(policy_dir); + GNUNET_SCHEDULER_shutdown(); + return; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_time (cfg, "REGEXPROFILER", - "REANNOUNCE_PERIOD_MAX", - &reannounce_period_max)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "reannounce_period_max not given. Using 10 minutes.\n"); - reannounce_period_max = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 10); - } + GNUNET_CONFIGURATION_get_value_time(cfg, "REGEXPROFILER", + "REANNOUNCE_PERIOD_MAX", + &reannounce_period_max)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "reannounce_period_max not given. Using 10 minutes.\n"); + reannounce_period_max = + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10); + } - stats_handle = GNUNET_STATISTICS_create ("regexprofiler", cfg); + stats_handle = GNUNET_STATISTICS_create("regexprofiler", cfg); - dht_handle = GNUNET_DHT_connect (cfg, 1); + dht_handle = GNUNET_DHT_connect(cfg, 1); if (NULL == dht_handle) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not acquire dht handle. Exiting.\n"); - global_ret = GNUNET_SYSERR; - GNUNET_free (policy_dir); - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not acquire dht handle. Exiting.\n"); + global_ret = GNUNET_SYSERR; + GNUNET_free(policy_dir); + GNUNET_SCHEDULER_shutdown(); + return; + } /* Read regexes from policy files */ - GNUNET_assert (-1 != GNUNET_DISK_directory_scan (policy_dir, &scan, - (void *) (long) peer_id)); - if (NULL == (components = REGEX_TEST_read_from_file (policy_filename))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Policy file %s contains no policies. Exiting.\n", - policy_filename); - global_ret = GNUNET_SYSERR; - GNUNET_free (policy_dir); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_free (policy_dir); - regex = REGEX_TEST_combine (components, 16); - REGEX_TEST_free_from_file (components); + GNUNET_assert(-1 != GNUNET_DISK_directory_scan(policy_dir, &scan, + (void *)(long)peer_id)); + if (NULL == (components = REGEX_TEST_read_from_file(policy_filename))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Policy file %s contains no policies. Exiting.\n", + policy_filename); + global_ret = GNUNET_SYSERR; + GNUNET_free(policy_dir); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_free(policy_dir); + regex = REGEX_TEST_combine(components, 16); + REGEX_TEST_free_from_file(components); /* Announcing regexes from policy_filename */ - GNUNET_asprintf (&rx_with_pfx, - "%s(%s)(0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f)*", - regex_prefix, - regex); - announce_regex (rx_with_pfx); - GNUNET_free (regex); - GNUNET_free (rx_with_pfx); + GNUNET_asprintf(&rx_with_pfx, + "%s(%s)(0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f)*", + regex_prefix, + regex); + announce_regex(rx_with_pfx); + GNUNET_free(regex); + GNUNET_free(rx_with_pfx); /* Scheduled the task to clean up when shutdown is called */ - GNUNET_SCHEDULER_add_shutdown (&shutdown_task, - NULL); + GNUNET_SCHEDULER_add_shutdown(&shutdown_task, + NULL); } @@ -366,19 +366,19 @@ run (void *cls, char *const *args GNUNET_UNUSED, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { static const struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; return (GNUNET_OK == - GNUNET_PROGRAM_run (argc, argv, "regexprofiler", - gettext_noop - ("Daemon to announce regular expressions for the peer using cadet."), - options, &run, NULL)) ? global_ret : 1; + GNUNET_PROGRAM_run(argc, argv, "regexprofiler", + gettext_noop + ("Daemon to announce regular expressions for the peer using cadet."), + options, &run, NULL)) ? global_ret : 1; } @@ -388,11 +388,11 @@ main (int argc, char *const *argv) /** * MINIMIZE heap size (way below 128k) since this process doesn't need much. */ -void __attribute__ ((constructor)) GNUNET_ARM_memory_init () +void __attribute__ ((constructor)) GNUNET_ARM_memory_init() { - mallopt (M_TRIM_THRESHOLD, 4 * 1024); - mallopt (M_TOP_PAD, 1 * 1024); - malloc_trim (0); + mallopt(M_TRIM_THRESHOLD, 4 * 1024); + mallopt(M_TOP_PAD, 1 * 1024); + malloc_trim(0); } #endif diff --git a/src/regex/gnunet-regex-profiler.c b/src/regex/gnunet-regex-profiler.c index a4d4ce99b..4262107d7 100644 --- a/src/regex/gnunet-regex-profiler.c +++ b/src/regex/gnunet-regex-profiler.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/gnunet-regex-profiler.c @@ -37,13 +37,12 @@ #include "gnunet_testbed_service.h" #define FIND_TIMEOUT \ - GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90) /** * DLL of operations */ -struct DLLOperation -{ +struct DLLOperation { /** * The testbed operation handle */ @@ -69,8 +68,7 @@ struct DLLOperation /** * Available states during profiling */ -enum State -{ +enum State { /** * Initial state */ @@ -112,8 +110,7 @@ enum State /** * Peer handles. */ -struct RegexPeer -{ +struct RegexPeer { /** * Peer id. */ @@ -150,7 +147,7 @@ struct RegexPeer /** * Handle to a running regex search. */ - struct REGEX_INTERNAL_Search *search_handle; + struct REGEX_INTERNAL_Search *search_handle; /** * Testbed operation handle for DHT. @@ -333,8 +330,8 @@ static struct GNUNET_TIME_Relative reannounce_period_max; * @param emsg error message. */ static void -dht_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op, - void *ca_result, const char *emsg); +dht_connect_cb(void *cls, struct GNUNET_TESTBED_Operation *op, + void *ca_result, const char *emsg); /** * DHT connect adapter. @@ -345,7 +342,7 @@ dht_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op, * @return */ static void * -dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg); +dht_ca(void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg); /** @@ -356,7 +353,7 @@ dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg); * @param op_result service handle returned from the connect adapter */ static void -dht_da (void *cls, void *op_result); +dht_da(void *cls, void *op_result); /** @@ -369,10 +366,10 @@ dht_da (void *cls, void *op_result); * @param emsg error message on failure */ static void -stats_connect_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg); +stats_connect_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg); /** @@ -381,7 +378,7 @@ stats_connect_cb (void *cls, * @param cls Index of the next peer in the peers array. */ static void -announce_next_regex (void *cls); +announce_next_regex(void *cls); /******************************************************************************/ @@ -395,7 +392,7 @@ announce_next_regex (void *cls); * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { struct RegexPeer *peer; unsigned int peer_cnt; @@ -404,75 +401,75 @@ do_shutdown (void *cls) size_t size; if (NULL != abort_task) - { - GNUNET_SCHEDULER_cancel (abort_task); - abort_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(abort_task); + abort_task = NULL; + } if (NULL != register_hosts_task) - { - GNUNET_SCHEDULER_cancel (register_hosts_task); - register_hosts_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(register_hosts_task); + register_hosts_task = NULL; + } for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++) - { - peer = &peers[peer_cnt]; - - if (GNUNET_YES != peer->search_str_matched && NULL != data_file) { - prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time); - size = - GNUNET_snprintf (output_buffer, - sizeof (output_buffer), - "%p Search string not found: %s (%d)\n" - "%p On peer: %u (%p)\n" - "%p After: %s\n", - peer, peer->search_str, peer->search_str_matched, - peer, peer->id, peer, - peer, - GNUNET_STRINGS_relative_time_to_string (prof_time, - GNUNET_NO)); - if (size != GNUNET_DISK_file_write (data_file, output_buffer, size)) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n"); + peer = &peers[peer_cnt]; + + if (GNUNET_YES != peer->search_str_matched && NULL != data_file) + { + prof_time = GNUNET_TIME_absolute_get_duration(peer->prof_start_time); + size = + GNUNET_snprintf(output_buffer, + sizeof(output_buffer), + "%p Search string not found: %s (%d)\n" + "%p On peer: %u (%p)\n" + "%p After: %s\n", + peer, peer->search_str, peer->search_str_matched, + peer, peer->id, peer, + peer, + GNUNET_STRINGS_relative_time_to_string(prof_time, + GNUNET_NO)); + if (size != GNUNET_DISK_file_write(data_file, output_buffer, size)) + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n"); + } + + if (NULL != peers[peer_cnt].op_handle) + GNUNET_TESTBED_operation_done(peers[peer_cnt].op_handle); } - if (NULL != peers[peer_cnt].op_handle) - GNUNET_TESTBED_operation_done (peers[peer_cnt].op_handle); - } - if (NULL != data_file) - { - GNUNET_DISK_file_close (data_file); - data_file = NULL; - } + { + GNUNET_DISK_file_close(data_file); + data_file = NULL; + } for (search_str_cnt = 0; search_str_cnt < num_peers && NULL != search_strings; search_str_cnt++) - { - GNUNET_free_non_null (search_strings[search_str_cnt]); - } - GNUNET_free_non_null (search_strings); + { + GNUNET_free_non_null(search_strings[search_str_cnt]); + } + GNUNET_free_non_null(search_strings); search_strings = NULL; if (NULL != reg_handle) - { - GNUNET_TESTBED_cancel_registration (reg_handle); - reg_handle = NULL; - } + { + GNUNET_TESTBED_cancel_registration(reg_handle); + reg_handle = NULL; + } if (NULL != mc) - { - GNUNET_TESTBED_controller_disconnect (mc); - mc = NULL; - } + { + GNUNET_TESTBED_controller_disconnect(mc); + mc = NULL; + } if (NULL != mc_proc) - { - GNUNET_TESTBED_controller_stop (mc_proc); - mc_proc = NULL; - } + { + GNUNET_TESTBED_controller_stop(mc_proc); + mc_proc = NULL; + } if (NULL != cfg) - { - GNUNET_CONFIGURATION_destroy (cfg); - cfg = NULL; - } + { + GNUNET_CONFIGURATION_destroy(cfg); + cfg = NULL; + } } @@ -482,15 +479,15 @@ do_shutdown (void *cls) * @param cls NULL */ static void -do_abort (void *cls) +do_abort(void *cls) { - unsigned long i = (unsigned long) cls; + unsigned long i = (unsigned long)cls; - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Aborting from line %lu...\n", i); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Aborting from line %lu...\n", i); abort_task = NULL; result = GNUNET_SYSERR; - GNUNET_SCHEDULER_add_now (&do_shutdown, NULL); + GNUNET_SCHEDULER_add_now(&do_shutdown, NULL); } @@ -509,10 +506,10 @@ do_abort (void *cls) * @return service handle to return in 'op_result', NULL on error */ static void * -stats_ca (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg) +stats_ca(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg) { - return GNUNET_STATISTICS_create ("", cfg); + return GNUNET_STATISTICS_create("", cfg); } @@ -524,13 +521,13 @@ stats_ca (void *cls, * @param op_result service handle returned from the connect adapter */ static void -stats_da (void *cls, void *op_result) +stats_da(void *cls, void *op_result) { struct RegexPeer *peer = cls; - GNUNET_assert (op_result == peer->stats_handle); + GNUNET_assert(op_result == peer->stats_handle); - GNUNET_STATISTICS_destroy (peer->stats_handle, GNUNET_NO); + GNUNET_STATISTICS_destroy(peer->stats_handle, GNUNET_NO); peer->stats_handle = NULL; } @@ -546,34 +543,34 @@ stats_da (void *cls, void *op_result) * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration */ static int -stats_iterator (void *cls, - const char *subsystem, - const char *name, - uint64_t value, int is_persistent) +stats_iterator(void *cls, + const char *subsystem, + const char *name, + uint64_t value, int is_persistent) { struct RegexPeer *peer = cls; char output_buffer[512]; size_t size; if (NULL == data_file) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "%p -> %s [%s]: %llu\n", - peer, - subsystem, - name, - (unsigned long long) value); - return GNUNET_OK; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "%p -> %s [%s]: %llu\n", + peer, + subsystem, + name, + (unsigned long long)value); + return GNUNET_OK; + } size = - GNUNET_snprintf (output_buffer, - sizeof (output_buffer), - "%p [%s] %llu %s\n", - peer, - subsystem, value, name); - if (size != GNUNET_DISK_file_write (data_file, output_buffer, size)) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Unable to write to file!\n"); + GNUNET_snprintf(output_buffer, + sizeof(output_buffer), + "%p [%s] %llu %s\n", + peer, + subsystem, value, name); + if (size != GNUNET_DISK_file_write(data_file, output_buffer, size)) + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Unable to write to file!\n"); return GNUNET_OK; } @@ -588,48 +585,48 @@ stats_iterator (void *cls, * successfully obtained, GNUNET_SYSERR if not. */ static void -stats_cb (void *cls, - int success) +stats_cb(void *cls, + int success) { static unsigned int peer_cnt; struct RegexPeer *peer = cls; if (GNUNET_OK != success) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Getting statistics for peer %u failed!\n", - peer->id); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Getting statistics for peer %u failed!\n", + peer->id); + return; + } - GNUNET_assert (NULL != peer->op_handle); + GNUNET_assert(NULL != peer->op_handle); - GNUNET_TESTBED_operation_done (peer->op_handle); + GNUNET_TESTBED_operation_done(peer->op_handle); peer->op_handle = NULL; peer_cnt++; peer = &peers[peer_cnt]; - fprintf (stderr, "s"); + fprintf(stderr, "s"); if (peer_cnt == num_peers) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "\nCollecting stats finished. Shutting down.\n"); - GNUNET_SCHEDULER_shutdown (); - result = GNUNET_OK; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "\nCollecting stats finished. Shutting down.\n"); + GNUNET_SCHEDULER_shutdown(); + result = GNUNET_OK; + } else - { - peer->op_handle = - GNUNET_TESTBED_service_connect (NULL, - peer->peer_handle, - "statistics", - &stats_connect_cb, - peer, - &stats_ca, - &stats_da, - peer); - } + { + peer->op_handle = + GNUNET_TESTBED_service_connect(NULL, + peer->peer_handle, + "statistics", + &stats_connect_cb, + peer, + &stats_ca, + &stats_da, + peer); + } } @@ -643,32 +640,32 @@ stats_cb (void *cls, * @param emsg error message on failure */ static void -stats_connect_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg) +stats_connect_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg) { struct RegexPeer *peer = cls; if (NULL == ca_result || NULL != emsg) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to connect to statistics service on peer %u: %s\n", - peer->id, emsg); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to connect to statistics service on peer %u: %s\n", + peer->id, emsg); - peer->stats_handle = NULL; - return; - } + peer->stats_handle = NULL; + return; + } peer->stats_handle = ca_result; - if (NULL == GNUNET_STATISTICS_get (peer->stats_handle, NULL, NULL, - &stats_cb, - &stats_iterator, peer)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not get statistics of peer %u!\n", peer->id); - } + if (NULL == GNUNET_STATISTICS_get(peer->stats_handle, NULL, NULL, + &stats_cb, + &stats_iterator, peer)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not get statistics of peer %u!\n", peer->id); + } } @@ -679,21 +676,21 @@ stats_connect_cb (void *cls, * @param cls NULL */ static void -do_collect_stats (void *cls) +do_collect_stats(void *cls) { struct RegexPeer *peer = &peers[0]; - GNUNET_assert (NULL != peer->peer_handle); + GNUNET_assert(NULL != peer->peer_handle); peer->op_handle = - GNUNET_TESTBED_service_connect (NULL, - peer->peer_handle, - "statistics", - &stats_connect_cb, - peer, - &stats_ca, - &stats_da, - peer); + GNUNET_TESTBED_service_connect(NULL, + peer->peer_handle, + "statistics", + &stats_connect_cb, + peer, + &stats_ca, + &stats_da, + peer); } @@ -708,7 +705,7 @@ do_collect_stats (void *cls) * @param cls Index of the next peer in the peers array. */ static void -find_string (void *cls); +find_string(void *cls); /** @@ -723,94 +720,94 @@ find_string (void *cls); * @param put_path_length Length of the put_path. */ static void -regex_found_handler (void *cls, - const struct GNUNET_PeerIdentity *id, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length) +regex_found_handler(void *cls, + const struct GNUNET_PeerIdentity *id, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length) { struct RegexPeer *peer = cls; char output_buffer[512]; size_t size; if (GNUNET_YES == peer->search_str_matched) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "String %s on peer %u already matched!\n", - peer->search_str, peer->id); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "String %s on peer %u already matched!\n", + peer->search_str, peer->id); + return; + } strings_found++; parallel_searches--; if (NULL != peer->timeout) - { - GNUNET_SCHEDULER_cancel (peer->timeout); - peer->timeout = NULL; - if (GNUNET_NO == in_shutdown) - GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL); - } + { + GNUNET_SCHEDULER_cancel(peer->timeout); + peer->timeout = NULL; + if (GNUNET_NO == in_shutdown) + GNUNET_SCHEDULER_add_now(&announce_next_regex, NULL); + } if (NULL == id) - { - // FIXME not possible right now - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "String matching timed out for string %s on peer %u (%i/%i)\n", - peer->search_str, peer->id, strings_found, num_peers); - peer->search_str_matched = GNUNET_SYSERR; - } + { + // FIXME not possible right now + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "String matching timed out for string %s on peer %u (%i/%i)\n", + peer->search_str, peer->id, strings_found, num_peers); + peer->search_str_matched = GNUNET_SYSERR; + } else - { - prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time); - - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "String %s found on peer %u after %s (%i/%i) (%u||)\n", - peer->search_str, peer->id, - GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO), - strings_found, num_peers, parallel_searches); - - peer->search_str_matched = GNUNET_YES; - - if (NULL != data_file) { - size = - GNUNET_snprintf (output_buffer, - sizeof (output_buffer), - "%p Peer: %u\n" - "%p Search string: %s\n" - "%p Search duration: %s\n\n", - peer, peer->id, - peer, peer->search_str, - peer, - GNUNET_STRINGS_relative_time_to_string (prof_time, - GNUNET_NO)); - - if (size != GNUNET_DISK_file_write (data_file, output_buffer, size)) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n"); + prof_time = GNUNET_TIME_absolute_get_duration(peer->prof_start_time); + + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "String %s found on peer %u after %s (%i/%i) (%u||)\n", + peer->search_str, peer->id, + GNUNET_STRINGS_relative_time_to_string(prof_time, GNUNET_NO), + strings_found, num_peers, parallel_searches); + + peer->search_str_matched = GNUNET_YES; + + if (NULL != data_file) + { + size = + GNUNET_snprintf(output_buffer, + sizeof(output_buffer), + "%p Peer: %u\n" + "%p Search string: %s\n" + "%p Search duration: %s\n\n", + peer, peer->id, + peer, peer->search_str, + peer, + GNUNET_STRINGS_relative_time_to_string(prof_time, + GNUNET_NO)); + + if (size != GNUNET_DISK_file_write(data_file, output_buffer, size)) + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n"); + } } - } - GNUNET_TESTBED_operation_done (peer->op_handle); + GNUNET_TESTBED_operation_done(peer->op_handle); peer->op_handle = NULL; if (strings_found == num_peers) - { - prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "All strings successfully matched in %s\n", - GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO)); - - if (NULL != search_timeout_task) { - GNUNET_SCHEDULER_cancel (search_timeout_task); - search_timeout_task = NULL; - } + prof_time = GNUNET_TIME_absolute_get_duration(prof_start_time); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "All strings successfully matched in %s\n", + GNUNET_STRINGS_relative_time_to_string(prof_time, GNUNET_NO)); + + if (NULL != search_timeout_task) + { + GNUNET_SCHEDULER_cancel(search_timeout_task); + search_timeout_task = NULL; + } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Collecting stats.\n"); - GNUNET_SCHEDULER_add_now (&do_collect_stats, NULL); - } + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Collecting stats.\n"); + GNUNET_SCHEDULER_add_now(&do_collect_stats, NULL); + } } @@ -821,33 +818,33 @@ regex_found_handler (void *cls, * @param cls NULL */ static void -search_timed_out (void *cls) +search_timed_out(void *cls) { unsigned int i; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Finding matches to all strings did not succeed after %s.\n", - GNUNET_STRINGS_relative_time_to_string (search_timeout_time, - GNUNET_NO)); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Found %i of %i strings\n", strings_found, num_peers); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Finding matches to all strings did not succeed after %s.\n", + GNUNET_STRINGS_relative_time_to_string(search_timeout_time, + GNUNET_NO)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Found %i of %i strings\n", strings_found, num_peers); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Search timed out after %s." - "Collecting stats and shutting down.\n", - GNUNET_STRINGS_relative_time_to_string (search_timeout_time, - GNUNET_NO)); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Search timed out after %s." + "Collecting stats and shutting down.\n", + GNUNET_STRINGS_relative_time_to_string(search_timeout_time, + GNUNET_NO)); in_shutdown = GNUNET_YES; for (i = 0; i < num_peers; i++) - { - if (NULL != peers[i].op_handle) { - GNUNET_TESTBED_operation_done (peers[i].op_handle); - peers[i].op_handle = NULL; + if (NULL != peers[i].op_handle) + { + GNUNET_TESTBED_operation_done(peers[i].op_handle); + peers[i].op_handle = NULL; + } } - } - GNUNET_SCHEDULER_add_now (&do_collect_stats, NULL); + GNUNET_SCHEDULER_add_now(&do_collect_stats, NULL); } @@ -858,17 +855,17 @@ search_timed_out (void *cls) * @param cls Index of the next peer in the peers array. */ static void -find_timed_out (void *cls) +find_timed_out(void *cls) { struct RegexPeer *p = cls; p->timeout = NULL; - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Searching for string \"%s\" on peer %d timed out.\n", - p->search_str, - p->id); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Searching for string \"%s\" on peer %d timed out.\n", + p->search_str, + p->id); if (GNUNET_NO == in_shutdown) - GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL); + GNUNET_SCHEDULER_add_now(&announce_next_regex, NULL); } @@ -878,34 +875,34 @@ find_timed_out (void *cls) * @param cls Index of the next peer in the peers array. */ static void -find_string (void *cls) +find_string(void *cls) { - unsigned int search_peer = (unsigned int) (long) cls; + unsigned int search_peer = (unsigned int)(long)cls; - if ( (search_peer >= num_peers) || - (GNUNET_YES == in_shutdown) ) + if ((search_peer >= num_peers) || + (GNUNET_YES == in_shutdown)) return; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Searching for string \"%s\" on peer %d (%u||)\n", - peers[search_peer].search_str, - search_peer, - parallel_searches); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Searching for string \"%s\" on peer %d (%u||)\n", + peers[search_peer].search_str, + search_peer, + parallel_searches); peers[search_peer].op_handle = - GNUNET_TESTBED_service_connect (NULL, - peers[search_peer].peer_handle, - "dht", - &dht_connect_cb, - &peers[search_peer], - &dht_ca, - &dht_da, - &peers[search_peer]); - GNUNET_assert (NULL != peers[search_peer].op_handle); + GNUNET_TESTBED_service_connect(NULL, + peers[search_peer].peer_handle, + "dht", + &dht_connect_cb, + &peers[search_peer], + &dht_ca, + &dht_da, + &peers[search_peer]); + GNUNET_assert(NULL != peers[search_peer].op_handle); peers[search_peer].timeout - = GNUNET_SCHEDULER_add_delayed (FIND_TIMEOUT, - &find_timed_out, - &peers[search_peer]); + = GNUNET_SCHEDULER_add_delayed(FIND_TIMEOUT, + &find_timed_out, + &peers[search_peer]); } @@ -917,44 +914,44 @@ find_string (void *cls) * @param emsg NULL on success; otherwise an error description */ static void -daemon_started (void *cls, - struct GNUNET_TESTBED_Operation *op, - const char *emsg) +daemon_started(void *cls, + struct GNUNET_TESTBED_Operation *op, + const char *emsg) { - struct RegexPeer *peer = (struct RegexPeer *) cls; + struct RegexPeer *peer = (struct RegexPeer *)cls; unsigned long search_peer; unsigned int i; - GNUNET_TESTBED_operation_done (peer->daemon_op); + GNUNET_TESTBED_operation_done(peer->daemon_op); peer->daemon_op = NULL; if (NULL != emsg) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Failed to start/stop daemon at peer %u: %s\n", peer->id, emsg); - GNUNET_assert (0); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Failed to start/stop daemon at peer %u: %s\n", peer->id, emsg); + GNUNET_assert(0); + } else - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Deamon %u started successfully\n", peer->id); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Deamon %u started successfully\n", peer->id); + } /* Find a peer to look for a string matching the regex announced */ - search_peer = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - num_peers); + search_peer = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + num_peers); for (i = 0; peers[search_peer].search_str != NULL; i++) - { - search_peer = (search_peer + 1) % num_peers; - if (i > num_peers) - GNUNET_assert (0); /* we ran out of peers, must be a bug */ - } + { + search_peer = (search_peer + 1) % num_peers; + if (i > num_peers) + GNUNET_assert(0); /* we ran out of peers, must be a bug */ + } peers[search_peer].search_str = search_strings[peer->id]; peers[search_peer].search_str_matched = GNUNET_NO; - GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_saturating_multiply( - reannounce_period_max, - 2), - &find_string, - (void *) search_peer); + GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_saturating_multiply( + reannounce_period_max, + 2), + &find_string, + (void *)search_peer); } @@ -966,21 +963,21 @@ daemon_started (void *cls, * @param tc the task context */ static void -do_announce (void *cls) +do_announce(void *cls) { unsigned int i; if (GNUNET_YES == in_shutdown) return; - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Starting announce.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Starting announce.\n"); for (i = 0; i < init_parallel_searches; i++) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - " scheduling announce %u\n", - i); - (void) GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + " scheduling announce %u\n", + i); + (void)GNUNET_SCHEDULER_add_now(&announce_next_regex, NULL); + } } @@ -990,36 +987,36 @@ do_announce (void *cls) * @param cls Closure (unused). */ static void -announce_next_regex (void *cls) +announce_next_regex(void *cls) { struct RegexPeer *peer; if (GNUNET_YES == in_shutdown) return; if (next_search >= num_peers) - { - if (strings_found != num_peers) { - struct GNUNET_TIME_Relative new_delay; - if (NULL != search_timeout_task) - GNUNET_SCHEDULER_cancel (search_timeout_task); - new_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15); - search_timeout_task = GNUNET_SCHEDULER_add_delayed (new_delay, - &search_timed_out, - NULL); + if (strings_found != num_peers) + { + struct GNUNET_TIME_Relative new_delay; + if (NULL != search_timeout_task) + GNUNET_SCHEDULER_cancel(search_timeout_task); + new_delay = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15); + search_timeout_task = GNUNET_SCHEDULER_add_delayed(new_delay, + &search_timed_out, + NULL); + } + return; } - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Starting daemon %u\n", next_search); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Starting daemon %u\n", next_search); peer = &peers[next_search]; peer->daemon_op = - GNUNET_TESTBED_peer_manage_service (NULL, - peer->peer_handle, - "regexprofiler", - &daemon_started, - peer, - 1); + GNUNET_TESTBED_peer_manage_service(NULL, + peer->peer_handle, + "regexprofiler", + &daemon_started, + peer, + 1); next_search++; parallel_searches++; } @@ -1036,29 +1033,29 @@ announce_next_regex (void *cls) * @param emsg error message. */ static void -dht_connect_cb (void *cls, - struct GNUNET_TESTBED_Operation *op, - void *ca_result, - const char *emsg) +dht_connect_cb(void *cls, + struct GNUNET_TESTBED_Operation *op, + void *ca_result, + const char *emsg) { - struct RegexPeer *peer = (struct RegexPeer *) cls; + struct RegexPeer *peer = (struct RegexPeer *)cls; if (NULL != emsg || NULL == op || NULL == ca_result) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "DHT connect failed: %s\n", emsg); - GNUNET_assert (0); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "DHT connect failed: %s\n", emsg); + GNUNET_assert(0); + } - GNUNET_assert (NULL != peer->dht_handle); - GNUNET_assert (peer->op_handle == op); - GNUNET_assert (peer->dht_handle == ca_result); + GNUNET_assert(NULL != peer->dht_handle); + GNUNET_assert(peer->op_handle == op); + GNUNET_assert(peer->dht_handle == ca_result); peer->search_str_matched = GNUNET_NO; - peer->search_handle = REGEX_INTERNAL_search (peer->dht_handle, - peer->search_str, - ®ex_found_handler, peer, - NULL); - peer->prof_start_time = GNUNET_TIME_absolute_get (); + peer->search_handle = REGEX_INTERNAL_search(peer->dht_handle, + peer->search_str, + ®ex_found_handler, peer, + NULL); + peer->prof_start_time = GNUNET_TIME_absolute_get(); } @@ -1071,11 +1068,11 @@ dht_connect_cb (void *cls, * @return */ static void * -dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg) +dht_ca(void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg) { struct RegexPeer *peer = cls; - peer->dht_handle = GNUNET_DHT_connect (cfg, 32); + peer->dht_handle = GNUNET_DHT_connect(cfg, 32); return peer->dht_handle; } @@ -1088,23 +1085,23 @@ dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg) * @param op_result Service handle returned from the connect adapter. */ static void -dht_da (void *cls, void *op_result) +dht_da(void *cls, void *op_result) { - struct RegexPeer *peer = (struct RegexPeer *) cls; + struct RegexPeer *peer = (struct RegexPeer *)cls; - GNUNET_assert (peer->dht_handle == op_result); + GNUNET_assert(peer->dht_handle == op_result); if (NULL != peer->search_handle) - { - REGEX_INTERNAL_search_cancel (peer->search_handle); - peer->search_handle = NULL; - } + { + REGEX_INTERNAL_search_cancel(peer->search_handle); + peer->search_handle = NULL; + } if (NULL != peer->dht_handle) - { - GNUNET_DHT_disconnect (peer->dht_handle); - peer->dht_handle = NULL; - } + { + GNUNET_DHT_disconnect(peer->dht_handle); + peer->dht_handle = NULL; + } } @@ -1122,51 +1119,51 @@ dht_da (void *cls, void *op_result) * failed */ static void -test_master (void *cls, - struct GNUNET_TESTBED_RunHandle *h, - unsigned int num_peers_, - struct GNUNET_TESTBED_Peer **testbed_peers, - unsigned int links_succeeded, - unsigned int links_failed) +test_master(void *cls, + struct GNUNET_TESTBED_RunHandle *h, + unsigned int num_peers_, + struct GNUNET_TESTBED_Peer **testbed_peers, + unsigned int links_succeeded, + unsigned int links_failed) { unsigned int i; - GNUNET_assert (num_peers_ == num_peers); + GNUNET_assert(num_peers_ == num_peers); - prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Testbed started in %s\n", - GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO)); + prof_time = GNUNET_TIME_absolute_get_duration(prof_start_time); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Testbed started in %s\n", + GNUNET_STRINGS_relative_time_to_string(prof_time, GNUNET_NO)); if (NULL != abort_task) - { - GNUNET_SCHEDULER_cancel (abort_task); - abort_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(abort_task); + abort_task = NULL; + } for (i = 0; i < num_peers; i++) - { - peers[i].peer_handle = testbed_peers[i]; - } + { + peers[i].peer_handle = testbed_peers[i]; + } if (GNUNET_NO == - GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT", "DISABLE_TRY_CONNECT")) - { - struct GNUNET_TIME_Relative settle_time; - - settle_time = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, - 10 * num_peers); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Waiting for DHT for %s to settle new connections.\n\n", - GNUNET_STRINGS_relative_time_to_string(settle_time, GNUNET_NO)); - GNUNET_SCHEDULER_add_delayed (settle_time, &do_announce, NULL); - } + GNUNET_CONFIGURATION_get_value_yesno(cfg, "DHT", "DISABLE_TRY_CONNECT")) + { + struct GNUNET_TIME_Relative settle_time; + + settle_time = + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, + 10 * num_peers); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Waiting for DHT for %s to settle new connections.\n\n", + GNUNET_STRINGS_relative_time_to_string(settle_time, GNUNET_NO)); + GNUNET_SCHEDULER_add_delayed(settle_time, &do_announce, NULL); + } else - { - GNUNET_SCHEDULER_add_now (&do_announce, NULL); - } + { + GNUNET_SCHEDULER_add_now(&do_announce, NULL); + } search_timeout_task = - GNUNET_SCHEDULER_add_delayed (search_timeout_time, &search_timed_out, NULL); + GNUNET_SCHEDULER_add_delayed(search_timeout_time, &search_timed_out, NULL); } /** @@ -1176,20 +1173,22 @@ test_master (void *cls, * @param event information on what is happening */ static void -master_controller_cb (void *cls, - const struct GNUNET_TESTBED_EventInformation *event) +master_controller_cb(void *cls, + const struct GNUNET_TESTBED_EventInformation *event) { switch (event->type) - { - case GNUNET_TESTBED_ET_CONNECT: - printf("."); - break; - case GNUNET_TESTBED_ET_PEER_START: - printf("#"); - break; - default: - break; - } + { + case GNUNET_TESTBED_ET_CONNECT: + printf("."); + break; + + case GNUNET_TESTBED_ET_PEER_START: + printf("#"); + break; + + default: + break; + } fflush(stdout); } @@ -1209,9 +1208,9 @@ master_controller_cb (void *cls, * #GNUNET_SYSERR otherwise. */ static int -count_and_separate_strings (char *data, - uint64_t data_size, - unsigned int str_max) +count_and_separate_strings(char *data, + uint64_t data_size, + unsigned int str_max) { char *buf; // Keep track of last string to skip blank lines unsigned int offset; @@ -1220,20 +1219,20 @@ count_and_separate_strings (char *data, buf = data; offset = 0; str_cnt = 0; - while ( (offset < (data_size - 1)) && (str_cnt < str_max) ) - { - offset++; - if ( ((data[offset] == '\n')) && - (buf != &data[offset]) ) + while ((offset < (data_size - 1)) && (str_cnt < str_max)) { - data[offset] = '\0'; - str_cnt++; - buf = &data[offset + 1]; + offset++; + if (((data[offset] == '\n')) && + (buf != &data[offset])) + { + data[offset] = '\0'; + str_cnt++; + buf = &data[offset + 1]; + } + else if ((data[offset] == '\n') || + (data[offset] == '\0')) + buf = &data[offset + 1]; } - else if ( (data[offset] == '\n') || - (data[offset] == '\0') ) - buf = &data[offset + 1]; - } return str_cnt; } @@ -1252,37 +1251,37 @@ count_and_separate_strings (char *data, * In case of error @a strings must not be freed. */ static int -create_string_array (char *data, uint64_t data_size, - char ***strings, unsigned int str_cnt) +create_string_array(char *data, uint64_t data_size, + char ***strings, unsigned int str_cnt) { uint64_t offset; uint64_t len; unsigned int i; - *strings = GNUNET_malloc (sizeof (char *) * str_cnt); + *strings = GNUNET_malloc(sizeof(char *) * str_cnt); offset = 0; for (i = 0; i < str_cnt; i++) - { - len = strlen (&data[offset]); - if (offset + len >= data_size) - { - GNUNET_free (*strings); - *strings = NULL; - return GNUNET_SYSERR; - } - if (0 == len) // empty line { - offset++; - i--; - continue; + len = strlen(&data[offset]); + if (offset + len >= data_size) + { + GNUNET_free(*strings); + *strings = NULL; + return GNUNET_SYSERR; + } + if (0 == len) // empty line + { + offset++; + i--; + continue; + } + + GNUNET_asprintf(&(*strings)[i], + "%s%s", + regex_prefix, + &data[offset]); + offset += len + 1; } - - GNUNET_asprintf (&(*strings)[i], - "%s%s", - regex_prefix, - &data[offset]); - offset += len + 1; - } return GNUNET_OK; } @@ -1297,9 +1296,9 @@ create_string_array (char *data, uint64_t data_size, * @return number of strings found in the file. #GNUNET_SYSERR on error. */ static int -load_search_strings (const char *filename, - char ***strings, - unsigned int limit) +load_search_strings(const char *filename, + char ***strings, + unsigned int limit) { char *data; uint64_t filesize; @@ -1307,54 +1306,54 @@ load_search_strings (const char *filename, /* Sanity checks */ if (NULL == filename) - { - return GNUNET_SYSERR; - } - if (GNUNET_YES != GNUNET_DISK_file_test (filename)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Could not find search strings file %s\n", filename); - return GNUNET_SYSERR; - } + { + return GNUNET_SYSERR; + } + if (GNUNET_YES != GNUNET_DISK_file_test(filename)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Could not find search strings file %s\n", filename); + return GNUNET_SYSERR; + } if (GNUNET_OK != - GNUNET_DISK_file_size (filename, - &filesize, - GNUNET_YES, - GNUNET_YES)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Search strings file %s cannot be read.\n", - filename); - return GNUNET_SYSERR; - } + GNUNET_DISK_file_size(filename, + &filesize, + GNUNET_YES, + GNUNET_YES)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Search strings file %s cannot be read.\n", + filename); + return GNUNET_SYSERR; + } if (0 == filesize) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Search strings file %s is empty.\n", - filename); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Search strings file %s is empty.\n", + filename); + return GNUNET_SYSERR; + } /* Read data into memory */ - data = GNUNET_malloc (filesize + 1); - if (filesize != GNUNET_DISK_fn_read (filename, - data, - filesize)) - { - GNUNET_free (data); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Could not read search strings file %s.\n", - filename); - return GNUNET_SYSERR; - } + data = GNUNET_malloc(filesize + 1); + if (filesize != GNUNET_DISK_fn_read(filename, + data, + filesize)) + { + GNUNET_free(data); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Could not read search strings file %s.\n", + filename); + return GNUNET_SYSERR; + } /* Process buffer and build array */ - str_cnt = count_and_separate_strings (data, filesize, limit); - if (GNUNET_OK != create_string_array (data, filesize, strings, str_cnt)) - { - str_cnt = GNUNET_SYSERR; - } - GNUNET_free (data); + str_cnt = count_and_separate_strings(data, filesize, limit); + if (GNUNET_OK != create_string_array(data, filesize, strings, str_cnt)) + { + str_cnt = GNUNET_SYSERR; + } + GNUNET_free(data); return str_cnt; } @@ -1368,10 +1367,10 @@ load_search_strings (const char *filename, * @param config configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *config) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *config) { unsigned int nsearchstrs; unsigned int i; @@ -1381,161 +1380,161 @@ run (void *cls, /* Check config */ if (NULL == config) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No configuration file given. Exiting\n")); - GNUNET_SCHEDULER_add_now (&do_shutdown, NULL); - return; - } - cfg = GNUNET_CONFIGURATION_dup (config); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No configuration file given. Exiting\n")); + GNUNET_SCHEDULER_add_now(&do_shutdown, NULL); + return; + } + cfg = GNUNET_CONFIGURATION_dup(config); if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, "REGEXPROFILER", - "REGEX_PREFIX", - ®ex_prefix)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "regexprofiler", - "regex_prefix"); - GNUNET_SCHEDULER_add_now (&do_shutdown, NULL); - return; - } + GNUNET_CONFIGURATION_get_value_string(cfg, "REGEXPROFILER", + "REGEX_PREFIX", + ®ex_prefix)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "regexprofiler", + "regex_prefix"); + GNUNET_SCHEDULER_add_now(&do_shutdown, NULL); + return; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (cfg, "REGEXPROFILER", - "PARALLEL_SEARCHES", - &init_parallel_searches)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Configuration option \"PARALLEL_SEARCHES\" missing." - " Using default (%d)\n", 10); - init_parallel_searches = 10; - } + GNUNET_CONFIGURATION_get_value_number(cfg, "REGEXPROFILER", + "PARALLEL_SEARCHES", + &init_parallel_searches)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Configuration option \"PARALLEL_SEARCHES\" missing." + " Using default (%d)\n", 10); + init_parallel_searches = 10; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_time (cfg, "REGEXPROFILER", - "REANNOUNCE_PERIOD_MAX", - &reannounce_period_max)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "reannounce_period_max not given. Using 10 minutes.\n"); - reannounce_period_max = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 10); - } + GNUNET_CONFIGURATION_get_value_time(cfg, "REGEXPROFILER", + "REANNOUNCE_PERIOD_MAX", + &reannounce_period_max)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "reannounce_period_max not given. Using 10 minutes.\n"); + reannounce_period_max = + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10); + } /* Check arguments */ if (NULL == policy_dir) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No policy directory specified on command line. Exiting.\n")); - return; - } - if (GNUNET_YES != GNUNET_DISK_directory_test (policy_dir, GNUNET_YES)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Specified policies directory does not exist. Exiting.\n")); - GNUNET_SCHEDULER_add_now (&do_shutdown, NULL); - return; - } - if (0 >= (int) (num_peers = GNUNET_DISK_directory_scan (policy_dir, NULL, NULL))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No files found in `%s'\n"), - policy_dir); - return; - } - GNUNET_CONFIGURATION_set_value_string (cfg, "REGEXPROFILER", - "POLICY_DIR", policy_dir); - if (GNUNET_YES != GNUNET_DISK_file_test (strings_file)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("No search strings file given. Exiting.\n")); - GNUNET_SCHEDULER_add_now (&do_shutdown, NULL); - return; - } - nsearchstrs = load_search_strings (strings_file, - &search_strings, - num_peers); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No policy directory specified on command line. Exiting.\n")); + return; + } + if (GNUNET_YES != GNUNET_DISK_directory_test(policy_dir, GNUNET_YES)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Specified policies directory does not exist. Exiting.\n")); + GNUNET_SCHEDULER_add_now(&do_shutdown, NULL); + return; + } + if (0 >= (int)(num_peers = GNUNET_DISK_directory_scan(policy_dir, NULL, NULL))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No files found in `%s'\n"), + policy_dir); + return; + } + GNUNET_CONFIGURATION_set_value_string(cfg, "REGEXPROFILER", + "POLICY_DIR", policy_dir); + if (GNUNET_YES != GNUNET_DISK_file_test(strings_file)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("No search strings file given. Exiting.\n")); + GNUNET_SCHEDULER_add_now(&do_shutdown, NULL); + return; + } + nsearchstrs = load_search_strings(strings_file, + &search_strings, + num_peers); if (num_peers != nsearchstrs) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error loading search strings.\n"); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "File (%s) does not contain enough strings (%u/%u).\n", - strings_file, nsearchstrs, num_peers); - GNUNET_SCHEDULER_add_now (&do_shutdown, NULL); - return; - } - if ( (0 == num_peers) || (NULL == search_strings)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - _("Error loading search strings. Exiting.\n")); - GNUNET_SCHEDULER_add_now (&do_shutdown, NULL); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error loading search strings.\n"); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "File (%s) does not contain enough strings (%u/%u).\n", + strings_file, nsearchstrs, num_peers); + GNUNET_SCHEDULER_add_now(&do_shutdown, NULL); + return; + } + if ((0 == num_peers) || (NULL == search_strings)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + _("Error loading search strings. Exiting.\n")); + GNUNET_SCHEDULER_add_now(&do_shutdown, NULL); + return; + } for (i = 0; i < num_peers; i++) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "search string: %s\n", - search_strings[i]); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "search string: %s\n", + search_strings[i]); /* Check logfile */ - if ( (NULL != data_filename) && - (NULL == (data_file = - GNUNET_DISK_file_open (data_filename, + if ((NULL != data_filename) && + (NULL == (data_file = + GNUNET_DISK_file_open(data_filename, GNUNET_DISK_OPEN_READWRITE | GNUNET_DISK_OPEN_TRUNCATE | GNUNET_DISK_OPEN_CREATE, GNUNET_DISK_PERM_USER_READ | - GNUNET_DISK_PERM_USER_WRITE))) ) - { - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, - "open", - data_filename); - return; - } + GNUNET_DISK_PERM_USER_WRITE)))) + { + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, + "open", + data_filename); + return; + } /* Initialize peers */ - peers = GNUNET_malloc (sizeof (struct RegexPeer) * num_peers); + peers = GNUNET_malloc(sizeof(struct RegexPeer) * num_peers); for (i = 0; i < num_peers; i++) peers[i].id = i; - GNUNET_CONFIGURATION_set_value_number (cfg, - "TESTBED", "OVERLAY_RANDOM_LINKS", - num_peers * 20); - GNUNET_CONFIGURATION_set_value_number (cfg, - "DHT", "FORCE_NSE", - (long long unsigned) - (log (num_peers) / log (2.0))); + GNUNET_CONFIGURATION_set_value_number(cfg, + "TESTBED", "OVERLAY_RANDOM_LINKS", + num_peers * 20); + GNUNET_CONFIGURATION_set_value_number(cfg, + "DHT", "FORCE_NSE", + (long long unsigned) + (log(num_peers) / log(2.0))); event_mask = 0LL; /* For feedback about the start process activate these and pass master_cb */ event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_START); // event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_STOP); event_mask |= (1LL << GNUNET_TESTBED_ET_CONNECT); // event_mask |= (1LL << GNUNET_TESTBED_ET_DISCONNECT); - prof_start_time = GNUNET_TIME_absolute_get (); - GNUNET_TESTBED_run (hosts_file, - cfg, - num_peers, - event_mask, - &master_controller_cb, - NULL, /* master_controller_cb cls */ - &test_master, - NULL); /* test_master cls */ + prof_start_time = GNUNET_TIME_absolute_get(); + GNUNET_TESTBED_run(hosts_file, + cfg, + num_peers, + event_mask, + &master_controller_cb, + NULL, /* master_controller_cb cls */ + &test_master, + NULL); /* test_master cls */ if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_time (cfg, "TESTBED", - "SETUP_TIMEOUT", - &abort_time)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "SETUP_TIMEOUT not given. Using 15 minutes.\n"); - abort_time = - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15); - } - abort_time = GNUNET_TIME_relative_add (abort_time, GNUNET_TIME_UNIT_MINUTES); + GNUNET_CONFIGURATION_get_value_time(cfg, "TESTBED", + "SETUP_TIMEOUT", + &abort_time)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "SETUP_TIMEOUT not given. Using 15 minutes.\n"); + abort_time = + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 15); + } + abort_time = GNUNET_TIME_relative_add(abort_time, GNUNET_TIME_UNIT_MINUTES); abort_task = - GNUNET_SCHEDULER_add_delayed (abort_time, - &do_abort, - (void*) __LINE__); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "setup_timeout: %s\n", - GNUNET_STRINGS_relative_time_to_string (abort_time, GNUNET_YES)); + GNUNET_SCHEDULER_add_delayed(abort_time, + &do_abort, + (void*)__LINE__); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "setup_timeout: %s\n", + GNUNET_STRINGS_relative_time_to_string(abort_time, GNUNET_YES)); } @@ -1547,53 +1546,52 @@ run (void *cls, * @return 0 on success */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { - - GNUNET_GETOPT_option_filename ('o', - "output-file", - "FILENAME", - gettext_noop ("name of the file for writing statistics"), - &data_filename), - - GNUNET_GETOPT_option_relative_time ('t', - "matching-timeout", - "TIMEOUT", - gettext_noop ("wait TIMEOUT before ending the experiment"), - &search_timeout_time), - - GNUNET_GETOPT_option_filename ('p', - "policy-dir", - "DIRECTORY", - gettext_noop ("directory with policy files"), - &policy_dir), - - - GNUNET_GETOPT_option_filename ('s', - "strings-file", - "FILENAME", - gettext_noop ("name of file with input strings"), - &strings_file), - - GNUNET_GETOPT_option_filename ('H', - "hosts-file", - "FILENAME", - gettext_noop ("name of file with hosts' names"), - &hosts_file), + GNUNET_GETOPT_option_filename('o', + "output-file", + "FILENAME", + gettext_noop("name of the file for writing statistics"), + &data_filename), + + GNUNET_GETOPT_option_relative_time('t', + "matching-timeout", + "TIMEOUT", + gettext_noop("wait TIMEOUT before ending the experiment"), + &search_timeout_time), + + GNUNET_GETOPT_option_filename('p', + "policy-dir", + "DIRECTORY", + gettext_noop("directory with policy files"), + &policy_dir), + + + GNUNET_GETOPT_option_filename('s', + "strings-file", + "FILENAME", + gettext_noop("name of file with input strings"), + &strings_file), + + GNUNET_GETOPT_option_filename('H', + "hosts-file", + "FILENAME", + gettext_noop("name of file with hosts' names"), + &hosts_file), GNUNET_GETOPT_OPTION_END }; int ret; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; result = GNUNET_SYSERR; ret = - GNUNET_PROGRAM_run (argc, argv, - "gnunet-regex-profiler", - _("Profiler for regex"), - options, &run, NULL); + GNUNET_PROGRAM_run(argc, argv, + "gnunet-regex-profiler", + _("Profiler for regex"), + options, &run, NULL); if (GNUNET_OK != ret) return ret; if (GNUNET_OK != result) diff --git a/src/regex/gnunet-regex-simulation-profiler.c b/src/regex/gnunet-regex-simulation-profiler.c index d82b7800a..aa297d2ea 100644 --- a/src/regex/gnunet-regex-simulation-profiler.c +++ b/src/regex/gnunet-regex-simulation-profiler.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** @@ -38,22 +38,21 @@ /** * MySQL statement to insert an edge. */ -#define INSERT_EDGE_STMT "INSERT IGNORE INTO `%s` "\ - "(`key`, `label`, `to_key`, `accepting`) "\ - "VALUES (?, ?, ?, ?);" +#define INSERT_EDGE_STMT "INSERT IGNORE INTO `%s` " \ + "(`key`, `label`, `to_key`, `accepting`) " \ + "VALUES (?, ?, ?, ?);" /** * MySQL statement to select a key count. */ -#define SELECT_KEY_STMT "SELECT COUNT(*) FROM `%s` "\ - "WHERE `key` = ? AND `label` = ?;" +#define SELECT_KEY_STMT "SELECT COUNT(*) FROM `%s` " \ + "WHERE `key` = ? AND `label` = ?;" /** * Simple struct to keep track of progress, and print a * nice little percentage meter for long running tasks. */ -struct ProgressMeter -{ +struct ProgressMeter { /** * Total number of elements. */ @@ -168,11 +167,11 @@ static char *regex_prefix; * @return the progress meter */ static struct ProgressMeter * -create_meter (unsigned int total, char *start_string, int print) +create_meter(unsigned int total, char *start_string, int print) { struct ProgressMeter *ret; - ret = GNUNET_new (struct ProgressMeter); + ret = GNUNET_new(struct ProgressMeter); ret->print = print; ret->total = total; ret->modnum = total / 4; @@ -180,9 +179,9 @@ create_meter (unsigned int total, char *start_string, int print) ret->modnum = 1; ret->dotnum = (total / 50) + 1; if (start_string != NULL) - ret->startup_string = GNUNET_strdup (start_string); + ret->startup_string = GNUNET_strdup(start_string); else - ret->startup_string = GNUNET_strdup (""); + ret->startup_string = GNUNET_strdup(""); return ret; } @@ -197,33 +196,33 @@ create_meter (unsigned int total, char *start_string, int print) * GNUNET_NO if more items expected */ static int -update_meter (struct ProgressMeter *meter) +update_meter(struct ProgressMeter *meter) { if (meter->print == GNUNET_YES) - { - if (meter->completed % meter->modnum == 0) { - if (meter->completed == 0) - { - fprintf (stdout, "%sProgress: [0%%", meter->startup_string); - } - else - fprintf (stdout, "%d%%", - (int) (((float) meter->completed / meter->total) * 100)); + if (meter->completed % meter->modnum == 0) + { + if (meter->completed == 0) + { + fprintf(stdout, "%sProgress: [0%%", meter->startup_string); + } + else + fprintf(stdout, "%d%%", + (int)(((float)meter->completed / meter->total) * 100)); + } + else if (meter->completed % meter->dotnum == 0) + fprintf(stdout, "%s", "."); + + if (meter->completed + 1 == meter->total) + fprintf(stdout, "%d%%]\n", 100); + fflush(stdout); } - else if (meter->completed % meter->dotnum == 0) - fprintf (stdout, "%s", "."); - - if (meter->completed + 1 == meter->total) - fprintf (stdout, "%d%%]\n", 100); - fflush (stdout); - } meter->completed++; if (meter->completed == meter->total) return GNUNET_YES; if (meter->completed > meter->total) - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Progress meter overflow!!\n"); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Progress meter overflow!!\n"); return GNUNET_NO; } @@ -237,7 +236,7 @@ update_meter (struct ProgressMeter *meter) * #GNUNET_SYSERR on error */ static int -reset_meter (struct ProgressMeter *meter) +reset_meter(struct ProgressMeter *meter) { if (meter == NULL) return GNUNET_SYSERR; @@ -253,10 +252,10 @@ reset_meter (struct ProgressMeter *meter) * @param meter the meter to free */ static void -free_meter (struct ProgressMeter *meter) +free_meter(struct ProgressMeter *meter) { - GNUNET_free_non_null (meter->startup_string); - GNUNET_free (meter); + GNUNET_free_non_null(meter->startup_string); + GNUNET_free(meter); } @@ -266,18 +265,18 @@ free_meter (struct ProgressMeter *meter) * @param cls NULL */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { if (NULL != mysql_ctx) - { - GNUNET_MYSQL_context_destroy (mysql_ctx); - mysql_ctx = NULL; - } + { + GNUNET_MYSQL_context_destroy(mysql_ctx); + mysql_ctx = NULL; + } if (NULL != meter) - { - free_meter (meter); - meter = NULL; - } + { + free_meter(meter); + meter = NULL; + } } @@ -293,16 +292,16 @@ do_shutdown (void *cls) * @param cls NULL */ static void -do_abort (void *cls) +do_abort(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Aborting\n"); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Aborting\n"); if (NULL != scan_task) - { - GNUNET_SCHEDULER_cancel (scan_task); - scan_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(scan_task); + scan_task = NULL; + } result = GNUNET_SYSERR; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } /** @@ -316,12 +315,12 @@ do_abort (void *cls) * @param edges edges leaving current state. */ static void -regex_iterator (void *cls, - const struct GNUNET_HashCode *key, - const char *proof, - int accepting, - unsigned int num_edges, - const struct REGEX_BLOCK_Edge *edges) +regex_iterator(void *cls, + const struct GNUNET_HashCode *key, + const char *proof, + int accepting, + unsigned int num_edges, + const struct REGEX_BLOCK_Edge *edges) { unsigned int i; int result; @@ -329,118 +328,118 @@ regex_iterator (void *cls, uint32_t iaccepting = (uint32_t)accepting; uint64_t total; - GNUNET_assert (NULL != mysql_ctx); + GNUNET_assert(NULL != mysql_ctx); for (i = 0; i < num_edges; i++) - { - struct GNUNET_MY_QueryParam params_select[] = { - GNUNET_MY_query_param_auto_from_type (key), - GNUNET_MY_query_param_string (edges[i].label), - GNUNET_MY_query_param_end - }; - - struct GNUNET_MY_ResultSpec results_select[] = { - GNUNET_MY_result_spec_uint64 (&total), - GNUNET_MY_result_spec_end - }; - - result = - GNUNET_MY_exec_prepared (mysql_ctx, - select_stmt_handle, - params_select); - - if (GNUNET_SYSERR == result) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error executing prepared mysql select statement\n"); - GNUNET_SCHEDULER_add_now (&do_abort, NULL); - return; - } - - result = - GNUNET_MY_extract_result (select_stmt_handle, - results_select); - - if (GNUNET_SYSERR == result) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error extracting result mysql select statement\n"); - GNUNET_SCHEDULER_add_now (&do_abort, NULL); - return; - } - - if (-1 != total && total > 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Total: %llu (%s, %s)\n", - (unsigned long long)total, - GNUNET_h2s (key), edges[i].label); - } - - struct GNUNET_MY_QueryParam params_stmt[] = { - GNUNET_MY_query_param_auto_from_type (&key), - GNUNET_MY_query_param_string (edges[i].label), - GNUNET_MY_query_param_auto_from_type (&edges[i].destination), - GNUNET_MY_query_param_uint32 (&iaccepting), - GNUNET_MY_query_param_end - }; - - result = - GNUNET_MY_exec_prepared (mysql_ctx, - stmt_handle, - params_stmt); - - if (0 == result) - { - char *key_str = GNUNET_strdup (GNUNET_h2s (key)); - char *to_key_str = GNUNET_strdup (GNUNET_h2s (&edges[i].destination)); - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Merged (%s, %s, %s, %i)\n", - key_str, - edges[i].label, - to_key_str, - accepting); - - GNUNET_free (key_str); - GNUNET_free (to_key_str); - num_merged_transitions++; - } - else if (-1 != total) - { - num_merged_states++; - } - - if (GNUNET_SYSERR == result || (1 != result && 0 != result)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error executing prepared mysql statement for edge: Affected rows: %i, expected 0 or 1!\n", - result); - GNUNET_SCHEDULER_add_now (&do_abort, NULL); + struct GNUNET_MY_QueryParam params_select[] = { + GNUNET_MY_query_param_auto_from_type(key), + GNUNET_MY_query_param_string(edges[i].label), + GNUNET_MY_query_param_end + }; + + struct GNUNET_MY_ResultSpec results_select[] = { + GNUNET_MY_result_spec_uint64(&total), + GNUNET_MY_result_spec_end + }; + + result = + GNUNET_MY_exec_prepared(mysql_ctx, + select_stmt_handle, + params_select); + + if (GNUNET_SYSERR == result) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error executing prepared mysql select statement\n"); + GNUNET_SCHEDULER_add_now(&do_abort, NULL); + return; + } + + result = + GNUNET_MY_extract_result(select_stmt_handle, + results_select); + + if (GNUNET_SYSERR == result) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error extracting result mysql select statement\n"); + GNUNET_SCHEDULER_add_now(&do_abort, NULL); + return; + } + + if (-1 != total && total > 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Total: %llu (%s, %s)\n", + (unsigned long long)total, + GNUNET_h2s(key), edges[i].label); + } + + struct GNUNET_MY_QueryParam params_stmt[] = { + GNUNET_MY_query_param_auto_from_type(&key), + GNUNET_MY_query_param_string(edges[i].label), + GNUNET_MY_query_param_auto_from_type(&edges[i].destination), + GNUNET_MY_query_param_uint32(&iaccepting), + GNUNET_MY_query_param_end + }; + + result = + GNUNET_MY_exec_prepared(mysql_ctx, + stmt_handle, + params_stmt); + + if (0 == result) + { + char *key_str = GNUNET_strdup(GNUNET_h2s(key)); + char *to_key_str = GNUNET_strdup(GNUNET_h2s(&edges[i].destination)); + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Merged (%s, %s, %s, %i)\n", + key_str, + edges[i].label, + to_key_str, + accepting); + + GNUNET_free(key_str); + GNUNET_free(to_key_str); + num_merged_transitions++; + } + else if (-1 != total) + { + num_merged_states++; + } + + if (GNUNET_SYSERR == result || (1 != result && 0 != result)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error executing prepared mysql statement for edge: Affected rows: %i, expected 0 or 1!\n", + result); + GNUNET_SCHEDULER_add_now(&do_abort, NULL); + } } - } if (0 == num_edges) - { - struct GNUNET_MY_QueryParam params_stmt[] = { - GNUNET_MY_query_param_auto_from_type (key), - GNUNET_MY_query_param_string (""), - GNUNET_MY_query_param_fixed_size (NULL, 0), - GNUNET_MY_query_param_uint32 (&iaccepting), - GNUNET_MY_query_param_end - }; - - result = - GNUNET_MY_exec_prepared (mysql_ctx, - stmt_handle, - params_stmt); - - if (1 != result && 0 != result) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Error executing prepared mysql statement for edge: Affected rows: %i, expected 0 or 1!\n", - result); - GNUNET_SCHEDULER_add_now (&do_abort, NULL); + struct GNUNET_MY_QueryParam params_stmt[] = { + GNUNET_MY_query_param_auto_from_type(key), + GNUNET_MY_query_param_string(""), + GNUNET_MY_query_param_fixed_size(NULL, 0), + GNUNET_MY_query_param_uint32(&iaccepting), + GNUNET_MY_query_param_end + }; + + result = + GNUNET_MY_exec_prepared(mysql_ctx, + stmt_handle, + params_stmt); + + if (1 != result && 0 != result) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Error executing prepared mysql statement for edge: Affected rows: %i, expected 0 or 1!\n", + result); + GNUNET_SCHEDULER_add_now(&do_abort, NULL); + } } - } } @@ -452,26 +451,26 @@ regex_iterator (void *cls, * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure. */ static int -announce_regex (const char *regex) +announce_regex(const char *regex) { struct REGEX_INTERNAL_Automaton *dfa; dfa = - REGEX_INTERNAL_construct_dfa (regex, - strlen (regex), - max_path_compression); + REGEX_INTERNAL_construct_dfa(regex, + strlen(regex), + max_path_compression); if (NULL == dfa) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create DFA for regex %s\n", - regex); - GNUNET_SCHEDULER_add_now (&do_abort, NULL); - return GNUNET_SYSERR; - } - REGEX_INTERNAL_iterate_all_edges (dfa, - ®ex_iterator, NULL); - REGEX_INTERNAL_automaton_destroy (dfa); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create DFA for regex %s\n", + regex); + GNUNET_SCHEDULER_add_now(&do_abort, NULL); + return GNUNET_SYSERR; + } + REGEX_INTERNAL_iterate_all_edges(dfa, + ®ex_iterator, NULL); + REGEX_INTERNAL_automaton_destroy(dfa); return GNUNET_OK; } @@ -486,7 +485,7 @@ announce_regex (const char *regex) * #GNUNET_SYSERR to abort iteration with error! */ static int -policy_filename_cb (void *cls, const char *filename) +policy_filename_cb(void *cls, const char *filename) { char *regex; char *data; @@ -494,70 +493,70 @@ policy_filename_cb (void *cls, const char *filename) uint64_t filesize; unsigned int offset; - GNUNET_assert (NULL != filename); + GNUNET_assert(NULL != filename); - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "Announcing regexes from file %s\n", - filename); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "Announcing regexes from file %s\n", + filename); - if (GNUNET_YES != GNUNET_DISK_file_test (filename)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Could not find policy file %s\n", - filename); - return GNUNET_OK; - } + if (GNUNET_YES != GNUNET_DISK_file_test(filename)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Could not find policy file %s\n", + filename); + return GNUNET_OK; + } if (GNUNET_OK != - GNUNET_DISK_file_size (filename, &filesize, - GNUNET_YES, GNUNET_YES)) + GNUNET_DISK_file_size(filename, &filesize, + GNUNET_YES, GNUNET_YES)) filesize = 0; if (0 == filesize) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Policy file %s is empty.\n", - filename); - return GNUNET_OK; - } - data = GNUNET_malloc (filesize); - if (filesize != GNUNET_DISK_fn_read (filename, data, filesize)) - { - GNUNET_free (data); - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Could not read policy file %s.\n", - filename); - return GNUNET_OK; - } - - update_meter (meter); + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Policy file %s is empty.\n", + filename); + return GNUNET_OK; + } + data = GNUNET_malloc(filesize); + if (filesize != GNUNET_DISK_fn_read(filename, data, filesize)) + { + GNUNET_free(data); + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Could not read policy file %s.\n", + filename); + return GNUNET_OK; + } + + update_meter(meter); buf = data; offset = 0; regex = NULL; while (offset < (filesize - 1)) - { - offset++; - if (((data[offset] == '\n')) && (buf != &data[offset])) { - data[offset] = '|'; - num_policies++; - buf = &data[offset + 1]; + offset++; + if (((data[offset] == '\n')) && (buf != &data[offset])) + { + data[offset] = '|'; + num_policies++; + buf = &data[offset + 1]; + } + else if ((data[offset] == '\n') || (data[offset] == '\0')) + buf = &data[offset + 1]; } - else if ((data[offset] == '\n') || (data[offset] == '\0')) - buf = &data[offset + 1]; - } data[offset] = '\0'; - GNUNET_asprintf (®ex, "%s(%s)", regex_prefix, data); - GNUNET_assert (NULL != regex); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Announcing regex: %s\n", regex); - - if (GNUNET_OK != announce_regex (regex)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not announce regex %s\n", - regex); - } - GNUNET_free (regex); - GNUNET_free (data); + GNUNET_asprintf(®ex, "%s(%s)", regex_prefix, data); + GNUNET_assert(NULL != regex); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Announcing regex: %s\n", regex); + + if (GNUNET_OK != announce_regex(regex)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not announce regex %s\n", + regex); + } + GNUNET_free(regex); + GNUNET_free(data); return GNUNET_OK; } @@ -568,7 +567,7 @@ policy_filename_cb (void *cls, const char *filename) * @param cls NULL */ static void -do_directory_scan (void *cls) +do_directory_scan(void *cls) { struct GNUNET_TIME_Absolute start_time; struct GNUNET_TIME_Relative duration; @@ -576,37 +575,37 @@ do_directory_scan (void *cls) /* Create an MySQL prepared statement for the inserts */ scan_task = NULL; - GNUNET_asprintf (&stmt, INSERT_EDGE_STMT, table_name); - stmt_handle = GNUNET_MYSQL_statement_prepare (mysql_ctx, stmt); - GNUNET_free (stmt); - - GNUNET_asprintf (&stmt, SELECT_KEY_STMT, table_name); - select_stmt_handle = GNUNET_MYSQL_statement_prepare (mysql_ctx, stmt); - GNUNET_free (stmt); - - GNUNET_assert (NULL != stmt_handle); - - meter = create_meter (num_policy_files, - "Announcing policy files\n", - GNUNET_YES); - start_time = GNUNET_TIME_absolute_get (); - GNUNET_DISK_directory_scan (policy_dir, - &policy_filename_cb, - stmt_handle); - duration = GNUNET_TIME_absolute_get_duration (start_time); - reset_meter (meter); - free_meter (meter); + GNUNET_asprintf(&stmt, INSERT_EDGE_STMT, table_name); + stmt_handle = GNUNET_MYSQL_statement_prepare(mysql_ctx, stmt); + GNUNET_free(stmt); + + GNUNET_asprintf(&stmt, SELECT_KEY_STMT, table_name); + select_stmt_handle = GNUNET_MYSQL_statement_prepare(mysql_ctx, stmt); + GNUNET_free(stmt); + + GNUNET_assert(NULL != stmt_handle); + + meter = create_meter(num_policy_files, + "Announcing policy files\n", + GNUNET_YES); + start_time = GNUNET_TIME_absolute_get(); + GNUNET_DISK_directory_scan(policy_dir, + &policy_filename_cb, + stmt_handle); + duration = GNUNET_TIME_absolute_get_duration(start_time); + reset_meter(meter); + free_meter(meter); meter = NULL; - printf ("Announced %u files containing %u policies in %s\n" - "Duplicate transitions: %llu\nMerged states: %llu\n", - num_policy_files, - num_policies, - GNUNET_STRINGS_relative_time_to_string (duration, GNUNET_NO), - num_merged_transitions, - num_merged_states); + printf("Announced %u files containing %u policies in %s\n" + "Duplicate transitions: %llu\nMerged states: %llu\n", + num_policy_files, + num_policies, + GNUNET_STRINGS_relative_time_to_string(duration, GNUNET_NO), + num_merged_transitions, + num_merged_states); result = GNUNET_OK; - GNUNET_SCHEDULER_shutdown (); + GNUNET_SCHEDULER_shutdown(); } @@ -619,65 +618,65 @@ do_directory_scan (void *cls) * @param config configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *config) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *config) { if (NULL == args[0]) - { - fprintf (stderr, - _("No policy directory specified on command line. Exiting.\n")); - result = GNUNET_SYSERR; - return; - } + { + fprintf(stderr, + _("No policy directory specified on command line. Exiting.\n")); + result = GNUNET_SYSERR; + return; + } if (GNUNET_YES != - GNUNET_DISK_directory_test (args[0], GNUNET_YES)) - { - fprintf (stderr, - _("Specified policies directory does not exist. Exiting.\n")); - result = GNUNET_SYSERR; - return; - } + GNUNET_DISK_directory_test(args[0], GNUNET_YES)) + { + fprintf(stderr, + _("Specified policies directory does not exist. Exiting.\n")); + result = GNUNET_SYSERR; + return; + } policy_dir = args[0]; - num_policy_files = GNUNET_DISK_directory_scan (policy_dir, - NULL, NULL); + num_policy_files = GNUNET_DISK_directory_scan(policy_dir, + NULL, NULL); meter = NULL; if (NULL == table_name) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "No table name specified, using default \"NFA\".\n"); - table_name = "NFA"; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "No table name specified, using default \"NFA\".\n"); + table_name = "NFA"; + } - mysql_ctx = GNUNET_MYSQL_context_create (config, "regex-mysql"); + mysql_ctx = GNUNET_MYSQL_context_create(config, "regex-mysql"); if (NULL == mysql_ctx) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Failed to create mysql context\n"); - result = GNUNET_SYSERR; - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Failed to create mysql context\n"); + result = GNUNET_SYSERR; + return; + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (config, - "regex-mysql", - "REGEX_PREFIX", - ®ex_prefix)) - { - GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, - "regex-mysql", - "REGEX_PREFIX"); - result = GNUNET_SYSERR; - return; - } + GNUNET_CONFIGURATION_get_value_string(config, + "regex-mysql", + "REGEX_PREFIX", + ®ex_prefix)) + { + GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, + "regex-mysql", + "REGEX_PREFIX"); + result = GNUNET_SYSERR; + return; + } result = GNUNET_OK; - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, - NULL); - scan_task = GNUNET_SCHEDULER_add_now (&do_directory_scan, NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, + NULL); + scan_task = GNUNET_SCHEDULER_add_now(&do_directory_scan, NULL); } @@ -689,34 +688,33 @@ run (void *cls, * @return 0 on success */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct GNUNET_GETOPT_CommandLineOption options[] = { - - GNUNET_GETOPT_option_string ('t', - "table", - "TABLENAME", - gettext_noop ("name of the table to write DFAs"), - &table_name), - - GNUNET_GETOPT_option_uint ('p', - "max-path-compression", - "MAX_PATH_COMPRESSION", - gettext_noop ("maximum path compression length"), - &max_path_compression), + GNUNET_GETOPT_option_string('t', + "table", + "TABLENAME", + gettext_noop("name of the table to write DFAs"), + &table_name), + + GNUNET_GETOPT_option_uint('p', + "max-path-compression", + "MAX_PATH_COMPRESSION", + gettext_noop("maximum path compression length"), + &max_path_compression), GNUNET_GETOPT_OPTION_END }; int ret; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; result = GNUNET_SYSERR; ret = - GNUNET_PROGRAM_run (argc, argv, - "gnunet-regex-simulationprofiler [OPTIONS] policy-dir", - _("Profiler for regex library"), options, &run, NULL); + GNUNET_PROGRAM_run(argc, argv, + "gnunet-regex-simulationprofiler [OPTIONS] policy-dir", + _("Profiler for regex library"), options, &run, NULL); if (GNUNET_OK != ret) return ret; if (GNUNET_OK != result) diff --git a/src/regex/gnunet-service-regex.c b/src/regex/gnunet-service-regex.c index a866288a3..90ea91780 100644 --- a/src/regex/gnunet-service-regex.c +++ b/src/regex/gnunet-service-regex.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/gnunet-service-regex.c @@ -33,9 +33,7 @@ /** * Information about one of our clients. */ -struct ClientEntry -{ - +struct ClientEntry { /** * Queue for transmissions to @e client. */ @@ -65,7 +63,6 @@ struct ClientEntry * Task for re-announcing. */ struct GNUNET_SCHEDULER_Task *refresh_task; - }; @@ -91,14 +88,14 @@ static struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key; * @param cls unused */ static void -cleanup_task (void *cls) +cleanup_task(void *cls) { - GNUNET_DHT_disconnect (dht); + GNUNET_DHT_disconnect(dht); dht = NULL; - GNUNET_STATISTICS_destroy (stats, - GNUNET_NO); + GNUNET_STATISTICS_destroy(stats, + GNUNET_NO); stats = NULL; - GNUNET_free (my_private_key); + GNUNET_free(my_private_key); my_private_key = NULL; } @@ -110,14 +107,14 @@ cleanup_task (void *cls) * announcement */ static void -reannounce (void *cls) +reannounce(void *cls) { struct ClientEntry *ce = cls; - REGEX_INTERNAL_reannounce (ce->ah); - ce->refresh_task = GNUNET_SCHEDULER_add_delayed (ce->frequency, - &reannounce, - ce); + REGEX_INTERNAL_reannounce(ce->ah); + ce->refresh_task = GNUNET_SCHEDULER_add_delayed(ce->frequency, + &reannounce, + ce); } @@ -129,18 +126,18 @@ reannounce (void *cls) * @return #GNUNET_OK if @am is well-formed */ static int -check_announce (void *cls, - const struct AnnounceMessage *am) +check_announce(void *cls, + const struct AnnounceMessage *am) { struct ClientEntry *ce = cls; - GNUNET_MQ_check_zero_termination (am); + GNUNET_MQ_check_zero_termination(am); if (NULL != ce->ah) - { - /* only one announcement per client allowed */ - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + /* only one announcement per client allowed */ + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -152,36 +149,36 @@ check_announce (void *cls, * @param am the actual message */ static void -handle_announce (void *cls, - const struct AnnounceMessage *am) +handle_announce(void *cls, + const struct AnnounceMessage *am) { struct ClientEntry *ce = cls; const char *regex; - regex = (const char *) &am[1]; - ce->frequency = GNUNET_TIME_relative_ntoh (am->refresh_delay); - ce->refresh_task = GNUNET_SCHEDULER_add_delayed (ce->frequency, - &reannounce, - ce); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting to announce regex `%s' every %s\n", - regex, - GNUNET_STRINGS_relative_time_to_string (ce->frequency, - GNUNET_NO)); - ce->ah = REGEX_INTERNAL_announce (dht, - my_private_key, - regex, - ntohs (am->compression), - stats); + regex = (const char *)&am[1]; + ce->frequency = GNUNET_TIME_relative_ntoh(am->refresh_delay); + ce->refresh_task = GNUNET_SCHEDULER_add_delayed(ce->frequency, + &reannounce, + ce); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting to announce regex `%s' every %s\n", + regex, + GNUNET_STRINGS_relative_time_to_string(ce->frequency, + GNUNET_NO)); + ce->ah = REGEX_INTERNAL_announce(dht, + my_private_key, + regex, + ntohs(am->compression), + stats); if (NULL == ce->ah) - { - GNUNET_break (0); - GNUNET_SCHEDULER_cancel (ce->refresh_task); - ce->refresh_task = NULL; - GNUNET_SERVICE_client_drop (ce->client); - return; - } - GNUNET_SERVICE_client_continue (ce->client); + { + GNUNET_break(0); + GNUNET_SCHEDULER_cancel(ce->refresh_task); + ce->refresh_task = NULL; + GNUNET_SERVICE_client_drop(ce->client); + return; + } + GNUNET_SERVICE_client_continue(ce->client); } @@ -196,12 +193,12 @@ handle_announce (void *cls, * @param put_path_length Length of the @a put_path. */ static void -handle_search_result (void *cls, - const struct GNUNET_PeerIdentity *id, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length) +handle_search_result(void *cls, + const struct GNUNET_PeerIdentity *id, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length) { struct ClientEntry *ce = cls; struct GNUNET_MQ_Envelope *env; @@ -209,30 +206,30 @@ handle_search_result (void *cls, struct GNUNET_PeerIdentity *gp; uint16_t size; - if ( (get_path_length >= 65536) || - (put_path_length >= 65536) || - ( (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity)) - + sizeof (struct ResultMessage) >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_break (0); - return; - } - size = (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity); - env = GNUNET_MQ_msg_extra (result, - size, - GNUNET_MESSAGE_TYPE_REGEX_RESULT); - result->get_path_length = htons ((uint16_t) get_path_length); - result->put_path_length = htons ((uint16_t) put_path_length); + if ((get_path_length >= 65536) || + (put_path_length >= 65536) || + ((get_path_length + put_path_length) * sizeof(struct GNUNET_PeerIdentity)) + + sizeof(struct ResultMessage) >= GNUNET_MAX_MESSAGE_SIZE) + { + GNUNET_break(0); + return; + } + size = (get_path_length + put_path_length) * sizeof(struct GNUNET_PeerIdentity); + env = GNUNET_MQ_msg_extra(result, + size, + GNUNET_MESSAGE_TYPE_REGEX_RESULT); + result->get_path_length = htons((uint16_t)get_path_length); + result->put_path_length = htons((uint16_t)put_path_length); result->id = *id; gp = &result->id; - GNUNET_memcpy (&gp[1], - get_path, - get_path_length * sizeof (struct GNUNET_PeerIdentity)); - GNUNET_memcpy (&gp[1 + get_path_length], - put_path, - put_path_length * sizeof (struct GNUNET_PeerIdentity)); - GNUNET_MQ_send (ce->mq, - env); + GNUNET_memcpy(&gp[1], + get_path, + get_path_length * sizeof(struct GNUNET_PeerIdentity)); + GNUNET_memcpy(&gp[1 + get_path_length], + put_path, + put_path_length * sizeof(struct GNUNET_PeerIdentity)); + GNUNET_MQ_send(ce->mq, + env); } @@ -243,26 +240,26 @@ handle_search_result (void *cls, * @param message the actual message */ static int -check_search (void *cls, - const struct RegexSearchMessage *sm) +check_search(void *cls, + const struct RegexSearchMessage *sm) { struct ClientEntry *ce = cls; const char *string; uint16_t size; - size = ntohs (sm->header.size) - sizeof (*sm); - string = (const char *) &sm[1]; + size = ntohs(sm->header.size) - sizeof(*sm); + string = (const char *)&sm[1]; if ('\0' != string[size - 1]) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + GNUNET_break(0); + return GNUNET_SYSERR; + } if (NULL != ce->sh) - { - /* only one search allowed per client */ - GNUNET_break (0); - return GNUNET_SYSERR; - } + { + /* only one search allowed per client */ + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -274,28 +271,28 @@ check_search (void *cls, * @param message the actual message */ static void -handle_search (void *cls, - const struct RegexSearchMessage *sm) +handle_search(void *cls, + const struct RegexSearchMessage *sm) { struct ClientEntry *ce = cls; const char *string; - string = (const char *) &sm[1]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Starting to search for `%s'\n", - string); - ce->sh = REGEX_INTERNAL_search (dht, - string, - &handle_search_result, - ce, - stats); + string = (const char *)&sm[1]; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Starting to search for `%s'\n", + string); + ce->sh = REGEX_INTERNAL_search(dht, + string, + &handle_search_result, + ce, + stats); if (NULL == ce->sh) - { - GNUNET_break (0); - GNUNET_SERVICE_client_drop (ce->client); - return; - } - GNUNET_SERVICE_client_continue (ce->client); + { + GNUNET_break(0); + GNUNET_SERVICE_client_drop(ce->client); + return; + } + GNUNET_SERVICE_client_continue(ce->client); } @@ -307,27 +304,27 @@ handle_search (void *cls, * @param service the initialized service */ static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_SERVICE_Handle *service) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_SERVICE_Handle *service) { - my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg); + my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration(cfg); if (NULL == my_private_key) - { - GNUNET_SCHEDULER_shutdown (); - return; - } - dht = GNUNET_DHT_connect (cfg, 1024); + { + GNUNET_SCHEDULER_shutdown(); + return; + } + dht = GNUNET_DHT_connect(cfg, 1024); if (NULL == dht) - { - GNUNET_free (my_private_key); - my_private_key = NULL; - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_SCHEDULER_add_shutdown (&cleanup_task, - NULL); - stats = GNUNET_STATISTICS_create ("regex", cfg); + { + GNUNET_free(my_private_key); + my_private_key = NULL; + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_SCHEDULER_add_shutdown(&cleanup_task, + NULL); + stats = GNUNET_STATISTICS_create("regex", cfg); } @@ -340,13 +337,13 @@ run (void *cls, * @return @a c */ static void * -client_connect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - struct GNUNET_MQ_Handle *mq) +client_connect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + struct GNUNET_MQ_Handle *mq) { struct ClientEntry *ce; - ce = GNUNET_new (struct ClientEntry); + ce = GNUNET_new(struct ClientEntry); ce->client = c; ce->mq = mq; return ce; @@ -361,28 +358,28 @@ client_connect_cb (void *cls, * @param internal_cls should be equal to @a c */ static void -client_disconnect_cb (void *cls, - struct GNUNET_SERVICE_Client *c, - void *internal_cls) +client_disconnect_cb(void *cls, + struct GNUNET_SERVICE_Client *c, + void *internal_cls) { struct ClientEntry *ce = internal_cls; if (NULL != ce->refresh_task) - { - GNUNET_SCHEDULER_cancel (ce->refresh_task); - ce->refresh_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(ce->refresh_task); + ce->refresh_task = NULL; + } if (NULL != ce->ah) - { - REGEX_INTERNAL_announce_cancel (ce->ah); - ce->ah = NULL; - } + { + REGEX_INTERNAL_announce_cancel(ce->ah); + ce->ah = NULL; + } if (NULL != ce->sh) - { - REGEX_INTERNAL_search_cancel (ce->sh); - ce->sh = NULL; - } - GNUNET_free (ce); + { + REGEX_INTERNAL_search_cancel(ce->sh); + ce->sh = NULL; + } + GNUNET_free(ce); } @@ -390,21 +387,21 @@ client_disconnect_cb (void *cls, * Define "main" method using service macro. */ GNUNET_SERVICE_MAIN -("regex", - GNUNET_SERVICE_OPTION_NONE, - &run, - &client_connect_cb, - &client_disconnect_cb, - NULL, - GNUNET_MQ_hd_var_size (announce, + ("regex", + GNUNET_SERVICE_OPTION_NONE, + &run, + &client_connect_cb, + &client_disconnect_cb, + NULL, + GNUNET_MQ_hd_var_size(announce, GNUNET_MESSAGE_TYPE_REGEX_ANNOUNCE, struct AnnounceMessage, NULL), - GNUNET_MQ_hd_var_size (search, + GNUNET_MQ_hd_var_size(search, GNUNET_MESSAGE_TYPE_REGEX_SEARCH, struct RegexSearchMessage, NULL), - GNUNET_MQ_handler_end ()); + GNUNET_MQ_handler_end()); /* end of gnunet-service-regex.c */ diff --git a/src/regex/perf-regex.c b/src/regex/perf-regex.c index ea331eed0..25960dc9f 100644 --- a/src/regex/perf-regex.c +++ b/src/regex/perf-regex.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/regex/perf-regex.c @@ -42,23 +42,23 @@ * @param edges edges leaving current state. */ static void -print_edge (void *cls, - const struct GNUNET_HashCode *key, - const char *proof, - int accepting, - unsigned int num_edges, - const struct REGEX_BLOCK_Edge *edges) +print_edge(void *cls, + const struct GNUNET_HashCode *key, + const char *proof, + int accepting, + unsigned int num_edges, + const struct REGEX_BLOCK_Edge *edges) { unsigned int i; - printf ("%s: %s, proof: `%s'\n", - GNUNET_h2s (key), - accepting ? "ACCEPTING" : "", - proof); + printf("%s: %s, proof: `%s'\n", + GNUNET_h2s(key), + accepting ? "ACCEPTING" : "", + proof); for (i = 0; i < num_edges; i++) - printf (" `%s': %s\n", - edges[i].label, - GNUNET_h2s (&edges[i].destination)); + printf(" `%s': %s\n", + edges[i].label, + GNUNET_h2s(&edges[i].destination)); } @@ -73,7 +73,7 @@ print_edge (void *cls, * @return 0 ok, 1 on error */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { struct REGEX_INTERNAL_Automaton* dfa; char **regexes; @@ -83,45 +83,45 @@ main (int argc, char *const *argv) unsigned int alphabet_size; long size; - GNUNET_log_setup ("perf-regex", "DEBUG", NULL); + GNUNET_log_setup("perf-regex", "DEBUG", NULL); if (4 != argc) - { - fprintf (stderr, - "Usage: %s REGEX_FILE ALPHABET_SIZE COMPRESSION\n", - argv[0]); - return 1; - } - regexes = REGEX_TEST_read_from_file (argv[1]); + { + fprintf(stderr, + "Usage: %s REGEX_FILE ALPHABET_SIZE COMPRESSION\n", + argv[0]); + return 1; + } + regexes = REGEX_TEST_read_from_file(argv[1]); if (NULL == regexes) - { - fprintf (stderr, - "Failed to read regexes from `%s'\n", - argv[1]); - return 2; - } - alphabet_size = atoi (argv[2]); - compression = atoi (argv[3]); - printf ("********* PERF-REGEX *********'\n"); - printf ("Using:\n file '%s'\n Alphabet size %u\n compression %d\n", - argv[1], alphabet_size, compression); + { + fprintf(stderr, + "Failed to read regexes from `%s'\n", + argv[1]); + return 2; + } + alphabet_size = atoi(argv[2]); + compression = atoi(argv[3]); + printf("********* PERF-REGEX *********'\n"); + printf("Using:\n file '%s'\n Alphabet size %u\n compression %d\n", + argv[1], alphabet_size, compression); fflush(stdout); - buffer = REGEX_TEST_combine (regexes, alphabet_size); - GNUNET_asprintf (®ex, "GNUNET_REGEX_PROFILER_(%s)(0|1)*", buffer); - size = strlen (regex); + buffer = REGEX_TEST_combine(regexes, alphabet_size); + GNUNET_asprintf(®ex, "GNUNET_REGEX_PROFILER_(%s)(0|1)*", buffer); + size = strlen(regex); - fprintf (stderr, - "Combined regex (%ld bytes):\n%s\n", - size, - regex); - dfa = REGEX_INTERNAL_construct_dfa (regex, size, compression); - printf ("********* ALL EDGES *********'\n"); - REGEX_INTERNAL_iterate_all_edges (dfa, &print_edge, NULL); - printf ("\n\n********* REACHABLE EDGES *********'\n"); - REGEX_INTERNAL_iterate_reachable_edges (dfa, &print_edge, NULL); - REGEX_INTERNAL_automaton_destroy (dfa); - GNUNET_free (buffer); - REGEX_TEST_free_from_file (regexes); - GNUNET_free (regex); + fprintf(stderr, + "Combined regex (%ld bytes):\n%s\n", + size, + regex); + dfa = REGEX_INTERNAL_construct_dfa(regex, size, compression); + printf("********* ALL EDGES *********'\n"); + REGEX_INTERNAL_iterate_all_edges(dfa, &print_edge, NULL); + printf("\n\n********* REACHABLE EDGES *********'\n"); + REGEX_INTERNAL_iterate_reachable_edges(dfa, &print_edge, NULL); + REGEX_INTERNAL_automaton_destroy(dfa); + GNUNET_free(buffer); + REGEX_TEST_free_from_file(regexes); + GNUNET_free(regex); return 0; } diff --git a/src/regex/plugin_block_regex.c b/src/regex/plugin_block_regex.c index bc2d287c5..9467c02b9 100644 --- a/src/regex/plugin_block_regex.c +++ b/src/regex/plugin_block_regex.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/plugin_block_regex.c @@ -57,37 +57,37 @@ * by this @a type of block (this is not an error) */ static struct GNUNET_BLOCK_Group * -block_plugin_regex_create_group (void *cls, - enum GNUNET_BLOCK_Type type, - uint32_t nonce, - const void *raw_data, - size_t raw_data_size, - va_list va) +block_plugin_regex_create_group(void *cls, + enum GNUNET_BLOCK_Type type, + uint32_t nonce, + const void *raw_data, + size_t raw_data_size, + va_list va) { unsigned int bf_size; const char *guard; - guard = va_arg (va, const char *); - if (0 == strcmp (guard, - "seen-set-size")) - bf_size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size (va_arg (va, unsigned int), - BLOOMFILTER_K); - else if (0 == strcmp (guard, - "filter-size")) - bf_size = va_arg (va, unsigned int); + guard = va_arg(va, const char *); + if (0 == strcmp(guard, + "seen-set-size")) + bf_size = GNUNET_BLOCK_GROUP_compute_bloomfilter_size(va_arg(va, unsigned int), + BLOOMFILTER_K); + else if (0 == strcmp(guard, + "filter-size")) + bf_size = va_arg(va, unsigned int); else - { - GNUNET_break (0); - bf_size = REGEX_BF_SIZE; - } - GNUNET_break (NULL == va_arg (va, const char *)); - return GNUNET_BLOCK_GROUP_bf_create (cls, - bf_size, - BLOOMFILTER_K, - type, - nonce, - raw_data, - raw_data_size); + { + GNUNET_break(0); + bf_size = REGEX_BF_SIZE; + } + GNUNET_break(NULL == va_arg(va, const char *)); + return GNUNET_BLOCK_GROUP_bf_create(cls, + bf_size, + BLOOMFILTER_K, + type, + nonce, + raw_data, + raw_data_size); } @@ -111,72 +111,74 @@ block_plugin_regex_create_group (void *cls, * @return characterization of result */ static enum GNUNET_BLOCK_EvaluationResult -evaluate_block_regex (void *cls, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *bg, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode *query, - const void *xquery, - size_t xquery_size, - const void *reply_block, - size_t reply_block_size) +evaluate_block_regex(void *cls, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *bg, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode *query, + const void *xquery, + size_t xquery_size, + const void *reply_block, + size_t reply_block_size) { struct GNUNET_HashCode chash; if (NULL == reply_block) - { - if (0 != xquery_size) - { - const char *s; - - s = (const char *) xquery; - if ('\0' != s[xquery_size - 1]) /* must be valid 0-terminated string */ - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; - } - } - return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; - } + { + if (0 != xquery_size) + { + const char *s; + + s = (const char *)xquery; + if ('\0' != s[xquery_size - 1]) /* must be valid 0-terminated string */ + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; + } + } + return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; + } if (0 != xquery_size) - { - const char *s; - - s = (const char *) xquery; - if ('\0' != s[xquery_size - 1]) /* must be valid 0-terminated string */ { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; + const char *s; + + s = (const char *)xquery; + if ('\0' != s[xquery_size - 1]) /* must be valid 0-terminated string */ + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; + } } - } else if (NULL != query) - { - /* xquery is required for regex GETs, at least an empty string */ - GNUNET_break_op (0); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "type %d, query %p, xquery %p\n", - type, query, xquery); - return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; - } - switch (REGEX_BLOCK_check (reply_block, - reply_block_size, - query, - xquery)) - { + { + /* xquery is required for regex GETs, at least an empty string */ + GNUNET_break_op(0); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "type %d, query %p, xquery %p\n", + type, query, xquery); + return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; + } + switch (REGEX_BLOCK_check(reply_block, + reply_block_size, + query, + xquery)) + { case GNUNET_SYSERR: GNUNET_break_op(0); return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + case GNUNET_NO: /* xquery missmatch, can happen */ return GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT; + default: break; - } - GNUNET_CRYPTO_hash (reply_block, - reply_block_size, - &chash); + } + GNUNET_CRYPTO_hash(reply_block, + reply_block_size, + &chash); if (GNUNET_YES == - GNUNET_BLOCK_GROUP_bf_test_and_set (bg, - &chash)) + GNUNET_BLOCK_GROUP_bf_test_and_set(bg, + &chash)) return GNUNET_BLOCK_EVALUATION_OK_DUPLICATE; return GNUNET_BLOCK_EVALUATION_OK_MORE; } @@ -202,60 +204,60 @@ evaluate_block_regex (void *cls, * @return characterization of result */ static enum GNUNET_BLOCK_EvaluationResult -evaluate_block_regex_accept (void *cls, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *bg, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode *query, - const void *xquery, - size_t xquery_size, const void *reply_block, - size_t reply_block_size) +evaluate_block_regex_accept(void *cls, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *bg, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode *query, + const void *xquery, + size_t xquery_size, const void *reply_block, + size_t reply_block_size) { const struct RegexAcceptBlock *rba; struct GNUNET_HashCode chash; if (0 != xquery_size) - { - GNUNET_break_op (0); - return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; - } + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_REQUEST_INVALID; + } if (NULL == reply_block) return GNUNET_BLOCK_EVALUATION_REQUEST_VALID; - if (sizeof (struct RegexAcceptBlock) != reply_block_size) - { - GNUNET_break_op(0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; - } + if (sizeof(struct RegexAcceptBlock) != reply_block_size) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } rba = reply_block; - if (ntohl (rba->purpose.size) != - sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) + - sizeof (struct GNUNET_TIME_AbsoluteNBO) + - sizeof (struct GNUNET_HashCode)) - { - GNUNET_break_op(0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; - } - if (0 == GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (rba->expiration_time)).rel_value_us) - { - /* technically invalid, but can happen without an error, so - we're nice by reporting it as a 'duplicate' */ - return GNUNET_BLOCK_EVALUATION_OK_DUPLICATE; - } + if (ntohl(rba->purpose.size) != + sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose) + + sizeof(struct GNUNET_TIME_AbsoluteNBO) + + sizeof(struct GNUNET_HashCode)) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } + if (0 == GNUNET_TIME_absolute_get_remaining(GNUNET_TIME_absolute_ntoh(rba->expiration_time)).rel_value_us) + { + /* technically invalid, but can happen without an error, so + we're nice by reporting it as a 'duplicate' */ + return GNUNET_BLOCK_EVALUATION_OK_DUPLICATE; + } if (GNUNET_OK != - GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_REGEX_ACCEPT, - &rba->purpose, - &rba->signature, - &rba->peer.public_key)) - { - GNUNET_break_op(0); - return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; - } - GNUNET_CRYPTO_hash (reply_block, - reply_block_size, - &chash); + GNUNET_CRYPTO_eddsa_verify(GNUNET_SIGNATURE_PURPOSE_REGEX_ACCEPT, + &rba->purpose, + &rba->signature, + &rba->peer.public_key)) + { + GNUNET_break_op(0); + return GNUNET_BLOCK_EVALUATION_RESULT_INVALID; + } + GNUNET_CRYPTO_hash(reply_block, + reply_block_size, + &chash); if (GNUNET_YES == - GNUNET_BLOCK_GROUP_bf_test_and_set (bg, - &chash)) + GNUNET_BLOCK_GROUP_bf_test_and_set(bg, + &chash)) return GNUNET_BLOCK_EVALUATION_OK_DUPLICATE; return GNUNET_BLOCK_EVALUATION_OK_MORE; } @@ -281,43 +283,44 @@ evaluate_block_regex_accept (void *cls, * @return characterization of result */ static enum GNUNET_BLOCK_EvaluationResult -block_plugin_regex_evaluate (void *cls, - struct GNUNET_BLOCK_Context *ctx, - enum GNUNET_BLOCK_Type type, - struct GNUNET_BLOCK_Group *bg, - enum GNUNET_BLOCK_EvaluationOptions eo, - const struct GNUNET_HashCode *query, - const void *xquery, - size_t xquery_size, - const void *reply_block, - size_t reply_block_size) +block_plugin_regex_evaluate(void *cls, + struct GNUNET_BLOCK_Context *ctx, + enum GNUNET_BLOCK_Type type, + struct GNUNET_BLOCK_Group *bg, + enum GNUNET_BLOCK_EvaluationOptions eo, + const struct GNUNET_HashCode *query, + const void *xquery, + size_t xquery_size, + const void *reply_block, + size_t reply_block_size) { enum GNUNET_BLOCK_EvaluationResult result; switch (type) - { + { case GNUNET_BLOCK_TYPE_REGEX: - result = evaluate_block_regex (cls, - type, - bg, - eo, - query, - xquery, xquery_size, - reply_block, reply_block_size); + result = evaluate_block_regex(cls, + type, + bg, + eo, + query, + xquery, xquery_size, + reply_block, reply_block_size); break; + case GNUNET_BLOCK_TYPE_REGEX_ACCEPT: - result = evaluate_block_regex_accept (cls, - type, - bg, - eo, - query, - xquery, xquery_size, - reply_block, reply_block_size); + result = evaluate_block_regex_accept(cls, + type, + bg, + eo, + query, + xquery, xquery_size, + reply_block, reply_block_size); break; default: result = GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED; - } + } return result; } @@ -334,35 +337,37 @@ block_plugin_regex_evaluate (void *cls, * (or if extracting a key from a block of this type does not work) */ static int -block_plugin_regex_get_key (void *cls, - enum GNUNET_BLOCK_Type type, - const void *block, - size_t block_size, - struct GNUNET_HashCode *key) +block_plugin_regex_get_key(void *cls, + enum GNUNET_BLOCK_Type type, + const void *block, + size_t block_size, + struct GNUNET_HashCode *key) { switch (type) - { + { case GNUNET_BLOCK_TYPE_REGEX: if (GNUNET_OK != - REGEX_BLOCK_get_key (block, block_size, - key)) - { - GNUNET_break_op (0); - return GNUNET_NO; - } + REGEX_BLOCK_get_key(block, block_size, + key)) + { + GNUNET_break_op(0); + return GNUNET_NO; + } return GNUNET_OK; + case GNUNET_BLOCK_TYPE_REGEX_ACCEPT: - if (sizeof (struct RegexAcceptBlock) != block_size) - { - GNUNET_break_op (0); - return GNUNET_NO; - } - *key = ((struct RegexAcceptBlock *) block)->key; + if (sizeof(struct RegexAcceptBlock) != block_size) + { + GNUNET_break_op(0); + return GNUNET_NO; + } + *key = ((struct RegexAcceptBlock *)block)->key; return GNUNET_OK; + default: - GNUNET_break (0); + GNUNET_break(0); return GNUNET_SYSERR; - } + } } @@ -370,7 +375,7 @@ block_plugin_regex_get_key (void *cls, * Entry point for the plugin. */ void * -libgnunet_plugin_block_regex_init (void *cls) +libgnunet_plugin_block_regex_init(void *cls) { static enum GNUNET_BLOCK_Type types[] = { @@ -380,7 +385,7 @@ libgnunet_plugin_block_regex_init (void *cls) }; struct GNUNET_BLOCK_PluginFunctions *api; - api = GNUNET_new (struct GNUNET_BLOCK_PluginFunctions); + api = GNUNET_new(struct GNUNET_BLOCK_PluginFunctions); api->evaluate = &block_plugin_regex_evaluate; api->get_key = &block_plugin_regex_get_key; api->create_group = &block_plugin_regex_create_group; @@ -393,11 +398,11 @@ libgnunet_plugin_block_regex_init (void *cls) * Exit point from the plugin. */ void * -libgnunet_plugin_block_regex_done (void *cls) +libgnunet_plugin_block_regex_done(void *cls) { struct GNUNET_BLOCK_PluginFunctions *api = cls; - GNUNET_free (api); + GNUNET_free(api); return NULL; } diff --git a/src/regex/regex_api_announce.c b/src/regex/regex_api_announce.c index e1af0b7a9..3b5801994 100644 --- a/src/regex/regex_api_announce.c +++ b/src/regex/regex_api_announce.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/regex_api_announce.c * @brief access regex service to advertise capabilities via regex @@ -29,13 +29,12 @@ #include "gnunet_regex_service.h" #include "regex_ipc.h" -#define LOG(kind,...) GNUNET_log_from (kind, "regex-api",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "regex-api", __VA_ARGS__) /** * Handle to store cached data about a regex announce. */ -struct GNUNET_REGEX_Announcement -{ +struct GNUNET_REGEX_Announcement { /** * Connection to the regex service. */ @@ -70,7 +69,7 @@ struct GNUNET_REGEX_Announcement * @param a REGEX to announce. */ static void -announce_reconnect (struct GNUNET_REGEX_Announcement *a); +announce_reconnect(struct GNUNET_REGEX_Announcement *a); /** @@ -81,14 +80,14 @@ announce_reconnect (struct GNUNET_REGEX_Announcement *a); * @param error error code */ static void -announce_mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +announce_mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_REGEX_Announcement *a = cls; - GNUNET_MQ_destroy (a->mq); + GNUNET_MQ_destroy(a->mq); a->mq = NULL; - announce_reconnect (a); + announce_reconnect(a); } @@ -98,31 +97,31 @@ announce_mq_error_handler (void *cls, * @param a REGEX to announce. */ static void -announce_reconnect (struct GNUNET_REGEX_Announcement *a) +announce_reconnect(struct GNUNET_REGEX_Announcement *a) { struct GNUNET_MQ_Envelope *env; struct AnnounceMessage *am; size_t slen; - a->mq = GNUNET_CLIENT_connect (a->cfg, - "regex", - NULL, - &announce_mq_error_handler, - a); + a->mq = GNUNET_CLIENT_connect(a->cfg, + "regex", + NULL, + &announce_mq_error_handler, + a); if (NULL == a->mq) return; - slen = strlen (a->regex) + 1; - env = GNUNET_MQ_msg_extra (am, - slen, - GNUNET_MESSAGE_TYPE_REGEX_ANNOUNCE); - am->compression = htons (a->compression); - am->reserved = htons (0); - am->refresh_delay = GNUNET_TIME_relative_hton (a->refresh_delay); - GNUNET_memcpy (&am[1], - a->regex, - slen); - GNUNET_MQ_send (a->mq, - env); + slen = strlen(a->regex) + 1; + env = GNUNET_MQ_msg_extra(am, + slen, + GNUNET_MESSAGE_TYPE_REGEX_ANNOUNCE); + am->compression = htons(a->compression); + am->reserved = htons(0); + am->refresh_delay = GNUNET_TIME_relative_hton(a->refresh_delay); + GNUNET_memcpy(&am[1], + a->regex, + slen); + GNUNET_MQ_send(a->mq, + env); } @@ -137,35 +136,35 @@ announce_reconnect (struct GNUNET_REGEX_Announcement *a) * Must be freed by calling #GNUNET_REGEX_announce_cancel(). */ struct GNUNET_REGEX_Announcement * -GNUNET_REGEX_announce (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *regex, - struct GNUNET_TIME_Relative refresh_delay, - uint16_t compression) +GNUNET_REGEX_announce(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *regex, + struct GNUNET_TIME_Relative refresh_delay, + uint16_t compression) { struct GNUNET_REGEX_Announcement *a; size_t slen; - slen = strlen (regex) + 1; - if (slen + sizeof (struct AnnounceMessage) >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Regex `%s' is too long!\n"), - regex); - GNUNET_break (0); - return NULL; - } - a = GNUNET_new (struct GNUNET_REGEX_Announcement); + slen = strlen(regex) + 1; + if (slen + sizeof(struct AnnounceMessage) >= GNUNET_MAX_MESSAGE_SIZE) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Regex `%s' is too long!\n"), + regex); + GNUNET_break(0); + return NULL; + } + a = GNUNET_new(struct GNUNET_REGEX_Announcement); a->cfg = cfg; a->refresh_delay = refresh_delay; a->compression = compression; - a->regex = GNUNET_strdup (regex); - announce_reconnect (a); + a->regex = GNUNET_strdup(regex); + announce_reconnect(a); if (NULL == a->mq) - { - GNUNET_free (a->regex); - GNUNET_free (a); - return NULL; - } + { + GNUNET_free(a->regex); + GNUNET_free(a); + return NULL; + } return a; } @@ -176,11 +175,11 @@ GNUNET_REGEX_announce (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param a handle returned by a previous #GNUNET_REGEX_announce() call. */ void -GNUNET_REGEX_announce_cancel (struct GNUNET_REGEX_Announcement *a) +GNUNET_REGEX_announce_cancel(struct GNUNET_REGEX_Announcement *a) { - GNUNET_MQ_destroy (a->mq); - GNUNET_free (a->regex); - GNUNET_free (a); + GNUNET_MQ_destroy(a->mq); + GNUNET_free(a->regex); + GNUNET_free(a); } /* end of regex_api_announce.c */ diff --git a/src/regex/regex_api_search.c b/src/regex/regex_api_search.c index ebd1a69f3..6a6a49a81 100644 --- a/src/regex/regex_api_search.c +++ b/src/regex/regex_api_search.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/regex_api_search.c * @brief access regex service to discover @@ -30,14 +30,13 @@ #include "gnunet_regex_service.h" #include "regex_ipc.h" -#define LOG(kind,...) GNUNET_log_from (kind, "regex-api",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "regex-api", __VA_ARGS__) /** * Handle to store data about a regex search. */ -struct GNUNET_REGEX_Search -{ +struct GNUNET_REGEX_Search { /** * Connection to the regex service. */ @@ -71,7 +70,7 @@ struct GNUNET_REGEX_Search * @param s context for the search search for */ static void -search_reconnect (struct GNUNET_REGEX_Search *s); +search_reconnect(struct GNUNET_REGEX_Search *s); /** @@ -83,18 +82,18 @@ search_reconnect (struct GNUNET_REGEX_Search *s); * @return #GNUNET_SYSERR if @a rm is not well-formed. */ static int -check_search_response (void *cls, - const struct ResultMessage *result) +check_search_response(void *cls, + const struct ResultMessage *result) { - uint16_t size = ntohs (result->header.size) - sizeof (*result); - uint16_t gpl = ntohs (result->get_path_length); - uint16_t ppl = ntohs (result->put_path_length); - - if (size != (gpl + ppl) * sizeof (struct GNUNET_PeerIdentity)) - { - GNUNET_break (0); - return GNUNET_SYSERR; - } + uint16_t size = ntohs(result->header.size) - sizeof(*result); + uint16_t gpl = ntohs(result->get_path_length); + uint16_t ppl = ntohs(result->put_path_length); + + if (size != (gpl + ppl) * sizeof(struct GNUNET_PeerIdentity)) + { + GNUNET_break(0); + return GNUNET_SYSERR; + } return GNUNET_OK; } @@ -107,24 +106,24 @@ check_search_response (void *cls, * @param result the message */ static void -handle_search_response (void *cls, - const struct ResultMessage *result) +handle_search_response(void *cls, + const struct ResultMessage *result) { struct GNUNET_REGEX_Search *s = cls; - uint16_t gpl = ntohs (result->get_path_length); - uint16_t ppl = ntohs (result->put_path_length); + uint16_t gpl = ntohs(result->get_path_length); + uint16_t ppl = ntohs(result->put_path_length); const struct GNUNET_PeerIdentity *pid; pid = &result->id; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Got regex result %s\n", - GNUNET_i2s (pid)); - s->callback (s->callback_cls, - pid, - &pid[1], - gpl, - &pid[1 + gpl], - ppl); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Got regex result %s\n", + GNUNET_i2s(pid)); + s->callback(s->callback_cls, + pid, + &pid[1], + gpl, + &pid[1 + gpl], + ppl); } @@ -136,14 +135,14 @@ handle_search_response (void *cls, * @param error error code */ static void -mq_error_handler (void *cls, - enum GNUNET_MQ_Error error) +mq_error_handler(void *cls, + enum GNUNET_MQ_Error error) { struct GNUNET_REGEX_Search *s = cls; - GNUNET_MQ_destroy (s->mq); + GNUNET_MQ_destroy(s->mq); s->mq = NULL; - search_reconnect (s); + search_reconnect(s); } @@ -153,35 +152,35 @@ mq_error_handler (void *cls, * @param s context for the search search for */ static void -search_reconnect (struct GNUNET_REGEX_Search *s) +search_reconnect(struct GNUNET_REGEX_Search *s) { struct GNUNET_MQ_MessageHandler handlers[] = { - GNUNET_MQ_hd_var_size (search_response, - GNUNET_MESSAGE_TYPE_REGEX_RESULT, - struct ResultMessage, - s), - GNUNET_MQ_handler_end () + GNUNET_MQ_hd_var_size(search_response, + GNUNET_MESSAGE_TYPE_REGEX_RESULT, + struct ResultMessage, + s), + GNUNET_MQ_handler_end() }; - size_t slen = strlen (s->string) + 1; + size_t slen = strlen(s->string) + 1; struct GNUNET_MQ_Envelope *env; struct RegexSearchMessage *rsm; - GNUNET_assert (NULL == s->mq); - s->mq = GNUNET_CLIENT_connect (s->cfg, - "regex", - handlers, - &mq_error_handler, - s); + GNUNET_assert(NULL == s->mq); + s->mq = GNUNET_CLIENT_connect(s->cfg, + "regex", + handlers, + &mq_error_handler, + s); if (NULL == s->mq) return; - env = GNUNET_MQ_msg_extra (rsm, - slen, - GNUNET_MESSAGE_TYPE_REGEX_SEARCH); - GNUNET_memcpy (&rsm[1], - s->string, - slen); - GNUNET_MQ_send (s->mq, - env); + env = GNUNET_MQ_msg_extra(rsm, + slen, + GNUNET_MESSAGE_TYPE_REGEX_SEARCH); + GNUNET_memcpy(&rsm[1], + s->string, + slen); + GNUNET_MQ_send(s->mq, + env); } @@ -198,37 +197,37 @@ search_reconnect (struct GNUNET_REGEX_Search *s) * Must be freed by calling #GNUNET_REGEX_search_cancel(). */ struct GNUNET_REGEX_Search * -GNUNET_REGEX_search (const struct GNUNET_CONFIGURATION_Handle *cfg, - const char *string, - GNUNET_REGEX_Found callback, - void *callback_cls) +GNUNET_REGEX_search(const struct GNUNET_CONFIGURATION_Handle *cfg, + const char *string, + GNUNET_REGEX_Found callback, + void *callback_cls) { struct GNUNET_REGEX_Search *s; - size_t slen = strlen (string) + 1; - - if (slen + sizeof (struct RegexSearchMessage) >= GNUNET_MAX_MESSAGE_SIZE) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _("Search string `%s' is too long!\n"), - string); - GNUNET_break (0); - return NULL; - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Starting regex search for %s\n", - string); - s = GNUNET_new (struct GNUNET_REGEX_Search); + size_t slen = strlen(string) + 1; + + if (slen + sizeof(struct RegexSearchMessage) >= GNUNET_MAX_MESSAGE_SIZE) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Search string `%s' is too long!\n"), + string); + GNUNET_break(0); + return NULL; + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Starting regex search for %s\n", + string); + s = GNUNET_new(struct GNUNET_REGEX_Search); s->cfg = cfg; - s->string = GNUNET_strdup (string); + s->string = GNUNET_strdup(string); s->callback = callback; s->callback_cls = callback_cls; - search_reconnect (s); + search_reconnect(s); if (NULL == s->mq) - { - GNUNET_free (s->string); - GNUNET_free (s); - return NULL; - } + { + GNUNET_free(s->string); + GNUNET_free(s); + return NULL; + } return s; } @@ -239,11 +238,11 @@ GNUNET_REGEX_search (const struct GNUNET_CONFIGURATION_Handle *cfg, * @param s Handle returned by a previous #GNUNET_REGEX_search() call. */ void -GNUNET_REGEX_search_cancel (struct GNUNET_REGEX_Search *s) +GNUNET_REGEX_search_cancel(struct GNUNET_REGEX_Search *s) { - GNUNET_MQ_destroy (s->mq); - GNUNET_free (s->string); - GNUNET_free (s); + GNUNET_MQ_destroy(s->mq); + GNUNET_free(s->string); + GNUNET_free(s); } diff --git a/src/regex/regex_block_lib.c b/src/regex/regex_block_lib.c index 77efa6180..f0feb3628 100644 --- a/src/regex/regex_block_lib.c +++ b/src/regex/regex_block_lib.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Bartlomiej Polot * @file regex/regex_block_lib.c @@ -27,15 +27,14 @@ #include "regex_block_lib.h" #include "gnunet_constants.h" -#define LOG(kind,...) GNUNET_log_from (kind,"regex-bck",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "regex-bck", __VA_ARGS__) GNUNET_NETWORK_STRUCT_BEGIN /** * Information for each edge. */ -struct EdgeInfo -{ +struct EdgeInfo { /** * Index of the destination of this edge in the * unique destinations array. @@ -53,9 +52,7 @@ struct EdgeInfo /** * @brief Block to announce a regex state. */ -struct RegexBlock -{ - +struct RegexBlock { /** * Length of the proof regex string. */ @@ -85,7 +82,6 @@ struct RegexBlock /* followed by 'char tokens[num_edges][edge_info[k].token_length]'; essentially all of the tokens one after the other in the order of the edges; tokens are NOT 0-terminated */ - }; @@ -100,15 +96,15 @@ GNUNET_NETWORK_STRUCT_END * @return #GNUNET_YES if the block is accepting, #GNUNET_NO if not */ int -GNUNET_BLOCK_is_accepting (const struct RegexBlock *block, - size_t size) +GNUNET_BLOCK_is_accepting(const struct RegexBlock *block, + size_t size) { - if (size < sizeof (struct RegexBlock)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - return ntohs (block->is_accepting); + if (size < sizeof(struct RegexBlock)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + return ntohs(block->is_accepting); } @@ -121,28 +117,27 @@ GNUNET_BLOCK_is_accepting (const struct RegexBlock *block, * @return #GNUNET_OK if the proof is valid for the given key. */ int -REGEX_BLOCK_check_proof (const char *proof, - size_t proof_len, - const struct GNUNET_HashCode *key) +REGEX_BLOCK_check_proof(const char *proof, + size_t proof_len, + const struct GNUNET_HashCode *key) { struct GNUNET_HashCode key_check; - if ( (NULL == proof) || (NULL == key)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Proof check failed, was NULL.\n"); - return GNUNET_NO; - } - GNUNET_CRYPTO_hash (proof, proof_len, &key_check); + if ((NULL == proof) || (NULL == key)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Proof check failed, was NULL.\n"); + return GNUNET_NO; + } + GNUNET_CRYPTO_hash(proof, proof_len, &key_check); return (0 == - GNUNET_CRYPTO_hash_cmp (key, &key_check)) ? GNUNET_OK : GNUNET_NO; + GNUNET_CRYPTO_hash_cmp(key, &key_check)) ? GNUNET_OK : GNUNET_NO; } /** * Struct to keep track of the xquery while iterating all the edges in a block. */ -struct CheckEdgeContext -{ +struct CheckEdgeContext { /** * Xquery: string we are looking for. */ @@ -152,7 +147,6 @@ struct CheckEdgeContext * Has any edge matched the xquery so far? (GNUNET_OK / GNUNET_NO) */ int found; - }; @@ -167,24 +161,24 @@ struct CheckEdgeContext * @return #GNUNET_YES, to keep iterating */ static int -check_edge (void *cls, - const char *token, - size_t len, - const struct GNUNET_HashCode *key) +check_edge(void *cls, + const char *token, + size_t len, + const struct GNUNET_HashCode *key) { struct CheckEdgeContext *ctx = cls; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "edge %.*s [%u]: %s\n", - (int) len, - token, - (unsigned int) len, - GNUNET_h2s (key)); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "edge %.*s [%u]: %s\n", + (int)len, + token, + (unsigned int)len, + GNUNET_h2s(key)); if (NULL == ctx->xquery) return GNUNET_YES; - if (strlen (ctx->xquery) < len) + if (strlen(ctx->xquery) < len) return GNUNET_YES; /* too long */ - if (0 == strncmp (ctx->xquery, token, len)) + if (0 == strncmp(ctx->xquery, token, len)) ctx->found = GNUNET_OK; return GNUNET_YES; /* keep checking for malformed data! */ } @@ -203,48 +197,48 @@ check_edge (void *cls, * #GNUNET_SYSERR if the block is invalid. */ int -REGEX_BLOCK_check (const struct RegexBlock *block, - size_t size, - const struct GNUNET_HashCode *query, - const char *xquery) +REGEX_BLOCK_check(const struct RegexBlock *block, + size_t size, + const struct GNUNET_HashCode *query, + const char *xquery) { struct GNUNET_HashCode key; struct CheckEdgeContext ctx; int res; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Block check\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Block check\n"); if (GNUNET_OK != - REGEX_BLOCK_get_key (block, size, - &key)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } + REGEX_BLOCK_get_key(block, size, + &key)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } if (NULL != query && - 0 != GNUNET_memcmp (&key, - query)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - if ( (GNUNET_YES == ntohs (block->is_accepting)) && - ( (NULL == xquery) || ('\0' == xquery[0]) ) ) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - " out! Is accepting: %u, xquery %p\n", - ntohs(block->is_accepting), - xquery); - return GNUNET_OK; - } + 0 != GNUNET_memcmp(&key, + query)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + if ((GNUNET_YES == ntohs(block->is_accepting)) && + ((NULL == xquery) || ('\0' == xquery[0]))) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + " out! Is accepting: %u, xquery %p\n", + ntohs(block->is_accepting), + xquery); + return GNUNET_OK; + } ctx.xquery = xquery; ctx.found = GNUNET_NO; - res = REGEX_BLOCK_iterate (block, size, &check_edge, &ctx); + res = REGEX_BLOCK_iterate(block, size, &check_edge, &ctx); if (GNUNET_SYSERR == res) return GNUNET_SYSERR; if (NULL == xquery) return GNUNET_YES; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Result %d\n", ctx.found); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Result %d\n", ctx.found); return ctx.found; } @@ -258,9 +252,9 @@ REGEX_BLOCK_check (const struct RegexBlock *block, * @return #GNUNET_OK on success, #GNUNET_SYSERR if the block is malformed */ int -REGEX_BLOCK_get_key (const struct RegexBlock *block, - size_t block_len, - struct GNUNET_HashCode *key) +REGEX_BLOCK_get_key(const struct RegexBlock *block, + size_t block_len, + struct GNUNET_HashCode *key) { uint16_t len; const struct GNUNET_HashCode *destinations; @@ -269,23 +263,23 @@ REGEX_BLOCK_get_key (const struct RegexBlock *block, uint16_t num_edges; size_t total; - if (block_len < sizeof (struct RegexBlock)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - num_destinations = ntohs (block->num_destinations); - num_edges = ntohs (block->num_edges); - len = ntohs (block->proof_len); - destinations = (const struct GNUNET_HashCode *) &block[1]; - edges = (const struct EdgeInfo *) &destinations[num_destinations]; - total = sizeof (struct RegexBlock) + num_destinations * sizeof (struct GNUNET_HashCode) + num_edges * sizeof (struct EdgeInfo) + len; + if (block_len < sizeof(struct RegexBlock)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + num_destinations = ntohs(block->num_destinations); + num_edges = ntohs(block->num_edges); + len = ntohs(block->proof_len); + destinations = (const struct GNUNET_HashCode *)&block[1]; + edges = (const struct EdgeInfo *)&destinations[num_destinations]; + total = sizeof(struct RegexBlock) + num_destinations * sizeof(struct GNUNET_HashCode) + num_edges * sizeof(struct EdgeInfo) + len; if (block_len < total) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - GNUNET_CRYPTO_hash (&edges[num_edges], len, key); + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + GNUNET_CRYPTO_hash(&edges[num_edges], len, key); return GNUNET_OK; } @@ -306,10 +300,10 @@ REGEX_BLOCK_get_key (const struct RegexBlock *block, * be errors in further edges. */ int -REGEX_BLOCK_iterate (const struct RegexBlock *block, - size_t size, - REGEX_INTERNAL_EgdeIterator iterator, - void *iter_cls) +REGEX_BLOCK_iterate(const struct RegexBlock *block, + size_t size, + REGEX_INTERNAL_EgdeIterator iterator, + void *iter_cls) { uint16_t len; const struct GNUNET_HashCode *destinations; @@ -321,54 +315,54 @@ REGEX_BLOCK_iterate (const struct RegexBlock *block, unsigned int n; size_t off; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Block iterate\n"); - if (size < sizeof (struct RegexBlock)) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - num_destinations = ntohs (block->num_destinations); - num_edges = ntohs (block->num_edges); - len = ntohs (block->proof_len); - destinations = (const struct GNUNET_HashCode *) &block[1]; - edges = (const struct EdgeInfo *) &destinations[num_destinations]; - aux = (const char *) &edges[num_edges]; - total = sizeof (struct RegexBlock) + num_destinations * sizeof (struct GNUNET_HashCode) + num_edges * sizeof (struct EdgeInfo) + len; + LOG(GNUNET_ERROR_TYPE_DEBUG, "Block iterate\n"); + if (size < sizeof(struct RegexBlock)) + { + GNUNET_break_op(0); + return GNUNET_SYSERR; + } + num_destinations = ntohs(block->num_destinations); + num_edges = ntohs(block->num_edges); + len = ntohs(block->proof_len); + destinations = (const struct GNUNET_HashCode *)&block[1]; + edges = (const struct EdgeInfo *)&destinations[num_destinations]; + aux = (const char *)&edges[num_edges]; + total = sizeof(struct RegexBlock) + num_destinations * sizeof(struct GNUNET_HashCode) + num_edges * sizeof(struct EdgeInfo) + len; if (size < total) - { - GNUNET_break_op (0); - return GNUNET_SYSERR; - } - for (n=0;n UINT16_MAX) - { - GNUNET_break (0); - return NULL; - } - unique_destinations = 0; - total = sizeof (struct RegexBlock) + len; - for (i=0;i UINT16_MAX) { - GNUNET_break (0); + GNUNET_break(0); return NULL; } - total += slen; - for (j=0;j= 1024) + unique_destinations = 0; + total = sizeof(struct RegexBlock) + len; + for (i = 0; i < num_edges; i++) { - GNUNET_break (0); - return NULL; + slen = strlen(edges[i].label); + if (slen > UINT16_MAX) + { + GNUNET_break(0); + return NULL; + } + total += slen; + for (j = 0; j < unique_destinations; j++) + if (0 == memcmp(&destinations[j], + &edges[i].destination, + sizeof(struct GNUNET_HashCode))) + break; + if (j >= 1024) + { + GNUNET_break(0); + return NULL; + } + destination_indices[i] = j; + if (j == unique_destinations) + destinations[unique_destinations++] = edges[i].destination; } - destination_indices[i] = j; - if (j == unique_destinations) - destinations[unique_destinations++] = edges[i].destination; - } - total += num_edges * sizeof (struct EdgeInfo) + unique_destinations * sizeof (struct GNUNET_HashCode); + total += num_edges * sizeof(struct EdgeInfo) + unique_destinations * sizeof(struct GNUNET_HashCode); if (total >= GNUNET_CONSTANTS_MAX_BLOCK_SIZE) - { - GNUNET_break (0); - return NULL; - } - block = GNUNET_malloc (total); - block->proof_len = htons (len); - block->is_accepting = htons (accepting); - block->num_edges = htons (num_edges); - block->num_destinations = htons (unique_destinations); - dests = (struct GNUNET_HashCode *) &block[1]; - GNUNET_memcpy (dests, destinations, sizeof (struct GNUNET_HashCode) * unique_destinations); - edgeinfos = (struct EdgeInfo *) &dests[unique_destinations]; - aux = (char *) &edgeinfos[num_edges]; + { + GNUNET_break(0); + return NULL; + } + block = GNUNET_malloc(total); + block->proof_len = htons(len); + block->is_accepting = htons(accepting); + block->num_edges = htons(num_edges); + block->num_destinations = htons(unique_destinations); + dests = (struct GNUNET_HashCode *)&block[1]; + GNUNET_memcpy(dests, destinations, sizeof(struct GNUNET_HashCode) * unique_destinations); + edgeinfos = (struct EdgeInfo *)&dests[unique_destinations]; + aux = (char *)&edgeinfos[num_edges]; off = len; - GNUNET_memcpy (aux, proof, len); - for (i=0;i. SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @author Bartlomiej Polot @@ -31,7 +31,7 @@ extern "C" { #if 0 - /* keep Emacsens' auto-indent happy */ +/* keep Emacsens' auto-indent happy */ } #endif #endif @@ -49,8 +49,7 @@ struct RegexBlock; /** * Edge representation. */ -struct REGEX_BLOCK_Edge -{ +struct REGEX_BLOCK_Edge { /** * Label of the edge. FIXME: might want to not consume exactly * multiples of 8 bits, need length! @@ -73,9 +72,9 @@ struct REGEX_BLOCK_Edge * @return #GNUNET_OK if the proof is valid for the given key. */ int -REGEX_BLOCK_check_proof (const char *proof, - size_t proof_len, - const struct GNUNET_HashCode *key); +REGEX_BLOCK_check_proof(const char *proof, + size_t proof_len, + const struct GNUNET_HashCode *key); /** @@ -91,10 +90,10 @@ REGEX_BLOCK_check_proof (const char *proof, * #GNUNET_SYSERR if the block is invalid. */ int -REGEX_BLOCK_check (const struct RegexBlock *block, - size_t size, - const struct GNUNET_HashCode *query, - const char *xquery); +REGEX_BLOCK_check(const struct RegexBlock *block, + size_t size, + const struct GNUNET_HashCode *query, + const char *xquery); /* FIXME: might want to use 'struct REGEX_BLOCK_Edge' here instead of 3 arguments! */ @@ -131,10 +130,10 @@ typedef int * be errors in further edges. */ int -REGEX_BLOCK_iterate (const struct RegexBlock *block, - size_t size, - REGEX_INTERNAL_EgdeIterator iterator, - void *iter_cls); +REGEX_BLOCK_iterate(const struct RegexBlock *block, + size_t size, + REGEX_INTERNAL_EgdeIterator iterator, + void *iter_cls); /** @@ -146,9 +145,9 @@ REGEX_BLOCK_iterate (const struct RegexBlock *block, * @return #GNUNET_OK on success, #GNUNET_SYSERR if the block is malformed */ int -REGEX_BLOCK_get_key (const struct RegexBlock *block, - size_t block_len, - struct GNUNET_HashCode *key); +REGEX_BLOCK_get_key(const struct RegexBlock *block, + size_t block_len, + struct GNUNET_HashCode *key); /** @@ -159,8 +158,8 @@ REGEX_BLOCK_get_key (const struct RegexBlock *block, * @return #GNUNET_YES if the block is accepting, #GNUNET_NO if not */ int -GNUNET_BLOCK_is_accepting (const struct RegexBlock *block, - size_t block_len); +GNUNET_BLOCK_is_accepting(const struct RegexBlock *block, + size_t block_len); /** @@ -174,11 +173,11 @@ GNUNET_BLOCK_is_accepting (const struct RegexBlock *block, * @return the regex block, NULL on error */ struct RegexBlock * -REGEX_BLOCK_create (const char *proof, - unsigned int num_edges, - const struct REGEX_BLOCK_Edge *edges, - int accepting, - size_t *rsize); +REGEX_BLOCK_create(const char *proof, + unsigned int num_edges, + const struct REGEX_BLOCK_Edge *edges, + int accepting, + size_t *rsize); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/regex/regex_internal.c b/src/regex/regex_internal.c index 55d16129f..34f0d9c42 100644 --- a/src/regex/regex_internal.c +++ b/src/regex/regex_internal.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/regex/regex_internal.c * @brief library to create Deterministic Finite Automatons (DFAs) from regular @@ -39,8 +39,7 @@ /** * Set of states using MDLL API. */ -struct REGEX_INTERNAL_StateSet_MDLL -{ +struct REGEX_INTERNAL_StateSet_MDLL { /** * MDLL of states. */ @@ -65,11 +64,11 @@ struct REGEX_INTERNAL_StateSet_MDLL * @param state state to be appended */ static void -state_set_append (struct REGEX_INTERNAL_StateSet *set, - struct REGEX_INTERNAL_State *state) +state_set_append(struct REGEX_INTERNAL_StateSet *set, + struct REGEX_INTERNAL_State *state) { if (set->off == set->size) - GNUNET_array_grow (set->states, set->size, set->size * 2 + 4); + GNUNET_array_grow(set->states, set->size, set->size * 2 + 4); set->states[set->off++] = state; } @@ -83,14 +82,14 @@ state_set_append (struct REGEX_INTERNAL_StateSet *set, * @return 0 if the strings are the same or both NULL, 1 or -1 if not. */ static int -nullstrcmp (const char *str1, const char *str2) +nullstrcmp(const char *str1, const char *str2) { if ((NULL == str1) != (NULL == str2)) return -1; if ((NULL == str1) && (NULL == str2)) return 0; - return strcmp (str1, str2); + return strcmp(str1, str2); } @@ -104,40 +103,40 @@ nullstrcmp (const char *str1, const char *str2) * @param to_state state to where the transition should point to */ static void -state_add_transition (struct REGEX_INTERNAL_Context *ctx, - struct REGEX_INTERNAL_State *from_state, - const char *label, - struct REGEX_INTERNAL_State *to_state) +state_add_transition(struct REGEX_INTERNAL_Context *ctx, + struct REGEX_INTERNAL_State *from_state, + const char *label, + struct REGEX_INTERNAL_State *to_state) { struct REGEX_INTERNAL_Transition *t; struct REGEX_INTERNAL_Transition *oth; if (NULL == from_state) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not create Transition.\n"); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not create Transition.\n"); + return; + } /* Do not add duplicate state transitions */ for (t = from_state->transitions_head; NULL != t; t = t->next) - { - if (t->to_state == to_state && 0 == nullstrcmp (t->label, label) && - t->from_state == from_state) - return; - } + { + if (t->to_state == to_state && 0 == nullstrcmp(t->label, label) && + t->from_state == from_state) + return; + } /* sort transitions by label */ for (oth = from_state->transitions_head; NULL != oth; oth = oth->next) - { - if (0 < nullstrcmp (oth->label, label)) - break; - } + { + if (0 < nullstrcmp(oth->label, label)) + break; + } - t = GNUNET_new (struct REGEX_INTERNAL_Transition); + t = GNUNET_new(struct REGEX_INTERNAL_Transition); if (NULL != ctx) t->id = ctx->transition_id++; if (NULL != label) - t->label = GNUNET_strdup (label); + t->label = GNUNET_strdup(label); else t->label = NULL; t->to_state = to_state; @@ -145,10 +144,10 @@ state_add_transition (struct REGEX_INTERNAL_Context *ctx, /* Add outgoing transition to 'from_state' */ from_state->transition_count++; - GNUNET_CONTAINER_DLL_insert_before (from_state->transitions_head, - from_state->transitions_tail, - oth, - t); + GNUNET_CONTAINER_DLL_insert_before(from_state->transitions_head, + from_state->transitions_tail, + oth, + t); } @@ -159,8 +158,8 @@ state_add_transition (struct REGEX_INTERNAL_Context *ctx, * @param transition transition that should be removed from state 'state'. */ static void -state_remove_transition (struct REGEX_INTERNAL_State *state, - struct REGEX_INTERNAL_Transition *transition) +state_remove_transition(struct REGEX_INTERNAL_State *state, + struct REGEX_INTERNAL_Transition *transition) { if (NULL == state || NULL == transition) return; @@ -168,14 +167,14 @@ state_remove_transition (struct REGEX_INTERNAL_State *state, if (transition->from_state != state) return; - GNUNET_free_non_null (transition->label); + GNUNET_free_non_null(transition->label); state->transition_count--; - GNUNET_CONTAINER_DLL_remove (state->transitions_head, - state->transitions_tail, - transition); + GNUNET_CONTAINER_DLL_remove(state->transitions_head, + state->transitions_tail, + transition); - GNUNET_free (transition); + GNUNET_free(transition); } @@ -190,10 +189,10 @@ state_remove_transition (struct REGEX_INTERNAL_State *state, * less than, equal to, or greater than the second. */ static int -state_compare (const void *a, const void *b) +state_compare(const void *a, const void *b) { - struct REGEX_INTERNAL_State **s1 = (struct REGEX_INTERNAL_State **) a; - struct REGEX_INTERNAL_State **s2 = (struct REGEX_INTERNAL_State **) b; + struct REGEX_INTERNAL_State **s1 = (struct REGEX_INTERNAL_State **)a; + struct REGEX_INTERNAL_State **s2 = (struct REGEX_INTERNAL_State **)b; return (*s1)->id - (*s2)->id; } @@ -209,7 +208,7 @@ state_compare (const void *a, const void *b) * @return number of edges. */ static unsigned int -state_get_edges (struct REGEX_INTERNAL_State *s, struct REGEX_BLOCK_Edge *edges) +state_get_edges(struct REGEX_INTERNAL_State *s, struct REGEX_BLOCK_Edge *edges) { struct REGEX_INTERNAL_Transition *t; unsigned int count; @@ -220,14 +219,14 @@ state_get_edges (struct REGEX_INTERNAL_State *s, struct REGEX_BLOCK_Edge *edges) count = 0; for (t = s->transitions_head; NULL != t; t = t->next) - { - if (NULL != t->to_state) { - edges[count].label = t->label; - edges[count].destination = t->to_state->hash; - count++; + if (NULL != t->to_state) + { + edges[count].label = t->label; + edges[count].destination = t->to_state->hash; + count++; + } } - } return count; } @@ -241,8 +240,8 @@ state_get_edges (struct REGEX_INTERNAL_State *s, struct REGEX_BLOCK_Edge *edges) * @return 0 if the sets are equal, otherwise non-zero */ static int -state_set_compare (struct REGEX_INTERNAL_StateSet *sset1, - struct REGEX_INTERNAL_StateSet *sset2) +state_set_compare(struct REGEX_INTERNAL_StateSet *sset1, + struct REGEX_INTERNAL_StateSet *sset2) { int result; unsigned int i; @@ -256,7 +255,7 @@ state_set_compare (struct REGEX_INTERNAL_StateSet *sset1, if (result > 0) return 1; for (i = 0; i < sset1->off; i++) - if (0 != (result = state_compare (&sset1->states[i], &sset2->states[i]))) + if (0 != (result = state_compare(&sset1->states[i], &sset2->states[i]))) break; return result; } @@ -268,9 +267,9 @@ state_set_compare (struct REGEX_INTERNAL_StateSet *sset1, * @param set set to be cleared */ static void -state_set_clear (struct REGEX_INTERNAL_StateSet *set) +state_set_clear(struct REGEX_INTERNAL_StateSet *set) { - GNUNET_array_grow (set->states, set->size, 0); + GNUNET_array_grow(set->states, set->size, 0); set->off = 0; } @@ -282,7 +281,7 @@ state_set_clear (struct REGEX_INTERNAL_StateSet *set) * @param a automaton to be cleared */ static void -automaton_fragment_clear (struct REGEX_INTERNAL_Automaton *a) +automaton_fragment_clear(struct REGEX_INTERNAL_Automaton *a) { if (NULL == a) return; @@ -292,7 +291,7 @@ automaton_fragment_clear (struct REGEX_INTERNAL_Automaton *a) a->states_head = NULL; a->states_tail = NULL; a->state_count = 0; - GNUNET_free (a); + GNUNET_free(a); } @@ -302,7 +301,7 @@ automaton_fragment_clear (struct REGEX_INTERNAL_Automaton *a) * @param s state that should be destroyed */ static void -automaton_destroy_state (struct REGEX_INTERNAL_State *s) +automaton_destroy_state(struct REGEX_INTERNAL_State *s) { struct REGEX_INTERNAL_Transition *t; struct REGEX_INTERNAL_Transition *next_t; @@ -310,16 +309,16 @@ automaton_destroy_state (struct REGEX_INTERNAL_State *s) if (NULL == s) return; - GNUNET_free_non_null (s->name); - GNUNET_free_non_null (s->proof); - state_set_clear (&s->nfa_set); + GNUNET_free_non_null(s->name); + GNUNET_free_non_null(s->proof); + state_set_clear(&s->nfa_set); for (t = s->transitions_head; NULL != t; t = next_t) - { - next_t = t->next; - state_remove_transition (s, t); - } + { + next_t = t->next; + state_remove_transition(s, t); + } - GNUNET_free (s); + GNUNET_free(s); } @@ -332,8 +331,8 @@ automaton_destroy_state (struct REGEX_INTERNAL_State *s) * @param s state to remove */ static void -automaton_remove_state (struct REGEX_INTERNAL_Automaton *a, - struct REGEX_INTERNAL_State *s) +automaton_remove_state(struct REGEX_INTERNAL_Automaton *a, + struct REGEX_INTERNAL_State *s) { struct REGEX_INTERNAL_State *s_check; struct REGEX_INTERNAL_Transition *t_check; @@ -344,21 +343,21 @@ automaton_remove_state (struct REGEX_INTERNAL_Automaton *a, /* remove all transitions leading to this state */ for (s_check = a->states_head; NULL != s_check; s_check = s_check->next) - { - for (t_check = s_check->transitions_head; NULL != t_check; - t_check = t_check_next) { - t_check_next = t_check->next; - if (t_check->to_state == s) - state_remove_transition (s_check, t_check); + for (t_check = s_check->transitions_head; NULL != t_check; + t_check = t_check_next) + { + t_check_next = t_check->next; + if (t_check->to_state == s) + state_remove_transition(s_check, t_check); + } } - } /* remove state */ - GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s); + GNUNET_CONTAINER_DLL_remove(a->states_head, a->states_tail, s); a->state_count--; - automaton_destroy_state (s); + automaton_destroy_state(s); } @@ -372,10 +371,10 @@ automaton_remove_state (struct REGEX_INTERNAL_Automaton *a, * @param s2 second state, will be destroyed */ static void -automaton_merge_states (struct REGEX_INTERNAL_Context *ctx, - struct REGEX_INTERNAL_Automaton *a, - struct REGEX_INTERNAL_State *s1, - struct REGEX_INTERNAL_State *s2) +automaton_merge_states(struct REGEX_INTERNAL_Context *ctx, + struct REGEX_INTERNAL_Automaton *a, + struct REGEX_INTERNAL_State *s1, + struct REGEX_INTERNAL_State *s2) { struct REGEX_INTERNAL_State *s_check; struct REGEX_INTERNAL_Transition *t_check; @@ -389,47 +388,47 @@ automaton_merge_states (struct REGEX_INTERNAL_Context *ctx, /* 1. Make all transitions pointing to s2 point to s1, unless this transition * does not already exists, if it already exists remove transition. */ for (s_check = a->states_head; NULL != s_check; s_check = s_check->next) - { - for (t_check = s_check->transitions_head; NULL != t_check; t_check = t_next) { - t_next = t_check->next; - - if (s2 == t_check->to_state) - { - is_dup = GNUNET_NO; - for (t = t_check->from_state->transitions_head; NULL != t; t = t->next) + for (t_check = s_check->transitions_head; NULL != t_check; t_check = t_next) { - if (t->to_state == s1 && 0 == strcmp (t_check->label, t->label)) - is_dup = GNUNET_YES; + t_next = t_check->next; + + if (s2 == t_check->to_state) + { + is_dup = GNUNET_NO; + for (t = t_check->from_state->transitions_head; NULL != t; t = t->next) + { + if (t->to_state == s1 && 0 == strcmp(t_check->label, t->label)) + is_dup = GNUNET_YES; + } + if (GNUNET_NO == is_dup) + t_check->to_state = s1; + else + state_remove_transition(t_check->from_state, t_check); + } } - if (GNUNET_NO == is_dup) - t_check->to_state = s1; - else - state_remove_transition (t_check->from_state, t_check); - } } - } /* 2. Add all transitions from s2 to sX to s1 */ for (t_check = s2->transitions_head; NULL != t_check; t_check = t_check->next) - { - if (t_check->to_state != s1) - state_add_transition (ctx, s1, t_check->label, t_check->to_state); - } + { + if (t_check->to_state != s1) + state_add_transition(ctx, s1, t_check->label, t_check->to_state); + } /* 3. Rename s1 to {s1,s2} */ #if REGEX_DEBUG_DFA char *new_name; new_name = s1->name; - GNUNET_asprintf (&s1->name, "{%s,%s}", new_name, s2->name); - GNUNET_free (new_name); + GNUNET_asprintf(&s1->name, "{%s,%s}", new_name, s2->name); + GNUNET_free(new_name); #endif /* remove state */ - GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s2); + GNUNET_CONTAINER_DLL_remove(a->states_head, a->states_tail, s2); a->state_count--; - automaton_destroy_state (s2); + automaton_destroy_state(s2); } @@ -441,10 +440,10 @@ automaton_merge_states (struct REGEX_INTERNAL_Context *ctx, * @param s state that should be added */ static void -automaton_add_state (struct REGEX_INTERNAL_Automaton *a, - struct REGEX_INTERNAL_State *s) +automaton_add_state(struct REGEX_INTERNAL_Automaton *a, + struct REGEX_INTERNAL_State *s) { - GNUNET_CONTAINER_DLL_insert (a->states_head, a->states_tail, s); + GNUNET_CONTAINER_DLL_insert(a->states_head, a->states_tail, s); a->state_count++; } @@ -464,13 +463,13 @@ automaton_add_state (struct REGEX_INTERNAL_Automaton *a, * @param action_cls closure for action. */ static void -automaton_state_traverse (struct REGEX_INTERNAL_State *s, - int *marks, - unsigned int *count, - REGEX_INTERNAL_traverse_check check, - void *check_cls, - REGEX_INTERNAL_traverse_action action, - void *action_cls) +automaton_state_traverse(struct REGEX_INTERNAL_State *s, + int *marks, + unsigned int *count, + REGEX_INTERNAL_traverse_check check, + void *check_cls, + REGEX_INTERNAL_traverse_action action, + void *action_cls) { struct REGEX_INTERNAL_Transition *t; @@ -480,24 +479,24 @@ automaton_state_traverse (struct REGEX_INTERNAL_State *s, marks[s->traversal_id] = GNUNET_YES; if (NULL != action) - action (action_cls, *count, s); + action(action_cls, *count, s); (*count)++; for (t = s->transitions_head; NULL != t; t = t->next) - { - if (NULL == check || - (NULL != check && GNUNET_YES == check (check_cls, s, t))) { - automaton_state_traverse (t->to_state, - marks, - count, - check, - check_cls, - action, - action_cls); + if (NULL == check || + (NULL != check && GNUNET_YES == check(check_cls, s, t))) + { + automaton_state_traverse(t->to_state, + marks, + count, + check, + check_cls, + action, + action_cls); + } } - } } @@ -515,12 +514,12 @@ automaton_state_traverse (struct REGEX_INTERNAL_State *s, * @param action_cls closure for @a action */ void -REGEX_INTERNAL_automaton_traverse (const struct REGEX_INTERNAL_Automaton *a, - struct REGEX_INTERNAL_State *start, - REGEX_INTERNAL_traverse_check check, - void *check_cls, - REGEX_INTERNAL_traverse_action action, - void *action_cls) +REGEX_INTERNAL_automaton_traverse(const struct REGEX_INTERNAL_Automaton *a, + struct REGEX_INTERNAL_State *start, + REGEX_INTERNAL_traverse_check check, + void *check_cls, + REGEX_INTERNAL_traverse_action action, + void *action_cls) { unsigned int count; struct REGEX_INTERNAL_State *s; @@ -532,10 +531,10 @@ REGEX_INTERNAL_automaton_traverse (const struct REGEX_INTERNAL_Automaton *a, for (count = 0, s = a->states_head; NULL != s && count < a->state_count; s = s->next, count++) - { - s->traversal_id = count; - marks[s->traversal_id] = GNUNET_NO; - } + { + s->traversal_id = count; + marks[s->traversal_id] = GNUNET_NO; + } count = 0; @@ -544,21 +543,20 @@ REGEX_INTERNAL_automaton_traverse (const struct REGEX_INTERNAL_Automaton *a, else s = start; - automaton_state_traverse (s, - marks, - &count, - check, - check_cls, - action, - action_cls); + automaton_state_traverse(s, + marks, + &count, + check, + check_cls, + action, + action_cls); } /** * String container for faster string operations. */ -struct StringBuffer -{ +struct StringBuffer { /** * Buffer holding the string (may start in the middle!); * NOT 0-terminated! @@ -607,7 +605,7 @@ struct StringBuffer * @return 0 if the strings are the same or both NULL, 1 or -1 if not. */ static int -sb_nullstrcmp (const struct StringBuffer *s1, const struct StringBuffer *s2) +sb_nullstrcmp(const struct StringBuffer *s1, const struct StringBuffer *s2) { if ((GNUNET_YES == s1->null_flag) && (GNUNET_YES == s2->null_flag)) return 0; @@ -617,7 +615,7 @@ sb_nullstrcmp (const struct StringBuffer *s1, const struct StringBuffer *s2) return -1; if (0 == s1->slen) return 0; - return memcmp (s1->sbuf, s2->sbuf, s1->slen); + return memcmp(s1->sbuf, s2->sbuf, s1->slen); } @@ -630,13 +628,13 @@ sb_nullstrcmp (const struct StringBuffer *s1, const struct StringBuffer *s2) * @return 0 if the strings are the same, 1 or -1 if not. */ static int -sb_strcmp (const struct StringBuffer *s1, const struct StringBuffer *s2) +sb_strcmp(const struct StringBuffer *s1, const struct StringBuffer *s2) { if (s1->slen != s2->slen) return -1; if (0 == s1->slen) return 0; - return memcmp (s1->sbuf, s2->sbuf, s1->slen); + return memcmp(s1->sbuf, s2->sbuf, s1->slen); } @@ -648,17 +646,17 @@ sb_strcmp (const struct StringBuffer *s1, const struct StringBuffer *s2) * @param nlen target length for the buffer, must be at least ret->slen */ static void -sb_realloc (struct StringBuffer *ret, size_t nlen) +sb_realloc(struct StringBuffer *ret, size_t nlen) { char *old; - GNUNET_assert (nlen >= ret->slen); + GNUNET_assert(nlen >= ret->slen); old = ret->abuf; - ret->abuf = GNUNET_malloc (nlen); + ret->abuf = GNUNET_malloc(nlen); ret->blen = nlen; - GNUNET_memcpy (ret->abuf, ret->sbuf, ret->slen); + GNUNET_memcpy(ret->abuf, ret->sbuf, ret->slen); ret->sbuf = ret->abuf; - GNUNET_free_non_null (old); + GNUNET_free_non_null(old); } @@ -669,14 +667,14 @@ sb_realloc (struct StringBuffer *ret, size_t nlen) * @param sarg string to append */ static void -sb_append (struct StringBuffer *ret, const struct StringBuffer *sarg) +sb_append(struct StringBuffer *ret, const struct StringBuffer *sarg) { if (GNUNET_YES == ret->null_flag) ret->slen = 0; ret->null_flag = GNUNET_NO; if (ret->blen < sarg->slen + ret->slen) - sb_realloc (ret, ret->blen + sarg->slen + 128); - GNUNET_memcpy (&ret->sbuf[ret->slen], sarg->sbuf, sarg->slen); + sb_realloc(ret, ret->blen + sarg->slen + 128); + GNUNET_memcpy(&ret->sbuf[ret->slen], sarg->sbuf, sarg->slen); ret->slen += sarg->slen; } @@ -688,16 +686,16 @@ sb_append (struct StringBuffer *ret, const struct StringBuffer *sarg) * @param cstr string to append */ static void -sb_append_cstr (struct StringBuffer *ret, const char *cstr) +sb_append_cstr(struct StringBuffer *ret, const char *cstr) { - size_t cstr_len = strlen (cstr); + size_t cstr_len = strlen(cstr); if (GNUNET_YES == ret->null_flag) ret->slen = 0; ret->null_flag = GNUNET_NO; if (ret->blen < cstr_len + ret->slen) - sb_realloc (ret, ret->blen + cstr_len + 128); - GNUNET_memcpy (&ret->sbuf[ret->slen], cstr, cstr_len); + sb_realloc(ret, ret->blen + cstr_len + 128); + GNUNET_memcpy(&ret->sbuf[ret->slen], cstr, cstr_len); ret->slen += cstr_len; } @@ -713,20 +711,20 @@ sb_append_cstr (struct StringBuffer *ret, const char *cstr) * @param extra_chars how long will the result be, in addition to 'sarg' length */ static void -sb_wrap (struct StringBuffer *ret, const char *format, size_t extra_chars) +sb_wrap(struct StringBuffer *ret, const char *format, size_t extra_chars) { char *temp; if (GNUNET_YES == ret->null_flag) ret->slen = 0; ret->null_flag = GNUNET_NO; - temp = GNUNET_malloc (ret->slen + extra_chars + 1); - GNUNET_snprintf (temp, - ret->slen + extra_chars + 1, - format, - (int) ret->slen, - ret->sbuf); - GNUNET_free_non_null (ret->abuf); + temp = GNUNET_malloc(ret->slen + extra_chars + 1); + GNUNET_snprintf(temp, + ret->slen + extra_chars + 1, + format, + (int)ret->slen, + ret->sbuf); + GNUNET_free_non_null(ret->abuf); ret->abuf = temp; ret->sbuf = temp; ret->blen = ret->slen + extra_chars + 1; @@ -744,17 +742,17 @@ sb_wrap (struct StringBuffer *ret, const char *format, size_t extra_chars) * @param sarg string to print into the format */ static void -sb_printf1 (struct StringBuffer *ret, - const char *format, - size_t extra_chars, - const struct StringBuffer *sarg) +sb_printf1(struct StringBuffer *ret, + const char *format, + size_t extra_chars, + const struct StringBuffer *sarg) { if (ret->blen < sarg->slen + extra_chars + 1) - sb_realloc (ret, sarg->slen + extra_chars + 1); + sb_realloc(ret, sarg->slen + extra_chars + 1); ret->null_flag = GNUNET_NO; ret->sbuf = ret->abuf; ret->slen = sarg->slen + extra_chars; - GNUNET_snprintf (ret->sbuf, ret->blen, format, (int) sarg->slen, sarg->sbuf); + GNUNET_snprintf(ret->sbuf, ret->blen, format, (int)sarg->slen, sarg->sbuf); } @@ -768,24 +766,24 @@ sb_printf1 (struct StringBuffer *ret, * @param sarg2 second string to print into the format */ static void -sb_printf2 (struct StringBuffer *ret, - const char *format, - size_t extra_chars, - const struct StringBuffer *sarg1, - const struct StringBuffer *sarg2) +sb_printf2(struct StringBuffer *ret, + const char *format, + size_t extra_chars, + const struct StringBuffer *sarg1, + const struct StringBuffer *sarg2) { if (ret->blen < sarg1->slen + sarg2->slen + extra_chars + 1) - sb_realloc (ret, sarg1->slen + sarg2->slen + extra_chars + 1); + sb_realloc(ret, sarg1->slen + sarg2->slen + extra_chars + 1); ret->null_flag = GNUNET_NO; ret->slen = sarg1->slen + sarg2->slen + extra_chars; ret->sbuf = ret->abuf; - GNUNET_snprintf (ret->sbuf, - ret->blen, - format, - (int) sarg1->slen, - sarg1->sbuf, - (int) sarg2->slen, - sarg2->sbuf); + GNUNET_snprintf(ret->sbuf, + ret->blen, + format, + (int)sarg1->slen, + sarg1->sbuf, + (int)sarg2->slen, + sarg2->sbuf); } @@ -801,27 +799,27 @@ sb_printf2 (struct StringBuffer *ret, * @param sarg3 third string to print into the format */ static void -sb_printf3 (struct StringBuffer *ret, - const char *format, - size_t extra_chars, - const struct StringBuffer *sarg1, - const struct StringBuffer *sarg2, - const struct StringBuffer *sarg3) +sb_printf3(struct StringBuffer *ret, + const char *format, + size_t extra_chars, + const struct StringBuffer *sarg1, + const struct StringBuffer *sarg2, + const struct StringBuffer *sarg3) { if (ret->blen < sarg1->slen + sarg2->slen + sarg3->slen + extra_chars + 1) - sb_realloc (ret, sarg1->slen + sarg2->slen + sarg3->slen + extra_chars + 1); + sb_realloc(ret, sarg1->slen + sarg2->slen + sarg3->slen + extra_chars + 1); ret->null_flag = GNUNET_NO; ret->slen = sarg1->slen + sarg2->slen + sarg3->slen + extra_chars; ret->sbuf = ret->abuf; - GNUNET_snprintf (ret->sbuf, - ret->blen, - format, - (int) sarg1->slen, - sarg1->sbuf, - (int) sarg2->slen, - sarg2->sbuf, - (int) sarg3->slen, - sarg3->sbuf); + GNUNET_snprintf(ret->sbuf, + ret->blen, + format, + (int)sarg1->slen, + sarg1->sbuf, + (int)sarg2->slen, + sarg2->sbuf, + (int)sarg3->slen, + sarg3->sbuf); } @@ -832,9 +830,9 @@ sb_printf3 (struct StringBuffer *ret, * should not be individually allocated) */ static void -sb_free (struct StringBuffer *sb) +sb_free(struct StringBuffer *sb) { - GNUNET_array_grow (sb->abuf, sb->blen, 0); + GNUNET_array_grow(sb->abuf, sb->blen, 0); sb->slen = 0; sb->sbuf = NULL; sb->null_flag = GNUNET_YES; @@ -848,19 +846,19 @@ sb_free (struct StringBuffer *sb) * @param out output string */ static void -sb_strdup (struct StringBuffer *out, const struct StringBuffer *in) +sb_strdup(struct StringBuffer *out, const struct StringBuffer *in) { out->null_flag = in->null_flag; if (GNUNET_YES == out->null_flag) return; if (out->blen < in->slen) - { - GNUNET_array_grow (out->abuf, out->blen, in->slen); - } + { + GNUNET_array_grow(out->abuf, out->blen, in->slen); + } out->sbuf = out->abuf; out->slen = in->slen; - GNUNET_memcpy (out->sbuf, in->sbuf, out->slen); + GNUNET_memcpy(out->sbuf, in->sbuf, out->slen); } @@ -871,21 +869,21 @@ sb_strdup (struct StringBuffer *out, const struct StringBuffer *in) * @param out output string */ static void -sb_strdup_cstr (struct StringBuffer *out, const char *cstr) +sb_strdup_cstr(struct StringBuffer *out, const char *cstr) { if (NULL == cstr) - { - out->null_flag = GNUNET_YES; - return; - } + { + out->null_flag = GNUNET_YES; + return; + } out->null_flag = GNUNET_NO; - out->slen = strlen (cstr); + out->slen = strlen(cstr); if (out->blen < out->slen) - { - GNUNET_array_grow (out->abuf, out->blen, out->slen); - } + { + GNUNET_array_grow(out->abuf, out->blen, out->slen); + } out->sbuf = out->abuf; - GNUNET_memcpy (out->sbuf, cstr, out->slen); + GNUNET_memcpy(out->sbuf, cstr, out->slen); } @@ -898,7 +896,7 @@ sb_strdup_cstr (struct StringBuffer *out, const char *cstr) * @return #GNUNET_YES if parentheses are needed, #GNUNET_NO otherwise */ static int -needs_parentheses (const struct StringBuffer *str) +needs_parentheses(const struct StringBuffer *str) { size_t slen; const char *op; @@ -916,23 +914,23 @@ needs_parentheses (const struct StringBuffer *str) cnt = 1; pos++; while (cnt > 0) - { - cl = memchr (pos, ')', end - pos); - if (NULL == cl) - { - GNUNET_break (0); - return GNUNET_YES; - } - /* while '(' before ')', count opening parens */ - while ((NULL != (op = memchr (pos, '(', end - pos))) && (op < cl)) { - cnt++; - pos = op + 1; + cl = memchr(pos, ')', end - pos); + if (NULL == cl) + { + GNUNET_break(0); + return GNUNET_YES; + } + /* while '(' before ')', count opening parens */ + while ((NULL != (op = memchr(pos, '(', end - pos))) && (op < cl)) + { + cnt++; + pos = op + 1; + } + /* got ')' first */ + cnt--; + pos = cl + 1; } - /* got ')' first */ - cnt--; - pos = cl + 1; - } return (*pos == '\0') ? GNUNET_NO : GNUNET_YES; } @@ -947,7 +945,7 @@ needs_parentheses (const struct StringBuffer *str) * epsilon could be found, NULL if 'str' was NULL */ static void -remove_parentheses (struct StringBuffer *str) +remove_parentheses(struct StringBuffer *str) { size_t slen; const char *pos; @@ -966,30 +964,30 @@ remove_parentheses (struct StringBuffer *str) cnt = 0; pos = &sbuf[1]; end = &sbuf[slen - 1]; - op = memchr (pos, '(', end - pos); - cp = memchr (pos, ')', end - pos); + op = memchr(pos, '(', end - pos); + cp = memchr(pos, ')', end - pos); while (NULL != cp) - { - while ((NULL != op) && (op < cp)) { - cnt++; - pos = op + 1; - op = memchr (pos, '(', end - pos); + while ((NULL != op) && (op < cp)) + { + cnt++; + pos = op + 1; + op = memchr(pos, '(', end - pos); + } + while ((NULL != cp) && ((NULL == op) || (cp < op))) + { + if (0 == cnt) + return; /* can't strip parens */ + cnt--; + pos = cp + 1; + cp = memchr(pos, ')', end - pos); + } } - while ((NULL != cp) && ((NULL == op) || (cp < op))) + if (0 != cnt) { - if (0 == cnt) - return; /* can't strip parens */ - cnt--; - pos = cp + 1; - cp = memchr (pos, ')', end - pos); + GNUNET_break(0); + return; } - } - if (0 != cnt) - { - GNUNET_break (0); - return; - } str->sbuf++; str->slen -= 2; } @@ -1004,7 +1002,7 @@ remove_parentheses (struct StringBuffer *str) * @return 0 if str has no epsilon, 1 if str starts with '(|' and ends with ')' */ static int -has_epsilon (const struct StringBuffer *str) +has_epsilon(const struct StringBuffer *str) { return (GNUNET_YES != str->null_flag) && (0 < str->slen) && ('(' == str->sbuf[0]) && ('|' == str->sbuf[1]) && @@ -1022,27 +1020,27 @@ has_epsilon (const struct StringBuffer *str) * epsilon could be found, NULL if 'str' was NULL */ static void -remove_epsilon (const struct StringBuffer *str, struct StringBuffer *ret) +remove_epsilon(const struct StringBuffer *str, struct StringBuffer *ret) { if (GNUNET_YES == str->null_flag) - { - ret->null_flag = GNUNET_YES; - return; - } + { + ret->null_flag = GNUNET_YES; + return; + } if ((str->slen > 1) && ('(' == str->sbuf[0]) && ('|' == str->sbuf[1]) && (')' == str->sbuf[str->slen - 1])) - { - /* remove epsilon */ - if (ret->blen < str->slen - 3) { - GNUNET_array_grow (ret->abuf, ret->blen, str->slen - 3); + /* remove epsilon */ + if (ret->blen < str->slen - 3) + { + GNUNET_array_grow(ret->abuf, ret->blen, str->slen - 3); + } + ret->sbuf = ret->abuf; + ret->slen = str->slen - 3; + GNUNET_memcpy(ret->sbuf, &str->sbuf[2], ret->slen); + return; } - ret->sbuf = ret->abuf; - ret->slen = str->slen - 3; - GNUNET_memcpy (ret->sbuf, &str->sbuf[2], ret->slen); - return; - } - sb_strdup (ret, str); + sb_strdup(ret, str); } @@ -1056,18 +1054,18 @@ remove_epsilon (const struct StringBuffer *str, struct StringBuffer *ret) * @return -1 if any of the strings is NULL, 0 if equal, non 0 otherwise */ static int -sb_strncmp (const struct StringBuffer *str1, - const struct StringBuffer *str2, - size_t n) +sb_strncmp(const struct StringBuffer *str1, + const struct StringBuffer *str2, + size_t n) { size_t max; if ((str1->slen != str2->slen) && ((str1->slen < n) || (str2->slen < n))) return -1; - max = GNUNET_MAX (str1->slen, str2->slen); + max = GNUNET_MAX(str1->slen, str2->slen); if (max > n) max = n; - return memcmp (str1->sbuf, str2->sbuf, max); + return memcmp(str1->sbuf, str2->sbuf, max); } @@ -1081,11 +1079,11 @@ sb_strncmp (const struct StringBuffer *str1, * @return -1 if any of the strings is NULL, 0 if equal, non 0 otherwise */ static int -sb_strncmp_cstr (const struct StringBuffer *str1, const char *str2, size_t n) +sb_strncmp_cstr(const struct StringBuffer *str1, const char *str2, size_t n) { if (str1->slen < n) return -1; - return memcmp (str1->sbuf, str2, n); + return memcmp(str1->sbuf, str2, n); } @@ -1097,10 +1095,10 @@ sb_strncmp_cstr (const struct StringBuffer *str1, const char *str2, size_t n) * @param n desired target length */ static void -sb_init (struct StringBuffer *sb, size_t n) +sb_init(struct StringBuffer *sb, size_t n) { sb->null_flag = GNUNET_NO; - sb->abuf = sb->sbuf = (0 == n) ? NULL : GNUNET_malloc (n); + sb->abuf = sb->sbuf = (0 == n) ? NULL : GNUNET_malloc(n); sb->blen = n; sb->slen = 0; } @@ -1116,14 +1114,14 @@ sb_init (struct StringBuffer *sb, size_t n) * @return -1 if any of the strings is NULL, 0 if equal, non 0 otherwise */ static int -sb_strkcmp (const struct StringBuffer *str1, - const struct StringBuffer *str2, - size_t k) +sb_strkcmp(const struct StringBuffer *str1, + const struct StringBuffer *str2, + size_t k) { if ((GNUNET_YES == str1->null_flag) || (GNUNET_YES == str2->null_flag) || (k > str1->slen) || (str1->slen - k != str2->slen)) return -1; - return memcmp (&str1->sbuf[k], str2->sbuf, str2->slen); + return memcmp(&str1->sbuf[k], str2->sbuf, str2->slen); } @@ -1136,9 +1134,9 @@ sb_strkcmp (const struct StringBuffer *str1, * @param s current state. */ static void -number_states (void *cls, - const unsigned int count, - struct REGEX_INTERNAL_State *s) +number_states(void *cls, + const unsigned int count, + struct REGEX_INTERNAL_State *s) { struct REGEX_INTERNAL_State **states = cls; @@ -1149,8 +1147,8 @@ number_states (void *cls, #define PRIS(a) \ - ((GNUNET_YES == a.null_flag) ? 6 : (int) a.slen), \ - ((GNUNET_YES == a.null_flag) ? "(null)" : a.sbuf) + ((GNUNET_YES == a.null_flag) ? 6 : (int)a.slen), \ + ((GNUNET_YES == a.null_flag) ? "(null)" : a.sbuf) /** @@ -1168,13 +1166,13 @@ number_states (void *cls, * @param R_cur_r optimization -- kept between iterations to avoid realloc */ static void -automaton_create_proofs_simplify (const struct StringBuffer *R_last_ij, - const struct StringBuffer *R_last_ik, - const struct StringBuffer *R_last_kk, - const struct StringBuffer *R_last_kj, - struct StringBuffer *R_cur_ij, - struct StringBuffer *R_cur_l, - struct StringBuffer *R_cur_r) +automaton_create_proofs_simplify(const struct StringBuffer *R_last_ij, + const struct StringBuffer *R_last_ik, + const struct StringBuffer *R_last_kk, + const struct StringBuffer *R_last_kj, + struct StringBuffer *R_cur_ij, + struct StringBuffer *R_cur_l, + struct StringBuffer *R_cur_r) { struct StringBuffer R_temp_ij; struct StringBuffer R_temp_ik; @@ -1202,27 +1200,27 @@ automaton_create_proofs_simplify (const struct StringBuffer *R_last_ij, if ((GNUNET_YES == R_last_ij->null_flag) && ((GNUNET_YES == R_last_ik->null_flag) || (GNUNET_YES == R_last_kj->null_flag))) - { - /* R^{(k)}_{ij} = N | N */ - R_cur_ij->null_flag = GNUNET_YES; - R_cur_ij->synced = GNUNET_NO; - return; - } + { + /* R^{(k)}_{ij} = N | N */ + R_cur_ij->null_flag = GNUNET_YES; + R_cur_ij->synced = GNUNET_NO; + return; + } if ((GNUNET_YES == R_last_ik->null_flag) || (GNUNET_YES == R_last_kj->null_flag)) - { - /* R^{(k)}_{ij} = R^{(k-1)}_{ij} | N */ - if (GNUNET_YES == R_last_ij->synced) { + /* R^{(k)}_{ij} = R^{(k-1)}_{ij} | N */ + if (GNUNET_YES == R_last_ij->synced) + { + R_cur_ij->synced = GNUNET_YES; + R_cur_ij->null_flag = GNUNET_NO; + return; + } R_cur_ij->synced = GNUNET_YES; - R_cur_ij->null_flag = GNUNET_NO; + sb_strdup(R_cur_ij, R_last_ij); return; } - R_cur_ij->synced = GNUNET_YES; - sb_strdup (R_cur_ij, R_last_ij); - return; - } R_cur_ij->synced = GNUNET_NO; /* $R^{(k)}_{ij} = N | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj} OR @@ -1234,334 +1232,334 @@ automaton_create_proofs_simplify (const struct StringBuffer *R_last_ij, R_cur_l->slen = 0; /* cache results from strcmp, we might need these many times */ - ij_kj_cmp = sb_nullstrcmp (R_last_ij, R_last_kj); - ij_ik_cmp = sb_nullstrcmp (R_last_ij, R_last_ik); - ik_kk_cmp = sb_nullstrcmp (R_last_ik, R_last_kk); - kk_kj_cmp = sb_nullstrcmp (R_last_kk, R_last_kj); + ij_kj_cmp = sb_nullstrcmp(R_last_ij, R_last_kj); + ij_ik_cmp = sb_nullstrcmp(R_last_ij, R_last_ik); + ik_kk_cmp = sb_nullstrcmp(R_last_ik, R_last_kk); + kk_kj_cmp = sb_nullstrcmp(R_last_kk, R_last_kj); /* Assign R_temp_(ik|kk|kj) to R_last[][] and remove epsilon as well * as parentheses, so we can better compare the contents */ - memset (&R_temp_ij, 0, sizeof (struct StringBuffer)); - memset (&R_temp_ik, 0, sizeof (struct StringBuffer)); - memset (&R_temp_kk, 0, sizeof (struct StringBuffer)); - memset (&R_temp_kj, 0, sizeof (struct StringBuffer)); - remove_epsilon (R_last_ik, &R_temp_ik); - remove_epsilon (R_last_kk, &R_temp_kk); - remove_epsilon (R_last_kj, &R_temp_kj); - remove_parentheses (&R_temp_ik); - remove_parentheses (&R_temp_kk); - remove_parentheses (&R_temp_kj); - clean_ik_kk_cmp = sb_nullstrcmp (R_last_ik, &R_temp_kk); - clean_kk_kj_cmp = sb_nullstrcmp (&R_temp_kk, R_last_kj); + memset(&R_temp_ij, 0, sizeof(struct StringBuffer)); + memset(&R_temp_ik, 0, sizeof(struct StringBuffer)); + memset(&R_temp_kk, 0, sizeof(struct StringBuffer)); + memset(&R_temp_kj, 0, sizeof(struct StringBuffer)); + remove_epsilon(R_last_ik, &R_temp_ik); + remove_epsilon(R_last_kk, &R_temp_kk); + remove_epsilon(R_last_kj, &R_temp_kj); + remove_parentheses(&R_temp_ik); + remove_parentheses(&R_temp_kk); + remove_parentheses(&R_temp_kj); + clean_ik_kk_cmp = sb_nullstrcmp(R_last_ik, &R_temp_kk); + clean_kk_kj_cmp = sb_nullstrcmp(&R_temp_kk, R_last_kj); /* construct R_cur_l (and, if necessary R_cur_r) */ if (GNUNET_YES != R_last_ij->null_flag) - { - /* Assign R_temp_ij to R_last_ij and remove epsilon as well - * as parentheses, so we can better compare the contents */ - remove_epsilon (R_last_ij, &R_temp_ij); - remove_parentheses (&R_temp_ij); - - if ((0 == sb_strcmp (&R_temp_ij, &R_temp_ik)) && - (0 == sb_strcmp (&R_temp_ik, &R_temp_kk)) && - (0 == sb_strcmp (&R_temp_kk, &R_temp_kj))) - { - if (0 == R_temp_ij.slen) - { - R_cur_r->null_flag = GNUNET_NO; - } - else if ((0 == sb_strncmp_cstr (R_last_ij, "(|", 2)) || - (0 == sb_strncmp_cstr (R_last_ik, "(|", 2) && - 0 == sb_strncmp_cstr (R_last_kj, "(|", 2))) - { - /* - * a|(e|a)a*(e|a) = a* - * a|(e|a)(e|a)*(e|a) = a* - * (e|a)|aa*a = a* - * (e|a)|aa*(e|a) = a* - * (e|a)|(e|a)a*a = a* - * (e|a)|(e|a)a*(e|a) = a* - * (e|a)|(e|a)(e|a)*(e|a) = a* - */ - if (GNUNET_YES == needs_parentheses (&R_temp_ij)) - sb_printf1 (R_cur_r, "(%.*s)*", 3, &R_temp_ij); - else - sb_printf1 (R_cur_r, "%.*s*", 1, &R_temp_ij); - } - else - { - /* - * a|aa*a = a+ - * a|(e|a)a*a = a+ - * a|aa*(e|a) = a+ - * a|(e|a)(e|a)*a = a+ - * a|a(e|a)*(e|a) = a+ - */ - if (GNUNET_YES == needs_parentheses (&R_temp_ij)) - sb_printf1 (R_cur_r, "(%.*s)+", 3, &R_temp_ij); - else - sb_printf1 (R_cur_r, "%.*s+", 1, &R_temp_ij); - } - } - else if ((0 == ij_ik_cmp) && (0 == clean_kk_kj_cmp) && - (0 != clean_ik_kk_cmp)) - { - /* a|ab*b = ab* */ - if (0 == R_last_kk->slen) - sb_strdup (R_cur_r, R_last_ij); - else if (GNUNET_YES == needs_parentheses (&R_temp_kk)) - sb_printf2 (R_cur_r, "%.*s(%.*s)*", 3, R_last_ij, &R_temp_kk); - else - sb_printf2 (R_cur_r, "%.*s%.*s*", 1, R_last_ij, R_last_kk); - R_cur_l->null_flag = GNUNET_YES; - } - else if ((0 == ij_kj_cmp) && (0 == clean_ik_kk_cmp) && - (0 != clean_kk_kj_cmp)) { - /* a|bb*a = b*a */ - if (R_last_kk->slen < 1) - { - sb_strdup (R_cur_r, R_last_kj); - } - else if (GNUNET_YES == needs_parentheses (&R_temp_kk)) - sb_printf2 (R_cur_r, "(%.*s)*%.*s", 3, &R_temp_kk, R_last_kj); - else - sb_printf2 (R_cur_r, "%.*s*%.*s", 1, &R_temp_kk, R_last_kj); + /* Assign R_temp_ij to R_last_ij and remove epsilon as well + * as parentheses, so we can better compare the contents */ + remove_epsilon(R_last_ij, &R_temp_ij); + remove_parentheses(&R_temp_ij); + + if ((0 == sb_strcmp(&R_temp_ij, &R_temp_ik)) && + (0 == sb_strcmp(&R_temp_ik, &R_temp_kk)) && + (0 == sb_strcmp(&R_temp_kk, &R_temp_kj))) + { + if (0 == R_temp_ij.slen) + { + R_cur_r->null_flag = GNUNET_NO; + } + else if ((0 == sb_strncmp_cstr(R_last_ij, "(|", 2)) || + (0 == sb_strncmp_cstr(R_last_ik, "(|", 2) && + 0 == sb_strncmp_cstr(R_last_kj, "(|", 2))) + { + /* + * a|(e|a)a*(e|a) = a* + * a|(e|a)(e|a)*(e|a) = a* + * (e|a)|aa*a = a* + * (e|a)|aa*(e|a) = a* + * (e|a)|(e|a)a*a = a* + * (e|a)|(e|a)a*(e|a) = a* + * (e|a)|(e|a)(e|a)*(e|a) = a* + */ + if (GNUNET_YES == needs_parentheses(&R_temp_ij)) + sb_printf1(R_cur_r, "(%.*s)*", 3, &R_temp_ij); + else + sb_printf1(R_cur_r, "%.*s*", 1, &R_temp_ij); + } + else + { + /* + * a|aa*a = a+ + * a|(e|a)a*a = a+ + * a|aa*(e|a) = a+ + * a|(e|a)(e|a)*a = a+ + * a|a(e|a)*(e|a) = a+ + */ + if (GNUNET_YES == needs_parentheses(&R_temp_ij)) + sb_printf1(R_cur_r, "(%.*s)+", 3, &R_temp_ij); + else + sb_printf1(R_cur_r, "%.*s+", 1, &R_temp_ij); + } + } + else if ((0 == ij_ik_cmp) && (0 == clean_kk_kj_cmp) && + (0 != clean_ik_kk_cmp)) + { + /* a|ab*b = ab* */ + if (0 == R_last_kk->slen) + sb_strdup(R_cur_r, R_last_ij); + else if (GNUNET_YES == needs_parentheses(&R_temp_kk)) + sb_printf2(R_cur_r, "%.*s(%.*s)*", 3, R_last_ij, &R_temp_kk); + else + sb_printf2(R_cur_r, "%.*s%.*s*", 1, R_last_ij, R_last_kk); + R_cur_l->null_flag = GNUNET_YES; + } + else if ((0 == ij_kj_cmp) && (0 == clean_ik_kk_cmp) && + (0 != clean_kk_kj_cmp)) + { + /* a|bb*a = b*a */ + if (R_last_kk->slen < 1) + { + sb_strdup(R_cur_r, R_last_kj); + } + else if (GNUNET_YES == needs_parentheses(&R_temp_kk)) + sb_printf2(R_cur_r, "(%.*s)*%.*s", 3, &R_temp_kk, R_last_kj); + else + sb_printf2(R_cur_r, "%.*s*%.*s", 1, &R_temp_kk, R_last_kj); - R_cur_l->null_flag = GNUNET_YES; - } - else if ((0 == ij_ik_cmp) && (0 == kk_kj_cmp) && - (! has_epsilon (R_last_ij)) && has_epsilon (R_last_kk)) - { - /* a|a(e|b)*(e|b) = a|ab* = a|a|ab|abb|abbb|... = ab* */ - if (needs_parentheses (&R_temp_kk)) - sb_printf2 (R_cur_r, "%.*s(%.*s)*", 3, R_last_ij, &R_temp_kk); + R_cur_l->null_flag = GNUNET_YES; + } + else if ((0 == ij_ik_cmp) && (0 == kk_kj_cmp) && + (!has_epsilon(R_last_ij)) && has_epsilon(R_last_kk)) + { + /* a|a(e|b)*(e|b) = a|ab* = a|a|ab|abb|abbb|... = ab* */ + if (needs_parentheses(&R_temp_kk)) + sb_printf2(R_cur_r, "%.*s(%.*s)*", 3, R_last_ij, &R_temp_kk); + else + sb_printf2(R_cur_r, "%.*s%.*s*", 1, R_last_ij, &R_temp_kk); + R_cur_l->null_flag = GNUNET_YES; + } + else if ((0 == ij_kj_cmp) && (0 == ik_kk_cmp) && + (!has_epsilon(R_last_ij)) && has_epsilon(R_last_kk)) + { + /* a|(e|b)(e|b)*a = a|b*a = a|a|ba|bba|bbba|... = b*a */ + if (needs_parentheses(&R_temp_kk)) + sb_printf2(R_cur_r, "(%.*s)*%.*s", 3, &R_temp_kk, R_last_ij); + else + sb_printf2(R_cur_r, "%.*s*%.*s", 1, &R_temp_kk, R_last_ij); + R_cur_l->null_flag = GNUNET_YES; + } else - sb_printf2 (R_cur_r, "%.*s%.*s*", 1, R_last_ij, &R_temp_kk); - R_cur_l->null_flag = GNUNET_YES; + { + sb_strdup(R_cur_l, R_last_ij); + remove_parentheses(R_cur_l); + } } - else if ((0 == ij_kj_cmp) && (0 == ik_kk_cmp) && - (! has_epsilon (R_last_ij)) && has_epsilon (R_last_kk)) + else { - /* a|(e|b)(e|b)*a = a|b*a = a|a|ba|bba|bbba|... = b*a */ - if (needs_parentheses (&R_temp_kk)) - sb_printf2 (R_cur_r, "(%.*s)*%.*s", 3, &R_temp_kk, R_last_ij); - else - sb_printf2 (R_cur_r, "%.*s*%.*s", 1, &R_temp_kk, R_last_ij); + /* we have no left side */ R_cur_l->null_flag = GNUNET_YES; } - else - { - sb_strdup (R_cur_l, R_last_ij); - remove_parentheses (R_cur_l); - } - } - else - { - /* we have no left side */ - R_cur_l->null_flag = GNUNET_YES; - } /* construct R_cur_r, if not already constructed */ if (GNUNET_YES == R_cur_r->null_flag) - { - length = R_temp_kk.slen - R_last_ik->slen; - - /* a(ba)*bx = (ab)+x */ - if ((length > 0) && (GNUNET_YES != R_last_kk->null_flag) && - (0 < R_last_kk->slen) && (GNUNET_YES != R_last_kj->null_flag) && - (0 < R_last_kj->slen) && (GNUNET_YES != R_last_ik->null_flag) && - (0 < R_last_ik->slen) && - (0 == sb_strkcmp (&R_temp_kk, R_last_ik, length)) && - (0 == sb_strncmp (&R_temp_kk, R_last_kj, length))) - { - struct StringBuffer temp_a; - struct StringBuffer temp_b; - - sb_init (&temp_a, length); - sb_init (&temp_b, R_last_kj->slen - length); - - length_l = length; - temp_a.sbuf = temp_a.abuf; - GNUNET_memcpy (temp_a.sbuf, R_last_kj->sbuf, length_l); - temp_a.slen = length_l; - - length_r = R_last_kj->slen - length; - temp_b.sbuf = temp_b.abuf; - GNUNET_memcpy (temp_b.sbuf, &R_last_kj->sbuf[length], length_r); - temp_b.slen = length_r; - - /* e|(ab)+ = (ab)* */ - if ((GNUNET_YES != R_cur_l->null_flag) && (0 == R_cur_l->slen) && - (0 == temp_b.slen)) - { - sb_printf2 (R_cur_r, "(%.*s%.*s)*", 3, R_last_ik, &temp_a); - sb_free (R_cur_l); - R_cur_l->null_flag = GNUNET_YES; - } - else - { - sb_printf3 (R_cur_r, "(%.*s%.*s)+%.*s", 3, R_last_ik, &temp_a, &temp_b); - } - sb_free (&temp_a); - sb_free (&temp_b); - } - else if (0 == sb_strcmp (&R_temp_ik, &R_temp_kk) && - 0 == sb_strcmp (&R_temp_kk, &R_temp_kj)) { + length = R_temp_kk.slen - R_last_ik->slen; + + /* a(ba)*bx = (ab)+x */ + if ((length > 0) && (GNUNET_YES != R_last_kk->null_flag) && + (0 < R_last_kk->slen) && (GNUNET_YES != R_last_kj->null_flag) && + (0 < R_last_kj->slen) && (GNUNET_YES != R_last_ik->null_flag) && + (0 < R_last_ik->slen) && + (0 == sb_strkcmp(&R_temp_kk, R_last_ik, length)) && + (0 == sb_strncmp(&R_temp_kk, R_last_kj, length))) + { + struct StringBuffer temp_a; + struct StringBuffer temp_b; + + sb_init(&temp_a, length); + sb_init(&temp_b, R_last_kj->slen - length); + + length_l = length; + temp_a.sbuf = temp_a.abuf; + GNUNET_memcpy(temp_a.sbuf, R_last_kj->sbuf, length_l); + temp_a.slen = length_l; + + length_r = R_last_kj->slen - length; + temp_b.sbuf = temp_b.abuf; + GNUNET_memcpy(temp_b.sbuf, &R_last_kj->sbuf[length], length_r); + temp_b.slen = length_r; + + /* e|(ab)+ = (ab)* */ + if ((GNUNET_YES != R_cur_l->null_flag) && (0 == R_cur_l->slen) && + (0 == temp_b.slen)) + { + sb_printf2(R_cur_r, "(%.*s%.*s)*", 3, R_last_ik, &temp_a); + sb_free(R_cur_l); + R_cur_l->null_flag = GNUNET_YES; + } + else + { + sb_printf3(R_cur_r, "(%.*s%.*s)+%.*s", 3, R_last_ik, &temp_a, &temp_b); + } + sb_free(&temp_a); + sb_free(&temp_b); + } + else if (0 == sb_strcmp(&R_temp_ik, &R_temp_kk) && + 0 == sb_strcmp(&R_temp_kk, &R_temp_kj)) + { + /* + * (e|a)a*(e|a) = a* + * (e|a)(e|a)*(e|a) = a* + */ + if (has_epsilon(R_last_ik) && has_epsilon(R_last_kj)) + { + if (needs_parentheses(&R_temp_kk)) + sb_printf1(R_cur_r, "(%.*s)*", 3, &R_temp_kk); + else + sb_printf1(R_cur_r, "%.*s*", 1, &R_temp_kk); + } + /* aa*a = a+a */ + else if ((0 == clean_ik_kk_cmp) && (0 == clean_kk_kj_cmp) && + (!has_epsilon(R_last_ik))) + { + if (needs_parentheses(&R_temp_kk)) + sb_printf2(R_cur_r, "(%.*s)+%.*s", 3, &R_temp_kk, &R_temp_kk); + else + sb_printf2(R_cur_r, "%.*s+%.*s", 1, &R_temp_kk, &R_temp_kk); + } + /* + * (e|a)a*a = a+ + * aa*(e|a) = a+ + * a(e|a)*(e|a) = a+ + * (e|a)a*a = a+ + */ + else + { + eps_check = (has_epsilon(R_last_ik) + has_epsilon(R_last_kk) + + has_epsilon(R_last_kj)); + + if (1 == eps_check) + { + if (needs_parentheses(&R_temp_kk)) + sb_printf1(R_cur_r, "(%.*s)+", 3, &R_temp_kk); + else + sb_printf1(R_cur_r, "%.*s+", 1, &R_temp_kk); + } + } + } /* - * (e|a)a*(e|a) = a* - * (e|a)(e|a)*(e|a) = a* + * aa*b = a+b + * (e|a)(e|a)*b = a*b */ - if (has_epsilon (R_last_ik) && has_epsilon (R_last_kj)) - { - if (needs_parentheses (&R_temp_kk)) - sb_printf1 (R_cur_r, "(%.*s)*", 3, &R_temp_kk); - else - sb_printf1 (R_cur_r, "%.*s*", 1, &R_temp_kk); - } - /* aa*a = a+a */ - else if ((0 == clean_ik_kk_cmp) && (0 == clean_kk_kj_cmp) && - (! has_epsilon (R_last_ik))) - { - if (needs_parentheses (&R_temp_kk)) - sb_printf2 (R_cur_r, "(%.*s)+%.*s", 3, &R_temp_kk, &R_temp_kk); - else - sb_printf2 (R_cur_r, "%.*s+%.*s", 1, &R_temp_kk, &R_temp_kk); - } + else if (0 == sb_strcmp(&R_temp_ik, &R_temp_kk)) + { + if (has_epsilon(R_last_ik)) + { + if (needs_parentheses(&R_temp_kk)) + sb_printf2(R_cur_r, "(%.*s)*%.*s", 3, &R_temp_kk, R_last_kj); + else + sb_printf2(R_cur_r, "%.*s*%.*s", 1, &R_temp_kk, R_last_kj); + } + else + { + if (needs_parentheses(&R_temp_kk)) + sb_printf2(R_cur_r, "(%.*s)+%.*s", 3, &R_temp_kk, R_last_kj); + else + sb_printf2(R_cur_r, "%.*s+%.*s", 1, &R_temp_kk, R_last_kj); + } + } /* - * (e|a)a*a = a+ - * aa*(e|a) = a+ - * a(e|a)*(e|a) = a+ - * (e|a)a*a = a+ + * ba*a = ba+ + * b(e|a)*(e|a) = ba* */ - else - { - eps_check = (has_epsilon (R_last_ik) + has_epsilon (R_last_kk) + - has_epsilon (R_last_kj)); - - if (1 == eps_check) + else if (0 == sb_strcmp(&R_temp_kk, &R_temp_kj)) { - if (needs_parentheses (&R_temp_kk)) - sb_printf1 (R_cur_r, "(%.*s)+", 3, &R_temp_kk); + if (has_epsilon(R_last_kj)) + { + if (needs_parentheses(&R_temp_kk)) + sb_printf2(R_cur_r, "%.*s(%.*s)*", 3, R_last_ik, &R_temp_kk); + else + sb_printf2(R_cur_r, "%.*s%.*s*", 1, R_last_ik, &R_temp_kk); + } else - sb_printf1 (R_cur_r, "%.*s+", 1, &R_temp_kk); + { + if (needs_parentheses(&R_temp_kk)) + sb_printf2(R_cur_r, "(%.*s)+%.*s", 3, R_last_ik, &R_temp_kk); + else + sb_printf2(R_cur_r, "%.*s+%.*s", 1, R_last_ik, &R_temp_kk); + } } - } - } - /* - * aa*b = a+b - * (e|a)(e|a)*b = a*b - */ - else if (0 == sb_strcmp (&R_temp_ik, &R_temp_kk)) - { - if (has_epsilon (R_last_ik)) - { - if (needs_parentheses (&R_temp_kk)) - sb_printf2 (R_cur_r, "(%.*s)*%.*s", 3, &R_temp_kk, R_last_kj); - else - sb_printf2 (R_cur_r, "%.*s*%.*s", 1, &R_temp_kk, R_last_kj); - } - else - { - if (needs_parentheses (&R_temp_kk)) - sb_printf2 (R_cur_r, "(%.*s)+%.*s", 3, &R_temp_kk, R_last_kj); - else - sb_printf2 (R_cur_r, "%.*s+%.*s", 1, &R_temp_kk, R_last_kj); - } - } - /* - * ba*a = ba+ - * b(e|a)*(e|a) = ba* - */ - else if (0 == sb_strcmp (&R_temp_kk, &R_temp_kj)) - { - if (has_epsilon (R_last_kj)) - { - if (needs_parentheses (&R_temp_kk)) - sb_printf2 (R_cur_r, "%.*s(%.*s)*", 3, R_last_ik, &R_temp_kk); - else - sb_printf2 (R_cur_r, "%.*s%.*s*", 1, R_last_ik, &R_temp_kk); - } else - { - if (needs_parentheses (&R_temp_kk)) - sb_printf2 (R_cur_r, "(%.*s)+%.*s", 3, R_last_ik, &R_temp_kk); - else - sb_printf2 (R_cur_r, "%.*s+%.*s", 1, R_last_ik, &R_temp_kk); - } - } - else - { - if (0 < R_temp_kk.slen) - { - if (needs_parentheses (&R_temp_kk)) - { - sb_printf3 (R_cur_r, - "%.*s(%.*s)*%.*s", - 3, - R_last_ik, - &R_temp_kk, - R_last_kj); - } - else { - sb_printf3 (R_cur_r, - "%.*s%.*s*%.*s", - 1, - R_last_ik, - &R_temp_kk, - R_last_kj); + if (0 < R_temp_kk.slen) + { + if (needs_parentheses(&R_temp_kk)) + { + sb_printf3(R_cur_r, + "%.*s(%.*s)*%.*s", + 3, + R_last_ik, + &R_temp_kk, + R_last_kj); + } + else + { + sb_printf3(R_cur_r, + "%.*s%.*s*%.*s", + 1, + R_last_ik, + &R_temp_kk, + R_last_kj); + } + } + else + { + sb_printf2(R_cur_r, "%.*s%.*s", 0, R_last_ik, R_last_kj); + } } - } - else - { - sb_printf2 (R_cur_r, "%.*s%.*s", 0, R_last_ik, R_last_kj); - } } - } - sb_free (&R_temp_ij); - sb_free (&R_temp_ik); - sb_free (&R_temp_kk); - sb_free (&R_temp_kj); + sb_free(&R_temp_ij); + sb_free(&R_temp_ik); + sb_free(&R_temp_kk); + sb_free(&R_temp_kj); if ((GNUNET_YES == R_cur_l->null_flag) && (GNUNET_YES == R_cur_r->null_flag)) - { - R_cur_ij->null_flag = GNUNET_YES; - return; - } + { + R_cur_ij->null_flag = GNUNET_YES; + return; + } if ((GNUNET_YES != R_cur_l->null_flag) && (GNUNET_YES == R_cur_r->null_flag)) - { - struct StringBuffer tmp; + { + struct StringBuffer tmp; - tmp = *R_cur_ij; - *R_cur_ij = *R_cur_l; - *R_cur_l = tmp; - return; - } + tmp = *R_cur_ij; + *R_cur_ij = *R_cur_l; + *R_cur_l = tmp; + return; + } if ((GNUNET_YES == R_cur_l->null_flag) && (GNUNET_YES != R_cur_r->null_flag)) - { - struct StringBuffer tmp; + { + struct StringBuffer tmp; - tmp = *R_cur_ij; - *R_cur_ij = *R_cur_r; - *R_cur_r = tmp; - return; - } + tmp = *R_cur_ij; + *R_cur_ij = *R_cur_r; + *R_cur_r = tmp; + return; + } - if (0 == sb_nullstrcmp (R_cur_l, R_cur_r)) - { - struct StringBuffer tmp; + if (0 == sb_nullstrcmp(R_cur_l, R_cur_r)) + { + struct StringBuffer tmp; - tmp = *R_cur_ij; - *R_cur_ij = *R_cur_l; - *R_cur_l = tmp; - return; - } - sb_printf2 (R_cur_ij, "(%.*s|%.*s)", 3, R_cur_l, R_cur_r); + tmp = *R_cur_ij; + *R_cur_ij = *R_cur_l; + *R_cur_l = tmp; + return; + } + sb_printf2(R_cur_ij, "(%.*s|%.*s)", 3, R_cur_l, R_cur_r); } @@ -1577,7 +1575,7 @@ automaton_create_proofs_simplify (const struct StringBuffer *R_last_ij, * @param a automaton for which to assign proofs and hashes, must not be NULL */ static int -automaton_create_proofs (struct REGEX_INTERNAL_Automaton *a) +automaton_create_proofs(struct REGEX_INTERNAL_Automaton *a) { unsigned int n = a->state_count; struct REGEX_INTERNAL_State *states[n]; @@ -1592,143 +1590,143 @@ automaton_create_proofs (struct REGEX_INTERNAL_Automaton *a) unsigned int j; unsigned int k; - R_last = GNUNET_malloc_large (sizeof (struct StringBuffer) * n * n); - R_cur = GNUNET_malloc_large (sizeof (struct StringBuffer) * n * n); + R_last = GNUNET_malloc_large(sizeof(struct StringBuffer) * n * n); + R_cur = GNUNET_malloc_large(sizeof(struct StringBuffer) * n * n); if ((NULL == R_last) || (NULL == R_cur)) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "malloc"); - GNUNET_free_non_null (R_cur); - GNUNET_free_non_null (R_last); - return GNUNET_SYSERR; - } + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "malloc"); + GNUNET_free_non_null(R_cur); + GNUNET_free_non_null(R_last); + return GNUNET_SYSERR; + } /* create depth-first numbering of the states, initializes 'state' */ - REGEX_INTERNAL_automaton_traverse (a, - a->start, - NULL, - NULL, - &number_states, - states); + REGEX_INTERNAL_automaton_traverse(a, + a->start, + NULL, + NULL, + &number_states, + states); for (i = 0; i < n; i++) - GNUNET_assert (NULL != states[i]); + GNUNET_assert(NULL != states[i]); for (i = 0; i < n; i++) for (j = 0; j < n; j++) R_last[i * n + j].null_flag = GNUNET_YES; /* Compute regular expressions of length "1" between each pair of states */ for (i = 0; i < n; i++) - { - for (t = states[i]->transitions_head; NULL != t; t = t->next) { - j = t->to_state->dfs_id; - if (GNUNET_YES == R_last[i * n + j].null_flag) - { - sb_strdup_cstr (&R_last[i * n + j], t->label); - } + for (t = states[i]->transitions_head; NULL != t; t = t->next) + { + j = t->to_state->dfs_id; + if (GNUNET_YES == R_last[i * n + j].null_flag) + { + sb_strdup_cstr(&R_last[i * n + j], t->label); + } + else + { + sb_append_cstr(&R_last[i * n + j], "|"); + sb_append_cstr(&R_last[i * n + j], t->label); + } + } + /* add self-loop: i is reachable from i via epsilon-transition */ + if (GNUNET_YES == R_last[i * n + i].null_flag) + { + R_last[i * n + i].slen = 0; + R_last[i * n + i].null_flag = GNUNET_NO; + } else - { - sb_append_cstr (&R_last[i * n + j], "|"); - sb_append_cstr (&R_last[i * n + j], t->label); - } - } - /* add self-loop: i is reachable from i via epsilon-transition */ - if (GNUNET_YES == R_last[i * n + i].null_flag) - { - R_last[i * n + i].slen = 0; - R_last[i * n + i].null_flag = GNUNET_NO; - } - else - { - sb_wrap (&R_last[i * n + i], "(|%.*s)", 3); + { + sb_wrap(&R_last[i * n + i], "(|%.*s)", 3); + } } - } for (i = 0; i < n; i++) for (j = 0; j < n; j++) - if (needs_parentheses (&R_last[i * n + j])) - sb_wrap (&R_last[i * n + j], "(%.*s)", 2); + if (needs_parentheses(&R_last[i * n + j])) + sb_wrap(&R_last[i * n + j], "(%.*s)", 2); /* Compute regular expressions of length "k" between each pair of states per * induction */ - memset (&R_cur_l, 0, sizeof (struct StringBuffer)); - memset (&R_cur_r, 0, sizeof (struct StringBuffer)); + memset(&R_cur_l, 0, sizeof(struct StringBuffer)); + memset(&R_cur_r, 0, sizeof(struct StringBuffer)); for (k = 0; k < n; k++) - { - for (i = 0; i < n; i++) { - for (j = 0; j < n; j++) - { - /* Basis for the recursion: - * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj} - * R_last == R^{(k-1)}, R_cur == R^{(k)} - */ - - /* Create R_cur[i][j] and simplify the expression */ - automaton_create_proofs_simplify (&R_last[i * n + j], - &R_last[i * n + k], - &R_last[k * n + k], - &R_last[k * n + j], - &R_cur[i * n + j], - &R_cur_l, - &R_cur_r); - } + for (i = 0; i < n; i++) + { + for (j = 0; j < n; j++) + { + /* Basis for the recursion: + * $R^{(k)}_{ij} = R^{(k-1)}_{ij} | R^{(k-1)}_{ik} ( R^{(k-1)}_{kk} )^* R^{(k-1)}_{kj} + * R_last == R^{(k-1)}, R_cur == R^{(k)} + */ + + /* Create R_cur[i][j] and simplify the expression */ + automaton_create_proofs_simplify(&R_last[i * n + j], + &R_last[i * n + k], + &R_last[k * n + k], + &R_last[k * n + j], + &R_cur[i * n + j], + &R_cur_l, + &R_cur_r); + } + } + /* set R_last = R_cur */ + R_swap = R_last; + R_last = R_cur; + R_cur = R_swap; + /* clear 'R_cur' for next iteration */ + for (i = 0; i < n; i++) + for (j = 0; j < n; j++) + R_cur[i * n + j].null_flag = GNUNET_YES; } - /* set R_last = R_cur */ - R_swap = R_last; - R_last = R_cur; - R_cur = R_swap; - /* clear 'R_cur' for next iteration */ - for (i = 0; i < n; i++) - for (j = 0; j < n; j++) - R_cur[i * n + j].null_flag = GNUNET_YES; - } - sb_free (&R_cur_l); - sb_free (&R_cur_r); + sb_free(&R_cur_l); + sb_free(&R_cur_r); /* assign proofs and hashes */ for (i = 0; i < n; i++) - { - if (GNUNET_YES != R_last[a->start->dfs_id * n + i].null_flag) { - states[i]->proof = GNUNET_strndup (R_last[a->start->dfs_id * n + i].sbuf, - R_last[a->start->dfs_id * n + i].slen); - GNUNET_CRYPTO_hash (states[i]->proof, - strlen (states[i]->proof), - &states[i]->hash); + if (GNUNET_YES != R_last[a->start->dfs_id * n + i].null_flag) + { + states[i]->proof = GNUNET_strndup(R_last[a->start->dfs_id * n + i].sbuf, + R_last[a->start->dfs_id * n + i].slen); + GNUNET_CRYPTO_hash(states[i]->proof, + strlen(states[i]->proof), + &states[i]->hash); + } } - } /* complete regex for whole DFA: union of all pairs (start state/accepting * state(s)). */ - sb_init (&complete_regex, 16 * n); + sb_init(&complete_regex, 16 * n); for (i = 0; i < n; i++) - { - if (states[i]->accepting) { - if ((0 == complete_regex.slen) && - (0 < R_last[a->start->dfs_id * n + i].slen)) - { - sb_append (&complete_regex, &R_last[a->start->dfs_id * n + i]); - } - else if ((GNUNET_YES != R_last[a->start->dfs_id * n + i].null_flag) && - (0 < R_last[a->start->dfs_id * n + i].slen)) - { - sb_append_cstr (&complete_regex, "|"); - sb_append (&complete_regex, &R_last[a->start->dfs_id * n + i]); - } + if (states[i]->accepting) + { + if ((0 == complete_regex.slen) && + (0 < R_last[a->start->dfs_id * n + i].slen)) + { + sb_append(&complete_regex, &R_last[a->start->dfs_id * n + i]); + } + else if ((GNUNET_YES != R_last[a->start->dfs_id * n + i].null_flag) && + (0 < R_last[a->start->dfs_id * n + i].slen)) + { + sb_append_cstr(&complete_regex, "|"); + sb_append(&complete_regex, &R_last[a->start->dfs_id * n + i]); + } + } } - } a->canonical_regex = - GNUNET_strndup (complete_regex.sbuf, complete_regex.slen); + GNUNET_strndup(complete_regex.sbuf, complete_regex.slen); /* cleanup */ - sb_free (&complete_regex); + sb_free(&complete_regex); for (i = 0; i < n; i++) for (j = 0; j < n; j++) - { - sb_free (&R_cur[i * n + j]); - sb_free (&R_last[i * n + j]); - } - GNUNET_free (R_cur); - GNUNET_free (R_last); + { + sb_free(&R_cur[i * n + j]); + sb_free(&R_last[i * n + j]); + } + GNUNET_free(R_cur); + GNUNET_free(R_last); return GNUNET_OK; } @@ -1743,8 +1741,8 @@ automaton_create_proofs (struct REGEX_INTERNAL_Automaton *a) * @return new DFA state */ static struct REGEX_INTERNAL_State * -dfa_state_create (struct REGEX_INTERNAL_Context *ctx, - struct REGEX_INTERNAL_StateSet *nfa_states) +dfa_state_create(struct REGEX_INTERNAL_Context *ctx, + struct REGEX_INTERNAL_StateSet *nfa_states) { struct REGEX_INTERNAL_State *s; char *pos; @@ -1753,16 +1751,16 @@ dfa_state_create (struct REGEX_INTERNAL_Context *ctx, struct REGEX_INTERNAL_Transition *ctran; unsigned int i; - s = GNUNET_new (struct REGEX_INTERNAL_State); + s = GNUNET_new(struct REGEX_INTERNAL_State); s->id = ctx->state_id++; s->index = -1; s->lowlink = -1; if (NULL == nfa_states) - { - GNUNET_asprintf (&s->name, "s%i", s->id); - return s; - } + { + GNUNET_asprintf(&s->name, "s%i", s->id); + return s; + } s->nfa_set = *nfa_states; @@ -1771,30 +1769,30 @@ dfa_state_create (struct REGEX_INTERNAL_Context *ctx, /* Create a name based on 'nfa_states' */ len = nfa_states->off * 14 + 4; - s->name = GNUNET_malloc (len); - strcat (s->name, "{"); + s->name = GNUNET_malloc(len); + strcat(s->name, "{"); pos = s->name + 1; for (i = 0; i < nfa_states->off; i++) - { - cstate = nfa_states->states[i]; - GNUNET_snprintf (pos, pos - s->name + len, "%i,", cstate->id); - pos += strlen (pos); - - /* Add a transition for each distinct label to NULL state */ - for (ctran = cstate->transitions_head; NULL != ctran; ctran = ctran->next) - if (NULL != ctran->label) - state_add_transition (ctx, s, ctran->label, NULL); - - /* If the nfa_states contain an accepting state, the new dfa state is also - * accepting. */ - if (cstate->accepting) - s->accepting = 1; - } + { + cstate = nfa_states->states[i]; + GNUNET_snprintf(pos, pos - s->name + len, "%i,", cstate->id); + pos += strlen(pos); + + /* Add a transition for each distinct label to NULL state */ + for (ctran = cstate->transitions_head; NULL != ctran; ctran = ctran->next) + if (NULL != ctran->label) + state_add_transition(ctx, s, ctran->label, NULL); + + /* If the nfa_states contain an accepting state, the new dfa state is also + * accepting. */ + if (cstate->accepting) + s->accepting = 1; + } pos[-1] = '}'; - s->name = GNUNET_realloc (s->name, strlen (s->name) + 1); + s->name = GNUNET_realloc(s->name, strlen(s->name) + 1); - memset (nfa_states, 0, sizeof (struct REGEX_INTERNAL_StateSet)); + memset(nfa_states, 0, sizeof(struct REGEX_INTERNAL_StateSet)); return s; } @@ -1813,7 +1811,7 @@ dfa_state_create (struct REGEX_INTERNAL_Context *ctx, * @return length of the substring comsumed from 'str' */ static unsigned int -dfa_move (struct REGEX_INTERNAL_State **s, const char *str) +dfa_move(struct REGEX_INTERNAL_State **s, const char *str) { struct REGEX_INTERNAL_Transition *t; struct REGEX_INTERNAL_State *new_s; @@ -1826,18 +1824,18 @@ dfa_move (struct REGEX_INTERNAL_State **s, const char *str) new_s = NULL; max_len = 0; for (t = (*s)->transitions_head; NULL != t; t = t->next) - { - len = strlen (t->label); - - if (0 == strncmp (t->label, str, len)) { - if (len >= max_len) - { - max_len = len; - new_s = t->to_state; - } + len = strlen(t->label); + + if (0 == strncmp(t->label, str, len)) + { + if (len >= max_len) + { + max_len = len; + new_s = t->to_state; + } + } } - } *s = new_s; return max_len; @@ -1854,9 +1852,9 @@ dfa_move (struct REGEX_INTERNAL_State **s, const char *str) * @param s state where the marked attribute will be set to #GNUNET_YES. */ static void -mark_states (void *cls, - const unsigned int count, - struct REGEX_INTERNAL_State *s) +mark_states(void *cls, + const unsigned int count, + struct REGEX_INTERNAL_State *s) { s->marked = GNUNET_YES; } @@ -1869,7 +1867,7 @@ mark_states (void *cls, * @param a DFA automaton */ static void -dfa_remove_unreachable_states (struct REGEX_INTERNAL_Automaton *a) +dfa_remove_unreachable_states(struct REGEX_INTERNAL_Automaton *a) { struct REGEX_INTERNAL_State *s; struct REGEX_INTERNAL_State *s_next; @@ -1879,20 +1877,20 @@ dfa_remove_unreachable_states (struct REGEX_INTERNAL_Automaton *a) s->marked = GNUNET_NO; /* 2. traverse dfa from start state and mark all visited states */ - REGEX_INTERNAL_automaton_traverse (a, - a->start, - NULL, - NULL, - &mark_states, - NULL); + REGEX_INTERNAL_automaton_traverse(a, + a->start, + NULL, + NULL, + &mark_states, + NULL); /* 3. delete all states that were not visited */ for (s = a->states_head; NULL != s; s = s_next) - { - s_next = s->next; - if (GNUNET_NO == s->marked) - automaton_remove_state (a, s); - } + { + s_next = s->next; + if (GNUNET_NO == s->marked) + automaton_remove_state(a, s); + } } @@ -1903,38 +1901,38 @@ dfa_remove_unreachable_states (struct REGEX_INTERNAL_Automaton *a) * @param a DFA automaton */ static void -dfa_remove_dead_states (struct REGEX_INTERNAL_Automaton *a) +dfa_remove_dead_states(struct REGEX_INTERNAL_Automaton *a) { struct REGEX_INTERNAL_State *s; struct REGEX_INTERNAL_State *s_next; struct REGEX_INTERNAL_Transition *t; int dead; - GNUNET_assert (DFA == a->type); + GNUNET_assert(DFA == a->type); for (s = a->states_head; NULL != s; s = s_next) - { - s_next = s->next; + { + s_next = s->next; - if (s->accepting) - continue; + if (s->accepting) + continue; - dead = 1; - for (t = s->transitions_head; NULL != t; t = t->next) - { - if (NULL != t->to_state && t->to_state != s) - { - dead = 0; - break; - } - } + dead = 1; + for (t = s->transitions_head; NULL != t; t = t->next) + { + if (NULL != t->to_state && t->to_state != s) + { + dead = 0; + break; + } + } - if (0 == dead) - continue; + if (0 == dead) + continue; - /* state s is dead, remove it */ - automaton_remove_state (a, s); - } + /* state s is dead, remove it */ + automaton_remove_state(a, s); + } } @@ -1946,8 +1944,8 @@ dfa_remove_dead_states (struct REGEX_INTERNAL_Automaton *a) * @return #GNUNET_OK on success */ static int -dfa_merge_nondistinguishable_states (struct REGEX_INTERNAL_Context *ctx, - struct REGEX_INTERNAL_Automaton *a) +dfa_merge_nondistinguishable_states(struct REGEX_INTERNAL_Context *ctx, + struct REGEX_INTERNAL_Automaton *a) { uint32_t *table; struct REGEX_INTERNAL_State *s1; @@ -1964,20 +1962,20 @@ dfa_merge_nondistinguishable_states (struct REGEX_INTERNAL_Context *ctx, unsigned long long idx1; if ((NULL == a) || (0 == a->state_count)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not merge nondistinguishable states, automaton was NULL.\n"); - return GNUNET_SYSERR; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not merge nondistinguishable states, automaton was NULL.\n"); + return GNUNET_SYSERR; + } state_cnt = a->state_count; - table = GNUNET_malloc_large ( - (sizeof (uint32_t) * state_cnt * state_cnt / 32) + sizeof (uint32_t)); + table = GNUNET_malloc_large( + (sizeof(uint32_t) * state_cnt * state_cnt / 32) + sizeof(uint32_t)); if (NULL == table) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "malloc"); - return GNUNET_SYSERR; - } + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "malloc"); + return GNUNET_SYSERR; + } for (i = 0, s1 = a->states_head; NULL != s1; s1 = s1->next) s1->marked = i++; @@ -1985,74 +1983,74 @@ dfa_merge_nondistinguishable_states (struct REGEX_INTERNAL_Context *ctx, /* Mark all pairs of accepting/!accepting states */ for (s1 = a->states_head; NULL != s1; s1 = s1->next) for (s2 = a->states_head; NULL != s2; s2 = s2->next) - if ((s1->accepting && ! s2->accepting) || - (! s1->accepting && s2->accepting)) - { - idx = (unsigned long long) s1->marked * state_cnt + s2->marked; - table[idx / 32] |= (1U << (idx % 32)); - } + if ((s1->accepting && !s2->accepting) || + (!s1->accepting && s2->accepting)) + { + idx = (unsigned long long)s1->marked * state_cnt + s2->marked; + table[idx / 32] |= (1U << (idx % 32)); + } /* Find all equal states */ change = 1; while (0 != change) - { - change = 0; - for (s1 = a->states_head; NULL != s1; s1 = s1->next) { - for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2->next) - { - idx = (unsigned long long) s1->marked * state_cnt + s2->marked; - if (0 != (table[idx / 32] & (1U << (idx % 32)))) - continue; - num_equal_edges = 0; - for (t1 = s1->transitions_head; NULL != t1; t1 = t1->next) + change = 0; + for (s1 = a->states_head; NULL != s1; s1 = s1->next) { - for (t2 = s2->transitions_head; NULL != t2; t2 = t2->next) - { - if (0 == strcmp (t1->label, t2->label)) + for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2->next) { - num_equal_edges++; - /* same edge, but targets definitively different, so we're different - as well */ - if (t1->to_state->marked > t2->to_state->marked) - idx1 = (unsigned long long) t1->to_state->marked * state_cnt + - t2->to_state->marked; - else - idx1 = (unsigned long long) t2->to_state->marked * state_cnt + - t1->to_state->marked; - if (0 != (table[idx1 / 32] & (1U << (idx1 % 32)))) - { - table[idx / 32] |= (1U << (idx % 32)); - change = 1; /* changed a marker, need to run again */ - } + idx = (unsigned long long)s1->marked * state_cnt + s2->marked; + if (0 != (table[idx / 32] & (1U << (idx % 32)))) + continue; + num_equal_edges = 0; + for (t1 = s1->transitions_head; NULL != t1; t1 = t1->next) + { + for (t2 = s2->transitions_head; NULL != t2; t2 = t2->next) + { + if (0 == strcmp(t1->label, t2->label)) + { + num_equal_edges++; + /* same edge, but targets definitively different, so we're different + as well */ + if (t1->to_state->marked > t2->to_state->marked) + idx1 = (unsigned long long)t1->to_state->marked * state_cnt + + t2->to_state->marked; + else + idx1 = (unsigned long long)t2->to_state->marked * state_cnt + + t1->to_state->marked; + if (0 != (table[idx1 / 32] & (1U << (idx1 % 32)))) + { + table[idx / 32] |= (1U << (idx % 32)); + change = 1; /* changed a marker, need to run again */ + } + } + } + } + if ((num_equal_edges != s1->transition_count) || + (num_equal_edges != s2->transition_count)) + { + /* Make sure ALL edges of possible equal states are the same */ + table[idx / 32] |= (1U << (idx % 32)); + change = 1; /* changed a marker, need to run again */ + } } - } } - if ((num_equal_edges != s1->transition_count) || - (num_equal_edges != s2->transition_count)) - { - /* Make sure ALL edges of possible equal states are the same */ - table[idx / 32] |= (1U << (idx % 32)); - change = 1; /* changed a marker, need to run again */ - } - } } - } /* Merge states that are equal */ for (s1 = a->states_head; NULL != s1; s1 = s1_next) - { - s1_next = s1->next; - for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2_next) { - s2_next = s2->next; - idx = (unsigned long long) s1->marked * state_cnt + s2->marked; - if (0 == (table[idx / 32] & (1U << (idx % 32)))) - automaton_merge_states (ctx, a, s1, s2); + s1_next = s1->next; + for (s2 = a->states_head; NULL != s2 && s1 != s2; s2 = s2_next) + { + s2_next = s2->next; + idx = (unsigned long long)s1->marked * state_cnt + s2->marked; + if (0 == (table[idx / 32] & (1U << (idx % 32)))) + automaton_merge_states(ctx, a, s1, s2); + } } - } - GNUNET_free (table); + GNUNET_free(table); return GNUNET_OK; } @@ -2066,22 +2064,22 @@ dfa_merge_nondistinguishable_states (struct REGEX_INTERNAL_Context *ctx, * @return GNUNET_OK on success */ static int -dfa_minimize (struct REGEX_INTERNAL_Context *ctx, - struct REGEX_INTERNAL_Automaton *a) +dfa_minimize(struct REGEX_INTERNAL_Context *ctx, + struct REGEX_INTERNAL_Automaton *a) { if (NULL == a) return GNUNET_SYSERR; - GNUNET_assert (DFA == a->type); + GNUNET_assert(DFA == a->type); /* 1. remove unreachable states */ - dfa_remove_unreachable_states (a); + dfa_remove_unreachable_states(a); /* 2. remove dead states */ - dfa_remove_dead_states (a); + dfa_remove_dead_states(a); /* 3. Merge nondistinguishable states */ - if (GNUNET_OK != dfa_merge_nondistinguishable_states (ctx, a)) + if (GNUNET_OK != dfa_merge_nondistinguishable_states(ctx, a)) return GNUNET_SYSERR; return GNUNET_OK; } @@ -2090,8 +2088,7 @@ dfa_minimize (struct REGEX_INTERNAL_Context *ctx, /** * Context for adding strided transitions to a DFA. */ -struct REGEX_INTERNAL_Strided_Context -{ +struct REGEX_INTERNAL_Strided_Context { /** * Length of the strides. */ @@ -2121,50 +2118,50 @@ struct REGEX_INTERNAL_Strided_Context * @param s current state in the depth-first traversal */ static void -dfa_add_multi_strides_helper (void *cls, - const unsigned int depth, - char *label, - struct REGEX_INTERNAL_State *start, - struct REGEX_INTERNAL_State *s) +dfa_add_multi_strides_helper(void *cls, + const unsigned int depth, + char *label, + struct REGEX_INTERNAL_State *start, + struct REGEX_INTERNAL_State *s) { struct REGEX_INTERNAL_Strided_Context *ctx = cls; struct REGEX_INTERNAL_Transition *t; char *new_label; if (depth == ctx->stride) - { - t = GNUNET_new (struct REGEX_INTERNAL_Transition); - t->label = GNUNET_strdup (label); - t->to_state = s; - t->from_state = start; - GNUNET_CONTAINER_DLL_insert (ctx->transitions_head, - ctx->transitions_tail, - t); - } + { + t = GNUNET_new(struct REGEX_INTERNAL_Transition); + t->label = GNUNET_strdup(label); + t->to_state = s; + t->from_state = start; + GNUNET_CONTAINER_DLL_insert(ctx->transitions_head, + ctx->transitions_tail, + t); + } else - { - for (t = s->transitions_head; NULL != t; t = t->next) { - /* Do not consider self-loops, because it end's up in too many - * transitions */ - if (t->to_state == t->from_state) - continue; + for (t = s->transitions_head; NULL != t; t = t->next) + { + /* Do not consider self-loops, because it end's up in too many + * transitions */ + if (t->to_state == t->from_state) + continue; - if (NULL != label) - { - GNUNET_asprintf (&new_label, "%s%s", label, t->label); - } - else - new_label = GNUNET_strdup (t->label); + if (NULL != label) + { + GNUNET_asprintf(&new_label, "%s%s", label, t->label); + } + else + new_label = GNUNET_strdup(t->label); - dfa_add_multi_strides_helper (cls, - (depth + 1), - new_label, - start, - t->to_state); + dfa_add_multi_strides_helper(cls, + (depth + 1), + new_label, + start, + t->to_state); + } } - } - GNUNET_free_non_null (label); + GNUNET_free_non_null(label); } @@ -2177,11 +2174,11 @@ dfa_add_multi_strides_helper (void *cls, * @param s current state. */ static void -dfa_add_multi_strides (void *cls, - const unsigned int count, - struct REGEX_INTERNAL_State *s) +dfa_add_multi_strides(void *cls, + const unsigned int count, + struct REGEX_INTERNAL_State *s) { - dfa_add_multi_strides_helper (cls, 0, NULL, s, s); + dfa_add_multi_strides_helper(cls, 0, NULL, s, s); } @@ -2193,11 +2190,11 @@ dfa_add_multi_strides (void *cls, * @param stride_len length of the strides. */ void -REGEX_INTERNAL_dfa_add_multi_strides (struct REGEX_INTERNAL_Context *regex_ctx, - struct REGEX_INTERNAL_Automaton *dfa, - const unsigned int stride_len) +REGEX_INTERNAL_dfa_add_multi_strides(struct REGEX_INTERNAL_Context *regex_ctx, + struct REGEX_INTERNAL_Automaton *dfa, + const unsigned int stride_len) { - struct REGEX_INTERNAL_Strided_Context ctx = {stride_len, NULL, NULL}; + struct REGEX_INTERNAL_Strided_Context ctx = { stride_len, NULL, NULL }; struct REGEX_INTERNAL_Transition *t; struct REGEX_INTERNAL_Transition *t_next; @@ -2205,22 +2202,22 @@ REGEX_INTERNAL_dfa_add_multi_strides (struct REGEX_INTERNAL_Context *regex_ctx, return; /* Compute the new transitions of given stride_len */ - REGEX_INTERNAL_automaton_traverse (dfa, - dfa->start, - NULL, - NULL, - &dfa_add_multi_strides, - &ctx); + REGEX_INTERNAL_automaton_traverse(dfa, + dfa->start, + NULL, + NULL, + &dfa_add_multi_strides, + &ctx); /* Add all the new transitions to the automaton. */ for (t = ctx.transitions_head; NULL != t; t = t_next) - { - t_next = t->next; - state_add_transition (regex_ctx, t->from_state, t->label, t->to_state); - GNUNET_CONTAINER_DLL_remove (ctx.transitions_head, ctx.transitions_tail, t); - GNUNET_free_non_null (t->label); - GNUNET_free (t); - } + { + t_next = t->next; + state_add_transition(regex_ctx, t->from_state, t->label, t->to_state); + GNUNET_CONTAINER_DLL_remove(ctx.transitions_head, ctx.transitions_tail, t); + GNUNET_free_non_null(t->label); + GNUNET_free(t); + } /* Mark this automaton as multistrided */ dfa->is_multistrided = GNUNET_YES; @@ -2240,13 +2237,13 @@ REGEX_INTERNAL_dfa_add_multi_strides (struct REGEX_INTERNAL_Context *regex_ctx, * @param transitions_tail transitions DLL. */ void -dfa_compress_paths_helper (struct REGEX_INTERNAL_Automaton *dfa, - struct REGEX_INTERNAL_State *start, - struct REGEX_INTERNAL_State *cur, - char *label, - unsigned int max_len, - struct REGEX_INTERNAL_Transition **transitions_head, - struct REGEX_INTERNAL_Transition **transitions_tail) +dfa_compress_paths_helper(struct REGEX_INTERNAL_Automaton *dfa, + struct REGEX_INTERNAL_State *start, + struct REGEX_INTERNAL_State *cur, + char *label, + unsigned int max_len, + struct REGEX_INTERNAL_Transition **transitions_head, + struct REGEX_INTERNAL_Transition **transitions_tail) { struct REGEX_INTERNAL_Transition *t; char *new_label; @@ -2255,27 +2252,27 @@ dfa_compress_paths_helper (struct REGEX_INTERNAL_Automaton *dfa, if (NULL != label && ((cur->incoming_transition_count > 1 || GNUNET_YES == cur->accepting || GNUNET_YES == cur->marked) || - (start != dfa->start && max_len > 0 && max_len == strlen (label)) || - (start == dfa->start && GNUNET_REGEX_INITIAL_BYTES == strlen (label)))) - { - t = GNUNET_new (struct REGEX_INTERNAL_Transition); - t->label = GNUNET_strdup (label); - t->to_state = cur; - t->from_state = start; - GNUNET_CONTAINER_DLL_insert (*transitions_head, *transitions_tail, t); - - if (GNUNET_NO == cur->marked) - { - dfa_compress_paths_helper (dfa, - cur, - cur, - NULL, - max_len, - transitions_head, - transitions_tail); + (start != dfa->start && max_len > 0 && max_len == strlen(label)) || + (start == dfa->start && GNUNET_REGEX_INITIAL_BYTES == strlen(label)))) + { + t = GNUNET_new(struct REGEX_INTERNAL_Transition); + t->label = GNUNET_strdup(label); + t->to_state = cur; + t->from_state = start; + GNUNET_CONTAINER_DLL_insert(*transitions_head, *transitions_tail, t); + + if (GNUNET_NO == cur->marked) + { + dfa_compress_paths_helper(dfa, + cur, + cur, + NULL, + max_len, + transitions_head, + transitions_tail); + } + return; } - return; - } else if (cur != start) cur->contained = GNUNET_YES; @@ -2286,24 +2283,24 @@ dfa_compress_paths_helper (struct REGEX_INTERNAL_Automaton *dfa, for (t = cur->transitions_head; NULL != t; t = t->next) - { - if (NULL != label) - GNUNET_asprintf (&new_label, "%s%s", label, t->label); - else - new_label = GNUNET_strdup (t->label); - - if (t->to_state != cur) { - dfa_compress_paths_helper (dfa, - start, - t->to_state, - new_label, - max_len, - transitions_head, - transitions_tail); + if (NULL != label) + GNUNET_asprintf(&new_label, "%s%s", label, t->label); + else + new_label = GNUNET_strdup(t->label); + + if (t->to_state != cur) + { + dfa_compress_paths_helper(dfa, + start, + t->to_state, + new_label, + max_len, + transitions_head, + transitions_tail); + } + GNUNET_free(new_label); } - GNUNET_free (new_label); - } } @@ -2316,9 +2313,9 @@ dfa_compress_paths_helper (struct REGEX_INTERNAL_Automaton *dfa, * @param max_len maximal length of the compressed paths. */ static void -dfa_compress_paths (struct REGEX_INTERNAL_Context *regex_ctx, - struct REGEX_INTERNAL_Automaton *dfa, - unsigned int max_len) +dfa_compress_paths(struct REGEX_INTERNAL_Context *regex_ctx, + struct REGEX_INTERNAL_Automaton *dfa, + unsigned int max_len) { struct REGEX_INTERNAL_State *s; struct REGEX_INTERNAL_State *s_next; @@ -2332,47 +2329,47 @@ dfa_compress_paths (struct REGEX_INTERNAL_Context *regex_ctx, /* Count the incoming transitions on each state. */ for (s = dfa->states_head; NULL != s; s = s->next) - { - for (t = s->transitions_head; NULL != t; t = t->next) { - if (NULL != t->to_state) - t->to_state->incoming_transition_count++; + for (t = s->transitions_head; NULL != t; t = t->next) + { + if (NULL != t->to_state) + t->to_state->incoming_transition_count++; + } } - } /* Unmark all states. */ for (s = dfa->states_head; NULL != s; s = s->next) - { - s->marked = GNUNET_NO; - s->contained = GNUNET_NO; - } + { + s->marked = GNUNET_NO; + s->contained = GNUNET_NO; + } /* Add strides and mark states that can be deleted. */ - dfa_compress_paths_helper (dfa, - dfa->start, - dfa->start, - NULL, - max_len, - &transitions_head, - &transitions_tail); + dfa_compress_paths_helper(dfa, + dfa->start, + dfa->start, + NULL, + max_len, + &transitions_head, + &transitions_tail); /* Add all the new transitions to the automaton. */ for (t = transitions_head; NULL != t; t = t_next) - { - t_next = t->next; - state_add_transition (regex_ctx, t->from_state, t->label, t->to_state); - GNUNET_CONTAINER_DLL_remove (transitions_head, transitions_tail, t); - GNUNET_free_non_null (t->label); - GNUNET_free (t); - } + { + t_next = t->next; + state_add_transition(regex_ctx, t->from_state, t->label, t->to_state); + GNUNET_CONTAINER_DLL_remove(transitions_head, transitions_tail, t); + GNUNET_free_non_null(t->label); + GNUNET_free(t); + } /* Remove marked states (including their incoming and outgoing transitions). */ for (s = dfa->states_head; NULL != s; s = s_next) - { - s_next = s->next; - if (GNUNET_YES == s->contained) - automaton_remove_state (dfa, s); - } + { + s_next = s->next; + if (GNUNET_YES == s->contained) + automaton_remove_state(dfa, s); + } } @@ -2386,12 +2383,12 @@ dfa_compress_paths (struct REGEX_INTERNAL_Context *regex_ctx, * @return new NFA fragment */ static struct REGEX_INTERNAL_Automaton * -nfa_fragment_create (struct REGEX_INTERNAL_State *start, - struct REGEX_INTERNAL_State *end) +nfa_fragment_create(struct REGEX_INTERNAL_State *start, + struct REGEX_INTERNAL_State *end) { struct REGEX_INTERNAL_Automaton *n; - n = GNUNET_new (struct REGEX_INTERNAL_Automaton); + n = GNUNET_new(struct REGEX_INTERNAL_Automaton); n->type = NFA; n->start = NULL; @@ -2401,8 +2398,8 @@ nfa_fragment_create (struct REGEX_INTERNAL_State *start, if (NULL == start || NULL == end) return n; - automaton_add_state (n, end); - automaton_add_state (n, start); + automaton_add_state(n, end); + automaton_add_state(n, start); n->state_count = 2; @@ -2421,30 +2418,30 @@ nfa_fragment_create (struct REGEX_INTERNAL_State *start, * @param states_tail tail of the DLL of states */ static void -nfa_add_states (struct REGEX_INTERNAL_Automaton *n, - struct REGEX_INTERNAL_State *states_head, - struct REGEX_INTERNAL_State *states_tail) +nfa_add_states(struct REGEX_INTERNAL_Automaton *n, + struct REGEX_INTERNAL_State *states_head, + struct REGEX_INTERNAL_State *states_tail) { struct REGEX_INTERNAL_State *s; if (NULL == n || NULL == states_head) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not add states\n"); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not add states\n"); + return; + } if (NULL == n->states_head) - { - n->states_head = states_head; - n->states_tail = states_tail; - return; - } + { + n->states_head = states_head; + n->states_tail = states_tail; + return; + } if (NULL != states_head) - { - n->states_tail->next = states_head; - n->states_tail = states_tail; - } + { + n->states_tail->next = states_head; + n->states_tail = states_tail; + } for (s = states_head; NULL != s; s = s->next) n->state_count++; @@ -2460,11 +2457,11 @@ nfa_add_states (struct REGEX_INTERNAL_Automaton *n, * @return new NFA state */ static struct REGEX_INTERNAL_State * -nfa_state_create (struct REGEX_INTERNAL_Context *ctx, int accepting) +nfa_state_create(struct REGEX_INTERNAL_Context *ctx, int accepting) { struct REGEX_INTERNAL_State *s; - s = GNUNET_new (struct REGEX_INTERNAL_State); + s = GNUNET_new(struct REGEX_INTERNAL_State); s->id = ctx->state_id++; s->accepting = accepting; s->marked = GNUNET_NO; @@ -2473,7 +2470,7 @@ nfa_state_create (struct REGEX_INTERNAL_Context *ctx, int accepting) s->lowlink = -1; s->scc_id = 0; s->name = NULL; - GNUNET_asprintf (&s->name, "s%i", s->id); + GNUNET_asprintf(&s->name, "s%i", s->id); return s; } @@ -2489,10 +2486,10 @@ nfa_state_create (struct REGEX_INTERNAL_Context *ctx, int accepting) * pass NULL for epsilon transition */ static void -nfa_closure_set_create (struct REGEX_INTERNAL_StateSet *ret, - struct REGEX_INTERNAL_Automaton *nfa, - struct REGEX_INTERNAL_StateSet *states, - const char *label) +nfa_closure_set_create(struct REGEX_INTERNAL_StateSet *ret, + struct REGEX_INTERNAL_Automaton *nfa, + struct REGEX_INTERNAL_StateSet *states, + const char *label) { struct REGEX_INTERNAL_State *s; unsigned int i; @@ -2501,58 +2498,58 @@ nfa_closure_set_create (struct REGEX_INTERNAL_StateSet *ret, struct REGEX_INTERNAL_State *currentstate; struct REGEX_INTERNAL_Transition *ctran; - memset (ret, 0, sizeof (struct REGEX_INTERNAL_StateSet)); + memset(ret, 0, sizeof(struct REGEX_INTERNAL_StateSet)); if (NULL == states) return; for (i = 0; i < states->off; i++) - { - s = states->states[i]; - - /* Add start state to closure only for epsilon closure */ - if (NULL == label) - state_set_append (ret, s); - - /* initialize work stack */ - cls_stack.head = NULL; - cls_stack.tail = NULL; - GNUNET_CONTAINER_MDLL_insert (ST, cls_stack.head, cls_stack.tail, s); - cls_stack.len = 1; - - while (NULL != (currentstate = cls_stack.tail)) - { - GNUNET_CONTAINER_MDLL_remove (ST, - cls_stack.head, - cls_stack.tail, - currentstate); - cls_stack.len--; - for (ctran = currentstate->transitions_head; NULL != ctran; - ctran = ctran->next) - { - if (NULL == (clsstate = ctran->to_state)) - continue; - if (0 != clsstate->contained) - continue; - if (0 != nullstrcmp (label, ctran->label)) - continue; - state_set_append (ret, clsstate); - GNUNET_CONTAINER_MDLL_insert_tail (ST, - cls_stack.head, - cls_stack.tail, - clsstate); - cls_stack.len++; - clsstate->contained = 1; - } + { + s = states->states[i]; + + /* Add start state to closure only for epsilon closure */ + if (NULL == label) + state_set_append(ret, s); + + /* initialize work stack */ + cls_stack.head = NULL; + cls_stack.tail = NULL; + GNUNET_CONTAINER_MDLL_insert(ST, cls_stack.head, cls_stack.tail, s); + cls_stack.len = 1; + + while (NULL != (currentstate = cls_stack.tail)) + { + GNUNET_CONTAINER_MDLL_remove(ST, + cls_stack.head, + cls_stack.tail, + currentstate); + cls_stack.len--; + for (ctran = currentstate->transitions_head; NULL != ctran; + ctran = ctran->next) + { + if (NULL == (clsstate = ctran->to_state)) + continue; + if (0 != clsstate->contained) + continue; + if (0 != nullstrcmp(label, ctran->label)) + continue; + state_set_append(ret, clsstate); + GNUNET_CONTAINER_MDLL_insert_tail(ST, + cls_stack.head, + cls_stack.tail, + clsstate); + cls_stack.len++; + clsstate->contained = 1; + } + } } - } for (i = 0; i < ret->off; i++) ret->states[i]->contained = 0; if (ret->off > 1) - qsort (ret->states, - ret->off, - sizeof (struct REGEX_INTERNAL_State *), - &state_compare); + qsort(ret->states, + ret->off, + sizeof(struct REGEX_INTERNAL_State *), + &state_compare); } @@ -2562,33 +2559,33 @@ nfa_closure_set_create (struct REGEX_INTERNAL_StateSet *ret, * @param ctx context */ static void -nfa_add_concatenation (struct REGEX_INTERNAL_Context *ctx) +nfa_add_concatenation(struct REGEX_INTERNAL_Context *ctx) { struct REGEX_INTERNAL_Automaton *a; struct REGEX_INTERNAL_Automaton *b; struct REGEX_INTERNAL_Automaton *new_nfa; b = ctx->stack_tail; - GNUNET_assert (NULL != b); - GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b); + GNUNET_assert(NULL != b); + GNUNET_CONTAINER_DLL_remove(ctx->stack_head, ctx->stack_tail, b); a = ctx->stack_tail; - GNUNET_assert (NULL != a); - GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a); + GNUNET_assert(NULL != a); + GNUNET_CONTAINER_DLL_remove(ctx->stack_head, ctx->stack_tail, a); - state_add_transition (ctx, a->end, NULL, b->start); + state_add_transition(ctx, a->end, NULL, b->start); a->end->accepting = 0; b->end->accepting = 1; - new_nfa = nfa_fragment_create (NULL, NULL); - nfa_add_states (new_nfa, a->states_head, a->states_tail); - nfa_add_states (new_nfa, b->states_head, b->states_tail); + new_nfa = nfa_fragment_create(NULL, NULL); + nfa_add_states(new_nfa, a->states_head, a->states_tail); + nfa_add_states(new_nfa, b->states_head, b->states_tail); new_nfa->start = a->start; new_nfa->end = b->end; new_nfa->state_count += a->state_count + b->state_count; - automaton_fragment_clear (a); - automaton_fragment_clear (b); + automaton_fragment_clear(a); + automaton_fragment_clear(b); - GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa); + GNUNET_CONTAINER_DLL_insert_tail(ctx->stack_head, ctx->stack_tail, new_nfa); } @@ -2598,7 +2595,7 @@ nfa_add_concatenation (struct REGEX_INTERNAL_Context *ctx) * @param ctx context */ static void -nfa_add_star_op (struct REGEX_INTERNAL_Context *ctx) +nfa_add_star_op(struct REGEX_INTERNAL_Context *ctx) { struct REGEX_INTERNAL_Automaton *a; struct REGEX_INTERNAL_Automaton *new_nfa; @@ -2608,31 +2605,31 @@ nfa_add_star_op (struct REGEX_INTERNAL_Context *ctx) a = ctx->stack_tail; if (NULL == a) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_ERROR, - "nfa_add_star_op failed, because there was no element on the stack"); - return; - } + { + GNUNET_log( + GNUNET_ERROR_TYPE_ERROR, + "nfa_add_star_op failed, because there was no element on the stack"); + return; + } - GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a); + GNUNET_CONTAINER_DLL_remove(ctx->stack_head, ctx->stack_tail, a); - start = nfa_state_create (ctx, 0); - end = nfa_state_create (ctx, 1); + start = nfa_state_create(ctx, 0); + end = nfa_state_create(ctx, 1); - state_add_transition (ctx, start, NULL, a->start); - state_add_transition (ctx, start, NULL, end); - state_add_transition (ctx, a->end, NULL, a->start); - state_add_transition (ctx, a->end, NULL, end); + state_add_transition(ctx, start, NULL, a->start); + state_add_transition(ctx, start, NULL, end); + state_add_transition(ctx, a->end, NULL, a->start); + state_add_transition(ctx, a->end, NULL, end); a->end->accepting = 0; end->accepting = 1; - new_nfa = nfa_fragment_create (start, end); - nfa_add_states (new_nfa, a->states_head, a->states_tail); - automaton_fragment_clear (a); + new_nfa = nfa_fragment_create(start, end); + nfa_add_states(new_nfa, a->states_head, a->states_tail); + automaton_fragment_clear(a); - GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa); + GNUNET_CONTAINER_DLL_insert_tail(ctx->stack_head, ctx->stack_tail, new_nfa); } @@ -2642,25 +2639,25 @@ nfa_add_star_op (struct REGEX_INTERNAL_Context *ctx) * @param ctx context */ static void -nfa_add_plus_op (struct REGEX_INTERNAL_Context *ctx) +nfa_add_plus_op(struct REGEX_INTERNAL_Context *ctx) { struct REGEX_INTERNAL_Automaton *a; a = ctx->stack_tail; if (NULL == a) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_ERROR, - "nfa_add_plus_op failed, because there was no element on the stack"); - return; - } + { + GNUNET_log( + GNUNET_ERROR_TYPE_ERROR, + "nfa_add_plus_op failed, because there was no element on the stack"); + return; + } - GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a); + GNUNET_CONTAINER_DLL_remove(ctx->stack_head, ctx->stack_tail, a); - state_add_transition (ctx, a->end, NULL, a->start); + state_add_transition(ctx, a->end, NULL, a->start); - GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, a); + GNUNET_CONTAINER_DLL_insert_tail(ctx->stack_head, ctx->stack_tail, a); } @@ -2670,7 +2667,7 @@ nfa_add_plus_op (struct REGEX_INTERNAL_Context *ctx) * @param ctx context */ static void -nfa_add_question_op (struct REGEX_INTERNAL_Context *ctx) +nfa_add_question_op(struct REGEX_INTERNAL_Context *ctx) { struct REGEX_INTERNAL_Automaton *a; struct REGEX_INTERNAL_Automaton *new_nfa; @@ -2679,28 +2676,28 @@ nfa_add_question_op (struct REGEX_INTERNAL_Context *ctx) a = ctx->stack_tail; if (NULL == a) - { - GNUNET_log ( - GNUNET_ERROR_TYPE_ERROR, - "nfa_add_question_op failed, because there was no element on the stack"); - return; - } + { + GNUNET_log( + GNUNET_ERROR_TYPE_ERROR, + "nfa_add_question_op failed, because there was no element on the stack"); + return; + } - GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a); + GNUNET_CONTAINER_DLL_remove(ctx->stack_head, ctx->stack_tail, a); - start = nfa_state_create (ctx, 0); - end = nfa_state_create (ctx, 1); + start = nfa_state_create(ctx, 0); + end = nfa_state_create(ctx, 1); - state_add_transition (ctx, start, NULL, a->start); - state_add_transition (ctx, start, NULL, end); - state_add_transition (ctx, a->end, NULL, end); + state_add_transition(ctx, start, NULL, a->start); + state_add_transition(ctx, start, NULL, end); + state_add_transition(ctx, a->end, NULL, end); a->end->accepting = 0; - new_nfa = nfa_fragment_create (start, end); - nfa_add_states (new_nfa, a->states_head, a->states_tail); - GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa); - automaton_fragment_clear (a); + new_nfa = nfa_fragment_create(start, end); + nfa_add_states(new_nfa, a->states_head, a->states_tail); + GNUNET_CONTAINER_DLL_insert_tail(ctx->stack_head, ctx->stack_tail, new_nfa); + automaton_fragment_clear(a); } @@ -2711,7 +2708,7 @@ nfa_add_question_op (struct REGEX_INTERNAL_Context *ctx) * @param ctx context */ static void -nfa_add_alternation (struct REGEX_INTERNAL_Context *ctx) +nfa_add_alternation(struct REGEX_INTERNAL_Context *ctx) { struct REGEX_INTERNAL_Automaton *a; struct REGEX_INTERNAL_Automaton *b; @@ -2720,31 +2717,31 @@ nfa_add_alternation (struct REGEX_INTERNAL_Context *ctx) struct REGEX_INTERNAL_State *end; b = ctx->stack_tail; - GNUNET_assert (NULL != b); - GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, b); + GNUNET_assert(NULL != b); + GNUNET_CONTAINER_DLL_remove(ctx->stack_head, ctx->stack_tail, b); a = ctx->stack_tail; - GNUNET_assert (NULL != a); - GNUNET_CONTAINER_DLL_remove (ctx->stack_head, ctx->stack_tail, a); + GNUNET_assert(NULL != a); + GNUNET_CONTAINER_DLL_remove(ctx->stack_head, ctx->stack_tail, a); - start = nfa_state_create (ctx, 0); - end = nfa_state_create (ctx, 1); - state_add_transition (ctx, start, NULL, a->start); - state_add_transition (ctx, start, NULL, b->start); + start = nfa_state_create(ctx, 0); + end = nfa_state_create(ctx, 1); + state_add_transition(ctx, start, NULL, a->start); + state_add_transition(ctx, start, NULL, b->start); - state_add_transition (ctx, a->end, NULL, end); - state_add_transition (ctx, b->end, NULL, end); + state_add_transition(ctx, a->end, NULL, end); + state_add_transition(ctx, b->end, NULL, end); a->end->accepting = 0; b->end->accepting = 0; end->accepting = 1; - new_nfa = nfa_fragment_create (start, end); - nfa_add_states (new_nfa, a->states_head, a->states_tail); - nfa_add_states (new_nfa, b->states_head, b->states_tail); - automaton_fragment_clear (a); - automaton_fragment_clear (b); + new_nfa = nfa_fragment_create(start, end); + nfa_add_states(new_nfa, a->states_head, a->states_tail); + nfa_add_states(new_nfa, b->states_head, b->states_tail); + automaton_fragment_clear(a); + automaton_fragment_clear(b); - GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, new_nfa); + GNUNET_CONTAINER_DLL_insert_tail(ctx->stack_head, ctx->stack_tail, new_nfa); } @@ -2755,20 +2752,20 @@ nfa_add_alternation (struct REGEX_INTERNAL_Context *ctx) * @param label label for nfa transition */ static void -nfa_add_label (struct REGEX_INTERNAL_Context *ctx, const char *label) +nfa_add_label(struct REGEX_INTERNAL_Context *ctx, const char *label) { struct REGEX_INTERNAL_Automaton *n; struct REGEX_INTERNAL_State *start; struct REGEX_INTERNAL_State *end; - GNUNET_assert (NULL != ctx); + GNUNET_assert(NULL != ctx); - start = nfa_state_create (ctx, 0); - end = nfa_state_create (ctx, 1); - state_add_transition (ctx, start, label, end); - n = nfa_fragment_create (start, end); - GNUNET_assert (NULL != n); - GNUNET_CONTAINER_DLL_insert_tail (ctx->stack_head, ctx->stack_tail, n); + start = nfa_state_create(ctx, 0); + end = nfa_state_create(ctx, 1); + state_add_transition(ctx, start, label, end); + n = nfa_fragment_create(start, end); + GNUNET_assert(NULL != n); + GNUNET_CONTAINER_DLL_insert_tail(ctx->stack_head, ctx->stack_tail, n); } @@ -2778,13 +2775,13 @@ nfa_add_label (struct REGEX_INTERNAL_Context *ctx, const char *label) * @param ctx context */ static void -REGEX_INTERNAL_context_init (struct REGEX_INTERNAL_Context *ctx) +REGEX_INTERNAL_context_init(struct REGEX_INTERNAL_Context *ctx) { if (NULL == ctx) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Context was NULL!"); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Context was NULL!"); + return; + } ctx->state_id = 0; ctx->transition_id = 0; ctx->stack_head = NULL; @@ -2801,7 +2798,7 @@ REGEX_INTERNAL_context_init (struct REGEX_INTERNAL_Context *ctx) * @return NFA, needs to be freed using REGEX_INTERNAL_destroy_automaton */ struct REGEX_INTERNAL_Automaton * -REGEX_INTERNAL_construct_nfa (const char *regex, const size_t len) +REGEX_INTERNAL_construct_nfa(const char *regex, const size_t len) { struct REGEX_INTERNAL_Context ctx; struct REGEX_INTERNAL_Automaton *nfa; @@ -2813,20 +2810,20 @@ REGEX_INTERNAL_construct_nfa (const char *regex, const size_t len) unsigned int atomcount; unsigned int poff; unsigned int psize; - struct - { + + struct { int altcount; int atomcount; } * p; - if (NULL == regex || 0 == strlen (regex) || 0 == len) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not parse regex. Empty regex string provided.\n"); + if (NULL == regex || 0 == strlen(regex) || 0 == len) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not parse regex. Empty regex string provided.\n"); - return NULL; - } - REGEX_INTERNAL_context_init (&ctx); + return NULL; + } + REGEX_INTERNAL_context_init(&ctx); regexp = regex; curlabel[1] = '\0'; @@ -2838,123 +2835,129 @@ REGEX_INTERNAL_construct_nfa (const char *regex, const size_t len) psize = 0; for (count = 0; count < len && *regexp; count++, regexp++) - { - switch (*regexp) { - case '(': - if (atomcount > 1) - { - --atomcount; - nfa_add_concatenation (&ctx); - } - if (poff == psize) - GNUNET_array_grow (p, psize, psize * 2 + 4); /* FIXME why *2 +4? */ - p[poff].altcount = altcount; - p[poff].atomcount = atomcount; - poff++; - altcount = 0; - atomcount = 0; - break; - case '|': - if (0 == atomcount) - { - error_msg = "Cannot append '|' to nothing"; - goto error; - } - while (--atomcount > 0) - nfa_add_concatenation (&ctx); - altcount++; - break; - case ')': - if (0 == poff) - { - error_msg = "Missing opening '('"; - goto error; - } - if (0 == atomcount) - { - /* Ignore this: "()" */ - poff--; - altcount = p[poff].altcount; - atomcount = p[poff].atomcount; - break; - } - while (--atomcount > 0) - nfa_add_concatenation (&ctx); - for (; altcount > 0; altcount--) - nfa_add_alternation (&ctx); - poff--; - altcount = p[poff].altcount; - atomcount = p[poff].atomcount; - atomcount++; - break; - case '*': - if (atomcount == 0) - { - error_msg = "Cannot append '*' to nothing"; - goto error; - } - nfa_add_star_op (&ctx); - break; - case '+': - if (atomcount == 0) - { - error_msg = "Cannot append '+' to nothing"; - goto error; - } - nfa_add_plus_op (&ctx); - break; - case '?': - if (atomcount == 0) - { - error_msg = "Cannot append '?' to nothing"; - goto error; - } - nfa_add_question_op (&ctx); - break; - default: - if (atomcount > 1) - { - --atomcount; - nfa_add_concatenation (&ctx); - } - curlabel[0] = *regexp; - nfa_add_label (&ctx, curlabel); - atomcount++; - break; + switch (*regexp) + { + case '(': + if (atomcount > 1) + { + --atomcount; + nfa_add_concatenation(&ctx); + } + if (poff == psize) + GNUNET_array_grow(p, psize, psize * 2 + 4); /* FIXME why *2 +4? */ + p[poff].altcount = altcount; + p[poff].atomcount = atomcount; + poff++; + altcount = 0; + atomcount = 0; + break; + + case '|': + if (0 == atomcount) + { + error_msg = "Cannot append '|' to nothing"; + goto error; + } + while (--atomcount > 0) + nfa_add_concatenation(&ctx); + altcount++; + break; + + case ')': + if (0 == poff) + { + error_msg = "Missing opening '('"; + goto error; + } + if (0 == atomcount) + { + /* Ignore this: "()" */ + poff--; + altcount = p[poff].altcount; + atomcount = p[poff].atomcount; + break; + } + while (--atomcount > 0) + nfa_add_concatenation(&ctx); + for (; altcount > 0; altcount--) + nfa_add_alternation(&ctx); + poff--; + altcount = p[poff].altcount; + atomcount = p[poff].atomcount; + atomcount++; + break; + + case '*': + if (atomcount == 0) + { + error_msg = "Cannot append '*' to nothing"; + goto error; + } + nfa_add_star_op(&ctx); + break; + + case '+': + if (atomcount == 0) + { + error_msg = "Cannot append '+' to nothing"; + goto error; + } + nfa_add_plus_op(&ctx); + break; + + case '?': + if (atomcount == 0) + { + error_msg = "Cannot append '?' to nothing"; + goto error; + } + nfa_add_question_op(&ctx); + break; + + default: + if (atomcount > 1) + { + --atomcount; + nfa_add_concatenation(&ctx); + } + curlabel[0] = *regexp; + nfa_add_label(&ctx, curlabel); + atomcount++; + break; + } } - } if (0 != poff) - { - error_msg = "Unbalanced parenthesis"; - goto error; - } + { + error_msg = "Unbalanced parenthesis"; + goto error; + } while (--atomcount > 0) - nfa_add_concatenation (&ctx); + nfa_add_concatenation(&ctx); for (; altcount > 0; altcount--) - nfa_add_alternation (&ctx); + nfa_add_alternation(&ctx); - GNUNET_array_grow (p, psize, 0); + GNUNET_array_grow(p, psize, 0); nfa = ctx.stack_tail; - GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa); + GNUNET_CONTAINER_DLL_remove(ctx.stack_head, ctx.stack_tail, nfa); if (NULL != ctx.stack_head) - { - error_msg = "Creating the NFA failed. NFA stack was not empty!"; - goto error; - } + { + error_msg = "Creating the NFA failed. NFA stack was not empty!"; + goto error; + } /* Remember the regex that was used to generate this NFA */ - nfa->regex = GNUNET_strdup (regex); + nfa->regex = GNUNET_strdup(regex); /* create depth-first numbering of the states for pretty printing */ - REGEX_INTERNAL_automaton_traverse (nfa, - NULL, - NULL, - NULL, - &number_states, - NULL); + REGEX_INTERNAL_automaton_traverse(nfa, + NULL, + NULL, + NULL, + &number_states, + NULL); /* No multistriding added so far */ nfa->is_multistrided = GNUNET_NO; @@ -2962,17 +2965,17 @@ REGEX_INTERNAL_construct_nfa (const char *regex, const size_t len) return nfa; error: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not parse regex: `%s'\n", regex); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not parse regex: `%s'\n", regex); if (NULL != error_msg) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "%s\n", error_msg); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "%s\n", error_msg); - GNUNET_free_non_null (p); + GNUNET_free_non_null(p); while (NULL != (nfa = ctx.stack_head)) - { - GNUNET_CONTAINER_DLL_remove (ctx.stack_head, ctx.stack_tail, nfa); - REGEX_INTERNAL_automaton_destroy (nfa); - } + { + GNUNET_CONTAINER_DLL_remove(ctx.stack_head, ctx.stack_tail, nfa); + REGEX_INTERNAL_automaton_destroy(nfa); + } return NULL; } @@ -2988,10 +2991,10 @@ error: * for starting. */ static void -construct_dfa_states (struct REGEX_INTERNAL_Context *ctx, - struct REGEX_INTERNAL_Automaton *nfa, - struct REGEX_INTERNAL_Automaton *dfa, - struct REGEX_INTERNAL_State *dfa_state) +construct_dfa_states(struct REGEX_INTERNAL_Context *ctx, + struct REGEX_INTERNAL_Automaton *nfa, + struct REGEX_INTERNAL_Automaton *dfa, + struct REGEX_INTERNAL_State *dfa_state) { struct REGEX_INTERNAL_Transition *ctran; struct REGEX_INTERNAL_State *new_dfa_state; @@ -3001,37 +3004,37 @@ construct_dfa_states (struct REGEX_INTERNAL_Context *ctx, struct REGEX_INTERNAL_StateSet nfa_set; for (ctran = dfa_state->transitions_head; NULL != ctran; ctran = ctran->next) - { - if (NULL == ctran->label || NULL != ctran->to_state) - continue; + { + if (NULL == ctran->label || NULL != ctran->to_state) + continue; - nfa_closure_set_create (&tmp, nfa, &dfa_state->nfa_set, ctran->label); - nfa_closure_set_create (&nfa_set, nfa, &tmp, NULL); - state_set_clear (&tmp); + nfa_closure_set_create(&tmp, nfa, &dfa_state->nfa_set, ctran->label); + nfa_closure_set_create(&nfa_set, nfa, &tmp, NULL); + state_set_clear(&tmp); - state_contains = NULL; - for (state_iter = dfa->states_head; NULL != state_iter; - state_iter = state_iter->next) - { - if (0 == state_set_compare (&state_iter->nfa_set, &nfa_set)) - { - state_contains = state_iter; - break; - } - } - if (NULL == state_contains) - { - new_dfa_state = dfa_state_create (ctx, &nfa_set); - automaton_add_state (dfa, new_dfa_state); - ctran->to_state = new_dfa_state; - construct_dfa_states (ctx, nfa, dfa, new_dfa_state); - } - else - { - ctran->to_state = state_contains; - state_set_clear (&nfa_set); + state_contains = NULL; + for (state_iter = dfa->states_head; NULL != state_iter; + state_iter = state_iter->next) + { + if (0 == state_set_compare(&state_iter->nfa_set, &nfa_set)) + { + state_contains = state_iter; + break; + } + } + if (NULL == state_contains) + { + new_dfa_state = dfa_state_create(ctx, &nfa_set); + automaton_add_state(dfa, new_dfa_state); + ctran->to_state = new_dfa_state; + construct_dfa_states(ctx, nfa, dfa, new_dfa_state); + } + else + { + ctran->to_state = state_contains; + state_set_clear(&nfa_set); + } } - } } @@ -3053,9 +3056,9 @@ construct_dfa_states (struct REGEX_INTERNAL_Context *ctx, * @return DFA, needs to be freed using REGEX_INTERNAL_automaton_destroy. */ struct REGEX_INTERNAL_Automaton * -REGEX_INTERNAL_construct_dfa (const char *regex, - const size_t len, - unsigned int max_path_len) +REGEX_INTERNAL_construct_dfa(const char *regex, + const size_t len, + unsigned int max_path_len) { struct REGEX_INTERNAL_Context ctx; struct REGEX_INTERNAL_Automaton *dfa; @@ -3063,50 +3066,50 @@ REGEX_INTERNAL_construct_dfa (const char *regex, struct REGEX_INTERNAL_StateSet nfa_start_eps_cls; struct REGEX_INTERNAL_StateSet singleton_set; - REGEX_INTERNAL_context_init (&ctx); + REGEX_INTERNAL_context_init(&ctx); /* Create NFA */ - nfa = REGEX_INTERNAL_construct_nfa (regex, len); + nfa = REGEX_INTERNAL_construct_nfa(regex, len); if (NULL == nfa) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not create DFA, because NFA creation failed\n"); - return NULL; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not create DFA, because NFA creation failed\n"); + return NULL; + } - dfa = GNUNET_new (struct REGEX_INTERNAL_Automaton); + dfa = GNUNET_new(struct REGEX_INTERNAL_Automaton); dfa->type = DFA; - dfa->regex = GNUNET_strdup (regex); + dfa->regex = GNUNET_strdup(regex); /* Create DFA start state from epsilon closure */ - memset (&singleton_set, 0, sizeof (struct REGEX_INTERNAL_StateSet)); - state_set_append (&singleton_set, nfa->start); - nfa_closure_set_create (&nfa_start_eps_cls, nfa, &singleton_set, NULL); - state_set_clear (&singleton_set); - dfa->start = dfa_state_create (&ctx, &nfa_start_eps_cls); - automaton_add_state (dfa, dfa->start); + memset(&singleton_set, 0, sizeof(struct REGEX_INTERNAL_StateSet)); + state_set_append(&singleton_set, nfa->start); + nfa_closure_set_create(&nfa_start_eps_cls, nfa, &singleton_set, NULL); + state_set_clear(&singleton_set); + dfa->start = dfa_state_create(&ctx, &nfa_start_eps_cls); + automaton_add_state(dfa, dfa->start); - construct_dfa_states (&ctx, nfa, dfa, dfa->start); - REGEX_INTERNAL_automaton_destroy (nfa); + construct_dfa_states(&ctx, nfa, dfa, dfa->start); + REGEX_INTERNAL_automaton_destroy(nfa); /* Minimize DFA */ - if (GNUNET_OK != dfa_minimize (&ctx, dfa)) - { - REGEX_INTERNAL_automaton_destroy (dfa); - return NULL; - } + if (GNUNET_OK != dfa_minimize(&ctx, dfa)) + { + REGEX_INTERNAL_automaton_destroy(dfa); + return NULL; + } /* Create proofs and hashes for all states */ - if (GNUNET_OK != automaton_create_proofs (dfa)) - { - REGEX_INTERNAL_automaton_destroy (dfa); - return NULL; - } + if (GNUNET_OK != automaton_create_proofs(dfa)) + { + REGEX_INTERNAL_automaton_destroy(dfa); + return NULL; + } /* Compress linear DFA paths */ if (1 != max_path_len) - dfa_compress_paths (&ctx, dfa, max_path_len); + dfa_compress_paths(&ctx, dfa, max_path_len); return dfa; } @@ -3119,7 +3122,7 @@ REGEX_INTERNAL_construct_dfa (const char *regex, * @param a automaton to be destroyed */ void -REGEX_INTERNAL_automaton_destroy (struct REGEX_INTERNAL_Automaton *a) +REGEX_INTERNAL_automaton_destroy(struct REGEX_INTERNAL_Automaton *a) { struct REGEX_INTERNAL_State *s; struct REGEX_INTERNAL_State *next_state; @@ -3127,17 +3130,17 @@ REGEX_INTERNAL_automaton_destroy (struct REGEX_INTERNAL_Automaton *a) if (NULL == a) return; - GNUNET_free_non_null (a->regex); - GNUNET_free_non_null (a->canonical_regex); + GNUNET_free_non_null(a->regex); + GNUNET_free_non_null(a->canonical_regex); for (s = a->states_head; NULL != s; s = next_state) - { - next_state = s->next; - GNUNET_CONTAINER_DLL_remove (a->states_head, a->states_tail, s); - automaton_destroy_state (s); - } + { + next_state = s->next; + GNUNET_CONTAINER_DLL_remove(a->states_head, a->states_tail, s); + automaton_destroy_state(s); + } - GNUNET_free (a); + GNUNET_free(a); } @@ -3150,32 +3153,32 @@ REGEX_INTERNAL_automaton_destroy (struct REGEX_INTERNAL_Automaton *a) * @return 0 if string matches, non-0 otherwise */ static int -evaluate_dfa (struct REGEX_INTERNAL_Automaton *a, const char *string) +evaluate_dfa(struct REGEX_INTERNAL_Automaton *a, const char *string) { const char *strp; struct REGEX_INTERNAL_State *s; unsigned int step_len; if (DFA != a->type) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Tried to evaluate DFA, but NFA automaton given"); - return -1; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Tried to evaluate DFA, but NFA automaton given"); + return -1; + } s = a->start; /* If the string is empty but the starting state is accepting, we accept. */ - if ((NULL == string || 0 == strlen (string)) && s->accepting) + if ((NULL == string || 0 == strlen(string)) && s->accepting) return 0; for (strp = string; NULL != strp && *strp; strp += step_len) - { - step_len = dfa_move (&s, strp); + { + step_len = dfa_move(&s, strp); - if (NULL == s) - break; - } + if (NULL == s) + break; + } if (NULL != s && s->accepting) return 0; @@ -3192,7 +3195,7 @@ evaluate_dfa (struct REGEX_INTERNAL_Automaton *a, const char *string) * @return 0 if string matches, non-0 otherwise */ static int -evaluate_nfa (struct REGEX_INTERNAL_Automaton *a, const char *string) +evaluate_nfa(struct REGEX_INTERNAL_Automaton *a, const char *string) { const char *strp; char str[2]; @@ -3204,43 +3207,43 @@ evaluate_nfa (struct REGEX_INTERNAL_Automaton *a, const char *string) int result; if (NFA != a->type) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Tried to evaluate NFA, but DFA automaton given"); - return -1; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Tried to evaluate NFA, but DFA automaton given"); + return -1; + } /* If the string is empty but the starting state is accepting, we accept. */ - if ((NULL == string || 0 == strlen (string)) && a->start->accepting) + if ((NULL == string || 0 == strlen(string)) && a->start->accepting) return 0; result = 1; - memset (&singleton_set, 0, sizeof (struct REGEX_INTERNAL_StateSet)); - state_set_append (&singleton_set, a->start); - nfa_closure_set_create (&sset, a, &singleton_set, NULL); - state_set_clear (&singleton_set); + memset(&singleton_set, 0, sizeof(struct REGEX_INTERNAL_StateSet)); + state_set_append(&singleton_set, a->start); + nfa_closure_set_create(&sset, a, &singleton_set, NULL); + state_set_clear(&singleton_set); str[1] = '\0'; for (strp = string; NULL != strp && *strp; strp++) - { - str[0] = *strp; - nfa_closure_set_create (&new_sset, a, &sset, str); - state_set_clear (&sset); - nfa_closure_set_create (&sset, a, &new_sset, 0); - state_set_clear (&new_sset); - } + { + str[0] = *strp; + nfa_closure_set_create(&new_sset, a, &sset, str); + state_set_clear(&sset); + nfa_closure_set_create(&sset, a, &new_sset, 0); + state_set_clear(&new_sset); + } for (i = 0; i < sset.off; i++) - { - s = sset.states[i]; - if ((NULL != s) && (s->accepting)) { - result = 0; - break; + s = sset.states[i]; + if ((NULL != s) && (s->accepting)) + { + result = 0; + break; + } } - } - state_set_clear (&sset); + state_set_clear(&sset); return result; } @@ -3253,24 +3256,26 @@ evaluate_nfa (struct REGEX_INTERNAL_Automaton *a, const char *string) * @return 0 if string matches, non-0 otherwise */ int -REGEX_INTERNAL_eval (struct REGEX_INTERNAL_Automaton *a, const char *string) +REGEX_INTERNAL_eval(struct REGEX_INTERNAL_Automaton *a, const char *string) { int result; switch (a->type) - { - case DFA: - result = evaluate_dfa (a, string); - break; - case NFA: - result = evaluate_nfa (a, string); - break; - default: - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Evaluating regex failed, automaton has no type!\n"); - result = GNUNET_SYSERR; - break; - } + { + case DFA: + result = evaluate_dfa(a, string); + break; + + case NFA: + result = evaluate_nfa(a, string); + break; + + default: + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Evaluating regex failed, automaton has no type!\n"); + result = GNUNET_SYSERR; + break; + } return result; } @@ -3288,7 +3293,7 @@ REGEX_INTERNAL_eval (struct REGEX_INTERNAL_Automaton *a, const char *string) * @return */ const char * -REGEX_INTERNAL_get_canonical_regex (struct REGEX_INTERNAL_Automaton *a) +REGEX_INTERNAL_get_canonical_regex(struct REGEX_INTERNAL_Automaton *a) { if (NULL == a) return NULL; @@ -3305,7 +3310,7 @@ REGEX_INTERNAL_get_canonical_regex (struct REGEX_INTERNAL_Automaton *a) * @return number of transitions in the given automaton. */ unsigned int -REGEX_INTERNAL_get_transition_count (struct REGEX_INTERNAL_Automaton *a) +REGEX_INTERNAL_get_transition_count(struct REGEX_INTERNAL_Automaton *a) { unsigned int t_count; struct REGEX_INTERNAL_State *s; @@ -3332,20 +3337,20 @@ REGEX_INTERNAL_get_transition_count (struct REGEX_INTERNAL_Automaton *a) * to construct the key */ size_t -REGEX_INTERNAL_get_first_key (const char *input_string, - size_t string_len, - struct GNUNET_HashCode *key) +REGEX_INTERNAL_get_first_key(const char *input_string, + size_t string_len, + struct GNUNET_HashCode *key) { size_t size; size = string_len < GNUNET_REGEX_INITIAL_BYTES ? string_len - : GNUNET_REGEX_INITIAL_BYTES; + : GNUNET_REGEX_INITIAL_BYTES; if (NULL == input_string) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Given input string was NULL!\n"); - return 0; - } - GNUNET_CRYPTO_hash (input_string, size, key); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Given input string was NULL!\n"); + return 0; + } + GNUNET_CRYPTO_hash(input_string, size, key); return size; } @@ -3362,12 +3367,12 @@ REGEX_INTERNAL_get_first_key (const char *input_string, * @param iterator_cls closure for the @a iterator function. */ static void -iterate_initial_edge (unsigned int min_len, - unsigned int max_len, - char *consumed_string, - struct REGEX_INTERNAL_State *state, - REGEX_INTERNAL_KeyIterator iterator, - void *iterator_cls) +iterate_initial_edge(unsigned int min_len, + unsigned int max_len, + char *consumed_string, + struct REGEX_INTERNAL_State *state, + REGEX_INTERNAL_KeyIterator iterator, + void *iterator_cls) { char *temp; struct REGEX_INTERNAL_Transition *t; @@ -3379,91 +3384,91 @@ iterate_initial_edge (unsigned int min_len, unsigned int cur_len; if (NULL != consumed_string) - cur_len = strlen (consumed_string); + cur_len = strlen(consumed_string); else cur_len = 0; if (((cur_len >= min_len) || (GNUNET_YES == state->accepting)) && (cur_len > 0) && (NULL != consumed_string)) - { - if (cur_len <= max_len) { - if ((NULL != state->proof) && - (0 != strcmp (consumed_string, state->proof))) - { - (void) state_get_edges (state, edges); - GNUNET_CRYPTO_hash (consumed_string, strlen (consumed_string), &hash); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Start state for string `%s' is %s\n", - consumed_string, - GNUNET_h2s (&hash)); - iterator (iterator_cls, - &hash, - consumed_string, - state->accepting, - num_edges, - edges); - } + if (cur_len <= max_len) + { + if ((NULL != state->proof) && + (0 != strcmp(consumed_string, state->proof))) + { + (void)state_get_edges(state, edges); + GNUNET_CRYPTO_hash(consumed_string, strlen(consumed_string), &hash); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Start state for string `%s' is %s\n", + consumed_string, + GNUNET_h2s(&hash)); + iterator(iterator_cls, + &hash, + consumed_string, + state->accepting, + num_edges, + edges); + } - if ((GNUNET_YES == state->accepting) && (cur_len > 1) && - (state->transition_count < 1) && (cur_len < max_len)) - { - /* Special case for regex consisting of just a string that is shorter than - * max_len */ - edge[0].label = &consumed_string[cur_len - 1]; - edge[0].destination = state->hash; - temp = GNUNET_strdup (consumed_string); - temp[cur_len - 1] = '\0'; - GNUNET_CRYPTO_hash (temp, cur_len - 1, &hash_new); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Start state for short string `%s' is %s\n", - temp, - GNUNET_h2s (&hash_new)); - iterator (iterator_cls, &hash_new, temp, GNUNET_NO, 1, edge); - GNUNET_free (temp); - } - } - else /* cur_len > max_len */ - { - /* Case where the concatenated labels are longer than max_len, then split. */ - edge[0].label = &consumed_string[max_len]; - edge[0].destination = state->hash; - temp = GNUNET_strdup (consumed_string); - temp[max_len] = '\0'; - GNUNET_CRYPTO_hash (temp, max_len, &hash); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Start state at split edge `%s'-`%s` is %s\n", - temp, - edge[0].label, - GNUNET_h2s (&hash_new)); - iterator (iterator_cls, &hash, temp, GNUNET_NO, 1, edge); - GNUNET_free (temp); + if ((GNUNET_YES == state->accepting) && (cur_len > 1) && + (state->transition_count < 1) && (cur_len < max_len)) + { + /* Special case for regex consisting of just a string that is shorter than + * max_len */ + edge[0].label = &consumed_string[cur_len - 1]; + edge[0].destination = state->hash; + temp = GNUNET_strdup(consumed_string); + temp[cur_len - 1] = '\0'; + GNUNET_CRYPTO_hash(temp, cur_len - 1, &hash_new); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Start state for short string `%s' is %s\n", + temp, + GNUNET_h2s(&hash_new)); + iterator(iterator_cls, &hash_new, temp, GNUNET_NO, 1, edge); + GNUNET_free(temp); + } + } + else /* cur_len > max_len */ + { + /* Case where the concatenated labels are longer than max_len, then split. */ + edge[0].label = &consumed_string[max_len]; + edge[0].destination = state->hash; + temp = GNUNET_strdup(consumed_string); + temp[max_len] = '\0'; + GNUNET_CRYPTO_hash(temp, max_len, &hash); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Start state at split edge `%s'-`%s` is %s\n", + temp, + edge[0].label, + GNUNET_h2s(&hash_new)); + iterator(iterator_cls, &hash, temp, GNUNET_NO, 1, edge); + GNUNET_free(temp); + } } - } if (cur_len < max_len) - { - for (t = state->transitions_head; NULL != t; t = t->next) { - if (NULL != strchr (t->label, (int) '.')) - { - /* Wildcards not allowed during starting states */ - GNUNET_break (0); - continue; - } - if (NULL != consumed_string) - GNUNET_asprintf (&temp, "%s%s", consumed_string, t->label); - else - GNUNET_asprintf (&temp, "%s", t->label); - iterate_initial_edge (min_len, - max_len, - temp, - t->to_state, - iterator, - iterator_cls); - GNUNET_free (temp); + for (t = state->transitions_head; NULL != t; t = t->next) + { + if (NULL != strchr(t->label, (int)'.')) + { + /* Wildcards not allowed during starting states */ + GNUNET_break(0); + continue; + } + if (NULL != consumed_string) + GNUNET_asprintf(&temp, "%s%s", consumed_string, t->label); + else + GNUNET_asprintf(&temp, "%s", t->label); + iterate_initial_edge(min_len, + max_len, + temp, + t->to_state, + iterator, + iterator_cls); + GNUNET_free(temp); + } } - } } @@ -3476,41 +3481,41 @@ iterate_initial_edge (unsigned int min_len, * @param iterator_cls closure. */ void -REGEX_INTERNAL_iterate_all_edges (struct REGEX_INTERNAL_Automaton *a, - REGEX_INTERNAL_KeyIterator iterator, - void *iterator_cls) +REGEX_INTERNAL_iterate_all_edges(struct REGEX_INTERNAL_Automaton *a, + REGEX_INTERNAL_KeyIterator iterator, + void *iterator_cls) { struct REGEX_INTERNAL_State *s; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Iterating over starting edges\n"); - iterate_initial_edge (GNUNET_REGEX_INITIAL_BYTES, - GNUNET_REGEX_INITIAL_BYTES, - NULL, - a->start, - iterator, - iterator_cls); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Iterating over DFA edges\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Iterating over starting edges\n"); + iterate_initial_edge(GNUNET_REGEX_INITIAL_BYTES, + GNUNET_REGEX_INITIAL_BYTES, + NULL, + a->start, + iterator, + iterator_cls); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Iterating over DFA edges\n"); for (s = a->states_head; NULL != s; s = s->next) - { - struct REGEX_BLOCK_Edge edges[s->transition_count]; - unsigned int num_edges; - - num_edges = state_get_edges (s, edges); - if (((NULL != s->proof) && (0 < strlen (s->proof))) || s->accepting) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Creating DFA edges at `%s' under key %s\n", - s->proof, - GNUNET_h2s (&s->hash)); - iterator (iterator_cls, - &s->hash, - s->proof, - s->accepting, - num_edges, - edges); + { + struct REGEX_BLOCK_Edge edges[s->transition_count]; + unsigned int num_edges; + + num_edges = state_get_edges(s, edges); + if (((NULL != s->proof) && (0 < strlen(s->proof))) || s->accepting) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Creating DFA edges at `%s' under key %s\n", + s->proof, + GNUNET_h2s(&s->hash)); + iterator(iterator_cls, + &s->hash, + s->proof, + s->accepting, + num_edges, + edges); + } + s->marked = GNUNET_NO; } - s->marked = GNUNET_NO; - } } @@ -3520,8 +3525,7 @@ REGEX_INTERNAL_iterate_all_edges (struct REGEX_INTERNAL_Automaton *a, * Contains the same info as the Regex Iterator parametes except the key, * which comes directly from the HashMap iterator. */ -struct temporal_state_store -{ +struct temporal_state_store { int reachable; char *proof; int accepting; @@ -3533,8 +3537,7 @@ struct temporal_state_store /** * Store regex iterator and cls in one place to pass to the hashmap iterator. */ -struct client_iterator -{ +struct client_iterator { REGEX_INTERNAL_KeyIterator iterator; void *iterator_cls; }; @@ -3552,31 +3555,31 @@ struct client_iterator * @param edges edges leaving current state. */ static void -store_all_states (void *cls, - const struct GNUNET_HashCode *key, - const char *proof, - int accepting, - unsigned int num_edges, - const struct REGEX_BLOCK_Edge *edges) +store_all_states(void *cls, + const struct GNUNET_HashCode *key, + const char *proof, + int accepting, + unsigned int num_edges, + const struct REGEX_BLOCK_Edge *edges) { struct GNUNET_CONTAINER_MultiHashMap *hm = cls; struct temporal_state_store *tmp; size_t edges_size; - tmp = GNUNET_new (struct temporal_state_store); + tmp = GNUNET_new(struct temporal_state_store); tmp->reachable = GNUNET_NO; - tmp->proof = GNUNET_strdup (proof); + tmp->proof = GNUNET_strdup(proof); tmp->accepting = accepting; tmp->num_edges = num_edges; - edges_size = sizeof (struct REGEX_BLOCK_Edge) * num_edges; - tmp->edges = GNUNET_malloc (edges_size); - GNUNET_memcpy (tmp->edges, edges, edges_size); - GNUNET_assert (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_put ( - hm, - key, - tmp, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)); + edges_size = sizeof(struct REGEX_BLOCK_Edge) * num_edges; + tmp->edges = GNUNET_malloc(edges_size); + GNUNET_memcpy(tmp->edges, edges, edges_size); + GNUNET_assert(GNUNET_YES == + GNUNET_CONTAINER_multihashmap_put( + hm, + key, + tmp, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)); } @@ -3589,8 +3592,8 @@ store_all_states (void *cls, * @param hm HashMap which stores all the states indexed by key. */ static void -mark_as_reachable (struct temporal_state_store *state, - struct GNUNET_CONTAINER_MultiHashMap *hm) +mark_as_reachable(struct temporal_state_store *state, + struct GNUNET_CONTAINER_MultiHashMap *hm) { struct temporal_state_store *child; unsigned int i; @@ -3601,16 +3604,16 @@ mark_as_reachable (struct temporal_state_store *state, state->reachable = GNUNET_YES; for (i = 0; i < state->num_edges; i++) - { - child = - GNUNET_CONTAINER_multihashmap_get (hm, &state->edges[i].destination); - if (NULL == child) { - GNUNET_break (0); - continue; + child = + GNUNET_CONTAINER_multihashmap_get(hm, &state->edges[i].destination); + if (NULL == child) + { + GNUNET_break(0); + continue; + } + mark_as_reachable(child, hm); } - mark_as_reachable (child, hm); - } } @@ -3624,9 +3627,9 @@ mark_as_reachable (struct temporal_state_store *state, * #GNUNET_NO if not. */ static int -reachability_iterator (void *cls, - const struct GNUNET_HashCode *key, - void *value) +reachability_iterator(void *cls, + const struct GNUNET_HashCode *key, + void *value) { struct GNUNET_CONTAINER_MultiHashMap *hm = cls; struct temporal_state_store *state = value; @@ -3635,12 +3638,12 @@ reachability_iterator (void *cls, /* already visited and marked */ return GNUNET_YES; - if (GNUNET_REGEX_INITIAL_BYTES > strlen (state->proof) && + if (GNUNET_REGEX_INITIAL_BYTES > strlen(state->proof) && GNUNET_NO == state->accepting) /* not directly reachable */ return GNUNET_YES; - mark_as_reachable (state, hm); + mark_as_reachable(state, hm); return GNUNET_YES; } @@ -3656,23 +3659,23 @@ reachability_iterator (void *cls, * #GNUNET_NO if not. */ static int -iterate_reachables (void *cls, const struct GNUNET_HashCode *key, void *value) +iterate_reachables(void *cls, const struct GNUNET_HashCode *key, void *value) { struct client_iterator *ci = cls; struct temporal_state_store *state = value; if (GNUNET_YES == state->reachable) - { - ci->iterator (ci->iterator_cls, - key, - state->proof, - state->accepting, - state->num_edges, - state->edges); - } - GNUNET_free (state->edges); - GNUNET_free (state->proof); - GNUNET_free (state); + { + ci->iterator(ci->iterator_cls, + key, + state->proof, + state->accepting, + state->num_edges, + state->edges); + } + GNUNET_free(state->edges); + GNUNET_free(state->proof); + GNUNET_free(state); return GNUNET_YES; } @@ -3687,22 +3690,22 @@ iterate_reachables (void *cls, const struct GNUNET_HashCode *key, void *value) * @param iterator_cls closure. */ void -REGEX_INTERNAL_iterate_reachable_edges (struct REGEX_INTERNAL_Automaton *a, - REGEX_INTERNAL_KeyIterator iterator, - void *iterator_cls) +REGEX_INTERNAL_iterate_reachable_edges(struct REGEX_INTERNAL_Automaton *a, + REGEX_INTERNAL_KeyIterator iterator, + void *iterator_cls) { struct GNUNET_CONTAINER_MultiHashMap *hm; struct client_iterator ci; - hm = GNUNET_CONTAINER_multihashmap_create (a->state_count * 2, GNUNET_NO); + hm = GNUNET_CONTAINER_multihashmap_create(a->state_count * 2, GNUNET_NO); ci.iterator = iterator; ci.iterator_cls = iterator_cls; - REGEX_INTERNAL_iterate_all_edges (a, &store_all_states, hm); - GNUNET_CONTAINER_multihashmap_iterate (hm, &reachability_iterator, hm); - GNUNET_CONTAINER_multihashmap_iterate (hm, &iterate_reachables, &ci); + REGEX_INTERNAL_iterate_all_edges(a, &store_all_states, hm); + GNUNET_CONTAINER_multihashmap_iterate(hm, &reachability_iterator, hm); + GNUNET_CONTAINER_multihashmap_iterate(hm, &iterate_reachables, &ci); - GNUNET_CONTAINER_multihashmap_destroy (hm); + GNUNET_CONTAINER_multihashmap_destroy(hm); } diff --git a/src/regex/regex_internal.h b/src/regex/regex_internal.h index 43686b5e2..ab8b6f22d 100644 --- a/src/regex/regex_internal.h +++ b/src/regex/regex_internal.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/regex/regex_internal.h * @brief common internal definitions for regex library. @@ -47,8 +47,7 @@ extern "C" * which they origin ('from_state'). Each state can have 0-n transitions. * If label is NULL, this is considered to be an epsilon transition. */ -struct REGEX_INTERNAL_Transition -{ +struct REGEX_INTERNAL_Transition { /** * This is a linked list. */ @@ -90,8 +89,7 @@ struct REGEX_INTERNAL_State; /** * Set of states. */ -struct REGEX_INTERNAL_StateSet -{ +struct REGEX_INTERNAL_StateSet { /** * Array of states. */ @@ -112,8 +110,7 @@ struct REGEX_INTERNAL_StateSet /** * A state. Can be used in DFA and NFA automatons. */ -struct REGEX_INTERNAL_State -{ +struct REGEX_INTERNAL_State { /** * This is a linked list to keep states in an automaton. */ @@ -245,8 +242,7 @@ struct REGEX_INTERNAL_State /** * Type of an automaton. */ -enum REGEX_INTERNAL_AutomatonType -{ +enum REGEX_INTERNAL_AutomatonType { NFA, DFA }; @@ -255,8 +251,7 @@ enum REGEX_INTERNAL_AutomatonType /** * Automaton representation. */ -struct REGEX_INTERNAL_Automaton -{ +struct REGEX_INTERNAL_Automaton { /** * Linked list of NFAs used for partial NFA creation. */ @@ -324,7 +319,7 @@ struct REGEX_INTERNAL_Automaton * @return NFA, needs to be freed using REGEX_INTERNAL_automaton_destroy. */ struct REGEX_INTERNAL_Automaton * -REGEX_INTERNAL_construct_nfa (const char *regex, const size_t len); +REGEX_INTERNAL_construct_nfa(const char *regex, const size_t len); /** @@ -340,8 +335,8 @@ REGEX_INTERNAL_construct_nfa (const char *regex, const size_t len); * @return GNUNET_YES to proceed traversal, GNUNET_NO to stop. */ typedef int (*REGEX_INTERNAL_traverse_check) (void *cls, - struct REGEX_INTERNAL_State * s, - struct REGEX_INTERNAL_Transition * t); + struct REGEX_INTERNAL_State * s, + struct REGEX_INTERNAL_Transition * t); /** @@ -352,8 +347,8 @@ typedef int (*REGEX_INTERNAL_traverse_check) (void *cls, * @param s state. */ typedef void (*REGEX_INTERNAL_traverse_action) (void *cls, - const unsigned int count, - struct REGEX_INTERNAL_State * s); + const unsigned int count, + struct REGEX_INTERNAL_State * s); /** @@ -370,12 +365,12 @@ typedef void (*REGEX_INTERNAL_traverse_action) (void *cls, * @param action_cls closure for action */ void -REGEX_INTERNAL_automaton_traverse (const struct REGEX_INTERNAL_Automaton *a, - struct REGEX_INTERNAL_State *start, - REGEX_INTERNAL_traverse_check check, - void *check_cls, - REGEX_INTERNAL_traverse_action action, - void *action_cls); +REGEX_INTERNAL_automaton_traverse(const struct REGEX_INTERNAL_Automaton *a, + struct REGEX_INTERNAL_State *start, + REGEX_INTERNAL_traverse_check check, + void *check_cls, + REGEX_INTERNAL_traverse_action action, + void *action_cls); /** * Get the canonical regex of the given automaton. @@ -389,7 +384,7 @@ REGEX_INTERNAL_automaton_traverse (const struct REGEX_INTERNAL_Automaton *a, * @return canonical regex string. */ const char * -REGEX_INTERNAL_get_canonical_regex (struct REGEX_INTERNAL_Automaton *a); +REGEX_INTERNAL_get_canonical_regex(struct REGEX_INTERNAL_Automaton *a); /** @@ -400,15 +395,14 @@ REGEX_INTERNAL_get_canonical_regex (struct REGEX_INTERNAL_Automaton *a); * @return number of transitions in the given automaton. */ unsigned int -REGEX_INTERNAL_get_transition_count (struct REGEX_INTERNAL_Automaton *a); +REGEX_INTERNAL_get_transition_count(struct REGEX_INTERNAL_Automaton *a); /** * Context that contains an id counter for states and transitions as well as a * DLL of automatons used as a stack for NFA construction. */ -struct REGEX_INTERNAL_Context -{ +struct REGEX_INTERNAL_Context { /** * Unique state id. */ @@ -439,9 +433,9 @@ struct REGEX_INTERNAL_Context * @param stride_len length of the strides. */ void -REGEX_INTERNAL_dfa_add_multi_strides (struct REGEX_INTERNAL_Context *regex_ctx, - struct REGEX_INTERNAL_Automaton *dfa, - const unsigned int stride_len); +REGEX_INTERNAL_dfa_add_multi_strides(struct REGEX_INTERNAL_Context *regex_ctx, + struct REGEX_INTERNAL_Automaton *dfa, + const unsigned int stride_len); diff --git a/src/regex/regex_internal_dht.c b/src/regex/regex_internal_dht.c index 7cfaea894..611fb0a23 100644 --- a/src/regex/regex_internal_dht.c +++ b/src/regex/regex_internal_dht.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/regex/regex_internal_dht.c * @brief library to announce regexes in the network and match strings @@ -32,7 +32,7 @@ #include "gnunet_signatures.h" -#define LOG(kind,...) GNUNET_log_from (kind,"regex-dht",__VA_ARGS__) +#define LOG(kind, ...) GNUNET_log_from(kind, "regex-dht", __VA_ARGS__) /** * DHT replication level to use. @@ -53,8 +53,7 @@ /** * Handle to store cached data about a regex announce. */ -struct REGEX_INTERNAL_Announcement -{ +struct REGEX_INTERNAL_Announcement { /** * DHT handle to use, must be initialized externally. */ @@ -93,92 +92,92 @@ struct REGEX_INTERNAL_Announcement * @param edges edges leaving current state. */ static void -regex_iterator (void *cls, - const struct GNUNET_HashCode *key, - const char *proof, - int accepting, - unsigned int num_edges, - const struct REGEX_BLOCK_Edge *edges) +regex_iterator(void *cls, + const struct GNUNET_HashCode *key, + const char *proof, + int accepting, + unsigned int num_edges, + const struct REGEX_BLOCK_Edge *edges) { struct REGEX_INTERNAL_Announcement *h = cls; struct RegexBlock *block; size_t size; unsigned int i; - LOG (GNUNET_ERROR_TYPE_INFO, - "DHT PUT for state %s with proof `%s' and %u edges:\n", - GNUNET_h2s (key), - proof, - num_edges); + LOG(GNUNET_ERROR_TYPE_INFO, + "DHT PUT for state %s with proof `%s' and %u edges:\n", + GNUNET_h2s(key), + proof, + num_edges); for (i = 0; i < num_edges; i++) - { - LOG (GNUNET_ERROR_TYPE_INFO, - "Edge %u `%s' towards %s\n", - i, - edges[i].label, - GNUNET_h2s (&edges[i].destination)); - } + { + LOG(GNUNET_ERROR_TYPE_INFO, + "Edge %u `%s' towards %s\n", + i, + edges[i].label, + GNUNET_h2s(&edges[i].destination)); + } if (GNUNET_YES == accepting) - { - struct RegexAcceptBlock ab; - - LOG (GNUNET_ERROR_TYPE_INFO, - "State %s is accepting, putting own id\n", - GNUNET_h2s (key)); - size = sizeof (struct RegexAcceptBlock); - ab.purpose.size = ntohl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) + - sizeof (struct GNUNET_TIME_AbsoluteNBO) + - sizeof (struct GNUNET_HashCode)); - ab.purpose.purpose = ntohl (GNUNET_SIGNATURE_PURPOSE_REGEX_ACCEPT); - ab.expiration_time = GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_DHT_MAX_EXPIRATION)); - ab.key = *key; - GNUNET_CRYPTO_eddsa_key_get_public (h->priv, - &ab.peer.public_key); - GNUNET_assert (GNUNET_OK == - GNUNET_CRYPTO_eddsa_sign (h->priv, - &ab.purpose, - &ab.signature)); - - GNUNET_STATISTICS_update (h->stats, "# regex accepting blocks stored", - 1, GNUNET_NO); - GNUNET_STATISTICS_update (h->stats, "# regex accepting block bytes stored", - sizeof (struct RegexAcceptBlock), GNUNET_NO); - (void) - GNUNET_DHT_put (h->dht, key, - DHT_REPLICATION, - DHT_OPT | GNUNET_DHT_RO_RECORD_ROUTE, - GNUNET_BLOCK_TYPE_REGEX_ACCEPT, - size, - &ab, - GNUNET_TIME_relative_to_absolute (DHT_TTL), - NULL, NULL); - } - block = REGEX_BLOCK_create (proof, - num_edges, - edges, - accepting, - &size); + { + struct RegexAcceptBlock ab; + + LOG(GNUNET_ERROR_TYPE_INFO, + "State %s is accepting, putting own id\n", + GNUNET_h2s(key)); + size = sizeof(struct RegexAcceptBlock); + ab.purpose.size = ntohl(sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose) + + sizeof(struct GNUNET_TIME_AbsoluteNBO) + + sizeof(struct GNUNET_HashCode)); + ab.purpose.purpose = ntohl(GNUNET_SIGNATURE_PURPOSE_REGEX_ACCEPT); + ab.expiration_time = GNUNET_TIME_absolute_hton(GNUNET_TIME_relative_to_absolute(GNUNET_CONSTANTS_DHT_MAX_EXPIRATION)); + ab.key = *key; + GNUNET_CRYPTO_eddsa_key_get_public(h->priv, + &ab.peer.public_key); + GNUNET_assert(GNUNET_OK == + GNUNET_CRYPTO_eddsa_sign(h->priv, + &ab.purpose, + &ab.signature)); + + GNUNET_STATISTICS_update(h->stats, "# regex accepting blocks stored", + 1, GNUNET_NO); + GNUNET_STATISTICS_update(h->stats, "# regex accepting block bytes stored", + sizeof(struct RegexAcceptBlock), GNUNET_NO); + (void) + GNUNET_DHT_put(h->dht, key, + DHT_REPLICATION, + DHT_OPT | GNUNET_DHT_RO_RECORD_ROUTE, + GNUNET_BLOCK_TYPE_REGEX_ACCEPT, + size, + &ab, + GNUNET_TIME_relative_to_absolute(DHT_TTL), + NULL, NULL); + } + block = REGEX_BLOCK_create(proof, + num_edges, + edges, + accepting, + &size); if (NULL == block) return; - (void) GNUNET_DHT_put (h->dht, - key, - DHT_REPLICATION, - DHT_OPT, - GNUNET_BLOCK_TYPE_REGEX, - size, - block, - GNUNET_TIME_relative_to_absolute (DHT_TTL), - NULL, - NULL); - GNUNET_STATISTICS_update (h->stats, - "# regex blocks stored", - 1, - GNUNET_NO); - GNUNET_STATISTICS_update (h->stats, - "# regex block bytes stored", - size, - GNUNET_NO); - GNUNET_free (block); + (void)GNUNET_DHT_put(h->dht, + key, + DHT_REPLICATION, + DHT_OPT, + GNUNET_BLOCK_TYPE_REGEX, + size, + block, + GNUNET_TIME_relative_to_absolute(DHT_TTL), + NULL, + NULL); + GNUNET_STATISTICS_update(h->stats, + "# regex blocks stored", + 1, + GNUNET_NO); + GNUNET_STATISTICS_update(h->stats, + "# regex block bytes stored", + size, + GNUNET_NO); + GNUNET_free(block); } @@ -195,22 +194,22 @@ regex_iterator (void *cls, * Must be freed by calling #REGEX_INTERNAL_announce_cancel(). */ struct REGEX_INTERNAL_Announcement * -REGEX_INTERNAL_announce (struct GNUNET_DHT_Handle *dht, - const struct GNUNET_CRYPTO_EddsaPrivateKey *priv, - const char *regex, - uint16_t compression, - struct GNUNET_STATISTICS_Handle *stats) +REGEX_INTERNAL_announce(struct GNUNET_DHT_Handle *dht, + const struct GNUNET_CRYPTO_EddsaPrivateKey *priv, + const char *regex, + uint16_t compression, + struct GNUNET_STATISTICS_Handle *stats) { struct REGEX_INTERNAL_Announcement *h; - GNUNET_assert (NULL != dht); - h = GNUNET_new (struct REGEX_INTERNAL_Announcement); + GNUNET_assert(NULL != dht); + h = GNUNET_new(struct REGEX_INTERNAL_Announcement); h->regex = regex; h->dht = dht; h->stats = stats; h->priv = priv; - h->dfa = REGEX_INTERNAL_construct_dfa (regex, strlen (regex), compression); - REGEX_INTERNAL_reannounce (h); + h->dfa = REGEX_INTERNAL_construct_dfa(regex, strlen(regex), compression); + REGEX_INTERNAL_reannounce(h); return h; } @@ -222,15 +221,15 @@ REGEX_INTERNAL_announce (struct GNUNET_DHT_Handle *dht, * @param h Handle returned by a previous #REGEX_INTERNAL_announce call(). */ void -REGEX_INTERNAL_reannounce (struct REGEX_INTERNAL_Announcement *h) +REGEX_INTERNAL_reannounce(struct REGEX_INTERNAL_Announcement *h) { - GNUNET_assert (NULL != h->dfa); /* make sure to call announce first */ - LOG (GNUNET_ERROR_TYPE_INFO, - "REGEX_INTERNAL_reannounce: %s\n", - h->regex); - REGEX_INTERNAL_iterate_reachable_edges (h->dfa, - ®ex_iterator, - h); + GNUNET_assert(NULL != h->dfa); /* make sure to call announce first */ + LOG(GNUNET_ERROR_TYPE_INFO, + "REGEX_INTERNAL_reannounce: %s\n", + h->regex); + REGEX_INTERNAL_iterate_reachable_edges(h->dfa, + ®ex_iterator, + h); } @@ -241,10 +240,10 @@ REGEX_INTERNAL_reannounce (struct REGEX_INTERNAL_Announcement *h) * @param h Handle returned by a previous #REGEX_INTERNAL_announce() call. */ void -REGEX_INTERNAL_announce_cancel (struct REGEX_INTERNAL_Announcement *h) +REGEX_INTERNAL_announce_cancel(struct REGEX_INTERNAL_Announcement *h) { - REGEX_INTERNAL_automaton_destroy (h->dfa); - GNUNET_free (h); + REGEX_INTERNAL_automaton_destroy(h->dfa); + GNUNET_free(h); } @@ -255,8 +254,7 @@ REGEX_INTERNAL_announce_cancel (struct REGEX_INTERNAL_Announcement *h) * Struct to keep state of running searches that have consumed a part of * the inital string. */ -struct RegexSearchContext -{ +struct RegexSearchContext { /** * Part of the description already consumed by * this particular search branch. @@ -284,8 +282,7 @@ struct RegexSearchContext /** * Type of values in `dht_get_results`. */ -struct Result -{ +struct Result { /** * Number of bytes in data. */ @@ -302,8 +299,7 @@ struct Result * Struct to keep information of searches of services described by a regex * using a user-provided string service description. */ -struct REGEX_INTERNAL_Search -{ +struct REGEX_INTERNAL_Search { /** * DHT handle to use, must be initialized externally. */ @@ -360,9 +356,9 @@ struct REGEX_INTERNAL_Search * @param ctx Context of the search. */ static void -regex_next_edge (const struct RegexBlock *block, - size_t size, - struct RegexSearchContext *ctx); +regex_next_edge(const struct RegexBlock *block, + size_t size, + struct RegexSearchContext *ctx); /** @@ -381,33 +377,33 @@ regex_next_edge (const struct RegexBlock *block, * @param data Pointer to the result data. */ static void -dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - enum GNUNET_BLOCK_Type type, - size_t size, const void *data) +dht_get_string_accept_handler(void *cls, struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + enum GNUNET_BLOCK_Type type, + size_t size, const void *data) { const struct RegexAcceptBlock *block = data; struct RegexSearchContext *ctx = cls; struct REGEX_INTERNAL_Search *info = ctx->info; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Regex result accept for %s (key %s)\n", - info->description, GNUNET_h2s(key)); - - GNUNET_STATISTICS_update (info->stats, - "# regex accepting blocks found", - 1, GNUNET_NO); - GNUNET_STATISTICS_update (info->stats, - "# regex accepting block bytes found", - size, GNUNET_NO); - info->callback (info->callback_cls, - &block->peer, - get_path, get_path_length, - put_path, put_path_length); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Regex result accept for %s (key %s)\n", + info->description, GNUNET_h2s(key)); + + GNUNET_STATISTICS_update(info->stats, + "# regex accepting blocks found", + 1, GNUNET_NO); + GNUNET_STATISTICS_update(info->stats, + "# regex accepting block bytes found", + size, GNUNET_NO); + info->callback(info->callback_cls, + &block->peer, + get_path, get_path_length, + put_path, put_path_length); } @@ -419,28 +415,28 @@ dht_get_string_accept_handler (void *cls, struct GNUNET_TIME_Absolute exp, * @param ctx Context containing info about the string, tunnel, etc. */ static void -regex_find_path (const struct GNUNET_HashCode *key, - struct RegexSearchContext *ctx) +regex_find_path(const struct GNUNET_HashCode *key, + struct RegexSearchContext *ctx) { struct GNUNET_DHT_GetHandle *get_h; - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Accept state found, now searching for paths to %s\n", - GNUNET_h2s (key), - (unsigned int) ctx->position); - get_h = GNUNET_DHT_get_start (ctx->info->dht, /* handle */ - GNUNET_BLOCK_TYPE_REGEX_ACCEPT, /* type */ - key, /* key to search */ - DHT_REPLICATION, /* replication level */ - DHT_OPT | GNUNET_DHT_RO_RECORD_ROUTE, - NULL, /* xquery */ // FIXME BLOOMFILTER - 0, /* xquery bits */ // FIXME BLOOMFILTER SIZE - &dht_get_string_accept_handler, ctx); - GNUNET_break (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put(ctx->info->dht_get_handles, - key, - get_h, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Accept state found, now searching for paths to %s\n", + GNUNET_h2s(key), + (unsigned int)ctx->position); + get_h = GNUNET_DHT_get_start(ctx->info->dht, /* handle */ + GNUNET_BLOCK_TYPE_REGEX_ACCEPT, /* type */ + key, /* key to search */ + DHT_REPLICATION, /* replication level */ + DHT_OPT | GNUNET_DHT_RO_RECORD_ROUTE, + NULL, /* xquery */ // FIXME BLOOMFILTER + 0, /* xquery bits */ // FIXME BLOOMFILTER SIZE + &dht_get_string_accept_handler, ctx); + GNUNET_break(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(ctx->info->dht_get_handles, + key, + get_h, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); } @@ -462,14 +458,14 @@ regex_find_path (const struct GNUNET_HashCode *key, * TODO: re-issue the request after certain time? cancel after X results? */ static void -dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp, - const struct GNUNET_HashCode *key, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length, - enum GNUNET_BLOCK_Type type, - size_t size, const void *data) +dht_get_string_handler(void *cls, struct GNUNET_TIME_Absolute exp, + const struct GNUNET_HashCode *key, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length, + enum GNUNET_BLOCK_Type type, + size_t size, const void *data) { const struct RegexBlock *block = data; struct RegexSearchContext *ctx = cls; @@ -477,32 +473,32 @@ dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp, size_t len; struct Result *copy; - LOG (GNUNET_ERROR_TYPE_INFO, - "DHT GET result for %s (%s)\n", - GNUNET_h2s (key), ctx->info->description); - copy = GNUNET_malloc (sizeof (struct Result) + size); + LOG(GNUNET_ERROR_TYPE_INFO, + "DHT GET result for %s (%s)\n", + GNUNET_h2s(key), ctx->info->description); + copy = GNUNET_malloc(sizeof(struct Result) + size); copy->size = size; copy->data = ©[1]; - GNUNET_memcpy (©[1], block, size); - GNUNET_break (GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (info->dht_get_results, - key, copy, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); - len = strlen (info->description); + GNUNET_memcpy(©[1], block, size); + GNUNET_break(GNUNET_OK == + GNUNET_CONTAINER_multihashmap_put(info->dht_get_results, + key, copy, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); + len = strlen(info->description); if (len == ctx->position) // String processed - { - if (GNUNET_YES == GNUNET_BLOCK_is_accepting (block, size)) { - regex_find_path (key, ctx); + if (GNUNET_YES == GNUNET_BLOCK_is_accepting(block, size)) + { + regex_find_path(key, ctx); + } + else + { + LOG(GNUNET_ERROR_TYPE_INFO, "block not accepting!\n"); + /* FIXME REGEX this block not successful, wait for more? start timeout? */ + } + return; } - else - { - LOG (GNUNET_ERROR_TYPE_INFO, "block not accepting!\n"); - /* FIXME REGEX this block not successful, wait for more? start timeout? */ - } - return; - } - regex_next_edge (block, size, ctx); + regex_next_edge(block, size, ctx); } @@ -515,32 +511,32 @@ dht_get_string_handler (void *cls, struct GNUNET_TIME_Absolute exp, * @return #GNUNET_YES: we should always continue to iterate. */ static int -regex_result_iterator (void *cls, - const struct GNUNET_HashCode * key, - void *value) +regex_result_iterator(void *cls, + const struct GNUNET_HashCode * key, + void *value) { struct Result *result = value; const struct RegexBlock *block = result->data; struct RegexSearchContext *ctx = cls; - if ( (GNUNET_YES == - GNUNET_BLOCK_is_accepting (block, result->size)) && - (ctx->position == strlen (ctx->info->description)) ) - { - LOG (GNUNET_ERROR_TYPE_INFO, - "Found accepting known block\n"); - regex_find_path (key, ctx); - return GNUNET_YES; // We found an accept state! - } - LOG (GNUNET_ERROR_TYPE_DEBUG, - "* %u, %u, [%u]\n", - ctx->position, - strlen (ctx->info->description), - GNUNET_BLOCK_is_accepting (block, result->size)); - regex_next_edge (block, result->size, ctx); - - GNUNET_STATISTICS_update (ctx->info->stats, "# regex cadet blocks iterated", - 1, GNUNET_NO); + if ((GNUNET_YES == + GNUNET_BLOCK_is_accepting(block, result->size)) && + (ctx->position == strlen(ctx->info->description))) + { + LOG(GNUNET_ERROR_TYPE_INFO, + "Found accepting known block\n"); + regex_find_path(key, ctx); + return GNUNET_YES; // We found an accept state! + } + LOG(GNUNET_ERROR_TYPE_DEBUG, + "* %u, %u, [%u]\n", + ctx->position, + strlen(ctx->info->description), + GNUNET_BLOCK_is_accepting(block, result->size)); + regex_next_edge(block, result->size, ctx); + + GNUNET_STATISTICS_update(ctx->info->stats, "# regex cadet blocks iterated", + 1, GNUNET_NO); return GNUNET_YES; } @@ -556,43 +552,43 @@ regex_result_iterator (void *cls, * @return #GNUNET_YES if should keep iterating, #GNUNET_NO otherwise. */ static int -regex_edge_iterator (void *cls, - const char *token, - size_t len, - const struct GNUNET_HashCode *key) +regex_edge_iterator(void *cls, + const char *token, + size_t len, + const struct GNUNET_HashCode *key) { struct RegexSearchContext *ctx = cls; struct REGEX_INTERNAL_Search *info = ctx->info; const char *current; size_t current_len; - GNUNET_STATISTICS_update (info->stats, "# regex edges iterated", - 1, GNUNET_NO); + GNUNET_STATISTICS_update(info->stats, "# regex edges iterated", + 1, GNUNET_NO); current = &info->description[ctx->position]; - current_len = strlen (info->description) - ctx->position; + current_len = strlen(info->description) - ctx->position; if (len > current_len) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, "Token too long, END\n"); - return GNUNET_YES; - } - if (0 != strncmp (current, token, len)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, "Token doesn't match, END\n"); - return GNUNET_YES; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "Token too long, END\n"); + return GNUNET_YES; + } + if (0 != strncmp(current, token, len)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "Token doesn't match, END\n"); + return GNUNET_YES; + } if (len > ctx->longest_match) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, "Token is longer, KEEP\n"); - ctx->longest_match = len; - ctx->hash = *key; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "Token is longer, KEEP\n"); + ctx->longest_match = len; + ctx->hash = *key; + } else - { - LOG (GNUNET_ERROR_TYPE_DEBUG, "Token is not longer, IGNORE\n"); - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, "Token is not longer, IGNORE\n"); + } - LOG (GNUNET_ERROR_TYPE_DEBUG, "* End of regex edge iterator\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, "* End of regex edge iterator\n"); return GNUNET_YES; } @@ -605,9 +601,9 @@ regex_edge_iterator (void *cls, * @param ctx Context of the search. */ static void -regex_next_edge (const struct RegexBlock *block, - size_t size, - struct RegexSearchContext *ctx) +regex_next_edge(const struct RegexBlock *block, + size_t size, + struct RegexSearchContext *ctx) { struct RegexSearchContext *new_ctx; struct REGEX_INTERNAL_Search *info = ctx->info; @@ -616,69 +612,69 @@ regex_next_edge (const struct RegexBlock *block, const char *rest; int result; - LOG (GNUNET_ERROR_TYPE_DEBUG, "Next edge\n"); + LOG(GNUNET_ERROR_TYPE_DEBUG, "Next edge\n"); /* Find the longest match for the current string position, * among tokens in the given block */ ctx->longest_match = 0; - result = REGEX_BLOCK_iterate (block, size, - ®ex_edge_iterator, ctx); - GNUNET_break (GNUNET_OK == result); + result = REGEX_BLOCK_iterate(block, size, + ®ex_edge_iterator, ctx); + GNUNET_break(GNUNET_OK == result); /* Did anything match? */ if (0 == ctx->longest_match) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "no match in block\n"); - return; - } + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "no match in block\n"); + return; + } hash = &ctx->hash; - new_ctx = GNUNET_new (struct RegexSearchContext); + new_ctx = GNUNET_new(struct RegexSearchContext); new_ctx->info = info; new_ctx->position = ctx->position + ctx->longest_match; - GNUNET_array_append (info->contexts, info->n_contexts, new_ctx); + GNUNET_array_append(info->contexts, info->n_contexts, new_ctx); /* Check whether we already have a DHT GET running for it */ if (GNUNET_YES == - GNUNET_CONTAINER_multihashmap_contains (info->dht_get_handles, hash)) - { - LOG (GNUNET_ERROR_TYPE_DEBUG, - "GET for %s running, END\n", - GNUNET_h2s (hash)); - GNUNET_CONTAINER_multihashmap_get_multiple (info->dht_get_results, - hash, - ®ex_result_iterator, - new_ctx); - return; /* We are already looking for it */ - } - - GNUNET_STATISTICS_update (info->stats, "# regex nodes traversed", - 1, GNUNET_NO); - - LOG (GNUNET_ERROR_TYPE_DEBUG, - "Following edges at %s for offset %u in `%s'\n", - GNUNET_h2s (hash), - (unsigned int) ctx->position, - info->description); + GNUNET_CONTAINER_multihashmap_contains(info->dht_get_handles, hash)) + { + LOG(GNUNET_ERROR_TYPE_DEBUG, + "GET for %s running, END\n", + GNUNET_h2s(hash)); + GNUNET_CONTAINER_multihashmap_get_multiple(info->dht_get_results, + hash, + ®ex_result_iterator, + new_ctx); + return; /* We are already looking for it */ + } + + GNUNET_STATISTICS_update(info->stats, "# regex nodes traversed", + 1, GNUNET_NO); + + LOG(GNUNET_ERROR_TYPE_DEBUG, + "Following edges at %s for offset %u in `%s'\n", + GNUNET_h2s(hash), + (unsigned int)ctx->position, + info->description); rest = &new_ctx->info->description[new_ctx->position]; get_h = - GNUNET_DHT_get_start (info->dht, /* handle */ - GNUNET_BLOCK_TYPE_REGEX, /* type */ - hash, /* key to search */ - DHT_REPLICATION, /* replication level */ - DHT_OPT, - rest, /* xquery */ - strlen (rest) + 1, /* xquery bits */ - &dht_get_string_handler, new_ctx); + GNUNET_DHT_get_start(info->dht, /* handle */ + GNUNET_BLOCK_TYPE_REGEX, /* type */ + hash, /* key to search */ + DHT_REPLICATION, /* replication level */ + DHT_OPT, + rest, /* xquery */ + strlen(rest) + 1, /* xquery bits */ + &dht_get_string_handler, new_ctx); if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put(info->dht_get_handles, hash, get_h, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)) - { - GNUNET_break (0); - return; - } + { + GNUNET_break(0); + return; + } } @@ -696,11 +692,11 @@ regex_next_edge (const struct RegexBlock *block, * Must be freed by calling #REGEX_INTERNAL_search_cancel(). */ struct REGEX_INTERNAL_Search * -REGEX_INTERNAL_search (struct GNUNET_DHT_Handle *dht, - const char *string, - REGEX_INTERNAL_Found callback, - void *callback_cls, - struct GNUNET_STATISTICS_Handle *stats) +REGEX_INTERNAL_search(struct GNUNET_DHT_Handle *dht, + const char *string, + REGEX_INTERNAL_Found callback, + void *callback_cls, + struct GNUNET_STATISTICS_Handle *stats) { struct REGEX_INTERNAL_Search *h; struct GNUNET_DHT_GetHandle *get_h; @@ -710,50 +706,50 @@ REGEX_INTERNAL_search (struct GNUNET_DHT_Handle *dht, size_t len; /* Initialize handle */ - GNUNET_assert (NULL != dht); - GNUNET_assert (NULL != callback); - h = GNUNET_new (struct REGEX_INTERNAL_Search); + GNUNET_assert(NULL != dht); + GNUNET_assert(NULL != callback); + h = GNUNET_new(struct REGEX_INTERNAL_Search); h->dht = dht; - h->description = GNUNET_strdup (string); + h->description = GNUNET_strdup(string); h->callback = callback; h->callback_cls = callback_cls; h->stats = stats; - h->dht_get_handles = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO); - h->dht_get_results = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_NO); + h->dht_get_handles = GNUNET_CONTAINER_multihashmap_create(32, GNUNET_NO); + h->dht_get_results = GNUNET_CONTAINER_multihashmap_create(32, GNUNET_NO); /* Initialize context */ - len = strlen (string); - size = REGEX_INTERNAL_get_first_key (string, len, &key); - LOG (GNUNET_ERROR_TYPE_INFO, - "Initial key for `%s' is %s (based on `%.*s')\n", - string, - GNUNET_h2s (&key), - size, - string); - ctx = GNUNET_new (struct RegexSearchContext); + len = strlen(string); + size = REGEX_INTERNAL_get_first_key(string, len, &key); + LOG(GNUNET_ERROR_TYPE_INFO, + "Initial key for `%s' is %s (based on `%.*s')\n", + string, + GNUNET_h2s(&key), + size, + string); + ctx = GNUNET_new(struct RegexSearchContext); ctx->position = size; ctx->info = h; - GNUNET_array_append (h->contexts, - h->n_contexts, - ctx); + GNUNET_array_append(h->contexts, + h->n_contexts, + ctx); /* Start search in DHT */ - get_h = GNUNET_DHT_get_start (h->dht, /* handle */ - GNUNET_BLOCK_TYPE_REGEX, /* type */ - &key, /* key to search */ - DHT_REPLICATION, /* replication level */ - DHT_OPT, - &h->description[size], /* xquery */ - // FIXME add BLOOMFILTER to exclude filtered peers - len + 1 - size, /* xquery bits */ - // FIXME add BLOOMFILTER SIZE - &dht_get_string_handler, ctx); - GNUNET_break ( + get_h = GNUNET_DHT_get_start(h->dht, /* handle */ + GNUNET_BLOCK_TYPE_REGEX, /* type */ + &key, /* key to search */ + DHT_REPLICATION, /* replication level */ + DHT_OPT, + &h->description[size], /* xquery */ + // FIXME add BLOOMFILTER to exclude filtered peers + len + 1 - size, /* xquery bits */ + // FIXME add BLOOMFILTER SIZE + &dht_get_string_handler, ctx); + GNUNET_break( GNUNET_OK == - GNUNET_CONTAINER_multihashmap_put (h->dht_get_handles, - &key, - get_h, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST) - ); + GNUNET_CONTAINER_multihashmap_put(h->dht_get_handles, + &key, + get_h, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST) + ); return h; } @@ -770,13 +766,13 @@ REGEX_INTERNAL_search (struct GNUNET_DHT_Handle *dht, * #GNUNET_NO if not. */ static int -regex_cancel_dht_get (void *cls, - const struct GNUNET_HashCode * key, - void *value) +regex_cancel_dht_get(void *cls, + const struct GNUNET_HashCode * key, + void *value) { struct GNUNET_DHT_GetHandle *h = value; - GNUNET_DHT_get_stop (h); + GNUNET_DHT_get_stop(h); return GNUNET_YES; } @@ -792,11 +788,11 @@ regex_cancel_dht_get (void *cls, * #GNUNET_NO if not. */ static int -regex_free_result (void *cls, - const struct GNUNET_HashCode * key, - void *value) +regex_free_result(void *cls, + const struct GNUNET_HashCode * key, + void *value) { - GNUNET_free (value); + GNUNET_free(value); return GNUNET_YES; } @@ -807,24 +803,24 @@ regex_free_result (void *cls, * @param h the search context. */ void -REGEX_INTERNAL_search_cancel (struct REGEX_INTERNAL_Search *h) +REGEX_INTERNAL_search_cancel(struct REGEX_INTERNAL_Search *h) { unsigned int i; - GNUNET_free (h->description); - GNUNET_CONTAINER_multihashmap_iterate (h->dht_get_handles, - ®ex_cancel_dht_get, NULL); - GNUNET_CONTAINER_multihashmap_iterate (h->dht_get_results, - ®ex_free_result, NULL); - GNUNET_CONTAINER_multihashmap_destroy (h->dht_get_results); - GNUNET_CONTAINER_multihashmap_destroy (h->dht_get_handles); + GNUNET_free(h->description); + GNUNET_CONTAINER_multihashmap_iterate(h->dht_get_handles, + ®ex_cancel_dht_get, NULL); + GNUNET_CONTAINER_multihashmap_iterate(h->dht_get_results, + ®ex_free_result, NULL); + GNUNET_CONTAINER_multihashmap_destroy(h->dht_get_results); + GNUNET_CONTAINER_multihashmap_destroy(h->dht_get_handles); if (0 < h->n_contexts) - { - for (i = 0; i < h->n_contexts; i++) - GNUNET_free (h->contexts[i]); - GNUNET_free (h->contexts); - } - GNUNET_free (h); + { + for (i = 0; i < h->n_contexts; i++) + GNUNET_free(h->contexts[i]); + GNUNET_free(h->contexts); + } + GNUNET_free(h); } diff --git a/src/regex/regex_internal_lib.h b/src/regex/regex_internal_lib.h index bbf89758e..9cb925a17 100644 --- a/src/regex/regex_internal_lib.h +++ b/src/regex/regex_internal_lib.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/regex_internal_lib.h * @brief library to parse regular expressions into dfa @@ -64,9 +64,9 @@ struct REGEX_INTERNAL_Automaton; * @return DFA, needs to be freed using #REGEX_INTERNAL_automaton_destroy(). */ struct REGEX_INTERNAL_Automaton * -REGEX_INTERNAL_construct_dfa (const char *regex, - const size_t len, - unsigned int max_path_len); +REGEX_INTERNAL_construct_dfa(const char *regex, + const size_t len, + unsigned int max_path_len); /** @@ -76,7 +76,7 @@ REGEX_INTERNAL_construct_dfa (const char *regex, * @param a automaton to be destroyed. */ void -REGEX_INTERNAL_automaton_destroy (struct REGEX_INTERNAL_Automaton *a); +REGEX_INTERNAL_automaton_destroy(struct REGEX_INTERNAL_Automaton *a); /** @@ -88,8 +88,8 @@ REGEX_INTERNAL_automaton_destroy (struct REGEX_INTERNAL_Automaton *a); * @return 0 if string matches, non 0 otherwise. */ int -REGEX_INTERNAL_eval (struct REGEX_INTERNAL_Automaton *a, - const char *string); +REGEX_INTERNAL_eval(struct REGEX_INTERNAL_Automaton *a, + const char *string); /** @@ -103,9 +103,9 @@ REGEX_INTERNAL_eval (struct REGEX_INTERNAL_Automaton *a, * to construct the key */ size_t -REGEX_INTERNAL_get_first_key (const char *input_string, - size_t string_len, - struct GNUNET_HashCode * key); +REGEX_INTERNAL_get_first_key(const char *input_string, + size_t string_len, + struct GNUNET_HashCode * key); /** @@ -136,9 +136,9 @@ typedef void * @param iterator_cls closure. */ void -REGEX_INTERNAL_iterate_all_edges (struct REGEX_INTERNAL_Automaton *a, - REGEX_INTERNAL_KeyIterator iterator, - void *iterator_cls); +REGEX_INTERNAL_iterate_all_edges(struct REGEX_INTERNAL_Automaton *a, + REGEX_INTERNAL_KeyIterator iterator, + void *iterator_cls); /** @@ -152,9 +152,9 @@ REGEX_INTERNAL_iterate_all_edges (struct REGEX_INTERNAL_Automaton *a, * @param iterator_cls closure. */ void -REGEX_INTERNAL_iterate_reachable_edges (struct REGEX_INTERNAL_Automaton *a, - REGEX_INTERNAL_KeyIterator iterator, - void *iterator_cls); +REGEX_INTERNAL_iterate_reachable_edges(struct REGEX_INTERNAL_Automaton *a, + REGEX_INTERNAL_KeyIterator iterator, + void *iterator_cls); @@ -182,11 +182,11 @@ struct REGEX_INTERNAL_Search; * Must be freed by calling #REGEX_INTERNAL_announce_cancel(). */ struct REGEX_INTERNAL_Announcement * -REGEX_INTERNAL_announce (struct GNUNET_DHT_Handle *dht, - const struct GNUNET_CRYPTO_EddsaPrivateKey *priv, - const char *regex, - uint16_t compression, - struct GNUNET_STATISTICS_Handle *stats); +REGEX_INTERNAL_announce(struct GNUNET_DHT_Handle *dht, + const struct GNUNET_CRYPTO_EddsaPrivateKey *priv, + const char *regex, + uint16_t compression, + struct GNUNET_STATISTICS_Handle *stats); /** @@ -196,7 +196,7 @@ REGEX_INTERNAL_announce (struct GNUNET_DHT_Handle *dht, * @param h Handle returned by a previous #REGEX_INTERNAL_announce() call. */ void -REGEX_INTERNAL_reannounce (struct REGEX_INTERNAL_Announcement *h); +REGEX_INTERNAL_reannounce(struct REGEX_INTERNAL_Announcement *h); /** @@ -206,7 +206,7 @@ REGEX_INTERNAL_reannounce (struct REGEX_INTERNAL_Announcement *h); * @param h Handle returned by a previous #REGEX_INTERNAL_announce() call. */ void -REGEX_INTERNAL_announce_cancel (struct REGEX_INTERNAL_Announcement *h); +REGEX_INTERNAL_announce_cancel(struct REGEX_INTERNAL_Announcement *h); /** @@ -242,11 +242,11 @@ typedef void * Must be freed by calling #REGEX_INTERNAL_search_cancel(). */ struct REGEX_INTERNAL_Search * -REGEX_INTERNAL_search (struct GNUNET_DHT_Handle *dht, - const char *string, - REGEX_INTERNAL_Found callback, - void *callback_cls, - struct GNUNET_STATISTICS_Handle *stats); +REGEX_INTERNAL_search(struct GNUNET_DHT_Handle *dht, + const char *string, + REGEX_INTERNAL_Found callback, + void *callback_cls, + struct GNUNET_STATISTICS_Handle *stats); /** * Stop search and free all data used by a #REGEX_INTERNAL_search() call. @@ -255,7 +255,7 @@ REGEX_INTERNAL_search (struct GNUNET_DHT_Handle *dht, * @param h Handle returned by a previous #REGEX_INTERNAL_search() call. */ void -REGEX_INTERNAL_search_cancel (struct REGEX_INTERNAL_Search *h); +REGEX_INTERNAL_search_cancel(struct REGEX_INTERNAL_Search *h); #if 0 /* keep Emacsens' auto-indent happy */ diff --git a/src/regex/regex_ipc.h b/src/regex/regex_ipc.h index 11c570178..5106ead24 100644 --- a/src/regex/regex_ipc.h +++ b/src/regex/regex_ipc.h @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/regex_ipc.h * @brief regex IPC messages (not called 'regex.h' due to conflict with @@ -31,9 +31,7 @@ /** * Request for regex service to announce capability. */ -struct AnnounceMessage -{ - +struct AnnounceMessage { /** * Type is GNUNET_MESSAGE_TYPE_REGEX_ANNOUNCE */ @@ -61,23 +59,20 @@ struct AnnounceMessage /** * Message to initiate regex search. */ -struct RegexSearchMessage -{ +struct RegexSearchMessage { /** * Type is GNUNET_MESSAGE_TYPE_REGEX_SEARCH */ struct GNUNET_MessageHeader header; /* followed by 0-terminated search string */ - }; /** * Result from regex search. */ -struct ResultMessage -{ +struct ResultMessage { /** * Type is GNUNET_MESSAGE_TYPE_REGEX_RESULT */ @@ -99,7 +94,6 @@ struct ResultMessage struct GNUNET_PeerIdentity id; /* followed by GET path and PUT path arrays */ - }; diff --git a/src/regex/regex_test_graph.c b/src/regex/regex_test_graph.c index 54ee1d17f..e809d578d 100644 --- a/src/regex/regex_test_graph.c +++ b/src/regex/regex_test_graph.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/regex/regex_test_graph.c * @brief functions for creating .dot graphs from regexes @@ -31,8 +31,7 @@ * Context for graph creation. Passed as the cls to * REGEX_TEST_automaton_save_graph_step. */ -struct REGEX_TEST_Graph_Context -{ +struct REGEX_TEST_Graph_Context { /** * File pointer to the dot file used for output. */ @@ -63,10 +62,10 @@ struct REGEX_TEST_Graph_Context * @param stack_size current size of the stack */ static void -scc_tarjan_strongconnect (unsigned int *scc_counter, - struct REGEX_INTERNAL_State *v, unsigned int *index, - struct REGEX_INTERNAL_State **stack, - unsigned int *stack_size) +scc_tarjan_strongconnect(unsigned int *scc_counter, + struct REGEX_INTERNAL_State *v, unsigned int *index, + struct REGEX_INTERNAL_State **stack, + unsigned int *stack_size) { struct REGEX_INTERNAL_State *w; struct REGEX_INTERNAL_Transition *t; @@ -78,32 +77,32 @@ scc_tarjan_strongconnect (unsigned int *scc_counter, v->contained = 1; for (t = v->transitions_head; NULL != t; t = t->next) - { - w = t->to_state; - - if (NULL == w) - continue; - - if (w->index < 0) { - scc_tarjan_strongconnect (scc_counter, w, index, stack, stack_size); - v->lowlink = (v->lowlink > w->lowlink) ? w->lowlink : v->lowlink; + w = t->to_state; + + if (NULL == w) + continue; + + if (w->index < 0) + { + scc_tarjan_strongconnect(scc_counter, w, index, stack, stack_size); + v->lowlink = (v->lowlink > w->lowlink) ? w->lowlink : v->lowlink; + } + else if (1 == w->contained) + v->lowlink = (v->lowlink > w->index) ? w->index : v->lowlink; } - else if (1 == w->contained) - v->lowlink = (v->lowlink > w->index) ? w->index : v->lowlink; - } if (v->lowlink == v->index) - { - (*scc_counter)++; - do { - w = stack[--(*stack_size)]; - w->contained = 0; - w->scc_id = *scc_counter; + (*scc_counter)++; + do + { + w = stack[--(*stack_size)]; + w->contained = 0; + w->scc_id = *scc_counter; + } + while (w != v); } - while (w != v); - } } @@ -114,7 +113,7 @@ scc_tarjan_strongconnect (unsigned int *scc_counter, * @param a the automaton for which SCCs should be computed and assigned. */ static void -scc_tarjan (struct REGEX_INTERNAL_Automaton *a) +scc_tarjan(struct REGEX_INTERNAL_Automaton *a) { unsigned int index; unsigned int scc_counter; @@ -123,21 +122,21 @@ scc_tarjan (struct REGEX_INTERNAL_Automaton *a) unsigned int stack_size; for (v = a->states_head; NULL != v; v = v->next) - { - v->contained = 0; - v->index = -1; - v->lowlink = -1; - } + { + v->contained = 0; + v->index = -1; + v->lowlink = -1; + } stack_size = 0; index = 0; scc_counter = 0; for (v = a->states_head; NULL != v; v = v->next) - { - if (v->index < 0) - scc_tarjan_strongconnect (&scc_counter, v, &index, stack, &stack_size); - } + { + if (v->index < 0) + scc_tarjan_strongconnect(&scc_counter, v, &index, stack, &stack_size); + } } @@ -151,8 +150,8 @@ scc_tarjan (struct REGEX_INTERNAL_Automaton *a) * @param s state. */ void -REGEX_TEST_automaton_save_graph_step (void *cls, unsigned int count, - struct REGEX_INTERNAL_State *s) +REGEX_TEST_automaton_save_graph_step(void *cls, unsigned int count, + struct REGEX_INTERNAL_State *s) { struct REGEX_TEST_Graph_Context *ctx = cls; struct REGEX_INTERNAL_Transition *ctran; @@ -162,100 +161,100 @@ REGEX_TEST_automaton_save_graph_step (void *cls, unsigned int count, char *to_name; if (GNUNET_YES == ctx->verbose) - GNUNET_asprintf (&name, "%i (%s) (%s) (%s)", s->dfs_id, s->name, s->proof, - GNUNET_h2s (&s->hash)); + GNUNET_asprintf(&name, "%i (%s) (%s) (%s)", s->dfs_id, s->name, s->proof, + GNUNET_h2s(&s->hash)); else - GNUNET_asprintf (&name, "%i", s->dfs_id); + GNUNET_asprintf(&name, "%i", s->dfs_id); if (s->accepting) - { - if (GNUNET_YES == ctx->coloring) { - GNUNET_asprintf (&s_acc, - "\"%s\" [shape=doublecircle, color=\"0.%i 0.8 0.95\"];\n", - name, s->scc_id * s->scc_id); + if (GNUNET_YES == ctx->coloring) + { + GNUNET_asprintf(&s_acc, + "\"%s\" [shape=doublecircle, color=\"0.%i 0.8 0.95\"];\n", + name, s->scc_id * s->scc_id); + } + else + { + GNUNET_asprintf(&s_acc, "\"%s\" [shape=doublecircle];\n", name, + s->scc_id); + } } - else + else if (GNUNET_YES == ctx->coloring) { - GNUNET_asprintf (&s_acc, "\"%s\" [shape=doublecircle];\n", name, - s->scc_id); + GNUNET_asprintf(&s_acc, + "\"%s\" [shape=circle, color=\"0.%i 0.8 0.95\"];\n", name, + s->scc_id * s->scc_id); } - } - else if (GNUNET_YES == ctx->coloring) - { - GNUNET_asprintf (&s_acc, - "\"%s\" [shape=circle, color=\"0.%i 0.8 0.95\"];\n", name, - s->scc_id * s->scc_id); - } else - { - GNUNET_asprintf (&s_acc, "\"%s\" [shape=circle];\n", name, s->scc_id); - } + { + GNUNET_asprintf(&s_acc, "\"%s\" [shape=circle];\n", name, s->scc_id); + } - GNUNET_assert (NULL != s_acc); + GNUNET_assert(NULL != s_acc); - fwrite (s_acc, strlen (s_acc), 1, ctx->filep); - GNUNET_free (s_acc); + fwrite(s_acc, strlen(s_acc), 1, ctx->filep); + GNUNET_free(s_acc); s_acc = NULL; for (ctran = s->transitions_head; NULL != ctran; ctran = ctran->next) - { - if (NULL == ctran->to_state) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Transition from State %i has no state for transitioning\n", - s->id); - continue; - } - - if (GNUNET_YES == ctx->verbose) { - GNUNET_asprintf (&to_name, "%i (%s) (%s) (%s)", ctran->to_state->dfs_id, - ctran->to_state->name, ctran->to_state->proof, - GNUNET_h2s (&ctran->to_state->hash)); - } - else - GNUNET_asprintf (&to_name, "%i", ctran->to_state->dfs_id); - - if (NULL == ctran->label) - { - if (GNUNET_YES == ctx->coloring) - { - GNUNET_asprintf (&s_tran, - "\"%s\" -> \"%s\" [label = \"ε\", color=\"0.%i 0.8 0.95\"];\n", - name, to_name, s->scc_id * s->scc_id); - } + if (NULL == ctran->to_state) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Transition from State %i has no state for transitioning\n", + s->id); + continue; + } + + if (GNUNET_YES == ctx->verbose) + { + GNUNET_asprintf(&to_name, "%i (%s) (%s) (%s)", ctran->to_state->dfs_id, + ctran->to_state->name, ctran->to_state->proof, + GNUNET_h2s(&ctran->to_state->hash)); + } else - { - GNUNET_asprintf (&s_tran, "\"%s\" -> \"%s\" [label = \"ε\"];\n", name, - to_name, s->scc_id); - } - } - else - { - if (GNUNET_YES == ctx->coloring) - { - GNUNET_asprintf (&s_tran, - "\"%s\" -> \"%s\" [label = \"%s\", color=\"0.%i 0.8 0.95\"];\n", - name, to_name, ctran->label, s->scc_id * s->scc_id); - } + GNUNET_asprintf(&to_name, "%i", ctran->to_state->dfs_id); + + if (NULL == ctran->label) + { + if (GNUNET_YES == ctx->coloring) + { + GNUNET_asprintf(&s_tran, + "\"%s\" -> \"%s\" [label = \"ε\", color=\"0.%i 0.8 0.95\"];\n", + name, to_name, s->scc_id * s->scc_id); + } + else + { + GNUNET_asprintf(&s_tran, "\"%s\" -> \"%s\" [label = \"ε\"];\n", name, + to_name, s->scc_id); + } + } else - { - GNUNET_asprintf (&s_tran, "\"%s\" -> \"%s\" [label = \"%s\"];\n", name, - to_name, ctran->label, s->scc_id); - } + { + if (GNUNET_YES == ctx->coloring) + { + GNUNET_asprintf(&s_tran, + "\"%s\" -> \"%s\" [label = \"%s\", color=\"0.%i 0.8 0.95\"];\n", + name, to_name, ctran->label, s->scc_id * s->scc_id); + } + else + { + GNUNET_asprintf(&s_tran, "\"%s\" -> \"%s\" [label = \"%s\"];\n", name, + to_name, ctran->label, s->scc_id); + } + } + + GNUNET_free(to_name); + + GNUNET_assert(NULL != s_tran); + + fwrite(s_tran, strlen(s_tran), 1, ctx->filep); + GNUNET_free(s_tran); + s_tran = NULL; } - GNUNET_free (to_name); - - GNUNET_assert (NULL != s_tran); - - fwrite (s_tran, strlen (s_tran), 1, ctx->filep); - GNUNET_free (s_tran); - s_tran = NULL; - } - - GNUNET_free (name); + GNUNET_free(name); } @@ -268,51 +267,51 @@ REGEX_TEST_automaton_save_graph_step (void *cls, unsigned int count, * mode */ void -REGEX_TEST_automaton_save_graph (struct REGEX_INTERNAL_Automaton *a, - const char *filename, - enum REGEX_TEST_GraphSavingOptions options) +REGEX_TEST_automaton_save_graph(struct REGEX_INTERNAL_Automaton *a, + const char *filename, + enum REGEX_TEST_GraphSavingOptions options) { char *start; char *end; struct REGEX_TEST_Graph_Context ctx; if (NULL == a) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not print NFA, was NULL!"); - return; - } - - if (NULL == filename || strlen (filename) < 1) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "No Filename given!"); - return; - } - - ctx.filep = fopen (filename, "w"); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not print NFA, was NULL!"); + return; + } + + if (NULL == filename || strlen(filename) < 1) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No Filename given!"); + return; + } + + ctx.filep = fopen(filename, "w"); ctx.verbose = - (0 == (options & REGEX_TEST_GRAPH_VERBOSE)) ? GNUNET_NO : GNUNET_YES; + (0 == (options & REGEX_TEST_GRAPH_VERBOSE)) ? GNUNET_NO : GNUNET_YES; ctx.coloring = - (0 == (options & REGEX_TEST_GRAPH_COLORING)) ? GNUNET_NO : GNUNET_YES; + (0 == (options & REGEX_TEST_GRAPH_COLORING)) ? GNUNET_NO : GNUNET_YES; if (NULL == ctx.filep) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not open file for writing: %s", - filename); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not open file for writing: %s", + filename); + return; + } /* First add the SCCs to the automaton, so we can color them nicely */ if (GNUNET_YES == ctx.coloring) - scc_tarjan (a); + scc_tarjan(a); start = "digraph G {\nrankdir=LR\n"; - fwrite (start, strlen (start), 1, ctx.filep); + fwrite(start, strlen(start), 1, ctx.filep); - REGEX_INTERNAL_automaton_traverse (a, a->start, NULL, NULL, - ®EX_TEST_automaton_save_graph_step, - &ctx); + REGEX_INTERNAL_automaton_traverse(a, a->start, NULL, NULL, + ®EX_TEST_automaton_save_graph_step, + &ctx); end = "\n}\n"; - fwrite (end, strlen (end), 1, ctx.filep); - fclose (ctx.filep); + fwrite(end, strlen(end), 1, ctx.filep); + fclose(ctx.filep); } diff --git a/src/regex/regex_test_lib.c b/src/regex/regex_test_lib.c index 7becd567c..d8eb22370 100644 --- a/src/regex/regex_test_lib.c +++ b/src/regex/regex_test_lib.c @@ -11,7 +11,7 @@ * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. - * + * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . @@ -32,8 +32,7 @@ /** * Struct to hold the tree formed by prefix-combining the regexes. */ -struct RegexCombineCtx -{ +struct RegexCombineCtx { /** * Child nodes with same prefix and token. */ @@ -62,14 +61,15 @@ struct RegexCombineCtx * @return Int in range [0, (base-1)] */ static int -c2i (char c, int size) +c2i(char c, int size) { switch (size) - { + { case 2: case 8: return c - '0'; break; + case 16: if (c >= '0' && c <= '9') return c - '0'; @@ -78,16 +78,17 @@ c2i (char c, int size) else if (c >= 'a' && c <= 'f') return c - 'a' + 10; else - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Cannot convert char %c in base %u\n", - c, size); - GNUNET_assert (0); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Cannot convert char %c in base %u\n", + c, size); + GNUNET_assert(0); + } break; + default: - GNUNET_assert (0); - } + GNUNET_assert(0); + } } @@ -97,10 +98,10 @@ c2i (char c, int size) * @param n Indentation level */ static void -space (int n) +space(int n) { for (int i = 0; i < n; i++) - fprintf (stderr, "| "); + fprintf(stderr, "| "); } @@ -111,24 +112,24 @@ space (int n) * @param level Indentation level to start with */ static void -debugctx (struct RegexCombineCtx *ctx, int level) +debugctx(struct RegexCombineCtx *ctx, int level) { #if DEBUG_REGEX if (NULL != ctx->s) - { - space (level - 1); - fprintf (stderr, "%u:'%s'\n", c2i(ctx->s[0], ctx->size), ctx->s); - } + { + space(level - 1); + fprintf(stderr, "%u:'%s'\n", c2i(ctx->s[0], ctx->size), ctx->s); + } else - fprintf (stderr, "ROOT (base %u)\n", ctx->size); + fprintf(stderr, "ROOT (base %u)\n", ctx->size); for (unsigned int i = 0; i < ctx->size; i++) - { - if (NULL != ctx->children[i]) { - space (level); - debugctx (ctx->children[i], level + 1); + if (NULL != ctx->children[i]) + { + space(level); + debugctx(ctx->children[i], level + 1); + } } - } fflush(stderr); #endif } @@ -141,8 +142,8 @@ debugctx (struct RegexCombineCtx *ctx, int level) * @param regex Regex to add. */ static void -regex_add (struct RegexCombineCtx *ctx, - const char *regex); +regex_add(struct RegexCombineCtx *ctx, + const char *regex); /** @@ -151,14 +152,14 @@ regex_add (struct RegexCombineCtx *ctx, * @param alphabet_size Size of the alphabet (and the Trie array) */ static struct RegexCombineCtx * -new_regex_ctx (unsigned int alphabet_size) +new_regex_ctx(unsigned int alphabet_size) { struct RegexCombineCtx *ctx; size_t array_size; array_size = sizeof(struct RegexCombineCtx *) * alphabet_size; - ctx = GNUNET_new (struct RegexCombineCtx); - ctx->children = GNUNET_malloc (array_size); + ctx = GNUNET_new(struct RegexCombineCtx); + ctx->children = GNUNET_malloc(array_size); ctx->size = alphabet_size; return ctx; @@ -166,19 +167,19 @@ new_regex_ctx (unsigned int alphabet_size) static void -move_children (struct RegexCombineCtx *dst, - const struct RegexCombineCtx *src) +move_children(struct RegexCombineCtx *dst, + const struct RegexCombineCtx *src) { size_t array_size; array_size = sizeof(struct RegexCombineCtx *) * src->size; - GNUNET_memcpy (dst->children, - src->children, - array_size); + GNUNET_memcpy(dst->children, + src->children, + array_size); for (unsigned int i = 0; i < src->size; i++) - { - src->children[i] = NULL; - } + { + src->children[i] = NULL; + } } @@ -190,7 +191,7 @@ move_children (struct RegexCombineCtx *dst, * @return Regex that matches any of the added regexes. */ static char * -regex_combine (struct RegexCombineCtx *ctx) +regex_combine(struct RegexCombineCtx *ctx) { struct RegexCombineCtx *p; unsigned int i; @@ -200,56 +201,56 @@ regex_combine (struct RegexCombineCtx *ctx) char *s; int opt; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "new combine %s\n", ctx->s); - regex = GNUNET_strdup (""); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "new combine %s\n", ctx->s); + regex = GNUNET_strdup(""); opt = GNUNET_NO; for (i = 0; i < ctx->size; i++) - { - p = ctx->children[i]; - if (NULL == p) - continue; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "adding '%s' to innner %s\n", - p->s, ctx->s); - s = regex_combine (p); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " total '%s'\n", s); - if (strlen(s) == 0) { - opt = GNUNET_YES; - } - else - { - GNUNET_asprintf (&tmp, "%s%s|", regex, s); - GNUNET_free_non_null (regex); - regex = tmp; + p = ctx->children[i]; + if (NULL == p) + continue; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "adding '%s' to innner %s\n", + p->s, ctx->s); + s = regex_combine(p); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, " total '%s'\n", s); + if (strlen(s) == 0) + { + opt = GNUNET_YES; + } + else + { + GNUNET_asprintf(&tmp, "%s%s|", regex, s); + GNUNET_free_non_null(regex); + regex = tmp; + } + GNUNET_free_non_null(s); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, " so far '%s' for inner %s\n", regex, ctx->s); } - GNUNET_free_non_null (s); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " so far '%s' for inner %s\n", regex, ctx->s); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "opt: %d, innner: '%s'\n", opt, regex); - len = strlen (regex); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "opt: %d, innner: '%s'\n", opt, regex); + len = strlen(regex); if (0 == len) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "empty, returning ''\n"); - GNUNET_free (regex); - return NULL == ctx->s ? NULL : GNUNET_strdup (ctx->s); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "empty, returning ''\n"); + GNUNET_free(regex); + return NULL == ctx->s ? NULL : GNUNET_strdup(ctx->s); + } if ('|' == regex[len - 1]) regex[len - 1] = '\0'; if (NULL != ctx->s) - { - if (opt) - GNUNET_asprintf (&s, "%s(%s)?", ctx->s, regex); - else - GNUNET_asprintf (&s, "%s(%s)", ctx->s, regex); - GNUNET_free (regex); - regex = s; - } - - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "partial: %s\n", regex); + { + if (opt) + GNUNET_asprintf(&s, "%s(%s)?", ctx->s, regex); + else + GNUNET_asprintf(&s, "%s(%s)", ctx->s, regex); + GNUNET_free(regex); + regex = s; + } + + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "partial: %s\n", regex); return regex; } @@ -263,22 +264,22 @@ regex_combine (struct RegexCombineCtx *ctx) * @return Number of characters of matching prefix. */ static unsigned int -get_prefix_length (const char *s1, const char *s2) +get_prefix_length(const char *s1, const char *s2) { unsigned int l1; unsigned int l2; unsigned int limit; unsigned int i; - l1 = strlen (s1); - l2 = strlen (s2); + l1 = strlen(s1); + l2 = strlen(s2); limit = l1 > l2 ? l2 : l1; for (i = 0; i < limit; i++) - { - if (s1[i] != s2[i]) - return i; - } + { + if (s1[i] != s2[i]) + return i; + } return limit; } @@ -293,7 +294,7 @@ get_prefix_length (const char *s1, const char *s2) * @return Child with the longest prefix, NULL if no child matches. */ static struct RegexCombineCtx * -get_longest_prefix (struct RegexCombineCtx *ctx, const char *regex) +get_longest_prefix(struct RegexCombineCtx *ctx, const char *regex) { struct RegexCombineCtx *p; struct RegexCombineCtx *best; @@ -305,26 +306,26 @@ get_longest_prefix (struct RegexCombineCtx *ctx, const char *regex) best = NULL; for (i = 0; i < ctx->size; i++) - { - p = ctx->children[i]; - if (NULL == p) - continue; - - l = get_prefix_length (p->s, regex); - if (l > best_l) { - GNUNET_break (0 == best_l); - best = p; - best_l = l; + p = ctx->children[i]; + if (NULL == p) + continue; + + l = get_prefix_length(p->s, regex); + if (l > best_l) + { + GNUNET_break(0 == best_l); + best = p; + best_l = l; + } } - } return best; } static void -regex_add_multiple (struct RegexCombineCtx *ctx, - const char *regex, - struct RegexCombineCtx **children) +regex_add_multiple(struct RegexCombineCtx *ctx, + const char *regex, + struct RegexCombineCtx **children) { char tmp[2]; long unsigned int i; @@ -333,43 +334,43 @@ regex_add_multiple (struct RegexCombineCtx *ctx, unsigned int count; if ('(' != regex[0]) - { - GNUNET_assert (0); - } + { + GNUNET_assert(0); + } /* Does the regex cover *all* possible children? Then don't add any, * as it will be covered by the post-regex "(a-z)*" */ - l = strlen (regex); + l = strlen(regex); count = 0; for (i = 1UL; i < l; i++) - { - if (regex[i] != '|' && regex[i] != ')') { - count++; + if (regex[i] != '|' && regex[i] != ')') + { + count++; + } } - } if (count == ctx->size) - { - return; - } + { + return; + } /* Add every component as a child node */ tmp[1] = '\0'; for (i = 1UL; i < l; i++) - { - if (regex[i] != '|' && regex[i] != ')') { - tmp[0] = regex[i]; - newctx = new_regex_ctx(ctx->size); - newctx->s = GNUNET_strdup (tmp); - if (children != NULL) - GNUNET_memcpy (newctx->children, - children, - sizeof (*children) * ctx->size); - ctx->children[c2i(tmp[0], ctx->size)] = newctx; + if (regex[i] != '|' && regex[i] != ')') + { + tmp[0] = regex[i]; + newctx = new_regex_ctx(ctx->size); + newctx->s = GNUNET_strdup(tmp); + if (children != NULL) + GNUNET_memcpy(newctx->children, + children, + sizeof(*children) * ctx->size); + ctx->children[c2i(tmp[0], ctx->size)] = newctx; + } } - } } /** @@ -383,19 +384,19 @@ regex_add_multiple (struct RegexCombineCtx *ctx, * @param prefix_l Lenght of common prefix of the new regex and @a ctx->s */ static void -regex_split (struct RegexCombineCtx *ctx, - unsigned int len, - unsigned int prefix_l) +regex_split(struct RegexCombineCtx *ctx, + unsigned int len, + unsigned int prefix_l) { struct RegexCombineCtx *newctx; unsigned int idx; char *suffix; - suffix = GNUNET_malloc (len - prefix_l + 1); + suffix = GNUNET_malloc(len - prefix_l + 1); /* * We can use GNUNET_strlcpy because ctx->s is null-terminated */ - GNUNET_strlcpy (suffix, &ctx->s[prefix_l], len - prefix_l + 1); + GNUNET_strlcpy(suffix, &ctx->s[prefix_l], len - prefix_l + 1); /* Suffix saved, truncate current node so it only contains the prefix, * copy any children nodes to put as grandchildren and initialize new empty @@ -405,21 +406,21 @@ regex_split (struct RegexCombineCtx *ctx, /* If the suffix is an OR expression, add multiple children */ if ('(' == suffix[0]) - { - struct RegexCombineCtx **tmp; - - tmp = ctx->children; - ctx->children = GNUNET_malloc (sizeof(*tmp) * ctx->size); - regex_add_multiple (ctx, suffix, tmp); - GNUNET_free (suffix); - GNUNET_free (tmp); - return; - } + { + struct RegexCombineCtx **tmp; + + tmp = ctx->children; + ctx->children = GNUNET_malloc(sizeof(*tmp) * ctx->size); + regex_add_multiple(ctx, suffix, tmp); + GNUNET_free(suffix); + GNUNET_free(tmp); + return; + } /* The suffix is a normal string, add as one node */ - newctx = new_regex_ctx (ctx->size); + newctx = new_regex_ctx(ctx->size); newctx->s = suffix; - move_children (newctx, ctx); + move_children(newctx, ctx); idx = c2i(suffix[0], ctx->size); ctx->children[idx] = newctx; } @@ -432,7 +433,7 @@ regex_split (struct RegexCombineCtx *ctx, * @param regex Regex to add. */ static void -regex_add (struct RegexCombineCtx *ctx, const char *regex) +regex_add(struct RegexCombineCtx *ctx, const char *regex) { struct RegexCombineCtx *p; struct RegexCombineCtx *newctx; @@ -443,54 +444,54 @@ regex_add (struct RegexCombineCtx *ctx, const char *regex) size_t len; int idx; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "regex_add '%s' into '%s'\n", - regex, ctx->s); - l = strlen (regex); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "regex_add '%s' into '%s'\n", + regex, ctx->s); + l = strlen(regex); if (0UL == l) return; /* If the regex is in the form of (a|b|c), add every character separately */ if ('(' == regex[0]) - { - regex_add_multiple (ctx, regex, NULL); - return; - } + { + regex_add_multiple(ctx, regex, NULL); + return; + } - p = get_longest_prefix (ctx, regex); + p = get_longest_prefix(ctx, regex); if (NULL != p) - { - /* There is some prefix match, reduce regex and try again */ - prefix_l = get_prefix_length (p->s, regex); - rest_s = &p->s[prefix_l]; - rest_r = ®ex[prefix_l]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "chosen '%s' [%u]\n", p->s, prefix_l); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "prefix r '%.*s'\n", prefix_l, p->s); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "rest r '%s'\n", rest_r); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "rest s '%s'\n", rest_s); - len = strlen (p->s); - if (prefix_l < len) { - regex_split (p, len, prefix_l); + /* There is some prefix match, reduce regex and try again */ + prefix_l = get_prefix_length(p->s, regex); + rest_s = &p->s[prefix_l]; + rest_r = ®ex[prefix_l]; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "chosen '%s' [%u]\n", p->s, prefix_l); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "prefix r '%.*s'\n", prefix_l, p->s); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "rest r '%s'\n", rest_r); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "rest s '%s'\n", rest_s); + len = strlen(p->s); + if (prefix_l < len) + { + regex_split(p, len, prefix_l); + } + regex_add(p, rest_r); + return; } - regex_add (p, rest_r); - return; - } /* There is no prefix match, add new */ idx = c2i(regex[0], ctx->size); if (NULL == ctx->children[idx] && NULL != ctx->s) - { - /* this was the end before, add empty string */ - newctx = new_regex_ctx (ctx->size); - newctx->s = GNUNET_strdup (""); - ctx->children[idx] = newctx; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " no match\n"); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " new state %s\n", regex); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " under %s\n", ctx->s); + { + /* this was the end before, add empty string */ + newctx = new_regex_ctx(ctx->size); + newctx->s = GNUNET_strdup(""); + ctx->children[idx] = newctx; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, " no match\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, " new state %s\n", regex); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, " under %s\n", ctx->s); newctx = new_regex_ctx(ctx->size); - newctx->s = GNUNET_strdup (regex); + newctx->s = GNUNET_strdup(regex); ctx->children[idx] = newctx; } @@ -501,7 +502,7 @@ regex_add (struct RegexCombineCtx *ctx, const char *regex) * @param ctx Context to free. */ static void -regex_ctx_destroy (struct RegexCombineCtx *ctx) +regex_ctx_destroy(struct RegexCombineCtx *ctx) { unsigned int i; @@ -509,12 +510,12 @@ regex_ctx_destroy (struct RegexCombineCtx *ctx) return; for (i = 0; i < ctx->size; i++) - { - regex_ctx_destroy (ctx->children[i]); - } - GNUNET_free_non_null (ctx->s); /* 's' on root node is null */ - GNUNET_free (ctx->children); - GNUNET_free (ctx); + { + regex_ctx_destroy(ctx->children[i]); + } + GNUNET_free_non_null(ctx->s); /* 's' on root node is null */ + GNUNET_free(ctx->children); + GNUNET_free(ctx); } @@ -533,27 +534,27 @@ regex_ctx_destroy (struct RegexCombineCtx *ctx) * @return A string with a single regex that matches any of the original regexes */ char * -REGEX_TEST_combine (char * const regexes[], unsigned int alphabet_size) +REGEX_TEST_combine(char * const regexes[], unsigned int alphabet_size) { unsigned int i; char *combined; const char *current; struct RegexCombineCtx *ctx; - ctx = new_regex_ctx (alphabet_size); + ctx = new_regex_ctx(alphabet_size); for (i = 0; regexes[i]; i++) - { - current = regexes[i]; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Regex %u: %s\n", i, current); - regex_add (ctx, current); - debugctx (ctx, 0); - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\nCombining...\n"); - debugctx (ctx, 0); + { + current = regexes[i]; + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Regex %u: %s\n", i, current); + regex_add(ctx, current); + debugctx(ctx, 0); + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "\nCombining...\n"); + debugctx(ctx, 0); - combined = regex_combine (ctx); + combined = regex_combine(ctx); - regex_ctx_destroy (ctx); + regex_ctx_destroy(ctx); return combined; } @@ -569,7 +570,7 @@ REGEX_TEST_combine (char * const regexes[], unsigned int alphabet_size) * @return A newly allocated, NULL terminated array of regexes. */ char ** -REGEX_TEST_read_from_file (const char *filename) +REGEX_TEST_read_from_file(const char *filename) { struct GNUNET_DISK_FileHandle *f; unsigned int nr; @@ -580,54 +581,55 @@ REGEX_TEST_read_from_file (const char *filename) char *regex; char **regexes; - f = GNUNET_DISK_file_open (filename, - GNUNET_DISK_OPEN_READ, - GNUNET_DISK_PERM_NONE); + f = GNUNET_DISK_file_open(filename, + GNUNET_DISK_OPEN_READ, + GNUNET_DISK_PERM_NONE); if (NULL == f) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Can't open file %s for reading\n", filename); - return NULL; - } - if (GNUNET_OK != GNUNET_DISK_file_handle_size (f, &size)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Can't get size of file %s\n", filename); - GNUNET_DISK_file_close (f); - return NULL; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "using file %s, size %llu\n", - filename, (unsigned long long) size); - - buffer = GNUNET_malloc (size + 1); - GNUNET_DISK_file_read (f, buffer, size); - GNUNET_DISK_file_close (f); - regexes = GNUNET_malloc (sizeof (char *)); + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Can't open file %s for reading\n", filename); + return NULL; + } + if (GNUNET_OK != GNUNET_DISK_file_handle_size(f, &size)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Can't get size of file %s\n", filename); + GNUNET_DISK_file_close(f); + return NULL; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "using file %s, size %llu\n", + filename, (unsigned long long)size); + + buffer = GNUNET_malloc(size + 1); + GNUNET_DISK_file_read(f, buffer, size); + GNUNET_DISK_file_close(f); + regexes = GNUNET_malloc(sizeof(char *)); nr = 1; offset = 0; regex = NULL; do - { - if (NULL == regex) - regex = GNUNET_malloc (size + 1); - len = (size_t) sscanf (&buffer[offset], "%s", regex); - if (0 == len) - break; - len = strlen (regex); - offset += len + 1; - if (len < 1) - continue; - regex[len] = '\0'; - regex = GNUNET_realloc (regex, len + 1); - GNUNET_array_grow (regexes, nr, nr + 1); - GNUNET_assert (NULL == regexes[nr - 2]); - regexes[nr - 2] = regex; - regexes[nr - 1] = NULL; - regex = NULL; - } while (offset < size); - GNUNET_free_non_null (regex); - GNUNET_free (buffer); + { + if (NULL == regex) + regex = GNUNET_malloc(size + 1); + len = (size_t)sscanf(&buffer[offset], "%s", regex); + if (0 == len) + break; + len = strlen(regex); + offset += len + 1; + if (len < 1) + continue; + regex[len] = '\0'; + regex = GNUNET_realloc(regex, len + 1); + GNUNET_array_grow(regexes, nr, nr + 1); + GNUNET_assert(NULL == regexes[nr - 2]); + regexes[nr - 2] = regex; + regexes[nr - 1] = NULL; + regex = NULL; + } + while (offset < size); + GNUNET_free_non_null(regex); + GNUNET_free(buffer); return regexes; } @@ -639,13 +641,13 @@ REGEX_TEST_read_from_file (const char *filename) * @param regexes NULL-terminated array of regexes. */ void -REGEX_TEST_free_from_file (char **regexes) +REGEX_TEST_free_from_file(char **regexes) { unsigned int i; for (i = 0; regexes[i]; i++) - GNUNET_free (regexes[i]); - GNUNET_free (regexes); + GNUNET_free(regexes[i]); + GNUNET_free(regexes); } /* end of regex_test_lib.c */ diff --git a/src/regex/regex_test_lib.h b/src/regex/regex_test_lib.h index 226a0fbb6..fe4b30498 100644 --- a/src/regex/regex_test_lib.h +++ b/src/regex/regex_test_lib.h @@ -11,7 +11,7 @@ * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. - * + * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . @@ -54,7 +54,7 @@ extern "C" * @return A string with a single regex that matches any of the original regexes */ char * -REGEX_TEST_combine (char * const regexes[], unsigned int alphabet_size); +REGEX_TEST_combine(char * const regexes[], unsigned int alphabet_size); /** @@ -67,7 +67,7 @@ REGEX_TEST_combine (char * const regexes[], unsigned int alphabet_size); * @return A newly allocated, NULL terminated array of regexes. */ char ** -REGEX_TEST_read_from_file (const char *filename); +REGEX_TEST_read_from_file(const char *filename); /** @@ -76,7 +76,7 @@ REGEX_TEST_read_from_file (const char *filename); * @param regexes NULL-terminated array of regexes. */ void -REGEX_TEST_free_from_file (char **regexes); +REGEX_TEST_free_from_file(char **regexes); /** @@ -93,7 +93,7 @@ REGEX_TEST_free_from_file (char **regexes); * needs to be freed, otherwise. */ char * -REGEX_TEST_generate_random_regex (size_t rx_length, char *matching_str); +REGEX_TEST_generate_random_regex(size_t rx_length, char *matching_str); /** @@ -106,15 +106,14 @@ REGEX_TEST_generate_random_regex (size_t rx_length, char *matching_str); * @return random string that needs to be freed. */ char * -REGEX_TEST_generate_random_string (size_t max_len); +REGEX_TEST_generate_random_string(size_t max_len); /** * Options for graph creation function * REGEX_TEST_automaton_save_graph. */ -enum REGEX_TEST_GraphSavingOptions -{ +enum REGEX_TEST_GraphSavingOptions { /** * Default. Do nothing special. */ @@ -142,9 +141,9 @@ enum REGEX_TEST_GraphSavingOptions * mode */ void -REGEX_TEST_automaton_save_graph (struct REGEX_INTERNAL_Automaton *a, - const char *filename, - enum REGEX_TEST_GraphSavingOptions options); +REGEX_TEST_automaton_save_graph(struct REGEX_INTERNAL_Automaton *a, + const char *filename, + enum REGEX_TEST_GraphSavingOptions options); diff --git a/src/regex/regex_test_random.c b/src/regex/regex_test_random.c index 7fcdd1e63..9a1e9665a 100644 --- a/src/regex/regex_test_random.c +++ b/src/regex/regex_test_random.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file src/regex/regex_test_random.c * @brief functions for creating random regular expressions and strings @@ -34,13 +34,13 @@ * @return random valid literal */ static char -get_random_literal () +get_random_literal() { uint32_t ridx; ridx = - GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, - (uint32_t) strlen (ALLOWED_LITERALS)); + GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, + (uint32_t)strlen(ALLOWED_LITERALS)); return ALLOWED_LITERALS[ridx]; } @@ -61,7 +61,7 @@ get_random_literal () * needs to be freed, otherwise. */ char * -REGEX_TEST_generate_random_regex (size_t rx_length, char *matching_str) +REGEX_TEST_generate_random_regex(size_t rx_length, char *matching_str) { char *rx; char *rx_p; @@ -80,56 +80,59 @@ REGEX_TEST_generate_random_regex (size_t rx_length, char *matching_str) else matching_strp = NULL; - rx = GNUNET_malloc (rx_length + 1); + rx = GNUNET_malloc(rx_length + 1); rx_p = rx; current_char = 0; last_was_op = 1; for (i = 0; i < rx_length; i++) - { - char_op_switch = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 2); - - if (0 == char_op_switch && !last_was_op) { - last_was_op = 1; - rx_op = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 4); - - switch (rx_op) - { - case 0: - current_char = '+'; - break; - case 1: - current_char = '*'; - break; - case 2: - current_char = '?'; - break; - case 3: - if (i < rx_length - 1) /* '|' cannot be at the end */ - current_char = '|'; - else - current_char = get_random_literal (); - break; - } + char_op_switch = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 2); + + if (0 == char_op_switch && !last_was_op) + { + last_was_op = 1; + rx_op = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 4); + + switch (rx_op) + { + case 0: + current_char = '+'; + break; + + case 1: + current_char = '*'; + break; + + case 2: + current_char = '?'; + break; + + case 3: + if (i < rx_length - 1) /* '|' cannot be at the end */ + current_char = '|'; + else + current_char = get_random_literal(); + break; + } + } + else + { + current_char = get_random_literal(); + last_was_op = 0; + } + + if (NULL != matching_strp && + (current_char != '+' && current_char != '*' && current_char != '?' && + current_char != '|')) + { + *matching_strp = current_char; + matching_strp++; + } + + *rx_p = current_char; + rx_p++; } - else - { - current_char = get_random_literal (); - last_was_op = 0; - } - - if (NULL != matching_strp && - (current_char != '+' && current_char != '*' && current_char != '?' && - current_char != '|')) - { - *matching_strp = current_char; - matching_strp++; - } - - *rx_p = current_char; - rx_p++; - } *rx_p = '\0'; if (NULL != matching_strp) *matching_strp = '\0'; @@ -148,22 +151,22 @@ REGEX_TEST_generate_random_regex (size_t rx_length, char *matching_str) * @return random string that needs to be freed. */ char * -REGEX_TEST_generate_random_string (size_t max_len) +REGEX_TEST_generate_random_string(size_t max_len) { unsigned int i; char *str; size_t len; if (1 > max_len) - return GNUNET_strdup (""); + return GNUNET_strdup(""); - len = (size_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max_len); - str = GNUNET_malloc (len + 1); + len = (size_t)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, max_len); + str = GNUNET_malloc(len + 1); for (i = 0; i < len; i++) - { - str[i] = get_random_literal (); - } + { + str[i] = get_random_literal(); + } str[i] = '\0'; diff --git a/src/regex/test_regex_api.c b/src/regex/test_regex_api.c index 7016bf9c4..2ee24800a 100644 --- a/src/regex/test_regex_api.c +++ b/src/regex/test_regex_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/test_regex_api.c * @brief base test case for regex api (and DHT functions) @@ -31,12 +31,12 @@ /** * How long until we really give up on a particular testcase portion? */ -#define TOTAL_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 600) +#define TOTAL_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 600) /** * How long until we give up on any particular operation (and retry)? */ -#define BASE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3) +#define BASE_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 3) static struct GNUNET_REGEX_Announcement *a; @@ -49,25 +49,25 @@ static struct GNUNET_SCHEDULER_Task *die_task; static void -end (void *cls) +end(void *cls) { die_task = NULL; - GNUNET_REGEX_announce_cancel (a); + GNUNET_REGEX_announce_cancel(a); a = NULL; - GNUNET_REGEX_search_cancel (s); + GNUNET_REGEX_search_cancel(s); s = NULL; ok = 0; } static void -end_badly () +end_badly() { die_task = NULL; - fprintf (stderr, "%s", "Testcase failed (timeout).\n"); - GNUNET_REGEX_announce_cancel (a); + fprintf(stderr, "%s", "Testcase failed (timeout).\n"); + GNUNET_REGEX_announce_cancel(a); a = NULL; - GNUNET_REGEX_search_cancel (s); + GNUNET_REGEX_search_cancel(s); s = NULL; ok = 1; } @@ -84,44 +84,44 @@ end_badly () * @param put_path_length Length of the put_path. */ static void -found_cb (void *cls, - const struct GNUNET_PeerIdentity *id, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length) +found_cb(void *cls, + const struct GNUNET_PeerIdentity *id, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length) { - GNUNET_SCHEDULER_cancel (die_task); + GNUNET_SCHEDULER_cancel(die_task); die_task = - GNUNET_SCHEDULER_add_now (&end, NULL); + GNUNET_SCHEDULER_add_now(&end, NULL); } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { die_task = - GNUNET_SCHEDULER_add_delayed (TOTAL_TIMEOUT, - &end_badly, NULL); - a = GNUNET_REGEX_announce (cfg, - "my long prefix - hello world(0|1)*", - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, - 5), - 1); - s = GNUNET_REGEX_search (cfg, - "my long prefix - hello world0101", - &found_cb, NULL); + GNUNET_SCHEDULER_add_delayed(TOTAL_TIMEOUT, + &end_badly, NULL); + a = GNUNET_REGEX_announce(cfg, + "my long prefix - hello world(0|1)*", + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, + 5), + 1); + s = GNUNET_REGEX_search(cfg, + "my long prefix - hello world0101", + &found_cb, NULL); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-regex-api", - "test_regex_api_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-regex-api", + "test_regex_api_data.conf", + &run, NULL)) return 1; return ok; } diff --git a/src/regex/test_regex_eval_api.c b/src/regex/test_regex_eval_api.c index f8565b380..88a05f912 100644 --- a/src/regex/test_regex_eval_api.c +++ b/src/regex/test_regex_eval_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/test_regex_eval_api.c * @brief test for regex.c @@ -29,14 +29,12 @@ #include "regex_test_lib.h" #include "regex_internal.h" -enum Match_Result -{ +enum Match_Result { match = 0, nomatch = 1 }; -struct Regex_String_Pair -{ +struct Regex_String_Pair { char *regex; int string_count; char *strings[20]; @@ -57,8 +55,8 @@ struct Regex_String_Pair * @return 0 on success, non 0 otherwise. */ int -test_random (unsigned int rx_length, unsigned int max_str_len, - unsigned int str_count) +test_random(unsigned int rx_length, unsigned int max_str_len, + unsigned int str_count) { unsigned int i; char *rand_rx; @@ -75,108 +73,108 @@ test_random (unsigned int rx_length, unsigned int max_str_len, char *canonical_regex = NULL; /* At least one string is needed for matching */ - GNUNET_assert (str_count > 0); + GNUNET_assert(str_count > 0); /* The string should be at least as long as the regex itself */ - GNUNET_assert (max_str_len >= rx_length); + GNUNET_assert(max_str_len >= rx_length); /* Generate random regex and a string that matches the regex */ - matching_str = GNUNET_malloc (rx_length + 1); - rand_rx = REGEX_TEST_generate_random_regex (rx_length, matching_str); + matching_str = GNUNET_malloc(rx_length + 1); + rand_rx = REGEX_TEST_generate_random_regex(rx_length, matching_str); /* Now match */ result = 0; for (i = 0; i < str_count; i++) - { - if (0 < i) { - matching_str = REGEX_TEST_generate_random_string (max_str_len); - } - - /* Match string using DFA */ - dfa = REGEX_INTERNAL_construct_dfa (rand_rx, strlen (rand_rx), 0); - if (NULL == dfa) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Constructing DFA failed\n"); - goto error; - } - - eval = REGEX_INTERNAL_eval (dfa, matching_str); - /* save the canonical regex for later comparison */ - canonical_regex = GNUNET_strdup (REGEX_INTERNAL_get_canonical_regex (dfa)); - REGEX_INTERNAL_automaton_destroy (dfa); - - /* Match string using glibc regex */ - if (0 != regcomp (&rx, rand_rx, REG_EXTENDED)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not compile regex using regcomp: %s\n", rand_rx); - goto error; - } - - eval_check = regexec (&rx, matching_str, 1, matchptr, 0); - regfree (&rx); - - /* We only want to match the whole string, because that's what our DFA does, - * too. */ - if (eval_check == 0 && - (matchptr[0].rm_so != 0 || matchptr[0].rm_eo != strlen (matching_str))) - eval_check = 1; - - /* Match canonical regex */ - dfa = - REGEX_INTERNAL_construct_dfa (canonical_regex, strlen (canonical_regex), - 0); - if (NULL == dfa) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Constructing DFA failed\n"); - goto error; - } - - eval_canonical = REGEX_INTERNAL_eval (dfa, matching_str); - REGEX_INTERNAL_automaton_destroy (dfa); - - if (0 != regcomp (&rx, canonical_regex, REG_EXTENDED)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not compile regex using regcomp: %s\n", - canonical_regex); - goto error; - } - - eval_canonical_check = regexec (&rx, matching_str, 1, matchptr, 0); - regfree (&rx); - - /* We only want to match the whole string, because that's what our DFA does, - * too. */ - if (eval_canonical_check == 0 && - (matchptr[0].rm_so != 0 || matchptr[0].rm_eo != strlen (matching_str))) - eval_canonical_check = 1; - - /* compare results */ - if (eval_check != eval || eval_canonical != eval_canonical_check) - { - regerror (eval_check, &rx, error, sizeof error); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Unexpected result:\nregex: %s\ncanonical_regex: %s\n\ + if (0 < i) + { + matching_str = REGEX_TEST_generate_random_string(max_str_len); + } + + /* Match string using DFA */ + dfa = REGEX_INTERNAL_construct_dfa(rand_rx, strlen(rand_rx), 0); + if (NULL == dfa) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Constructing DFA failed\n"); + goto error; + } + + eval = REGEX_INTERNAL_eval(dfa, matching_str); + /* save the canonical regex for later comparison */ + canonical_regex = GNUNET_strdup(REGEX_INTERNAL_get_canonical_regex(dfa)); + REGEX_INTERNAL_automaton_destroy(dfa); + + /* Match string using glibc regex */ + if (0 != regcomp(&rx, rand_rx, REG_EXTENDED)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not compile regex using regcomp: %s\n", rand_rx); + goto error; + } + + eval_check = regexec(&rx, matching_str, 1, matchptr, 0); + regfree(&rx); + + /* We only want to match the whole string, because that's what our DFA does, + * too. */ + if (eval_check == 0 && + (matchptr[0].rm_so != 0 || matchptr[0].rm_eo != strlen(matching_str))) + eval_check = 1; + + /* Match canonical regex */ + dfa = + REGEX_INTERNAL_construct_dfa(canonical_regex, strlen(canonical_regex), + 0); + if (NULL == dfa) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Constructing DFA failed\n"); + goto error; + } + + eval_canonical = REGEX_INTERNAL_eval(dfa, matching_str); + REGEX_INTERNAL_automaton_destroy(dfa); + + if (0 != regcomp(&rx, canonical_regex, REG_EXTENDED)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not compile regex using regcomp: %s\n", + canonical_regex); + goto error; + } + + eval_canonical_check = regexec(&rx, matching_str, 1, matchptr, 0); + regfree(&rx); + + /* We only want to match the whole string, because that's what our DFA does, + * too. */ + if (eval_canonical_check == 0 && + (matchptr[0].rm_so != 0 || matchptr[0].rm_eo != strlen(matching_str))) + eval_canonical_check = 1; + + /* compare results */ + if (eval_check != eval || eval_canonical != eval_canonical_check) + { + regerror(eval_check, &rx, error, sizeof error); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Unexpected result:\nregex: %s\ncanonical_regex: %s\n\ string: %s\ngnunet regex: %i\nglibc regex: %i\n\ canonical regex: %i\ncanonical regex glibc: %i\n\ glibc error: %s\n\n", rand_rx, canonical_regex, matching_str, - eval, eval_check, eval_canonical, eval_canonical_check, error); - result += 1; + eval, eval_check, eval_canonical, eval_canonical_check, error); + result += 1; + } + GNUNET_free(canonical_regex); + GNUNET_free(matching_str); + canonical_regex = NULL; + matching_str = NULL; } - GNUNET_free (canonical_regex); - GNUNET_free (matching_str); - canonical_regex = NULL; - matching_str = NULL; - } - GNUNET_free (rand_rx); + GNUNET_free(rand_rx); return result; error: - GNUNET_free_non_null (matching_str); - GNUNET_free_non_null (rand_rx); - GNUNET_free_non_null (canonical_regex); + GNUNET_free_non_null(matching_str); + GNUNET_free_non_null(rand_rx); + GNUNET_free_non_null(canonical_regex); return -1; } @@ -193,8 +191,8 @@ error: * @return 0 on successfull, non 0 otherwise */ int -test_automaton (struct REGEX_INTERNAL_Automaton *a, regex_t * rx, - struct Regex_String_Pair *rxstr) +test_automaton(struct REGEX_INTERNAL_Automaton *a, regex_t * rx, + struct Regex_String_Pair *rxstr) { int result; int eval; @@ -204,48 +202,48 @@ test_automaton (struct REGEX_INTERNAL_Automaton *a, regex_t * rx, int i; if (NULL == a) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Automaton was NULL\n"); - return 1; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Automaton was NULL\n"); + return 1; + } result = 0; for (i = 0; i < rxstr->string_count; i++) - { - eval = REGEX_INTERNAL_eval (a, rxstr->strings[i]); - eval_check = regexec (rx, rxstr->strings[i], 1, matchptr, 0); - - /* We only want to match the whole string, because that's what our DFA does, - * too. */ - if (eval_check == 0 && - (matchptr[0].rm_so != 0 || - matchptr[0].rm_eo != strlen (rxstr->strings[i]))) - eval_check = 1; - - if ((rxstr->expected_results[i] == match && (0 != eval || 0 != eval_check)) - || (rxstr->expected_results[i] == nomatch && - (0 == eval || 0 == eval_check))) { - result = 1; - regerror (eval_check, rx, error, sizeof error); - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unexpected result:\nregex: %s\ncanonical_regex: %s\n" - "string: %s\nexpected result: %i\n" - "gnunet regex: %i\nglibc regex: %i\nglibc error: %s\n" - "rm_so: %i\nrm_eo: %i\n\n", rxstr->regex, - REGEX_INTERNAL_get_canonical_regex (a), rxstr->strings[i], - rxstr->expected_results[i], eval, eval_check, error, - matchptr[0].rm_so, matchptr[0].rm_eo); + eval = REGEX_INTERNAL_eval(a, rxstr->strings[i]); + eval_check = regexec(rx, rxstr->strings[i], 1, matchptr, 0); + + /* We only want to match the whole string, because that's what our DFA does, + * too. */ + if (eval_check == 0 && + (matchptr[0].rm_so != 0 || + matchptr[0].rm_eo != strlen(rxstr->strings[i]))) + eval_check = 1; + + if ((rxstr->expected_results[i] == match && (0 != eval || 0 != eval_check)) + || (rxstr->expected_results[i] == nomatch && + (0 == eval || 0 == eval_check))) + { + result = 1; + regerror(eval_check, rx, error, sizeof error); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unexpected result:\nregex: %s\ncanonical_regex: %s\n" + "string: %s\nexpected result: %i\n" + "gnunet regex: %i\nglibc regex: %i\nglibc error: %s\n" + "rm_so: %i\nrm_eo: %i\n\n", rxstr->regex, + REGEX_INTERNAL_get_canonical_regex(a), rxstr->strings[i], + rxstr->expected_results[i], eval, eval_check, error, + matchptr[0].rm_so, matchptr[0].rm_eo); + } } - } return result; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - GNUNET_log_setup ("test-regex", "WARNING", NULL); + GNUNET_log_setup("test-regex", "WARNING", NULL); struct REGEX_INTERNAL_Automaton *a; regex_t rx; @@ -256,71 +254,71 @@ main (int argc, char *argv[]) char *check_proof; struct Regex_String_Pair rxstr[19] = { - {"ab?(abcd)?", 5, - {"ababcd", "abab", "aabcd", "a", "abb"}, - {match, nomatch, match, match, nomatch}}, - {"ab(c|d)+c*(a(b|c)d)+", 5, - {"abcdcdcdcdddddabd", "abcd", - "abcddddddccccccccccccccccccccccccabdacdabd", - "abccccca", "abcdcdcdccdabdabd"}, - {match, nomatch, match, nomatch, match}}, - {"ab+c*(a(bx|c)d)+", 5, - {"abcdcdcdcdddddabd", "abcd", - "abcddddddccccccccccccccccccccccccabdacdabd", - "abccccca", "abcdcdcdccdabdabd"}, - {nomatch, nomatch, nomatch, nomatch, nomatch}}, - {"a+X*y+c|p|R|Z*K*y*R+w|Y*6+n+h*k*w+V*F|W*B*e*", 1, - {"kaXycQepRZKyRwY6nhkwVFWBegNVtLPj39XhJJ6bEifRSZRYZg"}, - {nomatch}}, - {"k|a+X*y+c|Q*e|p|R|Z*K*y*R+w|Y*6+n+h*k*w+V*F|W*B*e*g|N+V|t+L|P*j*3*9+X*h*J|J*6|b|E*i*f*R+S|Z|R|Y*Z|g*", 1, - {"kaXycQepRZKyRwY6nhkwVFWBegNVtLPj39XhJJ6bEifRSZRYZg"}, - {nomatch}}, - {"F?W+m+2*6*c*s|P?U?a|B|y*i+t+A|V|6*C*7*e?Z*n*i|J?5+g?W*V?7*j?p?1|r?B?C+E+3+6*i+W*P?K?0|D+7?y*m+3?g?K?", 1, - {"osfjsodfonONONOnosndfsdnfsd"}, - {nomatch}}, - {"V|M*o?x*p*d+h+b|E*m?h?Y*E*O?W*W*P+o?Z+H*M|I*q+C*a+5?5*9|b?z|G*y*k?R|p+u|8*h?B+l*H|e|L*O|1|F?v*0?5|C+", 1, - {"VMoxpdhbEmhYEOWWPoZHMIqCa559bzGykRpu8hBlHeLO1Fv05C"}, - {nomatch}}, - {"(bla)*", 8, - {"", "bla", "blabla", "bl", "la", "b", "l", "a"}, - {match, match, match, nomatch, nomatch, nomatch, nomatch, nomatch}}, - {"ab(c|d)+c*(a(b|c)+d)+(bla)(bla)*", 8, - {"ab", "abcabdbla", "abdcccccccccccabcbccdblablabla", "bl", "la", "b", - "l", - "a"}, - {nomatch, match, match, nomatch, nomatch, nomatch, nomatch, nomatch}}, - {"a|aa*a", 6, - {"", "a", "aa", "aaa", "aaaa", "aaaaa"}, - {nomatch, match, match, match, match, match}}, - {"ab(c|d)+c*(a(b|c)+d)+(bla)+", 1, - {"abcabdblaacdbla"}, - {nomatch}}, - {"(ac|b)+", 8, - {"b", "bb", "ac", "", "acb", "bacbacac", "acacac", "abc"}, - {match, match, match, nomatch, match, match, match, nomatch}}, - {"(ab|c)+", 7, - {"", "ab", "c", "abc", "ababcc", "acc", "abac"}, - {nomatch, match, match, match, match, nomatch, nomatch}}, - {"((j|2j)K|(j|2j)AK|(j|2j)(D|e|(j|2j)A(D|e))D*K)", 1, - {"", "2j2jADK", "j2jADK"}, - {nomatch, match, match}}, - {"((j|2j)K|(j|2j)(D|e|((j|2j)j|(j|2j)2j)A(D|e))D*K|(j|2j)AK)", 2, - {"", "2j2jjADK", "j2jADK"}, - {nomatch, match, match}}, - {"ab(c|d)+c*(a(b|c)d)+", 1, - {"abacd"}, - {nomatch}}, - {"d|5kl", 1, - {"d5kl"}, - {nomatch}}, - {"a()b", 1, - {"ab"}, - {match}}, - {"GNVPN-0001-PAD(001110101001001010(0|1)*|001110101001001010000(0|1)*|001110101001001010001(0|1)*|001110101001001010010(0|1)*|001110101001001010011(0|1)*|001110101001001010100(0|1)*|001110101001001010101(0|1)*|001110101001001010110(0|1)*|001110101001001010111(0|1)*|0011101010110110(0|1)*|001110101011011000000(0|1)*|001110101011011000001(0|1)*|001110101011011000010(0|1)*|001110101011011000011(0|1)*|001110101011011000100(0|1)*|001110101011011000101(0|1)*|001110101011011000110(0|1)*|001110101011011000111(0|1)*|001110101011011001000(0|1)*|001110101011011001001(0|1)*|001110101011011001010(0|1)*|001110101011011001011(0|1)*|001110101011011001100(0|1)*|001110101011011001101(0|1)*|001110101011011001110(0|1)*|001110101011011001111(0|1)*|001110101011011010000(0|1)*|001110101011011010001(0|1)*|001110101011011010010(0|1)*|001110101011011010011(0|1)*|001110101011011010100(0|1)*|001110101011011010101(0|1)*|001110101011011010110(0|1)*|001110101011011010111(0|1)*|001110101011011011000(0|1)*|001110101011011011001(0|1)*|001110101011011011010(0|1)*|001110101011011011011(0|1)*|001110101011011011100(0|1)*|001110101011011011101(0|1)*|001110101011011011110(0|1)*|001110101011011011111(0|1)*|0011101110111101(0|1)*|001110111011110100000(0|1)*|001110111011110100001(0|1)*|001110111011110100010(0|1)*|001110111011110100011(0|1)*|001110111011110100100(0|1)*|001110111011110100101(0|1)*|001110111011110100110(0|1)*|001110111011110100111(0|1)*|001110111011110101000(0|1)*|001110111011110101001(0|1)*|001110111011110101010(0|1)*|001110111011110101011(0|1)*|001110111011110101100(0|1)*|001110111011110101101(0|1)*|001110111011110101110(0|1)*|001110111011110101111(0|1)*|001110111011110110000(0|1)*|001110111011110110001(0|1)*|001110111011110110010(0|1)*|001110111011110110011(0|1)*|001110111011110110100(0|1)*|001110111011110110101(0|1)*|001110111011110110110(0|1)*|001110111011110110111(0|1)*|001110111011110111000(0|1)*|001110111011110111001(0|1)*|001110111011110111010(0|1)*|001110111011110111011(0|1)*|001110111011110111100(0|1)*|001110111011110111101(0|1)*|001110111011110111110(0|1)*|0111010001010110(0|1)*|011101000101011000000(0|1)*|011101000101011000001(0|1)*|011101000101011000010(0|1)*|011101000101011000011(0|1)*|011101000101011000100(0|1)*|011101000101011000101(0|1)*|011101000101011000110(0|1)*|011101000101011000111(0|1)*|011101000101011001000(0|1)*|011101000101011001001(0|1)*|011101000101011001010(0|1)*|011101000101011001011(0|1)*|011101000101011001100(0|1)*|011101000101011001101(0|1)*|011101000101011001110(0|1)*|011101000101011001111(0|1)*|011101000101011010000(0|1)*|011101000101011010001(0|1)*|011101000101011010010(0|1)*|011101000101011010011(0|1)*|011101000101011010100(0|1)*|011101000101011010101(0|1)*|011101000101011010110(0|1)*|011101000101011010111(0|1)*|011101000101011011000(0|1)*|011101000101011011001(0|1)*|011101000101011011010(0|1)*|011101000101011011011(0|1)*|011101000101011011100(0|1)*|011101000101011011101(0|1)*|011101000101011011110(0|1)*|011101000101011011111(0|1)*|0111010001010111(0|1)*|011101000101011100000(0|1)*|011101000101011100001(0|1)*|011101000101011100010(0|1)*|011101000101011100011(0|1)*|011101000101011100100(0|1)*|011101000101011100101(0|1)*|011101000101011100110(0|1)*|011101000101011100111(0|1)*|011101000101011101000(0|1)*|011101000101011101001(0|1)*|011101000101011101010(0|1)*|011101000101011101011(0|1)*|011101000101011101100(0|1)*|011101000101011101101(0|1)*|011101000101011101110(0|1)*|011101000101011101111(0|1)*|011101000101011110000(0|1)*|011101000101011110001(0|1)*|011101000101011110010(0|1)*|011101000101011110011(0|1)*|011101000101011110100(0|1)*|011101000101011110101(0|1)*|011101000101011110110(0|1)*|011101000101011110111(0|1)*|011101000101011111000(0|1)*|011101000101011111001(0|1)*|011101000101011111010(0|1)*|011101000101011111011(0|1)*|011101000101011111100(0|1)*|011101000101011111101(0|1)*|011101000101011111110(0|1)*|011101000101011111111(0|1)*|0111010001011000(0|1)*|011101000101100000000(0|1)*|011101000101100000001(0|1)*|011101000101100000010(0|1)*|011101000101100000011(0|1)*|011101000101100000100(0|1)*|011101000101100000101(0|1)*|011101000101100000110(0|1)*|011101000101100000111(0|1)*|011101000101100001000(0|1)*|011101000101100001001(0|1)*|011101000101100001010(0|1)*|011101000101100001011(0|1)*|011101000101100001100(0|1)*|011101000101100001101(0|1)*|011101000101100001110(0|1)*|011101000101100001111(0|1)*|011101000101100010000(0|1)*|011101000101100010001(0|1)*|011101000101100010010(0|1)*|011101000101100010011(0|1)*|011101000101100010100(0|1)*|011101000101100010101(0|1)*|011101000101100010110(0|1)*|011101000101100010111(0|1)*|011101000101100011000(0|1)*|011101000101100011001(0|1)*|011101000101100011010(0|1)*|011101000101100011011(0|1)*|011101000101100011100(0|1)*|011101000101100011101(0|1)*|011101000101100011110(0|1)*|011101000101100011111(0|1)*|01110100010110010(0|1)*|011101000101100100000(0|1)*|011101000101100100001(0|1)*|011101000101100100010(0|1)*|011101000101100100011(0|1)*|011101000101100100100(0|1)*|011101000101100100101(0|1)*|011101000101100100110(0|1)*|011101000101100100111(0|1)*|011101000101100101000(0|1)*|011101000101100101001(0|1)*|011101000101100101010(0|1)*|011101000101100101011(0|1)*|011101000101100101100(0|1)*|011101000101100101101(0|1)*|011101000101100101110(0|1)*|011101000101100101111(0|1)*|011101000101100101111000(0|1)*|1100101010011100(0|1)*|110010101001110000000(0|1)*|110010101001110000000001(0|1)*|110010101001110000000010(0|1)*|110010101001110000000110(0|1)*|110010101001110000001(0|1)*|110010101001110000001000(0|1)*|110010101001110000001001(0|1)*|110010101001110000001010(0|1)*|110010101001110000001011(0|1)*|110010101001110000001101(0|1)*|110010101001110000001110(0|1)*|110010101001110000010(0|1)*|110010101001110000011(0|1)*|110010101001110000100(0|1)*|110010101001110000101(0|1)*|110010101001110000110(0|1)*|110010101001110000111(0|1)*|110010101001110001000(0|1)*|110010101001110001001(0|1)*|110010101001110001010(0|1)*|110010101001110001011(0|1)*|110010101001110001100(0|1)*|110010101001110001101(0|1)*|110010101001110001110(0|1)*|110010101001110001111(0|1)*|110010101001110010000(0|1)*|110010101001110010001(0|1)*|110010101001110010010(0|1)*|110010101001110010011(0|1)*|110010101001110010100(0|1)*|110010101001110010101(0|1)*|110010101001110010110(0|1)*|110010101001110010111(0|1)*|110010101001110011000(0|1)*|110010101001110011001(0|1)*|110010101001110011010(0|1)*|110010101001110011011(0|1)*|110010101001110011100(0|1)*|110010101001110011101(0|1)*|110010101001110011110(0|1)*|110010101001110011111(0|1)*|1101101010111010(0|1)*|110110101011101000000(0|1)*|110110101011101000000001(0|1)*|110110101011101000001000(0|1)*|110110101011101000001001(0|1)*|110110101011101000001010(0|1)*|110110101011101000001011(0|1)*|110110101011101000001100(0|1)*|110110101011101000001110(0|1)*|110110101011101000001111(0|1)*|110110101011101000010(0|1)*|110110101011101000010000(0|1)*|110110101011101000010001(0|1)*|110110101011101000010010(0|1)*|110110101011101000010011(0|1)*|110110101011101000011(0|1)*|110110101011101000100(0|1)*|110110101011101000101(0|1)*|110110101011101000110(0|1)*|110110101011101000111(0|1)*|110110101011101001000(0|1)*|110110101011101001001(0|1)*|110110101011101001010(0|1)*|110110101011101001011(0|1)*|110110101011101001100(0|1)*|110110101011101001101(0|1)*|110110101011101001110(0|1)*|110110101011101001111(0|1)*|110110101011101010000(0|1)*|110110101011101010001(0|1)*|110110101011101010010(0|1)*|110110101011101010011(0|1)*|110110101011101010100(0|1)*|110110101011101010101(0|1)*|110110101011101010110(0|1)*|110110101011101010111(0|1)*|110110101011101011000(0|1)*|110110101011101011001(0|1)*|110110101011101011010(0|1)*|110110101011101011011(0|1)*|110110101011101011100(0|1)*|110110101011101011101(0|1)*|110110101011101011110(0|1)*|110110101011101011111(0|1)*|1101101011010100(0|1)*|110110101101010000000(0|1)*|110110101101010000001(0|1)*|110110101101010000010(0|1)*|110110101101010000011(0|1)*|110110101101010000100(0|1)*|110110101101010000101(0|1)*|110110101101010000110(0|1)*|110110101101010000111(0|1)*|110110101101010001000(0|1)*|110110101101010001001(0|1)*|110110101101010001010(0|1)*|110110101101010001011(0|1)*|110110101101010001100(0|1)*|110110101101010001101(0|1)*|110110101101010001110(0|1)*|110110101101010001111(0|1)*|110110101101010010000(0|1)*|110110101101010010001(0|1)*|110110101101010010010(0|1)*|110110101101010010011(0|1)*|110110101101010010100(0|1)*|1101101011010100101000(0|1)*|110110101101010010101(0|1)*|110110101101010010110(0|1)*|110110101101010010111(0|1)*|110110101101010011000(0|1)*|110110101101010011010(0|1)*|110110101101010011011(0|1)*|110110101101010011100(0|1)*|110110101101010011101(0|1)*|110110101101010011110(0|1)*|110110101101010011111(0|1)*|1101111010100100(0|1)*|110111101010010000000(0|1)*|110111101010010000001(0|1)*|110111101010010000010(0|1)*|110111101010010000011(0|1)*|110111101010010000100(0|1)*|110111101010010000101(0|1)*|110111101010010000110(0|1)*|110111101010010000111(0|1)*|110111101010010001000(0|1)*|110111101010010001001(0|1)*|110111101010010001010(0|1)*|110111101010010001011(0|1)*|110111101010010001100(0|1)*|110111101010010001101(0|1)*|110111101010010001110(0|1)*|110111101010010001111(0|1)*|110111101010010010000(0|1)*|110111101010010010001(0|1)*|110111101010010010010(0|1)*|110111101010010010011(0|1)*|110111101010010010100(0|1)*|110111101010010010101(0|1)*|110111101010010010110(0|1)*|110111101010010010111(0|1)*|110111101010010011000(0|1)*|110111101010010011001(0|1)*|110111101010010011010(0|1)*|110111101010010011011(0|1)*|110111101010010011100(0|1)*|110111101010010011101(0|1)*|110111101010010011110(0|1)*|110111101010010011111(0|1)*|11011110101001010(0|1)*|110111101010010100000(0|1)*|110111101010010100001(0|1)*|110111101010010100010(0|1)*|110111101010010100011(0|1)*|110111101010010100100(0|1)*|110111101010010100101(0|1)*|110111101010010100110(0|1)*|110111101010010100111(0|1)*|110111101010010101000(0|1)*|110111101010010101001(0|1)*|110111101010010101010(0|1)*|110111101010010101011(0|1)*|110111101010010101100(0|1)*|110111101010010101101(0|1)*|110111101010010101110(0|1)*|110111101010010101111(0|1)*)", - 2, - {"GNVPN-0001-PAD1101111010100101011101010101010101", - "GNVPN-0001-PAD11001010100111000101101010101"}, - {match, match}} + { "ab?(abcd)?", 5, + { "ababcd", "abab", "aabcd", "a", "abb" }, + { match, nomatch, match, match, nomatch } }, + { "ab(c|d)+c*(a(b|c)d)+", 5, + { "abcdcdcdcdddddabd", "abcd", + "abcddddddccccccccccccccccccccccccabdacdabd", + "abccccca", "abcdcdcdccdabdabd" }, + { match, nomatch, match, nomatch, match } }, + { "ab+c*(a(bx|c)d)+", 5, + { "abcdcdcdcdddddabd", "abcd", + "abcddddddccccccccccccccccccccccccabdacdabd", + "abccccca", "abcdcdcdccdabdabd" }, + { nomatch, nomatch, nomatch, nomatch, nomatch } }, + { "a+X*y+c|p|R|Z*K*y*R+w|Y*6+n+h*k*w+V*F|W*B*e*", 1, + { "kaXycQepRZKyRwY6nhkwVFWBegNVtLPj39XhJJ6bEifRSZRYZg" }, + { nomatch } }, + { "k|a+X*y+c|Q*e|p|R|Z*K*y*R+w|Y*6+n+h*k*w+V*F|W*B*e*g|N+V|t+L|P*j*3*9+X*h*J|J*6|b|E*i*f*R+S|Z|R|Y*Z|g*", 1, + { "kaXycQepRZKyRwY6nhkwVFWBegNVtLPj39XhJJ6bEifRSZRYZg" }, + { nomatch } }, + { "F?W+m+2*6*c*s|P?U?a|B|y*i+t+A|V|6*C*7*e?Z*n*i|J?5+g?W*V?7*j?p?1|r?B?C+E+3+6*i+W*P?K?0|D+7?y*m+3?g?K?", 1, + { "osfjsodfonONONOnosndfsdnfsd" }, + { nomatch } }, + { "V|M*o?x*p*d+h+b|E*m?h?Y*E*O?W*W*P+o?Z+H*M|I*q+C*a+5?5*9|b?z|G*y*k?R|p+u|8*h?B+l*H|e|L*O|1|F?v*0?5|C+", 1, + { "VMoxpdhbEmhYEOWWPoZHMIqCa559bzGykRpu8hBlHeLO1Fv05C" }, + { nomatch } }, + { "(bla)*", 8, + { "", "bla", "blabla", "bl", "la", "b", "l", "a" }, + { match, match, match, nomatch, nomatch, nomatch, nomatch, nomatch } }, + { "ab(c|d)+c*(a(b|c)+d)+(bla)(bla)*", 8, + { "ab", "abcabdbla", "abdcccccccccccabcbccdblablabla", "bl", "la", "b", + "l", + "a" }, + { nomatch, match, match, nomatch, nomatch, nomatch, nomatch, nomatch } }, + { "a|aa*a", 6, + { "", "a", "aa", "aaa", "aaaa", "aaaaa" }, + { nomatch, match, match, match, match, match } }, + { "ab(c|d)+c*(a(b|c)+d)+(bla)+", 1, + { "abcabdblaacdbla" }, + { nomatch } }, + { "(ac|b)+", 8, + { "b", "bb", "ac", "", "acb", "bacbacac", "acacac", "abc" }, + { match, match, match, nomatch, match, match, match, nomatch } }, + { "(ab|c)+", 7, + { "", "ab", "c", "abc", "ababcc", "acc", "abac" }, + { nomatch, match, match, match, match, nomatch, nomatch } }, + { "((j|2j)K|(j|2j)AK|(j|2j)(D|e|(j|2j)A(D|e))D*K)", 1, + { "", "2j2jADK", "j2jADK" }, + { nomatch, match, match } }, + { "((j|2j)K|(j|2j)(D|e|((j|2j)j|(j|2j)2j)A(D|e))D*K|(j|2j)AK)", 2, + { "", "2j2jjADK", "j2jADK" }, + { nomatch, match, match } }, + { "ab(c|d)+c*(a(b|c)d)+", 1, + { "abacd" }, + { nomatch } }, + { "d|5kl", 1, + { "d5kl" }, + { nomatch } }, + { "a()b", 1, + { "ab" }, + { match } }, + { "GNVPN-0001-PAD(001110101001001010(0|1)*|001110101001001010000(0|1)*|001110101001001010001(0|1)*|001110101001001010010(0|1)*|001110101001001010011(0|1)*|001110101001001010100(0|1)*|001110101001001010101(0|1)*|001110101001001010110(0|1)*|001110101001001010111(0|1)*|0011101010110110(0|1)*|001110101011011000000(0|1)*|001110101011011000001(0|1)*|001110101011011000010(0|1)*|001110101011011000011(0|1)*|001110101011011000100(0|1)*|001110101011011000101(0|1)*|001110101011011000110(0|1)*|001110101011011000111(0|1)*|001110101011011001000(0|1)*|001110101011011001001(0|1)*|001110101011011001010(0|1)*|001110101011011001011(0|1)*|001110101011011001100(0|1)*|001110101011011001101(0|1)*|001110101011011001110(0|1)*|001110101011011001111(0|1)*|001110101011011010000(0|1)*|001110101011011010001(0|1)*|001110101011011010010(0|1)*|001110101011011010011(0|1)*|001110101011011010100(0|1)*|001110101011011010101(0|1)*|001110101011011010110(0|1)*|001110101011011010111(0|1)*|001110101011011011000(0|1)*|001110101011011011001(0|1)*|001110101011011011010(0|1)*|001110101011011011011(0|1)*|001110101011011011100(0|1)*|001110101011011011101(0|1)*|001110101011011011110(0|1)*|001110101011011011111(0|1)*|0011101110111101(0|1)*|001110111011110100000(0|1)*|001110111011110100001(0|1)*|001110111011110100010(0|1)*|001110111011110100011(0|1)*|001110111011110100100(0|1)*|001110111011110100101(0|1)*|001110111011110100110(0|1)*|001110111011110100111(0|1)*|001110111011110101000(0|1)*|001110111011110101001(0|1)*|001110111011110101010(0|1)*|001110111011110101011(0|1)*|001110111011110101100(0|1)*|001110111011110101101(0|1)*|001110111011110101110(0|1)*|001110111011110101111(0|1)*|001110111011110110000(0|1)*|001110111011110110001(0|1)*|001110111011110110010(0|1)*|001110111011110110011(0|1)*|001110111011110110100(0|1)*|001110111011110110101(0|1)*|001110111011110110110(0|1)*|001110111011110110111(0|1)*|001110111011110111000(0|1)*|001110111011110111001(0|1)*|001110111011110111010(0|1)*|001110111011110111011(0|1)*|001110111011110111100(0|1)*|001110111011110111101(0|1)*|001110111011110111110(0|1)*|0111010001010110(0|1)*|011101000101011000000(0|1)*|011101000101011000001(0|1)*|011101000101011000010(0|1)*|011101000101011000011(0|1)*|011101000101011000100(0|1)*|011101000101011000101(0|1)*|011101000101011000110(0|1)*|011101000101011000111(0|1)*|011101000101011001000(0|1)*|011101000101011001001(0|1)*|011101000101011001010(0|1)*|011101000101011001011(0|1)*|011101000101011001100(0|1)*|011101000101011001101(0|1)*|011101000101011001110(0|1)*|011101000101011001111(0|1)*|011101000101011010000(0|1)*|011101000101011010001(0|1)*|011101000101011010010(0|1)*|011101000101011010011(0|1)*|011101000101011010100(0|1)*|011101000101011010101(0|1)*|011101000101011010110(0|1)*|011101000101011010111(0|1)*|011101000101011011000(0|1)*|011101000101011011001(0|1)*|011101000101011011010(0|1)*|011101000101011011011(0|1)*|011101000101011011100(0|1)*|011101000101011011101(0|1)*|011101000101011011110(0|1)*|011101000101011011111(0|1)*|0111010001010111(0|1)*|011101000101011100000(0|1)*|011101000101011100001(0|1)*|011101000101011100010(0|1)*|011101000101011100011(0|1)*|011101000101011100100(0|1)*|011101000101011100101(0|1)*|011101000101011100110(0|1)*|011101000101011100111(0|1)*|011101000101011101000(0|1)*|011101000101011101001(0|1)*|011101000101011101010(0|1)*|011101000101011101011(0|1)*|011101000101011101100(0|1)*|011101000101011101101(0|1)*|011101000101011101110(0|1)*|011101000101011101111(0|1)*|011101000101011110000(0|1)*|011101000101011110001(0|1)*|011101000101011110010(0|1)*|011101000101011110011(0|1)*|011101000101011110100(0|1)*|011101000101011110101(0|1)*|011101000101011110110(0|1)*|011101000101011110111(0|1)*|011101000101011111000(0|1)*|011101000101011111001(0|1)*|011101000101011111010(0|1)*|011101000101011111011(0|1)*|011101000101011111100(0|1)*|011101000101011111101(0|1)*|011101000101011111110(0|1)*|011101000101011111111(0|1)*|0111010001011000(0|1)*|011101000101100000000(0|1)*|011101000101100000001(0|1)*|011101000101100000010(0|1)*|011101000101100000011(0|1)*|011101000101100000100(0|1)*|011101000101100000101(0|1)*|011101000101100000110(0|1)*|011101000101100000111(0|1)*|011101000101100001000(0|1)*|011101000101100001001(0|1)*|011101000101100001010(0|1)*|011101000101100001011(0|1)*|011101000101100001100(0|1)*|011101000101100001101(0|1)*|011101000101100001110(0|1)*|011101000101100001111(0|1)*|011101000101100010000(0|1)*|011101000101100010001(0|1)*|011101000101100010010(0|1)*|011101000101100010011(0|1)*|011101000101100010100(0|1)*|011101000101100010101(0|1)*|011101000101100010110(0|1)*|011101000101100010111(0|1)*|011101000101100011000(0|1)*|011101000101100011001(0|1)*|011101000101100011010(0|1)*|011101000101100011011(0|1)*|011101000101100011100(0|1)*|011101000101100011101(0|1)*|011101000101100011110(0|1)*|011101000101100011111(0|1)*|01110100010110010(0|1)*|011101000101100100000(0|1)*|011101000101100100001(0|1)*|011101000101100100010(0|1)*|011101000101100100011(0|1)*|011101000101100100100(0|1)*|011101000101100100101(0|1)*|011101000101100100110(0|1)*|011101000101100100111(0|1)*|011101000101100101000(0|1)*|011101000101100101001(0|1)*|011101000101100101010(0|1)*|011101000101100101011(0|1)*|011101000101100101100(0|1)*|011101000101100101101(0|1)*|011101000101100101110(0|1)*|011101000101100101111(0|1)*|011101000101100101111000(0|1)*|1100101010011100(0|1)*|110010101001110000000(0|1)*|110010101001110000000001(0|1)*|110010101001110000000010(0|1)*|110010101001110000000110(0|1)*|110010101001110000001(0|1)*|110010101001110000001000(0|1)*|110010101001110000001001(0|1)*|110010101001110000001010(0|1)*|110010101001110000001011(0|1)*|110010101001110000001101(0|1)*|110010101001110000001110(0|1)*|110010101001110000010(0|1)*|110010101001110000011(0|1)*|110010101001110000100(0|1)*|110010101001110000101(0|1)*|110010101001110000110(0|1)*|110010101001110000111(0|1)*|110010101001110001000(0|1)*|110010101001110001001(0|1)*|110010101001110001010(0|1)*|110010101001110001011(0|1)*|110010101001110001100(0|1)*|110010101001110001101(0|1)*|110010101001110001110(0|1)*|110010101001110001111(0|1)*|110010101001110010000(0|1)*|110010101001110010001(0|1)*|110010101001110010010(0|1)*|110010101001110010011(0|1)*|110010101001110010100(0|1)*|110010101001110010101(0|1)*|110010101001110010110(0|1)*|110010101001110010111(0|1)*|110010101001110011000(0|1)*|110010101001110011001(0|1)*|110010101001110011010(0|1)*|110010101001110011011(0|1)*|110010101001110011100(0|1)*|110010101001110011101(0|1)*|110010101001110011110(0|1)*|110010101001110011111(0|1)*|1101101010111010(0|1)*|110110101011101000000(0|1)*|110110101011101000000001(0|1)*|110110101011101000001000(0|1)*|110110101011101000001001(0|1)*|110110101011101000001010(0|1)*|110110101011101000001011(0|1)*|110110101011101000001100(0|1)*|110110101011101000001110(0|1)*|110110101011101000001111(0|1)*|110110101011101000010(0|1)*|110110101011101000010000(0|1)*|110110101011101000010001(0|1)*|110110101011101000010010(0|1)*|110110101011101000010011(0|1)*|110110101011101000011(0|1)*|110110101011101000100(0|1)*|110110101011101000101(0|1)*|110110101011101000110(0|1)*|110110101011101000111(0|1)*|110110101011101001000(0|1)*|110110101011101001001(0|1)*|110110101011101001010(0|1)*|110110101011101001011(0|1)*|110110101011101001100(0|1)*|110110101011101001101(0|1)*|110110101011101001110(0|1)*|110110101011101001111(0|1)*|110110101011101010000(0|1)*|110110101011101010001(0|1)*|110110101011101010010(0|1)*|110110101011101010011(0|1)*|110110101011101010100(0|1)*|110110101011101010101(0|1)*|110110101011101010110(0|1)*|110110101011101010111(0|1)*|110110101011101011000(0|1)*|110110101011101011001(0|1)*|110110101011101011010(0|1)*|110110101011101011011(0|1)*|110110101011101011100(0|1)*|110110101011101011101(0|1)*|110110101011101011110(0|1)*|110110101011101011111(0|1)*|1101101011010100(0|1)*|110110101101010000000(0|1)*|110110101101010000001(0|1)*|110110101101010000010(0|1)*|110110101101010000011(0|1)*|110110101101010000100(0|1)*|110110101101010000101(0|1)*|110110101101010000110(0|1)*|110110101101010000111(0|1)*|110110101101010001000(0|1)*|110110101101010001001(0|1)*|110110101101010001010(0|1)*|110110101101010001011(0|1)*|110110101101010001100(0|1)*|110110101101010001101(0|1)*|110110101101010001110(0|1)*|110110101101010001111(0|1)*|110110101101010010000(0|1)*|110110101101010010001(0|1)*|110110101101010010010(0|1)*|110110101101010010011(0|1)*|110110101101010010100(0|1)*|1101101011010100101000(0|1)*|110110101101010010101(0|1)*|110110101101010010110(0|1)*|110110101101010010111(0|1)*|110110101101010011000(0|1)*|110110101101010011010(0|1)*|110110101101010011011(0|1)*|110110101101010011100(0|1)*|110110101101010011101(0|1)*|110110101101010011110(0|1)*|110110101101010011111(0|1)*|1101111010100100(0|1)*|110111101010010000000(0|1)*|110111101010010000001(0|1)*|110111101010010000010(0|1)*|110111101010010000011(0|1)*|110111101010010000100(0|1)*|110111101010010000101(0|1)*|110111101010010000110(0|1)*|110111101010010000111(0|1)*|110111101010010001000(0|1)*|110111101010010001001(0|1)*|110111101010010001010(0|1)*|110111101010010001011(0|1)*|110111101010010001100(0|1)*|110111101010010001101(0|1)*|110111101010010001110(0|1)*|110111101010010001111(0|1)*|110111101010010010000(0|1)*|110111101010010010001(0|1)*|110111101010010010010(0|1)*|110111101010010010011(0|1)*|110111101010010010100(0|1)*|110111101010010010101(0|1)*|110111101010010010110(0|1)*|110111101010010010111(0|1)*|110111101010010011000(0|1)*|110111101010010011001(0|1)*|110111101010010011010(0|1)*|110111101010010011011(0|1)*|110111101010010011100(0|1)*|110111101010010011101(0|1)*|110111101010010011110(0|1)*|110111101010010011111(0|1)*|11011110101001010(0|1)*|110111101010010100000(0|1)*|110111101010010100001(0|1)*|110111101010010100010(0|1)*|110111101010010100011(0|1)*|110111101010010100100(0|1)*|110111101010010100101(0|1)*|110111101010010100110(0|1)*|110111101010010100111(0|1)*|110111101010010101000(0|1)*|110111101010010101001(0|1)*|110111101010010101010(0|1)*|110111101010010101011(0|1)*|110111101010010101100(0|1)*|110111101010010101101(0|1)*|110111101010010101110(0|1)*|110111101010010101111(0|1)*)", + 2, + { "GNVPN-0001-PAD1101111010100101011101010101010101", + "GNVPN-0001-PAD11001010100111000101101010101" }, + { match, match } } }; check_nfa = 0; @@ -328,39 +326,39 @@ main (int argc, char *argv[]) check_rand = 0; for (i = 0; i < 19; i++) - { - if (0 != regcomp (&rx, rxstr[i].regex, REG_EXTENDED)) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not compile regex using regcomp()\n"); - return 1; + if (0 != regcomp(&rx, rxstr[i].regex, REG_EXTENDED)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not compile regex using regcomp()\n"); + return 1; + } + + /* NFA test */ + a = REGEX_INTERNAL_construct_nfa(rxstr[i].regex, strlen(rxstr[i].regex)); + check_nfa += test_automaton(a, &rx, &rxstr[i]); + REGEX_INTERNAL_automaton_destroy(a); + + /* DFA test */ + a = REGEX_INTERNAL_construct_dfa(rxstr[i].regex, strlen(rxstr[i].regex), 0); + check_dfa += test_automaton(a, &rx, &rxstr[i]); + check_proof = GNUNET_strdup(REGEX_INTERNAL_get_canonical_regex(a)); + REGEX_INTERNAL_automaton_destroy(a); + + a = REGEX_INTERNAL_construct_dfa(check_proof, strlen(check_proof), 0); + check_dfa += test_automaton(a, &rx, &rxstr[i]); + REGEX_INTERNAL_automaton_destroy(a); + if (0 != check_dfa) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "check_proof: %s\n", check_proof); + GNUNET_free_non_null(check_proof); + + regfree(&rx); } - /* NFA test */ - a = REGEX_INTERNAL_construct_nfa (rxstr[i].regex, strlen (rxstr[i].regex)); - check_nfa += test_automaton (a, &rx, &rxstr[i]); - REGEX_INTERNAL_automaton_destroy (a); - - /* DFA test */ - a = REGEX_INTERNAL_construct_dfa (rxstr[i].regex, strlen (rxstr[i].regex), 0); - check_dfa += test_automaton (a, &rx, &rxstr[i]); - check_proof = GNUNET_strdup (REGEX_INTERNAL_get_canonical_regex (a)); - REGEX_INTERNAL_automaton_destroy (a); - - a = REGEX_INTERNAL_construct_dfa (check_proof, strlen (check_proof), 0); - check_dfa += test_automaton (a, &rx, &rxstr[i]); - REGEX_INTERNAL_automaton_destroy (a); - if (0 != check_dfa) - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "check_proof: %s\n", check_proof); - GNUNET_free_non_null (check_proof); - - regfree (&rx); - } - /* Random tests */ - srand (time (NULL)); + srand(time(NULL)); for (i = 0; i < 20; i++) - check_rand += test_random (50, 60, 10); + check_rand += test_random(50, 60, 10); return check_nfa + check_dfa + check_rand; } diff --git a/src/regex/test_regex_graph_api.c b/src/regex/test_regex_graph_api.c index 92792c19f..356782dec 100644 --- a/src/regex/test_regex_graph_api.c +++ b/src/regex/test_regex_graph_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/test_regex_graph_api.c * @brief test for regex_graph.c @@ -39,39 +39,39 @@ * @return 0 if ok, non 0 on error. */ static int -filecheck (const char *filename) +filecheck(const char *filename) { int error = 0; FILE *fp; /* Check if file was created and delete it again */ - if (NULL == (fp = fopen (filename, "r"))) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not find graph %s\n", filename); - return 1; - } - - GNUNET_break (0 == fseek (fp, 0L, SEEK_END)); - if (1 > ftell (fp)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Graph writing failed, got empty file (%s)!\n", filename); - error = 2; - } - - GNUNET_assert (0 == fclose (fp)); + if (NULL == (fp = fopen(filename, "r"))) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not find graph %s\n", filename); + return 1; + } + + GNUNET_break(0 == fseek(fp, 0L, SEEK_END)); + if (1 > ftell(fp)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Graph writing failed, got empty file (%s)!\n", filename); + error = 2; + } + + GNUNET_assert(0 == fclose(fp)); if (!KEEP_FILES) - { - if (0 != unlink (filename)) - GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "unlink", filename); - } + { + if (0 != unlink(filename)) + GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "unlink", filename); + } return error; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { int error; struct REGEX_INTERNAL_Automaton *a; @@ -93,66 +93,65 @@ main (int argc, char *argv[]) "PADPADPADPADPADPabcdefghixxxxxxxxxxxxxjklmnop*qstoisdjfguisdfguihsdfgbdsuivggsd" }; - GNUNET_log_setup ("test-regex", "WARNING", NULL); + GNUNET_log_setup("test-regex", "WARNING", NULL); error = 0; for (i = 0; i < 12; i++) - { - /* Check NFA graph creation */ - a = REGEX_INTERNAL_construct_nfa (regex[i], strlen (regex[i])); - REGEX_TEST_automaton_save_graph (a, filename, REGEX_TEST_GRAPH_DEFAULT); - REGEX_INTERNAL_automaton_destroy (a); - error += filecheck (filename); - - a = REGEX_INTERNAL_construct_nfa (regex[i], strlen (regex[i])); - REGEX_TEST_automaton_save_graph (a, filename, - REGEX_TEST_GRAPH_DEFAULT | - REGEX_TEST_GRAPH_VERBOSE); - REGEX_INTERNAL_automaton_destroy (a); - error += filecheck (filename); - - a = REGEX_INTERNAL_construct_nfa (regex[i], strlen (regex[i])); - REGEX_TEST_automaton_save_graph (a, filename, - REGEX_TEST_GRAPH_DEFAULT | - REGEX_TEST_GRAPH_COLORING); - REGEX_INTERNAL_automaton_destroy (a); - error += filecheck (filename); - - a = REGEX_INTERNAL_construct_nfa (regex[i], strlen (regex[i])); - REGEX_TEST_automaton_save_graph (a, filename, - REGEX_TEST_GRAPH_DEFAULT | - REGEX_TEST_GRAPH_VERBOSE | - REGEX_TEST_GRAPH_COLORING); - REGEX_INTERNAL_automaton_destroy (a); - error += filecheck (filename); - - - /* Check DFA graph creation */ - a = REGEX_INTERNAL_construct_dfa (regex[i], strlen (regex[i]), 0); - REGEX_TEST_automaton_save_graph (a, filename, REGEX_TEST_GRAPH_DEFAULT); - REGEX_INTERNAL_automaton_destroy (a); - error += filecheck (filename); - - a = REGEX_INTERNAL_construct_dfa (regex[i], strlen (regex[i]), 0); - REGEX_TEST_automaton_save_graph (a, filename, - REGEX_TEST_GRAPH_DEFAULT | - REGEX_TEST_GRAPH_VERBOSE); - REGEX_INTERNAL_automaton_destroy (a); - error += filecheck (filename); - - a = REGEX_INTERNAL_construct_dfa (regex[i], strlen (regex[i]), 0); - REGEX_TEST_automaton_save_graph (a, filename, - REGEX_TEST_GRAPH_DEFAULT | - REGEX_TEST_GRAPH_COLORING); - REGEX_INTERNAL_automaton_destroy (a); - error += filecheck (filename); - - - a = REGEX_INTERNAL_construct_dfa (regex[i], strlen (regex[i]), 4); - REGEX_TEST_automaton_save_graph (a, filename, REGEX_TEST_GRAPH_DEFAULT); - REGEX_INTERNAL_automaton_destroy (a); - error += filecheck (filename); - - } + { + /* Check NFA graph creation */ + a = REGEX_INTERNAL_construct_nfa(regex[i], strlen(regex[i])); + REGEX_TEST_automaton_save_graph(a, filename, REGEX_TEST_GRAPH_DEFAULT); + REGEX_INTERNAL_automaton_destroy(a); + error += filecheck(filename); + + a = REGEX_INTERNAL_construct_nfa(regex[i], strlen(regex[i])); + REGEX_TEST_automaton_save_graph(a, filename, + REGEX_TEST_GRAPH_DEFAULT | + REGEX_TEST_GRAPH_VERBOSE); + REGEX_INTERNAL_automaton_destroy(a); + error += filecheck(filename); + + a = REGEX_INTERNAL_construct_nfa(regex[i], strlen(regex[i])); + REGEX_TEST_automaton_save_graph(a, filename, + REGEX_TEST_GRAPH_DEFAULT | + REGEX_TEST_GRAPH_COLORING); + REGEX_INTERNAL_automaton_destroy(a); + error += filecheck(filename); + + a = REGEX_INTERNAL_construct_nfa(regex[i], strlen(regex[i])); + REGEX_TEST_automaton_save_graph(a, filename, + REGEX_TEST_GRAPH_DEFAULT | + REGEX_TEST_GRAPH_VERBOSE | + REGEX_TEST_GRAPH_COLORING); + REGEX_INTERNAL_automaton_destroy(a); + error += filecheck(filename); + + + /* Check DFA graph creation */ + a = REGEX_INTERNAL_construct_dfa(regex[i], strlen(regex[i]), 0); + REGEX_TEST_automaton_save_graph(a, filename, REGEX_TEST_GRAPH_DEFAULT); + REGEX_INTERNAL_automaton_destroy(a); + error += filecheck(filename); + + a = REGEX_INTERNAL_construct_dfa(regex[i], strlen(regex[i]), 0); + REGEX_TEST_automaton_save_graph(a, filename, + REGEX_TEST_GRAPH_DEFAULT | + REGEX_TEST_GRAPH_VERBOSE); + REGEX_INTERNAL_automaton_destroy(a); + error += filecheck(filename); + + a = REGEX_INTERNAL_construct_dfa(regex[i], strlen(regex[i]), 0); + REGEX_TEST_automaton_save_graph(a, filename, + REGEX_TEST_GRAPH_DEFAULT | + REGEX_TEST_GRAPH_COLORING); + REGEX_INTERNAL_automaton_destroy(a); + error += filecheck(filename); + + + a = REGEX_INTERNAL_construct_dfa(regex[i], strlen(regex[i]), 4); + REGEX_TEST_automaton_save_graph(a, filename, REGEX_TEST_GRAPH_DEFAULT); + REGEX_INTERNAL_automaton_destroy(a); + error += filecheck(filename); + } return error; } diff --git a/src/regex/test_regex_integration.c b/src/regex/test_regex_integration.c index f264c4fae..b107c6d09 100644 --- a/src/regex/test_regex_integration.c +++ b/src/regex/test_regex_integration.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/test_regex_integration.c * @brief base test case for regex integration with VPN; @@ -35,12 +35,12 @@ /** * How long until we really give up on a particular testcase portion? */ -#define TOTAL_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 600) +#define TOTAL_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 600) /** * How long until we give up on any particular operation (and retry)? */ -#define BASE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 3) +#define BASE_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 3) static struct GNUNET_REGEX_Announcement *a4; @@ -57,26 +57,26 @@ static struct GNUNET_SCHEDULER_Task *die_task; static void -end (void *cls) +end(void *cls) { die_task = NULL; - GNUNET_REGEX_announce_cancel (a4); + GNUNET_REGEX_announce_cancel(a4); a4 = NULL; - GNUNET_REGEX_search_cancel (s4); + GNUNET_REGEX_search_cancel(s4); s4 = NULL; - GNUNET_REGEX_announce_cancel (a6); + GNUNET_REGEX_announce_cancel(a6); a6 = NULL; - GNUNET_REGEX_search_cancel (s6); + GNUNET_REGEX_search_cancel(s6); s6 = NULL; ok = 0; } static void -end_badly () +end_badly() { - fprintf (stderr, "%s", "Testcase failed (timeout).\n"); - end (NULL); + fprintf(stderr, "%s", "Testcase failed (timeout).\n"); + end(NULL); ok = 1; } @@ -92,36 +92,36 @@ end_badly () * @param put_path_length Length of the @a put_path. */ static void -found_cb (void *cls, - const struct GNUNET_PeerIdentity *id, - const struct GNUNET_PeerIdentity *get_path, - unsigned int get_path_length, - const struct GNUNET_PeerIdentity *put_path, - unsigned int put_path_length) +found_cb(void *cls, + const struct GNUNET_PeerIdentity *id, + const struct GNUNET_PeerIdentity *get_path, + unsigned int get_path_length, + const struct GNUNET_PeerIdentity *put_path, + unsigned int put_path_length) { const char *str = cls; static int found; - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "IPv%s-exit found\n", - str); - if (0 == strcmp (str, "4")) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "IPv%s-exit found\n", + str); + if (0 == strcmp(str, "4")) found |= 4; - if (0 == strcmp (str, "6")) + if (0 == strcmp(str, "6")) found |= 2; - if ((4|2) == found) - { - GNUNET_SCHEDULER_cancel (die_task); - die_task = - GNUNET_SCHEDULER_add_now (&end, NULL); - } + if ((4 | 2) == found) + { + GNUNET_SCHEDULER_cancel(die_task); + die_task = + GNUNET_SCHEDULER_add_now(&end, NULL); + } } static void -run (void *cls, - const struct GNUNET_CONFIGURATION_Handle *cfg, - struct GNUNET_TESTING_Peer *peer) +run(void *cls, + const struct GNUNET_CONFIGURATION_Handle *cfg, + struct GNUNET_TESTING_Peer *peer) { char rxstr4[GNUNET_TUN_IPV4_REGEXLEN]; char rxstr6[GNUNET_TUN_IPV6_REGEXLEN]; @@ -135,72 +135,72 @@ run (void *cls, struct in6_addr i6; die_task = - GNUNET_SCHEDULER_add_delayed (TOTAL_TIMEOUT, - &end_badly, NULL); - GNUNET_assert (1 == - inet_pton (AF_INET, - "127.0.0.1", - &i4)); - GNUNET_assert (1 == - inet_pton (AF_INET6, - "::1:5", - &i6)); - GNUNET_TUN_ipv4toregexsearch (&i4, - 8080, - rxstr4); - GNUNET_TUN_ipv6toregexsearch (&i6, - 8686, - rxstr6); - GNUNET_asprintf (&ss4, - "%s%s", - GNUNET_APPLICATION_TYPE_EXIT_REGEX_PREFIX, - rxstr4); - GNUNET_asprintf (&ss6, - "%s%s", - GNUNET_APPLICATION_TYPE_EXIT_REGEX_PREFIX, - rxstr6); - p4r = GNUNET_TUN_ipv4policy2regex ("0.0.0.0/0:!25;"); - p6r = GNUNET_TUN_ipv6policy2regex ("::/0:!25;"); - GNUNET_asprintf (&p4, - "%s%s", - GNUNET_APPLICATION_TYPE_EXIT_REGEX_PREFIX, - p4r); - GNUNET_asprintf (&p6, - "%s%s", - GNUNET_APPLICATION_TYPE_EXIT_REGEX_PREFIX, - p6r); - GNUNET_free (p4r); - GNUNET_free (p6r); - a4 = GNUNET_REGEX_announce (cfg, - p4, - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, - 5), - 1); - a6 = GNUNET_REGEX_announce (cfg, - p6, - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, - 5), - 1); - GNUNET_free (p4); - GNUNET_free (p6); - - s4 = GNUNET_REGEX_search (cfg, - ss4, - &found_cb, "4"); - s6 = GNUNET_REGEX_search (cfg, - ss6, - &found_cb, "6"); - GNUNET_free (ss4); - GNUNET_free (ss6); + GNUNET_SCHEDULER_add_delayed(TOTAL_TIMEOUT, + &end_badly, NULL); + GNUNET_assert(1 == + inet_pton(AF_INET, + "127.0.0.1", + &i4)); + GNUNET_assert(1 == + inet_pton(AF_INET6, + "::1:5", + &i6)); + GNUNET_TUN_ipv4toregexsearch(&i4, + 8080, + rxstr4); + GNUNET_TUN_ipv6toregexsearch(&i6, + 8686, + rxstr6); + GNUNET_asprintf(&ss4, + "%s%s", + GNUNET_APPLICATION_TYPE_EXIT_REGEX_PREFIX, + rxstr4); + GNUNET_asprintf(&ss6, + "%s%s", + GNUNET_APPLICATION_TYPE_EXIT_REGEX_PREFIX, + rxstr6); + p4r = GNUNET_TUN_ipv4policy2regex("0.0.0.0/0:!25;"); + p6r = GNUNET_TUN_ipv6policy2regex("::/0:!25;"); + GNUNET_asprintf(&p4, + "%s%s", + GNUNET_APPLICATION_TYPE_EXIT_REGEX_PREFIX, + p4r); + GNUNET_asprintf(&p6, + "%s%s", + GNUNET_APPLICATION_TYPE_EXIT_REGEX_PREFIX, + p6r); + GNUNET_free(p4r); + GNUNET_free(p6r); + a4 = GNUNET_REGEX_announce(cfg, + p4, + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, + 5), + 1); + a6 = GNUNET_REGEX_announce(cfg, + p6, + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, + 5), + 1); + GNUNET_free(p4); + GNUNET_free(p6); + + s4 = GNUNET_REGEX_search(cfg, + ss4, + &found_cb, "4"); + s6 = GNUNET_REGEX_search(cfg, + ss6, + &found_cb, "6"); + GNUNET_free(ss4); + GNUNET_free(ss6); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - if (0 != GNUNET_TESTING_peer_run ("test-regex-integration", - "test_regex_api_data.conf", - &run, NULL)) + if (0 != GNUNET_TESTING_peer_run("test-regex-integration", + "test_regex_api_data.conf", + &run, NULL)) return 1; return ok; } diff --git a/src/regex/test_regex_iterate_api.c b/src/regex/test_regex_iterate_api.c index bbc60475e..7711a1154 100644 --- a/src/regex/test_regex_iterate_api.c +++ b/src/regex/test_regex_iterate_api.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/test_regex_iterate_api.c * @brief test for regex.c @@ -41,8 +41,7 @@ static unsigned int transition_counter; -struct IteratorContext -{ +struct IteratorContext { int error; int should_save_graph; FILE *graph_filep; @@ -51,8 +50,7 @@ struct IteratorContext unsigned int match_count; }; -struct RegexStringPair -{ +struct RegexStringPair { char *regex; unsigned int string_count; char *strings[20]; @@ -60,63 +58,63 @@ struct RegexStringPair static void -key_iterator (void *cls, const struct GNUNET_HashCode *key, - const char *proof, - int accepting, unsigned int num_edges, - const struct REGEX_BLOCK_Edge *edges) +key_iterator(void *cls, const struct GNUNET_HashCode *key, + const char *proof, + int accepting, unsigned int num_edges, + const struct REGEX_BLOCK_Edge *edges) { unsigned int i; struct IteratorContext *ctx = cls; char *out_str; - char *state_id = GNUNET_strdup (GNUNET_h2s (key)); + char *state_id = GNUNET_strdup(GNUNET_h2s(key)); - GNUNET_assert (NULL != proof); + GNUNET_assert(NULL != proof); if (GNUNET_YES == ctx->should_save_graph) - { - if (GNUNET_YES == accepting) - GNUNET_asprintf (&out_str, "\"%s\" [shape=doublecircle]\n", state_id); - else - GNUNET_asprintf (&out_str, "\"%s\" [shape=circle]\n", state_id); - fwrite (out_str, strlen (out_str), 1, ctx->graph_filep); - GNUNET_free (out_str); - - for (i = 0; i < num_edges; i++) { - transition_counter++; - GNUNET_asprintf (&out_str, "\"%s\" -> \"%s\" [label = \"%s (%s)\"]\n", - state_id, GNUNET_h2s (&edges[i].destination), - edges[i].label, proof); - fwrite (out_str, strlen (out_str), 1, ctx->graph_filep); - - GNUNET_free (out_str); + if (GNUNET_YES == accepting) + GNUNET_asprintf(&out_str, "\"%s\" [shape=doublecircle]\n", state_id); + else + GNUNET_asprintf(&out_str, "\"%s\" [shape=circle]\n", state_id); + fwrite(out_str, strlen(out_str), 1, ctx->graph_filep); + GNUNET_free(out_str); + + for (i = 0; i < num_edges; i++) + { + transition_counter++; + GNUNET_asprintf(&out_str, "\"%s\" -> \"%s\" [label = \"%s (%s)\"]\n", + state_id, GNUNET_h2s(&edges[i].destination), + edges[i].label, proof); + fwrite(out_str, strlen(out_str), 1, ctx->graph_filep); + + GNUNET_free(out_str); + } } - } else - { - for (i = 0; i < num_edges; i++) - transition_counter++; - } + { + for (i = 0; i < num_edges; i++) + transition_counter++; + } for (i = 0; i < ctx->string_count; i++) - { - if (0 == strcmp (proof, ctx->strings[i])) - ctx->match_count++; - } - - if (GNUNET_OK != REGEX_BLOCK_check_proof (proof, strlen (proof), key)) - { - ctx->error++; - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Proof check failed: proof: %s key: %s\n", proof, state_id); - } - GNUNET_free (state_id); + { + if (0 == strcmp(proof, ctx->strings[i])) + ctx->match_count++; + } + + if (GNUNET_OK != REGEX_BLOCK_check_proof(proof, strlen(proof), key)) + { + ctx->error++; + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Proof check failed: proof: %s key: %s\n", proof, state_id); + } + GNUNET_free(state_id); } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - GNUNET_log_setup ("test-regex", "WARNING", NULL); + GNUNET_log_setup("test-regex", "WARNING", NULL); int error; struct REGEX_INTERNAL_Automaton *dfa; @@ -128,132 +126,132 @@ main (int argc, char *argv[]) error = 0; const struct RegexStringPair rxstr[13] = { - {INITIAL_PADDING "ab(c|d)+c*(a(b|c)+d)+(bla)+", 2, - {INITIAL_PADDING "abcdcdca", INITIAL_PADDING "abcabdbl"}}, - {INITIAL_PADDING - "abcdefghixxxxxxxxxxxxxjklmnop*qstoisdjfguisdfguihsdfgbdsuivggsd", 1, - {INITIAL_PADDING "abcdefgh"}}, - {INITIAL_PADDING "VPN-4-1(0|1)*", 2, - {INITIAL_PADDING "VPN-4-10", INITIAL_PADDING "VPN-4-11"}}, - {INITIAL_PADDING "(a+X*y+c|p|R|Z*K*y*R+w|Y*6+n+h*k*w+V*F|W*B*e*)", 2, - {INITIAL_PADDING "aaaaaaaa", INITIAL_PADDING "aaXXyyyc"}}, - {INITIAL_PADDING "a*", 1, {INITIAL_PADDING "aaaaaaaa"}}, - {INITIAL_PADDING "xzxzxzxzxz", 1, {INITIAL_PADDING "xzxzxzxz"}}, - {INITIAL_PADDING "xyz*", 1, {INITIAL_PADDING "xyzzzzzz"}}, - {INITIAL_PADDING - "abcd:(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1):(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)", - 2, {INITIAL_PADDING "abcd:000", INITIAL_PADDING "abcd:101"}}, - {INITIAL_PADDING "(x*|(0|1|2)(a|b|c|d)+)", 2, - {INITIAL_PADDING "xxxxxxxx", INITIAL_PADDING "0abcdbad"}}, - {INITIAL_PADDING "(0|1)(0|1)23456789ABC", 1, {INITIAL_PADDING "11234567"}}, - {INITIAL_PADDING "0*123456789ABC*", 3, - {INITIAL_PADDING "00123456", INITIAL_PADDING "00000000", - INITIAL_PADDING "12345678"}}, - {INITIAL_PADDING "0123456789A*BC", 1, {INITIAL_PADDING "01234567"}}, - {"GNUNETVPN000100000IPEX6-fc5a:4e1:c2ba::1", 1, {"GNUNETVPN000100000IPEX6-"}} + { INITIAL_PADDING "ab(c|d)+c*(a(b|c)+d)+(bla)+", 2, + { INITIAL_PADDING "abcdcdca", INITIAL_PADDING "abcabdbl" } }, + { INITIAL_PADDING + "abcdefghixxxxxxxxxxxxxjklmnop*qstoisdjfguisdfguihsdfgbdsuivggsd", 1, + { INITIAL_PADDING "abcdefgh" } }, + { INITIAL_PADDING "VPN-4-1(0|1)*", 2, + { INITIAL_PADDING "VPN-4-10", INITIAL_PADDING "VPN-4-11" } }, + { INITIAL_PADDING "(a+X*y+c|p|R|Z*K*y*R+w|Y*6+n+h*k*w+V*F|W*B*e*)", 2, + { INITIAL_PADDING "aaaaaaaa", INITIAL_PADDING "aaXXyyyc" } }, + { INITIAL_PADDING "a*", 1, { INITIAL_PADDING "aaaaaaaa" } }, + { INITIAL_PADDING "xzxzxzxzxz", 1, { INITIAL_PADDING "xzxzxzxz" } }, + { INITIAL_PADDING "xyz*", 1, { INITIAL_PADDING "xyzzzzzz" } }, + { INITIAL_PADDING + "abcd:(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1):(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)", + 2, { INITIAL_PADDING "abcd:000", INITIAL_PADDING "abcd:101" } }, + { INITIAL_PADDING "(x*|(0|1|2)(a|b|c|d)+)", 2, + { INITIAL_PADDING "xxxxxxxx", INITIAL_PADDING "0abcdbad" } }, + { INITIAL_PADDING "(0|1)(0|1)23456789ABC", 1, { INITIAL_PADDING "11234567" } }, + { INITIAL_PADDING "0*123456789ABC*", 3, + { INITIAL_PADDING "00123456", INITIAL_PADDING "00000000", + INITIAL_PADDING "12345678" } }, + { INITIAL_PADDING "0123456789A*BC", 1, { INITIAL_PADDING "01234567" } }, + { "GNUNETVPN000100000IPEX6-fc5a:4e1:c2ba::1", 1, { "GNUNETVPN000100000IPEX6-" } } }; const char *graph_start_str = "digraph G {\nrankdir=LR\n"; const char *graph_end_str = "\n}\n"; for (i = 0; i < 13; i++) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Iterating DFA for regex %s\n", - rxstr[i].regex); - - - /* Create graph */ - if (GNUNET_YES == REGEX_INTERNAL_ITERATE_SAVE_DEBUG_GRAPH) { - GNUNET_asprintf (&filename, "iteration_graph_%u.dot", i); - ctx.graph_filep = fopen (filename, "w"); - if (NULL == ctx.graph_filep) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - "Could not open file %s for saving iteration graph.\n", - filename); - ctx.should_save_graph = GNUNET_NO; - } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Iterating DFA for regex %s\n", + rxstr[i].regex); + + + /* Create graph */ + if (GNUNET_YES == REGEX_INTERNAL_ITERATE_SAVE_DEBUG_GRAPH) + { + GNUNET_asprintf(&filename, "iteration_graph_%u.dot", i); + ctx.graph_filep = fopen(filename, "w"); + if (NULL == ctx.graph_filep) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + "Could not open file %s for saving iteration graph.\n", + filename); + ctx.should_save_graph = GNUNET_NO; + } + else + { + ctx.should_save_graph = GNUNET_YES; + fwrite(graph_start_str, strlen(graph_start_str), 1, ctx.graph_filep); + } + GNUNET_free(filename); + } else - { - ctx.should_save_graph = GNUNET_YES; - fwrite (graph_start_str, strlen (graph_start_str), 1, ctx.graph_filep); - } - GNUNET_free (filename); - } - else - { - ctx.should_save_graph = GNUNET_NO; - ctx.graph_filep = NULL; - } - - /* Iterate over DFA edges */ - transition_counter = 0; - ctx.string_count = rxstr[i].string_count; - ctx.strings = rxstr[i].strings; - ctx.match_count = 0; - dfa = - REGEX_INTERNAL_construct_dfa (rxstr[i].regex, strlen (rxstr[i].regex), 0); - REGEX_INTERNAL_iterate_all_edges (dfa, key_iterator, &ctx); - num_transitions = - REGEX_INTERNAL_get_transition_count (dfa) - dfa->start->transition_count; - - if (transition_counter < num_transitions) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Automaton has %d transitions, iterated over %d transitions\n", - num_transitions, transition_counter); - error += 1; - } - - if (ctx.match_count < ctx.string_count) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Missing initial states for regex %s\n", rxstr[i].regex); - error += (ctx.string_count - ctx.match_count); - } - else if (ctx.match_count > ctx.string_count) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Duplicate initial transitions for regex %s\n", - rxstr[i].regex); - error += (ctx.string_count - ctx.match_count); - } - - REGEX_INTERNAL_automaton_destroy (dfa); - - /* Finish graph */ - if (GNUNET_YES == ctx.should_save_graph) - { - fwrite (graph_end_str, strlen (graph_end_str), 1, ctx.graph_filep); - fclose (ctx.graph_filep); - ctx.graph_filep = NULL; - ctx.should_save_graph = GNUNET_NO; + { + ctx.should_save_graph = GNUNET_NO; + ctx.graph_filep = NULL; + } + + /* Iterate over DFA edges */ + transition_counter = 0; + ctx.string_count = rxstr[i].string_count; + ctx.strings = rxstr[i].strings; + ctx.match_count = 0; + dfa = + REGEX_INTERNAL_construct_dfa(rxstr[i].regex, strlen(rxstr[i].regex), 0); + REGEX_INTERNAL_iterate_all_edges(dfa, key_iterator, &ctx); + num_transitions = + REGEX_INTERNAL_get_transition_count(dfa) - dfa->start->transition_count; + + if (transition_counter < num_transitions) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Automaton has %d transitions, iterated over %d transitions\n", + num_transitions, transition_counter); + error += 1; + } + + if (ctx.match_count < ctx.string_count) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Missing initial states for regex %s\n", rxstr[i].regex); + error += (ctx.string_count - ctx.match_count); + } + else if (ctx.match_count > ctx.string_count) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Duplicate initial transitions for regex %s\n", + rxstr[i].regex); + error += (ctx.string_count - ctx.match_count); + } + + REGEX_INTERNAL_automaton_destroy(dfa); + + /* Finish graph */ + if (GNUNET_YES == ctx.should_save_graph) + { + fwrite(graph_end_str, strlen(graph_end_str), 1, ctx.graph_filep); + fclose(ctx.graph_filep); + ctx.graph_filep = NULL; + ctx.should_save_graph = GNUNET_NO; + } } - } for (i = 0; i < 13; i++) - { - ctx.string_count = rxstr[i].string_count; - ctx.strings = rxstr[i].strings; - ctx.match_count = 0; - - dfa = - REGEX_INTERNAL_construct_dfa (rxstr[i].regex, strlen (rxstr[i].regex), 0); - REGEX_INTERNAL_dfa_add_multi_strides (NULL, dfa, 2); - REGEX_INTERNAL_iterate_all_edges (dfa, key_iterator, &ctx); - - if (ctx.match_count < ctx.string_count) { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Missing initial states for regex %s\n", rxstr[i].regex); - error += (ctx.string_count - ctx.match_count); + ctx.string_count = rxstr[i].string_count; + ctx.strings = rxstr[i].strings; + ctx.match_count = 0; + + dfa = + REGEX_INTERNAL_construct_dfa(rxstr[i].regex, strlen(rxstr[i].regex), 0); + REGEX_INTERNAL_dfa_add_multi_strides(NULL, dfa, 2); + REGEX_INTERNAL_iterate_all_edges(dfa, key_iterator, &ctx); + + if (ctx.match_count < ctx.string_count) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Missing initial states for regex %s\n", rxstr[i].regex); + error += (ctx.string_count - ctx.match_count); + } + + REGEX_INTERNAL_automaton_destroy(dfa); } - REGEX_INTERNAL_automaton_destroy (dfa); - } - error += ctx.error; return error; diff --git a/src/regex/test_regex_proofs.c b/src/regex/test_regex_proofs.c index 4f49ef656..3649ac8aa 100644 --- a/src/regex/test_regex_proofs.c +++ b/src/regex/test_regex_proofs.c @@ -11,12 +11,12 @@ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later -*/ + */ /** * @file regex/test_regex_proofs.c * @brief test for regex.c @@ -40,32 +40,32 @@ * @return 0 on success, 1 on failure */ static unsigned int -test_proof (const char *regex) +test_proof(const char *regex) { unsigned int error; struct REGEX_INTERNAL_Automaton *dfa; char *c_rx1; const char *c_rx2; - dfa = REGEX_INTERNAL_construct_dfa (regex, strlen (regex), 1); - GNUNET_assert (NULL != dfa); - c_rx1 = GNUNET_strdup (REGEX_INTERNAL_get_canonical_regex (dfa)); - REGEX_INTERNAL_automaton_destroy (dfa); - dfa = REGEX_INTERNAL_construct_dfa (c_rx1, strlen (c_rx1), 1); - GNUNET_assert (NULL != dfa); - c_rx2 = REGEX_INTERNAL_get_canonical_regex (dfa); + dfa = REGEX_INTERNAL_construct_dfa(regex, strlen(regex), 1); + GNUNET_assert(NULL != dfa); + c_rx1 = GNUNET_strdup(REGEX_INTERNAL_get_canonical_regex(dfa)); + REGEX_INTERNAL_automaton_destroy(dfa); + dfa = REGEX_INTERNAL_construct_dfa(c_rx1, strlen(c_rx1), 1); + GNUNET_assert(NULL != dfa); + c_rx2 = REGEX_INTERNAL_get_canonical_regex(dfa); - error = (0 == strcmp (c_rx1, c_rx2)) ? 0 : 1; + error = (0 == strcmp(c_rx1, c_rx2)) ? 0 : 1; if (error > 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Comparing canonical regex of\n%s\nfailed:\n%s\nvs.\n%s\n", - regex, c_rx1, c_rx2); - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Comparing canonical regex of\n%s\nfailed:\n%s\nvs.\n%s\n", + regex, c_rx1, c_rx2); + } - GNUNET_free (c_rx1); - REGEX_INTERNAL_automaton_destroy (dfa); + GNUNET_free(c_rx1); + REGEX_INTERNAL_automaton_destroy(dfa); return error; } @@ -81,7 +81,7 @@ test_proof (const char *regex) * @return 0 on succes, number of failures otherwise. */ static unsigned int -test_proofs_random (unsigned int count, size_t rx_length) +test_proofs_random(unsigned int count, size_t rx_length) { unsigned int i; char *rand_rx; @@ -90,11 +90,11 @@ test_proofs_random (unsigned int count, size_t rx_length) failures = 0; for (i = 0; i < count; i++) - { - rand_rx = REGEX_TEST_generate_random_regex (rx_length, NULL); - failures += test_proof (rand_rx); - GNUNET_free (rand_rx); - } + { + rand_rx = REGEX_TEST_generate_random_regex(rx_length, NULL); + failures += test_proof(rand_rx); + GNUNET_free(rand_rx); + } return failures; } @@ -106,7 +106,7 @@ test_proofs_random (unsigned int count, size_t rx_length) * @return 0 on success, number of failures otherwise. */ static unsigned int -test_proofs_static () +test_proofs_static() { unsigned int i; unsigned int error; @@ -130,43 +130,43 @@ test_proofs_static () error = 0; for (i = 0; i < 8; i += 2) - { - dfa1 = REGEX_INTERNAL_construct_dfa (regex[i], strlen (regex[i]), 1); - dfa2 = REGEX_INTERNAL_construct_dfa (regex[i + 1], strlen (regex[i + 1]), 1); - GNUNET_assert (NULL != dfa1); - GNUNET_assert (NULL != dfa2); + { + dfa1 = REGEX_INTERNAL_construct_dfa(regex[i], strlen(regex[i]), 1); + dfa2 = REGEX_INTERNAL_construct_dfa(regex[i + 1], strlen(regex[i + 1]), 1); + GNUNET_assert(NULL != dfa1); + GNUNET_assert(NULL != dfa2); - canon_rx1 = REGEX_INTERNAL_get_canonical_regex (dfa1); - canon_rx2 = REGEX_INTERNAL_get_canonical_regex (dfa2); + canon_rx1 = REGEX_INTERNAL_get_canonical_regex(dfa1); + canon_rx2 = REGEX_INTERNAL_get_canonical_regex(dfa2); - error += (0 == strcmp (canon_rx1, canon_rx2)) ? 0 : 1; + error += (0 == strcmp(canon_rx1, canon_rx2)) ? 0 : 1; - if (error > 0) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Comparing canonical regex failed:\nrx1:\t%s\ncrx1:\t%s\nrx2:\t%s\ncrx2:\t%s\n", - regex[i], canon_rx1, regex[i + 1], canon_rx2); - } + if (error > 0) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Comparing canonical regex failed:\nrx1:\t%s\ncrx1:\t%s\nrx2:\t%s\ncrx2:\t%s\n", + regex[i], canon_rx1, regex[i + 1], canon_rx2); + } - REGEX_INTERNAL_automaton_destroy (dfa1); - REGEX_INTERNAL_automaton_destroy (dfa2); - } + REGEX_INTERNAL_automaton_destroy(dfa1); + REGEX_INTERNAL_automaton_destroy(dfa2); + } return error; } int -main (int argc, char *argv[]) +main(int argc, char *argv[]) { - GNUNET_log_setup ("test-regex", "WARNING", NULL); + GNUNET_log_setup("test-regex", "WARNING", NULL); int error; error = 0; - error += test_proofs_static (); - error += test_proofs_random (100, 30); + error += test_proofs_static(); + error += test_proofs_random(100, 30); return error; } diff --git a/src/rest/gnunet-rest-server.c b/src/rest/gnunet-rest-server.c index 30acc1125..eb930c17b 100644 --- a/src/rest/gnunet-rest-server.c +++ b/src/rest/gnunet-rest-server.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach * @file src/rest/gnunet-rest-server.c @@ -54,7 +54,7 @@ * After how long do we clean up unused MHD SSL/TLS instances? */ #define MHD_CACHE_TIMEOUT \ - GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5) + GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5) #define GN_REST_STATE_INIT 0 #define GN_REST_STATE_PROCESSING 1 @@ -142,8 +142,7 @@ static char *allow_credentials; /** * MHD Connection handle */ -struct MhdConnectionHandle -{ +struct MhdConnectionHandle { struct MHD_Connection *con; struct MHD_Response *response; @@ -168,21 +167,21 @@ struct MhdConnectionHandle * @param cls NULL */ static void -do_httpd (void *cls); +do_httpd(void *cls); /** * Run MHD now, we have extra data ready for the callback. */ static void -run_mhd_now () +run_mhd_now() { if (NULL != httpd_task) - { - GNUNET_SCHEDULER_cancel (httpd_task); - httpd_task = NULL; - } - httpd_task = GNUNET_SCHEDULER_add_now (&do_httpd, NULL); + { + GNUNET_SCHEDULER_cancel(httpd_task); + httpd_task = NULL; + } + httpd_task = GNUNET_SCHEDULER_add_now(&do_httpd, NULL); } /** @@ -194,121 +193,121 @@ run_mhd_now () * @param status #GNUNET_OK if successful */ static void -plugin_callback (void *cls, struct MHD_Response *resp, int status) +plugin_callback(void *cls, struct MHD_Response *resp, int status) { struct MhdConnectionHandle *handle = cls; + handle->status = status; handle->response = resp; - MHD_resume_connection (handle->con); - run_mhd_now (); + MHD_resume_connection(handle->con); + run_mhd_now(); } static int -cleanup_url_map (void *cls, const struct GNUNET_HashCode *key, void *value) +cleanup_url_map(void *cls, const struct GNUNET_HashCode *key, void *value) { - GNUNET_free_non_null (value); + GNUNET_free_non_null(value); return GNUNET_YES; } static void -cleanup_handle (struct MhdConnectionHandle *handle) +cleanup_handle(struct MhdConnectionHandle *handle) { if (NULL != handle->response) - MHD_destroy_response (handle->response); + MHD_destroy_response(handle->response); if (NULL != handle->data_handle) - { - - if (NULL != handle->data_handle->header_param_map) - { - GNUNET_CONTAINER_multihashmap_iterate (handle->data_handle - ->header_param_map, - &cleanup_url_map, - NULL); - GNUNET_CONTAINER_multihashmap_destroy ( - handle->data_handle->header_param_map); - } - if (NULL != handle->data_handle->url_param_map) { - GNUNET_CONTAINER_multihashmap_iterate (handle->data_handle->url_param_map, - &cleanup_url_map, - NULL); - GNUNET_CONTAINER_multihashmap_destroy ( - handle->data_handle->url_param_map); + if (NULL != handle->data_handle->header_param_map) + { + GNUNET_CONTAINER_multihashmap_iterate(handle->data_handle + ->header_param_map, + &cleanup_url_map, + NULL); + GNUNET_CONTAINER_multihashmap_destroy( + handle->data_handle->header_param_map); + } + if (NULL != handle->data_handle->url_param_map) + { + GNUNET_CONTAINER_multihashmap_iterate(handle->data_handle->url_param_map, + &cleanup_url_map, + NULL); + GNUNET_CONTAINER_multihashmap_destroy( + handle->data_handle->url_param_map); + } + GNUNET_free(handle->data_handle); } - GNUNET_free (handle->data_handle); - } - GNUNET_free (handle); + GNUNET_free(handle); } static int -header_iterator (void *cls, - enum MHD_ValueKind kind, - const char *key, - const char *value) +header_iterator(void *cls, + enum MHD_ValueKind kind, + const char *key, + const char *value) { struct GNUNET_REST_RequestHandle *handle = cls; struct GNUNET_HashCode hkey; char *val; char *lowerkey; - lowerkey = GNUNET_strdup (key); - GNUNET_STRINGS_utf8_tolower (key, lowerkey); - GNUNET_CRYPTO_hash (lowerkey, strlen (lowerkey), &hkey); - GNUNET_asprintf (&val, "%s", value); - if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put ( - handle->header_param_map, - &hkey, - val, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not load add header `%s'=%s\n", - lowerkey, - value); - } - GNUNET_free (lowerkey); + lowerkey = GNUNET_strdup(key); + GNUNET_STRINGS_utf8_tolower(key, lowerkey); + GNUNET_CRYPTO_hash(lowerkey, strlen(lowerkey), &hkey); + GNUNET_asprintf(&val, "%s", value); + if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put( + handle->header_param_map, + &hkey, + val, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not load add header `%s'=%s\n", + lowerkey, + value); + } + GNUNET_free(lowerkey); return MHD_YES; } static int -url_iterator (void *cls, - enum MHD_ValueKind kind, - const char *key, - const char *value) +url_iterator(void *cls, + enum MHD_ValueKind kind, + const char *key, + const char *value) { struct GNUNET_REST_RequestHandle *handle = cls; struct GNUNET_HashCode hkey; char *val; - GNUNET_CRYPTO_hash (key, strlen (key), &hkey); - GNUNET_asprintf (&val, "%s", value); - if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put ( - handle->url_param_map, - &hkey, - val, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not load add url param `%s'=%s\n", - key, - value); - } + GNUNET_CRYPTO_hash(key, strlen(key), &hkey); + GNUNET_asprintf(&val, "%s", value); + if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put( + handle->url_param_map, + &hkey, + val, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not load add url param `%s'=%s\n", + key, + value); + } return MHD_YES; } static int -post_data_iter (void *cls, - enum MHD_ValueKind kind, - const char *key, - const char *filename, - const char *content_type, - const char *transfer_encoding, - const char *data, - uint64_t off, - size_t size) +post_data_iter(void *cls, + enum MHD_ValueKind kind, + const char *key, + const char *filename, + const char *content_type, + const char *transfer_encoding, + const char *data, + uint64_t off, + size_t size) { struct GNUNET_REST_RequestHandle *handle = cls; struct GNUNET_HashCode hkey; @@ -317,20 +316,20 @@ post_data_iter (void *cls, if (MHD_POSTDATA_KIND != kind) return MHD_YES; - GNUNET_CRYPTO_hash (key, strlen (key), &hkey); - GNUNET_asprintf (&val, "%s", data); - if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put ( - handle->url_param_map, - &hkey, - val, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Could not load add url param '%s'=%s\n", - key, - data); - GNUNET_free (val); - } + GNUNET_CRYPTO_hash(key, strlen(key), &hkey); + GNUNET_asprintf(&val, "%s", data); + if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put( + handle->url_param_map, + &hkey, + val, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Could not load add url param '%s'=%s\n", + key, + data); + GNUNET_free(val); + } return MHD_YES; } @@ -360,14 +359,14 @@ post_data_iter (void *cls, * error while handling the request */ static int -create_response (void *cls, - struct MHD_Connection *con, - const char *url, - const char *meth, - const char *ver, - const char *upload_data, - size_t *upload_data_size, - void **con_cls) +create_response(void *cls, + struct MHD_Connection *con, + const char *url, + const char *meth, + const char *ver, + const char *upload_data, + size_t *upload_data_size, + void **con_cls) { char *plugin_name; char *origin; @@ -378,135 +377,135 @@ create_response (void *cls, con_handle = *con_cls; if (NULL == *con_cls) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "New connection %s\n", url); - char tmp_url[strlen (url) + 1]; - strcpy (tmp_url, url); - con_handle = GNUNET_new (struct MhdConnectionHandle); - con_handle->con = con; - con_handle->state = GN_REST_STATE_INIT; - *con_cls = con_handle; - - plugin_name = strtok (tmp_url, "/"); - - if (NULL != plugin_name) { - GNUNET_CRYPTO_hash (plugin_name, strlen (plugin_name), &key); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "New connection %s\n", url); + char tmp_url[strlen(url) + 1]; + strcpy(tmp_url, url); + con_handle = GNUNET_new(struct MhdConnectionHandle); + con_handle->con = con; + con_handle->state = GN_REST_STATE_INIT; + *con_cls = con_handle; - con_handle->plugin = GNUNET_CONTAINER_multihashmap_get (plugin_map, &key); - } - if (NULL == con_handle->plugin) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Queueing response with MHD\n"); - GNUNET_free (con_handle); - return MHD_queue_response (con, MHD_HTTP_NOT_FOUND, failure_response); - } + plugin_name = strtok(tmp_url, "/"); - return MHD_YES; - } + if (NULL != plugin_name) + { + GNUNET_CRYPTO_hash(plugin_name, strlen(plugin_name), &key); + + con_handle->plugin = GNUNET_CONTAINER_multihashmap_get(plugin_map, &key); + } + if (NULL == con_handle->plugin) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Queueing response with MHD\n"); + GNUNET_free(con_handle); + return MHD_queue_response(con, MHD_HTTP_NOT_FOUND, failure_response); + } + + return MHD_YES; + } if (GN_REST_STATE_INIT == con_handle->state) - { - rest_conndata_handle = GNUNET_new (struct GNUNET_REST_RequestHandle); - rest_conndata_handle->method = meth; - rest_conndata_handle->url = url; - rest_conndata_handle->data = upload_data; - rest_conndata_handle->data_size = *upload_data_size; - rest_conndata_handle->url_param_map = - GNUNET_CONTAINER_multihashmap_create (16, GNUNET_NO); - rest_conndata_handle->header_param_map = - GNUNET_CONTAINER_multihashmap_create (16, GNUNET_NO); - con_handle->data_handle = rest_conndata_handle; - MHD_get_connection_values (con, - MHD_GET_ARGUMENT_KIND, - (MHD_KeyValueIterator) &url_iterator, - rest_conndata_handle); - MHD_get_connection_values (con, - MHD_HEADER_KIND, - (MHD_KeyValueIterator) &header_iterator, - rest_conndata_handle); - con_handle->pp = MHD_create_post_processor (con, - 65536, - post_data_iter, - rest_conndata_handle); - if (*upload_data_size) { - MHD_post_process (con_handle->pp, upload_data, *upload_data_size); + rest_conndata_handle = GNUNET_new(struct GNUNET_REST_RequestHandle); + rest_conndata_handle->method = meth; + rest_conndata_handle->url = url; + rest_conndata_handle->data = upload_data; + rest_conndata_handle->data_size = *upload_data_size; + rest_conndata_handle->url_param_map = + GNUNET_CONTAINER_multihashmap_create(16, GNUNET_NO); + rest_conndata_handle->header_param_map = + GNUNET_CONTAINER_multihashmap_create(16, GNUNET_NO); + con_handle->data_handle = rest_conndata_handle; + MHD_get_connection_values(con, + MHD_GET_ARGUMENT_KIND, + (MHD_KeyValueIterator) & url_iterator, + rest_conndata_handle); + MHD_get_connection_values(con, + MHD_HEADER_KIND, + (MHD_KeyValueIterator) & header_iterator, + rest_conndata_handle); + con_handle->pp = MHD_create_post_processor(con, + 65536, + post_data_iter, + rest_conndata_handle); + if (*upload_data_size) + { + MHD_post_process(con_handle->pp, upload_data, *upload_data_size); + } + MHD_destroy_post_processor(con_handle->pp); + + con_handle->state = GN_REST_STATE_PROCESSING; + con_handle->plugin->process_request(rest_conndata_handle, + &plugin_callback, + con_handle); + *upload_data_size = 0; + run_mhd_now(); + return MHD_YES; } - MHD_destroy_post_processor (con_handle->pp); - - con_handle->state = GN_REST_STATE_PROCESSING; - con_handle->plugin->process_request (rest_conndata_handle, - &plugin_callback, - con_handle); - *upload_data_size = 0; - run_mhd_now (); - return MHD_YES; - } if (NULL == con_handle->response) - { - //Suspend connection until plugin is done - MHD_suspend_connection (con_handle->con); - return MHD_YES; - } - MHD_resume_connection (con_handle->con); - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Queueing response from plugin with MHD\n"); - //Handle Preflights for extensions - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Checking origin\n"); - GNUNET_CRYPTO_hash ("origin", strlen ("origin"), &key); - origin = GNUNET_CONTAINER_multihashmap_get (con_handle->data_handle - ->header_param_map, - &key); - if (NULL != origin) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Origin: %s\n", origin); - //Only echo for browser plugins - if (GNUNET_YES == echo_origin) { - if ((0 == - strncmp ("moz-extension://", origin, strlen ("moz-extension://"))) || - (0 == strncmp ("chrome-extension://", - origin, - strlen ("chrome-extension://")))) - { - MHD_add_response_header (con_handle->response, - MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, - origin); - } + //Suspend connection until plugin is done + MHD_suspend_connection(con_handle->con); + return MHD_YES; } - if (NULL != allow_origins) + MHD_resume_connection(con_handle->con); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Queueing response from plugin with MHD\n"); + //Handle Preflights for extensions + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Checking origin\n"); + GNUNET_CRYPTO_hash("origin", strlen("origin"), &key); + origin = GNUNET_CONTAINER_multihashmap_get(con_handle->data_handle + ->header_param_map, + &key); + if (NULL != origin) { - char *tmp = GNUNET_strdup (allow_origins); - char *allow_origin = strtok (tmp, ","); - while (NULL != allow_origin) - { - if (0 == strncmp (allow_origin, origin, strlen (allow_origin))) + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Origin: %s\n", origin); + //Only echo for browser plugins + if (GNUNET_YES == echo_origin) + { + if ((0 == + strncmp("moz-extension://", origin, strlen("moz-extension://"))) || + (0 == strncmp("chrome-extension://", + origin, + strlen("chrome-extension://")))) + { + MHD_add_response_header(con_handle->response, + MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, + origin); + } + } + if (NULL != allow_origins) { - MHD_add_response_header (con_handle->response, - MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, - allow_origin); - break; + char *tmp = GNUNET_strdup(allow_origins); + char *allow_origin = strtok(tmp, ","); + while (NULL != allow_origin) + { + if (0 == strncmp(allow_origin, origin, strlen(allow_origin))) + { + MHD_add_response_header(con_handle->response, + MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN, + allow_origin); + break; + } + allow_origin = strtok(NULL, ","); + } + GNUNET_free(tmp); } - allow_origin = strtok (NULL, ","); - } - GNUNET_free (tmp); } - } if (NULL != allow_credentials) - { - MHD_add_response_header (con_handle->response, - "Access-Control-Allow-Credentials", - allow_credentials); - } + { + MHD_add_response_header(con_handle->response, + "Access-Control-Allow-Credentials", + allow_credentials); + } if (NULL != allow_headers) - { - MHD_add_response_header (con_handle->response, - "Access-Control-Allow-Headers", - allow_headers); - } - run_mhd_now (); - int ret = MHD_queue_response (con, con_handle->status, con_handle->response); - cleanup_handle (con_handle); + { + MHD_add_response_header(con_handle->response, + "Access-Control-Allow-Headers", + allow_headers); + } + run_mhd_now(); + int ret = MHD_queue_response(con, con_handle->status, con_handle->response); + cleanup_handle(con_handle); return ret; } @@ -523,15 +522,15 @@ create_response (void *cls, * @param toe reason for request termination (ignored) */ static void -mhd_completed_cb (void *cls, - struct MHD_Connection *connection, - void **con_cls, - enum MHD_RequestTerminationCode toe) +mhd_completed_cb(void *cls, + struct MHD_Connection *connection, + void **con_cls, + enum MHD_RequestTerminationCode toe) { if (MHD_REQUEST_TERMINATED_COMPLETED_OK != toe) - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "MHD encountered error handling request: %d\n", - toe); + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "MHD encountered error handling request: %d\n", + toe); } @@ -539,39 +538,39 @@ mhd_completed_cb (void *cls, * Kill the MHD daemon. */ static void -kill_httpd () +kill_httpd() { if (NULL != httpd) - { - MHD_stop_daemon (httpd); - httpd = NULL; - } + { + MHD_stop_daemon(httpd); + httpd = NULL; + } if (NULL != httpd_task) - { - GNUNET_SCHEDULER_cancel (httpd_task); - httpd_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(httpd_task); + httpd_task = NULL; + } if (NULL != ltask4) - { - GNUNET_SCHEDULER_cancel (ltask4); - ltask4 = NULL; - } + { + GNUNET_SCHEDULER_cancel(ltask4); + ltask4 = NULL; + } if (NULL != ltask6) - { - GNUNET_SCHEDULER_cancel (ltask6); - ltask6 = NULL; - } + { + GNUNET_SCHEDULER_cancel(ltask6); + ltask6 = NULL; + } if (NULL != lsock4) - { - GNUNET_NETWORK_socket_close (lsock4); - lsock4 = NULL; - } + { + GNUNET_NETWORK_socket_close(lsock4); + lsock4 = NULL; + } if (NULL != lsock6) - { - GNUNET_NETWORK_socket_close (lsock6); - lsock6 = NULL; - } + { + GNUNET_NETWORK_socket_close(lsock6); + lsock6 = NULL; + } } @@ -583,7 +582,7 @@ kill_httpd () * @param hd the daemon to schedule */ static void -schedule_httpd () +schedule_httpd() { fd_set rs; fd_set ws; @@ -595,50 +594,50 @@ schedule_httpd () MHD_UNSIGNED_LONG_LONG timeout; struct GNUNET_TIME_Relative tv; - FD_ZERO (&rs); - FD_ZERO (&ws); - FD_ZERO (&es); + FD_ZERO(&rs); + FD_ZERO(&ws); + FD_ZERO(&es); max = -1; - if (MHD_YES != MHD_get_fdset (httpd, &rs, &ws, &es, &max)) - { - kill_httpd (); - return; - } - haveto = MHD_get_timeout (httpd, &timeout); + if (MHD_YES != MHD_get_fdset(httpd, &rs, &ws, &es, &max)) + { + kill_httpd(); + return; + } + haveto = MHD_get_timeout(httpd, &timeout); if (MHD_YES == haveto) - tv.rel_value_us = (uint64_t) timeout * 1000LL; + tv.rel_value_us = (uint64_t)timeout * 1000LL; else tv = GNUNET_TIME_UNIT_FOREVER_REL; if (-1 != max) - { - wrs = GNUNET_NETWORK_fdset_create (); - wws = GNUNET_NETWORK_fdset_create (); - GNUNET_NETWORK_fdset_copy_native (wrs, &rs, max + 1); - GNUNET_NETWORK_fdset_copy_native (wws, &ws, max + 1); - } + { + wrs = GNUNET_NETWORK_fdset_create(); + wws = GNUNET_NETWORK_fdset_create(); + GNUNET_NETWORK_fdset_copy_native(wrs, &rs, max + 1); + GNUNET_NETWORK_fdset_copy_native(wws, &ws, max + 1); + } else - { - wrs = NULL; - wws = NULL; - } + { + wrs = NULL; + wws = NULL; + } if (NULL != httpd_task) - { - GNUNET_SCHEDULER_cancel (httpd_task); - httpd_task = NULL; - } + { + GNUNET_SCHEDULER_cancel(httpd_task); + httpd_task = NULL; + } if ((MHD_YES == haveto) || (-1 != max)) - { - httpd_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, - tv, - wrs, - wws, - &do_httpd, - NULL); - } + { + httpd_task = GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT, + tv, + wrs, + wws, + &do_httpd, + NULL); + } if (NULL != wrs) - GNUNET_NETWORK_fdset_destroy (wrs); + GNUNET_NETWORK_fdset_destroy(wrs); if (NULL != wws) - GNUNET_NETWORK_fdset_destroy (wws); + GNUNET_NETWORK_fdset_destroy(wws); } /** @@ -647,11 +646,11 @@ schedule_httpd () * @param cls NULL */ static void -do_httpd (void *cls) +do_httpd(void *cls) { httpd_task = NULL; - MHD_run (httpd); - schedule_httpd (); + MHD_run(httpd); + schedule_httpd(); } @@ -662,7 +661,7 @@ do_httpd (void *cls) * @param tc the scheduler context */ static void -do_accept (void *cls) +do_accept(void *cls) { struct GNUNET_NETWORK_Handle *lsock = cls; struct GNUNET_NETWORK_Handle *s; @@ -670,42 +669,42 @@ do_accept (void *cls) const struct sockaddr *addr; socklen_t len; - GNUNET_assert (NULL != lsock); + GNUNET_assert(NULL != lsock); if (lsock == lsock4) - { - ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - lsock, - &do_accept, - lsock); - } + { + ltask4 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + lsock, + &do_accept, + lsock); + } else if (lsock == lsock6) - { - ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - lsock, - &do_accept, - lsock); - } + { + ltask6 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + lsock, + &do_accept, + lsock); + } else - GNUNET_assert (0); - s = GNUNET_NETWORK_socket_accept (lsock, NULL, NULL); + GNUNET_assert(0); + s = GNUNET_NETWORK_socket_accept(lsock, NULL, NULL); if (NULL == s) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "accept"); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Got an inbound connection, waiting for data\n"); - fd = GNUNET_NETWORK_get_fd (s); - addr = GNUNET_NETWORK_get_addr (s); - len = GNUNET_NETWORK_get_addrlen (s); - if (MHD_YES != MHD_add_connection (httpd, fd, addr, len)) - { - GNUNET_log (GNUNET_ERROR_TYPE_WARNING, - _ ("Failed to pass client to MHD\n")); - return; - } - GNUNET_free (s); - schedule_httpd (); + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "accept"); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Got an inbound connection, waiting for data\n"); + fd = GNUNET_NETWORK_get_fd(s); + addr = GNUNET_NETWORK_get_addr(s); + len = GNUNET_NETWORK_get_addrlen(s); + if (MHD_YES != MHD_add_connection(httpd, fd, addr, len)) + { + GNUNET_log(GNUNET_ERROR_TYPE_WARNING, + _("Failed to pass client to MHD\n")); + return; + } + GNUNET_free(s); + schedule_httpd(); } @@ -715,12 +714,12 @@ do_accept (void *cls) * @param cls closure */ static void -do_shutdown (void *cls) +do_shutdown(void *cls) { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Shutting down...\n"); - kill_httpd (); - GNUNET_free_non_null (allow_credentials); - GNUNET_free_non_null (allow_headers); + GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Shutting down...\n"); + kill_httpd(); + GNUNET_free_non_null(allow_credentials); + GNUNET_free_non_null(allow_headers); } @@ -730,31 +729,31 @@ do_shutdown (void *cls) * @return NULL on error */ static struct GNUNET_NETWORK_Handle * -bind_v4 () +bind_v4() { struct GNUNET_NETWORK_Handle *ls; struct sockaddr_in sa4; int eno; - memset (&sa4, 0, sizeof (sa4)); + memset(&sa4, 0, sizeof(sa4)); sa4.sin_family = AF_INET; - sa4.sin_port = htons (port); + sa4.sin_port = htons(port); sa4.sin_addr.s_addr = address; #if HAVE_SOCKADDR_IN_SIN_LEN - sa4.sin_len = sizeof (sa4); + sa4.sin_len = sizeof(sa4); #endif - ls = GNUNET_NETWORK_socket_create (AF_INET, SOCK_STREAM, 0); + ls = GNUNET_NETWORK_socket_create(AF_INET, SOCK_STREAM, 0); if (NULL == ls) return NULL; - if (GNUNET_OK != GNUNET_NETWORK_socket_bind (ls, - (const struct sockaddr *) &sa4, - sizeof (sa4))) - { - eno = errno; - GNUNET_NETWORK_socket_close (ls); - errno = eno; - return NULL; - } + if (GNUNET_OK != GNUNET_NETWORK_socket_bind(ls, + (const struct sockaddr *)&sa4, + sizeof(sa4))) + { + eno = errno; + GNUNET_NETWORK_socket_close(ls); + errno = eno; + return NULL; + } return ls; } @@ -765,31 +764,31 @@ bind_v4 () * @return NULL on error */ static struct GNUNET_NETWORK_Handle * -bind_v6 () +bind_v6() { struct GNUNET_NETWORK_Handle *ls; struct sockaddr_in6 sa6; int eno; - memset (&sa6, 0, sizeof (sa6)); + memset(&sa6, 0, sizeof(sa6)); sa6.sin6_family = AF_INET6; - sa6.sin6_port = htons (port); + sa6.sin6_port = htons(port); sa6.sin6_addr = address6; #if HAVE_SOCKADDR_IN_SIN_LEN - sa6.sin6_len = sizeof (sa6); + sa6.sin6_len = sizeof(sa6); #endif - ls = GNUNET_NETWORK_socket_create (AF_INET6, SOCK_STREAM, 0); + ls = GNUNET_NETWORK_socket_create(AF_INET6, SOCK_STREAM, 0); if (NULL == ls) return NULL; - if (GNUNET_OK != GNUNET_NETWORK_socket_bind (ls, - (const struct sockaddr *) &sa6, - sizeof (sa6))) - { - eno = errno; - GNUNET_NETWORK_socket_close (ls); - errno = eno; - return NULL; - } + if (GNUNET_OK != GNUNET_NETWORK_socket_bind(ls, + (const struct sockaddr *)&sa6, + sizeof(sa6))) + { + eno = errno; + GNUNET_NETWORK_socket_close(ls); + errno = eno; + return NULL; + } return ls; } @@ -802,32 +801,33 @@ bind_v6 () * @param lib_ret the object returned by the plugin initializer */ static void -load_plugin (void *cls, const char *libname, void *lib_ret) +load_plugin(void *cls, const char *libname, void *lib_ret) { struct GNUNET_REST_Plugin *plugin = lib_ret; struct GNUNET_HashCode key; + if (NULL == lib_ret) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Could not load plugin `%s'\n", - libname); - return; - } - GNUNET_assert (1 < strlen (plugin->name)); - GNUNET_assert ('/' == *plugin->name); - GNUNET_CRYPTO_hash (plugin->name + 1, strlen (plugin->name + 1), &key); - if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put ( - plugin_map, - &key, - plugin, - GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) - { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, - "Could not load add plugin `%s'\n", - libname); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Loaded plugin `%s'\n", libname); + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Could not load plugin `%s'\n", + libname); + return; + } + GNUNET_assert(1 < strlen(plugin->name)); + GNUNET_assert('/' == *plugin->name); + GNUNET_CRYPTO_hash(plugin->name + 1, strlen(plugin->name + 1), &key); + if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put( + plugin_map, + &key, + plugin, + GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)) + { + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, + "Could not load add plugin `%s'\n", + libname); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Loaded plugin `%s'\n", libname); } @@ -840,174 +840,175 @@ load_plugin (void *cls, const char *libname, void *lib_ret) * @param c configuration */ static void -run (void *cls, - char *const *args, - const char *cfgfile, - const struct GNUNET_CONFIGURATION_Handle *c) +run(void *cls, + char *const *args, + const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *c) { char *addr_str; + cfg = c; - plugin_map = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO); + plugin_map = GNUNET_CONTAINER_multihashmap_create(10, GNUNET_NO); /* Get port to bind to */ if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_number (cfg, "rest", "HTTP_PORT", &port)) - { - //No address specified - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Using default port...\n"); - port = GNUNET_REST_SERVICE_PORT; - } + GNUNET_CONFIGURATION_get_value_number(cfg, "rest", "HTTP_PORT", &port)) + { + //No address specified + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Using default port...\n"); + port = GNUNET_REST_SERVICE_PORT; + } /* Get address to bind to */ if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, "rest", "BIND_TO", &addr_str)) - { - //No address specified - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Don't know what to bind to...\n"); - GNUNET_SCHEDULER_shutdown (); - return; - } - if (1 != inet_pton (AF_INET, addr_str, &address)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse address %s\n", - addr_str); - GNUNET_free (addr_str); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_free (addr_str); + GNUNET_CONFIGURATION_get_value_string(cfg, "rest", "BIND_TO", &addr_str)) + { + //No address specified + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Don't know what to bind to...\n"); + GNUNET_SCHEDULER_shutdown(); + return; + } + if (1 != inet_pton(AF_INET, addr_str, &address)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse address %s\n", + addr_str); + GNUNET_free(addr_str); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_free(addr_str); /* Get address to bind to */ - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "rest", - "BIND_TO6", - &addr_str)) - { - //No address specified - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Don't know what to bind6 to...\n"); - GNUNET_SCHEDULER_shutdown (); - return; - } - if (1 != inet_pton (AF_INET6, addr_str, &address6)) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse IPv6 address %s\n", - addr_str); - GNUNET_free (addr_str); - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_free (addr_str); + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "rest", + "BIND_TO6", + &addr_str)) + { + //No address specified + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Don't know what to bind6 to...\n"); + GNUNET_SCHEDULER_shutdown(); + return; + } + if (1 != inet_pton(AF_INET6, addr_str, &address6)) + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse IPv6 address %s\n", + addr_str); + GNUNET_free(addr_str); + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_free(addr_str); /* Get CORS data from cfg */ echo_origin = - GNUNET_CONFIGURATION_get_value_yesno (cfg, - "rest", - "REST_ECHO_ORIGIN_WEBEXT"); + GNUNET_CONFIGURATION_get_value_yesno(cfg, + "rest", + "REST_ECHO_ORIGIN_WEBEXT"); allow_origins = NULL; - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "rest", - "REST_ALLOW_ORIGIN", - &allow_origins)) - { - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "No CORS Access-Control-Allow-Origin header will be sent...\n"); - } + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "rest", + "REST_ALLOW_ORIGIN", + &allow_origins)) + { + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "No CORS Access-Control-Allow-Origin header will be sent...\n"); + } if (GNUNET_OK != - GNUNET_CONFIGURATION_get_value_string (cfg, - "rest", - "REST_ALLOW_CREDENTIALS", - &allow_credentials)) - { - //No origin specified - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "No CORS Credential Header will be sent...\n"); - } - - if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, - "rest", - "REST_ALLOW_HEADERS", - &allow_headers)) - { - //No origin specified - GNUNET_log (GNUNET_ERROR_TYPE_INFO, - "No CORS Access-Control-Allow-Headers Header will be sent...\n"); - } + GNUNET_CONFIGURATION_get_value_string(cfg, + "rest", + "REST_ALLOW_CREDENTIALS", + &allow_credentials)) + { + //No origin specified + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "No CORS Credential Header will be sent...\n"); + } + + if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, + "rest", + "REST_ALLOW_HEADERS", + &allow_headers)) + { + //No origin specified + GNUNET_log(GNUNET_ERROR_TYPE_INFO, + "No CORS Access-Control-Allow-Headers Header will be sent...\n"); + } /* Open listen socket proxy */ - lsock6 = bind_v6 (); + lsock6 = bind_v6(); if (NULL == lsock6) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind"); - } - else - { - if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock6, 5)) { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen"); - GNUNET_NETWORK_socket_close (lsock6); - lsock6 = NULL; + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "bind"); } - else + else { - ltask6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - lsock6, - &do_accept, - lsock6); + if (GNUNET_OK != GNUNET_NETWORK_socket_listen(lsock6, 5)) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "listen"); + GNUNET_NETWORK_socket_close(lsock6); + lsock6 = NULL; + } + else + { + ltask6 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + lsock6, + &do_accept, + lsock6); + } } - } - lsock4 = bind_v4 (); + lsock4 = bind_v4(); if (NULL == lsock4) - { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind"); - } - else - { - if (GNUNET_OK != GNUNET_NETWORK_socket_listen (lsock4, 5)) { - GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "listen"); - GNUNET_NETWORK_socket_close (lsock4); - lsock4 = NULL; + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "bind"); } - else + else { - ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, - lsock4, - &do_accept, - lsock4); + if (GNUNET_OK != GNUNET_NETWORK_socket_listen(lsock4, 5)) + { + GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "listen"); + GNUNET_NETWORK_socket_close(lsock4); + lsock4 = NULL; + } + else + { + ltask4 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, + lsock4, + &do_accept, + lsock4); + } } - } if ((NULL == lsock4) && (NULL == lsock6)) - { - GNUNET_SCHEDULER_shutdown (); - return; - } - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Service listens on port %llu\n", port); - httpd = MHD_start_daemon (MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET | - MHD_ALLOW_SUSPEND_RESUME, - 0, - NULL, - NULL, - &create_response, - NULL, - MHD_OPTION_CONNECTION_TIMEOUT, - (unsigned int) 16, - MHD_OPTION_NOTIFY_COMPLETED, - &mhd_completed_cb, - NULL, - MHD_OPTION_END); + { + GNUNET_SCHEDULER_shutdown(); + return; + } + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Service listens on port %llu\n", port); + httpd = MHD_start_daemon(MHD_USE_DEBUG | MHD_USE_NO_LISTEN_SOCKET | + MHD_ALLOW_SUSPEND_RESUME, + 0, + NULL, + NULL, + &create_response, + NULL, + MHD_OPTION_CONNECTION_TIMEOUT, + (unsigned int)16, + MHD_OPTION_NOTIFY_COMPLETED, + &mhd_completed_cb, + NULL, + MHD_OPTION_END); if (NULL == httpd) - { - GNUNET_SCHEDULER_shutdown (); - return; - } + { + GNUNET_SCHEDULER_shutdown(); + return; + } /* Load plugins */ - GNUNET_PLUGIN_load_all ("libgnunet_plugin_rest", - (void *) cfg, - &load_plugin, - NULL); - GNUNET_SCHEDULER_add_shutdown (&do_shutdown, NULL); + GNUNET_PLUGIN_load_all("libgnunet_plugin_rest", + (void *)cfg, + &load_plugin, + NULL); + GNUNET_SCHEDULER_add_shutdown(&do_shutdown, NULL); } @@ -1021,29 +1022,29 @@ run (void *cls, * */ int -main (int argc, char *const *argv) +main(int argc, char *const *argv) { - struct GNUNET_GETOPT_CommandLineOption options[] = {GNUNET_GETOPT_OPTION_END}; + struct GNUNET_GETOPT_CommandLineOption options[] = { GNUNET_GETOPT_OPTION_END }; static const char *err_page = "{}"; int ret; - if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv)) return 2; - GNUNET_log_setup ("gnunet-rest-server", "WARNING", NULL); - failure_response = MHD_create_response_from_buffer (strlen (err_page), - (void *) err_page, - MHD_RESPMEM_PERSISTENT); - ret = (GNUNET_OK == GNUNET_PROGRAM_run (argc, - argv, - "gnunet-rest-server", - _ ("GNUnet REST server"), - options, - &run, - NULL)) - ? 0 - : 1; - MHD_destroy_response (failure_response); - GNUNET_free_non_null ((char *) argv); + GNUNET_log_setup("gnunet-rest-server", "WARNING", NULL); + failure_response = MHD_create_response_from_buffer(strlen(err_page), + (void *)err_page, + MHD_RESPMEM_PERSISTENT); + ret = (GNUNET_OK == GNUNET_PROGRAM_run(argc, + argv, + "gnunet-rest-server", + _("GNUnet REST server"), + options, + &run, + NULL)) + ? 0 + : 1; + MHD_destroy_response(failure_response); + GNUNET_free_non_null((char *)argv); return ret; } diff --git a/src/rest/plugin_rest_config.c b/src/rest/plugin_rest_config.c index 7f1d0eedf..55797f543 100644 --- a/src/rest/plugin_rest_config.c +++ b/src/rest/plugin_rest_config.c @@ -16,7 +16,7 @@ along with this program. If not, see . SPDX-License-Identifier: AGPL3.0-or-later - */ + */ /** * @author Martin Schanzenbach * @file gns/plugin_rest_config.c @@ -35,15 +35,13 @@ /** * @brief struct returned by the initialization function of the plugin */ -struct Plugin -{ +struct Plugin { const struct GNUNET_CONFIGURATION_Handle *cfg; }; const struct GNUNET_CONFIGURATION_Handle *cfg; -struct RequestHandle -{ +struct RequestHandle { /** * Handle to rest request */ @@ -77,12 +75,12 @@ struct RequestHandle * @param handle Handle to clean up */ static void -cleanup_handle (struct RequestHandle *handle) +cleanup_handle(struct RequestHandle *handle) { - GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); + GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Cleaning up\n"); if (NULL != handle->url) - GNUNET_free (handle->url); - GNUNET_free (handle); + GNUNET_free(handle->url); + GNUNET_free(handle); } @@ -93,45 +91,46 @@ cleanup_handle (struct RequestHandle *handle) * @param tc scheduler context */ static void -do_error (void *cls) +do_error(void *cls) { struct RequestHandle *handle = cls; struct MHD_Response *resp; - resp = GNUNET_REST_create_response (NULL); - handle->proc (handle->proc_cls, resp, handle->response_code); - cleanup_handle (handle); + resp = GNUNET_REST_create_response(NULL); + handle->proc(handle->proc_cls, resp, handle->response_code); + cleanup_handle(handle); } static void -add_sections (void *cls, - const char *section, - const char *option, - const char *value) +add_sections(void *cls, + const char *section, + const char *option, + const char *value) { json_t *sections_obj = cls; json_t *sec_obj; - sec_obj = json_object_get (sections_obj, section); + sec_obj = json_object_get(sections_obj, section); if (NULL != sec_obj) - { - json_object_set_new (sec_obj, option, json_string (value)); - return; - } - sec_obj = json_object (); - json_object_set_new (sec_obj, option, json_string (value)); - json_object_set_new (sections_obj, section, sec_obj); + { + json_object_set_new(sec_obj, option, json_string(value)); + return; + } + sec_obj = json_object(); + json_object_set_new(sec_obj, option, json_string(value)); + json_object_set_new(sections_obj, section, sec_obj); } static void -add_section_contents (void *cls, - const char *section, - const char *option, - const char *value) +add_section_contents(void *cls, + const char *section, + const char *option, + const char *value) { json_t *section_obj = cls; - json_object_set_new (section_obj, option, json_string (value)); + + json_object_set_new(section_obj, option, json_string(value)); } /** @@ -140,9 +139,9 @@ add_section_contents (void *cls, * @param handle the lookup handle */ static void -get_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +get_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct MHD_Response *resp; struct RequestHandle *handle = cls; @@ -150,50 +149,50 @@ get_cont (struct GNUNET_REST_RequestHandle *con_handle, char *response; json_t *result; - if (strlen (GNUNET_REST_API_NS_CONFIG) > strlen (handle->url)) - { - handle->response_code = MHD_HTTP_BAD_REQUEST; - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - if (strlen (GNUNET_REST_API_NS_CONFIG) == strlen (handle->url)) - { - result = json_object (); - GNUNET_CONFIGURATION_iterate (cfg, &add_sections, result); - } + if (strlen(GNUNET_REST_API_NS_CONFIG) > strlen(handle->url)) + { + handle->response_code = MHD_HTTP_BAD_REQUEST; + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + if (strlen(GNUNET_REST_API_NS_CONFIG) == strlen(handle->url)) + { + result = json_object(); + GNUNET_CONFIGURATION_iterate(cfg, &add_sections, result); + } else - { - result = json_object (); - section = &handle->url[strlen (GNUNET_REST_API_NS_CONFIG) + 1]; - GNUNET_CONFIGURATION_iterate_section_values (cfg, - section, - &add_section_contents, - result); - } - response = json_dumps (result, 0); - resp = GNUNET_REST_create_response (response); - handle->proc (handle->proc_cls, resp, MHD_HTTP_OK); - cleanup_handle (handle); - GNUNET_free (response); - json_decref (result); + { + result = json_object(); + section = &handle->url[strlen(GNUNET_REST_API_NS_CONFIG) + 1]; + GNUNET_CONFIGURATION_iterate_section_values(cfg, + section, + &add_section_contents, + result); + } + response = json_dumps(result, 0); + resp = GNUNET_REST_create_response(response); + handle->proc(handle->proc_cls, resp, MHD_HTTP_OK); + cleanup_handle(handle); + GNUNET_free(response); + json_decref(result); } struct GNUNET_CONFIGURATION_Handle * -set_value (struct GNUNET_CONFIGURATION_Handle *config, - const char *section, - const char *option, - json_t *value) +set_value(struct GNUNET_CONFIGURATION_Handle *config, + const char *section, + const char *option, + json_t *value) { - if (json_is_string (value)) - GNUNET_CONFIGURATION_set_value_string (config, section, option, json_string_value (value)); - else if (json_is_number (value)) - GNUNET_CONFIGURATION_set_value_number (config, section, option, json_integer_value (value)); - else if (json_is_null (value)) - GNUNET_CONFIGURATION_set_value_string (config, section, option, NULL); - else if (json_is_true (value)) - GNUNET_CONFIGURATION_set_value_string (config, section, option, "yes"); - else if (json_is_false (value)) - GNUNET_CONFIGURATION_set_value_string (config, section, option, "no"); + if (json_is_string(value)) + GNUNET_CONFIGURATION_set_value_string(config, section, option, json_string_value(value)); + else if (json_is_number(value)) + GNUNET_CONFIGURATION_set_value_number(config, section, option, json_integer_value(value)); + else if (json_is_null(value)) + GNUNET_CONFIGURATION_set_value_string(config, section, option, NULL); + else if (json_is_true(value)) + GNUNET_CONFIGURATION_set_value_string(config, section, option, "yes"); + else if (json_is_false(value)) + GNUNET_CONFIGURATION_set_value_string(config, section, option, "no"); else return NULL; return config; // for error handling (0 -> success, 1 -> error) @@ -205,13 +204,13 @@ set_value (struct GNUNET_CONFIGURATION_Handle *config, * @param handle the lookup handle */ static void -set_cont (struct GNUNET_REST_RequestHandle *con_handle, - const char *url, - void *cls) +set_cont(struct GNUNET_REST_RequestHandle *con_handle, + const char *url, + void *cls) { struct RequestHandle *handle = cls; char term_data[handle->rest_handle->data_size + 1]; - struct GNUNET_CONFIGURATION_Handle *out = GNUNET_CONFIGURATION_dup (cfg); + struct GNUNET_CONFIGURATION_Handle *out = GNUNET_CONFIGURATION_dup(cfg); json_error_t err; json_t *data_json; @@ -220,89 +219,89 @@ set_cont (struct GNUNET_REST_RequestHandle *con_handle, json_t *sec_obj; json_t *value; char *cfg_fn; - + // invalid url - if (strlen (GNUNET_REST_API_NS_CONFIG) > strlen (handle->url)) - { - handle->response_code = MHD_HTTP_BAD_REQUEST; - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } - + if (strlen(GNUNET_REST_API_NS_CONFIG) > strlen(handle->url)) + { + handle->response_code = MHD_HTTP_BAD_REQUEST; + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } + // extract data from handle term_data[handle->rest_handle->data_size] = '\0'; - GNUNET_memcpy (term_data, - handle->rest_handle->data, - handle->rest_handle->data_size); - data_json = json_loads (term_data, JSON_DECODE_ANY, &err); - + GNUNET_memcpy(term_data, + handle->rest_handle->data, + handle->rest_handle->data_size); + data_json = json_loads(term_data, JSON_DECODE_ANY, &err); + if (NULL == data_json) - { - GNUNET_log (GNUNET_ERROR_TYPE_ERROR, - "Unable to parse JSON Object from %s\n", - term_data); - GNUNET_SCHEDULER_add_now (&do_error, handle); - return; - } + { + GNUNET_log(GNUNET_ERROR_TYPE_ERROR, + "Unable to parse JSON Object from %s\n", + term_data); + GNUNET_SCHEDULER_add_now(&do_error, handle); + return; + } // POST /config => {
: {